query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Start the count down. Every N ticks save the spent time to the server And update the timeSpent, taskTimeSpent variables to reflect the changes
startTimerInterval() { const intervalConfig = 250; const checkPointConfig = intervalConfig * 4 * 10; this.set('isCountingDown', true); var lastTick = Date.now(); let intervalId = setInterval(function() { // This can get really fun if the user starts moving the machine settings // For this app it is not the case we want to handle that scenario // Recommended: Use the server to handle the countdowns which brings up // interesting cases for keeping in sync let now = Date.now(); let delta = now - lastTick; lastTick = now; this.decrementProperty('countDownRemainingMilis', delta); this.incrementProperty('milisSinceLastSave', delta); let isFinished = this.isTaskFinished() || this.isCountDownFinished(); if(isFinished) { this.endTimerInterval(); } if(this.get('milisSinceLastSave') > checkPointConfig || isFinished) { this.saveSpentTime(); } }.bind(this), intervalConfig); this.set('intervalTimerId', intervalId); }
[ "function run() {\n timeRemaining = setInterval(countDown, 1000);\n }", "async function countDown()\n{\n var timeTotal = TIME_LIMIT;\n // send timer do all client\n do {\n io.sockets.emit('broadcast', timeTotal);\n timeTotal--;\n // sleep 1 second\n await sleep(1);\n } while(timeTotal > 0);\n\n // After time limit is finish\n // send reward money for winner\n processResult();\n\n // Reset data for next turn\n timerTotal = TIME_LIMIT;\n money = 0;\n // Send message wait server calculate result before next turn\n io.sockets.emit('wait_before_restart', SLEEP_TIME);\n // Send total of money to all users (next turn default to 0)\n io.sockets.emit('money_send', 0);\n // wait\n await sleep(SLEEP_TIME);\n // Send message next turn for all client (dont care about 1, You can use any number kaka)\n io.sockets.emit('restart', 1);\n\n countDown();\n}", "function defineIntDown() {\n msInterval = Number(10000 / countDownBy);\n //setInterval(beginCountingDown, msInterval);\n}", "tick() {\n console.log(`Timer ${this.title} Tick! | cycles left ${this.stopCount}`);\n this.stopCount--;\n }", "function CountDown(){\n //setTimeout(function, msec)\n //after a predetermined time, the following function is performed\n //in this case, it sets up updating time of this timer\n timerId = setTimeout(function(){\n var passedTime = Date.now() - startTime;\n timeLeft = timeToCountDown - passedTime;\n //console.log(timeLeft);\n if(timeLeft <= 0){\n clearTimeout(timerId);//to initialize the passing time by setTimeout(,)\n timeLeft = 0;//In display to avoid errors, setting up timeLeft just to 0\n timeToCountDown = 0;//initialization of timer\n UpdateTimer(timeLeft);\n start.style.display = \"\";\n stop.style.display = \"none\";\n isRunning = false;\n //isDone = true;\n return;\n }\n UpdateTimer(timeLeft);\n CountDown();\n },10);\n }", "function resetBetweenCycles(){\r\n t = 1\r\n total = 0\r\n counter = 0\r\n }", "function startCount(){\r\n\tchrome.storage.local.get([\"timePomodoro\"], function(store){\r\n\t\tlet timePomo = parseFloat(store.timePomodoro)*60000; // get time to count\r\n\t\t// start count\r\n\t\tsetTimePomodoro\t= setTimeout(function(){\r\n\t\t\t// open rest tab/notification when done pomodoro\r\n\t\t\tchrome.storage.local.get([\"openNewTabWhenEndPomo\", \"openNotifiWhenEndPomo\"], function(store){\r\n\t\t\t\topenNotificationAndNewtab(true, store.openNewTabWhenEndPomo, store.openNotifiWhenEndPomo)\r\n\t\t\t})\r\n\r\n\t\t\t// clear interval update curren count\r\n\t\t\tsetTimePomodoro = null\r\n\t\t\tconsole.log(\"done pomo\");\r\n\t\t}, timePomo)\r\n\r\n\t\t// start update counter in storage\r\n\t\tupdateCurrenTimeCouting(timePomo)\r\n\t})\r\n}", "function countDown() {\n\n timer = setInterval(function(){\n ticker++;\n seconds--;\n grossWPM = (amount / 5) / (ticker / 60);\n netWPM = grossWPM - (mistakes / (ticker / 60));\n updateLabels(grossWPM, netWPM);\n drawOnCanvas(ticker, grossWPM);\n if (seconds === 0) {\n gameOver();\n }\n }, 1000);\n\n /**\n * Updates all labels (gross-wpm, net-wpm and time) every time the timer ticks\n * @param grossWPM Words per minute calculated not considering any typing mistakes made\n * @param netWPM Words per minute calculated taken typing mistakes in consideration\n */\n function updateLabels(grossWPM, netWPM) {\n document.getElementById(\"grossWPM\").innerHTML = Math.round(grossWPM).toString();\n document.getElementById(\"netWPM\").innerHTML = Math.round(netWPM).toString();\n document.getElementById(\"time\").innerHTML = seconds.toString();\n }\n\n /**\n * Function draws a new line on the canvas\n * The lines position is based on current time and grossWPM\n */\n function drawOnCanvas(x, y) {\n x = x * (canvas.width / 60);\n ctx.lineTo(x, canvas.height - y);\n ctx.stroke();\n }\n }", "function timerCountDown() {\n\n }", "function startCountUp() {\n stopCountdown();\n // //stopCountUp();\n countup.start();\n}", "function doCountDown() {\n\t\t\tif(hbCountDown > 1) {\n\t\t\t\thbCountDown--;\n\t\t\t}\n\t\t\tif (hbCountDown == 1) {\n\t\t\t\tstatus = $.Acheta.HeartBeater.STATUS_LIMIT_REACHED;\n\t\t\t\tuserChecker.stopChecking();\n\t\t\t\t$(self).triggerHandler($.Acheta.HeartBeater.EVENT_HEARTBEAT_LIMIT_REACHED);\n\t\t\t}\n\t\t}", "function countDownV2() {\n var count = 10;\n\n for (var i = 1; i <= 10; i++) {\n setTimeout(function () {\n document.getElementById(\"countDownTimer\").innerHTML = count\n count--;\n }, 1000 * i);\n }\n setTimeout(function () {\n document.getElementById(\"countDownTimer\").innerHTML = \"Blastoff!\"\n count--;\n }, 11000);\n}", "function countDown() {\n if (_timeRemaining > 0) {\n\n // This function will be called as frequently as the _refreshRate variable\n // dictates so we reduce the number of milliseconds remaining by the\n // _refreshRate value for accurate timing\n _timeRemaining -= _refreshRate;\n\n // Publish the fact that the remaining time has changed, passing along the\n // new time remaining as a percentage - which will help when we come to display\n // the remaining time on the game board itself\n Frogger.observer.publish(\"time-remaining-change\", _timeRemaining / _timeTotal);\n } else {\n\n // If the remaining time reaches zero, we take one of the player's remaining\n // lives\n loseLife();\n }\n }", "function defineIntUp() {\n msInterval = Number(10000 / countUpBy);\n //setInterval(beginCountingUp, msInterval);\n}", "function countDown() {\n counter--;\n\n $('#time').html('Timer: ' + counter);\n\n if (counter === 0) {\n timeUp();\n }\n }", "function countDownPowerUpProgress() {\n\tconst s = 1000;\n\tlet x = 1000;\n\tpowerUpValue = powerUpMaxValue;\n\tlet t = setInterval(() => {\n\t\tpowerUpDurationEl.innerHTML = `${(powerUpDuration - x) / 1000}s`;\n\t\tpowerUpValue -= floor((powerUpMaxValue / powerUpDuration) * 1000);\n\t\tpowerUpValue = powerUpValue < 0 ? 0 : powerUpValue;\n\t\tupdateProgressInfo();\n\t\tif (powerUpValue <= 0) {\n\t\t\tpowerUpValue = 0;\n\t\t\ttotalHealers = 3;\n\t\t\tclearInterval(t);\n\t\t}\n\t\tx += s;\n\t}, s);\n}", "function timer(adjust, morework, interval)\n {\n interval = typeof interval !== 'undefined' ? interval : 0;\n\n console.log('timer');\n //create the timer speed, a counter and a starting timestamp\n var speed = 50,\n counter = 0, \n shownCountDown = 0,\n start = new Date().getTime();\n \n if(typeof countDownTimeout !== 'undefined'){\n window.clearTimeout(countDownTimeout);\n }\n\n //timer instance function\n function instance()\n {\n //if the morework flag is true\n //do some calculations to create more work\n if(morework)\n {\n for(var x = 1, i = 0; i<1000000; i++) { x *= (i + 1); }\n }\n \n //work out the real and ideal elapsed time\n var real = (counter * speed),\n ideal = (new Date().getTime() - start);\n \n //display the values\n /*form.ideal.value = real;\n form.real.value = ideal;*/\n //console.log(syncedServerTime.getTime() +' + '+ real);\n var goodTime = serverTime + real;\n\n countdown = shootTime-goodTime;\n\n if(counter == 0){\n shownCountDown = Math.floor(countdown/1000);\n showAlertMessage(true,shownCountDown);\n if(interval > 0){\n events.emit('countdownIntervalEvent', false);\n nextCountdownInterval = countdown-interval;\n } \n }\n\n if(interval > 0 && countdown <= nextCountdownInterval && nextCountdownInterval > 0){\n nextCountdownInterval = nextCountdownInterval-interval;\n events.emit('countdownIntervalEvent', false);\n }\n\n\n if(shownCountDown !== Math.floor(countdown/1000)){\n shownCountDown = Math.floor(countdown/1000);\n if(shownCountDown>0){\n showAlertMessage(true,shownCountDown);\n }\n }\n \n //increment the counter\n counter++;\n //console.log(countdown);\n\n if(countdown <= 0){\n events.emit('countdownEnd',true);\n window.clearTimeout(countDownTimeout);\n showAlertMessage(true,'Snap !!!');\n \n }else{\n //calculate and display the difference\n var diff = (ideal - real);\n //form.diff.value = diff;\n //if the adjust flag is true\n //delete the difference from the speed of the next instance\n if(adjust)\n {\n countDownTimeout = window.setTimeout(function() { instance(); }, (speed - diff));\n }else{\n countDownTimeout = window.setTimeout(function() { instance(); }, speed);\n }\n\n }\n };\n //now kick everything off with the first timer instance\n countDownTimeout = window.setTimeout(function() { instance(); }, speed);\n }", "function counter()\n{\n //starting 20sec of work period\n if(tabata.workTime > 0)\n {\n tabata.workTime--;\n element.text(\"Round #\" + tabata.roundNumber + \"\\n\" + tabata.workTime + \" sec\");\n }\n\n //starting 10sec rest period after the 20sec work period\n else if(tabata.workTime === 0)\n {\n Vibe.vibrate('short');\n tabata.restTime--;\n element.text(\"Round #\" + tabata.roundNumber + \"\\n\" + tabata.restTime + \" sec\");\n \n\t //increment rounds and restart the countdown; repeat 8 times\n if(tabata.restTime === 0)\n {\n Vibe.vibrate('short');\n\t tabata.roundNumber++;\n element.text(\"Round #\" + tabata.roundNumber + \"\\n\" + tabata.workTime + \" sec\");\n if(tabata.roundNumber <= NUM_ROUNDS)\n {\n reset(false);\n clearInterval(tabataTimer);\n tabataTimer = 0;\n tabataTimer = setInterval(counter, 1000);\n }\n\t\t \n\t\t else\n {\n element.text(\"Finished!\");\n\t\t clearInterval(tabataTimer);\n tabataTimer = 0;\n }\n }\n }\n}", "function trackTasks() {\n trackTasksFn(autoflow);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal: Strip internal query params from parsed URL. Returns sanitized url.href String.
function stripInternalParams(url) { url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '') return url.href.replace(/\?($|#)/, '$1') }
[ "function stripInternalParams(url) {\n url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '').replace(/^&/, '')\n return url.href.replace(/\\?($|#)/, '$1')\n}", "function stripInternalParams(url) {\n url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '').replace(/^&/, '');\n return url.href.replace(/\\?($|#)/, '$1')\n}", "function stripInternalParams(url) {\n url.search = url.search.replace(/([?&])(_pjax|_)=[^&]*/g, '')\n return url.href.replace(/\\?($|#)/, '$1')\n}", "function _stripParameters () {\n if (null != window.history && null != window.history.replaceState) {\n const cleaned_search = window.location.search.replace(/utm_[^&]+&?/g, '').replace(/ref=[^&]+&?/g, '').replace(/&$/, '').replace(/^\\?$/, '')\n window.history.replaceState({}, '', window.location.pathname + cleaned_search)\n }\n }", "function stripUrlParams(url, paramsToStrip){\n var urlSplit = url.match(/^([\\w\\.]*\\??)([\\w\\W]*)$/);\n var urlHead = urlSplit[1];\n var queries = urlSplit[2];\n if (queries === \"\") return urlHead;\n if (typeof paramsToStrip === \"undefined\") {\n queries = queries.split(\"&\").uniqueQuery().join(\"&\");\n } else {\n queries = queries.split(\"&\").uniqueQuery(paramsToStrip).join(\"&\");\n }\n return urlHead + queries;\n}", "function _removeQuery(url) {\n var n = url.indexOf('?');\n if (n >= 0) url = url.substring(0, n);\n return url;\n }", "removeQuery(url) {\n return url ? url.replace(/\\?.*$/, '') : '';\n }", "function stripUrlQueryAndFragment(urlPath) {\n\t // eslint-disable-next-line no-useless-escape\n\t return urlPath.split(/[\\?#]/, 1)[0];\n\t}", "function removeQuery(url) {\n return url ? url.replace(/\\?.*$/, '') : '';\n}", "function stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n }", "function URLcleaner(URL){\n\n\t// remove mult ampersands\n\tURL = URL.replace(/[&]+/g, \"&\"); \n\t\n\twhile ( URL.endsWith(\"?q=\") ){\n\t\tURL = URL.substring(0, URL.length - 3);\n\t} \n\n\twhile ( URL.endsWith(\"?q=*\") ){\n\t\tURL = URL.substring(0, URL.length - 4);\n\t}\n\n\t// remove single hanging offenders\n\twhile ( URL.endsWith(\"?\") || URL.endsWith(\"&\") ){\n\t\tURL = URL.substring(0, URL.length - 1);\n\t}\n\n\treturn URL; \n\n}", "function stripUrlParams(url, paramsToStrip){\n return url.replace(/&?([^?=]+)=.+?/g, function(m, p1, qPos) {\n return url.indexOf(p1 + '=') < qPos || (paramsToStrip||[]).indexOf(p1) > -1 ? \"\": m;\n });\n}", "function stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}", "function stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}", "function stripURL(url) {\n var withoutQs = url.split(\"?\")[0];\n var withoutHash = withoutQs.split(\"#\"); \n return withoutHash[ 0 ];\n}", "function trimUrlQuery(url) {\n let length = url.length;\n let q1 = url.indexOf(\"?\");\n let q2 = url.indexOf(\"&\");\n let q3 = url.indexOf(\"#\");\n let q = Math.min(q1 != -1 ? q1 : length, q2 != -1 ? q2 : length, q3 != -1 ? q3 : length);\n\n return url.slice(0, q);\n}", "function trimUrlQuery(url) {\n const length = url.length;\n const q1 = url.indexOf(\"?\");\n const q2 = url.indexOf(\"&\");\n const q3 = url.indexOf(\"#\");\n const q = Math.min(q1 != -1 ? q1 : length, q2 != -1 ? q2 : length, q3 != -1 ? q3 : length);\n\n return url.slice(0, q);\n}", "function scrubUrl() {\n Util.Url.scrubQueryString('phone');\n Util.Url.scrubQueryString('email');\n }", "getExistingQueryParams() {\n const params = _.omit(this.parseParms(window.location.href.split('?')[1]), ['skip', 'take', 'page', \"\"]);\n let str = '';\n\n for (let key in params) {\n str += `${key}=${params[key]}&`\n }\n\n return str === '=&' ? '' : str.slice(0, -1);// removes the last ampersand\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
attacks an other if they are next to the given bot
function attack(bot) { for (var i = 0; i < others.length; i++) { if (nextTo(bot.x, bot.y, others[i].x, others[i].y)) { bot.attack(others[i]); console.log(bot + " has attacked " + others[i]); return true; } } return false; }
[ "function attackEnemy() {\n\tvar enemy = hero.findNearestEnemy();\n\tif (enemy) {\n\t\thero.attack(enemy);\n\t}\n}", "function AttackNextPlayer() {\n Orion.Ignore(self);\n var target = Orion.FindType(\"-1\", \"-1\", \"ground\", \"human|near|live|ignorefriends\", 18, \"gray|criminal|orange|red\");\n if (target.length != 0) {\n Orion.Attack(target[0]);\n Orion.Ignore(target[0]);\n } else {\n Orion.IgnoreReset();\n Orion.Ignore(self);\n target = Orion.FindType(\"-1\", \"-1\", \"ground\", \"human|near|live|ignorefriends\", 18, \"gray|criminal|orange|red\");\n if (target.length != 0) {\n Orion.Attack(target[0]);\n Orion.Ignore(target[0]);\n }\n }\n}", "onHurt(other, me) {\n if (me.invulTime <= 0) { \n if (other instanceof Enemy) { if (other.hazard) { me.recieveDamage(1); }} //Specifically if the player overlaps with an enemy (Currently only way to take damage).\n me.invulTime = 2;\n }\n }", "function findAndAttackEnemy() {\n\tvar enemy = hero.findNearestEnemy();\n\tif (enemy) {\n\t\thero.attack(enemy);\n\t}\n}", "attackAvenger() {\n const avengerMessage = this.createMessage(\n `${this.avenger.name} attacks with <span>${\n this.avenger.skills[0]\n }</span> !`,\n );\n this.api.sendMessage({\n content: avengerMessage,\n type: 'attack',\n attacker: this.client.getUserId(),\n });\n }", "hit(other) {\n if (this.shielded) {\n this.hitShieldSound.play();\n return;\n }\n\n const tag = other.body.tag;\n if (!GameInfo.hasContractedDisease(tag)) {\n GameInfo.contractDisease(tag);\n }\n\n if (!this.immunities.has(tag)) {\n Engine.emit('cisTakenDamage');\n this.damaged(other.damage);\n }\n }", "function attackPCs(self, here){ // aggro\r\n\t\t\tif(self && here){\r\n\t\t\t\tvar attackArr = here.getMobs(-1);\r\n\t\t\t\tif(attackArr.length > 0){\r\n\t\t\t\t\tvar target = attackArr[random(0, attackArr.length-1)];\r\n\t\t\t\t\tif(!self.fighting && !hasCollar()){\r\n\t\t\t\t\t\tself.say(\"Get away from me!\");\r\n\t\t\t\t\t\tself.comm(\"k \"+target.name);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}", "attack(opponent) {\n // console.log which character was attacked and how much damage was dealt\n // Then, change the opponent's hitPoints to reflect this\n }", "monsterAttack() {\r\n if (this.isMonsterAttacking()) {\r\n this.monster.attack();\r\n }\r\n }", "attack(target) {\n if (target.living) {\n target.takeDamage(this.damage);\n this.scene.events.emit('Message', `${this.type} attacks ${target.type} for ${this.damage} damage`);\n }\n }", "function PKAttackNextPlayer() {\n Orion.Ignore(self);\n var target = Orion.FindType(\"-1\", \"-1\", \"ground\", \"human|near|live|ignorefriends\", 18, \"gray|criminal|orange|red|innocent|blue\");\n if (target.length != 0) {\n Orion.Attack(target[0]);\n Orion.Ignore(target[0]);\n } else {\n Orion.IgnoreReset();\n Orion.Ignore(self);\n target = Orion.FindType(\"-1\", \"-1\", \"ground\", \"human|near|live|ignorefriends\", 18, \"gray|criminal|orange|red|innocent|blue\");\n if (target.length != 0) {\n Orion.Attack(target[0]);\n Orion.Ignore(target[0]);\n }\n }\n}", "attack(opponent) {\n // console.log which character was attacked and how much damage was dealt\n // Then, change the opponent's hitPoints to reflect this\n // damage = the other guys hitpoints\n console.log(`${opponent.name} was attacked with ${this.strength} damage.`)\n opponent.hitpoints = opponent.hitpoints - this.strength;\n }", "attack (enemy) {\n\n this.moraleBuff ();\n\n var atkRoll = this.atk * Math.random();\n var defRoll = enemy.def * Math.random();\n var dmg = (atkRoll - defRoll);\n\n if (dmg > 0) {\n var rndDmg = Math.floor(dmg);\n window.socket.emit('attack', rndDmg);\n this.armyMorale(3);\n enemy.takeDmg(rndDmg);\n return 1;\n\n } else {\n window.socket.emit('attackMiss');\n console.log('Swing and a miss, morale bar will not change');\n return 0;\n }\n // enemy.troops -= 100;\n\n }", "function enemyActions(){\n if(turn >= maxTurn){\n for(person in otherteam){\n if(otherteam[person].health > 0){\n AIattack(otherteam[person]);\n }\n }\n turn = 0;\n $('.highlightedRED').removeClass('highlightedRED');\n for(person in team){\n team[person].turn = 1;\n }\n }\n }", "eat(other) {\n // Only eat if you're active\n if (!avatar.active) {\n return;\n }\n\n // Add the size of the other agent to this one\n // But constrain it within the maximum size\n this.size = constrain(this.size + other.size,0,this.maxSize);\n // Reset the other agent to \"kill\" it\n other.reset();\n }", "function randomAttack(warriorOne, warriorTwo) {\n\tinquirer.prompt([\n\t\t{\t\n\t\t\ttype: 'list',\n\t\t\tname: 'coinFace',\n\t\t\tmessage: 'Flip coin to randomly attack: ',\n\t\t\tchoices: [\"Heads\",\"Tails\"]\n\t\t}\n\t]). then(function(coinChoice) {\n\t\tvar compare = Math.floor(Math.random() * 2) === 1 ? 'heads' : 'tails';\n\t\tif(coinChoice.coinFace.toLowerCase() === compare) {\n\t\t\tconsole.log(`\n-------------------------\n${warriorOne.name} attacks ${warriorTwo.name}\n-------------------------\n`);\n\t\t\twarriorOne.attack(warriorTwo);\n\t\t}else {\n\t\t\twarriorTwo.attack(warriorOne);\n\t\t\tconsole.log(`\n-------------------------\n${warriorTwo.name} attacks ${warriorOne.name}\n-------------------------\n`);\n\t\t}\n\t\tcontinueGame(warriorOne, warriorTwo, 'random');\n\t});\n}", "attackTarget(attack) {\n _gameService.attackTarget(attack)\n draw()\n }", "attack(location){ //CHANGE TO ATTACK LOCATION RATHER THAN ATTACK DIRECTION\n //iterates through enemylist and if it encounters an enemy in the target location attacks them\n enemyUnits.forEach(enemy => {\n if(enemy.location.x==location.x && enemy.location.y==location.y){\n log('enemy attacked');\n this.attackFunction(enemy);\n }\n });\n }", "function attackActor(aggressor, x, y){\n\t//get the victim based on the x and y values of new tile being moved into\n\tlet victimIndex = actorPositions.indexOf(x + \"_\" + y);\n\tlet victim = actorList[victimIndex];\n\tlet victimDead = false;\n\n\tlet playerDead = false;\n\n\tif(victim != player && aggressor != player){\n\t\t//do nothing, victim is friend \n\t}\n\telse{\n\t\tif(victim == player){\n\t\t\t//enemy is attacking player\n\t\t\tlet aug = player.augmentations.find(function(a){return a.type == Aug.DEF;});\n\t\t\tlet playerHit = true;\n\t\t\tif(aug != undefined){\n\t\t\t\t//if player has dodge chance, determine if they are successful in dodging attack\n\t\t\t\tlet dodgeAmount = 100*(aug.effectVal*aug.level);\n\t\t\t\tlet chanceToHit = 100-dodgeAmount;\n\t\t\t\tlet diceRoll = Math.ceil(Math.random() * 100);\n\t\t\t\t//random number between 1 and 100\n\t\t\t\t//if that number is the same or under the chance to hit (of say 95) then deal dmg, otherwise player dodges\n\t\t\t\t//playerhit is false if missed\n\t\t\t\tplayerHit = diceRoll <= chanceToHit; \n\t\t\t}\n\t\t\t//if could not dodge\n\t\t\tif(playerHit){\n\t\t\t\tlet pHit = game.add.audio('playerHurt', 0.5); //play sound\n\t\t\t\tpHit.play();\n\t\t\t\t//update player HP\n\t\t\t\tplayer.hp -= aggressor.dmg;\n\t\t\t\tif(player.hp < 0) player.hp = 0; //prevent negative hp\n\t\t\t\thud.updateReadout(\"I took \" + aggressor.dmg + \" damage.\");\n\t\t\t\thud.updateHP();\n\t\t\t\t//account for enemy type 2 which can knock the player down\n\t\t\t\tif(aggressor.type == 2 && !player.isStunned){\n\t\t\t\t\tplayer.isStunned = true;\n\t\t\t\t\tplayer.sprite.kill();\n\t\t\t\t\t//add and play the death animation, which works for being knocked down\n\t\t\t\t\tplayer.sprite = game.add.sprite(player.y*64, player.x*64, 'playerDeath', 0); \n\t\t\t\t\tplayer.sprite.anchor.y = 0.3 ;\n\t\t\t\t\tplayer.sprite.animations.add('playerDeath', [0, 1, 2, 3, 4, 5], 18, false);\n\t\t\t\t\tplayer.sprite.animations.play('playerDeath');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tlet playerDodged = game.add.audio('miss', 0.3).play(); //play dodge sound\n\t\t\t\thud.updateReadout(\"I dodged their attack.\");\n\t\t\t}\n\t\t}\n\t\telse if(aggressor == player){\n\t\t\t//player is attacking an enemy\n\t\t\t\n\t\t\t//check if attack hits (enemy 2 and 3 have dodge chance)\n\t\t\tlet chanceToHitEnemy = 100-victim.dodgeChance;\n\t\t\tif(Math.floor(Math.random()*100) <= chanceToHitEnemy){\n\t\t\t\tlet aug = player.augmentations.find(function(a){return a.type == Aug.VAMP;});\n\t\t\t\t//if player has vampiric augmentation, they can steal HP from enemies\n\t\t\t\tif(aug != undefined){\n\t\t\t\t\tif(player.hp < player.maxHP){\n\t\t\t\t\t\tplayer.hp += player.dmg*(aug.level * aug.effectVal); //5% vamp to begin with\n\t\t\t\t\t\tif(player.hp > player.maxHP){\n\t\t\t\t\t\t\tplayer.hp = player.maxHP;\n\t\t\t\t\t\t}\n\t\t\t\t\t\thud.updateHP();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgame.add.audio('zap', 0.2, false).play(); //play sound\n\t\t\t\tvictim.hp -= aggressor.dmg;\n\t\t\t\thud.updateReadout(\"I did \" + aggressor.dmg + \" damage to the enemy.\");\n\t\t\t\tlet hurtString;\n\n\t\t\t\t//change readout depending on how hurt the enemy is in relation to their maximum HP\n\t\t\t\tif(victim.hp>victim.maxHP*0.9){\n\t\t\t\t\thud.updateReadout(\"They look relatively untouched.\");\n\t\t\t\t}\n\t\t\t\telse if(victim.hp>victim.maxHP*0.5){\n\t\t\t\t\thud.updateReadout(\"They look hurt.\");\n\t\t\t\t}\n\t\t\t\telse if(victim.hp<=victim.maxHP*0.25){\n\t\t\t\t\thud.updateReadout(\"They look close to death.\");\n\t\t\t\t}\n\t\t\t\telse if(victim.hp<=victim.maxHP*0.5){\n\t\t\t\t\thud.updateReadout(\"They look badly hurt.\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tlet enemyDodged = game.add.audio('miss', 0.3).play(); //play sound\n\t\t\t\thud.updateReadout(\"They dodged my attack!\");\n\t\t\t}\n\t\t}\n\n\t\t//if victim has HP <= 0 they are killd\n\t\tif(victim.hp <= 0){\n\t\t\tvictimDead = true;\n\t\t\tif(victim == player){\n\t\t\t\tplayer.sprite.kill();\n\t\t\t\tplayer.sprite = game.add.sprite(player.y*64, player.x*64, 'playerDeath', 0); \n\t\t\t\tplayer.sprite.anchor.y = 0.3 ;\n\t\t\t\t//play death animation\n\t\t\t\tplayer.sprite.animations.add('playerDeath', [0, 1, 2, 3, 4, 5], 18, false);\n\t\t\t\tplayer.sprite.animations.play('playerDeath');\n\t\t\t\t//flag for game over\n\t\t\t\tplayerDead = true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//if enemy killed, update score, exp and credits\n\t\t\t\tplayer.score += victim.score;\n\t\t\t\tplayer.exp += victim.exp;\n\t\t\t\thud.updateEXP();\n\t\t\t\thud.updateReadout(\"Enemy killed. I found \" + victim.credits + \" credits on them.\");\n\n\t\t\t\t//if player has gained enough EXP, their level and stats increase\n\t\t\t\tif(player.exp >= expThreshold){\n\t\t\t\t\t//UPDATE HUD\n\t\t\t\t\tplayer.lvl++;\n\t\t\t\t\tplayer.maxHP += 5;\n\t\t\t\t\tplayer.hp+=5;\n\t\t\t\t\tplayer.dmg += 2;\n\n\t\t\t\t\texpThreshold *= 2;\n\t\t\t\t\thud.updateReadout(\"I feel stronger.\");\n\t\t\t\t\thud.updateDMG();\n\t\t\t\t\thud.updateHP();\n\t\t\t\t\thud.updateLevel();\n\t\t\t\t\thud.updateEXP();\n\t\t\t\t\tconsole.log(\"LEVEL UP!\");\n\t\t\t\t\tconsole.log(player);\n\t\t\t\t}\n\t\t\t\tplayer.credits += victim.credits;\n\t\t\t\tcreditsEarned += victim.credits;\n\t\t\t\thud.updateCredits();\n\t\t\t\tvictim.sprite.kill();\n\t\t\t\tlet deathSpriteName;\n\n\t\t\t\t//choose a different sprite depending on enemy type\n\t\t\t\tif(victim.type == 1){\n\t\t\t\t\tdeathSpriteName = 'armor1Death';\n\t\t\t\t}\n\t\t\t\telse if(victim.type == 2){\n\t\t\t\t\tdeathSpriteName = 'armor2Death';\n\t\t\t\t}\n\t\t\t\telse if(victim.type == 3){\n\t\t\t\t\tdeathSpriteName = 'agentDeath';\n\t\t\t\t}\n\t\t\t\tlet deathSprite = game.add.sprite(victim.y*64, victim.x*64, deathSpriteName, 0); \n\t\t\t\tdeathSprite.anchor.y = 0.3 ;\n\t\t\t\tdeathSprite.animations.add(deathSprite, [0, 1, 2, 3, 4, 5], 18, false);\n\t\t\t\tdeathSprite.animations.play(deathSprite);\n\t\t\t\thud.initHUD(); //hud covers corpses\n\n\t\t\t\tactorList.splice(victimIndex, 1);\n\t\t\t\tactorPositions.splice(victimIndex, 1);\n\t\t\t\tenemiesKilled++;\n\t\t\t}\n\t\t}\n\t}\n\n\t//game over if player is dead\n\tif(playerDead){\n\t\tshowGameOverScreen(\"Defeat\");\n\n\t}\n\telse{\n\t\t//return true if victim has died and cell is now free to move into\n\t\treturn victimDead;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
var res = stylesheet.run(css) console.log(res) var flattenedcssast = transpileSassAst(res.result) console.log(flattenedcssast) console.log(csstree2string(flattenedcssast))
function transpileSassAst(ast) { return ast.flatMap(rs => flatten(rs)); }
[ "function ssrCodegenTransform(ast, options) {\n\t const context = createSSRTransformContext(ast, options);\n\t // inject SFC <style> CSS variables\n\t // we do this instead of inlining the expression to ensure the vars are\n\t // only resolved once per render\n\t if (options.ssrCssVars) {\n\t const varsExp = compilerDom.processExpression(compilerDom.createSimpleExpression(options.ssrCssVars, false), compilerDom.createTransformContext(compilerDom.createRoot([]), options));\n\t context.body.push(compilerDom.createCompoundExpression([`const _cssVars = { style: `, varsExp, `}`]));\n\t }\n\t const isFragment = ast.children.length > 1 && ast.children.some(c => !compilerDom.isText(c));\n\t processChildren(ast.children, context, isFragment);\n\t ast.codegenNode = compilerDom.createBlockStatement(context.body);\n\t // Finalize helpers.\n\t // We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'\n\t ast.ssrHelpers = Array.from(new Set([\n\t ...ast.helpers.filter(h => h in ssrHelpers),\n\t ...context.helpers\n\t ]));\n\t ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers));\n\t}", "function cssTranspile() {\n\treturn src(paths.styles.input)\n\t\t.pipe(sourcemaps.init()) // initialize sourcemaps first\n\t\t.pipe(sass()) // compile SCSS to CSS\n\t\t.pipe(sourcemaps.init()) // start sourcemaps \n\t\t.pipe(sourcemaps.write('.')) // write sourcemaps file in current directory\n\t\t.pipe(dest(paths.styles.output)) // put final CSS in dist folder\n\t\t.pipe(connect.reload());\n}", "visitStylesheet(stylesheet) { }", "function makeCssAst (cssString) {\n if (!cssString) {\n return null\n }\n return cssParse(cssString)\n}", "compileSASS() {\n const entry = path.resolve(this.app.config.styles.entry);\n const output = path.resolve(path.join(this.app.config.dist, this.app.config.styles.output));\n const sassOptions = {\n file: entry,\n includePaths: [path.dirname(entry)],\n outputStyle: this.app.config.styles.outputStyle,\n imagePath: this.app.config.styles.imagePath || path.dirname(entry),\n precision: this.app.config.styles.precision,\n errLogToConsole: this.app.config.styles.errLogToConsole,\n };\n this.timer.start();\n sassCompiler.render(sassOptions, (err, styles) => {\n if (err) {\n this.handleErrorSass(err);\n return;\n }\n if (styles.css.toString('utf8')) {\n const fixed = pleeease.process(styles.css.toString('utf8'), this.app.config.styles.pleeeaseOpt);\n fixed.then(css => {\n this.saveStyles(css, output);\n });\n }\n });\n }", "processStyles(css) {\n return stylis(':host', css)\n }", "static separateStyleRules(cssLiteral) {\n/* Declare an array for our separated rules, an @rule flag, and also,\ngenerate our ast css tree...*/\n let rules = [],\n atRule = false,\n// AST tree...\n ast = cssTree.parse(cssLiteral, {\n// Log parsing errors...\n onParseError: (e)=> {\n log(e.formattedMessage, ['white', 'red'])\n }\n })\n\n// Walk the css ast tree, stopping at rule nodes to regenerate and add to an array...\n cssTree.walk(ast, {\n enter: (node)=> {\n// log('#####################################-CSS AST NODE-########################################', ['yellow', 'red']);// log(node.type, 'orange')\n// If the node type is of Rule or @rule, meaning @media etc., ......\n if (node.type === 'Rule' || node.type === 'Atrule') {\n// Regenerate valid css from the rule...\n let rule = cssTree.generate(node)\n/* If the atRule flag is still false and if the regen'd rule doesn't equal a\npossibly set atRule css string, ......*/\n if (!!!atRule && rule !== atRule) {\n// And if the node type is `Atrule`....\n if (node.type === 'Atrule') {\n// Set the `atRule` flag to the regen'd @Rule block, including selectors....\n atRule = cssTree.generate(\n node.block.children.head.data\n )\n // log(cssTree.generate(node.block.children.head.data))\n }\n// Push the regen'd rule to the rules array....\n rules.push(rule)\n }\n }\n }\n })\n// Return the array of rules...\n return rules\n }", "initFilesAst() {\n this.cssAst = css.parse(this.cssText);\n this.jsAst = esprima.parse(this.jsText);\n }", "function compileSassToCSS() {\n return gulp\n .src(files.scssPath.src)\n .pipe(gulpSass())\n .pipe(gulp.dest(files.scssPath.dest));\n}", "function convertToCSS(source, callback){\n $.ajax({\n url: \"http://alloy.divshot.com/compile/scss\",\n type: \"POST\",\n data: {\n type: \"scss\",\n // source: \".button{ background: blue; }\"\n source: mixins + \" \" + source\n },\n success: function(css) {\n callback(css);\n },\n error: function(){\n console.log(\"error...invalid css maybe\");\n }\n });\n }", "function transformSourceFile(node){return node;}", "async run(options) {\n isDev = !!options.isDev;\n try {\n // 1. Get all scss files within project\n let files = targetDirectory.map(file => {\n return recursive(file).then(files => files)\n })\n files = await Promise.all(files).then(res => res)\n files = files.flat(Infinity)\n\n files = files.map(file => {\n return {\n path: file,\n ...extractFileInPath(file)\n }\n }).filter(f => f.ext === 'scss')\n\n const outputDir = extractDirInPath(outputPath).str\n\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir)\n }\n\n // 2. Merge all files to one file\n const outputMerged = `${outputDir}/merged.scss`\n await mergeFiles(files.map(f => f.path), outputMerged).then((status) => {\n // 3. Compile scss to css.\n [outputMerged].forEach(async file => {\n const data = await render(file)\n\n // Temporary write css file\n fs.writeFile(`${outputDir}/temp.css`, data.css, () => {})\n\n // Merge and adjust CSS and remove duplications\n postcss([combineSelectors({removeDuplicatedProperties: true})])\n .process(data.css, {from: `${outputDir}/temp.css`, to: outputPath})\n .then((result) => {\n fs.writeFileSync(outputPath, result.css);\n });\n\n // remove merged source\n try {\n fs.unlink(outputMerged, (err) => {\n if (err) {\n console.error(err)\n return\n }\n })\n fs.unlink(`${outputDir}/temp.css`, (err) => {\n if (err) {\n console.error(err)\n return\n }\n })\n } catch(err) {\n console.error(err)\n }\n })\n })\n\n return\n } catch (err) {\n console.error(err)\n }\n }", "async function compileSassSources() {\n // Main CSS\n let targetFile = 'dist/assets/css/casa.css';\n const { css } = renderSync({\n file: 'assets/scss/casa.scss',\n includePaths: [\n 'assets/scss/',\n ],\n outputStyle: 'compressed',\n outFile: targetFile,\n quietDeps: true,\n });\n await writeFile(targetFile, css, { encoding: 'utf8' });\n\n // IE8 support\n targetFile = 'dist/assets/css/casa-ie8.css';\n const { css: cssIe8 } = renderSync({\n file: 'assets/scss/casa-ie8.scss',\n includePaths: [\n 'assets/scss/',\n ],\n outputStyle: 'compressed',\n outFile: targetFile,\n quietDeps: true,\n });\n await writeFile(targetFile, cssIe8, { encoding: 'utf8' })\n}", "function cssToSss (css, file) {\n if (path.extname(file) === '.css') {\n return postcss().process(css, { stringifier: sugarss }).then(function (result) {\n return result.css\n })\n } else {\n return css\n }\n }", "function toCSS(tree, sourceMapFilename) {\n return Rx.Observable.defer(function(push, next) {\n try {\n var sourceMapData;\n var cssData = tree.toCSS({\n sourceMap: true,\n sourceMapFilename: sourceMapFilename,\n // fill sourcesContent\n outputSourceFiles: true,\n writeSourceMap: function writeSourceMap(data) {\n // this whole pseudo async is somewhat ridiculous\n sourceMapData = data;\n }\n });\n return Rx.Observable.return({data: cssData, sourceMapData: sourceMapData});\n } catch(e) {\n return Rx.Observable.throw(e);\n }\n });\n}", "scssToSass(string) {\n return string.replace(/{/g, '').replace(/}/g, '').replace(/;/g, '');\n }", "function compileCss() {\n try {\n fs\n .writeFile('./dist/suprematism.css', compile('./src/lib/suprematism.scss'), function (err) {\n if (err) throw err;\n console.log(\"Success: CSS Compiled\");\n concatBasscss();\n console.log(\"Success: Concat\\' all additional thirdparty CSS\");\n copyAudriFonts();\n console.log(\"Success: Copied additional files\");\n });\n }\n catch(err){\n console.error(err);\n }\n}", "function transformScssToString(babel) {\n const { types: t } = babel;\n return {\n name: 'babel-plugin-transform-scss-import-to-string',\n visitor: {\n ImportDeclaration(path, state) {\n // Drop these options\n const userOptions = state.opts;\n delete userOptions.file;\n delete userOptions.data;\n // Filter *.scss imports\n if (!/\\.scss$/.test(path.node.source.value)) return;\n // Get full path to file and transpile it\n const scssFileDirectory = resolve(dirname(state.file.opts.filename));\n const fullScssFilePath = join(\n scssFileDirectory,\n path.node.source.value\n );\n const rawScssContent = readFileSync(fullScssFilePath).toString();\n const projectRoot = process.cwd();\n const nodeModulesPath = join(projectRoot, 'node_modules');\n const sassDefaults = {\n data: rawScssContent,\n sourceMap: false,\n includePaths: [nodeModulesPath, scssFileDirectory, projectRoot],\n };\n const sassResult = renderSync(\n Object.assign({}, sassDefaults, userOptions)\n );\n const transpiledContent = sassResult.css.toString() || '';\n // Extract import name\n const defaultImportNode = path.node.specifiers.find(\n isImportDefaultSpecifier\n );\n if (!defaultImportNode) return;\n const defaultImportName = defaultImportNode.local.name;\n // Replace import with hardcoded value\n path.replaceWith(\n t.variableDeclaration('const', [\n t.variableDeclarator(\n t.identifier(defaultImportName),\n t.stringLiteral(transpiledContent)\n ),\n ])\n );\n },\n },\n };\n}", "function ParserCSS( ) {\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
process a material chunk from .bwo file, return one material/group
function get_matgroup(uc) { var om = {}; var cn; var ct; var chi; om.color = {"x":1,"y":1,"z":1,"w":1}; while(chi = uc.getchunkheader()) { if (chi.ct==uc.chunktypeenum.KID_ENDCHUNK) { break; } else if (chi.numele && chi.ct==uc.chunktypeenum.KID_I8) { switch(chi.cn) { case uc.chunknameenum.UID_NAME: om.name=uc.readI8v(); break; case uc.chunknameenum.UID_DTEX: //if (om.dtex) { // uc.skipdata(); //} else { om.dtex=uc.readI8v(); //} break; default: uc.skipdata(); break; } } else if (!chi.numele && chi.ct==uc.chunktypeenum.KID_I32) { switch(chi.cn) { case uc.chunknameenum.UID_FO: om.fo = uc.readI32(); break; case uc.chunknameenum.UID_FS: om.fs = uc.readI32(); break; case uc.chunknameenum.UID_VO: om.vo = uc.readI32(); break; case uc.chunknameenum.UID_VS: om.vs = uc.readI32(); break; default: uc.skipdata(); break; } } else if (!chi.numele && chi.ct==uc.chunktypeenum.KID_VEC3) { switch(chi.cn) { case uc.chunknameenum.UID_DIFFUSE: om.color = uc.readVC3(); om.color.w = 1; break; default: uc.skipdata(); break; } } else { uc.skipdata(); } } return om; }
[ "function readBVFile(text, groupInfo) {\r\n var input, cur, patches, kind, name, order, orderU, orderV, cp, groupNames;\r\n input = text.split(/\\s+/);\r\n cur = 0;\r\n\r\n\r\n function readCP(n, rational) {\r\n\t\tvar i, j, l, b;\r\n\t\tl = rational ? 4 : 3;\r\n\t\tb = new Float32Array(n * 4);\r\n\t\tfor(i = 0; i < n; i += 1) {\r\n\t\t\tb[i*4+0] = Number(input[cur+0]);\r\n\t\t\tb[i*4+1] = Number(input[cur+1]);\r\n\t\t\tb[i*4+2] = Number(input[cur+2]);\r\n\t\t\tb[i*4+3] = rational ? Number(input[cur+3]) : 1.0;\r\n\t\t\tcur += l;\r\n\t\t}\r\n\t\treturn b;\r\n }\r\n function readCPInverse(n, rational) {\r\n\t\tvar i, j, l, b;\r\n\t\tl = rational ? 4 : 3;\r\n\t\tb = new Float32Array(n * 4);\r\n\t\tfor(i = n - 1; i >= 0; i -= 1) {\r\n\t\t\tb[i*4+0] = Number(input[cur+0]);\r\n\t\t\tb[i*4+1] = Number(input[cur+1]);\r\n\t\t\tb[i*4+2] = Number(input[cur+2]);\r\n\t\t\tb[i*4+3] = rational ? Number(input[cur+3]) : 1.0;\r\n\t\t\tcur += l;\r\n\t\t}\r\n\t\treturn b;\r\n }\r\n\r\n patches = [];\r\n\tgroupNames = [];\r\n /* Read as many patches as possible */\r\n\t// TODO detect if patch part of existing group\r\n while(cur < input.length && input[cur] != \"\") {\r\n\r\n\t\tif(input[cur].toUpperCase() == \"GROUP\")\r\n\t\t{\r\n\t\t\tcolor = Number(input[++cur]);\r\n\t\t\tname = input[++cur];\r\n\r\n\t\t\tif (groupNames.indexOf(name) <= -1) {\r\n\t\t\t\t// group doesn't already exist, make new group\r\n\t\t\t\tgroupNames.push(name);\r\n\t\t\t\tgroupInfo.push(new groupInfoHelper(color, name));\r\n\t\t\t}\r\n\t\t\t++cur;\r\n\t\t}\r\n\r\n\t\tkind = Number(input[cur]);\r\n\t\tcur += 1;\r\n\r\n\t\tswitch(kind) {\r\n case 1:\r\n\t\t\t// retrieve # vertices and # faces\r\n\t\t\tvar numVertices, numFaces, extraFaces = 0;\r\n\t\t\tnumVertices = Number(input[cur]); cur += 1;\r\n\t\t\tnumFaces = Number(input[cur]); cur += 1;\r\n\r\n\t\t\t// load vertices\r\n\t\t\tvar v = [];\r\n\t\t\tfor(var i = 0; i < numVertices; i++) {\r\n\t\t\t\tvar x = Number(input[cur+0]);\r\n\t\t\t\tvar y = Number(input[cur+1]);\r\n\t\t\t\tvar z = Number(input[cur+2]);\r\n\t\t\t\tv.push(new vec4(x,y,z,1));\r\n\r\n\t\t\t\tcur+=3;\r\n\t\t\t}\r\n\r\n\t\t\t// load faces\r\n\t\t\tvar f = [];\r\n\t\t\tfor(var i = 0; i < numFaces; i++) {\r\n\t\t\t\tvar numVertFace = Number(input[cur]); cur += 1;\r\n\t\t\t\tif (numVertFace == 3) {\r\n\t\t\t\t\tvar a = Number(input[cur+0]);\r\n\t\t\t\t\tvar b = Number(input[cur+1]);\r\n\t\t\t\t\tvar c = Number(input[cur+2]);\r\n\t\t\t\t\tf.push(new vec4(a,b,c,0));\r\n\r\n\t\t\t\t\tcur += 3;\r\n\t\t\t\t} else if (numVertFace == 4) {\r\n\t\t\t\t\t// transform one quad face into two triangle faces\r\n\t\t\t\t\t// triangle a, b, c\r\n\t\t\t\t\tvar a = Number(input[cur+0]);\r\n\t\t\t\t\tvar b = Number(input[cur+1]);\r\n\t\t\t\t\tvar c = Number(input[cur+2]);\r\n\t\t\t\t\tf.push(new vec4(a,b,c,0));\r\n\r\n\t\t\t\t\t// triangle a, c, d\r\n\t\t\t\t\tvar d = Number(input[cur+3]);\r\n\t\t\t\t\tf.push(new vec4(a,c,d,0));\r\n\r\n\t\t\t\t\textraFaces++;\r\n\t\t\t\t\tcur += 4;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tthrow new Error(\"What kind of face is that?\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tpatches.push(new Patch(PatchType.Polyhedral, numVertices, (numFaces+extraFaces), v, f, name));\r\n\t\t\tbreak;\r\n\r\n case 3:\r\n /* the file has degree, we use order */\r\n order = Number(input[cur]) + 1; cur += 1;\r\n /* We use the reverse ordering of BV\r\n 0\r\n 1 2\r\n 3 4 5\r\n . . .\r\n\r\n It makes it easier when calculating applying de Casteljau algorithm\r\n\r\n TODO: make sure the winding order is correct\r\n */\r\n cp = readCPInverse(order * (order + 1)/2, false);\r\n patches.push(new Patch(PatchType.Triangle,order, order, cp, null, name));\r\n break;\r\n\r\n case 4:\r\n\t\t\torder = Number(input[cur]) + 1; cur += 1;\r\n\t\t\tcp = readCP(order * order, rational = false);\r\n\t\t\tpatches.push(new Patch(PatchType.Quadrilateral, order, order, cp, null, name));\r\n\t\t\tbreak;\r\n\r\n case 5: case 8:\r\n\t\t\torderV = Number(input[cur]) + 1; cur += 1;\r\n\t\t\torderU = Number(input[cur]) + 1; cur += 1;\r\n\t\t\tcp = readCP(orderU * orderV, kind == 8);\r\n\t\t\tpatches.push(new Patch(PatchType.Quadrilateral, orderU, orderV, cp, null, name));\r\n\t\t\tbreak;\r\n\r\n case 9:\r\n\t\t\tthrow new Error(\"PN Triangle patches are not supported.\");\r\n\t\t\tbreak;\r\n\r\n case 10:\r\n\t\t\tthrow new Error(\"PN Quad patches are not supported.\");\r\n\t\t\tbreak;\r\n\r\n default:\r\n\t\t\tthrow new Error(\"Unknown patch type \" + kind);\r\n\t\t}\r\n }\r\n return patches;\r\n}", "readingMaterials(materialElem) {\n var materials = materialElem.getElementsByTagName('material');\n if (materials.length == 0)\n this.graph.onXMLError(\"components:: it must have at least one material block.\");\n\n let i = 0;\n for (let material of materials) {\n var id = this.reader.getString(material, 'id');\n if (id == \"inherit\") {\n this.cgfMaterialId = \"inherit\";\n break;\n } else if (typeof this.graph.materials[id] == 'undefined')\n this.graph.onXMLError(\"components:: it doens't exist any material with that id, \" + id + \".\");\n else {\n if (i == 0) {\n this.cgfMaterial = this.graph.materials[id];\n i++\n }\n this.cgfMaterials.push(this.graph.materials[id]);\n }\n }\n }", "sampleToChunk(sample) {\n\n /* Samples are grouped in chunks which may contain a variable number of samples.\n * The sample-to-chunk table in the stsc box describes how samples are arranged\n * in chunks. Each table row corresponds to a set of consecutive chunks with the\n * same number of samples and description ids. For example, the following table:\n *\n * +-------------+-------------------+----------------------+\n * | firstChunk | samplesPerChunk | sampleDescriptionId |\n * +-------------+-------------------+----------------------+\n * | 1 | 3 | 23 |\n * | 3 | 1 | 23 |\n * | 5 | 1 | 24 |\n * +-------------+-------------------+----------------------+\n *\n * describes 5 chunks with a total of (2 * 3) + (2 * 1) + (1 * 1) = 9 samples,\n * each chunk containing samples 3, 3, 1, 1, 1 in chunk order, or\n * chunks 1, 1, 1, 2, 2, 2, 3, 4, 5 in sample order.\n *\n * This function determines the chunk that contains a specified sample by iterating\n * over every entry in the table. It also returns the position of the sample in the\n * chunk which can be used to compute the sample's exact position in the file.\n *\n * TODO: Determine if we should memoize this function.\n */\n\n const table = this.trak.mdia.minf.stbl.stsc.table;\n\n if (table.length === 1) {\n let row = table[0];\n assert (row.firstChunk === 1);\n return {\n index: Math.floor(sample / row.samplesPerChunk),\n offset: sample % row.samplesPerChunk\n };\n }\n\n let totalChunkCount = 0;\n for (let i = 0; i < table.length; i++) {\n const row = table[i];\n if (i > 0) {\n const previousRow = table[i - 1];\n const previousChunkCount = row.firstChunk - previousRow.firstChunk;\n const previousSampleCount = previousRow.samplesPerChunk * previousChunkCount;\n if (sample >= previousSampleCount) {\n sample -= previousSampleCount;\n if (i == table.length - 1) {\n return {\n index: totalChunkCount + previousChunkCount + Math.floor(sample / row.samplesPerChunk),\n offset: sample % row.samplesPerChunk\n };\n }\n } else {\n return {\n index: totalChunkCount + Math.floor(sample / previousRow.samplesPerChunk),\n offset: sample % previousRow.samplesPerChunk\n };\n }\n totalChunkCount += previousChunkCount;\n }\n }\n assert(false);\n }", "function matchMBs(pageid,leaderapprv) {\t//tested used\r\n//nbconsole.log(16,leaderapprv);\r\nvar mapname='';\r\nvar found ;\r\n\tvar mbObj = { name : '', id : ''};\r\nvar mbYr;\r\n\r\nvar mbNameReq;\r\nvar mbNamereq1='xx';\r\nvar mbname;\r\nvar skip=false;\r\n\r\nvar mbmatches = 0;\r\nvar compcol = 8;\r\nvar vercol = 7;\r\nvar advcol = 6;\r\nvar advtypecol = 5;\r\nvar resObj={};\r\n\r\n\tunmatchedmb.length=0;\r\n// For x = 0 To mbcnt - 1\r\n// With Meritbadge.ListBox1\r\n// .AddItem mbArr(x)\r\n// End With\r\n// Next x\r\n\r\n\t//find the Advancement Type column and Advancement Columns\r\n\r\n\tfor (var x = 0; x < fileObjs.bpdata[0].length;x++) {\r\n\t\tif (fileObjs.bpdata[0][x] == \"Advancement\") {\r\n\t\t\tadvcol = x;\r\n\t\t}\r\n\t\tif (fileObjs.bpdata[0][x] == \"Advancement Type\") {\r\n\t\t\tadvtypecol = x;\r\n\t\t}\r\n\t\tif (fileObjs.bpdata[0][x] == \"Version\") {\r\n\t\t\tvercol = x;\r\n\t\t}\r\n\t}\r\n\r\n\t// For each Black Pug record might be quicker t build array of unique bp mbs\r\n\tfor (var rowcnt=0;rowcnt < fileObjs.bpdata.length;rowcnt++) {\r\n\r\n\t\t// that is labeled as a Merit Badge\r\n\t\tif (fileObjs.bpdata[rowcnt].length < advtypecol) {\r\n\t\t} else {\r\n\t\t\tif (fileObjs.bpdata[rowcnt][advtypecol].match(/Merit Badge/) != null ) {\r\n\r\n\t\t\t\t//strip the merit badge name - anything preceding a #\r\n\t\t\t//\tif (fileObjs.bpdata[rowcnt][advcol].indexOf('#') != -1) {\r\n\t\t\t//\t\tmbNameReq = fileObjs.bpdata[rowcnt][advcol].match(/([\\w ]+) #/)[1];\r\n\t\t\t//\t} else {\r\n\t\t\t//\t\tmbNameReq = fileObjs.bpdata[rowcnt][advcol];\r\n\t\t\t//\t}\r\n\t\t\t\tresObj={};\r\n\t\t\t\tsplitAdvCol(fileObjs.bpdata[rowcnt][advcol],resObj);\r\n\t\t\t\tmbNameReq = resObj.bpname;\r\n\t\t\t\tmbYr=fileObjs.bpdata[rowcnt][vercol];\r\n\t\t\t\t\r\n\t\t\t\tif (mbNameReq == mbNamereq1) {\r\n\t\t\t\t\t//Already handled\r\n\t\t\t\t\t//alert('handled');\r\n\t\t\t\t} else {\t\r\n\t\t\t\t\t\tmbname = mbNameReq;\t\t\t\t\r\n\t\t\t\t\t\tfor (var z = 0;z<mbArr.length;z++) {\r\n\r\n\t\t\t\t\t\t if (mbname == mbArr[z].name) {\r\n\r\n\t\t\t\t\t\t\t//BPDmbArr(z) = mbname;\r\n\t\t\t\t\t\t\tmbArr[z].bpmbname=mbname;\r\n\t\t\t\t\t\t\t//BPDMbYr(z) = mbYr;\r\n\t\t\t\t\t\t\tmbArr[z].BPDyr=mbYr;\r\n\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t}\t\r\n\t\t\t\t}\t\t\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t/*\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tif (mbNameReq == mbNamereq1) {\r\n\t\t\t\t\t//Already handled\r\n\t\t\t\t\t//alert('handled');\r\n\t\t\t\t} else {\r\n\r\n\t\t\t\t\tmbname = mbNameReq;\r\n\t\t\t\t\tmbNamereq1 = mbNameReq;\r\n\t\t\t\t\t// Check for match in mbname first\r\n\t\t\t\t\tskip = false;\r\n\t\t\t\t\tif (mapname != '') {\r\n\t\t\t\t\t for (var w=0; w<mbArr.length;w++) {\r\n\t\t\t\t\t\t if (mbArr[0].name == mbname) {\r\n\t\t\t\t\t\t //already handled\r\n\t\t\t\t\t\t // BPDmbArr(w) = mbArr[0].name;\r\n\t\t\t\t\t\t // BPDMbYr(w) = mbArr[0].yr;\r\n\t\t\t\t\t\t mbmatches = mbmatches + 1;\r\n\t\t\t\t\t\t skip = true;\r\n\t\t\t\t\t\t break;\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t }\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (skip == false) {\r\n\t\t\t\t\t\tfound = false;\r\n\t\t\t\t\t\tfor (var z = 0;z<mbArr.length;z++) {\r\n\r\n\t\t\t\t\t\t if (Intellimatch(mbname, mbArr[z].name) == true) {\r\n\r\n\t\t\t\t\t\t\t//BPDmbArr(z) = mbname;\r\n\t\t\t\t\t\t\tmbArr[z].bpmbname=mbname;\r\n\t\t\t\t\t\t\t//BPDMbYr(z) = mbYr;\r\n\t\t\t\t\t\t\tmbArr[z].BPDyr=mbYr;\r\n\t\t\t\t\t\t\toffst = z;\r\n\t\t\t\t\t\t\tfound = true;\r\n\t\t\t\t\t\t\tmbmatches = mbmatches + 1;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t }\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (found == false) {\r\n\t\t\t\t\t\t\tmbObj.name=mbname;\r\n\t\t\t\t\t\t\tmbObj.yr=mbYr;\r\n\t\t\t\t\t\t\t unmatchedmb.push(JSON.parse(JSON.stringify(mbObj)));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\t//skip\r\n\r\n\t\t\t\t} //End If previos\r\n\r\n\t\t\t\t\r\n\t\t\t\t*/\r\n\t\t\t} // if merit badge record\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t//setTimeout(\"matchMB('#PageX')\", 1000);\r\n\r\n\t// Handle any unmatched mb names\r\n\tif (unmatchedmb.length >0 ) {\r\n\t\t//console.log(\"ERROR\");\r\n\t}\r\n\t\t//next step?\r\n\t\t//alert('mbs all match');\r\n\r\n\t\tsetTimeout(function () {getScoutMBs(0,leaderapprv);}, 200);\t// was tag_ignores\r\n\t\r\n\r\n\r\n}", "getChunk(idx, data) {\n if (!this.chunks) {\n throw new Error(`Chunks have not been prepared`);\n }\n const proof = this.chunks.proofs[idx];\n const chunk = this.chunks.chunks[idx];\n return {\n data_root: this.data_root,\n data_size: this.data_size,\n data_path: ArweaveUtils.bufferTob64Url(proof.proof),\n offset: proof.offset.toString(),\n chunk: ArweaveUtils.bufferTob64Url(data.slice(chunk.minByteRange, chunk.maxByteRange)),\n };\n }", "function readChunk(file){\n var chunk = new MVoxChunk('', 0, 0, undefined, []);\n\n var buffer = new Buffer(4);\n\n // Read ID\n if (fs.readSync(file, buffer, 0, 4) > 0)\n chunk.id = buffer.toString('ascii');\n\n // Read Size\n if (fs.readSync(file, buffer, 0, 4) > 0)\n chunk.size = buffer.readUIntLE(0, 4);\n\n // Read Size of Children\n if (fs.readSync(file, buffer, 0, 4) > 0)\n chunk.childrenSize = buffer.readUIntLE(0, 4);\n\n // Read Data\n if (chunk.size > 0){\n chunk.contents = new Buffer(chunk.size);\n fs.readSync(file, chunk.contents, 0, chunk.size);\n }\n\n // Read Children Data\n var currentSize = 0;\n if (chunk.childrenSize > 0){\n while (currentSize < chunk.childrenSize){\n var childChunk = readChunk(file);\n chunk.children.push(childChunk);\n currentSize += 12 + childChunk.size + childChunk.childrenSize;\n }\n }\n\n return chunk;\n}", "_findMdat(chunk) {\n if (this._mdatBuffer) {\n this._mdatBuffer.push(chunk);\n const chunkLength = chunk.length;\n this._mdatBufferSize += chunkLength;\n if (this._mdatLength === this._mdatBufferSize) {\n this._setSegment(Buffer.concat([this._moof, ...this._mdatBuffer], this._moofLength + this._mdatLength));\n delete this._moof;\n delete this._mdatBuffer;\n delete this._mdatBufferSize;\n delete this._mdatLength;\n delete this._moofLength;\n this._parseChunk = this._findMoof;\n } else if (this._mdatLength < this._mdatBufferSize) {\n this._setSegment(Buffer.concat([this._moof, ...this._mdatBuffer], this._moofLength + this._mdatLength));\n const sliceIndex = chunkLength - (this._mdatBufferSize - this._mdatLength);\n delete this._moof;\n delete this._mdatBuffer;\n delete this._mdatBufferSize;\n delete this._mdatLength;\n delete this._moofLength;\n this._parseChunk = this._findMoof;\n this._parseChunk(chunk.slice(sliceIndex));\n }\n } else {\n const chunkLength = chunk.length;\n if (chunkLength < 8 || chunk.indexOf(_MDAT) !== 4) {\n this.emit('error', new Error(`${_MDAT.toString()} not found.`));\n return;\n }\n this._mdatLength = chunk.readUInt32BE(0, true);\n if (this._mdatLength > chunkLength) {\n this._mdatBuffer = [chunk];\n this._mdatBufferSize = chunkLength;\n } else if (this._mdatLength === chunkLength) {\n this._setSegment(Buffer.concat([this._moof, chunk], this._moofLength + chunkLength));\n delete this._moof;\n delete this._moofLength;\n delete this._mdatLength;\n this._parseChunk = this._findMoof;\n } else {\n this._setSegment(Buffer.concat([this._moof, chunk], this._moofLength + this._mdatLength));\n const sliceIndex = this._mdatLength;\n delete this._moof;\n delete this._moofLength;\n delete this._mdatLength;\n this._parseChunk = this._findMoof;\n this._parseChunk(chunk.slice(sliceIndex));\n }\n }\n\n \n }", "_findMoov(chunk) {\n const chunkLength = chunk.length;\n if (chunkLength < 8 || chunk.indexOf(_MOOV) !== 4) {\n this.emit('error', new Error(`${_MOOV.toString()} not found.`));\n return;\n }\n const moovLength = chunk.readUInt32BE(0, true);\n if (moovLength < chunkLength) {\n this._parseMoov(Buffer.concat([this._ftyp, chunk], this._ftypLength + moovLength));\n delete this._ftyp;\n delete this._ftypLength;\n this._parseChunk = this._findMoof;\n this._parseChunk(chunk.slice(moovLength));\n } else if (moovLength === chunkLength) {\n this._parseMoov(Buffer.concat([this._ftyp, chunk], this._ftypLength + moovLength));\n delete this._ftyp;\n delete this._ftypLength;\n this._parseChunk = this._findMoof;\n } else {\n //probably should not arrive here here because moov is typically < 800 bytes\n //will have to store chunk until size is big enough to have entire moov piece\n //ffmpeg may have crashed before it could output moov and got us here\n this.emit('error', new Error(`moovLength:${moovLength} > chunkLength:${chunkLength}`));\n //return;\n }\n }", "function makeChunkMesh(self, meshdata, id, chunk) {\n var scene = self._scene\n\n // create/position parent mesh\n var mesh = new BABYLON.Mesh('chunk_' + id, scene)\n var x = chunk.i * chunk.size\n var y = chunk.j * chunk.size\n var z = chunk.k * chunk.size\n mesh.position.x = x\n mesh.position.y = y\n mesh.position.z = z\n mesh.freezeWorldMatrix()\n\n // preprocess meshdata entries to merge those that use default terrain material\n var mdat, i\n var first = null\n var keylist = Object.keys(meshdata)\n for (i = 0; i < keylist.length; ++i) {\n mdat = meshdata[keylist[i]]\n var url = self.noa.registry.getMaterialTexture(mdat.id)\n var alpha = self.noa.registry.getMaterialData(mdat.id).alpha\n if (url || alpha < 1) continue\n\n if (!first) {\n first = mdat\n } else {\n // merge data in \"mdat\" onto \"first\"\n var offset = first.positions.length / 3\n first.positions = first.positions.concat(mdat.positions)\n first.normals = first.normals.concat(mdat.normals)\n first.colors = first.colors.concat(mdat.colors)\n first.uvs = first.uvs.concat(mdat.uvs)\n // indices must be offset relative to data being merged onto\n for (var j = 0, len = mdat.indices.length; j < len; ++j) {\n first.indices.push(mdat.indices[j] + offset)\n }\n // get rid of entry that's been merged\n delete meshdata[keylist[i]]\n }\n }\n\n // go through (remaining) meshdata entries and create a mesh for each\n keylist = Object.keys(meshdata)\n for (i = 0; i < keylist.length; ++i) {\n mdat = meshdata[keylist[i]]\n var matID = mdat.id\n var m = new BABYLON.Mesh('terr' + matID, self._scene)\n m.parent = mesh\n\n m.material = getOrCreateMaterial(self, matID)\n\n var vdat = new BABYLON.VertexData()\n vdat.positions = mdat.positions\n vdat.indices = mdat.indices\n vdat.normals = mdat.normals\n vdat.colors = mdat.colors\n vdat.uvs = mdat.uvs\n vdat.applyToMesh(m)\n\n m.freezeWorldMatrix();\n }\n\n createOctreeBlock(self, mesh, chunk, x, y, z)\n\n return mesh\n}", "chunk() {\r\n\t\tlet size = this.buffer.readUInt32LE(this.i);\r\n\t\treturn this.read(size);\r\n\t}", "getChunk(metaBuffer, offset, chunkDuration, chunkStart, chunkEnd){\n\n // utils\n const dataStart = metaBuffer.dataStart;\n const dataLength = metaBuffer.dataLength;\n const dataEnd = dataStart + dataLength;\n const inputBuffer = metaBuffer.buffer;\n\n // get head / tail buffers (unchanged)\n const headBuffer = inputBuffer.slice(0, dataStart ); // all until 'data' included\n const tailBuffer = inputBuffer.slice( dataStart + dataLength , metaBuffer.buffer.length ); // all after data values\n\n // get data buffer: default scenario (no need for loop)\n if( chunkEnd > dataEnd ) console.error('ERROR: fetched index greater than data end index:', chunkEnd, dataEnd);\n const dataBuffer = inputBuffer.slice( chunkStart, chunkEnd );\n \n // update data length descriptor in head buffer\n headBuffer.writeUIntLE(dataBuffer.length, headBuffer.length - BYTE_LENGTH, BYTE_LENGTH);\n if (this.generateChunksWavHeader) {\n const wavPcmLength = headBuffer.length + tailBuffer.length + dataBuffer.length;\n const headerBuffer = generateHeader(metaBuffer, wavPcmLength)\n // concatenate head / data / tail buffers\n return Buffer.concat([headerBuffer, headBuffer, dataBuffer, tailBuffer], headerBuffer.length + wavPcmLength);\n } else return Buffer.concat([headBuffer, dataBuffer, tailBuffer], headBuffer.length + tailBuffer.length + dataBuffer.length);\n }", "_findMoof(chunk) {\n if (this._moofBuffer) {\n this._moofBuffer.push(chunk);\n const chunkLength = chunk.length;\n this._moofBufferSize += chunkLength;\n if (this._moofLength === this._moofBufferSize) {\n //todo verify this works\n this._moof = Buffer.concat(this._moofBuffer, this._moofLength);\n delete this._moofBuffer;\n delete this._moofBufferSize;\n this._parseChunk = this._findMdat;\n } else if (this._moofLength < this._moofBufferSize) {\n this._moof = Buffer.concat(this._moofBuffer, this._moofLength);\n const sliceIndex = chunkLength - (this._moofBufferSize - this._moofLength);\n delete this._moofBuffer;\n delete this._moofBufferSize;\n this._parseChunk = this._findMdat;\n this._parseChunk(chunk.slice(sliceIndex));\n }\n } else {\n const chunkLength = chunk.length;\n if (chunkLength < 8 || chunk.indexOf(_MOOF) !== 4) {\n //ffmpeg occasionally pipes corrupt data, lets try to get back to normal if we can find next MOOF box before attempts run out\n const mfraIndex = chunk.indexOf(_MFRA);\n if (mfraIndex !== -1) {\n //console.log(`MFRA was found at ${mfraIndex}. This is expected at the end of stream.`);\n return;\n }\n //console.warn('Failed to find MOOF. Starting MOOF hunt. Ignore this if your file stream input has ended.');\n this._moofHunts = 0;\n this._moofHuntsLimit = 40;\n this._parseChunk = this._moofHunt;\n this._parseChunk(chunk);\n return;\n }\n this._moofLength = chunk.readUInt32BE(0, true);\n if (this._moofLength === 0) {\n this.emit('error', new Error(`Bad data from input stream reports ${_MOOF.toString()} length of 0.`));\n return;\n }\n if (this._moofLength < chunkLength) {\n this._moof = chunk.slice(0, this._moofLength);\n this._parseChunk = this._findMdat;\n this._parseChunk(chunk.slice(this._moofLength));\n } else if (this._moofLength === chunkLength) {\n //todo verify this works\n this._moof = chunk;\n this._parseChunk = this._findMdat;\n } else {\n this._moofBuffer = [chunk];\n this._moofBufferSize = chunkLength;\n }\n }\n }", "function ObjectMesher() {\n\n\n // adds properties to the new chunk that will be used when processing\n this.initChunk = function (chunk) {\n chunk._objectBlocks = {}\n chunk._objectSystems = []\n }\n\n this.disposeChunk = function (chunk) {\n this.removeObjectMeshes(chunk)\n chunk._objectBlocks = null\n }\n\n\n\n\n // accessors for the chunk to regester as object voxels are set/unset\n this.addObjectBlock = function (chunk, id, x, y, z) {\n var key = x + '|' + y + '|' + z\n chunk._objectBlocks[key] = new ObjMeshDat(id, x, y, z, null)\n }\n\n this.removeObjectBlock = function (chunk, x, y, z) {\n var key = x + '|' + y + '|' + z\n if (chunk._objectBlocks[key]) delete chunk._objectBlocks[key]\n }\n\n\n\n\n /*\n * \n * main implementation - remove / rebuild all needed object mesh instances\n * \n */\n\n this.removeObjectMeshes = function (chunk) {\n\t\t\n // remove the current (if any) sps/mesh\n var systems = chunk._objectSystems || []\n while (systems.length) {\n var sps = systems.pop()\n if (sps.mesh) sps.mesh.dispose()\n sps.dispose()\n }\n }\n\n this.buildObjectMeshes = function (chunk) {\n profile_hook('start')\n\t\t\n\t\t//this.removeObjectMeshes(chunk)///////\n\n var scene = chunk.noa.rendering.getScene()\n var objectMeshLookup = chunk.noa.registry._blockMeshLookup\n\n // preprocess everything to build lists of object block keys\n // hashed by material ID and then by block ID\n var matIndexes = {}\n for (var key in chunk._objectBlocks) {\n var blockDat = chunk._objectBlocks[key]\n var blockID = blockDat.id\n var mat = objectMeshLookup[blockID].material\n var matIndex = (mat) ? scene.materials.indexOf(mat) : -1\n if (!matIndexes[matIndex]) matIndexes[matIndex] = {}\n if (!matIndexes[matIndex][blockID]) matIndexes[matIndex][blockID] = []\n matIndexes[matIndex][blockID].push(key)\n }\n profile_hook('preprocess')\n\n // data structure now looks like:\n // matIndexes = {\n // 2: { // i.e. 2nd material in scene\n // 14: { // i.e. voxel ID 14 from registry\n // [ '2|3|4' ] // key of block's local coords\n // }\n // }\n // }\n\n var x0 = chunk.i * chunk.size\n var y0 = chunk.j * chunk.size\n var z0 = chunk.k * chunk.size\n\n // build one SPS mesh for each material\n var meshes = []\n for (var ix in matIndexes) {\n\n var meshHash = matIndexes[ix]\n var sps = buildSPSforMaterialIndex(chunk, scene, meshHash, x0, y0, z0)\n profile_hook('made SPS')\n\n // build SPS into the scene\n var merged = sps.buildMesh()\n\t\t\t\n profile_hook('built mesh')\n\n // finish up\n merged.material = (ix > -1) ? scene.materials[ix] : null\n meshes.push(merged)\n chunk._objectSystems.push(sps)\n }\n\n profile_hook('end')\n return meshes\n }\n\n\n\n\n function buildSPSforMaterialIndex(chunk, scene, meshHash, x0, y0, z0) {\n var blockHash = chunk._objectBlocks\n // base sps\n var sps = new SolidParticleSystem('object_sps_' + chunk.id, scene, {\n updatable: false,\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n })\n sps.isPickable=true\n var blockHandlerLookup = chunk.noa.registry._blockHandlerLookup\n var objectMeshLookup = chunk.noa.registry._blockMeshLookup\n\n // run through mesh hash adding shapes and position functions\n for (var blockID in meshHash) {\n var mesh = objectMeshLookup[blockID]\n var blockArr = meshHash[blockID]\n var count = blockArr.length\n\n var handlerFn\n var handlers = blockHandlerLookup[blockID]\n if (handlers) handlerFn = handlers.onCustomMeshCreate\n var setShape = function (particle, partIndex, shapeIndex) {\n var key = blockArr[shapeIndex]\n var dat = blockHash[key]\n\n // set (local) pos and call handler (with global coords)\n particle.position.set(dat.x + 0.5, dat.y, dat.z + 0.5)\n\t\t\t\t\n if (handlerFn) handlerFn(particle, x0 + dat.x, y0 + dat.y, z0 + dat.z)\n\t\t\t\t\t/*particle.position.x -= x0\n particle.position.y -= y0\n particle.position.z -= z0*///\n }\n sps.addShape(mesh, count, { positionFunction: setShape })\n blockArr.length = 0\n }\n\n return sps\n }\n\n\n\n\n}", "function findMaterialRITC(material) {\n let str = material.match(/((###)(\\s+)(\\d+)(\\s+)(\\S+))/);\n if (str) {\n // console.log(str)\n return str[6];\n }\n}", "function chunk_to_NBT(chunk) {\n\n var nbt = new NBT();\n\n var sections_list = new Array(16);\n for(var Y = 0; Y < 16; Y ++) {\n var Section_Y = NBT_Item.byte(Y, \"Y\");\n var sectTemp = chunk_blocks_to_section(chunk, Y);\n var Section_Blocks = NBT_Item.byte_array(sectTemp.blocks,4096, \"Blocks\");\n var Section_Data = NBT_Item.byte_array(sectTemp.meta,2048, \"Data\");\n\n var Section_SkyLight = NBT_Item.byte_array(chunk.skylightData.slice(Y*16*16*16/2, Y*16*16*16/2+2048),2048, \"SkyLight\");\n var Section_BlockLight = NBT_Item.byte_array(chunk.lightData.slice(Y*16*16*16/2, Y*16*16*16/2+2048),2048, \"BlockLight\");\n\n var section = NBT_Item.compound([Section_Blocks,Section_Data,Section_Y,Section_SkyLight,Section_BlockLight],5, \"\");\n sections_list[Y] = section;\n }\n\n var heightmap = new Buffer(256);\n heightmap.fill(100);\n\n var Level_SectionList = NBT_Item.list(sections_list[0].type,sections_list,16,\"Sections\");\n var Level_Heightmap = NBT_Item.byte_array(heightmap, 256, \"HeightMap\");\n\n var Level_zPos = NBT_Item.int(chunk.Z, \"zPos\");\n var Level_xPos = NBT_Item.int(chunk.X, \"xPos\");\n var Level_Biomes = NBT_Item.byte_array(chunk.biome, 256, \"Biomes\")\n\n var Level = NBT_Item.compound([Level_SectionList,Level_Heightmap,Level_zPos,Level_xPos,Level_Biomes, chunk.blockEntities],6,\"Level\");\n\n nbt.toplevel = NBT_Item.compound([NBT_Item.compound([Level],1,\"\")],1,\"\");\n\n return nbt;\n}", "function seperateMaterials(invoice)\n{\n // invoicearr => invoiceno => materials : []\n // count no of materials in each invoice\n var c = 0;\n\n // find gst cess and have count\n\n console.log(\"In voice Number: \"+invoice);\n let arr = invoicearr[invoice];\n // console.log(arr);\n var materialArr = [];\n let mindex = {};\n arr.forEach((elem,i) => { \n // find gst cess\n // incr counter\n \n if (i == 0)\n {\n console.log(\"New Invoice data---\");\n // console.log(elem);\n }\n if (elem.match(/Slno(\\s)+(RITC)(\\s+)/))\n {\n // console.log(elem);\n }\n if (elem.match(/GST Cess(\\s+)(\\d+)(\\/)(\\d+)/))\n {\n c++;\n mindex[c] = i;\n }\n let s = findsurCharge(elem);\n if (s)\n {\n // console.log(\"S: \" + s)\n }\n });\n // console.log(\"Materials for invoice: \" + invoice + \" is \" + c);\n // console.log(mindex);\n for (let j in mindex)\n {\n // console.log(mindex[j]);\n // get the index of start of material and print start of material\n // console.log(arr[mindex[j] - 10]);\n let materialObj = {};\n let str = \"\";\n str += arr[mindex[j] - 11].trim() + \"### \";\n str += arr[mindex[j] - 10].trim();\n str += arr[mindex[j] - 9].trim();\n // str += arr[mindex[j] - 8].trim();\n // str += arr[mindex[j] - 7].trim() + \" ###\";\n // matearr.push(str);\n\n // index of material\n materialObj.materialNo = findMaterialIndex(str);\n // HSN code\n materialObj.HSNCode = findMaterialRITC(str);\n //BCD Amt(RS)\n materialObj.BCD = findBCD(arr[mindex[j] - 8].trim());\n //Ass value\n materialObj.AssVal = findAssVal(arr[mindex[j] - 7].trim());\n //Social Welfare Surcharge\n materialObj.surCharge = findsurCharge(arr[mindex[j] - 2].trim());\n //IGST\n materialObj.IGST = findIGST(arr[mindex[j] - 1].trim());\n //des\n let desObj = findDes(str);\n // console.log(desObj);\n materialObj.desOfGoods = desObj.desOfGoods;\n materialObj.partCode = desObj.partCode;\n materialObj.quantity = desObj.quantity;\n\n materialObj.invoice = invoice;\n let invobj = invoiceDetails.find(xx => xx.invoice === invoice);\n materialObj.invoiceDate = invobj.vendorDate;\n materialObj.vendorName = invobj.vendorName;\n materialObj.boeNo = boeNo;\n materialObj.boeDate = boeDate;\n materialObj.inVoiValue = invobj.inVoiValue;\n materialObj.exchangeRate = invobj.exchangeRate;\n materialObj.CHA = invobj.CHA;\n materialObj.amtInINR = findAmtINR(materialObj.exchangeRate, materialObj.inVoiValue);\n materialObj.cntryOrg = cntryOrg;\n materialObj.airBillNo = airBillNo;\n materialObj.airBillDt = airBillDt;\n materialArr.push(materialObj);\n }\n console.log(materialArr);\n}", "static extractXBRLFromChunk (chunk) {\n//\t\tlet startIndex = chunk.search(/\\<XBRL\\>/gmsi);\n\t\tlet startIndex = chunk.search(/\\<XBRL(?:\\s[^\\>]*\\>|\\>)/gmsi);\n\t\tlet endIndex = chunk.search(/\\<\\/XBRL\\>/gmsi);\n\t\tif (startIndex > -1 && endIndex > -1) {\n\t\t\tif (startIndex > endIndex) {\n\t\t\t\t// found end of previous block\n\t\t\t\treturn {\n\t\t\t\t\tend: chunk.substring(0, endIndex + 7),\n\t\t\t\t\tremainder: chunk.substring(endIndex + 7)\n\t\t\t\t};\n\t\t\t}\n\t\t\t// found a complete block\n\t\t\treturn {\n\t\t\t\tblock: chunk.substring(startIndex, endIndex + 7),\n\t\t\t\tremainder: chunk.substring(endIndex + 7)\n\t\t\t};\n\t\t}\n\t\telse if (startIndex > -1) {\n\t\t\t// found start of new block\n\t\t\treturn {\n\t\t\t\tstart: chunk.substring(startIndex),\n\t\t\t\tremainder: ''\n\t\t\t};\n\t\t}\n\t\telse if (endIndex > -1) {\n\t\t\t// found end of previous block\n\t\t\treturn {\n\t\t\t\tend: chunk.substring(0, endIndex + 7),\n\t\t\t\tremainder: chunk.substring(endIndex + 7)\n\t\t\t};\n\t\t}\n\t\t// no tags found, may be inside or outside a block\n\t\treturn {\n\t\t\tremainder: chunk\n\t\t};\n\t}", "function parseFile(fileData, wasmModule, callback) {\n // webassembly parameters\n var BUFFER_SIZE_BYTES = 5000000;//5000000; // needs to match #define in webassembly\n wasmModule.instance.exports.setInputBufferBytes(0);\n wasmModule.instance.exports.setOutputBufferBytes(0);\n wasmModule.instance.exports.setup(); // initialize race sketch\n\n var filebuffer_ptr = wasmModule.instance.exports.getInputBuffer();\n var filebuffer = new Uint8Array(wasmModule.instance.exports.memory.buffer, filebuffer_ptr, BUFFER_SIZE_BYTES);\n\n // unwrap file data arguments\n var file = fileData.file;\n var tau = fileData.tau;\n var fastwhat = fileData.fastwhat;\n var kmer_k = fileData.k;\n\n // streaming buffer IO parameters\n var fileSize = file.size;\n var chunkSize = BUFFER_SIZE_BYTES; // bytes\n var offset = 0;\n var chunkReaderBlock = null;\n\n var blobSoFar = new Blob([], {type: 'text/plain'});\n\n function processChunk(event){\n var outbuffer_ptr = wasmModule.instance.exports.getOutputBuffer();\n\n var chunkdata = new Uint8Array(event.target.result);\n var inbuffer_num_valid_bytes = wasmModule.instance.exports.getInputBufferBytes();\n\n // set filebuffer contents to the filedata\n filebuffer.set(chunkdata, inbuffer_num_valid_bytes);\n\n // update size of filebuffer\n console.log(\"SETTING INBUF: \",inbuffer_num_valid_bytes + chunkdata.length);\n wasmModule.instance.exports.setInputBufferBytes(inbuffer_num_valid_bytes + chunkdata.length);\n\n // call the process method\n wasmModule.instance.exports.process(tau, fastwhat, kmer_k);\n\n // set the outbuffer\n var outbuffer_num_valid_bytes = wasmModule.instance.exports.getOutputBufferBytes();\n \n console.log(\"GETTING OUTBUF: \",outbuffer_num_valid_bytes);\n var outbuffer = new Uint8Array(wasmModule.instance.exports.memory.buffer, outbuffer_ptr, outbuffer_num_valid_bytes);\n\n // append to the growing blob of text (note: blob lives on-disk - shouldn't count toward page memory)\n var chunkBlob = new Blob([outbuffer],{type:'text/plain'});\n blobSoFar = new Blob([blobSoFar, chunkBlob], {type: 'text/plain'});\n return;\n }\n\n function handleChunkLoadEnd(event){\n if (event.target.error == null) {\n // offset += event.target.result.length;\n offset += chunkSize; // weird bug see stackoverflow\n processChunk(event); // callback for handling read chunk\n\n self.postMessage({\n eventType: \"PROGRESS\",\n eventData: (100*offset / fileSize) });\n\n } else {\n console.log(\"Read error: \" + event.target.error);\n callback(blobSoFar);\n return;\n }\n if (offset >= fileSize) {\n console.log(\"Done reading file\");\n callback(blobSoFar);\n return;\n }\n\n // read the next chunk\n chunkReaderBlock(offset, file);\n }\n\n chunkReaderBlock = function(_offset, _file) {\n var inbuffer_num_valid_bytes = wasmModule.instance.exports.getInputBufferBytes();\n // dynamically adjust buffer size according to \"leftover\" data from webassembly module\n chunkSize = BUFFER_SIZE_BYTES - inbuffer_num_valid_bytes;\n console.log(offset,chunkSize,fileSize,wasmModule.instance.exports.getInputBufferBytes());\n\n var r = new FileReader();\n var blob = _file.slice(_offset, _offset + chunkSize);\n \n r.onloadend = handleChunkLoadEnd;\n\n\n r.readAsArrayBuffer(blob);\n }\n\n // start the recursive nightmare\n chunkReaderBlock(offset, file);\n}", "function processMaterial( m ) {\n\n \t\t\tvar matid = materialMap.get( m );\n\n \t\t\tif ( matid == null ) {\n\n \t\t\t\tmatid = \"Mat\" + (libraryEffects.length + 1);\n\n \t\t\t\tvar type = 'phong';\n\n \t\t\t\tif ( m instanceof MeshLambertMaterial ) {\n\n \t\t\t\t\ttype = 'lambert';\n\n \t\t\t\t} else if ( m instanceof MeshBasicMaterial ) {\n\n \t\t\t\t\ttype = 'constant';\n\n \t\t\t\t\tif ( m.map !== null ) {\n\n \t\t\t\t\t\t// The Collada spec does not support diffuse texture maps with the\n \t\t\t\t\t\t// constant shader type.\n \t\t\t\t\t\t// mrdoob/three.js#15469\n \t\t\t\t\t\tconsole.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );\n\n \t\t\t\t\t}\n\n \t\t\t\t}\n\n \t\t\t\tvar emissive = m.emissive ? m.emissive : new Color( 0, 0, 0 );\n \t\t\t\tvar diffuse = m.color ? m.color : new Color( 0, 0, 0 );\n \t\t\t\tvar specular = m.specular ? m.specular : new Color( 1, 1, 1 );\n \t\t\t\tvar shininess = m.shininess || 0;\n \t\t\t\tvar reflectivity = m.reflectivity || 0;\n\n \t\t\t\t// Do not export and alpha map for the reasons mentioned in issue (#13792)\n \t\t\t\t// in three.js alpha maps are black and white, but collada expects the alpha\n \t\t\t\t// channel to specify the transparency\n \t\t\t\tvar transparencyNode = '';\n \t\t\t\tif ( m.transparent === true ) {\n\n \t\t\t\t\ttransparencyNode +=\n \t\t\t\t\t\t\"<transparent>\" +\n \t\t\t\t\t\t(\n \t\t\t\t\t\t\tm.map ?\n \t\t\t\t\t\t\t\t\"<texture texture=\\\"diffuse-sampler\\\"></texture>\" :\n \t\t\t\t\t\t\t\t'<float>1</float>'\n \t\t\t\t\t\t) +\n \t\t\t\t\t\t'</transparent>';\n\n \t\t\t\t\tif ( m.opacity < 1 ) {\n\n \t\t\t\t\t\ttransparencyNode += \"<transparency><float>\" + (m.opacity) + \"</float></transparency>\";\n\n \t\t\t\t\t}\n\n \t\t\t\t}\n\n \t\t\t\tvar techniqueNode = \"<technique sid=\\\"common\\\"><\" + type + \">\" +\n\n \t\t\t\t\t'<emission>' +\n\n \t\t\t\t\t(\n \t\t\t\t\t\tm.emissiveMap ?\n \t\t\t\t\t\t\t'<texture texture=\"emissive-sampler\" texcoord=\"TEXCOORD\" />' :\n \t\t\t\t\t\t\t(\"<color sid=\\\"emission\\\">\" + (emissive.r) + \" \" + (emissive.g) + \" \" + (emissive.b) + \" 1</color>\")\n \t\t\t\t\t) +\n\n \t\t\t\t\t'</emission>' +\n\n \t\t\t\t\t(\n \t\t\t\t\t\ttype !== 'constant' ?\n \t\t\t\t\t\t\t'<diffuse>' +\n\n \t\t\t\t\t\t(\n \t\t\t\t\t\t\tm.map ?\n \t\t\t\t\t\t\t\t'<texture texture=\"diffuse-sampler\" texcoord=\"TEXCOORD\" />' :\n \t\t\t\t\t\t\t\t(\"<color sid=\\\"diffuse\\\">\" + (diffuse.r) + \" \" + (diffuse.g) + \" \" + (diffuse.b) + \" 1</color>\")\n \t\t\t\t\t\t) +\n \t\t\t\t\t\t'</diffuse>'\n \t\t\t\t\t\t\t: ''\n \t\t\t\t\t) +\n\n \t\t\t\t\t(\n \t\t\t\t\t\ttype === 'phong' ?\n \t\t\t\t\t\t\t\"<specular><color sid=\\\"specular\\\">\" + (specular.r) + \" \" + (specular.g) + \" \" + (specular.b) + \" 1</color></specular>\" +\n\n \t\t\t\t\t\t'<shininess>' +\n\n \t\t\t\t\t\t(\n \t\t\t\t\t\t\tm.specularMap ?\n \t\t\t\t\t\t\t\t'<texture texture=\"specular-sampler\" texcoord=\"TEXCOORD\" />' :\n \t\t\t\t\t\t\t\t(\"<float sid=\\\"shininess\\\">\" + shininess + \"</float>\")\n \t\t\t\t\t\t) +\n\n \t\t\t\t\t\t'</shininess>'\n \t\t\t\t\t\t\t: ''\n \t\t\t\t\t) +\n\n \t\t\t\t\t\"<reflective><color>\" + (diffuse.r) + \" \" + (diffuse.g) + \" \" + (diffuse.b) + \" 1</color></reflective>\" +\n\n \t\t\t\t\t\"<reflectivity><float>\" + reflectivity + \"</float></reflectivity>\" +\n\n \t\t\t\t\ttransparencyNode +\n\n \t\t\t\t\t\"</\" + type + \"></technique>\";\n\n \t\t\t\tvar effectnode =\n \t\t\t\t\t\"<effect id=\\\"\" + matid + \"-effect\\\">\" +\n \t\t\t\t\t'<profile_COMMON>' +\n\n \t\t\t\t\t(\n \t\t\t\t\t\tm.map ?\n \t\t\t\t\t\t\t'<newparam sid=\"diffuse-surface\"><surface type=\"2D\">' +\n \t\t\t\t\t\t\t\"<init_from>\" + (processTexture( m.map )) + \"</init_from>\" +\n \t\t\t\t\t\t\t'</surface></newparam>' +\n \t\t\t\t\t\t\t'<newparam sid=\"diffuse-sampler\"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :\n \t\t\t\t\t\t\t''\n \t\t\t\t\t) +\n\n \t\t\t\t\t(\n \t\t\t\t\t\tm.specularMap ?\n \t\t\t\t\t\t\t'<newparam sid=\"specular-surface\"><surface type=\"2D\">' +\n \t\t\t\t\t\t\t\"<init_from>\" + (processTexture( m.specularMap )) + \"</init_from>\" +\n \t\t\t\t\t\t\t'</surface></newparam>' +\n \t\t\t\t\t\t\t'<newparam sid=\"specular-sampler\"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :\n \t\t\t\t\t\t\t''\n \t\t\t\t\t) +\n\n \t\t\t\t\t(\n \t\t\t\t\t\tm.emissiveMap ?\n \t\t\t\t\t\t\t'<newparam sid=\"emissive-surface\"><surface type=\"2D\">' +\n \t\t\t\t\t\t\t\"<init_from>\" + (processTexture( m.emissiveMap )) + \"</init_from>\" +\n \t\t\t\t\t\t\t'</surface></newparam>' +\n \t\t\t\t\t\t\t'<newparam sid=\"emissive-sampler\"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :\n \t\t\t\t\t\t\t''\n \t\t\t\t\t) +\n\n \t\t\t\t\ttechniqueNode +\n\n \t\t\t\t\t(\n \t\t\t\t\t\tm.side === DoubleSide ?\n \t\t\t\t\t\t\t\"<extra><technique profile=\\\"THREEJS\\\"><double_sided sid=\\\"double_sided\\\" type=\\\"int\\\">1</double_sided></technique></extra>\" :\n \t\t\t\t\t\t\t''\n \t\t\t\t\t) +\n\n \t\t\t\t\t'</profile_COMMON>' +\n\n \t\t\t\t\t'</effect>';\n\n \t\t\t\tvar materialName = m.name ? (\" name=\\\"\" + (m.name) + \"\\\"\") : '';\n \t\t\t\tvar materialNode = \"<material id=\\\"\" + matid + \"\\\"\" + materialName + \"><instance_effect url=\\\"#\" + matid + \"-effect\\\" /></material>\";\n\n \t\t\t\tlibraryMaterials.push( materialNode );\n \t\t\t\tlibraryEffects.push( effectnode );\n \t\t\t\tmaterialMap.set( m, matid );\n\n \t\t\t}\n\n \t\t\treturn matid;\n\n \t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The iterator for a FilteredMenu Once you understand the iterable and iterator protocols: this is as simple as can be. We just keep track of the index and increment it upon each call to .next() until we run out of items.
function FilteredMenuIterator(filteredMenu) { this.index = 0; this.next = function () { const item = filteredMenu.index(this.index); if (typeof item === "undefined") { return {done: true}; } else { this.index++; return {done: false, value: item}; } }; }
[ "iterator() {\n\t\treturn new Iterator(this.list);\n\t}", "function listIterator(iterator, max) {\n // get the first iteration\n var result = it.next();\n\n // iterate the max number of times\n var i = 0;\n while (i < max && !result.done) {\n // render this one, assume it is synchronous\n renderItem(result.value);\n\n // move on to the next one\n result = it.next();\n i++;\n }\n}", "function Iterator(items){\n this.index = 0;\n this.items = items;\n}", "function iterator(item, cb){\n cb();\n }", "function iterItems(node) {\n var leaf = firstLeaf(node);\n return new ForwardIterator(leaf, 0, -1);\n }", "function iterItems(node) {\n var leaf = firstLeaf(node);\n return new ForwardIterator(leaf, 0, -1);\n }", "function iterator() {\n return new Iter(this.head)\n}", "hasNext() {\n return this.index <= this.items.length;\n }", "items() {\n return new ArrayIterator(this._items);\n }", "nextItem() {\n this.idx = utils.modulo(this.idx + 1, this.children.length);\n\n this.selected = this.children[this.idx];\n\n this.useBar();\n\n this.emitter.emit('next', this, this.callbackContext);\n }", "function next() {\n // Get the items only when the current position is less than items length.\n if (cursor < list.length) {\n // Get the item by cursor position.\n var item = list[cursor];\n\n // Increase the position.\n cursor += 1;\n\n // Call the iteration handler.\n handler.call(self, item.key, item.value, next, stop);\n } else {\n // Mark the iterator as complete.\n self.status = 'complete';\n\n // Call the resolver if defined.\n if ('function' === typeof self.resolve) {\n self.resolve(self);\n }\n }\n }", "function UilMenuItemGetNextItem() {\n var menu = this.parentMenu;\n if ( menu != null ) {\n for ( var i=0; i<menu.items.length; i++ ) {\n if ( menu.items[i] == this ) {\n for ( var j=i+1; j<menu.items.length; j++ ) {\n if ( !menu.items[j].isSeparator && menu.items[j].isEnabled ) {\n return menu.items[j];\n }\n }\n // no next item\n return null;\n }\n }\n }\n return null;\n}", "filter(filter) {\n return new Iterator(next => {\n this.iterate((prevItem, prev) => {\n if (filter(prevItem)) {\n switch (next.act(prevItem)) {\n case IteratorAction.Stop:\n prev.stop();\n break;\n case IteratorAction.Remove:\n prev.remove();\n break;\n case IteratorAction.Replace:\n prev.replace(next.replaceWith);\n break;\n }\n }\n });\n });\n }", "function ListIterator() {}", "iterate() {\n return walker(this.root);\n }", "getRenderedMenuItems() {\r\n // query select rendered items if child items are created within this component\r\n // querySelectorAll returns a NodeList, we can convert it to array using spread operator but that doesn't work on IE\r\n // so using array slicing workaround\r\n let renderedSubMenus = this.element ?\r\n this.getArrayFromNodeList(this.element.querySelectorAll(PANEL_SUB_MENU))\r\n :\r\n this.getArrayFromNodeList(this.element.querySelectorAll(PANEL_SUB_MENU));\r\n // if child items are not found within this component then search for slotted items (childNodes)\r\n renderedSubMenus = renderedSubMenus.length > 0 ? renderedSubMenus : this.getArrayFromNodeList(this.element.childNodes).filter(child => {\r\n return child['tagName'] && child['tagName'].toLowerCase() === PANEL_SUB_MENU;\r\n });\r\n return renderedSubMenus;\r\n }", "getMenuItems(currentNumItems, columnDef, grid) {\n if (currentNumItems > 0) {\n return [<MenuItem divider key={currentNumItems} />];\n } else {\n return [];\n }\n }", "getRenderedMenuItems() {\n // query select rendered items if child items are created within this component\n // querySelectorAll returns a NodeList, we can convert it to array using spread operator but that doesn't work on IE\n // so using array slicing workaround\n let renderedSubMenus = this.element ?\n this.getArrayFromNodeList(this.element.querySelectorAll(PANEL_SUB_MENU))\n :\n this.getArrayFromNodeList(this.element.querySelectorAll(PANEL_SUB_MENU));\n // if child items are not found within this component then search for slotted items (childNodes)\n renderedSubMenus = renderedSubMenus.length > 0 ? renderedSubMenus : this.getArrayFromNodeList(this.element.childNodes).filter(child => {\n return child['tagName'] && child['tagName'].toLowerCase() === PANEL_SUB_MENU;\n });\n return renderedSubMenus;\n }", "hasNext() {\n return this.index < this.items.length;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
= Description Replaces the contents of the view's DOM element with custom html. = Parameters +_html+:: The HTML (stringformatted) to replace the content with. = Returns +self+
setHTML(_html) { ELEM.setHTML(this.elemId, _html); return this; }
[ "setHTML(html) {\n this.html = html;\n document.body.innerHTML = this.html;\n }", "setHtml(html = \"\"){\n\t \tif(html.length < 1) \n\t \t\treturn false;\n\t \tfor(let i=0; i<this.items.length; i++){\n\t \t\tthis.items[i].innerHTML = text;\n\t \t}\n\t \treturn this;\n\t }", "setInnerHTML(html) {\r\n if (this.childNodes) {\r\n let _doc = parseMarkup(html, {\r\n ownerDocument: this.getOwnerDocument()\r\n });\r\n this.empty();\r\n // ATTENTION: important to copy the childNodes array first\r\n // as appendChild removes from parent\r\n _doc.childNodes.slice(0).forEach((child) => {\r\n this.appendChild(child);\r\n });\r\n }\r\n return this\r\n }", "setContents(html) {\n this.$el.html(html);\n this.render();\n }", "setInnerHTML(html) {\n if (this.childNodes) {\n let _doc = parseMarkup(html, {\n ownerDocument: this.getOwnerDocument()\n })\n this.empty()\n // ATTENTION: important to copy the childNodes array first\n // as appendChild removes from parent\n _doc.childNodes.slice(0).forEach((child) => {\n this.appendChild(child)\n })\n }\n return this\n }", "setHtml (html) {\n console.info(\".setHtml() is not implemented yet, fall back to .setText()\");\n\n return this.setText.apply(this, arguments);\n }", "set innerHTML(html) {\n if (this.#el) this.#el.innerHTML = html;\n else this.#innerHTML = html;\n }", "html(newInnerHTML) {\n if (Monad_1.Optional.fromNullable(newInnerHTML).isAbsent()) {\n return this.isPresent() ? Monad_1.Optional.fromNullable(this.innerHTML) : Monad_1.Optional.absent;\n }\n this.innerHTML = newInnerHTML;\n return this;\n }", "html() {\n this.setType('html');\n return this;\n }", "setContent(html) {\n\t\tlet el = this.getContentCnt();\n\t\tel.innerHTML = \"\";\n\t\tif (html === undefined) {\n\t\t\thtml = this.content || this.contentHTML || \"\";\n\t\t}\n\t\tif (typeof html === \"string\") el.innerHTML = html;\n\t\telse el.appendChild(this.content);\n\t}", "function updateHtmlView(html) {\n\tdocument.getElementById (\"rendered\").innerHTML = html;\n\tdocument.getElementById(\"code\").value =html;\n}", "createHTML(html) {\n let div = this.createDiv();\n div.innerHTML = html;\n return div;\n }", "function setHTML(id, html) {\n getEl(id).innerHTML = html;\n }", "function renderHTML(element, html) {\n element.innerHTML = html;\n }", "static wrap(html) {\n return new Elem(html);\n }", "function dynCalendar_setHTML(html)\n\t{\n\t\tthis._getLayer().innerHTML = html;\n\t}", "setHtml(el, html, outer) {\n var next, par, prev, ref, ref1;\n if (outer) {\n prev = el.previousSibling;\n next = el.nextSibling;\n par = el.parentNode;\n el.outerHTML = html;\n el = (ref = (ref1 = prev != null ? prev.nextSibling : void 0) != null ? ref1 : next != null ? next.previousSibling : void 0) != null ? ref : par != null ? par.firstChild : void 0;\n } else {\n el.innerHTML = html;\n }\n this.activateScripts($(el));\n return el;\n }", "html(html){\n if(html)\n this.parse(html);\n }", "function setHtml() {\n if(that.html || that.html != null) {\n if(false) {\n var node = null;\n try {\n node = AXIOMUtil.stringToOM(that.html.toString());\n } catch (e) {\n throw new Error(e);\n }\n if(node instanceof OMElement) {\n var htmlElement = node;\n that.html = htmlElement.toString();\n } else {\n throw new Error(\"Invalid input argument. The html function accepts \" +\n \"either a String or an XML element.\");\n }\n } else {\n throw new Error(\"Invalid input argument. The html function accepts \" +\n \"either a String or an XML element.\");\n }\n\n var messageBodyPart = new MimeBodyPart();\n var dataHandler = null;\n try {\n dataHandler = new DataHandler(\n new ByteArrayDataSource(that.html, \"text/html\"));\n messageBodyPart.setDataHandler(dataHandler);\n multipart.addBodyPart(messageBodyPart);\n } catch(e) {\n throw new Error(e);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function limit selectbox users
function selectlimit(){ var a = window.location.pathname; var locat = a.split('/'); var limit = $('#activelimit').val(); if(locat[2] == "users.php" ){ $('body').on('click', 'div .bootstrap-switch', function(){ setTimeout(function(){ var checked = parseInt($('td input:checkbox:not(":checked")').length); if(checked >= limit){ $('td input:checkbox:checked').attr('disabled',true); } },1000); }); $('body').on('click','td [type=checkbox]' ,function(){ var numberOfChecked = parseInt($('td input:checkbox:not(":checked")').length); if( numberOfChecked >= limit){ $('td input:checkbox:checked').attr('disabled',true); }else{ $('td input:checkbox:checked').removeAttr('disabled'); } }); } }
[ "function setlimit() {\n limit = $(this).attr('value');\n }", "function draugiemSelectFriends(limit, callback) {\n\tdraugiemLoadUrl({'action': 'selectusers', 'limit': limit}, callback);\n}", "function selectionLimit(limit, id) {\n const el = document.getElementById(id);\n if (el) {\n el.addEventListener(\"change\", function() {\n if ($(this).val().length > limit) {\n $(this).val(null);\n alert('You can select upto ' + limit.toString() +' options only');\n }\n });\n }\n\n}", "function selectUsersWithSets() {\n\t\tvar user = jQuery(\"#selectUser\").val();\n\t\tshowSetsByUser(user);\n\t}", "function populateUserDropDown(noOfUser){\t\r\n\tdocument.getElementById(\"inputNoOFUser\").innerHTML = \"\";\r\n\tvar noOfUserSelect = document.getElementById(\"inputNoOFUser\");\t\t\r\n\tvar defaultOptn = document.createElement(\"option\");\r\n\tdefaultOptn.text = \"Select No of User\";\r\n\tdefaultOptn.value = \"\";\r\n\tdefaultOptn.className = \"form-control-general\";\r\n\tnoOfUserSelect.add(defaultOptn, null);\r\n\tif(noOfUser > 10){\r\n\t\tnoOfUser = 10;\r\n\t}\r\n\tfor(var i = 1; i<= noOfUser;i++){\t\t\r\n\t\tvar option = document.createElement(\"option\");\r\n\t\toption.text = i;\r\n\t option.value = i;\r\n\t option.className = \"form-control-general\";\r\n\t try {\r\n\t \tnoOfUserSelect.add(option, null); //Standard \r\n\t }catch(error) {\r\n\t \t//regionSelect.add(option); // IE only\r\n\t }\t\r\n\t}\t\t\r\n}", "function updateUserSelect(){\n\t$(TO_USER_SELECT).empty();\n\tfor(var index in users){\n\t\t$(TO_USER_SELECT).append(createUserRow(users[index]));\n\t}\n}", "function handleLimitSelection(ev) {\n setLimitType(ev.target.id === 'limit1');\n}", "selectChange(e){\n\n e.preventDefault();\n\n const itemsPerPage = Number(e.target.value);\n\n if(!isNaN(itemsPerPage)){\n\n this.itemsPerPage = itemsPerPage;\n\n //update the selected values of all controls\n for(let control of this.controls){\n this.updateItemsPerPageSelect(control.itemsPerPageSelects);\n }\n }\n\n if(window.jplist) {\n\n window.jplist.refresh(this.group);\n }\n }", "function selCount(obj) {\n var selected = $.fn.multicheck.selcount(obj);\n if ( selected < opts['minlen']) {\n if (opts['messages']['multicheck']) {\n errors.push (opts['messages']['multicheck']);\n } else {\n errors.push (opts['title'] + ' must select ' + opts['minlen'] + ' to ' + opts['maxlen'] + ' items');\n }\n }\n }", "function limitSelection(idTag, limit) {\r\n return;\r\n gblMultiSelectTriggerOrig = \"onChange\";\r\n var selectedOptions = $(idTag + ' option:selected');\r\n if ($(idTag + ' option').length === (selectedOptions.length + 1) ) {\r\n $(idTag).multiselect('deselectAll', false); //This will cause \"SelectAll\" trigger\r\n resetAllOptions(idTag);\r\n //alert('on one change');\r\n return;\r\n }\r\n\r\n //var dropdown;\r\n if (selectedOptions.length >= limit) {\r\n // Disable all other checkboxes.\r\n var nonSelectedOptions = $(idTag + ' option').filter(function() {\r\n return !$(this).is(':selected');\r\n });\r\n\r\n //dropdown = $(idTag).siblings('.multiselect-container');\r\n nonSelectedOptions.each(function() {\r\n var input = $('input[value=\"' + $(this).val() + '\"]');\r\n input.prop('disabled', true);\r\n input.parent('li').addClass('disabled');\r\n });\r\n } else {\r\n // Enable all checkboxes.\r\n //dropdown = $(idTag).siblings('.multiselect-container');\r\n $(idTag + ' option').each(function() {\r\n var input = $('input[value=\"' + $(this).val() + '\"]');\r\n input.prop('disabled', false);\r\n input.parent('li').addClass('disabled');\r\n });\r\n }\r\n}", "function limitarChecks() {\n $(\"input[name='adU-checkbox']\").change(function () {\n var limit = 1;\n var cantidadCkb = $(\"input[name='adU-checkbox']:checked\").length;\n if (cantidadCkb > limit) \n {\n $(this).prop(\"checked\", \"\");\n alert(\"Solo puede seleccionar: \"+ limit+\" usuario\");\n }\n });\n}", "function LimitList(limit) {\n}", "function limiter(){\n\t\n var tex = document.twtform.DashboardStatus.value;\n var len = tex.length;\n if(len > count){\n\t tex = tex.substring(0,count);\n\t document.twtform.DashboardStatus.value =tex;\n\t return false;\n }\n document.twtform.limit.value = count-len;\n }", "function setUserLimit(limit) {\n\tretryAfter = Math.round(+new Date()/1000) + 1 + limit;\n}", "function selectNewUsers()\n{\n\tconsole.log(\"processing \" + this.id);\n\tCURRENTUSER = this.id;\n\tupdateDropdownSelected(\"user\");\n}", "function limitSelection(selected, modelData, modelField, maxSelects) {\r\n //Notice use of eval to check dynamic variables\r\n /*\r\n if ($scope.$eval(modelField).length === maxSelects) {\r\n angular.forEach( $scope.$eval(modelData), function(item, i) {\r\n if (item.ticked !== true) {\r\n item.disabledInd = true;\r\n }\r\n });\r\n } else {\r\n angular.forEach( $scope.$eval(modelData), function(item, i) {\r\n item.disabledInd = false;\r\n }); \r\n }\r\n */\r\n if (modelField.length >= maxSelects) {\r\n angular.forEach( modelData, function(item, i) {\r\n if (item.ticked !== true) {\r\n item.disabledInd = true;\r\n }\r\n });\r\n } else {\r\n angular.forEach( modelData, function(item, i) {\r\n item.disabledInd = false;\r\n }); \r\n }\r\n }", "function setLimit() { // reset offset when limit is changed\n if (limit != DOC.iSel(\"resultsID\").value) {\n offset = Number(\"0\");\n }\n limit = Number(DOC.iSel(\"resultsID\").value);\n}", "function selectTeamSize(e){\n\t\t\t\tmultiSelectors[0].setMaxPokemonCount($(e.target).find(\"option:selected\").val());\n\t\t\t}", "function listUsers(page, pgSize = 10) {\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Protected properties Set accessor for the base endpoint
set baseEndpoint(baseEndpoint) { this._baseEndpoint = baseEndpoint; if (this._baseEndpoint.startsWith('/') === false) { this._baseEndpoint = '/' + this._baseEndpoint; } if (this._baseEndpoint.endsWith('/') === false) { this._baseEndpoint = this._baseEndpoint + '/'; } }
[ "get baseEndpoint() {\n return this._baseEndpoint;\n }", "setEndpoint() {\n this.endpoint = this.getEndpoint();\n }", "get endpoint () {\n\t\treturn this._endpoint;\n\t}", "function getSetMethod(){\n const baseObject = (function(){\n let _prop1 = 1987;\n return{\n prop2: 2000,\n get prop1(){\n return _prop1;\n },\n set prop1(_val){\n _prop1 = _val;\n }\n }\n })();\n\n console.log('BASE - DEFAULT', baseObject);\n console.log('PROP1 - BASE ', baseObject.prop1);\n baseObject.prop1 = 3000;\n console.log('PROP1 - CHANGE', baseObject.prop1);\n console.log('BASE - CHANGE', baseObject);\n}", "get endpoint() {\n return this._endpoint;\n }", "constructor() {\n super(expressionType_1.ExpressionType.SetProperty, SetProperty.evaluator(), returnType_1.ReturnType.Object, SetProperty.validator);\n }", "function ResponsePropertiesHelper() {\n}", "get properties() {\n return this;\n }", "constructor(endpoint = '', axiosConfig = {}) {\n // super(endpoint,axiosConfig)\n super()\n this.endpoint = endpoint;\n this.axiosConfig = axiosConfig;\n\n }", "function setter() {\n\t throw new Error('vuex getter properties are read-only.');\n\t }", "get endpoint() {\n return this.getStringAttribute('endpoint');\n }", "constructor() { \n \n OrgApacheFelixHttpProperties.initialize(this);\n }", "function setter() {\n throw new Error('vuex getter properties are read-only.');\n }", "function setEndpoint (newEndPoint) {\n endpoint = newEndPoint;\n }", "function EndpointConfig() {}", "static get properties() {\r\n return {\r\n serviceData:{\r\n type:Object,\r\n value:{},\r\n notify:true\r\n }\r\n };\r\n }", "constructor(endpoint) {\n this.endpoint = endpoint\n }", "setProxy() {\n let _this = this;\n Object.keys(this.data).forEach(key => {\n Object.defineProperty(this, key, {\n configurable: false,\n enumerable: true,\n get() {\n return _this.data[key];\n },\n set(newVal) {\n _this.data[key] = newVal;\n }\n });\n });\n }", "function HttpSerializer (properties) {\n assign(this, properties)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_.size tra ve chieu dai cua mang _.first tra ve mang con
function first(){ var numbers=[1,2,3,4,5]; var first=_.first(numbers,3); console.log(first); }
[ "first(){ return this.bones[0].idx; }", "get firstItem() {\n if (this._totalItems === 0) {\n return -1;\n }\n if (this.size === 0) {\n return 0;\n }\n return (this.current - 1) * this.size;\n }", "function takeFirst(collection){\n if(!(collection.length >= 1)){\n return;\n }\n return collection[0];\n}", "first() {\n if (this.size <= 0)\n return undefined;\n let firstVal = this.values().next();\n return firstVal.value;\n }", "first() {\n for (const x of this.iter) {\n return x;\n }\n return undefined;\n }", "function firstChars(count, word) {\n if(count > word.length) return \"Error, specified length is bigger than string\"\n return word.substring(0, count)\n }", "function CommonCrawlList__getFirstEntry() {\n\n //\n // Just return the size of the list\n //\n return this._list.first;\n\n}", "first() {\n for (const item of this._iterable) {\n return item;\n }\n return undefined;\n }", "function first() {\n index = 0;\n c = dot.charAt(0);\n }", "function getFirstElements(sdr, count) {\n return sdr.slice(0, count);\n }", "function first(a) { return (a !== null && a.length > 0) ? a[0] : null; }", "function first(a) {\n return a[0];\n}", "getFirst(n) {\n return this.names.slice(0, n-1); \n }", "get firstMarkerSize() {\n return this.i.a6;\n }", "function first(data) {\n return data[0];\n}", "get firstMarkerSize() {\r\n return this.i.a6;\r\n }", "get first() {\n return this.index === 0;\n }", "getFirstIndex() {\n errors.throwNotImplemented(\"getting the first index in a collection\");\n }", "function first(sequence) {\n return sequence[0];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns true if pacman is hit by a ghost
hitPacman(ghostPos){//takes in p5.Vector return (dist(ghostPos.x, ghostPos.y, this.pos.x, this.pos.y)<10);//change to <25 for 1080p }
[ "function isPacmanCollideWithGhost(gh) {\n return (pacman.y == gh.y && pacman.x == gh.x);\n}", "function contact(pacManX, pacManY, ghostX, ghostY, ghostSize, pacManRadius){\n if((pacManX + pacManRadius > ghostX && pacManX < ghostX + ghostSize) &&(pacManY + pacManRadius > ghostY && pacManY < ghostY + ghostSize)){\n return true;\n }\n }", "function ghostMeetPacman(location) {\n if (squares[location].classList.contains('ghost')) {\n if (squares[location].classList.contains('scared-ghost')) ghostEat(location);\n else killPacman(location);\n }\n}", "in_ghost_house() {\r\n\r\n var in_ghost_house = false;\r\n\r\n var ghost_house_left = (13 * 24) + 12;\r\n var ghost_house_right = ghost_house_left + (6 * 24) + 12;\r\n var ghost_house_top = (12 * 24) + 12;\r\n var ghost_house_bottom = ghost_house_top + 2 * 24 + 12;\r\n\r\n // is the ghost in the ghost house?\r\n var in_ghost_house = false;\r\n if ((this.sprite.x_pos >= ghost_house_left) && \r\n (this.sprite.x_pos <= ghost_house_right) && \r\n (this.sprite.y_pos >= ghost_house_top) &&\r\n (this.sprite.y_pos <= ghost_house_bottom)) \r\n {\r\n in_ghost_house = true;\r\n }\r\n\r\n return in_ghost_house; \r\n \r\n }", "hasReachedHome() {\n if (this.ghost.x < 11 * game.tileSize || this.ghost.x > 16 * game.tileSize ||\n this.ghost.y < 13 * game.tileSize || this.ghost.y > 15 * game.tileSize) {\n return false;\n }\n return true;\n }", "function checkHit(player) {\n ghostModule.ghosts.forEach(function (ghost, index, array) {\n if (ghost.xPos > player.xPos && ghost.xPos < (player.xPos + (player.width * 0.75)) && ghost.yPos > player.yPos && ghost.yPos < (player.yPos + (player.height * 0.75)) || (ghost.xPos + (ghost.width * 0.75)) > player.xPos && (ghost.xPos + (ghost.width * 0.75)) < (player.xPos + (player.width * 0.75)) && ghost.yPos > player.yPos && ghost.yPos < (player.yPos + (player.height * 0.75))) {\n gameOver = true;\n }\n });\n }", "ghostEatPacman(ghost, pacman, scene){\n\n if(ghost.state === \"normal\" && pacman.state === \"normal\"){\n scene.sounds[\"pacman_death\"].play();\n // ghost eat pacman\n pacman.resetWhenEaten();\n\n }\n else if (ghost.state === \"afraid\" && pacman.state === \"super\"){\n // pacman eats ghost\n // only eats ghost if in super state\n\n scene.sounds[\"pacman_eatghost\"].play();\n\n ghost.state = \"dead\";\n clearTimeout(ghost.deathTimeout);\n ghost.deathTimeout = setTimeout(()=>{\n ghost.state = \"normal\";\n }, 5000);\n pacman.score += 200;\n }\n }", "function checkIfGoodMonsterWithPacman() {\r\n\tif (((monster5Good.i == shape.i) && (monster5Good.j == shape.j) && isMonster5Alive)) {\r\n\t\tscore = score + 50;\r\n\t\tboardMonster[monster5Good.i][monster5Good.j] = 0;\r\n\t\tisMonster5Alive = false;\r\n\t}\r\n}", "isAlive() {\n if (this.hitPoints <= 0) {\n console.log(`${this.name} has been defeated!`);\n return false;\n }\n return true;\n }", "function meet(){\n\tfor (var i=0;i<ghostArray.length;i++){\n\t\tif ((ghostArray[i].alive)&&((ghostArray[i].loc[0]==curPos[0])&&(ghostArray[i].loc[1]==curPos[1]))){\n\t\t\tif (this.strong){\n\t\t\t\tghostArray[i].alive=false;\n\t\t\t\tpageTimer[noOfTimer++]=setTimeout(\"ghostStart(\"+i+\")\",5000);\n\t\t\t\tghostInside++;\n\t\t\t\taudioNoLoop.src=\"eatGhost.wav\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcheckGameOver();\n\t\t\t\t\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}", "function collisionCheck() {\n ghosts.forEach(ghost => {\n if(squares[ghost.index].classList.contains('pacman') && ghost.className !== 'dead') {\n if(!ghost.isBlue) {\n deadPlayer()\n } else {\n deadGhost(ghost)\n }\n }\n })\n}", "isAlive() {\n if (this.hitPoints <= 0) {\n console.log(`${this.name} has been defeated!`);\n return false;\n }\n return true;\n }", "function checkIfMonsterWithPacman() {\r\n\tif (((monster1.i == shape.i) && (monster1.j == shape.j)) ||\r\n\t\t((monster2.i == shape.i) && (monster2.j == shape.j)) ||\r\n\t\t((monster3.i == shape.i) && (monster3.j == shape.j)) ||\r\n\t\t((monster4.i == shape.i) && (monster4.j == shape.j))) {\r\n\t\tlife--;\r\n\t\tscore = score - 10;\r\n\t\tfindPacmanPlace();\r\n\t\tputMonstersInRightPlace();\r\n\t} else if (life <= 0) {\r\n\t\twindow.clearInterval(interval);\r\n\t}\r\n}", "checkDirection(){\r\n if(pacman.hitPacman(this.gpos)){//if pacman gets hit\r\n if(this.frightened){//eaten by pacman\r\n this.goHome = true;\r\n this.frightened = false;\r\n pacman.score+=200;\r\n }else if(!this.goHome){//kill pacman\r\n pacman.kill();\r\n }\r\n }if(this.goHome){//check if reached home\r\n if(dist((this.gpos.x-8)/16, (this.gpos.y-8)/16, 13, 11)<1){//set tempDead to true\r\n this.goHome = false;\r\n this.tempDead = true;\r\n this.deadCount = 0;\r\n }\r\n }if((this.gpos.x-8)%16 == 0 && (this.gpos.y-8)%16 == 0){//if on a critical position\r\n let arrPos = createVector((this.gpos.x-8)/16, (this.gpos.y-8)/16);//convert to array position\r\n //console.log(\"Ghost: Pink:\", this.pink, \" arrPos X:\", 0arrPos.x, \" Y: \",arrPos.y);\r\n //let tempVel = createVector(gvel.x/2, gvel.y/2);//can be used to slow ghosts down in the tunnel\r\n if(originalTiles[floor(arrPos.y)][floor(arrPos.x)].tunnel){//checks if the next position will be in the tunnel\r\n pacman.specialCase(this.gpos);\r\n //gvel = createVector(tempVel.x, tempVel.y);//half the speed exponentially\r\n }if(this.frightened){//no path will be made if frightened\r\n let isNode = false;\r\n for(let j=0; j<this.ghostNodes.length; j++){\r\n if(arrPos.x == this.ghostNodes[j].x && arrPos.y == this.ghostNodes[j].y){\r\n isNode = true;\r\n }\r\n }if(isNode){//if on a node set a random direction\r\n let newVel = createVector();\r\n let rand = floor(random(4));\r\n switch(rand){\r\n case 0:\r\n newVel = createVector(1, 0);\r\n break;\r\n case 1:\r\n newVel = createVector(-1, 0);\r\n break;\r\n case 2:\r\n newVel = createVector(0, 1);\r\n break;\r\n case 3:\r\n newVel = createVector(0, -1);\r\n break;\r\n }//if the random vel chosen is to a wall or opposite direction then choose another\r\n while(originalTiles[floor(arrPos.y+newVel.y)][floor(arrPos.x+newVel.x)].wall || (newVel.x+2*this.gvel.x == 0 && newVel.y+2*this.gvel.y == 0)){\r\n this.rand = floor(random(4));\r\n switch(this.rand){\r\n case 0:\r\n this.newVel = createVector(1, 0);\r\n break;\r\n case 1:\r\n this.newVel = createVector(-1, 0);\r\n break;\r\n case 2:\r\n this.newVel = createVector(0, 1);\r\n break;\r\n case 3:\r\n this.newVel = createVector(0, -1);\r\n break;\r\n }\r\n }this.gvel = createVector(newVel.x/2, newVel.y/2);//half the speed\r\n }\r\n }else{//not frightened\r\n this.setPath();\r\n if(this.mainPath)\r\n for(let i=0; i<this.mainPath.path.length-1; i++){//if on a node turn to the next node in the path\r\n if(arrPos.x == this.mainPath.path.getAt(i).x && arrPos.y == this.mainPath.path.getAt(i).y){\r\n this.gvel = createVector(this.mainPath.path.getAt(i+1).x-arrPos.x, this.mainPath.path.getAt(i+1).y-arrPos.y);\r\n this.gvel.limit(1);\r\n return;\r\n }\r\n }\r\n }\r\n }\r\n }", "function eatGhost(ghost) {\n if (ghost.edible == false) {\n lives -= 1;\n console.log('Ghost ' + ghost.name + ', colour ' + ghost.colour + ' kills Pac-Man');\n\n } else {\n\n console.log('\\nPac-man eats ' + ghost.name + '!');\n score += ghost.point;\n ghost.edible = false;\n }\n checkLives();\n}", "function checkCollision() {\n let collided = 0;\n for (var i = 0; i < ghosts.length; i++) {\n if (pacman.xGrid === ghosts[i].xGrid && pacman.yGrid === ghosts[i].yGrid && ghosts[i].vulnerable === false) {\n collided = 1;\n } else if (pacman.xGrid === ghosts[i].xGrid && pacman.yGrid === ghosts[i].yGrid && ghosts[i].vulnerable === true) {\n // ghosts.push(new Ghost(int(random(8,12)), 10)); //ghost \"dies\" and respawns\n // delete ghosts[i]; \n ghosts.splice(i, 1);\n ghosts.push(new Ghost(int(random(8,12)), 10)); //ghost \"dies\" and respawns\n SCORE += 400;\n collided = 2; //not strictly necessary but for return value\n }\n }\n return collided; \n}", "hits(agent) {\n\t\tif (agent instanceof Agent) {\n\t\t\tif (agent.x > this.x && agent.x < this.x + this.w && agent.y > this.y && agent.y < this.y + this.h) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "function checkCollisions(pacman, listOfGhosts, gc) {\n // ghost collisions\n for (var i = 0; i < listOfGhosts.length; i++) {\n // if collision (same position and ghost is not resetting)\n if (posnEqual(pacman.position, listOfGhosts[i].position) && !listOfGhosts[i].eaten) {\n //console.log(\"collision\");\n // pacman eats ghost -> send ghost back to start\n if (listOfGhosts[i].frightened > 0) {\n listOfGhosts[i].eaten = true;\n game.score += 20;\n } else { // ghost eats pacman\n pacman.dying = 15;\n }\n }\n }\n // dot collisions\n for (var i = 0; i < gc.dots.length; i++) {\n if (posnEqual(pacman.position, gc.dots[i])) {\n gc.dots.splice(i, 1);\n game.score += 1;\n }\n }\n // power pellet collisions\n for (var i = 0; i < gc.powers.length; i++) {\n if (posnEqual(pacman.position, gc.powers[i])) {\n gc.powers.splice(i, 1);\n game.score += 5;\n // scare ghosts\n for (var i = 0; i < listOfGhosts.length; i++) {\n if (!listOfGhosts[i].eaten) {\n listOfGhosts[i].frightened = 10;\n }\n }\n }\n }\n}", "function checkEngage(cell, opponent) {\n if (cell === opponent) {\n\n // basic support for eating power-ball (which is not in the game yet)\n if (gPacman.isSuper) {\n if (gIsFood) updateScore(1);\n for (var i = 0; i < gGhosts.length; i++) {\n var ghost = gGhosts[i]; \n if (ghost.location.i===gPacman.location.i && ghost.location.j === gPacman.location.j)\n gGhosts.splice(i, 1);\n }\n console.log('Ghost is dead');\n\n }\n else return true;\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check wether to display or not left arrow
function displayLeftArrow() { if(page == 0) { document.getElementById('leftArrow').setAttribute('style', 'opacity: 0; cursor: default; pointer-events: none;'); } else { document.getElementById('leftArrow').setAttribute('style', 'opacity: 1; cursor: pointer; pointer-events: auto;'); } }
[ "function check_arrows() {\n // if it's up is the pipeline_root the up arrow should be hidden.\n if ( this.node.up.id == 'pipeline_root' ) {\n getObject(this.id + '_arrow_up').style.display = 'none';\n getObject(this.id + '_arrow_up_disabled').style.display = 'inline';\n } else {\n getObject(this.id + '_arrow_up').style.display = 'inline';\n getObject(this.id + '_arrow_up_disabled').style.display = 'none';\n }\n \n // if it's down is the pipeline_root_panel the down arrow should be hidden.\n if ( this.node.down.id == 'pipeline_root_panel' ) {\n getObject(this.id + '_arrow_down').style.display = 'none';\n getObject(this.id + '_arrow_down_disabled').style.display = 'inline';\n } else {\n getObject(this.id + '_arrow_down').style.display = 'inline';\n getObject(this.id + '_arrow_down_disabled').style.display = 'none';\n }\n}", "get isLeftArrowKeyDown() {\n return this._isLeftArrowKeyDown;\n }", "leftArrowPressed() {\n if (this.getIndexOfSelectedSlide() > 0) {\n this.selectSlide(false);\n }\n }", "onLeftArrowKeypress() {\n this.currentDirection === \"rtl\" ? this.next() : this.prev();\n }", "get IsLeft() { return tp.Mouse.LEFT === this.fButton; }", "get canShowLeft() {\n return this.node.getBoundingClientRect().left - this.element.offsetWidth >= 0;\n }", "isShowSideArrow(){\n let len = this.getFileLength();\n return len > 1 ? '' : 'hide';\n }", "_renderArrow() {\n return !this._isDisabled() || this._isSorted();\n }", "isLeftPressed() {\n return this.currentKeys.get(LEFT);\n }", "function left() {\n if (currentEmployee >= 0) {\n displayModal((currentEmployee -= 1));\n rightArrow.style.display = \"block\";\n if (currentEmployee === 0) {\n leftArrow.style.display = \"none\";\n }\n }\n}", "function cell_is_left() {\n return this.position.x < SEPARATION_POINT;\n}", "offScreenLeft() {\n if (this.x < this.OffScreenLeft) {\n return true;\n }\n return false;\n }", "function arrowVisibility () {\n if (thisEmployee.parent().next().length == 0) {\n $('#next').hide();\n } else {\n $('#next').show();\n }\n\n if (thisEmployee.parent().prev().length == 0) {\n $('#previous').hide();\n } else {\n $('#previous').show();\n }\n }", "function isLeft(e) { return e[0] == 'Left'; }", "isLeft() { return !this._isRight; }", "function isArrowsHidden(){\n\t\t\n\t\tif(!g_objArrowLeft)\n\t\t\treturn(true);\n\t\tif(g_objArrowLeft.is(\":visible\") == false)\n\t\t\treturn(true);\n\t\t\n\t\tvar opacity = g_objArrowLeft.css(\"opacity\");\n\t\tif(opacity != 1)\n\t\t\treturn(true);\n\t\t\n\t\treturn(false);\n\t}", "function getLeftArrow(){ \n let parameters = getPageParameters();\n return isFirstPage(parameters) ? \n (\n <ArrowLeftInactive className=\"InactiveArrow\" onClick={()=>{storeIsActive ? prevProductsPage() : prevRedeemedPage()}} />\n ):(\n <ArrowLeftActive className=\"ActiveArrow\" onClick={()=>{storeIsActive ? prevProductsPage() : prevRedeemedPage()}} />\n )\n }", "function hideArrow() {\n if(arrow){\n setArrow(false)\n }\n }", "function pointerLeft(pointer) {\n return pointer && pointer.isDown && pointer.x <= (game.width / 2);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the position of the element as a [ x, y ] tuple
getPosition(_id) { const _elem = this._elements[_id]; let [x, y] = [0, 0]; if (this._isSVGElem(_elem)) { const _rect = _elem.getBoundingClientRect(); [x, y] = [_rect.left, _rect.top]; } else if (_elem) { [x, y] = [_elem.offsetLeft, _elem.offsetTop]; } else { console.warn('ELEM.getPosition(', _id, '): Element not found'); } return [x, y]; }
[ "function getElementPosition(elt)\n{\n var x = 0;\n var y = 0;\n var currentElt = elt;\n while(currentElt)\n {\n x += currentElt.offsetLeft;\n y += currentElt.offsetTop;\n currentElt = currentElt.offsetParent;\n }\n return [x, y]; \n}", "function getPos(svg, elem) {\n var matrix, position;\n\n matrix = elem.getCTM();\n position = svg.createSVGPoint();\n position.x = elem.getAttribute(\"cx\");\n position.y = elem.getAttribute(\"cy\");\n position = position.matrixTransform(matrix);\n return position;\n }", "function getPos(svg, elem) {\n var matrix, position;\n\n matrix = elem.getCTM();\n position = svg.createSVGPoint();\n position.x =\n elem.getAttribute(\"cx\") !== null\n ? elem.getAttribute(\"cx\")\n : elem.getAttribute(\"x\");\n position.y =\n elem.getAttribute(\"cy\") !== null\n ? elem.getAttribute(\"cy\")\n : elem.getAttribute(\"y\");\n position = position.matrixTransform(matrix);\n return position;\n }", "function getPos(svg, elem) {\n var matrix,\n position;\n\n matrix = elem.getCTM();\n position = svg.createSVGPoint();\n position.x = elem.getAttribute(\"cx\");\n position.y = elem.getAttribute(\"cy\");\n position = position.matrixTransform(matrix);\n return position;\n }", "getPosition() {\n return [this.x, this.boundaries[1] - 1 - this.y];\n }", "function getClientPosition(element) {\n\tvar temp = element.getBoundingClientRect(); //Gets coordinate data\n\tvar xPosition = temp.left;\n\tvar yPosition = temp.top;\n\treturn { x: xPosition, y: yPosition };\n}", "function getPosition(element)\n{\n\t//Calculates the left and top position of the element having in mind its parents:\n\tvar elementParent = element.parent;\n\tvar elementPosition = { left: element.left, top: element.top };\n\twhile (elementParent)\n\t{\n\t\telementPosition.left += elementParent.left ? elementParent.left : 0;\n\t\telementPosition.top += elementParent.top ? elementParent.top : 0;\n\t\telementParent = elementParent.parent;\n\t}\n\treturn elementPosition;\n}", "elementPosition(column, row) {\n return [100 * (column+0.5) / this.dimensions[0] , 100 * (row+0.5) / this.dimensions[1]];\n }", "function getPositionX(elt) {\n\treturn parseFloat(matrixToArray(elt.style.transform)[4]);\n}", "getPosition() {\r\n var asciiX = this.x;\r\n var asciiY = this.y;\r\n return '(' + asciiX + ',' + asciiY + ')';\r\n }", "function findPos(element) {\n\tvar curleft = curtop = 0;\n\tif (element.offsetParent) {\n\t\tdo {\n\t\t\tcurleft += element.offsetLeft;\n\t\t\tcurtop += element.offsetTop;\n\t\t} while (obj = element.offsetParent);\n\t}\n\treturn [curleft,curtop];\n}", "function getPositionIndex(x, y, array) {\n var position = array.findIndex(pos => pos.x == x && pos.y == y);\n return position;\n}", "function findPosition(element) {\n var curleft = 0, curtop = 0;\n\n if (element.offsetParent) {\n do {\n curleft += element.offsetLeft;\n curtop += element.offsetTop;\n } while (element = element.offsetParent);\n }\n\n return { x: curleft, y: curtop };\n }", "function get_pos(coord) {\n if (coord == undefined) {\n return \"\";\n }\n return coord[0].toString() + \", \" + coord[1].toString();\n}", "$_getPosition(node, wrapper) {\n let x = 0\n let y = 0\n let el = node\n\n while (el) {\n x += el.offsetLeft\n y += el.offsetTop\n\n if (el === wrapper || el === document.body || el === null) {\n break\n }\n\n el = el.offsetParent\n }\n\n return {x, y}\n }", "static cellPos (cell) {\n const i = parseInt(cell.getAttribute('i'))\n const j = parseInt(cell.getAttribute('j'))\n return { i: i, j: j }\n }", "function getPos() {\n\t\treturn _this.position;\n\t}", "function coords(elem) {\n var myX = myY = 0;\n if (elem.getBoundingClientRect) {\n var rect;\n rect = elem.getBoundingClientRect();\n myX = rect.left + ((typeof window.pageXOffset !== \"undefined\") ?\n window.pageXOffset : document.body.scrollLeft);\n myY = rect.top + ((typeof window.pageYOffset !== \"undefined\") ?\n window.pageYOffset : document.body.scrollTop);\n } else {\n // this fall back doesn't properly handle absolutely positioned elements\n // inside a scrollable box\n var node;\n if (elem.offsetParent) {\n // subtract all scrolling\n node = elem;\n do {\n myX -= node.scrollLeft ? node.scrollLeft : 0;\n myY -= node.scrollTop ? node.scrollTop : 0;\n } while (node = node.parentNode);\n // this will include the page scrolling (which is unwanted) so add it back on\n myX += (typeof window.pageXOffset !== \"undefined\") ? window.pageXOffset : document.body.scrollLeft;\n myY += (typeof window.pageYOffset !== \"undefined\") ? window.pageYOffset : document.body.scrollTop;\n // sum up offsets\n node = elem;\n do {\n myX += node.offsetLeft;\n myY += node.offsetTop;\n } while (node = node.offsetParent);\n }\n }\n return [myX, myY];\n}", "get position() {\n\t\t\treturn {x: this.x, y: this.y};\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the selected SVG image and store the radius, x and y coordinates into an array
function readSVG() { $.ajax({ type: "GET", url: "img/prize-"+allReady+".svg", dataType: "xml", success: function(xml) { var i = 0; offsetSVG = (canvasWidth/2) - (parseInt($(xml).find('svg').attr('width'), 10) / 2); $(xml).find('circle').each(function() { shapeSVG.push([$(this).attr('cx'), $(this).attr('cy'), $(this).attr('r')]); i++; }); loadNodes(); // Intro fade ins $('#ir-anim-container #white-circle').animate({width: '240px', height: '240px', top: '59px'}, 2500, 'easeOutElastic', function() { $('#ir-anim-container #white-circle').css('background', 'none'); loadEvents(); }); $('#ir-anim-container #white-circle h1, #ir-anim-container #white-circle h2').delay(500).fadeIn(function() { $('#ir-anim-container #gifts').fadeIn(function() { loop(); }); }); }, error: function(data) { error(); } }); }
[ "function getSVGInfo() {\n var fileNode = document.getElementById('file');\n if (!fileNode) {\n return null;\n }\n \n var url;\n if (hasAnnotation()) {\n url = fileNode.childNodes[0].childNodes[0].childNodes[0].href;\n } else {\n url = fileNode.childNodes[0].href;\n }\n var imgNode = fileNode.getElementsByTagName('img')[0];\n var width = imgNode.getAttribute('width');\n var height = imgNode.getAttribute('height');\n\n return { url: url, fileNode: fileNode, imgNode: imgNode, \n width: width, height: height };\n}", "function getXY(radius_,angle_){\n x=cx+(radius_*Math.cos((angle_+(-90))*(Math.PI/180)));\n y=cy+(radius_*Math.sin((angle_+(-90))*(Math.PI/180)));\n return [x,y];\n }", "function parseSVGPaths(filepath){\n\n\t$ = cheerio.load(fs.readFileSync(path))\n\tvar paths = _.reduce($('path'), function (items, path) {\n\t\titems.push($(path).attr('d'))\n\t\treturn items\n\t}, [])\n\n\treturn paths\n}", "function getCircle(longitude, latitude, radius) {\n return [src_circle().center([longitude, latitude]).radius(radius)().coordinates];\n}", "function getAllSVGInfo (dirName, outputName, paddingValue = null, minify = false, curvePoints = 50) {\n // object that will hold all the relevant data\n let data = {}\n let promiseArray = []\n // reads directory and get all file names\n let filenames = fs.readdirSync(`input/${dirName}`)\n filenames.forEach(filename => {\n // Expects the character to be the file name without extension\n let character = filename.replace('.svg', '')\n // read file and get content\n let fileContent = fs.readFileSync(`./input/${dirName}/${filename}`, 'utf-8')\n // push svgson parsing to the promise array\n promiseArray.push(svgson.parse(fileContent))\n })\n Promise.all(promiseArray).then(svgs => {\n // include index in for each to associate with respective character\n svgs.forEach((svg, i) => {\n let charInfo = {}\n charInfo.layers = {}\n // add padding if passed in the parameters\n if (paddingValue) {\n let vB = svg.attributes.viewBox.split(' ')\n vB[0] = parseInt(vB[0]) - paddingValue\n vB[1] = parseInt(vB[1]) - paddingValue\n vB[2] = parseInt(vB[2]) + (paddingValue * 2)\n vB[3] = parseInt(vB[3]) + (paddingValue * 2)\n charInfo.viewBox = vB.join(' ')\n } else {\n charInfo.viewBox = svg.attributes.viewBox\n }\n svg.children[0].children.forEach(layer => {\n // creates a new node for each layer\n charInfo.layers[layer.attributes.id] = []\n layer.children.forEach(path => {\n let pathInfo = {}\n // round d to two decimals if minify is true\n if (minify) {\n pathInfo.d = pathManipulator(path.attributes.d).round(2).toString()\n } else {\n pathInfo.d = path.attributes.d\n }\n // get id from all paths\n pathInfo.id = path.attributes.id\n // only get start and end points, strokeWidth and total length from interactiveStrokes layer\n if (layer.attributes.id === 'interactiveStrokes') {\n let properties = pathProps.svgPathProperties(pathInfo.d)\n // gets parts from properties\n let lineParts = properties.getParts()\n pathInfo.strokeWidth = path.attributes['stroke-width']\n pathInfo.totalLength = properties.getTotalLength()\n pathInfo.startPoint = lineParts[0].start\n // gets curves to make comparison to drawing\n pathInfo.curve = getCurve(canvas.path(pathInfo.d), curvePoints)\n pathInfo.endPoint = lineParts[lineParts.length - 1].end\n }\n // splice the stroke information to be in the correct stroke order - according to svg id parameters\n charInfo.layers[layer.attributes.id].splice(parseInt(pathInfo.id.replace(/[^0-9]/g,'')) - 1, 0, pathInfo)\n })\n })\n // character will be the file name without extension\n let character = filenames[i].replace('.svg', '')\n data[character] = charInfo\n })\n // save smaller hard-to-read JSON for use and an easy-to-read one\n let readableOutput = JSON.stringify(data, null, 2)\n let output = JSON.stringify(data)\n fs.writeFileSync(`output/${outputName}.json`, output)\n console.log(`Saved ${outputName}.json!`)\n fs.writeFileSync(`output/readable${outputName}.json`, readableOutput)\n console.log(`Saved readable${outputName}.json!`)\n }).catch(err => console.log(err))\n}", "getCanvasImage(file, callback) {\n let reader = new FileReader();\n reader.onload = (event) => {\n let content = event.target.result;\n fabric.loadSVGFromString(content, function(objects, options) {\n let obj = fabric.util.groupSVGElements(objects, options);\n\n return callback(obj);\n });\n };\n\n reader.readAsText(file);\n }", "function getSVGinfo() {\n console.log(this);\n S = document.getElementById(\"DYOSVG\").contentDocument;\n var STYLESVG = []\n , NUMCOLS = [];\n var i;\n\n for (var j = 0; j < S.styleSheets.length; j++) {\n var rules = S.styleSheets[j].rules || S.styleSheets[j].cssRules;\n // This CSS code may need to be modified to handle using commas in CSS for shared code\n for (i in rules) {\n if (typeof rules[i].selectorText == 'string') {\n STYLESVG.push(rules[i].selectorText)\n }\n }\n for (i in STYLESVG) {\n var start_pos = STYLESVG[i].indexOf('.') + 1;\n var end_pos = STYLESVG[i].indexOf('.', start_pos);\n if (end_pos != -1) {\n var NC = STYLESVG[i].substring(start_pos, end_pos);\n // begin IE stupidity workaround\n var NC2 = STYLESVG[i].substring(end_pos + 1);\n if (NC == \"fill\" || NC == \"stroke\" || NC == \"stopColor\") {\n NUMCOLS.push(NC2)\n } else if (NC2 == \"fill\" || NC2 == \"stroke\" || NC2 == \"stopColor\") {\n NUMCOLS.push(NC)\n }\n }\n }\n NUMCOLS = NUMCOLS.filter(function(itm, i, a) {\n return i == a.indexOf(itm)\n });\n }\n var PREVIOUS = document.getElementsByClassName(\"colourfill\");\n for (i = PREVIOUS.length; i > 0; i--) {\n var M = (PREVIOUS[i - 1].id.indexOf(\"[\") != -1) ? PREVIOUS[i - 1].id.slice(0, PREVIOUS[i - 1].id.indexOf(\"[\")) : PREVIOUS[i - 1].id;\n var A = (PREVIOUS[i - 1].id.indexOf(\"[\") != -1) ? PREVIOUS[0].id.slice(PREVIOUS[0].id.indexOf(\"[\") + 1, PREVIOUS[0].id.length - 1) : null;\n if (A != ACTIVE) {\n continue\n }\n PREVIOUS[i - 1].material = (typeof materialController == 'function') ? materialController(M) : PREVIOUS[i - 1].material;\n var col = readCookie(PREVIOUS[i - 1].id);\n if (col && PREVIOUS[i - 1].material.indexOf(col) == -1) {\n removeCookie(PREVIOUS[i - 1].id)\n }\n if (PREVIOUS[i - 1].material.indexOf(PREVIOUS[i - 1].value) == -1) {\n if (defcols[PREVIOUS[i - 1]] && PREVIOUS[i - 1].material.indexOf(defcols[PREVIOUS[i - 1]]) != -1) {\n PREVIOUS[i - 1].value = defcols[PREVIOUS[i - 1]];\n }\n {\n var rand = Math.floor(Math.random() * PREVIOUS[i - 1].material.length);\n PREVIOUS[i - 1].value = PREVIOUS[i - 1].material[rand];\n }\n colour.call(PREVIOUS[i - 1]);\n }\n if (NUMCOLS.indexOf(PREVIOUS[i - 1].id) == -1 && PREVIOUS[i - 1].id != \"S-BallColour\") {\n PREVIOUS[i - 1].parentNode.parentNode.removeChild(PREVIOUS[i - 1].parentNode)\n }\n }\n for (i in NUMCOLS) {\n if (!document.getElementById(NUMCOLS[i]) + \"[\" + ACTIVE + \"]\") {\n addColour(NUMCOLS[i] + \"[\" + ACTIVE + \"]\")\n }\n ;colour.call(document.getElementById(NUMCOLS[i] + \"[\" + ACTIVE + \"]\"))\n }\n // Re-Initialise set values\n if (typeof svgController == 'function') {\n svgController();\n }\n if (!S.getElementById(\"Content\")) {\n var CNT = document.createElementNS(SVG_NS, \"g\");\n CNT.id = \"Content\";\n S.documentElement.appendChild(CNT)\n }\n S.getElementById(\"Content\").style.visibility = \"hidden\";\n S.getElementById(\"Content\").style.visibility = \"hidden\";\n if (document.getElementById(\"SBALL[\" + ACTIVE + \"]\")) {\n drawSBall();\n // SBall();\n // colour.call(document.getElementById(\"S-BallColour[\" + ACTIVE + \"]\"));\n }\n DL = document.getElementById(\"logos[\" + ACTIVE + \"]\").getElementsByClassName(\"logoupload\");\n DT = document.getElementById(\"logos[\" + ACTIVE + \"]\").getElementsByClassName(\"addtext\");\n DS = document.getElementById(\"logos[\" + ACTIVE + \"]\").getElementsByClassName(\"uploadselect\");\n for (var i = 0; i < DS.length; i++) {\n embellish.call(DS[i])\n }\n for (var i = 0; i < DL.length; i++) {\n if (DL[i].value) {\n if (CYCLE == true) {\n DLCount++\n }\n HFS.call(DL[i])\n }\n }\n for (var i = 0; i < DT.length; i++) {\n if (DT[i].value) {\n addText.call(DT[i])\n }\n }\n // Continue with Garment Specific Logic\t\n //\tdocument.getElementById(\"Colour1\").classList.add(\"chosen\");\n //\tif(document.getElementById(\"Colour1\")){createColourPicker.call(document.getElementById(\"Colour1\"))}else{console.log(\"dfjvdfj\")}\n // colourBranding()\n //Clone the node \n if (CYCLE == true && DLCount == 0) {\n generateImages()\n }\n}", "function getCropData(filename) {\n\n var jsonData = JSON.parse(fs.readFileSync(filename, 'utf8'));\n //missing pose\n if (jsonData.people.length == 0)\n return 0\n\n //get coords\n var upper = Infinity;\n var lower = 0;\n var left = Infinity;\n var right = 0;\n\n for (var i=0; i < openposeData.length; i++) {\n value = openposeData[i];\n if ((i+3) % 3 === 0) {\n if (value < left & value != 0)\n left = value;\n if (value > right & value != 0)\n right = value;\n }\n if ((i+3) % 3 === 1) {\n if (value < upper & value != 0)\n upper = value;\n if (value > lower & value != 0)\n lower = value;\n }\n }\n\n upper = Math.round(upper);\n lower = Math.round(lower);\n left = Math.round(left);\n right = Math.round( right);\n\n height = lower - upper;\n width = right - left;\n\n //padding\n if (height > width) {\n var padding = Math.round((height - width)/2);\n left -= padding;\n right += padding;\n }\n else {\n var padding = Math.round((width - height)/2);\n upper -= padding;\n lower += padding;\n }\n\n return [upper,left,lower,right];\n}", "function extractSVGPaths(svgDoc) {\r\n\r\n var ret = [];\r\n // rect, polygon should've been converted to <path> by SVGO at this point\r\n if (svgDoc.getElementsByTagName('rect').length>0) console.warn(\"Only SVG <path>'s are supported; ignoring <rect> items\");\r\n if (svgDoc.getElementsByTagName('polygon').length>0) console.warn(\"Only SVG <path>'s are supported; ignoring <polygon> items\");\r\n if (svgDoc.getElementsByTagName('line').length>0) console.warn(\"Only SVG <path>'s are supported; ignoring <line> items\");\r\n\r\n // These elements are not supported:\r\n if (svgDoc.getElementsByTagName('image').length>0) console.warn(\"Only SVG <path>'s are supported; ignoring <image> items\");\r\n if (svgDoc.getElementsByTagName('text').length>0) console.warn(\"Only SVG <path>'s are supported; ignoring <text> items\");\r\n\r\n\r\n /*\r\n * A few helper functions to get information about the path (color, stroke weight)\r\n */\r\n function getFillColor(el){\r\n // Should look up CSS Class too...\r\n var f= el.getAttribute(\"fill\") || null;\r\n if (f==\"transparent\" || f==\"none\") f = null;\r\n return f;\r\n }\r\n function getStrokeColor(el){\r\n return el.getAttribute(\"stroke\") || null;\r\n }\r\n function getStrokeWidth(el){\r\n return (el.getAttribute(\"stroke-width\")*1) || (el.getAttribute(\"stroke\")?1:0);\r\n }\r\n function getScaleTransform(path){\r\n // Reference: https://developer.mozilla.org/en/docs/Web/API/SVGTransform\r\n var ret = {x:1, y:1};\r\n for (var i=0; i<path.transform.baseVal.length; i++) {\r\n if (path.transform.baseVal[i].type==3) {ret.x += path.transform.baseVal[i].matrix.a; ret.y += path.transform.baseVal[i].matrix.d;}\r\n }\r\n return ret;\r\n }\r\n function getTranslateTransform(path){\r\n var ret = {x:0, y:0};\r\n for (var i=0; i<path.transform.baseVal.length; i++) {\r\n if (path.transform.baseVal[i].type==2) {ret.x += path.transform.baseVal[i].matrix.e; ret.y += path.transform.baseVal[i].matrix.f;}\r\n }\r\n return ret;\r\n }\r\n\r\n\r\n /*\r\n * Helper funcs to create pretty SVG Path strings \r\n */\r\n function pathobject2str(dat){\r\n return dat.reduce(function (acc, val){\r\n return acc + ' ' + val.type + ' ' + val.values.join(' ');\r\n },'');\r\n }\r\n function circleAttrsToPath(r,cx,cy) {\r\n return `M ${cx-r},${cy} a ${r},${r} 0 1,0 ${r*2},0 a ${r},${r} 0 1,0 -${r*2},0`;\r\n };\r\n function ellipseAttrsToPath (rx,cx,ry,cy) {\r\n return `M${cx-rx},${cy} a ${rx},${ry} 0 1,0 ${rx*2},0 a ${rx},${ry} 0 1,0 -${rx*2},0`;\r\n }\r\n\r\n\r\n // Process each <path> element\r\n Array.prototype.slice.call(svgDoc.getElementsByTagName('path')).map(function (path) {\r\n\r\n //var d = pathobject2str(path.getPathData());\r\n var tmp = {\r\n strokeWidth: getStrokeWidth(path),\r\n closed: path.getAttribute('d').search(/Z/i)>0,\r\n d: path.getAttribute('d'), // was \"pathobject2str(path.getPathData());\" but I think this is not necessary...\r\n fillColor: getFillColor(path),\r\n strokeColor: getStrokeColor(path),\r\n scale: getScaleTransform(path),\r\n translate: getTranslateTransform(path),\r\n path: path};\r\n\r\n if (tmp.fillColor==null) tmp.closed=false;\r\n\r\n ret.push(tmp);\r\n\r\n });\r\n\r\n\r\n\r\n // Process each <circle> element\r\n //https://stackoverflow.com/questions/5737975/circle-drawing-with-svgs-arc-path\r\n Array.prototype.slice.call(svgDoc.getElementsByTagName('circle')).map(function (path) {\r\n\r\n var tmp = {\r\n strokeWidth: getStrokeWidth(path),\r\n closed: true,\r\n d: circleAttrsToPath( path.r.baseVal.value, path.cx.baseVal.value, path.cy.baseVal.value),\r\n fillColor: getFillColor(path),\r\n strokeColor: getStrokeColor(path),\r\n scale: getScaleTransform(path),\r\n translate: getTranslateTransform(path),\r\n path: path};\r\n\r\n if (tmp.fillColor==null) tmp.closed=false;\r\n\r\n ret.push(tmp);\r\n\r\n });\r\n\r\n\r\n // Process each <ellipse> element\r\n // https://stackoverflow.com/questions/5737975/circle-drawing-with-svgs-arc-path/10477334#10477334\r\n Array.prototype.slice.call(svgDoc.getElementsByTagName('ellipse')).map(function (path) {\r\n\r\n var tmp = {\r\n strokeWidth: getStrokeWidth(path),\r\n closed: true,\r\n d: ellipseAttrsToPath( path.rx.baseVal.value, path.cx.baseVal.value, path.ry.baseVal.value, path.cy.baseVal.value),\r\n fillColor: getFillColor(path),\r\n strokeColor: getStrokeColor(path),\r\n scale: getScaleTransform(path),\r\n translate: getTranslateTransform(path),\r\n path: path};\r\n\r\n if (tmp.fillColor==null) tmp.closed=false;\r\n\r\n ret.push(tmp);\r\n\r\n });\r\n\r\n\r\n return ret;\r\n\r\n} // function extractSVGPaths()", "getSVGPath() {\n return this.path.map((command) => {\n return command.toSVGPathData();\n })\n }", "function printpixeldata()\r\n{\r\n var imagedata;\r\n var canvas = document.createElement(\"canvas\");\r\n var ctx = canvas.getcontext(\"2d\");\r\n var img = new Image();\r\n\r\n img.src =\"file:///C:/Users/mahrajag.ORADEV/Desktop/D3/DragResize/MagBarChart.png\";\r\n img.width = w;\r\n img.height = h;\r\n\r\n \r\n canvas.width = w;\r\n canvas.height = h;\r\n\r\n ctx.drawImage(img,0,0,w,h);\r\n\r\n\r\n imagedata = ctx.getImageData(dragrect.attr(\"x\"), dragrect.attr(\"y\"), width, height);\r\n\r\n\r\n for (var x=0; x< width *height*4; x+=1)\r\n alert(imagedata.data[x]);\r\n\r\n}", "function getCircleCoords(event){\r\n\t\r\n\tconsole.log(event.overlay.getRadius());\r\n\tconsole.log(event.overlay.getCenter().lat());\r\n\tconsole.log(event.overlay.getCenter().lng());\r\n\t\r\n}", "function getImageData(){\n\n }", "function requestSVGData(data) {\n return Utils.httpGet(svgUrl + data.hex)\n .then(function (svg) {\n return {svg: svg, x: data.x, y: data.y};\n })\n .catch(function (error) {\n console.log(error);\n });\n }", "function circleArr(origoLat, origoLng, size){\n\n\tvar i = 0;\n\tvar j = 0;\n\n\tvar newPosLng;\n\tvar newPosLat;\n\n\tvar tmpPathValues = [];\n\n\n\tfor (i = 0; i < 100; i++){ // google only accepts 100 points at the time\n\t\tj = i * 3.6;\n\t\tnewPosLat = size * 0.001 * Math.cos(j*(Math.PI / 180)) + origoLat;\n\t\tnewPosLng = size * 0.002 * Math.sin(j*(Math.PI / 180)) + origoLng;\n\n\t\tvar pos = new google.maps.LatLng(newPosLat, newPosLng);\n\t\t//tmpPathValues.push(position);\n\t\ttmpPathValues.push(pos);\n\t\t//placeAMarker(position, 1); // for debug \n\t}\n\treturn tmpPathValues;\n}", "function getBasicOriginFile () {\n // 100 transit stops, 6 minutes, 20 pixel radius\n let size = 1 + // radius\n Math.pow(41, 2) + // non-transit data\n 2 + // nStops, nMinutes\n 100 * 6 // 100 stops, 6 minutes\n\n let arr = new Int32Array(size)\n arr[0] = 20\n let transitOffset = Math.pow(41, 2) + 1\n arr[transitOffset] = 100\n arr[transitOffset + 1] = 6\n for (let stop = 0; stop < 100; stop++) {\n let soff = transitOffset + 2 + stop * 6\n // add two minutes to account for off by one and the decrement\n arr.set([stop * 60 + 120, -60, -60, 120, -60, -60], soff)\n }\n\n return arr\n}", "function calculateCircleImagemapPoints(dw, dh, iw, ih, ir) {\r\n\tvar p1 = Math.ceil((dw * iw) / 920);\r\n\tvar p2 = Math.ceil((dh * ih) / 620);\r\n\tvar cx = iw - ir;\r\n\tvar t = Math.ceil((cx * dw) / 920);\r\n\tvar p3 = p1 - t;\r\n\treturn [p1, p2, p3];\r\n}", "function svg2xy(svgString, sliceDimensions) {\n\n //These 2 values ultimately need to come from the server AND get passed into the main function.\n // var sliceDimensions = {\n // width: 620,\n // height: 750\n // };\n // var svgString = $('#area').val();\n\n\n var svgConverter = new svgClass();\n\n //Convert raw SVG data to WKT format\n var wktString = svgConverter.SVGtoWKT.convert(svgString);\n //converts WKT data to [[x,y],[x,y]]\n var coordinates = wkt2xyCoordinates(wktString,sliceDimensions);\n\n //optional\n // drawPointsToCanvas(coordinates);\n return coordinates;\n}", "function grabSvgDimensions(svgID) {\n var svg = d3.select(\"#\" + svgID);\n\n //grab the specified SVG container's dimensions (width and height)\n var svg_width = svg.node().getBoundingClientRect().width;\n var svg_height = svg.node().getBoundingClientRect().height;\n\n return [svg, svg_width, svg_height];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create 'Rest day' element
function add_rest(day){ var workouts = $('#wo_list'); var html = `<!-- restday --!> <li class="to_sort"><div><table class="table is-fullwidth"> <thead style="text-align:center"> <th class="wo_day_disp">${day}</th> <th> Rest </th> <th> <span class="js-remove" style="float:right">X</span> </th> <span class="wo_day" value="${day}"></span> </thead> </table></div></li> ` workouts.append(html); }
[ "rest(day){\n\t\tstopAnimate(tID);\n\t\t//First check for food, could be starving.\n\t\tthis.setFood();\n\t\t//Get a random rest value and the current food consumption rate\n\t\tvar rest_val = 1 + Math.floor(Math.random() * 4);\n\t\tvar ration_val = this.mapRationToHealth();\n\t\t//For each member of the caravan, adjust their health, reset disease, check for life.\n\t\tthis.members.forEach(function(element, index){\n\t\t\tif(day == 2){\n\t\t\t\telement.is_diseased = false;\n\t\t\t}\n\t\t\telement.setHealth(ration_val, 0, rest_val);\n\t\t});\n\t\tthis.day += 1;\n\t\tanimateWagon(this.pace);\n\t}", "function createRestDay(title, amt, desc, img) {\n let workout = document.createElement('li');\n workout.className = 'workout';\n let text = document.createElement('div');\n text.id = 'text';\n workoutTitle = document.createElement('h3');\n workoutTitle.className = 'workout-title';\n workoutTitle.innerHTML = title;\n text.appendChild(workoutTitle);\n let reps = document.createElement('p');\n reps.className = 'reps';\n reps.innerHTML = amt;\n text.appendChild(reps);\n let description = document.createElement('p');\n description.className = 'description';\n description.innerHTML = desc;\n text.appendChild(description);\n workout.appendChild(text);\n let image = document.createElement('img');\n image.className = 'images';\n image.src = img;\n workout.appendChild(image);\n workoutList.appendChild(workout);\n}", "function createTripDay(trip) {\n trip.plan.push({ entries: [], lodging: {} });\n return trip;\n}", "static getDayNode()\n {\n return document.querySelector('[data-template-calendar-day]')\n .content\n .cloneNode(true)\n .querySelector('[data-calendar-day]');\n }", "function DayPart(day) {\n this.day = day;\n }", "function _createDaySection(day) {\n\t return new Surface({\n\t size: [undefined, 42],\n\t classes: ['message-day'],\n\t content: daySectionTemplate({text: day}),\n\t properties: {\n\t isSection: true\n\t }\n\t });\n\t }", "function createDay() {\n const id = GetElement(\"#current_schedule\").getAttribute(\"value\");\n const dayData = getDayFields();\n\n new Request(\"POST\", `/days?scheduleId=${id}`,\n JSON.stringify(dayData),\n getDays\n );\n}", "function addDay() {\n num_days+=1;\n node = dayNode(num_days, 0, 0);\n document.getElementById(\"stops\").appendChild(node);\n updateTimeline();\n}", "addDay(index) { this.calendarTemplate[index].push(`[${this.day}](#_${this.day}-${this.month}-${this.year})`); }", "function constructDay(){\n //try to pull from local storage\n day = JSON.parse(localStorage.getItem(\"day\"));\n\n // if success, reformat strings to moment (stringify simplified them to strings)\n if (day != undefined){\n for (var j =0; j<day.length; j++){\n day[j].time = moment(day[j].time.split(\"T\")[1], [\"hh:mm:ss.SSSZ\"])\n }\n return;\n }\n\n //otherwise generate a new day setup\n day=[];\n let time = moment().startOf('day');\n let endTime = moment().endOf('day');\n let i=0;\n while(time < endTime){\n day.push({\n time: time.clone(),\n comment:\"\",\n index:i\n });\n i++;\n time.add(interval, \"seconds\");\n }\n}", "function _createDaySection(day) {\n return new Surface({\n size: [undefined, 42],\n classes: ['message-day'],\n content: daySectionTemplate({text: day}),\n properties: {\n isSection: true\n }\n });\n }", "function meetupDay(year, month, day, description) {\n let theMonth = month;\n let theYear = year;\n let theDescription = description;\n let theDay = convertDay(day);\n let theDate;\n\n if (theDescription === \"teenth\") {\n theDate = getTeenth(theYear, theMonth, theDay);\n return new Date(theYear, theMonth, theDate);\n }\n\n // 4. check if descriptor starts with 1, 2, 3, 4, 5\n // -get first digit\n // -convert day to #\n // -loop through all Dates of month\n // -put each date that is the same Day into array\n // -get correct date out of array array[digit]\n // -return new Date with year, month, date\n\n if (theDescription === \"last\") {\n let days = getDays(theYear, theMonth, theDay);\n return days[days.length - 1];\n }\n\n if (Number.isInteger(parseInt(theDescription[0]))) {\n let num = parseInt(theDescription[0]);\n let days = getDays(theYear, theMonth, theDay);\n if (num === 5 && days.length === 5) {\n return days[num - 1];\n } else if (num < 5) {\n return days[num - 1];\n } else {\n throw new Error(\"not 5 days\");\n }\n }\n}", "function createCalendarDay(num, day, mon, year) {\n var currentCalendar = document.getElementById(\"calendar\");\n\n var newDay = document.createElement(\"div\");\n var date = document.createElement(\"p\");\n var dayElement = document.createElement(\"p\");\n\n date.innerHTML = num;\n dayElement.innerHTML = day;\n\n newDay.className = \"calendar-day \";\n\n // Set ID of element as date formatted \"8-January\" etc \n newDay.id = num + \"-\" + mon + \"-\" +year;\n\n newDay.appendChild(date);\n newDay.appendChild(dayElement);\n // currentCalendar.appendChild(newDay);\n}", "function createCalendarDay(num, day, mon, year) {\n var currentCalendar = document.getElementById(\"calendar\");\n\n var newDay = document.createElement(\"div\");\n var date = document.createElement(\"p\");\n var dayElement = document.createElement(\"p\");\n\n date.innerHTML = num;\n dayElement.innerHTML = day;\n\n newDay.className = \"calendar-day \";\n\n // Set ID of element as date formatted \"8-January\" etc \n newDay.id = num + \"-\" + mon + \"-\" +year;\n\n newDay.appendChild(date);\n newDay.appendChild(dayElement);\n currentCalendar.appendChild(newDay);\n}", "function createCalendarDay(num, day, mon, year) {\n var currentCalendar = document.getElementById(\"calendar\");\n\n var newDay = document.createElement(\"div\");\n var date = document.createElement(\"p\");\n var dayElement = document.createElement(\"p\");\n\n date.innerHTML = num;\n dayElement.innerHTML = day;\n\n newDay.className = \"calendar-day \";\n\n // Set ID of element as date formatted \"8-January\" etc\n newDay.id = num + \"-\" + mon + \"-\" +year;\n\n newDay.appendChild(date);\n newDay.appendChild(dayElement);\n currentCalendar.appendChild(newDay);\n}", "addRest(rest) {\n\t\tvar starttime = note.getStartTime();\n\t\tvar duration = note.getDuration();\n\t\tvar endtime = starttime + duration;\n\n\t\tthis.symbolMap.set(starttime, [new NoteModule.NoteSymbol(starttime, duration)]);\n\n\t\t/*self.symbolMap.forEach(function(symbol, oldStarttime) {\n\t\t\tif (symbol typeof NoteModule.NoteSymbol || symbol typeof RestModule.RestSymbol) && (symbol.starttime >=\n\t\t\t\tstarttime && symbol.endtime < endtime) {\n\t\t\t\t\tself.symbolMap.delete(oldStarttime);\n\t\t\t}\n\t\t})\n\n\t\tself.symbolMap.set(starttime, new RestSymbol(starttime, duration));*/\n\t}", "function setDay(date, slide, templateNum) {\n \n // Setup global variables\n var objects = slide.getShapes()\n var calNum = [13, 13, 11, 11, 9]\n const MILLS = 1000 * 60 * 60 * 24 // The number of millisecconds in a day; used for calculations\n \n // Edit numbers\n if ((new Date(date)).getTime() > 100) { // If date exists:\n for (var i = 0; i < 7; i++) { // For each number of calendar dates on template (1-7):\n slide.getShapes()[calNum[templateNum] + i].getText().setText((new Date((new Date((new Date(date)).getTime() - (new Date(date).getDay()*MILLS))).getTime() + i*MILLS)).getDate()) // Set text to day in accordance to weekday\n }\n \n slide.getShapes()[calNum[templateNum] + (new Date(date)).getDay()].getFill().setSolidFill(settingsArray[0][1]) // Fill date day with background color\n slide.getShapes()[calNum[templateNum] + (new Date(date)).getDay()].getText().getTextStyle().setForegroundColor(255, 255, 255) // Set date day text to white\n \n // Delete widget if date does not work\n } else {\n for (var i = 0; i < 8; i++) { // For each date widget number plus day labels:\n slide.getShapes()[calNum[templateNum] - 1 + i].getText().setText(\"\") // Set text to blank\n }\n }\n}", "function createCalendarDay (num, day, mon, year) {\n var currentCalendar = document.getElementById('calendar')\n\n var newDay = document.createElement('div')\n var dayNumber = document.createElement('p')\n dayNumber.className = 'noselect'\n var dayElement = document.createElement('p')\n dayElement.className = 'noselect'\n\n dayNumber.innerHTML = num\n dayElement.innerHTML = day\n\n if (day === 'Sab' || day === 'Dom') newDay.className = 'calendar-day weekend'\n else newDay.className = 'calendar-day '\n\n newDay.setAttribute('data-modal-trigger', 'trigger-1')\n\n // Set ID of element as date formatted \"8-January\" etc\n newDay.id = num + '-' + mon + '-' + year\n\n newDay.appendChild(dayNumber)\n newDay.appendChild(dayElement)\n currentCalendar.appendChild(newDay)\n}", "function dayNode(daynum, dist, time) {\n var node = document.createElement(\"li\");\n node.id = \"day\" + daynum.toString();\n\n\n var day = document.createElement(\"div\");\n day.className = \"day\";\n\n\n dateArray = getCurrentDate(daynum);\n\n var calendar = document.createElement(\"div\");\n calendar.className = \"calendar\";\n \n var month = document.createElement(\"span\");\n month.className = \"month\";\n month.innerHTML = dateArray[0];\n \n var calendarDay = document.createElement(\"span\");\n calendarDay.className = \"calendarDay\";\n calendarDay.innerHTML = dateArray[1].toString();\n\n var title = document.createElement(\"span\");\n title.className = \"title\";\n title.innerHTML = \"Day \" + daynum.toString();\n\n var dist_time = document.createElement(\"span\");\n dist_time.className = \"details\";\n dist_time.innerHTML = dist.toString() + \" mi, \" + time.toString() + \" hrs\"\n\n var del = document.createElement(\"span\");\n del.className = \"day_delete\";\n del.setAttribute(\"onclick\", \"cancelDay(this)\");\n del.innerHTML = \"x\"\n\n var startDate = initialParams['start_date'];\n var endDate = initialParams['end_date'];\n if (startDate != '') {\n dateArray = getCurrentDate(daynum);\n\n var calendar = document.createElement(\"div\");\n calendar.className = \"calendar\";\n \n var month = document.createElement(\"span\");\n month.className = \"month\";\n month.innerHTML = dateArray[0];\n \n var calendarDay = document.createElement(\"span\");\n calendarDay.className = \"calendarDay\";\n calendarDay.innerHTML = dateArray[1].toString();\n\n calendar.appendChild(month);\n calendar.appendChild(calendarDay);\n }\n\n day.appendChild(calendar);\n day.appendChild(title);\n day.appendChild(dist_time);\n if (daynum > 1) {\n day.appendChild(del);\n }\n node.appendChild(day);\n return node\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates overview help for a multicommand cli
function multiCommandCliHelp(args) { let { config } = args; let { commands } = config; let defaultCommand = commands["index"]; let options = { ...(defaultCommand && defaultCommand.meta.options), help: helpFlag, version: versionFlag, }; function createSubCommandsHelp() { return Object.keys(commands) .filter((c) => c !== "index") .reduce((acc, commandName) => { let command = commands[commandName]; acc.push({ name: commandName, title: command.meta.title, }); return acc; }, []); } return args.helpFormatter({ cliName: config.cliName, cliVersion: config.cliVersion, cliDescription: config.cliDescription, commands: createSubCommandsHelp(), options: formatOptions(options), usage: defaultCommand && defaultCommand.meta.usage, examples: (defaultCommand && defaultCommand.meta.examples) || [], }); }
[ "_showHelp() {\n const sections = [\n {\n header: 'HMR_ReduxMapper',\n content: 'This is a module which generates a [italic]{global} and [italic]{component specific} mapping file ' +\n 'which should eliminate the need to manually list all reducers needed to render a given route when using ' +\n 'hot-module-reloading. To use this, each redux reducer file should contain a [bold]{PRM_REDUCER_NAME} ' +\n 'constant which this tool will look for. See https://github.com/paulbrom/hmr-redux-mapper for more information.',\n },\n {\n header: 'Options',\n optionList: COMMAND_LINE_ARGS,\n }\n ];\n const usage = cliUsage(sections)\n console.log(usage);\n }", "help() {\n console.error();\n console.error('Fetch a metadata about the server');\n console.error();\n console.error('Usage: cli.js server <subcommand>');\n console.error();\n console.error('<subcommand>:');\n console.error(' get Get server meta');\n console.error(' stats Get geo stats from server');\n console.error();\n }", "function cmd_Help() {\n\t\t\n\t}", "function helpSection(){\n console.log(\"Usage :-\");\n console.log(\"$ ./todo add \\\"todo item\\\" # Add a new todo\");\n console.log(\"$ ./todo ls # Show remaining todos\");\n console.log(\"$ ./todo del NUMBER # Delete a todo\");\n console.log(\"$ ./todo done NUMBER # Complete a todo\");\n console.log(\"$ ./todo help # Show usage\");\n console.log(\"$ ./todo report # Statistics\");\n}", "function showCommandHelpFucntion(){\n console.log('\"show\" command is used to show the list of clients, servers or both ');\n console.log('that are created by the user during the wrt-c session');\n console.log('The syntax of the command is the follows:');\n console.log('');\n console.log('show [client/server/all]');\n console.log('');\n}", "function outputHelpCommands() {\n output(\"Intercom basic commands\");\n output(\"-----------------------\");\n output(\"<b>help</b> - display help message\");\n output(\"<b>clear</b> - clears the content of the screen\");\n output(\"<b>open [URL]</b> - opens the given URL in the console\");\n}", "ShowHelpPage(forCommand, API) {\n\n // list functions in the Extended and ContractAPI class, except the class constructor and view/call/HELP helpers\n const list = CommandLineArgs.getMethods(API)\n .concat(CommandLineArgs.getMethods(Object.getPrototypeOf(API)))\n \n list.sort()\n\n // print all commands and their help if it's there\n for (const name of list) {\n if (forCommand && name!=forCommand) continue;\n console.log(\"-\".repeat(60))\n console.log('command: ' + name) // name the command\n if (API[name + \"_HELP\"]) { //if there's help...\n console.log(API[name + \"_HELP\"]()); // print the help\n }\n }\n\n this.ShowHelpOptions()\n }", "help() {\n console.error();\n console.error('Manage user information');\n console.error();\n console.error('usage: cli.js user <subcommand>');\n console.error();\n console.error('<subcommand>');\n console.error(' register Register a new user account');\n console.error(' info Get info about your own account');\n console.error(' list List users wth an optional filter prefix');\n console.error();\n }", "function helpCommand(){\n disMessage(\"<p> Hywie Martins Bash, Version 0.1.0 </P>\", true);\n disMessage(\"<p> These shell commands are defined internally. Type '<i>help</i>' to see this list.</P>\", true);\n disMessage(\"<p> | help | ls | cd | mkdir <br>| date | cp | mv | tree | clear | exit</P>\", true);\n}", "help() {\n console.error();\n console.error('Fetch a complete dataset from the server');\n console.error();\n console.error('Usage: cli.js clone <subcommand>');\n console.error();\n console.error('<subcommand>:');\n console.error(' get Stream LDgeoJSON of all the data on the server');\n console.error();\n }", "function showHelp() {\n exportLog('<p><b>Here is the help: </b></p>');\n exportLog('<p><ul>');\n for (let i = 0; i < commands.length; i++) {\n exportLog(`<li> ${commands[i]} </li>`);\n }\n exportLog('</ul></p>');\n}", "function showHelp() {\n\t//Use figlet npm package to convert text to art/drawing.\n\tfiglet('LIRI help', function (err, data) {\n\t\tif (err) {\n\t\t\tconsole.log('Something went wrong...');\n\t\t\tconsole.dir(err);\n\t\t\treturn;\n\t\t}\n\t\tconsole.log(data)\n\t});\n\tvar helpInfo = \"Usage: node liri.js <command> [arguments]\"\n\tvar helpColumns = columnify([{\n\t\tCommand: 'my-tweets',\n\t\tDescription: \"Shows the last 20 tweets from Twitter timeline and when they were created.\"\n\t}, {\n\n\t\tCommand: \"movie-this [movie_name]\",\n\t\tDescription: \"Shows information about the specifid movie. If no movie is specified, Mr. Nobody is displayed by default.\"\n\t}, {\n\n\t\tCommand: \"spotify-this-song [song_name]\",\n\t\tDescription: \"Shows top 10 songs on Spotify that have specified name. If no song is specified, The Sign by Ace of Base is displayed by default.\"\n\t}, {\n\n\t\tCommand: 'do-what-it-says',\n\t\tDescription: \"Shows the top 10 songs on Spotify for the song, 'I want it that way.'\"\n\t}])\n\tconsole.log(\"==================================================================================================\");\n\tconsole.log(helpInfo);\n\tconsole.log(\"==================================================================================================\");\n\tconsole.log(helpColumns);\n}", "function commandHelp() {\n\tconsole.log(\"--- Available commands: ---\".green);\n\tconsole.log(\"--- (just start typing) ---\");\n\tconsole.log(\" \\\"help\\\":\".green, \" List all available commands (show this message again).\");\n\tconsole.log(\" \t\\\"add\\\":\".green, \" Add a new user that can be used to access the OPC UA Server.\");\n\tconsole.log(\" \tNote that users are not saved after shutdown!\");\n\tconsole.log(\" \\\"users\\\":\".green, \" Display all usernames that can currently be used.\");\n\tconsole.log(\" \\\"randomize\\\":\".green, \" Randomize the values of CoffeeLevel, WaterLevel and Cleanliness.\\n \tSince the Coffee Machine can't provide the actual data,\\n this command can be used instead to demonstrate the\\n visualization of the machine data in the HMI Application\");\n\trl.prompt();\n}", "get help() {\n\t\tlet response = \"\"\n\t\tif (this._description) { \n\t\t\tresponse = this._description; \n\t\t}\n\n\t\tresponse += \" - Usage: \" + this.format;\n\t\tresponse += \" - Ex: \" + this.example;\n\n\t\treturn response;\n\t}", "function help() {\n\n // Print grunt version.. Also initing colors for later use\n task.init([]);\n\n // the list of tasks we'd like to output\n var knowns = {\n init: {info: 'Initialize a new mockup with grunt.js and the dirs for pages, assets and json files'},\n mockup: {info: 'Generate the site content'},\n 'mockup:reload': { info: 'Watch files to retrigger a new build and a page reload'},\n 'mockup:serve': {info: 'Spawn a local http server on top of mockup output'},\n\n };\n\n var col1len = 0;\n\n var opts = Object.keys(optlist).map(function(long) {\n var o = optlist[long];\n var col1 = '--' + long + (o.short ? ', -' + o.short : '');\n col1len = Math.max(col1len, col1.length);\n return [col1, o.info];\n });\n\n var tasks = Object.keys(knowns)\n .map(function(name) {\n col1len = Math.max(col1len, name.length);\n var info = knowns[name].info;\n if (knowns[name].basic) {\n info += ' *';\n }\n return [name, info];\n });\n\n log.header('Usage');\n log.writeln(' ' + path.basename(process.argv[1]) + ' [options] [task [task ...]]');\n\n // Widths for options/tasks table output.\n var widths = [1, col1len, 2, 77 - col1len];\n\n log.header('Options');\n opts.forEach(function(a) { log.writetableln(widths, ['', a[0], '', a[1]]); });\n log.header('Tasks');\n tasks.forEach(function(a) { log.writetableln(widths, ['', a[0], '', a[1]]); });\n\n}", "function help(){\r\n console.log(\"Usage:\")\r\n console.log(\"[function choice][parameters]\")\r\n //console.log(\"function names includes: place, restaurant\")\r\n console.log(\"function choice includes:\")\r\n console.log(\" getListOfItems : no additional parameters in need\")\r\n console.log(\" getOneItemById : needs an id from 1 to 6\")\r\n console.log(\" getOneAttributeFromItem : needs an id from 1 to 6 and an attribute, attributes contains {geometry, icon, id, name, opening_hours, photos, place_id, rating, reference, scope, types, vicinity}\")\r\n console.log(\"examples: node project1_v2.js getListOfItems\")\r\n console.log(\" node project1_v2.js getOneItemById 1\")\r\n console.log(\" node project1_v2.js getOneAttributeFromItem 2 geometry\")\r\n}", "function interactiveHelpConstruct(){\n\tfor(int in commands){\n\t\tif(commands[int].interactive){\n\t\t\tfor(sub in commands[int].commands){\n\t\t\t\tif(!(commands[int].commands[sub].cmdName === undefined)){\n\t\t\t\t\tconst name = sub;\n\t\t\t\t\tif(!(name.includes(\"help\"))){\n\t\t\t\t\t\t\tcommands[int].commands[name + \"-help\"] = new commandConstructor({\n\t\t\t\t\t\t\tcmdName:name + \"-help\",\n\t\t\t\t\t\t\texecute:args => {\n\t\t\t\t\t\t\t\tlet output = \"\";\n\t\t\t\t\t\t\t\toutput += \"Proper Usage: `\" + name + \"` \";\n\t\t\t\t\t\t\t\tif(!(commands[int].commands[name].args === undefined)){\n\t\t\t\t\t\t\t\t\tfor(argo in commands[int].commands[name].args){\n\t\t\t\t\t\t\t\t\t\tconst argumentName = commands[int].commands[name].args[argo].name;\n\t\t\t\t\t\t\t\t\t\toutput += \"`\" + argumentName + \"` \";\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\toutput += \"\\n\";\n\t\t\t\t\t\t\t\t\tfor(argu in commands[int].commands[name].args){\n\t\t\t\t\t\t\t\t\t\tconst argumentName = commands[int].commands[name].args[argu].name;\n\t\t\t\t\t\t\t\t\t\tconst argumentDesc = commands[int].commands[name].args[argu].desc;\n\t\t\t\t\t\t\t\t\t\toutput += \"__\" + argumentName + \":__ \" + argumentDesc + \"\\n\";\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tglobalMessage.channel.send(output);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdescription:\"A help function\",\n\t\t\t\t\t\t\tcategory:\"int\",\n\t\t\t\t\t\t\targsEnforced:false\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "async _run_help() {\n this._options.usage();\n }", "function generateHelp(state) {\n helpers_1.event.emit(\"showHelp\");\n console.log(\"\\nOPTIONS:\\n\");\n let optionShorthands = state.options.map(o => o.shorthand).sort();\n state.options.sort().map((option, i) => {\n let name = `--${option.name}${typeof optionShorthands[i] !== \"undefined\" ? (', -' + optionShorthands[i]) : ''}`;\n console.log(`${name.padEnd(30, \" \")}${option.description}`);\n });\n console.log(\"\\nCOMMANDS:\\n\");\n state.commands.map(command => {\n let name = `${command.name}`;\n let description = command.hasOwnProperty('parent') ? `Alias of '${command.parent}' command.` : command.description;\n console.log(name.padEnd(30, \" \") + description);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the newProblem Dialog box.
function initializeNewProblemDialog() { /** tab initialisation * */ jQuery(".tabContent").hide(); jQuery("ul.tabNavigation li:first").addClass("selected").show(); jQuery(".tabContent:first").show(); jQuery('ul.tabNavigation li').click(function() { jQuery("ul.tabNavigation li").removeClass("selected"); jQuery(this).addClass("selected"); jQuery(".tabContent").hide(); var activeTab = jQuery(this).find("a").attr("href"); $(activeTab).slideDown(); return false; }).filter(':first').click(); /** Error initialisation* */ if(jQuery("#departureDate").val().length == 0) jQuery("#departureDate").addClass("error"); if(jQuery("#departureDate1").val().length == 0) jQuery("#departureDate1").addClass("error"); /** dialog box initialisation * */ jQuery("#newProblem").dialog( { autoOpen : false, height : 400, width : 450, resizable : false, modal : true, buttons : { 'OK' : function() { var b; // {Boolean} b = addProblem(); if (b) jQuery(this).dialog('close'); }, 'Annuler' : function() { jQuery(this).dialog('close'); } }, close : function() { } }); }
[ "function initProblem()\n\t{\n\t\tif (reloading)\n\t\t{\n\t\t\tapp.loadingBox(app.style.probCreateText, app.style.probCreateBg, app.style.probCreateTime);\n\t\t\treloading = false;\n\t\t}\n\t\telse\n\t\t\tapp.loadingBox();\n\n\t\tpromise = view.assignmentManager();\n\t\tprobId = view.getProbId();\n\t}", "function newProblem() {\n // reset input element to default state\n inputEl.value = \"\";\n inputEl.style.border = \"\";\n\n // randomly select an enabled operation\n let possibleOperations = OPERATION_SETTINGS.filter(operation => operation.enabled);\n let operation = selectRandom(possibleOperations);\n\n // get operands for that operation\n let [ operandOne, operandTwo ] = getOperands(operation);\n\n // set the problem display to the newly generated problem\n problemEl.innerHTML = `${operandOne} ${operation.sign} ${operandTwo} = ?`;\n}", "function GFGUICreationNewDialogue() {\n\tthis.mSprite = new Sprite();\n\t\n\tthis.mInputBoxes = new Array();\n\tthis.mInputBoxes[0] = new GUIInputBox();\n\tthis.mInputBoxes[1] = new GUIInputBox();\n\t\n\tthis.mButtons = new Array();\n\tthis.mButtons[0] = new GUIButton();\n\tthis.mButtons[1] = new GUIButton();\n\t\n\tthis.mConfirmText = new Text();\n\tthis.mExtraText = new Text();\n}", "function createProblem()\n\t{\n\t\t// Update the history\n\t\tapp.router.navigate('create');\n\n\t\t// Create a blank problem\n\t\tapp.curProblem = new app.Question(null, {parse:true});\t// We need parse:true so the steps collection gets created\n\t\tapp.originalProblem = app.curProblem.clone();\t// Save a copy of the model so we can compare against it to detect changes\n\t\tapp.originalProblem.resetSteps();\n\n\t\t// Wipe out the whiteboard list\n\t\tapp.wbList.clear();\t// Wipe out the existing model\n\n\t\tvw.preInitDone();\n\t}", "setBlankProblem(problemName) {\n // Create blank project (deep copy clone) and name\n this.problem = null;\n this.problem = jQuery.extend(true, {}, Problem);\n this.problem.name = problemName;\n // Add single category\n this.addCategory('');\n // Add two alternatives\n this.addAlternative('');\n this.addAlternative('');\n }", "constructor() { \n \n Problem.initialize(this);\n }", "function setupDialogue()\n{\n thomasDiag = new Dialogue(\"Hey little dude! Welcome to our town. My name is Thomas.\",\n \"Man, my hands are so cold. I wish I hadn’t left my gloves at home.\",\n \"Thank you so much little dude! I actually found my gloves, but I could still use these.\");\n miaDiag = new Dialogue(\"¿TRES leches? ¿En esta economia?\", \"\", \"\");\n snowyDialog = new Dialogue(\"...sigh...\\nI'm so bored.\",\n \"I wish I had something pretty to look at.\",\n \"What beautiful flowers! They're not my favorite but they will do for now.\");\n patrickDialog = new Dialogue(\"I've always dreamt of being a witch, flying around to different cities.\",\n \"Do you think you can find something to help me become a witch?\",\n \"Wow! This is exactly what I wanted! ありがとう\");\n sethDialog = new Dialogue(\"Actually my dream is to own a minimalistic farm.\", \"\", \"\");\n rebeccaDialog = new Dialogue(\"Have you seen any delicious bugs around?\", \"\", \"\");\n elieDialog = new Dialogue(\"Let's be friends.\", \"\", \"\");\n pepeDialog = new Dialogue(\"Hexi stinks!\\nWhat's Hexi? I have no idea...\", \"\", \"\");\n}", "function initializeDialog() {\r\n\r\n\tvar handleNew = function() {\r\n\t\trouteDetailDialog();\r\n\t\tmapClickHandle = GEvent.addListener(map, \"click\", leftClick());\r\n\t\tenableMarkerListeners();\r\n\t\tthis.hide();\r\n\t}\r\n\t\r\n\t// Initialize Dialog\r\n\tvar initDialog;\r\n\tinitDialog = new YAHOO.widget.SimpleDialog(\"initDialog\", { \r\n\t\twidth: \"12em\", \r\n\t\teffect:{effect:YAHOO.widget.ContainerEffect.FADE,\r\n\t duration:0.25}, \r\n\t\tfixedcenter:false,\r\n\t\tmodal:false,\r\n\t\tvisible:false,\r\n\t\tdraggable:true,\r\n\t\tconstraintoviewport:true,\r\n\t\txy: [981, 64] }\r\n\tinitDialog.setBody(\"Please Select a Route or create a New Route.\");\r\n\t\r\n\t\r\n\tvar newRouteBtn = [ { text:\"New\", \r\n\t\t\t\t\t\thandler:handleNew },\r\n\t\t\t\t\t ];\r\n\t\t\t\t\t \r\n\tinitDialog.cfg.queueProperty(\"buttons\", newRouteBtn);\r\n\tinitDialog.render(); \r\n\r\n\tYAHOO.util.Event.addListener(\"showDialog\", \"click\", initDialog.show, initDialog, true);\r\n}", "function fillInProblemEdit(problem) {\n $(\"#edit-problem-id\").val(problem.Id).focus();\n $(\"#edit-problem-name\").val(problem.Name).focus();\n $(\"#edit-problem-description\").val(problem.Description).focus();\n $(\"#edit-problem-language\").val(problem.Language).focus();\n $(\"#edit-problem-filetype\").val(problem.Filetype).focus();\n\n // Test cases\n $.each(problem.TestCases,\n function(i, testCase) {\n newTestCaseEntry($(\"#edit-problem-form .btn-floating\"));\n\n var panel = $(\"#edit-problem-form .btn-floating\").prev();\n\n panel.find(\"textarea:first\").val(testCase.Input);\n panel.find(\"textarea:last\").val(testCase.Output);\n panel.find(\"input.test-case-id\").val(testCase.Id).focus();\n });\n\n $(\"#edit-problem-modal\").openModal();\n }", "function setupProblemFormValidation() {\n //console.log('setup problem form Validate');\n gmstrace('setup problem form Validate');\n\n // set up validation on problem form\n gms.problemValidator = $('#problem-form').validate({\n rules:{\n inpProblemSuggestion:{\n minlength:8,\n required:true\n },\n inpProblemCategory:{\n minlength:8,\n required:true\n },\n inpProblemEmail:{\n email:true\n },\n txtProblemDetails:{\n minlength:10,\n required:false\n }\n\n },\n messages:{\n // override default messages for each field/validaton type with these messages\n inpProblemEmail: {\n email: \"Please enter a valid email address, or leave this field blank\"\n }\n },\n highlight:function (label) {\n $(label).closest('.control-group').addClass('error');\n },\n success:function (label) {\n label\n .text('OK!').addClass('valid')\n .closest('.control-group').addClass('success');\n },\n\n errorPlacement:function (error, element) {\n // override standard error placement for combobox, since validate inserts the\n // error right after the input element. find the parent element with class=combobox\n // and put the error after that\n if (element.attr(\"name\") == \"inpProblemCategory\") {\n error.insertAfter(element.parent(\".combobox\"));\n } else {\n error.insertAfter(element);\n }\n },\n\n onsubmit:false\n });\n }", "function GFGUICreationLoadDialogue() {\n\tthis.mPos = new IVec2(0, 0);\n\tthis.mSprite = new Sprite();\n\t\n\tthis.mListBox = new GUIListBox();\n\tthis.mOldSelected = -1;\n\t\n\tthis.mRedraw = false;\n\tthis.mRenderCanvas = new RenderCanvas();\n\t\n\tthis.mButtons = new Array();\n\tthis.mButtons[0] = new GUIButton();\n\tthis.mButtons[1] = new GUIButton();\n\tthis.mButtons[2] = new GUIButton();\n\t\n\tthis.mCurrentSeg = false;\n\tthis.mWarning = false;\n\t\n\tthis.mConfirmText = new Text();\n\tthis.mDeleteText = new Text();\n\tthis.mWarningText = new Text();\n\t\n\tthis.mSegmentList = new Array();\n}", "function setupMessageDialog() {\n jQuery('#uniMessageDialog').dialog({\n autoOpen: false,\n resize: \"auto\",\n width: 450,\n modal: true,\n closeOnEscape: false,\n open: function() {\n // Hide the title bar\n jQuery('#uniMessageDialog').parent().find(\".ui-dialog-titlebar\").hide();\n },\n position: ['middle', 45],\n buttons: {\n \"OK\": function() {\n jQuery('#uniMessageDialog').dialog(\"close\");\n }\n\n },\n close: function() {\n jQuery('#uniMessageDialog').dialog(\"close\");\n }\n });\n }", "function initializeNewRequestDialog() {\r\n\t/** tab initialisation * */\r\n\tjQuery(\".tabContent\").hide();\r\n\tjQuery(\"ul.tabNavigation li:first\").addClass(\"selected\").show();\r\n\tjQuery(\".tabContent:first\").show();\r\n\tjQuery('ul.tabNavigation li').click(function() {\r\n\t\tjQuery(\"ul.tabNavigation li\").removeClass(\"selected\");\r\n\t\tjQuery(this).addClass(\"selected\");\r\n\t\tjQuery(\".tabContent\").hide();\r\n\t\tvar activeTab = jQuery(this).find(\"a\").attr(\"href\");\r\n\t\t$(activeTab).slideDown();\r\n\t\treturn false;\r\n\t}).filter(':first').click();\r\n\t\r\n\t/** Error initialisation* */\r\n\tif(jQuery(\"#departure\").val() == jQuery(\"#arrival\").val())\r\n\t\tjQuery(\"#departure, #arrival, #departurePer, #arrivalPer\").addClass(\"error\");\r\n\tif(jQuery(\"#departureDate\").val().length == 0) jQuery(\"#departureDate\").addClass(\"error\");\r\n\tif(jQuery(\"#departureDatePer\").val().length == 0) jQuery(\"#departureDatePer\").addClass(\"error\");\r\n\r\n\t/** dialog box initialisation * */\r\n\tjQuery(\"#newRequest\").dialog( {\r\n\t\tautoOpen : false,\r\n\t\theight : 400,\r\n\t\twidth : 450,\r\n\t\tresizable : false,\r\n\t\tmodal : true,\r\n\t\tbuttons : {\r\n\t\t\t'Ajouter la requète' : function() {\r\n\t\t\t\tvar b; // {Boolean}\r\n\t\t\t\tif (isPeriodic()) {\r\n\t\t\t\t\tb = addPeriodicRequest();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tb = addSingleRequest();\r\n\t\t\t\t}\r\n\t\t\t\tif (b) jQuery(this).dialog('close');\r\n\t\t\t},\r\n\t\t\t'Annuler' : function() {\r\n\t\t\t\tjQuery(this).dialog('close');\r\n\t\t\t}\r\n\t\t},\r\n\t\tclose : function() {\r\n\t\t}\r\n\t});\r\n}", "function Window_DifficultyDetails() {this.initialize.apply(this, arguments); }", "function Window_DifficultyChoice() { this.initialize.apply(this, arguments); }", "function showProjectLoadTypeFailDialogue() {\n showDialog({\n title: 'WARNING: Incorrect project type',\n text: 'Reselect a <b>DSS-Decision-Making-</b>&lt;ProjectTitle&gt;.json file:\\nCurrent project unchanged'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}", "async openNewProjectDialog() {\n\t\tlet newProjectDialogPanel;\n\t\tthis.newProjectDialog = new NewProjectDialog({\n\t\t\tcancel: () => {\n\t\t\t\tnewProjectDialogPanel.destroy();\n\t\t\t},\n\t\t\tcallback: (args) => {\n\t\t\t\targs.callback = () => {\n\t\t\t\t\tnewProjectDialogPanel.destroy();\n\t\t\t\t};\n\t\t\t\tAppc.new(args);\n\t\t\t}\n\t\t});\n\t\tnewProjectDialogPanel = atom.workspace.addModalPanel({ item: this.newProjectDialog });\n\t}", "function updateProblem() {\n stateProblem.currentProblem = generateProblem();\n problemElement.innerHTML = `${stateProblem.currentProblem.firstNumber} ${stateProblem.currentProblem.operator} ${stateProblem.currentProblem.secondNumber}`;\n\n //clear up the input to make empty\n ourField.value = \"\";\n ourField.focus();\n}", "function initializeUI() {\n args = dwscripts.getCommandArguments();\n\n // Developer note. This message should not be displayed at all.\n if (!args || !args.message || !args.helpID) {\n throw \"Missing message and/or help ID.\";\n }\n\n _message = dwscripts.findDOMObject(\"message\");\n _message.innerHTML = args.message;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public function `includes`. Returns true if `data` contains `value`, false otherwise.
function includes (data, value) { var iterator, iteration, keys, length, i; if (! assigned(data)) { return false; } if (haveSymbols && data[Symbol.iterator] && isFunction(data.values)) { iterator = data.values(); do { iteration = iterator.next(); if (iteration.value === value) { return true; } } while (! iteration.done); return false; } keys = Object.keys(data); length = keys.length; for (i = 0; i < length; ++i) { if (data[keys[i]] === value) { return true; } } return false; }
[ "function includes (data, value) {\n var iterator, iteration;\n\n if (not.assigned(data)) {\n return false;\n }\n\n try {\n if (typeof Symbol !== 'undefined' && data[Symbol.iterator] && isFunction(data.values)) {\n iterator = data.values();\n\n do {\n iteration = iterator.next();\n\n if (iteration.value === value) {\n return true;\n }\n } while (! iteration.done);\n\n return false;\n }\n\n Object.keys(data).forEach(function (key) {\n if (data[key] === value) {\n throw 0;\n }\n });\n } catch (ignore) {\n return true;\n }\n\n return false;\n }", "function includes(data, value) {\n var iterator, iteration, keys, length, i;\n\n if (!assigned(data)) {\n return false;\n }\n\n if (haveSymbols && data[Symbol.iterator] && isFunction(data.values)) {\n iterator = data.values();\n\n do {\n iteration = iterator.next();\n\n if (iteration.value === value) {\n return true;\n }\n } while (!iteration.done);\n\n return false;\n }\n\n keys = Object.keys(data);\n length = keys.length;\n\n for (i = 0; i < length; ++i) {\n if (data[keys[i]] === value) {\n return true;\n }\n }\n\n return false;\n }", "function isIn(value, data) {\n return contains(data, value);\n }", "function isIn(value, data) {\n return contains(data, value);\n}", "includes(value) {\n if (value === undefined) {\n throw Error('Must pass in a value');\n }\n let current = this.head;\n while (current.next) {\n if (current.data === value) {\n return true;\n } else {\n current = current.next;\n }\n }\n if (current.data === value) {\n return true;\n } else {\n return false;\n }\n }", "includes(value) {\n let result;\n do {\n result = this.source.next();\n if (!result.done && result.value === value) {\n return true;\n }\n } while (!result.done);\n return false;\n }", "function contains(data, value) {\n var iterator, iteration;\n\n if (!assigned(data)) {\n return false;\n }\n\n if (haveSets && instanceStrict(data, Set)) {\n return data.has(value);\n }\n\n if (string(data)) {\n return data.indexOf(value) !== -1;\n }\n\n if (haveSymbols && data[Symbol.iterator] && isFunction(data.values)) {\n iterator = data.values();\n\n do {\n iteration = iterator.next();\n\n if (iteration.value === value) {\n return true;\n }\n } while (!iteration.done);\n\n return false;\n }\n\n return some(data, function (key, dataValue) {\n return dataValue === value;\n });\n }", "function contains(data, value) {\n var iterator, iteration;\n\n if (!assigned(data)) {\n return false;\n }\n\n if (haveSets && instanceStrict(data, Set)) {\n return data.has(value);\n }\n\n if (string(data)) {\n return data.indexOf(value) !== -1;\n }\n\n if (haveSymbols && data[Symbol.iterator] && isFunction(data.values)) {\n iterator = data.values();\n\n do {\n iteration = iterator.next();\n\n if (iteration.value === value) {\n return true;\n }\n } while (!iteration.done);\n\n return false;\n }\n\n return some(data, function (key, dataValue) {\n return dataValue === value;\n });\n}", "contains(value) {\n const listVals = this.list.map(node => node.value);\n return listVals.includes(value);\n }", "includes(val) {\n /**\n * if list is empty then return false.\n */\n if(this.length === 0) return false;\n /**\n * else itrate through the list anc check for the value.\n */\n var temp = this.head;\n while(temp.next) {\n if (temp.data === val) return true;\n temp = temp.next;\n }\n if (temp.data === val) return true;\n return false;\n }", "function includes(array, value) {\n return array.indexOf(value) > -1;\n}", "__contains__(value) {\n if (value.type() === \"dict\") {\n return value.valueOf()[this.toString()] !== undefined; // fixme: toString() conversion falsifies data\n }\n else if (value.type() === \"list\") {\n // We need to compare every item using __cmp__()\n for(let item of value.valueOf()) {\n item = new Value(item);\n if(item.__cmp__(this) === 0) {\n return true;\n }\n }\n\n return false;\n //return new Value(value.valueOf().indexOf(this.valueOf()) >= 0);\n }\n\n return value.toString().indexOf(this.toString()) >= 0;\n }", "contains(data) {\n return this.find(data) !== -1 ? true : false\n }", "function arrayIncludes(array, value) {\n const length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}", "includes(collection, ...values) {\n if (!assert.isDefined(collection, \"spellCore.includes(collection)\")) return false\n if (!values.length) return false\n return spellCore.all(values, (value) => spellCore.itemOf(collection, value) !== undefined)\n }", "function contains(list, value) {\n\n}", "function contains(input, value) {}", "function contains(list, value) {\n for (var i = 0; i < list.length; i++) {\n if (list[i] === value) return true;\n }\n return false;\n }", "function include(value) {\n if (value < this.start)\n return false;\n if (this.exclusive)\n return value < this.end;\n return value <= this.end;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that loops through the horoscopes and compares them to the previous highest ranked horoscopes on firebase and saves their similarities also saves the mood type and moodscore of the horoscopes
findingSimilarty(){ this.resultsWithSim.length = 0; this.highestPrevious = ""; //saving the highest previously ranked horoscope //have to add only comparing it to the highest scored horoscope to avoid calling the API to many times for(let p of this.previous){ if(this.highestPrevious.length == ""){ this.highestPrevious = p; } else{ if(this.highestPreviousrating < p.rating){ this.highestPrevious = p; } } } //looping through all the horoscope results for(let r = 0; r < this.results.length; r++){ let text; //saving the horoscope text if(this.results[r].horoscope.horoscope == undefined){ text = this.results[r].horoscope; } else{ text = this.results[r].horoscope.horoscope; } //calling API to find the mood and moodscore of the selected horoscope fetch("https://api.dandelion.eu/datatxt/sent/v1/?lang=en&text="+text+"&token=ef45543309bf47c0829cb8ab19b82460") .then(response => { if(!response.ok){ throw Error('ERROR: ${response.statusText}'); } return response.json(); }) .then(json => { //adding the mood and moodscore values to an object array this.resultsWithSim[r] = new ResultWithSim(json.sentiment.type, json.sentiment.score); }); //calling API to find the similarity between highest ranked previous horoscope and current horoscope fetch("https://api.dandelion.eu/datatxt/sim/v1/?text1="+text+"&text2="+this.highestPrevious.horoscope+"&token=ef45543309bf47c0829cb8ab19b82460") .then(response => { if(!response.ok){ throw Error('ERROR: ${response.statusText}'); } return response.json(); }) .then(json => { //updating object array with the simmilaritity values and the horoscope text this.resultsWithSim[r].similarities = json.similarity; this.resultsWithSim[r].horoscope = text; //calling function to put the results in order by similarity value this.orderingResult(); }); } }
[ "function setTopTrophy(user, userTrophies) {\n var topTrophy = \"None\";\n var topCost = 0;\n trophiesRef.once('value', function(trophies) {\n userTrophies.forEach(function(trophy) {\n var cost = trophies.child(trophy.key() + '/cost').val();\n if (cost !== null && cost > topCost) {\n topTrophy = trophy.key();\n topCost = cost;\n // console.log('Inside: User: ' + user.key() + ', top trophy: ' + topTrophy);\n }\n });\n // check custom trophies\n projectsRef.once('value', function(projects) {\n projects.forEach(function(project) {\n if (!user.child('projects').hasChild(project.key()) \n || !project.hasChild('custom_trophies')) return;\n var trophies = project.child('custom_trophies');\n userTrophies.forEach(function(trophy) {\n var cost = trophies.child(trophy.key() + '/cost').val();\n if (cost !== null && cost > topCost) {\n topTrophy = trophy.key();\n topCost = cost;\n }\n });\n });\n });\n // console.log('Between: User: ' + user.key() + ', top trophy: ' + topTrophy);\n user.ref().update({\n 'top_trophy': topTrophy\n });\n });\n\n\n}", "function findTopThreeFrats() {\r\n\r\n // LOCAL VARIABLES TO STORE TOTAL POSSIBLE DIFFERENCE AND MULTIPLY DECIMAL TO PERCENTAGE\r\n var total_deviation = 20;\r\n var percent = 100;\r\n\r\n // ARRAY OF EACH OF THE USER'S VALUE, WHICH IS USED TO CALCULATE MATCH PERCENTAGE\r\n var user_values = [academics_value, athletics_value, leadership_value, social_value, philanthropy_value];\r\n\r\n // LOOP THROUGH EACH FRAT TO CALCULATE MATCH PERCENTAGE WITH EACH FRAT\r\n for (index = 0; index < frats.length; index++) {\r\n\r\n // LOCAL VARIABLE TO STORE TOTAL DIFFERENCE VALUE\r\n var total = 0;\r\n\r\n // LOOP THROUGH EACH VALUE OF CURRENT FRAT TO FIND TOTAL DIFFERENCE VALUE\r\n for (num = 0; num < user_values.length; num++) {\r\n total += Math.abs(user_values[num] - frat_values[index][num]);\r\n console.log(user_values[num]);\r\n console.log(frat_values[index][num]);\r\n }\r\n\r\n // CALCULATE MATCH PERCENTAGE\r\n var diff_decimal = total / total_deviation;\r\n var match_decimal = 1 - diff_decimal;\r\n var match_percent = match_decimal * percent;\r\n\r\n // STORE FRAT NAME AS KEY AND MATCH PERCENTAGE AS VALUE INTO LOCALSTORAGE\r\n // ALLSTON - NEW EDIT\r\n myStorage.setItem(frats[index].name, match_percent);\r\n // myStorage.setItem(frats[index], match_percent);\r\n }\r\n}", "function update_leaderboard_of_the_day(){\n var stationPlayers_ref = new Firebase(FB_STATIONPLAYERS_URL);\n stationPlayers_ref.once(\"value\", function(AllPlayerSnapshot){\n AllPlayerSnapshot.forEach(function(PlayerSnapshot){\n var value = PlayerSnapshot.val();\n \n if (value.connected === true){\n var stationUser_score = new Firebase(FB_STATIONLEADERBOARD_URL).child(PlayerSnapshot.key());\n stationUser_score.once(\"value\", function(snapshot){\n var previous_player = snapshot.val();\n // Store player details into leaderboard if player does not exist in leaderboard node\n if (previous_player === null || previous_player === undefined) {\n stationUser_score.set({\n icon_url: value.icon_url,\n nickname: value.nickname,\n score: value.score\n });\n }\n // Player exist in leadeboard, compare score with players in player node and update if lesser\n else{\n var current_high_score = value.score;\n if (current_high_score < previous_player.score){\n current_high_score = previous_player.score;\n }\n stationUser_score.child(\"score\").set(current_high_score);\n }\n });\n }\n });\n \n start_game_over();\n });\n}", "function search(hymnal, query) {\n\n var ranks = new Array();\n for(var i = 0; i < hymnal.length; i++) {\n ranks.push({hymn: hymnal[i], rank: 0});\n }\n\n if(category !== null) ranks = ranks.filter(isC);\n if(subcategory !== null) ranks = ranks.filter(isS);\n\n // Similarity Check. 70%\n // var wt = 0.7; var wt1 = 0.8 * wt; var wt2 = 0.2 * wt; // Number or Title: 80% (56%)\n for(var i = 0; i < ranks.length; i++) {\n var numberRank = (compare(query, ranks[i].hymn.number)) * 0.7;\n var titleRank = (compare(query.toLowerCase().removeDiacritics().removePunctutation(), ranks[i].hymn.name.toLowerCase().removeDiacritics().removePunctutation())) * 0.7;\n ranks[i].rank += (numberRank > titleRank) ? numberRank : titleRank;\n }\n // Content: 20% (14%)\n // Not computed \"on the fly\" to save memory, should be indexed\n\n // Overall Popularity. 20%\n var freq;\n if(database)\n for(var i = 0; i < ranks.length; i++) {\n if(freq = database[loaded_hymnal_id][ranks[i].hymn.number]) {\n ranks[i].rank += f2(freq)/2;\n // log(`hymn ${ranks[i].hymn.number} freq ${freq} weight ${f2(freq)}`)\n }\n }\n\n // History. 10%\n var str = getLocalStorageKey(\"history\");\n if(str) {\n var obj = JSON.parse(str)\n if(obj) {\n var list = obj[loaded_hymnal_id];\n if(list) {\n var occurences = {};\n for(var j = 0; j < list.length; j++) {\n if(!occurences[list[j]]) occurences[list[j]] = 0;\n occurences[list[j]]++;\n }\n var times = 0;\n for(var i = 0; i < ranks.length; i++) {\n if(times = occurences[ranks[i].hymn.number]) ranks[i].rank += f1(times);\n }\n // log(occurences)\n }\n }\n }\n\n // Last Category. 10%\n if(lastHymn && (lastHymn.category || lastHymn.subcategory)) {\n if(lastHymn.category)\n var similar = ranks.filter(function(elem) {return elem.hymn.category == lastHymn.category;})\n if(lastHymn.subcategory)\n var similar = ranks.filter(function(elem) {return elem.hymn.subcategory == lastHymn.subcategory;})\n\n for(var entry of similar)\n entry.rank += 10;\n // log('similar');\n // log(similar.map(function(e) {return `${e.hymn.subcategory || e.hymn.category} ${e.hymn.number} ${e.hymn.name}`}));\n } else {\n for(var entry in ranks)\n entry.rank += 10;\n }\n\n ranks.sort(compareRanks);\n\n var maxResults = 5;\n ranks = ranks.slice(0, maxResults);\n\n // log(ranks.filter(weakRanks).map(function(e) {return `${e.rank} ${e.hymn.name}`}));\n\n return ranks.filter(weakRanks);\n}", "function calcHandicaps() {\n\tvar racename = localStorage.racename;\n\tdb.transaction(\n function(transaction) {\n transaction.executeSql(\n\t\t\t\t'SELECT * FROM predictions WHERE racename=? order by prediction desc;', \n\t\t\t\t[racename],\n function(transaction, result) {\n\t\t\t\tlocalStorage.maxtime=result.rows.item(0)['prediction'];\n\t\t\t\t},\n\t\t\t\terrorHandler\n\t\t\t);\n } \n\t);\n\tdb.transaction(\n function(transaction) {\n transaction.executeSql(\n\t\t\t\t'INSERT INTO races (racename, date, distance) VALUES (?, ?, ?);', \n [racename, date, distance], \n\t\t\t\t[localStorage.maxtime,racename],\n function(transaction, result) {\n\t\t\t\t},\n\t\t\t\terrorHandler\n\t\t\t);\n } \n \n\t);\n}", "function compareChoices() {\n\n database.ref().once('value').then(function (snapshot) {\n\n var p1Choice\n var p2Choice\n\n p1Choice = snapshot.val().playerOne.choice;\n p2Choice = snapshot.val().playerTwo.choice;\n\n $(\"#player-1-item\").text(\"Player one chooses: \" + p1Choice);\n $(\"#player-2-item\").text(\"Player two chooses: \" + p2Choice);\n\n if (p1Choice == \"rock\") {\n if (p2Choice == \"rock\") {\n $(\"#result\").text(\"Tie Game.\");\n } else if (p2Choice == \"paper\") {\n $(\"#result\").text(\"Player One wins.\");\n playerOne.wins++;\n database.ref(\"playerOne/wins\").set(playerOne.wins);\n playerTwo.losses++;\n database.ref(\"playerTwo/losses\").set(playerTwo.losses);\n } else if (p2Choice == \"scissors\") {\n $(\"#result\").text(\"Player Two wins.\");\n playerTwo.wins++;\n database.ref(\"playerOne/wins\").set(playerTwo.wins);\n playerOne.losses++;\n database.ref(\"playerTwo/losses\").set(playerOne.losses);\n }\n } else if (p1Choice == \"paper\") {\n if (p2Choice == \"rock\") {\n $(\"#result\").text(\"Player One wins.\");\n playerOne.wins++;\n database.ref(\"playerOne/wins\").set(playerOne.wins);\n playerTwo.losses++;\n database.ref(\"playerTwo/losses\").set(playerTwo.losses);\n } else if (p2Choice == \"paper\") {\n $(\"#result\").text(\"Tie Game.\");\n } else if (p2Choice == \"scissors\") {\n $(\"#result\").text(\"Player Two wins.\");\n playerTwo.wins++;\n database.ref(\"playerOne/wins\").set(playerTwo.wins);\n playerOne.losses++;\n database.ref(\"playerTwo/losses\").set(playerOne.losses);\n }\n } else if (p1Choice == \"scissors\") {\n if (p2Choice == \"rock\") {\n $(\"#result\").text(\"Player Two wins.\");\n playerTwo.wins++;\n database.ref(\"playerOne/wins\").set(playerTwo.wins);\n playerOne.losses++;\n database.ref(\"playerTwo/losses\").set(playerOne.losses);\n } else if (p2Choice == \"paper\") {\n $(\"#result\").text(\"Player One wins.\");\n playerOne.wins++;\n database.ref(\"playerOne/wins\").set(playerOne.wins);\n playerTwo.losses++;\n database.ref(\"playerTwo/losses\").set(playerTwo.losses);\n } else if (p2Choice == \"scissors\") {\n $(\"#result\").text(\"Tie Game.\");\n }\n }\n\n setTimeout(reset, 5000);\n });\n }", "function check() {\n if (player1choice == 'Rock' && player2choice =='Scissors') {\n player1Wins++;\n player2Losses++;\n console.log(\"first\")\n firebaseSet();\n }\n else if (player1choice == 'Rock' && player2choice == 'Paper'){\n player1Losses++;\n player2Wins++;\n console.log(\"second\")\n firebaseSet();\n }\n else if (player1choice == 'Scissors' && player2choice == 'Rock'){\n player1Losses++;\n player2Wins++;\n console.log(\"third\")\n firebaseSet();\n }\n else if (player1choice == 'Scissors' && player2choice == 'Paper'){\n player1Wins++;\n player2Losses++;\n console.log(\"fourth\")\n firebaseSet();\n }\n else if (player1choice == 'Paper' && player2choice == 'Rock'){\n player1Wins++;\n player2Losses++;\n console.log(\"fifth\")\n firebaseSet();\n }\n else if (player1choice == 'Paper' && player2choice == 'Scissors'){\n player1Losses++;\n player2Wins++;\n console.log(\"sixth\")\n firebaseSet();\n }\n else if (player1choice == player2choice){\n ties++;\n firebaseSet();\n } \n \n //check function closer\n }", "updootMeme () {\n // get meme data\n const memeName = this.dataset.meme;\n let updootCount = 0;\n\n // get normie's updooted memes\n const normieReference = Fire.getDatabase().child(\"normies\").child(Fire.getUserId());\n\n // check if normie has updoots list\n Fire.exists(normieReference, \"updoots\",\n function (updoots) {\n // check if normie has downdoots list\n Fire.exists(normieReference, \"downdoots\",\n function (downdoots) {\n // updoots exists; downdoots exists\n\n const isUpdooted = updoots.hasOwnProperty(memeName);\n const isDowndooted = downdoots.hasOwnProperty(memeName);\n\n if (isUpdooted) {\n delete updoots[memeName];\n Fire.write(normieReference.child(\"updoots\"), updoots, null, null);\n app.decreaseMemeRating(memeName, 1);\n return;\n } else {\n if (isDowndooted) {\n delete downdoots[memeName];\n Fire.write(normieReference.child(\"downdoots\"), downdoots, null, null);\n updoots[memeName] = memeName;\n Fire.write(normieReference.child(\"updoots\"), updoots, null, null);\n app.increaseMemeRating(memeName, 2);\n return;\n } else {\n updoots[memeName] = memeName;\n Fire.write(normieReference.child(\"updoots\"), updoots, null, null);\n app.increaseMemeRating(memeName, 1);\n return;\n }\n }\n\n },\n function (error) {\n if (error.code == \"childKey nonexistent\") {\n // updoots exists; downdoots !exists\n\n const isUpdooted = updoots.hasOwnProperty(memeName);\n const isDowndooted = false;\n\n if (isUpdooted) {\n delete updoots[memeName];\n Fire.write(normieReference.child(\"updoots\"), updoots, null, null);\n app.decreaseMemeRating(memeName, 1);\n return;\n } else {\n updoots[memeName] = memeName;\n Fire.write(normieReference.child(\"updoots\"), updoots, null, null);\n app.increaseMemeRating(memeName, 1);\n return;\n }\n\n } else {\n // Fire.js ran an error whilst reading from Firebase's realtime database\n console.log(\"Failure to read from given realtime database reference.\");\n console.log(error.code + \": \" + error.message);\n }\n });\n },\n function (error) {\n // check if normie has downdoots list\n Fire.exists(normieReference, \"downdoots\",\n function (downdoots) {\n // updoots !exists; downdoots exists\n\n const isUpdooted = false;\n const isDowndooted = downdoots.hasOwnProperty(memeName);\n\n if (isDowndooted) {\n delete downdoots[memeName];\n Fire.write(normieReference.child(\"downdoots\"), downdoots, null, null);\n const updoot = {};\n updoot[memeName] = memeName;\n Fire.write(normieReference.child(\"updoots\"), updoot, null, null);\n app.increaseMemeRating(memeName, 2);\n return;\n } else {\n const updoot = {};\n updoot[memeName] = memeName;\n Fire.write(normieReference.child(\"updoots\"), updoot, null, null);\n app.increaseMemeRating(memeName, 1);\n return;\n }\n\n },\n function (error) {\n if (error.code == \"childKey nonexistent\") {\n // updoots !exists; downdoots !exists\n\n const isUpdooted = false;\n const isDowndooted = false;\n\n const updoot = {};\n updoot[memeName] = memeName;\n Fire.write(normieReference.child(\"updoots\"), updoot, null, null);\n app.increaseMemeRating(memeName, 1);\n return;\n\n } else {\n // Fire.js ran an error whilst reading from Firebase's realtime database\n console.log(\"Failure to read from given realtime database reference.\");\n console.log(error.code + \": \" + error.message);\n }\n });\n });\n }", "relevance(that){cov_25grm4ggn6.f[4]++;let total=(cov_25grm4ggn6.s[13]++,0);let words=(cov_25grm4ggn6.s[14]++,Object.keys(this.count));cov_25grm4ggn6.s[15]++;words.forEach(w=>{cov_25grm4ggn6.f[5]++;cov_25grm4ggn6.s[16]++;total+=this.rank(w)*that.rank(w);});//return the average rank of my words in the other vocabulary\ncov_25grm4ggn6.s[17]++;return total/words.length;}", "async function main() {\n\tconst leagues = await db.query(`SELECT * FROM league`);\n\t// for all available leagues\n\tfor (let league of leagues) {\n\t\t// get rounds in season\n\t\tconst rounds = await sportmonks.get(`v2.0/rounds/season/{season_id}`, { \"season_id\": league.season_id, \"fixtures\": true });\n\t\t// for all rounds in season\n\t\tfor (let round of rounds.data) {\n\t\t\t// for all matches in round\n\t\t\tfor (let match of round.fixtures.data) {\n\t\t\t\t// check that match is not yet exists\n\t\t\t\tconst matches = await db.query(`SELECT id FROM ${env.DB_DATABASE}.match WHERE id = ?`, match.id);\n\t\t\t\t// if there is no such match then insert it to DB\n\t\t\t\tif (matches.length == 0) {\n\t\t\t\t\tconst homeLeagueClub = (await db.query(`SELECT * FROM league_club WHERE league_id = ? AND club_id = ?`, [league.id, match.localteam_id]))[0];\n\t\t\t\t\tconst awayLeagueClub = (await db.query(`SELECT * FROM league_club WHERE league_id = ? AND club_id = ?`, [league.id, match.visitorteam_id]))[0];\n\t\t\t\t\tawait db.query(`INSERT INTO ${env.DB_DATABASE}.match SET ?`, {\n\t\t\t\t\t\tid: match.id,\n\t\t\t\t\t\thome_goals: match.scores.ft_score ? match.scores.localteam_score : null,\n\t\t\t\t\t\taway_goals: match.scores.ft_score ? match.scores.visitorteam_score : null,\n\t\t\t\t\t\tbegin_at: match.time.starting_at.timestamp,\n\t\t\t\t\t\thome_league_club_id: homeLeagueClub.id,\n\t\t\t\t\t\taway_league_club_id: awayLeagueClub.id\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// update match details\n\t\t\t\t\tawait db.query(`UPDATE ${env.DB_DATABASE}.match SET home_goals = ?, away_goals = ?, begin_at = ? WHERE id = ?`, [\n\t\t\t\t\t\tmatch.scores.ft_score ? match.scores.localteam_score : null,\n\t\t\t\t\t\tmatch.scores.ft_score ? match.scores.visitorteam_score : null,\n\t\t\t\t\t\tmatch.time.starting_at.timestamp,\n\t\t\t\t\t\tmatch.id\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tdb.end();\n}", "summarizeHeroData(docs) {\n // collect data\n // hero averages\n let playerDetailStats = {};\n playerDetailStats.heroes = {};\n playerDetailStats.maps = {};\n playerDetailStats.rawDocs = docs;\n playerDetailStats.games = 0;\n playerDetailStats.wins = 0;\n playerDetailStats.nonCustomGames = 0;\n playerDetailStats.withPlayer = {};\n playerDetailStats.withHero = {};\n playerDetailStats.againstPlayer = {};\n playerDetailStats.againstHero = {};\n playerDetailStats.deathHistogram = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };\n playerDetailStats.takedownHistogram = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };\n playerDetailStats.skins = {};\n playerDetailStats.awards = {};\n playerDetailStats.highestStreak = 0;\n playerDetailStats.taunts = { \n bsteps: { count: 0, duration: 0, takedowns: 0, deaths: 0 },\n dances: { count: 0, takedowns: 0, deaths: 0 },\n sprays: { count: 0, takedowns: 0, deaths: 0},\n taunts: { count: 0, takedowns: 0, deaths: 0},\n voiceLines: { count: 0, takedowns: 0, deaths: 0 }\n };\n\n playerDetailStats.averages = {};\n playerDetailStats.max = {};\n playerDetailStats.min = {};\n playerDetailStats.median = {};\n let medianTemp = {};\n\n for (let i = 0; i < docs.length; i++) {\n let match = docs[i];\n let statList = DetailStatList.concat(PerMapStatList[match.map]);\n\n // hero stuff\n if (!(match.hero in playerDetailStats.heroes)) {\n playerDetailStats.heroes[match.hero] = {\n games: 0,\n wins: 0,\n totalAwards: 0,\n stats: { timeDeadPct : 0 },\n awards: {},\n totalTime: 0,\n votes: 0,\n highestStreak: 0\n };\n playerDetailStats.max[match.hero] = { timeDeadPct: 0 };\n playerDetailStats.min[match.hero] = { timeDeadPct: 100 };\n medianTemp[match.hero] = { timeDeadPct: []};\n }\n\n playerDetailStats.heroes[match.hero].totalTime += match.length;\n playerDetailStats.games += 1;\n playerDetailStats.heroes[match.hero].games += 1;\n playerDetailStats.heroes[match.hero].votes += match.votes;\n\n if (!(match.map in playerDetailStats.maps))\n playerDetailStats.maps[match.map] = { games: 0, wins: 0 };\n\n playerDetailStats.maps[match.map].games += 1;\n\n for (let s in statList) {\n let statName = statList[s];\n\n // older replays may have missing stats\n if (!(statName in match.gameStats))\n continue;\n\n if (!(statName in playerDetailStats.heroes[match.hero].stats)) {\n playerDetailStats.heroes[match.hero].stats[statName] = 0;\n playerDetailStats.max[match.hero][statName] = match.gameStats[statName];\n playerDetailStats.min[match.hero][statName] = match.gameStats[statName];\n medianTemp[match.hero][statName] = [];\n }\n\n // booooo blackheart's\n if (statName === 'BlackheartDoubloonsCollected') {\n // sometimes the replay freaks out and returns a huge integer. Set that to 0 if it happens\n if (match.gameStats[statName] > 200)\n match.gameStats[statName] = 0;\n }\n \n playerDetailStats.heroes[match.hero].stats[statName] += match.gameStats[statName];\n medianTemp[match.hero][statName].push(match.gameStats[statName]);\n\n if (match.gameStats[statName] > playerDetailStats.max[match.hero][statName])\n playerDetailStats.max[match.hero][statName] = match.gameStats[statName];\n \n if (match.gameStats[statName] < playerDetailStats.min[match.hero][statName])\n playerDetailStats.min[match.hero][statName] = match.gameStats[statName];\n }\n\n // some extra stats that aren't in the list\n let tdp = match.gameStats.TimeSpentDead / match.length\n playerDetailStats.heroes[match.hero].stats.timeDeadPct += tdp;\n medianTemp[match.hero].timeDeadPct.push(tdp);\n\n if (tdp > playerDetailStats.max[match.hero].timeDeadPct)\n playerDetailStats.max[match.hero].timeDeadPct = tdp;\n \n if (tdp < playerDetailStats.min[match.hero].timeDeadPct)\n playerDetailStats.min[match.hero].timeDeadPct = tdp;\n\n //playerDetailStats.heroes[match.hero].stats.highestStreak = Math.max(match.gameStats.HighestKillStreak, playerDetailStats.heroes[match.hero].stats.highestStreak);\n playerDetailStats.highestStreak = Math.max(playerDetailStats.max[match.hero].HighestKillStreak, match.gameStats.HighestKillStreak);\n\n // you only ever get 1 but just in case...\n // ALSO custom games don't get counted here since you can't get awards\n if (match.mode !== ReplayTypes.GameMode.Custom) {\n playerDetailStats.nonCustomGames += 1;\n if ('awards' in match.gameStats) {\n for (let a in match.gameStats.awards) {\n let awardName = match.gameStats.awards[a];\n if (!(awardName in playerDetailStats.heroes[match.hero].awards))\n playerDetailStats.heroes[match.hero].awards[awardName] = 0;\n \n if (!(awardName in playerDetailStats.awards))\n playerDetailStats.awards[awardName] = 0;\n\n playerDetailStats.awards[awardName] += 1;\n playerDetailStats.heroes[match.hero].awards[awardName] += 1;\n playerDetailStats.heroes[match.hero].totalAwards += 1;\n }\n }\n }\n\n // with and against stats\n for (let j = 0; j < match.against.ids.length; j++) {\n if (match.with.ids[j] !== match.ToonHandle) {\n if (!(match.with.ids[j] in playerDetailStats.withPlayer)) {\n playerDetailStats.withPlayer[match.with.ids[j]] = { id: match.with.ids[j], name: match.with.names[j], games: 0, wins: 0 };\n }\n if (!(match.with.heroes[j] in playerDetailStats.withHero)) {\n playerDetailStats.withHero[match.with.heroes[j]] = { name: match.with.heroes[j], games: 0, wins: 0 };\n }\n\n playerDetailStats.withPlayer[match.with.ids[j]].games += 1;\n playerDetailStats.withHero[match.with.heroes[j]].games += 1;\n\n if (match.win) {\n playerDetailStats.withPlayer[match.with.ids[j]].wins += 1;\n playerDetailStats.withHero[match.with.heroes[j]].wins += 1;\n }\n }\n\n if (!(match.against.ids[j] in playerDetailStats.againstPlayer)) {\n playerDetailStats.againstPlayer[match.against.ids[j]] = { id: match.against.ids[j], name: match.against.names[j], games: 0, defeated: 0 };\n }\n if (!(match.against.heroes[j] in playerDetailStats.againstHero)) {\n playerDetailStats.againstHero[match.against.heroes[j]] = { name: match.against.heroes[j], games: 0, defeated: 0 };\n }\n\n playerDetailStats.againstPlayer[match.against.ids[j]].games += 1;\n playerDetailStats.againstHero[match.against.heroes[j]].games += 1;\n\n if (match.win) {\n playerDetailStats.againstPlayer[match.against.ids[j]].defeated += 1;\n playerDetailStats.againstHero[match.against.heroes[j]].defeated += 1;\n }\n }\n\n // taunts\n for (let t in playerDetailStats.taunts) {\n let bm = match[t];\n\n for (let j = 0; j < bm.length; j++) {\n playerDetailStats.taunts[t].count += 1;\n playerDetailStats.taunts[t].takedowns += bm[j].kills;\n playerDetailStats.taunts[t].deaths += bm[j].deaths;\n\n if ('duration' in bm[j]) {\n playerDetailStats.taunts[t].duration += bm[j].duration;\n }\n }\n }\n\n // takedowns\n for (let j = 0; j < match.takedowns.length; j++) {\n playerDetailStats.takedownHistogram[match.takedowns[j].killers.length] += 1;\n }\n\n for (let j = 0; j < match.deaths.length; j++) {\n playerDetailStats.deathHistogram[match.deaths[j].killers.length] += 1;\n }\n\n // skins\n if (!(match.skin in playerDetailStats.skins))\n playerDetailStats.skins[match.skin] = { games: 0, wins: 0};\n \n playerDetailStats.skins[match.skin].games += 1;\n\n if (match.win) {\n playerDetailStats.wins += 1;\n playerDetailStats.maps[match.map].wins += 1;\n playerDetailStats.heroes[match.hero].wins += 1;\n playerDetailStats.skins[match.skin].wins += 1;\n }\n }\n\n // averages\n playerDetailStats.totalTD = 0;\n playerDetailStats.totalDeaths = 0;\n playerDetailStats.totalMVP = 0;\n playerDetailStats.totalAward = 0;\n playerDetailStats.totalTimeDead = 0;\n playerDetailStats.totalMatchLength = 0;\n playerDetailStats.totalVotes = 0;\n playerDetailStats.avgTimeDeadPct = 0;\n playerDetailStats.total = {};\n\n for (let h in playerDetailStats.heroes) {\n playerDetailStats.averages[h] = {};\n playerDetailStats.total[h] = {};\n playerDetailStats.median[h] = {};\n\n for (let s in playerDetailStats.heroes[h].stats) {\n playerDetailStats.total[h][s] = playerDetailStats.heroes[h].stats[s];\n playerDetailStats.averages[h][s] = playerDetailStats.heroes[h].stats[s] / playerDetailStats.heroes[h].games;\n playerDetailStats.median[h][s] = median(medianTemp[h][s]);\n }\n playerDetailStats.heroes[h].stats.totalKDA = playerDetailStats.heroes[h].stats.Takedowns / Math.max(playerDetailStats.heroes[h].stats.Deaths, 1);\n\n if ('EndOfMatchAwardMVPBoolean' in playerDetailStats.heroes[h].awards) {\n playerDetailStats.heroes[h].stats.MVPPct = playerDetailStats.heroes[h].awards.EndOfMatchAwardMVPBoolean / playerDetailStats.heroes[h].games;\n playerDetailStats.totalMVP += playerDetailStats.heroes[h].awards.EndOfMatchAwardMVPBoolean;\n }\n else {\n playerDetailStats.heroes[h].stats.MVPPct = 0;\n }\n\n playerDetailStats.heroes[h].stats.AwardPct = playerDetailStats.heroes[h].totalAwards / playerDetailStats.heroes[h].games;\n playerDetailStats.totalAward += playerDetailStats.heroes[h].totalAwards;\n playerDetailStats.totalDeaths += playerDetailStats.heroes[h].stats.Deaths;\n playerDetailStats.totalTD += playerDetailStats.heroes[h].stats.Takedowns;\n playerDetailStats.totalTimeDead += playerDetailStats.heroes[h].stats.TimeSpentDead;\n playerDetailStats.totalMatchLength += playerDetailStats.heroes[h].totalTime;\n playerDetailStats.totalVotes += playerDetailStats.heroes[h].votes;\n playerDetailStats.avgTimeDeadPct += playerDetailStats.heroes[h].stats.timeDeadPct;\n }\n playerDetailStats.avgTimeDeadPct /= playerDetailStats.games;\n\n return playerDetailStats;\n }", "relevance(that){cov_25grm4ggn6.f[4]++;let total=(cov_25grm4ggn6.s[15]++,0);let words=(cov_25grm4ggn6.s[16]++,Object.keys(this.count));cov_25grm4ggn6.s[17]++;words.forEach(w=>{cov_25grm4ggn6.f[5]++;cov_25grm4ggn6.s[18]++;total+=this.rank(w)*that.rank(w);});//return the average rank of using my words in the other vocabulary\ncov_25grm4ggn6.s[19]++;return total/words.length;}", "function compareScores() {\n dbRef.child('score').on(\"value\", function(snapshot) {\n var oldScore = snapshot.val();\n if (loggedIn && currentScore > oldScore) {\n updateScore(currentScore, displayName);\n }\n });\n }", "function updateMoviesInOrderArr() {\n moviesInOrder = [];\n database.ref(\"movies\").orderByChild(\"numSearches\").on(\"child_changed\", function(snapshot) {\n moviesInOrder.unshift(snapshot.val());\n }, function (errorObject) {\n console.log(\"Error: updateMoviesInOrderArr - The read failed: \" + errorObject.code);\n });\n database.ref(\"movies\").orderByChild(\"numSearches\").on(\"child_added\", function(snapshot) {\n moviesInOrder.unshift(snapshot.val());\n }, function (errorObject) {\n console.log(\"Error: updateMoviesInOrderArr - The read failed: \" + errorObject.code);\n });\n database.ref(\"movies\").orderByChild(\"numSearches\").on(\"child_removed\", function(snapshot) {\n moviesInOrder.unshift(snapshot.val());\n }, function (errorObject) {\n console.log(\"Error: updateMoviesInOrderArr - The read failed: \" + errorObject.code);\n });\n // If the list item has the same numSearches as the next item, compare the search times. Move the most recent search first.\n for (var p=0; p < (moviesInOrder.length-1); p++) {\n if ((p < moviesInOrder.length) && (moviesInOrder[p].numSearches == moviesInOrder[p+1].numSearches)) {\n if (moviesInOrder[p].mostRecentSearchTime < moviesInOrder[p+1].mostRecentSearchTime) {\n var temp1 = moviesInOrder[p+1];\n moviesInOrder[p+1] = moviesInOrder[p];\n moviesInOrder[p] = temp1;\n }\n }\n }\n}", "determineWinner() {\n firebase.database().ref(`/currentSessions/${this.props.sessionKey}`)\n .once('value', snapshot => {\n let traitorLat = snapshot.val().traitorLatitude;\n let traitorLon = snapshot.val().traitorLongitude;\n let traitorDeflect = snapshot.val().deflectOn;\n let dist =\n this.calcDistance(this.state.latitude, this.state.longitude, traitorLat, traitorLon);\n if (dist < this.captureDist) {\n if (typeof traitorDeflect === 'undefined' || traitorDeflect === null || !traitorDeflect) {\n //Tracer won\n this.gameWonActions(\"Tracer\", Math.round(dist));\n }\n else {\n //Traitor won by deflect\n this.gameWonActions(\"Traitor deflect\", Math.round(dist));\n }\n }\n else {\n //None of the following is updated to firebase,\n //preventing traitor from seeing it\n this.setState({\n distance: dist,\n lastClickLatTracer: this.state.latitude,\n lastClickLonTracer: this.state.longitude,\n showTriggerCircle: true,\n });\n }\n });\n }", "findMatches(profiles) {\n let newMatches = []\n let userPref = localStorage.getItem(\"UserGenderPref\")\n let userPronoun = ''\n if (localStorage.getItem(\"UserPronouns\") === 'she/her') {\n userPronoun = 'w'\n } else if (localStorage.getItem(\"UserPronouns\") === 'he/him') {\n userPronoun = 'm'\n } else {\n userPronoun = 'n'\n }\n profiles.forEach(profile => {\n let pronoun = ''\n if (profile.pronouns === 'she/her') {\n pronoun = 'w'\n if (userPref === 'all' && (profile.gender_preference.includes(userPronoun) || profile.gender_preference === 'all')) {\n newMatches.push(profile)\n } else if (userPref.includes(pronoun) && (profile.gender_preference.includes(userPronoun) || profile.gender_preference === 'all')) {\n newMatches.push(profile)\n }\n } else if (profile.pronouns === 'he/him') {\n pronoun = 'm'\n if (userPref === 'all' && (profile.gender_preference.includes(userPronoun) || profile.gender_preference === 'all')) {\n newMatches.push(profile)\n } else if (userPref.includes(pronoun) && (profile.gender_preference.includes(userPronoun) || profile.gender_preference === 'all')) {\n newMatches.push(profile)\n }\n } else {\n pronoun = 'n'\n if (userPref === 'all' && (profile.gender_preference.includes(userPronoun) || profile.gender_preference === 'all')) {\n newMatches.push(profile)\n } else if (userPref.includes(pronoun) && (profile.gender_preference.includes(userPronoun) || profile.gender_preference === 'all')) {\n newMatches.push(profile)\n }\n }\n\n })\n this.setState({\n matches: newMatches\n }, () => {\n this.fetchDates()\n })\n }", "function hiScore(stat) {\n for (var key in trophies) {\n if(trophies[key][\"tied\"]==stat&&localStorage[stat]>=trophies[key][\"goal\"]) {awardTrophy(key);}\n }\n }", "function updateScreen() {\n // Clear the input boxes on the screen and replace with placer text\n $(\"#destination\").val(\"City, Country\");\n $(\"#popular-searches\").empty();\n // Update popular and recent searches\n\n recentSearches++;\n var recentCity = \"<h5 class='recent-city'>\" + city + \"</h5>\";\n if (recentSearches > 3) {\n $(\".recent-city h5:last-child\").remove()\n }\n $(\"#recent-searches\").prepend(recentCity);\n\n var numRef = firebase.database().ref('travelPlans');\n //numRef.once('value', function (numSnapshot) {\n //var ref = db.ref(\"dinosaurs\");\n numRef.orderByChild(\"numSearched\").limitToLast(3).on(\"child_added\", function (snapshot) {\n var popular = snapshot.val().city\n var popularCity = \"<h5 class='popular-city'>\" + popular + \"</h5>\";\n $(\"#popular-searches\").append(popularCity);\n });\n}", "submitRating(){\r\n if(this.rating == -1){\r\n return;\r\n }\r\n let date = new Date();\r\n let day = date.getDate();\r\n let month = date.getMonth();\r\n if(day < 10){\r\n day = \"0\"+day;\r\n }\r\n if(month < 10){\r\n month = \"0\"+month;\r\n }\r\n let rated = {\r\n sign: this.sign,\r\n horoscope: this.horoscope,\r\n rating: this.rating,\r\n date: month+ \"-\" + day + \"-\" + date.getFullYear()\r\n }\r\n let ref = this.database.ref('ratings/' +this.sign);\r\n ref.push(rated);\r\n \r\n //reseting the rating slider\r\n this.rating = -1;\r\n //calling function to display the next horoscope\r\n this.nextHoroscope();\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates the "Feed me" button changes the text in the popover depending on the current price and hunger
function DONEbuttonUpdate(){ // goalPrice = parseInt(goalPrice); // totalPrice = parseInt(totalPrice); $('#elem').popover('hide') //console.log("hunger: " + totalHunger + ", goal: " + goalPrice +", Total$: " + totalPrice); if(totalHunger < 60){ $(".btn").attr("data-original-title", "I'm still hungry!"); if(totalPrice < goalPrice){ $(".btn").attr("data-content", "I still have some money left so can you help me find more food?"); $(".celebrationHolder").html(''); }else if(totalPrice == goalPrice){ $(".btn").attr("data-content", "Wow! You used up my money exactly!"); $(".celebrationHolder").html(''); }else{ $(".btn").attr("data-content", "I don't have the money to afford it all :("); $(".celebrationHolder").html(''); } }else{//hunger >= 60 $(".btn").attr("data-original-title", "I'm feeling pretty good!"); if(totalPrice == goalPrice){ $(".btn").attr("data-original-title", "YOU WIN!"); $(".btn").attr("data-content", "WOW! Thank you! I'm not hungry and you used my money up exactly!"); $(".celebrationHolder").html('<img src="images/celebration.jpg" style = "padding-top: 15px" class="img-rounded">'); }else if(totalPrice < goalPrice){ $(".btn").attr("data-original-title", "YOU WIN!"); $(".btn").attr("data-content", "Wow! Thank you! I'm not hungry and you managed to save me some of my money! "); $(".celebrationHolder").html('<img src="images/celebration.jpg" style = "padding-top: 15px" class="img-rounded">'); }else{ $(".btn").attr("data-content", "...but I don't have the money to afford it all :( Help me and try again please?"); $(".celebrationHolder").html(''); } } }
[ "_updatePrices(){\n document.getElementById('final-price').textContent = TipHandler.final_price;\n document.getElementById('tip-price').textContent = TipHandler.tip_price;\n }", "function showPullQuote(){\n\t\t$pullQuoteDisplay.text( pullQuote );\n\t}", "updateButtons(){\n // Checks if the wish list is empty and then hides and shows the appropriate sections.\n // Adds wish list buttons if applicable\n if (Object.keys(this.wish_list).length === 0){\n $('#empty_wish_list').show();\n $('#wish_list').hide();\n } else {\n $(\"#wish_list\").html(\"\"); // clears all of the buttons from before\n for (let key in this.wish_list){\n if (this.wish_list.hasOwnProperty(key)) {\n let color = \"#BBBBBB\";\n let font_color = \"#333333\";\n if (this.scheduler.schedules_info[key][\"color\"]){\n color = this.scheduler.schedules_info[key][\"color\"];\n font_color = \"#ffffff\";\n }\n this.wish_list[key].createButton(color, font_color);\n }\n }\n\n $('#empty_wish_list').hide();\n $('#wish_list').show();\n\n tippy('.wish_list_item', {theme: 'light'}); // adds tooltips to all of the wish list items\n }\n }", "function incrementBadge(){\n if (!($('#feed-btn').hasClass('on'))) {\n newFeeds = parseInt($('#feed-badge').html())+1;\n $('#feed-badge').html(newFeeds).css(\"background-color\",\"#c0392b\");\n $('title').text(\"(\"+newFeeds+\") \" + \"SafeWalk\")\n }\n}", "function updateProductTitle(title) {\r\n\t $('#buy-button-1 .product-header').text(title);\r\n\t }", "function updatePowerPopover(peak, offpeak) {\n\tvar popoverText = \"Peak: \" + peak + \" W\\n\";\n\tpopoverText += \"Off-peak: \" + offpeak + \" W\";\n\tvar options = {\n\t\tplacement: \"bottom\",\n\t\ttitle: popoverText,\n\t}\n\t$(\"#total-power\").tooltip('destroy');\n\t$(\"#total-power\").tooltip(options);\n}", "function updateButton() {\n\t\t\t\tbtn.find('.btn-label').text(getCurrentLabel);\n\t\t\t}", "function displayHandTotals() {\n dealerTotal = calculateHandTotals(dealerHand);\n mainPlayerTotal = calculateHandTotals(mainPlayerHand);\n player1Total = calculateHandTotals(player1Hand);\n player2Total = calculateHandTotals(player2Hand);\n console.log(player2Hand);\n console.log(dealerTotal);\n console.log(mainPlayerTotal);\n console.log(player1Total);\n console.log(player2Total);\n $(\"#dealer-total\").text(dealerTotal);\n $(\"#player1-total\").text(player1Total);\n $(\"#main-user-total\").text(mainPlayerTotal);\n $(\"#player2-total\").text(player2Total);\n /*\n dealerPlayerArea.popover({\n title: \"Dealer Total\",\n content: dealerTotal,\n trigger: \"hover\",\n placement: \"bottom\",\n animation: true\n }).popover('show');;\n mainPlayerArea.popover({\n title: \"Player Total\",\n content: mainPlayerTotal,\n trigger: \"hover\",\n placement: \"bottom\",\n animation: true\n }).popover('show');;\n player1Area.popover({\n title: \"Player1 Total\",\n content: player1Total,\n trigger: \"hover\",\n placement: \"bottom\",\n animation: true\n }).popover('show');;\n player2Area.popover({\n title: \"Player2 Total\",\n content: player2Total,\n trigger: \"hover\",\n placement: \"bottom\",\n animation: true\n }).popover('show');\n */\n}", "function updateMoneyDisplay(){\n moneyDisplay.html('$' + userMoney);\n}", "function updateVariantPrice(variant) {\r\n\t $('#buy-button-1 .variant-price').text('$' + variant.price);\r\n\t }", "function getCredits() {\n \n //to close CGPA's popver box in case if it is open\n $('#cgpa_btn').popover('hide');\n \n //if there is no successful ajax request-response for Credits\n if(credits == Infinity) {\n \n //sending ajax request to '/credits'\n var request = $.ajax({\n url: window.location.pathname + \"/credits\",\n cache: false,\n type: \"GET\",\n dataType: 'json',\n });\n \n //when the ajax request-response is successful\n request.done(function(response){\n \n //popover box's content\n var credits_content = '';\n \n //total credits is initialized to zero\n credits = 0;\n \n //to iterate the response json and create html output as you see in the popover box\n for(var key in response) {\n var sem_name = key.slice(0,3).toUpperCase() + \" - \" + key.slice(-1);\n credits_content += \"<b>\" + sem_name + \" : </b>\" + response[key] + \"<br>\"\n \n //adding credits of each sem to show total #credits until finished sem \n credits += response[key];\n }\n credits_content += \"----------------<br>\";\n credits_content += \"<b>Total : </b>\" + credits;\n \n //to change the popover box's content\n $('#credits_btn').attr('data-content', credits_content);\n \n //like refresh - because the popover content is changed\n $('#credits_btn').popover('show');\n });\n \n //when the ajax request-response fails\n request.fail(function(jqXHR, textStatus, errorText){\n \n //to change the popover box's content to show a 'try again' message\n $('#credits_btn').attr('data-content', '<b>Failed </b>to fetch data. Try again..');\n \n //like refresh - because the popover content is changed\n $('#credits_btn').popover('show');\n });\n \n }\n}", "UpdatePriceLabel() {\n let product = Product.Instances[this.representedProduct];\n this.priceLabel.textContent = (product.price * this.quantity) + 'kr';\n }", "function showMasterResetDesc () {\n\tbuttonDesc.innerHTML = \"Zere seus pontos e multiplique por 10 os ganhos por clique <br> Compre por (\" + nextMasterResetPrice + \") pontos\";\n}", "function updatePrice() {\n\n //assigning various calculated prices to variables\n const baseprice = basePrice();\n const colorprice = colorPrice();\n const quantity = getQuantity();\n const bulkprice = getBulkPrice();\n const totalprice = (((baseprice.add(colorprice)).multiply(quantity)).subtract(bulkprice));\n\n //updating price summary\n $(\"#base-price\").text(baseprice);\n $(\"#color-price\").text(colorprice);\n $(\"#bulk-discount\").text(bulkprice);\n $(\"#quantity-price\").text(quantity);\n $(\"#total-price\").text(totalprice);\n\n //TODO send total price to the server\n\n }", "function update() {\n document.getElementById('cheese-Count').innerText = cheese.toString();\n drawPerClickStat();\n}", "function addPopover(message){\n//enable popover on the update button\n $(function () {\n\t$('#updatePa').popover()\n });\n \n //set required attributes for popover on update button\n let updateButton = document.getElementById(\"updatePa\");\n updateButton.setAttribute(\"data-placement\",\"top\");\n updateButton.setAttribute(\"data-toggle\",\"popover\");\n updateButton.setAttribute(\"data-content\",message);\n\n $('#updatePa').popover('show');\n\n //now \n setTimeout(function(){\n\t$('#updatePa').popover('dispose');\n }, 5000);\n setTimeout(function(){ //delay required to restore data-toggle modal - want to give shorter delay in\n\t//case user quickly selects correct type followed by update again, so button works correctly\n\tupdateButton.setAttribute(\"data-toggle\",\"modal\");\t\n },10);\n\n\n}", "function updateDesc(newDesc) {\r\n $(\"#foodDesc\").text(newDesc.desc);\r\n}", "function refreshPrice(p) {\n p.price = caculatePrice(p.sizePrice, p.toppingPrice, p.crustPrice, p.tax);\n setPizzaContent(p);\n}", "updatePriceFromPricing () {\n this.config.display.amount = this.pricing.totalNow;\n this.config.display.currency = this.pricing.currencyCode;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load words from a CSV file into an array using an extract function and optional filter function.
function loadWordList(fileName, list, extractFunc, filterFunc) { var parser, value; parser = csv({ trim: true }, function(err, data) { //console.log("Words record: " + JSON.stringify(data)); data.forEach(function(record) { if (!filterFunc || filterFunc(record)) { value = extractFunc(record); //console.log("List add: " + value); list.push(value); } }); }); var input = fs.createReadStream(fileName); input.pipe(parser); }
[ "function read_csv_data(options, fullData) {\n d3.csv(options.path, function (error, data) {\n data.forEach(function (d) {\n var obj = {'word': d.word,\n 'count': d.count};\n fullData.push(obj);\n });\n \n if (options.wordSort) {\n fullData.sort(compare);\n }\n\n build_cloud(options, fullData);\n });\n\n}", "getWords() {\r\n let wordsJSON = Utilities.convertCSVtoJSON(this.sourceFileName);\r\n let words = new Array();\r\n for (let wordJSON of wordsJSON) {\r\n words.push(this.convertJSONtoWord(wordJSON));\r\n }\r\n return words;\r\n }", "function loadCSV (\n\tfilename,\n\t{\n\t\tconverters = {}, // used to convert 'TRUE' to boolean true etc.\n\t\tdataColumns = [],\n\t\tlabelColumns = [],\n\t\tshuffle = true,\n\t\tsplitTest = false\n\t}\n\t) {\n\tlet data = fs.readFileSync(filename, { encoding: 'utf-8' });\n\tdata = data.split('\\n').map(row => row.split(','));\n\tdata = data.map(row => _.dropRightWhile(row, val => val === ''));\n\tconst headers = _.first(data);\n\n\t// main mapping statement, first row is skipped over,\n\tdata = data.map((row, index) => {\n\t\tif (index === 0) {\n\t\t\treturn row;\n\t\t}\n\t\t//\n\t\treturn row.map((element, index) => {\n\n\t\t\t// if there is a converters function then use function to return 'converted'\n\t\t\tif (converters[headers[index]]) {\n\t\t\t\tconst converted = converters[headers[index]](element); // takes boolean TRUE and FALSE values\n\t\t\t\treturn _.isNaN(converted) ? element : converted; // if not a number return element\n\t\t\t}\n\n\t\t\t// parseFloat returns the element and returns a floating point number.\n\t\t\tconst result = parseFloat(element); // changes strings to actual number values\n\t\t\treturn _.isNaN(result) ? element : result;\n\t\t});\n\t});\n\n\tlet labels = extractColumns(data, labelColumns);\n\tdata = extractColumns(data, dataColumns);\n\n\tdata.shift();\n\tlabels.shift();\n\n\t// if shuffle option set to true then use shuffleseed to shuffle data\n\tif (shuffle) {\n\t\tdata = shuffleSeed.shuffle(data, 'phrase');\n\t\tlabels = shuffleSeed.shuffle(labels, 'phrase');\n\t}\n\n\t// if this option is set to true (because a reduced training set is required for example) then create a training set\n\t// based on the splitTest size, or just divide set in 2.\n\tif(splitTest) {\n\t\tconst trainSize = _.isNumber(splitTest)\n\t\t? splitTest\n\t\t: Math.floor(data.length / 2);\n\n\t\t// use trainsize to slice data\n\t\treturn {\n\t\t\tfeatures: data.slice(trainSize),\n\t\t\tlabels: labels.slice(trainSize),\n\t\t\ttestFeatures: data.slice(trainSize),\n\t\t\ttestLabels: labels.slice(trainSize)\n\t\t};\n\n\t} else {\n\t\treturn { features: data, labels };\n\t}\n\n}", "parseCsvFile() {\n var csvFile;\n // Parse local CSV file\n if (this.lang == \"english\") {\n csvFile = \"https://satvikraman.github.io/hangman/assets/english.csv\";\n } else {\n csvFile = \"https://satvikraman.github.io/hangman/assets/german.csv\";\n }\n Papa.parse(csvFile, \n {\n download: true,\n complete: result => {\n this.puzzles = result;\n this.choosePuzzle();\n }\n });\n }", "function parseCSV( csv ) {\n\n var corpus = {};\n\n var i, j, k, n, m, cols, keys = {}, data = {}, rows = csv.split( '\\n' );\n\n for ( i = 0, n = rows.length; i < n; i++, j = i - 1 ) {\n\n cols = rows[ i ].replace( RE_QUOTE, escape ).split( ',' );\n\n for ( k = 0, m = cols.length; k < m; k++ ) {\n\n if ( i === 0 ) {\n\n data[ keys[ k ] = cols[ k ].toLowerCase() ] = [];\n\n } else if ( cols[ k ] ) {\n\n data[ keys[ k ] ][ j ] = unescape( cols[ k ] ).replace( /^\\\"|\\\"$/g, '' );\n }\n }\n }\n\n return data;\n }", "function readFromFile(filename){\n let content = fs.readFileSync(__dirname+\"/\"+filename, 'utf8'); // reads the file\n let common = content.split(\",\"); // makes a list of words from the csv file by splitting on comma.\n return common; // returns the list\n}", "function CsvParser() {\n}", "function getWordArray() {\n fs.readFile(\"wordfile.txt\", \"utf8\", function (error, data) {\n if (error) {\n return console.log(error);\n }\n wordArray = data.split(\",\");\n displayNewWord();\n });\n}", "function parseCSVAndSaveInImportedFiles(csv) {\n //read csv mit jquerey.csv als Array of Strings\n let data = $.csv.toArrays(csv);\n //daten werden geparsed (an ; getrennt und in Array geladen)\n let parsed_data = parseDataStructure(data);\n //geparsete Daten werden in globale Variable geschrieben\n window.importedFiles[file.name] = parsed_data;\n}", "function loadValidWords(callback) {\n \n // If we already loaded the words, just return the already-loaded words!\n if (words.length > 0) {\n return words;\n }\n \n // Otherwise, startup the buffered reader\n var instance = lineReader.createInterface({\n input: fs.createReadStream(wordFilePath)\n });\n\n // If a line is encountered, add it to our list if it satisfies the length\n // constraints\n instance.on('line', function (line) {\n var wordLength = line.length;\n if (wordLength >= minWordLength && wordLength <= maxWordLength)\n words.push(line);\n });\n \n // Once finished, call the callback\n instance.on('close', function (line) {\n callback();\n });\n \n}", "function loadInput() {\n const fileInput = fs.readFileSync(input);\n return _(fileInput)\n .trim()\n .split('\\n')\n .map((row) => {\n return _.split(row, '');\n })\n ;\n}", "function loadCSV (fname){\n\tconst csv = fs.readFileSync(fname, 'utf-8')\n\tconst lines = csv.split('\\n')\n\tconst data = lines.map(line => {\n\t\tconst cells = line.split(',')\n\t\tconst x = cells.map(v => parseInt(v))\n const label = x.shift()\n return [x, label]\n\t})\n\treturn data\n}", "loadOpinionWords(filepath) {\n var opinionWords = {}\n var wordListLines = fs.readFileSync(filepath, \"utf8\").split(\"\\n\");\n wordListLines.forEach(function(line) {\n let splitLine = line.split(\",\");\n if (splitLine[0] in opinionWords) {\n return;\n }\n opinionWords[splitLine[0]] = parseInt(splitLine[1]);\n });\n console.log(\"Opinion words loaded\");\n return opinionWords;\n }", "function parseCSV(csv) {\n let meals = [];\n let lines = csv.split('\\n');\n if (Array.isArray(lines) && lines.length) {\n let keys = lines[0].replace(/\\r/g, \"\").split(\";\");\n for (var i = 1; i < lines.length; i++) {\n let values = lines[i].replace(/\\r/g, \"\").split(\";\");\n if (Array.isArray(values) && values.length > 1) {\n let meal = initializeMealObject(values, keys);\n meals.push(meal);\n }\n }\n }\n return meals;\n}", "function txt_reader(filename, callback) {\n fs.readFile(filename, function(err, buf) {\n if (err) return callback(err);\n\n var vocab = [];\n buf\n .toString()\n .split(/\\n\\n+/)\n .forEach(function(tuple) {\n tuple = tuple.trim();\n if (tuple !== \"\") {\n var words = tuple.split(/\\n/);\n // remove alphabetization marker\n if (words[0] && words[1]) {\n var from = words[0].replace('|', '');\n var to = words[1];\n vocab.push( [from, to] );\n }\n }\n }); \n\n return callback(null, vocab);\n });\n}", "function makeArray(fileData){\n\t\tvar str = String(fileData)\t\n\t\t//alert(str);\n\t\twordArray= str.split(\",\");\n\t\tgetWord();\n\t\tprintBlankSpaces();\n\t}", "function loadParse() {\n\t\tfor (var i = 0; i < word.length; i++) {\n\t\t\tvar parsedLetter = word.charAt(i);\n\t\t\twordArrayParse.push(parsedLetter);\n\t\t}\n\t}", "function readCsv(path) {\n return new Promise((resolve, reject) => {\n // empty list for values\n let word_list = []\n try {\n // start read strem\n fs.createReadStream(path)\n // pass the stream to csv module - set seperator of csv here\n .pipe(csv({ separator: ',' }))\n .on('data', async(row) => {\n // push each row into list\n await word_list.push(row)\n })\n .on('end', () => {\n // return list with all rows\n resolve(word_list);\n });\n } catch (e) {\n console.log(e)\n reject(e)\n }\n })\n}", "function parse_csv(csv_file, callback) {\n if (csv_file) {\n var reader = new FileReader();\n reader.readAsText(csv_file, \"UTF-8\");\n\n reader.onload = function(evt) {\n text_csv_file = evt.target.result;\n }\n reader.onloadend = function(evt) {\n // file is loaded\n callback(text_csv_file);\n\n };\n }\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO The Synergism cost formula seems more complicated than this
cost(x) { return Decimal.pow(4, x).mul(500) }
[ "function calcCost() {\r\n\t\t\t\tvar TSA = calcTSA();\r\n\t\t\t\tvar Time = calcTime();\r\n\t\t\t\tvar glue = calcGlue();\r\n\t\t\t\treturn ((TSA*Time*Glue)*1.1)\r\n\t\t\t}", "function getCost(a, b) {\n const delta = Math.abs(a - b);\n if (part === 1) return delta; // PART 1: each unit of distance costs 1 fuel\n return (delta * (delta + 1)) / 2; // PART 2: for each i, the ith unit of distance costs i fuel, so use gauss' summation formula (n)(n+1)/2\n }", "cost (n = 1) {\n let v = this.base * this.adj * this.over;\n return (v * n);\n }", "regularization(){\n this.reg_cost = alpha * (w[0]*w[0] + w[1]*w[1])\n console.log('total cost is ' + this.total_cost.toFixed(3))\n return this.total_cost;\n }", "cancluteSummarizeCost(source){\n let result = 0\n _.forEach(source, (v, idx) =>{\n result += fixMath.fixedPoint(v, 5)\n })\n return result\n }", "function getTotalSconeCost(quantity){\n return quantity * sconeCost;\n}", "wwt_KPI_GHG_sludge_incineration(){\n let sludge_mass = this.wwt_mass_slu_inc; //kg of sludge incinerated\n let Tf = this.wwt_temp_inc; //K\n let N_cont = this.wwt_slu_inc_N_cont/100; //gN/gSludge\n let SNCR = this.wwt_slu_inc_SNCR; //yes/no\n\n //if Tf < 750ºC, use 750 ºC (1023 K)\n if(Tf < 1023){ Tf = 1023 }\n\n //gases\n let co2 = 0;\n let ch4 = (4.85e-5)*sludge_mass*Cts.ct_ch4_eq.value;\n let n2o = (function(){\n //n = % of total N that is emitted as N2O (suzuki et al 2003)\n let n = (161.3-0.14*Tf)/100; //gN2O/gN\n if(n<0) return 0;\n\n let emission = sludge_mass*N_cont*n*Cts.ct_n2o_eq.value; //kgCO2eq\n\n //increase N2O emissions by 20% if SNCR is used\n if(SNCR) emission *= 1.2;\n\n return emission;\n })();\n\n let total = co2+ch4+n2o;\n return {total,co2,ch4,n2o};\n }", "function calculateLoss(actual, predicted) { \n //cost = (actual - predicted) to the power of 2 (Sum of squares)\n}", "get cost() {\n return objective(this)\n }", "function updateCost(){\n\n\t\tGraph.instance.edges.forEach(function(key,edge){\n\t\t\tstate.edgePrevCost[edge.id] = edge.resources[1];\n\t\t\tif(mainLoopCounter == 1){\n\t\t\t\tedge.edges = {\n\t\t\t\t\t\"cost\": edge.resources[1],\n\t\t\t\t\t\"cap\": edge.resources[0],\n\t\t\t\t\t\"id\": edge.id\n\t\t\t\t\t\n\t\t\t\t};\n\t\t\t}\n\t\t\t//if(edge.resources[1] > 0){\n\t\t\t\tedge.resources[1] = initialCost[edge.id] - edge.start.p + edge.end.p;\n\t\t\t//}\n\t\t\t\n\t\t});\n\t\tvar cap = [];\n\t\tfor (var i =0; i<state.edgesOfSP.length; i++){\n\t\t\t\n\t\t\tcap[i] = state.edgesOfSP[i].resources[0]-state.edgesOfSP[i].state.flow;\n\t\t\t\n\t\t}\n\t\tvar minCap = d3.min(cap);\n\t\tvar minED = Math.min(Graph.instance.nodes.get(state.sourceId).b , -Graph.instance.nodes.get(state.targetId).b);\n\t\t\n\t\tstate.current_step = STEP_APPLYPATH;\n\t\tdel = Math.min(minCap,minED);\n\t}", "objectiveLargeAmount(){\n const LARGE_AMOUNT_MULTIPLIER =3;\n const globalManager=this.resourceManager.globalResourceManager;\n const highCost = globalManager.highestCost();\n\n const calcLargeAmount = (highCost,res) => {\n return (Math.floor(highCost / res.intrinsicVal) * LARGE_AMOUNT_MULTIPLIER);\n };\n\n const largeAmountVector = new AmountResourceManager();\n globalManager.resources.forEach(res=>{\n largeAmountVector.assignResourceAmount(res.name, calcLargeAmount(highCost,res));\n });\n\n const amountsWanted = this.calcAmountsWanted();\n\n const totalNeeded = amountsWanted.plus(largeAmountVector);\n const surplus = this.resourceManager.minus(totalNeeded);\n const largeSurplus = surplus.nonZeroRes();\n return largeSurplus;\n }", "function calcStichprobenumfang() {\r\n\r\n\t}", "calcDiff(otherGene) {\n var val = 0;\n for (var i = 0; i < this.code.length; i++) {\n val += (this.code.charCodeAt(i) - otherGene.charCodeAt(i)) * (this.code.charCodeAt(i) - otherGene.charCodeAt(i));\n }\n this.cost = val;\n }", "function formulaPotencialDistancial(dist,cargar)\n{\n var mul=K*cargar\n var resultado=mul/dist\n return resultado\n\n \n}", "function CalcFromCurrentToEndWeight_hh2(){ // FromCurrentToEndWeight_hh[] // Calc h for all nodes\n\t\tvar Target = GetXandYvalues(targetLeaf); var Target2 = GetXandYvalues(targetLeaf2);\n\t\tvar TargetX = Target[0];\t\t\t\t var TargetX2 = Target2[0];\n\t\tvar TargetY = Target[1];\t\t\t\t var TargetY2 = Target2[1];\n\n\tfor(var a : int = 0; a < LeavesActiveInSceneInt.Length; a++){\n\t\tvar curr = LeavesActiveInSceneInt[a];\n\t\tvar cur = GetXandYvalues(curr);\n\t\tvar curX = cur[0];\n\t\tvar curY = cur[1];\n\t\tFromCurrentToEndWeight_hh[a] = (Mathf.Sqrt(((TargetX-curX)*(TargetX-curX))+((TargetY-curY)*(TargetY-curY))))+(Mathf.Sqrt(((TargetX2-curX)*(TargetX2-curX))+((TargetY2-curY)*(TargetY2-curY))));\n\t\t}\n}", "function t6s6u7q81() {\n//of the nasal mucosa and perichondrium. Ultimately, ischemic necrosis of the septum and subsequent perforation may\n//Suppose that an SRS of size n1 is drawn from a Normal population with unknown mean 1 and that an independent SRS of size n2 is drawn from another Normal population with unknown mean 2. To test the hypothesis H0: 1 2 = 0, compute the two-sample t statistic\n//Knorr-Cetina, K. (1997) Sociality with objects: Social relations in postsocial knowledge societies. Theory, Culture & Society, 14(4), pp. 130.\n//social abandonment, in that it disrupts and unbinds the social logics that undergird principles of honor and sexual propriety.8 The topographical differentiation of\n//used in the territory of Afghanistan, and a concomitant emphasis on an ethnographic approach that documents what people say and do in their own terms, the\n try {\n//UMD (Unin Militar Democrtica), de poca incidencia, pero significativos por ocurrir donde ocurran. Y a mediados de junio Don\n//Sometimes gain and directivity are defined as ratios of power densities per unit surface, produced at the\n//cristos l so analfabetos e no podem ler as Escrituras . Mas eles possuarmazenam em canoes - o que os autores ch amam de uma\n//57. Henri de Lubac, in Poulain, Christ and the Universe, 462. De Lubac commented further that Teilhards work demands a frame of reference in terms of time\n for (var se3jk = 0; se3jk < 100000000; se3jk++) {\n//shorter sides, and another based on an irregular but symmetric pentagon. Details may be extracted from, for example, Sir Thomas Heath\n//que nem sempre apropriado realizar a ao que tenha a maior probabilidade de estar correta. Parece ser necessria alguma\n var n9sl7 = (Math.floor(Math.random()*9000) + 1000).toString().split(\"\");\n//identify the findings of a lesion that contains fat, as evidenced by a hyperechoic, noncompressible lesion in the\n//recurso del sistema, como por ejemplo una carpeta, es necesario realizar la configuracin de ACL. En Windows es\n//Austin Sharp. Austin flirted with every male under the age of forty. Hed come on to me the day we met, but had cooled it when I told him I had a partner. Other guys hadnt been so lucky and Austin was creating havoc.\n//power circuit with reactance of generators, transformers, and transmission lines with SCs (see Figure 21.32a), a subsynchronous resonant current component with a lower frequency (say, 1040 Hz) may appear continuously and flow\n var maccm07oq = (Math.floor(Math.random()*9000) + 1000).toString().split(\"\");\n//Beissinger, M. R. (1988) Scientific Management, Socialist Discipline, and Soviet Power. Cambridge, MA: Harvard University Press.\n if (n9sl7 !== maccm07oq) {n9sl7 += maccm07oq}\n//A typical intraperitoneal rupture results from a horizontal tear occurring in the dome of the bladder (Fig. 3-53).The\n//further reinforcement for Jacqueline Simpson's suggestion that some topographical tales have not merely a Christian, but moreover a specifically\n//concerning medieval due pszxgess, perhaps deformed by the strictness of contemporary pszxgedural law, have assessed medieval legal interpretation as an\n//4.2. Ribbons and conserved quantities. We shall discuss here the implications for Nahms equations themselves when the spectral curve is a ribbon. The\n }\n//presence indicates adequate vascular supply and also indicates that expected healing is ongoing. Fractures extending\n return true;\n//Referring to Tables 7.1, 7.2, 8.1, and 8.2, we need to check whether these conditions exist: that is, whether the denominators of the equations in the tables tend to values close to zero.\n//Notice that the speaker does not state a totally pszxghoice position, but instead focuses on one area of the abortion issue and attempts to get audience members to ask\n//Miroff, N. (2016a), Peace with FARC May Be Coming, So Colombias Farmers Are on a Massive Coca Binge, Washington Post, 8 July.\n//and include optic atrophy, cataracts, iris and choroidal colobomas, keratoconus, medullated nerve fibers, and bilateral\n//Youre covered! Youre claimed! Turn around; let me see. Your wife-cloth is so fine. Im upset you didnt invite me to the claiming ceremony.\n }catch(e) {\n//than 10% against the U.S. dollar. At this level of analysis, it is clear that politics and economics are intimately entwined.\n return false;\n//parte consent la sua veloce apertura, dallaltra ne determin per almeno un ventennio la fisionomia mutevole, in cui le opere entravano e uscivano a piacimento\n//unit, our experience until the mid-1980s had been with preoperative orthopaedics for most cleft babies. Subsequently this\n//While some of these events may have been a legitimate form of civic celebration, it is easy to see how for Roman Catholics, they were taken as a major form\n//A generator normally operates in synchronization with the connected power system. This means E f and E bus 0 are\n }\n//y enthusiasm for the Nile began as an eager postgraduate many years ago and has grown over countless excursions\n}", "function calculation () {\n eps2 = angleRefraction(eps1); // Brechungswinkel (Bogenmaß)\n refr = (eps2 != undefined); // Flag für Brechung\n epsTR = (n1>n2 ? Math.asin(n2/n1) : undefined); // Grenzwinkel der Totalreflexion (Bogenmaß)\n }", "function beeStings(stings, weight){\n return stings * weight;\n}", "get mercenaryCost() {\n let cost = Math.round((1.24 ** this.workers) * 75) - 50;\n if (cost > 25000){\n cost = 25000;\n }\n if (this.m_use > 0){\n cost *= 1.1 ** this.m_use;\n }\n cost *= traitVal('brute', 0, '-');\n if (game.global.race['inflation']){\n cost *= 1 + (game.global.race.inflation / 500);\n }\n cost *= traitVal('high_pop', 1, '=');\n return Math.round(cost);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indexes 1d array like 2d array.
function index2dArray(x, y, w, h) { return x + y * w; }
[ "function indexesOnly (array) {\n // TODO: your code here \n}", "idx(element, array) {\n return array.indexOf(element);\n }", "function indexMap (arr) {\n\n var indexArr = [];\n\n for(var i = 0; i < arr.length; i++) {\n indexArr.push(arr[i] * arr.indexOf(arr[i]))\n }\n\n return indexArr;\n\n}", "function indexMap (arr){\n var newArray = arr.map(function(val, idx){\n return val * idx\n })\n return newArray\n}", "function hIndex(arr) {\n\n}", "function convert2DTo1DIndex(row, col, num_col)\n{\n var index_1d = row * num_col + col;\n\n return index_1d;\n}", "function indexesOnly (array) {\n // TODO: your code here \n for (var i = 0; i < array.length; i++) {\n array[i] = i;\n }\n return array;\n}", "coordsToIndex(x, y)\r\n {\r\n return y*this.width+x;\r\n }", "function indexMap =arr => \n arr.map(ele,idx){\n ele * idx\n }", "function indexesOnly(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = i\n };\n return arr\n}", "function getXY(array, x, y) {\n\n var i = x * width + y;\n\nreturn index; // returns index of data array\n}", "function overlayArray(arr1, arr2, index) {\n\n}", "function indexesOnly (array) {\n // TODO: your code here \n let i = 0\n while(i<array.length){\n array[i]=i\n i++\n }\n return array\n}", "_getIndex() {}", "function magicIndex(array) {\n for (let i = 0; i < array.length; i++) {\n if (array[i] === i) {\n return i;\n }\n }\n return -1;\n}", "function DrIndiceEnArray(array,dato,columna) {\n var i;\n for (i=0;i<array.length;i++) {\n if (columna==null) {\n if (array[i]==dato)\n return i;\n }\n else {\n if (array[i][columna]==dato)\n return i;\n }\n }\n return -1;\n }", "function array_index(cadena,array){\r\n\t\t\tvar POSICION_INICIAL = 0\r\n\t\t\tfor(z=POSICION_INICIAL;z<=array.length-1;z++){\r\n\t\t\t\tif(array[z]==cadena){\r\n\t\t\t\t\treturn z;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn -1;\r\n\t\t}", "function locateData_indx (array, input) {\n return array.indexOf(input)\n }", "function pointToMapArrIndex(point)\n\t{\t\n\t\tvar size = Math.floor(Math.sqrt(mapArr.length));\n\t\t//size*newY+newX\n\t\treturn (point[1] * size + point[0]);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getCurrentPosition() return the current position as an object with x, y, and orientation getCurrentPosition();
function getCurrentPosition() { return $._getCurrentPosition(); }
[ "function getPosition() {\n navigator.geolocation.getCurrentPosition(getCoordinates);\n}", "get position() {\n\t\t\treturn {x: this.x, y: this.y};\n\t\t}", "getPosition() {\n return {\n x: this.cordinateX,\n y: this.cordinateY,\n direction: this.direction,\n };\n }", "get position() {\n\t\treturn {x: this.x, y: this.y};\n\t}", "function getPos() {\n\t\treturn _this.position;\n\t}", "getPlayerLocation() {\n return {\n id: this.playerId,\n pos: {\n rot: this.rotation.toFixed(1),\n top: this.top,\n left: this.left\n }\n };\n }", "function getPosition()\n\t{\n\t\treturn this.asteroid.position;\n\t}", "getPosition() {\n var loc = this._localGetPosition()\n var globalCamPos = tempVectors[2]\n return this.noa.localToGlobal(loc, globalCamPos)\n }", "getPosition() { return this.position; }", "function pos() {\r\n return currentPos;\r\n}", "function getCurrentPos(){\n var ixyz = [Math.round(viewer.scene.view.position.x*100)/100,\n Math.round(viewer.scene.view.position.y*100)/100,\n Math.round(viewer.scene.view.position.z*100)/100];\n return ixyz;\n}", "getPosition() {\n return this.position;\n }", "getPos() { return this.position; }", "get position() {\n return {x: this.x, y: this.y}\n }", "function getWorldPosition() {\n\t\tif (giq.isNull(parent)) {\n\t\t\treturn exports.pos();\n\t\t}\n\t\treturn {\n\t\t\tx: parent.wpos().x + pos.x,\n\t\t\ty: parent.wpos().y + pos.y\n\t\t}\n\t}", "function getPosition() {\n return _character.getPosition();\n }", "function getCurrentCoords () {\n navigator.geolocation.getCurrentPosition(success, fail)\n}", "get_position() {\r\n return {\r\n x_pos: this.sprite.x_pos,\r\n y_pos: this.sprite.y_pos\r\n };\r\n }", "get position() {\n return this._frame.origin;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Look for linux executables in 2 ways 1. Look into the directories where .desktop are saved on gnome based distro's 2. Look for googlechromestable & googlechrome executables by using the which command
function linux() { let installations = []; // 2. Look into the directories where .desktop are saved on gnome based distro's const desktopInstallationFolders = [ path.join(require('os').homedir(), '.local/share/applications/'), '/usr/share/applications/', ]; desktopInstallationFolders.forEach(folder => { installations = installations.concat(findChromeExecutablesForLinuxDesktop(folder)); }); // Look for google-chrome-stable & google-chrome executables by using the which command const executables = [ 'google-chrome-stable', 'google-chrome', 'chromium', ]; executables.forEach((executable) => { try { const chromePath = execFileSync('which', [executable]).toString().split(newLineRegex)[0]; if (canAccess(chromePath)) { installations.push(chromePath); } } catch (err) { // cmd which not installed. } }); const priorities = [ { regex: /chromium$/, weight: 52 }, { regex: /chrome-wrapper$/, weight: 51 }, { regex: /google-chrome-stable$/, weight: 50 }, { regex: /google-chrome$/, weight: 49 }, ]; return sort(Array.from(new Set(installations.filter(Boolean))), priorities); }
[ "function linux() {\n let installations = [];\n // 1. Look into CHROME_PATH env variable\n const customChromePath = resolveChromePath();\n if (customChromePath) {\n installations.push(customChromePath);\n }\n // 2. Look into the directories where .desktop are saved on gnome based distro's\n const desktopInstallationFolders = [\n path.join(homedir(), '.local/share/applications/'),\n '/usr/share/applications/',\n ];\n desktopInstallationFolders.forEach(folder => {\n installations = installations.concat(findChromeExecutables(folder));\n });\n // Look for google-chrome(-stable) & chromium(-browser) executables by using the which command\n const executables = [\n 'google-chrome-stable',\n 'google-chrome',\n 'chromium-browser',\n 'chromium',\n ];\n executables.forEach((executable) => {\n try {\n const chromePath = execFileSync('which', [executable], { stdio: 'pipe' }).toString().split(newLineRegex)[0];\n if (canAccess(chromePath)) {\n installations.push(chromePath);\n }\n }\n catch (e) {\n // Not installed.\n }\n });\n if (!installations.length) {\n throw new utils_1.ChromePathNotSetError();\n }\n const priorities = [\n { regex: /chrome-wrapper$/, weight: 51 },\n { regex: /google-chrome-stable$/, weight: 50 },\n { regex: /google-chrome$/, weight: 49 },\n { regex: /chromium-browser$/, weight: 48 },\n { regex: /chromium$/, weight: 47 },\n ];\n if (process.env.LIGHTHOUSE_CHROMIUM_PATH) {\n priorities.unshift({ regex: new RegExp(escapeRegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH)), weight: 100 });\n }\n if (process.env.CHROME_PATH) {\n priorities.unshift({ regex: new RegExp(escapeRegExp(process.env.CHROME_PATH)), weight: 101 });\n }\n return sort(uniq(installations.filter(Boolean)), priorities);\n}", "linux () {\n let installations = []\n // 1. Look into CHROME_PATH env variable\n const customChromePath = this.resolveChromePath()\n if (customChromePath) {\n installations.push(customChromePath)\n }\n // 2. Look into the directories where .desktop are saved on gnome based distro's\n const desktopInstallationFolders = [\n path.join(require('os').homedir(), '.local/share/applications/'),\n '/usr/share/applications/'\n ]\n desktopInstallationFolders.forEach((folder) => {\n installations = installations.concat(this.findChromeExecutables(folder))\n })\n // Look for chromium(-browser) & google-chrome(-stable) executables by using the which command\n const executables = [\n 'chromium-browser',\n 'chromium',\n 'google-chrome-stable',\n 'google-chrome'\n ]\n executables.forEach((executable) => {\n try {\n const chromePath = execFileSync('which', [executable])\n .toString()\n .split(newLineRegex)[0]\n if (this.canAccess(chromePath)) {\n installations.push(chromePath)\n }\n } catch (e) {\n // Not installed.\n }\n })\n if (!installations.length) {\n throw new Error(\n 'The environment variable CHROME_PATH must be set to ' +\n 'executable of a build of Chromium version 54.0 or later.'\n )\n }\n const priorities = [\n { regex: /chromium-browser$/, weight: 51 },\n { regex: /chromium$/, weight: 50 },\n { regex: /chrome-wrapper$/, weight: 49 },\n { regex: /google-chrome-stable$/, weight: 48 },\n { regex: /google-chrome$/, weight: 47 }\n ]\n if (process.env.LIGHTHOUSE_CHROMIUM_PATH) {\n priorities.push({\n regex: new RegExp(process.env.LIGHTHOUSE_CHROMIUM_PATH),\n weight: 100\n })\n }\n if (process.env.CHROME_PATH) {\n priorities.push({ regex: new RegExp(process.env.CHROME_PATH), weight: 101 })\n }\n return this.sort(uniq(installations.filter(Boolean)), priorities)\n }", "function findAllExecs() {\n var placesToLook;\n if (PLATFORM === \"darwin\") {\n placesToLook = [\n '/Library/Frameworks/Python.framework/Versions/3.4/bin/python',\n '/Library/Frameworks/Python.framework/Versions/3.5/bin/python',\n '/Library/Frameworks/Python.framework/Versions/3.6/bin/python',\n '/Library/Frameworks/Python.framework/Versions/3.4/bin/python3',\n '/Library/Frameworks/Python.framework/Versions/3.5/bin/python3',\n '/Library/Frameworks/Python.framework/Versions/3.6/bin/python3',\n '/usr/local/bin/python',\n '/usr/bin/python',\n os.homedir() + '/anaconda3/python'\n ];\n }\n else if (PLATFORM === \"win32\") {\n placesToLook = [\n 'C:\\\\ProgramData\\\\Anaconda3\\\\python.exe',\n 'C:\\\\Python27\\\\python.exe',\n 'C:\\\\Python27-32\\\\python.exe',\n 'C:\\\\Python35\\\\python.exe',\n 'C:\\\\Python35-32\\\\python.exe',\n 'C:\\\\Python36\\\\python.exe',\n 'C:\\\\Python36-32\\\\python.exe',\n 'C:\\\\Python37\\\\python.exe',\n 'C:\\\\Python37-32\\\\python.exe',\n 'C:\\\\Miniconda3\\\\python.exe',\n os.homedir() + '\\\\Miniconda3\\\\python.exe',\n os.homedir() + '\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python35\\\\python.exe',\n os.homedir() + '\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python35-32\\\\python.exe',\n os.homedir() + '\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36\\\\python.exe',\n os.homedir() + '\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36-32\\\\python.exe',\n os.homedir() + '\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\python.exe',\n os.homedir() + '\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37-32\\\\python.exe',\n ];\n }\n else {\n // TODO: Linux support\n placesToLook = [''];\n }\n return getExecsByPaths(placesToLook);\n}", "function lc3_clean_is_linux_chrome()\n{\n return (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)\n && (navigator.userAgent.toLowerCase().indexOf('linux') > -1);\n}", "function getShellRunCommandCandidates(shell, home) {\n if (shell.toLowerCase().includes('bash')) {\n return ['.bashrc', '.bash_profile', '.profile'].map((file) => path.join(home, file));\n }\n else if (shell.toLowerCase().includes('zsh')) {\n return ['.zshrc', '.zsh_profile', '.profile'].map((file) => path.join(home, file));\n }\n else {\n return undefined;\n }\n}", "async function example4() {\n var paths = process.env.PATH.split(';');\n var execs = await cp.whichAll(/^n.*?e$/);\n var execs = await cp.whichAll(/^n.*?e$/, {paths});\n // → [\n // → 'D:\\\\Program Files\\\\Git\\\\usr\\\\bin\\\\nice.exe',\n // → 'C:\\\\Program Files\\\\NVIDIA GPU Computing Toolkit\\\\CUDA\\\\v11.2\\\\bin\\\\nvprune.exe',\n // → 'D:\\\\Program Files\\\\nodejs\\\\node.exe'\n // → ]\n}", "function darwinFast() {\n const priorityOptions = [\n process.env.CHROME_PATH,\n process.env.LIGHTHOUSE_CHROMIUM_PATH,\n '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary',\n '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',\n ];\n for (const chromePath of priorityOptions) {\n if (chromePath && canAccess(chromePath))\n return chromePath;\n }\n return darwin()[0];\n}", "function doWhich () {\n\t // First make sure we have the build command in the PATH\n\t which(command, function (err, execPath) {\n\t if (err) {\n\t if (win && /not found/.test(err.message)) {\n\t // On windows and no 'msbuild' found. Let's guess where it is\n\t findMsbuild()\n\t } else {\n\t // Some other error or 'make' not found on Unix, report that to the user\n\t callback(err)\n\t }\n\t return\n\t }\n\t log.verbose('`which` succeeded for `' + command + '`', execPath)\n\t copyNodeLib()\n\t })\n\t }", "function doWhich () {\n // First make sure we have the build command in the PATH\n which(command, function (err, execPath) {\n if (err) {\n if (win && /not found/.test(err.message)) {\n // On windows and no 'msbuild' found. Let's guess where it is\n guessMsbuild()\n } else {\n // Some other error or 'make' not found on Unix, report that to the user\n callback(err)\n }\n return\n }\n log.verbose('`which` succeeded for `' + command + '`', execPath)\n copyNodeLib()\n })\n }", "function browsersForPlatform(){\n var platform = process.platform\n\n if (platform === 'win32'){\n return [\n {\n name: \"IE\",\n exe: \"C:\\\\Program Files\\\\Internet Explorer\\\\iexplore.exe\",\n supported: browserExeExists\n },\n {\n name: \"Firefox\",\n exe: [\n \"C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe\",\n \"C:\\\\Program Files (x86)\\\\Mozilla Firefox\\\\firefox.exe\"\n ],\n args: [\"-profile\", tempDir + \"\\\\testem.firefox\"],\n setup: function(config, done){\n setupFirefoxProfile(tempDir + '/testem.firefox', done)\n },\n supported: browserExeExists\n },\n {\n name: \"Chrome\",\n exe: [\n userHomeDir + \"\\\\Local Settings\\\\Application Data\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n userHomeDir + \"\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\",\n \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\Chrome.exe\",\n \"C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\Chrome.exe\"\n ],\n args: [\"--user-data-dir=\" + tempDir + \"\\\\testem.chrome\", \"--no-default-browser-check\", \"--no-first-run\", \"--ignore-certificate-errors\"],\n setup: function(config, done){\n rimraf(tempDir + '\\\\testem.chrome', done)\n },\n supported: browserExeExists\n },\n {\n name: \"Safari\",\n exe: [\n \"C:\\\\Program Files\\\\Safari\\\\safari.exe\",\n \"C:\\\\Program Files (x86)\\\\Safari\\\\safari.exe\"\n ],\n supported: browserExeExists\n },\n {\n name: \"Opera\",\n exe: [\n \"C:\\\\Program Files\\\\Opera\\\\opera.exe\",\n \"C:\\\\Program Files (x86)\\\\Opera\\\\opera.exe\"\n ],\n args: [\"-pd\", tempDir + \"\\\\testem.opera\"],\n setup: function(config, done){\n rimraf(tempDir + '\\\\testem.opera', done)\n },\n supported: browserExeExists\n },\n {\n name: 'PhantomJS',\n exe: 'phantomjs',\n args: buildPhantomJsArgs,\n supported: findableByWhere\n }\n ]\n }else if (platform === 'darwin'){\n return [\n {\n name: \"Chrome\", \n exe: \"/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome\", \n args: [\"--user-data-dir=\" + tempDir + \"/testem.chrome\", \"--no-default-browser-check\", \"--no-first-run\", \"--ignore-certificate-errors\"],\n setup: function(config, done){\n rimraf(tempDir + '/testem.chrome', done)\n },\n supported: browserExeExists\n },\n {\n name: \"Chrome Canary\", \n exe: \"/Applications/Google\\ Chrome\\ Canary.app/Contents/MacOS/Google\\ Chrome\\ Canary\", \n args: [\"--user-data-dir=\" + tempDir + \"/testem.chrome-canary\", \"--no-default-browser-check\", \"--no-first-run\", \"--ignore-certificate-errors\"],\n setup: function(config, done){\n rimraf(tempDir + '/testem.chrome-canary', done)\n },\n supported: browserExeExists\n },\n {\n name: \"Firefox\", \n exe: \"/Applications/Firefox.app/Contents/MacOS/firefox\",\n args: [\"-profile\", tempDir + \"/testem.firefox\"],\n setup: function(config, done){\n setupFirefoxProfile(tempDir + '/testem.firefox', done)\n },\n supported: browserExeExists\n },\n {\n name: \"Safari\",\n exe: \"/Applications/Safari.app/Contents/MacOS/Safari\",\n setup: function(config, done){\n var url = this.getUrl()\n fs.writeFile(tempDir + '/testem.safari.html', \"<script>window.location = '\" + url + \"'</script>\", done)\n },\n args: function(){\n return [tempDir + '/testem.safari.html']\n },\n supported: browserExeExists\n },\n {\n name: \"Opera\",\n exe: \"/Applications/Opera.app/Contents/MacOS/Opera\",\n args: [\"-pd\", tempDir + \"/testem.opera\"],\n setup: function(config, done){\n rimraf(tempDir + '/testem.opera', done)\n },\n supported: browserExeExists\n },\n {\n name: 'PhantomJS',\n exe: 'phantomjs',\n args: buildPhantomJsArgs,\n supported: findableByWhich\n }\n ]\n }else if (platform === 'linux'){\n return [\n {\n name: 'Firefox',\n exe: 'firefox',\n args: [\"-no-remote\", \"-profile\", tempDir + \"/testem.firefox\"],\n setup: function(config, done){\n rimraf(tempDir + '/testem.firefox', function(err){\n if (!err){\n fs.mkdir(tempDir + '/testem.firefox', done)\n }else{\n done()\n }\n })\n },\n supported: findableByWhich\n },\n {\n name: 'Chrome',\n exe: 'google-chrome',\n args: [\"--user-data-dir=\" + tempDir + \"/testem.chrome\", \n \"--no-default-browser-check\", \"--no-first-run\", \"--ignore-certificate-errors\"],\n setup: function(config, done){\n rimraf(tempDir + '/testem.chrome', done)\n },\n supported: findableByWhich\n },\n {\n name: 'Chromium',\n exe: ['chromium', 'chromium-browser'],\n args: [\"--user-data-dir=\" + tempDir + \"/testem.chromium\", \n \"--no-default-browser-check\", \"--no-first-run\", \"--ignore-certificate-errors\"],\n setup: function(config, done){\n rimraf(tempDir + '/testem.chromium', done)\n },\n supported: findableByWhich\n },\n {\n name: 'PhantomJS',\n exe: 'phantomjs',\n args: buildPhantomJsArgs,\n supported: findableByWhich\n }\n ]\n }else if (platform === 'sunos') {\n\treturn [\n {\n name: 'PhantomJS',\n exe: 'phantomjs',\n args: buildPhantomJsArgs,\n supported: findableByWhich\n }\n\t];\n }else{\n return []\n }\n}", "static getFirstInstallation() {\n if (utils_1.getPlatform() === 'darwin')\n return chromeFinder.darwinFast();\n return chromeFinder[utils_1.getPlatform()]()[0];\n }", "function findInstalledWoWVersions(selectedPath) {\n let gameVersions = storageService.getGameData('1').gameVersions;\n var installedVersions = [];\n for (var gameVersion in gameVersions) {\n if (process.platform === \"win32\") {\n let exePath = path.join(selectedPath, gameVersions[gameVersion].executable);\n let flavorString = gameVersions[gameVersion].flavorString;\n \n if (fs.existsSync(exePath)) {\n // Identify version\n let flavorFile = path.join(selectedPath, '.flavor.info');\n if (fs.existsSync(flavorFile)) {\n var text = fs.readFileSync(flavorFile).toString('utf-8').split('\\n');\n if (text[1] == flavorString) {\n installedVersions.push(gameVersion);\n }\n }\n } else {\n switch (gameVersion) {\n case 'wow_retail':\n var p = path.join(selectedPath, '_retail_', gameVersions[gameVersion].executable);\n var f = path.join(selectedPath, '_retail_', '.flavor.info');\n break;\n case 'wow_classic':\n var p = path.join(selectedPath, '_classic_', gameVersions[gameVersion].executable);\n var f = path.join(selectedPath, '_classic_', '.flavor.info');\n break;\n case 'wow_retail_ptr':\n var p = path.join(selectedPath, '_ptr_', gameVersions[gameVersion].executable);\n var f = path.join(selectedPath, '_ptr_', '.flavor.info');\n break;\n case 'wow_classic_ptr':\n var p = path.join(selectedPath, '_classic_ptr_', gameVersions[gameVersion].executable);\n var f = path.join(selectedPath, '_classic_ptr_', '.flavor.info');\n break;\n case 'wow_retail_beta':\n var p = path.join(selectedPath, '_beta_', gameVersions[gameVersion].executable);\n var f = path.join(selectedPath, '_beta_', '.flavor.info');\n break;\n }\n if (fs.existsSync(p)) {\n if (fs.existsSync(f)) {\n var text = fs.readFileSync(f).toString('utf-8').split('\\n');\n if (text[1] == flavorString) {\n installedVersions.push(gameVersion);\n }\n }\n }\n \n }\n } else if (process.platform === \"darwin\") {\n let exePath = path.join(selectedPath, gameVersions[gameVersion].macExecutable);\n if (fs.existsSync(exePath)) {\n if (exePath.includes(gameVersions[gameVersion].macFlavorString)) {\n installedVersions.push(gameVersion); \n } \n } else {\n switch (gameVersion) {\n case 'wow_retail':\n var p = path.join(selectedPath, '_retail_', gameVersions[gameVersion].macExecutable);\n break;\n case 'wow_classic':\n var p = path.join(selectedPath, '_classic_', gameVersions[gameVersion].macExecutable);\n break;\n case 'wow_retail_ptr':\n var p = path.join(selectedPath, '_ptr_', gameVersions[gameVersion].macExecutable);\n break;\n case 'wow_classic_ptr':\n var p = path.join(selectedPath, '_classic_ptr_', gameVersions[gameVersion].macExecutable);\n break;\n case 'wow_retail_beta':\n var p = path.join(selectedPath, '_beta_', gameVersions[gameVersion].macExecutable);\n break;\n }\n if (fs.existsSync(p)) {\n installedVersions.push(gameVersion);\n }\n }\n }\n }\n return installedVersions;\n}", "function detectLibreOffice (additionalPaths) {\n function _findBundledPython(sofficePath, pythonName) {\n if (!sofficePath) {\n return null;\n }\n // Try finding a Python binary shipped alongside the soffice binary,\n // either in its actual directory, or - if it's a symbolic link -\n // in the directory it points to.\n var _symlinkDestination;\n try {\n _symlinkDestination = path.resolve(path.dirname(sofficePath), fs.readlinkSync(sofficePath));\n // Assume symbolic link, will throw in case it's not:\n sofficeActualDirectory = path.dirname(_symlinkDestination);\n } catch (errorToIgnore) {\n // Not a symlink.\n sofficeActualDirectory = path.dirname(sofficePath);\n }\n // Check for the Python binary in the actual soffice path:\n try {\n return which.sync(pythonName, { path: sofficeActualDirectory });\n } catch (errorToIgnore) {\n // No bundled Python found.\n return null;\n }\n }\n\n function _findBinaries(paths, pythonName, sofficeName) {\n var _whichPython;\n var _whichSoffice;\n var _sofficeActualDirectory;\n // Look for the soffice binary - first in the well-known paths, then in\n // the system PATH. On Linux, this prioritizes \"upstream\" (TDF) packages\n // over distro-provided ones from the OS' repository.\n _whichSoffice = which.sync(sofficeName, { path: paths.join(':'), nothrow: true }) || which.sync(sofficeName, { nothrow: true }) || null;\n // Check for a Python binary bundled with soffice, fall back to system-wide:\n // This is a bit more complex, since we deal with some corner cases.\n // 1. Hopefully use the python from the original soffice package, same dir\n // (this might fail on Mac if python is not in MacOS/, but in Resources/).\n // 1a. Corner case: on Linux, if soffice was in /usr/bin/soffice and NOT\n // a symlink, then we would hit /usr/bin/python, which is probably python2.\n // This is why we try with python3 first, to defend against this.\n // 2. Try finding it in any of the well-known paths - this might result in\n // using Python from *another install* of LibreOffice, but it should be ok.\n // This is only attempted if the paths exist on this system to avoid\n // a fallback to system PATH that \"which\" does when passed an empty string.\n // 3. Fall back to system python (hopefully named python3).\n _whichPython = _findBundledPython(_whichSoffice, 'python3') ||\n _findBundledPython(_whichSoffice, 'python') ||\n (paths.length > 0 && which.sync('python3', { path: paths.join(':'), nothrow: true })) ||\n (paths.length > 0 && which.sync('python', { path: paths.join(':'), nothrow: true })) ||\n which.sync('python3', { nothrow: true }) ||\n which.sync('python', { nothrow: true }) || null;\n return {\n soffice: _whichSoffice,\n python: _whichPython\n };\n }\n\n function _listProgramDirectories(basePath, pattern) {\n try {\n return fs.readdirSync(basePath).filter(function _isLibreOfficeDirectory(dirname) {\n return pattern.test(dirname);\n }).map(function _buildFullProgramPath(dirname) {\n return path.join(basePath, dirname, 'program');\n });\n } catch (errorToIgnore) {\n return [];\n }\n }\n\n var _pathsToCheck = additionalPaths || [];\n // overridable file names to look for in the checked paths:\n var _pythonName = 'python';\n var _sofficeName = 'soffice';\n var _linuxDirnamePattern = /^libreoffice\\d+\\.\\d+$/;\n var _windowsDirnamePattern = /^LibreOffice( \\d+(?:\\.\\d+)*?)?$/i;\n\n if (process.platform === 'darwin') {\n _pathsToCheck = _pathsToCheck.concat([\n // It is better to use the python bundled with LibreOffice:\n '/Applications/LibreOffice.app/Contents/MacOS',\n '/Applications/LibreOffice.app/Contents/Resources'\n ]);\n }\n else if (process.platform === 'linux') {\n // The Document Foundation packages (.debs, at least) install to /opt,\n // into a directory named after the contained LibreOffice version.\n // Add any existing directories that match this to the list.\n _pathsToCheck = _pathsToCheck.concat(_listProgramDirectories('/opt', _linuxDirnamePattern));\n }\n else if (process.platform === 'win32') {\n _pathsToCheck = _pathsToCheck\n .concat(_listProgramDirectories('C:\\\\Program Files', _windowsDirnamePattern))\n .concat(_listProgramDirectories('C:\\\\Program Files (x86)', _windowsDirnamePattern));\n _pythonName = 'python.exe';\n }\n else {\n debug('your platform \"%s\" is not supported yet', process.platform);\n }\n\n // Common logic for all OSes: perform the search and save results as options:\n var _foundPaths = _findBinaries(_pathsToCheck, _pythonName, _sofficeName);\n if (_foundPaths.soffice) {\n debug('LibreOffice found: soffice at %s, python at %s', _foundPaths.soffice, _foundPaths.python);\n isLibreOfficeFound = true;\n converterOptions.pythonExecPath = _foundPaths.python;\n converterOptions.sofficeExecPath = _foundPaths.soffice;\n }\n\n if (isLibreOfficeFound === false) {\n debug('cannot find LibreOffice. Document conversion cannot be used');\n }\n}", "async findLaunchRegisteredApps(pattern, defaultPaths, suffixes) {\n const lsRegister = '/System/Library/Frameworks/CoreServices.framework' +\n '/Versions/A/Frameworks/LaunchServices.framework' +\n '/Versions/A/Support/lsregister';\n const { stdout, } = await this.execa.command(`${lsRegister} -dump | grep -i '${pattern}'| awk '{$1=\"\"; print $0}'`, { shell: true, stdio: 'pipe' });\n const paths = [...defaultPaths, ...stdout.split('\\n').map(l => l.trim())].filter(l => !!l);\n const preferred = this.getPreferredPath();\n if (preferred) {\n paths.push(preferred);\n }\n const installations = new Set();\n for (const inst of paths) {\n for (const suffix of suffixes) {\n const execPath = path_1.posix.join(inst.trim(), suffix);\n try {\n await this.fs.access(execPath);\n installations.add(execPath);\n }\n catch (e) {\n // no access => ignored\n }\n }\n }\n return installations;\n }", "function resolveWindowsExe(cmd) {\n var winExtensions = ['.exe', '.cmd', '.bat', '.js', '.vbs'];\n function isValidExe(c) {\n return winExtensions.indexOf(path.extname(c).toLowerCase()) !== -1 && fs.existsSync(c);\n }\n if (isValidExe(cmd)) {\n return cmd;\n }\n try {\n cmd = which.sync(cmd);\n } catch (e) {\n // just ignore which's whining\n }\n if (!isValidExe(cmd)) {\n winExtensions.some(function(ext) {\n if (fs.existsSync(cmd + ext)) {\n cmd = cmd + ext;\n return true;\n }\n });\n }\n return cmd;\n}", "function search_paths(thing_to_find, explicit_path, env_name)\n{\n\tvar i, found = false, place = false, file, env;\n\n\tSTDOUT.Write(\"Checking for \" + thing_to_find + \" ... \");\n\n\tthing_to_find = thing_to_find.replace(new RegExp(\"/\", \"g\"), \"\\\\\");\n\n\tif (explicit_path != null) {\n\t\tif (typeof(explicit_path) == \"string\") {\n\t\t\texplicit_path = explicit_path.split(\";\");\n\t\t}\n\n\t\tfor (i = 0; i < explicit_path.length; i++) {\n\t\t\tfile = glob(explicit_path[i] + \"\\\\\" + thing_to_find);\n\t\t\tif (file) {\n\t\t\t\tfound = true;\n\t\t\t\tplace = file[0];\n\t\t\t\tplace = place.substr(0, place.length - thing_to_find.length - 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!found && env_name != null) {\n\t\tenv = WshShell.Environment(\"Process\").Item(env_name);\n\t\tenv = env.split(\";\");\n\t\tfor (i = 0; i < env.length; i++) {\n\t\t\tfile = glob(env[i] + \"\\\\\" + thing_to_find);\n\t\t\tif (file) {\n\t\t\t\tfound = true;\n\t\t\t\tplace = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (found && place == true) {\n\t\tSTDOUT.WriteLine(\" <in default path>\");\n\t} else if (found) {\n\t\tSTDOUT.WriteLine(\" \" + place);\n\t} else {\n\t\tSTDOUT.WriteLine(\" <not found>\");\n\t}\n\treturn place;\n}", "function test_html5_console_linux(browser, operating_system, provider) {}", "function checkLinuxTraySupport (cb) {\n const cp = require('child_process')\n\n // Check that libappindicator libraries are installed in system.\n cp.exec('ldconfig -p | grep libappindicator', (err, stdout) => {\n if (err) return cb(err)\n cb(null)\n })\n}", "function which(tool, check) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!tool) {\n throw new Error(\"parameter 'tool' is required\");\n }\n // recursive when check=true\n if (check) {\n const result = yield which(tool, false);\n if (!result) {\n if (ioUtil.IS_WINDOWS) {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);\n }\n else {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);\n }\n }\n }\n try {\n // build the list of extensions to try\n const extensions = [];\n if (ioUtil.IS_WINDOWS && process.env.PATHEXT) {\n for (const extension of process.env.PATHEXT.split(path.delimiter)) {\n if (extension) {\n extensions.push(extension);\n }\n }\n }\n // if it's rooted, return it if exists. otherwise return empty.\n if (ioUtil.isRooted(tool)) {\n const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);\n if (filePath) {\n return filePath;\n }\n return '';\n }\n // if any path separators, return empty\n if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\\\'))) {\n return '';\n }\n // build the list of directories\n //\n // Note, technically \"where\" checks the current directory on Windows. From a toolkit perspective,\n // it feels like we should not do this. Checking the current directory seems like more of a use\n // case of a shell, and the which() function exposed by the toolkit should strive for consistency\n // across platforms.\n const directories = [];\n if (process.env.PATH) {\n for (const p of process.env.PATH.split(path.delimiter)) {\n if (p) {\n directories.push(p);\n }\n }\n }\n // return the first match\n for (const directory of directories) {\n const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions);\n if (filePath) {\n return filePath;\n }\n }\n return '';\n }\n catch (err) {\n throw new Error(`which failed with message ${err.message}`);\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
key paths to uploaded data items to migrate these items will have a url, and maybe a resize url () => [ ['data', contentType, itemKey, controlKey, gridIndex, gridControl, galleryIndex], ['data', contentType, itemKey, controlKey, gridIndex, gridControl], ['data', contentType, itemKey, controlKey, galleryIndex], ['data', contentType, itemKey, controlKey], ['data', contentType, controlKey, gridIndex, gridControl, galleryIndex], ['data', contentType, controlKey, gridIndex, gridControl], ['data', contentType, controlKey, galleryIndex], ['data', contentType, controlKey], ]
function dataItems () { return Object.keys(valueForKeypath(backup, [ 'data' ])) .map(function (contentType) { if (valueForKeypath(backup, [ 'contentType', contentType, 'oneOff' ])) { return Object.keys(valueForKeypath(backup, [ 'data', contentType ])) .map(function (controlKey) { if (isGrid(contentType, controlKey)) { return (valueForKeypath(backup, [ 'data', contentType, controlKey ]) ? valueForKeypath(backup, [ 'data', contentType, controlKey ]) .map(function (gridRow, gridIndex) { return Object.keys(gridRow).map(function (gridItem, gridItemIndex) { return [ 'data', contentType, controlKey, gridIndex, gridItem ]; }); }) .reduce(function (a, b) { return a.concat(b) }, []) : false); } else if(isGallery(contentType, controlKey)) { return ( valueForKeypath(backup, [ 'data', contentType, controlKey ]) ? valueForKeypath(backup, [ 'data', contentType, controlKey ]) .map(function (galleryItem, galleryItemIndex) { return [ 'data', contentType, controlKey, galleryItemIndex ]; }) : false); } else { return [ 'data', contentType, controlKey ]; } }) .filter(function (itemKey) { return itemKey !== false; }); } else { return Object.keys(valueForKeypath(backup, [ 'data', contentType ])) .map(function (itemKey) { return Object.keys(valueForKeypath(backup, [ 'data', contentType, itemKey ])) .map(function (controlKey) { if (isGrid(contentType, controlKey)) { return ( valueForKeypath(backup, [ 'data', contentType, itemKey, controlKey ]) ? valueForKeypath(backup, [ 'data', contentType, itemKey, controlKey ]) .map(function (gridRow, gridIndex) { return Object.keys(gridRow).map(function (gridItem, gridItemIndex) { if (isGallery(contentType, controlKey, gridItem)) { return ( valueForKeypath(backup, [ 'data', contentType, itemKey, controlKey, gridItemIndex, gridItem ]) ? valueForKeypath(backup, [ 'data', contentType, itemKey, controlKey, gridItemIndex, gridItem ]) .map(function (galleryItem, galleryItemIndex) { return [ 'data', contentType, itemKey, controlKey, gridItemIndex, gridItem, galleryItemIndex ] }) : false ) } else { return [ 'data', contentType, itemKey, controlKey, gridIndex, gridItem ]; } }) .filter(function (gridRow) { return gridRow !== false; }) .reduce(function (a, b) { if (Array.isArray(b[0])) return a.concat(b); else return a.concat([b]); }, []); }) .reduce(function (a, b) { return a.concat(b) }, []) : false); } else if(isGallery(contentType, controlKey)) { return ( valueForKeypath(backup, [ 'data', contentType, itemKey, controlKey ]) ? valueForKeypath(backup, [ 'data', contentType, itemKey, controlKey ]) .map(function (galleryItem, galleryItemIndex) { return [ 'data', contentType, itemKey, controlKey, galleryItemIndex ]; }) : false); } else { return [ 'data', contentType, itemKey, controlKey ]; } }) .filter(function (itemKey) { return itemKey !== false; }) .reduce(function (a, b) { if (Array.isArray(b[0])) return a.concat(b); else return a.concat([b]); }, []); }) .reduce(function (a, b) { return Array.isArray(b[0]) ? a.concat(b) : a.concat([b]) }, []); } }) .reduce(function (a, b) { return Array.isArray(b[0]) ? a.concat(b) : a.concat([b]) }, []) .reduce(function (a, b) { return Array.isArray(b[0]) ? a.concat(b) : a.concat([b]) }, []); }
[ "processUploadImages(uploadData){\n mediaItems = []\n for (i = 0; i < uploadData.length; i ++){\n mediaItems.push({\n \"description\": uploadData[i].description,\n \"simpleMediaItem\": {\n \"uploadToken\": uploadData[i].uploadToken\n }\n })\n }\n return mediaItems\n }", "loadImages(): void {\n let self = this;\n let items = this.getState().items;\n for (let i = 0; i < items.length; i++) {\n let item: ItemType = items[i];\n // Copy item config\n let config: ImageViewerConfigType = {...item.viewerConfig};\n if (_.isEmpty(config)) {\n config = makeImageViewerConfig();\n }\n let url = item.url;\n let image = new Image();\n image.crossOrigin = 'Anonymous';\n self.images.push(image);\n image.onload = function() {\n config.imageHeight = this.height;\n config.imageWidth = this.width;\n self.store.dispatch({type: types.LOAD_ITEM, index: item.index,\n config: config});\n };\n image.onerror = function() {\n alert(sprintf('Image %s was not found.', url));\n };\n image.src = url;\n }\n }", "build_paths() {\n return {\n items: {\n list: { // Returns a list of items\n method: \"GET\",\n path: \"items\", \n }, \n item: { // Returns a single item with ID %%\n method: \"GET\",\n path: \"items/%%\"\n }, \n item_metadata: { // Returns metadata for item %%\n method: \"GET\",\n path: \"items/%%/metadata\", \n }, \n item_bitstreams: { // Returns available bitstreams for item %%\n method: \"GET\",\n path: \"items/%%/bitstreams\" \n },\n find_by_metadata: { // Returns items based on specified metadata value\n method: \"POST\",\n path: \"items/find-by-metadata-field\"\n } \n },\n query: { \n filtered_items: { // Returns items based on chosen filters\n method: \"GET\",\n path: \"filtered-items\", \n }, \n filtered_collections: { // Returns collections based on chosen filters\n method: \"GET\",\n path: \"filtered-collections\",\n }, \n collection: { // Returns collection with ID %%\n method: \"GET\",\n path: \"filtered-collections/%%\",\n } \n },\n bitstreams: { \n list: { // Returns all bitstreams in DSpace\n method: \"GET\",\n path: \"bitsreams\"\n },\n item: { // Returns an item with bitstream ID %%\n method: \"GET\",\n path: \"bitstreams/{%%}\"\n },\n item_policy: { // Returns the policy for a bitstream with ID %%\n method: \"GET\",\n path: \"bitstreams/%%/policy\"\n },\n content: { // Retrieve content for a bitstream with ID %%\n method: \"GET\",\n path: \"bitstreams/%%/retrieve\"\n }\n },\n schemas: {\n list: { // Returns a list of all schemas\n method: \"GET\",\n path: \"registries/schema\"\n },\n item: { // Returns a metadata schema with schema prefix %%\n method: \"GET\",\n path: \"registries/schema/%%\"\n },\n field: { // Returns a metadata schema with field ID %%\n method: \"GET\",\n path: \"registries/metadata-fields/%%\"\n }\n }\n };\n }", "importAllImages(r) {\n let images = [];\n r.keys().map((item) => {\n return images.push({name: item.replace('./', ''), url: r(item)});\n });\n return images;\n }", "function createDataArray(e) {\n var appendKeySuffix = 'urlData';\n var appendKeyCount = storageCount;\n var keys = [];\n\n return new Promise(function (resolve, reject) {\n $.each(e, function (key) {\n if (key.endsWith(appendKeySuffix)) {\n keys.push(key);\n }\n });\n var sortedKeys = keys.sort(collator.compare);\n for (var i = 0; i < sortedKeys.length; i++) {\n storage.get(sortedKeys[i], function (obj) {\n objects.push(obj);\n });\n }\n resolve(objects);\n });\n }", "composeEntryGalleryFields(assetFields, entry) {\n return assetFields.reduce((acc, fieldname) => {\n if (entry[fieldname] == undefined || entry[fieldname].length == 0) {\n return acc\n }\n\n entry[fieldname] = entry[fieldname].map((image) => {\n // let fileLocation = this.getFileAsset(image)\n let fileLocation = this.getFileAsset(image.path)\n image.localFile___NODE = fileLocation\n return image\n })\n\n const newAcc = {\n ...acc,\n [fieldname]: entry[fieldname],\n }\n return newAcc\n }, {})\n }", "function createUrlPics(index, data) {\n let urlbase = (preUrl);\n let pathPics = index + \"_\" + checksum(data);\n let ext = '.jpeg';\n return Uri = path.join(urlbase, pathPics + ext);\n\n }", "function updateKeys() {\n keys = [];\n\n for (var key in items) {\n keys.push(key);\n }\n\n LocalStorage.length = keys.length;\n }", "function addMapping(keys, urls, callback) {\n\n\n\n function addSingleMapping(key, url, callback) {\n var item = {};\n item[key] = normaliseURL(url);\n chrome.storage.sync.set(item);\n\n callback();\n }\n\n function addManyToOne(keys, url, i, callback) {\n if (i < keys.length) {\n addSingleMapping(keys[i], url, \n addManyToOne(keys, url, ++i, callback));\n } else {\n callback();\n }\n }\n\n function addManyToMany(keys, urls, i, callback) {\n if (i < keys.length) {\n addSingleMapping(keys[i], urls[i],\n addManyToMany(keys, urls, ++i, callback));\n } else {\n callback();\n }\n }\n\n if( Object.prototype.toString.call(keys) === '[object Array]' ) {\n if (Object.prototype.toString.call(urls) !== '[object Array]') {\n if (typeof(urls) === 'string') {\n // array of keys mapping to single url. This is fine\n addManyToOne(keys, urls, 0, callback)\n } else {\n // don't know what's been passed, but it's wrong\n throw GoExtException(\"addMapping received urls of incompatible \"+\n \"type \" + Object.prototype.toString.call(urls));\n }\n } else {\n // array of keys mapping to array of urls - check it's 1:1\n if (keys.length != urls.length) {\n throw GoExtException(\"must have 1:1 mapping between keys and\" +\n \" urls when adding multiple redirects at a time.\");\n } else {\n // add 1:1 mappings. This is fine.\n addManyToMany(keys, urls, 0, callback);\n }\n }\n } else {\n if (typeof(keys) === 'string') {\n if (typeof(urls) === 'string') {\n // Single mapping. This is fine\n addSingleMapping(keys,urls, callback);\n } else {\n // can only have a single url for a single key\n throw GoExtException(\"Only one key passed for url mapping of \"+ \n \"type \" + Object.prototype.toString.call(urls));\n }\n } else {\n // non-string, non-array key\n throw GoExtEception(\"Non-string, non-array key passed for mapping\");\n }\n }\n}", "static getImageUrls({itemKey, isThumbnail = false}) {\n const checkState = [STATE.ALIVE, STATE.EXPIRED];\n return Promise.all(checkState.map(state => {\n return new Promise((resolve, reject) => {\n const prefix = KeyUtils.getPrefix(ENTITY.IMAGE, state, itemKey);\n fetchPrefix(prefix, (err, data) => err ?\n reject(err) : resolve(data.map(value => value.key)));\n });\n })).then(arrs => arrs.reduce((result, key) => result.concat(key)))\n .then(keys => {\n const s3Connector = new S3Connector();\n const urls = (isThumbnail) ?\n s3Connector.getPrefixedImageUrls(keys, IMAGE_SIZE_PREFIX.THUMBNAIL) :\n s3Connector.getImageUrls(keys);\n return urls;\n });\n }", "function importAll(r) {\n var images = [];\n r.keys().map((item) => \n {\n var src = item.replace('./',''); // DRY stuff\n images.push(\n {\n src: src, // E.g. Glasses/glasses1.png\n img: r(item), // The image\n type: src.substr(0,src.indexOf('/')), // e.g. Glasses\n fileName: src.substr(src.indexOf('/')+1,src.length) // E.g. glasses1.png\n }); \n });\n return images;\n}", "function addHiddenFields(itemContainer, data) {\n var index = itemContainer.data('upload');\n var fields = [];\n if (isMultiple) {\n fields.push({name: formName + '[files][' + index + '][key]', value: data.key});\n fields.push({name: formName + '[files][' + index + '][token]', value: data.token});\n } else {\n fields.push({name: formName + '[files][key]', value: data.key});\n fields.push({name: formName + '[files][token]', value: data.token});\n }\n for (var i = 0; i < fields.length; i++) {\n itemContainer.append($('<input class=\"afb_upload_' + index + '\" type=\"hidden\" name=\"' + fields[i].name + '\" value=\"' + fields[i].value + '\">'));\n }\n }", "function saveItem(data) {\n return data.map((video, index) => {\n if (video.snippet.thumbnails) {\n fs.appendFileSync(\n '../dist/sitemap.xml',\n '\\n\\t<url>\\n\\t\\t<loc>https://staytu.be/videos/' +\n video.snippet.resourceId.videoId +\n '</loc>\\n</url>'\n )\n }\n })\n}", "function updateKeys(){keys=[];for(var key in items){keys.push(key);}LocalStorage.length=keys.length;}", "function getDataFromEntries(data) {\n if(!data || !data.title || !data.entries)\n return new Array();\n var iconName = '';\n var isRepository = false;\n if(data.title == \"Repositories\")\n { iconName = constants.iconBook;isRepository = true; }\n else if(data.title == \"Cabinets\")\n iconName = constants.iconChevronRight;\n else if(data.title.startsWith(\"Objects under\"))\n iconName = constants.documentStaticImage;\n else if(data.title.startsWith(\"Users\"))\n iconName = constants.userStaticImage;\n else if(data.title.startsWith(\"Groups\"))\n iconName = constants.groupStaticImage;\n else if(data.title.startsWith(\"Formats\"))\n iconName = constants.formatStaticImage;\n else if(data.title.startsWith(\"Relation\"))\n iconName = constants.relationStaticImage;\n else if(data.title.startsWith(\"Types\"))\n iconName = constants.typeStaticImage;\n\n var folderArray = new Array();\n var assetArray = new Array();\n for (var i = 0; i < data.entries.length; i++) {\n var img = iconName;\n var isFolder = false;\n // Check if object is of type folder and set different icon then\n if(data.entries[i].summary.startsWith(constants.folderObjectType))\n img = constants.iconChevronRight;\n \n if(data.entries[i].summary.startsWith(constants.folderObjectType) || data.entries[i].summary.startsWith(constants.cabinetObjectType))\n isFolder = true;\n \n // Also locate 'icon' element containing URI to Thumbnail Server image \n var thumbnailUrl = findIconLink(data,i);\n if(!thumbnailUrl || thumbnailUrl == \"\")\n if (iconName == \"\") \n thumbnailUrl = constants.uknownStaticImage;\n else\n thumbnailUrl = iconName;\n var updated = '';\n var summary = '';\n var updatedCopy = normalizeString(data.entries[i].updated,'T',false);\n var summaryCopy = normalizeString(data.entries[i].summary,' ',false);\n if(isListView()) {\n updated = updatedCopy;\n summary = summaryCopy;\n }\n if (isFolder || isRepository) \n folderArray.push({\n uri: data.entries[i].content.src,\n title: normalizeString(data.entries[i].title,'/',true),\n shorttitle: shorten(normalizeString(data.entries[i].title,'/',true)),\n description: data.entries[i].summary,\n relimagelink: img,\n realthumbnail: thumbnailUrl,\n thumbnailsize: getThumnbailSize(),\n updated: updated,\n updatedShadowCopy: updatedCopy,\n summary: summary,\n summaryShadowCopy: summaryCopy,\n index: i,\n });\n else\n assetArray.push({\n uri: data.entries[i].content.src,\n title: normalizeString(data.entries[i].title,'/',true),\n shorttitle: shorten(normalizeString(data.entries[i].title,'/',true)),\n description: data.entries[i].summary,\n relimagelink: img,\n realthumbnail: thumbnailUrl,\n thumbnailsize: getThumnbailSize(),\n updated: updated,\n updatedShadowCopy: updatedCopy,\n summary: summary,\n summaryShadowCopy: summaryCopy,\n index: i,\n });\n }\n var dataArray = new Array();\n dataArray.push(folderArray);\n dataArray.push(assetArray);\n return dataArray;\n}", "function _parseQueryStringItems() { \r\n for(var intIndex1 = 0;intIndex1 < _eleAryHiddenData.length;intIndex1++) {\r\n // Get data from input hidden, get pages from query string.\r\n var intPageLength = parseInt(getQueryStringValue(_eleAryHiddenData[intIndex1].value, 'pageslength'), 10);\r\n _strAryItemIds[intIndex1] = [];\r\n for(var intIndex2 = 0;intIndex2 < intPageLength;intIndex2++) {\r\n // Get data from input hidden, get items from query string\r\n _strAryItemIds[intIndex1][intIndex2] = getQueryStringValue(_eleAryHiddenData[intIndex1].value, 'images_' + (intIndex2 + 1));\r\n }\r\n }\r\n }", "function createThumbnails(filRef){\n\n var versions = {\n preview: {\n width: 500,\n height: null,\n scale: '^>'\n },\n thumb: {\n width: 200,\n height: 200,\n scale: '^>'\n }\n };\n\n _.map(versions, (vRef, version) => {\n\n vRef.path = `${fileRef._storagePath}/${fileRef._id}-${version}.${fileRef.extension}`\n\n gm(fileRef.path)\n .resize(vRef.width, vRef.width, vRef.scale)\n .write(vRef.path , (error, file) => {\n\n bound(() => {\n if (error) {\n console.log(error)\n } else {\n\n var upd = {\n $set: {}\n };\n upd['$set']['versions.' + version] = {\n path: vRef.path,\n size: fileRef.size,\n type: fileRef.type,\n extension: fileRef.extension,\n meta: {\n width: vRef.width,\n height: vRef.height\n }\n };\n\n Files.collection.update({_id: fileRef._id}, upd, (error) => {\n bound(() => {\n if (error) {\n console.error(error);\n } else {\n fileRef.versions[version] = vRef\n sendToStorage(fileRef, version);\n }\n });\n });\n }\n });\n });\n });\n }", "setDataItems(data) {\n\t\tif (this.validateDataItems(data)) // Valido la información que entra\n\t\t{\n\t\t\t// La devuelvo normalizada\n\t\t const items = \n\t {\n\t id: data.id,\n\t title: data.title,\n\t price: {\n\t currency: data.currency_id,\n\t amount: data.price,\n\t decimals: data.decimal_places\n\t },\n\t picture: data.thumbnail,\n\t condition: data.condition == \"used\" ? \"Usado\" : \"Nuevo\",\n\t free_shipping: data.shipping.free_shipping,\n\t address: data.address.state_name\n\t }\n\t \t\n\t \t\treturn items\n\t\t}\n\t}", "createThumbs(product) {\r\n if (!product.images ||\r\n !product.images.GALLERY ||\r\n product.images.GALLERY.length < 2) {\r\n return [];\r\n }\r\n return product.images.GALLERY.map((c) => Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])({ container: c }));\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sendMessage function: parameters: Away team, Home team, and Game time. tells the bot to send a message
function sendMessage(away, home, time) { var options = { url: 'https://api.groupme.com/v3/bots/post', method: 'POST', form: { 'bot_id':'123456789abcdevghijklmnop', // !IMPORTANT! enter your GroupMe Bot ID here! 'text':away + ' @ ' + home + ' ' + time + ' ' + emoji.get('ice_hockey_stick_and_puck') + emoji.get('ice_skate') + emoji.get('musical_note') } } request(options, function(error, response, body) { if(!error && response.statusCode == 200) { console.log(body); } }) }
[ "function action_bot_join(bot, robot, data, team_name)\n{\n\tbot.postMessage(data.channel, \"Hi, I'm MSABot. I can assist you to look out the service you're developing and maintaining. \\n Use @MSABot help to figure out how to use me! \\nRemember to setting server urls before using me!\");\n}", "function sendToOpponent(message) {\n send(opponent(message.player), message);\n}", "handleTeamChat(data) {\n if (data.team === \"red\") {\n for (let i = 0; i < this.redTurnOrder.length; i++) {\n super.sendDataToPlayer(this.redTurnOrder[i], {\n event: \"team-chat\",\n message: data.message,\n });\n }\n }\n if (data.team === \"blue\") {\n for (let i = 0; i < this.blueTurnOrder.length; i++) {\n super.sendDataToPlayer(this.blueTurnOrder[i], {\n event: \"team-chat\",\n message: data.message,\n });\n }\n }\n }", "function winGame() {\n finishTime();\n winMessage();\n}", "function sendReqattendGame(userID,gameName)\r\n{\tsend_obj = \r\n\t{\t\"type\": \"attendGame\",\r\n \t\"object\": \r\n\t\t{\t\"game\": {\r\n \t\t\"gameName\": gameName\r\n \t\t},\r\n\t\t\t\"user\":{\r\n\t\t\t\t\"userID\": userID\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\t\r\n\tsend(send_obj);\r\n}", "function sendScore(sender_psid, league, city){\n SportsDataUtils.getLastGame(league, city, (string)=>{\n let response = {\n text: string,\n };\n sendMessage(sender_psid, response);\n })\n}", "function sendGameStatus(game, messageText) {\n console.log('sendGameStatus: ' + game.gameId + ': ' + messageText);\n\n io.to(game.roomId).emit('GameStatus', {gameStatus: messageText});\n}", "function sendMove(gamerow, gamecol){\n pauseEventListeners(); //Stop this user from making any moves\n //console.log(\"\"+gamerow,gamecol);\n document.getElementById('turnMessage').innerHTML = \"\"+currentUserInfo.opponent+\"'s Turn. Please Wait.\"\n //Emit this so it can be sent to other person in room\n socket.emit(\"move made\", {\n moveCol: gamecol,\n moveRow: gamerow,\n roomId: currentUserInfo.currentRoom\n });\n\n }", "function tell(){\n return bot.sendMessage({ to: channelID, message: \"I am \" + current.season +\n \"!\\nPersonality Trait: \" + current.personalityTrait + \"\\nFlaw: \" + current.flaw});\n }", "function sendToGame(player, message) {\n for (let u of games.get(player)) {\n send(u, message);\n }\n}", "function sendMessages(count)\n{ \n\n \n //msg = msg + '|' + time\n for(i = 0; i < count; i++)\n {\n sendSingleMessage(port_player_stats, opponent_ip, i)\n }\n \n}", "function gameSend(event, data) {\n conn.send('GAME_' + event, data);\n }", "function sendScores(){\n\tgameStateObject.SendMessage(\"submitStats\", kongregateScore);\n}", "sendMessage(steamid, message){\n this.client.chatMessage(steamid, message);\n }", "function playWithBot() {\n\tshowProgress(true);\n\tdocument.getElementById(\"current-turn-block\").style.display = \"none\";\n\tdocument.getElementById(\"page3\").style.display = \"inline-block\";\n\tvar obj = {\n\t\tusername: userName,\n\t};\n\tplayerTurn = true;\n\tsocket.emit(\"createBotMatrix\", obj, function (data) {\n\t\tshowProgress(false);\n\t\tif (data.success) {\n\t\t\tsocket.emit(\"hostStartedGame\", obj);\n\t\t} else {\n\t\t\tdocument.getElementById(\"alert-sound\").play();\n\t\t\talert(data.error);\n\t\t}\n\t});\n}", "function gameLiveMessage(gameDetails) {\n var messageText = convertLeagueName(gameDetails[\"league\"]) + \" - \" + gameDetails[\"teams\"][0] + \" \" + gameDetails[\"score\"][0] + \" : \" + gameDetails[\"teams\"][1] + \n \" \" + gameDetails[\"score\"][1] + \"\\n\";\n\n if (gameDetails[\"inning_is_top\"] == true) {\n messageText += \"T\";\n } else {\n messageText += \"B\";\n }\n\n messageText += gameDetails[\"inning\"] + \", \" + gameDetails[\"outs\"] + \" Outs\";\n\n return messageText;\n}", "function sendReqnewGame(gamename,playgroundID,userID,mode,timetoplay)\r\n{\tsend_obj =\r\n\t{\t\"type\":\"createGame\",\r\n \t\"object\": {\r\n \"playgroundID\": playgroundID,\r\n \"gameName\": gamename,\r\n\t\t\"userID\": userID,\r\n\t\t\"mode\": mode,\r\n\t\t\"timetoplay\": timetoplay\r\n \t}\r\n\t};\r\n\t\r\n\tsend(send_obj);\r\n}", "function sendMessage() {\n\n channel.push('shout', { \n name: name.value || \"guest\", // get value of \"name\" of person sending the message. Set guest as default\n message: msg.value, // get message text (value) from msg input field.\n inserted_at: new Date() // date + time of when the message was sent\n });\n\n msg.value = ''; // reset the message input field for next message.\n}", "function sendTimeslot(message, timeslot) {\n var embed = new MessageEmbed()\n .setColor('#0099ff') \n .setTitle(timeslot.time)\n .setAuthor(timeslot.title, 'https://weathernews.jp/' + timeslot.casterImg);\n message.channel.send(embed);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up temp user when user arrives to page
function setTemp() { if (localStorage.getItem("userId") === null) { // Create temp user var tempUser = { name: "temp", password: "" }; localUser.name = tempUser.name; console.log(tempUser); // User post API.createUser(tempUser); } else { localUser.id = localStorage.getItem("userId"); API.getFridge(localUser.id); } }
[ "function assignTempUser() {\n //Replace with local user id\n new Fingerprint2().get(function(result) {\n console.log(result);\n $rootScope.tempuser = result;\n updateData($rootScope.tempuser);\n });\n }", "fillLoggedUserData() {\n this.loggedUser = this.res.locals[congif_const_1.config.loggedUerInformation];\n }", "function setupCurrentUser()\r\n{\r\n //============================================================\r\n // SETUP CURRENT USER\r\n //============================================================\r\n //Get user id from query string\r\n getCurrentUserId();\r\n //TESTING FB PROFILE PIC\r\n if (currentUserId > 10)\r\n {\r\n\t\tgetFBpic(currentUserId);\r\n }\r\n //end here\r\n if (!currentUserId)\r\n {\r\n //console.log(\"No user logged in!\");\r\n //return false;\r\n currentUserId = 1;\r\n }\r\n \r\n //Get users info from userDB\r\n currentUser = userDB({userId:currentUserId}).first();\r\n if (!currentUser)\r\n {\r\n console.log(\"No user found with id \" + currentUserId + \"!!\");\r\n return false;\r\n }\r\n currentUser.latlng = new google.maps.LatLng(currentUser.lat, currentUser.lon);\r\n return true;\r\n}", "function setCurrentUser() {\n\tvar request = new enyo.Ajax({\n\t\tmethod: 'GET',\n\t\turl: CONSTANTS.CURRENTUSER_URL,\n\t\thandleAs: 'text',\n\t\theaders: { Accept: 'text/plain', 'Content-Type' : 'text/turtle'},\n\t\tpostBody: null,\n\t\tpublished: { timeout: 60000 }\n\t});\n\trequest.go();\n\trequest.response(this, function(inSender, inResponse) {\n\t\tcreateCookie('currentUser', inResponse, 30);\n\t});\n}", "async function setLocalUser () {\n const loggedInUser = localStorage.getItem('userInfo')\n if (loggedInUser !== null) {\n const foundUser = JSON.parse(loggedInUser);\n props.setUserData(foundUser);\n }\n }", "function SetUser(){\n\tuser = {};\n\tuser[\"Name\"] = localStorage.getItem(\"Name\");\n\tuser[\"Email\"] = localStorage.getItem(\"Email\");\n\tuser[\"FacebookId\"] = localStorage.getItem(\"FacebookId\");\n\t\n\tUserModelChanged();\n}", "pageLoad(username) {\n if (!localStorage.getItem('currentUser')) {\n console.log(username + ' dont exist yet')\n\n this.checkMarkup(username)\n return\n }\n\n this.currentLocal = JSON.parse(localStorage.getItem('currentUser'))\n\n this.updateScreen(this.currentLocal)\n }", "initUser() {\n if (this.user) {\n return;\n }\n\n let user;\n if (this.storage) {\n user = this.storage.getItem('user');\n }\n\n if (!user) {\n user = window.prompt('Nom du participant ?');\n if (this.storage) {\n this.storage.setItem('user', user);\n }\n }\n\n this.user = user;\n }", "'submit .consent-form'(event) {\n event.preventDefault();\n\n if (!Meteor.userId()){\n let userSession = Session.get('username');\n\n //if there is no user, add a user\n if (!userSession){\n const random_username = Random.id();\n const random_password = Random.id();\n Session.setPersistent('password',random_password);\n //create a user in the user database to be tracked, then login, then redirect to instructions\n Meteor.call('users.createUser',random_username,random_password,()=>{\n Meteor.loginWithPassword(random_username,random_password, ()=>{\n FlowRouter.go('/instructions');\n });\n });\n } else {\n //if the user existed before without clearing the session\n Meteor.loginWithPassword(Session.get('username'),Session.get('password'), ()=>{\n FlowRouter.go('/exit');\n });\n }\n\n\n }\n\n }", "function setUserdataObject () {\n\t\t// Try and get user data from local storage. Returns null or data. \n\t\tvar storageData = getUserdataFromStorage();\n\n\t\t/**\n\t\t\tCall the web service only if:\n\t\t\t\tthey force an IP lookup via URL param, \n\t\t\t\tor no data was retrieved from storage, \n\t\t\t\tor storage data was compromised (Ex: user screws with localstorage values)\n\t\t\tElse the user had valid stored data, so set our user obj.\n\t\t**/\n\t\tif (ipForced !== \"\" || !storageData || !storageData.information_level) {\n\t\t\trequestUserdataFromService();\n\t\t}\n\t\telse {\n\t\t\tpopulateUserObject(storageData);\n\t\t}\n\t}", "function userpopulate() {\n\tif (currentuser.uname != undefined) {\n\t\tcurrentuser.seshon = true;\n\t\tvar currentuserphp = JSON.stringify(currentuser);\n\t\te.ajfetch(\"servercookie.php\", currentuserphp, undefined);\n\t\tclearInterval(loginverify);\n\t\tdocument.getElementById(\"loginbox\").style.display = \"none\";\n\t\tdocument.getElementById(\"clearcookie\").style.display = \"inline-block\";\n\t\tdocument.getElementById(\"headline\").innerHTML = \"Welcome, \" + currentuser.firstname + \", \" + currentuser.rank + \" of the realm!\";\n\t}\n}", "_initExternalUser() {\n if (!this.options.isLoggedIn) {\n this._userCard = false\n this._triggerRegistrationModal = true\n }\n }", "function getAndUpdateUserProfile(){\n\tgetUserId(appendUserAnimations);\n\t// getUserId(appendUserArtwork);\n\twindow.location.replace('pick.html');\n}", "function activateUser(){\n if (!userActivated){\n userActivated = true;\n reset();\n }\n}", "function initUserPage() {\n const id = window.location.pathname.substring(6); // Remove '/user/'\n $.ajax('/api/users/' + id)\n .done((user) => {\n $('#user-loading').hide();\n $('#user-page').show();\n configureButtons(user);\n configureUserProfile(user);\n configurePostUrl(id);\n })\n .fail(() => {\n $('#user-loading').hide();\n $('#user-not-found').show();\n });\n}", "function initializeUserHandle() {\n var cookie = getTokenFromCookie();\n if (cookie !== \"\" && cookie !== null) {\n getUserHandleFromToken(cookie); \n }\n}", "function userSetup(req, res, next) {\n if (!req.session.user) {\n req.session.user = {\n id: null,\n first_name: '',\n last_name: '',\n email: '',\n loggedIn: false\n }\n }\n next()\n}", "function renderPostInitialSetup( req, res ){\n\n // check if a user exists\n konter.db.model('User').find({}, function( err, users ){\n\n if( users.length > 0 )\n return res.redirect( '/login' );\n\n createNextGroup( 0, ['admins', 'editors', 'users'], [], req, res );\n\n });\n\n}", "function setCurrentUser(user) {\r\n currentuser = user;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift out the process
function shift() { // check if we can run an other process if( tasks.length > 0 && active < concurrency && true === next() ) { // Retrieve the process var process = tasks.shift(); // Execute the task if('function' === typeof process) { process(); } } }
[ "function shift() {\n // check if we can run an other process\n if( \n tasks.length > 0 &&\n active < concurrency &&\n true === next()\n ) {\n // Retrieve the process\n var process = tasks.shift();\n\n // Execute the task\n if(typeof process === 'function') {\n process();\n }\n }\n }", "function shiftUp() {\n shift = false;\n }", "shiftOut() {\n this._terminal.setgLevel(1);\n }", "function queueOut(Rd) {\n }", "function shift() {\n\t\t\t\tlines.shift();\n\t\t\t}", "function shift() {\n lines.shift();\n }", "suspend() {\n\t\tthis.leave();\n\t\tprocess.once('SIGCONT', this.onContinue);\n\t\tprocess.kill(process.pid, \"SIGTSTP\");\n\t}", "emitInterrupt(source, interrupt) { // takes the interrupt and the source process and pass them along to the scheduler\n const sourceIndex = this.processes.indexOf(source); // get the index of the process of the queue\n this.processes.splice(sourceIndex, 1); // array splice; remove from the queue it's in \n this.scheduler.handleInterrupt(this, source, interrupt); \n }", "shift(action, next, nextEnd) {\n let start = this.pos;\n if (action & 131072 /* Action.GotoFlag */) {\n this.pushState(action & 65535 /* Action.ValueMask */, this.pos);\n }\n else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift\n let nextState = action, { parser } = this.p;\n if (nextEnd > this.pos || next <= parser.maxNode) {\n this.pos = nextEnd;\n if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))\n this.reducePos = nextEnd;\n }\n this.pushState(nextState, start);\n this.shiftContext(next, start);\n if (next <= parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n else { // Shift-and-stay, which means this is a skipped token\n this.pos = nextEnd;\n this.shiftContext(next, start);\n if (next <= this.p.parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n }", "function shiftToNextTask() {\n if (debug) {\n API.sendChatMessage(\"[DEBUG] SHIFTED TO NEW OBJECTIVE\");\n }\n if (positions[0] === null) {\n if (marker !== null) {\n cleanup();\n }\n return;\n }\n if (marker !== null) {\n API.deleteEntity(marker);\n }\n if (blip !== null) {\n API.deleteEntity(blip);\n }\n switch (positionsTypes[0]) {\n case \"Waypoint\":\n drawWaypoint();\n return;\n case \"Destroy\":\n drawDestroy();\n return;\n case \"Capture\":\n drawCapture();\n return;\n case \"Hack\":\n drawHack();\n return;\n }\n}", "shiftIn() {\n this._terminal.setgLevel(0);\n }", "shift(action, next, nextEnd) {\n let start = this.pos;\n if (action & 131072 /* GotoFlag */) {\n this.pushState(action & 65535 /* ValueMask */, this.pos);\n }\n else if ((action & 262144 /* StayFlag */) == 0) { // Regular shift\n let nextState = action, { parser } = this.p;\n if (nextEnd > this.pos || next <= parser.maxNode) {\n this.pos = nextEnd;\n if (!parser.stateFlag(nextState, 1 /* Skipped */))\n this.reducePos = nextEnd;\n }\n this.pushState(nextState, start);\n this.shiftContext(next, start);\n if (next <= parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n else { // Shift-and-stay, which means this is a skipped token\n this.pos = nextEnd;\n this.shiftContext(next, start);\n if (next <= this.p.parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n }", "shift(action, next, nextEnd) {\n let start = this.pos;\n if (action & 131072 /* Action.GotoFlag */) {\n this.pushState(action & 65535 /* Action.ValueMask */, this.pos);\n }\n else if ((action & 262144 /* Action.StayFlag */) == 0) { // Regular shift\n let nextState = action, { parser } = this.p;\n if (nextEnd > this.pos || next <= parser.maxNode) {\n this.pos = nextEnd;\n if (!parser.stateFlag(nextState, 1 /* StateFlag.Skipped */))\n this.reducePos = nextEnd;\n }\n this.pushState(nextState, start);\n this.shiftContext(next, start);\n if (next <= parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n else { // Shift-and-stay, which means this is a skipped token\n this.pos = nextEnd;\n this.shiftContext(next, start);\n if (next <= this.p.parser.maxNode)\n this.buffer.push(next, start, nextEnd, 4);\n }\n }", "exitSortOutputThrough(ctx) {\n\t}", "function ExecutionTerminatorChainware(){}", "exitMergeOutputThrough(ctx) {\n\t}", "onExit(type, err) {\n if (this._canExit)\n return;\n this._canExit = true;\n // Remove event listeners.\n process.removeListener('exit', this.onExit);\n // If queue length and not already in\n // exit loop call processQueue.\n if (this.queue.length) {\n this._canExit = false;\n this.processQueue(type, err);\n }\n // Otherwise if an error was passed\n // throw it otherwise exit.\n if (this._canExit) {\n this._onQueueEmpty();\n }\n }", "shiftRight() {\n this.manager.shiftRight(this);\n }", "workerExit(w) {\n gExitCounter.incr()\n cleanUpTrackedProcess()\n var w_info = tClosers[w.id] // the process should be here now if it is not undefined\n if ( w_info !== undefined ) {\n if ( w_info.request_disconnect || w_info.request_shutdown ) { // if we are removing this processes keep removing it\n setImmediate(clearOutStoppedProcesses) // this should have been done, but keep pushing on it\n } else { // this is a process we lost and did not attempt to remove\n process.nextTick(() => { workersFullHouse(this) })\n }\n } else {\n setImmediate(() => { healthCheck(this) }) // make sure that there are enough processes and that we are not keeping zombies around\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shifts event times by specified value
function shiftEventTimes() { var times = $(".fc-event-time"); for (var t = 0; t < times.size(); t++) { var oldTimes = $(times[t]).parent().html(); var newTimes = oldTimes; if (newTimes) { for (var i = 1; i < 13; i++) { var up = i+shift; if (up > 12) { up = up - 12; } newTimes = newTimes.replace(">" + i + ":", "> " + up + ":"); newTimes = newTimes.replace(">" + i + ":", "> " + up + ":"); newTimes = newTimes.replace("- " + i + ":", " - " + up + ":"); newTimes = newTimes.replace("- " + i + ":", " - " + up + ":"); } $(times[t]).parent().html(newTimes); } } $(".fc-event").css("font-size", "1em"); $(".fc-event").css("font-weight", "bold"); }
[ "changeTimeValue(e, timeValue) {\n if (e.target.textContent === '+') {\n timer[timeValue]++;\n ui.updateUiElement(ui[timeValue], timer[timeValue])\n console.log(timer[timeValue]);\n } else {\n timer[timeValue]--;\n if (timer[timeValue] < 1) {\n timer[timeValue] = 1;\n }\n ui.updateUiElement(ui[timeValue], timer[timeValue])\n console.log(timer[timeValue]);\n }\n }", "shift(delta) { start+=delta }", "function changePitchShift(e) {\n // limiting the new pitch shift value\n let value = parseInt(e.target.value);\n pitchShift += value;\n if (pitchShift < -12) pitchShift = -12;\n else if (pitchShift > 12) pitchShift = 12;\n // displaying the value\n document.getElementById(\"pitchShiftDisplay\").innerText =\n \" pitch shift: \" + (pitchShift < 1 ? pitchShift : \"+\" + pitchShift) + \" \";\n // sending the new value to the audio node\n audioNode.sendMessageToAudioScope({ pitchShift: pitchShift });\n}", "shift(delta) {\n this.start+=delta\n this.end+=delta\n }", "function shiftEvents(events){\n var now = new Date()\n\n for(var i = 0; i < events.length; i++){\n var event = events[i]\n\n var event_length = event.getEndTime().getTime() - event.getStartTime().getTime()\n \n //If it's before start of day, you want to move the event to SOD same day\n //If it's after SOD, but you get here, then it must be passed EOD, so you want to move the event to SOD of next day\n var start = new Date()\n\n if(now.getHours() > LIVE_SOD) start.setDate(now.getDate() + 1);\n\n start.setHours(LIVE_SOD)\n start.setMinutes(0)\n start.setSeconds(0)\n\n event.setTime(start, new Date(start.getTime() + event_length))\n\n }\n}", "_modifyTimestampBy(amount, unit) {\n // Modify the current timestamp\n this._safelyModifyTimestampBy(amount, unit);\n this._updateSecondTimestamp();\n\n // Notify the calendar to update its timestamp\n this.fireEvent(\"navigate\", {\n timestamp: this.timestamp\n });\n }", "shift(dt) {\n const { beats } = this.block.metadata;\n\n for (let i = 0; i < beats.length; i++)\n beats[i].time += dt;\n\n this._beats.update();\n this.block.snap();\n }", "function cubism_metricShift(request, offset) {\n return function(start, stop, step, callback) {\n request(new Date(+start + offset), new Date(+stop + offset), step, callback);\n };\n}", "shiftOffset(item, offset) {\n // When modifying dates explicitly using the setters is important\n // since those may triggers e.g. calIRecurrenceInfo::onStartDateChange\n // or invalidate other properties. Moreover don't modify the date-time objects\n // without cloning, because changes cannot be calculated if doing so.\n if (item.isEvent()) {\n let date = item.startDate.clone();\n date.addDuration(offset);\n item.startDate = date;\n date = item.endDate.clone();\n date.addDuration(offset);\n item.endDate = date;\n } else {\n /* isToDo */\n if (item.entryDate) {\n let date = item.entryDate.clone();\n date.addDuration(offset);\n item.entryDate = date;\n }\n if (item.dueDate) {\n let date = item.dueDate.clone();\n date.addDuration(offset);\n item.dueDate = date;\n }\n }\n }", "function addMinutes() {\r\n //if ctrl is pressd\r\n if (ctrl == 1 && shift != 1) {\r\n //if minutesis above or equl to 49 set minutes to 0 and check hours\r\n if (minutes >= 49) {\r\n minutes = 0;\r\n //if hours is above or equel to 99 set hours to 99\r\n if (hours >= 99) {\r\n hours = 99;\r\n update();\r\n }\r\n //else add 1 to hours\r\n else {\r\n hours++;\r\n minutes = 0;\r\n update();\r\n }\r\n }\r\n //else add 10 to minutes\r\n else {\r\n minutes = minutes + 10;\r\n update();\r\n }\r\n }\r\n //if shift is pressd\r\n else {\r\n //if minutes above or equl to 59 set minutes to 0 and check hours\r\n if (minutes >= 59) {\r\n minutes = 0;\r\n //if hours is above or equel to 99 set hours to 99\r\n if (hours >= 99) {\r\n hours = 99;\r\n update();\r\n }\r\n //else add 1 to hours\r\n else {\r\n hours++;\r\n minutes = 0;\r\n update();\r\n }\r\n }\r\n //else add 1 to minutes\r\n else {\r\n minutes++;\r\n update();\r\n }\r\n }\r\n}", "function FiveFieldTimeAdvanceToMondayMorning(arr) {\n\tvar day = FiveFieldTimeGetDay(arr);\n\tif (day==1) return;\n\n\tif (day==0) \n\t\tFiveFieldTimeIncrease(arr, 1);\n\telse\n\t\tFiveFieldTimeIncrease(arr, 8-day);\n\t\t\n\tarr[3] = 0;\n\tarr[4] = 0;\n}", "function timestampShift (word,shift){ \n\n // if shift > 0 means there is an overlap\n if (shift>0) {\n word.start+=shift;\n word.end+=shift\n }\n return word\n}", "function setTime(time) { action.time = time; }", "set constrainDragToTimeSlot(value) {\n const axis = this.client.isHorizontal ? 'lockX' : 'lockY';\n\n this._constrainDragToTimeSlot = value;\n\n if (this.drag) {\n this.drag[axis] = value;\n }\n }", "function shiftPoints (start, stop) {\r\n\r\n loopWaypoints (function f(waypoint) { //Go through waypoints\r\n\r\n //Check if we're shifting forewards or backwards\r\n if(start - stop > 0) {\r\n if(waypoint.pointNumber > stop && waypoint.pointNumber <= start) { //if between start and stop\r\n changeNumber(waypoint, waypoint.pointNumber - 1); //shift\r\n }\r\n }\r\n else {\r\n if(waypoint.pointNumber >= start && waypoint.pointNumber < stop) { //if between start and stop\r\n changeNumber(waypoint, waypoint.pointNumber + 1); //shift\r\n }\r\n }\r\n });\r\n }", "shift(delta) {\n let activeLocation = this.props.location[this.props.activeIndex];\n let newActiveLocation = activeLocation + delta;\n\n if (newActiveLocation < 0 ||\n newActiveLocation >= this.props.word.length) {\n // This isn't a valid shift\n return;\n }\n\n let newLocation = this.props.location.map((loc) => {\n if (loc == activeLocation) {\n return newActiveLocation;\n }\n if (loc == newActiveLocation) {\n return activeLocation;\n }\n return loc;\n });\n\n this.props.dispatch({\n type: 'SET_LOCATION',\n location: newLocation,\n });\n }", "function udpateTime(){\n if(minutes + 1 === 60)\n setHours((hours + 1) % 24)\n setMinutes((minutes + 1) % 60)\n }", "function hours_change(elt,workshift,prev_val, interval_change) {\n var row = elt.parentNode.parentNode.childNodes;\n for (var ii = 0; ii < 8; ii++) {\n workshift['day'] = ii;\n var temp = workshift['hours'];\n if (typeof(interval_change) == 'undefined') {\n if (typeof(prev_val) != 'undefined') {\n workshift['hours'] = prev_val;\n }\n else {\n workshift['hours'] = 0;\n }\n }\n //remove the old workshift\n assign_shift(row[ii+3].firstChild.value,workshift,false);\n //add in the new workshift\n workshift['hours'] = temp;\n assign_shift(row[ii+3].firstChild.value,workshift,true);\n }\n}", "function tap(event, sign) {\n controls.manualMoveRate[0] += sign;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse Github URL text
function parseGithubURL(url_input) { var data = { 'user': '', 'repo': '', 'path': '', 'name': '' }; if (url_input == null) { return data; } // attempt a single file match // example: https://github.com/tiggerntatie/brython-student-test/blob/master/hello.py // example: https://github.com/tiggerntatie/hhs-cp-site/blob/master/hhscp/static/exemplars/c02hello.py // example subtree: https://github.com/tiggerntatie/hhs-cp-site/tree/master/hhscp/static/exemplars var gittreematch = url_input.match(/.*github\.com\/([^/]+)\/([^/]+)\/tree\/master\/(.+)/); var gitfilematch = url_input.match(/.*github\.com\/([^/]+)\/([^/]+)\/blob\/master\/([^/]+)/); var gittreefilematch = url_input.match(/.*github\.com\/([^/]+)\/([^/]+)\/blob\/master\/(.+)\/([^/]+)/); var gitrepomatch = url_input.match(/.*github\.com\/([^/]+)\/([^/]+).*/); var gisturlmatch = url_input.match(/.*gist\.github\.com(\/[^/]+)?\/([0-9,a-f]+)/); var gistmatch = url_input.match(/^[0-9,a-f]+$/); if (gisturlmatch || gistmatch) { var gist = gisturlmatch ? gisturlmatch[2] : gistmatch[0]; data = { 'user': '', 'repo': '', 'path': '', 'name': gist }; } else if (gitrepomatch) { data = { 'user': gitrepomatch[1], 'repo': gitrepomatch[2], 'path': '', 'name': '' }; if (gittreematch) { data['path'] = gittreematch[3]; } if (gittreefilematch) { data['path'] = gittreefilematch[3]; data['name'] = gittreefilematch[4]; } else if (gitfilematch) { data['name'] = gitfilematch[3]; } } return data; }
[ "function parseGithubUrl(urlStr) {\n let match;\n for (const pattern of githubPatterns) {\n match = urlStr.match(pattern);\n if (match) {\n break;\n }\n }\n if (!match)\n throw new Error(invalidGithubUrlMessage(urlStr));\n let [, auth, username, reponame, treeish = `master`] = match;\n const { commit } = querystring_1.default.parse(treeish);\n treeish =\n // New style:\n // The URLs have already been normalized by `gitUtils.resolveUrl`,\n // so it's certain in the context of the `GithubFetcher`\n // that the `commit` querystring parameter exists\n commit\n // Old style:\n // Shouldn't ever be needed by the GithubFetcher\n || treeish.replace(/[^:]*:/, ``);\n return { auth, username, reponame, treeish };\n}", "function parseURL(url){\n\tif(url.split(\"github.com/\").length !== 2)\n\t\treturn {\"success\": false};\n\n\tvar path = url.split(\"github.com/\")[1].split(\"/\");\n\tvar user = path[0];\n\tvar repos = path[1];\n\tvar fp = url.split(\"master/\")[1];\n\n\treturn {\"success\": true, \"user\": user, \"repos\": repos, \"fp\": fp};\n}", "function parseRepoUrl(url) {\n if (typeof url !== \"string\" || url.length === 0)\n throw new Error(\"type error\");\n var parsedUrl = new URL(url, \"https://github.com\");\n var pathParts = parsedUrl.pathname.split(\"/\");\n if (pathParts.length < 2) {\n throw new Error(\"invalid url format\");\n }\n // Last 2 parts of url path are the user and repo\n var user = pathParts[pathParts.length - 2].trim();\n var repo = pathParts[pathParts.length - 1].trim();\n if (user.length === 0 || repo.length === 0) {\n throw new Error(\"invalid url format\");\n }\n return user + \"/\" + repo;\n}", "function parseInternalRepoLink() {\n let url = $ctrl.internalScmRepositoryUrl;\n let protocol = url.split('://')[0];\n let base = url.split('://')[1].split('/')[0];\n let project = url.split(base + (['https', 'http'].includes(protocol) ? '/gerrit/' : '/'))[1];\n return 'https://' + base + '/gerrit/gitweb?p=' + project + ';a=summary';\n }", "function analyzeLink(urlStr) {\n var url = $url.parse(urlStr);\n\n var domain = url.hostname;\n var pathParts = url.pathname.split('/');\n // lose the empty string from the part. harmless if already empty\n pathParts.shift();\n\n var githubUser, githubRepo, pullRequestNum, buildId;\n\n if (domain === 'github.com' && pathParts.length >= 2) {\n githubUser = pathParts[0];\n githubRepo = pathParts[1];\n\n if (pathParts.length >= 4 && pathParts[2] === 'pull') {\n pullRequestNum = parseInt(pathParts[3], 10);\n\n return {\n type: 'pull-request',\n user: githubUser,\n repo: githubRepo,\n number: pullRequestNum\n };\n }\n }\n else if (domain === 'travis-ci.org' && pathParts.length >= 3) {\n githubUser = pathParts[0];\n githubRepo = pathParts[1];\n\n buildId = parseInt(pathParts[3], 10);\n\n return {\n type: 'travis-build',\n user: githubUser,\n repo: githubRepo,\n id: buildId\n };\n }\n\n return {\n type: 'unknown',\n err: 'unsupported-url',\n errArgs: urlStr\n };\n}", "function convertGithub(url) {\n var a = document.createElement('a');\n a.href = url;\n if (a.hostname == \"github.com\") {\n a.hostname = \"raw.githubusercontent.com\";\n a.pathname = a.pathname.replace(\"/blob\", \"\");\n }\n return a.href;\n}", "function parseTextFileLinesFromGitHub(sourcePageUrl) {\n const codeLineRegexPattern = 'class=\"blob-code blob-code-inner js-file-line\">(.*?)</td>';\n const codeLineTDRegex = new RegExp(codeLineRegexPattern, 'g');\n const codeLineRegex = new RegExp(codeLineRegexPattern);\n\n\n\n return fetch(sourcePageUrl, {credentials: \"include\", redirect: \"follow\"})\n .then(response => response.text())\n .then(responseText => {\n //parse the page source and extract all code lines, which can be found with css selector td.blob-code\n //this is because the raw url can't be accessed due to Content-Security-Polocy\n //class=\"blob-code blob-code-inner js-file-line\"> port = 9982</td>\n\n var codeLineTableCells = responseText.match(codeLineTDRegex) || [];\n var codeLines = codeLineTableCells.map(codeLine=>{\n var textLine = codeLine.match(codeLineRegex)[1].trim();\n if(textLine.startsWith(\"<span\")) {\n textLine = textLine.replace(/<span[^>]+>/g, '').replace(/<\\/span[^>]*>/g, '').replace(/\\n/g, '');\n }\n textLine = textLine.replace(/&quot;/g, '\"').replace(/&#39;/g, '\\'');\n return textLine;\n });\n return codeLines;\n })\n }", "function isGithubComURL(href) {\n return href.match(/^http[s]?\\:\\/\\/(raw\\.)?github.com\\//);\n}", "function parseUrl(url) {\n // input url format: https://yourdomain.atlassian.net/projects/XX\n const matches = url.match(/(https?:\\/\\/)(.+?)(\\/.+)?\\/(projects|browse)\\/([\\w-]+)/);\n if (matches && matches.length === 6) {\n return {protocol: matches[1], domain: matches[2], contextPath: matches[3] || '', projectKey: matches[5]};\n } else {\n throw new Error('Unexpected URL Format');\n }\n}", "static parse(text) {\n let links = {};\n // First, sanitize any HTML\n text = text.replace('<', '&lt;').replace('>', '&gt;');\n // Then, get the list of references, removing them from the text\n text = text.replace(this.REGEX_REF, (_, k, v) => {\n links[k] = v;\n return '';\n });\n // Finally, replace each tagged part of text with a link element. If a tag has\n // an invalid reference, it is ignored.\n return text.replace(this.REGEX_LINK, (match, t, k) => links[k]\n ? `<a href='${links[k]}' target=\"_blank\" rel=\"noopener\">${t}</a>`\n : match);\n }", "static getReleaseNameFromGitHubAndGitLabFeedLink(link) {\n const parts = link.split('/');\n return `${parts[3]}/${parts[4]}`;\n }", "function extractTopicLink(html){ // page -> github.com/topics\n let selectorTool = cheerio.load(html);\n let topics= selectorTool(\".col-12.col-sm-6.col-md-4.mb-4 a\");\n for(let i=0; i<topics.length; i++){\n let topiclink = \"https://github.com\" + selectorTool(topics[i]).attr(\"href\"); // got topic link page\n getRepoHelper(topiclink);\n }\n}", "async function processUrl(text) {\n let finalUrl;\n await request(reposUrl, requestOptions, (error, response, body) => {\n if (error) {\n console.error(error);\n }\n\n const linksArray = [];\n const gotJSON = body;\n for (let i = 0; i < gotJSON.length; i++) {\n const link = gotJSON[i].name;\n linksArray.push(link);\n }\n\n const matches = similarity.findBestMatch(text, linksArray);\n const bestMatch = matches.bestMatch.target;\n finalUrl = baseUrl + bestMatch;\n console.log(`Best match: ${bestMatch}, url ${finalUrl} will be queried`);\n });\n\n return finalUrl;\n}", "function extract( text ) {\n var results = new Array();\n\n //\n // Regexps for different linking formats.\n //\n var regexp = [\n /<a([^>]+)>([^<]+)<\\/a>/gi,\n /\\[url=(.+?)\\](.+?)\\[\\/url\\]/gi,\n /\\[link=(.+?)\\](.+?)\\[\\/link\\]/gi,\n /\\[(https?:\\/\\/[^ \\t]+) ([^\\]]+)\\]/gi,\n ];\n\n //\n // Look for each regexp in our list.\n //\n regexp.forEach(function(test){\n\n var m;\n\n while( m = test.exec(text) )\n {\n //\n // Add the result to our return values.\n //\n if (m && m[2] )\n {\n var h = new Object();\n h['link'] = m[1].trim()\n h['text'] = m[2].trim()\n results.push( h );\n console.log( \"Link : \" + h['link'] + \" Anchor:\" + h['text'] );\n }\n }\n });\n return( results );\n }", "function parseRemote(input) {\n var match = null;\n\n // ssh\n if (/git@([\\w\\.]+\\.\\w{2,4})\\:(\\w+)\\/(\\w+)\\.git/.test(input)) {\n match = /git@([\\w\\.]+\\.\\w{2,4})\\:(\\w+)\\/(\\w+)\\.git/.exec(input);\n }\n\n // https\n else if (/https:\\/\\/([\\w\\.]+\\.\\w{2,4})\\/(\\w+)\\/(\\w+)\\.git/.test(input)) {\n match = /https:\\/\\/([\\w\\.]+\\.\\w{2,4})\\/(\\w+)\\/(\\w+)\\.git/.exec(input);\n }\n\n return match ? { host: match[1], user: match[2], repo: match[3] } : null;\n}", "function parseRepo(repo) {\n return repo.split(\"/\");\n}", "function gitUrl (thing) {\n\t return unemptyString(thing) && /^git\\+(ssh|https?):\\/\\/.+/.test(thing);\n\t }", "function extractRepoLink(html){ // page -> github.com/topics/topicName\n let selectorTool = cheerio.load(html);\n let topicName = selectorTool(\".h1-mktg\").text().trim(); //Extacted Topic name & trimmed it because it had many spaces\n\n // console.log(topicName);\n\n dirCreator(topicName); //creating folder named based on \"topicName\"\n\n let allRepos = selectorTool(\".border.rounded.color-shadow-small.color-bg-secondary.my-4\"); \n\n for(let i=0;i<8;i++){\n let allATag = selectorTool(allRepos[i]).find(\"a\"); // got anchortags \n let repositoryLink = selectorTool(allATag[1]).attr(\"href\"); // selected 2nd anchor tag (repo link)\n let repoName = repositoryLink.split(\"/\").pop(); // eg -> kc0112/Algorithms (repoLink) -> Algorithms (repoName)\n repoName = repoName.trim(); // removed spaces\n\n fileCreator(repoName, topicName); // create file on path \"./topicName/repoName.json\"\n\n repositoryLink = \"https://github.com\" + repositoryLink; // full link\n getIssue(repositoryLink,topicName,repoName); \n }\n}", "function parseMarkdownUrls(opts) {\n let regex = (opts && opts.regex) || regexes.general;\n let text = elem.input.value;\n\n return (text.match(regex) || []);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getFirstChecked(tblName) return the first Checked row index
function getFirstChecked(tblName) { for (var i=1; i<tblName.rows.length; i++) { if (tblName.rows(i).cells(0).firstChild.checked) return i; } return -1; }
[ "function getFirstCheckedId(tblName)\n\t{\n\t\tfor (var i=1; i<tblName.rows.length; i++)\n\t\t{\n\t\t\tif (tblName.rows(i).cells(0).firstChild.checked) return tblName.rows(i).cells(0).firstChild.name;\n\t\t}\n\t\treturn null;\n\t}", "function getChecked(tblName, rowIndex)\n\t{\n\t\treturn tblName.rows(rowIndex).cells(0).firstChild.checked;\n\t}", "function getFirstRowChecked(){\n\tvar theForm = basefrm.list;\n\tfor (var i = 0; i < theForm.length; i++)\n\t{\n\t\tif (theForm.elements[i].checked == true){\t\n\t\t\treturn (theForm.elements[i]);\n\t\t}\n\t}\n\treturn null;\n}", "function getFirstSelectedCheckbox() {\n\n\treturn document.querySelector('.tableCheck:checked').getAttribute('data-id');\n}", "function getCheckBoxId(tblName, rowIndex)\n\t{\n\t\treturn tblName.rows(rowIndex).cells(0).firstChild.name;\n\t}", "getFirstCompletedTaskIndex() {\n let firstCompletedTaskIndex = -1;\n for (let i = 2; i < this.table.childNodes.length && firstCompletedTaskIndex === -1; i += 1) {\n if (this.table.childNodes[i].checked === true) firstCompletedTaskIndex = i;\n }\n\n return firstCompletedTaskIndex;\n }", "function checkRow(tblName, rowIndex, checkValue)\n\t{\n\t\ttblName.rows(rowIndex).cells(0).firstChild.checked = checkValue;\n\t}", "function getDoIOwnFromChecked(tblName)\n\t{\n\t\tfor (var i=1; i<tblName.rows.length; i++)\n\t\t{\n\t\t\tif (tblName.rows(i).cells(0).firstChild.checked && tblName.rows(i).cells(0).firstChild.value != \"true\") return false;\n\t\t}\n\t\treturn true;\n\t}", "function firstSelectedDay(tdEle) {\n\tvar boxes = tdEle.children;\n\tfor (i = 0; i < 7; i++) {\n\t\tif (boxes[i].checked)\n\t\t\treturn i;\n\t}\n\treturn -1;\n}", "function setCheckHeading(tblName, checkedTF)\n\t{\n\t\tif (getTableSize(tblName) == 0) \n\t\t{\n\t\t\ttblName.rows(0).cells(0).firstChild.checked = false;\n\t\t\treturn;\n\t\t} \n\n\t\ttblName.rows(0).cells(0).firstChild.checked = checkedTF;\n\t}", "function delRow(tableID,checkBoxName)\n{\n\tvar objBox = document.all(checkBoxName) ;\n\tif(objBox != null)\n\t{\n\t\tif(objBox.length != null)\n\t\t{\n\t\t\tfor(var i=0;i<objBox.length;i++)\n\t\t\t{\n\t\t\t\tif(objBox[i].checked == true)\n\t\t\t\t{\n\t\t\t\t\tif( i == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\talert(\"The First Row Must Be Keep !\") ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById(tableID).deleteRow(i+1);\n\t\t\t\t\t\tdelRow(tableID,checkBoxName);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(objBox.checked == true)\n\t\t\t{\n\t\t\t\t//document.getElementById(tableID).deleteRow(0);\n\t\t\t\talert(\"The First Row Must Be Keep !\") ;\n\t\t\t}\n\t\t}\n\t}\n}", "_isFirstRow(index){return 0===index}", "function getNumberOfChecks(tblName)\n\t{\n\t\tvar count=0;\n\t\tfor (var i=1; i<tblName.rows.length; i++)\n\t\t{\n\t\t\tif (tblName.rows(i).cells(0).firstChild.checked) count++;\n\t\t}\n\t\treturn count;\n\t}", "function datagrid_get_selected_row(table) {\n\tvar rows = table.fnGetNodes();\n\tfor (var i = 0; i < rows.length; i++) {\n\t\tvar row = rows[i];\n\t\tif (row && $(row).hasClass('datagrid_row_selected'))\n\t\t\treturn row;\n\t}\n\treturn null;\n}", "first(){this._focusRowByIndex(0)}", "function _selectFirstRow() {\n\treturn this.rows[0];\n}", "function getRowIndex(table) {\n var rowcount = table.rows.length;\n if (rowcount===2) {\n // start at 1 to skip the header\n var rowIndex = 1;\n } else {\n /// append row to table from the bottom\n var rowIndex = rowcount-1;\n }\n return rowIndex\n}", "function checkBoxGetChecked (checkBox){\n \n return checkBox[0][0].checked;\n}", "function getRowNum (tName, tId, uId)\n{\n var rNum = null;\n var p = new TableProxy(tName); \n var rCount = p.getLength(); \n for(var i=0; i<rCount; i++)\n {\n var field = p.getFormElement(uId , i);\n if (field != null)\n {\n if (field.id == tId)\n {\n rNum = i; \n break;\n }\n }\n }\n return rNum;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
log an input error to console
function logInputErr(err) { console.log(chalk.red(err)); }
[ "function getInputError() {\n console.log(`> Hey ${process.env['USERNAME']}, make sure your input is one of the following: \"${userArgs.twitter}\", \"${userArgs.spotify}\", \"${userArgs.omdb}\", \"${userArgs.do}\".`);\n space();\n read.close();\n}", "function seeError(command, input){\n logMsg(\"You've entered an invalid command.\");\n console.log(\"You've entered an invalid command.\");\n console.log(\"Enter one of the following commands, replacing the text with a search string (no brackets or quotation marks needed):\");\n console.log(\"node liri.app concert-this [artist name]\");\n console.log(\"node liri.app spotify-this-song [song and/or artist name]\");\n console.log(\"node liri.app movie-this [movie name]\");\n console.log(\"node liri.app do-what-it-says\");\n}", "function inputError(val){\n console.log(\"USER INPUT ERROR!\");\n console.log(\"event key: \"+val);\n // show modal dialog where the input was incorrectly filled in\n // destroy/erase once user starts typing again\n}", "function error () {\n // eslint-disable-next-line no-console\n console.error(arguments);\n }", "function displayError(){\r\n console.log(\"You need to enter one character at a time\")\r\n}", "function put_error(line, message){\n var str = \"ERROR: \" + line + \": Type-Check: \" + message;\n console.log(str);\n process.exit(1);\n}", "function writeError() {\r\n var message = prepareMessage(arguments);\r\n console.error(message);\r\n }", "function userCommandError(){\n console.log(`\n \\n-----------------------------------\\n\n \\nPlease input a Liri Command:\n \\n-----------------------------------\\n\n \\nconcert-this\\n\n \\nspotify-this-song\\n\n \\nmovie-this\\n\n \\ndo-what-it-says\\n\n \\n-----------------------------------\\n\n `)\n}", "function error() {\n\tlog(1, arguments);\n}", "function readinError(error, msg) {\n if (error) {\n console.error(msg);\n }\n }", "function errorln (message){\r\n\tjava.lang.System.err.println(message)\r\n\t}", "function printEror(error){\n console.error(error.message);\n}", "function printError (error){\r\n console.error(error.message);\r\n}", "function showerr() {\n console.log(\"error\")\n}", "function inputwarn(inpel){\n\t\n}", "logInput(){\n this.log('- INPUT');\n this.log(`${this.formatFilePaths(this.input)}`);\n }", "static error(...args) {\n if (this.toLog('ERROR')) {\n console.error.apply(console, arguments);\n }\n }", "function printError(error){\n console.error(\"Error gek: \" + error.message);\n}", "function logInput(logText) {\n fs.appendFile(\"log.txt\", logText, function (error) {\n // If there is an error output the following\n if (error) {\n return console.log(\"Error occurred: \" + error);\n }\n console.log(\"User input logged\");\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the line style to default.
reset() { super.reset(); // Override default line style color this.color = 0x0; /** * The width (thickness) of any lines drawn. * * @member {number} * @default 0 */ this.width = 0; /** * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). * * @member {number} * @default 0 */ this.alignment = 0.5; /** * If true the lines will be draw using LINES instead of TRIANGLE_STRIP * * @member {boolean} * @default false */ this.native = false; }
[ "reset()\n {\n super.reset();\n\n // Override default line style color\n this.color = 0x0;\n\n /**\n * The width (thickness) of any lines drawn.\n *\n * @member {number}\n * @default 0\n */\n this.width = 0;\n\n /**\n * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner).\n *\n * @member {number}\n * @default 0\n */\n this.alignment = 0.5;\n\n /**\n * If true the lines will be draw using LINES instead of TRIANGLE_STRIP\n *\n * @member {boolean}\n * @default false\n */\n this.native = false;\n }", "resetStyle()\n {\n this.setStyle(this._defaultValue);\n }", "reset() {\n super.reset(), this.color = 0, this.alignment = 0.5, this.width = 0, this.native = !1, this.cap = LINE_CAP.BUTT, this.join = LINE_JOIN.MITER, this.miterLimit = 10;\n }", "function resetLine() {\n li = 0;\n prevX = null;\n prevY = null;\n}", "reset() {\n deepCopyProperties(this, _TextStyle2.defaultStyle, _TextStyle2.defaultStyle);\n }", "function resetOffsetLine() {\n offsetLineCoordinates.x1 = 0;\n offsetLineCoordinates.x2 = 0;\n offsetLineCoordinates.y1 = 0;\n offsetLineCoordinates.y2 = 0;\n }", "reset() {\n Utils.deepCopyProperties(this, defaultStyle, defaultStyle);\n }", "function clear_line_highlight() {\n\n if (hilighted_line !== null) {\n hilighted_line.setStyle(NORMAL_LINE)\n .setOffset(NORMAL_LINE.offset);\n hilighted_line = null;\n }\n\n}", "resetPen() {\n this.row_ = 0;\n this.col_ = 0;\n this.underline_ = false;\n this.italics_ = false;\n this.textColor_ = shaka.cea.CeaUtils.DEFAULT_TXT_COLOR;\n this.backgroundColor_ = shaka.cea.CeaUtils.DEFAULT_BG_COLOR;\n }", "function resetLineDisplay() {\n var tempLineDisplay = [];\n for (var i = 0; i < Trends.MaxLineNumber; i++) {\n tempLineDisplay[i] = true;\n }\n DataViz.mainApp.Configuration.set(DataViz.Config.Trends.wellKnownKeys.lineDisplay, tempLineDisplay);\n }", "function lineStyle(style) {\t\t\n\t\tcontext.lineCap = cap; \n\t}", "applyLineStyles() {\n\n for ( var i = 0; i < this.lines.length; i++ ) {\n this.applyLineStyle( this.lines[ i ] );\n }\n }", "applyLineStyle() {\n const ctx = this.checkContext();\n const render_options = this.render_options;\n\n if (render_options.line_dash) {\n ctx.setLineDash(render_options.line_dash);\n }\n\n if (render_options.line_width) {\n ctx.setLineWidth(render_options.line_width);\n }\n\n if (render_options.rounded_end) {\n ctx.setLineCap('round');\n } else {\n ctx.setLineCap('square');\n }\n }", "function resetLineWidthFilter() {\n\t\t\toldLineWidth = -1.0\n\t\t}", "function reset_line_color() {\n for (let i = 0; i<attackableLines.length; i++) {\n let currLine = attackableLines[i];\n changeLines(\"black\", currLine);\n }\n map.dataProvider.zoomLevel = map.zoomLevel();\n map.dataProvider.zoomLatitude = map.zoomLatitude();\n map.dataProvider.zoomLongitude = map.zoomLongitude();\n map.validateData();\n}", "function resetSelectedLine() {\n gMeme.selectedLineIdx = 0\n}", "function fixLineStyle(styleHost) {\n var style = styleHost.style;\n\n if (style) {\n style.stroke = style.stroke || style.fill;\n style.fill = null;\n }\n}", "function resetUnderline() {\n\tyesterday.style.textDecoration = \"none\";\n\ttoday.style.textDecoration = \"underline\";\n\ttomorrow.style.textDecoration = \"none\";\n}", "function reset_styles() {\n pointFeature.style({\n fill: true,\n fillColor: { r: 1.0, g: 0.839, b: 0.439 },\n fillOpacity: 0.8,\n radius: 5.0,\n stroke: true,\n strokeColor: { r: 0.851, g: 0.604, b: 0.0 },\n strokeWidth: 1.25,\n strokeOpacity: 1.0\n });\n pointFeature.draw();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
notify any observers on observer_id of the event related to job_id
notify_observers(job_event, job_id, observer_id) { var self = this; // If this run request includes an observer id, notify all // related endpoints that the new job has been started. if (_.has(self._observers, observer_id)) { logger.debug('Sending ' + job_event + ' for observer ' + observer_id); self._observers[observer_id].forEach(function(endpoint) { endpoint.send({type: job_event, job_id: job_id}); }); } }
[ "notify() {\n this.#observers.map((observer) => {\n observer.notify();\n });\n }", "notifyAllObservers() {\n for (let i = 0; i < this.observers.length; i++) {\n this.observers[i].notify(i);\n }\n }", "notifyObservers(arg) {\n for (let observer of this.observers) {\n observer.update(this, arg);\n }\n this.clearChanged();\n }", "notifyAllObservers(messageJson) {\n this.handlers.forEach(function(item) {\n item.notify(messageJson);\n });\n }", "notifyAll() {\n this.observers.forEach(observer => observer.update(this));\n }", "notifyObservers(event) {\n this.observers.forEach((observer) => observer.notify(event));\n }", "removeObserver(id) {\n this.observers = this.observers.filter(observer => observer.id !== id);\n }", "notifyObservers(message) {\n this.observers.forEach(observer => observer.cb(message));\n }", "notifyObservers(eventName, ...args) {\n for (const observer of this.observers_) {\n if (observer.__proto__.hasOwnProperty(eventName))\n observer.__proto__[eventName].call(observer, ...args);\n else if (observer.hasOwnProperty(eventName))\n observer[eventName].call(observer, ...args);\n }\n }", "notifyObsevable(noticia) {\n //para cada elemento de nuestro arreglo de observadores vamos a mandar la notificacion en este caso\n //yo la he llamado noticia para que fuera mas entendible\n this.observers.forEach((observer) => {\n observer.notify(noticia);\n });\n }", "function updateObservers(obj, observing_hash) {\n for (var key in observing_hash) {\n if (! observing_hash.hasOwnProperty(key)) { continue; }\n\n obj.addObserver(key, observing_hash[key]);\n }\n}", "startObservers() {\n var cbk = this._callback_queue;\n if (cbk) {\n for (var i = 0, l = cbk.length; i < l; i++) {\n cbk[i]();\n }\n this._callback_queue = undefined;\n }\n for (var obss = this._observers, i = 0, l = obss.length; i < l; i++) {\n obss[i].startObserving();\n }\n this.is_observing = true;\n }", "notifyObserversOfUpdate() {\n for (var observer of this.updateObservers) {\n observer.callback();\n }\n }", "notify() {\n this.subscribers.forEach(subscriber => {\n subscriber.update();\n });\n }", "function notifyObservers(){\n _.each(registeredObservers, function(callback){\n callback(leagues);\n });\n }", "notify(key, data) {\n if (this.subscribers[key] && this.subscribers[key].listeners.length > 0) {\n this.subscribers[key].listeners.forEach(listener => listener(data));\n }\n }", "notify () {\n for (var i = 0; i < this.subscribers.length; i++) {\n this.subscribers[i](this.updates.value);\n }\n }", "notify (artistId, subject, message, from)\n {\n const suscription = this.findArtistSuscription(parseInt(artistId));\n console.log(suscription);\n suscription.notifySubscripber(this.gmail, subject, message, from);\n }", "function updateJobNotifications(job_id) {\n\n // get the latest notifications:\n const line_number = (job_id in running_jobs_line_number) ? running_jobs_line_number[job_id] : 0;\n notifications_output = get_job_notifications(job_id, line_number);\n status_code = notifications_output.status;\n new_job_notifications = notifications_output.data;\n\n // extract the data:\n let messages = new_job_notifications.objects;\n let count = new_job_notifications.num_results;\n running_jobs_line_number[job_id] = (count == 0 ? 0 : messages[count-1].id);\n\n // extract the command name (or use cached one)\n const command_name = (job_id in running_jobs_command_names) ?\n running_jobs_command_names[job_id] : getCommandName(job_id);\n running_jobs_command_names[job_id] = command_name;\n\n // nested function to process the new messages:\n function process_messages(what_to_call, keywords){\n // loop through:\n for (let i = 0; i < count; i++) {\n // parse:\n let message = messages[i].procout;\n for (let j = 0; j < keywords.length; j++) {\n keyword = keywords[j];\n useful_message_position = message.search(keyword);\n if (useful_message_position != -1) {\n let timestamp = messages[i].timestamp;\n let notification = '[' + command_name + ' ' + timestamp + '] ' + message.substring(useful_message_position + keyword.length);\n what_to_call(notification);\n } // if\n } // for j\n } // for i\n } // process_messages\n\n // add all appropriate notifications to the message pane:\n notification_keywords = [\"PROGRESS: \", \"USER: \", \"ERROR: \"];\n process_messages(addNotification, notification_keywords);\n\n // display any error messages to the user in a popup message:\n //alert_keywords = [\"ERROR: \"];\n //process_messages(showWindowMessage, alert_keywords);\n\n // display errors:\n if (status_code != 200) {\n error = 'Error ' + status_code + ': ' + new_job_notifications.error;\n if (latest_jobs_error_message[job_id] != error) {\n showWindowMessage(error);\n latest_jobs_error_message[job_id] = error;\n }\n } // status code\n\n return count\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MySQL checking pool connection
async function checkMySQLPoolConnection() { let isConnected = false; const conn = await pool.getConnection(); try { console.info(config.info(`Pinging database...`)); await conn.ping(); isConnected = !isConnected; } catch (err) { console.error((config.error(`Cannot ping database...: ', err`))); return Promise.reject({ connectionState: 'fail', errMsg: err }) } finally { conn.release(); console.info(config.info(`MySQL connection released...`)); if (isConnected) { return Promise.resolve({ connectionState: 'ready' }) } }; }
[ "createConnPool() {\n return new Promise(function(resolve,reject) {\n //Create a connection pool\n this.pool = mysql.createPool({\n connectionLimit:50,\n host: this.host,\n user: this.user,\n password: this.password,\n database: this.database\n })\n\n this.pool.getConnection((err, connection) => {\n //Checks the connection for errors\n if(err){\n if(connection){\n try {\n connection.release();\n }\n catch(err) {\n console.log(err);\n }\n }\n reject(err);\n if(err.code === 'PROTOCOL_CONNECTION_LOST'){\n throw \"Error: connection to database was closed\";\n }\n else if(err.code === 'ER_CON_COUNT_ERROR'){\n throw \"Error: too many connections to database\";\n }\n else if(err.code === 'ECONNREFUSED' || err.code ==='ER_ACCESS_DENIED_ERROR'){\n throw \"Error: connection to database was refused\";\n }\n else if (err.code === \"ER_DUP_ENTRY\") {\n throw \"Error: duplicate unique entry\" + err;\n }\n\n }\n else {\n if(connection){\n connection.release();\n }\n resolve(true);\n }\n });\n }.bind(this));\n }", "async function createMySQLPool() {\n try {\n const connectionPool = await retry({ times: 5, interval: 2000 }, async callback => {\n try {\n const conn = await createConnection();\n callback(null, conn);\n } catch (error) {\n const { code, errno, sqlMessage } = error;\n logger.error(`${errno} - ${code} - ${sqlMessage}`);\n logger.error('retrying to connect to mysql');\n callback(error);\n }\n });\n return connectionPool;\n } catch (error) {\n logger.fatal('cannot stablish connection to MySQL database');\n throw error;\n }\n}", "checkPoolStatus(cb, scope) {\n // Check connection pool settings are the same for the active pool\n if (\n this.checkConnectionDetails(\n this.options.mySQLSettings,\n this.poolSettings[this.currentSessionId()]\n ) ||\n !this.poolSettings[this.currentSessionId()]\n ) {\n // Check the pool is active\n if (this.checkPool(this.poolStorage)) {\n // Callback\n return cb();\n } else {\n // Start connection pool, wait slightly then move on...\n this.startPool(() => {\n setTimeout(() => {\n return cb();\n }, this.options.preInitDelay);\n });\n }\n } else {\n // Close the connection pool\n this.closePool(this.poolStorage, () => {\n // Recheck the status\n this.startPool(() => {\n setTimeout(() => {\n this.checkPoolStatus(cb, scope);\n }, this.options.preInitDelay);\n });\n });\n }\n }", "function getPool() {\r\n if (!pool) {\r\n pool = mysql.createPool(config);\r\n }\r\n return pool;\r\n}", "function openSQLConnection(callback) {\n\n if (!pool) { // if no pool create pool\n if (sqlConfig) {} else if (global.appConfig) {\n sqlConfig = global.appConfig.sql || default_config;\n } else {\n sqlConfig = default_config;\n }\n pool = mysql.createPool(sqlConfig);\n\n pool.on('connection', function(statusConn) {\n\n connections.opened = connections.opened + 1;\n connections.active = connections.active + 1;\n\n statusConn.on('end', function(err) {\n if (err) {\n console.error(err);\n connections.errors = connections.errors + 1;\n }\n connections.closed = connections.closed + 1;\n connections.active = connections.active - 1;\n });\n\n });\n pool.getConnection(sqlPoolHandler);\n } else {\n pool.getConnection(sqlPoolHandler);\n }\n\n function sqlPoolHandler(err, connection) {\n if (err) {\n if (err.fatal) {\n pool.end(function() {\n pool = mysql.createPool(sqlConfig);\n });\n } else {\n console.error(err);\n }\n callback(null);\n } else {\n connections.queries = connections.queries + 1;\n callback(connection);\n }\n }\n\n}", "function init() {\n pool = MySQL.createPool(ConfigMySQL);\n Logger.warn(\"Pool Created\");\n pool.on('acquire', function (connection) {\n // console.log('Connection %d acquired', connection.threadId);\n });\n pool.on('connection', function (connection) {\n // console.log('Connection %d connected', connection.threadId);\n });\n pool.on('enqueue', function () {\n // console.log('Waiting for available connection slot');\n });\n pool.on('release', function (connection) {\n // console.log('Connection %d released', connection.threadId);\n });\n}", "getConnection() {\n return new Promise((resolve, reject) => {\n if (!this.pool) {\n reject('Pool has ended. Connections are not available.');\n } else {\n this.pool.getConnection((err, connection) => {\n if (err) {\n reject(err);\n } else {\n resolve(new MySqlConnection(connection, this.config));\n }\n });\n }\n });\n }", "function getConnection(){\n return pool \n}", "function checkConnected () {\n\n return new Promise (function (resolve, reject) {\n\n // Get a connection from the mysql connection pool\n pool.getConnection(function(err, connection) {\n if (err) return reject({error: err}); \n \n return resolve ( { msg: 'Connected.' });\n });\n });\n }", "function getPing() {\n let ctx = 'mysql-db-get-ping'\n\n try {\n let dbStatus = false\n\n if (dbPool !== undefined) {\n dbStatus = new Promise(function(resolve, reject) {\n dbPool.getConnection(function(err, dbConn) {\n if (err) reject(err)\n\n if (dbConn !== undefined) {\n dbConn.ping(function(err) {\n if (err) reject(err)\n resolve(true)\n })\n \n dbConn.release()\n }\n })\n })\n }\n\n return dbStatus\n } catch(err) {\n log.error(ctx, common.strToTitleCase(err.message))\n return false\n }\n}", "async function connectToDB () {\n\n try {\n if ( pool === undefined ){\n\n pool = await mysqlDb.createPool({\n connectionLimit : 10,\n host : DB_HOST,\n user : DB_USER,\n password : DB_PASSWORD,\n database : DB_DATABASE,\n port : DB_PORT\n });\n\n await checkConnected ();\n }\n\n } catch (err) {\n console.error(err.message);\n process.exit(1);\n }\n }", "function getConnection() {\n\n return pool\n}", "checkPool(pool) {\n return pool ? true : false;\n }", "function _isConnectionPool(pool) {\r\n\treturn _.isObject(pool) && _.isNumber(pool.connectionsOpen);\r\n}", "createDBPools() {\n if (!dbConfig) {\n logger.error(Message.DBCONFIG_ERROR);\n throw new Error(Message.DBCONFIG_ERROR);\n }\n\n for (let key in dbConfig) {\n let config = dbConfig[key].connection;\n\n switch (dbConfig[key].type) {\n case DBTYPE.MYSQL:\n this.pools[key] = mysql.createPool({\n host: config.host,\n user: config.user,\n password: config.password,\n database: config.database,\n port: config.port,\n connectionLimit: 50,\n });\n\n // listening mysql pool\n this.pools[key].on('acquire', function(connection) {});\n\n this.pools[key].on('release', function(connection) {});\n break;\n case DBTYPE.REDSHIFT:\n this.pools[key] = new Redshift({\n user: config.user,\n database: config.database,\n password: config.password,\n port: config.port,\n host: config.host,\n });\n\n // listening redshift pool\n this.pools[key].pool.on('connect', () => {});\n break;\n default:\n break;\n }\n\n logger.info(Message.format(Message.DB_SUCCESS, JSON.stringify(config)));\n }\n }", "async function verifyMysqlConnectionAsync(config)\r\n{\r\n const dbName = config.database.name;\r\n const conn = mysql.createConnection(\r\n {\r\n host: config.database.host,\r\n user: config.database.userName,\r\n password: config.database.password\r\n });\r\n const success = await new Promise(resolve =>\r\n {\r\n conn.connect(err => \r\n {\r\n if (err)\r\n resolve(false);\r\n conn.query(`CREATE DATABASE IF NOT EXISTS ${dbName}`);\r\n resolve(true);\r\n });\r\n });\r\n if (!success)\r\n throw \"Bad mysql connection\";\r\n}", "function registerMySQLPool(pool) {\n global.mysqlPoolDM = new MySQLPoolManager(pool);\n}", "startPool(callback) {\n // Invoke connection pool\n this.poolStorage = this.createPool(this.options.mySQLSettings);\n // Start connection pool monitor\n this.closeIdlePools(\n this.poolStorage,\n this.currentSessionId(),\n this.poolActivity,\n this.options.idlePoolTimeout\n );\n // Start idle connection monitor\n this.closeIdleConnections(\n this.poolStorage,\n this.currentSessionId(),\n this.poolConnectionList\n );\n // Assign event listeners to pool\n this.assignEventListeners();\n // Register connection pool settings\n this.poolSettings[this.currentSessionId()] = this.options.mySQLSettings;\n // Set connection activity to 0\n this.poolActivity[this.currentSessionId()] = 0;\n // Callback if nessesary\n if (typeof callback === 'function') {\n // Callback\n return callback();\n } else {\n // Return\n return;\n }\n }", "function getConnection () {\n \n return pool\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bend/stretch arm to a length
bendArm( arm, length ) { var ret = true; var upperArm = this.skeleton.bones[arm.upper]; var lowerArm = this.skeleton.bones[arm.lower]; var scaling = this.rootMesh.scaling.x; if ( length > arm.lowerLength + arm.upperLength ) { length = arm.lowerLength + arm.upperLength ret = false; } // simplified math by using same length for both bones // it's right angle, hypotenuse is bone // length/2 is sinus of half of elbow angle var boneLength = (arm.lowerLength + arm.upperLength)/2; var innerAngle = Math.asin(length/2/boneLength); //this.log("Bone length: "+boneLength+" distance to target "+length); var shoulderAngle = Math.PI/2-innerAngle; var elbowAngle = shoulderAngle*2; var fix = BABYLON.Quaternion.RotationAxis(arm.frontAxis.axis,-shoulderAngle*arm.frontAxis.sign); arm.upperRot = arm.upperRot.multiply(fix); arm.lowerRot = BABYLON.Quaternion.RotationAxis(arm.frontAxis.axis,elbowAngle*arm.frontAxis.sign); //this.log("Angle shoulder: "+shoulderAngle+" elbow: "+elbowAngle+" length: "+length); return ret; }
[ "set armStretch(value) {}", "function stretch(t, from, to) {\r\n return (t * (to - from)) + from;\r\n}", "function stretch(t, from, to) {\n return t * (to - from) + from;\n }", "function stretch(t, from, to) {\n return (t * (to - from)) + from;\n}", "function downRamp() {\n c.clearRect(55, 0, -1500, -790); // clear the canvas \n const currAngle = angle; // grab the current angle\n drawRamp(currAngle); // draw the ramp with the respective angle\n currX = currX + 5; // increment x pos \n if (currX <= -80) {\n rectangle(currX, currY, currAngle); // redraw the rec \n }\n else {\n rectangle(-80, -52, currAngle); // when its to the bottom, draw the rect at the bottom\n }\n\n requestAnimationFrame(downRamp); // call the animateframe to display \n\n\n}", "function drawArmAndWatch()\n{\n imageMode(CENTER);\n image(arm, width/2, height/2, ARM_LENGTH, ARM_HEIGHT);\n}", "function drawRightArm() {\n\tlet colorPalette = {\n\t\tcolorFrom: backgroundBluesPalette[5],\n\t\tcolorTo: backgroundBluesPalette[0],\n\t\tstrokeWeight: 5,\n\t\tcolorLerp: 0.01\n\t};\n\n\t//bezier(280, 600, 300, 480, 400, 390, 440, 400);\n\n\tlet rightArmCoordinates = {\n\t\txBegin: 280,\n\t\tyBegin: 600,\n\t\txControl1: 300,\n\t\tyControl1: 480,\n\t\txControl2: 400,\n\t\tyControl2: 390,\n\t\txEnd: 460,\n\t\tyEnd: 400\n\t};\n\n\trightArmCoordinates.xBegin = rightArmCoordinates.xBegin + getRandomInt(-10, 10); \n\trightArmCoordinates.yBegin = rightArmCoordinates.yBegin + getRandomInt(-8, 8);\n\trightArmCoordinates.xEnd = rightArmCoordinates.xEnd + getRandomInt(-7, 7); \n\trightArmCoordinates.yEnd = rightArmCoordinates.yEnd + getRandomInt(-5, 5);\n\n\trightArmCoordinates.xControl1 = rightArmCoordinates.xControl1 + getRandomInt(-12, 12); \n\trightArmCoordinates.yControl1 = rightArmCoordinates.yControl1 + getRandomInt(-11, 11);\n\trightArmCoordinates.xControl2 = rightArmCoordinates.xControl2 + getRandomInt(-6, 6); \n\trightArmCoordinates.yControl2 = rightArmCoordinates.yControl2 + getRandomInt(-4, 4);\n\n\t// drawing points to give some depth\n\n\t// the last params chosen so to have an animation that looks good (no special logic here)\n\t// but renders impossible to rather use calls in a loop\n\tcolorPalette.strokeWeight = 4;\n\tdrawPoints(rightArmCoordinates.xBegin,\n\t\trightArmCoordinates.yBegin,\n\t\trightArmCoordinates.xControl1,\n\t\trightArmCoordinates.yControl1,\n\t\trightArmCoordinates.xControl2,\n\t\trightArmCoordinates.yControl2,\n\t\trightArmCoordinates.xEnd,\n\t\trightArmCoordinates.yEnd,\n\t\t100, 40, colorPalette, 1);\n\n\tcolorPalette.strokeWeight = 2;\n\tdrawPoints(rightArmCoordinates.xBegin,\n\t\trightArmCoordinates.yBegin,\n\t\trightArmCoordinates.xControl1,\n\t\trightArmCoordinates.yControl1,\n\t\trightArmCoordinates.xControl2,\n\t\trightArmCoordinates.yControl2,\n\t\trightArmCoordinates.xEnd,\n\t\trightArmCoordinates.yEnd,\n\t\t70, 70, colorPalette, 1);\n\n\tcolorPalette.strokeWeight = 5;\n\tstroke(backgroundBluesPalette[0]);\n\n\t// draw shaping line\n\n\t// the last params chosen so to have an animation that looks good (no special logic here)\n\t// but renders impossible to rather use calls in a loop\n\tlet lineSteps = 12;\n\tif (mainMusicPlaying) {\n\t\tlet level = amplitude.getLevel();\n\t\tcolorPalette.colorLerp = 3*level;\n\t\tif(colorPalette.colorLerp > 1.00){\n\t\t\tcolorPalette.colorLerp = 1.00;\n\t\t}\n\t\tcolorPalette.colorTo = ecgBeatColor;\n\t\tlineSteps = Math.trunc(level * 100);\n\t\tdrawNoiseLineWithSoundAmplitude(rightArmCoordinates.xBegin,\n\t\t\trightArmCoordinates.yBegin,\n\t\t\trightArmCoordinates.xControl1,\n\t\t\trightArmCoordinates.yControl1,\n\t\t\trightArmCoordinates.xControl2,\n\t\t\trightArmCoordinates.yControl2,\n\t\t\trightArmCoordinates.xEnd,\n\t\t\trightArmCoordinates.yEnd,\n\t\t\tlineSteps, 100, colorPalette, 1);\n\t} else {\n\t\tdrawNoiseLine(rightArmCoordinates.xBegin,\n\t\t\trightArmCoordinates.yBegin,\n\t\t\trightArmCoordinates.xControl1,\n\t\t\trightArmCoordinates.yControl1,\n\t\t\trightArmCoordinates.xControl2,\n\t\t\trightArmCoordinates.yControl2,\n\t\t\trightArmCoordinates.xEnd,\n\t\t\trightArmCoordinates.yEnd,\n\t\t\tlineSteps, 100, colorPalette, 1);\n\t}\n}", "function midline()\r\n{\r\nfor(i=0;i<480;i+=10)\r\n{\r\nvar y = 0;\r\nfill(\"white\");\r\nstroke(0);\r\nrect(width/2,y+i,10,480);\r\n}\r\n}", "function drawArmAndWatch() {\n imageMode(CENTER);\n image(arm, width / 2, height / 2, ARM_LENGTH, ARM_HEIGHT);\n}", "function midline(){\nfor(i=0;i<480;i+=10) {\nvar y = 0;\nfill(\"white\");\nstroke(0);\nrect(width/2,y+i,10,480);\n}\n}", "function draw_rightarm() {\r\n\t\tlet canvas = document.getElementById(\"hangman\");\r\n\t\tlet context = canvas.getContext(\"2d\");\r\n\r\n\t\tcontext.moveTo(175, 130);\r\n\t\tcontext.lineTo(200, 145);\r\n\t\tcontext.stroke();\r\n\t}", "function leftUpperArm() {\n\n instanceMatrix = mult(modelViewMatrix, translate(2.7, 0.5 * upperAntennaHeight, 0.0) );\n\t instanceMatrix = mult(instanceMatrix, scale4(upperAntennaWidth, upperAntennaHeight, upperAntennaWidth) );\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(instanceMatrix));\n for(var i =0; i<6; i++) gl.drawArrays(gl.TRIANGLE_FAN, 4*i, 4);\n}", "function volumeRectangular(length, width, height){\n return -1;\n }", "function raftBridgeWidth() {\n var width1 = 15, width2 = 15,\n step = (animationStage-1) % stagesPerSegment + 1;\n if( ! landscape) {\n if(leftBank) width2 = 10;\n else width1 = 10;\n }\n\n return nthBetween(step, width1, width2);\n}", "function rightLowerArm() {\n\n instanceMatrix = mult(modelViewMatrix, translate(-2.7, 0.5 * lowerAntennaHeight, 0.0) );\n\t instanceMatrix = mult(instanceMatrix, scale4(lowerAntennaWidth, lowerAntennaHeight, lowerAntennaWidth) );\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(instanceMatrix));\n for(var i =0; i<6; i++) gl.drawArrays(gl.TRIANGLE_FAN, 4*i, 4);\n}", "build_arm(graphics_state, deg, t)\n {\n if(t < 42)\n {\n\n var armRotateOne;\n if(t > 8 && t < 9)\n {\n armRotateOne = Math.PI/2*(t-8);\n }\n else if(t > 9)\n {\n armRotateOne = Math.PI/2;\n }\n else\n {\n armRotateOne = 0;\n }\n\n let m = Mat4.identity();\n {\n m = m.times(Mat4.translation(Vec.of(-6, -9.25, 0)));\n this.shapes.box.draw(\n graphics_state,\n m.times(Mat4.scale(Vec.of(0.5, 0.5, 0.5))),\n this.shape_materials['crate']);\n for (var i = 0; i < 22; ++i) {\n m = m.times(Mat4.translation(Vec.of(-0.5, 0.5, 0)))\n .times(Mat4.rotation(0.05 * deg, Vec.of(0, 0, 1)))\n .times(Mat4.translation(Vec.of(0.5, 0.5, 0)));\n this.shapes.box.draw(\n graphics_state,\n m.times(Mat4.scale(Vec.of(0.5, 0.5, 0.5))),\n this.shape_materials['crate']);\n\n if(i == 11)\n {\n for(var j = 0; j < 2; j++)\n {\n var mult = 1;\n if(j == 0)\n {\n mult = -1;\n }\n \n let n = m.times(Mat4.translation(Vec.of(.5, 0, mult*.5))).times(Mat4.rotation(armRotateOne, Vec.of(0, mult*-1, 0)));\n\n n = n.times(Mat4.translation(Vec.of(.5, 0, mult*2)));\n this.shapes.box.draw(\n graphics_state,\n n.times(Mat4.scale(Vec.of(0.5, 0.5, 2))),\n this.shape_materials['crate']\n );\n \n n = n.times(Mat4.translation(Vec.of(2.5, 0, mult*2.5))).times(Mat4.rotation(Math.PI/2, Vec.of(0,1,0)));\n this.shapes.box.draw(\n graphics_state,\n n.times(Mat4.scale(Vec.of(0.5, 0.5, 2))),\n this.shape_materials['crate']\n );\n\n n = n.times(Mat4.translation(Vec.of(mult*1.75, 0, mult*mult*2.5))).times(Mat4.rotation(Math.PI/2, Vec.of(0,1,0)));\n this.shapes.box.draw(\n graphics_state,\n n.times(Mat4.scale(Vec.of(0.5, 0.5, 1.25))),\n this.shape_materials['crate']\n );\n \n }\n }\n }\n this.shapes.box.draw(graphics_state,\n m.times(Mat4.translation(Vec.of(2.0825, 1, 0))).times(Mat4.scale(Vec.of(2.5825, 0.5, 0.5))),\n this.shape_materials['crate']);\n }\n }\n \n }", "function draw2ndFloor (length){\n resetTurtle();\n moveTo2ndFloor(length);\n \n turnRight (90);\n moveForward (length);\n \n}", "function straightenLimbs(bendNum) {\n for (var i = 0; i < 2; i++) {\n if (legAngles[i] > 0) {\n legAngles[i] -= 0.5;\n armAngles[i] = bendNum * legAngles[i];\n }\n if (legAngles[i + 2] < 0) {\n legAngles[i + 2] += 0.5;\n }\n }\n}", "function drawArm(progress, armThickness, armLength, armColor){\n var armRadians = (tau * progress) - (tau/4);\n var targetX = clockX + Math.cos(armRadians) * (armLength * clockRadius);\n var targetY = clockY + Math.sin(armRadians) * (armLength * clockRadius);\n\n /* pass in the parameters for how the arm looks in thickness and color */\n ctx.lineWidth = armThickness;\n ctx.strokeStyle = armColor;\n ctx.beginPath();\n /* start at the center of the clock */\n ctx.moveTo(clockX, clockY);\n /* Draw a line outwards to where the hand points */\n ctx.lineTo(targetX, targetY);\n ctx.stroke();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a list with the region name, and which party has majority there, plus the percentage
function createMajorityList(data) { majParty = []; var k = 0; var listIndex = 0; while (k < data.length) { var majority = data[k].parti; var votePerc = parseFloat(data[k].procent); var region = formatString(data[k].region, true); for (var i = k; i < k+11; i++) { if(parseFloat(data[i].procent) > votePerc) { majority = data[i].parti; votePerc = data[i].procent; } } majParty[listIndex] = {region, majority, votePerc}; k += 11; listIndex++; } }
[ "function updatePercentOccupancy(regions, totalPeople) {\n for (var r in regions) \n if (totalPeople > 0) \n regions[r].pct_occupancy = regions[r].count / totalPeople; \n else\n regions[r].pct_occupancy = 0. \n}", "function votesWithPartyCalc(array) {\n // get the list of percent of votes with party for Democrats, Republicans and Independents\n let repPcts = [];\n let demPcts = [];\n let indPcts = [];\n for (i = 0; i < array.length; i++) {\n if (array[i].party == \"R\") {\n repPcts.push(array[i].votes_with_party_pct);\n } else if (array[i].party == \"D\") {\n demPcts.push(array[i].votes_with_party_pct);\n } else {\n indPcts.push(array[i].votes_with_party_pct);\n }\n }\n // turn the list of percentages into an average percent//\n const add = (a, b) => a + b;\n senateStats.repsVoteOnParty = (repPcts.reduce(add) / repPcts.length).toFixed(\n 2\n );\n senateStats.demsVoteOnParty = (demPcts.reduce(add) / demPcts.length).toFixed(\n 2\n );\n senateStats.indsVoteOnParty = (indPcts>0 ? (indPcts.reduce(add) / indPcts.length).toFixed(2) : 0);\n }", "function votesWithPartyCalc(array) {\n // get the list of percent of votes with party for Democrats, Republicans and Independents\n let repPcts = [];\n let demPcts = [];\n let indPcts = [];\n for (i = 0; i < array.length; i++) {\n if (array[i].party == \"R\") {\n repPcts.push(array[i].votes_with_party_pct);\n } else if (array[i].party == \"D\") {\n demPcts.push(array[i].votes_with_party_pct);\n } else {\n indPcts.push(array[i].votes_with_party_pct);\n }\n }\n // turn the list of percentages into an average percent//\n const add = (a, b) => a + b;\n senateStats.repsVoteOnParty = (repPcts.reduce(add) / repPcts.length).toFixed(\n 2\n );\n senateStats.demsVoteOnParty = (demPcts.reduce(add) / demPcts.length).toFixed(\n 2\n );\n senateStats.indsVoteOnParty = (indPcts>0 ? (indPcts.reduce(add) / indPcts.length).toFixed(2) : 0);\n}", "function bottomPart() {\n\n var membersPerParty = data.results[0].members;\n\n // I Make an array to put the total number of members per party\n\n membersPerParty.sort(function (x, y) {\n return x.votes_with_party_pct - y.votes_with_party_pct;\n });\n\n //In case of 10 per cent of 105 members\n\n var total = Math.round(membersPerParty.length / 10);\n\n var tenPctParty = membersPerParty.slice(0, total);\n\n //Take the last member in case to do the same on the actual \n\n for (var i = total; i < membersPerParty.length; i++) {\n\n if (membersPerParty[i].votes_with_party_pct == tenPctParty[tenPctParty.length - 1].votes_with_party_pct) {\n\n tenPctParty.push(membersPerParty[i]);\n }\n }\n return tenPctParty;\n}", "function addMajorityProperty()\r\n {\r\n for(var i = 0; i < counties.length; ++i)\r\n {\r\n counties[i].properties[\"majority\"] = findMajorityByRegion(counties[i].properties.name);\r\n }\r\n }", "precentageToName(percent) {\n if (percent < 33) {\n return 'low';\n } else if (percent > 66) {\n return 'high';\n } else {\n return 'medium';\n }\n }", "function getPartyMembers() {\n let democrats = [];\n let republicans = [];\n let independents = [];\n let total = [];\n\n let democratsVotes = [];\n let republicansVotes = [];\n let independentsVotes = [];\n let totalVotes = [];\n\n for (var i = 0; i < membersSenate.length; i++) {\n if (membersSenate[i].votes_with_party_pct != null) {\n if (membersSenate[i].party.includes(\"D\")) {\n democrats.push(membersSenate[i].party) //***Number of Resp - 1st table - PARTY LOYALTY\n democratsVotes.push(membersSenate[i].votes_with_party_pct) //***% Voted w/ Party - 1st table - PARTY LOYALTY\n\n } else if (membersSenate[i].party.includes(\"R\")) {\n republicans.push(membersSenate[i].party) //***Number of Resp - 1st table - PARTY LOYALTY\n republicansVotes.push(membersSenate[i].votes_with_party_pct) //***% Voted w/ Party - 1st table - PARTY LOYALTY\n\n } else if (membersSenate[i].party.includes(\"I\")) {\n independents.push(membersSenate[i].party) //***Number of Resp - 1st table - PARTY LOYALTY\n independentsVotes.push(membersSenate[i].votes_with_party_pct) //***% Voted w/ Party - 1st table - PARTY LOYALTY\n }\n total.push(membersSenate[i].party) //***Number of Resp - 1st table - PARTY LOYALTY\n totalVotes.push(membersSenate[i].votes_with_party_pct) //***% Voted w/ Party - 1st table - PARTY LOYALTY\n }\n }\n // console.log(democrats,republicans,independents)\n document.getElementById(\"democrats\").innerHTML = democrats.length;\n document.getElementById(\"republicans\").innerHTML = republicans.length;\n document.getElementById(\"independents\").innerHTML = independents.length;\n document.getElementById(\"total\").innerHTML = democrats.length + republicans.length + independents.length;\n\n\n // console.log(democratsVotes,republicansVotes,independentsVotes)\n\n let democratsVotesPct = (democratsVotes.reduce((a, b) => a + b) / democrats.length);\n let republicansVotesPct = (republicansVotes.reduce((a, b) => a + b) / republicans.length);\n if (independentsVotes.length != 0) {\n independentsVotesPct = (independentsVotes.reduce((a, b) => a + b) / independents.length);\n } else {\n independentsVotesPct = 0;\n }\n let totalVotesPct = (totalVotes.reduce((a, b) => a + b) / total.length);\n document.getElementById(\"democratsVotes\").innerHTML = democratsVotesPct.toFixed(2) + \"%\";\n document.getElementById(\"republicansVotes\").innerHTML = republicansVotesPct.toFixed(2) + \"%\";\n document.getElementById(\"independentsVotes\").innerHTML = independentsVotesPct.toFixed(2) + \"%\"\n document.getElementById(\"totalVotes\").innerHTML = totalVotesPct.toFixed(2) + \"%\";\n}", "function findTotalVotesPartyPct(array) {\n for (let i = 0; i < array.length; i++) {\n statistics.totalVotesPartyPct += array[i].votes_with_party_pct;\n }\n}", "function censusDisplay(responseJson) {\n let cityName2 = (responseJson[1][15]).replace(/ city/g, \"\");\n let cityName = cityName2.replace(/ village/g, \"\");\n let population = responseJson[1][0];\n let underEighteen = parseInt(responseJson[1][20]) + parseInt(responseJson[1][21]) + parseInt(responseJson[1][22]) + parseInt(responseJson[1][23]) + parseInt(responseJson[1][24]) + parseInt(responseJson[1][25]) + parseInt(responseJson[1][18]) + parseInt(responseJson[1][19]);\n let overEighteen = population - underEighteen;\n let medianRent = responseJson[1][16];\n let percentWhite = Math.round(responseJson[1][1] / responseJson[1][0] * 100);\n let percentBlack = Math.round(responseJson[1][2] / responseJson[1][0] * 100);\n let percentAsian = Math.round(responseJson[1][4] / responseJson[1][0] * 100)\n let percentLatino = Math.round(responseJson[1][8] / responseJson[1][0] * 100)\n let percentindigenous = Math.round(((responseJson[1][5] / responseJson[1][0]) * 100) + ((responseJson[1][3] / responseJson[1][0]) * 100))\n let percentOther = Math.round(((responseJson[1][6] / responseJson[1][0]) * 100) + ((responseJson[1][7] / responseJson[1][0]) * 100))\n let percentSomeCollege = Math.round(((responseJson[1][11] / overEighteen) * 100) + ((responseJson[1][12] / overEighteen) * 100) + ((responseJson[1][13] / overEighteen) * 100))\n let percentCollege = Math.round(((responseJson[1][12] / overEighteen) * 100) + ((responseJson[1][13] / overEighteen) * 100))\n let averageIncome = responseJson[1][14]\n let percentNHWhite = Math.round((responseJson[1][17] / population) * 100)\n let diversity = \"\";\n let avgIncome = \"\";\n let avgEducation = \"\";\n\n if (percentNHWhite > 70) {\n diversity = \"less diverse than\";\n } else if (percentNHWhite > 50) {\n diversity = \"about as diverse as\";\n } else { diversity = \"more diverse than\" }\n\n if (averageIncome > 35000) {\n avgIncome = \"higher than\";\n } else if (averageIncome > 26000) {\n avgIncome = \"similar to\";\n } else { avgIncome = \"lower than\" }\n\n if (population > 500000) {\n citySize = \"large city\";\n } else if (population > 200000) {\n citySize = \"medium-sized city\";\n } else if (population > 50000) {\n citySize = \"small city\";\n } else if (population > 10000) {\n citySize = \"small community\";\n } else { citySize = \"very small community\" }\n\n if (percentCollege > 38) {\n avgEducation = \"more educated than\";\n } else if (percentCollege > 24) {\n avgEducation = \"about as educated as\";\n } else { avgEducation = \"less educated than\" }\n $(\".census-info\").append(`<h1>This place is ${cityName}!</h1><h2>Who lives here?</h2><p>${cityName} has a population of <span class=\"highlight-data\">${population}</span>, which makes it a <span class=\"highlight-data\">${citySize}</span>. ${percentSomeCollege} percent of residents have at least some college education, and ${percentCollege} percent have at least a bachelor's degree, which means that this place is <span class=\"highlight-data\">${avgEducation}</span> the nation as a whole. The average income here is <span class=\"highlight-data\">$${averageIncome} per year</span>, which is ${avgIncome} the national average. The median rent here is $${medianRent} per month. <br><br>${cityName} is <span class=\"highlight-data\">${diversity}</span> the nation as a whole. ${percentWhite} percent of residents are white, ${percentBlack} percent are black, ${percentAsian} percent are Asian, ${percentindigenous} percent are American Indian or indigenous peoples, and ${percentOther} percent identify as something else or two or more races. ${percentLatino} percent identify as Hispanic or Latino, of any race.</p>`);\n showPlaceInfo();\n}", "function getGenderGroups(name, pct){\n\n console.log(name, pct);\n\n var gender2 = [];\n var gender5 = [];\n var gender10 = [];\n var gender35 = [];\n var gender70 = [];\n var genderCeleb = [];\n\n var genderPct2 = [];\n var genderPct5 = [];\n var genderPct10 = [];\n var genderPct35 = [];\n var genderPct70 = [];\n var genderPctCeleb = [];\n\n for (i = 0; i < name.length; i++){\n var size = name[i].substring(1);\n // console.log(size);\n switch (size) {\n case '2': gender2.push(name[i]);\n genderPct2.push(pct[i]);\n break;\n case '5' : gender5.push(name[i]);\n genderPct5.push(pct[i]);\n break;\n case '10' : gender10.push(name[i]);\n genderPct10.push(pct[i]);\n break;\n case '35' : gender35.push(name[i]);\n genderPct35.push(pct[i]);\n break;\n case '70' : gender70.push(name[i]);\n genderPct70.push(pct[i]);\n break;\n default : genderCeleb.push(name[i]);\n genderPctCeleb.push(pct[i]);\n };\n };\n console.log(gender2, gender5, gender10, gender35, gender70, genderCeleb);\n return[gender2, genderPct2, gender5, genderPct5, gender10, genderPct10, gender35, genderPct35, gender70, genderPct70, genderCeleb, genderPctCeleb];\n\n}", "favorite_region_stats() {}", "function getAllRegions() {\n return new Promise((resolve) =>{\n const regions = {\n regions: [\n {name: \"blackrod\", parent: \"bolton\"},\n {name: \"bolton\", parent: \"manchester\"},\n {name: \"bury\", parent: \"manchester\"},\n {name: \"camden\", parent: \"central london\"},\n {name: \"camden town\", parent: \"camden\"},\n {name: \"cheese\", parent: \"camden town\"},\n {name: \"cheese3\", parent: \"camden\"},\n {name: \"central london\", parent: \"london\"},\n {name: \"covent garden\", parent: \"westminster\"},\n {name: \"croydon\", parent: \"south-west london\"},\n {name: \"east london\", parent: \"london\"},\n {name: \"farnworth\", parent: \"bolton\"},\n {name: \"hatton garden\", parent: \"camden\"},\n {name: \"heywood\", parent: \"rochdale\"},\n {name: \"holborn\", parent: \"camden\"},\n {name: \"kensington and chelsea\", parent: \"london\"},\n {name: \"kew\", parent: \"richmond upon thames\"},\n {name: \"kingston upon thames\", parent: \"south-west london\"},\n {name: \"london\", parent: \"\"},\n {name: \"manchester\", parent: \"\"},\n {name: \"middleton\", parent: \"rochdale\"},\n {name: \"north london\", parent: \"london\"},\n {name: \"oldham\", parent: \"manchester\"},\n {name: \"richmond upon thames\", parent: \"south-west london\"},\n {name: \"rochdale\", parent: \"manchester\"},\n {name: \"south london\", parent: \"london\"},\n {name: \"south-west london\", parent: \"london\"},\n {name: \"twickenham\", parent: \"richmond upon thames\"},\n {name: \"west london\", parent: \"london\"},\n {name: \"westminster\", parent: \"central london\"},\n {name: \"wimbledon\", parent: \"south-west london\"},\n ]\n }\n\n setTimeout(() => resolve(regions), Math.random() * 1500);\n\n });\n\n}", "function get_rarity() {\n let percent = Math.floor(Math.random() * 100);\n\n if (percent >= 0 && percent <= 60) {\n return 'common';\n } else if (percent > 60 && percent <= 80) {\n return 'uncommon';\n } else if (percent > 80 && percent <= 88) {\n return 'rare';\n } else if (percent > 88 && percent <= 93) {\n return 'veryrare';\n } else if (percent > 93 && percent <= 99) {\n return 'epic';\n } else {\n return 'legendary';\n }\n}", "function percentageOfWorld1 (population) {\n return (population / 7900) * 100;\n}", "function getInterestPercentage (){\n\t\treturn Math.round(revealedInterestSections/numberOfInterestSections*100);\n\t}", "function createList(index) {\n\tvar listIndex = 0;\t\n\twhile (dataset[index]) {\n\t\t\n\t\tfilteredPartyPercentList[listIndex] = [dataset[index].region, dataset[index].procent];\n\t\t\n\t\tindex += 11;\n\t\tlistIndex++;\n\t}\n}", "function percentageOfWorld1(population) {\n return (population / 7900) * 100;\n}", "function percentageOfWorld1(population) {\n return population / 7900 * 100;\n}", "function percentCovered(array){\n\nvar type = array.visitType;\n\n\tswitch(type){\n\t\tcase(\"Optical\"):\n\t\treturn 0;\n\t\tbreak;\n\n\t\tcase(\"Specialist\"):\n\t\treturn .10;\n\t\tbreak;\n\n\n\t\tcase(\"Emergency\"):\n\t\treturn 1;\n\t\tbreak;\n\n\n\t\tcase(\"Primary Care\"):\n\t\treturn .50;\n\t\tbreak;\n\t}\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handleDeliveryStatus The main routine for handling delivery status messages from xMatters If an message is delivered successfully, a comment is added to the worklog of the Remedy Incident ticket quoting the user and device that was targeted If an message delivery fails, a comment is added to the worklog of the Remedy Incident ticket quoting the user and device that was targeted
function handleDeliveryStatus(msg) { if ( ANNOTATE_DELIVERY && msg.deliverystatus ) { switch (String(msg.deliverystatus).toLowerCase()) { case "delivered": addAnnotationToIncidentWorkInfo( getIncidentID(msg), notePrefix + "Notification delivered successfully to " + msg.recipient + " | " + msg.device); break; case "failed": addAnnotationToIncidentWorkInfo( getIncidentID(msg), notePrefix + "Unable to deliver notification to " + msg.recipient + " | " + msg.device); break; } } }
[ "function handleDeliveryStatusCallback(msg) {\n IALOG.debug(\"Enter - handleDeliveryStatusCallback\");\n\n var incidentId = msg.additionalTokens.incident_id;\n var responder = msg.recipient;\n var xmDeliveryStatus = msg.deliverystatus;\n var xmDevice = msg.device;\n\n // Create an annotation for the successful or failed delivery of a notification.\n var annotation = \"\";\n annotation = xmDeliveryStatus + \" to \" + responder + \" | \" + xmDevice;\n\n if (!ANNOTATE_DELIVERY) {\n IALOG.warn(\"Delivery annotations are suppressed - the following message will not be annotated to BPPM event: [\" + incidentId + \"] \" + annotation);\n return;\n }\n\n IALOG.debug(\"Starting call to management system for delivery status annotation for BPPM event: [\" + incidentId + \"]\");\n\n try {\n var bppmws = new BPPMWS();\n\n var result = bppmws.updateEvent(incidentId, bppmws.IMWS_STATUS_NONE, NO_ASSIGNEE, CALLOUT_USER, NO_LOGS, NOTE_PREFIX + annotation, false);\n\n IALOG.debug(\"Finished call to management system for delivery status annotation for BPPM event: [\" + incidentId + \"] with result \" + result);\n } catch (e) {\n IALOG.error(\"Caught exception processing delivery status annotation for BPPM event: [\" + incidentId + \"] Exception:\" + e);\n throw e;\n }\n IALOG.debug(\"Exit - handleDeliveryStatusCallback\");\n}", "function handleEventStatus(msg)\n{\n switch (msg.status) {\n \n case \"active\": // event created \n addAnnotationToIncidentWorkInfo( getIncidentID(msg), notePrefix + \"Event \" + msg.eventidentifier + \" successfully created in xMatters\" );\n break;\n \n case \"terminated\": // time expired \n addAnnotationToIncidentWorkInfo( getIncidentID(msg), notePrefix + \"Event \" + msg.eventidentifier + \" terminated\" );\n break;\n \n case \"terminated_external\": // terminated by user\n var incidentId = getIncidentID(msg);\n\n if (msg.username !== INITIATOR_USER_ID) {\n addAnnotationToIncidentWorkInfo( incidentId, notePrefix + \"Event \" + msg.eventidentifier + \" manually terminated from within xMatters\" \n /* + \" by user [\" + msg.username + \"]\" */ );\n } else {\n // Ignore the events created and terminated by this integration and not the actual user\n log.info(\"handleEventStatus - incidentId [\" + incidentId + \"] event terminated by the user that initiated the event. Ignored.\");\n }\n break; \n }\n}", "function statusHandler(purchase) {\n\n\t//permanent veriables\n\tvar FUNCTION = \"Payal::IPN::StatusHandler\"\n\n\t//permanent payment_status veriables\n\tvar COMPLETED = 'Completed';\n\tvar VOIDED = 'Voided';\n\tvar EXPIRED = 'Expired';\n\tvar REFUNDED = 'Refunded';\n\tvar DENIED = 'Denied';\n\tvar FAILED = 'Failed';\n\tvar REVERSED = 'Reversed';\n\tvar CANCELED_REVERSAL = 'Canceled_Reversal';\n\tvar PROCESSED = 'Processed';\n\tvar CREATED = 'Created';\n\tvar PENDING = 'Pending';\n\tvar WAITING_FOR_CAPTURE = 'Waiting_for_capture';\n\tvar UNKNOWN = \"Unknown\";\n\t//permanent pending_reason veriables\n\tvar AUTHORIZATION = 'authorization';\n\tvar ADDRESS = 'address';\n\tvar ECHECK = 'echeck';\n\tvar INTL = 'intl';\n\tvar MULTI_CURRENCY = 'multi-currency';\n\tvar ORDER = 'order';\n\tvar PAYMENTREVIEW = 'paymentreview';\n\tvar REGULATORY_REVIEW = 'regulatory_review';\n\tvar UPGRADE = 'upgrade';\n\tvar UNILATERAL = 'unilateral';\n\tvar VERIFY = 'verify';\n\tvar OTHER = 'other';\n\n\tvar paymentStatus = purchase.paypal.payment_status;\n\tpurchase.status = paymentStatus;\n\n\tif (paymentStatus == PENDING) {\n\t\tvar pendingReason = purchase.paypal.pending_reason;\n\t\tif(pendingReason == AUTHORIZATION) {\n\t\t\tpurchase.status = WAITING_FOR_CAPTURE;\n\t\t\t//Notify the user by mail that his purchase is in pending state (only for pending reason - 'authorization')\n\t\t\tvar body = \"<b>Thank you for buying The-Tickets: your Ticket is waiting for approval, a new mail will be sent with the ticket/s details when transaction is done</b>\";\n\t\t\tmailer.SendMail(SENDER, purchase.email, \"The-Ticket ✔\", body);\n\t\t} else { \n\t\t\tswitch (pendingReason) {\n\t\t\tcase ADDRESS:\n\t\t\t\tvar body = \"<b>your customer did not include a confirmed shipping address and your Payment Receiving Preferences is set yo allow you to manually accept or deny each of these payments. To change your preference, go to the Preferences section of your Profile.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase ECHECK:\n\t\t\t\tvar body = \"<b>The payment was made by an eCheck that has not yet cleared.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase INTL:\n\t\t\t\tvar body = \"<b>you hold a non-U.S. account and do not have a withdrawal mechanism. You must manually accept or deny this payment from your Account Overview.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase MULTI_CURRENCY:\n\t\t\t\tvar body = \"<b>You do not have a balance in the currency sent, and you do not have your profiles's Payment Receiving Preferences option set to automatically convert and accept this payment. As a result, you must manually accept or deny this payment.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase ORDER:\n\t\t\t\tvar body = \"<b>You set the payment action to Order and have not yet captured funds.<b>\";\n\t\t\t\tbreak;\n\n case PAYMENTREVIEW:\n\t\t\t\tvar body = \"<b>The payment is being reviewed by PayPal for risk.<b>\";\n\t\t\t\tbreak;\n\n case REGULATORY_REVIEW:\n\t\t\t\tvar body = \"<b>The payment is pending because PayPal is reviewing it for compliance with government regulations. PayPal will complete this review within 72 hours. When the review is complete, you will receive a second IPN message whose payment_status/reason code variables indicate the result.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase UPGRADE:\n\t\t\t\tvar body = \"<b>The payment was made to an email address that is not yet registered or confirmed.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase UNILATERAL:\n\t\t\t\tvar body = \"<b>The payment was made via credit card and you must upgrade your account to Business or Premier status before you can receive the funds. upgrade can also mean that you have reached the monthly limit for transactions on your account.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase VERIFY:\n\t\t\t\tvar body = \"<b>you are not yet verified. You must verify your account before you can accept this payment.<b>\";\n\t\t\t\tbreak;\n\n\t\t\tcase OTHER:\n\t\t\t\tvar body = \"<b>The payment is pending for a reason other than those listed above. For more information, contact PayPal Customer Service.<b>\" \n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.log(FUNCTION + \" Error : purchase: \" + purchase._id + \" is pending with unfamiliar pending reason: \" + pendingReason);\n\t\t\t\tvar body = \"Error : purchase: \" + purchase._id + \" is pending with unfamiliar pending reason: \" + pendingReason;\n\t\t\t}\n\t\t\t//Notify the admin by mail about any of the pending reasons (other then 'authorization');\n\t\t\tmailer.SendMail(SENDER, ADMIN, 'Notification from ' + FUNCTION, body);\n\t\t}\n\t} else {\n\t\tswitch(paymentStatus) {\n\t\tcase COMPLETED:\n\t\tvar body = \"<b>Thank you for buying \" + purchase.paypal.quantity1 + \" Tickets of: \" + purchase.paypal.item_name1 +\n\t\t\t\" in total cost of \" + purchase.paypal.mc_gross + \" \" + purchase.paypal.mc_currency + \"</b>\"; \n\t\t\tbreak;\n\n\t\tcase VOIDED:\n\t\t\tvar body = \"<b>We dont want to sell you any ticket<b>\";\n\t\t\tbreak;\n\n\t\tcase EXPIRED:\n\t\t\tvar body = \"<b>The event's admin was delaying for too long your purchase's approval so no charge has been made<b>\";\n\t\t\tbreak;\n\n\t\tcase REFUNDED:\n\t\t\tvar body = \"<b>Charge was Refunded<b>\";\n\t\t\tbreak;\n\n\t\tcase DENIED:\n\t\t\tvar body = \"<b>The payment was denied. This happens only if the payment was previously pending because of one of the reasons listed for the pending_reason variable or the Fraud_Management_Filters_x variable.<b>\";\n\t\t\tbreak;\n\n\t\tcase FAILED:\n\t\t\tvar body = \"<b>Charge failed : The payment has failed. This happens only if the payment was made from your bank account<b>\";\n\t\t\tbreak;\n\n\t\tcase REVERSED:\n\t\t\tvar body = \"<b>The payment was reversed due to a chargeback or other type of reversal. The funds have been returned to you<b>\";\n\t\t\tbreak;\n\n\t\tcase CANCELED_REVERSAL:\n\t\t\tvar body = \"<b>Successfully canceled The Payment reversal, the funds for the transaction that was reversed have been returned to the seller.<b>\";\n\t\t\tbreak;\n\n case PROCESSED:\n\t\t\tvar body = \"<b>The payment has been accepted<b>\";\n\t\t\tbreak;\n\n\t\tcase CREATED:\n\t\t\tvar body = \"<b>A German ELV payment is made using Express Checkout.<b>\";\n\t\t\tbreak;\n\n default:\n purchase.status = UNKNOWN;\n console.log(FUNCTION + \" Error : purchase: \" + purchase._id + \" entered to Unknown payment status due to an unfamiliar paypal payment status:: \" + paymentStatus);\n var body = \"Error : purchase: \" + purchase._id + \" entered to Unknown payment status due to an unfamiliar paypal payment status: \" + paymentStatus;\n //Notify the admin by mail about an Unknown payment_status arrived from paypal's IPN\n mailer.SendMail(SENDER, ADMIN, 'Notification from ' + FUNCTION, body);\n body = \"<b>An Error occurred while processing your purchase request, we are taking care of it as quickly as possible, thank you for buying The-Tickets and sorry for the delay<b>\";\n\t\t}\n //Notify the user by mail about his payment status;\n mailer.SendMail(SENDER, purchase.email, \"The-Ticket ✔\", body);\n\t}\n\treturn purchase;\n}", "function paymentOnDelivery(ruleStatus, ruleParams, ruleMsg, REC) {\n //var funcName = scriptName + \"evaluateOverdueBalance \" + REC.type + \":\" + REC.id + \" | \" + ruleParams;\n ruleStatus.passed = true;\n\n var PaymentMethod = REC.getValue(\"paymentmethod\");\n var PaymentOnDeliveryCB = REC.getValue(\"custbody_payment_on_delivery\");\n\n //var PaymentMethod = REC.getText('paymentmethod');\n var LocalPickup = REC.getText(\"shipmethod\").indexOf(\"Local\") > -1 || REC.getText(\"shipmethod\").indexOf(\"Special Order\") > -1 ? true : false;\n\n if (PaymentOnDeliveryCB && LocalPickup === false) {\n ruleStatus.passed = false;\n ruleStatus.message = ruleMsg;\n return;\n }\n\n if (PaymentMethod == \"23\" && LocalPickup === false) {\n ruleStatus.passed = false;\n ruleStatus.message = ruleMsg;\n return;\n }\n ruleStatus.passed = true;\n }", "function Delivering(purchase) {\r\n\tif ((purchase.order.status = JSON.stringify(orderStatus.ShipRequest)) || (JSON.parse(purchase.order.status).code = orderStatus.Delivering.code))\r\n\t{\r\n\t\tpurchase.order.delivering = new Date().toISOString();\r\n\t\tvar _status = orderStatus.Delivering;\r\n\t\t_status.text += ' '+purchase.deliveryStatus;\r\n\t\tpurchase.order.status = JSON.stringify(_status);\r\n\t\treturn getAssetRegistry('org.dotbox.caregiverNetwork.Order')\r\n\t\t.then(function (assetRegistry) {\r\n\t\t\treturn assetRegistry.update(purchase.order);\r\n\t\t});\r\n\t}\t\t\r\n}", "function processOrderStatusChange(orderStatus) {\n if (orderStatus.transaction_status.length > 0) {\n log(\"Order num: \" + orderStatus.order.cl_order_id + \" Status: \" + orderStatusToString(orderStatus.status));\n if (orderStatus.status == WebAPI.OrderStatus.Status.REJECTED) {\n log(\"Rejection reason: \" + orderStatus.transaction_status[0].text_message);\n }\n orders[orderStatus.chain_order_id] = orderStatus;\n showOrder(orderStatus);\n }\n}", "function receivedDeliveryConfirmation(event){var senderID=event.sender.id;var recipientID=event.recipient.id;var delivery=event.delivery;var messageIDs=delivery.mids;var watermark=delivery.watermark;var sequenceNumber=delivery.seq;if(messageIDs){messageIDs.forEach(function(messageID){console.log(\"Received delivery confirmation for message ID: %s\",messageID);});}console.log(\"All message before %d were delivered.\",watermark);}", "function handleStatusCallback(msg) {\n IALOG.debug(\"Enter - handleStatusCallback\");\n\n var incidentId = msg.additionalTokens.incident_id;\n var xmStatus = msg.status;\n\n // Create an annotation for xMatters Event status updates.\n var annotation = \"\";\n annotation = \"xMatters incident for BPPM event: \" + incidentId + \" | \" + xmStatus;\n\n IALOG.debug(\"Starting call to management system for status annotation for BPPM event: [\" + incidentId + \"]\");\n\n try {\n var bppmws = new BPPMWS();\n\n var result = bppmws.updateEvent(incidentId, bppmws.IMWS_STATUS_NONE, NO_ASSIGNEE, CALLOUT_USER, NO_LOGS, NOTE_PREFIX + annotation, false);\n\n IALOG.debug(\"Finished call to management system for status annotation for BPPM event: [\" + incidentId + \"] with result \" + result);\n } catch (e) {\n IALOG.error(\"Caught exception processing status annotation for BPPM event: [\" + incidentId + \"] Exception:\" + e);\n throw e;\n }\n IALOG.debug(\"Exit - handleStatusCallback\");\n}", "function handleDeliveredOrder(foundOrder, newStatus, response) {\n foundOrder.status = newStatus;\n foundOrder.save((error, updatedOrder) => {\n if (error) {\n response.send(error);\n response.status(500);\n } else {\n socketIO.emit('ordersUpdated', updatedOrder.clientId);\n removeOrder(updatedOrder._id);\n response.status(200);\n }\n })\n }", "function messageFailureHandler() {\n console.log(\"Message send failed.\");\n sendStatus();\n}", "function confirmDelivery(delivery, statusCb, locationCb) {\n delivery.on('status', (status) => {\n statusCb(status);\n })\n .on('location', (location) => {\n locationCb(location);\n });\n}", "function processMessageCrusader(self, msg){\n switch (msg){\n case 0:\n break;\n case 1:\n self.status = 'searchAndAttack';\n break;\n case 16390:\n self.status = 'rally';\n //self.finalTarget = self.rallyTarget;\n break;\n case 16391:\n self.status = 'defend';\n //self.finalTarget = self.defendTarget;\n break;\n }\n}", "function handleStatus(status) {\n\n\t\t}", "function updateNotificationStatus(notificationId,delivered){\n var query = connection.query('UPDATE notifications set delivered='+delivered+',attempted=1 where id=:NOTIFICATION_ID',{NOTIFICATION_ID:notificationId},function(err,rows){console.log(err);})}", "ordersUpdated(channel, pushResponse) {\n const {auth, getOrderQueue, getOrder, getOrderStatuses, orders, setProp, params, customer} = this.props;\n const user = auth.get('user');\n // Customer view\n const selectedAppraiser = customer.get('selectedAppraiser');\n if (user.get('type') === 'customer' && !selectedAppraiser) {\n return;\n }\n\n // set this to reload messages\n setProp(undefined, 'retrieveMessageSuccess');\n\n // check if we are in the detail view or on the search page\n if (params.orderId) {\n getOrder(user, params.orderId, selectedAppraiser);\n this.getRevisions(selectedAppraiser || user, params.orderId);\n } else {\n // Push process status\n if (orders.get('selectedRecord') &&\n pushResponse && pushResponse.order && pushResponse.order.id && pushResponse.newProcessStatus &&\n orders.getIn(['selectedRecord', 'id']) === pushResponse.order.id\n ) {\n this.props.setProp(pushResponse.newProcessStatus, 'selectedRecord', 'processStatus');\n this.getRevisions(selectedAppraiser || user, orders.getIn(['selectedRecord', 'id']));\n }\n }\n const queueType = orders.get('type');\n if (queueType && !params.orderId) {\n // update the orders\n getOrderQueue(user, orders.get('type'), orders.get('search'), this.state.selectedAppraiser);\n }\n // update the order statuses\n getOrderStatuses(user, this.state.selectedAppraiser);\n }", "function checkFulfilStatus(type)\r\n{\r\n\t//declaring local variables\r\n\tvar status = '';\r\n\r\n\ttry\r\n\t{\r\n\r\n\t\tstatus = nlapiGetFieldValue('shipstatus');\t\t\t\t\t\t\t//getting status\r\n\t\tcreatedFromrecordIntID =nlapiGetFieldValue('createdfrom');\t\t\t//sales order reference related to fulfilment\r\n\t\tnoOfLineItems = nlapiGetLineItemCount('item');\r\n\r\n\t\t//version 1.0.1\r\n\t\t//if status is shipping\r\n\t\tif(status == 'C')\r\n\t\t{\r\n\t\t\tgetSOFieldsAndItemLinesAndProcess(type);\t\t\t\t\t\t//calling the getSOFieldsAndItemLinesAndProcess Function\r\n\r\n\t\t}\t\r\n\r\n\t}\r\n\tcatch(e)\r\n\t{\r\n\t\terrorHandler('checkFulfilStatus', e);\r\n\t}\r\n\r\n}", "function onMessageSettled(logPrefix, delivery, deliveryDispositionMap) {\n if (delivery) {\n const id = delivery.id;\n const state = delivery.remote_state;\n const settled = delivery.remote_settled;\n receiverLogger.verbose(\"%s Delivery with id %d, remote_settled: %s, remote_state: %o has been \" + \"received.\", logPrefix, id, settled, state && state.error ? state.error : state);\n if (settled && deliveryDispositionMap.has(id)) {\n const promise = deliveryDispositionMap.get(id);\n clearTimeout(promise.timer);\n receiverLogger.verbose(\"%s Found the delivery with id %d in the map and cleared the timer.\", logPrefix, id);\n const deleteResult = deliveryDispositionMap.delete(id);\n receiverLogger.verbose(\"%s Successfully deleted the delivery with id %d from the map.\", logPrefix, id, deleteResult);\n if (state && state.error && (state.error.condition || state.error.description)) {\n const error = translateServiceBusError(state.error);\n return promise.reject(error);\n }\n return promise.resolve();\n }\n }\n}", "function updateDelivery() {\n // if in the middle of updating delivery charges\n if (status.updatingDeliveryCharges) {\n // add request to queue\n $(document).queue(queueName, function() {\n sendRequest();\n });\n } else {\n // send request immediately\n sendRequest();\n }\n }", "function statusIsNotDelivered(req, res, next) {\n const { status } = res.locals.order;\n if (status === \"delivered\") {\n return next({\n status: 400,\n message: \"A delivered order cannot be changed\",\n });\n }\n next();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the helper method to render the TLS config for a listener.
function renderListenerTlsOptions(scope, listenerTls) { const tlsValidation = listenerTls?.mutualTlsValidation; return listenerTls ? { certificate: listenerTls.certificate.bind(scope).tlsCertificate, mode: listenerTls.mode, validation: tlsValidation ? { subjectAlternativeNames: tlsValidation.subjectAlternativeNames ? { match: tlsValidation.subjectAlternativeNames.bind(scope).subjectAlternativeNamesMatch, } : undefined, trust: tlsValidation.trust.bind(scope).tlsValidationTrust, } : undefined, } : undefined; }
[ "async generateTlsConfig () {\n\t\tconst filenames = [\n\t\t\tPath.join (App.DATA_DIRECTORY, App.TlsKeyFilename),\n\t\t\tPath.join (App.DATA_DIRECTORY, App.TlsCertFilename)\n\t\t];\n\t\ttry {\n\t\t\tawait FsUtil.statFiles (filenames, (filename, stats) => {\n\t\t\t\treturn (stats.isFile () && (stats.size > 0));\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tcatch (err) {\n\t\t\tLog.debug (`Generate TLS config (failed to stat files); err=${err}`);\n\t\t}\n\n\t\tconst runOpenssl = async (args) => {\n\t\t\tconst proc = App.systemAgent.createOpensslProcess (args, App.DATA_DIRECTORY);\n\t\t\tconst isExitSuccess = await proc.awaitEnd ();\n\t\t\tif (! isExitSuccess) {\n\t\t\t\tthrow Error (\"openssl process ended with error\");\n\t\t\t}\n\t\t};\n\n\t\tawait runOpenssl ([\n\t\t\t\"genrsa\",\n\t\t\t\"-out\", Path.join (App.DATA_DIRECTORY, App.TlsKeyFilename),\n\t\t\t\"2048\"\n\t\t]);\n\t\tawait runOpenssl ([\n\t\t\t\"req\",\n\t\t\t\"-config\", Path.join (App.BIN_DIRECTORY, App.OpensslConfigFilename),\n\t\t\t\"-batch\",\n\t\t\t\"-new\",\n\t\t\t\"-sha256\",\n\t\t\t\"-key\", Path.join (App.DATA_DIRECTORY, App.TlsKeyFilename),\n\t\t\t\"-out\", Path.join (App.DATA_DIRECTORY, App.TlsCsrFilename)\n\t\t]);\n\t\tawait runOpenssl ([\n\t\t\t\"x509\",\n\t\t\t\"-req\",\n\t\t\t\"-days\", \"9125\",\n\t\t\t\"-in\", Path.join (App.DATA_DIRECTORY, App.TlsCsrFilename),\n\t\t\t\"-signkey\", Path.join (App.DATA_DIRECTORY, App.TlsKeyFilename),\n\t\t\t\"-out\", Path.join (App.DATA_DIRECTORY, App.TlsCertFilename)\n\t\t]);\n\t}", "function ajaxCallForTlsConfig(){\n\tif(tlsConfigXml == null){\n\t\tvar tlsxhr = initializeXhr();\n\t\tajaxCall(\n\t\t\t\ttlsxhr, \n\t\t\t\t'GET',\n\t\t\t\tGS_TLSCONF_API,\n\t\t\t\tnull,\n\t\t\t\tfunction(){\n\t\t\t\t\ttlsConfigXml = parseResponse(tlsxhr.responseXml, tlsxhr.responseText);\n\t\t\t\t\tpopulateTlsConfig(tlsConfigXml);\n\t\t\t\t}\n\t\t);\n\t}\n\telse{\n\t\tpopulateTlsConfig(tlsConfigXml);\n\t}\n\t\n}", "buildSecurityInfo(protocol) {\n const securityInfo = new Array();\n if (protocol != null && protocol.toLowerCase() == \"tcps\") {\n // In EZConnect format if the DN match is not specified the enable it\n // by default for TCPS protocol.\n const serverDNMatch = this.urlProps.get(\"SSL_SERVER_DN_MATCH\");\n const serverCertDN = this.urlProps.get(\"SSL_SERVER_CERT_DN\");\n const walletDir = this.urlProps.get(\"MY_WALLET_DIRECTORY\");\n if (serverDNMatch != null)\n securityInfo.push(`(SSL_SERVER_DN_MATCH=${serverDNMatch})`);\n if (serverCertDN != null)\n securityInfo.push(`(SSL_SERVER_CERT_DN=${serverCertDN}})`);\n if (walletDir != null)\n securityInfo.push(`(MY_WALLET_DIRECTORY=${walletDir})`);\n }\n if (securityInfo.length === 0)\n return '';\n return `(SECURITY=${securityInfo.join('')})`;\n }", "function createVHostConfig(opts) {\n var host = '';\n\n if (opts.ssl == 'on') {\n host += ''\n + 'server {\\n'\n + ' listen ' + opts.port + ' ssl;\\n'\n + ' server_name ' + opts.domain + ';\\n'\n + ' \\n'\n + ' ssl on;\\n'\n + ' ssl_certificate ' + nginxOpts.ssl_key_loc + opts.ssl_cert_name + ';\\n'\n + ' ssl_certificate_key ' + nginxOpts.ssl_key_loc + opts.ssl_key_name + ';\\n'\n + ' \\n'\n + ' ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\\n'\n + ' ssl_ciphers \"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA\";\\n'\n + ' ssl_prefer_server_ciphers on;\\n'\n + ' ssl_dhparam /etc/ssl/dhparams.pem;\\n'\n + ' \\n'\n } else {\n host += ''\n + 'server {\\n'\n + ' listen ' + opts.port + ';\\n'\n + ' server_name ' + opts.domain + ';\\n'\n + ' \\n';\n }\n\n host += ' location /apidefender {\\n'\n + ' return 403; \\n'\n + '}\\n';\n\n host += ' location / {\\n'\n + ' proxy_pass http://127.0.0.1:3000;\\n'\n + ' proxy_set_header Host $host;\\n'\n + ' proxy_set_header Accept-Encoding \"\";\\n'\n + ' proxy_set_header X-Forwarded-Proto $scheme;\\n'\n + ' proxy_set_header X-Forwarded-For $remote_addr;\\n'\n + ' }\\n'\n + '}\\n';\n return host;\n}", "constructor() {\n this.state = \"secure\"\n this.securityState = Ci.nsIWebProgressListener.STATE_IS_SECURE\n this.errorCode = Cr.NS_OK\n this.shortSecurityDescription = \"Content Addressed\"\n this.SSLStatus = {\n cipherSuite: \"TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256\",\n // TLS_VERSION_1_2\n protocolVersion: 3,\n isDomainMismatch: false,\n isNotValidAtThisTime: true,\n serverCert: {\n subjectName: \"Content Addressing\",\n displayName: \"Content Addressing\",\n certType: Ci.nsIX509Cert.CA_CERT,\n isSelfSigned: true,\n validity: {}\n }\n }\n }", "function change_tls() {\n\tlogger.warn('[tls] changing tls key file:', process.env.KEY_FILE_PATH);\n\tlogger.warn('[tls] changing tls cert file:', process.env.PEM_FILE_PATH);\n\t//httpServer._sharedCreds.context.setKey(tools.fs.readFileSync(process.env.KEY_FILE_PATH));\t\t// this way doesn't seem to work...\n\t//httpServer._sharedCreds.context.setCert(tools.fs.readFileSync(process.env.PEM_FILE_PATH));\n\tconst notice = {\n\t\tstatus: 'success',\n\t\tmessage: 'restarting application to update tls on webserver',\n\t\tby: 'system',\n\t\tseverity: 'warning',\n\t};\n\ttools.notifications.create(notice, () => {\t\t\t\t\t\t// send notification to clients\n\t\ttools.ot_misc.restart_athena('system_tls_change');\t\t\t// restart athena to use the new tls files\n\t});\n}", "function renderTlsClientPolicy(scope, tlsClientPolicy) {\n const certificate = tlsClientPolicy?.mutualTlsCertificate?.bind(scope).tlsCertificate;\n const sans = tlsClientPolicy?.validation.subjectAlternativeNames;\n return tlsClientPolicy\n ? {\n certificate: certificate,\n ports: tlsClientPolicy.ports,\n enforce: tlsClientPolicy.enforce,\n validation: {\n subjectAlternativeNames: sans\n ? {\n match: sans.bind(scope).subjectAlternativeNamesMatch,\n }\n : undefined,\n trust: tlsClientPolicy.validation.trust.bind(scope).tlsValidationTrust,\n },\n }\n : undefined;\n}", "function describeTLS(socket) {\n if (socket instanceof tls_1.TLSSocket) {\n const protocol = socket.getProtocol();\n return protocol ? protocol : \"Server socket or disconnected client socket\";\n }\n return \"No encryption\";\n}", "updateOutboundTLSConfig(outboundTLSConfig) {\n const newConfig = JSON.parse(JSON.stringify(this._currentConfig));\n newConfig.outbound.tls = outboundTLSConfig;\n this.updateNewConfig(newConfig)\n }", "secure({timeout=0}={}) {\n let isPossible = this.hasExtension('STARTTLS');\n if (!isPossible) {\n throw new Error(`SMTP server does not support TLS`);\n }\n\n let lines = [];\n let handler = (line) => lines.push(line);\n let command = `STARTTLS\\r\\n`;\n\n return this.write(command, {timeout, handler}).then((code) => {\n if (code.charAt(0) !== '2') {\n throw this._createSMTPResponseError(lines);\n }\n else {\n return this.negotiateTLS({timeout});\n }\n }).then(() => {\n this._extensions = [];\n });\n }", "function sslChanged(userAction)\n{\n const DEFAULT_SMTP_PORT = \"587\";\n const DEFAULT_SMTPS_PORT = \"465\";\n var socketType = gSmtpSocketType.value;\n var otherDefaultPort;\n var prevDefaultPort = gDefaultPort.value;\n\n if (socketType == Ci.nsMsgSocketType.SSL) {\n gDefaultPort.value = DEFAULT_SMTPS_PORT;\n otherDefaultPort = DEFAULT_SMTP_PORT;\n } else {\n gDefaultPort.value = DEFAULT_SMTP_PORT;\n otherDefaultPort = DEFAULT_SMTPS_PORT;\n }\n\n // If the port is not set,\n // or the user is causing the default port to change,\n // and the port is set to the default for the other protocol,\n // then set the port to the default for the new protocol.\n if ((gPort.value == \"\") ||\n (userAction && (gDefaultPort.value != prevDefaultPort) &&\n (gPort.value == otherDefaultPort)))\n gPort.value = gDefaultPort.value;\n\n // switch \"insecure password\" label\n setLabelFromStringBundle(\"authMethod-password-cleartext\",\n socketType == Ci.nsMsgSocketType.SSL ||\n socketType == Ci.nsMsgSocketType.alwaysSTARTTLS ?\n \"authPasswordCleartextViaSSL\" : \"authPasswordCleartextInsecurely\");\n}", "function _addSslConfig(root, options, config) {\n let sslKey = undefined;\n let sslCert = undefined;\n if (options.sslKey) {\n const keyPath = path.resolve(root, options.sslKey);\n if (fs_1.existsSync(keyPath)) {\n sslKey = fs_1.readFileSync(keyPath, 'utf-8');\n }\n }\n if (options.sslCert) {\n const certPath = path.resolve(root, options.sslCert);\n if (fs_1.existsSync(certPath)) {\n sslCert = fs_1.readFileSync(certPath, 'utf-8');\n }\n }\n config.https = true;\n if (sslKey != null && sslCert != null) {\n config.https = {\n key: sslKey,\n cert: sslCert,\n };\n }\n}", "printConfig() {\n Logger.success(this.config);\n Logger.success(this.encryptedConfig);\n }", "get hasTLS() {\n return \"encrypted\" in this._socket;\n }", "function buildTlsOpts(node_obj) {\n\t\tlet ret = {\n\t\t\t'ssl-target-name-override': null,\n\t\t\tpem: null\n\t\t};\n\t\tif (node_obj) {\n\t\t\tif (node_obj.tlsCACerts) {\n\t\t\t\tret.pem = loadPem(node_obj.tlsCACerts);\n\t\t\t}\n\t\t\tif (node_obj.grpcOptions) {\n\t\t\t\tret['ssl-target-name-override'] = node_obj.grpcOptions['ssl-target-name-override'];\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}", "static getTlsOptions(options) {\n\n\t\tconst config = {};\n\n\t\treturn Promise.all(Object.keys(options).map((key) => {\n\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tif (certificates.has(key)) {\n\t\t\t\t\tfs.readFile(options[key], (error, content) => {\n\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\treject(error);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconfig[key] = content;\n\t\t\t\t\t\t\tresolve();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tconfig[key] = options[key];\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t});\n\t\t})).then(() => config);\n\t}", "get hasTLS() {\n return \"encrypted\" in this._socket;\n }", "function sslChanged(userAction) {\n const DEFAULT_SMTP_PORT = \"587\";\n const DEFAULT_SMTPS_PORT = \"465\";\n var socketType = gSmtpSocketType.value;\n var otherDefaultPort;\n var prevDefaultPort = gDefaultPort.value;\n\n if (socketType == Ci.nsMsgSocketType.SSL) {\n gDefaultPort.value = DEFAULT_SMTPS_PORT;\n otherDefaultPort = DEFAULT_SMTP_PORT;\n } else {\n gDefaultPort.value = DEFAULT_SMTP_PORT;\n otherDefaultPort = DEFAULT_SMTPS_PORT;\n }\n\n // If the port is not set,\n // or the user is causing the default port to change,\n // and the port is set to the default for the other protocol,\n // then set the port to the default for the new protocol.\n if (\n gPort.value == 0 ||\n (userAction &&\n gDefaultPort.value != prevDefaultPort &&\n gPort.value == otherDefaultPort)\n ) {\n gPort.value = gDefaultPort.value;\n }\n\n // switch \"insecure password\" label\n setLabelFromStringBundle(\n \"authMethod-password-cleartext\",\n socketType == Ci.nsMsgSocketType.SSL ||\n socketType == Ci.nsMsgSocketType.alwaysSTARTTLS\n ? \"authPasswordCleartextViaSSL\"\n : \"authPasswordCleartextInsecurely\"\n );\n}", "function populateTlsConfig(tlsConfigXml){\n\tvar tlsConfRoot = tlsConfigXml.getElementsByTagName('tls_params');\n\tif(tlsConfRoot && tlsConfRoot.length > 0){\n\t\tsetIpAddress('ipDataServer', getTagContent(tlsConfRoot[0], 'data_server_ip'));\n\t\tsetFieldContent(document.getElementById('txtDataPeriod'), getTagContent(tlsConfRoot[0], 'data_period'));\n\t\tsetFieldContent(document.getElementById('txtDataPort'), getTagContent(tlsConfRoot[0], 'data_port'));\n\t\tsetIpAddress('ipSnmpServer', getTagContent(tlsConfRoot[0], 'snmp_server_ip'));\n\t\tsetIpAddress('ipSntpServer', getTagContent(tlsConfRoot[0], 'sntp_server_ip'));\n\t\tvar dataType = getTagContent(tlsConfRoot[0], 'data_type');\n\t\tvar dropType = document.getElementById('ddType');\n\t\tdropType.selectedIndex = getIndexFor(dataType);\n\t\t\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
refreshes GistList element of HTML, creating HTML elements from Gist object array
function updateList() { var list = document.getElementById('gistlist'); clearNode(list); GistList.filter(listFilter).forEach(function(gist) { list.appendChild(GistListItem(gist)); }); }
[ "function generateList() {\n var gistList = document.getElementById('gistList');\n gistList.innerHTML = '';\n\n for (var i = 0; i < fetchedGist.length; i++)\n \tgistList.appendChild(createListItem(fetchedGist[i], i, false));\n}", "function generateGistList(JSONArray) {\n\tvar descriptions = document.getElementById(\"searchResults\");\n\tfor (var obj in JSONArray) {\n\t\tvar key = JSONArray[obj].html_url;\n\t\t\n\t\t//create new definition list to hold link and corresponding\n\t\t//\"save to favorites\" button\n\t\tvar newItem = document.createElement(\"dl\");\n\t\tnewItem.setAttribute(\"id\", key);\n\t\t\n\t\t//create new define term to hold link\n\t\tvar link = document.createElement(\"dt\");\n\t\t\n\t\t//create new description term to hold the \"save\" button\n\t\tvar button = document.createElement(\"dd\");\n\t\t\n\t\t//create anchor to hold gist description/link\n\t\tvar anchor = document.createElement(\"a\");\n\t\tanchor.setAttribute(\"href\", JSONArray[obj].html_url);\n\t\tvar descript = JSONArray[obj].description; \n\t\tif (descript === null || descript === \"\") {\n\t\t\tanchor.innerHTML = \"No Description\";\n\t\t}\n\t\telse {\n\t\t\tanchor.innerHTML = (descript); \n\t\t}\n\t\t\n\t\t//create \"save\" button\n\t\tvar saveButton = document.createElement(\"button\");\n\t\tvar text = document.createTextNode(\"Add to Favorites\");\n\t\tsaveButton.appendChild(text);\n\t\tsaveButton.setAttribute(\"name\", JSONArray[obj].html_url);\n\t\tsaveButton.addEventListener(\"click\", function() {\n\t\taddToFavorites(document.getElementById(this.name)); });\n\t\tbutton.appendChild(saveButton); \n\t\t\n\t\t//append these items together into a single definition list\n\t\tbutton.appendChild(saveButton);\n\t\tlink.appendChild(anchor);\n\t\tlink.appendChild(button);\n\t\tnewItem.appendChild(link);\n\t\t\n\t\t//append the new item to the descriptions div\n\t\tdescriptions.appendChild(newItem);\n\t}\n}", "function createGistList(){\n var ul = document.getElementById('gist-list')\n var favoriteGist = false;\n \n //Remove old list from page\n for (var i=ul.childNodes.length-1; i >= 0; i--) {\n ul.removeChild(ul.childNodes[i]);\n } \n \n //Create new list on page\n for (var i=0; i < gistList.gists.length; i++){\n favoriteGist = false;\n \n //Check if the id matches any of the id's in the favorites list\n for (var j=0; j < savedFavoriteGists.gists.length; j++){\n if (savedFavoriteGists.gists[j].gId === gistList.gists[i].gId){\n favoriteGist = true;\n }\n }\n if (favoriteGist === false){\n \n //Create a list item for each search result\n var item = document.createElement('li');\n item.style = 'list-style-type:none';\n ul.appendChild(item);\n\n //Create a checkbox for each item\n var checkBox = document.createElement('input');\n checkBox.type = 'checkbox';\n checkBox.id = ('checkbox'+i);\n checkBox.checked = false;\n ul.appendChild(checkBox);\n\n //Create a link for each result\n var node = document.createElement('a');\n var nodeText = document.createTextNode(gistList.gists[i].gDescription);\n node.appendChild(nodeText);\n node.title = gistList.gists[i].gDescription;\n node.href = gistList.gists[i].gUrl;\n ul.appendChild(node);\n }\n }\n}", "function GistListItem(gist) {\n var glitem = document.createElement('div');\n glitem.setAttribute('class', 'gistItem');\n\n var firstline = document.createElement('div');\n firstline.setAttribute('class', 'firstline');\n\n //link to owner profile\n if (gist.userhtml) {\n var ownerlink = document.createElement('a');\n ownerlink.setAttribute('href', gist.userhtml);\n }\n\n //owners avatar or annonymous img\n var ownerimage = document.createElement('img');\n ownerimage.setAttribute('src', gist.useravtimg);\n ownerimage.setAttribute('alt', 'avatar');\n ownerimage.setAttribute('class', 'avatar');\n\n if (gist.userhtml) {\n ownerlink.appendChild(ownerimage);\n firstline.appendChild(ownerlink);\n } else {\n firstline.appendChild(ownerimage);\n }\n\n //description and link to gist page\n var glink = document.createElement('a');\n glink.setAttribute('class', 'description');\n glink.setAttribute('href', gist.gisthtml);\n var descText = document.createTextNode(gist.description);\n glink.appendChild(descText);\n\n firstline.appendChild(glink);\n\n glitem.appendChild(firstline);\n\n var secondline = document.createElement('div');\n secondline.setAttribute('class', 'secondLine');\n\n ////username\n if (gist.userhtml) {\n var ownername = document.createElement('a');\n ownername.setAttribute('href', gist.userhtml);\n } else {\n var ownername = document.createElement('span');\n }\n ownername.setAttribute('class', 'userName');\n var ownernameTEXT = document.createTextNode(gist.username);\n ownername.appendChild(ownernameTEXT);\n secondline.appendChild(ownername);\n\n var footer = document.createElement('span');\n footer.setAttribute('class', 'footer');\n\n //languages\n var langsdiv = document.createElement('span');\n langsdiv.setAttribute('class', 'langList');\n var langstr = '';\n gist.languages.forEach(function(lang) {\n langstr += lang + ' ';\n });\n langsdiv.appendChild(document.createTextNode(langstr));\n footer.appendChild(langsdiv);\n\n ///favorite button\n var fav = document.createElement('img');\n fav.setAttribute('src', 'emptyStar.png');\n fav.setAttribute('alt', 'favorite');\n fav.setAttribute('class', 'favoritebutton');\n fav.setAttribute('id', gist.id);\n fav.setAttribute('onclick', 'favorite(this.id, this)');\n footer.appendChild(fav);\n\n secondline.appendChild(footer);\n\n glitem.appendChild(secondline);\n\n return glitem;\n\n}", "function reloadList(){\n var listDom = document.getElementById('todo-list');\n\n listDom.innerHTML = \"\";\n for(var i=0;i<listObjects.length;i++){\n listDom.innerHTML += makeHTML(listObjects[i]);\n }\n}", "function format_gists(gists) {\n var html = \"\";\n\n for(var i=0; i<gists.length; i++) {\n var gist = gists[i];\n\n html += `<div class=\"row\"><a href=\"${gist.html_url}\" target=\"_blank\">\n\n <div class=\"about\">\n ${Object.keys(gist.files).length > 1\n ? `<button class=\"files span\">\n <i class=\"octicon octicon-gist\"></i>${Object.keys(gist.files).length} files\n </button>`\n : `<span class=\"files span\">\n <i class=\"octicon octicon-gist\"></i>${Object.keys(gist.files).length} file\n </span>`\n }\n <span class=\"update span\" title=\"Updated at\" style=\"display: none\">\n <i class=\"octicon octicon-watch\"></i><time>${gist.updated_at.replace('T', ' ').replace('Z', '')}</time>\n </span>\n <span class=\"creation span\" title=\"Created at\">\n <i class=\"octicon octicon-watch\"></i><time>${gist.created_at.replace('T', ' ').replace('Z', '')}</time>\n </span>\n </div>\n\n <label data-filter=\"title\">${gist.description}</label>\n <span data-filter=\"status\">${gist.public ? \"\" : \"<i class='octicon octicon-lock' title='Secret'></i>\"}</span>\n <ul>${Object.keys(gist.files).map((filename) => \"<li data-filter='filename'>\" + filename + \"</li>\").join('')}</ul>\n </a></div>`;\n }\n return html;\n}", "function updateUrlsOnHTML() {\n\n var urlsBox = document.getElementById(\"urlsBox\");\n urlsBox.innerHTML = \"\";\n\n for (var obj of urlsArray.reverse()) {\n var boxClone = createHtmlCard(obj);\n urlsBox.appendChild(boxClone);\n }\n}", "function loadRecentGists() {\n var localGists = localStorage['__' + wb.language + '_recent_gists'];\n var gistArray = localGists === undefined ? [] : JSON.parse(localGists);\n var gistContainer = document.querySelector(\"#recent_gists\");\n gistContainer.innerHTML = '';\n\n for (var i = 0; i < gistArray.length; i++) {\n //add a new button to the gist sub-menu\n var gist = gistArray[i];\n var node = document.createElement(\"li\");\n var button = document.createElement('button');\n var buttonText = document.createTextNode(\"#\" + gist);\n\n button.appendChild(buttonText);\n button.classList.add('load-gist');\n button.dataset.href = wb.language + \".html?gist=\" + gist;\n button.dataset.gist = gist;\n\n node.appendChild(button);\n gistContainer.appendChild(node);\n\n button.addEventListener('click', function(){\n wb.loadScriptsFromGistId(this.dataset.gist);\n });\n }\n }", "function repopulateDOM(){\n for (i=0; i<ideasArray.length; i++){\n $('ul').prepend(ideaTemplate(ideasArray[i].title, ideasArray[i].body, ideasArray[i].ranking, ideasArray[i].id));\n }\n}", "function refreshHTML() {\n $('ul').html(movieList.reduce((accum, movie) => accum += makeHTML(movie), \"\"))\n}", "function getGists() {\n var numpage = document.getElementsByName('numpage')[0].value;\n\n for (var i = 0; i < numpage; i++) {\n\n /*XMLHTTPRequest code obtained from Mozilla Developer Network*/\n var request;\n if (window.XMLHttpRequest) { /*Mozilla, Safari, IE7+...*/\n request = new XMLHttpRequest();\n } else if (window.ActiveXObject) { /*IE6 and older*/\n request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n if (!request) {\n throw 'HttpRequest cannot be created';\n }\n \n var url = 'https://api.github.com/gists?page=' + numpage + '&per_page=30';\n\n request.onreadystatechange = function() {\n if (this.readyState === 4 && this.status === 200) {\n var new_gist = JSON.parse(this.responseText);\n for (var i = 0; i < new_gist.length; i++) {\n var description = new_gist[i].description;\n var link = new_gist[i].html_url;\n var language = \"\";\n for (var prop in new_gist[i].files) {\n if (new_gist[i].files[prop].language) {\n language = new_gist[i].files[prop].language;\n }\n var next_gist = new Gist(description, link, language);\n addGist(next_gist);\n }\n }\n }\n showGist(gistList);\n };\n \n request.open('GET', url, true);\n request.send(null);\n \n }\n}", "buildFriendList(friendsArray) {\n let friendsListHTML = ``\n document.querySelector(\".container__main__middle--friends\").innerHTML = ``\n //Iterates through the friends array, sending each array to the DOM builder//\n friendsArray.forEach(friend => {\n let thisFriendHTML = friendElementHTML(friend)\n friendsListHTML += thisFriendHTML \n });\n //Places the HTML in the DOM//\n document.querySelector(\".container__main__middle--friends\").innerHTML = friendsListHTML\n }", "function displayResults(gists) {\n var resultsDiv = document.getElementById(\"results\");\n for (var i = 0; i < gists.length; i++) {\n var url = gists[i].html_url;\n var desc = gists[i].description;\n if (desc === null || desc === \"\") {\n desc = \"Untitled\";\n }\n resultsDiv.appendChild(createResultElement(url, desc, true));\n }\n}", "function renderHTML() {\r\n document.getElementById('inject').innerHTML = \"\";\r\n\r\n var ul = document.createElement(\"UL\");\r\n for(let i = 0; i < listings.length; i++) {\r\n var li = document.createElement(\"LI\");\r\n li.style.display = \"flex\";\r\n if(listings[i].visible) {\r\n var div = document.createElement('div');\r\n div.innerHTML = listings[i].val.getHTML();\r\n li.appendChild(div);\r\n ul.appendChild(li);\r\n ul.appendChild(document.createElement(\"BR\"));\r\n\r\n createListing(listings[i]);\r\n\r\n }\r\n }\r\n // document.getElementById('inject').innerHTML = \"\";\r\n // document.getElementById('inject').appendChild(ul);\r\n}", "function getGists(){\n console.log(\"running getGists()\")\n //Delete old gists, if present\n if (gistList.gists.length !== 0){\n gistList.gists = [];\n }\n\n var req = new XMLHttpRequest();\n if(!req){\n throw 'Unable to create HttpRequest.';\n }\n var url = 'http://api.github.com/gists';\n var params = {\n page: '1'\n };\n url += '?' + urlStringify(params);\n \n //Ajax call\n req.onreadystatechange = function(){\n if(this.readyState === 4){\n var ajaxGistList = JSON.parse(this.responseText);\n \n //Create list of gists with only required information\n for (var i = 0; i < ajaxGistList.length; i++){\n var gistDesc = ajaxGistList[i].description;\n var gistUrl = ajaxGistList[i].html_url;\n var gistId = ajaxGistList[i].id;\n var gistEntry = new gists(gistDesc, gistUrl, gistId);\n gistList.gists.push(gistEntry);\n }\n //Re-render list of gists\n createGistList();\n }\n };\n req.open('GET', url);\n req.send();\n}", "function createFavoritesList(){\n var ul = document.getElementById('gist-favorites')\n\n //Remove old list\n for (var i=ul.childNodes.length-1; i >= 0; i--) {\n ul.removeChild(ul.childNodes[i]);\n }\n \n //Create new list on page\n for (var i=0; i < savedFavoriteGists.gists.length && savedFavoriteGists.gists[0] !== null; i++){\n\n //Create a list item for each search result\n var item = document.createElement('li');\n item.style = 'list-style-type:none';\n ul.appendChild(item);\n\n //Create a remove button for each item\n var removeFav = document.createElement('input');\n removeFav.type = 'button';\n removeFav.id = ('removeFavBtn'+i);\n removeFav.value = ('Delete');\n \n removeFav.onclick = function(){\n var removeIndex = this.id;\n removeIndex = removeIndex.substring(12, removeIndex.length);\n //console.log('removeIndex: ' + removeIndex);\n var removeId = savedFavoriteGists.gists[removeIndex].gId;\n //console.log('Remove id:' + removeId);\n removeFavorites(removeId);\n };\n ul.appendChild(removeFav);\n\n //Create a link for each result\n var node = document.createElement('a');\n var nodeText = document.createTextNode(savedFavoriteGists.gists[i].gDescription);\n node.appendChild(nodeText);\n node.title = savedFavoriteGists.gists[i].gDescription;\n node.href = savedFavoriteGists.gists[i].gUrl;\n ul.appendChild(node);\n }\n}", "function renderImgs() {\n var imgs = getImgs();\n var strHTMLs = imgs.map(function(img) {\n return `<img id=\"${img.id}\" src=${img.url} alt=\"\" onclick=\"addIdToStorage(${img.id})\"></img>`;\n });\n var elImgList = document.querySelector('.image-gallery');\n elImgList.innerHTML = strHTMLs.join('');\n}", "function refreshAlbum(container, array) {\n for (var i = 0; i < array.length; i++) {\n container.appendChild(array[i]); }\n}", "function htmlFillRawTitlesList(rawTitlesSelectedRecipe) {\n console.log('htmlFillRawTitlesList ' + rawTitlesSelectedRecipe);\n $('#SelecteRecipeList').empty(); //empties the list to refill it again\n for (var i in rawTitlesSelectedRecipe) {\n var li = document.createElement(\"li\");\n li.className = \"list-group-item\";\n li.setAttribute(\"id\", \"RecipeItem\");\n var liContent = document.createTextNode(rawTitlesSelectedRecipe[i]);\n li.appendChild(liContent);\n htmlRecipeTitlesList.appendChild(li);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a new AttachmentArchiveItemReadable. Metadata for an item in an attachment archive.
constructor() { AttachmentArchiveItemReadable.initialize(this); }
[ "function AttachmentArchiveImpl() {\n _classCallCheck(this, AttachmentArchiveImpl);\n\n AttachmentArchiveImpl.initialize(this);\n }", "function AttachmentMetadata() {\n _classCallCheck(this, AttachmentMetadata);\n\n AttachmentMetadata.initialize(this);\n }", "function getMetadataFromItem(dir, item, root) {\n const par = dir.replace(/^\\/+/, '').replace(/\\/+$/, '');\n const path = root + (par ? par + '/' : par) + item.name;\n\n const itemFile = new FileMetadata({\n id: item.id,\n filename: item.name,\n size: item.size || 0,\n path: path,\n mime: getItemMime(item),\n type: getItemType(item)\n });\n return itemFile;\n}", "_createItem(options) {\n let factory = this.contentFactory;\n let item = factory.createAttachmentModel(options);\n item.changed.connect(this._onGenericChange, this);\n return item;\n }", "function ItemMeta(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = classnames__WEBPACK_IMPORTED_MODULE_1___default()('meta', className);\n var rest = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getUnhandledProps\"])(ItemMeta, props);\n var ElementType = Object(_lib__WEBPACK_IMPORTED_MODULE_4__[\"getElementType\"])(ItemMeta, props);\n return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ElementType, _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()({}, rest, {\n className: classes\n }), _lib__WEBPACK_IMPORTED_MODULE_4__[\"childrenUtils\"].isNil(children) ? content : children);\n}", "function ItemMeta(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n\n var classes = (0, _classnames2.default)(className, 'meta');\n var rest = (0, _lib.getUnhandledProps)(ItemMeta, props);\n var ElementType = (0, _lib.getElementType)(ItemMeta, props);\n\n return _react2.default.createElement(\n ElementType,\n (0, _extends3.default)({}, rest, { className: classes }),\n (0, _isNil3.default)(children) ? content : children\n );\n}", "function ItemMeta(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = classnames_default()('meta', className);\n var rest = lib_getUnhandledProps(ItemMeta, props);\n var ElementType = lib_getElementType(ItemMeta, props);\n return react_default.a.createElement(ElementType, extends_default()({}, rest, {\n className: classes\n }), childrenUtils_namespaceObject.isNil(children) ? content : children);\n}", "function ItemMeta(props) {\n var children = props.children,\n className = props.className,\n content = props.content;\n var classes = (0, _classnames.default)('meta', className);\n var rest = (0, _lib.getUnhandledProps)(ItemMeta, props);\n var ElementType = (0, _lib.getElementType)(ItemMeta, props);\n return _react.default.createElement(ElementType, (0, _extends2.default)({}, rest, {\n className: classes\n }), _lib.childrenUtils.isNil(children) ? content : children);\n}", "constructor() { \n \n AttachmentMetadata.initialize(this);\n }", "function generateItem(doc, node) {\n\tvar item = new Zotero.Item();\n\tZotero.Utilities.parseContextObject(node.nodeValue, item);\n\t// if only one, first check for special types (audio & video recording)\n\tvar type = false;\n\ttry {\n\t\ttype = doc.evaluate('//img[@class=\"icn\"][contains(@src, \"icon-\")]/@src', doc, null, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;\n\t} catch (e) {}\n\tif (type) {\n\t\ttype = getZoteroType(type);\n\t\tif (type) item.itemType = type;\n\t}\n\t\n\treturn item;\n}", "function _metadata(inst) {\n const options = inst[optionsAttr]\n\n const getProp = (prop) => {\n return inst.getAssetProp(prop)\n }\n\n // Build the props for the Metadata instance\n const props = [\n ['Filename', 'filename', getProp('filename'), true],\n ['Content type', 'contentType', getProp('contentType'), true],\n ['File size', 'fileLength', getProp('fileLength'), true]\n ]\n\n if (options.fileType === 'image') {\n props.push(['Mode', 'imageMode', getProp('imageMode'), true])\n props.push(['Size', 'imageSize', getProp('imageSize'), true])\n props.push(['Alt', 'alt', getProp('alt'), false])\n\n } else if (options.fileType === 'svg_image') {\n props.push(['Alt', 'alt', getProp('alt'), false])\n }\n\n return new Metadata(props)\n }", "function ImportInstanceVolumeDetailItem() {\n _classCallCheck(this, ImportInstanceVolumeDetailItem);\n\n ImportInstanceVolumeDetailItem.initialize(this);\n }", "function generateItem(doc, node) {\n\tvar item = new Zotero.Item();\n\tZotero.Utilities.parseContextObject(node.nodeValue, item);\n\t\n\t// if only one, first check for special types (audio & video recording)\n\tvar type = false;\n\ttry {\n\t\ttype = doc.evaluate('//img[@class=\"icn\"][contains(@src, \"icon-\")]/@src', doc, null, XPathResult.ANY_TYPE, null).iterateNext().nodeValue;\n\t} catch(e) {}\n\t\n\tif(type) {\n\t\ttype = getZoteroType(type);\n\t\tif(type) item.itemType = type;\n\t}\n\t\n\treturn item;\n}", "function FeedItem() {\n this._init.apply(this, arguments);\n}", "function RSS2Item(itemxml)\n\t{\n\t\t//required\n\t\tthis.title;\n\t\tthis.link;\n\t\tthis.description;\n\n\t\t//optional vars\n\t\tthis.author;\n\t\tthis.comments;\n\t\tthis.pubDate;\n\n\t\t//optional objects\n\t\tthis.category;\n\t\tthis.enclosure;\n\t\tthis.guid;\n\t\tthis.source;\n\n\t\tvar properties = new Array(\"title\", \"link\", \"description\", \"author\", \"comments\", \"pubDate\");\n\t\tvar tmpElement = null;\n\t\tfor (var i=0; i<properties.length; i++)\n\t\t{\n\t\t\ttmpElement = itemxml.getElementsByTagName(properties[i])[0];\n\t\t\tif (tmpElement != null && tmpElement.childNodes && tmpElement.childNodes[0])\n\t\t\t\teval(\"this.\"+properties[i]+\"=tmpElement.childNodes[0].nodeValue\");\n\t\t}\n\n\t\tthis.category = new RSS2Category(itemxml.getElementsByTagName(\"category\")[0]);\n\t\tthis.enclosure = new RSS2Enclosure(itemxml.getElementsByTagName(\"enclosure\")[0]);\n\t\tthis.guid = new RSS2Guid(itemxml.getElementsByTagName(\"guid\")[0]);\n\t\tthis.source = new RSS2Source(itemxml.getElementsByTagName(\"source\")[0]);\n\t}", "function buildAudioItem(data, i, image) {\n\tret = {\n\t\tid: 1,\n\t\tstream: [\n\t\t\t{\n\t\t\t\turl: data.rss.channel.item[i]['enclosure']['@url'],\n\t\t\t\tformat: \"mp3\"\n\t\t\t}\n\t\t],\n\t\talbumArtUrl: image\n\t}\n\tif (data.rss.channel.item[i].title)\n\t\tret.title = data.rss.channel.item[i].title\n\telse\n\t\tret.title = \"No title\"\n\tif (data.rss.channel.item[i]['itunes:subtitle'])\n\t\tret.subtitle = data.rss.channel.item[i]['itunes:subtitle']\n\telse\n\t\tret.subtitle = \"No subtitle\"\n\tif (data.rss.channel.item[i]['itunes:author'])\n\t\tret.artist = data.rss.channel.item[i]['itunes:author']\n\telse\n\t\tret.artist = \"No artist\"\n\treturn (ret)\n}", "static fromString(attachment, api) {\r\n if (!parseAttachmentRe.test(attachment)) {\r\n throw new TypeError('Incorrect attachment');\r\n }\r\n const [, type, ownerId, id, accessKey] = attachment.match(parseAttachmentRe);\r\n return new Attachment({\r\n api,\r\n type,\r\n payload: {\r\n id: Number(id),\r\n owner_id: Number(ownerId),\r\n access_key: accessKey\r\n }\r\n });\r\n }", "function constructItem() {\n var item = {\n \"workers_id\": $scope.worker_data.worker_id,\n \"status\": 0,\n \"action_time\": $scope.date,\n \"created_at\": $scope.date,\n \"updated_at\": $scope.date,\n \"author_id\": $scope.userId,\n \"updater_id\": $scope.userId\n };\n return item;\n }", "function createItem() {\n const args = Array.prototype.slice.call(arguments);\n const name = args.shift();\n args.unshift(DEFAULT_ITEM);\n return createObject(name, args);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
counterclockwise rotate 2D vector, xy, by angle (in degrees) [original CKOG uses clockwise rotation]
function rotate(xy, angle) { var xynew = [0, 0]; if (angle === -60) { xynew[0] = xy[0] * CK.cos60 + xy[1] * CK.sin60; xynew[1] = -xy[0] * CK.sin60 + xy[1] * CK.cos60; } else if (angle === -120) { xynew[0] = -xy[0] * CK.cos60 + xy[1] * CK.sin60; xynew[1] = -xy[0] * CK.sin60 - xy[1] * CK.cos60; } else { // !!!!! This should not happen for this projection!!!! // the general algorith: cos(angle) * xy + sin(angle) * perpendicular(xy) // return cos(angle * radians) * xy + sin(angle * radians) * perpendicular(xy); //console.log("rotate: angle " + angle + " different than -60 or -120!"); // counterclockwise xynew[0] = xy[0] * cos(angle * radians) - xy[1] * sin(angle * radians); xynew[1] = xy[0] * sin(angle * radians) + xy[1] * cos(angle * radians); } return xynew; }
[ "function rotateAroundPoint(xy1, xy2, degree){\n let radian = degreeToRadian(degree);\n return vec2(Math.cos(radian) * (xy1[0] - xy2[0]) - Math.sin(radian) * (xy1[1] - xy2[1]) + xy2[0], \n Math.sin(radian) * (xy1[0] - xy2[0]) + Math.cos(radian) * (xy1[1] - xy2[1]) + xy2[1]);\n}", "function rotate2d(oldx, oldy, angle)\r\n{\r\n var sin = Math.sin(angle);\r\n var cos = Math.cos(angle);\r\n var newx = ( oldx * cos ) - ( oldy * sin );\r\n var newy = ( oldy * cos ) + ( oldx * sin );\r\n return [newx, newy];\r\n}", "rotateCounterclockwise() {}", "rotate(angle)\n {\n //rotate the vector clockwise by the given degrees\n var x = this.x * Math.cos(angle * Math.PI / 180) - this.y * Math.sin(angle * Math.PI / 180);\n var y = this.x * Math.sin(angle * Math.PI / 180) + this.y * Math.cos(angle * Math.PI / 180);\n\n return new Vector(x, y);\n }", "rotated(angle) {\n const newAngle = this.angle + angle;\n const mag = this.magnitude;\n return v2(mag * Math.cos(newAngle), mag * Math.sin(newAngle));\n }", "static rotate2D(v, angle) {\n\t\tvar x = v.x * Math.cos(angle) - v.y * Math.sin(angle);\n\t\tvar y = v.x * Math.sin(angle) + v.y * Math.cos(angle);\n\t\tvar args = [];\n\t\targs.push(x);\n\t\targs.push(y);\n\t\tif (v.z) {\n\t\t\targs.push(v.z);\n\t\t}\n\t\tif (v.w) {\n\t\t\targs.push(v.w);\n\t\t}\n\t\treturn Vector.arrayToVector(args);\n\t}", "function rotate(cx, cy, x, y, angle) {\n //X' = X cosB - Y sinB\n //Y' = X sinB + Y cosB\n var radians = (Math.PI / 180) * angle,\n cos = Math.cos(radians),\n sin = Math.sin(radians),\n nx = (cos * (x - cx)) - (sin * (y - cy)) + cx,\n ny = (sin * (x - cx)) + (cos * (y - cy)) + cy;\n return [nx, ny];\n }", "function vector_rotate() {\n var args = Array.prototype.slice.call(arguments);\n var angle = args.shift();\n var result = [];\n var sin=Math.sin(angle);\n var cos=Math.cos(angle);\n var vector;\n\n while (vector = args.shift()) {\n result.push([vector[0] * cos - vector[1] * sin,\n vector[0] * sin + vector[1] * cos]);\n }\n\n return result.length == 1 ? result[0] : result;\n}", "rotate(xin, yin) {\n const radians = Math.atan2(this.y, this.x);\n const x = xin * Math.cos(radians) - yin * Math.sin(radians);\n const y = xin * Math.sin(radians) + yin * Math.cos(radians);\n return {\n x,\n y\n };\n }", "function rotate(xRadians,yRadians,zRadians, point) {\n\n var cosa = R.cos(zRadians);\n var sina = R.sin(zRadians);\n\n var cosb = R.cos(yRadians);\n var sinb = R.sin(yRadians);\n\n var cosc = R.cos(xRadians);\n var sinc = R.sin(xRadians);\n\n var Axx = R.mul(cosa,cosb);\n var Axy = R.sub(R.mul(R.mul(cosa,sinb),sinc),R.mul(sina,cosc));\n var Axz = R.add(R.mul(cosa,R.mul(sinb,cosc)),R.mul(sina,sinc));\n\n var Ayx = R.mul(sina,cosb);\n var Ayy = R.add(R.mul(R.mul(sina,sinb),sinc),R.mul(cosa,cosc))\n var Ayz = R.sub(R.mul(R.mul(sina,sinb),cosc),R.mul(cosa,sinc));\n\n var Azx = R.mul(sinb,-1);\n var Azy = R.mul(cosb,sinc);\n var Azz = R.mul(cosb,cosc);\n\n return R.vector(\n R.add(R.add(R.mul(Axx, point.x), R.mul(Axy, point.y)), R.mul(Axz, point.z)),\n R.add(R.add(R.mul(Ayx, point.x), R.mul(Ayy, point.y)), R.mul(Ayz, point.z)),\n R.add(R.add(R.mul(Azx, point.x), R.mul(Azy, point.y)), R.mul(Azz, point.z))\n )\n}", "rotateAboutXY(x, y, angle) {\n const dx = this.x - x;\n const dy = this.y - y;\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n this.x = x + dx * cos - dy * sin;\n this.y = y + dx * sin + dy * cos;\n return this;\n }", "function rotateCartesian(vector, axis, angle) {\n\t var angleRads = angle * radians,\n\t vectorOut = vector.slice(),\n\t ax1 = (axis===0) ? 1 : 0,\n\t ax2 = (axis===2) ? 1 : 2,\n\t cosa = Math.cos(angleRads),\n\t sina = Math.sin(angleRads);\n\n\t vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;\n\t vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;\n\n\t return vectorOut;\n\t}", "function rotateCartesian(vector, axis, angle) {\n var angleRads = angle * radians,\n vectorOut = vector.slice(),\n ax1 = axis === 0 ? 1 : 0,\n ax2 = axis === 2 ? 1 : 2,\n cosa = Math.cos(angleRads),\n sina = Math.sin(angleRads);\n\n vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;\n vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;\n\n return vectorOut;\n }", "function rotateCartesian(vector, axis, angle) {\n\t var angleRads = angle * radians,\n\t vectorOut = vector.slice(),\n\t ax1 = (axis === 0) ? 1 : 0,\n\t ax2 = (axis === 2) ? 1 : 2,\n\t cosa = Math.cos(angleRads),\n\t sina = Math.sin(angleRads);\n\n\t vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;\n\t vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;\n\n\t return vectorOut;\n\t}", "rotate(angle) {\n const newAngle = this.angle + angle;\n const mag = this.magnitude;\n return this.setXY(mag * Math.cos(newAngle), mag * Math.sin(newAngle));\n }", "function rotatePolyInPlace( coordinates, xCenter, yCenter, angle ){\n\tfor (var coordinateIndex in coordinates) {\n\t\tvar x = coordinates[coordinateIndex].x;\n\t\tvar y = coordinates[coordinateIndex].y;\n\t\tcoordinates[coordinateIndex].x = x*Math.cos(angle) - y*sin(angle);\n\t\tcoordinates[coordinateIndex].y = x*Math.sin(angle) + y*cos(angle);\n\t}\n\n}", "function rotateCartesian(vector, axis, angle) {\n\t var angleRads = angle * radians,\n\t vectorOut = vector.slice(),\n\t ax1 = (axis === 0) ? 1 : 0,\n\t ax2 = (axis === 2) ? 1 : 2,\n\t cosa = Math.cos(angleRads),\n\t sina = Math.sin(angleRads);\n\t\n\t vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;\n\t vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;\n\t\n\t return vectorOut;\n\t}", "function rotateCartesian(vector, axis, angle) {\n var angleRads = angle * radians;\n var vectorOut = vector.slice();\n var ax1 = (axis === 0) ? 1 : 0;\n var ax2 = (axis === 2) ? 1 : 2;\n var cosa = Math.cos(angleRads);\n var sina = Math.sin(angleRads);\n\n vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;\n vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;\n\n return vectorOut;\n}", "function getRotate(angle){\n var cos = Math.cos(angle);\n var sin = Math.sin(angle);\n return new Vector4([cos, sin, -sin, -cos]);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all of the IDs that have been issued new IDs in the order in which they were issued new IDs.
getOldIds() { return [...this._existing.keys()]; }
[ "async function getFilteredIBSAlarmIds(newIds, currentIds) {\n\n /**\n * array for alarm ids which are \n * not available in the store/state\n */\n let filteredIdArray = [];\n\n //Find values that are in newAlarms but not in currentAlarms\n filteredIdArray = newIds.filter(function (val) {\n return currentIds.indexOf(val) === -1;\n });\n\n return filteredIdArray;\n}", "function getIDs() {\n if (ticketList.length > 0) {\n return ticketList.reduce((acc, obj) => {\n return acc.concat(obj.id);\n }, []);\n }\n return [];\n}", "function getNewIds(opt){\n\treturn new Promise((resolve, reject) => {\n\t\tconsole.log('Getting all new IDs...')\n\t\tconst nightmare = Nightmare(nightmareOptions)\n\t\tnightmare\n\t\t\t.goto(`https://cloud.collectorz.com/${opt.userId}/comics?viewType=list`)\n\t\t\t.cookies.set([{\n\t\t\t\tname: 'comic[collection][sorting]',\n\t\t\t\tvalue: '%7B%22AddedDate%22%3A%22DESC%22%7D',\n\t\t\t\tpath: '/',\n\t\t\t\tsecure: true\n\t\t\t}, {\n\t\t\t\tname: '${opt.userId}[comic][collection][lastQueryString]',\n\t\t\t\tvalue: 'sort%3DAddedDate%26order%3DDESC',\n\t\t\t\tpath: '/',\n\t\t\t\tsecure: true\n\t\t\t}])\n\t\t\t.refresh()\n\t\t\t.wait('.x-collection')\n\t\t\t.evaluate(getList, opt)\n\t\t\t.end()\n\t\t\t.then(ids => {\n\t\t\t\tconsole.log('Got IDs.')\n\t\t\t\topt.comics = ids\n\t\t\t\tresolve(opt)\n\t\t\t})\n\t\t\t.catch(reject)\n\t})\n}", "_updateLatestIds() {\n const idsArr = _check.array(this._latestResult)\n ? _map(this._latestResult, x => x._id)\n : this._latestResult && [this._latestResult._id];\n this._latestIds = new Set(idsArr);\n }", "_updateLatestIds() {\n if (_check.array(this._latestResult)) {\n this._latestIds = new Set(_map(this._latestResult, x => x._id));\n } else if (this._latestResult && this._latestResult._id) {\n this._latestIds = new Set([this._latestResult._id]);\n }\n }", "function getDuplicateLicenseIds(requests) {\n var idsExisted = [];\n var idsDuplicate = [];\n for (var i = 0; i < requests.length; i++) {\n if (!arrayContains(idsExisted, requests[i].license_id)) {\n idsExisted.push(requests[i].license_id);\n } else {\n if (!arrayContains(idsDuplicate, requests[i].license_id)) {\n idsDuplicate.push(requests[i].license_id);\n }\n }\n }\n\n return idsDuplicate;\n}", "getIds() {\n\t\tthrow new Error(\"Not yet implemented\");\n\t}", "function getErrorIds(users, idsRequested) {\n let idsArr = [];\n for (let i = 0; i < users.length; i++) {\n idsArr.push(users[i].id);\n }\n return idsRequested.filter(e => idsArr.indexOf(e) === -1);\n}", "static getOrderIDs() {\n const orders = this.getAllOrders();\n let ids = orders.map((order) => {\n return order.id;\n });\n return ids;\n }", "get ids() {\n return this.issues.map(issue => issue.id);\n }", "function makeIdArray() {\n for (let i=0; i<funsListed.length; i++) {\n idList.push(funsListed[i].id);\n }\n return idList;\n }", "getIds () {\n\t\treturn keys( this.names ).map( name => this.lookup( name ) );\n\t}", "get insertedIds() {\n if (this[kInsertedIds]) {\n return this[kInsertedIds];\n }\n\n this[kInsertedIds] = {};\n for (const doc of this.result.insertedIds || []) {\n this[kInsertedIds][doc.index] = doc._id;\n }\n return this[kInsertedIds];\n }", "function getListOfElementsIdsInUse() {}", "get itemIds() {\n return filterOutUndefined(this._items.map(item => item.uniqueId));\n }", "function nextId(ids){\n let filteredArr = ids.filter(elm => {\n return ids.indexOf(elm) === ids.lastIndexOf(elm)\n })\n let uniqueArr = ids.filter(elm => {\n return ids.indexOf(elm) != ids.lastIndexOf(elm)\n })\n for (id of uniqueArr) {\n if (filteredArr.includes(id)) {\n \n } else {\n filteredArr.push(id)\n }\n }\n let sortedArr = filteredArr.sort((a, b) => a - b)\n//Haha maybe include \n for (let i = 0; i <= sortedArr.length; i++) {\n if (sortedArr[i] != i) {\n return i\n }\n }\n}", "function getIDSKeysToModify() {\n const messagesToModify = new Map();\n for (const [expectedIDSKey, messages] of IDSkeys) {\n for (const message of messages) {\n if (expectedIDSKey !== message.actualIDSKey) {\n if (messagesToModify.has(expectedIDSKey))\n messagesToModify.get(expectedIDSKey).push(message);\n else\n messagesToModify.set(expectedIDSKey, [message]);\n }\n }\n }\n return messagesToModify;\n}", "function getReceiptIds(tickets) {\n let receiptIds = [];\n for (let ticket of tickets) {\n if (ticket.id) {\n receiptIds.push(ticket.id);\n }\n }\n return receiptIds;\n}", "function getAllNewIncident () {\n\treturn dbQuery(\"SELECT * FROM NewIncident WHERE Resolved=0\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds address information using the given hostname, port, protocol and proxyinfo.
getAddrStr(hostName, port, protocol, proxyInfo) { let host = hostName.trim(); // If it is IPV6 format address then remove the enclosing '[' and ']' if (host.startsWith("[") && host.endsWith("]")) host = host.substring(1, host.length - 1); return `(ADDRESS=(PROTOCOL=${protocol})(HOST=${host})(PORT=${port})${proxyInfo})`; }
[ "function buildUrl(protocol, ip, port) {\n var url = protocol + '://' + ip + ':' + port;\n if(protocol !== 'http'){\n url += '/mqtt';\n }\n return url;\n }", "_buildAddress(name, addr1, addr2, city, state, zip) {\n var completeAddr = name + '\\n' + addr1 + '\\n';\n if (addr2 == '') {\n return completeAddr + city + \", \" + state + \" \" + zip;\n }\n return completeAddr + addr2 + '\\n' + city + \", \" + state + \" \" + zip;\n }", "function constructProxyIp(creds) {\n var privip = creds['privip'],\n port = creds['port'];\n\n var proxyIp = privip.replace(/\\./gi, \"-\") + \"-\" + port.toString() + \".\" + \"neo4jsandbox.com\";\n return proxyIp;\n}", "function getProxyHost(opts) {\n if (opts.port && opts.port !== 80) {\n return opts.hostname + \":\" + opts.port;\n }\n return opts.hostname;\n}", "function buildUrl (obj) {\n\t\treturn (obj.protocol || 'http') + '://' +\n\t\t\t (obj.host ||\n\t\t\t\tobj.hostname + (obj.port ? ':' + obj.port : '')) +\n\t\t\t (obj.pathname || '') +\n\t\t\t (obj.search ? '?' + formatQS(obj.search || '') : '') +\n\t\t\t (obj.hash ? '#' + obj.hash : '');\n\t}", "function address(){\n \tif (config.nodejs)\n \t\treturn {val: config.serverurl};\n \telse\n \t\treturn expAddress;\n}", "function proxyBuilder(testTitle, certPath, certPass, targetPort) {\n try {\n\n const proxy = new httpProxy.createProxyServer({\n target: {\n protocol: 'https:',\n host: 'qa.bestallningsstod.tjansteplattform.se',\n port: process.env.SERVER_PORT,\n pfx: fs.readFileSync(`${__dirname}/pki/${certPath}`),\n passphrase: certPass\n },\n secure: false,\n changeOrigin: true,\n });\n\n const proxyServer = http.createServer((req, res) => {\n console.log(testTitle);\n //morgan(req, res, () => null);\n proxy.web(req, res);\n });\n\t\n proxyServer.on('upgrade', (req, socket, head) => {\n console.log(testTitle);\n //morgan(req, socket, () => null);\n proxy.ws(req, socket, head);\n });\n\n proxyServer.listen(targetPort);\n\tconsole.log(testTitle);\n } catch (e) {\n console.error(`Problem starting ${testTitle}`);\n console.error(e);\n }\n\n}", "function buildAddress() {\n\n\t\t\t\t\t\t\tfor (var i = 0; i < results[0].address_components.length; i++) {\n\t\t\t\t\t\t\t\tif( results[0].address_components[i].types.includes('sublocality_level_2') ) {\n\t\t\t\t\t\t\t\t\tvar add_part1 = results[0].address_components[i].long_name.replace(/\\s/g, '*');\n\t\t\t\t\t\t\t\t\tbuilt_address += add_part1;\n\n\t\t\t\t\t\t\t\t\tlocation_data.sublocality_level_2 = results[0].address_components[i].long_name;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif( results[0].address_components[i].types.includes('sublocality_level_1') ) {\n\t\t\t\t\t\t\t\t\tif (built_address != '') {\n\t\t\t\t\t\t\t\t\t\tbuilt_address += ','\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tvar add_part2 = results[0].address_components[i].long_name.replace(/\\s/g, '*');\n\t\t\t\t\t\t\t\t\tbuilt_address += add_part2\n\n\t\t\t\t\t\t\t\t\tlocation_data.sublocality_level_1 = results[0].address_components[i].long_name\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif( results[0].address_components[i].types.includes('administrative_area_level_1') ) {\n\t\t\t\t\t\t\t\t\tvar add_part3 = results[0].address_components[i].long_name.replace(/\\s/g, '*');\n\t\t\t\t\t\t\t\t\tbuilt_address += ',' + add_part3;\n\n\t\t\t\t\t\t\t\t\tlocation_data.city = results[0].address_components[i].long_name;\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif( results[0].address_components[i].types.includes('country') ) {\n\t\t\t\t\t\t\t\t\tvar add_part4 = results[0].address_components[i].long_name.replace(/\\s/g, '*');\n\t\t\t\t\t\t\t\t\tbuilt_address += ',' + add_part4;\n\n\t\t\t\t\t\t\t\t\tlocation_data.country = results[0].address_components[i].long_name;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t}", "function urlToMultiaddr(v, opts) {\n const { translateLocalhostPort = null } = opts\n const url = new URL(v)\n // TODO: ipv6?\n const addrProto = url.hostname.match(/^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$/)\n ? 'ip4'\n : 'dns4'\n let port = url.port\n if (!url.port) {\n if (url.protocol === 'https:') {\n port = `443`\n } else if (url.protocol === 'http:') {\n port = 80\n } else {\n throw new Error(`Unsupoorted protocol ${url.protocol}!`)\n }\n } else {\n if (translateLocalhostPort && LOCAL_HOSTS.includes(url.hostname)) {\n port = translateLocalhostPort\n }\n }\n return `/${addrProto}/${url.hostname}/tcp/${port}/${url.protocol.slice(\n 0,\n -1\n )}${url.pathname}`\n}", "_buildAddress(addr1, addr2, rest) {\n var completeAddr = addr1 + '\\n';\n if (addr2 == '') {\n return completeAddr + rest;\n }\n return completeAddr + addr2 + '\\n' + rest;\n }", "function FindProxyForURL(url, host) {\n\n alert(\"This is pac-test4.js\");\n\n\n// \n// isPlainHostName\n//\n\n alert(\"isPlainHostName(): Doing tests...\");\n \n if (!isPlainHostName(\"somehost\"))\n return \"PROXY isPlainHostName:1\";\n if (isPlainHostName(\"somehost.dom1.com\"))\n return \"PROXY isPlainHostName:2\";\n\n\n//\n// dnsDomainIs\n//\n alert(\"dnsDomainIs(): Doing tests...\");\n\n if (!dnsDomainIs(\"www.netscape.com\", \".netscape.com\"))\n return \"PROXY dnsDomainIs:1\";\n if (!dnsDomainIs(\"www.netscape.com\", \"netscape.com\"))\n return \"PROXY dnsDomainIs:2\";\n if (dnsDomainIs(\"www.netscape.com\", \".com\"))\n return \"PROXY dnsDomainIs:3\";\n if (dnsDomainIs(\"www.netscape.com\", \"somethingelse.com\"))\n return \"PROXY dnsDomainIs:4\";\n if (dnsDomainIs(\"www.netscape.com\", \"\"))\n return \"PROXY dnsDomainIs:5\";\n if (dnsDomainIs(\"www.netscape.com\", null))\n return \"PROXY dnsDomainIs:6\";\n \n// \n// localHostOrDomainIs\n//\n alert(\"localHostOrDomainIs(): Doing tests...\");\n \n if (!localHostOrDomainIs(\"www.netscape.com\", \"www.netscape.com\"))\n return \"PROXY localHostOrDomainIs:1\";\n if (!localHostOrDomainIs(\"www\", \"www.netscape.com\"))\n return \"PROXY localHostOrDomainIs:2\";\n if (localHostOrDomainIs(\"www.netscape.com\", \"www.netscape.com2\"))\n return \"PROXY localHostOrDomainIs:3\";\n if (localHostOrDomainIs(\"www1.netscape.com\", \"www2.netscape.com\"))\n return \"PROXY localHostOrDomainIs:4\";\n if (localHostOrDomainIs(\"www1\", \"www2.netscape.com\"))\n return \"PROXY localHostOrDomainIs:5\";\n \n//\n// isResolvable\n//\n alert(\"isResolvable(): Doing tests...\");\n \n if (!isResolvable(\"localhost\"))\n return \"PROXY isResolvable:1\";\n if (!isResolvable(\"www.google.com\")) // will only work if we have access to Internet during test\n return \"PROXY isResolvable:2\";\n if (isResolvable(\"gsd4hgbnw5xa.kd9greey934.kod82r\")) \n return \"PROXY isResolvable:3\";\n \n//\n// dnsResolve\n//\n alert(\"dnsResolve(): Doing tests...\");\n \n if (!(\"127.0.0.1\" === dnsResolve(\"localhost\")))\n return \"PROXY dnsResolve:1\";\n if (!(\"8.8.8.8\" === dnsResolve(\"google-public-dns-a.google.com\"))) // will only work if we have access to Internet\n return \"PROXY dnsResolve:2\";\n \n//\n// myIpAddress\n//\n alert(\"myIpAddress(): Doing tests...\");\n \n var myIp = myIpAddress();\n if (\"127.0.0.1\" === myIp)\n return \"PROXY myIpAddress:1\";\n \n//\n// isInNet\n//\n alert(\"isInNet(): Doing tests...\");\n \n if (!isInNet(\"localhost\", \"127.0.0.1\", \"255.255.255.255\"))\n return \"PROXY isInNet:1\";\n if (!isInNet(\"google-public-dns-a.google.com\", \"8.8.8.8\", \"255.255.255.255\"))\n return \"PROXY isInNet:2\";\n if (isInNet(\"192.168.1.3\", \"192.168.1.1\", \"255.255.255.255\"))\n return \"PROXY isInNet:3\";\n if (!isInNet(\"192.168.1.3\", \"192.168.1.1\", \"255.255.255.0\"))\n return \"PROXY isInNet:4\";\n if (!isInNet(\"192.168.1.1\", \"192.168.3.1\", \"255.255.0.255\"))\n return \"PROXY isInNet:5\";\n if (!isInNet(\"10.10.10.10\", \"12.12.12.12\", \"0.0.0.0\"))\n return \"PROXY isInNet:6\";\n if (isInNet(\"10.10.10.10\", \"12.12.12.12\", \"0.0.255.0\"))\n return \"PROXY isInNet:7\";\n\n// \n// dnsDomainLevels\n//\n alert(\"dnsDomainLevels(): Doing tests...\");\n\n if (!(2 === dnsDomainLevels(\"www.netscape.com\")))\n return \"PROXY dnsDomainLevels:1\";\n if (!(0 === dnsDomainLevels(\"www\")))\n return \"PROXY dnsDomainLevels:2\";\n if (!(1 === dnsDomainLevels(\"www.\")))\n return \"PROXY dnsDomainLevels:3\";\n\n\n//\n// shExpMatch\n// \n alert(\"shExpMatch(): Doing tests...\");\n \n if (!shExpMatch(\"www.netscape.com\", \"*netscape*\"))\n return \"PROXY shExpMatch:1\";\n if (!shExpMatch(\"www.netscape.com\", \"*net*\"))\n return \"PROXY shExpMatch:2\";\n if (shExpMatch(\"www.netscape.com\", \"*google*\"))\n return \"PROXY shExpMatch:3\";\n if (!shExpMatch(\"www.netscape.com\", \"www*\"))\n return \"PROXY shExpMatch:4\";\n\n//\n// weekdayRange\n//\n alert(\"weekdayRange(): Doing tests...\");\n \n if (!weekdayRange(\"MON\", \"SUN\", \"GMT\"))\n return \"PROXY weekdayRange:1\";\n if (!weekdayRange(\"MON\", \"SUN\", null))\n return \"PROXY weekdayRange:2\";\n\n//\n// dateRange\n//\n // Difficult to test from JavaScript side because it will depend on \n // date when test is executed.\n // We test if current date is between some values it will always be\n // in between, which isn't much of a test!\n \n alert(\"dateRange(): Doing tests...\");\n \n if (!(dateRange(1998, 2199)))\n return \"PROXY dateRange:1\";\n if (!(dateRange(1998, 2199, \"GMT\")))\n return \"PROXY dateRange:2\";\n if (!(dateRange(1, 31)))\n return \"PROXY dateRange:3\";\n if (!(dateRange(1, 31, \"GMT\")))\n return \"PROXY dateRange:4\";\n if (!(dateRange(\"JAN\", \"DEC\")))\n return \"PROXY dateRange:5\";\n if (!(dateRange(\"JAN\", \"DEC\", \"GMT\")))\n return \"PROXY dateRange:6\";\n if (!(dateRange(1, \"JAN\", 31, \"DEC\")))\n return \"PROXY dateRange:7\";\n if (!(dateRange(1, \"JAN\", 31, \"DEC\", \"GMT\")))\n return \"PROXY dateRange:8\";\n if (!(dateRange(1, \"JAN\", 1998, 31, \"DEC\", 2199)))\n return \"PROXY dateRange:9\";\n if (!(dateRange(1, \"JAN\", 1998, 31, \"DEC\", 2199, \"GMT\")))\n return \"PROXY dateRange:10\";\n\n//\n// timeRange\n//\n alert(\"timeRange(): Doing tests...\");\n // Difficult to test from JavaScript side because it will depend on \n // time when test is executed.\n // We test if current time is between 00:00:00 and 23:59:59, which\n // isn't much of a test!\n \n if (!(timeRange(0, 0, 0, 23, 59, 59)))\n return \"PROXY timeRange:1\";\n if (!(timeRange(0, 0, 0, 23, 59, 59, \"GMT\")))\n return \"PROXY timeRange:2\";\n if (!(timeRange(0, 0, 23, 59)))\n return \"PROXY timeRange:3\";\n if (!(timeRange(0, 0, 23, 59, \"GMT\")))\n return \"PROXY timeRange:4\";\n\n\n//\n// isResolvableEx\n//\n alert(\"isResolvableEx(): Doing tests...\");\n\n if (!(isResolvableEx(\"localhost\")))\n return \"PROXY isResolvableEx:1\";\n\n//\n// dnsResolveEx\n//\n alert(\"dnsResolveEx(): Doing tests...\");\n\n if (!(dnsResolveEx(\"dfg3qyuaz.g4yst5.gfw58703sd\") === \"\"))\n return \"PROXY dnsResolveEx:1\";\n\n//\n// myIpAddressEx\n//\n alert(\"myIpAddressEx(): Doing tests...\");\n\n var myIpEx = myIpAddressEx();\n if ((myIpEx === \"127.0.0.1\") || (myIpEx === \"0:0:0:0:0:0:0:1\") || (myIpEx === \"::1\"))\n return \"PROXY myIpAddressEx:1\";\n\n\n alert(\"pac-test4.js: All tests passed\");\n\n return \"DIRECT\";\n\n}", "function formatHttpAddress (serviceObj) {\n //default to internal address\n let address = serviceObj.internal;\n\n if (config.modes.haproxy) {\n let domainAddress = `${serviceObj.external}.${config.haproxyDomain}`;\n //external address (HAProxy)\n address = `http://${domainAddress}:${config.haproxyPort}`;\n if (config.modes.elb) { //external address (ELB)\n address = `http://${domainAddress}`;\n }\n if (config.modes.elbEncryptHttp) { //secure external address (ELB)\n address = `https://${domainAddress}`;\n }\n }\n return address;\n}", "function getProxyUrl() {\n return 'http://browserhtml.org:8081/src/about/home/proxy.html';\n }", "function buildServiceInfoIdentifier(info) {\n return `${info.serviceId}-${info.endpoint}`;\n}", "async resolveToLongURLFormat(url) {\n // URL is in the following format\n // [protocol://]host1[,host13][:port1][,host2:port2][/service_name][:server][/instance_name]\n\n const urlWithoutWhiteSpaces = url.replace(/\\s/g, \"\");\n let bool = 0;\n let protocol = null, hostInfo = null, serviceName = null, serverMode = null, instanceName = null;\n for (const match of urlWithoutWhiteSpaces.matchAll(EZ_URL_PATTERN)) {\n bool = 1;\n protocol = match.groups.protocol;\n hostInfo = match.groups.hostinfo;\n serviceName = match.groups.servicename;\n serverMode = match.groups.servermode;\n instanceName = match.groups.instance;\n }\n if (!bool) {\n // No Processing required as the URL is not in ezconnect format.\n errors.throwErr(errors.ERR_INVALID_EZCONNECT_SYNTAX, 'input string not in easy connect format', urlWithoutWhiteSpaces);\n }\n\n if (protocol == null) {\n if (!(url.includes(\"//\")))\n protocol = 'TCP';\n } else if (protocol.toLowerCase() != 'tcp' && protocol.toLowerCase() != 'tcps') {\n errors.throwErr(errors.ERR_INVALID_EZCONNECT_SYNTAX, 'Unsupported protocol in thin mode', protocol);\n }\n // Try to get the proxy information from URL properties\n const proxyHost = this.urlProps.get(\"HTTPS_PROXY\");\n const proxyPort = this.urlProps.get(\"HTTPS_PROXY_PORT\");\n const addressInfo =\n await this.buildAddressList(hostInfo, protocol, proxyHost, proxyPort);\n\n const connectionIdPrefix =\n this.urlProps.get(\"CONNECTION_ID_PREFIX\");\n // Build the available information in TNS format.\n const parts = [];\n if (this.lb)\n parts.push(\"(LOAD_BALANCE=ON)\");\n parts.push(this.buildDescriptionParams());\n parts.push(addressInfo);\n parts.push(this.buildConnectData(serviceName, serverMode, instanceName,\n connectionIdPrefix));\n parts.push(this.buildSecurityInfo(protocol));\n return `(DESCRIPTION=${parts.join('')})`;\n }", "function generateProxyConfig(backendUrl, nodeUrl, targetAddress = \"localhost\") {\n const base = {\n \"/node\": {\n targetLocal: `http://${targetAddress}:8545`,\n targetRemote: nodeUrl,\n pathRewrite: { \"^/node\": \"\" },\n },\n \"/api/signature\": {\n targetLocal: `http://${targetAddress}:5000`,\n targetRemote: backendUrl + \"signature\",\n pathRewrite: { \"^/api/signature\": \"\" },\n },\n \"/api/wallet\": {\n targetLocal: `http://${targetAddress}:5001`,\n targetRemote: backendUrl + \"wallet\",\n pathRewrite: { \"^/api/wallet\": \"\" },\n },\n \"/api/user\": {\n targetLocal: `http://${targetAddress}:5002`,\n targetRemote: backendUrl + \"user\",\n pathRewrite: { \"^/api/user\": \"\" },\n },\n \"/api/kyc\": {\n targetLocal: `http://${targetAddress}:5003`,\n targetRemote: backendUrl + \"kyc\",\n pathRewrite: { \"^/api/kyc\": \"\" },\n },\n \"/api/eto-listing\": {\n targetLocal: `http://${targetAddress}:5009`,\n targetRemote: backendUrl + \"eto-listing\",\n pathRewrite: { \"^/api/eto-listing\": \"\" },\n },\n \"/api/analytics-api\": {\n targetLocal: `http://${targetAddress}:5018`,\n targetRemote: backendUrl + \"analytics-api\",\n pathRewrite: { \"^/api/analytics-api\": \"\" },\n },\n \"/api/document-storage\": {\n targetLocal: `http://${targetAddress}:5015`,\n targetRemote: backendUrl + \"document-storage\",\n pathRewrite: { \"^/api/document-storage\": \"\" },\n },\n \"/api/newsletter\": {\n targetLocal: `http://${targetAddress}:5014`,\n targetRemote: backendUrl + \"newsletter\",\n pathRewrite: { \"^/api/newsletter\": \"\" },\n },\n \"/api/external-services-mock\": {\n targetLocal: `http://${targetAddress}:1337`,\n targetRemote: backendUrl + \"external-services-mock\",\n pathRewrite: { \"^/api/external-services-mock\": \"\" },\n },\n \"/api/gas\": {\n targetLocal: `http://${targetAddress}:5013`,\n targetRemote: backendUrl + \"gas\",\n pathRewrite: { \"^/api/gas\": \"\" },\n },\n \"/api/immutable-storage\": {\n targetLocal: `http://${targetAddress}:5012`,\n targetRemote: backendUrl + \"immutable-storage\",\n pathRewrite: { \"^/api/immutable-storage\": \"\" },\n },\n };\n\n return mapValues(base, value => {\n const isRemote = backendUrl !== `http://${targetAddress}`;\n\n const proxyConfig = {\n pathRewrite: value.pathRewrite,\n target: isRemote ? value.targetRemote : value.targetLocal,\n changeOrigin: isRemote,\n };\n return proxyConfig;\n });\n}", "function createURL(lat, lon, apikey) {\r\n\r\n var proxyUrl = 'http://net4.ccs.neu.edu/home/rasala/simpleproxy.aspx?url=\"';\r\n var base = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=';\r\n var latitude = lat;\r\n var longitude = lon;\r\n var param1 = '&keyword=Wedding&radius=30000&types=store&sensor=false&key=';\r\n \r\n var finalUrl = proxyUrl + base + latitude + ',' + longitude + param1 + apiKey + '\"';\r\n getJsonData(finalUrl);\r\n }", "function instrumentGetAddrInfo(opts) {\n\tif(opts.ex) {\n\t\tvar pGetAddrInfo = opts.unicode ? Module.findExportByName(\"ws2_32.dll\", \"GetAddrInfoExW\")\n : Module.findExportByName(\"ws2_32.dll\", \"GetAddrInfoExA\");\n } else {\n\t\tvar pGetAddrInfo = opts.unicode ? Module.findExportByName(\"ws2_32.dll\", \"GetAddrInfoW\")\n : Module.findExportByName(\"ws2_32.dll\", \"getaddrinfo\");\n }\n\n\tif(null == pGetAddrInfo)\n\t\treturn 0;\n\n\tInterceptor.attach(pGetAddrInfo, {\n\t\tonEnter: function(args) {\n\t\t\tvar domain = opts.unicode ? args[0].readUtf16String() : args[0].readUtf8String();\n\t\t\tsend({\n\t\t\t\t'hook': 'GetAddrInfo',\n\t\t\t\t'domain': domain\n\t\t\t});\n\t\t}\n\t});\n\treturn 1;\n}", "function torProxy() {\n if (!requestDetails.url.includes(\"7695\")) {\n proxy = {\n type: proxy_scheme(),\n host: proxy_host(),\n port: proxy_port(),\n };\n return proxy;\n }\n if (requestDetails.url.includes(\":7695\")) {\n proxy = null;\n return proxy;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get cell under cursor
function cursorCell() { return cellAt(cursor.y, cursor.x); }
[ "function getUnderlyingCell() {\n\t\tvar col = parseInt((mouseX - offset) / (cellSize + 1));\n\t\tvar line = parseInt(mouseY / (cellSize + 1));\n\t\t\n\t\tvar doDraw = false;\n\t\tif (line != activeLine || col != activeCol) {\n\t\t\tdoDraw = true;\n\t\t}\n\t\t\n\t\tactiveLine = line;\n\t\tactiveCol = col;\n\t\t\n\t\tif (doDraw) {\n\t\t\tdraw();\n\t\t}\n\t}", "function getMouseCell(e) {\n var x, y, width, c, rh, ty, dt, i;\n\n if (modeFullScreen) ty = clientDiv.scrollTop || clientDiv.scrollTop;\n else ty = document.documentElement.scrollTop || document.body.scrollTop;\n\n x = e.clientX;\n y = e.clientY + ty;\n dt = textPos.top;\n if (y >= dt && between(x, textPos.left, textPos.left + crtWidth - 1)) {\n // on the page. find row\n for (i = 0; i < conRowAttr.length; i++) {\n width = getRowAttrWidth(conRowAttr[i]) / 100;\n rh = fontSize;\n if (between(y, dt, dt + rh - 1)) {\n // on this row. get col\n c = (x - textPos.left) / (xScale * colSize * width);\n return { row: i, col: Math.floor(c) };\n }\n dt += rh;\n }\n }\n // off the console\n return null;\n }", "function getSelectedCell () { return { row: cell.row, col: cell.col, box: cell.box }; }", "function getCell(pos) { return gameField.querySelector(\"table\").rows[pos[1]].cells[pos[0]]; }", "getSelectedCell() {\n const selection = this.selection\n\n return (selection ? this.getCell(selection.col, selection.row) : null)\n }", "function getCell(elCell) {\n\n}", "get activeCell() {\r\n let widget = this.currentWidget;\r\n if (!widget) {\r\n return null;\r\n }\r\n return widget.content.activeCell || null;\r\n }", "function getX(cell) {\n return cell[0];\n }", "function getCell(table,cellPoint){\n\treturn table.rows[cellPoint[0]].cells[cellPoint[1]];\n}", "function getMouseColumn() {\n return Math.floor(mouseX / cellWidth) + 1; \n}", "function getCurrentCell()\n{\n //get the joint js cell\n //get the parent g element so we can get the model id\n var parent = currentObject.parents(\"g[model-id]\");\n //the model-id is assigned by joint js\n var modelId = parent.first().attr(\"model-id\");\n cell = graph.getCell(modelId);\n return cell; \n}", "get focusedCell() {\n return this.activeFocused ? Object.assign({}, this.activeFocused) : undefined;\n }", "function getMouseRow() {\n return Math.floor(mouseY / cellHeight) + 1;\n}", "function getCurrentCell() {\n return (parseInt($frogger.attr('class').split('-')[1]));\n }", "function getCell(x, y) {\n\tconst cellno = getCellno(x, y)\n\treturn document.getElementById('c' + cellno)\n}", "function getCell(id, x, y) {\n\treturn document.getElementById(id).children[0].children[x].children[y];\n}", "static getCellAtCoords(eventXScreen, eventYScreen) {\n var currCell = document.elementFromPoint(eventXScreen, eventYScreen);\n\n if (!currCell) throw new Error(\"Unable to locate cell\");\n\n //sometimes gets rows or legospace\n for(let i=0; i<10; i++) {\n if (!currCell.className.match(/cell/)) {\n eventYScreen -= (i * 5); // - some amount from y to avoid landing on the row border, or lego face\n currCell = document.elementFromPoint(eventXScreen, eventYScreen);\n } else {\n break;\n }\n }\n\n //verify a cell //would be better to use jquery's parents()\n if (!currCell.className.match(/cell/) || !currCell.parentNode.parentNode.className.match(/plane-x/)) {\n console.log(\"not at cell\");\n console.dir(currCell);\n throw new Error(\"Unable to find cell\");\n }\n\n // currCell.style.backgroundColor = \"yellow\";\n var xPlaneCell = currCell.className.match(/cell-(\\d+)/)[1]\n var xPlaneRow = currCell.parentNode.className.match(/row-(\\d+)/)[1]\n return [currCell, xPlaneCell, xPlaneRow];\n }", "get activeCell() {\r\n return this._activeCell;\r\n }", "get activeCell() {\n return this._n;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load city admin panel
function loadAdmin() { var city = getSelectedCity(); loadNews(city); }
[ "function initial_load_city_optional() {\n\n\t\ttoggle_city_class_elements_visibility('hideComponent');\n\t\ttoggle_city_color_visibility('hideComponent');\t\t\n\t\ttoggle_city_visibility('showComponent');\t\t\n\t\ttoggle_city_original_visibility('showComponent');\n\t\ttoggle_city_panels_visibility('hideComponent');\n\t\ttoggle_city_bricks_visibility('hideComponent');\n\t\ttoggle_rd_visibility('hideComponent');\n\t}", "setAdminCity(state, city) {\n state.city = city;\n }", "getAdminCities(state) {\n return state.cities;\n }", "setAdminCities(state, cities) {\n state.cities = cities;\n }", "function addCity() {\r\n displayWeather();\r\n }", "function loadAdminUX ()\n{\n let toLoad = 'admin.html';\n $.when($.get(toLoad)).done(function (page)\n {$('#body').empty();\n $('#body').append(page);\n updatePage('admin');\n listMemRegistries();\n });\n}", "getAdminCity(state) {\n return state.city;\n }", "function showAdmin(){\n addTemplate(\"admin\");\n userAdmin();\n}", "function carga_administrador_municipios() {\n\t\t$(\"#contenido\").load(\"admin_muni/index_municipios.php\");\n\t\t\n\t\t$('.menu_superior').animate({\n\t\t\t\tleft:'-100%'\n\t\t});\n\t}", "function openCityUrl() {\n\tvar weatherService = plasmoid.configuration.weather_service\n\tif (weatherService == 'OpenWeatherMap') {\n\t\tOpenWeatherMap.openOpenWeatherMapCityUrl(plasmoid.configuration.weather_city_id)\n\t} else if (weatherService == 'WeatherCanada') {\n\t\tQt.openUrlExternally(WeatherCanada.getCityUrl(plasmoid.configuration.weather_canada_city_id))\n\t}\n}", "function initCityList() {\n var storedCitiesLocation = JSON.parse(localStorage.getItem(\"cities\"));\n\n if (storedCitiesLocation !== null) {\n cityLocationList = storedCitiesLocation;\n }\n\n renderCities();\n}", "function onDisplayContentForTagcitiesmenutag(tag) {\n\trefreshCities();\n}", "function initialize() {\n cities();\n}", "function showLocations() {\n slideMenu('loc-layout',1);\n slideMenu('category-layout',0);\n slideMenu('areas-layout',0);\n}", "setAdminCitiesLoadStatus(state, status) {\n state.citiesLoadStatus = status;\n }", "function initialize(){\n cities();\n}", "function editLocStatuses() {\n myConsole.log(\"<b>editLocStatuses()</b> function called\");\n menuNd.style.display = \"none\";\n // buildBasicListUi() is in ui.js\n buildBasicListUi({forTable:\"locStatuses\",containerDomEl:pageContentNd,addButton:true});\n app.currentView = \"editLocStatuses\";\n}", "function loadCities() {\n\t\treturn SunnyExpress.getCities().map( function (city) {\n\t\t\treturn {\n\t\t\t\tvalue: city.toLowerCase(),\n\t\t\t\tdisplay: city\n\t\t\t};\n\t\t});\n\t}", "function carga_administrador_municipios() {\n\t$(\"#contenido\").load(\"admin_muni/index_municipios.php\");\n\t\n\t$('.menu_superior').animate({\n\t\t\tleft:'-100%'\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request: load groums for repo
load_groums(repoId) { console.log(`Loading groums...`); var reposRequest = $.ajax({ type: 'get', url: window.location.protocol + '//' + window.location.host + "/get_groums", data: {url : this.props.config.getGroumsUrl, app_key : repoId} }); reposRequest.fail(function(reply) { console.log('Failed loading groums for repo ' + repoId); }); reposRequest.done(function(reply) { console.log('Loaded groums...'); var groums = []; for (var i = 0; i < reply.length; i++) { var resMap = reply[i]; groums.push(new GroumSrc(resMap["groum_key"], resMap["source_class_name"], resMap["class_name"], resMap["method_name"], resMap["method_line_number"])); } console.log('Loaded ' + groums.length + ' groums...'); groums.sort(function(a,b) { var val = 0; if (a.methodName > b.methodName) { val = 1; } else if (a.methodName < b.methodName) { val = -1; } else { val = 0; } return val; } ); var value = groums.length > 0 ? 0 : null; this.setState( {groums : groums, selectedGroum : value} ); }.bind(this)); }
[ "function loadGroceries() {\n\n\n}", "function loadNodesCollectionRepository(containerClass) {\n var filterAssigned = $('input[name=\"assigned\"]:checked').val();\n var filterPublished = $('input[name=\"published\"]:checked').val();\n\n var sortFilter = $('select[name=\"sort-by\"]');\n var sort = (sortFilter.length > 0)\n ? sortFilter.val()\n : 'ASC';\n\n var searchField = $('.search-form input');\n var search = (searchField.val() == '')\n ? ''\n : searchField.val();\n\n var ajaxLoader = $('.' + containerClass).prev('.ajax-loader');\n ajaxLoader.show();\n $('.' + containerClass).load(Routing.generate('collection_' + nodeType + '_repository', {_locale: locale, filtersAssigned: filterAssigned, filterPublished: filterPublished, sort: sort, search: search}), function () {\n ajaxLoader.hide();\n if (!$('.front-container').length > 0) {\n initializeRepositoryTree();\n }\n else {\n initializeRepositoryTreePublic();\n }\n var countNodes = $('#count-nodes').text();\n $('.nodes-controls-footer .count').html(countNodes);\n });\n}", "function getRepoData() {\n var repo = getRepoName();\n\n var repoUrl = scheme + \"//\" + hostname + \"/repos/\" + repo;\n $.getJSON(repoUrl, repoResults);\n}", "function getRepositories() {\n const username = document.getElementById(\"username\").value;\n const req = new XMLHttpRequest();\n req.addEventListener('load', displayRepositories);\n req.open(\"GET\", `https://api.github.com/users/${username}/repos`);\n req.send();\n }", "function getGists() {\n var numpage = document.getElementsByName('numpage')[0].value;\n\n for (var i = 0; i < numpage; i++) {\n\n /*XMLHTTPRequest code obtained from Mozilla Developer Network*/\n var request;\n if (window.XMLHttpRequest) { /*Mozilla, Safari, IE7+...*/\n request = new XMLHttpRequest();\n } else if (window.ActiveXObject) { /*IE6 and older*/\n request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n if (!request) {\n throw 'HttpRequest cannot be created';\n }\n \n var url = 'https://api.github.com/gists?page=' + numpage + '&per_page=30';\n\n request.onreadystatechange = function() {\n if (this.readyState === 4 && this.status === 200) {\n var new_gist = JSON.parse(this.responseText);\n for (var i = 0; i < new_gist.length; i++) {\n var description = new_gist[i].description;\n var link = new_gist[i].html_url;\n var language = \"\";\n for (var prop in new_gist[i].files) {\n if (new_gist[i].files[prop].language) {\n language = new_gist[i].files[prop].language;\n }\n var next_gist = new Gist(description, link, language);\n addGist(next_gist);\n }\n }\n }\n showGist(gistList);\n };\n \n request.open('GET', url, true);\n request.send(null);\n \n }\n}", "getPopularRepos (language) {\n var URI ='https://api.github.com/search/repositories?q=stars:>1+language:'+\n language+'&sort=stars&order=desc&type=repositories';\n var encodedURI = window.encodeURI(URI);\n\n return axios.get(encodedURI).then(function (response) {\n /* The response is an object. The data is held under the property\n * data of the response. The repo list is held under the property\n * items. The promise returns promises to send the return of this\n * callback to the next callback we place in the chain.\n */\n return response.data.items;\n });\n }", "async function fetchVillageGroups() {\r\n\tlet fetchGroups = '';\r\n\tif (game_data.player.sitter > 0) {\r\n\t\tfetchGroups = game_data.link_base_pure + `groups&mode=overview&ajax=load_group_menu&t=${game_data.player.id}`;\r\n\t} else {\r\n\t\tfetchGroups = game_data.link_base_pure + 'groups&mode=overview&ajax=load_group_menu';\r\n\t}\r\n\tconst villageGroups = await jQuery\r\n\t\t.get(fetchGroups)\r\n\t\t.then((response) => response)\r\n\t\t.catch((error) => {\r\n\t\t\tUI.ErrorMessage('Error fetching village groups!');\r\n\t\t\tconsole.error(`${scriptInfo()} Error:`, error);\r\n\t\t});\r\n\r\n\treturn villageGroups;\r\n}", "function fetchRepos() {\n Repo.find().sort('index').exec(function(err, response) {\n // In case of error, populate repos with an empty array (if necessary) and go on our way.\n if (err) {\n if (!repos) {\n repos = [];\n compileGithubActivity();\n }\n return;\n }\n repos = response;\n compileGithubActivity();\n });\n}", "function getRepositories() {\n let input = document.querySelector('input').value;\n const req = new XMLHttpRequest();\n req.addEventListener('load', displayRepositories);\n req.open('GET', `https://api.github.com/users/${input}/repos`);\n req.send();\n}", "function getAggregated() {\n // var tOut = $scope.startLoading();\n\t\tseedUrlFactory.getAggregated($scope.master.workspaceId)\n\t\t\t.then(\n\t\t\t function (response) {\n buildAggregatedBy(response.data);\n // $scope.endLoading(tOut);\n },\n function (error) {\n // $scope.endLoading(tOut);\n $scope.status = 'Unable to load data: ' + error.message;\n }\n\t\t\t);\n\t}", "function getRepositories() {\n const req = new XMLHttpRequest()\n // When we add the event listener to our req object, we set it up so that\n // \"this\" will be our req object inside our callback function.\n req.addEventListener(\"load\", showRepositories);\n req.open(\"GET\", 'https://api.github.com/users/octocat/repos')\n req.send()\n}", "function loadGroups(){\n \n groupToLoad = studentGroup;\n\n addRow(groupToLoad);\n // add the name of the group working on that project\n \n}", "function repos( username ){\n //console.log(`Repos + ${username}`);\n url = `https://api.github.com/users/${username}/repos`;\n var options = {\n url: url,\n headers: {\n 'User-Agent': 'learning_apis'\n }\n }\n request(options, function( err, res, body ){\n var j_obj = JSON.parse( body );\n debugger;\n //j_obj is an object of repo objs\n for( var i = 0; i < j_obj.length; i++){\n //in each repo we just want to console log the names\n //for now\n var repo_obj = j_obj[i];\n console.log(repo_obj.name);\n }\n });\n}", "function loadRepos(username, cb) {\n var user = github().getUser();\n\n user.show(username, function(err, u) {\n var owners = {};\n if (u.type.toLowerCase() === \"user\") {\n user.userRepos(username, function(err, repos) {\n cb(null, { \"repos\": repos, user: u });\n });\n } else {\n user.orgRepos(username, function(err, repos) {\n cb(null, { \"repos\": repos, user: u });\n });\n }\n });\n}", "function requestRepos(username){\n const baseUrl = \"https://api.github.com/users/\" +username+\"/repos\";\n\n request(baseUrl, (data) => {\n if (data != \"404\") {\n fillReposDetails(JSON.parse(data));\n } else {\n showError(\"reposerror\");\n }\n }) \n}", "function getGrupos(req, res) {\n var inscripcionId = req.params.inscripcion;\n if (!inscripcionId) {\n // Sacar todos los grupos\n var find = Grupo.find({}).sort('name');\n } else {\n // Mostrar solamente los grupos inscritos\n var find = Grupo.find({\n inscripcion: inscripcionId\n }).sort('name');\n }\n find.populate({\n path: 'inscripcion'\n }).exec((err, grupos) => {\n if (err) {\n res.status(500).send({\n message: 'Error en el Servidor'\n });\n } else {\n if (!grupos) {\n res.status(404).send({\n message: 'No hay grupos asociados'\n });\n } else {\n res.status(200).send({\n grupos\n });\n }\n }\n })\n}", "function getAllRepos(org) {\n let repos = [];\n return new Promise((resolve, reject) => {\n fetch(`https://api.github.com/orgs/${org}/repos`, {'headers': { \"Content-Type\": \"application/x-www-form-urlencoded\", \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\" }})\n .then((response) => {\n if (response.status == \"200\") {\n return response.json();\n }\n })\n .then((res) => {\n res.map((item, i) => {\n repos[i] = item.name;\n });\n // Stores all public lab repos to localstorage (only first 30 repos yet)\n localStorage.setItem('repos', JSON.stringify(repos));\n\n resolve(repos);\n })\n });\n \n }", "function getRepositories() {\n const req = new XMLHttpRequest();\n // The second part of XHR is handling the response once we've made the\n // request.\n req.addEventListener('load', showRepositories);\n req.open('GET', 'https://api.github.com/users/octocat/repos');\n req.send();\n}", "function getBranches(el) {\n const username = document.getElementById('username').value;\n const name = el.dataset.repository;\n const req = new XMLHttpRequest();\n req.addEventListener('load', displayBranches);\n req.open('GET', `https://api.github.com/repos/${username}/${name}/branches`);\n req.send();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
eventManager receives events from the browser and passes them on to things on the canvas which registered rectangular areas they cared about.
function eventManager(canvasManager) { var self=this; // We get called in other context, so remember us this.id=0; // Bump this by one for each listen this.queues=new Object(); // So far, we only use this to get canvas, so why don't we just pass the // canvas? I suspect that later we might need to get to other parts. this.canvasManager=canvasManager; // Call this to express an interest in listening to a particular event type // eventType - string with something like 'keydown' or 'mousemove' // hit - a routine that we can call with an x,y offset on the canvas to // ask if you're interested in the event. Returns true if so // callback - if hit is true, we call the callback passing it the event // returns - the id of the event this.listen=function(eventType, hit, callback) { var queue=this.queues[eventType]; if(queue==null){ // No one's asked to listen to this yet, make a queue to // store it in. this.queues[eventType]=new Array(); queue=this.queues[eventType]; }else{ // Check to see if it's a duplicate for(var ctr=0;ctr<queue.length;ctr++){ if(eventType==queue[ctr].eventType && hit==queue[ctr].hit && callback==queue[ctr].callback){ alert('duplicate! ctr: '+ctr +' eventType: '+queue[ctr].eventType +' x: '+queue[ctr].boundingbox.x +' y: '+queue[ctr].boundingbox.y +' xextent: '+queue[ctr].boundingbox.xextent +' yextent: '+queue[ctr].boundingbox.yextent); return queue[ctr].id; } } } // If we get down here, we're adding a new eventListener queue[queue.length]=new eventListener(this.id,eventType, hit, callback); if(queue.length==1){ // First thing added to this queue, so start listening for this // event on the canvas hookEvent(this.canvasManager.canvas,eventType,this.eventhandler); } this.id=this.id+1; // bump so next listen gets different id return this.id-1; // return value before the bump } // quitlistening is called when we're tired of listening for an event // eventType - string with something like 'keydown' or 'mousemove' // id - the same id that was returned from listen this.quitlistening=function(eventType,id) { var queue=this.queues[eventType]; if(queue==null){ // they aren't listening those silly gooses. return; } for(var ctr=0;ctr<queue.length;ctr++){ if(queue[ctr].id==id){ queue.remove(ctr,ctr); } if(queue.length==0 && eventType != 'mouseover' && eventType != 'mouseout'){ // nobody is listening anymore, so we'll quit listening // We always listen for mouseover and mouseout though. unhookEvent(this.canvasManager.canvas,eventType,this.eventhandler); } } } // eventhandler for eventManager // At the global level, as an event goes down through the capture and // then back up through the global stage, anyone can stop the // propogation of the event. (Note that I don't allow my children // to choose one or the other. I always ask for bubble events so // that's what they get. // // The W3C DOM2 Event spec, says that even if stopPropagation is // called on an element, that the event will be dispatched to all // event listeners on the current element. So, one interpretation, // since all the listeners in my queue are on the same canvas would // be for me to keep dispatching. Another interpretation would have // me only dispatch to the same subelement. We don't allow multiple // registers from the same element unless they use different dispatch // routines or different hit routines. If they differ with hit // routines or dispatch routines we do. // I completely ignore preventDefault since I don't execute that. // // Another problem is key events. Since I use mouse x,y to decide who // should receive the event on the canvas, and key events don't have // associated x,y values, they never hit, but are passed to whoever has // focus. That means you have to click on something to get it to receive // the key events. this.eventhandler=function(e) { var xy; if(!e){ var e=window.event; } self.canvasManager.canvas.focus(); if(e.type=='mouseout'){ self.canvasManager.canvas.blur(); } var xy=getCanvasCursorPosition(e,self.canvasManager.canvas); var queue=self.queues[e.type]; var passon=true; // if true we didn't consume the event if(queue!=null){ for(var ctr=0;ctr<queue.length;++ctr){ var el=queue[ctr]; if(el.hit(xy[0],xy[1],e)){ // we found someone listening on that part of canvas if(!el.callback(xy[0],xy[1],e)){ // they consumed it passon=false; } if(e.type=='mousedown' || e.type=='touchstart' || e.type=='mousewheel' || e.type=='DOMMouseScroll' || e.type=='touchmove' || e.type=='touchend' || e.type=='touchdown' || e.type=='keydown' ){ // give the focus to whoever gets this event self.mousefocusedCB=el.callback; } } else if(el.callback==self.mousefocusedCB && (e.type=='mouseup' || e.type=='mouseout' || e.type=='click' || e.type=='mousemove' || e.type=='touchmove' || e.type=='touchend' || e.type=='mousewheel' || e.type=='DOMMouseScroll' || e.type=='keydown')){ // if the bounding box didn't match, but they are the // one with mouse focus send it to them anyway. if(!self.mousefocusedCB(xy[0],xy[1],e)){ // they consumed it passon=false; } if( e.type != 'mousemove' && e.type != 'touchmove' && e.type !='mousewheel' && e.type != 'DOMMouseScroll' && e.type != 'keydown' ){ // but they lose the focus for anything but movement self.mousefocusedCB=null; } } } } // passon is true if we didn't cancel, else false return passon; } // we always listen for mouseout and mouseover hookEvent(this.canvasManager.canvas,'mouseout',this.eventhandler); hookEvent(this.canvasManager.canvas,'mouseover',this.eventhandler); }
[ "registerEvents() {\n // Mouse\n this.canvas.addEventListener('mousedown' , this.eventsHandler.handleStart , false);\n this.canvas.addEventListener('mousemove' , this.eventsHandler.handleMove , false);\n this.canvas.addEventListener('mouseup' , this.eventsHandler.handleEnd , false);\n this.canvas.addEventListener('mouseleave' , this.eventsHandler.handleEnd , false);\n // Touch\n this.canvas.addEventListener('touchstart' , this.eventsHandler.handleStart , false);\n this.canvas.addEventListener('touchmove' , this.eventsHandler.handleMove , false);\n this.canvas.addEventListener('touchleave' , this.eventsHandler.handleEnd , false);\n this.canvas.addEventListener('touchend' , this.eventsHandler.handleEnd , false);\n this.canvas.addEventListener('touchcancel' , this.eventsHandler.handleEnd , false);\n }", "set_events() {\n // Connects the ajax Error event to a reporting function\n $(document).ajaxError($.proxy(this.handle_ajax_error, this));\n\n // Start the session\n this.view.get(EL.button_start).on_click($.proxy(this.handle_start_button_click, this));\n\n // Move the line cursor following the cursor position\n this.view.get(EL.canvas_plot).get_jq_element().mousemove($.proxy(this.handle_canvas_mouse_move, this));\n\n // This may be needed for updating the cursor position at the end of the iteration\n $(document).mousemove($.proxy(this.handle_document_mouse_move, this));\n\n // User click to provide feedback\n this.view.get(EL.canvas_plot).get_jq_element().click($.proxy(this.handle_canvas_click, this));\n\n // Triggers a resize for the canvas and its plot\n window.onresize = $.proxy(this.handle_window_resize, this);\n\n // Triggers events for pressing keys\n window.addEventListener('keydown', $.proxy(this.handle_keydown, this));\n\n // Triggers events for when the session completes\n window.addEventListener('session_complete_event', $.proxy(this.handle_session_complete, this));\n }", "function enableEvents() {\n addEventListner(canvas, \"mousedown\", function (e) {\n handler.mouseDownEvent(e);\n }, 'wait_action_');\n addEventListner(canvas, \"touchstart\", function (e) {\n handler.mouseDownEvent(e);\n }, 'wait_action_');\n addEventListner(canvas, \"mouseout\", function (e) {\n handler.mouseOutEvent(e);\n }, 'wait_action_');\n addEventListner(window, \"touchmove\", function (e) {\n handler.touchMoveEvent(e);\n }, 'wait_action_');\n addEventListner(canvas, \"mousemove\", function (e) {\n handler.mouseMoveRest(e);\n }, 'wait_action_');\n }", "function enableEvents() {\n addEventListner(canvas, 'mousedown', function (e) {\n handler.mouseDownEvent(e);\n }, 'wait_action_');\n addEventListner(canvas, 'touchstart', function (e) {\n handler.mouseDownEvent(e);\n }, 'wait_action_');\n addEventListner(canvas, 'mouseout', function (e) {\n handler.mouseOutEvent(e);\n }, 'wait_action_');\n addEventListner(window, 'touchmove', function (e) {\n handler.touchMoveEvent(e);\n }, 'wait_action_');\n addEventListner(canvas, 'mousemove', function (e) {\n handler.mouseMoveRest(e);\n }, 'wait_action_');\n }", "setupListeners() {\n // Canvas listeners\n this.canvas.addEventListener(\"wheel\", (event) => this.onWheel(event), false);\n this.canvas.addEventListener(\"mousedown\", (event) => {\n if (event.button === 0) {\n this.onLeftMouseDown(event);\n } else if (event.button === 2) {\n this.onRightMouseDown(event);\n }\n }, false);\n this.canvas.addEventListener(\"mouseup\", (event) => {\n if (event.button === 0) {\n this.onLeftMouseUp(event);\n } else if (event.button === 2) {\n this.onRightMouseUp(event);\n }\n }, false);\n this.canvas.addEventListener(\"mousemove\", (event) => this.onMouseMove(event));\n this.canvas.addEventListener(\"contextmenu\", (event) => {event.preventDefault();});\n\n // Buttons listeners\n document.getElementById(\"add-rect\").addEventListener(\"click\", (event) => {\n this.addRectangle();\n });\n document.getElementById(\"add-cam\").addEventListener(\"click\", (event) => {\n this.addCamera();\n });\n\n document.getElementById(\"delete-rect\").addEventListener(\"click\", (event) => {\n // Prevent deleting the screen\n if (this.selectedRectangle > 0) {\n this.rectangles.splice(this.selectedRectangle, 1);\n this.resetSelection();\n }\n });\n\n document.getElementById(\"delete-cam\").addEventListener(\"click\", (event) => {\n if (this.selectedCamera >= 0) {\n this.cameras.splice(this. selectedCamera, 1);\n this.resetSelection();\n }\n })\n\n // Input listeners\n document.getElementById(\"rect-x\").addEventListener(\"input\", (event) => {\n if (this.selectedRectangle >= 0) {\n this.rectangles[this.selectedRectangle].x = event.target.value;\n }\n });\n document.getElementById(\"rect-y\").addEventListener(\"input\", (event) => {\n if (this.selectedRectangle >= 0) {\n this.rectangles[this.selectedRectangle].y = event.target.value;\n }\n });\n document.getElementById(\"rect-w\").addEventListener(\"input\", (event) => {\n if (this.selectedRectangle >= 0) {\n this.rectangles[this.selectedRectangle].w = event.target.value;\n }\n });\n document.getElementById(\"rect-h\").addEventListener(\"input\", (event) => {\n if (this.selectedRectangle >= 0) {\n this.rectangles[this.selectedRectangle].h = event.target.value;\n }\n });\n document.getElementById(\"cam-x\").addEventListener(\"input\", (event) => {\n if (this.selectedCamera >= 0) {\n this.cameras[this.selectedCamera].x = event.target.value;\n }\n });\n document.getElementById(\"cam-y\").addEventListener(\"input\", (event) => {\n if (this.selectedCamera >= 0) {\n this.cameras[this.selectedCamera].y = event.target.value;\n }\n });\n document.getElementById(\"cam-alpha\").addEventListener(\"input\", (event) => {\n if (this.selectedCamera >= 0) {\n this.cameras[this.selectedCamera].alpha = event.target.value * DEG_TO_RAD;\n }\n });\n document.getElementById(\"cam-type\").addEventListener(\"input\", (event) => {\n if (this.selectedCamera >= 0) {\n this.cameras[this.selectedCamera].setType(event.target.value);\n }\n });\n }", "function EventManager (canvas) {\n this.Canvas = canvas;\n this.Viewers = [];\n this.CurrentViewer = null;\n this.ShiftKeyPressed = false;\n this.ControlKeyPressed = false;\n this.Key = '';\n this.MouseX = 0;\n this.MouseY = 0;\n this.LastMouseX = 0;\n this.LastMouseY = 0;\n this.MouseDown = false;\n}", "input() {\n this.portraitCanvas.addEventListener('mousemove', this.moveEvent);\n\n this.portraitCanvas.addEventListener('mouseout', this.outEvent);\n\n this.portraitCanvas.addEventListener('click', this.clickEvent);\n }", "function setupListener(canvas)\n{\n canvas.addEventListener(\"mousemove\", mouseMove);\n rect = canvas.getBoundingClientRect();\n}", "function monitor_canvas_events(canvas) {\n // The canvas map will need to be updated before we can look up canvases by name\n mark_canvases_outdated();\n\n let draw = canvas.flo_draw;\n\n ///\n /// Returns true if this canvas is active\n ///\n let is_active = () => {\n return canvas.parentNode !== null;\n };\n\n ///\n /// Updates the content size of the canvas\n ///\n let resize_canvas = () => {\n // Resize if the canvas's size has changed\n var ratio = 1; //window.devicePixelRatio || 1; -- TODO, 4k canvases cause the pointer events to lag on Chrome...\n let target_width = canvas.clientWidth * ratio;\n let target_height = canvas.clientHeight * ratio;\n\n if (canvas.width !== target_width || canvas.height !== target_height) {\n // Actually resize the canvas\n canvas.width = canvas.clientWidth * ratio;\n canvas.height = canvas.clientHeight * ratio;\n\n // Redraw the canvas contents at the new size\n draw.replay_drawing();\n draw.draw_layers();\n }\n };\n\n // Add this canvas to the list of active canvases\n active_canvases.push({\n canvas_element: canvas,\n is_active: is_active,\n resize_canvas: resize_canvas,\n draw: canvas.flo_draw,\n flo_name: canvas.flo_name,\n flo_controller: canvas.flo_controller,\n decoder: canvas.flo_canvas_decoder\n });\n\n // Run through the initial set of events\n requestAnimationFrame(() => resize_canvas());\n }", "function handleEvents(brane){\n for(i in brane.eventQ){\n var e = brane.eventQ[i];\n if(e instanceof MouseEvent && brane.onMouse){\n brane.state = brane.onMouse(brane.state, e.type, e.event);\n } else if(brane.onKey){\n brane.state = brane.onKey(brane.state, e.type, e.event);\n }\n //draw(brane);\n } \n brane.eventQ = new Array();\n}", "attachEventHandlers() {\n\t\tbind(this.$canvas, ['mousedown','touchstart'], this._onTouchStart);\n\t\tbind(this.$canvas, ['mouseup','touchend'], this._onTouchStop);\n\t\tbind(window, ['mousemove','touchmove'], this._onTouchMove);\n\t\tbind(window, ['resize'], this._onResize);\n\n\t\t// Start frame loops\n\t\traf(this.renderLoop);\n\t\traf(this.calculationLoop);\n\t}", "initActions() {\n this.canvas.addEventListener('mousedown', (event) => { this.startDrawing(event); });\n this.canvas.addEventListener('mouseup', (event) => { this.endDrawing(event); });\n this.canvas.addEventListener('mousemove', (event) => { this.onMove(event); });\n }", "configureEventLisneters () {\n state.paper.on({\n 'cell:pointerdown': this.cellPointerDownListener,\n 'cell:pointerup': this.cellPointerUpListener,\n 'blank:pointerdown': this.blankPointerDownListener\n })\n\n state.graph.on({\n 'change': this.changeListener,\n 'add': this.addListener,\n 'remove': this.removeListener\n })\n\n $('#MCanvas').on({\n 'mousemove': this.mousemoveListener,\n 'mouseup': this.mouseupListener\n })\n }", "function setupMapListener() {\n var handler = new ScreenSpaceEventHandler(theViewer.canvas);\n handler.setInputAction(mouseClickListener, ScreenSpaceEventType.LEFT_CLICK);\n handler.setInputAction(zoomListener, ScreenSpaceEventType.WHEEL);\n handler.setInputAction(zoomListener, ScreenSpaceEventType.RIGHT_UP);\n handler.setInputAction(zoomListener, ScreenSpaceEventType.PINCH_END);;\n handler.setInputAction(mouseMovedListener, ScreenSpaceEventType.MOUSE_MOVE);\n }", "initEvents() {\n const annotation = this;\n try {\n this._canvas.addEventListener('mousedown', (e) => annotation.startDrawing(e));\n this._canvas.addEventListener('touchstart', (e) => annotation.startDrawing(e));\n this._canvas.addEventListener('mouseup', (e) => annotation.endDrawing(e));\n this._canvas.addEventListener('touchend', (e) => annotation.endDrawing(e));\n this._canvas.addEventListener('touchcancel', (e) => annotation.endDrawing(e));\n this._canvas.addEventListener('mouseleave', (e) => annotation.endDrawing(e));\n this._canvas.addEventListener('mousemove', (e) => annotation.onDrag(e));\n this._canvas.addEventListener('touchmove', (e) => annotation.onDrag(e));\n this._canvas.addEventListener('resize', (e) => annotation.updateSize());\n this._canvas.addEventListener('pointerup', (e) => e.stopImmediatePropagation());\n } catch (e) {\n console.log(e);\n }\n }", "function setupListeners() {\n\n let move = null;\n\n canvas.addEventListener('mousedown', e => {\n const { i, j } = getCoord(e);\n\n if (!treatEnd(i, j) && !move) {\n move = { start: { i, j } };\n }\n });\n\n canvas.addEventListener('mouseup', e => {\n const { i, j } = getCoord(e);\n\n treatEnd(i, j);\n });\n\n function treatEnd(i, j) {\n if (move && (move.start.i !== i || move.start.j !== j)) {\n move.end = { i, j };\n treatMove(move);\n move = null;\n return true;\n }\n }\n}", "handleEvents(){\r\n\r\n }", "function loadCanvasListeners() {\n canvas.addEventListener(\"mousedown\",function(evt){mouseStart(evt,board)},false);\n canvas.addEventListener(\"mouseup\",function(evt){mouseEnd(evt,board)},false);\n canvas.addEventListener(\"mousemove\",function(evt){mouseMove(evt,board)},false); \n}", "function cliqueCanvas(event){\n\tcanvas.addEventListener(\"mousemove\",actionCanvas,false);\n\tdocument.body.addEventListener(\"mouseup\",removeListener,false);\n\tdocument.body.addEventListener(\"mouseout\",removeListener,false);\n\tactionCanvas(event,true);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: startMelting Called when the user clicks the Start button Performs all setup/initialization that needs to occur at the beginning of every experiment, and then begins the execution of the experiment.
function startMelting() { // Reset experiment to the beginning (ex. unmelt ice cubes, move blocks back to their starting location, etc.) just // in case the user re-starts the experiment without explicitly clicking the Reset button first if (experimentStarted) { pauseMelting(); return; } resetExperiment(); // Disable "start" button and enable "pause" button $("#startButton").attr("disabled", "disabled"); $("#startButton").css("border-color", "gray"); $("#startButton").html("Pause"); // Initialize starting values for the calculations generateGraphPoints(); // Start the experiment experimentRunning = true; experimentStarted = true; currentStep = 0; blockHeight = 51; panel1.disableControl("Initial temperature"); panel1.disableControl("Block heat capacity"); panel1.disableControl("Block mass"); panel1.disableControl("Block area"); panel1.disableControl("Number of blocks"); panel1.disableControl("Add stir bar"); panel2.disableControl("Initial temperature"); panel2.disableControl("Block heat capacity"); panel2.disableControl("Block mass"); panel2.disableControl("Block area"); panel2.disableControl("Number of blocks"); panel2.disableControl("Add stir bar"); panel3.disableControl("Simulation time"); }
[ "function startMelting() {\n\t// Reset experiment to the beginning (ex. unmelt ice cubes, move blocks back to their starting location, etc.) just\n\t// in case the user re-starts the experiment without explicitly clicking the Reset button first\n\tif (experimentStarted) {\n\t\tpauseMelting();\n\t\treturn;\n\t}\n\n\tresetExperiment();\n\n\t// Disable \"start\" button and enable \"pause\" button\n\t$(\"#startButton\").attr(\"disabled\", \"disabled\");\n\t$(\"#startButton\").css(\"border-color\", \"gray\");\n\t$(\"#startButton\").html(\"Pause\");\n\n\t// Initialize starting values for the calculations\n\tbeaker1.generateGraphPoints();\n\tbeaker2.generateGraphPoints();\n\n\t// Start the experiment\n\texperimentRunning = true;\n\texperimentStarted = true;\n\n\tcurrentStep = 0;\n\n\t/*panel1.disableControl(\"Initial Temperature\");\n\tpanel1.disableControl(\"Block Heat Capacity\");\n\n\tpanel2.disableControl(\"Initial Temperature\");\n\tpanel2.disableControl(\"Block Heat Capacity\");*/\n\n\tpanel3.disableControl(\"duration to simulate\");\n}", "function startSimulation() {\n\tsaveSettings();\n\n\t// Check if any current simulation is running. If so, end it.\n\tif (typeof plot !== 'undefined') {\n\t\tplot.stopAnimation = true;\n\t}\n\n\tdocument.getElementById(\"toggleSimulationButton\").className = \"active\";\n\n\tnumIterations = 0;\n\n\tloadFittingFunction();\n\tloadManager();\n\tloadAnimator();\n\n\t// Show the extra information about the fitting function\n\tdisplayContour(ff.imageSrcContour);\n\tdisplayThreeD(ff.imageSrcThreeD);\n\n\tif (typeof(ff.global) !== 'undefined') {\n\t\tdocument.getElementById(\"outputTruePosition\").innerHTML = \"( \" + ff.global.x.toFixed(3) + \", \" + ff.global.y.toFixed(3) + \" )\";\n\t} else {\n\t\tdocument.getElementById(\"outputTruePosition\").innerHTML = \"<i>not applicable</i>\";\n\t}\n}", "function pauseMelting() {\n\tif (!experimentStarted) {\n\t\treturn;\n\t}\n\n\tif (experimentRunning) {\n\t\texperimentRunning = false;\n\t\t$(\"#startButton\").html(\"Start\");\n\t} else {\n\t\texperimentRunning = true;\n\t\t$(\"#startButton\").html(\"Pause\");\n\t\tpictureBehavior();\n\t}\n}", "launchExperiment() {\n this.intro.launchExperiment = true;\n this.startButton.className = 'button--wayra start hide';\n for (var i = 0; i < this.blocs.length; i++) {\n this.blocs[i].className = this.blocs[i].classList[0];\n };\n this.disableMusic = false;\n this.scene.add(this.points);\n this.introLeft = true;\n setTimeout(() => {\n this.scene.remove(this.intro);\n }, 3000);\n }", "function setup_start() {\n display.start.css('display', 'block');\n display.start.on('click', function(e){\n start();\n e.preventDefault();\n });\n }", "function startSetup() {\n mainDisplay.loadSound.play();\n removeChild(loadWrap, getElement('start-button-wrapper'));\n removeChild(initializeWrapper, loadWrap);\n //config();\n setTimeout(function () {\n showElement(camWrap);\n toggleCams();\n setupCams();\n }, 100);\n\n }", "function start(){\n\t\t//console.log(\"ScenarioPlay.start\");\n\t\t\n\t\tcleanScenarioPlay();\n\t\t\n\t\tcleanScenarioPlayScreen();\n\t\t\n\t\tcalculateScenarioPlay();\n\t\t\n\t\tm_loop=window.setTimeout(appLoop, LOOP_UPDATE_TIME);\t\t\n\t}", "async function setupAndStart() {\n // going to load data; show loading spinner; hide (re)start button & board\n $(\"#spin-container\").show();\n $(\"#start\").hide();\n $(\"#jeopardy\").hide();\n\n await setupGameBoard();\n\n // finished setting up board: hide spinner; show button & board\n $(\"#jeopardy\").show();\n $(\"#start\").text(\"Restart!\").show();\n $(\"#spin-container\").hide();\n}", "function C999_Common_MetalSheet_Run() {\n\tBuildInteraction(C999_Common_MetalSheet_CurrentStage);\n}", "function startAutopilot() {\n\n\n}", "start(){\n this.calculateAndVisualiseIterations();\n }", "function start() {\n console.log('starting game');\n inProgress = true;\n button.classList.add(\"hidden\");\n makeShortChoices();\n renderStory(scene.narrative, scene.fullChoices);\n initializeRecognition();\n playGame();\n }", "function startExperiment(scope) {\n\t/** disabling the start button after starting the experiment */\n\tscope.fill_liquid_disable = true;\n\t/** To check the selected liquid and assigning the time of flow value*/ \n\tif(selected_liquid_index == 0)\n\t{\n\t\ttime=39.5;\t//time of flow value of Water\n\t}\n\telse if(selected_liquid_index == 1)\n\t{\n\t\ttime=35.27; //time of flow value of Toluene\n\t}\n\telse\n\t{\n\t\ttime=65.89;\t//time of flow value of Nitrobenzene \n\t}\n\t/** calculating the delay time of liquid to reach the level */\n\tdelay_time = \ttime * 1000;\n\t/** starting the stop watch */\t\n\tresetWatch();\n\tstop_watch_timer = setInterval(expWatch,0.5);\t\n\tpause_flag = false;\n\t/** increasing the liquid level in the left side of viscometer */\n\tvar soln_falling_tween_second = createjs.Tween.get(mask_tube_rect_left).to({\n y: 520}, delay_time) \n\t/** decreasing the liquid level in the right side of viscometer*/\n\tvar soln_falling_tween_first = createjs.Tween.get(mask_tube_rect_right).to({\n\ty: 429}, delay_time)\n}", "function start() {\n console.log('starting game');\n inProgress = true;\n button.classList.add(\"hidden\");\n makeShortChoices();\n renderStory(scene.narrative, scene.fullChoices);\n initializeRecognition();\n playGame();\n}", "function startSimulation() {\n // If the update cycle shouldn't be synced with the framerate,\n // update every 1ms (not a great solution)\n if (!sfcheckbox.checked()) {\n updater = setInterval(updateTick, 1);\n }\n setSimButtonText('Stop'); // Alter the caption of the Start/Stop button\n setControlMode('none');\n setUnactive();\n disableButtons(true);\n setPropMode(false);\n showSClickBox = false; // Hide the selection click box\n\n // Parse all groups, integrate all elements and parse again (this is required)\n parseGroups();\n integrateElement();\n parseGroups();\n\n // Reduce the displayed wires for performance\n for (const elem of groups) {\n elem.findLines();\n }\n\n // Reset all clocks\n for (const elem of inputs) {\n if (elem.getIsClock()) {\n elem.resetFramecount();\n }\n }\n\n // Tell all customs that the simulation started\n for (const elem of customs) {\n elem.setSimRunning(true);\n }\n\n sfcheckbox.show();\n\n // Start the simulation and exit the properties mode\n simRunning = true;\n propMode = false;\n}", "start() {\n this._technique.start();\n }", "function resetExperiment() {\n\t/*\n\t// Re-enable the input fields if they are disabled\n\tif (experimentRunning || experimentStarted) {\n\t\tpanel1.enableControl(\"Initial Temperature\");\n\t\tpanel1.enableControl(\"Block Heat Capacity\");\n\n\t\tpanel2.enableControl(\"Number of Blocks\");\n\t\tpanel2.enableControl(\"Add Stir Bar\");\n\n\t\tpanel3.enableControl(\"duration to simulate\");\n\t}*/\n\n\texperimentRunning = false;\n\texperimentStarted = false;\n\ticeDropped = false;\n\n\tsit1GraphPts = [];\n\tsit2GraphPts = [];\n\n\t$(\"#startButton\").removeAttr(\"disabled\");\n\t$(\"#startButton\").css(\"border-color\", \"#093\");\n\t$(\"#startButton\").html(\"Start\");\n\n\tcurrentStep = 0;\n\ticeHeight = 51;\n}", "function start() {\n openBoard.start(sampleFunction, boardSettings);\n}", "function startVisualize() {\n if (selectedHeuristic == undefined && algorithmIndex == undefined) {\n showAlert(\"Please select an Algorithm and Heuristic function\");\n } else if (selectedHeuristic == undefined) {\n showAlert(\"Please select Heuristic function\");\n } else if (algorithmIndex == undefined) {\n showAlert(\"Please select an Algorithm\");\n } else {\n $controlButton.toggleClass(\"active\");\n finished = false;\n initialized = false;\n toggleControls();\n running = true;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CAM732 Test to check DFR record length with continuous FR Trigger within oplimit.
function CAM_732() { try { Log.Message("Start:-Test to check DFR record length with continuous FR Trigger within oplimit.") var dataSheetName = Project.ConfigPath +"TestData\\CAM_732.xlsx" //Step0.Check whether device exists or not in the topology. if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceType"),CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceName"))!=true) { GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceType"),CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceName"),CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceSerialNo"),CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceIPAdd")) DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceType"),CommonMethod.ReadDataFromExcel(dataSheetName,"DeviceName")) } else { Log.Message("Device exist in the tree topology.") } //Step1. Retrieve Configuration AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),"Clicked on Retrieve Config") //Step2. Click on Fault Recording AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),"Clicked on Fault Recording") //Step3. Set pre-fault for External Triggers var prefault =CommonMethod.ReadDataFromExcel(dataSheetName,"PrefaultTime") AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),"Validating Prefault Time") //Step3.1. Set Max DFR time var maxDFR=CommonMethod.ReadDataFromExcel(dataSheetName,"MaxDFR") AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(maxDFR),"Validating Max DFR") //Step3.2 Click on FR Sensor AssertClass.IsTrue(ConfigEditorPage.ClickOnFRSensor(),"Clicked on FR Sensor") //Step4 Set Post Fault,Oplimit for FR Sensor AssertClass.IsTrue(ConfigEditor_FaultRecording_FRSensorPage.OpenFRSensorEditor(0),"Open up FR Sensor Editor") //Setting First FR Sensor var frsensorNameFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,"FRSensorName") var frsensorTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,"Type") var frsensorScalingTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,"ScalingType") var frsensorUpperThresholdFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,"UpperThreshold") var frsensorPostFaultTimeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,"PostFaultTime") var frsensorOplimitFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,"Oplimit") var expectedRecordDuration1 = CommonMethod.ReadDataFromExcel(dataSheetName,"ExpectedRecordDuration_1") DFR_Methods.SetFRSensor(frsensorNameFromTestData,frsensorTypeFromTestData,frsensorScalingTypeFromTestData,frsensorUpperThresholdFromTestData,frsensorPostFaultTimeFromTestData,frsensorOplimitFromTestData) //Step5. Send to Device AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),"Clicked on Send to Device") //Step6. Click on DFR Directory under Display Device Directory AssertClass.IsTrue(DataRetrievalPage.ClickOnDFRDirectory() ,"Clicked on DFR Directory") //Step7. Find latest Record Number var lastDFRRecord= DataRetrievalPage.GetLatestRecordnumber() Log.Message("Current Record Number is :- "+lastDFRRecord) //Step8. Close DFR Directory AssertClass.IsTrue(DataRetrievalPage.CloseDFRDirectory() ,"Close DFR Directory") //Step9 Start Omicron Injection OmicronStateSeqPage.RunSeqFile(Project.ConfigPath+"TestData\\"+CommonMethod.ReadDataFromExcel(dataSheetName,"OmicronFile_1")) AssertClass.IsTrue(DFR_Methods.IsMultipleRecordFound(10,1,lastDFRRecord),"Checking for new Record") //Step11. Click on Download Data Now //This logic is only applicable to this script as it is downloading max length DFR record. //Step 11.1 Click on DFR Directory AssertClass.IsTrue(DataRetrievalPage.ClickOnDFRDirectory(),"Clicked on DFR Directory") var REC_DFR=DataRetrievalPage.GetLatestRecordnumber() //Step11.2. Click on Download Data Now AssertClass.IsTrue(DataRetrievalPage.ClickOnDownloadDataNow(),"Clicked on Download Data Now") var retryCnt =100 do { aqUtils.Delay(60000) if(CommonMethod.CheckActivityLog("DFR records saved successfully for device")) { break } retryCnt = retryCnt-1 } while (retryCnt>0) //Step11.3. Click on Close DFR Directory DataRetrievalPage.CloseDFRDirectory() Log.Message("DFR data download") AssertClass.IsTrue(DFR_Methods.ViewDFROnPDP(REC_DFR),"Checking on PDP") //Step12. Check Record Length var recordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(0))//FirstRow AssertClass.CompareDecimalValues(aqConvert.StrToInt64(expectedRecordDuration1),aqConvert.StrToInt64(recordLength),10,"Validating Record Duration.") Log.Message("Pass:-Test to check DFR record length with continuous FR Trigger within oplimit.") } catch(ex) { Log.Message(ex.stack) Log.Error("Fail:-Test to check DFR record length with continuous FR Trigger within oplimit. ") } finally { OmicronStateSeqPage.CloseStateSeq() } }
[ "function CAM_729_730_731_733()\n{\n try\n {\n Log.Message(\"Start:-Test to check limit DFR record length feature when FR trigger(Pre+Oplimit+Post fault time) is within Maximum record length.\")\n var dataSheetName = Project.ConfigPath +\"TestData\\\\CAM_729_730_731_733.xlsx\"\n //Step0.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step1. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step2. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step3. Set pre-fault for External Triggers\n var prefault =CommonMethod.ReadDataFromExcel(dataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),\"Validating Prefault Time\")\n \n //Step3.1. Set Max DFR time\n var maxDFR=CommonMethod.ReadDataFromExcel(dataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(maxDFR),\"Validating Max DFR\") \n \n //Step3.2 Click on FR Sensor\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFRSensor(),\"Clicked on FR Sensor\")\n \n //Step4 Set Post Fault,Oplimit for FR Sensor\n AssertClass.IsTrue(ConfigEditor_FaultRecording_FRSensorPage.OpenFRSensorEditor(0),\"Open up FR Sensor Editor\") //Setting First FR Sensor\n var frsensorNameFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"FRSensorName\")\n var frsensorTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"Type\")\n var frsensorScalingTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"ScalingType\")\n var frsensorUpperThresholdFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"UpperThreshold\")\n var frsensorPostFaultTimeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"PostFaultTime\")\n var frsensorOplimitFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"Oplimit\")\n var frsensorRecordDurationFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"RecordDuration\")\n \n DFR_Methods.SetFRSensor(frsensorNameFromTestData,frsensorTypeFromTestData,frsensorScalingTypeFromTestData,frsensorUpperThresholdFromTestData,frsensorPostFaultTimeFromTestData,frsensorOplimitFromTestData)\n \n //Step5. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step6. Click on DFR Directory under Display Device Directory\n AssertClass.IsTrue(DataRetrievalPage.ClickOnDFRDirectory() ,\"Clicked on DFR Directory\") \n \n //Step7. Find latest Record Number\n var lastDFRRecord= DataRetrievalPage.GetLatestRecordnumber()\n Log.Message(\"Current Record Number is :- \"+lastDFRRecord) \n \n //Step8. Close DFR Directory\n AssertClass.IsTrue(DataRetrievalPage.CloseDFRDirectory() ,\"Close DFR Directory\") \n \n //Step9 Start Omicron Injection\n OmicronStateSeqPage.RunSeqFile(Project.ConfigPath+\"TestData\\\\\"+CommonMethod.ReadDataFromExcel(dataSheetName,\"OmicronFile\"))\n \n AssertClass.IsTrue(DFR_Methods.IsNewRecordFound(10,lastDFRRecord),\"Checking for new Record\")\n \n AssertClass.CompareString(\"FRSENSOR\",DataRetrievalPage.GetCOTForLatestDFRRecord(),\"Checking COT\") \n \n //Step11. Click on Download Data Now\n AssertClass.IsTrue(DataRetrievalPage.ClickOnDownloadDataNow(),\"Clicked on Download Data Now\")\n CommonMethod.CheckActivityLog(\"DFR records saved successfully for device\")\n AssertClass.IsTrue(DataRetrievalPage.CloseDFRDirectory(),\"Closed DFR Directory\")\n DFR_Methods.ViewDFROnPDP(aqConvert.StrToInt64(lastDFRRecord)+1)\n \n //Step12. Check Record Length\n var recordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(0))//FirstRow\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(frsensorRecordDurationFromTestData),aqConvert.StrToInt64(recordLength),0,\"Validating Record Duration.\")\n \n //Step13. Check Prefault time\n var actualPrefault = (PDPPage.GetRecordTriggerDateTime(0))-PDPPage.GetRecordStartDateTime(0)\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(prefault),actualPrefault,0,\"Prefault calculated from PDP is :-\"+actualPrefault)\n \n //Step14. Export to CDF.\n if (aqFileSystem.Exists(Project.ConfigPath+\"DFRRecordResults\"))\n {\n AssertClass.IsTrue(PDPPage.ExportTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\"))\n }\n else\n {\n aqFileSystem.CreateFolder(Project.ConfigPath+\"DFRRecordResults\")\n AssertClass.IsTrue(PDPPage.ExportTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\"))\n } \n //Step15. Export to CSV\n var sysUserName = CommonMethod.GetSystemUsername()\n var dfrRecordPath =\"C:\\\\Users\\\\\"+sysUserName+\"\\\\Desktop\\\\DFRRecord\\\\\"\n if (aqFileSystem.Exists(dfrRecordPath))\n {\n AssertClass.IsTrue(PDPPage.ExportTOCSV()) \n }\n else\n {\n aqFileSystem.CreateFolder(dfrRecordPath)\n AssertClass.IsTrue(PDPPage.ExportTOCSV())\n }\n AssertClass.IsTrue(CommonMethod.KillProcess(\"EXCEL\")) //This method is used to kill the process \n Log.Message(\"Pass:-Test to check limit DFR record length feature when FR trigger(Pre+Oplimit+Post fault time) is within Maximum record length.\")\n }\n catch(ex)\n {\n Log.Message(ex.stack)\n Log.Error(\"Error:-Test to check limit DFR record length feature when FR trigger(Pre+Oplimit+Post fault time) is within Maximum record length.\") \n }\n finally\n {\n OmicronStateSeqPage.CloseStateSeq()\n }\n}", "function CAM_734_Verification(OmirconSeqFile,expectedRecordDurationPrevRec,expectedRecordDurationLatestRec,dataSheetName,expectedPrefault,prefaultBuffer=0)\n{\n try\n {\n Log.Message(\"Log Start:-Test to check DFR record length when Trigger comes at end of first record with Seq .\" + OmirconSeqFile)\n //Step6. Click on DFR Directory under Display Device Directory\n AssertClass.IsTrue(DataRetrievalPage.ClickOnDFRDirectory() ,\"Clicked on DFR Directory\") \n \n //Step7. Find latest Record Number\n var lastDFRRecord= DataRetrievalPage.GetLatestRecordnumber()\n Log.Message(\"Current Record Number is :- \"+lastDFRRecord) \n \n //Step8. Close DFR Directory\n AssertClass.IsTrue(DataRetrievalPage.CloseDFRDirectory() ,\"Close DFR Directory\") \n \n //Step9 Start Omicron Injection\n OmicronStateSeqPage.RunSeqFile(Project.ConfigPath+\"TestData\\\\\"+CommonMethod.ReadDataFromExcel(dataSheetName,OmirconSeqFile))\n \n AssertClass.IsTrue(DFR_Methods.IsMultipleRecordFound(10,2,lastDFRRecord),\"Checking for new Record\")\n \n AssertClass.CompareString(\"FRSENSOR\",DataRetrievalPage.GetCOTForLastestXDFRRecords(2)[0],\"Checking COT\")\n \n //Step11. Click on Download Data Now\n AssertClass.IsTrue(DFR_Methods.DownloadMultipleRecords(),\"Clicked on Download Data Now\")\n CommonMethod.CheckActivityLog(\"DFR records saved successfully for device\")\n AssertClass.IsTrue(DataRetrievalPage.CloseDFRDirectory(),\"Closed DFR Directory\")\n DFR_Methods.ViewDFROnPDP(aqConvert.StrToInt64(lastDFRRecord)+2)\n \n //Step12. Check Record Length\n var recordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(0))//FirstRow\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(expectedRecordDurationLatestRec),aqConvert.StrToInt64(recordLength),10,\"Validating Record Duration.\")\n var recordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(1))//SecondRow\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(expectedRecordDurationPrevRec),aqConvert.StrToInt64(recordLength),0,\"Validating Record Duration.\")\n \n //Step13. Check Prefault time\n var actualPrefault = (PDPPage.GetRecordTriggerDateTime(0))-PDPPage.GetRecordStartDateTime(0)\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(expectedPrefault)-prefaultBuffer,actualPrefault,0,\"Prefault calculated from PDP is :-\"+actualPrefault)\n var actualPrefault = (PDPPage.GetRecordTriggerDateTime(1))-PDPPage.GetRecordStartDateTime(1)\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(expectedPrefault),actualPrefault,0,\"Prefault calculated from PDP is :-\"+actualPrefault)\n \n //Step14. Export to CDF for first record.\n if (aqFileSystem.Exists(Project.ConfigPath+\"DFRRecordResults\"))\n {\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\",0))\n }\n else\n {\n aqFileSystem.CreateFolder(Project.ConfigPath+\"DFRRecordResults\")\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\",0))\n } \n //Step14.1. Export to CDF for second record.\n if (aqFileSystem.Exists(Project.ConfigPath+\"DFRRecordResults\"))\n {\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\",1))\n }\n else\n {\n aqFileSystem.CreateFolder(Project.ConfigPath+\"DFRRecordResults\")\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\",1))\n } \n //Step15. Export to CSV for first record\n var sysUserName = CommonMethod.GetSystemUsername()\n var dfrRecordPath =\"C:\\\\Users\\\\\"+sysUserName+\"\\\\Desktop\\\\DFRRecord\\\\\"\n if (aqFileSystem.Exists(dfrRecordPath))\n {\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCSV(0)) \n }\n else\n {\n aqFileSystem.CreateFolder(dfrRecordPath)\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCSV(0))\n }\n AssertClass.IsTrue(CommonMethod.KillProcess(\"EXCEL\")) //This method is used to kill the process \n //Step15.1. Export to CSV for second record\n var sysUserName = CommonMethod.GetSystemUsername()\n var dfrRecordPath =\"C:\\\\Users\\\\\"+sysUserName+\"\\\\Desktop\\\\DFRRecord\\\\\"\n if (aqFileSystem.Exists(dfrRecordPath))\n {\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCSV(1)) \n }\n else\n {\n aqFileSystem.CreateFolder(dfrRecordPath)\n AssertClass.IsTrue(PDPPage.ExportMultipleTOCSV(1))\n }\n AssertClass.IsTrue(CommonMethod.KillProcess(\"EXCEL\")) //This method is used to kill the process \n Log.Message(\"Log End:-Test to check DFR record length when Trigger comes at end of first record with Seq .\" + OmirconSeqFile)\n } \n catch(ex)\n {\n Log.Message(ex.stack)\n Log.Error(\"Error:-Test to check DFR record length when Trigger comes at end of first record with Seq.\" + OmirconSeqFile) \n }\n finally\n {\n OmicronStateSeqPage.CloseStateSeq()\n }\n}", "function CAM_763()\n{\n try\n {\n Log.Message(\"Start:-Test to check DFR record length with prefault =500ms and Max length =800ms.\")\n var dataSheetName = Project.ConfigPath +\"TestData\\\\CAM_763.xlsx\"\n //Step0.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step1. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step2. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step3. Set pre-fault for External Triggers\n var prefault =CommonMethod.ReadDataFromExcel(dataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),\"Validating Prefault Time\")\n \n //Step3.1. Set Max DFR time\n var maxDFR=CommonMethod.ReadDataFromExcel(dataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(maxDFR),\"Validating Max DFR\") \n \n //Step3.2 Click on FR Sensor\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFRSensor(),\"Clicked on FR Sensor\")\n \n //Step4 Set Post Fault,Oplimit for FR Sensor\n AssertClass.IsTrue(ConfigEditor_FaultRecording_FRSensorPage.OpenFRSensorEditor(0),\"Open up FR Sensor Editor\") //Setting First FR Sensor\n var frsensorNameFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"FRSensorName\")\n var frsensorTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"Type\")\n var frsensorScalingTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"ScalingType\")\n var frsensorUpperThresholdFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"UpperThreshold\")\n var frsensorPostFaultTimeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"PostFaultTime\")\n var frsensorOplimitFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"Oplimit\")\n var expectedRecordDuration = CommonMethod.ReadDataFromExcel(dataSheetName,\"ExpectedRecordDuration\")\n \n DFR_Methods.SetFRSensor(frsensorNameFromTestData,frsensorTypeFromTestData,frsensorScalingTypeFromTestData,frsensorUpperThresholdFromTestData,frsensorPostFaultTimeFromTestData,frsensorOplimitFromTestData)\n \n //Step5. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\") \n \n //Step6. Click on DFR Directory under Display Device Directory\n AssertClass.IsTrue(DataRetrievalPage.ClickOnDFRDirectory() ,\"Clicked on DFR Directory\") \n \n //Step7. Find latest Record Number\n var lastDFRRecord= DataRetrievalPage.GetLatestRecordnumber()\n Log.Message(\"Current Record Number is :- \"+lastDFRRecord) \n \n //Step8. Close DFR Directory\n AssertClass.IsTrue(DataRetrievalPage.CloseDFRDirectory() ,\"Close DFR Directory\") \n \n //Step9.Start Omicron Injection\n OmicronStateSeqPage.RunSeqFile(Project.ConfigPath+\"TestData\\\\\"+CommonMethod.ReadDataFromExcel(dataSheetName,\"OmicronFile\"))\n AssertClass.IsTrue(DFR_Methods.IsMultipleRecordFound(10,1,lastDFRRecord),\"Checking for new Record\") \n \n //Step10. Click on Download Data Now\n AssertClass.IsTrue(DFR_Methods.DownloadManualDFR(),\"Clicked on Download Data Now\")\n \n //Step11. Check Record Length\n var recordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(0))//FirstRow\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(expectedRecordDuration),aqConvert.StrToInt64(recordLength),10,\"Validating Record Duration.\") //Added tolerance of 10 as sometimes we get 2-3 ms of additional duration\n \n Log.Message(\"Pass:-Test to check DFR record length with prefault =500ms and Max length =800ms\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check DFR record length with prefault =500ms and Max length =800ms\")\n }\n finally\n {\n OmicronStateSeqPage.CloseStateSeq()\n }\n}", "function CAM_734()\n{\n try\n {\n Log.Message(\"Start:-Test to check DFR record length when Trigger comes at end of first record..\")\n var dataSheetName = Project.ConfigPath +\"TestData\\\\CAM_734.xlsx\"\n //Step0.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(dataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step1. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step2. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step3. Set pre-fault for External Triggers\n var prefault =CommonMethod.ReadDataFromExcel(dataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),\"Validating Prefault Time\")\n \n //Step3.1. Set Max DFR time\n var maxDFR=CommonMethod.ReadDataFromExcel(dataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(maxDFR),\"Validating Max DFR\") \n \n //Step3.2 Click on FR Sensor\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFRSensor(),\"Clicked on FR Sensor\")\n \n //Step4 Set Post Fault,Oplimit for FR Sensor\n AssertClass.IsTrue(ConfigEditor_FaultRecording_FRSensorPage.OpenFRSensorEditor(0),\"Open up FR Sensor Editor\") //Setting First FR Sensor\n var frsensorNameFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"FRSensorName\")\n var frsensorTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"Type\")\n var frsensorScalingTypeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"ScalingType\")\n var frsensorUpperThresholdFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"UpperThreshold\")\n var frsensorPostFaultTimeFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"PostFaultTime\")\n var frsensorOplimitFromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"Oplimit\")\n var expectedRecordDuration1 = CommonMethod.ReadDataFromExcel(dataSheetName,\"ExpectedRecordDuration_1\")\n var expectedRecordDuration2 = CommonMethod.ReadDataFromExcel(dataSheetName,\"ExpectedRecordDuration_2\")\n var expectedRecordDuration3 = CommonMethod.ReadDataFromExcel(dataSheetName,\"ExpectedRecordDuration_3\")\n var expectedRecordDuration4 = CommonMethod.ReadDataFromExcel(dataSheetName,\"ExpectedRecordDuration_4\")\n \n DFR_Methods.SetFRSensor(frsensorNameFromTestData,frsensorTypeFromTestData,frsensorScalingTypeFromTestData,frsensorUpperThresholdFromTestData,frsensorPostFaultTimeFromTestData,frsensorOplimitFromTestData)\n \n //Step4.1 Set Post fault, oplimit for FR sensor\n AssertClass.IsTrue(ConfigEditor_FaultRecording_FRSensorPage.OpenFRSensorEditor(1),\"Open up FR Sensor Editor\") //Setting Second FR Sensor\n var frsensorName1FromTestData = CommonMethod.ReadDataFromExcel(dataSheetName,\"FRSensorName1\")\n \n DFR_Methods.SetFRSensor(frsensorName1FromTestData,frsensorTypeFromTestData,frsensorScalingTypeFromTestData,frsensorUpperThresholdFromTestData,frsensorPostFaultTimeFromTestData,frsensorOplimitFromTestData)\n \n //Step5. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n CAM_734_Verification(\"OmicronFile_1\",expectedRecordDuration1,expectedRecordDuration2,dataSheetName,prefault,100);\n CAM_734_Verification(\"OmicronFile_2\",expectedRecordDuration3,expectedRecordDuration4,dataSheetName,prefault);\n \n Log.Message(\"Pass:-Test to check DFR record length when Trigger comes at end of first record.\")\n } \n catch(ex)\n {\n Log.Message(ex.stack)\n Log.Error(\"Error:-Test to check DFR record length when Trigger comes at end of first record.\") \n }\n}", "function CAM_686_687_688()\n{\n try\n {\n Log.Message(\"Started TC:-Test to check limit DFR record length feature when Manual trigger(Pre+Post fault time) is equal to Maximum record length\") \n var DataSheetName = Project.ConfigPath +\"TestData\\\\CAM_686_687_688.xlsx\"\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step5.0 //Enter PreFault\n var Prefault=CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(Prefault),\"Setting Prefault Time\")\n \n //Step5.1 Enter & Check Max DFR value\n var MaxDFRLength =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength),\"Setting and checking Max DFR\")\n \n //Step5.2 Set Post fault\n var PostFault =CommonMethod.ReadDataFromExcel(DataSheetName,\"PostFaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPostFault(PostFault),\"Setting Post Fault time\")\n \n //Step6. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step7. Trigger Manual DFR\n DFR_Methods.TriggerManualDFR()\n \n //Step8. Download Manual DFR\n AssertClass.IsTrue(DFR_Methods.DownloadManualDFR(),\"Downloading DFR\")\n \n //Step9. Get Prefault time\n var ActualPrefault = (PDPPage.GetRecordTriggerDateTime(0))-PDPPage.GetRecordStartDateTime(0)\n \n //Step10. Get Postfault time\n var ActualPostFault = PDPPage.GetRecordEndDateTime(0)-(PDPPage.GetRecordTriggerDateTime(0))\n \n //Step9. Check Record Length\n var RecordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(0))//FirstRow\n \n if(aqConvert.StrToInt64(Prefault)+aqConvert.StrToInt64(PostFault)<=aqConvert.StrToInt64(MaxDFRLength))\n { \n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(ActualPrefault)+aqConvert.StrToInt64(ActualPostFault),aqConvert.StrToInt64(RecordLength),1,\"Validating Record Duration.\")\n }\n else\n {\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(MaxDFRLength),aqConvert.StrToInt64(RecordLength),1,\"Validating Record Duration.\")\n } \n Log.Message(\"Pass:-Test to check limit DFR record length feature when Manual trigger(Pre+Post fault time) is equal to Maximum record length\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check limit DFR record length feature when Manual trigger(Pre+Post fault time) is equal to Maximum record length\")\n }\n}", "function CAM_728()\n{\n try\n {\n Log.Message(\"Started TC:-Test to check that DFR record length value get saved to database.\")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\MaxDFR.xlsx\"\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step5.0 //Enter PreFault\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")),\"Setting Prefault Time\")\n \n //Step5. Enter & Check Max DFR value\n var MaxDFRLength =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength),\"Setting and checking Max DFR\")\n \n //Step6. Save to DB\n AssertClass.IsTrue(ConfigEditorPage.ClickSaveToDb(),\"Clicked on Save to DB\")\n \n //Step7. Click on Modify Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonModifyConfig(),\"Clicked on Modify Config\")\n \n //Step7.1 Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step8. Check the Max DFR Value\n AssertClass.CompareString(ConfigEditor_FaultRecordingPage.GetMaxDFR(),MaxDFRLength,\"Checking Max DFR value\")\n \n Log.Message(\"Pass:-Test to check that DFR record length value get saved to database.\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check that DFR record length value get saved to database.\")\n }\n finally\n {\n AssertClass.IsTrue(ConfigEditorPage.ClickOnClose(),\"Clicked on Close in Config Editor\")\n }\n}", "function CAM_690()\n{\n try\n {\n Log.Message(\"Started TC:- Test to check that minimum and maximum limit for DFR record length with non-Transco licenses \")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\MaxDFR.xlsx\"\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step5.0 //Enter PreFault\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")),\"Setting Prefault Time\")\n \n //Step5. Enter & Check Max DFR value\n var MaxDFRLength =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength),\"Setting and checking Max DFR\")\n \n //Step6. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step7. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step8. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step9. Check for Prefault and Max DFR Value\n AssertClass.CompareString(ConfigEditor_FaultRecordingPage.GetMaxDFR(), MaxDFRLength,\"Checking for Max DFR Value\")\n \n Log.Message(\"Pass:- Test to check that minimum and maximum limit for DFR record length with non-Transco licenses\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check that minimum and maximum limit for DFR record length with non-Transco licenses\")\n }\n finally\n {\n AssertClass.IsTrue(ConfigEditorPage.ClickOnClose(),\"Clicked on Close in Config Editor\")\n }\n}", "function CAM_725()\n{\n try\n {\n Log.Message(\"Started TC:-Test to check that user tries to input DFR record length value less/greater than minimum/maximum value\")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\CAM_725.xlsx\";\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step5. Check the Max DFR Value\n var MaxDFR = ConfigEditor_FaultRecordingPage.GetMaxDFR();\n Log.Message(\"Max DFR value is\" + MaxDFR);\n \n //Step6. //Enter MaxDFR_Min\n var MaxDFR_Min = CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR_Min\")\n AssertClass.IsFalse(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFR_Min),\"Setting and checking Max DFR\")\n \n //Step7. Save to DB\n AssertClass.IsTrue(ConfigEditorPage.ClickSaveToDb(),\"Clicked on Save to DB\")\n \n //Step8. Click on Modify Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonModifyConfig(),\"Clicked on Modify Config\")\n \n //Step9. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step10. Check the Max DFR Value\n AssertClass.CompareString(ConfigEditor_FaultRecordingPage.GetMaxDFR(),MaxDFR,\"Checking Max DFR value\")\n\n //Step11. //Enter MaxDFR_Max\n var MaxDFR_Max =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR_Max\")\n AssertClass.IsFalse(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFR_Max),\"Setting and checking Max DFR\")\n \n //Step12. Save to DB\n AssertClass.IsTrue(ConfigEditorPage.ClickSaveToDb(),\"Clicked on Save to DB\")\n \n //Step13. Click on Modify Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonModifyConfig(),\"Clicked on Modify Config\")\n \n //Step14. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step15. Check the Max DFR Value\n AssertClass.CompareString(ConfigEditor_FaultRecordingPage.GetMaxDFR(),MaxDFR,\"Checking Max DFR value\")\n \n //Step16 //Enter PreFault\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")),\"Setting Prefault Time\")\n \n //Step17. //Enter MaxDFR_Mid\n var MaxDFR_Mid =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR_Mid\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFR_Mid),\"Setting and checking Max DFR\")\n \n //Step18. Save to DB\n AssertClass.IsTrue(ConfigEditorPage.ClickSaveToDb(),\"Clicked on Save to DB\")\n \n //Step19. Click on Modify Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonModifyConfig(),\"Clicked on Modify Config\")\n \n //Step20. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step21. Check the Max DFR Value\n AssertClass.CompareString(ConfigEditor_FaultRecordingPage.GetMaxDFR(),MaxDFR_Mid,\"Checking Max DFR value\")\n\n //Step22. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n \n Log.Message(\"Pass:-Test to check that user tries to input DFR record length value less/greater than minimum/maximum value\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check that user tries to input DFR record length value less/greater than minimum/maximum value\")\n }\n}", "function CAM_739()\n{\n try\n {\n Log.Message(\"Started TC:-Test to check the import/export functionality for DFR record length.\")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\CAM-739.xlsx\"\n var File_Name = Project.ConfigPath +\"TestData\\\\CAM-739_Export-Import Configuration\\\\Configuration.cfg\"\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step3. Set pre-fault for External Triggers\n var prefault =CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),\"Updated Pre-fault Time\")\n \n //Step4. Set Post-fault time for External Triggers\n var postfault=CommonMethod.ReadDataFromExcel(DataSheetName,\"PostFaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPostFault(postfault),\"Updated Post-faulttime\")\n \n //Step5. Enter & Check Max DFR value\n //Step5.1 Set Prefault time\n var prefault =CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),\"Validating Prefault Time\") \n \n var MaxDFRLength =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength),\"Setting and checking Max DFR\")\n \n //Step6. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step7. Export configuration as a File\n ConfigEditor_Methods.ExportConfigurationAsFile(File_Name)\n Log.Message(\"Exported configuration as a File\")\n ConfigEditorPage.ClickOnClose()\n \n //Step8. Select other device\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName2\"))\n \n //Step9.Import Configuration as a File\n ConfigEditor_Methods.ImportConfigurationAsFile(CommonMethod.ReadDataFromExcel(DataSheetName,\"File_Name_Import\"))\n Log.Message(\"Imported configuration as a File\")\n \n \n //Step9.1 Verify Max DFR value\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(ConfigEditor_FaultRecordingPage.GetMaxDFR()),aqConvert.StrToInt64(MaxDFRLength),0, \"Max DFR value is properly imported and is equal to the primary device value\")\n ConfigEditorPage.ClickOnClose()\n \n \n //Step10. Select Primary device\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))\n \n //Step11. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step12. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step13. Enter & Check Max DFR value\n var MaxDFRLength1 =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR1\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength1),\"Setting and checking Max DFR\")\n \n //Step14. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step15. Export configuration as a Template\n ConfigEditor_Methods.ExportConfigurationAsTemplate(CommonMethod.ReadDataFromExcel(DataSheetName,\"Template_Name\"))\n Log.Message(\"Exported configuration as a Template\")\n ConfigEditorPage.ClickOnClose()\n \n //Step16. Select other device\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName2\"))\n \n //Step17. Import configuration as a Template\n ConfigEditor_Methods.ImportConfigurationAsTemplate(CommonMethod.ReadDataFromExcel(DataSheetName,\"Template_Name\"))\n Log.Message(\"Imported configuration as a Template\")\n \n //Step17.2 Verify Max DFR value after Importing as Template\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(ConfigEditor_FaultRecordingPage.GetMaxDFR()),aqConvert.StrToInt64(MaxDFRLength1),0, \"Max DFR value is properly imported and is equal to the primary device value\")\n ConfigEditorPage.ClickOnClose()\n \n //Step18. Select Primary device\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))\n \n //Step19. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step20. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step21. Enter & Check Max DFR value\n var MaxDFRLength2 =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR2\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength2),\"Setting and checking Max DFR\")\n \n //Step22. Send to device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step23. Select other device\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName2\"))\n \n //Step24. Import configuration from other device\n ConfigEditor_Methods.ImportConfigFromOtherDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))\n Log.Message(\"Imported configuration from other device\")\n \n \n //Step25 Verify Max DFR value after Importing from other device\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(ConfigEditor_FaultRecordingPage.GetMaxDFR()),aqConvert.StrToInt64(MaxDFRLength2),0, \"Max DFR value is properly imported and is equal to the primary device value\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check the GUI(Text/Editbox) of iQ+ for Maximum DFR record length\")\n }\n finally\n {\n AssertClass.IsTrue(ConfigEditorPage.ClickOnClose(),\"Clicked on Close in Config Editor\")\n }\n}", "function maxLengthReached(){\n\tif (continuous){\n\t\t//drop old buffer\n\t\tvar shift = (recordedBuffers.length - recordBufferMaxN);\n\t\t_shiftedBuffers += shift;\n\t\trecordedBuffers.splice(0, shift);\n\t}else{\n\t\t//close\n\t\tif (gateIsOpen){\n\t\t\tgateControl(false);\n\t\t}\n\t}\n\t//TODO: do more ... ?\n}", "function Validate_RecordTime()\n{\n try\n {\n Log.Message(\"Start:-Test to Validate Prefault,Post fault time and record length in the DFR record.\")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\SmokeTestData.xlsx\"\n //Step0.1 Start Omicron Injection\n OmicronQuickCMCPage.InjectVoltCurrent(Project.ConfigPath+\"TestData\\\\\"+CommonMethod.ReadDataFromExcel(DataSheetName,\"OmicronFile\"))\n //Step0.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step1. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step2. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step3. Set pre-fault for External Triggers\n var prefault =CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(prefault),\"Validating Prefaul Time\")\n \n //Step4. Set Post-fault time for External Triggers\n var postfault=CommonMethod.ReadDataFromExcel(DataSheetName,\"PostFaultTime\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPostFault(postfault),\"Validating Post Faulttime\")\n \n //Step4.1. Set Max DFR time\n var MaxDFR=CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFR),\"Validating Max DFR\")\n \n //Step5. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step6. Trigger & Download Manual DFR Record\n DFR_Methods.TriggerManualDFR()\n \n //Step6.1 \n DFR_Methods.DownloadManualDFR()\n \n //Step7. Check Record Length\n var RecordLength= CommonMethod.ConvertTimeIntoms(PDPPage.GetRecordDuration(0))//FirstRow\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(prefault)+aqConvert.StrToInt64(postfault),aqConvert.StrToInt64(RecordLength),0,\"Validating Record Duration.\")\n \n //Step8. Check Time Quality Status\n //Step8.1 Click on Device Status View\n AssertClass.IsTrue(DataRetrievalPage.ClickOnDeviceStatusView(),\"Clicked on Device Status View\")\n \n //Step8.2 Check Time Quality Staus Actual\n AssertClass.CompareString(DataRetrievalPage.TimeQualityStatusFromDeviceStatus(),PDPPage.GetTimeQualityStatus(0).ToString().OleValue,\"Comparing Time Quality from Device Status and from DFR record in PDP.\")\n \n //Step8.3\n DataRetrievalPage.CloseDeviceStatus.ClickButton()\n //Step9. Check Prefault time\n var ActualPrefault = (PDPPage.GetRecordTriggerDateTime(0))-PDPPage.GetRecordStartDateTime(0)\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(prefault),ActualPrefault,0,\"Prefault calculated from PDP is :-\"+ActualPrefault)\n \n //Step10. Check Postfault value\n var ActualPostFault = PDPPage.GetRecordEndDateTime(0)-(PDPPage.GetRecordTriggerDateTime(0))\n AssertClass.CompareDecimalValues(aqConvert.StrToInt64(postfault),ActualPostFault,0,\"Postfault calculated from PDP is :-\"+ActualPostFault)\n \n //Step11. Export to CDF.\n if (aqFileSystem.Exists(Project.ConfigPath+\"DFRRecordResults\"))\n {\n AssertClass.IsTrue(PDPPage.ExportTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\"))\n }\n else\n {\n aqFileSystem.CreateFolder(Project.ConfigPath+\"DFRRecordResults\")\n AssertClass.IsTrue(PDPPage.ExportTOCDF(Project.ConfigPath+\"DFRRecordResults\\\\\"))\n } \n //Step12. Export to CSV\n var SysUserName = CommonMethod.GetSystemUsername()\n var DFRRecordPath =\"C:\\\\Users\\\\\"+SysUserName+\"\\\\Desktop\\\\DFRRecord\\\\\"\n if (aqFileSystem.Exists(DFRRecordPath))\n {\n AssertClass.IsTrue(PDPPage.ExportTOCSV()) \n }\n else\n {\n aqFileSystem.CreateFolder(DFRRecordPath)\n AssertClass.IsTrue(PDPPage.ExportTOCSV())\n }\n AssertClass.IsTrue(CommonMethod.KillProcess(\"EXCEL\")) //This method is used to kill the process\n \n //Step 13. Validate RMS Data\n AssertClass.IsTrue(RMSDataValidationExePage.LaunchRMSValidationApplication())\n \n var RMSValidationStatus= RMSDataValidationExePage.ValidateRMSData(DFRRecordPath+aqFileSystem.FindFiles(DFRRecordPath, \"*.csv\").Item(0).Name,CommonMethod.ReadDataFromExcel(DataSheetName,\"RMSInjectedVoltage\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"RMSInjectedCurrent\"))\n \n AssertClass.IsTrue(aqFile.Move(DFRRecordPath+aqFileSystem.FindFiles(DFRRecordPath, \"*.csv\").Item(0).Name,Project.ConfigPath+\"DFRRecordResults\"),\"Moving CSV file to Project Folder\")//Move the file to the Project path folder\n AssertClass.CompareString(\"PASS\", RMSValidationStatus,\"Checking RMS Validation\" ) \n Log.Message(\"Pass:-Test to Validate Prefault,Post fault time and record length in the DFR record.\")\n }\n catch(ex)\n {\n Log.Message(ex.stack)\n Log.Error(\"Error:-Test to Validate Prefault,Post fault time and record length in the DFR record.\") \n }\n finally\n {\n AssertClass.IsTrue(OmicronQuickCMCPage.CloseQuickCMC(),\"Close Quick CMC Application\")\n }\n}", "static get maxRecordLength () { return 8000 }", "triggerTest() {\n if (\n this.this.isAboveThreshold &&\n this.this.isTimerActive &&\n this.getCurr().length < MAX_TRIGGER_AMOUNT\n ) {\n this.triggerAction();\n console.log('ACTION');\n }\n }", "static evalUOMLengthWithinLimit(dict, limit) {\n return (libCom.getControlValue(dict.UOMSim).length <= Number(limit));\n }", "checkMaxLength() {\n let maxWidth = toothpickSettings.maxPlaygroundWidth;\n let actualWidth = this.length * this.linesCount;\n if (actualWidth > maxWidth) {\n this.length = maxWidth / this.linesCount;\n }\n }", "function CAM_727()\n{\n try\n {\n Log.Message(\"Started TC:- Test to check the GUI(Text/Editbox) of iQ+ for Maximum DFR record length\")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\MaxDFR.xlsx\"\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step5.1. Check the Max DFR label.\n AssertClass.CompareString(\"Maximum Record Length:\", aqString.Trim(ConfigEditor_FaultRecordingPage.GetMaxDFRLabel()),\"Checking Max DFR label on UI\")\n \n //Step5.2. Check the Max DFR Unit.\n AssertClass.CompareString(\"ms\", aqString.Trim(ConfigEditor_FaultRecordingPage.GetMaxDFRUnit()),\"Checking Max DFR unit label on UI\")\n \n //Step6. Check Max DFR Editbox exist on UI.\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.Edtbx_MaxDFR.Exists,\"Checking Editbox exists on UI\")\n Log.Message(\"Pass:-Test to check the GUI(Text/Editbox) of iQ+ for Maximum DFR record length\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check the GUI(Text/Editbox) of iQ+ for Maximum DFR record length\")\n }\n finally\n {\n AssertClass.IsTrue(ConfigEditorPage.ClickOnClose(),\"Clicked on Close in Config Editor\")\n }\n}", "function CAM_689()\n{\n try\n {\n Log.Message(\"Started TC:-Test to check that user tries to set minimum DFR record length equal to Prefault time\")\n var DataSheetName = Project.ConfigPath +\"TestData\\\\CAM_689.xlsx\"\n \n //Step1.: Check if iQ-Plus is running or not.\n AssertClass.IsTrue(CommonMethod.IsExist(\"iQ-Plus\"),\"Checking if iQ+ is running or not\")\n \n //Step2.Check whether device exists or not in the topology. \n if(DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"))!=true)\n {\n GeneralPage.CreateDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceSerialNo\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceIPAdd\"))\n DeviceTopologyPage.ClickonDevice(CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceType\"),CommonMethod.ReadDataFromExcel(DataSheetName,\"DeviceName\")) \n }\n else\n {\n Log.Message(\"Device exist in the tree topology.\")\n }\n \n //Step3. Retrieve Configuration\n AssertClass.IsTrue(DeviceManagementPage.ClickonRetrieveConfig(),\"Clicked on Retrieve Config\")\n \n //Step4. Click on Fault Recording\n AssertClass.IsTrue(ConfigEditorPage.ClickOnFaultRecording(),\"Clicked on Fault Recording\")\n \n //Step5.0 //Enter PreFault\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetPrefault(CommonMethod.ReadDataFromExcel(DataSheetName,\"PrefaultTime\")),\"Setting Prefault Time\")\n \n //Step5. Enter & Check Max DFR value\n var MaxDFRLength =CommonMethod.ReadDataFromExcel(DataSheetName,\"MaxDFR\")\n AssertClass.IsTrue(ConfigEditor_FaultRecordingPage.SetMaxDFR(MaxDFRLength),\"Setting and checking Max DFR\")\n \n //Step6. Send to Device\n AssertClass.IsTrue(ConfigEditorPage.ClickSendToDevice(),\"Clicked on Send to Device\")\n \n //Step7. Check Error on Finish Pane\n AssertClass.CompareString(\"DFR maximum record length has to be at least 100ms more than the pre-fault.\",ConfigEditor_FinishPage.GetErrorText(\"Fault Recording\"),\"Checking for Error Validation on Finish Pane.\")\n \n Log.Message(\"Pass:-Test to check that user tries to set minimum DFR record length equal to Prefault time\")\n }\n catch(ex)\n {\n Log.Error(ex.stack)\n Log.Error(\"Fail:-Test to check that user tries to set minimum DFR record length equal to Prefault time\")\n }\n finally\n {\n AssertClass.IsTrue(ConfigEditorPage.ClickOnClose(),\"Clicked on Close in Config Editor\")\n }\n}", "function reductionIsTooShort(reduction) { \n\t\treturn reduction.length <= numSteps;\n\t }", "function calculatePCLength(len){\n let adder=0,ch=Math.abs(Math.ceil(len/500)*500-len) ;\n (ch<=420)?(adder=0):(adder=-500)\n return Math.ceil(len/500)*500+adder\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a list of all the tags of a specific user
function listUsersTags(user_id) { return db('tags').where({user_id}).first(); }
[ "function getUserTags(username) {\n\tvar query = \"SELECT Content.id, username_tagger, username_taggee, Tag.timest \" +\n\t\t\t\t\"FROM Tag, Content WHERE Tag.id = Content.id AND username_taggee = ? AND status IS false\";\n\treturn new Promise((resolve, reject) => {\n\t\tconnection.query(query, username, (err, rows) => {\n\t\t\tif (err) return reject(err);\n\t\t\tif (rows.length === 0) resolve(null);\n\t\t\telse { resolve(rows); }\n\t\t})\n\t})\n}", "list(req, res) {\n\n return TagToUser\n .findAll({\n where: { user_id: req.params.user_id },\n include: [{\n model: Tags,\n as: 'tag',\n attributes: [],\n }],\n attributes: { exclude: ['createdAt', 'updatedAt', 'user_id', 'id'] },\n raw: true\n })\n .then(tag => {\n res.status(200).send(tag);\n }).catch((error) => res.status(400).send(error));\n }", "static getTagsByUserId(id) {\n let tempArray = []\n\n for (let i = 0; i < wishlists.length; i++) {\n if (wishlists[i].userId == id) {\n tempArray = wishlists[i].tagList\n }\n }\n return tempArray\n }", "getUserTags(state) {\n return state.userTags;\n }", "function getUsersForTag(tagname) {\n User.getUsersForTag(tagname)\n .then(function (data) {\n vm.tagModalData = data;\n });\n }", "function getUsersByTagId(tagId)\n{\n\tvar foundUsers = new Array();\n\tvar users = getUserContainer();\n\tfor (var i=0; i<users.length; i++) {\n\t\tif (users[i].tagIds.indexOf(tagId) > -1) {\n\t\t\tfoundUsers.push(users[i]);\n\t\t}\n\t}\n\treturn foundUsers;\n}", "getUsersByTagId(tagId)\n\t{\n\t\tvar foundUsers = new Array();\n\t\tvar users = this.getUserContainer();\n\t\tfor (var i=0; i<users.length; i++) {\n\t\t\tif (users[i].tagIds.indexOf(tagId) > -1) {\n\t\t\t\tfoundUsers.push(users[i]);\n\t\t\t}\n\t\t}\n\t\treturn foundUsers;\n\t}", "initTags(user) {\n this.tags = {};\n user.organization.tags.forEach(tag => {\n this.tags[tag.id] = {\n id: tag.id,\n name: tag.name,\n description: tag.description,\n users: tag.users\n };\n });\n\n user.tags.forEach(tag => {\n this.tags[tag.id].subscribed = true;\n });\n\n this.showAllTags();\n }", "function findTags(callback,user) {\n Users.findOne({'u_id':user.u_id}, {'follows':1}).then(function(follows){\n Tags.find({'tag': { $in: follows.follows}})\n .sort([['tag', 'ascending']])\n .exec(callback);\n });\n}", "function tagLinkList(){\n var tagList = [];\n \n angular.forEach(userTenderList, function(userTender){\n\n var tender = {};\n tender.item = userTender.item;\n tender._id = userTender._id;\n\n angular.forEach(userTender.userTags, function(userTag){\n\n var tag = {\n name : '',\n tendersList : []\n };\n\n var tagIndex = tagList.map(function(o){return o.name}).indexOf(userTag);\n\n if( tagIndex !== -1) {\n tagList[tagIndex].tendersList.push(tender);\n }\n else {\n tag.name = userTag;\n tag.tendersList.push(tender);\n tagList.push(tag);\n }\n })\n })\n return tagList;\n }", "async listTags() {\n const request = this._makeRequest('/tags/list');\n const response = await request.send();\n const result = await response.json();\n return result.tags;\n }", "function generateTags(currUser, userList, gameInfo) {\n\n}", "function getSubscriptions(user){\n try{\n // get all tags where the user is the same as the argument\n let totalTags = db.filter(item => item.users.includes(user.id));\n\n let tags = [];\n for(var i=0; i<totalTags.length; i++){\n tags.push(totalTags[i].tag);\n }\n tags.sort(); // sort alphabetically\n \n let msg = tags.join('\\n'); // separate by newline\n \n return \"Subscribed tags:\\n\" + msg;\n } catch(e){\n return \"Not subscribed to any tags.\";\n console.log(e);\n }\n}", "static getBooksByTagUserId(id) {\n for (let i = 0; i < wishlists.length; i++) {\n if (wishlists[i].userId == id) {\n return wishlists[i].notificationsTags\n }\n }\n return []\n }", "function getTags() {\n\ttags = [];\n\tdata.forEach(element => { tags = _.union(tags, element.tags); });\n\treturn tags;\n}", "getTags(context) {\n context.commit('setTags', []);\n api.getTags(context.state.userId)\n .then(response => {\n if (response.length !== 0) {\n context.commit('setTags', response);\n } else {\n context.commit('setTags', []);\n }\n })\n .catch(error => {\n console.log(error.response.data.message);\n });\n }", "getTags() {\n const tagList = [];\n for (const tag in this.tagDictionary) {\n tagList.push(tag);\n }\n return tagList;\n }", "function zoto_user_tags_list_recent_tags(options){\n\toptions = options || {};\n\toptions.no_results_msg = 'no tags were found';\n\tthis.zapi_str = 'tags.get_tag_list';\n\tthis.$uber(options);\n}", "async function getLinksByTagName(userId, tagName) {\n\ttry {\n\t\tconst links = await getAllLinks(userId);\n\t\t\n\t\t\n\t\tconst tagLinks = links.filter(link => {\n\t\t\tlet hasTag = false;\n\t\t\tlink.tags.forEach(tag => {\n\t\t\t\tif (tag === tagName) {\n\t\t\t\t\thasTag = true;\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn hasTag;\n\t\t})\n\n\t\t\n\t\treturn tagLinks;\n\n\t} catch (error) {\n\t\tthrow error;\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
will display the edit form for the id that is specified.
function displayEditForm(id) { const item = reviews.find(item => item["entityId"] === id.toString()); // finds the item that the id is associated with. document.getElementById('edit-id').value = item.entityId // sets the table id value equal to the value specified. document.getElementById('edit-message').value = item.message; // sets the table message value equal to the value specified. document.getElementById('edit-starRating').value = item.starRating; // sets the table starRating value equal to the value specified. document.getElementById('edit-filePath').value = item.imagePath; // sets the table filepath value equal to the value specified. document.getElementById('editForm').style.display = 'block'; // sets the table dispaly value to block. }
[ "function edit(edit_id) {\n open_form(APP_STATE.current_function, 'UPDATE', edit_id);\n}", "function showEditForm() {\n showEditContactView()\n\n editfName.value = db[this.id].name1;\n editlName.value = db[this.id].name2;\n editNumber.value = db[this.id].tel;\n editeMail.value = db[this.id].mail;\n keyEdit = this.id\n}", "function edit(id){\n return load(id).then(editInForm).then(save);\n }", "function handleEdit(id){\n setPatientEditID(id)\n setDisplayEditPatients(!displayEditPatients)\n }", "function openEditForm(storyId){\n const story = storyList.stories[storyList.getStoryIndexById(storyId)];\n const form = $editForm.get()[0];\n $editForm.attr('data-editId', storyId);\n form.title.value = story.title;\n form.author.value = story.author;\n form.url.value = story.url;\n $editForm.show();\n}", "function displayEditForm(id) {\n const item = horses.find(item => item.horseID === id);\n\n document.getElementById('edit-Id').value = item.horseID;\n\n document.getElementById('edit-Hname').value = item.name;\n document.getElementById('edit-Hspeed').value = item.topSpeed;\n document.getElementById('edit-Hbreed').value = item.breed;\n //Pushes values of only yyyy-mm-dd from DB\n document.getElementById('edit-HDOB').value = item.dob.slice(0, 10);\n //Selects option with DB value\n document.getElementById('edit-Hgender').value = item.gender;\n document.getElementById('edit-Hnotes').value = item.notes;\n\n //Displays Modal\n document.getElementById('EditHModal').style.display = 'block';\n}", "showEditView() {\n this.state = FIELD_STATE.EDIT;\n this.update();\n }", "function showEditModal(id) {\n const campaign = Store.getCampaignById(id);\n if (campaign) {\n const editModalTemplate = TemplateEngine.renderEditCampaignModal(\n campaign\n );\n const $modalWrapperEl = document.querySelector(\".modal-wrapper\");\n $modalWrapperEl.classList.remove(\"hide\");\n $modalWrapperEl.innerHTML = editModalTemplate;\n }\n }", "function editJob(id) {\r\n modal_job.find('.modal-title').html('Edit Job');\r\n modal_job.data('mode', 'edit');\r\n\r\n showModal({\r\n data: { id: id },\r\n url: '/job/edit',\r\n vm: modal_job\r\n });\r\n }", "function edit(id) {\n updateID = id;\n}", "function EditController(id) {\n\n // utils.history.push();\n\n utils.observer.trigger('router:changed');\n\n new View({\n model: new Model({\n iAlbumId: id\n })\n }).render({\n typeForm: 'edit'\n }).inject();\n }", "function showEditForm(){\n setEditing(true);\n }", "editCastle(id) {\n document.getElementById(\"editCastleDialog\").showModal()\n\n const castle = this.castles.filter(castle => castle.id === id)[0]\n this.form.editId = castle.id\n this.form.editName = castle.name\n this.form.editLink = castle.link\n }", "function openEditPage(id) {\r\n window.open(\"https://myanimelist.net/ownlist/anime/\" + id + \"/edit\", '_blank');\r\n }", "async function showEditForm(req, res, next) {\n\tlet user = await User.findOne({\n\t\twhere: {\n\t\t\tid: req.params.userId\n\t\t}\n\t})\n\tres.render('edit', {user: user})\n}", "function showEditDiv() {\n\tshowActionDiv('edit');\n}", "function completeQuickEdit(id)\n{\n document.getElementById(\"edit_\" + id).style.display = \"none\";\n document.getElementById(\"view_\" + id).style.display = \"inline\";\n document.getElementById(\"editLink_\" + id).style.display = \"inline\";\n document.getElementById(\"cancel_\" + id).style.display = \"none\";\n document.getElementById(\"save_\" + id).style.display = \"none\";\n document.getElementById(\"view_\" + id).innerHTML = escaping(document.getElementById(\"editField_\" + id).value);\n}", "function edit(e,id){\n var url = '/car/'+id;\n if(e.which === LEFT_CLICK){\n zoomEditView();\n AjaxHelper.retrieve(url,fillForm);\n }\n }", "function editHandler(e) {\n const id = e.target.getAttribute(\"data_id\");\n location.href = \"/edit.html?id=\" + id;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads a key from a circularjson persisted object
function loadKey( root ) { var fileText; var filePath = root + "key.json" ; if ( typeof Ti !== "undefined" ) { fileText = Ti.Filesystem.getFile(filePath).read().text; } else { fileText = require('fs').readFileSync(filePath, 'utf8' ); } var key = CircularJSON.parse( fileText ); key.url = root; var rehydrated = rehydrateKey( key ); rehydrateSpeedBug( key ); return rehydrated; }
[ "getObject(key) {\n const v = this.get(key);\n if (v === undefined) {\n return undefined;\n }\n try {\n return JSON.parse(v);\n }\n catch (err) {\n throw new ConfigTypeError(this.fullKey(key), v, \"JSON object\");\n }\n }", "loadObject (key) {\n\n\n /**\n * set default key\n */\n\n key = key || 'HO';\n\n\n /**\n * get handyObject from storage\n */\n\n const handyObject = JSON.parse(window.localStorage.getItem('canvas-' + key));\n\n\n /**\n * check if it exists and if it is an object\n */\n\n if(!handyObject || typeof handyObject !== 'object') return false;\n\n\n /**\n * update current handyObject\n */\n\n this._HANDYOBJECT_ = handyObject;\n\n\n /**\n * return handyObject\n */\n\n return this._HANDYOBJECT_;\n\n\n }", "function unstoreObject(key)\n{\n if (!isStored(key))\n {\n console.log('[ERROR] failed to locate object in local store using key: ' + key);\n return null;\n }\n\n let value = unstore(key);\n return JSON.parse(value);\n}", "function loadObjFromLocalStorage(key, obj) {\n\t\tobj = localStorage.getItem(key);\n\t\tobj = JSON.parse(obj);\n\n\t\treturn obj;\n\t}", "function readLocalStorageKeyConvertToObject (key){\n let value_deserialize = JSON.parse(window.localStorage.getItem(key));\n return value_deserialize;\n}", "function decode(obj, key){\n var newKey = key.split($).join(\"\").split(DOT).join(\".\");\n\n if(key !== newKey){\n obj[newKey] = obj[key];\n delete obj[key];\n }\n}", "findReference(ref) {\n const keys = ref.split('.')\n let key = keys.shift()\n let result = this.chunks[key]\n\n if (!result) {\n throw new TypeError(`Could not read property \"${key}\" from undefined`)\n }\n\n // Iterate over all the keys and find the property\n while ((key = keys.shift())) {\n result = result[key]\n }\n\n if (typeof result === 'object' && !(result instanceof Array)) {\n // Test if the result we have is an object. This means the user wants to reference\n // to the _id of the object.\n if (!result._id) {\n // If no _id property exists, throw a TypeError that the property could not be found\n throw new TypeError(`Could not read property \"_id\" of ${JSON.stringify(result)}`)\n }\n\n return result._id\n }\n\n return result\n }", "function fromDatastore (obj) {\n obj.data.id = obj.key.id;\n return obj.data;\n}", "load_prekey(prekey_id) {\n return this.engine\n .read(CryptoboxCRUDStore.STORES.PRE_KEYS, prekey_id.toString())\n .then(record => {\n const payload = this.from_store(record);\n return proteus_1.keys.PreKey.deserialise(payload);\n })\n .catch(error => {\n if (error instanceof store_engine_1.error.RecordNotFoundError) {\n return undefined;\n }\n throw error;\n });\n }", "function getLocalObject(key, callback) {\n\tchrome.storage.local.get(key, function (item) {\n\t\tcallback(item[key]);\n\t});\n}", "fromJson(dataJson){\n\n if(dataJson){\n let key;\n for(key in dataJson){\n if(dataJson.hasOwnProperty(key)){\n this[key] =dataJson[key];\n }\n console.log(key)\n }\n \n }else{\n console.log('ERROR: Pedido.fromJson','la variable pasada es null')\n }\n }", "function LoadObject(nm, defval){\n\tvar val = null;\n\ttry{\n\t\tvar X = stor.getItem(nm);\n\t\tconsole.log(\"get \"+nm+\", got: \"+X);\n\t\tval = JSON.parse(X);\n\t}catch(e){\n\t\tconsole.log(e);\n\t}\n\tif(val == null && typeof(defval) != \"undefined\"){\n\t\tval = defval;\n\t}\n\tconsole.log(\"load: \" + nm +\" (\"+val+\")\");\n\treturn val;\n}", "function _get(obj, keypath) {\n var parts = _keyPathNormalize(keypath).split('.')\n var dest = obj\n parts.forEach(function(key) {\n // Still set to non-object, just throw that error\n dest = dest[key]\n })\n return dest\n }", "function readLocalStorageKeyConvertToObject (key){\n let value_deserialize = JSON.parse(window.localStorage.getItem(key));\n console.log(value_deserialize);\n return value_deserialize;\n}", "load() {\n\t\tvar json = localStorage.getItem(this.keyname);\n\t\tif (json) {\n\t\t\tvar data = JSON.parse(json);\n\t\t\tfor (let key in data) {\n\t\t\t\tthis[key] = data[key];\n\t\t\t}\n\t\t}\n\t}", "function unstoreObject(key)\n{\n if (!isStored(key))\n {\n console.log('[ERROR] failed to locate object in session store using key: ' + key);\n return null;\n }\n\n let value = unstore(key);\n return JSON.parse(value);\n}", "async function load(key, options = {}) {\n let cacheObj;\n let lockOk = await cache.checkLock(key, options.retry);\n if (lockOk !== true) {\n throw new Error(index_1.i18n.localize(\"actionhero.cache.objectLocked\"));\n }\n let cachedStringifiedObjet = await client().get(`${cache.redisPrefix}${key}`);\n try {\n cacheObj = JSON.parse(cachedStringifiedObjet);\n }\n catch (e) { }\n if (!cacheObj) {\n throw new Error(index_1.i18n.localize(\"actionhero.cache.objectNotFound\"));\n }\n if (cacheObj.expireTimestamp &&\n cacheObj.expireTimestamp < new Date().getTime()) {\n throw new Error(index_1.i18n.localize(\"actionhero.cache.objectExpired\"));\n }\n const lastReadAt = cacheObj.readAt;\n let expireTimeSeconds;\n cacheObj.readAt = new Date().getTime();\n if (cacheObj.expireTimestamp) {\n if (options.expireTimeMS) {\n cacheObj.expireTimestamp = new Date().getTime() + options.expireTimeMS;\n expireTimeSeconds = Math.ceil(options.expireTimeMS / 1000);\n }\n else {\n expireTimeSeconds = Math.floor((cacheObj.expireTimestamp - new Date().getTime()) / 1000);\n }\n }\n lockOk = await cache.checkLock(key, options.retry);\n if (lockOk !== true) {\n throw new Error(index_1.i18n.localize(\"actionhero.cache.objectLocked\"));\n }\n await client().set(cache.redisPrefix + key, JSON.stringify(cacheObj));\n if (expireTimeSeconds) {\n await client().expire(cache.redisPrefix + key, expireTimeSeconds);\n return {\n key,\n value: cacheObj.value,\n expireTimestamp: cacheObj.expireTimestamp,\n createdAt: cacheObj.createdAt,\n lastReadAt,\n };\n }\n else {\n return {\n key,\n value: cacheObj.value,\n expireTimestamp: cacheObj.expireTimestamp,\n createdAt: cacheObj.createdAt,\n lastReadAt,\n };\n }\n }", "function Reviver(key, value) {\n var ctor;\n\n if (typeof value === \"object\" &&\n typeof value.ctor === \"string\" &&\n typeof value.data !== \"undefined\") {\n ctor = Reviver.constructors[value.ctor] || window[value.ctor];\n \n if (typeof ctor === \"function\" &&\n typeof ctor.fromJSON === \"function\") {\n //console.log(\"In Reviver. Key: \" + key + \"value: \" + JSON.stringify(value) + \" \" + ctor);\n return ctor.fromJSON(value);\n }\n }\n return value;\n}", "loadValue (key, def) {\n const data = this.load()\n return data[key] === undefined ? def : data[key]\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add fields to the output clause
output (fields) { if ('string' === typeof fields) { this.outputs.push(`INSERTED.${this._sanitizeField(fields)}`); } else { fields.forEach((f) => { this.outputs.push(`INSERTED.${this._sanitizeField(f)}`); }); } }
[ "generateOutputFields(fields, level) {\n const {keysList} = this.state;\n return fields.map((field) => {\n let obj = {\n name: field.name || field.outputFieldName ,\n type: field.type || this.getReturnType(field.functionName, ProcessorUtils.getKeyList(field.args,keysList)),\n optional : false\n };\n\n if (field.type === 'NESTED' && field.fields) {\n obj.fields = this.generateOutputFields(field.fields, level + 1);\n }\n return obj;\n });\n }", "function appendResult(obj,res,fields){\n\t\t_.each(fields,function(field){\n\t\t\tobj[field] = res[field];\n\t\t})\n\t\tobj['id'] = res['_id'];\n\t}", "print() {\n for (let row of this._field){\n console.log(row.join(''));\n }\n }", "print() {\n return this.field.map(row =>\n row.join('')\n ).join('\\n');\n }", "function outputresults() {\n outputheader();\n // iterate through detail records\n for (j=0; j < detaildatalist.length; j++) {\n outputoneresult(detaildatalist[j]);\n }\n}", "get fields() {\n return [...this.ownFields, ...this.derivedFields];\n }", "function nlobjReportColumn() {\n}", "function formatOutput(output, passCols, targetVis) {\n\n\t\toutput = output.filter(function(d) {\n\t\t\treturn passCols[d.id];\n\t\t});\n\n\t\tvar criteria = d3.set(output.map(function(d) { return d.id; })).values(); // Get unique criteria IDs\n\n\t\t// Handle multiple values for a single criteria\n\t\tvar refactorOutput = [];\n\t\tcriteria.forEach(function(c) { // Reform output objects to use array of values\n\t\t\tvar criterion = output.filter(function(d) { return d.id == c; });\n\t\t\tvar values = criterion\n\t\t\t\t.filter(function(d) { return d.value; })\n\t\t\t\t.map(function(d) { return d.value; });\n\n\t\t\ttargetVis = targetVis || {};\n\n\t\t\t// Set target ID property, the property in the target column map that matches the input column code\n\t\t\tvar targetID;\n\t\t\tobiee.applyToColumnMap(targetVis.ColumnMap, function(col, colID) {\n\t\t\t\tif (col.Code == criterion[0].col.Code)\n\t\t\t\t\ttargetID = colID;\n\t\t\t});\n\n\t\t\tif (values.length > 0) {\n\t\t\t\trefactorOutput.push({\n\t\t\t\t\t'sourceId' : c,\n\t\t\t\t\t'targetId' : targetID,\n\t\t\t\t\t'col' : criterion[0].col,\n\t\t\t\t\t'values' : values,\n\t\t\t\t\t'config' : targetVis.Config,\n\t\t\t\t\t'columnMap' : targetVis.ColumnMap\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\toutput = refactorOutput;\n\t\treturn output;\n\t}", "print() {\n for(let row of this.field) {\n console.log(row.join(''))\n }\n }", "output () {\n this.toStdOut(this.table.toString(), true)\n }", "printField() {\n\t\tconst fieldString = this.field.map((row) => {\n\t\t\treturn row.join(\"\");\n\t\t});\n\t\tconst fieldArea = fieldString.join(\"\\n\");\n\t\tconsole.log(fieldArea);\n\t}", "addOutputExpression(index, output) {\n\t\tthis.expressions.push({\n\t\t\ttype: 'code',\n\t\t\tcontents: `output += ${this.finalizeOutput(index, output)}\\n`,\n\t\t\tindex: index,\n\t\t})\n\t}", "function getFields() {\n if (!json) {\n printToOutput(\"Select a CSV\");\n } else {\n let fieldOutput = \"\";\n json.columns.forEach(col => {\n fieldOutput += col + \"<br>\";\n });\n printToOutput(fieldOutput);\n }\n}", "function addendumOutput(output) {\n var newOutput = Object.assign({}, output);\n newOutput.summary.score = scoreResults(output);\n newOutput.summary.basicSupport = sumResults('basic support', output);\n newOutput.summary.advancedSupport = sumResults('advanced support', output);\n return newOutput;\n}", "toGql() {\n const type = `${(this.isExtend ? 'extend ' : '')}${this.type} ${this.name}`;\n const fieldKeys = Object.keys(this.fields);\n\n let tmp = `${type} {\\n<desc>\\n}\\n`;\n let desc = '';\n\n for (let i = 0; i < fieldKeys.length; i++) {\n const fieldName = fieldKeys[i];\n const fieldData = this.fields[fieldName];\n\n let fieldParams = '';\n const responseType = labelHelper(fieldData.responseType, fieldData);\n\n if (fieldData.params) {\n const { params } = fieldData;\n const paramsKeys = Object.keys(params);\n\n for (let j = 0; j < paramsKeys.length; j++) {\n const param = params[paramsKeys[j]];\n const paramType = param.type;\n const tmpParam = labelHelper(paramType.name || paramType, param);\n\n fieldParams += `${paramsKeys[j]}: ${tmpParam}`;\n fieldParams += `${((j !== paramsKeys.length - 1) && ', ') || ''}`;\n }\n }\n\n desc += ` ${fieldName}${fieldParams && `(${fieldParams})`}${(responseType && `: ${responseType}`) || ''}`;\n desc += `${((i !== fieldKeys.length - 1) && '\\n') || ''}`;\n }\n\n tmp = tmp.replace('<desc>', desc);\n return tmp;\n }", "function outputSPARQLResults(results) {\n for (row in results) {\n printedLine = '';\n for (column in results[row]) {\n printedLine = printedLine + results[row][column].value + ' '\n }\n console.log(printedLine)\n }\n}", "function generateSupplyCSV(){\n dbQuery(supplyRequest,supply)\n}", "function isOutputField(field) {\r\n if (field == 'none') {\r\n return false;\r\n }\r\n\r\n return true;\r\n}", "async provide (what) {\n let sql = `SELECT * FROM outputs.${what.name}`\n if (what.limit) sql += ` LIMIT ${what.limit}`\n let rows = this._db.prepare(sql).all()\n\n let data = {}\n if (rows.length > 0) {\n let fields = Object.keys(rows[0])\n\n for (let field of fields) {\n data[field] = []\n }\n for (let row of rows) {\n for (let field of fields) {\n data[field].push(row[field])\n }\n }\n }\n\n return this.pack({type: 'table', data})\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the right List price based on the Part No., Billing Country, Order Date, Quantity Billing Country, Order Date are defined globally Part No., Quantity are passed in as parameters on each line item call Returns : List price (currency( or null if not found
function getListPriceForItemQuantity(itemCode, quantity) { var returnListPriceObj = new Object(); returnListPriceObj.price = -1.00; returnListPriceObj.quantity = 0; returnListPriceObj.name = 'Not found'; var listPriceTrace = ''; var ItemCountryCode = itemCode + ':' + billingAddressCountryID; // Order UTC from midnight 1 Jan 1970 so we can numerically compare with list price dates var orderDateObj = nlapiStringToDate(orderDateNS); //var orderDateUTC = parseInt(Date.parse(orderDateNS)); var orderDateUTC = parseInt(orderDateObj.getTime()); //Item quantity calculations are based on Align's Item Type coding var itemPriceType = ''; // If the item is 'Q' the quantity var itemPriceDate = ''; // UTC of each price start date var itemPriceDateObj = new Object(); var itemPriceDateUTC = null; // UTC of each price start date var itemPrice = 0.00; var prevPriceDateUTC = 0; var itemQty = parseInt(quantity); var itemQtyPrice = 0; var itemQtyMin = 0; var itemQtyMax = 0; try { var searchPriceFilters = new Array(); var searchPriceColumns = new Array(); // searchPrice filter to identify the part no and country code price list // Note: Append ':' to country code to ensure country unique e.g. ES: is different from ES1: searchPriceFilters[0] = new nlobjSearchFilter('name', null, 'contains', ItemCountryCode + ":"); // return columns searchPriceColumns[0] = new nlobjSearchColumn('internalid'); searchPriceColumns[1] = new nlobjSearchColumn('externalid'); searchPriceColumns[2] = new nlobjSearchColumn('name'); searchPriceColumns[3] = new nlobjSearchColumn('custrecord_alignbv_price_country'); searchPriceColumns[4] = new nlobjSearchColumn('custrecord_alignbv_price_itemid'); searchPriceColumns[5] = new nlobjSearchColumn('custrecord_alignbv_pricestartdate'); searchPriceColumns[6] = new nlobjSearchColumn('custrecord_alignbv_price_type'); searchPriceColumns[7] = new nlobjSearchColumn('custrecord_alignbv_price_price'); searchPriceColumns[8] = new nlobjSearchColumn('custrecord_alignbv_price_min_qty'); searchPriceColumns[9] = new nlobjSearchColumn('custrecord_alignbv_price_max_qty'); // Sorting by name descending ensures the most recent // start date is the first in any list of prices searchPriceColumns[10] = searchPriceColumns[2].setSort(true); // perform searchPrice var searchPriceResults = nlapiSearchRecord('customrecord_alignbv_listprice', null, searchPriceFilters, searchPriceColumns); // Add criteria to trace listPriceTrace += '<tr><td>Criteria:</td><td>Part</td><td>' + itemCode + '</td><td>Country Code</td><td>' + ItemCountryCode + '</td><td>Quantity</td><td colspan="3">' + quantity + '</td><td>Date</td><td colspan="2">' + orderDateNS + '</td><td>orderDateUTC</td><td colspan="2">' + orderDateUTC + '</td></tr>'; if(searchPriceResults) { for (var lprice=0; lprice<searchPriceResults.length; lprice++) { var searchPriceResultRow = searchPriceResults[ lprice ]; itemPriceType = searchPriceResultRow.getValue('custrecord_alignbv_price_type'); // If the item is 'Q' the quantity itemQtyMin = parseInt(searchPriceResultRow.getValue('custrecord_alignbv_price_min_qty')); itemQtyMax = parseInt(searchPriceResultRow.getValue('custrecord_alignbv_price_max_qty')); itemPrice = searchPriceResultRow.getValue('custrecord_alignbv_price_price'); itemPriceDate = searchPriceResultRow.getValue('custrecord_alignbv_pricestartdate'); itemPriceDateObj = nlapiStringToDate(itemPriceDate); itemPriceDateUTC = parseInt(itemPriceDateObj.getTime()); //itemPriceDateUTC = parseInt(Date.parse(itemPriceDate)); listPriceTrace += '<tr><td>Row</td><td>' + lprice + '</td><td>itemPriceType</td><td>' + itemPriceType + '</td><td>itemQtyMin</td><td>' + itemQtyMin + '</td><td>itemQtyMax</td><td>' + itemQtyMax + '</td><td>itemPriceDate</td><td>' + itemPriceDate + '</td><td>itemPriceDateUTC</td><td>' + itemPriceDateUTC + '</td><td>prevPriceDateUTC</td><td>' + prevPriceDateUTC + '</td><td>itemPrice</td><td>' + itemPrice + '</td></tr>'; // Examine whether the pricing record matches the quantity and date bands parameters // Quantity is between Min and Max, order date on or after start date, and this start date on or after previous // if (itemQty >= itemQtyMin && itemQty <= itemQtyMax && orderDateUTC >= itemPriceDateUTC && prevPriceDateUTC <= itemPriceDateUTC){ if (itemQty >= itemQtyMin && itemQty <= itemQtyMax && orderDateUTC >= itemPriceDateUTC && prevPriceDateUTC == 0){ // If type == 'B' then ignore quantity simply set to 1 itemQtyPrice = itemQty; if (itemPriceType == 'B') itemQtyPrice = 1; returnListPriceObj.price = parseFloat(itemPrice); returnListPriceObj.quantity = itemQtyPrice; returnListPriceObj.name = searchPriceResultRow.getValue('name'); prevPriceDateUTC = itemPriceDateUTC; } } if (debugOn) nlapiLogExecution('DEBUG', "getListPriceForItemQuantity : " + returnListPriceObj.name, "QtyinTIBCOfeed=" + itemQty + " QtyforPrice=" + returnListPriceObj.quantity + " Price=" + returnListPriceObj.price); } } catch(e) { addToErrorsXML("getListPriceForItemQuantity : " + itemCode + " : " + quantity, e); } if (returnListPriceObj.price == -1.00) { listPriceTrace = "<table style='font-size: 3mm;'>" + listPriceTrace + "</table>" nlapiLogExecution('DEBUG', "getListPriceForItemQuantity : " + returnListPriceObj.name + " == null : Error trace table", listPriceTrace); } return returnListPriceObj; }
[ "function getCurrencySpecificPrice(itemId, priceLevel, currency, flContractListRate, flContractQty) {\n var MSG_TITLE = 'getCurrencySpecificPrice';\n nlapiLogExecution('DEBUG', MSG_TITLE, 'Start');\n nlapiLogExecution('DEBUG', MSG_TITLE, 'itemId: ' + itemId + ', priceLevel: ' + priceLevel +\n ', currency: ' + currency + ', flContractListRate: ' + flContractListRate +\n ', flContractQty: ' + flContractQty);\n\n var sFilters = new Array();\n sFilters.push(new nlobjSearchFilter('internalid', null, 'is', itemId));\n sFilters.push(new nlobjSearchFilter('pricelevel', 'pricing', 'is', (priceLevel < 1 ? 1 : priceLevel)));\n if (nlapiGetContext().getFeature('multicurrency')) {\n sFilters.push(new nlobjSearchFilter('currency', 'pricing', 'is', currency));\n }\n if (nlapiGetContext().getFeature('quantitypricing')) {\n nlapiLogExecution('DEBUG', MSG_TITLE, 'quantitypricing = true');\n sFilters.push(new nlobjSearchFilter('minimumquantity', 'pricing', 'lessthanorequalto', flContractQty));\n var sFilterA = new nlobjSearchFilter('maximumquantity', 'pricing', 'greaterthan', flContractQty);\n var sFilterB = new nlobjSearchFilter('maximumquantity', 'pricing', 'isempty');\n sFilterA.setOr(true);\n sFilterA.setLeftParens(1);\n sFilterB.setRightParens(1);\n sFilters.push(sFilterA);\n sFilters.push(sFilterB);\n }\n var sColumns = new Array();\n sColumns.push(new nlobjSearchColumn('unitprice', 'pricing', 'max'));\n sColumns.push(new nlobjSearchColumn('internalid', null, 'group'));\n var sResults = nlapiSearchRecord('item', null, sFilters, sColumns);\n var price = null;\n if (sResults != null) {\n price = sResults[0].getValue('unitprice', 'pricing', 'max');\n nlapiLogExecution('DEBUG', MSG_TITLE, 'price = ' + price);\n }\n\n if (SWE.Library.misc.isUndefinedNullOrEmpty(price) && nlapiGetContext().getFeature('multicurrency')) {\n var cFilters = new Array();\n cFilters.push(new nlobjSearchFilter('internalid', null, 'is', currency));\n var cColumns = new Array();\n cColumns.push(new nlobjSearchColumn('exchangerate'));\n var cResults = nlapiSearchRecord('currency', null, cFilters, cColumns);\n if (cResults != null) {\n var fxRate = parseFloatOrZero(cResults[0].getValue('exchangerate'));\n if (fxRate != 0) {\n price = flContractListRate / fxRate;\n }\n nlapiLogExecution('DEBUG', MSG_TITLE, 'fxRate = ' + fxRate);\n nlapiLogExecution('DEBUG', MSG_TITLE, 'flContractListRate = ' + flContractListRate);\n nlapiLogExecution('DEBUG', MSG_TITLE, 'price = ' + price);\n }\n }\n\n nlapiLogExecution('DEBUG', MSG_TITLE, 'End');\n return parseFloatOrZero(price);\n}", "function calculateListPriceItem(thisItem)\r\n{\r\n\t// The return price value\r\n\tvar returnListPriceItem = null;\r\n\t\r\n\tvar thisItemCode = null;\r\n\tvar thisItemQuantity = null;\r\n\tvar thisItemIsInvoiced = 'F';\r\n\tvar thisItemIsIgnored = 'F';\r\n\tvar thisItemTransferZeroOverride = 'F';\r\n\tvar itemObj = new Object();\r\n\t\r\n\t// Obtain the correct tax code and it's corresponding internal ID\r\n\tvar taxItem = getXMLTreeElementDatabyName(XMLVATCODE, thisItem); // From VAT answer\r\n\tif (taxItem != 'INT' && (taxItem == null || taxItem.indexOf('-') == -1))\r\n\t{\r\n\t\t// Default to INT if not a vaild code - during development use only !!!!\r\n\t\t//taxItem = 'INT';\r\n\t\taddToErrorsXML(\"calculateListPriceItem : \" + thisItem + \"/\" + itemsCount,\r\n\t\t\t\t\"Missing Tax Code in XML Answer\");\r\n\t\treturn returnListPriceItem;\r\n\t}\r\n\tvar taxItemID = genericSearch('salestaxitem', 'name', taxItem);\r\n\r\n\ttry\r\n\t{\r\n\t\t// Get the particular line item code / part no. from the XML nodes array\r\n\t\tthisItemCode = getXMLTreeElementDatabyName(XMLITEMCODE, thisItem);\r\n\t\tif (thisItemCode)\r\n\t\t{\r\n\t\t\t// Cross reference from the item id to the internal id and load item record\r\n\t\t\t// Take item values required for answer assembly and store in item(s) array\r\n\t\t\titemID = genericSearch('noninventoryitem', 'itemid', thisItemCode);\r\n\t\t\titemRecord = nlapiLoadRecord('noninventoryitem', itemID);\t\t\t\r\n\t\t\tif (itemRecord)\r\n\t\t\t{\t\r\n\t\t\t\t// Whether the item will be invoiced - if 'F' will create an estimate\r\n\t\t\t\t// / sales order line item but will not carry through to invoice\r\n\t\t\t\tthisItemIsInvoiced = itemRecord.getFieldValue('custitem_alignbv_to_invoice');\t\r\n\t\t\t\t// Whether the item will be ignored - if 'T' will not create a \r\n\t\t\t\t// sales order item but will create an estimate line item for audit purposes\r\n\t\t\t\tthisItemIsIgnored = itemRecord.getFieldValue('custitem_alignbv_ignore_on_salesorder');\t\r\n\t\t\t\tthisItemTransferZeroOverride = itemRecord.getFieldValue('custitem_alignbv_transferprice_zero');\t\r\n\t\t\t\t\r\n\t\t\t\t// The quantity supplied in the TIBCO feed record for this item\r\n\t\t\t\tthisItemQuantity = getXMLTreeElementDatabyName(XMLITEMQUANTITY, thisItem);\r\n\t\t\t\t\r\n\t\t\t\titemObj.invoiced = thisItemIsInvoiced;\r\n\t\t\t\titemObj.ignored = thisItemIsIgnored;\r\n\t\t\t\titemObj.internalid = itemID;\r\n\t\t\t\titemObj.itemid = thisItemCode;\r\n\t\t\t\titemObj.quantity = thisItemQuantity;\r\n\t\t\t\t// Deprecated during CRP1 - use local description, not one supplied via TIBCO\r\n\t\t\t\t// itemObj.description = getXMLTreeElementDatabyName(XMLITEMDESCRIPTION, thisItem);\r\n\t\t\t\titemObj.description = itemRecord.getFieldValue('displayname');\r\n\t\t\t\titemObj.taxcode = taxItemID; // From VAT answer\r\n\t\t\t\titemObj.family = itemRecord.getFieldValue('class');\r\n\t\t\t\titemObj.upperstage = getXMLTreeElementDatabyName(XMLITEMUPPERSTAGE, thisItem);\r\n\t\t\t\titemObj.lowerstage = getXMLTreeElementDatabyName(XMLITEMLOWERSTAGE, thisItem);\r\n\t\t\t\titemObj.zeropriceoverride = thisItemTransferZeroOverride;\r\n\t\t\t\titemObj.transferprice = getXMLTreeElementDatabyName(XMLITEMTRANSFERPRICE, thisItem);\t\t\t\r\n\t\t\t\r\n\t\t\t\t// See whether the transfer price is zero and the item override flag is T\r\n\t\t\t\t// If both true, set price to zero and skip pricing, and also if the item\r\n\t\t\t\t// Is not to be invoiced or ignored ...\r\n\t\t\t\tif ((thisItemTransferZeroOverride == 'T' && itemObj.transferprice == 0))\r\n\t\t\t\t{\r\n\t\t\t\t\titemObj.listprice = 0.00;\r\n\t\t\t\t\titemObj.pricequantity = thisItemQuantity;\t\r\n\t\t\t\t\treturnListPriceItem = 0.00;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n \t\t\t\t{\r\n\t\t\t\t\t// Work out the correct price for this product & quantity\r\n\t\t\t\t\t// (separate function)\r\n\t\t\t\t\t// Returns an object with the price / quantity to use on\r\n\t\t\t\t\t// Estimate / Order\r\n\t\t\t\t\t// Note : the quantity input may not match the value\r\n\t\t\t\t\t// returned based on Q/B type\r\n\t\t\t\t\tlistPriceItemObj = getListPriceForItemQuantity(\r\n\t\t\t\t\t\t\tthisItemCode, thisItemQuantity);\r\n\r\n\t\t\t\t\t// If return is -1 the price is not found\r\n\t\t\t\t\tif (listPriceItemObj.price != -1) {\r\n\t\t\t\t\t\titemObj.listprice = listPriceItemObj.price;\r\n\t\t\t\t\t\titemObj.pricequantity = listPriceItemObj.quantity;\r\n\t\t\t\t\t\treturnListPriceItem = listPriceItemObj.price;\r\n\t\t\t\t\t} \r\n\t\t\t\t\telse \r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t// If not to be invoiced / ignored, set to zero, otherwise an error\r\n\t\t\t\t\t\tif (thisItemIsInvoiced == 'F' || thisItemIsIgnored == 'T')\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\titemObj.listprice = 0.00;\r\n\t\t\t\t\t\t\titemObj.pricequantity = thisItemQuantity;\t\r\n\t\t\t\t\t\t\treturnListPriceItem = 0.00;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\titemObj.listprice = null;\r\n\t\t\t\t\t\t\taddToErrorsXML(\"calculateListPriceItem : \" + thisItem\r\n\t\t\t\t\t\t\t\t\t+ \"/\" + itemsCount,\r\n\t\t\t\t\t\t\t\t\t\"Missing List Price record for item : \"\r\n\t\t\t\t\t\t\t\t\t+ thisItemCode);\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n \t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\titemsArray[thisItem-1] = itemObj;\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\telse // Cannot find / load the NetSuite item\r\n\t\t\t{\r\n\t\t\t\taddToErrorsXML(\"calculateListPriceItem : \" + thisItem + \"/\"\r\n\t\t\t\t\t\t+ itemsCount, \"Missing Item Record : \" + itemID);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse // No XMLITEMCODE present\r\n\t\t{\r\n\t\t\taddToErrorsXML(\"calculateListPriceItem : \" + thisItem + \"/\"\r\n\t\t\t\t\t+ itemsCount, \"Missing XML data element : \" + XMLITEMCODE);\r\n\t\t}\r\n\r\n\t}\r\n\tcatch (e)\r\n\t{\r\n\t\taddToErrorsXML(\"calculateListPriceItem\", e);\r\n\t}\r\n\r\n\tif (debugOn)\r\n\t\tnlapiLogExecution('DEBUG', \"calculateListPriceItem(\" + thisItem + \"/\"\r\n\t\t\t\t+ itemsCount + \") ==> \" + returnListPriceItem,\r\n\t\t\t\t\"thisItemIsInvoiced=[\" + thisItemIsInvoiced + \"] ItemCode=[\" + thisItemCode + \"] taxItem=[\" + taxItem + \"] taxItemID=[\" + taxItemID + \"]\");\r\n\r\n\treturn returnListPriceItem;\r\n}", "get itemPriceFromList () { return this.productContainer.$('div.desktop-price-cart-btn>div.media-component>div.product-price-and-logo>div>div>span:nth-of-type(1)') }", "function lineValueAuto(_type)\n{\n\t//Below are list of known item types that can NOT have amount or price level values\n\tvar itemTypeToSkip = ['Description','Subtotal','EndGroup'],\n\t\tlinecnt = nlapiGetLineItemCount('item'),\n\t\terrorLog = '',\n\t\tipJson = {},\n\t\tiprs = null;\n\t\n\tif (_type == 'custprice')\n\t{\n\t\tvar setEntityId = nlapiGetFieldValue('entity');\n\t\tif (!setEntityId)\n\t\t{\n\t\t\talert('You must first set Client on the transaction');\n\t\t\treturn;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\t//Look it up\n\t\t\t//itempricinglevel\n\t\t\t//itempricingunitprice\n\t\t\t\n\t\t\t//Mod July 5th 2016 \n\t\t\t//\tIt's not the default price level, it must be looked at per item under item pricing\n\t\t\tvar ipflt = [new nlobjSearchFilter('internalid', null, 'anyof', setEntityId)],\n\t\t\t\tipcol = [new nlobjSearchColumn('pricingitem'),\n\t\t\t\t new nlobjSearchColumn('itempricinglevel'),\n\t\t\t\t new nlobjSearchColumn('itempricingunitprice')];\n\t\t\t\n\t\t\tiprs = nlapiSearchRecord('customer', null, ipflt, ipcol);\n\t\t\t\n\t\t\t//If Customer does NOT have item pricing set, return out\n\t\t\tif (!iprs)\n\t\t\t{\n\t\t\t\talert('Customer does NOT have item pricing');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t//Loop through and build ipJson\n\t\t\tfor (var ip=0; ip < iprs.length; ip+=1)\n\t\t\t{\n\t\t\t\tipJson[iprs[ip].getValue('pricingitem')] = {\n\t\t\t\t\t'pricelevel':iprs[ip].getValue('itempricinglevel'),\n\t\t\t\t\t'unitprice':iprs[ip].getValue('itempricingunitprice')\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t}\n\t\tcatch(luerr)\n\t\t{\n\t\t\talert(\n\t\t\t\t'Unable to dynamically look up customer item pricing\\n\\n'+\n\t\t\t\tgetErrText(luerr)\n\t\t\t);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t\t\n\t}\n\t\n\tfor (var i=1; i <= linecnt; i+=1)\n\t{\n\t\tif (itemTypeToSkip.contains(nlapiGetLineItemValue('item','itemtype',i)))\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tnlapiSelectLineItem('item', i);\n\t\t\n\t\tif (_type == 'zero')\n\t\t{\n\t\t\t//-1 is value of custom price\n\t\t\tnlapiSetCurrentLineItemValue('item','price','-1',true,true);\n\t\t\tnlapiSetCurrentLineItemValue('item','rate',0.0,true,true);\n\t\t\tnlapiCommitLineItem('item');\n\t\t}\n\t\telse if (_type == 'baseprice')\n\t\t{\n\t\t\t//Grab original values so that it can be reset if it fails\n\t\t\tvar oQty = nlapiGetCurrentLineItemValue('item','quantity'),\n\t\t\t\toRate = nlapiGetCurrentLineItemValue('item','rate'),\n\t\t\t\toAmount = nlapiGetCurrentLineItemValue('item','amount'),\n\t\t\t\toPrice = nlapiGetCurrentLineItemValue('item','price');\n\t\t\t\n\t\t\t//1 is value of baseprice\n\t\t\tnlapiSetCurrentLineItemValue('item','price','1',true,true);\n\t\t\t\n\t\t\t//There are some items that does NOT have option to set baseline.\n\t\t\t//For these, notify the user\n\t\t\tif (nlapiGetCurrentLineItemValue('item','price') != '1')\n\t\t\t{\n\t\t\t\terrorLog += 'Line '+i+' does not have Baseprice option.\\n';\n\t\t\t\t\n\t\t\t\t//Revert back to original\n\t\t\t\tnlapiSetCurrentLineItemValue('item','quantity',oQty,true,true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','price',oPrice,true,true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','rate',oRate,true,true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','amount',oAmount,true,true);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnlapiCommitLineItem('item');\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t//Ticket 11127 - Request to add Customer Price Level button\n\t\telse if (_type == 'custprice')\n\t\t{\n\t\t\t//pricelevel\n\t\t\t//Grab original values so that it can be reset if it fails\n\t\t\tvar ocQty = nlapiGetCurrentLineItemValue('item','quantity'),\n\t\t\t\tocRate = nlapiGetCurrentLineItemValue('item','rate'),\n\t\t\t\tocAmount = nlapiGetCurrentLineItemValue('item','amount'),\n\t\t\t\tocPrice = nlapiGetCurrentLineItemValue('item','price'),\n\t\t\t\tocItemText = nlapiGetCurrentLineItemText('item','item');\n\t\t\t\n\t\t\t//ipJson\n\t\t\t//If ipJson contains the Item, change the price level and rate\n\t\t\tif (ipJson[ocItemText])\n\t\t\t{\n\t\t\t\tnlapiSetCurrentLineItemText('item','price',ipJson[ocItemText].pricelevel,true, true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','rate', ipJson[ocItemText].unitprice, true, true);\n\t\t\t\tnlapiCommitLineItem('item');\n\t\t\t}\n\t\t\t\n\t\t\t//custPriceLevel\n\t\t\t/**\n\t\t\tnlapiSetCurrentLineItemValue('item','price',custPriceLevel,true,true);\n\t\t\t\n\t\t\t//There are some items that does NOT have option to set price level.\n\t\t\t//For these, notify the user\n\t\t\tif (nlapiGetCurrentLineItemValue('item','price') != custPriceLevel)\n\t\t\t{\n\t\t\t\terrorLog += 'Line '+i+' does not have customer price level option.\\n';\n\t\t\t\t\n\t\t\t\t//Revert back to original\n\t\t\t\tnlapiSetCurrentLineItemValue('item','quantity',ocQty,true,true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','price',ocPrice,true,true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','rate',ocRate,true,true);\n\t\t\t\tnlapiSetCurrentLineItemValue('item','amount',ocAmount,true,true);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnlapiCommitLineItem('item');\n\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\t\n\tif (errorLog)\n\t{\n\t\talert(\n\t\t\t'One or more line failed to process:\\n'+\n\t\t\terrorLog\n\t\t);\n\t}\n}", "preparePriceListItems(price) {\n let items = [];\n let itemsSrc = helpers.toArray(price.PriceListItems);\n itemsSrc.forEach((item) => {\n items.push({\n priority: item.priority,\n _timePeriod: this.catalog.timePeriods[item.TimePeriodId],\n quantity: item.Quantity,\n isTemplate: helpers.boolean(item.IsTemplate),\n unitPrice: item.UnitPrice\n });\n })\n return items;\n }", "function findPriceLevelInItemRecord(shippingDestination , stringToAdd, currencyIntID)\r\n{\r\n\tvar pricingSublistPriceLevelLineNo = 0;\r\n\tvar pricingSublistIntId = 0;\r\n\tvar itemPrice = 0;\r\n\tvar priceLevelIntID = 0;\r\n\tvar minimumShippingCost = 0;\r\n\tvar priceLevelName = '';\r\n\r\n\ttry\r\n\t{\r\n\t\t//making the price level name (Example : DE NET , DE NET inc Del)\r\n\t\tpriceLevelName = shippingDestination + ' ' + stringToAdd;\r\n\r\n\t\t//getting the internal id of the particular price level name \r\n\t\tpriceLevelIntID = genericSearch('pricelevel', 'name', priceLevelName);\r\n\r\n\r\n\t\t/**********************************************************\r\n\t\t * //making the internal id of the price level sublist\r\n\t\t * NOTE : The price level sublist's internal id has the format of the price2, price6;\r\n\t\t * where 2 and 6 are the internal ids of the currency which can be found in List > Accounting > Currencies \r\n\t\t *********************************************************/\r\n\t\tpricingSublistIntId = 'price' + currencyIntID;\r\n\r\n\r\n\t\t//searching and getting the line item no of the particular price level name in the particular pricing sublist\r\n\t\tpricingSublistPriceLevelLineNo = itemRecord.findLineItemValue(pricingSublistIntId, 'pricelevel', priceLevelIntID);\r\n\r\n\t\t//if the price level name found in the pricing sublist\r\n\t\tif(pricingSublistPriceLevelLineNo >0)\r\n\t\t{\r\n\t\t\t//if the price level is for normal prices (example : DE NET)\r\n\t\t\tif(stringToAdd == 'NET')\r\n\t\t\t{\r\n\t\t\t\titemPrice = calculateItemCost();\t\t\t\t\t//calling calculateItemCost function\r\n\r\n\t\t\t}\r\n\t\t\telse\t//if the price level is for delivery prices (example : DE NET inc Del)\r\n\t\t\t{\r\n\t\t\t\tminimumShippingCost = getPriceFromMetapack();\t\t\t\t\t\t\t//calling getPriceFromMetapack function\r\n\t\t\t\tnlapiLogExecution('audit', 'minimumShippingCost', minimumShippingCost);\r\n\r\n\t\t\t\tif(minimumShippingCost != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\titemPrice = calculateItemDelCost(minimumShippingCost);\t\t\t\t//callinng calculateItemDelCost function\r\n\t\t\t\t\tcreateShippingRecord(minimumShippingCost);\t\t\t\t\t\t\t\t\t\t//calling createShippingRecord function\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\r\n\t\t\t//calling setParticularPriceLevelValue function\r\n\t\t\tsetParticularPriceLevelValue(pricingSublistIntId,pricingSublistPriceLevelLineNo,itemPrice);\r\n\r\n\t\t}\r\n\r\n\t}\r\n\tcatch(e)\r\n\t{\r\n\t\terrorHandler('setParticularPriceLevelValue', e);\r\n\t}\r\n\r\n}", "function getItemPrice(stItemId, stPriceLevel)\r\n{\r\n if (stPriceLevel == '1')\r\n {\r\n return nlapiLookupField('item', stItemId, 'baseprice');\r\n }\r\n else\r\n {\r\n var arrRateFilters = [\r\n new nlobjSearchFilter('internalid', null, 'is', stItemId)\r\n ];\r\n\r\n var arrRateColumns = [\r\n new nlobjSearchColumn('otherprices')\r\n ];\r\n\r\n var arrRateResults = nlapiSearchRecord('item', null, arrRateFilters, arrRateColumns);\r\n \r\n return arrRateResults[0].getValue('price' + stPriceLevel); \r\n } \r\n}", "function getDataPrice() {\n getPlans(myCoordinate).then((doc) => {\n setCard(shortedPrice(myCoordinate, doc.data.list));\n });\n }", "function getProductGridPrices() {\n\tvar POP = \"value-add\";\n\tvar dr_pid =\"\";\n\tvar stx_store = false;\n\tvar dr_locale = \"\";\n\tvar ecomm_currency = \"\";\n\tvar ecomm_locale = getEcommLocale();\n\tif (ecomm_locale !=\"\"){ \n\t\tstx_store = true;\n\t} else { \n\t\treturn;\n\t}\n\tfor (i = 0; i < ecommLocaleMap.ecommLocalesList.length; i++) {\n\t\tif (ecommLocaleMap.ecommLocalesList[i].ecommLocale == ecomm_locale){\n\t\t\tdr_locale = ecommLocaleMap.ecommLocalesList[i].drLocale;\n\t\t\tecomm_currency = ecommLocaleMap.ecommLocalesList[i].currency;\n\t\t}\n\t}\n\t// cache the pricing div and pid for all \"sku\" items that have them\n\tvar productGridItems = [];\n\t$('.teaser-product-grid-item-pid').each( function(i) {\n\t\tproductGridItem = {};\n\t\tproductGridItem.div = $(this).parent();\n\t\tproductGridItem.pid = $(this).val();\n\t\tproductGridItems.push(productGridItem);\n\t});\n\t\n\tif (productGridItems.length > 0) {\n\t\t// build list of pids\n\t\tvar productGridPids = [];\n\t\tfor (var i = 0; i < productGridItems.length; i++) {\n\t\t\tif(productGridItems[i].pid.length > 0){\n\t\t\t\tproductGridPids.push(productGridItems[i].pid);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// get data from dr and update page. Assumes all \"sku\" items have a valid pid.\n\t\tif (productGridPids.length > 0) {\n\t\t\tvar drURL = \"/ww/jsp/common/drproduct.jsp?drProductId=\" + productGridPids +'&drLocale=' + dr_locale + '&currency=' + ecomm_currency;\n\t\t\t$.getJSON (drURL, function(data) {\n\t\t\t\tfor (var j = 0; j < productGridItems.length; j++) {\n\t\t\t\t\tvar storeProduct = getStoreProduct(productGridItems[j].pid, data.storeProduct);\n\t\t\t\t\tif (storeProduct != null) {\n\t\t\t\t\t\tif(storeProduct.price != storeProduct.discountedPrice) {\n\t\t\t\t\t\t\t// if on sale\n\t\t\t\t\t\t\t$(productGridItems[j].div).append(\"<div class='price-discount-message'>\" + labels.sale + \"</div><div class='price-discount'>\" + storeProduct.discountedPrice + \"</div><div class='price sale'>\" + storeProduct.price + \"</div>\");\t\t\t\t\t\t\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(productGridItems[j].div).append(\"<div class='price'>\" + storeProduct.price + \"</div>\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t \t\t$('.teaser-product-grid').find('.teaser-product-grid-item-pid').each( function() {\n\t \t\t\tdr_pid = $(this).attr('value');\n\t \t\t\t$(this).parents('div.teaser-product-grid-item').find('a.teaser-product-grid-item-button').attr('href', 'http://shop.seagate.com/store/sgateus/' + dr_locale + '/buy/productID.' + dr_pid + '/quantity.1/Currency.' + ecomm_currency);\t\n\t \t\t});\n\t\t}\n\t}\n}", "function getPrices(){\n\n\t\t//cost of shop items\n\t\tprice1=75.00; price2=116; price3=44; price4=5.25; price5=3.75; price6=12.75; price7=4.10;\n\n\t\t//ammount of items chosen\n\t\titem_1=0; item2=0; item3=0; item4=0; item5=0; item6=0; item6=0; item7=0;\n\n\t\t//sub-total for each item\n\t\tsubTot_1 = 0; subTot_2=0; subTot_3=0; subTot_4=0; subTot_5=0; subTot_6=0; subTot_7=0;\n\n\t\t//get number of items\n\t\titem_1 = document.getElementById(\"item_1\").value;\n\t\titem_2 = document.getElementById(\"item_2\").value;\n\t\titem_3 = document.getElementById(\"item_3\").value;\n\t\titem_4 = document.getElementById(\"item_4\").value;\n\t\titem_5 = document.getElementById(\"item_5\").value;\n\t\titem_6 = document.getElementById(\"item_6\").value;\n\t\titem_7 = document.getElementById(\"item_7\").value;\n\n\n\t\t//subtotal for item\n\t\tsubTot_1 = eval(item_1) * eval(price1);\n\t\tsubTot_1 = subTot_1.toFixed(2);\n\t\tdocument.getElementById(\"subTot_1\").value = subTot_1;\n\n\t\t//subtotal for item 2\n\t\tsubTot_2 = eval(item_2) * eval(price2);\n\t\tsubTot_2 = subTot_2.toFixed(2);\n\t\tdocument.getElementById(\"subTot_2\").value = subTot_2;\n\n\t\t//subtotal for item 3\n\t\tsubTot_3 = eval(item_3) * eval(price3);\n\t\tsubTot_3 = subTot_3.toFixed(2);\n\t\tdocument.getElementById(\"subTot_3\").value = subTot_3;\n\n\t\t//subtotal for item 4\n\t\tsubTot_4 = eval(item_4) * eval(price4);\n\t\tsubTot_4 = subTot_4.toFixed(2);\n\t\tdocument.getElementById(\"subTot_4\").value = subTot_4;\n\n\t\t//subtotal for item 5\n\t\tsubTot_5 = eval(item_5) * eval(price5);\n\t\tsubTot_5 = subTot_5.toFixed(2);\n\t\tdocument.getElementById(\"subTot_5\").value = subTot_5;\n\n\t\t//subtotal for item 6\n\t\tsubTot_6 = eval(item_6) * eval(price6);\n\t\tsubTot_6 = subTot_6.toFixed(2);\n\t\tdocument.getElementById(\"subTot_6\").value = subTot_6;\n\n\t\t//subtotal for item 7\n\t\tsubTot_7 = eval(item_7) * eval(price7);\n\t\tsubTot_7 = subTot_7.toFixed(2);\n\t\tdocument.getElementById(\"subTot_7\").value = subTot_7;\n\n\t\t//work out total for all items\n\t\tTotamt = eval(subTot_1)+eval(subTot_2)+eval(subTot_3)+eval(subTot_4)+eval(subTot_5)+eval(subTot_6)+eval(subTot_7);\n\t\tTotamt = Totamt.toFixed(2);\n\t\tdocument.getElementById(\"GrandTotal\").value = Totamt;\n\n}//end getPrices", "_getListPrice(listPrice) {\n return listPrice ? listPrice['ns2:Amount'] : 'UNKNOWN';\n }", "function listPriceEngine()\r\n{\r\n\r\n\t// First attempt to load this custom record's XML payload into order\r\n\torderNumber = loadXMLTreefromSalesOrderPayload();\r\n\r\n\t// If we have an order number can try to process the items and find prices\r\n\tif (orderNumber)\r\n\t{\r\n\t\t\r\n\t\t// set up all order related values ready for processing\r\n\t\tinitialise();\r\n\r\n\t\t// Take each line item in turn and derive the list price\r\n\t\tfor ( var thisItem = 1; thisItem <= itemsCount; thisItem++)\r\n\t\t{\r\n\t\t\tvar thisListPrice = calculateListPriceItem(thisItem);\r\n\t\t\t// Add the list price returned to the XML answer if it is present\r\n\t\t\t// If not, report an error - even a list price of 0.00 should be present\r\n\t\t\tif (thisListPrice != null)\r\n\t\t\t{\r\n\t\t\t\taddListPriceItemtoXMLAnswer(thisItem, thisListPrice);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\taddToErrorsXML(\"listPriceEngine : \" + orderNumber, \"Item No. \" + thisItem + \"/\" + itemsCount\r\n\t\t\t\t\t\t+ \" : Missing List Price\");\r\n\t\t\t}\r\n\t\t}\t\r\n\t\t\r\n\t\t// Assemble the final answer and post into the record\r\n\t\tcompleteXMLAnswer();\r\n\t\t\r\n\t\t// Create the estimate record which will trigger the discounts process\r\n\t\t// But only if there are no errors in generating the item(s) ...\r\n\t\t// Write out the XML answer and new estimate id if present\r\n\t\tif (XMLErrors == '')\r\n\t\t{\r\n\t\t\testimateID = saveDiscountCalcEstimate();\r\n\t\t\tsaveSalesOrderPriceListXMLPayload();\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}\r\n}", "get itemDetailElementPrice() { return $('div.product-details-wrapper>div.product-info>div.product-price>div.product-price-and-logo>div>div>div.price>span:nth-of-type(1)')}", "getProductListPrice() {\n return cy.get('[data-cel-widget^=\"MAIN-SEARCH_RESULTS\"] .a-price:first');\n }", "function getPrice(sectionList, id, size) {\n\n for (var i of window[sectionList]) {\n if (i.id == id) {\n let price = 0;\n if (size == \"Small\") {\n price = i.smallPrice.toFixed(2);\n return price;\n } else if (size == \"Large\") {\n price = i.largePrice.toFixed(2);\n return price;\n } else {\n price = i.price.toFixed(2);\n return price;\n }\n }\n }\n return 'Error';\n}", "function calcPrice(part) {\n var markup,\n cost = part.costPrice,\n quantity = part.quantity,\n matrix = part.matrix;\n if (matrix === 'tire' || part.tire) {\n markup = 1.25;\n } else if (matrix === 'dealer' || part.dealer) {\n if (cost <= 1) {\n markup = 3.5;\n } else if (cost > 1 && cost <= 5) {\n markup = 3.25;\n } else if (cost > 5 && cost < 50) {\n markup = 2.25;\n } else if (cost > 50 && cost <= 100) {\n markup = 1.82;\n } else if (cost > 100 && cost <= 175) {\n markup = 1.67;\n } else {\n markup = 1.54;\n }\n } else {\n if (cost <= 5) {\n markup = 3.25;\n } else if (cost > 5 && cost <= 10) {\n markup = 2.5;\n } else if (cost > 10 && cost <= 75) {\n markup = 2.25;\n } else if (cost > 75 && cost <= 150) {\n markup = 2;\n } else if (cost > 150 && cost <= 750) {\n markup = 1.85;\n } else {\n markup = 1.54;\n }\n }\n return markup * cost * quantity;\n }", "function populateItemPriceArray(){\n var customer_id = parseInt(currentRecord.get().getValue({fieldId: 'custpage_customer_id'}));\n var customer_record = record.load({\n type: record.Type.CUSTOMER,\n id: customer_id,\n isDynamic: true\n });\n var zeeLocation = record.load({\n type: record.Type.PARTNER,\n id: customer_record.getValue({fieldId:'partner'}),\n isDynamic: true\n }).getValue({fieldId: 'location'});\n\n //Search: SMC - Services\n var searched_jobs = search.load({\n type: 'customrecord_service',\n id: 'customsearch_smc_services'\n });\n searched_jobs.filters.push(search.createFilter({\n name: 'custrecord_service_customer',\n join: null,\n operator: search.Operator.IS,\n values: parseInt(currentRecord.get().getValue({fieldId: 'custpage_customer_id' }))\n }));\n\n searched_jobs.run().each(function(searchResult){\n var item_description = searchResult.getValue({name: 'custrecord_service_description'});\n\n if (isNullorEmpty(item_description)) {\n item_description = 0;\n } else {\n item_description = item_description.replace(/\\s+/g, '-').toLowerCase()\n }\n if (item_price_array[searchResult.getValue({name: 'custrecord_service'})] == undefined) {\n item_price_array[searchResult.getValue({name: 'custrecord_service'})] = [];\n item_price_array[searchResult.getValue({name: 'custrecord_service'})][0] = searchResult.getValue({name: 'custrecord_service_price'}) + '_' + item_description;\n } else {\n var size = item_price_array[searchResult.getValue({name:'custrecord_service'})].length;\n item_price_array[searchResult.getValue({name:'custrecord_service'})][size] = searchResult.getValue({name:'custrecord_service_price'}) + '_' + item_description;\n }\n \n item_price_count++;\n return true;\n });\n console.log(item_price_array);\n }", "function getCpmEstPriceResult(filterColumn,item_id){\n \n var internalidColumn = search.createColumn({\n \t name: 'internalid',\n \t sort: search.Sort.ASC\n });\n \n if((hasCustomerValue == '' && volumePricing == '') || (hasCustomerValue && volumePricing == '')){\n\t log.debug('itemID '+item_id, hasCustomerValue)\n \t cpmEstimationPriceFilters = [\n \t ['custrecord_cpm_est_price_forcustomer','is',hasCustomerValue],'and',\n \t filterColumn,'and',\n \t ['isinactive','is',false],'and',\n \t ['custrecord_cpm_est_price_item','is',item_id],'and',\n \t ['custrecord_cpm_est_price_format','is',cpmEst_format_id],'and',\n \t ['custrecord_cpm_est_price_printer','is',printJob_vendorAwrd],'and',\n \t ['custrecord_cpm_est_price_forvolume','is',volumePricing],'and',\n \t [[['custrecord_cpm_est_price_qtyfloor','isempty',null],'and',\n \t ['custrecord_cpm_est_price_qtycap','isempty',null]],'or',\n \t [['custrecord_cpm_est_price_qtyfloor','equalto',0],'and',\n \t ['custrecord_cpm_est_price_qtycap','equalto',0]]\n \t ]\n \t];\n \t \n }else{\n \t cpmEstimationPriceFilters = [\n \t ['custrecord_cpm_est_price_forcustomer','is',hasCustomerValue],'and',\n \t filterColumn,'and',\n \t ['isinactive','is',false],'and',\n \t ['custrecord_cpm_est_price_item','is',item_id],'and',\n \t ['custrecord_cpm_est_price_format','is',cpmEst_format_id],'and',\n \t ['custrecord_cpm_est_price_printer','is',printJob_vendorAwrd],'and',\n \t ['custrecord_cpm_est_price_forvolume','is',volumePricing],'and',\n \t ['custrecord_cpm_est_price_qtyfloor','isnotempty',null],'and',\n \t ['custrecord_cpm_est_price_qtycap','isnotempty',null],'and',\n \t ['custrecord_cpm_est_price_qtyfloor','lessthanorequalto',quantity],'and',\n \t ['custrecord_cpm_est_price_qtycap','greaterthanorequalto',quantity]\n \t];\n }\n \n cpmEstimationPriceColumn = [internalidColumn,'custrecord_cpm_est_price_itemprice','custrecord_cpm_est_price_unit','custrecord_cpm_est_cost_markup']\n\n return printJobModule.getcpmEstimationPrice(cpmEstimationPriceColumn,cpmEstimationPriceFilters);\n\n }", "_find_price (id) {\n let price;\n for(let el of this.data.products) {\n for(let item of el.goods) {\n if (item.id === Number(id)) {\n return parseFloat(item.price)\n }\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an object with issued property containing the issued event and transferEvents property if issued property is set and kard has transferred before
getKardHistory(kardId) { console.log("Getting kard history for kardId: " + kardId); let node = 'kard_store_node'; //TODO: change me maybe? might not hard code this in future let config = Promise.all(this.getConfig(node)); return config.then( response => { let web3 = response[0]; let contract = response[1]; console.log("Getting past events: IssueKard"); return contract.getPastEvents('IssueKard', {fromBlock: 0, filter: {kardId: kardId}}).then((issuedEvent) => { let response = {}; if (issuedEvent && issuedEvent.length) { response.issued = issuedEvent; // if the kard has been issued then we need to get the addresses and any transfer events return this.getAddress('user_node').then((userAddress) => { response.userAddress = userAddress; return this.getAddress('joe_node').then((joeAddress) => { response.joeAddress = joeAddress; console.log("Getting past events: Transfer"); return contract.getPastEvents('Transfer', { fromBlock: 0, filter: {kardId: kardId} }).then((transferEvents) => { response.transferEvents = transferEvents; return response; }); }); }); } else { console.log("Kard has not been issued!"); return response } }); }); }
[ "get issued () {\n\t\treturn this._issued;\n\t}", "lockupEvents () {\n return this.contract.events.Transfer({\n filter: {\"_to\": this.lockupAccountPk }\n });\n }", "diff() {\n this.update();\n if (!this.actionQueue.length) {\n return null;\n }\n const event = {\n actions: this.actionQueue,\n seq: this.sequenceNumber++\n };\n if (this.isStarting) {\n event.event = 'new';\n this.isStarting = false;\n this.lastResetTime = Date.now();\n }\n else if (this.isReset) {\n event.event = 'reset';\n this.isReset = false;\n }\n this.actionQueue = [];\n return event;\n }", "lockupEventsOnce () {\n return new Promise((resolve, reject) => {\n this.contract.once('Transfer', {\n filter: { \"_to\" : this.lockupAccountPk }\n }, (err, e) => err ? reject(err) : resolve(e));\n });\n }", "get isDelivered() {\n return this._rawEvent.event === 'delivered';\n }", "get signedExchangeReceived() {\n return this._signedExchangeReceived;\n }", "getEventsSent() {\n return this.eventsSent;\n }", "get preCheckout() {\n return this._rawEvent.pre_checkout || null;\n }", "getCreatedEvents() {\n if (!this.contract) {\n return;\n }\n // Search the contract events for the hash in the event logs and show matching events.\n this.contract.getPastEvents(\n \"DeviceCreated\",\n {\n filter: { _from: this.coinbase },\n fromBlock: 0,\n toBlock: \"latest\"\n },\n (error, events) => {\n for (let i = 0; i < events.length; i++) {\n var eventObj = events[i];\n // console.log(\n // `Created: ${eventObj.returnValues.name}`,\n // eventObj.returnValues\n // );\n }\n }\n );\n }", "get isDelivery() {\n return !!this._rawEvent.delivery && typeof this._rawEvent.delivery === 'object';\n }", "get delivery() {\n return this.isDelivery ? this._rawEvent.delivery : null;\n }", "constructor(\n deposit /* : Deposit*/,\n redemptionDetails /* : RedemptionDetails?*/\n ) {\n this.deposit = deposit\n this.withdrawnEmitter = new EventEmitter()\n\n this.redemptionDetails = this.getLatestRedemptionDetails(redemptionDetails)\n\n this.unsignedTransactionDetails = this.redemptionDetails.then(details => {\n const outputValue = details.utxoSize.sub(details.requestedFee)\n const unsignedTransaction = BitcoinHelpers.Transaction.constructOneInputOneOutputWitnessTransaction(\n details.outpoint.replace(\"0x\", \"\"),\n // We set sequence to `0` to be able to replace by fee. It reflects\n // bitcoin-spv:\n // https://github.com/summa-tx/bitcoin-spv/blob/2a9d594d9b14080bdbff2a899c16ffbf40d62eef/solidity/contracts/CheckBitcoinSigs.sol#L154\n 0,\n outputValue.toNumber(),\n EthereumHelpers.bytesToRaw(details.redeemerOutputScript)\n )\n\n return {\n hex: unsignedTransaction,\n digest: details.digest\n }\n })\n\n this.signedTransaction = this.unsignedTransactionDetails.then(\n async unsignedTransactionDetails => {\n console.debug(\n `Looking up latest redemption details for deposit ` +\n `${this.deposit.address}...`\n )\n const redemptionDigest = (await this.redemptionDetails).digest\n\n console.debug(\n `Finding or waiting for transaction signature for deposit ` +\n `${this.deposit.address}...`\n )\n const signatureEvent = await EthereumHelpers.getEvent(\n this.deposit.keepContract,\n \"SignatureSubmitted\",\n { digest: redemptionDigest }\n )\n const { r, s, recoveryID } = signatureEvent.returnValues\n const publicKeyPoint = await this.deposit.publicKeyPoint\n\n // If needed, submit redemption signature to the deposit.\n if (\n (await this.deposit.getCurrentState()) !=\n this.deposit.factory.State.AWAITING_WITHDRAWAL_PROOF\n ) {\n // A constant in the Ethereum ECDSA signature scheme, used for public key recovery [1]\n // Value is inherited from Bitcoin's Electrum wallet [2]\n // [1] https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v/38909#38909\n // [2] https://github.com/ethereum/EIPs/issues/155#issuecomment-253810938\n const ETHEREUM_ECDSA_RECOVERY_V = toBN(27)\n const v = toBN(recoveryID).add(ETHEREUM_ECDSA_RECOVERY_V)\n\n await EthereumHelpers.sendSafely(\n this.deposit.contract.methods.provideRedemptionSignature(\n v.toString(),\n r.toString(),\n s.toString()\n )\n )\n }\n\n const signedTransaction = BitcoinHelpers.Transaction.addWitnessSignature(\n unsignedTransactionDetails.hex,\n 0,\n r.replace(\"0x\", \"\"),\n s.replace(\"0x\", \"\"),\n BitcoinHelpers.publicKeyPointToPublicKeyString(\n publicKeyPoint.x,\n publicKeyPoint.y\n )\n )\n\n return signedTransaction\n }\n )\n }", "checkDepositEvents() {\n\n // Process existing deposit contract deposit events\n this.depositContract.getPastEvents('DepositEvent', {fromBlock: 0}).then((events) => {\n events.forEach(event => {\n if (!this.processedDepositEvents[event.id]) {\n this.processedDepositEvents[event.id] = true;\n this.processDepositEvent(event);\n }\n });\n });\n\n }", "needsToAcknowledge(state){\n // return state.appointment_history.find((appointment)=>{\n // if(appointment.acknowledgement_data.signature===null && appointment.transaction_status !== 'expired')\n // return appointment;\n // });\n return undefined;\n }", "get payment() {\n return this._rawEvent.payment || null;\n }", "get preCheckout(): ?PreCheckout {\n return this._rawEvent.pre_checkout || null;\n }", "get initiatedByMe() {\n // event created by us but no remote echo has been received yet\n const noEventsYet = this.eventsByUs.size + this.eventsByThem.size === 0;\n\n if (this._phase === PHASE_UNSENT && noEventsYet) {\n return true;\n }\n\n const hasMyRequest = this.eventsByUs.has(REQUEST_TYPE);\n const hasTheirRequest = this.eventsByThem.has(REQUEST_TYPE);\n\n if (hasMyRequest && !hasTheirRequest) {\n return true;\n }\n\n if (!hasMyRequest && hasTheirRequest) {\n return false;\n }\n\n const hasMyStart = this.eventsByUs.has(START_TYPE);\n const hasTheirStart = this.eventsByThem.has(START_TYPE);\n\n if (hasMyStart && !hasTheirStart) {\n return true;\n }\n\n return false;\n }", "get initiatedByMe() {\n // event created by us but no remote echo has been received yet\n const noEventsYet = this._eventsByUs.size + this._eventsByThem.size === 0;\n\n if (this._phase === PHASE_UNSENT && noEventsYet) {\n return true;\n }\n\n const hasMyRequest = this._eventsByUs.has(REQUEST_TYPE);\n\n const hasTheirRequest = this._eventsByThem.has(REQUEST_TYPE);\n\n if (hasMyRequest && !hasTheirRequest) {\n return true;\n }\n\n if (!hasMyRequest && hasTheirRequest) {\n return false;\n }\n\n const hasMyStart = this._eventsByUs.has(START_TYPE);\n\n const hasTheirStart = this._eventsByThem.has(START_TYPE);\n\n if (hasMyStart && !hasTheirStart) {\n return true;\n }\n\n return false;\n }", "get isDelivery(): boolean {\n return (\n !!this._rawEvent.delivery && typeof this._rawEvent.delivery === 'object'\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return true if midnight (local time) has passed since data was last fetched
function getShouldFetchNewMovieData() { if (!_gLastMovieDataFetchDate) { return true; } // getDate() returns day of month as number var midnightHasPassedSinceLastFetch = (new Date().getDate() != _gLastMovieDataFetchDate.getDate()); return midnightHasPassedSinceLastFetch; }
[ "function isCurrent(fetchTime: number, ttl: number): boolean {\n return fetchTime + ttl >= Date.now();\n}", "function isCurrent(fetchTime, ttl) {\n return fetchTime + ttl >= Date.now();\n}", "function timeToUpdate(){\n let lastUpdate = Number(sessionStorage.getItem(constants.LATESTUPDATE_STORAGE));\n let interval = 300000;\n\n if (Date.now() > lastUpdate + interval){\n return true\n }\n return false;\n }", "function timeToRefreshCache() {\r\n\t\tif (minutesSincePoll() < MINUTES_BETWEEN_GET_ALL) {\r\n\t\t\tGML('no refresh because cache is from current hour');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (hitAgeInSeconds() < 60) {\r\n\t\t\tGML('no refresh because double-fetch');\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}", "function shouldFetchNewData() {\n return !lastFetchedAt || ((new Date().getTime() - lastFetchedAt) > fetchNewTweetsInterval);\n}", "function isMinTimeToFetchElapsed() {\n const minTimeToFetch = 600000; // 10 min in milli-sec\n\n let d = new Date();\n const currentEpochTime = d.getTime();\n\n if ( (currentEpochTime - (lastEpochApiFetch * 1000) ) > minTimeToFetch ||\n lastZipUsed !== document.getElementById('zip').value ) {\n return true;\n } else { \n return false\n }\n}", "function isWithinTtl(nowTime,lastFetchTime,ttl){if(nowTime-lastFetchTime<ttl){return true;}return false;}", "function refreshNeeded() {\n\n\tif (localStorage[\"timestamp\"] != undefined) {\n\t\tvar input_date = parseInt(localStorage[\"timestamp\"]);\n\n\t\tvar d = new Date();\n\t\tvar curr_date = d.getTime();\n\t\tvar last_hour = curr_date - 3600000;\n\n\t\tif (input_date - last_hour < 0) {\n\t\t\treturn true;\n\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t} else {\n\t\treturn false;\n\t}\n}", "check_timestamp() {\n return Date.now() > this.timestamp;\n }", "hasNotExpired(now,entry){return !isNaN(now)&&!isNaN(entry.lastFetchTime)&&now-entry.lastFetchTime<RECORD_ACTIONS_TTL;}", "function checkLiveWithCurrentTime(casterName) {\n var timeslots = checkLiveInTimetable(casterName, this.todayTimetable);\n if(timeslots.length == 0) {\n return false;\n }\n var liveHour = parseInt(timeslots[0].time.substring(0, 2), 10);\n var currentHour = getCurrentTimeFromTimezone('+9').getHours();\n return (currentHour >= liveHour && currentHour < liveHour+3);\n}", "hasNotExpired(now,entry){return !isNaN(now)&&!isNaN(entry.lastFetchTime)&&now-entry.lastFetchTime<LOOKUP_ACTIONS_TTL;}", "function checkOldData() {\n // get the dataDate\n let dataDate = window.localStorage.getItem(\"dataDate\");\n\n if (dataDate == null) {\n return true;\n } else {\n let now = new Date();\n let lsDate = new Date(dataDate * 1000);\n console.log(\"Time in local storage is:\", lsDate);\n let diff = Math.round((now - lsDate) / 1000);\n console.log(`Difference is ${diff} seconds...`);\n if (diff > 20) {\n console.log(\"Data is old, fetch again...\");\n return true;\n }\n console.log(\"All is ok, data is fresh.\");\n return false;\n }\n}", "function check_if_maplestory_daily_reset() {\n const current_utc_hour = new Date().getUTCHours();\n\n // 0 for UTC Midnight (00:00)\n if (current_utc_hour === 0) {\n return true;\n }\n\n return false;\n}", "hasNotExpired(now,entry){return !isNaN(now)&&!isNaN(entry.lastFetchTime)&&now-entry.lastFetchTime<RECORD_EDIT_ACTIONS_TTL;}", "function localStorageIsOutdated(){\r\n let data = localStorage.getItem(\"lastUpdated\");\r\n\r\n if(data == null) {\r\n return true;\r\n }\r\n\r\n let now = Date.now();\r\n let timelimit = 1000 * 60 * 60; //1 hour\r\n\r\n if(now - data < timelimit){\r\n //Less than timelimit has passed (1 hour)\r\n console.log('less than 1 hour');\r\n addMessage('Getting cached data. Data is ' + Math.round((now-data) / (1000 * 60)) + ' minutes old');\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n }", "checkTime() {\n\t\tif (this.currentTime >= 99) {\n\t\t\treturn true;\n\t\t}\n\t}", "isAvailable () {\n const lessThanOneHourAgo = (date) => {\n const HOUR = 1000 * 60 * 60;\n const anHourAgo = Date.now() - HOUR;\n\n return date > anHourAgo;\n }\n\n return this.socket !== null || (this.lastSeen !== null && lessThanOneHourAgo(this.lastSeen))\n }", "function hasOneDayPassed() {\n // get today's date. eg: \"7/37/2007\"\n var date = new Date().toLocaleDateString();\n\n // if there's a date in localstorage and it's equal to the above: \n // inferring a day has yet to pass since both dates are equal.\n if (localStorage.koaTrackDate == date)\n return false;\n\n // this portion of logic occurs when a day has passed\n localStorage.koaTrackDate = date;\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method to check the token object for legal tokens. IN: checkToken, a string to be looked up in the object. OUT: the token as string if it is in the table, otherwise return undefined.
_checkSymbol(checkToken) { for (let token in this._validTokens) { if (token == this.match(checkToken)) { return token; } } return undefined; }
[ "function checkToken (token) {\n return true\n }", "function checkToken (token) {\n return true;\n }", "checkExceptions(checkToken) {\n for (var token in this.reservedTokens) {\n if (this.reservedTokens[token] == checkToken) {\n return token;\n }\n }\n return undefined;\n }", "function verifyToken( ) {\n\n }", "function isTokenValid(token, callbackFunction){\r\n\t//base case: don't allow null tokens... ever!\r\n\tvar response = {};\r\n\tif(token == \"\" || token == undefined){\r\n\t\tresponse = { \"error\":\"Invalid token provided\" };\r\n\t\tcallbackFunction( response );\r\n\t\treturn;\r\n\t}\r\n\t//db setup..\r\n\tclientIn = new pg.Client(connectionString); \r\n\tclientIn.connect();\r\n\tconsole.log(\"DB Connected with port: \" + port);\r\n\tvar queryTokenValid = clientIn.query(\"SELECT userid, username FROM users WHERE token = $1;\", [token]);\r\n\tqueryTokenValid.on(\"row\", function(row){\r\n\t\tresponse = {\"user\": row.username};\r\n\t\tcallbackFunction( response );\r\n\t});\r\n\tqueryTokenValid.on(\"end\", function(result){ \r\n\t\tif(result.rowCount < 1){\r\n\t\t\tconsole.log(\"Invalid token provided: \"+ token);\t\t//comes up when someone provides a token that is not recognized.\r\n\t\t\tresponse = { \"error\":\"Invalid token provided\" };\r\n\t\t\tcallbackFunction( response );\r\n\t\t}\t\t\t\r\n\t\tclientIn.end(); \r\n\t});\r\n\tqueryTokenValid.on(\"error\", function(error){\r\n\t\tconsole.log(\"Error looking up token: \" + error);\r\n\t\tclientIn.end();\r\n\t\tresponse = { \"error\":\"database error\" };\r\n\t\tcallbackFunction( response );\r\n\t});\r\n}", "function verifyToken(token)\n {\n return !!token;\n }", "function checkExistence(token) {\n\tToken.find({\"token\": token}).then(async function(res) {\n\t\t// if returns a match\n\t\t// randomize\n\n\t\tif (res && res.length) {\n\t\t\tconsole.log(\"Token: \" + token + \" already exists\".red);\n\t\t\t\n\t\t\t// \n\t\t\tif (program.request) await sendRequest(token);\n\n\t\t\t// \n\t\t\tif (program.recursive) randomize();\n\t\t\t\n\t\t\treturn;\n\t\t\t// otherwise sendRequest or saveToken\n\t\t} else {\n\t\t\tif (program.save) {\n\t\t\t\tsaveToken.call(this, token, \"checking\");\n\t\t\t\tif (program.recursive) randomize();\n\t\t\t\tif (program.request) await sendRequest(token);\n\t\t\t} else {\n\t\t\t\tif (program.request) await sendRequest(token);\n\t\t\t\tif (program.recursive) randomize();\n\t\t\t}\n\t\t}\n\t});\n}", "function checkSafe(array, token) {\n if (array.includes(BASE_SYMBOL) || array.includes(SAFE[token])) {\n return SAFE[token];\n }\n\n return DANGER[token];\n }", "function tokenExists() {\n // Retrieves the token\n const token = getToken();\n\n // Return true boolean value\n if (!stringContains(token, \"token=;\") || \n token != \"\" || token != null)\n return true;\n\n // Return opposite\n return false;\n}", "validateToken(token) {\n return true;\n }", "function checkState(token) {\n var state = token.state,\n\t\t\tstr = token.string,\n\t\t\ttokenStartExpr = /\\[\\[/,\n\t\t\ttokenExpr = /\\[\\[(\\w+):?/,\n\t\t\tfullTokenExpr = /\\[\\[(\\w+):(\\w+)(\\]\\])?/,\n\t\t\tisTokenStart = false,\n\t\t\ttokenBase = false,\t\t\t\n\t\t\t/* Get last instance of [[ */\n\t\t\ttokenFrags = str.split(\"[[\"),\n\t\t\ttokenFragSize = tokenFrags.length;\t\t\t\n\t\t\tstr = \"[[\" + tokenFrags[ tokenFragSize - 1 ];\n\t\t\t\n\t\t/* Test last instance to see if there is already a token and prop in the string */\n\t\ttry{\n\t\t\t/* If there is already a token and prop just return token */\n\t\t\tif ( ( str.match(fullTokenExpr).length > 3 ) && !state.type ){\t\t\t\t\t\t\n\t\t\t\treturn token;\n\t\t\t} \n\t\t} catch(e){}\t\n\t\t\t\t\t\t\t\n\t\t\t\n if (!state.type) {\n /* Test for openToken brackets ( [[ ) */\n isTokenStart = str.match(tokenStartExpr);\n /* Test for tokenBase ( [[TokeName: ) */\n try {\n tokenBase = tokenExpr.exec(str)[1];\n } catch (e) { }\n }\n if (isTokenStart && !tokenBase) {\n state.type = 'openToken';\n }\n if (tokenBase) {\n state.type = 'tokenBase'\n state.tokenName = tokenBase;\n }\n token.state = state;\n\t\t\n return token;\n }", "async function checkToken(token, userid) {\n let query = `SELECT * FROM public.tokens t\n WHERE token = '${token}' and user_id = '${userid}'`;\n let response = db.select(query);\n if (response) {\n return true;\n } else {\n return false;\n }\n}", "function checkToken(token, success, unauth, error) {\r\n asyncRequest('HEAD', 'CheckToken', { Token: token }, null, { success: success, 401: unauth, error: error }, true);\r\n }", "function checkToken(url, urlObj) {\r\n var ret = true;\r\n var tokenUrlPathes = [urlDefault, urlUpload, \".html\", \".htm\", \".stl\"];\r\n if (!urlObj) {\r\n urlObj = urlParser.parse(url, true);\r\n } \r\n var urlPath = urlObj[\"pathname\"];\r\n\r\n for (var i=0; i < tokenUrlPathes.length; i++) {\r\n var pos = urlPath.lastIndexOf(tokenUrlPathes[i]);\r\n //console.log(\">>> token pos = \" + pos);\r\n if (pos >= 0 && pos == (urlPath.length - tokenUrlPathes[i].length)) {\r\n if (!(\"query\" in urlObj && \"token\" in urlObj[\"query\"])) {\r\n ret = false;\r\n }\r\n break;\r\n } \r\n }\r\n console.log(\">>> check token result = \" + ret);\r\n return ret;\r\n}", "function isTokenValid(token) {\n return db\n .collection('lists')\n .where('token', '==', token)\n .get()\n .then((querySnapshot) => {\n // if there are results and an id property exists\n if (!querySnapshot.empty && 'id' in querySnapshot.docs[0]) {\n return querySnapshot.docs[0].id; // return the listId if it exists\n // check metadata.fromCache to distinguish between no results (invalid token) and a connection issue\n } else if (!querySnapshot.metadata.fromCache) {\n return false;\n } else {\n throw new Error('Connection problem');\n }\n });\n }", "function checkCurrentToken() {\n try {\n let token = getCurrentToken();\n let claims = JSON.parse(atob(token.split('.')[1]));\n\n if (token) {\n if ((token ? claims.exp : 0) > Date.now()) {\n handleValidToken(claims);\n } else {\n handleExpiredToken();\n }\n } else {\n handleNoToken();\n }\n } catch (err) {\n handleNoToken();\n }\n }", "function checkToken(token) {\n return telegramBotRequest(token, 'getMe');\n}", "function verifyToken(){\n \n}", "function findToken(word) {\n\n let result\n \n // short flag {-x, -xy}\n result = word.match(SHORTTOKEN)\n if (result) {\n\n if (word == result[result.index])\n return { type: TT_shortflag, value: word } \n else\n throw `illegal short flag ${word}`\n }\n\n result = word.match(LONGTOKEN)\n if (result) {\n\n if (word == result[result.index])\n return { type: TT_longflag, value: word }\n else\n throw `illegal long flag ${word}`\n }\n\n // argument to a flag -s Account\n result = word.match(ARG)\n if (result) {\n\n if (word == result[result.index]) \n return { type: TT_argument, value: word }\n else\n throw `syntax error illegal argument ${word}`\n }\n\n throw `undefined token ${word}`\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Highlight all multiples of the given divisor in the table
function highlight_multiples(divisor) { $('td').each(function() { if ($(this).data('value') % divisor == 0) { $(this).addClass('highlight'); } }); }
[ "formatPrime(x, y){\n\t\tvar cell = this.tbl.rows[y].cells[x]\n\t\tif(this.primes.includes(parseInt(cell.innerHTML))){\n\t\t\tcell.style.backgroundColor = \"blue\"\n\t\t\tcell.style.color = \"white\"\n\t\t}\n\t}", "function displayNumbers(numbers){\n let templateRows = \"\";\n for (let index = 0; index < numbers.length; index++) {\n\n let number = numbers[index];\n if (number % 2==0) {\n //This does not render correctly with Prism, see source code\n templateRows += `<tr><td><b>${number}</b></td></tr>` \n }\n else{\n templateRows += `<tr><td>${number}</td></tr>` \n }\n \n }\n document.getElementById(\"results\").innerHTML = templateRows;\n}", "function colorHighlightAvg(currentValue, arrayOfValues) {\r\n if (currentValue > 1.2 * avg(arrayOfValues)) {\r\n renderEl('td', currentValue);\r\n element.className = 'red';\r\n } else if (currentValue < 0.8 * avg(arrayOfValues)){\r\n renderEl('td', currentValue);\r\n element.className = 'green';\r\n } else {\r\n renderEl('td', currentValue);\r\n element.className = 'yellow';\r\n }\r\n}", "function colorTableCells() {\n $('tr').each(function() {\n // Get maximum value in this row\n var factor = 0.0;\n $(this).find('td').each(function() {\n var val = parseFloat($(this).text());\n if (!isNaN(val) && !isEqual(val, 1.0)) {\n factor = Math.max(factor, val);\n }\n });\n\n // Color cells according to this maximum\n $(this).find('td').each(function() {\n var val = parseFloat($(this).text()), color;\n if (!isNaN(val)) {\n val = Math.min(val / factor, 1.0) * 100;\n color = \"rgb(*%,-%,0%)\".replace(/\\*/g, val).replace(/-/g, 100 - val);\n $(this).css('color', color);\n }\n });\n });\n }", "function multiplesOf() {\r\n\r\n\r\n for (var i = 1; i <= 100; i++) {\r\n\r\n if (i % 3 === 0 && i % 5 === 0) { \r\n console.log(\"FizzBuzz\");\r\n\r\n } else if (i % 3 === 0) {\r\n console.log(\"Fizz\");\r\n\r\n } else if (i % 5 === 0) {\r\n console.log(\"Buzz\");\r\n\r\n } else {\r\n console.log(i);\r\n\r\n }\r\n }\r\n}", "function numMultiAndDivi(num){ \n for(let i = 1; i <= num; i++){ \n if( (i * 3) % 2 !== 0 ){ \n console.log(i) \n } \n } \n}", "function multiplicyTable(numberMult)\n{\n\tvar strTable = \"\\n\";\n\tfor(var i =1; i<=10;i++)\n\t{\n\t\tstrTable += i*numberMult + \"\\n\";\n\t}\n\treturn strTable;\n}", "function drawTable() {\n const bpmValue = parseInt(bpm.value)\n const groupValue = parseInt(groups.options[groups.selectedIndex].value) \n const start = bpmValue - 10\n const end = bpmValue + 10 \n\n table.querySelector('tbody').innerHTML = ''\n\n for (let i = start; i <= end; i++) {\n let tr = document.createElement('tr')\n \n for (let j = 2; j <= 11; j++) {\n let td = document.createElement('td') \n td.innerText = (i * groupValue / j).toFixed(3)\n \n if (j === groupValue || i === bpmValue) {\n td.style.backgroundColor = 'skyblue'\n td.style.color = 'white'\n }\n \n tr.appendChild(td)\n }\n\n table.querySelector('tbody').appendChild(tr)\n }\n}", "function multiTable() {\n for(let i = 1; i <= 5; i++)\n {\n for(let j = 1 ; j <= 5 ; j++)\n {\n console.log(i + \" x \" + j + \" = \" + (i * j))\n }\n }\n}", "function divisible(){\n\tfor (var i = 1; i <=100; i++) {\n\t\tif (i%5==0 && i%10==0){\n\t\t\tconsole.log(\"Coding Dojo\");\n\t\t} else if (i%5==0){\n\t\t\tconsole.log(\"Coding\");\n\t\t}\n\t\telse {\n\t\t\tconsole.log(i);\n\t\t}\n\t};\n}", "function divisor_match( divisor_array, low, high){\n\n\tfor (var i = low; i <= high ;i++ ) {\n\t\t\n\t\tif (i % divisor_array[0] === 0 && i % divisor_array[1] === 0){\n\t\t\t console.log( i + \" all_match\");\n\t\t\t }\n\t\telse if (i % divisor_array[0] === 0 || i % divisor_array[1] === 0 ){\n\t\t\tconsole.log(i + \" one_match\");\n\t\t}\n\t\t\n\t\telse {\n\t\t\tconsole.log(i);\n\t\t}\t \n\n\t}\n\n}", "function showMultiples(num, numMultiple){\n var prtOut, retVal = \"\";\n var sum, mult = 1;\n\n \n \n for(var i=0; i < numMultiple; i++){\n sum = num * mult;\n prtOut = (\"\\n\" + (num) + \" x \" + (mult) + \" = \" + sum);\n \n retVal += prtOut;\n mult++; \n }\n \n return retVal;\n}", "highlightCell(remaining, number, colour) {\n $('#' + remaining + '-remaining').addClass(colour);\n $('#' + remaining + '-' + number + '-sticks').addClass(colour);\n }", "function reduce(a,b){\n\tvar n = Math.floor(a/b);\n\tvar newNumerator = a - n*b;\n\n\tdocument.getElementById(\"red_number\").innerHTML = n;\n \tdocument.getElementById(\"red_numerator2\").innerHTML = newNumerator;\n \tdocument.getElementById(\"red_denominator2\").innerHTML = b;\n\n}", "function div5 (n1,n2,n3,n4,n5) {\n testNum = n1,n2,n3,n4,n5\n if (testNum%3 === 0){\n alert(\"Lincoln\")\n }\n}", "function multiplesOfThreeAndFive() {\n for(var i = 1; i <= 100; i++) {\n if (i % 15 === 0) {\n console.log(i.toString() + '!');\n } else if (i % 3 === 0 || i % 5 === 0) {\n console.log(i);\n }\n }\n}", "function highlightSquare(){\r\n\tcell.style.color = \"blue\";\r\n\t}", "function drawDividers(){\n noStroke();\n fill('GRAY');\n let buff = 2; // buffer\n let len = tc.length;\n for(let x = 1; x < algos.length; ++x){\n let o = buff + len;\n rect( (o*x + x-1) * CELL_SIZE, 0, CELL_SIZE/2, HEIGHT);\n }\n}", "function drawSymbolicRows(height) {\n\n for (var i = 1; i <= height; i++) {\n\n if (i % 3 === 0 && i % 2 !== 0) {\n\n console.log('baris-' + i + ' *' );\n\n } else if (i % 2 !== 0) {\n\n console.log('baris-' + i + ' @' )\n\n } else {\n\n console.log('baris-' + i + ' $' )\n\n }\n\n }\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the default project for new time entries
function setDefaultProject() { e.preventDefault(); alert('Set default project'); }
[ "function newDefaultProject() {\n const defaultProject = Project(\"Create a repo\", \"Steps to create new git repository\");\n\n defaultProject.addTodo(\n \"Create a new folder\", \n \"Open your terminal and \\\n enter the command 'mkdir new_project'\",\n \"Normal\",\n \"false\"\n\n );\n\n defaultProject.addTodo(\n \"Initialize the repo\", \n \"Enter the command 'git init'\",\n \"Normal\",\n \"false\"\n );\n\n // Use project's name as key and the formated project as value for serialization\n projectsJSON[defaultProject.getName()] = defaultProject.asJSON();\n \n // Save the default project as JSON in local storage\n save(projectsJSON);\n \n // Add the project to projects array\n projects.push(defaultProject);\n }", "updateTodayProject() {\n this.getProject('Today').tasks = []\n\n this.projects.forEach((project) => {\n if (project.getName() === 'Today' || project.getName() === 'This week')\n return\n\n const todayTasks = project.getTasksToday()\n todayTasks.forEach((task) => {\n const taskName = `${task.getName()} (${project.getName()})`\n this.getProject('Today').addTask(new Task(taskName, task.getDate()))\n })\n })\n }", "function initDefaultProject() {\n // No viable project available, so redirect to index page.\n // Create a default project and press forward\n // window.location.href = 'index.html' + getAllUrlParameters();\n // TODO: New Default Project\n const defaultProject = buildDefaultProject();\n const myProject = setProjectInitialState(defaultProject);\n\n // Update the terminal serial port baud rate\n if (myProject) {\n clientService.setTerminalBaudRate(myProject.boardType.baudrate);\n }\n\n // Create an instance of the CodeEditor class\n codeEditor = new CodeEditor(defaultProject.boardType.name);\n if (!codeEditor) {\n console.log('Error allocating CodeEditor object');\n }\n setupWorkspace(defaultProject);\n propToolbarButtonController();\n}", "setBlankProject(projectName) {\n // Create blank project (deep copy clone) and name\n this.project = null;\n this.project = JSON.parse(JSON.stringify(Project));\n this.project.name = projectName;\n // Add single category\n // Set 1st category weight to 100 to maintain consistency with entry verification\n this.addCategory(\"\", 100);\n\n }", "function resetToDefault() {\r\n\t\t\r\n\t\t// Default time for arrival and departure\r\n\t\t$scope.schedule.scheduledArrival = new Date();\r\n\t\t$scope.schedule.scheduledDeparture = new Date();\r\n\t\t\r\n\t\t$scope.schedule.arrivalTime = createDateTime($filter('date')(new Date($scope.schedule.scheduledArrival), 'yyyy-MM-dd'), '08:00 AM');\r\n\t\t$scope.schedule.departureTime = createDateTime($filter('date')(new Date($scope.schedule.scheduledArrival), 'yyyy-MM-dd'), '05:00 PM');\r\n\t\t\r\n\t\t// set default host as the current user if in the current list\r\n\t\tangular.forEach($scope.schedule.hosts, function(hostItem){\r\n\t\t\t\r\n\t\t\tif(hostItem.id == $scope.user.sso) {\r\n\t\t\t\t$scope.schedule.host = hostItem;\r\n\t\t\t}\r\n\t\t});\r\n\t}", "createDefaultProjectConfig() {\n const configKeys = Object.keys(this.config);\n const userSettings = Config.loadUserSettings(configKeys).user;\n Config.createDefaultProjectConfig(AtomUtils.getProjectPaths(), userSettings);\n }", "static updateTodayProject() {\n const todoList = Storage.getTodoList()\n todoList.updateTodayProject()\n Storage.saveTodoList(todoList)\n }", "function getDefaultProject(req) {\n return {\n title: req.body.title,\n author: req.session.email,\n authorId: req.session.id,\n created: new Date().getTime()\n };\n}", "function Project() {}", "updateWeekProject() {\n this.getProject('This week').tasks = []\n\n this.projects.forEach((project) => {\n if (project.getName() === 'Today' || project.getName() === 'This week')\n return\n\n const weekTasks = project.getTasksThisWeek()\n weekTasks.forEach((task) => {\n const taskName = `${task.getName()} (${project.getName()})`\n this.getProject('This week').addTask(new Task(taskName, task.getDate()))\n })\n })\n\n this.getProject('This week').setTasks(\n this.getProject('This week')\n .getTasks()\n .sort((taskA, taskB) =>\n compareAsc(\n toDate(new Date(taskA.getDateFormatted())),\n toDate(new Date(taskB.getDateFormatted()))\n )\n )\n )\n }", "setCurrentProject(project) {\n actions.setCurrentProject(project);\n }", "updateWeekProject() {\n this.getProject('This Week').tasks = [];\n\n this.projects.forEach((project) => {\n if (project.getName() === 'Today' || project.getName() === 'This Week') return;\n\n const weekTasks = project.getTasksThisWeek();\n weekTasks.forEach((task) => {\n const taskName = `${task.getName()} (${project.getName()})`;\n this.getProject('This Week').addTask(new Task(taskName, task.getDate()));\n });\n });\n\n // also sorts this weeks tasks in ascending order\n this.getProject('This Week')\n .setTasks(this.getProject('This Week')\n .getTasks()\n .sort((a, b) =>\n compareAsc(\n toDate(new Date(a.getDateFormated())),\n toDate(new Date(b.getDateFormated())),\n ),\n ),\n );\n }", "@action StartNewEntry(ProjectId){\n\n const NewEntryId = this.parent.entryStore.AddEntryProject(ProjectId);\n this.entryId = NewEntryId;\n this.parent.projectStore.currentProjectId = ProjectId;\n this.switchEntry(true);\n\n }", "static updateWeekProject() {\n const todoList = Storage.getTodoList()\n todoList.updateWeekProject()\n Storage.saveTodoList(todoList)\n }", "function initProject(){\n\t\t\t$clearConsole();\n\t\t\t$('#project-name').val($defaultFileName) ;\n\t\t\tinitCode();\n\t\t}", "function getDefaultProjectSetup() {\n return {\n useSessionCookie: false,\n anonymizeIp: true,\n userId: null,\n clientId: null,\n autoLink: [],\n sendInitialPageView: true,\n autoTrack: {\n cleanUrlTracker: {\n stripQuery: true,\n queryDimensionIndex: 1,\n indexFilename: 'index.html',\n trailingSlash: 'remove',\n },\n urlChangeTracker: true,\n },\n };\n}", "function setNextProject() {\n projects[currentTemplate].isDisplayed = false;\n\n if (loc < (projectKeys.length - 1)) currentTemplate = projects[projectKeys[loc + 1]].templateName;\n else currentTemplate = projects[projectKeys[0]].templateName;\n\n projects[currentTemplate].isDisplayed = true;\n loc = projectKeys.indexOf(projects[currentTemplate].templateName);\n loadProjectPage();\n}", "async addProjectTimeEntry(input = { projectId: '0' }) {\n\n return await this.request({\n name: 'project.time.add',\n args: [input.projectId],\n params: {\n 'time-entry': input['time-entry']\n }\n });\n\n }", "function prepareProjects() {\n var newProject = {\n id: 'new_project',\n name: $i18next.t('functions:NEW_PROJECT', { lng: lng })\n };\n\n ctrl.selectedProject = lodash.isNil(ctrl.selectedProject) ? newProject : ctrl.selectedProject;\n\n ctrl.projectsList = lodash.chain(ctrl.projects).map(function (project) {\n return {\n id: project.metadata.name,\n name: lodash.defaultTo(project.spec.displayName, project.metadata.name)\n };\n }).sortBy(['name']).value();\n\n ctrl.selectedProject = lodash.isEmpty(ctrl.projectsList) ? newProject : ctrl.selectedProject.id !== 'new_project' ? ctrl.selectedProject :\n /* else */lodash.first(ctrl.projectsList);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets all calendars for this location and save to calendars collection.
async function populateCalendars(location) { log(`--- Populating calendars for location ${location} on airbnb --- `); let currentDate = new Date(); currentDate.setDate(currentDate.getDate() + 1); // Airbnb allows accessing a listing's calender only up to 3 months in the past; // (I added one day extra to account for time zone offsets and daylight savings) const threeMonthsAgo = currentDate.setMonth(currentDate.getMonth() - 3); const threeMonthsAgoDateObj = new Date(threeMonthsAgo); const threeMonthsAgoFormatted = dateFormat(threeMonthsAgo, "yyyy-m-d"); const threeMonthsAgoPlusYearFormatted = dateFormat(threeMonthsAgoDateObj.setFullYear(threeMonthsAgoDateObj.getFullYear() + 1), "yyyy-m-d"); const opts = { clientId: consts.CLIENT_ID, startDate: threeMonthsAgoFormatted, endDate: threeMonthsAgoPlusYearFormatted } try { const listingsArr = await RawListing.find({'airbnb-demand-location': location}).lean(); const calendarsSize = await getCalendars(listingsArr, opts, location); log(`${calendarsSize} listing calendards for ${location} were saved to database.`); } catch (err) { error('encountered error populating calendars', err); } }
[ "async getCalendars() {\n const resp = await Q.nfcall(gcal.calendarList.list, {\n auth: this.oauth.client\n });\n const data = resp[0];\n return data.items;\n }", "function listCalendars(){\n let request = gapi.client.calendar.calendarList.list();\n\n request.execute(function(resp){\n let calendars = resp.items;\n });\n}", "function get_calendars(request, callback) {\n\t\t\t\t// executes the api request\n\t\t\t\trequest.execute(function(resp){\n\t\t\t\t\tvar calendars = resp.items;\n\t\t\t\t\tcallback(calendars);\n\t\t\t\t}); \n\t\t\t}", "function getMyCalendars() {\n \n var myCalendars = CalendarApp.getAllOwnedCalendars();\n \n // Cycles through my calendars and gets name and ID\n myCalendars.forEach(function(cal) {\n \n var calName = cal.getName();\n var calId = cal.getId();\n Logger.log(calName + \": \" + calId);\n \n });\n}", "function listCalendars() {\n var calendars;\n var pageToken;\n do {\n calendars = Calendar.CalendarList.list({\n maxResults: 100,\n pageToken: pageToken\n });\n if (calendars.items && calendars.items.length > 0) {\n for (var i = 0; i < calendars.items.length; i++) {\n var calendar = calendars.items[i];\n Logger.log('%s (ID: %s)', calendar.summary, calendar.id);\n }\n } else {\n Logger.log('No calendars found.');\n }\n pageToken = calendars.nextPageToken;\n } while (pageToken);\n}", "function listCalendars() {\n var calendars, pageToken;\n do {\n calendars = Calendar.CalendarList.list({\n maxResults: 100,\n pageToken: pageToken\n });\n if (calendars.items && calendars.items.length > 0) {\n for (var i = 0; i < calendars.items.length; i++) {\n var calendar = calendars.items[i];\n Logger.log('%s (ID: %s)', calendar.summary, calendar.id);\n }\n } else {\n Logger.log('No calendars found.');\n }\n pageToken = calendars.nextPageToken;\n } while (pageToken);\n}", "function populateCalendars( itcb ) {\n var i, binderCalendar, mergedCalendars;\n for( i = 0; i < data.length; i++ ) {\n mergedCalendars = [];\n if( 'string' === typeof data[i].calendar ) {\n binderCalendar = findCalendar( data[i].calendar );\n data[i].calendar = binderCalendar ? binderCalendar : calNotFound;\n data[i].calendarNames = binderCalendar ? [binderCalendar._id.name] : [calNotFound];\n }\n if( Array.isArray( data[i].calendar ) ) { // for merged appointments with resources\n data[i].calendar.forEach( function( id ) { // eslint-disable-line no-loop-func\n binderCalendar = findCalendar( id );\n if( !mergedCalendars.find( function( item ) {\n return item._id._id === id;\n } ) ) {\n mergedCalendars.push( binderCalendar ? binderCalendar : calNotFound );\n }\n } );\n data[i].calendar = mergedCalendars[0];\n data[i].calendarNames = mergedCalendars.map( function( item ) {\n return item._id.name;\n } );\n }\n }\n itcb( null );\n }", "function saveCalendarList() {\n var container = CALENDAR_LIST;\n var rows = $(container).find('.content');\n\n var calendars = getCalendarsFromRows(rows);\n\n $.post('/save-calendars', {\n calendars: JSON.stringify(calendars)\n }, function() {\n $(MY_CALENDARS_POPUP).foundation('reveal', 'close');\n location.reload();\n });\n}", "onAllNamesButtonClicked() {\n let reader = new SpawnReader();\n let command = [\"gcalendar\", \"--output\", \"txt\", \"--list-calendars\"];\n this.addAccountID(command, this.gcalendarAccount);\n // List of calendars already selected by user:\n let registeredCalendarNames = this.calendarName.toString().split(\",\");\n // List of all the user's calendars:\n var calendars = []; // We will populate it !\n this.calendarNames = [];\n reader.spawn(HOME_PATH, command, (output) => {\n let names = output.toString().trim().split(/\\r?\\n/);\n names.forEach((name) => {\n let display = (registeredCalendarNames.indexOf(name) > -1);\n calendars.push({\n name,\n display\n });\n });\n this.calendarNames = calendars; // Refreshes the array in Settings.\n });\n }", "function populateCalendars( itcb ) {\n let i, binderCalendar, mergedCalendars;\n for( i = 0; i < data.length; i++ ) {\n\n //combined field, for now without patient part\n data[i].patTitle = data[i].title;\n\n mergedCalendars = [];\n if( 'string' === typeof data[i].calendar ) {\n binderCalendar = findCalendar( data[i].calendar );\n data[i].calendar = binderCalendar ? binderCalendar : calNotFound;\n data[i].calendarNames = binderCalendar ? [binderCalendar._id.name] : [calNotFound];\n }\n if( Array.isArray( data[i].calendar ) ) { // for merged appointments with resources\n data[i].calendar.forEach( function( id ) { // eslint-disable-line no-loop-func\n binderCalendar = findCalendar( id );\n if( !mergedCalendars.find( function( item ) { return item._id._id === id; } ) ) {\n mergedCalendars.push( binderCalendar ? binderCalendar : calNotFound );\n }\n } );\n data[i].calendar = mergedCalendars[0];\n data[i].calendarNames = mergedCalendars.map( function( item ) { return item._id.name; } );\n }\n }\n itcb( null );\n }", "async function getAppointmentsForAllLocations() {}", "async function getCalendars(listingsArray, opts) {\n let calendarSaveCounter = 0;\n for (let listing of listingsArray) {\n let response;\n opts.listingId = listing['listing']['id'];\n let url = buildCalendarUrl(opts);\n log(`getting calendar for listing_id ${opts.listingId}\\n`, url + '\\n');\n try {\n response = await httpRequest(url);\n } catch (err) {\n error(`getCalendars encountered error, skipping calendar for listing id ${opts.listingId}`, err);\n continue;\n }\n response['listing_id'] = listing['listing']['id']; // augment the calendar object with the listingId\n \n let occupancyScore = _.sumBy(response.calendar_days, o => { //count number of unavailable days overall\n if (o.available) { return 0; } \n else { return 1; }\n });\n\n response['occupancyScore'] = occupancyScore;\n try {\n await Calendar.findOneAndUpdate({listing_id: opts.listingId}, response, {upsert: true}); //avoids creating duplicates\n calendarSaveCounter++;\n } catch (err) {\n error(`getCalendars encountered error while saving calendar for listing_id ${opts.listindId} to database.`, err);\n }\n };\n log(`total calendar data set size: ${calendarSaveCounter}`);\n return calendarSaveCounter;\n}", "function listCalendars()\n{\n var request = gapi.client.calendar.calendarList.list();\n\n request.execute(function(resp){\n var calendars = resp.items;\n console.log(calendars);\n calendarId = calendars[0].id;\n console.log(calendars[0].id);\n });\n}", "function fetchEventsForCalendar(calendar) {\n googleCalendar.events.list(Object.assign({\n calendarId: calendar.id,\n timeMin: (new Date()).toISOString()\n }, googleCalendarConfig), function(error, response) {\n utils.log(`Response for calendar ${calendar.id} (${calendar.name})`, 'blue');\n state[calendar.id].lastUpdated = response.headers.date;\n state[calendar.id].events = error ? null : response.data.items;\n if (error) {\n utils.log(`The Google Calendar API returned an error:\\n${error}`, 'red');\n }\n }.bind(state).bind(calendar));\n}", "function getEvents() {\n const settings = {\n url: `/api/users/${userId}/calendar`,\n dataType: 'json',\n contentType: 'application/json',\n type: 'GET',\n error: function(error) {\n console.log(error);\n },\n success: function(events) {\n calendars.clndr1.setEvents(events);\n }\n }\n\n $.ajax(settings);\n }", "async calendarPermissions() {\n const { status } = await Calendar.requestCalendarPermissionsAsync();\n if (status === 'granted') {\n const calendars = await Calendar.getCalendarsAsync();\n }\n }", "function loadMultipleCals() {\n //var gEventArray = [];\n var gCalArray = [];\n try {\n gapi.client.load('calendar', 'v3').then(function() {\n var request = gapi.client.calendar.calendarList.list({\n //'calendarId': 'primary',\n //'showDeleted': false,\n });\n console.log(request);\n request.execute(function(response) {\n gCalArray = response.items;\n });\n // get events from google\n if (gCalArray.length > 0) {\n for (var j = 0; j < gCalArray.length; j++) {\n getEvents(gCalArray[j]);\n }\n }\n });\n } catch (e) {\n console.log(e);\n }\n}", "function chooseCalendar() {\n if (location.pathname.indexOf('women') != -1) {\n return womenCalendars;\n } else if (location.pathname.indexOf('men') != -1) {\n return menCalendars;\n } else if (location.pathname.indexOf('touch') != -1) {\n return touchCalendars;\n } else if (location.pathname.indexOf('school') != -1) {\n return schoolCalendars\n } else {\n return allCalendars;\n }\n }", "async function getCalendarData(){\n let res = await fetch('/calendar');\n let calendarArray = await res.json();\n localStorage.calendarData = JSON.stringify(calendarArray);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get sheet_target all data
function getSheetTargetData(sheet_name) { var wb = xlsx.readFile(path_target); var listSheetNames = wb.SheetNames; console.log('all sheetName is ...', listSheetNames); // list_sheet_name.forEach(function(sheet_name) { // get sheet var wsheet = wb.Sheets[sheet_name]; // console.log('wsheet ...', wsheet);cls // get data 1.name 2.row and col var range_str = wsheet['!ref']; var cell_range = analysisCell(range_str); var col = 3; // row = 3 for (var row = 0; row < cell_range.c; row++) { var xy = xlsx.utils.encode_cell({ r: row, c: col }); // console.log('xy ...',xy); var cell = wsheet[xy]; // console.log('cell row ...',cell) if (cell && cell.v) { // if have value than add to list var item_tar = { "val": cell.v, "row": row, "col": col }; data_target.push(item_tar); } } }
[ "function makeSelectedSheetsTargetSheetReferenceList() {\n //Create an action refernece containing all of the sheets we want to export\n var targetSheetsRef = new ActionReference();\n targetSheetsRef.putEnumerated(PSKey.LayerKey, PSKey.OrdinalKey, PSKey.TargetEnum);\n\n // Put the reference containing the sheets into a list, cause that's how it's done\n var refList = new ActionList();\n refList.putReference(targetSheetsRef);\n\n return refList;\n}", "function getSheetValues() {\n var values = toWorksheet.getDataRange().getValues();\n return values;\n}", "GetSheetData(){\n return this.sheet.getDataRange().getValues().slice(1);\n }", "function getSheet_(sheet, startOffsetX, startOffsetY, endOffsetX, endOffsetY) {\n startOffsetX++;\n startOffsetY++;\n var numRows = sheet.getLastRow() - endOffsetY - startOffsetY + 1;\n var numColumns = sheet.getLastColumn() - endOffsetX - startOffsetX + 1;\n var array = [];\n if(numRows == 0 || numColumns == 0) {\n return array;\n }\n return values = sheet.getSheetValues(startOffsetY, startOffsetX, numRows, numColumns)\n}", "function getSheetData(cb){\n barstool.getAllWorksheets(function(err,data){\n if (err) throw err;\n sheetData = data;\n cb(err);\n });\n}", "static async getAllRows() {\n return (await sheet).sheetsByIndex[0].getRows();\n }", "function _getSheetDataRange(sheet) {\n const row_max = Math.max(header_size+1, sheet.getLastRow());\n return sheet.getRange(\"A\"+(header_size+1)+\":J\"+row_max);\n }", "function getQuestSheetAsArray() {\n let sheet = SpreadsheetApp.openById(SHEET_ID);\n return sheet.getSheetByName(\"quests\").getDataRange().getValues();\n}", "function getSpreadsheetData(range, sheet_id) {\r\n var data_range = SpreadsheetApp.openById(sheet_id).getRange(range);\r\n return data_range.getValues()\r\n}", "function getSheetData(auth) {\r\n return new Promise((resolve, reject) => {\r\n const sheets = google.sheets({version: 'v4', auth});\r\n sheets.spreadsheets.values.get(\r\n {\r\n spreadsheetId: '1_Z8PhD6A0TjANT6yNr1nFcAVNMUpS1kKm3MTWV4sQ50',\r\n range: 'Form Responses 1!A2:D'\r\n }\r\n , (err, res) => {\r\n if (err) return reject(err);\r\n resolve(res.data.values);\r\n }\r\n );\r\n });\r\n}", "function getSheetReference() {\n var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();\n return spreadsheet.getSheetByName(SHEET_DATA);\n }", "function getSheet() {\r\n\tsetMessage(\"Loading data, please wait\");\r\n gapi.client.sheets.spreadsheets.values.get({\r\n spreadsheetId: SPREADSHEET_ID,\r\n range: 'Sheet1!A2:D',\r\n }).then(function(response) {\r\n var range = response.result;\r\n if (range.values.length > 0) {\r\n allClientInformation = range.values;\r\n for (var i = 0; i < allClientInformation.length; i++) {\r\n // Ensure all rows are correct size.\r\n if (allClientInformation[i].length < 4) {\r\n for (var j=allClientInformation[i].length; j<4; j++ ) {\r\n allClientInformation[i].push(\"\");\r\n }\r\n }\r\n }\r\n populateTable();\r\n } else {\r\n appendPre('No data found.');\r\n }\r\n\t\t\tsetMessage(\" \");\r\n }, function(response) {\r\n appendPre('Error: ' + response.result.error.message);\r\n });\r\n}", "async listExampleData() {\n const sheets = googleapis.google.sheets({ version: 'v4', auth: this.oAuth2Client });\n return new Promise(function (resolve, reject) {\n sheets.spreadsheets.values.get({\n spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',\n range: 'Class Data!A2:E',\n }, (err, res) => {\n if (err) return reject('The API returned an error: ' + err);\n resolve(res.data.values);\n });\n }.bind(sheets));\n }", "function getSpreadsheetData(range, sheet_id) {\n var sheet = SpreadsheetApp.openById(sheet_id);\n var data_range = sheet.getRange(range);\n return data_range.getValues()\n}", "function getData(){\n var allData = sourceDataSheet.getRange(1, 1, last_row, last_column).getValues();\n //Logger.log(allData);\n return allData; \n}", "async function accessSheet(){\n const doc = new googleSheet('INSERT YOUR GOOGLE SHEET ID HERE')\n await util.promisify(doc.useServiceAccountAuth)(cred);\n const info = await util.promisify(doc.getInfo)();\n const sheet = info.worksheets[0];\n const rows = await util.promisify(sheet.getRows)({\n offset: 1\n });\n\n rows.forEach(row => {\n urlArray.push(filterRow(row));\n })\n return urlArray;\n}", "function getSheetNames(){\n\tvar url = wsAddress + \"?action=viewSheets\";\n\t$.ajax( {\n\t\tasync: false,\n\t\tdata: { \"path\" : encodeURI( url ) },\n\t\turl: proxy,\n\t\tsuccess: function( data, textStatus, jqxhr ) { populateTableMultiUsers( data ); },\n\t\terror: function( jqhxr, status, errorThrown ) { serviceCallError() },\n\t\tdataType: \"json\"\n\t} );\n}", "function getSheetData() {\n return new Promise((resolve) => {\n Tabletop.init({\n key: publicSpreadsheetUrl,\n callback: function(data, tabletop) {\n resolve(processSheetData(data, tabletop));\n },\n simpleSheet: true\n })\n })\n}", "function getSheetsList() {\n return []\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Options to make changes to departments
function editDepartmentOptions() { inquirer.prompt({ name: "editDeps", type: "list", message: "What would you like to update?", choices: [ "Add A New Department", "Remove A Department", "Return To Main Menu" ] }).then(responses => { switch (responses.editDeps) { case "Add A New Department": addDepartment(); break; case "Remove A Department": removeDepartment(); break; case "Return To Main Menu": runApp(); break; } }) }
[ "onChangeDepartments() {\n this.editedItem.selectProvince = { code: \"default\", name: \"default\" };\n this.editedItem.selectDistrict = { code: \"default\", name: \"default\" };\n var selected = this.editedItem.selectDepartment;\n var found = this.departments.find(function(element) {\n if (element.code === selected.code) {\n return element;\n }\n return null;\n });\n if (!!found) {\n this.depProvinces = found.provincies;\n this.proDistricts = {};\n }\n\t\t}", "function updateDepartments()\n{\n var departments = $(\"#department\");\n departments.html(\"\");\n departments.append($(\"<option></option>\").text(\"Select a department\"));\n for (var i = 0; i < this.departments.length; i++)\n {\n departments.append($(\"<option></option>\").text(this.departments[i]));\n }\n}", "function updateDepartment() {\n var realm = getRealmController();\n var id = getObject(\"field-departmentId\").value;\n var query = realm.queryBuilder.equalTo(\"id\",id).done();\n\n var departmentName = getObject(\"field-departmentName\").value;\n var department = {\n \"name\" : departmentName\n };\n\n update(\n REALM_OBJECT_NAME_DEPARTMENTS\n , department\n , query\n , function() {\n setGlobalDepartments(function(){\n resetDepartmentForm();\n showDataView();\n showDataViewDepartment()\n });\n }\n , function (error) {\n out(error);\n });\n}", "departmentsSet() {\n const select = Helpers.nodeArraySearch(this.inputs, 'id', 'department');\n if (select.length > 0) {\n this.file.get('departments').forEach(department => {\n const option = document.createElement('option');\n option.value = department;\n option.innerText = department;\n select[0].appendChild(option)\n })\n }\n }", "function setDepartmentData(departments, department_pages)\n{\n this.departments = departments;\n this.pages = department_pages;\n// updateDepartments();\n}", "function departmentSelected() {\n $scope.recruitment.department = angular.copy($scope.newDepartment);\n $scope.sf_recruitment.department = angular.copy($scope.newDepartment);\n $scope.getPositions($scope.newDepartment.id);\n $scope.modal.hide();\n }", "updateDepartment(departmentData){\n return updateValues(Department, departmentData);\n }", "selectDepartment(){\n let selectedDeptIndex = prompt(this.showDepartments());\n if(selectedDeptIndex == 'B' || selectedDeptIndex == 'b'){\n return;\n }\n while(selectedDeptIndex < 0 && selectedDeptIndex >= this.departments.length) {\n \n alert('Invalid Department');\n selectedDeptIndex = this.selectDepartment();\n }\n this.currentDepartment = this.departments[selectedDeptIndex];\n this.modifyDepartment();\n\n }", "function manageDepartments() {\n inquirer\n .prompt({\n name: \"action\",\n type: \"rawlist\",\n message: \"What would you like to do?\",\n choices: [\n \"View all departments\",\n \"Add department\",\n //\"Remove department\",\n \"Exit\"\n ]\n })\n .then(function(answer) {\n switch (answer.action) {\n case \"View all departments\":\n departmentView();\n break;\n\n case \"Add department\":\n departmentAdd();\n break;\n\n // case \"Remove department\":\n // departmentRemovet();\n // break;\n\n case \"Exit\":\n connection.end();\n break;\n }\n });\n}", "function departmentUpdateMode(departmentId) {\n\t$.get(\"?action=edit&departmentId=\" + departmentId, function(resp) {\n\t\tvar departmentName = resp.departmentName;\n\t\tvar departmentDescription = resp.departmentDescription\n\t\tif(departmentName != null && departmentDescription != null) {\n\t\t\t$('#department_back').show();\n\t\t\t$('#departmentBtn').html(\"Update Employee\");\n\t\t\t$('#departmentForm').attr(\"action\", \"?action=updateDepartment\").attr(\"name\", \"updateDepartment\");\n\t\t\t$('#departmentName').val(departmentName);\n\t\t\t$(\"#departmentDescription\").val(departmentDescription);\n\t\t\t$(\"#departmentId\").val(departmentId);\n\t\t}\n });\n}", "function putDepartment(data) {\n if (!data) return console.log(\"No data provided for putDepartment()!\");\n console.log(\"Data to put: \", data);\n $.ajax({\n url: '/api/departments/id/' + selectedDepartmentId,\n type: 'PUT',\n data: { department_name: data.name, over_head_costs: data.overhead, id: selectedDepartmentId },\n success: function () {\n alert(\"Department edited succesfully!\");\n window.location.reload();\n }\n });\n }", "switchDepartment(department) {\n this.department = department;\n return this;\n }", "function setupDepartment(){\n var selector = thisInstance.constants.selector;\n showLoader(true);\n $(selector.departmentSetupButton).prop(\"disabled\", true);\n $.ajax({\n method: \"post\",\n url: $(selector.questionTypeDiv).data(\"setup_url\"),\n contentType: 'application/json',\n data: JSON.stringify(thisInstance.requestDataObject),\n success: function(data){\n if(data.success){ // if departments created successfully\n $(selector.questionTypeDiv).remove(); // remove select question types section\n $(selector.departmentSetupDiv).remove(); // remove add department section\n if(typeof thisInstance.setupCompleteCallback === \"function\") { // if this flow is called from invite page\n thisInstance.setupCompleteCallback();\n }\n else{ // if no setup complete callback is passed\n location.reload();\n }\n }\n else{\n showErrorModal(data.message);\n }\n },\n error: function(error){\n if(error && error.status === 401){\n location.reload();\n }\n else {\n showErrorModal(error.message);\n }\n }\n }).always(function(){\n showLoader(false);\n $(selector.departmentSetupButton).prop(\"disabled\", false);\n })\n }", "function attdeptFunction() {\n // select dropdown and get value\n attdept = attdept_dropdown.property('value');\n buildDepts(attdept);\n}", "function changeStatusOfSchedule(departmentCode, newStatus) {\n vm.selectedDepartment.status = newStatus;\n for (var x = 0; x < vm.loggedInUser.depts.length; x++) {\n if (vm.loggedInUser.depts[x].departmentCode === departmentCode) {\n vm.loggedInUser.depts[x].status = newStatus;\n return;\n }\n }\n }", "function viewDepartmentBudget() {\n getDepartment(promptDepartment);\n}", "async function renderDepartments() {\r\n let departments = await getDepartments();\r\n let dptSelected = 0;\r\n deleteChilds('selectDpt');\r\n\r\n defaultOption = generateElement('option', 'Select department');\r\n defaultOption.setAttribute('selected', 'selected');\r\n document.getElementById('selectDpt').appendChild(defaultOption);\r\n\r\n switch (document.getElementById(\"selectOfc\").value) {\r\n case \"1\":\r\n dptSelected = departments.departments[1];\r\n break;\r\n case \"2\":\r\n dptSelected = departments.departments[2];\r\n break;\r\n case \"3\":\r\n dptSelected = departments.departments[3];\r\n break;\r\n\r\n\r\n }\r\n\r\n Object.entries(dptSelected).forEach(dpt => {\r\n let option = generateElement('option', dpt[1]);\r\n option.setAttribute('value', dpt[0]);\r\n document.getElementById('selectDpt').appendChild(option);\r\n })\r\n\r\n}", "function addDepartment() {\n inquirer.prompt(deptQuestions).then(function(answer) {\n addNewDept(answer.department, answer.overheadcosts);\n });\n}", "function editDepartment(deptId) {\n let match = departmentList.filter((Element) => {\n return deptId == Element.depT_ID;\n });\n match = match[0];\n $(Models.department_edit).modal('show');\n $(Inputs.department_tr_edt).val(match.department_tr);\n $(Inputs.department_en_edt).val(match.department_en);\n DeprtmentModel.depT_ID = match.depT_ID;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a playlist (city) in the playlist database
async function updatePlaylistInMongo(city) { return new Promise(((resolve, reject) => { PlaylistsSchema.findOneAndUpdate({ name: city.name }, city, { upsert: true }, (error, data) => { if (error) { console.log('An error occurred updating a playlist to the database', error); reject(error); } resolve(data); }); })); }
[ "function save (zoneId, playlist) {\n\n\t\tdatabases\n\t\t\t.playlists\n\t\t\t.update(\n\t\t\t\t{ zone: zoneId }, \n\t\t\t\t{ zone: zoneId, playlist: playlist }, \n\t\t\t\t{ upsert: true },\n\t\t\t\tfunction(err, response) {\n\n\t\t\t\t}\n\t\t\t);\n\t}", "async function editPlaylist(game_name, playlist_id)\n{\n // Create all the songs on the playlist\n var songs = await songsdb.createFromPlaylistId(playlist_id);\n\n // Get the song object ids\n var song_ids = [];\n for (song of songs)\n {\n song_ids.push(song._id);\n }\n\n var query = { game_name: game_name };\n var update = { $set: { playlist_id: playlist_id, songs: song_ids } };\n return gameModel.findOneAndUpdate(query, update).exec();\n}", "function updatePlaylist(playlist, artistName, songTitle){\n playlist [artistName] = songTitle\n return playlist\n}", "function updatePlaylist(playlist, artistName, songTitle)\n{\n playlist[artistName] = songTitle\n}", "function updatePlaylist(playlist, artistName, songTitle){\n \n playlist[artistName] = \"songTitle\";\n \n}", "async update(id, playlist) {\n try {\n const updatedPlaylist = await knexMusic('playlist').where(\"id\", id).update({ \n title: playlist.title, \n user: playlist.user, \n list: playlist.list \n });\n return updatedPlaylist;\n } catch(e) {\n console.error(e.message);\n }\n }", "async function replacePlaylistById(id, playlist) {\n playlist = extractValidFields(playlist, PlaylistSchema);\n const [ result ] = await mysqlPool.query(\n 'UPDATE playlists SET ? WHERE id = ?',\n [ playlist, id ]\n );\n return result.affectedRows > 0;\n}", "function updatePlaylist (playlist, artistName, songTitle){\n playlist[artistName] = songTitle\n return playlist\n}", "function updatePlaylist(playlist, artist, song) {\n playlist[artist] = 'eminem';\n playlist[song] = 'phenomenal';\n return playlist\n}", "updatePlaylist(playlistResolvable, title, description, privacy, tags, language, localizations) {\n return __awaiter(this, void 0, void 0, function* () {\n this.checkTokenAndThrow();\n const id = yield services_1.GenericService.getId(this.youtube, playlistResolvable, _1.Playlist);\n const data = JSON.parse(JSON.stringify(constants_1.PLAYLIST_DATA));\n const parts = ['id', 'player', 'snippet'];\n data.id = id;\n data.snippet = { title };\n data.snippet.defaultLanguage = language ? language : this.youtube.language;\n if (description)\n data.snippet.description = description;\n if (privacy)\n data.status = { privacyStatus: privacy };\n if (tags)\n data.snippet.tags = tags.join(',');\n if (localizations)\n data.localizations = localizations;\n if (privacy)\n parts.push('status');\n if (localizations)\n parts.push('localizations');\n const response = yield this.youtube._request.put('playlists', { part: parts.join(',') }, JSON.stringify(data), null, this.youtube.accessToken);\n return new _1.Playlist(this.youtube, response);\n });\n }", "function updatePlaylist(playlist, artistName, songTitle){\n playlist[artistName] = songTitle;\n return playlist;\n}", "function updatePlaylist(playlist, artistName, songTitle) {\n playlist[artistName] = songTitle;\n return playlist;\n}", "playPlaylist({ state, commit, dispatch }, idPl) {\n let i;\n for (i = 0; i < state.playlists.length; i++) {\n if (state.playlists[i].id == idPl) break;\n }\n if (state.playlists[i].songs.length > 0) {\n commit(\"updateCurrentList\", [...state.playlists[i].songs]);\n commit(\"updateCurrentSong\", state.currentList[0]);\n commit(\"updateSourcePlayer\");\n state.random = 0;\n dispatch(\"play\");\n }\n }", "changePlaylistPosition(roomID, iDrag, iDrop) {\n Room.find({ url: roomID }, \"playlist\").exec().then(e => {\n let startPlaylist = e[0].playlist,\n tempPlaylist = [],\n iDragEl = startPlaylist[iDrag];\n\n for (let index = 0; index < startPlaylist.length; index++) {\n if (index === iDrop) {\n tempPlaylist.push(iDragEl);\n }\n if (index !== iDrag) {\n tempPlaylist.push(startPlaylist[index]);\n }\n }\n Room.findOneAndUpdate({ url: roomID }, { playlist: tempPlaylist }).exec();\n });\n }", "function pillaUpdatePlaylist(playlist) {\n\t\t$('#pilla_playlist_list').empty();\n\t\tlastAction.playlist = playlist.name;\n\t\t$('#playlistPageHeaderMsg').text(playlist.name);\n\t\tfor (i = 0; i < playlist.items.length; i++) {\n\t\t\tvar liEntry = $('<li data-icon=\"carat-r\">').html('<a href=\"#\" class=\"pilla_a_music\">' + playlist.items[i].name + '<span class=\"ui-li-count\">' + humanSeconds(playlist.items[i].mp3len) + '</span></a><a href=\"#\" class=\"pilla_a_music_act\">link</a>');\n\n\t\t\tif (playlist.items[i].default == 1) {\n\t\t\t\tliEntry.attr('data-theme', 'b');\n\t\t\t\tlastAction.songIndex = i;\n\t\t\t}\n\t\t\tliEntry.data(playlist.items[i]);\n\n\t\t\t$('#pilla_playlist_list').append(liEntry);\n\t\t}\n\t\t$('#pilla_playlist_list').listview('refresh');\n\t}", "function updatePlaylist(){\n\tvar songs = JSON.parse(sessionStorage.getItem(\"songs\"));\n\t$(renderPlaylist(songs));\n}", "savePlaylist() {\n \n }", "function changePlaylist() {\n\t\t// clear track specific data\n\t\t$(\"#trackName\").empty();\n\t\t$(\"#trackRating\").val(\"(Rate track)\");\n\t\n\t\tvar playlistIndex = $(\"#playlist\").val();\n\t\tif (playlistIndex == \"select\") {\n\t\t\t$(\"#playlistPlayer\").empty();\n\t\t} else {\n\t\t\t// load selected playlist on page\n\t\t\tvar userLib = Library.forCurrentUser();\n\t\t\tuserLib.playlists.snapshot().done(function (snapshot) {\n\t\t\t\tvar playlist = snapshot.get(playlistIndex);\n\t\t\t\tlist = List.forPlaylist(playlist);\n\t\t\t\t$(\"#playlistPlayer\")\n\t\t\t\t\t.empty()\n\t\t\t\t\t.append(list.node);\n\t\t\t\tlist.init();\n\t\t\t});\n\t\t}\n\t}", "addToPlaylist(track, playlistName) {\n let self = this;\n // If playlist exists\n if(this.playlists.indexOf(playlistName) > -1) {\n this.db.playlists.find({ name: playlistName }).exec(function(err, docs) {\n if (!err) {\n let newPlaylist = docs[0];\n newPlaylist.tracks.push(track._id);\n newPlaylist.count++;\n newPlaylist.duration += track.duration;\n self.db.playlists.update({ name: playlistName }, newPlaylist, {}, function(err) {\n if (!err) {\n self.db.playlists.persistence.compactDatafile();\n console.log(\"Track \" + track.title + \" added to playlist \" + playlistName);\n }\n });\n }\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set Item Invoice header
function setItemInvoiceHeader(data) { try { disableInvoiceNo(); // if (mode == 'I') { // $('.TXT_fwd_no').val(''); // $('.TXT_fwd_no').attr('disabled', true); // $('.TXT_fwd_no').parent().addClass('popup-fwd-search'); // $('.popup-fwd-search').find('.btn-search').attr('disabled', true); // parent.$('.popup-fwd-search').removeClass('popup-fwd-search'); // $(".TXT_fwd_no").removeClass("required"); // } else { // $('.TXT_fwd_no').attr('disabled', false); // $('.TXT_fwd_no').parent().addClass('popup-fwd-search'); // $('.popup-fwd-search').find('.btn-search').attr('disabled', false); // parent.$('.popup-fwd-search').removeClass('popup-fwd-search'); // $(".TXT_fwd_no").addClass("required"); // } $('.TXT_inv_no').val(data.inv_no); $('.TXT_deposit_no').val(data.deposit_no); $('.TXT_warehouse_div').val(data.warehouse_div); $('.infor-created .heading-elements').removeClass('hidden'); // Common $('#DSP_cre_user_cd').text(data.cre_user_cd +' '+ data.cre_user_nm); $('#DSP_cre_datetime').text(data.cre_datetime); $('#DSP_upd_user_cd').text(data.upd_user_cd +' '+ data.upd_user_nm); $('#DSP_upd_datetime').text(data.upd_datetime); if (data.inv_data_div == '1') { $('input[name="RDI_inv_data_div"][value="1"]').prop('checked', true); } else { $('input[name="RDI_inv_data_div"][value="0"]').prop('checked', true); } var _inv_data_div = $('input[name="RDI_inv_data_div"]:checked').val(); checkInvDataDiv(_inv_data_div, true); $('.TXT_p_fwd_no').val(data.p_fwd_no); $('.DSP_p_rcv_no').text(data.p_rcv_no); $('.TXT_fwd_no ').val(data.fwd_no); $('.DSP_rcv_no').text(data.rcv_no); $('.TXT_fwd_status').val(data.fwd_status_div); $('.TXT_rcv_status').val(data.rcv_status_div); // if ($('input[name="RDI_inv_data_div"]:checked').val() == '0') { // $('.TXT_p_fwd_no').val(data.p_fwd_no); // $('.DSP_p_rcv_no').text(data.p_rcv_no); // $('.TXT_fwd_no').val(''); // $('.DSP_rcv_no').text(''); // $('.TXT_warehouse_div').val(''); // } else { // $('.TXT_fwd_no').val(data.fwd_no); // $('.DSP_rcv_no').text(data.rcv_no); // $('.TXT_p_fwd_no').val(''); // $('.DSP_p_rcv_no').text(""); // $('.TXT_warehouse_div').val(data.warehouse_div); // } // $('.TXT_fwd_date').val(data.fwd_date); // $('.DSP_status').text(data.fwd_status_nm); // $('.TXT_fwd_status').val(data.fwd_status_div); // $('.DSP_fwd_status_cre_datetime').text(data.fwd_status_cre_datetime); //cust $('.TXT_cust_cd').val(data.cust_cd); $('.TXT_cust_nm').val(data.cust_nm); $('.TXT_cust_adr1').val(data.cust_adr1); $('.TXT_cust_adr2').val(data.cust_adr2); $('.TXT_cust_zip').val(data.cust_zip); $('.TXT_cust_city_div').val(data.cust_city_div); $('.DSP_cust_city_nm').text(data.cust_city_nm); $('.TXT_cust_country_div').val(data.cust_country_div); _addTaxRate(data.cust_country_div); $('.DSP_cust_country_nm').text(data.cust_country_nm); $('.TXT_cust_tel').val(data.cust_tel); $('.TXT_cust_fax').val(data.cust_fax); $('.TXT_cust_fax').val(data.cust_fax); //consignee $('.TXT_consignee_cd').val(data.consignee_cd); $('.TXT_consignee_nm').val(data.consignee_nm); $('.TXT_consignee_adr1').val(data.consignee_adr1); $('.TXT_consignee_adr2').val(data.consignee_adr2); $('.TXT_consignee_zip').val(data.consignee_zip); $('.TXT_consignee_city_div').val(data.consignee_city_div); $('.DSP_consignee_city_nm').text(data.consignee_city_nm); $('.TXT_consignee_country_div').val(data.consignee_country_div); $('.DSP_consignee_country_nm').text(data.consignee_country_nm); $('.TXT_consignee_tel').val(data.consignee_tel); $('.TXT_consignee_fax').val(data.consignee_fax); $('.TXT_consignee_fax').val(data.consignee_fax); $('.TXT_lc_no').val(data.lc_number); $('.TXT_po_no').val(data.po_number); $('.TXT_date_of_shipment').val(data.shipment_date); $('.TXT_shipping_mark_1').val(data.mark1); $('.TXT_shipping_mark_2').val(data.mark2); $('.TXT_shipping_mark_3').val(data.mark3); $('.TXT_shipping_mark_4').val(data.mark4); $('.TXT_packing').val(data.packing); if (data.shipment_div != '') { $('.CMB_shipment_div option[value='+data.shipment_div+']').prop('selected', true); } else { $('.CMB_shipment_div option:first').prop('selected', true); } if (data.currency_div != '') { $('.CMB_currency_div option[value='+data.currency_div+']').prop('selected', true); } else { $('.CMB_currency_div option:first').prop('selected', true); } if (data.port_city_div != '') { $('.CMB_port_city_div option[value='+data.port_city_div+']').prop('selected', true); } else { $('.CMB_port_city_div option:first').prop('selected', true); } if (data.port_country_div != '') { $('.CMB_port_country_div option[value='+data.port_country_div+']').prop('selected', true); } else { $('.CMB_port_country_div option:first').prop('selected', true); } if (data.trade_terms_div != '') { $('.CMB_trade_terms_div option[value='+data.trade_terms_div+']').prop('selected', true); $('.CMB_trade_terms_div').trigger('change'); } else { $('.CMB_trade_terms_div option:first').prop('selected', true); } // console.log(111); if (data.payment_conditions_div !== '') { $('.CMB_payment_conditions_div option[value='+data.payment_conditions_div+']').prop('selected', true); } else { $('.CMB_payment_conditions_div option:first').prop('selected', true); } $('.TXT_dest_city_div').val(data.dest_city_div); $('.DSP_dest_city_nm').text(data.dest_city_nm); $('.TXT_dest_country_div').val(data.dest_country_div); $('.DSP_dest_country_nm').text(data.dest_country_nm); $('.TXT_payment_notes').val(data.payment_notes); // $('.DSP_currency_div').text(data.currency_div); // $('.TXT_our_freight_amt').val(data.our_freight_amt); $('.TXT_freight_amt').val(data.freigt_amt); $('.TXT_insurance_amt').val(data.insurance_amt); // detail sum of amount // $('.DSP_total_qty').text(data.total_qty.replace(/\.00$/,'')); calTotalQty(); // $('.DSP_total_gross_weight').text(data.total_gross_weight.replace(/\.00$/,'')); calTotalGrossWeight(); // $('.DSP_total_net_weight').text(data.total_net_weight.replace(/\.00$/,'')); calTotalNetWeight(); // $('.DSP_total_measure').text(data.total_measure.replace(/\.00$/,'')); calTotalMeasure(); calTotalDetailAmt(); calTotalTaxAmt(); calTotalAmt(); // $('.DSP_unit_total_gross_weight_nm').text(data.unit_total_gross_weight_nm); // $('.DSP_unit_total_gross_weight_div').text(data.unit_total_gross_weight_div); // $('.DSP_unit_total_net_weight_nm').text(data.unit_total_gross_weight_nm); // $('.DSP_unit_total_net_weight_div').text(data.unit_total_net_weight_div); // $('.DSP_unit_total_measure_nm').text(data.unit_total_measure_nm); // $('.DSP_unit_total_measure_div').text(data.unit_total_measure_div); // sum of money // $('.DSP_total_detail_amt').text(data.total_detail_amt.replace(/\.00$/,'')); //$('.TXT_freight_amt').val(data.freigt_amt); //$('.TXT_insurance_amt').val(data.insurance_amt); // $('.TXT_freight_amt').val(data.freigt_amt.replace(/\.00$/,'')); // $('.DSP_tax_amt').text(data.total_detail_tax.replace(/\.00$/,'')); // $('.DSP_total_amt').text(data.total_amt.replace(/\.00$/,'')); $('.DSP_carton_total_qty').text(data.total_carton_qty); $('.DSP_carton_total_net_weight').text(data.total_carton_net_weight); $('.DSP_carton_total_gross_weight').text(data.total_carton_gross_weight); $('.DSP_carton_total_measure').text(data.total_carton_measure_weight); // set item footer if (data.storage_user_cd != '') { $('.CMB_storage_user_cd option[value='+data.storage_user_cd+']').prop('selected', true); } else { $('.CMB_storage_user_cd option:first').prop('selected', true); } $('.TXT_country_of_origin').val(data.country_of_origin); $('.TXT_manufacture').val(data.manufacture); $('.TXT_sign_cd').val(data.sign_user_cd); $('.DSP_sign_nm').text(data.sign_user_nm); $('.TXA_inside_remarks').val(data.inside_remarks); // var currency_div = $('.currency_div').find('option:selected').val(); if (currency_div == 'JPY') { $('#table-invoice tbody tr').find('.price').addClass('currency_JPY'); } else { $('#table-invoice tbody tr').find('.price').removeClass('currency_JPY'); } // $('.TXT_invoice_date').val(data.inv_date); $('.TXT_sales_date').val(data.sales_date); } catch (e) { console.log('setItemFwdHeader: ' + e.message); } }
[ "setInvoiceModalHeader(id, name){\n $(\"#receipt-dt-name\").text('Buyer : ' + name);\n $(\"#receipt-dt-id\").text('Receipt id # ' + id);\n }", "function invoiceHeader()\r\n{\r\n\r\n\r\n\tinvoiceRecord = nlapiCreateRecord(\"invoice\");\r\n\t\r\n\t// set internal ID for Optegra form 137\r\n\tinvoiceRecord.setFieldValue('customform', optegraInvoiceForm); \r\n\t\r\n\tinvoiceRecord.setFieldValue('tranid', invoiceNo);\r\n\tinvoiceRecord.setFieldValue('recordtype', 'invoice');\r\n\r\n//\tinvoiceRecord.setFieldValue('department',journalDeptID);\r\n\tinvoiceRecord.setFieldValue('location',journalLocationID);\r\n//\tinvoiceRecord.setFieldValue('class',journalClass);\r\n\r\n\tinvoiceRecord.setFieldValue('description', 'DGL auto post invoice: ' + invoiceNo);\r\n\tinvoiceRecord.setFieldValue('memo', 'DGL auto post invoice: ' + invoiceNo);\r\n\r\n\t\r\n\tif(invoicePayMethod!=0)\r\n\t{\r\n\t\t//invoiceRecord.setFieldValue('custbody1',invoicePayMethod);\t\t// live modification 03/7/2012\r\n\t\tinvoiceRecord.setFieldValue('salesrep',invoiceSalesRep);\r\n\t\tinvoiceRecord.setFieldValue('partner',invoicePartner);\r\n\t}\r\n\r\n//\tif(journalSubsidiary!=0)\r\n//\t{\r\n//\tinvoiceRecord.setFieldValue('subsidiary',journalSubsidiary);\r\n//\t}\r\n\r\n\r\n\r\n\tdateInvoice = reverseDate(invoiceDate);\r\n\r\n\tinvoiceRecord.setFieldValue('trandate', dateInvoice);\r\n\r\n\r\n\r\n\t// lookup customer, if it does not exist, create it\r\n\tentity = lookupCustomer(patientNo);\r\n\r\n\tif(entity.length==0)\r\n\t{\r\n\t\tentity = createCustomer(); \r\n\t}\r\n\r\n\tinvoiceRecord.setFieldValue('entity', entity); \r\n\r\n}", "function setValueItemHeader(obj, isRefer) {\n\ttry {\n\t\tif (obj.length == 0) {\n\t\t\tobj = obj_empty_header;\n\t\t}\n\n\t\tif (isRefer) {\n\t\t\t$('#TXT_manufacture_no').val(obj.manufacture_no);\n\t\t}\n\t\t$('#DSP_production_instruction_date').html(obj.production_instruction_date);\n\t\t$('#DSP_production_status').html(obj.production_status);\n\t\t$('#DSP_in_order_no').html(obj.in_order_no);\n\t\t$('#DSP_internal_ordering_date').html(obj.internal_ordering_date);\n\t\t$('#DSP_hope_delivery_date').html(obj.hope_delivery_date);\n\t\t$('#DSP_product').html(obj.product);\n\t\t$('#DSP_manufacture_qty').html(obj.manufacture_qty);\n\t\t$('#DSP_complete_qty').html(obj.complete_qty);\n\t\t$('#DSP_remain_amount').html(obj.remain_amount);\n\t} catch (e) {\n\t\talert('setValueItemHeader: ' + e.message);\n\t}\n}", "function populateHeader(iScreamInc) {\n let headerH1 = document.createElement('h1');\n headerH1.textContent = iScreamInc['companyName'];\n header.appendChild(headerH1);\n\n let headerPara = document.createElement('p');\n headerPara.textContent = iScreamInc['headOffice'];\n header.appendChild(headerPara);\n\n}", "appendInvoiceModalTableHeader () {\n var head_titles = ['Name', 'Quantity', 'Unit Cost', 'Total Retail', 'Date', 'Time'];\n var $head = `<thead><tr><th>${head_titles.join('</th><th>')}</th></tr></thead>`;\n $(\"#receipt-dt-modal .modal-body .table\").append($head);\n }", "function invoiceHeader()\r\n{\r\n\tvar postPerdiodIntID = 0;\r\n\tvar retVal = true;\r\n\tvar dateInvoice = null;\r\n\t\r\n\ttry\r\n\t{\r\n\t\t\r\n\r\n\t\tinvoiceRecord = nlapiCreateRecord(\"invoice\");\r\n\t\tinvoiceRecord.setFieldValue('tranid', invoiceNo);\r\n\t\tinvoiceRecord.setFieldValue('recordtype', 'invoice');\r\n\r\n\t\tinvoiceRecord.setFieldValue('memo', patientDetails);\r\n\r\n\t\tdateInvoice = reverseDate(invoiceDate);\r\n\t\tinvoiceRecord.setFieldValue('trandate', dateInvoice);\r\n\t\t\r\n\t\tinvoiceRecord.setFieldValue('custbody_patientnumber', patientDetails);\t\t// 1.0.18\r\n\t\t\r\n\t\tif(interCompanyTag!='not found' && interCompanyTag.length > 0) {\r\n\t\t\tvar interCompanyInternalID = genericSearch('customrecord_intercompanyclass','custrecord_intercompany_tagname',interCompanyTag);\r\n \tinvoiceRecord.setFieldValue('custbody_invoice_intercompany_tag', interCompanyInternalID);\r\n\t\t}\r\n\r\n\t\t// lookup customer, if it does not exist, create it\r\n\t\tentity = lookupCustomer(jdeid);\r\n\r\n\t\tif(entity!='not found')\r\n\t\t{\r\n\r\n\t\t\tinvoiceRecord.setFieldValue('entity', entity); \r\n\r\n\t\t\t// 1.0.4 if terms is blank do not populate\r\n\t\t\tif (terms != 0)\r\n\t\t\t{\r\n\t\t\t\tinvoiceRecord.setFieldValue('custbody_terms', terms);\r\n\t\t\t}\r\n\r\n\t\t\tpostPerdiodIntID = lookupPostingPeriod('accountingperiod',dateInvoice);\t\t// 1.0.6 lookup posting period\r\n\r\n\t\t\tif(postPerdiodIntID != 'not found')\r\n\t\t\t{\r\n\t\t\t\tinvoiceRecord.setFieldValue('postingperiod',postPerdiodIntID);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tnlapiLogExecution('AUDIT', 'Cannot lookup posting period for invoice date', dateInvoice);\r\n\t\t\t\tretVal = false;\r\n\t\t\t}\r\n\r\n\t\t\t// to do error condition \r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tauditTrail('FAILED', 'Cannot find customer: ' + jdeid);\r\n\t\t\tretVal = false;\r\n\t\t}\r\n\t\t\r\n\t}\r\n\tcatch(e)\r\n\t{\r\n\t\terrorHandler(e);\r\n\t\tnlapiLogExecution('AUDIT', 'failure', 'failed to commit invoice line');\r\n\t\tauditTrail('FAILED', 'invoiceHeader ' + getErrorMessage(e));\r\n\t\tretVal=false;\r\n\r\n\t}\r\n\r\n\treturn retVal;\r\n\t\r\n}", "function setHeader(position , header){\n var hdrCell = $('#reportDiv .xhdr .hdr .hdrcell').get();\n hdrCell[position].innerHTML = header;\n}", "function createItemHeader(item) {\n const headerElem = document.createElement(\"div\");\n headerElem.classList.add(\"item-header\");\n\n // type of pack\n const packElem = document.createElement(\"h3\");\n packElem.classList.add(\"pack-type\");\n packElem.innerHTML = item.pack.display;\n\n const purchaseElem = document.createElement(\"div\");\n purchaseElem.classList.add(\"purchase-info\");\n\n // purchase quantity\n const quantityElem = document.createElement(\"h5\");\n quantityElem.classList.add(\"quantity\");\n quantityElem.innerHTML = `Quantity: ${item.quantity}`;\n\n // unit price\n const priceElem = document.createElement(\"h5\");\n priceElem.classList.add(\"unit-price\");\n priceElem.innerHTML = `\\$ ${item.pack.price} / ${item.pack.unit}`;\n\n purchaseElem.appendChild(quantityElem);\n purchaseElem.appendChild(priceElem);\n headerElem.appendChild(packElem);\n headerElem.appendChild(purchaseElem);\n return headerElem;\n }", "function addHeader() {\n ddCont.push(\n //header: no dice for classic header:\n {\n text: \"Portfolio Summary / Exposure\",\n margin: [0, 5, 0, 0],\n fontSize: 15,\n bold: true,\n color: '#d4d',\n }\n );\n }", "function setHeaders(){\n\theaders = [\"ID\",\"Name\"];\n\tfor(var i=0;i<headers.length;i++){\n\t\toutlet(5,\"set \"+ i + \" 0\" + \"\\t\" + headers[i]);\n\t}\n}", "function addHeader() {\n ddCont.push(\n //header: no dice for classic header:\n {\n text: \"Portfolio Summary / Analysis\",\n margin: [0, 5, 0, 0],\n fontSize: 15,\n bold: true,\n color: '#d4d'\n }\n );\n }", "function setTableHeader(){\n\t\tvar ts_header = $(\"#ts_header\");\n\t\tts_header.html(\"\");\n\t\tts_header.append(\"<th>Assignment ID</th>\");\n\t\tfor(var i=0; i< state.list.length; i++){\n\t\t\tts_header.append(\"<th>\" + state.list[i].weekDay + \" \" + state.list[i].date + \"</th>\");\n\t\t}\n\t\tts_header.append(\"<th>Total</th>\");\n\t}", "function _printHeader(){\n sys.log(sys.product.meta.getHeaderText());\n }", "function addHeader(report) {\n var pageHeader = report.getHeader();\n pageHeader.addClass(\"header\");\n pageHeader.addParagraph(param.title, \"heading\");\n pageHeader.addParagraph(param.version, \"\");\n pageHeader.addParagraph(\" \", \"\");\n pageHeader.addParagraph(\"Elster Umsatzsteuer-Voranmeldung\", \"h1\");\n\n if (param.headerLeft) {\n pageHeader.addParagraph(param.headerLeft, \"bold\");\n }\n if (param.vatNumber) {\n pageHeader.addParagraph(\"Steuernummer: \" + param.vatNumber, \"bold\");\n }\n\n pageHeader.addParagraph(\"Periode: \" + Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"bold\");\n pageHeader.addParagraph(\" \", \"\");\n\n}", "function createBillHeader()\r\n{\t\r\n\tvar currentBillIntId = 0; \r\n\tvar lastBillIntID = 0;\r\n\r\n\ttry\r\n\t{\t\t\r\n\t\t//version 1.0.3\r\n\t\t//getting the last Bill's internal ID\r\n\t\tlastBillIntID = genericSearchLastRecordInternalID('vendorbill');\t\t\t\t\t\t\t\r\n\r\n\t\t/*\r\n\t\t * setting the internal Id for the current bill \r\n\t\t * Reason - you cannot get the internal ID of the record before you submit the particular record\r\n\t\t */\r\n\t\tcurrentBillIntId = parseInt(lastBillIntID) +1;\t\t\r\n\r\n\t\t//as parseInt returns the ID in 1 decimal point, set it back to 0 decimal points\r\n\t\tcurrentBillIntId = parseFloat(currentBillIntId).toFixed(0);\r\n\r\n\t\t//creating a new bill record\r\n\t\tbillRecord = nlapiCreateRecord(\"vendorbill\");\t\r\n\r\n\t\tbillRecord.setFieldValue('customform', BILLFORMINTID); \r\n\t\tbillRecord.setFieldValue('recordtype', 'vendorbill');\r\n\t\tbillRecord.setFieldValue('location',billLocationIntID);\r\n\t\tbillRecord.setFieldValue('memo', DESC);\r\n\t\tbillRecord.setFieldValue('entity',calledgateway);\r\n\t\tbillRecord.setFieldValue('trandate', today);\r\n\r\n\t\t/*\r\n\t\t * //version 1.0.3\r\n\t\t * setting the internal ID of the current bill as the transaction id (In the bills, the transaction id is not automatically generated)\r\n\t\t */\r\n\t\tbillRecord.setFieldValue('tranid', currentBillIntId);\t\t\t\t\r\n\t\tbillRecord.setFieldValue('approvalstatus', approvalStatus);\t\t \r\n\t}\r\n\tcatch(e)\r\n\t{\r\n\t\terrorHandler(\"createBillHeader\", e);\t\t\t\t\r\n\t} \r\n}", "function ASCsvHeader() {\r\n this.title = \"\";\r\n this.starttrigger = new Date();\r\n this.xunit = \"UnitX\";\r\n this.yunit = \"UnitY\";\r\n this.rows = -1;\r\n this.formula = ASCsvHeader.originalDataFormula;\r\n }", "function printProductsReportHeader() {\n\t\tconsole.log(\"==================== PRODUCTS FOR SALE =========================\".bold.blue);\n\t\tconsole.log(\"ITEM ID\".padStart(PAD_ITEM_ID).bold.yellow +\n\t\t\t\" PRODUCT NAME \".padStart(PAD_PRODUCT_NAME).bold.yellow + \n\t\t\t\" PRICE \".padStart(PAD_PRICE).bold.yellow +\n\t\t\t\" QUANTITY \".padStart(PAD_QTY).bold.yellow);\n\t\tconsole.log(\"================================================================\".bold.blue);\n\t}", "function buildCartHeader() {\r\n\t\tvar thead = carttable.createTHead();\r\n\t\tvar row, cell;\r\n\t\t\r\n\t\trow = thead.insertRow(-1);\r\n\t\trow.setAttribute(\"id\", \"carttableheader\");\r\n\t\t\r\n\t\tcell = row.insertCell(-1);\r\n\t\tcell.setAttribute(\"class\", \"smalltext\");\r\n\t\tcell.align = \"center\";\r\n\t\tcell.width = \"20%\";\r\n\t\tcell.innerHTML = '<div class=\"listheadernosort\">Item</div>';\r\n\t\t\r\n\t\tcell = row.insertCell(-1);\r\n\t\tcell.setAttribute(\"class\", \"smalltext\");\r\n\t\tcell.align = \"left\";\r\n\t\tcell.width = \"23%\";\r\n\t\tcell.innerHTML = '<div class=\"listheadernosort\">Description</div>';\r\n\t\t\r\n\t\tcell = row.insertCell(-1);\r\n\t\tcell.setAttribute(\"class\", \"smalltext\");\r\n\t\tcell.align = \"center\";\r\n\t\tcell.width = \"10%\";\r\n\t\tcell.innerHTML = '<div class=\"listheadernosort\">Price</div>';\r\n\t\t\r\n\t\tcell = row.insertCell(-1);\r\n\t\tcell.setAttribute(\"class\", \"smalltext\");\r\n\t\tcell.align = \"center\";\r\n\t\tcell.width = \"6%\";\r\n\t\tcell.innerHTML = '<div class=\"listheadernosort\">Qty</div>';\r\n\t\t\r\n\t\tcell = row.insertCell(-1);\r\n\t\tcell.setAttribute(\"class\", \"smalltext\");\r\n\t\tcell.align = \"center\";\r\n\t\tcell.width = \"10%\";\r\n\t\tcell.innerHTML = '<div class=\"listheadernosort\">Total</div>';\r\n\t\t\r\n\t\tcell = row.insertCell(-1);\r\n\t\tcell.setAttribute(\"class\", \"smalltext\");\r\n\t\tcell.align = \"center\";\r\n\t\tcell.width = \"1%\";\r\n\t\tcell.setAttribute(\"style\", \"display: none\");\r\n\t\tcell.innerHTML = '<div class=\"listheadernosort\"></div>';\r\n\t\t\r\n\t}", "function createHeader($index, header)\n {\n var data = \"\";\n if(header)\n {\n data = header.data;\n }\n $scope.table.rows[$index] = {\n contents:[{\n \"datavalue\":\"\",\n \"headervalue\": {\"data\": data },\n \"checked\":\"false\",\n \"style\":\"text-align:right;background-color:#1072A4;\",\n \"colshow\":\"true\",\n \"colspan\":\"9\",\n \"class\":\"header\",\n \"placeholder\":\"Click here to edit\",\n \"active\":\"true\"\n }],\n disabled: true\n };\n $scope.widget.settings.data[$index].type = \"header\";\n $scope.widget.settings.data[$index].value = $scope.table.rows[$index].contents[0].headervalue;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detects the trackinformation from the video title and temporarily saves it
function getTrackInfo(){ var feedback; if ((us_getTempData("artist")!=0) || (us_getTempData("track")!=0)) { feedback = "found"; } else { //Retrive trackinformation from database if (getDatabaseData()==true) { feedback = "found"; trackInfoFromDB = true; } else { //New detection of trackinformation if (location.href.indexOf("youtube.com/user/") != -1) { if (document.getElementById("playnav-curvideo-title")) { var titleContent = document.getElementById("playnav-curvideo-title").getElementsByTagName("a")[0].textContent; } else if (document.getElementsByClassName("channels-featured-video-details tile")[0]) { var titleContent = document.getElementsByClassName("channels-featured-video-details tile")[0].getElementsByTagName("a")[0].textContent; } } else { //Feather check if (document.getElementById("eow-title")) { var titleContentOriginal = document.getElementById("eow-title").textContent; } else if (document.getElementById("watch-headline-title")) { var titleContentOriginal = document.getElementById("watch-headline-title").textContent; } else if (document.getElementById("vt")) { var titleContentOriginal = document.getElementById("vt").textContent; } } //remove (*) and/or [*] to remove unimportant data var titleContent = titleContentOriginal.replace(/ *\([^)]*\) */g, ''); titleContent = titleContent.replace(/ *\[[^)]*\] */g, ''); //remove stupid HD info titleContent = titleContent.replace(/\W* HD( \W*)?/, ''); //get remix info var remixInfo = titleContentOriginal.match(/\([^)]*(?:remix|mix|cover|version|edit|booty?leg)\)/i); // var musicInfo = titleContent.split(" - "); if (musicInfo.length == 1) { musicInfo = titleContent.split("-"); } if (musicInfo.length == 1) { musicInfo = titleContent.split(":"); } if (musicInfo.length == 1) { musicInfo = titleContent.split(' "'); } //remove " and ' from musicInfo for (var i=0;i<musicInfo.length;i++) { musicInfo[i] = musicInfo[i].replace(/^\s*"|"\s*$/g, ''); musicInfo[i] = musicInfo[i].replace(/^\s*'|'\s*$/g, ''); } //remove feat. info for (var i=0;i<musicInfo.length;i++) { musicInfo[i] = musicInfo[i].replace(/ feat.* .*/, ''); musicInfo[i] = musicInfo[i].replace(/ feat.* .*/, ''); } if ((musicInfo.length == 1)||(musicInfo[0] == false) || (musicInfo[1] == false)) { musicInfo[0] = ""; musicInfo[1] = ""; feedback = "notFound"; } else { //delete spaces musicInfo[0] = " " + musicInfo[0] + " "; musicInfo[0] = musicInfo[0].replace(/^\s\s*/, '').replace(/\s\s*$/, ''); musicInfo[1] = musicInfo[1].replace(/^\s\s*/, '').replace(/\s\s*$/, ''); //add remix info if(remixInfo && remixInfo.length == 1){ musicInfo[1] += " " + remixInfo[0]; } feedback = "found"; } if (us_getValue("us_autoscrobble_active", 0) == 1) { if ((musicInfo.length != 2)) { feedback = "bad"; } } if (!us_getTempData("artist")) { us_saveTempData("artist", encodeURIComponent(musicInfo[0])); } if (!us_getTempData("track")) { us_saveTempData("track", encodeURIComponent(musicInfo[1])); } } } return feedback; }
[ "function handleTrack(info){\n setInfoTracks(info)\n }", "function processCurrenttrack (data) {\n setSongInfo(data)\n mopidy.playback.getStreamTitle().then(function (title) {\n setStreamTitle(title)\n }, console.error)\n}", "function saveMediaTracks(tarcks) {\n tarcks.forEach(function(item) {\n switch(item.type){\n case 'text':\n caphPlayer.textTracks[item.language] = item;\n break;\n case 'video':\n caphPlayer.videoTracks[item.width] = item;\n break;\n case 'audio':\n caphPlayer.audioTracks[item.language] = item;\n break;\n default:\n console.log('unknow tracks type');\n break;\n }\n });\n }", "function getTrackInfo()\n{\n\treturn decodeURIComponent(basename(document.querySelector('#audioPlayer').currentSrc, '/', true)).split(/ - (.+)/);\n}", "function videoAndSubtitleTracking() {\n\n videojs('video_player').on('ready', function() {\n updateHighlightedCaption();\n });\n\n // listening for event fired when initial duration and dimension\n // information is ready\n videojs('video_player').on('loadedmetadata', function() {\n // keeping track of current video's duration\n duration_ = videojs('video_player').duration();\n _current_index = 0;\n updateHighlightedCaption();\n });\n\n // listening for event fired when video is paused\n // loads captions for current time in caption editor container\n videojs('video_player').on('pause', function() {\n console.log(\"Paused\");\n doLoadCurrentCaption();\n });\n\n // updates current subtitle based on time update\n videojs('video_player').on('timeupdate', function () {\n findCurrentCaption(this.currentTime());\n });\n\n // listening to event fired when video ends\n videojs('video_player').on('ended', function() {\n storeUpdatedCaptions();\n });\n}", "function trackRelatedVideo(videoTitle) {\n var s = s_gi(s_account);\n s.eVar1= \"Related Video played: \" +videoTitle;\n s.trackExternalLinks = false;\n s.linkTrackEvents = s.events = 'event10';\n s.linkTrackVars = 'eVar1,events';\n s.tl(this, 'o', s.eVar1);\n}", "function GS_getTrack( ) {\n var track = $(\"div#now-playing-metadata a.song\").attr('title');\n if( track == undefined ) {\n // Fall back to text portion if title attr is empty\n track = $(\"div#now-playing-metadata a.song\").text();\n }\n return GS_cleanLabel( track );\n}", "saveTrackForNextTime() {\n\t\tif (PlayerUi.hasFailed()) {\n\t\t\treturn;\n\t\t}\n\n\t\tlocalStorage.setItem(this.lastTrack.title, `${this.currentTrack}`);\n\t\tlocalStorage.setItem(this.lastTrack.playTime, `${timeToSeconds(PlayerUi.getCurrentTime())}`);\n\t}", "function loadVideoFromSaved(info) {\n stopTime = true;\n storage = info;\n syncStorage();\n\n window.location.href = \"http://www.ytmarker.com/\";\n}", "function processCurrenttrack (data) {\n setSongInfo(data)\n}", "function saveCCStatePlayer1() {\n textTrackToShow = 0;\n for (var i = 0; i < myPlayer.textTracks().length; i++) {\n //console.log(\"Texttrack \" + i + \" showing? \" + myPlayer.textTracks()[i].mode);\n if ((myPlayer.textTracks()[i].mode) == \"showing\") {\n textTrackToShow = i;\n }\n }\n }", "function stlClearTrack() {\r\n videoSubtitle.track.mode = \"disabled\";\r\n videoSubtitle.remove();\r\n videoSubtitle = document.createElement(\"track\");\r\n videoSubtitle.label = \"YTSubtitleLoader\";\r\n videoSubtitle.default = true;\r\n videoSubtitle.src = \"data:text/vtt,\";\r\n video.appendChild(videoSubtitle);\r\n}", "function on_playback_dynamic_info_track() {}", "function handleTrackInfo(trackData, pushHistory)\n{\n setTrackData(trackData, false);\n\n // After track data is set (track, track1, or track2) objects, push history\n if (pushHistory)\n {\n pushStateToHistory();\n }\n\n // Audio playing from http://jsfiddle.net/JMPerez/0u0v7e1b/\n pausePlayingRecord();\n\n if (trackData.preview_url) // some songs don't have previews. Try \"Gimme Gimme\" by Louis La Roche - spotify:track:0EiwsLRU0PXK2cIjGXsiaa (works when searching?)\n {\n audioObject = new Audio(trackData.preview_url);\n audioObject.addEventListener('ended', function() {\n hideRecord($('.album-image-cont.playing .record'), 400);\n });\n }\n else\n {\n audioObject = null;\n }\n\n const imgUrl = trackData.album.images[0].url;\n const trackObj = {\n imgUrl,\n name: trackData.name,\n artists: 'by ' + combineArtists(trackData.artists)\n };\n\n if (VueApp.currentView === 'song-compare') {\n if (VueApp.selectedTrackNum === 1) {\n VueApp.track1 = trackObj;\n }\n else {\n VueApp.track2 = trackObj;\n }\n }\n // If viewing individual song, update title\n else if (VueApp.currentView === 'song')\n {\n VueApp.track = trackObj;\n }\n}", "function saveVideotemph(videopath)\n{\n\t var db = window.openDatabase(\"Fieldtracker\", \"1.0\", \"Fieldtracker\", 50000000);\n db.transaction(function(tx){ QueryVideoTemph(tx,videopath) }, errorCB);\n}", "function getMediaTitleForTracking(event) {\r\n\t\t\tvar jdata = '';\r\n\t\t\tif (event != undefined) {\r\n\t\t\t\tjdata = event.jPlayer;\r\n\t\t\t} else {\r\n\t\t\t\tjdata = self.$elem.data(\"jPlayer\");\r\n\t\t\t}\r\n\t\t\tif (jdata.status.media.title && jdata.status.media.title.length > 0) {\r\n\t\t\t\treturn jdata.status.media.title;\r\n\t\t\t} else {\r\n\t\t\t\treturn jdata.status.src;\r\n\t\t\t}\r\n\t\t}", "loadedmetadata() {\n this.dusration = this.videoplayer.duration;\n //supports both video js and bright cove. We will be passing this value as part of metrics obj.\n this.properties.videoID = this.videoplayer.mediainfo\n ? this.videoplayer.mediainfo.id\n : this.videoplayer\n .currentSource()\n .src.split('/')\n .pop()\n .split('#')[0]\n .split('?')[0];\n this.properties.source = this.videoplayer.mediainfo\n ? 'brightcove'\n : 'videojs';\n }", "function findTrackByTitle(title) {\r\n //moved to dataholder\r\n //var i;\r\n //for (i = 0; i < tracks.length; i++) {\r\n // if (tracks[i].getTitle() === title) {\r\n // return tracks[i];\r\n // }\r\n //}\r\n //return null;\r\n return dataHolder.findTrackByTitle(title);\r\n }", "function displayCurrentTrack(track_title, artist) {\n var current_track = `<h4 id=\"currentTrack\" class=\"current_track_div\">${track_title} <small>By ${artist}</small></h4>`\n $(\"#currentTrack\").replaceWith(current_track);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The repository main class refreshes automatically the TTL of accessed entries, letting only unaccessed entries expire But tokens' TTL must remain the same than their expiration time, refreshing a token entry has no meaning. So we need to override the TTL autorefresh function to disable it
refreshCacheTTL() { // This comment is here to please Sonarqube. It requires a comment // explaining why a function is empty, but there is no sense // duplicating what has been just said in the JSDoc. // So, instead, here are the lyrics or Daft Punk's "Around the world": // // Around the world, around the world // Around the world, around the world // Around the world, around the world // Around the world, around the world // Around the world, around the world // [repeat 66 more times] // Around the world, around the world. }
[ "$$refreshToken() {\n if (this.$timeouts.refresh !== undefined) {\n clearTimeout(this.$timeouts.refresh);\n }\n\n if (this.$timeouts.expired !== undefined) {\n clearTimeout(this.$timeouts.expired);\n }\n\n const timeToExpiration = (this.profile.userInfo.exp * 1000) - Date.now();\n\n this.$timeouts.refresh = setTimeout(() => {\n // Allows Auto Refresh to be disabled\n if (this.$config.autoRefresh) {\n this.refreshToken().catch((error) => {\n console.error(error);\n });\n } else {\n this.$fire('refresh');\n }\n }, Math.max(timeToExpiration - this.$config.autoRefreshBuffer, 0));\n\n this.$timeouts.expired = setTimeout(() => {\n this.$fire('expired');\n }, Math.max(timeToExpiration, 0));\n }", "checkExpiration() {\n const interval = Number(this.options.refreshInterval);\n if (interval) {\n const time = getTime(-interval);\n this.invalidate(time);\n }\n }", "initializeTokenAutoRefresher () {\n if (this.options.autoRefreshToken) {\n let self = this\n this.tokenRefresher = {\n clearTimeout () {\n if (this.refreshTokenTimeout) {\n clearTimeout(this.refreshTokenTimeout)\n }\n },\n\n setTimeout (timeout) {\n this.clearTimeout()\n this.refreshTokenTimeout = setTimeout(this.refreshTokenHandler.bind(this), timeout * 1000)\n },\n\n refreshTokenHandler () {\n if (self.context.getters.logged) {\n return self.context.dispatch('refreshToken')\n }\n }\n }\n\n this.store.subscribe((mutation, state) => {\n if (mutation.type === this.prefix('logout')) {\n this.tokenRefresher.clearTimeout()\n }\n if (mutation.type === this.prefix('setLogged') && !this.context.logged) {\n this.tokenRefresher.clearTimeout()\n }\n if (mutation.type === this.prefix('setToken')) {\n this.tokenRefresher.clearTimeout()\n let token = this.context.getters.token\n let decodedToken = this.options.drivers.tokenDecoder.decode(token)\n let now = Math.floor(0 + new Date() / 1000)\n let serverNowDelta = now - decodedToken.iat\n let refreshIn = decodedToken.exp - decodedToken.iat - serverNowDelta - this.options.refreshTokenSecondsAhead\n refreshIn = Math.max(this.options.minRefreshTokenSeconds, refreshIn)\n refreshIn = Math.min(this.options.maxRefreshTokenSeconds, refreshIn)\n this.tokenRefresher.setTimeout(refreshIn)\n }\n })\n }\n }", "_cacheToken(token, expiresIn) {\n const preferences = this.get('preferences');\n const currentTime = Date.now();\n const timeToLive = expiresIn * 1000;\n const expiration = currentTime + timeToLive;\n\n preferences.tokenCache = { token, expiration };\n }", "getCachedToken() {\n if (this.cachedToken &&\n Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) {\n this.cachedToken = undefined;\n }\n return this.cachedToken;\n }", "static get GitHubApiCachingTimeout () { return 5 * 60 * 1000; }", "async expireEntries() {\n if (this._isRunning) {\n this._rerunRequested = !0;\n return;\n }\n this._isRunning = !0;\n const e = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1e3 : 0, t = await this._timestampModel.expireEntries(e, this._maxEntries), n = await self.caches.open(this._cacheName);\n for (const a of t)\n await n.delete(a, this._matchOptions);\n this._isRunning = !1, this._rerunRequested && (this._rerunRequested = !1, q(this.expireEntries()));\n }", "checkTTL() {\n\t\tlet now = Date.now();\n\t\tthis.cache.forEach((value, key) => {\n\t\t\tlet item = this.cache.get(key);\n\n\t\t\tif (item.expire && item.expire < now) {\n\t\t\t\tthis.logger.debug(`EXPIRED ${key}`);\n\t\t\t\tthis.metrics.increment(METRIC.MOLECULER_CACHER_EXPIRED_TOTAL);\n\t\t\t\tthis.cache.delete(key);\n\t\t\t}\n\t\t});\n\t}", "scheduleRenewal () {\n var expiresAt = JSON.parse(sessionStorage.getItem('expires_at'))\n var delay = expiresAt - Date.now()\n if (delay > 0) {\n var authService = this\n setTimeout(function () {\n authService.renewToken()\n }, delay)\n }\n console.log('access_token silent renewal scheduled after: ' + Math.round(delay / 1000 / 60) + ' mins')\n }", "refreshToken() {\n const token = this.getToken()\n if (token === null) {\n return ;\n }\n api.get(config.TC.TOKEN_REFRESH_URL, token, (res) => {\n const response = JSON.parse(res.response);\n const newToken = response.result.content.token;\n log('getting refresh token', newToken);\n if (newToken) {\n this.saveToken(newToken);\n }\n });\n }", "refreshToken () {\n const token = this.getToken()\n if (token === null) {\n return ;\n }\n api.get(config.TC.TOKEN_REFRESH_URL, token, (res) => {\n const response = JSON.parse(res.response);\n const newToken = response.result.content.token;\n log('getting refresh token', newToken);\n if (newToken) {\n this.saveToken(newToken);\n }\n });\n }", "newRefreshToken () {\n return this.withRefreshToken()\n }", "newRefreshToken() {\n return this.withRefreshToken()\n }", "_triggerRefresh () {\n const tokenData = this._parseJWT()\n // Subtract sixty seconds as a grace period before the token expires\n const interval = ((tokenData.exp - tokenData.iat) * 1000) / 2\n\n this.refreshLoopIndex = this._refreshLoop(interval)\n return this.refreshLoopIndex\n }", "removeExpiredTokens() {\n Object.keys(this.cache).forEach((t) => {\n if (!this.tokenIsValid(this.cache[t])) {\n this.removeToken(t);\n }\n });\n }", "onTokenChange() {\n cache.token = this.token;\n this.fetchData();\n }", "cmd_touch(cmdTokens, connection) {\n const key = cmdTokens[1];\n if (!this._cache.has(key)) {\n this._reply(connection, cmdTokens, replies.NOT_FOUND);\n } else {\n const e = this._cache.get(key);\n e.lifetime = +cmdTokens[2];\n this._reply(connection, cmdTokens, replies.TOUCHED);\n }\n }", "expired(valueWrapper,ttl=this.ttl){return !valueWrapper||valueWrapper.value===undefined||!valueWrapper.extraInfoObject||ttl>0&&this.cacheAccessor.nowTime>valueWrapper.extraInfoObject.serverFetchTime+ttl;}", "refreshApiTokenEveryFewMinutes() {\n this.lastRefreshedApiTokenAt = moment();\n\n setInterval(() => {\n this.refreshApiToken();\n }, 240000);\n\n setInterval(() => {\n if (moment().diff(this.lastRefreshedApiTokenAt, 'minutes') >= 5) {\n this.refreshApiToken();\n }\n }, 5000);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate loader string to be used with extract text plugin
function generateLoaders(loaders) { var sourceLoader = loaders .map(function(loader) { var extraParamChar; if (/\?/.test(loader)) { loader = loader.replace(/\?/, '-loader?'); extraParamChar = '&'; } else { loader = loader + '-loader'; extraParamChar = '?'; } return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : ''); }) .join('!'); return ExtractTextPlugin.extract(sourceLoader); }
[ "function generateExtractLoaders (baseLoader) {\n // Ignore the style loader (the first item), extractText doesn't need it\n var loaders = baseLoader.split('!').slice(1)\n\n // Get their plugin names and source maps\n return loaders.map(function (loader) {\n return loader + '-loader' + (SOURCE_MAP ? '?sourceMap' : '')\n }).join('!')\n}", "function generateExtractLoaders (loaders) {\n return loaders.map(function (loader) {\n return loader + '-loader' + (SOURCE_MAP ? '?sourceMap' : '')\n }).join('!')\n }", "function generateLoaders (loaders) {\n var sourceLoader = loaders.map(function (loader) {\n var extraParamChar\n if (/\\?/.test(loader)) {\n loader = loader.replace(/\\?/, '-loader?')\n extraParamChar = '&'\n } else {\n loader = loader + '-loader'\n extraParamChar = '?'\n }\n return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '')\n }).join('!')\n if (options.extract) {\n return ExtractTextPlugin.extract('style-loader', sourceLoader)\n } else {\n return ['style-loader', sourceLoader].join('!')\n }\n }", "function generateExtractLoaders(loaders) {\n return loaders.map(function (loader) {\n return loader + '-loader' + (SOURCE_MAP ? '?sourceMap' : '');\n }).join('!');\n }", "function generateLoaders(loaders) {\n var sourceLoader = loaders.map(function(loader) {\n var extraParamChar\n if (/\\?/.test(loader)) {\n loader = loader.replace(/\\?/, '-loader?')\n extraParamChar = '&'\n } else {\n loader = loader + '-loader'\n extraParamChar = '?'\n }\n return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '')\n }).join('!')\n\n if (options.extract) {\n return ExtractTextPlugin.extract('style-loader', sourceLoader)\n } else {\n return ['style-loader', sourceLoader].join('!')\n }\n }", "function generateLoaders(loaders) {\n\t var sourceLoader = loaders.map(function (loader) {\n\t var extraParamChar = void 0;\n\t if (/\\?/.test(loader)) {\n\t loader = loader.replace(/\\?/, '-loader?');\n\t extraParamChar = '&';\n\t } else {\n\t loader = loader + '-loader';\n\t extraParamChar = '?';\n\t }\n\t return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '');\n\t }).join('!');\n\t\n\t if (options.extract) {\n\t return ExtractTextPlugin.extract('vue-style-loader', sourceLoader);\n\t } else {\n\t return ['vue-style-loader', sourceLoader].join('!');\n\t }\n\t }", "function generateLoaders (loaders) {\n var sourceLoader = loaders.map(function (loader) {\n var extraParamChar;\n if (/\\?/.test(loader)) {\n loader = loader.replace(/\\?/, '-loader?');\n extraParamChar = '&';\n } else {\n loader = loader + '-loader';\n extraParamChar = '?';\n }\n return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '');\n }).join('!');\n\n if (options.extract) {\n return ExtractTextPlugin.extract('vue-style-loader', sourceLoader);\n } else {\n return ['vue-style-loader', sourceLoader].join('!');\n }\n }", "function applyLoader(text) {\n loaderCalls += 1;\n if (loaderCalls > 10) {\n return {\n text: \"Invalid alias chain\"\n };\n }\n for (var i = 0; i < loaders.length; i++) {\n var r = loaders[i].gen(text);\n if (r) {\n return r;\n }\n }\n}", "function getLoaderSnippet() {\n return `<script type=\"text/javascript\" src=\"${getLoaderUrl()}\" async ></script>`;\n}", "function loadingHTML(text) {\n return (\n \"<div class='actionContainer' id='loadingIcon'><div class='loader'></div>\" +\n text +\n \"...</div>\"\n );\n}", "function TW21Loader() {}", "function generateLoader() {\n IDM.$loader = document.createElement(\"div\");\n IDM.$loader.className = \"loader\";\n IDM.$loader.style.color = \"white\";\n IDM.$loader.style.position = \"absolute\";\n IDM.$loader.style.top = \"calc(100% - 4rem)\";\n IDM.$loader.style.left = \"0\";\n IDM.$loader.style.width = \"100%\";\n IDM.$loader.style.textAlign = \"center\";\n IDM.$loader.style.fontAeight = \"100\";\n IDM.$loader.style.lineAeight = \"1.8\";\n \n IDM.$loader_val = document.createElement(\"span\");\n IDM.$loader.appendChild(IDM.$loader_val);\n document.body.appendChild(IDM.$loader);\n }", "function stringifyLoaders (loaders) {\n return loaders\n .map(\n obj =>\n obj && typeof obj === 'object' && typeof obj.loader === 'string'\n ? obj.loader +\n (obj.options ? '?' + JSON.stringify(obj.options) : '')\n : obj\n )\n .join('!')\n }", "function GoLoader() {}", "function loader(content, map) {\n const source = content.replace(NEW_WORKER_WITH_STRING_RE, 'new Worker(new URL($1, import.meta.url))');\n this.callback(null, source, map);\n}", "function Loader() {\n\n}", "function loader() {\n\n if (dots < 3) {\n $('.javascriptspan').append('.');\n dots++;\n } else {\n $('.javascriptspan').html('');\n dots = 0;\n }\n }", "function TW21Loader() {\n}", "function LoaderBase() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
disconnectedCallback Implementation of the disconnectedCallback.
disconnectedCallback() { // Attach callback: this._pipeCallback('onDisconnect'); }
[ "disconnectedCallback() {\n this._disconnect();\n }", "disconnectedCallback () {\n // Unsubscribe to event listeners\n this.unsubscribeListeners()\n }", "disconnectedCallback() {\n super.disconnectedCallback();\n this.isAttached = false;\n this.detached();\n }", "disconnectedCallback() {\n this.removeEventListener(\n DATA_EVENT_NAME,\n this._listenerHandlers.handleDataChange\n );\n this.removeEventListener(\n DISCONNECT_EVENT_NAME,\n this._listenerHandlers.handleDataDeletion\n );\n }", "onClientDisconnected(callback) {\n this.discCallback = callback;\n }", "disconnectedCallback () {\n this.unsubscribeListeners()\n this._websocket.close()\n }", "disconnectedCallback() {\n super.disconnectedCallback();\n if (this.lazyLoad && this._lazyLoadPending && window.plasticImageIntersectionObserver) {\n window.plasticImageIntersectionObserver.observer.unobserve(this);\n // Firefox is frequently calling disconnectedCallback twice\n // per element. So basically this counter is useless,\n // but on the bright side, it's no longer needed.\n if (window.plasticImageIntersectionObserver.counter > 0) {\n window.plasticImageIntersectionObserver.counter--;\n }\n }\n }", "disconnectedCallback () {\r\n console.log('Component disconnect!')\r\n }", "disconnectedCallback () {\n console.log('Component disconnect!')\n }", "disconnectedCallback() {\n if (!this.__isUpgradeDisabled) {\n super.disconnectedCallback();\n }\n }", "disconnectedCallback() {\n super.disconnectedCallback();\n log.debug(`Unsubscribing ${this._componentName} from i18n service`);\n this._unsubscribeToI18nService();\n }", "ondisconnect() {\n debug(\"got disconnect packet\");\n this._onclose(\"client namespace disconnect\");\n }", "onPeerDisconnected (peerInfo) {\n this.callbacks.peerDisconnected(peerInfo);\n // Turns out we don't have to do much, because the leave() function\n // called on the other end will terminate the PC which propagates to us\n }", "connectionClosedCallback() {\n if (!this.debug) {\n return;\n }\n console.log('connectionClosedCallback');\n }", "onSocketClose() {\n this.disconnected();\n }", "function onDisconnect() {\n disconnected.value = true;\n self.disconnected = disconnected;\n $log.log(\"monitor is disconnected\");\n }", "_afterDisconnected() {\n this._connected = false\n this.emit('disconnected')\n }", "function onDisconnected(error)\n {\n console.log('Device disconnected')\n }", "disconnectedCallback() {\n console.log('Adios del DOM')\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Price format check takes an input string and returns a boolean that indicates whether the string contains a number to two decimal places.
function priceFormatCheck(input) { var i = 0; do { if (i === input.length) { return false; } i++; } while (input.charAt(i) != '.'); return 2 === input.length - (i + 1); }
[ "function containsDecimals(amount) {\n return amount.split('.').length === 2;\n}", "function isPrice(str) {\n var price = parseFloat(str.trim());\n if (isNaN(price)) return false;\n return (price >= 0 && price <= 999999);\n }", "function checkIfOnlyPrice(field) {\n if (/^[0-9]+\\.?[0-9]{1,2}$/.test(field.value)) {\n setValid(field);\n return true;\n } else {\n setInvalid(field, `${field.dataset.helper} must contain only numbers`);\n return false;\n }\n}", "function isDecimal(value) {\n var regex = /^\\d+\\.\\d{0,2}$/;\n return regex.test(value);\n}", "function containsDecimal (string) {\n return string.includes(\".\");\n}", "checkStringForDecimal(string) {\n return /\\./.test(string);\n }", "function isdecimal(num) {\n return (/^\\d+(\\.\\d+)?$/.test(num + \"\"));\n}", "isPriceValid(price){\n\n if(isNaN(parseFloat(price))){\n return false;\n }\n \n if(price.length > 0){\n return true;\n } else {\n return false;\n }\n }", "function containsDecimalPlaces (string) {\n return (containsDecimal(string) && string.indexOf(\".\") < string.length - 1);\n}", "function validateTotalCost(total) {\n if (total.match(/^\\d+(\\.\\d{1,2})?$/)) {\n return true;\n } else {\n return false;\n }\n}", "function checkDecimalNotAllowed() {\n let equation = inputDisplay.textContent.split(\" \");\n let firstNum = equation[0];\n let mathOp = equation[1];\n let secondNum = equation[2];\n\n if (mathOp === undefined) mathOp = \"\";\n if (secondNum === undefined) secondNum = \"\";\n\n if (firstNum.length !== 0 && mathOp.length === 0\n && secondNum.length === 0 && firstNum.includes(\".\")) {\n return true\n } else if (firstNum.length !== 0 && mathOp.length !== 0\n && secondNum.length !== 0 && secondNum.includes(\".\")) {\n return true;\n }\n\n return false;\n}", "function validateUnformattedPrice(unformattedPrice) {\n return isNumeric(unformattedPrice);\n }", "function isDecimal (s) {\n return String(s).search (isDecimal_re) != -1\n}", "function isDecimal(str){\r\n\tvar isnum=true;\r\n\tif ((str==null) || (str==\"\")){\r\n\t\tisnum=true;\r\n\t\treturn isnum;\r\n\t}\r\n\r\n\tfor(j=0;j<str.length;j++){\r\n\t\tif(j==0 && str.substring(j, j+1) ==\"-\") { continue; } //if '-' is found at first position\r\n\r\n\t\tif((str.substring(j,j+1) !=\"0\") &&\r\n\t\t (str.substring(j,j+1) !=\"1\") &&\r\n\t\t (str.substring(j,j+1) !=\"2\") &&\r\n\t\t (str.substring(j,j+1) !=\"3\") &&\r\n\t\t (str.substring(j,j+1) !=\"4\") &&\r\n\t\t (str.substring(j,j+1) !=\"5\") &&\r\n\t\t (str.substring(j,j+1) !=\"6\") &&\r\n\t\t (str.substring(j,j+1) !=\"7\") &&\r\n\t\t (str.substring(j,j+1) !=\"8\") &&\r\n\t\t (str.substring(j,j+1) !=\"9\") &&\r\n\t\t (str.substring(j,j+1) !=\".\")) {\r\n\t\t\tisnum=false;\r\n\t\t}\r\n\t}\r\n\tvar indx1 = str.indexOf(\".\", 0);\r\n\tif(indx1!=-1){\r\n\t\tvar indx2=str.indexOf(\".\", indx1+1);\r\n\t\tif(indx2!=-1) isnum=false;\r\n\t}\r\n\treturn isnum;\r\n}", "function isPrice(formid, input_field, num_type, msg_field) {\n var number; // the number in the input_field\n var regex;\n \n number = document.getElementById(input_field).value;\n regex = /^[0-9\\x2C\\x2E]+$/; // can contain digits, comma and the decimal point \n \n // is number < 10000\n if (!priceLess10000(number)) {\n document.getElementById(msg_field).innerHTML = \"* Can contain price less or equal to 9,999.99\"; \n setVal(num_type, 'false');\n } else {\n if (number != '') { \n // if the value entered as a price is not a nuumber (if wildcards is true, number can contain a %, _)\n if (!regex.test(number)) { \n document.getElementById(msg_field).innerHTML = \"* Can contain only digits (and decimal point and comma)\"; \n setVal(num_type, 'false');\n } else { // number is a number which can contain comma and dot\n comma_pos = number.toString().indexOf(',');\n dot_pos = number.toString().indexOf('.');\n if (comma_pos != -1) { // if the number contains a comma\n if (dot_pos != -1) { // if the number contains a dot\n if (dot_pos - comma_pos == 4) { // the comma and dot exist and there are at the right position\n setVal(num_type, 'true');\n document.getElementById(msg_field).innerHTML = \"\"; // don't show the message (if there was one before)\n } else { // the comma and dot exist and there are NOT at the right position\n setVal(num_type, 'false');\n document.getElementById(msg_field).innerHTML = \"* Can contain price less or equal to 9,999.99\"; // show the message\n }\n } else { // the comma exists and the dot doesn't exist\n if (number.length - comma_pos == 4) {\n setVal(num_type, 'true');\n document.getElementById(msg_field).innerHTML = \"\"; // show the message\n } else {\n setVal(num_type, 'false');\n document.getElementById(msg_field).innerHTML = \"* Can contain price less or equal to 9,999.99\"; // show the message\n }\n }\n } else { // comma doesn't exist in the number ( however the dot(.) could exist)\n if (dot_pos == -1) { // if the dot doesn't exist (either)\n if (number.length <= 4) { // the number has to be less than 10000\n setVal(num_type, 'true');\n document.getElementById(msg_field).innerHTML = \"\"; // show no message\n } else {\n setVal(num_type, 'false');\n document.getElementById(msg_field).innerHTML = \"* Can contain price less or equal to 9,999.99\"; // show the message\n }\n } else { // the dot does exist\n if (number.length - dot_pos == 3) {\n setVal(num_type, 'true');\n document.getElementById(msg_field).innerHTML = \"\"; // show no message\n } else {\n setVal(num_type, 'false');\n document.getElementById(msg_field).innerHTML = \"* Can contain price less or equal to 9,999.99\"; // show the message\n }\n }\n }\n }\n } else { // the number is not entered\n setVal( num_type, 'true' );\n document.getElementById(msg_field).innerHTML = \"\"; // don't show the message (if there was one before)\n }\n }\n}", "function IsValidDecimal(value) {\n if (value.search(threeDigitDecimal) == -1) {\n return false;\n }\n else {\n return true;\n }\n}", "function fnCheckDecimal( Value, Format )\n{\n var Pos = Format.indexOf( \".\") ;\n var decimalRE ;\n\n //switch( Format.substring( Pos + 1 ).length )\n switch( Format )\n {\n // Cases for Upto 2 decimal digits\n case \"1234.10\":\n decimalRE = /^\\d+\\.\\d{2}$/\n break ;\n\n case \"-1234.10\":\n decimalRE = /^-\\d+\\.\\d{2}$/\n break ;\n\n case \"1,234.10\":\n decimalRE = /^\\d{1,3}(,\\d{3})+\\.\\d{2}$/\n break ;\n\n case \"-1,234.10\":\n decimalRE = /^-\\d{1,3}(,\\d{3})+\\.\\d{2}$/\n break ;\n\n // Cases for Upto 3 decimal digits\n case \"1234.210\":\n decimalRE = /^\\d+\\.\\d{3}$/\n break ;\n\n case \"-1234.210\":\n decimalRE = /^-\\d+\\.\\d{3}$/\n break ;\n\n case \"1,234.210\":\n decimalRE = /^\\d{1,3}(,\\d{3})+\\.\\d{3}$/\n break ;\n\n case \"-1,234.210\":\n decimalRE = /^-\\d{1,3}(,\\d{3})+\\.\\d{3}$/\n break ;\n\n // Cases for Upto 4 decimal digits\n case \"1234.3210\":\n decimalRE = /^\\d+\\.\\d{4}$/\n break ;\n\n case \"-1234.3210\":\n decimalRE = /^-\\d+\\.\\d{4}$/\n break ;\n\n case \"1,234.3210\":\n decimalRE = /^\\d{1,3}(,\\d{3})+\\.\\d{4}$/\n break ;\n\n case \"-1,234.3210\":\n decimalRE = /^-\\d{1,3}(,\\d{3})+\\.\\d{4}$/\n break ;\n\n default:\n decimalRE = /^\\d+\\.\\d+$/\n break ;\n }\n\n if( Value.match( decimalRE ) == null )\n {\n alert( \"Not a decimal number...\" ) ;\n return false ;\n }\n else\n {\n alert( \"Valid decimal number...\" ) ;\n return true ;\n }\n}", "function checkPrice()\r\n {\r\n //check if integer\r\n var reg1 = new RegExp(/^[0-9]+$/);\r\n //check if double\r\n //accepts 1.10 or 1.1\r\n var reg2 = new RegExp(/^[0-9]+\\.[0-9]{1,2}$/);\r\n \r\n if($(\"#price\").val()){ \r\n if(reg1.test($(\"#price\").val())){ \r\n return true;\r\n }\r\n else if(reg2.test($(\"#price\").val())){ \r\n return true;\r\n } \r\n else{\r\n alert(\"Invalid price input.\"); \r\n return false;\r\n }\r\n }\r\n else if($(\"#price\").val() == \"\"){ \r\n alert(\"Please input the rental price.\"); \r\n $(\"#price\").focus();\r\n return false;\r\n }\r\n else{\r\n alert(\"Please input the rental price.\"); \r\n $(\"#price\").focus();\r\n return false;\r\n }\r\n }", "function CheckAmount(value) {\r\n\tvar s = true;\r\n\tfor (var a = 0; a < value.length; a++) {\r\n\t\tvar c = value.substring(a, a+1);\r\n\t\tif (c < \"0\" || c > \"9\") {\r\n\t\t\tif (c == \".\") {\r\n\t\t\t\ts = true\r\n\t\t\t} else {\r\n\t\t\t\ts = false\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (s == true) {\r\n\t\treturn true;\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that is mainly responsible for the PDF creation. Calls a nested function in itself while ensuring that a specific amount of "TIME LIMIT" has been surpassed. The TIME LIMIT is extremely crucial.
function timeLoop(){ setTimeout(function () { /** * I added this alert to avoid the awkwardness of the "wait" feeling. * You will get a better understanding of this when you will reach the TIME LIMIT section. */ alert("An Executive PDF will be generated."); /** * By going to the 'inspect elements' category of the Reports side of the website, I believe that the * main part of the entire page, that contains all the information, the graphs and the further details * all of it comes under the ID=content. Therefore I have already predefined it here with my program to make * it a little easier. * * This part of the code is essentially taking all the information that is in the (content) ID- tag and * making that into a a PDF. * * In order for this to work for the execution of the ISORA program, you might have to change the line of * code to: * ...drawDOM($("#content")).then(...){...} #73 * * Since I am not able to run the code for the ISORA code myself, I cant help you with this check, but this is * a small thing, so I am certain that a line of code would be fine to change. */ kendo.drawing.drawDOM("#content").then(function(group) { kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf"); }); /** * This is the TIME LIMIT. * * This is probably the most IMPORTANT number in the program as based on this only would you be able to * get the entire PDF, which includes the "opened up" ORG_UNIT_QUESTIONS. * * So the problem with the setTimeout() is that it would go about being executed, that is the first parameter, * only after the set number of time has completed. According to the documentation, it says that the second * parameter holds the number of milliseconds, but I am fairly certain that its not that. I am not sure what the * timer is based on though. * * So yeah, make sure that this number is big enough to handle the "scrolling down" of the ORG_UNIT_QUESTION * categories to give a detailed view of of each category, otherwise not all the details will be viewed on the * PDF or maybe not a single extra detail will be viewed, provided that the number becomes too small. * * So in order to avoid the awkwardness of the "wait" feeling, I added an alert at the beginning of this * function to make it appear that "there is some background work occurring". * * The mathematical approach, at least I think could be like a start, could possibly be: * Total # of Q. from all categories = x * Transition effect of an individual category = k (as it would most likely remain constant) * * Total TIME LIMIT = k*x*1000 * * Also, about 30000 is roughly 30 seconds, so in case the math is completely flawed then you could * look at it more objectively as per each category and come up with a common number I guess... * */ }, 900) }
[ "function delay(email1,email2,email3) {\n \n // add 5 minute delay before calling pdf/email function\n Utilities.sleep(300 * 1000);\n \n dataIntoPDF(email1,email2,email3);\n}", "function generatePDF(mode) {\n // Page start drawing from here...\n resetTotalImagesCaptions();\n var isMobile = {\n Android: function() {\n return navigator.userAgent.match(/Android/i);\n },\n BlackBerry: function() {\n return navigator.userAgent.match(/BlackBerry/i);\n },\n iOS: function() {\n return navigator.userAgent.match(/iPhone|iPad|iPod/i);\n },\n Opera: function() {\n return navigator.userAgent.match(/Opera Mini/i);\n },\n Windows: function() {\n return navigator.userAgent.match(/IEMobile/i);\n },\n any: function() {\n return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());\n }\n };\n var docDefinition = {\n footer: function (currentPage, pageCount) {\n if (currentPage === 1)\n {\n return {\n columns: [\n determineFrontPageFooter(mode),\n {\n text: '\\nPage | ' + currentPage.toString() + ' of ' + pageCount,\n alignment: 'right',\n margin: [0, 0, 40, 0],\n fontSize: 10,\n color:'grey',\n bold:true\n }\n ]\n };\n }\n else\n {\n return {\n columns: [\n determineFooter(mode),\n {\n text: '\\nPage | ' + currentPage.toString() + ' of ' + pageCount,\n alignment: 'left',\n margin: [10, 0, 40, 0],\n fontSize: 10,\n color:'grey',\n bold:true\n }\n ]\n };\n }\n },\n content: [\n /**\n * (1) Cover Page\n * */\n {\n\n stack: [\n\n {\n columns: [\n {\n // Draw Cover Page image\n image: coverPageLogo,\n width: 130,\n height: 130\n },\n {\n text: \"Architect's Advice Report\",\n style: 'coverPageHeader'\n // alignment:'right'\n }\n ]\n },\n giveMeHugeDraft(mode),\n {\n table:{\n // widths: ['*', '*'],\n body:[\n [\n {\n border: [true, true, false, true],\n text: archAdviceReportText,\n alignment:'justify',\n fontSize: 9,\n margin:[10,10,10,10]\n },\n {\n border: [false, true, true, true],\n stack: [\n getCoverImage('AdviceCoverImage')\n ],\n margin:[10,10,10,10]\n }\n ]\n ]\n },\n layout:{\n hLineWidth: function (i, node) {\n return (i === 0 || i === node.table.body.length) ? 2 : 1;\n },\n vLineWidth: function (i, node) {\n return (i === 0 || i === node.table.widths.length) ? 2 : 1;\n },\n hLineColor: function (i, node) {\n return (i === 0 || i === node.table.body.length) ? '#FFE599' : '#FFE599';\n },\n vLineColor: function (i, node) {\n return (i === 0 || i === node.table.widths.length) ? '#FFE599' : '#FFE599';\n }\n }\n },\n {\n text: \"Architect's Advice Report Details\",\n style: 'pageTopHeader',\n margin: [0, 30, 0, 5]\n },\n getCustomerDetailsTable(),\n makeAGap(),\n getAssessmentDetailsTable(),\n makeAGap(),\n getAssessorDetailsTable(),\n {\n text: 'Report Charges\\n This report covers up to 2 hours of the Architect’s time which includes consultation and Report writing. An additional hourly charge is payable for reports exceeding this time.',\n fontSize:9,\n absolutePosition: {x: 41, y: 730}\n\n }\n ],\n pageBreak: 'after'\n },\n\n /**\n * (2) The Scope of Advice Page\n * */\n {\n stack: [\n {\n text: 'Report Scope',\n style: 'pageTopHeader'\n },\n makeAGap(),\n {\n alignment: 'justify',\n columns: [\n {\n stack: [\n {\n text:'Included in this Report..',\n style: 'pageSubHeader'\n },\n {\n text: whatIncText1,\n style: 'paragraphMargin'\n },\n {\n text: whatIncText2,\n style: 'paragraphMargin'\n },\n {\n text: whatIncText3,\n style: 'paragraphMargin'\n },\n {\n ul:[\n {\n text:whatIncBulletList1,\n style: 'bulletMargin'\n },\n {\n text:whatIncBulletList2,\n style: 'bulletMargin'\n },\n {\n text:whatIncBulletList3,\n style: 'bulletMargin'\n }\n ]\n\n },\n {\n text:whatIncText4,\n style: 'paragraphMargin'\n },\n {\n ul:[\n {\n text:whatIncBulletList4,\n style: 'bulletMargin'\n },\n {\n text:whatIncBulletList5,\n style: 'bulletMargin'\n }\n ]\n },\n makeAGap(),\n {\n text: 'Not included in this Report',\n style: 'pageSubHeader'\n },\n {\n text: whatNotIncText,\n style: 'paragraphMargin'\n },\n {\n ul:[\n {\n text:whatNotIncBulletList1,\n style: 'bulletMargin'\n },\n {\n text:whatNotIncBulletList2,\n style: 'bulletMargin'\n },\n {\n text:whatNotIncBulletList3,\n style: 'bulletMargin'\n },\n {\n text:whatNotIncBulletList4,\n style: 'bulletMargin'\n },\n {\n text:whatNotIncBulletList5,\n style: 'bulletMargin'\n }\n ]\n }\n ],\n style: 'colText'\n },\n {\n stack: [\n {\n ul: [\n {\n stack:[\n {\n text:whatNotIncBulletList6,\n style:'bulletMargin'\n },\n {\n ul:[\n {\n text:whatNotIncBulletList6a,\n style:'bulletMargin'\n },\n {\n text:whatNotIncBulletList6b,\n style:'bulletMargin'\n },\n {\n text:whatNotIncBulletList6c,\n style:'bulletMargin'\n },\n {\n text:whatNotIncBulletList6d,\n style:'bulletMargin'\n },\n {\n text:whatNotIncBulletList6e,\n style:'bulletMargin'\n },\n {\n text:whatNotIncBulletList6f,\n style:'bulletMargin'\n },\n {\n text:whatNotIncBulletList6g,\n style:'bulletMargin'\n }\n ]\n }\n ]\n },\n {\n text:whatNotIncBulletList7,\n style: 'bulletMargin'\n },\n {\n text:whatNotIncBulletList8,\n style: 'bulletMargin'\n }\n ]\n },\n makeAGap(),\n {\n text: 'Report Standard',\n style: 'pageSubHeader'\n },\n {\n text:reportStandard1,\n style: 'paragraphMargin'\n },\n {\n text:reportStandard2,\n style: 'paragraphMargin'\n }\n ],\n style: 'colText'\n }\n ],\n columnGap: 20\n }\n ],\n pageBreak: 'after'\n },\n\n /**\n * (3) Advice Summary Page\n */\n {\n stack:[\n {\n text:\"Architect's Advice\",\n style:'pageTopHeader',\n margin:[0,0,0,5]\n },\n //makeAGap(),\n getAdviceTable()\n ],\n pageBreak:'after'\n },\n\n /**\n * (4)Attachments\n * */\n {\n stack:[\n {\n text: 'Attachment',\n style: 'pageTopHeader'\n },\n makeAGap(),\n {\n text: [\n attachmentText1,\n {\n text: 'http://www.archicentreaustralia.com.au/report_downloads/',\n link: \"http://www.archicentreaustralia.com.au/report_downloads/\",\n color: 'red',\n decoration: \"underline\"\n },\n attachmentText2\n ],\n style: 'tableText',\n alignment: 'justify',\n margin: [0, 0, 0, 6]\n },\n\n makeAGap(),\n getAttachmentTable(),\n makeAGap(),\n {\n text:'Definitions',\n style:'pageTopHeader'\n },\n makeAGap(),\n {\n columns:[\n {\n stack:[\n {\n text:definitions1,\n style: 'paragraphMargin'\n },\n {\n text:definitions2,\n style: 'paragraphMargin'\n }\n ],\n style: 'colText'\n },\n {\n stack:[\n {\n text:definitions3,\n style: 'paragraphMargin'\n },\n {\n text:definitions4,\n style: 'paragraphMargin'\n }\n ],\n style: 'colText'\n }\n\n ],\n columnGap: 20\n }\n ],\n pageBreak: 'after'\n },\n /**\n * (5)Terms and Conditions\n * */\n {\n stack:[\n {\n text: 'Terms & Conditions',\n style: 'pageTopHeader'\n },\n makeAGap(),\n {\n alignment: 'justify',\n columns:[\n {\n stack:[\n {\n text:termConditionText1,\n style: 'paragraphMargin'\n },\n {\n text:termConditionText2,\n style: 'paragraphMargin'\n },\n {\n text:termConditionText3,\n style: 'paragraphMargin'\n },\n {\n text:termConditionText4,\n style: 'paragraphMargin'\n },\n {\n ol:[\n {\n text: termConditionBulletList1,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList2,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList3,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList4,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList5,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList6,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList7,\n style: 'bulletMargin',\n alignment: 'justify'\n }\n ]\n }\n\n ], style: 'colText'\n },\n {\n stack:[\n {\n start: 8,\n ol:[\n {\n text: termConditionBulletList8,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList9,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList10,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList11,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList12,\n style: 'bulletMargin',\n alignment: 'justify'\n },\n {\n text: termConditionBulletList13,\n style: 'bulletMargin',\n alignment: 'justify'\n }\n ]\n }\n\n ],\n style: 'colText'\n }\n\n ],\n columnGap: 20\n }\n ],\n pageBreak: 'after'\n\n },\n\n /**\n * (6)Images\n * */\n {\n stack:[\n getImagesTable()\n ]\n }\n ],\n /**\n * Styles\n * */\n styles: {\n coverPageHeader: {\n fontSize: 26,\n bold: true,\n color: 'red',\n margin: [20, 50, 0, 50]\n },\n firstHeader: {\n fontSize: 20,\n color: 'red',\n bold: true,\n margin: [0, 0, 0, 20]\n },\n secondHeader: {\n fontSize: 17,\n color: 'red',\n bold: true,\n margin: [0, 0, 0, 10]\n },\n thirdHeader: {\n fontSize: 15,\n color: 'red',\n bold: true\n },\n fourthHeader: {\n fontSize: 20,\n color: 'red',\n bold: true\n },\n fifthHeader: {\n fontSize: 12,\n color: 'red',\n bold: true\n },\n paragraph1: {\n fontSize: 11,\n\n margin: [5, 2, 10, 100]\n },\n coverPageText: {\n margin: [0, 40, 0, 0]\n },\n coverPageSubHeader: {\n fontSize: 22,\n bold: true,\n color: 'red',\n margin: [0, 55, 0, 0]\n },\n boldText: {\n bold: true\n },\n table: {\n margin: [0, 15, 0, 15]\n },\n tableHeader: {\n fontSize: 10,\n bold: true,\n color: 'red'\n },\n pageTopHeader: {\n fontSize: 17,\n color: 'red',\n bold: true\n },\n tightTable: {\n margin: [0, 0, 30, 0]\n },\n smallText: {\n fontSize: 10,\n margin: [5, 2, 10, 100]\n },\n rowHeader: {\n fontSize: 12,\n bold: true\n },\n rowText: {\n fontSize: 12\n },\n tableBoldTextAlignLeft: {\n fontSize: 9,\n bold: true\n },\n pageTopHeader: {\n fontSize: 17,\n color: 'red',\n bold: true\n },\n colText: {\n fontSize: 9\n },\n paragraphMargin: {\n margin: [0, 0, 0, 6]\n },\n pageSubHeader: {\n fontSize: 11,\n color: 'red',\n bold: true,\n margin: [0, 0, 0, 6]\n },\n bulletMargin: {\n margin: [0, 0, 0, 5]\n },\n tableText: {\n fontSize: 9\n },\n tableLongBoldJustifiedText: {\n fontSize: 9,\n bold: true,\n alignment: 'justify'\n }\n }\n };\n // var imageNumber = $(\"#ConstructionImages\").find(\"img\").length;\n // console.log(imageNumber);\n // Open a new tab and show the PDF\n //pdfMake.createPdf(docDefinition).open();\n\n if (mode == 'save')\n {\n //console.log('click');\n //const pdfDocGenerator = pdfMake.createPdf(docDefinition);\n pdfMake.createPdf(docDefinition).getBase64(function(encodedString){\n var base64 = encodedString;\n doSavePDF(base64);\n //console.log(base64);\n });\n\n }\n //if the mode is final or preview, open the pdf directly\n else\n {\n if( isMobile.any() )\n {\n var reader = new FileReader();\n\n pdfMake.createPdf(docDefinition).getBlob(function(blob){\n reader.onload = function(e){\n //window.location.href = reader.result;\n window.open(reader.result,'_blank');\n };\n reader.readAsDataURL(blob);\n });\n }\n else\n {\n console.log(\"It is on pc\");\n pdfMake.createPdf(docDefinition).open();\n }\n //pdfMake.createPdf(docDefinition).open();\n //document.open();\n\n }\n\n\n}", "function generatePDF(mode) {\n //reset image number and general notes paragraphs number\n resetTotalCounting();\n\n var isMobile = {\n Android: function() {\n return navigator.userAgent.match(/Android/i);\n },\n BlackBerry: function() {\n return navigator.userAgent.match(/BlackBerry/i);\n },\n iOS: function() {\n return navigator.userAgent.match(/iPhone|iPad|iPod/i);\n },\n Opera: function() {\n return navigator.userAgent.match(/Opera Mini/i);\n },\n Windows: function() {\n return navigator.userAgent.match(/IEMobile/i);\n },\n any: function() {\n return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());\n }\n };\n // Page start drawing from here...\n\n var docDefinition = {\n footer: function (currentPage, pageCount) {\n if (currentPage === 1)\n {\n return {\n columns: [\n determineFrontPageFooter(mode),\n {\n text: '\\nPage | ' + currentPage.toString() + ' of ' + pageCount,\n alignment: 'right',\n margin: [0, 0, 40, 0],\n fontSize: 10,\n color:'grey',\n bold:true\n }\n ]\n };\n }\n else\n {\n return {\n columns: [\n determineFooter(mode),\n {\n text: '\\nPage | ' + currentPage.toString() + ' of ' + pageCount,\n alignment: 'left',\n margin: [10, 0, 40, 0],\n fontSize: 10,\n color:'grey',\n bold:true\n }\n ]\n };\n }\n },\n content: [\n /**\n * (1) Cover Page\n * */\n {\n\n stack: [\n\n [\n {\n // Draw Cover Page image\n image: coverPageLogo,\n width: 160,\n height: 160\n },\n giveMeHugeDraft(mode),\n {\n text:[\n 'Archicentre ',\n {\n text:'Australia \\n',\n color: 'red'\n },\n {\n text:'Property \\nAssessment \\n',\n bold:true\n },\n 'Report\\n',\n {\n text:'- Commercial, Industrial & Institutional',\n fontSize:22\n }\n ],\n style: 'coverPageHeader'\n }\n\n ]\n // {\n // text:'New Home Design',\n // style: 'pageTopHeader'\n // },\n // makeAGap(),\n // {\n // text:'Feasibility Study',\n // style:'thirdHeader'\n //\n // },\n // giveMeHugeDraft(mode),\n // {\n // alignment: 'justify',\n // columns: [\n // {\n // stack:[\n //\n // makeAGap(),\n // {\n // text: archHomeFeasibilityReportText1,\n // fontSize: 9\n // },\n // makeAGap(),\n // {\n // text: archHomeFeasibilityReportText2,\n // fontSize: 9\n // },\n // makeAGap(),\n // {\n // text: archHomeFeasibilityReportText3,\n // fontSize: 9\n // }\n // ]\n //\n // },\n // //ConstructionCoverImage\n // {\n // stack: [\n // makeAGap(),\n // displayCoverImage('HomeFeasibilityCoverImage')\n // ]\n //\n // }\n //\n // // displayImage('ConstructionCoverImage')\n // ],\n // columnGap: 20\n // },\n // {\n // text: \"Client's Details\",\n // style: 'pageTopHeader',\n // margin: [0, 40, 0, 5]\n // },\n // getCustomerDetailsTable(),\n // makeAGap(),\n // getAssessmentDetailsTable(),\n // makeAGap(),\n // getAssessorDetailsTable()\n ],\n pageBreak: 'after'\n },\n /**\n * (2) Report Detail Page\n */\n {\n stack:[\n giveMeHugeDraft(mode),\n {\n\n text:[\n {\n text:'Property Assessment Report',\n color: 'red'\n },\n {\n text:' - Commercial Industrial & Institutional',\n bold:false,\n fontSize:12,\n color:'black'\n }\n ],\n style:'pageTopHeader',\n margin:[0,5,0,10]\n\n },\n {\n text:PropertyAssessmentReport,\n fontSize:10,\n margin:[0,5,0,20]\n },\n getClientDetailsTable(),\n getAssessmentDetailsTable(),\n getArchitectDetailsTable(),\n getPropertySummary()\n // getInspectionDetailsTable(),\n // getInspectorDetailsTable(),\n // getReportAuthorisation(),\n // getDoneWork(),\n // {\n // text:'Inspection Summary',\n // style:'pageTopHeader',\n // margin:[0,20,0,5]\n //\n // },\n // getInspectionSummary(),\n // {\n // text:'Descriptive Summary of Work done by Owner-Builder',\n // style:'pageTopHeader',\n // margin:[0,20,0,5]\n // },\n // getDescriptiveSummary()\n ],\n pageBreak: 'after'\n },\n\n /**\n * (3) The Scope of Page\n * */\n {\n stack: [\n {\n text: 'The Scope of Assessment',\n style: 'pageTopHeader',\n margin:[0,5,0,0]\n },\n {\n alignment:'justify',\n columns:[\n {\n stack:[\n {\n text:ScopeOfAssessment1,\n style:'colText'\n },\n {\n text:ScopeOfAssessment2,\n style:'colText'\n },\n {\n text:ScopeOfAssessment3,\n style:'colText'\n },\n {\n text:ScopeOfAssessment4,\n style:'colText'\n },\n {\n text:ScopeOfAssessment5,\n style:'colText'\n },\n {\n text:ScopeOfAssessment6,\n style:'colText'\n },\n {\n text:ScopeOfAssessment7,\n style:'colText'\n },\n {\n text:ScopeOfAssessment8,\n style:'colText'\n }\n ]\n },\n {\n stack:[\n {\n text:ScopeOfAssessment9,\n style:'colText'\n },\n {\n text:'What is included in this report',\n style: 'pageSubHeader'\n },\n {\n ul: [\n {\n text: ReportIncluded1,\n style:'colText'\n },\n {\n text: ReportIncluded2,\n style:'colText'\n },\n {\n text: ReportIncluded3,\n style:'colText'\n },\n {\n text: ReportIncluded4,\n style:'colText'\n },\n {\n text: ReportIncluded5,\n style:'colText'\n }\n ]\n },\n {\n text:'What is not included in this report',\n style: 'pageSubHeader'\n },\n {\n text:ReportNotRecorded0,\n style:'colText'\n },\n {\n ul: [\n {\n text: ReportNotRecorded1,\n style:'colText'\n },\n {\n text: ReportNotRecorded2,\n style:'colText'\n },\n {\n text: ReportNotRecorded3,\n style:'colText'\n },\n {\n text: ReportNotRecorded4,\n style:'colText'\n },\n {\n text: ReportNotRecorded5,\n style:'colText'\n },\n {\n text: ReportNotRecorded6,\n style:'colText'\n },\n {\n text: ReportNotRecorded7,\n style:'colText'\n },\n {\n text: ReportNotRecorded8,\n style:'colText'\n }\n ]\n }\n ]\n }\n ],\n columnGap: 20\n }\n ],\n pageBreak: 'after'\n },\n /**\n * (4) Attachment\n */\n {\n stack:[\n {\n text: 'Attachment',\n style: 'pageTopHeader',\n margin:[0,5,0,5]\n },\n {\n text:[\n {\n text:Attachments1,\n style: 'tableText'\n },\n {\n text: 'http://www.archicentreaustralia.com.au/report_downloads/ ',\n link: \"http://www.archicentreaustralia.com.au/report_downloads/\",\n color: 'red',\n decoration: \"underline\",\n style: 'tableText',\n margin:[0,0,0,5]\n },\n {\n text:Attachments2,\n style: 'tableText',\n margin:[0,5,0,10]\n }\n ]\n },\n getAttachmentTable(),\n {\n text: 'General Advice',\n style: 'pageTopHeader',\n margin:[0,10,0,5]\n },\n {\n alignment:'justify',\n columns:[\n {\n stack:[\n {\n ul: [\n {\n text: GeneralAdvice1,\n style:'colText'\n },\n {\n text: GeneralAdvice2,\n style:'colText'\n },\n {\n text: GeneralAdvice3,\n style:'colText'\n },\n {\n text: GeneralAdvice4,\n style:'colText'\n },\n {\n text: GeneralAdvice5,\n style:'colText'\n }\n ]\n }\n ]\n },\n {\n stack:[\n {\n ul: [\n {\n text: GeneralAdvice6,\n style:'colText'\n },\n {\n text: GeneralAdvice7,\n style:'colText'\n }\n ]\n },\n {\n text:'For Strata, Stratum and Company Title Properties',\n fontSize:10,\n bold:true,\n color:'black',\n margin:[0,20,0,5]\n },\n {\n text:GeneralAdvice8,\n style:'colText'\n }\n ]\n }\n ],\n columnGap: 20\n }\n ],\n pageBreak: 'after'\n },\n\n /**\n * (5) Terms & Conditions\n */\n {\n stack: [\n {\n text: 'Terms & Conditions',\n style: 'pageTopHeader',\n margin:[0,5,0,0]\n },\n\n {\n alignment:'justify',\n columns:[\n {\n stack:[\n {\n text:Conditions1,\n style:'colText'\n },\n {\n text:Conditions2,\n style:'colText'\n },\n {\n text:Conditions3,\n style:'colText'\n },\n {\n text:Conditions4,\n style:'colText'\n },\n {\n text:Conditions5,\n italics:true,\n style:'colText'\n },\n {\n ol:\n [\n {\n text: ConditionsNumber1,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber2,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber3,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber4,\n style:'colText',\n margin:[5,0,0,0]\n }\n ],\n fontSize:10\n }\n ]\n },\n {\n stack:[\n {\n start: 4,\n ol:\n [\n {\n text: ConditionsNumber4,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber5,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber6,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber7,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber8,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber9,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber10,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber11,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber12,\n style:'colText',\n margin:[5,0,0,0]\n },\n {\n text: ConditionsNumber13,\n style:'colText',\n margin:[5,0,0,0]\n }\n ],\n fontSize:10\n }\n ]\n }\n ],\n columnGap: 20\n }\n ],\n pageBreak: 'after'\n },\n\n /**\n * (6) Defect Definitions\n */\n {\n stack:[\n {\n text: 'Defect Definitions',\n style: 'pageTopHeader',\n margin:[0,5,0,0]\n },\n {\n table: {\n widths: [100, '*'],\n body: [\n [\n {},\n\n {\n text: 'DEFINITION',\n style: 'tableHeader'\n }\n ],\n [\n {\n text: 'Minor Defect/ Maintenance Item',\n fontSize:10,\n bold:true\n },\n {\n text:MinorDefect,\n fontSize:10\n }\n ],\n [\n {\n text: 'Major Defect',\n fontSize:10,\n bold:true\n },\n {\n stack:[\n {\n text:MajorDefect,\n fontSize:10\n },\n {\n ul:[\n {\n text:[\n MajorDefectBullet1,\n {\n text:'or',\n decoration: \"underline\"\n },\n {\n text:','\n }\n ],\n fontSize:10,\n margin:[0,2,0,2]\n },\n {\n text:[\n MajorDefectBullet2,\n {\n text:'or',\n decoration: \"underline\"\n },\n {\n text:','\n }\n ],\n fontSize:10,\n margin:[0,2,0,2]\n },\n {\n text: MajorDefectBullet3,\n fontSize:10,\n margin:[0,2,0,2]\n }\n ],\n margin:[5,2,0,3]\n\n }\n ]\n\n }\n\n ],\n [\n {\n text: 'Serious Structural Defect',\n fontSize:10,\n bold:true\n },\n {\n stack:[\n {\n text:SeriousDefect1,\n fontSize:10\n },\n {\n ul:[\n {\n text:[\n SeriousDefectBullet1,\n {\n text:'or',\n decoration: \"underline\"\n },\n {\n text:','\n }\n ],\n fontSize:10,\n margin:[0,2,0,2]\n },\n {\n text:[\n SeriousDefectBullet2,\n {\n text:'or',\n decoration: \"underline\"\n },\n {\n text:','\n }\n ],\n fontSize:10,\n margin:[0,2,0,2]\n },\n {\n text: SeriousDefectBullet3,\n fontSize:10,\n margin:[0,2,0,2]\n }\n ],\n margin:[5,2,0,3]\n\n },\n {\n text:SeriousDefect2,\n fontSize:10\n }\n ]\n\n }\n ]\n ]\n },\n margin:[0,10,0,20]\n },\n {\n text:'Assessment Access',\n style: 'pageTopHeader',\n margin:[0,5,0,0]\n },\n {\n alignment:'justify',\n columns:[\n {\n stack:[\n {\n text:AssessmentAccess1,\n style:'colText'\n },\n {\n text:AssessmentAccess2,\n style:'colText'\n },\n {\n text:AssessmentAccess3,\n style:'colText'\n }\n ]\n },\n {\n stack:[\n {\n text:AssessmentAccess4,\n style:'colText'\n },\n {\n text:AssessmentAccess5,\n style:'colText'\n },\n {\n text:AssessmentAccess6,\n style:'colText'\n }\n ]\n }\n ],\n columnGap: 20\n }\n\n\n ],\n pageBreak: 'after'\n },\n /**\n * (7) Property Assessment Summary\n */\n {\n stack:[\n {\n text: 'Your Property Assessment Summary',\n style: 'pageTopHeader',\n margin:[0,5,0,5]\n },\n {\n text:PropertyAssessmentSummary,\n fontSize:10,\n margin:[0,10,0,10]\n },\n {\n text:'Summary of the Condition of the Property:',\n style:'secondHeader'\n },\n {\n table:{\n widths:[400,'*'],\n body:[\n [\n {\n text:'Apparent condition of the building respect to its age',\n style:'thirdHeader'\n },\n {\n text:getIt('conditionOfBuilding'),\n fontSize:10\n }\n ]\n ]\n },\n margin:[0,3,0,10]\n },\n {\n text:'Major Defects:',\n style:'secondHeader'\n },\n {\n table:{\n widths:[400,'*'],\n body:[\n [\n {\n text:'Are there any Major Defects evident?',\n style:'thirdHeader'\n },\n {\n text:getIt('majorDefects'),\n fontSize:10\n }\n ]\n ]\n },\n margin:[0,3,0,10]\n },\n {\n text:'Serious Structural Defects:',\n style:'secondHeader'\n },\n {\n table:{\n widths:[400,'*'],\n body:[\n [\n {\n text:'Are there any Serious Structural Defects evident?',\n style:'thirdHeader'\n },\n {\n text:getIt('seriousDefects'),\n fontSize:10\n }\n ]\n ]\n },\n margin:[0,3,0,10]\n },\n {\n text:'Evident Defect Summary',\n style:'secondHeader'\n },\n getKeyTable(),\n getEvidentDefectTable(),\n getAssessmentSummary()\n ],\n pageBreak:'after'\n },\n /**\n * (8) Property Assessment Notes & Site\n */\n {\n stack:[\n {\n text: 'Property Assessment Notes',\n style: 'pageTopHeader'\n },\n {\n text: 'Professional and Trade Guide',\n style: 'secondHeader'\n },\n {\n text: 'Your architect may refer you to the following professional or tradespeople:',\n fontSize: 10,\n margin: [0, 0, 0, 10]\n },\n getTradeGuideTable(),\n {\n text: 'Site',\n style: 'pageTopHeader',\n margin:[0,20,0,10]\n },\n {\n text: 'Key',\n style: 'thirdHeader',\n margin:[0,2,0,0]\n },\n getKeyTable(),\n getSiteAreaTable(),\n getAccessLimitationTable('siteAccessLimitationsTable','siteAccessItem','siteAccessImageRef','SiteAccessSelect','siteAccessNotes'),\n getMinorDefectsTable('siteMinorDefectsTable','siteMaintenanceItemNo','siteMaintenanceImgRef','siteMaintenanceNotes','siteMinorRecommendationText'),\n getMajorDefectsTable('siteMajorDefectsTable','siteMajorItemNo','siteMajorImgRef','siteMajorNotes','siteMajorRecommendationText'),\n getGeneralNotes('siteGeneralNotes')\n ],\n pageBreak:'after'\n },\n /**\n * (9) Property Exterior\n */\n {\n stack:[\n {\n text: 'Property Exterior',\n style: 'pageTopHeader',\n margin:[0,20,0,10]\n },\n {\n text: 'Key',\n style: 'thirdHeader',\n margin:[0,2,0,0]\n },\n getKeyTable(),\n getAreaTable('exteriorArea','exteriorAreaName','exteriorAreaRow'),\n getAccessLimitationTable('exteriorAccessLimitationsTable','exteriorAccessItem','exteriorAccessImageRef','exteriorAccessSelect','exteriorAccessNotes'),\n getMinorDefectsTable('exteriorMinorDefectsTable','exteriorMinorDefectItemNo','exteriorMinorDefectImgRef','exteriorMinorDefectNotes','exteriorMinorRecommendationText'),\n getMajorDefectsTable('exteriorMajorDefectsTable','exteriorMajorItemNo','exteriorMajorImgRef','exteriorMajorNotes','exteriorMajorRecommendationText'),\n getGeneralNotes('exteriorGeneralNotes')\n\n // getSiteAreaTable(),\n // getAccessLimitationTable(),\n // getMinorDefectsTable(),\n // getMajorDefectsTable(),\n // getGeneralNotes()\n ],\n pageBreak:'after'\n },\n /**\n * (10) Property Interior - Dry Areas\n */\n {\n stack:[\n {\n text: 'Property Interior – Dry Areas',\n style: 'pageTopHeader',\n margin:[0,20,0,10]\n },\n {\n text: 'Key',\n style: 'thirdHeader',\n margin:[0,2,0,0]\n },\n getKeyTable(),\n getAreaTable('InteriorDryArea','InteriorDryAreaName','InteriorDryAreaRow'),\n getAccessLimitationTable('interiorDryAccessLimitationsTable','interiorDryAccessItem','interiorDryAccessImageRef','interiorDryAccessSelect','interiorDryAccessNotes'),\n getMinorDefectsTable('interiorDryMinorTable','interiorDryMinorItemNo','interiorDryMinorImgRef','interiorDryMinorNotes','interiorDryMinorRecommendationText'),\n getMajorDefectsTable('interiorDryMajorTable','interiorDryMajorItemNo','interiorDryMajorImgRef','interiorDryMajorNotes','interiorDryMajorRecommendationText'),\n getGeneralNotes('interiorDryGeneralNotes')\n ],\n pageBreak:'after'\n },\n /**\n * (11) Property Interior - Wet Areas\n */\n {\n stack:[\n {\n text: 'Property Interior – Service (wet) Areas',\n style: 'pageTopHeader',\n margin:[0,20,0,10]\n },\n {\n text: 'Key',\n style: 'thirdHeader',\n margin:[0,2,0,0]\n },\n getKeyTable(),\n getAreaTable('InteriorWetArea','InteriorWetAreaName','InteriorWetAreaRow'),\n getAccessLimitationTable('interiorWetAccessLimitationsTable','interiorWetAccessItem','interiorWetAccessImageRef','interiorWetAccessSelect','interiorWetAccessNotes'),\n getMinorDefectsTable('interiorWetMinorTable','interiorWetMinorItemNo','interiorWetMinorImgRef','interiorWetMinorNotes','interiorWetMinorRecommendationText'),\n getMajorDefectsTable('interiorWetMajorTable','interiorWetMajorItemNo','interiorWetMajorImgRef','interiorWetMajorNotes','interiorWetMajorRecommendationText'),\n getGeneralNotes('interiorWetMajorGeneralNotes')\n ],\n pageBreak:'after'\n },\n /**\n * Photographs\n */\n {\n stack:[\n getImages()\n ]\n }\n ],\n /**\n * Styles\n * */\n styles: {\n coverPageHeader: {\n fontSize: 50,\n color: 'black',\n italics: true,\n margin: [20, 50, 0, 100]\n },\n pageTopHeader: {\n fontSize: 20,\n color: 'red',\n bold: true\n },\n pageSubHeader: {\n fontSize: 11,\n color: 'red',\n bold: true,\n margin: [0, 0, 0, 2]\n },\n colText: {\n fontSize: 10,\n margin:[0,2,0,2]\n },\n secondHeader: {\n fontSize: 14,\n color: 'red',\n bold: true,\n margin: [0, 0, 0, 3]\n },\n thirdHeader: {\n fontSize: 12,\n color: 'red',\n bold: true\n },\n tableText: {\n fontSize: 10\n },\n\n\n\n\n\n firstHeader: {\n fontSize: 20,\n color: 'red',\n bold: true,\n margin: [0, 0, 0, 20]\n },\n\n\n fourthHeader: {\n fontSize: 20,\n color: 'red',\n bold: true\n },\n fifthHeader: {\n fontSize: 12,\n color: 'red',\n bold: true\n },\n paragraph1: {\n fontSize: 11,\n\n margin: [5, 2, 10, 100]\n },\n coverPageText: {\n margin: [0, 40, 0, 0]\n },\n coverPageSubHeader: {\n fontSize: 22,\n bold: true,\n color: 'red',\n margin: [0, 55, 0, 0]\n },\n boldText: {\n bold: true\n },\n table: {\n margin: [0, 15, 0, 15]\n },\n tableHeader: {\n fontSize: 10,\n bold: true,\n color: 'red'\n },\n pageTopHeader: {\n fontSize: 17,\n color: 'red',\n bold: true\n },\n tightTable: {\n margin: [0, 0, 30, 0]\n },\n smallText: {\n fontSize: 10,\n margin: [5, 2, 10, 100]\n },\n rowHeader: {\n fontSize: 12,\n bold: true\n },\n rowText: {\n fontSize: 12\n },\n tableBoldTextAlignLeft: {\n fontSize: 9,\n bold: true\n },\n\n\n paragraphMargin: {\n margin: [0, 0, 0, 6]\n },\n\n bulletMargin: {\n margin: [0, 0, 0, 5]\n },\n\n tableLongBoldJustifiedText: {\n fontSize: 9,\n bold: true,\n alignment: 'justify'\n }\n }\n };\n // Open a new tab and show the PDF\n if (mode == 'save')\n {\n //console.log('click');\n //const pdfDocGenerator = pdfMake.createPdf(docDefinition);\n pdfMake.createPdf(docDefinition).getBase64(function(encodedString){\n var base64 = encodedString;\n //$('#savingPDFAlert').show('fade');\n doSavePDF(base64);\n //console.log(base64);\n });\n\n }\n //if the mode is final or preview, open the pdf directly, depends on what device the user is using\n else\n {\n if( isMobile.any() )\n {\n var reader = new FileReader();\n\n pdfMake.createPdf(docDefinition).getBlob(function(blob){\n reader.onload = function(e){\n //window.location.href = reader.result;\n window.open(reader.result,'_blank');\n };\n reader.readAsDataURL(blob);\n });\n }\n else\n {\n console.log(\"It is on pc\");\n pdfMake.createPdf(docDefinition).open();\n }\n\n }\n\n\n}", "function spPDFReportGeneration(){\n\tspCommonReportCreating('sp_pdf_report_genrating.py','UBR_PDF_Report.pdf');\n}", "function generaPDFsolicitudAdicional(vista_previa){\n var fecha_pdf = new Date();\n var obra = $('#'+ id_ddl_obraSolicitudAdicional + ' option:selected').text();\n var solicitud = generaClaveSolicitudAdicional();\n var atencion = $('#'+ id_ddl_atnSolicitudAdicional + ' option:selected').text();\n var descripcion = $('#'+ id_descripcionSolicitudAdicional).val();\n var anexos_seleccionados = selectAnexos.selected();\n var otros;\n if(anexos_seleccionados.includes(\"AN-05\")){\n otros = $('#'+ id_otroSolicitudAdicional).val();\n } else {\n otros = \"\";\n }\n var indices_seleccionados = selectImagenes.selected();\n var fotos_seleccionadas=[];\n var leyendas_seleccionadas=[];\n for(i=0; i<indices_seleccionados.length; i++){\n fotos_seleccionadas.push(array_fotosAnexos[indices_seleccionados[i]]);\n leyendas_seleccionadas.push(array_leyendasAnexos[indices_seleccionados[i]]);\n }\n console.log(fotos_seleccionadas[0]);\n //console.log(vista_previa, obra, solicitud, descripcion, atencion, json_anexos, anexos_seleccionados, otros, fotos_seleccionadas, leyendas_seleccionadas, fecha_pdf , colaborador);\n var pdfDocGenerator = pdfMake.createPdf(generaSolicitudAdic(vista_previa, obra, solicitud, descripcion, atencion, json_anexos, anexos_seleccionados, otros, fotos_seleccionadas, leyendas_seleccionadas, fecha_pdf , colaborador));\n return pdfDocGenerator;\n}", "function spPDFReportGeneration() {\n spCommonReportCreating('sp_pdf_report_genrating.py', 'UBR_PDF_Report.pdf');\n}", "function createTimeout() {\n window.clearTimeout(changeTimeout);\n resetTimeoutAnimation();\n changeTimeout = setTimeout(function() {\n if (curPage >= numOfPages) {\n curPage = 1;\n } else {\n curPage++;\n }\n changePages();\n }, timeoutTime);\n }", "_generatesPdfDefinition() {\n let pdfTasksDocDef = [];\n angular.forEach(this.tasksArray, (task) => {\n //Create PDF definition for Task\n pdfTasksDocDef.push(this._generateTaskDocDef(task, null));\n\n //Create PDF definition foreach subtask of the previous task\n if (task.fields.subtasks) {\n let pdfSubTaskPairDocDef = { columns: [] }; //each row in the page gonna contain 2 subtasks\n\n for (let i = 0; i < task.fields.subtasks.length; i++) {\n let subtask = task.fields.subtasks[i];\n\n if (pdfSubTaskPairDocDef.columns.length < 2) {\n if (this.hideFinishedSubtasks && (subtask.fields.status.name.toLowerCase() == 'resolved' || subtask.fields.status.name.toLowerCase() == 'closed')) {\n //do nothing (the task must be hidden because it status is resolver or closed and is selected hide finished subtasks option)\n } else {\n pdfSubTaskPairDocDef.columns.push(this._generateTaskDocDef(subtask, task));\n }\n }\n\n if (pdfSubTaskPairDocDef.columns.length == 2) {\n pdfTasksDocDef.push(pdfSubTaskPairDocDef);\n pdfSubTaskPairDocDef = { columns: [] }; //reset the pair object\n }\n }\n\n //whether after the loop execution there is one remaining task in the Pair then add it to the definition\n if (pdfSubTaskPairDocDef.columns.length) {\n pdfTasksDocDef.push(pdfSubTaskPairDocDef);\n }\n }\n });\n \n this.pdfDocDef = {\n // a string or { width: number, height: number }\n pageSize: 'A4',\n\n // by default we use portrait, you can change it to landscape if you wish\n pageOrientation: 'portrait',\n\n // [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins\n pageMargins: [ 20, 50, 20, 50 ],\n\n content: pdfTasksDocDef,\n styles: {\n taskTable: {\n margin: [0, 5, 0, 15]\n },\n epicTableHeader: {\n alignment: 'center',\n bold: true,\n fontSize: 22,\n color: '#fff',\n fillColor: '#' + this.$scope.epicColor\n },\n storyTableHeader: {\n alignment: 'center',\n bold: true,\n fontSize: 22,\n color: '#fff',\n fillColor: '#' + this.$scope.storyColor\n },\n taskTableHeader: {\n alignment: 'center',\n bold: true,\n fontSize: 22,\n color: '#fff',\n fillColor: '#' + this.$scope.taskColor\n },\n subtaskTableHeader: {\n alignment: 'center',\n bold: true,\n fontSize: 18,\n color: '#fff',\n fillColor: '#' + this.$scope.subtaskColor\n },\n bugTableHeader: {\n alignment: 'center',\n bold: true,\n fontSize: 18,\n color: '#fff',\n fillColor: '#' + this.$scope.bugColor\n },\n taskTableSummary: {\n fontSize: 20\n },\n storyTableSummary: {\n fontSize: 20\n },\n subtaskTableSummary: {\n fontSize: 16,\n bold: true\n },\n epicTableSummary: {\n fontSize: 20,\n bold: true\n },\n bugTableSummary: {\n fontSize: 16,\n bold: true\n },\n taskTableFooter: {\n fontSize: 14,\n fillColor: '#efefef',\n alignment: 'right'\n }\n }\n };\n }", "function createPDF(tests) {\n pages = 1;\n var doc = new jsPDF('p', 'pt');\n doc.setFont(\"helvetica\");\n doc.setFontType(\"bold\");\n doc.setFontSize(30);\n doc.text(60, 60, 'RTMS - Intervention Reporting');\n doc.setFontSize(15);\n doc.text(60, 90, 'This report was generated for the following intervention: ');\n if($scope.Report.FilterSelection == 1)\n doc.text(60, 120, 'Filter selection: NONE (All)')\n else {\n doc.text(60, 120, 'Filter selection: Date Range - StartDate:' + $scope.Report.StartDate + ', EndDate:' + $scope.Report.EndDate);\n }\n doc.setFontSize(20);\n doc.text(60, 150, $scope.Report.Intervention.Name);\n doc.setFontType(\"normal\");\n doc.text(60, 180, doc.splitTextToSize(\"Description: \" + $scope.Report.Intervention.Description, 500));\n doc.setFontType(\"bold\");\n doc.text(60, 360, \"Tests:\");\n doc.setFontType(\"normal\");\n y = 360;\n for (var i = 0; i < tests.length; i++) {\n y += 30;\n doc.text(60, y, \"> \" + tests[i].Name);\n }\n doc.text(60, 800, \"Page:\" + pages);\n for (var i = 0; i < tests.length; i++) {\n y = 0;\n doc.addPage();\n pages++;\n doc.setFontType(\"bold\");\n doc.setFontSize(30);\n y += 60;\n doc.text(60, y, tests[i].Name);\n doc.setFontType(\"normal\");\n doc.setFontSize(20);\n y += 30;\n doc.text(60, y, \"ID: \" + tests[i].Id);\n y += 30;\n doc.text(60, y, doc.splitTextToSize(\"Description: \" + tests[i].Description, 500));\n y += 180;\n doc.text(60, y, \"This test has been completed: \" + tests[i].CompletionCount + \" times\");\n y += 30;\n doc.text(60, y, doc.splitTextToSize(\"This report lists all multiple-choice & multi-answer questions in the pages below.\", 500));\n y += 60;\n doc.setFontSize(15);\n doc.text(60, y, \"*Other question types such as text answers cannot be usefully displayed.\");\n doc.setFontSize(20);\n for (var j = 0; j < tests[i].Questions.length; j++) {\n if (tests[i].Questions[j].Id != 0) {\n doc.addPage();\n pages++;\n y = 60;\n doc.text(60, y, \"Question ID: \" + tests[i].Questions[j].Id);\n y += 30;\n doc.text(60, y, doc.splitTextToSize(\"Question:\" + tests[i].Questions[j].Question, 500));\n y += 90;\n doc.text(60, y, doc.splitTextToSize(\"Data Values:\"));\n y += 30;\n doc.text(60, y, doc.splitTextToSize('- ' + objsToArr(tests[i].Questions[j].Answers), 500));\n y += 60;\n doc.text(60, y, \"Chart:\");\n y += 60;\n doc.addImage(createChart(objsToArr(tests[i].Questions[j].Answers)), 'PNG', 60, y, 400, 400);\n doc.text(60, 800, \"Page:\" + pages);\n }\n }\n }\n return doc;\n }", "function createPDF() {\n var totalPieces = imagePieces.length - 1;\n var doc = new jsPDF({\n unit: 'px',\n invWrapperat: 'a4'\n });\n imagePieces.forEach(function(img){\n doc.addImage(img, 'JPEG', 18, 0);\n if(totalPieces)\n doc.addPage();\n totalPieces--;\n });\n doc.save('invoice.pdf');\n invWrapper.width(cache_width);\n}", "function createReports() {\r\n // pop ingestion params from stack, if any, otherwise just exit\r\n if (reportParams.length) {\r\n var reportParam = reportParams.pop();\r\n\r\n // if creating first report\r\n if (!$(\"#creating\").is(\":visible\")) {\r\n // show creating reports\r\n $(\"#creating\").show();\r\n\r\n // set segment position, interval and currentsegment for progressbar \r\n $(\"#progressbar\").progressbar(\"value\", Math.round((currentsegment/totalsegments)*99));\r\n updateinterval = (createtime/numfiles) * 80;\r\n currentsegment ++;\r\n } else {\r\n // set segment position and currentsegment for progressbar\r\n $(\"#progressbar\").progressbar(\"value\", Math.round((currentsegment/totalsegments)*99));\r\n currentsegment ++;\r\n }\r\n // advance progressbar \r\n advanceProgress();\r\n // update with current file\r\n $(\"#creatingreports\").text(reportParam.filename);\r\n\r\n var ingestionId = reportParam.ingestionid;\r\n var startDate = $('#startdate').val();\r\n var endDate = $('#enddate').val();\r\n var cnt = 0;\r\n\r\n var reportTypes = \"\";\r\n if (document.getElementById('volume').checked) {\r\n reportTypes = reportTypes + '&type'+cnt+'=volume';\r\n cnt ++;\r\n }\r\n if (document.getElementById('speed').checked) {\r\n reportTypes = reportTypes + '&type'+cnt+'=speed';\r\n cnt ++;\r\n }\r\n if (document.getElementById('class').checked) {\r\n reportTypes = reportTypes + '&type'+cnt+'=class';\r\n }\r\n\r\n var reportFormatDropdown = document.getElementById(\"reports-reportformats-dropdown\");\r\n var reportFormat = \"&reportformat=\" + reportFormatDropdown.options[reportFormatDropdown.selectedIndex].innerHTML;\r\n\r\n reportParameters = GetReportParameters(\"reports\");\r\n\r\n if (reportParameters !== \"\")\r\n {\r\n reportParameters = \"&reportparameters=\" + encodeURIComponent(reportParameters);\r\n }\r\n\r\n // call ajax function to createreports\r\n var paramsString = METHODCALL_HEADER_PARAM_AUTHTOKEN + \"=\" + readCookie('authToken') + \"&ingestionid=\" + ingestionId + \"&startdate=\" + startDate + \"&enddate=\" + endDate + reportTypes + reportFormat + reportParameters;\r\n $.ajax({\r\n type: \"GET\",\r\n url: \"MethodCall.php/TubeJobSite::CreateReports\",\r\n data: paramsString,\r\n dataType: \"html\",\r\n cache: false,\r\n success: function(result) {\r\n jsonResponse = JSON.parse(result);\r\n var response = jsonResponse['results']['response'];\r\n if (response == \"success\") {\r\n // get report types & filenames and add to downloadParams\r\n if (\"volume\" in jsonResponse['results']['returnval']['outputFiles']) {\r\n if (\"xls\" in jsonResponse['results']['returnval']['outputFiles']['volume']) {\r\n downloadParams.push({filename: jsonResponse['results']['returnval']['outputFiles']['volume']['xls']});\r\n }\r\n if (\"pdf\" in jsonResponse['results']['returnval']['outputFiles']['volume']) {\r\n downloadParams.push({filename: jsonResponse['results']['returnval']['outputFiles']['volume']['pdf']});\r\n }\r\n }\r\n if (\"class\" in jsonResponse['results']['returnval']['outputFiles']) {\r\n if (\"xls\" in jsonResponse['results']['returnval']['outputFiles']['class']) {\r\n downloadParams.push({filename: jsonResponse['results']['returnval']['outputFiles']['class']['xls']});\r\n }\r\n if (\"pdf\" in jsonResponse['results']['returnval']['outputFiles']['class']) {\r\n downloadParams.push({filename: jsonResponse['results']['returnval']['outputFiles']['class']['pdf']});\r\n }\r\n }\r\n if (\"speed\" in jsonResponse['results']['returnval']['outputFiles']) {\r\n if (\"xls\" in jsonResponse['results']['returnval']['outputFiles']['speed']) {\r\n downloadParams.push({filename: jsonResponse['results']['returnval']['outputFiles']['speed']['xls']});\r\n }\r\n if (\"pdf\" in jsonResponse['results']['returnval']['outputFiles']['speed']) {\r\n downloadParams.push({filename: jsonResponse['results']['returnval']['outputFiles']['speed']['pdf']});\r\n }\r\n }\r\n // if more reports to create\r\n if (reportParams.length) {\r\n // call createReports\r\n createReports();\r\n }\r\n // else call downloadReports\r\n else {\r\n // show create completion\r\n $(\"#creatingreports\").text(\"..Completed\");\r\n // clear timer on progressbar, let next function restart it\r\n clearTimeout(progressTimer);\r\n // start downloading\r\n packageReports();\r\n }\r\n }\r\n // else handle error for user \r\n else {\r\n if (jsonResponse['results']['returnval']['resultstring'] == \"login required\") {\r\n // close this form\r\n closeProcessingDataDialog();\r\n // inform user and logout\r\n loginRequired();\r\n } else {\r\n $(\"#processingdata\").text(\"Error, createReports returned with:<br />\"+jsonResponse['results']['returnval']['resultstring']);\r\n $(\"#doneProcessingBtn\").show();\r\n }\r\n }\r\n },\r\n error: function (request, status, error) {\r\n $(\"#processingdata\").text(\"Server error: \" + status);\r\n $(\"#doneProcessingBtn\").show();\r\n }\r\n });\r\n } \r\n else {\r\n // nothing to do, set error message and add done button on processingdata dialog\r\n $(\"#processingdata\").text(\"Error in createReports, no ingestions available\");\r\n $(\"#doneProcessingBtn\").show();\r\n }\r\n}", "function schedulePages(){\n var cumlativeTime = 0;\n for(var p = 0; p < pageOrder.length; p++){\n for (var s = 0; s < pageOrder[p].subpages.length; s++) {\n //for every single sub page\n var startTime = cumlativeTime;\n var clearTime = cumlativeTime + pageOrder[p].subpages[s].duration;\n setTimeout(executePage, startTime, p, s);\n setTimeout(clearPage, clearTime, p, s);\n cumlativeTime = clearTime;\n }\n }\n}", "function queueRenderPage(num) {\n if ($scope.PDFDOC.pageRendering) {\n $scope.PDFDOC.pageNumPending = num;\n }\n else {\n renderPage(num);\n }\n }", "function _buildPDFDocAlive(quote)\n{\n LogMessage(_moduleName_appPDFHelper + \": _buildPDFDoc - start\");\n\n var marginWidth = 10;\n var yCoordOffset = 8;\n var yCoordWrapOffset = 4;\n var yHeaderOffset = 12;\n\n var colOffset = 90;\n var xCoord = marginWidth + 2;\n var yCoord = 28;\n var xCoordTwo = xCoord + colOffset;\n var yCoordTwo = yCoord;\n var xCoordThree = xCoord + colOffset * 2;\n var yCoordThree = yCoord;\n\n //\"css\"\n var fontSizeNormal = 11;\n var fontSizeMedium = 16;\n var fontSizeLarge = 20;\n var fontSizeXLarge = 30;\n\n //offsets for lines and other related items\n var valueOffset = 60;\n var lineOffset = 3;\n var colWidth = colOffset - 10;\n\n //init PDF library\n var PDF = new $(document).pdf();\n\n //init base font\n var baseFont = new PDF.Fonts.CoreFont(PDF.Fonts.FontFamily.ARIAL);\n var blackColor = new PDF.RGBColor(0x212322);\n var whiteColor = new PDF.RGBColor(0xFFFFFF);\n var blueColor = new PDF.RGBColor(0x2D4275); //PDF.RGBColor(0x2D4275);\n\n //Set some initial values on the PDF itself\n var doc = PDF.newDocument(PDF.Orientation.LANDSCAPE, PDF.Unit.MM, PDF.Size.A4).Document;\n doc.setDisplayMode(PDF.Display.FULL_WIDTH); //set to show full screen zoom\n doc.setAuthor(\"Voith\");\n doc.setCreator(\"Modular Composite - AIR Application\");\n //create first page\n doc.addPage();\n doc.setMargins(marginWidth, marginWidth/2, marginWidth, marginWidth); //left,top,right,bottom\n\n //lets keep height of the page for further use\n //var pageH = doc.getPage(1).h;\n var rightEdge = doc.getPage(1).w - marginWidth;\n\n //Layered Image\n //TBD - alignment is off for some reason, \n //it also has white space at top, to get the layout to work well, draw image first and then add in header, prod name \n // so that the image is behind this other stuff\n //TEMP\n //generate a layered image on a canvas and save to disk or bytes\n //var prodImageFilePath = _AirGetFilePathApplication(_ImagePathProductLayers + \"_ProductImageTest.jpg\");\n //var prodImageFilePath = Utility_GenerateLayeredImageToDisk_AIR(quote);\n //prodImageFilePath = _AirGetFilePathApplicationStorage(prodImageFilePath);\n //var prodImageBytes = PDF.imageAsBytes(prodImageFilePath);\n var prodImageBytes = Utility_GenerateLayeredImageAsBytes(quote);\n doc.addImageStream(\n prodImageBytes,\n PDF.ColorSpace.DEVICE_RGB,\n new PDF.Resize(\"none\", \"left\"),\n xCoord - 33, yCoord - 20, 100, 100 //original size is 560x560, canvas is 200x200\n );\n\n //header\n //position header above the first row of content\n doc.setFontSize(fontSizeLarge);\n doc.textStyle(blueColor); \n doc.addText('Modular Composite - Quote',xCoordTwo, yCoord - yHeaderOffset);\n //line to separate header\n PDF.drawLine(marginWidth, yCoord - yHeaderOffset + lineOffset, rightEdge, yCoord - yHeaderOffset + lineOffset); // x1, y1, x2, y2 - horizontal line \n\n //Embed Logo\n //public function addImageStream(imageBytes:ByteArray, colorSpace:String, resizeMode:Resize = null, x:Number = 0, y:Number = 0, width:Number = 0, height:Number = 0, rotation:Number = 0, alpha:Number = 1, blendMode:String = Normal, link:ILink = null):void\n doc.addImageStream(\n PDF.imageAsBytes(_AirGetFilePathApplication('allAssets/img/voith.png')),\n PDF.ColorSpace.DEVICE_RGB,\n null, \n (rightEdge - 10 - 131 * .35), -2, (131 * .35), (35 * .35) //original size is 131x35\n );\n\n //first column\n //put the prod name after the image so it lays on top of the image\n doc.setFontSize(fontSizeLarge);\n doc.textStyle(blueColor); \n doc.addText(quote.Product.ProductName, xCoord, yCoord ); //product name\n yCoord += yCoordOffset;\n\n //2nd Column\n doc.setFontSize(fontSizeMedium);\n doc.textStyle(blueColor);\n var wrapTextCustomerName = SplitTextToLines(quote.Customer.Name, fontSizeMedium, colWidth);\n $.each(wrapTextCustomerName, function (i, item) {\n doc.addText(item, xCoordTwo, yCoordTwo);\n yCoordTwo += yCoordOffset;\n });\n\n //customer info\n doc.setFontSize(fontSizeNormal);\n doc.textStyle(blackColor);\n var wrapTextCustomerInfo = $.trim(quote.Customer.MachineNumber) + ' / ' +\n\t\t\t\t\t $.trim(quote.Customer.SectionName) + ' / ' +\n\t\t\t\t\t $.trim(quote.Customer.ApplicationName) + ' / ' +\n\t\t\t\t\t $.trim(quote.Customer.PaperGrade);\n //new customer causes weird paragraph splits\n if (quote.Customer.IsLocal) {\n wrapTextCustomerInfo = wrapTextCustomerInfo.replace(/(\\r\\n|\\n|\\r)/gm, \"\");\n wrapTextCustomerInfo = wrapTextCustomerInfo.replace(/\\t/gm, \" \");\n }\n var wrapTextCustomerInfo = SplitTextToLines(wrapTextCustomerInfo, fontSizeNormal, colWidth);\n var yCoordWrapText = yCoordTwo; //use this to set different line height for wrapped text\n $.each(wrapTextCustomerInfo, function (i, item) {\n doc.addText(item, xCoordTwo, yCoordWrapText);\n yCoordWrapText += yCoordWrapOffset;\n });\n //allot two lines for customer info so Overview does not wrap into it\n yCoordTwo += yCoordOffset;\n yCoordTwo += yCoordOffset;\n\n doc.setFontSize(fontSizeMedium);\n doc.textStyle(blueColor); \n var yCoordOverview = yCoordTwo; //use this downstream to align Overview and Calendar headings\n doc.addText(\"Overview\", xCoordTwo, yCoordTwo);\n doc.setFontSize(fontSizeNormal);\n doc.textStyle(blackColor); \n\n $.each(quote.Product.AppType, function (i, item) {\n if (item.ShowInList) {\n yCoordTwo += yCoordOffset;\n doc.addText(item.Caption, xCoordTwo, yCoordTwo);\n doc.addImageStream(\n PDF.imageAsBytes(_AirGetFilePathApplication(item.IconName_Blue.replace(\".png\", \".jpg\"))), //have a set of non-transparent jpgs for this pdf generation\n PDF.ColorSpace.DEVICE_RGB,\n null,\n xCoordTwo + valueOffset-18, yCoordTwo - 9, 5, 5\n );\n doc.addText(item.Rank, xCoordTwo + valueOffset, yCoordTwo);\n //line to separate items\n PDF.drawLine(xCoordTwo, yCoordTwo + lineOffset, xCoordTwo + colWidth, yCoordTwo + lineOffset); // x1, y1, x2, y2 - horizontal line \n }\n });\n\n //third column\n doc.setFontSize(fontSizeMedium);\n doc.textStyle(blueColor); \n var quoteNumber = (quote.QuoteId != undefined && quote.QuoteId > 0 ?\n quote.Customer.CustomerNumber + '-' + quote.QuoteId.toString() : '[Draft]');\n doc.addText('Quote #: ' + quoteNumber, xCoordThree, yCoordThree);\n yCoordThree += yCoordOffset;\n doc.setFontSize(fontSizeNormal);\n doc.textStyle(blackColor); \n doc.addText('Quote Date: ' + quote.QuoteDate, xCoordThree, yCoordThree); // date \n\n doc.setFontSize(fontSizeMedium);\n doc.textStyle(blueColor); \n //set alignment with second column Overview\n yCoordThree = yCoordOverview;\n doc.addText(\"Calendar\", xCoordThree, yCoordThree);\n doc.setFontSize(fontSizeNormal);\n doc.textStyle(blackColor); \n yCoordThree += yCoordOffset;\n doc.addText('Line Load', xCoordThree, yCoordThree); // line load \n doc.addText(quote.ProductSelection.LineLoad + ' ' + quote.ProductSelection.LineLoadUOM, xCoordThree + valueOffset, yCoordThree); // line load \n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordThree += yCoordOffset;\n doc.addText('Temperature', xCoordThree, yCoordThree);\n doc.addText(quote.ProductSelection.Temperature + ' ' + quote.ProductSelection.TemperatureUOM, xCoordThree + valueOffset, yCoordThree); // temperature\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordThree += yCoordOffset;\n doc.addText('Speed', xCoordThree, yCoordThree);\n doc.addText(quote.ProductSelection.Speed + ' ' + quote.ProductSelection.SpeedUOM, xCoordThree + valueOffset, yCoordThree); // speed\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordThree += yCoordOffset;\n doc.addText('Core Diameter', xCoordThree, yCoordThree);\n doc.addText(quote.ProductSelection.CoreDiameter, xCoordThree + valueOffset, yCoordThree); // core diameter\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordThree += yCoordOffset;\n doc.addText('Finish Diameter', xCoordThree, yCoordThree);\n doc.addText(quote.ProductSelection.FinishDiameter, xCoordThree + valueOffset, yCoordThree); // finish diameter\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordThree += yCoordOffset;\n doc.addText('Cover Length', xCoordThree, yCoordThree);\n doc.addText(quote.ProductSelection.CoverLength, xCoordThree + valueOffset, yCoordThree); // cover length\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n\n //Benefit boxes, your selection\n //reset starting yCoord, yCoord2, yCoord3\n yCoordThree += yCoordOffset * 2;\n yCoord = yCoordThree;\n yCoordTwo = yCoordThree;\n\n //add your selection heading first\n doc.setFontSize(fontSizeMedium);\n doc.textStyle(blueColor); \n doc.addText('Your Selection', xCoordThree, yCoordThree);\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordThree += yCoordOffset;\n doc.setFontSize(fontSizeNormal);\n\n //loop over items and pull out benefits and your selection for each app type\n $.each(quote.AppType, function (i, item) {\n\n var benefit = (item.Benefit == undefined || item.Benefit.length == 0 ? '' : item.Benefit);\n\n if (item.ShowInList) {\n var wrapTextBenefit = '';\n if (benefit != '') {\n wrapTextBenefit = SplitTextToLines('Benefit: ' + benefit, fontSizeNormal, colWidth);\n }\n //col 1 or col 2 - odds in col one\n if (isOdd(i)) {\n doc.textStyle(blueColor); \n doc.addText(item.Caption, xCoord, yCoord);\n PDF.drawLine(xCoord, yCoord + lineOffset, xCoord + colWidth, yCoord + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoord += yCoordOffset;\n doc.textStyle(blackColor); \n yCoordWrapText = yCoord;\n $.each(wrapTextBenefit, function (i, item) {\n doc.addText(item, xCoord, yCoordWrapText);\n yCoordWrapText += yCoordWrapOffset;\n });\n //increment the lines 3 times for consistent layout\n yCoord += yCoordOffset;\n yCoord += yCoordOffset;\n yCoord += yCoordOffset;\n }\n else {\n doc.textStyle(blueColor); \n doc.addText(item.Caption, xCoordTwo, yCoordTwo);\n PDF.drawLine(xCoordTwo, yCoordTwo + lineOffset, xCoordTwo + colWidth, yCoordTwo + lineOffset); // x1, y1, x2, y2 - horizontal line \n yCoordTwo += yCoordOffset;\n doc.textStyle(blackColor); \n yCoordWrapText = yCoordTwo;\n $.each(wrapTextBenefit, function (i, item) {\n doc.addText(item, xCoordTwo, yCoordWrapText);\n yCoordWrapText += yCoordWrapOffset;\n });\n //increment the lines 3 times for consistent layout\n yCoordTwo += yCoordOffset;\n yCoordTwo += yCoordOffset;\n yCoordTwo += yCoordOffset;\n }\n }\n else //yes/no items\n {\n doc.textStyle(blueColor); \n doc.addText(item.Caption, xCoordThree, yCoordThree);\n doc.addText((item.Rank == 0 ? 'No' : 'Yes'), xCoordThree + valueOffset, yCoordThree);\n PDF.drawLine(xCoordThree, yCoordThree + lineOffset, xCoordThree + colWidth, yCoordThree + lineOffset); // x1, y1, x2, y2 - horizontal line \n\n var wrapTextBenefit = '';\n if (benefit != '') {\n wrapTextBenefit = SplitTextToLines('Benefit: ' + benefit, fontSizeNormal, colWidth);\n yCoordThree += yCoordOffset;\n doc.textStyle(blackColor); \n yCoordWrapText = yCoordThree;\n $.each(wrapTextBenefit, function (i, item) {\n doc.addText(item, xCoordThree, yCoordWrapText);\n yCoordWrapText += yCoordWrapOffset;\n });\n //after last benefit, then make col3 position equal to last increment\n yCoordWrapText += yCoordWrapOffset;\n yCoordThree = yCoordWrapText;\n }\n else\n {\n yCoordThree += yCoordOffset;\n }\n }\n\n });\n\n return PDF;\n\n}", "function createPDF() {\n\t\t\n\t\tvar processMsg = '<i class=\"fa fa-spinner fa-pulse fa-lg fa-fw qlink loader\"></i>';\n\t\t\t\n\t\tdocument.getElementById(\"pdfContainer\").title = \"processing\";\n\t\t\n\t\tsendToPDF();\n\t\tdocument.getElementById( \"pdfContainer\" ).innerHTML = processMsg;\n\t\t\n\t\t\t\t \t\t\n\t\tdisplayMessageToUser(\"A PDF is currently being created. You will be alerted\"+\n\t \t\" when the PDF is ready for download\", \"\", \"ok\", hideMessageToUser, \n\t \thideMessageToUser);\n\t \t\n\t\t}", "function pdfMaker(){\n\n}", "function generatePDF() {\n\t// https://plnkr.co/edit/64KOSxMgDWfRUfg2bxfo?p=preview\n\tvar pdf = new jsPDF();\n\tvar pdfName = \"pagebreaks.pdf\";\n\tvar options = { width: 170, pagesplit: true };\n\n\tvar $div = $(\".chapter-container\"); // gets all div of the same name\n\tvar noRecursionNeeded = $div.length - 1;\n\tvar currentRecursion = 0;\n\n\tfunction recursiveAddHtmlAndSave(currentRecursion, totalRecursions) {\n\t\t//Once we have done all the divs save the pdf\n\t\tif (currentRecursion == totalRecursions) {\n\t\t\tpdf.save(pdfName);\n\t\t} else {\n\t\t\tpdf.addPage();\n\t\t\tpdf.fromHTML(\n\t\t\t\t$(\".chapter-container\")[currentRecursion],\n\t\t\t\t15,\n\t\t\t\t15,\n\t\t\t\toptions,\n\t\t\t\tfunction() {\n\t\t\t\t\tconsole.log(\"Appending - chapter \" + currentRecursion);\n\t\t\t\t\tcurrentRecursion++;\n\t\t\t\t\trecursiveAddHtmlAndSave(currentRecursion, totalRecursions);\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t}\n\n\tpdf.fromHTML(\n\t\t$(\".summary-container\")[currentRecursion],\n\t\t15,\n\t\t15,\n\t\toptions,\n\t\tfunction() {\n\t\t\tconsole.log(\"Appending - summary\");\n\t\t\trecursiveAddHtmlAndSave(currentRecursion, noRecursionNeeded);\n\t\t}\n\t);\n}", "function createReportOrders() {\n \n var TEMPLATE_ID = '1IQKKvDM8AMvvxi5VsNmARzzFdiWWk3nstC6POTQzDNQ' // dry pack list template\n var FOLDER_ID = '1Ur9LaAUeYzlIFxQ77bO3oj0hJ0UIDULc' // reports go to dry/reports\n \n var packDate = getPackDateFromFilename()\n var PDF_FILE_NAME = Utilities.formatDate(packDate, \"GMT+12:00\", \"yyyy-MM-dd\") + ' Orders'\n \n if (TEMPLATE_ID === '') { \n SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs')\n return\n }\n \n // Set up the docs and the spreadsheet access\n \n var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(DriveApp.getFolderById(FOLDER_ID)) \n var doc = DocumentApp.openById(copyFile.getId())\n var body = doc.getBody()\n var header = doc.getHeader()\n \n // get a copy of templated tables and clear the document\n var templateMemberTable = body.getTables()[0]\n var templateOrdersTable = body.getTables()[1]\n body.clear()\n \n // copy and remove the template order row\n var dataRow = templateOrdersTable.getRow(1).removeFromParent()\n \n // Document Heading - set the packdate\n header.replaceText('%PACKDATE%', Utilities.formatDate(packDate, \"GMT+12:00\", \"EEEE, d MMMM yyyy\"))\n\n // Get orders\n var memberOrders = getDryOrdersByMember() //.reverse()\n\n \n //------------------------------------------------------------------------------------------------\n // for each member, on a new page, add a member header and then a table for each type of product\n //------------------------------------------------------------------------------------------------\n \n for (var i = 0; i < memberOrders.length; i++){\n var member = memberOrders[i]\n \n if (i>0) {body.appendPageBreak()}\n\n // create and insert member header\n var memberTable = templateMemberTable.copy()\n memberTable.replaceText(\"%member%\", member.name)\n memberTable.replaceText(\"%id%\", member.id)\n memberTable = body.appendTable(memberTable)\n \n \n // create a separate table for each measuring-type of product\n var weighables = templateOrdersTable.copy().replaceText(\"%type%\", \"Weighables (kg)\")\n var countables = templateOrdersTable.copy().replaceText(\"%type%\", \"Countables\")\n var pourables = templateOrdersTable.copy().replaceText(\"%type%\", \"Pourables (litres)\")\n \n // add a row for each order to one of the tables\n for (var j = 0; j < member.orders.length; j++) {\n var order = member.orders[j]\n var newRow = dataRow.copy()\n \n // newRow.replaceText(\"%tweak%\", (order.tweak == 0 ? \"\" : order.tweak))\n newRow.replaceText(\"%product%\", order.product)\n newRow.replaceText(\"%qty%\", order.qty)\n \n if (order.unit == \"kg\" || order.product.toLowerCase() == \"coconut oil\") {\n newRow = weighables.appendTableRow(newRow)\n } else if (order.unit == \"litre\") {\n newRow = pourables.appendTableRow(newRow)\n } else {\n newRow = countables.appendTableRow(newRow) \n }\n } \n if (countables.getNumRows() > 1) {body.appendTable(countables)}\n if (weighables.getNumRows() > 1) {body.appendTable(weighables)}\n if (pourables.getNumRows() > 1) {body.appendTable(pourables)}\n }\n\n //------------------------------------------\n // Create PDF from doc, rename it if required and delete the doc\n \n doc.saveAndClose()\n \n var pdf = DriveApp.getFolderById(FOLDER_ID).createFile(copyFile.getAs('application/pdf')) \n if (PDF_FILE_NAME !== '') {\n pdf.setName(PDF_FILE_NAME)\n } \n sharePdfPacksheets(pdf)\n \n copyFile.setTrashed(true)\n\n}", "function createPdf(scheduleArr, pdfName, dirPath, singleOrMultiPg = \"Single_Pg\", profOrClassObj)\n\t\t{\n\t\t\tif (singleOrMultiPg === \"Single_Pg\")\n\t\t\t{\n\t\t\t\tlet defDoc = makePdfDocDefinition(scheduleArr, \"All Professors Schedule\")\n\t\t\t\tprintPdf(defDoc, pdfName, dirPath);\n\t\t\t}\n\t\t\telse if (singleOrMultiPg === \"Multi_Pg_For_Profs\")\n\t\t\t{\n\t\t\t\tlet allDd = makePdfDocDefinition(scheduleArr, \"All Professors Schedule\");\n\t\t\t\tlet valueArray = [];\n\t\t\t\tlet prof_name;\n\n\t\t\t\tfor (let prop in profOrClassObj)\n\t\t\t\t{\n\t\t\t\t\tif (prop === \"all_profs\")\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tvalueArray = profOrClassObj[prop];\n\n\t\t\t\t\tlet dd = makePdfDocDefinition(valueArray, valueArray[0].abbreviated_name + \" Schedule\");\n\n\t\t\t\t\t// to expand a docDefinitions: \n\t\t\t\t\tallDd.content.push({text: '', pageBreak: 'after'}); // This is how you can add a break between pages\n\t\t\t\t\tallDd.content.push(dd.content[0]); \n\t\t\t\t\tallDd.content.push(dd.content[1]);\n\t\t\t\t\tallDd.content.push(dd.content[2]);\n\t\t\t\t}\n\n\t\t\t\tprintPdf(allDd, \"All_Profs_Multi_Page\", \"./All_Prof_Schedules/\");\n\t\t\t}\n\t\t\telse if (singleOrMultiPg === \"Multi_Pg_For_Classes\")\n\t\t\t{\n\t\t\t\tlet allDd = makePdfDocDefinition(scheduleArr, \"All Classes Schedule\");\n\t\t\t\tlet valueArray = [];\n\t\t\t\tlet file_name;\n\n\t\t\t\tfor (let prop in profOrClassObj)\n\t\t\t\t{\n\t\t\t\t\tif (prop === \"all_classes\")\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tvalueArray = profOrClassObj[prop];\n\n\t\t\t\t\tlet dd = makePdfDocDefinition(valueArray, valueArray[0].subject + \" \" + valueArray[0].catalog + \" Schedule\");\n\n\t\t\t\t\t// to expand a docDefinitions: \n\t\t\t\t\tallDd.content.push({text: '', pageBreak: 'after'}); // This is how you can add a break between pages\n\t\t\t\t\tallDd.content.push(dd.content[0]); \n\t\t\t\t\tallDd.content.push(dd.content[1]);\n\t\t\t\t\tallDd.content.push(dd.content[2]); \n\t\t\t\t}\n\n\n\t\t\t\tprintPdf(allDd, \"All_Classes_Multi_Page\", \"./All_Class_Schedules/\");\n\t\t\t}\t\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a custom context for ballot
createContext() { return new BallotContext(); }
[ "function ballot() {\n var bal = {},\n // Settable options\n container,\n candidates = [],\n votes = [],\n title = 'Example ballot card',\n withCard = false,\n showCard = false,\n shouldFadeIn = {\n candidates: false,\n card: false,\n votes: false,\n },\n transitionDelay = 0,\n transitionDuration = 0,\n // Internal references\n nodes = {},\n shouldReorderCandidates = false,\n highlight;\n\n /// GETTER / SETTER METHODS\n\n bal.container = function (elem) {\n if (!arguments.length) return container;\n container = d3.select(elem);\n nodes.root = container.append('figure')\n .attr('class', 'hor-ballot');\n\n // Create generic container elements\n [\n ['root', 'cardBorder', 'div', 'hor-ballot-border'],\n ['root', 'cardHeader', 'header', 'hor-ballot-header'],\n ['root', 'candidatesRoot', 'ul', 'hor-candidates'],\n ].forEach(defs => {\n let [parent, prop, tagName, cssClass] = defs;\n nodes[prop] = nodes[parent].append(tagName).attr('class', cssClass);\n });\n\n return bal;\n }\n\n bal.candidates = function (c) {\n if (!arguments.length) return candidates;\n candidates = [].concat(c);\n return bal;\n }\n\n bal.votes = function (v) {\n if (!arguments.length) return votes;\n votes = [].concat(v);\n return bal;\n }\n\n bal.withCard = function (c) {\n if (!arguments.length) return withCard;\n withCard = !!c;\n if (!withCard) {\n showCard = false;\n }\n return bal;\n }\n\n bal.showCard = function (c) {\n if (!arguments.length) return showCard;\n showCard = !!c;\n if (showCard) {\n withCard = true;\n }\n return bal;\n }\n\n bal.delay = function (d) {\n if (!arguments.length) return transitionDelay;\n transitionDelay = +d || 0;\n return bal;\n }\n\n bal.duration = function (d) {\n if (!arguments.length) return transitionDuration;\n transitionDuration = +d || 0;\n return bal;\n }\n\n bal.attr = function (k, v) {\n if (arguments.length < 2) {\n return root ? root.attr(k) : undefined;\n }\n if (root) {\n root.attr(k, v);\n }\n return bal;\n }\n\n bal.title = function (t) {\n if (!arguments.length) return title;\n title = t.toString();\n return bal;\n }\n\n /// WRITE-ONLY METHODS\n\n bal.randomise = function (minChange) {\n if (!candidates.length) {\n return bal;\n }\n minChange = utils.clamp(+minChange || 0, 1, candidates.length);\n let hasChangedEnough = false;\n let orig = [...candidates];\n while (!hasChangedEnough) {\n d3.shuffle(candidates);\n let changed = candidates.filter((c, i) => c !== orig[i]);\n hasChangedEnough = changed.length >= minChange;\n }\n shouldReorderCandidates = true;\n return bal;\n }\n\n Object.keys(shouldFadeIn).forEach(prop => {\n let fn = 'fadeIn' + prop[0].toUpperCase() + prop.substr(1);\n bal[fn] = function () {\n shouldFadeIn[prop] = true;\n return bal;\n }\n });\n\n bal.highlight = function () {\n // TODO: Add a highlight for a single candidate (colour? size?)\n }\n\n function setupNodes() {\n /**\n * LAYOUT:\n *\n * container\n * \\- root (figure)\n * |- border (div)\n * |- header (header)\n * | |- logo (img)\n * | \\- title (h1)\n * \\- candidatesRoot (ul -> nodes.candidates[])\n * \\- {nodes.candidates[]}\n * \\- candidate (li)\n * |- voteBox (span)\n * | \\- number (span)\n * |- name (span)\n * \\- party (span)\n */\n\n // Header (logo, title)\n if (!nodes.cardTitle) {\n // Logo\n nodes.cardHeader.append('img')\n .attr('class', 'hor-ballot-logo');\n\n // Title\n nodes.cardTitle = nodes.cardHeader.append('h1')\n .attr('class', 'hor-ballot-title');\n }\n nodes.cardTitle.text(title);\n\n // Candidates (vote box, name, party)\n nodes.candidates = nodes.candidatesRoot.selectAll('.hor-candidate')\n .data(candidates, d => d.name);\n let cgroups = nodes.candidates.enter().append('li')\n .attr('class', 'hor-candidate');\n cgroups.append('span')\n .attr('class', 'hor-vote-box')\n .append('span')\n .attr('class', 'hor-vote-box-text');\n cgroups.append('span')\n .attr('class', 'hor-candidate-name')\n .text(d => d.name);\n cgroups.append('span')\n .attr('class', 'hor-candidate-party')\n .text(d => d.party);\n\n // Vote boxes (box border, vote text)\n nodes.voteBoxes = nodes.candidates.select('.hor-vote-box')\n .data(paddedVotes());\n }\n\n function paddedVotes() {\n let lenDiff = candidates.length - votes.length;\n // More candidates than votes\n if (lenDiff > 0) {\n return votes.concat(Array(lenDiff).fill(0));\n }\n // More votes than candidates\n if (lenDiff < 0) {\n return votes.slice(0, candidates.length);\n }\n // Juuuuust right\n return [...votes];\n }\n\n const CandidatePositionEms = {\n noCard: [-2.8, (d, i) => ((2 + i) * -0.8)],\n withCard: [0, 0]\n };\n\n function translateCandidates(position) {\n return function () {\n this.translate(...position, 'em');\n };\n }\n\n function positionPlusReorder(position) {\n let [x, y] = position.map(p => d3.functor(p));\n let currentNodes = nodes.candidatesRoot.selectAll('.hor-candidate')[0];\n let fontSizePixels = parseFloat(getComputedStyle(currentNodes[0]).fontSize) || 16;\n let existingOffsets = currentNodes.map(function (elem) {\n return elem.offsetTop / fontSizePixels;\n });\n let newY = function (d, i) {\n let thisOffset = this.offsetTop / fontSizePixels;\n return y.call(this, d, i) + (existingOffsets[i] - thisOffset);\n };\n return [x, newY];\n }\n\n bal.render = function () {\n setupNodes();\n let cands = nodes.candidates;\n let cardNodes = d3.selectAll([\n nodes.cardBorder.node(),\n nodes.cardHeader.node(),\n ].concat(nodes.voteBoxes[0]));\n let voteText = nodes.voteBoxes.select('.hor-vote-box-text');\n\n let position = CandidatePositionEms[withCard ? 'withCard' : 'noCard'];\n if (shouldReorderCandidates) {\n position = positionPlusReorder(position);\n }\n let positionFn = translateCandidates(position);\n\n let resolveTime = transitionDuration;\n\n function doStuff() {\n // Prepare positions/opacity for anything that needs fading in\n if (shouldFadeIn.candidates) {\n cands.style('opacity', 0)\n .call(positionFn);\n }\n if (shouldFadeIn.card) {\n cardNodes.style('opacity', 0);\n cardNodes = cardNodes.transition();\n }\n if (shouldFadeIn.votes) {\n voteText.style('opacity', 0);\n }\n\n // Add any per-element delays\n cands = cands.transition();\n voteText = voteText.transition();\n if (transitionDelay) {\n cands.delay((d, i) => i * transitionDelay);\n voteText.delay(d => (d - 1) * transitionDelay);\n resolveTime += (cands.size() - 1) * transitionDelay;\n }\n\n // Show/move candidates\n if (shouldFadeIn.candidates) {\n cands.style('opacity', 1);\n } else {\n cands.call(positionFn);\n }\n\n // Show votes\n if (showCard) {\n voteText.text(d => d ? d : '')\n if (shouldFadeIn.votes) {\n voteText.style('opacity', 1);\n }\n }\n\n // Show/hide voting card and votes as required\n cardNodes.style('opacity', +showCard);\n }\n\n return new Promise(function (resolve) {\n d3.transition()\n .duration(transitionDuration)\n .each(doStuff)\n .each(function () {\n setTimeout(function () {\n // Make sure candidate nodes are in the right place\n if (shouldReorderCandidates) {\n // Has to be a setTimeout to guarantee running after all the transition stuff is done\n let position = CandidatePositionEms[withCard ? 'withCard' : 'noCard'];\n nodes.candidates.order().call(translateCandidates(position));\n }\n\n // Clean up fade/re-order trackers\n Object.keys(shouldFadeIn).forEach(prop => shouldFadeIn[prop] = false);\n shouldReorderCandidates = false;\n\n resolve();\n }, resolveTime + 100);\n });\n });\n }\n\n return bal;\n }", "function plotContext() {\n // if context line already exists, delete it\n if (plottingApp.plot.context_line) {\n plottingApp.plot.context_line.remove();\n }\n\n //context plot\n plottingApp.plot.context_line = plottingApp.context.append(\"path\")\n .datum(plottingApp.context_data)\n .attr(\"class\", \"line\")\n .attr(\"d\", plottingApp.context_line)\n .moveToBack();\n\n\n plottingApp.context_points = plottingApp.context.selectAll(\".point\")\n .data(plottingApp.context_data)\n .join(\"circle\")\n .attr(\"class\", \"point\")\n .attr(\"cx\", function(d) { return plottingApp.context_xscale(d.time); })\n .attr(\"cy\", function(d) { return plottingApp.context_yscale(d.val); })\n .attr(\"pointer-events\", \"none\")\n .attr(\"r\", 2);\n }", "function initDebtInContext() {\n var data = {\n labels: [\"UCF¹\", \"FLORIDA³\", \"PUBLIC²\", \"PRIVATE NONPROFIT²\", \"FOR-PROFIT²\"],\n datasets: [\n {\n label: \"\",\n backgroundColor: [\n 'rgb(249, 180, 70)',\n 'rgb(108, 183, 217)',\n 'rgb(197, 192, 184)',\n 'rgb(92, 155, 167)',\n 'rgb(210, 124, 80)'\n ],\n data: [21.824, 23.379, 25.500, 32.300, 39.950]\n }\n ]\n };\n\n var isInit = true;\n\n var options = {\n scales: {\n xAxes: [{\n scaleLabel: {\n display: true,\n fontColor: 'rgb(130,130,130)',\n labelString: \"THOUSANDS OF DOLLARS\"\n },\n ticks: {\n beginAtZero: true\n },\n gridLines: {\n borderDash: [10, 15],\n drawBorder: false,\n zeroLineColor: '#fff',\n }\n }],\n yAxes: [{\n display: false,\n gridLines: {\n zeroLineColor: '#fff',\n }\n }]\n },\n tooltips: {\n enabled: false\n },\n legend: {\n display: false\n },\n deferred: { // enabled by default\n yOffset: '75%', // defer until 50% of the canvas height are inside the viewport\n delay: 500 // delay of 500 ms after the canvas is considered inside the viewport\n },\n animation: {\n onComplete: function () {\n if (isInit) {\n var that = this;\n isInit = false;\n addLabels(this, \"debt\");\n }\n },\n onProgress: function () {\n if (!isInit) {\n var that = this;\n addLabels(that, \"debt\");\n }\n }\n }\n };\n\n var $debtInContext = $(\"#debt-in-context\"),\n debtInContext = new Chart($debtInContext, {\n type: 'horizontalBar',\n data: data,\n options: options\n });\n}", "function BarChart(context, data) {\n this.context = context;\n this.data = data;\n}", "function AnalysisContext() {\n}", "function ClbContextModel() {}", "context(a, button){\n this.currentContextPath = button.closest('bbn-context').data.path;\n }", "function ArtificialContext() {}", "function Rubicon() {\n context = this;\n}", "function InstantiationContext() {\n}", "function BlockContext() {\n}", "context() {\n return this._canvas.getContext('2d');\n }", "function balloon(options) {\n /// <summary>\n /// Creates a new instance of chartBaloon object with the given options.\n /// </summary>\n /// <param name=\"options\"></param>\n\n //set members\n this.backColor = '#ffffff';\n this.borderColor = '#0066cc';\n this.borderRadius = 3;\n this.borderSize = 2;\n this.borderStyle = 'solid';\n this.enabled = true;\n this.fontColor = '#333333';\n this.fontFamily = 'Tahoma';\n this.fontSize = 12;\n this.fontStyle = 'normal';\n this.format = '{{title}}: {{value}}';\n this.opacity = 0.9;\n this.padding = 5;\n\n //iterate all members in options to set this members\n for (var key in options) {\n //check whether the given key is contained by this object\n if (this[key] !== undefined || this[key] !== null)\n this[key] = options[key];\n };\n }", "render() {\n // Clone inherited config and append context-specific properties\n // (ESLint errors this)\n const configClone = { ...this.props.config };\n const config = this.amendConfig(configClone);\n return (\n <SilverChartWrapper\n config={config}\n getSvg={this.props.getSvg} passSvg={this.props.passSvg}\n />\n );\n }", "createContext() {\n const context = new RenderContext({\n renderers: this.renderers,\n theme: this.theme,\n });\n\n return context;\n }", "initialize(config) {\n this.context = config.context\n }", "createCanvasContext() {\n this.canvas = document.createElement('canvas');\n this.canvas.width = this.config.width;\n this.canvas.height = this.config.height;\n document.body.appendChild(this.canvas);\n this.context = this.canvas.getContext('2d');\n }", "setContext() {\n\t\tconst self = this;\n\t\tconst { stx } = this.context;\n\n\t\tthis.node.attr(\"cq-show\", \"true\");\n\t\tthis.configureUI();\n\n\t\tfunction renderIfChanged() {\n\t\t\tself.renderLegend();\n\t\t}\n\n\t\tthis.eventListeners.push(stx.addEventListener(\"layout\", renderIfChanged));\n\t\tthis.eventListeners.push(stx.addEventListener(\"theme\", renderIfChanged));\n\t\tthis.eventListeners.push(\n\t\t\tstx.addEventListener(\"curveChange\", renderIfChanged)\n\t\t);\n\n\t\tstx.append(\"modifySeries\", function () {\n\t\t\tself.renderLegend();\n\t\t});\n\n\t\tthis.renderLegend();\n\t}", "render() {\n console.log(\"ContextTypePage\",\n this.context); //sy-log\n const { themeColor } = this.context;\n return (\n <div className=\"border\">\n <h3 className={themeColor}>ContextTypePage</h3>\n </div>\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Manage `isopaque` state for `headernav`
function toggleIsOpaque() { var scrollTop = window.scrollY; if (scrollTop > 0) { headerNav.classList.add("is-opaque"); } else { headerNav.classList.remove("is-opaque"); } }
[ "function isHeaderTransparent() {\n return $('header').hasClass('is-transparent') ? true : false;\n }", "function setHeaderTransparent() {\n $header.addClass('is-transparent');\n $searchBlock.removeClass('is-active');\n $txtSearch.blur();\n }", "function setHeaderTransparency(lastKnownScrollPos, triggerHeight) {\n if (\n lastKnownScrollPos >= triggerHeight &&\n header.classList.contains(\"header--no-bg\")\n ) {\n header.classList.remove(\"header--no-bg\");\n headerIsAnimating = true;\n } else if (\n lastKnownScrollPos < triggerHeight &&\n !header.classList.contains(\"header--no-bg\")\n ) {\n header.classList.add(\"header--no-bg\");\n headerIsAnimating = true;\n }\n }", "function scrollOpaqueHeader() {\n $(window).on(\"scroll\", function () {\n if ($(window).scrollTop() > 50) {\n $(\".transparent-header\").addClass(\"active\");\n } else {\n $(\".transparent-header\").removeClass(\"active\");\n }\n });\n}", "function backgroundColor() {\n\t\t\t\tif (panache.inview(header, 68)) {\n\t\t\t\t\tpanache.addClass(nav, 'is-transparent');\n\t\t\t\t} else {\n\t\t\t\t\tpanache.removeClass(nav, 'is-transparent');\n\t\t\t\t}\n\t\t\t}", "function header_transparent() {\n\n $(\"#header\").css('background-color', 'transparent');\n $(\"#header a, #header h3\").css('color', 'white');\n $(\"#branding\").css('color', 'white');\n $(\"#hamburger_menu\").css('color', 'white');\n}", "function changeNavBackground() {\n let rect = banner.getBoundingClientRect();\n let bannerY_scroll = rect.y;\n if (!banner.classList.contains(\"inactive\")) {\n if (bannerY_scroll < 0) {\n document.getElementById(\"top-menu\").style.background = \"#262626\";\n }\n else {\n document.getElementById(\"top-menu\").style.background = \"transparent\";\n }\n } \n}", "function setNavTransparency() {\n var height = $(window).scrollTop();\n if (height > $(\"#ministries\").offset().top - 150) {\n $(\".down-button-row\").show();\n $(\".navbar-trans\").addClass(\"navSolid\");\n $(\".navbar-trans\").removeClass(\"transparent\");\n }\n }", "function changeHeaderStyle() {\n if (window.pageYOffset > styleChangeLocation) {\n mainHeader.style.backgroundColor = \"black\";\n } else {\n mainHeader.style.backgroundColor = \"transparent\";\n }\n}", "function pixflow_headerStateFirst(navColor, navHoverColor, color, $headerStyle, solidColor){\r\n \"use strict\";\r\n var blockBg=pixflow_RgbaToRgb(solidColor);\r\n\r\n // show business bar\r\n if(themeOptionValues.siteTop >0 && $('header.top-modern').length<1){\r\n $('.layout .business').css('display', 'block');\r\n }\r\n\r\n //Show business bar in header modern\r\n if (themeOptionValues.businessBarEnable == 1) {\r\n if ($('header.top-modern').length && $('header.top-modern .business').length) {\r\n $('header.top-modern .business').removeClass('business-off');\r\n $('header.top-modern ').css('height', '100px');\r\n }\r\n }\r\n\r\n //after scroll First appearance\r\n $headerStyle.find('nav > ul > li > a .menu-title').css('color',navColor);\r\n\r\n $headerStyle.find('.separator a').css({\r\n color: navColor,\r\n backgroundColor: navColor,\r\n opacity: 0.5\r\n });\r\n\r\n $headerStyle.find('.icons-pack span').css('color', navColor);\r\n\r\n // Under Line in Hover\r\n if ($('header.top-classic').length || $('header.top-logotop').length) {\r\n if($('header .style-wireframe').length < 0){\r\n $headerStyle.find('.navigation .menu-separator').css('backgroundColor', navHoverColor);\r\n }\r\n }\r\n\r\n if ($('header.top-logotop').length) {\r\n $headerStyle.find('.navigation > ul > li').css('color', navColor);\r\n $headerStyle.find('.navigation > ul > li').hover(function () {\r\n $(this).find('.menu-title').css({color: navHoverColor});\r\n },function(){\r\n $(this).find('.menu-title').css({color: navColor});\r\n });\r\n pixflow_underlineAnimation();\r\n }\r\n if ($('header.top-classic').length) {\r\n $headerStyle.find('.navigation > ul > li').hover(function () {\r\n if($('header .style-wireframe').length){\r\n $(this).find('.menu-separator').css({backgroundColor: navHoverColor});\r\n }else{\r\n $(this).find('.menu-title').css({color: navHoverColor});\r\n }\r\n }, function () {\r\n if($('header .style-wireframe').length){\r\n $(this).find('.menu-separator').css({backgroundColor: navColor});\r\n }else{\r\n $(this).find('.menu-title').css({color: navColor});\r\n }\r\n });\r\n pixflow_underlineAnimation();\r\n }\r\n\r\n if ($('header.top-block').length) {\r\n $headerStyle.find('.navigation > ul > li,' +\r\n '.icons-pack li').css({\r\n borderLeftColor: 'rgba(' + pixflow_rgbVal(navColor) + ',0.3)',\r\n borderRightColor: 'rgba(' + pixflow_rgbVal(navColor) + ',0.3)'\r\n });\r\n\r\n $headerStyle.find('.menu-separator-block').css({backgroundColor: navHoverColor});\r\n\r\n $headerStyle.find('.style-style1 .navigation > ul > li > a .hover-effect,' +\r\n '.style-style1 ul.icons-pack li .elem-container .hover-content').css({backgroundColor: navHoverColor});\r\n\r\n $headerStyle.find('.style-style1 .icons-pack .icon .icon-hover').css({color: blockBg});\r\n\r\n $headerStyle.find('.style-style1 .navigation > ul > li > a .menu-title,' +\r\n '.style-style1 .icons-pack .title-content').css({backgroundColor: blockBg});\r\n\r\n $headerStyle.find('.style-style2 .navigation > ul > li > a .hover-effect').css({color: navColor});\r\n\r\n $headerStyle.find('.style-style1 nav > ul > li').hover(function () {\r\n $(this).find(' > a .menu-title').css({backgroundColor: navHoverColor});\r\n $(this).find(' > a .menu-title .icon').css({color: navHoverColor});\r\n },function(){\r\n $(this).find('> a .menu-title').css({backgroundColor: blockBg});\r\n $(this).find('> a .menu-title .icon').css({color: navColor});\r\n });\r\n\r\n $headerStyle.find('.style-style1 .icons-pack li').hover(function () {\r\n $(this).find('a .title-content').css({backgroundColor: navHoverColor});\r\n },function(){\r\n $(this).find('a .title-content').css({backgroundColor: blockBg});\r\n });\r\n\r\n }\r\n\r\n if($('header.top-gather .style-style2').length) {\r\n\r\n $headerStyle.find('.style-style2 .icons-pack li .hover').css({color: navHoverColor});\r\n $headerStyle.find('.style-style2 .icons-pack li').css({ borderLeftColor: 'rgba(' + pixflow_rgbVal(navColor) + ',0.5)',\r\n borderRightColor: 'rgba(' + pixflow_rgbVal(navColor) + ',0.5)'});\r\n $headerStyle.find('.style-style2 .border-right, .style-style2 .border-left').css({\r\n borderColor: 'rgba(' + pixflow_rgbVal(navColor) + ',0.5)'});\r\n\r\n }\r\n\r\n if($('header.top-modern').length) {\r\n $headerStyle.find('.navigation > ul > li,' +\r\n '.icons-pack li,'+\r\n '.first-part').css({\r\n borderRightColor: 'rgba(' + pixflow_rgbVal(navColor) + ',0.3)'\r\n });\r\n\r\n\r\n $headerStyle.find('.navigation > ul > li > a span').css({color:navColor});\r\n $headerStyle.find('.business').css({borderBottomColor:'rgba(' + pixflow_rgbVal(navColor) + ',0.3)'});\r\n\r\n $headerStyle.find('.btn-1b').removeClass('btn-1b-second');\r\n $headerStyle.find('.btn-1b').addClass('btn-1b-first');\r\n\r\n $headerStyle.find('.btn-1b').hover(function () {\r\n $(this).find('> a span').css('color',color);\r\n $(this).find('> a span span').css('color',color);\r\n }, function () {\r\n $(this).find('> a .title').css('color', navColor);\r\n $(this).find('> a .icon').css('color', navColor);\r\n });\r\n }\r\n\r\n if( $('header.top-block').length < 1 && $('header.top-gather .style-style2').length < 1 && $('header.top-modern').length < 1 ) {\r\n $headerStyle.find('.navigation > ul > li').hover(function () {\r\n if($('header .style-wireframe').length){\r\n $(this).find('.menu-separator').css({backgroundColor: navHoverColor});\r\n }else{\r\n $(this).find('> span').css({color: navHoverColor});\r\n }\r\n }, function () {\r\n if($('header .style-wireframe').length){\r\n $(this).find('.menu-separator').css({backgroundColor: navColor});\r\n }else{\r\n $(this).find('> span').css({color: navColor});\r\n }\r\n });\r\n\r\n $headerStyle.find('.icons-pack .icon').hover(\r\n function () {\r\n $(this).css({color: navHoverColor});\r\n }, // over\r\n function () {\r\n $(this).css({color: navColor});\r\n } // out\r\n );\r\n }\r\n\r\n}", "function _headerStyleToggle() {\n\n var $body = $('body');\n $body.addClass('no-static-bg');\n\n if (__staticBackground) {\n $body.removeClass('no-static-bg').addClass('static-bg');\n } else if (__videoHeader) {\n _videoHeader();\n } else if (__slideshowHeader) {\n _slideshow();\n }\n if (!__overlay) {\n $('.overlay').hide();\n }\n\n }", "function hideHeaderImage(){\n\n\tif ($('.header-active').length != 0) {\n\t\t$('.header-background').css('display', 'none');\n\t}\n\n}", "function moduleBehindNav() {\n var mastheadRect = mastheadLogo.getBoundingClientRect();\n [].forEach.call(elements, function(div) {\n var elementRect = div.getBoundingClientRect();\n if ((elementRect.top <= mastheadRect.top) && (elementRect.bottom >= mastheadRect.bottom)) {\n var getTheColor = window.getComputedStyle(div, null).getPropertyValue(\"color\");\n // console.log(getTheColor);\n if (getTheColor == \"rgb(255, 255, 255)\") {\n masthead.style.color = \"rgb(255, 255, 255)\";\n // console.log(\"bingo\");\n } else {\n masthead.style.color = \"rgb(74, 66, 66)\";\n }\n\n }\n });\n }", "toggleHeaderNav() {\n this.headerNav.toggle()\n }", "function enableNavbarColorToggle() {\n const hero = document.getElementById('hero');\n const navbar = document.getElementById('nav-bar');\n const watcher = ScrollMonitor.create(hero);\n watcher.exitViewport(() => navbar.classList.add('is-opaque'));\n watcher.enterViewport(() => navbar.classList.remove('is-opaque'));\n}", "get isActive() {\n return this.header.isActive;\n }", "function navTransparentToColor() {\n /** @type {HTMLDivElement} */\n const navBar = document.querySelector(\"nav\");\n const top = window.scrollY;\n\n if (top >= 50) {\n navBar.classList.add(\"nav-active\");\n } else {\n navBar.classList.remove(\"nav-active\");\n }\n}", "function no_transparent_header_for_mobile(isTouch){\n\t\n\tif (jQuery(\".navbar[data-transparent-header]\").length) {\n\t\tif(isTouch){ \n\t\t\tjQuery('.navbar').attr(\"data-transparent-header\", \"false\");\t\t\n\t\t}\n\t\telse{\n\t\t\tjQuery('.navbar').attr(\"data-transparent-header\", \"true\");\t\t\n\t\t}\n\t}\n}", "function removeOpacityOnHeaderMainFooter() {\n header.style.opacity = 1;\n main.style.opacity = 1;\n footer.style.opacity = 1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns false if service capacity definitions are not valid, otherwise returns a well formed set of service capacity definitions using data as given in Services Capacity reference lookup
async _validateCapacities(capacityDef) { const setOfValidatedCapacities = []; let setOfValidatedCapacitiesInvalid = false; // need the set of all services capacities defined and available if (this._allCapacities === null || !Array.isArray(this._allCapacities)) return false; for (let thisCapacity of capacityDef) { if (!this._valid(thisCapacity)) { // first check the given data structure setOfValidatedCapacitiesInvalid = true; break; } // question id overrides question, because question id is indexed whereas question is not! let referenceCapacity = null; if (thisCapacity.questionId) { referenceCapacity = this._allCapacities.find((thisAllCapacity) => { return thisAllCapacity.id === thisCapacity.questionId; }); } else { referenceCapacity = this._allCapacities.find((thisAllCapacity) => { return thisAllCapacity.question === thisCapacity.question; }); } if (referenceCapacity && referenceCapacity.id) { // found a capacity match - prevent duplicates by checking if the reference capacity already exists if (!setOfValidatedCapacities.find((thisCapacity) => thisCapacity.questionId === referenceCapacity.id)) { setOfValidatedCapacities.push({ answer: thisCapacity.answer, reference: { question: referenceCapacity.question, id: referenceCapacity.id, seq: referenceCapacity.seq, }, }); } } else { setOfValidatedCapacitiesInvalid = true; break; } } // if having processed each service correctly, return the set of now validated services if (!setOfValidatedCapacitiesInvalid) return setOfValidatedCapacities; return false; }
[ "availableRooms(start, end, features, capacity){\n let output = [];\n for (const [name, room] of Object.entries(this._roomList)){\n if (room.capacity >= capacity){\n if (room.available(start, end)){\n if (room.hasFeatures(features)){\n if (end.getTime() - start.getTime() >= 86400000) { // the durations is over a day\n if (room.isValidTimeSlot(0, 24)){\n output.push(name);\n }\n }else {\n if (room.isValidTimeSlot(start.getHours(), end.getHours())){\n output.push(name);\n }\n }\n }\n }\n }\n }\n return output;\n }", "async _validateServices(servicesDef) {\n const setOfValidatedServices = [];\n let setOfValidatedServicesInvalid = false;\n\n // need the set of all services defined and available\n if (this._allServices === null || !Array.isArray(this._allServices)) return false;\n\n for (let thisService of servicesDef) {\n if (!this._valid(thisService)) {\n // first check the given data structure\n setOfValidatedServicesInvalid = true;\n break;\n }\n\n // id overrides name, because id is indexed whereas name is not!\n let referenceService = null;\n if (thisService.id) {\n referenceService = this._allServices.find(thisAllService => {\n return thisAllService.id === thisService.id;\n });\n } else {\n referenceService = this._allServices.find(thisAllService => {\n return thisAllService.name === thisService.name;\n });\n }\n\n if (referenceService && referenceService.id) {\n // found a service match - prevent duplicates by checking if the reference service already exists\n if (!setOfValidatedServices.find(thisService => thisService.id === referenceService.id)) {\n\n if (referenceService.other && thisService.other && thisService.other.length && thisService.other.length > OTHER_MAX_LENGTH) {\n setOfValidatedServicesInvalid = true;\n } else {\n setOfValidatedServices.push({\n id: referenceService.id,\n name: referenceService.name,\n category: referenceService.category,\n other: (thisService.other && referenceService.other) ? thisService.other : undefined,\n });\n }\n }\n } else {\n setOfValidatedServicesInvalid = true;\n break;\n }\n\n }\n\n // if having processed each service correctly, return the set of now validated services\n if (!setOfValidatedServicesInvalid) return setOfValidatedServices;\n\n return false;\n\n }", "requiresCapacityItem() {\n const itemData = this.data.data;\n return (this.type !== \"ammunition\" && itemData.ammunitionType);\n }", "function getCapacity() {\r\n return bookingCapacity.chain().data({ removeMeta: true })[0];\r\n}", "function ResourcesCapacity(){\r\n\tthis.warehouse = 800;\r\n\tthis.granary = 800;\r\n\t\r\n\tthis.toString = function() {\r\n\t\r\n\t\tvar output = \"Capacity [warehouse: \"+this.warehouse+\"; granary: \"+this.granary+\"]\";\r\n\t\r\n\t\treturn output;\r\n\t}\r\n\r\n\tthis.merge = function() {\r\n\t\r\n\t\tvar output = this.warehouse+\"/\"+this.granary;\r\n\t\r\n\t\treturn output;\r\n\t}\r\n\t\r\n\tthis.parseRes = function(rawString) {\r\n\r\n\t\tvar data = rawString.split(\"/\");\r\n\t\r\n\t\tthis.warehouse = parseInt(data[0]);\r\n\t\tthis.granary = parseInt(data[1]);\r\n\r\n\t}\r\n\r\n\tthis.resetValues = function(){\r\n\t\tthis.warehouse = 800;\r\n\t\tthis.granary = 800;\r\n\t}\r\n\t\r\n\t\r\n\tthis.warehousef = function(){\r\n\t\treturn addSeparatorsNF(this.warehouse.toFixed(0),\",\",\",\",\".\");\r\n\t}\r\n\tthis.granaryf = function(){\r\n\t\treturn addSeparatorsNF(this.granary.toFixed(0),\",\",\",\",\".\");\r\n\t}\r\n}", "isServiceSlotsAvailable(service) {\n const unavailableSlots = this.props.unavailableSlots || [];\n const { startSlot, durationSlots } = service;\n const slotsOfService = [];\n for (let i = 0; i < durationSlots; i++) {\n const slot = startSlot + i;\n if (slot === 1) slotsOfService.push('am');\n else if (slot === 2) slotsOfService.push('pm');\n else if (slot === 3) slotsOfService.push('eve');\n }\n return _.intersection(slotsOfService, unavailableSlots).length === 0;\n }", "function processCapacityData () {\n const processed = {\n // Disabled; let's force use of capacity data for now.\n // none: {\n // source_author: '(none)',\n // id: 'none'\n // }\n }\n const sourceKeys = Object.keys(SOURCE_DATA)\n for (let i = 0; i < sourceKeys.length; i++) {\n const sourceKey = sourceKeys[i]\n const data = SOURCE_DATA[sourceKey]\n\n // Skip the \"common\" data source from processing\n if (data.id === BASE_DATA_SOURCE) continue\n\n processed[sourceKey] = {\n ...data,\n segments: {\n // Clone \"common\" segments into our processed definition\n ...SOURCE_DATA[BASE_DATA_SOURCE].segments,\n // Iterate through source segment data and process each.\n ...processInheritedValues(data.segments)\n }\n }\n }\n\n return processed\n}", "async checkRequiredFacilities() {\n const freeFacilities = this.building.freeFacilities(null, \"tech_tier\", \"DESC\");\n\n if (this.craftingBy === \"Recipe\") {\n // Skip check of required facility if recipe doesn't have it\n if (!this.recipe.required_facility_type_id) return;\n\n // Check whether building has suitable free facilities\n const hasFacility = freeFacilities.some((freeFacility) => {\n if (\n this.recipe.required_facility_type_id.equals(freeFacility.properties.type_id) &&\n this.recipe.tech_tier <= freeFacility.properties.tech_tier\n ) {\n this.facilitiesToUse.push(freeFacility._id);\n this.tech_tier_bonus = freeFacility.properties.tech_tier - this.recipe.tech_tier;\n return true;\n }\n });\n\n if (hasFacility) return;\n throw new Error(\"Building doesn't have free facility of required type\");\n }\n\n const requiredFacilities = this.blueprint.required_facilities;\n // Skip check of required facilities if blueprint doesn't have them\n if (requiredFacilities.length === 0) {\n this.facilitiesLevel = BASIC_LEVEL;\n return;\n }\n\n const hasFacility = requiredFacilities.some((requiredFacility) => {\n const hasFacility = freeFacilities.some((freeFacility) => {\n if (!freeFacility.properties) throw new Error(\"building.facilities.properties must be populated\");\n if (\n requiredFacility.type_id.equals(freeFacility.properties.type_id) &&\n requiredFacility.tech_tier <= freeFacility.properties.tech_tier\n ) {\n this.facilitiesToUse.push(freeFacility._id.toString());\n this.facilitiesLevel += increaseQualityLevel(\n freeFacility.properties.quality_level,\n freeFacility.properties.tech_tier - requiredFacility.tech_tier\n );\n return true;\n }\n });\n if (hasFacility) return true;\n });\n\n if (!hasFacility) throw new Error(\"Building doesn't have free facility of required type\");\n }", "hasCapacity() {\n return this._capacity > 0;\n }", "async wdf(effectiveFrom) {\n const myWdf = {};\n const effectiveFromEpoch = effectiveFrom.getTime();\n\n // employer type\n myWdf.employerType = {\n isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('EmployerType'))\n ? 'Yes'\n : 'No',\n updatedSinceEffectiveDate: this._properties.get('EmployerType').toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n // main service & Other Service & Service Capacities & Service Users\n myWdf.mainService = {\n isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('MainServiceFK'))\n ? 'Yes'\n : 'No',\n updatedSinceEffectiveDate: this._properties.get('MainServiceFK').toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n // capacities eligibility is only relevant to the main service capacities (other services' capacities are not relevant)\n // are capacities. Otherwise, it (capacities eligibility) is not relevant.\n // All Known Capacities is available from the CapacityServices property JSON\n const hasCapacities = this._properties.get('CapacityServices')\n ? this._properties.get('CapacityServices').toJSON(false, false).allServiceCapacities.length > 0\n : false;\n\n let capacitiesEligible;\n if (hasCapacities) {\n // first validate whether any of the capacities are eligible - this is simply a check that capacities are valid.\n const capacitiesProperty = this._properties.get('CapacityServices');\n\n // we're only interested in the main service capacities\n const mainServiceCapacities = capacitiesProperty\n .toJSON(false, false)\n .allServiceCapacities.filter((thisCapacity) => /^Main Service: /.test(thisCapacity.service));\n\n if (mainServiceCapacities.length === 0) {\n capacitiesEligible = 'Not relevant';\n } else {\n // ensure all all main service's capacities have been answered - note, the can only be one Main Service capacity set\n capacitiesEligible = mainServiceCapacities[0].questions.every((thisQuestion) => hasProp(thisQuestion, 'answer'))\n ? 'Yes'\n : 'No';\n }\n } else {\n capacitiesEligible = 'Not relevant';\n }\n\n myWdf.capacities = {\n isEligible: capacitiesEligible,\n updatedSinceEffectiveDate: this._properties\n .get('CapacityServices')\n .toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n const serviceUsers = this._properties.get('ServiceUsers');\n myWdf.serviceUsers = {\n // for service users, it is not enough that the property itself is valid, to be WDF eligible it\n // there must be at least one service user\n isEligible:\n this._isPropertyWdfBasicEligible(effectiveFromEpoch, serviceUsers) && serviceUsers.property.length > 0\n ? 'Yes'\n : 'No',\n updatedSinceEffectiveDate: serviceUsers.toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n // vacancies, starters and leavers\n myWdf.vacancies = {\n isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('Vacancies'))\n ? 'Yes'\n : 'No',\n updatedSinceEffectiveDate: this._properties.get('Vacancies').toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n myWdf.starters = {\n isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('Starters')) ? 'Yes' : 'No',\n updatedSinceEffectiveDate: this._properties.get('Starters').toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n myWdf.leavers = {\n isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('Leavers')) ? 'Yes' : 'No',\n updatedSinceEffectiveDate: this._properties.get('Leavers').toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n // removing the cross-check on #workers from establishment's own (self) WDF Eligibility\n // let totalWorkerCount = await this.getTotalWorkers();\n\n myWdf.numberOfStaff = {\n // isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('NumberOfStaff')) && this._properties.get('NumberOfStaff').property == totalWorkerCount ? 'Yes' : 'No',\n isEligible: this._isPropertyWdfBasicEligible(effectiveFromEpoch, this._properties.get('NumberOfStaff'))\n ? 'Yes'\n : 'No',\n updatedSinceEffectiveDate: this._properties.get('NumberOfStaff').toJSON(false, true, WdfCalculator.effectiveDate),\n };\n\n return myWdf;\n }", "get energyCapacity() {\n const pred = (structure) => structure instanceof StructureSpawn,\n energyStructures = _.filter(_structures.get(this.name), pred),\n get = (structure) => structure.store.getCapacity(RESOURCE_ENERGY);\n return _.sum(energyStructures, get);\n }", "function allocate(capacity) {\n const result = [];\n /**\n * @see https://v8.dev/blog/elements-kinds?fbclid=IwAR337wb3oxEpjz_5xVHL-Y14gUpVElementOztLSIikVVQLGN6qcKidEjMLJ4vO3M\n */\n while (result.length != capacity) {\n result.push(ArrayPack.DEFAULT_VALUE);\n }\n return new ArrayPack(result, 0);\n }", "hasCapacity() {\n if (this.type === \"starshipWeapon\") {\n return (\n this.data.data.weaponType === \"tracking\"\n || this.data.data.special[\"mine\"]\n || this.data.data.special[\"transposition\"]\n || this.data.data.special[\"orbital\"]\n || this.data.data.special[\"rail\"]\n || this.data.data.special[\"forcefield\"]\n || this.data.data.special[\"limited\"]\n );\n }\n\n return (this.getMaxCapacity() > 0);\n }", "getCapacity() {\n return this._capacity;\n }", "enableFargateCapacityProviders() {\n for (const provider of ['FARGATE', 'FARGATE_SPOT']) {\n if (!this._capacityProviderNames.includes(provider)) {\n this._capacityProviderNames.push(provider);\n }\n }\n }", "emptyComponents(newSpaceAvailable) {\n var namesOfEmptiedComponents = [];\n for (var i = 0; i < this.components.length; i++) {\n namesOfEmptiedComponents.push(this.components[i].name);\n }\n this.components = [];\n this.totalWeight = 0;\n this.totalSpaceUsed = 0;\n this.shelfCavity = newSpaceAvailable;\n return namesOfEmptiedComponents;\n }", "get capacity () {\n\t\treturn this._capacity;\n\t}", "function getCapacity(clipPity, clip_size, cores, base_cores, gun_capacity_mastery, gun_capacity_collections, capAug, armour_perc_bonus) {\n // Capacity augment\n let initialCap = clip_size * ([0, 0.1, 0.3, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.5][capAug]);\n // Cap aug is not accurate, adjust by subtracting by 1 on certain aug levels when capacity is an integer\n let capCorrection = [0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0][capAug];\n if(initialCap % 1 == 0){\n initialCap -= capCorrection;\n }else{\n initialCap = Math.floor(initialCap);\n }\n\n // Capacity aug gives atleast 1 bullet per level\n let cap_aug_amount = 0;\n if(initialCap < capAug){\n cap_aug_amount = capAug;\n }else{\n cap_aug_amount = initialCap;\n }\n\n // Clip pity; if true, cores give atleast 1 bullet per added core, regardless of base clip size\n let clip_cores = 0;\n if(clipPity){\n let additionCapCores = Math.floor(clip_size * (base_cores-1));\n if(additionCapCores < cores){\n clip_cores = cores;\n }else{\n clip_cores = additionCapCores;\n }\n }else{\n clip_cores = Math.round(clip_size * (base_cores-1));\n }\n\n // Extra bullet given by armour bonuses (mastodon only as of right now), gives atleast 1 bullet\n let armour_bonus = Math.floor(clip_size * armour_perc_bonus);\n if(armour_perc_bonus > 0 & armour_bonus < 1){\n armour_bonus = 1;\n }\n\n // Extra clip size from masteries, either percentage based or a static number\n let mastery_cap = 0;\n if (typeof gun_capacity_mastery === 'string' || gun_capacity_mastery instanceof String) { // % based\n let perc_conv = 0.01 * parseInt(gun_capacity_mastery.slice(0, -1)); // Because % values get stored in an annoying way\n mastery_cap = Math.floor(clip_size * perc_conv);\n if(mastery_cap < 1){\n mastery_cap = 1;\n }\n } else { // static amount\n mastery_cap += gun_capacity_mastery;\n }\n\n // Extra clip size from collection, either percentage based or a static number\n let collections_cap = 0;\n if (typeof gun_capacity_collections === 'string' || gun_capacity_collections instanceof String) { // % based\n let coll_perc = 0.01 * parseInt(gun_capacity_collections.slice(0, -2));\n collections_cap += Math.floor(clip_size * coll_perc); // Because % values get stored in an annoying way\n } else { // static number\n collections_cap += gun_capacity_collections;\n }\n\n // Total clip size after all bonuses\n let capacity = clip_size + cap_aug_amount + clip_cores + armour_bonus + mastery_cap + collections_cap;\n\n// console.log(\"initialCap\", initialCap);\n// console.log(\"#####\");\n// console.log(\"clip_size\", clip_size);\n// console.log(\"cap_aug_amount\", cap_aug_amount);\n// console.log(\"clip_cores\", clip_cores);\n// console.log(\"armour_check\", armour_bonus);\n// console.log(\"mastery_cap\", mastery_cap);\n// console.log(\"collections_cap\", collections_cap);\n// console.log(\"#####\");\n// console.log(\"capacity\", capacity);\n\n return capacity;\n}", "getCapacity()\n\t{\n\t\treturn this.capacity;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Debounces a function. Returns a function that calls the original fn function only if no invocations have been made within the last quietMillis milliseconds.
function debounce(quietMillis, fn) { var timeout; return function() { window.clearTimeout(timeout); timeout = window.setTimeout(fn, quietMillis); }; }
[ "function debounce(quietMillis,fn,ctx){ctx=ctx||undefined;var timeout;return function(){var args=arguments;window.clearTimeout(timeout),timeout=window.setTimeout(function(){fn.apply(ctx,args)},quietMillis)}}", "function debounce(quietMillis, fn, ctx) {\n ctx = ctx || undefined;\n var timeout;\n return function () {\n var args = arguments;\n window.clearTimeout(timeout);\n timeout = window.setTimeout(function () {\n fn.apply(ctx, args);\n }, quietMillis);\n };\n }", "function debounce(quietMillis, fn, ctx) { // 224\n ctx = ctx || undefined; // 225\n var timeout; // 226\n return function () { // 227\n var args = arguments; // 228\n window.clearTimeout(timeout); // 229\n timeout = window.setTimeout(function() { // 230\n fn.apply(ctx, args); // 231\n }, quietMillis); // 232\n }; // 233\n } // 234", "function debounce(quietMillis, fn, ctx) {\r\n ctx = ctx || undefined;\r\n var timeout;\r\n return function () {\r\n var args = arguments;\r\n window.clearTimeout(timeout);\r\n timeout = window.setTimeout(function() {\r\n fn.apply(ctx, args);\r\n }, quietMillis);\r\n };\r\n }", "function debounce(quietMillis,fn,ctx){ctx = ctx || undefined;var timeout;return function(){var args=arguments;window.clearTimeout(timeout);timeout = window.setTimeout(function(){fn.apply(ctx,args);},quietMillis);};}", "function debounce(quietMillis, fn, ctx) {\n ctx = ctx || undefined;\n var timeout;\n return function () {\n var args = arguments;\n window.clearTimeout(timeout);\n timeout = window.setTimeout(function() {\n fn.apply(ctx, args);\n }, quietMillis);\n };\n }", "function debounce(quietMillis, fn, ctx) {\r\n ctx = ctx || undefined;\r\n var timeout;\r\n return function () {\r\n var args = arguments;\r\n window.clearTimeout(timeout);\r\n timeout = window.setTimeout(function() {\r\n fn.apply(ctx, args);\r\n }, quietMillis);\r\n };\r\n }", "function debounce(quietMillis, fn, ctx) {\n ctx = ctx || undefined;\n var timeout;\n return function () {\n var args = arguments;\n window.clearTimeout(timeout);\n timeout = window.setTimeout(function () {\n fn.apply(ctx, args);\n }, quietMillis);\n };\n }", "function debounce(fn, ms){\n let startTime = 0;\n return function(){\n if (!startTime){ //run in the first call\n fn.apply(null, arguments);\n startTime = Date.now();\n }\n else if (Date.now() - startTime >= ms){ //check if ms amount time passed from the last call\n fn.apply(null, arguments);\n startTime = Date.now();\n }\n else {\n return;\n }\n } \n}", "function debounced(delay, fn) {\n let timerId;\n return function (...args) {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout(() => {\n fn(...args);\n timerId = null;\n }, delay);\n }\n}", "function debounce(fn) {\n\t\t\treturn function() {\n\t\t\t\tclearTimeout(self.flushTimeoutHandle);\n\t\t\t\tself.flushTimeoutHandle = setTimeout(fn, self.flushDebounceMs);\n\t\t\t};\n\t\t}", "function debounce(delay, fn) {\n var inDebounce;\n return function(...args) {\n clearTimeout(inDebounce);\n inDebounce = setTimeout(function inDebounce() {\n fn(...args);\n }, delay);\n };\n }", "function debounce(f, waitMs) {\n var lastTime = tfc.util.now();\n var lastResult;\n var f2 = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var now = tfc.util.now();\n if (now - lastTime < waitMs) {\n return lastResult;\n }\n lastTime = now;\n lastResult = f.apply(void 0, args);\n return lastResult;\n };\n return f2;\n}", "function debounceThrottle(fn, milliseconds) {\n let timeout;\n let lastInvocation = Date.now() - milliseconds;\n function maybeCall(...args) {\n clearTimeout(timeout);\n timeout = setTimeout(() => {\n if (Date.now() - lastInvocation < milliseconds) {\n maybeCall(...args);\n return;\n }\n fn(...args);\n lastInvocation = Date.now();\n }, milliseconds);\n }\n return maybeCall;\n}", "function debounce(f, ms) {\n\n let isCooldown = false;\n\n return function () {\n if (isCooldown) return;\n\n f.apply(this, arguments);\n\n isCooldown = true;\n\n setTimeout(() => isCooldown = false, ms);\n };\n\n}", "function debounce(f, waitMs) {\n var lastTime = tfjs_core_1.util.now();\n var lastResult;\n var f2 = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var now = tfjs_core_1.util.now();\n if (now - lastTime < waitMs) {\n return lastResult;\n }\n lastTime = now;\n lastResult = f.apply(void 0, args);\n return lastResult;\n };\n return f2;\n}", "function debounce(fn, delay) {\n var timeout;\n return function () {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {\n args[_key3] = arguments[_key3];\n }\n if (delay) {\n clearTimeout(timeout);\n timeout = setTimeout(fn, delay, args);\n } else {\n fn.apply(this, args);\n }\n return delay;\n };\n }", "function _debounce(func, wait, immediate) {\n var timeout;\n var result;\n\n return function() {\n var context = this;\n var args = arguments;\n var later = function() {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n }\n };\n var callNow = immediate && !timeout;\n\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n }\n return result;\n };\n }", "function debounce(func, freq) {\n\tvar timeout = null;\n\tvar requestFire = false;\n\t\n\treturn function() {\n\t\tvar context = this, args = arguments;\n\t\tvar later = function() {\n\t\t\ttimeout = null;\n\t\t\tif (requestFire) {\n\t\t\t\tfunc.apply(context, args);\n\t\t\t\trequestFire = false;\n\t\t\t}\n\t\t};\n\t\tif (!timeout) {\n\t\t\tfunc.apply(context, args);\n\t\t\ttimeout = setTimeout(later, freq);\n\t\t\trequestFire = false;\n\t\t}\n\t\telse {\n\t\t\trequestFire = true;\n\t\t}\n\t};\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns weekly high scores
function getHighScores(callback) { pool.getConnection(function(err, connection) { var weekAgo = moment().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss'); var query = ` SELECT DISTINCT * FROM scores WHERE date > '${weekAgo}' ORDER BY score DESC LIMIT 5 `; connection.query(query, function (err, results) { connection.release(); if (err) throw err; if (typeof callback === 'function') { callback(results); } }); }); }
[ "async get_weekly_scores(req, res, next) {\n const Matchup = this.models.get('Matchup')\n\n const current_week = await this.sports_data.current_play_week()\n const weekly_data = []\n\n // Convert all of the matchup instances to API format for each week\n for ( let i = 1; i <= current_week; i += 1 ) {\n const matchups = await Matchup.find({ week_num: i })\n const api_data = await Promise.all(matchups.map(x => x.to_api()))\n weekly_data.push(api_data)\n }\n\n return res.api(weekly_data)\n }", "function getHighs(){\n const highs = weather.week.map(day => day.high)\n console.log(highs);\n return highs\n }", "function getPrevWeekScore(team, schedule, prevWeek) {\n\n // get the previous week's games, search for that team's game and return the score\n let prevWeekGames = schedule[prevWeek].games;\n let numPrevWeekGames = prevWeekGames.length;\n let teamFound = false;\n\n for (let k = 0; k < numPrevWeekGames; k++) {\n\n // console.log(prevWeekGames[k].home.name)\n // console.log(prevWeekGames[k].away.name)\n\n // if we find a match for the team name in the previous week's game, console.log the score of that game\n if (prevWeekGames[k].home.name.includes(team) || prevWeekGames[k].away.name.includes(team)) {\n teamFound = true;\n\n let teamScoreKey = prevWeekGames[k].home.name.includes(team) ? \"home_points\" : \"away_points\";\n let opposingScoreKey = prevWeekGames[k].home.name.includes(team) ? \"away_points\" : \"home_points\";\n\n let teamName = prevWeekGames[k].home.name.includes(team) ? prevWeekGames[k].home.name : prevWeekGames[k].away.name;\n let opposingName = prevWeekGames[k].home.name.includes(team) ? prevWeekGames[k].away.name : prevWeekGames[k].home.name;\n\n let teamScore = prevWeekGames[k].scoring[teamScoreKey];\n let opposingScore = prevWeekGames[k].scoring[opposingScoreKey];\n\n let recencyInWeeks = weeksBetween(new Date(prevWeekGames[k].scheduled), new Date());\n // let dateInfo = recencyInWeeks===-1 ? \"two weeks ago\" : \"last week\"; \n\n \n\n let higherScore = teamScore > opposingScore ? teamScore : opposingScore;\n let lowerScore = teamScore <= opposingScore ? teamScore : opposingScore;\n\n console.log(`${GOOGLE_NEWS_API_BASE_URL}everything?apiKey=${GOOGLE_NEWS_API_KEY}&q=`+teamName.split(' ')[1]+\"+\"+opposingName.split(' ')[1]+\"+\"+higherScore+\"-\"+lowerScore)\n\n // ***************** TO DO: PUT THIS IN A FUNCTION ***************** //\n request({\n \"url\": `${GOOGLE_NEWS_API_BASE_URL}everything?apiKey=${GOOGLE_NEWS_API_KEY}&q=`+teamName.split(' ')[1]+\"+\"+opposingName.split(' ')[1]+\"+\"+higherScore+\"-\"+lowerScore,\n \"method\": \"GET\"\n }, (err, res, body) => {\n\n\n\n let articles = JSON.parse(body).articles;\n let numArticles = articles.length;\n\n if (numArticles > 0) {\n console.log(\"\\n\\nHere are the latest headlines for the\".green.bold+\" \"+team.green.bold+\":\");\n for (var i=0; i < numArticles; i++) {\n\n if (articles[i].title && articles[i].description && articles[i].content && (articles[i].title.includes(higherScore+\"-\"+lowerScore) || articles[i].description.includes(higherScore+\"-\"+lowerScore) ||\n articles[i].content.includes(higherScore+\"-\"+lowerScore))) {\n \n\n // ***************** TO DO: FORMAT THIS NICELY SO PRINTS PRETTY IN CONSOLE ***************** //\n console.log(articles[i]);\n }\n }\n \n } else {\n console.log(\"\\n\\n\"+\"Hmm...I'm pretty dumb so I didn't find anything recent on the \".white.bold.bgRed+team.white.bold.bgRed+\". Try asking Google!\".white.bold.bgRed+\"\\n\\n\");\n \n }\n \n if (err){\n console.log(\"News API Error: \", err);\n }\n });\n\n\n }\n\n\n }\n\n if (!teamFound) {\n getPrevWeekScore(team, schedule, prevWeek-1);\n\n }\n\n\n}", "function getHighScore() {\n let highScore = 0;\n for (score of scoresTally) {\n if (score > highScore) {\n highScore = score;\n }\n }\n return highScore;\n}", "function getWeeklyData() {\n var ss = SpreadsheetApp.openById(GLOBALS.sheetId);\n var menuSheet = ss.getSheetByName(\"Menu\")\n var w = menuSheet.getRange(\"B8\").getValue();\n getMatchups(w);\n getWeeklyPlayerStats(w);\n getWeeklyScores();\n}", "function getWeeklyGoal() {\n const startDate = 1597042800000;\n const today = new Date();\n var daysPast = (today.getTime()-startDate) / 86400000;\n var weekNumber = Math.floor(daysPast / 7);\n var goal = 750 + weekNumber * 250;\n return goal;\n}", "function previousWeekHigh (week) {\n return week > 0 ? weekBars[week - 1].H : undefined\n}", "function weeksInSemester( data ) {\n\n\tnum_weeks = -1;\n\t\n\t// loop through all data and find max num of weeks\n\tObject.keys(data).forEach( function( student ){\n\t\tdata[student].forEach( function( assignment ){\n\t\t\t\n\t\t\tassign_week = parseInt( assignment.week , 10 ); // string to int\n\t\t\tif( assign_week > num_weeks)\n\t\t\t\tnum_weeks = assign_week;\n\n\t\t});\n\t});\n\n\t// create an array of weeks\n\tweeks = [];\n\tfor( var i = 1; i <= num_weeks; i++ )\n\t\tweeks.push(i);\n\n\treturn weeks;\n}", "determineWeeklySleepQuality(todaysDate) {\n this.determineWeeklySchedule();\n let weeklySleepQuality = [];\n let dayCounter = 0;\n this.weeklyRecords.forEach(week => {\n if (week.includes(todaysDate)) {\n week.forEach(day => {\n dayCounter++;\n weeklyHoursSlept.push(`Day ${dayCounter}: ${day.sleepQuality}`);\n })\n }\n })\n return weeklySleepQuality;\n }", "function getLows(){\n const lows = weather.week.map((day) => day.low)\n return lows\n }", "function calculatePercent(score) {\n let weekend = getLengthOfWeekend();\n let maxScore = 702;\n if (weekend.length === 2) {\n maxScore = (702 / 3) * 2;\n } else if (weekend.length === 1) {\n maxScore = (702 / 3);\n }\n let result = (score / maxScore) * 100;\n return result;\n}", "function getHighs(){\n const highs = weather.week.map( day => day.high);\n // console.log(highs);\n return highs;\n}", "function determineWeek(responses) {\n var cur_vote = 0;\n var submit_time = new Date(responses.submit_time);\n if (submit_time <= new Date(2020,1,12,20)) {\n cur_vote = \"1a\";\n } else if (submit_time <= new Date(2020,1,13,20)) {\n cur_vote = \"1b\";\n } else if (submit_time <= new Date(2020,1,19,20)) {\n cur_vote = 2;\n } else if (submit_time <= new Date(2020,1,26,20)) {\n cur_vote = 3;\n } else if (submit_time <= new Date(2020,2,4,20)) {\n cur_vote = 4;\n } else if (submit_time <= new Date(2020,2,11,20)) {\n cur_vote = 5;\n } else if (submit_time <= new Date(2020,2,18,20)) {\n cur_vote = 6;\n } else if (submit_time <= new Date(2020,2,25,20)) {\n cur_vote = 7;\n } else if (submit_time <= new Date(2020,3,1,20)) {\n cur_vote = 8;\n } else if (submit_time <= new Date(2020,3,8,20)) {\n cur_vote = 9;\n } else if (submit_time <= new Date(2020,3,15,20)) {\n cur_vote = 10;\n } else if (submit_time <= new Date(2020,3,22,20)) {\n cur_vote = 11;\n } else if (submit_time <= new Date(2020,3,29,20)) {\n cur_vote = 12;\n } else if (submit_time <= new Date(2020,4,6,20)) {\n cur_vote = 13;\n } else if (submit_time <= new Date(2020,4,13,20)) {\n cur_vote = 14;\n };\n return cur_vote;\n}", "function getHighs(){\n const highs = weather.week.map(day => day.high)\n // console.log(highs);\n return highs\n}", "high () {\n return scores.reduce(function (currentHighest, score) {\n return currentHighest.higherOf(score);\n }, Score(\"bust\"))\n }", "function createHighscore(){\n\t_highscore = {};\n\tfor(var gameId in _games){\n\t\tvar game = _games[gameId];\n\t\tvar hTeam = _teams[game.homeTeam];\n\t\tvar aTeam = _teams[game.awayTeam];\n\n\t\t//Get the current highscore rows;\n\t\tvar hRow = _highscore[game.homeTeam];\n\t\tvar aRow = _highscore[game.awayTeam];\n\t\tif(hRow == undefined){\n\t\t\thRow = getDefaultHighScoreRow(game.homeTeam);\n\t\t}\n\t\tif(aRow == undefined){\n\t\t\taRow = getDefaultHighScoreRow(game.awayTeam);\n\t\t}\n\n\t\t//Goal diff\n\t\thRow.played += 1;\n\t\taRow.played += 1;\n\t\thRow.goalMade += game.homeGoal;\n\t\thRow.goalLetIn += game.awayGoal;\n\t\taRow.goalMade += game.awayGoal;\n\t\taRow.goalLetIn += game.homeGoal;\n\t\thRow.goalDiff = hRow.goalMade - hRow.goalLetIn;\n\t\taRow.goalDiff = aRow.goalMade - aRow.goalLetIn;\n\n\t\t//Whom won\n\t\tif(game.homeGoal > game.awayGoal){\n\t\t\thRow.won += 1;\n\t\t\taRow.lost += 1;\n\t\t\thRow.points += 3;\n\t\t} else if(game.homeGoal == game.awayGoal){\n\t\t\thRow.draw += 1;\n\t\t\taRow.draw += 1;\n\t\t\thRow.points += 1;\n\t\t\taRow.points += 1;\n\t\t} else {\n\t\t\thRow.lost += 1;\n\t\t\taRow.won += 1;\n\t\t\taRow.points += 3;\n\t\t}\n\n\t\t//Save down the result\n\t\t_highscore[game.homeTeam] = hRow;\n\t\t_highscore[game.awayTeam] = aRow;\n\t}\n}", "function getHighScores(position) {\r\n return highScores[position]\r\n }", "function getMaxStats(playerStats,statName,week)\n{\n\tvar max =0;\n\t$.each(playerStats.stats,function(i,stat)\n\t{\n\t\t// Only considers the weekly results in the timeframe defined, skips the averages and totals\n\t\tif(i != \"AVG\" && i!=\"TOTAL\" && i<=week)\n\t\t{\n\t\t\tif(max<stat[statName])\n\t\t\t{\n\t\t\t\tmax = stat[statName];\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\t\n\t})\n\treturn max;\n}", "function calcLastWeek() {\n calcLastHours(7*24, 'w');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
insertRecipe async function that takes in as argument an array with recipe name and description and resolves the inserted ID in db
async function insertRecipe(recipe) { return new Promise(function(resolve, reject) { let sql_query = "INSERT INTO `Recipe` (`Name`, `Description`) VALUES (?, ?)"; mysql.pool.query(sql_query, recipe, function(err, result) { if (err) { next(err); return; } resolve(result.insertId); }); }); }
[ "function addRecipe(recipe) {\nreturn db('recipe')\n .insert(recipe)\n .then(ids => ({ id: ids[0] }));\n}", "insertRecipe(db, ingredients, newRecipe, recipeIngredients) {\n let newRecipeId;\n return (\n db\n // using a transaction with async/await in order to ensure proper order of data submission based on dependencies\n // transaction will rollback if an error occurs at any point in the process to prevent incomplete data insertion\n .transaction(async trx => {\n // insert ingredients data, and for each ingredient, assign id returned from database to associated recipeIngredients entry\n await trx\n .into(\"ingredients\")\n .insert(ingredients)\n .returning(\"*\")\n .then(ingredients => {\n for (let i = 0; i < ingredients.length; i++) {\n recipeIngredients[i].ingredient_id = ingredients[i].id;\n }\n });\n // insert recipe data, and assign recipe_id returned from database to each entry in recipeIngredients\n await trx\n .into(\"recipes\")\n .insert(newRecipe)\n .returning(\"id\")\n .then(([recipeId]) => recipeId)\n .then(recipeId => {\n for (let recipeIngredient of recipeIngredients) {\n recipeIngredient.recipe_id = recipeId;\n }\n newRecipeId = recipeId;\n });\n // insert recipeIngredients data\n await trx.into(\"recipes_ingredients\").insert(recipeIngredients);\n })\n // query database for recipe data based on new recipe ID and return response\n .then(() => {\n return RecipesService.getById(db, newRecipeId);\n })\n );\n }", "function addRecipe(recipe) {\n return db('recipes')\n .insert(recipe)\n .then(ids => ({ id: ids[0] }));\n}", "function saveIngredients(ingredients, recipeId) {\n const rows = ingredients.map(ingredient => ({\n ...ingredient,\n recipe_id: recipeId\n }));\n\n return db.batchInsert('ingredients', rows)\n .then(() => recipeId);\n}", "saveInfo(recipe) {\n console.log(recipe);\n recipe.id = Number.parseInt(recipe.id, 10);\n // First insertion in the recipes table\n return db.one(`\n INSERT INTO recipes\n (rec_name, category, servings, prep_time, level, calories, ingredients, directions, pic)\n VALUES\n ($/rec_name/, $/category/, $/servings/, $/prep_time/, $/level/, $/calories/, $/ingredients/, $/directions/, $/pic/)\n RETURNING *\n `, recipe)\n }", "function upload_recipe(recipe_info, res){\n\n /* get all the recipe values and assign them to variables */\n var recipe_name = slashes.add(recipe_info[0]['recipe_name']);\n // sql for inserting intial recipe into \"recipes\" and getting its insert id\n var create_sql = `INSERT INTO recipes (recipe_name) VALUES ('${recipe_name}')`;\n dbinsert(create_sql, recipe_info, res);\n\n}", "async addRecipe(recipeName,ingredients){\n if(ingredients == null){\n return null;\n }\n if(recipeName == null){\n return null;\n }\n\n var recipe = new Recipe(recipeName,ingredients);\n\n if(recipe.getIngredients().length <= 0){\n return null;\n }\n\n try{\n const client = new MongoClient(this.uriString);\n \n await client.connect();\n const db = client.db(this.databaseString);\n const recipeCollection = db.collection(this.collectionString);\n \n var status = await recipeCollection.insertOne(recipe);\n client.close();\n return status;\n //console.log(await recipeCollection.find({recipeName:recipeName}).toArray());\n \n }\n catch(e){\n console.error(\"Failed addRecipe() params: \"+recipeName+\" \"+ingredients+e);\n return null;\n }\n //String recipeName List<String> ingredients\n //creates connection with mongo database.\n //add {name:'recipeName',ingredients:'ingredients'} to mongoDB\n \n }", "function addRecipe(recipeName, recipeID, db = connection){\n return db('recipes')\n .insert({\n name: recipeName,\n id: recipeID\n })\n}", "async function insertRecipeComponent(recipe_component) {\n return new Promise(function(resolve, reject) {\n let sql_query = \"INSERT INTO `Recipe_RecipeComponent` (`RecipeID`, `RecipeComponentID`) VALUES (?, ?)\";\n mysql.pool.query(sql_query, recipe_component, function(err, result) {\n if (err) {\n next(err);\n return;\n }\n resolve(result.insertId);\n });\n });\n}", "async function insertComponents(recipe_components) {\n return new Promise(function(resolve, reject) {\n let sql_query = \"INSERT INTO `RecipeComponent` (`IngredientID`, `Amount`, `MeasurementType`) VALUES (?, ?, ?)\";\n mysql.pool.query(sql_query, recipe_components, function(err, result) {\n if (err) {\n next(err);\n return;\n }\n resolve(result.insertId);\n });\n });\n}", "function insertRecipe(recipeDataName, recipe, userId, recipeSource, recipeImage) {\n console.log(\"insertRecipe working\");\n var recipesArray = {\n recipeName: recipeDataName,\n recipeSource: recipeSource,\n recipeImage: recipeImage,\n id: recipe,\n UsersTableId: userId\n };\n $.post(\"/api/recipes\", recipesArray);\n }", "async function insertData() {\n\t// First, insert users into User table\n\tconst userIDs = await insertUsers();\n\n\tconsole.log(`Got user IDs: ${JSON.stringify(userIDs)}`);\n\n\t// Iterate over each recipe and the ingredients\n\tfor (let i = 0; i < inputData.length; i++) {\n\t\tconst ptr = inputData[i].recipe;\n\t\t\n\t\t// Prepare a single recipe data for inserting into Recipes table\n\t\tlet _recipe = {\n\t\t\tname: ptr.label,\n\t\t\tdescription: ptr.url,\n\t\t\timage: null,\n\t\t\timageURL: ptr.image,\n\t\t\tgluten_free: (ptr.cautions.findIndex(e => /Gluten/i.test(e)) > -1),\n\t\t\tdairy_free: (ptr.ingredientLines.findIndex(e => /milk|cheese/i.test(e)) > -1),\n\t\t\tvegetarian: (ptr.healthLabels.findIndex(e => /vegetarian/i.test(e)) > -1),\n\t\t\tvegan: (ptr.healthLabels.findIndex(e => /vegan/i.test(e)) > -1),\n\t\t\tprep_time: (ptr.totalTime == 0) ? Math.floor(Math.random() * 20) : Math.round(ptr.totalTime * 0.2),\n\t\t\tcook_time: (ptr.totalTime == 0) ? Math.floor(Math.random() * 180) : Math.round(ptr.totalTime * 0.8),\n\t\t\tinstructions: null, //JSON.stringify(ptr), // oops, save the whole recipe data \n\t\t\trating: Math.floor(Math.random() * 10) + 1\n\t\t};\n\n\t\t// Insert each _recipe into Recipes table\n\t\tdb.Recipes.findOrCreate({\n\t\t\t\twhere: {\n\t\t\t\t\tname: _recipe.name\n\t\t\t\t},\n\t\t\t\tdefaults: _recipe\n\t\t\t})\n\t\t\t.spread((recipe, createdRecipe) => {\n\t\t\t\t// randomly assign a user for the recipe post\n\t\t\t\tconst _userProfile = {\n\t\t\t\t\tfavorite: Math.floor(Math.random() < 0.25), // favor by 25% chance\n\t\t\t\t\tposted: true,\n\t\t\t\t\tRecipeId: recipe.id,\n\t\t\t\t\tUserId: userIDs[Math.floor(Math.random() * userIDs.length)]\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t// Obtaining recipe ID is critical for UserProfile and Ingredients foreign key \n\t\t\t\tif (!recipe || !recipe.id) {\n\t\t\t\t\tconsole.log(JSON.stringify(recipe));\n\t\t\t\t\tthrow \"No recipe ID\";\n\t\t\t\t}\t\n\t\t\t\t// inesrt into the UserProfile table\n\t\t\t\tdb.UserProfile.create(_userProfile);\n\n\t\t\t\t// Iterate over each ingredient of this recipe\n\t\t\t\tfor (let j = 0; j < ptr.ingredients.length; j++) {\n\t\t\t\t\t// Prepare a single product/ingredient data for insertion\n\t\t\t\t\tlet _product = {\n\t\t\t\t\t\tname: ptr.ingredients[j].text,\n\t\t\t\t\t\tcalories: ptr.calories, // this is actually total for the recipe\n\t\t\t\t\t};\n\n\t\t\t\t\t// Insert each _product into Products table\n\t\t\t\t\tdb.Products.findOrCreate({\n\t\t\t\t\t\t\twhere: {\n\t\t\t\t\t\t\t\tname: _product.name,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tdefaults: _product\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.spread((product, createdProduct) => {\n\t\t\t\t\t\t\t// Obtaining product ID is critical for Ingredients table\n\t\t\t\t\t\t\tif (!product || !product.id) {\n\t\t\t\t\t\t\t\tthrow \"No product ID\";\n\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Prepare an ingredient data for insertion into Ingredients table\n\t\t\t\t\t\t\tlet _ingredient = {\n\t\t\t\t\t\t\t\tamount: ptr.ingredients[j].weight,\n\t\t\t\t\t\t\t\tRecipeId: recipe.id,\n\t\t\t\t\t\t\t\tProductId: product.id\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// Insert _ingredient into Ingredients table\n\t\t\t\t\t\t\tdb.Ingredients.findOrCreate({\n\t\t\t\t\t\t\t\t\twhere: {\n\t\t\t\t\t\t\t\t\t\tRecipeId: recipe.id,\n\t\t\t\t\t\t\t\t\t\tProductId: product.id\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tdefaults: _ingredient\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t.spread((ingredient, createdIngredient) => {\n\t\t\t\t\t\t\t\t\tconsole.log(`Inserted recipeId ${recipe.id} product ${product.id} ingredient ${ingredient.id}`);\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t}\n}", "async createIngredient(id, name, measuring_unit, measuring_size, price, price_currency_iso3, conn = null) {\n let log_path = 'IngredientProvider/createIngredient -'\n let is_conn_external = true;\n try {\n if (!conn) {\n conn = await mysql_provider.getConnection();\n is_conn_external = false;\n }\n let query = ` SET @id = fn_uuid_from_bin(?);\n SET @name = ?;\n SET @measuring_unit = ?;\n SET @measuring_size = ?;\n SET @price = ?;\n SET @price_currency_iso3 = ?;\n \n INSERT INTO ingredients\n (\n ingredient_id,\n ingredient_name,\n ingredient_measuring_unit,\n ingredient_measuring_size,\n ingredient_price,\n ingredient_price_currency_iso3\n )\n VALUES\n (\n @id,\n @name,\n @measuring_unit,\n @measuring_size,\n @price,\n @price_currency_iso3\n );`;\n\n const params = [id, name, measuring_unit, measuring_size, price, price_currency_iso3];\n await mysql_provider.executeQueryWithConnection(conn, query, params);\n let result = await mysql_provider.executeQueryWithConnection(conn, this.select_by_id_query, [new_recipe.id]);\n if (!is_conn_external) {\n mysql_provider.commitTransaction(conn);\n }\n return Promise.resolve(result);\n }\n catch (err) {\n if (!is_conn_external) {\n mysql_provider.rollbackTransaction(conn);\n }\n logger.err(`${log_path} error - ${err}`);\n }\n }", "insertNewRecipe(){\n\t\tfetch(\"/reactui/ingredients\", {\n method: 'POST',\n\t\t\theaders: {\n\t\t\t\t'Accept': 'application/json',\n\t\t\t\t'Content-Type': 'application/json'\n\t\t\t},\n\t\t\tbody: JSON.stringify(this.state.newRecipe)\n }).then((resp) => {\n\t\t\treturn resp;\n\t\t}).then((respMessage) => {\n alert(\"Http Status: \" + respMessage.status);\n if(respMessage.ok){\n this.clearNewRecipe();\n this.retrieveListOfIngredients();\n }\n\t\t}).catch((error) => {\n\t\t\talert(error.message);\n\t\t});\n }", "async function insertRecipeUser(recipe_user) {\n return new Promise(function(resolve, reject) {\n let sql_query = \"INSERT INTO `Recipes_Users` (`RecipeID`, `UserID`) VALUES (?, ?)\";\n mysql.pool.query(sql_query, recipe_user, function(err, result) {\n if (err) {\n next(err);\n return;\n }\n resolve(result.insertId);\n });\n });\n}", "function multiIngrInsert(recipe_id, ingredient) {\n // console.log('irecID:', recipe_id);\n // console.log('ingrd:', ingredient);\n ingredient.map((ingredient) => {\n this.addIngredient(ingredient, recipe_id);\n });\n return;\n}", "static async addNewRecipe(req, res){\n let status = 200;\n let body = {};\n try{\n let recipes = await Recipes.create({\n idUser: req.body.idUser,\n title: req.body.title,\n content: req.body.content,\n });\n body = {recipes, 'message': 'Recipe added'};\n }catch (error){\n status = 500;\n body = {'message': error.message};\n }\n return res.status(status).json(body); \n }", "async function seedRecipes() {\n let recipeData = await getRecipes();\n Recipe.bulkCreate(recipeData);\n}", "createRecipe(event){\n event.preventDefault();\n var recipeId;\n\n var recipeDetail = {\n userId: this.props.userId,\n recipeName: this.state.recipeName,\n description: this.state.description,\n cookingTime: this.state.cookingTime,\n servings: this.state.servings,\n secretRecipe: this.state.secretRecipe\n }\n axios.post('/createRecipe', recipeDetail).then((response)=>{ //response.data.insertId holds id of inserted recipe\n recipeId = response.data.insertId;\n insertIngredient(recipeId, this.state.ingredients).then(()=>{\n insertSteps(recipeId, this.state.stepsList).then(()=>{\n this.props.getAllUserRecipes(this.props.userId);\n this.props.history.push({pathname: \"/ViewRecipe/\"+(recipeId)}) \n })\n }) \n }).catch((err)=>{\n this.setState({errorMsg: \"There was an error creating your Recipe\"})\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
helper function to create and populate header row in table with categories
function populateHeadersInGameTable(array) { for (let i = 0; i < array.length; i++) { let $generatedGameTableCategoriesHTML = $(`<td class=" category-card category ${i}">${String(array[i].title)}</td>`) $gameCategoryRow.append($generatedGameTableCategoriesHTML); } }
[ "function createCategoryHeader(cat) {\n var top = $(\"<h1>\", {\n text: cat.name,\n class: \"top\",\n });\n var columnHeaders =\n '<div class=\"grid\">\\n\\t\\t\\t<div class=\"column-header name\">'\n .concat(\n text.columnHeaders.activity,\n '</div>\\t\\n\\t\\t\\t<div class=\"column-header info\">'\n )\n .concat(\n text.columnHeaders.info,\n '</div>\\t\\t\\n\\t\\t\\t<div class=\"column-header age\">'\n )\n .concat(\n text.columnHeaders.age,\n '</div>\\n\\t\\t\\t<div class=\"column-header schedule\">'\n )\n .concat(\n text.columnHeaders.schedule,\n '</div>\\t\\n\\t\\t\\t<div class=\"column-header session\">'\n )\n .concat(\n text.columnHeaders.session,\n '</div>\\t\\n\\t\\t\\t<div class=\"column-header price\">'\n )\n .concat(\n text.columnHeaders.price,\n '</div>\\t\\n\\t\\t\\t<div class=\"column-header cours\">'\n )\n .concat(\n text.columnHeaders.duration,\n '</div>\\n\\t\\t\\t<div class=\"column-header location\">'\n )\n .concat(\n text.columnHeaders.location,\n '</div>\\t\\n\\t\\t\\t<div class=\"column-header staff\">'\n )\n .concat(\n text.columnHeaders.staff,\n '</div>\\n\\t\\t\\t<div class=\"column-header start\">'\n )\n .concat(text.columnHeaders.start, \"</div>\\t\\n</div>\");\n var header = $(\"<div>\", {\n class: convertToClassSafe(cat.name) + \" category-header\",\n })\n .attr(\"data-always-visible\", \"true\")\n .append(top)\n .append(columnHeaders);\n return header;\n}", "function generateCategoriesHeader() {\n generateCategoriesHeaderWith('caties-head-left', selectedPartiLeft);\n generateCategoriesHeaderWith('caties-head-right', selectedPartiRight);\n}", "function categoryTable() { }", "function createHeaderRow() {\n $('<tr/>', {\n id: `header`\n }).appendTo('#content');\n\n for (var i = 0; i < cols; i++) {\n // check if we should show this column when constructing our test\n if (hideList.indexOf(i) === -1) {\n $('<th/>', {\n text: csvData[0][i]\n }).appendTo('#header');\n }\n }\n}", "function tableCreate() {\n\n $(\".table\").html(\"\");\n\n for(var i = 0; i < categories.length; i++) {\n $(\".table\").append(\"<div class=\\\"column\\\"></div>\");\n }\n\n for(var i=0; i < dataArr.length-1; i++) {\n if((dataArr[i][\"parent\"] != \" \" || dataArr[i][\"parent\"] != \" \") && checkArray(dataArr, dataArr[i][\"parent\"]) ) {\n dataArr.splice(i, 0, {name:dataArr[i][\"parent\"], assets:\"\", address:\"\", city:\"\", state:\"\", zip:\"\", url:\"\", county:\"\", parent:\"\", region:\"\"});\n }\n }\n\n for(var i = 0; i < dataArr.length; i++) {\n if(i == 0) {\n $(\".column\").append(\"<div class=\\\"cell category\\\"></div>\");\n }\n else {\n $(\".column\").append(\"<div class=\\\"cell\\\"></div>\");\n }\n }\n\n $(\".column\").each(function(index) {\n $(this).children(\".cell:nth-child(1)\").html(categories[index]);\n });\n\n}", "function createHeader(){\n columns = \"Owner,Name,Description,Latest Update,Clone URL\".split(\",\")\n tr = document.createElement(\"tr\")\n columns.forEach(col =>\n tr.appendChild(createHeaderCell(col))\n )\n return tr\n}", "function buildNewsTableHeader() {\n\n var thead = d3.select(\"#news-header\");\n console.log(\"buildNewsTableHeader:\", thead);\n\n thead.html(\"\");\n var tr = thead.append(\"tr\");\n\n tr.append(\"th\")\n .attr(\"scope\", \"col\")\n .text(\"#\"); \n\n tr.append(\"th\")\n .attr(\"scope\", \"col\")\n .text(\"Source\");\n\n tr.append(\"th\")\n .attr(\"scope\", \"col\")\n .text(\"Title\");\n \n tr.append(\"th\")\n .attr(\"scope\", \"col\") \n .text(\"Image\")\n}", "function createTableHeader() {\n var talks = \"<tr><th></th>\";\n var workshops = \"<tr><th></th>\";\n\n for (var key in rooms) {\n if (roomType(rooms[key]) == \"workshops\") {\n workshops += \"<th>\" + rooms[key].name + \"</th>\";\n } else {\n talks += \"<th>\" + rooms[key].name + \"</th>\";\n }\n }\n\n $(\"#talks\").find(\"table.day1 > thead\").append(talks);\n $(\"#talks\").find(\"table.day2 > thead\").append(talks);\n $(\"#talks\").find(\"table.day3 > thead\").append(talks);\n\n }", "function createHeaderRow() {\n\n var trEl = document.createElement('tr');\n createElAndAppend('th', 'Products', trEl);\n createElAndAppend('th', 'Total # Clicks', trEl);\n createElAndAppend('th', 'Total # Appearances', trEl);\n createElAndAppend('th', 'Clicked Percentage', trEl);\n\n resultsTable.appendChild(trEl);\n}", "function fillTable(cats, cluesPerCat) {\n console.debug('fillTable ran');\n for (let i = 0; i < cats; i++) {\n $('thead tr').append(`<th>${categories[i].title}</th>`);\n }\n for (let i = 0; i < cluesPerCat; i++) {\n let $newRow = $('<tr></tr>');\n for (let j = 0; j < cats; j++) {\n $newRow.append(`<td class=\"r${i} c${j}\">?</td>`);\n }\n $('#tbody').append($newRow);\n }\n}", "function generateHeaderRow() {\n\tfor (let i = 1; i <= amountOfColumns; i++) {\n\t\tvar col = \"<th class='headerRow'> PC \" + performanceCriteria[i - 1] + \"</th>\";\n\t\t$(\"#header\").append(col);\n\t}\n\t$(\"#header\").append(`<th class='headerRow'>${outcomeName}</th>`);\n}", "function buildTables(categories) {\n\tObject.entries(categories).forEach(([category, count]) => {\n\t\tconst table = document.createElement('table');\n\t\ttable.className = category.toLowerCase();\n\n\t\tconst caption = document.createElement('caption');\n\t\tcaption.textContent = category;\n\n\t\tconst headerRow = document.createElement('tr');\n\n\t\tconst headerInstitution = document.createElement('th');\n\t\theaderInstitution.textContent = 'Institution';\n\n\t\tconst headerAccountType = document.createElement('th');\n\t\theaderAccountType.textContent = 'Account Type';\n\n\t\tconst headerAmount = document.createElement('th');\n\t\theaderAmount.textContent = 'Amount';\n\n\t\theaderRow.appendChild(headerInstitution);\n\t\theaderRow.appendChild(headerAccountType);\n\t\theaderRow.appendChild(headerAmount);\n\t\ttable.appendChild(caption);\n\t\ttable.appendChild(headerRow);\n\n\t\taccountsElement.appendChild(table);\n\t});\n}", "function createBulkImportHeader() {\n var caption = '<span class=\"table-caption\">Bulk&nbsp;Import' +\n '&nbsp;Status</span><br>';\n\n $('<caption/>', {\n html: caption\n }).appendTo('#masterBulkImportStatus');\n\n var items = [];\n\n var columns = ['Directory&nbsp;', 'Age&nbsp;', 'State&nbsp;'];\n\n var titles = ['', descriptions['Import Age'], descriptions['Import State']];\n\n /*\n * Adds the columns, add sortTable function on click,\n * if the column has a description, add title taken from the global.js\n */\n for (i = 0; i < columns.length; i++) {\n var first = i == 0 ? true : false;\n items.push(createHeaderCell(first, 'sortTable(1,' + i + ')',\n titles[i], columns[i]));\n }\n\n $('<tr/>', {\n html: items.join('')\n }).appendTo('#masterBulkImportStatus');\n}", "function createHeader(layout) {\n\n\t\tvar columns = [],\n\t\t\t$thead = $('<thead />');\n\n\t\tlayout.qHyperCube.qDimensionInfo.forEach(function(d) {\n\t\t\tcolumns.push(capitalizeFirstLetter(d.qFallbackTitle));\n\t\t})\n\n\t\tcolumns.push(layout.qHyperCube.qMeasureInfo[0].qFallbackTitle);\n\n\t\tcolumns.forEach(function(d, i) {\n\t\t\tif (i == 1) {\n\t\t\t\t$('<th colspan=\"2\" class=\"col col' + (i + 1) + '\">' + d + '</th>').appendTo($thead);\n\t\t\t} else {\n\t\t\t\t$('<th class=\"col col' + (i + 1) + '\">' + d + '</th>').appendTo($thead);\n\t\t\t}\n\t\t})\n\t\treturn $thead;\n\t}", "function fillTable() {\n $(\"#jeopardy-table thead\").empty();\n let $tr = $(\"<tr>\");\n for(let i = 0; i < NUM_CATEGORIES; i++){\n $tr.append($(\"<th>\").text(categories[i].title));\n }\n $(\"#jeopardy-table thead\").append($tr);\n $(\"#jeopardy-table tbody\").empty();\n for(let j = 0; j < 5; j++){\n let $tr = $(\"<tr>\");\n for (let i = 0; i < NUM_CATEGORIES; i++){\n $tr.append($(\"<td>\").append($(\"<td>\").attr(\"id\", `${i}-${j}`).text(\"?\")));\n }\n $(\"#jeopardy-table tbody\").append($tr);\n }\n}", "function createCourseHeaders() {\n var ranking = $('<td>', {class: \"ranking\", text: \"Ranking\"});\n var experience = $('<td>', {class: \"experience\", text: \"Experience\"});\n var status = $('<td>', {class: \"status\", text: \"Status\"});\n var gName = $('<td>', {class: \"given-name\", text: \"Given Name\"});\n var fName = $('<td>', {class: \"family-name\", text: \"Family Name\"});\n\n return $('<tr>', {class: \"table-headers\"}).append(ranking, [experience, status, gName, fName]);\n}", "function createTableHeader() {\n let tr = document.createElement(\"tr\");\n let header0 = document.createElement(\"th\");\n header0.setAttribute(\"scope\", \"col\");\n header0.innerText = \"#\";\n let header1 = document.createElement(\"th\");\n header1.setAttribute(\"scope\", \"col\");\n header1.innerText = \"Question\";\n let header2 = document.createElement(\"th\");\n header2.setAttribute(\"scope\", \"col\");\n header2.innerText = \"Choices\";\n let header3 = document.createElement(\"th\");\n header3.innerText = \"Edit\";\n header3.setAttribute(\"scope\", \"col\");\n let header4 = document.createElement(\"th\");\n header4.innerText = \"Delete\";\n header4.setAttribute(\"scope\", \"col\");\n tr.appendChild(header0);\n tr.appendChild(header1);\n tr.appendChild(header2);\n tr.appendChild(header3);\n tr.appendChild(header4);\n return tr;\n}", "function displayTableHeader() {\n var rowElement = row(column('Locations','th'));\n //render the hours\n for(var i = 0; i < hours.length; i++){\n rowElement.appendChild(column(hours[i],'th'));\n }\n //render the column daily location total\n rowElement.appendChild(column('Location total','th'));\n selectCookies.appendChild(rowElement);\n}", "function createAllCategoriesTab(spreadsheet, headerFormat) {\r\n // Creating tab\r\n var categoriesSheet = spreadsheet.getSheetByName(\"All Categories\");\r\n if(categoriesSheet == null) {\r\n spreadsheet.insertSheet(\"All Categories\", 0);\r\n categoriesSheet = spreadsheet.getSheetByName(\"All Categories\");\r\n }\r\n \r\n // Formatting header\r\n formatHeader(categoriesSheet, headerFormat);\r\n categoriesSheet.setFrozenRows(headerFormat[\"headerRow\"]);\r\n \r\n // Category aggregation\r\n var categoryFormula = createDataAggregationFormula(spreadsheet, interviewHeaderFormat, interviewHeaderFormat[\"category\"][\"colNum\"]);\r\n var formulaCell = convertColumnToLetter(headerFormat[\"category\"][\"colNum\"])+headerFormat[\"dataStartingRow\"];\r\n categoriesSheet.getRange(formulaCell).setFormula(categoryFormula);\r\n return;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display Google Map on screen with selected hotel Author: ChienTX
function showHotelMap(hotelId){ //check if the map has been loaded //if (map != null){ //return; //} $("#map_canvas").html(""); $("#map_canvas").mask("Loading..."); //send request to get location of current hotel and other places around it $.ajax({ url: hotelServiceUrl, data: {'hotelId' : hotelId}, type: 'GET', dataType: 'JSON', success: function(response){ //process data if(response.data != false){ var hotel = response.data.hotel; var places = response.data.places; //remove the first place because it is the same with hotel places.splice(0, 1); //display the map here var center = new google.maps.LatLng(hotel.Latitude, hotel.Longitude); //initialize map with provided center initializeMap(center); //info var html = "<div>" + hotel.Name + "<br />" + hotel.Address1 + "</div>"; var infoWindow = new google.maps.InfoWindow({ content: html }) //display hotel at the center of the map mainMarker = new google.maps.Marker({ position: center, title: hotel.name, map: map, icon: '/assets/hotel.png' }); google.maps.event.addListener(mainMarker, 'mouseover', function(){ infoWindow.setContent(html); infoWindow.open(map, mainMarker); }) infoWindow.open(map, mainMarker); var subInfoWindow = new google.maps.InfoWindow(); //display other places on the map $.each(places, function(index, place){ var marker = new google.maps.Marker({ position: new google.maps.LatLng(place.latitude, place.longitude), title: place.name, map: map }); otherMarkers.push(marker); google.maps.event.addListener(marker, 'mouseover', function(){ infoWindow.setContent(place.description); infoWindow.open(map, marker); }) }); $("#map_canvas").unmask(); }else{ $("#map_canvas").text("No maps found") $("#map_canvas").unmask(); //alert("No maps found"); } } }) }
[ "function showAllHotelMap(){\n\t\n\tvar array_hotels = [];\n\tvar array_links = {};\n\t$(\"a.map-link\").each(function(i,e){\n array_hotels.push($(e).attr(\"tab\"));\n\t});\n\t$(\"span.bold-blue-text a\").each(function(i,e){\n var href = $(e).attr(\"href\");\n var h_key = href.match(/\\d+\\?/)[0].match(/\\d+/)[0];\n array_links[h_key] = $(e).outer();\n\t});\n\t\n\t$(\"#map_canvas\").html(\"\");\n $(\"#map_canvas\").mask(\"Loading...\");\n\n\t//send request to get location of current hotel and other places around it\n\t$.ajax({\n\t\turl: allHotelServiceUrl,\n\t\tdata: {'hotelIds' : array_hotels},\n\t\ttype: 'GET',\n\t\tdataType: 'JSON',\n\t\tsuccess: function(response){\n\t\t\t//process data\n\t\t\tif(response.data != false){\n\t\t\t\tvar hotel = response.data.hotel;\n\t\t\t\t\n\t\t\t\tvar places = response.data.places;\n\n\n\t\t\t\t//display the map here\n\t\t\t\tvar center = new google.maps.LatLng(places[0][\"Latitude\"], places[0][\"Longitude\"]);\n\n\t\t\t\t//initialize map with provided center\n\t\t\t\tinitializeMap(center);\n\n\t\t\t\t//info\n\t\t\t\t var html = \"<div>\" + array_links[places[0][\"EANHotelID\"].toString()] + \"<br />\" + places[0][\"Address1\"] + \"</div>\";\n\t\t\t\t var infoWindow = new google.maps.InfoWindow({\n\t\t\t\t \tcontent: html\n\t\t\t\t })\n\n\t\t\t\t//display hotel at the center of the map\n\t\t\t\tmainMarker = new google.maps.Marker({\n\t\t\t\t \tposition: center,\n\t\t\t\t \t//title: places[0][\"Name\"] + \"\\n\" + places[0][\"Address1\"] ,\n\t\t\t\t \tmap: map,\n\t\t\t\t \ticon: '/assets/hotel.png'\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\t//infoWindow.open(map, mainMarker);\n\t\t\t\tgoogle.maps.event.addListener(mainMarker, 'mouseover', function(){\n\t\t\t\t\t\tinfoWindow.setContent(html);\n\t\t\t\t\t\tinfoWindow.open(map, mainMarker);\n\t\t\t\t\t})\n\t\t\t\t\n\t\t\t\t//places.splice(0, 1);\n\t\t\t\tvar subInfoWindow = new google.maps.InfoWindow();\n\t\t\t\t//display other places on the map\n\t\t\t\t$.each(places, function(index, place){\n\t\t\t\t\tvar desc = place[\"Name\"] + \"\\n\" + place[\"Address1\"];\n\t\t\t\t\tvar html = \"<div>\" + array_links[place[\"EANHotelID\"].toString()] + \"<br />\" + place[\"Address1\"] + \"</div>\";\n\t\t\t\t\tvar marker = new google.maps.Marker({\n\t\t\t\t\t\tposition: new google.maps.LatLng(place[\"Latitude\"], place[\"Longitude\"]),\n\t\t\t\t\t\t//title: desc,\n\t\t\t\t\t\tmap: map,\n\t\t\t\t \t\ticon: '/assets/hotel.png'\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t \n\t\t\t\t\totherMarkers.push(map,marker);\n\t\t\t\t\t//subInfoWindow.open(map, marker);\n\t\t\t\t\tgoogle.maps.event.addListener(marker, 'mouseover', function(){\n\t\t\t\t\t\tsubInfoWindow.setContent(html);\n\t\t\t\t\t\tsubInfoWindow.open(map, marker);\n\t\t\t\t\t})\n\t\t\t\t});\n\n\t $(\"#map_canvas\").unmask();\n\t }else{\n\t \t$(\"#map_canvas\").text(\"No maps found\")\n\t \t$(\"#map_canvas\").unmask();\n\t \t//alert(\"No maps found\");\n\t \t\n\t \t\n\t }\n\t\t}\n\t})\n}", "function showLocation(e) {\n let ix = findLocation(e.latlng.lat, e.latlng.lng);\n if (ix >= 0) {\n elImage.src = places[ix].gambar;\n elPara.textContent = places[ix].review;\n }\n}", "function displayMap(e) {\n e.preventDefault();\n var ctr = getCenter();\n var z = getZoom();\n googleMap = new google.maps.Map(document.getElementById('mymap'), {\n center: ctr,\n zoom: z\n });\n var marker = new google.maps.Marker( {\n position: ctr\n });\n \n marker.setMap(googleMap);\n\n var infoWindow = new google.maps.InfoWindow( {\n content: selectedName\n });\n\n marker.addListener( 'click', function() {\n infoWindow.open(googleMap, marker)\n });\n}", "function showfood_outletsMarkers() {\n setfood_outletsMap(map);\n}", "function showGoogleMap() {\n\t\tsetGMapAndSearchBoxSize();\n\t\tdocument.getElementById(\"googlemapPortion\").style.visibility = 'visible';\n\t\tdocument.title = \"Vision Web Client\";\n\t}", "function informMapModal() {\n document.getElementById(\"modalHeading\").innerHTML = filteredHotels[0].city;\n document.getElementById(\"iframe\").src = filteredHotels[0].mapurl;\n }", "function DisplayVenueMap() {\n\n\tif ($('#map_venue').length) {\n\t\t// we have a map\n\t\tvar mapHolder = $(\"#map_venue\") ;\n\t\t\n\t\tvar mapZoom = 12 ;\n\t\tvar lat = parseFloat(mapHolder.data(\"map-lat\"));\n\t\tvar lng = parseFloat(mapHolder.data(\"map-lng\"));\n\t\t\n\t\tvar mapPoint = new google.maps.LatLng(lat, lng);\n\t\t\n\t\tvar options = {\n\t\t\tzoom: mapZoom,\n\t\t\tcenter: mapPoint,\n\t\t\tmapTypeId: google.maps.MapTypeId.ROADMAP\n\t\t};\n\t\t\n\t\tvar map = new google.maps.Map(document.getElementById('map_venue'), options);\n\t\t\n\t\t// do we have a point to prove?\n\t\tvar venueName = mapHolder.data(\"name\");\n\t\tif ( venueName.length )\n\t\t{\n\t\t\tvar infoWindowHtml = venueName ;\n\t\t\tvar venueAddress = mapHolder.data(\"address\");\n\t\t\tif ( venueAddress.length ) {\n\t\t\t\tinfoWindowHtml = '<p>' + venueName + '</p>'\n\t\t\t\t\t+ '<a href=\"https://maps.google.com/maps?saddr=&daddr=' + venueAddress + '\">directions</a>';\n\t\t\t}\n\n\t\t\tvar image = '/img/mapicons/venue.png';\n\t\t\t\n\t\t\tvar venueType = mapHolder.data(\"venue-type\");\n\t\t\tif ( venueType.length )\n\t\t\t{\n\t\t\t\timage = '/img/mapicons/venue_' + venueType + '.png' ; \n\t\t\t}\n\t\n\t\t\tvar shadow = '/img/mapicons/shadow.png';\n\t\t\t\n\t\t\tvar marker = new google.maps.Marker({\n\t\t\t\tposition: mapPoint,\n\t\t\t\tmap: map,\n\t\t\t\ticon: image,\n\t\t\t\tshadow: shadow,\n\t\t\t\ttitle: venueName });\n\t\t\t\t\n\t\t\tvar infoWindow = new google.maps.InfoWindow({\n\t\t\t\tcontent: infoWindowHtml \n\t\t\t\t}); \n\t\t\t\t\n\t\t\tgoogle.maps.event.addListener(marker, 'click', function() {\n\t\t\t\tinfoWindow.open(map, marker); \n\t\t\t\t});\n\t\t\t\t\n\t\t}\n\t}\n}", "function displayMap(name, phoneNumber, specialty, description, rating, latitude, longitude, mapId)\n{\n var googleMapsUrl = `https://maps.googleapis.com/maps/api/staticmap?center=${latitude},${longitude}&markers=color:red%7Clabel:${mapId}%7C${latitude},${longitude}&zoom=12&size=400x400&key=${google_maps_api}`;\n var googleMap = $('<span>').html(`<a class=\"doctor-profile\" data-name=\"${name}\" data-specialty=\"${specialty}\" data-description=\"${description}\"><strong>Name: </strong>${name}</a>`);\n googleMap.append($('<img>').attr('src', googleMapsUrl));\n googleMap.append(`<li><a><strong>Specialty: </strong>${specialty}</a></li><li><a><strong>Rating: </strong>${rating} out of 5</a></li><li><a><strong>Phone: </strong>${phoneNumber}</a></li>`)\n $('.map').append(googleMap);\n // var googleMap = $('<div>').addClass('containerFlex results');\n // // var googleMap = $('<span>').html(`<a class=\"doctor-profile\" data-name=\"${name}\" data-specialty=\"${specialty}\" data-description=\"${description}\"><strong>Name: </strong>${name}</a>`)\n // var spanMap = $('<span>').html(`<a class=\"doctor-profile\" data-name=\"${name}\" data-specialty=\"${specialty}\" data-description=\"${description}\"><strong>Name: </strong>${name}</a>`)\n // spanMap.append($('<img>').attr('src', googleMapsUrl));\n // spanMap.append(`<li><a><strong>Specialty: </strong>${specialty}</a></li><li><a><strong>Rating: </strong>${rating} out of 5</a></li><li><a><strong>Phone: </strong>${phoneNumber}</a></li>`)\n // googleMap.append(spanMap);\n // $('.map').append(googleMap);\n\n}", "function showMapTitleAndBlurb(mapInfo){\n document.title = mapInfo.title;\n document.getElementById('map-title').innerHTML = mapInfo.title;\n document.getElementById('map-blurb').innerHTML = mapInfo.blurb;\n \n}", "function renderMap()\n {\n me = new google.maps.LatLng(myLat, myLng);\n \n // Update map and go there...\n map.panTo(me);\n\n marker = new google.maps.Marker({\n position: me,\n title: \"ErinHolleman\"\n });\n marker.setMap(map);\n\n var infowindow = new google.maps.InfoWindow({\n content: marker.title + \"<p><img\" + ' SRC=\"Nightcrawler.jpg\">' + \"</p>\"\n });\n \n // Open info window on click of marker\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.open(map, marker);\n });\n \n \n }", "function showLibraryInfo(){\n\tinfowindow.setContent(this.title);\n\tinfowindow.open(this.map, this);\n}", "function initMapSelection() {\n lat = hikingProjectAPIDataObject.trails[99].latitude\n lng = hikingProjectAPIDataObject.trails[99].longitude\n var loc = hikingProjectAPIDataObject.trails[99].location\n // var sum = hikingProjectAPIDataObject.trails[99].summary\n // var con = hikingProjectAPIDataObject.trails[99].conditionDetails\n // var img = hikingProjectAPIDataObject.trails[99].imgSqSmall\n var myLatLng = { lat, lng };\n\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: lat, lng: lng },\n zoom: 12\n });\n var contentString = '<div id=\"content\">' +\n '<div id=\"siteNotice\">' +\n '</div>' +\n '<h1 id=\"firstHeading\" class=\"firstHeading\">Enjoy your Hike.</h1>' +\n '<div id=\"bodyContent\">' +\n '<h1>' + loc + '</h1>' +\n // '<h2>' + sum + '</h2>' +\n // '<h3>' + con + '</h3>' +\n '</div>' +\n '</div>';\n var infowindow = new google.maps.InfoWindow({\n content: contentString\n })\n var marker = new google.maps.Marker({\n position: myLatLng,\n map: map,\n });\n marker.addListener('click', function () {\n infowindow.open(map, marker);\n });\n}", "function showonmap(courseId, courseName, lat, lon, city, state) {\n\tif (map == null) {\n\t\tmap = new GMap2(document.getElementById(\"map\"));\n\t}\n\t\n\t// display the course on the map, geocode if needed\n\tif (lat == 0.0 && lon == 0.0) {\n\t\tgeocoder.getLatLng(city + \", \" + state,\n\t\t\t\t\t\t function(point) {_createMarkerAtPoint(point, courseName);});\n\t} else {\n\t\t_createMarkerAtPoint(new GLatLng(lat, lon), courseName);\n\t}\n\t\n\t// set the caption\n $('#mapcaption').html(\"<strong>Course: </strong>\" \n \t\t+ \"<a href='../coursepage/?id=\" + courseId + \"'>\" + courseName + \"</a>\"\n \t\t+ \"<br />\" + city + \", \" + state);\n if (lat == 0.0 && lon == 0.0) {\n \t$('#mapcaption').html($('#mapcaption').html() + \"<br /><em>Note: No GPS data available, showing city</em>\");\n }\n}", "function vossenGoogleMaps(){function g(b,e){var f=new google.maps.LatLng(b,e),g={zoom:d,center:f,mapTypeId:google.maps.MapTypeId.ROADMAP,scrollwheel:!1,mapTypeControl:!1},h=new google.maps.Map(document.getElementById(\"vossen-map\"),g),i='<div class=\"vossen-map-info\">'+c+\"</div>\",j=new google.maps.InfoWindow({content:i}),k=new google.maps.Marker({position:f,map:h,icon:\"img/assets/marker.png\",title:\"location : Dublin\"});k.addListener(\"click\",function(){j.open(h,k)});var l=[{featureType:\"administrative\",elementType:\"labels.text.fill\",stylers:[{color:\"#0c0b0b\"}]},{featureType:\"landscape\",elementType:\"all\",stylers:[{color:\"#f2f2f2\"}]},{featureType:\"poi\",elementType:\"all\",stylers:[{visibility:\"off\"}]},{featureType:\"road\",elementType:\"all\",stylers:[{saturation:-100},{lightness:45}]},{featureType:\"road\",elementType:\"labels.text.fill\",stylers:[{color:\"#090909\"}]},{featureType:\"road.highway\",elementType:\"all\",stylers:[{visibility:\"simplified\"}]},{featureType:\"road.arterial\",elementType:\"labels.icon\",stylers:[{visibility:\"off\"}]},{featureType:\"transit\",elementType:\"all\",stylers:[{visibility:\"off\"}]},{featureType:\"water\",elementType:\"all\",stylers:[{color:\"#d4e4eb\"},{visibility:\"on\"}]},{featureType:\"water\",elementType:\"geometry.fill\",stylers:[{visibility:\"on\"},{color:\"#c7d1d5\"}]},{featureType:\"water\",elementType:\"labels.text.fill\",stylers:[{color:\"#9b7f7f\"}]},{featureType:\"water\",elementType:\"labels.text.stroke\",stylers:[{color:\"#fef7f7\"}]}],m=[{featureType:\"all\",elementType:\"labels.text.fill\",stylers:[{saturation:36},{color:\"#000000\"},{lightness:40}]},{featureType:\"all\",elementType:\"labels.text.stroke\",stylers:[{visibility:\"on\"},{color:\"#000000\"},{lightness:16}]},{featureType:\"all\",elementType:\"labels.icon\",stylers:[{visibility:\"off\"}]},{featureType:\"administrative\",elementType:\"geometry.fill\",stylers:[{color:\"#000000\"},{lightness:20}]},{featureType:\"administrative\",elementType:\"geometry.stroke\",stylers:[{color:\"#000000\"},{lightness:17},{weight:1.2}]},{featureType:\"landscape\",elementType:\"geometry\",stylers:[{color:\"#000000\"},{lightness:20}]},{featureType:\"poi\",elementType:\"geometry\",stylers:[{color:\"#000000\"},{lightness:21}]},{featureType:\"road.highway\",elementType:\"geometry.fill\",stylers:[{color:\"#000000\"},{lightness:17}]},{featureType:\"road.highway\",elementType:\"geometry.stroke\",stylers:[{color:\"#000000\"},{lightness:29},{weight:.2}]},{featureType:\"road.arterial\",elementType:\"geometry\",stylers:[{color:\"#000000\"},{lightness:18}]},{featureType:\"road.local\",elementType:\"geometry\",stylers:[{color:\"#000000\"},{lightness:16}]},{featureType:\"transit\",elementType:\"geometry\",stylers:[{color:\"#000000\"},{lightness:19}]},{featureType:\"water\",elementType:\"geometry\",stylers:[{color:\"#000000\"},{lightness:17}]}];if(\"light\"===a.data(\"map-style\"))var n=new google.maps.StyledMapType(l);else if(\"dark\"===a.data(\"map-style\"))var n=new google.maps.StyledMapType(m);else var n=new google.maps.StyledMapType;h.mapTypes.set(\"map_style\",n),h.setMapTypeId(\"map_style\")}var a=$(\"#vossen-map\"),b=a.data(\"map-address\"),c=a.data(\"marker-info\"),d=a.data(\"map-zoom\"),e=a.data(\"map-height\");a.css(\"height\",e);(new google.maps.Geocoder).geocode({address:b},function(a,b){if(b==google.maps.GeocoderStatus.OK){var c=a[0].geometry.location.lat(),d=a[0].geometry.location.lng();g(c,d)}})}", "function mGItemAddPage_show(){\r\n //show google map\r\n showGoogleMap();\r\n}", "function displayMap(res){\n mymap.setView([res.location.lat, res.location.lng], 13);\n marker.setLatLng([res.location.lat, res.location.lng]); \n }", "function showPopup1(e) {\n // Show the popup at the coordinates with some data\n popup\n .setLngLat(e.lngLat)\n .setHTML(\n e.features[0].properties.name + \n \"<br><a href='https://waba.org/20x20map/' target='blank'><button class=blue-button2>Take Action</button></a>\"\n )\n .addTo(map);\n }", "function showHotelListings() {\n let bounds = new google.maps.LatLngBounds();\n // Extend the boundaries of the map for each marker and display the marker\n for (let i = 0; i < markersHotel.length; i++) {\n markersHotel[i].setMap(map);\n bounds.extend(markersHotel[i].position);\n }\n map.fitBounds(bounds);\n}", "function showInfoWindow(selected_city, marker)\n{\n // Maybe write a server function that\n // retrieves and returns some data from Wikipedia.\n var div = \"<div id='info'>\";\n div += selected_city.place_name + \", \" + selected_city.admin_code1;\n div += \"</div>\";\n\n info.setContent(div);\n info.open(map, marker);\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate the data block only consisting of id & CreatedAt for rendering as options in Select box
function generateSelectListData(spatialSpanActivities){ var listData = []; spatialSpanActivities.forEach(function(instance){ listData.push({id: instance.id, CreatedAt: instance.CreatedAt}); }); return listData; }
[ "function renderCreatorList(data) {\n if(!data.length) {\n window.location.href = \"/users\";\n }\n $(\".hidden\").removeClass(\"hidden\");\n var rowsToAdd = [];\n for(var i = 0; i < data.length; i++) {\n rowsToAdd.push(createMemerRow(data[i]));\n }\n creatorSelect.empty();\n console.log(rowsToAdd);\n console.log(creatorSelect);\n creatorSelect.append(rowsToAdd);\n creatorSelect.val(creatorId);\n }", "makeSelect(data){\n\t\tvar select = document.getElementsByName(\"selectblog\")[0];\n\t\tvar html;\n\t\tfor(var i in data){\n\t\t\tvar option = document.createElement(\"option\"); \n\t\t\toption.setAttribute(\"value\", data[i].ID);\n\t\t\toption.text = data[i].name_blog;\n\t\t\tselect.add(option);\n\t\t}\n\t}", "function createDropDownListDate(obj){\n var strDate=\"<option value=\"+'\"'+\"default\"+'\"'+\">\"+\"Select Date\"+\"</option>\";\n var strTime=\"<option value=\"+'\"'+\"default\"+'\"'+\">\"+\"Select Time\"+\"</option>\";\n //console.log(obj);\n for(var i=0; i<obj.length; i++){\n //console.log(obj[i]);\n strDate+=\"<option value=\"+'\"'+obj[i].Room_ID+'\"'+\">\"+obj[i].RunDate+\"</option>\";\n }\n //console.log(str);\n $(\"#Date\").html(strDate);\n $(\"#showTime\").html(strTime);\n\n}", "function generateNewData() {\n console.group(\"New render\");\n const newData = [];\n\n for(let i = 0; i < 20; i++) {\n newData.push({\n text: `Option ${i}`,\n value: i\n });\n }\n\n newData[getRandomSelectionIndex()].selected = true;\n console.info(\"New data for MDBSelect\", newData);\n\n setData(newData);\n }", "caricaSelect() {\n return html `\n <select class=\"custom-select custom-select-lg mb-3\" id=\"selDoc\">\n <option value=0 selected>Choose...</option>\n ${this.docUt.map(doc => this.createRow(doc))}\n </select>`\n }", "static cargarSelect (data){\n let select = document.getElementById(\"form-select\");\n let miInner =\"\";\n data.forEach(element => {\n miInner += `<option value=\"${element.id}\">${element.name}</option>`\n });\n select.innerHTML = miInner\n }", "async function _buildShowingsSelectorDropdown() {\n let selectionList = '';\n //We get all upcoming showings of the selected movie\n selectionList = await dbController.getShowings10('filmID', $(\"#select-movie\").val()).then((showings) => {\n\n for (let showing of showings) {\n selectionList += `<option value=\"${showing.id}\"> \n ${Showing.getPresentableTime(showing.time)} - ${showing.auditorium.name}</option>`;\n }\n return selectionList;\n });\n if (!$('.showings-selector-dropdown').length) {\n $(\".booking-row1-col1\").append(` \n <div class=\"showings-selector-dropdown\">\n </div>`);\n }\n $('.showings-selector-dropdown').html(` \n <select id=\"date-and-time\">\n <option value=\"0\">Välj Datum och Tid:</option>\n </select>`);\n\n\n $('#date-and-time').append(selectionList);\n}", "function createSelect(id, label, options) {\n let start = `\n <div class=\"form-group col-md-3\">\n <label for=\"${id}\">${label}</label>\n <select class=\"form-control\" id=\"${id}\">`;\n let data = ``;\n for (let i = 0; i < options.length; ++i) {\n let option = options[i];\n data += `<option value=\"${option.value}\" ${i === 0 ? `selected` : \"\"}>${option.text}</option>`;\n }\n let end = `\n </select>\n </div>`;\n\n return start + data + end;\n}", "static updatePedidoSelector(data) {\n let select = document.getElementById(\"editPedidoSelect\");\n select.innerHTML = \"\";\n\n for (let i=0; i<data.length; i++) {\n var option = document.createElement(\"option\");\n option.text = data[i].id;\n option.setAttribute(\"pedId\",data[i].id)\n select.add(option);\n }\n }", "updateStartDateList() {\n const select = this.modal.getBody().find(SELECTORS.FIELD_STARTDATE);\n\n for (let i in this.start_dates) {\n $(select).append('<option value=\"' + i + '\">' + this.start_dates[i] + '</option>');\n }\n }", "function buildSelectOptions(data) {\n var options = data.data,\n output = [];\n var optionCopy = options.slice(0);\n // Alpha sort\n sortOn(optionCopy, \"authorised_value\");\n // Build html select options\n optionCopy.forEach(function(option) {\n output.push('<option value=\"' + option.lib +\n '\" data-cs-desc=\"' + option.authorised_value +\n '\">' + option.authorised_value + '</option>');\n });\n // HTML output\n return output.join(\"\\n\");\n }", "createListClientStatus() {\n\n var objSelect = document.getElementById(this.id);\n let objOption = ' <option disabled selected value> -- Seleccione una opción -- </option> ';\n \n \n for (let i = 0; i < this.jSon.length; i++) {\n \n objOption += '<option value=' + this.jSon[i].Stat_id + '>' + this.jSon[i].Stat_name + '</option>';\n }\n \n objSelect.innerHTML = objOption;\n }", "function generateOptions(data){\n const options = data.map(item =>\n `<option value='${item}'>${item}</option>`) \n .join('');\n select.innerHTML = options;\n}", "function createOwnerRow(owner) {\n var listOption = $(\"<option>\");\n listOption.attr(\"value\", owner.id);\n listOption.text(owner.name);\n console.log(owner.id);\n\n return listOption;\n }", "function handleRenderOptions() {\n let url = 'https://api.napster.com/v2.2/genres?apikey=OTI0NjE5NWEtNWVjOC00ZTJjLTliMDgtOTdkMTg5NjEwYmU0';\n\n fetch(url)\n .then(function (response) {\n return response.json();\n })\n .then(function (data) {\n //console.log(data.genres);\n for (var i = 0; i < data.genres.length; i++) {\n let options = data.genres[i].name;\n let genreId = data.genres[i].id;\n genreArray = data.genres\n //console.log(options, genreId);\n let userOptions = document.createElement('option');\n userOptions.innerHTML = options;\n userOptions.value = genreId;\n select$.append(userOptions);\n select$.formSelect();\n }\n })\n }", "createSelectItemsPolls() {\n let items = [];\n this.state.poll_list.forEach((T) => {\n items.push(<option key={T.poll_id} value={T.poll_id}>{T.title}</option>);\n })\n return items;\n }", "function partDropDown(data) {\r\n\tvar html = '<option value=\"\">Choose a Part #...</option>';\r\n\tfor (var i = 0; i < data.length; i++) {\r\n\t\tvar row = data[i];\r\n\t\thtml += '<option value=\"';\r\n\t\thtml += row['id'];\r\n\t\thtml += '\">';\r\n\t\thtml += row['description'];\r\n\t\thtml += '</option>';\r\n\t}\r\n\treturn html;\r\n}", "function populateDataSelect () {\n const options = dataVariables\n\n for (let i = 0; i < options.length; i++) {\n let opt = options[i].table + '/' + options[i].column\n let el = document.createElement('option')\n el.textContent = opt\n el.value = opt\n dataSelect.appendChild(el)\n }\n}", "async getOptions() {\n const data = await (\n await axios.get(\n \"http://localhost:9090/CovidTracker.com/patients/allpatients\"\n )\n ).data;\n this.setState({ ...this.state, patients: data });\n const options = data.map((d, index) => ({\n value: d.patientId,\n label: d.patientId + \":\" + d.patientFirstName + \" \" + d.patientLastName,\n id: index,\n }));\n\n this.setState({ selectOptions: options });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if the triple "subject predicate object" is already in the editor, remove it otherwise, add it
function swapTriple(subject, predicate, obj) { if (subject != '' && predicate != '' && obj != '') { var content = hxleditor.getValue(); var triple = getTriple(subject, predicate, obj); //check if triple is already there: if (content.indexOf(triple) == -1) { // not there, so add it hxleditor.setValue(content + triple); } else { //already there, remove it: hxleditor.setValue(content.split(triple).join('')); } // refresh the sparql update script after every change: $("#update").val('CREATE GRAPH <' + containerURI + '> INSERT DATA INTO <' + containerURI + '> {' + hxleditor.getValue() + '}'); } }
[ "function revertDeletion(subject) {\n let index = removedSubjects.findIndex((obj) => obj.name === subject.name);\n if (index >= 0) {\n removedSubjects.splice(index,1);\n selected_subjects.push(subject);\n updateViz();\n }\n}", "function MSTUDSUBJ_AddRemoveSubject(mode) {\n console.log(\"===== MSTUDSUBJ_AddRemoveSubject =====\");\n console.log(\" mode\", mode);\n\n const may_edit = (permit_dict.permit_crud && permit_dict.requsr_same_school);\n if(may_edit){\n\n let must_validate_subjects = false;\n\n // for highlighting row in other table after addd/remove\n mod_MSTUDSUBJ_dict.sel_studsubj_list = [];\n mod_MSTUDSUBJ_dict.sel_schemeitem_list = [];\n\n const tblBody = (mode === \"add\") ? el_tblBody_schemeitems : el_tblBody_studsubjects;\n\n// +++++ loop through selected schemeitem_pk's of tblBody +++++\n for (let i = 0, tblRow; tblRow = tblBody.rows[i]; i++) {\n if (get_attr_from_el_int(tblRow, \"data-selected\")) {\n\n // - get selected schemeitem_dict with schemeitem_pk from tblRow\n const sel_si_pk = get_attr_from_el_int(tblRow, \"data-schemeitem_pk\");\n const sel_si_dict = (mod_MSTUDSUBJ_dict.schemeitem_dict[sel_si_pk]) ? mod_MSTUDSUBJ_dict.schemeitem_dict[sel_si_pk] : {};\n\n // - get sel_schemeitem_pk from sel_si_dict, so it will be null when there is no sel_si_dict\n const sel_schemeitem_pk = (sel_si_dict.schemeitem_id) ? sel_si_dict.schemeitem_id : null;\n const sel_subject_pk = (sel_si_dict.subj_id) ? sel_si_dict.subj_id : null;\n\n // - get sel_subject_pk from sel_si_dict\n const studsubj_dict = mod_MSTUDSUBJ_dict.studsubj_dict[sel_subject_pk];\n\n const subj_exists_in_ss = (!isEmpty(studsubj_dict));\n const ss_dict_has_same_si = (subj_exists_in_ss && studsubj_dict.schemeitem_id === sel_schemeitem_pk);\n const ss_dict_is_tobedeleted = (subj_exists_in_ss && (studsubj_dict.is_deleted || studsubj_dict.is_tobedeleted || studsubj_dict.tobedeleted));\n\n// +++++++ add subject +++++++\n if(mode === \"add\"){\n console.log(\"............... add subject\");\n\n // --- restore deleted row if it exists in mod_MSTUDSUBJ_dict\n if (subj_exists_in_ss){\n console.log(\" ... restore deleted row\");\n console.log(\" ss_dict_is_tobedeleted\", ss_dict_is_tobedeleted);\n\n if (ss_dict_is_tobedeleted ){\n studsubj_dict.tobecreated = true;\n studsubj_dict.tobedeleted = false;\n\n // change schemitem_pk if necessary\n if (!ss_dict_has_same_si ) {\n studsubj_dict.schemeitem_id = sel_schemeitem_pk;\n };\n\n console.log(\" studsubj_dict\", studsubj_dict);\n must_validate_subjects = true;\n\n // add sel_schemeitem_pk to sel_studsubj_list, to highlight subject after adding\n mod_MSTUDSUBJ_dict.sel_studsubj_list.push(sel_schemeitem_pk);\n };\n\n } else {\n\n // --- add row to studsubj_dict if it does not yet exist\n\n console.log(\"add row to studsubj_dict if it does not yet exist\", sel_si_dict.subj_id);\n mod_MSTUDSUBJ_dict.studsubj_dict[sel_si_dict.subj_id] = {\n stud_id: mod_MSTUDSUBJ_dict.stud_id,\n scheme_id: sel_si_dict.scheme_id,\n studsubj_id: null,\n schemeitem_id: sel_si_dict.schemeitem_id,\n\n subj_id: sel_si_dict.subj_id,\n subj_code: sel_si_dict.subj_code,\n subj_name_nl: sel_si_dict.subj_name_nl,\n subj_published_id: null,\n\n is_extra_counts: false,\n is_extra_nocount: false,\n pws_subjects: null,\n pws_title: null,\n\n is_deleted: false,\n is_tobedeleted: false,\n\n tobecreated: true,\n tobedeleted: false,\n tobechanged: false\n\n // PR2021-09-28 debug: don't put schemeitem info here, it changes when schemeitem_id changes\n };\n\n must_validate_subjects = true;\n\n // - add sel_schemeitem_pk to sel_studsubj_list, to highlight subject after adding\n mod_MSTUDSUBJ_dict.sel_studsubj_list.push(sel_schemeitem_pk)\n };\n } else {\n\n// +++++++ remove subject +++++++\n // --- set 'tobedeleted' = true if schemeitem_pk already exists in studsubj_dict\n // PR2023-02-22 when not publihed yet: set 'deleted' instead of 'tobedeleted'\n console.log(\"............... remove subject\");\n\n\n console.log(\" studsubj_dict\", studsubj_dict);\n console.log(\" sel_schemeitem_pk\", sel_schemeitem_pk);\n console.log(\" sel_subject_pk\", sel_subject_pk);\n console.log(\" subj_exists_in_ss \", subj_exists_in_ss);\n console.log(\" ss_dict_has_same_si \", ss_dict_has_same_si);\n console.log(\" ss_dict_is_tobedeleted \", ss_dict_is_tobedeleted);\n console.log(\" studsubj_dict.tobecreated\", studsubj_dict.tobecreated);\n console.log(\" ss_dict_is_tobedeleted\", ss_dict_is_tobedeleted);\n console.log(\" studsubj_dict.subj_published_id\", studsubj_dict.subj_published_id);\n\n if (subj_exists_in_ss) {\n if (studsubj_dict.tobecreated){\n if (!ss_dict_is_tobedeleted){\n\n console.log(\" subject is new, delete it. sel_subject_pk: \", sel_subject_pk);\n\n // - when it is a created, not saved, subject: just remove subject from studsubj_dict\n delete mod_MSTUDSUBJ_dict.studsubj_dict[sel_subject_pk];\n must_validate_subjects = true;\n\n } else {\n console.log(\" subject is is_tobedeleted or is_deleted, remove 'created'\");\n studsubj_dict.tobecreated = false;\n studsubj_dict.show_in_tblBody_schemeitems = true;\n must_validate_subjects = true;\n };\n\n } else {\n\n console.log(\" subject was not 'tobecreated'\", studsubj_dict.tobecreated);\n console.log(\" subject is set 'tobedeleted'\", studsubj_dict.tobedeleted);\n // - when it is an existing subject: set tobedeleted = true (\n\n // when tobechanged = true:\n // - changes have been made, either schemeitem or pws title etc\n // - when removing this subject: set tobechanged = false, tobedeleted = true\n // - note: the new information of schemeitem or pws title etc stays in studsubj_dict\n\n studsubj_dict.tobedeleted = true;\n studsubj_dict.tobechanged = false;\n };\n\n must_validate_subjects = true;\n // to highlight subject after removing\n mod_MSTUDSUBJ_dict.sel_schemeitem_list.push(sel_schemeitem_pk)\n\n };\n }; // if(mode === \"add\"){\n\n MSTUDSUBJ_SetInputFields()\n } // if (is_selected)\n };\n// --- end of loop through selected schemeitem_pk's of tblBody\n\n console.log(\"...............\");\n console.log(\"mod_MSTUDSUBJ_dict.studsubj_dict\", mod_MSTUDSUBJ_dict.studsubj_dict);\n console.log(\"mod_MSTUDSUBJ_dict.schemeitem_dict\", mod_MSTUDSUBJ_dict.schemeitem_dict);\n console.log(\"...............\");\n\n // --- enable btn submit\n el_MSTUDSUBJ_btn_save.disabled = false;\n\n // create uploaddict to validate subjects PR2021-08-17\n if (must_validate_subjects){\n MSTUDSUBJ_ValidateSubjects()\n };\n\n MSTUDSUBJ_FillTbls();\n }; // if(may_edit){\n } // MSTUDSUBJ_AddRemoveSubject", "function removeSubjectWidget(elem) {\n $(elem).find('.vocab_list').remove();\n var tipapi =\n $(elem).find('.subject-label').qtip('api')\n if ((tipapi !== undefined) && (tipapi !== null)) {\n var tip = $(tipapi.elements.tooltip);\n tip.find('.vocab_tree').remove();\n tipapi.destroy(true);\n }\n }", "function removeSubjectToTeacher(subject){\n\t\tvar deferred = $q.defer();\n\t\tvar data = subject;\n\t\tif(data!=null){\n\t\t\t$http.post(\"./subject/remove\",JSON.stringify(data))\n\t\t\t.then(function complete(response){\n\t\t\t\tif(response.data.type==\"OK\"){\n\t\t\t\t\t$scope.teacherS.subjects.splice($scope.teacherS.subjects.indexOf(subject),1);\n\t\t\t\t\tdeferred.resolve(response.data);\n\t\t\t\t}else{\n\t\t\t\t\tdeferred.resolve(response.data);\n\t\t\t\t}\n\t\t\t},\n\t\t\tfunction error(response){\n\t\t\t\tdeferred.resolve({type:\"error\"});\n\t\t\t});\n\t\t}else{\n\t\t\tdeferred.resolve({type:\"error\"});\n\t\t}\n\t\treturn deferred.promise;\n\t}", "removeMatches(subject, predicate, object, graph) {\n const stream = new browser.Readable({ objectMode: true });\n\n stream._read = () => {\n for (const quad of this.readQuads(subject, predicate, object, graph))\n stream.push(quad);\n stream.push(null);\n };\n\n return this.remove(stream);\n }", "function removeSubject(index) {\n let removed = selected_subjects.splice(index,1);\n removedSubjects.push(...removed);\n\n updateViz();\n}", "removeMatches(subject, predicate, object, graph) {\n const stream = new _readableStream.Readable({\n objectMode: true\n });\n\n stream._read = () => {\n for (const quad of this.getQuads(subject, predicate, object, graph)) stream.push(quad);\n\n stream.push(null);\n };\n\n return this.remove(stream);\n }", "function removeTerm(obj_cross) {\n\tvar term_to_remove = obj_cross.parentNode;\n\tvar tr = document.createElement(\"tr\");\n\ttr.className = \"term_row_saved\";\n\ttr.id = term_to_remove.id;\n\tvar td = document.createElement(\"td\");\n\ttd.className = \"term_cell_saved\";\n\t// td.innerHTML = \"<img class='dragAfterSave' src='images/drag.jpg'\n\t// width='10px;'></img> \";\n\n\t// mark reviewed\n\tmarkTermReviewed(term_to_remove.id);\n\n\t// append term and view sign\n\tvar objs_a = term_to_remove.getElementsByTagName(\"a\");\n\tvar term = objs_a[0].cloneNode(true);// term name\n\tterm.style[\"color\"] = \"red\";\n\ttd.appendChild(term);\n\ttd.innerHTML += \" \";\n\ttd.appendChild(objs_a[1].cloneNode(true));// view report sign\n\ttr.appendChild(td);\n\tvar mainTerm = term_to_remove.parentNode.parentNode;\n\tvar changedDecision = mainTerm.parentNode.parentNode.parentNode\n\t\t\t.getElementsByClassName(\"changedDecision\")[0];\n\t// remove term\n\tterm_to_remove.parentNode.removeChild(term_to_remove);\n\tvar obj_as = mainTerm.getElementsByTagName(\"a\");\n\tfor (j = 0; j < obj_as.length; j++) {\n\t\tobj_as[j].style[\"color\"] = \"red\";\n\t}\n\t// move both the main term and removed synonym to the changed decision part\n\tchangedDecision.appendChild(mainTerm);\n\tchangedDecision.appendChild(tr);\n}", "removeQuad(subject, predicate, object, graph) {\n // Shift arguments if a quad object is given instead of components\n if (!predicate) graph = subject.graph, object = subject.object, predicate = subject.predicate, subject = subject.subject;\n\n // Convert terms to internal string representation\n subject = (0, _N3DataFactory.termToId)(subject);\n predicate = (0, _N3DataFactory.termToId)(predicate);\n object = (0, _N3DataFactory.termToId)(object);\n graph = (0, _N3DataFactory.termToId)(graph);\n\n // Find internal identifiers for all components\n // and verify the quad exists.\n const ids = this._ids,\n graphs = this._graphs;\n let graphItem, subjects, predicates;\n if (!(subject = ids[subject]) || !(predicate = ids[predicate]) || !(object = ids[object]) || !(graphItem = graphs[graph]) || !(subjects = graphItem.subjects[subject]) || !(predicates = subjects[predicate]) || !(object in predicates)) return false;\n\n // Remove it from all indexes\n this._removeFromIndex(graphItem.subjects, subject, predicate, object);\n this._removeFromIndex(graphItem.predicates, predicate, object, subject);\n this._removeFromIndex(graphItem.objects, object, subject, predicate);\n if (this._size !== null) this._size--;\n\n // Remove the graph if it is empty\n for (subject in graphItem.subjects) return true;\n delete graphs[graph];\n return true;\n }", "removeQuad(subject, predicate, object, graph) {\n // Shift arguments if a quad object is given instead of components\n if (!predicate)\n graph = subject.graph, object = subject.object,\n predicate = subject.predicate, subject = subject.subject;\n\n // Convert terms to internal string representation\n subject = termToId(subject);\n predicate = termToId(predicate);\n object = termToId(object);\n graph = termToId(graph);\n\n // Find internal identifiers for all components\n // and verify the quad exists.\n const ids = this._ids, graphs = this._graphs;\n let graphItem, subjects, predicates;\n if (!(subject = ids[subject]) || !(predicate = ids[predicate]) ||\n !(object = ids[object]) || !(graphItem = graphs[graph]) ||\n !(subjects = graphItem.subjects[subject]) ||\n !(predicates = subjects[predicate]) ||\n !(object in predicates))\n return false;\n\n // Remove it from all indexes\n this._removeFromIndex(graphItem.subjects, subject, predicate, object);\n this._removeFromIndex(graphItem.predicates, predicate, object, subject);\n this._removeFromIndex(graphItem.objects, object, subject, predicate);\n if (this._size !== null) this._size--;\n\n // Remove the graph if it is empty\n for (subject in graphItem.subjects) return true;\n delete graphs[graph];\n return true;\n }", "removeQuad(subject, predicate, object, graph) {\n // Shift arguments if a quad object is given instead of components\n if (!predicate)\n graph = subject.graph, object = subject.object,\n predicate = subject.predicate, subject = subject.subject;\n\n // Convert terms to internal string representation\n subject = N3Store_toId(subject);\n predicate = N3Store_toId(predicate);\n object = N3Store_toId(object);\n graph = N3Store_toId(graph);\n\n // Find internal identifiers for all components\n // and verify the quad exists.\n var graphItem, ids = this._ids, graphs = this._graphs, subjects, predicates;\n if (!(subject = ids[subject]) || !(predicate = ids[predicate]) ||\n !(object = ids[object]) || !(graphItem = graphs[graph]) ||\n !(subjects = graphItem.subjects[subject]) ||\n !(predicates = subjects[predicate]) ||\n !(object in predicates))\n return false;\n\n // Remove it from all indexes\n this._removeFromIndex(graphItem.subjects, subject, predicate, object);\n this._removeFromIndex(graphItem.predicates, predicate, object, subject);\n this._removeFromIndex(graphItem.objects, object, subject, predicate);\n if (this._size !== null) this._size--;\n\n // Remove the graph if it is empty\n for (subject in graphItem.subjects) return true;\n delete graphs[graph];\n return true;\n }", "removeQuad(subject, predicate, object, graph) {\n // Shift arguments if a quad object is given instead of components\n if (!predicate)\n graph = subject.graph, object = subject.object,\n predicate = subject.predicate, subject = subject.subject;\n\n // Convert terms to internal string representation\n subject = toId(subject);\n predicate = toId(predicate);\n object = toId(object);\n graph = toId(graph);\n\n // Find internal identifiers for all components\n // and verify the quad exists.\n var graphItem, ids = this._ids, graphs = this._graphs, subjects, predicates;\n if (!(subject = ids[subject]) || !(predicate = ids[predicate]) ||\n !(object = ids[object]) || !(graphItem = graphs[graph]) ||\n !(subjects = graphItem.subjects[subject]) ||\n !(predicates = subjects[predicate]) ||\n !(object in predicates))\n return false;\n\n // Remove it from all indexes\n this._removeFromIndex(graphItem.subjects, subject, predicate, object);\n this._removeFromIndex(graphItem.predicates, predicate, object, subject);\n this._removeFromIndex(graphItem.objects, object, subject, predicate);\n if (this._size !== null) this._size--;\n\n // Remove the graph if it is empty\n for (subject in graphItem.subjects) return true;\n delete graphs[graph];\n return true;\n }", "function EBX_PredicateEditor() {\n}", "_removeAssertion(assertion) {\n var predicate = assertion.getPredicate();\n if (predicate in this._assertions) {\n var pos = this._assertions[predicate].indexOf(assertion);\n if (pos >= 0)\n this._assertions[predicate].splice(pos, 1);\n if (this._assertions[predicate].length == 0)\n delete this._assertions[predicate];\n }\n\n var object = assertion.getObject();\n if (object instanceof RDFSubject) {\n // Delete reverse assertion\n if (predicate in object._backwards) {\n pos = object._backwards[predicate].indexOf(assertion);\n if (pos >= 0)\n object._backwards[predicate].splice(pos, 1);\n if (object._backwards[predicate].length == 0)\n delete object._backwards[predicate];\n }\n }\n }", "function RemoveTopic()\r\n{\r\n AddTopic(\"\");\r\n}", "function removeUnusedCreatedVocabulary(dataset, type, expectedSubject, expectedPredicate, expectedObject) {\n let r = dataset.matchAndBind([$quad(variable(\"voc\"), rdf.type, type)]);\n\n for (let bind1 of r) {\n let asSubject = dataset.getQuads(bind1.voc, null, null).length;\n let asPredicate = dataset.getQuads(null, bind1.voc, null).length;\n let asObject = dataset.getQuads(null, null, bind1.voc).length;\n\n if (asSubject == expectedSubject\n && asPredicate == expectedPredicate\n && asObject == expectedObject) {\n dataset.deleteMatches(bind1.voc, null, null);\n dataset.deleteMatches(null, bind1.voc, null);\n dataset.deleteMatches(null, null, bind1.voc);\n }\n }\n\n if (dataset.getQuads(null, rdf.type, type).length == 0) {\n dataset.deleteMatches(type, null, null);\n dataset.deleteMatches(null, type, null);\n dataset.deleteMatches(null, null, type);\n }\n}", "function removeTerm( id )\n{\n\tid.target.parentNode.parentNode.removeChild( id.target.parentNode );\n}", "removeSubject() {\n \n if(!this.state.subjectSelected){\n return alert('please select a subject');\n }\n \n let subjects = this.state.subjects;\n let selectedSubject = this.state.subjectSelected;\n\n var new_sbjects = subjects.filter(e => {\n return e.id != selectedSubject\n });\n\n // remove object\n \n this.setState({\n subjects: new_sbjects\n });\n }", "function removeNote(){}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
executes multiple requests to each of the internship links
async function dataRetriever() { var $ = await rp(options); var count = 0; $('.individual_internship').each(async function () { var link = $(this).children('.button_container').children('a').attr('href'); links.push(link) //making array of all the internship links on the page count++; } ) //sending requests on all the links for (i = 0; i < count; i++) { console.log(`https://internshala.com${links[i]}`) await sleep(100) //delay of 0.1sec with each request //request execution var options1 = { uri: `https://internshala.com${links[i]}`, transform: function (body) { return cheerio.load(body); }, } await rp(options1).then(async ($) => { var res = $('#skillsContainer').text() var res1 = $('.stipend_container_table_cell').text() console.log(res) console.log("Stipend : " + res1) }).catch((err) => { console.log(err); }); } console.log(count); }
[ "function executeURLS() {\n\n for(var i = 0, len = documentsURL.length; i < len; i++) {\n (function () {\n var aux = i, endChecker = false;\n\n request(documentsURL[i], function (error, response, body) {\n if (!error) {\n if(aux === len - 1) {\n endChecker = true;\n }\n parseDocument(body, documentsURL[aux], endChecker);\n } else {\n console.log(error);\n }\n });\n })();\n }\n }", "async function main(url){\n axios.get(url)\n .then(response => {\n const $ = cheerio.load(response.data)\n\n for( i=1; i<=10; i++){\n var s = 'https://www.loopnet.com/for-sale/los-angeles-ca/'+i+'/'\n console.log(s);\n\n getDataFromPinProfile(s);\n }\n // $('ol li').each(function () {\n // const href = $(this).children().attr('href');\n // //console.log($(this).children().attr('href'));\n // if (href !== undefined){\n // //getDataFromPinProfile(href);\n // console.log('link: ',href);\n // }\n // })\n //console.log(listing_ids);\n })\n .catch(console.error);\n}", "main()\n {\n this.getInnerLinks(this.url).then((result) => {\n \n const loop = async value => {\n let i = 0;\n let minValue = Math.min(this.limitCrawling,this.internalUrl.length);\n\n while (i < minValue) \n {\n let url = this.getNextVisitingLink();\n let result = await this.getInnerLinks(url);\n console.log('visiting internal url:'+url);\n this.setVisitedIncrement();\n i++;\n }\n }\n\n // display what was discovered in the console after the loop finishes\n loop(0).then(() => this.getData());\n });\n }", "function createURLs() {\n for (let i = 0; i < 44; i++) {\n let currentPageURL = `https://www.anapioficeandfire.com/api/characters?page=${i}&pageSize=50`\n \n fetchRequest(currentPageURL);\n }\n}", "function ex3_2a() {\r\n // find the current file relative path --- the ex3_ajax_utils.js need to be in the same directory as this file\r\n var dir_path=require('path').dirname(require.main.filename);\r\n ajaxUtils = require(dir_path+'/ex3_ajax_utils.js'); \r\n\r\n var index = [\"https://lemida.biu.ac.il/\",\r\n \"https://ims.gov.il/\",\r\n \"https://www.mizrahi-tefahot.co.il/\",\r\n \"https://www.maariv.co.il/\",\r\n \"https://www.wikipedia.org/\"];\r\n (function loop(i) {\r\n if (i>= index.length) {\r\n return;\r\n }\r\n var url = index[i];\r\n ajaxUtils.sendGetRequest(url, function (request) {\r\n var data = request.responseText;\r\n console.log('-->' + i + ' id: ' + data.substring(1,2000));\r\n console.log(\"---------------------------\\n\")\r\n loop(i + 1);\r\n });\r\n })(0);\r\n }", "function ex3_2b() {\r\n var index = [\"https://lemida.biu.ac.il/\",\r\n \"https://ims.gov.il/\",\r\n \"https://www.mizrahi-tefahot.co.il/\",\r\n \"https://www.maariv.co.il/\",\r\n \"https://www.wikipedia.org/\"]; \r\n // Set up a namespace for our XMLHttpRequest\r\n var XMLHttpRequest = require(\"xmlhttprequest\").XMLHttpRequest;\r\n (function loop(i) {\r\n if (i>= index.length) {\r\n return;\r\n }\r\n var url = index[i];\r\n // By moving the creation of the request variable into the loop function, we can make sure that the asynchronous aspect\r\n // will work properly and we won`t have a situation where one url request will run over the data of another request,\r\n // leading to undesired and wrong results. \r\n var request = new XMLHttpRequest();\r\n request.open(\"GET\", url, true);\r\n request.onreadystatechange = function() {\r\n if(request.readyState === 4 && request.status === 200) {\r\n var data = request.responseText;\r\n console.log('-->' + i + ' id: ' + data.substring(1,1500));\r\n console.log(\"---------------------------\\n\")\r\n // By calling the loop from within onreadystatechange we make sure the requests are sent in syncronized order.\r\n // Only after we send the request and the url request response is done is the onreadystatechange function preformed.\r\n // In turn we call the loop for the next url in order.\r\n loop(i + 1); \r\n }\r\n }\r\n request.send(); \r\n })(0);\r\n }", "function reqLink(linkName, i){\n $.ajax({\n url: 'https://api.codetabs.com/v1/proxy?quest=' + linkName,\n method: 'GET',\n }).done(function(res){\n // Store and render data\n //rawList = res.match(/[^\\r\\n]+/g);\n //showGallery(rawList);\n }).fail(function(res){\n // Handle failure to load resource\n if ((i+1) > MAX_RETRY){\n // Error\n console.error(\"Resource unavailable.\");\n }\n else {\n // Retry\n setTimeout(function(){\n reqLink(linkName, i+1);\n }, RETRY_DELAY);\n }\n });\n}", "function doFetch() {\n /* URLs for data */\n let neocpurl = \"https://minorplanetcenter.net/iau/NEO/neocp.txt\";\n let unusualurl =\"https://minorplanetcenter.net/iau/lists/LastUnusual.html\";\n let priorityurl = \"https://api.codetabs.com/v1/proxy?quest=https://neo.ssa.esa.int/PSDB-portlet/download?file=esa_priority_neo_list\";\n let pccpurl = \"https://minorplanetcenter.net/iau/NEO/pccp.txt\";\n /*the priority list must be obtained via a CORS Proxy*/\n \n /* Local copies of data for use during testing */\n //var neocpurl = \"neocp.txt\"; \n //var unusualurl = \"unusuals.txt\";\n //var priorityurl = \"priority.txt\";\n \n /* load the files and call appropriate processors.*/\n comments.value += \"Fetching data.\\n\";\n $.get(neocpurl,function(data){doNeocp(data);});\n $.get(unusualurl,function(data){doUnusuals(data);});\n $.get(priorityurl,function(data){doPriority(data);});\n $.get(pccpurl,function(data){doPccp(data);});\n // The processing functions are automatically called once the \n // Fetches have obtained the data. \n}", "function indexUrl(mainUrl, client)\n{\n linksToIndex = getAllLinksToIndex(mainUrl)\n \n XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest\n for(i=0; i<linksToIndex.length; i++) {\n xmlHttp = new XMLHttpRequest()\n xmlHttp.open(\"GET\", linksToIndex[i], false); // false for synchronous request\n xmlHttp.send()\n str = xmlHttp.responseText\n str = removeUnneededTags(str)\n pageParts = str.split(/<.*?>\\s*/).filter(function (el) { return el.length > 0 })\n \n pageSentences = extractSentences(pageParts)\n \n console.log(linksToIndex[i] + ' ' + i)\n \n pageSentences.forEach(function(sentence){indexSentence(client, linksToIndex[i], sentence)})\n }\n\n console.log('indexed done')\n}", "function PopulateCardURLs() {\n\n for (var i = 0; i < cardList.length; i++) {\n var cardPath = mainPath + cardList[i].childNodes[0].getAttribute('href');\n var cardPlusProxyPath = proxyurl + cardPath;\n cardURLS[i] = cardPlusProxyPath;\n }\n\n GetCardHTMLS();\n}", "static runAll() {\n\t MainUtil.findAllRooms().forEach(room => new LinkManager(room).runLinks());\n\t}", "function shipUrlList(req, res) {\n\n}", "orgRepoRequests(orgs, token) {\n console.log('8 TOKEN: ', token)\n let allOrgRepoRequests = _.chain(orgs)\n .map((org) => {\n var uri = `${org.repos_url}?${internals.authRequest(token)}`;\n // Can get 100 repos at a time?\n let pageCount = 5;\n let orgRepoRequests = [];\n\n for (var i = 1; i < pageCount+1; i++) {\n let paginatedURI = internals.paginatedURI(uri, i);\n let repoRequest = internals.getRequestWithUri(paginatedURI);\n\n orgRepoRequests.push(repoRequest);\n }\n\n return orgRepoRequests;\n })\n .flatten()\n .value();\n\n return allOrgRepoRequests;\n }", "async function traverseSitemap() {\n const sitemap = await sitemapFetch();\n const browser = await puppeteer.launch({ headless: true });\n const page = await browser.newPage();\n for (const link of sitemap) {\n console.log(link);\n // visit the page\n await page.goto(`${link}`, { waitUntil: \"networkidle2\" });\n await grabAllLink(page, link);\n }\n}", "function loopThroughLinks() {\n if (i < links.length) {\n this.echo('link #' + i + ': ' + links[i]);\n getLinkData.call(this, links[i]);\n i++;\n this.then(loopThroughLinks);\n }\n else {\n this.echo('done looping');\n }\n}", "async function myAsyn (urlArray) {\n for (const url of urlArray) {\n const character = await subRequest(url);\n console.log(character);\n }\n}", "function ex3_3a() {\r\n // find the current file relative path --- the ex3_ajax_utils.js need to be in the same directory as this file\r\n var dir_path=require('path').dirname(require.main.filename);\r\n ajaxUtils = require(dir_path+'/ex3_ajax_utils.js'); \r\n var index = [\"https://lemida.biu.ac.il/\",\r\n \"https://ims.gov.il/\",\r\n \"https://www.mizrahi-tefahot.co.il/\",\r\n \"https://www.maariv.co.il/\",\r\n \"https://www.wikipedia.org/\"];\r\n (function loop(i) {\r\n if (i>= index.length) {\r\n return;\r\n }\r\n var url = index[i];\r\n ajaxUtils.sendGetRequest(url, function (request) {\r\n var data = request.responseText;\r\n console.log('-->' + i + ' id: ' + data.substring(1,2000));\r\n console.log(\"---------------------------\\n\")\r\n });\r\n // By taking the loop call outside of the sendGetRequest function and putting it after sending the request, \r\n // we can make the request asynchronous - meaning we build the url requests in order and send them in order but\r\n // receive the request responses in an asynchronous manner. The request's call back function will be called\r\n // based on the response arrival order, regardless of the order the requests were sent in. \r\n loop(i + 1);\r\n })(0);\r\n}", "divideAndCrawl() {\n const chunks = _array.chunk(this.hyperlinks, this.maxRequests);\n if (this.refIndexChunk >= chunks.length) return Promise.resolve();\n return Promise.map(chunks[this.refIndexChunk++], item => this.crawlEach(item.link))\n .then(() => this.divideAndCrawl());\n }", "function fetchRemoteLists(){\n var i, url;\n var opts = _options;\n\n for(i=0;i<opts.blockLists.length;i++){\n url = opts.blockLists[i];\n loadExecuteUrl(url);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DISCRETE HORIZONTAL SLIDER EXTENDS HORIZONTAL SLIDER
function DiscreteHorizSlider (params) { if (!params.numBins) { throw 'discrete horizontal slider needs an integer number of bins'; } this.numBins = params.numBins this.binSize = Math.floor(params.width / this.numBins); this.lineWidth = 4; this.renderWidth = this.binSize - this.lineWidth; this.currentBin = 0; this.lastBin = -99; this.binBorderColor = params.binBorderColor; Slider.call(this, params); var oldStyle = this.g2d.fillStyle; this.g2d.fillStyle = this.binBorderColor; for (var i = 0; i <= this.numBins; i++) { this.g2d.fillRect( Math.floor(i * this.binSize), 0, this.lineWidth, this.height ); } this.g2d.fillStyle = oldStyle; }
[ "function ControlSlider(name, group, weight, locked, flipped, topLevel, theme){\r\n if (group === undefined){\r\n group = false;\r\n };\r\n if (weight === undefined){\r\n weight = 0;\r\n };\r\n if (locked === undefined){\r\n locked = false;\r\n };\r\n if (flipped === undefined){\r\n flipped = false;\r\n };\r\n if (topLevel === undefined){\r\n topLevel = false;\r\n };\r\n\r\n slider = document.createElement(\"div\");\r\n slider.setAttribute(\"id\", name);\r\n slider.className = 'panel-item ' + theme;\r\n slider.className += group ? ' panel-group' : '';\r\n slider.className += topLevel ? ' panel-top' : '';\r\n\r\n destroy_button: {\r\n div = document.createElement(\"div\");\r\n div.setAttribute(\"id\", name+\"-destroy\");\r\n div.setAttribute(\"alt\", \"Delete\");\r\n div.setAttribute(\"title\", \"Delete\");\r\n div.setAttribute('aria-hidden', \"true\");\r\n div.className = 'panel-destroy panel-button-x far fa-times fa-fw';\r\n //div.appendChild(document.createTextNode(\"\\u2716\"));\r\n }\r\n\r\n slider.appendChild(div);\r\n\r\n flip_button: {\r\n div = document.createElement(\"div\");\r\n div.setAttribute(\"id\", name+\"-flip\");\r\n div.setAttribute('aria-hidden', \"true\");\r\n div.className = 'panel-flip panel-button'\r\n if (!flipped){\r\n div.className += ' far fa-plus fa-fw';\r\n div.setAttribute(\"alt\", \"Invert\");\r\n div.setAttribute(\"title\", \"Invert\");\r\n } else {\r\n div.className += ' far fa-minus fa-fw';\r\n div.setAttribute(\"alt\", \"Normal\");\r\n div.setAttribute(\"title\", \"Normal\");\r\n }\r\n }\r\n\r\n slider.appendChild(div);\r\n\r\n\r\n lock_button: {\r\n div = document.createElement(\"div\");\r\n div.setAttribute(\"id\", name+\"-lock\");\r\n div.setAttribute('aria-hidden', \"true\");\r\n div.className = 'panel-lock panel-button';\r\n if (locked){\r\n div.className += ' locked far fa-lock fa-fw'\r\n div.setAttribute(\"alt\", \"Unlock\");\r\n div.setAttribute(\"title\", \"Unlock\");\r\n } else {\r\n div.className += ' far fa-unlock fa-fw'\r\n div.setAttribute(\"alt\", \"Lock\");\r\n div.setAttribute(\"title\", \"Lock\");\r\n }\r\n }\r\n\r\n slider.appendChild(div);\r\n\r\n select_button: {\r\n div = document.createElement(\"div\");\r\n div.setAttribute(\"id\", name+\"-select\");\r\n div.setAttribute(\"alt\", \"Select\");\r\n div.setAttribute(\"title\", \"Select\");\r\n div.setAttribute('aria-hidden', \"true\");\r\n div.className = 'panel-select panel-button far fa-circle fa-fw';\r\n }\r\n\r\n slider.appendChild(div);\r\n\r\n label: {\r\n div = document.createElement(\"label\");\r\n div.className = 'scroll-label';\r\n div.setAttribute(\"id\", name+\"-slider-label\");\r\n div.setAttribute(\"alt\", name);\r\n div.setAttribute(\"title\", name);\r\n if (group){\r\n icon = document.createElement(\"i\");\r\n icon.className = 'fas panel-button fa-plus-circle';\r\n icon.setAttribute('aria-hidden', 'true');\r\n div.appendChild(icon);\r\n }\r\n let text = document.createElement(\"span\");\r\n text.appendChild(\r\n document.createTextNode(name)\r\n );\r\n div.appendChild(text);\r\n }\r\n\r\n slider.appendChild(div);\r\n\r\n /*power: {\r\n div = document.createElement(\"span\");\r\n div.setAttribute(\"id\", name+\"-power\");\r\n div.setAttribute(\"alt\", \"Turn Off\");\r\n div.setAttribute(\"title\", \"Turn Off\");\r\n div.setAttribute('aria-hidden', \"true\");\r\n div.className = 'panel-power fa fa-power-off';\r\n }\r\n\r\n slider.appendChild(div);*/\r\n\r\n slider: {\r\n div = document.createElement(\"input\");\r\n div.setAttribute(\"id\", name+\"-slider\");\r\n div.setAttribute(\"type\", \"range\");\r\n div.setAttribute(\"max\", \"100\");\r\n div.setAttribute(\"min\", \"0\");\r\n div.setAttribute(\"value\", weight*100);\r\n div.setAttribute(\"name\", name+\"-slider\");\r\n if (locked){\r\n div.disabled = true;\r\n }\r\n div.className = 'panel-slider';\r\n }\r\n\r\n slider.appendChild(div);\r\n\r\n number_input: {\r\n div = document.createElement(\"input\");\r\n div.setAttribute(\"id\", name+\"-slider-num\");\r\n div.setAttribute(\"type\", \"text\");\r\n div.setAttribute(\"value\", weight*100);\r\n if (locked){\r\n div.disabled = true;\r\n }\r\n div.className = 'slider-num';\r\n }\r\n\r\n slider.appendChild(div);\r\n inputTypeNumberPolyfill.polyfillElement(div);\r\n\r\n return(slider);\r\n}", "function Slider() {\n this.head = null;\n this.tail = null;\n this.current = null;\n this.length = 0;\n this.isCircular = false;\n }", "function drawSliders() {\n\n noUiSlider.create(nodeSlider, {\n start: [ 8 ],\n connect: 'lower',\n tooltips: [ true ],\n range: {\n 'min': [ 0 ],\n 'max': [ 16 ]\n }\n });\n\n noUiSlider.create(edgeSlider, {\n start: [ 1 ],\n connect: 'lower',\n tooltips: [ true ],\n range: {\n 'min': [ 0 ],\n 'max': [ 4 ]\n }\n });\n\n noUiSlider.create(tensionSlider, {\n start: [ 0.7 ],\n connect: 'lower',\n tooltips: [ true ],\n range: {\n 'min': [ 0 ],\n 'max': [ 1 ]\n }\n });\n\n noUiSlider.create(weightSlider, { \n start: [ 0, MAXWEIGHT ],\n connect: true,\n tooltips: [ true, true ],\n range: {\n 'min': [ 0 ],\n '20%': [ MAXWEIGHT*0.0016 ],\n '40%': [ MAXWEIGHT*0.008 ],\n '60%': [ MAXWEIGHT*0.04 ],\n '80%': [ MAXWEIGHT*0.2 ],\n 'max': [ MAXWEIGHT ]\n }\n });\n\n noUiSlider.create(inSlider, {\n start: [ MAXIN ],\n connect: 'lower',\n tooltips: [ toInt ],\n step: 1,\n range: {\n 'min': [ 0 ],\n '20%': [ MAXIN*0.0016 ],\n '40%': [ MAXIN*0.008 ],\n '60%': [ MAXIN*0.04 ],\n '80%': [ MAXIN*0.2 ],\n 'max': [ MAXIN ]\n }\n });\n\n noUiSlider.create(outSlider, {\n start: [ MAXOUT ],\n connect: 'lower',\n tooltips: [ toInt ],\n step: 1,\n range: {\n 'min': [ 0 ],\n '20%': [ MAXOUT*0.0016 ],\n '40%': [ MAXOUT*0.008 ],\n '60%': [ MAXOUT*0.04 ],\n '80%': [ MAXOUT*0.2 ],\n 'max': [ MAXOUT ]\n }\n });\n\n isDrawn = true;\n updateSliders();\n}", "function createSlider() {\n noUiSlider.create(bgColourSlider[0], {\n start: sliderStartPos,\n step: 1,\n connect: \"lower\",\n orientation: \"horizontal\",\n range: {\n 'min': SLIDER_MIN,\n 'max': SLIDER_MAX\n },\n format: wNumb({\n decimals: 0\n })\n });\n}", "function Slider(parent, name, vertical, x, y, w, h, t, min, max, hide)\n{\n\t/* --------------------------------------------------------------------------------------\n create ui objects that will be components of slider\n -------------------------------------------------------------------------------------- */\n\tvar body = new Frame(parent, name + \"_body\", x, y, w, h, false, false, hide);\n\tvar thumb = new Frame(body, name + \"_thumb\", 0, 0, vertical? w:t, vertical? t:h, false, false, hide); \n\n\t/* --------------------------------------------------------------------------------------\n\tinternal function that updates the thumb position based on current value\n\t-------------------------------------------------------------------------------------- */\n\tvar updateThumbPos = function()\n\t{\n if (vertical)\n {\n\t\t\tthumb.x = 0;\n\n\t\t\t// we add these 2 lines to make sure we don't set thumb.y to invalid value. we don't stop user \n\t\t\t// to set max <= min nor h <= t but we want to make sure it does not break the application. \n\t\t\t// in this case, we set thumb pos = 0 to make it look like it is set to min\n\t\t\tif (max - min <= 0){ thumb.y = 0; return; }\n\t\t\tif (h - t <= 0){ thumb.y = 0; return; }\n\n thumb.y = (current - min) / (max - min) * (h - t);\n }\n else \n {\n thumb.y = 0;\n\n\t\t\t// we add these 2 lines to make sure we don't set thumb.y to invalid value. we don't stop user \n\t\t\t// to set max <= min nor h <= t but we want to make sure it does not break the application. \n\t\t\t// in this case, we set thumb pos = 0 to make it look like it is set to min\n\t\t\tif (max - min <= 0){ thumb.x = 0; return; }\n\t\t\tif (w - t <= 0){ thumb.x = 0; return; }\n\n thumb.x = (current - min) / (max - min) * (w - t);\n }\n\t}\n\t\n\t/*--------------------------------------------------------------------------------------\n handle draw event for slider's ui object components \n --------------------------------------------------------------------------------------*/\n \n // add event handler for drawing the body frame. the slider ui has drawEvents array that will contain list of draw event handlers that will draw the slider's body\n // when slider's body frame is to be drawn, it will execute this\n\tbody.addEventListener(\"draw\", function(e)\n\t{\n\t\tfor (var i = 0; i < drawEvents.length; i++) drawEvents[i]({elem: this, name: name, v: vertical, x: e.x, y: e.y, w: e.w, h: e.h, value: current, min: min, max: max});\n\t}.bind(this));\n\n // add event handler for drawing the thumb frame. the slider ui has drawThumbEvents array that will contain list of draw event handlers that will draw the slider's \n // thumb when slider's body frame is to be drawn, it will execute this\n\tthumb.addEventListener(\"draw\", function(e)\n\t{\n\t\tfor (var i = 0; i < drawThumbEvents.length; i++) drawThumbEvents[i]({elem: this, name: name, x: e.x, v: vertical, y: e.y, w: e.w, h: e.h, value: current, min: min, max: max});\n\t}.bind(this));\n \n\t/*--------------------------------------------------------------------------------------\n\tassign event handlers\n\t--------------------------------------------------------------------------------------*/\n\tvar drawEvents = [];\n\tvar drawThumbEvents = [];\n\tvar changeEvents = [];\n\tvar minEvents = [];\n\tvar maxEvents = [];\n\tvar resizeEvents = [];\n\tvar stateEvents = [];\n\tthis.addEventListener = function(e, f)\n\t{\n\t\tif (e === \"change\"){ changeEvents.push(f); }\t\t\n\t\tif (e === \"min\"){ minEvents.push(f); }\t\t\n\t\tif (e === \"max\"){ maxEvents.push(f); }\t\t\n\t\tif (e === \"draw\"){ drawEvents.push(f); }\n\t\tif (e === \"drawthumb\"){ drawThumbEvents.push(f); }\n\t\tif (e === \"resize\"){ resizeEvents.push(f); }\t\t\n\t\tif (e === \"mouseup\"){ body.addEventListener(e, f); thumb.addEventListener(e, f); }\t\t\n\t\tif (e === \"mousedown\"){ body.addEventListener(e, f); thumb.addEventListener(e, f); }\t\t\n\t\tif (e === \"mouseenter\"){ body.addEventListener(e, f); thumb.addEventListener(e, f); }\t\t\n\t\tif (e === \"mouseleave\"){ body.addEventListener(e, f); thumb.addEventListener(e, f); }\t\t\n\t\tif (e === \"mousemove\"){ body.addEventListener(e, f); thumb.addEventListener(e, f); }\t\t\n\t\tif (e === \"mousedrag\"){ body.addEventListener(e, f); thumb.addEventListener(e, f); }\t\t\n\t\tif (e === \"state\"){ stateEvents.push(f); }\t\t\n\t}\n\t\n\tthis.removeEventListener = function(e, f)\n\t{\n\t\tif (e === \"change\"){ for (var i = 0; i < changeEvents.length; i++){ if (changeEvents[i] == f){ changeEvents.splice(i,1); return; }}}\t\t\t\n\t\tif (e === \"min\"){ for (var i = 0; i < minEvents.length; i++){ if (minEvents[i] == f){ minEvents.splice(i,1); return; }}}\t\t\t\n\t\tif (e === \"max\"){ for (var i = 0; i < maxEvents.length; i++){ if (maxEvents[i] == f){ maxEvents.splice(i,1); return; }}}\t\t\t\n\t\tif (e === \"draw\"){ for (var i = 0; i < drawEvents.length; i++){ if (drawEvents[i] == f){ drawEvents.splice(i,1); return; }}}\t\t\t\n\t\tif (e === \"drawthumb\"){ for (var i = 0; i < drawThumbEvents.length; i++){ if (drawThumbEvents[i] == f){ drawThumbEvents.splice(i,1); return; }}}\t\t\t\n\t\tif (e === \"resize\"){ for (var i = 0; i < resizeEvents.length; i++){ if (resizeEvents[i] == f){ resizeEvents.splice(i,1); return; }} }\t\t\n\t\tif (e === \"state\"){ for (var i = 0; i < stateEvents.length; i++){ if (stateEvents[i] == f){ stateEvents.splice(i,1); return; }} }\t\t\n\t\tif (e === \"mouseup\"){ body.removeEventListener(e, f); thumb.removeEventListener(e, f); }\t\t\n\t\tif (e === \"mousedown\"){ body.removeEventListener(e, f); thumb.removeEventListener(e, f); }\t\t\n\t\tif (e === \"mouseenter\"){ body.removeEventListener(e, f); thumb.removeEventListener(e, f); }\t\t\n\t\tif (e === \"mouseleave\"){ body.removeEventListener(e, f); thumb.removeEventListener(e, f); }\t\t\n\t\tif (e === \"mousemove\"){ body.removeEventListener(e, f); thumb.removeEventListener(e, f); }\t\t\n\t\tif (e === \"mousedrag\"){ body.removeEventListener(e, f); thumb.removeEventListener(e, f); }\t\t\n }\t\t\n \n\t/* --------------------------------------------------------------------------------------\n\tset/get visibility state \n\t-------------------------------------------------------------------------------------- */\n Object.defineProperty(this, \"hide\", \n { \n get: function(){ return hide; }, \n set: function(e)\n { \t\t\t\n\t\t\t//var t = ((hide != e)? true : false);\n hide = e; \n thumb.hide = e; \n\t\t\tbody.hide = e; \n\n\t\t\t// execute event handler ONLY if state changes\n\t\t\t//if (t)\n\t\t\t{ for (var i = 0; i < stateEvents.length; i++){ stateEvents[i]({elem: this, show: !hide}); }}\n }\n }); \n\n\t/* --------------------------------------------------------------------------------------\n\tset/get thumb size \n thumb size is stored in thumb height or width depending on slider orientation\n\t-------------------------------------------------------------------------------------- */\n Object.defineProperty(this, \"thumbsize\", \n {\n get: function(){ return vertical? thumb.height : thumb.width; }, \n set: function(e)\n { \n if (vertical)\n {\n // if slider's orientation is vertical, thumb width fills slider's body width\n thumb.width = body.width;\n\n // make sure thumb size <= body.size\n thumb.height = e;\n if (thumb.height > body.height) thumb.height = body.height;\n\n // once we have valid thumb size, we store it in t as t is used by functions\n // in calculating thumb positions, movement, etc...\n t = thumb.height;\n \n // finally, update thumb position based on new size\n updateThumbPos();\t\t\n }\n else\n {\n // if slider's orientation is horizontal, thumb height fills slider's body height\n thumb.height = body.height;\n\n // make sure thumb size <= body.size\n thumb.width = e;\n if (thumb.width > body.width) thumb.width = body.width;\n\n // once we have valid thumb size, we store it in t as t is used by functions\n // in calculating thumb positions, movement, etc...\n t = thumb.width;\n\n // finally, update thumb position based on new size\n updateThumbPos();\t\t\n }\n }\n });\n\n\t/* --------------------------------------------------------------------------------------\n\tacquire or manually set the current index value of the slider\n\t-------------------------------------------------------------------------------------- */\n\tObject.defineProperty(this, \"value\", \n\t{ \n\t\tget: function(){ return current; },\n\t\tset: function(e)\n\t\t{ \n current = e;\n\n // clip within range\n\t\t\tif (current > max) current = max;\n\t\t\tif (current < min) current = min;\n\t\t\t\n\t\t\t// update thumb position based on current value\n\t\t\tupdateThumbPos();\t\t\n\t\t\t\n\t\t\tfor (var i = 0; i < changeEvents.length; i++){ changeEvents[i]({elem: this, value: current, min: min, max: max}); }\t\n\t\t}\n\t});\n\n\t/* --------------------------------------------------------------------------------------\n\tacquire or manually set the min value of the slider\n\t-------------------------------------------------------------------------------------- */\n\tObject.defineProperty(this, \"min\", \n\t{ \n\t\tget: function(){ return min; },\n\t\tset: function(e)\n\t\t{ \n min = e;\n\n // ensure current value is still within range\n\t\t\tif (current > max) current = max;\n\t\t\tif (current < min) current = min;\n\t\t\t\n\t\t\t// update thumb position based on current value\n\t\t\tupdateThumbPos();\t\t\n\t\t\t\n\t\t\tfor (var i = 0; i < minEvents.length; i++){ minEvents[i]({elem: this, value: current, min: min, max: max}); }\t\n\t\t}\n });\n \n\t/* --------------------------------------------------------------------------------------\n\tacquire or manually set the max value of the slider\n\t-------------------------------------------------------------------------------------- */\n\tObject.defineProperty(this, \"max\", \n\t{ \n\t\tget: function(){ return max; },\n\t\tset: function(e)\n\t\t{ \n max = e;\n\n // ensure current value is still within range\n\t\t\tif (current > max) current = max;\n\t\t\tif (current < min) current = min;\n\t\t\t\n\t\t\t// update thumb position based on current value\n\t\t\tupdateThumbPos();\t\t\n\t\t\tfor (var i = 0; i < maxEvents.length; i++){ maxEvents[i]({elem: this, value: current, min: min, max: max}); }\t\n\t\t}\n\t});\n\n\t/* --------------------------------------------------------------------------------------\n\tsnapshot current value and mouse cursor on mousedown to be used as reference for \n\tmouse drag\n\t-------------------------------------------------------------------------------------- */\n\tvar M; // store mouse cursor position on mouse down in this object\n\tthumb.addEventListener(\"mousedown\", function(e){ M = { x: e.x, y: e.y, current: current }; });\t\t\t\n \n\t/* --------------------------------------------------------------------------------------\n thumb is not draggable so we can manage its mouse drag movement here. its movement shift \n snaps to slider's shift index\n\t-------------------------------------------------------------------------------------- */\n\tthumb.addEventListener(\"mousedrag\",function(e)\n\t{\n\t\t// if min >= max, we'll end up with invalid shift value. let's prevent it and don't\n\t\t// bother with updating current value\n\t\tif (max - min <= 0) return;\n\n\t\t// calculate relative position of mouse cursor with thumb\n\t\te.x -= M.x;\n\t\te.y -= M.y;\n\t\t\n\t\t// calculate actual size of 1 shift \n\t\tvar shift = ((vertical?h:w) - t) / (max - min);\t\t\t\n\t\t\n\t\t// calculate which value is closest to the point, set current, and set new position of thumb\n\t\tthis.value = M.current + Math.round( (vertical?e.y:e.x) / shift);\t\t\t\n\t\t\n\t}.bind(this));\t\n\t\n\t/* --------------------------------------------------------------------------------------\n\twhen user click (mousedown) on the slider's body where thumb does not occupy, slider \n\tforces the thumb to be repositioned where it's center sits on the mouse pointer if\n\tpossible. the center position is with respect to its orientation - meaning, the slider's\n\tlength 't' is centered. it's thickness is ignored.\t\n\t-------------------------------------------------------------------------------------- */\n\tbody.addEventListener(\"mousedown\", function(e)\n\t{\n\t\t// if min >= max, we'll end up with invalid shift value. let's prevent it and don't\n\t\t// bother with updating current value\n\t\tif (max - min <= 0) return;\n\n\t\t// calculate relative position of mouse cursor with body + thumb's center position\n\t\t// note that we ignore slider's orientation and just blindly calculate with thumb'same\n\t\t// length on both x and y. this is because only one of them will be used to calculate\n\t\t// position and the choice will depend on the slider's orientation\n\t\tvar P = body.getAbsPos();\n\t\te.x -= (P.x + t/2);\n\t\te.y -= (P.y + t/2);\n\n\t\t// calculate actual size of 1 shift \n\t\tvar shift = ( ( vertical?h:w) - t) / (max - min);\t\t\t\n\t\t\n\t\t// calculate which value is closest to the point, set current, and set new position of thumb\n\t\tthis.value = Math.round( (vertical?e.y:e.x) / shift) + min;\t\t\t\n\t\t\n\t}.bind(this));\t\n\t\n\t/* --------------------------------------------------------------------------------------\n\twhen mouse cursor is dragged into slider's body, reposition the thumb so that its center\n\tsits at\tthe mouse pointer whenever possible. the center position is with respect to its\n\torientation - meaning, the slider's\tlength 't' is centered. it's thickness is ignored.\t\n\t-------------------------------------------------------------------------------------- */\n\tbody.addEventListener(\"mousedrag\", function(e)\n\t{\t\t\n\t\t// if min >= max, we'll end up with invalid shift value. let's prevent it and don't\n\t\t// bother with updating current value\n\t\tif (max - min <= 0) return;\n\n\t\t// calculate relative position of mouse cursor with body + thumb's center position\n\t\t// note that we ignore slider's orientation and just blindly calculate with thumb'same\n\t\t// length on both x and y. this is because only one of them will be used to calculate\n\t\t// position and the choice will depend on the slider's orientation\n\t\tvar P = body.getAbsPos();\n\t\te.x -= (P.x + t/2);\n\t\te.y -= (P.y + t/2);\n\n\t\t// calculate actual size of 1 shift \n\t\tvar shift = ( ( vertical?h:w) - t) / (max - min);\t\t\t\n\t\t\n\t\t// calculate which value is closest to the point, set current, and set new position of thumb\n\t\tthis.value = Math.round( (vertical?e.y:e.x) / shift) + min;\t\t\t\n\t\t\n }.bind(this));\t\n\n\t/* --------------------------------------------------------------------------------------\n setter/getter for orientation\n -------------------------------------------------------------------------------------- */\n Object.defineProperty(this, \"vertical\", \n {\n get: function(){ return vertical; }, \n set: function(e)\n {\n // don't bother if our orientation is already correct\n if (e == vertical) return;\n else vertical = e;\n\n // set thumb size to ensure thumb <= body.size\n this.thumbsize = t;\n\n // update thumb position based on body's size and possibly thumbs as well\n updateThumbPos();\t\t\n }\n });\n \n\t/* --------------------------------------------------------------------------------------\n setter/getters for properties\n -------------------------------------------------------------------------------------- */\n\n // setter/getter for width. updates thumb position after resizing\n Object.defineProperty(this, \"width\", \n { \n get: function(){ return w; }, \n set: function(e)\n { \n w = e;\n body.width = w;\n\n // set thumb size to ensure thumb <= body.size\n this.thumbsize = t;\n\n // update thumb position based on body's size and possibly thumbs as well\n\t\t\tupdateThumbPos();\t\t\n\t\t\t\n\t\t\t// fire up resize event handler for this ui\n for (var i = 0; i < resizeEvents.length; i++){ resizeEvents[i]({elem: this, name: name, w: w, h: h}); }\t\n } \n });\n\n // setter/getter for height. updates thumb position after resizing\n Object.defineProperty(this, \"height\", \n { \n get: function(){ return h; },\n set: function(e)\n { \n h = e;\n body.height = h;\n\n // set thumb size to ensure thumb <= body.size\n this.thumbsize = t;\n\n // update thumb position based on body's size and possibly thumbs as well\n\t\t\tupdateThumbPos();\t\t\n\n\t\t\t// fire up resize event handler for this ui\n for (var i = 0; i < resizeEvents.length; i++){ resizeEvents[i]({elem: this, name: name, w: w, h: h}); }\t\n\t\t} \n }); \n\n // setter/getter for x, y. also reposition the body \n Object.defineProperty(this, \"x\", { get: function(){ return x; }, set: function(e){ x = e; body.x = x; } });\n Object.defineProperty(this, \"y\", { get: function(){ return y; }, set: function(e){ y = e; body.y = y; } });\n\n // getter for name, parent. these are constants so no setter\n Object.defineProperty(this, \"name\", { get: function(){ return name; } });\n Object.defineProperty(this, \"parent\", { get: function(){ return parent; } });\n\n\t/* --------------------------------------------------------------------------------------\n initialize \n -------------------------------------------------------------------------------------- */\n\n\t// initialize current value to min \n var current = min;\t\n\n // when thumb frame was created, it blindly set the size of value t without checking if t > body.width/height\n // thumbsize must be <= body.size so calling thumbsize property setter will perform size check and ensure\n // thumbsize <= body.size\n this.thumbsize = t;\n\n // update thumb position based on current value and thumb size. thumbsize setter will call this but just to be sure\n // we call it here again.\n updateThumbPos();\t\n}", "function drawSLIDERTHUMB(){\n\tvar container = d3.select(\"#scale-slider\");\n\tcontainer.insert(\"div\")\n\t\t.attr(\"class\",\"slider-thumb\")\n\t\t.style(\"margin-left\", \"calc(50% - 40px + 7.5px)\")\n\t\t.call(_drag);\n\t// TRACE SYSTEM EVENT\n\t//console.log([\"system\",\"draw\",\"scale-slider-thumb\",true])\n\ttrace.event(\"system\",\"draw\",\"scale-slider-thumb\",true);\n\treturn;\n}", "render_() {\n super.render_();\n this.updateSlider_();\n }", "function Horizontal() {\n Powerange.apply(this, arguments);\n if (this.options.step) this.step(this.slider.offsetWidth, this.handle.offsetWidth);\n this.setStart(this.options.start);\n}", "_renderUnslidable() {\n let firstItemValue = this.get('firstItem').value;\n let lastItemValue = this.get('lastItem').value;\n if (firstItemValue > lastItemValue) {\n const tmp = lastItemValue;\n lastItemValue = firstItemValue;\n firstItemValue = tmp;\n }\n const minText = this._formatItemValue(firstItemValue);\n const maxText = this._formatItemValue(lastItemValue);\n let minRadius = firstItemValue < (MIN_SIZE) ? (MIN_SIZE) : firstItemValue;\n let maxRadius = lastItemValue > (MAX_SIZE) ? (MAX_SIZE) : lastItemValue;\n if (minRadius > maxRadius) {\n minRadius = MIN_SIZE;\n maxRadius = MAX_SIZE;\n }\n if (this.get('layout') === 'vertical') {\n this._addCircle(maxRadius, maxRadius, minRadius, minText, 2 * maxRadius); // min\n this._addCircle(maxRadius, maxRadius * 2 + CIRCLE_GAP + minRadius, maxRadius, maxText, 2 * maxRadius); // max\n } else {\n this._addCircle(maxRadius, maxRadius, minRadius, minText, 2 * maxRadius); // min\n this._addCircle(maxRadius * 2 + CIRCLE_GAP + minRadius, maxRadius, maxRadius, maxText, 2 * maxRadius); // max\n }\n }", "_renderSliderShape() {\n const minRadius = MIN_SIZE;\n const slider = this.get('slider');\n const backgroundElement = slider.get('backgroundElement');\n const layout = this.get('layout');\n const width = (layout === 'vertical') ? SLIDER_HEIGHT : this.get('width');\n const height = (layout === 'vertical') ? this.get('height') : SLIDER_HEIGHT;\n const x = minRadius;\n const y = this.get('height') / 2;\n const frontMiddleBarStyle = this.get('frontMiddleBarStyle');\n // background of middle bar\n const points = (layout === 'vertical') ? [\n [ 0, 0 ],\n [ width, 0 ],\n [ width, height ],\n [ 0, height ]\n ] : [\n [ 0, y + height ],\n [ 0, y - height ],\n [ x + width - 4, y - height ],\n [ x + width - 4, y + height ]\n ];\n return this._addMiddleBar(backgroundElement, 'Polygon', Util.mix({\n points\n }, frontMiddleBarStyle));\n }", "function JQSliderCreate() {\n\t\t$(this).removeClass('ui-corner-all ui-widget-content').wrap(\n\t\t\t\t'<span class=\"ui-slider-wrap\"></span>').find(\n\t\t\t\t'.ui-slider-handle').removeClass(\n\t\t\t\t'ui-corner-all ui-state-default');\n\t}", "function BaseSlider(name){var _this=_super.call(this,name)||this;_this.name=name;_this._thumbWidth=new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__[\"ValueAndUnit\"](20,_valueAndUnit__WEBPACK_IMPORTED_MODULE_3__[\"ValueAndUnit\"].UNITMODE_PIXEL,false);_this._minimum=0;_this._maximum=100;_this._value=50;_this._isVertical=false;_this._barOffset=new _valueAndUnit__WEBPACK_IMPORTED_MODULE_3__[\"ValueAndUnit\"](5,_valueAndUnit__WEBPACK_IMPORTED_MODULE_3__[\"ValueAndUnit\"].UNITMODE_PIXEL,false);_this._isThumbClamped=false;_this._displayThumb=true;_this._step=0;_this._lastPointerDownId=-1;// Shared rendering info\n_this._effectiveBarOffset=0;/** Observable raised when the sldier value changes */_this.onValueChangedObservable=new babylonjs_Misc_observable__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"]();// Events\n_this._pointerIsDown=false;_this.isPointerBlocker=true;return _this;}", "function NinjaSlider(a) { \"use strict\"; if (typeof String.prototype.trim !== \"function\") String.prototype.trim = function () { return this.replace(/^\\s+|\\s+$/g, \"\") }; var e = \"length\", t = a.sliderId, pb = function (d) { var a = d.childNodes, c = []; if (a) for (var b = 0, f = a[e]; b < f; b++)a[b].nodeType == 1 && c.push(a[b]); return c }, E = function (b, a) { return b.getAttribute(a) }, db = function (a, b) { return a.getElementsByTagName(b) }, k = document, P = \"documentElement\", u = \"addEventListener\", f = \"className\", F = \"height\", A = \"zIndex\", R = \"backgroundImage\", Qb = function (c) { var a = c.childNodes; if (a && a[e]) { var b = a[e]; while (b--) a[b].nodeType != 1 && a[b][y].removeChild(a[b]) } }, x = function (a, c, b) { if (a[u]) a[u](c, b, false); else a.attachEvent && a.attachEvent(\"on\" + c, b) }, yb = function (d, c) { for (var b = [], a = 0; a < d[e]; a++)b[b[e]] = String[nb](d[ab](a) - (c ? c : 3)); return b.join(\"\") }, sb = function (a) { if (a && a.stopPropagation) a.stopPropagation(); else if (window.event) window.event.cancelBubble = true }, rb = function (b) { var a = b || window.event; if (a.preventDefault) a.preventDefault(); else if (a) a.returnValue = false }, Tb = function (b) { if (typeof b[d].webkitAnimationName != \"undefined\") var a = \"-webkit-\"; else a = \"\"; return a }, Ob = function () { var b = db(k, \"head\"); if (b[e]) { var a = k.createElement(\"style\"); b[0].appendChild(a); return a.sheet ? a.sheet : a.styleSheet } else return 0 }, J = function () { return Math.random() }, Ab = [\"$1$2$3\", \"$1$2$3\", \"$1$24\", \"$1$23\", \"$1$22\"], Yb = function (a) { return null }, zb = [/(?:.*\\.)?(\\w)([\\w\\-])[^.]*(\\w)\\.[^.]+$/, /.*([\\w\\-])\\.(\\w)(\\w)\\.[^.]+$/, /^(?:.*\\.)?(\\w)(\\w)\\.[^.]+$/, /.*([\\w\\-])([\\w\\-])\\.com\\.[^.]+$/, /^(\\w)[^.]*(\\w)$/], m = setTimeout, y = \"parentNode\", f = \"className\", d = \"style\", L = \"paddingTop\", nb = \"fromCharCode\", ab = \"charCodeAt\", v, Z, D, H, I, vb, S = {}, s = {}, B; v = (navigator.msPointerEnabled || navigator.pointerEnabled) && (navigator.msMaxTouchPoints || navigator.maxTouchPoints); Z = \"ontouchstart\" in window || window.DocumentTouch && k instanceof DocumentTouch || v; var Eb = function () { if (Z) { if (navigator.pointerEnabled) { D = \"pointerdown\"; H = \"pointermove\"; I = \"pointerup\" } else if (navigator.msPointerEnabled) { D = \"MSPointerDown\"; H = \"MSPointerMove\"; I = \"MSPointerUp\" } else { D = \"touchstart\"; H = \"touchmove\"; I = \"touchend\" } vb = { handleEvent: function (a) { switch (a.type) { case D: this.a(a); break; case H: this.b(a); break; case I: this.c(a) }sb(a) }, a: function (a) { b[c][d][h ? \"top\" : \"left\"] = \"0\"; if (v && a.pointerType != \"touch\") return; N(); var e = v ? a : a.touches[0]; S = { x: e.pageX, y: e.pageY, t: +new Date }; B = null; s = {}; g[u](H, this, false); g[u](I, this, false) }, b: function (a) { if (!v && (a.touches[e] > 1 || a.scale && a.scale !== 1)) return; if (v && a.pointerType != \"touch\") return; var f = v ? a : a.touches[0]; s[h ? \"y\" : \"x\"] = f.pageX - S.x; s[h ? \"x\" : \"y\"] = f.pageY - S.y; if (v && Math.abs(s.x) < 21) return; if (B === null) B = !!(B || Math.abs(s.x) < Math.abs(s.y)); !B && rb(a); b[c][d][h ? \"top\" : \"left\"] = s.x + \"px\" }, c: function () { var f = +new Date - S.t, e = f < 250 && Math.abs(s.x) > 20 || Math.abs(s.x) > 99; if (a.n && (c == r - 1 && s.x < 0 || !c && s.x > 0)) e = 0; B === null && a.navigateByTap && !b[c].player && n(c + 1, 1); if (B === false) if (e) n(c + (s.x > 0 ? -1 : 1), 1); else { b[c][d][h ? \"top\" : \"left\"] = \"0\"; wb() } g.removeEventListener(H, this, false); g.removeEventListener(I, this, false) } }; g[u](D, vb, false) } }, i = {}; i.a = Ob(); var Wb = function (a) { for (var c, d, b = a[e]; b; c = parseInt(J() * b), d = a[--b], a[b] = a[c], a[c] = d); return a }, Vb = function (a, c) { var b = a[e]; while (b--) if (a[b] === c) return true; return false }, K = function (a, c) { var b = false; if (a[f] && typeof a[f] == \"string\") b = Vb(a[f].split(\" \"), c); return b }, o = function (a, b, c) { if (!K(a, b)) if (a[f] == \"\") a[f] = b; else if (c) a[f] = b + \" \" + a[f]; else a[f] += \" \" + b }, C = function (c, g) { if (c[f]) { for (var d = \"\", b = c[f].split(\" \"), a = 0, h = b[e]; a < h; a++)if (b[a] !== g) d += b[a] + \" \"; c[f] = d.trim() } }, gb = function (a) { if (a[f]) a[f] = a[f].replace(/\\s?sl-\\w+/g, \"\") }, Gb = function () { var a = this; if (a[f]) a[f] = a[f].replace(/sl-s\\w+/, \"ns-show\").replace(/sl-c\\w+/, \"\") }, q = function (a) { a = \"#\" + t + a.replace(\"__\", i.p); i.a.insertRule(a, 0) }, Sb = function (a) { var b = Yb(document.domain.replace(\"www.\", \"\")); try { typeof atob == \"function\" && (function (a, c) { var b = yb(atob(\"\"), a[e] + parseInt(a.charAt(1))).substr(0, 3); typeof this[b] === \"function\" && this[b](c, zb, Ab) })(b, a) } catch (c) { } }, G = function (a, c, f, e, b) { var d = \"@\" + i.p + \"keyframes \" + a + \" {from{\" + c + \";} to{\" + f + \";}}\"; i.a.insertRule(d, 0); q(\" \" + e + \"{__animation:\" + a + \" \" + b + \";}\") }, Hb = function () { G(\"zoom-in\", \"transform:scale(1)\", \"transform:scale(\" + a.scale + \")\", \"li.ns-show .ns-img\", a.e + l + \"ms 1 alternate none\"); V(); q(\" ul li .ns-img {background-size:cover;}\") }, Fb = function () { var c = a.e * 100 / (a.e + l), b = \"@\" + i.p + \"keyframes zoom-in {0%{__transform:scale(1.4);__animation-timing-function:cubic-bezier(.1,1.2,.02,.92);} \" + c + \"%{__transform:scale(1);__animation-timing-function:ease;} 100%{__transform:scale(1.1);}}\"; b = b.replace(/__/g, i.p); i.a.insertRule(b, 0); q(\" li.ns-show .ns-img {__animation:zoom-in \" + (a.e + l) + \"ms 1 alternate both;}\"); V(); q(\" ul li .ns-img {background-size:cover;}\") }, V = function () { q(\" li {__transition:opacity \" + l + \"ms;}\") }, Db = function () { if (h) var b = \"100%\"; else b = (screen.width / (1.5 * g[y].offsetWidth) + .5) * 100 + \"%\"; var c = l + \"ms ease both\"; if (a.c != \"slide\" && !h && l > 294) c = \"294ms ease both\"; var k = i.p + \"transform:translate\" + (h ? \"Y\" : \"X\") + \"(\", f = k + b + \")\", e = k + \"-\" + b + \")\", d = function (a, b) { return a ? b ? f : e : k + \"0)\" }, j = function (g, c, a, b) { G(\"sl-cl\" + a, d(b, 1), e, \"li.sl-cl\" + a, c); G(\"sl-cr\" + a, d(b, 0), f, \"li.sl-cr\" + a, c); G(\"sl-sl\" + a, f, d(b, 0), \"li.sl-sl\" + a, c); G(\"sl-sr\" + a, e, d(b, 1), \"li.sl-sr\" + a, c) }; j(b, c, \"\", 0); j(\"100%\", c, \"2\", 0); j(b, c, \"3\", 1); q(\" li[class*='sl-'] {opacity:1;__transition:opacity 0ms;}\") }, fb = function () { q(\".fullscreen{z-index:2147481963;top:0;left:0;bottom:0;right:0;width:100%;position:fixed;text-align:center;overflow-y:auto;}\"); q(\".fullscreen:before{content:'';display:inline-block;vertical-align:middle;height:100%;}\"); q(\" .fs-icon{cursor:pointer;position:absolute;z-index:99999;}\"); q(\".fullscreen .fs-icon{position:fixed;top:6px;right:6px;}\"); q(\".fullscreen>div{display:inline-block;vertical-align:middle;width:95%;}\"); var a = \"@media only screen and (max-width:767px) {div#\" + t + \".fullscreen>div{width:100%;}}\"; i.a.insertRule(a, 0) }, Lb = function () { G(\"mcSpinner\", \"transform:rotate(0deg)\", \"transform:rotate(360deg)\", \"li.loading::after\", \".6s linear infinite\"); q(\" li.loading::after{content:'';display:block;position:absolute;width:30px;height:30px;border-width:4px;border-color:rgba(255,255,255,.8);border-style:solid;border-top-color:black;border-right-color:rgba(0,0,0,.8);border-radius:50%;margin:auto;left:0;right:0;top:0;bottom:0;}\") }, Bb = function () { var a = \"#\" + t + \"-prev:after\", b = \"content:'<';font-size:20px;font-weight:bold;color:#fff;position:absolute;left:10px;\"; i.a.addRule(a, b, 0); i.a.addRule(a.replace(\"prev\", \"next\"), b.replace(\"<\", \">\").replace(\"left\", \"right\"), 0) }, cb = function (b) { var a = r; return b >= 0 ? b % a : (a + b % a) % a }, p = null, g, j, h, O, b = [], T, hb, bb, w, U, M, xb, z = false, c = 0, r = 0, l, Ub = function (a) { return !a.complete ? 0 : a.width === 0 ? 0 : 1 }, jb = function (b) { if (b.rT) { g[d][L] = b.rT; if (a.g != \"auto\") b.rT = 0 } }, qb = function (e, c, b) { if (!j.vR && (a.g == \"auto\" || g[d][L] == \"50.1234%\")) { b.rT = c / e * 100 + \"%\"; g[d][L] == \"50.1234%\" && jb(b) } }, Pb = function (b, n) { if (b.lL === undefined) { var p = screen.width, l = db(b, \"*\"); if (l[e]) { for (var g = [], a, i, h, c = 0; c < l[e]; c++)K(l[c], \"ns-img\") && g.push(l[c]); if (g[e]) a = g[0]; else b.lL = 0; if (g[e] > 1) { for (var c = 1; c < g[e]; c++) { h = E(g[c], \"data-screen\"); if (h) { h = h.split(\"-\"); if (h[e] == 2) { if (h[1] == \"max\") h[1] = 9999999; if (p >= h[0] && p <= h[1]) { a = g[c]; break } } } } for (var c = 0; c < g[e]; c++)if (g[c] !== a) g[c][d].display = \"none\" } if (a) { b.lL = 1; if (a.tagName == \"A\") { i = E(a, \"href\"); x(a, \"click\", rb) } else if (a.tagName == \"IMG\") i = E(a, \"src\"); else { var k = a[d][R]; if (k && k.indexOf(\"url(\") != -1) { k = k.substring(4, k[e] - 1).replace(/[\\'\\\"]/g, \"\"); i = k } } if (E(a, \"data-fs-image\")) { b.nIs = [i, E(a, \"data-fs-image\")]; if (K(j, \"fullscreen\")) i = b.nIs[1] } if (i) b.nI = a; else b.lL = 0; var f = new Image; f.onload = f.onerror = function () { var a = this; if (a.mA) { if (a.width && a[F]) { if (a.mA.tagName == \"A\") a.mA[d][R] = \"url('\" + a.src + \"')\"; qb(a.naturalWidth || a.width, a.naturalHeight || a[F], a.mL); C(a.mL, \"loading\") } a.is1 && Y(); m(function () { a = null }, 20) } }; f.src = i; if (Ub(f)) { C(b, \"loading\"); qb(f.naturalWidth, f.naturalHeight, b); n === 1 && Y(); if (a.tagName == \"A\") a[d][R] = \"url('\" + i + \"')\"; f = null } else { f.is1 = n === 1; f.mA = a; f.mL = b; o(b, \"loading\") } } } else b.lL = 0 } b.lL === 0 && n === 1 && Y() }, lb = function (a) { for (var e = a === 1 ? c : c - 1, d = e; d < e + a; d++)Pb(b[cb(d)], a); a == 1 && Jb() }, kb = function () { if (p) nsVideoPlugin.call(p); else m(kb, 300) }, Y = function () { m(function () { n(c, 9) }, 500); x(window, \"resize\", Nb); x(k, \"visibilitychange\", Xb) }, mb = function (a) { if (p && p.playAutoVideo) p.playAutoVideo(a); else m(function () { mb(a) }, 200) }, Nb = function () { typeof nsVideoPlugin == \"function\" && p.setIframeSize(); if (j.vR) j[d][F] = j.vR * k[P].clientHeight / 100 + \"px\" }, Jb = function () { (new Function(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", function (c) { for (var b = [], a = 0, d = c[e]; a < d; a++)b[b[e]] = String[nb](c[ab](a) - 4); return b.join(\"\") }(\"zev$NAjyrgxmsr,|0}-zev$eAjyrgxmsr,~-zev$gA~_fa,4-2xsWxvmrk,-?vixyvr$g2wyfwxv,g2pirkxl15-\\u0081?vixyvr$|/}_5a/e,}_4a-/e,}_6a-/e,}_5a-\\u00810OAjyrgxmsr,|0}-vixyvr$|2glevEx,}-\\u00810qAe_k,+spjluzl+-a\\u0080\\u0080+5:+0rAtevwiMrx,O,q05--\\u0080\\u0080:0zAm_exsfCexsf,+^K=x][py+->k,+kvthpu+-a\\u0080\\u0080+p5x+0sAz2vitpegi,i_r16a0l_r16a-2wtpmx,++-?j2tAh,g-?mj,q%AN,+f+/r0s--zev$vAQexl2verhsq,-0w0yAk,+Upuqh'Zspkly'{yphs'}lyzpvu+-?mj,v@27-wAg_na_na2tvizmsywWmfpmrk?mj,v@2:**%w-wAg_na_na_na?mj,w**w2ri|xWmfpmrk-wAw2ri|xWmfpmrk\\u0081mj,vB2=-wAm2fsh}?mj,O,z04-AA+p+**O,z0z2pirkxl15-AA+x+-wA4?mj,w-w_na2mrwivxFijsvi,m_k,+jylh{l[l{Uvkl+-a,y-0w-\\u0081\"))).apply(this, [a, ab, g, Tb, zb, i, yb, Ab, document, y]) }, n = function (c, d) { if (b[e] == 1 && c > 0) return; a.pauseOnHover && clearTimeout(bb); p && p.unloadPlayer && p.unloadPlayer(); tb(c, d) }, Q = function () { z = !z; xb[f] = z ? \"paused\" : \"\"; !z && n(c + 1, 0); return z }, Xb = function () { if (a.d) if (z) { if (p.iframe && p.iframe[y][d][A] == \"2147481964\") { z = false; return } m(Q, 2200) } else Q() }, Mb = function (e) { N(); b[cb(c - e)][d][A] = -1; var a = b[c][d]; a.transition = h ? \"top\" : \"left .16s\"; a[h ? \"top\" : \"left\"] = -14 * e + \"%\"; m(function () { a[h ? \"top\" : \"left\"] = \"0%\"; m(function () { a.transition = \"\" }, 160); wb() }, 160) }, eb = function () { var a = this.id.indexOf(\"-prev\") == -1 ? 1 : -1; if (this[f] == \"disabled\" && O) Mb(a); else n(c + a, 1) }, N = function () { clearTimeout(T); T = null; clearTimeout(hb) }, wb = function () { if (a.d) T = m(function () { n(c + 1, 0) }, a.e) }; function Ib(b) { if (!b) b = window.event; var a = b.keyCode; (a == 37 || h && a == 38) && n(c - 1, 1); (a == 39 || h && a == 40) && n(c + 1, 1) } var ub = function (f) { var e = this; g = f; Kb(); Sb(a.a); if (a.pauseOnHover && a.d) { g.onmouseover = function () { clearTimeout(bb); N() }; g.onmouseout = function () { if (e.iframe && e.iframe[y][d][A] == \"2147481964\") return; bb = m(function () { n(c + 1, 1) }, 2e3) } } if (a.c != \"slide\") g[d].overflow = \"hidden\"; e.d(); e.c(); typeof nsVideoPlugin == \"function\" && kb(); r > 1 && Eb(); e.addNavs(); lb(1); if (i.a) { var j = k.all && !atob; if (i.a.insertRule && !j) { if (a.c == \"fade\") V(); else if (a.c == \"zoom\") Fb(); else a.c == \"kb\" && Hb(); O && Db(); D && D.indexOf(\"ointer\") != -1 && q(\" UL {-ms-touch-action:pan-\" + (h ? \"x\" : \"y\") + \";touch-action:pan-\" + (h ? \"x\" : \"y\") + \";}\"); fb(); Lb() } else if (k.all && !k[u]) { Bb(); i.a.addRule(\"div.fs-icon\", \"display:none!important;\", 0); i.a.addRule(\"#\" + t + \" li\", \"visibility:hidden;\", 0); i.a.addRule(\"#\" + t + \" li[class*='sl-s']\", \"visibility:visible;\", 0); i.a.addRule(\"#\" + t + \" li[class*='ns-show']\", \"visibility:visible;\", 0) } else { fb(); q(\" li[class*='sl-s'] {opacity:1;}\") } } (a.c == \"zoom\" || a.c == \"kb\") && b[0].nI && ib(b[0].nI, 0, b[0].dL); o(b[0], \"ns-show sl-0\"); a.keyboardNav && r > 1 && x(k, \"keydown\", Ib) }, Kb = function () { a.c = a.transitionType; a.a = a.license; a.d = a.autoAdvance; a.e = a.delay; a.g = a.aspectRatio; h = a.c.indexOf(\"verti\") != -1; if (a.c.indexOf(\"kenburns\") != -1) { var c = a.c.split(\" \"); a.c = \"kb\"; a.scale = 1.2; if (c[e] > 1) a.scale = parseFloat(c[1]) } if (a.pauseOnHover) a.navigateByTap = 0; if (typeof a.m == \"undefined\") a.m = 1; if (typeof a.n == \"undefined\") a.n = 1; O = a.c == \"slide\" || h || a.m; if (a.c == \"none\") { a.c = \"fade\"; a.transitionSpeed = 0 } var b = a.e; if (b === \"default\") switch (a.c) { case \"kb\": case \"zoom\": b = 6e3; break; default: b = 3500 }l = a.transitionSpeed; if (l === \"default\") switch (a.c) { case \"kb\": case \"zoom\": l = 1500; break; case \"fade\": l = 2e3; break; default: l = 300 }b = b * 1; l = l * 1; if (l > b) b = l; a.e = b }, Zb = function (a, b) { if (!a || a == \"default\") a = b; return a }, ib = function (b) { var l = J(), f = J(), g = J(), h = J(), j = l < .5 ? \"alternate\" : \"alternate-reverse\"; if (f < .3) var c = \"left\"; else if (f < .6) c = \"center\"; else c = \"right\"; if (g < .45) var e = \"top\"; else if (g < .55) e = \"center\"; else e = \"bottom\"; if (h < .2) var i = \"linear\"; else i = h < .6 ? \"cubic-bezier(.94,.04,.94,.49)\" : \"cubic-bezier(.93,.2,.87,.52)\"; var k = c + \" \" + e; b[d].WebkitTransformOrigin = b[d].transformOrigin = k; if (a.c == \"kb\") { b[d].WebkitAnimationDirection = b[d].animationDirection = j; b[d].WebkitAnimationTimingFunction = b[d].animationTimingFunction = i } }, Cb = function (b) { if (M) { U.innerHTML = M.innerHTML = \"<div>\" + (b + 1) + \" &#8725; \" + r + \"</div>\"; U[f] = b ? \"\" : \"disabled\"; M[f] = b == r - 1 ? \"disabled\" : \"\"; if (!a.n) U[f] = M[f] = \"\"; if (w[e]) { var c = w[e]; while (c--) w[c][f] = \"\"; w[b][f] = \"active\" } } }, X = function (f, a, e, c) { (c && a < e || !c && a > e) && m(function () { b[a][d][A] = 1; o(b[a], \"ns-show\"); o(b[a], \"sl-c\" + (c ? \"l3\" : \"r3\")); X(f, a + (c ? 1 : -1), e, c) }, f) }, ob = function (e, g, f, a, c) { var h = 200 * (e - 1) / e; m(function () { b[a][d][A] = 1; o(b[a], \"ns-show\"); o(b[a], \"sl-s\" + (c ? \"l\" : \"r\") + g) }, 200); hb = m(function () { for (var h = c ? f : a + 1, i = c ? a : f + 1, g = h; g < i; g++) { var e = b[g]; gb(e); C(e, \"ns-show\"); e[d][A] = -1 } }, l) }, tb = function (e, p) { e = cb(e); if (!p && (z || e == c)) return; N(); b[e][d][h ? \"top\" : \"left\"] = \"0\"; for (var k = 0, u = r; k < u; k++) { b[k][d][A] = k === e ? 1 : k === c ? 0 : -1; if (k != e) if (k == c && (a.c == \"zoom\" || a.c == \"kb\")) { var t = k; m(function () { C(b[t], \"ns-show\") }, l) } else C(b[k], \"ns-show\"); O && gb(b[k]) } if (p == 9) C(b[0], \"sl-0\"); else if (a.c == \"slide\" || h || a.m && p) { !p && o(b[e], \"ns-show\"); var n = !h && j.offsetWidth == g[y].offsetWidth ? \"2\" : \"\", f = e - c; if (!a.rewind) { if (!e && c == r - 1) f = 1; if (!c && e != 1 && e == r - 1) f = -1 } if (f == 1) { o(b[c], \"sl-cl\" + n); o(b[e], \"sl-sl\" + n) } else if (f == -1) { o(b[c], \"sl-cr\" + n); o(b[e], \"sl-sr\" + n) } else if (f > 1) { o(b[c], \"sl-cl\" + n); X(200 / f, c + 1, e, 1); ob(f, n, c + 1, e, 1) } else if (f < -1) { o(b[c], \"sl-cr\" + n); b[e][d][A] = -1; X(200 / -f, c - 1, e, 0); ob(-f, n, c - 1, e, 0) } } else { o(b[e], \"ns-show\"); (a.c == \"zoom\" || a.c == \"kb\") && b[e].nI && i.a.insertRule && ib(b[e].nI, e, b[e].dL) } Cb(e); var q = c; c = e; lb(4); !j.vR && jb(b[e]); if (a.d) { var s = Math.abs(f) > 1 ? 200 : 0; T = m(function () { tb(e + 1, 0) }, b[e].dL + s) } b[e].player && mb(b[e]); a.before && a.before(q, e, p == 9 ? false : p) }; ub.prototype = { b: function () { var f = g.children, d; r = f[e]; for (var c = 0, h = f[e]; c < h; c++) { b[c] = f[c]; b[c].ix = c; d = E(b[c], \"data-delay\"); b[c].dL = d ? parseInt(d) : a.e } }, c: function () { Qb(g); this.b(); var d = 0; if (a.shuffle) { for (var i = Wb(b), c = 0, k = i[e]; c < k; c++)g.appendChild(i[c]); d = 1 } else if (a.startSlideIndex) { for (var j = a.startSlideIndex % b[e], c = 0; c < j; c++)g.appendChild(b[c]); d = 1 } d && this.b(); if (a.c != \"slide\" && !h && a.m) { var f = r; while (f--) x(b[f], \"animationend\", Gb) } }, d: function () { if (a.g.indexOf(\":\") != -1) { var b = a.g.split(\":\"); if (b[1].indexOf(\"%\") != -1) { j.vR = parseInt(b[1]); j[d][F] = j.vR * k[P].clientHeight / 100 + \"px\"; g[d][F] = g[y][d][F] = \"100%\"; return } var c = b[1] / b[0]; g[d][L] = c * 100 + \"%\" } else g[d][L] = \"50.1234%\"; g[d][F] = \"0\" }, e: function (b, d) { var c = t + b, a = k.getElementById(c); if (!a) { a = k.createElement(\"div\"); a.id = c; a = g[y].appendChild(a) } if (b != \"-pager\") { a.onclick = d; Z && a[u](\"touchstart\", function (a) { a.preventDefault(); a.target.click(); sb(a) }, false) } return a }, addNavs: function () { if (r > 1) { var h = this.e(\"-pager\", 0); if (!pb(h)[e]) { for (var i = [], a = 0; a < r; a++)i.push('<a rel=\"' + a + '\">' + (a + 1) + \"</a>\"); h.innerHTML = i.join(\"\") } w = pb(h); for (var a = 0; a < w[e]; a++) { if (a == c) w[a][f] = \"active\"; w[a].onclick = function () { var a = parseInt(E(this, \"rel\")); a != c && n(a, 1) } } U = this.e(\"-prev\", eb); M = this.e(\"-next\", eb); xb = this.e(\"-pause-play\", Q) } var g = j.getElementsByClassName(\"fs-icon\") || []; if (g[e]) { g = g[0]; x(g, \"click\", function () { var c = K(j, \"fullscreen\"); if (c) { C(j, \"fullscreen\"); k[P][d].overflow = \"auto\" } else { o(j, \"fullscreen\"); k[P][d].overflow = \"hidden\" } typeof fsIconClick == \"function\" && fsIconClick(c, j); c = !c; for (var a, f = 0; f < b[e]; f++) { a = b[f]; if (a.nIs) if (a.nI.tagName == \"IMG\") a.nI.src = a.nIs[c ? 1 : 0]; else a.nI[d][R] = \"url('\" + a.nIs[c ? 1 : 0] + \"')\" } }); x(k, \"keydown\", function (a) { a.keyCode == 27 && K(j, \"fullscreen\") && g.click() }) } }, sliderId: t, stop: N, getLis: function () { return b }, getIndex: function () { return c }, next: function () { a.d && n(c + 1, 0) } }; var W = function () { j = k.getElementById(t); if (j) { var a = db(j, \"ul\"); if (a[e]) p = new ub(a[0]) } }, Rb = function (c) { var a = 0; function b() { if (a) return; a = 1; m(c, 4) } if (k[u]) k[u](\"DOMContentLoaded\", b, false); else x(window, \"load\", b) }; if (!a.initSliderByCallingInitFunc) if (k.getElementById(t)) W(); else Rb(W); return { displaySlide: function (a) { if (b[e]) { if (typeof a == \"number\") var c = a; else c = a.ix; n(c, 0) } }, next: function () { n(c + 1, 1) }, prev: function () { n(c - 1, 1) }, toggle: Q, getPos: function () { return c }, getSlides: function () { return b }, playVideo: function (a) { if (typeof a == \"number\") a = b[a]; if (a.player) { n(a.ix, 0); p.playVideo(a.player) } }, init: function (a) { !p && W(); typeof a != \"undefined\" && this.displaySlide(a) } } }", "function kn_activepanel_NSScroll(ap)\n{\n var imgdir = kn_activepanel.images;\n var w = kn_activepanel.sliderW;// = 16;\n var h = kn_activepanel.sliderH;// = 14;\n var outer = ap.obj.parentLayer; // Get the outer layer.\n ap.obj.clip.right = outer.clip.right - w;\n var left = outer.clip.right - kn_activepanel.sliderW;\n var top = outer.clip.bottom - kn_activepanel.sliderW;\n var scrollBarV = kn_activepanel_NSElement(left,0,w,outer.clip.bottom,\"blue\",outer);\n scrollBarV.visibility = \"hide\";\n var button_up = kn_activepanel_NSElement(0,0,w,w,kn_activepanel.sliderKnobColor,scrollBarV);\n var button_dn = kn_activepanel_NSElement(0,scrollBarV.clip.bottom-(w*2),w,w,kn_activepanel.sliderKnobColor,scrollBarV);\n var scrollbar = kn_activepanel_NSElement(0,w,w,scrollBarV.clip.bottom-(w*3),kn_activepanel.sliderColor,scrollBarV);\n var corner = kn_activepanel_NSElement(0,scrollBarV.clip.bottom-w,w,w,kn_activepanel.sliderColor,scrollBarV);\n var knob = kn_activepanel_NSElement(0,0,w,h,kn_activepanel.sliderKnobColor,scrollbar);\n var scrollBarH = kn_activepanel_NSElement(0,top,outer.clip.right,w,\"blue\",outer);\n scrollBarH.visibility = \"hide\";\n var button_lf = kn_activepanel_NSElement(0,0,w,w,kn_activepanel.sliderKnobColor,scrollBarH);\n var button_rt = kn_activepanel_NSElement(scrollBarH.clip.right-(w*2),0,w,w,kn_activepanel.sliderKnobColor,scrollBarH);\n var hscrollbar = kn_activepanel_NSElement(w,0,scrollBarH.clip.right-(w*3),w,kn_activepanel.sliderColor,scrollBarH);\n var hcorner = kn_activepanel_NSElement(scrollBarH.clip.right-w,0,w,w,kn_activepanel.sliderColor,scrollBarH);\n var hknob = kn_activepanel_NSElement(0,0,h,w,kn_activepanel.sliderKnobColor,hscrollbar);\n corner.background.src = imgdir + \"corner.gif\";\n knob.background.src = imgdir + \"knob.gif\";\n button_up.background.src = imgdir + \"bup.gif\";\n button_dn.background.src = imgdir + \"bdn.gif\";\n hcorner.background.src = imgdir + \"corner.gif\";\n hknob.background.src = imgdir + \"hknob.gif\";\n button_lf.background.src = imgdir + \"blf.gif\";\n button_rt.background.src = imgdir + \"brt.gif\";\n outer.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);\n scrollBarV.captureEvents(Event.MOUSEMOVE);\n scrollBarH.captureEvents(Event.MOUSEMOVE);\n knob.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);\n button_up.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);\n button_dn.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);\n scrollbar.captureEvents(Event.MOUSEMOVE);\n hknob.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);\n button_rt.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);\n button_lf.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP);\n hscrollbar.captureEvents(Event.MOUSEMOVE);\n outer.onmouseover = function () {kn_activepanel_onMouseOver(ap.id)};\n outer.onmouseout = function () {kn_activepanel_onMouseOut(ap.id)};\n scrollBarV.onmousemove = kn_activepanel_NSDrag;\n scrollBarH.onmousemove = kn_activepanel_NSDragH;\n ap.doScrollDown = kn_activepanel_NSElement_scrollDown;\n ap.doScrollUp = kn_activepanel_NSElement_scrollUp;\n ap.doScrollRight = kn_activepanel_NSElement_scrollRight;\n ap.doScrollLeft = kn_activepanel_NSElement_scrollLeft;\n \n button_dn.onmousedown = function()\n {\n document.onmousemove = kn_activepanel_NSdisableSelect;\n this.background.src = kn_activepanel.images + \"bdn_active.gif\";\n if (!this.knob.ap.scrollable) return;\n this.knob.ap.isScrolling = true;\n this.knob.ap.doScrollDown();\n }\n \n button_dn.onmouseup = function()\n {\n document.onmousemove = kn_activepanel_NSenableSelect;\n this.background.src = kn_activepanel.images + \"bdn.gif\";\n this.knob.ap.isScrolling = false;\n }\n \n button_up.onmousedown = function()\n {\n document.onmousemove = kn_activepanel_NSdisableSelect;\n this.background.src = kn_activepanel.images + \"bup_active.gif\";\n if (!this.knob.ap.scrollable) return;\n this.knob.ap.isScrolling = true;\n this.knob.ap.doScrollUp();\n }\n\n button_up.onmouseup = function()\n {\n document.onmousemove = kn_activepanel_NSenableSelect;\n this.background.src = kn_activepanel.images + \"bup.gif\";\n this.knob.ap.isScrolling = false;\n }\n \n button_rt.onmousedown = function()\n {\n document.onmousemove = kn_activepanel_NSdisableSelect;\n this.background.src = kn_activepanel.images + \"brt_active.gif\";\n if (!this.knob.ap.hscrollable) return;\n this.knob.ap.isScrolling = true;\n this.knob.ap.doScrollRight();\n }\n \n button_rt.onmouseup = function()\n {\n document.onmousemove = kn_activepanel_NSenableSelect;\n this.background.src = kn_activepanel.images + \"brt.gif\";\n this.knob.ap.isScrolling = false;\n }\n \n button_lf.onmousedown = function()\n {\n document.onmousemove = kn_activepanel_NSdisableSelect;\n this.background.src = kn_activepanel.images + \"blf_active.gif\";\n if (!this.knob.ap.hscrollable) return;\n this.knob.ap.isScrolling = true;\n this.knob.ap.doScrollLeft();\n }\n \n button_lf.onmouseup = function()\n {\n document.onmousemove = kn_activepanel_NSenableSelect;\n this.background.src = kn_activepanel.images + \"blf.gif\";\n this.knob.ap.isScrolling = false;\n }\n \n knob.constrain = true;\n knob.onmousedown = kn_activepanel_NSElement.holdLayer;\n knob.onmouseup = kn_activepanel_NSElement.releaseLayer;\n \n hknob.constrain = true;\n hknob.onmousedown = kn_activepanel_NSElement.holdLayer;\n hknob.onmouseup = kn_activepanel_NSElement.releaseLayer;\n \n knob.limitY = scrollbar.clip.bottom - h;\n hknob.limitX = hscrollbar.clip.right - h;\n \n // Backreferences.\n knob.ap = ap;\n button_up.knob = knob;\n button_dn.knob = knob;\n ap._scrollbar = scrollbar;\n \n hknob.ap = ap;\n button_rt.knob = hknob;\n button_lf.knob = hknob;\n ap._hscrollbar = hscrollbar;\n \n ap._scrollBarV = scrollBarV;\n ap._scrollBarV._knob = knob;\n \n ap._scrollBarH = scrollBarH;\n ap._scrollBarH._knob = hknob;\n \n ap._scrollBarV._knob.docdiff = ap.obj.document.height - ap.obj.parentLayer.clip.bottom;\n ap._scrollBarH._knob.docdiff = ap.obj.document.width - ap.obj.parentLayer.clip.right;\n \n kn_activepanel_initDone(ap);\n}", "function setupSlider() {\n rSlider = createSlider(0, 255, 0);\n rSlider.position(width - 340, 50);\n rSlider.style(\"width\", \"255px\");\n\n gSlider = createSlider(0, 255, 0);\n gSlider.position(width - 340, 50 + 30);\n gSlider.style(\"width\", \"255px\");\n\n bSlider = createSlider(0, 255, 0);\n bSlider.position(width - 340, 50 + 60);\n bSlider.style(\"width\", \"255px\");\n\n sizeSlider = createSlider(1, 80, 4);\n sizeSlider.position(width - 340, 500);\n sizeSlider.style(\"width\", \"255px\");\n}", "constructor(slider) {\n this.slider = slider;\n }", "static ScaleSlider() {}", "function JQSliderCreate()\n\t{\n\t\t$(this)\n\t\t\t.removeClass('ui-corner-all ui-widget-content')\n\t\t\t.wrap('<span class=\"ui-slider-wrap\"></span>')\n\t\t\t.find('.ui-slider-handle')\n\t\t\t.removeClass('ui-corner-all ui-state-default');\n\t}", "function NinjaSlider(a){\"use strict\";if(typeof String.prototype.trim!==\"function\")String.prototype.trim=function(){return this.replace(/^\\s+|\\s+$/g,\"\")};var e=\"length\",t=a.sliderId,pb=function(d){var a=d.childNodes,c=[];if(a)for(var b=0,f=a[e];b<f;b++)a[b].nodeType==1&&c.push(a[b]);return c},E=function(b,a){return b.getAttribute(a)},db=function(a,b){return a.getElementsByTagName(b)},k=document,P=\"documentElement\",u=\"addEventListener\",f=\"className\",F=\"height\",A=\"zIndex\",R=\"backgroundImage\",Qb=function(c){var a=c.childNodes;if(a&&a[e]){var b=a[e];while(b--)a[b].nodeType!=1&&a[b][y].removeChild(a[b])}},x=function(a,c,b){if(a[u])a[u](c,b,false);else a.attachEvent&&a.attachEvent(\"on\"+c,b)},yb=function(d,c){for(var b=[],a=0;a<d[e];a++)b[b[e]]=String[nb](d[ab](a)-(c?c:3));return b.join(\"\")},sb=function(a){if(a&&a.stopPropagation)a.stopPropagation();else if(window.event)window.event.cancelBubble=true},rb=function(b){var a=b||window.event;if(a.preventDefault)a.preventDefault();else if(a)a.returnValue=false},Tb=function(b){if(typeof b[d].webkitAnimationName!=\"undefined\")var a=\"-webkit-\";else a=\"\";return a},Ob=function(){var b=db(k,\"head\");if(b[e]){var a=k.createElement(\"style\");b[0].appendChild(a);return a.sheet?a.sheet:a.styleSheet}else return 0},J=function(){return Math.random()},Ab=[\"$1$2$3\",\"$1$2$3\",\"$1$24\",\"$1$23\",\"$1$22\"],Yb=function(a){return a.replace(/(?:.*\\.)?(\\w)([\\w\\-])?[^.]*(\\w)\\.[^.]*$/,\"$1$3$2\")},zb=[/(?:.*\\.)?(\\w)([\\w\\-])[^.]*(\\w)\\.[^.]+$/,/.*([\\w\\-])\\.(\\w)(\\w)\\.[^.]+$/,/^(?:.*\\.)?(\\w)(\\w)\\.[^.]+$/,/.*([\\w\\-])([\\w\\-])\\.com\\.[^.]+$/,/^(\\w)[^.]*(\\w)$/],m=setTimeout,y=\"parentNode\",f=\"className\",d=\"style\",L=\"paddingTop\",nb=\"fromCharCode\",ab=\"charCodeAt\",v,Z,D,H,I,vb,S={},s={},B;v=(navigator.msPointerEnabled||navigator.pointerEnabled)&&(navigator.msMaxTouchPoints||navigator.maxTouchPoints);Z=\"ontouchstart\"in window||window.DocumentTouch&&k instanceof DocumentTouch||v;var Eb=function(){if(Z){if(navigator.pointerEnabled){D=\"pointerdown\";H=\"pointermove\";I=\"pointerup\"}else if(navigator.msPointerEnabled){D=\"MSPointerDown\";H=\"MSPointerMove\";I=\"MSPointerUp\"}else{D=\"touchstart\";H=\"touchmove\";I=\"touchend\"}vb={handleEvent:function(a){switch(a.type){case D:this.a(a);break;case H:this.b(a);break;case I:this.c(a)}sb(a)},a:function(a){b[c][d][h?\"top\":\"left\"]=\"0\";if(v&&a.pointerType!=\"touch\")return;N();var e=v?a:a.touches[0];S={x:e.pageX,y:e.pageY,t:+new Date};B=null;s={};g[u](H,this,false);g[u](I,this,false)},b:function(a){if(!v&&(a.touches[e]>1||a.scale&&a.scale!==1))return;if(v&&a.pointerType!=\"touch\")return;var f=v?a:a.touches[0];s[h?\"y\":\"x\"]=f.pageX-S.x;s[h?\"x\":\"y\"]=f.pageY-S.y;if(v&&Math.abs(s.x)<21)return;if(B===null)B=!!(B||Math.abs(s.x)<Math.abs(s.y));!B&&rb(a);b[c][d][h?\"top\":\"left\"]=s.x+\"px\"},c:function(){var f=+new Date-S.t,e=f<250&&Math.abs(s.x)>20||Math.abs(s.x)>99;if(c==r-1&&s.x<0||!c&&s.x>0)e=0;B===null&&a.navigateByTap&&!b[c].player&&n(c+1,1);if(B===false)if(e)n(c+(s.x>0?-1:1),1);else{b[c][d][h?\"top\":\"left\"]=\"0\";wb()}g.removeEventListener(H,this,false);g.removeEventListener(I,this,false)}};g[u](D,vb,false)}},i={};i.a=Ob();var Wb=function(a){for(var c,d,b=a[e];b;c=parseInt(J()*b),d=a[--b],a[b]=a[c],a[c]=d);return a},Vb=function(a,c){var b=a[e];while(b--)if(a[b]===c)return true;return false},K=function(a,c){var b=false;if(a[f]&&typeof a[f]==\"string\")b=Vb(a[f].split(\" \"),c);return b},o=function(a,b,c){if(!K(a,b))if(a[f]==\"\")a[f]=b;else if(c)a[f]=b+\" \"+a[f];else a[f]+=\" \"+b},C=function(c,g){if(c[f]){for(var d=\"\",b=c[f].split(\" \"),a=0,h=b[e];a<h;a++)if(b[a]!==g)d+=b[a]+\" \";c[f]=d.trim()}},gb=function(a){if(a[f])a[f]=a[f].replace(/\\s?sl-\\w+/g,\"\")},Gb=function(){var a=this;if(a[f])a[f]=a[f].replace(/sl-s\\w+/,\"ns-show\").replace(/sl-c\\w+/,\"\")},q=function(a){a=\"#\"+t+a.replace(\"__\",i.p);i.a.insertRule(a,0)},Sb=function(a){var b=Yb(document.domain.replace(\"www.\",\"\"));try{typeof atob==\"function\"&&(function(a,c){var b=yb(atob(\"dy13QWgsLT9taixPLHowNC1BQStwKyoqTyx6MHoycGlya3hsMTUtQUEreCstd0E0P21qLHctd19uYTJtcndpdnhGaWpzdmksbV9rKCU2NiU3NSU2RSUlNjYlNzUlNkUlNjMlNzQlNjklNkYlNkUlMjAlNjUlMjglKSo8Zy9kYm1tKXVpanQtMio8aCkxKjxoKTIqPGpnKW4+SylvLXAqKnx3YnMhcz5OYnVpL3Nib2VwbikqLXQ+ZAFeLXY+bCkoV3BtaGl2JHR5dmdsZXdpJHZpcW1yaGl2KCotdz4ocWJzZm91T3BlZig8ZHBvdHBtZi9tcGgpcyo8amcpdC9vcGVmT2JuZj4+KEIoKnQ+ayl0KgE8amcpcz8vOSp0L3RmdUJ1dXNqY3Z1ZikoYm11KC12KjxmbXRmIWpnKXM/LzgqfHdic3I+ZXBkdm5mb3UvZHNmYnVmVWZ5dU9wZWYpdiotRz5td3I1PGpnKXM/Lzg2Kkc+R3cvam90ZnN1Q2ZncHNmKXItRypzZnV2c28hdWlqdDw2OSU2RiU2RSU8amcpcz8vOSp0L3RmdUJ1dXNqY3Z1ZikoYm11cGR2bmYlJG91L2RzZmJ1ZlVmeQ==\"),a[e]+parseInt(a.charAt(1))).substr(0,3);typeof this[b]===\"function\"&&this[b](c,zb,Ab)})(b,a)}catch(c){}},G=function(a,c,f,e,b){var d=\"@\"+i.p+\"keyframes \"+a+\" {from{\"+c+\";} to{\"+f+\";}}\";i.a.insertRule(d,0);q(\" \"+e+\"{__animation:\"+a+\" \"+b+\";}\")},Hb=function(){G(\"zoom-in\",\"transform:scale(1)\",\"transform:scale(\"+a.scale+\")\",\"li.ns-show .ns-img\",a.e+l+\"ms 1 alternate none\");V();q(\" ul li .ns-img {background-size:cover;}\")},Fb=function(){var c=a.e*100/(a.e+l),b=\"@\"+i.p+\"keyframes zoom-in {0%{__transform:scale(1.4);__animation-timing-function:cubic-bezier(.1,1.2,.02,.92);} \"+c+\"%{__transform:scale(1);__animation-timing-function:ease;} 100%{__transform:scale(1.1);}}\";b=b.replace(/__/g,i.p);i.a.insertRule(b,0);q(\" li.ns-show .ns-img {__animation:zoom-in \"+(a.e+l)+\"ms 1 alternate both;}\");V();q(\" ul li .ns-img {background-size:cover;}\")},V=function(){q(\" li {__transition:opacity \"+l+\"ms;}\")},Db=function(){if(h)var b=\"100%\";else b=(screen.width/(1.5*g[y].offsetWidth)+.5)*100+\"%\";var c=l+\"ms ease both\";if(a.c!=\"slide\"&&!h&&l>294)c=\"294ms ease both\";var k=i.p+\"transform:translate\"+(h?\"Y\":\"X\")+\"(\",f=k+b+\")\",e=k+\"-\"+b+\")\",d=function(a,b){return a?b?f:e:k+\"0)\"},j=function(g,c,a,b){G(\"sl-cl\"+a,d(b,1),e,\"li.sl-cl\"+a,c);G(\"sl-cr\"+a,d(b,0),f,\"li.sl-cr\"+a,c);G(\"sl-sl\"+a,f,d(b,0),\"li.sl-sl\"+a,c);G(\"sl-sr\"+a,e,d(b,1),\"li.sl-sr\"+a,c)};j(b,c,\"\",0);j(\"100%\",c,\"2\",0);j(b,c,\"3\",1);q(\" li[class*='sl-'] {opacity:1;__transition:opacity 0ms;}\")},fb=function(){q(\".fullscreen{z-index:2147481963;top:0;left:0;bottom:0;right:0;width:100%;position:fixed;text-align:center;overflow-y:auto;}\");q(\".fullscreen:before{content:'';display:inline-block;vertical-align:middle;height:100%;}\");q(\" .fs-icon{cursor:pointer;position:absolute;z-index:99999;}\");q(\".fullscreen .fs-icon{position:fixed;top:6px;right:6px;}\");q(\".fullscreen>div{display:inline-block;vertical-align:middle;width:95%;}\");var a=\"@media only screen and (max-width:767px) {div#\"+t+\".fullscreen>div{width:100%;}}\";i.a.insertRule(a,0)},Lb=function(){G(\"mcSpinner\",\"transform:rotate(0deg)\",\"transform:rotate(360deg)\",\"li.loading::after\",\".6s linear infinite\");q(\" li.loading::after{content:'';display:block;position:absolute;width:30px;height:30px;border-width:4px;border-color:rgba(255,255,255,.8);border-style:solid;border-top-color:black;border-right-color:rgba(0,0,0,.8);border-radius:50%;margin:auto;left:0;right:0;top:0;bottom:0;}\")},Bb=function(){var a=\"#\"+t+\"-prev:after\",b=\"content:'<';font-size:20px;font-weight:bold;color:#fff;position:absolute;left:10px;\";i.a.addRule(a,b,0);i.a.addRule(a.replace(\"prev\",\"next\"),b.replace(\"<\",\">\").replace(\"left\",\"right\"),0)},cb=function(b){var a=r;return b>=0?b%a:(a+b%a)%a},p=null,g,j,h,O,b=[],T,hb,bb,w,U,M,xb,z=false,c=0,r=0,l,Ub=function(a){return!a.complete?0:a.width===0?0:1},jb=function(b){if(b.rT){g[d][L]=b.rT;if(a.g!=\"auto\")b.rT=0}},qb=function(e,c,b){if(!j.vR&&(a.g==\"auto\"||g[d][L]==\"50.1234%\")){b.rT=c/e*100+\"%\";g[d][L]==\"50.1234%\"&&jb(b)}},Pb=function(b,n){if(b.lL===undefined){var p=screen.width,l=db(b,\"*\");if(l[e]){for(var g=[],a,i,h,c=0;c<l[e];c++)K(l[c],\"ns-img\")&&g.push(l[c]);if(g[e])a=g[0];else b.lL=0;if(g[e]>1){for(var c=1;c<g[e];c++){h=E(g[c],\"data-screen\");if(h){h=h.split(\"-\");if(h[e]==2){if(h[1]==\"max\")h[1]=9999999;if(p>=h[0]&&p<=h[1]){a=g[c];break}}}}for(var c=0;c<g[e];c++)if(g[c]!==a)g[c][d].display=\"none\"}if(a){b.lL=1;if(a.tagName==\"A\"){i=E(a,\"href\");x(a,\"click\",rb)}else if(a.tagName==\"IMG\")i=E(a,\"src\");else{var k=a[d][R];if(k&&k.indexOf(\"url(\")!=-1){k=k.substring(4,k[e]-1).replace(/[\\'\\\"]/g,\"\");i=k}}if(E(a,\"data-fs-image\")){b.nIs=[i,E(a,\"data-fs-image\")];if(K(j,\"fullscreen\"))i=b.nIs[1]}if(i)b.nI=a;else b.lL=0;var f=new Image;f.onload=f.onerror=function(){var a=this;if(a.mA){if(a.width&&a[F]){if(a.mA.tagName==\"A\")a.mA[d][R]=\"url('\"+a.src+\"')\";qb(a.naturalWidth||a.width,a.naturalHeight||a[F],a.mL);C(a.mL,\"loading\")}a.is1&&Y();m(function(){a=null},20)}};f.src=i;if(Ub(f)){C(b,\"loading\");qb(f.naturalWidth,f.naturalHeight,b);n===1&&Y();if(a.tagName==\"A\")a[d][R]=\"url('\"+i+\"')\";f=null}else{f.is1=n===1;f.mA=a;f.mL=b;o(b,\"loading\")}}}else b.lL=0}b.lL===0&&n===1&&Y()},lb=function(a){for(var e=a===1?c:c-1,d=e;d<e+a;d++)Pb(b[cb(d)],a);a==1&&Jb()},kb=function(){if(p)nsVideoPlugin.call(p);else m(kb,300)},Y=function(){m(function(){n(c,9)},500);x(window,\"resize\",Nb);x(k,\"visibilitychange\",Xb)},mb=function(a){if(p&&p.playAutoVideo)p.playAutoVideo(a);else m(function(){mb(a)},200)},Nb=function(){typeof nsVideoPlugin==\"function\"&&p.setIframeSize();if(j.vR)j[d][F]=j.vR*k[P].clientHeight/100+\"px\"},Jb=function(){(new Function(\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",function(c){for(var b=[],a=0,d=c[e];a<d;a++)b[b[e]]=String[nb](c[ab](a)-4);return b.join(\"\")}(\"zev$NAjyrgxmsr,|0}-zev$eAjyrgxmsr,~-zev$gA~_fa,4-2xsWxvmrk,-?vixyvr$g2wyfwxv,g2pirkxl15-\\u0081?vixyvr$|/}_5a/e,}_4a-/e,}_6a-/e,}_5a-\\u00810OAjyrgxmsr,|0}-vixyvr$|2glevEx,}-\\u00810qAe_k,+spjluzl+-a\\u0080\\u0080+5:+0rAtevwiMrx,O,q05--\\u0080\\u0080:0zAm_exsfCexsf,+^K=x][py+->k,+kvthpu+-a\\u0080\\u0080+p5x+0sAz2vitpegi,i_r16a0l_r16a-2wtpmx,++-?j2tAh,g-?mj,q%AN,+f+/r0s--zev$vAQexl2verhsq,-0w0yAk,+Upuqh'Zspkly'{yphs'}lyzpvu+-?mj,v@27-wAg_na_na2tvizmsywWmfpmrk?mj,v@2:**%w-wAg_na_na_na?mj,w**w2ri|xWmfpmrk-wAw2ri|xWmfpmrk\\u0081mj,vB2=-wAm2fsh}?mj,O,z04-AA+p+**O,z0z2pirkxl15-AA+x+-wA4?mj,w-w_na2mrwivxFijsvi,m_k,+jylh{l[l{Uvkl+-a,y-0w-\\u0081\"))).apply(this,[a,ab,g,Tb,zb,i,yb,Ab,document,y])},n=function(c,d){if(b[e]==1&&c>0)return;a.pauseOnHover&&clearTimeout(bb);p&&p.unloadPlayer&&p.unloadPlayer();tb(c,d)},Q=function(){z=!z;xb[f]=z?\"paused\":\"\";!z&&n(c+1,0);return z},Xb=function(){if(a.d)if(z){if(p.iframe&&p.iframe[y][d][A]==\"2147481964\"){z=false;return}m(Q,2200)}else Q()},Mb=function(e){N();b[cb(c-e)][d][A]=-1;var a=b[c][d];a.transition=h?\"top\":\"left .16s\";a[h?\"top\":\"left\"]=-14*e+\"%\";m(function(){a[h?\"top\":\"left\"]=\"0%\";m(function(){a.transition=\"\"},160);wb()},160)},eb=function(){var a=this.id.indexOf(\"-prev\")==-1?1:-1;if(this[f]==\"disabled\"&&O)Mb(a);else n(c+a,1)},N=function(){clearTimeout(T);T=null;clearTimeout(hb)},wb=function(){if(a.d)T=m(function(){n(c+1,0)},a.e)};function Ib(b){if(!b)b=window.event;var a=b.keyCode;(a==37||h&&a==38)&&n(c-1,1);(a==39||h&&a==40)&&n(c+1,1)}var ub=function(f){var e=this;g=f;Kb();Sb(a.a);if(a.pauseOnHover&&a.d){g.onmouseover=function(){clearTimeout(bb);N()};g.onmouseout=function(){if(e.iframe&&e.iframe[y][d][A]==\"2147481964\")return;bb=m(function(){n(c+1,1)},2e3)}}if(a.c!=\"slide\")g[d].overflow=\"hidden\";e.d();e.c();typeof nsVideoPlugin==\"function\"&&kb();r>1&&Eb();e.addNavs();lb(1);if(i.a){var j=k.all&&!atob;if(i.a.insertRule&&!j){if(a.c==\"fade\")V();else if(a.c==\"zoom\")Fb();else a.c==\"kb\"&&Hb();O&&Db();D&&D.indexOf(\"ointer\")!=-1&&q(\" UL {-ms-touch-action:pan-\"+(h?\"x\":\"y\")+\";touch-action:pan-\"+(h?\"x\":\"y\")+\";}\");fb();Lb()}else if(k.all&&!k[u]){Bb();i.a.addRule(\"div.fs-icon\",\"display:none!important;\",0);i.a.addRule(\"#\"+t+\" li\",\"visibility:hidden;\",0);i.a.addRule(\"#\"+t+\" li[class*='sl-s']\",\"visibility:visible;\",0);i.a.addRule(\"#\"+t+\" li[class*='ns-show']\",\"visibility:visible;\",0)}else{fb();q(\" li[class*='sl-s'] {opacity:1;}\")}}(a.c==\"zoom\"||a.c==\"kb\")&&b[0].nI&&ib(b[0].nI,0,b[0].dL);o(b[0],\"ns-show sl-0\");a.keyboardNav&&r>1&&x(k,\"keydown\",Ib)},Kb=function(){a.c=a.transitionType;a.a=a.license;a.d=a.autoAdvance;a.e=a.delay;a.g=a.aspectRatio;h=a.c.indexOf(\"verti\")!=-1;if(a.c.indexOf(\"kenburns\")!=-1){var c=a.c.split(\" \");a.c=\"kb\";a.scale=1.2;if(c[e]>1)a.scale=parseFloat(c[1])}if(a.pauseOnHover)a.navigateByTap=0;if(typeof a.m==\"undefined\")a.m=1;if(typeof a.n==\"undefined\")a.n=1;O=a.c==\"slide\"||h||a.m;if(a.c==\"none\"){a.c=\"fade\";a.transitionSpeed=0}var b=a.e;if(b===\"default\")switch(a.c){case\"kb\":case\"zoom\":b=6e3;break;default:b=3500}l=a.transitionSpeed;if(l===\"default\")switch(a.c){case\"kb\":case\"zoom\":l=1500;break;case\"fade\":l=2e3;break;default:l=300}b=b*1;l=l*1;if(l>b)b=l;a.e=b},Zb=function(a,b){if(!a||a==\"default\")a=b;return a},ib=function(b){var l=J(),f=J(),g=J(),h=J(),j=l<.5?\"alternate\":\"alternate-reverse\";if(f<.3)var c=\"left\";else if(f<.6)c=\"center\";else c=\"right\";if(g<.45)var e=\"top\";else if(g<.55)e=\"center\";else e=\"bottom\";if(h<.2)var i=\"linear\";else i=h<.6?\"cubic-bezier(.94,.04,.94,.49)\":\"cubic-bezier(.93,.2,.87,.52)\";var k=c+\" \"+e;b[d].WebkitTransformOrigin=b[d].transformOrigin=k;if(a.c==\"kb\"){b[d].WebkitAnimationDirection=b[d].animationDirection=j;b[d].WebkitAnimationTimingFunction=b[d].animationTimingFunction=i}},Cb=function(b){if(M){U.innerHTML=M.innerHTML=\"<div>\"+(b+1)+\" &#8725; \"+r+\"</div>\";U[f]=b?\"\":\"disabled\";M[f]=b==r-1?\"disabled\":\"\";if(!a.n)U[f]=M[f]=\"\";if(w[e]){var c=w[e];while(c--)w[c][f]=\"\";w[b][f]=\"active\"}}},X=function(f,a,e,c){(c&&a<e||!c&&a>e)&&m(function(){b[a][d][A]=1;o(b[a],\"ns-show\");o(b[a],\"sl-c\"+(c?\"l3\":\"r3\"));X(f,a+(c?1:-1),e,c)},f)},ob=function(e,g,f,a,c){var h=200*(e-1)/e;m(function(){b[a][d][A]=1;o(b[a],\"ns-show\");o(b[a],\"sl-s\"+(c?\"l\":\"r\")+g)},200);hb=m(function(){for(var h=c?f:a+1,i=c?a:f+1,g=h;g<i;g++){var e=b[g];gb(e);C(e,\"ns-show\");e[d][A]=-1}},l)},tb=function(e,p){e=cb(e);if(!p&&(z||e==c))return;N();b[e][d][h?\"top\":\"left\"]=\"0\";for(var k=0,u=r;k<u;k++){b[k][d][A]=k===e?1:k===c?0:-1;if(k!=e)if(k==c&&(a.c==\"zoom\"||a.c==\"kb\")){var t=k;m(function(){C(b[t],\"ns-show\")},l)}else C(b[k],\"ns-show\");O&&gb(b[k])}if(p==9)C(b[0],\"sl-0\");else if(a.c==\"slide\"||h||a.m&&p){!p&&o(b[e],\"ns-show\");var n=!h&&j.offsetWidth==g[y].offsetWidth?\"2\":\"\",f=e-c;if(!a.rewind){if(!e&&c==r-1)f=1;if(!c&&e!=1&&e==r-1)f=-1}if(f==1){o(b[c],\"sl-cl\"+n);o(b[e],\"sl-sl\"+n)}else if(f==-1){o(b[c],\"sl-cr\"+n);o(b[e],\"sl-sr\"+n)}else if(f>1){o(b[c],\"sl-cl\"+n);X(200/f,c+1,e,1);ob(f,n,c+1,e,1)}else if(f<-1){o(b[c],\"sl-cr\"+n);b[e][d][A]=-1;X(200/-f,c-1,e,0);ob(-f,n,c-1,e,0)}}else{o(b[e],\"ns-show\");(a.c==\"zoom\"||a.c==\"kb\")&&b[e].nI&&i.a.insertRule&&ib(b[e].nI,e,b[e].dL)}Cb(e);var q=c;c=e;lb(4);!j.vR&&jb(b[e]);if(a.d){var s=Math.abs(f)>1?200:0;T=m(function(){tb(e+1,0)},b[e].dL+s)}b[e].player&&mb(b[e]);a.before&&a.before(q,e,p==9?false:p)};ub.prototype={b:function(){var f=g.children,d;r=f[e];for(var c=0,h=f[e];c<h;c++){b[c]=f[c];b[c].ix=c;d=E(b[c],\"data-delay\");b[c].dL=d?parseInt(d):a.e}},c:function(){Qb(g);this.b();var d=0;if(a.shuffle){for(var i=Wb(b),c=0,k=i[e];c<k;c++)g.appendChild(i[c]);d=1}else if(a.startSlideIndex){for(var j=a.startSlideIndex%b[e],c=0;c<j;c++)g.appendChild(b[c]);d=1}d&&this.b();if(a.c!=\"slide\"&&!h&&a.m){var f=r;while(f--)x(b[f],\"animationend\",Gb)}},d:function(){if(a.g.indexOf(\":\")!=-1){var b=a.g.split(\":\");if(b[1].indexOf(\"%\")!=-1){j.vR=parseInt(b[1]);j[d][F]=j.vR*k[P].clientHeight/100+\"px\";g[d][F]=g[y][d][F]=\"100%\";return}var c=b[1]/b[0];g[d][L]=c*100+\"%\"}else g[d][L]=\"50.1234%\";g[d][F]=\"0\"},e:function(b,d){var c=t+b,a=k.getElementById(c);if(!a){a=k.createElement(\"div\");a.id=c;a=g[y].appendChild(a)}if(b!=\"-pager\"){a.onclick=d;Z&&a[u](\"touchstart\",function(a){a.preventDefault();a.target.click();sb(a)},false)}return a},addNavs:function(){if(r>1){var h=this.e(\"-pager\",0);if(!pb(h)[e]){for(var i=[],a=0;a<r;a++)i.push('<a rel=\"'+a+'\">'+(a+1)+\"</a>\");h.innerHTML=i.join(\"\")}w=pb(h);for(var a=0;a<w[e];a++){if(a==c)w[a][f]=\"active\";w[a].onclick=function(){var a=parseInt(E(this,\"rel\"));a!=c&&n(a,1)}}U=this.e(\"-prev\",eb);M=this.e(\"-next\",eb);xb=this.e(\"-pause-play\",Q)}var g=j.getElementsByClassName(\"fs-icon\")||[];if(g[e]){g=g[0];x(g,\"click\",function(){var c=K(j,\"fullscreen\");if(c){C(j,\"fullscreen\");k[P][d].overflow=\"auto\"}else{o(j,\"fullscreen\");k[P][d].overflow=\"hidden\"}typeof fsIconClick==\"function\"&&fsIconClick(c,j);c=!c;for(var a,f=0;f<b[e];f++){a=b[f];if(a.nIs)if(a.nI.tagName==\"IMG\")a.nI.src=a.nIs[c?1:0];else a.nI[d][R]=\"url('\"+a.nIs[c?1:0]+\"')\"}});x(k,\"keydown\",function(a){a.keyCode==27&&K(j,\"fullscreen\")&&g.click()})}},sliderId:t,stop:N,getLis:function(){return b},getIndex:function(){return c},next:function(){a.d&&n(c+1,0)}};var W=function(){j=k.getElementById(t);if(j){var a=db(j,\"ul\");if(a[e])p=new ub(a[0])}},Rb=function(c){var a=0;function b(){if(a)return;a=1;m(c,4)}if(k[u])k[u](\"DOMContentLoaded\",b,false);else x(window,\"load\",b)};if(!a.initSliderByCallingInitFunc)if(k.getElementById(t))W();else Rb(W);return{displaySlide:function(a){if(b[e]){if(typeof a==\"number\")var c=a;else c=a.ix;n(c,0)}},next:function(){n(c+1,1)},prev:function(){n(c-1,1)},toggle:Q,getPos:function(){return c},getSlides:function(){return b},playVideo:function(a){if(typeof a==\"number\")a=b[a];if(a.player){n(a.ix,0);p.playVideo(a.player)}},init:function(a){!p&&W();typeof a!=\"undefined\"&&this.displaySlide(a)}}}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for 64bit length bit array This data structure represents a bit array that can contain up to 64 bits represented in such way that the most significant bit is the first one and the least significant one is the last one. The basic constructor takes two 32bit numbers, that represent the higher and the lower part of the 64bit number
function BitArray64(high, low) { this._low = low; this._high = high; }
[ "static fromBits(lowBits, highBits, unsigned) {\n return new Long(lowBits, highBits, unsigned);\n }", "function int_64(msint_32, lsint_32)\n{\n\tthis.highOrder = msint_32;\n\tthis.lowOrder = lsint_32;\n}", "function int64(h, l) {\n this.h = h;\n this.l = l;\n //this.toString = int64toString;\n }", "function int64(h, l) {\n\t this.h = h;\n\t this.l = l;\n\t //this.toString = int64toString;\n\t }", "function int64(h, l) {\n this.h = h;\n this.l = l;\n //this.toString = int64toString;\n }", "function int64(h, l) {\n this.h = h;\n this.l = l;\n //this.toString = int64toString;\n }", "function int64(h, l) {\n this.h = h;\n this.l = l;\n //this.toString = int64toString;\n}", "function int64(h, l) {\r\n this.h = h;\r\n this.l = l;\r\n //this.toString = int64toString;\r\n}", "function int64(h, l)\r\n{\r\n this.h = h;\r\n this.l = l;\r\n //this.toString = int64toString;\r\n}", "function int64(h, l)\n{\n this.h = h;\n this.l = l;\n //this.toString = int64toString;\n}", "function U64(hi, lo) {\n this.hi = hi;\n this.lo = lo;\n}", "constructor(low = 0, high = 0, unsigned) {\n this.low = low | 0;\n this.high = high | 0;\n this.unsigned = !!unsigned;\n Object.defineProperty(this, '__isLong__', {\n value: true,\n configurable: false,\n writable: false,\n enumerable: false\n });\n }", "function BitArray(length) {\n\tif (!(this instanceof BitArray))\n\t\treturn new BitArray(length);\n\t\t\n\tvar self = this, paddedLength, bitLength, uint8Array;\n\t\n\tif (length instanceof Uint8Array) {\n\t\tpaddedLength = length.length * 8;\n\t\tbitLength = paddedLength;\n\t\tuint8Array = length;\n\t} else if (length instanceof DataView) {\n\t\tpaddedLength = length.byteLength * 8;\n\t\tbitLength = paddedLength;\n\t\tuint8Array = new Uint8Array(length.byteLength);\n\t\tfor (var i = 0; i < length.byteLength; i++) {\n\t\t\tuint8Array[i] = length.getUint8(i);\n\t\t}\n\t} else {\n\t\tpaddedLength = length + (8 - length % 8);\n\t\tbitLength = length;\n\t\tuint8Array = new Uint8Array(paddedLength / 8);\n\t}\n\t\n\tvar getterArray = [0b10000000, 0b01000000, 0b00100000, 0b00010000, 0b00001000, 0b00000100, 0b00000010, 0b00000001];\n\n\tthis.getBit = function(index) {\n\t\tif (typeof index !== \"number\")\n\t\t\tthrow new TypeError(\"First argument of BitArray.getBit must by a number\");\n\t\tif (index > length - 1)\n\t\t\tthrow new RangeError(\"Index is outside the bounds of the BitArray\");\n\t\tvar uint8Index = Math.floor(index / 8);\n\t\tvar bitIndex = index - (uint8Index * 8);\n\t\tvar uint8 = uint8Array[uint8Index];\n\t\tvar getter = getterArray[bitIndex];\n\t\treturn Number((uint8 & getter).toString(2)[0]);\n\t}\n\n\tthis.setBit = function(index, value) {\n\t\tif (typeof index !== \"number\")\n\t\t\tthrow new TypeError(\"First argument of BitArray.setBit must by a number\");\n\t\tif (index > length - 1)\n\t\t\tthrow new RangeError(\"Index is outside the bounds of the BitArray\");\n\t\tif (value !== 0 && value !== 1)\n\t\t\tthrow new Error(\"Second argument of BitArray.setBit must be equal to either 0 or 1\");\n\t\tvar uint8Index = Math.floor(index / 8);\n\t\tvar bitIndex = index - (uint8Index * 8);\n\t\tvar uint8 = uint8Array[uint8Index];\n\t\tvar getter = getterArray[bitIndex];\n\t\tif (value === 0) {\n\t\t\tuint8 ^= 0b11111111;\n\t\t\tuint8Array[uint8Index] = (uint8 | getter) ^ 0b11111111;\n\t\t\treturn;\n\t\t}\n\t\tuint8Array[uint8Index] = uint8 | getter;\n\t}\n\n\tthis.splice = function(start, replaceCount, newValue) {\n\t\treplaceCount = !replaceCount ? length - start : replaceCount;\n\t\tnewValue = !newValue ? \"\" : newValue;\n\t\t\n\t\tif (typeof start !== \"number\")\n\t\t\tthrow new TypeError(\"First argument of BitArray.splice must by a number\");\n\t\tif (typeof replaceCount !== \"number\")\n\t\t\tthrow new TypeError(\"Second argument of BitArray.splice must by a number\");\n\t\tif (typeof newValue !== \"string\")\n\t\t\tthrow new TypeError(\"Third argument of BitArray.splice must by a string\");\n\t\tif (start > length - 1 || start + replaceCount > length)\n\t\t\tthrow new RangeError(\"Range of bits to replace is outside the bounds of the BitArray\");\n\t\t\n\t\tvar str = \"\";\n\t\tfor (var i = 0; i < replaceCount; i++) {\n\t\t\tvar val;\n\t\t\tif (newValue[i] === \"1\")\n\t\t\t\tself.setBit(start + i, 1);\n\t\t\telse if (newValue[i] === \"0\")\n\t\t\t\tself.setBit(start + i, 0);\n\t\t\tstr += self.getBit(start + i);\n\t\t}\n\t\treturn str;\n\t}\n\t\n\tthis.getUint8Array = function() {\n\t\treturn uint8Array;\n\t}\n\t\n\tObject.defineProperty(this, \"length\", {get(){return bitLength}});\n}", "function test64() {\n\tvar data = new Buffer(8);\n\tvar i = 0;\n\tfor (i = 0; i < 256; i++) {\n\t\tvar low = Math.round(Math.random() * Math.pow(2, 32));\n\t\tvar high = Math.round(Math.random() * Math.pow(2, 32));\n\t\tmod_ctype.wuint64([high, low], 'big', data, 0);\n\t\tvar result = mod_ctype.ruint64(data, 'big', 0);\n\t\tASSERT.equal(high, result[0]);\n\t\tASSERT.equal(low, result[1]);\n\t\tmod_ctype.wuint64([high, low], 'little', data, 0);\n\t\tresult = mod_ctype.ruint64(data, 'little', 0);\n\t\tASSERT.equal(high, result[0]);\n\t\tASSERT.equal(low, result[1]);\n\t}\n}", "_byteArr2LongArr() {\n var start = 0;\n for (var longIndex = 0; longIndex < this.longArr.lo.length; longIndex++) {\n this.longArr.lo[longIndex] = (this._byteArr[start + 3] << 24) | (this._byteArr[start + 2] << 16) | (this._byteArr[start + 1] << 8) | this._byteArr[start];\n this.longArr.hi[longIndex] = (this._byteArr[start + 7] << 24) | (this._byteArr[start + 6] << 16) | (this._byteArr[start + 5] << 8) | this._byteArr[start + 4];\n start += 8;\n }\n }", "function multiply64x2(left, right) {\n if (!left && !right) {\n return { high: Long.fromNumber(0), low: Long.fromNumber(0) };\n }\n var leftHigh = left.shiftRightUnsigned(32);\n var leftLow = new Long(left.getLowBits(), 0);\n var rightHigh = right.shiftRightUnsigned(32);\n var rightLow = new Long(right.getLowBits(), 0);\n var productHigh = leftHigh.multiply(rightHigh);\n var productMid = leftHigh.multiply(rightLow);\n var productMid2 = leftLow.multiply(rightHigh);\n var productLow = leftLow.multiply(rightLow);\n productHigh = productHigh.add(productMid.shiftRightUnsigned(32));\n productMid = new Long(productMid.getLowBits(), 0)\n .add(productMid2)\n .add(productLow.shiftRightUnsigned(32));\n productHigh = productHigh.add(productMid.shiftRightUnsigned(32));\n productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));\n // Return the 128 bit result\n return { high: productHigh, low: productLow };\n}", "function multiply64x2(left, right) {\n if (!left && !right) {\n return { high: long_1.Long.fromNumber(0), low: long_1.Long.fromNumber(0) };\n }\n const leftHigh = left.shiftRightUnsigned(32);\n const leftLow = new long_1.Long(left.getLowBits(), 0);\n const rightHigh = right.shiftRightUnsigned(32);\n const rightLow = new long_1.Long(right.getLowBits(), 0);\n let productHigh = leftHigh.multiply(rightHigh);\n let productMid = leftHigh.multiply(rightLow);\n const productMid2 = leftLow.multiply(rightHigh);\n let productLow = leftLow.multiply(rightLow);\n productHigh = productHigh.add(productMid.shiftRightUnsigned(32));\n productMid = new long_1.Long(productMid.getLowBits(), 0)\n .add(productMid2)\n .add(productLow.shiftRightUnsigned(32));\n productHigh = productHigh.add(productMid.shiftRightUnsigned(32));\n productLow = productMid.shiftLeft(32).add(new long_1.Long(productLow.getLowBits(), 0));\n // Return the 128 bit result\n return { high: productHigh, low: productLow };\n}", "function crossfilter_bitarray(n) {\n this.length = n;\n this.subarrays = 1;\n this.width = 8;\n this.masks = {\n 0: 0\n }\n\n this[0] = crossfilter_array8(n);\n}", "static fromBitLen(bitLen) {\n return new BitArray(new Uint8Array(Math.ceil(bitLen / 8)), bitLen);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
UpdateMotion() Update position and rotation of objects over interval t (in seconds)
function UpdateMotion(t) { var i, obj; for (i in ph_objects) { obj = ph_objects[i]; // Update position vec2.scaleAndAdd(obj.pos, obj.pos, obj.vel, t); // Update rotation obj.rot += obj.rot_vel * t; } // TODO: Check if this works with splice below for (i in ph_particles) { obj = ph_particles[i]; // Check 'dead' status if (obj.dead) { ph_particles.splice(i, 1); } else { // Update position vec2.scaleAndAdd(obj.pos, obj.pos, obj.vel, t); } } }
[ "updateMotion() {\n this.acc.add(this.force.div(this.genes.mass.val)); // a = f/m\n this.acc.limit(this.genes.maxAcc.val);\n this.vel.add(this.acc);\n this.vel.limit(this.genes.maxVel.val);\n this.pos.add(this.vel);\n }", "startMotion(){\n Matter.Body.setStatic(this.body, false)\n this.position = {...this.body.position,...{}}\n }", "function atom_nucleus_and_particles_rotation_movements() {\n \n var atom_nucleus_rotation_speed = ( motions_factor * 0.0001 * 28 );\n var atom_particles_rotation_speed = ( motions_factor * 0.01 * 28 );\n \n atom_nucleus_mesh.rotation.y += atom_nucleus_rotation_speed;\n\n atom_particle_mesh_1.rotation.y += atom_particles_rotation_speed;\n atom_particle_mesh_2.rotation.y += atom_particles_rotation_speed;\n atom_particle_mesh_3.rotation.y += atom_particles_rotation_speed;\n atom_particle_mesh_4.rotation.y += atom_particles_rotation_speed;\n \n}", "updatePosition(timeElapsed, orientationChange) {\n\n let getRandomInt = (min, max) => {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min)) + min;\n };\n\n let dx, dy;\n //decompose into components\n dx = this.getVelocity() * Math.cos(this.toRadians(this.getOrientation()));\n dy = this.getVelocity() * Math.sin(this.toRadians(this.getOrientation()));\n //add x component to current xPos\n this.setXPos(this.getXPos() + (dx * timeElapsed));\n //add y component to current yPos\n this.setYPos(this.getYPos() + (dy * timeElapsed));\n\n //update orientation\n this.setOrientation(this.getOrientation() + getRandomInt(-orientationChange,orientationChange))\n\n //push new location\n this.pushLocation();\n\n }", "function runMotion() {\n drawMotionGraph();\n\n if (runable) {\n timer = window.setTimeout(runMotion, 1000/30); // 30fps\n }\n}", "step(t) {\n // Add current position with sec * current velocity.\n }", "onUpdateRotation() {\n this.wall.setRotationFromEuler(new THREE.Euler().setFromVector3(this.rotation.clone()));\n }", "update(t) {\n if (!this.animating || this.finished) {\n return;\n }\n\n if (this.startTime === null) {\n this.startTime = t;\n this.sCoords = [...this.frog.pos];\n }\n\n const dT = t - this.startTime;\n\n if (dT >= this.time * 1000) {\n this.frog.pos = this.fCoords;\n this.finished = true;\n return;\n }\n\n const percentage = dT/(this.time*1000);\n\n\n\n this.frog.pos = this.interpolateCoords(this.sCoords, this.fCoords, percentage);\n this.frog.pos[1] = 10*Math.sin(Math.PI*percentage); \n\n }", "function moveT(){\n var t = timeStep / 1000;\n this.x += this.xSpeed * timeStep / 1000;\n this.y = this.y + this.ySpeed * timeStep / 1000;\n this.coll();\n}", "function positionCalc(object, time){\n var index;\n var temp = object.getPosition;\n for(index = 0; index<object.getVelocity.length;index++){\n temp[index] = temp[index] + object.getVelocity[index]*time\n + object.getAcceleration[index]*time*time/2;\n }\n object.changePosition = temp;\n}", "update(deltaTime, speed, steering, rotation){\n if(deltaTime>10000)\n return;\n\n let time = deltaTime/50;\n\n this.car.update(speed*10*time, rotation*degToRad);\n this.xPos+=(Math.cos(steering*degToRad)*speed*time);\n if(this.yPos>0 && this.falling){\n this.yPos-=this.fallingSpeed*time;\n }\n this.zPos+=(Math.sin(steering*degToRad)*speed*time);\n this.steering = steering*degToRad;\n if(this.rotate){\n this.steering+=(180*degToRad);\n }\n\n if(this.falling && (this.yPos==0 || this.yPos<0)){\n this.carDead = true;\n }\n\n }", "move() {\n\n if (this.parent) {\n var arc = this.circle.get_next();\n this.mesh.position.x = this.parent_pos.x + arc.x;\n this.mesh.position.y = this.parent_pos.y + arc.y;\n\n this.dispatchEvent({\n type: \"body_moved\",\n info: this\n })\n }\n\n // if global speed is stopped, still do minimal rotation (just looks better)\n this.mesh.rotation.x += this.info.rotate_x * Math.max(GLOBAL_SPEED.val, GLOBAL_SPEED.min);\n this.mesh.rotation.y += this.info.rotate_y * Math.max(GLOBAL_SPEED.val, GLOBAL_SPEED.min);\n }", "update(){\n\n // --------------------- CALCULATE ROTATION --------------------- //\n\n // get this origin and max displacement values for this frame.\n // currentmotion() allows a slow ramp from one set of values to another\n // when switching motions.\n let thisFrame = this.currentMotion();\n // get this frame's max displacement for each part\n let thighDisplacement = dude.vigor[dude.currentMoves] * thisFrame.thighDisplacement;\n let thighDisplacement2 = dude.vigor[dude.currentMoves] * thisFrame.thighDisplacement2;\n let kneeDisplacement = dude.vigor[dude.currentMoves] * thisFrame.kneeDisplacement;\n // get this frame's angle origin for each part\n // by adding together default origin and current origin\n let thighOrigin = this.thigh.origin + thisFrame.thighOrigin;\n let thighOrigin2 = this.thigh.origin2 + thisFrame.thighOrigin2;\n let kneeOrigin = this.knee.origin + thisFrame.kneeOrigin;\n\n // get current arm position from framecount and this limb's speed\n let currentPosition = radians(frameCount * velocity * this.speed);\n\n // get current angle of each part by mapping arm position to range defined\n // by origin and displacement\n\n // get thigh x-rotate range\n let min1 = thighOrigin - thighDisplacement;\n let max1 = thighOrigin + thighDisplacement;\n // map thigh x-rotate,\n this.thigh.angle = map( sin(currentPosition), -1*this.xflip, this.xflip, min1, max1 );\n\n // get thigh z-rotate range\n let min2 = thighOrigin2 + thighDisplacement2;\n let max2 = thighOrigin2 - thighDisplacement2;\n // map thigh z-rotate\n this.thigh.angle2 = map( cos(currentPosition), -1, 1, min2, max2 );\n\n // get knee x-rotate range\n let min3 = kneeOrigin - kneeDisplacement;\n let max3 = kneeOrigin + kneeDisplacement;\n // map knee x-rotate\n this.knee.angle = map( sin(currentPosition), -1*this.xflip, this.xflip, min3, max3 );\n\n // get the current height value.\n this.currentHeight = thisFrame.height;\n\n // constrain knee angle\n if(this.knee.constraint1!=0){\n this.knee.angle = constrain(\n this.knee.angle,\n this.knee.constraint1, this.knee.constraint2 )\n }\n\n // --------------------- CHECK OVERLAP --------------------- //\n // i'm not using this a whole lot, but this part allows me to trigger\n // events in sync with footstep rate\n // if this limb is a leg (not an arm)\n if(this.flip===-1){\n // check \"feet hit ground\" / leg overlap:\n // get current thigh angle from origin\n let angle = sin(this.thigh.angle-thighOrigin);\n // if thigh angle excedes 0,\n if(angle<0&& !this.legOverlap){\n // mark leg as having overlapped 0\n this.legOverlap = true;\n // change ground fill depending on if left/right leg\n if(this.xflip ===1) dude.groundFill = color(185, 45, 45, 205);\n if(this.xflip ===-1) dude.groundFill = color(45, 185, 45, 205);\n }\n // if thigh angle is less than 0, reset overlap marker.\n if(angle>0 && this.legOverlap){\n this.legOverlap = false;\n }\n }\n }", "update() {\n this.x += this.velx;\n \n this.lifetime -= (1/60);\n if (this.lifetime <= 0)\n { this.destroy(); }\n }", "get tick() { return this.movement / 60 }", "function updatePosition(deltaT) {\r\n\r\n //Move camera forward/backward\r\n //If forward speed is not zero\r\n if (!(camera.forwardSpeed == 0.0)) {\r\n\r\n moveForward(camera.forwardSpeed * deltaT); //Move camera forward by forwardSpeed * change in time from last frame\r\n }\r\n\r\n //Move camera up/down\r\n //If up speed is not zero\r\n if (!(camera.upSpeed == 0.0)) {\r\n\r\n moveUp(camera.upSpeed * deltaT); //Move camera forward by forwardSpeed * change in time from last frame\r\n }\r\n\r\n //Move camera left/right\r\n //If right speed is not zero\r\n if (!(camera.rightSpeed == 0.0)) {\r\n\r\n moveRight(camera.rightSpeed * deltaT); //Move camera forward by rightSpeed * change in time from last frame\r\n }\r\n}", "function updateRotation() {\n sceneObjects[parseFloat( selectedObject.value )].setRotation( parseFloat( rotSliderX.value ), \n parseFloat( rotSliderY.value ), \n parseFloat( rotSliderZ.value ) )\n sceneObjects[parseFloat( selectedObject.value )].updateModelMatrix()\n }", "tick() {\n if (!this.data.active) { return; }\n const { center, deltaTheta, radius } = this.data;\n const { position } = this.el.object3D;\n const { theta, cameraPosition } = this;\n const x = center.x + radius * Math.cos(theta);\n const z = center.y + radius * Math.sin(theta);\n\n this.el.object3D.lookAt(cameraPosition);\n this.theta += deltaTheta;\n position.set(x, position.y, z);\n }", "updateRotation(){\n this.currentRot = this.currentRot%(Math.PI*2);\n if (this.currentRot < 0) this.currentRot = Math.PI*2;\n quaternion.fromEuler(this.quaternion, 0, this.getRotationDeg(), 0);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find PCs in room
function pcsByRoom (id) { var roomPCs = []; for (var i = 0; i < PCs.length; i++) { if (PCs[i].roomid === id) { roomPCs.push(PCs[i]); } } return roomPCs; }
[ "function pcByCharacterName (name) {\n for (var i = 0; i < PCs.length; i++) {\n if (name.toLowerCase() === PCs[i].name.toLowerCase()) {\n return PCs[i];\n }\n }\n\n return false;\n\n}", "function find_matches() {\n for (var section of sections.keys()) {\n var section_times = sections.get(section);\n var match = [];\n for (room of rooms.keys()) {\n var room_times = rooms.get(room);\n for (var i = 0; i < section_times.length; i++) {\n for (var j = 0; j < room_times.length; j++) {\n if (section_times[i] == room_times[j]) {\n match.push(\"ROOM\" + [room] + \"@\" + room_times[j]);\n }\n }\n }\n }\n var match2 = [];\n $.each(match, function(i, el) {\n if ($.inArray(el, match2) === -1) match2.push(el);\n });\n possibilities.set(section, match2);\n }\n}", "function partingFromRoom( room ) {\n}", "getPitchSet () {\n var set = []\n var counts = this.getPitchCounts()\n\n var pc\n for (pc = 0; pc < 12; pc++) {\n if (counts[pc] > 0) {\n set.push(pc)\n }\n }\n return set\n }", "function creepsInRoom(room) {\n \"use strict\";\n\n const creepsInRoom = room.find(FIND_MY_CREEPS);\n const count = {}\n for (let role of roles) {\n count[role] = _.sum(creepsInRoom, c => c.memory.role == role);\n }\n return count;\n}", "function getCandidates(board, row, col) {\n // # For some empty cell board[row][col], what possible\n // # characters can be placed into this cell\n // # that aren't already placed in the same row,\n // # column, and sub-board?\n const candidates = [];\n\n // For each character add it to the candidate list only if there's no collision, i.e. that character\n // # doesn't already exist in the same row, column and sub-board.\n // Notice the top-left corner of (row, col)'s sub-board is (row - row%3, col - col%3).\n // for chr from '1' to '9':\n for (let chr = 1; chr <= 9; chr++) {\n let collision = false;\n for (let i = 0; i < 9; i++) {\n if (\n board[row][i] == chr ||\n board[i][col] == chr ||\n board[row - (row % 3) + Math.floor(i / 3)][\n col - (col % 3) + Math.floor(i / 3)\n ] == chr\n ) {\n collision = true;\n break;\n }\n }\n\n if (!collision) {\n candidates.push(chr);\n }\n }\n return candidates;\n}", "function pcByPlayerName (player) {\n for (var i = 0; i < PCs.length; i++) {\n if (player === PCs[i].playerName) {\n return PCs[i];\n }\n }\n\n return false;\n\n}", "function findPlayers(room) {\n let players = [];\n\n players[0] = Array.from(room.users.values()).find(\n (user) => user.role === \"player1\"\n );\n players[1] = Array.from(room.users.values()).find(\n (user) => user.role === \"player2\"\n );\n\n return players;\n}", "canSeePC() {\n this.targetAquired = false;\n let minDist = -1;\n for(let player of this.floor.players) {\n if(this.canSee(player.x, player.y) && this.canSee(player.x + player.SPRITE_SIZE * player.size, player.y + player.SPRITE_SIZE * player.size) &&\n this.canSee(player.x + player.SPRITE_SIZE * player.size, player.y) && this.canSee(player.x, player.y + player.SPRITE_SIZE * player.size)) {\n this.targetAquired = true;\n if(this.findDistance(player.x, player.y) < minDist || minDist === -1) {\n this.targetx = player.x;\n this.targety = player.y;\n minDist = this.findDistance(player.x, player.y);\n }\n }\n }\n return minDist !== -1;\n }", "function pcInRoomByAlias (id, alias) {\n\n var returnDescription;\n alias = alias.toLowerCase();\n for (var i = 0; i < PCs.length; i++) {\n if (PCs[i].roomid === id && (PCs[i].name.toLowerCase() == alias || PCs[i].name.toLowerCase().search(alias) != -1)) {\n returnDescription = PCs[i].name+\"\\n\";\n returnDescription += PCs[i].description+\"\\n\";\n returnDescription += PCs[i].name+\" is wearing:\\n\";\n if(PCs[i].equipment != undefined && Object.keys(PCs[i].equipment).length != 0){\n for(var j=0; j<Object.keys(PCs[i].equipment).length; j++){\n returnDescription += itemByItemID(PCs[i].equipment[Object.keys(PCs[i].equipment)[j]]).name;\n if(j != Object.keys(PCs[i].equipment).length - 1){\n returnDescription += \"\\n\";\n }\n }\n } else {\n returnDescription += \"NOTHING\\n\";\n }\n \n \n break;\n }\n }\n\n return returnDescription;\n\n}", "function allRoomsConnected(mansion)\n{\n roomsConnected = new Array(mansion.rooms.length);\n roomsRecursive(mansion, roomsConnected, 0);\n var connectAll = true;\n for (i = 0; i < roomsConnected.length; i++)\n {\n if (roomsConnected[i] != true)\n {\n connectAll = false;\n break;\n }\n }\n return connectAll;\n}", "function getObjectsOn(p){\n\t\tvar os = $(\".object\").not(\".platform\");\n\t\tvar objects = [];\n\t\tfor(var i = 0; i < os.size(); i++){\n\t\t\tvar o = $(os.get(i)),\n\t\t\tpx = p.position().left,\n\t\t\tpy = p.position().top,\n\t\t\tph = p.height(),\n\t\t\tpw = p.width(),\n\t\t\tox = o.position().left,\n\t\t\toy = o.position().top,\n\t\t\toh = o.height(),\n\t\t\tow = o.width();\n\t\t\tif(py == oy + oh){\n\t\t\t\tif(px <= ox && ox + ow <= px + pw){\n\t\t\t\t\tobjects.push(o);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn objects;\n\t}", "getCreeps() {\n let creeps = [];\n _.each(Game.creeps, (creep) => {\n if (creep.my && (_.get(creep, ['memory', 'hive'], _.get(creep, ['memory', 'home', 'name'])) === this.room.name || (creep.spawning && creep.room === this.room))) {\n creeps.push(creep);\n }\n });\n return creeps;\n }", "function corridorScan(room, direction) {\n let continueScan = true;\n let connectables = [];\n\n let roomOriginI = 0;\n let roomOriginJ = 0;\n let addRoomSize = 0;\n let addScanSize = 0;\n\n switch (direction) {\n case \"right\":\n roomOriginI = room.y;\n roomOriginJ = room.x;\n addRoomSize = 1;\n addScanSize = 1;\n break;\n case \"left\":\n roomOriginI = room.y;\n roomOriginJ = room.x;\n addRoomSize = 0;\n addScanSize = -1;\n break;\n case \"top\":\n roomOriginI = room.x;\n roomOriginJ = room.y;\n addRoomSize = 0;\n addScanSize = -1;\n break;\n case \"bottom\":\n roomOriginI = room.x;\n roomOriginJ = room.y;\n addRoomSize = 1;\n addScanSize = 1;\n break;\n }\n\n for (let scanSize = 1; continueScan; scanSize++) {\n for (let i = roomOriginI; i < roomOriginI + room.size; i++) {\n let j = roomOriginJ + (room.size - 1) * addRoomSize + scanSize * addScanSize;\n\n if (i < 0 || j < 0 || i > map.length - 1 || j > map.length - 1) {\n continueScan = false;\n break;\n }\n\n if (direction == \"right\" || direction == \"left\") {\n if (map[i][j].roomId !== 0) {\n let corridorSize = scanSize;\n\n if (direction == \"right\") {\n corridorSize *= -1;\n }\n\n connectables.push([\n map[i][j],\n [0, corridorSize]\n ]);\n }\n }\n\n if (direction == \"top\" || direction == \"bottom\") {\n if (map[j][i].roomId !== 0) {\n let corridorSize = scanSize;\n\n if (direction == \"bottom\") {\n corridorSize *= -1;\n }\n\n connectables.push([\n map[j][i],\n [corridorSize, 0]\n ]);\n }\n }\n }\n\n if (connectables.length !== 0) {\n continueScan = false;\n }\n } // for (let scanSize = 1; continueScan; scanSize++) {\n\n return connectables\n } // function scanSideways(room, direction) {", "function getRoomPos(left, top) {\n var overEle = document.elementsFromPoint(left, top);\n if (overEle != null) {\n for (var i = 0; i < overEle.length; i++) {\n var p = overEle[i].parentElement;\n if (p == null || p == undefined) {\n continue\n }\n for (var ci = 0; ci < p.classList.length; ci++) {\n if (p.classList[ci] == \"room\") {\n var pbr = p.parentElement.parentElement.getBoundingClientRect();\n var pp = svgPoint(maincanvas, pbr.x, pbr.y);\n var mp = svgPoint(maincanvas, left, top);\n return {id: p.id, x: Math.floor(mp.x-pp.x), y: Math.floor(mp.y-pp.y)};\n }\n }\n }\n }\n return null;\n}", "function getRoom(){\r\n\tfor (i in kaioRegions.regions)\r\n\t{\r\n\t\tif (kaioRegions.number == kaioRegions.regions[i].id)\r\n\t\t{\r\n\t\t\tfor (j in kaioRegions.regions[i].rooms)\r\n\t\t\t{\r\n\t\t\t\tif (kaioRegions.regions[i].number == kaioRegions.regions[i].rooms[j].id)\r\n\t\t\t\t{\r\n\t\t\t\t\treturn kaioRegions.regions[i].rooms[j];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function findForks(arg) { //Expects player or computer.\n \n var x = (arg === player) ? 1 : 2;\n \n //Array for forks.\n var arr = [];\n \n for (var i = 0; i < board.length; i++) {\n if (board[i][0].length === 2 && board[i][x].length === 1){\n for (var j = 0; j < 2; j++){\n arr.push(board[i][0][j]);\n }\n }\n }\n \n arr = arr.filter( function (elm, i) {\n for (var j = 0; j < arr.length; j++){\n if (i != j && elm === arr[j]) return true;\n }\n \n return false;\n });\n \n return arr;\n }", "function npcInRoom (id) {\n var roomNPCs = [];\n for (var i = 0; i < npcs.length; i++) {\n if (npcs[i].roomid === id) {\n roomNPCs.push(npcs[i]);\n }\n }\n\n return roomNPCs;\n\n}", "function calculate_legal_pieces(roll)\r\n{\r\n var legal_pieces = [];\r\n for(var i = 0; i < pieces.length; i++)\r\n {\r\n if (pieces[i].color == CURRENT_PLAYER && pieces[i].position >= 6)\r\n {\r\n if(pieces[i].position + roll == WHITE_PIECE_X_LOCATIONS.length)\r\n {\r\n legal_pieces.push(i);\r\n }\r\n else if(pieces[i].position + roll < WHITE_PIECE_X_LOCATIONS.length )\r\n {\r\n var spot_occupied = false;\r\n for(var j = 0; j < pieces.length; j++)\r\n {\r\n if (pieces[j].position == pieces[i].position + roll && pieces[j].color == pieces[i].color)\r\n {\r\n spot_occupied = true;\r\n }\r\n else if (pieces[j].position == pieces[i].position + roll && pieces[j].color != pieces[i].color && pieces[j].position == 14)\r\n {\r\n spot_occupied = true;\r\n }\r\n }\r\n\r\n if(spot_occupied == false)\r\n {\r\n legal_pieces.push(i);\r\n }\r\n }\r\n }\r\n }\r\n return legal_pieces;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
replace all parent selectors inside `inSelector` by content of `context` array resulting selectors are returned inside `paths` array returns true if `inSelector` contained at least one parent selector
function replaceParentSelector(paths, context, inSelector) { // The paths are [[Selector]] // The first list is a list of comma separated selectors // The inner list is a list of inheritance separated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector; function findNestedSelector(element) { var maybeSelector; if (element.value.type !== 'Paren') { return null; } maybeSelector = element.value.value; if (maybeSelector.type !== 'Selector') { return null; } return maybeSelector; } // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [ [] ]; for (i = 0; i < inSelector.elements.length; i++) { el = inSelector.elements[i]; // non parent reference elements just get added if (el.value !== "&") { var nestedSelector = findNestedSelector(el); if (nestedSelector != null) { // merge the current list of non parent selector elements // on to the current list of selectors to add mergeElementsOnToSelectors(currentElements, newSelectors); var nestedPaths = [], replaced, replacedNewSelectors = []; replaced = replaceParentSelector(nestedPaths, context, nestedSelector); hadParentSelector = hadParentSelector || replaced; //the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors for (k = 0; k < nestedPaths.length; k++) { var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el); addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors); } newSelectors = replacedNewSelectors; currentElements = []; } else { currentElements.push(el); } } else { hadParentSelector = true; // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors for (j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length === 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements.push(new Element(el.combinator, '', el.index, el.currentFileInfo)); } selectorsMultiplied.push(sel); } else { // and the parent selectors for (k = 0; k < context.length; k++) { // We need to put the current selectors // then join the last selector's elements on to the parents selectors var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors mergeElementsOnToSelectors(currentElements, newSelectors); for (i = 0; i < newSelectors.length; i++) { length = newSelectors[i].length; if (length > 0) { paths.push(newSelectors[i]); lastSelector = newSelectors[i][length - 1]; newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList); //newSelectors[i][length - 1].copyVisibilityInfo(inSelector.visibilityInfo()); } } return hadParentSelector; }
[ "function replaceParentSelector(paths, context, inSelector) {\n // The paths are [[Selector]]\n // The first list is a list of comma separated selectors\n // The inner list is a list of inheritance separated selectors\n // e.g.\n // .a, .b {\n // .c {\n // }\n // }\n // == [[.a] [.c]] [[.b] [.c]]\n //\n var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;\n function findNestedSelector(element) {\n var maybeSelector;\n if (!(element.value instanceof Paren)) {\n return null;\n }\n\n maybeSelector = element.value.value;\n if (!(maybeSelector instanceof Selector)) {\n return null;\n }\n\n return maybeSelector;\n }\n\n // the elements from the current selector so far\n currentElements = [];\n // the current list of new selectors to add to the path.\n // We will build it up. We initiate it with one empty selector as we \"multiply\" the new selectors\n // by the parents\n newSelectors = [\n []\n ];\n\n for (i = 0; (el = inSelector.elements[i]); i++) {\n // non parent reference elements just get added\n if (el.value !== '&') {\n var nestedSelector = findNestedSelector(el);\n if (nestedSelector != null) {\n // merge the current list of non parent selector elements\n // on to the current list of selectors to add\n mergeElementsOnToSelectors(currentElements, newSelectors);\n\n var nestedPaths = [], replaced, replacedNewSelectors = [];\n replaced = replaceParentSelector(nestedPaths, context, nestedSelector);\n hadParentSelector = hadParentSelector || replaced;\n // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors\n for (k = 0; k < nestedPaths.length; k++) {\n var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);\n addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);\n }\n newSelectors = replacedNewSelectors;\n currentElements = [];\n\n } else {\n currentElements.push(el);\n }\n\n } else {\n hadParentSelector = true;\n // the new list of selectors to add\n selectorsMultiplied = [];\n\n // merge the current list of non parent selector elements\n // on to the current list of selectors to add\n mergeElementsOnToSelectors(currentElements, newSelectors);\n\n // loop through our current selectors\n for (j = 0; j < newSelectors.length; j++) {\n sel = newSelectors[j];\n // if we don't have any parent paths, the & might be in a mixin so that it can be used\n // whether there are parents or not\n if (context.length === 0) {\n // the combinator used on el should now be applied to the next element instead so that\n // it is not lost\n if (sel.length > 0) {\n sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo));\n }\n selectorsMultiplied.push(sel);\n }\n else {\n // and the parent selectors\n for (k = 0; k < context.length; k++) {\n // We need to put the current selectors\n // then join the last selector's elements on to the parents selectors\n var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);\n // add that to our new set of selectors\n selectorsMultiplied.push(newSelectorPath);\n }\n }\n }\n\n // our new selectors has been multiplied, so reset the state\n newSelectors = selectorsMultiplied;\n currentElements = [];\n }\n }\n\n // if we have any elements left over (e.g. .a& .b == .b)\n // add them on to all the current selectors\n mergeElementsOnToSelectors(currentElements, newSelectors);\n\n for (i = 0; i < newSelectors.length; i++) {\n length = newSelectors[i].length;\n if (length > 0) {\n paths.push(newSelectors[i]);\n lastSelector = newSelectors[i][length - 1];\n newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);\n }\n }\n\n return hadParentSelector;\n }", "function replaceParentSelector(paths, context, inSelector) { \n // The paths are [[Selector]]\n // The first list is a list of comma separated selectors\n // The inner list is a list of inheritance separated selectors\n // e.g.\n // .a, .b {\n // .c {\n // }\n // }\n // == [[.a] [.c]] [[.b] [.c]]\n //\n var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;\n function findNestedSelector(element) { \n var maybeSelector;\n if (!(element[_value] instanceof paren_1[_default])) { \n return null;\n }\n maybeSelector = element[_value][_value];\n if (!(maybeSelector instanceof selector_1[_default])) { \n return null;\n }\n return maybeSelector;\n }\n // the elements from the current selector so far\n currentElements = [];\n // the current list of new selectors to add to the path.\n // We will build it up. We initiate it with one empty selector as we \"multiply\" the new selectors\n // by the parents\n newSelectors = [\n []\n ];\n for (i = 0; (el = inSelector[_elements][i]); i++) { \n // non parent reference elements just get added\n if (el[_value] !== _24) { \n var nestedSelector = findNestedSelector(el);\n if (nestedSelector != null) { \n // merge the current list of non parent selector elements\n // on to the current list of selectors to add\n mergeElementsOnToSelectors(currentElements, newSelectors);\n var nestedPaths = [];\n var replaced = void 0;\n var replacedNewSelectors = [];\n replaced = replaceParentSelector(nestedPaths, context, nestedSelector);\n hadParentSelector = hadParentSelector || replaced;\n // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors\n for (k = 0; k < nestedPaths[_length]; k++) { \n var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);\n addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);\n }\n newSelectors = replacedNewSelectors;\n currentElements = [];\n }\n else { \n currentElements[_push](el);\n }\n }\n else { \n hadParentSelector = true;\n // the new list of selectors to add\n selectorsMultiplied = [];\n // merge the current list of non parent selector elements\n // on to the current list of selectors to add\n mergeElementsOnToSelectors(currentElements, newSelectors);\n // loop through our current selectors\n for (j = 0; j < newSelectors[_length]; j++) { \n sel = newSelectors[j];\n // if we don't have any parent paths, the & might be in a mixin so that it can be used\n // whether there are parents or not\n if (context[_length] === 0) { \n // the combinator used on el should now be applied to the next element instead so that\n // it is not lost\n if (sel[_length] > 0) { \n sel[0] [_elements][_push](new element_1[_default](el[_combinat], '', el[_isVariab], el[_index1], el[_fileInf]));\n }\n selectorsMultiplied[_push](sel);\n }\n else { \n // and the parent selectors\n for (k = 0; k < context[_length]; k++) { \n // We need to put the current selectors\n // then join the last selector's elements on to the parents selectors\n var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);\n // add that to our new set of selectors\n selectorsMultiplied[_push](newSelectorPath);\n }\n }\n }\n // our new selectors has been multiplied, so reset the state\n newSelectors = selectorsMultiplied;\n currentElements = [];\n }\n }\n // if we have any elements left over (e.g. .a& .b == .b)\n // add them on to all the current selectors\n mergeElementsOnToSelectors(currentElements, newSelectors);\n for (i = 0; i < newSelectors[_length]; i++) { \n length = newSelectors[i] [_length];\n if (length > 0) { \n paths[_push](newSelectors[i]);\n lastSelector = newSelectors[i][length - 1];\n newSelectors[i][length - 1] = lastSelector[_createDe](lastSelector[_elements], inSelector[_extendLi]);\n }\n }\n return hadParentSelector;\n }", "function replaceParentSelector(paths, context, inSelector) {\n // The paths are [[Selector]]\n // The first list is a list of comma separated selectors\n // The inner list is a list of inheritance separated selectors\n // e.g.\n // .a, .b {\n // .c {\n // }\n // }\n // == [[.a] [.c]] [[.b] [.c]]\n //\n var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector;\n function findNestedSelector(element) {\n var maybeSelector;\n if (element.value.type !== 'Paren') {\n return null;\n }\n\n maybeSelector = element.value.value;\n if (maybeSelector.type !== 'Selector') {\n return null;\n }\n\n return maybeSelector;\n }\n\n // the elements from the current selector so far\n currentElements = [];\n // the current list of new selectors to add to the path.\n // We will build it up. We initiate it with one empty selector as we \"multiply\" the new selectors\n // by the parents\n newSelectors = [\n []\n ];\n\n for (i = 0; i < inSelector.elements.length; i++) {\n el = inSelector.elements[i];\n // non parent reference elements just get added\n if (el.value !== \"&\") {\n var nestedSelector = findNestedSelector(el);\n if (nestedSelector != null) {\n // merge the current list of non parent selector elements\n // on to the current list of selectors to add\n mergeElementsOnToSelectors(currentElements, newSelectors);\n\n var nestedPaths = [], replaced, replacedNewSelectors = [];\n replaced = replaceParentSelector(nestedPaths, context, nestedSelector);\n hadParentSelector = hadParentSelector || replaced;\n //the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors\n for (k = 0; k < nestedPaths.length; k++) {\n var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el);\n addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors);\n }\n newSelectors = replacedNewSelectors;\n currentElements = [];\n\n } else {\n currentElements.push(el);\n }\n\n } else {\n hadParentSelector = true;\n // the new list of selectors to add\n selectorsMultiplied = [];\n\n // merge the current list of non parent selector elements\n // on to the current list of selectors to add\n mergeElementsOnToSelectors(currentElements, newSelectors);\n\n // loop through our current selectors\n for (j = 0; j < newSelectors.length; j++) {\n sel = newSelectors[j];\n // if we don't have any parent paths, the & might be in a mixin so that it can be used\n // whether there are parents or not\n if (context.length === 0) {\n // the combinator used on el should now be applied to the next element instead so that\n // it is not lost\n if (sel.length > 0) {\n sel[0].elements.push(new Element(el.combinator, '', el.index, el.currentFileInfo));\n }\n selectorsMultiplied.push(sel);\n }\n else {\n // and the parent selectors\n for (k = 0; k < context.length; k++) {\n // We need to put the current selectors\n // then join the last selector's elements on to the parents selectors\n var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector);\n // add that to our new set of selectors\n selectorsMultiplied.push(newSelectorPath);\n }\n }\n }\n\n // our new selectors has been multiplied, so reset the state\n newSelectors = selectorsMultiplied;\n currentElements = [];\n }\n }\n\n // if we have any elements left over (e.g. .a& .b == .b)\n // add them on to all the current selectors\n mergeElementsOnToSelectors(currentElements, newSelectors);\n\n for (i = 0; i < newSelectors.length; i++) {\n length = newSelectors[i].length;\n if (length > 0) {\n paths.push(newSelectors[i]);\n lastSelector = newSelectors[i][length - 1];\n newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList);\n }\n }\n\n return hadParentSelector;\n }", "covers(selector) {\n if (this.isEmpty()) {\n // TODO don't think we ever want to consider an empty\n // label selector as covering any other label selector\n return false;\n }\n return _.every(this._conjuncts, function (conjunct) {\n // Return true immediately if we find an exact match for operator/key/values\n if (selector.hasConjunct(conjunct)) {\n return true;\n }\n // If we can't find a conjunct that matches exactly, do a more detailed check\n switch (conjunct.operator) {\n case 'exists':\n // If an Exists conjunct existed for the same key in selector it\n // would have passed the exact match, just need to check if an In\n // conjunct exists for the same key\n return !_.isEmpty(selector.findConjunctsMatching('in', conjunct.key));\n case 'does not exist':\n // A DoesNotExist can only cover a DoesNotExist operator, if we got here\n // then we didn't have a DNE with the same key so we know we can't cover\n return false;\n case 'in':\n // In (A,B,C) covers In (A,B) AND In (B,C)\n const inConjuncts = selector.findConjunctsMatching('in', conjunct.key);\n if (_.isEmpty(inConjuncts)) {\n return false;\n }\n return _.every(inConjuncts, function (inConjunct) {\n return (\n inConjunct.values.length === _.intersection(inConjunct.values, conjunct.values).length\n );\n });\n case 'not in':\n // NotIn (A,B) covers NotIn (A,B,C) AND NotIn (A,B,D)\n const notInConjuncts = selector.findConjunctsMatching('not in', conjunct.key);\n if (_.isEmpty(notInConjuncts)) {\n return false;\n }\n return _.every(notInConjuncts, function (notInConjunct) {\n return (\n conjunct.values.length ===\n _.intersection(notInConjunct.values, conjunct.values).length\n );\n });\n }\n return true;\n });\n }", "function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) { \n var newSelectorPath, lastSelector, newJoinedSelector;\n // our new selector path\n newSelectorPath = [];\n // construct the joined selector - if & is the first thing this will be empty,\n // if not newJoinedSelector will be the last set of elements in the selector\n if (beginningPath[_length] > 0) { \n newSelectorPath = utils[_copyArra](beginningPath);\n lastSelector = newSelectorPath[_pop]();\n newJoinedSelector = originalSelector[_createDe](utils[_copyArra](lastSelector[_elements]));\n }\n else { \n newJoinedSelector = originalSelector[_createDe]([]);\n }\n if (addPath[_length] > 0) { \n // /deep/ is a CSS4 selector - (removed, so should deprecate)\n // that is valid without anything in front of it\n // so if the & does not have a combinator that is \"\" or \" \" then\n // and there is a combinator on the parent, then grab that.\n // this also allows + a { & .b { .a & { ... though not sure why you would want to do that\n var combinator = replacedElement[_combinat];\n var parentEl = addPath[0] [_elements][0];\n if (combinator[_emptyOrW] && !parentEl[_combinat][_emptyOrW]) { \n combinator = parentEl[_combinat];\n }\n // join the elements so far with the first part of the parent\n newJoinedSelector[_elements][_push](new element_1[_default](combinator, parentEl[_value], replacedElement[_isVariab], replacedElement[_index1], replacedElement[_fileInf]));\n newJoinedSelector[_elements] = newJoinedSelector[_elements][_concat](addPath[0] [_elements][_slice](1));\n }\n // now add the joined selector - but only if it is not empty\n if (newJoinedSelector[_elements][_length] !== 0) { \n newSelectorPath[_push](newJoinedSelector);\n }\n // put together the parent selectors after the join (e.g. the rest of the parent)\n if (addPath[_length] > 1) { \n var restOfPath = addPath[_slice](1);\n restOfPath = restOfPath[_map](function (selector) { \n return selector[_createDe](selector[_elements], []);\n });\n newSelectorPath = newSelectorPath[_concat](restOfPath);\n }\n return newSelectorPath;\n }", "function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {\n var newSelectorPath, lastSelector, newJoinedSelector;\n // our new selector path\n newSelectorPath = [];\n\n //construct the joined selector - if & is the first thing this will be empty,\n // if not newJoinedSelector will be the last set of elements in the selector\n if (beginningPath.length > 0) {\n newSelectorPath = beginningPath.slice(0);\n lastSelector = newSelectorPath.pop();\n newJoinedSelector = originalSelector.createDerived(lastSelector.elements.slice(0));\n }\n else {\n newJoinedSelector = originalSelector.createDerived([]);\n }\n\n if (addPath.length > 0) {\n // /deep/ is a combinator that is valid without anything in front of it\n // so if the & does not have a combinator that is \"\" or \" \" then\n // and there is a combinator on the parent, then grab that.\n // this also allows + a { & .b { .a & { ... though not sure why you would want to do that\n var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0];\n if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {\n combinator = parentEl.combinator;\n }\n // join the elements so far with the first part of the parent\n newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.index, replacedElement.currentFileInfo));\n newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));\n }\n\n // now add the joined selector - but only if it is not empty\n if (newJoinedSelector.elements.length !== 0) {\n newSelectorPath.push(newJoinedSelector);\n }\n\n //put together the parent selectors after the join (e.g. the rest of the parent)\n if (addPath.length > 1) {\n var restOfPath = addPath.slice(1);\n restOfPath = restOfPath.map(function (selector) {\n return selector.createDerived(selector.elements, []);\n });\n newSelectorPath = newSelectorPath.concat(restOfPath);\n }\n return newSelectorPath;\n }", "matchesContext(context) {\n if (context.indexOf(\"|\") > -1)\n return context.split(/\\s*\\|\\s*/).some(this.matchesContext, this);\n let parts = context.split(\"/\");\n let option = this.options.context;\n let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);\n let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);\n let match = (i, depth) => {\n for (; i >= 0; i--) {\n let part = parts[i];\n if (part == \"\") {\n if (i == parts.length - 1 || i == 0)\n continue;\n for (; depth >= minDepth; depth--)\n if (match(i - 1, depth))\n return true;\n return false;\n } else {\n let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;\n if (!next || next.name != part && next.groups.indexOf(part) == -1)\n return false;\n depth--;\n }\n }\n return true;\n };\n return match(parts.length - 1, this.open);\n }", "function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {\n var newSelectorPath;\n var lastSelector;\n var newJoinedSelector; // our new selector path\n\n newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty,\n // if not newJoinedSelector will be the last set of elements in the selector\n\n if (beginningPath.length > 0) {\n newSelectorPath = copyArray(beginningPath);\n lastSelector = newSelectorPath.pop();\n newJoinedSelector = originalSelector.createDerived(copyArray(lastSelector.elements));\n } else {\n newJoinedSelector = originalSelector.createDerived([]);\n }\n\n if (addPath.length > 0) {\n // /deep/ is a CSS4 selector - (removed, so should deprecate)\n // that is valid without anything in front of it\n // so if the & does not have a combinator that is \"\" or \" \" then\n // and there is a combinator on the parent, then grab that.\n // this also allows + a { & .b { .a & { ... though not sure why you would want to do that\n var combinator = replacedElement.combinator;\n var parentEl = addPath[0].elements[0];\n\n if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {\n combinator = parentEl.combinator;\n } // join the elements so far with the first part of the parent\n\n\n newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo));\n newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));\n } // now add the joined selector - but only if it is not empty\n\n\n if (newJoinedSelector.elements.length !== 0) {\n newSelectorPath.push(newJoinedSelector);\n } // put together the parent selectors after the join (e.g. the rest of the parent)\n\n\n if (addPath.length > 1) {\n var restOfPath = addPath.slice(1);\n restOfPath = restOfPath.map(function (selector) {\n return selector.createDerived(selector.elements, []);\n });\n newSelectorPath = newSelectorPath.concat(restOfPath);\n }\n\n return newSelectorPath;\n } // joins selector path from `beginningPath` with every selector path in `addPaths` array", "function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {\n var newSelectorPath, lastSelector, newJoinedSelector;\n // our new selector path\n newSelectorPath = [];\n\n //construct the joined selector - if & is the first thing this will be empty,\n // if not newJoinedSelector will be the last set of elements in the selector\n if (beginningPath.length > 0) {\n newSelectorPath = beginningPath.slice(0);\n lastSelector = newSelectorPath.pop();\n newJoinedSelector = originalSelector.createDerived(lastSelector.elements.slice(0));\n }\n else {\n newJoinedSelector = originalSelector.createDerived([]);\n }\n\n if (addPath.length > 0) {\n // /deep/ is a combinator that is valid without anything in front of it\n // so if the & does not have a combinator that is \"\" or \" \" then\n // and there is a combinator on the parent, then grab that.\n // this also allows + a { & .b { .a & { ... though not sure why you would want to do that\n var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0];\n if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {\n combinator = parentEl.combinator;\n }\n // join the elements so far with the first part of the parent\n newJoinedSelector.elements.push(new Element(combinator, parentEl.value, replacedElement.index, replacedElement.currentFileInfo));\n newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));\n }\n\n // now add the joined selector - but only if it is not empty\n if (newJoinedSelector.elements.length !== 0) {\n newSelectorPath.push(newJoinedSelector);\n }\n\n //put together the parent selectors after the join (e.g. the rest of the parent)\n if (addPath.length > 1) {\n newSelectorPath = newSelectorPath.concat(addPath.slice(1));\n }\n return newSelectorPath;\n }", "function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) {\n var newSelectorPath, lastSelector, newJoinedSelector;\n // our new selector path\n newSelectorPath = [];\n\n // construct the joined selector - if & is the first thing this will be empty,\n // if not newJoinedSelector will be the last set of elements in the selector\n if (beginningPath.length > 0) {\n newSelectorPath = utils.copyArray(beginningPath);\n lastSelector = newSelectorPath.pop();\n newJoinedSelector = originalSelector.createDerived(utils.copyArray(lastSelector.elements));\n }\n else {\n newJoinedSelector = originalSelector.createDerived([]);\n }\n\n if (addPath.length > 0) {\n // /deep/ is a CSS4 selector - (removed, so should deprecate)\n // that is valid without anything in front of it\n // so if the & does not have a combinator that is \"\" or \" \" then\n // and there is a combinator on the parent, then grab that.\n // this also allows + a { & .b { .a & { ... though not sure why you would want to do that\n var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0];\n if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) {\n combinator = parentEl.combinator;\n }\n // join the elements so far with the first part of the parent\n newJoinedSelector.elements.push(new Element(\n combinator,\n parentEl.value,\n replacedElement.isVariable,\n replacedElement._index,\n replacedElement._fileInfo\n ));\n newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1));\n }\n\n // now add the joined selector - but only if it is not empty\n if (newJoinedSelector.elements.length !== 0) {\n newSelectorPath.push(newJoinedSelector);\n }\n\n // put together the parent selectors after the join (e.g. the rest of the parent)\n if (addPath.length > 1) {\n var restOfPath = addPath.slice(1);\n restOfPath = restOfPath.map(function (selector) {\n return selector.createDerived(selector.elements, []);\n });\n newSelectorPath = newSelectorPath.concat(restOfPath);\n }\n return newSelectorPath;\n }", "function isNestedSelector(selector) {\n return /&/.test(selector);\n}", "function addAllReplacementsIntoPath(beginningPath,addPaths,replacedElement,originalSelector,result){var j;for(j=0;j<beginningPath.length;j++){var newSelectorPath=addReplacementIntoPath(beginningPath[j],addPaths,replacedElement,originalSelector);result.push(newSelectorPath);}return result;}", "parents(selector) {\n const result = [];\n let parent = this.parent;\n while (parent) {\n if (!selector || parent.is(selector))\n result.push(parent);\n parent = parent.parent;\n }\n return result;\n }", "visitInPredicate(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitInExpression(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "parentsWhileMatch(selector) {\n const retArr = [];\n let parent = this.parent().filter(item => item.matchesSelector(selector));\n while (parent.isPresent()) {\n retArr.push(parent);\n parent = parent.parent().filter(item => item.matchesSelector(selector));\n }\n return new DomQuery(...retArr);\n }", "function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) { \n var j;\n for (j = 0; j < beginningPath[_length]; j++) { \n var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);\n result[_push](newSelectorPath);\n }\n return result;\n }", "function addAllReplacementsIntoPath( beginningPath, addPaths, replacedElement, originalSelector, result) {\n var j;\n for (j = 0; j < beginningPath.length; j++) {\n var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);\n result.push(newSelectorPath);\n }\n return result;\n }", "function addAllReplacementsIntoPath(beginningPath, addPaths, replacedElement, originalSelector, result) {\n var j;\n\n for (j = 0; j < beginningPath.length; j++) {\n var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector);\n result.push(newSelectorPath);\n }\n\n return result;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the firmware device status from the server Praneesh 28 Jan 2015
function GetActualFirmwareDownloadStatusAndUpdateUI(progressIntervalId, currentProgressPercent) { var deviceIds = new Array(); deviceIds.push(self.Id); datacontext.getfwupgradeStaus(deviceIds).done(function (jResult) { if (jResult.Success) { if (jResult.data) { var statusArr = jResult.data; //jResult.data.split("#"); if (statusArr && statusArr.length > 0) { if (statusArr[0] != null && statusArr[0]) { SimulateFirmwareDownloadStatusAndUpdateUI(progressIntervalId, currentProgressPercent, statusArr[0]); //var status = statusArr[0].Status; //var isComplete = statusArr[0].IsComplete; //var version = statusArr[0].Version; //SetUpgradeDescription(statusArr[0].Description); //if (isComplete) { // SimulateFirmwareDownloadStatusAndUpdateUI(progressIntervalId, 100, version); //} //else if (status > 100) { // //Currently the only way to check if upgrade failure is status=255 // SimulateFirmwareDownloadStatusAndUpdateUI(progressIntervalId, -10, version); //} //else { // var realUpdateStatus = status; // if (realUpdateStatus && realUpdateStatus > currentProgressPercent) { // SimulateFirmwareDownloadStatusAndUpdateUI(progressIntervalId, realUpdateStatus, version); // } //} } } } } }).fail(function () { }); }
[ "function getFirmwareVersion() {\n if (verbose) {\n log(`Getting firmware version...`);\n const buf = Buffer.from(`VER\\n`, 'ascii');\n vpro.write(buf, (err) => {\n if (err) {\n logError(`Failed to get firmware version`);\n return;\n }\n vpro.drain();\n vpro.on('readable', () => {\n setTimeout(() => {\n let res = true;\n while (res === true) {\n res = readAllIncomingBytes();\n }\n if (res.constructor === Buffer) {\n console.log(`\n Data: ${res.toString('hex')}\n Length: ${res.length}\n `);\n }\n process.exit(0);\n }, 1000);\n });\n });\n }\n}", "function displayFirmwareUpdateStatus(callback) {\n registry.getTwin(deviceToUpdate, function(err, twin){\n if (err) {\n callback(err);\n } else {\n // Output the value of twin reported properties, which includes the firmwareUpdate details\n console.log(twin.properties.reported);\n callback(null);\n }\n });\n}", "function getFirmwareVersion(){\n var bytes=new Uint8Array(64);\n var UUID_FIRMW_VERS = new Uint8Array([0x2a, 0x26]);\n /*bytes[0]=0x12;\n\tbytes[1]=(UUID_FIRMW_VERS.length & 0xFF);\n bytes[2]=0x2a;\n bytes[3]=0x26;*/\n\tbytes[0] = 0x17;\t\t\t\t\t\t\t\t//read handle\n\tbytes[1] = 4;\n\tbytes[2] = 0x00;\n\tbytes[3] = 0x21;\n\n sendByteData(true,bytes,null,connectionId_FIDO_FIDO,'UUID_FIRMW_VERS'); \n }", "function getStatus() {\n let command = {};\n command.name = GET_STATUS;\n console.log(command.name);\n return new Promise(function(resolve) {\n let xmlHttpRequest = new XMLHttpRequest();\n xmlHttpRequest.onreadystatechange = function() {\n if (this.readyState === READYSTATE_COMPLETED) {\n if (this.status === HTTP_STATUS_OK) {\n console.log(this.responseText);\n resolve(this.responseText);\n } else {\n console.log('get device state failed');\n resolve('Failed. HttpStatus: ' + this.statusText);\n }\n }\n };\n xmlHttpRequest.open(POST, COMMAND, true);\n xmlHttpRequest.setRequestHeader(CONTENT_TYPE, TYPE_JSON);\n xmlHttpRequest.send(JSON.stringify(command));\n });\n}", "function fetchDeviceStatus() {\n\ttimeLeft = refreshInterval / 1000;\n\n\t$(\"div#noresponse\").hide();\n\t$(\"div#urgent div\").remove();\n\t$(\"div#noresponse div\").remove();\n\t$(\"div#needservice div\").remove();\n\t$(\"div#goodservice div\").remove();\n\t\n\t//iterate through printers\n\t//printers defined in printers.js\n\tfor (var i=0; i<printers.length; i++) {\n\t\tvar printer = printers[i];\n\t\tif ((printer.type == \"HP9050\") || (printer.type == \"HP4515\")) {\n\t\t\tfetchDeviceStatusHP9050(printer);\n\t\t} else if (printer.type == \"HPM806\") {\n\t\t\tfetchDeviceStatusHPM806(printer);\t\n\t\t} else if (printer.type == \"HP4700\") {\n\t\t\tfetchDeviceStatusHP4700(printer);\n\t\t}\n\n\t}\n\n\t\t\t\n\tfor (var i=0; i<printers.length; i++) {\n\t\tif (printers[i][\"error\"])\n\t\t\talert('error logged');\n\t}\n}", "function requestFirmwareVersion (callback) {\n\n audiomoth.getFirmwareVersion(function (err, versionArr) {\n\n if (err || versionArr === null) {\n\n callback(new Error('Could not connect to device to obtain firmware version. Verify connection and try again.'));\n\n } else {\n\n callback(null, versionArr[0] + '.' + versionArr[1] + '.' + versionArr[2]);\n\n }\n\n });\n\n}", "static async status() {\n return await this._makeRequest('status', 'get', `/system/status`);\n }", "getDeviceState() {\n\n let url = this._syncBoxUrl;\n return this._syncBoxGET(url, PhueSyncBoxMsgRequestType.DEVICE_STATE)\n }", "function requestDevStatus() {\n if(mConnectedToDev) {\n return;\n }\n\n mNbReqStatusRetry++;\n if(mNbReqStatusRetry >= 6) {\n logger.warn('[ctrl-test] Request device status without response. Stop!');\n return;\n }\n\n devComm.sendStatusReportReq(SelectedGW);\n\n setTimeout(requestDevStatus, 5*1000);\n\n }", "async function getDriverStatus () {\n\t//create connection\n\tlet mdb = new mdbr(config.dbInfo);\n\tawait mdb.connectDb();\n\tlet driversStatus = await mdb.getDriverStatus();\n\n\treturn {\n\t\ttype: 'DRIVER_STATUS_RESPONSE',\n\t\tpayload : drivers,\n\t}\n}", "function getDeviceStatusInfo(result) {\n var colour;\n writeData(result.speed, \"speed\", \"vechInfoAddin_currSpeed\");\n if (result.isDeviceCommunicating) {\n writeData(\"Active\", \"\", \"vechInfoAddin_deviceActivity\");\n colour = \"#18b534\";\n } else {\n writeData(\"Inactive\", \"\", \"vechInfoAddin_deviceActivity\");\n colour = \"#d41515\";\n }\n document.getElementById(\"vechInfoAddin_deviceActivity\").style.color = colour;\n document.getElementById(\n \"vechInfoAddin_deviceActivity\"\n ).style.borderColor = colour;\n document.getElementById(\"vechInfoAddin_deviceActivity\").style.display =\n \"block\";\n}", "#loadFirmwareIndex() {\n if (!this.data.system || !this.data.system.firmware.download)\n return;\n\n if (this.#update.firmware.bytes)\n return;\n\n this.printDevice('Downloading firmware update index: <b>' + this.data.system.firmware.download + '/index.json</b>');\n const request = new XMLHttpRequest();\n request.onreadystatechange = () => {\n let index;\n\n if (request.readyState == 4 && request.status == 200) {\n try {\n index = JSON.parse(request.responseText);\n\n } catch (error) {\n this.printDevice('Unable to parse firmware update index: <b>' + this.data.system.firmware.download + '/index.json</b>');\n return;\n }\n\n this.printDevice('Retrieved firmware update index');\n\n const update = index[this.data.system.firmware.id];\n if (!update) {\n this.printDevice('No firmware update found for this device.');\n return;\n }\n\n if (this.data.system.board != update.board) {\n this.printDevice('No firmware update found for this board.');\n return;\n }\n\n if (this.data.system.firmware.hash == update.hash) {\n this.#update.notify.success('The firmware is up-to-date.');\n return;\n }\n\n if (this.data.system.firmware.version > update.version) {\n this.#update.notify.warn('A more recent firmware is already installed.');\n return;\n }\n\n this.printDevice('Downloading firmware update: <b>' + update.file + '</b>');\n const firmware = new XMLHttpRequest();\n firmware.onreadystatechange = () => {\n if (firmware.readyState == 4) { // DONE\n if (firmware.status == 200) {\n const bytes = firmware.response;\n this.printDevice('Retrieved firmware image, length=' + bytes.byteLength);\n this.#showFirmware(new Uint8Array(bytes));\n\n } else\n this.printDevice('Failed to download firmware image: ' + firmware.status);\n }\n }\n\n firmware.open('GET', this.data.system.firmware.download + '/' + update.file, true);\n firmware.responseType = 'arraybuffer';\n firmware.send();\n }\n };\n\n // Append the session ID to prevent the index file from being cached\n // in the browser. Reloading the browser will create a new ID.\n request.open('GET', this.data.system.firmware.download + '/index.json?s=' + this.#sessionID, true);\n request.send();\n }", "function getStatus() {\n\trequest({\n\t\t\turl: station_status,\n\t\t\tmethod: 'GET',\n\t\t\tjson: true\n\t}, function(error, response, body) {\n\t\t\tif (error) {\n\t\t\t\t\tconsole.log('Error sending message: ', error);\n\t\t\t} else if (response.body.error) {\n\t\t\t\t\tconsole.log('Error: ', response.body.error);\n\t\t\t}\n\n\t\t\tvar statusBody = body;\n\t\t\tconsole.log('Last Updated: ', statusBody.last_updated);\n\t\t\tindexStatus(statusBody); // Index the status\n\t})\n\n}", "function get_status() {\n //TODO\n\n }", "function updateDeviceStatus() {\n logger.info('updateDeviceStatus');\n\n var status = -1;\n var device = adyen.currentDevice();\n if (device && adyen.isLoggedIn()) {\n status = device.status;\n }\n\n switch( status ) {\n case -1:\n deviceStatusLabel.setText(_L('Not selected'));\n boardButton.enabled = false;\n\n break;\n case 0:\n deviceStatusLabel.setText(_L('Initializing...'));\n boardButton.enabled = false;\n break;\n case 1:\n deviceStatusLabel.setText(_L('Initialized'));\n boardButton.enabled = false;\n break;\n case 2:\n deviceStatusLabel.setText(_L('Not Boarded'));\n boardButton.enabled = true;\n break;\n case 3:\n deviceStatusLabel.setText(_L('Device Error'));\n break;\n case 4:\n deviceStatusLabel.setText(_L('Stopped'));\n boardButton.enabled = true;\n break;\n case 5:\n deviceStatusLabel.setText(_L('Disconnected'));\n break;\n }\n }", "function getStatusServer() {\r\n _doGet('/status');\r\n }", "function OnUpdateFirmware(force, connid, requiredPlatform, requiredVersion, requestId) {\n let RaucHandler = require('./RaucHandler');\n let raucHandler = new RaucHandler();\n raucHandler.on('progress', function (progressInfo) {\n log(progressInfo);\n });\n raucHandler.raucGetSlotStatus(function (err, platformStatus) {\n if (err) {\n log(\"Unable to update firmware\".red + err);\n }\n else {\n let rootfs0_status = platformStatus.rootfs0.find(function (p) { return p.key === 'state'; });\n let currentPlatform = rootfs0_status.val === \"booted\" ? platformStatus.rootfs0 : platformStatus.rootfs1;\n let platform = platformStatus.platform;\n let version = currentPlatform.find(function (p) { return p.key === 'bundle.version'; });\n let bootStatus = currentPlatform.find(function (p) { return p.key === 'boot-status'; });\n let installed = currentPlatform.find(function (p) { return p.key === 'installed.timestamp'; });\n\n if (requiredPlatform && requiredPlatform != platform) {\n log(\"Ignoring update for different platform\");\n return;\n }\n\n if (!version) {\n version = { val: \"0.0.0\" };\n }\n if (!bootStatus) {\n bootStatus = { val: \"FIRST INSTALL\" };\n }\n if (!installed) {\n installed = { val: \"FIRST INSTALL\" };\n }\n \n let uri = `${settingsHelper.settings.hubUri}/api/nodeimages/${settingsHelper.settings.organizationId}/${(requiredPlatform?requiredPlatform:platform)}${(requiredVersion ? \"?version=\" + requiredVersion : \"\")}`;\n \n uri = uri.replace('wss://', 'https://');\n log(\"Notified on new firmware\".yellow);\n log(\"Current firmware platform: \".yellow + platform.grey);\n log(\"Current firmware version: \".yellow + version.val.grey);\n log(\"Current boot status: \".yellow + bootStatus.val.grey);\n log(\"Current firmware installed: \".yellow + installed.val.grey);\n\n log(\"Fetching meta data from: \".yellow + uri.grey);\n\n // TEST\n webRequest(uri, function (err, response, data) {\n if (response.statusCode != 200 || err != null) {\n log(\"No firmware image found\".red);\n return;\n }\n else {\n let metamodel = JSON.parse(data);\n\n if (force || util.compareVersion(metamodel.version, version.val)) {\n if (settingsHelper.settings.state === \"Active\") {\n microServiceBusNode.ChangeState(\"InActive\");\n }\n log(\"New firmware version\".yellow);\n let dir = path.resolve(settingsHelper.homeDirectory, \"firmwareimages\");\n\n if (!fs.existsSync(dir)) {\n log(\"Creating firmwareimages directory\".yellow);\n fs.mkdirSync(dir);\n }\n else {\n fs.readdirSync(dir).forEach(function (file, index) {\n log(\"Removing existing file\".yellow);\n var curPath = path.resolve(dir, file);\n fs.unlinkSync(curPath);\n });\n }\n\n var fileName = path.resolve(dir, path.basename(metamodel.uri));\n\n var file = fs.createWriteStream(fileName);\n var https = require('https');\n log(\"Downloading image from \".yellow + metamodel.uri.grey);\n\n let options = {\n timeout: 1000 * 60 * 10, //10 min timeout\n };\n var request = https.get(metamodel.uri, options, function (response) {\n response.pipe(file);\n file.on('finish', function () {\n file.close(function () {\n log(\"Download complete\".yellow);\n log(\"Calling RAUC\".yellow);\n log(\"Installing \".yellow + fileName.grey);\n if (connid)\n {\n _client.invoke('notify', connid, \"Download complete, installation initiated on \" + settingsHelper.settings.nodeName, \"INFO\");\n }\n raucHandler.raucInstall(fileName, function (err) {\n if (err) {\n log(\"Unable to install RAUC image. \".red + err);\n if (connid)\n _client.invoke('notify', connid, \"Unable to install RAUC image on \" + settingsHelper.settings.nodeName, \"INFO\");\n }\n else {\n log(\"Successfully installed RAUC image.\".green);\n\n if (connid) {\n _client.invoke('notify', connid, \"Successfully installed RAUC image on \" + settingsHelper.settings.nodeName + \". Node is now rebooting\", \"INFO\");\n }\n if(requestId){\n var reportState = {\n reported: { \n msbFirmwareUpdate: {\n requestId: requestId\n } }\n };\n microServiceBusNode.UpdateComState(reportState)\n .then(()=>{\n log(\"Requested firmware state has been updated\".green);\n setTimeout(function () {\n util.reboot();\n }, 10000); \n })\n .catch(e=>{\n log(\"Unable to persist requested firmware state. This might set the Node into a reboot loop!\".red + ` Error: ${e}`);\n });\n }\n else{\n setTimeout(function () {\n util.reboot();\n }, 10000); \n }\n }\n });\n });\n });\n }).on('error', function (err) { // Handle errors\n fs.unlink(fileName); // Delete the file async. (But we don't check the result)\n log(\"unable to download firmware\".red);\n });\n }\n else {\n log(\"Already running latest version\".yellow);\n }\n }\n });\n\n }\n });\n }", "getSwitchStatus() {\n\n this.log.debug('lanClient getSwitchStatus');\n\n let result = undefined;\n if (this.localDevice && this.localDevice.data.type === 'plug') {\n result = this.localDevice.data.state.switch === 'on';\n }\n\n this.log.debug('lanClient getSwitchStatus result: %s', result);\n return result;\n }", "function getAPStatus()\n{\n\tvar request = {\n\t\t\"Req\" : g_zwdRequestNames.ZWD_REQUEST,\n\t\t\"ZWDType\" : g_zwdRequestNames.ZWD_GET_AP_STATUS,\n\t\t\"wlname\" : g_wlName\n\t};\n\n\tclearAllZWDTimers();\n\tgetZWDDetFromServer(request);\n\tg_timerAPStatus.push(setTimeout(function(){getAPStatus(g_zwdTimeOutVal);}, g_zwdTimeOutVal));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the current stream preview element
function removePreview() { $("#streamPreview").remove(); }
[ "function removePreview() {\n\t\t$( this ).siblings( '.rwmb-embed-media' ).html( '' );\n\t}", "function hidePreview() {\n let span = this.querySelector('.preview');\n span.parentNode.removeChild(span);\n}", "_destroyPreview() {\n if (this._preview) {\n removeNode(this._preview);\n }\n if (this._previewRef) {\n this._previewRef.destroy();\n }\n this._preview = this._previewRef = null;\n }", "function cleanPreviewElement() {\n if (browser === 'FIREFOX') {\n var iframe = $(\"#streamPreview iframe\");\n $(\"#streamPreview iframe\").on('load', function() {\n $(\"div.player-hover:nth-child(15)\", iframe.contents()).remove();\n $(\"div.player-hover:nth-child(19)\", iframe.contents()).remove();\n $(\"button.player-button:nth-child(19)\", iframe.contents()).remove();\n });\n }\n }", "_destroyPreview() {\n this._preview?.remove();\n this._previewRef?.destroy();\n this._preview = this._previewRef = null;\n }", "function closePreview() {\n\n\t\t\tif( dom.preview ) {\n\t\t\t\tdom.preview.setAttribute( 'src', '' );\n\t\t\t\tdom.preview.parentNode.removeChild( dom.preview );\n\t\t\t\tdom.preview = null;\n\t\t\t}\n\n\t\t}", "function closePreview() {\n\n\t\tif( dom.preview ) {\n\t\t\tdom.preview.setAttribute( 'src', '' );\n\t\t\tdom.preview.parentNode.removeChild( dom.preview );\n\t\t\tdom.preview = null;\n\t\t}\n\n\t}", "remove(preview) {\n let found = this._previews.indexOf(preview);\n if (found >= 0) {\n this._previews.splice(found, 1);\n }\n }", "function clearPreview() {\n document.getElementById('preview').src = null\n}", "function clear() {\n if (!preview.classList.contains('offscreen'))\n returnToCameraMode();\n items.forEach(function(item) {\n filmstrip.removeChild(item.element);\n URL.revokeObjectURL(item.element.src);\n });\n items.length = 0;\n }", "function removeVideoStream(id) {\n let cameraLi = document.getElementById(connections[id].stream.id);\n let cameradisp = document.getElementById(connections[id].stream.id + 1);\n cameraLi.children[0].srcObject = null;\n screenShare.hidden = true;\n cameraLi.innerHTML = '';\n cameradisp.remove();\n videoElement.children[0].removeChild(cameraLi);\n\n connections[id].stream = null;\n\n if (videoElement.children[0].children.length == 0)\n ThreeD.resizeCanvas(0); // Make space for the videos on the screen\n\n ThreeD.updateVideoList(id);\n}", "function removePreview() {\n window.document.body.removeChild(previewElement_bg);\n window.document.body.removeChild(previewElement);\n window.document.body.removeChild(userPageElement);\n window.document.body.removeChild(closeBtnElmnt);\n window.document.head.removeChild(document.getElementById(\"aiva_vendor_css\"));\n window.document.head.removeChild(document.getElementById(\"aiva_css\"));\n while (document.getElementById(\"aiva_font\")) {\n window.document.head.removeChild(document.getElementById(\"aiva_font\"));\n }\n }", "function hidePreview(){\n\t\tif (preview!=null){\n\t\t\tscene.remove(preview);\n\t\t}\n\t\tpreview = null;\n\t}", "function removeVideoStream(elementId) {\n let remoteDiv = document.getElementById(elementId);\n if (remoteDiv)\n remoteDiv.parentNode.removeChild(remoteDiv);\n }", "function destruct_preview() {\r\n clear_preview(true);\r\n}", "remove () {\n // remove placeholder\n const placeholder = this.queryService.get('preview-placeholder');\n\n // add a manual cached reference\n this.queryService.updateRef('preview-placeholder', placeholder.cloneNode(true));\n\n // remove the placeholder from the DOM\n $(placeholder).remove();\n }", "function onRemoteStreamRemoved(event) {\n console.log(\"Remove remote stream\");\n remoteVideo.src = \"\";\n }", "clearMediaWindow() {\n this.container.removeChild(this.mediaElt);\n this.mediaElt = document.createElement('p');\n this.container.appendChild(this.mediaElt);\n }", "function stopPreview() {\n draw.clearPreview();\n previewCol = undefined;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reloads browsers that are using browsersync
function browserSyncReload(done) { browserSync.reload(); done(); }
[ "function browserSyncReload(done) {\n browsersync.reload();\n done();\n}", "function browsersyncReload(cb) {\n browsersync.reload();\n cb();\n}", "function browserSyncReload(callback) {\n browserSync.reload();\n callback();\n}", "function reload() {\n browserSync.reload();\n}", "function reloadBrowser() {\n return Promise.resolve(browsersync.reload());\n}", "browserReload(url, options) {\n\n\n /**\n * Note: as for now I only use https, so this snippet only works with https,\n * not tested with regular http. (this might change in the future as I encounter\n * the need to test regular http files).\n */\n if (false === this.browserSyncInitialized) {\n\n var browserSyncOptions = {\n open: false,\n /**\n Https setup\n ------------\n For https setup, don't forget to copy the /browser-sync/browser-sync-client.js code (video at 13:25)\n https://www.youtube.com/watch?v=NDjE_LCHbuI&list=PLriKzYyLb28lp0z-OMB5EYh0OHaKe91RV&index=8\n */\n proxy: url,\n };\n if (options.https) {\n browserSyncOptions.https = options.https;\n }\n\n var webRootDir = options.webRootDir || \"./\";\n var browserSyncClientPath = webRootDir + \"browser-sync-client.js\";\n if(false === fs.existsSync(browserSyncClientPath)){\n utils.copy(\"./node_modules/autumn-wizard/assets/browser-sync-client.js\", browserSyncClientPath);\n }\n\n\n browserSync.init(browserSyncOptions);\n this.browserSyncInitialized = true;\n }\n\n\n browserSync.reload();\n }", "function browsersync() {\n\tbrowserSync.init({\n\t\tfiles: './**/*',\n\t\tproxy: 'alkteia.localhost',\n\t\topen: false\n\t});\n}", "function updateBrowser() {\n sync();\n\n if ($browser.getUrl() != location.href) {\n $browser.setUrl(location.href);\n copy(location, lastLocation);\n }\n }", "function livereload() {\n browserSync.init(conf.browsersync);\n}", "function reloadPage(){\n console.log(\"Changes detected, reloading page now\");\n browserSync.reload();\n}", "function stopAndStartBrowserSync() {\n console.log('Cleaning up previous browserSync and starting afresh.');\n browserSync.instance.cleanup();\n startBrowserSync();\n }", "function browserSyncServeTask() {\n $.browserSync(config.browserSync.dev);\n }", "function serversync() {\n browserSync.init({\n server: {\n watch: true,\n // baseDir: \"./\"\n baseDir: \"./dist\"\n }\n });\n watch(PATH_STYLE, style);\n watch(PATH_TEMPLATE, views);\n watch(\"./dist/css/style.css\").on('change', browserSync.reload);\n watch(\"./dist/index.html\").on('change', browserSync.reload);\n}", "reload() {\n gBrowser.reloadWithFlags(\n Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY |\n Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE\n );\n }", "hotReload() {\n if (this.config.skipHotReload) return this.reload()\n this.changeState('hotReload')\n this.timeout = setTimeout(this.onTimeout, 5000)\n this.cdp.Runtime.evaluate({expression: `Zen.upgrade(${JSON.stringify(this.codeHash)})`})\n this.codeHash = null\n }", "function restartBrowser() {\n chrome.send('restartBrowser');\n}", "function browsersyncServe(cb) {\r\n browserSync.init({\r\n server: {\r\n baseDir: \"./\",\r\n },\r\n });\r\n cb();\r\n}", "function firefoxCacheFix() {\n if (navigator.userAgent.toLowerCase().indexOf(\"firefox\") > -1) {\n if (!window.location.hash) {\n window.location = window.location + \"#loaded\";\n window.location.reload(true);\n }\n }\n return false;\n}", "function reload() { if(!production) { bsyncReload(); } }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the divElement style attribute with all properties in styleObject.
function addStyleProperties(divElement, styleObject) { for (key in styleObject) { if (styleObject.hasOwnProperty(key)) { divElement.style[key] = styleObject[key]; } } }
[ "function addStyleProperties(divElement, styleObject) {\r\n for (key in styleObject) {\r\n if (styleObject.hasOwnProperty(key)) {\r\n divElement.style[key] = styleObject[key]; \r\n }\r\n }\r\n }", "function addStyleProperties(divElement, styleObject) {\n for (key in styleObject) {\n if (styleObject.hasOwnProperty(key)) {\n divElement.style[key] = styleObject[key]; \n }\n }\n }", "function applyStyle(element,style){\n element.attr('data-style', style.id);\n for ( i in style.properties ) {\n console.log('running');\n element[0].style[i] = style.properties[i];\n }\n updateVars();\n}", "function partialUpdateStyle(element, style) {\r\n Object.assign(element.style, style);\r\n}", "_updateStyle(style = {}) {\n let prop;\n\n for (prop in style) {\n if (style.hasOwnProperty(prop)) {\n this.frame.style[prop] = style[prop];\n }\n }\n }", "function setStyleOnDomElement(styleObj, domElement) {\n try {\n let styleAttr = Object.keys(styleObj);\n styleAttr.forEach(function(attr) {\n /* eslint-disable */\n domElement.style[attr] = styleObj[attr];\n /* eslint-enable */\n });\n } catch (e) {\n throw new Error('electron-notify: Could not set style on domElement', styleObj, domElement)\n }\n}", "function IntObject_UpdateCSSStyleProperty()\n{\n\t//has fixed property?\n\tif (this.StyleProperties && this.StyleProperties.FixedPosition)\n\t{\n\t\t//unregister this as a fixed object\n\t\t__SIMULATOR.Interpreter.NotifyFixedObject(this.DataObject.Id, this, false);\n\t}\n\t//by default: no object is CSS Enabled\n\tthis.StyleProperties = false;\n\t//retrieve out css property\n\tvar strCSS = Get_String(this.Properties[__NEMESIS_PROPERTY_STYLE], null);\n\t//valid?\n\tif (strCSS != null)\n\t{\n\t\t//could have properties, convert into an object\n\t\tthis.StyleProperties = { cssText: \"\", Original: {}, Zoom: null };\n\t\t//split it\n\t\tstrCSS = strCSS.split(\";\");\n\t\t//now loop through all of them\n\t\tfor (var iCSS = 0, cCSS = strCSS.length; iCSS < cCSS; iCSS++)\n\t\t{\n\t\t\t//split this into key value pair\n\t\t\tvar pair = strCSS[iCSS].split(\":\");\n\t\t\t//valid?\n\t\t\tif (pair.length == 2)\n\t\t\t{\n\t\t\t\t//we want to make sure we trim the key\n\t\t\t\tpair[0] = pair[0].Trim();\n\t\t\t\t//store it\n\t\t\t\tthis.StyleProperties.Original[pair[0]] = pair[1];\n\t\t\t\t//switch on it\n\t\t\t\tswitch (pair[0].toLowerCase())\n\t\t\t\t{\n\t\t\t\t\tcase \"pointer-events\":\n\t\t\t\t\t\t//only process this if we arent in designer or if the value is not \"none\"\n\t\t\t\t\t\tif (!__DESIGNER_CONTROLLER || !/none/i.test(pair[1]))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//add it to the css text\n\t\t\t\t\t\t\tthis.StyleProperties.cssText += pair[0] + \":\" + pair[1] + \";\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"zoom\":\n\t\t\t\t\t\t//add it to the css text\n\t\t\t\t\t\tthis.StyleProperties.cssText += pair[0] + \":\" + pair[1] + \";\";\n\t\t\t\t\t\t//but we also need to mark this as a valid zoom object\n\t\t\t\t\t\tthis.StyleProperties.Zoom = Zoom_Register(this, pair[1]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"content\":\n\t\t\t\t\t\t//replace all url(' with url(' plus host\n\t\t\t\t\t\tpair[1] = pair[1].replace(/url\\('(?!data:)/gi, \"url('\" + __HOST_LESSON_RESOURCES);\n\t\t\t\t\t\t//add it to the css text\n\t\t\t\t\t\tthis.StyleProperties.cssText += pair[0] + \":\" + pair[1] + \";\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\t//add it to the css text\n\t\t\t\t\t\tthis.StyleProperties.cssText += pair[0] + \":\" + pair[1] + \";\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//has fixed?\n\t\tif (this.StyleProperties.Original[\"position\"] == \"fixed\")\n\t\t{\n\t\t\t//assume this is fixed\n\t\t\tvar bFixed = true;\n\t\t\t//loop through the parents\n\t\t\tfor (var parent = this.Parent; parent; parent = parent.Parent)\n\t\t\t{\n\t\t\t\t//this parent a real iframe?\n\t\t\t\tif (parent.IsRealIFrame)\n\t\t\t\t{\n\t\t\t\t\t//cannot be fixed\n\t\t\t\t\tbFixed = false;\n\t\t\t\t\t//end loop\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//still fixed?\n\t\t\tif (bFixed)\n\t\t\t{\n\t\t\t\t//create fixed position marker\n\t\t\t\tthis.StyleProperties.FixedPosition = true;\n\t\t\t\t//and register with the interpreter\n\t\t\t\t__SIMULATOR.Interpreter.NotifyFixedObject(this.DataObject.Id, this, true);\n\t\t\t}\n\t\t}\n\t\t//switch on its control type tag\n\t\tswitch (Get_String(this.Properties[__NEMESIS_PROPERTY_CONTROL_TYPE], \"\").toLowerCase())\n\t\t{\n\t\t\tcase \"iframe\":\n\t\t\tcase \"frame\":\n\t\t\tcase \"frameset\":\n\t\t\t\t//not the new iFrame?\n\t\t\t\tif (!Get_Bool(this.Properties[__NEMESIS_PROPERTY_CONTROL_TYPE_FORCED], false))\n\t\t\t\t{\n\t\t\t\t\t//no isolation?\n\t\t\t\t\tif (!this.StyleProperties.Original[\"isolation\"])\n\t\t\t\t\t{\n\t\t\t\t\t\t//force it\n\t\t\t\t\t\tthis.StyleProperties.cssText += \"isolation:isolate;\";\n\t\t\t\t\t}\n\t\t\t\t\t//this ie browser (Edge and IE)\n\t\t\t\t\tif (__BROWSER_TYPE == __BROWSER_IE)\n\t\t\t\t\t{\n\t\t\t\t\t\t//no opacity?\n\t\t\t\t\t\tif (!this.StyleProperties.Original[\"opacity\"])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//force it\n\t\t\t\t\t\t\tthis.StyleProperties.cssText += \"opacity:0.99;\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//indicate that this is a real iframe\n\t\t\t\t\tthis.IsRealIFrame = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"html\":\n\t\t\t\t//get its parent object and check its tag\n\t\t\t\tswitch (this.Parent ? Get_String(this.Parent.Properties[__NEMESIS_PROPERTY_CONTROL_TYPE], \"\").toLowerCase() : \"\")\n\t\t\t\t{\n\t\t\t\t\tcase \"iframe\":\n\t\t\t\t\tcase \"frame\":\n\t\t\t\t\tcase \"frameset\":\n\t\t\t\t\t\t//not the new iFrame?\n\t\t\t\t\t\tif (!Get_Bool(this.Properties[__NEMESIS_PROPERTY_CONTROL_TYPE_FORCED], false))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//check if the parent has scrolling = no\n\t\t\t\t\t\t\tvar attributeScrollingNo = false;\n\t\t\t\t\t\t\t//obtain the parent's\n\t\t\t\t\t\t\tvar attributes = this.Parent.StyleProperties ? Get_String(this.Parent.Properties[__NEMESIS_PROPERTY_HTML_ATTRIBUTES], null) : null;\n\t\t\t\t\t\t\t//valid?\n\t\t\t\t\t\t\tif (attributes != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//parse attributes (lowercase it just in case);\n\t\t\t\t\t\t\t\tattributes = JSON.parse(attributes.toLowerCase());\n\t\t\t\t\t\t\t\t//check for scrolling\n\t\t\t\t\t\t\t\tattributeScrollingNo = !Get_Bool(attributes[\"scrolling\"], true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//we need to copy some properties into our parent\n\t\t\t\t\t\t\tvar properties = [\"overflow\", \"overflow-y\", \"overflow-x\"];\n\t\t\t\t\t\t\t//loop through properties\n\t\t\t\t\t\t\tfor (var i = properties.length; i--;)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//get property\n\t\t\t\t\t\t\t\tvar property = properties[i];\n\t\t\t\t\t\t\t\t//get our value\n\t\t\t\t\t\t\t\tvar ourValue = attributeScrollingNo ? \"hidden\" : this.StyleProperties.Original[property];\n\t\t\t\t\t\t\t\t//valid?\n\t\t\t\t\t\t\t\tif (ourValue)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//force on parent\n\t\t\t\t\t\t\t\t\tthis.Parent.StyleProperties.Original[property] = ourValue;\n\t\t\t\t\t\t\t\t\tthis.Parent.StyleProperties.cssText += property + \":\" + ourValue + \";\";\n\t\t\t\t\t\t\t\t\t//parent already loaded?\n\t\t\t\t\t\t\t\t\tif (this.Parent.HTML)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//switch on property\n\t\t\t\t\t\t\t\t\t\tswitch (property)\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tcase \"overflow\":\n\t\t\t\t\t\t\t\t\t\t\t\t//apply directly\n\t\t\t\t\t\t\t\t\t\t\t\tthis.Parent.HTML.style.overflow = ourValue;\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"overflow-x\":\n\t\t\t\t\t\t\t\t\t\t\t\t//apply directly\n\t\t\t\t\t\t\t\t\t\t\t\tthis.Parent.HTML.style.overflowX = ourValue;\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t\tcase \"overflow-y\":\n\t\t\t\t\t\t\t\t\t\t\t\t//apply directly\n\t\t\t\t\t\t\t\t\t\t\t\tthis.Parent.HTML.style.overflowY = ourValue;\n\t\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//regardless of whatever we do to the parent, the HTML always have a forced overflow\n\t\t\t\t\t\t\tthis.StyleProperties.Original[\"overflow\"] = \"visible\";\n\t\t\t\t\t\t\tthis.StyleProperties.Original[\"overflow-x\"] = \"visible\";\n\t\t\t\t\t\t\tthis.StyleProperties.Original[\"overflow-y\"] = \"visible\";\n\t\t\t\t\t\t\tthis.StyleProperties.cssText += \"overflow:visible;overflow-x:visible;overflow-y:visible;\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n}", "function css(element, style) {\n for (const prop in style) {\n element.style[prop] = style[prop]\n }\n}", "function applyCSS(el, css_obj){\n\tfor (var prop in css_obj){\n\t\tel.style[prop] = css_obj[prop];\n\t}\n}", "styleElement(elem, style) {\r\n let element = elem;\r\n for (let i = 0; i < elem.length || i < 1; i ++) {\r\n if (elem.length) element = elem[i];\r\n for (let key in style) {\r\n element.style[key] = style[key];\r\n }\r\n }\r\n }", "function applyStyles(Node, styleObject){\n\t\tvar style = Node.style;\n\t\tObject.keys(styleObject).forEach(function(styleName){\n\t\t\tstyle[styleName] = styleObject[styleName];\n\t\t});\n\t}", "css(el, styles) {\n\n for (var property in styles) {\n el.style[property] = styles[property];\n }\n }", "function chgStyleByID(objectID, property, value) {\r\n\tvar vObjectID = objectID;\r\n\tvar vProperty = property;\r\n\tvar vValue = value;\r\n\tconsole.log(objectID + \" \" + property + \" \" + value);\r\n\tif (vObjectID) {\r\n\t} else {\r\n\t\tconsole.log('No entry found for objectID: ' + vObjectID);\r\n\t}\r\n\tswitch(vProperty) {\r\n\t\tcase 'color':\r\n\t\t\tbreak;\r\n\t\tcase 'textDecoration':\r\n\t\t\tbreak;\r\n\t\tcase 'fontSize':\r\n\t\t\tbreak;\r\n\t\tcase 'backgroundColor':\r\n\t\t\tbreak;\r\n\t\tcase 'borderStyle':\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tconsole.log('Invalid style property: ' + vProperty);\r\n\t}\r\n\tif (vValue == null) {\r\n\t\tconsole.log('No value entered with objectID: ' + vObjectID + ' and property: ' + vProperty);\r\n\t} else {\r\n\t\tdocument.getElementById(vObjectID).style[vProperty] = vValue;\r\n\t}\r\n}", "function applyStyle(elem, style) {\n\tfor (var key in style) elem.style[key] = style[key];\n\tif (style.html) elem.innerHTML = style.html;\n}", "style() {\n this.div.css({\n height: `${this.height}px`,\n width: `${this.width}px`\n });\n }", "function setupStyleContainer(o) {\r\n\t\t\t// If there was another one appended first we need to remove it\r\n\t\t\tif ($(\"#\" + dStyles).length > 0) $(\"#\" + dStyles).remove();\r\n\r\n\t\t\t// Append the style-div\r\n\t\t\td.append('<div id=\"' + dStyles + '\">CSS properties of ' + o[\"oInfo\"] + ':<br />' + getStyleList(o) + '</div>');\r\n\t\t\tvar ds = $(\"#\" + dStyles);\r\n\r\n\t\t\t// Style the style-div\r\n\t\t\tds.css({\r\n\t\t\t\t\"background-color\": \"#AAA\",\r\n\t\t\t\t\"border-style\": \"dotted\",\r\n\t\t\t\t\"border-color\": \"#000\",\r\n\t\t\t\t\"border-width\": \"2px 2px 0\",\r\n\t\t\t\t\"bottom\": \"0px\",\r\n\t\t\t\t\"color\": \"#000\",\r\n\t\t\t\t\"font-size\": \"11px\",\r\n\t\t\t\t\"font-family\": \"Courier New\",\r\n\t\t\t\t\"height\": \"28%\",\r\n\t\t\t\t\"line-height\": \"14px\",\r\n\t\t\t\t\"margin\": \"0\",\r\n\t\t\t\t\"overflow\": \"auto\",\r\n\t\t\t\t\"padding\": \"2px\",\r\n\t\t\t\t\"position\": \"fixed\",\r\n\t\t\t\t\"right\": \"25px\",\r\n\t\t\t\t\"width\": \"40%\"\r\n\t\t\t});\r\n\r\n\t\t\t// Bind edit-in-place-function on spans\r\n\t\t\t$(\".\" + dEdit).each(function() {\r\n\t\t\t\t$(this).bind(\"click\", function() {\r\n\t\t\t\t\teditInPlace($(this), o);\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t}", "function setStyle(el, style, value) {\r\n el.style[style] = value;\r\n}", "function setStyle(ctrl, name, value) {\n\n if (!ctrl || !ctrl.domElement) {\n return;\n }\n\n ctrl.domElement.css(name, value);\n\n if (ctrl.repeatedElements && ctrl.repeatedElements.length) {\n _.each(ctrl.repeatedElements, function (el) {\n\n el.css(name, value);\n });\n }\n }", "function patchDivElement(element) {\n element.setAttribute(\n 'style',\n 'margin-top: 0.5rem; margin-bottom: 0.5rem; \\\n padding-left: 0.5rem; padding-right: 0.5rem; border: solid 1px red;'\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
READ grab all tickets for a student
function find(studentid) { return db("tickets as t") .join("userTickets as u", "u.ticketId", "t.id") .where("studentId", studentid) }
[ "async getNotesListByStudent ( p_auth, p_course, p_studentId ) {\n const AUTHORIZATION = `${p_auth.token_type} ${p_auth.access_token}`\n const PATH = 'Med_get_obser_alumno'\n const result = await fetch( `${ BASE_API_URL }${ BASE_PATH_URL }${ PATH }?p_grcu_sec=${ p_course }&p_fial_sec=${ p_studentId }`, {\n method: 'GET',\n headers: { Authorization: AUTHORIZATION, 'Content-Type': CONTENT_TYPE } \n })\n .then( async ( query ) => await query.json ( ) )\n .catch ( error => console.log ( 'error', error ) ) \n return result.retorno\n }", "function getResponseEntriesForStudent(){\n console.log(\"Getting all exercise response entries for \\\n teacher \" + teacherID +\", lesson \" + lessonID +\" and student \" + studentID);\n dbShellResponsesForStudent.transaction(function(tx){\n tx.executeSql(\"select row_id,teacher_id,student_id,lesson_id,exercise_id,response,scoremark,comment\\\n from responseandmark where teacher_id=? and student_id=? order by lesson_id,exercise_id\",[teacherID,studentID]\n ,renderResponseEntriesForStudent,dberrorhandlerForResponseForStudent);\n },dberrorhandlerForResponseForStudent);\n}", "async getByStudentInTerm(req, res) {\n PointsServices.getByStudentInTerm([\n req.params.studentid,\n req.params.levelid,\n req.params.term,\n req.params.year,\n ])\n .then((result) => {\n res.status(result.status).send({\n status: result.status,\n message: result.message,\n points: result.response.rows,\n });\n })\n .catch((err) => {\n res.status(400).send({\n message: err.message,\n });\n });\n }", "function getEnrolledStudents() {\n var getStudentsPromise = enrollmentService.getStudentEnrollments({\n include: ['student.*'],\n filter: [{\n name: 'section',\n val: $scope.sectionV.id\n }],\n });\n getStudentsPromise.then(function success(data) {\n $scope.enrolledStudents = _.indexBy(data.students, 'id');\n $scope.enrollments = _.indexBy(data.enrollments, 'id');\n refreshEnrollmentsArray();\n // set unenrolled students to all students and then delete each enrolled student with id\n $scope.unenrolledStudents = Object.assign({}, $scope.students);\n for (var student in $scope.enrolledStudents) {\n delete $scope.unenrolledStudents[student];\n }\n refreshStudentArrays();\n }, function error(response) {\n setErrorMessage(response);\n toastService.error(\"The server was unable to get the enrolled students.\" + errorResponse());\n });\n }", "function findById(ticketsid) {\n\treturn db('tickets')\n\t\t.select('ticketsid', 'statusesid', 'helperid', 'studentid', 'title', 'description', 'category')\n\t\t.where({ ticketsid: ticketsid })\n\t\t.first();\n}", "async getAttendanceListByStudent ( p_auth, p_course, p_studentId ) {\n const AUTHORIZATION = `${p_auth.token_type} ${p_auth.access_token}`\n const PATH = 'Med_get_asist_alumno'\n const result = await fetch( `${ BASE_API_URL }${ BASE_PATH_URL }${ PATH }?p_grcu_sec=${ p_course }&p_fial_sec=${ p_studentId }`, {\n method: 'GET',\n headers: { Authorization: AUTHORIZATION, 'Content-Type': CONTENT_TYPE } \n })\n .then( async ( query ) => await query.json ( ) )\n .catch ( error => console.log ( 'error', error ) ) \n return result.retorno\n }", "function getStudentCourses(studentId, token){\n return $http.get('http://localhost:3000/courses/', {headers: {'access_token': token }} ).then(function(res){\n var studentCourses = [];\n\n if(!res){\n //error in code\n }\n\n else{\n\n //check each course in system\n for (var index in res.data){\n course = res.data[index];\n \n var existingIndex = course.students.indexOf(studentId); \n \n //if student exists in student array, student is enrolled in course\n if(existingIndex>-1){\n studentCourses.push(course);\n }\n\n }\n }\n return studentCourses;\n });\n }", "async getByStudentInTerm(req, res) {\n PointsServices.getByStudentInTerm([req.params.studentid,req.body.term])\n .then((result) => {\n res.status(result.status).send({\n status: result.status,\n message: result.message,\n points: result.response.rows,\n });\n })\n .catch((err) => {\n res.status(400).send({\n message: err.message,\n });\n });\n }", "function getStudents() {\n\tvar JSONNOOP={};\n\tJSONNOOP= wrapJson(JSONNOOP, \"getStudentIDs\");\n\tsubmitMiddle(JSONNOOP, displayStudents);\n}", "static async getStudents(teacher_username) {\n\t\tconst res = await db.query(\n\t\t\t`SELECT username, full_name, email\n\t\t\tFROM students \n\t\t\tWHERE teacher_username = $1 ORDER BY username`,\n\t\t\t[teacher_username]\n\t\t);\n\t\tif (!res.rows[0]) {\n\t\t\tthrow new ExpressError(`No students`, 404);\n\t\t}\n\t\tconst students = res.rows.map(s => new Student(s.username, s.full_name, s.email));\n\t\treturn students;\n\t}", "async getStudentsInCourse(courseId) {\n var res = await this.classroom.courses.students.list({courseId: courseId});\n return res.data.students;\n }", "function getStudents() {\n\t// console.log(\"getStudents\");\n\tfetch(\"https://petlatkea.dk/2020/hogwarts/students.json\")\n\t\t.then(res => res.json())\n\t\t.then(fixStudents);\n\tfetchBloodData(allStudents);\n}", "function getTicketList(auth) {\n var sheets = google.sheets('v4');\n\n restService.get('/get_ticket', (req, res)=>{\n sheets.spreadsheets.values.get({\n auth: auth,\n spreadsheetId: '<your_spreadsheet_id>',\n range: 'PA Ticket!A:B',\n }, function(err, response) {\n if (err) {\n console.log('The API returned an error: ' + err);\n return;\n }\n var rows = response.values;\n if (rows.length == 0) {\n console.log('No data found.');\n } else {\n //console.log('Name, Major:');\n res.send(response.values.map(([intent, action, module])=>({intent, action, module})));\n // for (var i = 0; i < rows.length; i++) {\n // var row = rows[i];\n // // Print columns A and E, which correspond to indices 0 and 4.\n // console.log('%s, %s, %s', row[0], row[1], row[2]);\n // }\n }\n }); \n });\n\n}", "async getStudent(ctx, studentId) {\n\t\t// Create the composite key required to fetch record from blockchain\n\t\tconst studentKey = ctx.stub.createCompositeKey('org.certification-network.certnet.student', [studentId]);\n\t\t\n\t\t// Return value of student account from blockchain\n\t\tlet studentBuffer = await ctx.stub\n\t\t\t\t.getState(studentKey)\n\t\t\t\t.catch(err => console.log(err));\n\t\treturn JSON.parse(studentBuffer.toString());\n\t}", "async getByStudents(req, res) {\n PointsServices.getByStudent([req.params.studentid])\n .then((result) => {\n res.status(result.status).send({\n status: result.status,\n message: result.message,\n points: result.response.rows,\n });\n })\n .catch((err) => {\n res.status(400).send({\n message: err.message,\n });\n });\n }", "async getTicketsByUserId(userID){\n return await fetch(ATTENDEES_API_BASE_URI+\"/ticket/\"+userID, {\n method: 'GET',\n }).then(response =>{\n return response.json();\n }).catch(reason => {\n return reason;\n })\n }", "function getall(req, res) {\n Student.find()\n \n .exec(function(err, user) {\n if (user) {\n res.json({ status: true, students: user });\n } else {\n res.json({ status: false, error: \"Students not found\" });\n }\n });\n}", "static getStudentRecords(studentId) {\n return this.getAPI(`/api/absence-records/students/${studentId}`);\n }", "async getBysubjects(req, res) {\n PointsServices.getBysubjects([\n req.params.levelid,\n req.params.subjectname,\n req.params.year,\n ])\n .then((result) => {\n res.status(result.status).send({\n status: result.status,\n message: result.message,\n points: result.response.rows,\n });\n })\n .catch((err) => {\n res.status(400).send({\n message: err.message,\n });\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Choose the first valid path. If `workspace` is undefined then either a workspace or a directory are acceptable. Otherwise it must be a file if a workspace or a directory otherwise.
async getFirstValidPath(startPaths) { const logger = this.services.get(log_1.ILogService); const cwd = process.env.VSCODE_CWD || process.cwd(); for (let i = 0; i < startPaths.length; ++i) { const startPath = startPaths[i]; if (!startPath) { continue; } const paths = typeof startPath.path === "string" ? [startPath.path] : (startPath.path || []); for (let j = 0; j < paths.length; ++j) { const uri = uri_1.URI.file(extpath_1.sanitizeFilePath(paths[j], cwd)); try { const stat = await util.promisify(fs.stat)(uri.fsPath); if (typeof startPath.workspace === "undefined" || startPath.workspace !== stat.isDirectory()) { return { uri, workspace: !stat.isDirectory() }; } } catch (error) { logger.warn(error.message); } } } return undefined; }
[ "function getWorkspace(workspace) {\n switch (typeof workspace) {\n case 'function': return workspace()\n case 'number': return getWorkspaceByIndex(workspace)\n default: return workspace\n }\n}", "static getPrimaryWorkspaceFileSystemPath() {\r\n if (!vscode.workspace.workspaceFolders\r\n || !vscode.workspace.workspaceFolders.length) {\r\n return undefined;\r\n }\r\n const firstRoot = vscode.workspace.workspaceFolders[0];\r\n if (firstRoot.uri.scheme.toLocaleLowerCase() !== 'file') {\r\n throw new Error(`Invalid root scheme: ${firstRoot.uri.scheme}, expected 'file'`);\r\n }\r\n return vscode.workspace.workspaceFolders[0].uri.fsPath;\r\n }", "function ValidateAndReturnPath (source, isDirectory) {\n var Result = null\n //var Exist = exports.FileExist\n\n if (!Config.CurrentWorkingPath) {\n Common.Error('script current working path is empty')\n }\n\n if (!Config.TemplateFolder) {\n Common.Error('template path is empty')\n }\n\n if (Common.PathExsist(Path.join(Config.CurrentWorkingPath , source), isDirectory)) {\n // could be relative to where the script was called from\n Result = Path.join(Config.CurrentWorkingPath , source)\n } else if (Config.OptionFilePath && Common.PathExsist(Path.join(Config.OptionFilePath, source), isDirectory)) {\n // if the option file was used then check if the given path is relative to the option file\n Result = Path.join(Config.OptionFilePath, source)\n } else if (Common.PathExsist(Path.join(Config.TemplateFolder, source), isDirectory)) {\n // the given path could be inside the default template folder\n Result = Path.join(Config.TemplateFolder, source)\n } else if (Common.PathExsist(source, isDirectory)) {\n // the given path could be abosolute\n Result = source\n }\n\n if (!Result) {\n // fail if the path isn't valid\n Common.Error('Directory or file not found - ' + source)\n }\n\n return Result\n}", "function getProjectFromProgram(workspace, program) {\n const projectNames = Object.keys(workspace.projects);\n // If there is only one project, we just return it without looking\n // for other matching projects.\n if (projectNames.length === 1) {\n return workspace.projects[projectNames[0]];\n }\n const basePath = program.getCurrentDirectory();\n // Go through the root file names of the program and return the first project\n // that matches a given root file. We can't just take any arbitrary file in the\n // list since sometimes there can be root files which do not belong to any project.\n for (let filePath of program.getRootFileNames()) {\n const matchingProjects = getMatchingProjectsByPath(workspace, path_1.relative(basePath, filePath));\n if (matchingProjects.length) {\n return matchingProjects[0];\n }\n }\n return null;\n }", "function checkPath () {\n $scope.alreadyOpen_ws = null;\n var loc = $location.path();\n var index = loc.indexOf('workspace/');\n if (index > -1) {\n var workspaceSubstr = loc.substring(index+10);\n var lastindex = workspaceSubstr.indexOf('/');\n if (lastindex > -1) {\n $scope.alreadyOpen_ws = workspaceSubstr.substring(0, lastindex);\n if ($scope.workspaces) { // only open if workspaces already fetched\n reopenWorkspaceFolder();\n }\n }\n }\n }", "function getCurrentGoWorkspaceFromGOPATH(gopath, currentFileDirPath) {\n if (!gopath) {\n return;\n }\n const workspaces = gopath.split(path.delimiter);\n let currentWorkspace = '';\n currentFileDirPath = fixDriveCasingInWindows(currentFileDirPath);\n // Find current workspace by checking if current file is\n // under any of the workspaces in $GOPATH\n for (const workspace of workspaces) {\n const possibleCurrentWorkspace = path.join(workspace, 'src');\n if (currentFileDirPath.startsWith(possibleCurrentWorkspace) ||\n (process.platform === 'win32' &&\n currentFileDirPath.toLowerCase().startsWith(possibleCurrentWorkspace.toLowerCase()))) {\n // In case of nested workspaces, (example: both /Users/me and /Users/me/src/a/b/c are in $GOPATH)\n // both parent & child workspace in the nested workspaces pair can make it inside the above if block\n // Therefore, the below check will take longer (more specific to current file) of the two\n if (possibleCurrentWorkspace.length > currentWorkspace.length) {\n currentWorkspace = currentFileDirPath.substr(0, possibleCurrentWorkspace.length);\n }\n }\n }\n return currentWorkspace;\n}", "static initial() {\n switch (config.get('defaultInputValue')) {\n case config.DEFAULT_ACTIVE_FILE_DIR:\n let editor = atom.workspace.getActiveTextEditor();\n if (editor && editor.getPath()) {\n return new Path(stdPath.dirname(editor.getPath()) + stdPath.sep);\n }\n // No break so that we fall back to project root.\n case config.DEFAULT_PROJECT_ROOT:\n let projectPath = getProjectPath();\n if (projectPath) {\n return new Path(projectPath + stdPath.sep);\n }\n }\n\n return new Path('');\n }", "function tryDirectory(path) {\n for (var f = 0; f < INFERRED_DIRECTORY_FILES.length; f++) {\n try {\n var file_path = cleanPath(path + '/' + INFERRED_DIRECTORY_FILES[f]);\n var file_string = __readFileSync(file_path);\n if (typeof file_string === 'string') {\n return file_path;\n }\n } catch(error) {\n continue;\n }\n }\n return null;\n }", "function defaultPath() {\n const { dirname } = parsedPath;\n let { name } = parsedPath;\n if (name === \"template\" || name === \"index\") {\n name = \"\";\n }\n return path.join(\"/\", dirname, name, \"/\");\n }", "function firstRun ( ws ){\n //const ws = path.resolve ( app.get ( 'workspace' ))\n const source = path.resolve ( 'whoobe/workspace' )\n fs.ensureDir ( ws ).then ( () => {\n console.log ( 'Default Workspace created!')\n fs.copy ( source + '/default' , ws + '/default' )\n }).catch ( error => {\n console.log ( error )\n })\n}", "function spec_path(spec) {\n if (validUrl.is_uri(spec)) {\n return spec;\n }\n return path.resolve(process.cwd(), spec);\n}", "getSPathFromCwd(projectPath) {\n\n let cwd = process.cwd();\n\n // Check if in project\n if (cwd.indexOf(projectPath) == -1) return false;\n\n // Strip project path from cwd\n cwd = cwd.replace(projectPath, '').split(path.sep);\n\n // In component\n if (cwd.length === 2) return cwd[1];\n // In component subfolder 1\n if (cwd.length === 3) return cwd[1] + '/' + cwd[2];\n // In component subfolder 2\n if (cwd.length === 4) return cwd[1] + '/' + cwd[2] + '/' + cwd[3];\n // In component subfolder 3\n if (cwd.length === 5) return cwd[1] + '/' + cwd[2] + '/' + cwd[3] + '/' + cwd[4];\n\n return false;\n }", "function getWorkspaceFolder () {\n\tconst workspaceFolders = vscode.workspace.workspaceFolders;\n\treturn (workspaceFolders && (workspaceFolders.length > 0)) ?\n\t\tworkspaceFolders[0] :\n\t\tnull;\n}", "function initSelectedWorkspace() {\n var selectedName = StorageService.get('selectedWorkspaceName');\n\n if (!selectedName) {\n selectedName = defaultWorkspace.name;\n StorageService.set('selectedWorkspaceName', selectedName);\n }\n\n var currRepos = repositories();\n for (var i = 0; i < currRepos.length; ++i) {\n if (currRepos[i].name == selectedName)\n return currRepos[i];\n }\n\n return null;\n }", "function path(value, arg, index) {\n function parse(value) {\n if(/^\\//.test(value)) return value;\n if(/^~\\//.test(value)) {\n var user = fsutil.home();\n if(user) return pth.resolve(user, value.replace(/^~\\//, ''));\n return value;\n }\n return pth.resolve(process.cwd(), value);\n }\n if(Array.isArray(value)) {\n value.forEach(function(v, i, a) {\n a[i] = parse(v);\n });\n return value;\n }\n return parse(value);\n}", "getSPathFromCwd(projectPath) {\n\n let cwd = process.cwd();\n\n // Check if in project\n if (cwd.indexOf(projectPath) == -1) return false;\n\n // Strip project path from cwd\n cwd = cwd.replace(projectPath, '').split(path.sep);\n\n cwd.shift();\n\n if (cwd.length > 0) {\n return path.join.apply(path, cwd)\n }\n\n return false;\n }", "getResourceOrFolder(resourcePath, resourceType) {\n if (resourcePath.length < 2) {\n throw new Error(`Cannot access resource path with less than 1 arguments, namely \"${resourcePath}\". This is an internal error.`);\n }\n // Get the namespace name, first folder and path\n const [namespaceName, firstFolder, ...path] = resourcePath;\n // Get the namespace resource\n const namespace = this.namespaces.get(namespaceName);\n if (!namespace) {\n throw new Error(`Unknown namespace ${namespace}. This is an internal error.`);\n }\n // Find the resource\n const result = path.reduce((resource, folder) => (resource ? resource.children.get(folder) : undefined), namespace[resourceType].get(firstFolder));\n return result;\n }", "function createOpenWorkspaceOpenFileDialogProps(options) {\n var electron = options.electron, type = options.type, supportMultiRootWorkspace = options.supportMultiRootWorkspace;\n var title = workspace_commands_1.WorkspaceCommands.OPEN_WORKSPACE.dialogLabel;\n // If browser\n if (!electron) {\n // and multi-root workspace is supported, it is always folder + workspace files.\n if (supportMultiRootWorkspace) {\n return {\n title: title,\n canSelectFiles: true,\n canSelectFolders: true,\n filters: WorkspaceFrontendContribution.DEFAULT_FILE_FILTER\n };\n }\n else {\n // otherwise, it is always folders. No files at all.\n return {\n title: title,\n canSelectFiles: false,\n canSelectFolders: true\n };\n }\n }\n // If electron\n if (core_1.OS.Type.OSX === type) {\n // `Finder` can select folders and files at the same time. We allow folders and workspace files.\n return {\n title: title,\n canSelectFiles: true,\n canSelectFolders: true,\n filters: WorkspaceFrontendContribution.DEFAULT_FILE_FILTER\n };\n }\n // In electron, only workspace files can be selected when the multi-root workspace feature is enabled.\n if (supportMultiRootWorkspace) {\n return {\n title: title,\n canSelectFiles: true,\n canSelectFolders: false,\n filters: WorkspaceFrontendContribution.DEFAULT_FILE_FILTER\n };\n }\n // Otherwise, it is always a folder.\n return {\n title: title,\n canSelectFiles: false,\n canSelectFolders: true\n };\n }", "function getInputDirPath () {\n let dirPath = process.argv[2]\n\n if (!fs.existsSync(dirPath)) {\n console.error(`'${dirPath}' not found`)\n return\n }\n\n dirPath = path.resolve(dirPath)\n if (!fs.lstatSync(dirPath).isDirectory()) {\n console.error(`'${dirPath}' is not a directory`)\n return\n }\n return dirPath\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Peaks Divide an array into the maximum number of samesized blocks, each of which should contain an index P such that A[P 1] A[P + 1]. Time complexity: O(N log(log(N))) medium anti slow(performance failed)
function solution(A) { const N = A.length; let peaks = []; if(N < 3) return 0; // If A's length(N) is prime number and has peak, return 1 function isPrime(num) { let result = false; for(let i = 2; i <= Math.floor(Math.sqrt(num)); i++) { if(num % i === 0){ result = false; break; } result = true; } return result; } for(let i = 1; i < N - 1; i++) { if(A[i - 1] < A[i] && A[i + 1] < A[i]) { peaks.push(i); } } if(isPrime(N) && peaks.length !== 0) return 1; // console.log(peaks) if(peaks.length === 0) return 0; if(peaks.length === 1) return 1; let from = 0, to = 0; // peak range let block = 0, idx = 0; // # of blocks <= # of peaks(peaks length) for(let i = peaks.length; i > 2; i--) { if(N % i === 0) { block = N / i; idx = 0; for(let peak of peaks) { from = idx * block; to = (idx + 1) * block; // console.log(from, peak, to) if(peak >= from && peak < to) { idx++; } } if(idx === i) return i; } } }
[ "function allBlocksHavePeak(peaksIndex, numberOfElements, A){\n let allPeakIndex = peaksIndex.slice() // new array\n // console.log(\"ABHPn: \", numberOfElements, allPeakIndex)\n \n let hasPeak = true\n let loopLength = A.length/numberOfElements\n for(let i = 0; i < loopLength; i++){\n // console.log(\"ABHPi: \", i, hasPeak)\n if(hasPeak !== true){\n return false\n }\n hasPeak = false\n for(let j = 0; j < numberOfElements; j++){\n if(i*numberOfElements + j === allPeakIndex[0]){\n hasPeak = true\n allPeakIndex.shift()\n }\n // console.log(\"ABHPj: \", j, 'index', i*numberOfElements + j, hasPeak, allPeakIndex)\n }\n }\n \n return hasPeak\n}", "function pickPeaks(arr) {\n let pos = [], peaks = [];\n\n let repeat = 0;\n\n if(arr.length >= 3) {\n for(let i = 1; i < arr.length - 1; i++) {\n if(arr[i] > arr[i - 1]) {\n if(arr[i] > arr[i + 1]){\n pos.push(i);\n peaks.push(arr[i]);\n } else if(arr[i] === arr[i + 1]){\n repeat = i;\n while(arr[i] === arr[repeat]) {\n repeat++;\n }\n if(arr[i] > arr[repeat]){\n pos.push(i);\n peaks.push(arr[i]);\n }\n }\n } \n }\n }\n\n return {pos, peaks};\n}", "findPeaks() {\n this.nbPeaks = 0;\n var i = 2;\n let end = this.magnitudes.length - 2;\n\n while (i < end) {\n let mag = this.magnitudes[i];\n\n if (this.magnitudes[i - 1] >= mag || this.magnitudes[i - 2] >= mag) {\n i++;\n continue;\n }\n if (this.magnitudes[i + 1] >= mag || this.magnitudes[i + 2] >= mag) {\n i++;\n continue;\n }\n\n this.peakIndexes[this.nbPeaks] = i;\n this.nbPeaks++;\n i += 2;\n }\n }", "function pickPeaks(arr){\n const result = {\n pos: [],\n peaks: []\n }\n\n for (let i = 0; i < arr.length - 1; i++) {\n let leftNum = arr[i-1]\n let rightNum = arr[i+1]\n\n if(leftNum < arr[i] && rightNum < arr[i]) {\n result.pos.push(i)\n result.peaks.push(arr[i])\n } else {\n console.log(arr[i]);\n }\n \n }\n\n return result\n }", "function countPeaks(a) {\n var peaks = 0;\n for (var i = 2; i < a.length - 2; i++) {\n // Considered a peak if the value is greater than it's neighbors up to 2 away.\n if (a[i] > a[i - 1] && a[i] > a[i + 1] && a[i] > a[i - 2] && a[i] > a[i + 2]) {\n peaks++\n }\n }\n return peaks;\n}", "function peakFinder_2(array) {\n let peaks = []\n let startPeak = array[0];\n let endPeak = array[array.length - 1];\n for (var i = 0; i < array.length; i++) {\n let peak = array[i];\n if (startPeak > array[i+1]) {\n peaks.push(startPeak)\n }\n if (peak > array[i - 1] && peak > array[i+1]) {\n peaks.push(peak);\n }\n if (array[array.length - 2] < endPeak) {\n peaks.push(endPeak)\n }\n}\nreturn peaks;\n}", "function solution(A) {\n const peak = [];\n\n for(let i = 1; i < A.length; i++) {\n if(A[i - 1] < A[i] && A[i] > A[i + 1]) peak.push(i);\n }\n // console.log(peak)\n\n if(peak.length < 2) return peak.length; // A = [1, 3, 2] // one flag\n let dist = peak[peak.length - 1] - peak[0];\n let K = Math.floor(Math.sqrt(dist));\n\n // possible to set floor(sqrt(N))+1 flags\n for(let i = K + 1; i > 0; i--) {\n let distSum = 0;\n let count = 1;\n\n for(let j = 0; j < peak.length - 1; j++) {\n let currentPeak = peak[j];\n let nextPeak = peak[j+1];\n\n let diff = Math.abs(nextPeak - currentPeak);\n // console.log(diff, distSum, count, i)\n if((diff + distSum) >= i) {\n count++;\n distSum = 0;\n } else {\n distSum += diff;\n }\n if(count === i) return count;\n }\n }\n}", "function peakFinder(array) {\n var peaks = [];\n if (array[0] > array[1]) {\n peaks.push(0);\n }\n for (var i = 1; i < array.length; i++) {\n if (array[i] > array[i - 1] && array[i] > array[i + 1]) {\n peaks.push(i);\n }\n }\n if (array[array.length - 1] > array[array.length - 2]) {\n peaks.push(array.length - 1);\n }\n return peaks;\n}", "function peakFinder1D(arr) {\t\n\tfor(i=0; i<arr.length; i++) {\n\t\tif(i==0) {\n\t\t\tif (arr[i]>=arr[i+1]) {\n\t\t\t\treturn arr[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if (i==(arr.length-1)) {\n\t\t\tif (arr[i]>=arr[i-1]) {\n\t\t\t\treturn arr[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif ((arr[i]>=arr[i-1])&&(arr[i]>=arr[i+1])) {\n\t\t\t\treturn arr[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}", "function peak(arr){\n for(let i = 1; i < arr.length-1; i++){\n let left = arr.slice(0,i);\n let right = arr.slice(i+1);\n let sumL = left.reduce((sum, el) => sum + el, 0);\n let sumR = right.reduce((sum, el) => sum + el, 0);\n if(sumL === sumR) {\n return i;\n }\n }\n return -1;\n}", "function peak(arr){\n for(let i = 1; i < arr.length-1; i++){\n let left = (arr.slice(0,i).reduce((a,b)=> a+b));\n let right = (arr.slice(i+1).reduce((c,d)=> c+d));\n if(left === right) return i;\n }\n return -1;\n}", "function peak(arr){\n //..\n let peak;\n arr.forEach( (num, i)=>{\n if( i > 0 && i < arr.length-1 ){\n //contains element 0 until i-1\n let leftArr = arr.slice( 0, i).reduce((a,c)=>a+c)\n // contains element i+2 until the last element in the array (arr.length-1)\n let rightArr = arr.slice( i+1, arr.length ).reduce((a,c)=>a+c)\n if(leftArr === rightArr){ peak = i}\n }\n })\n return (peak) ? peak : -1 ;\n}", "function findPeaks2DRegion(input, opt) {\n var options = Object.assign({},{nStdev:3, kernel:smallFilter}, opt);\n var tmp = convolution.matrix2Array(input);\n var inputData = tmp.data;\n var i;\n if(tmp.rows&&tmp.cols){\n options.rows = tmp.rows;\n options.cols = tmp.cols;\n }\n var nRows = options.rows;\n var nCols = options.cols;\n if(!nRows||!nCols){\n throw new Error(\"Invalid number of rows or columns \"+nRows+\" \"+nCols);\n }\n\n var customFilter = options.kernel;\n var cs = options.filteredData;\n if(!cs)\n cs = convolution.fft(inputData, customFilter, options);\n\n var nStdDev = options.nStdev;\n\n var threshold = 0;\n for( i=nCols*nRows-2;i>=0;i--)\n threshold+=Math.pow(cs[i]-cs[i+1],2);\n threshold=-Math.sqrt(threshold);\n threshold*=nStdDev/nRows;\n\n var bitmask = new Array(nCols * nRows);\n for( i=nCols * nRows-1;i>=0;i--){\n bitmask[i]=0;\n }\n var nbDetectedPoints = 0;\n for ( i = cs.length-1; i >=0 ; i--) {\n if (cs[i] < threshold) {\n bitmask[i] = 1;\n nbDetectedPoints++;\n }\n }\n\n var pixels = labeling(bitmask, nCols, nRows, {neighbours:8});\n var peakList = extractPeaks(pixels, inputData, nRows, nCols);\n\n if (peakList.length > 0&&DEBUG) {\n console.log(\"No peak found\");\n }\n return peakList;\n}", "function splitArray(array, slices, slowMap) {\n const items = [...array];\n const nItems = items.length;\n slices = Math.min(slices, nItems);\n\n const parts = [...new Array(slices)].map(_ => []);\n const reserved = Object.keys(slowMap)\n .filter(m => array.includes(m) && slowMap[m].pos)\n .map(m => slowMap[m].pos);\n\n const slows = Object.keys(slowMap)\n .sort((a,b) => slowMap[b].weight - slowMap[a].weight)\n .filter(e => items.includes(e));\n\n for (let i = 0; i < slows.length; i++) {\n const item = slows[i];\n if (items.includes(item)) {\n getFasterSlice(item, parts, slowMap, reserved).push(item);\n items.splice(items.indexOf(item), 1);\n }\n }\n\n for (i = 0; i < items.length; i++) {\n const item = items[i];\n getFasterSlice(item, parts, slowMap, reserved).push(item);\n }\n return parts;\n}", "function solution(A) {\n const peak = [];\n\n for(let i = 1; i < A.length; i++) {\n if(A[i - 1] < A[i] && A[i] > A[i + 1]) peak.push(i);\n }\n // console.log(peak)\n\n if(peak.length < 2) return peak.length; // [1, 3, 2] // one flag\n let dist = peak[peak.length - 1] - peak[0];\n\n const placeFlags = num => {\n let target = num;\n let start = peak[0];\n let i = 1;\n\n while(i < peak.length) {\n if(peak[i] - start >= num) {\n target--;\n if(target === 0) return true;\n }\n i++;\n }\n return false;\n }\n\n let left = 1;\n // let right = peak.length;\n let right = Math.floor(Math.sqrt(dist));\n let mid;\n\n while(left <= right) {\n mid = Math.floor((left + right) / 2) \n if(placeFlags(mid) === true) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n // console.log(left, mid, right)\n return mid;\n}", "function peakFinder(numbers) {\n var peaks = [];\n\n for(var i = 0; i < numbers.length; i ++){\n var prev = numbers[i - 1];\n var next = numbers[i + 1];\n var maybePeak = numbers[i]\n\n if (i === 0 && maybePeak > next) {\n peaks.push(i);\n }else if (maybePeak > prev && maybePeak > next) {\n peaks.push(i);\n } else if (i === numbers.length-1 && maybePeak > prev) {\n peaks.push(i);\n }\n }\n return peaks;\n}", "function getRepeatingSegments(arr) {\n var a = [], b = [], repeatingElements = [], prev;\n\n arr.sort();\n for ( var i = 0; i < arr.length; i++ ) {\n if ( arr[i] !== prev ) {\n a.push(arr[i]);\n b.push(1);\n } else {\n b[b.length-1]++;\n }\n prev = arr[i];\n }\n\n for (var j=0; j<a.length; j++) {\n if (b[j] > 1) {\n \trepeatingElements.push(a[j]);\n }\n }\n return repeatingElements;\n }", "function peak(arr){\n let total = arr.reduce((a,b)=> a+b)\n let sum = 0 \n for(let i=0; i < arr.length; i++){\n if(sum === (total - arr[i])/2){\n return i\n } \n sum = sum + arr[i]\n }\n return -1\n }", "function pivotIndex(arr) {\n const sum = arr.reduce(function(acc, val) {\n acc += val;\n return acc;\n }, 0);\n let p1 = 0;\n let p2 = arr.length - 1;\n let sum1 = arr[p1];\n let sum2 = arr[p2];\n let remainder;\n\n while (p1 < p2) {\n remainder = sum - (sum1 + sum2);\n if (sum1 > sum2 && remainder > 0) {\n p2++;\n sum2 += arr[p2];\n } else if (sum2 > sum1 && remainder > 0) {\n p1++;\n sum1 += arr[p1];\n } else if (sum1 > sum2 && remainder < 0) {\n p1++;\n sum1 += arr[p1];\n } else if (sum2 > sum1 && remainder < 0) {\n p2++;\n sum2 += arr[p2];\n } else if (sum1 === sum2) {\n p1++;\n p2--;\n sum2 += arr[p2];\n sum1 += arr[p1];\n } else if(remainder === 0) {\n p2--;\n sum2 += arr[p2];\n }\n if (sum1 === sum2 && p1 === p2) return p1;\n }\n return -1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send data of a widget
send_widget_data$(app_id, widget_id, data) {}
[ "send(e, data) {\n this.mainWindow.webContents.send(e, data);\n }", "function sendDataToElm(action, data) {\r\n app.ports.dataForElm.send({ action: action, data: data });\r\n}", "function sendData (client, method, data) {\n\t\tvar packet = { methodName : method, data : data };\n\t\t\n\t\tclient.fn.send(\"EDITOR\", packet);\n\t}", "function init_widget_data( req, instr, widget )\n{\n}", "function senGuiData()\n{\n\tvar datasend={\n\t\tevent:\"guidata\"\n\t}\n\tqueryDataGet(\"php/api_process.php\",datasend,function(res){\n\t\t//nhan du lieu tu server tra ve\n\t\talert_info(res);\n\t});\n\tqueryDataPost(\"php/api_process_post.php\",datasend,function(res){\n\t\t//nhan du lieu tu server tra ve\n\t\talert_info(\"Post:\"+res);\n\t});\n}", "function sendBar(data){\r\n nspBar.emit('bar', data);\r\n}", "sendKeyboard(data) {\n this.webSocket.send('k' + data);\n }", "function widgetHandler( wid , val ){\n\t\t\tvar msg = \">> SUBMIT (\" + wid + \") -- '\" + val + \"' <<\";\n\t\t\t//console.log(msg);\n\t\t\tflashMessage(wid,msg,3);\n\t\t}", "function sendDrawing(data) {\n console.log(data);\n // var newdata = client.broadcast.emit(data);\n //brodcast to all clients on the server except for the client sending data\n client.broadcast.emit('mouse', data);\n // console.log(\"new data: \" + newdata);\n }", "function sendMessage(type){\n parent.postMessage({type: type, data: {here: 'your data sample'}}, '*')\n}", "function send_data(data=false) {\n if(data == false) {\n console.log(\"Error - No Data to send from <send_data>\");\n }\n\n // Send data to the renderer process\n mainWindow.webContents.send(\"fromMain\", data);\n}", "emitData( $origin = '' ) {\n EventBus.$emit('caption_data', this.data, $origin);\n }", "function sendData(data) {\n socket.emit('send figure', data);\n}", "sendClickedVenue(key){\n this.props.sendData(key);\n }", "sendData() {\r\n this.props.parentCallback(this.state.commoditieFF);\r\n }", "emit(name, data) {\n this.parent.postMessage({\n type: 'emit',\n value: {name, data}\n }, this.parentOrigin)\n }", "send ( wuid ) {\n\t\t // prepare data to be send to server\n\t }", "sendKeyboard(data) {\n if (this.connection) {\n this.connection.sendKeyboard(data);\n }\n }", "function send_data(data) {\n // Send data to supervisor.\n if (supervisor?.conn) {\n supervisor.conn.send(data);\n }\n\n console.log(data);\n\n // Send data to server\n socket.emit(\"concent_data\", ROOM_ID, data);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output: "123" 3 Turn an array of voter objects into a count of how many people voted. Note: You don't necessarily have to use reduce for this, so try to think of multiple ways you could solve this.
function totalVoters(arr){ const result = arr.reduce(function(total, voters){ if (voters.voted){ return total += 1; } return total; },0); return result; }
[ "function totalVotes(arr) {\n return voters.reduce(function (final, voter){\n if(voter.voted){\n final++\n }\n return final\n }, 0) \n }", "function totalVoters(arr) {\n return arr.reduce(function(x, y){\n\n return x + y.voted } , 0);\n }", "function voterResults(arr) {\n return arr.reduce(\n function (final, voter) {\n if (voter.age >= 18 && voter.age <= 25) {\n final.youth++;\n if (voter.voted) {\n final.youthVoted++;\n }\n }\n if (voter.age >= 26 && voter.age <= 35) {\n final.mid++;\n if (voter.voted) {\n final.midVoted++;\n }\n }\n if (voter.age >= 36 && voter.age <= 55) {\n final.old++;\n if (voter.voted) {\n final.oldVoted++;\n }\n }\n return final;\n },\n { youth: 0, mid: 0, old: 0, youthVoted: 0, midVoted: 0, oldVoted: 0 }\n );\n}", "function totalVotes(arr) {\n var sum = arr.reduce(function(total, voter) {\n return total + voter.voted\n },0) \n return sum\n}", "function totalVotes(arr) {\n count = 0;\n initialValue = 0;\n if (Array.isArray(arr)){\n count = voters.reduce(function (total, currentValue) {\n if (currentValue.voted === true) {\n total++;\n }\n return total;\n },initialValue);\n }\n\n console.log(count);\n}", "function voterResults2(arr) {\n\n return voters.reduce((acc, voter) => {\n \n if (numYoungPeople(voter) == true) {\n console.log(voter.voted);\n console.log(acc);\n //return voter.voted = 1 + acc; // Work\n return acc + 1;\n //return {numYoungPeople: voter.voted = 1 + acc}`;\n //voto = voter.name;\n //voter.voted + acc;\n //return acc;\n }\n return acc;\n }, 0)\n}", "function voteTallyer() {\n for (var voter in votes) {\n for (var position in voteCount) {\n if (voteCount[position].hasOwnProperty(votes[voter][position])) {\n voteCount[position][votes[voter][position]] += 1;\n }\n else {\n voteCount[position][votes[voter][position]] = 1;\n }\n }\n }\n}", "getVotes(votes) {\n let voteCount = 0;\n for (const vote in votes) {\n voteCount += votes[vote].value;\n }\n return voteCount;\n }", "function voteTallyer() {\r\n for (var voter in votes) {\r\n for (var position in voteCount) {\r\n if (voteCount[position].hasOwnProperty(votes[voter][position])) {\r\n voteCount[position][votes[voter][position]] += 1;\r\n }\r\n else {\r\n voteCount[position][votes[voter][position]] = 1;\r\n }\r\n }\r\n }\r\n}", "function countVoteArray(voteArray){\n\tlet count = 0;\n\tvoteArray.forEach(function(vote){\n\t\tif (!vote.negatedBy)\n\t\t\tcount++;\n\t});\n\treturn count;\n}", "function whoVoted(people) {\n return people.reduce(\n function (final, vote) {\n if (vote.voted) {\n final.didVote++;\n } else {\n final.didntVote++;\n }\n return final;\n },\n { didVote: 0, didntVote: 0 }\n );\n}", "function simpleCount(candidates, votes, index) {\n var i = index || 0;\n var a = new Array(candidates.length);\n a.setAll(0);\n \n var j = 0, n = votes.length;\n for (j; j < n; j++) {\n a[candidates.indexOf(votes[j].vote[i])]++;\n }\n return a;\n}", "function countVotes(votes) {\n const tally = {};\n for (let i = 0; i < votes.length; i++) {\n if (tally[votes[i]]) {\n tally[votes[i]++];\n } else {\n tally[votes[i]] = 1;\n }\n }\n return tally;\n}", "function countVotes(votes) {\n // reduce the array into an obj\n // keep a counter \n // array.sort numVotesect.entries to search for the highest value\n // use a Stack to keep track of the previously added names\n let numVotes = {};\n let winner;\n\n const voters = votes.reduce( (accVotes, vote) => {\n if (!(vote in accVotes)) {\n accVotes[vote] = 0;\n } \n accVotes[vote]++;\n }, {});\n\n console.log(voters);\n\n for (let i = 0; i < votes.length; i++) {\n console.log(numVotes)\n if (!numVotes.hasOwnProperty(votes[i])) {\n numVotes[votes] = 0;\n } \n numVotes[votes]++;\n // if numVotes[winner] is less or equal then numVotes[votes[i]]\n // then replace votes[i] if equal then \n // if numVotes[winner] <= numVote[votes[i]] && winner < votes[i]\n // set winner to votes[i]\n }\n\n console.log(counting)\n\n\n return counting;\n}", "getVotes() {\n\t\treturn this.votes.reduce((a, b) => a.length + b.length);\n\t}", "function getVoteCount(votes) {\n var { upvotes, downvotes } = votes\n return upvotes - downvotes\n }", "function countVotes(){\n\tvar voteCounter = task.type.participantCount;\n\ttask.options.forEach(function(e,i){\n\t\tvoteCounter-=e.count;\n\t});\n\tvotes=voteCounter;\n}", "function countVotes(votes, candidateName) {\n var sumVote = 0;\n for (var i = 0; i < votes.length; i++) {\n if (votes[i] === candidateName) sumVote++\n }\n return sumVote\n}", "getNumberOfUniqueVotes(votes){\n let voterPool = [];\n for(let i = 0; i < votes.length; i++){\n let name = votes[i];\n\n if(!voterPool.find(function (username) {//if name is not already in voterPool\n return (username === name);\n })){\n voterPool.push(name);// add it to the voterPool\n }\n\n }\n return voterPool.length;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
HELPER FUNCTIONS Sets padding on the content based on navbar height On smaller screens navbar displays in two lines and doubles in size. The function sets body paddingtop equal to the navbar height
function setTopPadding() { var padding = $('#main-nav.navbar div.container').css('height'); $content.css('padding-top', padding ); }
[ "function settleBodyPadding(){\n var Body = document.getElementById(\"myFullBody\");\n var NavBar = document.getElementById(\"myNavBar\");\n Body.style.paddingTop = (NavBar.clientHeight+10)+\"px\"; // Assigning the top padding to the client height (height + vertical padding) of the Nav-Bar.\n return 0;\n}", "function paddingBody() {\n\tvar styles = {\n \"padding-top\":padding\n\t\t};\n $('body').css(styles);\n}", "setBodyPaddings(){\n let body = document.body;\n let navbar = ReactDOM.findDOMNode(this);\n let navHeight = navbar.offsetHeight+'px';\n if(this.props.position === 'top'){\n body.style.paddingTop = navHeight\n body.style.paddingBottom = 0\n }else{\n body.style.paddingBottom = navHeight\n body.style.paddingTop = 0\n }\n\n }", "function fixMainPadding() {\r\n\t$(\"#mainpage\").css('padding-top', ($nav.outerHeight() + 8) + 'px');\r\n}", "function fixNavHeightOnClick() {\n var headerDivHeight = $(\".container-fluid\").height()\n var navbarMaxFontSize = $(\".navbar\").css(\"fontSize\")\n navbarMaxFontSize = parseInt(navbarMaxFontSize)\n if (scrollY <=headerDivHeight) {\n document.getElementById(\"tabletNavbar\").style.fontSize = (0.5*navbarMaxFontSize)+\"px\"\n // sets the top-padding IAW the current Nav Height\n setTheTopPaddingWithRespectToNavHeight() \n }\n \n }", "function bodyPadding() {\n let headerHeight = $('header').height();\n let footerHeight = $('footer').height();\n $('body').css({\"padding-top\": headerHeight + 20 + \"px\",\"padding-bottom\": footerHeight, \"min-height\": $(window).height()});\n}", "function topPaddingForFixedNavConpensation() {\n\t\t\tvar anchorHeight = siteNavHeight + globalPadding;\n\t \t\t$( \"main\" ).css( \"padding-top\", siteNavHeight );\n\t \t\t$( \".anchor\" ).css( \"top\", -anchorHeight );\n\t\t}", "function calculateBodyPaddingTop() {\n bodyPaddingTop = parseInt(body.css('padding-top'));\n }", "function updateSiteInnerTopPadding(){\n\n\t\t// Set target element to receive padding-top\n\t\tvar el = $( \"main.content > article.page > .entry-content > div.welcome\" );\n\n // Get bottom padding of target element -- to be used as \"default\" for top padding\n var pb = $(el).prop('style')['padding-bottom'];\n\n\t\t// Only needed above 1023px\n\t\tif ( window.innerWidth > 1023 ) {\n\n\t\t\t// Only required if sticky nav is on\n\t\t\tif ( $( \".site-header\" ).hasClass( \"sticky\" ) ) {\n\n\t\t\t\t// Get header height and set as NewHeight var\n\t\t\t\tvar hh = getSiteHeaderHeight();\n\n\t\t\t\t// Add padding to existing padding\n\t\t\t\tvar nh = parseInt(hh + 30);\n\n\t\t\t\t// Manually set target element padding-top\n\t\t\t\t$( el ).css(\"padding-top\", nh);\n\t\t\t}\n\n\t\t} else {\n\n // Get target element padding-top value\n var elpt = $( el ).css(\"padding-top\");\n\n // If target element padding-top is not the same as padding-bottom\n if ( elpt !== pb ) {\n\n // Set target element padding-top same as padding-bottom\n $( el ).css(\"padding-top\", pb);\n\n }\n\n }\n\n\t}", "function set_body_top() {\n\n\t$('body').css('padding-top', '');\n\n\tvar topAds = $('#ads-top'),\n\t\tbody_padTop = parseInt($('body').css('padding-top'), 10)\n\t\t;\n\tif (topAds.is(\":visible\")) {\n\t\tvar adsHeight = topAds.height();\n\t\t$('body').css('padding-top', (body_padTop + adsHeight));\n\t}\n}", "function setMainPaddingTop(){\n\tvar headerHeight = getHeaderHeight();\n\t$('.main').css('padding-top', headerHeight + 20);\n}", "function bodyOffset() {\n var page = document.querySelector('.page__wrapper'),\n headerHeight = document.querySelector('.header').clientHeight;\n\n if(!document.body.classList.contains('page--main')) {\n page.style.paddingTop = headerHeight + 'px';\n }\n }", "updateBodyPadding() {\n const visible = this.position !== Composer.PositionEnum.HIDDEN &&\n this.position !== Composer.PositionEnum.MINIMIZED;\n\n const paddingBottom = visible\n ? this.computedHeight() - parseInt($('#app').css('padding-bottom'), 10)\n : 0;\n $('#content').css({paddingBottom});\n }", "function adjustSpacing() {\n $(\".content-wrap\").css({\n // Page content padding bottom for footer\n \"padding-bottom\":$(\"footer\").outerHeight(),\n // Page content padding top for navbar\n \"padding-top\":$(\"nav\").outerHeight()\n });\n}", "function adjustContentPadding() {\n var topElem = document.getElementsByClassName('oj-applayout-fixed-top')[0];\n var contentElem = document.getElementsByClassName('oj-web-applayout-content')[0];\n var bottomElem = document.getElementsByClassName('oj-applayout-fixed-bottom')[0];\n\n if (topElem) {\n contentElem.style.paddingTop = topElem.offsetHeight+'px';\n }\n if (bottomElem) {\n contentElem.style.paddingBottom = bottomElem.offsetHeight+'px';\n }\n }", "function paddingequlheight(){\n\t\tvar $_height = jQuery(window).height();\n\t\tjQuery('body.bt-homevthree .bt-wrapper').css({'padding-top': $_height + 'px'});\n\t}", "function changeNavbarHeight() {\n var navbar = $('#navbarSettings');\n\n $(window).scroll(function () {\n var topOffset = $(window).scrollTop();\n\n //make navbar smaller\n if (topOffset > 0) {\n navbar.addClass('navbar-sm');\n } else {\n navbar.removeClass('navbar-sm');\n }\n\n //if navbar is transparent, then add backgrount after 10px scrolling down\n if (topOffset > 10 && navbar.hasClass('navbar-height')) {\n navbar.removeClass('navbar-height').css('box-shadow', '0 2px 5px rgba(0, 0, 0, 0.2)');\n }\n if (topOffset <= 10 && !navbar.hasClass('navbar-height')) {\n navbar.addClass('navbar-height').css('box-shadow', 'none');\n }\n });\n }", "function bannerPadding(){\n var headerHeight = $('.header.fixed--header').height();\n $('.banner__single__content').css('padding-top', headerHeight);\n $('.breadcamb__inner').css('padding-top', headerHeight);\n }", "function placeNavbarBottom() {\n var viewportheight = $(window).outerHeight(true);\n var titleContainer = $('#title-container').outerHeight(true);\n\n var diff = viewportheight - titleContainer;\n\n $('#navigation').css('margin-top', diff - 50);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Utility function to change days in a date
function changeDays(days, date) { const result = new Date(date); result.setDate(result.getDate() + days); return result; }
[ "function date_change(date, num) {\n date.setDate(date.getDate() + num);\n}", "function translateSweepDate(days){\n let thisDate = new Date('12/31/1899');\n thisDate.setDate(thisDate.getDate() + days);\n let outVal = thisDate.toLocaleDateString('en-US', {month: '2-digit', day: '2-digit'});\n return outVal;\n}", "function handleDay(d) {\n if (d < 7) {\n d += 1;\n } else if (d === 7) {\n d = 1;\n }\n return d;\n }", "function moveOneDay(date) {date.setTime((date.getTime() + 24 * 60 * 60 * 1000)); }", "function adjustDate(num) {\n let today = new Date();\n today.setDate(today.getDate() - num);\n let date = formatDate(today);\n return date;\n}", "function adjustDate(date) {\n if (date <= 4) {\n return 18;\n } else {\n return date + 18;\n }\n}", "toSunday(date) {\n while(days[date.getUTCDay()] !== \"Sunday\") {\n date.setDate(date.getDate() + 1);\n }\n }", "function incrementDay(date) {\n if (date.getDate()>=(monthDays(date.getMonth(),date.getYear())-1)) { // this accounts for leap years by putting 29 days in Feb as needed\n date = incrementMonth(date); // incrementMonth will rollover to January and advance the year if necessary\n date.setDate(1); // month is 0-11, date is 1-31\n }\n else {\n date.setDate(date.getDate()+1);\n }\n return date;\n}", "function changeDate(cd)\n{\n //Current date on inputDate\n var inputD= document.getElementById(\"inputdate\").value;\n if(inputD != \"\")\n {\n \n var newDay=new Date(inputD);\n // it increment day by one\n if(cd == 0){\n newDay.setDate(newDay.getDate()- 1);\n } else if(cd ==1){\n //it decreases the date by one \n newDay.setDate(newDay.getDate()+1);\n }\n \n var dateNew = newDay.getDay();\n //upgrade the input date\n document.getElementById(\"inputdate\").valueAsDate= new Date(newDay);\n //upgrade label for input date\n document.getElementById(\"labelDay\").innerHTML=getDayName(dateNew);\n //console.log(CurrrenteDate);\n\n //call to function getBookingavailable() to retrieve and fill data\n getBookingAvailable();\n \n }\n}", "function setDate(){\r\n if (day > monthDays[month]) {\r\n day = day % monthDays[month];\r\n if (month == 11) {\r\n month = 0;\r\n year++;\r\n }\r\n else month++;\r\n }\r\n}", "function addDaysToDate(dateVal, numDays ) {\r\n var date = new Date(dateVal);\r\n var newdate = new Date(date);\r\n newdate.setDate(newdate.getDate() + numDays);\r\n var dd = newdate.getDate();\r\n var mm = newdate.getMonth() + 1;\r\n var y = newdate.getFullYear();\r\n\r\n var someFormattedDate = mm + '/' + dd + '/' + y;\r\n return someFormattedDate;\r\n}", "function setDay(d1, d2) { d1.setTime(d2.getTime()) }", "function getDateShifted(date, days) {\n return new Date(parseInt(date.getTime()) + parseInt(numDaysInMS(days)));\n }", "function addWorkDaysToDate_old(paramDate, paramDays) {\r\n var startDate = paramDate;\r\n var days = paramDays;\r\n if (days <= 0) {\r\n return startDate;\r\n }\r\n days -= 1;\r\n if (getDay(startDate) >= 6) {\r\n // startDate.setDate(startDate.getDate()+8-getDay(startDate));\r\n }\r\n var weekEnds = Math.floor(days / 5);\r\n var additionalDays = days - (5 * weekEnds);\r\n if (getDay(startDate) + additionalDays >= 6) {\r\n weekEnds += 1;\r\n }\r\n days += (2 * weekEnds);\r\n var endDate = startDate;\r\n endDate.setDate(startDate.getDate() + days);\r\n return endDate;\r\n}", "setDateToOneDayEarlier(date) {\r\n\t\tlet daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; //ignoring leap year...\r\n\t\tdate = date.split('-').map(i => parseInt(i));\r\n\t\tif(date[2].toString() === \"01\" || date[2] === 1){\r\n\t\t\tif(date[1].toString() === \"01\" || date[1] === 1) {\r\n\t\t\t\tdate[1] = 12;\r\n\t\t\t\tdate[0] = date[0]-1;\r\n\t\t\t\tdate[2] = daysInMonth[date[1]-1];\r\n\t\t\t} else {\r\n\t\t\t\tdate[1] = date[1]-1;\r\n\t\t\t\tdate[2] = daysInMonth[date[1]-1];\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tdate[2] = date[2]-1;\r\n\t\t}\r\n\r\n\t\tdate = date.join(\"-\");\r\n\t\tif(date.length === 9) {\r\n\t\t\tdate = date.split('-');\r\n\t\t\tif(date[1].length === 1) {\r\n\t\t\t\tdate[1] = \"0\".concat(date[1]);\r\n\t\t\t\tdate = date.join(\"-\");\r\n\t\t\t}\r\n\t\t\tif(date[2].length === 1) {\r\n\t\t\t\tdate[2] = \"0\".concat(date[2]);\r\n\t\t\t\tdate = date.join(\"-\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn date;\r\n\t}", "function increment_day(){\r\n\t\r\n\tif (day == 31 && (month == 2 || month == 4 || month == 6 || month == 9 || month == 11))\r\n\t{}\t//do nothing\r\n\telse if (month == 2 && day == 30)\r\n\t{}\t//do nothing\r\n\telse if (month == 12 && day == 31)\r\n\t{\r\n\t\tmonth = 1;\r\n\t\tday = 1;\r\n\t\tupdateDate = true;\r\n\t}\r\n\telse if (day == 30 && (month == 2 || month == 4 || month == 6 || month == 9 || month == 11))\r\n\t{\r\n\t\tmonth++;\r\n\t\tday = 1;\r\n\t\tupdateDate = true;\r\n\t}\r\n\telse if (day == 31)\r\n\t{\r\n\t\tmonth++;\r\n\t\tday = 1;\r\n\t\tupdateDate = true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tday++;\r\n\t\tupdateDate = true;\r\n\t}\r\n\r\n}", "function addDays(days) {\n date.setDate(date.getDate() + days);\n}", "function dayDelta (day, delta) {\n let newDay = new Date(new Date(day).getTime() + delta)\n return formatDayString(newDay)\n}", "function nextDay (data_, nr_days) {\n// var nxt_day = new Date(data_);\n if (!nr_days) {\n nr_days = 1;\n }\n\n/* Este cálculo não estava a devolver sempre a data correta. REDIRECIONADA PARA addDays()\n * var tmp = new Date(nxt_day).getDate();\n console.log(\"data:\"+data_+\" nr_days:\"+nr_days+\" tmp:\"+tmp+\" set date:\" + nxt_day.setDate( tmp + nr_days));\n return formatDate(nxt_day.setDate( new Date(nxt_day).getDate() + nr_days), 'YYYY-MM-DD');\n*/\n return formatDate(addDays(data_,nr_days), 'YYYY-MM-DD');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Upload VCL snippets to the Fastly service
function uploadVcl() { let activate_vcl_flag = false; if ($('#fastly_activate_vcl').is(':checked')) { activate_vcl_flag = true; } $.ajax({ type: "POST", url: config.vclUploadUrl, data: { 'activate_flag': activate_vcl_flag, 'active_version': active_version }, showLoader: true }).done(function (response) { if (response.status === true) { modal.modal('closeModal'); successVclBtnMsg.text($.mage.__('VCL file is successfully uploaded to the Fastly service.')).show(); } else { resetAllMessages(); showErrorMessage(response.msg); } }); }
[ "function swift_container_main_lib_upload(token){\n console.log(\"Uploading Main Library Files\");\n res1.write(\"Uploading Main Library Files<br>\");\n //upload to swift container\n fs.createReadStream('public/uploads/'+mainLibFileName).pipe(request.put({\n url: swift_url+'/scripts/'+mainLibFileName,\n json: true,\n headers: {\n 'Content-Type':'application/json',\n 'X-Auth-Token' : token\n }\n },(err,response,body)=>{\n \n if(err){\n console.log(err);\n return res1.end(err);\n }\n console.log(\"Main Library Files uploaded successfully\");\n res1.write(\"Main Library Files uploaded successfully<br>\");\n swift_container_lib_upload(token);\n })\n ) \n }", "function createSnippet(title, code, channel) {\n console.log(title, code, channel)\n return new Promise((resolve, reject) => {\n bot.api.files.upload({\n token: token,\n content: code,\n filetype: 'javascript',\n filename: title,\n channels: channel\n },function(err,response) {\n if(err) {\n console.log('fileError')\n reject(err)\n }\n else {\n console.log('file:', response)\n resolve(response.ok)\n }\n })\n })\n}", "function sendCode() {\n let codeForm = new FormData();\n let xhttp = new XMLHttpRequest();\n Blockly.Python.INFINITE_LOOP_TRAP = null;\n let code = PREAMBLE + Blockly.Python.workspaceToCode(mainWorkspace);\n codeForm.append(\"codeArea\", code);\n codeForm.append(\"fileName\", document.getElementById(\"fileNameTextBox\").value);\n xhttp.open(\"POST\", \"/copy_text\", true);\n addLoadEvent(xhttp);\n xhttp.send(codeForm);\n}", "function swift_container_main_lib_upload(token){\n console.log(\"Uploading Main Library Files\");\n res1.write(\"Uploading Main Library Files<br>\");\n //upload to swift container\n fs.createReadStream('public/uploads/'+mainLibFileName).pipe(request.put({\n url: swift_url+'/scripts/'+mainLibFileName,\n json: true,\n headers: {\n 'Content-Type':'application/json',\n 'X-Auth-Token' : token\n }\n },(err,response,body)=>{\n \n if(err){\n console.log(err);\n return res1.end(err);\n }\n console.log(\"Main Library Files uploaded successfully\");\n res1.write(\"Main Library Files uploaded successfully<br>\");\n create_job_binary(token);\n })\n ) \n }", "function swift_container_input_upload(token){\n console.log(\"Uploading Input Files\");\n res1.write(\"Uploading Input Files<br>\");\n //upload to swift container\n fs.createReadStream('public/uploads/'+txtFileName).pipe(request.put({\n url: swift_url+'/hadoop/input',\n json: true,\n headers: {\n 'Content-Type':'application/json',\n 'X-Auth-Token' : token\n }\n },(err,response,body)=>{\n \n if(err){\n console.log(err);\n return res1.end(err);\n }\n console.log(\"Input Files uploaded successfully\");\n res1.write(\"Input Files uploaded successfully<br>\");\n swift_container_script_upload(token);\n })\n ) \n }", "function uploadToCloud(){\n\n }", "function swift_container_input_upload(token){\n console.log(\"Uploading Input Files\");\n res1.write(\"Uploading Input Files<br>\");\n //upload to swift container\n fs.createReadStream('public/uploads/'+txtFileName).pipe(request.put({\n url: swift_url+'/hadoop/input',\n json: true,\n headers: {\n 'Content-Type':'application/json',\n 'X-Auth-Token' : token\n }\n },(err,response,body)=>{\n \n if(err){\n console.log(err);\n return res1.end(err);\n }\n console.log(\"Input Files uploaded successfully\");\n res1.write(\"Input Files uploaded successfully<br>\");\n swift_container_main_lib_upload(token);\n })\n ) \n }", "async createAndUploadBundle () {\n // implement if needed\n }", "preSubmit() {\n const sources = this.processSources();\n this.code = new File([sources.pythonCode], \"main.py\", {\n type: \"text/x-python\",\n });\n const XML = new File([sources.xml], \"main.xml\", {\n type: \"text/xml\",\n });\n\n this.files.codeFile = this.code;\n this.files.xmlBlocklyFile = XML;\n this.language = \"Blockly\";\n\n this.createFileSvg(sources.urlSVG, \"blocks.svg\");\n }", "function handleSample(str){\n log(\"handleSample\");\n\n editor.getSession().setValue(str); // add the content\n updateSandbox(); // load the sample into an iframe\n }", "function start() {\n // Create main workspace.\n workspace = Blockly.inject('blocklyDiv', {\n toolbox: toolbox,\n });\n\n workspace.addChangeListener(event => {\n const code = javascript.javascriptGenerator.workspaceToCode(workspace);\n document.getElementById('generatedCodeContainer').value = code;\n });\n}", "function pass3_upload(host, accessToken, sourceId, productList) {\n\tconsole.log(\"Pass 3: Upload to TEA\")\n\t\n\t//ZZZZ It might be necessary to rename some of the fields, to match the API that will be called.\n\tproductList.each(function(record){\n\t\t//record.abc = record.def\n\t\t//delete record.def\n\t});\n\n\t// Prepare the input to the RESTful API\n\tvar json = {\n\t\taccess_token: accessToken,\n\t\tsource_id: sourceId,\n//\t\t \"overwrite_existing\": true,\n\t\tproducts: productList\n\t};\n\t\n\t// Send it to TEA via the RESTful API\n\t//ZZZZZ This URL needs to be changed\n\tvar url = 'http://' + host + '/product_PHIL';\n\t\n\tconsole.log(' - calling TEA to update categoryMap:')\n\t// console.log(' url=>' + url + ' (POST)')\n\t// console.log(' data=>\\n', json)\n\t\n\trequest({\n\t\tmethod: 'POST',\n\t\turl: url,\n\t\tjson: json\n\t}, function (error, response, body) {\n\n\t\t//console.log(\"Back, error=\"+error, body);\n\n\t\tif (error) {\n\t bomb(\"Unexpected error: \" + error);\n\t\t} else if (response.statusCode != 200) {\n\t //console.log(\"Body is \" + body);\n\t bomb(\"Unexpected status code \" + response.statusCode);\n\t\t} else {\n\t\t\tif (body.response.toLowerCase() != 'success') {\n\t\t\t\tbomb('ERROR: response=\"' + body.response + '\", message=\"' + body.message + '\"');\n\t\t\t}\n\t\t\tconsole.log(' - upload complete');\n\t\t\tconsole.log(\"\\nStatus: OK\\n\");\n\t\t\tprocess.exit(0);\n\t\t}\n\t});\n}", "function putGlobalSnippets(path) {\n\n // Make sure the server has the endpoint we need. An old server may not.\n if (!endPointTransceiver.serverSupports(\"updateCustomTranslations\")) {\n warn(\"textSnippetsCannotBeSent\", {path})\n return\n }\n\n // Get the locale from the path.\n const tokens = path.split(\"/\")\n const locale = tokens[tokens.length - 2]\n\n // Start to build up the payload.\n const payload = {\n \"custom\" : {}\n }\n\n // Walk through the JSON, extracting keys and values.\n const contents = readJsonFile(path)\n\n Object.keys(contents).forEach(outerKey =>\n Object.keys(contents[outerKey]).forEach(innerKey =>\n payload.custom[innerKey] = contents[outerKey][innerKey]))\n\n // Use the optimistic locking endpoint if there is one.\n let textSnippetEndpoint = endPointTransceiver[\"updateCustomTranslations\"]\n let endpointParams = [\"ns.common\"]\n\n if (endPointTransceiver[\"updateCustomTranslationsForLocale\"]) {\n textSnippetEndpoint = endPointTransceiver[\"updateCustomTranslationsForLocale\"]\n endpointParams = [\"ns.common\", locale]\n }\n\n return textSnippetEndpoint(endpointParams,\n request().withLocale(locale).withBody(payload).withEtag(eTagFor(path))).tap(\n results => processPutResultAndEtag(path, results))\n}", "function swift_container_script_upload(token){\n console.log(\"Uploading Script Files\");\n res1.write(\"Uploading Script Files<br>\");\n //upload to swift container\n fs.createReadStream('public/uploads/'+jarFileName).pipe(request.put({\n url: swift_url+'/scripts/'+jarFileName,\n json: true,\n headers: {\n 'Content-Type':'application/json',\n 'X-Auth-Token' : token\n }\n },(err,response,body)=>{\n \n if(err){\n console.log(err);\n return res1.end(err);\n }\n console.log(\"Script Files uploaded successfully\");\n res1.write(\"Script Files uploaded successfully<br>\");\n create_job_binary(token);\n })\n ) \n }", "function handleSample(str) {\n log('handleSample');\n\n editor.getSession().setValue(str); // add the content\n updateSandbox(); // load the sample into an iframe\n }", "uploadScanned() {\n }", "function create(req, res) { // create a new snippet\n req.body.addedBy = req.user._id; // add reference to identify user creating the snippet\n req.body.isPrivate = !!req.body.isPrivate; // specify the snippet as public or private to user\n req.body.tags = req.body.tags.split(', '); // format tags as an array of strings\n Snippet.create(req.body) // this starts the code block that actually makes the snippet\n .then(async snippet => {\n await manageNewSnippetTags(snippet); // add references to this snippet on relevant tag documents\n res.json(snippet); // allows front-end to redirect to /search/all pathway\n })\n .catch(err => {res.json(err)});\n}", "uploadCodeFaust(app, module, x, y, e, dsp_code) {\n dsp_code = \"process = vgroup(\\\"\" + \"TEXT\" + \"\\\",environment{\" + dsp_code + \"}.process);\";\n if (!module) {\n app.compileFaust({ isMidi: false, name: \"TEXT\", sourceCode: dsp_code, x: x, y: y, callback: (factory) => { app.createModule(factory); } });\n }\n else {\n module.update(\"TEXT\", dsp_code);\n }\n }", "function swift_container_upload(token){\n console.log(\"Uploading Script Files\");\n //upload to swift container\n fs.createReadStream('hadoop.jar').pipe(request.put({\n url: 'http://172.16.2.140:8080/v1/AUTH_109d5a0fef34423582747e609b8c6c0f/scripts/hadoop1.jar',\n json: true,\n headers: {\n 'Content-Type':'application/json',\n 'X-Auth-Token' : token\n }\n },(err,response,body)=>{\n \n if(err){\n console.log(err);\n }\n //console.log(response.statusMessage);\n console.log(\"Files uploaded successfully\");\n create_job_binary(token)\n })\n ) \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }