query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Processes everything required to complete the reveal phase of a round. Shows everyone's hand and determines who lost the hand. | function completeRevealPhase () {
/* reveal everyone's hand */
for (var i = 0; i < players.length; i++) {
if (players[i] && !players[i].out) {
determineHand(i);
showHand(i);
}
}
/* figure out who has the lowest hand */
recentLoser = determineLowestHand();
console.log("Player "+recentLoser+" is the loser.");
/* look for the unlikely case of an absolute tie */
if (recentLoser == -1) {
console.log("Fuck... there was an absolute tie");
/* inform the player */
/* hide the dialogue bubbles */
for (var i = 1; i < players.length; i++) {
$gameDialogues[i-1].html("");
$gameAdvanceButtons[i-1].css({opacity : 0});
$gameBubbles[i-1].hide();
}
/* reset the round */
$mainButton.html("Deal");
$mainButton.attr('disabled', false);
if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {
setTimeout(advanceGame, FORFEIT_DELAY);
}
return;
}
/* update behaviour */
var clothes = playerMustStrip (recentLoser);
updateAllGameVisuals();
/* highlight the loser */
for (var i = 0; i < players.length; i++) {
if (recentLoser == i) {
$gameLabels[i].css({"background-color" : loserColour});
} else {
$gameLabels[i].css({"background-color" : clearColour});
}
}
/* set up the main button */
if (recentLoser != HUMAN_PLAYER && clothes > 0) {
$mainButton.html("Continue");
} else {
$mainButton.html("Strip");
}
if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {
setTimeout(advanceGame,FORFEIT_DELAY);
}
} | [
"function completeStripPhase () {\n /* strip the player with the lowest hand */\n stripPlayer(recentLoser);\n updateAllGameVisuals();\n}",
"function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}",
"removeLife () {\n document.querySelectorAll('#scoreboard img')[this.missed].setAttribute(\"src\", \"images/lostHeart.png\");\n this.missed += 1;\n if (this.missed === 4 && document.querySelector('#hint p').innerHTML !== this.activePhrase.hint) {\n document.getElementById('hint').style.display = \"none\";\n } else if (this.missed === 5) {\n checkSound([\"gameLost\"], \"start\");\n this.end(500, 450, false);\n }\n }",
"humanHitOrStay() {\n while (this.human.HitOrStay()) {\n\n console.clear();\n this.showMoney();\n this.dealer.nextCard.call(this);\n this.displayHandsWhileHitting();\n\n if (this.human.isBusted()) {\n console.clear();\n break;\n }\n\n }\n }",
"function userHand() {\n\n}",
"async function changeHandState() {\n isHandRaised.toggleState();\n isHandRaised.sendAttendeeHandState();\n handleParticipantUpdate();\n document.getElementById(\"hand-img\").classList.toggle(\"hidden\");\n document.querySelector(\".raise-hand-button\").innerText = `${\n attendee.handRaised ? \"Lower Hand\" : \"Raise Hand\"\n }`;\n document.querySelector(\".hand-state\").innerText = `${\n attendee.handRaised ? \"Your hand is raised 🙋\" : \"Your hand is down 💁\"\n }`;\n\n // Turn on video if hand is raised\n if (attendee.handRaised && !callFrame.participants().local.video) {\n callFrame.setLocalVideo(!callFrame.participants().local.video);\n } \n}",
"moveCompleted() {\n // Housekeeping\n this.from = null;\n // Check if the game is actually over!\n let moves = this.getMoves();\n if (moves.length === 0) {\n if (this.game.in_check()) {\n // CHECKMATE\n this.showResult(true, this.getTurn(false));\n }\n else {\n // STALEMATE\n this.showResult(false);\n }\n }\n else {\n if (this.gameOver) return;\n\n // If the game isn't over we want to show the results of the last move\n // in terms of updating the fog, so\n // Flip the turn back to the player who just played\n this.flipTurn();\n // Display the fog\n this.setupFog(false);\n // Flip the turn back to the correct player\n this.flipTurn();\n // Wait and then...\n setTimeout(() => {\n // Animate the fog to totally opaque so that nobody can see anything\n $.when($('.fog').animate({\n opacity: 1\n }, 1000))\n .then(() => {\n // And then show the instructions for the next turn\n this.showInstruction();\n });\n }, 2000);\n }\n\n }",
"function continueDealPhase () {\n\t/* hide the dialogue bubbles */\n for (var i = 1; i < players.length; i++) {\n $gameDialogues[i-1].html(\"\");\n $gameAdvanceButtons[i-1].css({opacity : 0});\n $gameBubbles[i-1].hide();\n }\n\t\n\t/* set visual state */\n if (!players[HUMAN_PLAYER].out) {\n showHand(HUMAN_PLAYER);\n }\n for (var i = 1; i < players.length; i++) {\n hideHand(i);\n }\n \n /* enable player cards */\n for (var i = 0; i < $cardButtons.length; i++) {\n $cardButtons[i].attr('disabled', false);\n }\n\t\n\t/* suggest cards to swap, if enabled */\n\tif (CARD_SUGGEST && !players[HUMAN_PLAYER].out) {\n\t\tdetermineAIAction(HUMAN_PLAYER);\n\t\t\n\t\t/* dull the cards they are trading in */\n\t\tfor (var i = 0; i < hands[HUMAN_PLAYER].tradeIns.length; i++) {\n\t\t\tif (hands[HUMAN_PLAYER].tradeIns[i]) {\n\t\t\t\tdullCard(HUMAN_PLAYER, i);\n\t\t\t}\n\t\t}\n\t}\n \n /* allow each of the AIs to take their turns */\n currentTurn = 0;\n advanceTurn();\n}",
"function HandleFrame(frame) {\t\n\tvar InteractionBox = frame.interactionBox;\n\t//No hand - variables undefine\n\tif(frame.hands.length == 1 || frame.hands.length == 2){\n\t\t//Grabs 1st hand per frame\n\t\tvar hand = frame.hands[0];\n\t\tHandleHand(hand,1,InteractionBox);\n\t\tif(frame.hands.length == 2){\n\t\t\t//Grabs 2nd hand per frame\n\t\t\t//var hand = frame.hands[1];\n\t\t\tHandleHand(hand,2,InteractionBox);\n\t\t}\n\t}\n}",
"showHostRevealHotSeatQuestionVictory_Continuation() {\n this.serverState.setCelebrationBanner({\n header: '',\n text: MONEY_STRINGS[this.serverState.hotSeatQuestionIndex]\n });\n this.serverState.resetHotSeatQuestion();\n\n // If the hot seat player won the million, the next option should be to say goodbye.\n if (this.serverState.hotSeatQuestionIndex + 1 >= HotSeatQuestion.PAYOUTS.length) {\n this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({\n nextSocketEvent: 'showHostSayGoodbyeToHotSeat',\n hostButtonMessage: LocalizedStrings.SAY_GOODBYE,\n aiTimeout: CORRECT_WAIT_TIMES[this.serverState.hotSeatQuestionIndex]\n }));\n } else {\n this.serverState.setShowHostStepDialog(this._getOneChoiceHostStepDialog({\n nextSocketEvent: 'showHostCueHotSeatQuestion',\n hostButtonMessage: LocalizedStrings.CUE_HOT_SEAT_QUESTION,\n aiTimeout: CORRECT_WAIT_TIMES[this.serverState.hotSeatQuestionIndex]\n }));\n }\n this._updateGame();\n }",
"function revealPokemon() {\n\t$(\"#pokemon-puzzle .mask\").stop().animate(\n\t\t{\"brightness\": 100},\n\t\t{\n\t\t\tduration: 400,\n\t\t\tstart: function() {\n\t\t\t\tthis.brightness = 0;\n\t\t\t},\n\t\t\tstep: function(now, fx){\n\t\t\t\t$(this).css(\"WebkitFilter\", \"brightness(\"+now+\"%)\");\n\t\t\t},\n\t\t\tcomplete: function(){\n\t\t\t\tthis.brightness = 0;\n\t\t\t}\n\t\t}\n\t);\n}",
"function pass() {\n displayRoundResults(PASS_SYMBOL, 0, rack.round);\n rack.round += 1;\n updateRackScores(0);\n resetRack();\n clearGuessBox();\n\n if (rack.round >= MAX_ROUNDS) {\n rackGiveUp();\n gameEndCleanUp();\n }\n}",
"function replayGame() {\n resetGame();\n togglePopup();\n }",
"function finalScreen() {\n\t$finalScreen.detach();\n\n\t// Update DOM to unhide appropriate text based on game state\n\tif (winner) {\n\t\t$finalScreen.find(\".win\").removeClass(\"hidden\");\n\t\t$finalScreen.find(\".win\").find(\"img\").show();\n\n\t\tif (goodStrategy)\n\t\t\t$finalScreen.find(\".win\").find(\".goodStrat\").removeClass(\"hidden\");\n\t\telse\n\t\t\t$finalScreen.find(\".win\").find(\".badStrat\").removeClass(\"hidden\");\n\n\t} else {\n\t\t$finalScreen.find(\".loss\").removeClass(\"hidden\");\n\t\t$finalScreen.find(\".loss\").find(\"img\").show();\n\n\t\tif (goodStrategy)\n\t\t\t$finalScreen.find(\".loss\").find(\".goodStrat\").removeClass(\"hidden\");\n\t\telse\n\t\t\t$finalScreen.find(\".loss\").find(\".badStrat\").removeClass(\"hidden\");\n\t}\n\n\t$(\"body\").animate({ backgroundColor: \"white\" }, 400);\n\t$(\".text,.doorContainer\").effect(\"puff\", \"slow\", function() {\n\n\t\t// Reattach finalScreen and animate!\n\t\t$finalScreen.removeClass(\"hidden\");\n\t\t$finalScreen.insertAfter($(\"header\"));\n\t\t$finalScreen.show(\"scale\", \"slow\", function() {\n\t\t\t$(\".ui-effects-wrapper\").remove();\n\t\t});\n\t});\n}",
"function dealFxn() {\n if (blackjackObj[\"turnOver\"] === true) {\n removeImg();\n }\n}",
"function stayPlay(){ \n // Turn off the hit and stay buttons\n hitHand.removeEventListener('click', hitPlay);\n stayHand.removeEventListener('click',stayPlay);\n // Function that checks if dealer should hit or stay\n updateDlrHnd();\n // Function that checks who wins the game\n checkWinner();\n}",
"async function handleJoinedMeeting(e) {\n attendee = {\n ...e.participants.local,\n handRaised: false\n };\n\n let attendeeInformationDisplay = document.querySelector(\n \".local-participant-info\"\n );\n attendeeInformationDisplay.innerHTML = `\n <img\n id=\"hand-img\"\n class=\" is-pulled-right hidden\"\n src=\"assets/hand.png\"\n alt=\"hand icon\"\n /> \n\n <p class=\"name-label\"><strong>${attendee.user_name + \" (You)\" ||\n \"You\"}</strong></p>\n <button\n class=\"button is-info raise-hand-button\"\n onclick=\"changeHandState()\"\n >Raise Hand\n </button>\n <p class=\"hand-state has-text-right\">Your hand is down 💁</p>\n`;\n await handleParticipantUpdate();\n setTimeout(isHandRaised.sendAttendeeHandState, 2500)\n toggleLobby();\n toggleMainInterface();\n}",
"function handleHold(userid, handID) {\n\tvar player = clients[userid];\n\tif (!player) {\n return false;\n }\n\n // Verify request is not spoofed\n\tif (!requestByCurrentTurn(player.player, handID)) {\n return;\n }\n\n\tplayer.player.hand.holding = true;\n\n\tsocket.sockets.emit(\"hold\", {\n\t\t\"playerID\": currentTurn,\n\t\t\"handID\": currentHandTurn,\n\t\t\"playerName\": player.player.name\n\t});\n\n // Set who plays next\n callNextTurn();\n\n playTurn();\n}",
"function revealSquare(classList) {\n // Set selected square\n const enemySquare = computerGrid.querySelector(`div[data-id='${shotFired}']`);\n const obj = Object.values(classList);\n // If selected square's class list contains \"explosion\" or \"miss\" and the game is not over already ->\n if (!enemySquare.classList.contains('explosion') && currentPlayer == 'user' && !isGameOver) {\n // See if the square's class includes any of the ship classes and add to the hit count of that ship class ->\n if (obj.includes('destroyer')) destroyerCount++;\n if (obj.includes('submarine')) submarineCount++;\n if (obj.includes('cruiser')) cruiserCount++;\n if (obj.includes('battleship')) battleshipCount++;\n if (obj.includes('carrier')) carrierCount++;\n }\n // If the sqaure's class includes \"taken\" ->\n if (obj.includes('taken')) {\n // Add class \"explosion\" to the class list of the square to designate you have hit a target at that location\n enemySquare.classList.add('explosion');\n // Change the info display to inform the user\n infoDisplay.innerHTML = `Confirmed Hit!`;\n } else {\n // Add class \"miss\" to the class list of the square to designate that you have missed at that location\n enemySquare.classList.add('miss');\n // Change the info display to inform the user\n infoDisplay.innerHTML = `Target Missed!`;\n }\n // Check to see if anyone has won yet\n checkForWins();\n // Set current player to \"enemy\" to inform client that it is the enemy's turn\n currentPlayer = 'enemy';\n if (gameMode == 'singlePlayer') playGameSingle();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a single activity's wait times for a date. | async getActivityWaitTimes(id, date) {
let found;
try {
log_1.default.debug(`Searching for waittimes for activity ${id} on ${date}`);
found = await this.models.activity.getWaittimes(id, [date]);
}
catch ({ message, code }) {
throw new common_1.InternalServerErrorException(message);
}
if (!found) {
throw new common_1.BadRequestException(`Activity ${id} does not exist or it does not support waittimes.`);
}
log_1.default.debug(`Found activity wait times ${id}, returning.`);
return found;
} | [
"function waitTimes(){\r\n if (times = getTimesFromPage()){\r\n // save the times on this page\r\n saveSetting('waitTimes', times.toString().replace(/,/g, \";\"));\r\n return times;\r\n }\r\n else {\r\n // use known times\r\n times = getSetting('waitTimes', 'times').split(\";\");\r\n if (times != 'times'){\r\n if (getSetting('showTimes', '1') == '1'){\r\n placeTable();\r\n setInterval(countdowns, 1000);\r\n }\r\n return times;\r\n }\r\n else {\r\n checkTimes();\r\n }\r\n }\r\n}",
"getWaitTime(t) {\n let _now = new Date();\n let _then = new Date(parseInt(t));\n let _t = (_now - _then) / 1000;\n let _m = Math.floor(_t / 60);\n let _s = _t - (_m * 60);\n\n _m = this._timeDigit(_m); //pretty strings\n _s = this._timeDigit(_s);\n\n return `${_m}:${_s}`; \n }",
"getActivitiesRange(date1, date2){\n let temp=[];\n let start = new Date(date1);\n let end = new Date(date2);\n let calBurned = 0;\n for(var i=0; i< this.activitiesLog.length; i++){\n if(this.activitiesLog[i].date >= start && this.activitiesLog[i].date <=end){\n temp.push(this.activitiesLog[i]);\n calBurned += this.activitiesLog[i].calories;\n }\n }\n return {activities: temp, caloriesBurned: calBurned};\n }",
"function getWaitTime(id) {\n\tvar idx;\n\tif (id) {\n\t\tidx = getOrderIdxById(id);\n\t\tif (idx === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t} else {\n\t\tidx = 0;\n\t}\n\tvar totalWait = 0;\n\tfor (var i = orders.length - 2; i > idx - 1; i--) {\n\t\ttotalWait += orders[i].turnaround;\n\t}\n\tvar now = new Date();\n\tvar daysRemaining = (orders.length > 0) ? (orders[orders.length - 1].turnaround - Math.round((now - orders[orders.length - 1].date) / (24 * 3600 * 1000), 0)) : 0;\n\tdaysRemaining = (daysRemaining > 0) ? daysRemaining : 0; // If days remaining is negative then order time is exceeded and we don't want to count it.\n\ttotalWait += daysRemaining;\n\treturn totalWait;\n}",
"getBettingEventsByDatePromise(date){\n var parameters = {};\n parameters['date']=date;\n return this.GetPromise('/v3/nhl/odds/{format}/BettingEventsByDate/{date}', parameters);\n }",
"async getActivitySchedule(id, date) {\n let found;\n try {\n log_1.default.debug(`Searching for schedules for activity ${id} on ${date}`);\n found = await this.models.activity.getActivitySchedule(id, date);\n }\n catch ({ message, code }) {\n throw new common_1.InternalServerErrorException(message);\n }\n if (!found) {\n throw new common_1.BadRequestException(`Activity ${id} does not exist or it does not support schedules.`);\n }\n log_1.default.debug(`Found activity schedule ${id}, returning.`);\n return found;\n }",
"getUserAvailableTimesForDay(availability, day, location) {\n // NOTE: Availability is stored in the Firestore database as:\n // availability: {\n // Gunn Library: {\n // Friday: [\n // { open: '10:00 AM', close: '3:00 PM' },\n // { open: '10:00 AM', close: '3:00 PM' },\n // ],\n // }\n // ...\n // };\n try {\n var times = [];\n Object.entries(availability[location]).forEach((entry) => {\n var d = entry[0];\n var t = entry[1];\n if (d === day) times = t;\n });\n\n var result = [];\n times.forEach((time) => {\n result = result.concat(this.getTimesBetween(time.open, time\n .close, day));\n });\n return result;\n } catch (e) {\n // This is most likely b/c the user's profile's location we deleted\n // or changed somehow\n console.warn('Error while getting userAvailableTimesForDay (' +\n day + 's at the ' + location + '):', e);\n Utils.viewNoAvailabilityDialog(location);\n }\n }",
"getTimesBetween(start, end, day) {\n var times = [];\n // First check if the time is a period\n if (this.data.periods[day].indexOf(start) >= 0) {\n // Check the day given and return the times between those two\n // periods on that given day.\n var periods = Data.gunnSchedule[day];\n for (\n var i = periods.indexOf(start); i <= periods.indexOf(end); i++\n ) {\n times.push(periods[i]);\n }\n } else {\n var timeStrings = this.data.timeStrings;\n // Otherwise, grab every 30 min interval from the start and the end\n // time.\n for (\n var i = timeStrings.indexOf(start); i <= timeStrings.indexOf(end); i += 30\n ) {\n times.push(timeStrings[i]);\n }\n }\n return times;\n }",
"function getMeals(date) {\n const requestURL = `api/planner?date=${date}`;\n let response = fetch(requestURL, {'method': 'GET'});\n return;\n}",
"getActivities( day , mon){\n var madekey=JSON.stringify([day,mon]);\n return calendar[madekey];\n }",
"function getLatestTrxAndActivityDate(jsonClient, arClientIds) {\r\n\t//3. Search for Latest Transaction Date of any kind for all client\r\n\t//order the search in trandate Latest.\r\n\t//array to keep track of already used client id\r\n\tvar arTrx = new Array();\r\n\tvar tflt = [new nlobjSearchFilter('entity', null, 'anyof', arClientIds),\r\n\t new nlobjSearchFilter('mainline', null, 'is', 'T')];\r\n\tvar tcol = [new nlobjSearchColumn('trandate').setSort(true),\r\n\t new nlobjSearchColumn('entity'),\r\n\t new nlobjSearchColumn('internalid'),\r\n\t new nlobjSearchColumn('type')];\r\n\tvar trslt = nlapiSearchRecord('transaction', null, tflt, tcol);\r\n\tfor (var t=0; trslt && t < trslt.length; t++) {\r\n\t\tif (!arTrx.contains(trslt[t].getValue('entity'))) {\r\n\t\t\tarTrx.push(trslt[t].getValue('entity'));\r\n\t\t\tjsonClient[trslt[t].getValue('entity')]['lasttrxdate'] = new Date(trslt[t].getValue('trandate'));\r\n\t\t\tjsonClient[trslt[t].getValue('entity')]['lasttrxtype'] = trslt[t].getText('type');\r\n\t\t\tjsonClient[trslt[t].getValue('entity')]['lasttrxid'] = trslt[t].getValue('internalid');\r\n\t\t}\r\n\t}\r\n\t\r\n\t//4. Search for Latest Activities Events, Phone calls, Tasks\r\n\tvar arAct = new Array();\r\n\tvar acflt = [new nlobjSearchFilter('company', null, 'anyof', arClientIds)];\r\n\tvar accol = [new nlobjSearchColumn('startdate').setSort(true),\r\n\t new nlobjSearchColumn('type'),\r\n\t new nlobjSearchColumn('internalid','company')];\r\n\tvar acrslt = nlapiSearchRecord('activity', null, acflt, accol);\r\n\tfor (var ac=0; acrslt && ac < acrslt.length; ac++) {\r\n\t\tlog('debug','activity company',acrslt[ac].getValue('internalid','company'));\r\n\t\tif (!arAct.contains(acrslt[ac].getValue('internalid','company'))) {\r\n\t\t\tarAct.push(acrslt[ac].getValue('internalid','company'));\r\n\t\t\tjsonClient[acrslt[ac].getValue('internalid','company')]['lastactivitydate'] = new Date(acrslt[ac].getValue('startdate'));\r\n\t\t\tjsonClient[acrslt[ac].getValue('internalid','company')]['lastactivitytype'] = acrslt[ac].getText('type');\r\n\t\t\tjsonClient[acrslt[ac].getValue('internalid','company')]['lastactivityid'] = acrslt[ac].getId();\r\n\t\t}\r\n\t}\r\n\t\r\n\tlog('debug','set latestdate','');\r\n\t\r\n\t//5. Loop through customer element and set latest date to use\r\n\t//jsonClient[crslt[c].getId()]['latestdate'] = '';\r\n\t//jsonClient[crslt[c].getId()]['latesttype'] = '';\r\n\t//jsonClient[crslt[c].getId()]['latestid'] = '';\r\n\tfor (var jc in jsonClient) {\r\n\t\tif (jsonClient[jc].lasttrxdate && jsonClient[jc].lastactivitydate) {\r\n\t\t\t//compare both to see which one to use\r\n\t\t\tif (jsonClient[jc].lasttrxdate.getTime() > jsonClient[jc].lastactivitydate.getTime()) {\r\n\t\t\t\tjsonClient[jc]['latestdate'] = jsonClient[jc].lasttrxdate;\r\n\t\t\t\tjsonClient[jc]['latesttype'] = jsonClient[jc].lasttrxtype;\r\n\t\t\t\tjsonClient[jc]['latestid'] = jsonClient[jc].lasttrxid;\r\n\t\t\t} else if (jsonClient[jc].lasttrxdate.getTime() < jsonClient[jc].lastactivitydate.getTime()) {\r\n\t\t\t\tjsonClient[jc]['latestdate'] = jsonClient[jc].lastactivitydate;\r\n\t\t\t\tjsonClient[jc]['latesttype'] = jsonClient[jc].lastactivitytype;\r\n\t\t\t\tjsonClient[jc]['latestid'] = jsonClient[jc].lastactivityid;\r\n\t\t\t}\r\n\t\t} else if ((!jsonClient[jc].lasttrxdate && jsonClient[jc].lastactivitydate) || (jsonClient[jc].lasttrxdate && !jsonClient[jc].lastactivitydate)) {\r\n\t\t\tjsonClient[jc]['latestdate'] = (jsonClient[jc].lasttrxdate)?jsonClient[jc].lasttrxdate:jsonClient[jc].lastactivitydate;\r\n\t\t\tjsonClient[jc]['latesttype'] = (jsonClient[jc].lasttrxdate)?jsonClient[jc].lasttrxtype:jsonClient[jc].lastactivitytype;\r\n\t\t\tjsonClient[jc]['latestid'] = (jsonClient[jc].lasttrxdate)?jsonClient[jc].lasttrxid:jsonClient[jc].lastactivityid;\r\n\t\t}\r\n\t}\r\n\t\r\n\tlog('debug','Run logic','');\r\n}",
"function getTimeEntries() {\n time.getTime().then(function(results) {\n vm.timeentries = results;\n updateTotalTime(vm.timeentries);\n console.log(vm.timeentries);\n }, function(error) {\n console.log(error);\n });\n }",
"function waitingTime(array, p) {\n let tickectsAmout = array[p];\n let result = 0;\n let personLocation = p;\n while(tickectsAmout > 0) {\n let reducedValue = array.shift();\n\t\treducedValue--;\n result = result + 1;\n if(personLocation === 0) {\n personLocation = array.length;\n tickectsAmout -= 1;\n }else {\n personLocation--;\n }\n if(reducedValue > 0){\n array.push(reducedValue)\n }\n }\n return result;\n}",
"getActivitiesWeek(){\n let temp = [];\n let today = new Date();\n let calBurned = 0;\n let lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);\n for(var i=0; i< this.activitiesLog.length; i++){\n if(this.activitiesLog[i].date >= lastWeek && this.activitiesLog[i].date <=today){\n temp.push(this.activitiesLog[i]);\n calBurned += this.activitiesLog[i].calories;\n }\n }\n return {activities: temp, caloriesBurned: calBurned}; \n }",
"function getTaskCompletionData(task_submissions, task_count) {\n //get number of days between start date and last task date\n let startDate = new Date(SPRINTS[currentSprint].sprintDate);\n let last_date = getLastSubmissionDate(task_submissions);\n\n let date_difference = calculateDateDifference(startDate, last_date);\n \n // console.log(date_difference);\n let tasks_remaining = [];\n\n //foreach day\n for(let i = 0; i <= date_difference; i++) \n {\n let task_date = new Date(startDate.getFullYear(),\n startDate.getMonth(),\n startDate.getDate() + i);\n\n //format the date into the standard date format for scrum tool\n task_date = FormatDate(task_date);\n\n if(task_submissions[task_date] != undefined) {\n task_count -= task_submissions[task_date];\n }\n tasks_remaining.push(task_count);\n }\n // console.log('tasks remaining', tasks_remaining);\n return tasks_remaining;\n}",
"function getRunningMeeting() {\n Safety_doAjax(runningMeetingURL, 'POST', { MeetingStatusType: 'Started' }, 'application/json', 'json', '', function (err, runningMeetingList) {\n if (err) {\n }\n else {\n //console.log(runningMeetingList);\n if (runningMeetingList.length > 0) {\n runningMeeting = runningMeetingList[0];\n hideMeetingBtn(true);\n //console.log(runningMeeting);\n }\n else {\n hideMeetingBtn(false);\n }\n }\n });\n}",
"function fetchOpeningTimes () {\n\t\tParkingService.getTimesForOne (ParkingService.data.selectedParking.id).then(function(response) {\n\t\t\t\n\t\t\t// save result to model\n\t\t\tParkingService.data.selectedParking.openingtimes = response;\n\t\t\t\n\t\t\t// hide table if no opening time data:\n\t\t\tif (response == false){ \n\t\t\t\tconsole.log ('no times available');\n\t\t\t\tParkingService.data.selectedParking.noTimesFlag = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t}",
"function updateWaitingTimeOfWaitingCallers() {\n var wc;\n for (wc in waitingCallers) {\n waitingCallers[wc].updateWaiting();\n }\n }",
"function getBusyTimeList(calendarList, startTime, endTime) {\n var p = new promise.Promise(),\n fb_query = {};\n\n if (typeof startTime === 'undefined') {\n fb_query.timeMin = startTime = new XDate();\n } else {\n fb_query.timeMin = startTime;\n }\n\n if (typeof endTime === 'undefined') {\n fb_query.timeMax = startTime.clone().addDays(7);\n } else {\n fb_query.timeMax = endTime;\n }\n\n fb_query.items = filterCalendars(calendarList);\n\n console.log('Asked for busy times');\n gapi.client.calendar.freebusy.query(fb_query).execute(function(x) {\n console.log('Got busy times back');\n p.done(false, x);\n });\n\n return p;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reads the tweets from the tweets.txt file this is a very inefficient way of fetching tweets but for this assignment we will use the .txt file as our database we can use a more aggressive caching. Instead of waiting for the method to be executed we could cache the tweets in the initialization. With that we would save time for the first call. But again that will also require some cache eviction strategy for data consistency. We need to update the cache or invalidate it when tweets file changed | function readTweets(callback) {
if (cache.tweets && cache.tweets.length > 0) {
callback(null, cache.tweets);
return;
}
try {
fs.readFile(path.join(__dirname, '/../assets/tweets.txt'), function (err, data) {
if (err) throw err;
var tweets = [];
const array = data.toString().split("\n");
if (!Array.isArray(array) && array.length < 1) {
callback(null, []);
}
//remove the first two rows(column header and dashes)
array.splice(0, 2);
//cache the tweets for next read
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (item.length > DATE_LENGTH + TWEET_TEXT_LENGTH + 1) {
tweets.push(resolveTweet(item));
} else {
// assuming the first 20 characters are always representing date
var createdDate = item.slice(0, DATE_LENGTH).trim();
item = item.replace(createdDate, '');
var text = '';
var flag = false;
while (true) {
var dateRegex = /^\d{4}\-\d{2}\-\d{2}\ \d{2}\:\d{2}\:\d{2}$/;
if (dateRegex.test(item.slice(0, DATE_LENGTH -1))) {
break;
} else {
text += ' ' + item.slice(0, item.length).trim();
}
// check boundaries
if (i < array.length - 1) {
item = array[++i];
} else {
flag = true;
break;
}
}
if (!flag && text) {
text = text.trim();
var textArr = text.split(' ');
var userId = textArr[textArr.length - 1];
if(userId){
// remove the user id from the text
text = text.substring(0, text.indexOf(userId));
tweets.push(new model.Tweet(createdDate, text, userId));
}
}
}
}
cache.tweets = tweets;
callback(null, cache.tweets);
});
} catch (exception) {
callback(exception, null);
console.log('exception', exception);
}
} | [
"function loadTweetData() {\n T.get(\"friends/list\", { screen_name: userName, count: 5 }, function(\n err,\n data,\n response\n ) {\n if (err) {\n // console.log(err);\n throw err;\n } else {\n myFriends = data.users;\n // console.log(data.users);\n }\n });\n\n T.get(\"direct_messages/sent\", { count: 5 }, function(err, data, response) {\n if (err) {\n console.log(err);\n } else {\n myChats = data;\n // console.log(data);\n }\n });\n\n T.get(\"statuses/user_timeline\", { screen_name: userName, count: 5 }, function(\n err,\n data,\n response\n ) {\n if (err) {\n console.log(err);\n } else {\n myTweets = data;\n // console.log(data);\n }\n });\n}",
"function parseTweets(runkeeper_tweets) {\n\t//Do not proceed if no tweets loaded\n\tif(runkeeper_tweets === undefined) {\n\t\twindow.alert('No tweets returned');\n\t\treturn;\n\t}\n\n\ttweet_array = runkeeper_tweets.map(function(tweet) {\n\t\treturn new Tweet(tweet.text, tweet.created_at);\n\t});\n\t\n\twritten_tweets = tweet_array.filter(tweet => tweet.writtenText);\n}",
"function loadTweets(callback) {\n if (GLOBALS.env == \"html\") {\n twitterUrl = \"twitter.php\";\n twitterType = \"POST\";\n twitterRequest = {\n q : \"%23Cannes2016\",\n count : 15,\n api : \"search_tweets\"\n };\n } else {\n twitterUrl = GLOBALS.api.twitterUrl;\n twitterType = \"GET\";\n twitterRequest = {\n offset : 40\n };\n }\n\n $.ajax({\n url : twitterUrl,\n type : twitterType,\n data : twitterRequest,\n success: function(data, textStatus, xhr) {\n if (GLOBALS.env == \"html\") {\n data = JSON.parse(data);\n if (typeof data.statuses !== 'undefined') {\n data = data.statuses;\n }\n\n var img = '';\n\n for (var i = 0; i < data.length; i++) {\n img = '',\n url = 'http://twitter.com/' + data[i].user.screen_name + '/status/' + data[i].id_str;\n try {\n if (data[i].entities['media']) {\n img = data[i].entities['media'][0].media_url;\n }\n } catch (e) {\n // no media\n }\n var textTweet = data[i].text.parseURL().parseUsername(true).parseHashtag(true);\n if (textTweet.length>180) {\n textTweet = (textTweet.substr(0, 180) + \"...\");\n }\n\n\n posts.push({'type': 'twitter', 'text': '<div class=\"vCenter text-container\"><div class=\" content vCenterKid\"><p class=\"text\">' + textTweet + '</p></div></div>', 'name': data[i].user.screen_name, 'img': img, 'url': url, 'date': data[i].created_at})\n\n if(i==data.length - 1) {\n callback();\n }\n }\n } else {\n var img = '';\n\n for (var i = 0; i < data.length; i++) {\n img = '';\n try {\n if (data[i].content) {\n img = data[i].content;\n }\n } catch (e) {\n // no media\n }\n\n posts.push({'type': 'twitter', 'text': '<div class=\"vCenter text-container\"><div class=\" content vCenterKid\"><p class=\"text\">' + data[i].message.parseURL().parseUsername(true).parseHashtag(true) + '</p></div></div>', 'img': img})\n\n if(i == data.length - 1) {\n callback();\n }\n }\n }\n }\n });\n\n}",
"function getTweets() {\n\tvar returnString = \"\";\n\tfor(i = 0; i < jsonFileObj.length; i++){\n\t\treturnString = returnString + \"{\\r\\n<br />\" +\n\t\t\t\"\\\"created-at\\\": \\\"\" + jsonFileObj[i].created_at + \"\\\"\\r\\n<br />\" +\n\t\t\t\"\\\"id_str\\\": \\\"\" + jsonFileObj[i].id_str + \"\\\"\\r\\n<br />\" +\n\t\t\t\"\\\"text\\\": \\\"\" + jsonFileObj[i].text + \"\\\"\\r\\n<br />\" +\n\t\t\t\"}\\r\\n<br />\";\n\t}\n\treturn returnString\n}",
"function twitterFeed(){\n\n\t//taking input\n\tconsole.log(\"Key word to find sentiment: \");\n\tprocess.stdin.setEncoding('utf8');\n\tprocess.stdin.on('readable', function(input) {\n\t\tvar word = process.stdin.read();\n\t \n\t\tif (word !== null) {\n\t\t\tstreamInput(word);\n\t\t}\n\t});\n\n\tprocess.stdin.on('end', function() {\n\t process.stdout.write('end');\n\t});\n\n\t//Authentication with twitter\n\tvar client = new Twitter({\n\t consumer_key: \"1LsrwvTSs3XAWeJE5fFcDp378\",\n\t consumer_secret: \"Vo7sfjoEOD7DP6haSFR2p4AFTE01qxfHTVSA8k1dgdARNlUQw1\",\n\t access_token_key: \"4329704114-FtRczjVFxQMo6x2tzA2tfyyud1fOchMEjI7xBPq\",\n\t access_token_secret: \"fyGrcotLQq7V1k94gergfJTXFcaHWcYBaV5nM3B5PSyvn\"\n\t});\n\n\t//stream and output\n\tfunction streamInput(keyWord){ \n\t\tvar numberOfTweets = 0; \n\n\t\t\tclient.stream('statuses/filter', {track: keyWord}, function(stream) {\t\t\t\t\n\t\t\tstream.on('data', function(tweet) {\n\t\t\t \t\n\t\t\t \t//number of tweets to take in\n\t\t\t \tif(numberOfTweets < 1000){ \n\t\t\t\t console.log(tweet.text);\n\t\t\t\t if(typeof(tweet.text) == 'string'){\n\t\t\t\t\t testVector.push(tweet.text);\n\t\t\t\t\t numberOfTweets++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\telse{\n\t\t\t\t\teventEmitter.emit('tweetsReady', testVector);\n\t\t\t\t\tstopStream(stream);\n\t\t\t\t}\t\n\t\t\t});\n\n\t\t\tstream.on('error', function(error) {\n\t\t\t throw error;\n\t\t\t process.exit(1);\n\t\t\t});\n\t\t});\n\t}\n\n\n\tfunction stopStream (s){\n\t\ts.destroy();\n\t}\n}",
"function twitter_parser(tweets){\n $.each(tweets, function(i,tweet){\n if(tweet.full_text !== undefined) {\n var tweettext = tweet.full_text,\n tweetapi;\n if(options._isSearch){\n\n tweetapi = {\n '{tweetdate}' : twitter_relative_time(tweet.created_at), // Calculate how many hours ago was the tweet posted\n '{tweeturl}' : 'https://www.twitter.com/' + tweet.user.screen_name + '/status/' + tweet.id_str,\n '{tweettext}' : tweettext.parseUrl().parseUsername().parseEmail().parseHashtag(),\n '{tweetuser:name}' : tweet.user.name,\n '{tweetuser:screenname}' : tweet.user.screen_name,\n '{tweetuser:url}': tweet.user.url,\n '{tweetuser:image}': tweet.user.profile_image_url,\n '{tweetuser:location}' : tweet.user.location,\n '{tweetuser:description}' : tweet.user.description\n };\n\n }else{\n\n tweetapi = {\n '{tweetdate}' : twitter_relative_time(tweet.created_at) , // Calculate how many hours ago was the tweet posted\n '{tweeturl}' : 'https://www.twitter.com/' + tweet.user.screen_name + '/status/' + tweet.id_str,\n '{tweettext}' : tweettext.parseUrl().parseUsername().parseEmail().parseHashtag(),\n '{tweetuser:name}' : tweet.user.name,\n '{tweetuser:screenname}' : tweet.user.screen_name,\n '{tweetuser:location}' : tweet.user.location,\n '{tweetuser:description}' : tweet.user.description,\n '{tweetuser:url}': tweet.user.url,\n '{tweetuser:image}': tweet.user.profile_image_url,\n '{tweetsource}': tweet.source\n };\n }\n\n var tweet_html,\n output;\n // if the tweet is a retweet parse the tweet string for retweet variables\n if(tweet.retweeted_status){\n tweetapi['{retweetuser:name}'] = tweet.retweeted_status.user.name;\n tweetapi['{retweetuser:screenname}'] = tweet.retweeted_status.user.screen_name;\n tweetapi['{retweetuser:image}'] = tweet.retweeted_status.user.profile_image_url;\n //output of the retweet\n output = tweetoptions.retweetstring;\n }else{\n //output of tweet\n output = tweetoptions.tweetstring;\n }\n //sets output html of the tweet\n var tweet_html = output.multiReplace(tweetapi);\n\n global_tweets.push({\n id:tweet.id,\n status:tweet_html\n });\n }\n });\n }",
"function twitterUpdate() {\n\t\t// Twitter読み込み\n\t\tif(twitter_id){\n//\t\t\tgetTwitterSearch();\n\t\t}\n\t\t// 逆ジオコーディング\n\t\tif(userExist){\n\t\t\tgeocoder.getLocations(nowPoint, geocoding);\n\t\t}\n\t\treloadId = setTimeout(twitterUpdate, twitterReloadTime);\n\t}",
"function findTweet(tweetnumber){\n\tfor(i = 0; i < jsonFileObj.length; i++){\n\t\tif (jsonFileObj[i].id_str == tweetnumber) {\n\t\t\treturn jsonFileObj[i];\n\t\t}\n\t}\n}",
"function getWords() {\n fs.readFile(\"./words.txt\", \"utf8\", function(error, data) {\n if (error) {\n console.log(error);\n } else {\n var wordArray = data.split(\"\\n\");\n // do something after creating wordArray\n pickWord(wordArray);\n }\n })\n}",
"function nextPage( callback ){\n // Get tweets from local archive if configured\n if( conf.archive ){\n if( ! archive ){\n archive = fs.readdirSync( conf.archive );\n }\n var filename = archive.pop();\n if( ! filename ){\n console.log('No more tweets in archive, quitting');\n process.exit(0);\n }\n // load these tweets via a GLOBAL hack\n Grailbird = { data: {} };\n require( conf.archive+'/'+filename );\n var key;\n for( key in Grailbird.data ){\n callback( Grailbird.data[key] );\n }\n return;\n }\n // else get page of tweets via API \n var params = { \n count: 200, \n user_id : userId, \n trim_user: true,\n include_rts: false\n };\n if( null != maxId ){\n params.max_id = maxId;\n } \n client.get( 'statuses/user_timeline', params, function( tweets, error, status ){\n if( ! tweets || error ){\n return handleTwitterError( status, error, run );\n }\n if( maxId ){\n var tweet = tweets.shift();\n if( ! tweet || tweet.id_str !== maxId ){\n // console.error('Expecting first tweet to match max_id '+maxId+', got '+(tweet?tweet.id_str:'none') );\n // not sure why this happens, but possibly due to tweeting while running.\n // process.exit( EXIT_TWFAIL );\n tweet && tweets.unshift(tweet);\n }\n }\n if( ! tweets.length ){\n if( ! conf.idleTime ){\n console.log('No more tweets in API, quitting');\n process.exit(0);\n }\n console.log('No more tweets, running again in '+conf.idleTime+' seconds..');\n maxId = null;\n setTimeout( run, conf.idleTime * 1000 );\n return;\n }\n callback( tweets );\n } ); \n}",
"function get_tweets_in_current_area() {\n\tfoundTweetCount = 0;\n\t$(\"#loading_button\").css(\"display\", \"inline-block\");\n\n\t// Check if the browser supports HTML 5 Geolocation.\n\tif(navigator.geolocation) {\n\t\t// If it does, get the user's current geolocation, and search for tweets in that area.\n\t\tnavigator.geolocation.getCurrentPosition(function(position) {\n\t\t\tvar lat_long_str = position.coords.latitude + \",\" + position.coords.longitude + \",5mi\";\n\t\t\t$(\"#results\").html(\"\");\n\t\t\t$(\"#results\").css(\"height\", \"100%\");\n\t\t\t$.get(\"scripts/php/search_twitter.php?geo=\"+lat_long_str, function(response) {\n\t\t\t\tjsonData = JSON.parse(response);\n\t\t\t\tnextSetOfTweets = jsonData.search_metadata.next_results;\n\t\t\t\tbuildTweetCard(jsonData);\n\t\t\t}).then(function() {\n\t\t\t\t$(\"#found_results\").html(\"Showing \"+foundTweetCount+\" tweets (scroll down to load more).\");\n\t\t\t});\n\t\t});\n\t}\n}",
"function oldAndCache () {\n let tweets = oldTweets.concat(tweetCache).sort((a, b) => a.timestamp > b.timestamp)\n // remove duplicates by comparing id\n for (let x = tweets.length - 1; x >= 0; x--) {\n for (let y = x-1; y >= 0; y--) {\n if (tweets[x].id == tweets[y].id) {\n tweets.splice(x, 1)\n break\n }\n }\n\n // Remove tweets that are banned/deleted by admin\n for (let y = 0; y < deleted.length; y++) {\n if (tweets[x].id == deleted[y].id) {\n tweets.splice(x, 1)\n break\n }\n }\n }\n console.log('Old and cache: ', tweets)\n return tweets\n}",
"function get_tweets(query, $q) {\n\tvar q = $q.defer();\n\n\tvar transaction \t= tweets_db.transaction([\"tweets\"],\"readonly\");\n\t\n\tvar store \t\t\t= transaction.objectStore(\"tweets\");\n\tconsole.log(\"Nemam Amma Bhagavan Sharanam -- Query is \" + query); \n\n\t// Open index\n\tvar index \t\t\t= store.index(\"query, status_id\");\n\tvar boundedKeyRange = IDBKeyRange.bound([query, \"\"], [query, \"Z\"]);\n\tvar tweets_array \t= new Array();\n\t\n\t// Asynchronous method to search tweets table and return the \n\t// tweets array after all the entries are searched\n\tindex.openCursor(boundedKeyRange, \"prev\").onsuccess = function(e) {\n\t var tweet_cursor = e.target.result;\n\t if(tweet_cursor) {\n\t \t\n\t\t\ttweets_array.push(tweet_cursor.value);\n\t\t\ttweet_cursor.continue();\n\t\t}\n\t\telse {\n\t\t\t// Resolve the promise if there is no error \n\t\t\tconsole.log(\"Nemam Amma Bhagavan Sharanam -- \" + tweets_array.length);\n\t\t\t q.resolve({tweets: tweets_array, num_tweets: tweets_array.length});\n\t\t}\n\t} // openCursor on success\n\t\n\treturn q.promise;\n\n} // get_tweets",
"function nextTweet(){\n if( tweet = tweets.shift() ){\n checkTweet();\n }\n else {\n setTimeout( run, 100 );\n }\n }",
"function refresh_tweets() {\n\t\n\t$('#panels').find('.panel_id').each(\n\t\tfunction(i) {\n\t\t\t\n\t\t\t\n\t\t\tget_tweets(this.value,'regular',1);\n\t\t\t\n\t\t}\n\t\t);\n\t\n}",
"function updateTweet ({ id, user, element }) {\n // if tweet has been detected previously\n if (state.tweets[id] !== undefined) {\n // render styles\n renderTweet(state.tweets[id], element)\n return\n }\n // else, it is a new tweet, check it\n analyzeTweet({ id, user, element })\n }",
"function getTwitterResults(articleCount) {\n return new Promise(function (resolve, reject) {\n textapi.entities({ url: content.articles[articleCount].url}, function async(error, response) {\n if (error === null) {\n const foundKeyWords = response.entities['keyword'];\n let keywordsString = \"\";\n if (foundKeyWords != undefined) {\n const arrayLength = foundKeyWords.length;\n for (let i = 0; i < arrayLength; i++) {\n if (i != arrayLength - 1) {\n keywordsString += foundKeyWords[i] + \", \";\n } else {\n keywordsString += foundKeyWords[i];\n }\n }\n } else {\n keywordsString = \"\";\n }\n\n //now we create our own twitter search String\n //it will be composed of the first response from each of the following sub-divisions\n // 1) location 2) organization 3) person 4) keywords\n let twitterQuery = \"\" + newsSearch + \", \"; //this one will not have any keywords\n if (response.entities != undefined) {\n if (response.entities['organization'] != undefined) {\n twitterQuery += response.entities['organization'][0] + \", \";\n }\n if (response.entities['person'] != undefined) {\n twitterQuery += response.entities['person'][0];\n }\n if (response.entities['keyword'] != undefined) {\n }\n db_print(\"twitterQuery2 is: \" + twitterQuery);\n }\n\n //now we try to get a twitter call\n twitterClient.get('search/tweets', {q: twitterQuery}, function async(error, tweets, response) {\n let tweetsList = tweets['statuses'];\n let maxTweets = 3;\n let tweetResults = [];\n let tweetsGotten = 0;\n for (let tweetIndex in tweetsList) {\n let userTweet = { screenName: tweetsList[tweetIndex].user.screen_name,\n name: tweetsList[tweetIndex].user.name,\n text: tweetsList[tweetIndex].text,\n profileImage: tweetsList[tweetIndex].user.profile_image_url,\n tweetURL: tweetsList[tweetIndex].user.url\n };\n if(tweetsGotten <= maxTweets) {\n tweetResults.push(userTweet);\n }\n tweetsGotten++;\n }\n\n if (tweetResults.length == 0) {\n tweetResults.push(\"No tweets found.\");\n }\n\n let curArticleResult = {\n articleName: content.articles[articleCount].title,\n articleTagline: content.articles[articleCount].description,\n articleDescription: content.articles[articleCount].content,\n articlePicture: content.articles[articleCount].urlToImage,\n articleURL: content.articles[articleCount].url,\n tweets: tweetResults,\n numTweets: tweetsGotten\n\n }\n\n articles.push(curArticleResult);\n\n // timeout to await results\n let wait = setTimeout(() => {\n clearTimeout(wait);\n return resolve(); // SUCCESS after timeout\n }, 200)\n });\n } // end of if statement\n }); //end of aylien api\n }); // end of promise\n }",
"function viewUserTweets(userStr){\n userProfile = true;\n resetUserTweets(userStr); // clears all tweets\n var UserTweets = _.filter(streams.home,function(tweet){\n if (tweet.user == userStr){\n generateTweet(tweet); // generates tweet with tweet object\n }\n });\n addBackButton();\n }",
"function load_more_tweets() {\n\t//Check if there are more tweets to load.\n\tif(nextSetOfTweets) {\n\t\t// Make another search if there are more.\n\t\t$.get(\"scripts/php/search_twitter.php?next_results=\"+encodeURIComponent(nextSetOfTweets), function(response) {\n\t\t\t// Check for errors and parse the json data.\n\t\t\tvar jsonData = JSON.parse(response);\n\t\t\t$(\"#error_result\").html(\"\");\n\t\t\tif(jsonData.hasOwnProperty('errors')) { \n\t\t\t\t$.each(jsonData.errors, function(key, val) {\n\t\t\t\t\t$(\"#error_result\").append(val.message + \"<br>\");\n\t\t\t\t});\n\t\t\t\treturn false;\n\t\t\t}else {\n\t\t\t\t// Check if there are more results.\n\t\t\t\tif(jsonData.search_metadata.hasOwnProperty(\"next_results\")) {\n\t\t\t\t\tnextSetOfTweets = jsonData.search_metadata.next_results;\n\t\t\t\t}else {\n\t\t\t\t\tnextSetOfTweets = \"\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Add more cards to the results.\n\t\t\t\tbuildTweetCard(jsonData);\n\t\t\t}\n\t\t}).then(function() {\n\t\t\t$(\"#found_results\").html(\"Showing \"+foundTweetCount+\" tweets (scroll down to load more).\");\n\t\t});\n\t}else {\n\t\t// If there are no more tweets to load, hide the button for loading them.\n\t\t$(\"#loading_button\").css(\"display\", \"none\");\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make nice html for a definition. def is (def symbol ) lambdaexpr is (\\lambda vardecllist body) used for toplevel definitions, or embedded in dt/dd inside proof (see htmlProofString). | function htmlDefString(def)
{
var args = def.getArgs();
var sym = args[0];
var lamEx = args[1];
var lArgs = lamEx.getArgs();
var vdl = lArgs[0];
var body = lArgs[1];
var result = '<b>def</b>';
result += '\\(\\ ';
result += sym.getArg(0);
result += "(";
result += latexVarDeclListString(vdl);
result += ')\\colon ';
// do the body
result += "\\ ";
result += latexMathString(body);
result += "\\)";
result += " <b>end</b>";
return result;
} | [
"function htmlProofString(pf, level)\n{\n var i, vardecllist, vdlArgs;\n var result = '<dl class=\\\"proof\\\">';\n\n level = level || 0;\n\n result += '<dt>' + pf.label + ': </dt>\\n';\n result += '<dd><b>proof</b></dd>\\n';\n\n result += '<dt></dt><dd><dl class=\\\"proof\\\">'; // description list.\n\n // display var decls\n vardecllist = pf.vars;\n vdlArgs = vardecllist.getArgs();\n if (vdlArgs.length > 0) {\n\tresult += '<dt></dt><dd><b>var </b>';\n }\n for (i = 0; i < vdlArgs.length; i++) {\n\tvar varDecl = vdlArgs[i];\n\tvar vdArgs = varDecl.getArgs();\n\tvar varName = vdArgs[0];\n\tvar varType = vdArgs[1];\n\tif (i > 0) {\n\t result += '<dd>';\n\t}\n\tif (varType === exprProto.anyMarker) {\n\tresult += '\\\\(' +\n\t\tlatexMathString(varName) +\n\t\t'\\\\)' +\n\t\t'</dd>\\n';\n\t}\n\telse {\n\t result += '\\\\(' +\n\t\tlatexMathString(varName) + \n\t\t'\\\\in ' +\n\t\tlatexMathString(varType) +\n\t\t'\\\\)' +\n\t\t'</dd>\\n';\n\t}\n }\n\n // display definitions\n for (i = 0; i < pf.defs.length; i++) {\n\tresult += '<dt></dt>';\n\tresult += '<dd>' + htmlDefString(pf.defs[i]) + '</dd>\\n';\n }\n\n // display premises\n for (i = 0; i < pf.premises.length; i++) {\n result += htmlConclusionString(pf.premises[i], level+1);\n }\n\n // display conclusions\n for (i = 0; i < pf.conclusions.length; i++) {\n result += htmlConclusionString(pf.conclusions[i], level+1);\n }\n result += '</dl></dd>\\n';\n result += \"<dt></dt><dd><b>end</b><dd>\\n\";\n result += '</dl>\\n';\n\n return result;\n}",
"transformDefToLambda(defExp) {\n const [_tag, name, params, body] = defExp;\n return ['var', name, ['lambda', params, body]];\n }",
"function evaluate_function_definition(stmt,env) {\n return make_function_value(\n pair(\"this\",\n function_definition_parameters(stmt)),\n locals(function_value_body(stmt)),\n function_definition_body(stmt),\n env);\n}",
"function latexProofString(pf)\n{\n var i;\n var result = '';\n\n result += pf.label + ':\\\\ \\\\textbf{proof}\\n';\n for (i = 0; i < pf.vars.length; i++) {\n result += 'var ' + pf.vars[i] + '\\n';\n }\n for (i = 0; i < pf.defs.length; i++) {\n result += latexConclusionString(pf.defs[i]);\n }\n for (i = 0; i < pf.premises.length; i++) {\n result += latexConclusionString(pf.premises[i]);\n }\n for (i = 0; i < pf.premises.length; i++) {\n result += latexConclusionString(pf.conclusions[i]);\n }\n result += '\\\\textbf{end}\\n';\n return result;\n}",
"function printDefinition() {\n $(\"#dictionaryDisplay\").removeClass(\"hide\");\n $(\"#dictionaryDisplay\").append(\"<p id='noun'> Noun: \" + noun + \"</p>\");\n $(\"#dictionaryDisplay\").append(\"<p id ='verb'> Verb: \" + verb + \"</p>\");\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adverb'> Adverb: \" + adverb + \"</p>\"\n );\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adjective'> Adjective: \" + adjective + \"</p>\"\n );\n }",
"generateFuncDocstring(line){\n let inputs = ''; //To set docstring about inputs params\n let returns = (line.indexOf('returns')>=0)? ' * @return : \\n' : '' ; //To set docstring about returned variable\n let functionDocstring;\n line = line.substring(line.indexOf('(')+1, line.indexOf(')') );\n params = line.split(',');\n for (var i = 0; i < params.length; i++) { //to generate inputs string\n inputs += ' * @param ' + this.trim(params[i]).split(' ')[0] + ' ' + this.trim(params[i]).split(' ')[1] + ' : ' + ' \\n';\n }\n return functionDocstring =\n '/** \\n'\n + ' * @dev: \\n'\n + inputs\n + returns\n + ' */ \\n';\n}",
"function ruleAsMarkdown(rule) {\n let markdown = `## Rule: ${asUrl(rule)}\\n\\n`;\n let targetEnumeration = \"\";\n if (hasPublic(rule)) {\n targetEnumeration += \"- Everyone\\n\";\n }\n if (hasAuthenticated(rule)) {\n targetEnumeration += \"- All authenticated agents\\n\";\n }\n if (hasCreator(rule)) {\n targetEnumeration += \"- The creator of this resource\\n\";\n }\n if (hasAnyClient(rule)) {\n targetEnumeration += \"- Users of any client application\\n\";\n }\n const targetAgents = getAgentAll(rule);\n if (targetAgents.length > 0) {\n targetEnumeration += \"- The following agents:\\n - \";\n targetEnumeration += targetAgents.join(\"\\n - \") + \"\\n\";\n }\n const targetGroups = getGroupAll(rule);\n if (targetGroups.length > 0) {\n targetEnumeration += \"- Members of the following groups:\\n - \";\n targetEnumeration += targetGroups.join(\"\\n - \") + \"\\n\";\n }\n const targetClients = getClientAll(rule);\n if (targetClients.length > 0) {\n targetEnumeration += \"- Users of the following client applications:\\n - \";\n targetEnumeration += targetClients.join(\"\\n - \") + \"\\n\";\n }\n markdown +=\n targetEnumeration.length > 0\n ? \"This rule applies to:\\n\" + targetEnumeration\n : \"<empty>\\n\";\n return markdown;\n}",
"function evaluate_var_definition(stmt,env) {\n define_variable(var_definition_variable(stmt),\n evaluate(var_definition_value(stmt),env),\n env);\n return undefined;\n}",
"function generateMD(answer) {\n return `\n# ${answer.title}\n\n## Description \n${answer.description}\n \n## Table of Contents\n* [Installation](#installation)\n* [Usage](#usage)\n* [Credits](#credits)\n* [License](#license)\n \n## Installation\n${answer.installation}\n \n## Usage \n${answer.usage}\n \n## License\n${answer.license}\n \n## Credits\nGitHub usernames:\n${answer.contribution}\n `\n}",
"function getHtmlExprStmt(e, sO, parentPath, myPos) {\r\n\r\n\r\n var ret = \"\"; // returned html string\r\n\r\n var myPath = parentPath + e.mySeq + \":\"; // path to this node\r\n\r\n // record active parent expression in sO. This is the way we obtain\r\n // an ExprObj that correspond to a path string. \r\n //\r\n if (myPath == sO.activeParentPath) {\r\n sO.activeParentExpr = e;\r\n }\r\n\r\n\r\n if (e.deleted == DeletedState.Deleted) { // if expr is deleted\r\n\r\n ret = \"<span style='color:red'>\" + DefDeletedName + \"</span>\";\r\n\r\n } else if (e.deleted == DeletedState.NeedUpdate) { // if expr needs update\r\n\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n ret = \"<span style='color:red' \" + oncE + \">\" + DefNeedUpdateName +\r\n \"</span>\";\r\n\r\n } else if (e.deleted == DeletedState.PlaceHolder) { // if place holder\r\n\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n ret = \"<span style='color:orange' \" + oncE + \">\" + e.str +\r\n \"</span>\";\r\n\r\n } else if (e.isFuncCall()) {\r\n\r\n\tvar args = \"\"; // arguments within ( )\r\n\tvar numargs = e.exprArr.length;\r\n\r\n\tfor (var i=0; i <= numargs; i++) { // note '<='\r\n\r\n // onclick and properties for spaces within the function call.\r\n // spaces are used as insertion points (similar to in a stmt)\r\n //\r\n var oncS_args = \"\\\"\" + myPath + \"\\\",\" + i;\r\n var oncS = \" onclick='spaceClicked(\" + oncS_args + \")' \";\r\n var sprop = oncS; // child space is clickable\r\n var cprop = \"\"; // child's properties\r\n\r\n if ((i > 0) && (i < numargs)) args += \",\";\r\n\r\n // if this child is active (highlighted expr/space)\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n if (!sO.isSpaceActive)\r\n cprop = \" style='background-color:#dcffed' \";\r\n else\r\n sprop += \" class='scursor' \";\r\n }\r\n\r\n // First add space, and then add spans for child expression\r\n //\r\n args += \"<span \" + sprop + \"> </span>\";\r\n // \r\n if (i < numargs) {\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n args += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n }\r\n\r\n } // for all args\r\n\r\n\r\n // put onclick function and cursor changing for func name\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='funcClicked(\" + onc_args + \")' \";\r\n var fprop = oncE + \" style='cursor:pointer' \";\r\n //\t\r\n // If the function name is already highlighted, clicking on it again\r\n // makes the function name editable\r\n //\r\n if ((parentPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n myPos)) {\r\n //var onin_args = \" oninput=\\\"updateFuncName(this)\\\" \"; \r\n var onin_args = \" onblur=\\\"updateFuncName(this)\\\" \";\r\n fprop += \" contenteditable \" + onin_args;\r\n }\r\n ret = \"<span \" + fprop + \">\" + e.str + \"</span>(\" + args + \")\";\r\n //+ \"<span \" + fprop + \">)</span>\";\r\n\r\n\r\n\r\n } else if (e.isGridCell()) {\r\n\r\n // Note: it is my parent's (callers) repsonsibility to put a span \r\n // around me (whole grid), with highlight if necessary. My\r\n // resposnsibility is to highlight a selected child. It's always\r\n // child resposnbility to handle onclick. \r\n // Note: There are no child spaces within a grid, so no space handling\r\n // is necessary\r\n //\r\n var gcont = \"\"; // grid contents within [ ]\r\n\r\n for (var i = 0; i < e.exprArr.length; i++) {\r\n\r\n var cprop = \"\";\r\n if (i > 0) gcont += \",\";\r\n\r\n // highlight my child (and all its children), if he has been\r\n // selected (clicked on) by the user\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n cprop = \" style='background-color:#dcffed' \";\r\n }\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n gcont += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n\r\n }\r\n\r\n // put onclick function and cursor changing for grid name\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n var gprop = oncE + \" style='cursor:pointer' \";\r\n //\t\r\n var brack1 = (e.exprArr && e.exprArr.length) ? \"[\" : \"\";\r\n var brack2 = (e.exprArr && e.exprArr.length) ? \"]\" : \"\";\r\n //\r\n var cap = e.gO.caption; // if gO.caption updated, use that\r\n //\r\n ret = \"<span \" + gprop + \">\" + cap + brack1 + \"</span>\" + gcont +\r\n \"<span \" + gprop + \">\" + brack2 + \"</span>\";\r\n\r\n\r\n } else if (e.isStatement()) { // an assignment/if statement (expr statement)\r\n\r\n // Just go thru the exprArr in sequence and collect (print) all\r\n // the html values\r\n // Note: This is the case for handling the root node\r\n // Note: i includes exprArr.length, to handle the trailing space\r\n //\r\n for (var i = 0; i <= e.exprArr.length; i++) {\r\n\r\n var oncS_args = \"\\\"\" + myPath + \"\\\",\" + i;\r\n var oncS = \" onclick='spaceClicked(\" + oncS_args + \")' \";\r\n\r\n // Every child is always 'clickable' individually\r\n //\r\n var cprop = \"\";\r\n var sprop = oncS; // child space is clickable\r\n\r\n //alert(\"mypath:\" + myPath + \" cpos:\" + i);\r\n\r\n // if this child is active (highlighted)\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n // alert(\"last space active\");\r\n\r\n // this child exprssion/space is selected. A selected\r\n // child is highlighted \r\n //\r\n if (!sO.isSpaceActive)\r\n cprop = \" style='background-color:#dcffed' \";\r\n else\r\n sprop += \" class='scursor' \";\r\n\r\n\r\n } else {\r\n // For showing where the spaces are\r\n // sprop += \" style='background-color:#fafafa' \";\r\n }\r\n\r\n // First add space, and then add spans for child expression\r\n // We insert insertion spaces only if a statement is editable\r\n //\r\n ret += \"<span \" + sprop + \"> </span>\";\r\n // \r\n if (i < e.exprArr.length) {\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n ret += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n\r\n }\r\n }\r\n\r\n // STEP: \r\n // Handle the leading *keyword* like if/else/elseif/foreach/...\r\n // NOTE: These keywords are NOT childrend of expression 'e' but\r\n // keywords are stroted in e.str which is the node itself.\r\n // in such cases, ROOTPOS is used as the child pos w/ \r\n // myPath (not parentPath + childPos)\r\n //\r\n if (e.isCondition() || e.isLoopStmt()) {\r\n\r\n // put onclick function and cursor changing\r\n // Note: since this is the root node property, we use myPath\r\n // instead of parentPath (plus ROOTPOS)\r\n //\r\n var onc_args = \"\\\"\" + myPath + \"\\\",\" + ROOTPOS;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n var gprop = oncE;\r\n //\t\r\n // if the keyword (at ROOTPS) is selected, highlight it\r\n // NOTE: keyword is in e.str and hence we use ROOTPOS as childPos\r\n //\r\n if ((sO.activeParentPath == myPath) &&\r\n (sO.activeChildPos == ROOTPOS)) {\r\n\r\n gprop += \" style='background-color:#dcffed'\";\r\n\r\n } else {\r\n gprop += \" style='cursor:pointer' \";\r\n }\r\n //\r\n if (!(ret == \"\") && (e.isIf() || e.isElseIf() || e.isBreakIf()))\r\n ret = \" (\" + ret + \")\";\r\n //\r\n ret = \" <span \" + gprop + \">\" + e.str + \"</span>\" + ret;\r\n\r\n }\r\n\r\n\r\n } else if (e.isRange()) {\r\n\r\n // Note: There are no child spaces within a range, so no space handling\r\n // is necessary\r\n //\r\n var rcont = \"\"; // range contents within ( )\r\n\r\n // whether the range name 'e.g., row, col' is highlighted by my parent\r\n //\r\n var amIhigh = (parentPath == sO.activeParentPath) &&\r\n (myPos == sO.activeChildPos);\r\n\r\n // if my parent has highlighted me OR if I am highligting a child of\r\n // mine like start/end/step, only then print start/step/end\r\n //\r\n if (amIhigh || (myPath == sO.activeParentPath)) {\r\n\r\n // Tool tips for each of he fields in the range\r\n //\r\n var rtips = ['grid name', 'start', 'end', 'step'];\r\n\r\n // For production caption/start/end/step. The output should\r\n // look like caption(start:end:step)\r\n //\r\n for (var i = 0; i < e.exprArr.length; i++) {\r\n\r\n // Add tool tip\r\n //\r\n var cprop = \" title='\" + rtips[i] + \"' \";\r\n\r\n if (i == 1) rcont += \"(\"; // after grid caption\r\n if (i > 1) rcont += \":\"; // after start/end\r\n\r\n // if this child is active (highlighted)\r\n //\r\n if ((myPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n i)) {\r\n\r\n cprop += \" style='background-color:#dcffed' \";\r\n }\r\n\r\n var ccont = getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n\r\n // alert(\"cont: \" + ccont);\r\n\r\n rcont += \"<span \" + cprop + \">\" + ccont + \"</span>\";\r\n }\r\n\r\n // put = ) around the 'caption(start:end:step' produced above\r\n //\r\n rcont = \"=\" + rcont + \")\";\r\n }\r\n\r\n // put onclick function and cursor changing for grid name\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='rangeClicked(\" + onc_args + \")' \";\r\n var rprop = oncE + \" style='cursor:pointer' \";\r\n rprop += \" title='index variable name' \";\r\n //\t\r\n ret = \"<span \" + rprop + \">\" + e.labelExpr.str + \"</span>\" +\r\n rcont;\r\n\r\n\r\n } else if (e.isLet()) {\r\n\r\n\r\n // This is a let definition (i.e., at position 0). Non definition\r\n // let names are handled as a regular leaf case\r\n\r\n // put onclick function for 'let' keyword\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos + \",\" + sO.curBox\r\n var oncLet = \" onclick='letClicked(\" + onc_args + \")' \";\r\n\r\n\r\n // Use mouse down/up functions on the let 'name'. Click and press to\r\n // edit. \r\n //\r\n var oncName = \" onmousedown='letNameMouseDown(\" + onc_args +\r\n \",this)' \" + \" onmouseup='letNameMouseUp(\" + onc_args +\r\n \",this)' \";\r\n\r\n var namestr = \"\";\r\n\r\n // the identifier for let is always at the 0th position\r\n //\r\n var ident = e.exprArr[0].str;\r\n\r\n // if this let definition is already selected, enable editing\r\n // of the let name. Otherwise, change cursor and font color to \r\n // show it is a clickable definition\r\n //\r\n if ((parentPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n myPos)) {\r\n //var onin_args = \" oninput=\\\"updateLetName(this)\\\" \"; \r\n var onin_args = \" onblur=\\\"updateLetName(this)\\\" \";\r\n oncName = \" contenteditable \" + onin_args;\r\n\r\n // NOTE: For some odd reason, we cannot put a space just before\r\n // the equal sign -- after </span> with contenteditable\r\n //\r\n namestr = \"<span \" + oncName + \">\" + ident + \"</span>=\";\r\n\r\n\r\n } else {\r\n\r\n // this let definition is not active. So, just draw it\r\n //\r\n oncName += \" style='cursor:pointer;color:brown' \";\r\n namestr = \"<span \" + oncName + \">\" + ident + \"</span> =\";\r\n\r\n }\r\n\r\n // Put let keyword and name\r\n //\r\n ret = \"<span \" + oncLet + \">let </span>\" + namestr;\r\n\r\n\r\n } else if (e.isLeaf()) { // any other leaf expr not handled above\r\n\r\n // Note: leaves like operators, indices are handled here\r\n //\r\n // Note: put leaf processing at the end because there are other\r\n // leaf expressions handled above which require special \r\n // handling\r\n // Note: Since this is a leaf, no highlighting is involved. \r\n // Highlighting is always parent's responsibility. However,\r\n // onclick handling for an expr is always child's responsibility.\r\n // For onclick, we need parent's seq# and my position --\r\n // position of e -- in parents exprArr().\r\n\r\n // if the leaf is selected (highlighted), in some cases we need to \r\n // allow editing of the leaf (e.g., for a number/string constant)\r\n //\r\n var prop = \"\";\r\n //\r\n if ((parentPath == sO.activeParentPath) && (sO.activeChildPos ==\r\n myPos)) {\r\n\r\n if (e.isNumber()) {\r\n prop = \" contenteditable onblur=\\\"updateNumber(this)\\\" \";\r\n } else if (e.isString()) {\r\n prop = \" contenteditable onblur=\\\"updateString(this)\\\" \";\r\n }\r\n }\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n var quote = (e.isString()) ? \"'\" : \"\";\r\n //\r\n ret = quote + \"<span \" + oncE + prop + \">\" + e.str + \"</span>\" +\r\n quote;\r\n\r\n } else if (e.isConcat()) {\r\n\r\n //alert(\"Concat\");\r\n\r\n // if this is an index concatanation -- e.g., col+4\r\n //\r\n var cont = \"\"; // contents of the concatenated index expr\r\n //\r\n for (var i = 0; i < e.exprArr.length; i++) {\r\n\r\n // No highlighting of children in index conacatenation\r\n //\r\n cont += getHtmlExprStmt(e.exprArr[i], sO, myPath, i);\r\n }\r\n\r\n // Put a span and onclick function around this concatenated \r\n // expression (since the entire concatenated expression is treate\r\n // as a leaf)\r\n //\r\n var onc_args = \"\\\"\" + parentPath + \"\\\",\" + myPos;\r\n var oncE = \" onclick='exprClicked(\" + onc_args + \")' \";\r\n ret = \"<span \" + oncE + \">\" + cont + \"</span>\";\r\n\r\n\r\n } else {\r\n\r\n alert(\"TODO: Handle expression not handled above\");\r\n }\r\n\r\n\r\n return ret;\r\n\r\n}",
"function printWikiSyntax()\n{\n print(\"\\t<div class=\\\"wikisyntax\\\">\\n\");\n print(\"\\t<table>\\n\");\n print(\"\\t\\t<tr>\\n\");\n print(\"\\t\\t\\t<td colspan=3>\");\n print(wikiparse(\"**__Syntax__** \")+\"<span class=\\\"optionalvalue\\\">(optional values)</span><br />\");\n print(\"\\t\\t\\t</td>\\n\");\n print(\"\\t\\t</tr>\\n\");\n print(\"\\t\\t<tr>\\n\");\n print(\"\\t\\t\\t<td align=\\\"right\\\">\");\n print( \"bold text: <br />\" );\n print( \"italic text: <br />\" );\n print( \"underlined text: <br />\" );\n print( \"verbatim(無効) text: <br />\" );\n print( \"link: <br />\" );\n if ( config.SYNTAX.WIKIWORDS )\n print( \"wiki link: <br />\" );\n print( \"image: <br />\" );\n print( \"hex-coloured text: <br />\" );\n if ( config.SYNTAX.HTMLCODE )\n print( \"html code: <br />\" );\n print( \"anchor link: <br />\" );\n print(\"\\t\\t\\t</td>\\n\");\n print(\"\\t\\t\\t<td>\");\n print( \"**abc**<br />\" );\n print( \"''abc''<br />\" );\n print( \"__abc__<br />\" );\n print( \"~~~abc~~~<br />\" );\n print( \"[[url|<span class=\\\"optionalvalue\\\">description</span>|<span class=\\\"optionalvalue\\\">target</span>]]<br />\" );\n if ( config.SYNTAX.WIKIWORDS )\n print( \"WikiWord<br />\" );\n print( \"{{url|<span class=\\\"optionalvalue\\\">alt</span>|<span class=\\\"optionalvalue\\\">width</span>|<span class=\\\"optionalvalue\\\">height</span>|<span class=\\\"optionalvalue\\\">align</span>|<span class=\\\"optionalvalue\\\">vertical-align</span>}}<br />\" );\n print( \"~~#AAAAAA:grey~~<br />\" );\n if ( config.SYNTAX.HTMLCODE )\n print( \"%%html code%%<br />\" );\n print( \"@@name@@<br />\" );\n print(\"\\t\\t\\t</td>\\n\");\n print(\"\\t\\t</tr>\\n\");\n print(\"\\t</table>\\n\");\n print(\"\\t</div>\\n\");\n}",
"function someFunctionDefinition(){\n console.log(\"this is a function statement\");\n}",
"function createDocumentation( sections ) {\n\n var documentedHtml = '',\n commentHtml = '',\n codeHtml = '',\n pretty = ( settings.pretty ) ? 'prettyprint' : '',\n linenums = 0;\n\n sections.forEach( function( s, indx ) {\n\n // add comments to line count since they always occur in a section before code\n linenums += s.comment.split(/\\|/).length - 1;\n if ( indx === 0) {\n commentHtml = '<div class=\"elucidate-comment-header\">' + formatHeader( s.comment ) + '</div>';\n documentedHtml +=\n '<div class=\"row elucidate-header\"> \\\n <div class=\"col-sm-12\">'+commentHtml+'</div> \\\n </div> \\\n <div class=\"row elucidate-row\"> \\\n <div class=\"col-sm-'+settings.width.comment+' elucidate-col-comment\"><div class=\"elucidate-comment elucidate-hack-width\">'+Array(settings.width.hack).join(' ')+'</div></div> \\\n <div class=\"col-sm-'+settings.width.code+' elucidate-col-code\"></div></div> \\\n </div>';\n } else {\n commentHtml = '<div class=\"elucidate-comment\">' + cheapMarkdown( s.comment ) + '</div>';\n codeHtml = (s.code !== '') ? '<pre class=\"elucidate-code '+pretty+' linenums:'+(linenums+1).toString() +'\">' + safeHtml( s.code ) + '</pre>' : '';\n documentedHtml +=\n '<div class=\"row elucidate-row\"> \\\n <div class=\"col-sm-'+settings.width.comment+' elucidate-col-comment\">'+commentHtml+'</div> \\\n <div class=\"col-sm-'+settings.width.code+' elucidate-col-code\">'+codeHtml+'</div> \\\n </div>';\n\n }\n // add code to line count\n linenums += s.code.split(/\\n/).length - 1 ;\n } );\n\n return documentedHtml;\n }",
"function renderDefinitions(sourceFile, analyzedClass, imports) {\n var printer = ts.createPrinter();\n var name = analyzedClass.declaration.name;\n var definitions = analyzedClass.compilation\n .map(function (c) { return c.statements.map(function (statement) { return transform_1.translateStatement(statement, imports); })\n .concat(transform_1.translateStatement(createAssignmentStatement(name, c.name, c.initializer), imports))\n .map(function (statement) {\n return printer.printNode(ts.EmitHint.Unspecified, statement, sourceFile);\n })\n .join('\\n'); })\n .join('\\n');\n return definitions;\n }",
"function FormulaPage() {}",
"visitPeriod_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function createRangeDescription() {\n if((!dual || single) && incrementTop === 1) {\n return `(range: ${topStart} to ${topEnd})`;\n } else if((!dual || single) && incrementTop !== 1) {\n return `(range: ${topStart} to ${topEnd}(step ${incrementTop}))`;\n } else if((topStart === bottomStart && topEnd === bottomEnd)) {\n return `(range: ${topStart} to ${topEnd}(top step ${incrementTop}, bottom step ${incrementBottom}))`;\n } else if(incrementTop === incrementBottom && (incrementTop !== 1 || incrementBottom !== 1)) {\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementTop}))`;\n } else if(incrementTop === incrementBottom){\n return `(ranges: ${topStart} to ${topEnd}(top) ${bottomStart} to ${bottomEnd}(bottom))`;\n } else {\n return `(ranges: ${topStart} to ${topEnd}(top) (step ${incrementTop}) ${bottomStart} to ${bottomEnd}(bottom) (step ${incrementBottom}))`;\n }\n }",
"function makeHtml(options) {\n options = options || {};\n\n var parts, fnCounter, propId, props;\n\n // Tagged function can be called multiple times, need to generate unique\n // IDs and track unique values per full use (until html.done is called).\n function reset() {\n parts = [];\n fnCounter = 0;\n propId = props = undefined;\n }\n reset();\n\n // The html() function used for the tagged template string. Call\n // html.done() to get the final string result.\n function html(strings, ...values) {\n strings.forEach(function(str, i) {\n // If there is no following value, at the end, just return;\n if (i >= values.length) {\n parts.push(str);\n return;\n }\n\n var value = values[i];\n if (!options.toStringAll &&\n typeof value !== 'string' &&\n !(value instanceof EscapedValue)) {\n // Check for propName=\" as the end of the previous string, if so, it\n // is a name to a property to be set/called later with the value.\n var match = propRegExp.exec(str);\n // data-prop should go the string path, since that is a defined HTML\n // API that maps to element.dataset.prop.\n if (match && match[1].indexOf('data-') !== 0) {\n if (propId === undefined) {\n propId = (idCounter++);\n }\n\n var propValueId = 'id' + (fnCounter++);\n\n if (!props) {\n props = {};\n }\n\n var propName = match[1];\n // Convert a-prop-name to aPropName\n if (propName.indexOf('-') !== -1) {\n propName = propName.split('-').map(function(part, partIndex) {\n return partIndex === 0 ?\n part : part.charAt(0).toUpperCase() + part.substring(1);\n }).join('');\n }\n\n props[propValueId] = {\n value: value,\n propName: propName\n };\n\n value = propValueId;\n\n // Swap out the attribute name to be specific to this html() use,\n // to make query selection faster and targeted.\n str = str.substring(0, match.index) + ' data-htemplateprop' +\n propId + '=\"';\n }\n }\n\n parts.push(str);\n\n if (value instanceof EscapedValue) {\n value = value.escapedValue;\n } else {\n if (typeof value !== 'string') {\n value = String(value);\n }\n value = esc(value);\n }\n parts.push(value);\n });\n }\n\n // Generates the final response by concatenating the previous html`` calls\n // into the final result.\n html.done = function() {\n var text = parts.join('');\n\n if (propId !== undefined) {\n // Process the text to replace multiple data-htemplateprop attributes\n // with one that groups the values. Otherwise the browser will just keep\n // the first value.\n text = groupProps(propId, text);\n }\n\n var result = {\n text: text\n };\n\n if (propId !== undefined) {\n result.propId = propId;\n result.props = props;\n }\n\n reset();\n\n return result;\n };\n\n return html;\n }",
"visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change function of the slider mass of object b | function massOfObjBChange(scope) {
mass_ball_b = scope.mass_of_b;
getChild("ball_b").scaleX = 0.5 + (scope.mass_of_b - 1) / 20;
getChild("ball_b").scaleY = 0.5 + (scope.mass_of_b - 1) / 20;
ball_b_radius = (getChild("ball_b").image.height * getChild("ball_b").scaleY) / 2;
} | [
"function massOfObjAChange(scope) {\n mass_ball_a = scope.mass_of_a;\n getChild(\"ball_a\").scaleX = 0.5 + (scope.mass_of_a - 1) / 20;\n getChild(\"ball_a\").scaleY = 0.5 + (scope.mass_of_a - 1) / 20;\n ball_a_radius = (getChild(\"ball_a\").image.height * getChild(\"ball_a\").scaleY) / 2;\n}",
"function sliderMove()\r\n{\r\n var offset = 0\r\n for (var t = 0; t < sliders.length; t++)\r\n {\r\n var slid = map(sin(angle+offset), -1, 1, 0, 255)\r\n sliders[t].value(slid)\r\n offset += vTest;\r\n } \r\n}",
"function slider_equation(val)\n{\n return (4.5 * Math.pow(val,2) - (0.75 * val) + 0.25);\n}",
"set speedVariation(value) {}",
"function minEleonchange(evt) {\n var uig = getg(this);\n uig.sliderEle.min = this.value*1;\n genedefs[uig.name].min = this.value*1;\n}",
"set bounceMinVelocity(value) {}",
"burnFuel(){\n this.fuel -=1;\n }",
"function rActive (fm10ros) {\n return 3.34 * fm10ros\n}",
"set useFriction(value) {}",
"increaseSpeed(value){\r\n this.speed += value;\r\n }",
"function setSourceVelocityFn(scope) {\n\tsource_velocity = scope.source_velocity_value; /** Setting the source speed based on the slider value */\n\tcircle_centre = 100; /**Resetting the circle radius while changing the slider */\n}",
"function scale_changed() {\n\n var s = document.getElementById(\"scale_input\");\n //alert(\"slider value \" + s.value);\n\n var range = s.value / 100; // .25 - 2\n\n g_config.scale_factor = range;\n\n if (g_enableInstrumentation) {\n alert(\"scale_factor \" + g_config.scale_factor);\n }\n\n updateScaleCSS(g_config.scale_factor);\n\n refreshMode();\n}",
"sliderBounce() {\n this.directionX = -this.directionX;\n }",
"increaseBallSpeed() {\n this.ballSpeed += 0.001;\n }",
"get forceScale() {}",
"get scale() { return (this.myscale.x + this.myscale.y)/2;}",
"function setSpeed(s)\r\n{\r\n \r\n ballSpeed = s;\r\n}",
"set smoothness(value) {}",
"function setDifference() {\n differenceThreshold = dSlider.value();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a schema object that matches a Buffer data type | function BufferType() {
BufferType.super_.call(this);
} | [
"deserialize(any) {\n const desc = this.lookupDescriptor(any);\n let bytes = any.value;\n if (typeof bytes === \"undefined\") {\n bytes = new Buffer(0);\n }\n return desc.decode(bytes);\n }",
"function makeBuffer(data) {\n\tvar buff = new Buffer(0), chunk;\n\tvar i = 0, j;\n\tfor(; i < data.length; ++i) {\n\t\tswitch (data[i].type) {\n\t\t\tcase type.short:\n\t\t\t\tchunk = new Buffer(2);\n\t\t\t\tchunk.writeInt16BE(data[i].value, 0);\n\t\t\t\tbreak;\n\n\t\t\tcase type.byte:\n\t\t\t\tchunk = new Buffer(1);\n\t\t\t\tchunk.writeInt8(data[i].value, 0);\n\t\t\t\tbreak;\n\n\t\t\tcase type.string:\n\t\t\t\tchunk = new Buffer(2 + (data[i].value.length * 2));\n\t\t\t\tchunk.fill(0);\n\n\t\t\t\t// Write the size (-2 because size is included in chunk.length)\n\t\t\t\tchunk.writeInt16BE(chunk.length - 2, 0);\n\n\t\t\t\t// Write the string character at a time because uft8 only encodes one byte per character\n\t\t\t\tvar j = 0;\n\t\t\t\tfor (; j < data[i].value.length; ++j) {\n\t\t\t\t\tchunk.writeInt16BE(data[i].value.charCodeAt(j), 2 + (j * 2));\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tconsole.log('Unrecognized type: \"' + data[i].type + '\"');\n\t\t\t\treturn buff;\n\t\t}\n\n\t\tbuff = Buffer.concat([buff, chunk]);\n\t}\n\n\treturn buff;\n}",
"async getJsonSchema(obj) {\n var self = this;\n\n // start creating the schema\n var jsonSchema = {\n definitions: {},\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n type: \"object\",\n properties: {}\n }\n var properties = {}\n var required = []\n\n // interpret the info message and create json schema\n self.rawSql.split('\\n').forEach(function (rawLine, index) {\n var line = self.sanitizeLine(rawLine)\n\n // ignore lines we're not interested in\n // TODO: these are important:\n // CONSTRAINT - primary key(s)\n // ALTER TABLE - foreign keys\n if (\n line.startsWith(\"CREATE\") ||\n line.startsWith(\"ALTER TABLE\") ||\n line.startsWith(\"CONSTRAINT\") ||\n line.startsWith('(') ||\n line.startsWith(')') ||\n line.length == 0\n ) {\n return\n }\n\n var lineSplit = line.trim().split(' ')\n\n // remove the brackets from the col name\n const columnName = lineSplit[0].substring(1, lineSplit[0].length-1);\n const dataType = lineSplit[1]\n\n properties[columnName] = {}\n // set description as the col type\n properties[columnName].description = dataType\n\n var dataTypeOnly = dataType.replace(/\\(.*\\)/, '')\n\n var isString = false\n // useful: https://www.connectionstrings.com/sql-server-2008-data-types-reference/\n switch (dataTypeOnly.toUpperCase()) {\n case 'BIGINT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = Math.pow(-2, 63)\n properties[columnName].exclusiveMaximum = Math.pow(2, 63)\n break\n case 'INT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = -2147483648\n properties[columnName].maximum = 2147483647\n break\n case 'SMALLINT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = -32768\n properties[columnName].maximum = 32767\n break\n case 'TINYINT':\n properties[columnName].type = 'integer'\n properties[columnName].minimum = 0\n properties[columnName].maximum = 255\n break\n case \"BIT\":\n properties[columnName].type = 'boolean'\n break\n case \"DECIMAL\":\n case \"NUMERIC\":\n properties[columnName].type = 'number'\n properties[columnName].exclusiveMinimum = Math.pow(-10, 38)\n properties[columnName].exclusiveMaximum = Math.pow(10, 38)\n break\n case \"MONEY\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = Math.pow(-2, 63) / 10000\n properties[columnName].maximum = (Math.pow(2, 63) - 1) / 10000\n break\n case \"SMALLMONEY\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = -214748.3648\n properties[columnName].maximum = 214748.3647\n break\n case \"FLOAT\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = -1.79e308\n properties[columnName].maximum = 1.79e308\n break\n case \"REAL\":\n properties[columnName].type = 'number'\n properties[columnName].minimum = -3.40e38\n properties[columnName].maximum = 3.40e38\n break\n case \"DATETIME\":\n case \"SMALLDATETIME\":\n case \"DATETIME2\":\n properties[columnName].type = 'string'\n // TODO should we accept sql server syntax instead?\n properties[columnName].format = \"date-time\"\n break\n case \"DATE\":\n properties[columnName].type = 'string'\n // TODO should we accept sql server syntax instead?\n properties[columnName].format = \"date\"\n break\n case \"TIME\":\n properties[columnName].type = 'string'\n // TODO should we accept sql server syntax instead?\n properties[columnName].format = \"time\"\n break\n case 'CHAR':\n isString = true\n properties[columnName].maxLength = 8000\n break\n case \"NCHAR\":\n isString = true\n properties[columnName].maxLength = 8000\n break\n case 'VARCHAR':\n isString = true\n properties[columnName].maxLength = Math.pow(2, 31)\n break\n case 'NVARCHAR':\n isString = true\n properties[columnName].maxLength = Math.pow(2, 30)\n break\n case \"TEXT\":\n isString = true\n properties[columnName].maxLength = 2147483647\n break\n case \"NTEXT\":\n isString = true\n properties[columnName].maxLength = 1073741823\n break\n case \"UNIQUEIDENTIFIER\":\n properties[columnName].type = 'string'\n properties[columnName].format = \"uuid\"\n properties[columnName].minLength = 36\n properties[columnName].maxLength = 36\n break;\n case \"XML\":\n properties[columnName].type = 'string'\n break\n // unsupported yet\n //case \"DATETIMEOFFSET\":\n //case \"BINARY\":\n //case \"VARBINARY\":\n //case \"IMAGE\":\n //case \"GEOGRAPHY\":\n //case \"GEOMETRY\":\n //case \"HIERARCHYID\":\n default:\n throw ('Unknown type: ' + dataType)\n }\n\n // handle extra stuff for strings\n if (isString) {\n properties[columnName].type = 'string'\n properties[columnName].minLength = 0\n\n // extract the max length\n var maxLength = dataType.substring(\n dataType.lastIndexOf(\"(\") + 1,\n dataType.lastIndexOf(\")\")\n );\n\n // if this isnt set to max then include it (max was set above)\n if (maxLength.toLowerCase() != 'max') {\n properties[columnName].maxLength = parseInt(maxLength)\n }\n }\n\n // check if it can be null\n if (line.endsWith(\"NOT NULL\")) {\n required.push(columnName)\n }\n });\n\n // sew the schema together\n jsonSchema.properties = properties\n jsonSchema.required = required\n\n return JSON.stringify(jsonSchema)\n }",
"* genFromBuffers (opts) {\n opts = opts === undefined ? {} : opts\n let res\n res = yield * this.expect(4)\n this.magicNum = new Br(res.buf).readUInt32BE()\n if (opts.strict && this.magicNum !== this.constants.Msg.magicNum) {\n throw new Error('invalid magicNum')\n }\n res = yield * this.expect(12, res.remainderbuf)\n this.cmdbuf = new Br(res.buf).read(12)\n res = yield * this.expect(4, res.remainderbuf)\n this.datasize = new Br(res.buf).readUInt32BE()\n if (opts.strict && this.datasize > this.constants.MaxSize) {\n throw new Error('message size greater than maxsize')\n }\n res = yield * this.expect(4, res.remainderbuf)\n this.checksumbuf = new Br(res.buf).read(4)\n res = yield * this.expect(this.datasize, res.remainderbuf)\n this.dataBuf = new Br(res.buf).read(this.datasize)\n return res.remainderbuf\n }",
"function toBuffer(v){if(!Buffer.isBuffer(v)){if(typeof v==='string'){if(isHexPrefixed(v)){return Buffer.from(padToEven(stripHexPrefix(v)),'hex');}else{return Buffer.from(v);}}else if(typeof v==='number'){if(!v){return Buffer.from([]);}else{return intToBuffer(v);}}else if(v===null||v===undefined){return Buffer.from([]);}else if(v instanceof Uint8Array){return Buffer.from(v);}else if(BN.isBN(v)){// converts a BN to a Buffer\nreturn Buffer.from(v.toArray());}else{throw new Error('invalid type');}}return v;}",
"newSchema() {\n const { ctx } = this;\n if (!this.useModelAsBase && this.isNewFile) {\n if (!this.options.name) {\n this.log.error('Missing schema name: yo labs:schema [name] \\n');\n this.log(this.help());\n process.exit(1);\n }\n const fileName = this.options.name\n .trim()\n .toLowerCase();\n\n const name = fileName.split('-').map((item) => {\n const firstChar = item.substring(0, 1).toUpperCase();\n return `${firstChar}${item.substring(1)}`;\n }).join('');\n\n const [schemaProdDeps, schemaDevDeps, schemaScripts] = template\n .createNewSchema(this, this.newFilePath, {\n importExport: ctx.importExport || true,\n name,\n });\n\n this.deps.prod.push(...schemaProdDeps);\n this.deps.dev.push(...schemaDevDeps);\n Object.assign(this.pkgScripts, schemaScripts);\n }\n }",
"schema(schema) {\n if (arguments.length) {\n this._schema = schema;\n return this;\n }\n if (!this._schema) {\n this._schema = this.constructor.definition();\n }\n return this._schema;\n }",
"function RecordType(schema, opts) {\n opts = getOpts(schema, opts);\n\n var resolutions = resolveNames(schema, opts.namespace);\n this._name = resolutions.name;\n this._aliases = resolutions.aliases;\n Type.call(this, opts.registry);\n\n if (!(schema.fields instanceof Array)) {\n throw new Error(f('non-array %s fields', this._name));\n }\n if (utils.hasDuplicates(schema.fields, function (f) { return f.name; })) {\n throw new Error(f('duplicate %s field name', this._name));\n }\n this._fields = schema.fields.map(function (f) {\n return new Field(f, opts);\n });\n\n this._constructor = this._createConstructor();\n this._read = this._createReader();\n this._skip = this._createSkipper();\n this._write = this._createWriter();\n this.isValid = this._createChecker();\n}",
"function makeSchema( entity ) {\n try {\n //DELETE EXTRA KEYS FROM MAP WHICH ARE NOT IN SCHEMA STRUCTURE\n Object.keys( entity ).forEach( ( property ) => {\n if( structure[ property ] == null ) {\n delete entity[ property ];\n }\n });\n //ADD NON EXISTING KEYS WITH DEFAULT VALUE\n Object.keys( structure ).forEach( ( property ) => {\n if( entity[ property ] == null ) {\n entity[ property ] = makeFunctions[ structure[ property ].type ]( structure[ property ].default );\n } else {\n entity[ property ] = makeFunctions[ structure[ property ].type ]( entity[ property ] );\n }\n });\n checkSchema( entity );\n return entity;\n } catch( error ) {\n throw error;\n }\n }",
"function main() {\n var builder = new flatbuffers.Builder(0);\n\n console.log(OMM.addBSTAR.toString().match(/builder\\.add([^\\(]{1,})/)[1]);\n console.log(builder.createFieldFloat32)\n let name = builder.createString('ISS');\n let centername = builder.createString('NASA JOHNSON SPACE FLIGHT CENTER, SOMEWHERE IN TEXAS, USA');\n OMM.startOMM(builder);\n \n OMM.addOBJECTNAME(builder, name);\n OMM.addCENTERNAME(builder, centername);\n var issBuiltOMM = OMM.endOMM(builder);\n\n builder.finish(issBuiltOMM);\n let testObject = {\n OBJECTNAME:\"ISS\",\n CENTERNAME:\"NASA JOHNSON SPACE FLIGHT CENTER, SOMEWHERE IN TEXAS, USA\"\n };\n console.log(testObject,\"\\n\", btoa(JSON.stringify(testObject)));\n var buf = builder.dataBuffer();\n let uint8 = builder.asUint8Array();\n var decoder = new TextDecoder('utf8');\n var b64encoded = btoa(unescape(encodeURIComponent(decoder.decode(uint8))));\n console.log(b64encoded);\n // Get access to the root:\n var iss = OMM.getRootAsOMM(buf);\n\n assert.equal(iss.OBJECTNAME(), 'ISS');\n console.log('\\n\\n\\n\\n');\n //for(let x in iss)console.log(x);\n Object.defineProperty(iss, 'OBJECT_NAME', {get:iss.OBJECTNAME});\n console.log(iss.OBJECT_NAME);\n console.log('The FlatBuffer was successfully created and verified!');\n}",
"function convertGeometryToBufferGeometry( geometry ) {\n\n return new BufferGeometry().fromGeometry( geometry );\n\n}",
"function mapTypeToSchema(p) {\n\tvar output;\n\tswitch (p) {\n\tcase \"Place\":\n\t\toutput = \"http://schema.org/Place\";\n\tbreak;\n\tcase \"Organization\":\n\t\toutput = \"http://schema.org/Organization\";\n\tbreak;\n\tcase \"Person\":\n\t\toutput = \"http://schema.org/Person\";\n\tbreak;\t\n\tdefault:\n\t\toutput = null;\n\t}\n\treturn output;\n}",
"serialize(obj) {\n if (!obj.constructor || typeof obj.constructor.encode !== \"function\" || !obj.constructor.$type) {\n throw new Error(\"Object \" + JSON.stringify(obj) +\n \" is not a protobuf object, and hence can't be dynamically serialized. Try passing the object to the \" +\n \"protobuf classes create function.\")\n }\n return Any.create({\n type_url: \"type.googleapis.com/\" + AnySupport.fullNameOf(obj.constructor.$type),\n value: obj.constructor.encode(obj).finish()\n });\n }",
"function schemaToSampleObj(schema) {\n var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var obj = {};\n\n if (!schema) {\n return;\n }\n\n if (schema.allOf) {\n var objWithAllProps = {};\n\n if (schema.allOf.length === 1 && !schema.allOf[0].properties && !schema.allOf[0].items) {\n // If allOf has single item and the type is not an object or array, then its a primitive\n if (schema.allOf[0].$ref) {\n return '{ }';\n }\n\n if (schema.allOf[0].readOnly && config.includeReadOnly) {\n var tempSchema = schema.allOf[0];\n return getSampleValueByType(tempSchema);\n }\n\n return;\n }\n\n schema.allOf.map(v => {\n if (v.type === 'object' || v.properties || v.allOf || v.anyOf || v.oneOf) {\n var partialObj = schemaToSampleObj(v, config);\n Object.assign(objWithAllProps, partialObj);\n } else if (v.type === 'array' || v.items) {\n var _partialObj = [schemaToSampleObj(v, config)];\n Object.assign(objWithAllProps, _partialObj);\n } else if (v.type) {\n var prop = \"prop\".concat(Object.keys(objWithAllProps).length);\n objWithAllProps[prop] = getSampleValueByType(v);\n } else {\n return '';\n }\n });\n obj = objWithAllProps;\n } else if (schema.oneOf) {\n if (schema.oneOf.length > 0) {\n obj = schemaToSampleObj(schema.oneOf[0], config);\n }\n } else if (schema.anyOf) {\n // First generate values for regular properties\n if (schema.type === 'object' || schema.properties) {\n for (var key in schema.properties) {\n if (schema.properties[key].deprecated && !config.includeDeprecated) {\n continue;\n }\n\n if (schema.properties[key].readOnly && !config.includeReadOnly) {\n continue;\n }\n\n if (schema.properties[key].writeOnly && !config.includeWriteOnly) {\n continue;\n }\n\n if (schema.example) {\n obj[key] = schema.example;\n } else if (schema.examples && schema.example.length > 0) {\n obj[key] = schema.examples[0];\n } else {\n obj[key] = schemaToSampleObj(schema.properties[key], config);\n }\n }\n }\n\n var i = 1;\n\n if (schema.anyOf.length > 0) {\n obj[\"prop\".concat(i)] = schemaToSampleObj(schema.anyOf[0], config);\n i++;\n }\n } else if (schema.type === 'object' || schema.properties) {\n for (var _key in schema.properties) {\n if (schema.properties[_key].deprecated && !config.includeDeprecated) {\n continue;\n }\n\n if (schema.properties[_key].readOnly && !config.includeReadOnly) {\n continue;\n }\n\n if (schema.properties[_key].writeOnly && !config.includeWriteOnly) {\n continue;\n }\n\n if (schema.example) {\n obj[_key] = schema.example;\n break;\n } else if (schema.examples && schema.example.length > 0) {\n obj[_key] = schema.examples[0];\n break;\n } else {\n obj[_key] = schemaToSampleObj(schema.properties[_key], config);\n }\n }\n } else if (schema.type === 'array' || schema.items) {\n if (schema.example) {\n obj = schema.example;\n } else if (schema.examples && schema.example.length > 0) {\n obj = schema.examples[0];\n } else {\n obj = [schemaToSampleObj(schema.items, config)];\n }\n } else {\n return getSampleValueByType(schema);\n }\n\n return obj;\n}",
"static getCompiledSchema () {\n if (!this._compiledSchema) {\n this._compiledSchema = new Schema(this)\n }\n return this._compiledSchema\n }",
"function createMessageBodyAssetFromJsonSchema(jsonSchema) {\n let messageBody = {};\n let annotation = undefined;\n\n try {\n messageBody = jsonSchemaFaker(jsonSchema);\n } catch (e) {\n annotation = new Annotation(e.message);\n annotation.code = 3; // Data is being lost in the conversion.\n annotation.classes.push('warning');\n }\n\n const bodyAsset = new Asset(JSON.stringify(messageBody, null, 2));\n bodyAsset.classes.push('messageBody');\n bodyAsset.attributes.set('contentType', 'application/json');\n\n let refractAnnotation = {};\n if (annotation !== undefined) {\n refractAnnotation = annotation.toRefract();\n }\n\n return {\n bodyAsset: bodyAsset.toRefract(),\n annotation: refractAnnotation,\n };\n}",
"function schemaToModel(schema, obj) {\n if (schema == null) {\n return;\n }\n if (schema.type === \"object\" || schema.properties) {\n for (let key in schema.properties) {\n obj[key] = schemaToModel(schema.properties[key], {});\n }\n }\n else if (schema.type === \"array\" || schema.items) {\n //let temp = Object.assign({}, schema.items );\n obj = [schemaToModel(schema.items, {})]\n }\n else if (schema.allOf) {\n if (schema.allOf.length === 1) {\n if (!schema.allOf[0]) {\n return `string~|~${schema.description ? schema.description : ''}`;\n }\n else {\n let overrideAttrib = {\n \"readOnly\": schema.readOnly,\n \"writeOnly\": schema.writeOnly,\n \"depricated\": schema.deprecated\n };\n return `${getTypeInfo(schema.allOf[0], overrideAttrib)}~|~${schema.description ? schema.description : ''}`\n }\n }\n\n // If allOf is an array of multiple elements, then they are the keys of an object\n let objWithAllProps = {};\n schema.allOf.map(function (v) {\n if (v && v.properties) {\n let partialObj = schemaToModel(v, {});\n Object.assign(objWithAllProps, partialObj);\n }\n });\n obj = objWithAllProps;\n }\n else {\n return `${getTypeInfo(schema)}~|~${schema.description ? schema.description : ''}`;\n }\n return obj;\n}",
"static create(field, constraint, schema) {\n if (field.type instanceof GraphQLScalarType) {\n field.type = new this(field.type, constraint);\n } else if (field.type instanceof GraphQLNonNull\n && field.type.ofType instanceof GraphQLScalarType) {\n field.type = new GraphQLNonNull(new this(field.type.ofType, constraint));\n } else if (isWrappingType(field.type) && field.type instanceof GraphQLList) {\n field.type = new GraphQLList(new this(field.type, constraint));\n } else {\n throw new Error(`Type ${field.type} cannot be validated. Only scalars are accepted`);\n }\n\n const typeMap = schema.getTypeMap();\n let { type } = field;\n if (isWrappingType(type)) {\n type = type.ofType;\n }\n\n if (isNamedType(type) && !typeMap[type.name]) {\n typeMap[type.name] = type;\n }\n }",
"function toBsonStructure(obj) {\n if (obj) {\n if (obj instanceof Uint8Array) {\n return new Binary(new Buffer(obj));\n } else if (Array.isArray(obj)) {\n let result = [];\n for (let v of obj) {\n result.push(toBsonStructure(v));\n }\n return result;\n } else if (obj.__proto__ === Object.prototype) {\n let result = {};\n for (let key in obj) {\n result[key] = toBsonStructure(obj[key]);\n }\n return result;\n }\n }\n return obj;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ducnq 12/07/2012 ham hien thi popup chi tiet thong bao | function dsp_popup_chi_tiet_thong_bao(p_loai_giao_dien, p_loai_trang) {
if (p_loai_trang > 0) {
url = "/ajax/thong_bao/index/" + p_loai_giao_dien + "/" + p_loai_trang;
show_box_popup('', 640, 600);
AjaxAction('_box_popup', url);
} else {
alert('Mã thông báo không tồn tại!');
}
} | [
"function ntv_huy_theo_doi() {\n\tvar url = '/ajax/ntv_quan_tri_theo_doi_tin_tuyen_dung/popup_huy_theo_doi/';\n\tshow_box_popup('', 420, 250);\n\tAjaxAction('_box_popup', url);\n\n}",
"function showpopup(msg_id, process_name, top_value) {\n GetFullDetailMessage(msg_id, process_name);\n}",
"function showQuestion(){\n var lstrMessage = '';\n lstrMessageID = showQuestion.arguments[0];\n lobjField = showQuestion.arguments[1];\n lstrCaleeFunction = funcname(arguments.caller.callee);\n //Array to store Place Holder Replacement\n var larrMessage = new Array() ;\n var insertPosition ;\n var counter = 0 ;\n\n larrMessage = showQuestion.arguments[2];\n \n lstrMessage = getErrorMsg(lstrMessageID);\n \n if(larrMessage != null &&\n larrMessage.length > 0 ){\n\n while((insertPosition = lstrMessage.indexOf('#')) > -1){\n\n if(larrMessage[counter] == null ){\n larrMessage[counter] = \"\";\n }\n lstrMessage = lstrMessage.substring(0,insertPosition) +\n larrMessage[counter] +\n lstrMessage.substring(insertPosition+1,lstrMessage.length);\n counter++;\n }\n }\n\n //lstrFinalMsg = lstrMessageID + ' : ' + lstrMessage;\n lstrFinalMsg = lstrMessage;\n\n if(lobjField!=null){\n lobjField.focus();\n }\n var cnfUser = confirm(lstrFinalMsg);\n if( !cnfUser ) {\n isErrFlg = true;\n }\n if(cnfUser && lstrCaleeFunction == 'onLoad'){\n \tdisableButtons('2');\n }\n //End ADD BY SACHIN\n return cnfUser;\n}",
"function PopUp(url, name, width,height,center,resize,scroll,posleft,postop)\r\n{\r\n\tshowx = \"\";\r\n\tshowy = \"\";\r\n\t\r\n\tif (posleft != 0) { X = posleft }\r\n\tif (postop != 0) { Y = postop }\r\n\t\r\n\tif (!scroll) { scroll = 1 }\r\n\tif (!resize) { resize = 1 }\r\n\t\r\n\tif ((parseInt (navigator.appVersion) >= 4 ) && (center))\r\n\t{\r\n\t\tX = (screen.width - width ) / 2;\r\n\t\tY = (screen.height - height) / 2;\r\n\t}\r\n\t\r\n\tif ( X > 0 )\r\n\t{\r\n\t\tshowx = ',left='+X;\r\n\t}\r\n\t\r\n\tif ( Y > 0 )\r\n\t{\r\n\t\tshowy = ',top='+Y;\r\n\t}\r\n\t\r\n\tif (scroll != 0) { scroll = 1 }\r\n\t\r\n\tself.name=\"ori_window\";\r\n\tvar Win = window.open( url, name, 'width='+width+',height='+height+ showx + showy + ',resizable='+resize+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no');\r\n\tWin.focus();\r\n\tWin.document.close;\r\n\r\n}",
"function wpbingo_ShowNLPopup() {\n\t\tif($('.newsletterpopup').length){\n\t\t\tvar cookieValue = $.cookie(\"digic_lpopup\");\n\t\t\tif(cookieValue == 1) {\n\t\t\t\t$('.newsletterpopup').hide();\n\t\t\t\t$('.popupshadow').hide();\n\t\t\t}else{\n\t\t\t\t$('.newsletterpopup').show();\n\t\t\t\t$('.popupshadow').show();\n\t\t\t}\t\t\t\t\n\t\t}\n\t}",
"function call_hscode(){\n\t\tstrURL = \"hs_code.html\";\n\t\tPopupOpenDialog(850,490);\n\n\t\tif(PopWinValue != null ){\n\t\t\tgcDs2.namevalue(gcDs2.rowposition,\"HSCODE\") = PopWinValue[0]; \n\t\t\tgcDs2.namevalue(gcDs2.rowposition,\"HSCODENM\") = PopWinValue[1]; \n\t\t}\n\t}",
"static set popup(value) {}",
"function ShowAlert()\n{\n var a = document.createElement('a');\n a.href='/enUS/search-editor/default.html?mode=newalert&' + $j('#search_state').val();\n a.setAttribute('rel','popup 700 750');\n showpopup(a);\n}",
"function popupFindItem(ui) {\n\n v_global.event.type = ui.type;\n v_global.event.object = ui.object;\n v_global.event.row = ui.row;\n v_global.event.element = ui.element;\n\n switch (ui.element) {\n case \"emp_nm\":\n case \"manager1_nm\":\n case \"manager2_nm\":\n case \"manager3_nm\":\n case \"manager4_nm\": \n {\n var args = { type: \"PAGE\", page: \"DLG_EMPLOYEE\", title: \"사원 선택\"\n \t, width: 700, height: 450, locate: [\"center\", \"top\"], open: true\n };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_EMPLOYEE\",\n param: { ID: gw_com_api.v_Stream.msg_selectEmployee }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"dept_nm\":\n {\n var args = { type: \"PAGE\", page: \"DLG_TEAM\", title: \"부서 선택\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_TEAM\",\n param: { ID: gw_com_api.v_Stream.msg_selectTeam }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"supp_nm\":\n {\n var args = { type: \"PAGE\", page: \"w_find_supplier\", title: \"협력사 선택\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"w_find_supplier\",\n param: { ID: gw_com_api.v_Stream.msg_selectedSupplier }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n default: return;\n }\n}",
"function popupPVAsWindow_bodyKeyDown(e)\n{\n}",
"function dynPopup(title,message,cbObject,cbAfterOpen,cbAfterClose)\n{\n//Display dynamically a popup dialogbox without having to insert template in all pages\n//Content of the dynamic popup can be text only or Full html - we reuse here the markup from current appibuddy Dialog (see dialogContent class in htmls)\n// with a new css class dynpopupContent derived from dialogContent see custom.css\n// main difference is that dynpopupContent is visible by default and display absolute instead of fixed\n\n\nvar content=[\n '<div class=\"dynpopupContent\">',\n ' <div class=\"dialogHeader\" >',\n ' <div>',\n ' <div class=\"dhLeft\" onclick= \"$(\\'#DynPopupPushNotif\\').popup(\\'close\\')\"><img src=\"' + app.rootFullPath + 'img/gr_close.png\" style=\"width:20px; height:20px\" /></div>',\n ' <div class=\"dhRight\"><img src=\"' + app.rootFullPath + 'img/gr_greenbuddy.png\" style=\"width:30px; height:40px\" /></div>',\n ' <div class=\"dhMid\"><span id =\"lblAlertTitle\">' + title + '</span></div>',\n ' </div>',\n ' </div>',\n ' <div class=\"dialogBody\" >',\n ' <div class=\"dbContent\">',\n ' <span id =\"lblAlertMsg\">' + message,\n ' </span>',\n ' </div>',\n ' <div class=\"dbButton center-wrapper\">',\n ' <div >',\n ' <div>',\n ' <a class=\"ui-btn\" style=\"background-color: #f2f2f2\" href=\"#\" data-role=\"button\" data-rel=\"back\"> OK</a>',\n ' </div>',\n ' </div>',\n ' </div>',\n ' </div>',\n '</div>'].join('\\n');\n\n if (!cbObject) //null cbObject passed then we could use directly the callback function \n cbObject = {\n popupafteropen: cbAfterOpen,\n popupafterclose: cbAfterClose\n };\n if ( ! (\"beforeposition\" in cbObject)) //providing default beforeposition callback\n {\n cbObject.beforeposition = function(event, ui)\n {\n var w = $(event.target).attr(\"width\");\n var h = $(event.target).attr(\"height\");\n debuglog('beforeposition w:' + w + ' h:' + h);\n $(event.target).attr(\"width\", \"280px\");\n };\n }\n $.dynamic_popup({\n content: content,\n popupId: \"DynPopupPushNotif\",\n 'data-transition': 'none', //was 'flow'\n 'data-position-to': 'window', //Centered on window can also be any other selector suche #divid\n 'dismissible' : false //modal dialog no click outside see http://api.jquerymobile.com/popup/#option-dismissible\n }).bind(cbObject);\n//Default dynamic+popup parameter\n// $.dynamic_popup({\n// content: '',\n// popupId: 'popup' + $activePage.attr('id'),\n// 'data-theme': 'a',\n// 'data-overlay-theme': 'none',\n// 'data-position-to': 'window',\n// 'data-rel': 'back',\n// 'data-dismissible': true,\n// 'data-transition': 'none',\n// 'data-arrow': false\n//});\n}",
"function showTransciption() {\n cuesList();\n for (i=0; i<cues.length; i++) {\n cues[i].addEventListener(\"click\", jumpToDataTime , false);\n cues[i].addEventListener(\"keydown\", keyFunktion, false);\n\n }\n}",
"function fPopCalendar(popCtrl, dateCtrl){\n event.cancelBubble=true;\n gdCtrl = dateCtrl;\n fSetYearMon(giYear, giMonth);\n var point = fGetXY(popCtrl);\n with (VicPopCal.style) {\n left = point.x+10;\n top = point.y+popCtrl.offsetHeight+15;\n width = VicPopCal.offsetWidth;\n height = VicPopCal.offsetHeight;\n fToggleTags(point);\n visibility = 'visible';\n }\n VicPopCal.focus();\n}",
"function CtrlStatisticPopup() {\n clickedElement = event.target;\n clickedElementId = clickedElement.id;\n\n //if one of the statistic paragraphs are clicked ,inside of the StatistikPopup, is clicked then we open the FillRandomlyPopup\n if(clickedElement.classList.contains(DOMStrings.statisticButton)) {\n UICtrl.closePopup();\n setTimeout(function(){ UICtrl.openFillRandomlyPopup();}, 200); //you need to wait till the previous popup is closed.\n }\n }",
"function toggleHelpAbsoluteFrench(obj, a_id) {\n\tvar content = document.getElementById(obj);\n\tvar opener = document.getElementById(a_id);\t\n\t\n\ticonState = opener.lastChild.alt;\n\ticonState = iconState.replace(\"R\\u00E9duire\",\"\");\n\ticonState = iconState.replace(\"D\\u00E9velopper\",\"\");\n\n\t\n\t\tif (content.style.display != \"none\" ) {\n\t\t\tcontent.style.display = 'none';\n\t\t\topener.lastChild.alt = 'D\\u00E9velopper' + iconState;\n\t\t\topener.focus();\n\t\t} else {\n\t\tcontent.style.display = '';\n\t\t\topener.lastChild.alt = 'R\\u00E9duire' + iconState;\n\t\t}\n\t\n\t\n\tif ((content.style.top == '' || content.style.top == 0) \n\t\t&& (content.style.left == '' || content.style.left == 0))\n\t{\n\t\t// need to fixate default size (MSIE problem)\n\t\tcontent.style.width = content.offsetWidth + 'px';\n\t\tcontent.style.height = content.offsetHeight + 'px';\t\t\n\t\n\t\t// if tooltip is too wide, shift left to be within parent \n\t\tposX = 0;\n\t\tposY = 17;\n\t\tif (posX + content.offsetWidth > opener.offsetWidth) posX = opener.offsetWidth - content.offsetWidth;\n\t\tif (posX < 0 ) posX = 0; \n\t\t\n\t\tx = xstooltip_findPosX(opener.lastChild) + posX;\n\t\ty = xstooltip_findPosY(opener.lastChild) + posY;\n\t\t\n\t\tcontent.style.top = y + 'px';\n\t\tcontent.style.left = x + 'px';\n\t\t\n\t\tcontent.style.position = 'absolute';\n\t\tcontent.style.zIndex = 2;\n\t\n\t}\n\t\n\n}",
"function popupScribd(url) { window.open(url,\"reader\",\"width=\"+900+\",height=\"+700+\",scrollbars=yes,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,left=100,top=100\");\n return false;\n}",
"function initialiseDatePopup(element){\n\tvar output_date = getOutputFormat(element.parentNode.querySelector('.date'));\n\tvar date = moment(output_date, format.date.display);\n\tvar j = 0;\n\tvar order = [];\n\n\tvar split_format = format.date.edit.split('');\n\tfor(var i = 0; i < split_format.length; i++){\n\t\tif(split_format[i] === 'M' && !contains(order, 'M')){\n\t\t\torder[j] = 'M';\n\t\t\tj++;\n\t\t}\n\t\telse if(split_format[i] === 'D' && !contains(order, 'D')){\n\t\t\torder[j] = 'D';\n\t\t\tj++;\n\t\t}\n\t\telse if(split_format[i] === 'Y' && !contains(order, 'Y')){\n\t\t\torder[j] = 'Y';\n\t\t\tj++;\n\t\t}\n\t}\n\n\n\tvar day_number = date.format('D');\n\tvar day_name = date.format('dddd');\n\tvar month_number = date.format('M');\n\tvar month_name = date.format('MMMM');\n\tvar year = date.format('Y');\n\n\telement.innerHTML += '<div class=\"date-in-popup\"></div>';\n\tvar div_date = element.querySelector('.date-in-popup');\n\n\tvar to_add_html = '<table style=\"width:100%;\"><tr>'\n\tfor(i = 0; i < order.length; i++){\n\t\tif(order[i] === 'Y'){\n\t\t\tto_add_html += '<td class=\"year-popup\" onclick=\"clickOnLabel(this)\"> '+year+'</td>';\n\t\t}\n\t\tif(order[i] === 'M'){\n\t\t\tto_add_html += '<td class=\"month-popup\" onclick=\"clickOnLabel(this)\"> '+month_name+'</td>';\n\t\t}\n\t\tif(order[i] === 'D'){\n\t\t\tto_add_html += '<td class=\"day-popup\" onclick=\"clickOnLabel(this)\"> '+day_name+' '+day_number+'</td>';\n\t\t}\n\t}\n\tto_add_html += '</tr></table>';\n\n\tdiv_date.innerHTML += to_add_html;\n\n\telement.innerHTML += '<div class=\"selector\"></div>';\n\tvar div_selector = element.querySelector('.selector');\n\n\tif(contains(order, 'D')){\n\t\tvar date_selector_html = getHtmlForDateSelector(date);\n\t\tdiv_selector.innerHTML += date_selector_html;\n\t\tif(contains(order, 'M') || contains(order, 'Y')){\n\t\t\tvar date_selector = div_selector.querySelector('.day-selector');\n\t\t\tdate_selector.style.display=\"none\";\n\t\t}\n\t}\n\tif(contains(order, 'M')){\n\t\tvar month_selector_html = getHtmlForMonthSelector(date);\n\t\tdiv_selector.innerHTML += month_selector_html;\n\t\t// TODO month selector\n\t\tif(contains(order, 'Y')){\n\t\t\tvar month_selector = div_selector.querySelector('.month-selector');\n\t\t\tmonth_selector.style.display=\"none\";\n\t\t}\n\t}\n\tif(contains(order, 'Y')){\n\t\tdiv_selector.innerHTML += '<table class=\"year-selector\"><tr><th>year</th></tr><tr><td>Year</td></tr></table>';\n\t\t// TODO year selector\n\t}\n}",
"function openMediaPopUp(sUnid, sType, iAnchorIndex) {\n\tvar sPageName = \"MediaPopUp\";\n\n\tvar url = \"http://\" + location.host + dbPath + \"/id/\" + sPageName + \"?open&unid=\" + sUnid + \"&type=\" + sType + (( typeof iAnchorIndex !== \"undefined\") ? \"#anchor\" + iAnchorIndex : \"\");\n\tvar width = \"504\";\n\tvar height = \"570\";\n\tvar Userparam = \"scrollbars=yes,resizable=yes,statusbar=no\";\n\tvar iPosLeft;\n\tvar iPosTop;\n\tif (screen.width) {\n\t\tiPosLeft = (screen.width / 2) - width / 2;\n\t\tiPosTop = (screen.height / 2) - height / 2;\n\t} else {\n\t\tiPosLeft = 0;\n\t\tiPosTop = 0;\n\t}\n\tvar param = Userparam + \",top=\" + String(iPosTop) + \",left=\" + String(iPosLeft) + \",\" + \"width=\" + width + \",height=\" + height;\n\t// dcsMultiTrack('DCS.dcsuri', url, 'WT.ti', 'Media PopUp Aufruf fr Typ: ' + sType + \", UNID: \" + sUnid);\n\tvar MediaPopUp = window.open(url, \"MediaPopUp\", param);\n\tMediaPopUp.focus();\n\n}",
"function popupText(data) {\n\t\tvar text = '<p class=\"alertHeader\">'+data.header+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody1\">'+data.body1+'</p>' +\n\t\t\t\t\t'<p class=\"alertBody2\">'+data.body2+'</p>';\n\t\treturn text;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decycles objects with circular references. This is used to print cyclic structures in development environment only. | function decycle(obj) {
var seen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();
if ( !obj || _typeof$1(obj) !== 'object') {
return obj;
}
if (seen.has(obj)) {
return '[Circular]';
}
var newSeen = seen.add(obj);
if (Array.isArray(obj)) {
return obj.map(function (x) {
return decycle(x, newSeen);
});
}
return Object.fromEntries(Object.entries(obj).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
return [key, decycle(value, newSeen)];
}));
} | [
"function recursiveDispose ( object ) {\n\n\t\t\tfor ( var i = object.children.length - 1; i >= 0; i-- ) {\n\n\t\t\t\trecursiveDispose( object.children[i] );\n\t\t\t\tobject.remove( object.children[i] );\n\n\t\t\t}\n\n\t\t\tif ( object instanceof PANOLENS.Infospot ) {\n\n\t\t\t\tobject.dispose();\n\n\t\t\t}\n\t\t\t\n\t\t\tobject.geometry && object.geometry.dispose();\n\t\t\tobject.material && object.material.dispose();\n\t\t\tobject.texture && object.texture.dispose();\n\t\t\t\n\t\t}",
"function deepClear(obj, up, level) { //** Change so to this uses prototypes of objects instead of trying to copy their members... **** Done, but need to test...\r\n\t\tshallowClear(obj);\r\n\t\treturn deepProto(obj, up, level);\t\t\r\n\t}",
"disconnect() {\n var parents = this.parents();\n for (var object of parents.keys()) {\n var path = parents.get(object);\n object.unset(path);\n }\n return this;\n }",
"detach() {\n this.surface = null;\n this.dom = null;\n }",
"UnloadAndClear()\n {\n for (const path in this._loadedObjects)\n {\n if (this._loadedObjects.hasOwnProperty(path))\n {\n this._loadedObjects[path].Unload();\n }\n }\n this._loadedObjects = {};\n }",
"function resetChain() {\n\t\t\tchain = {};\n\t\t}",
"resetTargetObject () {\r\n this._targetObject = null;\r\n }",
"unmerge (dereferenced){\n const refMatchingFunction = (obj) => {\n if (obj.hasOwnProperty('$ref')){\n return true;\n }\n return false;\n };\n\n this.swaggerObject = this._traverseToUnmerge(this.swaggerObject, refMatchingFunction, dereferenced);\n\n const that = this;\n\n return this\n ._validate(this.swaggerObject)\n .then(() => {\n return that;\n })\n .catch((e) => {\n throw new SyntaxError(`Swagger Schema validation failed after un-merging swagger object.\\n\\nORIGINAL MESSAGE: \\n${e.message}`);\n });\n }",
"constructor(ref){\n this.ref = ref;\n this.next = null;\n }",
"outChildComponents() {\n if(Array.isArray(this.props.loopedComponents)) {\n this.props.loopedComponents.forEach((component) => {\n if(Array.isArray(component.renderedComponents)) {\n Array.from(component.renderedComponents).forEach(comp => {\n comp.out();\n })\n component.renderedComponents = [];\n }\n })\n }\n if(typeof this.childsObj == \"object\") {\n Object.values(this.childsObj).map((component) => {\n component.out();\n })\n }\n }",
"clear() {\n this.name = '';\n this.adj.clear();\n this.node.clear();\n clear(this.graph);\n }",
"unrefUnusedSubchannels() {\n let allSubchannelsUnrefed = true;\n /* These objects are created with Object.create(null), so they do not\n * have a prototype, which means that for (... in ...) loops over them\n * do not need to be filtered */\n // eslint-disable-disable-next-line:forin\n for (const channelTarget in this.pool) {\n const subchannelObjArray = this.pool[channelTarget];\n const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef());\n if (refedSubchannels.length > 0) {\n allSubchannelsUnrefed = false;\n }\n /* For each subchannel in the pool, try to unref it if it has\n * exactly one ref (which is the ref from the pool itself). If that\n * does happen, remove the subchannel from the pool */\n this.pool[channelTarget] = refedSubchannels;\n }\n /* Currently we do not delete keys with empty values. If that results\n * in significant memory usage we should change it. */\n // Cancel the cleanup task if all subchannels have been unrefed.\n if (allSubchannelsUnrefed && this.cleanupTimer !== null) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }",
"delete () {\n\t\t// This is to call the parent class's delete method\n\t\tsuper.delete();\n\n\t\t// Remove all remaining chain links\n\t\twhile (this.chains.length > 0) this.removeLastChain();\n\n\t\t// Clear the class's hook instance.\n\t\tHook.hookElement = null;\n\t}",
"function pruneBackToLevel1OutboundOnly() {\n// currentTopLevel = 1;\n var rootObjectId = objectId;\n var rootNode = nodes.get(rootObjectId);\n var nodesToKeep = [];\n var linksToDelete = [];\n \n nodesToKeep.push(rootNode);\n \n var linkIds = edges.getIds();\n \n for (var i = 0; i < linkIds.length; i++) {\n var linkId = linkIds[i];\n var link = edges.get(linkId);\n if (link.from === rootObjectId) {\n var nodeToKeep = nodes.get(link.to);\n nodesToKeep.push(nodeToKeep);\n } else {\n linksToDelete.push(link);\n }\n }\n \n var nodesToDelete = [];\n \n var nodeIds = nodes.getIds();\n for (var n = 0; n < nodeIds.length; n++) {\n var nodeId = nodeIds[n];\n var node = nodes.get(nodeId);\n if (!isKeepNode(node, nodesToKeep)) {\n nodesToDelete.push(node);\n }\n }\n \n removeNodes(nodesToDelete);\n removeLinks(linksToDelete); \n }",
"function printMemberChain(path,options,print){// The first phase is to linearize the AST by traversing it down.\n//\n// a().b()\n// has the following AST structure:\n// CallExpression(MemberExpression(CallExpression(Identifier)))\n// and we transform it into\n// [Identifier, CallExpression, MemberExpression, CallExpression]\nvar printedNodes=[];function rec(path){var node=path.getValue();if(node.type===\"CallExpression\"&&isMemberish(node.callee)){printedNodes.unshift({node:node,printed:comments$3.printComments(path,function(){return concat$2([printOptionalToken(path),printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)]);},options)});path.call(function(callee){return rec(callee);},\"callee\");}else if(isMemberish(node)){printedNodes.unshift({node:node,printed:comments$3.printComments(path,function(){return node.type===\"MemberExpression\"?printMemberLookup(path,options,print):printBindExpressionCallee(path,options,print);},options)});path.call(function(object){return rec(object);},\"object\");}else{printedNodes.unshift({node:node,printed:path.call(print)});}}// Note: the comments of the root node have already been printed, so we\n// need to extract this first call without printing them as they would\n// if handled inside of the recursive call.\nvar node=path.getValue();printedNodes.unshift({node:node,printed:concat$2([printOptionalToken(path),printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)])});path.call(function(callee){return rec(callee);},\"callee\");// Once we have a linear list of printed nodes, we want to create groups out\n// of it.\n//\n// a().b.c().d().e\n// will be grouped as\n// [\n// [Identifier, CallExpression],\n// [MemberExpression, MemberExpression, CallExpression],\n// [MemberExpression, CallExpression],\n// [MemberExpression],\n// ]\n// so that we can print it as\n// a()\n// .b.c()\n// .d()\n// .e\n// The first group is the first node followed by\n// - as many CallExpression as possible\n// < fn()()() >.something()\n// - then, as many MemberExpression as possible but the last one\n// < this.items >.something()\nvar groups=[];var currentGroup=[printedNodes[0]];var i=1;for(;i<printedNodes.length;++i){if(printedNodes[i].node.type===\"CallExpression\"){currentGroup.push(printedNodes[i]);}else{break;}}if(printedNodes[0].node.type!==\"CallExpression\"){for(;i+1<printedNodes.length;++i){if(isMemberish(printedNodes[i].node)&&isMemberish(printedNodes[i+1].node)){currentGroup.push(printedNodes[i]);}else{break;}}}groups.push(currentGroup);currentGroup=[];// Then, each following group is a sequence of MemberExpression followed by\n// a sequence of CallExpression. To compute it, we keep adding things to the\n// group until we has seen a CallExpression in the past and reach a\n// MemberExpression\nvar hasSeenCallExpression=false;for(;i<printedNodes.length;++i){if(hasSeenCallExpression&&isMemberish(printedNodes[i].node)){// [0] should be appended at the end of the group instead of the\n// beginning of the next one\nif(printedNodes[i].node.computed&&isNumericLiteral(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);continue;}groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}if(printedNodes[i].node.type===\"CallExpression\"){hasSeenCallExpression=true;}currentGroup.push(printedNodes[i]);if(printedNodes[i].node.comments&&printedNodes[i].node.comments.some(function(comment){return comment.trailing;})){groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}}if(currentGroup.length>0){groups.push(currentGroup);}// There are cases like Object.keys(), Observable.of(), _.values() where\n// they are the subject of all the chained calls and therefore should\n// be kept on the same line:\n//\n// Object.keys(items)\n// .filter(x => x)\n// .map(x => x)\n//\n// In order to detect those cases, we use an heuristic: if the first\n// node is just an identifier with the name starting with a capital\n// letter, just a sequence of _$ or this. The rationale is that they are\n// likely to be factories.\nvar shouldMerge=groups.length>=2&&!groups[1][0].node.comments&&groups[0].length===1&&(groups[0][0].node.type===\"ThisExpression\"||groups[0][0].node.type===\"Identifier\"&&(groups[0][0].node.name.match(/(^[A-Z])|^[_$]+$/)||groups[1].length&&groups[1][0].node.computed));function printGroup(printedGroup){return concat$2(printedGroup.map(function(tuple){return tuple.printed;}));}function printIndentedGroup(groups){if(groups.length===0){return\"\";}return indent$2(group$1(concat$2([hardline$2,join$2(hardline$2,groups.map(printGroup))])));}var printedGroups=groups.map(printGroup);var oneLine=concat$2(printedGroups);var cutoff=shouldMerge?3:2;var flatGroups=groups.slice(0,cutoff).reduce(function(res,group){return res.concat(group);},[]);var hasComment=flatGroups.slice(1,-1).some(function(node){return hasLeadingComment(node.node);})||flatGroups.slice(0,-1).some(function(node){return hasTrailingComment(node.node);})||groups[cutoff]&&hasLeadingComment(groups[cutoff][0].node);// If we only have a single `.`, we shouldn't do anything fancy and just\n// render everything concatenated together.\nif(groups.length<=cutoff&&!hasComment&&// (a || b).map() should be break before .map() instead of ||\ngroups[0][0].node.type!==\"LogicalExpression\"){return group$1(oneLine);}var expanded=concat$2([printGroup(groups[0]),shouldMerge?concat$2(groups.slice(1,2).map(printGroup)):\"\",printIndentedGroup(groups.slice(shouldMerge?2:1))]);var callExpressionCount=printedNodes.filter(function(tuple){return tuple.node.type===\"CallExpression\";}).length;// We don't want to print in one line if there's:\n// * A comment.\n// * 3 or more chained calls.\n// * Any group but the last one has a hard line.\n// If the last group is a function it's okay to inline if it fits.\nif(hasComment||callExpressionCount>=3||printedGroups.slice(0,-1).some(willBreak)){return group$1(expanded);}return concat$2([// We only need to check `oneLine` because if `expanded` is chosen\n// that means that the parent group has already been broken\n// naturally\nwillBreak(oneLine)?breakParent$2:\"\",conditionalGroup$1([oneLine,expanded])]);}",
"function collapseAll(){\n function recurse(node){\n if (node.children) node.children.forEach(recurse); // recurse to bottom of tree\n if (node.children){ // hide children in _children then remove\n node._children = node.children;\n node.children = null;\n } \n }\n\n recurse(root);\n update();\n}",
"function disposeBranch(root) {\n if (root.nodeType === 1) {\n var component = componentMap.get(root);\n if (component)\n component.dispose();\n }\n for (var node = root.firstChild; node; node = node.nextSibling) {\n disposeBranch(node);\n }\n }",
"function knockOffSym(aObj){\r\n\taObj.pop();\r\n}",
"removeAllChildren() {\n this.__childNodes = [];\n this.repeats = [];\n this.dispatchNodeEvent(new NodeEvent('repeated-fields-all-removed', this.repeats, false));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns whether the phase is PHASE_DONE | get done() {
return this.phase === PHASE_DONE;
} | [
"isFinished() {\n\t\treturn this.staircases.every(function(s) {return s.staircase.isComplete();});\n\t}",
"function completed () {\n return this.resolved.length === this.chain.__expectations__.length;\n}",
"function isTodoCompleted(todo) {\n return todo.isDone;\n }",
"end() {\n\t\treturn this.prog.length === 0;\n\t}",
"isCompletedRunCurrent () {\n return this.runCurrent?.RunDigest && Mdf.isRunCompleted(this.runCurrent)\n }",
"isFinished() {\n if (this.audio !== null && (typeof (this.audio) !== null) && this.audio !== undefined) { return this.audio.ended; }\n return null;\n }",
"function isTournamentCompleted(tournament){\n console.log(tournament.tournament.progressMeter);\n return tournament.tournament.progressMeter == 100\n}",
"function completed_word()\n{\n if (_line_idx == 0) {\n return (false);\n }\n \n if (_line[_line_idx-1] == 0x20) {\n return (true);\n }\n \n return (false);\n}",
"function endPhaseConditions(){\r\n\r\n if (killerCountSetup == 0 || userKilled || totalFuel == userScore + computerScore || fuel == 0){\r\n return false;\r\n }\r\n else{\r\n return true;\r\n }\r\n}",
"isTakeoff() {\n return this.flightPhase === FLIGHT_PHASE.TAKEOFF;\n }",
"function checkPageDone(page) {\n var isDone = _.every(page.differences, function(d) { return d.state != \"in_use\"; });\n if (isDone) {\n console.log(\"Marking page as done:\", page._id);\n page.state = \"done\";\n page.saveAsync();\n }\n return isDone;\n}",
"isLoadingFinished() {\n return this.isLoadingCompleted() || this.isLoadingError();\n }",
"function animationRunning(){\r\n\treturn animations.length > 0;\r\n}",
"handleDone () {\n const priv = privs.get(this)\n switch (priv.state) {\n case State.Done:\n case State.Errored:\n return\n\n case State.Running:\n case State.Stopped:\n case State.Stopping:\n priv.state = State.Done\n }\n }",
"function checkTaskCompleted(item) {\n if(item == 'apple') {\n appleCompleted = 'completed'\n } else if (item === 'match') {\n matchCompleted = 'completed'\n }\n // activate tunnel if both tasks completed\n if (matchCompleted === 'completed' && appleCompleted === 'completed') {\n let tunnel = document.querySelector('#Tunnel')\n tunnel.style.pointerEvents = 'visible'\n tunnel.style.animation = 'keyStepGlow 2s infinite'\n }\n}",
"_succeed () {\n const message = domain.chains.isMockChain(this.chain)\n ? domain.i18n.getText('success', 'mocknet')\n : domain.i18n.getText('success', 'blockchain');\n log(message);\n return this._setFinalStep({ status: VERIFICATION_STATUSES.SUCCESS, message });\n }",
"function isFinalState(currentState){\n let finalStates = [state27, state25, state19, state15, state11, state10, state8, state5];\n let finalStateFlag = 0;\n for(let s = 0; s < finalStates.length; s++){\n if(currentState == finalStates[s]){\n finalStateFlag++;\n }\n }\n if(finalStateFlag > 0){\n return true;\n }else{\n return false;\n }\n}",
"done() {\n // Let's find the screen position of the particle\n let pos = scaleToPixels(this.body.GetPosition());\n // Is it off the bottom of the screen?\n if (pos.y > .69*height + this.r * 2) {\n this.killBody();\n return true;\n }\n return false;\n }",
"isActionAborted() {}",
"function completeCycleIfNecessary() {\n if (stateManager.getAccountsWithStatus(Statuses.NOT_STARTED).length == 0 &&\n stateManager.getStatus() != Statuses.COMPLETE) {\n stateManager.setStatus(Statuses.COMPLETE);\n stateManager.saveState();\n processFinalResults(stateManager.getResults());\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validating /////////////////////////////////////////////////////////////////// validate probe clone | function validateProbeClone() {
console.log("validateProbeClone()");
if (vm.apiDomain.derivedFromAccID == undefined || vm.apiDomain.derivedFromAccID == "") {
return;
}
if (vm.apiDomain.derivedFromAccID.includes("%")) {
return;
}
pageScope.loadingStart();
var params = {};
params.accID = vm.apiDomain.derivedFromAccID;
ProbeSearchAPI.search(params, function(data) {
if (data.length == 0) {
alert("Invalid Probe Clone: " + vm.apiDomain.derivedFromAccID);
document.getElementById("derivedFromAccID").focus();
vm.apiDomain.derivedFromAccID = "";
vm.apiDomain.derivedFromName = "";
vm.apiDomain.derivedFromKey = "";
pageScope.loadingEnd();
}
else {
vm.apiDomain.derivedFromAccID = data[0].accID;
vm.apiDomain.derivedFromName = data[0].name;
vm.apiDomain.derivedFromKey = data[0].probeKey;
vm.apiDomain.probeSource = data[0].probeSource;
if (vm.apiDomain.probeSource.processStatus == "x") {
vm.apiDomain.probeSource.processStatus = "u";
}
pageScope.loadingEnd();
}
}, function(err) {
pageScope.handleError(vm, "API ERROR: ProbeSearchAPI.search");
document.getElementById("derivedFromAccID").focus();
vm.apiDomain.derivedFromAccID = "";
vm.apiDomain.derivedFromName = "";
vm.apiDomain.derivedFromKey = "";
pageScope.loadingEnd();
});
} | [
"validate() {\n this.verifTitle();\n this.verifDescription();\n this.verifNote();\n this.verifImg();\n console.log(this.errors);\n console.log(this.test);\n if (this.test !== 0) {\n return false;\n }\n return true;\n }",
"function PlateValidation() {\n\n /* Flags for standard plate types */\n\n this.PLATE_6WELL = 0;\n this.PLATE_12WELL = 1;\n this.PLATE_24WELL = 2;\n this.PLATE_48WELL = 3;\n this.PLATE_96WELL = 4;\n this.PLATE_384WELL = 5;\n this.PLATE_1536WELL = 6;\n this.PLATE_CUSTOM = -1;\n\n /* Flags for standard row numbers */\n\n this.ROWS_6WELL = 2;\n this.ROWS_12WELL = 3;\n this.ROWS_24WELL = 4;\n this.ROWS_48WELL = 6;\n this.ROWS_96WELL = 8;\n this.ROWS_384WELL = 16;\n this.ROWS_1536WELL = 32;\n\n /* Flags for standard column numbers */\n\n this.COLUMNS_6WELL = 3;\n this.COLUMNS_12WELL = 4;\n this.COLUMNS_24WELL = 6;\n this.COLUMNS_48WELL = 8;\n this.COLUMNS_96WELL = 12;\n this.COLUMNS_384WELL = 24;\n this.COLUMNS_1536WELL = 48;\n}",
"function MarketValidator(filePath) {\n\n this.filePath = filePath;\n this.errorsCount = 0;\n this.warningsCount = 0;\n\n this.validate = function() {\n var data = fs.readFileSync(this.filePath, 'utf8');\n var json = JSON.parse(data);\n var features = json.features;\n var cityName = this.getCityName();\n\n var featuresValidator = new FeaturesValidator(features, cityName);\n featuresValidator.validate();\n featuresValidator.printIssues();\n this.errorsCount += featuresValidator.getErrorsCount();\n this.warningsCount += featuresValidator.getWarningsCount();\n\n var metadataValidator = new MetadataValidator(json.metadata, cityName);\n metadataValidator.validate();\n metadataValidator.printWarnings();\n metadataValidator.printErrors();\n this.errorsCount += metadataValidator.getErrorsCount();\n this.warningsCount += metadataValidator.getWarningsCount();\n\n this.printSummary();\n\n if (this.errorsCount !== 0) {\n exitCode = 1;\n }\n };\n\n this.getCityName = function() {\n return path.basename(this.filePath, path.extname(this.filePath));\n };\n\n\n this.printSummary = function() {\n if (this.errorsCount === 0) {\n this.printSuccess();\n\n } else {\n this.printFailure();\n }\n };\n\n this.printSuccess = function() {\n if (this.warningsCount === 0) {\n console.log(\"\\nValidation PASSED without warnings or errors.\".passed);\n } else {\n console.log(\"\\nValidation PASSED with %d warning(s) and no errors.\".passed, this.warningsCount);\n }\n };\n\n this.printFailure = function() {\n console.log(\"\\nValidation done. %d warning(s), %d error(s) detected.\".error, this.warningsCount, this.errorsCount);\n };\n\n}",
"function validate(inst, vo)\n{\n if (inst.enablePolicy) {\n if (inst.policyInitFunction === 'Custom') {\n if (!isCName(inst.policyInitCustomFunction)) {\n logError(vo, inst, \"policyInitCustomFunction\",\n \"Not a valid C identifier\");\n }\n if (inst.policyInitCustomFunction === '') {\n logError(vo, inst, \"policyInitCustomFunction\",\n \"Must contain a valid function name if the \" +\n \"Policy Init Function field == 'Custom'\");\n }\n }\n if (inst.policyFunction === 'Custom') {\n if (!isCName(inst.policyCustomFunction)) {\n logError(vo, inst, \"policyCustomFunction\",\n \"is not a valid C identifier\");\n }\n if (inst.policyCustomFunction === '') {\n logError(vo, inst, \"policyCustomFunction\",\n \"Must contain a valid function name if the \" +\n \"Policy Function field == 'Custom'\");\n }\n }\n }\n\n if ((inst.enableHFXTClock)) {\n if ((inst.hfxtFrequency == '0')) {\n if (inst.bypassHFXT) {\n logError(vo, inst, 'hfxtFrequency',\n 'If HFXT is enabled in bypass mode, please specify ' +\n 'the external crystal square wave frequency.');\n } else {\n logError(vo, inst, 'hfxtFrequency',\n 'Specify the desired HFXT oscillator frequency.');\n }\n }\n }\n\n if ((inst.initialPerfLevel - inst.customPerfLevels) > 3) {\n logError(vo, inst, ['initialPerfLevel', 'customPerfLevels'],\n 'The initial performance level refers to an undefined custom ' +\n 'performace level.');\n }\n\n if (!isCName(inst.resumeShutdownHookFunction)) {\n logError(vo, inst, \"resumeShutdownHookFunction\", 'Not a valid C identifier');\n }\n\n if (inst.advancedConfiguration) {\n if (!isCName(inst.isrClockSystem)) {\n logError(vo, inst, \"isrClockSystem\", 'Not a valid C identifier');\n }\n }\n}",
"validateData(){\n\t//todo\n\tvar invalideMessages = [];\n\tvar oPapers = StoreHelper.getPapers();\n\tvar subPages = Object.keys(oPapers)\n\t .reduce((pre,curPaperKey) => {\n\t\tvar curPaper = oPapers[curPaperKey];\n\t\tif(paper.isSubPage(curPaper.paperType)){\n\t\t pre[curPaperKey] = curPaper.key;\n\t\t}\n\t\treturn pre;\n\t },{});\n\n\tvar isValide = !subPages || Object.keys(subPages)\n\t\t.every((subPaperUUID)=>{\n\t\t var hasPaper = Object.keys(oPapers).find((paperKey)=>{\n\t\t\tvar curPaper = oPapers[paperKey];\n\t\t\tif(paper.isSubPage(curPaper)){\n\t\t\t return false;\n\t\t\t}\n\t\t\tif(paper.hasDeviceNumber(curPaper, subPages[subPaperUUID])){\n\t\t\t return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t });\n\t\t if(hasPaper){\n\t\t\treturn true;\n\t\t } else {\n\t\t\tinvalideMessages.push(`子页面${oPapers[subPaperUUID].paperName}绑定设备:${subPages[subPaperUUID]} 不存在`);\n\t\t\treturn false;\n\t\t }\n\t\t});\n\tvar duplicateInfo = this.checkDuplicateInfo(oPapers);\n\tif(duplicateInfo){\n\t isValide = false;\n\t invalideMessages = invalideMessages.concat(duplicateInfo);\n\t}\n\treturn {\n\t isValide: !!isValide,\n\t messages: invalideMessages\n\t};\n }",
"function validateParry (data, command) {\n // no additional validation necessary\n return true;\n }",
"function validateRun (data, command) {\n // no additional validation necessary\n return true;\n }",
"validate(invalidProperties)\n\t{\n\t\tif(typeof this.addressLine1 === \"string\" && this.addressLine1.length > 0 && this.addressLine1.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine1;\n\t\t}\n\t\tif(typeof this.addressLine2 === \"string\" && this.addressLine2.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine2;\n\t\t}\n\t\tif(typeof this.addressLine3 === \"string\" && this.addressLine3.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine3;\n\t\t}\n\t\tif(typeof this.city === \"string\" && this.city.length > 0 && this.city.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.city;\n\t\t}\n\t\t//TODO: Check to see if countryData has a list of provinces or not, if it doesn't, this is theoretically valid\n\t\tif(countryData.data[this.country] && typeof this.stateProvince === \"string\" && this.stateProvince.length < 35)\n\t\t{\n\n\t\t\tif(Object.keys(countryData.data[this.country].subdivisions).length === 0)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.stateProvince;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//TODO: FIX This hack before deploying to production.\n\t\t\t\tvar valid = false;\n\t\t\t\tObject.keys(countryData.data[this.country].subdivisions).forEach(subdiv => {\n\t\t\t\t\tif(this.stateProvince === subdiv || this.stateProvince === subdiv.split('-')[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tvalid = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif(valid === true)\n\t\t\t\t{\n\t\t\t\t\tdelete invalidProperties.stateProvince;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(typeof this.country === \"string\" && this.country.length > 0 && this.country.length <= 3)\n\t\t{\n\t\t\tdelete invalidProperties.country;\n\t\t}\n\t\tif(this.country === \"CAN\" && typeof this.zipPostalCode === \"string\")\n\t\t{\n\t\t\tif(this.zipPostalCode[3] !== \" \")\n\t\t\t{\n\t\t\t\tthis.zipPostalCode = this.zipPostalCode.slice(0,3).toUpperCase()+\" \"+this.zipPostalCode.slice(3,6).toUpperCase();\n\t\t\t}\n\n\t\t\tif(/^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]( )?\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$/i.test(this.zipPostalCode) === true)\n\t\t\t{\n\t\t\t\tthis.zipPostalCode = this.zipPostalCode.toUpperCase();\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t\telse if(this.country === \"USA\" && typeof this.zipPostalCode === \"string\")\n\t\t{\n\t\t\tif(/^[0-9]{5}(?:-[0-9]{4})?$/.test(this.zipPostalCode) === true)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(typeof this.zipPostalCode === \"string\" && this.zipPostalCode.length < 35)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t}",
"function validateParameters(args) {\n\tif (!args.camera) {\n\t\tsumerian.SystemBus.emit(\"sumerian.warning\", { title: \"Please specify the camera entity on Initialization.js\", message: \"Please specify the camera entity on the inspector panel of 'Initialization.js' on the 'Main Script' entity to configure your scene. By default, this entity is called 'Closeup Camera', and you can drag and drop the entity onto the inspector panel of the script file.\"});\n\t}\n\n\tif (!args.host) {\n\t\tsumerian.SystemBus.emit(\"sumerian.warning\", { title: \"Please specify the Host entity on Initialization.js\", message: \"Please specify the Host entity on the inspector panel of 'Initialization.js' on the 'Main Script' entity to configure the scene for your target screen size. By default, this entity is called 'Host', and you can drag and drop the entity onto the inspector panel of the script file.\"});\n\t}\n\n\tif (!args.poiTarget) {\n\t\tsumerian.SystemBus.emit(\"sumerian.warning\", { title: \"Please specify the Host POI entity on Initialization.js\", message: \"Please specify the Host's point of interest (POI) target entity on the inspector panel of 'Initialization.js' on the 'Main Script' entity to configure the scene for your target screen size. By default, this entity is called 'Host POI Target', and you can drag and drop the entity onto the inspector panel of the script file.\"});\n\t}\n}",
"function validate_fasta(fasta) {\n //split fasta data into multiple fasta targets:\n var fasta_targets = fasta.split(\"\\n>\");\n var added_tars = [];\n var errors = [];\n\n angular.forEach(fasta_targets, function(fasta_target, index) {\n\n // prepend \">\" which was trimmed during the split to the fasta target:\n\t if (! fasta_target.trim().match(/^>/)) {\n\t fasta_target = \">\" + fasta_target.trim();\n\t }\n\t var header = fasta_target.split(\"\\n\")[0];\n var seq = fasta_target.split(header)[1];\n\t var regExp = new RegExp(header, \"gi\");\n\t var count = (fasta.match(regExp) || []).length;\n var open_p = \"<p>\";\n var close_p = \"</p>\";\n\n // fasta sequence must be valid:\n var msg = \"FASTA sequence \"+header+\" is not valid.\";\n msg = open_p + msg + close_p;\n\t if ( (! seq.trim().match(/^[a-zA-Z\\n]+$/)) && (errors.indexOf(msg) == -1) ) {\n\t this.push(msg);\n }\n\n // fasta header must be valid:\n\t var msg = \"FASTA header \"+header+\" is not valid.\";\n\t msg = open_p + msg + close_p;\n\t if ( (! header.trim().match(/^>[^<>]+$/)) && (errors.indexOf(msg) == -1) ) {\n this.push(msg);\n }\n \n // header must be unique:\n var msg = \"You have added multiple FASTA targets with a header \"+header+\". A header must be unique.\";\n msg = open_p + msg + close_p;\n\t if ((count > 1) && (errors.indexOf(msg) == -1)) { \n\t this.push(msg);\n }\n\n // fasta length must be < 25K:\n msg = \"The length of your FASTA target \"+header+\" is \"+ (fasta_target.length - header.length - 1)+\". Please make sure the target sequence does not exceed 25K.\";\n msg = open_p + msg + close_p;\n\t if ( ((fasta_target.length - header.length - 1) > 25000) && (errors.indexOf(msg) == -1) ) {\n\t this.push(msg);\n\t } \n added_tars.push(fasta_target);\n }, errors);\n\n if (errors.length) {\n $scope.data.error = errors.join('');\n return false;\n } else {\n return added_tars;\n }\n }",
"static validateTools(_tools) { }",
"function processTracker() {\n\n\tvar success = true;\n\tconsole.log(\"\\n2. Validating exported metadata\");\n\t\n\t//Configure sharing and metadata ownership\n\tconfigureSharing();\n\tconfigureOwnership();\n\n\t//Remove users from user groups\n\tclearUserGroups();\n\t\t\n\t//Make sure the \"default defaults\" are used\n\tsetDefaultUid();\n\t\n\t//Make sure we don't include orgunit assigment in datasets or users\n\tclearOrgunitAssignment();\n\t\n\t//Verify that all data elements referred in indicators, validation rules,\n\t//predictors are included\n\tif (!validateDataElementReference()) success = false;\n\n\t//Verify that all program indicators referred to in indicators and predictors are included\n\tif (!validateProgramIndicatorReference()) success = false;\n\n\t//Remove invalid references to data elements or indicators from groups\n\t//Verify that there are no data elements or indicators without groups\n\tif (!validateGroupReferences()) success = false;\t\n\t\n\t//Verify that favourites only use relative orgunits\n\tif (!validateFavoriteOrgunits()) success = false;\n\t\n\t//Verify that favourites only use indicators\n\tif (!validateFavoriteDataItems()) success = false;\n\t\n\t//Verify that no unsupported data dimensions are used\n\tif (!validateFavoriteDataDimension()) success = false;\n\n\t//Verify that data sets with section include all data elements\n\tif (!validationDataSetSections()) success = false;\n\n\n\t/** CUSTOM MODIFICATIONS */\n\tif (currentExport.hasOwnProperty(\"_customFuncs\")) {\n\t\tfor (var customFunc of currentExport._customFuncs) {\n\t\t\tvar func = new Function(\"metaData\", customFunc);\n\t\t\tfunc(metaData); \n\t\t}\n\t}\n\t\n\tif (success) {\n\t\tconsole.log(\"✔ Validation passed\");\n\t\tsaveTracker();\n\t}\n\telse {\n\t\tconsole.log(\"\");\n\t\tvar schema = {\n\t\t\tproperties: {\n\t\t\t\tcontinue: {\n\t\t\t\t\tdescription: \"Validation failed. Continue anyway? (yes/no)\",\n\t\t\t\t\trequired: true,\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tdefault: \"no\",\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t\tif(args.ignoreerrors)\n\t\t{\n\t\t\tsaveTracker();\n\t\t} else {\n\t\t\tprompt.get(schema, function (err, result) {\t\n\t\t\t\tif (result.continue == \"yes\") saveTracker();\n\t\t\t\telse cancelCurrentExport();\n\t\t\t});\n\t\t}\n\t}\n}",
"function ValidateCoordinatorsAndTrustmeWithoutFork(conn, coordinators, objUnit, objValidationState, callback) {\n\t// console.log(\"validating ValidateCoordinatorsAndTrustmeWithoutFork\");\n\t// console.log(\"validating objUnit: \" + JSON.stringify(objUnit));\n\tif(objUnit.authors.length === 11){ // recover trustme unit\n\t\treturn callback();\n\t}\n\t//check only single main chain without fork ,there is no two trust me units with same mci\n\tstorage.getUnitsInfoWithMci(conn,objUnit.hp, function(units){\n\t\tif(units.length > 0)\n\t\t\treturn callback(\"duplicated trust me units with same MCI !\");\n\t\t\n\t\tif(coordinators.length < ( 2 * constants.TOTAL_BYZANTINE + 1) )\n\t\t\treturn callback(\"not enough coordinators, not reach to 2f + 1 threshold \");\n\t\tif(coordinators.length > constants.TOTAL_COORDINATORS )\n\t\t\treturn callback(\"too many coordinators \");\n\t\t\n\t\t\t// check coordinators are sorted and no duplicated\n\t\tvar prev_address = \"\";\n\t\tfor (var i=0; i<coordinators.length; i++){\n\t\t\tvar objCoodinator = coordinators[i];\n\t\t\tif (objCoodinator.address <= prev_address)\n\t\t\t\treturn callback(\"coordinator addresses not sorted\");\n\t\t\tprev_address = objCoodinator.address;\n\t\t}\n\n\t\t// console.log(\"validating coordinators: \" + JSON.stringify(coordinators));\n\t\tasync.eachSeries(coordinators, function(coordinator, cb){\n\t\t\t// Make sure all coordinators are correct witness of round\n\t\t\tround.getWitnessesByRoundIndex(conn, objUnit.round_index, function(witnesses){\n\t\t\t\tif(witnesses.indexOf(coordinator.address) === -1)\n\t\t\t\t\treturn cb(\"Incorrect coordinator deteced :\" + coordinator.address);\n\t\t\t\t// Validate signature\n\t\t\t\tobjValidationState.unit_hash_to_sign = objectHash.getProposalHashToSign(objUnit);\n\t\t\t\tvalidateAuthor(conn, coordinator, objUnit, objValidationState, cb);\n\t\t\t});\n\t\t}, callback);\n\t});\n}",
"validar() { }",
"function validateAdharcardProof() {\r\n\t\tclearMsg(\"adharcardProofMsg\");\r\n\t\tvar adharcard = document.getElementById(\"adharcard\");\r\n\t\tif (adharcard.files.length == 0) {\r\n\t\t\tdocument.getElementById(\"adharcardProofMsg\").innerHTML = \"Choose Adhar card proof\";\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}",
"function name_check() {\r\n name_warn();\r\n final_validate();\r\n}",
"static verifyClues(oldclues, newclues) {\n\n // make sure that each old clue corresponds to a new clue.\n Object.keys(oldclues).forEach((direction) => {\n if (newclues[direction] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n\n Object.keys(newclues[direction]).forEach((number) => {\n if (newclues[direction][number] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n });\n });\n\n // make sure that each new clue corresponds to an old clue.\n Object.keys(newclues).forEach((direction) => {\n if (oldclues[direction] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n Object.keys(newclues[direction]).forEach((number) => {\n if (oldclues[direction][number] == null) {\n console.error('ERROR!! invalid clue state!');\n console.info(oldclues);\n console.info(newclues);\n throw 'ERROR!! invalid clue state!';\n }\n });\n });\n }",
"static validate(pokemonWannabeeObj) {\n const schema = Joi.object({\n pokPokemonId: Joi.number()\n .integer()\n .min(1),\n pokName: Joi.string()\n .min(1)\n .max(50),\n pokHeight: Joi.string()\n .max(50),\n pokWeight: Joi.string()\n .max(50),\n pokAbilities: Joi.string()\n .max(255),\n pokGender: Joi.string()\n .max(50),\n pokFavorite: Joi.number()\n .integer()\n .min(1)\n .allow(null),\n pokTypes: Joi.array()\n .items(\n Joi.object({\n pokTypeId: Joi.number()\n .integer()\n .min(1)\n .required(),\n pokTypeName: Joi.string()\n .min(1)\n .max(255),\n pokTypeDescription: Joi.string()\n .max(255)\n .allow(null)\n })\n )\n });\n return schema.validate(pokemonWannabeeObj);\n }",
"_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
simple plugin to provide server.app.config in request.app.config | function appConfigPlugin(server) {
server.ext("onRequest", (request, h) => {
request.app.config = server.app.config;
return h.continue;
});
} | [
"configurationRequestHandler (context, request, callback) {\n callback(null);\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"function configApp(appConfig) {\n for (var i in appConfig) {\n if (appConfig.hasOwnProperty(i)) {\n config[i] = appConfig[i];\n }\n }\n}",
"function getConfiguration() {\n var request = new XMLHttpRequest();\n\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n\n /*---------- getting app configuration ----------*/\n var appConfiguration = JSON.parse(request.response);\n /*---------- assigning appname or main module ----------*/\n w.appName = appConfiguration.appName;\n /*---------- main redirect url for ui-router default url link ----------*/\n w.defaultUrl = appConfiguration.defaultUrl;\n /*---------- all the modules to load ----------*/\n var modules = appConfiguration.modules;\n\n for (var i = 0; i < modules.length; i++) {\n loadSingleScript(modules[i].name);\n // ===============================\n // saving modules for using\n // in the bootstrap file\n // as dependency\n // =============================== \n w.modules.push(modules[i].name);\n // =================================\n // if modules main files are loaded\n // this is called to load their\n // dependend files\n // =================================\n if ((i + 1) == modules.length) {\n setTimeout(function() {\n loadDependencyFiles(appConfiguration);\n }, 100);\n }\n }\n }\n }\n\n request.open('Get', 'app.json');\n request.send();\n }",
"$registerHttpServer() {\n this.$container.singleton('Adonis/Core/Server', () => {\n const Logger = this.$container.use('Adonis/Core/Logger');\n const Profiler = this.$container.use('Adonis/Core/Profiler');\n const Config = this.$container.use('Adonis/Core/Config');\n const Encryption = this.$container.use('Adonis/Core/Encryption');\n const config = Object.assign({ secret: Config.get('app.appKey') }, Config.get('app.http', {}));\n return new Server_1.Server(this.$container, Logger, Profiler, Encryption, config);\n });\n }",
"function loadMainConfig() {\n return $http({\n method: 'Get',\n data: {},\n url: 'config.json',\n withCredentials: false\n })\n .then(transformResponse)\n .then(conf => {\n try {\n if (conf && conf.endpoints && conf.endpoints.mdx2json) {\n MDX2JSON = conf.endpoints.mdx2json.replace(/\\//ig, '').replace(/ /g, '');\n NAMESPACE = conf.namespace.replace(/\\//ig, '').replace(/ /g, '');\n }\n } catch (e) {\n console.error('Incorrect config in file \"config.json\"');\n }\n adjustEndpoints();\n })\n }",
"appConfig() {\n /** first middleware for convert json request */\n this.app.use(\n bodyParser.json()\n )\n }",
"cb(config) {\n //you have access to the gulp config here for\n //any extra customization after merging => don't forget to return config\n return merge(config, serverConfig);\n }",
"function routehelperConfig() {\n this.config = {\n // These are the properties we need to set\n $routeProvider: undefined,\n resolveAlways: {},\n };\n\n this.$get = () => ({\n config: this.config,\n });\n }",
"prepareWebpackConfig() {\r\n this.clientConfig = createClientConfig(this.context).toConfig()\r\n this.serverConfig = createServerConfig(this.context).toConfig()\r\n\r\n const userConfig = this.context.siteConfig.configureWebpack\r\n if (userConfig) {\r\n this.clientConfig = applyUserWebpackConfig(\r\n userConfig,\r\n this.clientConfig,\r\n false\r\n )\r\n this.serverConfig = applyUserWebpackConfig(\r\n userConfig,\r\n this.serverConfig,\r\n true\r\n )\r\n }\r\n }",
"DisplayAspNetConfigSettings() {\n\n }",
"function webpackServerConfig() {\n let config = webpackBaseConfig.call(this, 'server');\n\n // env object defined in nuxt.config.js\n let env = {};\n _.each(this.options.env, (value, key) => {\n env['process.env.' + key] = ['boolean', 'number'].indexOf(typeof value) !== -1 ? value : JSON.stringify(value);\n });\n\n config = Object.assign(config, {\n target: 'node',\n node: false,\n devtool: 'source-map',\n entry: path.resolve(this.options.buildDir, 'server.js'),\n output: Object.assign({}, config.output, {\n filename: 'server-bundle.js',\n libraryTarget: 'commonjs2'\n }),\n performance: {\n hints: false,\n maxAssetSize: Infinity\n },\n externals: [],\n plugins: (config.plugins || []).concat([new VueSSRServerPlugin({\n filename: 'server-bundle.json'\n }), new webpack.DefinePlugin(Object.assign(env, {\n 'process.env.NODE_ENV': JSON.stringify(env.NODE_ENV || (this.options.dev ? 'development' : 'production')),\n 'process.env.VUE_ENV': JSON.stringify('server'),\n 'process.mode': JSON.stringify(this.options.mode),\n 'process.browser': false,\n 'process.client': false,\n 'process.server': true,\n 'process.static': this.isStatic\n }))])\n });\n\n // https://webpack.js.org/configuration/externals/#externals\n // https://github.com/liady/webpack-node-externals\n this.options.modulesDir.forEach(dir => {\n if (fs.existsSync(dir)) {\n config.externals.push(nodeExternals({\n // load non-javascript files with extensions, presumably via loaders\n whitelist: [/es6-promise|\\.(?!(?:js|json)$).{1,5}$/i],\n modulesDir: dir\n }));\n }\n });\n\n // --------------------------------------\n // Production specific config\n // --------------------------------------\n if (!this.options.dev) {}\n\n // Extend config\n if (typeof this.options.build.extend === 'function') {\n const isDev = this.options.dev;\n const extendedConfig = this.options.build.extend.call(this, config, {\n get dev() {\n console.warn('dev has been deprecated in build.extend(), please use isDev'); // eslint-disable-line no-console\n return isDev;\n },\n isDev,\n isServer: true\n });\n // Only overwrite config when something is returned for backwards compatibility\n if (extendedConfig !== undefined) {\n config = extendedConfig;\n }\n }\n\n return config;\n}",
"function parseConfig(contents, config) {\n contents.server = contents.server || {};\n contents.proxy = contents.proxy || {};\n\n if (contents.proxy.gateway && typeof(contents.proxy.gateway) === \"string\" && contents.proxy.gateway.length > 0) {\n contents.proxy.gateway = parseGateway(contents.proxy.gateway);\n }\n\n contents.proxy.forward = parseConfigMap(contents.proxy.forward, parseForwardRule);\n contents.proxy.headers = parseConfigMap(contents.proxy.headers, parseHeaderRule);\n\n // override any values in the config object with values specified in the file;\n config.server.port = contents.server.port || config.server.port;\n config.server.webroot = contents.server.webroot || config.server.webroot;\n config.server.html5mode = contents.server.html5mode || config.server.html5mode;\n config.proxy.gateway = contents.proxy.gateway || config.proxy.gateway;\n config.proxy.forward = contents.proxy.forward || config.proxy.forward;\n config.proxy.headers = contents.proxy.headers || config.proxy.headers;\n\n return config;\n}",
"function getGlobalConfiguration(axios$$1, identifier) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/configuration');\n }",
"remoteConfig() {\n const configs = Object.assign({}, Remote_1.RemoteConfig);\n configs.uri = this.apiUrl();\n return configs;\n }",
"function updateGlobalConfiguration(axios$$1, identifier, config) {\n return restAuthPost(axios$$1, 'instance/microservice/' + identifier + '/configuration', config);\n }",
"function getPluginFrontendConfig () {\r\n return {\r\n 'name': 'pattern-lab\\/' + pluginName, \r\n 'templates': [],\r\n 'stylesheets': [],\r\n 'javascripts': ['patternlab-components\\/pattern-lab\\/' + pluginName +\r\n '\\/js\\/' + pluginName + '.js'],\r\n 'onready': '',\r\n 'callback': ''\r\n }\r\n}",
"extend(config) {\n\t\t\t// Add '~/shared' as an alias.\n\t\t\tconfig.resolve.alias.shared = resolve(__dirname, '../shared');\n\t\t\tconfig.resolve.alias['~shared'] = resolve(__dirname, '../shared');\n\t\t}",
"function setupConfig() {\n var origin = 'https://developer.mozilla.org';\n if (window.URL) {\n var url = new URL(window.location.href);\n if (url.searchParams) {\n var param = url.searchParams.get('origin');\n if (param) {\n origin = param;\n }\n }\n }\n window.ieConfig = {\n origin: origin\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve partner object by Id. | static get(id = null){
let kparams = {};
kparams.id = id;
return new kaltura.RequestBuilder('partner', 'get', kparams);
} | [
"static getPublicInfo(id = null){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('partner', 'getPublicInfo', kparams);\n\t}",
"getTrainerById(id) {\n logger.debug(`get trainer by id: ${id}`);\n return this.store.findOneBy(this.collection, {\n id: id\n });\n }",
"async obterPorId(pessoaId) {\n const pessoa = await PessoaRepository.findById(pessoaId).exec();\n return pessoa;\n }",
"getById(id) {\n // verify required parameter 'id' is not null or undefined\n if (id === null || id === undefined) {\n throw new Error('Required parameter id was null or undefined when calling getById.');\n }\n let queryParameters = {};\n if (id !== undefined)\n queryParameters['id'] = id;\n let headerParams = this.defaultHeaders;\n let isFile = false;\n let formParams = {};\n return this.execute('GET', '/api/user/v1/account/get-by-id', queryParameters, headerParams, formParams, isFile, false, undefined);\n }",
"async getPartage(id){\n try{\n const partage = Object.assign(new Partage(), await this.partageApi.get(id));\n return partage;\n }\n catch (e) {\n if (e === 404) return null;\n if (e === 403) return 403;\n return undefined;\n }\n }",
"function getClientByID(id) {\n\tfor (var c in clients) {\n\t\tif (clients[c].player.id === id) {\n\t\t\treturn clients[c];\n\t\t}\n\t}\n\treturn null;\n}",
"findObject(id) {\n\t\tfor (var i in this.gameobjects) {\n\t\t\tif (this.gameobjects[i].id == id) {\n\t\t\t\treturn this.gameobjects[i];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"async getPlayerById(id) {\n let row = await sql.get(`SELECT * FROM Players p WHERE p.ID = $id`, {$id: id});\n\t\tif(row) {\n\t\t\treturn await this.getPlayerInternal(row);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n }",
"getById(id) {\n return HubSite(this, `GetById?hubSiteId='${id}'`);\n }",
"async pegarPorId(id) {\n const encontrado = await ModeloTabelaFornecedor.findOne({\n where : {id},\n raw : true\n });\n if(!encontrado) {\n throw new NaoEncontrado(`Fornecedor de id ${id}`);\n } \n return encontrado;\n }",
"findById(id) {\n return request.get(`/api/flows/${id}`);\n }",
"function getClientById(id){\n var count = users.length;\n var client = null;\n for(var i=0;i<count;i++){\n \n if(users[i].userId==id){\n client = users[i];\n break;\n }\n }\n return client;\n}",
"retrieveCourse (id) {\n return apiClient.retrieveCourse(id)\n }",
"function findById(id) {\n return _.find(fields, { '_id': id });\n }",
"function findPerson(id) {\n var foundPerson = null;\n for (var i = 0; i < persons.length; i++) {\n var person = persons[i];\n if (person.id == id) {\n foundPerson = person;\n break;\n }\n }\n\n return foundPerson;\n }",
"static async fetchProductById(productId) {\n const product = storage\n .get(\"products\")\n .find({ id: Number(productId) })\n .value()\n return product\n }",
"findById(id) {\n return db.one(`\n SELECT parks.id, parks.name, states.name AS state\n FROM parks\n JOIN states\n ON states.code = parks.state\n WHERE parks.id = $1`, id);\n }",
"static async findById(id) {\n // Ensure model is registered before finding by ID\n assert.instanceOf(this.__db, DbApi, 'Model must be registered.');\n\n // Return model found by ID\n return await this.__db.findById(this, id);\n }",
"static get(name, id, opts) {\n return new RelationshipLink(name, undefined, Object.assign(Object.assign({}, opts), { id: id }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Undeploy and deregister the element | function undeployComponent(type, element, deleteFromModel) {
return ComponentService.undeploy(ENDPOINT_URI + "/deploy/" + type + "/" + element.data("id")).then(
function(response) {
element.data("deployed", false);
element.removeData("depError");
element.removeClass("error-element");
element.removeClass("deployed-element");
element.addClass("success-element");
// Deregister the element in second step
var promise = deregisterComponent(type, element, deleteFromModel);
vm.deletionPromises.push(promise);
},
function(response) {
element.data("depError", response.data ? response.data.globalMessage : response.status);
element.removeClass("success-element");
element.removeClass("deployed-element");
element.addClass("error-element");
vm.processing.undeployedDeregistered = false;
if (deleteFromModel) {
saveModel().then(function(response) {
vm.processing.message = "Undeployment of " + element.data("name") + " ended with an error";
vm.processing.success = false;
processingTimeout();
});
}
});
} | [
"function stopObservingElement(element) {\r\n // Do a manual registry lookup because we don't want to create a registry\r\n // if one doesn't exist.\r\n var uid = getUniqueElementID(element), registry = GLOBAL.Event.cache[uid];\r\n // This way we can return early if there is no registry.\r\n if (!registry) return;\r\n\r\n destroyRegistryForElement(element, uid);\r\n\r\n var entries, i;\r\n for (var eventName in registry) {\r\n // Explicitly skip elements so we don't accidentally find one with a\r\n // `length` property.\r\n if (eventName === 'element') continue;\r\n\r\n entries = registry[eventName];\r\n i = entries.length;\r\n while (i--)\r\n removeEvent(element, eventName, entries[i].responder);\r\n }\r\n }",
"function removeDeploy(cb){\n del(distPath, cb);\n}",
"function undeploy (argv, cb) {\n var args = argv._;\n if (args.length === 0){\n return cb(undeploy.usage);\n }\n\n var appId = fhc.appId(args[0]);\n var appType = args[1];\n var deployTarget = ini.getEnvironment(argv);\n\n return undeployApp(appId, deployTarget, appType, cb);\n}",
"function unsubscribe_observe(element) {\n let subs = new Subscription();\n for (let i = 0; i < observe_arr[element].length; i++) {\n subs.add(observe_arr[element][i]);\n }\n subs.unsubscribe();\n ob_attr_arr[element].disconnect();\n element.removeAttribute(\"TrueValue\");\n}",
"function undeployComponents() {\n vm.processing = {};\n vm.processing.status = true;\n vm.processing.undeployed = true;\n vm.processing.finished = false;\n\n var undeployPromises = [];\n $(\".jtk-node\").each(function(index, element) {\n var $element = $(element);\n var type = $element.attr('class').toString().split(\" \")[1];\n\n if (type == \"actuator\" && $element.data(\"deployed\")) {\n var promise = undeploy(ENDPOINT_URI + \"/deploy/actuator/\" + $element.data(\"id\"), $element);\n undeployPromises.push(promise);\n } else if (type == \"sensor\" && $element.data(\"deployed\")) {\n var promise = undeploy(ENDPOINT_URI + \"/deploy/sensor/\" + $element.data(\"id\"), $element);\n undeployPromises.push(promise);\n }\n });\n\n // save the model after the undeployment\n $q.all(undeployPromises).then(function() {\n if (undeployPromises.length === 0) {\n vm.processing.message = \"No components to undeploy\";\n vm.processing.success = false;\n processingTimeout();\n } else {\n saveModel().then(function(response) {\n if (vm.processing.undeployed && vm.processing.saved) {\n vm.processing.message = \"Undeployment completed, model saved\";\n vm.processing.success = true;\n } else if (vm.processing.undeployed && !vm.processing.saved) {\n vm.processing.message = \"Undeployment completed, model saving error\";\n vm.processing.success = false;\n } else if (!vm.processing.undeployed && vm.processing.saved) {\n vm.processing.message = \"Undeployment error, model saved\";\n vm.processing.success = false;\n } else if (!vm.processing.undeployed && !vm.processing.saved) {\n vm.processing.message = \"Undeployment error, model saving error\";\n vm.processing.success = false;\n }\n processingTimeout();\n });\n }\n });\n }",
"function stopObservingEventName(element, eventName) {\r\n var registry = getRegistryForElement(element);\r\n var entries = registry[eventName];\r\n if (!entries) return;\r\n delete registry[eventName];\r\n \r\n var i = entries.length;\r\n while (i--)\r\n removeEvent(element, eventName, entries[i].responder);\r\n\r\n for (var name in registry) {\r\n if (name === 'element') continue;\r\n return; // There is another registered event\r\n }\r\n\r\n // No other events for the element, destroy the registry:\r\n destroyRegistryForElement(element);\r\n }",
"function unregister(element, eventName, handler) {\r\n var registry = getRegistryForElement(element);\r\n var entries = registry[eventName];\r\n if (!entries) return;\r\n \r\n var i = entries.length, entry;\r\n while (i--) {\r\n if (entries[i].handler === handler) {\r\n entry = entries[i];\r\n break;\r\n }\r\n }\r\n \r\n // This handler wasn't in the collection, so it doesn't need to be\r\n // unregistered.\r\n if (!entry) return;\r\n\r\n // Remove the entry from the collection;\r\n var index = entries.indexOf(entry);\r\n entries.splice(index, 1);\r\n\r\n if (entries.length == 0) {\r\n stopObservingEventName(element, eventName);\r\n }\r\n return entry;\r\n }",
"remove() {\n const ownerElement = this.node.ownerElement\n if(ownerElement) {\n ownerElement.removeAttribute(this.name)\n }\n }",
"destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }",
"function deactivate() {\n global.hadronApp.appRegistry.deregisterRole('Collection.Tab', ROLE);\n global.hadronApp.appRegistry.deregisterAction('Validation.Actions');\n global.hadronApp.appRegistry.deregisterStore('Validation.Store');\n}",
"async unregister () {\n if (serviceId) {\n clearInterval(intervalId)\n await axios.delete(`${serviceRegistryUrl}/${serviceId}`)\n .catch(reason => console.error(`Unable to unregister service from registry : ${reason}`))\n serviceId = undefined\n }\n }",
"function deactivate() {\n global.hadronApp.appRegistry.deregisterRole('Collection.Tab', ROLE);\n global.hadronApp.appRegistry.deregisterAction('LatencyHistogram.Actions');\n global.hadronApp.appRegistry.deregisterStore('LatencyHistogram.Store');\n}",
"function unsubscribe() {\n getSubscription().then(subscription => {\n return subscription.unsubscribe()\n .then(() => {\n console.log('Unsubscribed ', subscription.endpoint)\n return fetch('http://localhost:4040/unregister', \n {\n method: 'POST',\n headers: {'Content-Type' : 'application/json'},\n body: JSON.stringify({\n endpoint: subscription.endpoint\n })\n })\n })\n }).then(setSubscribeButton)\n}",
"function removeElement(node) {\n\t\tjQuery(node).remove();\n\t}",
"function pushdeRegister()\n{\n\t//kony.print(\"************ JS unregisterFromAPNS() called *********\");\n\tkony.application.showLoadingScreen(\"sknLoading\",\"Deregistering from push notification..\",constants.LOADING_SCREEN_POSITION_FULL_SCREEN, true, true,null);\n\t\tkony.push.deRegister({});\n\t\taudiencePushSubs=false;\n\t\teditAudience2();\n\t\t\n}",
"remove() {\n // remove this element from appering \n document.getElementById(this.mainEl.id).remove();\n // send a request to remove this node \n axios.delete('post', {\n id: this.post.id\n })\n }",
"remove(element) {\n this.set.splice(this.set.indexOf(element), 1);\n console.log(\"element removed successfully\");\n }",
"function RemoveUpgrade(){\n\tplayer.upgraded = false;\n\tplayer.sprite =Sprite(currentActivePlayer);\n}",
"__unregisterInterfaceAttribute__( interfaceAttr ){\n delete VIRTUAL_BUTTONS_STATE[ interfaceAttr ];\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Row chart to show the top 10 countries with the highest suicide rate | function show_countries_with_highest_suicide(ndx) {
//Data dimension for country
let country_dim = ndx.dimension(dc.pluck('country'));
//Data group for no of suicides per 100k people for each country
let total_suicide_by_country = country_dim.group().reduceSum(dc.pluck('suicides_100k'));
//To set the number of countries in the chart
let top_countries = 10;
dc.rowChart("#row-chart")
.width(300)
.height(450)
.margins({ top: 20, left: 10, right: 10, bottom: 20 })
.transitionDuration(750)
.dimension(country_dim)
.group(total_suicide_by_country)
.data(function(d) { return d.top(top_countries); })
.ordinalColors(["#084099","#084080", "#0868af","#0868aa", "#2b8cbf","#2b8cba", "#4eb3d3","#4eb3d3", "#7bccc4", "#a8ddb5"])
.renderLabel(true)
.gap(1)
.title(function(d) { return "No. of suicides: " + d.value; })
.elasticX(true)
.useViewBoxResizing(true)
.xAxis().ticks(10).tickFormat(d3.format("s"));
} | [
"filterTopTenCountries(data) { \n let header = data['columns'].map(header => header);\n let lastEntryInHeaders = (header[header.length - 1])\n \n //sort data in descending order by total numbers\n let countriesSortedByTotalNumbers = data.sort(compareTotal);\n function compareTotal(a, b) {\n let country1 = a[lastEntryInHeaders]; \n let country2 = b[lastEntryInHeaders]; \n\n let comparison = 0;\n if (country1 > country2) {\n comparison = -1;\n } else if (country1 < country2) {\n comparison = 1;\n }\n return comparison;\n }\n return countriesSortedByTotalNumbers.slice(0, 10)\n }",
"function populateMostActiveCountriesChart(topCountries, id){\n let countries = topCountries.countries,\n\ttaskRuns = topCountries.n_task_runs;\n let con = $(`#${id}`).find(\".canvas-container\"),\n\tcanvas = $(`#${id}`).find(\"canvas\"),\n\tdata = {\n\t labels: countries.slice(0,5),\n\t datasets: getBarDataset(\"contribution\", taskRuns.slice(0,5))\n\t};\n let chart = drawBarChart(canvas, con, data);\n highlightBar(chart.datasets[0].bars[0]);\n chart.update();\n\n // Populate the table\n $.each(countries, function(i){\n\t$(`#${id}`).find(\"tbody\").append(\n\t `<tr>\n\t <td class=\"text-center\">${countries[i]}</td>\n\t <td class=\"text-center\">${taskRuns[i]}</td>\n\t </tr>`\n\t);\n });\n}",
"function chart_chef(chef_data) {\n const labels = []\n const data_count = []\n for ( var i in chef_data ) {\n labels.push(chef_data[i]._id)\n data_count.push(chef_data[i].count)\n }\n const data = {\n labels: labels,\n datasets: [{\n label: 'Top 5 Chefs, by recipe count',\n data: data_count,\n backgroundColor: [\n 'rgba(255, 99, 132, 0.2)',\n 'rgba(255, 159, 64, 0.2)',\n 'rgba(255, 205, 86, 0.2)',\n 'rgba(75, 192, 192, 0.2)',\n 'rgba(54, 162, 235, 0.2)'\n ],\n borderColor: [\n 'rgb(255, 99, 132)',\n 'rgb(255, 159, 64)',\n 'rgb(255, 205, 86)',\n 'rgb(75, 192, 192)',\n 'rgb(54, 162, 235)'\n ],\n borderWidth: 1\n }]\n };\n\n const config = {\n type: 'bar',\n data,\n options: {\n scales: {\n y: {\n beginAtZero: true\n }\n }\n }\n };\n\n var myChart = new Chart(\n document.getElementById('chefChart'),\n config\n );\n}",
"function get10RiskCountry(req, res) {\n var query = `\n SELECT DISTINCT Country, sum(Confirmed) AS total_Confirmed\n FROM World_df\n Where Date = (select MAX(Date) from World_df)\n Group by Country\n Order by total_Confirmed DESC\n LIMIT 10;\n `\n connection.query(query, function (err, rows, fields) {\n if (err) console.log(err)\n else {\n res.json(rows)\n }\n })\n}",
"function show_no_of_suicides_by_year(ndx) {\n //Data dimension for year\n let year_dim = ndx.dimension(function(d) {\n return new Date(d.year);\n });\n\n //Data group for no of suicides per 100k people for each gender\n let male_suicides_per_year = year_dim.group().reduceSum(function(d) {\n if (d.sex == \"male\") {\n return d.suicides_100k;\n }\n else {\n return 0;\n }\n });\n\n let female_suicides_per_year = year_dim.group().reduceSum(function(d) {\n if (d.sex == \"female\") {\n return d.suicides_100k;\n }\n else {\n return 0;\n }\n });\n\n //Setting min and max year for x-axis\n let min_year = year_dim.bottom(1)[0].year;\n let max_year = year_dim.top(1)[0].year;\n\n dc.lineChart(\"#line-chart\")\n .renderArea(true)\n .width(500)\n .height(350)\n .transitionDuration(1000)\n .margins({ top: 30, right: 50, bottom: 40, left: 50 })\n .dimension(year_dim)\n .group(female_suicides_per_year, \"Female\")\n .stack(male_suicides_per_year, \"Male\")\n .ordinalColors(['#fa9fb5', '#67a9cf'])\n .elasticY(true)\n .transitionDuration(500)\n .x(d3.time.scale().domain([min_year, max_year]))\n .renderHorizontalGridLines(true)\n .renderVerticalGridLines(true)\n .useViewBoxResizing(true)\n .title(function(d) { return \"Year \" + d.key.getFullYear() + \"\\n No. of suicides: \" + d.value; })\n .legend(dc.legend().x(400).y(30).itemHeight(13).gap(5))\n .brushOn(false)\n .xAxisLabel(\"Year\")\n .yAxisLabel(\"No. of Suicides per 100k people\")\n .yAxis().ticks(10);\n}",
"function show_country_map(ndx, countriesJson) {\n\n //Data dimension for country\n let country_dim = ndx.dimension(dc.pluck('country'));\n \n //Data group for no of suicides per 100k people for each country\n let total_suicide_by_country = country_dim.group().reduceSum(dc.pluck('suicides_100k'));\n\n dc.geoChoroplethChart(\"#map-chart\")\n .width(1000)\n .height(480)\n .dimension(country_dim)\n .group(total_suicide_by_country)\n .colors([\"#f0f9e8\", \"#ccebc5\", \"#a8ddb5\", \"#7bccc4\", \"#43a2ca\", \"#0868ac\"])\n .colorAccessor(function(d) { return d; })\n .colorDomain([1, 6000])\n .overlayGeoJson(countriesJson[\"features\"], \"country\", function(d) {\n return d.properties.name;\n })\n .projection(d3.geo.mercator()\n .center([10, 40])\n .scale(110))\n .useViewBoxResizing(true)\n .title(function(d) {\n if (d.value == undefined) {\n return \"Country: \" + d.key +\n \"\\n\" +\n \"Data Unavailable\";\n }\n else {\n return \"Country: \" + d.key +\n \"\\n\" +\n \"Total Suicides: \" + d.value;\n }\n });\n}",
"function popularity(data) {\n var d = data;\n answer = {};\n data.forEach(element => {\n start = element[\"Starting Station ID\"];\n end = element[\"Ending Station ID\"];\n if (start) {\n if (answer[start]) {\n answer[start]++;\n } else {\n answer[start] = 1;\n }\n }\n if (end) {\n if (answer[end]) {\n answer[end]++;\n } else {\n answer[end] = 1;\n }\n }\n });\n\n // Sorts the data\n sortedData = [];\n var sum = 0;\n Object.keys(answer).forEach(key => {\n var v = {\n id: key,\n freq: answer[key],\n }\n sortedData.push(v);\n sum += v.freq;\n });\n sortedData.sort(function (a, b) {\n return b.freq - a.freq;\n });\n\n var table = document.getElementById(\"popularity\");\n\n for (let index = 0; index < sortedData.length; index++) {\n const element = sortedData[index];\n\n var rank = document.createElement(\"td\");\n rank.innerText = index + 1;\n var id = document.createElement(\"td\");\n id.innerText = element.id;\n var freq = document.createElement(\"td\");\n freq.innerText = element.freq;\n\n var row = document.createElement(\"tr\");\n row.appendChild(rank);\n row.appendChild(id);\n row.appendChild(freq);\n table.appendChild(row);\n }\n\n sortedData.forEach(element => {\n var id = document.createElement(\"td\");\n id.innerText = element.id;\n var freq = document.createElement(\"td\");\n freq.innerText = element.freq;\n\n var row = document.createElement(\"tr\");\n row.appendChild(id);\n row.appendChild(freq);\n table.appendChild(row);\n });\n myData.innerText = sum;\n // myData.innerText = JSON.stringify(sortedData);\n}",
"function showPopPercent(ndx, element, colorScale) {\n var countryDim = ndx.dimension(dc.pluck(\"Country\"));\n var population = countryDim.group().reduceSum(dc.pluck(\"Population\"));\n dc.pieChart(element)\n .height(330)\n .radius(100)\n .transitionDuration(1000)\n .dimension(countryDim)\n .group(population)\n .colors(colorScale);\n}",
"async function getTopTradingPartners(targetCountry) {\n try {\n //Get exports\n const exports = await te.getComtradeTotalByType(\n (country = targetCountry),\n (type = 'export')\n )\n //Get imports\n const imports = await te.getComtradeTotalByType(\n (country = targetCountry),\n (type = 'import')\n )\n const exportCountries = exports.filter(\n (entry) => entry.country2.toLowerCase() != 'world'\n )\n const importCountries = imports.filter(\n (entry) => entry.country2.toLowerCase() != 'world'\n )\n //Top 5 export markets\n const top5Export = exportCountries\n .sort((a, b) => b.value - a.value)\n .slice(0, 5)\n //Top 5 import sources\n const top5Import = importCountries\n .sort((a, b) => b.value - a.value)\n .slice(0, 5)\n console.log('Top 5 export markets:', '\\n', top5Export)\n console.log('Top 5 import sources:', '\\n', top5Import)\n } catch (error) {\n console.log(error)\n }\n}",
"function chart_user(activity_data) {\n const labels = []\n const data_count = []\n for ( var i in activity_data ) {\n labels.push(activity_data[i]._id)\n data_count.push(activity_data[i].total)\n }\n const data = {\n labels: labels,\n datasets: [{\n label: 'Top 5 Active Users',\n data: data_count,\n backgroundColor: [\n 'rgba(255, 99, 132, 0.2)',\n 'rgba(255, 159, 64, 0.2)',\n 'rgba(255, 205, 86, 0.2)',\n 'rgba(75, 192, 192, 0.2)',\n 'rgba(54, 162, 235, 0.2)'\n ],\n borderColor: [\n 'rgb(255, 99, 132)',\n 'rgb(255, 159, 64)',\n 'rgb(255, 205, 86)',\n 'rgb(75, 192, 192)',\n 'rgb(54, 162, 235)'\n ],\n borderWidth: 1\n }]\n };\n\n const config = {\n type: 'bar',\n data,\n options: {\n scales: {\n y: {\n beginAtZero: true\n }\n }\n }\n };\n\n var myChart = new Chart(\n document.getElementById('userChart'),\n config\n );\n}",
"function show_total_no_of_suicides(ndx) {\n let total_no_of_suicides = ndx.groupAll().reduceSum(dc.pluck('suicides_100k'));\n\n dc.numberDisplay(\"#suicides-figure\")\n .group(total_no_of_suicides)\n .formatNumber(d3.format(\"d\"))\n .valueAccessor(function(d) {\n return d;\n });\n}",
"function getTopCrimePlayers() {\r\n\t\t$.get('http://nflarrest.com/api/v1/player', function(data) {\r\n\t\t\t//console.log(data)\r\n\t\t\t// compare function of array object properties to sort by arrest_count\r\n\t\t\tfunction compare(a,b) {\r\n\t\t\t\tif (a.arrest_count < b.arrest_count) {\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t} else if (a.arrest_count > b.arrest_count) {\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// sort data by highest arrests before mapping into new array\r\n\t\t\tdata.sort(compare);\r\n\t\t\t// map top 5 arrested players into array\r\n\t\t\tlet topPlayers = new Array();\r\n\t\t\tfor (var i = 0; i < data.length; i++) {\r\n\t\t\t\tif (i < 5) {\r\n\t\t\t\t\ttopPlayers.push('<li>' + data[i].Name + ' (' + data[i].arrest_count + ')');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t$(\"#top-players\").append(topPlayers);\r\n\t\t});\r\n\t}",
"function popularityChart(file_name, div_num, country_name) { \n // document.getElementById('download_file').action = file_name; \n\n google.charts.load('current', {'packages':['corechart']});\n google.charts.setOnLoadCallback(drawBoxPlot);\n\n function drawBoxPlot() {\n var arrayStars = [];\n $.ajax({\n type: \"GET\", \n url: file_name,\n dataType: \"text\", \n success: function(response) {\n var arrayData = $.csv.toArrays(response);\n var i, starsCol; \n for(i = 0; i < arrayData[0].length; i++) { \n if(arrayData[0][i] === 'num_watchers') {\n starsCol = i; \n break;\n }\n }\n\n arrayStars[0] = [];\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'x');\n arrayStars[0][0] = arrayData[0][starsCol];\n for(i = 0; i < arrayData.length-1; i++) { \n arrayStars[0][i+1] = Number(arrayData[i+1][starsCol]);\n // console.log('series' + i);\n data.addColumn('number', 'series' + i); \n }\n\n arrayStars = getBoxPlotValues(arrayStars); \n\n var data = new google.visualization.DataTable();\n data.addColumn('string', 'x');\n for(i = 0; i < arrayStars[0].length-6; i++) { \n data.addColumn('number', 'series' + i); \n }\n\n data.addColumn({id:'max', type:'number', role:'interval'});\n data.addColumn({id:'min', type:'number', role:'interval'});\n data.addColumn({id:'firstQuartile', type:'number', role:'interval'});\n data.addColumn({id:'median', type:'number', role:'interval'});\n data.addColumn({id:'thirdQuartile', type:'number', role:'interval'});\n\n data.addRows(arrayStars);\n\n function getBoxPlotValues(array) {\n // console.log(array[0]);\n for (var i = 0; i < array.length; i++) {\n var arr = array[i].slice(1).sort(function (a, b) {\n return a - b;\n });\n\n var max = arr[arr.length - 1];\n var min = arr[0];\n var median = getMedian(arr);\n if(arr.length %2 === 0) { \n var midUpper = arr.length / 2;\n var midLower = midUpper;\n } else { \n var midLower = Math.floor(arr.length / 2); \n var midUpper = midLower + 1; \n }\n\n // First Quartile is the median from lowest to overall median.\n var firstQuartile = getMedian(arr.slice(0, midUpper));\n\n // Third Quartile is the median from the overall median to the highest.\n var thirdQuartile = getMedian(arr.slice(midLower));\n\n var arr_result = []\n arr_result[0] = 'num_watchers'; \n var begin = firstQuartile-1.5*(thirdQuartile-firstQuartile);\n var end = thirdQuartile+1.5*(thirdQuartile -firstQuartile); \n for(var j = 0; j < arr.length; j++){\n if(arr[j] >= begin && arr[j] <= end ){\n arr_result.push(arr[j]);\n }\n }\n\n var pos = arr_result.length;\n arr_result[pos] = arr_result[arr_result.length-1];\n pos++;\n arr_result[pos] = arr_result[1];\n pos++;\n arr_result[pos] = firstQuartile;\n pos++;\n arr_result[pos] = median;\n pos++;\n arr_result[pos] = thirdQuartile;\n\n array[i] = arr_result; \n\n\n }\n // console.log(arr_result);\n return array;\n }\n\n /*\n * Takes an array and returns\n * the median value.\n */\n function getMedian(array) {\n var length = array.length;\n\n /* If the array is an even length the\n * median is the average of the two\n * middle-most values. Otherwise the\n * median is the middle-most value.\n */\n if (length % 2 === 0) {\n var midUpper = length / 2;\n var midLower = midUpper - 1;\n\n return (array[midUpper] + array[midLower]) / 2;\n } else {\n return array[Math.floor(length / 2)];\n }\n }\n\n var options = {\n title: country_name,\n height: 500,\n width: 200,\n legend: {position: 'none'},\n hAxis: {\n gridlines: {color: '#fff'}\n },\n lineWidth: 0,\n series: [{'color': '#D3362D'}],\n intervals: {\n barWidth: 1,\n boxWidth: 1,\n lineWidth: 2,\n style: 'boxes'\n },\n interval: {\n max: {\n style: 'bars',\n fillOpacity: 1,\n color: '#777'\n },\n min: {\n style: 'bars',\n fillOpacity: 1,\n color: '#777'\n }\n }\n };\n\n // document.getElementById('download_button').style.display = \"inline\";\n var div = document.createElement('div_'+div_num);\n div.style.width = \"100px\";\n div.style.height = \"100px\";\n div.style.display = \"table-cell\";\n \n var chart = new google.visualization.LineChart(div);\n\n document.getElementById(\"chart_div\").appendChild(div);\n chart.draw(data, options);\n\n if(div_num === 0) {\n createDataTable(arrayData[0]);\n }\n\n insertDataOnTable(arrayData.slice(1));\n }\n });\n }\n}",
"function show_no_of_suicides_by_age_group(ndx) {\n //Data dimension for age group\n let age_dim = ndx.dimension(dc.pluck('age'));\n\n //Data group for no of suicides per 100k people for each age group, categorized by gender\n let male_suicides_per_age_group = age_dim.group().reduceSum(function(d) {\n if (d.sex == \"male\") {\n return d.suicides_100k;\n }\n else {\n return 0;\n }\n });\n\n let female_suicides_per_age_group = age_dim.group().reduceSum(function(d) {\n if (d.sex == \"female\") {\n return d.suicides_100k;\n }\n else {\n return 0;\n }\n });\n\n dc.barChart(\"#bar-chart\")\n .width(500)\n .height(350)\n .margins({ top: 30, right: 50, bottom: 40, left: 50 })\n .dimension(age_dim)\n .group(female_suicides_per_age_group, \"Female\")\n .stack(male_suicides_per_age_group, \"Male\")\n .ordinalColors(['#fa9fb5', '#67a9cf'])\n .elasticY(true)\n .useViewBoxResizing(true)\n .title(function(d) { return \"Age Group: \" + d.key + \"\\n No. of suicides: \" + d.value; })\n .x(d3.scale.ordinal())\n .renderHorizontalGridLines(true)\n .legend(dc.legend().x(100).y(20).itemHeight(13).gap(5))\n .xUnits(dc.units.ordinal)\n .xAxisLabel(\"Age Group\")\n .yAxisLabel(\"No. of Suicides per 100k people\")\n .yAxis().ticks(10);\n}",
"renderDistinctValues() {\n const values = this.props.data.values;\n const barChartData = values; // values.slice(0, Math.min(TOP_K, values.length));\n return (\n <div className=\"p-2\">\n {this.renderTitle()}\n {this.renderBarChart(barChartData)}\n {this.renderLabel('Distinct Values', values.length.toString())}\n </div>\n );\n }",
"function populateTopUsersThisWeekChart(top5Users1Week, id) {\n if(!top5Users1Week.length) {\n\t$(`#${id}`).hide();\n\treturn;\n }\n\n let users = [],\n\ttaskRuns = [];\n for (i = 0; i < top5Users1Week.length; i++) {\n\tusers.push(top5Users1Week[i]['name']);\n\ttaskRuns.push(parseInt(top5Users1Week[i]['task_runs']));\n }\n\n let con = $(`#${id}`).find(\".canvas-container\"),\n\tcanvas = $(`#${id}`).find(\"canvas\"),\n\tdata = {\n\t labels: users,\n\t datasets: getBarDataset(\"contribution\", taskRuns)\n\t};\n let chart = drawBarChart(canvas, con, data);\n let highScore = taskRuns.indexOf(Math.max.apply(Math, taskRuns));\n highlightBar(chart.datasets[0].bars[highScore]);\n chart.update();\n}",
"function sortingMales(){\n if(keyCode===UP_ARROW){\n BubbleSort();\n for(i=0;i<data.countrydata.length;i++){\n fill(255,0,0)\n stroke(0,0,255)\n strokeWeight(6);\n rect(i,0,2,data.countrydata[i].males/80000)\n }\n}\n}",
"function addVolunteersCountryMap(number_of_users_per_country) {\n var number_of_users_per_country_data = []\n var MIN = 1000000;\n var MAX = -1;\n \n for(var i=0;i<number_of_users_per_country.rows.length;i++){\n var c = number_of_users_per_country.rows[i]\n var data_point = {}\n if(country_code_map[c[0].replace(\"&\",\"&\")] !== undefined){\n data_point[\"hc-key\"] = country_code_map[c[0].replace(\"&\",\"&\")].toLowerCase()\n data_point[\"value\"] = parseInt(c[1])\n if(parseInt(c[1]) > MAX) {\n MAX = parseInt(c[1]);\n };\n \n if(parseInt(c[1]) < MIN) {;\n MIN = parseInt(c[1]);\n }\n number_of_users_per_country_data.push(data_point);\n }else {\n console.log(\"Wrong mapping: \" + c[0]);\n }\n }\n\n\n // Initiate the chart\n $('#map').highcharts('Map', {\n\n title : {\n text : ''\n },\n mapNavigation: {\n enabled: true,\n enableMouseWheelZoom: false,\n buttonOptions: {\n verticalAlign: 'bottom',\n align: \"right\"\n }\n },\n\n colorAxis: {\n min: MIN,\n max: MAX\n },\n\n\n series : [{\n data : number_of_users_per_country_data,\n mapData: Highcharts.maps['custom/world'],\n joinBy: 'hc-key',\n name: 'Total Volunteers',\n states: {\n hover: {\n color: '#BADA55'\n }\n },\n dataLabels: {\n enabled: false,\n format: '{point.name}'\n }\n }],\n credits: {\n enabled: true\n } \n }).unbind(document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel');\n}",
"function drawProvincesPieChart() {\n const data = new google.visualization.DataTable();\n data.addColumn('string', 'Ethnic Group');\n data.addColumn('number', 'Count');\n data.addRows(CHINA_PROVINCES_TABLE);\n\n const options = {\n title: CHARTS_TITLES.MINORITIES_PIE_CHART,\n width: 700,\n height: 500\n };\n\n const chart = new google.visualization.PieChart(document.getElementById(DOM_CONTAINARS_IDS.DEMOGRAPHIC_CHART));\n chart.draw(data, options);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an IFolder intance given a base object and either an absolute or server relative path to a folder | async function folderFromPath(base, path) {
return (isUrlAbsolute(path) ? folderFromAbsolutePath : folderFromServerRelativePath)(base, path);
} | [
"function folderFromServerRelativePath(base, serverRelativePath) {\n return Folder([base, extractWebUrl(base.toUrl())], `_api/web/getFolderByServerRelativePath(decodedUrl='${encodePath(serverRelativePath)}')`);\n}",
"function fileFromServerRelativePath(base, serverRelativePath) {\n return File([base, extractWebUrl(base.toUrl())], `_api/web/getFileByServerRelativePath(decodedUrl='${encodePath(serverRelativePath)}')`);\n}",
"createFolder(parentPath, name, callback) {\n\t\tlet params = {\n\t\t\tBucket: this._bucket,\n\t\t\tKey: parentPath + name\n\t\t};\n\t\tthis._s3.putObject(params, function (err, data) {\n\t\t\tcallback(parentPath + name);\n\t\t});\n\t}",
"static _createCacheFolder() {\n const dir = './cache';\n\n try {\n fs.accessSync(dir, fs.F_OK);\n } catch (e) {\n fs.mkdirSync(dir);\n }\n }",
"function createNewFolder() {\n var id = $(this).parent().attr(\"data-id\");\n fileSystem.createFileOrFolder(id, \"folder\");\n updateUI();\n }",
"function Folder( name, path ) {\n this.name = name;\n this.path = decodeURIComponent(path);\n this.isFolder = true;\n}",
"function makeFolders(){\n try {\n var projFolderString = my.dat.meta.rootFolder + \"ScriptProjects/\" + my.dflts.titles.cTitle\n var dskPath = projFolderString + \"/\";\n writeFolder(dskPath);\n\n var myPath;\n var diskFolders = my.dat.folders.descendants().(@disk == \"yes\");\n // Do the disk folders\n for (var s = 0; s < diskFolders.length(); s++) {\n var finalPath;\n myPath = \"\";\n var currLmnt = diskFolders.child(s);\n var topLev = \"\";\n if (currLmnt.parent().name() == \"folders\") {\n topLev = currLmnt.@name + \"/\"; // Previously, topLev had been defined here. I moved the declaration out above.\n }\n while(currLmnt.parent().name() != \"folders\") {\n myPath = currLmnt.@name + \"/\" + myPath;\n currLmnt = currLmnt.parent();\n }\n finalPath = dskPath + topLev + myPath; // This was messed up, with erroneous slashes.\n writeFolder(finalPath);\n } \n } catch(err){ alert(\"Oops. On line \" + err.line + \" of \\\"makeFolders()\\\" you got \" + err.message);}\n }",
"function pathStaticS3(id, baseFolder, subFolder) {\n\tvar path = '';\n\tpath += baseFolder + '/';\n\tpath += idLevel(id) + '/';\n\tif (subFolder) {\n\t\tpath += subFolder + '/';\n\t}\n\treturn path;\n}",
"function createFolder(auth) {\r\n\tconst drive = google.drive({version: 'v3', auth}); \r\n\t\r\n\tvar fileMetadata = {\r\n\t\t'name': DRIVE_PATH,\r\n\t\tmimeType: 'application/vnd.google-apps.folder'\r\n\t};\r\n\r\n\tdrive.files.create(\r\n\t\t{\r\n\t\t\tresource: fileMetadata,\r\n\t\t\tfields: 'id'\r\n\t\t}, \r\n\t\t(err, folder) => {\r\n\t\t\tif (err) {\r\n\t\t\t console.error(err);\r\n\t\t\t} else {\r\n\t\t\t DRIVE_PATH_ID = folder.data.id;\r\n\t\t\t console.log('Created folder with id: ', folder.data.id);\r\n\t\t\t}\r\n\t\t}\r\n\t);\r\n}",
"function addBase (base, path) {\n var result = path\n\n // add if exists\n if (base) result = `${base}/${path}`\n\n return result\n }",
"function createItemFolder (req, res, next) {\r\n\r\n\tvar folder = ParseReqRes.getItemFolder(req, res);\r\n\r\n\tconsole.log('DEBUG (INFO): createItemFolder:', folder);\r\n\r\n\tcreateDir(folder).done(\r\n\r\n\t\tfunction (result) {\r\n\t\t\treturn next();\r\n\t\t},\r\n\t\tfunction (error) {\r\n\t\t\tconsole.log('DEBUG (ERR): createItemFolder:', error);\r\n\t\t\treturn res.status(500).send(error);\r\n\t\t}\r\n\t);\r\n}",
"function test_custom_folder_exists() {\n assert_folder_mode(\"smart\");\n assert_folder_displayed(smartFolderA);\n // this is our custom smart folder parent created in folderPane.js\n mc.folderTreeView.selectFolder(subfolderA);\n assert_folder_selected_and_displayed(subfolderA);\n}",
"function getLocalFolders() {\r\n\tvar server = getLocalFoldersServer();\r\n\tvar folder = server.rootFolder;\r\n\treturn folder;\r\n}",
"function subFolderCreate() {\n var requester = gapi.client.request({\n 'path': '/drive/v2/files',\n 'method': 'POST',\n 'body': {'title': 'Auto Save', 'mimeType' : 'application/vnd.google-apps.folder', 'parents': [{\"id\": ENGRFolderId}]}\n });\n requester.execute(function(res) {\n autoSaveFolderId = res.id;\n readFiles(ENGRFolderId, autoSaveFolderId);\n })\n }",
"function jsDAV_Directory() {}",
"function createTestFolder() {\n DriveApp.createFolder('test1');\n DriveApp.createFolder('test2');\n}",
"function sdFolderService($http,$q,sdUtilService){\n this.$http = $http;\n this.$q = $q;\n this.rootUrl = sdUtilService.getBaseUrl();\n }",
"function mkdirp(base, subdir) {\n var steps = subdir.split(path.sep);\n var current = base;\n for (var i = 0; i < steps.length; i++) {\n current = path.join(current, steps[i]);\n if (!fs.existsSync(current))\n fs.mkdirSync(current);\n }\n }",
"async getFolder(href) {\n const [result] = await this.client('folders').select('folder').where('href', href);\n if (typeof result !== 'undefined') {\n return new Folder(result.href, result.folder);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This Col component offers us the convenience of being able to set a column's "size" prop instead of its className We can also omit the col at the start of each Bootstrap column class, e.g.size = "md12" instead of className = "colmd12" | function Col(props) {
const size = props.size
.split(` `)
.map(s => `col-${ s}`)
.join(` `);
return <div className={size}>{props.children}</div>;
} | [
"function ColumnLayout({\n mobileSize,\n tabletSize,\n desktopSize,\n children\n}) {\n\n let errorJsx = [];\n if (mobileSize === undefined && tabletSize === undefined && desktopSize === undefined) {\n throw new Error(\"Please set at least one of mobileSize, tableSize, and desktopSize\");\n }\n\n let columnClass = \"ColumnLayout\";\n if (desktopSize !== undefined) {\n if (desktopSize === 0) {\n columnClass += \" col-desktop-hidden\";\n }\n else {\n columnClass += \" col-desktop-\" + desktopSize;\n }\n }\n\n if (tabletSize !== undefined) {\n if (tabletSize === 0) {\n columnClass += \" col-tablet-hidden\";\n }\n else {\n columnClass += \" col-tablet-\" + tabletSize;\n }\n }\n\n if (mobileSize !== undefined) {\n if (mobileSize === 0) {\n columnClass += \" col-mobile-hidden\";\n }\n else {\n columnClass += \" col-mobile-\" + mobileSize;\n }\n }\n\n return (\n <div className={columnClass}>\n {errorJsx}\n {children}\n </div>\n );\n}",
"constructor(row, col, size) {\n this.size = size\n this.row = row\n this.col = col\n }",
"function addSizesToElement(element, sizes){\n var classString = element.className;\n var currentSizes = getElementSizes(element);\n classString = stripColumns(classString);\n for(i in sizes){\n currentSizes[i] += sizes[i];\n classString += (' col-' + i + '-' + currentSizes[i]);\n }\n element.className = classString;\n}",
"SetColumn() {}",
"function subtractSizesFromElement(element, sizes){\n var classString = element.className;\n var currentSizes = getElementSizes(element);\n classString = stripColumns(classString);\n for(i in sizes){\n currentSizes[i] -= sizes[i];\n classString += (' col-' + i + '-' + currentSizes[i]); \n }\n element.className = classString; \n}",
"function col(numCol) {\n return numCol * COL + COL_OFFSET;\n}",
"function columnSizeValidation(props, propName, componentName) {\n componentName = componentName || \"ANONYMOUS\";\n\n if (props[propName]) {\n const size = props[propName];\n\n if (typeof size === \"number\") {\n return (size <= 6 && size >= 0)\n ? null\n : new Error(\"Prop \" + propName + \" in \" + componentName + \" is \" + size + \", should be a number between 0 to 6\");\n }\n else {\n return new Error(\"Prop \" + propName + \" in \" + componentName + \" should be a number, not a \" + typeof size);\n }\n }\n}",
"function Columns(count = 1, id = null, border = true) {\r\n id = id || \"\";\r\n bind.Columns(count, id, border);\r\n }",
"function getColumns(maxCols, colWidths) {\n let cols = [];\n for (let i = 0; i < maxCols; i++) {\n cols.push(<Col key={i} width={colWidths[i]} />);\n }\n\n return cols;\n}",
"function getColId(col) {\n var r;\n $.each(col.classList, function () {\n if (this.match(/^col-/)) {\n r = this.replace(/^col-/, '');\n }\n });\n return r;\n }",
"getCols() {\r\n let cols = Math.floor(Math.ceil(this.getWidth() / 100) / 2) * 2;\r\n\r\n return cols > 0 ? cols : 1;\r\n }",
"function setColumns() {\n\n }",
"assignImgsToCols() {\n let numOfCols = this.calculateCols();\n \n // Init cols\n let cols = [];\n let i;\n for (i = 0; i < numOfCols; i += 1) {\n cols.push({key: i, imgs: []});\n }\n\n let {imgs} = this.props;\n \n // Init colHeights\n let colHeights = [];\n for (i = 0; i < cols.length; i+=1) {\n colHeights[i] = 0;\n };\n\n // Add image to shortest column\n if (cols.length > 0) {\n imgs.forEach((img) => {\n let col = this.findShortestColumn(colHeights);\n cols[col].imgs.push(img);\n let {dimensions} = img.props.img.value;\n colHeights[col] += dimensions.small.maxHeight;\n });\n }\n \n return cols;\n }",
"updateColumnDisplay() {\n let i = 0;\n while (i < this.columnData.length) {\n let colData = this.columnData[i];\n let colWidth = colData.getValue('widthVal');\n let colSpan = colData.getValue('colspanVal');\n colData.getElement().show();\n if (colSpan > 1) {\n let colspanEndIndex = ((i + colSpan) < this.columnData.length) ? (i + colSpan) : this.columnData.length;\n i++;\n // hide columns within colspan\n while (i < colspanEndIndex) {\n colWidth += this.columnData[i].getValue('widthVal');\n this.columnData[i].getElement().hide();\n i++;\n }\n } else {\n i++;\n }\n colData.setDisplayWidth(colWidth);\n colData.updateDisplay();\n }\n }",
"function LineColComponent(props) {\n const translator = props.translator || nullTranslator;\n const trans = translator.load('jupyterlab');\n return (React.createElement(TextItem, { onClick: props.handleClick, source: trans.__('Ln %1, Col %2', props.line, props.column), title: trans.__('Go to line number…') }));\n}",
"function initializeColumns() {\n const columns = [\n //first column\n {\n title: ' Title',\n dataIndex: 'title'\n },\n //second column\n {\n title: 'Description',\n dataIndex: 'description'\n },\n\n {\n title: 'Category',\n width: 200,\n dataIndex: 'category',\n render: (category) => {\n return category.name;\n }\n },\n {\n title: 'Log Created',\n width: 200,\n dataIndex: 'createTime'\n },\n //fourth column\n {\n title: 'Modifier',\n width: 200,\n dataIndex: 'modifier',\n render: (modifier) => {\n return modifier.firstName;\n }\n },\n {\n title: 'Action',\n width: 200,\n dataIndex: 'action'\n },\n ];\n setColumns(columns);\n }",
"function drawCol(note) {\n const { notes_insert } = NOTES_DOM;\n const notesCOL = createNoteCol(note);\n if (!notesCOL) return;\n notes_insert.append(notesCOL);\n}",
"getFontSize() {\n return (this.props.cellSizeInPx / 2.77) + 'px';\n }",
"function getElementSizes(element){\n var classString = element.className;\n var outObj = {};\n let regexp = /col-[\\w]+-[0-9]+/ig;\n let array = [...classString.matchAll(regexp)];\n for(i in array){\n let string = array[i][0];\n string = string.replace('col-','');\n const index = string.indexOf('-');\n const col = string.substring(0,index);\n const value = parseInt(string.substring(index + 1));\n outObj[col] = value;\n }\n return outObj;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sorts locations in "my library" before groups and group subfolders | function isMyLibraryComparator(a, b) {
if (isMyFolder(a) && !isMyFolder(b)) {
return -1;
} else if (!isMyFolder(a) && isMyFolder(b)) {
return 1;
} else {
return 0;
}
} | [
"function sortVideosArray() {\n\tlet mainObject = {\"type\": \"folder\"}; // Object that will hold array of objects\n\t// Loop through videos array\n\tlet currObject;\n\tfor (let i = 0; i < videos.length; i++) {\n\t\tlet folderArray = videos[i].folder.split(\"->\"); // Split folder name into array of separate strings\n\t\tcurrObject = mainObject;\n\t\t// Loop through array of folders\n\t\tfor (let j = 0; j < folderArray.length; j++) {\n\t\t\tif (currObject[folderArray[j]] == null) { // if folder does not exist, create it\n\t\t\t\tcurrObject[folderArray[j]] = {};\n\t\t\t\tcurrObject[folderArray[j]][\"parent\"] = currObject; // Add parent of current folder\n\t\t\t}\n\n\t\t\tcurrObject = currObject[folderArray[j]]; // reset currObject\n\t\t\tcurrObject[\"type\"] = \"folder\"; // add type\n\t\t}\n\t\tcurrObject[\"content\"] = videos[i]; // add content to end of tree node\n\t}\n\tconsole.log(mainObject);\n\treturn mainObject;\n\n\n}",
"function _sortGroups(first, second) {\n var firstGroup = CockpitHelper.hashedGroupList[first];\n var secondGroup = CockpitHelper.hashedGroupList[second];\n return firstGroup.position - secondGroup.position;\n }",
"function GetAlbumsSortedBy(id, sortMode, sortOverride) {\n $('#loading_anim_albums').show();\n var sortModes = ['DATE ADDED', 'A TO Z', 'RELEASE YEAR', 'ARTIST'];\n\n leftListId = id;\n\n if (id !== null && id.startsWith(\"albumartists\")) {\n //remove the artist because we do not need to display it when showing albums for an artist\n sortModes.splice(3, 1);\n }\n var theSortMode;\n\n if (sortOverride === false) {\n var idx = sortModes.indexOf(sortMode);\n if (idx == sortModes.length - 1) {\n theSortMode = sortModes[0];\n }\n else {\n theSortMode = sortModes[idx + 1];\n }\n }\n else {\n theSortMode = sortMode;\n }\n\t\n\t//todo: remove hardcoded album width values and get real values\n\tvar xAlbums = Math.floor($(\"#albums\").width() / 130);\n\tvar yAlbums = Math.ceil($(\"#albums\").height() / 161)\n\t//+ 1 row to prevent the div from scrolling while albums are loading\n\tvar numAlbsToGet = xAlbums * yAlbums + xAlbums;\n\t\n\tif(theSortMode === 'ARTIST'){\n\t\tnumAlbsToGet = yAlbums;\n\t}\n\n switch (theSortMode) {\n case \"DATE ADDED\":\n QueryAlbumsSortedByDateAdded(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'DATE ADDED', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithNoHeaderings(result, 'DATE ADDED'));\n }\n });\n break;\n case \"A TO Z\":\n QueryAlbumsSortedByAlbumTitle(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'A TO Z', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithNoHeaderings(result, 'A TO Z'));\n }\n });\n break;\n case \"RELEASE YEAR\":\n QueryAlbumsSortedByReleaseYear(id, 0, numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n if (id.startsWith('albumartists')) {\n UpdateView(CreateAlbumObjectsWithNoHeaderingsForArtists(result, 'RELEASE YEAR', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithYearHeadersForGenres(id, result, 'RELEASE YEAR'));\n }\n }\n else {\n UpdateView(CreateAlbumObjectsWithYearHeaders(result, 'RELEASE YEAR'));\n }\n });\n break;\n case \"ARTIST\":\n QueryAlbumsSortedByArtist(id, 0,numAlbsToGet, function (result) {\n if (id !== null && id.length > 0) {\n //just for genres\n UpdateView(CreateAlbumObjectsWithArtistHeadersForGenres(id, result, 'ARTIST', id));\n }\n else {\n UpdateView(CreateAlbumObjectsWithArtistHeaders(result, 'ARTIST'));\n }\n });\n }\n\n function UpdateView(result) {\n\t\t//render header\n\t\t$(\"#middle_header\").remove();\n $(\"#content\").append(\"#tmpl_albums_container\", result);\n\t\t\n\t\t$(\"#albums > .inner\").empty();\n\t\t//render results\n\t\t$.each(result.AlbumsOrHeaders,function(idx,value){\n\t\t\tif(value.IsContent === false){\n\t\t\t\t$(\"#albums > .inner\").append(\"#tmpl_album_header\",value);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tRenderAlbumToView($(\"#albums > .inner\"),value.Content);\n\t\t\t}\n\t\t});\n\t\t\n\t\t//for the first row of albums we need to remove the top padding\n\t\t\n\t\t//infinite scroll\n\t\tvar elem = $('#albums')\n elem.scroll(function () {\n\t\t\tif (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) {\n\t\t\t\tconsole.log(\"getting more albums...\");\n\t\t\t\tGetMoreAlbums(leftListId);\n\t\t\t}\n });\n\n\t\t\n $('#loading_anim_albums').hide();\n }\n}",
"function topologicalSort(libs) {\n // Good luck!\n return true;\n}",
"function sortFiles() {\n var sortedFiles = {\n personal: [],\n academy: [],\n };\n files.forEach((file) => {\n sortedFiles[file.type].push(\n <grid\n item\n key={file.id}\n onDragStart={(event) => onDragStart(event, file.name)}\n draggable\n className=\"draggable\"\n >\n <DescriptionIcon fontSize=\"large\" />\n <br />\n {file.name}\n </grid>\n );\n });\n return sortedFiles;\n }",
"function sortByDist(trees) {\n\ttrees.forEach(function(tree) {\n\t\ttree.dist = getDistanceFromLatLonInM([tree.lon, tree.lat], state.user.location)\n\t})\n\ttrees.sort(function(a, b) {\n\t\tif (a.dist < b.dist)\n\t\t\treturn -1;\n\t\tif (a.dist > b.dist)\n\t\t\treturn 1;\n\t\treturn 0;\n\t})\n\treturn trees\n}",
"function sortFn(a, b) {\n return find(a).deepDepends.indexOf(b) >= 0 ? 1 : find(b).deepDepends.indexOf(a) >= 0 ? -1 : 0;\n }",
"function pathsort(paths, sep, algorithm) {\n sep = sep || '/'\n\n return paths.map(function(el) {\n return el.split(sep)\n }).sort(algorithm || levelSorter).map(function(el) {\n return el.join(sep)\n })\n}",
"function sortedGroupNames(callback) {\n chrome.storage.local.get(\"groups\", function(data) {\n let groups = data[\"groups\"]; //Enter groups object\n let groupNames = Object.keys(groups);\n //Sorts the groups from highest \"priority\" to lowest \"priority\" in 'sorted' array\n for (groupName of groupNames) {\n let nameA = groupName;\n let nameB = null;\n let indexA = groupNames.indexOf(groupName);\n let indexB = null;\n for (groupName2 of groupNames) {\n if ((groups[groupName].priority > groups[groupName2].priority) && (indexA < groupNames.indexOf(groupName2)) && (nameA !== groupName2)) {\n nameB = groupName2;\n indexB = groupNames.indexOf(groupName2);\n }\n }\n if (nameB !== null) {\n groupNames[indexA] = nameB;\n }\n if (indexB !== null) {\n groupNames[indexB] = nameA;\n }\n }\n callback(groupNames);\n });\n}",
"function sortExpoAutolinkingAndroidConfig(config) {\n for (const module of config.modules) {\n // Sort the projects by project.name\n module.projects.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);\n }\n return config;\n}",
"function sortGroceries() {\n let categories = Array.from(new Set(groceryList.map((grocery) => grocery.category))).sort();\n let tempgroceryList = [];\n categories.forEach((category) => {\n let currentCategoryItems = groceryList.filter((grocery) => grocery.category == category);\n currentCategoryItems = currentCategoryItems.sort((a, b) => (a.qty > b.qty) ? 1 : ((b.qty > a.qty) ? -1 : 0));\n currentCategoryItems.forEach((item) => {\n tempgroceryList.push(item)\n })\n })\n groceryList = tempgroceryList;\n}",
"static refreshList(sortBy = null) {\n if (typeof sortBy == \"string\") {\n Settings.current.sortBy = sortBy;\n }\n if (this.songListElement) {\n let sortFunc = (a, b) => { return 0; };\n try {\n switch (Settings.current.sortBy) {\n case \"title\":\n sortFunc = (a, b) => {\n if (a.details.title.toLowerCase() > b.details.title.toLowerCase()) {\n return 1;\n }\n if (a.details.title.toLowerCase() < b.details.title.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n case \"length\":\n sortFunc = (a, b) => {\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength > b.details.songLength) {\n return 1;\n }\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength < b.details.songLength) {\n return -1;\n }\n return 0;\n };\n break;\n case \"artist\": // Fall-through\n default:\n sortFunc = (a, b) => {\n if (a.details.artist.toLowerCase() > b.details.artist.toLowerCase()) {\n return 1;\n }\n if (a.details.artist.toLowerCase() < b.details.artist.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n }\n }\n catch (error) {\n }\n var _sort = function (a, b) {\n // Make order reversable\n return sortFunc(a, b);\n };\n SongManager.songList.sort(_sort);\n let nList = SongManager.songList;\n let opened = SongGroup.getAllGroupNames(false);\n opened = [...new Set(opened)];\n SongManager.songListElement.innerHTML = \"\";\n let noGrouping = false;\n // Group Songs\n if (typeof Settings.current.songGrouping == \"number\" && Settings.current.songGrouping > 0 && Settings.current.songGrouping <= 7) {\n let groups = {};\n let addToGroup = function (name, song, missingText = \"No group set\") {\n if (name == null || (typeof name == \"string\" && name.trim() == \"\")) {\n name = missingText;\n }\n if (groups.hasOwnProperty(name)) {\n groups[name].push(song);\n }\n else {\n groups[name] = [song];\n }\n };\n switch (Settings.current.songGrouping) {\n case 1:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist, s, \"[No artist set]\");\n });\n break;\n case 2:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.album, s, \"[No album set]\");\n });\n break;\n case 3:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.source, s, \"[No source set]\");\n });\n break;\n case 4:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.language, s, \"[No language set]\");\n });\n break;\n case 5:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.genre, s, \"[No genre set]\");\n });\n break;\n case 6:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.year, s, \"[No year set]\");\n });\n break;\n case 7:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.customGroup, s, \"[No group set]\");\n });\n break;\n case 8:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist[0].toUpperCase(), s, \"[No artist set]\");\n });\n break;\n case 9:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.title[0].toUpperCase(), s, \"[No title set]\");\n });\n break;\n default:\n noGrouping = true;\n break;\n }\n if (noGrouping == false) {\n for (const key in groups) {\n if (groups.hasOwnProperty(key)) {\n const sg = new SongGroup(key);\n sg.songList = groups[key];\n if (opened.includes(sg.name)) {\n sg.collapsed = false;\n }\n else {\n sg.collapsed = true;\n }\n sg.refreshList();\n }\n }\n }\n }\n // Don't Group Songs\n else {\n noGrouping = true;\n }\n if (noGrouping == true) {\n for (let i = 0; i < nList.length; i++) {\n const song = nList[i];\n song.refreshElement();\n SongManager.songListElement.appendChild(song.element);\n }\n }\n SongManager.search();\n }\n else {\n console.error(\"No div element applied to SongManager.songListElement\", \"SongManager.songListElement is \" + typeof SongManager.songListElement);\n }\n Toxen.resetTray();\n }",
"function getOrderedJsFiles() {\n return gulp.src(paths.js)\n .pipe(plugins.order(paths.jsOrder))\n}",
"function parseCodeDir (data) {\n var files = [], $dom = $(data);\n $dom.find(\"a\").each(function () {\n var url, name, timestamp, $a;\n //$a = $(this).find(\"a\");\n $a = $(this);\n url = $a.attr(\"href\");\n name = $a.html();\n timestamp = new Date($(this).find(\"td:nth-child(4)\").html());\n if (/^.+\\.js$/i.test(name)) {\n files.push({url: url, name: name, timestamp: timestamp});\n }\n });\n files.sort(function (a, b) {\n return (a.timestamp < b.timestamp ? 1 : -1); \n });\n return files;\n }",
"function sortLists() {\n\t\t// Loop all ul, and for each list do initial sort\n\t\tvar ul = $(\".subpageListContainer ul\");\n\t\t$.each(ul, function() {\n\t\t\tsortList($(this), false);\n\t\t});\n\t}",
"function sortLayersByPosition() {\n scope.filtered_layers = filterLayers();\n scope.filtered_layers.sort(function(a, b) {\n return b.layer.get('position') - a.layer.get('position')\n });\n scope.generateLayerTitlesArray();\n }",
"function sortResidentialLayout() {\n $('div.inner_wrapper').each(function() {\n // if element's index is odd then sort\n if($(this).index() % 2 !== 0) {\n\n var content_wrapper = $(this).find('div.residential_content');\n var img_wrapper = $(this).find('div.residential_img');\n\n $(content_wrapper).css('float','right');\n $(img_wrapper).css('float','left');\n }\n });\n }",
"function getPlatformsFolderList() {\n\n function whackItem(theList, key) {\n var idx = theList.indexOf(key);\n if (idx > -1) {\n theList.splice(idx, 1);\n }\n }\n\n //We know the folder exists, so go read the folder's contents\n console.log('Checking platforms folder contents');\n folderList = fs.readdirSync(platformsFolder);\n //Next strip the '.' entry\n whackItem(folderList, '.');\n //and the '..' entry\n whackItem(folderList, '..');\n //finally the platforms.json file\n whackItem(folderList, 'platforms.json');\n //Write the folder list to the screen\n if (debug) {\n listArray('Folders', folderList);\n }\n //return what's left\n return folderList;\n}",
"function sortPacks(a, b) {\n if (a.packSize > b.packSize) {\n return b;\n } else {\n return (b.packSize < a.packSize) ? -1 : 1;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove all children of node from expandedIDs | removeExpandedChildren(expandedIDs, node) {
if ("children" in node) {
for (var i = 0; i < node.children.length; i++) {
var index = expandedIDs.indexOf(node.children[i].id); //get index of child ID
if (index !== -1) { //if child ID is in expandedIDs
expandedIDs.splice(index, 1); //remove child ID from expandedIDs
}
this.removeExpandedChildren(expandedIDs, node.children[i]); //call recursively to remove all descendants
}
}
} | [
"function removeChildren(node) {\n\t\tjQuery(node).empty();\n\t}",
"function expandChildren(node)\n{\n node.children = node._children;\n node._children = null;\n}",
"function delete_all_children() {\n var theRightSide = document.getElementById(\"rightSide\");\n var theLeftSide = document.getElementById(\"leftSide\");\n\n while (theRightSide.firstChild) {\n theRightSide.removeChild(theRightSide.firstChild)\n }\n while (theLeftSide.firstChild) {\n theLeftSide.removeChild(theLeftSide.firstChild)\n }\n}",
"removeAllChildren() {\n this.__childNodes = [];\n this.repeats = [];\n this.dispatchNodeEvent(new NodeEvent('repeated-fields-all-removed', this.repeats, false));\n }",
"function collapseAll(){\n function recurse(node){\n if (node.children) node.children.forEach(recurse); // recurse to bottom of tree\n if (node.children){ // hide children in _children then remove\n node._children = node.children;\n node.children = null;\n } \n }\n\n recurse(root);\n update();\n}",
"function clearChildren() {\n while(board.firstChild) {\n board.removeChild(board.firstChild);\n }\n }",
"function remove_all_children(element,args) {\n //\n while (element.firstChild) {\n element.removeChild(element.firstChild);\n }\n}",
"function removeChildren() {\n plantBox.innerHTML = '';\n}",
"function expandAll(d) {\n root.children.forEach(expand);\n update(root);\n }",
"function removeOrphanedChildren(children, unmountOnly) {\n\tfor (var i = children.length; i--;) {\n\t\tif (children[i]) {\n\t\t\trecollectNodeTree(children[i], unmountOnly);\n\t\t}\n\t}\n}",
"function removecommentsubtree( pid ) {\n\tvar myctrclass = \".descendent-of-\" + pid;\n\n\t$( myctrclass ).each( function () { removecommentsubtree( $(this).attr( \"id\" ) ); } )\n\t\t.remove();\n}",
"function _uncheckChildStates(el) {\n el.prop(\"checked\", false)\n var childrenCheckboxes = el.parent(\".checkbox\").children().find(\".checkbox input\").prop(\"checked\", false)\n }",
"dropEmptyBlocks() {\n Object.keys(this.emptyMap).forEach((parentBlockId) => {\n const node = this.emptyMap[parentBlockId];\n if (node.updateReference !== this.updateReference) {\n node.parent.removeChild(node);\n delete this.emptyMap[parentBlockId];\n }\n });\n }",
"function deleteMenuElelement(id) {\n for (var key in submenu_content) {\n if (submenu_content.hasOwnProperty(key)) {\n if (submenu_content[key].parentId == id) {\n tmpelid = submenu_content[key].elementId;\n delete submenu_content[key];\n deleteMenuElelement(tmpelid);\n }\n }\n }\n }",
"prune(callback) {\n if (_.isArray(this.contents)) {\n const length = this.contents.length;\n\n if ((this.type === \"REPEAT\" && length > 0) || (this.type === \"REPEAT1\" && length > 1)) {\n // Any subtree may be removed\n for (let i = 0; i < length; i++) {\n const tree = _.cloneDeep(this);\n tree.contents.splice(i, 1);\n if (!callback(tree)) {\n return;\n }\n }\n }\n\n for (let i = 0; i < length; i++) {\n let callbackResult = true;\n\n this.contents[i].prune(t => {\n const tree = _.cloneDeep(this);\n tree.contents[i] = t;\n callbackResult = callback(tree);\n return callbackResult;\n });\n\n if (!callbackResult) {\n return;\n }\n }\n }\n }",
"set children(kids) {\n\t this._children = kids.slice(0);\n\t}",
"function collapseChildLayers(id, displayType) {\n var layer = ge.getLayerRoot().getLayerById(id);\n var children = layer.getFeatures().getChildNodes();\n for (var j = 0; j < children.getLength(); j++) {\n var child = children.item(j);\n var childId = child.getId();\n var type = child.getType();\n var name = child.getName();\n var layerStyle = child.getComputedStyle().getListStyle();\n var expandable = layerStyle.getListItemType();\n if (type == 'KmlFolder' && expandable == 1) {\n collapseExpandLayers(childId, displayType);\n }\n }\n}",
"function toggleChildrenVisibility() {\n toggleVisibility($(this));\n const children = $(this).children();\n children.each(function () {\n toggleVisibility($(this), 1);\n });\n }",
"function tree_collapse() {\n let $allPanels = $('.nested').hide();\n let $elements = $('.treeview-animated-element');\n\n $('.closed').click(function () {\n \n $this = $(this);\n $target = $this.siblings('.nested');\n $pointer = $this.children('.fa-angle-right');\n\n $this.toggleClass('open')\n $pointer.toggleClass('down');\n\n !$target.hasClass('active') ? $target.addClass('active').slideDown() : \n $target.removeClass('active').slideUp();\n \n return false;\n });\n\n $elements.click(function () {\n \n $this = $(this);\n \n if ($this.hasClass('opened')) {\n ($this.removeClass('opened'));\n } else {\n ($elements.removeClass('opened'), $this.addClass('opened'));\n }\n\n })\n }",
"function i2uiCollapsePadTree(tablename, depth)\r\n{\r\n var column = 0;\r\n\r\n //i2uitrace(1,\"collapsepadtree depth=\"+depth);\r\n\r\n var table;\r\n var savemasterscrolltop;\r\n var saveslavescrolltop;\r\n\r\n //i2uitrace(1,\"tablename=[\"+tablename+\"]\");\r\n\r\n table = document.getElementById(tablename+\"_data\");\r\n if (table == null)\r\n {\r\n table = document.getElementById(tablename);\r\n }\r\n\r\n //i2uitrace(1,\"table=[\"+table+\"]\");\r\n\r\n if (table != null &&\r\n table.rows != null)\r\n {\r\n var len = table.rows.length;\r\n var rowdepth;\r\n var img;\r\n var cellname;\r\n var childkey;\r\n var childnode;\r\n //i2uitrace(1,\"#rows=\"+len);\r\n for (var i=0; i<len; i++)\r\n {\r\n rowdepth = table.rows[i].cells[column].id.split(\"_\").length - 2;\r\n //i2uitrace(1,\"rowdepth=\"+rowdepth);\r\n if (rowdepth <0)\r\n continue;\r\n\r\n cellname = table.rows[i].cells[column].id.substr(9);\r\n //i2uitrace(1,\"id=\"+table.rows[i].cells[column].id+\" cellname=\"+cellname);\r\n\r\n childkey = \"TREECELLIMAGE_\"+tablename+\"_\"+cellname + \"_1\";\r\n childnode = document.getElementById(childkey);\r\n //i2uitrace(1,\"childnode=\"+childnode+\" key=\"+childkey);\r\n\r\n img = document.getElementById(\"TREECELLIMAGE_\"+tablename+\"_\"+cellname);\r\n\r\n if (rowdepth == depth)\r\n {\r\n //i2uitrace(1,\"COLLAPSE ME id=\"+table.rows[i].cells[column].id);\r\n if (img != null)\r\n {\r\n // test for children\r\n if (childnode == null)\r\n {\r\n if (img.src.indexOf(\"plus_loadondemand.gif\") == -1)\r\n img.src = i2uiImageDirectory+\"/tree_bullet.gif\";\r\n }\r\n else\r\n {\r\n img.src = i2uiImageDirectory+\"/plus_norgie.gif\";\r\n }\r\n }\r\n table.rows[i].style.display = \"\";\r\n }\r\n else\r\n {\r\n if (rowdepth > depth)\r\n {\r\n // test for children\r\n if (childnode == null)\r\n {\r\n if (img != null)\r\n {\r\n if (img.src.indexOf(\"plus_loadondemand.gif\") == -1)\r\n img.src = i2uiImageDirectory+\"/tree_bullet.gif\";\r\n }\r\n }\r\n //i2uitrace(1,\"HIDE ME id=\"+table.rows[i].cells[column].id);\r\n table.rows[i].style.display = \"none\";\r\n }\r\n else\r\n {\r\n // test for children\r\n if (childnode == null)\r\n {\r\n if (img != null)\r\n {\r\n if (img.src.indexOf(\"plus_loadondemand.gif\") == -1)\r\n img.src = i2uiImageDirectory+\"/tree_bullet.gif\";\r\n }\r\n }\r\n else\r\n {\r\n if (img != null)\r\n {\r\n img.src = i2uiImageDirectory+\"/minus_norgie.gif\";\r\n }\r\n }\r\n //i2uitrace(1,\"EXPAND ME id=\"+table.rows[i].cells[column].id);\r\n table.rows[i].style.display = \"\";\r\n }\r\n }\r\n }\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grabs image from form and formats for meme | function graphic(){
let memeImage = document.createElement("img");
memeImage.className = "memeImage";
memeImage.src = image.value;
return memeImage;
} | [
"function get_img(i,f){var b,a=__CONF__.img_url+\"/img_new/{0}--{1}-{2}-1\",g=__CONF__.img_url+\"/img_src/{0}\",c=\"d96a3fdeaf68d3e8db170ad5\",d=\"43e2e6f41e3b3ebe22aa6560\",k=\"726a17bd880cff1fb375718c\",j=\"6ea1ff46aab3a42c975dd7ab\";i=i||\"0\";f=f||{};ObjectH.mix(f,{type:\"head\",w:30,h:30,sex:1});if(i!=\"0\"){if(f.type==\"src\"){b=g.format(i);}else{b=a.format(i,f.w,f.h);}}else{if(f.type==\"head\"){if(f.sex==1){b=a.format(c,f.w,f.h);}else{b=a.format(d,f.w,f.h);}}else{if(f.type==\"subject\"){b=a.format(k,f.w,f.h);}else{if(f.type==\"place\"){b=a.format(j,f.w,f.h);}else{b=a.format(\"0\",f.w,f.h);}}}}return b;}",
"function Enter_image(input) {\n if (input.files && input.files[0]) {\n var reader = new FileReader();\n\n reader.onload = function (e) {\n\t\t\tvar nextEI=$(input).next('.enter_image');\n nextEI.attr('src', e.target.result);\n\t\t\tnextEI.attr('width','50px');\n\t\t\tnextEI.attr('height','50px');\n }\n\n reader.readAsDataURL(input.files[0]);\n }\n}",
"function getImage(){\n\tvar radioButtons = document.getElementsByName(\"meme-select\");\n\tfor(var i = 0; i < radioButtons.length; i++){\n\t\tif(radioButtons[i].checked){\n\t\t\tdocument.getElementById(\"image\").src = radioButtons[i].value;\n\t\t}\n\t}\n}",
"function correctImageUrl(event)\n{\n event.stopPropagation();\n let form = this.form;\n let imageLine = document.getElementById(\"ImageButton\");\n let imageUrl = '';\n let nextSibling;\n for(var child = imageLine.firstChild;\n child;\n child = nextSibling)\n {\n if (child.nodeType == 1 &&\n child.nodeName == 'INPUT' &&\n child.name == 'Image')\n { // <input name='Image' ...\n imageUrl = child.value;\n } // <input name='Image' ...\n nextSibling = child.nextSibling;\n imageLine.removeChild(child);\n } // loop through children of imageLine\n\n // create new label and <input type='text'>\n imageLine.appendChild(\n document.createTextNode(\"Enter URL of Census Image:\"));\n let inputTag = document.createElement(\"INPUT\");\n inputTag.type = 'text';\n inputTag.size = '64';\n inputTag.maxlength = '128';\n inputTag.name = 'Image';\n inputTag.value = imageUrl;\n inputTag.className = 'black white leftnc';\n imageLine.appendChild(inputTag);\n}",
"function handleImage(e) {\n var reader = new FileReader();\n reader.onload = function (event) {\n var img = new Image();\n img.onload = function () {\n //Update the canvas when the image file is loaded\n var topText = document.getElementById(\"topText\").value;\n var bottomText = document.getElementById(\"bottomText\").value;\n var fontSize = document.getElementById(\"fontSize\").value;\n var fontFamily = document.getElementById(\"fontFamily\").value;\n showCanvas(topText, bottomText, img, fontSize, fontFamily);\n }\n\n //Set the img element's source to be the image the user chose\n img.src = event.target.result;\n document.getElementById(\"img1\").src = img.src;\n }\n\n //Read the image file as a URL string\n reader.readAsDataURL(e.target.files[0]);\n}",
"function loadImg(img, target_name) {\n if (img.files && img.files[0]) {\n var FR = new FileReader();\n FR.onload = function (e) {\n //e.target.result = base64 format picture\n $('#' + target_name + '_preview').attr(\"src\", e.target.result);\n $('#' + target_name + '_input').val(e.target.result);\n };\n FR.readAsDataURL(img.files[0]);\n }\n}",
"function promptImageAttrs(pm, callback, nodeType) {\n\t var _pm$selection = pm.selection;\n\t var node = _pm$selection.node;\n\t var from = _pm$selection.from;\n\t var to = _pm$selection.to;var attrs = nodeType && node && node.type == nodeType && node.attrs;\n\t new FieldPrompt(pm, \"Insert image\", {\n\t src: new TextField({ label: \"Location\", required: true, value: attrs && attrs.src }),\n\t title: new TextField({ label: \"Title\", value: attrs && attrs.title }),\n\t alt: new TextField({ label: \"Description\",\n\t value: attrs ? attrs.title : pm.doc.textBetween(from, to, \" \") })\n\t }).open(callback);\n\t}",
"function imageUploaded(error, result) {\n $('#recipe-upload-image').prop(\"src\", result[0].secure_url);\n $('#image_upload_url').val(result[0].secure_url);\n}",
"function getFormImg(id, append, page){\n\n // Form data JS Object\n var myFormData = new FormData();\n myFormData.append( '_token', $('meta[name=\"csrf-token\"]').attr('content'));\n myFormData.append('page', page);\n\n $.ajax({\n\n url: '/form/' + id,\n type: \"POST\",\n contentType: false,\n processData: false,\n data: myFormData,\n success: function(data){\n\n // Insert rendering page\n append.html(data);\n\n console.log(\"log di data \",data);\n },\n\n error: function(error){\n console.log(\"error\",error);\n }\n });\n\n }",
"function ciniki_writingcatalog_images() {\n this.webFlags = {\n '1':{'name':'Visible'},\n };\n this.init = function() {\n //\n // The panel to display the edit form\n //\n this.edit = new M.panel('Edit Image',\n 'ciniki_writingcatalog_images', 'edit',\n 'mc', 'medium', 'sectioned', 'ciniki.writingcatalog.images.edit');\n this.edit.default_data = {};\n this.edit.data = {};\n this.edit.writingcatalog_id = 0;\n this.edit.sections = {\n '_image':{'label':'Image', 'type':'imageform', 'fields':{\n 'image_id':{'label':'', 'type':'image_id', 'hidelabel':'yes', 'controls':'all', 'history':'no'},\n }},\n 'info':{'label':'Information', 'type':'simpleform', 'fields':{\n 'name':{'label':'Title', 'type':'text', },\n// 'webflags':{'label':'Website', 'type':'flags', 'join':'yes', 'flags':this.webFlags},\n }},\n '_website':{'label':'Website Information', 'fields':{\n 'webflags_1':{'label':'Visible', 'type':'flagtoggle', 'field':'webflags', 'bit':0x01, 'default':'on'},\n }},\n '_description':{'label':'Description', 'type':'simpleform', 'fields':{\n 'description':{'label':'', 'type':'textarea', 'size':'medium', 'hidelabel':'yes'},\n }},\n '_buttons':{'label':'', 'buttons':{\n 'save':{'label':'Save', 'fn':'M.ciniki_writingcatalog_images.saveImage();'},\n 'delete':{'label':'Delete', 'visible':'no', 'fn':'M.ciniki_writingcatalog_images.deleteImage();'},\n }},\n };\n this.edit.fieldValue = function(s, i, d) { \n if( this.data[i] != null ) {\n return this.data[i]; \n } \n return ''; \n };\n this.edit.fieldHistoryArgs = function(s, i) {\n return {'method':'ciniki.writingcatalog.imageHistory',\n 'args':{'tnid':M.curTenantID, \n 'writingcatalog_image_id':M.ciniki_writingcatalog_images.edit.writingcatalog_image_id, 'field':i}};\n };\n this.edit.addDropImage = function(iid) {\n M.ciniki_writingcatalog_images.edit.setFieldValue('image_id', iid, null, null);\n return true;\n };\n this.edit.sectionGuidedTitle = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gtitle-edit'];\n } else {\n return this.sections[s]['gtitle-add'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gtitle != null ) { return this.sections[s].gtitle; }\n return null;\n };\n this.edit.sectionGuidedText = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gtext-edit'];\n } else {\n return this.sections[s]['gtext-add'];\n }\n }\n if( s == '_buttons' ) {\n if( this.sections[s].buttons.delete.visible == 'yes' ) {\n return this.sections[s]['gtext-edit'];\n } else {\n return this.sections[s]['gtext-add'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gtext != null ) { return this.sections[s].gtext; }\n return null;\n };\n this.edit.sectionGuidedMore = function(s) {\n if( s == '_image' ) {\n if( this.data.image_id != null && this.data.image_id > 0 ) {\n return this.sections[s]['gmore-edit'];\n } else {\n return this.sections[s]['gmore-add'];\n }\n }\n if( s == '_buttons' ) {\n if( this.sections[s].buttons.delete.visible == 'yes' ) {\n return this.sections[s]['gmore-edit'];\n }\n }\n if( this.sections[s] != null && this.sections[s].gmore != null ) { return this.sections[s].gmore; }\n return null;\n };\n this.edit.addButton('save', 'Save', 'M.ciniki_writingcatalog_images.saveImage();');\n this.edit.addClose('Cancel');\n };\n\n this.start = function(cb, appPrefix, aG) {\n args = {};\n if( aG != null ) { args = eval(aG); }\n\n //\n // Create container\n //\n var appContainer = M.createContainer(appPrefix, 'ciniki_writingcatalog_images', 'yes');\n if( appContainer == null ) {\n M.alert('App Error');\n return false;\n }\n\n if( args.add != null && args.add == 'yes' ) {\n this.showEdit(cb, 0, args.writingcatalog_id);\n } else if( args.writingcatalog_image_id != null && args.writingcatalog_image_id > 0 ) {\n this.showEdit(cb, args.writingcatalog_image_id);\n }\n return false;\n }\n\n this.showEdit = function(cb, iid, eid) {\n if( iid != null ) { this.edit.writingcatalog_image_id = iid; }\n if( eid != null ) { this.edit.writingcatalog_id = eid; }\n this.edit.reset();\n if( this.edit.writingcatalog_image_id > 0 ) {\n this.edit.sections._buttons.buttons.delete.visible = 'yes';\n var rsp = M.api.getJSONCb('ciniki.writingcatalog.imageGet', \n {'tnid':M.curTenantID, 'writingcatalog_image_id':this.edit.writingcatalog_image_id}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n M.ciniki_writingcatalog_images.edit.data = rsp.image;\n M.ciniki_writingcatalog_images.edit.refresh();\n M.ciniki_writingcatalog_images.edit.show(cb);\n });\n } else {\n this.edit.data = {};\n this.edit.sections._buttons.buttons.delete.visible = 'no';\n this.edit.refresh();\n this.edit.show(cb);\n }\n };\n\n this.saveImage = function() {\n if( this.edit.writingcatalog_image_id > 0 ) {\n var c = this.edit.serializeFormData('no');\n if( c != '' ) {\n var rsp = M.api.postJSONFormData('ciniki.writingcatalog.imageUpdate', \n {'tnid':M.curTenantID, \n 'writingcatalog_image_id':this.edit.writingcatalog_image_id}, c,\n function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n } else {\n M.ciniki_writingcatalog_images.edit.close();\n }\n });\n } else {\n this.edit.close();\n }\n } else {\n var c = this.edit.serializeFormData('yes');\n var rsp = M.api.postJSONFormData('ciniki.writingcatalog.imageAdd', \n {'tnid':M.curTenantID, 'writingcatalog_id':this.edit.writingcatalog_id}, c,\n function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n } else {\n M.ciniki_writingcatalog_images.edit.close();\n }\n });\n }\n };\n\n this.deleteImage = function() {\n M.confirm('Are you sure you want to delete this image?',null,function() {\n var rsp = M.api.getJSONCb('ciniki.writingcatalog.imageDelete', {'tnid':M.curTenantID, \n 'writingcatalog_image_id':M.ciniki_writingcatalog_images.edit.writingcatalog_image_id}, function(rsp) {\n if( rsp.stat != 'ok' ) {\n M.api.err(rsp);\n return false;\n }\n M.ciniki_writingcatalog_images.edit.close();\n });\n });\n };\n}",
"displayAvatar( message ){\n let allowedImageFileTypes = [ '.png', '.jpeg', '.jpg', '.gif' ];\n let accountWithAvatar;\n\n for( let account of this.accounts ){\n if( account.usernick === message.usernick ){\n accountWithAvatar = account.avatar;\n }\n }\n if( accountWithAvatar != null ){\n for( let type of allowedImageFileTypes ){\n if( accountWithAvatar.toLowerCase().includes( type ) ){\n return accountWithAvatar;\n }\n }\n }\n return 'http://158.174.120.227/CatchUp/avatar01.png';\n }",
"function parseDataModelFromForm(form) {\n var data = {};\n\n // Add item id in the data to pass to save method\n data[config.fieldId] = $(form).find(\"#\" + createIdName(config.fieldId)).val();\n\n $.each(config.fields, function (index, field) {\n if (field.type != FieldType.IMAGE) {\n\t data[field.name] = $(form).find(\"#\" + createIdName(field.name)).val();\n }\n });\n\n return data;\n }",
"function processImageToString(image) {\n\treturn image.toString();\n}",
"function processImage(image_id){\n // Code to Resize the selected image to MobileNet Input Size\n const img = new Image();\n img.crossOrigin = \"anonymous\";\n img.src = document.getElementById(image_id).src;\n img.width = 224;\n img.height = 224;\n return img;\n}",
"function trySaveOptionalImage() {\n //if data is given\n if (preparedArticle.field_image.base64) {\n var imgData = preparedArticle.field_image.base64;\n delete preparedArticle.field_image.base64;\n\n var newImage = {};\n\n newImage.file = imgData;\n newImage.filename = \"drupal.jpg\";\n newImage.filesize = newImage.file.length;\n newImage.filepath = \"field/image/\";\n (newImage.filemime = \"image/jpeg\"),\n (newImage.image_file_name = \"drupal.jpg\");\n\n return FileResource.create(newImage);\n }\n\n //else fail\n return $q.reject(false);\n }",
"function afiCreateImage( $imageContainer, $deleteImage, $uploadImage, json, inputField){\n\t\t$imageContainer.append( '<img src=\"' + json.url + '\" alt=\"' + json.caption + '\" style=\"max-width: 100%;\" />' );\n\t\tinputField.val( json.url );\n\t\t$deleteImage.removeClass( 'hidden' );\n\t\t$uploadImage.addClass( 'hidden' );\n\t}",
"function getModelImage(model,biggie,ac){\n\tvar imageObj = new Image();\n\tvar retImgObj = function (){\n\t\tif(model.match(/asr1/gi) != null || model.match(/isr/gi) != null || model.match(/ios/gi) != null || model.match(/sword/gi) != null || model.match(/dagger/gi) != null || model.match(/utah/gi) != null || model.match(/junos/gi) != null || model.match(/ciscoxe/gi) != null) {\n\t\t\tif(biggie){\n\t\t\t\timageObj.src = dir+\"/img/model_icons/150px/qfp_bfcommit_150px.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/qfp_afcommit_62px.png\";\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/qfp_bfcommit_62px.png\";\n\t\t\t\t}\n\t\t\t}\n\n\t\t}else if(model.match(/asr9/gi) != null || model.match(/ciscoasr/gi) != null || model.match(/ciscoxr/gi) != null ){\n\t\t\tif(biggie){\n imageObj.src = dir+\"/img/model_icons/150px/juniper_150px.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n imageObj.src = dir+\"/img/model_icons/62px/juniper_green_62px.png\";\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/juniper_62px.png\";\n\t\t\t\t}\n\t\t\t}\n\t\t}else if(model.match(/124/gi) != null || model.match(/1200/gi) != null || model.match(/128/gi) != null || model.match(/ciscogsr/gi) != null ){\n\t\t\tif(biggie){\n imageObj.src = dir+\"/img/model_icons/150px/GSR_Vivid-150px.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n imageObj.src = dir+\"/img/model_icons/62px/gsr_cisco_green-62px.png\"\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/GSR_Vivid-62px.png\";\n\t\t\t\t}\n\t\t\t}\n\t\t}else if(model.match(/65/gi) != null){\n\t\t\tif(biggie){\n imageObj.src = dir+\"/img/model_icons/150px/6500catalyst_150px_bfcommit.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n imageObj.src = dir+\"/img/model_icons/62px/6500catalyst_62px_afcommit.png\";\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/6500catalyst_62px_bfcommit.png\";\n\t\t\t\t}\n\t\t\t}\n\t }else if(model.match(/760/gi) != null){\n\t\t\tif(biggie){\n imageObj.src = dir+\"/img/model_icons/150px/7600_bfcommit_150px.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n imageObj.src = dir+\"/img/model_icons/62px/7600_afcommit_62px.png\";\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/7600_bfcommit_62px.png\";\n\t\t\t\t}\n\t\t\t}\n\t }else if(model.match(/ix/gi) != null || model.match(/olm/gi) != null || model ==\"3500\" || model.match(/anue/gi) != null || model.match(/breaking/gi) != null || model.match(/xm/gi) != null || model.match(/lsm/gi) != null ){\n\t\t\tif(biggie){\n imageObj.src = dir+\"/img/model_icons/150px/ixia_blue_150px.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n imageObj.src = dir+\"/img/model_icons/62px/ixia_black_62px.png\";\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/ixia_blue_62px.png\";\n\t\t\t\t}\n\t\t\t}\n\t }else if(model.toLowerCase() == 'none'){\n\t\t\timageObj.src = dir+\"/img/model_icons/server_linux.png\";\n\t\t}else if(model.toLowerCase() == 'n/a'){\n\t\t\timageObj.src = dir+\"/img/model_icons/server_linux.png\";\n\t\t}else if(model.toLowerCase() == 'ubuntu'){\n\t\t\timageObj.src = dir+\"/img/model_icons/server_linux.png\";\n\t\t}else if(model.toLowerCase() == 'centos'){\n\t\t\timageObj.src = dir+\"/img/model_icons/server_centOS_62px.png\";\n\t\t}else if(model.toLowerCase() == 'vm ware'){\n\t\t\timageObj.src = dir+\"/img/model_icons/server_linux.png\";\n\t\t}else{\n\t\t\tif(biggie){\n imageObj.src = dir+\"/img/model_icons/150px/cisco_vivid_blue-150px.png\";\n\t\t\t}else{\n\t\t\t\tif(ac){\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/62px/cisco_vivid_62px.png\";\n\t\t\t\t}else{\n\t\t\t\t\timageObj.src = dir+\"/img/model_icons/cisco_vivid_blue_55.png\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn imageObj;\n\t}\n\treturn retImgObj();\n}",
"function generateUploadifyHtml(name, img_url, deleted_url, type)\n{\n deleted_url += \"?type=\" + type + \"&img=\" + name;\n html = '<div class=\"pointer-mouse\" style=\";float:left;margin-right:5px;margin-top:5px;\">';\n html += '<div class=\"img_hover\">';\n html += '<img src=\"' + img_url + name + '\" style=\"width:100px;height:100px\" onclick=\"dozoomer(this)\" />';\n html += '</div>';\n html += '<input type=\"hidden\" name=\"uploaded_image[]\" value=\"' + name + '\" />';\n html += '<input type=\"text\" name=\"image_title[]\" value=\"Title\" />';\n html += '<input class=\"image_radio\" type=\"radio\" name=\"model_image\" value=\"' + name + '\" title=\"Primary image\" alt=\"Primary image\" />';\n html += '<div class=\"clear\"></div>';\n html += '<a href=\"#deltetimage\" onclick=\"deletetimage(this)\">Delete</a>';\n html += '<input type=\"hidden\" name=\"href_path\" value=\"' + deleted_url + '\" />';\n html += '</div>';\n\n return html;\n}",
"_previewImageByPath()\n\t{\n\t\tlet imagePath = $(\"textarea#page_content_value\").val();\n\t\tlet mediaDetailRoute = Routing.generate('reaccion_cms_admin_media_detail_by_path');\n\n\t\t$(\"div#selected_image_preview\").removeClass(\"d-none\");\n\n\t\t// load media data\n\t\t$.post(mediaDetailRoute, { 'path' : imagePath }, function(response)\n\t\t{\n\t\t\t// create and dispatch event\n\t\t\tvar event = new CustomEvent(\n\t\t\t\t\t\t\t\t'selectedItemFromMediaGallery', \n\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\t'detail' : {\n\t\t\t\t\t\t\t\t\t\t'image' : response\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\n\t\t\tdocument.dispatchEvent(event);\n\n\t\t\t// check media option for current image in the image preview component\n\t\t\tfor(var key in response)\n\t\t\t{\n\t\t\t\tif(imagePath == response[key]) \n\t\t\t\t{\n\t\t\t\t\t$('input[data-path-key=\"' + key + '\"]').attr('checked', 'checked');\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// hide loader\n\t\t\t$(\"div#selected_image_preview div.dimmer\").removeClass(\"active\");\n\t\t}, \n\t\t\"json\");\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A filter to invert the colors in the image | invertFilter() {
let canvasID = `canvasID:${this.state.canvasID}`;
let c = document.getElementById(canvasID);
let ctx = c.getContext("2d");
let imgData = ctx.getImageData(0, 0, c.width, c.height);
// invert colors
var i;
for (i = 0; i < imgData.data.length; i += 4) {
imgData.data[i] = 255 - imgData.data[i];
imgData.data[i + 1] = 255 - imgData.data[i + 1];
imgData.data[i + 2] = 255 - imgData.data[i + 2];
imgData.data[i + 3] = 255;
}
ctx.putImageData(imgData, 0, 0);
} | [
"function invertColours()\n{\n\t'use strict';\n\t\n\t// Get the canvas, context, and image data\n\tvar canvas = document.getElementById(\"canvas\");\n\tvar context = canvas.getContext(\"2d\");\n\tvar imgData = context.getImageData(0, 0, canvas.width, canvas.height);\n\t\n\t// Loop to modify the colours in the image data array\n\tfor(var i = 0; i < imgData.data.length; i += 4)\n\t{\n\t\timgData.data[i] = 255 - imgData.data[i];\t\t// Invert red colour\n\t\timgData.data[i + 1] = 255 - imgData.data[i + 1];\t// Invert green colour\n\t\timgData.data[i + 2] = 255 - imgData.data[i + 2];\t// Invert blue colour\n\t}\n\t\n\t// Put modified image data array back to canvas\n\tcontext.putImageData(imgData, 0, 0);\n}",
"function colorInvert(rgb) {\n\treturn rgb.map(x => 255 - x);\n}",
"invert() {\n for (let i = 0; i < this._data.length; i++) {\n this._data[i] = ~this._data[i];\n }\n }",
"function invertColor(hexColor) {\r\n var color = hexColor;\r\n color = color.substring(1); // remove #\r\n color = parseInt(color, 16); // convert to integer\r\n color = 0xFFFFFF ^ color; // invert three bytes\r\n color = color.toString(16); // convert to hex\r\n color = (\"000000\" + color).slice(-6); // pad with leading zeros\r\n color = \"#\" + color; // prepend #\r\n return color;\r\n}",
"function contrastFilter ( sourceImageData){\n //calculate contrast factor\n var contrastFactor = (259 * (contrastValue + 255))/(255 * (259 - contrastValue));\n\n //update pixel value\n for(var i=0; i< sourceImageData.data.length; i+=4){\n for(var x=0; x<3; x++){\n sourceImageData.data[i+x] = setNewColor(contrastFactor * ( sourceImageData.data[i+x] - 128) + 128); \n }\n }\n\n return sourceImageData;\n}",
"function reverseImage(image) {\n\tfor (let i = 0; i < image.length; i++) {\n\t\tfor (let j = 0; j < image[i].length; j++) {\n\t\t\timage[i][j] = 1 - image[i][j];\n\t\t}\n\t}\n\treturn image;\n}",
"function brightnessFilter ( sourceImageData){\n //build imageData\n var returnImageData = ctx.createImageData(canvas.width, canvas.height);\n var imageDataArray = returnImageData.data;\n for(var i=0; i < sourceImageData.data.length; i+=4){\n imageDataArray[i] = setNewColor(sourceImageData.data[i] + brightnessValue);\n imageDataArray[i+1] = setNewColor(sourceImageData.data[i+1] + brightnessValue);\n imageDataArray[i+2] = setNewColor(sourceImageData.data[i+2] + brightnessValue);\n imageDataArray[i+3] = sourceImageData.data[i+3];\n }\n\n returnImageData.data = imageDataArray;\n\n return returnImageData;\n \n}",
"invert(){\n let out = new matrix4();\n for(var column = 0; column < 4; column++){\n for(var row = 0; row < 4; row++){\n out.matArray[column][row] = -this.matArray[column][row];\n }\n }\n return out;\n }",
"function doFilter() {\n var output;\n var imageEl = document.getElementById('sourceimg');\n\n var tmpcanvas = document.createElement('canvas');\n tmpcanvas.width = 100;\n tmpcanvas.height = 100;\n \n var tmpctx = tmpcanvas.getContext('2d');\n tmpctx.drawImage(imageEl, 0, 0, 100, 100);\n\n var imageData = tmpctx.getImageData(0, 0, 100, 100);\n\n var intensity = parseFloat(document.getElementById('intensity').value);\n\n switch(this.id) {\n case 'saturate':\n output = saturate(intensity, imageData);\n break;\n case 'brighten':\n output = brighten(intensity, imageData);\n break;\n case 'default':\n console.log('No such filter: '+this.id);\n }\n\n ctx.putImageData(output, 0, 0);\n}",
"function rangedGrayScaleOFF(){\n var rangedHero = document.getElementsByClassName(\"ranged\");\n for (var i = 0; i < rangedHero.length; i++) {\n rangedHero[i].style.filter = \"grayscale(0%)\";\n }\n}",
"getInvertLightness() {\n return this._invertLightness;\n }",
"function meleeGrayScaleOFF(){\n var meleeHero = document.getElementsByClassName(\"melee\");\n for (var i = 0; i < meleeHero.length; i++) {\n meleeHero[i].style.filter = \"grayscale(0%)\";\n }\n}",
"function rgbToCmy(n) {\n return Math.round((rgbInvert(n) / 255) * 100);\n}",
"setInvertLightness(invertFlag) {\n this._inverse.set_enabled(invertFlag);\n }",
"getAverageImageColor(image) {\n let ctx = document.createElement('canvas').getContext('2d');\n\n ctx.canvas.width = CANVAS_WIDTH;\n ctx.canvas.height = CANVAS_WIDTH * image.height/image.width;\n\n // ctx.canvas.height = ctx.canvas.width * (image.height/image.width);\n ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);\n\n let data = ctx.getImageData(0,0,ctx.canvas.width,ctx.canvas.height),\n color = [0,0,0],\n hex = \"\",\n contrast = 0;\n\n for (let i = 0; i <= data.data.length - 1; i+=4) {\n if (data.data[i+3] != 1) {\n color[0] += data.data[i];\n color[1] += data.data[i+1];\n color[2] += data.data[i+2];\n }\n }\n\n color[0] = Math.round(color[0] / ((data.data.length - 1)/4)) * 2;\n color[1] = Math.round(color[1] / ((data.data.length - 1)/4)) * 2;\n color[2] = Math.round(color[2] / ((data.data.length - 1)/4)) * 2;\n\n let coloring = color.map((colors) => {\n if (colors > 255) return 255;\n return colors;\n });\n\n hex = this.rgbToHex(coloring[0],coloring[1],coloring[2]);\n this.GraphCore.App.Project.settings.startColor = hex;\n\n return hex;\n }",
"function gray(enc, number) {\n if (enc) return number ^ (number >> 1);\n\n let decodedNumber = number;\n\n while (number !== 1) {\n number = number >> 1;\n decodedNumber = decodedNumber ^ number;\n }\n\n return decodedNumber;\n}",
"function makeRed() {\n if (imageisloaded(image3)) {\n filterRed(image3);\n }\n image3.drawTo(canvas);\n}",
"function white2transparentImageData(imageData){\n var pixel = imageData.data;\n var r=0, g=1, b=2,a=3;\n for (var p = 0; p<pixel.length; p+=4)\n {\n if ((pixel[p+r] > 245) & (pixel[p+g]) > 245 & (pixel[p+b] > 245)){ // if white then change alpha to 0\n pixel[p+a] = 0;\n }\n if (pixel[p] != 0){\n }\n // if ((pixel[p+r] < 5) & (pixel[p+g]) < 5 & (pixel[p+b] < 5)){ // if white then change alpha to 0\n // pixel[p+a] = 0;\n // }\n }\n imageData.data = pixel;\n return imageData;\n}",
"setInvertLightness(flag) {\n this._invertLightness = flag;\n if (this._magShaderEffects)\n this._magShaderEffects.setInvertLightness(this._invertLightness);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for set the properties of theme object into styles. | function setTheme(themValueObj) {
for (const key in themValueObj) {
document.documentElement.style.setProperty(`--${key}`, themValueObj[key]);
}
} | [
"function updateStyle() {\r\n\tif (settings.darkThemeSettings) {\r\n\t\t//dark theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#0F0F0F\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#a53737\");\r\n\t} else {\r\n\t\t//light theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#000000\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#f55555\");\r\n\t}\r\n}",
"function setupTheme() {\n var theme = interactive.theme;\n\n if (arrays[\"a\" /* default */].isArray(theme)) {\n // [\"a\", \"b\"] => \"lab-theme-a lab-theme-b\"\n theme = theme.map(function (el) {\n return 'lab-theme-' + el;\n }).join(' ');\n } else if (theme) {\n theme = 'lab-theme-' + theme;\n } else {\n theme = '';\n }\n\n $interactiveContainer.alterClass('lab-theme-*', theme);\n }",
"_initStyles() {\n const styles = this.constructor.styles !== undefined ? this.constructor.styles : this.styles();\n if (!styles) { return }\n this.styleSheet = new ScreenStyle(styles, this.id);\n }",
"updateStyles(properties = {}) {\n console.warn(\n `WARNING: Since Vaadin 23, updateStyles() is deprecated. Use the native element.style.setProperty API to set custom CSS property values.`\n );\n\n Object.entries(properties).forEach(([key, value]) => {\n this.style.setProperty(key, value);\n });\n\n this._updateLayout();\n }",
"injectTheme(themeId){\n //helper function to clone a style\n function cloneStyle(style) {\n var s = document.createElement('style');\n s.id = style.id;\n s.textContent = style.textContent;\n return s;\n }\n\n var n = document.querySelector(themeId);\n this.shadowRoot.appendChild(cloneStyle(n));\n }",
"function setCSS(styles, elements) {\n if (elements.length > 1) {\n for (var i = 0; i < elements.length; i++) {\n Object.assign(elements[i].style, styles);\n }\n } else {\n Object.assign(elements.style, styles);\n }\n} // Set CSS before elements appear",
"function setHtmlObjectsProperties(){\n\t\t \t\n\t\t\t//set size\t\t\n\t\t var objCss = {\n\t\t\t\t \"max-width\":g_options.gallery_width+\"px\",\n\t\t\t\t\t\"min-width\":g_options.gallery_min_width+\"px\",\n\t\t\t\t\t\"height\":g_options.gallery_height+\"px\"\n\t\t\t};\n\t\t \n\t\t //set background color\n\t\t if(g_options.gallery_background_color)\n\t\t\t objCss[\"background-color\"] = g_options.gallery_background_color;\n\t\t \n\t\t g_objWrapper.css(objCss);\t\t \t\t \n\t}",
"reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }",
"_onThemeChanged() {\n this._changeStylesheet();\n if (!this._disableRedisplay)\n this._updateAppearancePreferences();\n }",
"async addTheme(){\n //If there is no page styling already\n if(!document.querySelector('.eggy-theme') && this.options.styles){\n //Create the style tag\n let styles = document.createElement('style');\n //Add a class\n styles.classList.add('eggy-theme');\n //Populate it\n styles.innerHTML = '{{CSS_THEME}}';\n //Add to the head\n document.querySelector('head').appendChild(styles);\n }\n //Resolve\n return;\n }",
"function updateThemeWithAppSkinInfo(appSkinInfo) {\n // console.log(appSkinInfo)\n var panelBgColor = appSkinInfo.panelBackgroundColor.color;\n var bgdColor = toHex(panelBgColor);\n var fontColor = \"F0F0F0\";\n if (panelBgColor.red > 122) {\n fontColor = \"000000\";\n }\n \n var styleId = \"hostStyle\";\n addRule(styleId, \"body\", \"background-color:\" + \"#\" + bgdColor);\n addRule(styleId, \"body\", \"color:\" + \"#\" + fontColor);\n \n var isLight = appSkinInfo.panelBackgroundColor.color.red >= 127;\n if (isLight) {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-light.css\");\n } else {\n $(\"#theme\").attr(\"href\", \"css/topcoat-desktop-dark.css\");\n }\n }",
"function splNvslApplyDynamicStyles() {\n var styles = splNvslConfig.styleSheet;\n\n $('.spl-nvsl-tab').css(styles.nvslTab);\n $('.spl-nvsl-tab a').css(styles.nvslTabAnchor);\n $('.spl-nvsl-tab a').hover(function() {\n $(this).css(styles.nvslTabAnchorHover);\n }, function() {\n $(this).css(styles.nvslTabAnchor);\n });\n\n $('.spl-nvsl-tab-active').css(styles.nvslTabActive);\n $('.spl-nvsl-tab-active a').css(styles.nvslTabActiveAnchor);\n $('.spl-nvsl-tab-active a').hover(function() {\n $(this).css(styles.nvslTabActiveAnchorHover);\n }, function() {\n $(this).css(styles.nvslTabActiveAnchor);\n });\n\n }",
"function addStyles() {\n\t styles.use();\n\t stylesInUse++;\n\t}",
"function applyTheme(themeName) {\n document.body.classList = '';\n document.body.classList.add(themeName);\n document.cookie = 'theme=' + themeName;\n }",
"function createStyleManager() {\n\t var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n\t jss = _ref.jss,\n\t _ref$theme = _ref.theme,\n\t theme = _ref$theme === undefined ? {} : _ref$theme;\n\t\n\t if (!jss) {\n\t throw new Error('No JSS instance provided');\n\t }\n\t\n\t var sheetMap = [];\n\t var sheetOrder = void 0;\n\t\n\t // Register custom jss generateClassName function\n\t jss.options.generateClassName = generateClassName;\n\t\n\t function generateClassName(str, rule) {\n\t var hash = (0, _murmurhash3_gc2.default)(str);\n\t str = rule.name ? rule.name + '-' + hash : hash;\n\t\n\t // Simplify after next release with new method signature\n\t if (rule.options.sheet && rule.options.sheet.options.name) {\n\t return rule.options.sheet.options.name + '-' + str;\n\t }\n\t return str;\n\t }\n\t\n\t /**\n\t * styleManager\n\t */\n\t var styleManager = {\n\t get sheetMap() {\n\t return sheetMap;\n\t },\n\t get sheetOrder() {\n\t return sheetOrder;\n\t },\n\t setSheetOrder: setSheetOrder,\n\t jss: jss,\n\t theme: theme,\n\t render: render,\n\t reset: reset,\n\t rerender: rerender,\n\t getClasses: getClasses,\n\t updateTheme: updateTheme,\n\t prepareInline: prepareInline,\n\t sheetsToString: sheetsToString\n\t };\n\t\n\t updateTheme(theme, false);\n\t\n\t function render(styleSheet) {\n\t var index = getMappingIndex(styleSheet.name);\n\t\n\t if (index === -1) {\n\t return renderNew(styleSheet);\n\t }\n\t\n\t var mapping = sheetMap[index];\n\t\n\t if (mapping.styleSheet !== styleSheet) {\n\t jss.removeStyleSheet(sheetMap[index].jssStyleSheet);\n\t sheetMap.splice(index, 1);\n\t\n\t return renderNew(styleSheet);\n\t }\n\t\n\t return mapping.classes;\n\t }\n\t\n\t /**\n\t * Get classes for a given styleSheet object\n\t */\n\t function getClasses(styleSheet) {\n\t var mapping = (0, _utils.find)(sheetMap, { styleSheet: styleSheet });\n\t return mapping ? mapping.classes : null;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function renderNew(styleSheet) {\n\t var name = styleSheet.name,\n\t createRules = styleSheet.createRules,\n\t options = styleSheet.options;\n\t\n\t var sheetMeta = name + '-' + styleManager.theme.id;\n\t\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object') {\n\t var element = document.querySelector('style[data-jss][data-meta=\"' + sheetMeta + '\"]');\n\t if (element) {\n\t options.element = element;\n\t }\n\t }\n\t\n\t var rules = createRules(styleManager.theme);\n\t var jssOptions = _extends({\n\t name: name,\n\t meta: sheetMeta\n\t }, options);\n\t\n\t if (sheetOrder && !jssOptions.hasOwnProperty('index')) {\n\t var index = sheetOrder.indexOf(name);\n\t if (index === -1) {\n\t jssOptions.index = sheetOrder.length;\n\t } else {\n\t jssOptions.index = index;\n\t }\n\t }\n\t\n\t var jssStyleSheet = jss.createStyleSheet(rules, jssOptions);\n\t\n\t var _jssStyleSheet$attach = jssStyleSheet.attach(),\n\t classes = _jssStyleSheet$attach.classes;\n\t\n\t sheetMap.push({ name: name, classes: classes, styleSheet: styleSheet, jssStyleSheet: jssStyleSheet });\n\t\n\t return classes;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function getMappingIndex(name) {\n\t var index = (0, _utils.findIndex)(sheetMap, function (obj) {\n\t if (!obj.hasOwnProperty('name') || obj.name !== name) {\n\t return false;\n\t }\n\t\n\t return true;\n\t });\n\t\n\t return index;\n\t }\n\t\n\t /**\n\t * Set DOM rendering order by sheet names.\n\t */\n\t function setSheetOrder(sheetNames) {\n\t sheetOrder = sheetNames;\n\t }\n\t\n\t /**\n\t * Replace the current theme with a new theme\n\t */\n\t function updateTheme(newTheme) {\n\t var shouldUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\t\n\t styleManager.theme = newTheme;\n\t if (!styleManager.theme.id) {\n\t styleManager.theme.id = (0, _murmurhash3_gc2.default)(JSON.stringify(styleManager.theme));\n\t }\n\t if (shouldUpdate) {\n\t rerender();\n\t }\n\t }\n\t\n\t /**\n\t * Reset JSS registry, remove sheets and empty the styleManager.\n\t */\n\t function reset() {\n\t sheetMap.forEach(function (_ref2) {\n\t var jssStyleSheet = _ref2.jssStyleSheet;\n\t jssStyleSheet.detach();\n\t });\n\t sheetMap = [];\n\t }\n\t\n\t /**\n\t * Reset and update all existing stylesheets\n\t *\n\t * @memberOf module:styleManager~styleManager\n\t */\n\t function rerender() {\n\t var sheets = [].concat(_toConsumableArray(sheetMap));\n\t reset();\n\t sheets.forEach(function (n) {\n\t render(n.styleSheet);\n\t });\n\t }\n\t\n\t /**\n\t * Prepare inline styles using Theme Reactor\n\t */\n\t function prepareInline(declaration) {\n\t if (typeof declaration === 'function') {\n\t declaration = declaration(theme);\n\t }\n\t\n\t var rule = {\n\t type: 'regular',\n\t style: declaration\n\t };\n\t\n\t prefixRule(rule);\n\t\n\t return rule.style;\n\t }\n\t\n\t /**\n\t * Render sheets to an HTML string\n\t */\n\t function sheetsToString() {\n\t return sheetMap.sort(function (a, b) {\n\t if (a.jssStyleSheet.options.index < b.jssStyleSheet.options.index) {\n\t return -1;\n\t }\n\t if (a.jssStyleSheet.options.index > b.jssStyleSheet.options.index) {\n\t return 1;\n\t }\n\t return 0;\n\t }).map(function (sheet) {\n\t return sheet.jssStyleSheet.toString();\n\t }).join('\\n');\n\t }\n\t\n\t return styleManager;\n\t}",
"get themeCSS(){\n\t\t\treturn CURRENT_THEME.BASETHEME_CACHE + CURRENT_THEME.THEME_CACHE;\n\t\t}",
"function setTheme(event, obj){\n function save(theme){\n storage.set({ 'devtools-theme': theme.value },\n function(){ panel.currentTheme = theme.text; });\n }\n if (event && event.type === 'change'){\n $themeTitle.style.display = 'none';\n var el = event.target || event.srcElement;\n var option = el.options[el.selectedIndex];\n save(option);\n $('.alert')[0].style.display = 'block';\n } else if (event === null && obj){\n save(obj);\n }\n }",
"_setCss(propertyName) {\n if (isPresent(get(this, propertyName))) {\n this.element.style[propertyName] = get(this, propertyName);\n }\n }",
"updateStyle(stateStyle) {\n let {styles} = this.stylesheet;\n\n this.setState({\n containerStyle: assign({}, styles.container, stateStyle)\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
overridable: getHassState will be called for getting a name/tele/HASS_STATE payload (should be chained) | getHassState() {
let hass_state = super.getHassState();
let gate_state = this.status;
hass_state[ 'Uptime' ] = this.secondsToDTHHMMSS( this.getUpTime() );
hass_state[ 'Last Connected' ] = gate_state.lastOpened;
hass_state[ 'Last Message' ] = gate_state.lastMessage;
hass_state[ 'Last Error' ] = gate_state.lastError;
hass_state[ 'Connections' ] = gate_state.sessionCount || 0;
hass_state[ 'Total Messages' ] = gate_state.messageCount || 0;
hass_state[ 'Dispatched Messages' ] = this.dl.dispatchCount;
hass_state[ 'Commands' ] = gate_state.commandCount || 0;
hass_state[ 'Confirmations' ] = gate_state.confirmCount || 0;
hass_state[ 'Errors' ] = gate_state.errorCount || 0;
return hass_state;
} | [
"function buildHueState(hue, bri, trans) {\n return JSON.stringify({\n on: true,\n bri: bri,\n hue: hue,\n sat: 254,\n transitiontime: trans/100\n })\n}",
"function readState(data) {\n\n gamestate = data.val();\n\n}",
"retrieveState(){\n if(this.storePath()){\n this.state = getLocal(this.storePath(), this.state)\n }\n }",
"getState(name, key, delmiter = '$') {\n if (typeof key !== 'undefined') {\n return this.state[name + delmiter + key];\n }\n\n let result = {},\n found = false;\n\n for (let key in this.state) {\n if (key.startsWith(`${name}${delmiter}`)) {\n result[key.split(`${delmiter}`).splice(-1)] = this.state[key];\n found = true;\n }\n }\n\n return found ? result : this.state[name];\n }",
"async getState(assetClass, key) {\n let ledgerKey = this.ctx.stub.createCompositeKey(assetClass, State.splitKey(key));\n let data = await this.ctx.stub.getState(ledgerKey);\n let state = State.deserialize(data, this.supportedClasses);\n return state;\n }",
"function _getPullHeaderState(instance) {\n \n var state = instance.data('pullHeaderState');\n if (!state) {\n // If unknown : take 'initial' as default\n state = 'initial';\n }\n \n return state;\n }",
"getActiveState() {\r\n return this.activeState.name;\r\n }",
"get(context) {\r\n const cached = context.get(this.stateKey);\r\n return typeof cached === 'object' && typeof cached.state === 'object' ? cached.state : undefined;\r\n }",
"_fetchState() {\n this._fetchLeagues();\n this._fetchSeasons();\n this._fetchRallies();\n this._fetchDrivers();\n }",
"async updateState(state) {\n let key = this.ctx.stub.createCompositeKey(state.getClass(), state.getSplitKey());\n let data = State.serialize(state);\n await this.ctx.stub.putState(key, data);\n }",
"get state() {\n if (!this._state)\n this.startState.applyTransaction(this);\n return this._state;\n }",
"load() {\n let jsonState = localStorage.getItem('state')\n if (jsonState) {\n let parsedState = JSON.parse(jsonState)\n // Do this so we add in the defaults for any new state objects which are missing.\n if (parsedState.version !== stateVersion) {\n state = defaultState()\n } else {\n state = Object.assign(defaultState(), parsedState)\n }\n } else {\n state = defaultState()\n }\n }",
"getTurn()\n {\n return this.state.currentTurn;\n }",
"fullState() {\n return Object.assign({}, this.state, this.internals);\n }",
"function currentStateOnload() {\n\tlet filepath = \"currentstate/currentstate.json\";\n\tfs.readFile (filepath, (err, data) => {\n\t\tif (err) return console.log(err);\n\t\tlet object = JSON.parse(data);\n\t\tlet filterNumber;\n\t\tfor (var key in object) {\n\t\t\tif (object.hasOwnProperty(key)){\n\t\t\t\tif (key.includes(\"gn\")){\n\t\t\t\t\tfilterNumber = \"f\" + key.substring(2); //get the filter number\n\t\t\t\t\tsendToAudioServer(filterNumber, \"gain\", object[key][\"value\"]);\n\t\t\t\t}\n\t\t\t\telse if (key.includes(\"qn\")){\n\t\t\t\t\tfilterNumber = \"f\" + key.substring(2);\n\t\t\t\t\tsendToAudioServer(filterNumber, \"q\", object[key][\"value\"]);\n\t\t\t\t}\n\t\t\t\telse if (key.includes(\"fn\")){\n\t\t\t\t\tfilterNumber = \"f\" + key.substring(2);\n\t\t\t\t\tsendToAudioServer(filterNumber, \"freq\", object[key][\"value\"]);\n\t\t\t\t}\n\t\t\t\telse if (key.includes(\"fs\")){\n\t\t\t\t\tfilterNumber = \"f\" + key.substring(2);\n\t\t\t\t\tsendToAudioServer(filterNumber, \"type\", object[key][\"value\"]);\n\t\t\t\t}\n\t\t\t\telse if (key == \"pgs\"){\n\t\t\t\t\tsendToAudioServer(\"pg\", \"gain\", object[key][\"value\"]);\n\t\t\t\t}\n\t\t\t\telse if (key == \"bypass\"){\n\t\t\t\t\tsendToAudioServer(\"bypass\", \"state\", object[key][\"value\"]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n}",
"function stateToHash(state) {\n var hash = '';\n for (var k in state) {\n if (hash) hash += '&';\n hash += k + ':' + state[k].replace(/,/g, '|');\n }\n return hash;\n}",
"async addState(state) {\n console.log(state.getClass())\n let key = this.ctx.stub.createCompositeKey(state.getClass(), state.getSplitKey())\n let data = State.serialize(state)\n await this.ctx.stub.putState(key, data)\n }",
"function getRoomState(voice_channel_id){\n var result = undefined\n var target_room = ROOMS.find((room) => room.channelID === voice_channel_id)\n if (target_room != undefined){\n result = target_room.state\n }\n return result\n}",
"static bindState () {\n for (const j in this.state) {\n if (this.state.hasOwnProperty(j)) {\n observe.watch(this.state, j, (newValue, oldValue) => {\n if (!this.__isSetState__) {\n this.state[j] = oldValue;\n this.__isSetState__ = true;\n console.error('Must use setState to update!');\n } else {\n this.__isSetState__ = false;\n }\n }, {\n deep: true\n });\n }\n }\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Debtor offers section end Debtor Offer line section start Only show those col for edit having visible true. | function dxGridDebOfferLines_OnEditingStart(e) {
editingIndex = e.component.getRowIndexByKey(e.key);
var grid = $("#dxGridDebtorOfferLine").dxDataGrid('instance');
manageDebCellVisibility(grid);
} | [
"showAdditionalDepartments(el) {\n if (el.parents('.drop').find('.reception-add-review').is(':visible')) {\n el.parents('.drop').find('.reception-add-review').hide();\n } else {\n el.parents('.drop').find('.reception-add-review').find('.department-select-row').show();\n el.parents('.drop').find('.reception-add-review').show();\n }\n }",
"function dxGridDebOrderLines_OnEditingStart(e) {\r\n editingIndex = e.component.getRowIndexByKey(e.key);\r\n var grid = $(\"#dxGridDebtorOrderLine\").dxDataGrid('instance');\r\n manageDebCellVisibility(grid);\r\n}",
"toggleDepartedColumn(){\n \t$('.departed-bucket').toggle();\n \t$('.chat-bucket').toggle();\n\t}",
"function show_hide_partner(obj,show_section)\n{\n}",
"function showDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }",
"function showSetDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }",
"function supplierExpanded() {\n var isFromSupplier = PPSTService.getAddingSupplier();\n if (isFromSupplier) {\n // Expand \n $scope.expandASection('suppliers-section', 8);\n PPSTService.setAddingSupplier(false);\n }\n }",
"function toggleCols(id,zeromargin,maincol) {\n var showit = 'show_' + escape(id);\n if (!zeromargin) { zeromargin = ''; }\n if (!id) { id = ''; }\n if (!maincol) { maincol = 'col1'; }\n if (document.getElementById(id).style.display == \"none\") {\n document.getElementById(id).style.display = \"block\";\n if (zeromargin == 'left') {\n document.getElementById(maincol).style.marginLeft = '';\n setSessionVar(showit,'y');\n } else {\n document.getElementById(maincol).style.marginRight = '';\n setSessionVar(showit,'y');\n }\n } else {\n document.getElementById(id).style.display = \"none\";\n if (zeromargin == 'left') {\n document.getElementById(maincol).style.marginLeft = '0';\n setSessionVar(showit,'n');\n } else {\n document.getElementById(maincol).style.marginRight = '0';\n setSessionVar(showit,'n');\n }\n }\n}",
"toggleColumn(e) {\n const t = !this.columnIsVisible(e), r = hp(this.columns, (i) => i.can_be_hidden ? i.key === e ? t : this.visibleColumns.includes(i.key) : !0);\n let n = ws(r, (i) => i.key).sort();\n ii(n, this.defaultVisibleToggleableColumns) && (n = []), this.visibleColumns = n.length === 0 ? this.defaultVisibleToggleableColumns : n, this.updateQuery(\"columns\", n, null, !1);\n }",
"function toggleInvitationsSection() {\n var string = 'invitationsSection';\n var value = getStyle(string, 'display');\n hideNewListSection();\n hideInviteMemberSection();\n if(value == 'none') {\n\tshowInvitationsSection();\n } else {\n\thideInvitationsSection();\n }\n}",
"function showautoDPortSrchTableByNum(num) {\n if(num==2){\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\tvar aswidth = $('#autoDPartnerInfoField').width()/2;\n\t\t}else{\n\t var aswidth = ($('#autoDPartnerInfoField').width()-15)/2;\n\t\t}\n \t$('#autoDPortSlotNum').width(aswidth);\n $('#autoDSlotNumPId').width(aswidth);\n\t $('#autoDPortSrch').hide();\n \t$.each($('#autoDPartnerInfoTbody > tr'), function(index,object){\n\t\t\tif(globalDeviceType == \"Mobile\"){\n\t if(object.children[2]!=undefined){object.children[2].remove();}\n\t\t\t}else{\n\t if(object.children[3]!=undefined){object.children[3].remove();}\n\t\t\t}\n\t });\n }else if(num==3){\n\t\tif((AutoDType.toLowerCase()=='testtool' || AutoDType.toLowerCase()=='server')) {\n\t\t\tvar tmpwidth = $('#autoDTestTPartnerInfoField').width();\n\t\t}else if(AutoDType.toLowerCase()!='admin'){\n\t\t\tvar tmpwidth = $('#autoDPartnerInfoField').width();\n\t\t}\n\t\t\n\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\tvar aswidth = tmpwidth/3;\n\t\t}else{\n\t var aswidth = (tmpwidth-15)/3;\n\t\t\t$('#autoDPortSlotChk').width(15);\n\t\t}\n\t\tvar tbodycon;\n\t\tif(AutoDType.toLowerCase()=='testtool' || AutoDType.toLowerCase()=='server') {\n\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t $('#autoDTestTPortSlotNum').width(aswidth);\n\t\t $('#autoDTestTNumPId').width(aswidth);\n \t\t$('#autoDTestTPortSrch').width(aswidth);\n\t\t\t}\n \t $('#autoDTestTPortSrch').show();\n\t\t\ttbodycon = $('#autoDTestTPartnerInfoTbody > tr');\n\t\t}else if(AutoDType.toLowerCase()=='admin'){\n\t\t\ttbodycon = $('#partSlotInfoAutoDAdminTbody > tr');\n\t\t}else{\n\t $('#autoDPortSlotNum').width(aswidth);\n \t $('#autoDSlotNumPId').width(aswidth);\n \t$('#autoDPortSrch').show();\n\t $('#autoDPortSrch').width(aswidth);\n\t\t\ttbodycon = $('#autoDPartnerInfoTbody > tr');\n\t\t}\n $.each(tbodycon, function(index,object){\n if(globalDeviceType == \"Mobile\"){\n \tvar input = \"<td id='\"+object.id+\"In'><input type='text' placeholder='Count:' style='border:none;font-size:16px;' onKeyPress='return checkPortSlotTotal(event,this)'></td>\";\n\t\t\t\tif(object.children.length<=2){$('#'+object.id).append(input);}\n\t\t\t}else{\n \tvar input = \"<td id='\"+object.id+\"In' style='text-align:center;'><input type='text' placeholder='Count:' onKeyPress='return checkPortSlotTotal(event,this)' style='border:none;width:90%;' disabled='disabled'></td>\";\n\t if(object.children.length<=3){$('#'+object.id).append(input);}\n\t\t\t}\n\t\t });\n }\n}",
"function toggleDetailTable() {\n $('.extend-data').hide();\n $('.luft-extend-table').click(function (e) {\n $(this).parent().next().slideToggle(200);\n $(this).parent().parent().toggleClass('data-expended');\n e.preventDefault();\n });\n $('.extend-data').slideUp(200);\n }",
"function checaVisibilidadePlano(){\n\n if($(\"#planoEstagio\").is(':visible')) {// checa se atributo esta visivel\n // faca nada\n }else{\n $( \"form > div > div\" ).hide();\n $(\"#planoEstagio\").show();\n }\n\n}",
"function tableIsVisible() {\r\n if ($(\"#myTable, #gra\").visibility == \"visible\") {\r\n } else {\r\n $(\"#myTable, #gra\").css('visibility', 'visible');\r\n }\r\n }",
"function showFactColumns(){\r\n\tif (document.getElementById(\"txtFact\").selectedIndex >= 0){\r\n\t\t//borramos los que habia antes\r\n\t\tborrarTextArea(\"txtFactColumns\");\r\n\t\r\n\t\tvar tablesSel = document.getElementById(\"txtFact\");\r\n\t\t// Obtener el índice de la opción que se ha seleccionado\r\n\t\tvar indiceSeleccionado = tablesSel.selectedIndex;\r\n\t\t// Con el índice y el array \"options\", obtener la opción seleccionada\r\n\t\tvar opcionSeleccionada = tablesSel.options[indiceSeleccionado];\r\n\t\t// Obtener el valor y el texto de la opción seleccionada\r\n\t\tvar tableName = opcionSeleccionada.text;\r\n\t\tvar tableId = opcionSeleccionada.value;\r\n\t\tfor(var i=0;i<document.getElementById(\"txtColumnsSel\").options.length;i++){\r\n\t\t\tvar optId = (document.getElementById(\"txtColumnsSel\").options[i].value);//valor compuesto: tblId.colId\r\n\t\t\tvar optNom = (document.getElementById(\"txtColumnsSel\").options[i].text);//valor compuesto: tblName.colName\r\n\t\t\t//alert(optNom + \"/\" + optId);\r\n\t\t\t//Mostramos solo las columnas seleccionadas de la tabla\r\n\t\t\tif (optId == 0 && optNom.indexOf(tableName)==0){ //es una recuperada de la base\r\n\t\t\t\tvar oOpt = document.createElement(\"OPTION\");\r\n\t\t\t\toOpt.innerHTML = optNom;\r\n\t\t\t\toOpt.value = optId;\r\n\t\t\t\t//if(notInColsFact(optId)){\r\n\t\t\t\t\tdocument.getElementById(\"txtFactColumns\").appendChild(oOpt);\r\n\t\t\t\t//}\r\n\t\t\t}else if((optId.indexOf(tableId)==0) && (optNom.indexOf(tableName)==0)){ //es una seleccionada por el usuario\r\n\t\t\t\tvar oOpt = document.createElement(\"OPTION\");\r\n\t\t\t\toOpt.innerHTML = optNom;\r\n\t\t\t\toOpt.value = optId;\r\n\t\t\t//\tif(notInColsFact(optId)){\r\n\t\t\t\t\tdocument.getElementById(\"txtFactColumns\").appendChild(oOpt);\r\n\t\t\t//\t}\r\n\t\t\t}\r\n\t\t}\r\n\t//\talert(\"tableId: \"+tableId);\r\n\t\tif (indiceSeleccionado == 0){ //Si se selecciono la fila nula\r\n\t\t\tborrarAllMeasures();\r\n\t\t}else {\r\n\t\t\ttrows=document.getElementById(\"gridMeasures\").rows;\r\n\t\t\tif (trows.length>0){\r\n\t\t\t\tvar val = trows[0].getElementsByTagName(\"TD\")[0].getElementsByTagName(\"INPUT\")[1].value;\r\n\t\t\t\tvar i = val.indexOf(\".\");\r\n\t\t\t\tvar k = val.indexOf(tableId);\r\n\t\t\t\tif (k == -1 || k>i){\r\n\t\t\t\t\tborrarAllMeasures();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tdocument.getElementById(\"txtFactColumns\").style.display=\"none\";\r\n\tdocument.getElementById(\"txtFactColumns\").style.display=\"block\";\r\n}",
"function showOrHideNextBtnToShowCustomerRecordForm() { \r\n\tvar selectedTimeId = document.querySelector('.timePicked');\r\n\tvar selectedDateId = document.querySelector('.datePicked');\r\n\tvar timeIs = selectedTimeId.length;\r\n\tvar dateIs = selectedDateId.length;\r\n\tif(selectedTimeId.innerText == \"---\" || selectedTimeId.innerText == \"\" || selectedDateId.innerText == \"\" || selectedDateId.innerText == \"---\" ){\r\n\t\t document.querySelector('.showGetCustomerBtn').style.display = 'none'; //hide next btn to show customer records\r\n\t}else{\r\n\t\t document.querySelector('.showGetCustomerBtn').style.display = 'block'; //show next btn to show customer records\r\n\t}\r\n }",
"updateColumnDisplay() {\n let i = 0;\n while (i < this.columnData.length) {\n let colData = this.columnData[i];\n let colWidth = colData.getValue('widthVal');\n let colSpan = colData.getValue('colspanVal');\n colData.getElement().show();\n if (colSpan > 1) {\n let colspanEndIndex = ((i + colSpan) < this.columnData.length) ? (i + colSpan) : this.columnData.length;\n i++;\n // hide columns within colspan\n while (i < colspanEndIndex) {\n colWidth += this.columnData[i].getValue('widthVal');\n this.columnData[i].getElement().hide();\n i++;\n }\n } else {\n i++;\n }\n colData.setDisplayWidth(colWidth);\n colData.updateDisplay();\n }\n }",
"function hideSecondPersonRow() {\n let row = document.getElementById('person2')\n row.classList.toggle('show')\n row.style.display = 'none'\n hideMinusPersonButton()\n showAddPersonButton()\n}",
"function setHideUntilRowVisibility( rowID, hideUntilVal){\n sheet = SpreadsheetApp.getActive().getSheetByName(CONFIG_SHEET_TODO);\n \n // check if date is > now\n var dtmHideUntil = new Date(hideUntilVal);\n var dtmNow = new Date(); \n \n Logger.log(\"rowID: \" + rowID );\n \n if( dtmNow <= dtmHideUntil ){\n // hide the row\n sheet.hideRows(rowID); \n }\n else{\n // show the row\n sheet.showRows(rowID);\n }\n \n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the examplebegin indices; shuffle them randomly. | generateExampleBeginIndices_() {
// Prepare beginning indices of examples.
this.exampleBeginIndices_ = [];
for (
let i = 0;
i < this.textLen_ - this.sampleLen_ - 1;
i += this.sampleStep_
) {
this.exampleBeginIndices_.push(i);
}
console.log('exampleBeginIndices_');
console.log(this.exampleBeginIndices_);
// Randomly shuffle the beginning indices.
// tf.util.shuffle(this.exampleBeginIndices_);
this.examplePosition_ = 0;
} | [
"generateExampleBeginIndices_() {\n // Prepare beginning indices of examples.\n this.exampleBeginIndices_ = [];\n for (let i = 0;\n i < this.textLen_ - this.sampleLen_ - 1;\n i += this.sampleStep_) {\n this.exampleBeginIndices_.push(i);\n }\n\n // Randomly shuffle the beginning indices.\n tf.util.shuffle(this.exampleBeginIndices_);\n this.examplePosition_ = 0;\n }",
"shuffle() {\n \n for (let i = 0; i < this._individuals.length; i++) {\n let index = getRandomInt( i + 1 );\n let a = this._individuals[index];\n this._individuals[index] = this._individuals[i];\n this._individuals[i] = a;\n }\n }",
"function shuffle_filler_quest(shuffled_indices) {\n q_list = [];\n for (var i = 0; i < shuffled_indices.length; i++) {\n index = shuffled_indices[i];\n q_list = _.concat(q_list, filler_question[index])\n }\n return q_list;\n}",
"function genSeeds() {\r\n analyser.getByteTimeDomainData(dataArray);\r\n sliceSize = Math.floor(bufferLength / 5);\r\n\r\n var sum = 0;\r\n var scaleFactor = 138.0;\r\n\r\n // Seed A\r\n for (var i = 0; i < sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedA = sum / (bufferLength/5)\r\n sum = 0;\r\n\r\n // Seed B\r\n for (var i = sliceSize; i < 2*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedB = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed C\r\n for (var i = 2*sliceSize; i < 3*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedC = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed D\r\n for (var i = 3*sliceSize; i < 4*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedD = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed E\r\n for (var i = 4*sliceSize; i < 5*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedE = sum / sliceSize\r\n sum = 0;\r\n\r\n console.log(`A: ${seedA}, B: ${seedB}, C: ${seedC}, D: ${seedD}, E: ${seedE}`);\r\n}",
"function shuffle_filler_conc(shuffled_indices) {\n c_list = [];\n for (var i = 0; i < shuffled_indices.length; i++) {\n index = shuffled_indices[i];\n c_list = _.concat(c_list, filler_conclusion[index])\n }\n return c_list;\n}",
"function elementLocations() {\n let choice;\n let transferArray = [];\n let newShuffle = [];\n\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < rows; j++) {\n choice = floor(random(allElements.length - 1));\n transferArray.push([allElements[choice], 0, 0]);\n allElements.splice(choice, 1);\n }\n newShuffle.push(transferArray);\n transferArray = [];\n }\n return newShuffle;\n}",
"function randomSequence(){\n\t\t\tvar sequence = [];\n\t\t\tfor(var i = 0; i < 20; i++){\n\t\t\t\tsequence.push(Math.floor((Math.random()*100)%4)+1);\n\t\t\t}\n\t\t\treturn sequence;\n\t\t}",
"function generateRandomIndex(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}",
"function setUp() {\n canvasCreate.start();\n createRandomIntArray();\n updateCanvas();\n}",
"function testInit_PersistentIndices() {\n asyncTestCase.waitForAsync('testInit_PersistentIndices');\n\n var tableSchema = env.schema.table('tableA');\n var rows = getSampleRows(tableSchema, 10, 0);\n\n simulatePersistedIndices(tableSchema, rows).then(\n function() {\n var prefetcher = new lf.cache.Prefetcher(lf.Global.get());\n return prefetcher.init(env.schema);\n }).then(\n function() {\n // Check that RowId index has been properly reconstructed.\n var rowIdIndex = env.indexStore.get(tableSchema.getRowIdIndexName());\n assertTrue(rowIdIndex instanceof lf.index.RowId);\n assertEquals(rows.length, rowIdIndex.getRange().length);\n\n // Check that remaining indices have been properly reconstructed.\n var indices = env.indexStore.getTableIndices(\n tableSchema.getName()).slice(1);\n indices.forEach(function(index) {\n assertTrue(index instanceof lf.index.BTree);\n assertEquals(rows.length, index.getRange().length);\n });\n\n asyncTestCase.continueTesting();\n }, fail);\n}",
"function randSampleOutPlace(collection, numSample) {\n var n = collection.length\n var s = Math.min(n, numSample)\n var result = new Array(s)\n for (var i = 0; i < s; i++) {\n result[i] = collection[i]\n }\n for (var i = s; i < n; i++) {\n var j = randomIntBetweenInclusive(0, i)\n if (j < s) {\n // swap in\n result[j] = collection[i]\n }\n }\n return result\n}",
"getRandomPhrase () {\n\t\tlet newIndex;\n\t\tdo {\n\t\t\tnewIndex = Math.floor(Math.random() * this.phrases.length);\n\t\t} while (this.usedIndexes.indexOf(newIndex) !== -1);\n\t\tthis.usedIndexes.push(newIndex);\n\t\tdocument.body.style.background = this.getRandomColor();\n\t\treturn this.phrases[newIndex];\n\t}",
"function setUpRandomizer() {\n\trandConstSpan = document.getElementById(\"rand_const\");\n\talreadyFoundP = document.getElementById(\"already_found\");\n}",
"function randSampleInPlace(collection, numSample) {\n var n = collection.length\n var s = Math.min(n, numSample)\n for (var i = n - 1; i >= n - s; i--) {\n var j = randomIntBetweenInclusive(0, i)\n if (i !== j) {\n // swap\n var temp = collection[j]\n collection[j] = collection[i]\n collection[i] = temp\n }\n }\n return collection.slice(n - s, n)\n}",
"function getRandomIndex(allShorts) {\n // A random number between 0 and len(allShorts)\n let rIndex = Math.floor(Math.random() * allShorts.length);\n // returning the random index\n return rIndex;\n}",
"assignTilesEx(excludedIndexes)\n {\n let indices = [];\n while(indices.length<7){\n let pickedIndex =Math.floor((Math.random()*100)%28);\n if(indices.indexOf(pickedIndex)<0 && excludedIndexes.indexOf(pickedIndex)<0)\n {\n indices.push(pickedIndex);\n }\n }\n this.unassignedTilePositions = this.unassignedTilePositions.filter(pos=>indices.indexOf(pos)<0);\n return indices;\n }",
"function indcpaGenMatrix(seed, transposed, paramsK) {\r\n var a = new Array(3);\r\n var output = new Array(3 * 168);\r\n const xof = new SHAKE(128);\r\n var ctr = 0;\r\n var buflen, offset;\r\n for (var i = 0; i < paramsK; i++) {\r\n\r\n a[i] = polyvecNew(paramsK);\r\n var transpose = new Array(2);\r\n\r\n for (var j = 0; j < paramsK; j++) {\r\n\r\n // set if transposed matrix or not\r\n transpose[0] = j;\r\n transpose[1] = i;\r\n if (transposed) {\r\n transpose[0] = i;\r\n transpose[1] = j;\r\n }\r\n\r\n // obtain xof of (seed+i+j) or (seed+j+i) depending on above code\r\n // output is 504 bytes in length\r\n xof.reset();\r\n const buffer1 = Buffer.from(seed);\r\n const buffer2 = Buffer.from(transpose);\r\n xof.update(buffer1).update(buffer2);\r\n var buf_str = xof.digest({ buffer: Buffer.alloc(504), format: 'hex' });\r\n // convert hex string to array\r\n for (var n = 0; n < 504; n++) {\r\n output[n] = hexToDec(buf_str[2 * n] + buf_str[2 * n + 1]);\r\n }\r\n\r\n // run rejection sampling on the output from above\r\n outputlen = 3 * 168; // 504\r\n var result = new Array(2);\r\n result = indcpaRejUniform(output, outputlen);\r\n a[i][j] = result[0]; // the result here is an NTT-representation\r\n ctr = result[1]; // keeps track of index of output array from sampling function\r\n\r\n while (ctr < paramsN) { // if the polynomial hasnt been filled yet with mod q entries\r\n var outputn = output.slice(0, 168); // take first 168 bytes of byte array from xof\r\n var result1 = new Array(2);\r\n result1 = indcpaRejUniform(outputn, 168); // run sampling function again\r\n var missing = result1[0]; // here is additional mod q polynomial coefficients\r\n var ctrn = result1[1]; // how many coefficients were accepted and are in the output\r\n\r\n // starting at last position of output array from first sampling function until 256 is reached\r\n for (var k = ctr; k < paramsN - ctr; k++) {\r\n a[i][j][k] = missing[k - ctr]; // fill rest of array with the additional coefficients until full\r\n }\r\n ctr = ctr + ctrn; // update index\r\n }\r\n\r\n }\r\n }\r\n return a;\r\n}",
"function getPivotIndex(startIndex, endIndex) {\n return startIndex + Math.floor(Math.random() * (endIndex - startIndex));\n}",
"function shuffle() {\n var parent = document.querySelector(\"#container\");\n for (var i = 0; i < parent.children.length; i++) {\n parent.appendChild(parent.children[Math.random() * i | 0]);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Property is to get whether the browser has MSPointer support. | static get isMSPointer() {
if (isUndefined(window.browserDetails.isMSPointer)) {
return window.browserDetails.isMSPointer = ('msPointerEnabled' in window.navigator);
}
return window.browserDetails.isMSPointer;
} | [
"get isTouch()\n {\n return \"ontouchstart\" in window;\n }",
"function isReallyTouch(e){//if is not IE || IE is detecting `touch` or `pen`\nreturn typeof e.pointerType==='undefined'||e.pointerType!='mouse';}",
"function isMediaDevicesSuported(){return hasNavigator()&&!!navigator.mediaDevices;}",
"function deviceHasTouchScreen() {\n let hasTouchScreen = false;\n if (\"maxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.maxTouchPoints > 0;\n } else if (\"msMaxTouchPoints\" in navigator) {\n hasTouchScreen = navigator.msMaxTouchPoints > 0;\n } else {\n var mQ = window.matchMedia && matchMedia(\"(pointer:coarse)\");\n if (mQ && mQ.media === \"(pointer:coarse)\") {\n hasTouchScreen = !!mQ.matches;\n } else if ('orientation' in window) {\n hasTouchScreen = true; // deprecated, but good fallback\n } else {\n // Only as a last resort, fall back to user agent sniffing\n var UA = navigator.userAgent;\n hasTouchScreen = (\n /\\b(BlackBerry|webOS|iPhone|IEMobile)\\b/i.test(UA) ||\n /\\b(Android|Windows Phone|iPad|iPod)\\b/i.test(UA)\n );\n }\n }\n return hasTouchScreen;\n }",
"function canEnumerateDevices(){return!!(isMediaDevicesSuported()&&navigator.mediaDevices.enumerateDevices);}",
"function supportsDisplay() {\n var hasDisplay =\n this.event.context &&\n this.event.context.System &&\n this.event.context.System.device &&\n this.event.context.System.device.supportedInterfaces &&\n this.event.context.System.device.supportedInterfaces.Display\n\n return hasDisplay;\n}",
"get isNativePlugin() {}",
"function useTouch() {\n return isNativeApp() || $.browser.mobile || navigator.userAgent.match(/iPad/i) != null;\n}",
"function isNotificationAvailable() {\n return (\"Notification\" in window);\n}",
"function isPluginEnabled() {\n return cordova && cordova.plugins && cordova.plugins.permissions;\n }",
"function IsMP()\n{\n return (g_isSupportMultiProfile || g_isMP1 || g_isMP73);\n}",
"function pluginInstalledIE(){\n\t\ttry{\n\t\t\tvar o = new ActiveXObject(\"npwidevinemediaoptimizer.WidevineMediaTransformerPlugin\");\n\t\t\to = null;\n\t\t\treturn true;\n\t\t}catch(e){\n\t\t\treturn false;\n\t\t}\n\t}",
"_isNativePlatform() {\n if ((this._isIOS() || this._isAndroid()) && this.config.enableNative) {\n return true;\n } else {\n return false;\n }\n }",
"isTrackingMouse() {\n return !!this._mouseTrackingId;\n }",
"function isEnabled() {\n return tray != undefined;\n}",
"function _supportsShadowDom() {\n if (shadowDomIsSupported == null) {\n var head = typeof document !== 'undefined' ? document.head : null;\n shadowDomIsSupported = !!(head && (head.createShadowRoot || head.attachShadow));\n }\n\n return shadowDomIsSupported;\n }",
"function check_web_storage_support(){\n if(typeof(storage)!==undefined){\n return (true);\n }\n else{\n alert(\"Web storage not supported\");\n return (false);\n }\n}",
"function checkSupport() {\n if (! $window.Notification)\n throw new Error('This browser does not support desktop notification.');\n }",
"function isEmulatingIE7() {\n var metaTags = document.getElementsByTagName(\"meta\"),\n content,\n i;\n for (i = 0; i < metaTags.length; i = i + 1) {\n content = metaTags[i].getAttribute(\"content\");\n if (content !== null && metaTags[i].getAttribute(\"http-equiv\") === \"X-UA-Compatible\" && (content.indexOf(\"IE=EmulateIE7\") > -1 || content.indexOf(\"IE=7\") > -1)) {\n return true;\n }\n }\n return false;\n }",
"set isNativePlugin(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates an date object of the match date | function fetchMatchDate(matchObj)
{
const TIME_EPOCH = matchObj.start_time;
var date = new Date(0);
date.setUTCSeconds(TIME_EPOCH);
return date;
} | [
"function createDate() {\n theDate = new Date();\n }",
"function getDates(result) {\n var currentTime = new Date(),\n rDate, \n opened,\n releaseDate;\n if (result.release_dates.theater) {\n rDate = result.release_dates.theater.split(\"-\");\n opened = new Date(rDate[0], rDate[1] - 1, rDate[2], 0, 0, 0);\n releaseDate = (currentTime - opened < 0) ? opened.toDateString().slice(4) : result.year;\n } else if (result.year > currentTime.getFullYear()) {\n releaseDate = result.year;\n }\n return releaseDate;\n }",
"function findSpecificDate(dateSpecific) {\n // Accept specific date and create a new object based on the date\n var d = new Date(dateSpecific);\n\n // get the date and assign to a variable d.\n d.setDate(d.getDate());\n \n // return the date in UNIX second\n return Math.floor( d / 1000); \n}",
"function createMatchDay() {\n\t\n\t// Create matchDay div\n\tvar matchDayElement = document.createElement('div');\n\tmatchDayElement.className = 'matchDay';\n\t$(matchDayElement).append('<h3>Match Day</h3>');\n\n\t// Add the date and time inserts\n\tcreateDateInput(matchDayElement, 'matchDayDateTime');\n\n\t// Add remove match day button\n\taddRemoveButton(matchDayElement, 'Remove Match Day', 'MatchDay')\n\n\t// Add ability to create a match\n\t$(matchDayElement).append('<br>');\n\tvar matchButton = document.createElement('button');\n\tmatchButton.innerHTML = \"Create Match\";\n\tmatchButton.className = 'matchButton';\n\tmatchButton.onclick = function() { createMatch(matchDayElement, 'match'); }; \n\tmatchDayElement.appendChild(matchButton);\n\n\t$('body').append(matchDayElement);\n}",
"static fromPartialString(v) {\n let match = /^(\\d{4})\\/(\\d{1,2})\\/(\\d{1,2})$/.exec(v);\n if (match) {\n return new NepaliDate(match[1], match[2], match[3]);\n }\n match = /^(\\d{1,2})\\/(\\d{1,2})$/.exec(v);\n if (match) {\n const nd = NepaliDate.today();\n let y = nd.nepaliYear;\n const m = match[1];\n const d = match[2];\n if (m > nd.nepaliMonth || (m === nd.nepaliMonth && d > nd.nepaliDay)) {\n y -= 1;\n }\n return new NepaliDate(y, m, d);\n }\n }",
"function transform_date(obj)\r\n {\r\n var hint,foo,num,i,jsDate\r\n if (obj && typeof obj === 'object')\r\n {\r\n hint = obj.hasOwnProperty('javaClass');\r\n foo = hint ? obj.javaClass === 'java.util.Date' : obj.hasOwnProperty('time');\r\n num = 0;\r\n // if there is no class hint but the object has 'time' property, count its properties\r\n if (!hint && foo)\r\n {\r\n for (i in obj)\r\n {\r\n if (obj.hasOwnProperty(i))\r\n {\r\n num++;\r\n }\r\n }\r\n }\r\n // if class hint is java.util.Date or no class hint set, but the only property is named 'time', we create jsdate\r\n if (hint && foo || foo && num === 1)\r\n {\r\n jsDate = new Date(obj.time);\r\n return jsDate;\r\n }\r\n else\r\n {\r\n for (i in obj)\r\n {\r\n if (obj.hasOwnProperty(i))\r\n {\r\n obj[i] = transform_date(obj[i]);\r\n }\r\n }\r\n return obj;\r\n }\r\n }\r\n else\r\n {\r\n return obj;\r\n }\r\n }",
"function dateWriter(year, month, day) {\n \n var date1 = new Date().toDateString();\n ; return date1;\n /*\n ;Output of above code is: Today's date is Sat Jun 02 2018\n ;close but doesn't pass in values and cannot get rid of Sat\n */\n // new Date().toLocaleDateString();\n // return Date();\n // ouput of above code is Today's date is \n // Sat Jun 02 2018 05:09:24 GMT-0500 (Central Daylight Time)\n // cannot get if formated that way I want\n // return dateWriter.day + \" \" + dateWriter.month + \", \" + dateWriter.year;\n // above code doesn't return \"fully qualified\" date object\n \n}",
"function buildDate(date, hours, minutes) {\n\t\t\t\t\tvar timestamp = date.setHours(hours, minutes);\n\n\t\t\t\t\treturn new Date(timestamp);\n\t\t\t\t}",
"GenerateStarDate() {\n\t\tlet date = new Date();\n\t\tdate.setDate(date.getDate() - 30);\n\t\tlet month = (date.getMonth() + 1).toString();\n\t\tlet day = date.getDate().toString();\n\t\tif (day.length < 2)\n\t\t\tday = \"0\" + day;\n\t\tif (month.length < 2)\n\t\t\tmonth = \"0\" + month;\n\t\tconst stringDate = date.getFullYear() + \"-\" + month + \"-\" + day;\n\t\treturn stringDate;\n\t}",
"toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }",
"function checkForDate(matchDate, testMsg, nextStepCallback) {\n\n // Make sure that we are in Jun 8th\n // Check the UIA element\n \n return Q.fcall(function () {\n\n return uia.root().findFirst(function (el) { return ((el.name === \"Meeting start date\") && (el.className === \"RichEdit20WPT\")); }, 4, 5);\n\n }).then(function (meetingStartDateArea) {\n\n // Get value pattern\n return meetingStartDateArea.getPattern(10002);\n\n }, function (error) { throw new Error(\"The promise for finding the meeting start date text area fails. \"); })\n .then(function (meetingStartDateAreaValuePat) {\n \n var curDateText = meetingStartDateAreaValuePat.getValue();\n\n // For QUnit testing\n QUnit.test(testMsg, function (assert) {\n // Test the output has all the necessary components\n assert.ok((curDateText.indexOf(matchDate) > -1), \"FROM TEST.JS: TEST WHEN INPUT DAY IS NORMAL - RESULT OF ASSERTION\");\n });\n\n // Continue to do next step if we have one\n if (nextStepCallback !== null) {\n nextStepCallback();\n }\n\n }, function (error) { throw new Error(\"The promise for finding the value pattern of meeting start date text area fails. \"); });\n}",
"function idAppointment2Day(id){\n let dateList = id.split(\"-\");\n return new Date(dateList[4], dateList[5]-1, dateList[6]);\n}",
"function getRentalReturnDate(pickupDate,numRentalDays)\n{\n \n const msecPerDay = 1000*60*60*24;\n\n let returnDate= (pickupDate + (numRentalDays*msecPerDay));\n\n returnDate = new Date(returnDate);\n\n return returnDate;\n}",
"function calculateDaysSinceMatch(matchDate)\n{\n const oneDay = 24 * 60 * 60 * 1000;\n const today = new Date();\n return Math.round(Math.abs((today - matchDate) / oneDay));\n}",
"function sameDate(date1, date2) {\n return (date1.getDate() === date2.getDate()\n && date1.getMonth() === date2.getMonth()\n && date1.getFullYear() === date2.getFullYear()\n );\n}",
"findEventsByDate(findDate) {\r\n searchDate = new Date(findDate);\r\n\r\n let results = []\r\n\r\n // Assuming same timezone for now\r\n for (let event of Event.all) {\r\n if (\r\n event.date.getMonth() == searchDate.getMonth()\r\n && event.date.getDay() == searchDate.getDay()\r\n && event.date.getYear() == searchDate.getYear()\r\n ) {\r\n results.add(event);\r\n }\r\n }\r\n console.log(results);\r\n return results;\r\n }",
"function matchToDateWithFromDate(){\n\t\tvar fDate = dojo.byId('f_fromDateField');\n\t\tvar tDate = dojo.byId('f_toDateField');\n\t\tif(tDate.value.length == 0){\n\t\t\t\tsyncDate(fDate);\n\t\t\t\ttDate.value = fDate.value;\n\t\t\t}\t\n\t}",
"function BuildDates(date){\n\tvar array = new Array();\n\tarray['day'] = (date.getDate() < 10) ? \n\t\t\t\t\t\t'0' + date.getDate().toString() : \n\t\t\t\t\t\tdate.getDate().toString();\n\t\t\t\t\t\t\n\tarray['month'] = (date.getMonth() < 9) ? \n\t\t\t\t\t\t'0' + (date.getMonth()+1).toString() : \n\t\t\t\t\t\t(date.getMonth()+1).toString();\n\t\t\t\t\t\t\n\tarray['year'] = date.getFullYear().toString();\n\treturn array;\n}",
"function getCompareNow( d1,d)\n\t{\n\t\tif (d1.length>10)\n\t\t\td1 = changeToMM(d1) ;\n\t\tif (d.length>10)\n\t\t\td = changeToMM(d) ;\n\t\t// Convert dash to slash\n\t\td1 = dashToSlash(d1) ;\n\t\td = dashToSlash(d) ;\n\t\t// Parse the string in DD/MM/YYYY format\n\t\tre = /(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4})/\n\t\tvar arr = re.exec( d1);\n\t\t//var d = getCurrentDate();\n\t\tvar arr2 = re.exec( d);\n\t\t//alert('getCompareNow');\n\t\tvar dt = new Date( parseInt(arr[3]), parseInt(arr[2], 10) - 1, parseInt(arr[1], 10));\n\t\tvar dn = new Date( parseInt(arr2[3]), parseInt(arr2[2], 10) - 1, parseInt(arr2[1], 10));\n\t\n\t\treturn dt >= dn;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method jsTabControl.turnTabOff() This function switches a tab into the off state given the tabID. Parameters: tabID (String) the ID of the tab to act on. Returns: nothing. | function _jsTabControl_turnTabOff(tabID) {
document.getElementById('tab' + tabID + 'text').style.backgroundImage = "url(" + IMG_TAB_OFF[1].filename + ")";
document.images['tab' + tabID + 'left'].src = IMG_TAB_OFF[0].filename;
document.images['tab' + tabID + 'right'].src = IMG_TAB_OFF[2].filename;
} | [
"function stopTimer(tabId) {\n if (tabIntervals[tabId]) {\n window.clearInterval(tabIntervals[tabId].intervalID);\n tabIntervals[tabId] = null;\n }\n}",
"function _jsTabControl_turnTabOn(tabID) {\n\tdocument.getElementById('tab' + tabID + 'text').style.backgroundImage = \"url(\" + IMG_TAB_ON[1].filename + \")\";\n\tdocument.images['tab' + tabID + 'left'].src = IMG_TAB_ON[0].filename;\n\tdocument.images['tab' + tabID + 'right'].src = IMG_TAB_ON[2].filename;\t\t\n}",
"function hideTab(container, id) {\n\t\t//var opts = $.data(container, 'tabs').options;\n\t\tvar elem;\n\t\t$('>div.tabs-header li', container).each(function () {\n\t\t\tvar tabAttr = $.data(this, 'tabs.tab');\n\t\t\tif (tabAttr.id == id) {\n\t\t\t\telem = this;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\t\tif (!elem) return;\n\t\t//if($(elem).is(':hidden'))return ;//如果非隐藏tab直接不处理\n\t\tif ($(elem).hidden) return;\n\t\tvar tabAttr = $.data(elem, 'tabs.tab');\n\t\tvar panel = $('#' + tabAttr.id);\n\n\t\tvar selected = $(elem).hasClass('tabs-selected');\n\t\t$(elem).hide();\n\t\t//setSize(container);\n\t\tif (selected) {\n\t\t\tpanel.hide();\n\t\t\tselectTab(container);\n\t\t} else {\n\t\t\tpanel.hide();\n\t\t\t//\t\t\tvar wrap = $('>div.tabs-header .tabs-wrap', container);\n\t\t\t//\t\t\tvar pos = Math.min(\n\t\t\t//\t\t\t\t\twrap.scrollLeft(),\n\t\t\t//\t\t\t\t\tgetMaxScrollWidth(container)\n\t\t\t//\t\t\t);\n\t\t\t//\t\t\twrap.animate({scrollLeft:pos}, opts.scrollDuration);\n\t\t}\n\t\tsetScrollers(container); //add by cy 重置表头\n\t}",
"function deactivateTabs () {\n for (t = 0; t < tabs.length; t++) {\n tabs[t].setAttribute('aria-selected', 'false');\n tabs[t].classList.remove('active');\n };\n\n for (p = 0; p < panels.length; p++) {\n panels[p].classList.remove('show');\n panels[p].classList.remove('active');\n };\n }",
"function i2uiToggleTabNoop()\r\n{\r\n}",
"closeTab () {\n if (this.currentTab) {\n this.currentTab.contentElement.setAttribute('aria-hidden', 'true')\n this.setAriaSelected(this.currentTab.titleElement, false)\n this.setAriaSelected(this.tabNavItems[this.currentTab.position], false)\n this.previousTab = this.currentTab\n this.currentTab = null\n }\n }",
"function switchOff() {\n stopGame(); \n infoscreen.text('Game is switched off'); \n usedPattern = []; //usedPattern array is empty\n gameSwitchedOn = false; //sets var gameSwitchedOn status to false\n strictMode = false; //strict mode is off\n $('.levelButton').css('background-color', 'lightskyblue'); //all level buttons get the same color\n }",
"function onSwitch(tabId) {\n var selectorForId = \"[data-tab-group='flink-tabs'][data-tab-item='\" + tabId + \"']\";\n\n Array\n // find all tab group elements on the page\n .from(document.getElementsByClassName(\"book-tabs\"))\n // filter out any elements that do not contain \n // the specific tab the user wants to switch to.\n // these tabs should remain on their current selection\n .filter(div => div.querySelectorAll(selectorForId).length > 0)\n // extract the input elements for all tab groups\n // that do contain the target tab id\n .flatMap(div => Array.from(div.querySelectorAll(\"[data-tab-group='flink-tabs']\")))\n // check input elements that contain the selected tabId\n // and uncheck all others\n .forEach(input => {\n if (input.matches(selectorForId)) {\n input.setAttribute(\"checked\", \"checked\")\n } else {\n input.removeAttribute(\"checked\")\n }\n });\n}",
"function unselectCCodeTab() {\n if (isCCodeTabSelected()) {\n selectMCodeTab();\n }\n}",
"function i2uiToggleVerticalTab(tabset_id, alttext, tab_element)\r\n{\r\n // handle Netscape 4.x\r\n if (document.layers)\r\n {\r\n var item;\r\n\r\n // display new description\r\n item = document.layers[tabset_id+\"_description\"];\r\n if (item != null)\r\n {\r\n var text = '<DIV style=\"color:#ffffff;background-color:#9999cc;text-align:left;position:absolute;top:0;left:0\">'+alttext+'</DIV>';\r\n item.document.open();\r\n item.document.write(text);\r\n item.document.close();\r\n }\r\n }\r\n else\r\n // handle IE and Netscape 6\r\n {\r\n if (tab_element.tagName == 'undefined' ||\r\n tab_element.tagName == null)\r\n {\r\n return;\r\n }\r\n\r\n //i2uitrace(1,\"activate=\"+tab_element.tagName);\r\n\r\n var item = document.getElementById(tabset_id);\r\n //i2uitrace(1,\"item=\"+item.tagName+\"\\n\"+\"TABLE body\\n\"+item.innerHTML);\r\n\r\n var item3 = item.getElementsByTagName('TBODY')[0];\r\n //i2uitrace(1,\"TBODY body\\n\"+item3.innerHTML);\r\n\r\n var len;\r\n var len2 = item3.getElementsByTagName('TR').length;\r\n //i2uitrace(1,\"#TR=\"+len2);\r\n if (len2 > 0)\r\n {\r\n var item2;\r\n var located = -1;\r\n var selectedtabid = \"tabSelected\";\r\n var unselectedtabid = \"tabUnSelected\";\r\n\r\n for (var j=0; j<len2; j++)\r\n {\r\n item = item3.getElementsByTagName('TR')[j];\r\n //i2uitrace(1,\"TR #\"+j+\" body\\n\"+item.innerHTML);\r\n len = item.getElementsByTagName('TD').length;\r\n //i2uitrace(1,\"#TD=\"+len);\r\n\r\n // turn off selected tab\r\n for (var i=0; i<len; i++)\r\n {\r\n item2 = item.getElementsByTagName('TD')[i];\r\n //i2uitrace(1,\"TD #\"+i+\" body\\n\"+item2.innerHTML);\r\n //i2uitrace(1,\"TD #\"+i+\" class=\"+item2.className+\" classid=\"+item2.id);\r\n if (item2.id == \"tabSelectedVert\")\r\n {\r\n item2.id = \"tabUnSelectedVert\";\r\n }\r\n else\r\n {\r\n if (item2.id == \"tabSelectedVert2\")\r\n {\r\n item2.id = \"tabUnSelectedVert2\";\r\n }\r\n }\r\n\r\n // find any child anchors\r\n if (item2.getElementsByTagName('A').length > 0)\r\n {\r\n item2 = item2.getElementsByTagName('A')[0];\r\n if (item2 == tab_element)\r\n {\r\n //i2uitrace(1,\"found A at \"+i);\r\n located = j;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"TD #\"+i+\" other class=\"+item2.className+\" id=\"+item2.id);\r\n if (item2.id == \"tabSelectedVert\")\r\n {\r\n item2.id = \"tabUnSelectedVert\";\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"new tab at \"+located);\r\n\r\n // now turn on the new tab\r\n if (located > -1)\r\n {\r\n item = tab_element.parentElement;\r\n if (item != null)\r\n {\r\n //i2uitrace(1,\"located parent=\"+item.tagName);\r\n item = item.parentElement;\r\n }\r\n\r\n if (item != null)\r\n {\r\n item2 = item.getElementsByTagName('TD')[0];\r\n if (item2 != null)\r\n {\r\n //i2uitrace(1,\"TD 0 fix this. class=\"+item2.className+\" id=\"+item2.id);\r\n item2.id = \"tabSelectedVert\";\r\n }\r\n item2 = item.getElementsByTagName('TD')[1];\r\n if (item2 != null)\r\n {\r\n //i2uitrace(1,\"TD 1 fix this. class=\"+item2.className+\" id=\"+item2.id);\r\n item2.id = \"tabSelectedVert2\";\r\n if (item2.getElementsByTagName('A').length > 0)\r\n {\r\n item2 = item2.getElementsByTagName('A')[0];\r\n //i2uitrace(1,\"..TD #\"+i+\" fix this A. class=\"+item2.className+\" id=\"+item2.id+\" newclass=\"+selectedtabid);\r\n item2.id = \"tabSelectedVert\";\r\n }\r\n }\r\n }\r\n\r\n item = item3.getElementsByTagName('TR')[located+1];\r\n if (item != null)\r\n {\r\n var len = item.getElementsByTagName('TD').length;\r\n //i2uitrace(1,\"located grandparent=\"+item.tagName+\" with \"+len+\" TDs\");\r\n for (i=0; i<len; i++)\r\n {\r\n item2 = item.getElementsByTagName('TD')[i];\r\n if (item2 != null)\r\n {\r\n //i2uitrace(1,\"TD #\"+i+\" fix this. class=\"+item2.className+\" id=\"+item2.id);\r\n item2.id = \"tabSelectedVert\";\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n //i2uitrace(1,document.getElementById(tabset_id).innerHTML);\r\n\r\n // set new description\r\n if (item != null)\r\n {\r\n item = document.getElementById(tabset_id+\"_description\");\r\n }\r\n if (item != null)\r\n {\r\n item.innerHTML = alttext;\r\n }\r\n }\r\n}",
"function updateHistoryTab(tab) {\n if (_historyObj && !isNaN(tab) && tab !== null) {\n _historyObj.tab = tab;\n } else {\n if (_historyObj) {\n delete _historyObj['tab'];\n }\n }\n } //****************************************************************",
"_deactivateUnselectedTabs () {\n this.panels.forEach((panel, index) => {\n if (!this._panelShouldBeActivated(panel)) {\n this._deactivateTab(panel, index)\n }\n })\n }",
"function kill_tabs() {\n\tbrowser.tabs.query({currentWindow: true}).then(function (tabs) {\n\t\tif (!tabs.length) return;\n\n\t\ttabs.map(function(o){\n\t\t\treturn {\"url\": o.url.split(\"#\")[0], \"id\": o.id}; //!\n\t\t}).forEach(function(item, i, arr){\n\t\t\tlet z = tabs.filter(function(o) {\n\t\t\t\tif (item.url == o.url)\n\t\t\t\t\treturn o.id;\n\t\t\t}).map(function(o) {\n\t\t\t\treturn o.id;\n\t\t\t});\n\n\t\t\tif (!z.length) return;\n\n\t\t\tz.shift();\n\t\t\tbrowser.tabs.remove(z);\n\t\t});\n\t});\n}",
"function mouseOutTab(i){\n\tvar n=i.substring(i.length-1,i.length);\n\tvar tab_body_display=document.getElementById(\"tab_body\"+n).style.display;\n\tif(tab_body_display==\"none\"){\n\t\tdocument.getElementById(i).style.borderBottomColor=\"gray\";\n\t}\n}",
"function clearTab() {\n removeAllChildren(getMainTab());\n}",
"function _jsTabControl_switchTo(idTo, idFrom) {\n\tdocument.getElementById(idFrom).style.visibility = \"hidden\";\n\tdocument.getElementById(idFrom).style.top = \"-1000pt\";\n\tdocument.getElementById(idTo).style.visibility = \"visible\";\n\tdocument.getElementById(idTo).style.top = this.top;\t\n}",
"function useTab(props) {\n var {\n isDisabled,\n isFocusable\n } = props,\n htmlProps = _objectWithoutPropertiesLoose(props, [\"isDisabled\", \"isFocusable\"]);\n\n var {\n setSelectedIndex,\n isManual,\n id,\n setFocusedIndex,\n enabledDomContext,\n domContext,\n selectedIndex\n } = useTabsContext();\n var ref = (0, _react.useRef)(null);\n /**\n * Think of `useDescendant` as the function that registers tab node\n * to the `enabledDomContext`, and returns it's index.\n *\n * Tab is registered if it's enabled or focusable\n */\n\n var enabledIndex = (0, _descendant.useDescendant)({\n disabled: Boolean(isDisabled),\n focusable: Boolean(isFocusable),\n context: enabledDomContext,\n element: ref.current\n });\n /**\n * Registers all tabs (whether disabled or not)\n */\n\n var index = (0, _descendant.useDescendant)({\n context: domContext,\n element: ref.current\n });\n var isSelected = index === selectedIndex;\n\n var onClick = () => {\n setFocusedIndex(enabledIndex);\n setSelectedIndex(index);\n };\n\n var onFocus = () => {\n var isDisabledButFocusable = isDisabled && isFocusable;\n var shouldSelect = !isManual && !isDisabledButFocusable;\n\n if (shouldSelect) {\n setSelectedIndex(index);\n }\n };\n\n var clickable = (0, _clickable.useClickable)(_extends({}, htmlProps, {\n ref: (0, _utils.mergeRefs)(ref, props.ref),\n isDisabled,\n isFocusable,\n onClick: (0, _utils.callAllHandlers)(props.onClick, onClick)\n }));\n var type = \"button\";\n return _extends({}, clickable, {\n id: makeTabId(id, index),\n role: \"tab\",\n tabIndex: isSelected ? 0 : -1,\n type,\n \"aria-selected\": isSelected ? true : undefined,\n \"aria-controls\": makeTabPanelId(id, index),\n onFocus: (0, _utils.callAllHandlers)(props.onFocus, onFocus)\n });\n}",
"function deactivate() {\n // this method is called when your extension is deactivated\n}",
"function mapTabIdToRecordingMode(tabId)\n{\n\tvar mode;\t\n if (tabId == \"tab-id-recordingLiveMode\")\n {\n \tmode = RECORDINGMODE_LIVE_MODE;\n }\n else if (tabId == \"tab-id-recordingOfflineMode\")\n {\n \tmode = RECORDINGMODE_OFFLINE_MODE;\n }\n //alert(mode);\n\treturn mode;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
metghod creating a game object and adding it to the team's games array | addGame(opponent, teamPoints, opponentPoints) {
const game = {
opponent,
teamPoints,
opponentPoints
}
//pushes to an array
this._games.push(game)
} | [
"addGame(opponentName, teamPoints, opponentPoints) {\n let game = {\n opponent: opponentName,\n teamPoints: teamPoints,\n opponentPoints: opponentPoints\n }\n // adds the new game to the _games array\n this._games.push(game);\n }",
"init_teams(teams)\n {\n console.log(teams);\n this.teams = {};\n // insert each team object in the teams array\n Object.keys(teams).forEach((t, idx) =>\n {\n // this.teams.push(new this.team_class(this, team_name, teams[team_name], idx));\n this.teams[teams[t][\"name\"]] = new this.team_class(this, teams[t][\"name\"], teams[t][\"score\"], idx, teams[t][\"color\"]);\n });\n }",
"function getOrCreateGame() {\r\n if (games.length <= 0 || games[games.length - 1].players.length >= 2) {\r\n games.push(new Game());\r\n }\r\n\r\n return games[games.length - 1];\r\n}",
"function create(ids,names,gameid){\r\n var ng = new Game(gameid);\r\n if (ids.length < 12){\r\n var roles=[\"WW\",\"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 6); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }else if((ids.length > 11 && ids.length < 18)){\r\n var roles=[\"WW\",\"WW\",\"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 7); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }else if((ids.length > 17 )){\r\n var roles=[\"WW\",\"WW\",\"WW\", \"WW\",\"Seer\",\"Witch\",\"Hunter\",\"Cupid\"];\r\n for (i = 0; i < (ids.length - 8); i++) {\r\n roles.push(\"Villager\");\r\n }\r\n }\r\n shuffled=shuffle(roles);\r\n for (i = 0; i < (ids.length); i++){\r\n var np = new GamePlayer(ids[i], names[i], shuffled[i]);\r\n np.checkwitch();\r\n final_players.push(np)\r\n console.log(\"np.id display role \");\r\n ng.addplayer(np);\r\n ng.Roles.push(np.role);\r\n ////////\r\n }\r\n return ng;\r\n\r\n }",
"addPlayer(firstName, lastName, age) {\n const player = {\n firstName,\n lastName,\n age\n }\n //pushes to an array\n this._players.push(player);\n }",
"function createGame() {\n console.log('Creating game...');\n socket.emit('create', {size: 'normal', teams: 2, dictionary: 'Simple'});\n}",
"function _createTeams() {\n gTeams = storageService.load('teams')\n storageService.store('teams', gTeams)\n}",
"function addGame() {\n console.log(\"in addGame...\");\n\n //only make new game if current game is empty\n // if ((vm.currentGame === null) || (vm.currentGame.gameInProgress || vm.currentGame.postGame)) {\n \n vm.games.$add(blankBoard)\n .then(function(ref) {\n setCurrentGame(ref.key());\n // vm.currentGame.time = Firebase.ServerValue.TIMESTAMP;\n vm.currentGame.time = new Date().getTime();\n saveCurrentGame();\n }, catchError);\n }",
"function createGamePage() {\n var gamePage = document.createElement('main');\n gamePage.classList.add('game-board');\n gamePage.innerHTML = getGamePageStructure();\n body.appendChild(gamePage);\n showRecentGames(deck.player.name, '.win-game-list-one');\n}",
"function createPieces(team) {\n var row = 0;\n var column = 1;\n // Creates 12 pieces for the team\n if (team === 'red') {\n for (i = 0; i < 12; i++) {\n game.redTeam[i] = new Piece(team, i, row, column);\n };\n for (i = 0; i < 3; i++) {\n game.redTeam[i*4].row = i;\n game.redTeam[i*4 + 1].row = i;\n game.redTeam[i*4 + 2].row = i;\n game.redTeam[i*4 + 3].row = i;\n };\n var n = 0;\n for (i = 0; i < 12; i++) {\n if (isOdd(game.redTeam[i].row)) {\n game.redTeam[i].column = n;\n } else {\n game.redTeam[i].column = n + 1;\n };\n if (n < 6) {\n n = n + 2;\n } else {\n n = 0;\n };\n };\n } else if (team === 'white') {\n for (i = 0; i < 12; i++) {\n game.whiteTeam[i] = new Piece(team, i, row, column);\n };\n for (i = 0; i < 3; i++) {\n game.whiteTeam[i*4].row = 7 - i;\n game.whiteTeam[i*4 + 1].row = 7 - i;\n game.whiteTeam[i*4 + 2].row = 7 - i;\n game.whiteTeam[i*4 + 3].row = 7 - i;\n };\n var n = 0;\n for (i = 0; i < 12; i++) {\n if (isOdd(game.whiteTeam[i].row)) {\n game.whiteTeam[i].column = n;\n } else {\n game.whiteTeam[i].column = n + 1;\n };\n if (n < 6) {\n n = n + 2;\n } else {\n n = 0;\n };\n };\n }\n}",
"gameInit() {\n\t\tthis.curGameData = new gameData.GameData(this.genome.length);\n\t\tthis.playHist = [];\n\t\tfor (let i = 0; i < this.hist.length; i++) {\n\t\t\tthis.playHist.push(this.hist[i]);\n\t\t}\n\t}",
"createPlayerManagers() {\n dg(`creating 4 player managers`, 'debug')\n for (let i = 0; i < 4; i++) {\n let player = new PlayerManager(i, this)\n player.init()\n this._playerManagers.push(player)\n this._playerManagers[0].isTurn = true\n }\n dg('player managers created', 'debug')\n }",
"initPlayers() {\n\n for( var i = 0; i < this.gameConfig.numPlayers; i++ ) {\n this.gameConfig.players.push({\n name : '',\n imgPath : 'img/ninja-odd.png',\n killed : false,\n nameToKill: '',\n word : ''\n })\n }\n\n this.saveGameConfig();\n }",
"static loadGames() {\n let gameList = [];\n let dataFile = fs.readFileSync('./data/currentGames.json', 'utf8');\n if (dataFile === '') return gameList;\n\n let gameData = JSON.parse(dataFile);\n if (!Array.isArray(gameData)) {\n gameData = [gameData];\n }\n gameData.forEach((element) => {\n gameList.push(\n new Game(\n element.Name,\n element.Creator,\n element.CreatedOn,\n element.Players\n )\n );\n });\n\n return gameList;\n }",
"function makeNewGame() {\n // //http://localhost:5000/\n //https://lit-retreat-32140.herokuapp.com/games/new\n\n postData('https://lit-retreat-32140.herokuapp.com/games/new', {\n username1: 'O',\n username2: 'x',\n }).then((data) => {\n if (data.game) {\n gameId = data.game._id;\n\n drawBoard();\n }\n });\n}",
"function setUpGame() {\n game = new Game();\n var width = document.documentElement.clientWidth;\n var height = document.documentElement.clientHeight;\n ctx = game.create('canvas-1', width, height);\n player = new Player();\n}",
"async function createGame(data) {\n let email = data.mail;\n\n // Creates the game entry\n const post = await prisma.game.create({\n data: {\n game_name: data.game_name,\n player: { connect: { email: email } },\n boundary: data.bound,\n time_limit: data.time,\n start_coord_long: data.start_long,\n start_coord_lat: data.start_lat,\n link: \"placeholder\",\n },\n include: {\n player: true, // Include all posts in the returned object\n },\n });\n\n // Grabs the game that was just inputted into the database\n let lastGame = await prisma.game\n .findFirst({\n orderBy: {\n id: \"desc\",\n },\n })\n .then((res) => {\n return res;\n });\n\n // The list of clues and hints to store\n let hintList = [];\n\n // Pushes all relevant clue and hint into into the array\n const hints = data.clueshints.forEach((item) => {\n return hintList.push({\n game_id: lastGame.id,\n order_num: item.order_num,\n clue: item.clue,\n hint: item.hint,\n coord_lat: item.coord.lat,\n coord_long: item.coord.lng,\n });\n });\n\n // Creates hint entries using the aforementioned list\n const createHints = await prisma.clueshint.createMany({\n data: hintList,\n skipDuplicates: true, // Skip 'Bobo'\n });\n\n return createHints;\n}",
"function createArrayOfPlayers() {\n let arrayOfPlayers = [];\n // Iterate through the array of player sprites,\n // and make new player with each sprite\n for (let i=0; i<ARRAY_PLAYER_SPRITES.length; i++) {\n arrayOfPlayers.push(new Player(ARRAY_PLAYER_SPRITES[i], i));\n }\n // Display the first player\n arrayOfPlayers[0].active = true;\n arrayOfPlayers[0].isVisible = true;\n return arrayOfPlayers;\n}",
"function GameState (state) {\n // Storage class that is passed to all players at end of turn\n this.Players = [] ;//Ordered array of players in game\n this.Name = \"\" ;// Game name\n this.id = \"\";\n this.Started = false\n this.GameOwner = 0; //Index into players array of player that owns game\n this.CurrentPlayer = 0; //Index into players array of current player\n // History is array of TurnStates keeping a detailed history of each turn.\n // Note first TurnState is only interesting in terms of initial bag state and each\n //player's tray state\n this.History = [];\n if (state) {\n this.Players = state.Players\n this.Name = state.Name\n this.id = state.id\n this.Started = state.Started \n if (state.GameOwner) this.GameOwner = state.GameOwner;\n if (state.CurrentPlayer) this.CurrentPlayer = state.CurrentPlayer;\n if (state.History ){\n var history = []\n for(var i=0;i<state.History.length;i++){\n var bag = new Bag(true, state.History[i].Bag.letters)\n var boardState = new BoardState(state.History[i].BoardState.letters)\n var turn = null;\n if (state.History[i].Turn) {\n turn = new Turn(state.History[i].Turn.Type, state.History[i].Turn.LettersIn, state.History[i].Turn.LettersOut, \n state.History[i].Turn.TurnNumber, state.History[i].Turn.Player, state.History[i].Turn.NextPlayer)\n }\n var trayStates = [];\n for(var j=0;j<state.History[i].TrayStates.length;j++){ \n trayStates.push( new TrayState(state.History[i].TrayStates[j].player, state.History[i].TrayStates[j].letters, state.History[i].TrayStates[j].score));\n }\n history.push( new TurnState(bag, boardState, trayStates, state.History[i].End, turn))\n }\n this.History = history ;\n }\n }\n this.GetNextPlayer = function() {\n var next = this.CurrentPlayer +1;\n if (next >= this.Players.length){\n next =0;\n }\n return next;\n }\n this.GetPlayers = function(){\n return this.Players;\n }\n this.GetCurrentPlayerIndex = function(){\n return this.CurrentPlayer\n }\n this.GetNumberOfPlayers = function(){\n return this.Players.length;\n }\n this.IsPlayer = function(playerName){\n for (var i=0;i<Players.length;i++){\n if (playerName == Players[i]) return true;\n }\n return false;\n }\n this.GetBoardState = function(){\n var boardState = null;\n var lastTurn = this.GetLastTurn();\n if (lastTurn){\n boardState = lastTurn.GetBoardState();\n }\n return boardState;\n }\n this.CloneLastTurnState =function(){\n var last = this.GetLastTurnState();\n return last.Clone();\n }\n this.GetLastTurnState = function(){\n var lastTurnState = null;\n if (this.History.length >0 ) {\n lastTurnState = this.History[this.History.length-1]\n }\n return lastTurnState;\n }\n this.HasGameEnded = function(){\n var ended = false;\n var lastTurnState = this.GetLastTurnState();\n if (lastTurnState){\n ended = lastTurnState.End;\n }\n return ended;\n }\n \n this.GetLastTurn = function(){\n //Actually only gets last proper turn because there is no turn object in first turnState\n var lastTurn = null;\n if (this.History.length >=1 ) {\n lastTurn = this.History[this.History.length-1].Turn;\n }\n return lastTurn;\n }\n this.GetMyTrayState =function (playerName) {\n var trayState = null;\n if (this.History.length >=1 ) {\n var trays = this.History[this.History.length-1].GetTrayStates();\n if (trays) {\n for (var i=0;i<trays.length;i++){\n if (trays[i].GetPlayer() == playerName){\n trayState = trays[i]\n break;\n }\n }\n }\n }\n return trayState;\n }\n this.AddTurnState = function(turnState){\n this.History.push(turnState);\n }\n this.HasScores = function(){\n return (this.History.length > 0);\n }\n this.GetBagSize = function(){\n var count = 0;\n if (this.History.length >=1 )\n {\n count = this.History[this.History.length-1].GetBagSize();\n }\n return count;\n }\n this.GetPlayerScore = function (playerName){\n var lastTurnState = this.History[this.History.length-1];\n return lastTurnState.GetPlayerScore(playerName);\n }\n this.GetGameOwner = function(){\n return this.Players[ this.GameOwner];\n }\n this.RemoveLastState = function(){\n var lastTurnState = this.History.pop();\n var newLastTurn = this.GetLastTurn();\n if (newLastTurn){\n this.CurrentPlayer = newLastTurn.NextPlayer;\n }else{\n //This is same code at start game first player is first tray state\n this.SetCurrentPlayerByName(lastTurnState.GetTrayState(0).GetPlayer());\n }\n }\n this.SetCurrentPlayerByName = function(playerName){\n this.CurrentPlayer = 0\n for (var i=0;i<this.Players.length;i++){\n if (this.Players[i] == playerName){\n this.CurrentPlayer = i;\n break;\n }\n }\n }\n this.SetCurrentPlayer = function(index){\n this.CurrentPlayer = index; \n }\n this.GetCurrentPlayer = function(){\n var player = \"\";\n if (this.CurrentPlayer <= (this.Players.length -1) ){\n player = this.Players[this.CurrentPlayer];\n }\n return player\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a union of this set with another Set or iterable. | union(otherSet) {
let newSet = new BetterSet(this);
newSet.addAll(otherSet);
return newSet;
} | [
"function unionOfIterators() {\n var iterators = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n iterators[_i - 0] = arguments[_i];\n }\n if (iterators.length === 0) {\n return intSet.empty;\n }\n var values = [];\n for (var i = 0; i < iterators.length; i++) {\n var it = iterators[i];\n while (it.hasNext()) {\n values.push(it.next());\n }\n }\n if (values.length === 0) {\n return intSet.empty;\n }\n values.sort(function (a, b) { return a - b; }); // Default sort function is alphabetical\n var builder = ozone.intSet.builder(values[0], values[values.length - 1]);\n var lastValue = NaN;\n for (i = 0; i < values.length; i++) {\n var val = values[i];\n if (val !== lastValue) {\n builder.onItem(val);\n lastValue = val;\n }\n }\n return builder.onEnd();\n }",
"difference(otherSet) {\n return this.disjunctiveUnion(otherSet);\n }",
"relativeComplement(otherSet) {\n let newSet = new BetterSet();\n this.forEach(item => {\n if (!otherSet.has(item)) {\n newSet.add(item);\n }\n });\n return newSet;\n }",
"function unionOfOrderedIterators() {\n var iterators = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n iterators[_i - 0] = arguments[_i];\n }\n if (iterators.length === 0) {\n return intSet.empty;\n }\n var builder = ozone.intSet.builder();\n var nexts = [];\n var previous = -1;\n var smallestIndex = 0;\n for (var i = 0; i < iterators.length; i++) {\n if (iterators[i].hasNext()) {\n nexts[i] = iterators[i].next();\n if (nexts[smallestIndex] == -1 || nexts[i] < nexts[smallestIndex]) {\n smallestIndex = i;\n }\n }\n else {\n nexts[i] = -1;\n }\n }\n while (nexts[smallestIndex] >= 0) {\n if (nexts[smallestIndex] > previous) {\n builder.onItem(nexts[smallestIndex]);\n previous = nexts[smallestIndex];\n }\n nexts[smallestIndex] = iterators[smallestIndex].hasNext() ? iterators[smallestIndex].next() : -1;\n // Find the new smallest value in nexts\n smallestIndex = 0;\n for (var i = 0; i < nexts.length; i++) {\n if ((nexts[smallestIndex] == -1) || (nexts[i] != -1 && nexts[i] < nexts[smallestIndex])) {\n smallestIndex = i;\n }\n }\n }\n return mostEfficientIntSet(builder.onEnd());\n }",
"function intersection(set1, set2) {} // → set",
"complement(otherSet) {\n return this.relativeComplement(otherSet);\n }",
"function getUnionVector(v1, v2) {\r\n\t//clone v1\r\n\tvar retval = v1.slice(0);\r\n\r\n\tfor (var i = 0; i < v2.length; i++) {\r\n\t\tvar obj = v2[i];\r\n\r\n\t\tif(!v1.contains(obj)) {\r\n\t\t\tretval.push(obj);\r\n\t\t}\r\n\t}\r\n\r\n\treturn retval;\r\n}",
"function intersectionOfUnionBySetOperations(container, toUnion) {\n if (toUnion.length === 0) {\n return container;\n }\n var intersected = [];\n for (var i = 0; i < toUnion.length; i++) {\n intersected.push(container.intersection(toUnion[i]));\n }\n var result = intersected[0];\n for (var i = 1; i < intersected.length; i++) {\n result = result.union(intersected[i]);\n }\n return result;\n }",
"union(subsets, x, y) {\n let xroot = this.find(subsets, x);\n let yroot = this.find(subsets, y);\n\n if (subsets.get(xroot).rank < subsets.get(yroot).rank) {\n subsets.get(xroot).parent = yroot;\n } else if (subsets.get(xroot).rank > subsets.get(yroot).rank) {\n subsets.get(yroot).parent = xroot;\n } else {\n subsets.get(yroot).parent = xroot;\n subsets.get(xroot).rank++;\n }\n }",
"function difference(set1, set2) {} // → set",
"function intersectionOfUnionByIteration(container, toUnion) {\n if (toUnion.length === 0) {\n return container;\n }\n var containerIt = container.iterator();\n var toUnionIts = [];\n for (var i = 0; i < toUnion.length; i++) {\n toUnionIts.push(new ozone.BufferedOrderedIterator(toUnion[i].iterator()));\n }\n var builder = ozone.intSet.builder();\n while (containerIt.hasNext()) {\n var index = containerIt.next();\n var shouldInclude = toUnionIts.some(function (it) {\n it.skipTo(index);\n return it.hasNext() && it.peek() === index;\n });\n if (shouldInclude) {\n builder.onItem(index);\n }\n }\n return builder.onEnd();\n }",
"function union(){\n //let arg = [].slice.call(arguments);\n let uniq = [];\n let arr = [];\n //solving it with CONCAT!!\n for(let i=0; i<arguments.length; i++){\n \t//CONACAT RETURNS A NEW ARR, which REFERENCE has to be saved in this case using the same arr var.\n arr = arr.concat(arguments[i]);\n }\n //solving it with PUSH!!\n // for (let i=0; i<arguments.length; i++){\n // for (let j=0; j<arguments[i].length; j++){\n // //console.log(\"arg[i][j] is \" + arg[i][j]);\n // uniq.push(arguments[i][j]);\n // }\n // }\n for (let j=0; j<arr.length; j++){\n if (!uniq.includes(arr[j])) uniq.push(arr[j]);\n }\n \n return uniq;\n}",
"static union(map_a, map_b, summation = false){\n let union = this.deep_copy(map_a)\n for(let key of map_b.keys()){\n if(union.has(key)){\n if(summation)\n union.set(key, map_a.get(key) + map_b.get(key))\n }\n else\n union.set(key, map_b.get(key))\n }\n return union\n }",
"function UnionTwoArrays(array1, array2) {\n var unionOfBothArrays = array1;\n\n for (var i = 0; i < array2.length; i++) {\n IfUniqueAddItemToArray(array2[i], unionOfBothArrays);\n }\n return unionOfBothArrays;\n}",
"clone() {\n return new SpecialSet(this);\n }",
"function mergeUnique(arr1, arr2) {\n return arr1.concat(arr2).filter((element, index, array) => array.indexOf(element) === index)\n //return Array.from(new Set(concat(arr1, arr2))\n}",
"equals(otherSet) {\n if (this === otherSet) {\n return true;\n } else if (\n !(otherSet instanceof BetterSet) ||\n this.size !== otherSet.size\n ) {\n return false;\n } else {\n for (let value of this.values()) {\n if (!otherSet.has(value)) {\n return false;\n }\n }\n return true;\n }\n }",
"function Union() {\n var alternatives = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n alternatives[_i] = arguments[_i];\n }\n var match = function () {\n var cases = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n cases[_i] = arguments[_i];\n }\n return function (x) {\n for (var i = 0; i < alternatives.length; i++) {\n if (alternatives[i].guard(x)) {\n return cases[i](x);\n }\n }\n };\n };\n var self = { tag: 'union', alternatives: alternatives, match: match };\n return (0, runtype_1.create)(function (value, visited) {\n var e_1, _a, e_2, _b, e_3, _c, e_4, _d;\n if (typeof value !== 'object' || value === null) {\n try {\n for (var alternatives_1 = __values(alternatives), alternatives_1_1 = alternatives_1.next(); !alternatives_1_1.done; alternatives_1_1 = alternatives_1.next()) {\n var alternative = alternatives_1_1.value;\n if ((0, runtype_1.innerValidate)(alternative, value, visited).success)\n return (0, util_1.SUCCESS)(value);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (alternatives_1_1 && !alternatives_1_1.done && (_a = alternatives_1.return)) _a.call(alternatives_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return util_1.FAILURE.TYPE_INCORRECT(self, value);\n }\n var commonLiteralFields = {};\n try {\n for (var alternatives_2 = __values(alternatives), alternatives_2_1 = alternatives_2.next(); !alternatives_2_1.done; alternatives_2_1 = alternatives_2.next()) {\n var alternative = alternatives_2_1.value;\n if (alternative.reflect.tag === 'record') {\n var _loop_1 = function (fieldName) {\n var field = alternative.reflect.fields[fieldName];\n if (field.tag === 'literal') {\n if (commonLiteralFields[fieldName]) {\n if (commonLiteralFields[fieldName].every(function (value) { return value !== field.value; })) {\n commonLiteralFields[fieldName].push(field.value);\n }\n }\n else {\n commonLiteralFields[fieldName] = [field.value];\n }\n }\n };\n for (var fieldName in alternative.reflect.fields) {\n _loop_1(fieldName);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (alternatives_2_1 && !alternatives_2_1.done && (_b = alternatives_2.return)) _b.call(alternatives_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n for (var fieldName in commonLiteralFields) {\n if (commonLiteralFields[fieldName].length === alternatives.length) {\n try {\n for (var alternatives_3 = (e_3 = void 0, __values(alternatives)), alternatives_3_1 = alternatives_3.next(); !alternatives_3_1.done; alternatives_3_1 = alternatives_3.next()) {\n var alternative = alternatives_3_1.value;\n if (alternative.reflect.tag === 'record') {\n var field = alternative.reflect.fields[fieldName];\n if (field.tag === 'literal' &&\n (0, util_1.hasKey)(fieldName, value) &&\n value[fieldName] === field.value) {\n return (0, runtype_1.innerValidate)(alternative, value, visited);\n }\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (alternatives_3_1 && !alternatives_3_1.done && (_c = alternatives_3.return)) _c.call(alternatives_3);\n }\n finally { if (e_3) throw e_3.error; }\n }\n }\n }\n try {\n for (var alternatives_4 = __values(alternatives), alternatives_4_1 = alternatives_4.next(); !alternatives_4_1.done; alternatives_4_1 = alternatives_4.next()) {\n var targetType = alternatives_4_1.value;\n if ((0, runtype_1.innerValidate)(targetType, value, visited).success)\n return (0, util_1.SUCCESS)(value);\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (alternatives_4_1 && !alternatives_4_1.done && (_d = alternatives_4.return)) _d.call(alternatives_4);\n }\n finally { if (e_4) throw e_4.error; }\n }\n return util_1.FAILURE.TYPE_INCORRECT(self, value);\n }, self);\n}",
"function collect(s1, s2) {\n for (let elem of s2) {\n s1.add(elem);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called by PluginManager upon receiving the __FxComponentUnLoadComplete event | function onUnloaded() {
Media.log('PluginComponent::onUnloaded ' + id());
assert(pluginObj);
pluginObj.onObjectUnloaded();
} | [
"unregisterLoadCallback () {\n this.loadCallback = null;\n }",
"static finishedRenderingComponent() {\n\t\trenderingComponents_.pop();\n\t\tif (renderingComponents_.length === 0) {\n\t\t\tIncrementalDomUnusedComponents.disposeUnused();\n\t\t}\n\t}",
"function loadComponent() {\n Media.log('PluginComponent::loadComponent ' + id());\n assert(state() == PluginComponent.State.Loading);\n assert(pluginObj.state() == Media.PluginObject.State.Attached);\n var args;\n try {\n args = Media.PluginDataHandler.generateBlob.apply(null, loadParams);\n pluginObj.innerObject().Load(specs.type, args);\n }\n catch (error) {\n debugger;\n cleanupPluginObject();\n state.set(PluginComponent.State.Unloaded);\n }\n }",
"function uninit() {\n Media.log('PluginManager::uninit');\n if (state() == Media.PluginManager.State.Deinitialized)\n return;\n assert(!task || task.promise.state() != 'pending');\n task = new Task('Unloading the media plugin.');\n try {\n // unload components\n for (var id in components)\n components[id].unload();\n pluginObj.innerObject().UnLoad();\n }\n catch (error) {\n cleanupPluginObject(error);\n state.set(Media.PluginManager.State.Deinitialized);\n if (!isCanceled)\n task.reject();\n }\n stopLoadTimer();\n stopPingTimer();\n return task.promise;\n }",
"function optionViewLoaded() {\r\n disableDataUpdate();\r\n LoadingBar.hide();\r\n }",
"disconnectedCallback() {\n this.removeBindings();\n }",
"onBeforeUnload(callback) {\n return this.windowEventHandler.addUnloadCallback(callback);\n }",
"beforeUnmount() {\n this.observer.disconnect(), this.flatpickrInstance && this.flatpickrInstance.destroy();\n }",
"componentWillUnmount() {\n this.props.fnEraseCityStateData();\n }",
"dispose() {\n this.context = null;\n\n // remove all global event listeners when component gets destroyed\n window.removeEventListener('message', this.sendUpdateTripSectionsEvent);\n }",
"_unbindLayoutAnimationEndEvent() {\n const menu = this.getMenu()\n\n if (this._transitionCallbackTimeout) {\n clearTimeout(this._transitionCallbackTimeout)\n this._transitionCallbackTimeout = null\n }\n\n if (menu && this._transitionCallback) {\n TRANS_EVENTS.forEach(e => {\n menu.removeEventListener(e, this._transitionCallback, false)\n })\n }\n\n if (this._transitionCallback) {\n this._transitionCallback = null\n }\n }",
"function handleImportTrackRemove() {\n //remove the track from the map\n theInterface.emit('ui:removeTrack');\n }",
"componentWillUnmount(){\n this.props.getProviderErase();\n }",
"loadFailed( exception ) {\n if (this.onFailure) {\n this.onFailure( exception );\n } else {\n console.log( \"Error loading world \"+this.name, exception);\n }\n if ( this.indicator ) {\n this.indicator.remove(this.name);\n }\n }",
"function onCompleteCallback() {\n imagesPendingLoad--;\n imagesPendingLoad == 0 && ONCOMPLETE in options && options[ONCOMPLETE]();\n }",
"handleLoaded(itemName) {\n this.toLoad = this.toLoad.filter(item => item !== itemName);\n\n if (this.toLoad.length === 0) {\n this.callbacks.onLoaded();\n }\n }",
"function onExecutableModuleDisposed() {\n goog.dom.classlist.remove(goog.dom.getElement('crash-warning'), 'hidden');\n}",
"disconnectedCallback() {\n if (this._form) {\n this._form.removeEventListener('formdata', this._handleFormData);\n this._form = null;\n }\n }",
"componentWillUnmount() {\n if (!this.diagramRef.current) return;\n const diagram = this.diagramRef.current.getDiagram();\n if (diagram) {\n diagram.removeDiagramListener('ChangedSelection', this.props.onDiagramEvent);\n diagram.removeDiagramListener('ObjectDoubleClicked', this.props.onDiagramDoubleClicked);\n }\n }",
"componentWillUnmount() {\n this.fadeOut();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that checks whether it is necessary to load new data Loads news data if necessary Returns correct noCandlesTrans | checkAvailData() {
return new Promise((resolve, reject) => {
// check if it is necessary to load new data
if (this.dataPointer-this.noCandles < 0) {
var dir = 'left';
var message = createMessageForDataLoad(this.dtArray[0], dir);
} else if (this.dataPointer > this.priceArray.length-1) {
var dir = 'right';
var message = createMessageForDataLoad(this.dtArray.slice(-1)[0], dir);
} else { return resolve(); }
// load new data if necessary
this.isLoadingData = true;
serverRequest('loadNewData', message).then((data) => {
if (dir === 'left') {
this.dataPointer += data.length;
data = this.parseDates(data);
this.priceArray = data.concat(this.priceArray);
this.createDtArray();
} else if (dir === 'right') {
data = this.parseDates(data);
this.priceArray = this.priceArray.concat(data);
this.createDtArray();
}
return resolve();
});
});
} | [
"loadXMLData(XMLData) {\n let transactionsDetails;\n try {\n transactionsDetails = xmlParser.parseStringSync(XMLData).TransactionList.SupportTransaction;\n } catch(err) {\n logger.warn('Invalid syntax.');\n this.lastDataLoadErrorCount++;\n return false;\n }\n\n for(let i = 0; i < transactionsDetails.length; i++) {\n let objectNumber = i + 1;\n let transactionDetails = transactionsDetails[i];\n\n if(!this.addTransaction(moment.fromOADate(transactionDetails.$.Date), transactionDetails.Parties[0].From[0], transactionDetails.Parties[0].To[0], transactionDetails.Description, transactionDetails.Value)) {\n logger.warn('Could not process transaction number ' + objectNumber + ': ' + this.lastAddTransactionError);\n this.lastDataLoadErrorCount++;\n }\n }\n\n return true;\n }",
"ifConversionRatesAvailable() {\n return !!(\n this.initialCurrencyConversionData?.rates &&\n Object.keys(this.initialCurrencyConversionData.rates).length !== 0\n );\n }",
"checkLoading() {\n if (this.props.loading.state == 'new') {\n const { centerId, reportingDate } = this.props.params\n this.props.dispatch(loadScoreboard(centerId, reportingDate))\n return false\n }\n return (this.props.loading.state == 'loaded')\n }",
"loadStocks() {\n stockService.get((err, data) => {\n if (err) return this.handleError(err);\n\n // the latest list of stocks on database\n const stocks = JSON.parse(data);\n\n // the list of stock symbols's currently on chart\n const chartedStockSymbols = this.stockChart.series.map((series) => {\n return series.name;\n });\n\n stocks.forEach((stock) => {\n // only get the pricing data of not-charted stock symbols\n if (chartedStockSymbols.indexOf(stock) == -1) {\n this.getStock(stock.symbol);\n }\n });\n\n this.stockSocket.start();\n });\n }",
"loadCSVData(CSVData) {\n let transactionStrings = CSVData.split('\\n');\n for(let i = 1; i < transactionStrings.length; i++) { // skip first row since it is header\n let lineNumber = i + 1;\n let transactionString = transactionStrings[i];\n let transactionDetails = transactionString.split(',');\n if(transactionDetails.length === 5) {\n if(!this.addTransaction(moment(transactionDetails[0], 'DD/MM/YYYY', true), transactionDetails[1], transactionDetails[2], transactionDetails[3], transactionDetails[4])) {\n logger.warn('Could not process transaction on line ' + lineNumber + ': ' + this.lastAddTransactionError);\n this.lastDataLoadErrorCount++;\n }\n } else if(transactionString.length > 0) {\n logger.warn('Could not process transaction on line ' + lineNumber + ': Not enough fields provided.');\n this.lastDataLoadErrorCount++;\n }\n }\n return true;\n }",
"function checkLiveData(teamUrl, scoreUrl){\n if ( teamDataDate === \"\" || Date.parse(teamDataDate) + 12*60*60*1000 < new Date ){\n refreshTeamData(teamUrl)\n }\n if( teamDataDate !== \"\" ){\n refreshLiveData(scoreUrl)\n }\n //add liveDataTimestamp comparison after timestamp has been set\n if( liveData.lastModified ){\n createTickerData(liveData)\n }\n}",
"isStreamingData(data){\n var isStreaming = false;\n var currTime = Math.floor(new Date().getTime());\n if(data && data.length && data.hasOwnProperty('latestTime') && data.latestTime > currTime - 30000){\n isStreaming = true;\n }\n return isStreaming;\n }",
"function loadArticles() {\n\t\t// Count Down\n\t\tlet i = articlesPerLoad; \n\t\t\n\t\twhile (i > 0) {\n\t\t\tif(articlesLoaded <= maxArticles) {\n\t\t\t\t// \"articlesLoaded\" is also the key of the array\n\t\t\t\tgetArticleData(storyIDs[articlesLoaded]); \n\t\t\t\tarticlesLoaded++;\n\t\t\t}\n\t\t\ti--;\n\t\t}\n\t}",
"hasLoadedAnyDataFiles() {\n return this.loadedDataFiles.length > 0;\n }",
"function loadLocalData() {\r\n var xmlhttp=new XMLHttpRequest();\r\n xmlhttp.open(\"GET\",\"Buses.xml\",false);\r\n xmlhttp.send();\r\n xmlData=xmlhttp.responseXML;\r\n generateBusList(xmlData, \"SAMPLE\");\r\n loadRouteColors(); // Bus list must be loaded first\r\n displayRoutesFromTripId(tripRouteShapeRef); // Bus list must be loaded first to have the trip IDs\r\n showPOIs();\r\n getTrolleyData(scope);\r\n loadTrolleyRoutes();\r\n getTrolleyStops(scope);\r\n getCitiBikes();\r\n addDoralTrolleys();\r\n addDoralTrolleyRoutes();\r\n addMetroRail();\r\n addMetroRailRoutes();\r\n addMetroRailStations();\r\n addMiamiBeachTrolleys();\r\n addMiamiBeachTrolleyRoutes();\r\n // Refresh Miami Transit API data every 5 seconds\r\n setInterval(function() {\r\n callMiamiTransitAPI();\r\n }, refreshTime);\r\n if (!test) {\r\n alert(\"Real-time data is unavailable. Check the Miami Transit website. Using sample data.\");\r\n }\r\n}",
"function is_data_stale() {\n\treturn last + max_age < Date.now();\n}",
"function loadTrackstatusData() {\n var path = [{ url: 'project/trackStatus/trackStatusData.json', method: \"GET\" }];\n PPSTService.getJSONData(path).then(function (response) {\n $scope.statusListData = response[0].data; // data for track status\n //$scope.loaderFlag = false;\n trackStatusService.dataChange();\n //trackStatusService.getChange();\n }).catch(function (err) {\n console.error(\"error fecthing tracj status data\");\n });\n }",
"function chartsLoaded() {\n chartLibraryLoaded = true; // Global var which can be checked before attempting to draw chart\n drawChart() // try to draw chart\n}",
"hasLoadedDataFile(fileName) {\n return this.loadedDataFiles.indexOf(fileName) >= 0;\n }",
"function fetchOpeningTimes () {\n\t\tParkingService.getTimesForOne (ParkingService.data.selectedParking.id).then(function(response) {\n\t\t\t\n\t\t\t// save result to model\n\t\t\tParkingService.data.selectedParking.openingtimes = response;\n\t\t\t\n\t\t\t// hide table if no opening time data:\n\t\t\tif (response == false){ \n\t\t\t\tconsole.log ('no times available');\n\t\t\t\tParkingService.data.selectedParking.noTimesFlag = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t}",
"function restoreCheckData(){\r\n var titleStr = GM_getValue(NICORANK_MARK_TITLE);\r\n // GM_log(\"[rank]load:\" + titleStr);\r\n if(titleStr){\r\n nicoRankMarkTitles = titleStr;\r\n }\r\n}",
"function checkNews(data) {\n var $data = $(data);\n var news = $data.find('.new-activity');\n\n $data.find('.activity-mini li:not(:last-child)').each(function () {\n var itemActivityplayerId = $(this).find('a[href]')[0].pathname.replace('/', '');\n var itemActivityText = $(this).text().replace(/(\\r\\n|\\n|\\r)/gm, \"\").replace(/ +/g, ' ');\n var itemActivityID = itemActivityplayerId + '+' + $(this).attr('class') + '+' + $(this).find('>a').text().split(' ').join('-');\n if (news.length) {\n if (storedNewsID.indexOf(itemActivityID) == -1) {\n storedNewsID.push(itemActivityID);\n console.log('Hey cowboy. We\\'ve got news!')\n fillNotification(itemActivityplayerId, itemActivityText, itemActivityID);\n }\n }\n });\n if (news.length) {\n showBadge();\n } else {\n clearBadge();\n }\n\n}",
"function crawlStarted() {\n return ($localStorage.currentCrawl !== undefined);\n }",
"shouldLazyLoad() {\n // We do not want lazy loading on pageskins because it messes up the roadblock\n // Also, if the special dll parameter is passed with a value of 1, we don't lazy load\n return !config.get('page.hasPageSkin') && getUrlVars().dll !== '1';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return displayable mentions per party for the specified topic. If too many, a random sample of matching mentions is returned. Mentions are returned in chronological order. | function findMentions(topic) {
return data.parties.map(function(party, i) {
var mentions = topic.parties[i].mentions;
if (mentions.length > maxMentions) {
shuffle(mentions).length = maxMentions;
mentions.sort(orderMentions);
mentions.truncated = true;
}
return mentions;
});
} | [
"async function loadPublicMemes() {\n const response = await fetch(url + '/api/memes/filter=public');\n if (response.ok) {\n const pubmemes = await response.json();\n return pubmemes.map(m => new Meme(m.id, m.title, url + m.url, m.sentence1, m.sentence2, \n m.sentence3, m.cssSentencesPosition.split(\",\"), m.cssFontClass, \n m.cssColourClass, Boolean(m.protected), m.name, m.user))\n }\n return [];\n}",
"function getMostPopularEmailed() {\n var url = 'https://api.nytimes.com/svc/mostpopular/v2/mostemailed/Magazine/7.json';\n let params = {\n q: 'query',\n 'api-key': '85b2939e3df349dd8502775e8623d350'\n }\n url += '?' + $.param(params)\n $.ajax({\n url: url,\n method: 'GET',\n }).done(function(data) {\n console.log(data);\n\n // Define which results will be displayed and display them\n for (var i = 0; i < 5; i++) {\n var title = data.results[i].title;\n $('.emailed').show();\n var article_url = data.results[i].url;\n var abstract = data.results[i].abstract;\n\n // Use bracket notation for media-metadata\n var image = data.results[i].media[0]['media-metadata'][0].url;\n console.log(image);\n \n // Display results in HTML\n $('#results-emailed').append(\"<li><h3>\" + title + \n \"</h3>\" + abstract + \"<br><br>\" + \"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a></li>\");\n $('#summary-emailed').append(\"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a>\");\n } \n }).fail(function(err) {\n throw err;\n });\n }",
"refreshMentions()\n {\n this.mentions = this.messageRaw.match(/<@(?:\\d){13}>/g) === null ? [] : new Array(...this.messageRaw.match(/<@(?:\\d){13}>/g));\n if (this.mentions.includes(`<@${thisUser.id}>`) && !this.msg.classList.contains('mention'))\n {\n $(this.msg).addClass('mention');\n if (document.visibilityState === 'hidden')\n {\n document.title = `${document.title.match(/\\d+/) === null ? 1 : parseInt(document.title.match(/\\d+/)[0]) + 1}🔴 🅱️iscord`;\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible')\n {\n document.title = '🅱️iscord';\n }\n }, { once: true });\n }\n }\n else if (!this.mentions.includes(`<@${thisUser.id}>`) && this.msg.classList.contains('mention'))\n {\n $(this.msg).removeClass('mention');\n document.title = `${document.title.match(/\\d+/) === null ? '' : parseInt(document.title.match(/\\d+/)[0]) - 1 <= 0 ? '' : `${parseInt(document.title.match(/\\d+/)[0]) - 1}🔴 `}🅱️iscord`;\n }\n }",
"function randomTopic()\n{ \n return Math.floor(Math.random()*ribbon_data.length);\n}",
"function showForumTopic(topicID)\r\n{\r\n topic = getForumTopicByID(topicID);\r\n if(topic == null)\r\n return;\r\n \r\n contents = '<h1>' + topic.title + '</h1>';\r\n participant = getParticipantByID(topic.participantID);\r\n if(participant == null)\r\n contents += '<h2>By: Removed participant</h2>';\r\n else\r\n contents += '<h2>By: ' + participant.name + ' ' + participant.surname + '</h2>';\r\n contents += '<p>' + topic.date + '</p>';\r\n contents += '<p>' + topic.text + '</p>';\r\n contents += '<h2>Replies:</h2>';\r\n contents += '<ul>';\r\n for(reply in topic.replies)\r\n {\r\n participant = getParticipantByID(topic.replies[reply].participantID);\r\n contents += '<li>';\r\n if(participant == null)\r\n contents += '<h2>By: Removed participant</h2>';\r\n else\r\n contents += '<h2>By: ' + participant.name + ' ' + participant.surname + '</h2>';\r\n contents += '<p>' + topic.replies[reply].date + '</p>';\r\n contents += '<p>' + topic.replies[reply].text + '</p>';\r\n contents += '</li>';\r\n }\r\n contents += '</ul>';\r\n //Add the reply textbox\r\n contents += '<h2>Reply:</h2>';\r\n contents += '<textarea id=\"forum-topic-reply-area\"></textarea>';\r\n contents += '<input id=\"forum-reply-button\" type=\"button\" value=\"Reply\" class=\"submit\" onclick=\"onForumTopicReplyClicked(' + topicID + ')\"/>';\r\n \r\n document.getElementById(\"center-panel\").innerHTML = contents;\r\n}",
"function send_popular_feeds(recipientId) {\n for (var index in recipientId) {\n sendMessage(recipientId[index]['fb_id'], { text: \"Today's Most Popular Stories\" });\n popular_news(recipientId[index]['fb_id']);\n\n }\n}",
"function showchats(target, context) {\r\n var viewer = context.username;\r\n\r\n var i = 0;\r\n while (i <= viewerObj.length) {\r\n if (viewerObj[i] == viewer) {\r\n sendMessage(target, context, context.username + ' has chatted ' + chatObj[i] + ' times!');\r\n console.log(\"viewer is in hugs array\")\r\n break;\r\n }\r\n else if (i == viewerObj.length) {\r\n console.log(viewer + \" is not in array\");\r\n sendMessage(target, context, context.username + ' has not chatted!');\r\n break;\r\n }\r\n i++;\r\n } \r\n}",
"function TopicMonitorController($scope, mediator) {\n $scope.topics = [];\n\n $scope.clearTopicList = function() {\n $scope.topics = [];\n };\n\n mediator.subscribe('wfm:user:list', function() {\n $scope.topics.push({\n topic: 'wfm:user:list',\n time: moment(new Date())\n });\n });\n\n mediator.subscribe('done:wfm:user:list', function() {\n $scope.topics.push({\n topic: 'done:wfm:user:list',\n time: moment(new Date())\n });\n });\n\n mediator.subscribe('wfm:user:create', function(userToCreate) {\n $scope.topics.push({\n topic: 'wfm:user:create',\n time: moment(new Date()),\n user: JSON.stringify(userToCreate)\n });\n });\n\n mediator.subscribe('done:wfm:user:create', function(createdUser) {\n $scope.topics.push({\n topic: 'done:wfm:user:create',\n time: moment(new Date()),\n user: JSON.stringify(createdUser)\n });\n });\n\n}",
"function mentions(tweet) {\n var string = tweet.split(\" \");\n var hash = [];\n for (var i = 0; i < string.length; i++) {\n if (string[i].startsWith(\"@\")) {\n hash.push(string[i]);\n }\n }\n return hash;\n}",
"function updateMemberList() {\n people_list = RTMchannel.getMembers().toString(); // gets list of channel members\n document.getElementById(\"people_list\").innerHTML = \"<u>People</u>: \" + people_list.toString();\n}",
"function getMostPopularShared() {\n var url = 'https://api.nytimes.com/svc/mostpopular/v2/mostshared/Magazine/7.json';\n let params = {\n q: 'query',\n 'api-key': '85b2939e3df349dd8502775e8623d350'\n }\n url += '?' + $.param(params)\n $.ajax({\n url: url,\n method: 'GET',\n }).done(function(data) {\n console.log(data);\n\n // Define which results will be displayed and display them\n for (var i = 0; i < 5; i++) {\n var title = data.results[i].title;\n $('.shared').show();\n var article_url = data.results[i].url;\n var abstract = data.results[i].abstract;\n\n // Use bracket notation for media-metadata\n var image = data.results[i].media[0]['media-metadata'][0].url;\n console.log(image);\n \n // Display results in HTML\n $('#results').append(\"<li><h3>\" + title + \n \"</h3>\" + abstract + \"<br><br>\" + \"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a></li>\");\n $('#summary-shared').append(\"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a>\");\n } \n }).fail(function(err) {\n throw err;\n });\n }",
"function recommendMorePeople(postToPopulate) {\n console.log(\"recommending more people\");\n var people = postToPopulate.data('people');\n var start_person = postToPopulate.data('start_person');\n var previously_shared = postToPopulate.data('previously_shared');\n var header = postToPopulate.find(\".feedme-suggestions\");\n var div_class = 'feedme-recommendation-group-' + start_person;\n \n var min_length = start_person + moreRecommendations < people.length ?\n start_person + moreRecommendations : people.length;\n var expanded_div = null;\n \n if (start_person < min_length || people.length == 0) {\n header.append('<div class=\"expand-container feedme-recommendations-group ' + div_class + '\"></div>');\n expanded_div = postToPopulate.find('.' + div_class);\n for (var i = start_person; i < min_length; i++) {\n var person = people[i];\n addFriend(person['email'], person['email'], person['shared_today'], person['seen_it'], person['sent'], expanded_div, postToPopulate);\n }\n \n if (start_person == 0) {\n expanded_div.removeClass('expand-container');\n expanded_div.css(\"display\", \"inline\"); // so the placeholder flows with it in the same line\n \n postToPopulate.find('.feedme-recommendation-group-0').append(postToPopulate.find(\".feedme-more-recommendations\"));\n postToPopulate.find(\".feedme-more-recommendations\").css('display', '');\n \n if (people.length == 0) {\n var more_recommendations_button = postToPopulate.find('.feedme-more-recommendations-button');\n // move the more recommendations to the end of the list and make it invisible; this retains the usual layout with just the autocomplete visible\n postToPopulate.find('.feedme-recommendation-group-0').append(more_recommendations_button);\n more_recommendations_button.css('visibility', 'hidden');\n \n // Undo the special css we usually put there\n postToPopulate.find('.feedme-recommendation-group-0').css('position', 'static').css('right', '0');\n postToPopulate.find('.feedme-recommendation-group-0').prepend($('<span>FeedMe<img src=\"http://groups.csail.mit.edu/haystack/feedme/like.png\" class=\"feedme-logo-icon\" />share with: </span>'));\n }\n }\n else {\n expanded_div.slideToggle(\"normal\");\n } \n \n /*\n // Initialize previously-shared folks\n for (var j=0; j<previously_shared.length; j++) {\n var person = previously_shared[j];\n postToPopulate.find('[email=\"' + person['email'] + '\"]')\n .addClass(\"feedme-sent\")\n .find('.feedme-num-shared').text('Sent!');\n }\n */\n \n\t\t// use .outerWidth() to account for margin and padding\n\t\tvar containerWidth = postToPopulate.find(\"div.feedme-suggestions\").outerWidth(true); \t\n \t// just check width of contents of newly added div \t\n var contentWidth = 0;\n\t\texpanded_div.children(\"div.feedme-person\").each(function() {\n \t\tcontentWidth += $(this).outerWidth(true);\n\t\t});\n\t\tcontentWidth += expanded_div.find(\"div.feedme-more-recommendations-button\").outerWidth(true);\n\t\tcontentWidth += expanded_div.find(\"input.feedme-autocomplete\").outerWidth(true);\n\t\tcontentWidth += expanded_div.find(\"img.feedme-addImg\").outerWidth(true);\n\t\t\n\t\tconsole.log(containerWidth);\n\t\tconsole.log(contentWidth);\n\t\t\n\t\twhile (contentWidth >= containerWidth) {\n\t\t\t// remove last person from the newly added div\n\t\t\tcontentWidth -= expanded_div.find(\".feedme-person:last\").outerWidth(true);\n\t\t\texpanded_div.find(\".feedme-person:last\").remove();\n\t\t\t// decrement min_length so that start_person is set to correct value\n\t\t\tmin_length -= 1;\n\t\t}\n\n postToPopulate.data('start_person', min_length);\n postToPopulate.find(\".wait-for-suggestions\").removeClass(\"wait-for-suggestions\");\n }\n}",
"function getTopicInfo()\n\t{\tvar userid= {};\n\t\tvar posts ={};\n\t\t\t\t\t\n\t\t\tPostFactory.getTopicInfo($routeParams, function (result){\t\n\t\t\tif(result){\n\t\t\t\t$scope.topicInfo = result;\n\t\t\t\t//Adding the id of the user who posted the topic to an object to reuse the getClikeduser\n\t\t\t\t//method in userfactory\n\t\t\t\tuserid.id = result._user; \n\t\t\t\t//Reusing userfactory getclickeduser method to get the username of the user who posted the topic\n\t\t\t\tUserFactory.getClickedUser(userid, function (output){\n\t\t\t\t\t $scope.topicInfo.username = output.username;\n\t\t\t\t\t $scope.topicInfo.loggeduser=JSON.parse(localStorage.userinfo);\t//adding the logged in users info to send while saving the post\n\t\t\t\t});\n\t\t\t\t \n\t\t\t}\n\t\t})\n\t}",
"static listAllUsersPerArticleSeen(articleId) {\n\t\treturn RestService.get(`api/news/seen-by/${articleId}`);\n\t}",
"async function parse(message) {\r\n let txt = message.content.split(' ').slice(1).join(' ');\r\n function mentions() {\r\n if (message.mentions) {\r\n return message.mentions.users.map((usr) => usr.avatarURL);\r\n }\r\n return [];\r\n } //mentions\r\n async function emojis() {\r\n let reg = /<:.+?:(\\d+?)>/gui, matches = txt.match(reg);\r\n if (matches && matches.length) {\r\n let rets = [];\r\n matches = matches.map((match) => match.replace(reg, \"$1\"));\r\n await Classes_1.chillout.forEach(matches, (match) => {\r\n if (vale.client.emojis.has(match))\r\n rets.push(vale.client.emojis.get(match).url);\r\n });\r\n return rets;\r\n }\r\n return [];\r\n } //emojis\r\n let rets = mentions().concat(await emojis());\r\n if (rets.length)\r\n return rets;\r\n if (message.channel instanceof discord_js_1.TextChannel) {\r\n let mmbs = message.channel.members.array().sort((mmb1, mmb2) => (mmb1.nickname || '').length - (mmb2.nickname || '').length), tmp = mmbs.find((mmb) => (mmb.nickname || mmb.user.username).toLowerCase().includes(txt.toLowerCase()));\r\n if (tmp) {\r\n rets.push(tmp.user.avatarURL);\r\n }\r\n else {\r\n mmbs = mmbs.sort((mmb1, mmb2) => mmb1.user.username.length - mmb2.user.username.length);\r\n tmp = mmbs.find((mmb) => mmb.user.username.toLowerCase().includes(txt.toLowerCase()));\r\n if (tmp) {\r\n rets.push(tmp.user.avatarURL);\r\n }\r\n else {\r\n tmp = mmbs.find((mmb) => mmb.id.toLowerCase().includes(txt.toLowerCase()));\r\n if (tmp)\r\n rets.push(tmp.user.avatarURL);\r\n }\r\n }\r\n }\r\n else if (message.channel instanceof discord_js_1.GroupDMChannel) {\r\n let tmp = message.channel.recipients.array().sort((usr1, usr2) => (usr1.username || '').length - (usr2.username || '').length).find((usr) => usr.id.includes(txt) || usr.username.toLowerCase().includes(txt.toLowerCase()));\r\n if (tmp)\r\n rets.push(tmp.avatarURL);\r\n }\r\n else if (message.channel instanceof discord_js_1.DMChannel) {\r\n let tmp = [message.channel.recipient, message.author].find((usr) => usr.username.toLowerCase().includes(txt.toLowerCase()) || usr.id.includes(txt));\r\n if (tmp)\r\n rets.push(tmp.avatarURL);\r\n }\r\n let tmp;\r\n if (rets.length === 0 && (tmp = vale.client.emojis.find((emj) => emj.name.toLowerCase().includes(txt.toLowerCase()))) !== null) {\r\n rets.push(tmp.url);\r\n }\r\n if (rets.length === 0)\r\n throw \"ENOTFOUND\";\r\n return rets;\r\n } //parse",
"countMentions( event ) {\n\t\tconst \tmsg = event.message,\n\t\t\t\tpingTypes = this.settings.get( `${this.settingsNamespace}.ping-types` ),\n\t\t\t\tmatchedPings = pingTypes.filter( ( value ) => msg.highlights?.has( value ) ),\n\t\t\t\tnotificationIcon = this.settings.get( `${this.settingsNamespace}.browser-notifications.icon-photo` ) === 'channel' ? msg.roomID : msg.user.id;\n\n\t\tlet pingAction = 'Mention';\n\n\t\t// Only count if the chat/browser window are inactive and the chat message is new, active, and actually contains a mention/ping of the user\n\t\tif ( ( document.visibilityState === 'visible' && document.hasFocus() ) || msg.deleted || msg.isHistorical || msg.ffz_removed || ! msg.mentioned ) {\n\t\t\treturn;\n\t\t}\n\n\t\tif ( msg.mentioned && matchedPings.length > 0 ) {\n\t\t\tthis.mentionCount++;\n\n\t\t\tthis.insertCounters();\n\n\t\t\tif ( ! matchedPings.includes( 'mention' ) ) {\n\t\t\t\tpingAction = 'Ping';\n\t\t\t}\n\n\t\t\tif ( this.settings.get( `${this.settingsNamespace}.browser-notifications.enabled` ) ) {\n\t\t\t\tconst notification = new Notification( `${pingAction}ed by ${msg.user.displayName} in ${msg.roomLogin}'s chat`, {\n\t\t\t\t\tbody: `${msg.user.displayName}: ${msg.message}`,\n\t\t\t\t\ticon: `https://cdn.frankerfacez.com/avatar/twitch/${notificationIcon}`,\n\t\t\t\t\trequireInteraction: this.settings.get( `${this.settingsNamespace}.browser-notifications.interact-to-close` )\n\t\t\t\t} );\n\t\t\t}\n\t\t}\n\t}",
"function gatherWords(author){\n\t\tvar result = [];\n\t\tvar confMap = {};\n\t\t\n\t\t// count the number of occurrences of each word \n\t\tfor (var j=0; j < author.publications.length; j++){\n\t\t\tvar pub = author.publications[j];\n\t\t\tif (conferences[pub.conference.series] && withinRange(pub)){\n\t\t\t\t var titleWords = pub.title.split(\" \");\n\t\t\t\t for (var k=0; k < titleWords.length; k++){\n\t\t\t\t\t var word = titleWords[k].toLowerCase();\n\t\t\t\t\t if (word.length > 3){ \n\t\t\t\t\t\t if (result[word] === undefined){\n\t\t\t\t\t\t\t result[word] = 1;\n\t\t\t\t\t\t\t confMap[word] = pub.conference.series;\n\t\t\t\t\t\t } else {\n\t\t\t\t\t\t\t result[word]++;\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\t\n\t\t// create the array structure required for jQcloud\n\t\tvar nresult = [ ];\n\t\tfor (var i in result){\n\t\t\tvar obj = {};\n\t\t\tobj.text = i;\n\t\t\tobj.weight = result[i];\n\t\t\tobj.html = { \"class\" : confMap[i] }; \n\t\t\tnresult.push(obj);\n\t\t}\n\t\t\n\t\treturn nresult;\n\t}",
"function followers(){\n for(var person in data){\n var followersString = \"\";\n followersString += data[person].name + \" follows \";\n data[person].follows.forEach(function(follower, index, followers){\n if(index === followers.length - 1 && index !== 0){\n followersString += \"and \";\n }\n followersString += data[follower].name + \" \";\n });\n var followers = getFollowers(person);\n if(followers){\n followersString += \", this are his/her followers \"\n followers.forEach(function(follower, index, followers){\n if(index === followers.length - 1 && index !== 0){\n followersString += \"and \";\n }\n followersString += data[follower].name + \" \";\n });\n }\n console.log(followersString);\n }\n}",
"render() {\n const { topics } = this.props.topics;\n if (topics.length > 0) {\n // topics are found matching query\n return (\n <div className=\"topic-grid-root\">\n <h3 className=\"title\">Topics:</h3>\n <Grid className=\"topic-grid-container\" container spacing={10}>\n {topics.map((topic) => (\n <Grid className=\"topic-card-grid-item\" item xs key={topic._id}>\n <TopicCard\n name={topic.topic_name}\n topicId={topic._id}\n photoUrl={topic.photo_url}\n description={topic.description}\n />\n </Grid>\n ))}\n </Grid>\n </div>\n );\n } else {\n // no subtopics are found matching query\n return (\n <div className=\"no-topics-message\">\n <h3>No Topics that Matched '{this.props.query}'.</h3>\n </div>\n );\n }\n }",
"function getAllArticlesOfAllTopics (req, res) {\n const articlesByTopicArray = []\n Topic.find({}, function (err, topicsArray) {\n if (err) return res.status(401).json({error: '/topics getAllArticlesOfAllTopics() error 1'})\n topicsArray.forEach(function (topic) {\n Article\n .find({topics: topic}, function (err, articlesArray) {\n if (err) return res.status(404).json({error: '/topics/:name getAllArticlesOfOneTopic() error 2'})\n articlesArray.forEach(function (article) {\n articlesByTopicArray.push(article)\n // console.log(article)\n })\n // console.log(articlesByTopicArray)\n })\n })\n })\n res.status(200).json(articlesByTopicArray) // why am i not able to get articlesByTopicArray on chrome? I can see it in the console..\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The AWS::Config::DeliveryChannel resource describes where AWS Config sends notifications and updated configuration states for AWS resources. Documentation: | function DeliveryChannel(props) {
return __assign({ Type: 'AWS::Config::DeliveryChannel' }, props);
} | [
"function DeliveryStream(props) {\n return __assign({ Type: 'AWS::KinesisFirehose::DeliveryStream' }, props);\n }",
"function cfnBucketNotificationConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnBucket_NotificationConfigurationPropertyValidator(properties).assertSuccess();\n return {\n EventBridgeConfiguration: cfnBucketEventBridgeConfigurationPropertyToCloudFormation(properties.eventBridgeConfiguration),\n LambdaConfigurations: cdk.listMapper(cfnBucketLambdaConfigurationPropertyToCloudFormation)(properties.lambdaConfigurations),\n QueueConfigurations: cdk.listMapper(cfnBucketQueueConfigurationPropertyToCloudFormation)(properties.queueConfigurations),\n TopicConfigurations: cdk.listMapper(cfnBucketTopicConfigurationPropertyToCloudFormation)(properties.topicConfigurations),\n };\n}",
"function Configuration(props) {\n return __assign({ Type: 'AWS::AmazonMQ::Configuration' }, props);\n }",
"function ConfigurationSetEventDestination(props) {\n return __assign({ Type: 'AWS::SES::ConfigurationSetEventDestination' }, props);\n }",
"function FirebaseChannelConfig() {\n\n this.databaseURL = null;\n this.serviceAccount = null;\n}",
"createChannel() {\n\t\tlet depends = this.props.depends ? this.props.depends : {};\n\t\tvar channelObj = manager.create(depends);\n\n\t}",
"function receivedDeliveryConfirmation(event) {\n console.log('inside received delivery confirmation event');\n var senderID = event.sender.id;\n var recipientID = event.recipient.id;\n var delivery = event.delivery;\n var messageIDs = delivery.mids;\n var watermark = delivery.watermark;\n var sequenceNumber = delivery.seq;\n\n if (messageIDs) {\n messageIDs.forEach(function (messageID) {\n console.log(\"Received delivery confirmation for message ID: %s\",\n messageID);\n });\n }\n\n console.log(\"All message before %d were delivered.\", watermark);\n}",
"function get_channel_key(){\n return this.channel;\n }",
"function cfnDataSourceEventBridgeConfigPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDataSource_EventBridgeConfigPropertyValidator(properties).assertSuccess();\n return {\n EventBusArn: cdk.stringToCloudFormation(properties.eventBusArn),\n };\n}",
"__resend_configuration_request() {\r\n // if we received all the pending configurations, clear the scheduled job\r\n if (this.pending_configurations.length == 0) {\r\n clearInterval(this.pending_configurations_job)\r\n this.pending_configurations_job = null\r\n return\r\n } else {\r\n // otherwise for each pending configuration, send again a request to controller/config\r\n for (var topic of this.pending_configurations) {\r\n this.__send_configuration_request(topic)\r\n }\r\n }\r\n }",
"function Destination(props) {\n return __assign({ Type: 'AWS::Logs::Destination' }, props);\n }",
"function ConfigurationAggregator(props) {\n return __assign({ Type: 'AWS::Config::ConfigurationAggregator' }, props);\n }",
"function cfnBucketEventBridgeConfigurationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnBucket_EventBridgeConfigurationPropertyValidator(properties).assertSuccess();\n return {\n EventBridgeEnabled: cdk.booleanToCloudFormation(properties.eventBridgeEnabled),\n };\n}",
"function createChannel(){\n return notificationsApi.postNotificationsChannels()\n .then(data => {\n console.log('---- Created Notifications Channel ----');\n console.log(data);\n\n channel = data;\n let ws = new WebSocket(channel.connectUri);\n ws.onmessage = () => {\n let data = JSON.parse(event.data);\n\n topicCallbackMap[data.topicName](data);\n };\n });\n}",
"function VPCEndpointConnectionNotification(props) {\n return __assign({ Type: 'AWS::EC2::VPCEndpointConnectionNotification' }, props);\n }",
"function updateSettings(event, payload) {\n fs.writeFile(configPath, JSON.stringify(payload, null, 2), function (err) {\n if (err) return console.log(err);\n event.sender.send('config', payload)\n });\n}",
"function channelObj(){\r\n\treturn {\r\n\t\tname: '',\r\n\t\tdisplay_name: '', \r\n\t\tlive: false,\r\n\t\tlogo: 'images/offline.png',\r\n\t\tstatus: '',\r\n\t\tfavorite: false,\r\n\t\tswitcher: false,\r\n\t\thosted: false,\r\n\t\tsingle: false,\r\n\t\tgame: '',\r\n\t\tviews: '',\r\n\t\tfollowers: '',\r\n\t\tviewers: 0,\r\n\t\tpartner: false,\r\n\t\tvideo_height: 0,\r\n\t\taverage_fps: 0\r\n\t}\r\n}",
"function ConfigurationRecorder(props) {\n return __assign({ Type: 'AWS::Config::ConfigurationRecorder' }, props);\n }",
"function EndpointConfig(props) {\n return __assign({ Type: 'AWS::SageMaker::EndpointConfig' }, props);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get TreeNode props with Tree props. | function getTreeNodeProps(key, _ref2) {
var expandedKeys = _ref2.expandedKeys,
selectedKeys = _ref2.selectedKeys,
loadedKeys = _ref2.loadedKeys,
loadingKeys = _ref2.loadingKeys,
checkedKeys = _ref2.checkedKeys,
halfCheckedKeys = _ref2.halfCheckedKeys,
dragOverNodeKey = _ref2.dragOverNodeKey,
dropPosition = _ref2.dropPosition,
keyEntities = _ref2.keyEntities;
var entity = keyEntities[key];
var treeNodeProps = {
eventKey: key,
expanded: expandedKeys.indexOf(key) !== -1,
selected: selectedKeys.indexOf(key) !== -1,
loaded: loadedKeys.indexOf(key) !== -1,
loading: loadingKeys.indexOf(key) !== -1,
checked: checkedKeys.indexOf(key) !== -1,
halfChecked: halfCheckedKeys.indexOf(key) !== -1,
pos: String(entity ? entity.pos : ''),
// [Legacy] Drag props
// Since the interaction of drag is changed, the semantic of the props are
// not accuracy, I think it should be finally removed
dragOver: dragOverNodeKey === key && dropPosition === 0,
dragOverGapTop: dragOverNodeKey === key && dropPosition === -1,
dragOverGapBottom: dragOverNodeKey === key && dropPosition === 1
};
return treeNodeProps;
} | [
"extractProps(node) {\n if (Element$1.isAncestor(node)) {\n var properties = _objectWithoutProperties(node, [\"children\"]);\n\n return properties;\n } else {\n var properties = _objectWithoutProperties(node, [\"text\"]);\n\n return properties;\n }\n }",
"function getNodeProps(node, key, opts, renderer) {\n\t var props = { key: key }, undef;\n\t\n\t // `sourcePos` is true if the user wants source information (line/column info from markdown source)\n\t if (opts.sourcePos && node.sourcepos) {\n\t props['data-sourcepos'] = flattenPosition(node.sourcepos);\n\t }\n\t\n\t var type = normalizeTypeName(node.type);\n\t\n\t switch (type) {\n\t case 'html_inline':\n\t case 'html_block':\n\t props.isBlock = type === 'html_block';\n\t props.escapeHtml = opts.escapeHtml;\n\t props.skipHtml = opts.skipHtml;\n\t break;\n\t case 'code_block':\n\t var codeInfo = node.info ? node.info.split(/ +/) : [];\n\t if (codeInfo.length > 0 && codeInfo[0].length > 0) {\n\t props.language = codeInfo[0];\n\t props.codeinfo = codeInfo;\n\t }\n\t break;\n\t case 'code':\n\t props.children = node.literal;\n\t props.inline = true;\n\t break;\n\t case 'heading':\n\t props.level = node.level;\n\t break;\n\t case 'softbreak':\n\t props.softBreak = opts.softBreak;\n\t break;\n\t case 'link':\n\t props.href = opts.transformLinkUri ? opts.transformLinkUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t if (opts.linkTarget) {\n\t props.target = opts.linkTarget;\n\t }\n\t break;\n\t case 'image':\n\t props.src = opts.transformImageUri ? opts.transformImageUri(node.destination) : node.destination;\n\t props.title = node.title || undef;\n\t\n\t // Commonmark treats image description as children. We just want the text\n\t props.alt = node.react.children.join('');\n\t node.react.children = undef;\n\t break;\n\t case 'list':\n\t props.start = node.listStart;\n\t props.type = node.listType;\n\t props.tight = node.listTight;\n\t break;\n\t default:\n\t }\n\t\n\t if (typeof renderer !== 'string') {\n\t props.literal = node.literal;\n\t }\n\t\n\t var children = props.children || (node.react && node.react.children);\n\t if (Array.isArray(children)) {\n\t props.children = children.reduce(reduceChildren, []) || null;\n\t }\n\t\n\t return props;\n\t}",
"getChildrenProps() {\n const { children } = this.props;\n const targetNode = this.getPositionTarget();\n const childrenProps = { children };\n const childrenParams = {\n targetNode,\n visible: this.getVisible(),\n };\n if (typeof children === 'function') {\n return {\n children: children(childrenParams),\n };\n }\n if (children === undefined && targetNode) {\n const tooltip = targetNode.getAttribute('data-tooltip');\n if (tooltip != null) {\n return {\n dangerouslySetInnerHTML: {\n __html: tooltip,\n },\n };\n }\n }\n return childrenProps;\n }",
"getData() {\n const { tree, props } = this\n const { root } = props\n\n /* Create a new root, where each node contains height, depth, and parent.\n * Embeds the old node under the data attribute of the new node */\n const rootHierarchy = d3.hierarchy(\n root,\n (d) => d.children && Object.values(d.children)\n )\n\n /* Adds x, y to each node */\n tree(rootHierarchy)\n\n /* Return the array of nodes */\n const data = rootHierarchy.descendants()\n\n /* Use fixed depth to maintain position as items are added / removed */\n data.forEach((d) => {\n d.y = d.depth * 180\n })\n return data\n }",
"prop(prop) {\n return !prop.perNode\n ? this.type.prop(prop)\n : this.props\n ? this.props[prop.id]\n : undefined\n }",
"tree(tree) {\n if (tree) {\n this._tree = tree;\n }\n return this._tree;\n }",
"function getCurrentPbtypeTreeSelectedObjs() {\r\n \tvar tree = $.jstree.reference(\"#jstree_div_pbtype\"); //get tree instance\r\n \tvar selNodes = tree.get_selected(true);\r\n\r\n \treturn selNodes;\r\n }",
"function TreeObject(_ref) {\n var path = _ref.path,\n tree = _ref.tree,\n url = _ref.url,\n selected = _ref.selected,\n pathSelected = _ref.pathSelected,\n onBlob = _ref.onBlob,\n depth = _ref.depth,\n filepath = _ref.filepath,\n comparer = _ref.comparer;\n var classes = useStyles();\n\n var _filepath = _path.default.join(filepath || '', path);\n\n var icon = selected ? /*#__PURE__*/_react.default.createElement(_icons.Folder, null) : /*#__PURE__*/_react.default.createElement(_icons.FolderOpen, null);\n return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_core.ListItem, {\n button: true,\n selected: selected,\n className: classes.root,\n style: {\n paddingLeft: depth + 'em'\n }\n }, /*#__PURE__*/_react.default.createElement(_core.ListItemIcon, {\n style: {\n marginRight: 0\n }\n }, icon), /*#__PURE__*/_react.default.createElement(_core.ListItemText, {\n className: classes.pathText,\n primary: path + '/'\n })), /*#__PURE__*/_react.default.createElement(_.Tree, {\n pathSelected: pathSelected,\n tree: tree,\n url: url,\n selected: selected,\n onBlob: onBlob,\n depth: depth + 1,\n filepath: _filepath,\n comparer: comparer\n }));\n}",
"function getCurrentTreeSelectedObjs() {\r\n \tvar tree = $.jstree.reference(\"#jstree_div\"); //get tree instance\r\n \tvar selNodes = tree.get_selected(true);\r\n\r\n \treturn selNodes;\r\n }",
"async getAllChildrenAsOrderedTree(props = {}) {\n const selects = [\"*\", \"customSortOrder\"];\n if (props.retrieveProperties) {\n selects.push(\"properties\", \"localProperties\");\n }\n const setInfo = await this.select(...selects)();\n const tree = [];\n const childIds = [];\n const ensureOrder = (terms, sorts, setSorts) => {\n // handle no custom sort information present\n if (!isArray(sorts) && !isArray(setSorts)) {\n return terms;\n }\n let ordering = null;\n if (sorts === null && setSorts.length > 0) {\n ordering = [...setSorts];\n }\n else {\n const index = sorts.findIndex(v => v.setId === setInfo.id);\n if (index >= 0) {\n ordering = [...sorts[index].order];\n }\n }\n if (ordering !== null) {\n const orderedChildren = [];\n ordering.forEach(o => {\n const found = terms.find(ch => o === ch.id);\n if (found) {\n orderedChildren.push(found);\n }\n });\n // we have a case where if a set is ordered and a term is added to that set\n // AND the ordering information hasn't been updated in the UI the new term will not have\n // any associated ordering information. See #1547 which reported this. So here we\n // append any terms remaining in \"terms\" not in \"orderedChildren\" to the end of \"orderedChildren\"\n orderedChildren.push(...terms.filter(info => ordering.indexOf(info.id) < 0));\n return orderedChildren;\n }\n return terms;\n };\n const visitor = async (source, parent) => {\n const children = await source();\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n childIds.push(child.id);\n const orderedTerm = {\n children: [],\n defaultLabel: child.labels.find(l => l.isDefault).name,\n ...child,\n };\n if (child.childrenCount > 0) {\n await visitor(this.getTermById(children[i].id).children.select(...selects), orderedTerm.children);\n orderedTerm.children = ensureOrder(orderedTerm.children, child.customSortOrder);\n }\n parent.push(orderedTerm);\n }\n };\n // There is a series of issues where users expect that copied terms appear in the result of this method call. Copied terms are not \"children\" so we need\n // to get all the children + all the \"/terms\" and filter out the children. This is expensive but this method call is already indicated to be used with caching\n await visitor(this.children.select(...selects), tree);\n await visitor(async () => {\n const terms = await Terms(this).select(...selects)();\n return terms.filter((t) => childIds.indexOf(t.id) < 0);\n }, tree);\n return ensureOrder(tree, null, setInfo.customSortOrder);\n }",
"function prop_resolve(p_tree, obj) {\n\tvar i, l, match,\n\t\tget_element_on_conditions, //sets e_ret to the resolved element (the \"selected\" flag is checked after)\n\t\tp_obj,\n\t\tp_obj_sub,\n\t\te_ret, //the element to return\n\t\tp\n\n\tp = p_tree[0]\n\n\t//checks if the conditions are meet along with the child\n\tget_element_on_conditions = function(e, i, a) {\n\t\tif(e_ret || !e) return\n\n\t\tvar conds_true = true, //becomes false only if a false cond is found\n\t\t\tconds\n\n\t\t//check conditions\n\t\tif(conds = p.conds)\n\t\t\tconds.forEach(function(condition){\n\t\t\t\tvar prop = prop_resolve(condition.prop, e)\n\n\t\t\t\tif(\n\t\t\t\t\t!prop ||\n\t\t\t\t\t(condition.value && prop != condition.value)\n\t\t\t\t\t)\n\t\t\t\t\t\tconds_true = false\n\n\t\t\t})\n\n\t\t//this is the selected element\n\t\tif(conds_true) {\n\t\t\tp_obj = e\n\n\t\t\t//set match\n\t\t\t//there is a pending child, get it, otherwise, this is the element\n\t\t\tif( p_tree.length > 1 ) {\n\t\t\t\t\tp_obj_sub = prop_resolve(p_tree.slice(1), p_obj)\n\t\t\t\t\tif(p_obj_sub)\n\t\t\t\t\t\te_ret = p_obj_sub\n\t\t\t\t}\n\t\t\telse\n\t\t\t\te_ret = p_obj\n\t\t}\n\t}\n\t//if its and array selector, execute for every element on ascending order,\n\t//otherwise just the prop name\n\tif(p.name == '[]') {\n\t\tif(!(obj instanceof Array))\n\t\t\treturn null\n\t\tobj.forEach(get_element_on_conditions)\n\t}\n\telse if(p.name && (match = p.name.match(/\\[(\\d+)\\]/)) )\n\t\tget_element_on_conditions( obj[match[1]] )\n\telse\n\t\tget_element_on_conditions(obj[p.name])\n\n\t//there is a match, check for \"selected\" flag on current element\n\tif(e_ret && p_obj_sub)\n\t\te_ret = (p.selected)? p_obj : p_obj_sub\n\n\treturn e_ret\n}",
"get tree() {\n return this.buffer ? null : this._tree._tree\n }",
"constructor(options) {\n /// @internal\n this.typeNames = [\"\"];\n /// @internal\n this.typeIDs = Object.create(null);\n /// @internal\n this.prop = new tree_es[\"c\" /* NodeProp */]();\n this.flags = options.flags;\n this.types = options.types;\n this.flagMask = Math.pow(2, this.flags.length) - 1;\n this.typeShift = this.flags.length;\n let subtypes = options.subtypes || 0;\n let parentNames = [undefined];\n this.typeIDs[\"\"] = 0;\n let typeID = 1;\n for (let type of options.types) {\n let match = /^([\\w\\-]+)(?:=([\\w-]+))?$/.exec(type);\n if (!match)\n throw new RangeError(\"Invalid type name \" + type);\n let id = typeID++;\n this.typeNames[id] = match[1];\n this.typeIDs[match[1]] = id;\n parentNames[id] = match[2];\n for (let i = 0; i < subtypes; i++) {\n let subID = typeID++, name = match[1] + \"#\" + (i + 1);\n this.typeNames[subID] = name;\n this.typeIDs[name] = subID;\n parentNames[subID] = match[1];\n }\n }\n this.parents = parentNames.map(name => {\n if (name == null)\n return 0;\n let id = this.typeIDs[name];\n if (id == null)\n throw new RangeError(`Unknown parent type '${name}' specified`);\n return id;\n });\n if (this.flags.length > 30 || this.typeNames.length > Math.pow(2, 30 - this.flags.length))\n throw new RangeError(\"Too many style tag flags to fit in a 30-bit integer\");\n }",
"function findNodeProperty(prop, contact) {\n\t\n\tif (prop.indexOf(getClassName(contact.m_node1.other)) != -1) {\n\t\t\n\t\treturn [contact.m_node1.other, contact.m_node2.other]\n\t\t\n\t}\n\t\n\telse if (prop.indexOf(getClassName(contact.m_node2.other)) != -1) {\n\t\t\n\t\treturn [contact.m_node2.other, contact.m_node1.other]\n\t\t\n\t}\n\t\n\telse return false;\n\t\n}",
"function getNodeValue(node, type) {\n var array = keys(node.children);\n \n // Just get the leaf node value,\n // if a node is not a leaf node and its value is not undefined,\n // then the value is ignored.\n if (array.length === 0){\n // Mark the parent node is the second last node,\n // so it is convenient to know in which node can remove attributes\n node.parentNode.secondNode = true;\n return node.value;\n }\n\n var assignArray = map(array, function(key) {\n var child = node.children[key];\n return {\n key: child.key,\n value: getNodeValue(child, type),\n };\n });\n\n return assignData(node, assignArray, type);\n\n}",
"function storeTreeCoords() {\n var treeId, treeObj, trunkTop, leafsTop;\n\n $trees.forEach(function ($tree) {\n treeId = $tree.getAttribute(\"data-id\");\n treesData[\"tree\" + treeId] = {};\n treeObj = treesData[\"tree\" + treeId];\n treeObj.isRight = $tree.classList.contains(\"m--right\");\n treeObj.$treeTrunk = $tree.querySelector(\".svgBg__tree-trunk\");\n treeObj.$treeLeafs = $tree.querySelector(\".svgBg__tree-leafs\");\n treeObj.trunkInitArrD = treeObj.$treeTrunk.getAttribute(\"d\").split(\" \");\n treeObj.leafsInitArrD = treeObj.$treeLeafs.getAttribute(\"d\").split(\" \");\n trunkTop = treeObj.trunkInitArrD[2];\n leafsTop = treeObj.leafsInitArrD[3];\n treeObj.trunkInitX = +trunkTop.split(\",\")[0];\n treeObj.leafsInitX = +leafsTop.split(\",\")[0];\n treeObj.trunkInitY = +trunkTop.split(\",\")[1];\n treeObj.leafsInitY = +leafsTop.split(\",\")[1];\n });\n }",
"visitColumn_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }",
"TreeNode(label, flags=0)\n {\n let win = this.getCurrentWindow();\n if (win.SkipItems) return false;\n let g = this.guictx;\n return this.treeNodeBehavior(win.GetID(label), flags,\n label.split(\"##\")[0]);\n }",
"get topNode() {\n return new TreeNode(this, 0, 0, null)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that only indicators are used in favourites | function validateFavoriteDataItems() {
//Data elements from favorites
var issues = [];
for (var type of ["charts", "mapViews", "reportTables"]) {
for (var i = 0; metaData.hasOwnProperty(type) && i < metaData[type].length; i++) {
var item = metaData[type][i];
for (var dimItem of item.dataDimensionItems) {
if (dimItem.dataDimensionItemType != "INDICATOR") {
//Exception: custom objects we list, but don't stop the export
var abort = customObject(type, item.id) ? false : true;
var nameableItem = (type == "mapViews") ? mapFromMapView(item.id) : item;
issues.push({
"id": nameableItem.id,
"name": nameableItem.name,
"type": type,
"error": dimItem.dataDimensionItemType,
"abort": abort
});
}
}
}
}
if (issues.length > 0) {
console.log("\nWARNING | Favourites not using indicators only:");
abort = false;
var printed = {};
for (var issue of issues) {
abort = abort || issue.abort;
if (!printed[issue.id + issue.error]) {
console.log(issue.type + ": " + issue.id + " - '" + issue.name +
"': " + issue.error);
printed[issue.id + issue.error] = true;
}
}
return !abort;
}
else return true;
} | [
"function checkOwnFavs(){\n if( ! conf.ownFavs || ! tweet.favorited ){\n return checkFinal();\n }\n checkOwnFavourite( tweet.id_str, function( favourited ){\n if( favourited ){\n console.log('Keeping tweet favourited by self');\n return nextTweet();\n }\n checkFinal();\n } );\n }",
"function checkForFavs() {\n for(let favStory of $(user.favorites)){\n let favStoryID = favStory.storyId;\n\n $(`#${favStoryID}`).find(\".fa-heart\").toggleClass(\"far fas\");\n }\n }",
"function checkNumFavs(){\n if( conf.minFavs && tweet.favorited && conf.minFavs <= tweet.favorite_count ){\n console.log('Keeping tweet favourited '+tweet.favorite_count+' times');\n return nextTweet();\n }\n checkTags();\n }",
"function filterFavoritesIfAppliable() {\n const favs = $('#favs');\n if (favs.text().localeCompare('My favorites') == 0) {\n const favorites = User.getFavoritesText();\n $('#fixtures tr').filter(function() {\n // The league and teams infos are only on the 3 first tds\n const arrayOfDisplayed = $(this).children('td').slice(0, 3).map(function() { // eslint-disable-line no-invalid-this\n return $(this).text().trim(); // eslint-disable-line no-invalid-this\n }).get();\n $(this).toggle(favorites.some((element) => arrayOfDisplayed.includes(element))); // eslint-disable-line no-invalid-this\n });\n } else {\n $('#fixtures tr').toggle(true);\n }\n}",
"function isRemoveFromFavoriets(req,res)\n{\n return checkTable(req,'favorites')\n}",
"function checkFavorites() {\n if (localStorage.getItem(\"favorites\") == null) {\n favoritesArray = [];\n localStorage.setItem(\"favorites\", JSON.stringify(favoritesArray));\n } else {\n favoritesArray = JSON.parse(localStorage.getItem(\"favorites\"));\n }\n }",
"function storyIsFavorite(story) {\n if (currentUser) {\n let favoriteIds = currentUser.favorites.map(story => story.storyId); \n return favoriteIds.includes(story.storyId);\n }\n }",
"cartHasUnAvailibleItems() {\n const itemAvailibility = Object.keys(this.state.itemsAvailible).map(\n itemId => this.state.itemsAvailible[itemId],\n );\n return !itemAvailibility.every(itemAvailible => itemAvailible === true);\n }",
"function checkIfFavourite() {\n const url = '/albumFavourite';\n // Since this is a GET request, simply call fetch on the URL\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json()\n } else {\n }\n })\n .then((favouriteAlbum) => { // the resolved promise with the JSON body\n for( let i = 0; i < favouriteAlbum.length; i++ )\n {\n if(favouriteAlbum[i]._id == album._id )\n {\n isFavourite = true\n }\n }\n styleFavouriteButton();\n }).catch((error) => {\n })\n}",
"function isFavorite(story) {\n // start with an empty set of favorite story ids\n let favoriteStoryIds = new Set();\n\n if (currentUser) {\n favoriteStoryIds = new Set(\n currentUser.favorites.map((story) => story.storyId)\n );\n }\n isFave = favoriteStoryIds.has(story.storyId);\n // return true or false\n return isFave;\n }",
"function emptyFavorites () {\n if (savedFavorites == null || savedFavorites == 0) {\n noFavotires.classList.remove('hide');\n } else {\n noFavotires.classList.add('hide');\n }\n}",
"isFavorite (serie) {\n\t\treturn this.favorites.find(item => item.id === serie.id)\n\t}",
"checkItemNarrative(target) {\n return false;\n }",
"validateWishlistCounterIconIncrement() {\n return this\n .waitForElementVisible('@wishlistCounter')\n .assert.visible('@wishlistCounter')\n .getText('@wishlistCounter', (text) => {\n this\n .assert.ok(text.value > 0, 'Item added to wishlist');\n });\n }",
"function CheckExpenseItems(itemCount)\n{\n if (itemCount > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}",
"function toggleFav()\n{\n //Retrieving favs array from localStorage and toggling according to membership \n\n var favs = JSON.parse(localStorage.getItem(\"favs\") || \"[]\");\n var favbtn = document.getElementById('fav-btn');\n\n if(!favs.includes(hero[\"id\"]))\n {\n favs.push(hero[\"id\"]);\n favbtn.innerText = 'Remove from Favourites';\n favbtn.style.backgroundColor = 'red';\n }\n else\n {\n favs = favs.filter(e => e !== hero[\"id\"]);\n favbtn.innerText = 'Add to Favourites';\n favbtn.style.backgroundColor = '#1e90ff';\n }\n\n window.localStorage.setItem(\"favs\", JSON.stringify(favs));\n}",
"function subtest_incomplete_provider_not_displayed(w) {\n wait_for_provider_list_loaded(w);\n // Make sure that the provider that didn't include the required fields\n // is not displayed.\n let input = w.window.document.querySelectorAll(\n 'input[type=\"checkbox\"][value=\"corrupt\"]'\n );\n Assert.equal(\n 0,\n input.length,\n \"The Corrupt provider should not have been displayed\"\n );\n\n // And check to ensure that at least one other provider is displayed\n input = w.window.document.querySelectorAll(\n 'input[type=\"checkbox\"][value=\"foo\"]'\n );\n Assert.equal(1, input.length, \"The foo provider should have been displayed\");\n}",
"function checkFavouriteProjects(projects, favouriteProjects) {\n angular.forEach(projects, function(p) {\n p.isFavourite = false;\n var index = favouriteProjects.indexOf(p._id);\n if (index !== -1) {\n p.isFavourite = true\n }\n });\n }",
"function checkLocalStorage() {\n if (!Array.isArray(topicsList)) {\n topicsList = [];\n }\n if (!Array.isArray(favList)) {\n favList = [];\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if an object is in an array, return index of the object if true | function arrayContains(arr, obj){
for (var i=0; i < arr.length; i++){
if (arr[i] == obj){
return i;
}
}
return false;
} | [
"static isExistInArray(arr, value, index=0){\n\t\tif( typeof arr === 'object'){\n\t\t\tlet arrList = [];\n\t\t\tforEach( arr, (item, key) => {\n\t\t\t\tif(item.id){\n\t\t\t\t\tarrList.push(item.id);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(indexOf(arrList, value, index) >= 0){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}",
"function inArray(value, array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] == value) return i;\n }\n return -1;\n}",
"function linearSearch(searchObj, searchArr){\n\n for(let index = 0; index < searchArr.length; index++){\n if(searchArr[index] === searchObj){\n return index\n }\n }\n return undefined\n}",
"function checkIfVehicleExists(vehicle, array) {\n for (var i = 0; i < array.length; i++) {\n if (vehicle.shortIdentifier == array[i].shortIdentifier) {\n return i;\n }\n }\n return -1;\n}",
"function instanceArrayPosition(instance) {\n for (var i = 0; i < objects.length; i++) {\n if (objects[i] == instance) {\n return i;\n }\n }\n return -1;\n}",
"function isIndexInside(index, arr) {\n let result = false\n arr.forEach(inArr => {\n inArr.forEach(target => {\n if ( index == target ) {\n result = true\n } \n })\n })\n return result\n }",
"function findIndexInDidArrayMatchingSelection() {\t\n\t\tvar i=0;\n\t\twhile(i<detailIdJson.did_array.length) {\n\t\t\tif(detailIdJson.did_array[i].color==self.color() &&\n\t\t\t detailIdJson.did_array[i].size ==self.size() &&\n\t\t\t detailIdJson.did_array[i].sex ==self.sex() )\n\t\t\t\tbreak;\n\t\t\ti++;\n\t\t}\n\t\tif(i==detailIdJson.did_array.length)\n\t\t{\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn i;\n\t\t}\t\n\t}",
"function isin(element, array) {\n\n var output = false;\n\n for (var i = 0; i <= array.length; i++) {\n\n if (element == array[i]) {\n\n output = true;\n\n }\n\n }\n\n return output;\n\n }",
"findBookIndex(book) {\n let bookIndex = this.allBooks.indexOf(book);\n if (bookIndex == -1) {\n console.error(\"Book does not exist in allBooks array\")\n return false\n } else {\n return bookIndex;\n }\n\n }",
"function search_in_array(element,array){\r\n\r\n var found = 0;\r\n \r\n for(i=0;i<array.length;i++)\r\n {\r\n if(array[i] == element)\r\n {\r\n found = 1;\r\n return 1;\r\n }\r\n }\r\n\r\n if(found == 0){\r\n return 0;\r\n }\r\n\r\n}",
"function arr_findIndex(arr = [], prop = \"\", val) {\n\treturn arr.findIndex(v => { return v && v[prop] === val })\n}",
"function isInside(arr, ele) { // [1,2,3], 3\n // if (arr.indexOf(ele) >= 0) {\n // return true;\n // } else {\n // return false;\n // }\n\n return arr.indexOf(ele) >= 0;\n}",
"function findInArray(array, attr) {\n for ( let i = 0; i < array.length; i++ ) {\n if ( array[i].Name == attr.toString() ) {\n return i;\n }\n }\n }",
"function findObjectByKey(array, value) {\n for (var i = 0; i < array.length; i++) {\n if (array[i][\"hashtag\"] === value) {\n return i\n }\n }\n return false\n }",
"contains (array, item, f) { return this.indexOf(array, item, f) >= 0 }",
"function getMatchingIndex(arr, key, value) {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i][key] === value)\n return i;\n }\n return null;\n}",
"getIndex(id, data){\n for(let i=0; i<data.length; i++){\n if(id === data[i].id){\n return i;\n }\n }\n console.log(\"No match found\");\n return 0;\n }",
"function findCard(arr, card){\n for (let i = 0; i < arr.length; i++){\n if(cards[i] == card) return i;\n }\n return -1;\n}",
"function findIndexOfItem(array, item){\r\n for (var x = 0; x < array.length; x++) {\r\n if (array[x][1] == item[1]) {\r\n return x;\r\n }\r\n}\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The stackLetter function should accept the array as the sole argument | function stackLetters (alphabet) {
for (var i=0; i < alphabet.length; i++) {
stack += alphabet[i]
console.log(stack)
};
} | [
"function fillDisplayWord (letter) {\n\n}",
"function makeHappy(arr){\n let result = arr.map(word => \"Happy \" + word)\n return result\n}",
"print() { \n let str = \"\"; \n for (var i = 0; i < this.size(); i++) \n str += this.stack[i] + \" \"; \n console.log(str); \n }",
"function shoutGreetings(array) {\nreturn array.map(elem => \n elem.toUpperCase() + `!`\n)\n}",
"displayWord() {\n var string = \"\";\n\n for (var i = 0; i < this.lettersArr.length; i++) {\n var char = this.lettersArr[i].toString();\n string += char;\n };\n\n return string;\n }",
"function findMissingLetter(array)\n{ const alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n const upperalph = alphabets.map(alphabet =>(alphabet.toUpperCase()))\n for (let x = 0; x<alphabets.length;x++) {\n if (alphabets[x]== array[0])\n var first = x\n if (upperalph[x] == array[0])\n var firstUpper = x\n } \n var slice = []\n for (let x = first; x<(first+array.length); x++) {\n slice.push(alphabets[x])}\n if (first !== undefined) {\n for (let x in slice) {\n if (array.indexOf(slice[parseInt(x)])==-1) {\n return slice[parseInt(x)]\n }\n }\n }\n for (let x = firstUpper; x<(firstUpper+array.length); x++) {\n slice.push(upperalph[x])}\n if (firstUpper !== undefined) {\n for (let x in slice) {\n if (array.indexOf(slice[parseInt(x)])==-1) {\n return slice[parseInt(x)]\n }\n }\n }\n}",
"function wordDivide(randomWord) {\n var wordArray = randomWord.split(\"\");\n for (var i = 0; i < wordArray.length; i++) {\n letters.push(wordArray[i]);\n console.log(wordArray[i]);\n }\n}",
"function setGuessedArray() {\n\tvar letter = prompt(\"Guess A Letter!\");\n\t// letter = event.key;\n\tif (letter != 1 && letter != 2) {\n\t\tguessedRight = 0;\n\t\tguessedLetters.push(letter);\n\t\tconsole.log(guessedLetters);\n\t\tfor (var i = 0; i < wordLength; i++) {\n\t\t\tif (letter == initialWord.charAt(i)) {\n\t\t\t\tinitialWordArray[i] = letter;\n\t\t\t\tdisplayWords();\n\t\t\t\tguessedRight = 1; //guessed right\n\t\t\t\tconsole.log(initialWordArray); //testing\n\t\t\t} else{\n\t\t\t\tdocument.getElementById(\"array of guessed letters\").innerHTML = guessedLetters.join(' ');\n\t\t\t}\n\t\t}\n\t\tif (guessedRight != 1) {\n\t\t\tguesses_Remaining--;\n\t\t\tguessesRemaining();\t\n\t\t}\n\t}\n}",
"function ex76(nums){\n array=[];\n array.push(nums[0],nums[nums.length-1]);\n return array;\n}",
"function zooInventory(array) {\n\t// create a variable, sentences and assign to an empty array\n\tconst sentences = [];\n\t// iterate through the array\n\tfor (let i = 0; i < array.length; i++) {\n\t\t// grab the elements assign to a variable animal\n\t\tlet animal = array[i];\n\t\t// create a name assign to the first element\n\t\tlet name = animal[0];\n\t\t// create a variable species assign to the first element at index 0\n\t\tlet species = animal[1][0];\n\t\t// create an age variable and assign to the first element at index 1\n\t\tlet age = animal[1][1];\n\t\t// create a variable called sentence assign to - name the species is age\n\t\tlet sentence = `${name} the ${species} is ${age}.`;\n\t\t// push sentence into sentences array\n\t\tsentences.push(sentence);\n\t}\n}",
"function construct_letter_array() {\n\tvar letter_array = [];\n\tfilter_letters.split(\"\").forEach( function( item ) {\n\t\tif ( letter_array[ item ] ) {\n\t\t\tletter_array[ item ] = letter_array[ item ] + 1;\n\t\t} else {\n\t\t\tletter_array[ item ] = 1;\n\t\t}\t\n\t}) ;\t\n\treturn letter_array;\n}",
"function sc(apple) {\n return apple.reduce((acc, letterArr, i) => {\n let letterIndex = letterArr.indexOf('B')\n letterIndex === -1 ? false : acc = [i, letterIndex]\n return acc\n }, -1)\n\n}",
"function stackBurger(e) { //this function adds the clicked ingredient to the burger stack\n const ingToAdd = ingredients.filter(ing => ing.name === e.target.innerText);//this is an array of all the ingredients added to the burger\n setStack([ingToAdd[0], ...stack]); //this adds clicked ingredients to the array by spreading the original array\n }",
"function convertToBaby(array) {\nconst babyArray = []\nfor (let i = 0; i < array.length; i++) {\n babyArray.push(`baby ` + array[i]);\n}\nreturn babyArray;\n}",
"function Solution(){\n let stack = []\n let queue = []\n this.pushCharacter = (ch) =>{\n return stack.push(ch)\n }\n this.enqueueCharacter = (ch) =>{\n return queue.push(ch)\n }\n this.popCharacter = () => {\n return stack.pop();\n }\n this.dequeueCharacter = () => {\n return queue.shift();\n }\n\n}",
"function firstLetterArray(sentenceIndex) {\n const wordArray = realSentences[sentenceIndex].sentence.split(\" \");\n const letterArray = [wordArray[0][0]];\n \n for (let i = 1; i < wordArray.length; i++) {\n letterArray.push(wordArray[i][0].toLowerCase());\n }\n\n return letterArray\n}",
"function start(){\n\tvar div = \"\";\n\tfor ( i = 0; i < 25; i++) {\n\t\tvar element = \"let\" + i;\n\t\tdiv = div + '<div class = \"letter\" onclick = \"check('+i+')\" id=\"'+element+'\">'+letters[i]+'</div>';\n\t\tif ((i + 1) % 7 == 0) div = div + '<div style = \"clear:both;\"></div>';\n\t}\n\tdocument.getElementById(\"alphabet\").innerHTML = div;\n\tgenerateWord();\n}",
"function addLetters(n) {\n for (i = 0; i <= 5; i++) {\n newArray.push(n);\n }\n}",
"function func8(str) {\r\n return str[0].toUpperCase() + str.slice(1);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modeled after the pushPayload for emberdata/serializers/rest | pushPayload(store, payload) {
const documentHash = {
data: [],
included: [],
};
Object.keys(payload).forEach(key => {
const modelName = this.modelNameFromPayloadKey(key);
const serializer = store.serializerFor(modelName);
const type = store.modelFor(modelName);
makeArray(payload[key]).forEach(hash => {
const { data, included } = serializer.normalize(type, hash, key);
documentHash.data.push(data);
if (included) {
documentHash.included.push(...included);
}
});
store.push(documentHash);
});
} | [
"function _push(object) {\n var payload = null;\n var callback = null;\n var error_callback = function (jqXHR,status,err) {\n //console.log(jqXHR,status,err.get_message());\n };\n var user_options = {};\n var url;\n for (var i = 0; i < arguments.length; i++) {\n switch(typeof arguments[i]) {\n case 'object':\n if (!payload) {\n payload = {currentview: 'push', model: {}}\n $.each(arguments[i], function (key,value) {\n payload[key] = value;\n });\n } else {\n user_options = arguments[i];\n }\n break;\n case 'function':\n if (!callback) {\n callback = arguments[i];\n } else {\n error_callback = arguments[i];\n }\n break;\n case 'string':\n url = arguments[i];\n break;\n }\n }\n options = { \n context: window,\n url: url, \n type: 'post', \n data: payload, \n timeout: 20000, \n success: callback, \n error: error_callback\n };\n if (typeof user_options == 'object') {\n $.each(user_options, function (key,value) {\n options[key] = value;\n });\n }\n $.ajax(options);\n}",
"createMeetUp(state, payload) {\n state.loadedMeetUps.push(payload);\n }",
"addPayloadEndpoint(opts) {\n if (this.event.payload.endpoints === undefined) {\n this.event.payload.endpoints = [];\n }\n\n if (opts === undefined) {\n opts = {};\n }\n\n // construct the proper structure expected for the endpoint\n let endpoint = {\n endpointId: Utils.defaultIfNullOrEmpty(opts.endpointId, 'dummy-endpoint-001'),\n manufacturerName: Utils.defaultIfNullOrEmpty(opts.manufacturerName, 'ioBroker Group'),\n description: Utils.defaultIfNullOrEmpty(opts.description, 'Device controlled by ioBroker'),\n friendlyName: Utils.defaultIfNullOrEmpty(opts.friendlyName, 'ioBroker Stub Endpoint'),\n displayCategories: Utils.defaultIfNullOrEmpty(opts.displayCategories, ['OTHER']),\n capabilities: this.alexaCapability().concat(Utils.defaultIfNullOrEmpty(opts.capabilities, [])),\n };\n\n if (opts.hasOwnProperty('cookie')) {\n endpoint.cookie = Utils.defaultIfNullOrEmpty('cookie', {});\n }\n\n this.event.payload.endpoints.push(endpoint);\n }",
"publish(queue, event, payload) {\n let message = {queue,event,payload};\n this.q.emit('publish', message); \n }",
"serialize(...args) {\n const attrs = Reflect.apply(AmpState.prototype.serialize, this, args);\n attrs.url = this.url;\n return attrs;\n }",
"did(eventName, payload) {\n this.emitter.emit(`did-${eventName}`, payload);\n }",
"publish(eventType, ...payload) {\n const subscribers = this.events.get(eventType);\n if (subscribers) {\n for (const eventHandler of subscribers) {\n eventHandler(...payload);\n }\n }\n }",
"function PayloadProcessor() {\n var self = this;\n this.listenerInstances = [];\n\n events.EventEmitter.call(this);\n}",
"[UPDATE_USER_CHANGE_STORES](context, payload) {\n const { stores } = payload;\n const user = { stores };\n return ApiService.put(\"user/\" + payload.id, user).then(({ data }) => {\n\n return data;\n });\n }",
"_fetchFromAPI() {\n // Generate new items\n let { indexedDb } = this;\n\n return indexedDb.add('item', [\n this._createItemPayload(),\n this._createItemPayload(),\n this._createItemPayload(),\n ]);\n }",
"function newItemRequest(endpoint, payload) {\n var request = baseRequest;\n request.url = endpoint;\n request.type = \"POST\";\n request.contentType = \"application/json;odata=verbose\";\n request.headers = {\n \"ACCEPT\": \"application/json;odata=verbose\",\n \"X-RequestDigest\": $(\"#__REQUESTDIGEST\").val()\n };\n request.data = payload;\n return request;\n }",
"extraReducers(builder) {\n builder.addCase(fetchNotifications.fulfilled, (state, action) => {\n // push the return array of action.payload into the current state array first\n // state.push(...action.payload);\n // state.forEach(notification => {\n // // all read notifications are no longer new\n // notification.isNew = !notification.read\n // })\n\n // notifications entity is no longer an array....KNOW YOUR ENTITY STRUCTURE BEFORE APPLY REDUCER FUNCS!\n // change the isNew in the new notification first\n Object.values(state.entities).forEach(notification => {\n notification.isNew = !notification.read;\n })\n\n // upsert: accept an array of entities or an object, shallowly insert it\n // upsertting the new notifications into the entity\n notificationsAdaptor.upsertMany(state, action.payload)\n\n // sort every date in the state \n // they are pre-sorted any time\n // state.sort((a, b) => b.date.localeCompare(a.date))\n })\n }",
"static payloader(command, payload) {\n var data = {\n \"command\": String(command),\n \"payload\": String(payload)\n }\n\n data = JSON.stringify(data)\n return data\n }",
"save(item){\n //if there is no data\n if(!this.data){\n this.data = [item];\n //create newData to store\n let newData = JSON.stringify(item);\n //pass in newData\n this.storage.set('todos', newData);\n } else {\n //if there is data, then push the new data\n this.data.push(item);\n let newData = JSON.stringify(this.data);\n this.storage.set('todos', newData);\n } // end save item if\n }",
"toJSON() {\n\n const obj = Object.assign({}, this);\n delete obj.app;\n\n return obj;\n }",
"addApplicationData(key, data, packOptions = {}) {\n const jsonData = packOptions.nopack ? data : packBinaryJson(data, this, null, packOptions);\n this.json[key] = jsonData;\n return this;\n }",
"action(type, payload) {\n var action;\n if (payload) {\n action = _.extend({}, payload, {actionType: type});\n } else {\n action = {actionType: type};\n }\n debug('Action: ' + type, action);\n this.dispatch(action);\n }",
"save() {\n undo.push();\n store.content.fromJSON(this.getValue());\n super.save();\n }",
"sendPushNotification (apiKey, title, message, payload, filter) {\n\n // check if apiKey is string\n if (typeof apiKey != \"string\" || apiKey.length <= 0)\n {\n this.emit(\"error\", new Error(\"No valid API Key given :'\"+ apiKey +\"'\"));\n }\n\n // check if title is string\n if (title != null && (typeof title != \"string\" || title.length <= 0))\n {\n this.emit(\"error\", new Error(\"No valid title given :'\"+ title +\"'\"));\n }\n\n // check if message is string\n if (typeof message != \"string\" || message.length <= 0)\n {\n this.emit(\"error\", new Error(\"No valid message given :'\"+ message +\"'\"));\n }\n\n // check if payload is object\n if (payload != null && typeof payload != \"object\")\n {\n this.emit(\"error\", new Error(\"No valid payload given :'\"+ payload +\"'\"));\n }\n\n // check if filter is object\n if (filter != null && typeof filter != \"object\" && typeof filter != \"array\")\n {\n this.emit(\"error\", new Error(\"No valid filter given :'\"+ filter +\"'\"));\n }\n\n var requestData = {\n \"restKey\": apiKey,\n \"body\": message\n };\n\n if (title != null)\n {\n requestData.title = title\n }\n\n if (payload != null)\n {\n requestData.payload = payload;\n }\n\n if (filter != null)\n {\n requestData.matchFilters = 1;\n requestData.filters = (typeof filter != \"object\") ? [filter] : filter;\n }\n request({\n method: \"POST\",\n url : 'https://push.appfarms.com/api/notifications',\n json : requestData\n })\n .on('response', (response) => {\n this.emit('success', response);\n })\n .on('error', (err) => {\n\n this.emit('error', err);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
allSettled() when passed an iterable containing either a single nonthenable value or a single thenable that resolves successfully should resolve to a singleelement array containing the resolved value | testSingleFulfilled() {
const expectedValue = {};
function subtest(iterable) {
return new AllSettledTestCaseBuilder()
.setInputIterable(iterable)
.setExpectedResults([newFulfilledValue(expectedValue)])
.test();
}
return Promise.all([
subtest([expectedValue]),
subtest([FakeThenable.asyncFulfill(expectedValue)]),
subtest([Promise.resolve(expectedValue)]),
subtest(new Set([expectedValue])),
subtest(new Set([FakeThenable.asyncFulfill(expectedValue)])),
subtest(new Set([Promise.resolve(expectedValue)])),
]);
} | [
"function test5_1() {\n var promise1 = Promise.resolve(3);\n var promise2 = new Promise((resolve, reject) => {\n setTimeout(reject, 100, 'foo')\n });\n var promises = [promise1, promise2];\n\n Promise.allSettled(promises).then((results) => results.forEach((result) => console.log(result.status)));\n // expected output:\n // \"fulfilled\"\n // \"rejected\"\n}",
"testSingleRejected() {\n const expectedReason = new Error('expected reason');\n const expectedResults = [newRejectedReason(expectedReason)];\n\n function subtest(iterable) {\n return new AllSettledTestCaseBuilder()\n .setInputIterable(iterable)\n .setExpectedResults(expectedResults)\n .test();\n }\n\n return Promise.all([\n subtest([FakeThenable.asyncReject(expectedReason)]),\n subtest([Promise.reject(expectedReason)]),\n subtest(new Set([FakeThenable.asyncReject(expectedReason)])),\n subtest(new Set([Promise.reject(expectedReason)])),\n ]);\n }",
"static all(promiseArray) {\n\t\tif (!(promiseArray instanceof Array)) {\n\t\t\tthrow new Error('Arg must be an array')\n\t\t}\n\n\t\treturn new P((resolve, reject) => {\n\t\t\tconst total = promiseArray.length\n\t\t\tconst results = []\n\n\t\t\tif (total === 0) {\n\t\t\t\tresolve(results)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlet numCompleted = 0\n\n\t\t\tpromiseArray.forEach((promise, index) => {\n\t\t\t\tpromise\n\t\t\t\t\t.then(value => {\n\t\t\t\t\t\tresults[index] = value\n\t\t\t\t\t\tnumCompleted++\n\n\t\t\t\t\t\tif (numCompleted === total) {\n\t\t\t\t\t\t\tresolve(results)\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch(reject)\n\t\t\t})\n\t\t})\n\t}",
"function Promise_all(array) {\n return new Promise((resolve, reject) => {\n let results = [];\n // Resolve it when all promises in a given array are successfully resolved.\n // And reject it if at least one of the promise returns a rejection.\n if (array.length === 0) resolve([]);\n for (const prom of array) {\n prom\n .then(value => {\n results.push(value);\n if (results.length === array.length) resolve(results);\n })\n .catch(reject);\n }\n });\n}",
"function update(arr) {\n arr.forEach(async ([p1, p2]) => {\n const A = await p1\n if (A.every(i => C.includes(i)))\n p2.resolve(A)\n })\n }",
"function test6_2() {\n const pErr = new Promise((resolve, reject) => {\n reject(\"Always fails\");\n });\n const pSlow = new Promise((resolve, reject) => {\n setTimeout(resolve, 500, \"Done eventually\");\n });\n const pFast = new Promise((resolve, reject) => {\n setTimeout(resolve, 100, \"Done quick\");\n });\n\n Promise.any([pErr, pSlow, pFast]).then((value) => {\n console.log(value);\n // pFast fulfils first\n });\n // expected output: \"Done quick\"\n}",
"function whenAll() {\n var p = new Promise();\n var dependencies = Array.prototype.slice.call(arguments);\n var values = new Array(dependencies.length);\n var promisedCount = dependencies.length;\n var resolvedCount = 0;\n\n debugLog(\"whenAll: has \" + promisedCount + \" dependencies.\");\n\n dependencies.forEach(function (dependency, index) {\n dependency.then(function (value) {\n resolvedCount++;\n values[index] = value;\n debugLog(\"whenAll: resolvedCount is \" + resolvedCount + \".\");\n\n if (resolvedCount === promisedCount) {\n debugLog(\"whenAll: resolved.\");\n p.resolve(values);\n }\n });\n });\n\n return p;\n }",
"function test3_2() {\n var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];\n var p = Promise.all(mixedPromisesArray);\n console.log(p);\n setTimeout(function () {\n console.log('the stack is now empty');\n console.log(p);\n });\n // logs\n // Promise { <state>: \"pending\" }\n // the stack is now empty\n // Promise { <state>: \"rejected\", <reason>: 44 }\n}",
"arrayInjector(somethings) {\n return Promise.all(somethings.map(something => this.inject(something)));\n }",
"function update(arr) {\n arr.forEach(async ([p1, p2]) => {\n const A = await p1\n if (A.every(i => G.includes(i)))\n p2.resolve(A)\n })\n }",
"function all( iterable )\n {\n var res = true;\n \n foreach(function (x)\n {\n if ( !x )\n {\n res = false;\n throw StopIteration;\n }\n },\n iterable);\n \n return res;\n }",
"function all(promises) {\n return new Promise(function(success, fail) {\n\n success(value);\n fail(throw new Error(error.message))\n\n\n });\n}",
"function allResolved(promises) {\n var deferred = $q.defer(),\n counter = 0,\n results = [];\n\n angular.forEach(promises, function(promise, key) {\n counter++;\n $q.when(promise).then(function(value) {\n if (results.hasOwnProperty(key)) {\n return;\n }\n results[key] = value;\n if (!(--counter)) {\n deferred.resolve(results);\n }\n }, function(reason) {\n if (results.hasOwnProperty(key)) {\n return;\n }\n results[key] = reason.data;\n if (!(--counter)) {\n deferred.resolve(results);\n }\n });\n });\n\n if (counter === 0) {\n deferred.resolve(results);\n }\n\n return deferred.promise;\n }",
"function mapEagerly (\n entriesOrThenables, // : any[] | Promise<any[]>,\n callbacks, // : Function,\n onRejected, // ?: Function,\n startIndex = 0,\n results = []) {\n let index = null;\n let errorName, entries, entryHead, valueCandidate;\n const callback = (typeof callbacks === \"function\")\n ? callbacks\n : (e => thenChainEagerly(e, callbacks));\n try {\n if (!Array.isArray(entriesOrThenables)) {\n if ((entriesOrThenables == null) || (typeof entriesOrThenables.then !== \"function\")) {\n throw new Error(\"mapEagerly: array expected as first argument\");\n }\n errorName = new Error(`mapEagerly.entriesOrThenables.catch`);\n return entriesOrThenables.then(\n entries_ => mapEagerly(entries_, callback, onRejected, startIndex, results),\n errorOnMapEagerly);\n }\n entries = entriesOrThenables;\n for (index = startIndex;\n index < entries.length;\n results[index++] = valueCandidate) {\n entryHead = entries[index];\n if ((entryHead == null) || (typeof entryHead.then !== \"function\")) {\n try {\n valueCandidate = callback(entryHead, index, entries);\n } catch (error) {\n errorName = new Error(getName(\"callback\"));\n return errorOnMapEagerly(error);\n }\n if ((valueCandidate == null) || (typeof valueCandidate.then !== \"function\")) continue;\n errorName = new Error(getName(\"callback thenable resolution\"));\n } else {\n // eslint-disable-next-line no-loop-func\n valueCandidate = entryHead.then(resolvedHead => callback(resolvedHead, index, entries));\n errorName = new Error(getName(\"head or callback promise resolution\"));\n }\n return valueCandidate.then(\n value => { // eslint-disable-line no-loop-func\n results[index] = value;\n return mapEagerly(entries, callback, onRejected, index + 1, results);\n },\n errorOnMapEagerly);\n }\n return results;\n } catch (error) {\n errorName = new Error(getName(\"handling\"));\n return errorOnMapEagerly(error);\n }\n function getName (info) {\n return `mapEagerly step #${index} ${info} ${\n !(onRejected && onRejected.name) ? \" \" : `(with ${onRejected.name})`}`;\n }\n function errorOnMapEagerly (error) {\n let innerError = error;\n try {\n if (onRejected) {\n return onRejected(error,\n (index === null) ? entries : entries[index],\n index, results, entries, callback, onRejected);\n }\n } catch (onRejectedError) { innerError = onRejectedError; }\n throw wrapError(innerError, errorName,\n \"\\n\\tentry head:\", ...dumpObject(entryHead, { nest: 0 }),\n \"\\n\\tmaybePromises:\", ...dumpObject(entries || entriesOrThenables),\n \"\\n\\tcurrent entry:\", ...dumpObject((entries || entriesOrThenables || [])[index]));\n }\n}",
"function tap(arr, callback){\n callback(arr); \n return arr;\n}",
"function any( iterable )\n {\n var res = false;\n \n foreach(function (x)\n {\n if ( x )\n {\n res = true;\n throw StopIteration;\n }\n },\n iterable);\n \n return res;\n }",
"function resolveOnlyIfOnSamePage(promises, store) {\n const ident = x => x;\n return ConditionalPromise.all(promises)\n .only(samePageCheckGenerator(store), ident, ident)._promise;\n}",
"function lookup(xs, pred) /* forall<a,b> (xs : list<(a, b)>, pred : (a) -> bool) -> maybe<b> */ {\n return foreach_while(xs, function(kv /* (21629, 21630) */ ) {\n var _x31 = pred(fst(kv));\n if (_x31) {\n return Just(snd(kv));\n }\n else {\n return Nothing;\n }\n });\n}",
"mapDefined(tryGetOutput) {\n return __awaiter(this, void 0, void 0, function* () {\n const { inputs } = this;\n let writeIndex = 0;\n for (let readIndex = 0; readIndex < inputs.length; readIndex++) {\n const output = yield tryGetOutput(inputs[readIndex]);\n if (output !== undefined) {\n inputs[writeIndex] = output;\n writeIndex++;\n }\n }\n inputs.length = writeIndex;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LOCAL FUNCTIONS function: getLineBreak description: returns line break based on platform | function getLineBreak(theForm){
var retVal;
var selInd = theForm.WhichPlatform.selectedIndex;
switch (selInd){
case 0:
retVal = "\r\n";
break;
case 1:
retVal = "\r";
break;
case 2:
retVal = "\n";
break;
}
return retVal;
} | [
"get lineBreak() {\n return this.facet(EditorState.lineSeparator) || '\\n'\n }",
"insertLinebreak() {\n const prompt = this.prompt;\n const model = prompt.model;\n const editor = prompt.editor;\n // Insert the line break at the cursor position, and move cursor forward.\n let pos = editor.getCursorPosition();\n const offset = editor.getOffsetAt(pos);\n const text = model.value.text;\n model.value.text = text.substr(0, offset) + '\\n' + text.substr(offset);\n // pos should be well defined, since we have inserted a character.\n pos = editor.getPositionAt(offset + 1);\n editor.setCursorPosition(pos);\n }",
"convertLineBreaksToNonBreaking() {\n for (const breakEl of document.querySelectorAll('.coding-line br')) {\n const parentNode = breakEl.parentNode;\n if (parentNode.childNodes.length === 1) {\n parentNode.innerHTML = ' ';\n } else {\n breakEl.remove();\n }\n }\n }",
"function breakOnLine(script, lineno) {\r\n breakOnAbsoluteLine(script, script.baseLineNumber + lineno);\r\n}",
"function printNewLine() {\r\n\tterminal.innerHTML += '\\n';\r\n}",
"function addingDiscretionaryLineBreakForURLs(){\r\n myResetFindChangePref();\r\n//~ app.findGrepPreferences.findWhat = \"https?:\\\\/\\\\/(www\\\\.)?[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)|(www\\\\.)?[-a-zA-Z0-9@:%._\\\\+~#=]{2,256}\\\\.[a-z]{2,6}\\\\b([-a-zA-Z0-9@:%_\\\\+.~#?&//=]*)|([A-Z]{20,})\";\r\n app.findGrepPreferences.findWhat = \"https?:\\\\/\\\\/(www\\\\.)?[\\\\-a-zA-Z0-9@:%\\\\.,;_\\\\+~\\\\#=]{2,256}\\\\.[a-z]{2,6}\\\\b([\\\\-a-zA-Z0-9@:%_\\\\+\\\\.,;~\\\\#?&\\\\/=]*)|(www\\\\.)?[\\\\-a-zA-Z0-9@:%\\\\.,;_\\\\+~\\\\#=]{2,256}\\\\.[a-z]{2,6}\\\\b([\\\\-a-zA-Z0-9@:%_\\\\+\\\\.,;~\\\\#?&\\\\/=]*)|([A-Z]{20,})\";\r\n app.findGrepPreferences.position = Position.NORMAL;\r\n var link = app.activeDocument.findGrep();\r\n var linkLen = link.length;\r\n for (n = linkLen - 1; n >= 0; n--) {\r\n var currLink = link[n].contents;\r\n var linkReturned = addLogicalBreaksToLinks(link[n]);\r\n }\r\n}",
"get widgetLineBreaks() {\n return typeof this._content == 'number' ? this._content : 0\n }",
"handleNewLine(editorState, event) {\n // https://github.com/jpuri/draftjs-utils/blob/e81c0ae19c3b0fdef7e0c1b70d924398956be126/js/keyPress.js#L64\n if (isSoftNewlineEvent(event)) {\n return this.addLineBreak(editorState);\n }\n\n const content = editorState.getCurrentContent();\n const selection = editorState.getSelection();\n const key = selection.getStartKey();\n const offset = selection.getStartOffset();\n const block = content.getBlockForKey(key);\n\n const isDeferredBreakoutBlock = [BLOCK_TYPE.CODE].includes(\n block.getType(),\n );\n\n if (isDeferredBreakoutBlock) {\n const isEmpty =\n selection.isCollapsed() &&\n offset === 0 &&\n block.getLength() === 0;\n\n if (isEmpty) {\n return EditorState.push(\n editorState,\n Modifier.setBlockType(\n content,\n selection,\n BLOCK_TYPE.UNSTYLED,\n ),\n 'change-block-type',\n );\n }\n\n return false;\n }\n\n return this.handleHardNewline(editorState);\n }",
"ensureLineGaps(current) {\n let gaps = [];\n // This won't work at all in predominantly right-to-left text.\n if (this.heightOracle.direction != Direction.LTR)\n return gaps;\n this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.state.doc, 0, 0, line => {\n if (line.length < 10000 /* Margin */)\n return;\n let structure = lineStructure(line.from, line.to, this.state);\n if (structure.total < 10000 /* Margin */)\n return;\n let viewFrom, viewTo;\n if (this.heightOracle.lineWrapping) {\n if (line.from != this.viewport.from)\n viewFrom = line.from;\n else\n viewFrom = findPosition(structure, (this.pixelViewport.top - line.top) / line.height);\n if (line.to != this.viewport.to)\n viewTo = line.to;\n else\n viewTo = findPosition(structure, (this.pixelViewport.bottom - line.top) / line.height);\n }\n else {\n let totalWidth = structure.total * this.heightOracle.charWidth;\n viewFrom = findPosition(structure, this.pixelViewport.left / totalWidth);\n viewTo = findPosition(structure, this.pixelViewport.right / totalWidth);\n }\n let sel = this.state.selection.primary;\n // Make sure the gap doesn't cover a selection end\n if (sel.from <= viewFrom && sel.to >= line.from)\n viewFrom = sel.from;\n if (sel.from <= line.to && sel.to >= viewTo)\n viewTo = sel.to;\n let gapTo = viewFrom - 10000 /* Margin */, gapFrom = viewTo + 10000 /* Margin */;\n if (gapTo > line.from + 5000 /* HalfMargin */)\n gaps.push(find(current, gap => gap.from == line.from && gap.to > gapTo - 5000 /* HalfMargin */ && gap.to < gapTo + 5000 /* HalfMargin */) ||\n new LineGap(line.from, gapTo, this.gapSize(line, gapTo, true, structure)));\n if (gapFrom < line.to - 5000 /* HalfMargin */)\n gaps.push(find(current, gap => gap.to == line.to && gap.from > gapFrom - 5000 /* HalfMargin */ &&\n gap.from < gapFrom + 5000 /* HalfMargin */) ||\n new LineGap(gapFrom, line.to, this.gapSize(line, gapFrom, false, structure)));\n });\n return gaps;\n }",
"function detectSeparator(a, b, step, isNum, isDescending) {\r\n var isChar = isCharClass(a, b, step, isNum, isDescending);\r\n if (!isChar) {\r\n return '|';\r\n }\r\n return '~';\r\n}",
"function splitLines(text) {\n\t return text.split(/\\r?\\n/);\n\t}",
"function BREAK_WORD$static_(){OverflowBehaviour.BREAK_WORD=( new OverflowBehaviour(\"break-word\"));}",
"get defaultLineHeight() {\n return this.viewState.heightOracle.lineHeight\n }",
"function isMultilineDiffBlock ({value}) {\n return value.indexOf('\\n') !== -1\n}",
"insertBreak(editor) {\n editor.insertBreak();\n }",
"function copy_divider_to_clipboard(divider_id)\n{\n\tvar div_data = document.getElementById(divider_id).innerHTML;\n\tvar buffer = div_data.replace(/<BR>/gm,'\\r\\n');\n\twindow.clipboardData.setData(\"Text\", buffer);\n} // end of copy_divider_to_clipboard",
"function _isLineBreakOrBlockElement(element) {\r\n if (_isLineBreak(element)) {\r\n return true;\r\n }\r\n\r\n if (wysihtml5.dom.getStyle(\"display\").from(element) === \"block\") {\r\n return true;\r\n }\r\n\r\n return false;\r\n }",
"function printNewLines(numberOfLines) {\r\n\tfor (var i = 0; i < numberOfLines; i++) { \r\n\t\tdocument.write('<br>');\r\n\t}\r\n}",
"function Divider(text)\n {\n console.log(\"\\r\\n--------------------\");\n console.log(text);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Undo buttton click handler | undoButton() {
this.state.undo();
} | [
"undoAction() {\n this.element.executeOppositeAction(this.details);\n }",
"handleUndoClick() {\n const newStep = this.state.currStep === 0 ? 0 : this.state.currStep - 1;\n let numCount = this.countNums(this.state.history[newStep].board);\n this.setState({\n currStep: newStep,\n numCount: numCount,\n });\n }",
"revert() {\n this.innerHTML = this.__canceledEdits;\n }",
"function undoSentRequests() {\n clickNextButton(\"Undo\", defaultUndoFriendSelector);\n}",
"function post_notes_unhook_controls()\n{\n\tjQuery(\"a.post_note_duplicate\").unbind('click');\n\tjQuery(\"a.post_note_delete\").unbind('click');\n}",
"function deactivateButtons(){\n $scope.clickMemoryButton = null;\n }",
"function unhighlightButton(oButton){\r\n oButton.style.backgroundColor = \"\";\r\n oButton.style.color = \"\";\r\n }",
"undoCheckout() {\n return spPost(File(this, \"undoCheckout\"));\n }",
"function deactivateClicks() {\n\t console.log( \"Deactivating cliker\");\n\tArray.from( ptrAnswers ).forEach( function( item ) {\n\t\titem.removeEventListener( \"click\", answerSelected );\n\t})\n}",
"function cancelEdit() {\n var currentBurger = $(this).data(\"burger\");\n if (currentBurger) {\n $(this).children().hide();\n $(this).children(\"input.edit\").val(currentBurger.text);\n $(this).children(\"span\").show();\n $(this).children(\"button\").show();\n }\n }",
"function deselectAction(prevId) {\n\t//we have to deal with jQuery bug, cannot select 'cz/psp/97'\n\tvar shortPrevIdAr = prevId.split('/');\n var shortPrevId = shortPrevIdAr[shortPrevIdAr.length-1];\n //deselect\n\t$(\".mp-clicked-\"+shortPrevId).addClass('mp-clicked-off');\n\t$(\".mp-clicked-\"+shortPrevId).removeClass('ui-state-highlight mp-clicked-on');\n\t$(\".mp-\"+shortPrevId).draggable({ disabled: false });\n\t$(\".mp-clicked-\"+shortPrevId).draggable({ disabled: false });\n}",
"function cancel(ev) {\n // Set that we should cancel the tap\n cancelled = true;\n // Remove selection on the target item\n $item.removeClass(options.klass);\n // We do not need cancel callbacks anymore\n $el.unbind('drag.tss hold.tss');\n }",
"function removeVisualiserButton(){\r\n\teRem(\"buttonWaves\");\r\n\teRem(\"buttonBars\");\r\n\teRem(\"buttonBarz\");\r\n\teRem(\"buttonCircleBars\");\r\n\teRem(\"buttonCirclePeaks\");\r\n\tremoveSliderSelector();\r\n}",
"function clearAddOnButtons(addOnButtons) {\r\n}",
"function setCancelButtonAction(action) {\n\t\t$cancelButton.unbind('click');\n\t\t$cancelButton.click(action);\n\t}",
"function removeEditAttribute(element) {\n $(editElement).removeAttr(\"contenteditable\");\n var newText = $(editElement).clone().children().remove().end().text();\n if (origText !== newText) {\n var new_data = $(\".drop\").contents().find(\"body\").clone();\n setUndoRedoEvent(old_data, new_data);\n console.log(\"Tag name: \" + element.tagName + \", Text Orig: '\" + origText + \"', New:'\" + newText + \"'\");\n }\n $(editElement).off(\"blur, focusout, click\");\n\n}",
"function unbindFollowUnfollowButton(){\n var unfollowButtons = document.getElementsByClassName(\"unfollow\");\n var followButtons = document.getElementsByClassName(\"follow\");\n for(var x = 0; x < unfollowButtons.length; x++){\n unfollowButtons[x].removeEventListener(\"click\", unfollow);\n }\n for(var x = 0; x < followButtons.length; x++){\n followButtons[x].removeEventListener(\"click\", follow);\n\n }\n}",
"function cancel() {\n history.goBack();\n }",
"function undo() {\n if (stateCurrent === 0) return false;\n stateCurrent--;\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Class for managing objects that need to be downloaded/parsed in memory/saved to disk. This class support resuming jobs with the following features: DownloadToFile will be skipped if target file exists. DownloadToMemory will actually read from disk if file exists. SaveToDisk will be skipped if file exists and will first save to filepath.tmp and then rename to filepath. | function DownloadableObject() {
// Construct object.
this.Init = function(filepath, url) {
this.filepath = filepath;
this.url = url;
};
// Check that we can write the target file.
this.TargetFileExists = function(onComplete) {
fs.access(_that.filepath, fs.constants.W_OK, function(err) {
var file_exist = !err;
onComplete(file_exist);
});
};
// Read target file from disk as buffer.
this.ReadTargetFile = function(onComplete, onError) {
fs.readFile(_that.filepath, function (err, data) {
if (err) {
if (onError) { onError(_that); }
}
else {
_that.file_content = data;
onComplete(_that);
}
});
};
// Download to file (by keeping file fully in memory).
// TODO: pipe directly to disk if file is too big (> 50MB).
this.DownloadToFile = function(onComplete, onError) {
_that.DownloadToMemory(function() {
_that.SaveToDisk(onComplete, onError);
}, onError);
};
// Download to file but do not save 404 file.
this.SilentDownloadToFile = function(onComplete, onError) {
_that.DownloadToMemory(function() {
_that.SaveToDisk(onComplete, onError);
}, onComplete);
};
this.DownloadToMemory = function(onComplete, onError) {
// If filepath is provided, check if file was already saved.
if (_that.filepath) {
_that.TargetFileExists(function(exists) {
if (exists) {
// If file exists, just read it.
_that.ReadTargetFile(onComplete, onError);
} else {
// If it doesn't, download it.
_that.DownloadBuffer(onComplete, onError);
}
});
} else {
console.log("Caching is disabled for \"" + _that.url + "\" as not filepath as been provided prior to DownloadToMemory.");
_that.DownloadBuffer(onComplete, onError);
}
};
this.DownloadBuffer = function(onComplete, onError) {
var downloader = _that.url.indexOf("https://") == -1 ? http : https;
var chunks = [];
downloader.get(_that.url, function(res) {
if (res.statusCode == 404) {
onError(_that);
return;
}
res.on('data', function(chunk) {
chunks.push(chunk)
});
res.on('error', function() {
if (onError) { onError(_that); }
});
res.on('end', function() {
_that.file_content = Buffer.concat(chunks);
onComplete(_that);
});
});
};
this.PostSoapRequest = function(guid, onComplete, onError) {
_that.url = "https://photosynth.net/photosynthws/photosynthservice.asmx";
var request_body = '';
request_body += '<?xml version="1.0" encoding="utf-8"?>';
request_body += '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
request_body += ' <soap:Body>';
request_body += ' <GetCollectionData xmlns="http://labs.live.com/">';
request_body += ' <collectionId>'+guid+'</collectionId>';
request_body += ' <incrementEmbedCount>false</incrementEmbedCount>';
request_body += ' </GetCollectionData>';
request_body += ' </soap:Body>';
request_body += '</soap:Envelope>';
request({
url: _that.url,
method: "POST",
headers: {
"content-type": "text/xml; charset=utf8",
},
body: request_body
}, function (error, response, body){
if (error) {
onError(error);
} else {
_that.file_content = body;
onComplete(body);
}
});
};
// Save content previously downloaded to disk.
this.SaveToDisk = function(onComplete, onError) {
// Skip saving if file already exists.
_that.TargetFileExists(function(exists) {
if (exists) {
onComplete(_that);
} else {
// Write to filepath.tmp file.
fs.writeFile(_that.filepath + ".tmp", _that.file_content, function (err) {
if (err) {
if (onError) { onError(_that); }
}
else {
// Rename filepath.tmp to filepath.
fs.rename(_that.filepath + ".tmp", _that.filepath, function(err) {
if (err) {
if (onError) { onError(_that); }
} else {
onComplete();
}
});
}
});
}
});
};
this.ParseJson = function() {
return JSON.parse(_that.file_content);
};
this.ParseXml = function(onComplete, onError) {
parseString(_that.file_content, function (err, result) {
if (err) {
if (onError) { onError(_that); }
} else {
onComplete(result);
}
});
};
this.Clear = function() {
this.filepath = "";
this.url = "";
this.file_content = "";
};
var _that = this;
this.filepath;
this.url;
this.file_content;
} | [
"downloadModelOBJ() {\n\t\tthis.emitWarningMessage(\"Preparing OBJ file...\", 60000);\n\t\tthis.props.loadingToggle(true);\n\t\twindow.LITHO3D.downloadOBJ(1, 1, 1, true).then(() => {\n\t\t\tthis.props.loadingToggle(false);\n\t\t\tthis.emitWarningMessage(\"File is ready for download.\", 500);\n\t\t})\n\t\t\t.catch(err => {\n\t\t\t\tthis.props.loadingToggle(false);\n\t\t\t\tthis.emitWarningMessage(err.message);\n\t\t\t});\n\t}",
"function FileManager(){\n\t\"use strict\";\n\n\tvar fs, requestQuota, requestFileSystem, errorHandler, setCurrentQuotaUsed, traverseAll, retrieveFile, dirName, dirPrefix,\n\t\tcurrentQuota = null,\n\t\tcurrentQuotaUsed = null,\n\t\tDEFAULTBYTESREQUESTED = 100 * 1024 * 1024;\n\n\tthis.getCurrentQuota = function(){return currentQuota;}; //REMOVE, IS TEMPORARY\n\tthis.getCurrentQuotaUsed = function(){return currentQuotaUsed;};\n\tthis.getFS = function(){return fs;};\n\t\n\t/**\n\t * Initializes the File Manager\n\t * @param {string}\t\t\t\t\tdirectory name of directory to store files in\n\t * @param {{success:Function, error:Function}} callbacks callback functions (error, and success)\n\t * @return {boolean}\t\t\t\t\treturns true/false if File API is supported by browser\n\t */\n\tthis.init = function(directory, callbacks){\n\t\tif (this.isSupported() && directory && directory.length > 0){\n\t\t\tvar that = this;\n\t\t\tdirName = directory;\n\t\t\tdirPrefix = '/'+directory+'/';\n\n\t\t\tsetCurrentQuotaUsed();\n\t\t\trequestQuota(\n\t\t\t\tDEFAULTBYTESREQUESTED,\n\t\t\t\t{\n\t\t\t\t\tsuccess: function(grantedBytes){\n\t\t\t\t\t\trequestFileSystem(\n\t\t\t\t\t\t\tgrantedBytes,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsuccess: function(fsys){\n\t\t\t\t\t\t\t\t\tfs = fsys;\n\t\t\t\t\t\t\t\t\tthat.createDir(\n\t\t\t\t\t\t\t\t\t\tdirName,\n\t\t\t\t\t\t\t\t\t\tcallbacks\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\terror: function(e){\n\t\t\t\t\t\t\t\t\tcallbacks.error(e);\n\t\t\t\t\t\t\t\t\terrorHandler(e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\terror: errorHandler\n\t\t\t\t}\n\t\t\t);\n\t\t\t//TODO: move this to final success eventhandler?\n\t\t\t$(document).on('submissionsuccess', function(ev, recordName, instanceID){\n\t\t\t\tthat.deleteDir(instanceID);\n\t\t\t});\n\t\t\treturn true;\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t}\n\t};\n\n\t/**\n\t * Checks if File API is supported by browser\n\t * @return {boolean}\n\t */\n\tthis.isSupported = function(){\n\t\twindow.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;\n\t\twindow.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;\n\t\twindow.storageInfo = window.storageInfo || window.webkitStorageInfo;\n\t\treturn (typeof window.requestFileSystem !== 'undefined' && typeof window.resolveLocalFileSystemURL !== 'undefined' && typeof window.storageInfo !== 'undefined');\n\t};\n\n\t/**\n\t * Requests PERSISTENT file storage (may prompt user) asynchronously\n\t * @param {number}\t\t\t\t\t\tbytesRequested the storage size in bytes that is requested\n\t * @param {Object.<string, Function>}\tcallbacks callback functions (error, and success)\n\t */\n\trequestQuota = function(bytesRequested, callbacks){\n\t\tconsole.log('requesting persistent filesystem quota');\n\t\t$(document).trigger('quotarequest', bytesRequested); //just to facilitate testing\n\t\twindow.storageInfo.requestQuota(\n\t\t\twindow.storageInfo.PERSISTENT,\n\t\t\tbytesRequested ,\n\t\t\t//successhandler is called immediately if asking for increase in quota\n\t\t\tcallbacks.success,\n\t\t\tcallbacks.error\n\t\t);\n\t};\n\n\t/**\n\t * requests filesystem\n\t * @param {number} bytes\t\twhen called by requestQuota for PERSISTENt storage this is the number of bytes granted\n\t * @param {Object.<string, Function>} callbacks callback functions (error, and success)\n\t */\n\trequestFileSystem = function(bytes, callbacks){\n\t\tconsole.log('requesting file system');\n\t\tconsole.log('quota for persistent storage granted in MegaBytes: '+bytes/(1024 * 1024));\n\t\tif (bytes > 0){\n\t\t\tcurrentQuota = bytes;\n\t\t\twindow.requestFileSystem(\n\t\t\t\twindow.storageInfo.PERSISTENT,\n\t\t\t\tbytes,\n\t\t\t\tcallbacks.success,\n\t\t\t\tcallbacks.error\n\t\t\t);\n\t\t}\n\t\telse{\n\t\t\t//actually not correct to treat this as an error\n\t\t\tconsole.error('User did not approve storage of local data using the File API');\n\t\t\tcallbacks.error();\n\t\t}\n\t};\n\n\t/**\n\t * generic error handler\n\t * @param {(Error|FileError|string)=} e [description]\n\t */\n\terrorHandler = function(e){\n\t\tvar msg = '';\n\n\t\tif (typeof e !== 'undefined'){\n\t\t\tswitch (e.code) {\n\t\t\t\tcase window.FileError.QUOTA_EXCEEDED_ERR:\n\t\t\t\t\tmsg = 'QUOTA_EXCEEDED_ERR';\n\t\t\t\t\tbreak;\n\t\t\t\tcase window.FileError.NOT_FOUND_ERR:\n\t\t\t\t\tmsg = 'NOT_FOUND_ERR';\n\t\t\t\t\tbreak;\n\t\t\t\tcase window.FileError.SECURITY_ERR:\n\t\t\t\t\tmsg = 'SECURITY_ERR';\n\t\t\t\t\tbreak;\n\t\t\t\tcase window.FileError.INVALID_MODIFICATION_ERR:\n\t\t\t\t\tmsg = 'INVALID_MODIFICATION_ERR';\n\t\t\t\t\tbreak;\n\t\t\t\tcase window.FileError.INVALID_STATE_ERR:\n\t\t\t\t\tmsg = 'INVALID_STATE_ERR';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tmsg = 'Unknown Error';\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconsole.log('Error occurred: ' + msg);\n\t\tif (typeof console.trace !== 'undefined') console.trace();\n\t};\n\n\t/**\n\t * Requests the amount of storage used (asynchronously) and sets variable (EXPERIMENTAL/UNSTABLE API)\n\t */\n\tsetCurrentQuotaUsed = function(){\n\t\tif (typeof window.storageInfo.queryUsageAndQuota !== 'undefined'){\n\t\t\twindow.storageInfo.queryUsageAndQuota(\n\t\t\t\twindow.storageInfo.PERSISTENT,\n\t\t\t\tfunction(quotaUsed){\n\t\t\t\t\tcurrentQuotaUsed = quotaUsed;\n\t\t\t\t},\n\t\t\t\terrorHandler\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\tconsole.error('browser does not support queryUsageAndQuota');\n\t\t}\n\t};\n\n\t/**\n\t * Saves a file (asynchronously) in the directory provided upon initialization\n\t * @param {Blob}\t\t\t\t\t\tfile File object from input field\n\t * @param {Object.<string, Function>}\tcallbacks callback functions (error, and success)\n\t */\n\tthis.saveFile = function(file, callbacks){\n\t\tvar that = this;\n\t\tfs.root.getFile(\n\t\t\tdirPrefix + file.name,\n\t\t\t{\n\t\t\t\tcreate: true,\n\t\t\t\texclusive: false\n\t\t\t},\n\t\t\tfunction(fileEntry){\n\t\t\t\tfileEntry.createWriter(function(fileWriter){\n\t\t\t\t\tfileWriter.write(file);\n\t\t\t\t\tfileWriter.onwriteend = function(e){\n\t\t\t\t\t\t//if a file write does not complete because the file is larger than the granted quota\n\t\t\t\t\t\t//the onwriteend event still fires. (This may be a browser bug.)\n\t\t\t\t\t\t//so we're checking if the complete file was saved and if not, do nothing and assume\n\t\t\t\t\t\t//that the onerror event will fire\n\t\t\t\t\t\tif(e.total === e.loaded){\n\t\t\t\t\t\t\t//console.log('write completed', e);\n\t\t\t\t\t\t\tsetCurrentQuotaUsed();\n\t\t\t\t\t\t\tconsole.log('complete file stored, with persistent url:'+fileEntry.toURL());\n\t\t\t\t\t\t\tcallbacks.success(fileEntry.toURL());\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\tfileWriter.onerror = function(e){\n\t\t\t\t\t\tvar newBytesRequest,\n\t\t\t\t\t\t\ttargetError = e.target.error;\n\t\t\t\t\t\tif (targetError instanceof FileError && targetError.code === window.FileError.QUOTA_EXCEEDED_ERR){\n\t\t\t\t\t\t\tnewBytesRequest = ((e.total * 5) < DEFAULTBYTESREQUESTED) ? currentQuota + DEFAULTBYTESREQUESTED : currentQuota + (5 * e.total);\n\t\t\t\t\t\t\tconsole.log('Required storage exceeding quota, going to request more, in bytes: '+newBytesRequest);\n\t\t\t\t\t\t\trequestQuota(\n\t\t\t\t\t\t\t\tnewBytesRequest,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tsuccess: function(bytes){\n\t\t\t\t\t\t\t\t\t\tconsole.log('request for additional quota approved! (quota: '+bytes+' bytes)');\n\t\t\t\t\t\t\t\t\t\tcurrentQuota = bytes;\n\t\t\t\t\t\t\t\t\t\tthat.saveFile(file, callbacks);\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\terror: callbacks.error\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tcallbacks.error(e);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}, callbacks.error);\n\t\t\t},\n\t\t\tcallbacks.error\n\t\t);\n\t};\n\n\t/**\n\t * Obtains specified files from a specified directory (asynchronously)\n\t * @param {string}\t\t\t\t\t\t\t\t\t\t\tdirectoryName\tdirectory to look in for files\n\t * @param {Array.<{nodeName: string, fileName: string}>}\tfiles\t\t\tarray of objects with file properties\n\t * @param {{success:Function, error:Function}}\t\t\t\tcallbacks\t\tcallback functions (error, and success)\n\t */\n\tthis.retrieveFiles = function(directoryName, files, callbacks){\n\t\tvar i, retrievedFiles = [], failedFiles = [],\n\t\t\tpathPrefix = (directoryName) ? '/'+directoryName+'/' : dirPrefix,\n\t\t\tcallbacksForFileEntry = {\n\t\t\t\tsuccess: function(fileEntry){\n\t\t\t\t\tretrieveFile(\n\t\t\t\t\t\tfileEntry,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsuccess: function(file){\n\t\t\t\t\t\t\t\tconsole.debug('retrieved file! ', file);\n\t\t\t\t\t\t\t\tvar index;\n\t\t\t\t\t\t\t\t//TODO: THIS WILL FAIL WHEN FILENAME OCCURS TWICE, problem?\n\t\t\t\t\t\t\t\t$.each(files, function(j, item){\n\t\t\t\t\t\t\t\t\tif (item.fileName === file.name){ \n\t\t\t\t\t\t\t\t\t\tretrievedFiles.push({\n\t\t\t\t\t\t\t\t\t\t\tnodeName: files[j].nodeName,\n\t\t\t\t\t\t\t\t\t\t\tfileName: files[j].fileName,\n\t\t\t\t\t\t\t\t\t\t\tfile: file\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\tconsole.log('value of requested files index i in successhandler: '+i);\n\t\t\t\t\t\t\t\t//if (file.name === files[files.length - 1].fileName){\n\t\t\t\t\t\t\t\tif (retrievedFiles.length + failedFiles.length === files.length){\n\t\t\t\t\t\t\t\t\tconsole.log('files to return with success handler: ', retrievedFiles);\n\t\t\t\t\t\t\t\t\tcallbacks.success(retrievedFiles);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\terror: function(e, fullPath){\n\t\t\t\t\t\t\t\tfailedFiles.push[fullPath];\n\t\t\t\t\t\t\t\tif (retrievedFiles.length + failedFiles.length === files.length){\n\t\t\t\t\t\t\t\t\tconsole.log('though error occurred with at least one file, files to return with success handler: ', retrievedFiles);\n\t\t\t\t\t\t\t\t\tcallbacks.success(retrievedFiles);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcallbacks.error();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\terror: callbacks.error\n\t\t\t};\n\n\t\tif (files.length === 0){\n\t\t\tconsole.log('files length is 0, calling success handler with empty array');\n\t\t\tcallbacks.success([]);\n\t\t}\n\n\t\tfor (i = 0 ; i<files.length ; i++){\n\t\t\tthis.retrieveFileEntry(\n\t\t\t\tpathPrefix+files[i].fileName,\n\t\t\t\t{\n\t\t\t\t\tsuccess: callbacksForFileEntry.success,\n\t\t\t\t\terror: callbacksForFileEntry.error\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t};\n\n\t/**\n\t * Obtains a fileEntry (asynchronously)\n\t * @param {string}\t\t\t\t\t\t\t\tfullPath\tfull filesystem path to the file\n\t * @param {{success:Function, error:Function}}\tcallbacks\tcallback functions (error, and success)\n\t */\n\tthis.retrieveFileEntry = function(fullPath, callbacks){\n\t\tconsole.debug('retrieving fileEntry for: '+fullPath);\n\t\tfs.root.getFile(\n\t\t\tfullPath,\n\t\t\t{},\n\t\t\tfunction(fileEntry){\n\t\t\t\tconsole.log('fileEntry retrieved: ',fileEntry);\n\t\t\t\tconsole.log('persistent URL: ',fileEntry.toURL());\n\t\t\t\tcallbacks.success(fileEntry);\n\t\t\t},\n\t\t\tfunction(e, fullPath){\n\t\t\t\tconsole.error('file with path: '+fullPath+' not found', e),\n\t\t\t\tcallbacks.error(e);\n\t\t\t}\n\t\t);\n\t};\n\n\t/**\n\t * Retrieves a file from a fileEntry (asynchronously)\n\t * @param {FileEntry} fileEntry [description]\n\t * @param {{success:function(File), error: ?function(FileError)}} callbacks [description]\n\t */\n\tretrieveFile = function(fileEntry, callbacks){\n\t\tfileEntry.file(\n\t\t\tcallbacks.success,\n\t\t\tcallbacks.error\n\t\t);\n\t};\n\n\t/**\n\t * Deletes a file from the file system (asynchronously) from the directory set upon initialization\n\t * @param {string}\t\t\t\t\t\t\t\tfileName\t\tfile name\n\t * @param {{success:Function, error:Function}}\tcallbacks\t\tcallback functions (error, and success)\n\t */\n\tthis.deleteFile = function(fileName, callbacks){\n\t\t//console.log('amount of storage used: '+this.getStorageUsed());\n\t\tconsole.log('deleting file: '+fileName);\n\t\tcallbacks = callbacks || {success: function(){}, error: function(){}};\n\t\t//console.log('amount of storage used: '+this.getStorageUsed());\n\t\tfs.root.getFile(\n\t\t\tdirPrefix + fileName,\n\t\t\t{\n\t\t\t\tcreate: false\n\t\t\t},\n\t\t\tfunction(fileEntry){\n\t\t\t\tfileEntry.remove(function(){\n\t\t\t\t\tsetCurrentQuotaUsed();\n\t\t\t\t\tconsole.log(fileName+' removed from file system');\n\t\t\t\t\tcallbacks.success();\n\t\t\t\t});\n\t\t\t},\n\t\t\tfunction(e){\n\t\t\t\terrorHandler(e);\n\t\t\t\tcallbacks.error();\n\t\t\t}\n\t\t);\n\t};\n\n\t/**\n\t * Creates a directory\n\t * @param {string}\t\t\t\t\t\t\t\t\tname name of directory\n\t * @param {{success: Function, error: Function}}\tcallbacks callback functions (error, and success)\n\t */\n\tthis.createDir = function(name, callbacks){\n\t\tvar that = this;\n\n\t\tcallbacks = callbacks || {success: function(){}, error: function(){}};\n\t\tfs.root.getDirectory(\n\t\t\tname,\n\t\t\t{\n\t\t\t\tcreate: true\n\t\t\t},\n\t\t\tfunction(dirEntry){\n\t\t\t\tsetCurrentQuotaUsed();\n\t\t\t\tconsole.log('Directory: '+name+' created (or found)', dirEntry);\n\t\t\t\tcallbacks.success();\n\t\t\t},\n\t\t\tfunction(e){\n\t\t\t\tvar newBytesRequest,\n\t\t\t\t\ttargetError = e.target.error;\n\t\t\t\t//TODO: test this\n\t\t\t\tif (targetError instanceof FileError && targetError.code === window.FileError.QUOTA_EXCEEDED_ERR){\n\t\t\t\t\tconsole.log('Required storage exceeding quota, going to request more.');\n\t\t\t\t\tnewBytesRequest = ((e.total * 5) < DEFAULTBYTESREQUESTED) ? currentQuota + DEFAULTBYTESREQUESTED : currentQuota + (5 * e.total);\n\t\t\t\t\trequestQuota(\n\t\t\t\t\t\tnewBytesRequest,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsuccess: function(bytes){\n\t\t\t\t\t\t\t\tcurrentQuota = bytes;\n\t\t\t\t\t\t\t\tthat.createDir(name, callbacks);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\terror: callbacks.error\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\tcallbacks.error(e);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//TODO: ADD similar request for additional storage if FileError.QUOTA_EXCEEEDED_ERR is thrown as don in saveFile()\n\t\t);\n\t};\n\n\t/**\n\t * Deletes a complete directory with all its contents\n\t * @param {string}\t\t\t\t\t\t\t\t\tname\t\tname of directory\n\t * @param {{success: Function, error: Function}}\tcallbacks\tcallback functions (error, and success)\n\t */\n\tthis.deleteDir = function(name, callbacks){\n\t\tcallbacks = callbacks || {success: function(){}, error: function(){}};\n\t\tconsole.log('going to delete directory: '+name);\n\t\tfs.root.getDirectory(\n\t\t\tname,\n\t\t\t{},\n\t\t\tfunction(dirEntry){\n\t\t\t\tdirEntry.removeRecursively(\n\t\t\t\t\tfunction(){\n\t\t\t\t\t\tsetCurrentQuotaUsed();\n\t\t\t\t\t\tcallbacks.success();\n\t\t\t\t\t},\n\t\t\t\t\tfunction(e){\n\t\t\t\t\t\terrorHandler(e);\n\t\t\t\t\t\tcallbacks.error();\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t},\n\t\t\terrorHandler\n\t\t);\n\t};\n\n\t/**\n\t * Deletes all files stored (for a subsubdomain)\n\t * @param {Function=} callbackComplete\tfunction to call when complete\n\t */\n\tthis.deleteAll = function(callbackComplete){\n\t\tcallbackComplete = callbackComplete || function(){};\n\t\tvar process = {\n\t\t\tentryFound : function(entry){\n\t\t\t\tif (entry.isDirectory){\n\t\t\t\t\tentry.removeRecursively(\n\t\t\t\t\t\tfunction(){\n\t\t\t\t\t\t\tsetCurrentQuotaUsed();\n\t\t\t\t\t\t\tconsole.log('Directory: '+entry.name+ ' deleted');\n\t\t\t\t\t\t},\n\t\t\t\t\t\terrorHandler\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tentry.remove(\n\t\t\t\t\t\tfunction(){\n\t\t\t\t\t\t\tsetCurrentQuotaUsed();\n\t\t\t\t\t\t\tconsole.log('File: '+entry.name+ ' deleted');\n\t\t\t\t\t\t},\n\t\t\t\t\t\terrorHandler\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t\tcomplete : callbackComplete\n\t\t};\n\t\ttraverseAll(process);\n\t};\n\n\t/**\n\t * Lists all files/folders in root (function may not be required)\n\t * @param {Function=} callbackComplete\tfunction to call when complete\n\t */\n\tthis.listAll = function(callbackComplete){\n\t\tcallbackComplete = callbackComplete || function(){};\n\t\tvar entries = [],\n\t\t\tprocess = {\n\t\t\t\tentryFound : function(entry){\n\t\t\t\t\tif (entry.isDirectory){\n\t\t\t\t\t\tentries.push('folder: '+entry.name);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tentries.push('file: '+entry.name);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tcomplete : function(){\n\t\t\t\t\tconsole.log('entries: ', entries);\n\t\t\t\t\tcallbackComplete();\n\t\t\t\t}\n\t\t};\n\t\ttraverseAll(process);\n\t};\n\n\t/**\n\t * traverses all folders and files in root\n\t * @param {{entryFound: Function, complete}} process [description]\n\t */\n\ttraverseAll = function(process){\n\t\tvar entry, type,\n\t\t\tdirReader = fs.root.createReader();\n\t \n\t\t// Call the reader.readEntries() until no more results are returned.\n\t\tvar readEntries = function() {\n\t\t\tdirReader.readEntries (function(results) {\n\t\t\t\tif (!results.length){\n\t\t\t\t\tprocess.complete();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfor (var i=0 ; i<results.length ; i++){\n\t\t\t\t\t\tentry = results[i];\n\t\t\t\t\t\tprocess.entryFound(entry);\n\t\t\t\t\t}\n\t\t\t\t\treadEntries();\n\t\t\t\t}\n\t\t\t}, errorHandler);\n\t\t};\n\t\treadEntries();\n\t};\n}",
"function downloadFile(fileHash){\n //unpack the download info\n var downloadInfo=allDownloadInfos[fileHash];\n var fileInfo=downloadInfo['fileInfo'];\n var fileOwners=downloadInfo['fileOwners'];\n var saveDir=downloadInfo['saveDir'];\n var downloadCallback=downloadInfo['downloadCallback'];\n var downloadProgressCallback=downloadInfo['progressCallback'];\n\n utils.assert(fileInfo['size']>0);\n utils.assert(fileInfo['file'].length>0);\n utils.assert(fileInfo['hash'].length>0);\n //var fileHash=fileInfo['hash'];\n \n var totalBlocksNum=fileBlocks(fileInfo['size']);\n\n // not allowed duplicated file download\n if(fileHash in fileDownloadStates){ \n\t if(fileDownloadStates[fileHash]==DownloadState.DOWNLOAD_OVER){ //the file download has been already over\n\t\tdownloadProgressCallback(totalBlocksNum,1.0); //set progress 100%\n\t\tdownloadCallback(null,filesToSave[fileHash]);\n\t\treturn;\n\t }else if(fileDownloadStates[fileHash]==DownloadState.PAUSED){//user pause download\n\t\treturn;\n\t }\n }\n fileDownloadStates[fileHash]=DownloadState.DOWNLOADING;//the file is processing\n \n global.log.info('fileHash:'+fileHash);\n utils.assert(utils.len(fileOwners)>0); \n availableFileOwners[fileHash]=fileOwners;//store the file owners\n \n var fileBlocksCnt=totalBlocksNum;\n if(fileHash in fileBlocksDownloadLeft){// useful for resume download\n //use history download blocks\n if(fileBlocksDownloadLeft[fileHash].length==0){//history download file OK\n fileDownloadStates[fileHash]=DownloadState.DOWNLOAD_OVER;\n downloadProgressCallback(totalBlocksNum,1.0); //set progress 100%\n downloadCallback(null,filesToSave[fileHash]);\n removeFileDownloadFromQueue(fileHash);\n downloadFileInQueue();\n return;\n }else{//history download\n global.log.info(\"discover history download...\");\n var progress=(1-fileBlocksDownloadLeft[fileHash].length/totalBlocksNum).toFixed(2); //%.2f\n var downloadedBlocks=totalBlocksNum-fileBlocksDownloadLeft[fileHash].length;\n utils.assert(downloadedBlocks>=0 && progress>=0);\n downloadProgressCallback(downloadedBlocks,progress);//report progress\n }\n }else{//new download\n fileBlocksDownloadLeft[fileHash]=utils.range(0,fileBlocksCnt);//record the download state\n }\n downloadHttpConnectionCnt[fileHash]=0;//every download task used socket is init 0\n\n utils.assert(utils.isFunction(downloadCallback));//must provide callback\n utils.assert(utils.isFunction(downloadProgressCallback));//must provide callback\n fileDownloadOverCallbacks[fileHash]=downloadCallback;\n downloadProgressCallbacks[fileHash]=downloadProgressCallback;\n \n\n fs.exists(saveDir, function(exists) {\n if (exists) {\n var savedFile=filesToSave[fileHash];\n var concurrentHttpCnt=Math.min(fileBlocksCnt,config.MAX_HTTP_CONNECTION_CNT);\n global.log.info(\"concurrentHttpCnt:\"+concurrentHttpCnt);\n for(var blockID=0;blockID<concurrentHttpCnt;++blockID){\n downloadBlock(fileInfo,savedFile,blockID);\n } \n } else {\n //utils.assert(false,\"file save dir not exist:\"+saveDir);\n global.log.info(\"file save dir not exist:\"+saveDir);\n fileDownloadOverCallbacks[fileHash](\"saved file dir not exist.\",null);//download file failed\n utils.assert(currentDownloadCnt>=0);\n }\n }); \n}",
"function FlatFile(_ref) {\n var dir = _ref.dir,\n logging = _ref.logging,\n ttl = _ref.ttl;\n\n _classCallCheck(this, FlatFile);\n\n this.games = require('node-persist');\n this.dir = dir;\n this.logging = logging || false;\n this.ttl = ttl || false;\n }",
"function resumeFileDownload(fileHash){\n if(fileHash in fileDownloadStates && fileDownloadStates[fileHash]==DownloadState.PAUSED){\n fileDownloadStates[fileHash]=DownloadState.DOWNLOADING;\n downloadFile(fileHash);\n }\n}",
"_autoSave() {\n clearImmediate(this.autoSaveImmediate);\n this.autoSaveImmediate = null;\n\n const jobsToSave = [];\n const refs = Object.keys(this.autoCreateQueue);\n\n for (let i = 0, iLen = refs.length; i < iLen; i++) {\n const ref = refs[i];\n if (!this.autoCreateQueue[ref]._saved) {\n jobsToSave.push(ref);\n this.autoCreateQueue[ref]._saved = true;\n } else {\n this.autoCreateQueue[ref] = null;\n delete this.autoCreateQueue[ref];\n }\n }\n\n if (!jobsToSave.length) return undefined;\n\n this.log.verbose(`Auto-saving ${jobsToSave.length} jobs.`);\n\n if (jobsToSave.length === 1) {\n return this.autoCreateQueue[jobsToSave[0]]\n .withoutProxy()\n .save(true)\n .then(() => this._cleanupAutoSave.call(this, null, jobsToSave))\n .catch(error => this._cleanupAutoSave.call(this, error, jobsToSave));\n }\n\n /* eslint no-confusing-arrow: 0 */\n return Promise\n .map(jobsToSave, (ref) => {\n if (this.autoCreateQueue && this.autoCreateQueue[ref]) {\n return this.autoCreateQueue[ref].withoutProxy().save(true);\n }\n return Promise.resolve();\n })\n .then(() => this._cleanupAutoSave.call(this, null, jobsToSave))\n .catch(error => this._cleanupAutoSave.call(this, error, jobsToSave));\n }",
"function FileQueue() {\n size = 0;\n}",
"function StorageDelegate() {\n}",
"FileLoader() {}",
"function FileOperation(name, path, defer) {\n if (!defer.promise) {\n console.trace();\n console.log(defer);\n throw \"YOU THINK THIS IS A DEFER?@!\";\n }\n this.originalFS = null;\n this.name = name;\n this.path = path;\n this.defer = defer;\n this.result = null;\n this.error = null;\n this.active = false;\n this.fh = null;\n this.openDefer = q.defer();\n this.closeDefer = null;\n var destroyer = this.destroy.bind(this);\n defer.promise.then(destroyer, destroyer);\n }",
"function processJobs () {\n jobs.process('url_jobs', function(job, cb) {\n fetchHTMLAndStore(job.data.URL, job.id, function(fetchError, resp) {\n if(fetchError) return cb(new Error('Job with jobId' + job.id + ' could not be processed'));\n // Job is removed from the queue after it has been processed\n job.remove(function(err){\n if (err) console.log(\"Job was processed but could not be removed from the queue\");\n console.log('Job removed ', job.id);\n return cb()\n });\n });\n });\n}",
"function pauseFileDownload(fileHash){\n if(fileHash in fileDownloadStates && fileDownloadStates[fileHash]==DownloadState.DOWNLOADING){\n fileDownloadStates[fileHash]=DownloadState.PAUSED;\n }\n}",
"function LoadOBJObject() {\r\n var mtlLoader = new THREE.MTLLoader();\r\n mtlLoader.setResourcePath(tempStorePath + lastUploadedObjectName.split(\".\")[0] + '/');\r\n mtlLoader.setPath(tempStorePath + lastUploadedObjectName.split(\".\")[0] + '/');\r\n mtlLoader.load(lastUploadedObjectName.split(\".\")[0] + '.mtl', function (materials) {\r\n materials.preload();\r\n var objLoader = new THREE.OBJLoader();\r\n objLoader.setMaterials(materials);\r\n objLoader.setPath(tempStorePath + lastUploadedObjectName.split(\".\")[0] + '/');\r\n objLoader.load(lastUploadedObjectName, function (object) {\r\n //add object to scene and array\r\n addNewObjectToProject(object, myTypes.importedObject);\r\n //Remove files when object is on scene\r\n removeTempFolder();\r\n });\r\n });\r\n}",
"function File() {\n \n /**\n The id of the file (if stored in the FC).\n * @name File#id\n * @type number\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.id = undefined; \n /**\n The size of the file in bytes.\n * @name File#size\n * @type number\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.size = undefined; \n /**\n Return the URL of the file (if stored in the FC).\n * @name File#url\n * @type string\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.url = undefined; \n /**\n The path to the file in the file cabinet.\n * @name File#path\n * @type string\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.path = undefined; \n /**\n The type of the file.\n * @name File#fileType\n * @type string\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.fileType = undefined; \n /**\n * Indicates whether or not the file is text-based or binary.\n * @name File#isText\n * @type boolean\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.isText = undefined; \n /**\n * The character encoding for the file.\n * @name File#encoding\n * @type string\n */ \n this.prototype.encoding = undefined; \n /**\n * The name of the file.\n * @name File#name\n * @type string\n */ \n this.prototype.name = undefined; \n /**\n * The internal ID of the folder that this file is in.\n * @name File#folder\n * @type number\n */ \n this.prototype.folder = undefined; \n /**\n * The file description.\n * @name File#description\n * @type string\n */ \n this.prototype.description = undefined; \n /**\n * The file's inactive status.\n * @name File#isInactive\n * @type boolean\n */ \n this.prototype.isInactive = undefined; \n /**\n * The file's \"Available without Login\" status.\n * @name File#isOnline\n * @type boolean\n */ \n this.prototype.isOnline = undefined; \n /**\n * @name File#lines\n * @type {Iterator} iterator - Iterator which provides the next line of text from the text file to the iterator function.\n * <pre> file.lines.iterator().each(function(lineContext){...}); </pre>\n *\n * @throws {SuiteScriptError} YOU_CANNOT_READ_FROM_A_FILE_AFTER_YOU_BEGAN_WRITING_TO_IT if you call after having called appendLine\n * @readonly\n */ \n this.prototype.lines = undefined; \n /**\n * Return the value (Base64 encoded for binary types) of the file.\n * Note: Contents are lazy loaded and must be less than 10MB in size in order to access.\n *\n * @throws {SuiteScriptError} SSS_FILE_CONTENT_SIZE_EXCEEDED when trying to get contents of a file larger than 10MB\n *\n * @return {string}\n */ \n this.prototype.getContents = function(options) {}; \n \n /**\n * Add/update a file in the file cabinet based on the properties of this object.\n *\n * @governance 20 units\n *\n * @throws {SuiteScriptError} SSS_MISSING_REQD_ARGUMENT when the folder property is not set\n * @throws {SuiteScriptError} INVALID_KEY_OR_REF if trying to save to a non-existing folder\n *\n * @return {number} return internal ID of file in the file cabinet\n *\n * @since 2015.2\n */ \n this.prototype.save = function(options) {}; \n \n /**\n * Append a chunk of text to the file.\n *\n * @param {Object} options\n * @param {string} options.value text to append\n * @return {file} Returns this file\n * @throws {SuiteScriptError} YOU_CANNOT_WRITE_TO_A_FILE_AFTER_YOU_BEGAN_READING_FROM_IT If you call it after having called FileLines#each\n * @since 2017.1\n */ \n this.prototype.append = function(options) {}; \n \n /**\n * Append a line of text to the file.\n *\n * @param {Object} options\n * @param {string} options.value text to append\n * @return {file} Returns this file\n * @throws {SuiteScriptError} YOU_CANNOT_WRITE_TO_A_FILE_AFTER_YOU_BEGAN_READING_FROM_IT If you call it after having called FileLines#each\n * @since 2017.1\n */ \n this.prototype.appendLine = function(options) {}; \n \n /**\n * Reset the reading and writing streams that may have been opened by appendLine or FileLines#each\n *\n * @since 2017.1\n */ \n this.prototype.resetStream = function(options) {}; \n \n /**\n * Returns the object type name (file.File)\n *\n * @returns {string}\n */ \n this.prototype.toString = function(options) {}; \n \n /**\n * JSON.stringify() implementation.\n *\n * @returns {{type: string, id: *, name: *, description: *, path: *, url: *, folder: *, fileType: *, isText: *,\n * size: *, encoding: *, isInactive: *, isOnline: *, contents: *}}\n */ \n this.prototype.toJSON = function(options) {}; \n}",
"makeCache(params, progressCallback, errorCallback, done) {\n if (!params) {\n return errorCallback('No parameters supplied')\n }\n if (!params.style.sources || !Object.keys(params.style.sources).length) {\n return errorCallback('Please provide one or more sources to cache')\n }\n if (!params.bounds || !params.bounds.length || params.bounds.length != 4) {\n return errorCallback('Please provide a valid bbox ( [minLng, minLat, maxLng, maxLat] )')\n }\n if (!params.hasOwnProperty('minZoom')) {\n return errorCallback('A minZoom is required')\n }\n if (!params.maxZoom) {\n return errorCallback('A maxZoom is required')\n }\n // If no name is provided set it to the current time\n params.name = params.name || new Date().toISOString().slice(0,19).replace('T', ':')\n\n let src = params\n\n /*\n TODO: Check if the provided name already exists - if so append the current time\n */\n\n src.size = 0\n src['created'] = new Date()\n\n // Immediately add the requested cache to the list of caches\n let transaction = this.db.transaction(['caches'], 'readwrite')\n\n let store = transaction.objectStore('caches')\n store.onerror = event => {\n if (this.options.debug) {\n console.error('Could not create a new transaction on the \"caches\" objectStore', event)\n }\n }\n let add = store.put(src)\n\n add.onerror = event => {\n if (this.options.debug) {\n console.error('Could not write to the \"caches\" objectStore', event)\n }\n }\n\n // If the source isn't specified as 'offline-' append it to the cached style\n let modifiedSources = {}\n Object.keys(params.style.sources).forEach(source => {\n modifiedSources[source] = params.style.sources[source]\n modifiedSources[source].type = (modifiedSources[source].type.indexOf('offline') > -1) ? modifiedSources[source].type : `offline-${modifiedSources[source].type}`\n })\n\n params.style.sources = modifiedSources\n\n // Return a TileDownloadManager that has an abort method to cancel the creation of the cache\n return new TileDownloadManager(this.db, this.accessToken, params, progressCallback, errorCallback, done)\n }",
"start(options={}){ //sent_from_job = null\n //out(\"Top of Job.\" + this.name + \".start()\")\n let the_active_job_with_robot_maybe = Job.active_job_with_robot(this.robot) //could be null.\n //must do this before setting status_code to \"starting\".\n //there can only be one Job trying to use a Dexter. (at least as the Job's main robot.)\n if((this.robot instanceof Dexter) && the_active_job_with_robot_maybe) {\n this.stop_for_reason(\"errored\", \"Dexter.\" + this.robot.name +\n \" already running Job.\" + the_active_job_with_robot_maybe.name)\n dde_error(\"Attempt to start Job.\" + this.name + \" with Dexter.\" + this.robot.name +\n \",<br/>but that Dexter is already running Job.\" + the_active_job_with_robot_maybe.name +\n \",<br/>so Job.\" + this.name + \" was automatically stopped.\")\n }\n if(this.wait_until_this_prop_is_false) { this.wait_until_this_prop_is_false = false } //just in case previous running errored before it could set this to false, used by start_objects\n if ([\"starting\", \"running\", \"stopping\", \"running_when_stopped\", \"suspended\", \"waiting\"].includes(this.status_code)){\n //does not run when_stopped instruction.\n dde_error(\"Attempt to restart job: \" + this.name +\n \" but it has status code: \" + this.status_code +\n \" which doesn't permit restarting.\")\n }\n else if ([\"not_started\", \"completed\", \"errored\", \"interrupted\"].includes(this.status_code)){\n let early_robot = this.orig_args.robot\n if(options.hasOwnProperty(\"robot\")) { early_robot = options.early_robot }\n //if(early_robot instanceof Dexter) { early_robot.remove_from_busy_job_array(this) }\n Dexter.remove_from_busy_job_arrays(this)\n }\n //active jobs & is_busy checking\n let early_start_if_robot_busy = this.orig_args.start_if_robot_busy\n if (options && options.hasOwnProperty(\"start_if_robot_busy\")) { early_start_if_robot_busy = options.start_if_robot_busy }\n if((this.robot instanceof Dexter) && //can 2 jobs use a Robot.Serial? I assume so for now.\n !early_start_if_robot_busy &&\n this.robot.is_busy()) {\n let one_active_job = this.robot.busy_job_array[0]\n let but_elt = window[one_active_job.name + \"_job_button_id\"]\n this.stop_for_reason(\"errored\", \"Another job: \" + one_active_job.name +\n \" is using robot: \" + this.robot.name)\n if(but_elt){\n let bg = but_elt.style[\"background-color\"]\n dde_error(\"Job.\" + this.name + \" attempted to use: Dexter.\" + this.robot.name +\n \"<br/>but that robot is in use by Job.\" + one_active_job.name +\n \"<br/>Click the <span style='color:black; background-color:\" + bg + \";'> \" +\n one_active_job.name + \" </span> Job button to stop it, or<br/>\" +\n \"create Job.\" + this.name + \" with <code>start_if_robot_busy=true</code><br/>\" +\n \"to permit it to be started.\")\n }\n else {\n dde_error(\"Job.\" + this.name + \" attempted to use: Dexter.\" + this.robot.name +\n \"<br/>but that robot is in use by Job.\" + one_active_job.name + \"<br/>\" +\n \"Create Job.\" + this.name + \" with <code>start_if_robot_busy=true</code><br/>\" +\n \"to permit it to be started.\")\n }\n return\n }\n //init from orig_args\n this.set_status_code(\"starting\") //before setting it here, it should be \"not_started\"\n this.wait_until_instruction_id_has_run = null //needed the 2nd time we run this job, init it just in case it didn't get set to null from previous job run\n //this.init_do_list(options.do_list)\n this.do_list = this.orig_args.do_list\n this.callback_param = this.orig_args.callback_param\n this.keep_history = this.orig_args.keep_history\n this.show_instructions = this.orig_args.show_instructions\n this.inter_do_item_dur = this.orig_args.inter_do_item_dur\n this.user_data = shallow_copy_lit_obj(this.orig_args.user_data)\n this.default_workspace_pose = this.orig_args.default_workspace_pose\n this.program_counter = this.orig_args.program_counter //see robot_done_with_instruction as to why this isn't 0,\n //its because the robot.start effectively calls set_up_next_do(1), incrementing the PC\n this.ending_program_counter = this.orig_args.ending_program_counter\n this.initial_instruction = this.orig_args.initial_instruction\n this.data_array_transformer = this.orig_args.data_array_transformer\n this.get_dexter_defaults = this.orig_args.get_dexter_defaults\n this.start_if_robot_busy = this.orig_args.start_if_robot_busy\n this.if_robot_status_error = this.orig_args.if_robot_status_error\n this.if_instruction_error = this.orig_args.if_instruction_error\n this.if_dexter_connect_error = this.orig_args.if_dexter_connect_error\n this.when_do_list_done = this.orig_args.when_do_list_done\n this.when_stopped = this.orig_args.when_stopped\n this.when_stopped_conditions = ((typeof(this.orig_args.when_stopped_conditions) == \"boolean\") ?\n this.orig_args.when_stopped_conditions :\n Object.assign({}, this.orig_args.when_stopped_conditions)) //make a copy in case it was munged in the previous running of the job\n\n //first we set all the orig (above), then we over-ride them with the passed in ones\n for (let key in options){\n if (options.hasOwnProperty(key)){\n let new_val = options[key]\n //if (key == \"program_counter\") { new_val = new_val - 1 } //don't do. You set the pc to the pos just before the first instr to execute.\n //if (key == \"do_list\") { continue; } //flattening & setting already done by init_do_list\n if (key == \"user_data\") { new_val = shallow_copy_lit_obj(new_val) }\n else if (key == \"name\") {} //don't allow renaming of the job\n else if ((key == \"when_stopped\") &&\n !Job.is_plausible_when_stopped_value(new_val)) {\n dde_error(\"Job.start called with an invalid value for 'when_stopped' of: \" +\n new_val)\n return\n }\n this[key] = new_val\n }\n else if (!Job.job_default_params.hasOwnProperty(key)){\n warning(\"Job.start passed an option: \" + key + \" that is unknown. This is probably a mistake.\")\n }\n }\n this.init_do_list()\n\n let maybe_symbolic_pc = this.program_counter\n this.program_counter = 0 //just temporarily so that instruction_location_to_id can start from 0\n const job_in_pc = Job.instruction_location_to_job(maybe_symbolic_pc, false)\n if ((job_in_pc != null) && (job_in_pc != this)) {\n dde_error(\"Job.\" + this.name + \" has a program_counter initialization<br/>\" +\n \"of an instruction_location that contains a job that is not the job being started. It shouldn't.\")\n return\n }\n this.program_counter = this.instruction_location_to_id(maybe_symbolic_pc)\n\n //this.robot_status = [] use this.robot.robot_status instead //only filled in when we have a Dexter robot by Dexter.robot_done_with_instruction or a Serial robot\n this.rs_history = [] //only filled in when we have a Dexter robot by Dexter.robot_done_with_instruction or a Serial robot\n this.sent_instructions = []\n this.sent_instructions_strings = []\n\n this.start_time = new Date()\n this.stop_time = null\n this.stop_reason = null\n\n this.wait_reason = null //not used when waiting for instruction, but used when status_code is \"waiting\"\n this.wait_until_instruction_id_has_run = null\n this.highest_completed_instruction_id = -1\n\n\n\n //this.iterator_stack = []\n if (this.sent_from_job_instruction_queue.length > 0) { //if this job hasn't been started when another job\n // runs a sent_to_job instruction to insert into this job, then that\n //instruction is stuck in this job's sent_from_job_instruction_queue,\n //so that it can be inserted into this job when it starts.\n //(but NOT into its original_do_list, so its only inserted the first time this\n //job is run.\n Job.insert_instruction(this.sent_from_job_instruction_queue, this.sent_from_job_instruction_location)\n }\n this.sent_from_job_instruction_queue = [] //send_to_job uses this. its on the \"to_job\" instance and only stores instructions when send_to_job has\n //where_to_insert=\"next_top_level\", or when this job has yet to be starter. (see above comment.)\n this.sent_from_job_instruction_location = null\n if (this.initial_instruction) { //do AFTER the sent_from_job_instruction_queue insertion.\n Job.insert_instruction(this.initial_instruction, {job: this, offset: \"program_counter\"})\n }\n //must be after insert queue and init_instr processing\n if ((this.program_counter == 0) &&\n (this.do_list.length == 0) &&\n ((this.when_do_list_done == \"wait\") || (typeof(this.when_stopped) == \"function\"))) {} //special case to allow an empty do_list if we are waiting for an instruction or have a callback.\n else if (this.do_list.length == 0) {\n warning(\"While starting job: \" + this.name + \", the do_list is empty.<br/>\" +\n \"The job still requests the status of Dexter, but does not cause it to move.\")\n }\n else if (this.program_counter >= this.do_list.length){ //note that maybe_symbolic_pc can be \"end\" which is length of do_list which is valid, though no instructions would be executed in that case so we error.\n dde_error(\"While starting job: \" + this.name +\n \"<br/>the program_counter is initialized to: \" + this.program_counter +\n \"<br/>but the highest instruction ID in the do_list is: \" + (this.do_list.length - 1))\n }\n Job.last_job = this\n this.go_state = true\n\n this.already_started_when_stopped = false\n this.final_status_code = null\n this.condition_when_stopped = null\n\n this.show_progress_maybe()\n //console.log('calling robot.start from job.start')\n //out(\"Bottom of Job.\" + this.name + \".start() calling \" + this.robot.name + \".start()\")\n this.robot.start(this) //the only call to robot.start\n return this\n }",
"_reset() {\n this._uploadState = {\n // exponential backoff, coming soon!\n inBackoff: false,\n backoffFactor: 0,\n\n // available pool of workers that are ready to perform, or are performing\n idleWorkers: this._generateMaxIdleWorkers(),\n workerAssignments: {}, // { chunkNumber: UploadWorker, ... }\n\n // the state of this UploadManager\n inProgress: false,\n\n // chunk state\n nextChunkNumber: 0, // the next chunk number to assign (!= the number uploaded as there could be uploads in flight)\n numChunksUploaded: 0,\n expectedNumChunksToUpload: 0, // the total number of chunks that should be uploaded, set in perform()\n };\n }",
"async function importObjects(argv) {\n const url = new URL(argv.url);\n url.search = argv.overwrite ? '?overwrite=true' : '';\n url.pathname = `/api/saved_objects/_import`;\n\n const buffer = await fs.readFile(argv.file, 'binary');\n const form = new FormData();\n form.append('file', buffer, {\n contentType: 'text/plain',\n name: 'file',\n filename: argv.file,\n });\n\n logger.info('loading saved objects from ' + argv.file);\n const options = {\n method: 'POST',\n headers: {\n 'kbn-xsrf': true,\n form: form.getHeaders(),\n },\n };\n\n try {\n const res = await fetch(url, { ...options, body: form });\n const body = JSON.stringify(await res.json(), null, 2);\n if (res.status === 200) {\n logger.info(`${res.status} ${res.statusText} Response:\\n${body}`);\n } else {\n logger.error(`${res.status} ${res.statusText} Error: ${body}`);\n }\n } catch (FetchError) {\n logger.error(`${FetchError.message}`);\n }\n}",
"function NetFile(href, document)\n{\n this.href = href;\n this.document = document;\n this.serial = ++gSerialNumber;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Contacts Balancer's The Graph API endpoint to query pool data | async function getBalancerGraph() {
// Balancer's The Graph API URL
const APIURL =
"https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-polygon-v2";
// query request with result settings
const poolsQuery = `
query {
pools(first: 100, orderBy: totalLiquidity, orderDirection: desc) {
id
name
owner
symbol
tokens {
id
name
symbol
address
}
address
poolType
totalLiquidity
totalSwapVolume
}
}
`;
// create new Apollo client
const client = new ApolloClient({
uri: APIURL,
cache: new InMemoryCache(),
});
// query data with query config object
await client
.query({
query: gql(poolsQuery),
})
.then((data) => {
balancerPoolData = data.data.pools;
// console.log("subgraph data: ", data);
// console.log("var data: ", balancerPoolData);
})
.catch((err) => {
console.log("Error fetching data: ", err);
});
} | [
"queryPool() {\n const request = new types.staking_query_pb.QueryPoolRequest();\n return this.client.rpcClient.protoQuery('/cosmos.staking.v1beta1.Query/Pool', request, types.staking_query_pb.QueryPoolResponse);\n }",
"function PoolRequests (){ \n return myContract.methods.getRequestCount().call().then(function(totalCount){ \n console.log(\"-----------------------------------------------------\");\n console.log(\"Total Request since start = \", totalCount);\n }).then(function(){\t \n return myContract.methods.getRequestPool().call().then(function(pool){ \n console.log(\"Active Request pool: total = \", pool.length);\n console.log(pool);\n return pool;\n })\n }).then(function(pool){\t\n ListoutPool(pool, 'request');\n }).catch(function(err){ //catch any error at end of .then() chain!\n console.log(\"List Pool Request Info Failed! \")\n console.log(err);\n process.exit();\n }) \n}",
"static async collegeList(){\n const result=await pool.query('SELECT * FROM college');\n return result;\n }",
"componentDidMount() {\n API.getPool(this.props.match.params.id)\n .then(res => this.setState({ pool: res.data }))\n .catch(err => console.log(err));\n }",
"function queryBuoyInstances() {\n server.getBuoyInstances().then(function(res) {\n vm.buoyInstances = res.data.buoyInstances;\n formatBuoys();\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }",
"function get_loads(req){\r\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\r\n //Limit to three boat results per page\r\n var q = datastore.createQuery(LOAD).limit(5);\r\n\r\n var results = {};\r\n\r\n if(Object.keys(req.query).includes(\"cursor\")){\r\n q = q.start(req.query.cursor);\r\n }\r\n\r\n return datastore.runQuery(q).then( (entities) => {\r\n results.loads = entities[0].map(ds.fromDatastore);\r\n for (var object in results.loads)\r\n {\r\n if(results.loads[object].carrier.length === 1)\r\n {\r\n var bid = results.loads[object].carrier[0];\r\n var boatUrl = req.protocol + '://' + req.get('host') + '/boats/' + bid;\r\n results.loads[object].carrier = [];\r\n results.loads[object].carrier = {\"id\": bid, \"self\": boatUrl};\r\n }\r\n \r\n // Make sure self link does not have cursor in it\r\n if(Object.keys(req.query).includes(\"cursor\"))\r\n {\r\n results.loads[object].self = req.protocol + '://' + req.get('host') + results.loads[object].id;\r\n }\r\n else\r\n {\r\n results.loads[object].self = fullUrl +'/' + results.loads[object].id;\r\n }\r\n }\r\n if(entities[1].moreResults !== ds.Datastore.NO_MORE_RESULTS){\r\n results.next = req.protocol + \"://\" + req.get(\"host\") + req.baseUrl + \"?cursor=\" + encodeURIComponent(entities[1].endCursor);\r\n }\r\n }).then(() =>{\r\n return count_loads().then((number) => {\r\n results.total_count = number;\r\n return results; \r\n });\r\n });\r\n}",
"async connect(props) {\n let blockl = props.block_lot ? clean(props.block_lot) : props.BL ? clean(props.BL) : 'NoBlocklot'\n let query = this.root+'&table='+this.layerLayer+'&fields=block_lot&fieldsVals='+blockl+'&purpose=connect';\n let serverReturnedThis = Object.values(await fetchData(query));\n //console.log('Operation : GetBlocklotsAssociatedRecords, Query Sent : ', query, ', Server Returned :', serverReturnedThis);\n return serverReturnedThis;\n }",
"async index({ params: { companyId }, request, response, auth }) {\n const user = await auth.getUser();\n const company = await user.company().fetch();\n const purchases = await company\n .purchases()\n .with('products')\n .fetch();\n\n response.status(200).json({\n message: 'Listado de compras',\n purchases: purchases,\n });\n }",
"static getStatistics(){\n\t\tlet kparams = {};\n\t\treturn new kaltura.RequestBuilder('partner', 'getStatistics', kparams);\n\t}",
"static async allColleges(limit,offset){\n const result=await pool.query('SELECT * FROM college ORDER BY collegecode LIMIT ?,?',[Number(offset),Number(limit)]);\n return result;\n }",
"function getBuses(admin) {\r\n\tvar query =\r\n`\r\nSELECT DISTINCT b.B_ID, b.Type, b.Status, r.R_Name\r\nFROM BUS b, ROUTE r, ROUTE_ASSIGNED a\r\nWHERE (b.B_ID = a.B_ID)\r\nAND (r.R_ID = a.R_ID)\r\n`\r\n\r\n\tif (!(admin)) query = 'SELECT B_ID, Type FROM BUS'\r\n\r\n\treturn tp\r\n\t.sql(query)\r\n\t.execute()\r\n\t.then(function(results){\r\n\t\treturn Promise.resolve(results)\r\n\t}) // follow up on the results\r\n\t.fail(function(err) {\r\n\t\treturn Promise.reject(err)\r\n\t}) // or do something if it errors\r\n}",
"taskList(req, res) {\n console.log('req.query>>>>>>>>>>>>>>>>>>>>.',req.query);\n con.query(\"SELECT * FROM `object_query_31` where ActiveStatus=? AND RelatedToId=? AND RelatedToObject=?\",[1,req.query.Id,req.query.Object],function(err, result) {\n if (err)\n throw err;\n else {\n console.log('resultt task>>>>>>>>>>>>..',result);\n return res.status(200).json({\n tasks: result\n })\n }\n })\n }",
"leadList(req, res) {\n\n con.query(\"SELECT * FROM `object_query_22` where ActiveStatus=1\", function(err, result) {\n if (err)\n throw err;\n else {\n\n return res.status(200).json({\n leads: result\n })\n }\n })\n }",
"function queryBuoys() {\n server.getBuoys().then(function(res) {\n vm.buoys = res.data.buoys;\n formatBuoys();\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }",
"getStats() {\n const propertyId = this.props.property.propertyId;\n axios.get(`http://localhost:1235/statistics/${propertyId}?distance=1755000`)\n .then(res => {\n this.setState({\n building_area_sqm: res.data.building_area_sqm,\n parcel_area_sqm: res.data.parcel_area_sqm,\n zone_density: res.data.zone_density,\n building_distances_m: res.data.building_distances_m,\n })\n })\n }",
"function getDetail(){\n console.log('Now for each page');\n\n companiesArr = companyListObj.companiesArr;\n companyList = companyListObj.companyListBuf;\n\n this.eachThen(companyList, function(res){\n console.log('Company: '+res.data.company);\n getCompanyDetail.call(this, res.data.businessId);\n }).then(function(){\n this.run(goNextPage);\n });\n}",
"summary_stats(node) {\n return merge({\n path : `/api/v1/nodes/${node}/proxy/stats/summary`,\n method : 'GET',\n }, this.master_api);\n }",
"function getPool(name='_default'){\n // pool exists ?\n if (name in _pools){\n return _pools[name];\n }else{\n throw new Error('Unknown pool <' + name + '> requested');\n }\n}",
"async getRecords(fieldValuePairs){\n let {fields, fieldsVals} = this.inputHandler(fieldValuePairs);\n\n // Get the records\n let query = this.root+'table='+this.layerLayer+'&fields='+fields+'&fieldsVals='+fieldsVals+'&purpose=records';\n let records = Object.values(await fetchData(query));\n console.log('Operation : getRecordsP1, Query Sent : ', query, ', Server Returned :', records);\n\n // Handle returnsDistinct.\n let getData = false;\n if( this.returnDistinct ){\n if(records.length > 1){ records = records.filter( record => record.fields === fieldsVals ) }\n if(records.length == 1){ getData = true }\n else if (records.length == 0){ alert('Search must return no more than 1 address') }\n }\n else if(!this.returnDistinct && records.length >= 1){ getData = true }\n else{ alert('No Data Found') }\n\n // Retrieve Points / Geometries From the Record(s).\n let uniqueBlockLots = getData == true ? [...new Set(records.map(record => record['block_lot']))] : [];\n\n // Contruct a GeoJson Object. \n // 1) if (uniqueBlockLots.length == 0) - do nothin\n // 2) else if( this.returnParcel && this.layerLayer != 'property_details' ) - // Retrieve Esri Parcel Geometries\n // 3) else if( uniqueBlockLots.length ) -\n // 4) else - error\n\n fieldsVals = ''; query = ''; let coords = []; let returnThis = []; let firstItem = true;\n if (uniqueBlockLots.length == 0){ }\n else if( this.returnParcel && this.layerLayer != 'property_details' ){\n\n // Retrieve Esri Parcel Geometries\n uniqueBlockLots.map( (blocklot, i) => { \n if(i>=1){ fieldsVals += '+OR+' };\n let loc = blocklot.split(\" \")[0]; let lot = blocklot.split(\" \")[1]; let blockl = blocklot.replace(/ /g, \"+\")\n fieldsVals += 'Blocklot+%3D+%27'+blockl+'%27+'; // Blocklot = '012 0015'\n fieldsVals += 'OR+%28lot+%3D+%27'+lot+'%27+AND+Block+%3D+%27'+loc+'%27%29+' // OR (lot='0015' AND Block = '012')\n fieldsVals += 'OR+%28lot+%3D+%27'+loc+'%27+AND+Block+%3D+%27'+lot+'%27%29' // OR (lot = '012' AND Block ='0015')\n } )\n coords = await this.parcelGeometry( fieldsVals );\n coords = coords.features.map(attr => attr)\n \n // Insert Geometries into each Record\n returnThis = records.map( (record, i) => {\n\n // Get the Parcel at each Blocklot\n let parcel = coords.filter( uniqueParcel => {\n let flag = uniqueParcel.properties['Blocklot'] == record['block_lot'];\n flag = flag ? flag : uniqueParcel.properties['BLOCK'] == record['block']\n flag = flag ? flag : uniqueParcel.properties['LOT'] == record['lot']\n flag = flag ? flag : uniqueParcel.properties['LOT'] +\" \"+uniqueParcel.properties['BLOCK'] == record['block_lot']\n return flag\n } )[0]\n var outGeoJson = {}\n outGeoJson['properties'] = record;\n outGeoJson['type']= \"Feature\";\n\n // If coordinates are found insert them into the record \n if(parcel != []){\n if(parcel['geometry'] && parcel['geometry']['coordinates']){ outGeoJson['geometry']= parcel['geometry'] }\n else if(record && record['xcord']){ outGeoJson['geometry']= {\"type\": \"Point\", \"coordinates\": [record['ycord'], record['xcord']] } }\n else{ outGeoJson['geometry']= {\"type\": \"Point\", \"coordinates\": [undefined,undefined] } }\n } else{ alert('parcel could not be found'); }\n return outGeoJson\n } )\n\n console.log('Operation : getRecordsP1A, Query Sent : ', query, ', Server Returned :', returnThis);\n }\n else if( uniqueBlockLots.length ){ // Get Coords\n uniqueBlockLots.map( (blocklot,i) => {\n if(i>=1){ fieldsVals += '+' }\n fieldsVals += blocklot\n } )\n query = this.root+'&table=basic_prop_info&fields=block_lot&fieldsVals=InTheBody&purpose=coords';\n coords = await fetchData([query, fieldsVals])\n console.log('Operation : getCoordinates, Query Sent : ', ', Server Returned :', coords);\n\n // Stuff the coords you just got into each record. Start by maping through your records.\n returnThis = records.map( record => {\n // Find its Coordinates And insert it into the record\n let parcel = coords.filter( uniqueParcel => { return uniqueParcel['block_lot'] == record['block_lot']; } )\n let newRecord = Object.assign(record, parcel[0])\n return newRecord\n } )\n\n\n // Process BNIA Data into an array of Json Features.\n returnThis = returnThis.map( record => {\n var outGeoJson = {}\n outGeoJson['properties'] = record;\n outGeoJson['type']= \"Feature\";\n outGeoJson['geometry']= {\"type\": \"Point\", \"coordinates\": [record['xcord'], record['ycord']]}\n return outGeoJson\n } );\n\n //let notAllData = returnThis.filter( newrecord => { return !newrecord.xcord || !(newrecord.properties && newrecord.properties.xcord ) } )\n }\n else{ alert('Server Error. Please contact the administrator'); }\n\n // Data will either be returned wrapped in its Feature Object or as Key:Value pairs that will be translated into a Feature Object\n console.log('Operation : getRecordsP2, Query Sent : ', '', ', Server Returned :', returnThis);\n return returnThis;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets all the values of a circuit object, returns array of all values and DELETES exercise key so exercises need to be extracted with extractExercisesFromCircuits before using this function | function getValuesFromCircuit(circuit) {
//circuitsArr.forEach(c => delete c["exercises"]);
let valuesArr = [];
// for (let c in circuitsArr) {
// let tempArr = [];
// Object.entries(circuitsArr[c]).forEach(([key, value]) => {
// tempArr.push(value)
// })
// valuesArr.push(tempArr);
// }
Object.entries(circuit).forEach(([key, value]) => {
valuesArr.push(value)})
return valuesArr;
} | [
"static getCryptoValueArray() {\n var coinArray = [];\n for(var i = 0; i < CryptoExchanger.cryptoExchangerArray.length; i++) {\n coinArray.push({\n name: CryptoExchanger.cryptoExchangerArray[i].getCoinName(),\n population: CryptoExchanger.cryptoExchangerArray[i].getCurrentValue(),\n });\n }\n return coinArray;\n }",
"function circuit (gates) {\n return {\n gates\n }\n}",
"function collectChords(){\n\t\tvar chords = [];\n\t\tfor(i=1;i<numChords+1;i++){\n\t\t\tif($('input[name=\"' + ordinal(i) + 'Chord\"]').val() !== ''){\n\t\t\t\tchords.push($('input[name=\"' + ordinal(i) + 'Chord\"]').val().toLowerCase());\n\t\t\t}\n\t\t}\n\t\treturn chords;\n\t}",
"getExposedJokerArray() {\n const tileArray = [];\n\n for (let i = 0; i < 4; i++) {\n for (const tileset of this.players[i].hand.exposedTileSetArray) {\n\n // Find unique tile in pong/kong/quint (i.e. non-joker)\n let uniqueTile = null;\n for (const tile of tileset.tileArray) {\n if (tile.suit !== SUIT.JOKER) {\n uniqueTile = tile;\n break;\n }\n }\n\n // For each joker in pong/kong/quint, return the unique tile\n if (uniqueTile) {\n for (const tile of tileset.tileArray) {\n if (tile.suit === SUIT.JOKER) {\n tileArray.push(uniqueTile);\n }\n }\n }\n }\n }\n\n return tileArray;\n }",
"function getExercisesByMuscles(exercises) {\n\n // initialMuscleRelatedExercises= {muscle1:[], muscle2:[],muscle3:[],...}\n const initialMuscleRelatedExercises = muscles.reduce((accumulator, muscle) => ({\n ...accumulator,\n [muscle]: [],\n }\n ), {});\n\n\n return Object.entries(\n exercises.reduce((accumulator, currentExercise) => {\n const {muscles} = currentExercise;\n accumulator[muscles] = [...accumulator[muscles], currentExercise];\n\n return accumulator;\n }, initialMuscleRelatedExercises),\n );\n}",
"get allClues() {\n return this.clues.across.concat(this.clues.down).filter(clue => clue);\n }",
"function getLab3JSON(){\n let exp = {};\n exp[EXP_JSON_TITLE] = \"Lab 3\";\n exp[EXP_JSON_CREATOR] = \"Gen Chem\";\n\n let equips = [];\n let scale = 0;\n let cylinder = 1;\n let flask = 2;\n let boat = 3;\n let rod = 4;\n let eyeDropper = 5;\n let refractometer = 6;\n let refractometerLens = 7;\n let water = 0;\n let salt = 1;\n equips.push(makeTestEquipmentJSON(ID_EQUIP_SCALE, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_GRADUATED_50mL, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_FLASK_125mL, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_WEIGH_BOAT, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_STIR_ROD, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_EYE_DROPPER, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_REFRACTOMETER, 1));\n equips.push(makeTestEquipmentJSON(ID_EQUIP_REFRACTOMETER_LENS, 1));\n exp[EXP_JSON_EQUIPMENT] = sortArrayByKey(equips, EXP_JSON_EQUIP_OBJ_ID, false);\n\n let chems = [];\n chems.push(makeTestChemicalJSON(COMPOUND_WATER_ID, 50, 1));\n chems.push(makeTestChemicalJSON(COMPOUND_TABLE_SALT_ID, 1.7, 1));\n exp[EXP_JSON_CHEMICALS] = sortArrayByKey(chems, [EXP_JSON_CHEM_ID, EXP_JSON_CHEM_MASS, EXP_JSON_CHEM_CONCENTRATION], true);\n\n let steps = [];\n var s = 0;\n // Part A\n steps.push(makeTestInstructionJSON(s++, scale, true, flask, true, ID_FUNC_SCALE_TO_TAKE_WEIGHT));\n steps.push(makeTestInstructionJSON(s++, scale, true, flask, true, ID_FUNC_SCALE_REMOVE_OBJECT));\n steps.push(makeTestInstructionJSON(s++, cylinder, true, water, false, ID_FUNC_CONTAINER_ADD_TO));\n steps.push(makeTestInstructionJSON(s++, cylinder, true, flask, true, ID_FUNC_CONTAINER_POUR_INTO));\n steps.push(makeTestInstructionJSON(s++, scale, true, boat, true, ID_FUNC_SCALE_TO_TAKE_WEIGHT));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_ZERO_OUT));\n steps.push(makeTestInstructionJSON(s++, boat, true, salt, false, ID_FUNC_CONTAINER_ADD_TO));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_REMOVE_OBJECT));\n steps.push(makeTestInstructionJSON(s++, boat, true, flask, true, ID_FUNC_CONTAINER_POUR_INTO));\n steps.push(makeTestInstructionJSON(s++, rod, true, flask, true, ID_FUNC_STIR_ROD_STIR));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_CLEAR_ZERO));\n steps.push(makeTestInstructionJSON(s++, scale, true, flask, true, ID_FUNC_SCALE_TO_TAKE_WEIGHT));\n steps.push(makeTestInstructionJSON(s++, scale, true, null, true, ID_FUNC_SCALE_REMOVE_OBJECT));\n\n // Part B\n steps.push(makeTestInstructionJSON(s++, flask, true, eyeDropper, true, ID_FUNC_CONTAINER_POUR_INTO));\n steps.push(makeTestInstructionJSON(s++, eyeDropper, true, refractometerLens, true, ID_FUNC_EYE_DROPPER_DROP));\n steps.push(makeTestInstructionJSON(s++, eyeDropper, true, refractometerLens, true, ID_FUNC_EYE_DROPPER_DROP));\n steps.push(makeTestInstructionJSON(s++, refractometer, true, refractometerLens, true, ID_FUNC_REFRACTOMETER_SET_LENS));\n steps.push(makeTestInstructionJSON(s++, flask, true, null, true, ID_FUNC_CONTAINER_EMPTY_IN_TRASH));\n\n // set the instruction list\n exp[EXP_JSON_INSTRUCTIONS] = sortArrayByKey(steps, EXP_JSON_INS_STEP_NUM, false);\n\n return exp;\n}",
"function populate() {\n technicalElectives = [];\n specialCases = [];\n CheckSocialScience = 0;\n CheckEthics = 0;\n CheckRtc2 = 0;\n CheckRtc3 = 0;\n CheckElsj = 0;\n CheckDiversity = 0;\n CheckCi3 = 0;\n CheckAmth108 = 0;\n CheckMath53 = 0;\n CheckAmth106 = 0;\n CheckChem11 = 0;\n doubledip = 0;\n var t = electives.length;\n for (var j = 0; j < t; j++) {\n document.getElementById(\"electiveRow\").deleteCell(0);\n }\n electives = [];\n\n var arrayLength = courses.length;\n\n for (var i = 0; i < arrayLength; i++) {\n generate(courses[i]);\n }\n handleSpecialCases();\n createCookie(\"cookieCourse\", courses, 365);\n}",
"getValues() {\n return this.getValuesFromElement(this.element);\n }",
"get coefficientList() {\n return this.coefficientLists[this.level];\n }",
"function getAllConditions() {\r\n\r\n logMessage('Fetching all conditions.');\r\n\r\n $.ajax({\r\n type : 'POST',\r\n async : false,\r\n url : '/tagmanager/web/getPage?TagManagementPage.mode=CONTAINER_OVERVIEW&containerOverview.tab=RULES&id=TagManagement&ds=' + CONTAINER_ID + '&hl=en_US&token=' + POST_TOKEN,\r\n dataType : 'json'\r\n })\r\n .done(function(data) {\r\n var resp = data.components[0].conditionTableContainer.row;\r\n CONDITIONS[CONTAINER_ID] = [];\r\n for (var i = 0; i < resp.length; i++) {\r\n CONDITIONS[CONTAINER_ID][resp[i].name] = resp[i].conditionId;\r\n }\r\n\r\n });\r\n\r\n }",
"function parseEquipment(rawEquips){\n // Parse all of the Equipment out of the json\n let equips = [];\n for(var i = 0; i < rawEquips.length; i++){\n // Get the Equipment\n let rawEq = rawEquips[i];\n\n // Get the attributes\n var amount = rawEq[EXP_JSON_EQUIP_AMOUNT];\n var id = rawEq[EXP_JSON_EQUIP_OBJ_ID];\n\n // Create the appropriate Equipment\n for(var j = 0; j < amount; j++){\n equips.push(idToEquipment(id));\n }\n }\n return equips;\n}",
"get operators() {return []}",
"function parseEquationComponents(rawComponents){\n let comps = [];\n for(var i = 0; i < rawComponents.length; i++){\n let c = rawComponents[i];\n comps.push(new EquationComponent(\n c[EQUATION_COMPONENT_PROPERTY_COEFFICIENT],\n new ChemProperties(c[EQUATION_COMPONENT_PROPERTY_ID])\n ));\n }\n return comps;\n}",
"get_all_citations(){\r\n\t\t\tlet citations = this.citations.slice();\r\n\t\t\tshuffle(citations);\r\n\r\n\t\t\treturn citations;\r\n\t\t}",
"function experimentToJSON(exp){\n // Get the basic information\n let expJSON = {};\n expJSON[EXP_JSON_TITLE] = exp.title;\n expJSON[EXP_JSON_CREATOR] = exp.creator;\n\n // Get the Equipment\n let equips = [];\n let equipTypes = {};\n exp.equipment.forEach(function(eqCont){\n let eq = eqCont.equipment;\n let id = eq.getID();\n if(id in equipTypes) equipTypes[id]++;\n else equipTypes[id] = 1;\n });\n for(var key in equipTypes){\n let newEquip = {};\n newEquip[EXP_JSON_EQUIP_OBJ_ID] = parseInt(key);\n newEquip[EXP_JSON_EQUIP_AMOUNT] = equipTypes[key];\n equips.push(newEquip);\n }\n expJSON[EXP_JSON_EQUIPMENT] = equips;\n\n\n // Get the Chemicals\n let chems = [];\n exp.chemicals.forEach(function(chemCont){\n let chem = chemCont.chemical;\n\n let newChem = {};\n newChem[EXP_JSON_CHEM_ID] = chem.getID();\n newChem[EXP_JSON_CHEM_MASS] = chem.mass;\n newChem[EXP_JSON_CHEM_CONCENTRATION] = chem.concentration;\n chems.push(newChem);\n });\n expJSON[EXP_JSON_CHEMICALS] = chems;\n\n\n // Get the Instructions\n let instructions = [];\n exp.instructions.forEach(function(insCont, index){\n let eqs = exp.equipment;\n let chs = exp.chemicals;\n let ins = insCont.instruction;\n\n let act = ins.actor;\n let actEquip = act instanceof EquipmentController2D;\n let actI = (actEquip) ? eqs.indexOf(act) : chs.indexOf(act);\n\n let rec = ins.receiver;\n let recEquip = rec instanceof EquipmentController2D;\n let recI = (recEquip) ? eqs.indexOf(rec) : chs.indexOf(rec);\n\n let action = ins.action;\n\n let newIns = {};\n newIns[EXP_JSON_INS_STEP_NUM] = index;\n newIns[EXP_JSON_INS_ACTOR_INDEX] = actI;\n newIns[EXP_JSON_INS_ACTOR_IS_EQUIP] = actEquip;\n newIns[EXP_JSON_INS_RECEIVER_INDEX] = recI;\n newIns[EXP_JSON_INS_RECEIVER_IS_EQUIP] = recEquip;\n newIns[EXP_JSON_INS_FUNC_ID] = act.funcToId(action);\n instructions.push(newIns);\n });\n expJSON[EXP_JSON_INSTRUCTIONS] = instructions;\n\n return expJSON;\n}",
"function CombineChefHotel() {\n //var compteur = 0;\n var toKeep = new Array();\n\n for (const h of hotelInfo) {\n for (const c of newChefArray) {\n\n if((h.Hotel === c.Hotel) && (c.Keep === 1)) {\n var temp = new Object();\n\n temp[\"Hotel\"]=h.Hotel;\n temp[\"Departement\"]=h.Departement;\n temp[\"Zipcode\"]=c.Zipcode;\n temp[\"NumberOfRooms\"]=h.NumberOfRooms;\n temp[\"Price\"]=h.Price;\n temp[\"Lien\"]=h.Lien;\n temp[\"Chef\"]=c.Chef;\n temp[\"Keep\"]=c.Keep;\n\n toKeep.push(temp);\n //compteur++;\n }\n }\n }\n //console.log(compteur);\n return toKeep;\n}",
"function getAllChords(inputScale){\n\tvar allChords = [];\n\tvar chordSeeds = chordmaker.chords; // TODO -- this.chordmaker?\n\n\t// for each pitch in input scale, get array of possible chords\n\tfor (var i = 0; i < inputScale.length; i++) {\n\t\tvar thisMode = getMode(inputScale, i);\n\t\t\n\t\t// for each type of chord defined above, get chord and push to allChords array\n\t\tfor(type in chordSeeds) {\n\t\t\tif (chordSeeds.hasOwnProperty(type)) {\n\t\t\t\t\n\t\t\t\tvar thisChord = [];\n\t\t \t// for each interval in the given chord type, get the note and push to this chord\n\t\t\t\tfor (var j = 0; j < chordSeeds[type].length; j++) {\n\t\t\t\t\t// TODO -- 0 v 1 indexing jankiness\n\t\t\t\t\tvar noteInt = chordSeeds[type][j] - 1;\n\t\t\t\t\t// console.log(noteInt);\n\n\t\t\t\t\tvar thisNote = thisMode[noteInt];\n\t\t\t\t\tthisChord.push(thisNote);\n\t\t\t\t}\n\t\t\t\tallChords.push(thisChord);\n\t\t }\n\t\t}\n\t}\n\tconsole.log(allChords);\n\treturn allChords;\n}",
"async function getData() {\n \n /*\n const carsDataReq = await fetch('https://storage.googleapis.com/tfjs-tutorials/carsData.json'); \n const carsData = await carsDataReq.json(); \n const cleaned = carsData.map(car => ({\n mpg: car.Miles_per_Gallon,\n horsepower: car.Horsepower,\n }))\n .filter(car => (car.mpg != null && car.horsepower != null));\n */\n return cleaned;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines a moment where the first registered observer is used to asynchronously execute a request, returning a single result If no result is returned (undefined) no further action is taken and the result will be undefined (i.e. additional observers are not used) | function moments_request() {
return async function (observers, ...args) {
if (!isArray(observers) || observers.length < 1) {
return undefined;
}
const handler = observers[0];
return Reflect.apply(handler, this, args);
};
} | [
"_createWatcher() {\n const _watcher = Looper.create({\n immediate: true,\n });\n _watcher.on('tick', () => safeExec(this, 'fetch'));\n\n this.set('_watcher', _watcher);\n }",
"requestAnalysis() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.update(AnalysisEvent.AnalysisRequest);\n });\n }",
"function queueObserver (observer) {\n if (queuedObservers.size === 0) {\n Promise.resolve().then(runObservers);\n }\n queuedObservers.add(observer);\n}",
"function resolved(x){\n\t if(async) context = cat(future.context, cat(asyncContext, context));\n\t settle(action.resolved(x));\n\t }",
"function differentApproach(event) {\n console.log(\"service worker fetching - approach with first checking cache (version is important!!)\")\n\n //check cache and respond form cache\n event.respondWith(\n caches.match(event.request)\n .then(cacheRequest => {\n console.log('response is here');\n return cacheRequest || fetch(event.request);\n })\n )\n}",
"async function networkFirst(req) {\n const cache = await caches.open('news-dynamic');\n\n try {\n const res = await fetch(req);\n cache.put(req, res.clone());\n return res;\n } catch (error) {\n const cachedResponse = await cache.match(req);\n return cachedResponse || await caches.match('./fallback.json')\n }\n}",
"async function getRunningSyncTask() {\n const result = await query(`\n PREFIX ext: <http://mu.semte.ch/vocabularies/ext/>\n PREFIX dct: <http://purl.org/dc/terms/>\n PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n PREFIX adms: <http://www.w3.org/ns/adms#>\n\n SELECT ?s WHERE {\n ?s a ext:SyncTask ;\n dct:creator <http://lblod.data.gift/services/${SERVICE_NAME}> ;\n adms:status <${TASK_ONGOING_STATUS}> .\n } ORDER BY ?created LIMIT 1\n `);\n\n return result.results.bindings.length ? {uri: result.results.bindings[0]['s']} : null;\n}",
"async waitForPingResult(userName) {\n if (!this.promises.has(userName)) {\n this.promises.set(userName, createDeferred())\n }\n\n await this.promises.get(userName)\n }",
"function getCurrentAndPromise(Ctor, options) {\n\tvar current = zoneStorage.getItem(options.storageKeys.currentProperty);\n\tvar promise = zoneStorage.getItem(options.storageKeys.currentPropertyPromise);\n\n\tif (promise == null) {\n\t\tpromise = Ctor[options.fetchMethodName]();\n\t\tzoneStorage.setItem(options.storageKeys.currentPropertyPromise, promise);\n\t\tCtor.dispatch(options.currentPropertyPromiseName, [promise]);\n\n\t\tpromise.then(function (value) {\n\t\t\tzoneStorage.setItem(options.storageKeys.currentProperty, value);\n\t\t\tCtor.dispatch(options.currentPropertyName, [value]);\n\t\t})\n\t\t.catch(function () {\n\t\t\tzoneStorage.setItem(options.storageKeys.currentProperty, null);\n\t\t\tCtor.dispatch(options.currentPropertyName, [null]);\n\t\t});\n\t}\n\n\treturn {\n\t\tcurrent: current,\n\t\tpromise: promise\n\t};\n}",
"async function getNextSyncTask() {\n const result = await query(`\n PREFIX ext: <http://mu.semte.ch/vocabularies/ext/>\n PREFIX dct: <http://purl.org/dc/terms/>\n PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n PREFIX adms: <http://www.w3.org/ns/adms#>\n\n SELECT ?s ?created WHERE {\n ?s a ext:SyncTask ;\n adms:status <${TASK_NOT_STARTED_STATUS}> ;\n dct:creator <http://lblod.data.gift/services/${SERVICE_NAME}> ;\n dct:created ?created .\n } ORDER BY ?created LIMIT 1\n `);\n\n if (result.results.bindings.length) {\n const syncTaskData = result.results.bindings[0];\n\n console.log(\n 'Getting the timestamp of the latest successfully ingested delta file. This will be used as starting point for consumption.');\n let latestDeltaTimestamp = await getLatestDeltaTimestamp();\n\n if (!latestDeltaTimestamp) {\n console.log(`It seems to be the first time we will consume delta's. No delta's have been consumed before.`);\n if (START_FROM_DELTA_TIMESTAMP) {\n console.log(`Service is configured to start consuming delta's since ${START_FROM_DELTA_TIMESTAMP}`);\n latestDeltaTimestamp = new Date(Date.parse(START_FROM_DELTA_TIMESTAMP));\n } else {\n console.log(\n `No configuration as of when delta's should be consumed. Starting consuming from sync task creation time ${syncTaskData['created'].value}.`);\n latestDeltaTimestamp = new Date(Date.parse(syncTaskData['created'].value));\n }\n }\n\n return new SyncTask({\n uri: syncTaskData['s'].value,\n status: TASK_NOT_STARTED_STATUS,\n since: latestDeltaTimestamp,\n created: new Date(Date.parse(syncTaskData['created'].value))\n });\n } else {\n return null;\n }\n}",
"function get_first_result(msg, destiny, sender_function)\n\t{\n\t\t\tvar dest = destiny;\n\t\t\tvar flag=0;\n\t\tconsole.log(dest + ' destino');\n\t\t var options = {\n\t url: 'http://www.metacritic.com/search/movie/' + dest + '/results',\n\t headers: {\n\t 'User-Agent': 'request'\n\t },\n\t enconding: 'ascii'\n\t };\n\t\t\n\t\t request(options, function(error, response, html){\n\t\tif (error)\n\t\tconsole.log(error);\n if(!error){\n var $ = cheerio.load(html);\n\t\t\t\n\t\t\t$('ul.search_results.module').children().filter(function(){\n\t\t\t\t\tif ($(this).hasClass('first_result'))\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log('entre aquí');\n\t\t\t\tvar data = $(this).children().last().children().first();\n\t\t\t\tvar link = data.children().first().children().first().children().first().attr('href');\n\t\t\t\tresult=link;\n\t\t\t\tconsole.log(link + ' titulo');\n\t\t\t\tconsole.log(result + ' resultado');\n\t\t\t\tflag=1;\n\t\t\t\tcallback(msg, result, sender_function);\n\t\t\t\t\t}\t\t\t\t\n })\n\t\t\tif (flag==0)\n\t\t\tsearch_suggestions(msg, destiny, sender_function);\n\t\t\t\n }\n\t\t\t})\n\t}",
"singleFetch(predicates, options){\n return new Promise((resolve) => {\n this.prismic.getResults(predicates, options)\n .then((content) => resolve(content))\n .catch((error) => console.error(error));\n });\n }",
"static Request(url) {\n\t\tvar d = Core.Defer();\n\t\tvar xhttp = new XMLHttpRequest();\n\t\t\n\t\txhttp.onreadystatechange = function() {\n\t\t\tif (this.readyState != 4) return;\n\t\t\n\t\t\t// TODO : Switched to this.response, check if it breaks anything\n\t\t\tif (this.status == 200) d.Resolve(this.response);\n\t\t\t\n\t\t\telse {\n\t\t\t\tvar error = new Error(this.status + \" \" + this.statusText);\n\n\t\t\t\td.Reject(error);\n\t\t\t}\n\t\t};\n\t\t\n\t\txhttp.open(\"GET\", url, true);\n\t\t\n\t\txhttp.send();\n\t\t\n\t\treturn d.promise;\n\t}",
"async _cachingFetch(url) {\n // super-hacky cache clearing without opening devtools like a sucker.\n if (/NUKECACHE/.test(url)) {\n this.cache = null;\n await caches.delete(this.cacheName);\n this.cache = await caches.open(this.cacheName);\n }\n\n let matchResp;\n if (this.cache) {\n matchResp = await this.cache.match(url);\n }\n if (matchResp) {\n const dateHeader = matchResp.headers.get('date');\n if (dateHeader) {\n const ageMillis = Date.now() - new Date(dateHeader);\n if (ageMillis > ONE_HOUR_IN_MILLIS) {\n matchResp = null;\n }\n } else {\n // evict if we also lack a date header...\n matchResp = null;\n }\n\n if (!matchResp) {\n this.cache.delete(url);\n } else {\n return matchResp;\n }\n }\n\n const resp = await fetch(url);\n this.cache.put(url, resp.clone());\n\n return resp;\n }",
"async onBegin() {\n\t}",
"function oneEventQueue() {\n console.log('\\n***Begin single queue, event-based test\\n')\n\n start = new Date()\n lr = new Limireq(1)\n .push({ url: 'http://www.google.com' })\n .push({ url: 'http://www.android.com' }, function(err, res, body) {\n console.log('Status Code:' + res.statusCode)\n console.log('Bypass the data event for Android.com')\n })\n .push({ url: 'http://www.youtube.com' })\n .push({ url: 'http://www.amazon.com' })\n .push({ url: 'http://www.apple.com' })\n .push({ url: 'http://www.bing.com' })\n .on('data', function(err, res, body) {\n console.log('Status Code: ' + res.statusCode)\n console.log('Do some common processing with the response')\n })\n .on('end', function() {\n timeOneEventQueue = new Date()-start\n threeCallbackQueues()\n })\n .start()\n }",
"function once$1() {\n let first = true;\n return async () => {\n if (first) {\n first = false;\n return true;\n }\n return false;\n };\n}",
"function findServer(callback) {\n const urls = [\n 'http://localhost:3000/server1',\n 'http://localhost:3000/server2',\n 'http://localhost:3000/server3',\n 'http://localhost:3000/server4',\n 'http://localhost:3000/server5'\n ];\n Promise.all(urls.map(url =>\n fetch(url)\n .then(checkOnlineStatus)\n .then(parseJSON)\n .catch(error => error)\n ))\n .then(data => {\n var find = _.filter(data, function (o) {\n return o !== null;\n });\n if (_.isEmpty(find)) {\n callback('no servers are online')\n } else {\n return Promise.resolve(find)\n }\n })\n .then((find) => {\n find.sort(function (a, b) {\n return a.priority - b.priority;\n });\n console.log(find)\n return Promise.resolve(find)\n })\n .then((find) => {\n callback(find[0])\n })\n}",
"getReturnForCall() {\n const args = this.lastCallArgs;\n for (const setup of this.methodReturnSetups) {\n const isMatch = this.argumentsMatch(setup.arguments, args);\n if (isMatch === true) {\n const returnValue = setup.returnValues[setup.nextIndex];\n setup.nextIndex++;\n if (setup.nextIndex === setup.returnValues.length) {\n setup.nextIndex--;\n }\n return setup.isAsync ? Promise.resolve(returnValue) : returnValue;\n }\n }\n return undefined;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load Consumer of given user | function loadConsumer(recipientId, user) {
if (user == null)
return;
return function (dispatch) {
return new parse_1.default.Query(ParseModels_1.Consumer).equalTo('user', user).first().then(function (consumer) {
if (consumer) {
dispatch({ type: types.CONSUMER_LOADED, data: { recipientId: recipientId, consumer: consumer } });
}
else {
dispatch({ type: types.CONSUMER_NOT_FOUND, data: { user: user } });
}
}).fail(function (e) {
dispatch({ type: types.CONSUMER_NOT_FOUND, data: { user: user } });
});
};
} | [
"function loadUser() {\n console.log(\"loadUser() started\");\n showMessage(\"Loading the currently logged in user ...\");\n osapi.jive.core.users.get({\n id : '@viewer'\n }).execute(function(response) {\n console.log(\"loadUser() response = \" + JSON.stringify(response));\n user = response.data;\n $(\".user-name\").html(user.name);\n loadUsers();\n });\n}",
"function load(req, res, next, userId) {\n Client.get(userId)\n .then((client) => {\n req.client = client;\n return next();\n })\n .catch(e => next(e));\n}",
"function loadUser() {\r\n makeHTTPRequest(`/usuarios/0`, 'GET', '', cbOk1);\r\n}",
"function loadFromUserType() {\n console.log(\"UserService: Loading additional information for user type: %s\", userType);\n\n factory.isCompany = function () {\n return userType === \"Company\";\n };\n\n factory.isStudent = function () {\n return userType === \"Student\";\n };\n\n factory.isAdmin = function () {\n return userType === \"Admin\";\n };\n\n if (userType === \"Student\") {\n // Then, this user must be in the student list as well\n var studentList = clientContext.get_web().get_lists().getByTitle(\"StudentList\");\n var camlQuery = new SP.CamlQuery();\n var query = \"<View><Query><Where>\" +\n \"<Eq><FieldRef Name='Email' /><Value Type='Text'>\" + factory.user.email + \"</Value></Eq>\" +\n \"</Where></Query></View>\";\n camlQuery.set_viewXml(query);\n var entries = studentList.getItems(camlQuery);\n\n clientContext.load(entries);\n clientContext.executeQueryAsync(function () {\n console.log(\"UserService: Additional user information loaded from student list\");\n var enumerator = entries.getEnumerator();\n if (!enumerator.moveNext()) {\n // not a student\n console.log(\"UserService: User is not a student\");\n factory.isStudent = function () {\n return false;\n };\n\n userType = null;\n } else {\n factory.user.name = enumerator.get_current().get_item(\"FullName\");\n }\n\n factory.userLoaded = true;\n\n }, onError);\n\n } else if (userType === \"Company\") {\n // Then, this user must be in the student list as well\n var companyList = clientContext.get_web().get_lists().getByTitle(\"CompanyList\");\n var camlQuery = new SP.CamlQuery();\n var query = \"<View><Query><Where>\" +\n \"<Eq><FieldRef Name='Email' /><Value Type='Text'>\" + factory.user.email + \"</Value></Eq>\" +\n \"</Where></Query></View>\";\n camlQuery.set_viewXml(query);\n var entries = companyList.getItems(camlQuery);\n\n clientContext.load(entries);\n clientContext.executeQueryAsync(function () {\n console.log(\"UserService: Additional company information loaded from company list\");\n var enumerator = entries.getEnumerator();\n if (!enumerator.moveNext()) {\n // not a company\n console.log(\"UserService: User is not a Company\");\n factory.isCompany = function () {\n return false;\n };\n\n userType = null;\n } else {\n factory.user.company = enumerator.get_current().get_item(\"Company\");\n }\n\n factory.userLoaded = true;\n }, onError);\n } else {\n factory.userLoaded = true;\n }\n }",
"async function load (req, res, next, id) {\n try {\n req.course = await User.get({ '_id': id })\n return next()\n } catch (e) {\n next(e)\n }\n}",
"fetchByUser(userId) {\n\t\t\treturn FruitRating.collection().query(qb => {\n\t\t\t\tqb.where('user_id', userId);\n\t\t\t\tqb.orderBy('created_at', 'desc');\n\t\t\t}).fetch({\n\t\t\t\twithRelated: [\n\t\t\t\t\t'fruit'\n\t\t\t\t]\n\t\t\t});\n\t\t}",
"function load(req, res, next, userId) {\n _models.Professional.get(userId).then(function (professional) {\n req.professional = professional;\n return next();\n }).catch(function (e) {\n return next(e);\n });\n}",
"function linkProviderWithUser() {\n // TODO: implement this: used for registering an already existing user with a provider\n }",
"async loadForUser (context, userId) {\n try {\n const response = await fetch(`https://ap-todo-list.herokuapp.com/getTodoList?uid=${userId}`)\n const data = await response.json()\n context.commit('setLists', data)\n } catch (error) {\n // Set the error and clear the lists.\n console.error(error)\n context.commit('setLists', [])\n }\n }",
"function getClientById(id){\n var count = users.length;\n var client = null;\n for(var i=0;i<count;i++){\n \n if(users[i].userId==id){\n client = users[i];\n break;\n }\n }\n return client;\n}",
"load() {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n if (this.session.isAuthenticated) {\n let user = await this.store.queryRecord('user', { me: true });\n this.set('user', user);\n resolve(user);\n } else {\n reject(new Error('User not authenticated.'));\n }\n });\n }",
"getConsumerName() {\n errors.throwNotImplemented(\"getting consumer name (dequeue options)\");\n }",
"function loadAuthorizer(credentialsFile, cb) {\n if (credentialsFile) {\n fs.readFile(credentialsFile, function (err, data) {\n if (err) {\n logger.error('Mosca credentials file not found')\n cb(err)\n return\n }\n var authorizer = new Authorizer()\n try {\n authorizer.users = JSON.parse(data)\n cb(null, authorizer)\n } catch (err) {\n logger.error('Mosca invalid credentials')\n cb(err)\n }\n })\n } else {\n cb(null, null)\n }\n}",
"async loadUser(username) {\n return this.UserModel.findOne({ username });\n }",
"function loadConsumerAddresses(recipientId, consumer) {\n if (consumer == null)\n return;\n return function (dispatch) {\n return new parse_1.default.Query(ParseModels_1.ConsumerAddress).equalTo('consumer', consumer).find().then(function (addresses) {\n dispatch({ type: types.CONSUMER_ADDRESSES_LOADED, data: { recipientId: recipientId, addresses: addresses } });\n }).fail(function (error) {\n console.log('Error ' + error);\n //TODO dispatch action with error\n });\n };\n}",
"function GetUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n debugger;\n console.log(user);\n });\n}",
"function loadUsers() {\n if( !userList ) {\n userList = new $.bb.lists.Users();\n }\n return userList;\n }",
"function _readAndCreateConsumers(bsBsrURI, bsrURI, productDetails, apicdevportal, apiCli, transferResult) {\r\n\tlogger.entry(\"_readAndCreateConsumers\", bsBsrURI, bsrURI, productDetails, apicdevportal, apiCli, transferResult);\r\n\t\r\n\tvar promise = ttStorage.existsConsumersYaml(bsBsrURI, bsrURI).then(function(exists){\r\n\t\tlogger.entry(\"_readAndCreateConsumers_exists\", exists);\r\n\t\t\r\n\t\tvar ret = null;\r\n\t\tif(exists === true) {\r\n\t\t\ttransferResult.consumersAttempted = true;\r\n\t\t\tret = ttStorage.readConsumersYaml(bsBsrURI, bsrURI).then(function(consumersObject){\r\n\t\t\t\tlogger.entry(\"_readAndCreateConsumers_read\", consumersObject);\r\n\t\t\t\t// create consumers\r\n\t\t\t\tvar createPromise = flowConsumers.createConsumersInCatalogs(bsBsrURI, bsrURI, consumersObject, productDetails, apicdevportal, apiCli); \r\n\t\t\t\tlogger.exit(\"_readAndCreateConsumers_read\", createPromise);\r\n\t\t\t\treturn createPromise;\r\n\t\t\t});\t\t\t\t\r\n\t\t} else {\r\n\t\t\t// do not create consumers because the file does not exist\r\n\t\t\tret = {};\r\n\t\t}\r\n\t\tlogger.exit(\"_readAndCreateConsumers_exists\", ret);\r\n\t\treturn ret;\r\n\t});\t\r\n\r\n\tlogger.exit(\"_readAndCreateConsumers\", promise);\r\n\treturn promise;\r\n}",
"function loadJokes() {\n const user = localStorage.getItem(\"userInfo\")\n const userInfo = JSON.parse(user)\n const userID = userInfo[0]._id\n // console.log(\"also hi\")\n API.getUsersById(userID)\n .then(res => {\n // console.log(res.data)\n setJokes(res.data[0].savedJokes)\n })\n .catch(err => console.log(err));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check to see if 'Lost' is in the phrase (using some). | function lostCarcosa (input) {
return input.some(x => x.includes('Lost'));
} | [
"checkWord(word){\n this.nonTerminalSymbols.forEach(item => {\n if (word.indexOf(item) !== -1) {\n this.wordExist = true;\n }\n });\n }",
"function doesWordExist(wordsArr, word) {\nif(wordsArr.includes(word)){\n return true;\n}else{\n return false;\n}\n}",
"play(word) {\n // TODO: turn the regex check into a method or function?\n let regex = /^[a-zA-Z]+$/;\n\n if (word === undefined || !regex.test(word)) {\n throw new Error('Need to be a valid word entry');\n }\n\n if (! this.hasWon()) {\n if (this.playArray.push(word)) {\n return true;\n }\n } else {\n return false;\n }\n }",
"function didYouSayFortnite(str) {\n return str.includes('fortnite')\n}",
"function isThereT(wordOne, wordTwo) {\n if (wordOne[0].toLowerCase() === 't' || wordTwo[0].toLowerCase() === 't') {\n return true;\n } else {\n return false;\n }\n}",
"knows_spell(spell){\n\t\treturn this.spells.hasOwnProperty(spell.symbol);\n\t}",
"function hasWord(string, word) {\n //console.log(string, word);\n let arr = string.split(' ');\nreturn (arr.includes(word)) ? true : false;\n}",
"function matchedWordsLeft() {\n gameState.wordsLeftToMatch--;\n if (gameState.wordsLeftToMatch === 0) {\n gameWon();\n }\n}",
"function checkBabyBot(words){\n return words.includes(\"@\" + configs.bot.username)\n || words.includes(\"@pete_bot_\")\n || words.includes(\"@pete_bot\")\n || words.includes(\"pete_bot\")\n || words.includes(\"pete_bot_\")\n || words.includes(\"pete_bot__\")\n || words.includes(\"@pete_bot_\")\n || words.includes(\"@Pete_Bot_\")\n || words.includes(\"@Pete_bot_\")\n || words.includes(\"Pete_Bot_\")\n || words.includes(\"Pete_bot_\")\n}",
"function countWordInPhrase(phrase, word){\n brokenPhrase = phrase.split(\" \");\n count = 0;\n for(b in brokenPhrase)\n if(brokenPhrase[b] == word)\n count++;\n \n return count;\n}",
"function spEng(sentence) {\n //write your code here\n var eng = /english/gi;\n if (sentence.match(eng)) {\n return true;\n }\n return false;\n}",
"function well(x){\n let goodArr = x.filter(word => word === 'good')\n if(goodArr.length > 2){\n return 'I smell a series!'\n }else if (goodArr.length > 0){\n return \"Publish!\"\n }else{\n return 'Fail!'\n }\n}",
"isValidWord() {\n if (this.words.includes(this.wordInput)) {\n this.validWord = true;\n this.wordValidate = 'La palabra se encuentra dentro de la gramatica ingresada'\n } else {\n this.validWord = true;\n this.wordValidate = 'La palabra NO se encuentra dentro de la gramatica ingresada'\n }\n }",
"checkForWin(){\n // checking if <li> elements have a class 'hide letter'\n if (document.querySelectorAll(\"#phrase li.show\").length === game.activePhrase.phrase.replace(/\\s/g, \"\").length) {\n return true;\n } \n else {\n return false;\n }\n }",
"function canPlace() {\r\n var pos = getLocation(parameters.openLocations[parameters.choice]);\r\n for (length = 0; length < parameters.word.length; length++) {\r\n if (alphabetSoup[pos.row][pos.col] !== 0 && alphabetSoup[pos.row][pos.col] !== parameters.word[length]) {\r\n parameters.openLocations.splice(parameters.choice, 1);\r\n return false;\r\n }\r\n pos = nextLocation(pos.row, pos.col);\r\n }\r\n return true;\r\n }",
"checkLetter(pressedLetter)\n {\n let clickedLetter = pressedLetter.textContent;\n const letterArray = this.phrase.split(\"\");\n const wordLength = letterArray.length;\n const newArray = letterArray.filter( letter => letter !== clickedLetter );\n if(newArray.length === wordLength)\n {\n return false; //returns false if no letter is filtered. this means the chosen leter is not in array.\n }\n else\n {\n return true; //otherwise, letter is in array and return true\n }\n }",
"hasTeams() {\n let has = false;\n this.entrants.forEach((entrant) => {\n if (entrant.team !== \"\") {\n has = true;\n }\n });\n return has;\n }",
"function longWord (input) {\n return input.some(x => x.length > 10);\n}",
"function isFailingGrade(str) {\n return [\n \"elégtelen\",\n \"fail\",\n \"nem felelt meg\",\n \"unsatisfactory\",\n \"nem jelent meg\",\n \"did not attend\",\n \"nem vizsgázott\",\n \"did not attend\",\n ].some(function (item) {\n return str.toLowerCase().indexOf(item) !== -1;\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts into Search Table Accepts the following api/search?lifetime=(int)&type=(string)&netFood=(int)&posFood=(int)&negFood=(int)&members=(json[]) | function search(err, client, done, req, res) {
if(err) {
return console.error('error fetching client from pool', err);
}
var reqArr = [req.body.lifetime, req.body.type, req.body.netFood, req.body.posFood, req.body.negFood, req.body.members];
var jsonQuery = "";
var i;
jsonQuery += "array[";
for (i=0; i<req.body.members.length; i++) {
jsonQuery += JSON.stringify(req.body.members[i]) + "::json";
if (i < (req.body.members.length-1)) {
jsonQuery += ",";
}
}
jsonQuery += "]";
reqArr[5] = jsonQuery;
client
//INSERT INTO "ACSchema"."Search"( "Lifetime", "Type", "Net_Food", "Pos_Food", "Neg_Food", "Members") VALUES (5, 4, 3, 2, 1, array_to_json('{{1,5},{99,100}}'::int[]));
.query('INSERT INTO "ACSchema"."Search"("Lifetime", "Type", "Net_Food", "Pos_Food", "Neg_Food", "Members") VALUES ($1, $2, $3, $4, $5, $6)',
//.query('INSERT INTO "ACSchema"."Search"("Lifetime", "Type", "Net_Food", "Pos_Food", "Neg_Food", "Members") VALUES (1, 1, 1, 1, 1, array[\'{"key\":"value"}\'::json,\'{"key":"value"}\'::json])',
reqArr,
function(err) {
done();
if(err) {
res.json({reqArr: reqArr[5]});
return console.error('error running query', err);
}
res.send(req.query);
});
} | [
"function pushFood(){\n for(var i = 0; i < data.length; i++){\n nutrifit_db_food.push(data[i]);\n }\n}",
"createOne (json: jsonUpdate, callback: mixed) {\n\t\tlet val = [json.headline, json.category, json.contents, json.picture, json.importance];\n\t\tsuper.query(\n\t\t\t\"insert into NewsArticle (headline,category,contents, picture, importance) values (?,?,?,?,?)\",\n\t\t\tval,\n\t\t\tcallback\n\t\t);\n\t}",
"queryJSON(search) {\n for (let i = 0; i < this.state.wasteJSON.length; i++) {\n if(this.state.wasteJSON[i]['keywords'].includes(search)) {\n this.state.searchJSON.push(this.state.wasteJSON[i]);\n }\n }\n }",
"function createSearchIndex(items){\n const builder = new lunr.Builder();\n let fields = null;\n if (CFG.search_fields){\n fields = CFG.search_fields.slice();\n } else {\n for (const [id, item] of Object.entries(items)) {\n const cur = Object.keys(item);\n if (fields === null){\n fields = cur;\n } else {\n fields = fields.filter(f => cur.includes(f));\n }\n }\n }\n console.log('Got search fields', fields);\n fields.forEach(field => builder.field(field));\n for (const [id, item] of Object.entries(items)) {\n item.id = id;\n builder.add(item);\n }\n return builder.build();\n}",
"function insertAllActivities(){\n var length = activities.length;\n\n if (length > 0) {\n //I go through all activities to get the the ids.\n for (var i = 0; i < activities.length; ++i) {\n getStravaDataActivity(activities[i]);\n }\n } else {\n console.error(\"No data activities\");\n }\n}",
"function add_records(){\n fetch('/add', {\n headers: { 'Content-Type': 'application/json'},\n method: 'POST',\n body: JSON.stringify(transactions)\n })\n}",
"function performSearch(srch, srchType, btnIndex){\n //Make the inputs into the URL and call the API\n //Reset variables\n currentFoodResults = [[],[],[],[],[]];\n currentWineResults = [[],[],[],[],[],[],[]];\n varietalInformation = null;\n foodRunFlag = false;\n wineRunFlag = false;\n numResults = 5;\n maxResults = 0;\n\n if(buttonTrigger === false){//Make API call if new search\n\n if(srchType === \"wine\"){ //If searching for a wine\n foodUrl = makeSearchIntoFoodURL(matchFoodToWine(userSearch, varietals)); //find food that pairs for the search\n wineUrl = makeSearchIntoWineURL(userSearch);\n varietalInformation = varietalInfo[userSearch];\n } else { //Otherwise\n foodUrl = makeSearchIntoFoodURL(userSearch); //assume search was for food\n wineUrl = makeSearchIntoWineURL(matchFoodToWine(userSearch, ingredients)); //Get a wine varietal to search\n }\n\n getFoods(foodUrl, extractFoodResults);\n getWines(wineUrl, extractWineResults);\n\n } else if(buttonTrigger === true) {//Skip the API call and reference the cached result\n extractFoodResults(foodResults[btnIndex][1], btnIndex);\n extractWineResults(wineResults[btnIndex][1], btnIndex);\n }\n }",
"post(tableName, newFood) {\n return fetch(`${remoteURL}/${tableName}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(newFood)\n }).then(data => data.json())\n }",
"function addVisitedRestaurant(name, date, cuisine, city) {\n // add to front of array so keep in date order\n // for (var i = 0; i < visitedRestaurants.length; i++) {\n // console.log(\"Before \" + i + \" \" + JSON.stringify(visitedRestaurants[i]));\n // }\n visitedRestaurants.unshift({\n name: name,\n date: date,\n cuisine: cuisine,\n city: city\n });\n // add to database\n visitedRef.set({ data: JSON.stringify(visitedRestaurants) });\n // for (var i=0; i < visitedRestaurants.length; i++) {\n // console.log(i + \" \" + JSON.stringify(visitedRestaurants[i])) ;\n // }\n // watcher will see this and update table\n}",
"function search()\n{\n //Show 10 hits\n return client.search({\n index: \"suv\",\n type: 'suv',\n body: {\n sort: [{ \"volume\": { \"order\": \"desc\" } }],\n size: 10,\n }\n });\n}",
"function processAddMemberForm(data)\n{\n var member_index = memberIndex(data);\n insertMember(data, member_index);\n}",
"_fetchFromAPI() {\n // Generate new items\n let { indexedDb } = this;\n\n return indexedDb.add('item', [\n this._createItemPayload(),\n this._createItemPayload(),\n this._createItemPayload(),\n ]);\n }",
"function multiSearch ( params ) {\n logger.silly('Multi search on params', params);\n var url = 'http://www.thecocktaildb.com/api/json/v1/1/filter.php?';\n if (params.hasOwnProperty('i')) {\n for (var param in params['i']) {\n url = url + 'i=' + param + '&';\n }\n }\n if (params.hasOwnProperty('c')) {\n if (checkType(params['c'])) {\n url = url + 'c=' + params['c'] + '&';\n } else {\n logger.warn('Multisearch given incorrect type (' + params['c'] + '), skipping in search');\n }\n }\n if (params.hasOwnProperty('a')) {\n if (params['a']) {\n url = url + 'a=' + 'Alcoholic' + '&';\n } else {\n url = url + 'a=' + 'Non_Alcoholic' + '&';\n }\n }\n logger.info('Created search term ' + url + ' from multisearch');\n\n return rp( {\n url: url,\n json: true\n }).then(function (res) {\n return res.drinks;\n }, function (err) {\n return err;\n });\n}",
"function searchBook() {\n var search = {};\n search[\"searchType\"] = $(\"select[name=search-type]\").val();\n search[\"searchValue\"] = $(\"input[name=search-value]\").val();\n console.log(search[\"searchType\"]);\n console.log(search[\"searchValue\"]);\n\n $.ajax({\n type: \"POST\",\n contentType: \"application/json\",\n url: \"/rest/search\",\n data: JSON.stringify(search),\n dataType: 'json',\n timeout: 100000,\n success: function (res) {\n displayBooks(res.result, \"No result can found!\");\n }\n });\n\n }",
"function addFeatureInES(latlng, indicatif, vehicule, type) {\n if (indicatif.length > 0 && vehicule.length > 0) {\n var d = new Date();\n client.index({\n index: 'neogeojson',\n type: type,\n body: {\n \"indicatif\":indicatif,\n \"vehicule\":vehicule,\n \"date\": d,\n \"location\": {\n \"lat\": latlng.lat,\n \"lon\": latlng.lng\n }\n }\n }, function (error, response) {\n if (error) console.error(error);\n myForm.reset();\n });\n }\n}",
"function insertAll(foods) {\n return Food.create(foods)\n}",
"function searchAPI(recipe_search, food_search) {\n $('p.search_error').empty();\n let search_params = 'default';\n if (recipe_search) {\n //use the recipe search\n search_params = recipe_search;\n } else if (food_search) {\n //Or, use the food search\n search_params = food_search;\n }\n var recipeData = $(this).attr(\"data-name\");\n var ourAPIid = \"4dced6d2\";\n var ourAPIkey = \"1a7e0fea32a0ad94892aaeb51b858b48\";\n\n var queryURL = \"https://api.yummly.com/v1/api/recipes\" +\n \"?_app_id=\" + ourAPIid +\n \"&_app_key=\" + ourAPIkey +\n \"&q=\" + search_params;\n\n // Checks if \"use your diets and allergies\" box is checked and creats an updated queryURL\n if ($(\"#search-restrictions\").is(':checked')) {\n queryURL = queryURL + searchCriteria.queryParams;\n }\n\n $.ajax({\n type: 'GET',\n dataType: 'json',\n url: queryURL,\n }).then(function (result) {\n let results_length = result.matches.length; //saves results as a variable\n\n $('div.column_results').append(`Search Results (${results_length})`);\n result.matches.forEach(showFood);\n });\n}",
"function findCampaigns(searchCrit, callback) {\r\n $.ajax({\r\n type: 'POST',\r\n url: '/api/search',\r\n data: JSON.stringify(searchCrit),\r\n success: function(data) {if (callback) {callback(null, data);}},\r\n error:function(jqXHR ) {if (callback) {callback(jqXHR.responseText);}},\r\n contentType: \"application/json\",\r\n dataType: 'json'\r\n });\r\n}",
"function addSong(entry, playlist) {\n entry.playlist = playlist;\n console.log(entry);\n \n request.post({\n url: 'http://songapp.ddns.net:8000/api/songs',\n body: entry,\n json: true\n }, function(error, response, body) {\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a PM to the given username | sendPrivateMessage(username, message) {
return this.sendMessage('/mp ' + username + ' ' + message);
} | [
"function sendPrivateMessage(user, name, text) {\n var target;\n var message = text.split(' ');\n message.splice(0, 2);\n message = message.join(' ');\n\n target = User.getUserByName(name);\n if(target) {\n target.sendPrivateMessage(user, message);\n } else {\n user.notify('Sorry, private message target does not exist.');\n }\n}",
"announceMinigame(player, name, command) {\n const formattedMessage = format(Message.ANNOUNCE_MINIGAME, name, command);\n\n server.playerManager.forEach(onlinePlayer =>\n onlinePlayer.sendMessage(formattedMessage));\n }",
"function welcomeUser(user) {\n user.notify('Welcome ' + user.getName() + '!');\n}",
"function sendToUser(name, packetID, msg){\n var user = getUserByName(name);\n var id = 0;\n if(user != null){\n id = user.id;\n if(id != 0){\n io.to(id).emit(packetID, msg);\n }else{\n console.log(\"Tried to send packet to offline user.\");\n }\n }\n}",
"announceMinigameParticipation(player, name, command) {\n this.manager_.announceMinigameParticipation(player, name, command);\n }",
"function distributeMessage(user, text) {\n var msg = user.getName() + ': ' + text;\n var room = Room.getRoomByName(user.getRoom());\n\n if(room && text.trim().length) {\n room.distributeMessage(user, msg);\n } else if(text.trim().length) {\n user.notify('No one can hear you.');\n }\n}",
"function send_message_player_added(uuid){\r\n let data = {\r\n \"cmd\" : \"player_added\"\r\n }\r\n send_message(uuid, data);\r\n}",
"announceMinigame(player, name, command, price = 0) {\n this.manager_.announceMinigame(player, name, command, price);\n }",
"announceToPlayers(message, ...args) {\n if (args.length)\n message = format(message, ...args);\n\n const formattedMessage = format(Message.ANNOUNCE_ALL, message);\n\n server.playerManager.forEach(player =>\n player.sendMessage(formattedMessage));\n\n this.nuwani_().echo('notice-announce', message);\n }",
"function sendMessageToOpponents(text) {\n\tsendPrivateChat(myOpponent(true), text);\n\tsendPrivateChat(myOpponent(false), text);\n}",
"announceReportToAdministrators(player, reportedPlayer, reason) {\n const formattedMessage = format(\n Message.ANNOUNCE_REPORT, player.name, player.id, reportedPlayer.name, \n reportedPlayer.id, reason);\n\n server.playerManager.forEach(player => {\n if (!player.isAdministrator())\n return;\n\n player.sendMessage(formattedMessage);\n });\n\n this.nuwani_().echo('notice-report', player.name, player.id, reportedPlayer.name,\n reportedPlayer.id, reason);\n }",
"announceToPlayers(message, ...args) {\n this.manager_.announceToPlayers(message, ...args);\n }",
"function SendUserJoined(ws) {\n var returnMessage = {}\n returnMessage[\"type\"] = \"user-joined\";\n returnMessage[\"data\"] = {};\n returnMessage.data[\"user-id\"] = ws.userId;\n returnMessage.data[\"user-name\"] = ws.userName;\n returnMessage.data[\"gamemode\"] = ws.gamemode;\n\n // tell all users in the lobby that a user joined the lobby //\n LobbyUserBroadcast(ws, ws.lobbyId, returnMessage);\n\n // tell server viewers a user joined a lobby //\n ServerViewerBroadcastUserUpdate(ws);\n}",
"function sendTimedMessage(userId, message, seconds) {\r\n setTimeout( function() {sendMessage(userId, message) }, seconds);\r\n}",
"function playerSendPloy(data) {\n\t// console.log('Player ID: ' + data.playerId + ' answered a question with: ' + data.answer);\n\n\t// The player's ploy is attached to the data object. \\\n\t// Emit an event with the ploy so it can be saved by the 'Host'\n\tio.sockets.in(data.gameId).emit('hostSavePloy', data);\n}",
"function send_user_auth_url(member){\n member.send(\"Just one last step to get into the IC DoCSoc server :)\")\n member.send(\"To complete your sign-up and verify your Discord Account, please login using your Imperial login details below:\");\n member.send(\"https://discord.docsoc.co.uk/\"+ member.id);\n member.send(\"This link will only work for your account! There is no point sharing it with other users\");\n log(\"Sent custom URL to user: \" + member.displayName + \" for verification\");\n}",
"function SendUserJoinedServer(ws) {\n var returnMessage = {}\n returnMessage[\"type\"] = \"user-joined-server\";\n returnMessage[\"data\"] = {};\n returnMessage.data[\"user-id\"] = ws.userId;\n returnMessage.data[\"user-name\"] = ws.userName;\n returnMessage.data[\"lobby-id\"] = ws.lobbyId;\n returnMessage.data[\"gamemode\"] = ws.gamemode;\n\n // don't use SendToAllServerViewers because we don't want to send this to the newly joined viewer //\n for (var i=0; i<serverViewers.length; i++) {\n if (serverViewers[i].userId != ws.userId) {\n serverViewers[i].send(JSON.stringify(returnMessage));\n }\n }\n}",
"function sendToPid(targetPid, room, type, message) {\n Utility.log('Sending ' + type + ' to peer ' + targetPid);\n var peer = pidMap[targetPid];\n\n if (type !== ACKNOWLEDGE) check(targetPid);\n\n if (peer !== undefined) {\n peer.sendDirectly(room, type, message);\n } else {\n Utility.log('Not sending to ' + targetPid + ', they are undefined.');\n }\n }",
"function sendServerMsgSpecific(msg, user)\n {\n var targetId = socketIdByName(user);\n if (targetId)\n {\n io.sockets.socket(targetId).emit('serverMsg', msg);\n }\n }",
"broadcastPlayerPrivateInfo() {\n this._players.forEach(p => {\n this.sendPlayerInfo(p);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PUBLIC FUNCTION / Fonction d'initialisation du "content managment" | function initContentmanagment()
{
_carouselResponseId = 0;
_emptyBreadcrumbContent = $(BREADCRUM_ID).html()
} | [
"function InitializeContentArea() {\n\tvar $content = $('.content');\n\tvar height = GetAvailableHeight() - GetVerticalMargin($content);\n\t$content.css('min-height', height);\n}",
"function loadContent() {\n\t\tMassIdea.loadHTML($contentList, URL_LOAD_CONTENT, {\n\t\t\tcategory : _category,\n\t\t\tsection : _section,\n\t\t\tpage : 0\n\t\t});\n\t}",
"function initArticleContent(data) {\n var article_content = document.createElement('p');\n var content = data.fields.body;\n if (content.length > 500) {\n article_content.innerHTML = content.substring(0, 500) + \"...\";\n } else {\n article_content.innerHTML = content;\n }\n article_content.className = \"flavour\";\n return article_content;\n }",
"function SetContent(selectedContentNumber) {\n\n SetPicture(selectedContentNumber);\n SetDescriptionText(selectedContentNumber);\n\n}",
"create(name, content) {\n const container = {};\n const docDef = content ? content : [];\n container[name] = docDef;\n return container;\n }",
"function fillContents(activeContent, subTopic){\n Object.entries(webKnowledge[activeContent][subTopic]).forEach((key, value) => {\n // json \"content\"\n if(key[value] == \"content\"){\n let head = document.createElement(\"h2\");\n let headContent = document.createTextNode(\"Erklärung:\")\n let entry = document.createElement(\"p\");\n let entryContent = document.createTextNode(key[value+1]);\n head.appendChild(headContent)\n entry.appendChild(head);\n entry.appendChild(entryContent);\n contentRoot.appendChild(entry);\n }\n // json \"references\" (is array and needs special treatment)\n else {\n let head = document.createElement(\"small\");\n let headContent = document.createTextNode(\"References: \")\n let entry = document.createElement(\"small\");\n let entryContent = document.createTextNode(key[value]);\n head.appendChild(headContent)\n entry.appendChild(head);\n entry.appendChild(entryContent);\n contentRoot.appendChild(entry);\n }\n\n });\n}",
"_initMarkdownAndPreviewSection() {\n this.$mdEditorContainerEl = this.$containerEl.find('.te-md-container .te-editor');\n this.$previewEl = this.$containerEl.find('.te-md-container .te-preview');\n }",
"function initValues() {\n\tNAME.value = \"\";\n\t\n\t// FROM\n\tACTION.value = \"\";\n\tTARGET.setIndex(0);\n\tMETHOD.setIndex(0);\n\tENCTYPE.setIndex(0);\n\n\tFORMAT.pickValue('');\n\tSTYLE.value = '';\n\tSKIN.pickValue('');\n\tPRESERVEDATA.pickValue('');\n\tSCRIPTSRC.value = '';\n\tARCHIVE.value = ''\n\tHEIGHT.value = '';\n\tWIDTH.value = '';\n}",
"function setupLayout() {\n\t$('body').layout({\n\t\twest__showOverflowOnHover : true,\n\t\tresizable : false,\n\t\tclosable : false\n\t});\n\n\t$('.ui-layout-west a').click(function() {\n\t\tvar id = $(this).attr('id');\n\t\tif (id == 'upload') {\n\t\t $('#uploadForm :input').val('');\n\t\t\t$('#errorBox').html('');\n\t\t\t$('#uploadDialog').dialog('open');\n\t\t} else {\n\t\t\t$('.ui-layout-west a').removeClass('selectedCat');\n\t\t\t$(this).addClass('selectedCat');\n\t\t\tcurrentContent = id;\n\t\t\tgetContent(id);\n\t\t}\n\t\treturn false;\n\t});\n\n // Select default content\n\t$(\".ui-layout-west a[id='\" + currentContent + \"']\").addClass('selectedCat');\n}",
"function addContentElement(content, container, activity) {\n let content_div = $($(\"#template-content\").html());\n \n //Add the correct elements based on the content type\n let item_div = content_div.find(\".content-item\");\n switch(content.type) {\n case \"text\": {\n let textarea = $(document.createElement(\"textarea\"));\n textarea.addClass(\"form-control\");\n textarea.attr(\"rows\", \"4\");\n textarea.appendTo(item_div);\n linkInputToProperty(content, \"text\", textarea);\n } break;\n \n case \"image\": {\n let image_div = $($(\"#template-content-image\").html());\n \n let image = image_div.find(\"img\");\n let input = image_div.find(\"input\");\n let name = image_div.find(\".file-upload-name\");\n \n if(content.url == \"\") {\n image.hide();\n } else {\n image.attr(\"src\", content.url);\n }\n \n input.on(\"change\", () => {\n editorDirty = true;\n name.text(input[0].files[0].name);\n image[0].src = URL.createObjectURL(input[0].files[0]);\n image.show();\n \n uploadFileAndStoreURL(input[0].files[0], content, \"url\");\n });\n \n linkInputToProperty(content, \"description\", image_div.find(\"textarea\"));\n \n image_div.appendTo(item_div);\n \n } break;\n \n case \"video\": {\n let video_div = $($(\"#template-content-video\").html());\n \n let video = video_div.find(\"video\");\n let source = video_div.find(\"source\");\n let input = video_div.find(\"input\");\n let name = video_div.find(\".file-upload-name\");\n \n if(content.url == \"\") {\n video.hide();\n } else {\n video.attr(\"src\", content.url);\n }\n \n input.on(\"change\", () => {\n editorDirty = true;\n name.text(input[0].files[0].name);\n source[0].src = URL.createObjectURL(input[0].files[0]);\n video[0].load();\n video.show();\n \n uploadFileAndStoreURL(input[0].files[0], content, \"url\");\n });\n \n \n linkInputToProperty(content, \"description\", video_div.find(\"textarea\"));\n \n video_div.appendTo(item_div);\n } break;\n }\n \n //Side buttons to delete or move the content\n let del = content_div.find(\".content-del\");\n del.on(\"click\", () => {\n removeFromArray(activity.contents, content);\n content_div.remove();\n editorDirty = true;\n \n updateAllUpDownButtons(container, \".content-up\", \".content-down\");\n });\n \n let i = activity.contents.indexOf(content);\n \n let up = content_div.find(\".content-up\");\n up.prop(\"disabled\", i == 0);\n up.on(\"click\", () => {\n editorDirty = true;\n \n //order the contents in the story object\n let array = activity.contents;\n let index = array.indexOf(content);\n let tmp = array[index];\n array[index] = array[index - 1];\n array[index - 1] = tmp;\n \n //order the widgets in the editor\n content_div.insertBefore(content_div.prev());\n \n updateAllUpDownButtons(container, \".content-up\", \".content-down\");\n });\n \n let down = content_div.find(\".content-down\");\n down.prop(\"disabled\", i == activity.contents.length - 1);\n down.on(\"click\", () => {\n editorDirty = true;\n \n let array = activity.contents;\n let index = array.indexOf(content);\n \n //order the contents in the story object\n let tmp = array[index];\n array[index] = array[index + 1];\n array[index + 1] = tmp;\n \n //order the widgets in the editor\n content_div.insertAfter(content_div.next());\n \n updateAllUpDownButtons(container, \".content-up\", \".content-down\");\n });\n \n content_div.appendTo(container);\n}",
"init() {\n set(this, 'isEditing', false);\n this._prefetchMentions(get(this, 'comment'));\n return this._super(...arguments);\n }",
"function init(){\n buildToolbar();\n initEditor();\n }",
"function setInitialValues(classHierarchy){\n\t\tconsole.log(\"=========== Inside setInitialValues =========\");\n\t\tvar children = classHierarchy[\"children\"];\n\t\tfor(var i in children){\n\t\t\tfirstLevelClassCategory.push(children[i][\"name\"]);\n\t\t\tvar secondLevelChld = children[i][\"children\"];\n\t\t\tfor(var j in secondLevelChld) {\n\t\t\t\tclassesContent[secondLevelChld[j][\"name\"]] = [];\n\t\t\t\tKPIClassesBool[secondLevelChld[j][\"name\"]] = 0;\n\t\t\t\tKPIClassesConfidence[secondLevelChld[j][\"name\"]] = 0;\n\t\t\t}\n\t\t}\t\t\n\t}",
"function createContent() {\n var objData = _buildDataObject();\n\n return CioContentService.createContent(objData,\n function(objErr, objResult, objPendingEvent) {\n\n if (objErr) {\n // do something\n }\n if (objPendingEvent) {\n return $rootScope.pending.set(objPendingEvent.loaded, objPendingEvent.total);\n }\n if (objResult.content && objResult.content._id) {\n return $state.go('contents.basicEdit', {\n id: objResult.content._id.toString(),\n });\n }\n });\n }",
"init(){\n\t\tif( this.packagename ){\n\t\t\tthis.componentname = this.packagename.replace(/[\\/\\.]/g,'_'); // id should not have dot\n\t\t}else{\n\t\t\tthis.componentname = this.constructor.name;\n\t\t}\n\t\tthis.componentId = this.componentname + '_' + this.component_serial;\n\t\tComponentStack.set(this.componentId,this);\n\t\t\n\t\tthis.view.id = this.componentId;\n\t}",
"function editorNewContent(content, container, activity)\n{\n editorDirty = true;\n activity.contents.push(content);\n addContentElement(content, container, activity);\n}",
"function initTinyMCE() {\n\ttinymce.init({\n\t\t\t\t//selector : '#questionContentText',\n\t\t\t\t//selector : \"textarea\",\n\t\t\t\tmode : \"textareas\",\n\t\t\t\theight : 242,\n\t\t\t\t//mode : \"none\",\n\t\t\t\tplugins : [\n\t\t\t\t\t\t'advlist autolink lists link charmap print preview anchor',\n\t\t\t\t\t\t'searchreplace visualblocks code fullscreen',\n\t\t\t\t\t\t'insertdatetime table contextmenu paste code',\n\t\t\t\t\t\t'codesample' ],\n\t\t\t\ttoolbar : 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link | codesample',\n\t\t\t\tcontent_css : [ '../bower_components/prism/prism.css' ],\n\t\t\t\t\n\t\t\t\tinit_instance_callback : function(inst){\n\t\t\t\t\tsetTimeout(function(){ $('#contentTab').click(); }, 100);\n\t\t\t\t\tfetchQuestionList();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\n}",
"function setContentOrTitle(dados)\n{\n var obj = \"\";\n dados['_type'].value = (dados['_type'].value == \"\") ? \"div\" : dados['_type'].value;\n obj += '<' + dados['_type'].value;\n obj += ' data-edit=\"true\" data-id=\"'+dados['_id']+'\"';\n if (dados['_css'].value) {\n obj += ' class=\"' + dados['_css'].value + '\"';\n }\n\n if (dados['_style'].value) {\n obj += ' style=\"' + dados['_style'].value + '\"';\n }\n obj += '>';\n //link somente títulos\n if (typeof dados['_link'] == 'object' && dados['_link'].value) {\n obj += '<a href=\"' + dados['_link'].value + '\"';\n obj += ' title=\"' + dados['_content'].value + '\"'\n if (dados['_link_target'].value) {\n obj += ' target=\"' + dados['_link_target'].value + '\"';\n }\n obj += '>';\n }\n\n obj += dados['_content'].value;\n\n //link somente títulos\n if (typeof dados['_link'] == 'object' && dados['_link'].value) {\n obj += '</a>';\n }\n\n obj += '</' + dados['_type'].value + '>';\n\n return obj;\n}",
"_loadDefaultTextAndVars() {\n\n /**\n * @type {Array}\n */\n let cat;\n\n //go though all categories\n for (let category in this._texts) {\n if (this._texts.hasOwnProperty(category)) {\n cat = [];\n //go though all texts in a categorie\n for (let textKey in this._texts[category]) {\n if (this._texts[category].hasOwnProperty(textKey)) {\n //Copy Text to Default\n this._texts[category][textKey].default = this._texts[category][textKey].text;\n\n //Go through all Vars to load default descriptions\n let length = this._texts[category][textKey].vars.length;\n for (let i = 0; i < length; i++) {\n if (typeof this._texts[category][textKey].vars[i] === \"string\") {\n this._texts[category][textKey].vars[i] = {\n \"tag\": this._texts[category][textKey].vars[i],\n \"desc\": this._defaultDescriptions[this._texts[category][textKey].vars[i]]\n };\n }\n }\n\n cat.push({\n textKey: textKey,\n item: this._texts[category][textKey]\n });\n }\n }\n this._hogan.push({\n catKey: category,\n catName: this._catNames[category],\n texts: cat\n });\n }\n }\n\n // load custom texts after loading defaults and vars\n this._loadCustomTexts();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chapter 101 RopeGroup Heather collars the player as her slave | function C101_KinbakuClub_RopeGroup_PlayerCollared() {
Common_PlayerOwner = CurrentActor;
Common_ActorIsOwner = true;
PlayerLockInventory("Collar");
CurrentTime = CurrentTime + 50000;
} | [
"function C101_KinbakuClub_RopeGroup_WillLucyTie() {\n\tif (ActorGetValue(ActorLove) >= 3 || ActorGetValue(ActorSubmission) >= 2) {\n\t\tOverridenIntroText = GetText(\"LucyNotTieYou\");\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 600;\n\t} else C101_KinbakuClub_RopeGroup_PlayerTied();\n}",
"function C101_KinbakuClub_RopeGroup_PlayerWhimperLucy() {\n\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed <= 0) {\n\t\tPlayerUngag();\n\t\tActorChangeAttitude( 1, -1)\n\t} else {\n\t\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed >= 2 || ActorGetValue(ActorLove) >= 1) {\n\t\t\tOverridenIntroText = GetText(\"AnnoyedNoUngag\");\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 640;\n\t\t} else {\n\t\t\tPlayerUngag();\n\t\t\tOverridenIntroText = GetText(\"AnnoyedUngag\");\n\t\t}\n\t}\n}",
"construct_player() {\n this.player = new Player(this);\n this.player.x = 832;\n this.player.y = 608;\n this.nubs = this.add.group();\n this.left_nub = this.physics.add.sprite(this.player.x - 17, this.player.y).setBodySize(3, 3);\n this.nubs.add(this.left_nub);\n this.right_nub = this.physics.add.sprite(this.player.x + 17, this.player.y).setBodySize(3, 3);\n this.nubs.add(this.right_nub);\n this.up_nub = this.physics.add.sprite(this.player.x, this.player.y - 17).setBodySize(3, 3);\n this.nubs.add(this.up_nub);\n this.down_nub = this.physics.add.sprite(this.player.x, this.player.y + 17).setBodySize(3, 3);\n this.nubs.add(this.down_nub);\n\n }",
"construct_player() {\n this.player = new Player(this);\n this.player.x = 352;\n this.player.y = 256;\n this.nubs = this.add.group();\n this.left_nub = this.physics.add.sprite(this.player.x - 17, this.player.y).setBodySize(3, 3);\n this.nubs.add(this.left_nub);\n this.right_nub = this.physics.add.sprite(this.player.x + 17, this.player.y).setBodySize(3, 3);\n this.nubs.add(this.right_nub);\n this.up_nub = this.physics.add.sprite(this.player.x, this.player.y - 17).setBodySize(3, 3);\n this.nubs.add(this.up_nub);\n this.down_nub = this.physics.add.sprite(this.player.x, this.player.y + 17).setBodySize(3, 3);\n this.nubs.add(this.down_nub);\n\n }",
"setColliders() {\n this.physics.add.collider(this.player, this.platforms);\n this.physics.add.collider(this.stars, this.platforms);\n this.physics.add.collider(this.bombs, this.platforms);\n this.physics.add.collider(this.player, this.bombs, this.endGame, null, this);\n this.physics.add.overlap(this.player, this.stars, this.collectStar, null, this);\n }",
"function C101_KinbakuClub_RopeGroup_LoadJenna() {\n\tActorLoad(\"Jenna\", \"ClubRoom1\");\n\tLeaveIcon = \"\";\n}",
"handleSkierRhinoCollision() {\n this.updateEatAsset();\n }",
"function C101_KinbakuClub_RopeGroup_StruggleForLucy() {\n\tif (!C101_KinbakuClub_RopeGroup_StruggledForLucy) ActorChangeAttitude( 1, -1)\n\tC101_KinbakuClub_RopeGroup_StruggledForLucy = true;\n}",
"collisions() {\r\n this.collisionEcran();\r\n }",
"spawn(mob){\r\n\r\n }",
"function collectMilkBottle() {\n if (collide(player, milkBottle, 60)) {\n player.sprite = player.withMb;\n milkBottle.hide();\n }\n }",
"handleEatingClue(clue) {\n // Calculate distance from this predator to the prey\n let d = dist(this.x, this.y, clue.x, clue.y);\n // Check if the distance is less than their two radii (an overlap)\n if (d < (this.radius + clue.radius) && clue.isAlive === true) {\n timeToGrowPower = 0;\n // Increase predator health and constrain it to its possible range\n this.health += this.healthGainPerEat;\n this.health = constrain(this.health, 0, this.maxHealth);\n //update the clues caught score if its not alive anymore\n this.cluesCaught += 1;\n itemCaughtSound.play(); //plays the catch sound when someone gets caught by spies\n clue.isAlive = false; //the clue is not alive anymore\n }\n }",
"function newPlayer() {\n player.tetromino = tetrominos[\n Math.floor(Math.random() * tetrominos.length)\n ].map((row) => row.slice());\n player.offset.x = player.tetromino.length === 2 ? 4 : 3;\n player.offset.y = 0;\n\n if (doesCollide()) {\n gameOver();\n }\n}",
"setPlayerLobby(player) {\n var game = this;\n //If lobby count is 0, creates a lobby and puts the player in it\n if (game._lobbies.length == 0) {\n var lobby = game.createLobby();\n\n lobby.addPlayer(player);\n } else {\n var playerJoinedFreeLobby = false;\n //Check if there's a lobby with free spaces to user join\n for (var i = 0; i < game._lobbies.length; i++) {\n var lobby = game._lobbies[i];\n if (lobby.canPlayerJoin()) {\n lobby.addPlayer(player);\n playerJoinedFreeLobby = true;\n break;\n }\n }\n\n //If there's no lobbies with free space, creates a new lobby and puts the player in it\n if (playerJoinedFreeLobby == false) {\n var lobby = game.createLobby();\n\n lobby.addPlayer(player);\n }\n }\n }",
"checkCollision(player) {\n // Check if the gear and the player overlap each other\n if (this.rowPos == player.rowPos &&\n this.colPos == player.colPos) {\n // If so, then hide the gear item\n this.hasBeenCollected = true;\n this.rowPos = null;\n this.colPos = null;\n this.x = null;\n this.y = null;\n }\n }",
"manageCollitions () {\n var paramRobot = this.robot.getParameters();\n for (var i = 0; i < this.maxFly; ++i) {\n var paramFly = this.fly[i].getParameters();\n var distance = Math.sqrt(Math.pow((paramFly.x - paramRobot.pos.x),2) + Math.pow((paramFly.y - paramRobot.pos.y),2)\n + Math.pow((paramFly.z - paramRobot.pos.z),2));\n\n if (distance <= (paramRobot.radio + paramFly.radio)) {\n this.fly[i].setCollision();\n this.lastHealth = this.health;\n\n if (!paramFly.behaviour) {\n this.health -= 10;\n if (this.health < 0) this.health = 0;\n } else if (paramFly.behaviour) {\n var scorePlus = Math.floor(Math.random()*(5+1))\n this.health += 5 - scorePlus;\n this.score += scorePlus;\n this.setScore();\n if(this.health > 100) this.health = 100;\n }\n this.manageHUD();\n this.hud.changeSize(this.health);\n this.hudRobot.changeSize(this.health);\n }\n }\n }",
"function createReplica(world, otherUser) {\n\n // Read the custom user data belonging to the user to choose an appropriate colour.\n // This will be used with a material shared by all the replica's parts.\n let rgb = otherUser.user.rgb;\n const replica = {\n material: rgb ? new THREE.MeshLambertMaterial({color: new THREE.Color(rgb)})\n : world.defaultMaterial,\n hands: [undefined, undefined]\n }\n // Build a \"head\" object, starting with a box representing the user's VR goggles.\n replica.head = new THREE.Mesh(world.primitiveGeo.box, replica.material);\n replica.head.scale.set(0.2, 0.1, 0.12);\n\n // Add to the box a sphere to create a sense of a head/face behind the goggles,\n // and help clarify which direction the goggles are pointing.\n const ball = new THREE.Mesh(world.primitiveGeo.sphere, replica.material); \n replica.head.add (ball);\n ball.scale.set(1.2, 3.5, 2);\n ball.position.set(0, -0.52, 0.75);\n ball.castShadow = true;\n world.scene.add(replica.head);\n\n // Create a box to serve as the torso.\n replica.body = new THREE.Mesh(world.primitiveGeo.box, replica.material);\n replica.body.scale.set(0.35, 0.65, 0.12);\n replica.body.castShadow = true;\n world.scene.add(replica.body);\n\n // Create text to show the user's display name.\n replica.nameGeo = new THREE.TextGeometry(otherUser.user.name, {font:font, size: 0.3, height: 0});\n replica.nameGeo.computeBoundingBox();\n const name = new THREE.Mesh(replica.nameGeo, textMaterial);\n name.rotation.set(0, Math.PI, 0);\n // Position the name so it hovers above the body, centered left-to-right.\n name.position.addScaledVector(replica.nameGeo.boundingBox.min, -0.5);\n name.position.addScaledVector(replica.nameGeo.boundingBox.max, -0.5);\n name.position.y += 1.5;\n name.position.x *= -1.0;\n replica.body.add(name);\n\n // Add the replica object to our master list of replicated client avatars.\n replicas[otherUser.id] = replica;\n return replica;\n}",
"function C101_KinbakuClub_RopeGroup_LeftBallGagged() {\n\tC101_KinbakuClub_RopeGroup_PlayerBallGagged()\n\tC101_KinbakuClub_RopeGroup_NoActor()\n}",
"function C101_KinbakuClub_RopeGroup_PlayerSusExpression() {\n\tC101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_LookDownNeutral\";\n\tif (ActorGetValue(ActorSubmission) >= 2) C101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_LookDownDominant\";\n\tif (ActorGetValue(ActorSubmission) <= -2) C101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_LookDownSubmissive\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the given text with the given context. Parsing works via loaded subparsers each responsible for their own mutually exclusive syntax. Parsers come in two flavors: Start parsers use syntax which can only occur at the start of a line, such as section headers and lists. These are expected to consume the entire line and must provide a parse method which returns the parsed element or null if either there is none or what was parsed shouldn't be added to the current section. Rest parsers use syntax which can occur at any point in a wika article. They provide two methods: index, which returns a lowcost speculation of the index of the next parseable element, and parse, which returns the parsed element or null if there is none. Plaintext is implicitly defined by what isn't parsed by the subparsers. | parse(text,context){
const title=context.title||"",s1=new Section(1,[new Text(title)]),
article=new Article(title,[s1]),tl=text.length;
context=context||{};
context.self_close=context.self_close||(()=>false);
this.pos=0;
this.cur=article.subsections[0];
this.path=[];
while(this.pos<tl){
let x;
while(
!(x=this.parse_start(text,context)) ||
this.parse_header(text)
){
this.cur.paragraphs.push(x);
}
x=this.parse_rest(text,context);
if(x){
this.cur.paragraphs.push(new Paragraph(x));
}
}
return article;
} | [
"parse_start(text,context){\n\t\tfor(const parser of this.start_parsers){\n\t\t\tconst res=parser.call(this,text,context);\n\t\t\tif(res){\n\t\t\t\treturn res;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}",
"get_parsers(text,context){\n\t\tconst EOL=/$/gm;\n\t\tEOL.lastIndex=this.pos;\n\t\tEOL.test(text);\n\t\tconst next=[],eol=EOL.lastIndex;\n\t\tfor(const parser of this.rest_parsers){\n\t\t\tconst index=parser.index(text,this);\n\t\t\tif(index<eol){\n\t\t\t\tnext.push({index,parser});\n\t\t\t}\n\t\t}\n\t\t\n\t\tnext.sort((a,b)=>a.index-b.index);\n\t\t\n\t\treturn next;\n\t}",
"function parseText( string, parsedText ) {\n var matches;\n parsedText = parsedText || [];\n\n if ( !string ) {\n return parsedText;\n }\n\n matches = descriptionRegex.exec( string );\n if ( matches ) {\n // Check if the first grouping needs more processing,\n // and if so, only keep the second (markup) and third (plaintext) groupings\n if ( matches[ 1 ].match( descriptionRegex ) ) {\n parsedText.unshift( matches[ 2 ], matches[ 3 ] );\n } else {\n parsedText.unshift( matches[ 1 ], matches[ 2 ], matches[ 3 ] );\n }\n\n return parseText( matches[ 1 ], parsedText );\n } else if ( !parsedText.length ) {\n // No links found\n parsedText.push( string );\n }\n\n return parsedText;\n }",
"function parseText(header, section) {\r\n let textArray = [];\r\n let indexArray = [];\r\n //get indexes of text breaks into sections based on header\r\n for (let i = 0; i < section.text.length; i++) {\r\n if (section.text.substr(i, header.length) == header && section.text.charAt(i + header.length) != \"#\" && section.text.charAt(i - 1) != \"#\" ) {\r\n indexArray.push(i);\r\n }\r\n }\r\n //get name if there is one after the header, break text, push into array\r\n for (let i = 0; i < indexArray.length; i++) {\r\n let pos = indexArray[i] + header.length;\r\n let name = \"\";\r\n for (let j = pos; j < section.text.length; j++) {\r\n if (section.text.charAt(j) == \"\\n\") {\r\n break;\r\n }\r\n name += section.text.charAt(j);\r\n }\r\n let end = 0;\r\n if (i == indexArray.length - 1) {\r\n end = section.text.length;\r\n } else {\r\n end = indexArray[i + 1];\r\n }\r\n textArray.push({\"name\": name, \"text\": section.text.substring(pos, end)});\r\n }\r\n\r\n if (textArray.length > 0) {\r\n for (let i = 0; i < textArray.length; i++) {\r\n section.sections.push({\r\n \"name\": textArray[i].name,\r\n \"id\": section.id + \".\" + i,\r\n \"text\": textArray[i].text,\r\n \"sections\": [],\r\n \"level\": section.level + 1,\r\n \"header\": header + \"#\",\r\n \"data\": {\r\n \"annotations\": [],\r\n /*\r\n {\r\n \"text\"\r\n \"start\"\r\n \"end\"\r\n }\r\n */\r\n \"highlights\": [],\r\n /*\r\n {\r\n \"key\"\r\n \"text\"\r\n \"start\"\r\n \"end\"\r\n }\r\n */\r\n \"topics\": []\r\n /*\r\n {\r\n \"key\"\r\n \"text\"\r\n \"start\"\r\n \"end\"\r\n }\r\n */\r\n }\r\n });\r\n }\r\n //recursively call on each section\r\n for (let i = 0; i < section.sections.length; i++) {\r\n parseText(section.sections[i].header, section.sections[i]);\r\n }\r\n }\r\n\r\n}",
"function InlineParser() {\n this.preEmphasis = \" \\t\\\\('\\\"\";\n this.postEmphasis = \"- \\t.,:!?;'\\\"\\\\)\";\n this.borderForbidden = \" \\t\\r\\n,\\\"'\";\n this.bodyRegexp = \"[\\\\s\\\\S]*?\";\n this.markers = \"*/_=~+\";\n\n this.emphasisPattern = this.buildEmphasisPattern();\n this.linkPattern = /\\[\\[([^\\]]*)\\](?:\\[([^\\]]*)\\])?\\]/g; // \\1 => link, \\2 => text\n\n // this.clockLinePattern =/^\\s*CLOCK:\\s*\\[[-0-9]+\\s+.*\\d:\\d\\d\\]/;\n // NOTE: this is a weak pattern. does not enforce lookahead of opening bracket type!\n this.timestampPattern =/([\\[<])(\\d{4}-\\d{2}-\\d{2})(?:\\s*([A-Za-z]+)\\s*)(\\d{2}:\\d{2})?([\\]>])/g;\n this.macroPattern = /{{{([A-Za-z]\\w*)\\(([^})]*?)\\)}}}/g;\n }",
"function ParserHandle(_config) {\n // One goal is to minimize the use of regular expressions...\n var FLOAT = /^\\s*-?(\\d*\\.?\\d+|\\d+\\.?\\d*)(e[-+]?\\d+)?\\s*$/i;\n\n var self = this;\n var _input; // The input being parsed\n var _parser; // The core parser being used\n var _paused = false; // Whether we are paused or not\n var _delimiterError; // Temporary state between delimiter detection and processing results\n var _fields = []; // Fields are from the header row of the input, if there is one\n var _results = { // The last results returned from the parser\n data: [],\n errors: [],\n meta: {}\n };\n _config = copy(_config);\n\n this.parse = function(input) {\n _delimiterError = false;\n if (!_config.delimiter) {\n var delimGuess = guessDelimiter(input);\n if (delimGuess.successful)\n _config.delimiter = delimGuess.bestDelimiter;\n else {\n _delimiterError = true; // add error after parsing (otherwise it would be overwritten)\n _config.delimiter = Papa.DefaultDelimiter;\n }\n _results.meta.delimiter = _config.delimiter;\n }\n\n if (isFunction(_config.step)) {\n var userStep = _config.step;\n _config.step = function(results) {\n _results = results;\n if (needsHeaderRow())\n processResults();\n else\n userStep(processResults(), self);\n };\n }\n\n if (_config.preview && _config.header)\n _config.preview++; // to compensate for header row\n\n _input = input;\n _parser = new Parser(_config);\n _results = _parser.parse(_input);\n processResults();\n if (isFunction(_config.complete) && !_paused)\n _config.complete(_results);\n return _paused ? { meta: { paused: true } } : _results;\n };\n\n this.pause = function() {\n _paused = true;\n _parser.abort();\n _input = _input.substr(_parser.getCharIndex());\n };\n\n this.resume = function() {\n _paused = false;\n _parser = new Parser(_config);\n _parser.parse(_input);\n if (isFunction(_config.complete) && !_paused)\n _config.complete(_results);\n };\n\n this.abort = function() {\n _parser.abort();\n if (isFunction(_config.complete))\n _config.complete(_results);\n _input = \"\";\n }\n\n function processResults() {\n if (_results && _delimiterError) {\n addError(\"Delimiter\", \"UndetectableDelimiter\", \"Unable to auto-detect delimiting character; defaulted to '\" + Papa.DefaultDelimiter + \"'\");\n _delimiterError = false;\n }\n\n if (needsHeaderRow())\n fillHeaderFields();\n\n return applyHeaderAndDynamicTyping();\n }\n\n function needsHeaderRow() {\n return _config.header && _fields.length == 0;\n }\n\n function fillHeaderFields() {\n if (!_results)\n return;\n for (var i = 0; needsHeaderRow() && i < _results.data.length; i++)\n for (var j = 0; j < _results.data[i].length; j++)\n _fields.push(_results.data[i][j]);\n _results.data.splice(0, 1);\n }\n\n function applyHeaderAndDynamicTyping() {\n if (!_results || (!_config.header && !_config.dynamicTyping))\n return _results;\n\n for (var i = 0; i < _results.data.length; i++) {\n var row = {};\n for (var j = 0; j < _results.data[i].length; j++) {\n if (_config.dynamicTyping) {\n var value = _results.data[i][j];\n if (value == \"true\")\n _results.data[i][j] = true;\n else if (value == \"false\")\n _results.data[i][j] = false;\n else\n _results.data[i][j] = tryParseFloat(value);\n }\n\n if (_config.header) {\n if (j >= _fields.length) {\n if (!row[\"__parsed_extra\"])\n row[\"__parsed_extra\"] = [];\n row[\"__parsed_extra\"].push(_results.data[i][j]);\n } else\n row[_fields[j]] = _results.data[i][j];\n }\n }\n\n if (_config.header) {\n _results.data[i] = row;\n if (j > _fields.length)\n addError(\"FieldMismatch\", \"TooManyFields\", \"Too many fields: expected \" + _fields.length + \" fields but parsed \" + j, i);\n else if (j < _fields.length)\n addError(\"FieldMismatch\", \"TooFewFields\", \"Too few fields: expected \" + _fields.length + \" fields but parsed \" + j, i);\n }\n }\n\n if (_config.header && _results.meta)\n _results.meta.fields = _fields;\n\n return _results;\n }\n\n function guessDelimiter(input) {\n var delimChoices = [\",\", \"\\t\", \"|\", \";\", Papa.RECORD_SEP, Papa.UNIT_SEP];\n var bestDelim, bestDelta, fieldCountPrevRow;\n\n for (var i = 0; i < delimChoices.length; i++) {\n var delim = delimChoices[i];\n var delta = 0,\n avgFieldCount = 0;\n fieldCountPrevRow = undefined;\n\n var preview = new Parser({\n delimiter: delim,\n preview: 10\n }).parse(input);\n\n for (var j = 0; j < preview.data.length; j++) {\n var fieldCount = preview.data[j].length;\n avgFieldCount += fieldCount;\n\n if (typeof fieldCountPrevRow === 'undefined') {\n fieldCountPrevRow = fieldCount;\n continue;\n } else if (fieldCount > 1) {\n delta += Math.abs(fieldCount - fieldCountPrevRow);\n fieldCountPrevRow = fieldCount;\n }\n }\n\n avgFieldCount /= preview.data.length;\n\n if ((typeof bestDelta === 'undefined' || delta < bestDelta) &&\n avgFieldCount > 1.99) {\n bestDelta = delta;\n bestDelim = delim;\n }\n }\n\n _config.delimiter = bestDelim;\n\n return {\n successful: !!bestDelim,\n bestDelimiter: bestDelim\n }\n }\n\n function tryParseFloat(val) {\n var isNumber = FLOAT.test(val);\n return isNumber ? parseFloat(val) : val;\n }\n\n function addError(type, code, msg, row) {\n _results.errors.push({\n type: type,\n code: code,\n message: msg,\n row: row\n });\n }\n }",
"function visit(text, visitor, options) {\n var _scanner = createScanner(text, false);\n function toNoArgVisit(visitFunction) {\n return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };\n }\n var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onError = toOneArgVisit(visitor.onError);\n var disallowComments = options && options.disallowComments;\n function scanNext() {\n while (true) {\n var token = _scanner.scan();\n switch (token) {\n case SyntaxKind.LineCommentTrivia:\n case SyntaxKind.BlockCommentTrivia:\n if (disallowComments) {\n handleError(ParseErrorCode.InvalidSymbol);\n }\n break;\n case SyntaxKind.Unknown:\n handleError(ParseErrorCode.InvalidSymbol);\n break;\n case SyntaxKind.Trivia:\n case SyntaxKind.LineBreakTrivia:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter, skipUntil) {\n if (skipUntilAfter === void 0) { skipUntilAfter = []; }\n if (skipUntil === void 0) { skipUntil = []; }\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n var token = _scanner.getToken();\n while (token !== SyntaxKind.EOF) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n var value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case SyntaxKind.NumericLiteral:\n var value = 0;\n try {\n value = JSON.parse(_scanner.getTokenValue());\n if (typeof value !== 'number') {\n handleError(ParseErrorCode.InvalidNumberFormat);\n value = 0;\n }\n }\n catch (e) {\n handleError(ParseErrorCode.InvalidNumberFormat);\n }\n onLiteralValue(value);\n break;\n case SyntaxKind.NullKeyword:\n onLiteralValue(null);\n break;\n case SyntaxKind.TrueKeyword:\n onLiteralValue(true);\n break;\n case SyntaxKind.FalseKeyword:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== SyntaxKind.StringLiteral) {\n handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === SyntaxKind.ColonToken) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n }\n else {\n handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n var needsComma = false;\n while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) {\n if (_scanner.getToken() === SyntaxKind.CommaToken) {\n if (!needsComma) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n }\n else if (needsComma) {\n handleError(ParseErrorCode.CommaExpected, [], []);\n }\n if (!parseProperty()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) {\n handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n var needsComma = false;\n while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) {\n if (_scanner.getToken() === SyntaxKind.CommaToken) {\n if (!needsComma) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n }\n else if (needsComma) {\n handleError(ParseErrorCode.CommaExpected, [], []);\n }\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) {\n handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case SyntaxKind.OpenBracketToken:\n return parseArray();\n case SyntaxKind.OpenBraceToken:\n return parseObject();\n case SyntaxKind.StringLiteral:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === SyntaxKind.EOF) {\n return true;\n }\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n return false;\n }\n if (_scanner.getToken() !== SyntaxKind.EOF) {\n handleError(ParseErrorCode.EndOfFileExpected, [], []);\n }\n return true;\n }",
"function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error) {\n errors.push({ error: error });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}",
"function parseTree(text, errors, options) {\n if (errors === void 0) { errors = []; }\n var currentParent = { type: 'array', offset: -1, length: -1, children: [] }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n var visitor = {\n onObjectBegin: function (offset) {\n currentParent = onValue({ type: 'object', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: function (name, offset, length) {\n currentParent = onValue({ type: 'property', offset: offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset: offset, length: length, parent: currentParent });\n },\n onObjectEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: function (offset, length) {\n currentParent = onValue({ type: 'array', offset: offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: function (offset, length) {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: function (value, offset, length) {\n onValue({ type: getLiteralNodeType(value), offset: offset, length: length, parent: currentParent, value: value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: function (sep, offset, length) {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.columnOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: function (error, offset, lngth) {\n errors.push({ error: error, offset: offset, length: lngth });\n }\n };\n visit(text, visitor, options);\n var result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n }",
"function parse() {\n var action;\n\n stackTop = 0;\n stateStack[0] = 0;\n stack[0] = null;\n lexicalToken = parserElement(true);\n state = 0;\n errorFlag = 0;\n errorCount = 0;\n\n if (isVerbose()) {\n console.log(\"Starting to parse\");\n parserPrintStack();\n }\n\n while(2 != 1) { // forever with break and return below\n action = parserAction(state, lexicalToken);\n if (action == ACCEPT) {\n if (isVerbose()) {\n console.log(\"Program Accepted\");\n }\n return 1;\n }\n\n if (action > 0) {\n if(parserShift(lexicalToken, action) == 0) {\n return 0;\n }\n lexicalToken = parserElement(false);\n if(errorFlag > 0) {\n errorFlag--; // properly recovering from error\n }\n } else if(action < 0) {\n if (parserReduce(lexicalToken, -action) == 0) {\n if(errorFlag == -1) {\n if(parserRecover() == 0) {\n return 0;\n }\n } else {\n return 0;\n }\n }\n } else if(action == 0) {\n if (parserRecover() == 0) {\n return 0;\n }\n }\n }\n }",
"parseTerm() {\n const startPos = this.tok.pos;\n // Parse groups and elements\n let items = [];\n let electron = false;\n let next;\n while (true) {\n next = this.tok.peek();\n if (next == \"(\")\n items.push(this.parseGroup());\n else if (next == \"e\") {\n this.tok.consume(next);\n electron = true;\n }\n else if (next !== null && /^[A-Z][a-z]*$/.test(next))\n items.push(this.parseElement());\n else if (next !== null && /^[0-9]+$/.test(next))\n throw new ParseError(\"Invalid term - number not expected\", this.tok.pos);\n else\n break;\n }\n // Parse optional charge\n let charge = null;\n if (next == \"^\") {\n this.tok.consume(next);\n next = this.tok.peek();\n if (next === null)\n throw new ParseError(\"Number or sign expected\", this.tok.pos);\n else {\n charge = this.parseOptionalNumber();\n next = this.tok.peek();\n }\n if (next == \"+\")\n charge = +charge; // No-op\n else if (next == \"-\")\n charge = -charge;\n else\n throw new ParseError(\"Sign expected\", this.tok.pos);\n this.tok.take(); // Consume the sign\n }\n // Check and postprocess term\n if (electron) {\n if (items.length > 0)\n throw new ParseError(\"Invalid term - electron needs to stand alone\", startPos, this.tok.pos);\n if (charge === null) // Allow omitting the charge\n charge = -1;\n if (charge != -1)\n throw new ParseError(\"Invalid term - invalid charge for electron\", startPos, this.tok.pos);\n }\n else {\n if (items.length == 0)\n throw new ParseError(\"Invalid term - empty\", startPos, this.tok.pos);\n if (charge === null)\n charge = 0;\n }\n return new Term(items, charge);\n }",
"function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}",
"function parseCommand(text) {\n var words = text.split(\" \");\n for (var i = 0; i < words.length; i++) {\n if (seeCommandList.indexOf(words[i]) > -1) {\n /*Randomly select messages to speak from the list in config.js file*/\n var mapArr = ['see', 'recognize', 'know'];\n var rand = mapArr[Math.floor(Math.random() * mapArr.length)];\n processCommand('see', rand);\n break;\n } else if (readCommandList.indexOf(words[i]) > -1) {\n processCommand('read', 'read');\n break;\n }\n }\n}",
"function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}",
"function WordParser () {}",
"function parseExamples(helpText) {\n const parseExample = (match) => {\n return {\n usage: match[1],\n description: match[2],\n };\n };\n return parseGroup(helpText, exampleGroupRegex, defaultItemRegex, parseExample);\n}",
"parse(string) {\n this._string = string;\n this._tokenizer.init(string);\n\n // Prime the tokenizer to obtain the first\n // token which is our lookahead. The lookahead is\n // used for predictive parsing.\n this._lookahead = this._tokenizer.getNextToken();\n\n return this.Program();\n }",
"function findSelectionIn(doc, node, pos, index, dir, text) {\n\t if (node.isTextblock) return new TextSelection(doc.resolve(pos));\n\t for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n\t var child = node.child(i);\n\t if (!child.type.isLeaf) {\n\t var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n\t if (inner) return inner;\n\t } else if (!text && child.type.selectable) {\n\t return new NodeSelection(doc.resolve(pos - (dir < 0 ? child.nodeSize : 0)));\n\t }\n\t pos += child.nodeSize * dir;\n\t }\n\t}",
"function process_bracketed_text(words) {\n // If the first word (other than null) is not |, or if any other word is,\n // that's a problem.\n if (words[1] !== '|') {\n throw new Error(\"Sentences should begin with the start character ('|').\");\n }\n if (words.slice(2).indexOf('|') !== -1) {\n throw new Error(\"Sentences should only use '|' at the start.\");\n }\n // We create a sentence from the words.\n var sentence = new Sentence(words);\n // We do some logs for debugging purposes.\n console.log(JSON.stringify(sentence));\n console.log(JSON.stringify(sentence.words.join(' ')));\n // We declare sentence.indices_to_clause_regions as an empty dictionary.\n sentence.indices_to_clause_regions = {};\n // We declare words_and_indices as a dictionary containing the words and indices information.\n // slice is used to get rid of the first (null) entry.\n var words_and_indices = words.map(function (x, y) {return {'word': x, 'index': y}}).slice(1);\n // c is the result of process_bracketed_text_coordination.\n // It will be a list of the main clauses.\n var c = process_bracketed_text_coordination(sentence, words_and_indices);\n // We make all our main clauses main, and add a main clause tag to each of them.\n c.forEach(function (x) {\n x.make_clause(\"main clause\");\n x.add_tag(new SingleRegionTag(\"main clause\"))\n });\n // We return the sentence object.\n return sentence\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get zoneName Validation Response | getZoneNameValidation(zoneName) {
return this.$http
.get(`${this.swsProxypassOrderPath}/new`, {
params: {
zoneName,
},
})
.then(response => response.data)
.catch(err => this.$q.reject(err));
} | [
"function getZone(axios$$1, zoneToken) {\n return restAuthGet(axios$$1, '/zones/' + zoneToken);\n }",
"get zoneType() {\n return this.getStringAttribute('zone_type');\n }",
"get parentZoneName() {\n return this.getStringAttribute('parent_zone_name');\n }",
"orderZoneName(zoneName, minimized) {\n return this.$http\n .post(`${this.swsProxypassOrderPath}/new`, {\n zoneName,\n minimized,\n })\n .then(response => response.data)\n .catch(err => this.$q.reject(err.data));\n }",
"function zoneinfo(loc){\r\n switch (map[loc].environ){\r\n case 0:\r\n return \"An empty snow covered field. Maybe there's something below all that snow, but it's probably just more snow...\";\r\n break;\r\n case 1:\r\n return \"Dirt extends in every direction with just patches of snow remaining. It looks as though someone has been clearing away as much of the snow as they can. You wonder what they may have been looking for...\";\r\n break;\r\n case 2:\r\n return \"Small spiky bushes stick out from the snow around making it difficult to walk through this zone. You could probably find something to burn here though.\";\r\n break;\r\n case 3:\r\n return \"Tall trees surround you, making it difficult to find your way. If you could chop them down you could probably make a pretty big fire. At least global warming isn't a concern any more\";\r\n break;\r\n default:\r\n return \"ERROR\";\r\n break;\r\n }\r\n}",
"getCondition() { return 'Bad Request' }",
"function nameValidation() {\n // Name validation\n const nameValue = name.value;\n const nameValidator = /[a-zA-z]+/.test(nameValue);\n\n return nameValidator;\n}",
"function zoneIdToName(zoneId) {\n var tmp = \"\";\n var idx;\n for (idx = 0; idx<zoneId.length; idx++) {\n var chr = zoneId[idx];\n if (chr === '=') {\n chr = zoneId[idx+1] + zoneId[idx+2];\n chr = String.fromCharCode(parseInt(chr, 16));\n idx += 2;\n }\n tmp += chr;\n }\n if (tmp.length > 1 && tmp[tmp.length-1] === '.') {\n tmp = tmp.substr(0, tmp.length-1);\n }\n return tmp;\n}",
"function getLocationName() {}",
"get endTimeZoneName()\n\t{\n\t\treturn this._endTimeZoneName;\n\t}",
"function callbackBaseName ( response )\n {\n\tif ( response.warnings )\n\t{\n\t var err_msg = response.warnings.join(\"</li><li>\") || \"There is a problem with the API\";\n\t setErrorMessage(\"pe_base_name\", err_msg);\n\t param_errors.base_name = 1;\n\t}\n\t\n\telse if ( response.errors )\n\t{\n\t var err_msg = response.errors.join(\"</li><li>\") || \"There is a problem with the API\";\n\t setErrorMessage(\"pe_base_name\", err_msg);\n\t param_errors.base_name = 1;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_base_name\", \"\");\n\t param_errors.base_name = 0;\n\t}\n\t\n\tupdateFormState();\n }",
"function tenantName(decodedToken) {\n var extAttr = jwt_1.readPropertyWithWarn(decodedToken, 'ext_attr');\n if (extAttr) {\n return jwt_1.readPropertyWithWarn(extAttr, 'zdn');\n }\n return undefined;\n}",
"function getLocation(name){\n var location = _.detect(locations, function(location){\n return name.match(location.re);\n });\n return location ? location.address : '';\n }",
"function collectZoneNames(tags) {\n var zones = {};\n var tagsLength = tags.length;\n\n for (var i = 1; i < tagsLength; i++) {\n zones[tags[i].zone] = tags[i].zone;\n }\n\n zoneNames = Object.keys(zones);\n zoneNames.sort();\n}",
"function validateSpeechFailACNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Audio coding not specified\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function getCountryName(place) {\n for (var i = 0; i < place.address_components.length; i++) {\n var addressType = place.address_components[i].types[0];\n if (addressType == 'country') {\n country = place.address_components[i]['long_name'];\n }\n }\n // console.log(\"Current country\" + country);\n}",
"function validateSpeechFailUPResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0002\", \"messageId\");\n equal(se[\"text\"], \"Undefined Parameter\", \"text\");\n equal(se[\"variables\"], \"%1\", \"variables\");\n }\n }\n}",
"getPlayersInZone(zone) {\n if(!DeathMatchLocation.hasLocation(zone))\n throw new Error('Unknown zone: ' + zone);\n\n return [...this.playersInDeathMatch_]\n .filter(item => item[1] === zone)\n .length;\n }",
"function constructResponse(msg) {\n\n //Example of replacing more variables\n\n\n return msg.replace(\"|VAR.FIRSTNAME|\", $scope.ngFname);\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name: storeYArray() (Store Year Array) variables: a (array), startYear, endYear Purpose: This function takes in an empty array, the start year, and the end year. Then the array is filled with each year. | function storeYArray(a, startYear, endYear) {
var i = 0, year = startYear;
//while(year <= endYear) {
while(year < endYear) {
a[i] = year;
year++
i++;
}
return a;
} | [
"function createYearsArray(size,year) {\n\t// Validate parameter value\n\tif (size+\"\" == \"undefined\" || size == null) \n\t\treturn null;\t\n\tthis.length = size;\n\tfor (var i = 0; i < size; i++) {\n\t\tthis[i] = year++; \n\t}\n\treturn this;\n}",
"function generateEndYears(selectedDatabaseMask) {\n var stringYear = $(\"input[name='stringYear']\");\n if (typeof stringYear == 'undefined') {\n console.warn(\"stringYear value could not be set!\");\n return;\n }\n\n var sy = calStartYear(selectedDatabaseMask, stringYear.val());\n var ey = calEndYear(selectedDatabaseMask);\n\n var years = new Array();\n var idx = 0;\n for (var j = ey; j >= sy; j--) {\n if (j == ey) years[idx++] = {\"label\": j, \"value\": j, \"selected\": true};\n else years[idx++] = {\"label\": j, \"value\": j};\n }\n return years\n\n }",
"iYearToJYear(iYear) {\n // console.log('** iYearToJYear ' + iYear + ' **');\n const jYears1 = []; // fill with tuple(s) of (startYear, eraCode) for matching era(s), then sort it\n const jYears2 = []; // fill this with tuple(s) of (eName, jName, eraYear)\n if ((iYear<this.minYear) || (iYear>this.maxYear+1)) {return jYears2;} // return blank if out of range\n for (const [eraCode, oneEra] of Object.entries(this.yDict)) {\n // console.log( 'iYear for ' + oneEra.getEraCode());\n if (oneEra.isIYearInEra(iYear)) {\n jYears1.push([oneEra.getStartYear(), eraCode]);\n }\n }\n jYears1.sort(function(a, b){return a[0]-b[0];}); // sort in order by start year\n for (const [startYear, eraCode] of jYears1) {\n jYears2.push([this.yDict[eraCode].getEName(), this.yDict[eraCode].getJName(),\n this.yDict[eraCode].iYearToEraYear(iYear)]);\n }\n // console.log(jYears2);\n return jYears2;\n }",
"function generateStartYears(selectedDatabaseMask) {\n var stringYear = $(\"input[name='stringYear']\");\n if (typeof stringYear == 'undefined') {\n console.warn(\"stringYear value could not be set!\");\n return;\n }\n\n var sy = calStartYear(selectedDatabaseMask, stringYear.val());\n var ey = calEndYear(selectedDatabaseMask);\n var dy = calDisplayYear(selectedDatabaseMask, stringYear.val());\n\n var years = new Array();\n var idx = 0;\n for (var j = sy; j <= ey; j++) {\n if (j == dy) years[idx++] = {\"label\": j, \"value\": j, \"selected\": true};\n else years[idx++] = {\"label\": j, \"value\": j};\n }\n return years\n }",
"function getYears(cbFinals) {\n const finalYears = [];\n const years = cbFinals(fifaData).map(function(element){\n finalYears.push(element.Year);\n })\n return finalYears;\n}",
"function getYears(getFinals) {\n return getFinals(fifaData).map(function(data){\n return data[\"Year\"];\n });\n\n}",
"function parse_years() {\n var raw_years = year_date_textbox.getValue();\n var years_to_list = raw_years.split(\"-\");\n return years_to_list;\n}",
"function filterByDate(books, yearMin, yearMax) {\r\n let filteredBooks = []; // stores the book objects that are within the filter range. stored in order they came in\r\n for(var i = 0; i < books.length; i++){ // iterates through my array a \r\n //console.log(\"\\nbook \" + i);\r\n let year = searchForDates(books[i]); // year store the date of the book that is returned from the searchForDates func\r\n if (year >= yearMin && year <= yearMax){ // checks if it passes the filter test.\r\n filteredBooks.push(books[i]); // stores data of the book in an array called filteredBooks\r\n }\r\n // need to push books that are within the range to a new array then return that array.\r\n}\r\nreturn filteredBooks; // returns an array of objects that contain book data within the date ranges\r\n}",
"function getData(year){\n var yearData = [];\n for(var i = 0, k = 0; i < data.length; i++){\n if (parseInt(data[i].TIME,10) === year) {\n yearData[k] = data[i];\n k++;\n }\n }\n return yearData;\n }",
"function setYear() {\n\n // GET THE NEW YEAR VALUE\n var year = tDoc.calControl.year.value;\n\n // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR\n if (isFourDigitYear(year)) {\n calDate.setFullYear(year);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n else {\n // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH\n tDoc.calControl.year.focus();\n tDoc.calControl.year.select();\n }\n}",
"listYearly() {\n const tenYearBefore = dateService.getYearsBefore(10);\n return this.trafficRepository.getYearlyData(tenYearBefore)\n .then(data => {\n data = this.mapRepositoryData(data);\n const range = numberService.getSequentialRange(tenYearBefore.getFullYear(), 10);\n const valuesToAdd = range.filter(x => !data.find(item => item.group === x));\n return data.concat(this.mapEmptyEntries(valuesToAdd));\n });\n }",
"function expand_year (y, century_break)\n{\n Result = parseInt (y);\n\n if (Result < 100)\n {\n\tif (! century_break)\n\t century_break = Date_century_break;\n\t\n\tif (Result <= century_break)\n\t Result += 2000;\n\telse\n\t Result += 1900;\n }\n\n return Result;\n}",
"function filterYear(data) {\n let filteredData = data.filter(function(d, i) {\n return data[i].year === \"1980\";\n });\n data = filteredData;\n return data;\n }",
"function setYearList() {\n\tvar res = \"<select id = 'selected_year' onchange = 'setYear();' >\";\n\tfor (i = 1950; i <= 2097; i++) {\n\t\tif (YEAR == i) {\n\t\t\tres += \"<option selected = 'selected' value =\" + i +\">\" + i +\"</option>\";\n\t\t}else {\n\t\t\tres += \"<option value =\" + i +\">\" + i +\"</option>\";\n\t\t}\n\t}\n\tres += \"</select>\";\n\treturn res;\n\n}",
"function loadYearlyCharts () {\n\n\t//TODO: Temporary. Downloads 365 days data when user clicks on year tab\n\tif (!downloadedYearlyData) {\n\t\tmakeHidden($('#dashboard'));\n\t\tmakeVisible($('#pageLoadSpinner'));\n\t\tloadCharts(true, YEARDAYS);\n\t\tdownloadedYearlyData = true;\n\t}\n\n\n\tchartsCurrentLevel = chartsLevel.yearly;\n\tchartsCurrentDays = YEARDAYS;\n\tchartsDateFormat = '%b';\n\n\t// reset the charts weekly and monthly periods\n\tchartsWeeklyPeriod = 0;\n\tchartsMonthlyPeriod = 0;\n\n\t// set the categories and series for all charts\n\tchartsData.currentAxisCategories = chartsData.months;\n\tchartsData.maxt.currentSeries = chartsData.maxt.monthsData;\n\tchartsData.mint.currentSeries = chartsData.mint.monthsData;\n\tchartsData.temperature.currentSeries = chartsData.temperature.monthsData;\n\tchartsData.qpf.currentSeries = chartsData.qpf.monthsData;\n\tchartsData.rain.currentSeries = chartsData.rain.monthsData;\n\tchartsData.et0.currentSeries = chartsData.et0.monthsData;\n\n\tfor (var programIndex = 0; programIndex < chartsData.programs.length; programIndex++) {\n\t\tchartsData.programs[programIndex].currentSeries = chartsData.programs[programIndex].monthsData;\n\t}\n\n\t// render all charts with the currentAxisCategories and currentSeries\n\tgenerateCharts();\n\t//For water gauge show only last year\n setWaterSavedValueForDays(chartsCurrentDays);\n generateWaterSavedGauge();\n}",
"function setNextYear() {\n\n var year = tDoc.calControl.year.value;\n if (isFourDigitYear(year)) {\n year++;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function setPreviousYear() {\n\n var year = tDoc.calControl.year.value;\n\n if (isFourDigitYear(year) && year > 1000) {\n year--;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function dateUsed(monthyear, array) {\n for (k = 0; k < array.length; k++) {\n if (monthyear == array[k]){\n return false;}\n }\n\n return true;\n}",
"function leapYear() {\r\n var y = 2021\r\n var i = 0\r\n while (i < 20) {\r\n if ((y % 4 === 0) && (y % 100 !== 0) || (y % 400 === 0)) {\r\n document.write(y + \"\\n\");\r\n y++\r\n i++\r\n }\r\n else {\r\n y++\r\n }\r\n }\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes dictionary entry and mirrors change to files on disk. Returns true after successful deletion. | function deleteEntry(key){
if(existsInDictionary(key)){
delete contents[key];
var json = JSON.stringify(contents);
fs.writeFile(jsonFilePath, json, 'utf8', function(){});
return true;
}
return false;
} | [
"delete(word) {\n\t\t// Helper function:\n\t\t// Works through the levels of the word/key\n\t\t// Once it reaches the end of the word, it checks if the last node\n\t\t// has any children. If it does, we just mark as no longer an end.\n\t\t// If it doesn't, we continue bubbling up deleting the keys until we find a node\n\t\t// that either has other children or is marked as an end.\n\t\tconst deleteHelper = (word, node, length, level) => {\n\t\t\tlet deletedSelf = false;\n\t\t\tif (!node) {\n\t\t\t\tconsole.log(\"Key doesn't exist\");\n\t\t\t\treturn deletedSelf;\n\t\t\t}\n\n\t\t\t// Base case\n\t\t\tif (length === level) {\n\t\t\t\tif (node.keys.length === 0) {\n\t\t\t\t\tdeletedSelf = true;\n\t\t\t\t} else {\n\t\t\t\t\tnode.setNotEnd();\n\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlet childNode = node.keys.get(word[level]);\n\t\t\t\tlet childDeleted = deleteHelper(word, childNode, length, level + 1);\n\t\t\t\tif (childDeleted) {\n\t\t\t\t\tnode.keys.delete(word[level]);\n\n\t\t\t\t\tif (node.isEnd()) {\n\t\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t\t} else if (node.keys.length) {\n\t\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdeletedSelf = true;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdeletedSelf = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn deletedSelf;\n\t\t};\n\n\t\tdeleteHelper(word, this.root, word.length, 0);\n\t}",
"function idbNoteDelete(whichTar) {\n\tif (!idbSupport) return;\n\tvar os = notepadIdLocal;\n\tvar dbPromise = idb.open(idbDB);\n\treturn dbPromise.then(function(db) {\n\t\tvar tx = db.transaction(os, 'readwrite');\n\t\tvar store = tx.objectStore(os);\n\t\tif (whichTar == \"all\") {\n\t\t\tstore.clear();\n\t\t} else {\n\t\t\tstore.delete(whichTar);\n\t\t}\n\t\tdb.close();\n\t\treturn tx.complete;\n\t}).then(function() {\n\t\tif (whichTar == \"all\") {\n\t\t\tconsole.log('All notes deleted from the \"'+ os +'\" object store.');\n\t\t} else {\n\t\t\tconsole.log('Note '+ whichTar +' deleted from the \"'+ os +'\" object store.');\n\t\t}\n\t\treturn true;\n\t});\n}",
"function del(kind, id) {\n var entity = store[kind];\n if (! entity) {\n return false;\n }\n\n var found = false;\n entity.rows = entity.rows.filter(function(row) {\n if (id === row.id) {\n found = true;\n return false; // return false delete this record\n }\n return true;\n });\n\n if (found) {\n writeData();\n }\n\n return found;\n}",
"delete(leaf) {\n const root = this.root();\n\n if (!root) {\n return false;\n }\n\n if (leaf === root) {\n this._root = null;\n this._numLeafs = 0;\n return true;\n } // Iterate up from the leaf deleteing it from it's parent's branches.\n\n\n let node = leaf.parent;\n let branchKey = leaf.branchKey;\n\n while (node) {\n var _node4;\n\n node.branches.delete(branchKey); // Stop iterating if we hit the root.\n\n if (node === root) {\n if (node.branches.size === 0) {\n this._root = null;\n this._numLeafs = 0;\n } else {\n this._numLeafs--;\n }\n\n return true;\n } // Stop iterating if there are other branches since we don't need to\n // remove any more nodes.\n\n\n if (node.branches.size > 0) {\n break;\n } // Iterate up to our parent\n\n\n branchKey = (_node4 = node) === null || _node4 === void 0 ? void 0 : _node4.branchKey;\n node = node.parent;\n } // Confirm that the leaf we are deleting is actually attached to our tree\n\n\n for (; node !== root; node = node.parent) {\n if (node == null) {\n return false;\n }\n }\n\n this._numLeafs--;\n return true;\n }",
"function deletePath(pathlistKey, pathIdx)\r\n{\r\n if (typeof(Storage) !== \"undefined\")\r\n {\r\n if (confirm(\"Permanently delete this route?\"))\r\n {\r\n // Retrieve stored paths, parse to object.\r\n let retrievedPDOString = localStorage.getItem(pathlistKey);\r\n let retrievedPDO = JSON.parse(retrievedPDOString);\r\n \r\n if (retrievedPDO.paths.length > 1)\r\n {\r\n // More than one path in the path list.\r\n // Remove path at pathIdx, save remaining paths to local storage.\r\n retrievedPDO.paths.splice(pathIdx, 1);\r\n saveObject(retrievedPDO, pathlistKey)\r\n }\r\n else\r\n {\r\n // Only one path in path list. Delete path list.\r\n localStorage.removeItem(pathlistKey)\r\n }\r\n\r\n // Reload page to update path lists.\r\n window.location.reload()\r\n }\r\n }\r\n else\r\n {\r\n alert(\"Local storage is not available. Could not remove route.\");\r\n }\r\n}",
"destroyDuplicateEntries() {\n const seen = new Set()\n for (const entry of this.entries.filter(isValidEntry)) {\n const stringOfEntry = entry.toString()\n if (seen.has(stringOfEntry)) entry.destroy()\n else seen.add(stringOfEntry)\n }\n }",
"delete(path, callback) {\n\t\tif (path.endsWith('/')) {\n\t\t\tlet params = {\n\t\t\t\tBucket: this._bucket,\n\t\t\t\tPrefix: path\n\t\t\t};\n\t\t\tthis._s3.listObjectsV2(params, function (err, data) {\n\t\t\t\tif (data.CommonPrefixes.length == 0 && data.Contents.length == 1) { // 1 is for the path itself\n\t\t\t\t\tlet params = {\n\t\t\t\t\t\tBucket: this._bucket,\n\t\t\t\t\t\tKey: path\n\t\t\t\t\t};\n\t\t\t\t\tthis._s3.deleteObject(params, function (err, data) {\n\t\t\t\t\t\tcallback(true);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcallback(false);\n\t\t\t\t}\n\t\t\t}.bind(this));\n\t\t}\n\t\telse {\n\t\t\tlet params = {\n\t\t\t\tBucket: this._bucket,\n\t\t\t\tKey: path\n\t\t\t};\n\t\t\tthis._s3.deleteObject(params, function (err, data) {\n\t\t\t\tcallback(true);\n\t\t\t});\n\t\t}\n\t}",
"removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }",
"function deleteManifest() {\n if (manifestExists()){\n fs.unlinkSync(testManifestPath);\n }\n}",
"removeStream( key ) {\n if ( !this.keys.has( key ) ) {\n return false\n }\n\n // Any-key helper\n if ( key === '*' ) {\n this.anyKey.destroy()\n }\n\n this.keys.get( key ).destroy()\n\n delete this.keys.get( key )\n this.keys.delete( key )\n\n return true\n }",
"_doDeleteNonPersisted(entity) {\n\t\tthis.entities = _.filter(this.entities, (item) => {\n\t\t\tconst match = item === entity;\n\t\t\tif (match) {\n\t\t\t\tentity.destroy();\n\t\t\t}\n\t\t\treturn !match;\n\t\t});\n\n\t\tif (this.isTree) {\n\t\t\tthis.assembleTreeNodes();\n\t\t}\n\n\t\treturn true;\n\t}",
"deleteMentor (mentorName) {\n let allMentors = this.getMentorList();\n if (this.getMentorByName(mentorName)) {\n allMentors = allMentors.filter(course=> course.name != mentorName);\n const newFileData = JSON.stringify(allMentors, null, 4); // converting object into string with space 4\n fs.writeFileSync(this.mentorsList, newFileData); // writing in the JSON file\n return true;\n } else {\n \n return false;\n }\n }",
"jsondelete(guid) {\n const alljson = this.jsonreadall();\n const result = alljson.filter((el) => el.guid !== guid);\n const resultstring = JSON.stringify(result);\n fs_1.default.writeFileSync(path_1.default.join(__dirname, 'guiddata.json'), resultstring);\n }",
"deleteAddressData(address) {\n addressdb.del(address, function(err) {\n addressdb.get(address, function(err, data) {\n console.log(address + \" has been deleted.\");\n })\n })\n }",
"async _deleteSearch(search_name, kv_data) {\r\n let deletedSearchName = search_name || this.search_name;\r\n let self = this;\r\n\r\n var searchDeleted = await this.saved_searches.del(deletedSearchName, null, function (err) {\r\n if (err) {\r\n return err;\r\n }\r\n else {\r\n self._deleteKVStore(kv_store);\r\n }\r\n });\r\n\r\n // Checks to verifiy promise is finished \r\n if (!!searchDeleted) {\r\n return true;\r\n }\r\n }",
"async delete() {\n await this.pouchdb.destroy();\n await this.database.removeCollectionDoc(this.dataMigrator.name, this.schema);\n }",
"function deleteEntry(ENTRY){\n ENTRY_LIST.splice(ENTRY.id, 1);\n // after we call the deleteEntry funciton we need to update the Total values again\n updateUI();\n }",
"deleteExternalMirror(callback) {\n return this.deleteExternalMirrorRequest().sign().send(callback);\n }",
"deleteFromCache(word, deleteAnagrams=false) {\n if(deleteAnagrams) {\n let anagrams = this.findAnagrams(word);\n for(let anagram of anagrams.anagrams) {\n this._deleteWordFromCache(anagram);\n }\n }\n this._deleteWordFromCache(word);\n return;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an observable where all callbacks are executed inside a given zone | function runInZone(zone) {
return (source) => {
return new rxjs__WEBPACK_IMPORTED_MODULE_2__["Observable"](observer => {
const onNext = (value) => zone.run(() => observer.next(value));
const onError = (e) => zone.run(() => observer.error(e));
const onComplete = () => zone.run(() => observer.complete());
return source.subscribe(onNext, onError, onComplete);
});
};
} | [
"createEventObservable(eventName, layer) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._layers.get(layer).then(m => {\n m.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }",
"createEventObservable(eventName, layer) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._layers.get(layer).then(d => {\n d.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }",
"createEventObservable(eventName, infoWindow) {\n return new rxjs__WEBPACK_IMPORTED_MODULE_2__[\"Observable\"](observer => {\n this._infoWindows.get(infoWindow).then(i => {\n i.addListener(eventName, e => this._zone.run(() => observer.next(e)));\n });\n });\n }",
"_startEventStreams() {\n let commandService = this.getService('core', 'commandService');\n\n // Create a stream for all the Discord events\n Object.values(Discord.Constants.Events).forEach((eventType) => {\n let streamName = eventType + '$';\n this.streams[streamName] =\n Rx.Observable\n .fromEvent(\n this.discord,\n eventType,\n function (...args) {\n if (args.length > 1) {\n return args;\n }\n return args[0];\n },\n );\n this.logger.debug(`Created stream nix.streams.${streamName}`);\n });\n\n // Create Nix specific event streams\n this.streams.command$ =\n this.streams.message$\n .filter((message) => message.channel.type === 'text')\n .filter((message) => commandService.msgIsCommand(message));\n\n // Apply takeUntil and share to all streams\n for (let streamName in this.streams) {\n this.streams[streamName] =\n this.streams[streamName]\n .do((data) => this.logger.silly(`Event ${streamName}: ${data}`))\n .takeUntil(this.shutdown$)\n .share();\n }\n\n let eventStreams = Rx.Observable\n .merge([\n ...Object.values(this.streams),\n this.streams.guildCreate$.flatMap((guild) => this.onNixJoinGuild(guild)),\n this.streams.command$.flatMap((message) => commandService.runCommandForMsg(message)),\n ])\n .ignoreElements();\n\n return Rx.Observable.of('').merge(eventStreams);\n }",
"addObserver(observer){\n \n this.observers.push(observer)\n }",
"function async(mapFunction) {\n return factory(Rx.AsyncSubject, mapFunction);\n}",
"extendRxObservables() {\n return require('nylas-observables');\n }",
"_sub_query(request){\n let sub = new BehaviorSubject(STATUS_CONNECTED);\n this.activeSubscriptions.set(request.request_id, sub);\n\n return sub.switchMap( state => {\n return this.multiplex(\n this.activateRequest(request),\n this.deactivateRequest(request),\n this.filterRequest(request),\n state\n )\n });\n }",
"constructor(filterFunc) {\n this._observers = [];\n this._otherCallbacks = [];\n this._filterFunc = filterFunc;\n this._nextId = 111;\n }",
"recordAxeptioEvents() {\n window._axcb = window._axcb || [];\n window._axcb.push(() => {\n window.__axeptioSDK.on(\n 'cookies:*',\n function (payload, event) {\n makeACall(event, payload, this.analytics);\n },\n // set to true to record the past events too that have been dispatched before the event handler is set\n { replay: true },\n );\n });\n }",
"function runObserver (observer) {\n currentObserver = observer;\n observer();\n}",
"function createZone (zoneid) {\n\t\tvar $tr = $('<tr/>').attr('zoneid',zoneid);\n\t\treturn $tr;\n}",
"function wrap(observable) { return new Wrapper(observable); }",
"subscribe(headers, callback) {\n const destination = headers.destination;\n\n headers.session = this.session;\n\n this.sendCommand('SUBSCRIBE', headers);\n\n this._subscribed_to[destination] = { enabled: true, callback: callback };\n\n this.log.debug('subscribed to: ' + destination + ' with headers ' + util.inspect(headers));\n }",
"constructor(geometry, zoneId, zoneType) {\n this.geometry = geometry;\n this.zoneId = zoneId;\n this.zoneType = zoneType;\n }",
"function getZone(axios$$1, zoneToken) {\n return restAuthGet(axios$$1, '/zones/' + zoneToken);\n }",
"orderZoneName(zoneName, minimized) {\n return this.$http\n .post(`${this.swsProxypassOrderPath}/new`, {\n zoneName,\n minimized,\n })\n .then(response => response.data)\n .catch(err => this.$q.reject(err.data));\n }",
"function runObservers () {\n try {\n queuedObservers.forEach(runObserver);\n } finally {\n currentObserver = undefined;\n queuedObservers.clear();\n }\n}",
"_bindClockEvents() {\n this._clock.on(\"start\", (time, offset) => {\n offset = new _Ticks.TicksClass(this.context, offset).toSeconds();\n this.emit(\"start\", time, offset);\n });\n\n this._clock.on(\"stop\", time => {\n this.emit(\"stop\", time);\n });\n\n this._clock.on(\"pause\", time => {\n this.emit(\"pause\", time);\n });\n }",
"makeObservable(propertyNames) {\n var that = this;\n for (var propertyName of propertyNames) {\n // wrap into anonymous function to get correct closure behavior\n (function(pn) {\n const fieldName = \"_\" + pn;\n that[fieldName] = that[pn]; // ensure initial value is set to created field\n Object.defineProperty(that, pn, {\n enumerable: true,\n configurable: true,\n get() { return that[\"_\" + pn]; },\n set(value) {\n const oldValue = that[fieldName];\n that[fieldName] = value;\n that._firePropertyChanged(pn, oldValue, value);\n }\n });\n const subscribeFunctionName = pn + \"Changed\";\n that[subscribeFunctionName] = (listenerFunction) => that._listen(pn, listenerFunction);\n })(propertyName);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The highFive function prints the numbers from 0 to the number passed in. If the number is 5 it instead prints "High Five!". Nothing is returned by the function. Result: We are not calling this function so there is no result. | function highFive(num){
for(var i=0; i<num; i++){
if(i == 5){
console.log("High Five!");
}
else{
console.log(i);
}
}
} | [
"function multipleOfFive(num){\n return num%5 === 0 \n}",
"function divisionBy5(num) {\n\treturn (num / 5);\n}",
"function five (num) {\n if (num>=5) {\n return \tparseInt(num/5)+five(parseInt(num/5));\n }\n else {\n return 0;\n }\n }",
"function divByFive(num){\n return num/5\n}",
"function displayHigh() {\n changeResultMessage('Too high!');\n}",
"function high(count) {\n //count == 'skor' variable\n if(count > highScore){\n highScore = count;\n hiSkor.innerHTML = highScore;\n }\n}",
"function stringFive(x){\n if(x === \"five\"){\n return 5;\n }\n }",
"function high()\r\n{\r\n for(var i=0;i<highScore.length;i++)\r\n{\r\n var curr = highScore[i];\r\n if(curr.score<point)\r\n {\r\n console.log(chalk.yellowBright('Congratulations! You have Beaten '+ curr.name + \" \" +\"in Avengers Quiz\"));\r\n }\r\n}\r\n}",
"function doFizzBuzz(incomingNumber) {\n// find out if it's a multiple of 5\n\n\tif(incomingNumber % 5 === 0 ) {\n\t\tconsole.log(\"fizz\");\n\t}\n\t// find out if its a multiple of 3\n\telse(incomingNumber % 3 === 0) {\n\t\tconsole.log(\"buzz\");\n\t}\n}",
"function fiveTo(number) {\n var array = [];\n if(number > 5) {\n for(var count = 5; count < number; count++) {\n array.push(count);\n }\n return array;\n } else {\n return array = [5];\n }\n }",
"function logAtMost5(n) {\n for (let i = 0; i <= Math.min(5, n); i ++){\n // O(1)\n console.log(i)\n }\n}",
"function hungry(hunger){\n \nreturn hunger <= 5 ? 'Grab a snack': 'Sit down and eat a meal';\n}",
"function random(high) {\n return Math.floor(Math.random() * (high + 1));\n}",
"function under50(num) {\n return num < 50;\n}",
"function playFives(num)\n{\n for(var i = 1; i <= num; i++)\n {\n var random = rollOne();\n if(random === 5)\n {\n console.log(random + \" That's good luck\");\n }\n else\n {\n console.log(random);\n }\n }\n}",
"function renderHighScores() {\n highScoreEl.style.display = \"none\";\n highScorePage.style.display = \"block\";\n for (var i = 0; i < initials.length; i++) {\n initialsAndHighScore.append(initials[i] + \": \" + highScore[i] + \"\\n\");\n }\n}",
"getDisplayNumber(number) {\n\n let displayNumber = '';\n\n if (number % 3 === 0) { // multiple of 3\n displayNumber += 'Fizz';\n }\n\n if (number % 5 === 0) { // multiple of 5\n displayNumber += 'Buzz';\n }\n\n // If displayNumber has a value, return the string\n if (displayNumber) {\n return displayNumber;\n }\n\n // else, just return the number\n return number;\n\n }",
"function logHighscore() {\r\n\tif( totalElapse > parseInt(getCookie()) || getCookie() == \"\" ) {\r\n\t\tsetCookie( totalElapse );\r\n\t\tuiHScore.innerHTML = (Math.floor(totalElapse / 100) / 10).toString();\r\n\t}else {\r\n\t\tuiHScore.innerHTML = (Math.floor(getCookie() / 100) / 10).toString();\r\n\t}\r\n}",
"function recursiveHighLow(data){if(data===void 0){return void 0}else if(babelHelpers.instanceof(data,Array)){for(var i=0;i<data.length;i++){recursiveHighLow(data[i])}}else{var value=dimension?+data[dimension]:+data;if(findHigh&&value>highLow.high){highLow.high=value}if(findLow&&value<highLow.low){highLow.low=value}}}// Start to find highest and lowest number recursively"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The static method means we do not have to instantiate this class(Make it an object) in order to use the CurrencyWidthIdentifier | static createCurrencyWidthIdentifier(identifier){
switch (identifier) {
case Currency.currencyList.nigeria:
let nigerianCurrency = new Currency(identifier, 1, 0.0021, 0.0028, 'N');
return nigerianCurrency;
break;
case Currency.currencyList.britain:
let britishCurrency = new Currency(identifier, 477.34, 1, 1.32, '£');
return britishCurrency;
break;
default:
let usaCurrency = new Currency(identifier, 360.50, 0.76, 1, '$');
}
} | [
"function CurrencyHandler() {\n\t\tthis.type = 'currency';\n\t}",
"static getCurrencyName(code) {\n let currencyName = this.getPhrase(code, \"CurrencyCode\");\n if (currencyName != \"\" && currencyName.length > 0)\n return currencyName;\n else\n return code;\n }",
"getPageWith() {\n const dimensions = InvoicePage.dimensions[this.props.pageFormat];\n return `${dimensions.page.width}${dimensions.unit}`;\n }",
"fracNum() {\n return styles[fracNum[this.id]];\n }",
"constructor() {\n\t\tsuper('CurrencyInput');\n\t}",
"function getCurrencyWidget(parent) {\n\tvar widget = document.createElement(\"select\");\n\twidget.id = \"currencyWidget\";\n\twidget.name = \"currency\";\n\tvar option = document.createElement(\"option\");\n\toption.value = \"CAD\";\n\toption.id = \"CAD\";\n\toption.selected = \"selected\";\n\toption.innerHTML = \"Canadian Dollar\";\n\twidget.appendChild(option);\n\toption = document.createElement(\"option\");\n\toption.value = \"USD\";\n\toption.id = \"USD\";\n\toption.innerHTML = \"US Dollar\";\n\twidget.appendChild(option);\n\toption = document.createElement(\"option\");\n\toption.value = \"MXN\";\n\toption.id = \"MXN\"\n\toption.innerHTML = \"Mexican Peso\";\n\twidget.appendChild(option);\n\twidget.addEventListener(\"change\", changeSelectedCurrency, false);\n\tif (parent) {\n\t\tparent.appendChild(widget);\n\t} else {\n\t\treturn widget;\n\t}\n}",
"function getCurrency(){\n //selected currencies\n fromCurr = selects[0].selectedOptions[0].textContent;\n toCurr = selects[1].selectedOptions[0].textContent;\n \n //get currency code according to currency name\n if(fromCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == fromCurr);\n base = currencies[index].currency_code;\n }\n\n if(toCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == toCurr);\n rateKey = currencies[index].currency_code;\n }\n}",
"function setCurrencyPrefixNF(cp)\n{\n this.currencyPrefix = cp;\n}",
"function init() {\n utilsService.addDropdownOptions('from-currency', availableCurrencies);\n document.getElementById('amount').value = defaultAmount;\n getRates(selectedBase);\n}",
"getCurrency() {\n const tier = this.getTier();\n return get(tier, 'currency', this.props.data.Collective.currency);\n }",
"function findCurrencyRate (currency, data) {\nconsole.log(currency)\nlet currencyDataList = data.bpi;\nconsole.log(currencyDataList);\nreturn currencyDataList[currency].rate; \n}",
"static getDecimalDigits(currency) {\n if (global.companyData.common.currencies != undefined) {\n let objCurrency = global.companyData.common.currencies.filter(currencyConfig => currencyConfig.code == currency);\n if (objCurrency.length > 0)\n return objCurrency[0].decimaldigits;\n }\n return 2;\n }",
"function normConv(rate, symbol) {\n curPrice = parseFloat(basePrice * rate).toFixed(2);\n curDaily = parseFloat(baseChange * rate).toFixed(2);\n $price.text(symbol + curPrice);\n $daily.text(symbol + curDaily);\n}",
"function getCurrency(amount) {\n\tvar fmtAmount;\n\tvar opts = {MinimumFractionDigits: 2, maximumFractionDigits: 2};\n\tif (selectedCurrency === \"CAD\") {\n\t\tfmtAmount = \"CAD $\" + amount.toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"USD\") {\n\t\tfmtAmount = \"USD $\" + (amount * currencyRates.USD).toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"MXN\") {\n\t\tfmtAmount = \"MXN ₱\" + (amount * currencyRates.MXN).toLocaleString(undefined, opts);\n\t} else {\n\t\tthrow \"Unknown currency code: this shouldn't have happened.\";\n\t}\n\treturn fmtAmount;\n}",
"function getItemBuyLimit(value) {\n switch (value){\n //BLINE - Bandos Line\n case \"bh\": return \"1/4\";\n case \"bcp\": return \"1/4\";\n case \"tass\": return \"1/4\";\n case \"bg\": return \"1/4\";\n case \"bb\": return \"1/4\";\n case \"bws\": return \"1/4\";\n //ALINE - Armadyl Line\n case \"ah\": return \"1/4\";\n case \"acp\": return \"1/4\";\n case \"acs\": return \"1/4\";\n case \"ag\": return \"1/4\";\n case \"ab\": return \"1/4\";\n case \"acb\": return \"1/4\";\n case \"oacb\": return \"1/4\";\n case \"buck\": return \"1/4\";\n //SLINE - Subjugation Line\n case \"sh\": return \"1/4\";\n case \"garb\": return \"1/4\";\n case \"gown\": return \"1/4\";\n case \"sg\": return \"1/4\";\n case \"sb\": return \"1/4\";\n case \"ward\": return \"1/4\";\n //T LINE - Tetsu Line\n case \"tth\": return \"2/4\";\n case \"ttb\": return \"2/4\";\n case \"ttl\": return \"2/4\";\n //\"DL LINE - Death Lotus Line\n case \"blh\": return \"2/4\";\n case \"dlcp\": return \"2/4\";\n case \"dlc\": return \"2/4\";\n // SS LINE - Seasinger's Line\n case \"ssh\": return \"2/4\";\n case \"sst\": return \"2/4\";\n case \"ssb\": return \"2/4\";\n //AMULETS - Amulets Line\n case \"hiss\": return \"1/4\";\n case \"murm\": return \"1/4\";\n case \"whisp\": return \"1/4\";\n //MISC LINE - Miscellaneous Line\n case \"sss\": return \"1/4\";\n case \"rhh\": return \"2/4\";\n case \"rb\": return \"2/4\";\n case \"blood\": return \"2/4\";\n //KITES - Kites Line\n case \"male\": return \"1/4\";\n case \"merc\": return \"1/4\";\n case \"veng\": return \"1/4\";\n default: return \"Unknown\";\n }\n}",
"get actualBorderWidth() {\n return this.i.bu;\n }",
"sup() {\n return styles[sup[this.id]];\n }",
"function currencyFormat(x) {\n return x.toString().replace(/\\B(?<!\\.\\d*)(?=(\\d{3})+(?!\\d))/g, \".\");\n}",
"function findCurrencyInfo (account: EdgeAccount, currencyCode: string): EdgeCurrencyInfo | void {\n for (const pluginName in account.currencyConfig) {\n const { currencyInfo } = account.currencyConfig[pluginName]\n if (currencyInfo.currencyCode.toUpperCase() === currencyCode) {\n return currencyInfo\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HandicapPair le asiga parejas a los jugadores dependiendo de su handicap. | function HandicapPair() {
db.transaction(function(transaction) {
transaction.executeSql('DROP TABLE IF EXISTS equipos');
transaction.executeSql('CREATE TABLE IF NOT EXISTS equipos(EquipoId INTEGER NOT NULL PRIMARY KEY, jugadorId INTEGER NOT NULL, numEquipo INTEGER NOT NULL, numPareja INTEGER NOT NULL)', [], nullHandler, errorHandler);
var nEarly = 'NO';
var count = 0;
var maxCapacity = 0;
var totalPlayers = 0;
transaction.executeSql('SELECT * FROM jugadores', [],
function(transaction, result) {
if (result != null && result.rows != null) {
maxCapacity = (Math.ceil(result.rows.length / 5.0) * 5) / 5;
totalPlayers = result.rows.length;
}
}, nullHandler, errorHandler);
transaction.executeSql('SELECT * FROM jugadores WHERE Early = ? ORDER BY Handicap ASC', [nEarly],
function(transaction, result) {
if (result != null && result.rows != null) {
var numTeamsT = 0;
var numPairT = 1;
var resultArray = [];
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
if (result.rows.length < 4) {
window.console.log('THIS CANNOT BE!');
} else {
resultArray.push(row.UserId);
}
}
window.console.log('Array de Ids ordenado ' + resultArray);
while (resultArray.length > 0) {
if (resultArray.length == 1) {
window.console.log('Solo hay un jugador restante sin pareja');
var player = resultArray.pop();
var pairLast = Math.floor(Math.random() * (numPairT - 2 + 1)) + 1;
//var pairLast = numPairT-1;
window.console.log('Se agrega el ultimo jugador a pareja ' + pairLast);
transaction.executeSql('INSERT INTO equipos (jugadorId, numEquipo, numPareja) VALUES (?, ?, ?)', [player, numTeamsT, pairLast], nullHandler, errorHandler);
window.console.log(resultArray);
count++;
} else {
var player1 = resultArray.shift();
var player2 = resultArray.pop();
window.console.log('Id ' + player1 + ' y id ' + player2 + ' salen del array');
transaction.executeSql('INSERT INTO equipos (jugadorId, numEquipo, numPareja) VALUES (?, ?, ?)', [player1, numTeamsT, numPairT], nullHandler, errorHandler);
transaction.executeSql('INSERT INTO equipos (jugadorId, numEquipo, numPareja) VALUES (?, ?, ?)', [player2, numTeamsT, numPairT], nullHandler, errorHandler);
window.console.log(resultArray);
count += 2;
numPairT++;
}
}
}
}, nullHandler, errorHandler);
var sEarly = 'SOLO';
transaction.executeSql('SELECT * FROM jugadores WHERE Early = ?', [sEarly],
function(transaction, result) {
if (result != null && result.rows != null) {
var numTeamsT = 0;
var numPairT = 0;
window.console.log(result.rows.length);
for (var i = 0; i < result.rows.length; i++) {
transaction.executeSql('INSERT INTO equipos (jugadorId, numEquipo, numPareja) VALUES (?, ?, ?)', [result.rows.item(i).UserId, numTeamsT, numPairT], nullHandler, errorHandler);
}
}
}, nullHandler, errorHandler);
var yEarly = 'YES';
transaction.executeSql('SELECT * FROM jugadores WHERE Early = ?', [yEarly],
function(transaction, result) {
if (result != null && result.rows != null) {
var numTeamsT = 0;
var numPairT = 0;
for (var i = 0; i < result.rows.length; i++) {
transaction.executeSql('INSERT INTO equipos (jugadorId, numEquipo, numPareja) VALUES (?, ?, ?)', [result.rows.item(i).UserId, numTeamsT, numPairT], nullHandler, errorHandler);
}
$('#page9 div[data-role="content"]').find('p:first-child b').html('HANDICAP');
HandicapTeam();
}
}, nullHandler, errorHandler);
}, errorHandler, nullHandler);
} | [
"function initPoses() {\n let num = 0;\n this.joints = {\n // wrist\n Wrist: new _JointObject.JointObject(\"wrist\", num++, this),\n // thumb\n T_Metacarpal: new _JointObject.JointObject(\"thumb-metacarpal\", num++, this),\n T_Proximal: new _JointObject.JointObject(\"thumb-phalanx-proximal\", num++, this),\n T_Distal: new _JointObject.JointObject(\"thumb-phalanx-distal\", num++, this),\n T_Tip: new _JointObject.JointObject(\"thumb-tip\", num++, this),\n // index\n I_Metacarpal: new _JointObject.JointObject(\"index-finger-metacarpal\", num++, this),\n I_Proximal: new _JointObject.JointObject(\"index-finger-phalanx-proximal\", num++, this),\n I_Intermediate: new _JointObject.JointObject(\"index-finger-phalanx-intermediate\", num++, this),\n I_Distal: new _JointObject.JointObject(\"index-finger-phalanx-distal\", num++, this),\n I_Tip: new _JointObject.JointObject(\"index-finger-tip\", num++, this),\n // middle\n M_Metacarpal: new _JointObject.JointObject(\"middle-finger-metacarpal\", num++, this),\n M_Proximal: new _JointObject.JointObject(\"middle-finger-phalanx-proximal\", num++, this),\n M_Intermediate: new _JointObject.JointObject(\"middle-finger-phalanx-intermediate\", num++, this),\n M_Distal: new _JointObject.JointObject(\"middle-finger-phalanx-distal\", num++, this),\n M_Tip: new _JointObject.JointObject(\"middle-finger-tip\", num++, this),\n // ring\n R_Metacarpal: new _JointObject.JointObject(\"ring-finger-metacarpal\", num++, this),\n R_Proximal: new _JointObject.JointObject(\"ring-finger-phalanx-proximal\", num++, this),\n R_Intermediate: new _JointObject.JointObject(\"ring-finger-phalanx-intermediate\", num++, this),\n R_Distal: new _JointObject.JointObject(\"ring-finger-phalanx-distal\", num++, this),\n R_Tip: new _JointObject.JointObject(\"ring-finger-tip\", num++, this),\n // little\n L_Metacarpal: new _JointObject.JointObject(\"pinky-finger-metacarpal\", num++, this),\n L_Proximal: new _JointObject.JointObject(\"pinky-finger-phalanx-proximal\", num++, this),\n L_Intermediate: new _JointObject.JointObject(\"pinky-finger-phalanx-intermediate\", num++, this),\n L_Distal: new _JointObject.JointObject(\"pinky-finger-phalanx-distal\", num++, this),\n L_Tip: new _JointObject.JointObject(\"pinky-finger-tip\", num++, this)\n };\n }",
"constructor(pairs) {\n super(pairs, \"Plugboard\");\n }",
"SolveBend_PBD_Triangle() {\n const stiffness = this.m_tuning.bendStiffness;\n for (let i = 0; i < this.m_bendCount; ++i) {\n const c = this.m_bendConstraints[i];\n const b0 = this.m_ps[c.i1].Clone();\n const v = this.m_ps[c.i2].Clone();\n const b1 = this.m_ps[c.i3].Clone();\n const wb0 = c.invMass1;\n const wv = c.invMass2;\n const wb1 = c.invMass3;\n const W = wb0 + wb1 + 2.0 * wv;\n const invW = stiffness / W;\n const d = new b2_math_js_1.b2Vec2();\n d.x = v.x - (1.0 / 3.0) * (b0.x + v.x + b1.x);\n d.y = v.y - (1.0 / 3.0) * (b0.y + v.y + b1.y);\n const db0 = new b2_math_js_1.b2Vec2();\n db0.x = 2.0 * wb0 * invW * d.x;\n db0.y = 2.0 * wb0 * invW * d.y;\n const dv = new b2_math_js_1.b2Vec2();\n dv.x = -4.0 * wv * invW * d.x;\n dv.y = -4.0 * wv * invW * d.y;\n const db1 = new b2_math_js_1.b2Vec2();\n db1.x = 2.0 * wb1 * invW * d.x;\n db1.y = 2.0 * wb1 * invW * d.y;\n b0.SelfAdd(db0);\n v.SelfAdd(dv);\n b1.SelfAdd(db1);\n this.m_ps[c.i1].Copy(b0);\n this.m_ps[c.i2].Copy(v);\n this.m_ps[c.i3].Copy(b1);\n }\n }",
"function car(pair){\n return pair[0];\n}",
"function buy(maisons) {\n for (let i in maisons) {\n GestionJoueur.getJoueurCourant().acheteMaison(GestionFiche.getById(maisons[i]));\n }\n}",
"static async getPair(base, other) {\n let data = await this.getAllRates();\n let pair = {};\n pair[base] = data.rates[base];\n pair[other] = data.rates[other];\n return pair;\n }",
"function setCouplesA(){\n\n // new couples\n for(i = 0; i < (numberOfPlayers / 2) - 1; ++i) { \n couples.push(new Couple(`${players[1 + i].name}`, `${players[(numberOfPlayers / 2) + 1 + i].name}`, 0));\n } \n}",
"function getAppelloDaPrenotare(cdsId,adId){\n return new Promise(function(resolve, reject) {\n var appelliDaPrenotare=[];\n var rawData='';\n\n getSingoloAppelloDaPrenotare(cdsId,adId).then((body)=>{\n //controllo che body sia un array\n if (Array.isArray(body)){\n rawData=JSON.stringify(body);\n //console.log('\\n\\nQUESTO IL BODY ESAMI PRENOTABILI ' +rawData);\n //creo oggetto libretto\n for(var i=0; i<body.length; i++){\n //modifica del 16/05/2019 dopo cambio query\n appelliDaPrenotare[i]= new appello(body[i].aaCalId,body[i].adCod, body[i].adDes, body[i].adId,body[i].appId, body[i].cdsCod,\n body[i].cdsDes,body[i].cdsId,body[i].condId,body[i].dataFineIscr,body[i].dataInizioApp, body[i].dataInizioIscr, body[i].desApp,\n //aggiunto qui in data 16/05/2019\n body[i].note,body[i].numIscritti,body[i].numPubblicazioni,body[i].numVerbaliCar,body[i].numVerbaliGen,\n body[i].presidenteCognome,body[i].presidenteId,body[i].presidenteNome,body[i].riservatoFlg,body[i].stato,body[i].statoAperturaApp,body[i].statoDes,body[i].statoInsEsiti,body[i].statoLog,body[i].statoPubblEsiti,body[i].statoVerb,\n body[i].tipoDefAppCod,body[i].tipoDefAppDes,body[i].tipoEsaCod,body[i].tipoSceltaTurno, null);\n \n appelliDaPrenotare[i].log();\n \n/*\n appelliDaPrenotare[i]= new appello(null,null, null, null,null, null,\n null,null,null,null,body[i].dataInizioApp, null, null,\n \n null,null,null,null,null,\n null,null,null,null,null,null,null,null,null,null,null,\n null,null,null,null, null);\n console.log('PD PD PD data '+body[i].dataInizioApp);\n appelliDaPrenotare[i].log();*/\n\n }\n resolve(appelliDaPrenotare);\n }\n });\n });\n\n}",
"static getPairForTrial(n_dots,win,correct,size=1){\n let stim_first = new Vs_stim('learn',win,size);\n stim_first.addRandomDots(n_dots);\n let stim_second = new Vs_stim('test',win,size);\n // copy elements because i dont want to write a copy ctor..\n // slice copies by value.\n stim_second.dots = stim_first.dots.slice(); \n stim_second.free_pos = stim_first.free_pos.slice(); \n\n if(correct == false){\n stim_second.moveRandomDot();\n }\n\n\n\n\n return {learn: stim_first,test:stim_second,toString:function(){return stim_first.toString()+\"_\"+stim_second.toString();}};\n\n }",
"function setupJoke() {\n randomKnockKnockJoke().forEach( stageOfJoke => {\n conversationBacklog.push(stageOfJoke)\n })\n \n}",
"function checkHand(current_hand) {\n let trump_count = 0;\n let queen_count = 0;\n let jack_count = 0;\n let total_points = 0;\n\n // Searching for all the trump, queens, and jacks (while adding up point total as well)\n for(let i = 0; i < current_hand.length; i++) {\n if(current_hand[i].code[0] == \"Q\"){\n queen_count++;\n }\n if(current_hand[i].code[0] == \"J\"){\n jack_count++;\n }\n if(current_hand[i].isTrump == true){\n trump_count++;\n }\n total_points += current_hand[i].pointValue;\n }\n\n // Determine strength of hand\n if(queen_count >= 3){\n return 1;\n }\n else if(queen_count >= 2 && trump_count >= 3){\n return 1;\n }\n else if(trump_count >= 4){\n return 1;\n }\n else if(queen_count == 2 && trump_count == 2){\n return 2;\n }\n else if(trump_count == 3 && total_points >=25){\n return 2;\n }\n else {\n return 0;\n }\n}",
"function libraryPairs(libraries) {\n if (libraries.length === 1) {\n return [libraries];\n }\n let pairedArray = [];\n libraries.forEach((element, index, ar)=> {\n for (let i = index + 1; i < ar.length; i++) {\n if (i !== index)\n pairedArray.push([element, ar[i]]);\n }\n });\n return pairedArray;\n }",
"function HandicapTeam() {\r\n db.transaction(function(transaction) {\r\n var maxCapacity = 0;\r\n var totalPlayers = 0;\r\n var count = 0;\r\n transaction.executeSql('SELECT * FROM jugadores', [],\r\n function(transaction, result) {\r\n if (result != null && result.rows != null) {\r\n maxCapacity = (Math.ceil(result.rows.length / 5.0) * 5) / 5;\r\n totalPlayers = result.rows.length;\r\n }\r\n }, nullHandler, errorHandler);\r\n\r\n var nEarly = 'NO';\r\n transaction.executeSql('SELECT * FROM jugadores, equipos WHERE jugadores.UserId = equipos.jugadorId AND jugadores.Early = ? ORDER BY equipos.numPareja DESC, jugadores.Handicap DESC', [nEarly],\r\n function(transaction, result) {\r\n if (result != null && result.rows != null) {\r\n var numTeam = maxCapacity;\r\n var len = result.rows.length;\r\n var pairs = len / 2;\r\n var countP = 0;\r\n var i = 0;\r\n if (pairs <= 1.5) {\r\n var triads = pairs;\r\n numTeam = 1;\r\n while (triads > 0) {\r\n var row = result.rows.item(i);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n count++;\r\n triads -= .5;\r\n i++;\r\n }\r\n } else {\r\n if (totalPlayers - len == 1 || (totalPlayers - (len * 2)) > 0) {\r\n numTeam = 1;\r\n i = len - 1;\r\n while ((pairs - countP) > 0) {\r\n var top = Math.round((pairs / maxCapacity) * 2) / 2;\r\n if ((pairs - countP) >= top) {\r\n var rim = top;\r\n while (rim > 0) {\r\n var row = result.rows.item(i);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n count++;\r\n i--;\r\n countP += .5;\r\n rim -= .5;\r\n }\r\n numTeam++;\r\n } else {\r\n var rem = pairs - countP;\r\n while (rem > 0) {\r\n var row = result.rows.item(i);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n count++;\r\n i--;\r\n countP += .5;\r\n rem -= .5;\r\n }\r\n numTeam++;\r\n }\r\n window.console.log('se agrega a numTeam= ' + numTeam + ' y countp= ' + countP);\r\n }\r\n } else {\r\n while ((pairs - countP) > 0) {\r\n var top = Math.round((Math.ceil(pairs) / maxCapacity) * 2) / 2;\r\n if (maxCapacity > 2) {\r\n if (top == 2.5) {\r\n if (numTeam < maxCapacity) {\r\n top = 2;\r\n }\r\n }\r\n if (top == 1.5) {\r\n if (numTeam == maxCapacity) {\r\n top = 2;\r\n }\r\n }\r\n }\r\n window.console.log('top ' + top);\r\n if ((pairs - countP) >= top) {\r\n var rim = top;\r\n while (rim > 0) {\r\n var row = result.rows.item(i);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n count++;\r\n i++;\r\n countP += .5;\r\n rim -= .5;\r\n window.console.log('se agrega a numTeam= ' + numTeam + ' y countp= ' + countP);\r\n }\r\n numTeam--;\r\n } else {\r\n var rem = pairs - countP;\r\n while (rem > 0) {\r\n var row = result.rows.item(i);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n count++;\r\n i++;\r\n countP += .5;\r\n rem -= .5;\r\n window.console.log('se agrega a numTeam= ' + numTeam + ' y countp= ' + countP);\r\n }\r\n numTeam--;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }, nullHandler, errorHandler);\r\n\r\n var topsArray = [];\r\n var sEarly = 'SOLO';\r\n transaction.executeSql('SELECT * FROM jugadores WHERE Early = ?', [sEarly],\r\n function(transaction, result) {\r\n if (result != null && result.rows != null) {\r\n if (result.rows.length == 0) {} else {\r\n window.console.log('count ' + count);\r\n var numTeam = 1;\r\n var resultArray = [];\r\n for (var i = 0; i < result.rows.length; i++) {\r\n resultArray.push(result.rows.item(i));\r\n }\r\n var shuffledArray = shuffle(resultArray);\r\n var len = result.rows.length;\r\n for (var w = 0; w < maxCapacity; w++) {\r\n topsArray.push(0);\r\n }\r\n var herm = count;\r\n var soly = totalPlayers - 1;\r\n var fnumTeams = maxCapacity;\r\n if (count <= 3) {\r\n topsArray[0] = count;\r\n } else {\r\n if (herm == soly) {\r\n fnumTeams = 1;\r\n while (herm > 0) {\r\n if (fnumTeams > maxCapacity) {\r\n fnumTeams = 1;\r\n }\r\n var rar = topsArray[fnumTeams - 1];\r\n topsArray[fnumTeams - 1] = rar + 1;\r\n fnumTeams++;\r\n herm--;\r\n }\r\n } else {\r\n while (herm > 0) {\r\n if (fnumTeams < 1) {\r\n fnumTeams = maxCapacity;\r\n }\r\n var rar = topsArray[fnumTeams - 1];\r\n topsArray[fnumTeams - 1] = rar + 1;\r\n fnumTeams--;\r\n herm--;\r\n }\r\n }\r\n }\r\n window.console.log('tops ' + topsArray);\r\n numTeam = maxCapacity;\r\n var min = topsArray[maxCapacity - 1];\r\n for (var m = 0; m < topsArray.length; m++) {\r\n if (topsArray[m] < min) {\r\n min = topsArray[m];\r\n }\r\n }\r\n window.console.log('min ' + min);\r\n for (var i = 0; i < len; i++) {\r\n var row = shuffledArray[i];\r\n if (numTeam < 1) {\r\n numTeam = maxCapacity;\r\n }\r\n window.console.log('esta iteracion ' + topsArray[numTeam - 1]);\r\n if (topsArray[numTeam - 1] > min) {\r\n var temp = topsArray[numTeam - 1];\r\n while (temp > min) {\r\n numTeam -= 1;\r\n if (numTeam < 1) {\r\n numTeam = maxCapacity;\r\n }\r\n temp = topsArray[numTeam - 1];\r\n }\r\n window.console.log('temp ' + temp + '\\nmin ' + min);\r\n }\r\n if (count <= 3 && len <= 2) {\r\n numTeam = 1;\r\n }\r\n window.console.log('iteracion antes de entrar ' + topsArray[numTeam - 1]);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n var temp = topsArray[numTeam - 1];\r\n topsArray[numTeam - 1] = temp + 1;\r\n numTeam--;\r\n window.console.log(topsArray);\r\n min = topsArray[maxCapacity - 1];\r\n for (var n = 0; n < topsArray.length; n++) {\r\n if (topsArray[n] < min) {\r\n min = topsArray[n];\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }, nullHandler, errorHandler);\r\n\r\n var yEarly = 'YES';\r\n transaction.executeSql('SELECT * FROM jugadores, equipos WHERE jugadores.UserId = equipos.jugadorId AND jugadores.Early = ? ORDER BY equipos.numPareja DESC', [yEarly],\r\n function(transaction, result) {\r\n if (result != null && result.rows != null) {\r\n if (result.rows.length == 0) {\r\n ListDBHandicapTeam();\r\n $(\"body\").pagecontainer(\"change\", \"#page9\");\r\n return;\r\n } else {\r\n var numTeam = maxCapacity;\r\n var resultArray = [];\r\n for (var i = 0; i < result.rows.length; i++) {\r\n resultArray.push(result.rows.item(i));\r\n }\r\n var shuffledArray = shuffle(resultArray);\r\n var len = result.rows.length;\r\n if (topsArray.length == 0) {\r\n for (var w = 0; w < maxCapacity; w++) {\r\n topsArray.push(0);\r\n }\r\n var herm = count;\r\n var soly = totalPlayers - 1;\r\n var fnumTeams = maxCapacity;\r\n if (count <= 3) {\r\n topsArray[0] = count;\r\n } else {\r\n if (herm == soly) {\r\n fnumTeams = 1;\r\n while (herm > 0) {\r\n if (fnumTeams > maxCapacity) {\r\n fnumTeams = 1;\r\n }\r\n var rar = topsArray[fnumTeams - 1];\r\n topsArray[fnumTeams - 1] = rar + 1;\r\n fnumTeams++;\r\n herm--;\r\n }\r\n } else {\r\n while (herm > 0) {\r\n if (fnumTeams < 1) {\r\n fnumTeams = maxCapacity;\r\n }\r\n var rar = topsArray[fnumTeams - 1];\r\n topsArray[fnumTeams - 1] = rar + 1;\r\n fnumTeams--;\r\n herm--;\r\n }\r\n }\r\n }\r\n }\r\n window.console.log('tops ' + topsArray);\r\n numTeam = maxCapacity;\r\n var min = topsArray[maxCapacity - 1];\r\n for (var m = 0; m < topsArray.length; m++) {\r\n if (topsArray[m] < min) {\r\n min = topsArray[m];\r\n }\r\n }\r\n window.console.log('min ' + min);\r\n for (var i = 0; i < result.rows.length; i++) {\r\n var row = shuffledArray[i];\r\n if (numTeam < 1) {\r\n numTeam = maxCapacity;\r\n }\r\n window.console.log('esta iteracion ' + topsArray[numTeam - 1]);\r\n if (topsArray[numTeam - 1] > min) {\r\n var temp = topsArray[numTeam - 1];\r\n while (temp > min) {\r\n numTeam -= 1;\r\n if (numTeam < 1) {\r\n numTeam = maxCapacity;\r\n }\r\n temp = topsArray[numTeam - 1];\r\n }\r\n window.console.log('temp ' + temp + '\\nmin ' + min);\r\n }\r\n /*if(topsArray[numTeam-1]==min){\r\n if(numTeam==1){\r\n numTeam=maxCapacity;\r\n }\r\n }*/\r\n if (count <= 3 && len <= 2) {\r\n numTeam = 1;\r\n }\r\n window.console.log('iteracion antes de entrar ' + topsArray[numTeam - 1] + ' en team ' + numTeam);\r\n transaction.executeSql('UPDATE equipos SET numEquipo = ? Where jugadorId = ?', [numTeam, row.UserId], nullHandler, errorHandler);\r\n var temp = topsArray[numTeam - 1];\r\n topsArray[numTeam - 1] = temp + 1;\r\n numTeam--;\r\n window.console.log(topsArray);\r\n min = topsArray[maxCapacity - 1];\r\n for (var n = 0; n < topsArray.length; n++) {\r\n if (topsArray[n] < min) {\r\n min = topsArray[n];\r\n }\r\n }\r\n }\r\n }\r\n ListDBHandicapTeam();\r\n $(\"body\").pagecontainer(\"change\", \"#page9\");\r\n } else {\r\n if (maxCapacity != 0) {\r\n ListDBHandicapTeam();\r\n $(\"body\").pagecontainer(\"change\", \"#page9\");\r\n }\r\n }\r\n }, nullHandler, errorHandler);\r\n\r\n }, errorHandler, nullHandler);\r\n}",
"function compute_LF_hopPP(ibu) {\n var LF_hopPP = 0.0;\n\n // Assume krausen, finings, filtering affect hop PP the same as other nonIAA.\n LF_hopPP = SMPH.LF_hopPP *\n SMPH.ferment_hopPP *\n compute_LF_nonIAA_krausen(ibu) *\n compute_LF_finings(ibu) *\n compute_LF_filtering(ibu);\n\n return(LF_hopPP);\n}",
"function adjustTask( task, state, handicap, highesthandicap ) {\n //\n if( state.adjustments ) {\n return state.adjustments;\n }\n\n // Make a new array for it\n var newTask = state.adjustments = _clonedeep(task);\n\n // reduction amount (%ish)\n var maxhtaskLength = task.distance / (highesthandicap/100);\n var mytaskLength = maxhtaskLength * (handicap/100);\n var mydifference = task.distance - mytaskLength;\n var spread = 2*(newTask.legs.length-1)+2; // how many points we can spread over\n var amount = mydifference/spread;\n\n // how far we need to move the radius in to achieve this reduction\n var adjustment = Math.sqrt( 2*(amount*amount) );\n\n // Now copy over the points reducing all symmetric\n newTask.legs.slice(1,newTask.legs.length-1).forEach( (leg) => {\n if( leg.type == 'sector' && leg.direction == 'symmetrical') {\n leg.r2 += adjustment;\n }\n else {\n console.log( \"Invalid handicap distance task: \"+leg.toString() );\n }\n });\n\n // For scoring this handicap we need to adjust our task distance as well\n newTask.distance = mytaskLength;\n return newTask;\n}",
"function compute_maltPP_beer(ibu) {\n var factor = 0.0;\n var IBU_malt = 0.0;\n var IBU1 = 0.70;\n var pH = ibu.pH.value;\n var points = 0.0;\n var PP_malt = 0.0;\n var preBoilIBU = 0.0;\n var preBoilpH = ibu.pH.value;\n var preOrPostBoilpH = ibu.preOrPostBoilpH.value;\n var slope = 1.7348;\n\n // If user specifies pre-boil pH, estimate the post-boil pH\n if (preOrPostBoilpH == \"preBoilpH\") {\n preBoilpH = pH;\n pH = compute_postBoil_pH(preBoilpH);\n }\n\n preBoilpH = 5.75; // approximate value before any pH adjustment\n points = (ibu.OG.value - 1.0) * 1000.0;\n preBoilIBU = points * 0.0190;\n factor = (slope * (preBoilpH - pH) / IBU1) + 1.0;\n IBU_malt = preBoilIBU * factor;\n // console.log(\"computing maltPP:\");\n // console.log(\" gravity \" + ibu.OG.value);\n // console.log(\" pre-boil pH \" + preBoilpH);\n // console.log(\" post-boil pH \" + pH);\n // console.log(\" correction factor \" + factor);\n // console.log(\" IBU before boil \" + preBoilIBU);\n // console.log(\" IBU after correction \" + IBU_malt);\n\n // the convertion from IBU to PP is not correct, but in the end we\n // want IBUs not PP and so it doesn't matter; we just need to undo\n // the Peacock conversion that we'll do later.\n PP_malt = IBU_malt * 69.68 / 50.0;\n\n // decrease the IBU by the amount of finings added and any filtration\n PP_malt = PP_malt * compute_LF_finings(ibu) * compute_LF_filtering(ibu);\n\n // console.log(\" PP_malt \" + PP_malt);\n return PP_malt;\n}",
"function triangulate(points){\n\tconst delaunay = Delaunator.from(points);\n\tconst tri = delaunay.triangles;\n\tvar triangles = []\n\tfor(var i=0;i<tri.length;i+=3){\n\t\ttriangles.push([tri[i], tri[i+1], tri[i+2]]);\n\t}\n\treturn(triangles);\n}",
"continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }",
"function Start () {\n PartLoader.PreloadParts();\n\tvar part1 = PartLoader.LoadPart(\"Cockpit1\");\n\tvar part2 = PartLoader.LoadPart(\"Engine1\");\n\t//var part3 = PartLoader.LoadPart(\"Engine1\");\n\t//var part4 = PartLoader.LoadPart(\"Engine1\");\n\t//var part5 = PartLoader.LoadPart(\"Engine1\");\n\tpart1.transform.parent = transform;\n\tpart2.transform.parent = transform;\n\t//part3.transform.parent = transform;\n\t//part4.transform.parent = transform;\n\t//part5.transform.parent = transform;\n\tvar ship : ShipBehavior = GetComponent(\"ShipBehavior\") as ShipBehavior;\n\tship.Initialize();\n\t(part1.GetComponent(PartBehavior) as PartBehavior).ConnectToHardpoint((part2.GetComponent(PartBehavior) as PartBehavior),0,0);\n\t//(part3.GetComponent(\"PartBehavior\") as PartBehavior).ConnectToHardpoint((part2.GetComponent(\"PartBehavior\") as PartBehavior),1,2);\n\t//(part4.GetComponent(\"PartBehavior\") as PartBehavior).ConnectToHardpoint((part2.GetComponent(\"PartBehavior\") as PartBehavior),2,1);\n\t//(part5.GetComponent(\"PartBehavior\") as PartBehavior).ConnectToHardpoint((part2.GetComponent(\"PartBehavior\") as PartBehavior),3,4);\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set up modal transaction status | function setModal(textColor, statusTx, transactionAddress) {
function removeClass(index, className) {
return (className.match(/\btext-\S+/g) || []).join(' ');
}
$('#contain-status-modal').removeClass(removeClass);
if (transactionAddress != null) {
let addressTxCompress = transactionAddress.substring(0, 10) + "..." + transactionAddress.substring(transactionAddress.length - 5, transactionAddress.length);
$('#transaction-hash-modal').html(addressTxCompress);
$('#link-to-ropsten').attr('href', 'https://ropsten.etherscan.io/tx/' + transactionAddress);
$('#link-to-ropsten').removeClass('d-none');
} else {
$('#transaction-hash-modal').html("Processing");
if (!$('#link-to-ropsten').hasClass('d-none')) {
$('#link-to-ropsten').addClass('d-none');
}
}
$('#contain-status-modal').addClass(textColor);
$('#name-status-modal').html(statusTx);
if (statusTx === 'Success') {
$('#icon-success-modal').removeClass('d-none');
$('#spinner-status-modal').addClass('d-none');
} else {
if (!$('#icon-success-modal').hasClass('d-none')) {
$('#icon-success-modal').addClass('d-none');
}
if ($('#spinner-status-modal').hasClass('d-none')) {
$('#spinner-status-modal').removeClass('d-none');
}
}
} | [
"function TxStatus(_util) {\n\t\tconst _$e = $(`\n\t\t\t<div class='TxStatus'>\n\t\t\t\t<div class='clear'>clear</div>\n\t\t\t\t<div class='status'></div>\n\t\t\t</div>\n\t\t`);\n\t\tconst _opts = {};\n\t\tconst _$clear = _$e.find(\".clear\").hide();\n\t\tconst _$status = _$e.find(\".status\");\n\n\t\t_$clear.click(function(){\n\t\t\t_$e.remove();\n\t\t\t(_opts.onClear || function(){})();\n\t\t});\n\n\t\tfunction _setTxPromise(p, opts) {\n\t\t\t_addOpts(opts);\n\t\t\tconst miningMsg = _opts.miningMsg || \"Your transaction is being mined...\";\n\t\t\tconst successMsg = _opts.successMsg || \"Your transaction was mined!\";\n\t\t\tconst waitTimeMs = _opts.waitTimeMs || 15000;\n\t\t\tconst onSuccess = _opts.onSuccess || function(){};\n\t\t\tvar txId;\n\t\t\tvar loadingBar;\n\n\t\t\t_$status.text(\"Waiting for signature...\");\n\t\t\tif (p.getTxHash){\n\t\t\t\tp.getTxHash.then(function(tId){\n\t\t\t\t\ttxId = tId;\n\t\t\t\t\tloadingBar = _util.getLoadingBar(waitTimeMs);\n\t\t\t\t\t_$status.empty()\n\t\t\t\t\t\t.append(_util.$getTxLink(miningMsg, txId))\n\t\t\t\t\t\t.append(loadingBar.$e);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tp.then(function(res){\n\t\t\t\tif (loadingBar) {\n\t\t\t\t\t_$clear.show();\n\t\t\t\t\tloadingBar.finish(500).then(()=>{\n\t\t\t\t\t\t_$status.empty().append(_util.$getTxLink(successMsg, txId));\n\t\t\t\t\t\tonSuccess(res);\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tonSuccess(res);\n\t\t\t\t}\n\t\t\t}).catch((e)=>{\n\t\t\t\t_$clear.show();\n\t\t\t\tif (txId) {\n\t\t\t\t\tloadingBar.finish(500).then(()=>{\n\t\t\t\t\t\t_$status.empty()\n\t\t\t\t\t\t\t.append(util.$getTxLink(\"Your tx failed.\", txId))\n\t\t\t\t\t\t\t.append(`<br>${e.message}`);\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t_$status.text(`${e.message.split(\"\\n\")[0]}`);\t\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tfunction _addOpts(opts) {\n\t\t\tif (!opts) return;\n\t\t\tObject.assign(_opts, opts);\n\t\t}\n\n\t\tthis.setTxPromise = (p, opts) => { _setTxPromise(p, opts); };\n\t\tthis.setStatus = (str) => { _$status.text(str); };\n\t\tthis.addOpts = (opts) => { _addOpts(opts); };\n\t\tthis.fail = (str) => { _$clear.show(); _$status.text(str); };\n\t\tthis.$e = _$e;\n\t\tthis.$status = _$status;\n\t}",
"function showStatusMultimodal()\n {\n //alert($('#leadsCount').val());\n var count = parseInt($('#leadsCount').val());\n if(count)\n {\n var leadCountTxt = (count>1)?count+\" Leads\":count+\" Lead\";\n //alert('showTransferMultiModal');\n $(\".leadCountTxt\").text(leadCountTxt);\n $(\"#show_status_multimodal\").modal('show');\n\n $.post(base_url+'plugins/get_status_list',\n function(msg){\n $('#statusId').html(msg);\n });\n }\n else\n {\n alert(\"Select a record to transfer.\");\n }\n }",
"commitTransaction() {\n\t\tthis.isTransacting = false;\n\t\tthis.save();\n\t}",
"function location_detail_change_status (location_detail_type, location_detail_id, location_detail_name, status) {\n\t\t// If status yes, activate. If status no, deactivate\n\t\tif (status==\"yes\") {\n\t\t\tconfirm_info = \"<strong>activate</strong>\";\n\t\t}\n\t\telse if (status==\"no\") {\n\t\t\tconfirm_info = \"<strong>deactive</strong>\";\n\t\t}\n\t\t// Set modal value and show it!\n\t\t$(\"#modal_form\").attr('action', './process.php');\n\t\t$(\"#modal_title\").html(\"Confirmation\");\n\t\t$(\"#modal_content\").html(\"<p class='text-center'>location_detail name : \"+location_detail_name+\" <br>Sure want to \"+confirm_info+\" this location detail?</p><input type='hidden' name='location_detail_id' value='\"+location_detail_id+\"'><input type='hidden' name='location_detail_type' value='\"+location_detail_type+\"'><input type='hidden' name='status' value='\"+status+\"'><input type='hidden' name='action' value='location_detail_change_status'>\");\n\t\t$(\"#modal_footer\").html(\"<button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button> <button type='submit' class='btn btn-primary'>Yes</button>\");\n\t\t$(\"#modal_dialog\").modal(\"show\");\n\t}",
"function uiPagePurchaseSuccess() {\n updateModalVisilibity(\n ['shop-success'], ['shop-tshirt', 'shop-checkout']);\n}",
"function initModalBoxes() {\n var newTransModal = document.getElementById('newTransactionPopup');\n var newTransSpan = document.getElementById(\"closeNewTrans\");\n var newTransBtn = document.getElementById('transactionButton');\n var viewTransModal = document.getElementById('viewTransactionPopup');\n var viewTransSpan = document.getElementById('viewTransSpan');\n var viewTransBtn = document.getElementById('viewTransactionsButton');\n var infoPopup = document.getElementById('infoPopup');\n var infoSpan = document.getElementById('infoSpan');\n var infoButton = document.getElementById('viewInfoButton');\n\n infoSpan.onclick = function() {\n infoPopup.style.display = \"none\";\n }\n newTransSpan.onclick = function() {\n newTransModal.style.display = \"none\";\n }\n window.onclick = function(event) {\n if (event.target == newTransModal) {\n newTransModal.style.display = \"none\";\n } else if (event.target == viewTransModal) {\n viewTransModal.style.display = \"none\";\n } else if (event.target == infoPopup) {\n infoPopup.style.display = \"none\";\n }\n }\n newTransBtn.onclick = function() {\n newTransModal.style.display = \"block\";\n }\n viewTransSpan.onclick = function() {\n viewTransModal.style.display = \"none\";\n }\n viewTransBtn.onclick = function() {\n viewTransModal.style.display = \"block\";\n getTable('/transactions', 'transactionsContainer', ['Storage', 'Product', 'Amount', 'Date']);\n }\n viewInfoButton.onclick = function() {\n infoPopup.style.display = \"block\";\n getTable('/productInfo', 'infoContainer', ['Name', 'Id number', 'Price']);\n }\n}",
"function handleNewTransaction() {\n setSelectedTransaction({});\n setIsOpen(true);\n }",
"function show_result(data){\n $('#result_modal').on('hide.bs.modal', function(){\n get_client(0);\n get_clients(0);\n get_transactions();\n pagination();\n load_transactions();\n });\n $title = $('#result_modal').find('#result_modal_label');\n $alert = $('#result_modal').find('.alert');\n $alert.removeClass('alert-danger');\n $alert.removeClass('alert-success');\n if(data['t_id']!=undefined || data['success']!=undefined){\n $title.text('Success');\n $alert.addClass('alert-success');\n $alert.text('Transaction submitted successfully');\n }else{\n $title.text('Error');\n $alert.addClass('alert-danger');\n $alert.text(data);\n }\n $('#result_modal').modal('show');\n setTimeout(function(){$('#result_modal').modal('hide');}, 3000);\n}",
"function ModConfirm_PartexCheck_Open() {\n console.log(\" ----- ModConfirm_PartexCheck_Open ----\")\n\n // --- create mod_dict\n mod_dict = {mode: \"remove_partex\"};\n\n const data_dict = mod_MEX_dict.partex_dict[mod_MEX_dict.sel_partex_pk];\n const partex_name = (data_dict) ? data_dict.name : \"-\";\n\n const msg_html = [\"<p class=\\\"p-2\\\">\", loc.All_partex_willbe_removed, \"<br>\",\n loc.except_for_selected_exam, \" '\", partex_name, \"'.\",\n \"</p><p class=\\\"p-2\\\">\", loc.Do_you_want_to_continue, \"</p>\"].join(\"\")\n el_confirm_msg_container.innerHTML = msg_html;\n\n el_confirm_header.innerText = loc.Remove_partial_exams;\n el_confirm_loader.classList.add(cls_hide);\n el_confirm_msg_container.classList.remove(\"border_bg_invalid\", \"border_bg_valid\");\n el_confirm_btn_save.innerText = loc.Yes_remove;\n add_or_remove_class(el_confirm_btn_save, \"btn-outline-secondary\", true, \"btn-primary\")\n\n el_confirm_btn_cancel.innerText = loc.No_cancel;\n\n// set focus to cancel button\n setTimeout(function (){\n el_confirm_btn_cancel.focus();\n }, 500);\n\n// show modal\n $(\"#id_mod_confirm\").modal({backdrop: true});\n\n }",
"toggleCleared(transaction) {\n\t\tthis.transactionModel.updateStatus(this.contextModel.path(this.context.id), transaction.id, transaction.status).then(() => this.updateReconciledTotals());\n\t}",
"_order_accepted(event) {\n const order = event.detail;\n if (order.pcode == this.pcode)\n return;\n\n this.$.modal.modal_text = `Do you want to ${order.is_bid ? 'sell' : 'buy'} for ${order.price}?`\n this.$.modal.on_close_callback = (accepted) => {\n if (!accepted)\n return;\n\n this.$.trader_state.accept_order(order);\n };\n this.$.modal.show();\n }",
"function onModalReady() {\n // count tasks to be shown in the progress bar\n var i, j;\n\n progressMax = progressMax + 1; // create zip\n progressMax = progressMax + 1; // look up form\n progressMax = progressMax + 1; // look up version\n\n for (i = 0; i < invoiceData.length; i++) {\n\n if (!invoiceData[i].patientId || !invoiceData[i].activities) {\n callback('Invalid data sent.');\n return;\n }\n\n patientsToProcess.push(invoiceData[i].patientId);\n progressMax = progressMax + 1; // load patient\n\n for (j = 0; j < invoiceData[i].activities.length; j++) {\n progressMax = progressMax + 1; // render activity\n }\n }\n\n jqProgress = $('#divRenderProgress');\n jqStatus = $('#divRenderStatus');\n\n jqStatus.html('Erstelle Zip-Archive...');\n Y.doccirrus.comctl.privateGet('/1/media/:createzip', {}, onZipCreated);\n }",
"function onTradeOfferSent (tradeofferid)\n{\n TradeOfferID = tradeofferid;\n\n showModal();\n checkTradeOffer();\n}",
"function showTaskStatus(status) {\n return $modal.open({\n templateUrl: apps_url + 'assets/sync_manager/templates/task_status.html',\n controller: 'taskStatusController',\n resolve: {\n status: function () {\n return status;\n }\n }\n });\n }",
"getAndSetModalOnUI() {\n this.modalOnUI = document.getElementById(\"iovon-hybrid-modal\");\n }",
"function editTransaction(tid) {\r\n document.getElementById(tid).click()\r\n document.getElementById('txnEdit-toggle').click()\r\n}",
"toggleTransactionDetails() {\n var showorHidden = (this.state.showTransaction === \"hidden\") ? \"show\" : \"hidden\";\n this.setState({\n showTransaction:showorHidden\n });\n }",
"reconcile() {\n\t\tif (!this.reconciling) {\n\t\t\t// Disable navigation on the table\n\t\t\tthis.ogTableNavigableService.enabled = false;\n\n\t\t\t// Show the modal\n\t\t\tthis.$uibModal.open({\n\t\t\t\ttemplateUrl: AccountReconcileView,\n\t\t\t\tcontroller: \"AccountReconcileController\",\n\t\t\t\tcontrollerAs: \"vm\",\n\t\t\t\tbackdrop: \"static\",\n\t\t\t\tsize: \"sm\",\n\t\t\t\tresolve: {\n\t\t\t\t\taccount: () => this.context\n\t\t\t\t}\n\t\t\t}).result.then(closingBalance => {\n\t\t\t\t// Make the closing balance available on the scope\n\t\t\t\tthis.closingBalance = closingBalance;\n\n\t\t\t\t// Refresh the list with only unreconciled transactions\n\t\t\t\tthis.toggleUnreconciledOnly(true);\n\n\t\t\t\t// Switch to reconcile mode\n\t\t\t\tthis.reconciling = true;\n\t\t\t}).finally(() => (this.ogTableNavigableService.enabled = true));\n\t\t}\n\t}",
"function addPendingTransactions() {\n blockchain.pendingTransactions.forEach(transaction => {\n const pendingTransactionsTable = document.getElementById(\"newPendingTransactionTable\");\n\n if (!document.getElementById(\"transactionId\") || transaction.transactionId !== document.getElementById(\"transactionId\").innerHTML) {\n let row = pendingTransactionsTable.insertRow();\n let transactionId = row.insertCell(0);\n transactionId.innerHTML = transaction.transactionId;\n transactionId.id = \"transactionId\";\n let txTimestamp = row.insertCell(1);\n txTimestamp.innerHTML = (new Date(transaction.txTimestamp)).toLocaleTimeString();\n let sender = row.insertCell(2);\n sender.innerHTML = transaction.sender;\n let recipient = row.insertCell(3);\n recipient.innerHTML = transaction.recipient;\n let amount = row.insertCell(4);\n amount.innerHTML = transaction.amount;\n } else {\n return;\n };\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Language: Mizar Description: The Mizar Language is a formal language derived from the mathematical vernacular. | function mizar(hljs) {
return {
name: 'Mizar',
keywords:
'environ vocabularies notations constructors definitions ' +
'registrations theorems schemes requirements begin end definition ' +
'registration cluster existence pred func defpred deffunc theorem ' +
'proof let take assume then thus hence ex for st holds consider ' +
'reconsider such that and in provided of as from be being by means ' +
'equals implies iff redefine define now not or attr is mode ' +
'suppose per cases set thesis contradiction scheme reserve struct ' +
'correctness compatibility coherence symmetry assymetry ' +
'reflexivity irreflexivity connectedness uniqueness commutativity ' +
'idempotence involutiveness projectivity',
contains: [
hljs.COMMENT('::', '$')
]
};
} | [
"function menutoshowlang(){\n}",
"function footerLanguage(){\r\n\tif(fileName==\"espana.html\"){\r\n\t\tfooterSpanish();\r\n\r\n\t} else if(fileName!=\"espana.html\"){\r\n\t \tfooterGerman();\r\n\t}\r\n}",
"function updateLanguage(select_language, select_dialect) {\n var list = langs[select_language.selectedIndex];\n select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';\n localStorage['dialect'] = select_dialect.selectedIndex; \n document.getElementById('voiceBtn').setAttribute('lang', list[select_dialect.selectedIndex + 1][0]);\n}",
"function helloWorld(language) {\r\n if (language === 'fr') {\r\n return 'Bonjour tout le monde';\r\n }\r\n else if (language === 'es') {\r\n return 'Hola, Mundo';\r\n }\r\n else (language === '') {\r\n return 'Hello, World';\r\n }\r\n}",
"function detectLanguage(){\r\n\tvar langIdentifier = 'notícias';\r\n\tif (gexQuery('#ctl00_ucMenu_lnkStart').text().toLowerCase() == langIdentifier)\r\n\t\t_isPortuguese = 1;\r\n}",
"function cyrillic_adjustments(graphemes) {\n\n cyr_graphemes = cyrillic_adjust_doubleVowel(graphemes)\n\n var au_for_capitals = {\n \"\\u0430\":\"\\u042F\", // CYRILLIC SMALL LETTER A to CAPITAL LETTER YA\n \"\\u0443\":\"\\u042E\", // CYRILLIC SMALL LETTER U to CAPITAL LETTER YU\n \n \"\\u0430\\u0304\":\"\\u042F\\u0304\", // CYRILLIC SMALL LETTER A with MACRON to CAPITAL LETTER YA with MACRON\n \"\\u04EF\":\"\\u042E\\u0304\", // CYRILLIC SMALL LETTER U with MACRON to CAPITAL LETTER YU with MACRON\n }\n\n var shortAU = {\n \"\\u0430\":\"\\u044F\", // CYRILLIC SMALL LETTER A to SMALL LETTER YA\n \"\\u0443\":\"\\u044E\", // CYRILLIC SMALL LETTER U to SMALL LETTER YU\n\n \"\\u0430\\u0301\":\"\\u044F\\u0301\", // CYRILLIC SMALL LETTER A with ACUTE ACCENT to SMALL LETTER YA with ACUTE ACCENT\n \"\\u0443\\u0301\":\"\\u044E\\u0301\", // CYRILLIC SMALL LETTER U with ACUTE ACCENT to SMALL LETTER YU with ACUTE ACCENT\n\n \"\\u0430\\u0302\":\"\\u044F\\u0302\", // CYRILLIC SMALL LETTER A with CIRCUMFLEX to SMALL LETTER YA with CIRCUMFLEX\n \"\\u0443\\u0302\":\"\\u044E\\u0302\", // CYRILLIC SMALL LETTER U with CIRCUMFLEX to SMALL LETTER YU with CIRCUMFLEX\n }\n\n var longAU = {\n \"\\u0430\\u0304\":\"\\u044F\\u0304\", // CYRILLIC SMALL LETTER A with MACRON to SMALL LETTER YA with MACRON\n \"\\u04EF\":\"\\u044E\\u0304\", // CYRILLIC SMALL LETTER U with MACRON to SMALL LETTER YU with MACRON\n\n \"\\u0430\\u0304\\u0301\":\"\\u044F\\u0304\\u0301\", // A with MACRON and ACUTE to YA with MACRON and ACUTE\n \"\\u04EF\\u0301\":\"\\u044E\\u0304\\u0301\", // U with MACRON and ACUTE to YU with MACRON and ACUTE\n\n \"\\u0430\\u0304\\u0302\":\"\\u044F\\u0304\\u0302\", // A with MACRON and CIRCUMFLEX to YA with MACRON and CIRCUMFLEX\n \"\\u04EF\\u0302\":\"\\u044E\\u0304\\u0302\", // U with MACRON and CIRCUMFLEX to YU with MACRON and CIRCUMFLEX\n }\n\n var vowels = { \n \"\\u0438\":\"i\", // CYRILLIC SMALL LETTER I \n \"\\u0430\":\"a\", // CYRILLIC SMALL LETTER A\n \"\\u0443\":\"u\", // CYRILLIC SMALL LETTER U\n \"\\u044B\":\"e\", // CYRILLIC SMALL LETTER YERU\n \"\\u04E3\":\"ii\", // CYRILLIC SMALL LETTER I with MACRON\n \"\\u0430\\u0304\":\"aa\", // CYRILLIC SMALL LETTER A with MACRON\n \"\\u04EF\":\"uu\", // CYRILLIC SMALL LETTER U with MACRON\n } \n\n var lzlls = {\n \"\\u043B\":\"l\", // CYRILLIC SMALL LETTER EL\n \"\\u0437\":\"z\", // CYRILLIC SMALL LETTER ZE\n \"\\u043B\\u044C\":\"ll\", // CYRILLIC SMALL LETTER EL and SMALL LETTER SOFT SIGN\n \"\\u0441\":\"s\", // CYRILLIC SMALL LETTER ES\n\n \"\\u041B\":\"L\", // CYRILLIC CAPITAL LETTER EL\n \"\\u0417\":\"Z\", // CYRILLIC CAPITAL LETTER ZE\n \"\\u0421\":\"S\", // CYRILLIC CAPITAL LETTER ES\n \"\\u041B\\u044C\":\"Ll\", // CYRILLIC CAPITAL LETTER EL and SMALL LETTER SOFT SIGN\n } \n\n // Swaps position of the labialization symbol, i.e. Small Letter U with Dieresis\n var labialC = {\n \"\\u043A\\u04F1\":\"\\u04F1\\u043A\", // CYRILLIC SMALL LETTER KA and SMALL LETTER U with DIERESIS\n \"\\u049B\\u04F1\":\"\\u04F1\\u049B\", // CYRILLIC SMALL LETTER KA with DESCENDER and SMALL LETTER U with DIERESIS \n \"\\u04F7\\u04F1\":\"\\u04F1\\u04F7\", // CYRILLIC SMALL LETTER GHE with DESCENDER and SMALL LETTER U with DIERESIS \n \"\\u0445\\u04F1\":\"\\u04F1\\u0445\", // CYRILLIC SMALL LETTER HA and SMALL LETTER U with DIERESIS\n \"\\u04B3\\u04F1\":\"\\u04F1\\u04B3\", // CYRILLIC SMALL LETTER HA with DESCENDER and SMALL LETTER U with DIERESIS\n \"\\u04A3\\u04F1\":\"\\u04F1\\u04A3\", // CYRILLIC SMALL LETTER EN with DESCENDER and SMALL LETTER U with DIERESIS\n \"\\u04A3\\u044C\\u04F1\":\"\\u04F1\\u04A3\\u044C\", // CYRILLIC SMALL LETTER EN with DESCENDER & SMALL LETTER SOFT SIGN\n // & SMALL LETTER U with DIERESIS\n }\n\n var voicelessC = {\n // Stops \n \"\\u043F\":\"p\", // CYRILLIC SMALL LETTER PE\n \"\\u0442\":\"t\", // CYRILLIC SMALL LETTER TE\n \"\\u043A\":\"k\", // CYRILLIC SMALL LETTER KA\n \"\\u043A\\u04F1\":\"kw\", // CYRILLIC SMALL LETTER KA and SMALL LETTER U with DIERESIS\n \"\\u049B\":\"q\", // CYRILLIC SMALL LETTER KA with DESCENDER\n \"\\u049B\\u04F1\":\"qw\", // CYRILLIC SMALL LETTER KA with DESCENDER and SMALL LETTER U with DIERESIS \n\n // Voiceless fricatives \n \"\\u0444\":\"ff\", // CYRILLIC SMALL LETTER EF\n \"\\u043B\\u044C\":\"ll\", // CYRILLIC SMALL LETTER EL and SMALL LETTER SOFT SIGN\n \"\\u0441\":\"s\", // CYRILLIC SMALL LETTER ES\n \"\\u0448\":\"rr\", // CYRILLIC SMALL LETTER SHA\n \"\\u0445\":\"gg\", // CYRILLIC SMALL LETTER HA\n \"\\u0445\\u04F1\":\"wh\", // CYRILLIC SMALL LETTER HA and SMALL LETTER U with DIERESIS\n \"\\u04B3\":\"ghh\", // CYRILLIC SMALL LETTER HA with DESCENDER\n \"\\u04B3\\u04F1\":\"ghhw\", // CYRILLIC SMALL LETTER HA with DESCENDER and SMALL LETTER U with DIERESIS\n \"\\u0433\":\"h\", // CYRILLIC SMALL LETTER GHE\n\n // Voiceless nasals \n \"\\u043C\\u044C\":\"mm\", // CYRILLIC SMALL LETTER EM and SMALL LETTER SOFT SIGN\n \"\\u043D\\u044C\":\"nn\", // CYRILLIC SMALL LETTER EN and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\":\"ngng\", // CYRILLIC SMALL LETTER EN with DESCENDER and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\\u04F1\":\"ngngw\", // CYRILLIC SMALL LETTER EN with DESCENDER & SMALL LETTER SOFT SIGN & SMALL LETTER U with DIERESIS\n }\n \n // Removes devoicing sign, i.e. Small Letter Soft Sign\n var voicelessNasals = {\n \"\\u043C\\u044C\":\"\\u043C\", // CYRILLIC SMALL LETTER EM and SMALL LETTER SOFT SIGN\n \"\\u043D\\u044C\":\"\\u043D\", // CYRILLIC SMALL LETTER EN and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\":\"\\u04A3\", // CYRILLIC SMALL LETTER EN with DESCENDER and SMALL LETTER SOFT SIGN\n \"\\u04A3\\u044C\\u04F1\":\"\\u04A3\\u04F1\", // CYRILLIC SMALL LETTER EN with DESCENDER & SMALL LETTER SOFT SIGN\n } // & SMALL LETTER U with DIERESIS\n\n var result = []\n\n for (var i = 0; i < cyr_graphemes.length; i++) {\n var grapheme = cyr_graphemes[i]\n\n // ADJUSTMENT 1: The Cyrillic pairings of 'y-a', 'y-u', 'y-aa', 'y-uu'are rewritten\n // into Cyrillic YA, YU, YA WITH MACRON, YU with MACRON respectively\n // First checks if grapheme is Cyrillic 'y'\n if (grapheme == \"\\u04E4\" && (i < cyr_graphemes.length - 1)) {\n after_for_capitals = cyr_graphemes[i+1]\n\n if (after_for_capitals in au_for_capitals) {\n result.push(au_for_capitals[after_for_capitals])\n i++\n } else {\n result.push(grapheme)\n }\n } else if (grapheme == \"\\u04E5\" && (i < cyr_graphemes.length - 1)) { \n after = cyr_graphemes[i+1]\n\n if (after in shortAU) {\n // ADJUSTMENT 2: If 'ya' or 'yu' follow a consonant, insert a Cyrillic soft sign between\n if (i > 0 && isAlpha(cyr_graphemes[i-1]) && !(cyr_graphemes[i-1] in vowels)) {\n result.push(\"\\u044C\")\n }\n result.push(shortAU[after])\n i++\n } else if (after in longAU) {\n result.push(longAU[after])\n i++\n } else {\n result.push(grapheme)\n }\n } \n\n // ADJUSTMENT 3: The 'a', 'u' Cyrillic representations are rewritten \n // if they follow the Cyrillic representations of 'l', 'z', 'll', 's'\n else if (i > 0 && grapheme in shortAU && cyr_graphemes[i-1] in lzlls) {\n result.push(shortAU[grapheme])\n }\n \n // ADJUSTMENT - Labialization symbol can appear either before or after\n // the consonant it labializes. It moves to appear next to a vowel \n else if (i > 0 && grapheme in labialC && cyr_graphemes[i-1] in vowels) {\n result.push(labialC[grapheme])\n }\n\n // ADJUSTMENT - Cyrillic representation of 'e' deletes before a voiceless\n // consonant cluster\n else if (grapheme == \"\\u042B\" && (i < cyr_graphemes.length - 2) &&\n cyr_graphemes[i+1] in voicelessC && cyr_graphemes[i+2] in voicelessC) {\n result.push(\"\")\n result.push(cyr_graphemes[i+1].toUpperCase())\n i++\n } else if (grapheme == \"\\u044B\" && (i < cyr_graphemes.length - 2) &&\n cyr_graphemes[i+1] in voicelessC && cyr_graphemes[i+2] in voicelessC) {\n result.push(\"\") \n }\n\n // ADJUSTMENT - Devoicing sign is omitted for a voiceless nasal if it\n // appears after a voiceless consonant\n else if (i > 0 && grapheme in voicelessNasals && cyr_graphemes[i-1] in voicelessC) {\n result.push(voicelessNasals[grapheme])\n }\n\n // No adjustments applicable\n else {\n result.push(grapheme)\n }\n\n } // End 'for' Loop\n\n return result\n}",
"function UmmAlQuraCalendar(language) {\r\n\tthis.local = this.regional[language || ''] || this.regional[''];\r\n}",
"static translation(v) {\r\n\t\tres = identity(); \t\tres.M[3] = v.x; \r\n\t\tres.M[7] = v.y; \t\tres.M[11] = v.z; \r\n\t\treturn res; \r\n\t}",
"function buildLayout(mode) {\n if (mode === \"Portuguese\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/portugal.png\" alt=\"Portugal\"> <br> Portuguese</p>';\n } else if (mode === \"Swedish\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/sweden.png\" alt=\"Sweden\"> <br> Swedish</p>';\n } else if (mode === \"French\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/france.png\" alt=\"France\"> <br>French</p>';\n } else if (mode === \"German\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/germany.png\" alt=\"Germany\"> <br> German</p>';\n } else if (mode === \"Random\") {\n document.getElementById(\"language\").innerHTML = '<p><img src=\"assets/images/globe.png\" alt=\"world\"> <br> Random</p>';\n }\n fetchWords();\n}",
"static mxVMult(v,m) {\r\n\t\tvar res = new mVec3(); \r\n\t\tres.x = (v.x * m.M[0]) + (v.y * m.M[4]) + (v.z * m.M[8]) + m.M[12];\r\n\t\tres.y = (v.x * m.M[1]) + (v.y * m.M[5]) + (v.z * m.M[9]) + m.M[13];\r\n\t\tres.z = (v.x * m.M[2]) + (v.y * m.M[6]) + (v.z * m.M[10]) + m.M[14];\r\n\t\treturn res; \r\n\t}",
"function updateLanguageToKorean() {\n localStorage.setItem('lang', 'ko');\n document.title = $('#title-ko').val();\n $('.navbar__language--english').removeClass('language--active');\n $('.navbar__language--korean').addClass('language--active');\n $('[data-lang=\"en\"]').addClass('hidden');\n $('[data-lang=\"ko\"]').removeClass('hidden');\n}",
"function getLanguage(){\n\tvar lang=document.getElementById(\"language\").value;\n\tswitch(lang){\n\t\tcase \"C\":\n\t\t\tlang=1;\n\t\t\tbreak;\n\t\tcase \"C++\":\n\t\t\tlang=2;\n\t\t\tbreak;\n\t\tcase \"Java\":\n\t\t\tlang=3;\n\t\t\tbreak;\n\t\tcase \"Python\":\n\t\t\tlang=5;\n\t\t\tbreak;\n\t}\n\treturn lang;\n}",
"function clearLanguages() {\n\t\tlangs = [];\n\t}",
"function toJalali() {\n\n const DATE_REGEX = /^((19)\\d{2}|(2)\\d{3})-(([1-9])|((1)[0-2]))-([1-9]|[1-2][0-9]|(3)[0-1])$/;\n\n if (DATE_REGEX.test(mDate)) {\n\n let dt = mDate.split('-');\n let ld;\n\n let mYear = parseInt(dt[0]);\n let mMonth = parseInt(dt[1]);\n let mDay = parseInt(dt[2]);\n\n let buf1 = [12];\n let buf2 = [12];\n\n buf1[0] = 0;\n buf1[1] = 31;\n buf1[2] = 59;\n buf1[3] = 90;\n buf1[4] = 120;\n buf1[5] = 151;\n buf1[6] = 181;\n buf1[7] = 212;\n buf1[8] = 243;\n buf1[9] = 273;\n buf1[10] = 304;\n buf1[11] = 334;\n\n buf2[0] = 0;\n buf2[1] = 31;\n buf2[2] = 60;\n buf2[3] = 91;\n buf2[4] = 121;\n buf2[5] = 152;\n buf2[6] = 182;\n buf2[7] = 213;\n buf2[8] = 244;\n buf2[9] = 274;\n buf2[10] = 305;\n buf2[11] = 335;\n\n if ((mYear % 4) !== 0) {\n day = buf1[mMonth - 1] + mDay;\n\n if (day > 79) {\n day = day - 79;\n if (day <= 186) {\n switch (day % 31) {\n case 0:\n month = day / 31;\n day = 31;\n break;\n default:\n month = (day / 31) + 1;\n day = (day % 31);\n break;\n }\n year = mYear - 621;\n } else {\n day = day - 186;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 6;\n day = 30;\n break;\n default:\n month = (day / 30) + 7;\n day = (day % 30);\n break;\n }\n year = mYear - 621;\n }\n } else {\n if ((mYear > 1996) && (mYear % 4) === 1) {\n ld = 11;\n } else {\n ld = 10;\n }\n day = day + ld;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 9;\n day = 30;\n break;\n default:\n month = (day / 30) + 10;\n day = (day % 30);\n break;\n }\n year = mYear - 622;\n }\n } else {\n day = buf2[mMonth - 1] + mDay;\n\n if (mYear >= 1996) {\n ld = 79;\n } else {\n ld = 80;\n }\n if (day > ld) {\n day = day - ld;\n\n if (day <= 186) {\n switch (day % 31) {\n case 0:\n month = (day / 31);\n day = 31;\n break;\n default:\n month = (day / 31) + 1;\n day = (day % 31);\n break;\n }\n year = mYear - 621;\n } else {\n day = day - 186;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 6;\n day = 30;\n break;\n default:\n month = (day / 30) + 7;\n day = (day % 30);\n break;\n }\n year = mYear - 621;\n }\n } else {\n day = day + 10;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 9;\n day = 30;\n break;\n default:\n month = (day / 30) + 10;\n day = (day % 30);\n break;\n }\n year = mYear - 622;\n }\n\n }\n\n return year.toString() + \"-\" + Math.floor(month).toString() + \"-\" + day.toString();\n }\n}",
"function setLanguageES() {\n\t\n\tCookies.remove(cookieLanguageEN, {domain: hostRootDomain});\n\tCookies.set(cookieLanguageES, valueLanguageES, {expires: 28, domain: hostRootDomain});\n\n\t// window.location.href = urlES + currentURLPath;\n\tcheckUI();\n\n}",
"function _getMonth(m) {\n\t\tif(mc.os.config.translations) {\n\t\t\treturn mc.os.config.translations.pc.settings.nodes['_constants'].months[m];\n\t\t} else {\n\t\t\treturn $MONTHS[m];\n\t\t}\n\t}",
"function vml(tag,attr){return createEl('<'+tag+' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"spin-vml\">',attr);}// No CSS transforms but VML support, add a CSS rule for VML elements:",
"function verificarVertical(){\r\n for(let f = 0 ; f < MAX_FILAS ; f++){\r\n if((matriz[f][0] == signoJugadorActual) && (matriz[f][1]==signoJugadorActual) && (matriz[f][2]==signoJugadorActual)){\r\n f = MAX_FILAS;\r\n estadoJuego = ESTADO_GANO;\r\n }\r\n }\r\n}",
"function setMenuLang(){\n \n // Browser basic settings\n var currentLang = \"lang_\"+getNavigatorLang();\n \n \n if(localStorage.myLang)\n {\n currentLang= \"lang_\"+localStorage.myLang;\n }\n\n //Menu setting\n \n var menu = document.querySelectorAll(\"ul.nav li a\");\n for(var i=0; i<menu.length; i++)\n {\n var data = menu[i].getAttribute(\"data-name\");\n menu[i].innerHTML= window[currentLang][data];\n }\n \n // Navbar title and header setting\n \n var getSelector = document.querySelector(\".navbar-header a\");\n \n var dataName = getSelector.getAttribute(\"data-title\");\n \n getSelector.innerHTML = window[currentLang][dataName];\n \n \n var getSelector = document.querySelector(\".starter-template h1\");\n \n var dataName = getSelector.getAttribute(\"header-title\");\n \n getSelector.innerHTML = window[currentLang][dataName]; \n}",
"loadMessageToUTF16String(folder, msgHdr, charset) {\n let str = this.loadMessageToString(folder, msgHdr, charset);\n let arr = new Uint8Array(Array.from(str, x => x.charCodeAt(0)));\n return new TextDecoder().decode(arr);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Puts a border on active slider's dot | function setCurrentDotActive($dot) {
$sliderDots.removeClass('active');
$dot.addClass('slider-dot active');
} | [
"drawSlider() {\n let c = color(255, 255, 255);\n fill(c);\n noStroke();\n rect(this.x, this.y + this.topPadding + this.lateralPadding, this.width, this.height, 1, 1, 1, 1);\n }",
"function f_refectSpEditBorder(){\n // set #sp-taginfo-border-width value.\n var bw = $('#sp-taginfo-border-width');\n var borderWidth = bw.val();\n if(borderWidth.length == 0){\n borderWidth = '1px';\n }\n bw.val(borderWidth);\n\n // set #sp-taginfo-border-color-input value.\n var bc = $('#sp-taginfo-border-color-input');\n var bcp = $('#sp-taginfo-border-color-picker');\n var borderColor = bcp.val().toUpperCase();\n bc.val(borderColor);\n\n // set .spEdit css\n var setCssBorder = '';\n setCssBorder += borderWidth;\n setCssBorder += ' ';\n setCssBorder += $('#sp-taginfo-border-style').val();\n setCssBorder += ' ';\n setCssBorder += borderColor;\n fdoc.find('.spEdit').css('border',setCssBorder);\n }",
"function DottedBorder(x, y, w, h){\n\tBorder.call(this, x, y, w, h);\n}",
"_carouselPointActiver() {\r\n const i = Math.ceil(this.currentSlide / this.slideItems);\r\n this.activePoint = i;\r\n this.cdr.markForCheck();\r\n }",
"function render_bottom_border() {\n context.setLineDash([5, 15]);\n\n context.lineWidth = 1;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(0, (canvas.height - 155));\n context.lineTo(canvas.width, (canvas.height - 155));\n context.stroke();\n }",
"get borderColor() {\n return brushToString(this.i.g5);\n }",
"function changeBorder(image, color){\n\tif (!blnN4){\n\t\timage.style.borderColor = color;\n\t\timage.style.borderWidth = 1;\n\t\timage.style.margin = 0;\n\t}\n\n}",
"function addBorder(){\n if(fgImg==null)\n alert(\"Image not loaded\");\n else{\n var height1 = borderOnImg.getHeight();\n var widhth1 = borderOnImg.getWidth();\n console.log(height1);\n for(var px of borderOnImg.values()){\n var count = px.getY();\n var count1 = px.getX();\n if(count<height1/13 || count>12*(height1/13) || count1<widhth1/13 || count1>12*(widhth1/13)){\n px.setRed(128);\n px.setGreen(0);\n px.setBlue(42);\n count++;\n }\n borderOnImg.drawTo(canvas);\n }\n }\n}",
"function renderCarouselDots() {\n\t\treturn (\n\t\t\t<S.CarouselDots>\n\t\t\t\t{items.map((_, index) => {\n\t\t\t\t\treturn <div key={index} className={`single-dot ${currentItemIndex === index ? \"active\" : \"\"}`}></div>;\n\t\t\t\t})}\n\t\t\t</S.CarouselDots>\n\t\t);\n\t}",
"function brightDot() {\n tickIndex = (tickIndex + 1) % 10;\n // all the dots are bright\n if(document.getElementById('bt' + tickIndex).style.opacity === '1') {\n // begin to blink dots\n loadState = 'blinking';\n }\n // bright this dot\n document.getElementById('bt' + tickIndex).style.opacity = '1';\n document.getElementById('dt' + tickIndex).style.opacity = '0';\n }",
"function sliderClick(slider, point) {\n\tif (insideBox([slider.x,slider.y,slider.x+slider.width,slider.y+slider.height], point)) {\n\t\tslider.active = !slider.active;\n\t\t//console.log(\"clicked\");\n\t\treturn true;\n\t}\n\telse {\n\t\tvar divX = slider.width*1/5;\n\t\tif (slider.active) {\n\t\t\tdivX = divX*3;\n\t\t}\n\t\tif (insideBox([slider.x+divX,slider.y-slider.height/3,slider.x+divX+slider.width*1.3/5, slider.y+slider.height*5/3], point)) {\n\t\t\tslider.active = !slider.active;\n\t\t\treturn true;\n\t\t}\n\t}\t\n\treturn false;\n}",
"function setActiveBulletClass() {\n for (var i = 0; i < bullets.length; i++) {\n if (slides[i].style['transform'] == 'translateX(0px)') {\n bullets[i].classList.add('active');\n }\n }\n }",
"function setThumbBorderEffect(objThumb, borderWidth, borderColor, noAnimation){\n\t\t\t\t\t\t\n\t\t\tif(!noAnimation)\n\t\t\t\tvar noAnimation = false;\n\t\t\t\n\t\t\tif(g_gallery.isFakeFullscreen())\n\t\t\t\tnoAnimation = true;\n\t\t\t\n\t\t\tvar objBorderOverlay = objThumb.children(\".ug-thumb-border-overlay\");\n\t\t\t\n\t\t\t//set the border to thumb and not to overlay if no border size transition\n\t\t\t/*\n\t\t\tif(g_options.thumb_border_width == g_options.thumb_over_border_width\n\t\t\t\t&& g_options.thumb_border_width == g_options.thumb_selected_border_width)\n\t\t\t\tobjBorderOverlay = objThumb;\n\t\t\t*/\n\t\t\t\n\t\t\tvar objCss = {};\n\t\t\t\n\t\t\tobjCss[\"border-width\"] = borderWidth + \"px\";\n\t\t\t\n\t\t\tif(borderWidth != 0)\n\t\t\t\tobjCss[\"border-color\"] = borderColor;\n\t\t\t\n\t\t\tif(noAnimation && noAnimation === true){\n\t\t\t\tobjBorderOverlay.css(objCss);\n\t\t\t\t\n\t\t\t\tif(borderWidth == 0)\n\t\t\t\t\tobjBorderOverlay.hide();\n\t\t\t\telse\n\t\t\t\t\tobjBorderOverlay.show();\n\t\t\t}\n\t\t\telse{\n\t\t\t\t\n\t\t\t\tif(borderWidth == 0)\n\t\t\t\t\tobjBorderOverlay.stop().fadeOut(g_options.thumb_transition_duration);\n\t\t\t\telse\n\t\t\t\t\tobjBorderOverlay.show().stop().fadeIn(g_options.thumb_transition_duration);\n\t\t\t\t\n\t\t\t\tanimateThumb(objBorderOverlay, objCss);\n\t\t\t}\n\t\t\n\t\t\t\n\t\t}",
"function activateNavDots(name,sectionIndex){if(options.navigation&&$(SECTION_NAV_SEL)[0]!=null){removeClass($(ACTIVE_SEL,$(SECTION_NAV_SEL)[0]),ACTIVE);if(name){addClass($('a[href=\"#'+name+'\"]',$(SECTION_NAV_SEL)[0]),ACTIVE);}else{addClass($('a',$('li',$(SECTION_NAV_SEL)[0])[sectionIndex]),ACTIVE);}}}",
"get showBorderLine() {\n\t\treturn this.nativeElement ? this.nativeElement.showBorderLine : undefined;\n\t}",
"function changeArrowIcon(){\n let prev = $(\".home-4 .gdz-slider-wrapper .prev\");\n let next = $(\".home-4 .gdz-slider-wrapper .next\");\n let newPrev = $('<svg width=\"25\" height=\"60\" viewBox=\"0 0 25 60\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M23.375 1.5L1.625 30L23.375 58.5\" stroke=\"#BEBEBE\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>');\n let newNext = $('<svg width=\"25\" height=\"60\" viewBox=\"0 0 25 60\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M1.625 58.5L23.375 30L1.625 1.5\" stroke=\"#BEBEBE\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>');\n prev.empty();\n prev.html(newPrev);\n next.empty();\n next.html(newNext);\n}",
"function drawOutline(){\n fill(125);\n stroke(125);\n index = buttonArr.indexOf(buttonVal2);\n rect(windowWidth/2 - 394 + 1920/42 * (index+1), windowHeight - 104, 39, 39, 4, 4) \n}",
"function showBorder(status) {\n if (status) {\n $element.append(groupIDView);\n } else {\n groupIDView.remove();\n }\n }",
"incGhostsDots() {\n if (this.inPen.length > 0) {\n this.inPen[0].increaseDots();\n this.checkDotLimit();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function takes an array of jQuery objects and shows/hides each according to whether their text equals the search params. | function searchList(searchArray, target) {
for(var i = 0; i < searchArray.length; i++) {
var current = $(searchArray[i]);
var possible = current.text().substring(0, target.length).toLowerCase();
if(target === '') { // Re-shows items if search input is cleared
current.show();
} else if(target === possible) {
current.show();
} else {
current.hide();
}
}
} | [
"function setup(array) {\n let searchInput = document.getElementById(\"search-field\");\n searchInput.addEventListener(\"input\", (event) => {\n let value = event.target.value.toLowerCase();\n let foundLists = array.filter((show) => {\n let toLowerCaseName = show.name.toLowerCase();\n let toLowerCaseSummary = show.summary.toLowerCase();\n\n return (\n toLowerCaseName.includes(value) || toLowerCaseSummary.includes(value)\n );\n });\n\n displayAllShows(foundLists);\n\n document.getElementById(\n \"results\"\n ).innerHTML = `Displaying ${foundLists.length} / ${array.length}`;\n\n\n });\n\n}",
"function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}",
"function searchVisibleResults(){\n target = $('.list .asked');\n target = target.filter(function () {\n return $(this).css('visibility') == 'visible'\n });\n target = target.filter(function () {\n return $(this).closest('.tldResults').css('display') != 'none'\n });\n return target;\n}",
"function filterNames() {\n document.getElementsByClassName(\"pagination\")[0].innerHTML = ' '; \n let filterValue = document.getElementById('input').value.toUpperCase(); \n let ul = document.getElementById('names'); \n let li = ul.querySelectorAll('li.student-item'); \n const searchResults = []; \n for(let i = 0; i < li.length; i++) {\n li[i].style.display = 'none'; \n let h3 = li[i].getElementsByTagName('h3')[0]; \n \n if (h3.innerHTML.toUpperCase().includes(filterValue)) { \n searchResults.push(li[i]); \n li[i].style.display = '' \n } \n \n if(searchResults.length === 0) {\n noNamesDiv.style.display = '' \n } else {\n noNamesDiv.style.display = 'none' \n }\n \n } \n showPage(searchResults,1); \n appendPageLinks(searchResults); \n}",
"function filterDataSetItems() {\n // Declare variables\n var input, filter, ul, li, a, i;\n input = document.getElementById('searchFilter');\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"data-set-list-ul\");\n li = ul.getElementsByClassName('data-set-item');\n // Loop through all list items, and hide those who don't match the search query\n for (i = 0; i < li.length; i++) {\n a = li[i];\n if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {\n li[i].style.display = \"\";\n } else {\n li[i].style.display = \"none\";\n }\n }\n}",
"function search_games() { \n\tvar searchTerm = document.getElementById('searchBar').value \n\t// To eliminte confusion between capital vs lowercase letters\n\tsearchTerm = searchTerm.toLowerCase(); \n\n\t// Gets elements by class name\n\tvar gameList = document.getElementsByClassName('games'); \n\t\n\t// Loops through the list of games search each list item for the searchTerm and either displaying it or not\n\tfor (i = 0; i < gameList.length; i++) { \n\t\tif (!gameList[i].innerHTML.toLowerCase().includes(searchTerm)) { \n\t\t\t// Does not display the game list item if it does not include the searchTerm\n\t\t\tgameList[i].style.display=\"none\"; \n\t\t} \n\t\telse { \n\t\t\t// Displays the game list item as an inline style\n\t\t\tgamelist[i].style.display=\"inline\";\t\t\t\t \n\t\t} \n\t} \n}",
"function searchForShow(elem) {\n const allShows = getAllShows();\n let searchString = elem.target.value.toLowerCase();\n let filteredShows = allShows.filter((episode) => {\n return (\n episode.name.toLowerCase().includes(searchString) ||\n episode.genres.join(\" \").toLowerCase().includes(searchString) || \n (episode.summary && episode.summary.toLowerCase().includes(searchString))\n );\n });\n container.innerHTML = \"\";\n makePageForShows(filteredShows);\n}",
"function searchArtists() {\n\tvar textbox = document.getElementById(\"searchbox-textbox\");\n\tvar listbox = document.getElementById(\"list-box\");\n\n\tvar nameSearched = textbox.value;\n\n\tfor (var i = 0; i < artistNames.length; i++) {\n\t\tif (!artistNames[i].includes(nameSearched)) {\n\t\t\tvar listItem = document.getElementById(artistNames[i]);\n\t\t\tlistItem.style.display = \"none\";\n\t\t}\n\t}\n}",
"function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}",
"function runSearch(){\n filteredObjects = [];\n let names = [];\n const searchValue = document.getElementById('search-input').value;\n for (let i = 0;i<objects.length;i++){\n let name = `${objects[i].name.first} ${objects[i].name.last}`\n name = name.toLowerCase();\n names.push(name);\n }\n\n for(let i = 0; i < names.length; i++){\n if(names[i].includes(searchValue)){\n filteredObjects.push(objects[i])\n }\n }\n \n generateGallery(filteredObjects);\n}",
"function minorFilter() {\n var input, filter, ul, li, a, i, txtValue, panel;\n input = document.getElementById(\"minorInput\");\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"MinorList\");\n li = ul.getElementsByClassName(\"accordion\");\n panel = ul.getElementsByClassName(\"panel\");\n \n for (i = 0; i < li.length; i++) {\n a = li[i].innerHTML.split(\",\")[0];\n txtValue = a;\n if (txtValue.toUpperCase().indexOf(filter) > -1) {\n li[i].style.display = \"\";\n panel[i].style.display = \"\";\n } else {\n li[i].style.display = \"none\";\n panel[i].style.display = \"none\";\n }\n }\n }",
"function filterStatus(status){\n\n $(\"#search\").val(\"\")\n $(\".scheme\").hide();\n $(\".ministry\").hide();\n $(\"#no-matches\").hide();\n\n $(\".scheme-status.\" + status).closest(\".scheme\").show();\n $(\".scheme-status.\" + status).closest(\".ministry\").show();\n\n if ($(\"#ministries-wrapper\").height() == 0) {\n $(\"#no-matches\").show();\n }\n\n}",
"function filterListing() {\n // Declare variables\n var input, filter, ul, li, a, i, txtValue;\n input = document.getElementById('searchFAQ');\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"listFAQ\");\n li = ul.getElementsByTagName('li');\n\n // Loop through and filter list to what is typed in search bar\n for (i = 0; i < li.length; i++) {\n a = li[i].getElementsByTagName(\"a\")[0];\n txtValue = a.textContent || a.innerText;\n if (txtValue.toUpperCase().indexOf(filter) > -1) {\n li[i].style.display = \"\";\n } else {\n li[i].style.display = \"none\";\n }\n }\n}",
"function filteredListOfToDos() {\n // Declare variables\n var input, filter, table, tr, td, i, txtValue;\n input = document.getElementById('filter');\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"filterlista\");\n tr = ul.getElementsByTagName('tr');\n \n // Loop through all list items, and hide those who don't match the search query\n for (i = 0; i < tr.length; i++) {\n td = tr[i].getElementsByTagName(\"td\")[nr];\n txtValue = td.textContent || td.innerText;\n if (txtValue.toUpperCase().indexOf(filter) > -1 && txtValue !== '') {\n tr[i].style.display = \"\";\n } \n else {\n tr[i].style.display = \"none\";\n }\n }\n}",
"function showCorrectStreamers() {\n var search = $('input').val();\n var re = new RegExp('^' + search, 'i');\n var status = $('.notch').parent().attr('id');\n for (var i = 0; i < streamers.length; i++) {\n var $streamer = $('#' + streamers[i]);\n if ($streamer.hasClass(status)) {\n $streamer.show();\n }\n if (!re.test(streamers[i])) {\n $streamer.hide();\n }\n }\n }",
"function filter() {\r\n $(\"input[name=filterBtn]\").click(function() {\r\n // Get form values\r\n let title = $(\"#title\").val();\r\n let pickedGenre = $(\"select[name='genreSelect'] option:selected\").val();\r\n\r\n // Clear current result space\r\n $(\"#filteredMovies\").html(\"\");\r\n\r\n // result flag\r\n var found = false;\r\n\r\n if (title == \"\" && pickedGenre != \"\") {\r\n movies.forEach(function(currObj) {\r\n if (currObj.genre == pickedGenre) {\r\n request(queryReview(currObj.title, queryNYTMovie), queryMovie(currObj.title, queryOMDb), currObj);\r\n found = true;\r\n }\r\n });\r\n } \r\n else { // Handles when title given, or no genre or title given\r\n const titleRegEx = new RegExp(\"^\" + title, \"i\");\r\n movies.forEach(function(currObj) {\r\n if (titleRegEx.test(currObj.title)) {\r\n request(queryReview(title, queryNYTMovie), queryMovie(title, queryOMDb), currObj);\r\n found = true;\r\n }\r\n });\r\n }\r\n ensureResults(found);\r\n // reveal results in modal\r\n modal.style.display = \"block\";\r\n });\r\n}",
"function filterActivities(term) {\n\n //Array.from converts the HTML collection into a Nodelist.This allows us to loop over the activities and grab the inner text. Then we match the input term to the activity if they do not match add the filtered class to the div to remove the activity but if they do not match remove the filtered class to show the activity \n Array.from(entries.children)\n .filter((activity) => !activity.textContent.includes(term))\n .forEach((activity) => {\n activity.classList.add('filtered')\n })\n \n Array.from(entries.children)\n .filter((activity) => activity.textContent.includes(term))\n .forEach((activity) => {\n activity.classList.remove('filtered')\n })\n}",
"function filterItems(e) {\n // grab text to filter/search\n let filterText = e.target.value.toLowerCase();\n\n // grab all the list items available\n let liAvailable = itemList.getElementsByTagName(\"li\");\n\n // convert the lis available to array\n Array.from(liAvailable).forEach(function (item) {\n // grabs the text content in the selected li\n let liText = item.firstChild.textContent;\n\n // checks if there is a match\n if (liText.toLowerCase().indexOf(filterText) != -1) {\n item.style.display = \"block\";\n } else {\n item.style.display = \"none\";\n }\n })\n }",
"function filterSongList(filterString) {\n $songList.each(function(index, element) {\n var $elem = $(element);\n var $songContainer = $(\"#\" + $elem.data(\"id\"));\n\n if ($elem.text().toLowerCase().indexOf(filterString.toLowerCase()) > -1) {\n $songContainer.removeClass(\"song-hidden\");\n } else {\n $songContainer.addClass(\"song-hidden\");\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a performer All new items needs to pass through this function | function createPerformer(obj) {
if (!obj._hash) {
console.log('No hash on obj, returning null');
return;
}
if (_performersHash[obj._hash]) {
console.log(obj, 'has already been seen');
return;
}
Utils.middleware(obj);
_performersHash[obj._hash] = obj;
obj.shared ? _performers.unshift(obj) : _performers.push(obj);
} | [
"get performer() {\n\t\treturn this.__performer;\n\t}",
"createLesson() {\n this.lessonService\n .createLesson(this.props.courseId, this.props.moduleId, this.lesson,\n () => {\n this.findAllLessonsForModule();\n });\n }",
"_fetchFromAPI() {\n // Generate new items\n let { indexedDb } = this;\n\n return indexedDb.add('item', [\n this._createItemPayload(),\n this._createItemPayload(),\n this._createItemPayload(),\n ]);\n }",
"createItem() {\n\t\tvar $li = $('<li>')\n\t\t$li.text(this.name)\n\t\tvar _this = this\n\t\t$li.on('click', function() {\n\t\t\tvar $page = _this.createPage()\n\t\t\tvar $view = $('#job-view')\n\t\t\t$view.empty()\n\t\t\t$view.append($page)\n\t\t})\n\t\treturn $li\n\t}",
"create_elevators() {\r\n for (let i = 0; i < this.nb_elevators; i++) {\r\n let elevator = new Elevator(i + 1, this.nb_floors);\r\n this.elevator_list.push(elevator);\r\n }\r\n }",
"function newToy(toy) {\n const toy_list = document.querySelector(\"#toy-collection\");\n const card = makeToyCard(toy);\n toy_list.appendChild(card);\n }",
"function makeBeerObject(apiBeer) {\n var beer = new Beer();\n beer.id = apiBeer.id;\n beer.name = apiBeer.name;\n beer.styleId = apiBeer.style.id;\n beer.styleName = apiBeer.style.name;\n beer.styleDescription = apiBeer.style.description;\n beer.categoryName = apiBeer.style.category.name;\n if (apiBeer.abv) { beer.abv = apiBeer.abv; } // check if provided\n if (apiBeer.ibu) { beer.ibu = apiBeer.ibu; } // check if provided\n beer.isOrganic = apiBeer.isOrganic;\n if (apiBeer.glass) { beer.glassName = apiBeer.glass.name; } // check if provided\n if (apiBeer.foodPairings) { beer.foodPairings = apiBeer.foodPairings; } // check if provided\n if (apiBeer.servingTemperature) { beer.servingTemperature = apiBeer.servingTemperature; } // check if provided\n if (apiBeer.year) { beer.year = apiBeer.year; } // check if provided\n if (apiBeer.labels) { // check if provided\n beer.imgLinkSmall = apiBeer.labels.icon;\n beer.imgLinkLarge = apiBeer.labels.large;\n }\n beer.price = ((Math.random() * (6 - 2 + 1)) + 2).toFixed(2); // random number between 20 and 2, with 2 decimals\n if (apiBeer.description) { beer.description = apiBeer.description; } // check if provided\n beerList.push(beer);\n}",
"function walmartSuggestionInstantiation(){\n const walmartAPI = new WalmartSuggestionInformation(); // make a new instance from the WalmartSuggestionInformation constructor\n walmartAPI.getItemInformation(); // use the getItemInformation method to make the network request for the information.\n}",
"function workOrderCreate() {\n // Define the data object and include the needed parameters.\n // Make the Create API call and assign a callback function.\n}",
"function fillPerformer(data){\n for(var i = 0; i < data[\"children\"].length; i++){\n var current = data[\"children\"][i];\n current[\"name\"] = gPerformer[current[\"reference\"]].name;\n current[\"specialty\"] = gPerformer[current[\"reference\"]].specialty;\n }\n}",
"function initializeNewItem(item) {\n item.assignedResource = resource1;\n console.log('A new item was created.');\n }",
"async function createManager() {\n const newManager = await new Manager();\n await newManager.getOfficeNumber();\n await manager.push(newManager);\n await generatorQs();\n}",
"function TruckFactory() {}",
"function addBeerToCollection() {\n _store2.default.dispatch((0, _beerActions.addBeer)());\n return;\n}",
"function createNewRunButton(resort) {\n let btn = document.createElement('button');\n btn.className = 'btn btn-info';\n btn.innerHTML = 'Create';\n btn.onclick = () => {\n resort.runs.push(new Run(getValue(`name-input-${resort.id}`), getValue(`difficulty-input-${resort.id}`)))\n drawDOM();\n };\n return btn;\n}",
"newRecord() {}",
"submit() {\n const { currentItem, addItem, inputMode, clearCurrentItem, setItemShowInput, editItem } = this.props\n if (inputMode === 'add') {\n addItem(currentItem);\n } else {\n editItem(currentItem)\n }\n clearCurrentItem();\n setItemShowInput(false);\n }",
"function WoodenToysFactory(){}",
"basketAdd(equipment) {\n equipmentBasket.push(equipment);\n this.specify();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does the message have options? | function hasOptions() {
if (typeof currMsg.opt == 'undefined' || currMsg.opt.length == 0) {
return false;
}
return true;
} | [
"function isMessageValid() {\n return $message.val().length > 0;\n }",
"function isTheMessageACommand(message) {\n if (message.content.toLowerCase().startsWith('!clear')) {\n clearMessages(message);\n }\n if (message.content.toLowerCase().startsWith('!theelders')) {\n firstUsers(message);\n }\n if (message.content.toLowerCase().startsWith('!noavatar')) {\n usersWithoutAvatar(message);\n }\n // WIP\n if (message.content.toLowerCase().startsWith('!patrulla')) {\n registerWarning(message);\n }\n}",
"get isReplyRequired() {\n return false;\n }",
"isAdding() {\n return Template.instance().uiState.get(\"addChat\") == CANCEL_TXT;\n }",
"function validateMessage(formname)\n{\n\t\n if(validateForm(formname,'frmSendToIds', 'Select Users', 'R', 'frmMessageType', 'Message Type', 'R', 'frmMessageSubject', 'message Subject', 'R'))\n {\t\n\t\t\n\t\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function isLineOverlong(text) {\n\t\tvar checktext;\n\t\tif (text.indexOf(\"\\n\") != -1) { // Multi-line message\n\t\t\tvar lines = text.split(\"\\n\");\n\t\t\tif (lines.length > MAX_MULTILINES)\n\t\t\t\treturn true;\n\t\t\tfor (var i = 0; i < lines.length; i++) {\n\t\t\t\tif (utilsModule.countUtf8Bytes(lines[i]) > MAX_BYTES_PER_MESSAGE)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (text.startsWith(\"//\")) // Message beginning with slash\n\t\t\tchecktext = text.substring(1);\n\t\telse if (!text.startsWith(\"/\")) // Ordinary message\n\t\t\tchecktext = text;\n\t\telse { // Slash-command\n\t\t\tvar parts = text.split(\" \");\n\t\t\tvar cmd = parts[0].toLowerCase();\n\t\t\tif ((cmd == \"/kick\" || cmd == \"/msg\") && parts.length >= 3)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 2);\n\t\t\telse if ((cmd == \"/me\" || cmd == \"/topic\") && parts.length >= 2)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 1);\n\t\t\telse\n\t\t\t\tchecktext = text;\n\t\t}\n\t\treturn utilsModule.countUtf8Bytes(checktext) > MAX_BYTES_PER_MESSAGE;\n\t}",
"function isMessage(val) {\n if (isObject(val)) {\n // all messages must have the `type` prop\n if (!hasOwnStringProperty(val, 'type')) {\n return false;\n }\n // validate other properties depending on the `type`\n switch (val.type) {\n case MessageType.ConnectionInit:\n // the connection init message can have optional payload object\n return (!hasOwnProperty(val, 'payload') ||\n val.payload === undefined ||\n isObject(val.payload));\n case MessageType.ConnectionAck:\n // the connection ack message can have optional payload object too\n return (!hasOwnProperty(val, 'payload') ||\n val.payload === undefined ||\n isObject(val.payload));\n case MessageType.Subscribe:\n return (hasOwnStringProperty(val, 'id') &&\n hasOwnObjectProperty(val, 'payload') &&\n (!hasOwnProperty(val.payload, 'operationName') ||\n val.payload.operationName === undefined ||\n val.payload.operationName === null ||\n typeof val.payload.operationName === 'string') &&\n hasOwnStringProperty(val.payload, 'query') &&\n (!hasOwnProperty(val.payload, 'variables') ||\n val.payload.variables === undefined ||\n val.payload.variables === null ||\n hasOwnObjectProperty(val.payload, 'variables')));\n case MessageType.Next:\n return (hasOwnStringProperty(val, 'id') &&\n hasOwnObjectProperty(val, 'payload'));\n case MessageType.Error:\n return hasOwnStringProperty(val, 'id') && areGraphQLErrors(val.payload);\n case MessageType.Complete:\n return hasOwnStringProperty(val, 'id');\n default:\n return false;\n }\n }\n return false;\n }",
"isMessage(this_frame) {\n return (this_frame.headers !== null && reallyDefined(this_frame.headers['message-id']));\n }",
"function isnotsu() {\nif(msguser !== superuserid ) {\nconst plaintext = \"<:warn_3:498277726604754946> Sorry, you don't have permissions to use this!\"\nconst embed = new RichEmbed() \n//.setTitle('Title') \n.setColor(0xCC0000) \n.setDescription('only ' + superuser + ' may use this command')\n//.setAuthor(\"Header\")\n.setFooter(\"@\" + msgauthor)\n//.addField(\"Field\");\nmessage.channel.send(plaintext, embed);\n\n\t/*\nreturn message.reply(\"Sorry, you don't have permissions to use this!\")\n*/\nreturn true\n}\nelse\nreturn false;\n}",
"sendMessages () {\n return false\n }",
"function anySelected(act) {\n if (YAHOO.alpine.current.selected <= 0){\n panelAlert('No messages selected to ' + act + '.<p>Select one or more messages by checking the box on the line of each desired message.');\n return false;\n }\n\n return true;\n}",
"async isAllowedChannel(message) {\n\t\treturn true;\n\t}",
"function displayType(msgType, args) {\n let display = true;\n if (args.type && args.type.toLowerCase() !== msgType.toLowerCase()) {\n display = false;\n }\n\n return display;\n}",
"selectMessageComingUp() {\n this._aboutToSelectMessage = true;\n }",
"function validateMessageField(reporting = true) {\n var messageField = $(\"#message\");\n if (!hasText(messageField)) {\n console.log(\"message error\");\n setError(messageField, true);\n if (reporting) {\n displayError(\"What, cat got your tongue?\");\n }\n return false;\n } else {\n setError(messageField, false);\n displayError(\"\");\n return true;\n }\n}",
"validateMessage (message) {\n\t\tif (message.post.$set) { return false; }\n\t\tAssert.ifError(this.shouldFail);\t// if this test should fail, we should not have recieved a message\n\t\tAssert(message.requestId, 'received message has no requestId');\n\t\tlet post = message.post;\n\t\tAssert.strictEqual(post.teamId, this.team.id, 'incorrect team ID');\n\t\tAssert.strictEqual(post.streamId, this.teamStream.id, 'incorrect stream ID');\n\t\tAssert.strictEqual(post.parentPostId, this.parentPost.id, 'incorrect parent post ID');\n\t\tAssert.strictEqual(post.text, this.expectedText, 'text does not match');\n\t\tAssert.strictEqual(post.creatorId, this.userData[0].user.id, 'creatorId is not the expected user');\n\t\treturn true;\n\t}",
"checkUnknownOptions() {\n const { rawOptions, globalCommand } = this.cli;\n if (!this.config.allowUnknownOptions) {\n for (const name of Object.keys(rawOptions)) {\n if (name !== '--' &&\n !this.hasOption(name) &&\n !globalCommand.hasOption(name)) {\n console.error(`error: Unknown option \\`${name.length > 1 ? `--${name}` : `-${name}`}\\``);\n process.exit(1);\n }\n }\n }\n }",
"static vsamValidateOptions(options) {\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options, ZosFiles_messages_1.ZosFilesMessages.missingFilesCreateOptions.message);\n /* If our caller does not supply these options, we supply default values for them,\n * so they should exist at this point.\n */\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.dsorg, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"dsorg\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.alcunit, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"alcunit\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.primary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"primary\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.secondary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"secondary\");\n // validate specific options\n for (const option in options) {\n if (options.hasOwnProperty(option)) {\n switch (option) {\n case \"dsorg\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_DSORG_CHOICES.includes(options.dsorg.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidDsorgOption.message + options.dsorg\n });\n }\n break;\n case \"alcunit\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_ALCUNIT_CHOICES.includes(options.alcunit.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidAlcunitOption.message + options.alcunit\n });\n }\n break;\n case \"primary\":\n case \"secondary\":\n // Validate maximum allocation quantity\n if (options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_ALLOC_QUANTITY) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.maximumAllocationQuantityExceeded.message + \" \" +\n ZosFiles_messages_1.ZosFilesMessages.commonFor.message + \" '\" + option + \"' \" + ZosFiles_messages_1.ZosFilesMessages.commonWithValue.message +\n \" = \" + options[option] + \".\"\n });\n }\n break;\n case \"retainFor\":\n if (options[option] < ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS ||\n options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS) {\n throw new imperative_1.ImperativeError({\n msg: imperative_1.TextUtils.formatMessage(ZosFiles_messages_1.ZosFilesMessages.valueOutOfBounds.message, {\n optionName: option,\n value: options[option],\n minValue: ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS,\n maxValue: ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS\n })\n });\n }\n break;\n case \"retainTo\":\n case \"volumes\":\n case \"storclass\":\n case \"mgntclass\":\n case \"dataclass\":\n case \"responseTimeout\":\n // no validation at this time\n break;\n default:\n throw new imperative_1.ImperativeError({ msg: ZosFiles_messages_1.ZosFilesMessages.invalidFilesCreateOption.message + option });\n } // end switch\n }\n } // end for\n }",
"function findRejectionOptions (option) {\n if (option.code === 'SRJ' || option.code === 'LRD') {\n return true;\n } else {\n return false;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put lyric in the tablature | _setLyric(x, lyric) {
var block, text;
block = this.model.rect(x - 5, 84, 700, 16, 9, 9);
block.attr({
fill: this.notes_color_map[lyric[0]]
});
return text = this.model.text(x, 97, lyric).attr({
"font-size": 12,
"font-family": "Arial"
});
} | [
"function displaySimpleLyric(data,songArtist,songName)\n{\n if(data.lyrics==undefined){\n alert(\"Sorry no lyric found\");\n document.getElementById('lyricSimple').innerHTML=\"<h1></h1>\";\n }\n else{\n const lyric = data.lyrics.replace(/(\\r\\n|\\r|\\n)/gi,'<br>');\n const string =`<h1 class='text-success mb-4'>${songArtist} - ${songName}</h1>\n <h5 id='fulll-lyric' class='lyric text-white'>\n ${lyric}\n \n </h5>`\n document.getElementById('lyricSimple').innerHTML=string;\n } \n \n}",
"function displayLyric(data,songArtist,songName){\n \n if(data.lyrics==undefined){\n document.getElementById('lyricFancy').innerHTML=\"<h1>SORRY! NOT FOUND</h1>\";\n alert(\"Sorry no lyric found\"); \n }\n\n else{\n const lyric = data.lyrics.replace(/(\\r\\n|\\r|\\n)/gi,'<br>');\n \n const string =`<h1 class='text-success mb-4'>${songArtist} - ${songName}</h1>\n <h5 id='fulll-lyric' class='lyric text-white'>\n ${lyric}\n \n </h5>`\n document.getElementById('lyricFancy').innerHTML=string;\n } \n}",
"function manage_labyrinth() {\n labyrinth.set_drawing_position()\n labyrinth.detect_input()\n save_mouse_position()\n labyrinth.display_background()\n labyrinth.display_arrows()\n labyrinth.display_grid()\n labyrinth.display_finish()\n labyrinth.display_player()\n labyrinth.display_number()\n labyrinth.display_led()\n labyrinth.clear_drawing_position()\n}",
"createTable(x, y, z) {\n\t\t'use strict';\n\t\tvar table = new Table(x, y, z);\n\n\t\ttable.createTableLeg(-35, 30, -50);\n\t\ttable.createTableLeg(-35, 30, 50);\n\t\ttable.createTableLeg(35, 30, -50);\n\t\ttable.createTableLeg(35, 30, 50);\n\t\ttable.createTableTop();\n\t\tthis.scene.add(table);\n\t\treturn table;\n\t}",
"function displayNarrative(data){\n if(data.route){\n var legs = data.route.legs, html = '', i = 0, j = 0, trek, maneuver;\n html += '<table><tbody>';\n\n for (; i < legs.length; i++) {\n for (j = 0; j < legs[i].maneuvers.length; j++) {\n maneuver = legs[i].maneuvers[j];\n html += '<tr>';\n html += '<td>';\n\n if (maneuver.iconUrl) {\n html += '<img src=\"' + maneuver.iconUrl + '\"> ';\n }\n\n for (k = 0; k < maneuver.signs.length; k++) {\n var sign = maneuver.signs[k];\n if (sign && sign.url) {\n html += '<img src=\"' + sign.url + '\"> ';\n }\n }\n html += '</td><td>' + maneuver.narrative + '</td>';\n html += '</tr>';\n }\n }\n html += '</tbody></table>';\n document.getElementById('narrative').innerHTML = html;\n }\n }",
"function addLyricsToPage(lyrics, title) {\n var str = consolidateHtml(lyrics);\n //console.log(str);\n var links = addOnClicks(str);\n //console.log(links);\n var output = \"<div class='lyric-title-container'>\" + \n \"<h2 class='lyric-title'>\" + title + \"</h2>\" + \"</div>\";\n links[0].id = \"lyricsContainer\";\n for(i = 0; i < links.length; i++) {\n output += links[i].outerHTML;\n }\n output = output;\n document.getElementById(\"watch-discussion\").innerHTML = \"\";\n document.getElementById(\"watch-discussion\").innerHTML = output;\n setUpListeners();\n linkIds = [];\n}",
"function ADLTOC()\r\n{\r\n}",
"function addHeads(){\r\n\tvar trHead = document.createElement(\"tr\");\r\n\tvar thDate = document.createElement(\"th\");\r\n\tvar thMood = document.createElement(\"th\");\r\n\tthDate.appendChild(document.createTextNode(\"Date\"));\r\n\tthMood.appendChild(document.createTextNode(\"Mood\"));\r\n\ttrHead.appendChild(thDate);\r\n\ttrHead.appendChild(thMood);\r\n\tdocument.getElementById(\"tabMood\").appendChild(trHead);\r\n}",
"function addLocationRow(ob, trow)\n{\n $(\"<td>\")\n\t .text(new Date(ob.start).toLocaleString() +\" to \"+ new Date(ob.end).toLocaleString())\n\t .appendTo(trow);\n $(\"<td>\")\n\t .text(ob.cluster_semantic)\n\t .appendTo(trow);\n $(\"<td>\")\n\t .text(ob.cluster)\n\t .appendTo(trow);\n $(\"<td>\")\n\t .text(ob.count)\n\t .appendTo(trow);\n $(\"<td>\")\n\t .text((ob.speech * 100 / ob.count).toFixed(2))\n\t .appendTo(trow);\n $(\"<td>\")\n\t .text((ob.nonspeech * 100 / ob.count).toFixed(2))\n\t .appendTo(trow);\n $(\"<td>\")\n\t .text((ob.pending * 100 / ob.count).toFixed(2))\n\t .appendTo(trow);\n}",
"function writeGenreArtistRow(artist) {\n\t$(\"#artist-table>tbody\").append(\n\t\t \"<tr>\"\n\t\t+ \"<td><a href=\\\"javascript:getDirectChildren(\\'\"\n\t\t+ jsEscape(artist.ID)\n\t \t+ \"\\', onGetGenreArtist)\\\">\"\n\t\t+ artist.Title + \"</a></td>\"\n\t\t+ \"</tr>\");\n}",
"function createLives() {\r\n textStyle = { font: '15px Arial', fill: '#FFFFFF' };\r\n livesHUD = this.add.text(this.world.width-10, 10, 'Lives: ' +lives, textStyle);\r\n livesHUD.anchor.set(1,0);\r\n\r\n}",
"function createDescCell(data) {\n var tabCellTxt = document.createTextNode(data.description);\n var anchor = document.createElement('a');\n anchor.href = data.url;\n anchor.appendChild(tabCellTxt);\n var tabCell = document.createElement('td');\n tabCell.appendChild(anchor);\n return tabCell;\n}",
"function addTable(r, c) {\n var b = idoc.body || idoc.find('body')[0];\n $(b).html(table.html(r,c))\n }",
"function appendTerm( item )\n{\n\t// Add a new row to the table below that's already been added\n\t// Avoid the heading row\n\tvar newRow = document.getElementById( \"termTable\" ).insertRow( 1 );\n\n\t// Add two cells to this new row\n \tvar termCell = newRow.insertCell( 0 );\n \tvar defCell = newRow.insertCell( 1 );\n\n \t// Give the new cells their IDs\n \ttermCell.setAttribute( \"class\", \"term\" + item.cat );\n \tdefCell.setAttribute( \"class\", \"definition\" );\n\n \ttermCell.innerHTML = item.term;\n \tdefCell.innerHTML = item.definition;\n}",
"function setPlaceTable(response){\n\t\t\tvar a=response.tagged_places.data;\n\t\t\tif(response.tagged_places==null||response.tagged_places==undefined||!response.hasOwnProperty('tagged_places'))\n\t\t\t{\n\t\t\t\t$(\".table-place\").append('Nothing to show');\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\tfor(i in a)\n\t\t\t\t{\n\t\t\t\t\t$(\".table-place\").append('<tr><td class=\"table-bi\" >'+a[i].place.name+\"</td></tr>\");\n\t\t\t\t\tconsole.log(a[i].place.name);\n\t\t\t\t\tconsole.log(a.length);\n\t\t\t\t\tconsole.log(response.tagged_places);\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"render() {\n const { skillData, settings } = this.state;\n \n return (\n <div>\n {\n skillData.map((skill, index) => \n <div key={index}>\n <SkillInfo \n skillData={skill}\n name={skill.name}\n properties={{}}\n shortDesc={skill.shortDesc}\n maxLevel={skill.maxLevel}\n animationSetting={settings.animations}/>\n </div>\n )\n }\n <a href=\"#skill\"><span className=\"jump-button-tabs\"/></a>\n </div>\n );\n }",
"function writeGenreTrackRow(track) {\n\t$(\"#track-table>tbody\").append(\n\t\t \"<tr>\"\n\t\t+ \"<td>\" + track.Title + \"</td>\"\n\t\t+ \"</tr>\");\n}",
"function loadScoreCardTable(firstLevelClassCategory){\n\t\tvar li;\n\t\tconsole.log(\"=========== Inside loadScoreCardTable =========\");\n\t\tfor(var i in firstLevelClassCategory) {\n\t\t\tli = \"\";\n\t\t\tli += '<li class=\"\" id=\"'+firstLevelClassCategory[i]+'\" onclick=\"open_table(this.id)\">'+\n\t\t\t\t\t\t'<a href=\"#\">'+firstLevelClassCategory[i]+'</a>'+\n\t\t\t\t\t\t'<span class=\"devider\">'+\n\t\t\t\t\t\t'</span> <span id=\"total_weighted_score_'+firstLevelClassCategory[i]+'\"> </span>'+\n\t\t\t\t\t'</li>';\n\t\t\t//document.getElementById(\"buttons-middle\").innerHTML += li;\n\t\t\t$('#buttons-middle').append(li);\n\t \n\t\t}\n\t}",
"function set_one_row(tguri, which){\r\n\t\t\tvar tr = Util.dom.element(\"tr\"),\r\n\t\t\ttd1 = Util.dom.element(\"td\", \"(\" + which + \" found)\"),\r\n\t\t\ttd2 = Util.dom.element(\"td\"),\r\n\t\t\tanc = Util.dom.element(\"a\", tguri);\r\n\t\t\tanc.href = tguri;\r\n\t\t\tanc.className = \"uri\";\r\n\t\t\tanc.innerHTML = anc.innerHTML.replace(\"/chname/\", \"/<b>chname</b>/\");\r\n\t\t\ttd2.appendChild(anc);\r\n\t\t\ttr.appendChild(td1);\r\n\t\t\ttr.appendChild(td2);\r\n\t\t\treturn tr;\r\n\t\t}",
"function YardsToMetres () {\r\n\t\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Roll a random background pic | function bgRoll() {
const bgm = ['../../resources/SBISL02.png','../../resources/MTLSL04.png','../../resources/OSCSL08.png','../../resources/PGTSL04.png','../../resources/PTWSL02.png','../../resources/STCSL01.png'];
$('body').css({
'background-image' : 'url('+ bgm[Math.floor(Math.random() * bgm.length)] + ')',
});
} | [
"function randomBG(){\n var BG = 0;\n BG = Math.floor(Math.random() * 3 ) + 1; // generates a random background from the 3 background images. \n // console.log(BG);\n if (BG === 1){\n return 'background1.jpg' // if the random number of 1 is chosen the background.jpg will be chosen\n } else if (BG === 2){ // if the background.jpg isnt the chosen one it will go to the next option being background2.jpg\n return 'background2.jpg' // if the random number of 2 is chosen the background2.jpg will be chosen\n } else{ // if the background2.jpg isn't the chosen one it will go to the next option being background3.jpg\n return 'background3.webp' // if the random number of 3 is chosen the background3.jpg will be chosen\n }\n \n}",
"function generateDefaultShibeImgs() {\n const shibeImg = document.getElementsByClassName(\"img-bk\")\n\n for(let i = 0; i < shibeImg.length; i++) {\n shibeImg[i].style.backgroundImage = `url(${shibeImgs[Math.floor(\n Math.random() * shibeImgs.length)]}\n )`\n }\n}",
"function randomColorGenerator() {\n\t\treturn Math.floor(Math.random() * backgroundColors.length);\n}",
"function randomColour() {\r\n pattern.push(colours[Math.floor(Math.random() * 4)]);\r\n animations(pattern);\r\n levelAndScoreCount();\r\n\r\n}",
"function randomBackground(){\n let chosenBg = Math.round(Math.random()*2);\n let bg = $('.blur-container');\n let bgClasses = [\"cat-bg\", \"dog-bg\", \"puppy-bg\"];\n if(chosenBg >= bgClasses.length || chosenBg < 0){\n bg.css('background-color', '#E2E1E0');\n }\n bg.addClass(bgClasses[chosenBg]);\n}",
"function randomAvatar() {\n currentColor = floor(random(0, COLORS.length));\n currentAvatar = floor(random(0, avatars.length));\n}",
"function randomBackground(value) {\n color =`rgb(${value()}, ${value()}, ${value()})`;\n return color\n }",
"function randomBackgroundColor() {\n var currentColor = document.body.style.backgroundColor;\n do { document.body.style.backgroundColor = \"#\"+((1<<24)*Math.random()|0).toString(16); } while (document.body.style.backgroundColor === currentColor);\n}",
"function rndColor() {\n var iRed = Math.floor((Math.random() * 255) + 1);\n var iGreen = Math.floor((Math.random() * 255) + 1);\n var iBlue = Math.floor((Math.random() * 255) + 1);\n\n $(\"#red\").slider(\"value\", iRed);\n $(\"#green\").slider(\"value\", iGreen);\n $(\"#blue\").slider(\"value\", iBlue);\n }",
"function assignMole() {\n\tvar circle = circles[Math.floor(Math.random() * circles.length)];\n\tcircle.style.backgroundImage = \"url(mole.png)\";\n\tcircle.hasMole = true;\n}",
"function rollDice(){\n var randomNum = getRandomInt(1,6);\n setDice(randomNum);\n // moveCoin(randomNum);\n }",
"function startDice() {\n var randomNum1 = Math.floor(Math.random() * dicePics.length);\n document.querySelector(\"img.img1\").src = dicePics[randomNum1];\n console.log(randomNum1);\n\n var randomNum2 = Math.floor(Math.random() * dicePics.length);\n document.querySelector(\"img.img2\").src = dicePics[randomNum2];\n console.log(randomNum2);\n}",
"function updateBackground() {\n var whichBackgroundIndex = (currentStep / bgChangeStepInterval) - 1;\n // print(\"whichBackgroundIndex: \"+whichBackgroundIndex);\n bg = loadImage(\"images/\" + bgImageNames[whichBackgroundIndex]);\n}",
"function createBackground() {\n var background = this.add.image(256, 256, \"background\");\n background.setScale(2.2, 2.5);\n}",
"function randomColorPicker(){\n\n\t\t\tvar randomColor = randomColorGenerator();\n\n\t\t\tif(randomColor !== lastColor){\n\t\t\tdocument.getElementById('body').style.background = backgroundColors[randomColor];\n\t\t\tlastColor = randomColor;\n\t\t} else {\n\t\t\trandomColorPicker();\n\t\t}\n}",
"function selBackground(name) {\n if (name === 'Death Star') return DeathStarBackgrounds[Math.floor(Math.random()*DeathStarBackgrounds.length)];\n else if (name === 'Star Destroyer') return starDestroyersBackgrounds[Math.floor(Math.random()*starDestroyersBackgrounds.length)];\n else if (name === 'Millennium Falcon') return MilleniumFalconBackgrounds[Math.floor(Math.random()*MilleniumFalconBackgrounds.length)];\n else if (name === 'X-wing') return XWingBackgrounds[Math.floor(Math.random()*XWingBackgrounds.length)];\n else if (name === 'Rebel transport') return RebelTransportBackground;\n else if (name === 'CR90 corvette') return corvetteBackground;\n else if (name === 'Sentinel-class landing craft') return landingCraftBackgrounds[Math.floor(Math.random()*landingCraftBackgrounds.length)];\n else if (name === 'Y-wing') return YWingBackground;\n else if (name === 'TIE Advanced x1') return TIEbackgrounds[Math.floor(Math.random()*TIEbackgrounds.length)];\n else if (name === 'Executor') return executorBackgrounds[Math.floor(Math.random()*executorBackgrounds.length)];\n}",
"function selectRandNum() {\nreturn Math.floor(Math.random()*imageSilo.length);\n}",
"function rollDice () {\n let randomArray = [];\n for (let dicePosition = 0; dicePosition < 6; dicePosition++) {\n let myRoll = Math.floor(Math.random() *6) + 1;\n randomArray.push(myRoll);\n let diceSVG = `img/small-dice/face${randomArray[dicePosition]}.svg`;\n if (document.getElementById(`dice${dicePosition + 1}`).className === 'dice') {\n document.querySelector(`.face${dicePosition}`).setAttribute('src', diceSVG);\n };\n };\n}",
"start(){\n this.picture = DRAWINGS[Math.floor(Math.random()*DRAWINGS.length)];\n this.setRoundTime(ROUND_TIME_VAR)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
teamDataSavedListener React to team data being saved, by storing the match id | function teamDataSavedListener () {
debug('match data saved, resolving state promise')
module.exports.internal.teamDataSavedPromiseResolver()
} | [
"function findMatch () {\n module.exports.internal.dataObj.seasons[module.exports.internal.seasonId].matches.forEach((match) => {\n if (match.id === module.exports.internal.matchId) {\n module.exports.internal.matchData = match\n }\n })\n}",
"function saveMatch(fixture) {\n Match.findOne({ MatchCode: fixture.MatchCode }, (err, doc) => {\n if (!err) {\n if (doc) {\n updateMatch(fixture);\n } else {\n let _match = new Match(fixture);\n\n _match.save((err, match) => {\n if (!err) {\n console.log(`${match.Winner} created successfully! :)`);\n } else {\n console.error(err);\n }\n });\n }\n } else {\n console.log(\"Error in saving match\", err);\n }\n });\n}",
"function storeData(data, store) {\r\n if(store === \"teams\") {\r\n $(data).find(\"match\").each(function(index) {\r\n var Match = {\r\n index: index + 1,\r\n name1: $(this).find(\"team\")[0].textContent,\r\n name2: $(this).find(\"team\")[1].textContent,\r\n score1: $(this).find(\"team\").eq(0).attr(\"score\") !== undefined ? $(this).find(\"team\").eq(0).attr(\"score\") : \"-\",\r\n score2: $(this).find(\"team\").eq(0).attr(\"score\") !== undefined ? $(this).find(\"team\").eq(0).attr(\"score\") : \"-\",\r\n venue: $(this).find(\"venue\")[0].textContent,\r\n date: $(this).find(\"day\")[0].textContent + \"/\" + $(this).find(\"month\")[0].textContent + \"/\" + $(this).find(\"year\")[0].textContent\r\n };\r\n\r\n matches.push(Match);\r\n\r\n if($.inArray(Match.name1, teams) === -1) {\r\n teams.push(Match.name1);\r\n }\r\n\r\n if($.inArray(Match.name2, teams) === -1) {\r\n teams.push(Match.name2);\r\n }\r\n });\r\n } else if (store === \"venues\") {\r\n $.each($(data).find(\"venues\").children(), function(index, venue) {\r\n if($.inArray(venue, venues) === -1) {\r\n venues.push(venue.textContent);\r\n }\r\n });\r\n }\r\n }",
"storeTeams() {\n try {\n const serializedTeams = JSON.stringify(this.state.teams);\n localStorage.setItem('teams', serializedTeams);\n } catch (err) {\n console.log('error: ', err);\n }\n }",
"function teamNameChanged(event, teamName){\n self.teamName = teamName;\n }",
"hashChangeListener () {\n let teamNameRegEx = /teams\\/([\\w+|\\x25|\\s]+)\\W/\n let urlSpaceEncodingRegEx = /\\x25\\d{2}/g\n let foundTeamNameRegExGroup = document.URL.match(teamNameRegEx)\n let foundTeamName = foundTeamNameRegExGroup !== null ? String(foundTeamNameRegExGroup[1]) : null\n if (foundTeamName === null) { return }\n let cleanedTeamName = foundTeamName.replace(urlSpaceEncodingRegEx, ' ')\n if (this.state.viewedTeamObjects.hasOwnProperty(cleanedTeamName) === true) {\n this.setState(this.state.viewedTeamObjects[cleanedTeamName])\n } else if (this.state.viewedTeamObjects.hasOwnProperty(cleanedTeamName) !== true && this.state.viewedTeams.indexOf(cleanedTeamName) === -1) {\n this.fetchTeamInfo(cleanedTeamName)\n }\n scrollToTop()\n }",
"updateSelectedTile(event) { \n console.log(event.detail.boatId);\n this.selectedBoatId=event.detail.boatId;\n this.sendMessageService(this.selectedBoatId); \n }",
"setPlayerTeam(player, zone, team = undefined) {\n const location = DeathMatchLocation.getById(zone);\n if (!location.hasTeams)\n return;\n\n if (!this.teamScore_.has(zone))\n this.teamScore_.set(zone, new DeathMatchTeamScore());\n\n if (!this.zoneTextDraws_.has(zone)) {\n this.zoneTextDraws_.set(zone, -1);\n const textDraw = new TextDraw({\n position: [482, 311],\n text: '_',\n\n color: Color.fromNumberRGBA(-1),\n shadowColor: Color.fromRGBA(0, 0, 0, 255),\n font: 2,\n letterSize: [0.33, 1.5],\n outlineSize: 1,\n proportional: true,\n });\n\n\n this.zoneTextDraws_.set(zone, textDraw);\n textDraw.displayForPlayer(player);\n } else {\n const textDraw = this.zoneTextDraws_.get(zone);\n textDraw.displayForPlayer(player);\n }\n\n this.updateTextDraw(zone);\n\n if (!isNaN(team) && team < 2) {\n this.playerTeam_.set(player, { zone: zone, team: team });\n return;\n }\n\n const teams = [...this.playerTeam_]\n .filter(item => item[1].zone === zone)\n .map(item => item[1].team);\n\n const amountOfRedTeam = teams.filter(item => item === RED_TEAM).length;\n const amountOfBlueTeam = teams.filter(item => item === BLUE_TEAM).length;\n\n const newTeam = amountOfRedTeam <= amountOfBlueTeam ? RED_TEAM : BLUE_TEAM;\n\n this.playerTeam_.set(player, { zone: zone, team: newTeam });\n }",
"function handlePlayerJoinedEvent(data) {\n if (data.uID === uID) {\n if (data.joinSuccess) {\n\n //set team background colour\n if (data.team === 0) {\n userTeam = 'red-team';\n teamColors = ColorService.getRedColors();\n } else if (data.team === 1) {\n userTeam = 'blue-team';\n teamColors = ColorService.getBlueColors();\n }\n\n // set the specials and gamestate\n specialPowers = SpecialPowerManagerService.setupSpecials(data.specials);\n gameState = data.state;\n lane = data.lane;\n heroClass = data.heroClass;\n\n joinPromise.resolve(data);\n } else {\n joinPromise.reject(data);\n }\n }\n }",
"function OnJoinTeamPressed() {\n // Get the team id asscociated with the team button that was pressed\n var teamId = $.GetContextPanel().GetAttributeInt(\"team_id\", -1);\n\n // Request to join the team of the button that was pressed\n Game.PlayerJoinTeam(teamId);\n}",
"savingChange (movie) {\n this.props.dispatch({ type: 'EDIT_MOVIE', payload: movie });\n this.props.dispatch({type: 'SET_MOOVIE', payload: movie});\n this.props.history.push(`/details/${this.state.id}`);\n\n\n }",
"addLeagueTie() {\n this.#records[\"league\"].addTie();\n }",
"addLeagueWin() {\n this.#records[\"league\"].addWin();\n }",
"updatePlayerData(playerData) {\n console.log(\"Updating player info...\");\n this.updateTeamData(this.contentRows, \".simLeft\", playerData);\n }",
"async triggerMatch(){\n const teams = this.teams;\n\n let fetchTeamsPromises = [];\n teams.forEach((teamId) => {\n let team = new Team(teamId, this.tournamentId);\n fetchTeamsPromises.push(team.fetchTeamDetails());\n });\n\n // 1. Get individual Team info.\n let teamsInfo = await Promise.all(fetchTeamsPromises);\n console.log(\"RS\", teamsInfo);\n\n // 2. get winning Match Score \n let payload = { tournamentId: this.tournamentId , round: this.round, match: this.match};\n let matchScore = await this.getMatchScore(payload);\n\n\n // 3. Get the Winning Score\n let teamScores = teamsInfo.map( (team) => {\n return team.score;\n });\n\n let winnerPayload = {tournamentId: this.tournamentId, teamScores: teamScores, matchScore: matchScore};\n let winningScore = await this.getWinnerScore(winnerPayload);\n\n //4. Find the teams which has the Winning Score\n let winnerTeams = teamsInfo.filter((team) => {\n return ( winningScore === team.score );\n });\n\n //5. If WinnerTeams more than one , with lowest teamId wins.\n if(winnerTeams.length>1){\n winnerTeams.sort((a,b) => a.teamId-b.teamId);\n }\n\n //6. Set the progress of the match in the DOM.\n this.setIndicatorLoading(this.round, this.match);\n return winnerTeams[0];\n }",
"addLeagueLoss() {\n this.#records[\"league\"].addLoss();\n }",
"function generateScoreBoard() {\n const tabs = `<p class=\"alert alert-info small text-center p-0 mt-2 mb-0\">🛈 Click team name to Edit</p>\n <div class=\"pt-2\">\n <ul class=\"nav nav-tabs nav-justified mb-3\" id=\"scoreTab\" role=\"tablist\">\n <li class=\"nav-item\" role=\"presentation\">\n <a class=\"nav-link active fw-bolder\"\n id=\"${match.battingTeam.id}-tab\"\n data-bs-toggle=\"tab\" href=\"#${match.battingTeam.id}-content\"\n role=\"tab\"\n aria-controls=\"${match.battingTeam.id}-content\"\n aria-selected=\"true\"\n contenteditable=\"true\">\n ${match.battingTeam.name}\n </a>\n </li>\n <li class=\"nav-item\" role=\"presentation\">\n <a class=\"nav-link fw-bolder\"\n id=\"${match.bowlingTeam.id}-tab\"\n data-bs-toggle=\"tab\" href=\"#${match.bowlingTeam.id}-content\"\n role=\"tab\"\n aria-controls=\"${match.bowlingTeam.id}-content\"\n aria-selected=\"true\"\n contenteditable=\"true\">\n ${match.bowlingTeam.name}\n </a>\n </li>\n </ul>\n\n <div class=\"tab-content\" id=\"scoreTabContent\">\n <div class=\"tab-pane fade show active\"\n id=\"${match.battingTeam.id}-content\"\n role=\"tabpanel\"\n aria-labelledby=\"${match.battingTeam.id}-tab\">\n ${createTab(match.battingTeam, match.bowlingTeam)}\n </div>\n <div class=\"tab-pane fade\"\n id=\"${match.bowlingTeam.id}-content\"\n role=\"tabpanel\"\n aria-labelledby=\"${match.bowlingTeam.id}-tab\">\n ${createTab(match.bowlingTeam, match.battingTeam)}\n </div>\n </div>\n </div>`;\n\n matchDetails.style.display = \"none\"; // Hide details div\n scoreboard.insertAdjacentHTML(\"beforeend\", tabs);\n\n // Add event listeners for team name changes\n document.querySelectorAll(\"a.nav-link.fw-bolder\").forEach((tab) => {\n tab.addEventListener(\"input\", (event) => {\n const team = event.target.getAttribute(\"id\").replace(\"-tab\", \"\");\n const name = event.target.textContent.trim()\n ? event.target.textContent\n : team;\n event.target.textContent = name;\n match[team].name = name;\n });\n });\n}",
"function pushDetailsInTeams(teams,matches){\n for(let i=0;i<teams.length;i++){\n let name=teams[i].name;\n for(let j=0;j<matches.length;j++){\n if(name==matches[j].t1 || name==matches[j].t2){\n if(name==matches[j].t1 ){\n teams[i].matches.push({\n opponenetTeam:matches[j].t2,\n teamScore:matches[j].team1Score,\n opponentScore:matches[j].team2Score,\n result:matches[j].result\n })\n }else{\n teams[i].matches.push({\n opponenetTeam:matches[j].t1,\n teamScore:matches[j].team2Score,\n opponentScore:matches[j].team1Score,\n result:matches[j].result\n })\n }\n }\n }\n }\n}",
"function handleEditGamePage() {\n document.addEventListener(\"DOMContentLoaded\", function (event) {\n \"use strict\";\n\n firebase.database().ref('/Globals').once('value').then(function (snapshot) {\n teamName = snapshot.child('TeamName');\n });\n\n var datetime = localStorage.getItem(\"datetime\");\n\n if (datetime != null) {\n firebase.database().ref('/Games/' + datetime).once('value').then(function (snapshot) {\n if (!snapshot.exists()) {\n alert('Not a recorded game');\n window.location = \"/view-game-schedule.html\";\n }\n\n var datetime = snapshot.child('datetime'),\n location = snapshot.child('location'),\n them = snapshot.child('them'),\n inputs = document.querySelectorAll('.form-control');\n\n inputs[0].value = them.val();\n inputs[1].value = location.val();\n inputs[2].value = datetime.val();\n });\n } else {\n alert('Not a valid game');\n window.location = \"/view-game-schedule.html\";\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
jshint W097 / globals module Defines a channel that syncs data to Firebase | function FirebaseChannelConfig() {
this.databaseURL = null;
this.serviceAccount = null;
} | [
"openChannel(params) {\n\n // define a couple potential payloads for the firebase add. \n const channelPayloadOptions = [\n // Option 1: new channel, n members, no admin. \n {\n channelName: \"\",\n members: members,\n thread: [ message ]\n }, \n // option 2: new channel, all members added except the admin. \n {\n channelName: \"\",\n // filtering the members param to remove the administrator, eg., the parent. \n members: members.filter(memberID => memberID !== admin ),\n thread: [ message ]\n },\n {\n channelName: \"\",\n members: members,\n admins: [admin],\n thread: [ message ]\n }\n ];\n // deconstruct the main variables param for easy reaching.\n const { message, members } = params;\n\n // simple check if optional param admin included, set admin to it where need be. \n let admin;\n if (params.admin) admin = params.admin;\n\n // within the scope of a promise to be returned, makke the firebase call to add the channel.\n new Promise((resolve, reject) => {\n firebase.firestore()\n .collection('channels')\n // fires the first option in the payloads array, being the n members no admin declared.\n .add(channelPayloadOptions[0])\n .then(newChannel => {\n if (newChannel.id) {\n\n // once there's a new channel id, map the members array provided to params and add permissions to that channel for each member in the array. \n members.map(memberID => {\n firebase.firestore().collection('memberDetails').doc(memberID).update({\n channels: firebase.firestore.FieldValue.arrayUnion(newChannel.id)\n })\n })\n\n resolve(newChannel.id);\n } else {\n reject(new Error('Encountered an unexpected error:'));\n }\n })\n .catch(err => {\n console.log({err});\n });\n });\n }",
"onUpdatedChannels () {\n //OnX modules\n this._privMsg = new PrivMsg(this.bot)\n this._userNotice = new UserNotice(this.bot)\n this._clearChat = new ClearChat(this.bot)\n this._clearMsg = new ClearMsg(this.bot)\n this._userState = new UserState(this.bot)\n\n setInterval(this.updateBotChannels.bind(this), UPDATE_ALL_CHANNELS_INTERVAL)\n\n Logger.info(\"### Fully setup: \" + this.bot.userId + \" (\" + this.bot.userName + \")\")\n }",
"function setupFirebaseConfig(){\n var config = {\n apiKey: \"AIzaSyCYDlrU2O3OT4jaJnaCF5krqCbof67yTWU\",\n authDomain: \"findmefuel-3c346.firebaseapp.com\",\n databaseURL: \"https://findmefuel-3c346.firebaseio.com\",\n storageBucket: \"findmefuel-3c346.appspot.com\",\n messagingSenderId: \"386153049618\"\n };\n firebase.initializeApp(config);\n database = firebase.database();\n }",
"function VueChat () {\n this.initFirebase()\n}",
"function setupChannel() {\n // Join the general channel\n generalChannel.join().then(function(channel) {\n print('Joined channel as <span class=\"me\">' + username + '</span>.', username, new Date());\n });\n\n // Listen for new messages sent to the channel\n generalChannel.on('messageAdded', function(message) {\n //printMessage(message.author, message.body);\n print(message.body,message.author,message.dateCreated);\n });\n // Listen for new messages sent to the channel\n generalChannel.on('memberLeft', function(data) {\n console(data);\n //print(message.body,message.author,message.dateCreated);\n });\n }",
"function SimplePush(options, cb) {\n\n var settings = JSON.parse(JSON.stringify(options));\n\n if (!settings.notifyPrefix) settings.notifyPrefix = '/notify/';\n if (!settings.host) settings.host = 'localhost';\n if (!settings.tls) settings.tls = false;\n\n var store = require('./store')(settings.db);\n var emitter = new events.EventEmitter();\n var protocol = settings.tls ? https : http;\n var server = protocol.createServer(requestCallback);\n\n var wsServer = new WebSocketServer({\n httpServer: server,\n autoAcceptConnections: false\n });\n\n // We wait until the database has connected to initialize the server\n store.connect(function(err) {\n if (err) return cb(err);\n server.listen(settings.port, settings.host, function(err) {\n cb(err, server);\n });\n });\n\n function channelIDToEndpoint(channelID) {\n return (settings.tls ? 'https' : 'http') + '://' + settings.host + ':' + settings.port + settings.notifyPrefix + channelID;\n }\n\n function endpointToChannelID(endpoint) {\n return endpoint.split(settings.notifyPrefix)[1];\n }\n\n // Callback for http server requests\n // Receives version updates from the AppServer for specified channeldIDs\n // After receiving a version update, it will notify the UserAgent\n // until it receives an acknowledgement\n\n function requestCallback(request, response) {\n console.log((new Date()) + ' Received request for ' + request);\n\n // Updates must be PUT requests\n if (request.method === 'PUT') {\n var body = '';\n request.on('data', function(data) {\n body += data;\n });\n\n request.on('end', function() {\n var data = qs.parse(body);\n var channelID, channel;\n\n var endpoint = request.url;\n async.waterfall([\n function(cb) {\n var chID = endpointToChannelID(endpoint);\n if (!chID) return cb('MissingChannelID');\n channelID = chID;\n\n store.get('channel/' + channelID, cb);\n },\n function(ch, cb) {\n if (!ch) return cb('UnknownChannel');\n channel = ch;\n // store the pending version\n channel.pendingVersion = data.version;\n store.set('channel/' + channelID, channel, cb);\n }\n ], function(err) {\n // respond to the appserver\n var status = 200;\n\n if (err === 'MissingChannelID' ||\n err === 'UnknownChannel') status = 400;\n else if (err) status = 500;\n\n response.writeHead(status);\n response.end();\n if (status === 200) {\n // send push notification to the UA\n // TODO set a timeout to check again after 60 seconds\n emitter.emit(channel.uaid, 'notification', { channelID: channelID, version: data.version });\n }\n });\n });\n } else {\n response.writeHead(400);\n response.end();\n }\n }\n\n // Revieves new client connections and registers push server event handlers\n wsServer.on('request', function(request) {\n var connection = request.accept('push-notification', request.origin);\n console.log((new Date()) + ' Connection accepted.');\n\n var uaid;\n connection.on('message', function(message) {\n if (message.type === 'utf8') {\n console.log('Received Message: ' + message.utf8Data);\n\n var data = JSON.parse(message.utf8Data);\n\n // Perform handshake and register new client\n if (data.messageType === 'hello') {\n if (typeof data.uaid !== 'string' || !data.channelIDs) {\n return connection.close();\n }\n uaid = data.uaid || uuid.v4();\n\n if (data.channelIDs) {\n resyncChannelIDs(uaid, data.channelIDs, function() {\n store.set('uaid/' + uaid, {\n channelIDs: data.channelIDs\n }, function() {\n var response = {\n messageType: 'hello',\n uaid: uaid\n };\n connection.sendUTF(JSON.stringify(response));\n });\n });\n }\n\n // dispatch messages sent to this ua\n var uaHandler = handler.bind(null, uaid, connection);\n emitter.on(uaid, uaHandler);\n connection.on('close', function() {\n try {\n emitter.removeListener(uaHandler);\n } catch(e) {}\n });\n\n } else if (uaid && data.messageType === 'register') {\n emitter.emit(uaid, 'register', data);\n\n } else if (uaid && data.messageType === 'unregister') {\n emitter.emit(uaid, 'unregister', data);\n\n } else if (uaid && data.messageType === 'ack') {\n emitter.emit(uaid, 'ack', data);\n }\n }\n });\n\n connection.on('close', function(reasonCode, description) {\n console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected. ' + description);\n });\n\n });\n\n function resyncChannelIDs(uaid, channelIDs, cb) {\n var storedChannelIDs;\n\n async.waterfall([\n function(cb) {\n store.get('uaid/' + uaid, cb);\n },\n function(ua, cb) {\n if (!ua) return cb('UnknownUserAgent');\n\n storedChannelIDs = ua.channelIDs;\n // delete channels the ua didn't specify\n async.each(ua.channelIDs, function(channelID, cb) {\n if (channelIDs.indexOf(channelID) === -1) {\n store.delete('channel/' + channelID, cb);\n } else {\n cb(null);\n }\n }, cb);\n },\n function(cb) {\n // reregister channelIDs that the server is missing\n async.each(channelIDs, function(channelID, cb) {\n if (storedChannelIDs.indexOf(channelID) === -1) {\n var endpoint = channelIDToEndpoint(channelID);\n store.set('channel/' + channelID, { uaid: uaid, endpoint: endpoint }, cb);\n } else {\n cb(null);\n }\n }, cb);\n }\n ], cb);\n }\n\n\n // Handle events for a UserAgent\n // Events include register, unregister, notification, and ack\n function handler(uaid, connection, type, data) {\n console.log('received event:', uaid, type, data);\n\n if (type === 'register') {\n\n // register the channel and send a response to the UA\n register(uaid, data.channelID, function(err, endpoint) {\n var status = 200;\n if (err) {\n status = err === 'UAMismatch' ? 409 : 500;\n console.error(err);\n }\n\n // send endpoint back to UA\n var response = {\n messageType: 'register',\n status: status,\n channelID: data.channelID,\n pushEndpoint: endpoint\n };\n connection.sendUTF(JSON.stringify(response));\n }\n );\n\n } else if (type === 'unregister') {\n\n // unregister the channel and send a response to the UA\n unregister(uaid, data, function(err) {\n var status = 200;\n\n // Don't send 500 errors for UA mismatches or unknown channel IDs\n if (err && err !== 'UAMismatch' && err !== 'UnknownChannelID') {\n status = 500;\n console.error(err);\n }\n\n // send confirmation back to UA\n var response = {\n messageType: 'unregister',\n status: status,\n channelID: data.channelID\n };\n connection.sendUTF(JSON.stringify(response));\n });\n\n } else if (type === 'notification') {\n\n // AppServer has just pinged the endpoint\n // send notifications to the UA of the channels that have been updated\n var response = {\n messageType: 'notification',\n updates: [data]\n };\n connection.sendUTF(JSON.stringify(response));\n\n } else if (type === 'ack') {\n\n // Acknowledgement from the UA that it received the notification\n // We update the channel's version with the pending version\n data.updates.forEach(function(update) {\n\n store.get('channel/' + update.channelID, function (err, channel) {\n\n // update the channel version with the acknowledged version\n // but only if it was currently pending\n if (channel.pendingVersion === update.version && update.version !== channel.version) {\n channel.version = update.version;\n store.set('channel/' + update.channelID, channel, function(err) {\n if (err) console.error(err);\n console.log('done updating pending for', update.channelID);\n });\n }\n });\n });\n\n }\n }\n\n // Utility function for registering a new channel\n function register(uaid, channelID, cb) {\n\n async.waterfall([\n function(cb) {\n // get UA info\n store.get('uaid/' + uaid, cb);\n },\n function(ua, cb) {\n // update list of channels\n ua.channelIDs.push(channelID);\n store.set('uaid/' + uaid, ua, cb);\n },\n function(cb) {\n // link channel with UAID and endpoint\n var endpoint = channelIDToEndpoint(channelID);\n store.set('channel/' + channelID,\n { uaid: uaid, endpoint: endpoint },\n function(err) { cb(err, endpoint); }\n );\n }\n ], cb);\n\n }\n\n // Utility function for unregistering a channel\n function unregister(uaid, data, cb) {\n\n async.waterfall([\n function(cb) {\n store.get('channel/' + data.channelID, cb);\n },\n function(channel, cb) {\n // the channel ID is unknown\n if (!channel) return cb('UnknownChannelID');\n\n // the UA doesn't match our current UA\n if (channel.uaid !== uaid) return cb('UAMismatch');\n\n store.delete('channel/' + data.channelID, cb);\n },\n function(cb) {\n // get UA info so we can remove this channel from its list\n store.get('uaid/' + uaid, cb);\n },\n function(ua, cb) {\n // remove the channel ID from the UA's list of channels\n ua.channelIDs.splice(ua.channelIDs.indexOf(data.channelID), 1);\n store.set('uaid/' + uaid, ua, cb);\n }\n ], cb);\n\n }\n\n}",
"static initFirebaseSession() {\n if (firebase.apps.length === 0) {\n const firebaseConfig = {\n apiKey: \"AIzaSyBXD35ShAvf1SrwVSKGrgsl-Odibwrq1G0\",\n authDomain: \"tic-tac-toe-owens.firebaseapp.com\",\n projectId: \"tic-tac-toe-owens\",\n storageBucket: \"tic-tac-toe-owens.appspot.com\",\n messagingSenderId: \"89134231715\",\n appId: \"1:89134231715:web:50b6e7d9333dd1542d8f16\",\n databaseURL: \"https://tic-tac-toe-owens-default-rtdb.firebaseio.com/\"\n };\n \n firebase.initializeApp(firebaseConfig);\n }\n }",
"function Firebase(_ref) {\n var config = _ref.config,\n dbname = _ref.dbname,\n engine = _ref.engine,\n cacheSize = _ref.cacheSize,\n adminClient = _ref.adminClient;\n\n _classCallCheck(this, Firebase);\n\n if (cacheSize === undefined) {\n cacheSize = 1000;\n }\n\n if (dbname === undefined) {\n dbname = 'bgio';\n } // // TODO: better handling for possible errors\n\n\n if (config === undefined) {\n config = {};\n }\n\n if (adminClient) {\n this.client = require('firebase-admin');\n } else {\n this.client = require('firebase');\n }\n\n this.engine = engine === ENGINE_RTDB ? engine : ENGINE_FIRESTORE;\n this.config = config;\n this.dbname = dbname;\n this.cache = new LRU$1({\n max: cacheSize\n });\n }",
"function startFirebase() {\n console.log('[startFirebase]');\n if (fbRef) {\n stopFirebase();\n }\n\n var fbURL = 'https://' + settings.appID + '.firebaseio.com/';\n fbRef = new Firebase(fbURL);\n fbRef.authAnonymously(onFirebaseConnected);\n}",
"function createChannel(){\n return notificationsApi.postNotificationsChannels()\n .then(data => {\n console.log('---- Created Notifications Channel ----');\n console.log(data);\n\n channel = data;\n let ws = new WebSocket(channel.connectUri);\n ws.onmessage = () => {\n let data = JSON.parse(event.data);\n\n topicCallbackMap[data.topicName](data);\n };\n });\n}",
"function loadChannels()\n{\n\t// Reset the arrays\n\tgChannels = [];\n\n\t// Load the XML\n\tfirebase.database().ref('/channels').once('value').then( function( snapshot ) {\n\n\t\tvar channels = snapshot.val();\n\t\tvar iChannels = channels.length;\n\n\t\t// Fill out the local copy of our data\n\t\tfor( var i=0; i<iChannels; i++ )\n\t\t{\n\t\t\tgChannels[i] = new Channel( channels[i] );\n\n\t\t\t// If this is a stream, parse the list\n\t\t\tif( gChannels[i].type == 'playlist' ) {\n\t\t\t\tgetStreamList( gChannels[i] );\n\t\t\t}\n\t\t\telse if( gChannels[i].type == 'stream' ) {\n\t\t\t\tgChannels[i].aURLs[0] = new Stream();\n\t\t\t\tgChannels[i].aURLs[0].url = gChannels[i].stream;\n\t\t\t\tgChannels[i].aURLs[0].title = gChannels[i].name;\n\t\t\t\tgChannels[i].valid = true;\n\t\t\t}\n\t\t}\n\t});\n}",
"pushRefreshedDatas() {\n var tt = this;\n MongoClient.connect(this.uri, function(err, db) {\n if (err) throw err;\n //Looking for a db called test\n var dbo = db.db(\"test\");\n for (var i = 0; i < tt.collections.length; ++i) {\n dbo.collection(\"rss\").insertOne(tt.collections[i],function(err, result) {\n if (err) throw err;\n });\n }\n db.close();\n });\n }",
"function pushToDb() {\n setInterval(function () {\n while(global.instruObj.length){\n // Until the global instruObj is empty, add data to the indexedDb\n let chunks = global.instruObj.splice(0,CHUNCK_LENGTH_TO_DB);\n dbFns.set(shortid.generate(),chunks).then(()=>{\n //console.log(\"Successfully wrote to db\",chunks)\n }).catch((err)=>{\n console.error(\" Error writing to db:\",err)\n });\n }\n },WRITE_TO_DB_INTERVAL)\n}",
"function idToChannel() {\n updateConfig()\n setTimeout(() => {\n AddChannel()\n }, 1000);\n }",
"function firstTimePushSetup() {\n // Start fetching the channel ID (it will arrive in the callback).\n chrome.pushMessaging.getChannelId(true, channelIdCallback);\n // chrome.app.window.create('index.html', { \"bounds\": { \"width\": 1024, \"height\": 768 } });\n console.log(\"getChannelId returned. Awaiting callback...\");\n chrome.app.window.create('index.html', { \"bounds\": { \"width\": 1024, \"height\": 768 } });\n console.log(\"get user info return. awarting callback..\")\n}",
"async function send() {\n console.log('Registering service worker...')\n const register = await navigator.serviceWorker.register('/serviceWorker.js', {\n // this worker is applied to the home page/index\n scope: '/'\n })\n console.log('Service worker registered')\n\n console.log('Registering push...')\n // register is the variable when we registered the service worker (all of this code can be found on the web-push Github page)\n const subscription = await register.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: urlBase64ToUint8Array(publicVapidKey),\n });\n console.log('Push registered')\n\n console.log('Sending push notification...')\n // Send the subscription obejct to our backend (see index.js)\n await fetch('/subscribe', {\n method: 'POST',\n body: JSON.stringify(subscription),\n headers: {\n 'content-type': 'application/json'\n }\n });\n console.log('Push sent')\n}",
"constructor(){\n \n // If class already instatiated, return the initial instance\n if (typeof this.instance === 'object') {\n return this.instance;\n }\n\n // Load Firebase modules and config files\n var firebase = require(\"firebase\"); \n var firebaseConfig = require('./../firebase.json');\n var firebaseAdmin = require(\"firebase-admin\");\n var firebaseAdminConfig = require('./../firebase.admin.json');\n\n // Instantiate key class properties\n this.firebase = firebase.initializeApp(firebaseConfig);\n this.firebaseAdmin = firebaseAdmin.initializeApp({\n credential: firebaseAdmin.credential.cert(firebaseAdminConfig),\n storageBucket: firebaseConfig.storageBucket,\n });\n this.storage = firebaseAdmin.firestore();\n this.bucket = firebaseAdmin.storage().bucket();\n\n // Store first instance, and return it\n this.instance = this;\n return this;\n }",
"function roomsCtrl($scope, $firebaseArray){\n var roomsRef = new Firebase(\"https://bloc-chat-aa.firebaseio.com/\");\n \n // create a synchronized array\n $scope.rooms = $firebaseArray(roomsRef);\n \n // add new items to the array\n $scope.addRoom = function() {\n console.log('in here')\n $scope.rooms.$add({\n roomName: $scope.newRoomText,\n userName: $scope.newUsernameText \n });\n }; \n \n var chatrooms = $firebaseArray(roomsRef.child('roomsCtrl'));\n\n return {\n all: chatrooms\n };\n \n }",
"_autoSyncClient() {\n const {\n serviceWorker,\n } = navigator;\n\n const updateLog = debug.scope('update');\n\n /* istanbul ignore next: won't occur in tests */\n serviceWorker.addEventListener('controllerchange', async () => {\n try {\n const registration = await connect(true);\n this.controller = registration.active;\n\n updateLog.color('crimson')\n .warn('mocker updated, reload your requests to take effect');\n } catch (error) {\n updateLog.error('connecting to new service worker failed', error);\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether the current user is a board member | isBoard(state) {
return state.oauth.user !== null && state.oauth.user.level === 'board';
} | [
"isMember(state) {\n return state.oauth.user !== null && ['board', 'member'].indexOf(state.oauth.user.level) !== -1;\n }",
"function isMember()\r\n{\r\n var userInfo = JSON.parse(sessionStorage.gUserInfo);\r\n\r\n if (userInfo && userInfo[\"m\"] && 0 < userInfo[\"m\"].length)\r\n {\r\n for (var i = 0; i < userInfo[\"m\"].length; ++i)\r\n {\r\n if (userInfo[\"uid\"] == userInfo[\"m\"][i][\"uid\"])\r\n {\r\n if (1 == userInfo[\"m\"][i][\"l\"])\r\n {\r\n return 1;\r\n }\r\n else\r\n {\r\n return 2;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return 0;\r\n}",
"function checkIfMember(user, chat) {\n if (user && user.id) return !!chat.users.find(u => u.id === user.id);\n return false;\n}",
"isPermitted(user_id) {\n if (!user_id) return false;\n for(var permitted in this.permitted) {\n if ( permitted == user_id ) return this.permitted[permitted] != null;\n if ( botStuff.userHasRole(this.server_id, user_id, permitted)) return this.permitted[permitted] != null;\n }\n return false;\n }",
"function isModerator(user){\r\n return user.mod;\r\n}",
"hasPrivilege (privilege) {\n let user = this.get('currentUser');\n if (user) {\n return (user.privileges.indexOf(privilege) > -1);\n } else {\n return false;\n }\n }",
"canManageTheServer(user_id) {\n return this.userHasPermissions(user_id, P_ADMINISTRATOR) ||\n this.userHasPermissions(user_id, P_MANAGE_GUILD) ||\n this.isServerOwner(user_id);\n }",
"function isMemberPresent(userid, channel){\n var userFound = false;\n channel.members.forEach(function(member){\n if(member.id === userid){\n userFound = true;\n }\n });\n return userFound;\n}",
"function isAdmin()\n {\n return (adminList.indexOf(socket.username) > -1);\n }",
"showUserLoggedConversation(){\n let loggedId = this.props.loggedUser && this.props.loggedUser.id;\n let membersId = false;\n this.props.conversation.members.forEach(msg => {\n if (msg === loggedId) {\n membersId = true;\n }\n });\n\n if(membersId){\n return this.conversationWithWho()\n }\n }",
"function isMasterUser()\n {\n return (masterUser == username && masterUserId == userId);\n }",
"canSeePlayer(){\n\t\t//enemy should act like it doesn't know where the player is if they're dead\n\t\tif(lostgame)\n\t\t\treturn false;\n\t\t\n\t\t// casts a ray to see if the line of sight has anything in the way\n\t\tvar rc = ray.fromPoints(this.pos, p1.pos);\n\t\t\n\t\t// creates a bounding box for the ray so that the ray only tests intersection\n\t\t// for the blocks in that bounding box\n\t\tvar rcbb = box.fromPoints(this.pos, p1.pos);\n\t\tvar poscols = []; // the blocks in the bounding box\n\t\tfor(var i = 0; i < blocks.length; i++){\n\t\t\tif(box.testOverlap(blocks[i].col, rcbb))\n\t\t\t\tposcols.push(blocks[i]);\n\t\t}\n\t\t\n\t\t// tests ray intersection for all the blocks in th ebounding box\n\t\tfor(var i = 0; i < poscols.length; i++){\n\t\t\tif(poscols[i].col.testIntersect(rc))\n\t\t\t\treturn false; // there is a ray intersection, the enemy's view is obstructed\n\t\t}\n\t\treturn true;\n\t}",
"function isPrivateLobby(name){\n for(var i = 0; i < private_lobby_list.length; i++){\n if(private_lobby_list[i].name === name){\n return true;\n }\n }\n return false;\n}",
"function canAffect(userRole, targetRole) {\n if (userRole === 'owner') {\n return true;\n }\n\n if (targetRole === 'owner') {\n return false;\n }\n\n return userRole === 'moderator' && targetRole === 'user';\n}",
"isGroupMember (groupId) {\n let user = this.get('currentUser');\n if (!Ember.isArray(user.groups)) {\n // if the provider has not been configured to load groups, show a warning...\n Ember.debug('Session.isGroupMember was called, but torii-provider-arcgis has not been configured to fetch user groups. Please see documentation. (https://github.com/dbouwman/torii-provider-arcgis#ember-cli-torii-provider-arcgis)');\n return false;\n } else {\n // look up the group in the groups array by it's Id\n let group = user.groups.find((g) => {\n return g.id === groupId;\n });\n if (group) {\n return true;\n } else {\n return false;\n }\n }\n }",
"static hasRightToWrite(){\n var idProject = Router.current().params._id\n var project = Projects.findOne(idProject)\n if(!project){\n return false;\n }\n var username = Meteor.user().username\n var participant = $(project.participants).filter(function(i,p){\n return p.username == username && p.right == \"Write\"\n })\n if(project.owner == username || participant.length > 0){\n return true\n }else{\n return false\n }\n }",
"function checkIfMyTurn() {\n console.log(\"in checkIfMyTurn...\");\n if (vm.currentGame.gameInProgress) {\n if ((vm.playerTeam === \"x\") && (vm.currentGame.turn) && (vm.playerName === vm.currentGame.player1) ||\n (vm.playerTeam === \"o\") && (!vm.currentGame.turn) && (vm.playerName === vm.currentGame.player2)){\n return true;\n }\n }\n return false;\n }",
"isBoardClear() {\n for (let x = 0; x < this.width; ++x) {\n for (let y = 0; y < this.height; ++y) {\n var square = this.grid[x][y];\n \n if (square !== null && square.hasOwnProperty('visible') && square.visible !== true) {\n return false;\n }\n }\n }\n \n return true;\n }",
"hasRemainingUsers() {\n return this.remainingUsers !== 0\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
roundEnded: Called when the round has been ended. If it's the first call after the round was continuing, we update buttons, stop the timer counter and induce a backend query to update the list of all words. | function roundEnded() {
if (roundCont == true) {
clearInterval(interval);
targetDate = null;
roundCont = false;
// document.myForm.round.disabled = false;
updateButtons();
getWords();
}
} | [
"endRound() {\n console.log(`Round ${this.round} completed.`)\n\n // update progress bar\n let point = this.round - 1;\n if (point >= 0) {\n // calc width for the bar\n let width = Math.round(100 / (totalRounds - 1) * point);\n progressBar.find('.active-line').animate({\n width: width + '%',\n }, 300, function() {\n progressBar.find('.point:eq(' + point + ')').addClass('active');\n });\n }\n\n }",
"function endRound () {\n\t/* check to see how many players are still in the game */\n var inGame = 0;\n var lastPlayer = 0;\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n inGame++;\n lastPlayer = i;\n }\n }\n \n /* if there is only one player left, end the game */\n if (inGame == 1) {\n\t\tconsole.log(\"The game has ended!\");\n\t\t$gameBanner.html(\"Game Over! \"+players[lastPlayer].label+\" won Strip Poker Night at the Inventory!\");\n\t\tgameOver = true;\n \n for (var i = 0; i < players.length; i++) {\n if (HUMAN_PLAYER == i) {\n $gamePlayerCardArea.hide();\n } \n else {\n $gameOpponentAreas[i-1].hide();\n }\n }\n \n\t\thandleGameOver();\n\t} else {\n\t\t$mainButton.html(\"Deal\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n\t}\n\t$mainButton.attr('disabled', false);\n actualMainButtonState = false;\n}",
"function quitRound() {\n clearInterval(timer);\n endRound();\n}",
"function gameEnd() {\n startingTime = 0;\n formatTime(startingTime);\n clearInterval(timer);\n let currentCards = qsa(\".card\");\n let i;\n for (i = 0; i < currentCards.length; i++) {\n currentCards[i].removeEventListener(\"click\", cardSelect, false);\n }\n $(\"refresh\").onclick = function() {\n return false;\n };\n deselectAll();\n\n }",
"function completeContinuePhase () {\n\t/* show the player removing an article of clothing */\n\tprepareToStripPlayer(recentLoser);\n updateAllGameVisuals();\n\t\n\t$mainButton.html(\"Strip\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}",
"function end_trial() {\n\n // kill any remaining setTimeout handlers\n jsPsych.pluginAPI.clearAllTimeouts();\n\n // gather the data to store for the trial\n var trial_data = {\n stimulus: trial.stimulus,\n rt: performance.now() - starttime\n };\n\n // clear the display\n display_element.innerHTML = '';\n\n // move on to the next trial\n jsPsych.finishTrial(trial_data);\n }",
"function endQuiz(){\n clearInterval(timerId)\n questionZoneEl.style.display = 'none';\n finalZoneEl.style.display = 'block';\n finalScoreEl.append(timeRemaining);\n\n}",
"function finishGame() {\n clearBoard();\n score += timePassed > score ? timePassed % score : score % timePassed;\n scoreText.innerText = `${score}`;\n showStats();\n updateScoreTable();\n saveGameData();\n setTimer(STOP_TIMER);\n document.getElementsByClassName('details')[0].style.display = 'none';\n getById('player-name').style.pointerEvents = 'all';\n}",
"finishGame(streak){\n let winner = this.currentPlayer;\n if(streak){\n for(let i=0; i<streak.length; i++){\n this.field[streak[i][0]][streak[i][1]] = \"<span class='winner'>\"+winner.toUpperCase()+\"</span>\";\n }\n this.winningStreak = streak;\n }\n else winner = true;\n this.winner = winner;\n $(this).trigger('finish');\n }",
"endRoll() {\n\t\tdie.stopRolling();\n\t\tshowGameplayButtons();\n\t}",
"function allQuestionsAnswered() {\n clearTimeout(countdown);\n}",
"function endGame(tie) {\n vm.currentGame.winner = tie ? \"Cat's game!\" : \n (vm.currentGame.turn ? $filter('firstName')(vm.currentGame.player1) + \" wins!\" : \n $filter('firstName')(vm.currentGame.player2) + \" wins!\");\n vm.currentGame.gameInProgress = false;\n vm.currentGame.postGame = true;\n }",
"function moveToNextPhrase() {\n currentPhraseIndex++;\n if (currentPhraseIndex < phrases.length) {\n document.getElementById('current-phrase').textContent = phrases[currentPhraseIndex];\n } else {\n document.getElementById('quiz-status').textContent = 'Quiz completed! Well done!';\n SpeechRecognitionService.stop();\n document.getElementById('stop-recording-btn').disabled = true;\n document.getElementById('start-recording-btn').disabled = true;\n }\n}",
"_drawing() {\n //TEST only\n // this.receiveAnswer(\"current\", \"word1\");\n //end test\n console.log(\"drawing\");\n if (this.state !== GameStates.Drawing) {\n return; //error\n }\n\n // on vérifie que le joueur courrant est connecté sinon on attend pour rien\n if (this.isCurrentPlayerConnected()) {\n if (this.timer === null) {\n // appelé une fois\n this.timer = setTimeout(() => {\n this._afterDrawing();\n }, this.roundTime);\n }\n } else {\n // on change de joueur\n console.log(\"ERROR ERROR\")\n this.state = GameStates.NextPlayer;\n }\n }",
"function end() {\n\t// set GAMEOVER to true\n\tGAME_OVER = true;\n\t// call clear methods\n\tUFO.clear();\n\tBULLET.clear();\n\tBOOM.clear();\n\t// fill the score\n\tscore.textContent = GAME_SCORE;\n\t// show score board\n\tgame.classList.remove('active');\n}",
"updateWinners() {\n const winners = [...this.continuing]\n .filter(candidate => this.count[this.round][candidate] >= this.thresh[this.round]);\n if (!winners.length) return; // no winners\n\n const text = this.newWinners(winners);\n this.roundInfo[this.round].winners = text;\n }",
"function completeRevealPhase () {\n /* reveal everyone's hand */\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n determineHand(i);\n showHand(i);\n }\n }\n \n /* figure out who has the lowest hand */\n recentLoser = determineLowestHand();\n console.log(\"Player \"+recentLoser+\" is the loser.\");\n \n /* look for the unlikely case of an absolute tie */\n if (recentLoser == -1) {\n console.log(\"Fuck... there was an absolute tie\");\n /* inform the player */\n \n /* hide the dialogue bubbles */\n for (var i = 1; i < players.length; i++) {\n $gameDialogues[i-1].html(\"\");\n $gameAdvanceButtons[i-1].css({opacity : 0});\n $gameBubbles[i-1].hide();\n }\n \n /* reset the round */\n $mainButton.html(\"Deal\");\n $mainButton.attr('disabled', false);\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame, FORFEIT_DELAY);\n }\n return;\n }\n \n /* update behaviour */\n\tvar clothes = playerMustStrip (recentLoser);\n updateAllGameVisuals();\n \n /* highlight the loser */\n for (var i = 0; i < players.length; i++) {\n if (recentLoser == i) {\n $gameLabels[i].css({\"background-color\" : loserColour});\n } else {\n $gameLabels[i].css({\"background-color\" : clearColour});\n }\n }\n \n /* set up the main button */\n\tif (recentLoser != HUMAN_PLAYER && clothes > 0) {\n\t\t$mainButton.html(\"Continue\");\n\t} else {\n\t\t$mainButton.html(\"Strip\");\n\t}\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}",
"function toggle_done() {\n if (active_timer_idx >= 0 && active_timer_idx != selected_timer_idx) {\n return; // Special case of discussion toggled on. Don't set to done in this case.\n }\n\n var next_timer_idx = -1;\n if (active_timer_idx < 0) {\n timer_object = timers[selected_timer_idx];\n } else {\n timer_object = timers[active_timer_idx];\n if (typeof timers[active_timer_idx + 1] != 'undefined') {\n next_timer_idx = active_timer_idx + 1;\n }\n }\n if (timer_object != null) {\n if (active_timer_idx >= 0) {\n timer_object.circleProgress('timer_done', 1);\n start_stop_timer(active_timer_idx, 0);\n if (next_timer_idx >= 0) {\n change_selected_to(next_timer_idx);\n start_stop_timer(next_timer_idx, 1);\n active_timer_idx = next_timer_idx;\n } else {\n active_timer_idx = -1;\n }\n\n } else {\n timer_object.circleProgress('timer_done', -1);\n }\n }\n}",
"function endQuiz() {\n\n // clear interval\n clearInterval(intervalId);\n\n // Show the user the quiz is over\n setTimeout(showHighScore, 2000);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the database JSON file | load() {
let database = fs.readFileSync(__dirname + '/database.json', 'utf8');
return JSON.parse(database);
} | [
"function loadJSON() {\n var client = new XMLHttpRequest();\n client.open(\"GET\", databasefilename, true);\n client.onreadystatechange = function () { //callback\n if (client.readyState === 4) {\n if (client.status === 200 || client.status === 0) {\n database_obj = JSON.parse(client.responseText);\n processInput();\n }\n }\n };\n client.send();\n }",
"loadDatabase() {\n fs.readFile(this.databasePath, (error, data) => {\n if (error) {\n return console.error(\"Unable to load database.\")\n }\n this.database = JSON.parse(data)\n console.log(this.database)\n })\n }",
"function LoadJson(){}",
"leerDb() {\n try {\n const informacion = fs.readFileSync(this.pathDb, {\n encoding: 'utf8'\n });\n const { historial } = JSON.parse(informacion);\n return this.historial = historial;\n }\n catch (e) {\n console.error(`Error al leer el archivo.`.red.bold);\n }\n }",
"load(){\n const file_name = \"hashdumpyard.json\"\n const fs = require('fs')\n const dumped = fs.readFileSync(file_name)\n this.primary_table = JSON.parse(dumped).primary_table\n this.slot_size = this.primary_table.length\n this.processed = true\n }",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"function readDatabase(filename) {\n //1.lue tiedosto levyltä\n //2.tallenna sisältö muuttujaan (JSON.parse(tiedostonSisalto))\n var pathToFile = path.join(__dirname, filename);\n fs.readFile(pathToFile, 'utf8', function (err, data) {\n if (err) {\n return console.log(err);\n }\n toVariable = JSON.parse(data);\n console.log(\"1) Tiedoston nimi: \"+filename);\n console.log(\"2) Tietueiden lukumäärä: \"+size());\n console.log(\"3) a) Löytyyko Jaska-niminen henkilö?: \"+containsPerson('Jaska'));\n console.log(\"3) b) Löytyyko Sarita-niminen henkilö?: \"+containsPerson('Sarita'));\n console.log(\"4) Mikä tietue vastaa tätä hakua?: \"+search('Tiia', '','','','','')+\". tietue\\n\"); \n console.log(toVariable[search('Tiia', '','','','','')]);\n })\n}",
"function insertData(){\n var obj = JSON.parse(fs.readFileSync('C:\\\\Users\\\\Tiankun\\\\Downloads\\\\doctors2.json', 'utf8'));\n mdb.collection('gp').insertMany(obj);\n}",
"function loadJSON() {\n return {\n resolve: {\n extensions: [\".json\"],\n },\n };\n}",
"static get DATABASE_URL() {\n return '/data/restaurants.json';\n }",
"function getDB(db, opts = {type: 'obj', createNew: true, returnNew: true}) {\n const dbPath = `./database/${db}.database.json`\n const newVal = opts.type === 'obj' ? '{}' : '[]'\n if (!fs.existsSync(dbPath)) {\n if (opts.createNew) fs.writeFileSync(dbPath, `${newVal}`)\n if (opts.returnNew) return JSON.parse(newVal)\n } else return JSON.parse(fs.readFileSync(dbPath).toString())\n}",
"static loadJson(pathToJson) {\n\t\tconsole.log(\"Loading story.json...\");\n\t\tvar r = new XMLHttpRequest();\n\t\tr.open(\"GET\", pathToJson, true);\n\t\tr.onload = function() {\n\t\t\tif (this.status >= 200 && this.status < 400)\n\t\t\t{\n\t\t\t\t// Set the active story to the loaded JSON\n\t\t\t\tstoryData.story = JSON.parse(this.responseText);\n\t\t\t\tStoryPlayer.initStory();\n\t\t\t}\n\t\t};\n\t\tr.send();\n\t\tconsole.log(\"story.js loaded!\");\n\t}",
"load(statsFile = Statistics.defaultLocation) {\n if (!fs.existsSync(path.dirname(statsFile))) {\n fs.mkdirSync(path.dirname(statsFile), { recursive: true });\n }\n if (!fs.existsSync(statsFile)) {\n if (fs.existsSync(\"./data/stats.json\")) {\n fs.renameSync(\"./data/stats.json\", statsFile);\n }\n else {\n console.error(\"No existing file! Creating file\");\n this.save();\n return;\n }\n }\n let object = JSON.parse(fs.readFileSync(statsFile, \"utf-8\"));\n for (const key in this) {\n if (this.hasOwnProperty(key) && object.hasOwnProperty(key)) {\n this[key] = object[key];\n }\n }\n }",
"async load() {\n await this.ensureExists();\n this.conf = await fs.readJSON(this.location);\n }",
"function readStartingData(){\n readUser = JSON.parse(fs.readFileSync('data/user.json'));\n listDoc = JSON.parse(fs.readFileSync('data/documents.json'));\n}",
"function loadConfig() {\n\tconfig_file = fs.readFileSync(\"./config.json\");\n\tconfig = JSON.parse(config_file);\n}",
"function loadInentory() {\n let invFile = fs.readFileSync('inventory.json', 'utf8');\n\n return JSON.parse(invFile);\n}",
"async getNotes() {\n\t\ttry {\n\t\t\tconst notes = await readFileAsync(\"db/db.json\", \"utf8\");\n\t\t\treturn JSON.parse(notes);\n\t\t} catch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}",
"async _loadDbConfig() {\n //dont trow exception for the case where the database is not installed\n try {\n //get config from db\n const configs = await this._configModel.findAll({})\n //set the config on an object\n await utils.asyncMap(configs, config => {\n this._configs[config.code] = {id: config.id, value: config.value}\n })\n } catch (error) {\n\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Functions ====== Fill tourList table with data | function populateTable(){
// Empty Content String
var tableContent = '';
// jQuery AJAX call for JSON
$.getJSON('/tours', function( data ){
tourList = data;
// For each item in our JSON, add a table row and cells to the content string
$.each(data,function(){
tableContent += '<tr>';
tableContent += '<td>' + this.title + '</td>';
tableContent += '<td><a href="#" class="linkdeletetour" rel="' + this._id + '">delete</a></td>';
});
// Inject Content onto HTML
$('#tourList table tbody').html(tableContent);
});
} | [
"function fill_table(list){\n $('#incidentListTable tbody tr').remove();\n $.each(list, function(i, item) {\n var $tr = $('<tr>').append(\n $('<th>').text(item.id),\n $('<td>').text(item.start),\n $('<td>').text(item.end),\n $('<td>').text(item.tags),\n $('<td>').text(item.subtags).addClass(\"d-none d-sm-table-cell\"),\n $('<td>').text(item.desc).addClass(\"d-none d-sm-table-cell\")\n );\n $tr.appendTo('#incidentListTable tbody');\n });\n}",
"function buildTable(){\n myDatabase.ref().once(\"value\", function (snapshot) {\n var latestSnapshot = snapshot.val();\n for(var looper in latestSnapshot){\n getArrival(latestSnapshot[looper].departTime,latestSnapshot[looper].tripTime);\n $('#trainTable').append(`<tr><td>${latestSnapshot[looper].trainName}</td><td>${latestSnapshot[looper].destination}</td><td>${latestSnapshot[looper].tripTime}</td><td class=\"nextArrival\">${nextArrival}<td class=\"minutesOut\">${minutesOut}</tr>`);\n }\n \n });\n }",
"function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredUFO.length; i++) {\n // Get get the current UFO object and its fields\n var ufo = filteredUFO[i];\n var observations = Object.keys(ufo);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < observations.length; j++) {\n // For every observations in the ufo object, create a new cell at set its inner text to be the current value at the current ufo'sobservation\n var observation = observations[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = ufo[observation];\n }\n }\n}",
"renderTableData() {\n window.$(\"#expenses\").find(\"tr:gt(0)\").remove();\n let table = document.getElementById(\"expenses\");\n for (let i = 0; i<exps.length; i++) {\n let row = table.insertRow();\n let cell0 = row.insertCell(0);\n let cell1 = row.insertCell(1);\n let cell2 = row.insertCell(2);\n cell0.innerHTML = exps[i].name;\n cell1.innerHTML = exps[i].cost;\n cell2.innerHTML = exps[i].category;\n }\n }",
"function populateLeaderboardTable() {\n\t// Ordeno el json dependiendo del score y los partidos ganados, perdidos o empatados\n\tleaderboardJson = leaderboardSorted(leaderboardJson);\n\t// imprimo las 5 primeras posiciones\n\tleaderboardTable.innerHTML = \"\";\n\tleaderboardJson.slice(0, 5).forEach(player => {\n\t\tleaderboardTable.innerHTML += \"<tr><th>\" + player.playerName + \"</th><td>\" + player.score + \"</td><td>\" +\n\t\t\tplayer.won + \"</td><td>\" + player.lost + \"</td><td>\" + player.tied + \"</td></tr>\"\n\t});\n}",
"function displayData(something){ \n tbody.text(\"\")\n something.forEach(function(et_sighting){\n new_tr = tbody.append(\"tr\")\n Object.entries(et_sighting).forEach(function([key, value]){\n new_td = new_tr.append(\"td\").text(value)\t\n })\n})}",
"function populateTable() {\t\n var table = $(\"#hiscore_table tr\");\n $.get(\"/hiscores\", function (data) {\n var hiscores = JSON.parse(data);\n hiscores.forEach(function (hiscore) {\n var html = createTableRow(hiscore.name, hiscore.score, hiscore.date);\n table.last().after(html);\t\t\n });\n });\t\n}",
"function gen_data_rows () {\n // loop over rows of data\n for (var i = 0; i < rep_data.data.length; i++) {\n // create a html row for representing the data\n var data_row = document.createElement (\"tr\");\n // loop over elements in the data row, add the data\n for (var j = 0; j < rep_data.data [i].length; j++) {\n // create td element for the data\n var td = document.createElement (\"td\");\n // set value in the td\n td.innerHTML = rep_data.data [i][j];\n // append td to the row\n data_row.appendChild (td);\n }\n // add the row to rep_table\n rep_table.appendChild (data_row);\n }\n}",
"function createAllTable() {\n let table = document.getElementById(\"tableHeadParkType\");\n table.innerHTML = \"\";\n let row = table.insertRow(table.rows.length);\n let cell1 = row.insertCell(0);\n cell1.innerHTML = \"Name\";\n let cell2 = row.insertCell(1);\n cell2.innerHTML = \"Address\";\n let cell3 = row.insertCell(2);\n cell3.innerHTML = \"City\";\n let cell4 = row.insertCell(3);\n cell4.innerHTML = \"State\";\n let cell5 = row.insertCell(4);\n cell5.innerHTML = \"Zip\";\n let cell6 = row.insertCell(5);\n cell6.innerHTML = \"Phone\";\n let cell7 = row.insertCell(6);\n cell7.innerHTML = \"Fax\";\n let cell8 = row.insertCell(7);\n cell8.innerHTML = \"Latitude\";\n let cell9 = row.insertCell(8);\n cell9.innerHTML = \"Longitude\";\n table.appendChild(row);\n table = document.getElementById(\"tableBodyParkType\");\n table.innerHTML = \"\";\n for (let i = 0; i < objs.parks.length; i++) {\n let row = table.insertRow(table.rows.length);\n let cell1 = row.insertCell(0);\n cell1.innerHTML = objs.parks[i].LocationName;\n table.appendChild(row);\n let cell2 = row.insertCell(1);\n cell2.innerHTML = objs.parks[i].Address;\n table.appendChild(row);\n let cell3 = row.insertCell(2);\n cell3.innerHTML = objs.parks[i].City;\n table.appendChild(row);\n let cell4 = row.insertCell(3);\n cell4.innerHTML = objs.parks[i].State;\n table.appendChild(row);\n let cell5 = row.insertCell(4);\n cell5.innerHTML = objs.parks[i].ZipCode;\n table.appendChild(row);\n let cell6 = row.insertCell(5);\n cell6.innerHTML = objs.parks[i].Phone;\n table.appendChild(row);\n let cell7 = row.insertCell(6);\n cell7.innerHTML = objs.parks[i].Fax;\n table.appendChild(row);\n let cell8 = row.insertCell(7);\n cell8.innerHTML = objs.parks[i].Latitude;\n table.appendChild(row);\n let cell9 = row.insertCell(8);\n cell9.innerHTML = objs.parks[i].Longitude;\n table.appendChild(row);\n }\n }",
"function buildHtmlTable() {\n\tvar columns = addAllColumnHeaders(myList);\n\n\tfor ( var i = 0; i < myList.length; i++) {\n\t\tvar row$ = $('<tr/>');\n\t\tfor ( var colIndex = 0; colIndex < columns.length; colIndex++) {\n\t\t\tvar cellValue = myList[i][columns[colIndex]];\n\n\t\t\tif (cellValue == null) {\n\t\t\t\tcellValue = \"\";\n\t\t\t}\n\n\t\t\trow$.append($('<td/>').html(cellValue));\n\t\t}\n\t\t$(\"#excelDataTable\").append(row$);\n\t}\n}",
"function createTasklistTable(){\n $('#tableWrapper').html(\"<table id='taskTable'></table>\");\n $('#taskTable').append(\"<th>Task</th>\"\n + \"<th>Person</th>\"\n + \"<th>Waiting</th>\"\n + \"<th>In Progress</th>\"\n + \"<th>Completed</th>\");\n}",
"function renderTable() {\n // Set the value of ending index\n var endingIndex = startingIndex + resultsPerPage;\n\n $tbody.innerHTML = \"\";\n // Set the value of ending index\n for (var i = 0; i < filteredAliens.length; i++) {\n // Get the current address object and its fields\n var alien = filteredAliens[i];\n var fields = Object.keys(alien);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell and set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = alien[field];\n };\n };\n}",
"function initTable(num){\n\n // Filter dataset by OTU id\n var filteredDate=dataset.metadata.filter(sample=>sample.id.toString()===num.toString())[0];\n\n\n // Create an list to store demographic information\n var valueList=Object.values(filteredDate);\n var valueKey=Object.keys(filteredDate);\n var demoInfo=[]\n for (var i=0;i<valueKey.length;i++){\n var element=`${valueKey[i]}: ${valueList[i]}`\n demoInfo.push(element);\n };\n\n // Add Demographic Information table in HTML\n var panel=d3.select(\"#sample-metadata\")\n var panelBody=panel.selectAll(\"p\")\n .data(demoInfo)\n .enter()\n .append(\"p\")\n .text(function(data){\n var number=data.split(\",\");\n return number;\n });\n \n }",
"fillTicketTable() {\n\n //if user has not changed (we already have tickets)\n if(this.lastUsername === shared.user.username) {\n return;\n }\n this.lastUsername = shared.user.username;\n\n //clear table\n $(\"#ticket_body\").html(\"\");\n this.ticketRowTotal = 0;\n\n //get user tickets\n shared.getRequest( {}, \"http://localhost:8080/reimbursement/get-user-reimb\", (json, statusCode, errorMessage)=> {\n\n if(!errorMessage) {\n\n this.tickets = json;\n\n for (let ticket of this.tickets) {\n\n //add row\n this.addRowToTicketTable(ticket);\n }\n }\n });\n }",
"function fillKPList(data) {\n console.log('Filling %s knowledge points', data.aaData.length);\n kpDataTable.empty();\n var kpSource = $('#kp-tmpl').html();\n var _template = Handlebars.compile(kpSource);\n var content = _template(data);\n kpDataTable.append(content);\n\n //syllabus information is set as tooltip. this is to initialize the tooltips\n $('[data-toggle=\"tooltip\"]').tooltip();\n }",
"function updateList() {\n\ttbody.innerHTML = '';\n\n\tif(employeeList.length === 0) {\n\t\ttbody.innerHTML = '<tr><td colspan=\"5\" style=\"text-align: center\">No Employee</td></tr>';\n\t}\n\n\tfor(let i = 0; i < employeeList.length; i++) {\n\t\tlet employee = employeeList[i];\n\t\ttbody.appendChild(createEmployeeElement(employee));\n\t}\n}",
"function createmountainTable() {\n let mountainChoice = document.getElementById(\"mountainChoice\").selectedIndex;\n // to select option from a specific dropdown, in this instance mountainChoice.\n let chosenMountain = document.getElementById(\"mountainChoice\").options[mountainChoice].value;\n let table = document.getElementById(\"tableBodyMountain\");\n table.innerHTML = \"\";\n\n for (let i = 0; i < objs.mountains.length; i++) {\n if (chosenMountain == objs.mountains[i].name) {\n let row = table.insertRow(table.rows.length);\n let cell1 = row.insertCell(0);\n cell1.innerHTML = \"Name\";\n let cell2 = row.insertCell(1);\n cell2.innerHTML = objs.mountains[i].name;\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell3 = row.insertCell(0);\n cell3.innerHTML = \"View\";\n let cell4 = row.insertCell(1);\n let img = document.createElement(\"img\");\n img.src = \"images/\" + objs.mountains[i].img;\n img.alt = objs.mountains[i].name;\n cell4.appendChild(img);\n\n row = table.insertRow(table.rows.length);\n let cell5 = row.insertCell(0);\n cell5.innerHTML = \"Elevation\";\n let cell6 = row.insertCell(1);\n cell6.innerHTML = objs.mountains[i].elevation;\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell7 = row.insertCell(0);\n cell7.innerHTML = \"Effort\";\n let cell8 = row.insertCell(1);\n cell8.innerHTML = objs.mountains[i].effort;\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell9 = row.insertCell(0);\n cell9.innerHTML = \"Description\";\n let cell10 = row.insertCell(1);\n cell10.innerHTML = objs.mountains[i].desc;\n table.appendChild(row);\n\n row = table.insertRow(table.rows[i].length);\n let cell11 = row.insertCell(0);\n cell11.innerHTML = \"Coordinates-Latitude\";\n let cell12 = row.insertCell(1);\n cell12.innerHTML = objs.mountains[i].coords.lat\n table.appendChild(row);\n\n row = table.insertRow(table.rows.length);\n let cell13 = row.insertCell(0);\n cell13.innerHTML = \"Coordinates-Longitude\";\n let cell14 = row.insertCell(1);\n cell14.innerHTML = objs.mountains[i].coords.lng\n table.appendChild(row);\n }\n }\n }",
"function _trip_to_table(sindex, trip) {\n\t\tvar row = trip_to_row(sindex++, trip);\n\t\t$(\"#paginated-table\").children(\"tbody\").append(row);\n\n\t\tvar text = get_trip_mtext (trip) || \"\"; // \"Business\"; // set default value\n\t\tvar imessage = $(\"#trip_\" + (sindex - 1)).find(\"input.message\");\n\t\t$(imessage).val(text);\n\t\ttext = get_trip_ntext (trip);\n\t\t$(\"#trip_\" + (sindex - 1)).find(\"textarea.note\").val(text);\n\t\t$(imessage).textbox({\n\t\t\titems: textbox_items\n\t\t});\n\t\treturn sindex;\n\t}",
"function populateHouses(characters) {\n characters.forEach(character => {\n data.push(character); // store all API data in an array of objects for use by search\n\n if(character.patronus === \"\" && character.house !== \"\") character.patronus = \"-\";\n if(character.house === \"\") character.house = \"None\";\n\n $(`<tr><td>${character.name}</td><td>${character.house}</td><td>${character.patronus}</td></tr>`).appendTo(`#${character.house} > table > tbody`);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================================================================= factory for handling tokens inject $window to store token clientside | function AuthToken($window){
var authTokenFactory = {}
//get the token out of local storage
authTokenFactory.getToken = function(){
return $window.localStorage.getItem('token')
}
//set the token or clear the token
authTokenFactory.setToken = function(token){
if(token)
$window.localStorage.setItem('token', token)
else {
$window.localStorage.removeItem('token')
}
}
return authTokenFactory
} | [
"function getToken() {\n return localStorage.getItem('token');\n}",
"function getToken() {\n\treturn localStorage.getItem('token')\n}",
"getByToken(){\n return http.get(\"/Employee/token/\" + localStorage.getItem('login').toString().split(\"Bearer \")[1]);\n }",
"function fetchTokens() {\n _.each(['fbtoken', 'dropboxtoken', 'livetoken'], function(key) {\n var token = localStorage.getItem(key);\n if (token != null) {\n Storage.getInstance().set(key, token);\n } \n Storage.getInstance().get(key).then(function (value) {\n console.log(key + \" \" + value);\n })\n });\n }",
"function setTokenHandlers(token){\n \n // Handle clicking on exit button\n \n $(token).find('button.exit').on('click', function(event){\n \n // Renumber other token names\n \n let tokenNo = $(token).prevAll('.token').length;\n \n $(token).nextAll('.token').each(function(){\n \n tokenNo ++;\n $(this).find('input[name$=\"-id\"]').attr('name', 'token' + tokenNo + '-id');\n $(this).find('input[name$=\"-type\"]').attr('name', 'token' + tokenNo + '-type');\n \n });\n \n // Remove token\n \n $(token).remove();\n \n });\n \n}",
"function tokenFunc() {\n\tlet data = {username : process.env.WORDPRESS_USER, password : process.env.WORDPRESS_PASS};\n\treturn new Promise(function(resolve, reject) {\n\t\trequest({\n\t\t\turl: process.env.WORDPRESS_ROOT_PATH + \"/wp-json/jwt-auth/v1/token\",\n\t\t\tContentType : 'application/x-www-form-urlencoded',\n\t\t\tmethod: \"POST\",\n\t\t\tform: data\n\t\t}, function(error, response, body) {\n\t\t\tif(error) {\n\t\t\t\treject(error)\n\t\t\t} else {\n\t\t\t\tlet info = body.substring(body.indexOf(\"{\"));\n\t\t\t\tinfo = JSON.parse(info);\n\t\t\t\tinfo = info.token;\n\t\t\t\tresolve(info);\n\t\t\t\t/*\n\t\t\t\trequest({\n\t\t\t\t\turl: process.env.WORDPRESS_ROOT_PATH + '/wp-json/jwt-auth/v1/token/validate',\n\t\t\t\t\tContentType: 'application/json',\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tauth: {'bearer' : info},\n\t\t\t\t\tjson: true\n\t\t\t\t}, function(error, response, body) {\n\t\t\t\t\tif(error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t\tif(body == undefined) {\n\t\t\t\t\t\treject(\"Not a real postID\");\n\t\t\t\t\t}\n\t\t\t\t\tbody = body.substring(body.indexOf(\"{\"));\n\t\t\t\t\tbody = JSON.parse(body);\n\t\t\t\t\tconsole.log(body);\n\t\t\t\t\tif(body.code == \"jwt_auth_valid_token\") {\n\t\t\t\t\t\tresolve(info);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t}\n\t\t});\n\t});\n}",
"function getToken() {\n oldToken = token;\n var request = new XMLHttpRequest();\n request.open(\"POST\", \"_assets/php/getToken.php\", true);\n request.send();\n request.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n token = request.responseText;\n }\n };\n}",
"receiveAuthParms() {\n var authData = {};\n\n if (document.location.search) {\n // Applies to authorizationCode flow\n var params = new URLSearchParams(document.location.search);\n var code = params.get('code');\n var error = params.get('error');\n var state = params.get('state');\n authData = {\n code,\n error,\n state,\n responseType: 'code'\n };\n } else if (window.location.hash) {\n // Applies to Implicit flow\n var token_type = this.parseQueryString(window.location.hash.substring(1), 'token_type'); // eslint-disable-line camelcase\n\n var access_token = this.parseQueryString(window.location.hash.substring(1), 'access_token'); // eslint-disable-line camelcase\n\n authData = {\n token_type,\n access_token,\n responseType: 'token'\n };\n }\n\n if (window.opener) {\n window.opener.postMessage(authData, this.target);\n return;\n }\n\n sessionStorage.setItem('rapidoc-oauth-data', JSON.stringify(authData)); // Fallback to session storage if window.opener dont exist\n }",
"function loadToken() {\n var tokenCookie = \"staticReader\";\n var t_value = document.cookie;\n var t_start = t_value.indexOf(tokenCookie + \"=\");\n if (t_start != -1){\n t_start = t_value.indexOf(\"=\") + 1;\n t_end = t_value.length;\n accessToken = \"access_token=\" + t_value.substr(t_start, t_end);\n colorGreen('tokenButton');\n document.getElementById('tokenField').value = accessToken;\n gistQuery = gitAPI + gistID + \"?\" + accessToken;\n \n }\n}",
"function tokenHandler(err, resp, body) {\n try { //google\n token = JSON.parse(body);\n } catch(err) { //facebook\n token = qs.parse(body);\n }\n if (token.error) return res.send(502, token.error); //TODO: improve error management\n //Facebook gives no token_type, Google gives 'Bearer' and Windows Live gives 'bearer', but is this test really useful?\n if ((token.token_type) && (token.token_type.toLowerCase() !== 'bearer')) return res.send(502, 'Invalid token type');\n request.get(providers[session.provider].profileURL + '?' + oAuth2.access_token + '=' + encodeURIComponent(token.access_token), profileHandler);\n //TODO: isn't it too soon to redirect as the profile may not have been saved yet?\n if(session.returnUrl) {\n var params = {\n access_token: token.access_token,\n expires: token.expires_in || token.expires, //Note: Facebook as token.expires instead of token.expires_in\n state: session.state\n };\n token.state = session.state;\n res.redirect(session.returnUrl + '#' + qs.stringify(params));\n }\n res.json(token); //Without returnUrl, the client receives the token as json to do whatever he/she deems necessary\n }",
"function setToken(token_temp) {\n token = token_temp\n}",
"setUserToken (callback) {\n\t\tthis.doApiRequest(\n\t\t\t{\n\t\t\t\tmethod: 'put',\n\t\t\t\tpath: '/provider-set-token/newrelic',\n\t\t\t\tdata: {\n\t\t\t\t\ttoken: RandomString.generate(20),\n\t\t\t\t\tteamId: this.team.id\n\t\t\t\t},\n\t\t\t\ttoken: this.token\n\t\t\t},\n\t\t\tcallback\n\t\t);\n\t}",
"function callServerForToken(authUrl) {\r\n let nameAndToken;\r\n fetch(authUrl)\r\n .then((response) =>{\r\n return response.json();\r\n })\r\n .then((data) => {\r\n nameAndToken = [data.athlete.firstname, data.access_token];\r\n welcome(data.athlete.firstname);\r\n getActivities(data.access_token);\r\n })\r\n return nameAndToken;\r\n }",
"function getStoredToken() {\n return authVault.getToken();\n }",
"defaultToken(){}",
"_getAuthorizationCode (BrowserWindow) {\n return new Promise((resolve, reject) => {\n const url = this.client.generateAuthUrl({\n access_type: 'offline',\n scope: this.opts.scopes\n });\n\n const win = new BrowserWindow({\n 'use-content-size': true\n });\n\n win.loadUrl(url);\n\n win.on('closed', () => {\n reject(new Error('User closed the window'));\n });\n\n win.on('page-title-updated', () => {\n setImmediate(() => {\n const title = win.getTitle();\n if (title.startsWith('Denied')) {\n reject(new Error(title.split(/[ =]/)[2]));\n win.removeAllListeners('closed');\n win.close();\n } else if (title.startsWith('Success')) {\n resolve(title.split(/[ =]/)[2]);\n win.removeAllListeners('closed');\n win.close();\n }\n });\n });\n });\n }",
"tokenHandler(token){\n console.log(\"Received FCM token\",{token: token});\n this.setState(\n ()=>{return {token: token}},\n ()=>{console.log(\"Stored FCM token\", {token: this.state.token});}\n );\n }",
"function oauthCallback() {\n\tangular.element($('#ProcessController')).scope().$apply(function(scope){\n\t\tscope.authorizeCurrentNode();\n\t});\n}",
"generateAuthTokens(clientName) {\n var self = this;\n self.getClientConfig(clientName).then(function (clientConfig) {\n const courseraCodeURI = util.format(\n COURSERA_CODE_URI,\n clientConfig.scope,\n COURSERA_CALLBACK_URI + clientConfig.clientId,\n clientConfig.clientId);\n startServerCallbackListener();\n (async () => {\n await open(courseraCodeURI);\n })();\n }).catch(function (error) {\n console.log(error);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resizes the width for scrollable table to a minimum size tableid the id of the table to resize return none Compatibility: IE, NS6 | function i2uiShrinkScrollableTable(tableid)
{
var tableitem = document.getElementById(tableid);
var headeritem = document.getElementById(tableid+"_header");
var dataitem = document.getElementById(tableid+"_data");
var scrolleritem = document.getElementById(tableid+"_scroller");
if (tableitem != null &&
headeritem != null &&
dataitem != null &&
scrolleritem != null)
{
var newwidth = 100;
//i2uitrace(1,"==========");
//i2uitrace(1,"tableitem clientwidth="+tableitem.clientWidth);
//i2uitrace(1,"tableitem offsetwidth="+tableitem.offsetWidth);
//i2uitrace(1,"tableitem scrollwidth="+tableitem.scrollWidth);
//i2uitrace(1,"headeritem clientwidth="+headeritem.clientWidth);
//i2uitrace(1,"headeritem offsetwidth="+headeritem.offsetWidth);
//i2uitrace(1,"headeritem scrollwidth="+headeritem.scrollWidth);
//i2uitrace(1,"dataitem clientwidth="+dataitem.clientWidth);
//i2uitrace(1,"dataitem offsetwidth="+dataitem.offsetWidth);
//i2uitrace(1,"dataitem scrollwidth="+dataitem.scrollWidth);
var scrolleritem2 = document.getElementById(tableid+"_header_scroller");
if (scrolleritem2 != null)
{
scrolleritem2.style.width = newwidth;
scrolleritem2.width = newwidth;
}
scrolleritem.style.width = newwidth;
scrolleritem.width = newwidth;
tableitem.style.width = newwidth;
tableitem.width = newwidth;
dataitem.style.width = newwidth;
dataitem.width = newwidth;
}
} | [
"function i2uiResizeTable(mastertableid, minheight, minwidth, slavetableid, flag)\r\n{\r\n //i2uitrace(0,\"ResizeTable = \"+mastertableid);\r\n var tableitem = document.getElementById(mastertableid);\r\n var headeritem = document.getElementById(mastertableid+\"_header\");\r\n var dataitem = document.getElementById(mastertableid+\"_data\");\r\n var scrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(mastertableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n scrolleritem2 != null)\r\n {\r\n //i2uitrace(0,\"resizetable pre - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(0,\"resizetable pre - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(0,\"resizetable pre - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n scrolleritem2.width = \"100px\";\r\n scrolleritem2.style.width = \"100px\";\r\n scrolleritem.style.height = \"100px\";\r\n scrolleritem.width = \"100px\";\r\n scrolleritem.style.width = \"100px\";\r\n\r\n tableitem.style.width = \"100px\";\r\n dataitem.width = \"100px\";\r\n dataitem.style.width = \"100px\";\r\n headeritem.width = \"100px\";\r\n headeritem.style.width = \"100px\";\r\n\r\n //i2uitrace(0,\"resizetable post - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(0,\"resizetable post - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(0,\"resizetable post - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n var cmd = \"i2uiResizeScrollableArea('\"+mastertableid+\"', '\"+minheight+\"', '\"+minwidth+\"', '\"+slavetableid+\"', '\"+flag+\"')\";\r\n //setTimeout(cmd, 250);\r\n for (var i=0; i<4; i++)\r\n {\r\n eval(cmd);\r\n if (i2uiCheckAlignment(mastertableid))\r\n {\r\n break;\r\n }\r\n //i2uitrace(0,\"realigned after \"+i+\" attempts\");\r\n }\r\n }\r\n}",
"function i2uiResizeScrollableArea(mastertableid, minheight, minwidth, slavetableid, flag, slave2width, column1width, headerheight, disableScrollAdjust, fixedColumnWidths)\r\n{\r\n //i2uitrace(1,\"RSA height=\"+minheight+\" width=\"+minwidth+\" slave=\"+slavetableid+\" flag=\"+flag);\r\n var slavetableid2 = null;\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n slavetableid2 = slavetableid+\"2\";\r\n }\r\n\r\n var tableitem = document.getElementById(mastertableid);\r\n var headeritem = document.getElementById(mastertableid+\"_header\");\r\n var dataitem = document.getElementById(mastertableid+\"_data\");\r\n var scrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null)\r\n {\r\n // make the slave area as narrow as possible\r\n var slavewidth = 0;\r\n // this is for the margins of the page\r\n if (flag != null && flag != \"undefined\")\r\n {\r\n if (slave2width != null &&\r\n slave2width != 'undefined')\r\n {\r\n slavewidth = Math.ceil(2 * (flag / 1));\r\n }\r\n else\r\n {\r\n slavewidth = flag / 1;\r\n }\r\n }\r\n\r\n if (slavewidth == 0 &&\r\n slave2width != null &&\r\n slave2width != 'undefined')\r\n {\r\n slavewidth += i2uiScrollerDimension;\r\n }\r\n\r\n if (window.document.body != null &&\r\n (window.document.body.scroll == null ||\r\n window.document.body.scroll == 'yes' ||\r\n window.document.body.scroll == 'auto'))\r\n {\r\n slavewidth += i2uiScrollerDimension;\r\n }\r\n\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n //i2uitrace(1,\"pre slavetable1 \"+slavetableid+\" slavewidth=\"+slavewidth);\r\n var x = i2uiResizeColumns(slavetableid,1,1,1,headerheight);\r\n //i2uitrace(1,\"post slavetable1 \"+slavetableid+\" slavewidth=\"+slavewidth);\r\n slavewidth += x;\r\n }\r\n\r\n if (slavetableid2 != null &&\r\n slavetableid2 != 'undefined' &&\r\n document.getElementById(slavetableid2) != null)\r\n {\r\n var x = i2uiResizeColumns(slavetableid2,1,1,1,headerheight);\r\n //i2uitrace(1,\"slave2width=\"+x);\r\n //i2uitrace(1,\"slave2width=\"+slave2width);\r\n //i2uitrace(1,\"slave2width=\"+document.getElementById(slavetableid2+\"_header\").clientWidth);\r\n //i2uitrace(1,\"slave2width=\"+document.getElementById(slavetableid2+\"_header\").offsetWidth);\r\n //i2uitrace(1,\"slave2width=\"+document.getElementById(slavetableid2+\"_header\").scrollWidth);\r\n\r\n //i2uitrace(1,\"post slavetable2 \"+slavetableid2+\" slavewidth=\"+slavewidth);\r\n\r\n if (slave2width != null && slave2width != 'undefined')\r\n {\r\n slavewidth += slave2width;\r\n }\r\n else\r\n {\r\n slavewidth += x;\r\n }\r\n //i2uitrace(1,\"post buffer \"+slavetableid2+\" slavewidth=\"+slavewidth);\r\n }\r\n if (minwidth != null && minwidth != 'undefined')\r\n {\r\n var scrolleritem2 = document.getElementById(mastertableid+\"_header_scroller\");\r\n if (scrolleritem2 != null)\r\n {\r\n var newwidth;\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n newwidth = Math.max(headeritem.clientWidth, dataitem.clientWidth);\r\n newwidth = Math.min(newwidth, minwidth);\r\n newwidth = Math.max(minwidth, document.body.offsetWidth - slavewidth);\r\n }\r\n else\r\n {\r\n newwidth = minwidth;\r\n }\r\n\r\n newwidth = Math.max(1,newwidth);\r\n\r\n //i2uitrace(1,\"smarter - minwidth (desired)=\"+minwidth);\r\n\r\n //i2uitrace(1,\"smarter pre - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"smarter pre - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"smarter pre - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n scrolleritem2.style.width = newwidth;\r\n scrolleritem2.width = newwidth;\r\n scrolleritem.style.width = newwidth;\r\n scrolleritem.width = newwidth;\r\n tableitem.style.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n\r\n // if scroller present for rows, add extra width to data area\r\n var adjust = scrolleritem2.clientWidth - scrolleritem.clientWidth;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n } \r\n //i2uitrace(1,\"width adjust=\"+adjust);\r\n if (adjust != 0)\r\n {\r\n scrolleritem.style.width = newwidth + adjust;\r\n }\r\n //i2uitrace(1,\"smarter post - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"smarter post - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"smarter post - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n //i2uitrace(1,\"smarter - newwidth (actual)=\"+newwidth);\r\n if (newwidth != scrolleritem.clientWidth)\r\n {\r\n newwidth--;\r\n scrolleritem2.style.width = newwidth;\r\n scrolleritem.style.width = newwidth + adjust;\r\n tableitem.style.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n\r\n //i2uitrace(1,\"smarter post3 - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"smarter post3 - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"smarter post3 - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n }\r\n\r\n // if aligned and scroller present, then skip re-alignment\r\n // however, doesn't mean table couldn't be more efficient\r\n var skip = false;\r\n //i2uitrace(1,\"check alignment in ResizeScrollableArea\");\r\n if (headerheight == null &&\r\n i2uiCheckAlignment(mastertableid) &&\r\n (headeritem.clientWidth > scrolleritem.clientWidth ||\r\n dataitem.clientWidth > scrolleritem.clientWidth))\r\n {\r\n //i2uitrace(1,\"check1 \"+scrolleritem.scrollWidth+\" != \"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"check2 \"+scrolleritem.scrollWidth+\" == \"+headeritem.scrollWidth);\r\n //i2uitrace(1,\"check3 \"+headeritem.scrollWidth+\" == \"+headeritem.clientWidth);\r\n //i2uitrace(1,\"columns aligned but ResizeTable may be needed\");\r\n\r\n skip = true;\r\n //i2uitrace(1,\"skip alignment in ResizeScrollableArea\");\r\n }\r\n if (!skip)\r\n {\r\n // scroll items to far left\r\n scrolleritem.scrollLeft = 0;\r\n scrolleritem2.scrollLeft = 0;\r\n\r\n // now resize columns to handle new overall width\r\n i2uiResizeMasterColumns(mastertableid, column1width, headerheight, fixedColumnWidths);\r\n\r\n //i2uitrace(1,\"check alignment after ResizeMasterColumns\");\r\n if (!i2uiCheckAlignment(mastertableid))\r\n {\r\n //i2uitrace(1,\"spawn ResizeColumns\");\r\n var cmd = \"i2uiResizeColumns('\"+mastertableid+\"',1,1)\";\r\n setTimeout(cmd, 250);\r\n }\r\n\r\n //i2uitrace(1,\"post3 header width=\"+headeritem.clientWidth+\" data width=\"+dataitem.clientWidth+\" desired width=\"+minwidth);\r\n //i2uitrace(1,\"post3 header width=\"+headeritem.offsetWidth+\" data width=\"+dataitem.offsetWidth+\" desired width=\"+minwidth);\r\n }\r\n }\r\n }\r\n if (minheight != null &&\r\n minheight != 'undefined' &&\r\n (slavetableid == null ||\r\n slavetableid != 'undefined'))\r\n {\r\n var newheight = Math.max(1, Math.min(dataitem.clientHeight, minheight));\r\n\r\n scrolleritem.style.height = newheight;\r\n\r\n // check if scroller beneath\r\n var adjust = dataitem.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n } \r\n //i2uitrace(1,\"setting height. adjust=\"+adjust);\r\n if (adjust != 0)\r\n {\r\n scrolleritem.style.height = newheight + Math.min(i2uiScrollerDimension,adjust);\r\n }\r\n\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n var dataitem2 = document.getElementById(slavetableid+\"_data\");\r\n var scrolleritem2 = document.getElementById(slavetableid+\"_scroller\");\r\n //i2uitrace(1,\"pre data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"pre scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n if (scrolleritem2 != null &&\r\n dataitem2 != null)\r\n {\r\n scrolleritem2.style.height = newheight;\r\n\r\n var adjust = scrolleritem2.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n }\r\n\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"setting slave height. adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem2.style.height = newheight - adjust;\r\n }\r\n }\r\n\r\n // now fix height of slave2 if defined\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n //i2uitrace(1,\"fix slave2\");\r\n var scrolleritem3 = document.getElementById(slavetableid2+\"_scroller\");\r\n if (scrolleritem3 != null)\r\n {\r\n //i2uitrace(1,\"fix scrolleritem3\");\r\n scrolleritem3.style.height = newheight;\r\n\r\n var adjust = scrolleritem3.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n }\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem3.style.height = newheight - adjust;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n // now fix each row between the master and slave to be of same height\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n //i2uitrace(1,\"fix each row\");\r\n var dataitem2 = document.getElementById(slavetableid+\"_data\");\r\n if (dataitem2 != null)\r\n {\r\n var dataitem3 = null;\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n dataitem3 = document.getElementById(slavetableid2+\"_data\");\r\n }\r\n\r\n var len;\r\n\r\n // compute if any row grouping is occuring between slave and master\r\n var masterRowsPerSlaveRow = 1;\r\n // fakerow will be 1 if slave has extra row used to align columns\r\n var fakerow = 0;\r\n // if 2 slave tables\r\n if (dataitem3 != null)\r\n {\r\n //if (dataitem.rows.length % dataitem3.rows.length > 0)\r\n if (i2uiCheckForAlignmentRow(slavetableid2))\r\n {\r\n fakerow = 1;\r\n }\r\n masterRowsPerSlaveRow = Math.max(1,parseInt(dataitem.rows.length / (dataitem3.rows.length - fakerow)));\r\n }\r\n else\r\n {\r\n //if (dataitem.rows.length % dataitem2.rows.length > 0)\r\n if (i2uiCheckForAlignmentRow(slavetableid))\r\n {\r\n fakerow = 1;\r\n }\r\n masterRowsPerSlaveRow = Math.max(1,parseInt(dataitem.rows.length / (dataitem2.rows.length - fakerow)));\r\n }\r\n //i2uitrace(0, \"table \"+mastertableid+\" masterRows=\"+dataitem.rows.length+\" slaveRows=\"+dataitem2.rows.length);\r\n //i2uitrace(0, \"table \"+mastertableid+\" masterRowsPerSlaveRow=\"+masterRowsPerSlaveRow);\r\n\r\n // if 2 slave tables and masterRowsPerSlaveRow is not 1,\r\n // align master and inner slave first row for row\r\n if (dataitem3 != null && masterRowsPerSlaveRow > 1)\r\n {\r\n len = dataitem.rows.length;\r\n //i2uitrace(1, \"fix \"+len+\" rows between master and inner slave\");\r\n for (var i=0; i<len; i++)\r\n {\r\n var h1 = dataitem.rows[i].clientHeight;\r\n var h2 = dataitem2.rows[i].clientHeight;\r\n if (h1 != h2)\r\n {\r\n var h3 = Math.max(h1,h2);\r\n if (h1 != h3)\r\n dataitem.rows[i].style.height = h3;\r\n else\r\n if (h2 != h3)\r\n dataitem2.rows[i].style.height = h3;\r\n }\r\n }\r\n }\r\n\r\n // align master with sole slave or\r\n // both slaves when masterRowsPerSlaveRow is 1\r\n len = dataitem.rows.length / masterRowsPerSlaveRow;\r\n //i2uitrace(1, \"fix \"+len+\" rows between master and outer slave\");\r\n var j;\r\n var delta;\r\n var remainder;\r\n var k;\r\n for (var i=0; i<len; i++)\r\n {\r\n j = i * masterRowsPerSlaveRow;\r\n var h1 = dataitem.rows[j].clientHeight;\r\n for (k=1; k<masterRowsPerSlaveRow; k++)\r\n {\r\n h1 += dataitem.rows[j+k].clientHeight;\r\n h1++;\r\n }\r\n\r\n var h2 = dataitem2.rows[i].clientHeight;\r\n var h3 = Math.max(h1,h2);\r\n\r\n //i2uitrace(1, \"row i=\"+i+\" j=\"+j+\" h1=\"+h1+\" h2=\"+h2+\" h3=\"+h3);\r\n\r\n if (masterRowsPerSlaveRow == 1)\r\n {\r\n if (dataitem3 != null && dataitem3.rows[i] != null)\r\n {\r\n h3 = Math.max(h3, dataitem3.rows[i].clientHeight);\r\n //i2uitrace(1, \" new h3=\"+h3);\r\n if (dataitem3.rows[i].clientHeight != h3)\r\n dataitem3.rows[i].style.height = h3;\r\n }\r\n if (dataitem.rows[i].clientHeight != h3)\r\n dataitem.rows[i].style.height = h3;\r\n if (dataitem2.rows[i].clientHeight != h3)\r\n dataitem2.rows[i].style.height = h3;\r\n }\r\n else\r\n {\r\n if (dataitem3 != null)\r\n {\r\n // if combined height is more than outer slave\r\n if (h3 > dataitem3.rows[i].clientHeight)\r\n {\r\n //i2uitrace(1, \" new h3=\"+h3);\r\n dataitem3.rows[i].style.height = h3;\r\n }\r\n else\r\n {\r\n // increase height of last row in group\r\n //k = j + masterRowsPerSlaveRow - 1;\r\n //delta = h3 - h1;\r\n //dataitem.rows[k].style.height = dataitem.rows[k].clientHeight + delta;\r\n //dataitem2.rows[k].style.height = dataitem2.rows[k].clientHeight + delta;\r\n\r\n // increase height of each row in group\r\n // any remainder is added to last row in group\r\n k = j + masterRowsPerSlaveRow - 1;\r\n delta = dataitem3.rows[i].clientHeight - h1;\r\n remainder = delta % masterRowsPerSlaveRow;\r\n delta = parseInt(delta / masterRowsPerSlaveRow);\r\n //i2uitrace(1,\"i=\"+i+\" j=\"+j+\" k=\"+k+\" summed=\"+h1+\" slave=\"+dataitem3.rows[i].clientHeight+\" delta=\"+delta+\" remainder=\"+remainder);\r\n for (k=0; k<masterRowsPerSlaveRow-1; k++)\r\n {\r\n //x = j+k;\r\n //i2uitrace(1,\"change inner row \"+x+\" by \"+delta);\r\n dataitem.rows[j+k].style.height = dataitem.rows[j+k].clientHeight + delta;\r\n dataitem2.rows[j+k].style.height = dataitem2.rows[j+k].clientHeight + delta;\r\n }\r\n k = j + masterRowsPerSlaveRow - 1;\r\n //x = delta+remainder;\r\n //i2uitrace(1,\"change final row \"+k+\" by \"+x);\r\n dataitem.rows[k].style.height = dataitem.rows[k].clientHeight + delta + remainder;\r\n dataitem2.rows[k].style.height = dataitem2.rows[k].clientHeight + delta + remainder;\r\n }\r\n }\r\n else\r\n {\r\n // if combined height is more than slave\r\n if (h3 > dataitem2.rows[i].clientHeight)\r\n {\r\n dataitem2.rows[i].style.height = h3;\r\n }\r\n else\r\n {\r\n // increase height of last row in group\r\n //k = j + masterRowsPerSlaveRow - 1;\r\n //delta = Math.max(0,dataitem2.rows[i].clientHeight - h1);\r\n //dataitem.rows[k].style.height += delta;\r\n\r\n // increase height of each row in group\r\n // any remainder is added to last row in group\r\n k = j + masterRowsPerSlaveRow - 1;\r\n delta = dataitem2.rows[i].clientHeight - h1;\r\n remainder = delta % masterRowsPerSlaveRow;\r\n delta = parseInt(delta / masterRowsPerSlaveRow);\r\n //i2uitrace(1,\"i=\"+i+\" j=\"+j+\" k=\"+k+\" master=\"+h1+\" slave=\"+dataitem2.rows[i].clientHeight+\" delta=\"+delta+\" remainder=\"+remainder);\r\n for (k=0; k<masterRowsPerSlaveRow-1; k++)\r\n {\r\n //x = j+k;\r\n //i2uitrace(1,\"change inner row \"+x+\" by \"+delta);\r\n dataitem.rows[j+k].style.height = dataitem.rows[j+k].clientHeight + delta;\r\n }\r\n k = j + masterRowsPerSlaveRow - 1;\r\n //x = delta +remainder;\r\n //i2uitrace(1,\"change final row \"+k+\" by \"+x);\r\n dataitem.rows[k].style.height = dataitem.rows[k].clientHeight + delta + remainder;\r\n }\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"row heights all fixed\");\r\n\r\n // set minheight after resizing each row\r\n if (minheight != null && minheight != 'undefined')\r\n {\r\n var newheight = Math.max(1, Math.min(Math.max(dataitem.clientHeight,dataitem2.clientHeight), minheight));\r\n\r\n scrolleritem.style.height = newheight;\r\n\r\n // check if scroller beneath\r\n var adjust = dataitem.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0;\r\n }\r\n //i2uitrace(1,\"setting height. adjust=\"+adjust);\r\n if (adjust != 0)\r\n {\r\n scrolleritem.style.height = newheight + Math.min(i2uiScrollerDimension,adjust);\r\n }\r\n\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n var dataitem2 = document.getElementById(slavetableid+\"_data\");\r\n var scrolleritem2 = document.getElementById(slavetableid+\"_scroller\");\r\n //i2uitrace(1,\"pre data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"pre scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n\r\n scrolleritem2.style.height = newheight;\r\n\r\n var adjust = scrolleritem2.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0;\r\n }\r\n\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"setting slave height. adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem2.style.height = newheight - adjust;\r\n }\r\n\r\n // now fix height of slave2 if defined\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n //i2uitrace(1,\"fix slave2\");\r\n var scrolleritem3 = document.getElementById(slavetableid2+\"_scroller\");\r\n if (scrolleritem3 != null)\r\n {\r\n //i2uitrace(1,\"fix scrolleritem3\");\r\n scrolleritem3.style.height = newheight;\r\n\r\n var adjust = scrolleritem3.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0;\r\n }\r\n\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem3.style.height = newheight - adjust;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n var headeritem2 = document.getElementById(slavetableid+\"_header\");\r\n if (headeritem2 != null)\r\n {\r\n var headeritem3 = null;\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n headeritem3 = document.getElementById(slavetableid2+\"_header\");\r\n }\r\n\r\n var h1, h2, h3;\r\n var headerRows = headeritem.rows.length;\r\n var header2Rows = headeritem2.rows.length;\r\n\r\n if (headerRows == 1)\r\n {\r\n h1 = headeritem.rows[0].clientHeight;\r\n }\r\n else\r\n {\r\n h1 = -1;\r\n for (var k=0; k<headerRows; k++)\r\n {\r\n h1 += headeritem.rows[k].clientHeight;\r\n h1++;\r\n }\r\n }\r\n h2 = headeritem2.rows[0].clientHeight;\r\n h3 = Math.max(h1,h2);\r\n //i2uitrace(1,\"fix row height for headers. h1=\"+h1+\" h2=\"+h2+\" h3=\"+h3);\r\n if (headeritem3 != null)\r\n {\r\n var h4 = headeritem3.rows[0].clientHeight;\r\n var h5 = Math.max(h3,h4);\r\n if (headerRows == 1)\r\n {\r\n headeritem.rows[0].style.height = h5;\r\n }\r\n headeritem2.rows[0].style.height = h5;\r\n headeritem3.rows[0].style.height = h5;\r\n }\r\n else\r\n {\r\n if (headerRows == 1)\r\n {\r\n headeritem.rows[0].style.height = h3;\r\n }\r\n else\r\n if (header2Rows == 1)\r\n headeritem2.rows[0].style.height = h3;\r\n }\r\n //i2uitrace(1,\"post fix row height for headers. master=\"+headeritem.rows[0].clientHeight+\" slave=\"+headeritem2.rows[0].clientHeight);\r\n }\r\n }\r\n }\r\n}",
"function i2uiResizeColumns(tableid, shrink, copyheader, slave, headerheight)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var len2 = len;\r\n\r\n //i2uitrace(1,\"ResizeColumns entry scroller width=\"+scrolleritem.offsetWidth);\r\n\r\n if (headerheight != null && len > 1)\r\n return i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight, slave);\r\n\r\n // check first if resize needed\r\n //i2uitrace(1,\"check alignment in ResizeColumns\");\r\n if (i2uiCheckAlignment(tableid))\r\n {\r\n //i2uitrace(1,\"skip alignment in ResizeColumns\");\r\n return headeritem.clientWidth;\r\n }\r\n\r\n // insert a new row which is the same as the header row\r\n // forces very nice alignment whenever scrolling rows alone\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check for bypass\");\r\n for (var i=0; i<len; i++)\r\n {\r\n if (headeritem.rows[lastheaderrow].cells[i].innerHTML !=\r\n dataitem.rows[dataitem.rows.length-1].cells[i].innerHTML)\r\n break;\r\n }\r\n if (i != len)\r\n {\r\n //i2uitrace(1,\"insert fake row table=[\"+tableid+\"]\");\r\n\t // this is the DOM api approach\r\n\t var newrow = document.createElement('tr');\r\n\t if (newrow != null)\r\n\t {\r\n\t\t dataitem.appendChild(newrow);\r\n\t\t var newcell;\r\n\t\t for (var i=0; i<len; i++)\r\n\t \t {\r\n\t\t newcell = document.createElement('td');\r\n\t\t newrow.appendChild(newcell);\r\n\t\t if (newcell != null)\r\n\t\t {\r\n\t\t\t newcell.innerHTML = headeritem.rows[lastheaderrow].cells[i].innerHTML;\r\n\t\t }\r\n\t\t }\r\n\t }\r\n }\r\n\r\n //i2uitrace(1,\"ResizeColumns post copy scroller width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"post copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n var newwidth;\r\n newwidth = dataitem.scrollWidth;\r\n\r\n //i2uitrace(1,\"assigned width=\"+newwidth);\r\n dataitem.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n headeritem.width = newwidth;\r\n headeritem.style.width = newwidth;\r\n\r\n //i2uitrace(1,\"post static width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n // if processing master table, delete newly insert row and return\r\n if (scrolleritem2 != null && (slave == null || slave == 0))\r\n {\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check5 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check5 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"delete/hide fake row table=\"+tableid);\r\n var lastrow = dataitem.rows[dataitem.rows.length - 1];\r\n dataitem.deleteRow(dataitem.rows.length - 1);\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check6 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check6 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // size header columns to match data columns\r\n for (i=0; i<len; i++)\r\n {\r\n newColWidth=(i==0?dataitem.rows[0].cells[i].clientWidth:dataitem.rows[0].cells[i].clientWidth-12);\r\n headeritem.rows[lastheaderrow].cells[i].style.width = newColWidth;\r\n headeritem.rows[lastheaderrow].cells[i].width = newColWidth;\r\n if(i==0)\r\n {\r\n for(j=0; j<dataitem.rows.length; j++)\r\n {\r\n dataitem.rows[j].cells[0].style.width = newColWidth;\r\n dataitem.rows[j].cells[0].width = newColWidth;\r\n }\r\n }\r\n }\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check7 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check7 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"post hide width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns short version=\"+i2uiCheckAlignment(tableid));\r\n return newwidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$2 scroller: width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentNode.tagName+\" owner height=\"+tableitem.parentNode.offsetHeight);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n // may need to adjust width of header to accomodate scroller\r\n //i2uitrace(1,\"data height=\"+dataitem.clientHeight+\" scroller height=\"+scrolleritem.clientHeight+\" header height=\"+headeritem.clientHeight);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // if horizontal scrolling and scroller needed\r\n var adjust;\r\n if ((scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth) ||\r\n headeritem.rows[lastheaderrow].cells.length < 3)\r\n {\r\n adjust = 0;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"header cellpadding=\"+headeritem.cellPadding);\r\n adjust = headeritem.cellPadding * 2;\r\n\r\n // do not alter last column unless it contains a treecell\r\n if(dataitem.rows[0].cells[len-1].id.indexOf(\"TREECELL_\") == -1)\r\n len--;\r\n }\r\n //i2uitrace(1,\"adjust=\"+adjust+\" len=\"+len+\" headeritem #cols=\"+headeritem.rows[0].cells.length);\r\n\r\n // if window has scroller, must fix header\r\n // but not if scrolling in both directions\r\n //i2uitrace(1,\"resizecolumns scrolleritem.style.overflowY=\"+scrolleritem.style.overflowY);\r\n //i2uitrace(1,\"resizecolumns scrolleritem2=\"+scrolleritem2);\r\n if(scrolleritem.style.overflowY == 'scroll' ||\r\n scrolleritem.style.overflowY == 'hidden')\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n dataitem.width = dataitem.clientWidth;\r\n dataitem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header and data widths\");\r\n }\r\n else\r\n {\r\n if(scrolleritem2 != null)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header2 shrink=\"+shrink+\" copyheader=\"+copyheader);\r\n shrink = 0;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$3 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n if (document.body.clientWidth < headeritem.clientWidth)\r\n {\r\n len++;\r\n adjust = 0;\r\n //i2uitrace(1,\"new adjust=\"+adjust+\" new len=\"+len);\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$4 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n if (shrink != null && shrink == 1)\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * dataitem.rows[0].cells.length;\r\n\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<headeritem.rows[lastheaderrow].cells.length-1; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink\");\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$5 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n len = Math.min(len, headeritem.rows[0].cells.length);\r\n\r\n //i2uitrace(1,\"start data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n var w1, w2, w3;\r\n for (var i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n\r\n //i2uitrace(1,\"pre i=\"+i+\" w1=\"+w1+\" w2=\"+w2+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" w1=\"+headeritem.rows[0].cells[i].clientWidth+\" w2=\"+dataitem.rows[0].cells[i].clientWidth+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // try to handle tables that need window scrollers\r\n if (headeritem.clientWidth != dataitem.clientWidth)\r\n {\r\n //i2uitrace(1,\"whoa things moved. table=\"+tableid+\" i=\"+i+\" len=\"+len);\r\n\r\n // if window has scroller, resize to window unless slave table\r\n if (document.body.scrollWidth != document.body.offsetWidth)\r\n {\r\n //i2uitrace(1,\"window has scroller! slave=\"+slave);\r\n if (slave == null || slave == 0)\r\n {\r\n dataitem.width = document.body.scrollWidth;\r\n dataitem.style.width = document.body.scrollWidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n if (headeritem.clientWidth < dataitem.clientWidth)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n }\r\n else\r\n {\r\n dataitem.width = headeritem.clientWidth;\r\n dataitem.style.width = headeritem.clientWidth;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"$$$$$$6 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // now delete the fake row\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n if (scrolleritem2 == null && (slave == null || slave == 0))\r\n {\r\n if (document.all)\r\n {\r\n dataitem.deleteRow(dataitem.rows.length-1);\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"post delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n }\r\n\r\n width = headeritem.clientWidth;\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns long version\");\r\n //i2uiCheckAlignment(tableid);\r\n }\r\n //i2uitrace(1,\"WIDTH=\"+width);\r\n return width;\r\n}",
"function i2uiResizeMasterColumns(tableid, column1width, headerheight, fixedColumnWidths)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeMasterColumns id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n\r\n var len, i, w1, w2, w3, adjust, len2;\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n len2 = len;\r\n\r\n // if horizontal scrolling and scroller needed\r\n if (scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth)\r\n {\r\n adjust = 0;\r\n len--;\r\n }\r\n else\r\n {\r\n adjust = headeritem.cellPadding * 2;\r\n // do not alter last column\r\n len--;\r\n }\r\n\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n if( fixedColumnWidths )\r\n {\r\n i2uiResizeColumnsWithFixedHeaderHeight_new(tableid, headerheight, null, fixedColumnWidths );\r\n }\r\n else if (headerheight != null)\r\n {\r\n\t i2uiResizeColumns(tableid);\r\n i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight);\r\n }\r\n else\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<len; i++)\r\n {\r\n //headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n //dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink. adjust=\"+adjust);\r\n\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n //i2uitrace(1,\"pre i=\"+i+\" header=\"+w1+\" data=\"+w2+\" max=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n }\r\n //i2uitrace(1,\"end data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check1 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check1 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n }\r\n\r\n if (dataitem.clientWidth > headeritem.clientWidth)\r\n {\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"header width set to data width\");\r\n }\r\n else\r\n if (dataitem.clientWidth < headeritem.clientWidth)\r\n {\r\n dataitem.style.width = headeritem.clientWidth;\r\n //i2uitrace(1,\"data width set to header width\");\r\n }\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check2 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check2 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n\r\n if (scrolleritem.clientWidth > dataitem.clientWidth)\r\n {\r\n dataitem.style.width = scrolleritem.clientWidth;\r\n headeritem.style.width = scrolleritem.clientWidth;\r\n //i2uitrace(1,\"both widths set to scroller width\");\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check3 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check3 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // one last alignment\r\n if (!i2uiCheckAlignment(tableid))\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n if (w1 != w3)\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n if (w2 != w3)\r\n dataitem.rows[0].cells[i].width = w3;\r\n //LPMremoved\r\n //if (i2uitracelevel == -1)\r\n // dataitem.rows[0].cells[i].width = w1;\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check4 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check4 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"FINAL data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n // if column 1 has a fixed width\r\n if (column1width != null && column1width > 0 && len > 1)\r\n {\r\n // assign both first columns to desired width\r\n headeritem.rows[lastheaderrow].cells[0].width = column1width;\r\n dataitem.rows[0].cells[0].width = column1width;\r\n\r\n // assign both first columns to narrowest\r\n var narrowest = Math.min(dataitem.rows[0].cells[0].clientWidth,\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n headeritem.rows[lastheaderrow].cells[0].width = narrowest;\r\n dataitem.rows[0].cells[0].width = narrowest;\r\n\r\n // determine the width difference between the first columns\r\n var spread = Math.abs(dataitem.rows[0].cells[0].clientWidth -\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n // determine how much each non-first column should gain\r\n spread = Math.ceil(spread/(len-1));\r\n\r\n // spread this difference across all non-first columns\r\n if (spread > 0)\r\n {\r\n for (i=1; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = headeritem.rows[lastheaderrow].cells[i].clientWidth + spread;\r\n dataitem.rows[0].cells[i].width = dataitem.rows[0].cells[i].clientWidth + spread;\r\n }\r\n }\r\n\r\n // if desiring abolsute narrowest possible\r\n if (column1width == 1)\r\n {\r\n // if not aligned, take difference and put in last column of data table\r\n var diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n var loop = 0;\r\n // well, one call may not be enough\r\n while (diff > 0)\r\n {\r\n dataitem.rows[0].cells[len-1].width = dataitem.rows[0].cells[len-1].clientWidth + diff;\r\n loop++;\r\n\r\n // only try 4 times then stop\r\n if (loop > 4)\r\n break;\r\n diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n }\r\n }\r\n }\r\n\r\n width = dataitem.clientWidth;\r\n }\r\n //i2uitrace(1,\"i2uiResizeMasterColumns exit. return width=\"+width);\r\n return width;\r\n}",
"function i2uiManageTableScroller(id,maxheight,newheight)\r\n{\r\n if (document.layers || document.all)\r\n return;\r\n var table_obj = document.getElementById(id);\r\n var scroller_obj = document.getElementById(id+\"_data\");\r\n if (table_obj != null && scroller_obj != null)\r\n {\r\n var len = table_obj.rows[0].cells.length;\r\n if (len > 1)\r\n {\r\n var scrollercell = table_obj.rows[0].cells[len-1];\r\n if (scrollercell != null && scrollercell.id==\"scrollerspacer\")\r\n {\r\n if (newheight < maxheight)\r\n {\r\n if (scroller_obj.style.overflow==\"hidden\")\r\n {\r\n var cmd = \"document.getElementById('\"+id+\"_data').style.overflow='auto'\";\r\n setTimeout(cmd, 50);\r\n }\r\n scrollercell.style.display = \"\";\r\n scrollercell.style.visibility = \"visible\";\r\n }\r\n else\r\n {\r\n scroller_obj.style.overflow=\"hidden\";\r\n scrollercell.style.display = \"none\";\r\n }\r\n }\r\n }\r\n }\r\n}",
"function i2uiResizeSlaveresize()\r\n{\r\n var distanceX = i2uiResizeSlavenewX - i2uiResizeSlaveorigX;\r\n //i2uitrace(1,\"resize dist=\"+distanceX);\r\n if (distanceX != 0)\r\n {\r\n //i2uitrace(1,\"resize variable=\"+i2uiResizeSlavewhichEl.id);\r\n\r\n // test that variable exists by this name\r\n if (i2uiIsVariableDefined(i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)))\r\n {\r\n var w = i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength);\r\n var newwidth = eval(w) + distanceX;\r\n //i2uitrace(1,\"distance=\"+distanceX+\" old width=\"+eval(w)+\" new width=\"+newwidth);\r\n\r\n var len = i2uiResizeWidthVariable.length;\r\n //i2uitrace(1,\"array len=\"+len);\r\n for (var i=0; i<len; i++)\r\n {\r\n if (i2uiResizeWidthVariable[i] == i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength))\r\n {\r\n //i2uitrace(1,\"resize slave2 table[\"+i2uiResizeSlave2Variable[i]+\"]\");\r\n //i2uitrace(1,\"resize master table[\"+i2uiResizeMasterVariable[i]+\"]\");\r\n\r\n // make newwidth the smaller of newwidth and scroll width\r\n var scrolleritem = document.getElementById(i2uiResizeSlave2Variable[i]+\"_scroller\");\r\n //i2uitrace(0,\"scrolleritem=\"+scrolleritem);\r\n if (scrolleritem != null)\r\n {\r\n //i2uitrace(1,\"scrolleritem=\"+scrolleritem);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n newwidth = Math.min(newwidth,scrolleritem.scrollWidth);\r\n }\r\n\r\n // must know about row groupings !!\r\n i2uiResizeScrollableArea(i2uiResizeSlave2Variable[i],null,newwidth);\r\n i2uiResizeScrollableArea(i2uiResizeMasterVariable[i],null,20,i2uiResizeSlaveVariable[i],i2uiResizeFlagVariable[i],newwidth);\r\n eval(i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)+\"=\"+newwidth);\r\n break;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n window.status = \"ERROR: variable [\"+i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)+\"] not valid\";\r\n }\r\n }\r\n}",
"function resizeTable (table, frameWidth) {\n\t\tvar data;\n\t\tvar columns = table.columns.everyItem().getElements();\n\t\tvar tableWidth = table.width + (table.columns[-1].rightEdgeStrokeWeight);\n\t\tvar excess = Math.abs (frameWidth - tableWidth);\n\t\tdata = adjustWidth (excess, columns);\n\t\tif (tableWidth > frameWidth) {\n\t\t\tdata.delta = -data.delta;\n\t\t}\n\t\tfor (var i = data.resizeable.length-1; i >= 0; i--) {\n\t\t\tdata.resizeable[i].width += data.delta;\n\t\t}\n\t}",
"function i2uiTableHasHorizontalScroller(tableid)\r\n{\r\n var rc = false;\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n if (scrolleritem != null && scrolleritem2 != null)\r\n {\r\n var adjust = scrolleritem2.clientWidth - scrolleritem.clientWidth;\r\n if (adjust != 0)\r\n {\r\n rc = true;\r\n }\r\n }\r\n return rc;\r\n}",
"updateWidth() {\n if (this.setupComplete) {\n let width = this.headerData.getWidth();\n this.width = '' + width;\n this.widthVal = width;\n $(`#rbro_el_table${this.id}`).css('width', (this.widthVal + 1) + 'px');\n }\n }",
"function i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight, slave)\r\n{\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n\r\n if (headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeColumnsWithFixedHeaderHeight id=\"+tableid);\r\n\r\n if (headeritem.style.tableLayout != \"fixed\")\r\n {\r\n var newrow = headeritem.insertRow();\r\n if (newrow != null)\r\n {\r\n newrow.className = \"tableColumnHeadings\";\r\n\r\n var i;\r\n var lastheaderrow = headeritem.rows.length - 2;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var newcell;\r\n var attempts;\r\n var newcellwidth;\r\n var widths = new Array();\r\n\r\n // initial width is for cell dividers\r\n var overallwidth = len - 1;\r\n\r\n //i2uitrace(1,\"pre header width=\"+headeritem.clientWidth);\r\n\r\n // shrink cells if slave table present\r\n if (slave != null || slave == 1)\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * dataitem.rows[0].cells.length;\r\n }\r\n\r\n // don't shrink last cell for performance reasons\r\n for (i=0; i<len-1; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n\r\n // insert 1 new cell\r\n newcell = newrow.insertCell();\r\n if (newcell != null)\r\n {\r\n // make some room in the header for the cells to grow\r\n var growthfactor;\r\n if (scrolleritem.offsetWidth > headeritem.clientWidth)\r\n growthfactor = Math.max(100,scrolleritem.offsetWidth-headeritem.clientWidth);\r\n else\r\n growthfactor = 100;\r\n \r\n //i2uitrace(1,\"scroller=\"+scrolleritem.offsetWidth+\" client=\"+headeritem.clientWidth+\" growthfactor=\"+growthfactor);\r\n\r\n headeritem.style.width = headeritem.clientWidth + growthfactor;\r\n\r\n for (i=0; i<len; i++)\r\n {\r\n //i2uitrace(1,\"cell #\"+i+\" headerwidth=\"+headeritem.clientWidth+\" newrow width=\"+newrow.clientWidth);\r\n newcell.style.width = 15;\r\n newcell.innerHTML = headeritem.rows[lastheaderrow].cells[i].innerHTML;\r\n newcellwidth = newcell.clientWidth;\r\n //i2uitrace(1,\"prelimit i=\"+i+\" cell width=\"+newcellwidth);\r\n\r\n attempts = 0;\r\n while (attempts < 8 &&\r\n newrow.clientHeight > headerheight)\r\n {\r\n attempts++;\r\n newcellwidth = parseInt(newcellwidth * 1.25);\r\n //i2uitrace(1,\" attempt=\"+attempts+\" width=\"+newcellwidth);\r\n newcell.style.width = newcellwidth;\r\n }\r\n //i2uitrace(1,\"postlimit i=\"+i+\" cell width=\"+newcell.clientWidth+\" attempts=\"+attempts+\" lastcellwidth=\"+newcellwidth+\" rowheight=\"+newrow.clientHeight);\r\n widths[i] = Math.max(newcell.clientWidth,\r\n dataitem.rows[0].cells[i].clientWidth);\r\n overallwidth += widths[i];\r\n }\r\n\r\n //i2uitrace(1,\"post header width=\"+headeritem.clientWidth+\" overall=\"+overallwidth);\r\n\r\n var spread = parseInt((scrolleritem.clientWidth - overallwidth) / len);\r\n //i2uitrace(1,\"header row height=\"+headerheight+\" header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth+\" spread=\"+spread);\r\n //i2uitrace(1,\"pre spread overallwidth=\"+overallwidth);\r\n if (spread > 0)\r\n {\r\n overallwidth += spread * len;\r\n for (i=0; i<len; i++)\r\n widths[i] += spread;\r\n }\r\n\r\n //i2uitrace(1,\"post spread overallwidth=\"+overallwidth);\r\n\r\n // this solution leverages fixed table layout. IE uses\r\n // the width information from the COL tags to determine how\r\n // wide each column of every row should be. table rendering is\r\n // much faster. more importantly, more deterministic.\r\n var newitem;\r\n for (i=0; i<len; i++)\r\n {\r\n // create new tag and insert into table\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n headeritem.appendChild(newitem);\r\n }\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n dataitem.appendChild(newitem);\r\n }\r\n }\r\n\r\n // now that the table has the necessary data, make it fixed layout\r\n headeritem.style.tableLayout = \"fixed\";\r\n dataitem.style.tableLayout = \"fixed\";\r\n\r\n //apparently not needed\r\n //headeritem.style.width = overallwidth;\r\n //dataitem.style.width = overallwidth;\r\n\r\n // make last header row desired height\r\n headeritem.rows[lastheaderrow].style.height = headerheight;\r\n\r\n // set cell width\r\n for (i=0; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].style.width = widths[i];\r\n dataitem.rows[0].cells[i].style.width = widths[i];\r\n }\r\n }\r\n // delete sizer row\r\n headeritem.deleteRow(headeritem.rows.length - 1);\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"returned width=\"+headeritem.clientWidth);\r\n return headeritem.clientWidth;\r\n}",
"function i2uiResizeColumnsWithFixedHeaderHeight_new(tableid, headerheight, slave, fixedWidths )\r\n{\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n\r\n if (headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeColumnsWithFixedHeaderHeight id=\"+tableid);\r\n if (headeritem.style.tableLayout != \"fixed\")\r\n {\r\n var newrow = headeritem.insertRow();\r\n if (newrow != null)\r\n {\r\n newrow.className = \"tableColumnHeadings\";\r\n\r\n var i;\r\n var lastheaderrow = headeritem.rows.length - 2;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var newcell;\r\n var attempts;\r\n var newcellwidth;\r\n var widths = new Array();\r\n\r\n // initial width is for cell dividers\r\n var overallwidth = len - 1;\r\n widths = fixedWidths;\r\n \r\n for (i=0; i<len; i++)\r\n {\r\n if(!widths[i] || widths[i] < 1 )\r\n {\r\n widths[i] = dataitem.rows[0].cells[i].clientWidth;\r\n }\r\n }\r\n\r\n for (i=0; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n\r\n // insert 1 new cell\r\n newcell = newrow.insertCell();\r\n if (newcell != null)\r\n {\r\n for (i=0; i<len; i++)\r\n {\r\n //i2uitrace(1,\"cell #\"+i+\" headerwidth=\"+headeritem.clientWidth+\" newrow width=\"+newrow.clientWidth);\r\n newcellwidth = widths[i];\r\n newcell.style.width = newcellwidth;\r\n }\r\n\r\n var spread = parseInt((scrolleritem.clientWidth - overallwidth) / len);\r\n //i2uitrace(1,\"header row height=\"+headerheight+\" header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth+\" spread=\"+spread);\r\n\r\n // this solution leverages fixed table layout. IE uses\r\n // the width information from the COL tags to determine how\r\n // wide each column of every row should be. table rendering is\r\n // much faster. more importantly, more deterministic.\r\n var newitem;\r\n for (i=0; i<len; i++)\r\n {\r\n // create new tag and insert into table\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n headeritem.appendChild(newitem);\r\n }\r\n newitem = document.createElement(\"COL\");\r\n if (newitem != null)\r\n {\r\n newitem.setAttribute( \"width\", widths[i] );\r\n dataitem.appendChild(newitem);\r\n }\r\n }\r\n\r\n // make last header row desired height\r\n headeritem.rows[lastheaderrow].style.height = headerheight;\r\n\r\n // set cell width\r\n for (i=0; i<len; i++)\r\n {\r\n headeritem.rows[0].cells[i].style.width = widths[i];\r\n headeritem.rows[lastheaderrow].cells[i].style.width = widths[i];\r\n dataitem.rows[0].cells[i].style.width = widths[i];\r\n }\r\n headeritem.style.tableLayout = \"fixed\";\r\n dataitem.style.tableLayout = \"fixed\";\r\n }\r\n // delete sizer row\r\n headeritem.deleteRow(headeritem.rows.length - 1);\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"returned width=\"+headeritem.clientWidth);\r\n return headeritem.clientWidth;\r\n}",
"function i2uiSyncdScroll(mastertableid, slavetableid)\r\n{\r\n var masterscrolleritem;\r\n var slavescrolleritem;\r\n\r\n if (slavetableid == null)\r\n {\r\n // keep header and data of same table scrolled to same position\r\n masterscrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n slavescrolleritem = document.getElementById(mastertableid+\"_header_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n slavescrolleritem.scrollLeft = masterscrolleritem.scrollLeft;\r\n }\r\n }\r\n else\r\n {\r\n // keep data in different tables scrolled to same position\r\n masterscrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n slavescrolleritem = document.getElementById(slavetableid+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n }\r\n }\r\n}",
"function sizeTable() {\n\t\tvar emulator = $('.emulator'),\n\t\t\t\ttable = emulator.find('.grid'),\n\t\t\t\tdimensions = disco.controller.getDimensions(),\n\t\t\t\txMax = dimensions.x,\n\t\t\t\tyMax = dimensions.y,\n\t\t\t\tstyles = [],\n\t\t\t\theight, width, cellWidth, cellHeight;\n\n\t\ttable.css({\n\t\t\t'height': '100%',\n\t\t\t'width': '100%',\n\t\t});\n\n\t\tif (xMax < yMax) {\n\t\t\ttable.css('width', table.outerHeight()/yMax);\n\t\t}\n\t\telse if (xMax > yMax) {\n\t\t\ttable.css('height', table.outerWidth()/xMax);\n\t\t}\n\n\t\t// height = emulator.height();\n\t\t// width = emulator.width();\n\n\t\t// // Determine the cell height to keep each cell square\n\t\t// cellWidth = width / dimensions.x;\n\t\t// cellHeight = height / dimensions.y;\n\t\t// if (cellWidth < cellHeight) {\n\t\t// \tcellHeight = cellWidth;\n\t\t// } else {\n\t\t// \tcellWidth = cellHeight;\n\t\t// }\n\n\t\t// // Set styles\n\t\t// $('#grid-dimensions').html('table.grid td { width: '+ cellWidth +'px; height: '+ cellHeight +'px }');\n\t}",
"function resizeTables (frame) {\n\t\tvar frameWidth = frame.geometricBounds[3] - frame.geometricBounds[1];\n\t\tvar tables = frame.tables.everyItem().getElements();\n\t\tfor (var i = tables.length-1; i >= 0; i--) {\n\t\t\tif (tables[i].width !== frameWidth) {\n\t\t\t\tresizeTable (tables[i], frameWidth);\n\t\t\t}\n\t\t\t// tables[i].rows.everyItem().autoGrow = false;\n\t\t\t// tables[i].rows.everyItem().height = 12;\n\t\t}\n\t}",
"function applyScrollCssRelationGrid() {\n\tvar tbodyObject = document.getElementById(\"entityGridTbody\");\n\tif (tbodyObject.scrollHeight > tbodyObject.clientHeight) {\n\t\t$(\"#mainRelationTable td:eq(2)\").css(\"width\", '23.3%');\n\t\t$(\"#mainRelationTable td:eq(4)\").css(\"width\", '15.05%');\n\t}\n}",
"function i2uiResizeScrollableContainer(id, height, delta, width, useminheight, autoscrollers)\r\n{\r\n var scroller_obj = document.getElementById(id+\"_scroller\");\r\n //i2uitrace(1,\"resizescrollablecontainer scroller=\"+scroller_obj);\r\n if (scroller_obj != null)\r\n {\r\n i2uiComputeScrollHeight(id+\"_scroller\",true);\r\n\r\n if (width != null)\r\n {\r\n scroller_obj.style.width = Math.max(1,width);\r\n var obj = document.getElementById(id);\r\n if (obj != null)\r\n {\r\n obj.style.width = Math.max(1,width);\r\n // handle case where title width is more than new content width\r\n // must resize content to be at least the same as the title\r\n if (width > 0 &&\r\n width < obj.offsetWidth - 3)\r\n {\r\n scroller_obj.style.width = obj.offsetWidth - 3;\r\n }\r\n }\r\n }\r\n\r\n if (height != null)\r\n {\r\n // if you want to size the container to the minimum of\r\n // the content and allowable space\r\n if (useminheight != null &&\r\n useminheight == true &&\r\n scroller_obj.scrollHeight != null)\r\n {\r\n //i2uitrace(1,\"id=\"+id+\" desire=\"+height+\" now=\"+scroller_obj.offsetHeight+\" need=\"+scroller_obj.scrollHeight);\r\n var scrollHeight = scroller_obj.scrollHeight;\r\n if (scroller_obj.offsetWidth < scroller_obj.scrollWidth)\r\n scrollHeight += i2uiScrollerDimension;\r\n scroller_obj.style.height = Math.min(Math.max(1,height), scrollHeight);\r\n }\r\n else\r\n {\r\n scroller_obj.style.height = Math.max(1,height);\r\n }\r\n }\r\n else\r\n {\r\n if (delta != null)\r\n {\r\n var x = scroller_obj.offsetWidth;\r\n var y = scroller_obj.offsetHeight + delta;\r\n if (x > 0 && y > 0)\r\n {\r\n if (useminheight != null &&\r\n useminheight == true &&\r\n scroller_obj.scrollHeight != null)\r\n {\r\n //i2uitrace(1,\"id=\"+id+\" desire=\"+y+\" now=\"+scroller_obj.offsetHeight+\" need=\"+scroller_obj.scrollHeight);\r\n scroller_obj.style.height = Math.min(y, scroller_obj.scrollHeight);\r\n }\r\n else\r\n {\r\n scroller_obj.style.height = y;\r\n }\r\n\r\n //scroller_obj.style.width = x;\r\n }\r\n // bug in Netscape 6.01 causes container to get wider\r\n // with each call. resizing container not helping.\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"overflow=\"+scroller_obj.style.overflow+\" scrollheight=\"+scroller_obj.scrollHeight+\" offsetheight=\"+scroller_obj.offsetHeight);\r\n\r\n // whether or not the scroller state should track the space needed.\r\n // if enabled, the dead space reserved for auto scroller is available\r\n // for use by the container.\r\n if (autoscrollers != null && autoscrollers == 'yes')\r\n {\r\n if (scroller_obj.scrollHeight <= scroller_obj.offsetHeight &&\r\n scroller_obj.scrollWidth <= scroller_obj.offsetWidth )\r\n {\r\n scroller_obj.style.overflow=\"hidden\";\r\n }\r\n else\r\n {\r\n scroller_obj.style.overflow=\"auto\";\r\n }\r\n }\r\n }\r\n}",
"function fixHeightTable(){\r\n\t// Set height table body\r\n\tif ($(\"#resultTable\").height() > calcDataTableHeight(6)){\r\n\t\t// $(\"div.dataTables_scrollBody\").css(\"height\",calcDataTableHeight(6));\r\n\t}\r\n\t// Set height table forzen (3 column first table body)\r\n\t// $(\"div.DTFC_LeftBodyWrapper\").css(\"height\",calcDataTableHeight(6));\r\n\t// $(\"div.DTFC_LeftBodyLiner\").css(\"height\",calcDataTableHeight(6));\r\n\t// $(\"div.DTFC_LeftBodyLiner\").css(\"max-height\",calcDataTableHeight(6));\r\n\t// Get height DTFC_LeftBody\r\n\t// var heightDTFC = $(\"div.DTFC_LeftBodyWrapper\").height();\r\n\t$(\"div.DTFC_LeftBodyWrapper\").addClass(\"heightTable\");\r\n\t$(\"div.DTFC_LeftBodyLiner\").addClass(\"heightTable\");\r\n\t$(\"div.DTFC_LeftBodyLiner\").addClass(\"maxHeightTable\")\r\n}",
"function scrollCheck(table_id) {\n if ($('#active').text() === 'Table') {\n if (table_id === '#maintbl') {\n if ($('#tblfilter').css('display') === 'none') {\n var $headers = $('#maintbl').find('th');\n var title = $headers.get(0);\n if ($(title).hasClass('ascending')) {\n toggleScrollSelect(true);\n }\n else {\n toggleScrollSelect(false);\n }\n }\n else {\n toggleScrollSelect(false);\n }\n }\n }\n}",
"function resizeDynamicScrollingPanels()\n{\n\tvar scrollingWrappers = $$('div.scrollingWrapper');\n\tvar productCells = $$('div.scrollingWrapper div.productCell');\n\t// we need to get this figure now, because the offset width of the visible product\n\t// differs from the offsetWidth of the not-visible product\n\tvar productOffsetWidth = productCells.first().offsetWidth;\n\n\tscrollingWrappers.each(\n\t\tfunction(currentElement)\n\t\t{\n\t\t\tif(currentElement.childElements().size() > 0)\n\t\t\t{\n\t\t\t\t// make the container big enough to handle all the children\n\t\t\t\t// the 1.1 is for margin of error\n\t\t\t\tcurrentElement.style.width = ((currentElement.childElements().size() * productOffsetWidth) * 1.02) + 'px';\n\t\t\t}\n\t\t}\n\t)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Captures the tag name from the start of the tag to the current character index, and converts it to lower case | function captureTagName() {
var startIdx = currentTag.idx + (currentTag.isClosing ? 2 : 1);
return html.slice(startIdx, charIdx).toLowerCase();
} | [
"function cleanTagName( name ) {\n\t\treturn name.split( ':', 1 )[ 0 ].replace( /[^a-zA-Z]/g, '' ).toLowerCase();\n\t}",
"function convert_attr_name_to_lowercase(code)\n{\n\tr = /(style=[\"'][^\"']*?[\"'])/gi;\n\treturn code.replace(r,function(s1,s2){\n\t\t\t\t\t\t\ts2 = s2.replace(/;?([^:]*)/g,function(d1,d2){return d2.toLowerCase();}\n\t\t\t\t\t\t);\n\t\t\treturn s2;\n\t});\n}",
"function LC(element) {\n return element.localName.toLowerCase();\n}",
"_getInitial(name) {\n return name[0].toUpperCase();\n }",
"function titleCase(name) {\r\n let nameArr = name.split(\" \");\r\n nameArr.forEach(function(curr, idx, arr) {\r\n arr[idx] = curr.toLowerCase().replace(/\\b[a-z]/g, function(first) {\r\n return first.toUpperCase();\r\n });\r\n });\r\n\r\n name = nameArr.join(\" \");\r\n return name;\r\n}",
"function lower(text) {\n return text.toLowerCase();\n }",
"function findFirstLetter(word){\n\treturn word[0].toUpperCase();\n}",
"_formatTag() {\n this.originalTag = this.originalTag.replace('\\n', ' ')\n let hedTagString = this.canonicalTag.trim()\n if (hedTagString.startsWith('\"')) {\n hedTagString = hedTagString.slice(1)\n }\n if (hedTagString.endsWith('\"')) {\n hedTagString = hedTagString.slice(0, -1)\n }\n if (hedTagString.startsWith('/')) {\n hedTagString = hedTagString.slice(1)\n }\n if (hedTagString.endsWith('/')) {\n hedTagString = hedTagString.slice(0, -1)\n }\n return hedTagString.toLowerCase()\n }",
"function caps(str){\n return str.replace(/\\w\\S*/g, function(txt){\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n}",
"function fnH5oGetTagName(elm) {\n return elm.tagName.toUpperCase();\n /* upper casing due to http://ejohn.org/blog/nodename-case-sensitivity/ */\n }",
"function translateParserNames(name) {\n var translated;\n switch (name) {\n case '\\'ALL\\'':\n case '\\'ANY\\'':\n case '\\'IP\\'':\n case '\\'SUBNET\\'':\n case '\\'TAG\\'':\n case '\\'VM\\'':\n case 'WORD':\n translated = name.toLowerCase();\n break;\n default:\n translated = name;\n break;\n }\n\n return translated;\n}",
"ucName() {\n return this.name.substr(0,1).toUpperCase() + this.name.substr(1);\n }",
"getOwnerToGoodCase(name) {\n if (_.includes(this.oracleReservedWords, name.toUpperCase())) {\n //The name is reserved, we return in normal case\n return name;\n } else {\n //The name is not reserved, we return in uppercase\n return name.toUpperCase();\n }\n }",
"function camelize(name, forceLower){\n if (firstDefined(forceLower, false)) {\n name = name.toLowerCase();\n }\n return name.replace(/\\-./g, function(u){\n return u.substr(1).toUpperCase();\n });\n }",
"function getCase(str) {\n\tconst a = [...new Set(str.match(/[a-z]/gi).map(x => x === x.toLowerCase() ? 1 : x === x.toUpperCase() ? 2 : 3))];\n\treturn a.length > 1 ? \"mixed\" : a[0] === 1 ? \"lower\" : \"upper\";\n}",
"function normalizeRenameTags() {\n\t// new dictionary for normalized tags\n\tglobalprefs.renameTagsNormalized = {};\n\t\n\t// iterate through the tags to rename\n\tfor (var key in globalprefs.renameTags) {\n\t\tvar newkey = key;\n\t\t\n\t\t// if matching not case sensitive, convert to lower case\n\t\tif (globalprefs.matchTagCase == false) {\n\t\t\tnewkey = key.toLowerCase();\n\t\t}\n\t\t\n\t\t// store key-value pair in normalized dictionary\n\t\tvar value = globalprefs.renameTags[key];\n\t\tglobalprefs.renameTagsNormalized[newkey] = value;\n\t}\n\t\n\treturn;\n}",
"function upperCaseName(name) {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}",
"capitalizer(str) {\n\t\treturn str.replace(/[aeiou]/g, char => char.toUpperCase());\n\t}",
"function upper_lower(str) {\n if (str.length < 3) {\n return str.toUpperCase();\n }\n front_part = (str.substring(0, 3)).toLowerCase();\n back_part = str.substring(3, str.length); \n return front_part + back_part;\n }",
"function capP1(match, p1, p2, p3, offset, string) {\n return match.replace(p1, p1[0].toUpperCase() + p1.substring(1));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get total number of wild cards in a word | function totalWC(word) {
return word.split("").filter(char => char == "*").length;
} | [
"function count(regex, str) {\n return str.length - str.replace(regex, '').length;\n }",
"function spoccures(string, regex) {\n return (string.match(regex) || []).length;\n }",
"function aCounter(word) {\n let count = 0;\n let index = 0\n while (index < word.length) {\n let char = word[index];\n if (char === \"a\" || char === \"A\") {\n count += 1;\n }\n index++\n }\n return count;\n }",
"function countMatches() {\n\tnumberOfMatches += 1;\n\treturn numberOfMatches;\n}",
"function task_filter_text_calculate_count(array, text) {\n array = array.filter(function(D) {\n return D.content.toLowerCase().indexOf(text.toLowerCase()) !== -1\n })\n length_total = array.length\n return length_total\n //$(div_id).html(length_total)\n}",
"function countWords(paragraph, love, you) {\n\t// split the string by spaces in a\n\tlet a = paragraph.split(\" \");\n\n\t// search for pattern in a\n\tlet countlove = 0;\n let countyou = 0;\n\tfor (let i = 0; i < a.length; i++) {\n\t // if match found increase count\n\t if (a[i].includes(love))\n\t\t countlove++;\n\n if (a[i].includes(you))\n countyou++;\n\n\t}\n\n if(countlove < countyou)\n\treturn `the word You is occurred more than Love with count ${countyou}`;\n\n return `the word Love is occurred more than You with count ${countlove}`;\n}",
"function countWordInPhrase(phrase, word){\n brokenPhrase = phrase.split(\" \");\n count = 0;\n for(b in brokenPhrase)\n if(brokenPhrase[b] == word)\n count++;\n \n return count;\n}",
"function instagramSticker(phrase) {\n let string = 'instagram'\n let insta = {}\n for (let char of string) {\n insta[char] ? insta[char]++ : insta[char] = 1\n }\n let count = 0\n let word = {}\n let sentence = phrase.split(' ').join('')\n for (let char of sentence) {\n word[char] ? word[char]++ : word[char] = 1\n }\n for (let char in word) {\n let amount = Math.ceil(word[char]/insta[char])\n if (amount > count) count = amount\n }\n return count\n}",
"function countDs(sentence) {\n\treturn sentence.toLowerCase().split('').filter(x => x === 'd').length;\n}",
"function findShort(s) {\n\t// Split string into seperate words -> load into an array -> sort the array by word length\n\tconst array = s.split(' ').sort((a, b) => a.length - b.length);\n\t// Return the length of the first word in the sorted array\n\treturn array[0].length;\n}",
"function countAs(string) {\n var stringArray = string.split(\"\");\n var count = 0;\n stringArray.forEach(function(letter) {\n if (letter === \"a\") {\n count++;\n }\n });\n return count;\n}",
"function getSylCount(line){\n var line_split = line.split(\" \");\n var word = line_split[0];\n \tvar containsNum = line_split[1].match(/\\d/g);\n \n if (containsNum){\n \tvar sylCount = containsNum.length;\n\n\t if (sylCount<8){ \n word = word.replace(/[^a-zA-Z]/g, \"\").toLowerCase();\n\t sylArr[sylCount].push(word);\n\t }\n\t //we don't care about words with more than 7 syllables\n }\n}",
"function CountBs(string)\r\n{\r\n\treturn CountChar(string, \"B\");\r\n}",
"function matchLength(text, exp) {\n var match = text.match(exp);\n return match ? match[0].length : 0;\n}",
"match(word) {\n if (this.pattern.length == 0)\n return [0];\n if (word.length < this.pattern.length)\n return null;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0);\n return first == chars[0] ? [0, 0, codePointSize(first)]\n : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return [0, 0, this.pattern.length];\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return null;\n }\n let preciseTo = 0;\n let byWordTo = 0, byWordFolded = false;\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {\n let next = codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)\n : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);\n if (type == 1 /* Upper */ || prevType == 0 /* NonWord */ && type != 0 /* NonWord */ &&\n (this.chars[byWordTo] == next || (this.folded[byWordTo] == next && (byWordFolded = true))))\n byWord[byWordTo++] = i;\n prevType = type;\n i += codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return [-200 /* CaseFold */, 0, adjacentEnd];\n if (direct > -1)\n return [-700 /* NotStart */, direct, direct + this.pattern.length];\n if (adjacentTo == len)\n return [-200 /* CaseFold */ + -700 /* NotStart */, adjacentStart, adjacentEnd];\n if (byWordTo == len)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */, byWord, word);\n return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);\n }",
"countBigWords(input) {\n // Set a counter equal to 0\n let counter = 0;\n // Split the input into words\n let temp = input.split(\" \");\n // Determine the length of each word by iterating over the array\n //If the word is greater than 6 letters, add 1 to a counter\n // If the word is less than or equal to 6 letters, go on to next word\n for(let i = 0; i < temp.length; i++) {\n if (temp[i].length > 6) {\n counter++;\n }\n }\n // Output the counter\n return counter;\n }",
"function countBs(subject)\n{\n return countChar(subject, \"B\");\n}",
"function countYZ(word) {\n word = word.toLowerCase();\n var count = 0;\n //console.log(word[word.length - 1]);\n if (word[word.length - 1] == \"y\" || word[word.length - 1] == \"z\") {\n count += 1;\n }\n for (var i = 0; i < word.length; i++) {\n if(word[i] == \" \") {\n\n if(word[i-1] == \"y\") {\n count += 1;\n }else if(word[i-1] == \"z\"){\n count += 1;\n }\n }\n }\n return count;\n}",
"function numStrings(list) {\n var count = 0;\n for(i = 0; i < list.length; i++) {\n\t\t//loops through each string, counting amount. \n \tif( typeof list[i] == \"string\") {\n \tcount++;\n \t}\n } \n \t\n return count;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enter a parse tree produced by ObjectiveCPreprocessorParserpreprocessorDef. | enterPreprocessorDef(ctx) {
} | [
"enterPreprocessorParenthesis(ctx) {\n\t}",
"enterPreprocessorBinary(ctx) {\n\t}",
"enterPreprocessorDefined(ctx) {\n\t}",
"enterPreprocessorImport(ctx) {\n\t}",
"enterPreprocessorConditional(ctx) {\n\t}",
"enterPreprocessorConstant(ctx) {\n\t}",
"enterPreprocessorConditionalSymbol(ctx) {\n\t}",
"enterPreprocessorNot(ctx) {\n\t}",
"enterPreprocessorPragma(ctx) {\n\t}",
"enterOrdinaryCompilation(ctx) {\n\t}",
"exitPreprocessorParenthesis(ctx) {\n\t}",
"enterModularCompilation(ctx) {\n\t}",
"enterPreprocessorWarning(ctx) {\n\t}",
"function InlineParser() {\n this.preEmphasis = \" \\t\\\\('\\\"\";\n this.postEmphasis = \"- \\t.,:!?;'\\\"\\\\)\";\n this.borderForbidden = \" \\t\\r\\n,\\\"'\";\n this.bodyRegexp = \"[\\\\s\\\\S]*?\";\n this.markers = \"*/_=~+\";\n\n this.emphasisPattern = this.buildEmphasisPattern();\n this.linkPattern = /\\[\\[([^\\]]*)\\](?:\\[([^\\]]*)\\])?\\]/g; // \\1 => link, \\2 => text\n\n // this.clockLinePattern =/^\\s*CLOCK:\\s*\\[[-0-9]+\\s+.*\\d:\\d\\d\\]/;\n // NOTE: this is a weak pattern. does not enforce lookahead of opening bracket type!\n this.timestampPattern =/([\\[<])(\\d{4}-\\d{2}-\\d{2})(?:\\s*([A-Za-z]+)\\s*)(\\d{2}:\\d{2})?([\\]>])/g;\n this.macroPattern = /{{{([A-Za-z]\\w*)\\(([^})]*?)\\)}}}/g;\n }",
"function parse_IntExpr(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_IntExpr()\" + '\\n';\n\tCSTREE.addNode('IntExpr', 'branch');\n\n\t\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\tif (tempType == 'digit'){\n\t\tmatchSpecChars(tempDesc,parseCounter);\n\t\t\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t\t\tif (tokenstreamCOPY[parseCounter][0] == '+'){\n\t\t\tdocument.getElementById(\"tree\").value += '\\n';\n\t\t\tparse_intop();\n\t\n\t\t\tparse_Expr();\n\t\n\t\t}\n\t\t\t\t\n\t}\n\t\n\t\n\t\n}",
"configure(config) {\n // Hideous reflection-based kludge to make it easy to create a\n // slightly modified copy of a parser.\n let copy = Object.assign(Object.create(LRParser.prototype), this)\n if (config.props) copy.nodeSet = this.nodeSet.extend(...config.props)\n if (config.top) {\n let info = this.topRules[config.top]\n if (!info) throw new RangeError(`Invalid top rule name ${config.top}`)\n copy.top = info\n }\n if (config.tokenizers)\n copy.tokenizers = this.tokenizers.map((t) => {\n let found = config.tokenizers.find((r) => r.from == t)\n return found ? found.to : t\n })\n if (config.specializers) {\n copy.specializers = this.specializers.slice()\n copy.specializerSpecs = this.specializerSpecs.map((s, i) => {\n let found = config.specializers.find((r) => r.from == s.external)\n if (!found) return s\n let spec = Object.assign(Object.assign({}, s), {\n external: found.to\n })\n copy.specializers[i] = getSpecializer(spec)\n return spec\n })\n }\n if (config.contextTracker) copy.context = config.contextTracker\n if (config.dialect) copy.dialect = this.parseDialect(config.dialect)\n if (config.strict != null) copy.strict = config.strict\n if (config.wrap) copy.wrappers = copy.wrappers.concat(config.wrap)\n if (config.bufferLength != null) copy.bufferLength = config.bufferLength\n return copy\n }",
"exitPreprocessorDef(ctx) {\n\t}",
"function processGrammar(dict, tokens) {\n\t var opts = {};\n\t if (typeof dict === 'string') {\n\t dict = lexParser.parse(dict);\n\t }\n\t dict = dict || {};\n\t\n\t opts.options = dict.options || {};\n\t opts.moduleType = opts.options.moduleType;\n\t opts.moduleName = opts.options.moduleName;\n\t\n\t opts.conditions = prepareStartConditions(dict.startConditions);\n\t opts.conditions.INITIAL = {rules:[],inclusive:true};\n\t\n\t opts.performAction = buildActions.call(opts, dict, tokens);\n\t opts.conditionStack = ['INITIAL'];\n\t\n\t opts.moduleInclude = (dict.moduleInclude || '').trim();\n\t return opts;\n\t}",
"function evaluator() {\n state.seg = segments['intro']; // starting from intro\n var block_ix = 0;\n\n // use global state to synchronize\n var handlers = {\n text : function(text) {\n var $text = $('<p></p>').appendTo($main);\n var timeoutid;\n var line_ix = 0;\n var char_ix = 0;\n state.status = 'printing';\n $triangle.hide();\n var text_printer = function() {\n var line = text.lines[line_ix];\n if (!line) {\n clearTimeout(timeoutid);\n $text.append('<br/>');\n // peek if next block is a branch block\n var next = get_next();\n if (next && next.type == 'branches') {\n next_block()\n } else {\n state.status = 'idle';\n $triangle.show();\n }\n return;\n }\n var interval = state.print_interval;\n if (char_ix < line.length) {\n var c = line[char_ix++];\n if (c == ' ') {\n c = ' ';\n }\n $text.append(c);\n } else {\n $text.append('<br/>');\n line_ix += 1;\n char_ix = 0;\n interval *= 6; // stop a little bit longer on new line\n }\n timeoutid = setTimeout(text_printer, interval);\n }\n timeoutid = setTimeout(text_printer, state.print_interval);\n },\n branches : function(branches) {\n var $ul = $('<ul class=\"branches\"></ul>').appendTo($main);\n state.status = 'branching'\n settings.cheated = false;\n var blur_cb = function(e) {\n settings.cheated = true;\n };\n $(window).on('blur', blur_cb);\n\n\n $.each(branches.cases, function(ix, branch){\n if (branch.pred == '?' || eval(branch.pred)) {\n var span = $('<span></span>').text(branch.text).data('branch_index', ix);\n $('<li></li>').append(span).appendTo($ul);\n }\n });\n $('li span', $ul).one('click', function(e){\n state.choice = parseInt( $(this).data('branch_index') );\n $(window).off('blur', blur_cb);\n clean_main();\n next_block();\n return false;\n });\n },\n code : function(code) {\n var control = new function() {\n var self = this;\n this.to_label = function(label) {\n self.next_label = label;\n };\n this.jump_to = function(segname) {\n self.next_seg = segname;\n }\n // extra functions\n this.clean_main = clean_main;\n this.reset = function() {\n settings = {}; // need to clean up the settings.\n constants.usual_print = 20; // on following playthrough, have faster printing\n self.jump_to('intro');\n };\n };\n eval(code.code);\n // handle the outcome\n if (control.next_seg) {\n state.seg = segments[control.next_seg];\n if (!state.seg) throw \"invalid segment jump:\" + control.next_seg;\n // jumping into label in another segment\n if (control.next_label) {\n var next = state.seg.labels[control.next_label]\n if (!next)\n throw \"invalid seg+label jump:\" + control.next_seg + \":\" + control.next_label;\n next_block(next);\n } else {\n next_block(state.seg[0]);\n }\n return;\n } else if (control.next_label) {\n var next = state.seg.labels[control.next_label];\n if (!next) throw \"invalid lable jump:\" + control.next_label;\n next_block(next);\n } else {\n next_block();\n }\n },\n label : function(label) {\n if (label.jump) {\n var next = state.seg.labels[label.name];\n if (!next) throw \"invalid jump label:\" + label.name;\n next_block(next);\n } else {\n next_block();\n }\n }\n\n };\n\n function clean_main() {\n $main.empty();\n }\n\n function handle_block() {\n console.log(\"doing block:\")\n console.log(state.block);\n handlers[state.block.type](state.block);\n }\n\n function get_next() {\n var block_in_seg = state.seg.indexOf(state.block);\n return state.seg[block_in_seg+1];\n }\n\n function next_block(block) {\n state.block = block || get_next();\n\n // necessary resets\n state.print_interval = constants.usual_print;\n handle_block();\n }\n\n function global_click_callback(e) {\n if (state.status == 'idle') {\n next_block();\n } else if (state.status == 'printing') {\n state.print_interval /= 5;\n }\n return false;\n }\n $(document).on('click', global_click_callback);\n\n // kick off\n state.block = state.seg[0];\n\n // !!!!!!!!!! DEBUG JUMP\n // state.seg = segments['puzzle'];\n // state.block = state.seg.labels['q1'];\n\n handle_block();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Consumes tokens from a Tokenizer to parse an At Rule node. | parseAtRule(tokenizer) {
let name = undefined;
let nameRange = undefined;
let rulelist = undefined;
let parametersStart = undefined;
let parametersEnd = undefined;
if (!tokenizer.currentToken) {
return null;
}
const start = tokenizer.currentToken.start;
while (tokenizer.currentToken) {
if (tokenizer.currentToken.is(token_1.Token.type.whitespace)) {
tokenizer.advance();
}
else if (!name && tokenizer.currentToken.is(token_1.Token.type.at)) {
// Discard the @:
tokenizer.advance();
const start = tokenizer.currentToken;
let end;
while (tokenizer.currentToken &&
tokenizer.currentToken.is(token_1.Token.type.word)) {
end = tokenizer.advance();
}
nameRange = tokenizer.getRange(start, end);
name = tokenizer.cssText.slice(nameRange.start, nameRange.end);
}
else if (tokenizer.currentToken.is(token_1.Token.type.openBrace)) {
rulelist = this.parseRulelist(tokenizer);
break;
}
else if (tokenizer.currentToken.is(token_1.Token.type.propertyBoundary)) {
tokenizer.advance();
break;
}
else {
if (parametersStart == null) {
parametersStart = tokenizer.advance();
}
else {
parametersEnd = tokenizer.advance();
}
}
}
if (name === undefined || nameRange === undefined) {
return null;
}
let parametersRange = undefined;
let parameters = '';
if (parametersStart) {
parametersRange = tokenizer.trimRange(tokenizer.getRange(parametersStart, parametersEnd));
parameters =
tokenizer.cssText.slice(parametersRange.start, parametersRange.end);
}
const end = tokenizer.currentToken ? tokenizer.currentToken.previous.end :
tokenizer.cssText.length;
return this.nodeFactory.atRule(name, parameters, rulelist, nameRange, parametersRange, { start, end });
} | [
"parseRule(tokenizer) {\n // Trim leading whitespace:\n const token = tokenizer.currentToken;\n if (token === null) {\n return null;\n }\n if (token.is(token_1.Token.type.whitespace)) {\n tokenizer.advance();\n return null;\n }\n else if (token.is(token_1.Token.type.comment)) {\n return this.parseComment(tokenizer);\n }\n else if (token.is(token_1.Token.type.word)) {\n return this.parseDeclarationOrRuleset(tokenizer);\n }\n else if (token.is(token_1.Token.type.propertyBoundary)) {\n return this.parseUnknown(tokenizer);\n }\n else if (token.is(token_1.Token.type.at)) {\n return this.parseAtRule(tokenizer);\n }\n else {\n return this.parseUnknown(tokenizer);\n }\n }",
"parseRules(tokenizer) {\n const rules = [];\n while (tokenizer.currentToken) {\n const rule = this.parseRule(tokenizer);\n if (rule) {\n rules.push(rule);\n }\n }\n return rules;\n }",
"function visit(text, visitor, options) {\n var _scanner = createScanner(text, false);\n function toNoArgVisit(visitFunction) {\n return visitFunction ? function () { return visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? function (arg) { return visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength()); } : function () { return true; };\n }\n var onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onError = toOneArgVisit(visitor.onError);\n var disallowComments = options && options.disallowComments;\n function scanNext() {\n while (true) {\n var token = _scanner.scan();\n switch (token) {\n case SyntaxKind.LineCommentTrivia:\n case SyntaxKind.BlockCommentTrivia:\n if (disallowComments) {\n handleError(ParseErrorCode.InvalidSymbol);\n }\n break;\n case SyntaxKind.Unknown:\n handleError(ParseErrorCode.InvalidSymbol);\n break;\n case SyntaxKind.Trivia:\n case SyntaxKind.LineBreakTrivia:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter, skipUntil) {\n if (skipUntilAfter === void 0) { skipUntilAfter = []; }\n if (skipUntil === void 0) { skipUntil = []; }\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n var token = _scanner.getToken();\n while (token !== SyntaxKind.EOF) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n var value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case SyntaxKind.NumericLiteral:\n var value = 0;\n try {\n value = JSON.parse(_scanner.getTokenValue());\n if (typeof value !== 'number') {\n handleError(ParseErrorCode.InvalidNumberFormat);\n value = 0;\n }\n }\n catch (e) {\n handleError(ParseErrorCode.InvalidNumberFormat);\n }\n onLiteralValue(value);\n break;\n case SyntaxKind.NullKeyword:\n onLiteralValue(null);\n break;\n case SyntaxKind.TrueKeyword:\n onLiteralValue(true);\n break;\n case SyntaxKind.FalseKeyword:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== SyntaxKind.StringLiteral) {\n handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === SyntaxKind.ColonToken) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n }\n else {\n handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n var needsComma = false;\n while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) {\n if (_scanner.getToken() === SyntaxKind.CommaToken) {\n if (!needsComma) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n }\n else if (needsComma) {\n handleError(ParseErrorCode.CommaExpected, [], []);\n }\n if (!parseProperty()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) {\n handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n var needsComma = false;\n while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) {\n if (_scanner.getToken() === SyntaxKind.CommaToken) {\n if (!needsComma) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n }\n else if (needsComma) {\n handleError(ParseErrorCode.CommaExpected, [], []);\n }\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) {\n handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case SyntaxKind.OpenBracketToken:\n return parseArray();\n case SyntaxKind.OpenBraceToken:\n return parseObject();\n case SyntaxKind.StringLiteral:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === SyntaxKind.EOF) {\n return true;\n }\n if (!parseValue()) {\n handleError(ParseErrorCode.ValueExpected, [], []);\n return false;\n }\n if (_scanner.getToken() !== SyntaxKind.EOF) {\n handleError(ParseErrorCode.EndOfFileExpected, [], []);\n }\n return true;\n }",
"function compileAction(lexer, ruleName, action) {\n if (!action) {\n return { token: '' };\n }\n else if (typeof (action) === 'string') {\n return action; // { token: action };\n }\n else if (action.token || action.token === '') {\n if (typeof (action.token) !== 'string') {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'a \\'token\\' attribute must be of type string, in rule: ' + ruleName);\n return { token: '' };\n }\n else {\n // only copy specific typed fields (only happens once during compile Lexer)\n var newAction = { token: action.token };\n if (action.token.indexOf('$') >= 0) {\n newAction.tokenSubst = true;\n }\n if (typeof (action.bracket) === 'string') {\n if (action.bracket === '@open') {\n newAction.bracket = 1 /* Open */;\n }\n else if (action.bracket === '@close') {\n newAction.bracket = -1 /* Close */;\n }\n else {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'a \\'bracket\\' attribute must be either \\'@open\\' or \\'@close\\', in rule: ' + ruleName);\n }\n }\n if (action.next) {\n if (typeof (action.next) !== 'string') {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'the next state must be a string value in rule: ' + ruleName);\n }\n else {\n var next = action.next;\n if (!/^(@pop|@push|@popall)$/.test(next)) {\n if (next[0] === '@') {\n next = next.substr(1); // peel off starting @ sign\n }\n if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists\n if (!__WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"i\" /* stateExists */](lexer, __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"j\" /* substituteMatches */](lexer, next, '', [], ''))) {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'the next state \\'' + action.next + '\\' is not defined in rule: ' + ruleName);\n }\n }\n }\n newAction.next = next;\n }\n }\n if (typeof (action.goBack) === 'number') {\n newAction.goBack = action.goBack;\n }\n if (typeof (action.switchTo) === 'string') {\n newAction.switchTo = action.switchTo;\n }\n if (typeof (action.log) === 'string') {\n newAction.log = action.log;\n }\n if (typeof (action.nextEmbedded) === 'string') {\n newAction.nextEmbedded = action.nextEmbedded;\n lexer.usesEmbedded = true;\n }\n return newAction;\n }\n }\n else if (Array.isArray(action)) {\n var results = [];\n var idx;\n for (idx in action) {\n if (action.hasOwnProperty(idx)) {\n results[idx] = compileAction(lexer, ruleName, action[idx]);\n }\n }\n return { group: results };\n }\n else if (action.cases) {\n // build an array of test cases\n var cases = [];\n // for each case, push a test function and result value\n var tkey;\n for (tkey in action.cases) {\n if (action.cases.hasOwnProperty(tkey)) {\n var val = compileAction(lexer, ruleName, action.cases[tkey]);\n // what kind of case\n if (tkey === '@default' || tkey === '@' || tkey === '') {\n cases.push({ test: null, value: val, name: tkey });\n }\n else if (tkey === '@eos') {\n cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });\n }\n else {\n cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture\n }\n }\n }\n // create a matching function\n var def = lexer.defaultToken;\n return {\n test: function (id, matches, state, eos) {\n var idx;\n for (idx in cases) {\n if (cases.hasOwnProperty(idx)) {\n var didmatch = (!cases[idx].test || cases[idx].test(id, matches, state, eos));\n if (didmatch) {\n return cases[idx].value;\n }\n }\n }\n return def;\n }\n };\n }\n else {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'an action must be a string, an object with a \\'token\\' or \\'cases\\' attribute, or an array of actions; in rule: ' + ruleName);\n return '';\n }\n}",
"_setTokenization(text, tokenOffsets) {\n this._text = text;\n this._tokenOffsets = tokenOffsets;\n let charToToken = new Array(text.length).fill(-1);\n tokenOffsets.forEach( (offset, index) => {\n for (let i = offset.start; i < offset.end; i++) {\n charToToken[i] = index;\n };\n });\n this._charToToken = charToToken;\n }",
"parseRulelist(tokenizer) {\n const rules = [];\n const start = tokenizer.currentToken.start;\n let endToken;\n // Take the opening { boundary:\n tokenizer.advance();\n while (tokenizer.currentToken) {\n if (tokenizer.currentToken.is(token_1.Token.type.closeBrace)) {\n endToken = tokenizer.currentToken;\n tokenizer.advance();\n break;\n }\n else {\n const rule = this.parseRule(tokenizer);\n if (rule) {\n rules.push(rule);\n }\n }\n }\n // If we don't have an end token it's because we reached the end of input.\n const end = endToken ? endToken.end : tokenizer.cssText.length;\n return this.nodeFactory.rulelist(rules, { start, end });\n }",
"function ParseStoryListener() {\n antlr4.tree.ParseTreeListener.call(this);\n return this;\n}",
"transform() {\n var iter = 0;\n while(true) {\n var result = this.rulesApply();\n if(!result)\n break\n if(this._text.length >= this._maxTokens || this._maxIterations <= ++iter)\n break;\n }\n }",
"pushTokens(tokens) {\n this.stack.push(...tokens);\n }",
"enterUnescapedAnnotation(ctx) {\n\t}",
"function getTokens(characters){\n var tokenPointer = 0;\n while (tokenPointer < characters.length){\n if (characters[tokenPointer] == \" \") {\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"-\") {\n tokens.push(\"neg\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"*\") {\n tokens.push(\"and\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"V\") {\n tokens.push(\"or\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"(\" || characters[tokenPointer] == \"[\") {\n if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"U\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"uq\");\n tokenPointer += 5;\n }\n else if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"E\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"eq\");\n tokenPointer += 5;\n }\n else {\n tokens.push(\"lp\")\n tokenPointer+=1\n }\n }\n else if (characters[tokenPointer] == \")\" || characters[tokenPointer] == \"]\") {\n tokens.push(\"rp\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toLowerCase()) {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]\n != characters[tokenPointer+1].toUpperCase()){\n tokens.push(\"pred\");\n tokenPointer += 1;\n while(tokenPointer<characters.length && characters[tokenPointer]\n != characters[tokenPointer].toUpperCase()){\n tokenPointer+=1;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toUpperCase()){\n tokens.push(\"sentLet\");\n tokenPointer+= 1;\n }\n else if (characters[tokenPointer] == \"<\") {\n if(tokenPointer+2<characters.length && characters[tokenPointer+1]==\"=\"\n && characters[tokenPointer+2]==\">\"){\n tokens.push(\"bicond\");\n tokenPointer += 3;\n }\n }\n else if (characters[tokenPointer] == \"=\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\">\"){\n tokens.push(\"cond\");\n tokenPointer += 2;\n }\n else {\n tokens.push(\"eqOp\");\n tokenPointer += 1;\n }\n }\n else if (characters[tokenPointer] == \"!\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\"=\"){\n tokens.push(\"notEqOp\");\n tokenPointer += 2;\n }\n else{\n tokens.push(\"error\");\n break;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n}",
"function readToken(data, input, token, stack, group) {\n var state = 0, groupMask = 1 << group, dialect = stack.cx.dialect;\n scan: for (var pos = token.start;;) {\n if ((groupMask & data[state]) == 0)\n break;\n var accEnd = data[state + 1];\n // Check whether this state can lead to a token in the current group\n // Accept tokens in this state, possibly overwriting\n // lower-precedence / shorter tokens\n for (var i = state + 3; i < accEnd; i += 2)\n if ((data[i + 1] & groupMask) > 0) {\n var term = data[i];\n if (dialect.allows(term) &&\n (token.value == -1 || token.value == term || stack.cx.parser.overrides(term, token.value))) {\n token.accept(term, pos);\n break;\n }\n }\n var next = input.get(pos++);\n // Do a binary search on the state's edges\n for (var low = 0, high = data[state + 2]; low < high;) {\n var mid = (low + high) >> 1;\n var index = accEnd + mid + (mid << 1);\n var from = data[index], to = data[index + 1];\n if (next < from)\n high = mid;\n else if (next >= to)\n low = mid + 1;\n else {\n state = data[index + 2];\n continue scan;\n }\n }\n break;\n }\n }",
"function parse(line) {\n\t\n\tif (!(line && typeof(line) == \"string\" && line.length)) {\n\t\treturn null;\n\t}\n\n\tvar tokens = line.trim().toUpperCase().split(' ');\n\n\tif (tokens.length) {\n\t\t//directive check first item\n\t\tvar cmd = Parser[tokens[0].toUpperCase()];\n\t\tif (cmd && cmd.length !=0) { //exact match\n\t\t\tif (!(tokens[0] == 'LOOK' && tokens.length != 1)) {\n\t\t\t\treturn cmd;\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\t//verb-object check\n\t\tvar verb = null, objet = null;\t\t\t\t\t\t\t\t//french spelling of object, why not?\t\t\t\t\t\n\t\tModifier = {};\n\n\t\tfor (var i in tokens) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_od('Parsing: ' + tokens[i]);\n\t\t\tif (!verb && Parser.hasOwnProperty(tokens[i])) {\n\t\t\t\tverb = tokens[i];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_od('Found verb: ' + verb);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (verb && !objet && Item.hasOwnProperty(tokens[i])) {\n\t\t\t\tif (Item[tokens[i]][verb]) {\n\t\t\t\t\tobjet = tokens[i];\n\t\t\t\t\tcontinue;\t\t\t\t\t\t\t\t\t\t\t\t_od('Found object ' + objet);\n\t\t\t\t}\n\t\t\t} \n\n\t\t\tif (verb && objet && tokens[i]=='ON') {\t\t\t\t\t_od('Found ON: ');\n\t\t\t\tModifier.ON = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (verb && objet && Modifier.hasOwnProperty('ON') && Item.hasOwnProperty(tokens[i])) {\t\t_od('Found ON object: ' + tokens[i]);\n\t\t\t\tModifier.ON = tokens[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t//otherwise ignore token\n\t\t}\n\t\tif (verb && objet) {\n\t\t\treturn Item[objet][verb];\n\t\t}\n\t}\n\t// either no tokens or no matches\n\treturn null;\n}",
"function parseExpression() {\n let expr;\n //lookahead = lex();\n // if (!lookahead) { //significa que es white o undefined\n // lookahead = lex();\n // }\n if (lookahead.type == \"REGEXP\") {\n expr = new Regexp({type: \"regex\", regex: lookahead.value, flags: null});\n lookahead = lex();\n return expr;\n } else if (lookahead.type == \"STRING\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"NUMBER\") {\n expr = new Value({type: \"value\", value: lookahead.value});\n lookahead = lex();\n if (lookahead.type === 'LC' || lookahead.type === 'DOT') return parseMethodApply(expr);\n return expr;\n } else if (lookahead.type == \"WORD\") {\n const lookAheadValue = lookahead;\n lookahead = lex();\n if (lookahead.type == 'COMMA' && lookahead.value == ':') {\n expr = new Value({type: \"value\", value: '\"' + lookAheadValue.value + '\"'});\n return expr;\n }\n if (lookahead.type == 'DOT') {\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n }\n expr = new Word({type: \"word\", name: lookAheadValue.value});\n return parseApply(expr);\n } else if (lookahead.type == \"ERROR\") {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${lookahead.value}`);\n } else {\n throw new SyntaxError(`Unexpected syntax line ${lineno}, col ${col}: ${program.slice(offset, offset + 10)}`);\n }\n}",
"parseUnknown(tokenizer) {\n const start = tokenizer.advance();\n let end;\n if (start === null) {\n return null;\n }\n while (tokenizer.currentToken &&\n tokenizer.currentToken.is(token_1.Token.type.boundary)) {\n end = tokenizer.advance();\n }\n return this.nodeFactory.discarded(tokenizer.slice(start, end), tokenizer.getRange(start, end));\n }",
"cfg2ast (cfg) {\n /* establish abstract syntax tree (AST) node generator */\n let asty = new ASTY()\n const AST = (type, ref) => {\n let ast = asty.create(type)\n if (typeof ref === \"object\" && ref instanceof Array && ref.length > 0)\n ref = ref[0]\n if (typeof ref === \"object\" && ref instanceof Tokenizr.Token)\n ast.pos(ref.line, ref.column, ref.pos)\n else if (typeof ref === \"object\" && asty.isA(ref))\n ast.pos(ref.pos().line, ref.pos().column, ref.pos().offset)\n return ast\n }\n\n /* establish lexical scanner */\n let lexer = new Tokenizr()\n lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/, (ctx, m) => {\n ctx.accept(\"id\")\n })\n lexer.rule(/[+-]?[0-9]+/, (ctx, m) => {\n ctx.accept(\"number\", parseInt(m[0]))\n })\n lexer.rule(/\"((?:\\\\\\\"|[^\\r\\n]+)+)\"/, (ctx, m) => {\n ctx.accept(\"string\", m[1].replace(/\\\\\"/g, \"\\\"\"))\n })\n lexer.rule(/\\/\\/[^\\r\\n]+\\r?\\n/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/[ \\t\\r\\n]+/, (ctx, m) => {\n ctx.ignore()\n })\n lexer.rule(/./, (ctx, m) => {\n ctx.accept(\"char\")\n })\n\n /* establish recursive descent parser */\n let parser = {\n parseCfg () {\n let block = this.parseBlock()\n lexer.consume(\"EOF\")\n return AST(\"Section\", block).set({ ns: \"\" }).add(block)\n },\n parseBlock () {\n let items = []\n for (;;) {\n let item = lexer.alternatives(\n this.parseProperty.bind(this),\n this.parseSection.bind(this),\n this.parseEmpty.bind(this))\n if (item === undefined)\n break\n items.push(item)\n }\n return items\n },\n parseProperty () {\n let key = this.parseId()\n lexer.consume(\"char\", \"=\")\n let value = lexer.alternatives(\n this.parseNumber.bind(this),\n this.parseString.bind(this))\n return AST(\"Property\", value).set({ key: key.value, val: value.value })\n },\n parseSection () {\n let ns = this.parseId()\n lexer.consume(\"char\", \"{\")\n let block = this.parseBlock()\n lexer.consume(\"char\", \"}\")\n return AST(\"Section\", ns).set({ ns: ns.value }).add(block)\n },\n parseId () {\n return lexer.consume(\"id\")\n },\n parseNumber () {\n return lexer.consume(\"number\")\n },\n parseString () {\n return lexer.consume(\"string\")\n },\n parseEmpty () {\n return undefined\n }\n }\n\n /* parse syntax character string into abstract syntax tree (AST) */\n let ast\n try {\n lexer.input(cfg)\n ast = parser.parseCfg()\n }\n catch (ex) {\n console.log(ex.toString())\n process.exit(0)\n }\n return ast\n }",
"_processToken (route, token, value) {\n switch (token) {\n case 'resource':\n this.addResource (route, value);\n break;\n\n default:\n this.addMethod (route, token, value);\n break;\n }\n }",
"function transformAtrule(rule, opts) {\n\t// update the at-rule params with its variables replaced by their corresponding values\n\trule.params = getReplacedString(rule.params, rule, opts);\n}",
"parseSubmission(s) {\n // define the parser (babel) and the abstract syntax tree generated\n // from parsing the submission\n const babel = require(\"@babel/core\");\n const ast = babel.parse(s.getSubmission);\n // define iterating variable\n let i = 0;\n // define empty arrays for storing individual strings and tokens.\n // The array of strings is used to generate the array of tokens\n //let myStrings : Array<string> = []\n let myTokens = [];\n // myOriginalText = original strings from submission\n // myTypes = the type of expression of each string (e.g. NumericLiteral)\n let myOriginalText = [];\n let myTypes = [];\n // the parser traverses through the abstract syntax tree and adds\n // any strings that it passes through to the array of strings\n babel.traverse(ast, {\n enter(path) {\n myTypes.push(path.node.type);\n myOriginalText.push(path.node.name);\n }\n });\n // each string in the array of strings is used to create a new\n // token, which is then added to the array of tokens\n for (i = 0; i < myOriginalText.length; i++) {\n myTokens.push(new Token_1.default(myOriginalText[i], myTypes[i]));\n }\n // create a TokenManager that holds the array of tokens\n let myTokenManager = new TokenManager_1.default(myTokens);\n // return the TokenManager which holds all of the tokens generated\n // by the strings extracted from the original submission\n return myTokenManager;\n // t1 = new Token(originaltext1: String, identifier1: String)\n // t2 = new Token(originaltext2: String, identifier2: String)\n // ...\n // tokenList = new List<Token>\n // tokenList.add(t1)\n // tokenList.add(t2)\n // ...\n // tmanager = new TokenManager(tokenList)\n // this.tokenizedSubmission = tmanager\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checkForPropertyClash() Because we are dynamically adding property names, we need to ensure that the name does not clash with any existing javaScript property names. Check the passed in property name. If it matches a javaScript property, return an amended property name. | function checkForPropertyClash(property) {
if (property === 'length') { return 'len'; }
return property;
} | [
"function shortenIfExists(obj, property) {\n if (obj[property]) {\n obj[property] = shorten(obj[property]);\n }\n}",
"function jptr(obj, prop, newValue) {\n if (typeof obj === 'undefined') return false;\n if (!prop || typeof prop !== 'string' || (prop === '#')) return (typeof newValue !== 'undefined' ? newValue : obj);\n\n if (prop.indexOf('#')>=0) {\n let parts = prop.split('#');\n let uri = parts[0];\n if (uri) return false; // we do internal resolution only\n prop = parts[1];\n prop = decodeURIComponent(prop.slice(1).split('+').join(' '));\n }\n if (prop.startsWith('/')) prop = prop.slice(1);\n\n let components = prop.split('/');\n for (let i=0;i<components.length;i++) {\n components[i] = jpunescape(components[i]);\n\n let setAndLast = (typeof newValue !== 'undefined') && (i == components.length-1);\n\n let index = parseInt(components[i],10);\n if (!Array.isArray(obj) || isNaN(index) || (index.toString() !== components[i])) {\n index = (Array.isArray(obj) && components[i] === '-') ? -2 : -1;\n }\n else {\n components[i] = (i > 0) ? components[i-1] : ''; // backtrack to indexed property name\n }\n\n if ((index != -1) || obj.hasOwnProperty(components[i])) {\n if (index >= 0) {\n if (setAndLast) {\n obj[index] = newValue;\n }\n obj = obj[index];\n }\n else if (index === -2) {\n if (setAndLast) {\n if (Array.isArray(obj)) {\n obj.push(newValue);\n }\n return newValue;\n }\n else return undefined;\n }\n else {\n if (setAndLast) {\n obj[components[i]] = newValue;\n }\n obj = obj[components[i]];\n }\n }\n else {\n if ((typeof newValue !== 'undefined') && (typeof obj === 'object') &&\n (!Array.isArray(obj))) {\n obj[components[i]] = (setAndLast ? newValue : ((components[i+1] === '0' || components[i+1] === '-') ? [] : {}));\n obj = obj[components[i]];\n }\n else return false;\n }\n }\n return obj;\n}",
"ensureProperty(obj, prop, value) {\n if (!(prop in obj)) {\n obj[prop] = value;\n }\n }",
"function video_property_exist(property_name)\n{\n test( function() {\n getmedia();\n assert_true(property_name in media, \"media.\" + property_name +\" exists\");\n }, name);\n}",
"function checkProperty(previous, property) {\n console.log(\"[EVT] Checking if property \" + property.key + \" changed to \" + property.value + \" \" + JSON.stringify(previous));\n\n if (previous[property.key]) {\n console.log(\"[EVT] Property present\");\n if (previous[property.key] === property.value) {\n console.log(\"[EVT] Same value, no need to forward\");\n return false;\n }\n else if ((property.key === 'x') || (property.key === 'y')) {\n console.log(\"[EVT] Checking x, y values from Hue\");\n if (previous.color.cie1931[property.key] === property.value) {\n console.log(\"[EVT] Same value, no need to forward\");\n return false;\n }\n }\n }\n return true;\n}",
"async _rename(properties, kv_data) {\r\n let new_search = await this._createSS(properties);\r\n\r\n if (!!new_search) {\r\n this._deleteSearch(this.search_name);\r\n this._updateKVstore(kv_store);\r\n this.search_name = properties.name;\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }",
"function getJSXName(name) {\n var replacement = acf.isget(acf, 'jsxNameReplacements', name);\n if (replacement) return replacement;\n return name;\n }",
"function testcase() {\n var obj = { \"a\": \"a\" };\n\n var result = Object.getOwnPropertyNames(obj);\n\n try {\n var beforeOverride = (result[0] === \"a\");\n result[0] = \"b\";\n var afterOverride = (result[0] === \"b\");\n\n return beforeOverride && afterOverride;\n } catch (ex) {\n return false;\n }\n }",
"function prop(name){\n return function(obj){\n return obj[name];\n };\n}",
"function search_location_property(parent)\n{\n if (parent.type!='MemberExpression' || !parent.property || parent.property.type!='Identifier') return false;\n var property_name = parent.property.name;\n //match Location properties\n if (my_property_property.includes(property_name)) {\n console.log(\"[Guessed by property name]\");\n count_gessed_prop++;\n return true;\n }\n //match Location methods\n if (my_property_methods.includes(property_name)) {\n console.log(\"[Guessed by method name]\");\n count_gessed_method++;\n return true;\n }\n return false;\n}",
"function getNameFromPropertyName(propertyName) {\n if (propertyName.type === typescript_estree_1.AST_NODE_TYPES.Identifier) {\n return propertyName.name;\n }\n return `${propertyName.value}`;\n}",
"onPropertyHas(room, property, identifier) {\n return room.hasOwnProperty(property);\n }",
"async expandProperty(property) {\n // JavaScript requires keys containing colons to be quoted,\n // so prefixed names would need to written as path['foaf:knows'].\n // We thus allow writing path.foaf_knows or path.foaf$knows instead.\n property = property.replace(/^([a-z][a-z0-9]*)[_$]/i, '$1:');\n\n // Expand the property to a full IRI\n const context = await this._context;\n const expandedProperty = context.expandTerm(property, true);\n if (!ContextUtil.isValidIri(expandedProperty))\n throw new Error(`The JSON-LD context cannot expand the '${property}' property`);\n return namedNode(expandedProperty);\n }",
"eatUnicodePropertyValueExpression() {\n const start = this.index;\n // UnicodePropertyName `=` UnicodePropertyValue\n if (this.eatUnicodePropertyName() && this.eat(unicode_1.EqualsSign)) {\n this._lastKeyValue = this._lastStrValue;\n if (this.eatUnicodePropertyValue()) {\n this._lastValValue = this._lastStrValue;\n if (isValidUnicodeProperty(this._lastKeyValue, this._lastValValue)) {\n return true;\n }\n this.raise(\"Invalid property name\");\n }\n }\n this.rewind(start);\n // LoneUnicodePropertyNameOrValue\n if (this.eatLoneUnicodePropertyNameOrValue()) {\n const nameOrValue = this._lastStrValue;\n if (isValidUnicodeProperty(\"General_Category\", nameOrValue)) {\n this._lastKeyValue = \"General_Category\";\n this._lastValValue = nameOrValue;\n return true;\n }\n if (isValidUnicodePropertyName(nameOrValue)) {\n this._lastKeyValue = nameOrValue;\n this._lastValValue = \"\";\n return true;\n }\n this.raise(\"Invalid property name\");\n }\n return false;\n }",
"function populatePropertyFromJsonFile(object, jsonFilePath, propertyName) {\n if (fileHelper_1.doesFileExist(jsonFilePath)) {\n const jsonObj = fileHelper_1.getFileJson(jsonFilePath);\n if (jsonObj) {\n // If same property exists in jsonObj then fetch that else use whole json object\n if (jsonObj[propertyName]) {\n object[propertyName] = jsonObj[propertyName];\n }\n else {\n object[propertyName] = jsonObj;\n }\n }\n }\n}",
"function isPropValid()\n{\n\n}",
"get propertyName() {}",
"getProperty(exemplar, key) {\n\t\tlet original = exemplar;\n\t\tlet prop = exemplar.prop(key);\n\t\twhile (!prop && exemplar.parent[0]) {\n\t\t\tlet { parent } = exemplar;\n\t\t\tlet entry = this.find(parent);\n\t\t\tif (!entry) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\texemplar = entry.read();\n\t\t\tprop = exemplar.prop(key);\n\t\t}\n\t\treturn prop;\n\t}",
"function objOverride(base, extension, property) {\n // extension doesn't have property; just return base\n if (extension[property] == null) {\n return;\n }\n // base doesn't have property; copy extension's property (ref copy if obj)\n if (base[property] == null) {\n base[property] = extension[property];\n return;\n }\n // both have property; do per-key copy/override of extension's properties\n // (ref copies if objs)\n for (let key in extension[property]) {\n base[property][key] = extension[property][key];\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return array of nodes that are domains | function getAllDomains(){
var domains = [];
var nodes = flattenAll_BF(root);
for(var i in nodes){
if(nodes[i].type == "domain") domains.push(nodes[i]);
}
return domains;
} | [
"function getDomains(data, tld){\n var vals = data.getValues(); \n var dot_coms = [];\n \n for (var i = 0; i < vals.length; i++) {\n for (var j = 0; j < vals[i].length; j++) {\n var cellVal = vals[i][j]\n \n if (typeof cellVal !== \"string\") continue; // skip non-string cells\n \n if (cellVal.indexOf(tld) !== -1) { // select only cells with the tld\n dot_coms.push(vals[i][j])\n } \n }\n }\n return dot_coms\n}",
"function getDomains( callback ) {\n\tchrome.storage.sync.get( {\n\t\tdomains: []\n\t}, function( items ) {\n\t\tcallback( items.domains );\n\t} );\n}",
"function getDomains() {\n var domains = new Array();\n $(\"#edit-field-domain-access :checked\").each(function(index, obj) {\n domains.push(obj.value);\n });\n setOptions(domains);\n }",
"get nodelist() {\n\t\treturn this.nodes.values();\n\t}",
"function getAllDTNs(){\n var dtns = [];\n var nodes = flattenAll_BF(root);\n for(var i in nodes){\n if(nodes[i].type == \"dtn\") dtns.push(nodes[i]);\n }\n\n return dtns;\n}",
"function getPatientKnnAttributeDomains() {\r\n let knnAttributeDomains = {};\r\n\r\n for (let attribute of App.patientKnnAttributes) {\r\n knnAttributeDomains[attribute] = self.axes[attribute].domain;\r\n }\r\n\r\n return knnAttributeDomains;\r\n }",
"function groupSourcesByDomain(sources) {\n return sources.valueSeq()\n .filter(source => !!source.get(\"url\"))\n .groupBy(source => (new URL(source.get(\"url\"))).hostname);\n}",
"findL2Domains() {\n let l2segment_domain = {};\n let l2domains = {};\n let l2links = [];\n let id = 0;\n this.scene.L3.children.forEach((parent_element) => {\n if(parent_element.userData.type === \"base\") {\n parent_element.children.forEach((element) => {\n if(element.userData.type == \"l2segment\") {\n l2segment_domain[element.userData.id] = id;\n l2domains[id] = [element.userData.id];\n id++;\n }\n });\n }\n else if(parent_element.userData.type === \"l2link\") {\n l2links.push(parent_element.userData);\n }\n });\n\n l2links.forEach((l2link) => {\n let dst_domain = l2segment_domain[l2link.e.l3_reference.dst_l2segment_id];\n let src_domain = l2segment_domain[l2link.e.l3_reference.src_l2segment_id];\n if(src_domain !== dst_domain) {\n l2domains[dst_domain].forEach((l2segment_id) => {\n l2segment_domain[l2segment_id] = src_domain;\n l2domains[src_domain].push(l2segment_id);\n });\n delete l2domains[dst_domain];\n /*\n for(let l2segment_id in l2segment_domain) {\n if(l2segment_domain[l2segment_id] === dst_domain) l2segment_domain[l2segment_id] = src_domain;\n }*/\n }\n });\n\n return [l2segment_domain, l2domains];\n }",
"function outgoingLinks(node) {\n return d3.select(\"#maindiv${divnum}\")\n .selectAll(\".link\")\n .filter(function(d) {\n return d.source.id == node[0][0].__data__.id;\n });\n}",
"function incomingLinks(node) {\n return d3.select(\"#maindiv${divnum}\")\n .selectAll(\".link\")\n .filter(function(d) {\n return d.target.id == node[0][0].__data__.id;\n });\n}",
"getUrnsFromInboundDomain(domain, stamp) {\n return __awaiter(this, void 0, void 0, function* () {\n this._checkParameter(domain, \"Domain not defined\");\n this._checkParameter(stamp, \"Target stamp not defined\");\n yield this._checkStamp(stamp);\n let urns = [];\n let admission = yield this._getAdmissionClient(stamp);\n let deployments = yield admission.findDeployments();\n if (deployments) {\n for (let name in deployments) {\n let deployment = deployments[name];\n if (deployment.service.indexOf(INBOUND_SERVICE_URN_PREFIX) == 0) {\n let vhost = utils_1.getNested(deployment, 'resources', 'vhost', 'resource', 'parameters', 'vhost');\n let refDomain = utils_1.getNested(deployment, 'roles', 'sep', 'entrypoint', 'refDomain');\n let sepDomain = utils_1.getNested(deployment, 'roles', 'sep', 'entrypoint', 'domain');\n if (vhost && vhost.localeCompare(domain) == 0) {\n for (let element of Object.keys(deployment.links.frontend)) {\n urns.push(element);\n }\n }\n else if (refDomain && refDomain.localeCompare(domain) == 0) {\n for (let element of Object.keys(deployment.links.frontend)) {\n urns.push(element);\n }\n }\n else if (sepDomain && sepDomain.localeCompare(domain) == 0) {\n for (let element of Object.keys(deployment.links.frontend)) {\n urns.push(element);\n }\n }\n }\n }\n }\n return urns;\n });\n }",
"function domainType(domains) {\n return domains.map((domain) => {\n if (domain.includes('com')) {\n return 'commercial';\n }\n\n if (domain.includes('org')) {\n return 'organization';\n }\n\n if (domain.includes('net')) {\n return 'network';\n }\n\n if (domain.includes('info')) {\n return 'information';\n }\n\n return 'other';\n });\n}",
"getPotentialHosts() {\n return this.getPotentialRegions()\n .map((r) => { return r.host; });\n }",
"GetSubdomainsFor(username, userpass)\r\n {\r\n let res = [];\r\n for (let name in this.list) {\r\n if (this.list[name].isAuthorized(username, userpass)) {\r\n res.push(name);\r\n }\r\n }\r\n return res;\r\n }",
"function handleDomainSelection(e) {\r\n\r\n\t$(\".nodeWord\").css(\"color\", \"\");\r\n\t$(\".relArrow\").css(\"color\", \"\");\r\n\t$(\"#chart\").empty();\r\n\tgraphPlotted = false;\r\n\r\n\t// rebuild selected node domain list\r\n\tnodeDomainLabelMap = {};\r\n\tnodeDomain = [];\r\n\tavailNodeDomain.forEach(function(domain) {\r\n\t\tvar checkedVal = $(\"input[name='\" + domain + \"']:checked\").val();\r\n\t\tif (typeof(checkedVal) != \"undefined\" && checkedVal != \"EXCLUDE\") {\r\n\t\t\tnodeDomainLabelMap[domain] = checkedVal;\r\n\t\t\tnodeDomain.push(domain);\r\n\t\t}\r\n\t});\r\n\r\n\t// rebuild selected relationship domain list\r\n\trelDomain = [];\r\n\tavailRelDomain.forEach(function(domain) {\r\n\t\tvar parts = getRelDomainParts(domain);\r\n\t\t\r\n\t\tif (nodeDomainLabelMap[parts.sourceKey] && nodeDomainLabelMap[parts.targetKey]) {\r\n\t\t\t$(\"#rel\" + domain).removeClass(\"disabled\");\r\n\t\t\t$(\"#lbl\" + domain).html(getRelHtml(nodeDomainLabelMap[parts.sourceKey], nodeDomainLabelMap[parts.targetKey], parts.type, domain));\r\n\t\t\tif ($(\"#chk\" + domain).is(\":checked\")) {\r\n\t\t\t\trelDomain.push(domain);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\t$(\"#rel\" + domain).addClass(\"disabled\");\r\n\t\t}\r\n\t});\r\n\t\r\n\t// if at least 2 node domains and 1 relationship are selected, then regenerate the plot\r\n\tif (nodeDomain.length > 1 && relDomain.length > 0) {\r\n\t\tvar args = {\r\n\t\t\tcontainerSelector: \"#chart\",\r\n\t\t\tgraph: graph,\r\n\t\t\tnodeDomain: nodeDomain,\r\n\t\t\trelationshipDomain: relDomain,\r\n\t\t\tgetNodeName: generateNodeName,\r\n\t\t\tgetNodeLabel: getNodeLabel\r\n\t\t};\r\n\t\t\r\n\t\tHivePlot.Plotter.draw(args);\r\n\r\n\t\t// color the node and relationship text according to the colors in the plot\r\n\t\tnodeDomain.forEach(function(d) {\r\n\t\t\t$(\".nodeWord.\" + d + \".\" + nodeDomainLabelMap[d]).css(\"color\", HivePlot.Plotter.getNodeColor(d));\r\n\t\t});\r\n\t\t\r\n\t\trelDomain.forEach(function(d) {\r\n\t\t\t$(\".relArrow.\" + d).css(\"color\", HivePlot.Plotter.getRelationshipColor(d));\r\n\t\t});\r\n\t\t\r\n\t\tdefaultInfo = \"Showing \" + formatNumber(HivePlot.Plotter.getRelationshipCount()) + \" links among \" + formatNumber(HivePlot.Plotter.getNodeCount()) + \" nodes.\";\r\n\t\tsetStatus(defaultInfo);\r\n\t\t\r\n\t\tgraphPlotted = true; \r\n\t}\r\n}",
"function getDomainFilterItems(str) {\n\n let outArr = [];\n let pageHost = window.location.hostname;\n pageHost = pageHost.replace(/www./g, \"\");\n\n let strArr = str.split(\",\");\n for (let i in strArr) {\n\n if (strArr[i].startsWith(\"*\")) {\n\n if (\n pageHost.search(\n strArr[i].replace(\"*.\", \"\").replace(\"*\", \"\")\n ) !== -1\n ){\n\n outArr.push(strArr[i]);\n }\n }\n }\n return outArr;\n}",
"getFioDomains(fioPublicKey, limit, offset) {\n const getNames = new queries.GetDomains(fioPublicKey, limit, offset);\n return getNames.execute(this.publicKey);\n }",
"getRelatedNodes(node, relation) {\n if (relation === 'parent') {\n return this._closest(node, (el) => el.classList.contains('nodes'))\n .parentNode.children[0].querySelector('.node');\n } else if (relation === 'children') {\n return Array.from(this._closest(node, (el) => el.nodeName === 'TABLE').lastChild.children)\n .map((el) => el.querySelector('.node'));\n } else if (relation === 'siblings') {\n return this._siblings(this._closest(node, (el) => el.nodeName === 'TABLE').parentNode)\n .map((el) => el.querySelector('.node'));\n }\n return [];\n }",
"function nodesTo(x, i) {\n const nodesToList = new go.List(\"string\");\n if (x instanceof go.Link) {\n x.fromNode.highlight = i;\n nodesToList.add(x.data.from);\n } else {\n x.findNodesInto().each(function (node) {\n node.highlight = i;\n nodesToList.add(node.data.key);\n });\n }\n return nodesToList;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hide the pop up => display none and zindex negativ => empty the title and content | function hidePopup () {
$('#popup').css('z-index', -20000);
$('#popup').hide();
$('#popup .popup-title').text('');
$('#popup .popup-content').text('');
$('.hide-container').hide();
$('.container').css('background', '#FAFAFA');
} | [
"function hide_popup()\n{\n\t$('.overlay').hide();\n\t$(\"#tooltip\").toggle();\n}",
"function showPopup () {\n $('#popup').css('z-index', '20000');\n $('#popup .popup-title').text($('#title').val());\n $('#popup .popup-content').text($('#content').val());\n $('.hide-container').show();\n $('#popup').show();\n }",
"function hidePopup() {\n // get the container which holds the variables\n var topicframe = findFrame(top, 'topic');\n\n if (topicframe != null) {\n if (topicframe.openedpopup != 1) {\n if ((topicframe.openpopupid != '') && (topicframe.popupdocument != null)) {\n var elmt = topicframe.popupdocument.getElementById(topicframe.openpopupid);\n if (elmt != null) {\n elmt.style.visibility = 'hidden';\n }\n openpopupid = '';\n }\n }\n\n openedpopup = 0;\n }\n}",
"function close_popup(popup) {\r\n popup.style.display = \"none\";\r\n}",
"function hidePopup () {\r\n editor.popups.hide('customPlugin.popup');\r\n }",
"function hide_global_supplier_settings()\n{\n\t//Empty the html \n\t$(\"#sup_list_view_global\").html(\"\");\n\t//Hide the modal box \n\t$('.overlay').hide(); \n\t$('#setng_supplier_global').hide();\n\t//Nothing else to be done \n}",
"function hide() {\n\t\t\t$doc.unbind('keydown', keypress);\n\t\t\t$win.unbind('resize');\n\t\t\tif( inlineParent ) {\n\t\t\t\tinlineParent.append( $overlayContent.html() );\n\t\t\t\tinlineParent = null;\n\t\t\t}\n\t\t\tif( $overlayBox.find('.overlay-nav').length != 0 ) {\n\t\t\t\t$overlayNav.unbind('click').remove();\n\t\t\t}\n\t\t\t$overlayBox.fadeOut( opts.duration/2, function(){\n\t\t\t\t$(this).remove().find('.overlay-close').unbind('click');\n\t\t\t\t$overlayContent.empty();\n\t\t\t});\n\t\t\t$overlayMask.fadeOut( opts.duration/2, function(){\n\t\t\t\t$(this).unbind('click').remove();\n\t\t\t});\n\t\t}",
"function CloseBubble()\r\n{\r\n\tdocument.getElementById(\"bubble_main\").style.visibility = \"hidden\";\r\n}",
"function _hidePopup(event) {\n if ($reverseNameResolver.css('display') != 'none') {\n $reverseNameResolver.fadeOut(300);\n }\n }",
"hide() {\n this.StartOverPopoverBlock.remove();\n this.StartOverPopoverDiv.remove();\n }",
"function closePopUp() {\n document.getElementById(\"loggerModalWrapper\").style.display = \"none\";\n }",
"function hideTipShowText() {\n tipElement.style.opacity = '0'\n nodeElement.style.opacity = '1'\n nodeTitleElement.textContent = title\n }",
"function hideImagePopup(){\n\tdocument.getElementById('popupImage').style.visibility = \"hidden\";\n}",
"function hideSettings() {\n $(\"#searchOptionsBox\").removeClass(\"visible\");\n zdPage.modalHidden();\n // Re-enable tooltip, unless we have a touch screen\n if (!zdPage.isTouch()) $(\".btnSettings\").tooltipster('enable');\n }",
"function openJobDetails(){\n\n document.getElementById(\"postOverlay\").style.display=\"block\";\n document.getElementById(\"body\").style.overflow=\"hidden\";\n}///to close the overlay",
"function hideResultModal() {\n\tvar modal = $('#popup-window');\n modal.css('display', 'none');\n}",
"function hidePopup() {\n $('#transparented').hide();\n $('#popup').hide();\n $(\"#typebox > textarea\").removeProp(\"disabled\");\n $(\"#typebox > textarea\").focus();\n}",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"function hideTitle() {\n UIController.getExpandedCoupon().firstElementChild.firstElementChild.classList.remove('show');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks with the scheduler to see if a process is executing or queued to execute. | function krnCheckExecution()
{
return _Scheduler.processEnqueued;
} | [
"needsReschedule() {\n if (!this.currentTask || !this.currentTask.isRunnable) {\n return true;\n }\n // check if there's another, higher priority task available\n let nextTask = this.peekNextTask();\n if (nextTask && nextTask.priority > this.currentTask.priority) {\n return true;\n }\n return false;\n }",
"function IsProcessRunning(exeName)\r\n{\r\n try {\r\n // Magic WMI incantations!\r\n if(!WMI) WMI = new ActiveXObject(\"WbemScripting.SWbemLocator\").ConnectServer(\".\",\"root/CIMV2\");\r\n \tvar x = new Enumerator(WMI.ExecQuery(\"Select * From Win32_Process Where Name=\\\"\" + exeName + \"\\\"\")).item().Name;\r\n \treturn true;\r\n } catch(e) {\r\n \treturn false;\r\n }\r\n}",
"function is_schedulable(schedule){\n return (check_cpu_utilization(schedule.workload.tasks) <= 1)\n &&\n (check_each_task_executes_in_period(schedule).total_result)\n &&\n (check_no_jobs_overlap(schedule))\n &&\n (check_no_jobs_unscheduled(schedule).length == 0)\n &&\n (check_job_intervals(schedule));\n}",
"run() {\n // Executes the scheduler in an infinite loop as long as there are processes in any of the queues\n while (true) {\n //log the current time\n const time Date.now();\n //take the difference between the current time and the\n //time logged by the last loop iteration\n const workTime = time - this.clock;\n // updated this.clock\n this.clock = time;\n\n // check the block queue to see if there are any processes there\n if (!this.blockingQueue.isEmpty()) {\n //if not empty will do blocking work\n this.blockingQueue.doBlockingWork(workTime);\n }\n\n //do some work on the cpu queues\n //use loop to start and break on finding a process\n for (let i = 0; i < PRIORITY_LEVELS; i++) {\n const queue = this.runningQueues[i];\n if (!queue.isEmpty()) {\n queue.doCPUTWORK(workTime);\n break;\n }\n }\n\n //check if all the queues are empty\n if (this.allQueuesEmpty()) {\n console.log(\"Idle mode\");\n break;\n }\n\n }\n\n }",
"function moduleCanExecute(module) {\n return modulesAreReady(module.requiring.items);\n }",
"function procExists(host) {\n return typeof getProc(host) != 'undefined'\n}",
"function waterfallTradeWorker() {\n if (STATE.TRADING) {\n return false;\n } else {\n // Check if ther eare things on the queue or not\n if (STATE.ORDER_QUEUE.length > 0) {\n logToFile('waterfall trade worker, going to execute order and take one off the order queue', true);\n logToFile(STATE.ORDER_QUEUE);\n // Execute the order\n executeOrder(STATE.ORDER_QUEUE.shift());\n }\n }\n}",
"function doCheckJobsProcess ()\n{\n if (!parseJobsReq.registeredJobs.length) {\n /* If there is no registered jobs, do not subscribe for jobs events */\n return;\n }\n\tjobsApi.jobs.on('job complete', function (id) {\n\t\tlogutils.logger.info(\"We are on jobs.on for event 'job complete', id:\" + id);\n\t\tjobsApi.kue.Job.get(id, function (err, job) {\n\t\t\tif ((err) || (null == job)) {\n\t\t\t\tlogutils.logger.error(\"Some error happened or job is null: \" +\n\t\t\t\t\terr + \" processID: \" + process.pid);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlogutils.logger.debug(\"Job \" + job.id + \" completed by process: \" + process.pid);\n\t\t\tcheckAndRequeueJobs(job);\n\t\t});\n\t});\n}",
"async _reserveAndProcess() {\n const session = await this._reserve(0);\n const timeout = 0;\n\n for (let tries = 0 ; tries < 2 ; ++tries) {\n try {\n\n let [jobID, payload] = await session.request('reserve_with_timeout', timeout);\n await this._runAndDestroy(session, jobID, payload);\n await this._reserveAndProcess();\n return true; // At least one job processed, resolve to true\n\n } catch (error) {\n if (!(error instanceof QueueError))\n throw error;\n }\n }\n return false; // Job not processed, but go on\n }",
"function scriptCanExecute(script) {\n if (script.requiresAll) {\n for (var i=0, files = Object.keys(fileModules), n=files.length; i<n; i++) {\n if (!fileModules[files[i]].isReady()) return false;\n }\n return true;\n } else {\n return modulesAreReady(script.requiring.items);\n }\n }",
"async function isSimulatorAppRunningAsync() {\n try {\n const zeroMeansNo = (await osascript.execAsync('tell app \"System Events\" to count processes whose name is \"Simulator\"')).trim();\n if (zeroMeansNo === '0') {\n return false;\n }\n }\n catch (error) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n return true;\n}",
"function checkIfProcessed(redditData, db, r) {\n db.get(\"SELECT name FROM redditPost WHERE name='\" + redditData.name + \"' AND processed='1'\", function (error, postId) {\n if (!postId) {\n console.log(\"Processing post\");\n checkIfEvent(redditData, db, r);\n }\n });\n}",
"function _canPromote() {\n return (remainingSeconds <= 0);\n }",
"get isExternallyProcessed() {\n const activeApplicationFlow = this.belongsTo(\n 'activeApplicationFlow'\n ).value();\n const firstApplicationStep = activeApplicationFlow\n .belongsTo('firstApplicationStep')\n .value();\n const externalProcessLink = firstApplicationStep.externalProcessLink;\n const isExternallyProcessed = firstApplicationStep\n .belongsTo('subsidyProceduralStep')\n .value().isExternallyProcessed;\n\n if (externalProcessLink && !isExternallyProcessed) {\n console.warn(\n 'found a link to an external processes, but step is not marked for external processing.'\n );\n\n return false;\n } else if (!externalProcessLink && isExternallyProcessed) {\n console.warn(\n 'found no link to an external processes, but step is marked for external processing.'\n );\n\n return true;\n }\n\n return externalProcessLink && isExternallyProcessed;\n }",
"isCompletedRunCurrent () {\n return this.runCurrent?.RunDigest && Mdf.isRunCompleted(this.runCurrent)\n }",
"manageTimeSlice(currentProcess, time) {\n // manageTimeSlice() is only for handling a running process. If blocking process, handle it differently\n if (currentProcess.isStateChanged()) {\n this.quantumClock = 0; // so that the next process that gets dequeued starts off with its full time.\n return;\n }\n // otherwise it is a running process\n this.quantumClock += time;\n // check to see if the process has used up all of its alloted time\n if (this.quantumClock >= this.quantum) {\n // reset quantumClock for next process\n this.quantumClock = 0;\n // dequeueing because either the process is finished and needs to be removed from scheduler, or did not finish and needs to put in another priority queue\n const process = this.dequeue();\n\n if (!process.isFinished()) {\n this.scheduler.handleInterrupt(\n this,\n process,\n SchedulerInterrupt.LOWER_PRIORITY\n );\n }\n }\n }",
"function isWaitingListExisting() {\n\tvar waitingList = spaceExpressConsoleDrawing.employeesWaiting;\n\tif(waitingList.length > 0) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function isQaTask(taskName) {\n var isQA = false;\n if (QATasks.has(taskName)) {\n isQA = true;\n }\n return isQA;\n }",
"isUseCurrentAsBaseRun () {\n return this.isCompletedRunCurrent && (!this.isReadonlyWorksetCurrent || this.isPartialWorkset())\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables only the markers in the specified timerange, all other markers are hidden | function selectMarkers(start, end)
{
for(index in markers)
{
current = markers[index].frameNo;
if(current >= start && current <= end)
{
markers[index].setVisible(true);
}
else
{
markers[index].setVisible(false);
}
}
markerCluster.repaint();
resetInfoWindow();
} | [
"function showMarkersWithinRange(range)\n{\n\t// the range is in miles\n\tvar milesToMeters = 1609.34;\n\trange = range*milesToMeters;\n\t// Try W3C Geolocation (Preferred)\n\tif(navigator.geolocation) {\n\tbrowserSupportFlag = true;\n\tnavigator.geolocation.getCurrentPosition(function(position) {\n\t initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);\n\t // if a location is sucessfuly obtained, clear all marrkes\n\t clearMarkers();\n\n\t // redisplay makers which are with the specified range \n\t for(i=0;i<markers.length;i++) {\n\t \tif (google.maps.geometry.spherical.computeDistanceBetween(initialLocation, markers[i].getPosition()) <= range)\n\t\t{ \n\t\t\tmarkers[i].setMap(map);\n\t\t\tmarkers[i].setVisible(true);\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\t }\n\t \n\t // recenter and zoom map to show all visible markers\n\t updateMapToShowAllMarkers();\n\t\n\t}, function() {\n\t handleNoGeolocation(browserSupportFlag);\n\t});\n\t}\n\t// Browser doesn't support Geolocation\n\telse {\n\tbrowserSupportFlag = false;\n\thandleNoGeolocation(browserSupportFlag);\n\t}\n\t\n\t// if an error occours in getting the location, display all of the markers\n\tfunction handleNoGeolocation(errorFlag) {\n\tif (errorFlag == true) { \n\t showMarkers();\n\t updateMapToShowAllMarkers();\n\t} else {\n\t showMarkers();\n\t updateMapToShowAllMarkers();\n\t}\n\t}\n}",
"function adjustVisibleTimeRangeToAccommodateAllEvents() {\r\n timeline.setVisibleChartRangeAuto();\r\n}",
"function toggleIpMarkers() {\n if (ipMarkersVisible) {\n ipMarkersGroup.remove();\n $('#ipLegendLabel').css('text-decoration', 'line-through');\n ipMarkersVisible = false;\n } else {\n ipMarkersGroup.addTo(mymap);\n $('#ipLegendLabel').css('text-decoration', 'none');\n ipMarkersVisible = true;\n }\n}",
"function toggleScrapingMarkers() {\n if (scrapingMarkersVisible) {\n scrapingMarkersGroup.remove();\n $('#scrapingLegendLabel').css('text-decoration', 'line-through');\n scrapingMarkersVisible = false;\n } else {\n scrapingMarkersGroup.addTo(mymap);\n $('#scrapingLegendLabel').css('text-decoration', 'none');\n scrapingMarkersVisible = true;\n }\n}",
"function enableBrushTime() {\n var range = x2.domain()[1] - x2.domain()[0];\n if (range > 3600000) {\n //enable 1h button\n $('[name=oneHour]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24) {\n //enable 1d button\n $('[name=oneDay]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24 * 7) {\n //enable 1w button\n $('[name=oneWeek]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24 * 30) {\n //enable 1month button\n $('[name=oneMonth]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24 * 365) {\n //enable 1y button\n $('[name=oneYear]', topToolbar).prop('disabled', false);\n }\n }",
"function show(type) {\n for (var i=0; i<gmarkers.length; i++) {\n if (gmarkers[i].type == type) {\n gmarkers[i].setVisible(true);\n }\n }\n $(\"#filter_\"+type).removeClass(\"inactive\");\n}",
"function changeVisibilitybyTime(time){\n\t// if current selected object is on the spline \n\tif (INTERSECTED) {\n\t\t// detach object if the spline has autoboxes for clear view \n\t\tif (INTERSECTED.name.dynamic == 1 && splineIsAutoBoxed[INTERSECTED.name.dynamicSeq]==1){ \n\t\t\tlabels[currentIdx].name.level_min = paras.level_min;\n\t\t\tlabels[currentIdx].name.level_max = paras.level_max;\n\t\t\tlabels_helper[currentIdx].material.linewidth = 1;\n\t\t\tattachControlCubes(INTERSECTED, [], false);\n\t\t}\n\t}\n\tfor (var i=0; i<labels.length; i++){\n\t\tif (labels[i].name.dynamic==0) { continue; }\n\t\t// visible if timestamp of the object is equal to the speficied time \n\t\tif (labels[i].name.timestamp == time){\n\t\t\tlabels[i].visible = controlHandler.showAnnotation;\n\t\t\tlabels_helper[i].visible = controlHandler.showAnnotation;\n\t\t\tlabels_arrow[i].visible = controlHandler.showAnnotation;\n\t\t}\n\t\t// visible if autoBox is not toggled \n\t\telse if (splineIsAutoBoxed[labels[i].name.dynamicSeq] == 0){\n\t\t\tlabels[i].visible = controlHandler.showAnnotation;\n\t\t\tlabels_helper[i].visible = controlHandler.showAnnotation;\n\t\t\tlabels_arrow[i].visible = controlHandler.showAnnotation;\n\t\t}\n\t\telse {\n\t\t\tlabels[i].visible = false;\n\t\t\tlabels_helper[i].visible = false;\n\t\t\tlabels_arrow[i].visible = false;\n\t\t}\n\n\t\t// if visibleSeq is specified, hide the other objects in different seqs\n\t\tif (controlHandler.dispMode==5 && labels[i].name.dynamicSeq!=visibleSeq) {\n\t\t\tlabels[i].visible = false;\n\t\t\tlabels_helper[i].visible = false;\n\t\t\tlabels_arrow[i].visible = false;\n\t\t}\n\t}\n\n}",
"function addruler (checked) {\r\r\n var map=$('#gmapArea').gmap3({'get' : 'map'});\r\r\n if (checked == true) {\r\r\n // show the ruler\r\r\n ruler1 = new google.maps.Marker({\r\r\n position: map.getCenter() ,\r\r\n map: map,\r\r\n options:{icon: \"mapMarkers/yellow-dot.png\"},\r\r\n draggable: true,\r\r\n zIndex: 999\r\r\n });\r\r\n \r\r\n ruler2 = new google.maps.Marker({\r\r\n position: map.getCenter() ,\r\r\n map: map,\r\r\n options:{icon: \"mapMarkers/yellow-dot.png\"},\r\r\n draggable: true,\r\r\n zIndex: 999\r\r\n });\r\r\n \r\r\n rulerpoly = new google.maps.Polyline({\r\r\n path: [ruler1.position, ruler2.position] ,\r\r\n strokeColor: \"#FFFF00\",\r\r\n strokeOpacity: .7,\r\r\n strokeWeight: 4\r\r\n });\r\r\n rulerpoly.setMap(map);\r\r\n \r\r\n \r\r\n google.maps.event.addListener(ruler1, 'drag', function() {\r\r\n showRulerLen();\r\r\n });\r\r\n \r\r\n google.maps.event.addListener(ruler2, 'drag', function() {\r\r\n showRulerLen();\r\r\n });\r\r\n } else {\r\r\n // hide the ruler\r\r\n ruler1.setMap(null);\r\r\n ruler2.setMap(null);\r\r\n rulerpoly.setMap(null);\r\r\n $(\"#rulerLen\").html(\"xxx.xx\");\r\r\n }\r\r\n}",
"function dragstart(e) {\n marker.dragging.disable();\n}",
"changeMarker() {\n\t\t_.forEach(this.markers, (a) => a.style.display = this.saved ? 'inline' : '');\n\t}",
"transparentMarker(){\n\t\tthis.moveableSprites.forEach(moveableFocus =>{\n\t\t\tmoveableFocus.alpha -= 0.7;\n\t\t})\n\t\tthis.hitmarker.forEach(hit =>{\n\t\t\thit.alpha -= 0.2;\n\t\t})\n\t}",
"function MapLayers_Time_CreateSlider() {\n\nMapLayers.Time.\nToolbar = new MapLayers.Time._TimeBar();\n\n}",
"function toggleTrialMap() {\n\tvar map = $('#g_map');\n\t\n\t// hide\n\tif (map.is(':visible')) {\n\t\tvar link_offset = $('#g_map_toggle').offset().top - $(window).scrollTop();\n\t\tgeo_hideMap();\n\t\tgeo_clearAllPins();\n\t\t$('#g_map_toggle > a').text('Show Map');\n\t\t$('#selected_trial').empty().hide();\n\t\t\n\t\t// scroll in place\n\t\tvar new_offset = $('#g_map_toggle').offset().top - $(window).scrollTop();\n\t\tif (Math.abs(link_offset - new_offset) > 50) {\n\t\t\t$(window).scrollTop(Math.max(0, $('#g_map_toggle').offset().top - link_offset));\n\t\t}\n\t}\n\t\n\t// show\n\telse {\n\t\tgeo_showMap();\n\t\t// map.append('<div id=\"g_map_loading\">Loading...</div>');\n\t\t$('#g_map_toggle > a').text('Hide Map');\n\t\t\n\t\t// pins\n\t\twindow.setTimeout(function() {\n\t\t\tupdateTrialLocations();\n\t\t}, 200);\n\t}\n}",
"function enableDistrictSelect() {\n\n\tcleanMap();\t\n\tselectControl.activate();\n\n}",
"function RouteRangeControl(options) {\n var _this = _super.call(this) || this;\n /****************************\n * Private Properties\n ***************************/\n /** Default options. */\n _this._options = {\n markerOptions: {\n color: '#F2C811',\n secondaryColor: '#011C2C',\n htmlContent: '<svg xmlns=\"http://www.w3.org/2000/svg\" style=\"cursor:move\" width=\"28px\" height=\"39px\" viewBox=\"-1 -1 27 38\"><path d=\"M12.25.25a12.254 12.254 0 0 0-12 12.494c0 6.444 6.488 12.109 11.059 22.564.549 1.256 1.333 1.256 1.882 0C17.762 24.853 24.25 19.186 24.25 12.744A12.254 12.254 0 0 0 12.25.25Z\" style=\"fill:{color};stroke:{secondaryColor};stroke-width:2\"/><g style=\"transform:scale(0.2);transform-origin: 13% 10%;\"><path d=\"m50 38h-4v14c0 0 0 1 0 1l9 9 2-2-9-9v-13z\" fill=\"{secondaryColor}\" stroke=\"{secondaryColor}\" stroke-width=\"2px\"/><path d=\"m48 81c-15 0-28-12-28-28s12-28 28-28 28 12 28 28-12 28-28 28zm23-52 3-3c1-1 1-3-0-4-1-1-3-1-4-0l-3 3c-4-3-10-5-16-5v-4h9v-6h-24v6h9v4c-15 1-28 13-30 29s7 31 22 36 31-0 40-14 6-31-5-42z\" fill=\"{secondaryColor}\" stroke=\"{secondaryColor}\" stroke-width=\"2px\"/></g></svg>'\n },\n style: azmaps.ControlStyle.light,\n isVisible: true,\n position: 'left',\n collapsible: false,\n calculateOnMarkerMove: true\n };\n /** How long to delay a search after the marker has been moved using the keyboard. */\n _this._markerMoveSearchDelay = 600;\n /** How many pixels the marker will move for an arrow key press occurs on the top level route range container. */\n _this._arrowKeyOffset = 5;\n /** When map is small, this specifies how long the options should be hidden to give the user a chance to move the marker. */\n _this._showOptionsDelay = 0;\n /** Data bound settings used for requesting a route range polygon. */\n _this._settings = {};\n /****************************\n * Private Methods\n ***************************/\n /**\n * Callback function for when localization resources have loaded.\n * Create the content of the container.\n * @param resx The localization resource.\n */\n _this._createContainer = function (resx) {\n //Cache variables and function for better minification. \n var self = _this;\n var css = RouteRangeControl._css;\n var createElm = Utils.createElm;\n //Create a binding to the settings object.\n var binding = new SimpleBinding(self._settings);\n self._binding = binding;\n //Create the main container.\n var container = Utils.createElm('div', {\n class: ['azure-maps-control-container', RouteRangeControl._css.container],\n style: {\n display: (self._options.isVisible) ? '' : 'none'\n },\n attr: {\n 'aria-label': resx.routeRangeControl,\n tabindex: '-1'\n }\n });\n container.addEventListener('keydown', _this._onContainerKeyDown);\n self._container = container;\n //Create travelTime option.\n //<input type=\"number\" value=\"15\" min=\"1\" max=\"1440\">\n var travelTime = createElm('input', {\n attr: {\n type: 'number',\n value: '15',\n min: '1',\n max: '1440'\n },\n propName: 'travelTime'\n }, resx, binding);\n var timeOptionRow = self._createOptionRow(resx.travelTime, travelTime);\n //Create distance options.\n /*\n <input type=\"number\" value=\"5\" min=\"1\" max=\"1000\">\n <select class=\"distanceUnits\">\n <option value=\"meters\">Meters</option>\n <option value=\"miles\">Miles</option>\n <option value=\"kilometers\" selected>Kilometers</option>\n <option value=\"yards\">Yards</option>\n </select>\n */\n var distance = createElm('input', {\n attr: {\n type: 'number',\n value: '5',\n min: '1',\n max: '1000'\n },\n propName: 'distance'\n }, resx, binding);\n var distanceUnits = createElm('select', {\n selectVals: ['meters', 'miles', 'kilometers', 'yards'],\n selected: 'kilometers',\n propName: 'distanceUnits'\n }, resx, binding);\n var distanceOptionRow = self._createOptionRow(resx.distance, [distance, distanceUnits]);\n //Create show area option.\n //<input type=\"checkbox\" checked=\"checked\"/>\n var showArea = createElm('input', {\n attr: {\n type: 'checkbox',\n checked: 'checked'\n },\n propName: 'showArea'\n }, resx, binding);\n //Create traffic options.\n /*\n <div class=\"atlas-route-range-row traffic-option\" style=\"display:none;\">\n <div class=\"atlas-route-range-col1\">Leave at</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"date\">\n <input type=\"time\" step=\"300\">\n </div>\n </div>\n */\n var leaveAtDate = createElm('input', {\n attr: {\n type: 'date'\n },\n style: {\n marginBottom: '3px'\n },\n propName: 'leaveAtDate'\n }, resx, binding);\n var leaveAtTime = createElm('input', {\n attr: {\n type: 'time',\n step: '300'\n },\n propName: 'leaveAtTime'\n }, resx, binding);\n var trafficOption = self._createOptionRow(resx.leaveAt, [leaveAtDate, leaveAtTime]);\n trafficOption.style.display = 'none';\n var isDateTimeSupported = Utils.isDateTimeInputSupported();\n //Set the initial date/time to the current date/time to the next 5 minute round value.\n if (isDateTimeSupported) {\n //Set the date and time pickers.\n var d = new Date();\n var hour = d.getHours();\n var min = d.getMinutes();\n //Round minutes to the next 5 minute.\n min = Math.ceil(min / 5) * 5;\n if (min === 60) {\n hour++;\n min = 0;\n }\n d = new Date(d.toDateString());\n d = new Date(d.setHours(hour, min));\n //Just in case the hours have increased into a new day.\n hour = d.getHours();\n self._settings.leaveAtDate = d.toISOString().split('T')[0];\n leaveAtDate.value = self._settings.leaveAtDate;\n leaveAtDate.setAttribute('min', self._settings.leaveAtDate);\n var hh = ((hour < 10) ? '0' : '') + Utils.USNumberFormat(hour);\n var mm = ((min < 10) ? '0' : '') + Utils.USNumberFormat(min);\n self._settings.leaveAtTime = hh + \":\" + mm;\n leaveAtTime.value = self._settings.leaveAtTime;\n }\n //Create length options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Length</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n <select>\n <option value=\"feet\">Feet</option>\n <option value=\"meters\" selected>Meters</option>\n <option value=\"yards\">Yards</option>\n </select>\n </div>\n </div>\n */\n var length = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'length'\n }, resx, binding);\n var lengthUnits = createElm('select', {\n selectVals: ['feet', 'meters', 'yards'],\n selected: 'meters',\n propName: 'lengthUnits'\n }, resx, binding);\n var lengthRow = self._createOptionRow(resx.length, [length, lengthUnits], true);\n //Create height options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Height</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n </div>\n </div>\n */\n var height = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'height'\n }, resx, binding);\n var heightRow = self._createOptionRow(resx.height, height, true);\n //Create width options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Width</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n </div>\n </div>\n */\n var width = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'width'\n }, resx, binding);\n var widthRow = self._createOptionRow(resx.width, width, true);\n //Create weight options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">Axle weight</div>\n <div class=\"atlas-route-range-col2\">\n <input type=\"number\" min=\"0\"/>\n <select>\n <option value=\"kilograms\" selected>Kilograms</option>\n <option value=\"longTon\">Long ton</option>\n <option value=\"metricTon\">Metric ton</option>\n <option value=\"pounds\">Pounds</option>\n <option value=\"shortTon\">Short ton</option>\n </select>\n </div>\n </div>\n */\n var axleWeight = createElm('input', {\n attr: {\n type: 'number',\n min: '0'\n },\n propName: 'axleWeight'\n }, resx, binding);\n var weightUnits = createElm('select', {\n selectVals: ['kilograms', 'longTon', 'metricTon', 'pounds', 'shortTon'],\n selected: 'kilograms',\n propName: 'weightUnits'\n }, resx, binding);\n var weightRow = self._createOptionRow(resx.axleWeight, [axleWeight, weightUnits], true);\n //Create toggle button for truck dimensions.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">\n <button class=\"atlas-route-range-expand-btn\" aria-expanded=\"false\" aria-label=\"Toggle truck dimension options\">Truck dimensions <span class=\"atlas-route-range-toggle-icon\"></span></button>\n </div>\n </div>\n */\n var truckDimensionsToggle = self._createToggleBtn(resx.truckDimensions, resx.truckDimensionsToggle, [\n lengthRow, heightRow, widthRow, weightRow\n ]);\n //Create load type options.\n /*\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">\n <button class=\"atlas-route-range-expand-btn\" aria-expanded=\"false\" aria-label=\"Toggle load type options\">Load type <span class=\"atlas-route-range-toggle-icon\"></span></button>\n </div>\n </div>\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\" style=\"display:none;\">\n <input value=\"USHazmatClass2\" type=\"checkbox\"/>Compressed gas<br/>\n <input value=\"USHazmatClass8\" type=\"checkbox\"/>Corrosives<br/>\n <input value=\"USHazmatClass1\" type=\"checkbox\"/>Explosives<br/>\n <input value=\"USHazmatClass3\" type=\"checkbox\"/>Flammable liquids<br/>\n <input value=\"USHazmatClass4\" type=\"checkbox\"/>Flammable solids\n </div>\n <div class=\"atlas-route-range-col2\" style=\"display:none;\">\n <input value=\"otherHazmatHarmfulToWater\" type=\"checkbox\"/>Harmful to water<br/>\n <input value=\"USHazmatClass9\" type=\"checkbox\"/>Miscellaneous<br/>\n <input value=\"USHazmatClass5\" type=\"checkbox\"/>Oxidizers<br/>\n <input value=\"USHazmatClass6\" type=\"checkbox\"/>Poisons<br/>\n <input value=\"USHazmatClass7\" type=\"checkbox\"/>Radioactive\n </div>\n </div>\n */\n var loadTypeOptions = self._createCheckboxGroup('loadType', ['USHazmatClass2', 'USHazmatClass8', 'USHazmatClass1', 'USHazmatClass3', 'USHazmatClass4', 'otherHazmatHarmfulToWater', 'USHazmatClass9', 'USHazmatClass5', 'USHazmatClass6', 'USHazmatClass7'], resx, function (values) {\n //Cross reference USHazmatClass1 with otherHazmatExplosive.\n var USHazmatClass1 = values.indexOf('USHazmatClass1');\n var otherHazmatExplosive = values.indexOf('otherHazmatExplosive');\n if (USHazmatClass1 > 0) {\n if (otherHazmatExplosive === -1) {\n values.push('otherHazmatExplosive');\n }\n }\n else if (otherHazmatExplosive > 0) {\n //Remove this value as the USHazmatClass1 is unselected.\n values = values.splice(otherHazmatExplosive, 1);\n }\n //Cross reference USHazmatClass9 with otherHazmatGeneral.\n var USHazmatClass9 = values.indexOf('USHazmatClass9');\n var otherHazmatGeneral = values.indexOf('otherHazmatGeneral');\n if (USHazmatClass9 > 0) {\n if (otherHazmatGeneral === -1) {\n values.push('otherHazmatGeneral');\n }\n }\n else if (otherHazmatGeneral > 0) {\n //Remove this value as the USHazmatClass9 is unselected.\n values = values.splice(otherHazmatGeneral, 1);\n }\n });\n //Group truck options.\n var truckToggleOptions = [truckDimensionsToggle, loadTypeOptions[0]];\n // const truckOptions = [lengthRow, heightRow, widthRow, weightRow, loadTypeOptions[1]];\n //Create avoid options.\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\">\n <button class=\"atlas-route-range-expand-btn\" aria-expanded=\"false\" aria-label=\"Toggle avoid type options list\">Avoid <span class=\"atlas-route-range-toggle-icon\"></span></button>\n </div>\n </div>\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\" style=\"display:none;\">\n <input value=\"borderCrossings\" type=\"checkbox\" />Border crossings<br/>\n <input value=\"carpools\" type=\"checkbox\" />Carpools<br/>\n <input value=\"ferries\" type=\"checkbox\" />Ferries\n </div>\n <div class=\"atlas-route-range-col2\" style=\"display:none;\">\n <input value=\"motorways\" type=\"checkbox\" />Motorways<br/>\n <input value=\"tollRoads\" type=\"checkbox\" />Toll roads<br/>\n <input value=\"unpavedRoads\" type=\"checkbox\" />Unpaved roads\n </div>\n </div>\n */\n var avoidOptions = self._createCheckboxGroup('avoid', ['borderCrossings', 'carpools', 'ferries', 'motorways', 'tollRoads', 'unpavedRoads'], resx);\n //Create traffic option.\n var useTraffic = createElm('input', {\n attr: { type: 'checkbox' },\n propName: 'traffic',\n bindingChanged: function (val) {\n trafficOption.style.display = self._getDateTimePickerDisplay();\n }\n }, resx, binding);\n var useTrafficRow = self._createOptionRow(resx.traffic, useTraffic);\n //Create selection area option.\n /*\n <select>\n <option value=\"distance\">Distance</option>\n <option value=\"time\" selected>Time</option>\n </select>\n */\n var selectionArea = createElm('select', {\n selectVals: ['distance', 'time'],\n selected: 'time',\n propName: 'selectionArea',\n bindingChanged: function (val) {\n //Hide/show options depending on the selection area value.\n var isTime = (val === 'time');\n timeOptionRow.style.display = (isTime) ? '' : 'none';\n distanceOptionRow.style.display = (!isTime) ? '' : 'none';\n useTrafficRow.style.display = (isTime && (self._settings.travelMode === 'car' || self._settings.travelMode === 'truck')) ? '' : 'none';\n trafficOption.style.display = self._getDateTimePickerDisplay();\n }\n }, resx, binding);\n //Create travel mode option.\n /*\n <select>\n <option value=\"car\" selected>Car</option>\n <option value=\"bicycle\">Bicycle</option>\n <option value=\"pedestrian\">Pedestrian</option>\n <option value=\"truck\">Truck</option>\n </select>\n */\n var travelMode = createElm('select', {\n selectVals: ['car', 'bicycle', 'pedestrian', 'truck'],\n selected: 'car',\n propName: 'travelMode',\n bindingChanged: function (val) {\n //Hide/show certain options depending on the selected travel mode.\n var isVehicle = true;\n var isTruck = false;\n switch (val) {\n case 'pedestrian':\n case 'bicycle':\n isVehicle = false;\n break;\n case 'truck':\n isTruck = true;\n break;\n }\n avoidOptions.forEach(function (ao) {\n ao.style.display = (isVehicle) ? '' : 'none';\n });\n truckToggleOptions.forEach(function (toggle) {\n toggle.style.display = (isTruck) ? '' : 'none';\n //Toggle close all truck options if not showing truck,\n if (!isTruck && toggle.getAttribute('aria-expanded') === 'true') {\n toggle.click();\n }\n });\n useTrafficRow.style.display = (isVehicle && self._settings.selectionArea === 'time') ? '' : 'none';\n trafficOption.style.display = self._getDateTimePickerDisplay();\n }\n }, resx, binding);\n //Create buttons\n /*\n <div class=\"atlas-route-range-row\">\n <div class=\"atlas-route-range-col1\"><button class=\"atlas-route-range-search-btn\">Search</button></div>\n <div class=\"atlas-route-range-col2\"><button class=\"atlas-route-range-cancel-btn\">Cancel</button></div>\n </div>\n */\n //Create search button.\n var searchBtn = createElm('button', {\n class: [css.searchBtn],\n propName: 'search',\n innerHTML: resx['search']\n }, resx);\n searchBtn.onclick = self._onSearch;\n self._searchBtn = searchBtn;\n //Create cancel button.\n var cancelBtn = createElm('button', {\n class: [css.cancelBtn],\n propName: 'cancel',\n innerHTML: resx['cancel']\n }, resx);\n if (!self._options.collapsible) {\n cancelBtn.style.display = 'none';\n }\n cancelBtn.onclick = self._onCancel;\n //Create button row.\n var btnRow = Utils.createElm('div', {\n class: [css.row],\n style: {\n display: 'block'\n },\n children: [Utils.createElm('div', {\n style: {\n 'text-align': 'center'\n },\n children: [searchBtn, cancelBtn]\n })]\n });\n //Create options container.\n self._optionSection = createElm('div', { class: [css.options], children: [\n //Add travel mode.\n self._createOptionRow(resx.travelMode, travelMode),\n //Add selection area option.\n self._createOptionRow(resx.selectionArea, selectionArea),\n //Add travelTime option.\n timeOptionRow,\n //Add distance options.\n distanceOptionRow,\n //Add show area option.\n self._createOptionRow(resx.showArea, showArea),\n //Add use traffic option.\n useTrafficRow,\n //Add traffic option.\n trafficOption,\n //Add truck dimension toggle.\n truckDimensionsToggle,\n //Add truck dimenion options.\n lengthRow, heightRow, widthRow, weightRow,\n //Add load type options.\n loadTypeOptions[0], loadTypeOptions[1],\n //Add avoid options.\n avoidOptions[0], avoidOptions[1]\n ] });\n //Add options to container.\n Utils.appendChildren(container, [\n //Add the intstructions.\n createElm('div', { class: [css.instructions], innerHTML: resx.selectOrigin }, resx),\n //Add options container.\n self._optionSection,\n //Add buttons.\n btnRow\n ]);\n self._map.events.add('resize', self._mapResized);\n self._mapResized();\n if (self._options.isVisible) {\n self.setVisible(self._options.isVisible);\n }\n };\n /** Event handler for when the search button is pressed. */\n _this._onSearch = function () {\n //Cache functions and variables for better minification.\n var self = _this;\n var convertDistance = azmaps.math.convertDistance;\n var round = Math.round;\n var request = self._settings;\n //Ensure numbers are properly formatted when converted to a string. Don't allow comma groupings.\n var numberFormatter = Utils.USNumberFormat;\n //Create the query string value. Have to manually create string since loadType and avoid values have to be added as individual parameters which JSON objects don't allow.\n var queryString = []; //encodeURIComponent\n //Origin query\n queryString.push(\"query=\" + numberFormatter(request.origin[1]) + \",\" + numberFormatter(request.origin[0]));\n queryString.push(\"travelMode=\" + request.travelMode);\n if (request.selectionArea === 'time') {\n queryString.push(\"timeBudgetInSec=\" + numberFormatter(round(request.travelTime * 60)));\n if (request.traffic) {\n queryString.push(\"traffic=true\");\n if (request.leaveAtDate && request.leaveAtTime) {\n //Check to see if seconds need to be added.\n var t = request.leaveAtTime;\n if (t.match(/:/g).length === 1) {\n t += ':00';\n }\n //1996-12-19T16:39:57 - Don't specify timezone in request. The service will use the timezone of the origin point automatically.\n queryString.push(\"departAt=\" + request.leaveAtDate + \"T\" + t);\n }\n }\n }\n else {\n queryString.push(\"distanceBudgetInMeters=\" + numberFormatter(round(convertDistance(request.distance, request.distanceUnits, 'meters'))));\n }\n if (request.travelMode === 'car' || request.travelMode === 'truck') {\n //avoid\n if (request.avoid) {\n request.avoid.forEach(function (a) {\n queryString.push(\"avoid=\" + a);\n });\n }\n }\n if (request.travelMode === 'truck') {\n //vehcileLength (m), vehicleWidth (m), vehicleHeight (m), vehicleAxleWeight (kg), vehicleLoadType \n if (!isNaN(request.length)) {\n queryString.push(\"vehcileLength=\" + numberFormatter(round(convertDistance(request.length, request.lengthUnits, 'meters'))));\n }\n if (!isNaN(request.width)) {\n queryString.push(\"vehicleWidth=\" + numberFormatter(round(convertDistance(request.width, request.lengthUnits, 'meters'))));\n }\n if (!isNaN(request.height)) {\n queryString.push(\"vehicleHeight=\" + numberFormatter(round(convertDistance(request.height, request.lengthUnits, 'meters'))));\n }\n if (!isNaN(request.height)) {\n queryString.push(\"vehicleAxleWeight=\" + numberFormatter(round(MapMath.convertWeight(request.axleWeight, request.weightUnits, 'kilograms'))));\n }\n if (request.loadType) {\n request.loadType.forEach(function (lt) {\n queryString.push(\"vehicleLoadType=\" + lt);\n });\n }\n }\n //Create the URL request. \n var url = \"https://\" + self._map.getServiceOptions().domain + \"/route/range/json?api-version=1.0&\" + queryString.join('&');\n //Sign the request. This will use the same authenication that the map is using to access the Azure Maps platform.\n //This gives us the benefit of not having to worry about if this is using subscription key or Azure AD.\n var requestParams = self._map.authentication.signRequest({ url: url });\n fetch(requestParams.url, {\n method: 'GET',\n mode: 'cors',\n headers: new Headers(requestParams.headers)\n })\n .then(function (r) { return r.json(); }, function (e) { return self._invokeEvent('error', self._resx.routeRangeError); })\n .then(function (response) {\n if (response.reachableRange) {\n //Convert the response into GeoJSON and add it to the map.\n var positions = response.reachableRange.boundary.map(function (latLng) {\n return [latLng.longitude, latLng.latitude];\n });\n var isochrone = new azmaps.data.Polygon([positions]);\n self._invokeEvent('rangecalculated', isochrone);\n if (self._settings.showArea) {\n self._invokeEvent('showrange', isochrone);\n }\n }\n else {\n self._invokeEvent('error', self._resx.routeRangeError);\n }\n }, function (error) { return self._invokeEvent('error', self._resx.routeRangeError); });\n if (self._options.collapsible) {\n //Hide the input panel and marker.\n self.setVisible(false);\n }\n };\n /** Event handler for when the cancel button is clicked. */\n _this._onCancel = function () {\n //Hide the input panel and marker.\n _this.setVisible(false);\n };\n /** Event handler for when the origin marker is dragged. */\n _this._onMarkerDragged = function () {\n var self = _this;\n self._settings.origin = self._marker.getOptions().position;\n self._optionSection.style.display = '';\n self._searchBtn.style.display = '';\n self._hideOptionsTimeout = null;\n if (self._options.calculateOnMarkerMove) {\n self._onSearch();\n }\n };\n /** Clears the timeout that is preventing the route range options panel from appearing. */\n _this._onMarkerDargStart = function () {\n if (_this._hideOptionsTimeout) {\n clearTimeout(_this._hideOptionsTimeout);\n _this._hideOptionsTimeout = null;\n }\n };\n /** Event handler for when a the container has focus and arrow keys are used to adjust the position of the marker. */\n _this._onContainerKeyDown = function (e) {\n //If the top level container has focus and an arrow key is pressed, move the marker.\n if (e.keyCode > 36 && e.keyCode < 41 && e.target.classList.contains('azure-maps-control-container')) {\n var self_1 = _this;\n //Convert the position of the marker to pixels based on the current zoom level of the map, then offset it accordingly. \n var zoom = self_1._map.getCamera().zoom;\n var pixel = azmaps.math.mercatorPositionsToPixels([self_1._marker.getOptions().position], zoom)[0];\n var offset = self_1._arrowKeyOffset;\n //Left arrow = 37, Up arrow = 38, Right arrow = 39, Down arrow = 40\n if (e.keyCode === 37) {\n pixel[0] -= offset;\n }\n else if (e.keyCode === 38) {\n pixel[1] -= offset;\n }\n else if (e.keyCode === 39) {\n pixel[0] += offset;\n }\n else if (e.keyCode === 40) {\n pixel[1] += offset;\n }\n var pos = azmaps.math.mercatorPixelsToPositions([pixel], zoom)[0];\n self_1._marker.setOptions({\n position: pos\n });\n self_1._settings.origin = pos;\n if (self_1._options.calculateOnMarkerMove) {\n if (self_1._markerKeyMoveTimeout) {\n clearTimeout(self_1._markerKeyMoveTimeout);\n }\n self_1._markerKeyMoveTimeout = setTimeout(function () {\n self_1._onSearch();\n }, self_1._markerMoveSearchDelay);\n }\n e.preventDefault();\n e.stopPropagation();\n }\n };\n /** Event handler for when the map resizes. */\n _this._mapResized = function () {\n var self = _this;\n var mapSize = self._map.getMapContainer().getBoundingClientRect();\n //If the map is 750 pixels wide or more, offset the position of the control away from the edge a little.\n var min = '';\n var delay = 0;\n var position = self._options.position;\n if (mapSize.width < 750 || (position === 'center' && mapSize.height < 600)) {\n min = '-min';\n //If the map is less 750 pixels width or 600 pixels high when centered, delay the display of options in the container so that the user has a chance to move the marker before it is covered up. \n //This delay will be be short circuited when the user stops dragging the marker.\n delay = 5000;\n }\n else if (position !== 'center') {\n //Check to see see if there are any other controls on the same side as this control. If not, then minimize the gap between the control and the side of the map.\n var controlContainers = Array.from(self._map.controls['controlContainer'].children);\n var cnt_1 = 0;\n controlContainers.forEach(function (c) {\n if (c.classList.toString().indexOf(position) > -1) {\n cnt_1 += c.children.length;\n }\n });\n if (cnt_1 === 0) {\n min = '-min';\n }\n }\n self._container.classList.remove('left', 'right', 'center', 'left-min', 'right-min', 'center-min');\n self._container.classList.add(position + min);\n self._showOptionsDelay = delay;\n };\n var self = _this;\n if (options.markerOptions) {\n Object.assign(options.markerOptions, self._options.markerOptions);\n }\n self._options = Object.assign(self._options, options || {});\n self._marker = new azmaps.HtmlMarker(Object.assign(self._options.markerOptions, { draggable: true }));\n return _this;\n }",
"startEditing() {\n if (this.editing) return;\n\n // Force the layer to be visible.\n if (!this.meanlines.on) {\n this.SeismogramMap.toggleLayer(this.meanlines);\n }\n\n this.meanlines.leafletLayer.getLayers().forEach((meanline) => {\n // We install the editing events on each mean line\n this.installEventsOnMeanline(meanline);\n // Turn on Leaflet.Editable on the mean line\n meanline.enableEdit();\n });\n\n this.editing = true;\n }",
"function highlight(lat,lng,year,title=null){\r\n\tsetMapOnAll(null);\r\n\tvar index = [lat,lng];\r\n\tx = (year/2) + 350;\r\n\tmovehair(x);\r\n\tvar marker = new google.maps.Marker({\r\n position: new google.maps.LatLng(lat, lng),\r\n title: title,\r\n map: map,\r\n icon: highlightedIcon()\r\n });\r\n\tmarkers.push(marker);\r\n\t// map.setCenter(google.maps.LatLng(lat, lng));\r\n}",
"function disableFunctionOnStartTimeSheet()\r\n {\r\n\t \r\n\t document.getElementById(\"timeSheetMainFunction\").style.display=\"none\"; \r\n\t document.getElementById(\"showStatusOfTimeSheet\").style.display=\"\"; \r\n\t \r\n\t \r\n }",
"function updateFromFilters(){\n\n //$(\"input\").prop('disabled', true);\n\n var newList = _(elements)\n .forEach(function(d){ map.removeLayer(d.marker) })\n .filter(computeFilter)\n .forEach(function(d){ d.marker.addTo(map) })\n .value();\n\n updateList(newList);\n updateFromMap();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Se encarga de mostrar la puntuacion para obtener el autoclic : | function mostrarAutoclic() {
$autoclic.innerHTML = "Autoclic de 5 seconds avec un score de : " + aupoints() + " Cookies ";
} | [
"function colocarNome(nome){\n app.activeDocument.layers[0].visible = true;\n app.activeDocument.layers[0].textItem.contents=nome;\n }",
"function onOpen(e) {\n DocumentApp.getUi().createAddonMenu()\n .addItem('Crypt It', 'doCrypt')\n .addItem('DeCrypt It', 'doDecrypt')\n .addToUi();\n}",
"function cambioPropuesta(){\n if(controlEdificioYPropuesta())\n return;\n\n reiniciarSelect(\"actividad\");\n actualizarTodo(URLS.actividadesDePropuesta,\"actividad\", \"propuesta\", true);\n}",
"function silencios_insert()\n{\n var silencio_nota = document.getElementById('silencio_notas');\n silencio_nota = silencio_nota.value;\n var textarea = document.getElementById('textarea');\n var text = textarea.value;\n var cursor = getCaret(textarea); \n switch (silencio_nota) { \n case \"redonda\":\n text = text.substring(0,cursor)+'_z8'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"blanca\":\n text = text.substring(0,cursor)+'_z4'+text.substring(cursor,text.length);\n textarea.value = text; \n break;\n case \"negra\":\n text = text.substring(0,cursor)+'_z2'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"corchea\":\n text = text.substring(0,cursor)+'_z1'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"semicorchea\":\n text = text.substring(0,cursor)+'_z1/2'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"fusa\":\n text = text.substring(0,cursor)+'_z1/4'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n case \"semifusa\":\n text = text.substring(0,cursor)+'_z1/8'+text.substring(cursor,text.length);\n textarea.value = text;\n break;\n default:\n alert(\"error\");\n break;\n }\n}",
"function showTransciption() {\n cuesList();\n for (i=0; i<cues.length; i++) {\n cues[i].addEventListener(\"click\", jumpToDataTime , false);\n cues[i].addEventListener(\"keydown\", keyFunktion, false);\n\n }\n}",
"afficherMotComplet() {\n var mot = this.mot.toString(true).split('');\n window.conteneurMot.innerHTML = \"Mot : \" + mot.join(' ');\n }",
"function enableCC() {\n\tada$(shell.caption.btnId).className = '';\n\tada$(shell.caption.btnId).style.cursor = 'pointer';\n\tada$(shell.caption.btnId).title = shell.caption.name;\n\tCCIsDim = false;\n}",
"function updateKeypadScreen() {\n\tvar l = pin.length;\n\tif (l <= 0) {\n\t\t// Stringa vuota\n\t\tkeypadScreen.textContent = \"PIN\";\n\t} else {\n\t\tvar i, s = \"\";\n\t\tfor (i = 0; i < l; i++) {\n\t\t\ts += \"*\";\n\t\t}\n\t\tkeypadScreen.textContent = s;\n\t}\n}",
"function poids()\n{\n message.channel.send({ embed: {\n color:0x00AE86,\n title:'Création du personnage',\n description: 'Quel est votre poids (en kg)?',\n } });\n}",
"function mostrarAutos(autos) {\n // Elimina los resultados previos del html\n limpiarHTML();\n\n // Itera en el arreglo autos contenido en el archivo db.js\n autos.forEach(auto => {\n // Crea un párrafo por marca\n const autoHTML = document.createElement('p');\n\n // Al declarar de esta manera, no es necesario que coloquemos: ${auto.marca} ${auto.marca}, solo escribimos ${marca} ${modelo}\n const { marca, modelo, year, puertas, transmision, precio, color } = auto;\n\n\n // Añade la marca para cada auto\n autoHTML.textContent = `\n ${marca} ${modelo} -${year} - ${puertas} puertas - Transmisión: ${transmision} - Color: ${color} - Precio: ${precio} \n `;\n\n // Inserta el HTML al DOM\n resultado.appendChild(autoHTML);\n })\n}",
"function mostrar_segunda_web(){\r\n document.getElementById(\"cabecera_aula\").style.display = 'block';\r\n document.getElementById(\"lema_aula\").style.display = 'block';\r\n document.getElementById(\"contenido_aula\").style.display = 'block';\r\n }",
"function click_btn_descargar_grabadora(){\n\t$(\"#btn_descargar_grabadora\").click(function(){\n\t\tdescargarGrabadoraApk();\n \t});\n}",
"function seleccionar_lapiz() {\n\t\t\therramienta = btn_lapiz.value;\n\t\t}",
"function displayInstructions() {\n textAlign(CENTER);\n textSize(12);\n textFont('Georgia');\n \n fill(\"white\");\n text(\"DIG FOR TREASURE! PRESS 'T' TO SWITCH TOOLS - FIND ALL TREASURE BEFORE YOU RUN OUT OF ENERGY\", width/2, height - 30);\n}",
"function copyright() {\n //Get the selected text and append the extra info\n var selection = window.getSelection(),\n website = 'www.binhbatoday.com', //website\n pagelink = '. Nguồn từ: ' + website, // text\n copytext = selection + pagelink,\n newdiv = document.createElement('div');\n\n //hide the newly created container\n newdiv.style.position = 'absolute';\n newdiv.style.left = '-99999px';\n\n //insert the container, fill it with the extended text, and define the new selection\n document.body.appendChild(newdiv);\n newdiv.innerHTML = copytext;\n selection.selectAllChildren(newdiv);\n\n window.setTimeout(function () {\n document.body.removeChild(newdiv);\n }, 100);\n }",
"function print() {\n document.write(\"atspaudintas su f-ja\");\n}",
"function asciiArtAssist(src,size,color,bgColor){\n\t//default values for src, size, color and bgColor\n\tsrc=!src?'none':src;\n\tsize=!size?'inherit':size;\n\tcolor=!color?'#fff':color;\n\tbgColor=!bgColor?'#000':bgColor;\n\tvar slf=window,txtA,F,r9=slf.Math.random().toFixed(9).replace(/\\./g,''),\n\t\tt=slf.document.getElementsByTagName('body')[0],\n\t\tE=slf.document.createElement('textarea');\n\tE.id='asciiA'+r9;\n\tE.style.cssText=\"color: \"+color+\";font-size: \"+size+\";background: url(\\'\"+src+\"\\') \"+bgColor+\" no-repeat;\";\n\ttxtA=t.appendChild(E),t=E=null;\n\t//returned function returns the current value of textarea tag\n\tF=function(){\n\t\treturn document.getElementById('asciiA'+r9).value;\n\t};\n\t//method to close textarea tag\n\tF.close=function(){\n\t\tvar r=document.getElementById('asciiA'+r9);\n\t\tr=r.parentNode.removeChild(r),r=null;\n\t};\n\treturn F;\n}",
"function printDefinition() {\n $(\"#dictionaryDisplay\").removeClass(\"hide\");\n $(\"#dictionaryDisplay\").append(\"<p id='noun'> Noun: \" + noun + \"</p>\");\n $(\"#dictionaryDisplay\").append(\"<p id ='verb'> Verb: \" + verb + \"</p>\");\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adverb'> Adverb: \" + adverb + \"</p>\"\n );\n $(\"#dictionaryDisplay\").append(\n \"<p id ='adjective'> Adjective: \" + adjective + \"</p>\"\n );\n }",
"function clearCC() {\n\t$('#'+shell.caption.textEl).empty();\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `CognitoUserPoolConfigProperty` | function CfnGraphQLApi_CognitoUserPoolConfigPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('appIdClientRegex', cdk.validateString)(properties.appIdClientRegex));
errors.collect(cdk.propertyValidator('awsRegion', cdk.validateString)(properties.awsRegion));
errors.collect(cdk.propertyValidator('userPoolId', cdk.validateString)(properties.userPoolId));
return errors.wrap('supplied properties not correct for "CognitoUserPoolConfigProperty"');
} | [
"function CfnAnomalyDetector_VpcConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('securityGroupIdList', cdk.requiredValidator)(properties.securityGroupIdList));\n errors.collect(cdk.propertyValidator('securityGroupIdList', cdk.listValidator(cdk.validateString))(properties.securityGroupIdList));\n errors.collect(cdk.propertyValidator('subnetIdList', cdk.requiredValidator)(properties.subnetIdList));\n errors.collect(cdk.propertyValidator('subnetIdList', cdk.listValidator(cdk.validateString))(properties.subnetIdList));\n return errors.wrap('supplied properties not correct for \"VpcConfigurationProperty\"');\n}",
"function CfnUser_LoginProfilePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('password', cdk.requiredValidator)(properties.password));\n errors.collect(cdk.propertyValidator('password', cdk.validateString)(properties.password));\n errors.collect(cdk.propertyValidator('passwordResetRequired', cdk.validateBoolean)(properties.passwordResetRequired));\n return errors.wrap('supplied properties not correct for \"LoginProfileProperty\"');\n}",
"function CfnMultiRegionAccessPointPolicyPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('mrapName', cdk.requiredValidator)(properties.mrapName));\n errors.collect(cdk.propertyValidator('mrapName', cdk.validateString)(properties.mrapName));\n errors.collect(cdk.propertyValidator('policy', cdk.requiredValidator)(properties.policy));\n errors.collect(cdk.propertyValidator('policy', cdk.validateObject)(properties.policy));\n return errors.wrap('supplied properties not correct for \"CfnMultiRegionAccessPointPolicyProps\"');\n}",
"function CfnAnomalyDetector_CloudwatchConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n return errors.wrap('supplied properties not correct for \"CloudwatchConfigProperty\"');\n}",
"function CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('grpc', CfnVirtualGateway_VirtualGatewayGrpcConnectionPoolPropertyValidator)(properties.grpc));\n errors.collect(cdk.propertyValidator('http', CfnVirtualGateway_VirtualGatewayHttpConnectionPoolPropertyValidator)(properties.http));\n errors.collect(cdk.propertyValidator('http2', CfnVirtualGateway_VirtualGatewayHttp2ConnectionPoolPropertyValidator)(properties.http2));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayConnectionPoolProperty\"');\n}",
"function CfnAccessPoint_VpcConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('vpcId', cdk.validateString)(properties.vpcId));\n return errors.wrap('supplied properties not correct for \"VpcConfigurationProperty\"');\n}",
"function CfnVirtualNode_VirtualNodeConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('grpc', CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator)(properties.grpc));\n errors.collect(cdk.propertyValidator('http', CfnVirtualNode_VirtualNodeHttpConnectionPoolPropertyValidator)(properties.http));\n errors.collect(cdk.propertyValidator('http2', CfnVirtualNode_VirtualNodeHttp2ConnectionPoolPropertyValidator)(properties.http2));\n errors.collect(cdk.propertyValidator('tcp', CfnVirtualNode_VirtualNodeTcpConnectionPoolPropertyValidator)(properties.tcp));\n return errors.wrap('supplied properties not correct for \"VirtualNodeConnectionPoolProperty\"');\n}",
"function proposalCoordinatorsExists(principalName) {\n\tvar exists = false;\n\toptions = $j('#' + propCoordId + ' > option');\n\tfor (i=0; i<options.length; i++) {\n\t\tif ($j(options[i]).val() == principalName) {\n\t\t\texists = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn exists;\n}",
"function hasProperties(json, properties) {\n return properties.every(property => {\n return json.hasOwnProperty(property);\n });\n}",
"function configValid(config) {\n config.forEach(obj => {\n checkMandatory(confSpec, obj);\n\n forEach(obj, ([key, val]) => {\n configMatchesSpec(val, key, confSpec);\n });\n });\n }",
"function CfnDataSource_OpenSearchServiceConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('awsRegion', cdk.requiredValidator)(properties.awsRegion));\n errors.collect(cdk.propertyValidator('awsRegion', cdk.validateString)(properties.awsRegion));\n errors.collect(cdk.propertyValidator('endpoint', cdk.requiredValidator)(properties.endpoint));\n errors.collect(cdk.propertyValidator('endpoint', cdk.validateString)(properties.endpoint));\n return errors.wrap('supplied properties not correct for \"OpenSearchServiceConfigProperty\"');\n}",
"function optionsMatches(options /*: Object */\n, propertyName /*: string */\n, input /*: string */\n) /*: boolean */{\n return !!(options && options[propertyName] && typeof input === 'string' && (0, _matchesStringOrRegExp.matchesStringOrRegExp)(input, options[propertyName]));\n}",
"function CfnUser_PolicyPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('policyDocument', cdk.requiredValidator)(properties.policyDocument));\n errors.collect(cdk.propertyValidator('policyDocument', cdk.validateObject)(properties.policyDocument));\n errors.collect(cdk.propertyValidator('policyName', cdk.requiredValidator)(properties.policyName));\n errors.collect(cdk.propertyValidator('policyName', cdk.validateString)(properties.policyName));\n return errors.wrap('supplied properties not correct for \"PolicyProperty\"');\n}",
"function CfnMultiRegionAccessPoint_PublicAccessBlockConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('blockPublicAcls', cdk.validateBoolean)(properties.blockPublicAcls));\n errors.collect(cdk.propertyValidator('blockPublicPolicy', cdk.validateBoolean)(properties.blockPublicPolicy));\n errors.collect(cdk.propertyValidator('ignorePublicAcls', cdk.validateBoolean)(properties.ignorePublicAcls));\n errors.collect(cdk.propertyValidator('restrictPublicBuckets', cdk.validateBoolean)(properties.restrictPublicBuckets));\n return errors.wrap('supplied properties not correct for \"PublicAccessBlockConfigurationProperty\"');\n}",
"function CfnAccessPoint_ObjectLambdaConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('allowedFeatures', cdk.listValidator(cdk.validateString))(properties.allowedFeatures));\n errors.collect(cdk.propertyValidator('cloudWatchMetricsEnabled', cdk.validateBoolean)(properties.cloudWatchMetricsEnabled));\n errors.collect(cdk.propertyValidator('supportingAccessPoint', cdk.requiredValidator)(properties.supportingAccessPoint));\n errors.collect(cdk.propertyValidator('supportingAccessPoint', cdk.validateString)(properties.supportingAccessPoint));\n errors.collect(cdk.propertyValidator('transformationConfigurations', cdk.requiredValidator)(properties.transformationConfigurations));\n errors.collect(cdk.propertyValidator('transformationConfigurations', cdk.listValidator(CfnAccessPoint_TransformationConfigurationPropertyValidator))(properties.transformationConfigurations));\n return errors.wrap('supplied properties not correct for \"ObjectLambdaConfigurationProperty\"');\n}",
"function CfnBucket_NotificationConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('eventBridgeConfiguration', CfnBucket_EventBridgeConfigurationPropertyValidator)(properties.eventBridgeConfiguration));\n errors.collect(cdk.propertyValidator('lambdaConfigurations', cdk.listValidator(CfnBucket_LambdaConfigurationPropertyValidator))(properties.lambdaConfigurations));\n errors.collect(cdk.propertyValidator('queueConfigurations', cdk.listValidator(CfnBucket_QueueConfigurationPropertyValidator))(properties.queueConfigurations));\n errors.collect(cdk.propertyValidator('topicConfigurations', cdk.listValidator(CfnBucket_TopicConfigurationPropertyValidator))(properties.topicConfigurations));\n return errors.wrap('supplied properties not correct for \"NotificationConfigurationProperty\"');\n}",
"function CfnBucket_LambdaConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('event', cdk.requiredValidator)(properties.event));\n errors.collect(cdk.propertyValidator('event', cdk.validateString)(properties.event));\n errors.collect(cdk.propertyValidator('filter', CfnBucket_NotificationFilterPropertyValidator)(properties.filter));\n errors.collect(cdk.propertyValidator('function', cdk.requiredValidator)(properties.function));\n errors.collect(cdk.propertyValidator('function', cdk.validateString)(properties.function));\n return errors.wrap('supplied properties not correct for \"LambdaConfigurationProperty\"');\n}",
"function CfnVirtualGateway_VirtualGatewayGrpcConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxRequests', cdk.requiredValidator)(properties.maxRequests));\n errors.collect(cdk.propertyValidator('maxRequests', cdk.validateNumber)(properties.maxRequests));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayGrpcConnectionPoolProperty\"');\n}",
"function CfnBucket_LoggingConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('destinationBucketName', cdk.validateString)(properties.destinationBucketName));\n errors.collect(cdk.propertyValidator('logFilePrefix', cdk.validateString)(properties.logFilePrefix));\n return errors.wrap('supplied properties not correct for \"LoggingConfigurationProperty\"');\n}",
"function CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('maxRequests', cdk.requiredValidator)(properties.maxRequests));\n errors.collect(cdk.propertyValidator('maxRequests', cdk.validateNumber)(properties.maxRequests));\n return errors.wrap('supplied properties not correct for \"VirtualNodeGrpcConnectionPoolProperty\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the input list of hashes as tiles in the index section | function renderHashes(hashes) {
$('#new-note-btn').hide();
$("#new-note-hr").hide();
$("#note-index-container").css('height', '410px');
clearNotesDisplay("hashes");
hashes.forEach(function(hash) {
$(".note-index").append('<div class="note-tile btn btn-block transition-quick" data-id=' + hash + '>' + trimTitle(hash, titleDisplayLen) + '</div>');
});
addTileListener(id=null, type="hash");
} | [
"function renderMemeImagesAsHexagons() {\n gState.renderMode = 'hexagons';\n var elImagesContainer = document.querySelector('.images-container');\n var strHtml = '';\n strHtml += '<ul id=\"hexGrid\">';\n gImages.forEach(function (image, imageIndex) {\n\n strHtml += '<li class= \"hex\" onclick=\"openMemeEditor(' + (imageIndex+1) + ')\"><div class=\"hexIn\"><a class=\"hexLink\" href=\"#\"><img src=\"' + image.url + '\" alt=\"\" /><h1>Click</h1><p>To open Editor</p></a></div></li>';\n\n });\n strHtml += '</ul>';\n elImagesContainer.innerHTML = strHtml;\n}",
"renderTiles() {\n for (const [key, value] of config.tiles.entries()) {\n for (const tile of value) {\n const tileToAdd = new _tile.TileSprite({\n game: this.game,\n location: { x: tile.x, y: tile.y },\n scale: tile.scale,\n tileName: tile.tileName\n });\n this.game.layerManager.layers.get('environmentLayer').add(tileToAdd);\n }\n }\n }",
"renderKey() {\n var context = {\n title: this.title,\n items: this.items\n }\n this.domElement.innerHTML = this.template(context)\n }",
"function highscoreRender(){\n\tscoreListEl.innerHTML = '';\n\n\tfor (var i = 0; i < userScore.length; i++) {\n\t var userName = userScore[i].name;\n \n\t var li = document.createElement('li');\n\t li.textContent = userName +\":\"+ userScore[i].score;\n\t li.setAttribute('data-index', i);\n\n\t scoreListEl.appendChild(li);\n\t}\n}",
"function showRepositories(repositoriesArray) {\n var print = '<h5> Repositories </h5>'\n \n print += \"<table>\";\n\n //Compose the render with stargazers coun and forks from git\n for(var i = 0; i < repositoriesArray.length; i++) {\n print += '<tr>';\n print += '<td>' + repositoriesArray[i].name + '</td>' \n + '<td> <i class=\"fa fa-star\" aria-hidden=\"true\"> </i>' + repositoriesArray[i].stargazers_count + '</td>'\n + '<td> <i class=\"fa fa-code-fork\" aria-hidden=\"true\"> </i>' + repositoriesArray[i].forks + '</td>'; \n print += '</tr>' //tr\n }\n\n print += '</table>' //table\n\n //Add the render to index\n document.getElementById(\"result\").innerHTML = print;\n }",
"function createTiles(){\n // figure out what tile specific information you need to add\n \n // can add all of the tiles here dynamically (which is useful if you are going to make the number of rows and columns adjustable, however you can also just specify them fixed in the HTML)\n}",
"artifactBlockList() {\n return this.state.artifacts.map((currArtifact, i) => {\n return <ArtifactBlock artifactData={currArtifact} key={i} />;\n });\n }",
"function renderLevel(args,cb){\n var bbox = args.bbox;\n var xyz = mercator.xyz(bbox, args.z);\n\n var alltiles = [];\n \n var i = 1;\n var total = (xyz.maxX - xyz.minX + 1) * (xyz.maxY - xyz.minY+ 1);\n for (var x = xyz.minX; x <= xyz.maxX; x++) {\n for (var y = xyz.minY; y <= xyz.maxY; y++) {\n alltiles.push({\n progress: args.progress,\n city: args.city,\n index: i++,\n total: total,\n pool: args.pool,\n z: args.z,\n x: x,\n y: y\n });\n }\n }\n \n \n async.map(alltiles, renderTile, function(err, results){\n if (err) return cb(err);\n cb(results);\n });\n}",
"render() {\n this.map.render(this.snake.getBody(), this.food.getCoordinates());\n }",
"function displayPageTiles(e){\n\t$.ajax({\n\t\turl: pageEditorScript,\n\t\tdata: {getPageTiles:\"true\",pageName:pageNameSelect.val()},\n\t\tsuccess: success,\n\t\tdataType: 'json'\n\t});\n\tfunction success(data){\n\t\t// Remove prevously existing editable tiles before new ones are added\n\t\t$(document).find($(pageEditorTileContainer).remove());\n\t\t\n\t\tvar i = 0;\n\t\tvar tile = pageEditorDOM[2];\n\t\tconsole.log(data);\n\t\t\n\t\tfor(i=0; i<data.length;i++){\n\t\t\t$(tile).attr(\"id\",data[i].id);\n\t\t\t$(tile).find(\".idInput\").val(data[i].id);\n\t\t\t$(tile).find(\".categoryInput\").val(data[i].category);\n\t\t\t$(tile).find(\".pageNameInput\").val(data[i].pageName);\n\t\t\t$(tile).find(\".tileLayoutInput\").val(data[i].layout);\n\t\t\t$(tile).find(\".tileOrderInput\").val(data[i].order);\n\t\t\t$(tile).find(\".col12Input\").val(data[i].col12);\n\t\t\t$(tile).find(\".col1Input\").text(data[i].col1);\n\t\t\t$(tile).find(\".col2Input\").text(data[i].col2);\n\t\t\t$(tile).clone().appendTo(content);\n\t\t}\n\t}\n}",
"render() {\n var tickers = this.state.data.map((currency) =>\n <Cryptocurrency data={currency} key={currency.id} />\n );\n //return the div with our 'ul' and tickets and source credit\n return (\n <div className=\"tickers-container\">\n <ul className=\"tickers\">{tickers}</ul>\n <p>Information updated every minute courtesy of coinmarketcap.com</p>\n </div>\n );\n }",
"function indexChecklists(){\n $('#all_checklists').on('click', function(event) {\n // when an element on the dom with an id of all_checklists, and it is clicked, run the following function\n // event.preventDefault()\n history.pushState(null, null, \"checklists\")\n //get back promise parsing the data on the response.\n //the data from url checklist.json\n fetch(`/checklists.json`)\n .then(resp => resp.json())\n .then(checklists => {\n //clears out\n $('#checklist_container').html('')\n\n //iteration\n checklists.forEach(checklist => {\n //variable = new class Checklist(argument is the object checklist)\n let newChecklist = new Checklist(checklist)\n let checklistHtml = newChecklist.formatChecklist()\n //Inject the HTML to the body of the page using append\n $('#checklist_container').append(checklistHtml)\n })\n })\n })\n}",
"function createTiles() {\n\n\tvar html = '<table id=\"tiles\" class=\"front\">';\n\thtml += '<tr><th><div> </div></th>';\n\n\tfor (var h = 0; h < hours.length; h++) {\n\t\thtml += '<th class=\"head' + h + '\">' + hours[h] + '</th>';\n\t}\n\n\thtml += '</tr>';\n\n\tfor (var d = 0; d < days.length; d++) {\n\t\thtml += '<tr class=\"d' + d + '\">';\n\t\thtml += '<th>' + days[d].abbr + '</th>';\n\t\tfor (var h = 0; h < hours.length; h++) {\n\t\t\thtml += '<td id=\"d' + d + 'h' + h + '\" class=\"d' + d + ' h' + h + '\"><div class=\"tile\"><div class=\"face front\"></div><div class=\"face back\"></div></div></td>';\n\t\t}\n\t\thtml += '</tr>';\n\t}\n\n\thtml += '</table>';\n\td3.select('#visualization').html(html);\n}",
"function buildThemeIndex(allTemplates, allRecipes) {\n var template = Handlebars.compile(allTemplates['theme-index']);\n var numberOfPages = calculateNumberOfPages(allRecipes);\n var recipesNumber = allRecipes.length;\n var lowLimit;\n var highLimit;\n var i;\n\n for (i = 0; i < numberOfPages; i++) {\n lowLimit = i * THEMES_PER_PAGE;\n highLimit = getHighLimit(lowLimit, recipesNumber);\n buildThemePage({\n allRecipes: allRecipes,\n startIndex: lowLimit,\n endIndex: highLimit,\n currentPage: i,\n pageLimit: numberOfPages,\n template: template\n });\n }\n}",
"renderList() {\n return this.props.posts.map((post) => {\n return (\n <div className='item' key={post.id}>\n <i className='large middle aligned icon user' />\n <div className='content'>\n <div className='description'>\n <h2>{post.title}</h2>\n <p>{post.body}</p>\n </div>\n <UserHeader userId={post.userId} />\n </div>\n </div>\n )\n })\n }",
"function renderNotes(){\n $('#new-note-btn').show();\n $(\"#new-note-hr\").show();\n $(\"#note-index-container\").css('height', '');\n clearNotesDisplay(\"notes\");\n raw_notes.forEach(function(note){\n $(\".note-index\").append('<div class=\"note-tile btn btn-block transition-quick\" data-id=' + note[\"id\"] + '>' + trimTitle(note[\"title\"], titleDisplayLen) + '</div>');\n });\n addTileListener();\n}",
"function renderShoppingList() {\n console.log('`renderShoppingList` ran');\n console.log(STORE);\n const shoppingList = generateShoppingList(STORE);\n\n // inserts the HTML into the DOM\n $('.container').html(shoppingList);\n}",
"function updateNumbers() {\n // look how I loop through all tiles\n tileSprites.forEach(function (item) {\n // retrieving the proper value to show\n var value = fieldArray[item.pos];\n // showing the value\n item.getChildAt(0).text = value;\n // tinting the tile\n item.tint = colors[value]\n });\n }",
"function render(items) {\n // LOOP\n // var item = ...\n // $(\"div#target\").append(\"<p>\" + item.message + \"</p>\")\n //\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MG Issue 1062 Allow Paste only Digists , Comma, and decimal | function checkPasteSigned(element) {
var key = window.event.keyCode;
if (key == 9 || (key >= 35 && key <= 40)) return;
// First Trim spaces
while (element.value.indexOf(' ') > 0)
element.value = element.value.replace(' ', '');
//Check if numeric
if (!isNumeric(element.value.replace('-', ''))) {
element.value = "";
alert('You entered an alphabetic character that is not allowed. Please enter a numeric value.');
return false;
}
//Delete Commas
while (element.value.indexOf(',') > 0) {
element.value = element.value.replace(',', '');
}
element.value = CommaFormattedN(element);
} | [
"function addCommaToIncomeInput(e){\n let val = Number(e.target.value.replaceAll(',',''))\n e.target.value = val.toLocaleString()\n}",
"function putMask_Number_Value(aValue, aintDigits, aintDecimals)\n{\n lstrValue = \"\"+aValue;\n re = new RegExp(\",\",\"g\");\n lstrValue = lstrValue.replace(re,\"\");\n\n // Curtailing Blank spaces from the begining and end of the entered text\n lstrValue = trimString(lstrValue);\n\n if( lstrValue == null || lstrValue.length == 0 ){\n return;\n }\n var posNeg=lstrValue.indexOf('-');\n\n // Get the number of digits that can be there before period (.)\n lintLen = aintDigits;\n // Get the number of digits that can be there after period (.)\n lDeciLen = aintDecimals;\n\n allVal = lstrValue.split(\".\")\n\n if(posNeg != 0) {\n intVal = allVal[0];\n } else {\n intVal = allVal[0].substring(1,allVal[0].length);\n }\n\n floatVal = allVal[1];\n\n var i = intVal.length;\n\n while(i >= 1) {\n\n if(intVal.indexOf(\"0\",0) == 0 ) {\n intVal = intVal.substring(1);\n }\n i = i-1;\n }\n\n if(intVal==null || intVal.length==0 ){\n intVal = \"0\";\n }\n\n if(allVal.length > 1){\n // Validating Float\n if(!validateFloat(lstrValue,lintLen,lDeciLen,true)){\n return;\n }\n }else{\n // Validating Integer\n if(!isInteger(intVal)){\n return;\n }\n }\n if(intVal.length > lintLen) {\n intVal = intVal.substring(0,lintLen);\n }\n if(allVal.length > 1){\n if(floatVal.length > lDeciLen) {\n floatVal = floatVal.substring(0,lDeciLen);\n } else if(floatVal.length < lDeciLen) {\n temp = floatVal.length;\n for(i = 0;i<(lDeciLen - temp);i++) {\n floatVal = floatVal + \"0\";\n }\n }\n }else{\n floatVal = \"\";\n for(i = 0;i<lDeciLen ;i++) {\n floatVal = floatVal + \"0\";\n }\n }\n remString = intVal;\n finalString = \"\";\n if(lintLen > 3) {\n while(remString.length > 3)\n {\n\n finalString = \",\" + remString.substring(remString.length-3) + finalString;\n remString = remString.substring(0,remString.length-3);\n }\n }\n finalString = remString + finalString ;\n finalString = finalString + \".\" + floatVal;\n return ((posNeg == 0 && finalString != 0)?'-':'') + finalString;\n}",
"function hideMask_Number(aField)\n{\n lstrValue = aField.value;\n re = new RegExp(\",\",\"g\");\n aField.value = lstrValue.replace(re,\"\");\n aField.select();\n}",
"function AcceptDigits(objtextbox)\n{\n var exp = /[^\\d]/g;\n objtextbox.value = objtextbox.value.replace(exp,'');\n}",
"function allowAlphabetAndFloatNumber(e) {\n // Get the ASCII value of the key that the user entered\n var key = (document.all) ? window.event.keyCode : e.which;\n\n if ((key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57) || (key == 8) || (key == 32) || (key == 0) || (key == 45)\n || (key >= 48 && key <= 57) || (key == 8) || (key == 45) || (key == 46) || (key == 0) || (key == 9))\n // If it was, then allow the entry to continue\n return true;\n else\n // If it was not, then dispose the key and continue with entry\n return false;\n }",
"function putMask_Number(aField, aintDigits, aintDecimals)\n{\n var lreComma = new RegExp(\",\",\"g\");\n\n lstrValue = aField.value;\n lstrValue = lstrValue.replace(lreComma,\"\");\n\n // Curtailing Blank spaces from the begining and end of the entered text\n lstrValue = trimString(lstrValue);\n\n if( lstrValue == null || lstrValue.length == 0 ){\n aField.value = lstrValue;\n return;\n }\n var posNeg=lstrValue.indexOf('-');\n\n // Get the number of digits that can be there before period (.)\n lintLen = aintDigits;\n // Get the number of digits that can be there after period (.)\n lDeciLen = aintDecimals;\n\n allVal = lstrValue.split(\".\")\n\n if(posNeg != 0) {\n intVal = allVal[0];\n } else {\n intVal = allVal[0].substring(1,allVal[0].length);\n }\n\n floatVal = allVal[1];\n\n var i = intVal.length;\n\n while(i >= 1) {\n\n if(intVal.indexOf(\"0\",0) == 0 ) {\n intVal = intVal.substring(1);\n }\n i = i-1;\n }\n\n if(intVal==null || intVal.length==0 ){\n intVal = \"0\";\n }\n\n if(allVal.length > 1){\n // Validating Float\n if(!validateFloat(lstrValue,lintLen,lDeciLen,true)){\n return;\n }\n }else{\n // Validating Integer\n if(!isInteger(intVal)){\n return;\n }\n }\n if(intVal.length > lintLen) {\n intVal = intVal.substring(0,lintLen);\n }\n if(allVal.length > 1){\n if(floatVal.length > lDeciLen) {\n floatVal = floatVal.substring(0,lDeciLen);\n } else if(floatVal.length < lDeciLen) {\n temp = floatVal.length;\n for(i = 0;i<(lDeciLen - temp);i++) {\n floatVal = floatVal + \"0\";\n }\n }\n }else{\n floatVal = \"\";\n for(i = 0;i<lDeciLen ;i++) {\n floatVal = floatVal + \"0\";\n }\n }\n remString = intVal;\n finalString = \"\";\n if(lintLen > 3) {\n while(remString.length > 3)\n {\n\n finalString = \",\" + remString.substring(remString.length-3) + finalString;\n remString = remString.substring(0,remString.length-3);\n }\n }\n finalString = remString + finalString ;\n finalString = finalString + \".\" + floatVal;\n aField.value = ((posNeg == 0 && finalString != 0)?'-':'') + finalString;\n}",
"function get_Number_WithOut_Mask(aField)\n{\n lstrValue = aField.value;\n re = new RegExp(\",\",\"g\");\n return lstrValue.replace(re,\"\");\n}",
"function numberCleaner(input) {\n var validNum = /[^0-9] -\\.()/;\n\n}",
"function maskPaymentInformation() {\r\n var validationType = $(this).attr(\"validation\");\r\n var value = $(this).val();\r\n if ((validationType != undefined && validationType != \"undefined\" && value != \"\" && value != undefined) && (validationType == \"SSN\" || validationType == \"credit\" || validationType == \"debit\" || validationType == \"Date\")) {\r\n var roundVal = value.trim().length;\r\n var regExp = new RegExp(\"^.{\" + roundVal + \"}\");\r\n var astrekStr = \"\";\r\n for (var int = 0; int < roundVal; int++) {\r\n astrekStr = astrekStr + \"*\";\r\n }\r\n if ($(this).attr(\"maskedValue\") == undefined) {\r\n $(this).attr({\r\n \"maskedValue\": value\r\n });\r\n\r\n } else if ($(this).attr(\"maskedValue\") != undefined) {\r\n $(this).attr(\"maskedValue\", value);\r\n }\r\n $(this).val(value.replace(regExp, astrekStr))\r\n }\r\n}",
"function fixCommas(item)\n{\n item.value = item.value.replace(/\\s*,\\s*/g, ',');\n item.value = item.value.replace(/^\\s*|\\s*$/g, '');\n item.value = item.value.replace(/^,*|,*$/g, '');\n item.value = item.value.replace(/,+/g, ',');\n}",
"function doBeforePaste(control){\n maxLength = control.attributes[\"maxLength\"].value;\n if(maxLength)\n {\n event.returnValue = false;\n }\n}",
"function removeExtraStuff(state) {\n if (config.currency) {\n state.value = removeCurrencySignAndPadding(state.value, state.selection);\n state.value = removeCommas(state.value, state.selection);\n }\n state.posFromEnd = state.value.length - state.selection.end;\n state.sign = false;\n var dotPos = -1;\n if (config.allowNegative) {\n state.sign = getSign(state.value);\n state.value = clearSign(state.value);\n }\n if (config.currency) {\n state.value = removeDot(state.value, state.selection);\n }\n }",
"function sanitizeValues(answer) {\n let values = slicePunctuation(answer).split(\",\");\n return values.map((value) => value.trim());\n}",
"function putMask_Integer(aField, aintDigits)\n{\n intVal = aField.value;\n\n re = new RegExp(\",\",\"g\");\n intVal = intVal.replace(re,\"\");\n\n lintLen = aintDigits;\n // Curtailing Blank spaces from the begining and end of the entered text\n intVal = trimString(intVal);\n\n if( intVal == null || intVal.length == 0 ){\n aField.value = intVal;\n return;\n }\n var posNeg=intVal.indexOf('-');\n\n // Validating Integer\n if(!isInteger(intVal)){\n return;\n }\n if(intVal.length > lintLen) {\n intVal = intVal.substring(0,lintLen);\n }\n\n remString = intVal;\n\n var i = remString.length;\n\n while(i > 1) {\n\n if(remString.indexOf(\"0\",0) == 0 ) {\n remString = remString.substring(1);\n }\n i = i-1;\n }\n\n finalString = \"\";\n\n if(lintLen > 3) {\n while(remString.length > 3)\n {\n\n finalString = \",\" + remString.substring(remString.length-3) + finalString;\n remString = remString.substring(0,remString.length-3);\n }\n }\n finalString = remString + finalString ;\n aField.value = ((posNeg == 0 && finalString != 0)?'-':'') + finalString;\n}",
"function validQuantity(input) {\n return parseInt(input) > 0 && input.toString().indexOf(\".\") === -1;\n }",
"function allowAlphabetAndNumerAndDotAndSlash(e) {\n // Get the ASCII value of the key that the user entered\n var key = (document.all) ? window.event.keyCode : e.which;\n\n if ((key >= 65 && key <= 90) || (key >= 97 && key <= 122) || (key >= 48 && key <= 57) || (key == 8) || (key == 32) || (key == 0) || (key == 45) ||\n (key == 47) || (key == 46))\n // If it was, then allow the entry to continue\n return true;\n else\n // If it was not, then dispose the key and continue with entry\n return false;\n }",
"function KeyPaste(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n Paste();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}",
"function ValidateSpecialAndNumeric(e) {\n var key = window.event ? e.keyCode : e.which;\n var text = String.fromCharCode(event.keyCode);\n var unicodeWord = RegExSpecialAndNumeric();\n if (unicodeWord.test(text)) {\n return true;\n }\n else {\n return false;\n }\n return true;\n\n}",
"function canPaste() {\n let selectedCal = getSelectedCalendar();\n if (!selectedCal || !cal.isCalendarWritable(selectedCal)) {\n return false;\n }\n\n const flavors = [\"text/calendar\", \"text/unicode\"];\n return getClipboard().hasDataMatchingFlavors(flavors,\n flavors.length,\n Components.interfaces.nsIClipboard.kGlobalClipboard);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the linear regression of a data set over a number of days. Data should be in the form of [Date, number] | function getLinearRegression (data, days) {
if (typeof days !== "undefined") {
data = getRecentData(data, days);
}
var reg = regression.linear(data);
return reg;
} | [
"function addFittedLine(series, chartId) {\n var index = 0;\n _.each(series, function (currentSeries) {\n var regressionOutput = dhcStatisticalService.getLinearFit(currentSeries.data);\n var color = dhcSeriesColorService.get(\"chart\" + chartId, currentSeries.name);\n series.push({\n name: currentSeries.name + \" Regression (Linear)\",\n marker: {\n enabled: false\n },\n type: \"line\",\n showInLegend: false,\n enableMouseTracking: false,\n color: color,\n data: regressionOutput.predictedValue\n });\n index++;\n });\n return series;\n }",
"function regressionLine(min_ns) {\n \n return {\n // calculate availability in 365\n y: Math.round((min_ns*regressionConstants.a + regressionConstants.b)*100)/100,\n x: min_ns\n }\n }",
"function updateChart (data, days=7) {\n var rsiSensitivity = Number($('#rsi').val()) || DEFAULT_RSI;\n var start = performance.now();\n var dataLows = getLocalExtrema(data, \"min\");\n var dataHighs = getLocalExtrema(data, \"max\");\n var regressionAll = getLinearRegression(data, days);\n var regressionLow = getLinearRegression(dataLows, days);\n var regressionHigh = getLinearRegression(dataHighs, days);\n var movingAverageN = Number($('#moving-average-n').val()) || DEFAULT_MOVING_AVERAGE_N;\n var movingAverageM = Number($('#moving-average-m').val()) || DEFAULT_MOVING_AVERAGE_M;\n var movingAverage = getMovingAverage(data, movingAverageN, days);\n var movingAverageLong = getMovingAverage(data, movingAverageM, days);\n var rsi = getRSI(data, rsiSensitivity, days);\n var pricingCtx = $(\"#pricing-chart\");\n var rsiCtx = $(\"#rsi-chart\");\n var end = performance.now();\n\n var pricingChart = new Chart(pricingCtx, {\n 'type': 'scatter',\n 'data': {\n 'datasets': [\n {\n 'label': `Moving Average 1`,\n 'data': convertDataForChart(movingAverage),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(255, 255, 0, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': `Moving Average 2`,\n 'data': convertDataForChart(movingAverageLong),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(255, 0, 255, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Regression',\n 'data': generateDataFromRegression(regressionAll, days),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(255, 0, 0, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Regression Highs',\n 'data': generateDataFromRegression(regressionHigh, days),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 0, 255, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Regression Lows',\n 'data': generateDataFromRegression(regressionLow, days),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 255, 255, 0.7)',\n 'borderWidth': 2\n },\n {\n 'label': 'Pricing History',\n 'data': convertDataForChart(getRecentData(data, days)),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 255, 0, 0.9)',\n 'borderWidth': 3,\n 'lineTension': 0\n }\n ]\n },\n 'options': {\n 'maintainAspectRatio': false,\n 'layout': {\n 'padding': 20\n },\n 'legend': {\n 'labels': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n }\n },\n 'tooltips': {\n 'mode': 'nearest',\n 'callbacks': {\n 'label': function (toolTipItem, data) {\n var x = `${moment().subtract((days - toolTipItem.xLabel) * 24, 'hours', true).format('MMM Do ha')}`\n var y = `$${toolTipItem.yLabel.toFixed(2)}`;\n return `${x}, ${y}`\n }\n } \n },\n 'scales': {\n 'scaleLabel': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n },\n 'xAxes': [{\n 'ticks': {\n 'min': 0,\n 'callback': function (value, index, values) {\n return moment().subtract(days - value, 'days').format('MMM Do');\n }\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n },\n }],\n 'yAxes': [{\n 'ticks': {\n 'callback': function (value, index, values) {\n return `$${value.toFixed(2)}`;\n }\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n }\n }]\n }\n }\n })\n\n var rsiChart = new Chart(rsiCtx, {\n 'type': 'scatter',\n 'data': {\n 'datasets': [\n {\n 'label': `RSI`,\n 'data': convertDataForChart(rsi),\n 'pointRadius': 0,\n 'pointHitRadius': 10,\n 'pointHoverRadius': 10,\n 'backgroundColor': 'rgba(0, 0, 0, 0)',\n 'borderColor': 'rgba(0, 255, 0, 0.9)',\n 'borderWidth': 3,\n 'lineTension': 0\n }\n ]\n },\n 'options': {\n 'maintainAspectRatio': false,\n 'layout': {\n 'padding': 20\n },\n 'legend': {\n 'labels': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n }\n },\n 'tooltips': {\n 'mode': 'nearest',\n 'callbacks': {\n 'label': function (toolTipItem, data) {\n var x = `${moment().subtract((days - toolTipItem.xLabel) * 24, 'hours', true).format('MMM Do ha')}`\n var y = `${toolTipItem.yLabel.toFixed(2)}`;\n return `${x}, ${y}`\n }\n } \n },\n 'scales': {\n 'scaleLabel': {\n 'fontColor': 'rgba(255, 255, 255, 1)'\n },\n 'xAxes': [{\n 'ticks': {\n 'min': 0,\n 'callback': function (value, index, values) {\n return moment().subtract(days - value, 'days').format('MMM Do');\n }\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n },\n }],\n 'yAxes': [{\n 'ticks': {\n 'beginAtZero': true,\n 'max': 100\n },\n 'gridLines': {\n 'color': \"rgba(255, 255, 255, 0.1)\"\n }\n }]\n }\n }\n })\n\n return {pricingChart, rsiChart};\n}",
"function drawRegressionLine() {\n let startPoint = regressionLine(90); \n let endPoint = regressionLine(122); \n startPoint = toCanvasPoint(startPoint);\n endPoint = toCanvasPoint(endPoint);\n line(startPoint.x, startPoint.y, endPoint.x, endPoint.y);\n}",
"function resampleDates(data) {\r\n const startDate = d3.min(data, d => d.key)\r\n const finishDate = d3.max(data, d => d.key)\r\n const dateRange = d3.timeDay.range(startDate, d3.timeDay.offset(finishDate,1), 1)\r\n return dateRange.map(day => {\r\n return data.find(d => d.key >= day && d.key < d3.timeHour.offset(day,1)) || {'key':day, 'value':0}\r\n })\r\n}",
"function linearStepwise(t0, v0, t1, v1, dt, t) {\n\t/*\n\t * perform the calculation according to formula\n\t * t - t0\n\t * dt ______\n\t * dt\n\t * v = v0 + (v1 - v0) ___________\n\t * t1 - t0\n\t *\n\t */\n\treturn v0 + Math.floor((v1 - v0) * Math.floor((t - t0) / dt) * dt / (t1 - t0));\n}",
"function gradientDescent() {\n var learningRate=0.01;\n for (var i=0;i<data.length;i++) {\n var x=data[i].x;\n var y=data[i].y;\n var guess=m*x+b;\n var error=y-guess;\n m=m+(error*x)*learningRate;\n b=b+error*learningRate;\n }\n}",
"function getMonthlyPrice(i) {\n var ret = [0, 0, 0];\n for (var j = 0; j<31; j++) {\n ret[0] = ret[0]+(prices[0][i][j]*data[i][j]);\n ret[1] = ret[1]+(prices[1][i][j]*data[i][j]);\n ret[2] = ret[2]+(prices[2][i][j]*data[i][j]);\n }\n return ret;\n}",
"function getRSI (data, sensitivity=14, days=7) {\n var set = [];\n var rs;\n var averageGain;\n var averageLoss;\n var sumOfGains = 0;\n var sumOfLosses = 0;\n var lastValue;\n if (data.length > sensitivity) {\n lastValue = data[0][1];\n for (var i = 1; i < data.length; i++) {\n let thisValue = data[i][1]\n if (i < sensitivity) {\n if (thisValue > lastValue) {\n sumOfGains += thisValue - lastValue;\n }\n else if (thisValue < lastValue) {\n sumOfLosses += lastValue - thisValue;\n }\n }\n if (i >= sensitivity) {\n // First Average Gain = Sum of Gains over the past N periods / N\n // First Average Loss = Sum of Losses over the past N periods / N\n if (i === sensitivity) {\n averageGain = sumOfGains / sensitivity;\n averageLoss = sumOfLosses / sensitivity;\n }\n else {\n // Average Gain = [(previous Average Gain) * (N-1) + Current Gain] / N\n // Average Loss = [(previous Average Loss) * (N-1) - Current Loss] / N\n if (thisValue > lastValue) {\n averageGain = (averageGain * (sensitivity - 1) + (thisValue - lastValue)) / sensitivity;\n }\n else if (thisValue < lastValue) {\n averageLoss = (averageLoss * (sensitivity - 1) + (lastValue - thisValue)) / sensitivity;\n }\n }\n // RS = Average Gain / Average Loss\n // Should the averageLoss be zero, RS is 100 by definition.\n // RSI = 100 - 100 / (1 + RS)\n rs = Math.min(averageGain / averageLoss, 100);\n rsi = 100 - 100 / (1 + rs);\n set.push([data[i][0], rsi]);\n }\n lastValue = thisValue;\n }\n }\n return getRecentData(set, days);\n}",
"function drawLineChart(data) {\n var lineData = [];\n lineData = data.map(d => { return { date: new Date(d.dateDate.year, d.dateDate.month - 1, d.dateDate.day), nps: d.nps } });\n\n lineData.sort(function (a, b) {\n return new Date(b.date) - new Date(a.date);\n });\n\n var height = 200;\n var width = 800;\n var hEach = 40;\n\n var margin = { top: 20, right: 15, bottom: 25, left: 25 };\n\n width = width - margin.left - margin.right;\n height = height - margin.top - margin.bottom;\n\n var svg = d3.select('#aDc').append(\"svg\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n // set the ranges\n var x = d3.scaleTime().range([0, width]);\n\n x.domain(d3.extent(lineData, function (d) { return d.date; }));\n\n\n var y = d3.scaleLinear().range([height, 0]);\n\n\n y.domain([d3.min(lineData, function (d) { return d.nps; }) - 5, 100]);\n\n var valueline = d3.line()\n .x(function (d) { return x(d.date); })\n .y(function (d) { return y(d.nps); })\n .curve(d3.curveMonotoneX);\n\n svg.append(\"path\")\n .data([lineData])\n .attr(\"class\", \"line\")\n .attr(\"d\", valueline);\n\n // var xAxis_woy = d3.axisBottom(x).tickFormat(d3.timeFormat(\"Week %V\"));\n var xAxis_woy = d3.axisBottom(x).ticks(11).tickFormat(d3.timeFormat(\"%y-%b-%d\")).tickValues(lineData.map(d => d.date));\n\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(xAxis_woy);\n\n // Add the Y Axis\n // svg.append(\"g\").call(d3.axisLeft(y));\n\n svg.selectAll(\".dot\")\n .data(lineData)\n .enter()\n .append(\"circle\") // Uses the enter().append() method\n .attr(\"class\", \"dot\") // Assign a class for styling\n .attr(\"cx\", function (d) { return x(d.date) })\n .attr(\"cy\", function (d) { return y(d.nps) })\n .attr(\"r\", 5);\n\n\n svg.selectAll(\".text\")\n .data(lineData)\n .enter()\n .append(\"text\") // Uses the enter().append() method\n .attr(\"class\", \"label\") // Assign a class for styling\n .attr(\"x\", function (d, i) { return x(d.date) })\n .attr(\"y\", function (d) { return y(d.nps) })\n .attr(\"dy\", \"-5\")\n .text(function (d) { return d.nps; });\n\n svg.append('text')\n .attr('x', 10)\n .attr('y', -5)\n .text('מתכונים לפי יום'); \n}",
"function ImpressionsTimeSeries() {\n var self = this;\n this.loading = false;\n\n this.loadData = function() {\n self.loading = true;\n Restangular\n .one('campaign_reports', ctrl.campaignId)\n .customGET('impressions_time_series')\n .then(function(response) {\n self.loading = false;\n self.data = [];\n self.data[0]={};\n var _count = [],_date = [];\n self.totalImpressions = numberWithCommas(response.totalImpressions);\n for(var i= 0; i<response.timeSeries.length; i++){\n _count.push(response.timeSeries[i].count);\n _date.push(response.timeSeries[i].date);\n }\n self.data[0].count = _count.toString();\n self.data[0].date = _date.toString();\n console.log(\"row--fourth ImpressionsTimeSeries::\", i, self.data);\n });\n };\n this.loadData();\n }",
"getWeightsRange(date1, date2){\n let temp = [];\n let progress = 0;\n let start = new Date(date1);\n let end = new Date(date2);\n for(var i=0; i< this.weightLog.length; i++){\n if(this.weightLog[i].date >= start && this.weightLog[i].date <=end){\n temp.push(this.weightLog[i]);\n }\n }\n if(temp.length >= 2){\n progress =temp[temp.length - 1].weight -temp[0].weight;\n }\n return {weights: temp, progress: progress}; \n }",
"function linear_interpolate(x, x0, x1, y0, y1){\n return y0 + ((y1 - y0)*((x-x0) / (x1-x0)));\n}",
"function getDateRangeArrayEarliestToYesterday(data, dateColumnIndex) {\n let historyDateArray = data.map((row) => {\n // Set hours to 0 for comparison\n let d = new Date(row[dateColumnIndex]);\n d.setHours(0, 0, 0, 0);\n return d;\n });\n historyDateArray.sort((a, b) => b - a);\n let historyStart = historyDateArray[historyDateArray.length - 1];\n // Must pull to yesterday because google finance data does not always include current day.\n let yesterday = new Date();\n yesterday = yesterday.setDate(yesterday.getDate() - 1);\n return getDates(historyStart, yesterday);\n}",
"function checkerdex(dates)\n{\n\tvar sum = 0;\n\n\tvar now = dates[dates.length - 1];\n\tfor (var i = 0; i < dates.length; i++)\n\t{\n\t\tvar weight = (rangeMS - (now - dates[i])) / rangeMS;\n\t\tsum += weight * baseScore;\n\t}\n\n\treturn sum;\n}",
"function renderStat(stats, limit){\n var dates = [],\n values = [];\n\n if (limit > stats.data.length) limit = stats.data.length\n\n var i, len, stat, date;\n len=stats.data.length;\n for (i=len-limit ; i < len; i++) {\n stat = stats.data[i];\n console.log(i)\n dates.push( new Date(stat.date).toDateString());\n values.push(stat.value)\n }\n\n var ctx = document.getElementById(stats.name).getContext(\"2d\");\n\n var data = {\n labels: dates,\n datasets: [\n {\n label: stats.name,\n fillColor: \"rgba(220,220,220,0.2)\",\n strokeColor: \"rgba(220,220,220,1)\",\n pointColor: \"rgba(220,220,220,1)\",\n pointStrokeColor: \"#fff\",\n pointHighlightFill: \"#fff\",\n pointHighlightStroke: \"rgba(220,220,220,1)\",\n data: values\n }\n ]\n };\n\n var myLineChart = new Chart(ctx).Line(data);\n\n\n}",
"function getNextSevenDays(data) {\n // Resolves issue of stacking array elements every time user hits refresh\n next_days_day = [];\n next_days_temp = [];\n next_days_weather = [];\n next_days_humidity = [];\n next_days_windspeed = [];\n\n for(var i = 1; i < 8; i++) {\n var day_day = data.daily[i].dt;\n day_day = getDateTime(day_day);\n var sub_day = day_day.split(',')[0];\n day_day = sub_day;\n next_days_day.push(day_day);\n\n var day_temp = Math.round(data.daily[i].temp.eve) + \"°C\" ;\n next_days_temp.push(day_temp);\n\n var day_weather = data.daily[i].weather[0].main;\n next_days_weather.push(day_weather);\n\n var day_humidity = data.daily[i].humidity + \"%\";\n next_days_humidity.push(day_humidity);\n\n var day_wind = (data.daily[i].wind_speed * 1.60934).toFixed(2) + \" km/h\";\n next_days_windspeed.push(day_wind);\n }\n}",
"function processdailyforecastsByDay(data) {\n\t\n\t//Separate Daily Forecasts By Day\n\tlet forecastSplitByDay = separateForecastsByDay(data.list);\n\n\t//Traverse through list\n\tfor(let forecastKey in forecastSplitByDay) {\n\t\t\n\t\t//Store current forecast\n\t\tlet forecast = forecastSplitByDay[forecastKey];\n\t\t\n\t\t//If forecast array is greater than 0\n\t\tif(forecast.length > 0) {\n\t\t\t\n\t\t\t//Push Day Forecast into observable array\n\t\t\tfivedayforeCast.push(consolidateToDailyForecast(forecastKey, forecast));\n\t\t\t\n\t\t}\n\t\t\n\t}\n\n}",
"function drawLineChart(chart, data) {\n let labels = [];\n let confirmedData = [];\n let deathsData = [];\n let recovereData = [];\n let activeData = [];\n\n data.forEach((item) => {\n labels.push(item.Date.split('T')[0]);\n confirmedData.push(item.Confirmed);\n deathsData.push(item.Deaths);\n recovereData.push(item.Recovered);\n activeData.push(item.Active);\n });\n chart.data.datasets[0].data = confirmedData;\n chart.data.datasets[1].data = deathsData;\n chart.data.datasets[2].data = recovereData;\n chart.data.datasets[3].data = activeData;\n chart.data.labels = labels;\n chart.update();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: _fnGetObjectDataFn Purpose: Return a function that can be used to get data from a source object, taking into account the ability to use nested objects as a source Returns: function: Data get function Inputs: string|int|function:mSource The data source for the object | function _fnGetObjectDataFn( mSource )
{
if ( mSource === null )
{
/* Give an empty string for rendering / sorting etc */
return function (data) {
return null;
};
}
else if ( typeof mSource == 'function' )
{
return function (data) {
return mSource( data );
};
}
else if ( typeof mSource == 'string' && mSource.indexOf('.') != -1 )
{
/* If there is a . in the source string then the data source is in a nested object
* we provide two 'quick' functions for the look up to speed up the most common
* operation, and a generalised one for when it is needed
*/
var a = mSource.split('.');
if ( a.length == 2 )
{
return function (data) {
return data[ a[0] ][ a[1] ];
};
}
else if ( a.length == 3 )
{
return function (data) {
return data[ a[0] ][ a[1] ][ a[2] ];
};
}
else
{
return function (data) {
for ( var i=0, iLen=a.length ; i<iLen ; i++ )
{
data = data[ a[i] ];
}
return data;
};
}
}
else
{
/* Array or flat object mapping */
return function (data) {
return data[mSource];
};
}
} | [
"getObject() {\n return this.object;\n }",
"getValueSource() {\n return this._source;\n }",
"getFabricObject(ag_objectID) {\n let canvas_objects = this._room_canvas.getObjects();\n let fab_buffer;\n canvas_objects.forEach(function (item, i) {\n if (item.isObject && item.AGObjectID == ag_objectID) {\n fab_buffer = item;\n }\n });\n return fab_buffer;\n }",
"function resetDataFromSourceEntities(data) {\n return function (sourceObjects) {\n\n //The actual sourceObjects aka sourceEntities of this batch\n data.sourceObjects = sourceObjects;\n\n //Map containing <refNorm,sourceRefId> for each existing refNorm. \n //This is used to add sourceRefId to _refs-object in SourceEntity.\n data.refNormIdToSourceRefIdMap = {};\n\n //Map of <sourceId, reference-object> used to update SourceEntities once done \n data.sourceIdToRefMap = _.reduce(sourceObjects, function (agg, obj) {\n agg[obj.id] = obj._refs || {};\n return agg;\n }, {});\n\n // List of all references (inside SourceEntity._refs) that are not linked\n // to a RefNorm yet\n data.unlinkedRefsWithSourceId = [];\n\n // Map containing sourceId -> RefNorm key-value-pairs. \n // These are populated (and created if needed) for all sourceIds referenced\n // in any SourceEntity reference.\n data.sourceIdToRefNormMap = {};\n\n };\n }",
"function getObjectCodenameProperty (data, property) {\n\tlet value = null;\n\n\tif (data.hasOwnProperty(property)) {\n\t\tvalue = { codename: data[property].toString() };\n\t}\n\n\treturn value; \n}",
"_getRowValueFromSourceColOrOriginalCol(colName) {\n const columns = this._table.getColumnsMap()\n const destColumn = columns[colName]\n const sourceColName = destColumn._getSourceColumnName()\n const sourceCol = columns[sourceColName]\n // only use source if we still have access to it\n const val = sourceColName && sourceCol ? this._getRowValueFromOriginalOrSource(sourceColName, sourceCol.getPrimitiveTypeName(), destColumn.getPrimitiveTypeName()) : this.getRowOriginalValue(colName)\n const res = destColumn.getPrimitiveTypeObj().getAsNativeJavascriptType(val)\n const mathFn = destColumn.getMathFn()\n if (mathFn) return mathFn(res)\n return res\n }",
"read(objectHash) {\n if (objectHash !== undefined) {\n const objectPath = nodePath.join(Files.gitletPath(), 'objects', objectHash);\n if (fs.existsSync(objectPath)) {\n return Files.read(objectPath);\n }\n }\n }",
"function generateDynamicDataRef(sourceName,bindingName,dropObject)\n{\n var retVal = \"\";\n\n var sbObjs = dwscripts.getServerBehaviorsByTitle(sourceName);\n if (sbObjs && sbObjs.length)\n {\n var paramObj = new Object();\n paramObj.bindingName = bindingName;\n retVal = extPart.getInsertString(\"\", \"CFStoredProc_DataRef\", paramObj);\n\n // We need to strip the cfoutput tags if we are inserting into a CFOUTPUT tag\n // or binding to the attributes of a ColdFusion tag.\n if (dwscripts.canStripCfOutputTags(dropObject, true))\n {\n retVal = dwscripts.stripCFOutputTags(retVal, true);\n } \n }\n \n return retVal;\n}",
"async function get_datasource(basePath, fromAddress) {\n let source = new Datasource(basePath, fromAddress)\n await source.init()\n return source\n}",
"function getDataRiferimento(objData,tipo)\n{\n\tvar dataInput;\n\tvar dataOutput;\n\tvar giorno;\n\tvar mese;\n\tvar anno;\n \n // objData e' una stringa che rappresenta una data\n if (typeof(objData)==\"string\")\n {\n \tdata=getDateFromText(objData);\n }\n // objData e' un campo INPUT\n else if (objData.tagName!=undefined)\n {\n \tdata=getDateFromText(objData.value);\t\t\t\t\n }\n // objData e' un oggetto Date\n else\n {\n \tdata=new Date(objData.getFullYear(),objData.getMonth(),objData.getDate(),0,0,0,0);\n }\n\t\n\tanno=data.getFullYear();\n\t\n\tswitch (tipo)\n\t{\n\t\t// Torna data INIZIO ANNO\n\t\tcase \"IA\":\n\t\t\tgiorno=1;\n\t\t\tmese=1;\n\t\t\tbreak;\n\t\t\t\n\t\t// Torna data FINE ANNO\n\t\tcase \"FA\":\n\t\t\tgiorno=31;\n\t\t\tmese=12;\n\t\t\tbreak;\n\t\t\t\n\t\t// Torna data INIZIO MESE\n\t\tcase \"IM\":\n\t\t\tgiorno=1;\n\t\t\tmese=data.getMonth()+1;\n\t\t\tbreak;\n\t\t\t\n\t\t// Torna data FINE MESE\n\t\tcase \"FM\":\n\t\t\tmese=data.getMonth()+1;\n\t\t\tswitch (mese)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\tcase 3:\n\t\t\t\tcase 5:\n\t\t\t\tcase 7:\n\t\t\t\tcase 8:\n\t\t\t\tcase 10:\n\t\t\t\tcase 12:\n\t\t\t\t\tgiorno=31;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\n\t\t\t\tcase 6:\n\t\t\t\tcase 9:\n\t\t\t\tcase 11:\n\t\t\t\t\tgiorno=30;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tif (anno%4!=0 || (anno%100==0 && anno%400!=0))\n\t \t\tgiorno=28;\n\t\t\t else\n\t\t\t \tgiorno=29;\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\t// Stringa vuota\n\t\tdefault:\n\t\t\treturn \"\";\n\t}\n\t\n\t// Normalizzazione giorno/mese\n\tif (giorno<10)\n\t\tgiorno=\"0\"+giorno;\n\t\n\tif (mese<10)\n\t\tmese=\"0\"+mese;\n\t\t\n\t// Data in formato GG/MM/AAAA\n\treturn giorno+\"/\"+mese+\"/\"+anno;\n\n}",
"_getSource(title, pid, ndata, sender) {\n if (!pid && !(ndata && ndata.notification))\n return null;\n\n // We use notification's source for the notifications we still have\n // around that are getting replaced because we don't keep sources\n // for transient notifications in this._sources, but we still want\n // the notification associated with them to get replaced correctly.\n if (ndata && ndata.notification)\n return ndata.notification.source;\n\n let source = this._lookupSource(title, pid);\n if (source) {\n source.setTitle(title);\n return source;\n }\n\n let appId = ndata ? ndata.hints['desktop-entry'] || null : null;\n source = new FdoNotificationDaemonSource(title, pid, sender, appId);\n\n this._sources.push(source);\n source.connect('destroy', () => {\n let index = this._sources.indexOf(source);\n if (index >= 0)\n this._sources.splice(index, 1);\n });\n\n Main.messageTray.add(source);\n return source;\n }",
"getSourceForLayerId(layerId) {\n let layer = this.mapsInterface.getLayerFromArray(layerId);\n let olLayer = layer.vectorLayer.getLayersArray()[0];\n if (!olLayer) {\n return null;\n }\n return olLayer.getSource();\n }",
"getData(weightId) {\n const data = {};\n const results = this.state.results;\n\n if (!results[weightId].aggregationData) {\n // cache the results if reading from the buffer (WebGL2 path)\n results[weightId].aggregationData = results[weightId].aggregationBuffer.getData();\n }\n\n data.aggregationData = results[weightId].aggregationData; // Check for optional results\n\n for (const arrayName in ARRAY_BUFFER_MAP) {\n const bufferName = ARRAY_BUFFER_MAP[arrayName];\n\n if (results[weightId][arrayName] || results[weightId][bufferName]) {\n // cache the result\n results[weightId][arrayName] = results[weightId][arrayName] || results[weightId][bufferName].getData();\n data[arrayName] = results[weightId][arrayName];\n }\n }\n\n return data;\n }",
"function getDataByProjection( rData, pKey, idx ) {\r\n\tlet list \t\t= rData.data;\r\n\tlet projection \t= rData.projection;\r\n\tif( !chkNull( idx ) ) {\r\n\t\tidx = 0;\r\n\t}\r\n\t\r\n\t//console.log( \"list[ idx ][ projection[pKey] ]\", list[ idx ][ projection[pKey] ] );\r\n\treturn list[ idx ][\"a\"][ projection[pKey] ];\r\n\t/*\r\n\tif( idx ) {\t// Handle as a list.\r\n\t\treturn list[ idx ][ projection[pKey] ];\t\t\r\n\t} else {\t// Handle as a object.\r\n\t\tconsole.log( \"list\", list );\r\n\t\tconsole.log( \"projection[pKey]\", projection[pKey] );\r\n\t\tconsole.log( \"list[ projection[pKey]\", list[ projection[pKey] ] );\r\n\t\treturn list[ projection[pKey] ];\r\n\t}\r\n\t*/\r\n}",
"async function fetchTasksFromSource(objTaskSource) {\n\n var objReturn = new Object();\n objReturn.retStatus = 0;\n objReturn.retMessage = null;\n objReturn.retObject = undefined;\n\n self.endpointAddress = objTaskSource.epTaskListApi;\n var ep = RestHelper.get(self.endpointAddress);\n\n var objTasks;\n try {\n\n ep.responseBodyFormat('json');\n await ep.fetch()\n .then(result => {\n objTasks = result.body;\n })\n .catch(error => {\n objReturn.retStatus = -1;\n objReturn.retMessage = error;\n return objReturn;\n });\n\n //Format objects to a format acceptable to Array data provider. \n //Use the attribute mapping in the task source.\n objReturn.retObject = [];\n\n\n\n if (objTasks != null) {\n //loop through tasks and exatrct attributes\n var countTasks = objTasks.items.length;\n for (var currTask = 0; currTask < countTasks; currTask++) {\n objReturn.retObject[currTask] = new Object;\n objReturn.retObject[currTask].Status = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .Status);\n objReturn.retObject[currTask].TaskID = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .TaskID);\n objReturn.retObject[currTask].Subject = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .Subject);\n objReturn.retObject[currTask].DateAssigned = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .DateAssigned);\n objReturn.retObject[currTask].AssignedBy = eval(\n 'objTasks.items[currTask].' + objTaskSource.epTaskListApiAttributeMap\n .AssignedBy);\n objReturn.retObject[currTask].Source = objTaskSource.name;\n }\n }\n\n } catch (error) {\n objReturn.retStatus = -1;\n objReturn.retMessage = error;\n objReturn.undefined;\n return objReturn;\n }\n\n return objReturn;\n }",
"getData() {\n return PRIVATE.get(this).opt.data;\n }",
"function fetchGcsObject(bucket, objectName, responseHandler) {\n console.log('Fetching', bucket, '#', objectName);\n if (!isServingAppFromMachine()) {\n gapi.client.storage.objects.get({\n 'bucket': bucket,\n 'object': objectName,\n 'alt': 'media'\n }).then(function(response) {\n responseHandler(response.body);\n }, function(reason) {\n console.log(reason);\n alert('Could not fetch ', objectName, reason.body);\n });\n } else {\n window.fetch('data/' + bucket + '/' + objectName).then(function(response) {\n if (response.ok) {\n return response.text();\n } else {\n console.log(response.statusText);\n alert('Could not fetch \"' + objectName + '\"\\nReason: ' + response.statusText);\n }\n }).then(function(text) {\n responseHandler(text);\n });\n }\n}",
"getResourceMaybeCached(orgId, resourceId) {\n return __awaiter(this, void 0, void 0, function* () {\n const resourceApi = new api_1.ResourceApi(this.firestore, orgId);\n //TODO: add temp cache layer\n return resourceApi.getResource(resourceApi.resourceRef(resourceId));\n });\n }",
"function get_blob(topic, options, label, key) {\n return _get_blob(topic, options, label, key, \"blob\");\n}",
"getField(iid, base, offset, val, isComputed, isOpAssign, isMethodCall) {\n this.state.coverage.touch(iid);\n Log.logHigh('Get field ' + ObjectHelper.asString(base) + '.' + ObjectHelper.asString(offset) + ' at ' + this._location(iid));\n\n //If dealing with a SymbolicObject then concretize the offset and defer to SymbolicObject.getField\n if (base instanceof SymbolicObject) {\n Log.logMid('Potential loss of precision, cocretize offset on SymbolicObject field lookups');\n return {\n result: base.getField(this.state, this.state.getConcrete(offset))\n }\n }\n\n //If we are evaluating a symbolic string offset on a concrete base then enumerate all fields\n //Then return the concrete lookup\n if (!this.state.isSymbolic(base) && \n this.state.isSymbolic(offset) &&\n typeof this.state.getConcrete(offset) == 'string') {\n this._getFieldSymbolicOffset(base, offset);\n return {\n result: base[this.state.getConcrete(offset)]\n }\n } \n\n //Otherwise defer to symbolicField\n const result_s = this.state.isSymbolic(base) ? this.state.symbolicField(this.state.getConcrete(base), this.state.asSymbolic(base), this.state.getConcrete(offset), this.state.asSymbolic(offset)) : undefined;\n const result_c = this.state.getConcrete(base)[this.state.getConcrete(offset)];\n\n return {\n result: result_s ? new ConcolicValue(result_c, result_s) : result_c\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1. Add 1 Write a function called addOne that takes an array of numbers and returns an array with each number incremented by 1. E.g. addOne([1,2,3]), should return [2,3,4] | function addOne(inputArray) {
return inputArray.map(item => item + 1);
} | [
"function addOne(array) {\n\tfor (var i = 0; i < array.length; i++) {\n\t\tconsole.log(array[i] + 1);\n\t}\n}",
"function add1ToEach(array) {\n return array.map (function (value2) { return value2 += 1; })\n}",
"function addOne(arr) {\n let carry = 1\n let result = []\n for (let i = arr.length - 1; i >= 0; i--) {\n console.log(i)\n const total = arr[i] + carry\n if(total === 10) {\n carry = 1\n } else {\n carry = 0\n }\n result[i] = total % 10\n }\n if(carry === 1) {\n for(let i = 0; i < arr.length + 1; i++) {\n result[i] = 0\n }\n result[0] = 1\n }\n console.log('result',result)\n return result\n}",
"function add(array) {\n var sum = 0;\n for (var i = 0; i < array.length; i++) {\n sum += array[i];\n }\n return sum;\n}",
"function plusOneSum(arr) { \n var sum = arr.length;\n for (var index = 0; index < arr.length; index++) {\n sum += arr[index];\n } \n return sum;\n }",
"function arraySum(array){\n var sum=0;\n var index=0;\n function add(){\n if(index===array.length-1)\n return sum;\n\n sum=sum+array[index];\n index++;\n return add();\n }\n return add();\n}",
"function incrementItems(arr) {\n\treturn arr.map(x => x + 1);\n}",
"function plusOne(digits) {\n // loop backwards\n\n for(let i = digits.length - 1; i >= 0; i--) {\n if( digits[i] >= 9) {\n digits[i] = 0\n } else {\n digits[i]++;\n return digits;\n }\n }\n\n // now if we had increased a 9 to a 10 then\n // we add one a the beginning of the array\n return [1, ...digits];\n}",
"function SimpleAdding(num) { \n var y=0;\n for (var i=1; i<num+1; i++){\n y=y+i;\n }\n return y; \n }",
"function increment(arr) {\n for (var x = 0; x < arr.length; x++) {\n if (x%2 != 0) {\n arr[x] += 1;\n }\n console.log(arr[x]);\n }\n return arr;\n}",
"function incrementRollup(array, value) {\n\n\t//return\n\n}",
"function addNumbers(num1, num2){ \n//arguments je koytai thak na keno \n// console.log(arguments[1]);\n// arguments e push/pop kicchu nai arrayr moto;\n//arguments holo array like object;\nlet result = 0;\n for(const num of arguments){\n // console.log(num);\n result = result + num; \n }\n // arguments.push(45); \n //kaj korbena oporer line;\n // const result = num1 + num2;\n return result; \n //when your function does not return any data/value then output shows this point as undefined;\n}",
"function addOdds(evensOnlyArray) {\n var newArr = []\n for(var i = 0; i < evensOnlyArray.length; i++) {\n newArr.push(evensOnlyArray[i] + 1)\n }\n evensOnlyArray.unshift(1)\n return allNums = evensOnlyArray.concat(newArr)\n}",
"function func(accumulator, currentValue, currentIndex, sourceArray) {\n return accumulator + currentValue;\n}",
"function addg(first){\n\tfunction more(next){\n\t\tif (next === undefined){\n\t\t\treturn first;\n\t\t}\n\t\tfirst += next;\n\t\treturn more;\n\t}\n\tif (first !== undefined){\n\t\treturn more;\n\t}\n}",
"function addRecurse(...num) {\n const array = [...num];\n let sum = 0;\n const array2 = [...array[0]];\n if (array2.length > 0) {\n let n = array2.shift();\n sum = n + addRecurse(array2);\n }\n return sum;\n}",
"function addNumbers() {\n questionNumber++;\n}",
"push() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n this._addArgs.index = this._array.length;\n\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n var source = arguments[0];\n\n for (var i = 0, l = source.length; i < l; i++) {\n this._array.push(source[i]);\n }\n } else {\n this._array.push.apply(this._array, arguments);\n }\n\n this._addArgs.addedCount = this._array.length - this._addArgs.index;\n this.notify(this._addArgs);\n\n this._notifyLengthChange();\n\n return this._array.length;\n }",
"function runningSum(nums) {\n let arr = [];\n for(let i = 0; i < nums.length; i++) {\n if(i===0) {\n arr.push(nums[i])\n } else {\n arr.push(nums[i] + arr[i - 1]);\n };\n };\n return arr;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
buildWatchBtn uses adds watch button to stocks information window | function buildWatchBtn(stockSym) {
var watchBtn = $("<button>");
watchBtn.addClass("ml-2 btn btn-success btn-sm watch-button").
attr("stock-id", stockSym).
html("+ Watchlist");
return watchBtn;
} | [
"function buildWatchBtn(stockSym) {\n var watchBtn = $(\"<button>\");\n\n watchBtn.addClass(\"ml-2 btn btn-success btn-sm watch-button\").\n attr(\"stock-id\", stockSym).\n html(\"+ Watchlist\");\n // html(\"Add to ★\");\n\n return watchBtn;\n }",
"function onWatchClick() {\n\t\t// Input from search box\n\t\t$('.watch').on('click', popWatchedRows);\n\t}",
"_create_window_button(ws_index, window) {\n\t\tvar w_box;\n\n\t\t// don't make a button for dropdown menu or modal dialog\n\t\tif ([Meta.WindowType.DROPDOWN_MENU, Meta.WindowType.MODAL_DIALOG].includes(window.window_type)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// windows on all workspaces have to be displayed only once\n\t\tif (!window.is_on_all_workspaces() || ws_index == 0) {\n\t\t\t// create button\n\t\t\tw_box = new St.Bin({visible: true, reactive: true, can_focus: true, track_hover: true});\n\t\t\tw_box.connect('button-press-event', () => this._toggle_window(ws_index, window));\n\t\t\tw_box.connect('notify::hover', () => this._show_tooltip(w_box, window.title));\n\t\t\tw_box.app = this.window_tracker.get_window_app(window);\n\t\t\tif (w_box.app) {\n\t\t\t\tw_box.icon = w_box.app.create_icon_texture(ICON_SIZE);\n\t\t\t}\n\n\t\t\t// sometimes no icon is defined\n\t\t\tif (!w_box.icon) {\n\t\t\t\tw_box.icon = this.fallback_icon;\n\t\t\t}\n\n\t\t\t// set icon style and opacity following window state\n\t\t\tif (window.is_hidden()) {\n\t\t\t\tw_box.style_class = 'window-hidden';\n\t\t\t\tw_box.icon.set_opacity(HIDDEN_OPACITY);\n\t\t\t} else {\n\t\t\t\tif (window.has_focus()) {\n\t\t\t\tw_box.style_class = 'window-focused';\n\t\t\t\tw_box.icon.set_opacity(FOCUSED_OPACITY);\n\t\t\t\t} else {\n\t\t\t\tw_box.style_class = 'window-unfocused';\n\t\t\t\tw_box.icon.set_opacity(UNFOCUSED_OPACITY);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// add button in task bar\n\t\t \tw_box.set_child(w_box.icon);\n\t\t \tif (window.is_on_all_workspaces()) {\n\t\t \t\tthis.ws_bar.insert_child_at_index(w_box, 0);\n\t\t \t} else {\n\t\t\t\tthis.ws_bar.add_child(w_box);\n\t\t\t}\n\t\t}\n\t}",
"function addToWatchList(event) {\n var stockSymbol = $(this).attr(\"stock-id\");\n\n event.preventDefault();\n // empty out stock-ticker content\n $(\"#stock-ticker-content\").empty();\n\n console.log(\"in addToWatchList() \");\n console.log(\"stock symbol: \" + stockSymbol);\n // $(\"#financial-text\").empty();\n // get current price of stock symbol\n buildBatchURL(stockSymbol, \"watch\");\n\n // get yesterday's close price of stock symbol\n buildTimeSeriesURL(stockSymbol);\n\n // add row to watchListTable\n renderWatchTable(stockSymbol);\n }",
"function initVidYardPlayBtn(){\n\tjQuery('.vidyard-lightbox-centering .play-button').append('<span>Watch Now</span>')\n}",
"createButton () {\n\n this.button = document.createElement('button')\n\n this.button.title = 'This model has multiple views ...'\n\n this.button.className = 'viewable-selector btn'\n\n this.button.onclick = () => {\n this.showPanel(true)\n }\n\n const span = document.createElement('span')\n span.className = 'fa fa-list-ul'\n this.button.appendChild(span)\n\n const label = document.createElement('label')\n this.button.appendChild(label)\n label.innerHTML = 'Views'\n \n this.viewer.container.appendChild(this.button)\n }",
"function addButtons() {\n target.css({\n 'border-width': '5px'\n });\n //console.log(\"INSIDE addButtons, thisID: \" + thisId + \" and thisKittenId: \" + thisKittenId);\n // append the delete and edit buttons, with data of metric document id, and kitten document id\n target.append(\"<button type='button' class='btn btn-default btn-xs littleX' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>\");\n target.append(\"<button type='button' class='btn btn-default btn-xs littleE' data_idKitten=\" + \n thisKittenId + \" data_id=\" + \n thisId + \"><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span></button>\");\n // set boolean to true that delete and edit buttons exist\n littleButton = true;\n }",
"function addToWatchList(event) {\n var stockSymbol = $(this).attr(\"stock-id\");\n\n console.log(\"in addToWatchList, currentUser: \" + appUser.email);\n\n event.preventDefault();\n // empty out stock-ticker content\n $(\"#stock-ticker-content\").empty();\n $(\"#my-watch-table\").show();\n\n console.log(\"in addToWatchList() \");\n console.log(\"stock symbol: \" + stockSymbol);\n\n // get current price of stock symbol\n buildBatchURL(stockSymbol, \"watch\");\n\n // get yesterday's close price of stock symbol\n buildTimeSeriesURL(stockSymbol);\n\n // add row to watchListTable\n renderWatchTable(stockSymbol);\n }",
"function buildGameButton(){\n\tbuttonStart.cursor = \"pointer\";\n\tbuttonStart.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundButton');\n\t\tgoPage('tutorial');\n\t});\n\t\n\tbuttonGotIt.cursor = \"pointer\";\n\tbuttonGotIt.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundButton');\n\t\tgoPage('game');\n\t});\n\t\n\tfor(n=0;n<pots_arr.length;n++){\n\t\t$.buttons[n+'_cook'].cursor = \"pointer\";\n\t\t$.buttons[n+'_cook'].id = n;\n\t\t$.buttons[n+'_cook'].addEventListener(\"click\", function(evt) {\n\t\t\tevt.preventDefault();\n\t\t\tstartCook(evt.target.id);\n\t\t});\n\t\t\n\t\t$.buttons[n+'_burn'].cursor = \"pointer\";\n\t\t$.buttons[n+'_burn'].id = n;\n\t\t$.buttons[n+'_burn'].addEventListener(\"mousedown\", function(evt) {\n\t\t\tevt.preventDefault();\n\t\t\tpots_arr[evt.target.id].heatUp = true;\n\t\t\tplaySound('soundBurn');\n\t\t});\n\t\t\n\t\t$.buttons[n+'_burn'].addEventListener(\"pressup\", function(evt) {\n\t\t\tevt.preventDefault();\n\t\t\tpots_arr[evt.target.id].heatUp = false;\n\t\t});\n\t}\n\t\n\tbuttonReplay.cursor = \"pointer\";\n\tbuttonReplay.addEventListener(\"click\", function(evt) {\n\t\tplaySound('soundButton');\n\t\tgoPage('tutorial');\n\t});\n\t\n\ticonFacebook.cursor = \"pointer\";\n\ticonFacebook.addEventListener(\"click\", function(evt) {\n\t\tshare('facebook');\n\t});\n\ticonTwitter.cursor = \"pointer\";\n\ticonTwitter.addEventListener(\"click\", function(evt) {\n\t\tshare('twitter');\n\t});\n\ticonGoogle.cursor = \"pointer\";\n\ticonGoogle.addEventListener(\"click\", function(evt) {\n\t\tshare('google');\n\t});\n}",
"function buildBuyBtn(stockSym) {\n var buyBtn = $(\"<button>\");\n\n buyBtn.addClass(\"ml-2 btn btn-sm btn-primary buy-button\").\n attr(\"buy-id\", stockSym).\n html(\"★ Buy\");\n\n return buyBtn;\n }",
"_update_ws() {\n\t\t// destroy old workspaces bar buttons and signals\n\t\tthis.ws_bar.destroy_all_children();\n\n\t\t// get number of workspaces\n\t\tthis.ws_count = WM.get_n_workspaces();\n\t\tthis.active_ws_index = WM.get_active_workspace_index();\n\n\t\t// display all current workspaces and tasks buttons\n\t\tfor (let ws_index = 0; ws_index < this.ws_count; ++ws_index) {\n\t\t\t// workspace\n\t\t\tvar ws_box = new St.Bin({visible: true, reactive: true, can_focus: true, track_hover: true});\n\t\t\tws_box.label = new St.Label({y_align: Clutter.ActorAlign.CENTER});\n\t\t\tif (ws_index == this.active_ws_index) {\n\t\t\t\tws_box.label.style_class = 'workspace-active';\n\t\t\t} else {\n\t\t\t\tws_box.label.style_class = 'workspace-inactive';\n\t\t\t}\n\t\t\tif (this.workspaces_names[ws_index]) {\n\t\t\t\tws_box.label.set_text(\" \" + this.workspaces_names[ws_index] + \" \");\n\t\t\t} else {\n\t\t\t\tws_box.label.set_text(\" \" + (ws_index + 1) + \" \");\n\t\t\t}\n\t\t\tws_box.set_child(ws_box.label);\n\t\t\tws_box.connect('button-press-event', () => this._toggle_ws(ws_index));\n\t\t\tthis.ws_bar.add_child(ws_box);\n\n\t\t\t// tasks\n\t\t\tthis.ws_current = WM.get_workspace_by_index(ws_index);\n\t\t\tthis.ws_current.windows = this.ws_current.list_windows().sort(this._sort_windows);\n\t\t\tfor (let window_index = 0; window_index < this.ws_current.windows.length; ++window_index) {\n\t\t\t\tthis.window = this.ws_current.windows[window_index];\n\t\t\t\tif (this.window) {\n\t\t\t\t\tthis._create_window_button(ws_index, this.window);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function renderWatchTable(sym) {\n var tRow = $(\"<tr>\"),\n tCellSym = $(\"<td>\"),\n tCellPrice = $(\"<td>\"),\n tCellChange = $(\"<td>\"),\n tCellPct = $(\"<td>\"),\n tCellRmv = $(\"<td>\"),\n delBtn = $(\"<button>\"),\n dbPath = \"watchlist/\" + sym,\n price, changeInPrice, pctCh,\n dbVal;\n\n // read current stock price from database\n database.ref(dbPath).on(\"value\", (snapshot) => {\n dbVal = snapshot.val();\n console.log(\"dbVal: \" + JSON.stringify(dbVal));\n console.log(\"price: \" + dbVal.stockPrice);\n price = dbVal.stockPrice;\n changeInPrice = dbVal.change;\n pctCh = dbVal.pctChange;\n\n console.log(\"in renderWatchTable: \" + price);\n // console.log(\"converted price: \" + numeral(cprice).format(\"$0,0.00\"));\n tCellSym.text(sym);\n tCellPrice.html(numeral(price).format(\"$0,0.00\"));\n tCellChange.html(numeral(changeInPrice).format(\"+0,0.00\"));\n tCellPct.html(numeral(pctCh).format(\"0.00%\"));\n delBtn.attr(\"id\", \"btn-\" + sym).\n attr(\"data-name\", sym).\n addClass(\"custom-remove remove-from-watchlist\").\n text(\"x\");\n tCellRmv.append(delBtn);\n tRow.attr(\"id\", \"wrow-\" + sym).\n attr(\"stock-sym\", sym);\n // empty out row so as to not repeat stock symbol on watchlist\n $(\"#wrow-\" + sym).empty();\n tRow = $(\"#wrow-\" + sym).append(tCellSym, tCellPrice, tCellChange, tCellPct, tCellRmv);\n }, (errorObject) => {\n console.log(\"Errors handled: \" + errorObject.code);\n });\n $(\"#watchlist-caption\").show();\n $(\"#watch-table-header\").show();\n $(\"#watch-table\").prepend(tRow);\n }",
"function renderWatchTable(sym) {\n var tRow = $(\"<tr>\"),\n tCellSym = $(\"<td>\"),\n tCellPrice = $(\"<td>\"),\n tCellChange = $(\"<td>\"),\n tCellPct = $(\"<td>\"),\n tCellRmv = $(\"<td>\"),\n delBtn = $(\"<button>\"),\n dbPath = \"/watchlist/\" + sym,\n price, changeInPrice, pctCh,\n dbVal;\n\n // read current stock price from database\n database.ref(dbPath).on(\"value\", (snapshot) => {\n dbVal = snapshot.val();\n console.log(\"in renderWatchTable dbVal: \" + JSON.stringify(dbVal));\n price = dbVal.stockPrice;\n changeInPrice = dbVal.change;\n pctCh = dbVal.pctChange;\n\n console.log(\"in renderWatchTable: \" + price);\n // console.log(\"converted price: \" + numeral(cprice).format(\"$0,0.00\"));\n tCellSym.text(sym);\n tCellPrice.html(numeral(price).format(\"$0,0.00\"));\n tCellChange.html(numeral(changeInPrice).format(\"+0,0.00\"));\n tCellPct.html(numeral(pctCh).format(\"0.00%\"));\n delBtn.attr(\"id\", \"btn-\" + sym).\n attr(\"data-name\", sym).\n addClass(\"custom-remove remove-from-watchlist\").\n text(\"x\");\n tCellRmv.append(delBtn);\n tRow.attr(\"id\", \"wrow-\" + sym).\n attr(\"stock-sym\", sym);\n // empty out row so as to not repeat stock symbol on watchlist\n $(\"#wrow-\" + sym).empty();\n tRow = $(\"#wrow-\" + sym).append(tCellSym, tCellPrice, tCellChange, tCellPct, tCellRmv);\n }, (errorObject) => {\n console.log(\"Errors handled: \" + errorObject.code);\n });\n $(\"#watchlist-caption\").show();\n $(\"#watch-table-header\").show();\n $(\"#watch-table\").prepend(tRow);\n }",
"function tb_add_clipping_to_workspace(){\n $(\"#TB_window input.link\").link_button();\n\t$(\"#project_name\").clear_search();\n $(\"form.new_clipping\").select_project_to_add();\n}",
"_createSceneryButton(buttons) {\r\n\t\tlet tokenButton = buttons.find((b) => b.name === 'token');\r\n\t\tif (tokenButton && game.user.isGM) {\r\n\t\t\ttokenButton.tools.push({\r\n\t\t\t\tname: 'scenery',\r\n\t\t\t\ttitle: 'NT.ButtonTitle',\r\n\t\t\t\ticon: 'fas fa-theater-masks',\r\n\t\t\t\tvisible: game.user.isGM,\r\n\t\t\t\ttoggle: true,\r\n\t\t\t\tactive: this.sharedState.scenery,\r\n\t\t\t\tonClick: (toggle) => {\r\n\t\t\t\t\tthis.scenery(toggle);\r\n\t\t\t\t},\r\n\t\t\t});\r\n\t\t}\r\n\t}",
"function createButton() { \n for (let i = 0; i < tvShows.length; i++) {\n const element = tvShows[i];\n let button = $(\"<button>\");\n \n button.addClass(\"btn btn-primary show-button\");\n button.attr(\"data-show\", element);\n button.attr(\"type\", \"submit\");\n button.text(element);\n $(\"#buttons\").append(button);\n }\n }",
"function addReportInAppButton() {\r\n if (userConfig.inappSvcURL) {\r\n removeReportInAppButton();\r\n $('.esriPopup .actionList').append('<a id=\"inFlag\"><span class=\"inappropriate\"></span>Flag as inappropriate</a>');\r\n }\r\n}",
"function addButtonClickHandlers()\n {\n \n $(\"#perc-wb-button-new\").unbind().click(function(){\n handleWidgetNew();\n });\n $(\"#perc-widget-save\").on(\"click\",function(){\n handleWidgetSave();\n });\n $(\"#perc-widget-close\").on(\"click\",function(){\n handleWidgetClose();\n });\n \n WidgetBuilderApp.updateToolBarButtons = function(disableButtons){\n if(disableButtons){\n $(\"#perc-wb-button-delete\").addClass(\"ui-disabled\").removeClass(\"ui-enabled\").unbind();\n $(\"#perc-wb-button-edit\").addClass(\"ui-disabled\").removeClass(\"ui-enabled\").unbind();\n $(\"#perc-wb-button-deploy\").addClass(\"ui-disabled\").removeClass(\"ui-enabled\").unbind();\n }\n else{\n $(\"#perc-wb-button-delete\").removeClass(\"ui-disabled\").addClass(\"ui-enabled\").unbind().click(function(){\n handleWidgetDelete();\n });\n $(\"#perc-wb-button-edit\").removeClass(\"ui-disabled\").addClass(\"ui-enabled\").unbind().click(function(){\n handleWidgetEdit();\n });\n $(\"#perc-wb-button-deploy\").removeClass(\"ui-disabled\").addClass(\"ui-enabled\").unbind().click(function(){\n handleWidgetDeploy();\n });\n }\n }\n }",
"function buildUI(thisObj){\n\n\t\t\t// ----- Main Window -----\n\t\t\tvar w = (thisObj instanceof Panel) ? thisObj : new Window(\"palette\", scriptName);\n\t\t\t\tw.alignChildren = ['fill', 'fill'];\n\n\t\t\t\tw.add(\"statictext\", undefined, \"Use the + button to add a project, or use the ? button to access the settings window and import a previous list.\", {multiline: true});\n\n\t\t\t\t// group for panel buttons\n\t\t\t\tvar panelBtns = w.add(\"group\");\n\n\t\t\t\t\t//panel buttons\n\t\t\t\t\tvar addProjBtn = panelBtns.add(\"button\", undefined, \"+\");\n\t\t\t\t\tvar remProjBtn = panelBtns.add(\"button\", undefined, \"-\");\n\t\t\t\t\tvar settingsBtn = panelBtns.add(\"button\", undefined, \"?\");\n\n\t\t\t\t\taddProjBtn.preferredSize = \n\t\t\t\t\tremProjBtn.preferredSize = \n\t\t\t\t\tsettingsBtn.preferredSize = [80, 30] \n\n\t\t\t\t// group for list of projects\n\t\t\t\tvar projsListGroup = w.add(\"group\");\n\t\t\t\t\tprojsListGroup.alignChildren = ['fill', 'fill'];\n\n\t\t\t\t\t// project list\n\t\t\t\t\tvar projList = projsListGroup.add(\"listbox\", undefined, theProjectNames, {scrollable: true});\n\t\t\t\t\t\tprojList.preferredSize = ['', 250]\n\n\t\t\t\t// group for system buttons\n\t\t\t\tvar systemBtns = w.add(\"group\");\n\n\t\t\t\t\t// system buttons\n\t\t\t\t\tvar importBtn = systemBtns.add(\"button\", undefined, \"Import\")\n\t\t\t\t\tvar openBtn = systemBtns.add(\"button\", undefined, \"Open\");\n\t\t\t\t\tvar cancelBtn = systemBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t\timportBtn.preferredSize =\n\t\t\t\t\topenBtn.preferredSize =\n\t\t\t\t\tcancelBtn.preferredSize = [80, 30]\n\n\t\t\t\t\t// ----- Main Window Functionality -----\n\t\t\t\taddProjBtn.onClick = function(){\n\t\t\t\t\taddProject();\n\t\t\t\t}\n\n\t\t\t\tremProjBtn.onClick = function(){\n\n\t\t\t\t\tdelete theList[projList.selection];\n\t\t\t\t\tupdateProjList(getProjectNames(theList));\t\t\t\t\n\n\t\t\t\t}\n\n\t\t\t\tsettingsBtn.onClick = function(){\n\t\t\t\t\tmakeSettingsWindow();\n\t\t\t\t}\n\n\t\t\t\timportBtn.onClick = function(){\n\n\t\t\t\t\tapp.project.importFile(new ImportOptions(File(theList[projList.selection])));\n\t\t\t\t}\n\n\t\t\t\topenBtn.onClick = function(){\n\t\t\t\t\tapp.open(File(theList[projList.selection]));\n\t\t\t\t}\n\n\t\t\t\tcancelBtn.onClick = function(){\n\n\t\t\t\t\tw.close();\n\t\t\t\t}\n\n\t\t\t\tw.onClose = function(){\n\t\t\t\t\tif (checkObjectForEmpty(theList) == false){\n\t\t\t\t\t\twriteListFile(theList); // save the list when closing the panel.\n\t\t\t\t\t } else {\n\t\t\t\t\t\twriteListFile(new Object ())\n\t\t\t\t\t }\t\n\t\t\t\t}\n\n\t\t\t\t// ----- End Main Window Functionality -----\n\n\t\t\t// ----- End Main Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- Make Add Project Window -----\n\n\t\t\tfunction addProject(){\n\n\t\t\t\tvar addProjWindow = new Window(\"palette\", \"Add Project\");\n\n\t\t\t\t// group for custom project\n\t\t\t\tvar customProjGroup = addProjWindow.add(\"group\");\n\t\t\t\t\tcustomProjGroup.orientation = \"column\";\n\t\t\t\t\tcustomProjGroup.alignChildren = ['left', 'fill']\n\n\t\t\t\t\t// Project name group\n\t\t\t\t\tvar projNameGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojNameGroup.add(\"statictext\", undefined, \"Project Name:\")\n\t\t\t\t\t\t// Project Name\n\t\t\t\t\t\tvar projName = projNameGroup.add(\"edittext\", undefined, \"Project Name\");\n\t\t\t\t\t\t\tprojName.characters = 32;\n\n\t\t\t\t\t// Project location group\n\t\t\t\t\tvar projLocGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojLocGroup.add(\"statictext\", undefined, \"Project Location:\")\n\n\t\t\t\t\t\t// Project Location\n\t\t\t\t\t\tvar projLoc = projLocGroup.add(\"edittext\", undefined, \"Project Location\");\n\t\t\t\t\t\t\tprojLoc.characters = 24;\n\n\t\t\t\t\t\tvar getProjLoc = projLocGroup.add(\"button\", undefined, \"...\");\n\t\t\t\t\t\t\tgetProjLoc.preferredSize = [31, 20];\n\n\t\t\t\t// group for buttons\n\t\t\t\tvar addProjBtns = addProjWindow.add(\"group\");\n\n\t\t\t\t\t// button for current project\n\t\t\t\t\tvar setCurProjBtn = addProjBtns.add(\"button\", undefined, \"Set Current\");\n\n\t\t\t\t\t// button to add the project\n\t\t\t\t\tvar addProjBtn = addProjBtns.add(\"button\", undefined, \"Add Project\");\n\t\t\t\t\t\n\t\t\t\t\t// button to cancel\n\t\t\t\t\tvar cancelAddBtn = addProjBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- SHOW WINDOW -----\n\t\t\t\taddProjWindow.show();\n\t\t\t\t\n\t\t\t\t// ----- Add Project Window Functionality -----\n\t\t\t\tgetProjLoc.onClick = function(){\n\t\t\t\t\tvar getAEP = File.openDialog(\"Please select the location of an AEP.\");\n\t\t\t\t\tif (getAEP != null){\n\n\t\t\t\t\t\tif (getAEP.fsName.split(\".\").pop() == \"aep\"){\n\n\t\t\t\t\t\t\tprojName.text = getAEP.fsName.split(\"/\").pop();\n\t\t\t\t\t\t\tprojLoc.text = getAEP.fsName;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(getAEP.name.split(\".\")[0] + \" is a \" + getAEP.fsName.split(\".\").pop() + \" file. Please select an AEP!\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open file. Please make sure you selected something!\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsetCurProjBtn.onClick = function(){\n\n\t\t\t\t\tif (app.project){\n\n\t\t\t\t\t\tprojName.text = String(app.project.file).split(\"/\").pop();\n\t\t\t\t\t\tprojLoc.text = app.project.file;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Please open a Project!\");\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\taddProjBtn.onClick = function(){\n\n\t\t\t\t\tif (new File(projLoc.text).exists){\n\t\t\t\t\t\tif(projName.text.length > 0 && projName.text != \"Project Name\"){\n\t\t\t\t\t\t\ttheList[projName.text] = projLoc.text;\n\t\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(\"The name \\'\" + projName.text + \"\\' is not valid. Please choose a better name.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"File at \" + projLoc.text + \" does not exist. Please double check that you've selected the correct file.\")\n\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcancelAddBtn.onClick = function(){\n\n\t\t\t\t\treturn addProjWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Add Project Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- Make Settings Window -----\n\n\t\t\tfunction makeSettingsWindow(){\n\n\t\t\t\tvar settingsWindow = new Window(\"palette\", \"Settings\");\n\t\t\t\t\tsettingsWindow.alignChildren = ['fill', 'fill'];\n\n\t\t\t\t\t// group for text (about, etc)\n\t\t\t\t\tvar aboutGroup = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\taboutGroup.add(\"statictext\", undefined, aboutText, {multiline: true});\n\n\t\t\t\t\t// group for importing and exporting lists\n\t\t\t\t\tvar importExportListGroup = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\t// import list\n\t\t\t\t\t\tvar importListBtn = importExportListGroup.add(\"button\", undefined, \"Import List\");\n\t\t\t\t\t\tvar exportListBtn = importExportListGroup.add(\"button\", undefined, \"Export List\");\n\n\t\t\t\t\t// group for settings buttons (OK)\n\t\t\t\t\tvar settingsBtns = settingsWindow.add(\"group\");\n\n\t\t\t\t\t\t// button to close the window\n\t\t\t\t\t\tvar closeSettings = settingsBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- Show Window -----\n\t\t\t\tsettingsWindow.show();\n\n\t\t\t\t// ----- Settings Window FUNCTIONALITY -----\n\t\t\t\timportListBtn.onClick = function(){\n\t\t\t\t\tvar theNewList = File.openDialog(\"Please select a JSON file created by this script.\");\n\t\t\t\t\tif (theNewList != null){\n\t\t\t\t\t\ttheList = readJSONFile(theNewList);\n\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open JSON file. Please try again and ensure a JSON file is selected.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\texportListBtn.onClick = function(){\n\t\t\t\t\tvar saveLoc = Folder.selectDialog(\"Please select a location to save your .JSON file.\");\n\t\t\t\t\tif (saveLoc != null){\n\t\t\t\t\t\texportList(theList, saveLoc);\n\t\t\t\t\t} \n\t\t\t\t}\n\n\t\t\t\tcloseSettings.onClick = function(){\t\t\t\t\n\t\t\t\t\treturn settingsWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Make Settings Window -----\n\n\n\n\n\n\n\n\n\n\t\t\t// ----- HELPER FUNCTIONS -----\n\t\t\t\n\t\t\tfunction updateProjList(newArrayOfItems){\n\t\t\t\tvar newList = projsListGroup.add(\"listbox\", projList.bounds, newArrayOfItems, {scrolling: true});\n\t\t\t\tprojsListGroup.remove(projList);\n\n\t\t\t\tprojList = newList;\n\t\t\t}\n\n\n\n\n\n\n\n\n\n\n\t\t\t\n\t\t\t// Return window.\n\t\t\tw.layout.layout(true);\n\t\t\treturn w;\n\n\n\t\t} // ----- End Build UI -----"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether a value is a sequence (e.g. array of numbers). | function isSequence(val) {
return val.length !== undefined;
} | [
"function ISARRAY(value) {\n return Object.prototype.toString.call(value) === '[object Array]';\n}",
"function ArraySeq(array){\n this.sElem = 0;\n this.sequence = array;\n}",
"static isArray(input) {\n return input instanceof Array;\n }",
"function regularBracketSequence1(sequence) {\n const stack = [];\n \n for(let i = 0; i < sequence.length; i++) {\n if(sequence[i] === ')') {\n if(stack.length > 0) {\n stack.pop();\n } else {\n return false;\n }\n } else {\n stack.push(sequence[i]);\n }\n }\n return stack.length > 0 ? false : true;\n}",
"isPath(value) {\n return Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number');\n }",
"function IsArrayLike(x) {\r\n return x && typeof x.length == \"number\" && (!x.length || typeof x[0] != \"undefined\");\r\n }",
"function isStrictlyArrayAnnotation (annotation: TypeAnnotation): ?boolean {\n switch (annotation.type) {\n case 'ArrayTypeAnnotation':\n case 'TupleTypeAnnotation':\n return true;\n case 'TypeAnnotation':\n case 'FunctionTypeParam':\n return isStrictlyArrayAnnotation(annotation.typeAnnotation);\n case 'GenericTypeAnnotation':\n return annotation.id.name === 'Array' ? true : null;\n case 'UnionTypeAnnotation':\n return annotation.types.every(isStrictlyArrayAnnotation);\n default:\n return false;\n }\n }",
"function is_array(obj){\n return Array.isArray(obj);\n}",
"isTextList(value) {\n return Array.isArray(value) && value.every(val => Text.isText(val));\n }",
"isOperationList(value) {\n return Array.isArray(value) && value.every(val => Operation.isOperation(val));\n }",
"function isaNumberEven(array){\n\t\n}",
"function isSubsequence(s1, s2) {\n if (s1.length < s2.length) {\n return false;\n }\n let idx1 = 0, idx2 = 0;\n while (idx2 < s2.length && idx1 < s1.length) {\n const t1 = s1[idx1], t2 = s2[idx2];\n if (isTransactionContain(t1, t2)) {\n idx1++;\n idx2++;\n } else {\n idx1++;\n }\n }\n return idx2 === s2.length;\n}",
"isValidRecordingData() {\n if (Array.isArray(this.recordingData)) {\n if (Array.isArray(this.recordingData[0]) && this.recordingData[0].length === 3) {\n return true;\n }\n }\n\n console.log(`Error: Input recording data is not in valid format`);\n return false;\n }",
"function testcase() {\n var b_num = Array.isArray(42);\n var b_undef = Array.isArray(undefined);\n var b_bool = Array.isArray(true);\n var b_str = Array.isArray(\"abc\");\n var b_obj = Array.isArray({});\n var b_null = Array.isArray(null);\n \n if (b_num === false &&\n b_undef === false &&\n b_bool === false &&\n b_str === false &&\n b_obj === false &&\n b_null === false) {\n return true;\n }\n }",
"function checkDNA (seq1, seq2) {\n\n}",
"function is_stream(xs) {\n return is_null(xs) || (is_pair(xs) && is_list(stream_tail(xs)));\n}",
"function in_array(val, array) {\n\t\tfor(var i = 0, l = array.length; i < l; i++) {\n\t\t\tif(array[i] == val) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"function arrayOrObject(value) {\n if(Array.isArray(value)) return \"array\";\n return \"object\";\n}",
"function costas_verify ( array ){\n var result;\n var diff_array = array_diff_vector( array );\n var array_set = set_of_values( array );\n var diff_array_set = set_of_values( diff_array );\n //console.log( 'diff_array length', diff_array.length );\n //console.log( 'diff_array_set length', diff_array_set.length );\n return ( diff_array.length === diff_array_set.length && array_set.length === array.length );\n}",
"function ISTEXT(value) {\n return 'string' === typeof value;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits a mnemonic phrase into words, handling extra whitespace anywhere in the phrase. | function splitMnemonic(mnemonic) {
return __spread(mnemonic.trim().split(/\s+/));
} | [
"function tokenize(phrase) {\n\n const tokenArray = [];\n let currToken = \"\";\n\n for (let i = 0; i < phrase.length; i++) {\n if(phrase[i] !== \" \") {\n currToken += phrase[i];\n } else {\n tokenArray.push(currToken);\n currToken = \"\";\n }\n }\n\n tokenArray.push(currToken);\n return tokenArray;\n}",
"static fromPhrase(phrase, password, wordlist) {\n // Normalize the case and space; throws if invalid\n const entropy = mnemonicToEntropy(phrase, wordlist);\n phrase = entropyToMnemonic(getBytes(entropy), wordlist);\n return new Mnemonic(_guard, entropy, phrase, password, wordlist);\n }",
"function textsplit(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.split());\n\tconsole.log(aku.split(\"\"));\n\tconsole.log(aku.split(\" \"));\n}",
"words(content) {\n //@TODO\n let content_array = content.split(/\\s+/);\n const normalized_content = content_array.map((w)=>normalize(w));\n const words = normalized_content.filter((w) => !this.noise_w_set.has(w)); \n return words;\n }",
"function WordParser () {}",
"function enterWords() {\n\tvar wordListInput = prompt(\"Enter your list of words here seperated by spaces\");\n\twordBank = [];\n\tvar i = 0;\n\n\twhile (wordListInput.includes(\" \") === true && i < 200) {\n\t\twordBank[i] = wordListInput.slice(0,wordListInput.indexOf(\" \"))\n\n\t\twordListInput = wordListInput.slice(wordListInput.indexOf(\" \"),wordListInput.length);\n\n\t\tif (wordListInput.charAt(0) === \" \") {\n\t\t\twordListInput = wordListInput.slice(1,wordListInput.length);\n\t\t}\n\t\ti++;\n\t}\n}",
"function isolateWord(str, loc) {\n var word = '';\n var sec1 = str.slice(0, loc);\n var sec2 = str.slice(loc);\n\n var j1 = sec1.lastIndexOf(' ');\n var j2 = sec1.lastIndexOf('\\n');\n var j3 = sec1.lastIndexOf(nbsp_str);\n\n var j = (j1<0 ? j2 : (j2<0 ? j1 : (j1>j2 ? j1 : j2)));\n j = (j3<0 ? j : (j<0 ? j3 : (j3>j ? j3 : j)));\n\n var i1 = sec2.indexOf(' ');\n var i2 = sec2.indexOf('\\n');\n var i3 = sec2.indexOf(nbsp_str);\n\n var i = (i1<0 ? i2 : (i2<0 ? i1 : (i1<i2 ? i1 : i2)));\n i = (i3<0 ? i : (i<0 ? i3 : (i3<i ? i3 : i)));\n\n if (j >= 0)\n word = sec1.slice(j+1);\n else\n word = sec1;\n\n if (i >= 0)\n word += sec2.slice(0,i);\n else\n word += sec2;\n\n return trimWordLowerCase(word);\n}",
"function getWords() {\n\t\tvar raw = Util.txt.getInputText();\n\t\tvar cleanText = Util.txt.clean(raw);\n\t\t\tcleanText = cleanText.toLowerCase();\n\t\t\tcleanText = cleanText.replace(/[\\t\\s\\n]/g,\" \");\n\t\t\tcleanText = cleanText.replace(/[ ]{2,}/g,\" \");\n\t\tvar words = cleanText.split(\" \");\n\t\t\twords = words.sort();\n\t\treturn Util.gen.unique(words);\n\t}",
"function reducer(sentence) {\nlet splittedArray = sentence.split(' ');\nlet newWord = splittedArray.reduce(function(initialValue, currentValue){\n\tif(splittedArray(currentValue).length === 3) {\n\t\tinitialValue += ' ';\n\t\treturn initialValue;\n\t}\n\telse {\n\t\tinitialValue += splittedArray(currentValue).charAt(currentValue.length-1).toUpperCase();\n\t\treturn initialValue;\n\t}\n\t}, '');\nreturn newWord;\n}",
"tokenizeWord(offset) {\n const start = offset;\n let character;\n // TODO(cdata): change to greedy regex match?\n while ((character = this.cssText[offset]) &&\n !common_1.matcher.boundary.test(character)) {\n offset++;\n }\n return new token_1.Token(token_1.Token.type.word, start, offset);\n }",
"function getSearchWords() {\n // get inpu\n let entry = document.getElementById('search-field').value;\n // split in words\n let words = entry.split(' ');\n // del empty elements of array, and make all to lower case\n for (let i = words.length - 1; i >= 0; i--) {\n // to lower case\n words[i] = words[i].toLowerCase();\n // del empty values\n if (words[i] == \"\") {\n words.splice(i, 1);\n }\n }\n return words;\n}",
"function tooManyWords(){\n\t\n\tanswer = prompt(\"Please enter a phrase...\");\n\t\n\tif (answer == null || typeof answer == undefined) {\n\t return;\n\t}\n\t // if empty string pass display message\n\t answer.trim();\n\t if (answer.length == 0) {\n\t \talert(\"Acronym can not be created using empty string\");\n\t }\t\n\t // copy split data to temp variable \n\t var temp_line = answer.split(\" \");\n\t \n\t var acronym =\"\";\n\t var acronym_line =\"\";\n\t \n\t for ( var i = 0; i <temp_line.length; i++){\n\t\t // create acronym \n\t\t acronym += temp_line[i].charAt(0).toUpperCase(); \n\t\t \n\t\t //copy acronym line with first letter upper case\n\t\t acronym_line += temp_line[i].charAt(0).toUpperCase();\n\t\t acronym_line += temp_line[i].substring(1, temp_line[i].length);\n\t\t acronym_line += \" \";\n\t\t \n\t }\t \n\t // display acronym to user\n\t alert (acronym + \" stands for \" + acronym_line);\n\t \n\t // count number of acronym created by user\n acronyms++;\n\t \n}",
"function sentensify(str) {\n // Add your code below this line\n var splitStr = str.split(/\\W/);\n var newSplitStr = splitStr.join(\" \");\n \n return newSplitStr;\n\n // Add your code above this line\n }",
"function wordStep(str) {\n var words = str.split('');\n\n var height = 0;\n var heightWordCount = 0;\n var heightWords = [];\n var onHeightWord = 0;\n\n var width = 0;\n var widthWordCount = 0;\n var widthWords = [];\n var onWidthWord = 0;\n\n var temp = [];\n var completedMatrix = [];\n\n for (let i = 0; i < words.length; i++) {\n for (let j = 0; j < words[i].length; j++) {\n if (i % 2 != 0) {\n width += words[i].length;\n widthWordCount++;\n widthWords.push(words[i]);\n }\n else {\n height += words[i].length;\n heightWordCount++;\n heightWords.push(words[i]);\n }\n width - widthWordCount;\n height - heightWordCount;\n }\n }\n\n console.log('the width is: ', width);\n console.log('the height is: ', height);\n \n // for (let x = 0; x < width; x++) {\n // for (let y = 0; y < height; y++) {\n // temp.push(' ');\n // }\n // completedMatrix.push(temp);\n // temp = [];\n // }\n\n\n // for (let a = 0; a < widthWordCount; a++) {\n // for (let b = 0; b < heightWordcount; b++) {\n //\n // }\n // }\n}",
"parseSearch() {\n const searchTerm = this.state.term.split(\" \");\n\n const data = { \n make: searchTerm[0],\n model: searchTerm[1]\n };\n return data;\n }",
"function correctSpacing(sentence) {\n\treturn sentence.replace(/\\s+/g,' ').trim();\n}",
"function onlyOneWord(arr){\n\n \treturn arr.filter(a=>!(a.includes(\" \")));\n\n \t\n }",
"function songDecoder(song) {\n\n //split input by WUB\n let words = song.split(\"WUB\");\n\n //store result in a string\n let result = '';\n\n //loop through array\n words.forEach(element => {\n\n //if element is not blank add to result with a space\n if (element !== '') {\n result += element + ' ';\n }\n\n });\n\n //we have to remove the extra space from the end of the string\n return result.trim(); //alternatives: str.substring(0, str.length - 1); or str.slice(0, -1);\n\n\n}",
"function parseAction(userInput) {\n let inputWordsArray = userInput.toLowerCase().split(' ')\n let action = inputWordsArray[0]\n let noun = inputWordsArray.slice(1,).join(' ')\n\n return {action,noun}\n}",
"function calculateWords(textInput){\n let wordsArr = textInput.trim().split(' ')\n return wordsArr.length;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mostrar datos de local Storage en listas | function localStorageListo() {
var tweets;
tweets = obtenerTweetsLocalStorage();
tweets.forEach(function cicloEach(val) {
agregarTweetsAListas(val);
})
} | [
"function obtenereCursosLocalStorage () {\n let cursosLS;\n\n //Comprobamos si hay items en el local storage\n if(localStorage.getItem('cursos') === null) {\n //si no hay cursos en el LS inicias como array vacio\n cursosLS = [];\n }else{\n cursosLS = JSON.parse(localStorage.getItem('cursos'));\n }\n return cursosLS;\n}",
"function loadItemList() {\n removeEmptyItems() // cleanup\n db = getDBFromLocalStorage() // get the latest saved object from localStorage\n Object.keys(db).forEach(function(key) {\n if(db[key]['title'] !== \"\") {\n main.innerHTML = `<section data-key='${key}'>${db[key]['title'].substr(0, titleLimit)}</section>` + main.innerHTML\n } else { // if title is blank, then show the first couple characters of the content as the title\n main.innerHTML = `<section data-key='${key}'>${decodeURIComponent(db[key]['content']).substr(0, titleLimit)}</section>` + main.innerHTML\n }\n })\n }",
"function saveStorage() {\r\n //acessando a variavel global localStorage, e inserindo o todo para fucar armazenado\r\n //é nessessário transformar em jason pois o localstorage não entende array\r\n localStorage.setItem(\"list_todo\", JSON.stringify(todos));\r\n}",
"function salvandoDados () {\n\n localStorage.setItem('tarefas', JSON.stringify(tarefas));\n\n}",
"function obtenerCamposLocalStorage(name){\n //Revisamos los valores del localStorage\n if(localStorage.getItem(name) === null){\n name=[];\n }else{\n name = JSON.parse(localStorage.getItem(name));\n }\n return name;\n }",
"static getDataFromLS(){\r\n let products;\r\n if(localStorage.getItem('products') === null){\r\n products = []\r\n }else{\r\n products = JSON.parse(localStorage.getItem('products'));\r\n }\r\n return products;\r\n }",
"function list() {\n\tfs.readFile(\n\t\tpath.resolve(__dirname, \"../\", \"main.json\"),\n\t\t\"utf8\",\n\t\tfunction readFileCallback(err, data) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t} else {\n\t\t\t\tconsole.log(\n\t\t\t\t\t\"Current File \" + chalk.keyword(\"green\")(JSON.parse(data).currentFile)\n\t\t\t\t);\n\t\t\t\tfs.readdir(path.resolve(__dirname, \"../\", \"asciiArt\"), function (err, items) {\n\t\t\t\t\tconsole.log(\"Files: \");\n\t\t\t\t\titems.forEach(item => {\n\t\t\t\t\t\tconsole.log(\"Name: \" + chalk.keyword(\"green\")(item.replace(\".txt\", \"\")) + \" File: \" + chalk.keyword(\"green\")(item));\n\t\t\t\t\t})\n\n\t\t\t\t});\n\n\t\t\t}\n\t\t}\n\t);\n\n\n}",
"function cargarTweetswLocalStorage(){\n let tweets;\n tweets = obtenerTweetsLocalStorage();\n tweets.forEach(function(tweet){\n // Crear boton de eliminar\n const botonBorrar = document.createElement('a');\n botonBorrar.classList = 'borrar-tweet';\n botonBorrar.innerText = 'X';\n // Crear elemento y añadirlo al contenido de la lista\n const li = document.createElement('li');\n li.innerText = tweet;\n li.appendChild(botonBorrar);\n listaTweets.appendChild(li);\n });\n}",
"saveToStore() {\n localStorage.setItem(STORAGE.TAG, JSON.stringify(this.list));\n }",
"function getLocalData() {\n\n //If null, won't add anything\n for (j = 9; j < 18; j++) {\n let data = localStorage.getItem(`${j}`);\n console.log(data);\n $(`#${j} textarea`).val(data);\n };\n }",
"function retrievePaths(){\n\tif (typeof(Storage) !== \"undefined\"){\n\t\tvar paths = JSON.parse(localStorage.getItem(APP_PREFIX))\n\t\tfor (var i = 0; i<paths.length; i++){\n\t\t\tvar current = new Path(paths[i]);\n\t\t\tpathList.push(current);\n\t\t\tpathNames.push(current.title);\n\t\t}\n\t}else{\n\t\tconsole.log(\"ERROR: Local Storage not supported by browser!\")\n\t}\n}",
"function getUploadData() {\n var localData = JSON.parse(window.localStorage.getItem(\"advantagescout_scoutdata\"))\n for (var i = 0; i < localData.length; i++) {\n var fields = Object.keys(localData[i])\n for (var f = 0; f < fields.length; f++) {\n var value = localData[i][fields[f]]\n var fileName = String(value).split(\"/\").pop()\n if (imageCache[fileName] != undefined) {\n localData[i][fields[f]] = imageCache[fileName]\n }\n }\n }\n return [JSON.stringify(localData)]\n }",
"function loadTodos() {\n const ul = document.querySelector('.todoList');\n const todos = getTodosFromLocalStorage();\n\n for (const todo of todos) {\n const li = createTodoElement(todo);\n ul.append(li);\n }\n}",
"function pullFromStorage(){\r\n return JSON.parse(localStorage.getItem(\"todoitems\"))\r\n}",
"function getStocks(){\n return JSON.parse(localStorage.getItem(STOCK_STORAGE_NAME));\n}",
"function loadCalenedarLocal(){\n let loadedCalendar = JSON.parse(localStorage.getItem(calendarLocalKey));\n \n if (!loadedCalendar){\n return;\n }\n timeArr.length = 0;\n\n loadedCalendar.forEach(element => {\n timeArr.push(element);\n });\n}",
"function guardarCursoLocalStorage(curso){\n\t\tlet cursos;\n\t\t//toma el valor de un arreglo con datos de ls o vacio\n\t\tcursos = obtenerCursosLocalStorage();\n\t\t//el curso seleccionado se agrega el arreglo\t\n\t\tcursos.push(curso);\n\n\t\tlocalStorage.setItem('cursos', JSON.stringify(cursos));\n\n\t}",
"getSavedImagesFromLocalStorage() {\n this.savedImagesInLocalStorage = [];\n\n const partialStorageArray = this.getPartialStorageArray();\n\n if (partialStorageArray.length > 0) {\n const finalArray = [];\n partialStorageArray.forEach((jsonImageInfo) => {\n const imageInfo = JSON.parse(jsonImageInfo);\n finalArray.push(imageInfo);\n });\n\n this.savedImagesInLocalStorage = finalArray.reverse();\n }\n }",
"function Listar() {\n $(\"#tbCadastro\").html(\"\");\n $(\"#tbCadastro\").html(\n \"<thead>\" +\n \" <tr>\" +\n \" <th>CPF</th>\" +\n \" <th>Nome</th>\" +\n \" <th></th>\" +\n \" </tr>\" +\n \"</thead>\" +\n \"<tbody>\" +\n \"</tbody>\"\n );\n\t\tfor (var i in tbDados) {\n var cli = JSON.parse(tbDados[i]);\n var novaLinha = $(\"<tr>\");\n var cols = \"\";\n cols += \"<td>\" + cli.cpf + \"</td>\";\n cols += \"<td>\" + cli.nome + \"</td>\";\n cols += \"<td>\" +\n \" <img src='img/edit.png' alt='\" +\n i + \"' class='btnEditar'/>\" + \" \" +\n \"<img src='img/delete.png' alt='\" +\n i + \"' class='btnExcluir'/>\" + \"</td>\";\n novaLinha.append(cols);\n\t\t\t$(\"#tbCadastro\").append(novaLinha);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create Leaflet Map on index page | function createMap(myLatitude, myLongitude) {
// Leaflet Map on index page
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZW5qb3ltcmJhbiIsImEiOiJjam5hY3EwcDQwZ2hiM3BwYWQ2dWt4a2x1In0.nlX1GeaPE2DQn3aZH0IJaA', {
maxZoom: 18,
minZoom: 4,
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(map);
placeEventsOnMap();
//set map center after all events are placed
map.setView([myLatitude, myLongitude], endZoom);
} | [
"function createMap(){\n\n // Add place searchbar to map\n L.Control.openCageSearch(options).addTo(map);\n\n // Add zoom control (but in top right)\n L.control.zoom({\n position: 'topleft'\n }).addTo(map);\n\n // build easy bar from array of easy buttons\n L.easyBar(buttons).addTo(map);\n\n // Add easy button to pull up splash screen\n L.easyButton('<img src=\"img/noun_Info_1845673_blk.svg\">', function(){\n $('#splash-screen').modal('show');\n },'info window',{ position: 'topleft' }).addTo(map);\n\n //load tile layer\n L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {\n\t attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',\n }).addTo(map);\n\n L.control.attribution({\n position: 'bottomright'\n }).addTo(map);\n //call getData function\n getData(map);\n}",
"function createMap() {\n currentTerritory= viewerOptions.territory || 'FXX';\n // viewer creation of type <Geoportal.Viewer>\n // création du visualiseur du type <Geoportal.Viewer>\n // HTML div id, options\n territoriesViewer[currentTerritory]= new Geoportal.Viewer.Default('viewerDiv', OpenLayers.Util.extend(\n OpenLayers.Util.extend({}, viewerOptions),\n // API keys configuration variable set by\n // <Geoportal.GeoRMHandler.getConfig>\n // variable contenant la configuration des clefs API remplie par\n // <Geoportal.GeoRMHandler.getConfig>\n window.gGEOPORTALRIGHTSMANAGEMENT===undefined? {'apiKey':'nhf8wztv3m9wglcda6n6cbuf'} : gGEOPORTALRIGHTSMANAGEMENT)\n );\n if (!territoriesViewer[currentTerritory]) {\n // problem ...\n OpenLayers.Console.error(OpenLayers.i18n('new.instance.failed'));\n return;\n }\n\n territoriesViewer[currentTerritory].addGeoportalLayers([\n 'ORTHOIMAGERY.ORTHOPHOTOS',\n 'GEOGRAPHICALGRIDSYSTEMS.MAPS'],\n {\n });\n territoriesViewer[currentTerritory].getMap().setCenter(\n territoriesViewer[currentTerritory].viewerOptions.defaultCenter,\n territoriesViewer[currentTerritory].viewerOptions.defaultZoom);\n // cache la patience - hide loading image\n territoriesViewer[currentTerritory].div.style[OpenLayers.String.camelize('background-image')]= 'none';\n}",
"function displayMap(){\n var coordinates = infoForMap();\n createMap(coordinates);\n}",
"function initMap() {\n $('#widgetRealTimeMapliveMap .loadingPiwik, .RealTimeMap .loadingPiwik').hide();\n map.addLayer(currentMap.length == 3 ? 'context' : 'countries', {\n styles: {\n fill: colorTheme[currentTheme].fill,\n stroke: colorTheme[currentTheme].bg,\n 'stroke-width': 0.2\n },\n click: function (d, p, evt) {\n evt.stopPropagation();\n if (currentMap.length == 2){ // zoom to country\n updateMap(d.iso);\n } else if (currentMap != 'world') { // zoom out if zoomed in\n updateMap('world');\n } else { // or zoom to continent view otherwise\n updateMap(UserCountryMap.ISO3toCONT[d.iso]);\n }\n },\n title: function (d) {\n // return the country name for educational purpose\n return d.name;\n }\n });\n if (currentMap.length == 3){\n map.addLayer('regions', {\n styles: {\n stroke: colors['region-stroke-color']\n }\n });\n }\n var lastVisitId = -1,\n lastReport = [];\n refreshVisits(true);\n }",
"function load_map() {\n\tmap = new L.Map('map', {zoomControl: true});\n\n\t// from osmUrl we can change the looks of the map (make sure that any reference comes from open source data)\n\tvar osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n\t// var osmUrl = 'https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png',\n\t\tosmAttribution = 'Map data © 2012 <a href=\"http://openstreetmap.org\">OpenStreetMap</a> contributors',\n\t\tosm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});\n\n\n\t// define the center and zoom level when loading the page (zoom level 3 allows for a global view)\n\tmap.setView(new L.LatLng(20, 10), 3).addLayer(osm);\n\n\n\t$.ajax({\n\t\turl: 'js/doe.csv',\n\t\tdataType: 'text/plain',\n\t}).done(successFunction);\n\n\tfunction successFunction(data) {\n\t\tvar planes = data.split('/\\r?\\n|\\r/');\n\t\tconsole.log(planes);\n\n\t\t// for (var i = 0; i < planes.length; i++) {\n\t\t// \tvar markersplit = planes[i].split(',');\n\t\t// \tmarker = new L.marker([markersplit[3],markersplit[4]]).bindPopup(markersplit[0]).addTo(map);\n\t\t// }\n\n\t}\n\n\n\t// variable to allow to read the points from above and pass that to the marker rendering function\n\n\n\n\t// create layer with all the markers to turn on and off (maybe no need for this)\n\t// var overlayMaps = {\n\t// \t\"Cities\" : marker\n\t// }\n\t// L.control.layers(overlayMaps).addTo(map);\n\n\n}",
"function MapViewFactory() {}",
"function initMaps() {\n\n configKaartItems = dataFactoryMap.configKaartItems;\n var maxIndex = 0;\n loDash.each(configKaartItems, function (item) {\n if (maxIndex < item.index) {\n maxIndex = parseInt(item.index);\n }\n });\n //console.log('dataFactoryMap configKaartItems getConfig: ', configKaartItems);\n\n configKaartHedenItems = loDash.filter(configKaartItems, function (kaart) {\n return kaart.type === 'heden';\n });\n configKaartToekomstItems = loDash.filter(configKaartItems, function (kaart) {\n return kaart.type === 'toekomst';\n });\n configKaartVerledenItems = loDash.filter(configKaartItems, function (kaart) {\n return kaart.type === 'verleden';\n });\n configKaartThemaItems = loDash.filter(configKaartItems, function (kaart) {\n return kaart.type === 'thema';\n });\n\n L.TileLayer.cachedNietHeden = function (url, options) {\n return new L.TileLayer.boundaryCanvas(url, options);\n };\n\n L.TileLayer.cachedHeden = function (url, options) {\n return new L.TileLayer.CachedHeden(url, options);\n };\n\n //console.log('datafactoryMap InitMaps aantal kaarten gevonden: ', configKaartItems.length - configKaartThemaItems.length);\n\n var tmp = configKaartVerledenItems.concat(configKaartToekomstItems);\n configKaartNietHedenItems = tmp.concat(configKaartThemaItems);\n\n loDash.each(configKaartHedenItems, function (configKaartItem) {\n\n var http = configKaartItem.url.indexOf('http');\n if (http < 0) {\n configKaartItem.url = url + configKaartItem.url;\n }\n configKaartItem.url = configKaartItem.url.replace('.nl/trinl', '.nl');\n\n //console.log('datafactoryMap Heden configKaartItem url, attribute: ', configKaartItem.url);\n\n if (ionic.Platform.isAndroid() || ionic.Platform.isIOS()) {\n dataFactoryMap.map[configKaartItem.index] = L.TileLayer.cachedHeden(configKaartItem.url, {\n attribution: configKaartItem.attribute,\n edgeBufferTiles: 1,\n minZoom: 8,\n maxZoom: configKaartItem.maxZoom,\n minNativeZoom: 8,\n maxNativeZoom: configKaartItem.maxZoom,\n format: 'image/png',\n transparent: true,\n async: true,\n maxBounds: globalBounds,\n bounds: globalBounds,\n hostPath: configKaartItem.url,\n useCache: configKaartItem.useCache,\n cacheFolder: configKaartItem.cacheFolder,\n cacheMaxAge: configKaartItem.cacheMaxAge,\n crossOrigin: true,\n subdomeins: configKaartItem.subdomeins\n });\n } else {\n var tileSize = 256;\n var zoomOffset = 0;\n if (configKaartItem.url.indexOf('https://api.maptiler.com/') !== -1) {\n tileSize = 512;\n zoomOffset = -1;\n }\n dataFactoryMap.map[configKaartItem.index] = L.tileLayer(configKaartItem.url, {\n attribution: configKaartItem.attribute,\n edgeBufferTiles: 1,\n tileSize: tileSize,\n zoomOffset: zoomOffset,\n minZoom: 8,\n maxZoom: configKaartItem.maxZoom,\n minNativeZoom: 8,\n maxNativeZoom: configKaartItem.maxZoom,\n format: 'image/png',\n transparent: true,\n async: true,\n maxBounds: globalBounds,\n bounds: globalBounds,\n hostPath: configKaartItem.url,\n useCache: configKaartItem.useCache,\n cacheFolder: configKaartItem.cacheFolder,\n cacheMaxAge: configKaartItem.cacheMaxAge,\n crossOrigin: true,\n subdomeins: configKaartItem.subdomeins\n });\n\n }\n });\n\n loDash.each(configKaartNietHedenItems, function (configKaartItem) {\n var geom = dataFactoryGeom.limburgGeom;\n if (configKaartItem.naam === '1600') {\n geom = dataFactoryGeom.limburg1600Geom;\n }\n //console.log('datafactoryMap NietHeden naam, url, geom: ', configKaartItem.naam, configKaartItem.url, geom);\n\n var http = configKaartItem.url.indexOf('http');\n if (http < 0) {\n configKaartItem.url = url + configKaartItem.url;\n }\n configKaartItem.url = configKaartItem.url.replace('.nl/trinl', '.nl');\n\n\n if (ionic.Platform.isAndroid() || ionic.Platform.isIOS()) {\n //console.log('datafactoryMap cacheNietHeden url: ', configKaartItem.url);\n dataFactoryMap.map[configKaartItem.index] = new L.TileLayer.cachedNietHeden(configKaartItem.url, {\n attribution: configKaartItem.attribute,\n edgeBufferTiles: 1,\n boundary: geom,\n minZoom: 8,\n maxZoom: configKaartItem.maxZoom,\n maxNativeZoom: configKaartItem.maxZoom,\n minNativeZoom: 8,\n format: 'image/png',\n transparent: true,\n bounds: globalBounds,\n hostPath: configKaartItem.url,\n useCache: configKaartItem.useCache,\n cacheFolder: configKaartItem.cacheFolder,\n cacheMaxAge: configKaartItem.cacheMaxAge,\n crossOrigin: true\n });\n } else {\n //console.log('datafactoryMap boundaryCanvas url: ', configKaartItem.url);\n dataFactoryMap.map[configKaartItem.index] = new L.TileLayer.boundaryCanvas(configKaartItem.url, {\n attribution: configKaartItem.attribute,\n edgeBufferTiles: 1,\n boundary: geom,\n minZoom: 8,\n maxZoom: configKaartItem.maxZoom,\n maxNativeZoom: configKaartItem.maxZoom,\n minNativeZoom: 8,\n format: 'image/png',\n transparent: true,\n bounds: globalBounds,\n hostPath: configKaartItem.url,\n useCache: configKaartItem.useCache,\n cacheFolder: configKaartItem.cacheFolder,\n cacheMaxAge: configKaartItem.cacheMaxAge,\n crossOrigin: true\n });\n\n }\n });\n $timeout(() => {\n dataFactoryMap.ready = true;\n //console.error('emit MapsReady LocalStorage');\n $rootScope.$emit('MapsReady');\n }, 200);\n\n //console.log(dataFactoryMap.map);\n //if (!ionic.Platform.isAndroid() && !ionic.Platform.isIOS()) {\n //dataFactoryMap.ready = true;\n //console.log('emit MapsReady!!!');\n //$rootScope.$emit('MapsReady');\n }",
"function addMap()\n{\n\tgbox.addObject({\n\t\tid: 'background_id',\t// object ID\n\t\tgroup: 'background',\t// rendering group\n\n\t\tblit: function() {\n\t\t\t// Clear canvas\n\t\t\tgbox.blitFade(gbox.getBufferContext(), { alpha: 1 });\n\t\t\t\n\t\t\t// Draw tilemap canvas to screen\n\t\t\tgbox.blit(gbox.getBufferContext(), gbox.getCanvas('map_canvas'), \n\t\t\t\t{ \n\t\t\t\tdx: 0, \n\t\t\t\tdy: 0,\n\t\t\t\tdw: gbox.getCanvas('map_canvas').width,\n\t\t\t\tdh: gbox.getCanvas('map_canvas').height,\n\t\t\t\tsourcecamera: true\n\t\t\t\t});\n\t\t}\n\t});\n}",
"function initOpenLayersMap() {\r\n map = new OpenLayers.Map('map', mapInitParams);\r\n \r\n }",
"function initMap(){\n //create markersLayer cluster\n markersLayer = new MarkerCluster.MarkerClusterGroup({ \n iconCreateFunction: function(cluster) {\n return L.divIcon({\n html: \"<div class='vtr-map__marker-cluster'>\"+cluster.getChildCount()+\"</div>\", //html for the marker cluster icon\n iconAnchor: [24, 24],\n iconSize: [48, 48]\n });\n },\n spiderfyDistanceMultiplier: 2,\n showCoverageOnHover: false\n });\n\n //create openmaps layer\n var openMapsLayer = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiYW5kcmVqZXN1cyIsImEiOiJjajM0bTVrNHQwMXNyMzJxNmJ4N3Y0eXJsIn0.VhyneGbaY7fCC1xqcJGKDQ', {\n attribution: 'Map data © <a href=\"https://www.openstreetmap.org/\">OpenStreetMap</a> contributors, <a href=\"https://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"https://www.mapbox.com/\">Mapbox</a>',\n maxZoom: 18,\n id: 'mapbox.streets',\n accessToken: 'your.mapbox.access.token'\n });\n\n //create map instance\n mainMap = L.map('mainMap').setView([39.3599791, -9.3922809], 3);\n \n //add openmaps layer to map instance\n mainMap.addLayer(openMapsLayer);\n}",
"function createOpenStreetMap(L,mapid,overlayMaps) {\n var map=L.map(mapid)\n\n\tconst osmURL='https://tile.openstreetmap.org/{z}/{x}/{y}.png'\n osmLayer=L.tileLayer(osmURL,{maxZoom: 18,subdomains: [\"maps1\", \"maps2\", \"maps3\", \"maps4\"]}).addTo(map);\n\n L.control.layers({\"OSM\": osmLayer}, overlayMaps,{\"hideSingleBase\":true}).addTo(map);\n\n return map\n}",
"function PuplishMap(){}",
"function drawMap() {\n map = document.createElement(\"div\");\n var tiles = createTiles(gameData);\n for (var tile of tiles) {\n map.appendChild(tile);\n }\n document.body.appendChild(map);\n }",
"function createLayer(key) {\n undoLayer();\n var main = new L.tileLayer('https://api.tiles.mapbox.com/v4/k3nnythe13ed.1oe7h7kd/{z}/{x}/{y}.png?access_token=sk.eyJ1IjoiazNubnl0aGUxM2VkIiwiYSI6ImNpdXBramh1MjAwMWUyb3BrZGZpaHRhNmUifQ.SVIjk10IlrzAkWopvYzMtg',\n {\n attribution: 'Map data © <a href=\"http://openstreetmap.org\">OpenStreetMap</a> contributors, <a href=\"http://openseamap.org\">OpenSeaMap</a>, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>, Imagery © <a href=\"http://mapbox.com\">Mapbox</a>',\n maxZoom: 21,\n \n continuousWorld: false,\n noWrap: true\n })\n\nvar sea = new L.tileLayer('http://tiles.openseamap.org/seamark/{z}/{x}/{y}.png',\n {\n attribution: 'Map data © <a href=\"http://openseamap.org\">OpenSeaMap</a>',\n maxZoom: 21,\n\n continuousWorld: false,\n noWrap: true\n })\n if(key !== null)\n {\n var weather = new L.tileLayer('http://{s}.maps.owm.io/current/' + String(key) + '/{z}/{x}/{y}?appid=b1b15e88fa797225412429c1c50c122a1',\n {\n attribution: 'Map data © <a href=\"http://openweathermap.org\">OpenWeatherMap</a>',\n maxZoom: 9,\n \n opacity: 0.9,\n continuousWorld: false,\n noWrap: true\n \n })\n layers = L.layerGroup([main, weather, sea])\n }\n else{\n layers = L.layerGroup([main, sea])\n }\n map.addLayer(layers);\n}",
"init() {\n this.worldMap.parseMap();\n }",
"function generateMap() {\n\t\t$('#koi-deeplink-root').extractDeeplinkIdentifiers();\n\n\t\tvar initializing = true;\n\n\t\tmapGenerated = true;\n\t\t\n\t\t$.address.history(use_history);\n\n\t\t$.address.init(function (event) {\n\t\t\t$.address.change(function (event) {\n\t\t\t\tif (!initializing) {\n\t\t\t\t\t_.recover(event.value, event.parameters);\n\t\t\t\t}\n\t\t\t});\n\t\n\t\t\tif ($.address.value() === '/') {\n\t\t\t\tif (enableFirstChildAutomation) {\n\t\t\t\t\tfirstChildAutomation = true;\n\t\t\t\t\tprocessAutomation();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\ttriggerPathSet();\n\t\t\t} else {\n\t\t\t\t_.recover(event.value, event.parameters);\n\t\t\t}\n\t\t\t\n\t\t\tinitializing = false;\n\t\t});\n\t}",
"function mapa_crearMapa() {\n\tvar dominio = JSON.parse(localStorage.getItem('dominio'));\n\tvar usuario_zonas = JSON.parse(localStorage.getItem('usuario_zonas'));\n\tvar zonas_codigos = {};\n\tvar zonas_colores = {};\n\tg_lista_zonas = usuario_zonas;\n\tfor (var i = 0; i < usuario_zonas.length; i++) {\n\t\tvar zona_id = usuario_zonas[i].idzona;\n\t\tvar zona_nombre = usuario_zonas[i].nombre;\n\t\tvar zona_color_hex = usuario_zonas[i].color_hex;\n\t\tvar zonas_subzonas = usuario_zonas[i].subzonas;\n\t\tfor (var j = 0; j < zonas_subzonas.length; j++) {\n\t\t\tvar subzona_estado_codigo = zonas_subzonas[j].estado_codigo;\n\t\t\tvar subzona_estado_nombre = zonas_subzonas[j].estado_nombre;\n\t\t\tif (!zonas_codigos.hasOwnProperty(subzona_estado_codigo)) {\n\t\t\t\tvar subzona_estado_escuelas = zonas_subzonas[j].escuelas;\n\t\t\t\tvar subzona_estado_escuelas_total = zonas_subzonas[j].escuelas_total;\n\t\t\t\tzonas_codigos[subzona_estado_codigo] = zona_nombre;\n\t\t\t\tg_mapa_subzonas.push({\n\t\t\t\t\tzona_id: zona_id,\n\t\t\t\t\tzona_nombre: zona_nombre,\n\t\t\t\t\testado_codigo: subzona_estado_codigo,\n\t\t\t\t\testado_nombre: subzona_estado_nombre,\n\t\t\t\t\tescuelas: subzona_estado_escuelas,\n\t\t\t\t\tescuelas_total: subzona_estado_escuelas_total\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tzonas_colores[zona_nombre] = zona_color_hex;\n\t}\n\t$('#vmap').vectorMap({\n\t\tmap: 'mx_en',\n\t\tenableZoom: true,\n\t\tshowTooltip: true,\n\t\tbackgroundColor: '#a5bfdd',\n\t\tborderColor: '#818181',\n\t\tborderOpacity: 0.25,\n\t\tborderWidth: 1,\n\t\tcolor: '#f4f3f0',\n\t\thoverColor: '#c9dfaf',\n\t\thoverOpacity: null,\n\t\tnormalizeFunction: 'polynomial',\n\t\tscaleColors: ['#b6d6ff', '#005ace'],\n\t\tselectedColor: '#c9dfaf',\n\t\tregionsSelectable: true,\n\t\tregionsSelectableOne: true,\n\t\tregionStyle: {\n\t\t\tinitial: {\n\t\t\t\tfill: '#eee',\n\t\t\t\t'fill-opacity': 1,\n\t\t\t\tstroke: 'black',\n\t\t\t\t'stroke-width': 0.5,\n\t\t\t\t'stroke-opacity': 1\n\t\t\t},\n\t\t\thover: {\n\t\t\t\tfill: '#000000',\n\t\t\t\t'fill-opacity': 0.5,\n\t\t\t\tcursor: 'pointer'\n\t\t\t},\n\t\t\tselected: {\n\t\t\t\tfill: '#3333'\n\t\t\t},\n\t\t\tselectedHover: {}\n\t\t},\n\t\tregionLabelStyle: {\n\t\t\tinitial: {\n\t\t\t\t'font-family': 'Verdana',\n\t\t\t\t'font-size': '12',\n\t\t\t\t'font-weight': 'bold',\n\t\t\t\tcursor: 'default',\n\t\t\t\tfill: 'black'\n\t\t\t},\n\t\t\thover: {\n\t\t\t\tcursor: 'pointer'\n\t\t\t}\n\t\t},\n\t\tseries: {\n\t\t\tregions: [{\n\t\t\t\tvalues: zonas_codigos,\n\t\t\t\tscale: zonas_colores,\n\t\t\t\tnormalizeFunction: 'polynomial'\n\t\t\t}]\n\t\t},\n\t\tonRegionSelected: function(element, code, region, isSelected) {\n\t\t\tif (g_mapa_interacciones == true) {\n\t\t\t\tvar regiones = $('#vmap').vectorMap('get', 'mapObject').getSelectedRegions();\n\t\t\t\tif (regiones.length === 1) {\n\t\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\t\tregion: code,\n\t\t\t\t\t\tanimate: true\n\t\t\t\t\t});\n\t\t\t\t\tvar subzona = obtenerObjectoEnArreglo(g_mapa_subzonas, 'estado_codigo', code);\n\t\t\t\t\tvar zona = obtenerObjectoEnArreglo(g_lista_zonas, 'idzona', subzona.zona_id);\n\t\t\t\t\tg_mapa_zona_seleccionada_id = zona.idzona;\n\t\t\t\t\tg_mapa_subzona_seleccionada_id = subzona.estado_codigo;\n\t\t\t\t\tmapa_cargarSelectZonasSubzonasDesdeMapa(g_mapa_zona_seleccionada_id, g_mapa_subzona_seleccionada_id, true);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tonRegionTipShow: function(e, el, code) {\n\t\t\t/*var zona = zonas_codigos[code];\n\t\t\tif (zona !== undefined) {\n\t\t\t var subzona = obtenerObjectoEnArreglo(g_mapa_subzonas, 'estado_codigo', code);\n\t\t\t var subzona_escuelas_total = subzona.escuelas_total;\n\t\t\t el.html(zona + ' • ' + el.html() + ' • ' + subzona_escuelas_total + ' escuelas');\n\t\t\t} else {\n\t\t\t el.html('¡No hay escuelas de ' + dominio + ' en ' + el.html() + '!');\n\t\t\t}*/\n\t\t\tel.html('');\n\t\t}\n\t});\n}",
"function mapSetup()\n{\n mapInit[\"lat\"] = 51.0;\n mapInit[\"lon\"] = -114.0;\n mapInit[\"zoom\"] = 11;\n return mapInit;\n}",
"function mapLoad() {\n\n // define starting center of map as center of contiguous US\n var center = new google.maps.LatLng(39.828182,-98.579144);\n\n // define map options to show roughly entire US\n var mapOptions = {\n zoom: 4,\n center: center\n }\n\n // create new map\n map = new google.maps.Map($('#map-canvas')[0], mapOptions);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get flow From flowCollector Server | function getFlows (socket) {
return (data) => {
UDPServer.send(JSON.stringify({ event : 'GET_FLOWS_MONITOR', data : [] }), 6000, '127.0.0.1')
}
} | [
"function getRemoteCollector (name, host) {\n\tvar col=host + \"-\" + name;\n\tif (!remoteList) remoteList = [];\n\tif (!remoteList[col]) {\n\t\tvar RC = require('../class/RemoteCollector');\n\t\tremoteList[col] = new RC(name, host);\n\t}\n\treturn remoteList[col];\n}",
"function __getFlow (fullUri) {\n\t// defaults to static if scheme not specified\n\tconst normalisedUri = this.__normaliseFlowUri(fullUri);\n\tconst baseUri = this.__getBaseFlowUri(normalisedUri);\n\tif (this.flows[baseUri]) {\n\t\treturn this.flows[baseUri];\n\t}\n\telse { // not found, try the same as a dynamic flow\n\t\tconst dynamicUri = this.__normaliseFlowUri(fullUri, true);\n\t\tconst dynamicBaseUri = this.__getBaseFlowUri(dynamicUri);\n\t\tif (this.flows[dynamicBaseUri]) {\n\t\t\treturn this.flows[dynamicBaseUri];\n\t\t}\n\t\telse { // still not found, try canonical URI\n\t\t\tconst matchingFlows = Object.values(this.flows)\n\t\t\t\t.filter(flow => flow.definition.canonicalUri &&\n flow.definition.canonicalUri === dynamicBaseUri);\n\t\t\treturn matchingFlows.length ? matchingFlows[0] : null;\n\t\t}\n\t}\n}",
"function __getDynamicFlows () {\n\treturn Object.values(this.flows).filter(flow => flow.type === `dynamic`);\n}",
"findById(id) {\n return request.get(`/api/flows/${id}`);\n }",
"function getDialogflowSenderID() {\n var array = request.body.queryResult.outputContexts;\n if (array.length > 2) {\n return request.body.queryResult.outputContexts[1].parameters.facebook_sender_id;\n } else {\n return request.body.queryResult.outputContexts[0].parameters.facebook_sender_id;\n }\n }",
"addCollector(){\r\n if(this.collectorPool.length<2){\r\n let worker = new FatusCollectorWorker(this);\r\n this.initWorker(worker);\r\n worker.setStackProtection(3);\r\n this.collectorPool.push(worker);\r\n worker.run();\r\n }\r\n }",
"get() {\n return this._channel && this._channel.get.apply(this._channel, arguments);\n }",
"get_captureType()\n {\n return this.liveFunc._captureType;\n }",
"function initFlow() {\n return {\n chunkSize: 104857600, // 100mb\n target: config.REST_URL + '/publish/email/mensagem/upload',\n //target: 'http://localhost:8500/rest/seeaway-app/contabil/upload',\n query: {\n type: 'contabil-upload'\n }\n };\n }",
"get_captureTypeAtStartup()\n {\n return this.liveFunc._captureTypeAtStartup;\n }",
"function getFlowsFromFiles(callback) {\n var dir = settings.userDir;\n fs.readdir(dir, function (err, results) {\n if (err) {\n return callback(err, null);\n }\n var files = results.filter(function (file) {\n return (file.startsWith('red_') && path.extname(file) === '.json');\n });\n\n async.concat(files, function (file, cb) {\n fs.readFile(path.join(dir, file), function (err, contents) {\n if (err) {\n return cb({ error: 'Internal server error', message: 'No nodered flows found' });\n }\n cb(null, JSON.parse(contents));\n });\n }, function (err, flowArray) {\n if (err) {\n return callback(err);\n }\n return callback(null, { flows: _.sortBy(flowArray, 'order') });\n });\n });\n }",
"constructor() { \n \n FlowLog.initialize(this);\n }",
"stream() {\n this.log.trace(\"DfuseBlockStreamer.stream()\");\n if (!this.apolloClient) {\n this.apolloClient = this.getApolloClient();\n }\n this.getObservableSubscription({\n apolloClient: this.apolloClient\n }).subscribe({\n start: () => {\n this.log.trace(\"DfuseBlockStreamer GraphQL subscription started\");\n },\n next: (value) => {\n this.onTransactionReceived(value.data.searchTransactionsForward);\n },\n error: (error) => {\n // TODO should we be doing anything else?\n this.log.error(\"DfuseBlockStreamer GraphQL subscription error\", error.message);\n },\n complete: () => {\n // TODO: how to handle completion? Will we ever reach completion?\n this.log.error(\"DfuseBlockStreamer GraphQL subscription completed\");\n }\n });\n }",
"function currentStream(callback) {\n chrome.storage.sync.get(\"streamSource\", function(result){\n saved = result.streamSource;\n document.getElementById(\"currentStream\").innerHTML = \"Current Stream: \" + saved;\n });\n}",
"function request_getStoredLink() {\n\tconsole.log(\"request_getStoredLink() called\");\n\tport.postMessage({\n\t\ttype: 'functionRequest',\n\t\tfunctionSignature: 'getStoredLink',\n\t\tfunctionArguments: {}\n\t});\n}",
"getStream() {\n if (this.mediaStream !== null && (typeof (this.mediaStream) !== null) && this.mediaStream !== undefined) { return this.mediaStream; }\n return null;\n }",
"function onP2PstreamRequest(evt) { \n util.trace('DataChannel opened');\n var chan = evt.channel;\n chan.binaryType = 'arraybuffer';\n var trackWanted = chan.label;\n var cancellable;\n\n chan.onmessage = apply(function(evt) {\n util.trace('Receiving P2P stream request');\n var req = JSON.parse(evt.data);\n if (cancellable) {\n // cancelling previous sending\n clearInterval(cancellable);\n } else {\n S.nbCurrentLeechers += 1;\n }\n var chunkI = req.from;\n\n function sendProgressively() {\n // goal rate: 75 kb/s\n for(var i = 0; chunkI < S.track.length && i < 150; i++) {\n var chunkNum = new Uint32Array(1);\n chunkNum[0] = chunkI;\n var chunkNumInt8 = new Uint8Array(chunkNum.buffer);\n var chunk = util.UInt8concat(chunkNumInt8, new Uint8Array(S.track[chunkI])).buffer;\n var b64encoded = base64.encode(chunk);\n chan.send(b64encoded);\n chunkI++;\n }\n if (chunkI >= S.track.length) {\n clearInterval(cancellable);\n cancellable = null;\n S.nbCurrentLeechers -= 1;\n }\n }\n sendProgressively();\n cancellable = setInterval(apply(sendProgressively), 1000);\n });\n\n chan.onclose = apply(function() {\n util.trace('datachannel closed');\n S.nbCurrentLeechers -= 1;\n });\n\n }",
"function collectstorm(){\n var URL = 'http://138.197.175.19:3000/stats_dfs';\n\n request.get(URL, function(err, resp, body){\n if(!err && resp.statusCode == 200){\n //convert data to json\n var data = JSON.parse(body);\n stormdata.push(data);\n }\n })\n //console.log(stormdata);\n}",
"createPipe(addr) {\n const pipeProps = {\n onNotified: (action) => {\n if (__IS_SERVER__ && action.type === SOCKET_CONNECT_TO_DST) {\n const [addr, callback] = action.payload;\n return this.connect(addr, () => {\n this._isHandshakeDone = true;\n callback();\n });\n }\n if (action.type === PROCESSING_FAILED) {\n return this.onPresetFailed(action);\n }\n }\n };\n this._pipe = new Pipe(pipeProps);\n this._pipe.setMiddlewares(MIDDLEWARE_DIRECTION_UPWARD, [\n createMiddleware(MIDDLEWARE_TYPE_FRAME, [addr]),\n createMiddleware(MIDDLEWARE_TYPE_CRYPTO),\n createMiddleware(MIDDLEWARE_TYPE_PROTOCOL),\n createMiddleware(MIDDLEWARE_TYPE_OBFS),\n ]);\n this._pipe.on(`next_${MIDDLEWARE_DIRECTION_UPWARD}`, (buf) => this.send(buf, __IS_CLIENT__));\n this._pipe.on(`next_${MIDDLEWARE_DIRECTION_DOWNWARD}`, (buf) => this.send(buf, __IS_SERVER__));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
play a sound via Web Audio API (external dependencies: vars masterGain, playbackVolume; input: stream ArrayBuffer (Uint8Array), relVolume: Number 0..1, callback: function) | function playWebSound(stream, volume, callback, id) {
try {
var source, gainNode, timer, relVolume;
if (!audioContext) audioContext = new AudioAPI();
if (!masterGain) {
masterGain = (audioContext.createGain) ? audioContext.createGain() : audioContext.createGainNode();
masterGain.connect(audioContext.destination);
masterGain.gain.value = playbackVolume;
}
source = audioContext.createBufferSource();
relVolume = parseFloat(volume);
if (relVolume === undefined || isNaN(relVolume) || relVolume < 0 || relVolume > 1) relVolume = 1;
gainNode = (audioContext.createGain) ? audioContext.createGain() : audioContext.createGainNode();
gainNode.connect(masterGain);
gainNode.gain.value = relVolume;
source.connect(gainNode);
audioContext.decodeAudioData(stream, function(audioData) {
var f = function() {
webSoundEndHandler(source, gainNode, callback, true, id.string);
};
if (!isChrome && source.onended !== undefined) {
source.onended = f;
} else {
var duration = audioData.duration;
setTimeout(f, duration ? Math.ceil(duration * 1000) : 10);
}
source.buffer = audioData;
if (chromeVersion >= 32 && source.start) source.start(0);
},
function(err) {
console.log('meSpeak: Web Audio Decoding Error: ' + ((typeof err == 'object') ? err.message : err));
if (timer) clearTimeout(timer);
if (source) source.disconnect();
if (gainNode) gainNode.disconnect();
if (webSoundPool[id.string]) delete webSoundPool[id.string];
if (!unloading && typeof callback == 'function') callback(false);
return 0;
});
webSoundPool[id.string] = {
'source': source,
'gainNode': gainNode,
'callback': callback,
'id': id.string,
'relVolume': relVolume
};
if (chromeVersion < 32) {
if (source.start) {
source.start(0);
} else {
source.noteOn(0);
}
}
return id.number;
} catch (e) {
console.warn('meSpeak: Web Audio Exception: ' + e.message);
if (timer) clearTimeout(timer);
webSoundEndHandler(source, gainNode, callback, false, id.string);
return 0;
}
} | [
"function playsound() {\r\n audio1.play();\r\n }",
"playSample(name)\n {\n if(name in this.bufferLookup)\n {\n let player = this.audio_context.createBufferSource();\n player.buffer = this.bufferLookup[name];\n player.loop = false;\n player.connect(this.masterVolume);\n player.start(this.audio_context.currentTime);\n }\n }",
"function initAudio() {\n\n // Default values for the parameters\n AudBuffSiz = 4096;\n AudAmplify = 0.02;\n AudAmpScale = 0.8; // 1.3 is good to emphasise \"peakiness\", 0.5 good to \"smooth\" the sounds out a bit\n AudMinFreq = 30.0; // In Hz\n AudMaxFreq = 900.0;\n\n AudioCtx = new AudioContext();\n GainNode = AudioCtx.createGain();\n //GainNode.connect(AudioCtx.destination);\n //GainNode.gain.value = 1;\n AudSampleRate = AudioCtx.sampleRate;\n AudioBuffer = AudioCtx.createBuffer(1, AudBuffSiz, AudSampleRate);\n\n PlayingSpec = -1;\n\n}",
"function playAudio(sound,distance,channel)\n{\n\tvar playSound;\n\tswitch (channel)\n\t{\n\t\tcase 1:\n\t\t\tplaySound = document.getElementById(\"channelOne\");\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tplaySound = document.getElementById(\"channelTwo\");\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn;\n\t}\n\t// First stop the old audio if one is playing.\n\tplaySound.pause();\n\tplaySound.currentTime = 0;\n\t// Set the new audio.\n\tplaySound.src = sound;\n\tplaySound.load();\n\t// Audio directly atop the player (distance 0) plays at 100% volume. Anything quieter plays at 25% less for every 1 distance between the player and the source.\n\t// As the result of this, any sound 4 rooms or further away is just silent.\n\tvar volume = 1 - (distance * 0.25);\n\t// The audio doesn't play if it would be silent.\n\tif (volume > 0)\n\t{\n\t\tplaySound.volume = volume;\n\t\tplaySound.play();\n\t}\n}",
"function WebGLSound() {}",
"function playSound(id) {\n sounds[id].play();\n}",
"function playAudio(filename){\n\tif (soundEnabled) {\n\t\tvar audio = new Audio(\"audio/\" + filename) ;\n\t\taudio.play();\n\t}\n}",
"function loadAudio (playerId, source) {\n var player = document.getElementById(playerId);\n var request = new XMLHttpRequest();\n request.onreadystatechange = function() {\n console.log('readyState: ' + request.readyState + ', status: ' + request.status)\n if (this.readyState == 4 && this.status >= 200) {\n var url = URL.createObjectURL(request.response);\n player.src = url;\n player.addEventListener('loaded', function(e) {\n URL.revokeObjectURL(player.src);\n });\n // player.play();\n console.log('should be able to play...');\n console.log(url);\n // Typical action to be performed when the document is ready:\n }\n };\n request.open(\"GET\", source, true);\n // request.setRequestHeader(\"Range\", \"bytes=0-10000\");\n request.responseType = 'blob';\n request.send();\n}",
"function soundEffectSuccessFun() {\n soundEffectSuccess.play();\n}",
"function play(alias) {\n var soundInstance = getSoundByAlias(alias);\n soundInstance.playSound();\n }",
"function playSound(sound) {\n if ($('#sound').is(':checked') === true) { //Check if the checkbox 'sound' is checked by the player\n sound.play (); //If so, you can play sounds :). Each sound that needs to be played will trigger this function\n }\n }",
"function playHadouken () {\n\t\t$('#hadouken-sound')[0].volume = 0.5;\n\t\t$('#hadouken-sound')[0].load();\n\t\t$('#hadouken-sound')[0].play();\n\t\t\n}",
"audioPlayer(\n audio = false,\n currentTrack = 0,\n skipAutoPlay = true,\n autoPlay = false\n ){\n\n // set default settings\n this.frequencyBarsEnable = null,\n this.oscilloscopeEnable = null,\n this.infoEnable = null,\n this.trackDuration = 0,\n this.currentPosition = 0,\n this.position = 0,\n this.startTime = 0,\n this.audioInit = false,\n this.audioEnd = false,\n this.resume = false,\n this.playing = false,\n this.currentTrack = currentTrack,\n this.skipAutoPlay = skipAutoPlay,\n this.autoPlay = autoPlay,\n this.audioRaw = audio;\n\n try {\n // Fix up prefixing\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n this.context = new AudioContext();\n }\n catch(e) {\n alert('Web Audio API is not supported in this browser');\n }\n\n var audioInfo;\n var audioCount;\n\n if(audio){\n this.audioPlay = document.querySelector(this.selectorClass);\n audioInfo = JSON.parse(audio);\n audioCount = audioInfo.tracks.length;\n this.audioInfo = audioInfo;\n } else if (this.audio) {\n this.audioPlay = document.querySelector(this.selectorClass);\n audioInfo = JSON.parse(this.audio);\n audioCount = audioInfo.tracks.length;\n this.audioInfo = audioInfo;\n }\n\n this.tracks = audioInfo.tracks.length;\n this.tracks--;\n this.playButton = this.audioPlay.querySelector('button.play');\n this.audioPosition = this.audioPlay.querySelector('.audio-position input[type=range]');\n\n this.gainNode = this.context.createGain();\n\n if (this.audioPlay.querySelector('.oscilloscope')){\n this.audioOscilloscope(this);\n }\n\n if (this.audioPlay.querySelector('.frequency-bars')){\n this.audioFrequencyBars(this);\n }\n\n if (this.audioPlay.querySelector('.audio-info')){\n this.audioInformation(this);\n }\n\n if(this.audioPlay.querySelector('button.stop')){\n this.stopButton = this.audioPlay.querySelector('button.stop');\n this.stopButton.onclick = () => this.stopAudio(true);\n }\n\n if(this.audioPlay.querySelector('button.next')){\n this.nextButton = this.audioPlay.querySelector('button.next');\n if(this.currentTrack == this.tracks){\n this.nextButton.classList.add(\"disabled\");\n this.nextButton.disabled = true;\n }\n if(this.currentTrack < this.tracks){\n this.nextButton.classList.remove(\"disabled\");\n this.nextButton.disabled = false;\n this.nextButton.onclick = () => this.nextAudio();\n }\n }\n\n if(this.audioPlay.querySelector('button.prev')){\n this.prevButton = this.audioPlay.querySelector('button.prev');\n if(this.currentTrack == 0){\n this.prevButton.classList.add(\"disabled\");\n this.prevButton.disabled = true;\n }\n if(this.currentTrack > 0){\n this.prevButton.classList.remove(\"disabled\");\n this.prevButton.disabled = false;\n this.prevButton.onclick = () => this.prevAudio();\n }\n }\n\n if(this.audioPlay.querySelector('div.volume')){\n this.volWrap = this.audioPlay.querySelector('.volume');\n this.volButton = this.audioPlay.querySelector('.volume > a');\n this.volDrop = this.audioPlay.querySelector('.volume > .dropdown-content');\n this.volInput = this.audioPlay.querySelector('.volume > .dropdown-content > li > .range-field > input');\n\n if(this.getCookie('mxvol')){\n this.volInput.value = this.getCookie('mxvol');\n this.gainNode.gain.value = this.getCookie('mxvol');\n } else {\n this.volInput.value = 1;\n this.gainNode.gain.value = 1;\n }\n\n this.volButton.onclick = () => {\n this.volDrop.classList.toggle(\"active\");\n };\n\n /**\n *\n * Detect Volume Range Change and set gainNode\n *\n */\n this.volInput.addEventListener('input', function(event){\n thisMedia.gainNode.gain.value = this.value;\n var currGain = thisMedia.gainNode.gain.value;\n thisMedia.gainNode.gain.setValueAtTime(currGain, thisMedia.context.currentTime + 1);\n thisMedia.setCookie('mxvol',this.value,1);\n }, true);\n\n document.addEventListener('click', (event) => {\n if(this.volDrop.classList.contains(\"active\")) {\n this.volDrop.classList.remove(\"active\");\n }\n }, true);\n\n }\n\n\n\n\n this.context.ended = this.endedAudio();\n\n this.playButton.onclick = () => this.playAudio(this.oAnalyser,this.fAnalyser,0);\n\n if(this.autoPlay){\n this.playButton.className = this.playButton.className.replace(/\\bplay\\b/g, \"pause\");\n this.pauseButton = this.audioPlay.querySelector('button.pause');\n if(this.audioPlay.querySelector('button.pause i').innerHTML !== \"pause\"){\n this.audioPlay.querySelector('button.pause i').innerHTML = \"pause\";\n }\n this.playAudio(this.oAnalyser,this.fAnalyser,0);\n this.pauseButton.onclick = () => this.pauseAudio();\n }\n\n if(this.audioPlay.querySelector('.audio-cover')){\n var activeCover;\n currentTrack = this.currentTrack;\n activeCover = this.audioPlay.querySelector('.track-' + currentTrack);\n getAverageColor(activeCover.src).then(rgb => {\n this.audioPlay.querySelector('.audio-cover').style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')';\n }) // { r: 66, g: 83, b: 25 }\n $(document).ready(function(){\n $('.covers').carousel('set', currentTrack);\n });\n }\n\n if(this.audioPlay.querySelector('div.audio-playlist')){\n this.audioPlay.querySelector('div.audio-playlist').innerHTML = '<table class=\"bordered centered highlight playlist-table\"><tbody></tbody></table>';\n var playlist,\n playliPre = '',\n playliCover,\n trackselector;\n this.audioPlay.querySelector('table.playlist-table tbody').innerHTML = '';\n for (var i = 0; i < audioInfo.tracks.length; i++) {\n if(i == this.currentTrack){\n playlist = '<tr><td><button id=\"track-' + i + '\" data-id=\"' + i + '\" class=\"waves-light btn-floating playlist-play disabled\"><i class=\"material-icons\">equalizer</i></button></td><td>' + audioInfo.tracks[i].title + '</td><td>' + audioInfo.tracks[i].artist + '</td><td>' + audioInfo.tracks[i].album + '</td></tr>';\n } else {\n playlist = '<tr><td><button id=\"track-' + i + '\" data-id=\"' + i + '\" class=\"waves-light btn-floating playlist-play\"><i class=\"material-icons\">play_arrow</i></button></td><td>' + audioInfo.tracks[i].title + '</td><td>' + audioInfo.tracks[i].artist + '</td><td>' + audioInfo.tracks[i].album + '</td></tr>';\n }\n this.audioPlay.querySelector('table.playlist-table tbody').insertAdjacentHTML('beforeend', playlist);\n }\n\n var playlistPlay = this.audioPlay.querySelectorAll(\".playlist-play\"),t;\n playlistPlay.forEach(function(element) {\n t = element.dataset.id;\n element.addEventListener('click', function(event){\n thisMedia.setTrack(this.dataset.id);\n }, true);\n });\n }\n\n var thisMedia = this;\n\n /**\n *\n * Detect Audio Range input and set position\n *\n */\n this.audioPosition.addEventListener('input', function(event){\n var thisTime = this.value;\n if(thisMedia.playing){\n thisMedia.stopAudio(false);\n thisMedia.audioEnd = true;\n thisMedia.audioPlayer(thisMedia.audioRaw,thisMedia.currentTrack);\n setTimeout(function(){\n thisMedia.playAudio(thisMedia.oAnalyser,thisMedia.fAnalyser,thisTime);\n thisMedia.currentPosition = thisTime;\n },100);\n }\n }, true);\n\n }",
"function tphAudioAbspielen(file) {\r\n console.log(file);\r\n audio = new Media(file, function() { // success callback\r\n console.log(\"playAudio():Audio Success\");\r\n }, function(error) { // error callback\r\n //alert('code: ' + error.code + '\\n' +\r\n // 'message: ' + error.message + '\\n');\r\n });\r\n // get audio duration\r\n var duration = audio.getDuration();\r\n // Abspielen der Audio-Datei\r\n audio.play();\r\n audio.seekTo(pausePos * 1000);\r\n // Update aktuelle Position der Wiedergabe\r\n if (audioTimer === null) {\r\n audioTimer = setInterval(function() {\r\n // get audio position\r\n audio.getCurrentPosition(\r\n function(position) { // get position success\r\n if (position > -1) {\r\n console.log('Position: ' + position);\r\n }\r\n }, function(e) { // get position error\r\n console.log(\"Error getting pos=\" + e);\r\n //setAudioPosition(duration);\r\n }\r\n );\r\n }, 1000);\r\n }\r\n}",
"function playOnPlayersChange() {\n beepSound.play();\n}",
"function updateSound() {\n maxCheck();\n var soundLevel = AudioHandler.getLevel();\n if (soundLevel > 0.1) {\n inflate(soundLevel);\n } else {\n deflate();\n }\n requestAnimationFrame(updateSound);\n}",
"function playButtonSound() { \nsound.src = 'music/click.mp3'\nsound.play() }",
"function to_audio(url) {\n return T(\"audio\").loadthis(url, function() {\n console.log(\"Done loading \" + url);\n }, function() {\n console.log(\"Failed to load \" + url);\n });\n}",
"function playSound(squareNum){\n var snd = new Audio(game.sounds[squareNum - 1]);\n snd.play();\n}",
"function startAudioOnMaster() {\n let masterAudioMessage = JSON.stringify({\n client_type: EWSClientType.MASTER,\n message: EWSMessageType.START_AUDIO,\n raspberry_pi_id: 1,\n payload: 'ada4f2fd-1a6e-4688-bbf9-e20aadda5435'\n });\n\n client.send(masterAudioMessage, function (err){\n if(err) {\n setTimeout(() => {\n startAudioOnMaster()\n }, 500);\n }\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get an option from argv or config before program.parse | function preParseOption(l, s, argv) {
// look for the option in argv covering when it's `--opt=foobar`
var i = argv.indexOf(l);
if (i === -1) i = argv.indexOf(s);
// maybe it's come in --argument=value style
if (i === -1) {
for (var ii = 0; ii < argv.length; ii++) {
// --long=value
i = argv[ii].indexOf(l + '=');
if (i !== -1) return argv[ii].substr(argv[ii].indexOf(l + '='));
// -s=value
i = argv[ii].indexOf(s + '=');
if (i !== -1) return argv[ii].substr(argv[ii].indexOf(s + '='));
}
}
// no dice
if (i === -1) return false;
// return the argument if there is one
if (argv[i + 1] && argv[i + 1][0] !== '-') return argv[i + 1];
// otherwise true for finding it at all
return true;
} | [
"function handle_options(optionsArray) {\n var programName = [];\n var currentItem = optionsArray.shift();\n var defaults = amberc.createDefaultConfiguration();\n\n while (currentItem != null) {\n switch (currentItem) {\n case '-C':\n defaults.configFile = optionsArray.shift();\n break;\n case '-p':\n optionsArray.shift.split(',').forEach(function (pairString) {\n var mapping = pairString.split(':');\n defaults.paths[mapping[0]] = mapping[1];\n });\n break;\n case '-l':\n defaults.load.push.apply(defaults.load, optionsArray.shift().split(','));\n break;\n case '-g':\n defaults.jsGlobals.push.apply(defaults.jsGlobals, optionsArray.shift().split(','));\n break;\n case '-n':\n defaults.amdNamespace = optionsArray.shift();\n break;\n case '-D':\n defaults.outputDir = optionsArray.shift();\n break;\n case '-d':\n amber_dir = path.normalize(optionsArray.shift());\n break;\n case '-v':\n defaults.verbose = true;\n break;\n case '-h':\n case '--help':\n case '?':\n case '-?':\n print_usage_and_exit();\n break;\n default:\n defaults.stFiles.push(currentItem);\n break;\n }\n currentItem = optionsArray.shift();\n }\n\n if (1 < programName.length) {\n throw new Error('More than one name for ProgramName given: ' + programName);\n } else {\n defaults.program = programName[0];\n }\n return defaults;\n}",
"function getFlagValueFromArgv(name) {\n for (let i = 0; i < process.argv.length; i++) {\n let list = process.argv[i].split(\"=\");\n if (list[0] === `--${name}`)\n return list[1];\n }\n\n return undefined;\n}",
"function setConfig (argv) {\n var configLookup = {}\n \n // expand defaults/aliases, in-case any happen to reference\n // the config.json file.\n applyDefaultsAndAliases(configLookup, aliases, defaults)\n \n Object.keys(flags.configs).forEach(function (configKey) {\n var configPath = argv[configKey] || configLookup[configKey]\n if (configPath) {\n try {\n var config = require(path.resolve(process.cwd(), configPath))\n \n Object.keys(config).forEach(function (key) {\n // setting arguments via CLI takes precedence over\n // values within the config file.\n if (argv[key] === undefined) {\n delete argv[key]\n setArg(key, config[key])\n }\n })\n } catch (ex) {\n if (argv[configKey]) error = Error('invalid json config file: ' + configPath)\n }\n }\n })\n }",
"function getopt (pat, opts, argv) {\n var arg, i = 0, $, arg, opt, l, alts, given = {};\n pat.replace(/--([^-]+)@/, function ($1, verbose) { opts[verbose] = [] });\n while (!(i >= argv.length || (argv[i] == \"--\" && argv.shift()) || !/^--?[^-]/.test(argv[i]))) {\n arg = argv.shift();\n arg = /^(--[^=]+)=(.*)$/.exec(arg) || /^(-[^-])(.+)$/.exec(arg) || [false, arg, true];\n alts = pat.replace(new RegExp(regular(arg[1]), 'g'), '').replace(/-[^,],--[^|]+\\|/g, '').split(\"|\");\n if ((l = alts.length - 1) != 1) abend(l ? \"ambiguous argument\" : \"unknown argument\", arg[1]);\n opt = (arg[1] + /,([^:@]*)/.exec(alts[0])[1]).replace(/^(-[^-]+)?--/, '').replace(/-/g, '');\n $ = /([:@])(.)$/.exec(alts[0]);\n if ($[2] != '!') {\n if ($[1].length == 1 || (argv.length && argv[0][0] != \"-\")) {\n if (!arg[0]) {\n if (!argv.length) abend(\"missing argument\", arg[1][1] != \"-\" ? arg[1] : \"--\" + opt);\n arg[2] = argv.shift();\n }\n if ($[2] == '#' && isNaN(arg[2] = parseFloat(arg[2]))) abend(\"numeric argument\", \"--\" + opt);\n }\n } else if (arg[0]) {\n if (arg[1][1] != \"-\") {\n argv.unshift(\"-\" + arg[2]);\n } else {\n abend(\"toggle argument\", arg[1][1] != \"-\" ? arg[1] : \"--\" + opt);\n }\n }\n given[opt] = true;\n if ($[1] == '@') opts[opt].push(arg[2]);\n else if (opts[opt] != null) abend(\"scalar argument\", arg[1]);\n else opts[opt] = arg[2];\n }\n return Object.keys(given);\n}",
"function parseArgs() {\n const pkg = require('../../package.json');\n\n config\n .usage('[options] <file ...>')\n .description('Send a file to all devices on a serial bus.')\n .version(pkg.version)\n .option('-l, --list', 'List all serial devices')\n .option('-b, --baud <number>', 'Baud rate to the serial device', parseInt)\n .option('-c, --command <number>', 'The Disco Bus message command that puts the devices into the bootloader.')\n .option('-d, --device <name>', 'The serial device to connect to')\n .option('-s, --page-size <number>', 'The programming page size for your device.', parseInt)\n .option('-p, --prog-version <maj.min>', 'The major.minor version of your program (for example 1.5)')\n .option('-t, --timeout <number>', 'How long to wait for devices to be ready for programming')\n .option('<file ...>', 'The file to program to your devices')\n .parse(process.argv);\n}",
"function handleCommandLineArgs (argv) {\n if (!argv || !argv.length) return\n\n // Ignore if there are too many arguments, only expect one\n // when app is launched as protocol handler. We can handle additional options in the future\n\n if (isDev && argv.length > 3) return // app was launched as: electron index.js $uri\n if (!isDev && argv.length > 2) return // packaged app run as: joystream $uri\n\n var $uri = isDev ? argv[2] : argv[1]\n\n if ($uri) {\n // arg is either a magnetlink or a filepath\n application.handleOpenExternalTorrent($uri, function (err, torrentName) {\n rootUIStore.openingExternalTorrentResult(err, torrentName)\n })\n }\n }",
"function getSuggestion(program, arg) {\n let message = '';\n program\n .showSuggestionAfterError() // make sure on\n .exitOverride()\n .configureOutput({\n writeErr: (str) => { message = str; }\n });\n // Do the same setup for subcommand.\n const sub = program._findCommand('sub');\n if (sub) sub.copyInheritedSettings(program);\n\n try {\n // Passing in an array for a few of the tests.\n const args = Array.isArray(arg) ? arg : [arg];\n program.parse(args, { from: 'user' });\n } catch (err) {\n }\n\n const match = message.match(/Did you mean (one of )?(.*)\\?/);\n return match ? match[2] : null;\n}",
"getOption(option, defaultValue = null) {\n if (this.options_.hasOwnProperty(option))\n return this.options_[option];\n\n return defaultValue;\n }",
"function handleArgFlags(env) {\n // Make sure that we're not overwriting `help`, `init,` or `version` args in generators\n if (argv._.length === 0) {\n // handle request for usage and options\n if (argv.help || argv.h) {\n out.displayHelpScreen();\n process.exit(0);\n }\n\n // handle request for initializing a new plopfile\n if (argv.init || argv.i) {\n const force = argv.force === true || argv.f === true || false;\n try {\n out.createInitPlopfile(force);\n process.exit(0);\n } catch (err) {\n console.error(chalk.red(\"[PLOP] \") + err.message);\n process.exit(1);\n }\n }\n\n // handle request for version number\n if (argv.version || argv.v) {\n const localVersion = env.modulePackage.version;\n if (localVersion !== globalPkg.version && localVersion != null) {\n console.log(chalk.yellow(\"CLI version\"), globalPkg.version);\n console.log(chalk.yellow(\"Local version\"), localVersion);\n } else {\n console.log(globalPkg.version);\n }\n process.exit(0);\n }\n }\n\n // abort if there's no plopfile found\n if (env.configPath == null) {\n console.error(chalk.red(\"[PLOP] \") + \"No plopfile found\");\n out.displayHelpScreen();\n process.exit(1);\n }\n}",
"function Option() {\n Argument.apply(this, arguments);\n this.type = Argument.OPTION;\n this.extra = undefined;\n this.required = undefined;\n this.multiple = undefined;\n\n // a type specified in the literal, eg: {Number}\n this.kind = undefined\n\n // default value for the option, eg: {=stdout}\n this.value = undefined;\n}",
"function startOptions(optConfig, optSet = undefined, classification = undefined) {\n optSet = initOptions(optConfig, optSet, true); // PreInit\n\n // Memory Storage fuer vorherige Speicherung...\n myOptMem = restoreMemoryByOpt(optSet.oldStorage);\n\n // Zwischengespeicherte Befehle auslesen...\n const __STOREDCMDS = getStoredCmds(myOptMem);\n\n // ... ermittelte Befehle ausführen...\n const __LOADEDCMDS = runStoredCmds(__STOREDCMDS, optSet, true); // BeforeLoad\n\n loadOptions(optSet);\n\n // Memory Storage fuer naechste Speicherung...\n myOptMem = startMemoryByOpt(optSet.storage, optSet.oldStorage);\n\n initScriptDB(optSet);\n\n optSet = initOptions(optConfig, optSet, false); // Rest\n\n if (classification !== undefined) {\n // Classification mit optSet verknuepfen...\n classification.optSet = optSet;\n\n // Umbenennungen durchfuehren...\n classification.renameOptions();\n }\n\n // ... ermittelte Befehle ausführen...\n runStoredCmds(__LOADEDCMDS, optSet, false); // Rest\n\n return optSet;\n}",
"bootstrapCLI(app) {\n core_1.CLI.registerGlobalOptions(app, this);\n }",
"getBuildType() {\n this.buildType = process.argv[2] ? process.argv[2].split('-').join('') : 'development';\n }",
"checkUnknownOptions() {\n const { rawOptions, globalCommand } = this.cli;\n if (!this.config.allowUnknownOptions) {\n for (const name of Object.keys(rawOptions)) {\n if (name !== '--' &&\n !this.hasOption(name) &&\n !globalCommand.hasOption(name)) {\n console.error(`error: Unknown option \\`${name.length > 1 ? `--${name}` : `-${name}`}\\``);\n process.exit(1);\n }\n }\n }\n }",
"function getCliConfig(): RNConfig {\n const cliArgs = minimist(process.argv.slice(2));\n const config = cliArgs.config != null\n ? Config.loadFile(path.resolve(__dirname, cliArgs.config))\n : Config.findOptional(__dirname);\n\n return {...defaultConfig, ...config};\n}",
"scanArgument(isOptional: boolean): ?Token {\n let start;\n let end;\n let tokens;\n if (isOptional) {\n this.consumeSpaces(); // \\@ifnextchar gobbles any space following it\n if (this.future().text !== \"[\") {\n return null;\n }\n start = this.popToken(); // don't include [ in tokens\n ({tokens, end} = this.consumeArg([\"]\"]));\n } else {\n ({tokens, start, end} = this.consumeArg());\n }\n\n // indicate the end of an argument\n this.pushToken(new Token(\"EOF\", end.loc));\n\n this.pushTokens(tokens);\n return start.range(end, \"\");\n }",
"function processArgs() {\n // Process command line arguments. Expecing only one. an app ID.\n const arg = process.argv.slice(2);\n\n // Fail if there is more than one argument passed.\n if (arg.length != 1) {\n throw Error(`DONEZO:\\n\\tExpected eactly one argument. Actually got: ${arg.length}.` +\n `\\n\\tArguments passed are: ${arg}`);\n }\n\n return arg[0];\n}",
"function readConfig (argv) {\n return new BB((resolve, reject) => {\n const npmBin = process.platform === 'win32' ? 'npm.cmd' : 'npm'\n const child = spawn(npmBin, [\n 'config', 'ls', '--json', '-l'\n // We add argv here to get npm to parse those options for us :D\n ].concat(argv || []), {\n env: process.env,\n cwd: process.cwd(),\n stdio: [0, 'pipe', 2]\n })\n\n let stdout = ''\n if (child.stdout) {\n child.stdout.on('data', (chunk) => {\n stdout += chunk\n })\n }\n\n child.on('error', reject)\n child.on('close', (code) => {\n if (code === 127) {\n reject(new Error('`npm` command not found. Please ensure you have npm@5.4.0 or later installed.'))\n } else {\n try {\n resolve(JSON.parse(stdout))\n } catch (e) {\n reject(new Error('`npm config ls --json` failed to output json. Please ensure you have npm@5.4.0 or later installed.'))\n }\n }\n })\n })\n}",
"function GetModuleArgSpec(model, options, appendMainModuleOptions, mainModule, useSdk) {\n var argSpec = GetArgSpecFromOptions(model, options, \"\", mainModule, useSdk);\n if (appendMainModuleOptions) {\n argSpec.push(argSpec.pop() + \",\");\n //if (this.NeedsForceUpdate)\n //{\n // argSpec.push(\"force_update=dict(\");\n // argSpec.push(\" type='bool'\");\n // argSpec.push(\"),\");\n //}\n argSpec.push(\"state=dict(\");\n argSpec.push(\" type='str',\");\n argSpec.push(\" default='present',\");\n argSpec.push(\" choices=['present', 'absent']\");\n argSpec.push(\")\");\n }\n return argSpec;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Message Event This event is called when a message is sent to your page. The 'message' object format can vary depending on the kind of message that was received. Read more at For this example, we're going to echo any text that we get. If we get some special keywords ('button', 'generic', 'receipt'), then we'll send back examples of those bubbles to illustrate the special message bubbles we've created. If we receive a message with an attachment (image, video, audio), then we'll simply confirm that we've received the attachment. | function receivedMessage(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfMessage = event.timestamp;
var message = event.message;
console.log("Received message for user %d and page %d at %d with message:",
senderID, recipientID, timeOfMessage);
console.log(JSON.stringify(message));
var messageId = message.mid;
// You may get a text or attachment but not both
var messageText = message.text;
var messageAttachments = message.attachments;
console.log('Message Received:', messageText);
if (messageText) {
// If we receive a text message, check to see if it matches any special
// keywords and send back the corresponding example. Otherwise, just echo
// the text we received.
switch (messageText) {
case 'image':
sendImageMessage(senderID);
break;
case 'button':
sendButtonMessage(senderID);
break;
case 'generic':
sendGenericMessage(senderID);
break;
case 'receipt':
sendReceiptMessage(senderID);
break;
default:
console.log('Message Received:', messageText);
sendTextMessage(senderID, messageText);
}
} else if (messageAttachments) {
sendTextMessage(senderID, "Message with attachment received");
}
} | [
"function onMessageReceived(e) {\n var data = JSON.parse(e.data);\n\n switch (data.event) {\n case 'ready':\n onReady();\n break;\n\n case 'playProgress':\n onPlayProgress(data.data);\n break;\n\n case 'pause':\n onPause();\n break;\n\n case 'finish':\n onFinish();\n break;\n }\n }",
"function handleMessageTopic(message) {\n console.info(`Message received - ${message}`);\n}",
"function onMessageArrived(message) {\n console.log(\"onMessageArrived: \"+message.payloadString);\n var json = JSON.parse(message.payloadString);\n drawCharts(json);\n\n}",
"_onClickMessage(event) {\r\n\t\tif (event && event.target.classList.contains('narrator-chat')) {\r\n\t\t\t//@ts-ignore\r\n\t\t\tconst roll = $(event.currentTarget);\r\n\t\t\tconst tip = roll.find('.message-metadata');\r\n\t\t\tif (!tip.is(':visible')) tip.slideDown(200);\r\n\t\t\telse tip.slideUp(200);\r\n\t\t}\r\n\t}",
"function MessageHandler() {\n\tEventEmitter.call( this );\n}",
"function onMessage(message) {\r\n\tswitch (message.type) {\r\n\t\tcase MessageType.BYE:\r\n\t\t\tlocalVideo.src = '';\r\n\t\t\tremoteVideo.src = '';\r\n\t\t\tconversation = null;\r\n\t\t\tbreak;\r\n\t\tcase MessageType.INVITATION:\r\n\t\t\tvar accept = confirm(\"Incoming call from: \" + \r\n\t\t\t\t\tmessage.from.rtcIdentity + \" Accept?\");\r\n\t\t\tif (accept == true)\t{\r\n\t\t\t\t// Create new conversation object\r\n\t\t\t\tconversation = new Conversation(myIdentity,\r\nthis.onRTCEvt.bind(this), this.onMessage.bind(this), iceServers, constraints);\r\n\t\t\t\tconversation.acceptInvitation(message);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tconversation.reject(message);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t}\r\n}",
"function newRecievedMessage(messageText) {\n\n\t// Variable storing the message with the \"\" removed\n\tvar removedQuotes = messageText.replace(/[\"\"]/g,\"\");\n\n\t// update the last message recieved variable for storage in the database\n\tlastRecievedMessage = removedQuotes;\n\n\t// If the message contains a <ar then it is a message\n\t// whose responses are buttons\n\tif (removedQuotes.includes(\"<br\")) \n\t{\n\t\tmultiMessage(removedQuotes);\n\t} \n\n\t// There arent multiple messages to be sent, or message with buttons\n\telse\n\t{\t\n\t\t// Show the typing indicator\n\t\tshowLoading();\n\n\t\t// After 3 seconds call the createNewMessage function\n\t\tsetTimeout(function() {\n\t\t\tcreateNewMessage(removedQuotes);\n\t\t}, DEFAULT_TIME_DELAY);\n\t}\n}",
"function handleMessage(message_event) {\n // Display to console\n console.log(message_event.data);\n // Parse incoming message string and update status with any messages prefixed by 'GLB'\n var newStr = new String(message_event.data);\n if (newStr.charAt(0) == 'G' && newStr.charAt(1) == 'L' && newStr.charAt(2) == 'B') {\n updateStatus(message_event.data);\n } else if (newStr == \"ExitModule\") {\n // ExitModule message ends NaCl module\n endModule();\n }\n}",
"function servermessage(event) {\n // console.log(\"Pubsub message received.\")\n if (typeof (event.data) === 'string') {\n // console.log(event.data)\n lioranboardclient.send(event.data);\n } else {\n // console.log(\"Message received from PubSub is not a string\")\n }\n}",
"receiveMessage() {\n setTimeout(function () {\n app.currentRecipient.messages.push(\n {\n date: app.getCurrentTime(),\n text: 'Ok',\n status: 'received'\n }\n );\n }, 1000);\n }",
"onMessage (message) {\n if (message.command && message.options) {\n this.executeCommand(message.command, message.options);\n }\n }",
"function showMessage(message) {\n\tlet html = \"\";\n\tif (message.isSentByMe()) {\n\t\thtml = \"\" +\n\t\t\t\"<div class='message sent'>\" +\n\t\t\t\"\t<span class='text'>\" + message.getText() + \"</span>\" +\n\t\t\t\"\t<span class='time'>\" + getCurrentTime(message.getTime()) + \"</span>\" +\n\t\t\t\"</div>\";\n\t} else {\n\t\thtml = \"\" +\n\t\t\t\"<div class='message'>\" +\n\t\t\t\"\t<span class='time'>\" + getCurrentTime(message.getTime()) + \"</span>\" +\n\t\t\t\"\t<span class='text'>\" + message.getText() + \"</span>\" +\n\t\t\t\"</div>\";\n\t}\n\n\tresults.innerHTML = html + results.innerHTML;\n}",
"async onmessage(e) {\n if(!this.connected) return;\n\n if (typeof e.data === 'string') {\n if(this.debug) console.log(\"Received string: '\" + e.data + \"'\");\n }\n else {\n // note: this fails on FireFox 83 due to Blob.arrayBuffer()\n // promise: the \"await\" results in bytes decoded\n // but with wrong timestamp order. Solved with patch-arrayBuffer.js\n let data = await e.data.arrayBuffer();\n let bytes = new Uint8Array(data);\n if(this.onreceive !== undefined) {\n this.onreceive(bytes);\n }\n if(this.debug) console.log(`websocket: received ${bytes.length} bytes`, this.array2String(bytes));\n }\n }",
"function receiveWindowMessage(evt) {\n if (evt) {\n // For now we handle messages that contain strings (for opening a report or a\n // screen in a new task window) or objects (for other purposes such as showing\n // Notes for a given entity such as an AR Customer).\n // NOTE: To test that we have a string, we use typeof (in case the string happens\n // to be ''), but to test for an object we need to use instanceof since it\n // returns false for null and true for an object whereas typeof returns\n // \"object\" for null as well as for objects.\n if (typeof evt.data === \"string\") {\n // We are being asked to open a report or screen as a new task window.\n openNewTask(evt.data);\n }\n else if (evt.data instanceof Object) {\n // Handle different types of messages that contain objects. For now, the\n // only type we handle is for showing Notes, but in future we might handle\n // other types of messages too.\n if (evt.data.notesOptions) {\n // We are being asked to show Notes for a given entity (e.g. an AR Customer).\n openNotesCenter(evt.data.notesOptions);\n }\n }\n }\n }",
"function onMavlinkMessage(msg) {\n d(\"onMavlinkMessage(): msg=\" + msg.name);\n\n switch(msg.name) {\n case \"HEARTBEAT\": {\n // Got a heartbeat message\n marklar.marklarTheMarklar();\n break;\n }\n }\n}",
"function trataMensagem(event){\n var senderID = event.sender.id;\n var recipientID = event.recipient.id;\n var timeOfMessage = event.timestamp;\n var message = event.message;\n \n console.log(\"Mensagem Recebida do usuario %d pela pagina %d\", senderID, recipientID);\n \n var messageID = message.mid;\n var messageText = message.text;\n var attachments = message.attachments;\n var quick_reply = message.quick_reply;\n \n if(message.text){\n \n if(_estados[senderID]){\n //Já começou a navegação\n switch(_estados[senderID]) {\n \n case 'options_menu':\n \n switch(messageText){\n \n case 'sim':\n console.log(\"enviar menu novamente\");\n sendFirstMenu(event.sender.id);\n break;\n \n case 'nao': \n console.log(\"dar xau\");\n sendTextMessage(senderID, \"Obrigada e volte sempre!\")\n break;\n }\n break;//fim options menu\n }//fim estados\n \n } else {//estado não é um dos considerados acima\n \n switch(messageText){\n case 'oi':\n sendTextMessage(senderID, \"Oi, tudo bem?\");\n break;\n case 'tchau':\n sendTextMessage(senderID, \"Até a próxima, pessoal o/\");\n break;\n case 'hey':\n sendTextMessage(senderID, \"I said hey, what's going on?\");\n sendTextMessage(senderID, \"yeah yeah yeah\");\n break;\n default:\n sendTextMessage(senderID, \"Desculpa, não consegui entender. :(\");\n }//fim switch de mensagem\n }//fim do else\n //se não for texto\n } else if (attachments) {\n //tratamento de anexos\n console.log(\"Me enviaram anexos!\");\n } else if (quick_reply) {\n console.log(\"Me enviaram um quick reply\");\n }\n}",
"function onMessage(evt) {\n let obj = JSON.parse(evt.data);\n if(obj.isMsg == true) {\n chatMsg(obj);\n } else {\n updateUsersList(obj);\n }\n}",
"function receiveChatMessage() {\n\tsocket.on('chat message', function(msg) {\n\t if (typeof(msg) === 'undefined' || msg === null || msg === '') {\n\t\treturn;\n\t }\n\t console.log(msg);\n\t var message = '<div class=\"receiver-message message\">###</div>'.replace('###', msg);\n\t $('#messages').append(message);\n\t});\n }",
"onBackgroundMessage(e) {\n if(e && e.params && e.params.name) {\n window.dispatchEvent(new CustomEvent(e.params.name, {detail: e.params.params}));\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.