query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
custom function to add an item to the favMeals state when <3 button pressed on top left corner of a meal card
function setFav(event) { const name = event.target.parentNode.textContent.slice( 2, event.target.parentNode.textContent.length - 1 ); //kinda stupid way to get this, but the name of the mealcard is kept at the top of the parentNode mealcard as "<3`name`X", so here we just remove the first two characters and last characters to get the name const { directions, ingredients, img } = meals.filter( (el) => el.name === name )[0]; //destructuring and grabbing all the necessary properties of the requested mealcard using the meals state const newFavMeals = [...favMeals]; //cloning favMeals state then adding new one and setting new state newFavMeals.push({ name, directions, ingredients, img }); setFavMeals(newFavMeals); }
[ "onAddMealButtonPressed(event) {\n\t\tthis.addMeal();\n\t}", "handleFavouriteFoods(meal) {\n let favouriteButtonDOM = document.querySelector(\".favourite-button\")\n let iconDOM = document.getElementById(\"icon\")\n favouriteButtonDOM.addEventListener(\"click\", () => {\n if (iconDOM.className.includes(\"fas\")) {\n // If selected meal is favourite meal, these lines will remove it from favouriteFoods array and localstorage\n // Changing icon's appearance\n iconDOM.classList = \"far fa-heart fa-3x\"\n let food = {}\n this.favouriteFoods.forEach(element => {\n if(element.id === meal.id){\n food = element\n }\n })\n let index = this.favouriteFoods.indexOf(food)\n // Deleting selected meal from array\n this.favouriteFoods.splice(index, 1);\n // Updating favourite array in localstorage\n localStorage.setItem('favFoods', JSON.stringify(this.favouriteFoods));\n } else if(iconDOM.className.includes(\"far\")) {\n // If selected meal is not favourite meal, these lines will add it to favouriteFoods array and localstorage\n // Adding selected meal to array\n this.favouriteFoods.push(meal)\n // Updating favourite array in localstorage\n localStorage.setItem(\"favFoods\", JSON.stringify(this.favouriteFoods))\n // Changing icon's appearance\n iconDOM.classList = \"fas fa-heart fa-3x\"\n }\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 markToBuy (event){\n // Get the element that triggered a specific event\n var selectedItem = event.target;\n // Get element by id\n var targetList = document.getElementById('toBuyItems');\n // Create new item if selected \n newBuyItem = ' <li class=\"list-group-item\"> <div role=\"group\" aria-label=\"Checklist Buttons\"> <button type=\"button\" onClick=\"markPacked(event);\" class=\"btn btn-check checkItem\" data-itemname=\"' + selectedItem.getAttribute(\"data-buyitemname\") + '\">Check</button> </div> ' + selectedItem.getAttribute(\"data-buyitemname\") + '</li>';\n // Where new item should be created\n var currentBuyList = targetList.innerHTML;\n targetList.innerHTML = currentBuyList + newBuyItem;\n // Hide item if selected\n selectedItem.parentElement.parentElement.classList.add('hideItem');\n saveItem('bought', selectedItem.getAttribute(\"data-buyitemname\"));\n }", "function clickOnItem() {\n var dogTrait = this.id;\n var dogPart = this.dataset.cat;\n dog[dogPart] = dogTrait;\n\n // time to display the cart\n createCartList(dog);\n}", "onAddToFavorite(e) {\n\t\te.stopPropagation();\n\t\tstoreActions.addAppToFolder(FAVORITES, this.props.app);\n\t\tstoreActions.addPin(this.props.app);\n\t}", "function clickItem(number) {\n if(blockInput) \n return; \n // Check if the user has an item in that slot. \n if(!items[number])\n return; \n // Heal the player. \n playerChar.hp += itemHealing; \n if (playerChar.hp > playerMaxHP) \n playerChar.hp = playerMaxHP; \n // Remove the item from that slot. \n items[number] = null; \n $(\"#divCombatButton\" + number).empty();\n}", "function showMeal(e) {\n const meal = e.target.parentElement;\n console.log(meal);\n\n if(meal.classList.contains('meal')) {\n const mealID = meal.getAttribute('data-mealid');\n getMealByID(mealID);\n } else {\n return false;\n }\n}", "function addMeal()\n{\n\t\n\tlet newMeal = {};\n\tvar foods = JSON.parse(localStorage.curMeal);\n\tconsole.log(foods);\n newMeal.id = ''.concat('meal', parseInt(n));\n n++;\n newMeal.category = document.getElementById(\"mealtype\");\n newMeal.food = foods;\n\tnewMeal.carbs = calcCarbs(foods);\n\twindow.location.href='insulin.html';\n \n meals.push(newMeal);\n // console.log(stickys);\n localStorage.setItem('meals', JSON.stringify(meals));\n\t// render(stickys);\n\tlocalStorage.setItem('curMeal', \"\");\n\t\n}", "function customIngredientToShoppingList() {\n let customIngredientName = document.getElementById(\"add-food\").value.toLowerCase()\n addCustomIngredient(customIngredientName)\n addToShoppingListExtra(getIngredientID(customIngredientName))\n toast(customIngredientName + \" Added\", successToast);\n}", "function addToFavorites(event) {\n event.preventDefault()\n let favorites = JSON.parse(localStorage.getItem(\"favorites\"))\n let id = getId(this)\n if (favorites.indexOf(id) < 0) {\n favorites.push(id)\n }\n localStorage.setItem(\"favorites\", JSON.stringify(favorites))\n changeTextIfFavorite(this)\n animateHeart(event.x, event.y)\n}", "function theClickedItem(item) {\n setHighlightItem(item);\n }", "function addItemShoppingList(newItem) {\n STORE.items.push({name: newItem, checked: false});\n}", "addItem() {\n this.setState({ addItem: 'true' })\n }", "function MealComponent({\n name,\n dishes,\n foodChange,\n animationSpeed,\n foodAdd,\n}) {\n const [fadeAnim] = useState(new Animated.Value(0)) // Initial value for opacity: 0\n\n React.useEffect(() => {\n Animated.timing(\n fadeAnim,\n {\n toValue: 1,\n duration: 800 * animationSpeed,\n }\n ).start();\n }, [])\n\n return (\n <Animated.View\n style={{\n opacity: fadeAnim\n }}\n >\n <Card\n title={name}\n titleStyle={styles.left_align_subheader_text}\n dividerStyle={{width: 0}}\n containerStyle={styles.cardStyle}\n >\n <View>\n { \n dishes.sort((a, b) => {\n return a[\"Food Name\"].localeCompare(b[\"Food Name\"])\n }).map((dish, i) => (\n <View key ={i}>\n <ListItem\n key={i}\n title={\n (\"Servings\" in dish) ?\n `${dish[\"Food Name\"]}, ${dish[\"Servings\"].toFixed(1)} servings`\n : (\"servings\" in dish) ?\n `${dish[\"Food Name\"]}, ${dish[\"servings\"].toFixed(1)} servings`\n :\n `${dish[\"Food Name\"]}, 1 serving`\n }\n bottomDivider\n topDivider={i === 0}\n chevron\n onPress={\n (\"Servings\" in dish) ? \n foodChange.bind(this, name, i, dish[\"Food Name\"], dish[\"food_id\"], dish[\"Servings\"])\n :\n foodChange.bind(this, name, i, dish[\"Food Name\"], dish[\"food_id\"], dish[\"servings\"])\n }\n />\n </View>\n ))\n }\n </View>\n\n <View>\n <Button\n title={`Add Food to ${name}`}\n onPress={foodAdd.bind(this, name)}\n buttonStyle={styles.nav_button}\n titleStyle={styles.nav_text}\n />\n </View> \n\n </Card>\n </Animated.View>\n );\n}", "function changeTextIfFavorite(button) {\n let favorites = JSON.parse(localStorage.getItem(\"favorites\"))\n let id = getId(button)\n if (favorites.indexOf(id) >= 0) {\n button.innerHTML = \"Saved to favorites\"\n button.classList.add('call-to-action')\n }\n}", "addOrRemoveFavorite(gifObj, favorite) {\n const newGif = {};\n newGif[gifObj.id] = gifObj;\n let newFavorites;\n\n if (favorite) {\n newFavorites = { ...this.state.favoritedGifs, ...newGif };\n this.setState({ favoritedGifs: newFavorites });\n localStorage.setItem('favorites', JSON.stringify(newFavorites));\n } else {\n // find in favorites, replace local storage with new object\n // make a copy of current state\n newFavorites = this.state.favoritedGifs;\n delete newFavorites[gifObj.id];\n\n this.setState({ favoritedGifs: newFavorites });\n localStorage.setItem('favorites', JSON.stringify(newFavorites));\n }\n }", "function setFoodItem(food) {\n let cartItems = localStorage.getItem(\"foodsInCart\");\n cartItems = JSON.parse(cartItems);\n\n if (cartItems != null) {\n if (cartItems[food.tag] == undefined) {\n cartItems = {\n ...cartItems,\n [food.tag]: food,\n };\n }\n cartItems[food.tag].inCart += 1;\n } else {\n food.inCart = 1;\n cartItems = {\n [food.tag]: food,\n };\n }\n\n localStorage.setItem(\"foodsInCart\", JSON.stringify(cartItems));\n}", "function createSkillItem(item, index) {\n // Item div\n var itemDiv = document.createElement(\"div\");\n itemDiv.classList.add(\"item\");\n itemDiv.id = \"skill-item-\" + index;\n itemDiv.setAttribute(\"tooltip\", \"\");\n\n // Item Picture\n var itemPic = document.createElement(\"div\");\n itemPic.classList.add(\"item-pic\");\n itemPic.style.backgroundImage = \"url(\\\"\" + item.sprite + \"\\\")\";\n\n // Checkmark shown when the item is unlocked\n var checkMark = document.createElement(\"div\");\n checkMark.classList.add(\"check\");\n\n // Register an onclick handler\n itemDiv.onclick = function(event) {\n // If the player's lavel is enough and the player didn't unlock this yet\n if (window.game.player.getLevel() >= item.levelNeeded && !window.game.player.unlockedItems.includes(item)) {\n // Unlock the item\n window.game.player.unlockItem(item);\n\n // Append the checkmark\n itemDiv.appendChild(checkMark);\n\n // Flash this element\n itemDiv.classList.add(\"flash-fast\");\n setTimeout(function() {\n itemDiv.classList.remove(\"flash-fast\");\n }, 500);\n\n // Go through all fruit trees and check if we can unlock them now\n window.game.farm.fruitTrees.forEach(function(fruitTree) {\n if (fruitTree.fruit == item && fruitTree.isLocked) {\n fruitTree.setLocked(false);\n }\n })\n\n // Repopulate the store so new items will be buyable\n populateStore();\n }\n }\n\n // Append the picture to the item div\n itemDiv.appendChild(itemPic);\n\n // Initially set the check marks on unlocked items\n if (window.game.player.unlockedItems.includes(item)) {\n itemDiv.appendChild(checkMark);\n\n // Also initially unlock the trees which are unlocked from start\n window.game.farm.fruitTrees.forEach(function(fruitTree) {\n if (fruitTree.fruit == item && fruitTree.isLocked) {\n fruitTree.setLocked(false);\n }\n })\n };\n\n // Return the created div\n return itemDiv;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the contents of the lootbox are empty. Removes the lootbox object and refreshes the contents, then respawns the lootbox after the set respawn time.
empty () { this.active = false; this.is_open = false; // No one can have it open because it will close when it is empty loot.CallRemoteCell('loot/sync/set_active', this.cell.x, this.cell.y, this.id, this.active); jcmp.events.Call('loot/lootbox_emptied', this.id); if (this.dropbox) { this.remove(); return; } this.respawn_time = this.get_respawn_time(); setTimeout(() => { // respawn lootbox object this.refresh(); }, this.respawn_time * 60 * 1000); }
[ "refresh ()\n {\n // If someone has it open, don't refresh\n if (!this.is_open)\n {\n this.contents = loot.generator.GetLoot(this.type, this.position);\n this.active = true;\n this.opened = false;\n this.sync_nearby();\n this.respawn_time = 0;\n jcmp.events.Call('log', 'loot', \n `Lootbox ${this.id} type ${this.type} refreshed.`);\n }\n else // Try again in 15 seconds to refresh.\n {\n setTimeout(() =>\n {\n this.refresh();\n }, 15 * 1000);\n }\n }", "function clearContentBox(){\n\t\tcontent.html('');\n\t}", "function lootboxbuy(chest) {\n var costmode, costemoji;\n //Decides which balance to add the rewarded amount to\n if (chest.type == \"cash\") {\n costmode = master.imp.bal;\n costemoji = \"💵\";\n } else if (chest.type == \"gems\") {\n costmode = master.imp.gem;\n costemoji = \"💎\";\n }\n if (chest.cost <= costmode) {\n //Decides which balance to deduce the cost from\n if (chest.type == \"cash\") {\n subbal(chest.cost);\n } else if (chest.type == \"gems\") {\n subgem(chest.cost);\n }\n //Bring up the Lootbox notification\n document.getElementById(\"lootboxnotif\").style.left = \"50%\";\n document.getElementById(\n \"lootnotifmain\"\n ).innerHTML = `Opening ${chest.name}! Wait for it...`;\n lootboxlist.forEach( (e) => {\n document.getElementById(`${e.id}B`).disabled = true\n });\n // for (let i = 0; i < lootboxlist.length; i++) {\n // document.getElementById(lootboxlist[i] + \"B\").disabled = true;\n // }\n //Declare the prize after 3 seconds\n setTimeout(() => {\n var chosen =\n chest.reward[Math.floor(Math.random() * chest.reward.length)];\n //If the selected reward is nothing\n if (chosen.type == \"none\") {\n document.getElementById(\"lootnotifmain\").innerHTML =\n \"Aw, you earned nothing...\";\n document.getElementById(\"lootboxnotif\").style.backgroundColor =\n \"rgb(216, 108, 108)\";\n //If the selected reward is cash\n } else if (chosen.type == \"cash\") {\n document.getElementById(\"lootnotifmain\").innerHTML =\n \"Congrats, you earned\";\n document.getElementById(\"lootnotifprize\").innerHTML = `${balformat(\n chosen.quan\n )}💵!`;\n document.getElementById(\"lootnotifprize\").style.fontSize = \"60px\";\n document.getElementById(\"lootboxnotif\").style.backgroundColor =\n \"rgb(139, 216, 108)\";\n addbal(chosen.quan);\n //If the selected reward is gems\n } else if (chosen.type == \"gems\") {\n document.getElementById(\"lootnotifmain\").innerHTML =\n \"Congrats, you earned\";\n document.getElementById(\"lootnotifprize\").innerHTML = `${balformat(\n chosen.quan\n )}💎!`;\n document.getElementById(\"lootnotifprize\").style.fontSize = \"60px\";\n document.getElementById(\"lootboxnotif\").style.backgroundColor =\n \"rgb(139, 216, 108)\";\n addgem(chosen.quan);\n }\n // document.addEventListener(\"click\", function () {\n // document.getElementById(\"lootboxnotif\").style.left = \"150%\";\n // for (let i = 0; i < lootboxlist.length; i++) {\n // document.getElementById(lootboxlist[i] + \"B\").disabled = false;\n // }\n // })\n }, 3000);\n //Hide the lootbox notification 3 seconds later\n setTimeout(() => {\n lootboxlist.forEach( (e) => {\n document.getElementById(`${e.id}B`).disabled = false\n });\n document.getElementById(\"lootboxnotif\").style.left = \"200%\";\n document.getElementById(\"lootboxnotif\").style.backgroundColor =\n \"rgb(175, 175, 175)\";\n document.getElementById(\"lootnotifprize\").style.fontSize = \"0px\";\n }, 6000);\n } else {\n notify(\n \"red\",\n `You don't have enough ${chest.type}! You need ${balformat(\n chest.cost - costmode\n )}${costemoji} more.`\n );\n }\n\n costmode, costemoji, (costloc = undefined);\n}", "function removeChildren() {\n plantBox.innerHTML = '';\n}", "function loadContent(){\n pole = game.instantiate(new Pole(Settings.pole.size));\n pole.setColor(Settings.pole.color);\n pole.setPosition(Settings.canvasWidth /2 , Settings.canvasHeight /2);\n\n shield = game.instantiate(new Shield(pole));\n shield.getBody().immovable = true;\n shield.setColor(Settings.shield.color);\n\n player = game.instantiate(new Player(\"\"));\n player.setPole(pole);\n player.setShield(shield);\n pole.setPlayer(player);\n\n //Player labels, name is set once again when the user has filled in his/her name\n scoreLabel = game.instantiate(new ScoreLabel(player, \"Score: 0\"));\n scoreLabel.setPosition(Settings.label.score);\n\n nameLabel = game.instantiate(new Label(\"Unknown Player\"));\n nameLabel.setPosition(Settings.label.name);\n\n highscoreLabel = game.instantiate(new Label(\"Highscore: 0\"));\n highscoreLabel.setPosition(Settings.label.highscore);\n\n createTempImage();\n setTimeout(deleteTempImage, 3000);\n\n //Hide the canvas for the player until a username is filled in and accepted\n var gameElem = document.getElementById(\"gameCanvas\");\n gameElem.style.display=\"none\";\n}", "function complete(){\n game.stage.removeChild(object);\n }", "function clearTemplate(){\n\t\tclearContentBox();\n\t\theader.find('header_title').html('');\n\t\theader.find('header_button').html('');\n\t}", "function clearEmptyGames() {\n\n }", "function update_loadbox() {\n\tif (px.ids.length > 0) {\n\t\tvar html = '';\n\n\t\t// async loop to load drawings\n\t\t// http://blog.chaoscollective.org/post/40284901138/webninja-tutorial-asynchronous-for-loops\n\t\t// https://gist.github.com/akumpf/4514343#file-forloop_jquery_callback-js\n\t\t(function(){\n\t\t\tvar i = 0;\n\t\t\tfunction forloop(){\n\t\t\tif ( i < Object.keys(px.ids).length ) {\n\t\t\t\tvar drawingID = 'pixelDrawing_' + px.ids[i];\n\t\t\t\tlocalforage.getItem(drawingID, function(drawing) {\n\t\t\t\t\tif (drawing) {\n\t\t\t\t\t\tif (drawing.id > 0) {\n\t\t\t\t\t\t\thtml += getHTMLsaveSnippet(drawing.id,drawing.img);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t\tforloop();\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t//console.log(\"all done\");\n\t\t\t\tpx.$saved.innerHTML = html;\n\t\t\t\thtml = null;\n\t\t\t\thideBusy();\n\t\t\t}\n\t\t\t}\n\t\t\tforloop();\n\t\t})();\n\n\t} else {\n\t\tpx.$saved.innerHTML = '<li class=\"nodrawings\">No Drawings. <span class=\"smaller\">Go push some pixels!</span><span class=\"ok\" data-js=\"ok\">ok</span></li>';\n\t\thideBusy();\n\t}\n\tpx.loaded = true;\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 refreshPopup(){\n document.querySelectorAll('.items').forEach(function(a){\n a.remove();\n })\n var DOMContentLoaded_event = document.createEvent(\"Event\");\n DOMContentLoaded_event.initEvent(\"DOMContentLoaded\", true, true);\n window.document.dispatchEvent(DOMContentLoaded_event);\n}", "function clearBoxes() {\n if (boxpolys != null) {\n for (var i = 0; i < boxpolys.length; i++) {\n boxpolys[i].setMap(null);\n }\n }\n boxpolys = null;\n }", "function complete(){\n stage.removeChild(object);\n }", "function doMboxen() {\n\t\t\tvar $mbClone = $('.mbox-small').clone(true, true);\n\t\t\tif ($mbClone.length) {\n\t\t\t\t// Remove the old one.\n\t\t\t\t$('.mbox-small').remove();\n\t\t\t\t$('#wsidebar').append($mbClone);\n\t\t\t}\n\t\t}", "Clear()\n {\n this._loadedObjects = {};\n }", "finalize() {\n for (const tile of this._cache.values()) {\n if (tile.isLoading) {\n tile.abort();\n }\n }\n this._cache.clear();\n this._tiles = [];\n this._selectedTiles = null;\n }", "function iglooContentManager () {\n\tthis.contentSize = 0;\n\tthis.discardable = 0;\n\tthis.content = {};\n\n\tthis.add = function (page) {\n\t\tthis.decrementScores();\n\t\tthis.contentSize++;\n\t\tthis.content[page.info.pageTitle] = {\n\t\t\texists: true,\n\t\t\tpage: page,\n\t\t\thold: true,\n\t\t\ttimeAdded: new Date(),\n\t\t\ttimeTouched: new Date(),\n\t\t\tscore: iglooConfiguration.defaultContentScore\n\t\t};\n\n\t\tigloo.log(\"Added a page to the content manager. Size: \" + this.contentSize);\n\t\tthis.gc();\n\n\t\treturn this.content[page.info.pageTitle];\n\t};\n\n\tthis.getPage = function (title) {\n\t\tif (this.content[title]) {\n\t\t\treturn this.content[title].page;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tthis.decrementScores = function () {\n\t\tvar s = \"CSCORE: \";\n\t\tfor (var i in this.content) {\n\t\t\tif (this.content[i].score > 0) {\n\t\t\t\ts += this.content[i].score + \", \";\n\t\t\t\tif (--this.content[i].score === 0) {\n\t\t\t\t\tigloo.log(\"an item reached a score of 0 and is ready for discard!\");\n\t\t\t\t\tthis.discardable++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tigloo.log(s);\n\t};\n\n\tthis.gc = function () {\n\t\tigloo.log(\"Running GC\");\n\t\tif (this.discardable === 0) return;\n\t\tif (this.contentSize > iglooUserSettings.maxContentSize) {\n\t\t\tigloo.log(\"GC removing items to fit limit (\" + this.contentSize + \"/\" + iglooUserSettings.maxContentSize + \")\");\n\t\t\tvar j = 0, lastZeroScore = null, gcVal = 0.3, gcStep = 0.05;\n\t\t\tfor (var i in this.content) {\n\t\t\t\tif (this.content[i].score !== 0 || this.content[i].isRecent !== false || this.content[i].page.displaying !== false) {\n\t\t\t\t\tj++;\n\t\t\t\t\tgcVal += gcStep;\n\t\t\t\t\tcontinue;\n\t\t\t\t} else {\n\t\t\t\t\tlastZeroScore = i;\n\t\t\t\t}\n\n\t\t\t\tif (j === this.contentSize - 1) {\n\t\t\t\t\tif (lastZeroScore !== null) {\n\t\t\t\t\t\tigloo.log(\"failed to randomly select item, discarding the last one seen\");\n\t\t\t\t\t\tthis.content[lastZeroScore] = undefined;\n\t\t\t\t\t\tthis.contentSize--;\n\t\t\t\t\t\tthis.discardable--;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (this.content[i].score === 0 && this.content[i].isRecent === false && Math.random() < gcVal && this.content[i].page.displaying === false) {\n\t\t\t\t\tigloo.log(\"selected an item suitable for discard, discarding\");\n\t\t\t\t\tthis.content[i] = undefined;\n\t\t\t\t\tthis.contentSize--;\n\t\t\t\t\tthis.discardable--;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tj++;\n\t\t\t\t\tgcVal += gcStep;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n}", "clear(){\n tiles.forEach(tile =>{\n tile.innerText = '';\n });\n }", "function fillInEmptyBlocks() {\n vm.numberOfRealPlayers = vm.competition.players.length;\n for (var i = vm.competition.players.length; i < vm.numberOfBlocks; i++) {\n vm.competition.players.push({\n firstName: 'Empty',\n lastName: 'Spot',\n displayName: 'Empty Spot',\n position: 99,\n class: 'empty',\n _id: 'XX'\n });\n }\n // We have to give levels to the new empty spots\n assignLevelsToPlayers();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if QoS rule string is valid or not QOS rules format: APP/GAME: ;;;; MAC : ;;;; PORT : ;;;;
function validRule(in_rule){ var rule = new String(in_rule); if(rule.length > 6 && rule != "" && rule.indexOf("\x02")!=-1){ rule = rule.split("\x02"); if(rule.length >= 5) return true; } return false; }
[ "function parse_apply_qos_rules(){\n if(validRule(apply_qos_rules)){\n apply_qos_rules_list = apply_qos_rules.split(\"\\x01\");\n apply_qos = apply_qos_rules.split(\"\\x01\");\n if(parseQoSRule(apply_qos) ){\n apply_qos_rules_count = apply_qos.length;\n return 1;\n }\n else{\n alert(getErrorMsgByVar(\"gsm_msg_qos_fail_parse_app\"));\n return 0;\n }\n }else{\n apply_qos_rules_count =0;\n return 0;\n }\n}", "function isDialrule (s) {\n\tvar i;\n\n\tif (isEmpty(s))\n if (isDialrule.arguments.length == 1) return defaultEmptyOK;\n else return (isDialrule.arguments[1] == true);\n\n\tfor (i = 0; i < s.length; i++) {\n\t\tvar c = s.charAt(i);\n\t\tif ( !isDialruleChar(c) ) {\n\t\t\tif (c.charCodeAt(0) != 13 && c.charCodeAt(0) != 10) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}", "function parseOnePortRule(rule){\n if (validRule(rule)==false ) {\n return \"err\";\n }\n\n rule = rule.split(\"\\x02\");\n\n //------------SOURCE PORT-----------------------\n rule[_src] = rule[_src].split(\"+\"); //tcp+udp\n if(isArray(rule[_src])){\n if(rule[_src].length == 2){\n rule[_src][_TCP] = rule[_src][_TCP].split(\",\"); //TCP\n rule[_src][_UDP] = rule[_src][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n //------------DESTINATION PORT-----------------------\n rule[_dst] = rule[_dst].split(\"+\"); //tcp+udp\n if(isArray(rule[_dst])){\n if(rule[_dst].length == 2){\n rule[_dst][_TCP] = rule[_dst][_TCP].split(\",\"); //TCP\n rule[_dst][_UDP] = rule[_dst][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");return \"err\";\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n return rule;\n}", "function isValidStation(s) {\n return s.match(/^\\s*\\S+\\s*$/)\n }", "validateDmac() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.dmac.replace(/^\\s+|\\s+$/g, \"\"))) return true;\n this.setState(\n {\n dmacError: true,\n },\n () => {\n return false;\n }\n );\n }", "isTickerValid(str) {\n str.trim();\n if (/^[a-zA-Z]+$/.test(str) && str.length <= 4) {\n return true;\n }\n return false;\n }", "function validateProtocol(proto2,url2) {\n if (proto2 == \"\" && (/^disk[0-2]|disk$/.test(url2) == true || /^slot[0-1]$/.test(url2) == true || /^NVRAM$/.test(url2) == true || /^bootflash$/.test(url2) == true || /^flash[0-1]|flash$/.test(url2) == true)) {\n return 0;\n } else if (/^FTP$/i.test(proto2) == false && /^TFTP$/i.test(proto2) == false) {\n return 1;\n } else {\n return 0;\n }\n\n}", "validateSmac() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.smac.replace(/^\\s+|\\s+$/g, \"\"))) return true;\n this.setState(\n {\n smacError: true,\n },\n () => {\n return false;\n }\n );\n }", "vaidateProtocol(host){\n let protocols = ['https://', 'http://'];\n if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host\n throw new Error('Host String must include http:// or https://')\n }", "function validateStringWithSpacesInput(value){\n\t\n\tvar stringWithSpaceRegExp = /(^[\\w-,\\(\\)]+)((\\s+)(\\w-,\\(\\)))*$/;\n\t//alert(stringWithSpaceRegExp);\n\t\n\tif(stringWithSpaceRegExp.test(value)==true){\n\t\t//alert(\"2\");\n\t\treturn true;\n\t}else{\n\t\t//alert(\"3\");\n\t\treturn false;\n\t}\n}", "function isMAC48Address(inputString) {\n return !!inputString.match(/^[0-9A-F]{2}(-[0-9A-F]{2}){5}$/g);\n}", "function validateSyntax() {\r\n\t\tsiteswapStr = siteswapStr.replace(/\\s/g,\"\");\r\n\t\tvar numJugglers = 1;\r\n\t\tvar isPassingPattern = /<[^ ]+>/.test(siteswapStr);\r\n\r\n\t\tif (isPassingPattern) {\r\n\t\t\tvar passingBeatArray = siteswapStr.match(/<[^ <>]+>/g);\r\n\t\t\tnumJugglers = passingBeatArray[0].split(\"|\").length;\r\n\r\n\t\t\t/* \r\n\t\t\t\tcheck to make sure each beat in the passing pattern has the same number of jugglers \r\n\t\t\t\tif a passing pattern only has 1 juggler than it's automatically a mismatch\r\n\t\t\t*/\r\n\t\t\tif(numJugglers == 1) {\r\n\t\t\t\treturn siteswap;\r\n\t\t\t};\r\n\t\t\t\r\n\t\t\tvar numJugglersTmp = numJugglers;\r\n\t\t\tpassingBeatArray.map(function(a) { \r\n\t\t\t\tif (a.split(\"|\").length != numJugglersTmp) \r\n\t\t\t\t\t{ return siteswap; } \r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\t/* the number of jugglers determines a valid pass pattern */\r\n\t\tvar passPattern = \"\";\r\n\t\tif (numJugglers == 2) {\r\n\t\t\tpassPattern = \"P\";\r\n\t\t} else if (numJugglers > 2) {\r\n\t\t\tpassPattern = \"P[1-\" + numJugglers + \"]\";\r\n\t\t}\r\n\r\n\t\t/* construct the various regex patterns. see blog post for details about this */\r\n\t\tvar validToss = \"([\\\\da-o])x?A?(\" + passPattern + \")?(C{(C|P)?})?(T{(C|P)?})?(B({\\\\d*(L|HL|F|HF)?\\\\d*})?)?(S{-?\\\\d+(.\\\\d+)?(,-?\\\\d+(.\\\\d+)?,-?\\\\d+(.\\\\d+)?,-?\\\\d+(.\\\\d+)?)?})?(D{\\\\d*\\\\.?\\\\d*})?\";\r\n\t\tvar validMultiplex = \"\\\\[(\" + validToss + \")+\\\\]\";\r\n\t\tvar validThrow = validToss + \"|\" + validMultiplex;\r\n\t\tvar validSync = \"\\\\((\" + validThrow + \"),(\" + validThrow + \")\\\\)\";\r\n\t\tvar validBeat = \"(\" + validThrow + \"|\" + validSync + \")\";\r\n\t\tvar validPass = \"<\" + validBeat + \"(\\\\|\" + validBeat + \")+>\";\r\n\t\tvar validSiteswap = \"^(\" + validPass + \")+|(\" + validBeat + \")+\\\\*?$\";\r\n\r\n\t\t// use this to identify passing pattern shorthand like <3P333|3P333>\r\n\t\t// we will then convert those patterns to standard notation like <3P|3P><3|3><3|3><3|3> \r\n\t\t// and parse them as we did before\r\n\t\tvar validPassShorthand = \"<\" + validBeat + \"+(\\\\|\" + validBeat + \"+)+>\"; \r\n\r\n\t\tvalidTossRe = new RegExp(validToss,\"g\");\r\n\t\tvalidMultiplexRe = new RegExp(validMultiplex,\"g\");\r\n\t\tvalidThrowRe = new RegExp(validThrow,\"g\");\r\n\t\tvalidSyncRe = new RegExp(validSync,\"g\");\r\n\t\tvalidBeatRe = new RegExp(validBeat,\"g\");\r\n\t\tvalidPassRe = new RegExp(validPass,\"g\");\r\n\t\tvalidSiteswapRe = new RegExp(validSiteswap,\"g\");\r\n\t\tvalidPassShorthandRe = new RegExp(validPassShorthand,\"g\");\r\n\r\n\t\t// if the input string was shorthand for a passing pattern\r\n\t\t// then replace the siteswap string with a fully formed passing pattern\r\n\t\t// ie. transform <33|33> to <3|3><3|3>\r\n\t\tif (siteswapStr.match(validPassShorthandRe) == siteswapStr) {\r\n\t\t\tvar newSiteswapStr = \"\";\r\n\t\t\tvar jugglerSiteswaps = siteswapStr.split('|');\r\n\t\t\tvar jugglerBeats = [];\r\n\t\t\tfor(var i = 0; i < jugglerSiteswaps.length; i++) {\r\n\t\t\t\tjugglerBeats.push(jugglerSiteswaps[i].match(validBeatRe));\r\n\t\t\t}\r\n\t\t\tfor (var i = 0; i < jugglerBeats[0].length; i++) {\r\n\t\t\t\tnewSiteswapStr += \"<\";\r\n\t\t\t\tfor (var j = 0; j < jugglerBeats.length; j++) {\r\n\t\t\t\t\tnewSiteswapStr += jugglerBeats[j][i];\r\n\t\t\t\t\tif (j < jugglerBeats.length - 1) {\r\n\t\t\t\t\t\tnewSiteswapStr += \"|\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tnewSiteswapStr += \">\";\r\n\t\t\t}\r\n\t\t\tsiteswapStr = newSiteswapStr;\r\n\t\t}\r\n\r\n\t\t// if the input string was a synchronous siteswap ending in *\r\n\t\t// then we repeat the input pattern, but swap the throws in each pair\r\n\t\t// to make the pattern symmetric\r\n\t\t// e.g. transform (6x,4)* to (6x,4)(4,6x)\r\n\t\tif (siteswapStr.charAt(siteswapStr.length-1) == \"*\") {\r\n\t\t\tvar newSiteswapStr = siteswapStr.slice(0,-1);\r\n\t\t\tvar pairs = newSiteswapStr.match(validSyncRe);\r\n\t\t\tif (pairs !== null) {\r\n\t\t\t\tfor (var i = 0; i < pairs.length; i++) {\r\n\t\t\t\t\tnewSiteswapStr += \"(\" + pairs[i].match(validThrowRe).reverse().join(\",\") + \")\";\r\n\t\t\t\t}\r\n\t\t\t\tsiteswapStr = newSiteswapStr;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (siteswapStr.match(validSiteswapRe) == siteswapStr) {\r\n\t\t\tsiteswap.validSyntax = true;\r\n\t\t\tsiteswap.multiplex = siteswapStr.match(validMultiplexRe) ? true : false;\r\n\t\t\tsiteswap.sync = siteswapStr.match(validSyncRe) ? true : false;\r\n\t\t\tsiteswap.pass = siteswapStr.match(validPassRe) ? true : false;\r\n\t\t\tsiteswap.numJugglers = numJugglers;\r\n\t\t} else {\r\n\t\t\tsiteswap.errorMessage = \"Invalid syntax\";\r\n\t\t} \r\n\t}", "function validateAttributeString(attrStr,options){//console.log(\"start:\"+attrStr+\":end\");\n//if(attrStr.trim().length === 0) return true; //empty string\nvar matches=util.getAllMatches(attrStr,validAttrStrRegxp);var attrNames={};for(var i=0;i<matches.length;i++){if(matches[i][1].length===0){//nospace before attribute name: a=\"sd\"b=\"saf\"\nreturn getErrorObject('InvalidAttr',\"Attribute '\"+matches[i][2]+\"' has no space in starting.\",getPositionFromMatch(attrStr,matches[i][0]));}else if(matches[i][3]===undefined&&!options.allowBooleanAttributes){//independent attribute: ab\nreturn getErrorObject('InvalidAttr',\"boolean attribute '\"+matches[i][2]+\"' is not allowed.\",getPositionFromMatch(attrStr,matches[i][0]));}/* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */var attrName=matches[i][2];if(!validateAttrName(attrName)){return getErrorObject('InvalidAttr',\"Attribute '\"+attrName+\"' is an invalid name.\",getPositionFromMatch(attrStr,matches[i][0]));}if(!attrNames.hasOwnProperty(attrName)){//check for duplicate attribute.\nattrNames[attrName]=1;}else{return getErrorObject('InvalidAttr',\"Attribute '\"+attrName+\"' is repeated.\",getPositionFromMatch(attrStr,matches[i][0]));}}return true;}", "function Validar_espacio(parametro){\n var Espacio= /\\s/;\n if(Espacio.test(parametro)){\n return false;\n }\n else{\n return true;\n }\n }", "checkRule(name) {\n const rule = this.rules[name];\n\n switch (rule.recurrent) {\n case true:\n if (typeof name === \"string\" && rule && rule.ruleset) {\n return true;\n }\n break;\n default:\n if (typeof name === \"string\" && rule && typeof rule.test === \"function\" && typeof rule.message === \"string\") {\n return true;\n }\n }\n\n throw new Error(\n name + \" is not a complete rule. A complete rule must contain both `test` function and `message` string.\"\n );\n }", "function validate(str) {\n return !str.includes('|||')\n}", "_isValidOperation (op) {\n return op && !/[^0-9.()\\-+*/,]/g.test(op)\n }", "static checkParamsValidity (channel) {\n const { clientId, clientSecret, serviceId } = channel\n channel.phoneNumber = channel.phoneNumber.split(' ').join('')\n\n if (!clientId) { throw new BadRequestError('Parameter is missing: Client Id') }\n if (!clientSecret) { throw new BadRequestError('Parameter is missing: Client Secret') }\n if (!serviceId) { throw new BadRequestError('Parameter is missing: Service Id') }\n if (!channel.phoneNumber) { throw new BadRequestError('Parameter is missing: Phone Number') }\n\n return true\n }", "static isValid(make) {\n return make != null && make !== '';\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an object with the list of properties named in |properties|. Every property access will be recorded in |record|, which will also be used to determine whether a particular property access should fail, or whether it should return an invalid value that will fail validation.
function createRecordingObjectWithProperties(record, properties) { const recordingObject = {}; for (const property of properties) { defineCheckedProperty(record, recordingObject, property, () => record.check(property) ? 'invalid' : undefined); } return recordingObject; }
[ "function createResource(properties) {\r\n var resource = {};\r\n var normalizedProps = properties;\r\n for (var p in properties) {\r\n var value = properties[p];\r\n if (p && p.substr(-2, 2) == '[]') {\r\n var adjustedName = p.replace('[]', '');\r\n if (value) {\r\n normalizedProps[adjustedName] = value.split(',');\r\n }\r\n delete normalizedProps[p];\r\n }\r\n }\r\n for (var p in normalizedProps) {\r\n // Leave properties that don't have values out of inserted resource.\r\n if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {\r\n var propArray = p.split('.');\r\n var ref = resource;\r\n for (var pa = 0; pa < propArray.length; pa++) {\r\n var key = propArray[pa];\r\n if (pa == propArray.length - 1) {\r\n ref[key] = normalizedProps[p];\r\n } else {\r\n ref = ref[key] = ref[key] || {};\r\n }\r\n }\r\n };\r\n }\r\n return resource;\r\n}", "function CfnStorageLens_AccountLevelPropertyValidator(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('activityMetrics', CfnStorageLens_ActivityMetricsPropertyValidator)(properties.activityMetrics));\n errors.collect(cdk.propertyValidator('advancedCostOptimizationMetrics', CfnStorageLens_AdvancedCostOptimizationMetricsPropertyValidator)(properties.advancedCostOptimizationMetrics));\n errors.collect(cdk.propertyValidator('advancedDataProtectionMetrics', CfnStorageLens_AdvancedDataProtectionMetricsPropertyValidator)(properties.advancedDataProtectionMetrics));\n errors.collect(cdk.propertyValidator('bucketLevel', cdk.requiredValidator)(properties.bucketLevel));\n errors.collect(cdk.propertyValidator('bucketLevel', CfnStorageLens_BucketLevelPropertyValidator)(properties.bucketLevel));\n errors.collect(cdk.propertyValidator('detailedStatusCodesMetrics', CfnStorageLens_DetailedStatusCodesMetricsPropertyValidator)(properties.detailedStatusCodesMetrics));\n return errors.wrap('supplied properties not correct for \"AccountLevelProperty\"');\n}", "function CfnStorageLens_StorageLensConfigurationPropertyValidator(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('accountLevel', cdk.requiredValidator)(properties.accountLevel));\n errors.collect(cdk.propertyValidator('accountLevel', CfnStorageLens_AccountLevelPropertyValidator)(properties.accountLevel));\n errors.collect(cdk.propertyValidator('awsOrg', CfnStorageLens_AwsOrgPropertyValidator)(properties.awsOrg));\n errors.collect(cdk.propertyValidator('dataExport', CfnStorageLens_DataExportPropertyValidator)(properties.dataExport));\n errors.collect(cdk.propertyValidator('exclude', CfnStorageLens_BucketsAndRegionsPropertyValidator)(properties.exclude));\n errors.collect(cdk.propertyValidator('id', cdk.requiredValidator)(properties.id));\n errors.collect(cdk.propertyValidator('id', cdk.validateString)(properties.id));\n errors.collect(cdk.propertyValidator('include', CfnStorageLens_BucketsAndRegionsPropertyValidator)(properties.include));\n errors.collect(cdk.propertyValidator('isEnabled', cdk.requiredValidator)(properties.isEnabled));\n errors.collect(cdk.propertyValidator('isEnabled', cdk.validateBoolean)(properties.isEnabled));\n errors.collect(cdk.propertyValidator('storageLensArn', cdk.validateString)(properties.storageLensArn));\n return errors.wrap('supplied properties not correct for \"StorageLensConfigurationProperty\"');\n}", "function CfnVirtualNode_AccessLogPropertyValidator(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('file', CfnVirtualNode_FileAccessLogPropertyValidator)(properties.file));\n return errors.wrap('supplied properties not correct for \"AccessLogProperty\"');\n}", "function CfnVirtualNode_LoggingPropertyValidator(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('accessLog', CfnVirtualNode_AccessLogPropertyValidator)(properties.accessLog));\n return errors.wrap('supplied properties not correct for \"LoggingProperty\"');\n}", "function CfnVirtualNode_FileAccessLogPropertyValidator(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('format', CfnVirtualNode_LoggingFormatPropertyValidator)(properties.format));\n errors.collect(cdk.propertyValidator('path', cdk.requiredValidator)(properties.path));\n errors.collect(cdk.propertyValidator('path', cdk.validateString)(properties.path));\n return errors.wrap('supplied properties not correct for \"FileAccessLogProperty\"');\n}", "function CfnBucket_CorsRulePropertyValidator(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('allowedHeaders', cdk.listValidator(cdk.validateString))(properties.allowedHeaders));\n errors.collect(cdk.propertyValidator('allowedMethods', cdk.requiredValidator)(properties.allowedMethods));\n errors.collect(cdk.propertyValidator('allowedMethods', cdk.listValidator(cdk.validateString))(properties.allowedMethods));\n errors.collect(cdk.propertyValidator('allowedOrigins', cdk.requiredValidator)(properties.allowedOrigins));\n errors.collect(cdk.propertyValidator('allowedOrigins', cdk.listValidator(cdk.validateString))(properties.allowedOrigins));\n errors.collect(cdk.propertyValidator('exposedHeaders', cdk.listValidator(cdk.validateString))(properties.exposedHeaders));\n errors.collect(cdk.propertyValidator('id', cdk.validateString)(properties.id));\n errors.collect(cdk.propertyValidator('maxAge', cdk.validateNumber)(properties.maxAge));\n return errors.wrap('supplied properties not correct for \"CorsRuleProperty\"');\n}", "function CfnVirtualGateway_VirtualGatewayAccessLogPropertyValidator(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('file', CfnVirtualGateway_VirtualGatewayFileAccessLogPropertyValidator)(properties.file));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayAccessLogProperty\"');\n}", "function CfnDomainNamePropsValidator(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('certificateArn', cdk.requiredValidator)(properties.certificateArn));\n errors.collect(cdk.propertyValidator('certificateArn', cdk.validateString)(properties.certificateArn));\n errors.collect(cdk.propertyValidator('description', cdk.validateString)(properties.description));\n errors.collect(cdk.propertyValidator('domainName', cdk.requiredValidator)(properties.domainName));\n errors.collect(cdk.propertyValidator('domainName', cdk.validateString)(properties.domainName));\n return errors.wrap('supplied properties not correct for \"CfnDomainNameProps\"');\n}", "function CfnBucket_ObjectLockRulePropertyValidator(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('defaultRetention', CfnBucket_DefaultRetentionPropertyValidator)(properties.defaultRetention));\n return errors.wrap('supplied properties not correct for \"ObjectLockRuleProperty\"');\n}", "function CfnStorageLensPropsValidator(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('storageLensConfiguration', cdk.requiredValidator)(properties.storageLensConfiguration));\n errors.collect(cdk.propertyValidator('storageLensConfiguration', CfnStorageLens_StorageLensConfigurationPropertyValidator)(properties.storageLensConfiguration));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n return errors.wrap('supplied properties not correct for \"CfnStorageLensProps\"');\n}", "function CfnRoute_HttpRetryPolicyPropertyValidator(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('httpRetryEvents', cdk.listValidator(cdk.validateString))(properties.httpRetryEvents));\n errors.collect(cdk.propertyValidator('maxRetries', cdk.requiredValidator)(properties.maxRetries));\n errors.collect(cdk.propertyValidator('maxRetries', cdk.validateNumber)(properties.maxRetries));\n errors.collect(cdk.propertyValidator('perRetryTimeout', cdk.requiredValidator)(properties.perRetryTimeout));\n errors.collect(cdk.propertyValidator('perRetryTimeout', CfnRoute_DurationPropertyValidator)(properties.perRetryTimeout));\n errors.collect(cdk.propertyValidator('tcpRetryEvents', cdk.listValidator(cdk.validateString))(properties.tcpRetryEvents));\n return errors.wrap('supplied properties not correct for \"HttpRetryPolicyProperty\"');\n}", "function CfnVirtualGateway_VirtualGatewayFileAccessLogPropertyValidator(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('format', CfnVirtualGateway_LoggingFormatPropertyValidator)(properties.format));\n errors.collect(cdk.propertyValidator('path', cdk.requiredValidator)(properties.path));\n errors.collect(cdk.propertyValidator('path', cdk.validateString)(properties.path));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayFileAccessLogProperty\"');\n}", "function CfnBucket_ReplicationRulePropertyValidator(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('deleteMarkerReplication', CfnBucket_DeleteMarkerReplicationPropertyValidator)(properties.deleteMarkerReplication));\n errors.collect(cdk.propertyValidator('destination', cdk.requiredValidator)(properties.destination));\n errors.collect(cdk.propertyValidator('destination', CfnBucket_ReplicationDestinationPropertyValidator)(properties.destination));\n errors.collect(cdk.propertyValidator('filter', CfnBucket_ReplicationRuleFilterPropertyValidator)(properties.filter));\n errors.collect(cdk.propertyValidator('id', cdk.validateString)(properties.id));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('priority', cdk.validateNumber)(properties.priority));\n errors.collect(cdk.propertyValidator('sourceSelectionCriteria', CfnBucket_SourceSelectionCriteriaPropertyValidator)(properties.sourceSelectionCriteria));\n errors.collect(cdk.propertyValidator('status', cdk.requiredValidator)(properties.status));\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n return errors.wrap('supplied properties not correct for \"ReplicationRuleProperty\"');\n}", "function CfnVirtualGateway_VirtualGatewayLoggingPropertyValidator(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('accessLog', CfnVirtualGateway_VirtualGatewayAccessLogPropertyValidator)(properties.accessLog));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayLoggingProperty\"');\n}", "function CfnStorageLens_BucketLevelPropertyValidator(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('activityMetrics', CfnStorageLens_ActivityMetricsPropertyValidator)(properties.activityMetrics));\n errors.collect(cdk.propertyValidator('advancedCostOptimizationMetrics', CfnStorageLens_AdvancedCostOptimizationMetricsPropertyValidator)(properties.advancedCostOptimizationMetrics));\n errors.collect(cdk.propertyValidator('advancedDataProtectionMetrics', CfnStorageLens_AdvancedDataProtectionMetricsPropertyValidator)(properties.advancedDataProtectionMetrics));\n errors.collect(cdk.propertyValidator('detailedStatusCodesMetrics', CfnStorageLens_DetailedStatusCodesMetricsPropertyValidator)(properties.detailedStatusCodesMetrics));\n errors.collect(cdk.propertyValidator('prefixLevel', CfnStorageLens_PrefixLevelPropertyValidator)(properties.prefixLevel));\n return errors.wrap('supplied properties not correct for \"BucketLevelProperty\"');\n}", "function CfnStorageLens_SelectionCriteriaPropertyValidator(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('delimiter', cdk.validateString)(properties.delimiter));\n errors.collect(cdk.propertyValidator('maxDepth', cdk.validateNumber)(properties.maxDepth));\n errors.collect(cdk.propertyValidator('minStorageBytesPercentage', cdk.validateNumber)(properties.minStorageBytesPercentage));\n return errors.wrap('supplied properties not correct for \"SelectionCriteriaProperty\"');\n}", "_buildPropertyProps(properties = {}) {\n const props = {};\n for (const propertyName in properties) {\n const property = properties[propertyName];\n const propData = NOTION_PAGE_PROPERTIES[property.type];\n\n if (!propData) continue;\n\n props[propertyName] = {\n type: propData.type,\n label: propertyName,\n description: this._buildPropDescription(property.type, propData.example),\n options: propData.options(property),\n optional: true,\n };\n }\n return props;\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by InputAdapter when an InputEvent resolves and is an Alt input. To handle events for nonAlt inputs, refer to onInputEvent(). Returns true if the event should be consumed. If consumed, the event will not propagate to other trigger other events.
onAltInputEvent(pointer) { return false; }
[ "function isAlt(event) {\n\t\tconst { altSecondaryEnabled } = getSettings();\n\t\treturn event && event.altKey && altSecondaryEnabled;\n\t}", "handleAltLockChanged() {\n this.isAltitudeLocked = this._inputDataStates.altLocked.state;\n\n if (this.isAltitudeLocked) {\n\n if (this.currentVerticalActiveState === VerticalNavModeState.TO || this.currentVerticalActiveState === VerticalNavModeState.GA) {\n SimVar.SetSimVarValue(\"K:AUTO_THROTTLE_TO_GA\", \"number\", 0);\n }\n\n this.currentVerticalActiveState = VerticalNavModeState.ALTC;\n\n }\n\n if (!this.isAltitudeLocked && (this.currentVerticalActiveState === VerticalNavModeState.ALTC || this.currentVerticalActiveState === VerticalNavModeState.ALT)) {\n if (this.vPathState === VPathState.ACTIVE) {\n this.currentVerticalActiveState = VerticalNavModeState.PATH;\n }\n else {\n this.currentVerticalActiveState = VerticalNavModeState.PTCH;\n }\n }\n this.setProperVerticalArmedStates();\n }", "handleAlt1Changed() {\n if (this._inputDataStates.selectedAlt1.state < 0) {\n this.selectedAlt1 = 0;\n Coherent.call(\"AP_ALT_VAR_SET_ENGLISH\", 1, 0);\n } else {\n this.selectedAlt1 = this._inputDataStates.selectedAlt1.state;\n }\n \n if (this.currentVerticalActiveState === VerticalNavModeState.ALT || this.currentVerticalActiveState === VerticalNavModeState.ALTC) {\n SimVar.SetSimVarValue(\"K:ALTITUDE_SLOT_INDEX_SET\", \"number\", 3);\n }\n \n this.setProperVerticalArmedStates();\n }", "handleAltCaptured() {\n if (this.isAltitudeLocked) {\n this.currentVerticalActiveState = VerticalNavModeState.ALT;\n if (SimVar.GetSimVarValue(\"AUTOPILOT VS SLOT INDEX\", \"number\") != 1) {\n SimVar.SetSimVarValue(\"K:VS_SLOT_INDEX_SET\", \"number\", 1);\n }\n if (SimVar.GetSimVarValue(\"AUTOPILOT ALTITUDE SLOT INDEX\", \"number\") != 3) {\n SimVar.SetSimVarValue(\"K:ALTITUDE_SLOT_INDEX_SET\", \"number\", 3);\n }\n\n //MOVED SETTING 0 VS rates from ALT CAP TO ALT CAPTURED\n if (SimVar.GetSimVarValue(\"AUTOPILOT VERTICAL HOLD VAR:1\", \"feet per minute\") != 0) {\n Coherent.call(\"AP_VS_VAR_SET_ENGLISH\", 1, 0);\n }\n if (SimVar.GetSimVarValue(\"AUTOPILOT VERTICAL HOLD VAR:2\", \"feet per minute\") != 0) {\n Coherent.call(\"AP_VS_VAR_SET_ENGLISH\", 2, 0);\n }\n }\n }", "handleAltSlotChanged() {\n this.currentAltSlotIndex = this._inputDataStates.altSlot.state;\n // console.log(\"alt slot changed to: \" + this.currentAltSlotIndex);\n\n //Prevent sim from changing to alt slot 1 automatically if we're trying to drive via\n //VNAV and PATH\n if (this.currentAltSlotIndex === 1 && this.vPathState === VPathState.ACTIVE && (this.isVNAVOn === true || this.currentVerticalActiveState === VerticalNavModeState.GP)) {\n console.log(\"alt slot changed to 2 for path\");\n SimVar.SetSimVarValue(\"K:ALTITUDE_SLOT_INDEX_SET\", \"number\", 2);\n this.currentAltSlotIndex = 2;\n }\n\n this.setProperVerticalArmedStates();\n }", "onKeyDown(key, input) {\n if (this.dialogueOpen) {\n return;\n }\n\n if (!this.file) return false;\n if (input.isKeyDown(\"Alt\")) return false;\n\n // iterate tools\n for (let tool of this.tools) {\n // if hotkey belongs to tool, switch to the tool\n if (tool.hotkey === key) {\n this.file.doAction(SetTool, tool);\n EventBus.$emit(\"try-selecting-tool\", tool.name);\n return true;\n }\n\n // if spicykey belongs to tool, switch to the tool until key is released\n if (tool.spicykey === key) {\n this.file.spicy = this.file.selectedTool;\n this.file.doAction(SetTool, tool);\n EventBus.$emit(\"try-selecting-tool\", tool.name);\n return true;\n }\n }\n }", "canHandle(handlerInput) {\n\n const attributesManager = handlerInput.attributesManager;\n const sessionAttributes = attributesManager.getSessionAttributes();\n\n const slots = [\"timeOfDay\", \"cuisine\", \"allergies\", \"diet\"]; // the meal recommendations are based on these factors and can only be done once they have been given by the user\n \n console.log('SuggestMealRecommendationIntent - meals:', sessionAttributes.recommendations.current.meals.length); //I suspect this logs how many meals are recommended but am not sure\n console.log('SuggestMealRecommendationIntent - meals:', JSON.stringify(sessionAttributes.recommendations.current.meals)); // this logs the meal recommendations\n\n return handlerInput.requestEnvelope.request.type === 'IntentRequest' // 5 conditions needed to be able to fulfil this intent\n && handlerInput.requestEnvelope.request.intent.name === 'RecommendationIntent'\n && !handlerInput.requestEnvelope.request.intent.slots.meal.value // no meal suggestion exist yet\n && intentSlotsHaveBeenFilled(handlerInput.requestEnvelope.request.intent, slots) // all slots have been filled\n && !intentSlotsNeedDisambiguation(handlerInput.requestEnvelope.request.intent, slots); // not sure what Disambiguation is\n }", "is_special_key(event){\n var allowable_is_special_key = [8,35,36,37,38,39,40,46, 9, 27, 13, 110, 116,115];\n var key = event.which || event.keyCode || event.charCode;\n var is_special = allowable_is_special_key.includes(key);\n //if ctrl+a or alt+a is down do not prevent\n var is_special_a = key === 65 && (event.ctrlKey === true || event.metaKey === true)\n //if meta+shift+a or alt+a is down do not prevent\n var is_special_r = key === 82 && (event.shiftKey === true || event.metaKey === true)\n if(is_special || is_special_a || is_special_r ){\n return true;\n }\n return false;\n }", "handleElectron4SpellCheck(text) {\n if (!this.currentSpellchecker) return true;\n\n if (isMac) {\n return !this.isMisspelled(text);\n }\n\n this.spellCheckInvoked.next(true);\n\n let result = this.isMisspelled(text);\n if (result) this.spellingErrorOccurred.next(text);\n return !result;\n }", "function altTextAnalysis(altText) {\n var regEx_redundantPhrase = /(image of|photo of|picture of|graphic of|photograph of)/g;\n var regEx_fileTypeExt = /\\.(png|jpg|jpeg|gif|pdf|doc|docx|svg)$/g;\n var regEx_nonDescAlt = /^(photo|photograph|picture|graphic|logo|icon|graph|image)$/g;\n\n if (altText !== \"\") {\n altText = altText.toLowerCase();\n if (regEx_redundantPhrase.test(altText)) { //check for redundant phrase in alt text\n alert = [alert_0174]; //redundant phrase in alt text\n } else if (regEx_fileTypeExt.test(altText)) { //Check for filename in alt text\n alert = [alert_0175]; //file name in alt text\n } else if (regEx_nonDescAlt.test(altText)) { //Check for non-descriptive alt text\n alert = [alert_0176]; //non-descriptive alt text\n }\n }\n }", "function $ffc54430b1dbeee65879852feaaff07d$var$isVirtualClick(event) {\n // JAWS/NVDA with Firefox.\n if (event.mozInputSource === 0 && event.isTrusted) {\n return true;\n }\n\n return event.detail === 0 && !event.pointerType;\n}", "function hasShortcutModifier(charModifier, currentModifiers) {\n var mods = {};\n for (var key in currentModifiers) {\n if (parseInt(key) !== XK_Shift_L) {\n mods[key] = currentModifiers[key];\n }\n }\n\n var sum = 0;\n for (var k in currentModifiers) {\n if (mods[k]) {\n ++sum;\n }\n }\n if (hasCharModifier(charModifier, mods)) {\n return sum > charModifier.length;\n }\n else {\n return sum > 0;\n }\n }", "_calculateTargetedAltitude() {\n if (this.mcp.autopilotMode !== MCP_MODE.AUTOPILOT.ON) {\n return;\n }\n\n if (this.flightPhase === FLIGHT_PHASE.LANDING) {\n return this._calculateTargetedAltitudeDuringLanding();\n }\n\n switch (this.mcp.altitudeMode) {\n case MCP_MODE.ALTITUDE.OFF:\n return this.altitude;\n\n case MCP_MODE.ALTITUDE.HOLD:\n return this.mcp.altitude;\n\n case MCP_MODE.ALTITUDE.APPROACH:\n return this._calculateTargetedAltitudeToInterceptGlidepath();\n\n // future functionality\n // case MCP_MODE.ALTITUDE.LEVEL_CHANGE:\n // return;\n\n // future functionality\n // case MCP_MODE.ALTITUDE.VERTICAL_SPEED:\n // return;\n\n case MCP_MODE.ALTITUDE.VNAV: {\n return this._calculateTargetedAltitudeVnav();\n }\n\n default:\n console.warn('Expected MCP altitude mode of \"OFF\", \"HOLD\", \"APPROACH\", \"LEVEL_CHANGE\", ' +\n `\"VERTICAL_SPEED\", or \"VNAV\", but received \"${this.mcp[MCP_MODE_NAME.ALTITUDE]}\"`);\n break;\n }\n }", "generateInputDataEvents() {\n for (var key in this._inputDataStates) {\n const event = this._inputDataStates[key].updateState();\n\n if (event !== undefined) {\n this.queueEvent(event);\n }\n }\n\n if (this.currentVerticalActiveState === VerticalNavModeState.ALTC) {\n const currentAltitude = SimVar.GetSimVarValue(\"INDICATED ALTITUDE\", \"feet\");\n const targetAltitude = SimVar.GetSimVarValue(\"AUTOPILOT ALTITUDE LOCK VAR:3\", \"feet\");\n\n if (Math.abs(currentAltitude - targetAltitude) < 50) {\n this.queueEvent(NavModeEvent.ALT_CAPTURED);\n }\n }\n\n const planVersion = SimVar.GetSimVarValue(\"L:WT.FlightPlan.Version\", \"number\");\n if (planVersion != this.currentPlanVersion) {\n this.currentPlanVersion = planVersion;\n\n const approach = this.flightPlanManager.getApproach();\n if (approach && approach.name !== this.currentApproachName) {\n this.currentApproachName = approach.name;\n this.queueEvent(NavModeEvent.APPROACH_CHANGED);\n }\n else if (this.flightPlanManager.getFlightPlan(0).procedureDetails.destinationRunwayIndex !== -1) {\n this.currentApproachName = 'VISUAL';\n this.queueEvent(NavModeEvent.APPROACH_CHANGED);\n }\n }\n }", "function handleInput(e)\n{\n\tconsole.info(\"A key was pressed: \" + e.keyCode);\n}", "function CLC_SR_SpeakARIAWidgetEvents_EventAnnouncer(event){\r\n if (!CLC_SR_Query_SpeakEvents()){\r\n return;\r\n }\r\n //For an element that the user has to be focused on to control,\r\n //then if the user has speak events turned on it means that the \r\n //element will be the CLC_SR_CurrentAtomicObject since that is\r\n //updated when a focused object is spoken. Therefore, if the\r\n //event target is the same as CLC_SR_CurrentAtomicObject,\r\n //then an attr change was probably caused by the user and the \r\n //change should be announced.\r\n if ( (CLC_SR_CurrentAtomicObject == event.target) && \r\n ((event.attrName == \"checked\") || (event.attrName == \"valuenow\") || (event.attrName == \"activedescendant\")) ){\r\n CLC_SR_SpeakEventBuffer = CLC_GetStatusFromRole(event.target);\r\n CLC_SR_Stop = true; \r\n window.setTimeout(\"CLC_Shout(CLC_SR_SpeakEventBuffer,1);\", 0);\r\n }\r\n\r\n //Try to do something more elegant with tree items, but this works for now.\r\n if (event.attrName == \"expanded\"){\r\n CLC_SR_GoToAndRead(event.target);\r\n }\r\n }", "function isNotProductAction(event) {\n return (\n event.EventCategory ===\n mParticle.CommerceEventType.ProductImpression ||\n event.EventCategory === mParticle.CommerceEventType.PromotionView ||\n event.EventCategory === mParticle.CommerceEventType.PromotionClick\n );\n }", "function is_alpn_available() {\n return binding_1.default.is_alpn_available();\n}", "function processInput() {\r\n\t\r\n\tvar time = 500;\r\n\tif (isAnswer()) {\r\n\t\tconsole.log('isAnswer');\r\n\t\r\n\t} else if(isRepeat()){\r\n\t\tconsole.log('isRepeat');\r\n\t\t\r\n\t} else if (isTrigger()) {\r\n\t\tconsole.log('isTrigger');\r\n\t\t\r\n\t} else if (includeKey()) {\r\n\t\tconsole.log('includeKey');\r\n\t\t\r\n\t} else if (isShort()) {\r\n\t\t//return;\r\n\t\tconsole.log('isShort');\r\n\t} else if (noReaction()) {\r\n\t\treturn;\r\n\t} else {\r\n\t\tconsole.log('notUnderstood');\r\n\t\tnotUnderstood();\r\n\t}\r\n\t\r\n\tvar read = userInput.current.length*50;\r\n\t\r\n\t//setTimeout(showWriting,read);\r\n\t\r\n\ttime += Math.ceil((Math.random()*500)-250);\r\n\tif (botAction.repeat()){\r\n\t\tinputState(true);\r\n\t} else {\t\r\n\t\tsetTimeout(processAllActions,read+time);\r\n\t}\r\n\t\r\n\tuserInput.last = userInput.format;\r\n}", "function wasCmdFromTagMenu()\n {\n var elt;\n\n // Commands can only be fired from the tag menu via the context menu\n // => document.popupNode exists. onpopupshowing for the corresponding\n // popups here in the sidebar, we manually set popupNode to null.\n elt= document.popupNode;\n if (!elt) return false;\n return ((elt.hasAttribute(\"bmt-bmid\") &&\n elt.localName === \"menuitem\") ||\n (elt.hasAttribute(\"bmt-tagid\") &&\n elt.localName === \"menu\"));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drink options for the app
get drinkOptions() { return [ { label: 'Apple juice', value: 'Apple juice' }, { label: 'Lemonade', value: 'Lemonade' }, { label: 'Ice Tea', value: 'Ice Tea' }, { label: 'Cola', value: 'Cola' }, { label: 'Diet Cola', value: 'Diet Cola' }, ]; }
[ "function enableDrinkOptions() {\r\n // Enable the 'take a sip' button.\r\n let drink = document.getElementById(\"drink\");\r\n drink.disabled = false;\r\n drink.onclick = drinkCoffee;\r\n\r\n // Enable 'cream','sugar', 'submit' buttons.\r\n let cream = document.getElementById(\"addcream\");\r\n let sugar = document.getElementById(\"addsugar\");\r\n let post = document.getElementById(\"submitcombination\");\r\n\r\n cream.disabled = false;\r\n cream.onclick = addCream;\r\n\r\n sugar.disabled = false;\r\n sugar.onclick = addSugar;\r\n\r\n post.disabled = false;\r\n post.onclick = postCoffee;\r\n }", "function addDrink(){\n \"use strict\";\n \n // Gets the chosen tea and milk from the dropdowns\n var teaIndex = getOptionIndex(\"tea\", teaOptions[0]);\n var milkIndex = getOptionIndex(\"milk\", milkOptions[0]);\n \n // Creates a new Drink and adds it to the drinks array\n drinks.push(new Drink(teaOptions[0][teaIndex], toppingList, milkOptions[0][milkIndex]));\n \n // Update the page\n updatePage();\n}", "get dessertOptions() {\n return [\n { label: 'Nothing for me, thanks!', value: 'Nothing for me, thanks!' },\n { label: 'Brownie', value: 'Brownie' },\n { label: 'Cupcake(Red Velvet)', value: 'Cupcake(Red Velvet)' },\n { label: 'Cupcake(Chocolate)', value: 'Cupcake(Chocolate)' },\n { label: 'Cupcake(Vanilla)', value: 'Cupcake(Vanilla)' },\n { label: 'Cookie(Chocolate Chip)', value: 'Cookie(Chocolate Chip)' },\n { label: 'Cookie(Oatmeal Raisin)', value: 'Cookie(Oatmeal Raisin)' },\n { label: 'Cookie(Peanut Butter)', value: 'Cookie(Peanut Butter)' },\n { label: 'Watermelon)', value: 'Watermelon' }\n ];\n }", "function BookOptions() {\n angular.extend(this, {\n desirability: 1.0,\n maxprice: 4.00,\n condition: 'Good',\n excludeLibrary: true,\n excludeCliffsNotes: true\n });\n }", "function Drink(teaType, toppingsList, milkOption){\n \"use strict\";\n \n this.teaType = teaType;\n this.toppingsList = toppingsList.slice();\n this.milkOption = milkOption;\n}", "options (config = {}) {\n return session.options(CUSTOMER_REVIEW, config)\n }", "function openOptionsPage() {\n runtime.openOptionsPage();\n}", "_setCompatibilityOptions() {\n // Convert the product config to a placement configuration\n this.config.backwards = 'Ad';\n this.config.type = okanjo.Placement.ContentTypes.products;\n\n // Id / single mode is now ids\n this.config.url = null;\n if (this.config.id) {\n this.config.ids = [this.config.id];\n } else {\n okanjo.warn('Ad widget should have parameter `id` set.');\n }\n this.config.take = 1;\n delete this.config.id;\n\n // Content is automatically determined whether the placement element contains children\n delete this.config.content;\n }", "get grindOption() {\n return 'select#grindOption'\n }", "function drawOptions() {\n\t\t\tvar ui = newElement('div', { id: 'adi-opts-view', class: 'adi-hidden' }),\n\t\t\t\thead1 = newElement('span', { class: 'adi-opt-heading' }),\n\t\t\t\thead2 = newElement('span', { class: 'adi-opt-heading' }),\n\t\t\t\tclose = newElement('span', { class: 'adi-opt-close' });\n\n\t\t\thead1.textContent = 'General options';\n\t\t\thead2.textContent = 'Observed nodes';\n\n\t\t\tui.appendChild(head1);\n\t\t\tui.appendChild(drawOptionRow('saving', 'Enable saving of settings'));\n\t\t\tui.appendChild(drawOptionRow('makeVisible', 'Scroll to the active element in DOM View'));\n\t\t\tui.appendChild(drawOptionRow('omitEmptyText', 'Hide empty text nodes'));\n\t\t\tui.appendChild(drawOptionRow('foldText', 'Fold the text nodes'));\n\t\t\tui.appendChild(drawOptionRow('transparent', 'Enable transparent background'));\n\t\t\tui.appendChild(head2);\n\t\t\tui.appendChild(drawOptionRow('nodeTypes-3', 'Text node'));\n\t\t\tui.appendChild(drawOptionRow('nodeTypes-8', 'Comment node'));\n\t\t\t// ui.appendChild(drawOptionRow('nodeTypes-1', 'Element node'));\n\t\t\t// ui.appendChild(drawOptionRow('nodeTypes-9', 'Document node'));\n\t\t\tui.appendChild(close);\n\n\t\t\treturn ui;\n\t\t}", "get mealOptions() {\n return [\n { label: 'Salad(vegan)', value: 'Salad(vegan)' },\n { label: 'Salad(veggie)', value: 'Salad(veggie)' },\n { label: 'Sandwich(Chicken)', value: 'Sandwich(Chicken)' },\n { label: 'Sandwich(Chicken,Gluten-free)', value: 'Sandwich(Chicken,Gluten-free)' },\n { label: 'Sandwich(Veggie)', value: 'Sandwich(Veggie)' },\n { label: 'Sandwich(Veggie,Gluten-free)', value: 'Sandwich(Veggie,Gluten-free)' }\n ];\n }", "function changeSideAndDrinks(){\n\t\t\n\t\tvar mealCombo = document.getElementById(\"meal-combo\").value; // Meal Selection\n\n\t\tvar sideSelection = document.getElementById(\"side-selection\"); //Side Selection - ADD ENHANCEMENT, change on the fly based off meal combo\n\t\tvar drinkSelection = document.getElementById(\"drink-selection\"); //Drinks Selection - ADD ENHANCEMENT, change on the fly based off meal combo\n\n\t\t\n\t\t/* Drop Box Arrays */\n\t\t\tvar selectFlash = [[\"Chili Cheese Flash Fries\", \"Vibe's Spicy Shaker Fries\", \"Frost's Snow Soft Mash\"],[\"Large Coke\",\"Large Pepsi\",\"A bottle of Harry's Beer\"]]\n\t\t\tvar selectArrow = [[\"Green Arrow's Baked Potatoes\", \"Queen's Chips\", \"Thea Queen's Pasta\"],[\"Large Coke\",\"Large Pepsi\",\"A Bottle of the Queen's Wine\"]]\n\t\t\tvar selectSMan = [[\"Kent Farm Mac'n'Cheese\", \"Louis Lane's Super Mash\", \"Metropolis Cheese Fries\"],[\"Large Coke\",\"Large Pepsi\",\"A bottle of Smallville Wineries Wine\",\"A bottle of Kent Farm Beer\"]]\n\t\t\tvar selectSGirl = [[\"Al's Dive Bar Vegan Chips\", \"Martian Boild Potato Slices\", \"Kat Co. Olives\"], [\"Large Coke\",\"Large Pepsi\",\"A bottle of National City Wineries Wine\",\"A bottle of Al's Dive Bar Black Beer\"]]\n\n\t\t\tvar sidePara = document.getElementById(\"sides-paragraph\")\n\t\t\tvar drinkPara = document.getElementById(\"drinks-paragraph\")\n\t\t\tsidePara.hidden = false;\n\t\t\tdrinkPara.hidden = false;\n\n\n\n\n\t\t/* If Statements - Checks combo selections, and dynamically changes behavior of form */\n\t\t\t/* Hides Side and Drink options when nothing is selected */\t\n\t\t\tif (mealCombo == \"\"){\n\t\t\t\tsidePara.hidden = true;\n\t\t\t\tdrinkPara.hidden = true;\n\t\t\t}\n\n\t\t\t/* When Big Belly Flash Burger is selected */\n\t\t\tif (mealCombo == \"Big Belly Flash Burger Combo\"){\t\t\n\t\t\t\tclearSelects(drinkSelection)\n\t\t\t\tclearSelects(sideSelection)\n\t\t\t\tfor (var index = 0; index < selectFlash[index].length; index ++){\n\t\t\t\t\t/* Prints Out Sides Selection */\n\t\t\t\t\tif (index == 0){\n\t\t\t\t\t\tfor (var j = 0; j < selectFlash[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectFlash[index][j]\n\t\t\t\t\t\t\toption.text = selectFlash[index][j]\n\t\t\t\t\t\t\tsideSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\t/* Prints Out Drinks Selection */\n\t\t\t\t\tif (index == 1){\n\t\t\t\t\t\tfor (var j = 0; j < selectFlash[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectFlash[index][j]\n\t\t\t\t\t\t\toption.text = selectFlash[index][j]\n\t\t\t\t\t\t\tdrinkSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* When Green Arrow Seabass is selected */\n\t\t\tif (mealCombo == \"Green Arrow Seabass Combo\"){\n\t\t\t\tclearSelects(drinkSelection)\n\t\t\t\tclearSelects(sideSelection)\n\t\t\t\tfor (var index = 0; index < selectArrow[index].length; index ++){\n\t\t\t\t\t/* Prints Out Sides Selection */\n\t\t\t\t\tif (index == 0){\n\t\t\t\t\t\tfor (var j = 0; j < selectArrow[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectArrow[index][j]\n\t\t\t\t\t\t\toption.text = selectArrow[index][j]\n\t\t\t\t\t\t\tsideSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t/* Prints Out Drinks Selection */\n\t\t\t\t\tif (index == 1){\n\t\t\t\t\t\tfor (var j = 0; j < selectArrow[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectArrow[index][j]\n\t\t\t\t\t\t\toption.text = selectArrow[index][j]\n\t\t\t\t\t\t\tdrinkSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* When Krypton Beef Steak is selected */\n\t\t\tif (mealCombo == \"Krypton Beef Steak Combo\"){\n\t\t\t\tclearSelects(drinkSelection)\n\t\t\t\tclearSelects(sideSelection)\n\t\t\t\t/* Prints Out Sides Selection */\n\t\t\t\tfor (var index = 0; index < selectSMan[index].length; index ++){\n\t\t\t\t\tif (index == 0){\n\t\t\t\t\t\tfor (var j = 0; j < selectSMan[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectSMan[index][j]\n\t\t\t\t\t\t\toption.text = selectSMan[index][j]\n\t\t\t\t\t\t\tsideSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t/* Prints Out Drinks Selection */\n\t\t\t\t\tif (index == 1){\n\t\t\t\t\t\tfor (var j = 0; j < selectSMan[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectSMan[index][j]\n\t\t\t\t\t\t\toption.text = selectSMan[index][j]\n\t\t\t\t\t\t\tdrinkSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* When Supergirl's Vegetarian Combo is selected */\n\t\t\tif (mealCombo == \"Supergirl's Vegetarian Combo\"){\n\t\t\t\tclearSelects(drinkSelection)\n\t\t\t\tclearSelects(sideSelection)\n\t\t\t\t/* Prints Out Sides Selection */\n\t\t\t\tfor (var index = 0; index < selectSGirl[index].length; index ++){\n\t\t\t\t\tif (index == 0){\n\t\t\t\t\t\tfor (var j = 0; j < selectSGirl[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectSGirl[index][j]\n\t\t\t\t\t\t\toption.text = selectSGirl[index][j]\n\t\t\t\t\t\t\tsideSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t/* Prints Out Drinks Selection */\n\t\t\t\t\tif (index == 1){\n\t\t\t\t\t\tfor (var j = 0; j < selectSGirl[index].length; j++){\n\t\t\t\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\t\t\t\toption.value = selectSGirl[index][j]\n\t\t\t\t\t\t\toption.text = selectSGirl[index][j]\n\t\t\t\t\t\t\tdrinkSelection.appendChild(option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t}", "function managerOptions() {\n // prompt for options available \n inquirer\n .prompt(\n {\n name: \"action\",\n type: \"list\",\n message: \"What would you like to do?\",\n choices: [\n \"View Products for Sale\",\n \"View Low Inventory\",\n \"Add to Inventory\",\n \"Add New Product\",\n \"Exit Menu\"\n ]\n }\n )\n .then(function (answer) {\n switch (answer.action) {\n case \"View Products for Sale\":\n viewProducts();\n break;\n\n case \"View Low Inventory\":\n lowQuantity();\n break;\n\n case \"Add to Inventory\":\n addInventory();\n break;\n\n case \"Add New Product\":\n addProduct();\n break;\n case \"Exit Menu\":\n exitMenu();\n break;\n }\n });\n}", "function flavour1(){\n flavourSelect=[\"flavour1\", 100];\n }", "function widgetOptions(id){\n\n }", "function supervisorView() {\n console.log('\\r\\n');\n inquirer\n .prompt(\n {\n name: \"supervisorOptions\",\n type: \"list\",\n message: \"Please select an option from the following list: \\r\\n\",\n choices: [\n \"View Product Sales by Department\",\n \"Create New Department\"\n ]\n\n })\n .then(function (answer) {\n switch (answer.supervisorOptions) {\n case \"View Product Sales by Department\":\n viewProductsSalesByDept();\n break;\n\n case \"Create New Department\":\n createNewDept();\n break;\n }\n })\n}", "function tShirtColor() {\n if (designSelector.value === \"Select Theme\") {\n colorListDiv.style.visibility = \"hidden\";\n } else if (designSelector.value === \"js puns\") {\n showColorOptions(puns);\n } else if (designSelector.value === \"heart js\") {\n showColorOptions(heart);\n }\n}", "options(params) {\n if(!params) {\n return {\n provider: _currentProvider,\n customProvider: customProvider,\n depth: depth,\n weight: weight,\n spamSeed: spamSeed,\n message: message,\n tag: tag,\n numberOfTransfersInBundle: numberOfTransfersInBundle,\n isLoadBalancing: optionsProxy.isLoadBalancing\n }\n }\n if(params.hasOwnProperty(\"provider\")) {\n _currentProvider = params.provider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"customProvider\")) {\n customProvider = params.customProvider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"depth\")) { depth = params.depth }\n if(params.hasOwnProperty(\"weight\")) { weight = params.weight }\n if(params.hasOwnProperty(\"spamSeed\")) { spamSeed = params.spamSeed }\n if(params.hasOwnProperty(\"message\")) { message = params.message }\n if(params.hasOwnProperty(\"tag\")) { tag = params.tag }\n if(params.hasOwnProperty(\"numberOfTransfersInBundle\")) { numberOfTransfersInBundle = params.numberOfTransfersInBundle }\n if(params.hasOwnProperty(\"isLoadBalancing\")) { optionsProxy.isLoadBalancing = params.isLoadBalancing }\n if(params.hasOwnProperty(\"onlySpamHTTPS\")) { onlySpamHTTPS = params.onlySpamHTTPS }\n }", "function addDrinks(args) {\r\n let drink = args[2].toLowerCase();\r\n let url = args[3];\r\n db.get(\"drinks\").push({ drink: drink, gif: url }).write();\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
use this function to use the world open food api
function getFoodInformation(Ean) { //https://world.openfoodfacts.org/api/v0/product/ var opts = { hostname: 'world.openfoodfacts.org', path: '/api/v0/product/' + Ean, method: 'GET', headers: { 'connection': 'keep-alive', "Content-Type": "application/json", } }; console.log(opts.hostname + opts.path); var req = https.request(opts, function (res) { res.on('data', function (d) { // console.log(d); }); }); req.end(); }
[ "function getAPIdata() {\n \n var url = \"https://api.openweathermap.org/data/2.5/forecast\";\n var apiKey =\"b93f0214e63748be2fedba711c6f1709\";\n var city = \"florida\";\n\n //Test OWM weaterlayers\n //var weatherLayer = \"https://tile.openweathermap.org/map/{clouds_new}/10/5/5.png?appid={b93f0214e63748be2fedba711c6f1709}\";\n\n // construct request\n var request = url + \"?\" + \"appid=\" + apiKey + \"&\" + \"q=\" + city;\n \n // get weather forecast\n fetch(request)\n\n // parse to JSON format\n .then(function(response) {\n return response.json();\n })\n \n // render weather per day\n .then(function(response) {\n\n // render weatherCondition\n onAPISucces(response);\n })\n \n // catch error\n .catch(function (error) {\n // onAPIError();\n console.error('Request failed', error);\n });\n }", "function getFoodInfo(meal_id, unirest, callback)\n\t{\n let foodData = {};\n foodData[\"mid\"] = meal_id;\n console.log(`Getting info for ${meal_id}`)\n\t\tunirest.get(`https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/${meal_id}/information?includeNutrition=true`)\n\t\t.header(\"X-RapidAPI-Key\", \"62649045e6msh29f8aefde649a9bp1591edjsnf389cd9bbedf\")\n\t\t.end(function(results) {\n\t\t // Store nutritional info\n for (let nutrient of results.body.nutrition.nutrients)\n {\n if (nutrient.title.toLowerCase() === 'calories')\n foodData[\"calories\"] = Math.round(nutrient.amount);\n if (nutrient.title.toLowerCase() === 'protein')\n foodData[\"protein\"] = Math.round(nutrient.amount);\n if (nutrient.title.toLowerCase() === 'carbohydrates')\n foodData[\"carbs\"] = Math.round(nutrient.amount);\n if (nutrient.title.toLowerCase() === 'fat')\n foodData[\"fats\"] = Math.round(nutrient.amount);\n }\n foodData[\"imagelink\"] = results.body.image;\n foodData[\"title\"] = results.body.title;\n foodData[\"link\"] = results.body.sourceUrl;\n foodData[\"slink\"] = results.body.spoonacularSourceUrl;\n foodData[\"vegetarian\"] = results.body.vegetarian;\n foodData[\"glutenfree\"] = results.body.glutenFree;\n foodData[\"vegan\"] = results.body.vegan;\n foodData[\"dairyfree\"] = results.body.dairyFree;\n foodData[\"ketogenic\"] = results.body.ketogenic;\n\n // Get and store price info\n\t\t let recipeStr = \"\";\n for (let ingredient of results.body.extendedIngredients)\n recipeStr += ingredient.originalString + \"\\n\";\n\n unirest.post(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/visualizePriceEstimator\")\n .header(\"X-RapidAPI-Key\", \"62649045e6msh29f8aefde649a9bp1591edjsnf389cd9bbedf\")\n .header(\"Accept\", \"text/html\")\n .header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n .send(\"defaultCss=true\")\n .send(\"mode=1\")\n .send(\"showBacklink=false\")\n .send(`ingredientList=${recipeStr}`)\n .send(\"servings=1\")\n .end(function(results){\n const priceRegex = /(?:Cost per Serving: )(\\$\\d+\\.\\d\\d)/;\n let res = priceRegex.exec(results.body);\n if (res !== null && typeof res !== 'undefined' && res.length > 1)\n foodData[\"price\"] = res[1];\n else\n {\n foodData[\"price\"] = \"$7.69\";\n console.log(\"ERROR:\\n\");\n console.log(results.body)\n }\n for (let key in foodData) {\n foodData[key] = sqlstr.escape(foodData[key]);\n }\n callback(foodData);\n });\n });\n\t}", "function callNearBySearchAPI() {\n //\n city = new google.maps.LatLng(coordinates.lat, coordinates.long);\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: city,\n zoom: 15,\n });\n //\n request = {\n location: city,\n radius: \"5000\", // meters\n type: [\"restaurant\"],\n // openNow: true,\n fields: [\n \"name\",\n \"business_status\",\n \"icon\",\n \"types\",\n \"rating\",\n \"reviews\",\n \"formatted_phone_number\",\n \"address_component\",\n \"opening_hours\",\n \"geometry\",\n \"vicinity\",\n \"website\",\n \"url\",\n \"address_components\",\n \"price_level\",\n \"reviews\",\n ],\n };\n //\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, getGooglePlacesData);\n //\n}", "function getAllFoodTrucks() {\n const URL = 'https://data.sfgov.org/resource/bbb8-hzi6.json?';\n\n axios.get(URL, {\n params: {\n $order: 'applicant ASC',\n $offset: 1000,\n $select: 'applicant, location, dayofweekstr, start24, end24',\n }\n })\n\n .then((response) => {\n const results = response.data;\n\n isOpen(results);\n\n return results;\n })\n .catch((error) => {\n console.log('Error:', error.message);\n });\n}", "function getWeather() {\n\n let inputVal = document.getElementById(\"location-input\").value;\n let url = \"\";\n let weather = new Object();\n\n if (hasNumber(inputVal)) {\n inputVal = inputVal.replace(/\\s/g, '');\n url = \"https://api.openweathermap.org/data/2.5/weather?zip=\" + inputVal + \"&appid=\" + APIKEY + \"&units=imperial\";\n } else {\n url = \"https://api.openweathermap.org/data/2.5/weather?q=\" + inputVal + \"&appid=\" + APIKEY + \"&units=imperial\";\n }\n\n fetch(url).then(response => response.json()).then(data => {\n\n weather = new Object();\n weather.name = data.name + \", \" + data.sys.country;\n weather.main = data.main;\n weather.wind = data.wind;\n weather.details = data.weather[0];\n locations.push(weather);\n makeWeatherCard(weather);\n\n })\n .catch(() => {\n msg.textContent = \"Locatioin not found. Please try another location\";\n });\n\n}", "function findFoods() {\n\n// userRequest will taken in the client information and ask them to type in what they are serching for \n let userRequest = document.getElementById('userRequest').value\n if(userRequest === '') {\n return alert('Please enter an ingrediant for query')\n }\n\n // Here we are delivering what we have found from the WebService\n // All Possible options that have been listed ae what we are able to get from the API \n // The API Has been provided in the assingment document files \n let RequestRecipe = document.getElementById('foundInformation')\n RequestRecipe.innerHTML = ''\n\n// Here we loggining into our documents what we have done \n document.getElementById('userRequest').value = '';\n \n // Here we are completing our HTTP Request\n // We are seeing if the responce is valid \n // If the responce if valid we are giving the client the correct information \n // Our for loop will complete all of this \n let myRequest = new XMLHttpRequest()\n myRequest.onreadystatechange = () => {\n if (myRequest.readyState == 4 && myRequest.status == 200) {\n let response = JSON.parse(myRequest.responseText) \n let foundInformation = response.foundInformation;\n\n // Here we are making sure that we are not over working the server, this was one of the major assingment requirments \n // We are also making sure that we arent requestig too much data at one instatance \n for(let i = 0; i < foundInformation.length; i++){\n RequestRecipe.innerHTML = RequestRecipe.innerHTML + `\n <ul>\n <li><a href=\"${foundInformation[i].f2f_url}\" target=\"_blank\"> <img src=\"${foundInformation[i].image_url}\"> </a></li>\n <li>${foundInformation[i].title}</li>\n </ul>\n `\n }\n }\n }\n\n // Here we are getting the reponce and making sure that all the correct content has been delivered \n myRequest.open('GET', `/recipe?userRequest=${userRequest}`, true)\n myRequest.send()\n}", "function requestFoodTruckData(callback) {\n var path = '/services/daily_schedule?appKey=' + appKey;\n var req = http.request({hostname : 'www.chicagofoodtruckfinder.com', path: path}, function(res) {\n var responseData = '';\n res.on('data', function(chunk) {\n responseData += chunk;\n });\n res.on('end', function() {\n callback(JSON.parse(responseData));\n });\n });\n req.on(\"error\", function(e) {\n console.log(\"Problem contacting food truck finder: \" + e.message);\n });\n req.end();\n}", "function get_tray_info(rid) {\n var url = 'http://foodbot.ordr.in:8000/TextSearch?rid='+rid+'&target=pizza pie';\n request({\n url: url,\n json: true\n }, function (error, response, body) {\n if (!error && response.statusCode === 200) {\n for(var i=0; i<body.length; i++){\n if(body[i].tray){\n tray = body[i].tray;\n price = body[i].price;\n place_pizza_order(rid,tray,price);\n break;\n }\n }\n }\n else{\n console.log(error);\n }\n });\n\n}", "function createWeatherURL() {\n weatherURL = \"https://api.openweathermap.org/data/2.5/weather?q=\" + city + \",\" + region + \",\" + country + \"&units=imperial&appid=\" + APIKey\n}", "function foodFactory(localFood, apiFood) {\n return `\n <div class=\"Item\">\n <h2>${localFood.name}</h2>\n <h3>${localFood.ethnicity}</h3>\n <p>${localFood.category}</p>\n <p>Country: ${apiFood.product.countries}</p>\n <p>Calories: ${apiFood.product.nutriments.energy_serving}</p>\n <p>Fat: ${apiFood.product.nutriments.fat_serving}</p>\n <p class=\"ingredients\">Ingredients: ${apiFood.product.ingredients_text}</p>\n </div>\n `;\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 petfinderCall() {\n var pf = new petfinder.Client({ apiKey: petfinderKey, secret: petfinderSecret });\n\n pf.animal.search({\n location: userSearch,\n type: \"dog\",\n distance: 15,\n limit: 100\n })\n .then(function (response) {\n //// Original array to pull data. \n animalsArr = response.data.animals;\n populateDogCards(animalsArr);\n })\n .catch(function (error) {\n // Handle the error\n console.log(error);\n });\n }", "function getWeather() {\n\tif (searchBox.getPlaces().length > 0)\n\t{\n\t\tvar loc = searchBox.getPlaces().pop();\n\t\tvar latLon = loc.geometry.location.lat() + \",\" + loc.geometry.location.lng();\n\t\tgetCity(latLon);\n\t\tgetForecast(latLon);\n\t}\n\telse {\n\t\talert(\"Could not retrieve location. Please enter a new location\");\n\t}\n}", "function getWeather( lat, lon ) {\n let key = '9425b5446dc273556c5b70a438f84526';\n fetch('https://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&units=imperial' + '&appid=' + key )\n .then(function(resp) {\n return resp.json();\n })\n .then(function(data) {\n insertWeatherData(data);\n })\n storeCityLocal(userInput.value);\n removeButtons();\n getStoredCities();\n}", "function printOpenWeatherMapsLocationHint () {\n console.log(' \"location\" contains get parameters to send to api.openweathermap.org/2.5/forecast to specify forecast location')\n console.log(' Valid key value pairs are:')\n console.log(' \"q\": \"CITY_NAME,ISO_3166_COUNTRY_CODE\"')\n console.log(' OR')\n console.log(' \"id\": \"CITY_ID\"')\n console.log(' OR')\n console.log(' \"lat\": \"LATITIUDE\",')\n console.log(' \"lon\": \"LONGITUDE\"')\n console.log(' OR')\n console.log(' \"zip\": \"ZIP_CODE,ISO_3166_COUNTRY_CODE\"')\n}", "function getFood() {\n var name=$(\"#txtSearch\").val();\n $.get(\"/search-food/\", {name: name, day: man_day}, function(data){\n setFood(man_day, data);\n });\n}", "function convertCityLatLong(inputCity){\n let directGeocodingAPI = 'https://api.openweathermap.org/geo/1.0/direct?q=' + inputCity + '&limit=5&appid=fe69a8ae1bfba9fa932a4b4358617cbf'\n fetch(directGeocodingAPI)\n .then(function(response){\n return response.json();\n })\n .then(function(data){\n var lat = data[0].lat\n var long = data[0].lon\n fiveDayForecastAPI(lat,long)\n })\n \n \n}", "getWeather (currentCity) {\n this.setState({ isLoading: ! this.state.isLoading })\n const apiKey = '1072dfe12c2f4f7e8ddfa30683df95ca';\n fetch(`https://api.weatherbit.io/v1.0/forecast/3hourly/geosearch?city=${currentCity}&days=1&key=${apiKey}`)\n .then( response => response.json())\n .then( response => {\n this.setState({ city: response.city_name,\n countryCode: response.country_code, \n items: response.data, \n error: false,\n temp: response.data[0].temp,\n isLoading: ! this.state.isLoading ,\n unit: 'C'})\n })\n //No response\n .catch( err => {\n this.setState({ error: true, isLoading: ! this.state.isLoading });\n })\n }", "function loadCity(){\n var url = 'http://api.openweathermap.org/data/2.5/weather?q='+cities.value()+\n '&APPID=f02124924447c73bc1d1626b1bee5f45&units=imperial';//set units=metric if you prefer Celcius\n loadJSON(url,setCity);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get one lottery for a league
function GetLottery(leagueId,lotteryId){ var urlLottery='http://bowling-api.nextcapital.com/api/leagues/'+leagueId+'/lotteries/'+'lotteryId'; return $http({ method: 'GET', url: urlLottery, headers: { 'Content-Type': 'application/json' }}); }
[ "function getGame(lobby) {\n return games.find(game => game.lobby === lobby);\n}", "static async getLatestGame(teamId) {\r\n let latestGame = {};\r\n\r\n const options = await {\r\n method: 'GET',\r\n url: `https://api-nba-v1.p.rapidapi.com/games/teamId/${teamId}`,\r\n headers: {\r\n 'x-rapidapi-key': NBA_API_KEY,\r\n 'x-rapidapi-host': 'api-nba-v1.p.rapidapi.com'\r\n }\r\n };\r\n\r\n await axios.request(options).then(res => {\r\n let games = res.data.api.games;\r\n for (let game of games.reverse()) {\r\n if (game.statusGame === 'Finished') {\r\n latestGame = game;\r\n break;\r\n }\r\n }\r\n });\r\n\r\n return latestGame;\r\n }", "function Lotto() {\n\t\t/**\n\t\t * The participants\n\t\t */\n\t\tthis.participants = [];\n\n\t\t/**\n\t\t * Add a participant.\n\t\t * @param participant The participant.\n\t\t * @param tickets The number of tickets held by the participant.\n\t\t */\n\t\tthis.add = function(participant, tickets) {\n\t\t\tthis.participants.push({ participant, tickets });\n\t\t\treturn this;\n\t\t};\n\n\t\t/**\n\t\t * Draw a winning participant.\n\t\t * @returns A winning participant.\n\t\t */\n\t\tthis.draw = function() {\n\t\t\t// We cannot do anything if there are no participants.\n\t\t\tif (!this.participants.length) {\n\t\t\t\tthrow \"cannot draw a lotto winner when there are no participants\";\n\t\t\t}\n\n\t\t\tconst pickable = [];\n\n\t\t\tthis.participants.forEach(({ participant, tickets }) => {\n\t\t\t\tfor (let ticketCount = 0; ticketCount < tickets; ticketCount++) {\n\t\t\t\t\tpickable.push(participant);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn getRandomItem(pickable);\n\t\t};\n\t}", "function getLeagues() {\n let url = \"/api/leagues\";\n $.getJSON(url, function(leagues) {\n $(\"#leaguecount\").html(leagues.length + \" Leagues!\");\n });\n }", "function pickWinner () {\n let pRnd = []\n\n for (key in this.players) {\n pRnd.push(this.players[key])\n }\n\n let ticket = Math.floor((Math.random() * pRnd.length) + 1)\n return pRnd[ticket]\n\n }", "function getTeam(number) {\n\t\t\t\tfor (var i = 0; i < teams.length; i++) {\n\t\t\t\t\tif (teams[i].number === number) {\n\t\t\t\t\t\treturn teams[i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar newTeam = new Team(number);\n\t\t\t\tteams.push(newTeam);\n\t\t\t\treturn newTeam;\n\t\t\t}", "function takeRoom(borrower_id){\n var ticket\n var available_room = ROOMS.find((room) => room.takeRoom(borrower_id))\n if (available_room != undefined){\n ticket = available_room.generateTicket()\n }\n return ticket\n}", "function yourLottoNbrs()\n {\n var nbr1, nbr2, nbr3, nbr4, nbr5, nbr6; //variables for 6 numbers\n {\n nbr1 = Math.floor(9 * Math.random());//random #1\n nbr2 = Math.floor(9 * Math.random());//random #2\n nbr3 = Math.floor(9 * Math.random());//random #3\n nbr4 = Math.floor(9 * Math.random());//random #4\n nbr5 = Math.floor(9 * Math.random());//random #5\n nbr6 = Math.floor(9 * Math.random());//random #6\n console.log(\"Your Lotto numbers for today are: \" + nbr1 + \" \" + nbr2 + \" \" + nbr3 + \" \" +\n nbr4 + \" \" + nbr5 + \" \" + nbr6 + \" .\");\n\n }\n }", "async function selectTeamFromAPI() {\n let competitionId;\n\n let competitions = await Api.getCompetitions();\n let captions = competitions.map((competition) => {\n return competition.caption;\n });\n let ids = competitions.map((competition) => {\n return competition.id;\n });\n let compIndex = readlineSync.keyInSelect(captions, \"\");\n\n if(compIndex === -1) {\n console.log('Bye!');\n process.exit();\n }\n\n console.log(`You selected ${captions[compIndex]} : ${ids[compIndex]}`);\n competitionId = ids[compIndex];\n\n let teams = await Api.getTeamsInCompetition(ids[compIndex]);\n\n captions = teams.map((team) => {\n return team.name;\n });\n\n ids = teams.map((team) => {\n //get id from url\n var re = /http:\\/\\/api.football-data.org\\/v1\\/teams\\/(\\d+)/;\n let matches = team._links.self.href.match(re);\n\n return matches[1];\n });\n\n let teamIndex = readlineSync.keyInSelect(captions, \"\");\n console.log(`You selected ${captions[teamIndex]} : ${ids[teamIndex]}`);\n\n return {teamId: parseInt(ids[teamIndex]), name: captions[teamIndex], competitionId: competitionId};\n}", "async getAllPlains(loja) {\n var url = 'https://api.isthereanydeal.com/v01/game/plain/list/?key=' + this.keys.ITADKeys.apiKey + '&shops=' + loja;\n axios.get(url)\n .then(function (response) {\n return response.data.data[loja];\n })\n .catch(function (error) {\n console.log(error);\n exit();\n });\n }", "function generateBotChoice () {\n return Math.floor(Math.random() * 3) + 1\n }", "function getMyTeam(optSet = undefined, teamParams = { }, myTeam = { }) {\n if (teamParams !== undefined) {\n addProps(myTeam, teamParams, __TEAMITEMS);\n console.log(\"Ermittelt: \" + JSON.stringify(myTeam));\n // ... und abspeichern...\n setOpt(optSet.team, myTeam, false);\n } else {\n const __TEAM = getOptValue(optSet.team); // Gespeicherte Parameter\n\n if ((__TEAM !== undefined) && (__TEAM.Land !== undefined)) {\n addProps(myTeam, __TEAM, __TEAMITEMS);\n console.log(\"Gespeichert: \" + JSON.stringify(myTeam));\n } else {\n console.error(\"Unbekannt: \" + JSON.stringify(__TEAM));\n }\n }\n\n //return ((myTeam.length > 0) ? myTeam : undefined);\n return myTeam;\n}", "function getRandomGame() {\n\t\t\treturn $http.get(GameApiConfig.baseUrl+'/game/random').then(function(result) {\n\t\t\t\treturn result.data;\n\t\t\t});\n\t\t}", "getBettingMarketsByGameIDPromise(gameID){\n var parameters = {};\n parameters['gameID']=gameID;\n return this.GetPromise('/v3/nhl/odds/{format}/BettingMarketsByGameID/{gameID}', parameters);\n }", "function getTheirPaddle()\n{\n return getPaddle(g_paddle_number);\n}", "function getGoals(data) {\n\n//returns team name with the highest average\n}", "function getNextGameID() {\n\n gameID++;\n\n const reply = { \"id\": gameID };\n\n return reply;\n\n}", "function getBestOddsFor(name, team) {\n var bestOdds = {\n \"back\": { \"odd\": 0, \"bookmaker\": \"\" },\n \"lay\": { \"odd\": 0, \"bookmaker\": \"\" }\n };\n var bookmakerObj = {};\n for(var bookmaker in team.bookmakers) {\n bookmakerObj = team.bookmakers[bookmaker];\n if (bookmakerObj.back > bestOdds.back.odd) {\n bestOdds.back.odd = bookmakerObj.back;\n bestOdds.back.bookmaker = bookmaker;\n }\n if (bookmakerObj.lay > bestOdds.lay.odd) {\n bestOdds.lay.odd = bookmakerObj.lay;\n bestOdds.lay.bookmaker = bookmaker;\n }\n }\n return bestOdds;\n }", "function getLobbies() {\n var lobbyObjects = [];\n for (var lobby of lobbies) {\n // Don't send details of unlisted lobbies\n if (!lobby.unlisted) {\n var players = [];\n for (var player of lobby.players.keys()) {\n players.push({\n name: users.get(player).name\n });\n }\n\n lobbyObjects.push({\n name: lobby.name,\n players: players,\n experimental: lobby.settings.experimental,\n maxPlayers: lobby.maxPlayers,\n password: lobby.password != ''\n });\n }\n }\n return lobbyObjects;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Put thumbnail in the result zone part B, in order to execute after proper load
function show_thumbnail_part_b(work,thmli,thmimg,thmprg,thmsel,thmi) { var width_orig = thmi.naturalWidth; var height_orig = thmi.naturalHeight; var width = 1000,height=200; if(width_orig==0 || height_orig==0) { work.status = 'error'; work.err='fail_load'; show_error(work); width = height = 200; thmimg.style.backgroundImage = 'url(site-img/error.svg)'; }else if(height_orig>height || width_orig>width) { var ratio_orig = width_orig/height_orig; if (width/height > ratio_orig) { width = height*ratio_orig; }else { height = width/ratio_orig; } thmimg.style.backgroundImage = 'url("'+thmi.src+'")'; }else { width = width_orig; height = height_orig; thmimg.style.backgroundImage = 'url("'+thmi.src+'")'; } thmimg.style.backgroundSize = width+'px '+height+'px'; thmli.style.width = thmimg.style.width = thmprg.style.width = width+'px'; thmli.style.height = thmimg.style.height = thmprg.style.height = height+'px'; thmli.style.marginTop = (205 - height)+'px'; thmsel.style.paddingTop = (height - 30)+'px'; thmprg.style.backgroundPosition = '0px center'; thmli.appendChild(thmimg); thmimg.appendChild(thmprg); thmprg.appendChild(thmsel); thmli.work = work; thmli.oncontextmenu = toggleinfo(); thmli.onclick = toggleinfo(); /* progress handler */ thmli.progress = progress(thmprg); result_zone.insertBefore(thmli, result_zone.lastElementChild); }
[ "imageLoaded(){}", "function loadOrRestoreImage (row, data, displayIndex) {\n // Skip if it is a container-type VM\n if (data.vm.type === \"container\") {\n return;\n }\n\n var img = $('img', row);\n var url = img.attr(\"data-url\");\n\n if (Object.keys(lastImages).indexOf(url) > -1) {\n img.attr(\"src\", lastImages[url].data);\n lastImages[url].used = true;\n }\n\n var requestUrl = url + \"&base64=true\" + \"&\" + new Date().getTime();\n\n $.get(requestUrl)\n .done(function(response) {\n lastImages[url] = {\n data: response,\n used: true\n };\n\n img.attr(\"src\", response);\n })\n .fail(function( jqxhr, textStatus, error) {\n var err = textStatus + \", \" + error;\n console.warn( \"Request Failed: \" + err );\n });\n}", "function append_thumbnail(options) {\n 'use strict';\n //\n // adds only one item to the list\n //\n // compile the output item template\n\n options = $.extend({\n data: null,\n template: null,\n colorbox_params: {},\n animate: false,\n container: null\n }, options);\n\n\n var data = options.data;\n var template = options.template;\n var colorbox_params = options.colorbox_params;\n var animate = options.animate;\n var container = options.container;\n\n // check if there is any video\n data.hires_download_path = data.hires_full_path;\n data.webres_download_path = data.webres_full_path;\n\n colorbox_params.iframe = false;\n if (data.webres_full_path.search('.webm') !== -1) {\n // it should have video replace the address with video player\n data.webres_full_path = 'video_player?video_full_path=/' + data.webres_full_path;\n colorbox_params.iframe = false;\n }\n\n var ref_item = $($.parseHTML(template(data)));\n\n if (animate) {\n ref_item.css({display: 'none'});\n }\n\n container.append(ref_item);\n if (animate) {\n ref_item.toggle('slow');\n }\n\n ref_item.find('[data-rel=\"colorbox\"]').colorbox(colorbox_params);\n}", "function appendThumbnail(img, type) {\n var thumbnail = createThumbnail(img, type),\n link = document.createElement('a');\n\n link.target = '_blank';\n link.href = img.src;\n link.appendChild(thumbnail);\n\n // append to DOM\n $preview.appendChild(link);\n\n }", "function ThumbnailSetPosition( GOMidx, cnt ) {\r\n var newTop= 0;\r\n var curTn= G.GOM.items[GOMidx];\r\n var idx= G.GOM.items[GOMidx].thumbnailIdx;\r\n var item= G.I[idx];\r\n \r\n if( curTn.neverDisplayed ) {\r\n // thumbnail is built but has never been displayed (=first display)\r\n var top=curTn.top-G.GOM.clipArea.top;\r\n if( G.tn.opt.Get('stacks') > 0 ) {\r\n // we have stacks -> do not display them here. They will be displayed at the end of the display animation\r\n item.$elt.last().css({ display: 'block'});\r\n item.$elt.css({ top: top , left: curTn.left });\r\n }\r\n else {\r\n item.$elt.css({ display: 'block', top: top , left: curTn.left });\r\n }\r\n newTop=top;\r\n \r\n // display the image of the thumbnail when fully loaded\r\n if( G.O.thumbnailWaitImageLoaded === true ) {\r\n var gi_imgLoad = ngimagesLoaded( item.$getElt('.nGY2TnImg') );\r\n gi_imgLoad.on( 'progress', function( instance, image ) {\r\n if( image.isLoaded ) {\r\n var idx=image.img.getAttribute('data-idx');\r\n var albumIdx=image.img.getAttribute('data-albumidx');\r\n if( albumIdx == G.GOM.albumIdx ) {\r\n // ignore event if not on current album\r\n G.I[idx].ThumbnailImageReveal();\r\n }\r\n }\r\n });\r\n }\r\n // display the thumbnail\r\n ThumbnailAppear(GOMidx, cnt);\r\n\r\n curTn.displayed=true;\r\n curTn.neverDisplayed=false;\r\n }\r\n else {\r\n var topOld=G.GOM.cache.containerOffset.top+item.top;\r\n var top=G.GOM.cache.containerOffset.top+(curTn.top-G.GOM.clipArea.top);\r\n newTop=curTn.top-G.GOM.clipArea.top;\r\n var vp=G.GOM.cache.viewport;\r\n if( G.O.thumbnailDisplayOutsideScreen || ( ( (topOld+curTn.height) >= (vp.t-vp.h) && topOld <= (vp.t+vp.h*4) ) ||\r\n ( (top+curTn.height) >= (vp.t-vp.h) && top <= (vp.t+vp.h*4) ) ) ) {\r\n // thumbnail positioned in enlarged viewport (viewport + 4 x viewport height) (v1.5: changed from 2 to 4)\r\n if( curTn.displayed ) {\r\n // thumbnail is displayed\r\n if( item.top != curTn.top || item.left != curTn.left ) {\r\n // set position\r\n if( G.O.galleryResizeAnimation == true ) {\r\n // with transition\r\n var tweenable = new NGTweenable();\r\n tweenable.tween({\r\n from: { top: item.top, left: item.left, height: item.height, width: item.width },\r\n to: { top: newTop, left: curTn.left, height: curTn.height, width: curTn.width },\r\n attachment: { $e: item.$elt },\r\n duration: 300,\r\n delay: cnt * G.tn.opt.Get('displayInterval'),\r\n easing: 'easeInOutQuart',\r\n step: function (state, att) {\r\n att.$e.css(state);\r\n },\r\n finish: function (state, att) {\r\n att.$e.css(state);\r\n this.dispose();\r\n }\r\n });\r\n }\r\n else {\r\n // set position without transition\r\n // item.$elt.css({ top: curTn.top , left: curTn.left });\r\n item.$elt.css({ top: newTop , left: curTn.left });\r\n }\r\n }\r\n }\r\n else {\r\n // re-display thumbnail\r\n curTn.displayed=true;\r\n // item.$elt.css({ display: 'block', top: curTn.top , left: curTn.left, opacity:1 });\r\n item.$elt.css({ display: 'block', top: newTop, left: curTn.left, opacity: 1 });\r\n ThumbnailAppearFinish(item);\r\n }\r\n }\r\n else {\r\n // undisplay thumbnail if not in viewport+margin --> performance gain\r\n curTn.displayed=false;\r\n item.$elt.css({ display: 'none'});\r\n }\r\n }\r\n item.left=curTn.left;\r\n item.top=newTop;\r\n \r\n // set new size if changed\r\n if( item.width != curTn.width || item.height != curTn.height ) {\r\n item.$elt.css({ width: curTn.width , height: curTn.height });\r\n item.width=curTn.width;\r\n item.height=curTn.height;\r\n \r\n // if( curTn.resizedContentWidth > 0 ) {\r\n // resize also the content (=image)\r\n if( item.resizedContentWidth != curTn.resizedContentWidth || item.resizedContentHeight != curTn.resizedContentHeight ) {\r\n if( item.kind == 'albumUp' ) {\r\n // item.$getElt('.nGY2GThumbnailAlbumUp').css({'height': curTn.resizedContentHeight, 'width': curTn.resizedContentWidth});\r\n }\r\n else {\r\n item.$getElt('.nGY2GThumbnailImg').css({'height': curTn.resizedContentHeight, 'width': curTn.resizedContentWidth});\r\n item.$getElt('.nGY2GThumbnailImage').css({'height': curTn.resizedContentHeight, 'width': curTn.resizedContentWidth});\r\n }\r\n item.resizedContentWidth=curTn.resizedContentWidth;\r\n item.resizedContentHeight=curTn.resizedContentHeight;\r\n }\r\n }\r\n \r\n \r\n // add counter of remaining (not displayed) images \r\n if( G.GOM.lastDisplayedIdxNew == GOMidx && G.layout.support.rows ) {\r\n if( (G.galleryDisplayMode.Get() == 'ROWS' && G.galleryMaxRows.Get() > 0) || (G.galleryDisplayMode.Get() == 'FULLCONTENT' && G.galleryLastRowFull.Get() && G.GOM.lastFullRow != -1) ){\r\n // number of items\r\n var nb=G.GOM.items.length - GOMidx -1;\r\n if( item.albumID != '0' && G.O.thumbnailLevelUp ) {\r\n nb--;\r\n }\r\n }\r\n\r\n if( nb > 0 ) {\r\n if( G.O.thumbnailOpenImage || G.O.thumbnailLastImgSliderDelay > 0 ) {\r\n item.$getElt('.nGY2GThumbnailIconsFullThumbnail').html('+'+nb);\r\n }\r\n\r\n if( G.layout.engine == 'GRID' && G.GOM.lastTn.startItem != G.GOM.NGY2Item(GOMidx) ) {\r\n // image slider on last displayed thumbnail\r\n G.GOM.lastTn.startIdx=GOMidx;\r\n G.GOM.lastTn.startItem=G.GOM.NGY2Item(GOMidx);\r\n G.GOM.lastTn.nextIdx=GOMidx;\r\n G.GOM.lastTn.currentIdx=GOMidx;\r\n G.GOM.lastTn.initiated=false;\r\n G.GOM.lastTn.enabled=true;\r\n }\r\n }\r\n G.GOM.lastDisplayedIdx=GOMidx;\r\n }\r\n\r\n }", "_prepareImages () {\n const maxWidth = Math.max(this._imageA.width, this._imageB.width)\n const maxHeight = Math.max(this._imageB.height, this._imageB.height)\n\n this._imageA = this._ensureImageDimensions(this._imageA, maxWidth, maxHeight)\n this._imageB = this._ensureImageDimensions(this._imageB, maxWidth, maxHeight)\n }", "function createThumbnailFromImage(imageSource, thumbnailSpace, hiddenField){\n // creates a variable to hold the original image\n var originalImage = new Image();\n // assigns the source of the original image\n originalImage.src = imageSource;\n // function that makes sure that the resto of the code executes once the\n // image finished loading\n originalImage.addEventListener(\"load\", function () {\n var thumbnailImage = resizeUsingCanvas(originalImage);\n populateThumbnail(thumbnailImage, thumbnailSpace, hiddenField);\n });\n\n}", "initializeThumbnails_() {\n const thumbnails = [];\n this.manager_\n .getThumbnails(this.currentLightboxGroupId_)\n .forEach((thumbnail) => {\n // Don't include thumbnails for ads, this may be subject to\n // change pending user feedback or ux experiments after launch\n if (thumbnail.element.tagName == 'AMP-AD') {\n return;\n }\n const thumbnailElement = this.createThumbnailElement_(thumbnail);\n thumbnails.push(thumbnailElement);\n });\n this.mutateElement(() =>\n thumbnails.forEach((thumbnailElement) =>\n this.gallery_.appendChild(thumbnailElement)\n )\n );\n }", "function setFigure(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\tvar mediaObj = element.data();\n\n\t\t\t\t$.each(mediaObj, function(media, path){\n\n\t\t\t\t\tvar num;\n\n\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\n\t\t\t\t\tif(!num)\n\t\t\t\t\t\tnum = 0;\n\n\t\t\t\t\tsizes[num] = path;\n\n\t\t\t\t});\n\n\t\t\t\tif(element.find('img').length == 0){\n\n\t\t\t\t\tvar prep = '<img src=\"' + sizes[currentMedia] + '\" alt=\"' + element.attr('title') + '\">';\n\n\t\t\t\t\tif($('>a', element).length == 0){\n\n\t\t\t\t\t\telement.append(prep);\n\n\t\t\t\t\t}else{\n\n\t\t\t\t\t\t$('>a', element).append(prep);\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}", "function showThumbnailPreview(tab){\r\n\tif(sniffedThumbnailUrls.hasOwnProperty(tab.id)){\r\n\t\tgetMediaLocation(sniffedThumbnailUrls[tab.id], \r\n\t\t\tfunction(videoUrl){\r\n\t\t\t\tvar modifiedUrl = videoUrl.match(/video.*_mp4/i);\r\n\t\t\t\tif(modifiedUrl != null){\r\n\t\t\t\t\tmodifiedUrl = modifiedUrl[0];\r\n\t\t\t\t\tmodifiedUrl = modifiedUrl.substring(0, modifiedUrl.length-4); //removing the _\r\n\t\t\t\t\tmodifiedUrl = \"http://static2.dmcdn.net/static/\" + modifiedUrl + \":jpeg_preview_contact.jpg\";\r\n\t\t\t\t\tconsole.log(\"thumbnail url is: \" + modifiedUrl);\r\n\t\t\t\t\tchrome.tabs.create({url: modifiedUrl});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t);\r\n\t\t\r\n\t}\r\n}", "swapPlaceholderImg(src) {\n this.$results.find('.results-overview-image img').attr('src', src).attr('alt', 'screenshot for ' + this.websiteUrl);\n }", "function privateHandleVisualizationBackup(){\n\t\tswitch( config.visualization_backup ){\n\t\t\t/*\n\t\t\t\tRemoves the visualization element from the page.\n\t\t\t*/\n\t\t\tcase \"nothing\":\n\t\t\t\t\n\t\t\t\tif( document.getElementById('amplitude-visualization') ){\n\t\t\t\t\tdocument.getElementById('amplitude-visualization').remove();\n\t\t\t\t}\n\t\t\tbreak;\n\t\t\t/*\n\t\t\t\tSets up the old visualization element to contain the\n\t\t\t\talbum art.\n\t\t\t*/\n\t\t\tcase \"album-art\":\n\t\t\t\t/*\n\t\t\t\t\tGets the old visualizationelement.\n\t\t\t\t*/\n\t\t\t\tvar old_visualization = document.getElementById('amplitude-visualization');\n\n\t\t\t\t/*\n\t\t\t\t\tIf there is a visualization element then we proceed.\n\t\t\t\t*/\t\n\t\t\t\tif( old_visualization ){\n\t\t\t\t\t/*\n\t\t\t\t\t\tGets the parent node to append the inner node to containing\n\t\t\t\t\t\tthe album art.\n\t\t\t\t\t*/\n\t\t\t\t\tvar parent_old_visualization = old_visualization.parentNode;\n\n\t\t\t\t\tvar new_album_art = document.createElement('img');\n\t\t\t\t\t/*\n\t\t\t\t\t\tSets the attribute to be the song infor for the cover\n\t\t\t\t\t\tart on the new element. Also apply the class 'amplitude-album-art'\n\t\t\t\t\t*/\n\t\t\t\t\tnew_album_art.setAttribute('amplitude-song-info', 'cover');\n\t\t\t\t\tnew_album_art.setAttribute('class', 'amplitude-album-art');\n\n\t\t\t\t\t/*\n\t\t\t\t\t\tTODO: is this the right place to do this? Shouldn't this happen\n\t\t\t\t\t\tAFTER we replace the visualization?\n\t\t\t\t\t*/\n\t\t\t\t\tif( document.querySelector('[amplitude-song-info=\"cover\"]') ){\n\n\t\t\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\t\t\tnew_album_art.setAttribute( 'src', config.active_metadata.cover_art_url );\n\t\t\t\t\t\t\tdocument.querySelector('[amplitude-song-info=\"cover\"]').setAttribute('src', config.active_metadata.cover_art_url);\n\t\t\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\t\t\tnew_album_art.setAttribute( 'src', config.default_album_art );\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tnew_album_art.setAttribute( 'src', '' );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tparent_old_visualization.replaceChild( new_album_art, old_visualization );\n\t\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}", "function setPicture(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\telement.find('source').each(function(){\n\n\t\t\t\t\tvar media, path, num;\n\t\t\t\t\tmedia = $(this).attr('media');\n\t\t\t\t\tpath = $(this).attr('src');\n\n\t\t\t\t\tif(media)\n\t\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\t\t\t\t\telse\n\t\t\t\t\t\tnum = 0;\n\n\t\t\t\t\tsizes[num] = path;\n\n\t\t\t\t});\n\n\t\t\t\tif(element.find('img').length == 0){\n\n\t\t\t\t\tvar prep = '<img src=\"' + sizes[currentMedia] + '\" style=\"' + element.attr('style') + '\" alt=\"' + element.attr('alt') + '\">';\n\n\t\t\t\t\tif($('>a', element).length == 0){\n\n\t\t\t\t\t\telement.append(prep);\n\n\t\t\t\t\t}else{\n\n\t\t\t\t\t\t$('>a', element).append(prep);\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\t\t\t\t\t\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}", "function loadContentViewer(imageId,position,rotation) {\r\n\t// When a RHS thumbnail is clicked, this function is called. \r\n\t// Because of that, and the fact we know if the page has already been loaded, we can reset the pageBeginLoadTime if needed.\r\n\t// Only Perform when debug = p.\r\n\t\r\n\tif (pageLoadDebug != -1 && initialPageLoad == false) {\r\n\t\tpageStartLoadTime = new Date();\r\n\t}\r\n\tinitialPageLoad = false;\r\n\t\r\n\t// Load the active page object into a global variable.\r\n\tobjPage = window.opener.objCase.pages[window.opener.activePageJsonId];\r\n\t\r\n\t// Clear the content viewer so we do not have non-used DOM elements on the page.\r\n\tclearContentViewer();\r\n\t\r\n\t// Get the image path from the spContentId field.\r\n\tcontentId = objPage.spContentID;\r\n\timagePath = 'ucm/getFile?contentId=' + contentId + '&rendition=web';\r\n\r\n\t// Load the preview image objects and set the preview image src attributes. \r\n\t// These are used for the 8 zoom levels.\r\n\t$('#content_preview_image1').attr('src', imagePath);\r\n\t$('#content_preview_image2').attr('src', imagePath);\r\n\t$('#content_preview_image3').attr('src', imagePath);\r\n\t$('#content_preview_image4').attr('src', imagePath);\r\n\t$('#content_preview_image5').attr('src', imagePath);\r\n\t$('#content_preview_image6').attr('src', imagePath);\r\n\t$('#content_preview_image7').attr('src', imagePath);\r\n\t$('#content_preview_image8').attr('src', imagePath);\r\n\t$('#content_preview_image9').attr('src', imagePath);\r\n\t\r\n\t// Set the names to the thumbnail id so we can retrive when rotating the images.\r\n\t$('#content_preview_image1').attr('name', imageId);\r\n\t\r\n\t// Initialize the map/zooming functionality\r\n\t$(\"#map-1\").mapz({\r\n\t\tzoom : true,\r\n\t\tcreatemaps : true,\r\n\t\tmousewheel : false\r\n\t});\r\n\r\n\t// Check which position the active document is within the thumbnail sequence and set the navigation controls appropriately.\r\n\tswitch(position) {\r\n\t\tcase 'first':\r\n\t\t\t$(\"#nav_prev_content\").attr('disabled','disabled');\r\n\t\t\t$(\"#nav_next_content\").removeAttr('disabled');\r\n\t\t\tbreak;\r\n\t\tcase 'last':\r\n\t\t\t$(\"#nav_prev_content\").removeAttr('disabled');\r\n\t\t\t$(\"#nav_next_content\").attr('disabled','disabled');\r\n\t\t\tbreak;\r\n\t\tcase 'only':\r\n\t\t\t$(\"#nav_prev_content\").attr('disabled','disabled');\r\n\t\t\t$(\"#nav_next_content\").attr('disabled','disabled');\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\t$(\"#nav_prev_content\").removeAttr('disabled');\r\n\t\t\t$(\"#nav_next_content\").removeAttr('disabled');\r\n\t}\r\n\t\r\n\t// If we are in step 2, display the grid lines\r\n\tif (step == 2) {\r\n\t\t$('#map-1').griddy({height:1350});\r\n\t\t$('.griddy').toggle(); \r\n\t}\r\n\t\r\n\t// Update sequencing information based on the current step.\r\n\tif (step == 1) {\r\n\t\t// Update the active page and final page number.\r\n\t\tupdateActivePageNumber();\r\n\t\tupdateActiveDocumentPageFinalNumber();\r\n\t\tupdateActiveDocumentPageDocDateAndType();\r\n\t} else if (step == 2) {\r\n\t\t// Update sequencing display data.\r\n\t\tupdateActiveDocumentNumber();\r\n\t\tupdateActiveDocumentPageNumber();\r\n\t\tupdateActiveDocumentPageFinalNumber();\r\n\t\tupdateActiveDocumentPageDocDateAndType();\r\n\t\tupdateDocumentCount();\r\n\t\tupdateDocumentPageCount();\r\n\t\t\r\n\t\t// Update sequencing controls.\r\n\t\tupdateDocumentControls();\r\n\t\tupdatePageControls();\r\n\t}\r\n\t\r\n\t/*IWS-357 : Not all the thumbnail image is showing, thumbnails are off center and far to the right*/\r\n\t\r\n\t/* Recommended Resolution - 1920 x 1080(Landscape) or 1080 x 1920(Portrait) \r\n\t To make the images to the center of screen \r\n\t if screen having resolution - 1080 x 1920(Portrait) */\r\n\tif($(screen)[0].width!='1920' || $(screen)[0].height!='1080'){\r\n\t\t$(\"#content_preview_image1\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image2\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image3\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image4\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image5\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image6\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image7\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image8\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image9\").addClass('removeMargin');\r\n\t}else{\r\n\t\t$(\"#content_preview_image1\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image2\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image3\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image4\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image5\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image6\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image7\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image8\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image9\").removeClass('removeMargin');\r\n\t}\r\n\t// To load the gridding to 100%\r\n\tvar stageId = window.opener.qsStageId;\r\n\tif(stageId == 4 || stageId == 5){ // stageId = 4 & stageId = 5 is for step1-OP and Step1-QA respectively\r\n\t\t$(\"#map-1\").css({ left : '0', width: '100%' });\r\n\t}else{\r\n\t\t$(\"#map-1\").addClass('map-override');\r\n\t}\r\n\t\r\n\t// Update the rotation.\r\n\t$(\"#content_preview_image1\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image2\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image3\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image4\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image5\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image6\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image7\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image8\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image9\").rotate({angle: rotation});\r\n\t\r\n\t// Postioining the image if rotation angle is 90/270 degrees\r\n\tif(rotation == '90' || rotation == '270'){\r\n\t\t$('#content_preview_image2').addClass('landscapeImg2Zoom');\r\n\t\t$('#content_preview_image3').addClass('landscapeImg3Zoom');\r\n\t\t$('#content_preview_image4').addClass('landscapeImg4Zoom');\r\n\t\t$('#content_preview_image5').addClass('landscapeImg5Zoom');\r\n\t\t$('#content_preview_image6').addClass('landscapeImg6Zoom');\r\n\t\t$('#content_preview_image7').addClass('landscapeImg7Zoom');\r\n\t\t$('#content_preview_image8').addClass('landscapeImg8Zoom');\r\n\t\t$('#content_preview_image9').addClass('landscapeImg9Zoom');\r\n\t}else{\r\n\t\t$('#content_preview_image2').removeClass('landscapeImg2Zoom');\r\n\t\t$('#content_preview_image3').removeClass('landscapeImg3Zoom');\r\n\t\t$('#content_preview_image4').removeClass('landscapeImg4Zoom');\r\n\t\t$('#content_preview_image5').removeClass('landscapeImg5Zoom');\r\n\t\t$('#content_preview_image6').removeClass('landscapeImg6Zoom');\r\n\t\t$('#content_preview_image7').removeClass('landscapeImg7Zoom');\r\n\t\t$('#content_preview_image8').removeClass('landscapeImg8Zoom');\r\n\t\t$('#content_preview_image9').removeClass('landscapeImg9Zoom');\r\n\t}\r\n\t// Only show the rotation controls if the page is not complete, suspended or excluded.\r\n\tpgCompleted = objPage.completed;\r\n\tpgDeleted = objPage.deleted;\r\n\tif (pgCompleted != true && pgCompleted != 'true' && pgDeleted != true && pgDeleted != 'true') {\r\n\t\tdisplayRotationControls();\r\n\t} else {\r\n\t\thideRotationControls();\r\n\t}\r\n}", "resetFileThumb() {\n const fileThumb = this.dom.querySelector(\".file-details-thumbnail\");\n fileThumb.src = require(\"../static/images/file-128x128.png\");\n }", "function insertIMGlinks() {\n //LOGGER.debug(\"FMA insertIMGlinks Function Executing\");\n let imgsrc = $('#image-1 img.sbar-fullimg').attr('src');\n imgsrc = imgsrc.substring(0, imgsrc.indexOf('?'));\n //LOGGER.debug(\" insertIMGlinks > imgsrc:\", imgsrc);\n $('#album-images').append(`<p><img src=\"http://musicbrainz.org/favicon.ico\" /><a href=\"${imgsrc}\">MB High Res Image</a></p>`);\n}", "function handleThumbnails(o)\r\n\t{\r\n\t\tif (o.success == true)\t\r\n\t\t{\r\n\t\t\tif (!checkForTimeout(o))\r\n\t\t\t{\r\n\t\t\t\t$('#thumbnail_box').html();\r\n\t\t\t\t$.jGrowl(\"Showing thumbnails...\");\r\n\t\t\t\t$('#thumbnail_box').html(\"<ul id='ulThumbnailList'>\"+decodeURIComponent(o.rows[def_lang] + ''));\r\n\r\n\t\t\t\t$('#ulThumbnailList').append('<li style=\"clear: both; list-style-type: none;\"></li></ul>');\r\n\t\t\t\t\r\n\t\t\t\t$('#localized_content').children().each(function()\r\n\t\t\t\t{\r\n\t\t\t\t\tvar lang_code = $(this).attr('id');\r\n\t\t\r\n\t\t\t\t\tif (lang_code != def_lang)\r\n\t\t\t\t\t{\t\t\t\t\t\r\n\t\t\t\t\t\tif ($($('#content-'+lang_code).children().get(1)).find('ul').length)\r\n\t\t\t\t\t\t\t$($('#content-'+lang_code).children().get(1)).find('ul').html('');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tvar content = o.rows[def_lang];\r\n\t\t\t\t\t\tif (lum_isDefined(o.rows[lang_code]) && o.rows[lang_code] != '')\r\n\t\t\t\t\t\t\tcontent = o.rows[lang_code];\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t$($('#content-'+lang_code).children().get(1)).append(\"<ul>\"+decodeURIComponent(content + '')+\"</ul>\");\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t\r\n\t\t\t\t makeEditable();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t$.jGrowl(o.errors, {sticky: true});\r\n\t\t}\r\n\t}", "function showLargeImage(caption,thumbnailArrayIndex){\n\t//set ID for previously selected thumbnail\n\tvar oldObjIdString = 'FSI_' + currentImageIndex;\n\tcurrentImageIndex = thumbnailArrayIndex;\n\tvar objIdString = 'FSI_' + thumbnailArrayIndex;\n\t//display image\n\tdocument.getElementById('selectedImage').innerHTML = document.getElementById(objIdString).innerHTML;\n\t//set selected class for current thumbnail\n\tdocument.getElementById(objIdString).className = 'imageWrapper selected';\n\t//remove selected class from previous thumbnail, but only if they're not the same\n\tif (oldObjIdString != objIdString){\n\t\tdocument.getElementById(oldObjIdString).className = 'imageWrapper';\n\t}\n\t//display caption\n\tdocument.getElementById('caption').innerHTML = caption;\n}", "function displayImagesThumbnail()\n\t{\n\t\t// Stored action to know if user act during the process\n\t\tvar actionID = _actionID + 0;\n\n\t\tfunction cleanUp()\n\t\t{\n\t\t\tURL.revokeObjectURL(this.src);\n\t\t}\n\n\t\tfunction process()\n\t\t{\n\t\t\t// Stop here if we change page.\n\t\t\tif (actionID !== _actionID) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar nodes = jQuery('.img:lt(5)');\n\t\t\tvar load = 0;\n\t\t\tvar total = nodes.length;\n\n\t\t\t// All thumbnails are already rendered\n\t\t\tif (!total) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Work with current loaded files\n\t\t\tnodes.each(function(){\n\t\t\t\tvar self = jQuery(this);\n\n\t\t\t\tClient.getFile( self.data('path'), function( data ) {\n\t\t\t\t\t// Clean from memory...\n\t\t\t\t\tMemory.remove(self.data('path'));\n\t\t\t\t\tself.removeClass('img').addClass('thumb');\n\n\t\t\t\t\tvar url = getImageThumbnail( self.data('path'), data );\n\n\t\t\t\t\t// Display image\n\t\t\t\t\tif (url) {\n\t\t\t\t\t\tvar img = self.find('img:first').get(0);\n\t\t\t\t\t\tif (url.match(/^blob\\:/)){\n\t\t\t\t\t\t\timg.onload = img.onerror = img.onabort = cleanUp;\n\t\t\t\t\t\t}\n\t\t\t\t\t\timg.src = url;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Fetch next range.\n\t\t\t\t\tif ((++load) >= total) {\n\t\t\t\t\t\tsetTimeout( process, 4 );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tprocess();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
progress patient to the next queue
function progressPatient(queue) { setShow('send'); }
[ "function processNextPatient() {\n\n if (0 === patientsToProcess.length) {\n // all done\n callback(null, zipId);\n return;\n }\n\n //alert('process next patient');\n\n // set the current patient id\n currentPatientId = patientsToProcess.pop();\n activitiesToProcess = [];\n\n // make list of activities to render for this patient\n var i, j;\n for (i = 0; i < invoiceData.length; i++) {\n if (currentPatientId === invoiceData[i].patientId) {\n for (j = 0; j < invoiceData[i].activities.length; j++) {\n activitiesToProcess.push(invoiceData[i].activities[j]);\n }\n }\n }\n\n // load the expanded patient object\n Y.doccirrus.comctl.privateGet( '/1/patient/' + currentPatientId, {}, onPatientLoaded );\n\n function onPatientLoaded(err, body) {\n var\n result = body && body.data;\n if (err || 0 === result.length) {\n callback('Konnte Patientendaten nicht laden: ' + err);\n return;\n }\n\n currentPatient = result[0];\n jqStatus.html('Bearbeite Patient: ' + currentPatient.firstname + ' ' + currentPatient.lastname);\n\n progressAt = progressAt + 1;\n updateProgress();\n processNextActivity();\n }\n\n }", "function movePatient(queue) {\n var newList = []\n if (queue === 'GP') {\n newList = gpQueue;\n newList.push(currPatient)\n setG(newList)\n } else if (queue === 'Specialist') {\n newList = spQueue;\n newList.push(currPatient)\n setSp(newList)\n } else if (queue === 'Surgeon') {\n newList = suQueue;\n newList.push(currPatient)\n setSu(newList) \n }\n setShow('queue');\n setCurrent(null);\n }", "function onQueue(data) {\n\tif (\"Error\" in data) {\n\t\tonError(data.Error);\n\t} else if (\"Value\" in data) {\n\t\tqueueSize = data.Value.length;\n\t\t$(\"#current-queue>tbody\").empty();\n\t\tfor (i = currentTrack; i < data.Value.length; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t\tfor (i = 0; i < currentTrack; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t}\n}", "async processQueue() {\n if (this.queueLock || this.audioPlayer.state.status !== AudioPlayerStatus.Idle || this.queue.length === 0) return;\n this.queueLock = true;\n const nextTrack = this.queue.shift();\n try {\n const resource = await nextTrack.createAudioResource();\n this.audioPlayer.play(resource);\n this.queueLock = false;\n } catch (error) {\n console.log(error);\n nextTrack.onError(error);\n this.queueLock = false;\n this.processQueue();\n }\n }", "function processNextActivity() {\n\n if (0 === activitiesToProcess.length) {\n Y.log('done with patient');\n processNextPatient();\n return;\n }\n\n var\n ts = new Date().getTime(),\n\n pdfName = '' +\n currentPatient.firstname + ' ' + currentPatient.lastname + '.' +\n activitiesToProcess.length + '.' +\n ts + '.pdf',\n\n nextActivityId = activitiesToProcess.pop();\n\n jqStatus.html('Bearbeite Patient: ' + currentPatient.firstname + ' ' + currentPatient.lastname + ' (' + activitiesToProcess.length + ')');\n progressAt = progressAt + 1;\n updateProgress();\n\n Y.doccirrus.comctl.privatePost(\n '/1/formtemplate/:makepdf',\n {\n 'formId': canonicalId,\n 'formVersionId': formVersionId,\n 'mapper': 'PubReceipt_T',\n 'mapCollection': 'activity',\n 'mapObject': nextActivityId,\n 'saveTo': 'zip',\n 'zipId': zipId,\n 'preferName': pdfName\n },\n onPDFRender\n );\n }", "function next () {\n var a = actions.shift()\n if ( a ) {\n a( function ( err ) {\n if ( err ) throw err\n // setTimeout( next, ACTION_INTERVAL )\n } )\n } else {\n setTimeout( finish, ACTION_INTERVAL )\n }\n }", "function sumNextQueue(nextQueue){}", "function tasks_queue() {\r\n let q_data = new Queue(1);\r\n q_data.push(4);\r\n q_data.push(8);\r\n q_data.push(9);\r\n q_data.push(19);\r\n\r\n q_data.parse_llist();\r\n let out = q_data.pop();\r\n let out1 = q_data.pop();\r\n let out2 = q_data.pop();\r\n let out3 = q_data.pop();\r\n console.log(\r\n \" queue gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n );\r\n q_data.push(100);\r\n // q_data.pop();\r\n\r\n console.log(\"queueu peeking out \", q_data.peek(), q_data.is_empty());\r\n q_data.parse_llist();\r\n }", "enqueue(track) {\n this.queue.push(track);\n void this.processQueue();\n }", "requestNextStep() {\n this.requestNextStepCallback();\n }", "prepareItems() {\n this.limiter.beginFrame();\n // Upload the graphics\n while (this.queue.length && this.limiter.allowedToUpload()) {\n const item = this.queue[0];\n let uploaded = false;\n if (item && !item._destroyed) {\n for (let i = 0, len = this.uploadHooks.length; i < len; i++) {\n if (this.uploadHooks[i](this.uploadHookHelper, item)) {\n this.queue.shift();\n uploaded = true;\n break;\n }\n }\n }\n if (!uploaded) {\n this.queue.shift();\n }\n }\n // We're finished\n if (!this.queue.length) {\n this.ticking = false;\n const completes = this.completes.slice(0);\n this.completes.length = 0;\n for (let i = 0, len = completes.length; i < len; i++) {\n completes[i]();\n }\n }\n else {\n // if we are not finished, on the next rAF do this again\n Timer_1.Timer.shared.addOnce(this.tick, this, Constants_1.Constants.UPDATE_PRIORITY.UTILITY);\n }\n }", "async processQueue() {\n let message;\n while (this.queue.length) {\n if (!message || this.needsTaskBoundaryBetween(this.queue[0], message)) {\n await async_1.timeout(0);\n }\n message = this.queue.shift();\n if (!message) {\n return; // may have been disposed of\n }\n switch (message.type) {\n case 'event':\n if (this.eventCallback) {\n this.eventCallback(message);\n }\n break;\n case 'request':\n if (this.requestCallback) {\n this.requestCallback(message);\n }\n break;\n case 'response':\n const response = message;\n const clb = this.pendingRequests.get(response.request_seq);\n if (clb) {\n this.pendingRequests.delete(response.request_seq);\n clb(response);\n }\n break;\n }\n }\n }", "function qNext() {\n var o = deferreds.shift(); //remove first element\n\n if( o ){\n o.deferred\n .fail(function( xml, textStatus ){\n qNext();\n });\n o.deferred\n .done(function( xml, textStatus ){\n recombined.push({\n xml: xml,\n category: o.category,\n index: o.index\n });\n self.setState({ data: recombined });\n qNext();\n });\n }\n }", "dequeue() {\n return this.processes.shift();\n }", "function loadNextItem() {\n\tif (queue.length === 0) {\n\t\t// if there's something playing stop it.\n\t\tloadCandidate(null);\n\t\t\n\t\tif (refillingQueue) {\n\t\t\t// loadNextItem will be called when the queue is refilled\n\t\t\treturn;\n\t\t}\n\t\t\n\t\trefillingQueue = true;\n\t\trefillQueue(function() {\n\t\t\trefillingQueue = false;\n\t\t\tif (queue.length === 0) {\n\t\t\t\tconsole.log(\"Couldn't find anything to add to the queue. Checking again shortly.\");\n\t\t\t\tsetTimeout(function() {\n\t\t\t\t\tif (liveCandidate === null) {\n\t\t\t\t\t\tloadNextItem();\n\t\t\t\t\t}\n\t\t\t\t}, 5000);\n\t\t\t}\n\t\t\telse if (liveCandidate === null) {\n\t\t\t\t// load the next item if there's still nothing playing\n\t\t\t\t// a live stream could have been added to the front.\n\t\t\t\tloadNextItem();\n\t\t\t}\n\t\t});\n\t}\n\telse {\n\t\tloadCandidate(queue.shift());\n\t}\n}", "function plusQueue (id) {\n\n\t\tvar view = Views.view;\n\n\t\tif (view.name === 'album' || view.name === 'songs') {\n\n\t\t\tViews.addNextSong(id).then(function () {\n\t\t\t\tPlayer.queue(id);\n\t\t\t});\n\n\t\t} else if (view.name === 'artist' || view.name === 'albums') {\n\t\t\tDb.getAlbum(id).then(queueSongs);\n\t\t} else if (view.name === 'artists') {\n\t\t\tDb.songsArtist(id).then(queueSongs);\n\t\t} else if (view.name === 'libraries') {\n\t\t\tDb.getSongs(id).then(queueSongs);\n\t\t}\n\n\t}", "async consumeNext() {\n const file = this.files[this.handledFiles];\n await file.consume(async (file, isSuccess) => {\n this.handledFiles++;\n console.log(`Consumed ${this.handledFiles}/${this.totalFiles} files`);\n await this.updateProgressStatus(file, isSuccess);\n\n if (this.progressStatus === 'progressing' && this.handledFiles < this.totalFiles) {\n await this.consumeNext();\n } else {\n if (this.progressStatus === 'failed') {\n await this.persistStatus(TASK_FAILED_STATUS);\n console.log(\n `Failed to finish sync task. Skipping the remaining files. Most recent delta file successfully consumed is created at ${this.latestDelta.toISOString()}.`);\n } else {\n await this.persistStatus(TASK_SUCCESS_STATUS);\n console.log(\n `Finished sync task successfully. Ingested ${this.totalFiles} files. Most recent delta file consumed is created at ${this.latestDelta.toISOString()}.`);\n }\n }\n });\n }", "function next () {\n var msg = nextMessage()\n if (!msg) {\n return stopQueue()\n }\n\n _self.currentMessage = msg.text\n _self.color = msg.color\n\n if (!_self.show) {\n _self.show = true\n }\n }", "function PlayNextStreamInQueue() { \r\n \r\n ytAudioQueue.splice(0, 1); \r\n \r\n // if there are streams remaining in the queue then try to play \r\n if (ytAudioQueue.length != 0) { \r\n console.log(\"Now Playing \" + ytAudioQueue[0].videoName); \r\n PlayStream(ytAudioQueue[0].streamUrl); \r\n } \r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to loop and see if the current peek image needs to be fetched from server
function updateCurImg(){ console.log('attempting to update current image'); //get the peek peekInsert var peekInsert = document.getElementById('peekOutsideDiv'); if(peekInsert.currentId) var result = results[peekInsert.currentId]; if(peekInsert.currentId && !result.hasImg){ console.log('requesting image for id: ' + peekInsert.currentId); //if the image has not been downloaded yet then send another request to the server requestSingleImg(peekInsert.currentId, function(){}); } setTimeout(function(){updateCurImg()}, 1000); }
[ "function checkImages(){ //Check if the images are loaded.\n\n if(game.doneImages >= game.requiredImages){ //If the image loads, load the page to the DOM.\n\n init();\n }else{ //loop until the images are loaded.\n\n setTimeout(function(){\n checkImages();\n },1);\n\n }\n }", "function checkStatus() {\n var allDone = true;\n\n for (var _i2 = 0; _i2 < layers.length; _i2++) {\n if (layers[_i2].loaded === false) {\n allDone = false;\n break;\n }\n }\n\n if (allDone) finish();else setTimeout(checkStatus, 500);\n }", "function voteFinished() {\n var finished = true;\n var arrCards = votingContainer.getElementsByTagName(\"IMG\");\n for (const card in arrCards) {\n if (arrCards.hasOwnProperty(card)) {\n const element = arrCards[card];\n if (element.getAttribute(\"src\") == \"/images/blank_card.png\") {\n finished = false;\n }\n }\n }\n return finished;\n}", "function urlExists(url) {\n\t\tvar http = new XMLHttpRequest();\n\t\thttp.open('HEAD', url);\n\t\thttp.send();\n\t\tif (http.status !== 404) {\n\t\t\timgsNumber++;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "function imageisloaded(image) {\n if (image == null || ! image.complete()) {\n alert(\"image not loaded :(\");\n return false;\n }\n else {\n return true; \n }\n}", "function hasThumbs(msg){\n //Create an array of every instance when there is the \"img\"\n let arr = msg.querySelectorAll(\"img\");\n //Loop through the array and if there is a thumbs return true\n for (let i = 0; i < arr.length; i++){\n if (arr[i].alt == \"👍🏼\"){\n return true;\n }\n //Yellow thumbs up img\n else if (arr[i].src == \"blob:https://web.whatsapp.com/95e06bf6-ffaf-4c76-9456-1fa5a499ed03\"){\n return true;\n }\n //Brown thumbs up sticker\n else if (arr[i].src == \"blob:https://web.whatsapp.com/db7755d6-18da-4246-9703-6f83d33fdad4\"){\n return true;\n }\n }\n return false;\n}", "function request_url() {\n // storing all of the image sources in an array.\n var img = document.getElementsByTagName(\"img\");\n var img_src = new Array(img.length);\n\n for (i = 0; i < img.length; i++) {\n img_src[i] = img[i].src;\n }\n\n // Counting the number of times an image is pulled from outside the site.\n var outsideRequest = 0;\n for (i = 0; i < img_src.length; i++) {\n if (pageDomain != getDomain(img_src[i])) {\n outsideRequest++;\n }\n }\n\n // determining the percentage of outside equests\n var requestPercent = Math.floor(100*(outsideRequest / img_src.length));\n\n // Returning the prediction of phishing.\n if (requestPercent < 20) {\n return 1;\n } else if (requestPercent > 50) {\n return -1;\n } else {\n return 0;\n }\n\n }", "static isImageLoaded(img){// During the onload event, IE correctly identifies any images that\n// weren’t downloaded as not complete. Others should too. Gecko-based\n// browsers act like NS4 in that they report this incorrectly.\nif(!img.complete){return false;}// However, they do have two very useful properties: naturalWidth and\n// naturalHeight. These give the true size of the image. If it failed\n// to load, either of these should be zero.\nif(img.naturalWidth===0){return false;}// No other way of checking: assume it’s ok.\nreturn true;}", "function checkEndOfPage(firstFill){\r\n\tfirstFill = firstFill || 0;\r\n\tvar endOfPage = document.getElementById('photoGallery').clientHeight;\r\n var lastDiv = document.querySelector(\"#photoBlock > div:last-child\");\r\n var lastDivOffset = lastDiv.offsetTop + lastDiv.clientHeight;\r\n var pageOffset = window.pageYOffset + window.innerHeight;\r\n if(firstFill == 0){\t\r\n\t \tif(Math.round(pageOffset) >= endOfPage){\r\n\t \t\tshowLoading();\r\n\t \t\tgetPhotos(per_page = 5, page = 1, function(data){createNewPhotoBlock(data)});\r\n\t \t}\r\n }\r\n \telse if(lastDivOffset < window.innerHeight){\r\n \tpage++;\r\n\t \tshowLoading();\r\n \t\tgetPhotos(per_page = 5, page, function(data){ createNewPhotoBlock(data, firstFill = 1) });\r\n \t}\r\n\t// \"page++\" variable page here makes the scroll down shows older images, with \"page = 1\" in the function getPhotos, \r\n\t// scroll down shows the newest images in flickr. \r\n\t//The method \"getRecents\" dont verify if the images are duplicated\r\n}", "function imageLoaded() {\n noOfImageLoaded++;\n if (noOfImageLoaded == 10) {\n onLoadFinish();\n }\n}", "function getMoreImages() {\n\t\t// Return 0 if fetched all images, 1 if enough to fill screen and >1 otherwise\n\t\tvar uncovered_px = $box.height()+$box.offset().top - ($(document).scrollTop()+window.innerHeight),\n\t\t\tuncovered_rows = uncovered_px / settings.row_height;\n\n\t\tif (unloaded) {\n\t\t\t// Don't load more than if not all have loaded (think: slow connections!)\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (!fetched_all) {\n\t\t\tif (uncovered_rows < 2) {\n\t\t\t\tif (!loading_images && settings.getImages) {\n\t\t\t\t\tloading_images = true;\n\t\t\t\t\tsettings.getImages(addNew);\n\t\t\t\t}\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}", "function infiniScroll(pageNumber) {\n \n $.ajax({\n url: \"rest/getMoreImages/\"+pageNumber+\"/\"+uploadCount,\n type:'GET',\n success: function(imageJSON){\n \n var imageResults = $.parseJSON(imageJSON);\n for(var i=0;i<6;i++) { \n if(imageResults.images[i].userID !== \"\") {\n \n getGPlusName(imageResults.images[i].userID);\n \n $(\"#contentList\").append(\n '<li class=\"polaroid\">'+\n '<a href=\"javascript:void(0)\" title=\"'+plusName+'\">'+\n '<img src=\"uploads/'+imageResults.images[i].filename+'\" alt=\"'+plusName+'\" />'+\n '</a>'+\n '</li>');\n } else {\n streamOK = false;\n }\n }\n \n }\n });\n}", "waitForImage(image, targetStatus = 3) {\n return this.waitFor(image, (image) => image.status === targetStatus)\n }", "autoFetch() {\n while (this.processes.length > 0) {\n\n // Remove url from 'process' array\n const xmUrl = this.processes.pop();\n log.log(`Queuing ${xmUrl}`);\n \n this.counter = this.counter + 1;\n\n // Push the url to 'processCompleted'\n this.processesCompleted.push(xmUrl);\n\n // Feed the base Url and fetch HTML\n webService.getWeb(xmUrl).then((data) => {\n\n log.log(`Data received for ${xmUrl}`);\n const newUrls = rulesService.checkRules(data);\n this.allUrls = _.union(this.allUrls, newUrls);\n\n log.log(`Data Queued ${this.counter} - Completed - ${this.dataFetched}`);\n this.dataFetched = this.dataFetched + 1;\n \n if ((this.counter === this.dataFetched) && this.counter !== 1) {\n filesService.createXml(rulesService.sortLinks(this.allUrls));\n } else {\n this.queueUrls(newUrls);\n }\n });\n }\n }", "imageLoaded(){}", "async function waitForLCP() {\n // eslint-disable-next-line no-use-before-define\n const lcpBlocks = LCP_BLOCKS;\n const block = document.querySelector('.block');\n const hasLCPBlock = (block && lcpBlocks.includes(block.getAttribute('data-block-name')));\n if (hasLCPBlock) await loadBlock(block, true);\n\n document.querySelector('body').classList.add('appear');\n const lcpCandidate = document.querySelector('main img');\n await new Promise((resolve) => {\n if (lcpCandidate && !lcpCandidate.complete) {\n lcpCandidate.setAttribute('loading', 'eager');\n lcpCandidate.addEventListener('load', () => resolve());\n lcpCandidate.addEventListener('error', () => resolve());\n } else {\n resolve();\n }\n });\n}", "function checkMatch() {\n\tif (imageTwo != null && imageOne.attr('src') != imageTwo.attr('src')) {\n\t\tsetTimeout(hideImages,500);\n\t\tsetTimeout(resetImages,600);\n\t\tsetTimeout(incrementMoves,600);\n\t} else if (imageTwo != null && imageOne.attr('src') === imageTwo.attr('src')) {\n\t\tmatches++;\n\t\t$(imageOne).attr('alt','matched');\n\t\t$(imageTwo).attr('alt','matched');\n\t\tsetTimeout(resetImages,100);\n\t\tsetTimeout(incrementMoves,100);\n\t}\n}", "function imageLoaded() {\n imagesLoaded++\n if (imagesLoaded == totalImages) {\n allImagesLoaded()\n }\n }", "function checkProgress() {\n\tvar finished = true;\n\tfor (var key in network.usersAwaiting) {\n\t\tif (network.usersAwaiting.hasOwnProperty(key)) {\n\t\t\tfinished = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (var key in network.friendsAwaiting) {\n\t\tif (network.friendsAwaiting.hasOwnProperty(key)) {\n\t\t\tfinished = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (var key in network.followersAwaiting) {\n\t\tif (network.followersAwaiting.hasOwnProperty(key)) {\n\t\t\tfinished = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t// there are no network requests waited for\n\tif (finished) {\n\t\t// stop timers\n\t\tclearInterval(network.timers['users']);\n\t\tclearInterval(network.timers['friends']);\n\t\tclearInterval(network.timers['followers']);\n\t\tclearInterval(network.timers['execution']);\n\t\t\n\t\t// return the built network\n\t\tnetwork.callback(network.users);\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cities: must have profit calculated and added into each item of each city returns true if items was filitered profitable, false if all items was removed
function filterDataByParameters(cities) { // cities[0] is the blackMarket first for loop then starts from 1 for (var i = 1; i < cities.length; i++) { // Loop through every city for (var j = 0; j < cities[i].length; j++) { // Loop through every item var item = cities[i][j]; // the reason for 2 item.profit comparisons even though < minProfit would be enough is because // some weird entries can show up if you enter a negative value in Min Profit if (item.profit < minProfit || item.profit <= 0 || item.highestProfitBM_Age > maxAgeBM || item.city_age > maxAgeCity) { cities[i].splice(j, 1); j--; } } totalApprovedTrades += cities[i].length; } // only true if all the items from all the cities have been spliced if (totalApprovedTrades == 0) { if (freshTrades == 0) { printToConsole("Data too old. Pick bigger max age or update the market via the Data Client.\n"); } else if (profitableTrades == 0) { printToConsole("No profitable trades found. Try decreasing Min Profit.\n"); } else if (profitableTrades != 0 && freshTrades != 0) { printToConsole("No fresh and profitable items found. Adjust one of the parameters and try again.\n") } } else { printToConsole("Profitable and fresh items found!\n"); } return totalApprovedTrades; }
[ "function calculateProfits(cities) {\n printToConsole(\"Calculating profits...\\n\");\n var item;\n // starts from the last city (6: Caerleon) so the profit properites for Caerleon are calculated before looping\n // through the other cities in descending order. does not loop through i=0 because BM is the first index (0)\n for (var i = cities.length - 1; i > 0; i--) { // loops through all the cities starting with fortSterling\n for (var j = 0; j < cities[i].length; j++) { // loops throught all the items in a city\n /*\n i: city [BM, FS, Th, Ly, Br, Ma, Ca]\n j: item\n */\n item = cities[i][j];\n\n compareQualities(cities, i, j, ignore_maxAgeCity = false);\n if (item.city == \"Caerleon\") // for later Caerleon properties comparison\n compareQualities(cities, i, j, ignore_maxAgeCity = true);\n\n // needs to calculate profit arrays for all qualities before it can find the optimal combination and add the Caerleon properties\n if (item.quality == 5) {\n findOptimalCombination(cities, i, j);\n assignOptimalCombination(cities, i, j);\n addCaerleonProperties(cities, i, j);\n }\n\n }\n }\n return true;\n}", "function compareQualities(cities, i, j, ignore_maxAgeCity) {\n var item = cities[i][j];\n item.bmPrice = cities[0][j].buy_price_max;\n item.cityPrice = item.sell_price_min;\n\n ignore_maxAgeCity ? item.profits_array_ignored_maxAgeCity = [] : item.profits_array = [];\n\n for (var k = 0; k < item.quality; k++) {\n /*\n Assuming item.quality == 5 (masterpiece):\n k = 0: masterpiece vs masterpiece\n k = 1: masterpiece vs excellent\n k = 2: masterpiece vs outstanding\n k = 3: masterpiece vs good\n k = 4: masterpiece vs normal\n */\n var tax_modifier = document.getElementById(\"premium\").checked ? 0.97 : 0.94;\n var qualityProfit = (cities[0][j - k].buy_price_max * tax_modifier) - item.sell_price_min;\n\n if (ignore_maxAgeCity) {\n\n if (qualityProfit > 0 && cities[i][j - k].bm_age <= maxAgeBM && item.city_age <= ONE_WEEK) {\n item.profits_array_ignored_maxAgeCity.splice(0, 0, qualityProfit);\n } else {\n item.profits_array_ignored_maxAgeCity.splice(0, 0, 0);\n }\n\n if (k == (item.quality - 1)) {\n item.profits_array_ignored_maxAgeCity.push(0);\n }\n\n } else {\n\n if (qualityProfit > 0 && cities[i][j - k].bm_age <= maxAgeBM && item.city_age <= maxAgeCity) {\n item.profits_array.splice(0, 0, qualityProfit);\n } else {\n item.profits_array.splice(0, 0, 0); // adds a zero if the quality comparison is outdated or not profitable\n }\n\n if (k == (item.quality - 1)) {\n item.profits_array.push(0); // adds an extra zero to get all possible combinations later\n }\n\n if (qualityProfit >= minProfit && !ignore_maxAgeCity)\n profitableTrades++;\n if (cities[i][j - k].bm_age <= maxAgeBM && item.city_age <= maxAgeCity && !ignore_maxAgeCity)\n freshTrades++;\n\n }\n\n }\n}", "function coolCities(cities) {\n let coolTowns = cities.filter(function (element) {\n return element.temperature < 70.0 })\n return coolTowns}", "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 addCaerleonProperties(cities, i, j) {\n for (var m = 0; m < cities[i][j].quality; m++) { // loop through every item quality\n cities[i][j - 4 + m].caerleonProfit = NEGATIVE_VALUE_LARGE;\n cities[i][j - 4 + m].caerleonAge = POSITIVE_VALUE_LARGE;\n cities[i][j - 4 + m].caerleonQuality = NEGATIVE_VALUE_LARGE;\n\n if (cities[i][j - 4 + m].highestProfitBM_Quality == NEGATIVE_VALUE_LARGE) // if the item isn't going to be displayed then it doesn't need to be compared either\n continue;\n\n for (var n = cities[i][j - 4 + m].highestProfitBM_Quality - 1; n < cities[i][j].quality; n++) { // loop through all the higher qualities\n // if any profit for the same quality as highestProfitBM_Quality is bigger than caerleonProfit, reassign Caerleon properties as that item in Caerleon can be sold to the same buy order\n if (cities[i][j - 4 + m].caerleonProfit < cities[6][j - 4 + n].profits_array_ignored_maxAgeCity[cities[i][j - 4 + m].highestProfitBM_Quality - 1]) {\n cities[i][j - 4 + m].caerleonProfit = cities[6][j - 4 + n].profits_array_ignored_maxAgeCity[cities[i][j - 4 + m].highestProfitBM_Quality - 1];\n cities[i][j - 4 + m].caerleonQuality = cities[6][j - 4 + n].quality;\n cities[i][j - 4 + m].caerleonAge = cities[6][j - 4 + n].city_age;\n }\n }\n }\n}", "function city_has_building(pcity,\n\t\t pimprove)\n{\n /* TODO: implement. */\n return false;\n}", "function CheckExpenseItems(itemCount)\n{\n if (itemCount > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "function assignOptimalCombination(cities, i, j) {\n\n for (var k = 0; k < cities[i][j].optimal_combination.length; k++) {\n var item = cities[i][j - 4 + k];\n\n // if it is equal to itself's quality then it means that the item is not sold (indices start at 0\n // whereas qualities start at 1, look at \"findOptimalCombination()\" function for more info)\n if (cities[i][j].optimal_combination[k] == item.quality) {\n item.highestProfitBM_Quality = NEGATIVE_VALUE_LARGE;\n item.highestProfitBM_Price = NEGATIVE_VALUE_LARGE;\n item.highestProfitBM_Age = POSITIVE_VALUE_LARGE;\n item.profit = NEGATIVE_VALUE_LARGE;\n item.BM_order_difference = NEGATIVE_VALUE_LARGE;\n item.BM_order_difference_age = POSITIVE_VALUE_LARGE;\n item.percentileProfit = NEGATIVE_VALUE_LARGE;\n } else {\n item.highestProfitBM_Quality = cities[i][j].optimal_combination[k] + 1; // indices start at 0 but qualities at 1, so need to add 1\n item.highestProfitBM_Price = cities[i][j - 5 + item.highestProfitBM_Quality].bmPrice; // indices start at 0 but qualities at 1, so need to subtract 1\n item.highestProfitBM_Age = cities[i][j - 5 + item.highestProfitBM_Quality].bm_age;\n item.profit = Math.round(item.profits_array[item.highestProfitBM_Quality - 1]);\n item.BM_order_difference = cities[0][j - 5 + item.highestProfitBM_Quality].sell_price_min - cities[0][j - 5 + item.highestProfitBM_Quality].buy_price_max;\n item.BM_order_difference_age = getAge(cities[0][j - 5 + item.highestProfitBM_Quality].sell_price_min_date);\n item.percentileProfit = Math.round(1000 * (item.profit / item.cityPrice)) / 10;\n }\n\n }\n\n}", "isInUse() {\n const { items, filters = {} } = this.props;\n let inUse = false;\n items.forEach(item => {\n if (item.key in filters && Array.isArray(filters[item.key]) && filters[item.key].length) {\n inUse = true;\n this.hasBeenUsed = true;\n }\n });\n return inUse;\n }", "function getAllPlacesByStateAndCity(cities, result, callback) {\n\tvar items_processed = 0;\n\tif (cities.length !== 0) {\n\t\t\tcities.map( (data) => { \n\n\t\t\t\treqStates(`${API_URL}/states/${data.state_id}/cities/${data.city_id}/places`, (json) => {\n\t\t\t\t\titems_processed++;\n\t\t\t\t\tconst places = new Schema('places');\n\t\t\t\t\tlet norm_json = normalize(json, arrayOf(places));\n\t\t\t\t\tconsole.log(\"ta\", norm_json.entities);\n\t\t\t\t\tObject.assign(result.places, norm_json.entities.places);\n\t\t\t\t\tif (items_processed === cities.length) {\n\t\t\t\t\t\tcallback();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t});\n\t\t\t});\n\t\t\t\n\t\t}\n\t\telse {\n\t\t\tcallback();\n\t\t}\n}", "passesFilter(item) {\n //Fetch filter\n let filter = this.props.filter;\n if (filter.rarity === \"0\" || filter.rarity === item.rarity) { //Check if it passes rarity\n if (filter.type === \"0\" || filter.type === item.type) { //Check if item passes type-check\n if (item.price >= filter.min && (filter.max === null || item.price <= filter.max || filter.max === 0)) { //Check if item passes price-check\n if (parseInt(item.stats[0]) >= parseInt(filter.stat1) && parseInt(item.stats[1]) >= parseInt(filter.stat2)) { //check if item passes stat-check\n return true; //If item passes checks, return true\n }\n }\n }\n }\n return false; //If any of the checks fail, return false\n }", "function itemFilter(item){\n const onlyEvolutionItems = ['Dubious Disc', 'Electirizer', 'Dragon Scale',\n 'Magmarizer', 'Prism Scale', 'Protector', 'Reaper Cloth', 'Sachet',\n 'Up-Grade', 'Whipped Dream'];\n return (!item.megaEvolves \n && !(item.name.endsWith(\"Ball\") && item.name !== 'Iron Ball') \n && !(item.name.endsWith(\"Stone\") \n && item.name !== 'Hard Stone' && item.name !== 'Float Stone')\n && !(item.name.endsWith(\"Fossil\"))\n && !(item.name.endsWith(\" Z\"))\n && !(onlyEvolutionItems.includes(item.name))\n && !(item.name.endsWith(\"Cap\")) \n );\n}", "function checkCity(lat, lng) {\n if (lat.toFixed(3) >= 50.000 && lat.toFixed(3) <= 52.000) {\n if (lng.toFixed(3) >= 5.000 && lng.toFixed(3) <= 7.000) {\n inCity = true;\n $('#content_overzicht').empty();\n getWeetjes();\n getKoepons();\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n}", "enCours() {\n return !this.estGagne() && !this.estPerdu();\n }", "function filterPlace () {\n const data = { amenities: listIdAmenities };\n getPlaces(JSON.stringify(data));\n}", "filterShops(prod) {\n if(!prod.length) {\n this.shops = this.shops.map(el => { \n el.active = true;\n return el;\n });\n return this.shops;\n }\n\n const filteredShops = this.shops.filter(el => prod.every(product => el.productsids.find(i => product === i)));\n \n this.shops = this.shops.map(el => {\n if(filteredShops.indexOf(el) === -1) { \n el.active = false;\n return el;\n }\n el.active = true;\n return el;\n });\n return this.shops;\n }", "function contoh(){\n let produk = [\n {name : \"aple\", type : \"PC\"},\n {name : \"asus\", type: \"laptop\"},\n {name : \"acer\", type : \"laptop\"}\n ];\n\n hasil = produk.every(product=>product.type=== \"laptop\"); //ini akan menampilkan false karena tidak semua type laptop, sedangkan syarat dari every() semua kriteria harus terpenuhi\n\n console.log(hasil);\n}", "function hasAllColumnsDeselected() {\n var allDeselected = true;\n for( var i = 0; i < vm.items.length; i++ ) {\n if(vm.items[i].selected) {\n \tallDeselected = false;\n break;\n }\n }\n return allDeselected;\n }", "isSatisfied(item) {\n return this.specs.every(x => x.isSatisfied(item));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert array of 2d polygons into noncombined array of array Vector3 objects.
function convertToV3NoCombine (points2d) // points2d is an array of 2d polygons. { var points_all =[]; //THREE.js Vector3 array. var box = getDataRange(points2d);// for my own projection. for (var i=0; i< points2d.length; i++) { var points = []; for (var j=0; j<points2d[i].length; j++) { //var v3 = inv_stereo(points2d[i][j]); // var v3 = mapToOne4thSphere(points2d[i][j][0], points2d[i][j][1], box); var v3 = wrapOnSphere (points2d[i][j][0], points2d[i][j][1]); points.push(v3); } points_all.push(points); } return points_all; }
[ "createTransformedPolygon() {\r\n this.transformedPolygon = [];\r\n\r\n for(let i=0; i<this.polygon.length; i++) {\r\n this.transformedPolygon.push(\r\n [\r\n this.polygon[i][0] * this.scale + this.origin.x,\r\n this.polygon[i][1] * this.scale + this.origin.y\r\n ]\r\n );\r\n }\r\n }", "function flattenPoints(input) {\n let res = new Array(input.length * 2);\n for (let i = 0; i < input.length; i++) {\n res[i * 2] = input[i].x;\n res[i * 2 + 1] = input[i].y;\n }\n return res;\n}", "function getGeometries(geometries, col_arcs_){\n\tvar polygons = [];\n\tgeometries.forEach(function(d){\n\t\tif(d.type==='Polygon'){\n\t\t\tvar a = readPolygon2({arcs:d.arcs}); \n\t\t\tpolygons.push({type:'Polygon', coordinates: a, properties: d.properties})\n\t\t}\n\t\telse if(d.type==='MultiPolygon'){\n\t\t\tvar a = d.arcs.map(function(e,i){return readPolygon2({arcs:d.arcs[i]})}); \n\t\t\tpolygons.push({type:'MultiPolygon', coordinates: a, properties: d.properties})\n\t\t}\n\t\t\n\t})\n\treturn polygons;\n\tfunction readPolygon2(data){\n\t\tvar interPolys = [];\n\t\t//loop the linestrings of the polygon\n\t\tfor (var i=0;i<data.arcs.length;i++){\n\t\t\t//get the related 'LineString's by splitting at the start/end points (length === 4) \n\t\t\tvar poly_cache = [];\n\t\t\tfor (var j=0; j<data.arcs[i].length;j++){\n\t\t\t\tvar arc_id = data.arcs[i][j];\n\t\t\t\tvar sign = 1; \n\t\t\t\tif(arc_id<0){arc_id= (arc_id*(-1))-1; sign = -1;}\n\t\t\t\tvar arcs_cache2 = col_arcs_[arc_id].coordinates.slice();//--> das war der knackpunkt!!!!!!!!!!http://www.d-mueller.de/blog/javascript-arrays-kopieren/\n\t\t\t\tif(sign===-1){arcs_cache2.reverse();}\n\t\t\t\t//remove the last (it is redundant!!!) ...do only, when it is not the last LineString\n\t\t\t\tif(j!==data.arcs[i].length-1){arcs_cache2.pop();}\n\t\t\t\t//re-build the polygon to test this implementation\n\t\t\t\tfor (var x = 0;x<arcs_cache2.length;x++) poly_cache.push(arcs_cache2[x])\t\t\t\t\n\t\t\t}\n\t\t\tinterPolys.push(poly_cache);\t\t\t\t\t\n\t\t}\n\t\treturn interPolys;\n\t}\n}", "get vertices3() {\r\n\t\tlet projectedVertices = [];\r\n\t\tconst len = this.vertices.length;\r\n\t\tfor (let i = 0; i < len; i++) projectedVertices.push(this.vertices[i].project());\r\n\t\treturn projectedVertices;\r\n\t}", "function convert4x4(array) {\n currentIndex = 0;\n var newArray = [[null,null,null,null],[null,null,null,null],[null,null,null,null],[null,null,null,null]];\n for (i = 0; i < 4; i++) {\n for (j = 0; j < 4; j++) {\n newArray[i][j] = array[currentIndex];\n currentIndex++;\n }\n }\n return newArray;\n }", "allPolygons() {\n\t\tlet polygons = this.polygons.slice();\n\t\tif (this.front) polygons = polygons.concat(this.front.allPolygons());\n\t\tif (this.back) polygons = polygons.concat(this.back.allPolygons());\n\t\treturn polygons;\n\t}", "function convertArrayToXY(array) {\n const newArray = [];\n for(let i = 0; i < array.length; i += 2) {\n newArray.push({\n x: array[i],\n y: array[i + 1]\n });\n }\n return newArray;\n}", "function mapByPolygonVertexToByVertex( data, indices, stride ) {\n\n var tmp = {};\n var res = [];\n var max = 0;\n\n for ( var i = 0; i < indices.length; ++ i ) {\n\n if ( indices[ i ] in tmp ) {\n\n continue;\n\n }\n\n tmp[ indices[ i ] ] = {};\n\n for ( var j = 0; j < stride; ++ j ) {\n\n tmp[ indices[ i ] ][ j ] = data[ i * stride + j ];\n\n }\n\n max = max < indices[ i ] ? indices[ i ] : max;\n\n }\n\n try {\n\n for ( i = 0; i <= max; i ++ ) {\n\n for ( var s = 0; s < stride; s ++ ) {\n\n res.push( tmp[ i ][ s ] );\n\n }\n\n }\n\n } catch ( e ) {\n //console.log( max );\n //console.log( tmp );\n //console.log( i );\n //console.log( e );\n }\n\n return res;\n\n}", "allPolygons() {\n let e = this.polygons.slice();\n return this.front && (e = e.concat(this.front.allPolygons())), this.back && (e = e.concat(this.back.allPolygons())), e;\n }", "function change_from_2D_to_1D(array)\n{\n\tvar new_array = [];\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\tfor (var j = 0; j < array[i].length; j++)\n\t\t{\n\t\t\tnew_array.push(array[i][j]);\n\t\t}\n\t}\n\treturn new_array;\n}", "static FromArray(array, offset = 0) {\n return new Vector3(array[offset], array[offset + 1], array[offset + 2]);\n }", "function FiltroPuntosPolygonCoroplejico(Polygon, Puntos) {//\n var statesData = {\"type\": \"FeatureCollection\", \"features\": []};\n var puntosFiltradosCliente = [];\n var lenPuntos = Puntos.length;\n //var GeoJSON = Polygon.toGeoJSON();\n statesData.features.push(Polygon);\n var gjLayer = L.geoJson(statesData);\n for (var i = 0; i < lenPuntos; i++) {\n var layer = null;\n layer = leafletPip.pointInLayer([Puntos[i][1], Puntos[i][0]], gjLayer, true);\n if (layer.length > 0) {\n puntosFiltradosCliente.push([Puntos[i][0], Puntos[i][1]]);\n }\n }\n return puntosFiltradosCliente;\n}", "function vectorize3D (oldpath, error) { // eslint-disable-line\n var path = []\n for (var seg = 0; seg < oldpath.length; ++seg) {\n var x0 = oldpath[seg][0][X]\n var y0 = oldpath[seg][0][Y]\n var z0 = oldpath[seg][0][Z]\n path[path.length] = [\n [x0, y0, z0]\n ]\n var xsum = x0\n var ysum = y0\n var zsum = z0\n var sum = 1\n for (var pt = 1; pt < oldpath[seg].length; ++pt) {\n var x = oldpath[seg][pt][X]\n var y = oldpath[seg][pt][Y]\n var z = oldpath[seg][pt][Z]\n var xold = x\n var yold = y\n var zold = z\n if (sum === 1) {\n xsum += x\n ysum += y\n zsum += z\n sum += 1\n } else {\n var xmean = xsum / sum\n var ymean = ysum / sum\n var zmean = zsum / sum\n var dx = xmean - x0\n var dy = ymean - y0\n var dz = zmean - z0\n var d = Math.sqrt(dx * dx + dy * dy + dz * dz)\n var nx = dx / d\n var ny = dy / d\n var nz = dz / d\n var vx = (x - x0)\n var vy = (y - y0)\n var vz = (z - z0)\n var l = Math.sqrt((vx * vx + vy * vy + vz * vz) - (vx * nx + vy * ny + vz * nz) * (vx * nx + vy * ny + vz * nz))\n if (l < error) {\n xsum += x\n ysum += y\n zsum += z\n sum += 1\n } else {\n path[path.length - 1][path[path.length - 1].length] = [xold, yold, zold]\n x0 = xold\n y0 = yold\n z0 = zold\n xsum = xold\n ysum = yold\n zsum = zold\n sum = 1\n }\n }\n if (pt === (oldpath[seg].length - 1)) {\n path[path.length - 1][path[path.length - 1].length] = [x, y, z]\n }\n }\n }\n return path\n}", "static FromArray(array, offset = 0) {\n return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }", "build(polygons) {\n\t\tif (!polygons.length) return;\n\t\tif (!this.plane) this.plane = polygons[0].plane.clone();\n\t\tlet front = [],\n\t\t\tback = [];\n\t\tfor (let i = 0; i < polygons.length; i++) {\n\t\t\tthis.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);\n\t\t}\n\t\tif (front.length) {\n\t\t\tif (!this.front) this.front = new Node();\n\t\t\tthis.front.build(front);\n\t\t}\n\t\tif (back.length) {\n\t\t\tif (!this.back) this.back = new Node();\n\t\t\tthis.back.build(back);\n\t\t}\n\t}", "function normalize(polygon, positionSize) {\n validate(polygon);\n const positions = [];\n const holeIndices = [];\n\n if ('positions' in polygon) {\n // complex flat\n const {\n positions: srcPositions,\n holeIndices: srcHoleIndices\n } = polygon;\n\n if (srcHoleIndices) {\n let targetIndex = 0; // split the positions array into `holeIndices.length + 1` rings\n // holeIndices[-1] falls back to 0\n // holeIndices[holeIndices.length] falls back to positions.length\n\n for (let i = 0; i <= srcHoleIndices.length; i++) {\n targetIndex = copyFlatRing(positions, targetIndex, srcPositions, positionSize, srcHoleIndices[i - 1], srcHoleIndices[i], i === 0 ? OUTER_POLYGON_WINDING : HOLE_POLYGON_WINDING);\n holeIndices.push(targetIndex);\n } // The last one is not a starting index of a hole, remove\n\n\n holeIndices.pop();\n return {\n positions,\n holeIndices\n };\n }\n\n polygon = srcPositions;\n }\n\n if (!isNested(polygon)) {\n // simple flat\n copyFlatRing(positions, 0, polygon, positionSize, 0, positions.length, OUTER_POLYGON_WINDING);\n return positions;\n }\n\n if (!isSimple(polygon)) {\n // complex polygon\n let targetIndex = 0;\n\n for (const [polygonIndex, simplePolygon] of polygon.entries()) {\n targetIndex = copyNestedRing(positions, targetIndex, simplePolygon, positionSize, polygonIndex === 0 ? OUTER_POLYGON_WINDING : HOLE_POLYGON_WINDING);\n holeIndices.push(targetIndex);\n } // The last one is not a starting index of a hole, remove\n\n\n holeIndices.pop(); // last index points to the end of the array, remove it\n\n return {\n positions,\n holeIndices\n };\n } // simple polygon\n\n\n copyNestedRing(positions, 0, polygon, positionSize, OUTER_POLYGON_WINDING);\n return positions;\n}", "function copy(shape) {\n return shape.map(p => new Vec2(p.x, p.y));\n}", "parse(array = [[0, 0]]) {\n var points = []; // if it is an array\n\n if (array instanceof Array) {\n // and it is not flat, there is no need to parse it\n if (array[0] instanceof Array) {\n return array;\n }\n } else {\n // Else, it is considered as a string\n // parse points\n array = array.trim().split(delimiter).map(parseFloat);\n } // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints\n // Odd number of coordinates is an error. In such cases, drop the last odd coordinate.\n\n\n if (array.length % 2 !== 0) array.pop(); // wrap points in two-tuples\n\n for (var i = 0, len = array.length; i < len; i = i + 2) {\n points.push([array[i], array[i + 1]]);\n }\n\n return points;\n }", "function convert(array) {\n return array.reduce((acc, layer) => {\n //console.log(layer.getProperties().group);\n acc.push({\n layer: layer,\n name: layer.getProperties().name,\n title: layer.getProperties().title,\n visibility: layer.getProperties().visible,\n group: layer.getProperties().group\n });\n return acc;\n }, []);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for this.mood_check, tells the model whether to offer mood check at the end.
set_mood_check(value) { this.mood_check = value; return this; }
[ "set_mood_induction(value) {\n this.mood_induction = value;\n return this;\n }", "function increaseMood(amount, threshold) {\n\tif(!threshold || WORLD.AGENT.state.mood < threshold)\n\t\tWORLD.AGENT.state.mood += amount;\n\t\n\t// clamp the value between 0 and 1\n\tWORLD.AGENT.state.mood = Math.max(0, Math.min(1, WORLD.AGENT.state.mood));\n}", "function getCurrentMood()\n{\n return currentMood;\n}", "mood_check_compute() {\n\n // get the phq uds and tally the score\n let mood_uds = this.uds.get_all(RESPONSE_MOOD);\n let score = 0;\n for(let ud of mood_uds) {\n score = Math.max(score, Number(ud.response));\n }\n\n if(score < MOOD_LOWEST_FAIL) {\n // Remove the positive induction frame\n let start_deleting_idx = null;\n for(let i=0; i<this.frames.length; i++) {\n let frame = this.frames[i];\n if(frame.template === POSITIVE_INDUCTION_TEMPLATE) {\n start_deleting_idx = i;\n break;\n }\n }\n let num_to_delete = 2; // Blocker frame and positive mood induction\n this.frames.splice(start_deleting_idx, num_to_delete);\n }\n }", "function showMoodSelectionConfirmation()\n{\n // change the color of the checkmark to reflect the mood of the user\n colorCheckMark();\n // show the mood confirmation window\n switchScreens(activeWindow, document.getElementById(\"mood-logged-screen\"));\n}", "updateMuteAlarm() {\n if (!MyOptions.isQueueAlarm()) { $(`input.pcm-muteAlarm`).prop('disabled', true); $(`label.pcm-muteAlarmLabel`).addClass('pcm-strikeThrough'); }\n else {\n $(`input.pcm-muteAlarm`).prop('disabled', false); $(`label.pcm-muteAlarmLabel`).removeClass('pcm-strikeThrough');\n if (MyAlarms.getMute('queueAlert')) $(`input.pcm-muteAlarm`).prop('checked', true); else $(`input.pcm-muteAlarm`).prop('checked', false);\n }\n }", "eat() {\n if (this.food >= 1) {\n this.food -= 1\n } else { \n this.isHealthy = false\n }\n }", "onClick() {\n this.happy = !this.happy;\n }", "function setCurrentMood(newMood)\n{\n currentMood = newMood;\n // change the picture representing the user's current mood\n document.getElementById(\"mood-image-main\").href = moodNameToFilename(moodEnumToName(currentMood));\n // send the mood, heart rate, and steps to the server\n sendMoodUpdate(newMood); \n}", "function C006_Isolation_Yuki_CheckToEat() {\n\t\n\t// Yuki forces the player if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"LickEgg\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n\t// Yuki forces the player if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"LickSub\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n}", "getMuted() {\r\n return this.volume === 0 ? true : this._muted;\r\n }", "function correctChoice() {\n let correctMusic = new Howl({\n src: [\"/music/415762__thebuilder15__notification-correct.wav\"],\n volume: 0.2,\n });\n\n correctMusic.play();\n}", "function colorCheckMark()\n{\n document.getElementById(\"mood-logged-checkmark\").style[\"fill\"] = moodColorsList[currentMood].color;\n}", "function showMoodLevel() {\n\t\tvar positiveOrNegative = moodLevel > 0 ? 1 : -1;\n\t\tvar startingColor = 242;\n\t\tvar blueStep = 242 / 100;\n\t\tvar redStep = moodLevel > 0 ? 242 / 100 : 142 / 100;\n\t\tvar greenStep = moodLevel < 0 ? 242 / 100 : 142 / 100;\n\n\t\tvar newRed = startingColor - redStep * moodLevel * positiveOrNegative;\n\t\tvar newGreen = startingColor - greenStep * moodLevel * positiveOrNegative;\n\t\tvar newBlue = startingColor - blueStep * moodLevel * positiveOrNegative;\n\n\t\ttextField.style.background = \"rgb(\" + newRed + \", \" + newGreen + \", \" + newBlue + \")\";\n\t}", "function handleCheck(e) {\n\t\tsetIsComplete(e.target.checked)\n\t}", "updateMoodNum (num) {\n this.props.updateMood({...this.props.mood, rating: num})\n }", "set weighting(newWeight) {\n this._weighting = newWeight;\n setValue(`cmi.interactions.${this.index}.correct_responses`, newWeight);\n }", "toggleMusic() {\n this.musicOn = !this.musicOn;\n let w = '', f = '';\n if (this.musicOn) {\n this.playMusic(this.playingMusic);\n w = 'on';\n f = 'On';\n }\n else {\n this.disableMusic();\n w = 'off';\n f = 'Off';\n }\n this.ecs.getSystem(System.GUIManager).runSequence('notification', new Map([['notification', 'music ' + w]]), new Map([['notification', 'HUD/music' + f]]));\n }", "updateMoodDesc (event) {\n this.props.updateMood({...this.props.mood, description: event.target.value, savedDate: new Date()})\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the color of the border depending on who is winning
function updateColor() { if( userScore > compScore ) { //Player is winning table.style.border = "5px solid #38d020" } else if ( compScore > userScore ) { //Computer is winnning table.style.border = "5px solid #d21f1f" } else { //If there is a draw table.style.border = "5px solid #363636" } }
[ "hitBorder() {\n let head = this.state.rat[0]\n if (head[0] >= 100 || head[1] >= 100 || head[0] < 0 || head[1] < 0) {\n this.gameOver()\n }\n }", "function matchMessageBoardColorTo(riskLevel) {\r\n if (riskLevel === \"lowRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#62b1f5';\r\n }\r\n if (riskLevel === \"mediumRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#ffff82';\r\n }\r\n if (riskLevel === \"highRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#f56262';\r\n }\r\n\r\n}", "get borderColor() {\n return brushToString(this.i.g5);\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 changeColor(e) {\n let column = e.target.cellIndex;\n let row = [];\n\n // start with i = 5 to check for buttom row first\n for (let i = 5; i >= 0; i--) {\n if (tableRow[i].children[column].style.backgroundColor == 'white') {\n row.push(tableRow[i].children[column]);\n if (currentPlayer === 1) {\n row[0].style.backgroundColor = player1Color;\n if (horizontalWin() || verticalWin() || diagonalWin() || diagonalWin2()) {\n playerTurn.textContent = `${player1} WINS!`;\n playerTurn.style.color = player1Color;\n\n return alert(`${player1} WINS!`);\n\n } else if (draw()) {\n playerTurn.textContent = 'Game is a Draw!';\n return alert('DRAW');\n } else {\n playerTurn.textContent = `${player2}'s turn!`\n return currentPlayer = 2;\n }\n\n\n\n\n } else {\n row[0].style.backgroundColor = player2Color;\n if (horizontalWin() || verticalWin() || diagonalWin() || diagonalWin2()) {\n playerTurn.textContent = `${player2} WINS!`;\n playerTurn.style.color = player2Color;\n\n return alert(`${player2} WINS!`);\n\n } else if (draw()) {\n playerTurn.textContent = 'Game is a Draw!';\n return alert('DRAW');\n } else {\n playerTurn.textContent = `${player1}'s turn!`;\n return currentPlayer = 1;\n }\n\n \n }\n }\n }\n}", "function changeColorsToWinner(color) {\r\n for (var i = 0; i < squareColors.length; i++) {\r\n squareColors[i].style.backgroundColor = color;\r\n }\r\n}", "function changeBorder(){\n \t var myBorder = document.getElementsByTagName('div');\n \t \n \t var valuesFive = values[4];\n\n \t\t if(valuesFive === 'none'){\n myBorder[3].className = 'noneBorder';\n } else if (valuesFive === 'thin'){\n myBorder[3].className = 'smallBorder';\n } else if (valuesFive === 'thick'){\n myBorder[3].className = 'bigBorder';\n }else if (valuesFive === 'filled'){\n myBorder[3].className = 'filledBorder';\n }\n else{\n console.log('break');\n }\n }", "function resetDraw() {\n\tfor (var i=0; i<=currentTournament.numberMatches*2;i++) { \n\t\t\t$(\"#p\" + i).css(\"color\", \"#000\");\n\t\t}\n\t}", "function highlightUserScore(user) {\n // searches the table rows for the entry that matches the user\n for (var i = 1; i < leaderboardTable.rows.length; i++) {\n var r = leaderboardTable.rows[i];\n var c = r.cells;\n if (c[1].textContent === user.name && parseInt(c[2].textContent) === user.score) {\n r.style.fontWeight = \"bold\";\n r.style.background = \"rgb(50, 119, 76)\";\n break;\n }\n }\n}", "function changeAllSquare(wincolor) {\n for (let i = 0; i < squares.length; i++) {\n squares[i].style.backgroundColor = wincolor;\n }\n}", "changeColor() {\n this.currentColor = this.intersectingColor;\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 toggleWin(winner, name, screen)\n{\n const message = screen.querySelector('.message');\n const winnerName = screen.querySelector('.winner');\n //color of the winner's name depends on who won\n const color = (winner === 'x') ? 205 : 0;\n\n //changes to win screen\n switchScreen(screen);\n\n //activates the win screen of the given winner\n screen.classList.add(`screen-win-${winner}`);\n //changes win message accordingly\n message.textContent = (winner === 't') ? ('It\\'s a Cat!') : ('Winner');\n //sets winner name's text and color for display\n winnerName.textContent = name.toUpperCase();\n winnerName.style.color = `rgba(${color}, ${color}, ${color}, 0.3)`\n}", "function disp_curr_game_state(){\n game_ctx.fillStyle = \"green\" ;\n for (i = 0; i < matrix_side_length; i++){\n for (j = 0; j < matrix_side_length; j++){\n if( matrix[i][j] == 1 ){\n game_ctx.fillRect(i*unit, j*unit, unit, unit); \n }\n }\n } \n}", "checkIfWin(){\n\t\tconst g = this.state.grid;\n\t\tvar hits = 0;\n\n\t\tfor(var i = 0; i < this.gridSize; i++) {\n\t\t\tfor(var j = 0; j < this.gridSize; j++) {\n\t\t\t\tif (g[i][j] === \"Hit\") {\n\t\t\t\t\thits++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(hits === this.maxNumberOfShips*2){\n\t\t\tvar theWinner = \"\";\n\n\t\t\tif(this.props.id === \"gridA\"){\n\t\t\t\ttheWinner = \"PlayerB\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttheWinner = \"PlayerA\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\n\t\t}\n\n\t}", "function checkWin() {\n\n var winPattern = [board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], // Horizontal 0,1,2\n board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], // Vertical 3,4,5,\n board[0] + board[4] + board[8], board[2] + board[4] + board[6]\n ]; // Diagonal 6,7\n\n var USER_String = USER + USER + USER; // USER_String == \"111\"\n var AI_String = AI + AI + AI; // AI_String == \"222\"\n\n for (var i = 0; i < 8; i++) {\n if (winPattern[i] == USER_String) {\n $(\"#status\").text(\"YOU WON\")\n activateWinAnimation(i);\n return USER; // User wins\t\t\t\t\n } else if (winPattern[i] == AI_String) {\n $(\"#status\").text(\"AI WON\")\n activateWinAnimation(i);\n return AI; // AI wins\t\t\t\n }\n }\n\n if (board.indexOf(\"-\") == -1) {\n $(\"#status\").text(\"IT'S A DRAW\")\n return DRAW; // Draw!\t\t\t\t\n }\n\n return 0;\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 highlightGrid(object) {\n if(hoverGrid) hoverGrid.style.backgroundColor = \"\";\n\n for (var i = 0; i < grids.length; i++) {\n if (withinIt(object, grids[i])) {\n hoverGrid = grids[i];\n hoverGrid.style.backgroundColor = \"rgb(75, 88, 98)\";\n break;\n }\n }\n }", "function switchTurn() {\n if (turn === \"player 2\") {\n turn = \"player 1\";\n setMessage(turn + \"'s turn\");\n document.getElementById(\"playerTurn\").style.color =\"hotpink\";\n } else {\n turn = \"player 2\";\n setMessage(turn + \"'s turn\");\n document.getElementById(\"playerTurn\").style.color =\"gold\";\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the given reference chain to its string representation.
function convertReferenceChainToString(chain) { return chain.join(' → '); }
[ "toString() {\n return `${changelogTitle}\n${changelogDescription}\n\n${stringifyReleases(this._releases, this._changes)}\n\n${stringifyLinkReferenceDefinitions(this._repoUrl, this._releases)}`;\n }", "toString() {\n return `${this.constructor.name}( ${this._stack\n .map((rc) => rc.toString())\n .join(', ')} )`;\n }", "function toString ()\n{\n let baleString = \"\";\n let fieldNames = Object.keys(PROPERTIES);\n\n // Loop through the fieldNames and build the string \n for (let name of fieldNames)\n {\n baleString += name + \":\" + this[name] +\";\";\n }\n\n return baleString;\n}", "asRevString() {\n const out = [];\n let n = this;\n\n while (n) {\n out.push(n.data.toString());\n n = n.next;\n }\n\n return out.reverse().join('');\n }", "toString() {\n // Sanity check: root block must be set\n if (this._root === undefined) {\n throw new Error('expected root');\n }\n // Optimize, if flag set\n if (this._rules.shouldOptimize) {\n this._optimize();\n }\n // Set offsets\n const iterator = new iterator_1.CalldataIterator(this._root);\n let offset = 0;\n for (const block of iterator) {\n block.setOffset(offset);\n offset += block.getSizeInBytes();\n }\n // Generate hex string\n const hexString = this._rules.shouldAnnotate\n ? this._toHumanReadableCallData()\n : this._toEvmCompatibeCallDataHex();\n return hexString;\n }", "function hashMapToStr(hm){\n\t//init result\n\t//ES 2016-09-17 (b_dbg_test): shorten the text (needed for debugger to display\n\t//\tcontent of complex objects compactly)\n\tvar res = \"HM{\";\n\t//init if have not processed hashmap, yet\n\tvar isFirst = true;\n\t//check if hashmap is not empty\n\tif( Object.keys(hm).length > 0 ){\n\t\t//loop thru keys\n\t\t$.each(\n\t\t\thm, \n\t\t\tfunction(key, value){\n\t\t\t\t//ES 2016-09-17 (b_dbg_test): if value has 'getTypeName' function AND\n\t\t\t\t//\tit is either ENTITY or CONTENT\n\t\t\t\tif( typeof value.getTypeName === \"function\" &&\n\t\t\t\t\t(\n\t\t\t\t\t\tvalue.getTypeName() == RES_ENT_TYPE.CONTENT ||\n\t\t\t\t\t\tvalue.getTypeName() == RES_ENT_TYPE.ENTITY\n\t\t\t\t\t)\n\t\t\t\t){\n\t\t\t\t\t//reset value to be actual content's value\n\t\t\t\t\tvalue = interpreter.getContentObj(value)._value;\n\t\t\t\t}\t//ES 2016-09-17 (b_dbg_test): end if 'getTypeName' and either ENTITY or CONTENT\n\t\t\t\t//convert value\n\t\t\t\tvar val = objToStr(value);\n\t\t\t\t//check if val is not empty string\n\t\t\t\tif( val.length != 0 ){\n\t\t\t\t\t//compose string\n\t\t\t\t\tres += (isFirst ? \"\" : \", \") + key + \" => \" + val;\n\t\t\t\t\t//ensure it is not the first key\n\t\t\t\t\tisFirst = false;\n\t\t\t\t}\t//end if cal is not empty string\n\t\t\t}\t//end iterative function to loop thru hashmap\n\t\t);\t//end loop thru hashmap\n\t}\t//end if hashmap is not empty\n\treturn res + \"}\";\n}", "toString() {\n let normalisedContent = pureAssign(get(this, CONTENT), {});\n return `changeset:${normalisedContent.toString()}`;\n }", "get allCallsString() {\n return `All Calls:\\n${this.calls.map(c => this.stringifyCall(c)).join('\\n')}`;\n }", "function _list_to_string(list) {\r\n var s = \"\";\r\n while(list) {\r\n s += _char_to_string(list.head);\r\n list = list.tail;\r\n }\r\n return s;\r\n}", "toSTRING() {\n switch (this._type) {\n case \"NODE\":\n return this._value.nodeType === 1 ? this._value.outerHTML : this._value.nodeValue;\n case \"STRING\":\n return this._value;\n case \"YNGWIE\":\n console.log(this._value);\n let node = this._value.render();\n console.log(node)\n return node.nodeType === 1 ? node.outerHTML : node.nodeValue;\n default:\n throw new _Transform_main_js__WEBPACK_IMPORTED_MODULE_3__.default(\"Cannot transform to STRING from unsuppoted type\", this._value);\n }\n }", "serialize() {\n // cur level\n let sCurLevel = this.curLevelNum + '';\n // instrs shown\n let sInstructions = 'none';\n if (this.instructionsShown.size > 0) {\n sInstructions = Array.from(this.instructionsShown).join(';');\n }\n // level infos\n let sLevelInfos = 'none';\n if (this.levelInfos.size > 0) {\n let arrLevelInfos = [];\n for (let [n, lvlInfo] of this.levelInfos.entries()) {\n arrLevelInfos.push(n + ':' + lvlInfo.serialize());\n }\n sLevelInfos = arrLevelInfos.join(';');\n }\n return [sCurLevel, sInstructions, sLevelInfos].join('|');\n }", "function uriSerialize(obj, prefix) {\n\t\tvar str = [];\n\t\tfor(var p in obj) {\n\t\t\tvar k = prefix ? prefix + \"[\" + p + \"]\" : p, v = obj[p];\n\t\t\tstr.push(typeof v == \"object\" ?\n\t\t\t\turiSerialize(v, k) :\n\t \t\tencodeURIComponent(k) + \"=\" + encodeURIComponent(v));\n\t\t}\n\t\treturn str.join(\"&\");\n\t}", "function object_to_string(obj)\r\n{\r\n var res = \"\";\r\n for (var key in obj)\r\n {\r\n res += key + \"\\t\" + obj[key] + \"\\n\";\r\n }\r\n return res;\r\n}", "toString() {\n const {name, _schema: schema} = this.constructor;\n return `${ name }<Model> {\\n ${\n Object.keys(schema.attributeIdentities).map(attribute => (\n `${ attribute }: ${ this[attribute] }`\n )).join(',\\n ')\n }\\n}`;\n }", "function decimal2String(val) {\n if (val == null || val == 'undefined') {\n return \"\";\n }\n var s = val.toString();\n return s;\n}", "string(node) {\n if (Text.isText(node)) {\n return node.text;\n } else {\n return node.children.map(Node$1.string).join('');\n }\n }", "function stringifyProperties(properties) {\n var result = [];\n var _loop_1 = function (name, value) {\n if (value != null) {\n if (Array.isArray(value)) {\n value.forEach(function (value) {\n value && result.push(styleToString(name, value));\n });\n }\n else {\n result.push(styleToString(name, value));\n }\n }\n };\n for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {\n var _a = properties_1[_i], name = _a[0], value = _a[1];\n _loop_1(name, value);\n }\n return result.join(';');\n}", "function preOrderToString(node, arr) {\n if (node === null) {\n arr.push('X');\n return;\n }\n arr.push(node.val);\n preOrderToString(node.left, arr);\n preOrderToString(node.right, arr);\n return arr;\n }", "function print(value) {\n return typeof value === 'string' ? JSON.stringify(value) : \"\" + value;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a scheduled task profile.
static deleteAction(id){ let kparams = {}; kparams.id = id; return new kaltura.RequestBuilder('scheduledtask_scheduledtaskprofile', 'delete', kparams); }
[ "static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'delete', kparams);\n\t}", "async function deleteSchedule(ctx) {\n const { usernamect, availdate } = ctx.params;\n try {\n const sqlQuery = `DELETE FROM parttime_schedules WHERE username = '${usernamect}' AND availdate = '${availdate}'`;\n await pool.query(sqlQuery);\n ctx.body = {\n 'success': 'True!',\n };\n } catch (e) {\n console.log(e);\n ctx.status = 403;\n }\n}", "static update(id, scheduledTaskProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.scheduledTaskProfile = scheduledTaskProfile;\n\t\treturn new kaltura.RequestBuilder('scheduledtask_scheduledtaskprofile', 'update', kparams);\n\t}", "static deleteAction(virusScanProfileId){\n\t\tlet kparams = {};\n\t\tkparams.virusScanProfileId = virusScanProfileId;\n\t\treturn new kaltura.RequestBuilder('virusscan_virusscanprofile', 'delete', kparams);\n\t}", "function deleteExpiredProfiles(cb) {\n console.log('INFO: delete expired profiles');\n var stream = Profile.find({'expires': true}).stream();\n\n stream.on('data', function(profile) {\n if (profile.isExpired()) {\n profile.remove();\n }\n });\n\n stream.on('close', function() {\n cb();\n });\n}", "static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'delete', kparams);\n\t}", "static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'delete', kparams);\n\t}", "static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'delete', kparams);\n\t}", "function deleteSchedule(axios$$1, token, force) {\n var query = '';\n if (force) {\n query += '?force=true';\n }\n return restAuthDelete(axios$$1, 'schedules/' + token + query);\n }", "static add(scheduledTaskProfile){\n\t\tlet kparams = {};\n\t\tkparams.scheduledTaskProfile = scheduledTaskProfile;\n\t\treturn new kaltura.RequestBuilder('scheduledtask_scheduledtaskprofile', 'add', kparams);\n\t}", "static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'delete', kparams);\n\t}", "function deleteFirefoxProfile(profile_name, callback) {\n\tlog(\"Deleting firefox profile \" + profile_name);\n\texec_dbg('rm -rf ' + config.external.firefox_profile_dir + profile_name, function (error, stdout, stderr) {\n\t\tif (error) {\n\t\t\tcallback(\"Cannot delete firefox profile + \" + profile_name + \": \" + JSON.stringify(error));\n\t\t} else {\n\t\t\tcallback(null);\n\t\t}\n\t});\n}", "static deleteAction(scheduleResourceId){\n\t\tlet kparams = {};\n\t\tkparams.scheduleResourceId = scheduleResourceId;\n\t\treturn new kaltura.RequestBuilder('schedule_scheduleresource', 'delete', kparams);\n\t}", "'click .delete'() {\n\t\tMeteor.call('tasks.remove', this._id, (error) => {\n\t\t\tif (error)\n\t\t\t\tBert.alert( 'An error occured: ' + error.reason + '! Only the creator of the task can delete it.', 'danger', 'growl-top-right' );\n\t\t\telse\n\t\t\t\tBert.alert( 'Task removed successfully!', 'success', 'growl-top-right' );\n\t\t});\n\t}", "function deleteTask(){\n // TODO: IF program.task exists you should use mongoose's .remove function\n // on the model to remove the task with {name: program.task}\n\n // YOUR CODE HERE\n if(program.task){\n ToDoItem.remove({ name: program.task }, function (err) {\n if (err) return console.error(err);\n console.log(\"Deleted task with name: \" + program.task);\n mongoose.connection.close();\n });\n } else {\n console.log(\"No task specified\");\n mongoose.connection.close();\n }\n}", "async remove(tenantUrl, siteId, webId, webUrl) {\n await spPost(FollowedListItems(this, \"oneDrive.remove\"), request_builders_body({\n value: [\n {\n id: [tenantUrl, webId, siteId].join(\",\"),\n webUrl: webUrl,\n },\n ],\n }));\n }", "function AM_policy_delete(amServer, inputAccountIntentId){\n\n var result = {};\n var ssoToken = amServer.ssoToken;\n\n restCall = {};\n restCall.url = constructAmUri(amServer) + \"/json/realms/\" + amServer.policyRealm + \"/policies/\" + inputAccountIntentId;\n\n\tconsole.log(\"[DEBUG]: url to delete - \" + restCall.url);\n\n restCall.headers = { \"contentType\" : \"application/json\",\n \"Accept-API-Version\" : \"protocol=1.0\",\n \"iPlanetDirectoryPro\" : ssoToken};\n restCall.method = \"DELETE\";\n\n executeRest(restCall);\n\n return;\n\n}", "function deleteTaskFromLocalStorage(task) {\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n let taskTitle = document.getElementById(task).firstElementChild.innerHTML;\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === taskTitle);\r\n LocalStorageTaskArray.splice(index, 1);\r\n setLocalStorage(\"task\", LocalStorageTaskArray);\r\n}", "function DeletePostTrigger(){\n var triggerIDs = [properties.getProperty('scheduledPost_ID'), properties.getProperty('deleteTrigger_ID')];\n var allTriggers = ScriptApp.getProjectTriggers();\n for(var i = 0; i < allTriggers.length; i++){\n for(var j = 0; j < triggerIDs.length; j++){\n var trigger = allTriggers[i]\n var triggerID = trigger.getUniqueId();\n if(triggerID == triggerIDs[j]){\n ScriptApp.deleteTrigger(trigger);\n }\n }\n }\n DeleteProperty('scheduledPost_ID');\n DeletePropery('deleteTrigger_ID');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For adding callbacks to right mouse button
onRightDown (callback) { this._addDownEvent(this._buttonNames.right, callback) }
[ "_handleRowRightClick(event)\r\n {\r\n if (this.view.contextMenu)\r\n {\r\n Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__CONTEXTMENU_SHOW, {top: event.pageY,\r\n left: event.pageX,\r\n items: this.view.contextMenu});\r\n }\r\n return false;\r\n }", "isRightClicking() {\r\n return this.activeClick === RIGHT_CLICK_ID;\r\n }", "addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }", "static set miniButtonRight(value) {}", "function rightCursor() {\n let beforeScroll = menu.scrollLeft;\n menu.scrollLeft += 1;\n if (beforeScroll == menu.scrollLeft) {\n rightArrow.style.display = \"none\";\n } else {\n rightArrow.style.display = \"inline\";\n }\n menu.scrollLeft = beforeScroll;\n}", "implementMouseInteractions() {\t\t\n\t\t// mouse click interactions\n\t\tthis.ctx.canvas.addEventListener(\"click\", this.towerStoreClick, false);\n\t\t\n\t\t// mouse move interactions\n\t\tthis.ctx.canvas.addEventListener(\"mousemove\", this.towerStoreMove, false);\t\n\t}", "function handleRightClick(event) {\n var target = event.target || event.toElement;\n\n if (!target) {\n return;\n }\n\n var figure = findFigure(scribe, target);\n\n if (figure) {\n event.preventDefault();\n event.stopPropagation();\n contextMenu.show(figure);\n }\n }", "static get miniButtonRight() {}", "function sendEvent(button, pos) {\n var term = ace.session.term;\n // term.emit('mouse', {\n // x: pos.x - 32,\n // y: pos.x - 32,\n // button: button\n // });\n\n if (term.vt300Mouse) {\n // NOTE: Unstable.\n // http://www.vt100.net/docs/vt3xx-gp/chapter15.html\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n var data = '\\x1b[24';\n if (button === 0) data += '1';\n else if (button === 1) data += '3';\n else if (button === 2) data += '5';\n else if (button === 3) return;\n else data += '0';\n data += '~[' + pos.x + ',' + pos.y + ']\\r';\n term.send(data);\n return;\n }\n\n if (term.decLocator) {\n // NOTE: Unstable.\n button &= 3;\n pos.x -= 32;\n pos.y -= 32;\n if (button === 0) button = 2;\n else if (button === 1) button = 4;\n else if (button === 2) button = 6;\n else if (button === 3) button = 3;\n term.send('\\x1b[' + button + ';' + (button === 3 ? 4 : 0) + ';' + pos.y + ';' + pos.x + ';' + (pos.page || 0) + '&w');\n return;\n }\n\n if (term.urxvtMouse) {\n pos.x -= 32;\n pos.y -= 32;\n pos.x++;\n pos.y++;\n term.send('\\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');\n return;\n }\n\n if (term.sgrMouse) {\n pos.x -= 32;\n pos.y -= 32;\n term.send('\\x1b[<' + ((button & 3) === 3 ? button & ~3 : button) + ';' + pos.x + ';' + pos.y + ((button & 3) === 3 ? 'm' : 'M'));\n return;\n }\n\n var data = [];\n\n encode(data, button);\n encode(data, pos.x);\n encode(data, pos.y);\n\n term.send('\\x1b[M' + String.fromCharCode.apply(String, data));\n }", "function setDown() {\n mouseDown = true;\n}", "static rightClickElement(element) {\n this.waitElement(element, timeToWait);\n //this.moveToComponent(element);\n element.rightClick();\n }", "function mouseReleased() {\n helmet.released();\n}", "add_click(func) {\n this.add_event(\"click\", func);\n }", "function mouseDown(e) {\n // Here we changing isMoving from false to true, and depicting that now we are moving the mouse over the wheel\n setMoving(true);\n }", "function enableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = true;\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = true;\n\t\t\t\tcu.button.cursor = \"pointer\";\n\t\t\t});\n\t\t\n\t\t\tself.aboutUsBtn.mouseEnabled = true;\n\t\t\tself.aboutUsBtn.cursor = \"pointer\";\n\t\t\n\t\t\tself.returnBtn.mouseEnabled = true;\n\t\t\tself.returnBtn.cursor = \"pointer\";\n\t\t}", "function mouseReleased() {\n console.log('released!');\n cursorColor = 'rgb(0,0,0)';\n cursorDia = 60;\n}", "static get miniButtonLeft() {}", "mDown(e){\n this.xMouseStart=e.offsetX;\n this.yMouseStart=e.offsetY;\n if(this.insideButton){\n Button.shape=this.name;\n }\n }", "hintRightClickPerturbingSelection() {\n this._saveSelection();\n }", "function mousePressed() {\n birthday();\n mouseWasPressed += 1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repopulates all other substantial data, including current county data, historical data, and county totals
async function repopulateCountyCollection() { const County = mongoose.model("County"); const CountyTotal = mongoose.model("CountyTotal"); var fips = 34001; for (var i = 0; i < zipcodesNJ.length; i++) { await axios .get( `https://api.covidactnow.org/v2/county/${fips}.json?apiKey=${apiKey}` ) .then((response) => { const index = i; var date = new Date(); date.setDate(date.getDate() - 2); // Insert newest (daily) data into county DB County.updateOne( { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) }, { $push: { [`data.${index}.counties.0.historicData`]: { $each: [ { date: date, deathCt: response.data.actuals.deaths, positiveCt: response.data.actuals.cases, }, ], $position: 0, }, }, }, (err) => { if (err) { console.log(err); } else { console.log(`Added newest data for ${zipcodesNJ[i]}`); } } ); // Delete oldest (daily) data from county DB County.updateOne( { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) }, { $pop: { [`data.${index}.counties.0.historicData`]: 1 } }, (err) => { if (err) { console.log(err); } else { console.log(`Deleted oldest data for ${zipcodesNJ[i]}`); } } ); CountyTotal.updateOne( { id: fips }, { totalCases: response.data.actuals.cases, }, { upsert: true }, function (err) { if (err) { console.log(err); } else { console.log(`Finished updating county total for FIPS: ${fips}`); } } ); fips += 2; }) .catch((error) => console.log(error)); } await County.findById( { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) }, (err, resp) => { var cumulativeRate = 0; for (var i = 0; i < localCountiesIndices.length; i++) { // daily increase var individualRate = resp.data[localCountiesIndices[i]].counties[0].historicData[0] .positiveCt - resp.data[localCountiesIndices[i]].counties[0].historicData[13] .positiveCt; cumulativeRate += individualRate / 14; } // rate per 100,000 cumulativeRate = (cumulativeRate / localCountyPopulation) * 100000; var date = new Date(); date.setDate(date.getDate() - 2); County.updateOne( { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) }, { $push: { averages: { $each: [{ date: date, caseRate: cumulativeRate }], $position: 0, }, }, }, (err) => { if (err) { console.log(err); } else { console.log(`Added newest data for County Averages`); } } ); County.updateOne( { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) }, { $pop: { averages: 1 } }, (err) => { if (err) { console.log(err); } else { console.log(`Deleted oldest data for County Averages`); } } ); County.updateOne( { _id: mongoose.Types.ObjectId(`5f591319ac41821082382d4b`) }, { $set: { pingryCountiesCaseRate: cumulativeRate } }, (err) => { if (err) { console.log(err); } else { console.log(`Updated 7 Day Pingry Counties Case Rate`); } } ); } ); console.log("Finished repopulating county collections."); }
[ "function doReferenceTotals() {\n if (verboseLogging) console.log(selectedCountry + 'All Countries: ' + startYear + '-' + endYear);\n\n httpGetAsync('freqs?start=' + startYear + '&end=' + endYear, function (response) {\n countryFreq = JSON.parse(response);\n var maxCorporaSize = countryFreq['max corpora size'];\n\n mergedData = mergeCountryFreq(countryFreq['countries'], maxCorporaSize, countryData, true);\n\n updateGUI();\n });\n}", "function loadCountyData(state, callback) {\n // for now let's always load the county data all at once. later we can again split\n // into single-state files if that turns out to be useful for performance.\n if(!countyData.has('USA')) {\n d3.json(\"data/county_boundaries_USA.json\", function(error, allCountiesTopo) {\n if(error) callback(error);\n \n // extract the topojson to geojson\n allCountiesGeo = topojson.feature(allCountiesTopo, allCountiesTopo.objects.counties);\n \n // cache in countyData\n countyData.set('USA', allCountiesGeo);\n \n cacheCountyData(state, callback);\n });\n } else {\n cacheCountyData(state, callback);\n }\n}", "recalculateTotals(inventories) {\n this.filteredInventories = inventories.inventories;\n Service.get(this).calculateTotals(1, inventories.inventories);\n }", "updateReconciledTotals() {\n\t\tconst decimalPlaces = 2;\n\n\t\t// Target is the closing balance, minus the opening balance\n\t\tthis.reconcileTarget = Number((this.closingBalance - this.openingBalance).toFixed(decimalPlaces));\n\n\t\t// Cleared total is the sum of all transaction amounts that are cleared\n\t\tthis.clearedTotal = this.transactions.reduce((clearedAmount, transaction) => {\n\t\t\tlet clearedTotal = clearedAmount;\n\n\t\t\tif (\"Cleared\" === transaction.status) {\n\t\t\t\tclearedTotal += transaction.amount * (\"inflow\" === transaction.direction ? 1 : -1);\n\t\t\t}\n\n\t\t\treturn Number(clearedTotal.toFixed(decimalPlaces));\n\t\t}, 0);\n\n\t\t// Uncleared total is the target less the cleared total\n\t\tthis.unclearedTotal = Number((this.reconcileTarget - this.clearedTotal).toFixed(decimalPlaces));\n\t}", "function clearTotals() {\n for (var i = 0; i < numOpenHours; i++){\n totals[i] = 0;\n tosserTotals[i] = 0;\n }\n}", "function formatRaceCountyData(json) {\n\n desiredRaceCountyData = [];\n\n for (var i = 1; i < json.length; i++) {\n var totalPopulationAllAges = json[i][0]\n var totalDesiredRace = json[i][1];\n var countyNameAndState = json[i][2];\n var stateID = json[i][3];\n var countyID = json[i][4];\n desiredRaceCountyData.push({\n TotalPopulationAllAges: totalPopulationAllAges,\n TotalDesiredRace: totalDesiredRace,\n CountyNameAndState: countyNameAndState,\n CountyID: +stateID + countyID\n });\n }\n return desiredRaceCountyData\n }", "function getCountiesPopulation(county_array){\n let all_counties_population = {};\n census_data.population.forEach((ele)=>{\n if(all_counties_population.hasOwnProperty(ele.county) === false){\n all_counties_population[ele.county] = {\n male: ele.male,\n female: ele.female,\n sum: ele.male + ele.female\n }\n }\n else\n {\n all_counties_population[ele.county].male += ele.male;\n all_counties_population[ele.county].female += ele.female;\n all_counties_population[ele.county].sum += ele.male + ele.female;\n }\n \n })\n \n return all_counties_population;\n}", "function addToAnnualTotals(record) {\n for(var field in record.totals) {\n if (record.totals.hasOwnProperty(field)) {\n if (!$scope.annualTotals.hasOwnProperty(field)) {\n $scope.annualTotals[field] = 0;\n }\n $scope.annualTotals[field] += record.totals[field];\n }\n }\n }", "function loadIndicatorsObservations(forASingleCounty) {\n\t\tvar bindings = queryIndicatorResults.results.bindings;\n\t\tvar localIndicators = [];\n\t\tvar localProps = [];\n\t\tvar localRegions = [];\n\t\tvar len = 0;\n\t\t\n\t\n\t\tfor (var i=0; i<bindings.length; i++) {\n\t\t\t// in each row we have ?prop ?proplabel ?geo ?geolabel ?val\n\t\t\tvar row = bindings[i];\n\t\t\tvar property = new Object;\n\t\t\tproperty.top1label = row.top1label.value.toUpperCase();\n\t\t\tproperty.top2label = row.top2label.value;\n\t\t\tproperty.prop = row.prop.value;\n\t\t\tproperty.proplabel = row.proplabel.value;\n\t\t\tproperty.geo = row.geo.value;\n\t\t\tproperty.geolabel = row.geolabel.value;\n\t\t\tproperty.val = row.val.value;\n\t\t\t//remover the (administrative) from the label\n\t\t\tindex = property.geolabel.indexOf(\"(administrative)\");\n\t\t\tif (index != -1)\n\t\t\t\tproperty.geolabel = property.geolabel.substring(0,index);\n\t\t\tlocalProps[property.prop] = property.proplabel;\n\t\t\tlocalRegions[property.geo] = property.geolabel; //keep it just in case\n\t\t\tlocalIndicators[len++] = property;\n\t\t\t\n\t\t\t//topLevelInd[property.top1label] = property.top1label;\n\t\t\t//topLevel2Ind[property.top2label] = property.top2label;\n\t\t\t\n\t\t\tupdateArrayLists(property.top1label,property.top2label,property.proplabel);\n\t\t\t\n\t\t}\n\t\t\n\t\tprocessIndicatorsObservations(localIndicators,localProps,localRegions);\n\t\t\n\t}", "function updateTotals(initialTotal){\n\tvar tempTotal = 0.00;\n\tvar donsTotal = 0.00;\n\tvar membershipTotal = 0.00;\n\tvar subsTotal = 0.00;\n\n\tvar subItems = '';\n\tvar cartItems = '';\n\n\tif(initialTotal != undefined){\n\t\ttempTotal = parseFloat(initialTotal);\n\t}\n\t//all subscription type items\n\t//cycles thorugh all items where class='subItem\n\t//id = subsriptionname\n\t//value = price\n\t//name = type of subscription\n\t$('.subItem').each(function(){\n\t\tif(this.checked){\n\t\t\tif(this.name==\"SUBSCRIPTIONNAME\"){\n\t\t\t\tsubsTotal += parseFloat(this.value);\n\t\t\t}\n\t\t\tif(this.name==\"MEMBERSHIPNAME\"){\n\t\t\t\tmembershipTotal += parseFloat(this.value);\n taxTotal = getMembershipTax( $(this).attr(\"id\"), $(\"#State\").val() );\n\t\t\t}\n\n\t\t\tsubItems += this.id+',';\n\t\t\ttempTotal += parseFloat(this.value) + parseFloat(taxTotal);\n\t\t}\n\n\t\tif((this.type==\"text\") && (parseFloat(this.value) > 0.00)){\n\t\t\tif(this.name==\"DONATIONNAME\"){\n\t\t\t\tdonsTotal += parseFloat(this.value);\n\t\t\t\tsubItems += this.id + '=' +this.value + ',';\n\t\t\t\ttempTotal += parseFloat(this.value);\n\t\t\t}\n\t\t}\n\t});\n\n\t$('#subsTotal').html(parseFloat(subsTotal).toFixed(2));\n\t$('#membershipTotal').html(parseFloat(membershipTotal).toFixed(2));\n\t$('#donsTotal').html(parseFloat(donsTotal).toFixed(2));\n\t$('#totalAmt').html(parseFloat(tempTotal).toFixed(2));\n\n\t//trim trailing comma off subitems\n\t$('#SUBITEMS').val(subItems.substring(0,subItems.length-1));\n\t//debug('Subitems: '+$('SUBITEMS').value);\n}", "function _resetDayCosts(date) {\r\n for (var department in departments) {\r\n if (!departments.hasOwnProperty(department)) {\r\n continue;\r\n }\r\n var $depRow = $dayCostTable.find(\"tr[data-dep-id=\"+department+\"]\");\r\n var $depHours = $depRow.find(\"td[data-col=hours]\");\r\n var $depOvertime = $depRow.find(\"td[data-col=overtime]\");\r\n var $depCost = $depRow.find(\"td[data-col=cost]\");\r\n\r\n $depHours.text(0);\r\n $depOvertime.text(0);\r\n $depCost.text(\"$0\");\r\n }\r\n var $depRow = $dayCostTable.find(\"tr[data-dep-id=total]\");\r\n var $depHours = $depRow.find(\"td[data-col=hours]\");\r\n var $depOvertime = $depRow.find(\"td[data-col=overtime]\");\r\n var $depCost = $depRow.find(\"td[data-col=cost]\");\r\n\r\n $depHours.text(0);\r\n $depOvertime.text(0);\r\n $depCost.text(\"$0\");\r\n }", "function resetData() {\n geoJSON = {\n type: \"FeatureCollection\",\n features: []\n };\n myMap.data.forEach(function(feature) {\n myMap.data.remove(feature);\n });\n }", "function updateData(){\n\tdataDict.clear();\n\tdataDict.setparse(\"NAMESPACES\", JSON.stringify(namespaces));\n\tdataDict.setparse(\"TRACKS\", tracksDict.stringify());\n\n\tupdateDef();\n}", "updateGoodTypeCounts() {\n getValidGoodTypes().forEach((goodType) => {\n // Reset all calculated values from previous iteration\n this.setRoyalty(goodType.name, 0);\n this.countSubtotals[goodType.name] = 0;\n // Each player has inputs that come in a specific type. Some goods score extra when it comes to\n // determining bonuses for first and second (King and Queen). Recaclulate the total for each goodType.\n goodType.goods.forEach((targetGood) => {\n // Multiplier is relevant for royal goods.\n this.countSubtotals[goodType.name] += this.getCount(targetGood.name) * targetGood.multiplier;\n });\n });\n }", "function partyTotals(data_json) {\n\n //array of objects\n\n var totals_obj = {\n D: 0,\n R: 0,\n I: 0\n }\n\n //loop NYT json data (watch out for senator/house linked scripts)\n\n var members = data_json.results[0].members\n\n for (var i = 0; i < members.length; i++) {\n //find party of current member\n var member_party = members[i].party\n //update by one the value of totals object matching value-name\n switch (member_party) {\n\n case \"D\":\n totals_obj.D += 1;\n //console.log(\"member_party is: \"+member_party)\n break;\n case \"R\":\n totals_obj.R += 1;\n //console.log(\"member_party is: \"+member_party)\n break;\n case \"I\":\n totals_obj.I += 1;\n //console.log(\"member_party is: \"+member_party)\n break;\n\n }\n\n }\n\n console.log(JSON.stringify(totals_obj)) //FEEDBACK: totals_obj\n\n\n return totals_obj\n }", "function initializeRecords(responseRecords) {\n for(var i in responseRecords) {\n var record = responseRecords[i];\n\n recordUtils.calculateDailyTotals(record);\n record.totals = recordUtils.getRecordTotals(record);\n\n if (record.scope === \"E\") {\n $scope.records.employee.push(record);\n } else {\n addToAnnualTotals(record);\n $scope.records.other.push(record);\n }\n }\n }", "updateCustomerList() {\r\n this.customers = this.calculateCustomerInfo(this.orders);\r\n }", "function fetchUserTotals() {\n database.ref('userWorkoutTotals').on('value', snapshot => {\n snapshot.forEach(child => {\n usersWithWorkouts.push(child.key);\n let userTotalData = {\n user: child.key\n }\n // Checks to see if there is a value for each before adding\n if (child.val().running != undefined) {\n userTotalData.running = child.val().running.total;\n }\n if (child.val().walking != undefined) {\n userTotalData.walking = child.val().walking.total;\n }\n if (child.val().biking != undefined) {\n userTotalData.biking = child.val().biking.total;\n }\n if (child.val().lifting != undefined) {\n userTotalData.lifting = child.val().lifting.total;\n }\n userTotals.push(userTotalData);\n });\n });\n\n // Generates the initial users list with all of the users in the database\n generateUserHTML();\n highlightCurrentUser();\n}", "function update2013Revenue() {\n\nvar i;\nvar update2013Revenue =\"\";\nfor (c in employees) employees[c]['2013 Revenue'] = \"\"; // RESETTING OLD REVENUE2013 VALUES\n\n//TABLE HEADER\n\tupdate2013Revenue += \"<table><th>Internal ID</th><th>Name</th><th>Supervisor</th><th>2012 Revenue</th><th>2013 Revenue</th>\"; \n\t\n//CALCULATING EACH EMPLOYEE'S REVENUE\t\n\tfor (i in employees){ \n\t\n\t\tfor (r in revenue2013) {\n\t\t\t\n\t\t\tif (employees[i].internalid == revenue2013[r].Employee) {\n\t\t\t\n\t\t\t\temployees[i]['2013 Revenue'] += Number(revenue2013[r].amount);\n\t\t\t\temployees[i]['2013 Revenue'] = Number(employees[i]['2013 Revenue']);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n// CALCULATING SUPERVISOR'S REVENUE\n\t\tif (employees[i].supervisor) { \n\t\t\t\n\t\t\temployees[employees[i].supervisor-1]['2013 Revenue'] += employees[i]['2013 Revenue'];\n\t\t\temployees[employees[i].supervisor-1]['2013 Revenue'] = parseInt(employees[employees[i].supervisor-1]['2013 Revenue']);\n\t\t}\n\t\t\n\t}\n\n// POPULATING REVENUE 2013 BY EMPLOYEES AND SUPERVISORS\n\tfor (i in employees) update2013Revenue += \"<tr><td>\" + employees[i].internalid + \"</td><td>\" + employees[i].name + \"</td><td>\" + employees[i].supervisor + \"</td><td>\" + \"$\" + employees[i]['2012 Revenue'].replace(/\\d(?=(\\d{3})+\\.)/g, '$&,') + \"</td><td>\" + \"$\" + employees[i]['2013 Revenue'].toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,') + \"</td></tr>\";\n\t\n\t\t\n// SENDING DATA TO HTML\n\t\tdocument.getElementById(\"update2013Revenue\").innerHTML = update2013Revenue;\n\t\tupdate2013Revenue +=\"</table>\";\n\t\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION NAME : modulePortContent AUTHOR : Krisfen G. Ducao DATE : March 12, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : PARAMETERS :
function modulePortContent(num,id,name,limit){ var tab = ""; var msg = "Port per device is over the limit.\nMaximum ports perr device is 256" $('#devicetypetabs').tabs(); if (num>=limit) { error(msg,"Notification") var val = 0; $('#portperdevice').val(""); } if(num==""){return 0;} for(var a=1; a<=num; a++){ tab +="<li id='"+id+a+"' style='display:none'"; tab +=" style='width: auto;'"; tab +=" onclick=\"slotPortInfoShow('"+id+a+"','"+a+"')\" "; tab +="class='ui-tabs-anchor ui-state-default ui-corner-top plimitshow'>"; tab +="<a href='#tabs-"+a+"' style='color: "; tab +="white;font-weight: bold;'>"+name+a+"</a></li>"; } var ret = ({tabs:tab});//,contents:content}); return ret; }
[ "function slotPOrtContent(num,id,name,limit){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\nMaximum ports perr device is 256\"\n\t$('#devicetypetabs').tabs();\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\t$('#portperdevice').val(\"\");\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\ttab +=\" style='width: auto;'\";\n\t\ttab +=\" onclick=\\\"slotPortInfoShow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top plimitshow'>\";\n\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n}", "function portSlotContent(){\n\tvar content = \"\";\n\tvar a = conterninfor.num\n\tvar addinfo = conterninfor.str\n\tcontent += \"<table \"+addinfo+\" id='tabs-\"+a+\"-slot\"+GlobalSlotId+\"'\";\n\tcontent += \" class='infoshowhide'>\";\n\tcontent += \"<tr><td style='width: 90px;'>\";\n\tcontent += \"<p>Physical port type: <br></td><td><br>\";\n\tcontent += \"<select id='porttypeinfo\"+a+\"' \";\n\tcontent += \"data-mini='true' style='width: 150px;'>\";\n\tcontent += \"<option value=''>Layer 1</option>\";\n\tcontent += \"<option value=''>Layer 2</option>\"\n\tcontent += \"<option value=''>Open Port</option>\";\n\tcontent += \"<option value=''>Direct connect\";\n\tcontent += \"</option></select>\";\n\tcontent += \"</p><br></td><td><br><p>Media type</p><br></td>\";\n\tcontent += \"<td><br><p><select></select></p><br></td>\";\n\tcontent += \"</tr><tr><td><p>Port name: <br></td><td><br>\";\n\tcontent += \"<input id='portnamenumber\"+a+\"' \";\n\tcontent += \"type='text'/></p><br></td>\";\n\tcontent += \"</tr><tr><td style='width: 90px;'><br>\";\n\tcontent += \"<p>Sub chanel</p></td></tr></table>\";\n\treturn content\n}", "function createPortlet(id, title, content, column) {\n var template = \"<div class='portlet' id='{0}'><div class='portlet-header'>{1}</div><div class='portlet-content'>{2}</div></div>\";\n var target = template.format(id, title, content);\n $('#' + column).append(target);\n makeIntoPortlet(id);\n}", "function dynamicModuleTab(num,id,name,limit,type){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\n\"\n\tmsg += \"Maximum ports perr device is 256.\"\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\tval = 0;\t\n\t\treturn 0;\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\tif (type == \"slotmodule\"){\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"moduleinfoshow('\"+id+a+\"','\"+a+\"','slotmodule')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-slot-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\n\t\t}else{\n\t\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\t\ttab +=\" style='width: auto;'\";\n\t\t\ttab +=\" onclick=\\\"moduleinfoshow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top splimitshow'>\";\n\t\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t\t}\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n}", "function SetContent(selectedContentNumber) {\n\n SetPicture(selectedContentNumber);\n SetDescriptionText(selectedContentNumber);\n\n}", "function BookmarksPortletData( namespace,\n bookmark_form_newWindow,\n bookmark_form_url,\n bookmark_forms_empty,\n bookmark_forms_error,\n bookmark_reference_url,\n bookmarksTreeAndForm,\n entry_childFolderPrefix,\n entry_edit_cancelLink,\n entry_edit_editLink,\n entry_form_action,\n entry_form_action_editBookmark,\n entry_form_action_editFolder,\n entry_form_action_editCollection,\n entry_form_action_newBookmark,\n entry_form_action_newFolder,\n entry_form_action_newCollection,\n entry_form_folderPath,\n entry_form_folderPathLabel,\n entry_form_idPath,\n entry_form_name,\n entry_form_note,\n entry_imagePrefix,\n entry_reference_folderPath,\n entry_reference_name,\n entry_reference_note,\n folder_forms_empty,\n folder_forms_error,\n folder_image_closed,\n folder_image_open,\n collection_form_url,\n collection_forms_empty,\n collection_forms_error,\n options_form,\n options_showLink,\n messages_folder_create,\n messages_folder_move,\n messages_delete_bookmark_prefix,\n messages_delete_bookmark_suffix,\n messages_delete_folder_prefix,\n messages_delete_folder_suffix,\n messages_delete_collection_prefix,\n messages_delete_collection_suffix) {\n\n this.namespace = namespace;\n\n this.bookmark_form_newWindow = bookmark_form_newWindow;\n this.bookmark_form_url = bookmark_form_url;\n this.bookmark_forms_empty = bookmark_forms_empty;\n this.bookmark_forms_error = bookmark_forms_error;\n this.bookmark_reference_url = bookmark_reference_url;\n this.bookmarksTreeAndForm = bookmarksTreeAndForm;\n this.entry_childFolderPrefix = entry_childFolderPrefix;\n this.entry_edit_cancelLink = entry_edit_cancelLink;\n this.entry_edit_editLink = entry_edit_editLink;\n this.entry_form_action = entry_form_action;\n this.entry_form_action_editBookmark = entry_form_action_editBookmark;\n this.entry_form_action_editFolder = entry_form_action_editFolder;\n this.entry_form_action_editCollection = entry_form_action_editCollection;\n this.entry_form_action_newBookmark = entry_form_action_newBookmark;\n this.entry_form_action_newFolder = entry_form_action_newFolder;\n this.entry_form_action_newCollection = entry_form_action_newCollection;\n this.entry_form_folderPath = entry_form_folderPath;\n this.entry_form_folderPathLabel = entry_form_folderPathLabel;\n this.entry_form_idPath = entry_form_idPath;\n this.entry_form_name = entry_form_name;\n this.entry_form_note = entry_form_note;\n this.entry_imagePrefix = entry_imagePrefix;\n this.entry_reference_folderPath = entry_reference_folderPath;\n this.entry_reference_name = entry_reference_name;\n this.entry_reference_note = entry_reference_note;\n this.collection_form_url = collection_form_url;\n this.collection_forms_empty = collection_forms_empty;\n this.collection_forms_error = collection_forms_error;\n this.folder_forms_empty = folder_forms_empty;\n this.folder_forms_error = folder_forms_error;\n this.folder_image_closed = folder_image_closed;\n this.folder_image_open = folder_image_open;\n this.options_form = options_form;\n this.options_showLink = options_showLink;\n this.messages_folder_create = messages_folder_create;\n this.messages_folder_move = messages_folder_move;\n this.messages_delete_bookmark_prefix = messages_delete_bookmark_prefix;\n this.messages_delete_bookmark_suffix = messages_delete_bookmark_suffix;\n this.messages_delete_folder_prefix = messages_delete_folder_prefix;\n this.messages_delete_folder_suffix = messages_delete_folder_suffix;\n this.messages_delete_collection_prefix = messages_delete_collection_prefix;\n this.messages_delete_collection_suffix = messages_delete_collection_suffix;\n\n\n //Handy function for debugging\n function toString() {\n var stringVal = \"BookmarksPortletData[\";\n var hasProperties = false;\n\n for (var property in this) {\n hasProperties = true;\n\n if ((this[property] + \"\").indexOf(\"function \") != 0) {\n stringVal += property + \"=\" + this[property] + \", \";\n }\n }\n \n\n if (hasProperties) {\n stringVal = stringVal.substring(0, stringVal.length - 2);\n }\n\n stringVal += \"]\";\n\n return stringVal;\n }\n this.toString = toString;\n\n //Object registers itself with the global array of data objects\n bookmarkPortletsData[namespace] = this;\n}", "function getHtmlContent(){\n \n }", "function rssFeed()\n{\n print( \"<?xml version=\\\"1.0\\\"?>\\n\" );\n print( \"<rss version=\\\"2.0\\\">\\n\" );\n print( \"\\t<channel>\\n\" );\n title = config.GENERAL.TITLE;\n print( \"\\t\\t<title>title</title>\\n\" );\n url = \"http://\"+_SERVER.SERVER_NAME._SERVER.SCRIPT_NAME;\n print( \"\\t\\t<link>\"+url+\"</link>\\n\" );\n print( \"\\t\\t<description>Recently changed pages on the title wiki.</description>\\n\" );\n print( \"\\t\\t<generator>Wiki v\"+config.PAWFALIKI_VERSION+\"</generator>\\n\" ); \n files = wikiReadDir(pageDir());\n details = [];\n for( i = 0 ; i < files.length ; i++ ){\n file = files[i];\n details[file] = FILE.filedate( file );\n }\n //arsort(details);\n //reset(details);\n item = 0;\n numItems = config.RSS.ITEMS;\n while ( list(key, val) = each(details) ) \n {\n title = basename(key);\n modtime = date( config.RSS.MODTIME_FORMAT, val );\n description = title+\" \"+modtime;\n print( \"\\t\\t<item>\\n\" );\n if (config.RSS.TITLE_MODTIME) \n print( \"\\t\\t\\t<title>description</title>\\n\" );\n else\n print( \"\\t\\t\\t<title>title</title>\\n\" );\n print( \"\\t\\t\\t<link>\"+url+\"?page=title</link>\\n\" ); \n print( \"\\t\\t\\t<description>\"+description+\"</description>\\n\" );\n print( \"\\t\\t</item>\\n\" ); \n item++;\n if (numItems!=-1&&item>=numItems)\n break;\n }\n print( \"\\t</channel>\\n\" );\n print( \"</rss>\\n\" );\n}", "function portContentMobile(){\n\tvar content = \"\";\n\tcontent += \"<table \";\n\tcontent += \" class='infoshowhide' style='width: 100%;'>\";\n\tcontent += \"<tr><td><table><tr>\"\n\tcontent += \"<td style='width: 20px;' !important;></td>\";\n\tcontent += \"<td style='width: 150px;'>\";\n\tcontent += \"Port type: <br></td><td><br>\";\n\tcontent += \"<select id='porttypeinfo1' onchange='appendToArrayInfo()'\";\n\tcontent += \" data-mini='true' style='width: 150px;'>\";\n\tcontent += \"<option value=''></option>\"+GlobalDevicePortType+\"</select>\";\n\tcontent += \"<br></td><td><br>Media type<br></td>\";\n\tcontent += \"<td><br><select id='mediatype' onchange='appendToArrayInfo()'><option value=''></option>\"+GlobalMedia+\"</select><br /></td>\";\n\tcontent += \"</tr><tr><td style='width: 20px;'></td>\";\n\tcontent += \"<td style='width: 150px;'>Port name: <br></td><td>\";\n\tcontent += \"<input id='portnamenumber' \";\n\tcontent += \"type='text' onblur='appendToArrayInfo()'/><br>\";\n\tcontent += \"</td></tr><tr><td style='width: 20px;'></td></tr></table></td></tr>\";\n\tcontent += \"<tr><td><table style='width: 100%;' cellspacing='10'><tr><td style='width: 100%;'> <fieldset style='border:2px solid #1c5a8d;border-radius:10px;overflow:auto;'>\";\n content += \"<legend style='margin-left:20px;'>Map Partner Port</legend>\";\n content += \"<table cellspacing='10' id='newDeviceinfo' style='width: 100%; overflow:auto;margin-left:15px;text-align:center;width:95%'><br><tr><td>\";\n\tcontent += \"Host Name: <select id='partnerhostname' onchange='appendToArrayInfo();checkHostIpaddress(this.value);'\";\n content += \"data-mini='true' style='width: 150px;'></select>\";\n\tcontent += \"Ip Address: <input id='partneripaddress' onchange='appendToArrayInfo()'\";\n content += \" style='width: 150px;'></input>\";\n\tcontent += \"</td><td>Slot Number: <select id='partnerslot' onchange='appendToArrayInfo(); checkSlotPortNumber();' data-mini='true' style='width: 150px;'></select>\";\n\tcontent += \"Port Name: <select id='partnerportinfo' onchange='appendToArrayInfo();' data-mini='true' style='width: 150px;'></select>\";\n\tcontent += \"</td></tr></table>\"\n\tcontent += \"</fieldset></td></tr></table></td></tr>\";\n\tcontent +=\t\"</table>\";\n\treturn content\n}", "function viewNewPortInfo(portIndex)\r\n{\r\n document.getElementById(\"portInfoCard\").style.display = \"block\";\r\n\tdocument.getElementById(\"portNameCard\").innerText = newPortList[portIndex].name;\r\n\tdocument.getElementById(\"country\").innerText = newPortList[portIndex].country;\r\n document.getElementById(\"type\").innerText = newPortList[portIndex].type;\r\n document.getElementById(\"size\").innerText = newPortList[portIndex].size;\r\n document.getElementById(\"locPrecision\").innerText = newPortList[portIndex].locprecision;\r\n document.getElementById(\"lat\").innerText = newPortList[portIndex].lat;\r\n document.getElementById(\"lng\").innerText = newPortList[portIndex].lng;\r\n\r\n}", "function fixURL(module, system) {\n var itemlink = document.getElementById(\"DisplayArea\").getElementsByTagName(\"a\");\n var pSystem = (system === null) ? getSystem() : system;\n var pAppl = (module === null) ? \"WRITER\" : module;\n var n = itemlink.length;\n for (var i = 0; i < n; i++) {\n if (itemlink[i].getAttribute(\"class\") != \"objectfiles\"){\n setURLParam(itemlink[i], pSystem, pAppl);\n };\n }\n}", "function moduleappend_response(req)\n{\n appending = false;\n if (!req.isSuccess()) {\n Zikula.showajaxerror(req.getMessage());\n return;\n }\n var data = req.getData();\n\n // copy new module li from module_1.\n var newmodule = $('module_'+firstmodule).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newmodule.id = 'module_' + data.id;\n $A(newmodule.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; node.value = ''; });\n $A(newmodule.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + data.id; });\n\n // append new module to the module list\n $('modulelist').appendChild(newmodule);\n\n // set initial values in input, hidden and select\n //$('modname_' + data.id).value = data.modname;\n //$('description_' + data.id).value = data.description;\n //$('members_' + data.id).href = data.membersurl;\n\n// Zikula.setselectoption('modulenavtype_' + data.id, data.navtype_disp);\n// Zikula.setselectoption('moduleenablelang_' + data.id, data.enablelang);\n\n // hide cancel icon for new modules\n// Element.addClassName('moduleeditcancel_' + data.id, 'z-hide');\n // update delete icon to show cancel icon\n// Element.update('moduleeditdelete_' + data.id, canceliconhtml);\n\n // update some innerHTML\n// Element.update('moduleid_' + data.id, data.id);\n// Element.update('modulemodname_' + data.id, data.modname);\n// Element.update('modulenavtype_' + data.id, data.navtype_disp);\n// Element.update('moduleenablelang_' + data.id, data.enablelang);\n //Element.update('members_' + data.id, data.membersurl);\n\n // add events\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n Event.observe('moduleeditsave_' + data.id, 'click', function(){modulemodify(data.id)}, false);\n Event.observe('moduleeditdelete_' + data.id, 'click', function(){moduledelete(data.id)}, false);\n Event.observe('moduleeditcancel_' + data.id, 'click', function(){modulemodifycancel(data.id)}, false);\n\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + data.id, 'z-hide');\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n\n // turn on edit mode\n allownameedit[data.id] = true;\n enableeditfields(data.id);\n\n // we are ready now, make it visible\n Element.removeClassName('module_' + data.id, 'z-hide');\n new Effect.Highlight('module_' + data.id, { startcolor: '#99ff66', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new module\n adding[data.id] = 1;\n}", "function foldingPortlets() {\n var portlets = getElementsByClassName(document.getElementById('column-one'), 'div', 'portlet');\n var portskip = ['p-personal', 'p-cactions', 'p-logo', 'ads-top-left', 'p-search', 'p-tbx', 'p-wikicities-nav', 'p-lang'];\n var num = 0;\n\n for (var i = 0; i < portlets.length; i++) {\n if (portskip.join(' ').indexOf(portlets[i].id) == -1) {\n var pd = portlets[i].getElementsByTagName('div')[0];\n var ph = portlets[i].getElementsByTagName('h5')[0];\n\n ph.className = 'portletCollapsible';\n pd.setAttribute('id', 'pbody-' + i);\n pd.style.display = 'none';\n\n var link = document.createElement('a');\n var head = getAllText(ph);\n\n while (ph.firstChild) {\n ph.removeChild(ph.firstChild);\n }\n\n link.appendChild(document.createTextNode(head));\n link.setAttribute('href', 'javascript:showPortlet(\\'' + i + '\\');');\n link.setAttribute('id', 'plink-'+i);\n link.className = 'portletClosed';\n ph.appendChild(link);\n\n if (num++ < 3) {\n showPortlet(i);\n }\n }\n }\n}", "renderPorts(node) {\n var nodeNoodle = node.noodle;\n for (var i in node.core.inPorts)\n nodeNoodle.port.render(node, node.core.inPorts[i]);\n\n for (var i in node.core.outPorts)\n nodeNoodle.port.render(node, node.core.outPorts[i]);\n\n nodeNoodle.node.forEachPort(node.core, nodeNoodle.port.renderVal);\n }", "function dynamicPortTab(num,id,name,limit){\n\tvar tab = \"\";\n\tvar msg = \"Port per device is over the limit.\\n\"\n\tmsg += \"Maximum ports perr device is 256.\"\n\tif (num>=limit) {\n\t\terror(msg,\"Notification\")\t\n\t\tvar val = 0;\t\n\t\treturn 0;\n\t}\n\tif(num==\"\"){return 0;}\n\tfor(var a=1; a<=num; a++){\n\t\ttab +=\"<li id='\"+id+a+\"' style='display:none'\";\n\t\ttab +=\" style='width: auto;'\";\n\t\ttab +=\" onclick=\\\"portinfoshow('\"+id+a+\"','\"+a+\"')\\\" \";\n\t\ttab +=\"class='ui-tabs-anchor ui-state-default ui-corner-top plimitshow'>\";\n\t\ttab +=\"<a href='#tabs-\"+a+\"' style='color: \";\n\t\ttab +=\"white;font-weight: bold;'>\"+name+a+\"</a></li>\";\t\n\t}\n\tvar ret = ({tabs:tab});//,contents:content});\n\treturn ret;\n\n}", "function generatePortList()\r\n{\r\n\r\n\tlet output = \"\";\r\n\r\n //create row for local port\r\n for (let j = 0; j < newPortList.length; j++)\r\n\t{\r\n output += \"<tr>\"\r\n output += \"<td onmousedown=\\\"viewNewPortInfo(\"+j+\")\\\" class=\\\"full-width mdl-data-table__cell--non-numeric\\\">\"\r\n output += \"<b>*NEW PORT*</b><br><br>\"\r\n output += \"Port Name: \" + newPortList[j].name ;\r\n output += \"<div class=\\\"subtitle\\\">\" + \"Country: \" + newPortList[j].country +\"<br><br><b>VIEW</b></div></td></tr>\";\r\n\t}\r\n\r\n //create row for port from API\r\n\tfor (let i = 0; i < portList.length; i++)\r\n\t{\r\n output += \"<tr>\"\r\n output += \"<td onmousedown=\\\"viewPortInfo(\"+i+\")\\\" class=\\\"full-width mdl-data-table__cell--non-numeric\\\">\"\r\n output += \"Port Name: \" + portList[i].name ;\r\n output += \"<div class=\\\"subtitle\\\">\" + \"Country: \" + portList[i].country +\"<br><br><b>VIEW</b></div></td></tr>\";\r\n\t}\r\n\r\n return output\r\n}", "function fetchPortForManageConnectivity(lineId){\n\twindow['variable' + dynamicManagePortArr[pageCanvas]] = [];\n\tvar line = lineId.split(\"||\");\n\tvar des = line[0];\n\tvar destSplit = des.split(\".\");\n\tvar sor = line[1];\n\tvar sorSplit = sor.split(\".\");\n\tvar destinationDevice = destSplit[0];\n\tvar sourceDevice = sorSplit[0];\n\tif(globalInfoType == \"JSON\"){\n\t\tvar json1 = getAllPortOfDevice(destinationDevice);\n\t\tvar json2 = getAllPortOfDevice(sourceDevice);\n var prtArr = json1.concat(json2);\n }else{\n var prtArr= portArr;\n }\n\tfor (var a=0; a<prtArr.length; a++){\n\t\tvar ob = prtArr[a].ObjectPath;\n\t\tvar portObj = ob.split(\".\");\n\t\tvar portDev = portObj[0];\n\t\tif (portDev == destinationDevice || portDev==sourceDevice){\n\t\t\tvar position = \"\";\n\t\t\tif (portDev == destinationDevice)\n\t\t\t\tposition = \"right\";\n\t\t\tif (portDev == sourceDevice)\n\t\t\t\tposition = \"left\";\n\n\t\t\twindow['variable' + dynamicManagePortArr[pageCanvas]].push({DevicePortObject : portDev, ObjectPath: prtArr[a].ObjectPath, PortName: prtArr[a].PortName, Description: prtArr[a].Description, PortType : prtArr[a].PortType, Position: position, Speed: prtArr[a].Speed, SwitchInfo: prtArr[a].SwitchInfo});\n\t\t}\t\n\t}\n\tif (window['variable' + dynamicManagePortArr[pageCanvas]].length != 0){\n\t\tappendListToTable(window['variable' + dynamicManagePortArr[pageCanvas]],lineId,destinationDevice,sourceDevice);\n\t}\n}", "function AndiModule(moduleVersionNumber,moduleLetter){\n\n\t//Display the module letter in the logo when the module is instantiated\n\tvar moduleName = $(\"#ANDI508-module-name\");\n\t$(moduleName).attr(\"data-ANDI508-module-version\",moduleLetter+\"ANDI: \"+moduleVersionNumber);\n\tif(moduleLetter == \"f\")\n\t\t$(moduleName).html(\"&nbsp;\"); //do not display default module letter\n\telse{\n\t\t$(moduleName).html(moduleLetter);\n\t\t$(\"head\").append(\"<link id='andiModuleCss' href='\"+host_url+moduleLetter+\"andi.css' type='text/css' rel='stylesheet' />\");\n\t}\n\n\t//The module should implement these priveleged methods\n\tthis.analyze = undefined;\n\tthis.results = undefined;\n\tthis.inspect = undefined;\n\t\t\n\t//Previous Element Button - automatically removes any overrides\n\t$(\"#ANDI508-button-prevElement\").off(\"click\").click(function(){\n\t\tvar index = parseInt($(\"#ANDI508-testPage .ANDI508-element-active\").attr(\"data-ANDI508-index\"));\n\t\tif(isNaN(index)) //no active element yet\n\t\t\tandiFocuser.focusByIndex(1); //first element\n\t\telse if(index == 1)\n\t\t\tandiFocuser.focusByIndex(testPageData.andiElementIndex); //loop back to last\n\t\telse{\n\t\t\t//Find the previous element with data-ANDI508-index\n\t\t\t//This will skip over elements that may have been removed from the DOM\n\t\t\tfor(x=index; x>0; x--){\n\t\t\t\tif($(\"#ANDI508-testPage [data-ANDI508-index='\"+(x - 1)+\"']\").length){\n\t\t\t\t\tandiFocuser.focusByIndex(x - 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t});\n\n\t//Next Element Button - automatically removes any overrides\n\t$(\"#ANDI508-button-nextElement\").off(\"click\").click(function(){\n\t\tvar index = parseInt($(\"#ANDI508-testPage .ANDI508-element-active\").attr(\"data-ANDI508-index\"));\n\t\tif(index == testPageData.andiElementIndex || isNaN(index))\n\t\t\tandiFocuser.focusByIndex(1); //loop back to first\n\t\telse{\n\t\t\t//Find the next element with data-ANDI508-index\n\t\t\t//This will skip over elements that may have been removed from the DOM\n\t\t\tfor(x=index; x<testPageData.andiElementIndex; x++){\n\t\t\t\tif($(\"#ANDI508-testPage [data-ANDI508-index='\"+(x + 1)+\"']\").length){\n\t\t\t\t\tandiFocuser.focusByIndex(x + 1);\n\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t});\n}", "function modulemodify_response(req)\n{\n if (!req.isSuccess()) {\n Zikula.showajaxerror(req.getMessage());\n showinfo();\n return;\n }\n\n var data = req.getData();\n\n // check for modules internal error\n if(data.error == 1) {\n showinfo();\n Element.addClassName($('moduleinfo_' + data.id), 'z-hide');\n Element.removeClassName($('modulecontent_' + data.id), 'z-hide');\n\n /*\n // add events\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n Event.observe('moduleeditsave_' + data.id, 'click', function(){modulemodify(data.id)}, false);\n Event.observe('moduleeditdelete_' + data.id, 'click', function(){moduledelete(data.id)}, false);\n Event.observe('moduleeditcancel_' + data.id, 'click', function(){modulemodifycancel(data.id)}, false);\n enableeditfields(data.id);\n */\n Zikula.showajaxerror(data.message);\n setmodifystatus(data.id, 0);\n modulemodifyinit(data.id);\n\n // refresh view/reload ???\n return;\n }\n\n $('enablelang_' + data.id).value = data.enablelang;\n\n Element.update('modulename_' + data.id, data.modname);\n Element.update('modulenavtype_' + data.id, data.navtype_disp);\n Element.update('moduleenablelang_' + data.id, data.enablelang_disp);\n Element.update('moduleexempt_' + data.id, data.exempt_disp);\n\n adding = adding.without(data.id);\n\n // show trascan icon for new moduless if necessary\n Element.removeClassName('moduleeditcancel_' + data.id, 'z-hide');\n // update delete icon to show trashcan icon\n Element.update('moduleeditdelete_' + data.id, deleteiconhtml);\n\n setmodifystatus(data.id, 0);\n showinfo(data.id);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the specified matrix is equal to this matrix.
equals(matrix) { //check if same size if (this.height() === matrix.height() && this.width() === matrix.width()) { //check each element let flag = true; for (let i = 0; i < this.height(); i++) for (let j = 0; j < this.height(); j++) { if (this.get(i, j) !== matrix.get(i, j)) { flag = false; break; } } return flag; } return false; }
[ "equals(grid) {\n if (this.height !== grid.height) { return false; }\n if (this.width !== grid.width) { return false; }\n\n let ans = true;\n for (let r = 0; r < this.height; r++) {\n for (let c = 0; c < this.width; c++) {\n if (this.get(r,c) !== grid.get(r,c)) { ans = false; }\n }\n }\n return ans;\n }", "function isEqual(board1, board2)\n{\n // iterate over each row index\n for (var i = 0; i < board1.length; i++)\n {\n // iterate over each column index\n for (var x = 0; x < board1[0].length; x++)\n {\n // check if corresponding cells are not equal\n if (board1[i][x] != board2[i][x])\n {\n // not equal\n return false;\n }\n }\n }\n // equal\n return true;\n}", "static equal(b1, b2) {\n\n var i,j;\n\n if (b1.size != b2.size) {\n console.log('b1 and b2 are of different sizes');\n return false;\n }\n\n for (i=0; i<b1.size; i++) {\n\n for (j=0; j<b1.size; j++) {\n\n if (b1.board[i][j] !== b2.board[i][j]) {\n return false;\n }\n }\n }\n\n console.log('b1 and b2 are equal');\n return true;\n }", "equals(viewport) {\n if (!(viewport instanceof Viewport)) {\n return false;\n }\n\n if (this === viewport) {\n return true;\n }\n\n return viewport.width === this.width && viewport.height === this.height && viewport.scale === this.scale && Object(_math_gl_core__WEBPACK_IMPORTED_MODULE_2__[\"equals\"])(viewport.projectionMatrix, this.projectionMatrix) && Object(_math_gl_core__WEBPACK_IMPORTED_MODULE_2__[\"equals\"])(viewport.viewMatrix, this.viewMatrix); // TODO - check distance scales?\n }", "equalTo(other) {\n other = new Complex(other);\n return this.re == other.re && this.im == other.im;\n }", "function allSame (arr) {\n\t if (!Array.isArray(arr)) {\n\t return false\n\t }\n\t if (!arr.length) {\n\t return true\n\t }\n\t var first = arr[0]\n\t return arr.every(function (item) {\n\t return item === first\n\t })\n\t}", "function compareBoard(old) {\n for (let i = 0; i < gameBoard.length; i++) {\n for (let k = 0; k < gameBoard.length; k++) {\n if (old[i][k] !== gameBoard[i][k]) {\n return true;\n }\n }\n }\n return false;\n}", "equals(path, another) {\n return path.length === another.length && path.every((n, i) => n === another[i]);\n }", "function checkNotInRow(mat,num,row){\r\nfor (let col = 0 ; col < 9 ;col++ ){\r\n if ( mat [row] [col] == num){\r\n return false;\r\n }\r\n }\r\nreturn true; \r\n}", "testMultiplyingMatricesIdentity() {\r\n console.info('test Matrix2.multiplyMatrices() by identity matrix')\r\n const firstMatrixElements = [\r\n 1, 2,\r\n 3, 4,\r\n ]\r\n const identityMatrixElements = [\r\n 1, 0,\r\n 0, 1,\r\n ]\r\n const expectedMatrixElements = [\r\n 1, 2,\r\n 3, 4,\r\n ]\r\n const matrix = new Matrix2(firstMatrixElements)\r\n matrix.multiplyMatrices(identityMatrixElements)\r\n const actualMatrixElements = matrix.elements\r\n this.assertIdentical(actualMatrixElements, expectedMatrixElements)\r\n }", "equalTo(otherTile) {\n\t\tif (otherTile == undefined) {\n\t\t\treturn false;\n\t\t}\n\t\treturn this.color == otherTile.color;\n\t}", "is_equal_to(block) {\n if (!this.header.is_equal_to(block.header)) {\n return false;\n }\n if (!this.merkle_tree.is_equal_to(block.merkle_tree)) {\n return false;\n\n }\n return true\n }", "function equalCells(cell1, cell2) {\n return cell1.row === cell2.row && cell1.column === cell2.column;\n}", "tilesAreEqual(tile1, tile2) {\n return tile1 && tile2 && tile1.x == tile2.x && tile1.y == tile2.y;\n }", "function eq(vm) {\n\tvar observerData = vm._mobxObserver;\n\n\tif (observerData.stale)\n\t\treturn false;\t// Re-render.\n\telse if (observerData.eq)\n\t\treturn observerData.eq.apply(this, arguments); // Let diff() choose.\n\telse\n\t\treturn true;\t// By default: no re-render.\n}", "function isCellsEqual(cell1, cell2) {\n\t\n\t\tif (!cell1 && !cell2) {\n\t\t\treturn true;\n\t\t}\n\t\n\t\tif (cell1 && cell2) {\n\t\t\treturn cell1.grid === cell2.grid &&\n\t\t\t\tcell1.row === cell2.row &&\n\t\t\t\tcell1.col === cell2.col;\n\t\t}\n\t\n\t\treturn false;\n\t}", "isIdentity() {\n if (this._isIdentityDirty) {\n this._isIdentityDirty = false;\n const m = this._m;\n this._isIdentity =\n m[0] === 1.0 &&\n m[1] === 0.0 &&\n m[2] === 0.0 &&\n m[3] === 0.0 &&\n m[4] === 0.0 &&\n m[5] === 1.0 &&\n m[6] === 0.0 &&\n m[7] === 0.0 &&\n m[8] === 0.0 &&\n m[9] === 0.0 &&\n m[10] === 1.0 &&\n m[11] === 0.0 &&\n m[12] === 0.0 &&\n m[13] === 0.0 &&\n m[14] === 0.0 &&\n m[15] === 1.0;\n }\n return this._isIdentity;\n }", "static areIdentical(){\n let temp\n\n for(let i = 0; i < arguments.length; i++){\n let argument = arguments[i]\n\n // handle NaN\n if(isNaN(argument.h)) argument.h = argument.h.toString()\n if(isNaN(argument.m)) argument.m = argument.m.toString()\n\n // handle string input\n if(typeof argument.h === \"string\") argument.h = parseInt(argument.h)\n if(typeof argument.m === \"string\") argument.m = parseInt(argument.m)\n\n // if temp is empty -> this is the first argument, store the first temp\n if(!temp){\n temp = argument\n continue\n }\n\n // if the temp and the current argument are not identical, return false\n if(argument.h !== temp.h || argument.m !== temp.m || argument.pm !== temp.pm) return false\n\n // store the current argument as the new temp\n temp = argument\n }\n\n return true\n }", "function differentSquares(matrix) {\n let matrices = [];\n \n for(let i = 0; i < matrix.length - 1; i++){\n let grid = '';\n for(let j = 0; j < matrix[0].length - 1; j++){\n grid = matrix[i][j].toString() + matrix[i][j+1] + matrix[i+1][j] + matrix[i+1][j+1];\n \n // push unique 2x2 grids by comparing the concatenation of the numbers as strings\n if(!matrices.includes(grid)) \n matrices.push(grid);\n }\n }\n return matrices.length;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Factory method returning all include reference resolvers, registered in the system.
function getIncludeReferenceResolvers() { return [new JSONResolver(), new XMLResolver()]; }
[ "resolve() {\n this.resolver.resolveAll(this.sources.definitions);\n }", "function generateResolversRecursively(path = '', module = {}) {\n /**\n * Create a resolver for the current level\n */\n resolvers.push(createResolver({ path, module }));\n\n /**\n * Recurse deeper if applicable\n */\n if (module.options && Array.isArray(module.options.modules)) {\n module.options.modules.forEach((module, i) => {\n if (module) {\n const nextPath = `${path}.options.modules[${i}]`;\n generateResolversRecursively(nextPath, module);\n }\n });\n }\n }", "function defineLazyLoadedRepos() {\r\n repoNames.forEach(function(name) {\r\n Object.defineProperty(service, name, {\r\n configurable: true, // will redefine this property once\r\n get: function() {\r\n // The 1st time the repo is request via this property,\r\n // we ask the repositories for it (which will inject it).\r\n var repo = getRepo(name);\r\n // Rewrite this property to always return this repo;\r\n // no longer redefinable\r\n Object.defineProperty(service, name, {\r\n value: repo,\r\n configurable: false,\r\n enumerable: true\r\n });\r\n return repo;\r\n }\r\n });\r\n });\r\n }", "onResolve(context, reflection) {\n if (reflection.kindOf(index_1.ReflectionKind.ClassOrInterface)) {\n this.postpone(reflection);\n walk(reflection.implementedTypes, (target) => {\n this.postpone(target);\n if (!target.implementedBy) {\n target.implementedBy = [];\n }\n target.implementedBy.push(new index_2.ReferenceType(reflection.name, reflection, context.project));\n });\n walk(reflection.extendedTypes, (target) => {\n this.postpone(target);\n if (!target.extendedBy) {\n target.extendedBy = [];\n }\n target.extendedBy.push(new index_2.ReferenceType(reflection.name, reflection, context.project));\n });\n }\n function walk(types, callback) {\n if (!types) {\n return;\n }\n types.forEach((type) => {\n if (!(type instanceof index_2.ReferenceType)) {\n return;\n }\n if (!type.reflection ||\n !(type.reflection instanceof index_1.DeclarationReflection)) {\n return;\n }\n callback(type.reflection);\n });\n }\n }", "function getResources() {\n\t\t\treturn $q.when(resources);\n\t\t}", "resolveDependencies(inputs) {\n const dependencies = super.resolveDependencies(inputs);\n // The suppression file neuters functions not working with differential\n // fuzzing. It can also be used to temporarily silence some functionality\n // leading to dupes of an active bug.\n dependencies.push(\n sourceHelpers.loadResource('differential_fuzz_suppressions.js'));\n // Extra printing and tracking functionality.\n dependencies.push(\n sourceHelpers.loadResource('differential_fuzz_library.js'));\n // Make Chakra tests print more.\n dependencies.push(\n sourceHelpers.loadResource('differential_fuzz_chakra.js'));\n\n if (hasMjsunit(dependencies)) {\n // Make V8 tests print more. We guard this as the functionality\n // relies on mjsunit.js.\n dependencies.push(sourceHelpers.loadResource('differential_fuzz_v8.js'));\n }\n\n if (hasJSTests(dependencies)) {\n dependencies.push(\n sourceHelpers.loadResource('differential_fuzz_jstest.js'));\n }\n\n return dependencies;\n }", "merge (){\n const validatePromise = this._validate(this.swaggerInput);\n const bundlePromise = this._bundle(this.swaggerInput);\n const promiseArray = [validatePromise, bundlePromise];\n const that = this;\n\n // Merging referenced and dereferenced swagger object to have ref links and the dereferenced object.\n return Promise.reduce(\n promiseArray,\n (aggregate, swagger) => {\n return merge(aggregate, swagger);\n },\n {}\n )\n .then((mergedSchema) => {\n that.swaggerObject = mergedSchema;\n return Promise.resolve(this);\n });\n }", "visitReferences_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getResources(includeTs) {\n const resources = this.data.manifest.control.resources;\n let pathsCollection = [];\n Object.keys(resources).forEach(resourceType => {\n let paths;\n if (resourceType !== constants.LIBRARY_ELEM_NAME) {\n paths = (resourceType === constants.CODE_ELEM_NAME && !includeTs) ? [] : resources[resourceType].map((resource) => resource.$.path);\n }\n else {\n paths = flatMap(resources[resourceType], (resource) => resource['packaged_library'] ? resource['packaged_library'].map((packagedLib) => packagedLib.$.path) : []);\n }\n pathsCollection.push(...paths);\n });\n return pathsCollection;\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 acquire (chain) {\n var resolver = pool.pop() || factory();\n\n // Reset the state of the resolver\n resolver.locks = 0;\n resolver.chain = chain;\n while (resolver.resolved.length > 0) {\n resolver.resolved.pop();\n }\n while (resolver.filters.length > 0) {\n resolver.filters.pop();\n }\n\n return resolver;\n}", "getResolve() {\n return {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n alias: this.config.alias !== undefined ? _objectSpread({}, this.config.alias) : {}\n };\n }", "defs() {\n if (!this.isRoot()) return this.root().defs();\n return adopt(this.node.querySelector('defs')) || this.put(new Defs());\n }", "collectIncludedFiles(dependencies) {\n dependencies.forEach(dependency => this.includedFiles.add(dependency.to));\n }", "function collectRefsRecursive(host, content, refs) {\n var childNodes = host.childNodes;\n for (var i = 0, n = content.length; i < n; ++i) {\n var elem = content[i];\n var type = elem.type;\n if (type === 1 /* Node */) {\n var node = childNodes[i];\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = node;\n collectRefsRecursive(node, elem.children, refs);\n }\n else if (type === 2 /* Component */) {\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = componentMap.get(childNodes[i]);\n }\n }\n }", "getLookupLists(listNames) {\n let lookupLists = get(this, 'lookupLists');\n let store = get(this, 'store');\n let listsToQuery = listNames.filter((listName) => {\n if (isEmpty(lookupLists[listName])) {\n return true;\n }\n });\n if (isEmpty(listsToQuery)) {\n return resolve(this._getLookupListsFromCache(listNames));\n } else {\n let queryHash = {};\n if (listsToQuery.includes('incidentCategories')) {\n queryHash.incidentCategories = store.findAll('inc-category');\n listsToQuery.removeObject('incidentCategories');\n }\n if (!isEmpty(listsToQuery)) {\n queryHash.lookup = store.query('lookup', {\n options: {\n keys: listsToQuery\n }\n });\n }\n return RSVP.hash(queryHash).then((hash) => {\n if (!isEmpty(hash.incidentCategories)) {\n lookupLists.incidentCategories = hash.incidentCategories.filterBy('archived', false);\n }\n if (!isEmpty(hash.lookup)) {\n listsToQuery.forEach((list) => {\n lookupLists[list] = hash.lookup.findBy('id', list);\n });\n }\n return this._getLookupListsFromCache(listNames);\n });\n }\n }", "function atomizeResolver(resolver, name, refObj, wire) {\n\t\twhen(atomize, function(atomize) {\n\t\t\tif(!name) return resolver.resolve(atomize);\n\n\t\t\tatomize.atomically(function() {\n\t\t\t\treturn name == ':root' ? atomize.root : atomize.root[name];\n\t\t\t}, resolver.resolve);\n\t\t});\n\t}", "function addSourceRefIdToExistingRefs(data) {\n\n return function () {\n\n var start = new Date().getTime();\n\n if (_.size(data.refNormIdToSourceRefIdMap)) {\n\n var normids = _.keys(data.refNormIdToSourceRefIdMap);\n\n return Promise.resolve()\n .then(function fetchSourceEntitiesWithRefsReferringRefNorms() {\n\n // SourceRefIds were added to a collection of refnorms (refNormIdToSourceRefIdMap). \n // Find the SourceEntities that contain references to any of these Refnorms\n\n // pluck: save bandwidth\n return tableSourceEntity.getAll.apply(tableSourceEntity, normids.concat({\n index: '_refNormIds'\n })).pluck(\"id\", \"_refNormIds\", \"_refToSourceRefIdMap\");\n\n })\n .then(function updateSourceEntitiesWithRefsReferringRefNorms(docs) {\n\n //Create an array of SourceEntity-docs (partial updates) that need to be updated. \n //Each partial doc contains 2 fields:\n //1. id\n //2. _refToSourceRefIdMap (partial)\n //\n //_refToSourceRefIdMap is a map containing Refnormid -> sourceRefId and thus\n //has the same format as refNormIdToSourceRefIdMap we're feeding from.\n //\n //Using a separate property `_refToSourceRefIdMap` to store these references\n //avoids potential racing writes on updating, say, _refs otherwise.\n //\n var sourceEntitiesToPartiallyUpdate = _.map(docs, function (d) {\n\n //Get normIds that might need updating.\n var intersectNormIds = _.intersection(d._refNormIds, normids);\n\n if (!intersectNormIds.length) {\n var err = new Error(\"refNormid instersection is length zero. Should not happen?\");\n err.halt = true;\n throw err;\n }\n\n //init _refToSourceRefIdMap\n d._refToSourceRefIdMap = d._refToSourceRefIdMap || {};\n\n var refToSourceRefIdMapDelta = _.reduce(intersectNormIds, function (agg, normId) {\n //only need to update if key/value not already present\n if (!d._refToSourceRefIdMap[normId]) {\n agg[normId] = data.refNormIdToSourceRefIdMap[normId];\n }\n return agg;\n }, {});\n\n if (!_.size(refToSourceRefIdMapDelta)) {\n return undefined; // there's nothing to update on this doc. \n }\n\n return {\n id: d.id,\n _refToSourceRefIdMap: refToSourceRefIdMapDelta\n };\n\n });\n\n //remove sourceEntities that don't need updating.\n sourceEntitiesToPartiallyUpdate = _.compact(sourceEntitiesToPartiallyUpdate);\n\n return tableSourceEntity.insert(sourceEntitiesToPartiallyUpdate, {\n conflict: \"update\",\n returnChanges: false\n });\n\n })\n .then(function () {\n data.time.addSourceRefIdToExistingRefs += new Date().getTime() - start;\n });\n }\n };\n }", "setupServices() {\n this.init = this.init.then(() => {\n // Instantiate independent core services.\n new NotificationEmailCoreSrv({mode: process.env.NODE_ENV});\n new NotificationSMSCoreSrv({mode: process.env.NODE_ENV});\n new SocketCoreSrv(this.server, {mode: process.env.NODE_ENV});\n\n return Promise.all([\n AuthSrv.connect(),\n UserSrv.connect(),\n FileSrv.connect(),\n ProductSrv.connect(),\n TagSrv.connect(),\n PriceSrv.connect(),\n OrderSrv.connect(),\n InvitationSrv.connect(),\n NotificationAlertSrv.connect(),\n CouponSrv.connect(),\n BrandSrv.connect(),\n ListSrv.connect(),\n ListSubscriptionSrv.connect(),\n CompanySrv.connect(),\n BillingSrv.connect(),\n AddressSrv.connect(),\n WalletSrv.connect(),\n TransferSrv.connect(),\n OrderItemSrv.connect()\n ]);\n });\n }", "getDependencyMap() {\n let obj = {}\n obj[this.path] = this.dependencies.map((dep) => {\n return dep.getDependencyMap()\n })\n return obj\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decreasing our character count
function decreaseCharCount(char, charCounts) { charCounts[char]--; }
[ "function erase() {\n\tif (eachLetter >= 0) {\n var str=openTo[adding].toString().substring(0, eachLetter);\n document.getElementById(\"demo\").innerHTML = str;\n eachLetter--;\n setTimeout(erase, speed-25);\n } else {\n adding++;\n if(adding>=openTo.length) \n adding=0;\n setTimeout(typingTexts, speed);\n }\n}", "function updateCharacterCounter(event) {\n const remainder = 140 - $(this).val().length;\n $(this).siblings('.counter').text(remainder);\n // can also be written like: $('.counter').text(remainder); but using $(this).siblings('.counter') is more efficient\n // conditional statement checks if counter number is\n // less than 140 and if so changes its color to red\n if (remainder < 0) {\n $(this).siblings('.counter').css(\"color\", \"#FF0000\");\n } else {\n // when backspacing, if counter goes back to MORE\n // than 140, change colour of counter back to black\n $(this).siblings('.counter').css(\"color\", \"#000000\");\n }\n}", "decrementCipherOffset(state) {\n\t\t\tstate.cipherOffset = state.cipherOffset - 1;\n\n\t\t\tstate.cipherText = encodeText(state.sourceText, state.cipherOffset);\n\t\t}", "function decrementCount(key) {\n if (counts[key] < 2) {\n delete counts[key];\n } else {\n counts[key] -= 1;\n }\n }", "function setMaxCharacterCount() {\n if ($(\".word\").width() <= 335) {\n return 8;\n } else if ($(\".word\").width() <= 425) {\n return 9;\n } else if ($(\".word\").width() <= 490) {\n return 10;\n } else if ($(\".word\").width() <= 510) {\n return 11;\n } else {\n return 12;\n }\n }", "function showCharacterCountWatcher(characters) {\n let excessCharacters = 280 - characters.length;\n\n // Unhide the chacterSurplus div and update the display of number of characters > 280 \n const characterSurplus = document.querySelector(\"#characterSurplus\");\n characterSurplus.className = \"flex justify-center items-center text-lg pr-2 text-red-400 border-r-2 border-gray-300\";\n characterSurplus.textContent = excessCharacters;\n}", "function deleteLetterIndex(e) {\n const word = document.querySelector('.word.active') || wordsContainer.firstChild\n if (word.lastChild.classList.contains('extra') && e.keyCode === 8) {\n letterIndex--\n letterIndex = letterIndex <= 0 ? 0 : letterIndex\n slashCoords()\n word.removeChild(word.lastChild)\n } else if (e.keyCode === 8 || e.keyCode === 46) {\n letterIndex--\n letterIndex = letterIndex <= 0 ? 0 : letterIndex\n const letter = word.children[letterIndex]\n letter.className = ''\n slashCoords()\n } \n}", "function livesdecrease(){\n if(replaceLetters()==false){\n maxtries=maxtries-1\n document.getElementById('lives').innerHTML= maxtries;\n }\n}", "function deleteCharAtPos() {\n if (column < promptText.length) {\n promptText =\n promptText.substring(0, column) +\n promptText.substring(column + 1);\n restoreText = promptText;\n return true;\n } else return false;\n }", "function retextCount() {\n this.Compiler = countWords;\n}", "function updateCount(){\r\n var commentText = document.getElementById(\"comment\").value;\r\n var charCount = countCharacters(commentText);\r\n var wordCountBox = document.getElementById(\"wordCount\");\r\n wordCountBox.value = charCount + \"/1000\";\r\n if (charCount > 1000) {\r\n wordCountBox.style.color = \"white\";\r\n wordCountBox.style.backgroundColor = \"red\";\r\n } else {\r\n wordCountBox.style.color = \"black\";\r\n wordCountBox.style.backgroundColor = \"white\";\r\n }\r\n}", "function resetCounter() {\n var m = x\n x = 0;\n return m + \" and the counter reset now\"\n}", "char_length() {\n return [...this.buf].length;\n }", "removeLetter(letter) {\n $('#letters').empty();\n for (let i = 0; i < alphabetArray.length; i++) {\n if (alphabetArray[i] === letter) {\n alphabetArray[i] = '_';\n }\n $('#letters').append(`<div class=\"letter\">${alphabetArray[i]}</div>`)\n }\n this.numOfGuesses--;\n $('.guesses').html(`Guesses left: ${this.numOfGuesses}`)\n }", "function clear() {\n if (count >= 1) {\n document.getElementById(\"numDisplay\").innerHTML = '';\n count = 0;\n }\n }", "function charCount(txt){\n return txt.length;\n}", "function ungetChar(state) {\n switch (state.ch) {\n case '\\t': advance(state, -4); break;\n case '\\n': state.line.pop(); break;\n default: advance(state, -1); break;\n }\n return state.ch = state.text.charAt((--state.at) - 1);\n }", "reset() {\n const _ = this;\n _._counter = _._startCount;\n }", "countDecrease(item) {\n if (item.count <= 1) {\n this.msg2;\n }\n else {\n item.count = item.count - 1;\n this.isErrorMsg = false;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit a parse tree produced by KotlinParsertopLevelObject.
exitTopLevelObject(ctx) { }
[ "visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitNormalClassDeclaration(ctx) {\n\t}", "exitBlockLevelExpression(ctx) {\n\t}", "decreaseTopLevel() {\n if (last_default()(this.indentTypes) === INDENT_TYPE_TOP_LEVEL) {\n this.indentTypes.pop();\n }\n }", "exitParenthesizedType(ctx) {\n\t}", "exitStatementWithoutTrailingSubstatement(ctx) {\n\t}", "exitOrdinaryCompilation(ctx) {\n\t}", "exitKotlinFile(ctx) {\n\t}", "exitControlStructureBody(ctx) {\n\t}", "exitJumpExpression(ctx) {\n\t}", "endGroup() {\n if (this.undefStack.length === 0) {\n throw new ParseError(\"Unbalanced namespace destruction: attempt \" + \"to pop global namespace; please report this as a bug\");\n }\n\n const undefs = this.undefStack.pop();\n\n for (const undef in undefs) {\n if (undefs.hasOwnProperty(undef)) {\n if (undefs[undef] === undefined) {\n delete this.current[undef];\n } else {\n this.current[undef] = undefs[undef];\n }\n }\n }\n }", "exitInheritanceModifier(ctx) {\n\t}", "exitPreprocessorParenthesis(ctx) {\n\t}", "exitMultiVariableDeclaration(ctx) {\n\t}", "exitClassLiteral(ctx) {\n\t}", "exitPackageOrTypeName(ctx) {\n\t}", "exitUnannReferenceType(ctx) {\n\t}", "exitMethodDeclarator(ctx) {\n\t}", "exitUnannPrimitiveType(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BasicTransition class changes slides without any animation. Do not remove this class, because carousels use it by default, if requested transition cannot be found.
function BasicTransition() {}
[ "function Transition() {}", "function transition(){\r\n document.querySelector('#cover').classList.add('disappear');\r\n document.querySelector('.result-wrapper').classList.add('result-appear');\r\n document.querySelector('#next').classList.add('next-appear');\r\n}", "function FadeInTransition() {}", "performSlide() {\n if (this.prevSlide) {\n this.prevSlide.removeClass('prev fade-out')\n }\n\n this.nextSlide.removeClass('next');\n this.prevSlide = this.nextSlide;\n this.prevSlide.addClass('prev');\n\n this.currentIndex++;\n if (this.currentIndex >= this.slides.length) {\n this.currentIndex = 0\n }\n\n this.setNextSlide();\n\n this.prevSlide.addClass('fade-out');\n }", "function SlideHorizontallyTransition() {}", "function handleResetTransition(){\n let swipeContainers = document.getElementsByClassName('react-swipeable-view-container');\n for(let i = 0; i < swipeContainers.length; i++) {\n swipeContainers[i].style.transition = null;\n }\n }", "function removeMobileAnimations(){\n var slideAnimations = document.querySelectorAll('.animated');\n if(slideAnimations || slideAnimations.length !=0) {\n for(var i=0; i<slideAnimations.length; i++) {\n slideAnimations[i].classList.remove('animated');\n }\n }\n}", "function TransitionSettings() {}", "function SlideVerticallyTransition() {}", "function switchSlides() {\n\n pit.cookies.set({\n name: 'cur_slide',\n value: 'presentation~' + window.location.pathname.split('/')[3] + curSlide,\n expires: 21600,\n path: '/'\n });\n\n for (var i = 0; i < slides.length; i++) {\n\n if (i < slidesOrder.indexOf(curSlide)) {\n\n slides[i].classList.remove('presentation__slide--active', 'presentation__slide--after');\n slides[i].classList.add('presentation__slide--before', 'presentation__slide--inactive');\n continue;\n\n }\n if (i > slidesOrder.indexOf(curSlide)) {\n\n slides[i].classList.remove('presentation__slide--active', 'presentation__slide--before');\n slides[i].classList.add('presentation__slide--after', 'presentation__slide--inactive');\n\n }\n\n }\n\n if (slidesOrder.indexOf(curSlide) !== -1) {\n\n slides[slidesOrder.indexOf(curSlide)].classList.remove('presentation__slide--after', 'presentation__slide--before', 'presentation__slide--inactive');\n slides[slidesOrder.indexOf(curSlide)].classList.add('presentation__slide--active');\n progressBar.style.width = parseInt(slidesOrder.indexOf(curSlide)/(slides.length-1) * 100) + '%';\n\n }\n\n if (slidesOrder.indexOf(curSlide) === 0) {\n\n prevSlideBtn.classList.add('hide');\n\n } else {\n\n prevSlideBtn.classList.remove('hide');\n\n }\n\n if (slidesOrder.indexOf(curSlide) === slides.length - 1) {\n\n nextSlideBtn.classList.add('hide');\n\n } else {\n\n nextSlideBtn.classList.remove('hide');\n\n }\n\n }", "slideNext() {\n super.slideNext();\n this.slides[this.lastSlide].style.opacity = 0;\n this.slides[this._index].style.opacity = 1;\n }", "function change_without_transition(element, procedure) {\n $(element).addClass('notransition');\n\n procedure(element);\n\n setTimeout(function () {\n $(element).removeClass('notransition');\n }, 100);\n}", "function doFlip(dir) {\n if (!container.querySelector(\".animate\")) {\n slider.classList.add(\"animate\");\n\n if (dir == -1) {\n slider.classList.add(\"animateL\");\n }\n\n frontSlide = slider.querySelector(\".front\");\n backSlide = findBack(dir);\n\n backSlide.classList.add(\"back\");\n\n\n timeout = setTimeout(function() {\n resetSlides();\n clearTimeout(timeout);\n }, options.timeout);\n }\n }", "defaultSlideShow() {\n this.preloadImg()\n utils.css(this.wrapper, \"left\", -this.defaultIndex * this.width);\n }", "supportsTransition(panorama) {\n return 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 WhitePane($) {\n const transitionsRequiringWhitePane = ['fade', 'zoom']; // Not: 'none', 'slide', 'convex', 'concave'\n\n // TODO: Inject white pane when required.\n let whitePane = document.getElementById('white-pane');\n\n if (transitionsRequiringWhitePane.indexOf($.getConfig().transition) === -1) {\n // Only these transition schemes require a white-pane. Ignore this\n // component in all other cases\n if (whitePane) whitePane.style.display = 'none';\n\n return;\n }\n\n if (!whitePane) {\n console.error('No white-pane detected. Skipping');\n\n return;\n }\n\n let displayWhitePane = whitePane.style.display !== 'none';\n\n $.addEventListener('slidechanged', onSlideChanged);\n $.addEventListener('transitionend', onSlideTransitionEnd);\n\n function hasWhitePane(slide) {\n try {\n return slide.firstElementChild.tagName.toUpperCase() === 'HEADER';\n } catch (e) {\n return false;\n }\n }\n\n function onSlideChanged(event) {\n if (displayWhitePane) {\n // If user moves through slides faster than intended, ensure white\n // pane is displayed.\n whitePane.style.display = '';\n }\n\n displayWhitePane = hasWhitePane(event.currentSlide);\n\n if (!displayWhitePane) {\n // Not displayed: remove the white pane to let reveal handle the\n // transition.\n whitePane.style.display = 'none';\n }\n }\n\n function onSlideTransitionEnd() {\n if (displayWhitePane) {\n // Transition done and the white pane should be displayed: show it.\n // This is done after transition to ensure fluid transitions.\n whitePane.style.display = '';\n }\n }\n }", "static _playTransitionAt(e, delay) {\n\t\t\n e._targetElem.setAttribute(\"style\", e._initialStyle);\n for(const x of Object.keys(e._initialStyleObject))\n e._targetElem.style[x] = getComputedStyle(e._targetElem).getPropertyValue(x);\n \n e._targetElem.setAttribute(\"style\", e._transformation);\n e._targetElem.style[\"transition-duration\"] = \"1s\";\n e._targetElem.style[\"transition-timing-function\"] = e._transitionEase;\n e._targetElem.style[\"transition-delay\"] = -delay + \"ms\";\n\n for(const x of Object.keys(e._transformationObject))\n e._targetElem.style[x] = getComputedStyle(e._targetElem).getPropertyValue(x);\n //e._eventState = __EVENT_STATES__.__RUNNING__;\n\n //e._targetElem.style.removeProperty(\"transition-duration\");\n //e._targetElem.style.removeProperty(\"transition-delay\");\n //e._targetElem.style.removeProperty(\"transition-timing-function\");\n \n }", "_updateUniformTransition() {\n // @ts-ignore (TS2339) internalState is alwasy defined when this method is called\n const {\n uniformTransitions\n } = this.internalState;\n\n if (uniformTransitions.active) {\n // clone props\n const propsInTransition = uniformTransitions.update();\n const props = Object.create(this.props);\n\n for (const key in propsInTransition) {\n Object.defineProperty(props, key, {\n value: propsInTransition[key]\n });\n }\n\n return props;\n }\n\n return this.props;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks whether this socket id is source
function isSource(_socketid, _sourceList){ return _sourceList.hasOwnProperty(_socketid); }
[ "isSource() {\n return this.mode == 'output' && this.high;\n }", "isSink() {\n\n return this.type == 'sink';\n }", "isSink() {\n return this.mode == 'output' && !this.high;\n }", "getSource(day) {\n return this.sources[day] ? this.sources[day] : false;\n }", "function isSourceSet() {\n if (allUrlParameters.hasOwnProperty('utm_source')){\n return allUrlParameters.utm_source;\n } else {\n return '(not set)';\n }\n}", "function Source(id) {\n this.id = id;\n this.timeId = 0;\n this.sinks = [];\n }", "function isIPConnected(socket) {\n // Check if this sockets ip address is already exists in the clientSockets array\n for (i = 0; i < clientSockets.length; i++) {\n // socket.handshake.address returns the IP address\n if (socket.handshake.address === clientSockets[i].handshake.address) {\n return true;\n }\n }\n return false;\n} // End isIPConnected()", "function checkSocketStatus() {\n\t\tif (ports.list().length) {\n\t\t\tglobalSettings.get(function(options) {\n\t\t\t\tsocket.setup(options).connect(handshakeInfo);\n\t\t\t});\n\t\t} else {\n\t\t\tsocket.disconnect();\n\t\t}\n\t}", "hasMultipleConnections() {\n let result = false;\n this.getConnections().forEach(connection => {\n this.getConnections().forEach(_connection => {\n if (_connection.id !== connection.id) {\n if (_connection.source.node === connection.source.node) {\n if (_connection.target.node === connection.target.node) {\n result = true;\n }\n }\n }\n })\n });\n return result;\n }", "getClient_sock_at(socket_id){\n \tif (this.nodes.has(socket_id))\n \t\treturn this.nodes.get(socket_id).socket;\n \tconsole.warn(\"Error:getClient_sock_at\");\n }", "function getUsernameFromSource(_sourceDetails){\n if(CONNECTION_CONST.username in _sourceDetails){\n return _sourceDetails[CONNECTION_CONST.username]\n }\n else{\n for(var key in _sourceDetails){\n if(key !== 'clienttype' && 'type' in _sourceDetails[key] && _sourceDetails[key]['type'] === 'channel')\n return _sourceDetails[key]['configuration'][CONNECTION_CONST.username];\n }\n }\n}", "isOverflight() {\n return this.origin === '' && this.destination === '';\n }", "function isActive() {\n return socket && socket.readyState == WebSocket.OPEN;\n }", "load(){\n console.debug(\"Loading\", this.id);\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if(typeof this.mediaSourceListeners[i].load === 'function')this.mediaSourceListeners[i].load(this);\n }\n if (this.element !== undefined) {\n return true;\n }\n return false;\n }", "function noSources()\n{\n alert(\"Citations.js: noSources error\");\n}\t\t// noSources", "function isDestination(x, y, dest) {\n if (x == dest.x && y == dest.y) {\n return true;\n }\n\n else {\n return false;\n }\n}", "function isMessageFromOpponent(data)\n{\n // Is it from our opponent and is it intended for us?\n return (data.payload.sender == g_remote_uuid && data.payload.target == g_local_uuid);\n}", "getTextureFromSource(source) {\n const src = typeof source === \"string\" ? source : source.src;\n // return the texture if the source is the same and if it's not the same texture\n return this.textures.find(element => element.source && element.source.src === src);\n }", "changeSrc(e, source) {\n e.preventDefault();\n const src = e.target.elements.source.value || source;\n if (src.includes('www.youtube.com')) {\n this.player.src({type: 'video/youtube', src: src});\n }\n else {\n this.player.src({src: src});\n }\n this.reset();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create root and layers
function create_root_and_layers(self) { var graph = self.config._mxgraph; var root = null; root = new mxCell(); root.setId("__mx_root__"); // Create the layer var __mx_cell__ = root.insert(new mxCell()); graph.getModel().beginUpdate(); try { graph.getModel().setRoot(root); } catch (e) { log_error(e); } finally { graph.getModel().endUpdate(); } }
[ "setupLayers() {\n this.d3.select(this.holderSelector).selectAll('*').remove();\n\n this.createSVGLayer();\n this.createPointsLayer();\n this.createTargetsLayer();\n }", "async function createNewLayer() {\n const layerObject = {\n featureSet: document.getElementById(\"layer-feature-select\").value,\n renderer: document.getElementById(\"layer-renderer-select\").value,\n editingEnabled: (document.getElementById(\"layer-edit-checkbox\").value == \"on\") ? true : false,\n };\n\n //Ask the user where to save, start them in the current project layers directory if possible.\n const newLayerHandle = await saveAsJSON(layerObject, projectLayersDirectoryHandle);\n\n const newLayer = await ProjectLayer.create(newLayerHandle);\n if (newLayer.featureLayer.sourceFS) {\n view.goTo(newLayer.featureLayer.sourceFS.features);\n }\n document.getElementById(\"create-layer-modal\").style.display = \"none\";\n }", "setup() {\n for (const layer in this.layerRegistry) {\n this.layers.set(`${layerRegistry[layer]}Layer`, this.game.add.group());\n this.game.world.bringToTop(this.layers.get(`${layerRegistry[layer]}Layer`));\n }\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 &copy; <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 &copy; <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 &copy; <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}", "initTree() {\n // var format=function(features){features.forEach(p=>{console.log(`{id:${new Number(p.properties.nid)}, x:${new Number(p.geometry.coordinates[1])}, y: ${new Number(p.geometry.coordinates[0])}},`)});}\n this._tree = new KDBush(this._points, p => Math.round(p.x), p => Math.round(p.y), 64, Int32Array);\n }", "function insertEarthLayer(name, id, depth, visibility, func, parent) {\n var div = document.getElementById('LayerDiv');\n var collapse = createExpandableFolder(id);\n // Create indentation elements based on depth.\n var ems = checkLayerDepth(depth);\n div.innerHTML += '<label title=\"' + name + '\" name=\"' +\n parent + '\">' + ems + makeEarthCheckbox(id, visibility, func) +\n name + collapse + '</label>';\n}", "create() {\n this.scene.bringToTop('CursorScene');\n console.log('Starting screen:', this.key);\n // this.layers.setLayersDepth();\n }", "addLayerSelection() {\n let mapButtonsContainer = this.ref.createMapButtonsContainer(this.map.height);\n let layerButtonContainer = this.ref.createDiv(\"layerButtonContainer\");\n let layerButtonList = this.ref.createLayerButtonList(\"layerButtonList\");\n\n for (let i = 0; i < this.ref.maxZ; i++) {\n let layerButton = this.ref.createLayerButton(\"layerButton-\" + String(i), \"layer-button\");\n layerButtonList.append(layerButton);\n }\n\n layerButtonContainer.append(layerButtonList);\n document.querySelector(\"body\").append(mapButtonsContainer);\n let layerSelector = this.ref.createDiv(\"mapLayerSelector\");\n\n for (let i = nrOfLayers - 1; i >= 0; i--) {\n let layerA = this.ref.createLayerA(\"#\", i + 1);\n layerA.addEventListener('click', (e) => {\n let selectedNr = Number(e.target.innerText) - 1;\n if (this.displayLayers.includes(selectedNr)) {\n let elIndex = this.displayLayers.indexOf(selectedNr);\n e.target.classList.remove('active');\n\n if (elIndex > -1)\n this.displayLayers.splice(elIndex, 1);\n } else {\n this.displayLayers.push(selectedNr);\n e.target.classList.add('active');\n\n }\n this.repaintMapCube(cubes, \"\", this.enhancedCubes, this.scaffoldingCubesCords, false)\n\n });\n layerSelector.append(layerA);\n }\n mapButtonsContainer.append(layerSelector);\n }", "function createLayers(dag) {\n const layers = [];\n const maxLayer = Math.max(\n 0,\n ...dag.descendants().map((node) => node.layer)\n );\n dag.descendants().forEach((node) => {\n const layer = layers[node.layer] || (layers[node.layer] = []);\n layer.push(node);\n node.children = node.children.map((child) => {\n if (child.layer > node.layer + 1) {\n // child is not in the next layer of node => insert nodes in the intermediate layers\n let last = child;\n for (let l = child.layer - 1; l > node.layer; l--) {\n const dummy = new Node(\n `${node.id}${debug ? \"->\" : \"\\0\"}${child.id}${\n debug ? \" (\" : \"\\0\"\n }${l}${debug ? \")\" : \"\"}`,\n undefined\n );\n dummy.heightRatio = 0;\n dummy.children = [last];\n (layers[l] || (layers[l] = [])).push(dummy);\n last = dummy;\n }\n return last;\n } else {\n return child;\n }\n });\n if (node.children.length === 0 && node.layer < maxLayer) {\n // insert a dummy node per layer\n let highestLayerNode = new Node(\n `${node.id}${debug ? \"->\" : \"\\0\"}${debug ? \" (\" : \"\\0\"}${maxLayer}${\n debug ? \")\" : \"\"\n }`,\n undefined\n );\n (layers[maxLayer] || (layers[maxLayer] = [])).push(highestLayerNode);\n let last = highestLayerNode;\n for (let l = maxLayer - 1; l > node.layer; l--) {\n const dummy = new Node(\n `${node.id}${debug ? \"->\" : \"\\0\"}${highestLayerNode.id}${\n debug ? \" (\" : \"\\0\"\n }${l}${debug ? \")\" : \"\"}`,\n undefined\n );\n dummy.heightRatio = 0;\n dummy.children = [last];\n (layers[l] || (layers[l] = [])).push(dummy);\n last = dummy;\n }\n node.children = [last];\n }\n });\n return layers;\n }", "function createLayer(layer){\n\t\t\t\tvar id = layer.getAttribute(\"label\");\n\t\t\t\tvar myLayer;\n\t\t\t\ttries[id]++;\n\t\t\t\t// Set layer properties on startup if specified on url\n\t\t\t\tif (queryObj.layer && queryObj.layer != \"\") {\n\t\t\t\t\tif (layer.getAttribute(\"url\").toLowerCase().indexOf(\"mapserver\") > -1) {\n\t\t\t\t\t\tif (layerObj[id]){\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": layerObj[id].opacity,\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": layerObj[id].visible,\n\t\t\t\t\t\t\t\t\t\"visibleLayers\": layerObj[id].visLayers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t// not found on url, not visible\n\t\t\t\t\t\t}else {\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\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\t// FeatureServer tlb 10/19/20\n\t\t\t\t\telse if (layer.getAttribute(\"url\").toLowerCase().indexOf(\"featureserver\") > -1){\n\t\t\t\t\t\tif (layerObj[id]) \n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\" : layerObj[id].visible,\n\t\t\t\t\t\t\t\t\t\"visibleLayers\" : layerObj[id].visLayers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Unknown operational layer type. It must be of type MapServer or FeatureServer. Or edit readConfig.js line 600 to add new type.\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t// Set layer properties from config.xml file\n\t\t\t\t} else {\n\t\t\t\t\t// MapServer\n\t\t\t\t\tif (layer.getAttribute(\"url\").toLowerCase().indexOf(\"mapserver\") > -1){\n\t\t\t\t\t\tif (layer.getAttribute(\"visible\") == \"false\")\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new ArcGISDynamicMapServiceLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": true\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t} \n\t\t\t\t\t// FeatureServer tlb 9/28/20\n\t\t\t\t\telse if (layer.getAttribute(\"url\").toLowerCase().indexOf(\"featureserver\") > -1){\n\t\t\t\t\t\tif (layer.getAttribute(\"visible\") == \"false\")\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": false\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmyLayer = new FeatureLayer(layer.getAttribute(\"url\"), {\n\t\t\t\t\t\t\t\t\t\"opacity\": Number(layer.getAttribute(\"alpha\")),\n\t\t\t\t\t\t\t\t\t\"id\": id,\n\t\t\t\t\t\t\t\t\t\"visible\": true,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Unknown operational layer type. It must be of type MapServer or FeatureServer. Or edit readConfig.js line 600 to add new type.\");\n\t\t\t\t\t\thideLoading();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// 3-21-22 check if loaded\n\t\t\t\tmyLayer.on(\"load\", layerLoadedHandler);\n\t\t\t\tmyLayer.on(\"error\", layerLoadFailedHandler);\n\t\t\t}", "function createMeshes() {\r\n mesh_lantern1 = createLantern ();\r\n scene.add(mesh_lantern1);\r\n\r\n mesh_lantern2 = mesh_lantern1.clone();\r\n mesh_lantern2.translateX(15.0);\r\n scene.add(mesh_lantern2);\r\n\r\n mesh_lantern3 = mesh_lantern1.clone();\r\n mesh_lantern3.translateZ(-20.0);\r\n scene.add(mesh_lantern3);\r\n}", "function earthLayerTree(layers, depthCounter) {\n // Keep track of how far away each layer is from the root.\n var depth = depthCounter || 0;\n depth += 1\n // Insert each layer into the UI.\n for (var i = 0; i < layers.getLength(); i++) {\n var layer = layers.item(i);\n var id = layer.getId();\n var name = layer.getName();\n var type = layer.getType();\n var url = layer.getUrl();\n var visible = layer.getVisibility();\n var layerStyle = layer.getComputedStyle().getListStyle();\n var expandable = layerStyle.getListItemType();\n var parent = layer.getParentNode().getId();\n // Type KmlLayerRoot must be handled differently than any other type.\n if (type == 'KmlLayerRoot') {\n insertEarthLayer(name, url, depth, visible, 'toggleRootLayer', parent);\n } else {\n insertEarthLayer(name, id, depth, visible, 'toggleEarthLayer', parent);\n }\n // If layer is a folder, find out more to determine if it\n // requires recursion to add child layers.\n if (type == 'KmlFolder') {\n var childNodes = layer.getFeatures().getChildNodes();\n var children = childNodes.getLength();\n if (children > 1 && expandable == 1) {\n earthLayerTree(childNodes, depth);\n }\n }\n }\n}", "function AddNewLayer(){\r\n /**\r\n * adding new layer to network.\r\n *\r\n */\r\n\tnewlayer = new Layer();\r\n\tcounter++;\r\n\tlayerslist.push(newlayer);\r\n\tcreateLayer(counter);\r\n}", "function createShapeLayers( style )\r\n{\r\n\tvar viewLayers = new Array();\r\n\t\r\n\tvar layerSource;\r\n\tvar mapLayers = imageMap.layers;\t\r\n\tvar vector;\r\n\tvar mapLayerId;\r\n\t\r\n\tfor( var i = 0; i < mapLayers.length; i++ )\r\n\t{\r\n\t\tlayerSource = new ol.source.Vector({wrapX: false});\r\n\t\tmapLayerId = mapLayers[i].id;\r\n\t\t\r\n\t\tvector = new ol.layer.Vector({\r\n\t\t\tsource: layerSource,\r\n\t\t\tstyle: function(feature) {\r\n\t\t\t\tstyle.getText().setText(feature.get('name'));\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\t\t});\r\n\t\tvector.id = mapLayerId;\r\n\t\tviewLayers.push( vector );\r\n\t}\r\n\treturn viewLayers;\r\n}", "createScene() {\n\n this.heightMap = new NoiseMap();\n this.heightMaps = this.heightMap.maps;\n\n this.moistureMap = new NoiseMap();\n this.moistureMaps = this.moistureMap.maps;\n\n this.textureMap = new TextureMap();\n this.textureMaps = this.textureMap.maps;\n\n this.normalMap = new NormalMap();\n this.normalMaps = this.normalMap.maps;\n\n this.roughnessMap = new RoughnessMap();\n this.roughnessMaps = this.roughnessMap.maps;\n\n for (let i=0; i<6; i++) { //Create 6 materials, each with white color\n let material = new THREE.MeshStandardMaterial({\n color: new THREE.Color(0xFFFFFF)\n });\n this.materials[i] = material;\n }\n\n let geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64); //Creating a box\n let radius = this.size;\n for (var i in geo.vertices) {\n \t\tvar vertex = geo.vertices[i];\n \t\tvertex.normalize().multiplyScalar(radius);\n \t}\n this.computeGeometry(geo); //Squeezing a box into a sphere\n\n this.ground = new THREE.Mesh(geo, this.materials); //Create ground mesh with squeezed box sphere and 6 materials\n this.view.add(this.ground);\n }", "function createTree(x) {\n\t// Create the root\n\tvar a = createVector(width / 2, height);\n\tvar b = createVector(width / 2, height - 100);\n\ttree = new Tree(a, b);\n\n\t// Create the branches\n\tcreateXGenerations(x);\n}", "function addBaseLayers(specs)\n{\n\tvar controls = {};\n\tfor(var i in specs)\n\t\tcontrols[capitalize(specs[i])] =\n\t\t\tmakeLayerMapBox(specs[i], \"mapbox.\" + specs[i]);\n\tcontrols[capitalize(specs[0])].addTo(map);\n\tL.control.scale({maxWidth: 150, metric: true, imperial: false})\n\t\t\t\t\t\t\t\t.setPosition(\"topleft\").addTo(map);\n\tL.control.layers(controls, {}).setPosition(\"topleft\").addTo(map);\n}", "createObjects() {\n //this.createCube();\n //this.createSphere();\n //this.createFloor();\n this.createLandscape();\n this.createWater();\n }", "init() {\n this._createShadowRoot()\n this._attachStyles()\n this._createElements()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the RGBA colors for a given frame Returns an array where: index 0 is the paper color index 1 is the layer A color 1 index 2 is the layer A color 2 index 3 is the layer B color 1 index 4 is the layer B color 2 index 5 is the layer C color 1 index 6 is the layer C color 2
getFramePalette(frameIndex) { assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index'); const indices = this.getFramePaletteIndices(frameIndex); return indices.map(colorIndex => this.globalPalette[colorIndex]); }
[ "function getColors(){\n var rgb = mixerBottle.attr('style').replace('background-color: rgb(', '').replace(')', '').split(',');\n return rgb.map(x => parseInt(x));\n }", "function getThemeColors(r, g, b) {\n var shades = [];\t\t\t\t\t\t\t\t\t\t\t\t\t // reset the shades array\n var rb = r/16, gb = g/16, bb = b/16;\t\t\t\t\t\t\t\t // step by 16 for each of the 3 componets, before \n var ra = (255-r)/16;\t\t\t\t\t\t\t\t\t\t\t\t // step by 16 for each of the 3 componets, after\n var ga = (255-g)/16;\n var ba = (255-b)/16;\n \n var fr = 0, fg = 0; fb = 0;\t\t\t\t\t\t\t\t\t\t\t // color shades begin at zero\n \n var ro, go, bo;\t\t\t\t\t\t\t\t\t\t\t\t\t\t // these will hold the 2digit hex values of each component\n\n for(var i=0;i<32; i++) {\n // want an integer, not a float\n ro = parseInt(fr);\n go = parseInt(fg);\n bo = parseInt(fb);\n // not too big ...\n if (ro > 255) ro = 255;\n if (bo > 255) go = 255;\n if (bo > 255) bo = 255;\t\t\t\t\n // convert to a base 16 hex with 2 digits, lead with zero if needed\n ro = ro.toString(16); if (ro.length == 1) ro = \"0\" + ro;\t\t\t\t\n go = go.toString(16); if (go.length == 1) go = \"0\" + go;\t\t\t\t\n bo = bo.toString(16); if (bo.length == 1) bo = \"0\" + bo;\t\t\t\t\n // assign to the shades\n shades[i] = '#' + ro + go + bo;\n \n // change steping after the middle value\n \n if (i == 15) {\n rb = ra;\n gb = ga;\n bb = ba;\t\n }\n \n // preform the step\n \n fr+=rb;\n fg+=gb;\n fb+=bb;\t\n }\n \n return shades;\n \n}", "_colors(points) {\n engine.trace(`getting colors from '${ this._name }' at ${ points.length } point${ points.length === 1 ? '' : 's' }...`);\n\n let shot = sharp(this._file);\n let meta = null;\n\n return shot.metadata()\n\n .then(results => {\n meta = results;\n return shot.raw().toBuffer();\n })\n\n .then(data => {\n let colors = [];\n let matched = points.length > 0;\n\n for (let i = 0; i < points.length; i++) {\n let point = points[i];\n let delta = meta.channels * (meta.width * point.y + point.x);\n let slice = data.slice(delta, delta + meta.channels);\n let found = { x: point.x, y: point.y, c: { r: slice[0], g: slice[1], b: slice[2] } };\n\n matched &= _.isEqual(point, found);\n colors.push(found);\n }\n\n return { colors: colors, matched: matched ? true : false };\n })\n\n .catch(err => engine.error('failure getting colors'))\n .finally(() => engine.trace('got colors'));\n }", "getFrameLayerDepths(frameIndex) {\r\n return [0, 0];\r\n }", "function parseRGB(digits) {\n\n var current_triplet = \"\";\n var start_position = 0;\n\n var red = 0;\n var green = 0;\n var blue = 0;\n\n var triplet = [];\n var triplets = [];\n\n for(var count = 0; count < (dimension * dimension); count ++) {\n\n start_position = count * 9;\n current_triplet = digits.substring(start_position, start_position + 9);\n\n red = parseInt(current_triplet.substring(0, 3)) % 255;\n green = parseInt(current_triplet.substring(3, 6)) % 255;\n blue = parseInt(current_triplet.substring(6, 9)) % 255;\n\n triplet = [red, green, blue];\n triplets[ count ] = triplet;\n }\n\n return triplets;\n }", "getFrameLayerOrder(frameIndex) {\r\n return [1, 0];\r\n }", "function GRAY_TO_RGBA() {\n var s = this.s();\n var a = this.a();\n\n return kolor.rgba(s, s, s, a);\n }", "getSurroundingColors(coord) {\n var colors = [];\n for (var x = coord.x - 1; x <= coord.x + 1; x++) {\n for (var y = coord.y - 1; y <= coord.y + 1; y++) {\n var color = this.getColor(new Coord(x, y));\n if (color !== null) {\n colors.push(color);\n }\n }\n }\n return colors;\n }", "function getColor(i, j) {\n let pix = img.get(i,j).toString();\n pix = pix.substring(0, pix.length - 4);\n pix = \"rgb(\" + pix + \")\";\n return pix;\n}", "function redEffect(pixels) {\n for (let i = 0; i < pixels.data.length; i += 4) {\n pixels.data[i] = pixels.data[i] + 100; //shift more red.\n pixels.data[i + 1] = pixels.data[i + 1] - 50; // less green\n pixels.data[i + 2] = pixels.data[i + 2] * 0.5; // less blue \n }\n return pixels;\n}", "getFrameLayerDepths(frameIndex) {\r\n assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index');\r\n this.seek(this.frameMetaOffsets[frameIndex] + 0x14);\r\n return [\r\n this.readUint8(),\r\n this.readUint8(),\r\n this.readUint8()\r\n ];\r\n }", "function getColor(grid, x, y) {\n var idx = round((y * grid.width + x) * 4);\n var c = [grid.pixels[idx], grid.pixels[idx+1], grid.pixels[idx+2]];\n return c;\n}", "function GetBgColor()\n{\n\t// if (3.0 > h5Ver && !MainPhotos[startIdxY][startIdxX].complete) return;\n\t// if (3.0 <= h5Ver && !MainPhotosTiny[startIdxY][startIdxX].complete) return;\n\t// if (isBgColorSet) return;\n\t// var tempCanvas = document.createElement('canvas'); \n\t// tempCanvas.width = 1; \n\t// tempCanvas.height = 1; \n\t// var tempContext = tempCanvas.getContext(\"2d\"); \n\t// if (3.0 > h5Ver) tempContext.drawImage(MainPhotos[startIdxY][startIdxX], 10, 10, 1, 1, 0, 0, 1, 1);\n\t// else tempContext.drawImage(MainPhotosTiny[startIdxY][startIdxX], 10, 10, 1, 1, 0, 0, 1, 1);\n\t// var imgData = tempContext.getImageData(0, 0, 1, 1);\n\t// bgRed = imgData.data[0];\n\t// bgGreen = imgData.data[1];\n\t// bgBlue = imgData.data[2];\n\t// isBgColorSet = true;\n\t// delete tempCanvas;\n\t// Log(\"BackColor: \" + bgRed + \", \" + bgGreen + \", \" + bgBlue);\n}", "function ComplementaryRGBColor(rgb_array){\n // white minus this color = Complementary / Opposite \n var color_r = 255 - rgb_array[0];\n var color_g = 255 - rgb_array[1];\n var color_b = 255 - rgb_array[2];\n\n return [color_r, color_g, color_b];\n}", "getFramePaletteUint32(frameIndex, paletteBuffer = new Uint32Array(16)) {\r\n assertRange(frameIndex, 0, this.frameCount - 1, 'Frame index');\r\n const colors = this.getFramePalette(frameIndex);\r\n paletteBuffer.fill(0);\r\n colors.forEach(([r, g, b, a], i) => paletteBuffer[i] = (a << 24) | (b << 16) | (g << 8) | r);\r\n return paletteBuffer;\r\n }", "function averageColour (pixels) {\n var red = 0\n var green = 0\n var blue = 0\n\n // Each pixel is actually 4 cells in the array\n for (var i = 0; i < pixels.length; i += 4) {\n red += pixels[i]\n green += pixels[i + 1]\n blue += pixels[i + 2]\n }\n\n return [\n Math.round(red / (i / 4))\n , Math.round(green / (i / 4))\n , Math.round(blue / (i / 4))\n ]\n}", "function rgba(r, g, b, a) {\n\treturn vec4.fromValues(r * a, g * a, b * a, a);\n}", "function flag_color(flag_index, i){\n return colors[flag_index][i % colors[flag_index].length]\n}", "function parseSelectionColors() {\n\t\t// $log.log(preDebugMsg + \"parseSelectionColors\");\n\t\tvar colors = $scope.gimme(\"GroupColors\");\n\t\tif(typeof colors === 'string') {\n\t\t\tcolors = JSON.parse(colors);\n\t\t}\n\n\t\tselectionColors = {};\n\n\t\tif(colors.hasOwnProperty(\"skin\") && colors.skin.hasOwnProperty(\"text\")) {\n\t\t\ttextColor = colors.skin.text;\n\t\t}\n\t\telse {\n\t\t\ttextColor = \"#000000\";\n\t\t}\n\n\t\tif(colors.hasOwnProperty('selection')) {\n\t\t\tif(colors['selection'].hasOwnProperty('border')) {\n\t\t\t\tselectionColors.border = colors['selection']['border'];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tselectionColors.border = '#FFA500'; // orange\n\t\t\t}\n\n\t\t\tif(colors['selection'].hasOwnProperty('color')) {\n\t\t\t\tselectionColors.color = hexColorToRGBA(colors['selection']['color'], selectionTransparency);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tselectionColors.color = hexColorToRGBA('#FFA500', selectionTransparency); // orange\n\t\t\t}\n\n\t\t\tif(colors['selection'].hasOwnProperty('gradient')) {\n\t\t\t\tif(selectionCanvas === null || selectionCtx === null) {\n\t\t\t\t\tvar selectionCanvasElement = $scope.theView.parent().find('#theSelectionCanvas');\n\t\t\t\t\tif(selectionCanvasElement.length > 0) {\n\t\t\t\t\t\tselectionCanvas = selectionCanvasElement[0];\n\t\t\t\t\t\tselectionCtx = selectionCanvas.getContext(\"2d\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t//$log.log(preDebugMsg + \"no selectionCanvas to resize!\");\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tselectionColors.grad = selectionCtx.createLinearGradient(0, 0, selectionCanvas.width, selectionCanvas.height);\n\t\t\t\tvar atLeastOneAdded = false;\n\t\t\t\tfor(var p = 0; p < colors['selection']['gradient'].length; p++) {\n\t\t\t\t\tif(colors['selection']['gradient'][p].hasOwnProperty('pos') && colors['selection']['gradient'][p].hasOwnProperty('color')) {\n\t\t\t\t\t\tselectionColors.grad.addColorStop(colors['selection']['gradient'][p]['pos'], hexColorToRGBA(colors['selection']['gradient'][p]['color'], selectionTransparency));\n\t\t\t\t\t\tatLeastOneAdded = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!atLeastOneAdded) {\n\t\t\t\t\tselectionColors.grad = selectionColors.color;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tselectionColors.grad = selectionColors.color;\n\t\t\t}\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Add verification List songs by user, if tags present, use that to filter tags can be a list
static queryByUser(req, res) { const { userId } = req.params if (req.query.tags) { var tags = JSON.parse(req.query.tags) } else { var tags = null } // If tag not given, return all the songs var filterBy = {}; if (tags) { filterBy = { name: tags, userId: userId } } else { filterBy = { userId: userId } } return Song //Find all song ids by the user and the tag .findAll({ attributes: ['id'], include: [{ model: Tag, where: filterBy, attributes: [] }], raw: true // Convert the song ids to a list of ids }).then(songs => { return songs.map(song => song.id) }) .then(ids => { // Find all songs with the ids, this is done to retain all the other // tags that the song might have // If no ids if (ids == []) { res.status(200).send({ message: `User does not have any songs with tag ${tags}` }) } return Song.findAll({ // Find all songs with those IDs where: { id: { [Sequelize.Op.or]: [ids] } }, include: [{ model: Tag, // Only get the name of the tag attributes: ['name'], // To ignore the join table through: { attributes: [] } }] }) }) .then(songs => { if (songs.length != 0) { res.status(200).send(songs) } else { // If the list of songs is empty if (tags) { var message = `User does not have any songs with tag ${tags}` } else { var message = `User does not have any songs` } res.status(200).send({ message: message }) } }); }
[ "function getSongs(Query) {\n var spotify = new Spotify(LiriTwitterBOT.spotify);\n if (!Query) {\n Query = \"what's+my+age+again\";\n };\n spotify.search({ type: 'track', query: Query }, function(err, data) {\n if ( err ) {\n console.log('Error occurred: ' + err);\n return;\n }\n console.log(data);\n // Do something with 'data' \n });\n\n // var queryURL = 'https://api.spotfiy.com/v1/search?q=' + query + '&limit=5&type=track';\n // request(queryURL, function(err, response, body) {\n // if (err) {\n // console.log(err);\n // };\n // body = JSON.parse(body);\n // console.log(body);\n // for (var i = 0; i < body.tracks.items.length; i++) {\n // logObject = input + \", \" + query + \", \" + body.tracks.items[i].artists[0].name + \", \" + body.tracks.items[i].name\n // body.tracks.items[i].name + \", \" + body.tracks.items[i].preview_url + \", \" + body.tracks.items[i].album.name + \"\\n\";\n // }; //end of loop\n // writeLog(logObject);\n // });\n}", "async function searchSong() {\n let response = await fetch('https://yt-music-api.herokuapp.com/api/yt/songs/' + input)\n let result = await response.json()\n setSongs(result.content)\n context.inputSongs = result.content\n }", "function findtags(musicfile){\n const tracks = document.querySelectorAll('.track')\n const jsmediatags = window.jsmediatags\n\n jsmediatags.read(musicfile, {\n onSuccess: function(tags){\n tracks.forEach(track => {\n let picture = tags.tags.picture\n if(picture){\n let base64String = ''\n for(let i = 0; i < picture.data.length; i++){\n base64String += String.fromCharCode(picture.data[i])\n }\n const imgSrc = 'data:'+ picture.format + ';base64,' + window.btoa(base64String);\n track.dataset.picture = imgSrc\n }\n \n track.dataset.title = tags.tags.title\n track.dataset.artist = tags.tags.artist\n track.dataset.album = tags.tags.album\n \n })\n \n \n },\n onError: function(error){\n console.log(error.type,error.info)\n \n }\n })\n}", "function songSearch() {\n var spotify = new Spotify({ id: keys.apiKeys.id, secret: keys.apiKeys.secret });\n\n if (liriArgs) {\n spotify\n .search({ type: \"track\", query: liriArgs })\n .then(response => {\n var reply = response.tracks.items;\n reply.forEach(element => {\n console.log(\"=======spotify data=======\");\n console.log(\"Artist:\", element.album.artists[0].name);\n console.log(\"Song Title:\", element.name);\n console.log(\"Preview:\", element.preview_url);\n console.log(\"Album:\", element.album.name);\n console.log(\"=======spotify end=======\");\n });\n })\n .catch(err => {\n console.log(err);\n });\n } else {\n spotify\n .search({ type: \"track\", query: \"The Sign\", limit: 1 })\n .then(response => {\n var search = response.tracks.items[0];\n console.log(\"=======spotify data=======\");\n console.log(\"Artist:\", search.album.artists[0].name);\n console.log(\"Song Title:\", search.name);\n console.log(\"Preview:\", search.preview_url);\n console.log(\"Album:\", search.album.name);\n console.log(\"=======spotify end=======\");\n })\n .catch(err => {\n console.log(err);\n });\n }\n}", "static async getAllSongs(username){\n const validUser = await db.query(`\n SELECT username \n FROM users \n WHERE username = $1`, [username]);\n\n const user = validUser.rows[0];\n\n if (!user) throw new NotFoundError(`No user: ${username}`);\n\n const songRes = await db.query(\n `SELECT title FROM distrokid WHERE username = $1\n UNION\n SELECT title FROM bandcamp_all_time WHERE username = $1\n UNION\n SELECT title FROM bandcamp_running WHERE username = $1\n UNION\n SELECT title FROM spotify_all_time WHERE username = $1\n UNION\n SELECT title FROM spotify_running WHERE username = $1`, [username]\n );\n\n if(!songRes.rows.length) return [];\n\n return Object.values(songRes.rows).map(d => d);\n }", "static getSelectedSongs() {\n return SongManager.songList.filter(s => s.element.hasAttribute(\"selectedsong\"));\n }", "function getSongs() {\n fetch(songsURL)\n .then((response) => response.json())\n .then((songs) => songs.forEach((song) => renderSong(song)));\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 }", "function listSongDetails(songs) {\n songs.forEach(song => console.log(`${song.name}, by ${song.artist} (${song.duration})`));\n}", "function getPlaylistSongs(playlist_id){\n let currentPlaylist = getPlaylistById(playlist_id);\n let url = currentPlaylist.link + \"/tracks\";\n\n ajaxCall(url, null, function(response){populatePlaylist(response, currentPlaylist);});\n}", "function populateSongs (songs, list) {\n\n\t\tfor (var song of songs) {\n\n\t\t\tvar songTemplate = importTemplate('album-song-template');\n\n\t\t\tsongTemplate.querySelector('.song-name').textContent = song.name;\n\t\t\tsongTemplate.querySelector('.album-song').value = song.number;\n\n\t\t\tvar addButton = songTemplate.querySelector('.add-song');\n\t\t\taddButton.addEventListener('click', emitEvent('add-song', song));\n\n\t\t\tlist.appendChild(songTemplate);\n\n\t\t}\n\n\t}", "function addTrack() {\n SC.get('/tracks/' + track).then(function(player) {\n\n trackList.push({\n id: player.id,\n trackName: player.title,\n url: player.stream_url,\n artist: player.user.username\n });\n\n if (trackList.length === 1) {\n $('.picked-songs').empty();\n }\n $('.picked-songs').append('<li class=\"column column-block\"><button class=\"button small picked-song\" data-value=\"' + player.id + '\">' + player.title + '</button></li>');\n })\n $('#songName').attr('placeholder', 'Search for another song or artist!')\n }", "function spotifyCommand(song) {\n if (!song) song = \"The Sign Ace of Base\";\n\n spotify.search({ type: 'track', query: song, limit: 1 }, function(err, data) {\n if (err) {\n return console.log('Error occurred: ' + err);\n }\n\n let trackList = data.tracks.items\n if (trackList.length==0) {\n console.log(`NO MATCH FOUND FOR: ${song}`)\n }\n for (let i=0; i<trackList.length; i++){\n let track = trackList[i]\n\n console.log(\"ARTIST: \"+track.artists[0].name)\n console.log(\"SONG TITLE: \"+track.name)\n \n let preview\n if (track.preview_url) preview = track.preview_url\n else preview = \"unavailable\"\n console.log(\"PREVIEW: \"+preview)\n\n console.log(\"ALBUM NAME: \"+track.album.name)\n console.log()\n }\n });\n\n}", "function loadTags() {\n const tags = JSON.parse(sessionStorage.getItem('tags'))\n tags && tags.headerTags.forEach(tag => {\n const li = document.createElement('li')\n li.classList.add('tags__tag')\n li.innerHTML = `${tag}`\n headerFields.appendChild(li)\n })\n tags && tags.heroTags.forEach(tag => {\n const li = document.createElement('li')\n li.classList.add('tags__tag')\n li.innerHTML = `${tag}`\n heroFields.appendChild(li)\n })\n}", "function searchSong(song) {\n\n // Lookup song using Spotify api\n const spotify = new Spotify(keys.spotify);\n\n if (song === '') {\n // Default if nothing specified\n song = 'The Sign by Ace of Base'\n } else {\n console.log(\"Searching for your song...\")\n }\n spotify.search({\n type: 'track',\n query: song\n }, function (err, data) {\n\n if (err) {\n console.log(\"Something went wrong!\");\n } else {\n console.log(\"|=======================================================\");\n console.log(\"| Artist: \", data.tracks.items[0].artists[0].name);\n console.log(\"|=======================================================\");\n console.log(\"| Track name: \", data.tracks.items[0].name);\n console.log(\"|=======================================================\");\n console.log(\"| Preview link: \", data.tracks.items[0].external_urls.spotify);\n console.log(\"|=======================================================\");\n console.log(\"| Album: \", data.tracks.items[0].album.name);\n console.log(\"|=======================================================\");\n }\n });\n}", "getAlbumSongs (idAlbum, options) {\n if (!options){ // Default Order by track\n options = { order: 'track'}\n // options.debug = true\n }\n return this.Restangular.one('albums', idAlbum).all('songs')\n \t.getList(options)\n \t.then(\tresponse => response )\n }", "function getSongsByArtist(songs, artist) {\n return songs.filter(song => song.artist === artist);\n}", "loadAlbumTracks() {\n this._ApiFactory.getAlbumsTracks(this.albumId).query({}, (response) => {\n\n const tracks = [];\n response.items.forEach((i) => {\n const track = {\n name: i.name,\n images: i.images,\n duration: this.convertToMinutesSeconds(i.duration_ms)\n }\n tracks.push(track);\n });\n this.tracks = tracks;\n\n }, (response) => {\n if (response.status === 401 || response.status === 403 || response.status === 419 || response.status === 440)\n this._JWT.login();\n });\n }", "getBoughtTracks () {\n return music.getBoughtTracks().then((response) => {\n return response.data\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for All zone transfer in reverse direction. Step1: Add the selected all zones to the existing zones in the zonemap. Step2: Remove All zones from selected_zone map to make it free/blank. Also make Free/Blank contract code map and Selected_contract code map.
function zoneReverseAll() { window.cnt += 1; // global variable. // alert(window.cnt); // Step-1: // -------- Collection of existing zone codes from zone map. var len1 = $("#zone option").length; // length of not selected zone. var html = ''; if (len1 > 0) { var e1 = document.getElementById("zone"); // contains zone list for (var i = 0; i < len1; i++) { html += '<option value="' + e1.options[i].value + '">' + e1.options[i].text + '</option>'; } } // Add all of currently selected zones in the zone map. var len2 = $("#selected_zone option").length; // length of selected_zone // map. if (len2 > 0) { var e2 = document.getElementById("selected_zone"); // contains // selected_zone // list. for (var i = 0; i < len2; i++) { html += '<option value="' + e2.options[i].value + '">' + e2.options[i].text + '</option>'; } } html += '</option>'; $('#zone').html(html); // populate zone map. // ------ End. // Step-2: // ------ Remove the selected zone from selected_zone map. var html = ''; $('#selected_zone').html(html); // Free selected_zone map. $('#contract').html(html); // Free contract map. $('#selected_contract').html(html); // Free selected_contract map. $('#contract_desc').html(html); // Free contract_desc map. }
[ "function zoneReverse(){\r\n\twindow.cnt += 1; // global variable.\r\n\t//alert(window.cnt);\r\n\tvar e = document.getElementById(\"selected_zone\"); // contains selected zone list.\r\n\tvar fromDate = document.getElementById(\"fromDate\").value; // contains fromDate value.\r\n\tvar toDate = document.getElementById(\"toDate\").value; // contains toDate value.\r\n\r\n\tvar zoneCode = e.options[e.selectedIndex].value;\r\n\tvar zoneDesc = e.options[e.selectedIndex].text;\r\n\t//alert(zoneCode + '---' + zoneDesc);\r\n\t\r\n\t// Step-1:\r\n\t// -------- Collection of not selected zone codes from zone map.\r\n\tvar len1 = $(\"#zone option\").length; // length of not selected zone.\r\n\tvar html = '';\r\n\t\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"zone\"); // contains zone list\r\n\t\t\r\n\t\tfor (var i=0; i<len1; i++){\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'+ e1.options[i].text+ '</option>';\r\n\t\t}\r\n\t}\r\n\t// Add currently selected zone in the zone map.\r\n\thtml += '<option value=\"' + zoneCode + '\">'+ zoneDesc + '</option>';\r\n\thtml += '</option>';\r\n\t\t\r\n\t$('#zone').html(html); // populate zone map.\r\n\t// ------ End.\r\n\t\r\n\t// Step-2:\r\n\t// ------ Remove the selected zone from selected_zone map.\r\n\tvar len2 = $(\"#selected_zone option\").length; // length of zone map.\r\n\tvar html = '';\r\n\tvar zoneCodeAll=\"\";\r\n\t\r\n\tif (len2 > 0){\r\n\t\tvar e2 = document.getElementById(\"selected_zone\"); // contains selected_zone list.\r\n\t\t\r\n\t\tfor (var i=0; i<len2; i++){\r\n\t\t\tif (e2.options[i].value != zoneCode){\r\n\t\t\t\thtml += '<option value=\"' + e2.options[i].value + '\">'+ e2.options[i].text+ '</option>';\r\n\t\t\t\tzoneCodeAll += \"'\"+e2.options[i].value+\"',\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#selected_zone').html(html); // populate selected_zone map after removal of selected zone.\r\n\t\r\n\t// Step-3.\r\n\tif (zoneCodeAll != \"\")\r\n\t{\r\n\t\tzoneCodeAll = zoneCodeAll.substring(0, zoneCodeAll.length - 1);\r\n\t\tzoneCode = \"'\"+ zoneCode + \"'\";\r\n\t\t\r\n\t\t// to remove contract code from already selected_contract map\r\n\t\t// as well as contract map who are under the removed zone code.\r\n\t\t$.ajax({\r\n\t\t\ttype: \"POST\",\r\n\t\t\turl: \"securityDeposit.htm\",\r\n\t\t\tdata : \"zoneCode=\" + zoneCode + \"&fromDate=\" + fromDate + \"&toDate=\" + toDate + \"&_target11=contract\",\r\n\t\t\t// data: \"zoneCode=\"+zoneCode+\"&_target11=contract\",\r\n\t\t\tsuccess: function(response){\r\n\t\t\t\tvar data= $.parseJSON(response);\r\n\t\t\t\tvar html = '';\r\n\t\t\t\t\r\n\t\t\t\t// display of contract code instead of contract desc in the map.\r\n\t\t\t\tvar len = data.length;\r\n\t\t\t\tfor (var i=0; i<len; i++){\r\n\t\t\t\t\tcontcd = data[i].contractCode;\r\n\t\t\t\t\tvar src=document.getElementById('selected_contract');\r\n\t\t\t\t\tfor(var count=0;count<src.options.length;count++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(src.options[count].value ==contcd)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttry{\r\n\t\t\t\t\t\t\t\tsrc.remove(count,null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcatch(error)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsrc.remove(count);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcount--;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar dest=document.getElementById('contract');\r\n\t\t\t\t\tfor(var count=0;count<dest.options.length;count++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(dest.options[count].value ==contcd) // if exists, then delete.\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttry{\r\n\t\t\t\t\t\t\t\tdest.remove(count,null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcatch(error)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdest.remove(count);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcount--;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpopulateContract ('selected_contract', 'selected_contract', src, src);\r\n\t\t\t},\r\n\t\t\terror: function(e){\r\n\t\t\t\t// alert('Error: ' + e);\r\n\t\t\t}\r\n\t\t}); // End of data fetching.\r\n\t}\r\n\telse{\r\n\t\t$('#contract').html('');\r\n\t\t$('#selected_contract').html('');\r\n\t\t$('#contract_desc').html(html); // Free contract_desc map.\r\n\t}\r\n\t\t\r\n}", "function zoneForwardAll(){\r\n\t// -------- Collection of already selected zone codes.\r\n\tvar len1 = $(\"#selected_zone option\").length; // length of already selected zone.\r\n\tvar html = '';\r\n\tvar zoneCodeAll=\"\";\r\n\t\r\n\t// checking for already selected zones.\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"selected_zone\"); // contains selected_zone list.\r\n\t\t\r\n\t\tfor (var i=0; i<len1; i++){\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'+ e1.options[i].text+ '</option>';\r\n\t\t\tzoneCodeAll += \"'\"+e1.options[i].value+\"',\";\r\n\t\t}\r\n\t}\r\n\t// ------ End.\r\n\t\r\n\t// ------ Population of rest of All zones.\r\n\tvar e = document.getElementById(\"zone\");\r\n\tvar fromDate = document.getElementById(\"fromDate\").value; // contains fromDate value.\r\n\tvar toDate = document.getElementById(\"toDate\").value; // contains toDate value.\r\n\r\n\tvar len = $(\"#zone option\").length;\r\n\t//alert(\"length of drdn:\"+len);\r\n\t\t\t\r\n\tfor (var i=0; i<len; i++){\r\n\t\thtml += '<option value=\"' + e.options[i].value + '\">'+ e.options[i].text+ '</option>';\r\n\t\tzoneCodeAll += \"'\"+e.options[i].value+\"',\";\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#selected_zone').html(html);\r\n\tzoneCodeAll = zoneCodeAll.substring(0,zoneCodeAll.length - 1); \r\n\t//alert(zoneCodeAll); \r\n\t\r\n\thtml='';\r\n\t$('#zone').html(html);\t\r\n\t\r\n\t// ------ Populate contract code map of selected zone.\r\n\t// Fetching contract codes of the rest of zones from database,\r\n\t// and then add the contracts into the contract drop down list.\r\n\t$.ajax({\r\n\t\ttype: \"POST\",\r\n\t\turl: \"securityDeposit.htm\",\r\n\t\tdata : \"zoneCode=\" + zoneCodeAll + \"&fromDate=\" + fromDate + \"&toDate=\"\t+ toDate + \"&_target11=contract\",\r\n\r\n\t\t// data: \"zoneCode=\"+zoneCodeAll+\"&_target11=contract\",\r\n\t\tsuccess: function(response){\r\n\t\t\tvar data= $.parseJSON(response);\r\n\t\t\t\r\n\t\t\t// checking for already populated contracts for previously selected zone.\r\n\t\t\t/*var len3 = $(\"#contract option\").length;\r\n\t\t\tvar html = '';\r\n\t\t\t\r\n\t\t\t// display of contract code instead of contract description in the map.\r\n\t\t\tif (len3 > 0){\r\n\t\t\t\tvar e3 = document.getElementById(\"contract\");\r\n\t\t\t\t\r\n\t\t\t\tfor (var i=0; i<len3; i++){\r\n\t\t\t\t\thtml += '<option value=\"' + e3.options[i].value + '\">'+ e3.options[i].value+ '</option>';\r\n\t\t\t\t}\r\n\t\t\t}*/\r\n\t\t\t\r\n\t\t\t// display of contract code instead of contract desc in the map.\r\n\t\t\tvar len = data.length;\r\n\t\t\tfor (var i=0; i<len; i++){\r\n\t\t\t\thtml += '<option value=\"' + data[i].contractCode + '\">'+ data[i].contractName+ '</option>';\r\n\t\t\t}\r\n\t\t\thtml += '</option>';\r\n\t\t\t$('#contract').html(html); // populate contract map.\r\n\t\t},\r\n\t\terror: function(e){\r\n\t\t\t// alert('Error: ' + e);\r\n\t\t}\r\n\t}); // End of data fetching.\r\n\t\r\n\t// Removal of already selected_contract from newly sorted contracted list.\r\n\t// on 24-03-2017.\r\n\tvar len1 = $(\"#selected_contract option\").length; \r\n\tvar html='';\r\n\talert(\"Contracts to be adjusted: \"+len1);\t//Without this alert the contracts are not removed.\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"selected_contract\");\r\n\t\tfor (var i = 0; i < len1; i++) {\r\n\t\t\tvar contcd = e1.options[i].value;\r\n\t\t\talert(\"Adjusting contract #: \"+contcd);\t\t\t//Without this alert the contracts are not removed.\r\n\t\t\tvar src = document.getElementById('contract');\r\n\t\t\tfor (var count = 0; count < src.options.length; count++) {\r\n\t\t\t\tif (src.options[count].value == contcd) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tsrc.remove(count, null);\r\n\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\tsrc.remove(count);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcount--;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t} // end of inner for loop\r\n\t\t} // end of outer for loop\r\n\t}\r\n}", "function zoneForward(){\r\n\twindow.cnt += 1;\r\n\t//alert(window.cnt);\r\n\tvar e = document.getElementById(\"zone\"); // contains zone list.\r\n\tvar zoneCode = e.options[e.selectedIndex].value;\r\n\tvar zoneDesc = e.options[e.selectedIndex].text;\r\n\tvar fromDate = document.getElementById(\"fromDate\").value; // contains fromDate value.\r\n\tvar toDate = document.getElementById(\"toDate\").value; // contains toDate value.\r\n\r\n\t\t\r\n\t// -------- Collection of already selected zone codes.\r\n\tvar len1 = $(\"#selected_zone option\").length; // length of already selected zone.\r\n\tvar html = '';\r\n\tvar zoneCodeAll = \"\";\r\n\t\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"selected_zone\"); // contains selected_zone list\r\n\t\t\r\n\t\tfor (var i=0; i<len1; i++){\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'+ e1.options[i].text+ '</option>';\r\n\t\t\tzoneCodeAll += \"'\" + e1.options[i].value + \"',\"; // include already selected zones.\r\n\t\t}\r\n\t}\r\n\t// Add currently selected zone in the selected_zone map.\r\n\thtml += '<option value=\"' + zoneCode + '\">'+ zoneDesc + '</option>';\r\n\thtml += '</option>';\r\n\tzoneCodeAll += \"'\" + zoneCode + \"'\"; // include currently selected zone.\r\n\t\r\n\t$('#selected_zone').html(html); // populate selected zone map.\r\n\t// ------ End.\r\n\t\r\n\t// ------ Remove the selected zone from zone map.\r\n\tvar len2 = $(\"#zone option\").length; // length of zone map.\r\n\tvar html = '';\r\n\t\r\n\tif (len2 > 0){\r\n\t\tvar e2 = document.getElementById(\"zone\"); // contains zone list.\r\n\t\t\r\n\t\tfor (var i=0; i<len2; i++){\r\n\t\t\tif (e2.options[i].value != zoneCode)\r\n\t\t\t html += '<option value=\"' + e2.options[i].value + '\">'+ e2.options[i].text+ '</option>';\r\n\t\t}\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#zone').html(html); // populate zone map after removal of selected zone.\r\n\t$('#contract').html('');\r\n\t\r\n\t// zoneCode = \"'\"+zoneCode+\"'\"; // e.g. '02'.\r\n\t\r\n\t// ------ End.\r\n\t\r\n\t// ------ Populate contract code map of selected zone.\r\n\t// Fetching contract codes of the selected zone from database,\r\n\t// and then add the contracts into the contract drop down list.\r\n\t$.ajax({\r\n\t\ttype: \"POST\",\r\n\t\turl: \"securityDeposit.htm\",\r\n\t\tdata : \"zoneCode=\" + zoneCodeAll + \"&fromDate=\" + fromDate + \"&toDate=\"\t+ toDate + \"&_target11=contract\",\r\n\t\t// data: \"zoneCode=\"+zoneCode+\"&_target11=contract\",\r\n\t\tsuccess: function(response){\r\n\t\t\tvar data= $.parseJSON(response);\r\n\t\t\t\r\n\t\t\t// checking for already populated contracts for previously selected zone.\r\n\t\t\t/*var len3 = $(\"#contract option\").length;\r\n\t\t\tvar html = '';\r\n\t\t\t\r\n\t\t\t// display of contract code instead of contract description in the map.\r\n\t\t\tif (len3 > 0){\r\n\t\t\t\tvar e3 = document.getElementById(\"contract\");\r\n\t\t\t\t\r\n\t\t\t\tfor (var i=0; i<len3; i++){\r\n\t\t\t\t\thtml += '<option value=\"' + e3.options[i].value + '\">'+ e3.options[i].value+ '</option>';\r\n\t\t\t\t}\r\n\t\t\t}*/\r\n\t\t\t\r\n\t\t\t// display of contract code instead of contraction desc in the map.\r\n\t\t\tvar len = data.length;\r\n\t\t\tvar html = '';\r\n\t\t\tfor (var i=0; i<len; i++){\r\n\t\t\t\thtml += '<option value=\"' + data[i].contractCode + '\">'+ data[i].contractName+ '</option>';\r\n\t\t\t}\r\n\t\t\thtml += '</option>';\r\n\t\t\t$('#contract').html(html); // populate contract map.\r\n\t\t},\r\n\t\terror: function(e){\r\n\t\t\t// alert('Error: ' + e);\r\n\t\t}\r\n\t}); // End of data fetching.\r\n\t\r\n\t// Removal of already selected_contract from newly sorted contracted list.\r\n\t// on 24-03-2017.\r\n\tvar len1 = $(\"#selected_contract option\").length; \r\n\tvar html='';\r\n\t//alert(\"Contracts to be adjusted: \"+len1);\t//Without this alert the contracts are not removed.\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"selected_contract\");\r\n\t\tfor (var i = 0; i < len1; i++) {\r\n\t\t\tvar contcd = e1.options[i].value;\r\n\t\t\talert(\"Adjusting contract #: \"+contcd);\t\t\t//Without this alert the contracts are not removed.\r\n\t\t\t//dummyFunction();\r\n\t\t\tvar src = document.getElementById('contract');\r\n\t\t\tfor (var count = 0; count < src.options.length; count++) {\r\n\t\t\t\tif (src.options[count].value == contcd) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tsrc.remove(count, null);\r\n\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\tsrc.remove(count);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcount--;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t} // end of inner for loop\r\n\t\t} // end of outer for loop\r\n\t}\r\n}", "function mapa_seleccionarSubZona(subzona_seleccionada_id, cargarEscuelas) {\n\tvar mapa_regiones = new Array();\n\tvar escuelas = new Array();\n\t// ¿Ninguna subzona?\n\tif (subzona_seleccionada_id === 'none') {\n\t\tg_mapa_interacciones = false;\n\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\tg_mapa_interacciones = true;\n\t\tif (cargarEscuelas === true) {\n\t\t\tmapa_obtenerEscuelas(null);\n\t\t}\n\t}\n\t// ¿Todas las subzonas?\n\telse if (subzona_seleccionada_id === 'all') {\n\t\t// ¿En todas las zonas?\n\t\tif (g_mapa_zona_seleccionada_id === 'all') {\n\t\t\t// Recorrer todas las subzonas de todas las zonas y obtener las escuelas y las regiones para el mapa\n\t\t\tfor (var i = 0; i < g_mapa_subzonas.length; i++) {\n\t\t\t\tmapa_regiones.push(g_mapa_subzonas[i].estado_codigo);\n\t\t\t\tvar subzona_escuelas = g_mapa_subzonas[i].escuelas;\n\t\t\t\tfor (var j = 0; j < subzona_escuelas.length; j++) {\n\t\t\t\t\tescuelas.push(subzona_escuelas[j]);\n\t\t\t\t}\n\t\t\t}\n\t\t\tg_mapa_interacciones = false;\n\t\t\tif (mapa_regiones.length > 0) {\n\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tregion: mapa_regiones,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tscale: 0.38094693877551017,\n\t\t\t\t\tlat: 0,\n\t\t\t\t\tlng: 447.51125016071666,\n\t\t\t\t\tx: 0.5,\n\t\t\t\t\ty: 0.5,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\t\t\t}\n\t\t\tg_mapa_interacciones = true;\n\t\t\tif (cargarEscuelas === true) {\n\t\t\t\tmapa_obtenerEscuelas(escuelas);\n\t\t\t}\n\t\t}\n\t\t// ¿En una zona en particular?\n\t\telse {\n\t\t\t// Recorrer todas las subzonas de la zona y obtener las escuelas y las regiones para el mapa\n\t\t\tfor (var i = 0; i < g_mapa_subzonas.length; i++) {\n\t\t\t\tif (g_mapa_subzonas[i].zona_id === Number(g_mapa_zona_seleccionada_id)) {\n\t\t\t\t\tmapa_regiones.push(g_mapa_subzonas[i].estado_codigo);\n\t\t\t\t\tvar subzona_escuelas = g_mapa_subzonas[i].escuelas;\n\t\t\t\t\tfor (var j = 0; j < subzona_escuelas.length; j++) {\n\t\t\t\t\t\tescuelas.push(subzona_escuelas[j]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tg_mapa_interacciones = false;\n\t\t\tif (mapa_regiones.length > 0) {\n\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tregion: mapa_regiones,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tscale: 0.38094693877551017,\n\t\t\t\t\tlat: 0,\n\t\t\t\t\tlng: 447.51125016071666,\n\t\t\t\t\tx: 0.5,\n\t\t\t\t\ty: 0.5,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\t\t\t}\n\t\t\tg_mapa_interacciones = true;\n\t\t\tif (cargarEscuelas === true) {\n\t\t\t\tmapa_obtenerEscuelas(escuelas);\n\t\t\t}\n\t\t}\n\t}\n\t// ¿Una subzona en particular?\n\telse {\n\t\t// ¿En todas las zonas?\n\t\tif (g_mapa_zona_seleccionada_id === 'all') {\n\t\t\t// Recorrer todas las subzonas de todas la zonas y obtener las escuelas y las regiones para el mapa\n\t\t\tfor (var i = 0; i < g_mapa_subzonas.length; i++) {\n\t\t\t\t// ¿Es esta la zona de la subzona seleccionada?\n\t\t\t\t// if (g_mapa_subzonas[i].estado_codigo === Number(subzona_seleccionada_id)) {\n\t\t\t\tif (g_mapa_subzonas[i].estado_codigo === subzona_seleccionada_id) {\n\t\t\t\t\tg_mapa_zona_seleccionada_id = g_mapa_subzonas[i].zona_id;\n\t\t\t\t\tmapa_regiones.push(g_mapa_subzonas[i].estado_codigo);\n\t\t\t\t\tvar subzona_escuelas = g_mapa_subzonas[i].escuelas;\n\t\t\t\t\tfor (var j = 0; j < subzona_escuelas.length; j++) {\n\t\t\t\t\t\tescuelas.push(subzona_escuelas[j]);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmapa_seleccionarZona(g_mapa_zona_seleccionada_id, false);\n\t\t\t$('#mapa-zona-select').val(g_mapa_zona_seleccionada_id);\n\t\t\t$('#mapa-zona-select').selectpicker('render');\n\t\t\t$('#mapa-subzona-select').val(subzona_seleccionada_id);\n\t\t\t$('#mapa-subzona-select').selectpicker('render');\n\t\t\tg_mapa_interacciones = false;\n\t\t\tif (mapa_regiones.length > 0) {\n\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tregion: mapa_regiones,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tscale: 0.38094693877551017,\n\t\t\t\t\tlat: 0,\n\t\t\t\t\tlng: 447.51125016071666,\n\t\t\t\t\tx: 0.5,\n\t\t\t\t\ty: 0.5,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\t\t\t}\n\t\t\tg_mapa_interacciones = true;\n\t\t\tif (cargarEscuelas === true) {\n\t\t\t\tmapa_obtenerEscuelas(escuelas);\n\t\t\t}\n\t\t}\n\t\t// ¿En una zona en particular?\n\t\telse {\n\t\t\t// Encontrar la subzona y obtener las escuelas y las regiones para el mapa\n\t\t\tfor (var i = 0; i < g_mapa_subzonas.length; i++) {\n\t\t\t\t// ¿Es esta la zona de la subzona seleccionada?\n\t\t\t\t// if (g_mapa_subzonas[i].estado_codigo === Number(subzona_seleccionada_id)) {\n\t\t\t\tif (g_mapa_subzonas[i].estado_codigo === subzona_seleccionada_id) {\n\t\t\t\t\tmapa_regiones.push(g_mapa_subzonas[i].estado_codigo);\n\t\t\t\t\tvar subzona_escuelas = g_mapa_subzonas[i].escuelas;\n\t\t\t\t\tfor (var j = 0; j < subzona_escuelas.length; j++) {\n\t\t\t\t\t\tescuelas.push(subzona_escuelas[j]);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tg_mapa_interacciones = false;\n\t\t\tif (mapa_regiones.length > 0) {\n\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tregion: mapa_regiones,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').clearSelectedRegions();\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setSelectedRegions(mapa_regiones);\n\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\tscale: 0.38094693877551017,\n\t\t\t\t\tlat: 0,\n\t\t\t\t\tlng: 447.51125016071666,\n\t\t\t\t\tx: 0.5,\n\t\t\t\t\ty: 0.5,\n\t\t\t\t\tanimate: true\n\t\t\t\t});\n\t\t\t}\n\t\t\tg_mapa_interacciones = true;\n\t\t\tif (cargarEscuelas === true) {\n\t\t\t\tmapa_obtenerEscuelas(escuelas);\n\t\t\t}\n\t\t}\n\t}\n\twindow.dispatchEvent(new Event('resize'));\n}", "function update_zones() {\n\n // list of floor\n var floorPanel = d3.select('#floor-list');\n\n // previous number of floors\n var currentNFloors = $(\"#floor-list > div\").length\n \n // update number of floors\n var updatedNFloors = parseInt(jQuery('#nfloors').val());\n \n // if now the number of floors is more\n if (updatedNFloors > currentNFloors) {\n \n // add new floors in the building\n for (var i=currentNFloors; i<updatedNFloors; i++) {\n \n // add new floor\n addFloor(i);\n \n // update building configuration json\n globalBuildingMap[\"building\"][\"floors\"].push({\"label\":\"F\"+(i+1).toString()});\n\n // personalize appliance list\n var applianceList = globalDefaultAppList;\n applianceList.forEach(element => element[\"app_id\"] = \"b_f\" + (i+1).toString() + \"_\" + element[\"label\"].toLowerCase());\n globalBuildingMap[\"building\"][\"floors\"][i][\"appliances\"] = applianceList;\n \n var applianceList = globalDefaultAppList;\n applianceList.forEach(element => element[\"app_id\"] = \"b_f\" + (i+1).toString() + \"_z1_\" + element[\"label\"].toLowerCase());\n globalBuildingMap[\"building\"][\"floors\"][i][\"zones\"] = [{\"label\":\"Z1\", \"appliances\":applianceList}];\n\n // add new floors and zones to the red list\n globalRedList.push(\"F\"+(i+1).toString())\n globalRedList.push(\"F\"+(i+1).toString() + \"_Z1\")\n }\n } \n // if now the number of floors is less\n else if (updatedNFloors < currentNFloors) {\n // remove floors from the end\n for (var i=currentNFloors-1; i>=updatedNFloors; i--) {\n \n // remove floor\n d3.select('.f' + (i+1).toString() + '-div').remove();\n \n // update json\n globalBuildingMap[\"building\"][\"floors\"].splice(i, 1);\n }\n \n // update max_nzones\n sysVariables['max_nzones'] = 0\n for (var i=0; i<updatedNFloors; i++) {\n \n var nZones = Object.keys(globalBuildingMap[\"building\"][\"floors\"][i][\"zones\"]).length\n if (nZones > sysVariables['max_nzones']) {\n sysVariables['max_nzones'] = nZones;\n }\n }\n }\n\n // build summary table\n generateTable();\n}", "function populateZones(formElements, country) {\n const zoneEl = formElements.zone;\n if (!zoneEl) {\n return;\n }\n\n if (country.zones.length === 0) {\n zoneEl.wrapper.dataset.ariaHidden = 'true';\n zoneEl.input.innerHTML = '';\n return;\n }\n\n zoneEl.wrapper.dataset.ariaHidden = 'false';\n\n const zoneSelect = zoneEl.input;\n const duplicatedZoneSelect = zoneSelect.cloneNode(true);\n duplicatedZoneSelect.innerHTML = '';\n\n country.zones.forEach((zone) => {\n const optionElement = document.createElement('option');\n optionElement.value = zone.code;\n optionElement.textContent = zone.name;\n duplicatedZoneSelect.appendChild(optionElement);\n if (zoneSelect.dataset.default == zone.name) {\n zoneSelect.dataset.default = zone.code;\n }\n });\n\n zoneSelect.innerHTML = duplicatedZoneSelect.innerHTML;\n\n if (zoneSelect.dataset.default) {\n zoneSelect.value = zoneSelect.dataset.default;\n }\n}", "function mapa_cargarSelectSubzonas(lista_subzonas) {\n\tg_lista_subzonas = new Array();\n\tvar html_subzonas = '<option value=\"none\">Selecciona un estado</option>';\n\tif (!(g_mapa_zona_seleccionada_id === 'none')) {\n\t\thtml_subzonas += '<option value=\"all\">Todos</option>';\n\t}\n\tfor (var i = 0; i < lista_subzonas.length; i++) {\n\t\tvar subzona = lista_subzonas[i];\n\t\thtml_subzonas += '<option value=\"' + subzona.estado_codigo + '\">' + subzona.estado_nombre + '</option>';\n\t\tg_lista_subzonas.push(subzona);\n\t}\n\t$('#mapa-subzona-select').html(html_subzonas);\n\t$('#mapa-subzona-select').selectpicker('refresh');\n\t$('#mapa-subzona-select').change(function() {\n\t\tg_mapa_subzona_seleccionada_id = $('#mapa-subzona-select').val();\n\t\tmapa_seleccionarSubZona(g_mapa_subzona_seleccionada_id, true);\n\t});\n\tg_mapa_subzona_seleccionada_id = 'none';\n}", "function buildZonesDict(helperArrFlat,geometry){\n var vertexDictZ;\n var vertexDictX;\n //iterate through vertices\n for(var i=0; i<geometry.vertices.length; i++){\n vertexDictZ=customFloor(geometry.vertices[i].x,globalTerrainData.distanceZ);\n vertexDictX=customFloor(geometry.vertices[i].y,globalTerrainData.distanceX);\n //Fill in vertexDict with appropriate value from helperArrFlat\n globalTerrainData.vertexDict[[vertexDictZ,vertexDictX]]=[helperArrFlat[i][0],helperArrFlat[i][helperArrFlat[i].length-1]];\n //The first time we hit a certain Z zone (i.e. path), record its Z coordinate\n if(!globalTerrainData.zZones[helperArrFlat[i][0]]){\n globalTerrainData.zZones[helperArrFlat[i][0]]=vertexDictX;\n }\n else if(vertexDictX<globalTerrainData.zZones[helperArrFlat[i][0]]){\n globalTerrainData.zZones[helperArrFlat[i][0]]=vertexDictX;\n }\n //The first time we hit a certain X zone (i.e. chunk), record its XCoordinate\n if(!globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]){\n globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]=vertexDictZ; \n }\n else if(vertexDictZ<globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]){\n globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]=vertexDictZ;\n }\n }\n //Get last padding zones\n var toAdd=globalTerrainData.zZones[0]-globalTerrainData.zZones[1];\n globalTerrainData.zZones[999]=globalTerrainData.zZones[0]+toAdd;\n globalTerrainData.zZones[-1] = globalTerrainData.zZones[2] - toAdd;\n var keys=Object.keys(globalTerrainData.xZones);\n toAdd=globalTerrainData.xZones[1]-globalTerrainData.xZones[0];\n globalTerrainData.xZones[999]=globalTerrainData.xZones[keys.length-2]+toAdd;\n globalTerrainData.xZones[-1] = globalTerrainData.xZones[0] - toAdd;\n}", "function updateZones() {\n var hrRest = parseIntInput(\"hrRest\");\n var hrMax = parseIntInput(\"hrMax\");\n var zones = CALC.hrzones.petehrr(hrRest, hrMax);\n document.getElementById('hrRecovery').innerHTML = zones.recovery[1];\n document.getElementById('hrGAmin').innerHTML = zones.generalaerobic[0];\n document.getElementById('hrGAmax').innerHTML = zones.generalaerobic[1];\n document.getElementById('hrEndurancemin').innerHTML = zones.endurance[0];\n document.getElementById('hrEndurancemax').innerHTML = zones.endurance[1];\n document.getElementById('hrLTmin').innerHTML = zones.lactatethreshold[0];\n document.getElementById('hrLTmax').innerHTML = zones.lactatethreshold[1];\n document.getElementById('hrVO2min').innerHTML = zones.vo2max[0];\n document.getElementById('hrVO2max').innerHTML = zones.vo2max[1];\n}", "function addExitRegions(gm) {\n for (let gate of this.ecs.getSystem(System.GateSelector).latest()) {\n let comps = this.ecs.getComponents(gate);\n let gateComp = comps.get(Component.Gate);\n let pos = comps.get(Component.Position);\n let zonePos = pos.p.copy().add_(new Point(0, 100).rotate_(-pos.angle));\n let degAngle = -(Constants.RAD2DEG * pos.angle);\n if (gateComp.exit) {\n gm.produce('nextToExitv2', {\n height: 1,\n width: 1,\n rotation: degAngle + 90,\n x: zonePos.x,\n y: zonePos.y,\n });\n }\n }\n }", "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 cleanMap() {\n\n\t// Disable position selection by mouse click.\n\tdisablePositionSelect();\n\n\t// Remove existing nearby stations layer.\n\tif (map.getLayersByName(\"Nearby Docking Stations\")[0] != null)\n\t\tmap.removeLayer(map.getLayersByName(\"Nearby Docking Stations\")[0]);\n\t\t\n\t// Reset select controls.\n\tif (selectControl !=null) {\n\t\tselectControl.unselectAll();\n\t\tselectControl.deactivate();\n\t}\n \tif (selIncControl !=null) {\n\t\tselIncControl.unselectAll();\n\t\tselIncControl.deactivate();\n\t}\n \tif (voteControl !=null) {\n\t\tvoteControl.unselectAll();\n\t\tvoteControl.deactivate();\n\t} \n\tif (selectDockControl != null) {\n\t\tselectDockControl.unselectAll();\n\t\tselectDockControl.deactivate();\n\t}\n\n\tif (distr_stats != null)\n\t\tmap.removeLayer(distr_stats);\n}", "function changeOrder() {\n\tvar controlsNode = this.parentNode.parentNode;\n\tvar maps = $(controlsNode).parent().parent().find('.map');\n\tvar orderedMaps = [];\n\tfor (var i = 0; i < maps.length; i++) {\n\t\torderedMaps[maps.length - 1 - i] = maps[i];\n\t}\n\tvar mapsNode = $(controlsNode.parentNode.parentNode).find('.maps')[0];\n\toutputMaps(orderedMaps, mapsNode);\n}", "function subtractMap(){\n $('#subtractButton').on('click',function() {\n rightMapProperties.map.centerAt([-114,53.5444]);\n $('#subtractButton').hide();\n $('#'+rightMapProperties.mapDivId).height('100%');\n $('#title').text('Compare Accessibility: '+' '+$('#title1').text()+' - '+$('#title2').text());\n $('#title2').hide();\n $('#section1').hide();\n $('#section2').width(\"100%\");\n $('#section2').height(\"95%\");\n\n difference = true;\n var list = {};\n for(var k in leftMapProperties.dataMatrix){\n list[k] = leftMapProperties.dataMatrix[k]-rightMapProperties.dataMatrix[k]\n }\n sort = Object.values(list).sort(function(a, b){return a - b});\n var symbol = new SimpleFillSymbol();\n rightMapProperties.renderer = new ClassBreaksRenderer(symbol, function(feature){\n if(rightMapProperties.check === false){\n return leftMapProperties.dataMatrix[feature.attributes.TAZ_New]-rightMapProperties.dataMatrix[feature.attributes.TAZ_New];\n }\n else{\n return leftMapProperties.reverseDataMatrix[feature.attributes.TAZ_New]-rightMapProperties.reverseDataMatrix[feature.attributes.TAZ_New];\n }\n });\n rightMapProperties.renderer=changeRender(rightMapProperties.renderer);\n rightMapProperties.travelZoneLayer.setRenderer(rightMapProperties.renderer);\n rightMapProperties.travelZoneLayer.redraw();\n });\n }", "function resetStreetViews(){\n for (var i = 0; i < svpArray.length; i++) {\n svpArray[i].marker.setMap(null);\n }\n svpArray = [];\n $(\"#loading\").css('visibility', 'visible');\n directionsDisplay.setMap(null);\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 }", "async refreshWallets() {\n const gapLimit = 1; //after 20 empty addresse we drop out\n\n //Deposit\n for (let i = 0, consecutivelyEmpty = 0; consecutivelyEmpty < gapLimit; i++) {\n let wallet = await this.refreshWallet({derive: `m/44'/1'/0'/0/${i}`})\n if (!wallet.used) {\n consecutivelyEmpty++;\n }\n }\n //Change\n for (let i = 0, consecutivelyEmpty = 0; consecutivelyEmpty < gapLimit; i++) {\n let wallet = await this.refreshWallet({derive: `m/44'/1'/0'/1/${i}`})\n if (!wallet.used) {\n consecutivelyEmpty++;\n }\n }\n }", "function DeleteNewZoneSubzone(type,address){\n // alert(type+address);\n var childid;\n var fromlead = 0;\n if(type == 1){\n document.getElementById('province').options.length = 1;\t\n document.getElementById('city').options.length = 1;\n document.getElementById('zone').options.length = 1;\n document.getElementById('subzone').options.length = 1;\n childid =document.getElementById(\"province\");\n \t}\n else if(type == 2){\t\t\n document.getElementById('city').options.length = 1;\n document.getElementById('zone').options.length = 1;\n document.getElementById('subzone').options.length = 1;\n childid =document.getElementById(\"city\");\n \t}\n\telse if(type == 3){ \n document.getElementById('zone').options.length = 1;\n document.getElementById('subzone').options.length = 1;\n childid =document.getElementById(\"zone\");\n \t}\n\telse if(type == 4){\t \n document.getElementById('subzone').options.length = 1;\n childid =document.getElementById(\"subzone\");\n }\nif(address !=\"\")\n{\n var flag = 1;\n fromlead = 1;\n callAjaxForDeleteZoneSubzone(type,address,flag);\n }\n}", "save() {\n this.init_();\n this.mergeFromMap_();\n Settings.getInstance().set(['map', 'z-order'], this.groups_);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shortcut function called when a section block is selected by the Theme Editor 'shopify:block:select' event.
onBlockSelect() { // Do something when a section block is selected }
[ "blockHitAreaClicked(e) {\n // When you click on the text, the browser will automatically select the word.\n // Therefore, the editor shrinks spans instead of selecting spans.\n // Deselect the text.\n if (e.button === 2) {\n clearTextSelection()\n }\n\n const selection = window.getSelection()\n\n // When you create a block span and\n // click on another block span while holding down the Shift key,\n // the Selection type will be 'None'.\n if (selection.type === 'Caret' || selection.type === 'None') {\n const spanId = e.target.dataset.id\n\n this._selectSpanAndEntity(e, spanId)\n }\n }", "function blockClassSelected() {selectedBlock.attr('class', 'selected')}", "function on_piece_select()\n{\n\tupdate_editor();\n}", "markerClick() {\n store.setActiveSection(store.currentFileSha, this.section);\n }", "function trackSelectedRegion(element, redirect) {\n var shift = false, anchor;\n var events = [];\n\n dome.on(document.body, \"keydown\", function (e) {\n shift = e.which === 16;\n });\n dome.on(document.body, \"keyup\", function (e) {\n shift = e.which !== 16;\n });\n\n dome.on(element, \"click\", function (e) {\n var region, currLine = getLineNum(e.target);\n if (!shift || !anchor) { anchor = e.target; }\n\n if (anchor && shift) {\n region = orderedRegion(getLineNum(anchor), currLine);\n e.preventDefault();\n } else {\n region = [currLine, currLine];\n }\n\n setRegion(element, region, redirect);\n });\n }", "function sectionOn() { }", "setBlockCategory(blockCategory) {\n repoCmsPage.getBlockCategoryDropdown().select(blockCategory);\n }", "onSelectionChange(cb) {\n this.on('selection-change', cb)\n }", "function SDitemSelection(section, order, choice) {\n // get current section layout\n curOrder = api.parameters.get({name: section}, \"CommPlugin_1\").data[0].value;\n curOrderArr = curOrder.split(',');\n // access the right order to alter user selection\n curOrderArr[order] = choice;\n // update parameter\n api.parameters.updateAsync({\n name: section,\n value: curOrderArr.toString()\n });\n}", "add_select(func) {\n this.add_event(\"select\", func);\n }", "onSelectionEdited(func){ return this.eventSelectionEdited.register(func); }", "function selectItem(e) {\n removeBorder();\n removeShow();\n // Add Border to current feature\n this.classList.add('feature-border');\n // Grab content item from DOM\n const featureContentItem = document.querySelector(`#${this.id}-content`);\n // Add show\n featureContentItem.classList.add('show');\n}", "static onSelect() {\n const node = Navigator.byItem.currentNode;\n if (MenuManager.isMenuOpen() || node.actions.length <= 1 ||\n !node.location) {\n node.doDefaultAction();\n return;\n }\n\n ActionManager.instance.menuStack_ = [];\n ActionManager.instance.menuStack_.push(MenuType.MAIN_MENU);\n ActionManager.instance.actionNode_ = node;\n ActionManager.instance.openCurrentMenu_();\n }", "function mark_selected(block_number) {\n if (block_number === \" \") return;\n\n // Change color for selection of a new block\n for(row = 0; row < game_board.length; row++) {\n for (column = 0; column < game_board[row].length; column++) {\n var div_name = game_board[row][column];\n var child_div = document.getElementById(div_name);\n if(child_div.innerHTML == String(block_number)) {\n child_div.style.backgroundColor = selected_color; \n } else {\n child_div.style.backgroundColor = unselected_color;\n }\n }\n }\n // Write out the collected to our div\n var selected_span = document.getElementById('selected');\n selected_span.innerHTML = String(block_number);\n}", "function preselectAccordionSection(sectionSelector, accordionSelector) {\n\t\n\t// apply shortcut syntax for the section selector\n\tvar queryResultIndex = 0;\n\tif ((typeof sectionSelector) == 'number') {\n\t\tqueryResultIndex = sectionSelector;\n\t\tsectionSelector = '.collapse';\n\t}\n\t\n\t// apply default accordion selector\n\tif (!accordionSelector) {\n\t\taccordionSelector = '#accordion';\n\t}\n\t\n\t// pre-select the section\n\t$($(accordionSelector).find(sectionSelector)[queryResultIndex]).addClass('in').css('height', '');\n\t\n}", "_onSlideSelected( event) {\n const selectedSlide = event.detail.slide;\n console.debug( `dia-show › on-slide-selected: ${selectedSlide}`);\n this.moveToSlide( selectedSlide);\n if( event.cancellable) { event.stopPropagation(); }\n }", "function SelectCodeBlock() {\r\n\tvar uSel = Editor.Selection;\r\n if (Sel.SelStartLine == 0) return;\r\n\r\n\tvar startLine = FindCodeStart(uSel.SelStartLine);\r\n\r\n\tif (startLine >= 0) { \t\t\t\t\t\t// We found the starting line\r\n\t\t// Find line with starting curly bracket (not always the same as the startLine)\r\n\t\tvar bracketLine = FindStartBracket(startLine);\r\n\t\tif (bracketLine != -1) {\t\t\t\t// We found the starting curly bracket\r\n\t\t\tvar endLine = FindCodeEnd(bracketLine);\r\n\t\t\tif (endLine >= startLine) { \t // We found the ending line\r\n\t\t\t\t// Set selection\r\n\t\t\t\tuSel.SelStartLine = startLine;\r\n\t\t\t\tuSel.SelStartCol = 0;\r\n\t\t\t\tuSel.SelEndLine = endLine + 1;\r\n\t\t\t\tuSel.SelEndCol = 0;\r\n\t\t\t\tEditor.Selection = uSel;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function onSelectedMeme(memeIdx){\n setMeme(memeIdx);\n openMemeGenSection();\n renderCanvas();\n}", "_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }", "_optionSelected(e) {\n let local = e.target;\n // fire that an option was selected and about what operation\n let ops = {\n element: this,\n operation: this.activeOp,\n option: local.getAttribute(\"id\"),\n };\n this.dispatchEvent(\n new CustomEvent(\"item-overlay-option-selected\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n detail: ops,\n })\n );\n // don't reset for movement, just confirm / reject actions\n if (this.activeOp != \"move\") {\n this._resetActive();\n this.activeOp = null;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of DefaultLinkHandler.
constructor() { super(); this.handler = (e) => { let {shouldHandleEvent, href} = DefaultLinkHandler.getEventInfo(e); if (shouldHandleEvent) { e.preventDefault(); this.history.navigate(href); } }; }
[ "_init() {\n try {\n if (!fs.existsSync(LINKS_DIR)) {\n fs.mkdirSync(LINKS_DIR);\n }\n this.links = require(LINKS_PATH);\n\n for (const key in this.links) {\n if (this.links.hasOwnProperty(key)) {\n const url = this.links[key].url;\n\n if (!this._urls[url]) {\n this._urls[url] = key;\n }\n }\n }\n }\n catch (e) {\n pino.error('Could not load links: ' + e.message);\n }\n }", "static create() {\n return new FastHttpMiddlewareHandler();\n }", "set link(aValue) {\n this._logService.debug(\"gsDiggEvent.link[set]\");\n this._link = aValue;\n\n var uri;\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n this._domain = uri.host;\n }", "function createLink(idSource, idTarget) {\n var links = JSON.parse(CacheService.getPrivateCache().get(\"links\"));\n if(links[idSource] == undefined) {\n links[idSource] = []; \n } \n var target = {};\n target[\"target\"] = idTarget;\n links[idSource].push(target);\n DocumentApp.getUi().alert('Link created (in the cache)'); \n CacheService.getPrivateCache().put('links', JSON.stringify(links), 3600); \n}", "function initMenuAnchorsHandler() {\n\t\t\t\tvar $anchorLinks = $scope.find( '.menu-item-link[href*=\"#\"]' );\n\n\t\t\t\tif ( $anchorLinks[0] ) {\n\t\t\t\t\t$anchorLinks.each( function() {\n\t\t\t\t\t\tif ( '' !== this.hash && location.pathname === this.pathname ) {\n\t\t\t\t\t\t\tmenuAnchorHandler( $( this ) );\n\t\t\t\t\t\t}\n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t}", "function link() {\n console.log('core::link,', 'linking modules');\n var i = 0,\n sorted = [],\n sortedLen = 0,\n parent = new Module(),\n name = '',\n module = null;\n\n // Sort modules in dependency order\n sorted = sort(modules);\n sortedLen = sorted.length;\n\n // Link modules in dependency order\n for (i = 0; i < sortedLen; i += 1) {\n name = sorted[i];\n module = modules[name];\n\n if (module.instance === undefined) {\n\n // Each module should inherit from a generic Module object\n module.def.prototype = parent;\n\n // Execute module code, pass requires, record exports\n modules[name].instance = instantiate(\n module.def,\n createParams(module.def, module.requires)\n );\n\n // Set module name\n modules[name].instance.name = name;\n\n if (typeof modules[name].instance.init === 'function') {\n modules[name].instance.init();\n }\n }\n }\n }", "set link(aValue) {\n this._logger.debug(\"link[set]\");\n this._link = aValue;\n\n let uri;\n\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n\n this._domain = uri.host;\n }", "_getLinkURL() {\n let href = this.context.link.href;\n\n if (href) {\n // Handle SVG links:\n if (typeof href == \"object\" && href.animVal) {\n return this._makeURLAbsolute(this.context.link.baseURI, href.animVal);\n }\n\n return href;\n }\n\n href = this.context.link.getAttribute(\"href\") ||\n this.context.link.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\");\n\n if (!href || !href.match(/\\S/)) {\n // Without this we try to save as the current doc,\n // for example, HTML case also throws if empty\n throw \"Empty href\";\n }\n\n return this._makeURLAbsolute(this.context.link.baseURI, href);\n }", "function CreateUrlTree ()\n{\n\treturn new UrlTreeNode (null, \"\", \"\");\n}", "constructor(defaultInstance = false) {\n this._events = {};\n\n if (defaultInstance == true) {\n Dispatcher._dispatchers = Dispatcher._dispatchers || {};\n Dispatcher._dispatchers['default'] = this;\n var _dispatcher = this;\n\n // Allows us to register a function with function.register(signal)\n Function.prototype.register = function (signal) {\n _dispatcher.register(signal, this); // this is resolved to the callee in this scope\n };\n }\n }", "function initializeLinks() {\n\tvar links = document.getElementById(\"links\"); // Da bismo uopste dosli do linkova, prvo moramo dobaviti element ID-a \"links\" u kom\n\t\t\t\t\t\t\t\t\t\t\t\t // se linkovi i nalaze.\n\tfor (var i = 0; i < links.children.length; i++) { // U ovoj for petlji prolazimo kroz svu \"decu\" elementa ID-a \"links\".\n\t\t\t\t\t\t\t\t\t\t\t\t\t // Deca ovog elementa su upravo linkovi koji su nam potrebni.\n\t\tvar link = links.children[i]; // Uzimamo i-to dete, tj. i-ti link.\n\t\tlink.onclick = showImage; // Govorimo JS-u da na klik linka treba da izvrsi funkciju \"showImage\".\n\t\tvar img = document.createElement(\"img\"); // Posto u link treba da ubacimo sliku, tj. \"img\" element, ovde taj \"img\" element kreiramo.\n\t\timg.setAttribute(\"src\", link.getAttribute(\"href\")); // Potom novokreiranoj slici postavljamo \"src\" atribut. Kao sto je receno\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// u opisu iznad ove funkcije, slika koja treba da se prikaze unutar linkova\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// jeste upravo ona slika na koju link vodi. Tako da \"src\" atribut novokreirane\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// slike treba da bude jednak \"href\" atributu linka.\n\t\tlink.appendChild(img); // Nakon sto smo kreirali i ispodesavali novi \"img\" element, dodajemo ga u tekuci link.\n\t}\n}", "function resetLink() {\n var instruction = gettext(\"This link will open the default version of this interactive:\");\n var link = window.location.href.split('?', 1)[0].replace(/^\\/+|\\/+$/g, '');\n $(\"#cfg-grammar-link\").html(`${instruction}<br><a target=\"_blank\" href=${link}>${link}</a>`);\n}", "function addRuleOpenLinksInNewPage(engine) {\n var defaultRender =\n engine.renderer.rules.link_open ||\n function (tokens, idx, options, env, self) {\n return self.renderToken(tokens, idx, options);\n };\n engine.renderer.rules.link_open = function (tokens, idx, options, env, self) {\n var aIndex = tokens[idx].attrIndex(\"target\");\n if (aIndex < 0) {\n tokens[idx].attrPush([\"target\", \"_blank\"]);\n } else {\n tokens[idx].attrs[aIndex][1] = \"_blank\";\n }\n return defaultRender(tokens, idx, options, env, self);\n };\n}", "function setSequenceLinkDefaultFlow(obj) {\n\t\t\n\t\t myDiagram.startTransaction(\"setSequenceLinkDefaultFlow\");\n\t\t var model = myDiagram.model;\n\t\t model.setDataProperty(obj.data, \"isDefault\", true);\n\t\t // Set all other links from the fromNode to be isDefault=null\n\t\t obj.fromNode.findLinksOutOf().each(function(link) {\n\t\t if (link !== obj && link.data.isDefault) {\n\t\t model.setDataProperty(link.data, \"isDefault\", null);\n\t\t }\n\t\t });\n\t\t myDiagram.commitTransaction(\"setSequenceLinkDefaultFlow\");\n\t\t }", "function createPointerEnterLinkHandler(polyline){\n return function(evt){\n polyline.setStyle(HOVER_LINK_STYLE);\n };\n }", "function setupBanLink() {\n\tvar a = $(\".banner a\");\n\tvar link = a.attr(\"href\");\n\ta.removeAttr(\"href\");\n\t\n\tif (isPath(homePath)) {\n\t\ta.click(toggleBanner);\n\t} else {\n\t\ta.click(function() {\n\t\t\tanimateLink(link, true);\n\t\t});\n\t}\n}", "get link() {\n this._logger.debug(\"link[get]\");\n return this._link;\n }", "function WrapperHandler (){\n\t//settings parameters \n\tthis.database = \"http://tdk3.csf.technion.ac.il:8890/sparql\";\n\tthis.graph_uri = \"http://dbpedia.org\";\n\t//create api\n\tthis.api = new ApiHandler(this);\n\t//setup wrapper\n\tthis.setup();\n}", "static getDefault() {\n return Dispatcher._dispatchers['default'];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draws bricks on canvas
function drawBricks() { for (var c = 0; c < brickColumnCount; c++) { for (var r = 0; r < brickRowCount; r++) { if (bricks[c][r].status === 1) { bricks[c][r].x = (c * (bricks[c][r].brickWidth + brickPadding)); bricks[c][r].y = (r * (bricks[c][r].brickHeight + brickPadding)); ctx.beginPath(); ctx.fillStyle = 'rgb(0,' + Math.floor(255 - 42.5 * r) + ',' + Math.floor(255 - 15 * c) + ')'; ctx.rect(bricks[c][r].x, bricks[c][r].y, bricks[c][r].brickWidth, bricks[c][r].brickHeight); ctx.fill(); ctx.closePath(); } } } }
[ "draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }", "function draw() {\n // clear the canvas\n canvas.width = canvas.width;\n drawBlocks();\n drawGrid();\n }", "drawBall() {\n fill('#FFFFFF');\n circle(this.x, this.y, 2 * this.radius);\n }", "drawBallReleaseBar() {\n const canvas = document.getElementById(\"myCanvas\");\n const ctx = canvas.getContext(\"2d\");\n ctx.beginPath();\n // ctx.rect(releaseBarX, releaseBarY, canvas.width-releaseBarWidth, releaseBarHeight, releaseBarWidth);\n ctx.strokeRect(381, 560, 280, 500);\n // ctx.fillStyle = \"#000000\";\n // ctx.fill();\n ctx.closePath();\n ctx.stroke();\n }", "draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }", "function drawApple(){\n\tctx.fillStyle = \"#ff0000\";\n\tctx.fillRect(appleX, appleY, blockSize, blockSize);\n}", "function drawBombers() {\n\t\tfor (var b = 0; b < bombers.length; b++) {\n\t\t\tif (bombers[b].isActive) {\n\t\t\t\tctx.save();\n\t\t\t\tctx.globalAlpha = bombers[b].health * 0.1;\n\t\t\t\tctx.translate(bombers[b].x, bombers[b].y);\n\t\t\t\tctx.rotate(Math.atan2(player.y - bombers[b].y, player.x-bombers[b].x));\n\t\t\t\tctx.drawImage(bomberImage, -15, -15, 30, 30);\n\t\t\t\t//ctx.drawImage(bomberImage, -10, -10);\n\t\t\t\tctx.fillStyle = 'red';\n\t\t\t\tctx.fillRect(-20, -10, 5, bombers[b].health/5);\n\t\t\t\tctx.strokeRect(-20, -10, 5, 20);\n\t\t\t\tctx.restore();\n//\t\t\t\tctx.globalAlpha = 1.0;\n\t\t\t}\n\t\t}\n\t}", "function drawAllBirds(context) {\r\n for (var i = 0; i < birds.length; i = i + 1) {\r\n var bird = birds[i];\r\n drawOneBird(context, bird);\r\n }\r\n}", "paintFrame() {\n for (let rowIterator = 0; rowIterator < this.gridState.length; rowIterator++) {\n for (let columnIterator = 0; columnIterator < this.columns; columnIterator++) {\n const cellState = Math.pow(2, columnIterator) & this.gridState[rowIterator]\n this.paintBrick(rowIterator, this.columns - columnIterator - 1, cellState !== 0)\n }\n }\n }", "function drawBucket(bucketWidth, bucketHeight) {\n\n var canvasWidth = context.canvas.width;\n var canvasHeight = context.canvas.height;\n\n context.save();\n\n context.strokeStyle = 'darkblue';\n context.lineWidth = 5;\n context.beginPath();\n context.moveTo(canvasWidth / 2 - bucketWidth / 2, canvasHeight - bucketHeight);\n context.lineTo(canvasWidth / 2 - bucketWidth / 2, canvasHeight);\n context.lineTo(canvasWidth / 2 + bucketWidth / 2, canvasHeight);\n context.lineTo(canvasWidth / 2 + bucketWidth / 2, canvasHeight - bucketHeight);\n context.stroke();\n\n context.restore();\n}", "function drawShapes() {\n\tfor (var i = 0; i < shapes.length; i++) {\n\t\tvar points = shapes[i];\n\t\tdrawFinishedShape(points);\n\t}\n}", "function sendBrick() {\n // move the stack down\n $('.catContainerOuter, .brick').animate({ top: '+=20' });\n\n // create a new brick\n var startingSide = Math.random() > 0.5 ? '-' : '';\n var speed = Math.max(1000, Math.floor(Math.random() * 2000) + 2000 - (score * 20));\n var additionalColorClass = (score + 1) % 10 === 0 ? 'ten' : (score + 1) % 5 === 0 ? 'five' : '';\n $('.brickContainer').prepend('<div class=\"brick ' + additionalColorClass + '\" style=\"left: ' + startingSide + '700px;\"></div>');\n $('.brick').eq(0).animate({ left: '50%' }, speed);\n }", "function drawPool() {\n //Draws water\n strokeWeight(2);\n fill(0, 0, 100, 220);\n rect(0, height-100, width, 100);\n\n //Pool deck\n fill(242, 242, 210);\n rect(0, height-102, 50, 102);\n rect(width-50, height-102, 50, 102);\n stroke(242, 242, 210);\n rect(0, height-20, width, 20);\n stroke(0);\n\n //Lines of the pool deck\n line(0, height-102, 0, height);\n line(50, height-21, width-50, height-21);\n strokeWeight(1);\n stroke(0);\n fill(0, 255, 0);\n\n //Diving boards\n rect(0, 110 * 1.5 - 11, width/3 + 10 + 3, 10);\n rect(0, 110 * 4.2 - 11, width/3 + 10 + 3, 10);\n}", "draw(ctx) {\r\n if (this.isDistanced) {\r\n this.distanceGraph();\r\n }\r\n // draw all nodes and store them in grid array\r\n this.nodeList.forEach(node => {\r\n node.draw(ctx);\r\n storeNodeAt(node, node.x, node.y);\r\n });\r\n\r\n // draw all edges\r\n this.edgeList.forEach(edge => {\r\n edge.draw(ctx);\r\n });\r\n\r\n\r\n }", "function updateAndDraw(){\r\n\t //Clear the canvas by drawing over the current dots\r\n\t clearDots();\r\n\t\t\t//Update the dots\r\n\t\t\tupdateDots();\r\n\t\t\t//Draw on the canvas\r\n\t\t\tdraw();\r\n\t\t}", "function paintAnalog()\n\t\t{\n\t\t\t// draw outer-background\n\t\t\tcontext.save();\n\t\t\tcontext.fillStyle = canvas.getAttribute( \"data-outer-color\" ) || \"rgba( 0,0,0,0 )\";\n\t\t\tcontext.fillRect( 0, 0, width, height );\n\t\t\tcontext.restore();\n\n\t\t\t// draw clock border and clock background\n\t\t\tcontext.beginPath();\t\n\t\t\tcontext.lineWidth = 1;\t\t\n\t\t\tdrawEllipse( context, centerX, centerY, width - context.lineWidth, height - context.lineWidth, 0, PI2, false );\n\t\t\tcontext.fill();\n\t\t\tcontext.stroke();\n\t\t\t\n\t\t\t// draw ticks\n\t\t\tvar ticks = canvas.getAttribute( \"data-ticks\" ) || \"lines\";\n\t\t\tticks = ticks.toLowerCase();\n\t\t\tif ( ticks != \"none\" )\n\t\t\t\tfor ( var i = 0; i < 60; i++ )\n\t\t\t\t{\n\t\t\t\t\tvar ang = PI2 / 60 * i;\n\t\t\t\t\tvar cos = Math.cos( ang ), sin = Math.sin( ang );\n\t\n\t\t\t\t\tcontext.beginPath();\t\t\t\t\n\t\t\t\t\tif ( ticks == \"lines\" )\n\t\t\t\t\t{\n\t\t\t\t\t\tcontext.lineWidth = 1;\n\t\t\t\t\t\tcontext.moveTo( centerX +cos * width / 2, centerY + sin * height / 2 );\n\t\t\t\t\t\tif ( i % 5 != 0 )\n\t\t\t\t\t\t\tcontext.lineTo( centerX + cos * width / 2.2, centerY + sin * height / 2.2 );\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontext.lineWidth = 2;\t\t\t\t\n\t\t\t\t\t\t\tcontext.lineTo( centerX + cos * width / 2.5, centerY + sin * height / 2.5 );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontext.stroke();\n\t\t\t\t\t}\n\t\t\t\t\telse if ( ticks == \"circles\" )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar radius = minwh / 50; \n\t\t\t\t\t\tif ( i % 5 != 0 )\n\t\t\t\t\t\t\tradius /= 2;\n\t\t\t\t\t\tcontext.fillStyle = context.strokeStyle;\n\t\t\t\t\t\tcontext.arc( centerX + Math.cos( ang ) * width / 2.3, centerY + Math.sin( ang ) * height / 2.3, radius, 0, PI2, false );\n\t\t\t\t\t\tcontext.fill();\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t// draw numerals\n\t\t\tvar numerals = canvas.getAttribute( \"data-numerals\" ) || \"none\";\n\t\t\tnumerals = numerals.toLowerCase();\n\t\t\tif ( numerals != \"none\" )\n\t\t\t{\n\t\t\t\tvar array_num = numerals == \"roman\" ? ARRAY_ROMAN : ARRAY_ARABIC;\n\t\t\t\tcontext.beginPath();\n\t\t\t\tcontext.textAlign = \"center\";\n\t\t\t\tcontext.font = minwh / 12 + \"px \" + fontFamily;\n\t\t\t\tfor ( var i = 1; i <= 12; i++ )\n\t\t\t\t{\n\t\t\t\t\tvar ang = -PI1_2 + PI2 / 12 * i;\n\t\t\t\t\tvar cos = Math.cos( ang ), sin = Math.sin( ang );\n\t\t\t\t\tcontext.save();\n\t\t\t\t\tcontext.strokeStyle = \"black\";\n\t\t\t\t\tcontext.strokeText( array_num[ i-1 ], centerX + cos * width / 2.8 + 1, centerY + sin * height / 2.8 + minwh / 30 + 1 );\n\t\t\t\t\tcontext.restore();\n\t\t\t\t\tcontext.strokeText( array_num[ i-1 ], centerX + cos * width / 2.8, centerY + sin * height / 2.8 + minwh / 30 );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// draw hour pointer\n\t\t\tcontext.beginPath();\n\t\t\tcontext.lineWidth = 4;\n\t\t\tvar ang = -Math.PI / 2 + ( timeInstance.hours % 12 ) / 12 * PI2;\n\t\t\tvar cos = Math.cos( ang ), sin = Math.sin( ang );\n\t\t\tcontext.moveTo( centerX, centerY );\n\t\t\tcontext.lineTo( centerX + width / 3 * cos, centerY + height / 3 * sin );\n\t\t\tcontext.stroke();\n\t\t\n\t\t\t// draw minute pointer\n\t\t\tcontext.beginPath();\n\t\t\tcontext.lineWidth = 2;\n\t\t\tang = -Math.PI / 2 + timeInstance.minutes / 60 * PI2;\n\t\t\tcos = Math.cos( ang ), sin = Math.sin( ang );\n\t\t\tcontext.moveTo( centerX, centerY );\n\t\t\tcontext.lineTo( centerX + width / 2.5 * cos, centerY + height / 2.5 * sin );\n\t\t\tcontext.stroke();\n\t\t\n\t\t\t// draw second pointer\n\t\t\tcontext.beginPath();\n\t\t\tcontext.lineWidth = 1;\n\t\t\tang = -Math.PI / 2 + timeInstance.seconds / 60 * PI2;\n\t\t\tcos = Math.cos( ang ), sin = Math.sin( ang );\n\t\t\tcontext.moveTo( centerX + width / -6.6 * cos, centerY + height / -6.6 * sin );\n\t\t\tcontext.lineTo( centerX + width / 2.2 * cos, centerY + height / 2.2 * sin );\n\t\t\tcontext.stroke();\n\t\t\t\n\t\t\t// draw central circle\n\t\t\tcontext.beginPath();\n\t\t\tcontext.fillStyle = context.strokeStyle;\n\t\t\tcontext.arc( centerX, centerY, minwh / 20, 0, PI2, false );\t\n\t\t\tcontext.fill();\n\t\t}", "draw() {\n this.ghosts.forEach((ghost) => ghost.draw());\n }", "draw()\n {\n var canvas = document.getElementById(\"CANVAS\");\n var ctx = canvas.getContext(\"2d\");\n var cVehicles = this.getVehicleCount();\n\n ctx.save();\n ctx.scale(def.scale, def.scale);\n\n this._drawRoute(ctx);\n for (let iVehicle = 0; iVehicle < cVehicles; iVehicle ++)\n this._drawVehicle(ctx, route.getVehicle(iVehicle));\n\n ctx.restore();\n }", "draw() {\n for (const waveform of this.waveforms) {\n this.drawInCanvas(waveform.canvas, waveform.samples);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Injects the Report Dialog script
function injectReportDialog(options) { if (options === void 0) { options = {}; } if (!global.document) { return; } if (!options.eventId) { _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error("Missing eventId option in showReportDialog call"); return; } if (!options.dsn) { _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error("Missing dsn option in showReportDialog call"); return; } var script = global.document.createElement('script'); script.async = true; script.src = new _sentry_core__WEBPACK_IMPORTED_MODULE_5__.API(options.dsn).getReportDialogEndpoint(options); if (options.onLoad) { // eslint-disable-next-line @typescript-eslint/unbound-method script.onload = options.onLoad; } var injectionPoint = global.document.head || global.document.body; if (injectionPoint) { injectionPoint.appendChild(script); } }
[ "function showReportDialog(options = {}) {\n core_1.getCurrentHub().getClient().showReportDialog(options);\n}", "function Dialog() {}", "function phpVATReport(params) {\n if (params) {\n var VATReportObject = Wtf.getCmp(params.reportID);\n if (VATReportObject == null) {\n VATReportObject = new Wtf.account.phpVATReport({\n title: Wtf.util.Format.ellipsis(params.title),\n tabTip: params.titleQtip,\n id: params.reportID,\n closable: true,\n border: false,\n params: params,\n layout: 'fit',\n iconCls: 'accountingbase receivepaymentreport'\n });\n Wtf.getCmp('as').add(VATReportObject);\n }\n Wtf.getCmp('as').setActiveTab(VATReportObject);\n Wtf.getCmp('as').doLayout();\n }\n}", "function VistaPreviaReporte() {\r\n ProcesarReporte('view',0);\r\n}", "function ReportLoad(strFilname) {\n if (strFilname != '')\n var m_WindowHandle = window.open(strFilname, 'New', 'location=no, toolbar=no, menubar=yes, resizable=yes, scrollbars=yes');\n try { m_WindowHandle.focus(); } catch (e) { }\n}", "function onReportClick(e) {\n\tcommonFunctions.sendScreenshot();\n}", "newWorkspaceDialog() {\n\t\tlet Dialog_SelectWorkspace = require(path.join(__rootdir, \"js\", \"dialogs\", \"selworkspace.js\"))\n\t\tnew Dialog_SelectWorkspace(600, \"\", (result) => {\n\t\t\tif(result === false)\n\t\t\t\treturn\n\t\t\t\n\t\t\tlet ws = wmaster.addWorkspace(result)\n\t\t\tthis.setWorkspace(ws)\n\t\t\t\n\t\t\t// display loading indicator\n\t\t\tthis.body.innerHTML = `<div class=\"abs-fill flex-col\" style=\"justify-content: center\"><div style=\"align-self: center\">...</dib></div>`\n\t\t})\n\t}", "function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}", "function printReport() {\n\n\tvar report = Banana.Report.newReport(param.reportName);\n\n\treport.addParagraph(param.title, \"heading1\");\n\treport.addParagraph(\" \");\n\treport.addParagraph(param.headerLeft + \" - \" + param.headerRight, \"heading3\");\n\treport.addParagraph(\"Periodo contabile: \" + Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"heading4\");\n\treport.addParagraph(\" \");\n\t\n\tvar table = report.addTable(\"table\");\n\ttableRow = table.addRow();\n\ttableRow.addCell(\"ID\", \"bold\", 1);\n\ttableRow.addCell(\"GRUPPO\", \"bold\", 1)\n\ttableRow.addCell(\"DESCRIZIONE\", \"bold\", 1);\n\ttableRow.addCell(\"IMPORTO\", \"bold\", 1);\n\n\tfor (var k = 0; k < form.length; k++) {\n\t\n\tif (form[k].sum) {\n\t\ttableRow = table.addRow();\n\t\ttableRow.addCell(form[k].id, \"bold\", 1);\n\t\ttableRow.addCell(form[k].gr, \"bold\", 1);\n\t\ttableRow.addCell(form[k].description, \"bold\", 1);\n\t\ttableRow.addCell(getBalance(form[k].gr), \"alignRight bold\", 1);\n\t} else {\n\t\ttableRow = table.addRow();\n\t\ttableRow.addCell(form[k].id, \"\", 1);\n\t\ttableRow.addCell(form[k].gr, \"\", 1);\n\t\ttableRow.addCell(form[k].description, \"\", 1);\n\t\ttableRow.addCell(getBalance(form[k].gr), \"alignRight\", 1);\n\t\t}\n\t}\n\n\t//Add the footer to the report\n\taddFooter(report)\n\n\t//Print the report\n\tvar stylesheet = createStyleSheet();\n\tBanana.Report.preview(report, stylesheet);\n}", "function processSaveReport(){\n var ContentFrame = findFrame(getTopWindow(),\"metricsReportContent\");\n if (ContentFrame.validateReport()){\n var footerFrame = $bmId('divPageFoot');\n pageControl.setWrapColSize(footerFrame.children[0].WrapColSize.value);\n if(pageControl.getSavedReportName() == \"\" || pageControl.getSavedReportName() == \"open .last\"){\n showModalDialog(\"emxMetricsSaveDialog.jsp\", 400, 225,true);\n }\n else if(pageControl.getOpenedLast())\n {\n showModalDialog(\"emxMetricsSaveDialog.jsp\", 400, 225,true);\n }else{\n if(confirm(STR_METRICS_SAVE_REPORT_MSG))\n {\n var result = saveReport(pageControl.getSavedReportName(),pageControl.getResultsTitle(), \"updateNotes\",\"criteriaUpdate\",pageControl.getSavedReportName());\n var hiddenFrame = findFrame(getTopWindow(),\"metricsReportHidden\");\n hiddenFrame.document.write(result);\n }\n }\n }\n}", "function filterPopUp(){\n\t$(\"#divAlert\").dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: width - 200,\n\t\tmaxHeight: 700\n\t});\n\tif(enDisFilter == true){\n\t\t$(\"#divAlert\").load(\"pages/ConfigEditor/Filter.html\",function(){\n\t\t\tinitDynamicFilterValue();\n\t\t});\n\t}\n}", "function open_export_dialog(event) {\n var id = this.dom.table.id + \"-export-dialog\";\n var modal = $(\"#\" + id);\n var amount = $(\".active\", this.dom.table).length;\n\n if (amount === 0) {\n // No rows selected: we're exporting all items.\n amount = $(this.dom.table).DataTable().page.info().recordsTotal;\n }\n\n $(\"[name=page_size]\", modal).attr(\"max\", amount).val(amount);\n $(\".num_items\", modal).text(amount);\n\n var data = {\n format: $(\"[name=format]\", modal),\n page_size: $(\"[name=page_size]\", modal),\n filename: $(\"[name=filename]\", modal),\n task: false,\n modal: modal,\n table: $(this.dom.table)\n };\n\n $(\"[name=export]\", modal).unbind().click(export_clicked.bind(data));\n $(\"select\", modal).unbind().change(function () {\n if (this.options[this.selectedIndex].value === \"spss\") {\n $(\".spss-warning\").removeClass(\"hide\");\n } else {\n $(\".spss-warning\").addClass(\"hide\");\n }\n });\n\n modal.modal();\n }", "function chooseFunctionAccordingToReport() {\r\n if (selectedReport == \"Severity\") {\r\n severityReport();\r\n }\r\n else if (selectedReport == \"Status\") {\r\n statusReport();\r\n }\r\n else if (selectedReport == \"Assignee\") {\r\n assigneeReport();\r\n }\r\n else {\r\n individualReport(selectedReport);\r\n }\r\n}", "function showReportBrokenLink (\tobj, form_name, reportingIntro, reportingEmail, labelEmail, labelNote, report, Close, errorEmailAddress, errorNoteNoEmailAddress, lang, instance) {\n\t \tvar reportWindow = document.getElementById('ReportWindow');\n\t \tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'inline');\n\t\tif (reportWindow == null) { \n\t\t\tvar txt = \t'<div id=\"ReportWindow\" ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += ' class=\"ExlRightBrokenLinkPopUp\"> '; } else { txt += ' class=\"ExlBrokenLinkPopUp\"> '; }\n\t\t\t\ttxt += \t'<div class=\"ExlRightDivBL\">' +\n\t\t\t\t\t\t'<a href=\"javascript:closeReportWindow();\" class=\"ExlCloseBL\" > ' +\n\t\t\t\t\t\t'<img src=\"/'+instance+'/img/express/darken_v-ico_close.gif\" width=\"16\" height=\"16\" border=\"0\" alt=' +Close+ ' title=' +Close+ '></a>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div id=\"ReportingIntro\" tabIndex=\"0\" >'+ reportingIntro + '<br /><br />' + reportingEmail + '<br /><br /></div>' +\n\t\t\t\t\t\t'<div class=\"ExlInputDivBL\" >' +\n\t\t\t\t\t\t'<label for=\"id_e-mail\" ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += ' class=\"ExlRightLabelBL\"> '; } else { txt += ' class=\"ExlLeftLabelBL\"> '; }\n\t\t\t\ttxt += \tlabelEmail+ ' </label>' +\n\t\t\t\t\t\t'<input name=\"e-mail_value\" id=\"id_e-mail\" class=\"ExlInputBL\" ></input>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div class=\"ExlInputDivBL\">' +\n\t\t\t\t\t\t'<label for=\"id_client_note\" ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += ' class=\"ExlRightLabelBL\"> '; } else { txt += ' class=\"ExlLeftLabelBL\"> '; }\n\t\t\t\ttxt += \tlabelNote+ ' </label>' + \n\t\t\t\t\t\t'<input name=\"note_value\" id=\"id_client_note\" class=\"ExlInputBL\" ></input>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div id=\"error_div\" tabIndex=\"0\" class=\"ExlErrorDivBL\" >' + \n\t\t\t\t\t\t'<label id=\"report_error1\" class=\"ExlErrorLabelBL\" >' +errorEmailAddress+ '</label>' +\n\t\t\t\t\t\t'<label id=\"report_error2\" class=\"ExlErrorLabelBL\" >' +errorNoteNoEmailAddress+ '</label>' +\n\t\t\t\t\t\t'</div><br />' +\n\t\t\t\t\t\t'<div ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += 'class=\"ExlLeftReportDiv\"> '; } else { txt += 'class=\"ExlRightReportDiv\"> '; }\n\t\t\t\ttxt += \t'<label id=\"report_label\" title=' +report+ '>' +\n\t\t\t\t\t\t'<a href=\"#\" id=\"reportLink\" onclick=\"clickReportBrokenLink (this, \\''+form_name+'\\');\" class=\"ExlReportBL\" >[' +report+ ']</a>' +\n\t\t\t\t\t\t'</label>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'</div>';\n\t\t var body = document.getElementsByTagName('body');\n\t\t document.body.innerHTML += txt;\n\t\t}else {\n\t\t\tdocument.getElementById('reportLink').setAttribute(\"onclick\",\"clickReportBrokenLink (this, '\"+form_name+\"')\");\n\t\t\tdocument.getElementById('id_e-mail').value = '';\n\t\t\tdocument.getElementById('id_client_note').value = '';\n\t\t\tset_element_display_by_id_safe('error_div', 'none');\n\t\t}\t\t\n\t\tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'none');\t\n\t\tset_element_display_by_id_safe('ReportWindow', 'inline');\n\t \tdocument.getElementById(\"ReportingIntro\").focus();\t\t\n}", "function showScriptPreviewFromFlex(url, label, jobHash) {\n // add preview image tag\n $('#logPopup').html('<img/>');\n\n // set onload handler\n $(\"#logPopup img\").error(function() {\n alert(\"The preview is not provided for \"+label+'.');\n }).one('load', function() {\n $('#logPopup').dialog('option', 'height', this.height+50);\n $('#logPopup').dialog('option', 'width', this.width+25);\n $('#logPopup').dialog('option', 'title', \"Script Preview (\"+label+\")\");\n $('#logPopup').dialog('open');\n });\n\n // set src and start loading\n $('#logPopup img').attr('src', url);\n}", "function portTablePopUp(){\n\t$( \"#testToolPopUp\" ).dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"auto\",\n\t\tmaxHeight: 500\n\t});\n\t$( \"#testToolPopUp\" ).load('pages/ConfigEditor/PortTestTool.html',function(){\n\t\t//deviceListPopupTable('deviceMenu','local');\n\t\t$('#PortTitle').text(HostName);\t\n\t\tsetTimeout(function(){\n\t\t\tPortTestToolTable();\n\t\t},100);\n\n\t\t$(\".ui-dialog\").position({\n\t\t my: \"center\",\n\t\t at: \"center\",\n\t\t of: window\n\t\t});\n\t});\n}", "function reportePagos(){\n //se obtiene el valor elegido del combobox\n let pago = $('#tipoPago').val(); \n //abre el reporte en otra pagina y manda a llamar el dato del combobox\n window.open('../../core/reportes/ventasPago1.php?pago='+pago);\n}", "function lpDialog() {\n\tSpreadsheetApp.getUi().showModalDialog(\n\t\tgenerateDialog('Views/lpDialogPage.html'),\n\t\t'Select GMail Label to Pull Data From:'\n\t);\n}", "function reportTemplate(id,username,date_time,report,operaVersion,operaBuildNumber,OS,domain,page,isComment){\n var content='';\n // parent element that specifies a list element is created\n content=\"<article><h6><a href='?mode=get_comment_list&include_report=true&user=\"+username+\"'>\"+username+\"</a> said on \"+date_time+\":</h6><div class='tools'>\";\n if(!isComment)\n // go button is created\n content+=\"<a href='?mode=get_comment&id=\"+id+\"' data-id=\"+id+\" class='go-button'> &gt; </a>\";\n // follow button is created\n content+=\"<a href='?mode=follow&id=\"+id+\"' data-id=\"+id+\" class='follow-button'> follow </a>\";\n // like button is created\n content+=\"<a href='?mode=like&id=\"+id+\"' data-id=\"+id+\" class='like-button'> like </a></div><p>\";\n // additional information area for list element is created \n content+=report+\"</p><span class='small'><a href=\"+page+\" target='_blank' title=\\\"\" + page + \"\\\">\"+(page.length > 40 ? page.substr(0, 40) + '...' : page)+\"</a> on \"+domain+\"</a><span class='additional-information'>\"+operaVersion+\".\"+operaBuildNumber+\" on \"+OS+\"</span></article>\";\n return content;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for mapping content of success story
function successStoryContentMapping(successStoryData) { var mapping = { '{title}': "Success Stories", '{successStories}': removeNull(successStoryData) }; return mapping; }
[ "function loadSuccessStoryTuples(response)\n{\n var tupleStructure = $(\"#successStoryBasicdiv\").html(),ssTupleHtml=\"\",contentHtml=\"\",mapObj=\"\";\n var mainContentStructure = $(\"#successStoryMainStructure\").html();\n var tupleNo;\n $.each(response.stories,function( key, val ){\n tupleNo = key +1;\n mapObj = successStoryBasicTupleMapping(val,tupleNo);\n ssTupleHtml+ = $.ReplaceJsVars(tupleStructure,mapObj);\n });\n if(ssTupleHtml)\n {\n mapObj = successStoryContentMapping(ssTupleHtml);\n contentHtml = $.ReplaceJsVars(mainContentStructure,mapObj);\n if(contentHtml)\n {\n $(\"#successStoryMaindiv\").append(contentHtml);\n }\n }\n //align images to container\n alignSuccessStoryImages();\n}", "function successStoryBasicTupleMapping(val,tupleNo)\n{\n var mapping = {\n 'data=\"{picUrl}\"': \"src='\"+removeNull(val.vspSSPicUrl)+\"'\",\n '{name1}': removeNull(val.NAME1),\n '{name2}': removeNull(val.NAME2),\n '{vspSuccessImgClass}':\"vspSuccessImgCover\",\n '{storyTuple}': \"story\"+tupleNo,\n '{year}':removeNull(val.YEAR),\n '{sid}':removeNull(val.SID)\n };\n return mapping;\n}", "function getStory() {\n return story;\n}", "convertStory(story){\n if(story.media.length === 1) return [{\n ...story,\n orderNum: 1, // Important for our custom slider component \n }]\n \n const stories = [];\n story.media.forEach(singleMedia => {\n singleMedia.orderNum = 1; // Important for our custom slider component\n stories.push({\n ...story,\n media: [singleMedia] // Must be an array\n })\n })\n\n return stories;\n }", "function writeStory(){\n var docElem2 = document.getElementById(\"cardstory\");\n clearCard(docElem2);\n var newName = document.createElement('p');\n\n var newTxt = document.createTextNode(characters.story.shift());\n newName.appendChild(newTxt);\n docElem2.appendChild(newName);\n}", "createClassGroupContent(mapFNameToContent, links, projectDetail, mapGroupNameToClassGroup) {\n const constants = new Constants();\n let mapGroupNameToClassGroupKeysArray = Array.from(mapGroupNameToClassGroup.keys());\n mapGroupNameToClassGroupKeysArray.forEach((strGroup) => {\n let cg = mapGroupNameToClassGroup.get(strGroup);\n if (cg.getContentSource()) {\n let cgContent = this.parseHTMLFile(cg.getContentSource());\n if (cgContent) {\n let strHtml = constants.getHeader(projectDetail) + links + \"<td class='contentTD'>\" +\n \"<h2 class='section-title'>\" +\n this.escapeHTML(cg.getName()) + \"</h2>\" + cgContent + \"</td>\";\n strHtml += constants.FOOTER;\n mapFNameToContent.set(cg.getContentFilename(), strHtml);\n }\n }\n });\n }", "formatWikiData(response) {\n let len = response[1].length;\n let data = [];\n for (let m = 0; m < len; m++) {\n data.push({});\n }\n for(let index = 0; index < response.length; index++) {\n let section = response[index];\n switch (index) {\n case 1:\n for (let i = 0; i < len; i++) {\n data[i].title = section[i];\n }\n // console.log(section);\n break;\n case 2:\n for (let j = 0; j < len; j++) {\n data[j].snippet = section[j];\n }\n // console.log(section);\n break;\n case 3:\n for (let k = 0; k < len; k++) {\n data[k].url = section[k];\n }\n // console.log(section);\n break;\n default:\n //skip any thing else\n }\n }\n // console.log(data);\n return data;\n }", "async function transformToTLJson() {\n var timelineJson = {}\n timelineJson.events = [];\n // list of slide objects (each slide is an event)\n\n //wikiDate is in iso-8601 format \n function parseDate(wikiDate) {\n var wdate = new Date(wikiDate);\n\n return {\n year: wdate.getUTCFullYear(),\n month: wdate.getUTCMonth(),\n day: wdate.getUTCDate(),\n hour: wdate.getUTCHours(),\n minute: wdate.getUTCMinutes(),\n second: wdate.getUTCSeconds(),\n display_date: `Date of discovery: ${wdate.getUTCFullYear()}`\n };\n\n }\n\n function newSlide(wikiElement) {\n var slide = {};\n\n if (wikiElement.dateOfDiscovery) {\n if (wikiElement.dateOfDiscovery.startsWith('-')) {\n let year = wikiElement.dateOfDiscovery.match(/(-\\d+)-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z/);\n if (year) {\n slide.start_date = {\n year: year[1]\n };\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n } else {\n slide.start_date = parseDate(wikiElement.dateOfDiscovery);\n if (isNaN(slide.start_date.year)) {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n }\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n\n slide.text = {\n headline: ` <a href=\"${wikiElement.elementWikiUrl}\">${wikiElement.elementLabel}</a>`,\n text: createTable(selectTableData(wikiElement))\n };\n\n slide.media = {\n url: wikiElement.elementWikiUrl,\n thumbnail: wikiElement.picture\n };\n slide.unique_id = \"a\" + wikiElement.anum;\n slide.autolink = false;\n return slide;\n }\n\n var wikiData = await getData();\n for (var ekey in wikiData) {\n timelineJson.events.push(newSlide(wikiData[ekey]));\n }\n return timelineJson;\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}", "wiki(title, elClass = \"wiki\"){\r\n const url = `https://en.wikipedia.org/w/api.php?action=query&titles=${title}&prop=extracts&explaintext=1&exintro&exlimit=2&format=json&formatversion=2&origin=*`;\r\n fetch(url)\r\n .then(data => data.json())\r\n .then(function (data){\r\n const wikiNodes = document.getElementsByClassName(elClass);\r\n //iterate over HTMLCollection javascript https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements\r\n [].forEach.call(wikiNodes, function(wikiNode) {\r\n wikiNode.innerHTML = data.query.pages[0].extract\r\n });\r\n // alert(data.query.pages[0].extract)\r\n console.log(data)\r\n return true\r\n })\r\n .catch(function(err){\r\n alert('Error on Loadin Wikipedia data')\r\n return false}); \r\n\r\n\r\n \r\n}", "function map(html, url, page){\n\t\n\tif(page === \"none\" || !page){\n\t\treturn \"hollahoop\";\n\t} else if(page === \"ajax\"){\n\t\treturn JSON.parse(html);\n\t}\n\t\n\tlet $html = $(html);\n\tif(page === \"unitlist\"){\n\t\treturn {\n\t\t\tsubids : $html.find(\".unit-list-2014 td:nth-child(1):not(.u-ed)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\ttype: $html.find(\".unit-list-2014 td:nth-child(3)\").map( (i, e) => $(e).attr(\"class\").split(\"-\")[1] ).get(),\n\t\t\tcountry: $html.find(\".unit-list-2014 td:nth-child(2):not(.u-n)\").map( (i, e) => $(e).attr(\"class\").split(\"-\")[1] ).get(),\n\t\t\tcity: $html.find(\".unit-list-2014 td:nth-child(2):not(.u-n)\").map( (i, e) => $(e).text().trim() ).get(),\n\t\t\tname: $html.find(\".unit-list-2014 td:nth-child(3) a\").map( (i, e) => $(e).text().trim() ).get(),\n\t\t\talert: $html.find(\".unit-list-2014 td:nth-child(8)\").map( (i, e) => $(e).html().replace(/\\s{2,}/g, \"\") ).get(),\n\t\t}\n\t} \n\telse if(page === \"main\"){\n\t\treturn {\n\t\t\temployees : numberfy($html.find(\".unit_box:has(.fa-users) tr:eq(0) td:eq(1)\").text()),\n\t\t\tsalaryNow : numberfy($html.find(\".unit_box:has(.fa-users) tr:eq(2) td:eq(1)\").text()),\n\t\t\tsalaryCity : numberfy($html.find(\".unit_box:has(.fa-users) tr:eq(3) td:eq(1)\").text()),\n\t\t skillNow : numberfy($html.find(\".unit_box:has(.fa-users) tr:eq(4) td:eq(1)\").text()),\n\t\t\tskillReq : numberfy($html.find(\".unit_box:has(.fa-users) tr:eq(5) td:eq(1)\").text()),\n\t\t\tequipNum : numberfy($html.find(\".unit_box:has(.fa-cogs) tr:eq(0) td:eq(1)\").text()),\n\t\t\tequipMax : numberfy($html.find(\".unit_box:has(.fa-cogs) tr:eq(1) td:eq(1)\").text()),\n\t\t\tequipQual : numberfy($html.find(\".unit_box:has(.fa-cogs) tr:eq(2) td:eq(1)\").text()),\n\t\t\tequipReq : numberfy($html.find(\".unit_box:has(.fa-cogs) tr:eq(3) td:eq(1)\").text()),\n\t\t\tequipWearBlack : numberfy($html.find(\".unit_box:has(.fa-cogs) tr:eq(4) td:eq(1)\").text().split(\"(\")[1]),\n\t\t\tequipWearRed : $html.find(\".unit_box:has(.fa-cogs) tr:eq(4) td:eq(1) span\").length === 1,\n\t\t\tmanagerPic : $html.find(\".unit_box:has(.fa-user) ul img\").attr(\"src\"),\n\t\t\tqual : numberfy($html.find(\".unit_box:has(.fa-user) tr:eq(1) td:eq(1)\").text()),\n\t\t\ttechLevel : numberfy($html.find(\".unit_box:has(.fa-industry) tr:eq(3) td:eq(1)\").text()),\n\t\t\tmaxEmployees : numberfy($html.find(\".unit_box:has(.fa-user) tr:eq(2) td:eq(1)\").text()),\n\t\t\timg : $html.find(\"#unitImage img\").attr(\"src\").split(\"/\")[4].split(\"_\")[0],\n\t\t\tsize : numberfy($html.find(\"#unitImage img\").attr(\"src\").split(\"_\")[1]),\n\t\t\thasBooster : !$html.find(\"[src='/img/artefact/icons/color/production.gif']\").length,\n\t\t\tonHoliday : !!$html.find(\"[href$=unset]\").length,\n\t\t\tisStore : !!$html.find(\"[href$=trading_hall]\").length,\n\t\t\tdepartments : numberfy($html.find(\"tr:contains('Number of departments') td:eq(1)\").text()),\n\t\t\tvisitors: numberfy($html.find(\"tr:contains('Number of visitors') td:eq(1)\").text()),\n\t\t}\n\t}\n\telse if(page === \"sale\"){ \n\t\treturn {\n\t\t\tpolicy : $html.find(\"select:even\").map( (i, e) => $(e).find(\"[selected]\").index() ).get(),\n\t\t\tprice : $html.find(\"input.money:even\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\toutqual : $html.find(\"td:has('table'):nth-last-child(6) tr:nth-child(2) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\toutprime : $html.find(\"td:has('table'):nth-last-child(6) tr:nth-child(3) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tstockqual : $html.find(\"td:has('table'):nth-last-child(5) tr:nth-child(2) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tstockprime : $html.find(\"td:has('table'):nth-last-child(5) tr:nth-child(3) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tproduct : $html.find(\".grid a:not([onclick])\").map( (i, e) => $(e).text() ).get(),\n\t\t\tproductId : $html.find(\".grid a:not([onclick])\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\tproductData : $html.find(\"input.money:even\").map( (i, e) => $(e).attr(\"name\").split(\"][\")[0]+\"]\" ).get(),\n\t\t\tvolume : $html.find(\"input.money:odd\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tconstraint : $html.find(\"select\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tregion : $html.find(\".officePlace a:eq(-2)\").text(),\n\t\t\tcontractpage : !!$html.find(\".tabsub\").length,\n\t\t\tcontractprice : ($html.find(\"script:contains(mm_Msg)\").text().match(/(\\$(\\d|\\.| )+)|(\\[\\'name\\'\\]\t\t= \\\"[a-zA-Zа-яА-ЯёЁ ]+\\\")/g) || []).map((e) => e[0] === \"[\"? e.slice(13, -1) : numberfy(e) )\n\t\t}\n\t} \n\telse if(page === \"salecontract\"){ \n\t\treturn {\n\t\t\tcategory : $html.find(\"#productsHereDiv a\").map( (i, e) => $(e).attr(\"href\") ).get(),\n\t\t\tcontractprice : ($html.find(\"script:contains(mm_Msg)\").text().match(/(\\$(\\d|\\.| )+)|(\\[\\'name\\'\\]\t\t= \\\"[a-zA-Zа-яА-ЯёЁ ]+\\\")/g) || []).map( (e) => e[0] === \"[\"? e.slice(13, -1) : numberfy(e) )\n\t\t}\n\t}\n\telse if(page === \"prodsupply\"){\n\t\treturn $html.find(\".inner_table\").length? { //new interface\n\t\t\tparcel : $html.find(\".quickchange\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\trequired : $html.find(\".list td:nth-child(3).inner_table tr:nth-child(1) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tstock : $html.find(\".list td:nth-child(4).inner_table tr:nth-child(1) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tbasequality : $html.find(\".list td:nth-child(4).inner_table tr:nth-child(2) td:nth-child(2)[align]\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tprodid : $html.find(\".list tr:has([src='/img/supplier_add.gif']) > td:nth-child(1) a\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\toffer : $html.find(\".destroy\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tprice : $html.find(\".list tr[onmouseover] table:has(a) tr:nth-child(2) td:nth-child(3)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tquality : $html.find(\".list tr[onmouseover] table:has(a) tr:nth-child(3) td:nth-child(3)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tavailable : $html.find(\".list tr[onmouseover] table:has(a) tr:nth-child(4) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tmaximum : $html.find(\".list td:has(.quicksave)\").map( (i, e) => $(e).find(\"[style='color: red;']\").length? numberfy($(e).find(\"[style='color: red;']\").text().match(/(\\d|\\s)+/)[0]) : Infinity ).get(),\n\t\t\treprice : $html.find(\".list tr[onmouseover] table:has(a) tr:nth-child(2)\").map( (i, e) => !!$(e).filter(\".ordered_red, .ordered_green\").length ).get(),\n\t\t\tmainrow : $html.find(\".list tr[onmouseover]\").map( (i, e) => !!$(e).find(\"[alt='Select supplier']\").length ).get(),\n\t\t\tnosupplier : $html.find(\".list tr[onmouseover]\").map( (i, e) => !$(e).find(\"[src='/img/smallX.gif']\").length ).get(),\n\t\t\timg : $html.find(\"#unitImage img\").attr(\"src\").split(\"/\")[4].split(\"_\")[0]\n\t\t} : { //old interface\n\t\t\tparcel : $html.find(\"input[type=type]\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\trequired : $html.find(\".list td:nth-child(2) table tr:nth-child(1) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tstock : $html.find(\".list td:nth-child(3) table tr:nth-child(1) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tbasequality : $html.find(\".list td:nth-child(3) table tr:nth-child(2) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tprodid : $html.find(\".list a:has(img)[title]\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\toffer : $html.find(\".destroy\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tprice : $html.find(\"[id^=totalPrice] tr:nth-child(1) td:nth-child(3)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tquality : $html.find(\"[id^=totalPrice] tr:nth-child(3) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tavailable : $html.find(\"[id^=quantity] tr:nth-child(2) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tmaximum : $html.find(\".list td:has([type=type])\").map( (i, e) => $(e).find(\"[style='color:red']\").length? numberfy($(e).find(\"[style='color:red']\").text().match(/(\\d|\\s)+/)[0]) : Infinity ).get(),\n\t\t\treprice : $html.find(\"[id^=totalPrice] tr:nth-child(1)\").map( (i, e) => !!$(e).filter(\"[style]\").length ).get(),\n\t\t\tmainrow : $html.find(\".list tr[id]\").map( (i, e) => !/sub/.test($(e).attr(\"id\")) ).get(),\n\t\t\tnosupplier : $html.find(\".list tr[id]\").map( (i, e) => !$(e).find(\"[src='/img/smallX.gif']\").length ).get(),\n\t\t\timg : $html.find(\"#unitImage img\").attr(\"src\").split(\"/\")[4].split(\"_\")[0]\n\t\t}\t\t\n\t}\n\telse if(page === \"manufacture\"){\n\t\treturn $html.find(\".unit_box:has('.fa-certificate')\").length ? { //new interface\n\t\t\t bonuses : $html.find(\".unit_box:has('.fa-certificate') .mainHintPanel :gt(1)\").map( (i, e) => numberfy($(e).text().match(/(\\+|\\-)\\s(\\d|\\.)+/)[0]) ).get()\n\t\t } : { //old interface\n\t\t\t bonuses : []\n\t\t }\t\t\n\t}\n\telse if(page === \"consume\"){\n\t\treturn {\n\t\t\tconsump : $html.find(\".list td:nth-last-child(1) div:nth-child(1)\").map( (i, e) => numberfy($(e).text().split(\":\")[1]) ).get()\n\t\t}\n\t}\n\telse if(page === \"traderef\"){\n\t\treturn {\n\t\t\titem : $html.find(\".list a:has(img)\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\tdepartment : $html.find(\".list a:has(img)\").map( (i, e) => $(e).parents(\"tr\").prevUntil(\":not([class])\").andSelf().prev().filter(\":not([class])\").text().trim() ).get()\n\t\t}\n\t}\n\telse if(page === \"citymarket\"){\n\t\treturn {\n\t\t\titem : $html.find(\".grid tr[class] td a\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\tlocalprice : $html.find(\"td:nth-child(5)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tlocalquality : $html.find(\"td:nth-child(6)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"storesupply\"){\n\t\treturn {\n\t\t\tparcel : $html.find(\"input:text[name^='supplyContractData[party_quantity]']\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tpurchase : $html.find(\"td.nowrap:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tquantity : $html.find(\"td:nth-child(2) table:nth-child(1) tr:nth-child(1) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tsold : $html.find(\"td:nth-child(2) table:nth-child(1) tr:nth-child(5) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\toffer : $html.find(\".destroy\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tavailable : $html.find(\"td:nth-last-child(2) tr:nth-child(3) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tmax : $html.find(\"tr:has(.destroy)\").map( (i, e) => numberfy($(e).find(\"span[style='color:red']\").text().split(\": \")[1]) || Infinity ).get(),\n\t\t\tprice : $html.find(\"td:nth-last-child(3) tr:nth-child(1) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\treprice : $html.find(\"td:nth-last-child(3) tr:nth-child(1) td:nth-child(2)\").map( (i, e) => !!$(e).find(\"div\").length ).get(),\n\t\t\tquality : $html.find(\"td:nth-last-child(3) tr:nth-child(2) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tbrand : $html.find(\"td:nth-last-child(3) tr:nth-child(3) td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\timg : $html.find(\".noborder td > img\").map( (i, e) => $(e).attr(\"src\") ).get(),\n\t\t\titem : $html.find(\".noborder tr:nth-child(1) a\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/g)[2]) ).get(),\n\t\t\tsupplier : $html.find(\".noborder tr:nth-child(1) a\").map( (i, e) => $(e).attr(\"href\") ).get(),\n\t\t\tsubrow : $html.find(\"tr:has(.destroy)\").map( (i, e) => $(e).hasClass(\"sub_row\") ).get(),\n\t\t\ttitle : $html.find(\".title\").map( (i, e) => $(e).text() ).get()\n\t\t}\n\t}\n\telse if(page === \"tradehall\"){\n\t\treturn {\n\t\t\tsold : $html.find(\".nowrap:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tstock : $html.find(\".nowrap:nth-child(6)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tdeliver : $html.find(\".nowrap:nth-child(5)\").map( (i, e) => numberfy($(e).text().split(\"[\")[1]) ).get(),\n\t\t\treport : $html.find(\".grid a:has(img):not(:has(img[alt]))\").map( (i, e) => $(e).attr(\"href\") ).get(),\n\t\t\timg : $html.find(\".grid a img:not([alt])\").map( (i, e) => $(e).attr(\"src\") ).get(),\n\t\t\tquality : $html.find(\"td:nth-child(7)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tpurch : $html.find(\"td:nth-child(9)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tprice : $html.find(\":text\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tname : $html.find(\":text\").map( (i, e) => $(e).attr(\"name\") ).get(),\n\t\t\tshare : $html.find(\".nowrap:nth-child(11)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tcityprice : $html.find(\"td:nth-child(12)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tcityquality : $html.find(\"td:nth-child(13)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\thistory : $html.find(\"a.popup\").map( (i, e) => $(e).attr(\"href\") ).get(),\n\t\t\titemid : $html.find(\".grid a:has(img):not(:has(img[alt]))\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get()\n\t\t}\n\t}\n\telse if(page === \"retailreport\"){\n\t\treturn {\n\t\t\tmarketsize : numberfy($html.find(\"b:eq(1)\").text()),\n\t\t\tlocalprice : numberfy($html.find(\".grid .even td:eq(0)\").text()),\n\t\t\tlocalquality : numberfy($html.find(\".grid .odd td:eq(0)\").text()),\n\t\t\tcityprice : numberfy($html.find(\".grid .even td:eq(1)\").text()),\n\t\t\tcityquality : numberfy($html.find(\".grid .odd td:eq(1)\").text())\n\t\t}\n\t}\n\telse if(page === \"pricehistory\"){\n\t\treturn {\n\t\t\tquantity : $html.find(\".list td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tprice : $html.find(\".list td:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"TM\"){\n\t\treturn {\n\t\t\tproduct : $html.find(\".grid td:odd\").map( (i, e) => $(e).clone().children().remove().end().text().trim() ).get(),\n\t\t\tfranchise : $html.find(\".grid b\").map( (i, e) => $(e).text() ).get()\n\t\t}\n\t}\n\telse if(page === \"IP\"){\n\t\treturn {\n\t\t\tproduct : $html.find(\".list td:nth-child(5n-3)\").map( (i, e) => $(e).text() ).get(),\n\t\t\tIP : $html.find(\".list td:nth-child(5n)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"transport\"){\n\t\treturn {\n\t\t\tcountryName : $html.find(\"select:eq(0) option\").map( (i, e) => $(e).text() ).get(),\n\t\t\tcountryId : $html.find(\"select:eq(0) option\").map( (i, e) => numberfy($(e).val().split(\"/\")[1]) ).get(),\n\t\t\tregionName : $html.find(\"select:eq(1) option\").map( (i, e) => $(e).text() ).get(),\n\t\t\tregionId : $html.find(\"select:eq(1) option\").map( (i, e) => numberfy($(e).val().split(\"/\")[2]) ).get(),\n\t\t\tcityName : $html.find(\"select:eq(2) option\").map( (i, e) => $(e).text() ).get(),\n\t\t\tcityId : $html.find(\"select:eq(2) option\").map( (i, e) => numberfy($(e).val().split(\"/\")[3]) ).get()\t\t\t\n\t\t}\n\t}\n\telse if(page === \"CTIE\"){\n\t\treturn {\n\t\t\tproduct : $html.find(\".list td:nth-child(3n-1)\").map( (i, e) => $(e).text() ).get(),\n\t\t\tprofitTax : numberfy($html.find(\".region_data td:eq(3)\").text()),\n\t\t\tCTIE : $html.find(\".list td:nth-child(3n)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"salary\"){\n\t\treturn {\n\t\t\temployees : numberfy($html.find(\"#quantity\").val()),\n\t\t\tform : $html.filter(\"form\"),\n\t\t\tsalaryNow : numberfy($html.find(\"#salary\").val()),\n\t\t\tsalaryCity : numberfy($html.find(\"tr:nth-child(3) > td\").text().split(\"$\")[1]),\n\t\t\tskillNow : numberfy($html.find(\"#apprisedEmployeeLevel\").text()),\n\t\t\tskillCity : numberfy($html.find(\"div span[id]:eq(1)\").text().match(/[0-9]+(\\.[0-9]+)?/)[0]),\n\t\t\tskillReq : numberfy($html.find(\"div span[id]:eq(1)\").text().split(\",\")[1].match(/(\\d|\\.)+/))\t\n\t\t}\t\n\t}\t\n\telse if(page === \"training\"){\n\t\treturn {\n\t\t\tform : $html.filter(\"form\"),\n\t\t\tsalaryNow : numberfy($html.find(\".list td:eq(8)\").text()),\n\t\t\tsalaryCity : numberfy($html.find(\".list td:eq(9)\").text().split(\"$\")[1]),\n\t\t\tweekcost : numberfy($html.find(\"#educationCost\").text()),\n\t\t\temployees : numberfy($html.find(\"#unitEmployeesData_employees\").val()),\t\n\t\t\tskillNow : numberfy($html.find(\".list span:eq(0)\").text()),\t\t\t\n\t\t\tskillCity : numberfy($html.find(\".list span:eq(1)\").text()),\n\t\t}\t\n\t}\n\telse if(page === \"equipment\"){\n\t\treturn {\n\t\t\tqualNow : numberfy($html.find(\"#top_right_quality\").text()),\n\t\t\tqualReq : numberfy($html.find(\".recommended_quality span:not([id])\").text()),\n\t\t\tequipNum : numberfy($html.find(\"#quantity_corner\").text()),\n\t\t\tequipMax : numberfy($html.find(\".contract:eq(1)\").text().split(\"(\")[1].match(/(\\d| )+/)[0]),\n\t\t\tequipPerc : numberfy($html.find(\"#wear\").text()),\n\t\t\tprice : $html.find(\".digits:contains($):odd:odd\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tqualOffer : $html.find(\".digits:not(:contains($)):odd\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tavailable : $html.find(\".digits:not(:contains($)):even\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\toffer : $html.find(\".choose span\").map( (i, e) => numberfy($(e).attr(\"id\")) ).get(),\n\t\t\timg : $html.find(\".rightImg\").attr(\"src\"),\n\t\t\tfiltername : $html.find(\"[name=doFilterForm]\").attr(\"action\").match(/db.*?\\//)[0].slice(2, -1)\n\t\t}\n\t}\n\telse if(page === \"manager\"){\n\t\treturn {\n\t\t\tbase : $html.find(\".qual_item .mainValue\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tbonus : $html.find(\".qual_item\").map( (i, e) => numberfy($(e).find(\".bonusValue\").text()) ).get(),\n\t\t\tpic : $html.find(\".qual_item img\").map( (i, e) => $(e).attr(\"src\") ).get()\n\t\t}\n\t}\n\telse if(page === \"tech\"){ \n\t\treturn $html.find(\".rounded-table\").length? {\n\t\t\tcurlevel : numberfy($html.find(\".rounded-table .current_row .level_field\").text().match(/\\d+/)[0]),\n\t\t\tlevel : $html.find(\".rounded-table .level_field\").map( (i, e) => numberfy($(e).text().match(/\\d+/)[0]) ),\n\t\t\tyours : $html.find(\".rounded-table tr:has(.level_field)\").map( (i, e) => !$(e).find(\".small_button\").length ),\n\t\t\timg : $html.find(\"#unitImage img\").attr(\"src\").split(\"/\")[4].split(\"_\")[0]\n\t\t} :\t{\n\t\t\tcurlevel : numberfy($html.find(\".list tr.disabled div:eq(0)\").text().match(/\\d+/)[0]),\n\t\t\tlevel : $html.find(\".list td:nth-child(1)\").map( (i, e) => numberfy($(e).text().match(/\\d+/)[0]) ).get(),\n\t\t\tyours : $html.find(\"tr td.nowrap:nth-child(2)\").map( (i, e) => !numberfy($(e).text()) ).get(),\n\t\t\timg : $html.find(\"#unitImage img\").attr(\"src\").split(\"/\")[4].split(\"_\")[0]\n\t\t};\n\t}\t\n\telse if(page === \"techlist\"){\n\t\treturn {\n\t\t\tsubid : $html.find(\".list_sublink:not([style])\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0] ) ).get(),\n\t\t\tlevel : $html.find(\".list td[align]\").map( (i, e) => numberfy($(e).text().match(/\\d+/)[0]) ).get(),\n\t\t\ttype : $html.find(\".list tr[class] img[alt]\").map( (i, e) => $(e).attr(\"src\").split(\"/\")[3].split(\".\")[0] ).get()\n\t\t}\n\t}\n\telse if(page === \"products\"){\n\t\treturn {\n\t\t\tname : $html.find(\".list td:nth-child(2n):has(a)\").map( (i, e) => $(e).text() ).get(),\n\t\t\tid : $html.find(\".list td:nth-child(2n) a:nth-child(1)\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get()\n\t\t}\n\t}\n\telse if(page === \"waresupply\"){\n\t\treturn {\t\t\t\n\t\t\tform : $html.find(\"[name=supplyContractForm]\"),\n\t\t\tcontract : $html.find(\".p_title\").map( (i, e) => $(e).find(\"a:eq(1)\").attr(\"href\") ).get(),\t\t\t\n\t\t\tid : $html.find(\".p_title\").map( (i, e) => numberfy($(e).find(\"a:eq(1)\").attr(\"href\").match(/\\d+$/)[0]) ).get(),\n\t\t\ttype : $html.find(\".p_title\").map( (i, e) => $(e).find(\"strong:eq(0)\").text() ).get(),\n\t\t\tstock : $html.find(\".p_title table\").map( (i, e) => $(e).find(\"strong\").length >= 2? numberfy($(e).find(\"strong:eq(0)\").text()) : 0 ).get(),\t\t\t\n\t\t\tshipments : $html.find(\".p_title table\").map( (i, e) => $(e).find(\"strong\").length === 1? numberfy($(e).find(\"strong:eq(0)\").text()) : numberfy($(e).find(\"strong:eq(2)\").text()) ).get(),\n\t\t\tparcel : $html.find(\"input:text[name^='supplyContractData[party_quantity]']\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tproduct : $html.find(\"tr:has(input:text[name])\").map( (i, e) => $(e).prevAll(\".p_title:first\").find(\"strong:eq(0)\").text() ).get(),\n\t\t\tprice : $html.find(\"tr:has(input) td:nth-child(4)\").map( (i, e) => numberfy($(e).text().match(/(\\d|\\.|\\s)+$/)) ).get(),\n\t\t\treprice : $html.find(\"tr:has(input) td:nth-child(4)\").map( (i, e) => !!$(e).find(\"span\").length ).get(),\n\t\t\tquality : $html.find(\"tr:has(input) td:nth-child(6)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\toffer : $html.find(\"tr input:checkbox\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tavailable : $html.find(\"tr:has(input) td:nth-child(9)\").map( (i, e) => $(e).text().split(/\\s[a-zA-Zа-яА-ЯёЁ]+\\s/).reduce( (a, b) => Math.min(a, b.match(/\\d+/) === null? Infinity : numberfy(b.match(/(\\d| )+/)[0])), Infinity) ).get(),\n\t\t\tmyself : $html.find(\"tr:has(input)[class]\").map( (i, e) => !!$(e).find(\"strong\").length ).get(),\n\t\t\tcontractAdd : $html.find(\".add_contract a:has(img)\").map( (i, e) => $(e).attr(\"href\") ).get(),\t\n\t\t\tidAdd : $html.find(\".add_contract a:has(img)\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+$/)[0]) ).get(),\t\n\t\t\ttypeAdd : $html.find(\".add_contract img\").map( (i, e) => $(e).attr(\"alt\") ).get(),\n\t\t}\n\t}\t\n\telse if(page === \"contract\"){\n\t\treturn {\n\t\t\tavailable : $html.find(\".price_w_tooltip:nth-child(4)\").map( (i, e) => numberfy($(e).find(\"i\").remove().end().text()) ).get(),\n\t\t\toffer : $html.find(\".unit-list-2014 tr[id]\").map( (i, e) => numberfy($(e).attr(\"id\").match(/\\d+/)[0]) ).get(),\n\t\t\tprice : $html.find(\".price_w_tooltip:nth-child(6)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tquality : $html.find(\"td:nth-child(7)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tbrand : $html.find(\"td:nth-child(8)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\ttm : $html.find(\".unit-list-2014 td:nth-child(1)\").map( (i, e) => $(e).find(\"img\").length ? $(e).find(\"img\").attr(\"title\") : \"\" ).get(),\n\t\t\tcompany : $html.find(\"td:has(i):not([class])\").map( (i, e) => $(e).find(\"b\").text() ).get(),\n\t\t\tmyself : $html.find(\".unit-list-2014 tr[id]\").map( (i, e) => !!$(e).filter(\".myself\").length ).get(),\n\t\t\tproduct : $html.find(\"img:eq(0)\").attr(\"title\")\n\t\t}\n\t}\n\telse if(page === \"research\"){\n\t\treturn {\n\t\t\tisFree : !$html.find(\".cancel\").length,\n\t\t\tisHypothesis : !!$html.find(\"#selectIt\").length,\n\t\t\tisBusy : !!numberfy($html.find(\".grid .progress_static_bar\").text()),\n\t\t\thypId : $html.find(\":radio\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tcurIndex : $html.find(\"tr:has([src='/img/v.gif'])\").index() - 1,\n\t\t\tchance : $html.find(\".grid td.nowrap:nth-child(3)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\ttime : $html.find(\".grid td.nowrap:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tisAbsent : !!$html.find(\"b[style='color: red']\").length,\n\t\t\tisFactory : !!$html.find(\"span[style='COLOR: red']\").length,\n\t\t\tunittype : $html.find(\":button:eq(2)\").attr(\"onclick\") && numberfy($html.find(\":button:eq(2)\").attr(\"onclick\").split(\",\")[1]),\n\t\t\tindustry : $html.find(\":button:eq(2)\").attr(\"onclick\") && numberfy($html.find(\":button:eq(2)\").attr(\"onclick\").split(\"(\")[1]),\n\t\t\tlevel : numberfy($html.find(\".list tr td[style]:eq(0)\").text())\n\t\t}\n\t}\n\telse if(page === \"experimentalunit\"){\n\t\treturn {\n\t\t\tid : $html.find(\":radio\").map( (i, e) => numberfy($(e).val()) ).get()\n\t\t}\n\t}\t\n\telse if(page === \"productreport\"){\n\t\treturn {\n\t\t\tmax : $html.find(\".grid td.nowrap:nth-child(2)\").map( (i, e) => numberfy($(e).text().split(\":\")[1]) ).get(),\n\t\t\ttotal : $html.find(\".grid td.nowrap:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tavailable : $html.find(\".grid td.nowrap:nth-child(3)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tquality : $html.find(\".grid td.nowrap:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tprice : $html.find(\".grid td.nowrap:nth-child(5)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tsubid : $html.find(\".grid td:nth-child(1) td:nth-child(1) a\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get()\n\t\t}\n\t}\n\telse if(page === \"financeitem\"){\n\t\treturn {\n\t\t\tenergy : numberfy($html.find(\".list tr:has(span[style]) td:eq(1)\").text()),\n\t\t}\n\t}\n\telse if(page === \"size\"){\n\t\treturn {\n\t\t\tsize : $html.find(\".nowrap:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\trent : $html.find(\".nowrap:nth-child(3)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tid : $html.find(\":radio\").map( (i, e) => numberfy($(e).val()) ).get()\n\t\t}\n\t}\n\telse if(page === \"waremain\"){\n\t\treturn {\n\t\t\tsize : numberfy($html.find(\".infoblock td:eq(1)\").text()),\n\t\t\tfull : numberfy($html.find(\"[nowrap]:eq(0)\").text()),\n\t\t\tproduct : $html.find(\".grid td:nth-child(1)\").map( (i, e) => $(e).text() ).get(),\n\t\t\tstock : $html.find(\".grid td:nth-child(2)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tshipments : $html.find(\".grid td:nth-child(6)\").map( (i, e) => numberfy($(e).text()) ).get(),\t\t\t\n\t\t}\n\t}\n\telse if(page === \"ads\"){\n\t\treturn {\n\t\t\tpop : numberfy($html.find(\"script\").text().match(/params\\['population'\\] = \\d+/)[0].substring(23)),\n\t\t\tbudget : numberfy($html.find(\":text:not([readonly])\").val()),\n\t\t\trequiredBudget : numberfy($html.find(\".infoblock tr:eq(1) td:eq(1)\").text().split(\"$\")[1])\n\t\t}\n\t}\n\telse if(page === \"employees\"){\n\t\treturn {\n\t\t\tsubid : $html.find(\".list tr:gt(2) :checkbox\").map( (i, e) => numberfy($(e).attr(\"id\").substring(5)) ).get(),\n\t\t\ttype : $html.find(\".list td[class]:nth-child(3)\").map( (i, e) => $(e).attr(\"class\").split(\"-\")[2] ).get(),\n\t\t\tcity : $html.find(\".u-a b\").map( (i, e) => $(e).text() ).get(),\n\t\t\templWrk : $html.find(\".list td:nth-child(5).nowrap\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\templMax : $html.find(\".list td:nth-child(6).nowrap\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tsalaryWrk : $html.find(\".list td:nth-child(7)\").map( (i, e) => numberfy($(e).find(\"span\").remove().end().text()) ).get(),\n\t\t\tsalaryCity : $html.find(\".list td:nth-child(8)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tskillWrk : $html.find(\".list td:nth-child(9)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tskillReq : $html.find(\".list td:nth-child(10)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tonHoliday : $html.find(\".list td:nth-child(11)\").map( (i, e) => !!$(e).find(\".in-holiday\").length ).get(),\n\t\t\tonTraining : $html.find(\"tr:has(.u-a)\").map( (i, e) => !!$(e).find(\".sizebar\").length ).get(),\n\t\t\tefficiency : $html.find(\".list td:nth-child(11)\").map( (i, e) => $(e).text().trim() ).get()\n\t\t};\n\t}\n\telse if(page === \"holiday\"){\n\t\treturn {\n\t\t\tsubid : $html.find(\".list tr:gt(2) :checkbox\").map( (i, e) => numberfy($(e).attr(\"id\").substring(5)) ).get(),\n\t\t\tskillCity : $html.find(\".list td:nth-child(9)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"promotion\"){\n\t\treturn {\n\t\t\tid : $html.find(\".grid tr[onmouseover] a\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\tbuyers : $html.find(\".grid .nowrap:nth-child(8)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tdelta : $html.find(\".grid .nowrap:nth-child(8)\").map( (i, e) => numberfy($(e).text().split(\"(\")[1]) ).get()\n\t\t}\n\t}\n\telse if(page === \"machines\"){\n\t\treturn {\n\t\t\tid : $html.find(\":checkbox[name]\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tsubid : $html.find(\":checkbox[name]\").map( (i, e) => numberfy($(e).attr(\"id\").split(\"_\")[1]) ).get(),\n\t\t\ttype : $html.find(\".list td[class]:nth-child(3)\").map( (i, e) => $(e).attr(\"class\").split(\"-\")[2] ).get(),\n\t\t\tnum : $html.find(\".list td[class]:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tperc : $html.find(\"td:nth-child(8)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tblack : $html.find(\"td:nth-child(8)\").map( (i, e) => numberfy($(e).text().split(\"(\")[1]) ).get(),\n\t\t\tred : $html.find(\"td:nth-child(8)\").map( (i, e) => numberfy($(e).text().split(\"+\")[1]) ).get(),\n\t\t\tquality : $html.find(\"td:nth-child(6).nowrap\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\trequired : $html.find(\"td:nth-child(7)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"animals\"){\n\t\treturn {\n\t\t\tid : $html.find(\":checkbox[name]\").map( (i, e) => numberfy($(e).val()) ).get(),\n\t\t\tsubid : $html.find(\":checkbox[name]\").map( (i, e) => numberfy($(e).attr(\"id\").split(\"_\")[1]) ).get(),\n\t\t\ttype : $html.find(\".list td[class]:nth-child(3)\").map( (i, e) => $(e).attr(\"class\").split(\"-\")[2] ).get(),\n\t\t\tnum : $html.find(\".list td[class]:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get(),\t\t\t\n\t\t\tquality : $html.find(\"td:nth-child(6)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tperc : $html.find(\"td:nth-child(7)\").map( (i, e) => numberfy($(e).text()) ).get(),\n\t\t\tblack : $html.find(\"td:nth-child(7)\").map( (i, e) => numberfy($(e).text().split(\"(\")[1]) ).get(),\n\t\t\tred : $html.find(\"td:nth-child(7)\").map( (i, e) => numberfy($(e).text().split(\"+\")[1]) ).get()\n\t\t}\n\t}\n\telse if(page === \"cityoverview\"){\n\t\treturn {\n\t\t\tcity : $html.find(\".geo > a\").map( (i, e) => $(e).text() ).get(),\n\t\t\tskill : $html.find(\".unit-list-2014 td:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"regionoverview\"){\n\t\treturn {\n\t\t\tregion : $html.find(\".geo > a\").map( (i, e) => $(e).text() ).get(),\n\t\t\tptax : $html.find(\".unit-list-2014 td:nth-child(9)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"prodhistory\"){\n\t\treturn {\n\t\t\tquality : $html.find(\".list tr[class] td:nth-child(4)\").map( (i, e) => numberfy($(e).text()) ).get()\n\t\t}\n\t}\n\telse if(page === \"specchange\"){\n\t\treturn {\n\t\t\tidMaterial : $html.find(\"tr:has([checked]) td:nth-child(5) a:has(img)\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\tidProduct : $html.find(\"tr:has([checked]) td:nth-child(6) a:has(img)\").map( (i, e) => numberfy($(e).attr(\"href\").match(/\\d+/)[0]) ).get(),\n\t\t\tshareMaterial : $html.find(\"tr:has([checked]) td:nth-child(5) table[align]\").map( (i, e) => numberfy(eval($(e).text().match(/(\\d|\\/)+/)[0])) ).get(),\n\t\t\tshareProduct : $html.find(\"tr:has([checked]) td:nth-child(6) table[align]\").map( (i, e) => numberfy(eval($(e).text().match(/(\\d|\\/)+/)[0])) ).get()\n\t\t}\n\t}\n}", "buildDescription(data) {\n return data.desc + \"\\n\\n Userfeed Story Link: \" + data.redirectUrl;\n }", "function SimpleStoryCreator() {\n // ************************************************************\n // * All required lists *\n // ************************************************************\n\n // List of all possible story plots\n var rPlotList = [\n\t\"destroy\",\n\t\"kidnap\",\n\t\"witch\",\n\t\"revenge\"\n ];\n\n // List of story intros\n var rIntroList = [\n\t\"Once Upon a Time\",\n\t\"In a land far away\",\n\t\"Before you were born\",\n\t\"In a little village\"\n ];\n\n // List of possible endings for the story\n var rPlotEndList = [\n\t\"flee\",\n\t\"kill\",\n\t\"kill_weapon\"\n ];\n\n // List of all good people (read: Heros)\n var rHeroList = [\n\t{ Article: \"a\" , Name: \"trader\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"merchant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesperson\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesman\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"peasant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"farmer\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"farmer's wife\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"hero\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"heroine\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"blacksmith\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"poet\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"programmer\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"musician\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"princess\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"prince\", Gender: \"male\" }\n ];\n\n // List of all adjectives of the Hero\n var rHeroMainAdjectiveList = [\n\t{ Article: \"a\", Word: \"brave\" },\n\t{ Article: \"a\", Word: \"wealthy\" },\n\t{ Article: \"a\", Word: \"rich\" },\n\t{ Article: \"a\", Word: \"poor\" }\n ];\n\n var rHeroSecondaryAdjectiveList = [\n\t{ Male: \"kind to everyone\", Female: \"kind to everyone\" },\n\t{ Male: \"madly in love with his wife\", Female: \"madly in love with her husband\" },\n\t{ Male: \"handsome\", Female: \"beautiful\" }\n ];\n\n // List of all bad people (read: Villains)\n var rVillainList = [\n\t{ Article: \"a\" , Name: \"warlock\" },\n\t{ Article: \"a\" , Name: \"necromancer\" },\n\t{ Article: \"a\" , Name: \"ghost\" },\n\t{ Article: \"a\" , Name: \"demon\" },\n\t{ Article: \"a\" , Name: \"goblin\" },\n\t{ Article: \"a\" , Name: \"troll\" },\n\t{ Article: \"a\" , Name: \"monster\" },\n\t{ Article: \"a\" , Name: \"dwarf\" },\n\t{ Article: \"a\" , Name: \"giant\" },\n\t{ Article: \"a\" , Name: \"barbarian\" },\n\t{ Article: \"a\" , Name: \"grook\" },\n\t{ Article: \"a\" , Name: \"rogue\" },\n\t{ Article: \"a\" , Name: \"bandit\" },\n\t{ Article: \"a\" , Name: \"rascal\" },\n\t{ Article: \"a\" , Name: \"scoundrel\" },\n\t{ Article: \"an\", Name: \"orc\" },\n\t{ Article: \"an\", Name: \"ogre\" },\n\t{ Article: \"a\" , Name: \"soldier\" },\n\t{ Article: \"a\" , Name: \"warrior\" },\n\t{ Article: \"a\" , Name: \"fighter\" },\n\t{ Article: \"a\" , Name: \"viking\" },\n\t{ Article: \"a\" , Name: \"mage\" },\n\t{ Article: \"a\" , Name: \"villain\" },\n\t{ Article: \"an\", Name: \"archer\" },\n\t{ Article: \"a\" , Name: \"phantom\" }\n ];\n\n // List of possible wording for \"kill\"\n var rKillList = [\n\t\"killed\",\n\t\"murdered\",\n\t\"slayed\",\n\t\"assassinated\"\n ];\n\n // List of possible wording for \"flee\"\n var rFleeList = [\n\t\"fled\",\n\t\"fled in terror\",\n\t\"escaped\",\n\t\"manged to escape\",\n\t\"was able to flee\"\n ];\n\n // List of possible wording for \"cheat\"\n var rCheatList = [\n\t\"cheated\",\n\t\"tricked\",\n\t\"was able to trick\",\n\t\"managed to cheat\",\n\t\"fooled\"\n ];\n\n\n // Plot: Destroy; List of ways to destroy an object\n var rDestroyList = [\n\t\"destroy\",\n\t\"ruined\",\n\t\"wrecked\",\n\t\"smashed\",\n\t\"demolished\"\n ];\n\n // Plot: Destroy; List of objects that can be destroyed\n var rDestroyObjectList = [\n\t\"house\",\n\t\"garden\",\n\t\"doghouse\",\n\t\"temple\",\n\t\"clock\",\n\t\"field\",\n\t\"farm\",\n\t\"tower\",\n\t\"building\",\n\t\"residence\",\n\t\"domicile\",\n\t\"place of birth\",\n\t\"home\",\n\t\"hovel\",\n\t\"hut\",\n\t\"flat\",\n\t\"flatlet\",\n ];\n\n\n // Plot: Witch; List of ways to cast the spell\n var rWitchList = [\n\t\"enchanted\",\n\t\"spellbound\",\n\t\"bewitched\",\n\t\"entranced\"\n ];\n\n // Plot: Witch; List of ways to end the spell\n var rWitchEndList = [\n\t\"freed\",\n\t\"ended the spell casted on\",\n\t\"ended the enchantment of\"\n ];\n\n // Plot: Kidnap; List of ways to be kidnaped\n var rKidnapList = [\n\t\"kidnapped\",\n\t\"abducted\",\n\t\"carried off\"\n ];\n\n // List of final moments\n var rFinalMoment = [\n\t\"Then\",\n\t\"Finally\",\n\t\"Ultimately\",\n\t\"In the end\",\n\t\"Thereupon\",\n\t\"Thereat\",\n\t\"After that\"\n ];\n\n // List of \"One day\" events\n var rOneDayList = [\n\t\"One day\",\n\t\"There came a day\",\n\t\"One night\"\n ];\n\n // List of all possible relatives\n var rRelativeList = [\n\t\"dog\",\n\t\"cat\",\n\t\"mother\",\n\t\"father\",\n\t\"grandfather\",\n\t\"grandmother\",\n\t\"brother\",\n\t\"son\",\n\t\"sister\",\n\t\"daughter\",\n\t\"friend\",\n\t\"mate\",\n\t\"uncle\",\n\t\"aunt\",\n\t\"son-in-law\",\n\t\"dauther-in-law\",\n\t\"goldfish\",\n\t\"lover\",\n\t\"lawyer\",\n\t\"helper\"\n ];\n\n // List of possible weapons\n var rWeaponList = [\n\t\"bastard sword\",\n\t\"dagger\",\n\t\"shovel\",\n\t\"rifle\",\n\t\"magnum\",\n\t\"UZI\",\n\t\"AK-47\"\n ];\n\n\n var rStory = []; // Stores the actual story and is returned by GetStoryText\n\n // Name : sprintf\n // Parameters : At least 2 parameters are required. 1 as the actual message, and another for the content.\n // More values have to be added in case of more placeholders.\n // Description: This function replaces placeholders acording to their type. This way it's possible\n // to format a string the way the user wants it.\n // Disclaimer : This function is (C) 2006 by Naden Badalgogtapeh. The source can be found at\n // http://www.naden.de/blog/javascript-printf\n function sprintf() {\n\tif (sprintf.arguments.length < 2) {\n\t return;\n\t}\n\n\tvar data = sprintf.arguments[0];\n\n\tfor (var k = 1; k < sprintf.arguments.length; ++k) {\n\n\t switch (typeof (sprintf.arguments[k])) {\n\t case 'string':\n\t\tdata = data.replace(/%s/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'number':\n\t\tdata = data.replace(/%d/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'boolean':\n\t\tdata = data.replace(/%b/, sprintf.arguments[k] ? 'true' : 'false');\n\t\tbreak;\n\t default:\n\t\t/// function | object | undefined\n\t\tbreak;\n\t }\n\t}\n\treturn data;\n }\n\n\n // Name : rRandom\n // Parameters : This function requires 2 parameters:\n // - aMin (Integer); The lowest possible number\n // - aMax (Integer); The highest possible number\n // Description: Generates a random number and returning it.\n // Disclaimer : Exchanged this function with a more reliable solution.\n // The new version is taken from\n // http://www.naden.de/blog/zufallszahlen-in-javascript-mit-mathrandom\n // Authors are:\n // - (C) 2006 by Naden Badalgogtapeh\n // - (C) 2008 by batzee\n // - (C) 2012 by MHN\n function rRandom(aMin, aMax) {\n\tvar lMin = Math.floor( parseInt( aMin ) );\n\tvar lMax = Math.floor( parseInt( aMax ) );\n\n\tif ( lMin > lMax) {\n\t return rRandom( lMax, lMin ); // This is a suggestion from MHN\n\t}\n\n\tif ( lMin == lMax ) {\n\t return lMin;\n\t}\n\n\tvar lRandomNumber;\n\n\t// Prevent that we go over the destined area\n\tdo {\n\t lRandomNumber = Math.random();\n\t}\n\twhile( lRandomNumber == 1.0 );\n\t// End of prevention\n\n\treturn lMin + parseInt( lRandomNumber * ( lMax-lMin + 1 ) );\n }\n\n\n // Name : NewStory\n // Parameters : aStoryMode (optional; string) - In case you want\n // a specific kind of story. Can be ignored otherwise.\n // Description: Creates a plot and builds a story upon the plot.\n // Uses a random hero and a random villain for this.\n // The story is stored in the private variable rStory and can\n // be called by using the GetStoryText-routine\n this.createStory = function ( aStoryMode ) {\n\t// General information about the story\n\tvar lPlotMode = rPlotList[ rRandom( 1, rPlotList.length ) - 1 ];\n\tvar lIntro = rIntroList[ rRandom( 1, rIntroList.length ) - 1 ];\n\tvar lSubIntro = rRandom( 1, 99 );\n\tvar lPlotEndMode = rPlotEndList[ rRandom( 1, rPlotEndList.length ) - 1 ];\n\tvar lHeroID = rRandom( 1, rHeroList.length ) - 1;\n\tvar lVillainID = rRandom( 1, rVillainList.length ) - 1;\n\n\tvar lKill = rKillList[ rRandom( 1, rKillList.length ) - 1 ]; // Plot-End: kill\n\tvar lWeapon = rWeaponList[ rRandom( 1, rWeaponList.length ) - 1 ]; // Plot-End: kill_weapon\n\tvar lFlee = rFleeList[ rRandom( 1, rFleeList.length ) - 1 ]; // Plot-End: flee\n\tvar lDayMode = rRandom( 1, rOneDayList.length ) - 1;\n\tvar lFinal = rFinalMoment[ rRandom( 1, rFinalMoment.length ) - 1 ];\n\n\tvar lKidnapWay = rRandom( 1, rKidnapList.length ) - 1; // Plot: Kidnap\n\tvar lDestroyWay = rRandom( 1, rDestroyList.length ) - 1; // Plot: Destroy\n\tvar lWitchWay = rRandom( 1, rWitchList.length ) - 1; // Plot: Witch\n\tvar lWitchEnd = rWitchEndList[ rRandom( 1, rWitchEndList.length ) - 1 ];\n\n\tvar lObjectID = rRandom( 1, rDestroyObjectList.length ) - 1; // Plot: Destroy\n\tvar lRelativeID = rRandom( 1, rRelativeList.length ) - 1; // Plot: Revenge\n\n\tvar lHeroGender = rHeroList[lHeroID].Gender;\n\tvar lHeroAlternateGender;\n\tvar lHeroName = rHeroList[lHeroID].Name;\n\tvar lHeroArticle = rHeroList[lHeroID].Article;\n\tvar lHeroMainAdjective = rHeroMainAdjectiveList[ rRandom( 1, rHeroMainAdjectiveList.length ) - 1 ];\n\tvar lHeroSecondaryAdjective;\n\tvar lHeroSecondary = rHeroSecondaryAdjectiveList[ rRandom( 1, rHeroSecondaryAdjectiveList.length ) - 1 ];\n\tvar lCheatWord = rCheatList[ rRandom( 1, rCheatList.length ) - 1 ];\n\n\tvar lVillainName = rVillainList[lHeroID].Name;\n\tvar lVillainArticle = rVillainList[lHeroID].Article;\n\n\tif ( aStoryMode == \"destroy\" ) lPlotMode = \"destroy\";\n\tif ( aStoryMode == \"kidnap\" ) lPlotMode = \"kidnap\";\n\tif ( aStoryMode == \"mindcontrol\" ) lPlotMode = \"witch\";\n\tif ( aStoryMode == \"revenge\" ) lPlotMode = \"revenge\";\n\n\n\tswitch ( lHeroGender ) {\n\tcase \"both\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t if ( rRandom( 1, 100 ) > 50 ) {\n\t\tlHeroGender = \"She\";\n\t\tlHeroSecondaryAdjective = lHeroSecondary.Female;\n\t }\n\t break;\n\tcase \"female\":\n\t lHeroGender = \"She\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Female;\n\t break;\n\tcase \"male\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t break;\n\t}\n\tlHeroAlternateGender = \"his\";\n\tif ( lHeroGender.toLowerCase() == \"she\" ) lHeroAlternateGender = \"her\";\n\n\n\t// Preparing the story and the plot\n\trStory = [];\n\tvar lPlot = [];\n\tswitch ( lPlotMode ) {\n\tcase \"destroy\":\n\t lPlot.push( \"destroy\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"kidnap\":\n\t lPlot.push( \"kidnap\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"witch\":\n\t lPlot.push(\"witch\");\n\t lPlot.push(\"cheat\");\n\t lPlot.push(\"entwitch\");\n\t break;\n\n\tcase \"revenge\":\n\t lPlot.push( \"revenge\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\t}\n\tlPlot.push( lPlotEndMode );\n\n\n\t// Adding the intro\n\tvar lPlotLine = sprintf(\"%s there lived %s %s.\", lIntro, lHeroArticle, lHeroName);\n\tif ( lSubIntro > 33 ) lPlotLine = sprintf(\"%s there was %s %s %s.\", lIntro, lHeroMainAdjective.Article, lHeroMainAdjective.Word, lHeroName );\n\tif ( lSubIntro > 66 ) lPlotLine = sprintf(\"%s there was %s %s who was %s.\", lIntro, lHeroArticle, lHeroName, lHeroSecondaryAdjective );\n\trStory.push( lPlotLine );\n\n\t// Adding the rest of the plot\n\tfor (var lIndex = 0; lIndex < lPlot.length; lIndex++) {\n\n\t switch ( lPlot[ lIndex ] ) {\n\t case \"cheat\":\n\t\tlPlotLine = sprintf(\"%s %s the %s.\", lHeroGender, lCheatWord, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"The %s %s the %s.\", lHeroName, lCheatWord, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"destroy\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, rDestroyList[ lDestroyWay ], rDestroyObjectList[ lObjectID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"entwitch\":\n\t\tlPotLine = sprintf(\"The %s %s the %s.\", lVillainName, lWitchEnd, lHeroName);\n\t\t//if ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"flee\":\n\t\tlPotLine = sprintf(\"%s %s %s.\", lFinal, lHeroGender.toLowerCase(), lFlee );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kidnap\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill_weapon\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s with %s %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName, lHeroAlternateGender, lWeapon );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"revenge\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, lKill, rRelativeList[ lRelativeID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"witch\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\t };\n\t}\n };\n\n // Name : GetStoryText\n // Parameters : None\n // Description: Returns the stored story as an array where each line is an entry\n this.getStoryText = function () {\n\treturn rStory;\n };\n\n\n // Name : AddHero\n // Parameters : This function requires 3 parameters:\n // - aArticle (string); The article of the hero; Can either be \"a\", \"an\", \"the\"or \"\"\n // - aName (string); the nma or job of the hero\n // - aGender (string); the gender of the hero; Can either be \"male\", \"female\" or \"both\"\n // Description: Adds a new possible hero to the list of heros. The user can define the name/job, the gender and an article\n // which is to be used with the name.\n this.addHero = function (aArticle, aName) {\n\tvar lArticle = aArticle.toLowerCase();\n\tvar lGender = aGender.toLowerCase();\n\n\trHeroList.push( { Article: lArticle, Name: aName, Gender: lGender } );\n };\n\n this.createStory(); // Creatinng a story in advance\n}", "function allStoryMaker(storyList) {\n const results = [];\n for (let story of storyList) {\n results.push(generateStoryHTML(story));\n }\n return results;\n }", "function generateStory() {\n return {\n title: faker.lorem.words(),\n content: faker.lorem.paragraphs(),\n img: 'https://source.unsplash.com/random/350x350',\n genre: faker.lorem.word(),\n user: \"testing\",\n };\n}", "function formatOsmEntitiesToLink(text){\n if (text) {\n var shortCodeRegex = /\\[\\w+\\/\\d+(,?\\s*\\w+\\/\\d+)*\\]/g;\n var entityRegex = /(\\w+)\\/(\\d+)/;\n var entityMap = {\n n: 'node',\n node: 'node',\n w: 'way',\n way: 'way',\n r: 'relation',\n rel: 'relation',\n relation: 'relation'\n };\n\n var shortCodeMatch = null;\n while (shortCodeMatch = shortCodeRegex.exec(text)) {\n // There could be multiple entities in a combo code, so split them up\n // and expand each one. Entities must be comma or space separated.\n var entities = shortCodeMatch[0].slice(1, -1).split(/,\\s*|\\s+/);\n\n var expandedEntities = entities.map(function(entity) {\n var entityMatch = entityRegex.exec(entity);\n // Ignore short codes we don't explicitly support\n if (!entityMap[entityMatch[1]]) {\n return null;\n }\n\n return {\n linkText: entityMap[entityMatch[1]] + '/' + entityMatch[2],\n linkTitle: entityMap[entityMatch[1]] + ' ' + entityMatch[2],\n overpassQuery: entityMap[entityMatch[1]] + '(' + entityMatch[2] + ');'\n };\n });\n\n // If there are any null entity expansions, we have an unsupported code, so ignore it.\n if (expandedEntities.indexOf(null) !== -1) {\n continue;\n }\n\n // Combine expansion data from all entities into final link\n var linkText = expandedEntities.map(function(e) { return e.linkText; }).join(', ');\n var linkTitle = expandedEntities.map(function(e) { return e.linkTitle; }).join(', ');\n var overpassQuery =\n '(' +\n expandedEntities.map(function(e) { return e.overpassQuery; }).join('') +\n ');(._;>;);out;';\n var linkUrl='http://overpass-turbo.eu/map.html?Q=' + encodeURIComponent(overpassQuery);\n var link = '<a target=\"_blank\" title=\"' + linkTitle + '\" href=\"' + linkUrl + '\">' + linkText + '</a>';\n\n // Replace short code in comment with generated link\n text = text.replace(shortCodeMatch[0], link);\n }\n }\n\n return text;\n }", "function output_wiki() {\n\tvar html, coords;\n\thtml = '<imagemap>';\n\tif (typeof myimgmap.pic != 'undefined') {\n\t\thtml+= 'Image:' + myimgmap.pic.src + '|' + myimgmap.pic.title + '\\n';\n\t}\n\t\n\t//foreach areas\n\tfor (var i=0; i<myimgmap.areas.length; i++) {\n\t\tif (myimgmap.areas[i]) {\n\t\t\tif (myimgmap.areas[i].shape && myimgmap.areas[i].shape != 'undefined') {\n\t\t\t\tcoords = myimgmap.areas[i].lastInput.split(',').join(' ');\n\t\t\t\thtml+= myimgmap.areas[i].shape + ' ' + coords + ' [[' + myimgmap.areas[i].ahref + '|' + myimgmap.areas[i].aalt + ']]\\n';\n\t\t\t}\n\t\t}\n\t}\n\thtml+= '#' + myimgmap.waterMark + '\\n</imagemap>';\n\t//alert(html);\n\treturn html;\n}", "function mapSpecialAbilitiesData () {\n formattedInput.special_abilities.forEach (async function (specialAbility, index) {\n \n // SET THE FEATTYPE\n let featType = \"misc\";\n \n setSpecialAbilityItem(specialAbility, featType, \"Special Ability\");\n \n });\n}", "function titleThumb(story_data) {\n story_data.content .. @each {\n |row|\n row .. @each {\n |block|\n if (block.type === 'img')\n return block.url;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to get chart rersource at the first time
function getChartResource() { if (isFirstTime) { isFirstTime = false; $.ajax({ type : "GET", url : "getChartSourceContent", success : function(data) { $('#chartContents').html(data); }, failure : function(errMsg) { alert(errMsg); } }); } }
[ "function initCharts() {\n xmlHttpReq('GET', '/storages_data', '', function(responseText) {\n var response = JSON.parse(responseText);\n if (response.success) {\n drawCharts(response.data);\n } else {\n snackbar(response.message);\n }\n });\n}", "init() {\n const series = this.chartData.series;\n const seriesKeys = Object.keys(series);\n\n for (let ix = 0, ixLen = seriesKeys.length; ix < ixLen; ix++) {\n this.addSeries(seriesKeys[ix], series[seriesKeys[ix]]);\n }\n\n if (this.chartData.data.length) {\n this.createChartDataSet();\n }\n }", "function createChart() {\n getSettings();\n $scope.chart = picasso.chart({\n element: $element.find('.adv-kpi-chart')[0],\n data: ds,\n settings: picassoSettings,\n beforeRender() { qlik.resize(); }\n });\n }", "onChartRender() {\n this.updateProxyOverlays();\n }", "function syncLineChart(callback){\n lineChartQuery(lineChartParams,callback);\n}", "renderliveOperationalStatisticsPie() {\n let me = this;\n this.loadingliveOperationalStatistics = true;\n this.loadingliveOperationalStatisticsPie = true;\n this.client.get('/statistics/liveoperationalstatistic').then(res => {\n if (res) {\n if (res.data) {\n this.opStatistics = res.data.current;\n this.opStatisticsPrevious = res.data.previous\n ? res.data.previous\n : null;\n //render pie chart\n let ctx = document.getElementById('operationalPie');\n me.cards.liveoperationalstatistics = new Chart(ctx, {\n type: 'pie',\n data: {\n labels: ['Not Operational', 'Operational', 'Unknown'],\n datasets: [\n {\n data: [\n me.opStatistics.notOperational,\n me.opStatistics.operational,\n me.opStatistics.unknown\n ],\n backgroundColor: ['#00838f', '#00acc1', '#b2ebf2', '#e0f7fa'],\n hoverBackgroundColor: ['#00838f', '#00acc1', '#b2ebf2', '#e0f7fa']\n }\n ]\n }\n });\n }\n }\n this.loadingliveOperationalStatisticsPie = false;\n });\n }", "function getChartResourceByTimeRange() {\n\t$.ajax({\n\t\ttype : \"POST\",\n\t\turl : \"getChartResourceByTimeRange\",\n\t\tdata : $(dateRangeForm).serialize(),\n\t\tbeforeSend : function() {\n\t\t\t//$('#loaderContainer').show();\n\t\t}\n\t}).done(function(response) {\n\t\t$('#chartContents').html(response);\n\t}).fail(function() {\n\t\tconsole.log(\"error\");\n\t}).always(function() {\n\t\t//$('#loaderContainer').hide();\n\t});\n\treturn false;\n}", "function getChartPoints() {\n \n var chartDataDiv = $(\"#chartData\");\n\n $.getJSON('/Main/GetGraphPoints',\n {\n end: chartDataDiv.attr(\"data-graph-end\"),\n numTicks: chartDataDiv.attr(\"data-graph-ticks\"),\n sensor: chartDataDiv.attr(\"data-graph-sensor\"),\n dataType: chartDataDiv.attr(\"data-graph-data\"),\n scale: chartDataDiv.attr(\"data-graph-scale\")\n },\n function (data) {\n chartProperties.xAxis = data.xAxis;\n chartProperties.yAxis = data.yAxis;\n drawChart();\n });\n}", "redraw(uid, serie, dt_str)\r\n\t{\r\n\t\t/* At start only one serie is visible */\r\n\t\tthis.__unvisible_counter = 3;\r\n\t\tthis.__currSerie = serie;\r\n\t\tthis.__currUid = uid;\r\n\t\t\r\n\t\tvar self = this;\r\n\t\tvar param = JSON.stringify({\r\n\t\t\t\"uid\": uid, \r\n\t\t\t\"serie\": serie, \r\n\t\t\t\"date\": dt_str\r\n\t\t});\r\n\t\t\r\n\t\tconsole.log(\"Daily chart redraw, now \" + param);\r\n\t\t\r\n \t$.ajax({\r\n \t\ttype: \"GET\",\r\n \t\turl: \"/restq/station/serie/daily/\"+param,\r\n \t\tsuccess: function(data)\r\n \t\t{\r\n var dailyData = JSON.parse(data);\r\n self.__dailyData = dailyData;\r\n \r\n self.__chart = self._create_dchart_template(self);\r\n \r\n self._set_chart_btn_type(self, \"CANDLE\");\r\n \t\t\r\n \t\tvar serieId=self.__desc[uid][\"serie\"][serie];\r\n \t\tvar serieUnit=serie_getUnit(self.__desc[uid][\"serie\"][serie]);\r\n \t\t\r\n \t\tvar chartTitle = dt_str + \" \" + serie.toUpperCase();\r\n \t\tself.__chart.options.title.text = chartTitle;\r\n \t\tself.__chart.options.axisY.title = serie;\r\n \t\t\r\n \t\tif(serie == \"Humidity\") {\r\n \t\t\tself.__chart.options.axisY.maximum = 102; \r\n \t\t}\r\n \t\t\t\r\n \t\tself.__chart.options.axisY.labelFormatter = function(e) \r\n \t\t\t\t\t\t\t{\r\n \t\t\t\t\t\t\t\treturn e.value.toFixed(1)+serieUnit;\r\n \t\t\t\t\t\t\t};\r\n \t\t\t\t\t\t\t\r\n \t\tself.__chart.options.axisY.stripLines = \r\n \t\t\t\tserie_getLabelColors(self.__desc[uid][\"serie\"][serie]);\r\n \t\t\r\n \t\tif(self.__draw_general == true) {\r\n \t\t\tself.__chart_general = \r\n \t\t\t\t\t\t\t\tself._create_dchart_general_template();\r\n \t\t\t\r\n \t\t\tvar generalSample = self._create_general_serie_data(\r\n \t\t\t\t\t\t\t\t\tself.__desc[uid][\"timezone\"],\r\n \t\t\t\t\t\t\t\t\tdailyData[\"general\"], \r\n \t\t\t\t\t\t\t\t\tserieId);\r\n \t\t\t\r\n \t\tif(serie == \"Humidity\") {\r\n \t\t\tself.__chart_general.options.axisY.maximum = 102; \r\n \t\t}\r\n \t\t\r\n \t\t\tself.__chart_general.options.title.text = \r\n \t\t\t\t\t\t\t\t\t\t\t\tdt_str + \" STATISTICS\";\r\n \t\t\tself.__chart_general.options.axisY.title = serie;\r\n \t\t\t\r\n \t\tself.__chart_general.options.axisY.labelFormatter = \r\n \t\t\t\t\t\tfunction(e) \r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\treturn e.value.toFixed(1)+serieUnit;\r\n\t\t\t\t\t\t\t\t\t};\r\n\t\t\t\t\tself.__chart_general.options.data = generalSample;\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar serieUnit = serie_getUnit(\r\n\t\t\t\t\t\t\t\t\t\tself.__desc[uid][\"serie\"][serie]);\r\n\t\t\t\t\tself.__chart_general.options.toolTip.content = \r\n\t\t\t\t\t\t\t\t\t\t\"{label}: {y}\"+serieUnit;\r\n\t\t\t\t\t\r\n\t\t\t\t\tconsole.log(\"__chart_general.render()\");\r\n\t\t\t\t\tself.__chart_general.render();\r\n \t\t\t}\r\n \t\t\r\n \t\tif(self.__draw_table == true) {\r\n \t\t\tself._create_table_body(self, dailyData, \r\n \t\t\t\t\t\t\t\t\t\t self.__desc[uid][\"timezone\"],\r\n \t\t\t\t\t\t\t\t\t\t serieId);\r\n \t\t}\r\n \t\t\r\n \t\tself.__chart.render();\r\n }\r\n \t});\r\n\t}", "subscription() {\n const currState = this.store.getState();\n const schema = _store.getIfChanged(\"schema\");\n if (schema) {\n this.visualization1.setSchema(JSON.parse(schema));\n this.visualization2.setSchema(JSON.parse(schema));\n }\n this.visualization1.setViewOptions({\n ...currState\n });\n this.visualization2.setViewOptions({\n ...currState\n });\n }", "function loadSeries()\n {\n for(var i = 2, j = 0; i < data.length, j < series_names.length; i++, j++)\n {\n chart.addSeries({name: series_names[j], data : data[i]});\n }\n }", "drawChart() {\n // create google pie chart with categories data\n var data = new google.visualization.DataTable();\n data.addColumn('string', \"Category\");\n data.addColumn('number', \"Count\");\n data.addRows(JSON.parse(localStorage.getItem(\"categoryPieData\")));\n var options = {\n is3D: true, \n legend :\"bottom\"\n };\n var div = document.getElementById(\"chart_div\");\n while (div != null && div.firstChild) {\n div.removeChild(div.firstChild);\n }\n var chart = new google.visualization.PieChart(document.getElementById('chart_div'));\n chart.draw(data, options);\n }", "loadGraph(){\n\n var current = this;\n var servicePathAPI = baseURL+'/api/transactions/all/'+ this.dataToken;\n \n $.getJSON(servicePathAPI, function (data) {\n\n var result = data;\n if(result){ \n \n var series = [];\n var categories = [];\n for(var i=0;i < result.length;i++){\n var item = result[i];\n var transDate = new Date(item[0]);\n var transAmount = item[1];\n categories.push( moment( transDate.getTime() ).format(\"MM/DD/YYYY\") );\n current._chartData.push( [ transDate, transAmount] );\n }\n\n }\n\n // Create the transactions chart\n this._transactionChart = Highcharts.chart('mainChart', {\n rangeSelector : {\n selected : 1,\n allButtonsEnabled: true\n },\n chart: {\n zoomType: 'x',\n alignTicks: false\n },\n title : {\n text : 'Transaction Volume'\n },\n xAxis: {\n type: 'datetime',\n categories: categories\n },\n yAxis: {\n title: {\n text: 'USD'\n }\n },\n tooltip: {\n formatter: function() {\n return 'Date: <b>' + moment(this.x).format(\"MM/DD/YYYY\") + '</b> <br/> Amount: <b>$' + accounting.format(this.y) + '</b>';\n }\n },\n series : [{\n name : 'Transactions',\n fillColor : {\n linearGradient : {\n x1: 0,\n y1: 0,\n x2: 0,\n y2: 1\n },\n stops : [\n [0, Highcharts.getOptions().colors[0]],\n [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]\n ]\n },\n data : current._chartData\n }]\n\n });\n\n });\n }", "disposeChart() {\n if (this.chart) {\n this.chart.dispose();\n this.chart = null;\n logger.debug(`TimelinePlot: disposed of chart`);\n }\n }", "function loadWattageLineChart(date) {\n\n $.getJSON(\"/WebService/MinuteWiseWattageDay\",\n {\n plantId: _currentPlantId,\n timeStamp: date.getTime(),\n mode: $(\".inverter-mode:checked\").val()\n }, function (serverData) {\n\n //draw the chart and bind to the plot hover event for updating the legend \n pvChart.wattageLineChart.plot = pvChart.wattageLineChart.loadWattageChart(serverData);\n pvChart.wattageLineChart.bindHoverEvent();\n\n });\n }", "function onRefresh3() {\n\tconfig3.data.datasets.forEach(function (dataset) {\n\t\tdataset.data.push({\n\t\t\tx: Date.now(),\n\t\t\ty: powerGenerate_real_2\n\t\t});\n\t});\n}", "function chartUpdate(config) {\n // Is it valid?\n if (config == null)\n return;\n\n // Generate the URL\n var base_url = config.data_url || window.location + \"/data.json\";\n var call_url = base_url + \"?resume=\" + config.resume\n if (config.last_id != \"\") {\n call_url = call_url + \"&last=\" + config.last_id;\n }\n if (config.points_limit != undefined) {\n call_url += \"&limit=\" + config.points_limit\n }\n\n // Do the API call\n $.getJSON(call_url).success(function(data){\n if (config.chart.series[0].data.length == 0) {\n var chartData = [];\n\n for (var i = data.length-1; i >= 0; i--)\n chartData.push([data[i].date*1000, data[i].result]);\n\n var chart = $(config.container).highcharts();\n chart.series[0].setData(chartData);\n }\n else {\n for (var i = 0; i < data.length-1; i++) {\n // Do we need to remove the first point in the chart?\n if ((config.points_limit != undefined) && (config.chart.series[0].data.count > config.points_limit))\n config.chart.series[0].addPoint([data[i].date*1000, data[i].result], false, true);\n else\n config.chart.series[0].addPoint([data[i].date*1000, data[i].result], false);\n }\n }\n\n // If there is data received, save the lastest id.\n if (data.length > 0)\n config.last_id = data[0].id;\n\n // 10 msec later, print the latest point.\n // This code is to solve a bug with the rangeSelector of HighStock\n setTimeout(function() {\n if (data.length > 0)\n config.chart.series[0].addPoint([data[data.length-1].date*1000, data[data.length-1].result], false);\n\n config.chart.redraw();\n config.chart.hideLoading();\n }, 10);\n });\n\n // Redraw the chart\n config.chart.redraw();\n}", "function renderChartObject(bindTag, chart, chartHeight, chartWidth) {\n\n var jqxhr = $.post(\"/chartconfig\", {\n data: JSON.stringify(chart),\n width: chartWidth\n },\n function () {\n var chartConfig = window[\"chart-\" + chart.filename];\n console.debug(\"Refreshing the chart, config:\", chartConfig);\n if (chartConfig) {\n chartConfig.chart.renderTo = \"chart\";\n new Highcharts.Chart(chartConfig);\n delete window[\"chart-\" + chart.filename]; //clear data from window object after rendering\n }\n }, \"script\")\n .fail(function (data, err) {\n console.error(err);\n console.log(\"Failed reading chart configuration from server\", chart);\n $(\"#chart\").empty();\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
fetch and save xbrl link form web scrape query
async function fetch_save_xbrl_instance(link, date, ticker, type){ let body =await rp(link) let file = link.split('/') let filename = file[file.length-1] logger.log({filename}) fs.writeFile(`./xbrl_files_2/${ticker}-${date}-${filename}`, body) /* OR.... Just parse and save in db? */ // let body = await fs.readFile(`./xbrl_files/${filename}`, 'utf8') let parsed_doc = await ParseXbrl.parseStr(body); parsed_doc.xml_filename = `${filename}` parsed_doc.ticker = ticker parsed_doc.filed_date = date parsed_doc.unique_id=`${ticker}-${date}-${type}` logger.log(parsed_doc) let res = await Listing_model.add_listing({ ...parsed_doc }); }
[ "function XML_(){\n let url = `https://${domain}/API/Account/${rad_id}/${APIendpoint}.json?offset=${pagenr}`;\n if (relation.length > 0) {\n url += `&load_relations=[${relation}]`;\n }\n if (query.length > 0) {\n url += query;\n }\n console.log(url);\n let uri = encodeURI(url);\n let e = new XMLHttpRequest();\n e.open(\"GET\", uri, document.getElementById('fasthands').checked),\n e.onload = function(){\n if ( e.status >= 200 && e.status < 400 ){\n t = JSON.parse(e.responseText);\n if (report === 'OrderNumbers') {\n unparse_();\n } else {\n parse_Data_();\n }\n }\n },\n e.send();\n }", "function getRelatedLink()\n{\n\tvar param='';\n\tparam = getObj(\"website\").value;\n\twindow.open('http://www.alexa.com/data/details/traffic_details?q=&url='+param,'relatedlink','height=400,width=700,resizable=no,titlebar,location,top=250,left=250');\n}", "function loadLibResults()\n{\n var result_cells;\n\n document.getElementById(\"extension-search-form\").style.display = \"none\";\n document.getElementById(\"results\").innerHTML = this.responseText;\n\n result_cells = document.querySelectorAll('div[id^=results_cell]');\n\n for (i = 0; i < result_cells.length; i++) {\n var isbn13 = document.querySelector('#' + result_cells[i].id + ' .isbnValue').value;\n var isbn10 = isbn13to10(isbn13);\n var detailLink = document.getElementById('detailLink' + i);\n\n /*\n * The links as they stand won't work since they use onclick which is \n * forbidden in extensions for security reasons. Update the links to\n * each books detail page instead of having a popup.\n */\n var onclick = detailLink.getAttribute('onclick');\n var link = onclick.match(/(ent:.*_ILS:\\d+\\/\\d+\\/\\d+)\\?/);\n var href = library_detail_page_url + link[1];\n\n detailLink.setAttribute('href', href);\n detailLink.setAttribute('target', '_blank');\n detailLink.removeAttribute('onclick');\n\n getAmazonRating(isbn10, result_cells[i], detailLink);\n } \n}", "function scrape(urlList) {\n\tfor (index in urlList) {\n\t\tvar url = urlList[index];\n\t\tvar pubID = url.match(/\\/detail\\/(\\d+)/)[1];\n\t\t\n\t\tvar apiUrl = \"https://academic.microsoft.com/api/browse/GetEntityDetails?entityId=\" +\n\t\t\tpubID + \"&correlationId=undefined\";\n\t\t\n\t\tZU.doGet(apiUrl, function(text) {\n\t\t\tvar data = JSON.parse(text);\n\t\t\tvar type;\n\t\t\tif (data.entity.c) {\n\t\t\t\ttype = \"conferencePaper\";\n\t\t\t} else if (data.entity.j) {\n\t\t\t\ttype = \"journalArticle\";\n\t\t\t} else {\n\t\t\t\ttype = \"book\";\n\t\t\t}\n\t\t\tvar item = new Zotero.Item(type);\n\t\t\titem.itemID = pubID;\n\t\t\titem.title = data.entityTitle;\n\t\t\titem.date = data.entity.d;//alternatively ZU.strToISO(data.date);\n\t\t\titem.abstractNote = data.abstract;\n\t\t\t\n\t\t\tif (data.authors) {\n\t\t\t\tfor (var i=0; i<data.authors.length; i++) {\n\t\t\t\t\titem.creators.push(ZU.cleanAuthor(data.authors[i].lt, \"author\"));\n\t\t\t\t}\n\t\t\t}\n\t\n\t\t\titem.publicationTitle = data.entity.extended.vfn;\n\t\t\titem.journalAbbreviation = data.entity.extended.vsn;\n\t\t\titem.volume = data.entity.extended.v;\n\t\t\titem.issue = data.entity.extended.i;\n\t\t\titem.pages = data.entity.extended.fp;\n\t\t\tif (data.entity.extended.lp) {\n\t\t\t\titem.pages += \"–\" + data.entity.extended.lp;\n\t\t\t}\n\t\t\titem.DOI = data.entity.extended.doi;\n\t\t\t\n\t\t\tif (data.fieldsOfStudy) {\n\t\t\t\tfor (var i=0; i<data.fieldsOfStudy.length; i++) {\n\t\t\t\t\titem.tags.push(data.fieldsOfStudy[i].lt);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//Save all links to the source in one HTML note.\n\t\t\tvar sourcesNote = \"<p>Data sources found by Microsoft Academic search engine:</p>\";\n\t\t\tif (data.sources) {\n\t\t\t\tfor (var i=0; i<data.sources.length; i++) {\n\t\t\t\t\tsourcesNote += '<a href=\"' +data.sources[i].u+ '\">'+data.sources[i].u+'</a><br/>';\n\t\t\t\t}\n\t\t\t}\n\t\t\titem.notes.push({note: sourcesNote});\n\t\t\t\n\t\t\titem.attachments.push({\n\t\t\t\turl: \"https://academic.microsoft.com/#/detail/\"+data.entity.id,\t\n\t\t\t\tsnapshot: false\n\t\t\t});\n\t\t\t\n\t\t\t/*\n\t\t\tdelete data.references;\n\t\t\tdelete data.citations;\n\t\t\tZ.debug(data);\n\t\t\t*/\n\t\t\t\n\t\t\titem.complete();\n\t\t});\n\t}\n}", "function scrapeShirtUrls(){\n var request = scrapeIt(ENTRY_POINT_URL, {\n shirtsHrefs: {\n listItem: \".products li\",\n data: {\n href: {\n selector: \"a\",\n attr: \"href\"\n }\n }\n }\n }).then(({ data, response }) => {\n if (response.statusCode === 200) {\n var hrefs = data.shirtsHrefs;\n scrapeShirtDetails(hrefs);\n }else{\n const errorMessage = new Error(`Error connecting to ${ENTRY_POINT_URL} ${response.statusMessage} (${response.statusCode})`);\n printError(errorMessage);\n }\n }).catch((error) => {\n const errorMessage = new Error(`Error with hostname: ${error.host} or connection`);\n printError(errorMessage);\n })\n}", "function sendRequest(url) {\n var userAgentString = navigator.userAgent;\n var xmlhttp = new XMLHttpRequest();\n \n xmlhttp.onreadystatechange = function() {\n if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {\n var data = JSON.parse(xmlhttp.responseText);\n document.getElementById(\"searchQ\").value = \"\";\n \n // get heading: data[1][0]\n // get description: data[2][0]\n // get url link: data[3][0]\n \n var WikiData = {};\n WikiData.heading = data[1][0];\n WikiData.description = data[2][0];\n WikiData.link = data[3][0];\n \n displayResult(WikiData);\n \n }\n };\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.setRequestHeader(\"Content-Type\", \"application/json; charset=UTF-8\");\n xmlhttp.send();\n}", "function getData( xHRObject, xsllnk )\n{\n var READY_STATE_UNINITIALIZED = 0;\n var READY_STATE_LOADING = 1;\n var READY_STATE_LOADED = 2;\n var READY_STATE_INTERACTIVE = 3;\n var READY_STATE_COMPLETE = 4;\n\t//var xmlDocs = xHRObject.responseText;\n\t//var xmlDocs = xHRObject.responseXML;\n\t//alert('getData called ' + xHRObject.readyState + ' ' + xHRObject.status + '\\n' + xmlDocs);\n\t\n\tif ((xHRObject.readyState == READY_STATE_COMPLETE) && (xHRObject.status == 200))//check to see if the obj is rdy\n\t{\n\t\t//If there's not stylesheet to manupulate the data send the txt back\n\t\tif( xsllnk == null || xsllnk == '') return xHRObject.responseText;\n\t\tif( xsllnk.toLowerCase() == 'xml' ) return xHRObject.responseXML;\n\t\t//Load XML\n\t\tvar xmlDoc = xHRObject.responseXML;\n return applyXSL( xmlDoc, xsllnk );\n\t}\n\treturn null;\n}", "function getStatusForAllISBNs(item, isbn) {\r\n\tvar wbUrl = 'http://labs.oclc.org/xisbn/' + isbn;\r\n\tGM_xmlhttpRequest({\r\n\t method: 'GET',\r\n\t url: wbUrl,\r\n\t headers: {\r\n\t 'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',\r\n\t 'Accept': 'application/atom+xml,application/xml,text/xml',\r\n\t },\r\n\t onload: function(responseDetails) {\r\n//\t\t\tGM_log(responseDetails.responseText);\t\r\n\t var parser = new DOMParser();\r\n\t var dom = parser.parseFromString(responseDetails.responseText,\r\n\t \"application/xml\");\r\n\r\n\t var isbns = dom.getElementsByTagName('isbn');\r\n\t for (var i = 0; i < isbns.length; i++){\r\n//\t\t\t\tGM_log(isbn+\": \"+items[i].textContent);\r\n\t\t\t\tgetBookStatus(item,isbns[i].textContent);\r\n\t\t\t}\r\n\t \r\n\t }\r\n\t});\t\r\n}", "function grabJumpToContent()\n{\n\tvar oXMLDoc = getXMLDocument(smf_prepareScriptUrl(smf_scripturl) + 'action=xmlhttp;sa=jumpto;xml', grabJumpResponse);\n}", "function guest_airbnb_url_create(data, type, row, meta) {\n url = \"https://www.airbnb.com/users/show/\" + row.id + \"\";\n data = '<a target=\"_blank\" href=\"' + url + '\">' + data + \"</a>\";\n return data;\n}", "function updateURL() {\n const URLelement = elements.get(\"title\").querySelector(\"a\");\n switch (URLelement) {\n case null:\n currentURL = undefined;\n break;\n default:\n const id = URLelement.href.replace(/[^0-9]/g, \"\");\n currentURL = `https://tidal.com/browse/track/${id}`;\n break;\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}", "function addBlastData(){\n $(\"#results-actions\").html('<p>Le blast est en cours ...</p>')\n $.post('/'+$(\"#protein-id\").text()+'/blast').done(function(blast_ids){\n var data = \"IDs des 3 protéines ayant la meilleure e-value : <br>\";\n blast_ids.forEach(id => {\n data += \"<a href='https://www.rcsb.org/structure/\"+id+\"' target='_blank'>\"+id+\"</a> <br>\"\n });\n $(\"#results-actions\").html(data);\n }).fail( function(){\n $(\"#results-actions\").html(\"<p>Le blast n'a pas fonctionné !</p>\")\n });\n}", "function stockInfoURL(sym) {\n var queryURL;\n\n queryURL = IEXEndpoint + sym + IEXSuffix;\n console.log(\"in stockInfoURL -- queryURL: \" + queryURL);\n\n $.ajax({\n \"method\": \"GET\",\n \"url\": queryURL\n }).\n done((response) => {\n console.log(\"stock info response: \" + JSON.stringify(response));\n currentWatchRow.companyName = response.companyName;\n currentWatchRow.website = response.website;\n currentWatchRow.description = response.description;\n }).\n fail(() => {\n console.log(\"Failure from Alpha Time Series function\");\n });\n }", "function get_site (input, city) {\r\n\trequest({\r\n\t\t uri: input,\r\n\t\t}, function(error, response, body) {\r\n\t\t if (error) {\r\n\t\t \tconsole.log(error);\r\n\t\t } else {\r\n\t\t \tvar regex;\r\n\t\t \tvar regex1 = /^<td>([0-9a-zA-Z.]+)<\\/td>$/;\r\n\t\t \tvar result;\r\n\t\t \tvar result1;\r\n\t\t \tvar lines = body.split(\"\\n\");\r\n\t\t \tvar lines_len = lines.length;\r\n\t\t \tvar indic_len = indicators.length;\r\n\r\n\t\t \tfor (var i = 0; i < lines_len; i++) {\r\n\t\t \t\tfor (var j = 0; j < indic_len; j++) {\r\n\r\n\t\t \t\t\tregex = new RegExp(\"^<td>\" + indicators[j] + \"<\\/td>$\");\t\r\n\t\t \t\t\tresult = lines[i].match(regex);\r\n\t\t \t\t\tif (result) {\r\n\t\t \t\t\t\tresult1 = lines[i+1].match(regex1);\r\n\t\t \t\t\t\tconsole.log(city + \": \" + indicators[j] + \": \" + result1[1]);\r\n\t\t \t\t\t\t\r\n\t\t \t\t\t\tvar element = new Element();\r\n\t\t \t\t\t\telement.location = city;\r\n\t\t \t\t\t\telement.indicator = indicators[j];\r\n\t\t \t\t\t\telement.value = result1[1];\r\n\t\t \t\t\t\telement.save(function (err) {\r\n\t\t \t\t\t\t\tif (err) {\r\n\t\t \t\t\t\t\t\tthrow err;\r\n\t\t \t\t\t\t\t}\r\n\t\t \t\t\t\t});\r\n\t\t \t\t\t}\r\n\t\t \t\t}\r\n\t\t \t}\r\n\t\t }\r\n\t\t});\r\n}", "function loadPage() {\n pageNumber++; // Increment the page number\n const options = {\n method: 'GET',\n uri: `https://doctor.webmd.com/results?so=&zip=${ZIP_CODE}&ln=Family%20Medicine&pagenumber=${pageNumber}`,\n headers: {\n 'User-Agent': 'Request-Promise',\n 'Authorization': 'Basic QWxhZGRpbjpPcGVuU2VzYW1l'\n },\n transform: body => {\n return cheerio.load(body);\n }\n };\n request(options)\n .then(async $ => {\n let results = await fetchResults($);\n return results;\n })\n .catch(err => console.error(err.message));\n }", "function stockInfoURL(sym) {\n var queryURL;\n\n queryURL = IEXEndpoint + sym + IEXSuffix;\n console.log(\"in stockInfoURL -- queryURL: \" + queryURL);\n\n $.ajax({\n \"method\": \"GET\",\n \"url\": queryURL\n }).\n then((response) => {\n console.log(\"stock info response: \" + JSON.stringify(response));\n currentWatchRow.companyName = response.companyName;\n currentWatchRow.website = response.website;\n currentWatchRow.description = response.description;\n $(\"#stock-input\").show();\n }).\n fail(() => {\n console.log(\"Failure from IEX endpoint stock info function\");\n $(\"#stock-input\").show();\n });\n }", "function dataSearchAndSave(){\n\t\t(async() => {\n\t\t\t// headless chrome browser open \n\t\t\tconst browser = await puppeteer.launch({headless: true});\n\t\t\tconst page = await browser.newPage();\n\n await page.goto(pagequery);\n\t\t\tawait page.waitFor(20000);\n\t\t\t\n\t\t\t// subcompare windows close \n const exitSelector = '.ResultsDialog__close__fc';\n\t\t\tawait page.click(exitSelector);\n\n\t\t\t// price part selecting and reading data\n\t\t\tconst resultsPrice = '.FlightResultsList__price__fc';\n\t\t\tawait page.waitForSelector(resultsPrice);\n\n\t\t\tconst linksPrice = await page.evaluate(resultsPrice => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsPrice));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsPrice);\n\t\n\t\t\t// Carrier company name selecting and reading \n\t\t\tconst resultsCarriername = '.FlightResultsList__carrierName__fc';\n\t\t\tawait page.waitForSelector(resultsCarriername);\n\n\t\t\tconst linksCarriername = await page.evaluate(resultsCarriername => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsCarriername));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsCarriername);\n\n\t\t\t// leaving and arriving time selecting and reading\n\t\t\tconst resultsTime = '.FlightResultsList__time__fc';\n\t\t\tawait page.waitForSelector(resultsTime);\n\n\t\t\tconst linksTime = await page.evaluate(resultsTime => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsTime));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsTime);\n\n\t\t\t// depart and destination code selecting and reading\n\t\t\tconst resultsCode = '.FlightResultsList__code__fc';\n\t\t\tawait page.waitForSelector(resultsCode);\n\n\t\t\tconst linksCode = await page.evaluate(resultsCode => {\n\t\t\t\tconst anchors = Array.from(document.querySelectorAll(resultsCode));\n\t\t\t\treturn anchors.map(anchor => {\n\t\t\t\t\tconst title = anchor.textContent;\n\t\t\t\t\treturn title;\n\t\t\t\t});\n\t\t\t}, resultsCode);\n\n\t\t\t// search result saving part in MongoDB\n\t\t\t//MongoDB connecting\n\t\t\tMongoClient.connect(url, function(err, db) {\n\t\t\t\tif (err) throw err;\n\t\t\t\tvar dbo = db.db(\"myflightdb\");\n\n\t\t\t\tfor(var i = 2; i < linksPrice.length; i+=2){\n\t\t\t\t\tvar myobj = { name: \"FlyTickets\", carriername: linksCarriername[i], departtime: linksTime[i*2], departcode: linksCode[i*2], desttime: linksTime[i*2+1], destcode: linksCode[i*2+1], price: linksPrice[i]};\n\t\t\t\t\tvar myobj1 = { name: \"FlyTickets\", carriername: linksCarriername[i+1], departtime: linksTime[i*2+2], departcode: linksCode[i*2+2], desttime: linksTime[i*2+3], destcode: linksCode[i*2+3], price: linksPrice[i+1]};\n\t\t\t\t\t// result input\n\t\t\t\t\tdbo.collection(\"tickets\").insertOne(myobj, function(err, res) {\n\t\t\t\t\t\tif (err) throw err;\n\t\t\t\t\t});\n\t\t\t\t\tdbo.collection(\"tickets\").insertOne(myobj1, function(err, res) {\n\t\t\t\t\t\tif (err) throw err;\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tdb.close();\n\n\t\t\t});\n\t\t\tawait browser.close();\n\t\t})();\n\n\t\treturn true;\n\t}", "function createXMLDownloadLink(dlXmlElm, xmlString, resultFilename) {\n if (window.navigator && window.navigator.msSaveBlob) { // for IE and Edge\n dlXmlElm.addEventListener('click', function(e) {\n e.preventDefault();\n navigator.msSaveBlob( new Blob(['<?xml version=\"1.0\" encoding=\"UTF-8\"?>' + xmlString], {type:'text/xml'}), resultFilename );\n }, false);\n } else {\n dlXmlElm.href = 'data:text/xml;charset=utf-8,' + encodeURIComponent(xmlString);\n dlXmlElm.download = resultFilename;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch all existing project issues from GitLab assigns gitLab.gitlabIssues
function getGitLabProjectIssues() { return getRemainingGitLabProjectIssues(0, 100) .then(function(result) { log_progress("Fetched " + result.length + " GitLab issues."); var issues = _.indexBy(result, 'iid'); return gitLab.gitlabIssues = issues; }); }
[ "function getIssues() {\n TestService.getTestCaseWorkItemsByType(test.id, 'BUG').\n then(function(rs) {\n if (rs.success) {\n vm.issues = rs.data;\n if (test.workItems.length && vm.attachedIssue) {\n angular.copy(vm.attachedIssue, vm.newIssue);\n }\n } else {\n messageService.error(rs.message);\n }\n });\n }", "function getAllIssues() {\n // Fetches all issues from server\n fetch('http://localhost:1234/whap/issues?' + 'getAllIssues')\n .then((resp) => resp.json())\n .then(function(data) {\n // Loads them all into fuck\n fuck = data[\"result\"];\n });\n}", "function initIssues() {\n\t//ids start at 5 so fill in 0-4 to make retrieval bawed on array index trivial\n\tissues = [0, 0, 0, 0, 0,\n {id:5,\tname:\"Alumni\"},\n\t\t\t{id:6,\tname:\"Animals\"},\n\t\t\t{id:7,\tname:\"Children\"},\n\t\t\t{id:8,\tname:\"Disabilities\"},\n\t\t\t{id:9,\tname:\"Disasters\"},\n\t\t\t{id:10,\tname:\"Education\"},\n\t\t\t{id:11,\tname:\"Elderly\"},\n\t\t\t{id:12,\tname:\"Environment\"},\n\t\t\t{id:13,\tname:\"Female Issues\"},\n\t\t\t{id:14, name:\"Fine Arts\"},\n\t\t\t{id:15,\tname:\"General Service\"},\n\t\t\t{id:16,\tname:\"Health\"},\n\t\t\t{id:17,\tname:\"Male Issues\"},\n\t\t\t{id:18, name:\"Minority Issues\"},\n\t\t\t{id:19,\tname:\"Office\"},\n\t\t\t{id:20,\tname:\"Patriotic\"},\n\t\t\t{id:21,\tname:\"Poverty\"},\n\t\t\t{id:22,\tname:\"PR\"},\n\t\t\t{id:23,\tname:\"Recreation\"},\n\t\t\t{id:24,\tname:\"Religious\"},\n\t\t\t{id:25,\tname:\"Service Leaders\"},\n\t\t\t{id:26,\tname:\"Technology\"}\n\t\t\t];\n}", "function getIssuesByProjectId(id){\n var deferred = $q.defer();\n\n $http.get(BASE_URL + 'projects/' + id + '/issues')\n .then(function(response){\n deferred.resolve(response.data);\n });\n\n return deferred.promise;\n }", "getV3ProjectsIdMergeRequestsMergeRequestIdClosesIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number |\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdMergeRequestsMergeRequestIdClosesIssues(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "async function transferIssues(owner, repo, projectId) {\n inform(\"Transferring Issues\");\n\n // Because each\n let milestoneData = await getAllGHMilestones(owner, repo);\n\n // get a list of all GitLab issues associated with this project\n // TODO return all issues via pagination\n let issues = await gitlab.Issues.all({projectId: projectId});\n\n // sort issues in ascending order of their issue number (by iid)\n issues = issues.sort((a, b) => a.iid - b.iid);\n\n // get a list of the current issues in the new GitHub repo (likely to be empty)\n let ghIssues = await getAllGHIssues(settings.github.owner, settings.github.repo);\n\n console.log(\"Transferring \" + issues.length.toString() + \" issues\");\n\n //\n // Create Placeholder Issues\n //\n\n for (let i=0; i<issues.length; i++) {\n // GitLab issue internal Id (iid)\n let expectedIdx = i+1;\n\n // is there a gap in the GitLab issues?\n // Create placeholder issues so that new GitHub issues will have the same\n // issue number as in GitLab. If a placeholder is used it is because there\n // was a gap in GitLab issues -- likely caused by a deleted GitLab issue.\n if (issues[i].iid != expectedIdx) {\n issues.splice(i, 0, {\n iid: expectedIdx,\n title: `placeholder issue for issue ${expectedIdx} which does not exist and was probably deleted in GitLab`,\n description: 'This is to ensure the issue numbers in GitLab and GitHub are the same',\n state: 'closed'\n });\n i++;\n console.log(\"Added placeholder issue for GitLab issue #\" + expectedIdx)\n }\n }\n\n //\n // Create GitHub issues for each GitLab issue\n //\n\n // if a GitLab issue does not exist in GitHub repo, create it -- along with comments.\n for (let issue of issues) {\n // TODO: get slice from issues instead of condition\n if (issue.iid < start || issue.iid > end) {\n continue\n }\n // try to find a GitHub issue that already exists for this GitLab issue\n let ghIssue = ghIssues.find(i => i.title.trim() === issue.title.trim() + \" - [glis:\" + issue.iid + \"]\");\n if (!ghIssue) {\n console.log(\"Creating: \" + issue.iid + \" - \" + issue.title);\n try {\n\n // process asynchronous code in sequence -- treats the code sort of like blocking\n await createIssueAndComments(settings.github.owner, settings.github.repo, milestoneData, issue);\n\n } catch (err) {\n console.error(\"Could not create issue: \" + issue.iid + \" - \" + issue.title);\n console.error(err);\n process.exit(1);\n }\n } else {\n console.log(\"Already exists: \" + issue.iid + \" - \" + issue.title);\n updateIssueState(ghIssue, issue);\n }\n };\n\n}", "getV3GroupsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.GroupsApi()\n/*let id = \"id_example\";*/ // String | The ID of a grou\n/*let opts = {\n 'state': \"'opened'\", // String | Return opened, closed, or all issues\n 'labels': \"labels_example\", // String | Comma-separated list of label names\n 'milestone': \"milestone_example\", // String | Return issues for a specific milestone\n 'orderBy': \"'created_at'\", // String | Return issues ordered by `created_at` or `updated_at` fields.\n 'sort': \"'desc'\", // String | Return issues sorted in `asc` or `desc` order.\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3GroupsIdIssues(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "getV3ProjectsIdMergeRequestMergeRequestIdClosesIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number |\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdMergeRequestMergeRequestIdClosesIssues(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "async function getAllIssues() {\n var issues;\n\n await axios\n \n axios.get(\"http://singhealthdb.herokuapp.com/api/issue/audit_id_param\", {\n params: { secret_token: token, audit_id : audit_id },\n })\n .then(\n resarr=>{\n //alert(\"hello\");\n issues = Object.values(resarr.data);\n console.log(issues);\n //setIssues(issues);\n categoriseIssues(issues);\n setLoading(false);\n setAuditResolved(issues);\n }\n \n )\n .catch((error) => {\n setIssues([]);\n setLoading(false);\n console.log(error);\n });\n }", "getV3ProjectsIdIssuesIssueIdAwardEmoji(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let issueId = 56;*/ // Number | The ID of an Issue, Merge Request or Snippe\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdIssuesIssueIdAwardEmoji(incomingOptions.id, incomingOptions.issueId, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "async function transferIssues() {\n inform('Transferring Issues');\n\n // Because each\n let milestoneData = await githubHelper.getAllGithubMilestones();\n\n // get a list of all GitLab issues associated with this project\n // TODO return all issues via pagination\n let issues = await gitlabApi.Issues.all({\n projectId: settings.gitlab.projectId,\n });\n\n // sort issues in ascending order of their issue number (by iid)\n issues = issues.sort((a, b) => a.iid - b.iid);\n\n // get a list of the current issues in the new GitHub repo (likely to be empty)\n let githubIssues = await githubHelper.getAllGithubIssues();\n\n console.log(`Transferring ${issues.length} issues.`);\n\n if (settings.usePlaceholderIssuesForMissingIssues) {\n for (let i = 0; i < issues.length; i++) {\n // GitLab issue internal Id (iid)\n let expectedIdx = i + 1;\n\n // is there a gap in the GitLab issues?\n // Create placeholder issues so that new GitHub issues will have the same\n // issue number as in GitLab. If a placeholder is used it is because there\n // was a gap in GitLab issues -- likely caused by a deleted GitLab issue.\n if (issues[i].iid !== expectedIdx) {\n issues.splice(i, 0, createPlaceholderIssue(expectedIdx));\n issueCounters.nrOfPlaceholderIssues++;\n console.log(\n `Added placeholder issue for GitLab issue #${expectedIdx}.`\n );\n }\n }\n }\n\n //\n // Create GitHub issues for each GitLab issue\n //\n\n // if a GitLab issue does not exist in GitHub repo, create it -- along with comments.\n for (let issue of issues) {\n // try to find a GitHub issue that already exists for this GitLab issue\n let githubIssue = githubIssues.find(\n i => i.title.trim() === issue.title.trim()\n );\n if (!githubIssue) {\n console.log(`\\nMigrating issue #${issue.iid} ('${issue.title}')...`);\n try {\n // process asynchronous code in sequence -- treats the code sort of like blocking\n await githubHelper.createIssueAndComments(milestoneData, issue);\n console.log(`\\t...DONE migrating issue #${issue.iid}.`);\n } catch (err) {\n console.log(`\\t...ERROR while migrating issue #${issue.iid}.`);\n\n console.error('DEBUG:\\n', err); // TODO delete this after issue-migration-fails have been fixed\n\n if (settings.useReplacementIssuesForCreationFails) {\n console.log('\\t-> creating a replacement issue...');\n const replacementIssue = createReplacementIssue(\n issue.iid,\n issue.title,\n issue.state\n );\n\n try {\n await githubHelper.createIssueAndComments(\n milestoneData,\n replacementIssue\n );\n\n issueCounters.nrOfReplacementIssues++;\n console.error('\\t...DONE.');\n } catch (err) {\n issueCounters.nrOfFailedIssues++;\n console.error(\n '\\t...ERROR: Could not create replacement issue either!'\n );\n }\n }\n }\n } else {\n console.log(`Updating issue #${issue.iid} - ${issue.title}...`);\n try {\n await githubHelper.updateIssueState(githubIssue, issue);\n console.log(`...Done updating issue #${issue.iid}.`);\n } catch (err) {\n console.log(`...ERROR while updating issue #${issue.iid}.`);\n }\n }\n }\n\n // print statistics about issue migration:\n console.log(`DONE creating issues.`);\n console.log(`\\n\\tStatistics:`);\n console.log(`\\tTotal nr. of issues: ${issues.length}`);\n console.log(\n `\\tNr. of used placeholder issues: ${issueCounters.nrOfPlaceholderIssues}`\n );\n console.log(\n `\\tNr. of used replacement issues: ${issueCounters.nrOfReplacementIssues}`\n );\n console.log(\n `\\tNr. of issue migration fails: ${issueCounters.nrOfFailedIssues}`\n );\n}", "function listMyIssues(){\n\n logDebug('listMyIssues: Starting getting my issues for...');\n log( ['comments', 'title', 'state', 'body', 'id' ].join(sep) );\n\n var request = $.ajax({\n\n url: 'https://api.github.com/issues?access_token=' + oauthToken.token,\n type: 'GET',\n\n \n success: function(data, textStatus, jqXHR){\n logDebug('listMyIssues: Yea, it worked...' + textStatus + ' - ' + JSON.stringify(data) );\n\n $.each( data, function(index, value) {\n value.body = value.body.replace(/(\\r\\n|\\n|\\r)/gm,\"\");\n\n log( [value.comments, value.title, value.state, value.body, value.id ].join(sep) );\n });\n\n parseHttpHeaders(jqXHR);\n\n },\n\n error: function(data){\n logErr('listMyIssues: Shit hit the fan...' + JSON.stringify(data));\n\n }\n\n });\n\n return request;\n\n}", "async function createRepositoryIssues({ issues }) {\n const issuesHTML = HtmlBuilder.div()\n .addClass('repository-detail__issues mb-3 border p-3')\n let issueDetailHTML = createIssueDetail({ issue: undefined })\n\n if (!issues || issues.length <= 0) {\n return issuesHTML.append(HtmlBuilder.div(\"Não há issues\"))\n }\n\n async function fetchAndFillIssueDetail({ issue }) {\n const { comments_url } = issue\n const issueComments = await _gitHubService.fetchIssueComments(comments_url)\n issueDetailHTML.html(createIssueDetail({ issue, issueComments }))\n moveToPageElemnt(\"#issue-detail\")\n }\n\n const issuesTableHTML = HtmlBuilder.table(\"\")\n .addClass('table table-striped border')\n .attr('id', 'issues-table')\n const theadHTML = HtmlBuilder.thead(\"\")\n .append(HtmlBuilder.tr()\n .append(HtmlBuilder.th(\"Nome\"))\n .append(HtmlBuilder.th(\"Status\").attr(DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN, DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN))\n .append(HtmlBuilder.th(\"Detalhes\")))\n const tbodyHTML = HtmlBuilder.tbody(\"\")\n\n for (issue of issues) {\n const issueWithoutCache = issue\n const { title, state } = issueWithoutCache\n\n function onOpenIssueDetail() { fetchAndFillIssueDetail({ issue: issueWithoutCache }) }\n\n const trHTML = HtmlBuilder.tr(\"\")\n .append(HtmlBuilder.td(`${title}`))\n .append(HtmlBuilder.td(`${state}`))\n .append(HtmlBuilder.td(HtmlBuilder.button(\"Mais\")\n .addClass('btn btn-primary')\n .click(onOpenIssueDetail)))\n\n tbodyHTML.append(trHTML)\n }\n\n issuesTableHTML.append(theadHTML).append(tbodyHTML)\n issuesHTML\n .append(HtmlBuilder.h3(\"Issues\"))\n .append(issuesTableHTML)\n .append(HtmlBuilder.hr())\n .append(issueDetailHTML)\n\n _dataTableFactory.of(issuesTableHTML)\n\n return issuesHTML\n }", "postV3ProjectsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssues(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "createIssueListofMilestone() {\n let milestoneIssues = [];\n let milestoneTitle = this.props.data[\"title\"];\n this.props.issueList.forEach(function (issue) {\n if (issue[\"milestone\"] != null) {\n if (issue[\"milestone\"][\"title\"] === milestoneTitle) {\n let object = {\n url: issue[\"url\"],\n html_url: issue[\"html_url\"],\n title: issue[\"issue_title\"],\n };\n milestoneIssues.push(object)\n }\n }\n });\n\n return milestoneIssues;\n }", "function get_issues(issue_callback, end_callback) {\n _get_issues(0, 0, issue_callback, end_callback);\n}", "getV3ProjectsIdRepositoryCommitsShaComments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | A commit sha, or the name of a branch or ta\n/*let opts = {\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdRepositoryCommitsShaComments(incomingOptions.id, incomingOptions.sha, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "getV3ProjectsIdRepositoryCommitsShaStatuses(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit has\n/*let opts = {\n 'ref': \"ref_example\", // String | The ref\n 'stage': \"stage_example\", // String | The stage\n 'name': \"name_example\", // String | The name\n 'all': \"all_example\", // String | Show all statuses, default: false\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdRepositoryCommitsShaStatuses(incomingOptions.id, incomingOptions.sha, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }", "get withPullRequest() {\n return issues.filter(obj => obj.pull_request !== undefined\n && obj.pull_request !== null)\n .map(obj => obj.id);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns compiled solidity code.
eth_compileSolidity(code) { return this.request("eth_compileSolidity", Array.from(arguments)); }
[ "function compile(code, output) {\n\tvar syntax = esprima.parse(code);\n\tvar compiler = new FirstPassCodeGen();\n\tvar module = compiler.compile(syntax);\n\tmodule.resolve();\n\tmodule.output(output);\n\treturn true;\n}", "eth_compileSerpent(code) {\n return this.request(\"eth_compileSerpent\", Array.from(arguments));\n }", "function getBytecode() {\n console.log(web3.eth.getCode(crowdsale.address));\n//\"0x\"\n//data: '0x' + bytecode\n}", "generate() {\n var ast = this.ast;\n\n this.print(ast);\n this.catchUp();\n\n return {\n code: this.buffer.get(this.opts),\n tokens: this.buffer.tokens,\n directives: this.directives\n };\n }", "Program() {\n return factory.Program(this.StatementList());\n }", "_compile(content, filename, filename2) {\n\n content = internalModule.stripShebang(content);\n\n // create wrapper function\n var wrapper = Module.wrap(content);\n\n var compiledWrapper = vm.runInThisContext(wrapper, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true\n });\n\n var inspectorWrapper = null;\n if (process._breakFirstLine && process._eval == null) {\n if (!resolvedArgv) {\n // we enter the repl if we're not given a filename argument.\n if (process.argv[1]) {\n resolvedArgv = Module._resolveFilename(process.argv[1], null, false);\n } else {\n resolvedArgv = 'repl';\n }\n }\n\n // Set breakpoint on module start\n if (filename2 === resolvedArgv) {\n delete process._breakFirstLine;\n inspectorWrapper = process.binding('inspector').callAndPauseOnStart;\n if (!inspectorWrapper) {\n const Debug = vm.runInDebugContext('Debug');\n Debug.setBreakPoint(compiledWrapper, 0, 0);\n }\n }\n }\n var dirname = path.dirname(filename);\n var require = internalModule.makeRequireFunction(this);\n var result;\n if (inspectorWrapper) {\n result = inspectorWrapper(compiledWrapper, this.exports, this.exports,\n require, this, filename, dirname, require.resolve);\n } else {\n result = compiledWrapper.call(this.exports, this.exports, require, this,\n filename, dirname, require.resolve);\n }\n return result;\n }", "function generateProgram()\n\t{\n\t\t// Start code generation from the root\n\t\tgenerateStatement(_AST.root);\n\t\t// Place a break statement after the program to pad the static data\n\t\t_ByteCodeList.push(\"00\");\n\t}", "function compileContracts (target_name) {\n let genFuns = target_genFuns.map(objFun => generateGenFuns(objFun)).join('');\n let payFuns = target_payFuns.map(objFun => generatePayFuns(objFun)).join('');\n let fallback_list = filterForFallback();\n\n fallback_list.map(objFun => generateFallbackFuns(objFun)).reduce(function (acc, objFun, index) {\n fs.writeFileSync(`${solPath}/Attack_${target_name}${index}.sol`, generateConstructor(target_name, index) + genFuns + payFuns + objFun);\n // console.log(`Attack contract ${target_name}${index} is saved!`);\n }, {});\n\n /// generate its deploy configure\n generateMigration(fallback_list.length);\n}", "function make_helper_for_contract(contract_name) {\n\n\n var contract = compiled_contracts_json[contract_name]\n var iface = JSON.parse(contract.interface) // note interface appears to be in a string rather than json so need to parse\n\n console.log(\"\\nBuilding helper for\", contract_name, \"...\")\n // console.log(\"contract: \",contract)\n\n\n\n // ********* set output compiled_file ***************\n\n var output_file = process.cwd() + mushroom_config.structure.helper_output_directory + contract_name + '_helper.js'\n\n console.log(\" ---> output_file: \", contract_name + '_helper.js')\n\n\n\n // ********* read in and customise header ****************\n\n // read in header_template\n var header_file = process.cwd() + mushroom_config.structure.helper_generator_location + 'helper_template_header.js';\n var header_str = fs.readFileSync(header_file).toString();\n\n // get host:ip from config and substitute\n var host_ip = '\\\"http://' + contract_config.rpc.host + \":\" + contract_config.rpc.port + '\\\"';\n header_str = header_str.replace(/sub_geth_host_port/g, host_ip);\n\n\n\n // ********** get deployed address ***********************\n\n var contract_ind\n for (var i in deployed_json.contracts) {\n if (deployed_json.contracts[i].name == contract_name) {\n // console.log(\"contract_name: \", contract_name)\n contract_ind = i;\n }\n }\n\n var deployed_address = deployed_json.contracts[contract_ind].details.address\n console.log(\" ---> deployed address: \", deployed_address)\n\n\n\n // ********** read in and customise module vars *************\n\n // read in helper_object_def template\n var module_vars_file = process.cwd() + mushroom_config.structure.helper_generator_location + 'helper_template_module_vars.js';\n var module_vars_str = fs.readFileSync(module_vars_file).toString();\n\n module_vars_str = module_vars_str.replace(/sub_abi/g, JSON.stringify(iface));\n module_vars_str = module_vars_str.replace(/sub_address/g, deployed_address)\n\n\n\n // ********** get number of methods in contract and generate method calls********************\n\n // console.log(\"contract: \", contract)\n\n var num_methods = iface.length\n console.log(\" ---> num_methods: \", num_methods)\n console.log(\" ---> methods:\")\n\n var method_strs = []; // stores the output strings for each method\n\n for (var i = 0; i < num_methods; i++) {\n\n var method = iface[i];\n\n var method_name = method.name;\n console.log(\" ---> \", method_name)\n\n if (method_name == undefined) {\n break;\n }\n\n\n // make the number of method arguments in the helper method to match the contract method\n var num_args = method.inputs.length\n\n var arg_str = '';\n var arg_log_str = ''\n\n for (var j = 0; j < (num_args + 1); j++) {\n arg_str = arg_str + 'args[' + j + '],';\n arg_log_str = arg_log_str + '\\\" ---> args[' + j + ']:\\\", args[' + j + '],'\n\n }\n\n // trim off trailing ','\n arg_str = arg_str.slice(0, arg_str.length - 1)\n arg_log_str = arg_log_str.slice(0, arg_log_str.length - 1)\n\n // check strings\n // console.log(\"arg_str: \", arg_str)\n // console.log(\"log_arg_str: \", arg_log_str, \"\\n\")\n\n\n // read in helper_method template (either tx or call depending if method is constant)\n var method_file;\n if (method.constant) {\n method_file = process.cwd() + mushroom_config.structure.helper_generator_location + 'helper_template_method_call.js';\n\n } else {\n\n method_file = process.cwd() + mushroom_config.structure.helper_generator_location + 'helper_template_method_sendtx.js';\n }\n\n method_strs[i] = fs.readFileSync(method_file).toString();\n\n // substitutions to make method specific\n method_strs[i] = method_strs[i].replace(/sub_method/g, method_name)\n method_strs[i] = method_strs[i].replace(/sub_args/g, arg_str)\n method_strs[i] = method_strs[i].replace(/sub_log_args/g, arg_log_str)\n\n }\n\n // creates a single string with all methods in\n var method_str = ''\n for (var i in method_strs) {\n method_str = method_str + method_strs[i]\n }\n\n\n // ********** create module.exports str *************\n\n var exports_str = 'module.exports = Contract;';\n\n\n // *********** create and write the complete output string to the output file_to_compile ***********\n\n var output_str = header_str + module_vars_str + method_str + exports_str\n\n fs.writeFileSync(output_file, output_str);\n\n}", "function run_code() {\n // if (document.getElementById(\"panel_output\").attributes.getNamedItem('data-status').nodeValue == 'closed'){\n // t = document.getElementsByClassName(\"toggler\");\n // for (i = 0; i < t.length; i++) {\n // if (t[i].attributes.getNamedItem('order').nodeValue == 'two'){\n //\n // t[i].click();\n // }\n // }\n // }\n // console.log(\"in run_code()\");\n var output_layout = myLayout.east.children.layout1;\n myLayout.open(\"east\");\n output_layout.open(\"south\");\n var code_val = '';\n\n if (isBlockly) {\n var pycode = document.getElementById(\"python_code\");\n\n pycode.value = Blockly.Python.workspaceToCode(Blockly.getMainWorkspace());\n pycode.innerHTML = pycode.value;\n code_val = Blockly.Python.workspaceToCode(Blockly.getMainWorkspace());\n backup_blocks();\n } else {\n code_val = editor.getValue();\n }\n // AJL: Should now be able to remove this and the textarea referenced. Or not because of Skulpt\n $('#code2').empty();\n $('#code2').text(code_val);\n\n pretty();\n \n if (NO_SKULPT == false) {\n runit();\n }\n Blockly.fireUiEvent(window, 'resize');\n return code_val;\n}", "function _glsl() {\n\treturn {\n\t\ttransform(code, id) {\n\t\t\tif (/\\.glsl$/.test(id) === false) return;\n\t\t\tvar transformedCode = 'export default ' + JSON.stringify(\n\t\t\t\tcode\n\t\t\t\t\t.replace( /[ \\t]*\\/\\/.*\\n/g, '' ) // remove //\n\t\t\t\t\t.replace( /[ \\t]*\\/\\*[\\s\\S]*?\\*\\//g, '' ) // remove /* */\n\t\t\t\t\t.replace( /\\n{2,}/g, '\\n' ) // # \\n+ to \\n\n\t\t\t) + ';';\n\t\t\treturn {\n\t\t\t\tcode: transformedCode,\n\t\t\t\tmap: { mappings: '' }\n\t\t\t};\n\t\t}\n\t};\n}", "function fillTemplate(contractName, contractArgs) {\n return `'use strict'\nObject.defineProperty(exports, '__esModule', { value: true })\nconst contract = require('@truffle/contract')\nconst ${contractName} = contract(${JSON.stringify(contractArgs, null, 1)})\n\nif (process.env.NODE_ENV === 'test') {\n try {\n eval('${contractName}.setProvider(web3.currentProvider)')\n } catch (e) {}\n}\n\nexports.${contractName} = ${contractName}\n`;\n}", "program() {\n this.eat(tokens.PROGRAM);\n const varNode = this.variable();\n const progNode = varNode.value;\n this.eat(tokens.semi);\n const blockNode = this.block();\n const programNode = new Program(progNode, blockNode);\n this.eat(tokens.dot);\n return programNode;\n }", "function jsCompile() {\n return src(jsSrc)\n .pipe(sourceMaps.init())\n .pipe(concat('min.js'))\n .pipe(terser())\n .pipe(sourceMaps.write('.'))\n .pipe(gulp.dest('dist/js'));\n}", "function generateJavascript(ast, options) {\n\t /* These only indent non-empty lines to avoid trailing whitespace. */\n\t function indent2(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\t function indent4(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\t function indent8(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\t function indent10(code) { return code.replace(/^(.+)$/gm, ' $1'); }\n\n\t function generateTables() {\n\t if (options.optimize === \"size\") {\n\t return [\n\t 'peg$consts = [',\n\t indent2(ast.consts.join(',\\n')),\n\t '],',\n\t '',\n\t 'peg$bytecode = [',\n\t indent2(arrays.map(ast.rules, function(rule) {\n\t return 'peg$decode(\"'\n\t + js.stringEscape(arrays.map(\n\t rule.bytecode,\n\t function(b) { return String.fromCharCode(b + 32); }\n\t ).join(''))\n\t + '\")';\n\t }).join(',\\n')),\n\t '],'\n\t ].join('\\n');\n\t } else {\n\t return arrays.map(\n\t ast.consts,\n\t function(c, i) { return 'peg$c' + i + ' = ' + c + ','; }\n\t ).join('\\n');\n\t }\n\t }\n\n\t function generateRuleHeader(ruleNameCode, ruleIndexCode) {\n\t var parts = [];\n\n\t parts.push('');\n\n\t if (options.trace) {\n\t parts.push([\n\t 'peg$trace({',\n\t ' type: \"rule.enter\",',\n\t ' rule: ' + ruleNameCode,\n\t '});',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t if (options.cache) {\n\t parts.push([\n\t 'var key = peg$currPos * ' + ast.rules.length + ' + ' + ruleIndexCode + ',',\n\t ' cached = peg$cache[key];',\n\t '',\n\t 'if (cached) {',\n\t ' peg$currPos = cached.nextPos;',\n\t '',\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t 'if (cached.result !== peg$FAILED) {',\n\t ' peg$trace({',\n\t ' type: \"rule.match\",',\n\t ' rule: ' + ruleNameCode + ',',\n\t ' result: cached.result',\n\t ' });',\n\t '} else {',\n\t ' peg$trace({',\n\t ' type: \"rule.fail\",',\n\t ' rule: ' + ruleNameCode,\n\t ' });',\n\t '}',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' return cached.result;',\n\t '}',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t return parts.join('\\n');\n\t }\n\n\t function generateRuleFooter(ruleNameCode, resultCode) {\n\t var parts = [];\n\n\t if (options.cache) {\n\t parts.push([\n\t '',\n\t 'peg$cache[key] = { nextPos: peg$currPos, result: ' + resultCode + ' };'\n\t ].join('\\n'));\n\t }\n\n\t if (options.trace) {\n\t parts.push([\n\t '',\n\t 'if (' + resultCode + ' !== peg$FAILED) {',\n\t ' peg$trace({',\n\t ' type: \"rule.match\",',\n\t ' rule: ' + ruleNameCode + ',',\n\t ' result: ' + resultCode,\n\t ' });',\n\t '} else {',\n\t ' peg$trace({',\n\t ' type: \"rule.fail\",',\n\t ' rule: ' + ruleNameCode,\n\t ' });',\n\t '}'\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t '',\n\t 'return ' + resultCode + ';'\n\t ].join('\\n'));\n\n\t return parts.join('\\n');\n\t }\n\n\t function generateInterpreter() {\n\t var parts = [];\n\n\t function generateCondition(cond, argsLength) {\n\t var baseLength = argsLength + 3,\n\t thenLengthCode = 'bc[ip + ' + (baseLength - 2) + ']',\n\t elseLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';\n\n\t return [\n\t 'ends.push(end);',\n\t 'ips.push(ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ');',\n\t '',\n\t 'if (' + cond + ') {',\n\t ' end = ip + ' + baseLength + ' + ' + thenLengthCode + ';',\n\t ' ip += ' + baseLength + ';',\n\t '} else {',\n\t ' end = ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ';',\n\t ' ip += ' + baseLength + ' + ' + thenLengthCode + ';',\n\t '}',\n\t '',\n\t 'break;'\n\t ].join('\\n');\n\t }\n\n\t function generateLoop(cond) {\n\t var baseLength = 2,\n\t bodyLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';\n\n\t return [\n\t 'if (' + cond + ') {',\n\t ' ends.push(end);',\n\t ' ips.push(ip);',\n\t '',\n\t ' end = ip + ' + baseLength + ' + ' + bodyLengthCode + ';',\n\t ' ip += ' + baseLength + ';',\n\t '} else {',\n\t ' ip += ' + baseLength + ' + ' + bodyLengthCode + ';',\n\t '}',\n\t '',\n\t 'break;'\n\t ].join('\\n');\n\t }\n\n\t function generateCall() {\n\t var baseLength = 4,\n\t paramsLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';\n\n\t return [\n\t 'params = bc.slice(ip + ' + baseLength + ', ip + ' + baseLength + ' + ' + paramsLengthCode + ');',\n\t 'for (i = 0; i < ' + paramsLengthCode + '; i++) {',\n\t ' params[i] = stack[stack.length - 1 - params[i]];',\n\t '}',\n\t '',\n\t 'stack.splice(',\n\t ' stack.length - bc[ip + 2],',\n\t ' bc[ip + 2],',\n\t ' peg$consts[bc[ip + 1]].apply(null, params)',\n\t ');',\n\t '',\n\t 'ip += ' + baseLength + ' + ' + paramsLengthCode + ';',\n\t 'break;'\n\t ].join('\\n');\n\t }\n\n\t parts.push([\n\t 'function peg$decode(s) {',\n\t ' var bc = new Array(s.length), i;',\n\t '',\n\t ' for (i = 0; i < s.length; i++) {',\n\t ' bc[i] = s.charCodeAt(i) - 32;',\n\t ' }',\n\t '',\n\t ' return bc;',\n\t '}',\n\t '',\n\t 'function peg$parseRule(index) {',\n\t ' var bc = peg$bytecode[index],',\n\t ' ip = 0,',\n\t ' ips = [],',\n\t ' end = bc.length,',\n\t ' ends = [],',\n\t ' stack = [],',\n\t ' params, i;',\n\t ].join('\\n'));\n\n\t parts.push(indent2(generateRuleHeader('peg$ruleNames[index]', 'index')));\n\n\t parts.push([\n\t /*\n\t * The point of the outer loop and the |ips| & |ends| stacks is to avoid\n\t * recursive calls for interpreting parts of bytecode. In other words, we\n\t * implement the |interpret| operation of the abstract machine without\n\t * function calls. Such calls would likely slow the parser down and more\n\t * importantly cause stack overflows for complex grammars.\n\t */\n\t ' while (true) {',\n\t ' while (ip < end) {',\n\t ' switch (bc[ip]) {',\n\t ' case ' + op.PUSH + ':', // PUSH c\n\t ' stack.push(peg$consts[bc[ip + 1]]);',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_UNDEFINED + ':', // PUSH_UNDEFINED\n\t ' stack.push(void 0);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_NULL + ':', // PUSH_NULL\n\t ' stack.push(null);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_FAILED + ':', // PUSH_FAILED\n\t ' stack.push(peg$FAILED);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_EMPTY_ARRAY + ':', // PUSH_EMPTY_ARRAY\n\t ' stack.push([]);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.PUSH_CURR_POS + ':', // PUSH_CURR_POS\n\t ' stack.push(peg$currPos);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.POP + ':', // POP\n\t ' stack.pop();',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.POP_CURR_POS + ':', // POP_CURR_POS\n\t ' peg$currPos = stack.pop();',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.POP_N + ':', // POP_N n\n\t ' stack.length -= bc[ip + 1];',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.NIP + ':', // NIP\n\t ' stack.splice(-2, 1);',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.APPEND + ':', // APPEND\n\t ' stack[stack.length - 2].push(stack.pop());',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.WRAP + ':', // WRAP n\n\t ' stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.TEXT + ':', // TEXT\n\t ' stack.push(input.substring(stack.pop(), peg$currPos));',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.IF + ':', // IF t, f\n\t indent10(generateCondition('stack[stack.length - 1]', 0)),\n\t '',\n\t ' case ' + op.IF_ERROR + ':', // IF_ERROR t, f\n\t indent10(generateCondition(\n\t 'stack[stack.length - 1] === peg$FAILED',\n\t 0\n\t )),\n\t '',\n\t ' case ' + op.IF_NOT_ERROR + ':', // IF_NOT_ERROR t, f\n\t indent10(\n\t generateCondition('stack[stack.length - 1] !== peg$FAILED',\n\t 0\n\t )),\n\t '',\n\t ' case ' + op.WHILE_NOT_ERROR + ':', // WHILE_NOT_ERROR b\n\t indent10(generateLoop('stack[stack.length - 1] !== peg$FAILED')),\n\t '',\n\t ' case ' + op.MATCH_ANY + ':', // MATCH_ANY a, f, ...\n\t indent10(generateCondition('input.length > peg$currPos', 0)),\n\t '',\n\t ' case ' + op.MATCH_STRING + ':', // MATCH_STRING s, a, f, ...\n\t indent10(generateCondition(\n\t 'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]',\n\t 1\n\t )),\n\t '',\n\t ' case ' + op.MATCH_STRING_IC + ':', // MATCH_STRING_IC s, a, f, ...\n\t indent10(generateCondition(\n\t 'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]',\n\t 1\n\t )),\n\t '',\n\t ' case ' + op.MATCH_REGEXP + ':', // MATCH_REGEXP r, a, f, ...\n\t indent10(generateCondition(\n\t 'peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))',\n\t 1\n\t )),\n\t '',\n\t ' case ' + op.ACCEPT_N + ':', // ACCEPT_N n\n\t ' stack.push(input.substr(peg$currPos, bc[ip + 1]));',\n\t ' peg$currPos += bc[ip + 1];',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.ACCEPT_STRING + ':', // ACCEPT_STRING s\n\t ' stack.push(peg$consts[bc[ip + 1]]);',\n\t ' peg$currPos += peg$consts[bc[ip + 1]].length;',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.FAIL + ':', // FAIL e\n\t ' stack.push(peg$FAILED);',\n\t ' if (peg$silentFails === 0) {',\n\t ' peg$fail(peg$consts[bc[ip + 1]]);',\n\t ' }',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.REPORT_SAVED_POS + ':', // REPORT_SAVED_POS p\n\t ' peg$reportedPos = stack[stack.length - 1 - bc[ip + 1]];',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.REPORT_CURR_POS + ':', // REPORT_CURR_POS\n\t ' peg$reportedPos = peg$currPos;',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.CALL + ':', // CALL f, n, pc, p1, p2, ..., pN\n\t indent10(generateCall()),\n\t '',\n\t ' case ' + op.RULE + ':', // RULE r\n\t ' stack.push(peg$parseRule(bc[ip + 1]));',\n\t ' ip += 2;',\n\t ' break;',\n\t '',\n\t ' case ' + op.SILENT_FAILS_ON + ':', // SILENT_FAILS_ON\n\t ' peg$silentFails++;',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' case ' + op.SILENT_FAILS_OFF + ':', // SILENT_FAILS_OFF\n\t ' peg$silentFails--;',\n\t ' ip++;',\n\t ' break;',\n\t '',\n\t ' default:',\n\t ' throw new Error(\"Invalid opcode: \" + bc[ip] + \".\");',\n\t ' }',\n\t ' }',\n\t '',\n\t ' if (ends.length > 0) {',\n\t ' end = ends.pop();',\n\t ' ip = ips.pop();',\n\t ' } else {',\n\t ' break;',\n\t ' }',\n\t ' }'\n\t ].join('\\n'));\n\n\t parts.push(indent2(generateRuleFooter('peg$ruleNames[index]', 'stack[0]')));\n\t parts.push('}');\n\n\t return parts.join('\\n');\n\t }\n\n\t function generateRuleFunction(rule) {\n\t var parts = [], code;\n\n\t function c(i) { return \"peg$c\" + i; } // |consts[i]| of the abstract machine\n\t function s(i) { return \"s\" + i; } // |stack[i]| of the abstract machine\n\n\t var stack = {\n\t sp: -1,\n\t maxSp: -1,\n\n\t push: function(exprCode) {\n\t var code = s(++this.sp) + ' = ' + exprCode + ';';\n\n\t if (this.sp > this.maxSp) { this.maxSp = this.sp; }\n\n\t return code;\n\t },\n\n\t pop: function() {\n\t var n, values;\n\n\t if (arguments.length === 0) {\n\t return s(this.sp--);\n\t } else {\n\t n = arguments[0];\n\t values = arrays.map(arrays.range(this.sp - n + 1, this.sp + 1), s);\n\t this.sp -= n;\n\n\t return values;\n\t }\n\t },\n\n\t top: function() {\n\t return s(this.sp);\n\t },\n\n\t index: function(i) {\n\t return s(this.sp - i);\n\t }\n\t };\n\n\t function compile(bc) {\n\t var ip = 0,\n\t end = bc.length,\n\t parts = [],\n\t value;\n\n\t function compileCondition(cond, argCount) {\n\t var baseLength = argCount + 3,\n\t thenLength = bc[ip + baseLength - 2],\n\t elseLength = bc[ip + baseLength - 1],\n\t baseSp = stack.sp,\n\t thenCode, elseCode, thenSp, elseSp;\n\n\t ip += baseLength;\n\t thenCode = compile(bc.slice(ip, ip + thenLength));\n\t thenSp = stack.sp;\n\t ip += thenLength;\n\n\t if (elseLength > 0) {\n\t stack.sp = baseSp;\n\t elseCode = compile(bc.slice(ip, ip + elseLength));\n\t elseSp = stack.sp;\n\t ip += elseLength;\n\n\t if (thenSp !== elseSp) {\n\t throw new Error(\n\t \"Branches of a condition must move the stack pointer in the same way.\"\n\t );\n\t }\n\t }\n\n\t parts.push('if (' + cond + ') {');\n\t parts.push(indent2(thenCode));\n\t if (elseLength > 0) {\n\t parts.push('} else {');\n\t parts.push(indent2(elseCode));\n\t }\n\t parts.push('}');\n\t }\n\n\t function compileLoop(cond) {\n\t var baseLength = 2,\n\t bodyLength = bc[ip + baseLength - 1],\n\t baseSp = stack.sp,\n\t bodyCode, bodySp;\n\n\t ip += baseLength;\n\t bodyCode = compile(bc.slice(ip, ip + bodyLength));\n\t bodySp = stack.sp;\n\t ip += bodyLength;\n\n\t if (bodySp !== baseSp) {\n\t throw new Error(\"Body of a loop can't move the stack pointer.\");\n\t }\n\n\t parts.push('while (' + cond + ') {');\n\t parts.push(indent2(bodyCode));\n\t parts.push('}');\n\t }\n\n\t function compileCall() {\n\t var baseLength = 4,\n\t paramsLength = bc[ip + baseLength - 1];\n\n\t var value = c(bc[ip + 1]) + '('\n\t + arrays.map(\n\t bc.slice(ip + baseLength, ip + baseLength + paramsLength),\n\t function(p) { return stack.index(p); }\n\t ).join(', ')\n\t + ')';\n\t stack.pop(bc[ip + 2]);\n\t parts.push(stack.push(value));\n\t ip += baseLength + paramsLength;\n\t }\n\n\t while (ip < end) {\n\t switch (bc[ip]) {\n\t case op.PUSH: // PUSH c\n\t parts.push(stack.push(c(bc[ip + 1])));\n\t ip += 2;\n\t break;\n\n\t case op.PUSH_CURR_POS: // PUSH_CURR_POS\n\t parts.push(stack.push('peg$currPos'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_UNDEFINED: // PUSH_UNDEFINED\n\t parts.push(stack.push('void 0'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_NULL: // PUSH_NULL\n\t parts.push(stack.push('null'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_FAILED: // PUSH_FAILED\n\t parts.push(stack.push('peg$FAILED'));\n\t ip++;\n\t break;\n\n\t case op.PUSH_EMPTY_ARRAY: // PUSH_EMPTY_ARRAY\n\t parts.push(stack.push('[]'));\n\t ip++;\n\t break;\n\n\t case op.POP: // POP\n\t stack.pop();\n\t ip++;\n\t break;\n\n\t case op.POP_CURR_POS: // POP_CURR_POS\n\t parts.push('peg$currPos = ' + stack.pop() + ';');\n\t ip++;\n\t break;\n\n\t case op.POP_N: // POP_N n\n\t stack.pop(bc[ip + 1]);\n\t ip += 2;\n\t break;\n\n\t case op.NIP: // NIP\n\t value = stack.pop();\n\t stack.pop();\n\t parts.push(stack.push(value));\n\t ip++;\n\t break;\n\n\t case op.APPEND: // APPEND\n\t value = stack.pop();\n\t parts.push(stack.top() + '.push(' + value + ');');\n\t ip++;\n\t break;\n\n\t case op.WRAP: // WRAP n\n\t parts.push(\n\t stack.push('[' + stack.pop(bc[ip + 1]).join(', ') + ']')\n\t );\n\t ip += 2;\n\t break;\n\n\t case op.TEXT: // TEXT\n\t parts.push(\n\t stack.push('input.substring(' + stack.pop() + ', peg$currPos)')\n\t );\n\t ip++;\n\t break;\n\n\t case op.IF: // IF t, f\n\t compileCondition(stack.top(), 0);\n\t break;\n\n\t case op.IF_ERROR: // IF_ERROR t, f\n\t compileCondition(stack.top() + ' === peg$FAILED', 0);\n\t break;\n\n\t case op.IF_NOT_ERROR: // IF_NOT_ERROR t, f\n\t compileCondition(stack.top() + ' !== peg$FAILED', 0);\n\t break;\n\n\t case op.WHILE_NOT_ERROR: // WHILE_NOT_ERROR b\n\t compileLoop(stack.top() + ' !== peg$FAILED', 0);\n\t break;\n\n\t case op.MATCH_ANY: // MATCH_ANY a, f, ...\n\t compileCondition('input.length > peg$currPos', 0);\n\t break;\n\n\t case op.MATCH_STRING: // MATCH_STRING s, a, f, ...\n\t compileCondition(\n\t eval(ast.consts[bc[ip + 1]]).length > 1\n\t ? 'input.substr(peg$currPos, '\n\t + eval(ast.consts[bc[ip + 1]]).length\n\t + ') === '\n\t + c(bc[ip + 1])\n\t : 'input.charCodeAt(peg$currPos) === '\n\t + eval(ast.consts[bc[ip + 1]]).charCodeAt(0),\n\t 1\n\t );\n\t break;\n\n\t case op.MATCH_STRING_IC: // MATCH_STRING_IC s, a, f, ...\n\t compileCondition(\n\t 'input.substr(peg$currPos, '\n\t + eval(ast.consts[bc[ip + 1]]).length\n\t + ').toLowerCase() === '\n\t + c(bc[ip + 1]),\n\t 1\n\t );\n\t break;\n\n\t case op.MATCH_REGEXP: // MATCH_REGEXP r, a, f, ...\n\t compileCondition(\n\t c(bc[ip + 1]) + '.test(input.charAt(peg$currPos))',\n\t 1\n\t );\n\t break;\n\n\t case op.ACCEPT_N: // ACCEPT_N n\n\t parts.push(stack.push(\n\t bc[ip + 1] > 1\n\t ? 'input.substr(peg$currPos, ' + bc[ip + 1] + ')'\n\t : 'input.charAt(peg$currPos)'\n\t ));\n\t parts.push(\n\t bc[ip + 1] > 1\n\t ? 'peg$currPos += ' + bc[ip + 1] + ';'\n\t : 'peg$currPos++;'\n\t );\n\t ip += 2;\n\t break;\n\n\t case op.ACCEPT_STRING: // ACCEPT_STRING s\n\t parts.push(stack.push(c(bc[ip + 1])));\n\t parts.push(\n\t eval(ast.consts[bc[ip + 1]]).length > 1\n\t ? 'peg$currPos += ' + eval(ast.consts[bc[ip + 1]]).length + ';'\n\t : 'peg$currPos++;'\n\t );\n\t ip += 2;\n\t break;\n\n\t case op.FAIL: // FAIL e\n\t parts.push(stack.push('peg$FAILED'));\n\t parts.push('if (peg$silentFails === 0) { peg$fail(' + c(bc[ip + 1]) + '); }');\n\t ip += 2;\n\t break;\n\n\t case op.REPORT_SAVED_POS: // REPORT_SAVED_POS p\n\t parts.push('peg$reportedPos = ' + stack.index(bc[ip + 1]) + ';');\n\t ip += 2;\n\t break;\n\n\t case op.REPORT_CURR_POS: // REPORT_CURR_POS\n\t parts.push('peg$reportedPos = peg$currPos;');\n\t ip++;\n\t break;\n\n\t case op.CALL: // CALL f, n, pc, p1, p2, ..., pN\n\t compileCall();\n\t break;\n\n\t case op.RULE: // RULE r\n\t parts.push(stack.push(\"peg$parse\" + ast.rules[bc[ip + 1]].name + \"()\"));\n\t ip += 2;\n\t break;\n\n\t case op.SILENT_FAILS_ON: // SILENT_FAILS_ON\n\t parts.push('peg$silentFails++;');\n\t ip++;\n\t break;\n\n\t case op.SILENT_FAILS_OFF: // SILENT_FAILS_OFF\n\t parts.push('peg$silentFails--;');\n\t ip++;\n\t break;\n\n\t default:\n\t throw new Error(\"Invalid opcode: \" + bc[ip] + \".\");\n\t }\n\t }\n\n\t return parts.join('\\n');\n\t }\n\n\t code = compile(rule.bytecode);\n\n\t parts.push([\n\t 'function peg$parse' + rule.name + '() {',\n\t ' var ' + arrays.map(arrays.range(0, stack.maxSp + 1), s).join(', ') + ';',\n\t ].join('\\n'));\n\n\t parts.push(indent2(generateRuleHeader(\n\t '\"' + js.stringEscape(rule.name) + '\"',\n\t asts.indexOfRule(ast, rule.name)\n\t )));\n\t parts.push(indent2(code));\n\t parts.push(indent2(generateRuleFooter(\n\t '\"' + js.stringEscape(rule.name) + '\"',\n\t s(0)\n\t )));\n\n\t parts.push('}');\n\n\t return parts.join('\\n');\n\t }\n\n\t var parts = [],\n\t startRuleIndices, startRuleIndex,\n\t startRuleFunctions, startRuleFunction,\n\t ruleNames;\n\n\t parts.push([\n\t '(function() {',\n\t ' /*',\n\t ' * Generated by PEG.js 0.8.0.',\n\t ' *',\n\t ' * http://pegjs.org/',\n\t ' */',\n\t '',\n\t ' function peg$subclass(child, parent) {',\n\t ' function ctor() { this.constructor = child; }',\n\t ' ctor.prototype = parent.prototype;',\n\t ' child.prototype = new ctor();',\n\t ' }',\n\t '',\n\t ' function peg$SyntaxError(message, expected, found, offset, line, column) {',\n\t ' this.message = message;',\n\t ' this.expected = expected;',\n\t ' this.found = found;',\n\t ' this.offset = offset;',\n\t ' this.line = line;',\n\t ' this.column = column;',\n\t '',\n\t ' this.name = \"SyntaxError\";',\n\t ' }',\n\t '',\n\t ' peg$subclass(peg$SyntaxError, Error);',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t ' function peg$DefaultTracer() {',\n\t ' this.indentLevel = 0;',\n\t ' }',\n\t '',\n\t ' peg$DefaultTracer.prototype.trace = function(event) {',\n\t ' var that = this;',\n\t '',\n\t ' function log(event) {',\n\t ' function repeat(string, n) {',\n\t ' var result = \"\", i;',\n\t '',\n\t ' for (i = 0; i < n; i++) {',\n\t ' result += string;',\n\t ' }',\n\t '',\n\t ' return result;',\n\t ' }',\n\t '',\n\t ' function pad(string, length) {',\n\t ' return string + repeat(\" \", length - string.length);',\n\t ' }',\n\t '',\n\t ' console.log(',\n\t ' event.line + \":\" + event.column + \" \"',\n\t ' + pad(event.type, 10) + \" \"',\n\t ' + repeat(\" \", that.indentLevel) + event.rule',\n\t ' );',\n\t ' }',\n\t '',\n\t ' switch (event.type) {',\n\t ' case \"rule.enter\":',\n\t ' log(event);',\n\t ' this.indentLevel++;',\n\t ' break;',\n\t '',\n\t ' case \"rule.match\":',\n\t ' this.indentLevel--;',\n\t ' log(event);',\n\t ' break;',\n\t '',\n\t ' case \"rule.fail\":',\n\t ' this.indentLevel--;',\n\t ' log(event);',\n\t ' break;',\n\t '',\n\t ' default:',\n\t ' throw new Error(\"Invalid event type: \" + event.type + \".\");',\n\t ' }',\n\t ' };',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' function peg$parse(input) {',\n\t ' var options = arguments.length > 1 ? arguments[1] : {},',\n\t ' parser = this,',\n\t '',\n\t ' peg$FAILED = {},',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.optimize === \"size\") {\n\t startRuleIndices = '{ '\n\t + arrays.map(\n\t options.allowedStartRules,\n\t function(r) { return r + ': ' + asts.indexOfRule(ast, r); }\n\t ).join(', ')\n\t + ' }';\n\t startRuleIndex = asts.indexOfRule(ast, options.allowedStartRules[0]);\n\n\t parts.push([\n\t ' peg$startRuleIndices = ' + startRuleIndices + ',',\n\t ' peg$startRuleIndex = ' + startRuleIndex + ','\n\t ].join('\\n'));\n\t } else {\n\t startRuleFunctions = '{ '\n\t + arrays.map(\n\t options.allowedStartRules,\n\t function(r) { return r + ': peg$parse' + r; }\n\t ).join(', ')\n\t + ' }';\n\t startRuleFunction = 'peg$parse' + options.allowedStartRules[0];\n\n\t parts.push([\n\t ' peg$startRuleFunctions = ' + startRuleFunctions + ',',\n\t ' peg$startRuleFunction = ' + startRuleFunction + ','\n\t ].join('\\n'));\n\t }\n\n\t parts.push('');\n\n\t parts.push(indent8(generateTables()));\n\n\t parts.push([\n\t '',\n\t ' peg$currPos = 0,',\n\t ' peg$reportedPos = 0,',\n\t ' peg$cachedPos = 0,',\n\t ' peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },',\n\t ' peg$maxFailPos = 0,',\n\t ' peg$maxFailExpected = [],',\n\t ' peg$silentFails = 0,', // 0 = report failures, > 0 = silence failures\n\t ''\n\t ].join('\\n'));\n\n\t if (options.cache) {\n\t parts.push([\n\t ' peg$cache = {},',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t if (options.trace) {\n\t if (options.optimize === \"size\") {\n\t ruleNames = '['\n\t + arrays.map(\n\t ast.rules,\n\t function(r) { return '\"' + js.stringEscape(r.name) + '\"'; }\n\t ).join(', ')\n\t + ']';\n\n\t parts.push([\n\t ' peg$ruleNames = ' + ruleNames + ',',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' peg$tracer = \"tracer\" in options ? options.tracer : new peg$DefaultTracer(),',\n\t ''\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' peg$result;',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.optimize === \"size\") {\n\t parts.push([\n\t ' if (\"startRule\" in options) {',\n\t ' if (!(options.startRule in peg$startRuleIndices)) {',\n\t ' throw new Error(\"Can\\'t start parsing from rule \\\\\"\" + options.startRule + \"\\\\\".\");',\n\t ' }',\n\t '',\n\t ' peg$startRuleIndex = peg$startRuleIndices[options.startRule];',\n\t ' }'\n\t ].join('\\n'));\n\t } else {\n\t parts.push([\n\t ' if (\"startRule\" in options) {',\n\t ' if (!(options.startRule in peg$startRuleFunctions)) {',\n\t ' throw new Error(\"Can\\'t start parsing from rule \\\\\"\" + options.startRule + \"\\\\\".\");',\n\t ' }',\n\t '',\n\t ' peg$startRuleFunction = peg$startRuleFunctions[options.startRule];',\n\t ' }'\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t '',\n\t ' function text() {',\n\t ' return input.substring(peg$reportedPos, peg$currPos);',\n\t ' }',\n\t '',\n\t ' function offset() {',\n\t ' return peg$reportedPos;',\n\t ' }',\n\t '',\n\t ' function line() {',\n\t ' return peg$computePosDetails(peg$reportedPos).line;',\n\t ' }',\n\t '',\n\t ' function column() {',\n\t ' return peg$computePosDetails(peg$reportedPos).column;',\n\t ' }',\n\t '',\n\t ' function expected(description) {',\n\t ' throw peg$buildException(',\n\t ' null,',\n\t ' [{ type: \"other\", description: description }],',\n\t ' peg$reportedPos',\n\t ' );',\n\t ' }',\n\t '',\n\t ' function error(message) {',\n\t ' throw peg$buildException(message, null, peg$reportedPos);',\n\t ' }',\n\t '',\n\t ' function peg$computePosDetails(pos) {',\n\t ' function advance(details, startPos, endPos) {',\n\t ' var p, ch;',\n\t '',\n\t ' for (p = startPos; p < endPos; p++) {',\n\t ' ch = input.charAt(p);',\n\t ' if (ch === \"\\\\n\") {',\n\t ' if (!details.seenCR) { details.line++; }',\n\t ' details.column = 1;',\n\t ' details.seenCR = false;',\n\t ' } else if (ch === \"\\\\r\" || ch === \"\\\\u2028\" || ch === \"\\\\u2029\") {',\n\t ' details.line++;',\n\t ' details.column = 1;',\n\t ' details.seenCR = true;',\n\t ' } else {',\n\t ' details.column++;',\n\t ' details.seenCR = false;',\n\t ' }',\n\t ' }',\n\t ' }',\n\t '',\n\t ' if (peg$cachedPos !== pos) {',\n\t ' if (peg$cachedPos > pos) {',\n\t ' peg$cachedPos = 0;',\n\t ' peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };',\n\t ' }',\n\t ' advance(peg$cachedPosDetails, peg$cachedPos, pos);',\n\t ' peg$cachedPos = pos;',\n\t ' }',\n\t '',\n\t ' return peg$cachedPosDetails;',\n\t ' }',\n\t '',\n\t ' function peg$fail(expected) {',\n\t ' if (peg$currPos < peg$maxFailPos) { return; }',\n\t '',\n\t ' if (peg$currPos > peg$maxFailPos) {',\n\t ' peg$maxFailPos = peg$currPos;',\n\t ' peg$maxFailExpected = [];',\n\t ' }',\n\t '',\n\t ' peg$maxFailExpected.push(expected);',\n\t ' }',\n\t '',\n\t ' function peg$buildException(message, expected, pos) {',\n\t ' function cleanupExpected(expected) {',\n\t ' var i = 1;',\n\t '',\n\t ' expected.sort(function(a, b) {',\n\t ' if (a.description < b.description) {',\n\t ' return -1;',\n\t ' } else if (a.description > b.description) {',\n\t ' return 1;',\n\t ' } else {',\n\t ' return 0;',\n\t ' }',\n\t ' });',\n\t '',\n\t /*\n\t * This works because the bytecode generator guarantees that every\n\t * expectation object exists only once, so it's enough to use |===| instead\n\t * of deeper structural comparison.\n\t */\n\t ' while (i < expected.length) {',\n\t ' if (expected[i - 1] === expected[i]) {',\n\t ' expected.splice(i, 1);',\n\t ' } else {',\n\t ' i++;',\n\t ' }',\n\t ' }',\n\t ' }',\n\t '',\n\t ' function buildMessage(expected, found) {',\n\t ' function stringEscape(s) {',\n\t ' function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }',\n\t '',\n\t /*\n\t * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string\n\t * literal except for the closing quote character, backslash, carriage\n\t * return, line separator, paragraph separator, and line feed. Any character\n\t * may appear in the form of an escape sequence.\n\t *\n\t * For portability, we also escape all control and non-ASCII characters.\n\t * Note that \"\\0\" and \"\\v\" escape sequences are not used because JSHint does\n\t * not like the first and IE the second.\n\t */\n\t ' return s',\n\t ' .replace(/\\\\\\\\/g, \\'\\\\\\\\\\\\\\\\\\')', // backslash\n\t ' .replace(/\"/g, \\'\\\\\\\\\"\\')', // closing double quote\n\t ' .replace(/\\\\x08/g, \\'\\\\\\\\b\\')', // backspace\n\t ' .replace(/\\\\t/g, \\'\\\\\\\\t\\')', // horizontal tab\n\t ' .replace(/\\\\n/g, \\'\\\\\\\\n\\')', // line feed\n\t ' .replace(/\\\\f/g, \\'\\\\\\\\f\\')', // form feed\n\t ' .replace(/\\\\r/g, \\'\\\\\\\\r\\')', // carriage return\n\t ' .replace(/[\\\\x00-\\\\x07\\\\x0B\\\\x0E\\\\x0F]/g, function(ch) { return \\'\\\\\\\\x0\\' + hex(ch); })',\n\t ' .replace(/[\\\\x10-\\\\x1F\\\\x80-\\\\xFF]/g, function(ch) { return \\'\\\\\\\\x\\' + hex(ch); })',\n\t ' .replace(/[\\\\u0100-\\\\u0FFF]/g, function(ch) { return \\'\\\\\\\\u0\\' + hex(ch); })',\n\t ' .replace(/[\\\\u1000-\\\\uFFFF]/g, function(ch) { return \\'\\\\\\\\u\\' + hex(ch); });',\n\t ' }',\n\t '',\n\t ' var expectedDescs = new Array(expected.length),',\n\t ' expectedDesc, foundDesc, i;',\n\t '',\n\t ' for (i = 0; i < expected.length; i++) {',\n\t ' expectedDescs[i] = expected[i].description;',\n\t ' }',\n\t '',\n\t ' expectedDesc = expected.length > 1',\n\t ' ? expectedDescs.slice(0, -1).join(\", \")',\n\t ' + \" or \"',\n\t ' + expectedDescs[expected.length - 1]',\n\t ' : expectedDescs[0];',\n\t '',\n\t ' foundDesc = found ? \"\\\\\"\" + stringEscape(found) + \"\\\\\"\" : \"end of input\";',\n\t '',\n\t ' return \"Expected \" + expectedDesc + \" but \" + foundDesc + \" found.\";',\n\t ' }',\n\t '',\n\t ' var posDetails = peg$computePosDetails(pos),',\n\t ' found = pos < input.length ? input.charAt(pos) : null;',\n\t '',\n\t ' if (expected !== null) {',\n\t ' cleanupExpected(expected);',\n\t ' }',\n\t '',\n\t ' return new peg$SyntaxError(',\n\t ' message !== null ? message : buildMessage(expected, found),',\n\t ' expected,',\n\t ' found,',\n\t ' pos,',\n\t ' posDetails.line,',\n\t ' posDetails.column',\n\t ' );',\n\t ' }',\n\t ''\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t ' function peg$trace(event) {',\n\t ' var posDetails = peg$computePosDetails(peg$currPos);',\n\t '',\n\t ' event.offset = peg$currPos;',\n\t ' event.line = posDetails.line;',\n\t ' event.column = posDetails.column;',\n\t '',\n\t ' peg$tracer.trace(event);',\n\t ' }',\n\t '',\n\t ].join('\\n'));\n\t }\n\n\t if (options.optimize === \"size\") {\n\t parts.push(indent4(generateInterpreter()));\n\t parts.push('');\n\t } else {\n\t arrays.each(ast.rules, function(rule) {\n\t parts.push(indent4(generateRuleFunction(rule)));\n\t parts.push('');\n\t });\n\t }\n\n\t if (ast.initializer) {\n\t parts.push(indent4(\"{\" + ast.initializer.code + \"}\"));\n\t parts.push('');\n\t }\n\n\t if (options.optimize === \"size\") {\n\t parts.push(' peg$result = peg$parseRule(peg$startRuleIndex);');\n\t } else {\n\t parts.push(' peg$result = peg$startRuleFunction();');\n\t }\n\n\t parts.push([\n\t '',\n\t ' if (peg$result !== peg$FAILED && peg$currPos === input.length) {',\n\t ' return peg$result;',\n\t ' } else {',\n\t ' if (peg$result !== peg$FAILED && peg$currPos < input.length) {',\n\t ' peg$fail({ type: \"end\", description: \"end of input\" });',\n\t ' }',\n\t '',\n\t ' throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);',\n\t ' }',\n\t ' }',\n\t '',\n\t ' return {',\n\t ].join('\\n'));\n\n\t if (options.trace) {\n\t parts.push([\n\t ' SyntaxError: peg$SyntaxError,',\n\t ' DefaultTracer: peg$DefaultTracer,',\n\t ' parse: peg$parse'\n\t ].join('\\n'));\n\t } else {\n\t parts.push([\n\t ' SyntaxError: peg$SyntaxError,',\n\t ' parse: peg$parse'\n\t ].join('\\n'));\n\t }\n\n\t parts.push([\n\t ' };',\n\t '})()'\n\t ].join('\\n'));\n\n\t ast.code = parts.join('\\n');\n\t}", "function compile_lit(env, expr) { \n \n if (expr === undefined || expr === null) {\n return JSON.stringify(expr); \n }\n\n if (expr.constructor === Number || expr.constructor == Boolean) {\n return JSON.stringify(expr);\n }\n\n return undefined;\n}", "eth_compileLLL(code) {\n return this.request(\"eth_compileLLL\", Array.from(arguments));\n }", "function js() {\n return new Promise(function (resolve, reject) {\n let b = browserify();\n b.add(config.jsIn);\n b.transform('babelify');\n // todo: minify\n var dest = fs.createWriteStream(config.jsOut);\n b.bundle().pipe(dest);\n console.log('bundled javascript');\n resolve();\n });\n}", "run() {\n if (!this.Wasm) {\n errorMessage(`${this.libraryName} is still loading. Try again in a few seconds.`);\n return;\n }\n this.hasRun = true;\n this._render();\n const canvas = this._resetCanvas();\n\n try {\n let f = new Function(this.libraryName, 'canvas', // actual params\n this.content); // user given code\n f(this.Wasm, canvas);\n } catch(e) {\n errorMessage(e);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns any array containing the default middleware installed by `configureStore()`. Useful if you want to configure your store with a custom `middleware` array but still keep the default set.
function getDefaultMiddleware(options) { if (options === void 0) { options = {}; } var _options = options, _options$thunk = _options.thunk, thunk$1 = _options$thunk === void 0 ? true : _options$thunk, _options$immutableChe = _options.immutableCheck, immutableCheck = _options$immutableChe === void 0 ? true : _options$immutableChe, _options$serializable = _options.serializableCheck, serializableCheck = _options$serializable === void 0 ? true : _options$serializable; var middlewareArray = new MiddlewareArray(); if (thunk$1) { if (isBoolean(thunk$1)) { middlewareArray.push(thunk); } else { middlewareArray.push(thunk.withExtraArgument(thunk$1.extraArgument)); } } { if (immutableCheck) { /* PROD_START_REMOVE_UMD */ var immutableOptions = {}; if (!isBoolean(immutableCheck)) { immutableOptions = immutableCheck; } middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions)); /* PROD_STOP_REMOVE_UMD */ } if (serializableCheck) { var serializableOptions = {}; if (!isBoolean(serializableCheck)) { serializableOptions = serializableCheck; } middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions)); } } return middlewareArray; }
[ "function getDefaultMiddleware() {\n var middlewareArray = [redux_thunk__WEBPACK_IMPORTED_MODULE_4__[\"default\"]];\n\n if (false) { var createImmutableStateInvariantMiddleware; }\n\n return middlewareArray;\n}", "getMiddleware() {\n var ref;\n const manifest = this.getMiddlewareManifest();\n const middleware = manifest == null ? void 0 : (ref = manifest.middleware) == null ? void 0 : ref[\"/\"];\n if (!middleware) {\n return;\n }\n return {\n match: getMiddlewareMatcher(middleware),\n page: \"/\"\n };\n }", "prepareMiddlewareArray (middlewareList) {\n if (!middlewareList) { return []; }\n return (Array.isArray(middlewareList) ? middlewareList : [middlewareList]);\n }", "function middlewares() {\n app.middlewares = {}\n const basePath = path.join(app.root, '/middlewares')\n let middlewares = app.config.get('express').middlewares\n if (middlewares && Array.isArray(middlewares) && middlewares.length) {\n for (let m of middlewares) {\n let middleware = require(path.join(basePath, m.dest))(app)\n app.middlewares[m.dest.toLowerCase()] = middleware\n\n if (middleware.length == 4) { //error handler\n errorHandlers.push(middleware)\n continue\n }\n\n if (m.src)\n server.use(m.src, wrapper(middleware))\n else\n server.use(wrapper(middleware))\n }\n if (middlewares.length)\n app.drivers.logger.success('Middleware', 'initialized')\n }\n }", "function initMiddleware() {\n app.use(express.compress());\n app.use(express.static(__dirname + '/public'));\n app.use(express.logger());\n app.use(express.bodyParser());\n\n /**\n * Rendr routes are attached with `app.get()`, which adds them to the\n * `app.router` middleware.\n */\n app.use(app.router);\n\n /**\n * Error handler goes last.\n */\n app.use(mw.errorHandler());\n}", "$registerMiddlewareStore() {\n this.$container.bind('Adonis/Core/MiddlewareStore', () => MiddlewareStore_1.MiddlewareStore);\n }", "function initStore (){\n if(ReactLogger){\n return createStore(\n reducer,\n applyMiddleware(logger)\n );\n }\n else{\n return createStore(reducer);\n }\n}", "function configureStore(){\n return createStore(calculatorReducer);\n}", "static getDefault() {\n return Dispatcher._dispatchers['default'];\n }", "getMiddlewareByName (middlewareName) {\n if (!check.isDefined(this.middlewares, middlewareName)) {\n throw new MiddlewareNotFoundException(middlewareName)\n }\n\n return this.middlewares[middlewareName]\n }", "initializeMiddleware() {\n if (this.hasInitialized) throw new Error('authenticated view middleware already initialized');\n this.hasInitialized = true;\n\n const {\n htmlDirectory,\n htmlFilename,\n } = this.configuration;\n\n const trshcmpctrClientRouter = express.Router();\n\n trshcmpctrClientRouter.get('/', [\n handleRenderAuthenticated.bind(null, htmlDirectory, htmlFilename),\n // Redirect to login if not authenticated\n handleRedirect.bind(null, '/login')\n ]);\n\n // Serve application static assets\n trshcmpctrClientRouter.use(express.static(htmlDirectory));\n trshcmpctrClientRouter.use(handleError);\n\n this.router = trshcmpctrClientRouter;\n }", "Middleware () {\n return store => next => action => {\n if (action.type === types.ADD_FAVORITE || action.type === types.REMOVE_FAVORITE) {\n const result = next(action)\n localStorage.setItem(this.key, JSON.stringify(store.getState().Favorites))\n return result\n }\n return next(action)\n }\n }", "function setHttpMiddleware(middleware) {\n\tconst cmfMiddlewareIndex = middlewares.indexOf(cmfMiddleware);\n\tmiddlewares.splice(cmfMiddlewareIndex - 1, 0, middleware);\n\tdefaultHttpMiddlewareOverwrite = true;\n}", "register (middleware) {\n this.stack.add(middleware)\n }", "appConfig() {\n /** first middleware for convert json request */\n this.app.use(\n bodyParser.json()\n )\n }", "function getDefaultFilters() {\n return {\n \"rawContent\": [\n 'report-type=disposition-notification', // Read receipts\n 'Content-Type: multipart/report', // Automatic delivery reports\n 'report-type=delivery-status', // Automatic delivery reports\n 'Content-Type: message/delivery-status' // Automatic delivery reports\n ],\n \"from\": [\n '(^|<)((mailer-daemon|postmaster)@.*)',\n 'noreply|no-reply|do-not-reply',\n '.+@.*\\\\bgoogle\\\\.com',\n Session.getActiveUser().getEmail()\n ],\n \"to\": [\n 'undisclosed-recipients' // Potential spams\n ] \n }\n}", "function compose() {\n var handlers = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n handlers[_i] = arguments[_i];\n }\n var middleware = generate(handlers);\n return function (req, res, done) { return middleware(null, req, res, done); };\n}", "get defaultDataSchema() {\n\t\treturn {\n\t\t\tprefix: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: this.client.config.prefix,\n\t\t\t\tmin: null,\n\t\t\t\tmax: 10,\n\t\t\t\tarray: this.client.config.prefix.constructor.name === 'Array',\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: `VARCHAR(10) NOT NULL DEFAULT '${this.client.config.prefix.constructor.name === 'Array' ? JSON.stringify(this.client.config.prefix) : this.client.config.prefix}'`\n\t\t\t},\n\t\t\tlanguage: {\n\t\t\t\ttype: 'language',\n\t\t\t\tdefault: this.client.config.language,\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: false,\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: `VARCHAR(5) NOT NULL DEFAULT '${this.client.config.language}'`\n\t\t\t},\n\t\t\tdisableNaturalPrefix: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: false,\n\t\t\t\tconfigurable: Boolean(this.client.config.regexPrefix),\n\t\t\t\tsql: `BIT(1) NOT NULL DEFAULT 0`\n\t\t\t},\n\t\t\tdisabledCommands: {\n\t\t\t\ttype: 'command',\n\t\t\t\tdefault: [],\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: true,\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: 'TEXT'\n\t\t\t}\n\t\t};\n\t}", "function defaultFastifyOptions() {\n return {\n return503OnClosing: false,\n ignoreTrailingSlash: false,\n caseSensitive: true,\n // use “legacy” header version with prefixed x- for better compatibility with existing enterprises infrastructures\n requestIdHeader: 'x-request-id',\n // set 30 seconds to\n pluginTimeout: 30000,\n // virtually disable the max body size limit\n bodyLimit: Number.MAX_SAFE_INTEGER,\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Patch various jQuery functions to handle tinymce specific attribute and content behavior we don't patch the jQuery.fn directly since it will most likely break compatibility with other jQuery logic on the page. Only instances created by TinyMCE should be patched.
function patch(jq) { // Patch some functions, only patch the object once if (jq.css !== css) { // Patch css/attr to use the data-mce- prefixed attribute variants jq.css = css; jq.attr = attr; jq.tinymce = editor; // Each pushed jQuery instance needs to be patched // as well for example when traversing the DOM jq.pushStack = function() { return patch(fn.pushStack.apply(this, arguments)); }; } return jq; }
[ "function initTinyMCE(options){\n // default options:\n var defaults={\n relative_urls: false,\n remove_script_host: false,\n skin_variant: 'ocms',\n mode: \"exact\",\n theme: \"advanced\",\n file_browser_callback: 'cmsTinyMceFileBrowser',\n setup: function(editor) { setupTinyMCE(editor); },\n plugins: \"autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,-opencms\",\n theme_advanced_toolbar_location: \"top\",\n theme_advanced_toolbar_align: \"left\",\n theme_advanced_statusbar_location: \"bottom\",\n width: '100%',\n theme_advanced_resizing: false,\n theme_advanced_resizing_use_cookie: false\n };\n // check for fullpage option\n if (options[\"fullpage\"]){\n defaults[\"plugins\"]+=\",fullpage\";\n }\n if (options[\"style_formats\"]){\n try{\n options[\"style_formats\"]=eval('('+options[\"style_formats\"]+')');\n }catch(error){\n delete options[\"style_formats\"];\n alert(\"Error while parsing style formats option for tinyMCE: \"+error);\n }\n }\n // the fullpage attribute needs to be removed otherwise tinyMCE won't start\n delete options[\"fullpage\"];\n $.extend(defaults, options);\n tinyMCE.init(defaults);\n}", "function set_content_tiny_step(p_id_etape,p_content)\r\n{\r\n\t// Hide to user the textarea\r\n\tdocument.getElementById('edit_etape').style.visibility = 'hidden';\r\n\r\n\t// Display the textarea for browser\r\n\tdocument.getElementById('edit_etape').style.display = '';\r\n\r\n\t// Set the content of the step into the tiny\r\n\tdocument.getElementById('edit_etape').value = p_content;\r\n\r\n\t// Init the TinyMCE\r\n\tinitmce_step(p_id_etape);\r\n\r\n\t// Test if the tinyMCE is available (in 10 ms)\r\n\tsetTimeout(function(){ctrl_dispo_tiny(p_id_etape,p_content);},10);\r\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 set_content_tiny_description(p_content)\r\n{\r\n\t// Hide to user the textarea\r\n\tdocument.getElementById('edit_etape').style.visibility = 'hidden';\r\n\t\r\n\t// Display the textarea for browser\r\n\tdocument.getElementById('edit_etape').style.display = '';\r\n\r\n\t// Set the content of the step into the tiny\r\n\tdocument.getElementById('edit_etape').value = p_content;\r\n\t\r\n\t// Init the TinyMCE\r\n\tinitmce_description();\r\n\t\r\n\t// Test if the tinyMCe is available (in 10 ms)\r\n\tsetTimeout(function(){ctrl_dispo_tiny(0,p_content);},10);\r\n}", "function _ajaxSetup( target, settings )\n\t{\n\t\treturn settings ?\n\n\t\t\t//\tBuilding a settings object\n\t\t\tajaxExtend( ajaxExtend( target, ajaxSettings ), settings ) :\n\n\t\t\t//\tExtending ajaxSettings\n\t\t\tajaxExtend( ajaxSettings, target );\n\t}", "function replace_all_html_emoticons(text_element){\n\n var working_copy = text_element.clone();\n\n // emoticon's img elements\n var imgs = working_copy.find('img[class=\"emoticon\"]');\n imgs.each(function () {\n var html_emoticon_element = $(this);\n replace_html_emoticon(html_emoticon_element);\n });\n\n // replace HTML emoticon with textual emoticon\n function replace_html_emoticon(html_emoticon_element){\n html_emoticon_element.replaceWith(html_emoticon_element.attr('alt'));\n }\n\n return working_copy;\n}", "function initEditor(){\n\t\n\tif(editor=='tinymce'){\n\t\t// tinyMCE.init({\n\t\t// theme : \"advanced\",\n\t\t// mode : \"specific_textareas\",\n\t\t// editor_selector : \"editor\",\n\t\t// theme_advanced_toolbar_location : \"top\",\n\t\t// theme_advanced_buttons1 : \"bold,italic,underline,separator,link,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,outdent,indent,separator,undo,redo,code\",\n\t\t// theme_advanced_buttons2 : \"\",\n\t\t// theme_advanced_buttons3 : \"\",\n\t\t// height:\"250px\",\n\t\t// width:\"600px\",\n\t\t// entity_encoding : \"raw\",\n\t\t// forced_root_block : ''\n\t\t// });\n\t\tif(tinymce) tinyMCE.triggerSave();\n\t\ttinymce.init({\n\t\t selector: \"textarea.editor\",\n\t\t theme: \"silver\",\n\t\t plugins: [\n\t\t \"advlist autolink lists link image charmap print preview hr anchor pagebreak\",\n\t\t \"searchreplace wordcount visualblocks visualchars code fullscreen\",\n\t\t \"insertdatetime media nonbreaking save table contextmenu directionality\",\n\t\t \"emoticons template paste\"\n\t\t ],\n\t\t height:\"250px\",\n\t\t width:\"700px\",\n\t\t entity_encoding : \"raw\",\n\t\t toolbar1: \"insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image\",\n\t\t});\n\n\t\t//reserve for future bindings\n\t\t// $(document).off('change', '#descriptions_rights .rifcs-type[vocab=RIFCSDescriptionType]')\n\t\t// \t.on('change', '#descriptions_rights .rifcs-type[vocab=RIFCSDescriptionType]', function(){\n\n\t\t// });\n\t}\n}", "function override_thickbox() {\n\t\t$( 'a[target=\"thickbox\"]' ).each( function( i, e ) {\n\t\t\tif ( !$( e ).prop( 'wr_override_thickbox' ) ) {\n\t\t\t\t$( e ).click( function( event ) {\n\t\t\t\t\tevent.preventDefault();\n\n\t\t\t\t\t// Calculate width and height for ThickBox window.\n\t\t\t\t\tvar width = $( this ).attr( 'data-width' ), height = $( this ).attr( 'data-height' );\n\n\t\t\t\t\tif ( width.substr( -1 ) == '%' ) {\n\t\t\t\t\t\twidth = $( window ).width() * ( parseInt( width ) / 100 );\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( height.substr( -1 ) == '%' ) {\n\t\t\t\t\t\theight = $( window ).height() * ( parseInt( height ) / 100 );\n\t\t\t\t\t}\n\n\t\t\t\t\t// Finalize the URL for opening ThickBox window.\n\t\t\t\t\tvar url = $( this ).attr( 'href' ) + ( $( this ).attr( 'href' ).indexOf( '?' ) > -1 ? '&' : '?' ) + 'width=' + width + '&height=' + height;\n\n\t\t\t\t\ttb_show( $( this ).attr( 'title' ), url );\n\n\t\t\t\t\t// Remove default close handler.\n\t\t\t\t\t$( '#TB_closeWindowButton, #TB_overlay' ).off( 'click', tb_remove );\n\n\t\t\t\t\t// Handle window resize event to resize ThickBox window.\n\t\t\t\t\tvar self = this,\n\n\t\t\t\t\tresize = function() {\n\t\t\t\t\t\t// Calculate new width and height for ThickBox window.\n\t\t\t\t\t\tvar width = $( self ).attr( 'data-width' ), height = $( self ).attr( 'data-height' );\n\n\t\t\t\t\t\tif ( width.substr( -1 ) == '%' ) {\n\t\t\t\t\t\t\twidth = $( window ).width() * ( parseInt( width ) / 100 );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( height.substr( -1 ) == '%' ) {\n\t\t\t\t\t\t\theight = $( window ).height() * ( parseInt( height ) / 100 );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update width and height for ThickBox window.\n\t\t\t\t\t\tTB_WIDTH = ( width * 1 ) + 30;\n\t\t\t\t\t\tTB_HEIGHT = ( height * 1 ) + 40;\n\n\t\t\t\t\t\tajaxContentW = TB_WIDTH - 30;\n\t\t\t\t\t\tajaxContentH = TB_HEIGHT - 45;\n\n\t\t\t\t\t\t$( '#TB_ajaxContent' ).css( {\n\t\t\t\t\t\t\twidth: ajaxContentW,\n\t\t\t\t\t\t\theight: ajaxContentH,\n\t\t\t\t\t\t} );\n\n\t\t\t\t\t\t$( '#TB_iframeContent' ).css( {\n\t\t\t\t\t\t\twidth: ajaxContentW + 29,\n\t\t\t\t\t\t\theight: ajaxContentH + 17,\n\t\t\t\t\t\t} );\n\n\t\t\t\t\t\ttb_position();\n\t\t\t\t\t}\n\n\t\t\t\t\t$( window ).on( 'resize', resize );\n\n\t\t\t\t\t$( '#TB_closeWindowButton, #TB_overlay' ).click( function( event ) {\n\t\t\t\t\t\t// Prevent default event handle.\n\t\t\t\t\t\tevent.preventDefault();\n\n\t\t\t\t\t\t// Check if closing modal is prevented?\n\t\t\t\t\t\tvar prevent_close = $( '#TB_closeWindowButton' ).attr( 'data-prevent-close' );\n\n\t\t\t\t\t\tif ( prevent_close ) {\n\t\t\t\t\t\t\tif ( $( this ).attr( 'id' ) == 'TB_closeWindowButton' ) {\n\t\t\t\t\t\t\t\t// Show alert.\n\t\t\t\t\t\t\t\treturn alert( prevent_close );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Close modal.\n\t\t\t\t\t\t\ttb_remove( event );\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Remove window resize handle.\n\t\t\t\t\t\t$( window ).off( 'resize', resize );\n\t\t\t\t\t} );\n\n\t\t\t\t\treturn false;\n\t\t\t\t} );\n\n\t\t\t\t$( e ).prop( 'wr_override_thickbox', true );\n\t\t\t}\n\t\t} );\n\t}", "function copyObjectJQuery (obj) {\n return jQuery.extend(true, {}, obj);\n}", "function jqLitePatchJQueryRemove(name,dispatchThis,filterElems,getterIfNoArguments){var originalJqFn=jQuery.fn[name];originalJqFn=originalJqFn.$original||originalJqFn;removePatch.$original=originalJqFn;jQuery.fn[name]=removePatch;function removePatch(param){// jshint -W040\nvar list=filterElems&&param?[this.filter(param)]:[this],fireEvent=dispatchThis,set,setIndex,setLength,element,childIndex,childLength,children;if(!getterIfNoArguments||param!=null){while(list.length){set=list.shift();for(setIndex=0,setLength=set.length;setIndex<setLength;setIndex++){element=jqLite(set[setIndex]);if(fireEvent){element.triggerHandler('$destroy');}else{fireEvent=!fireEvent;}for(childIndex=0,childLength=(children=element.children()).length;childIndex<childLength;childIndex++){list.push(jQuery(children[childIndex]));}}}}return originalJqFn.apply(this,arguments);}}/////////////////////////////////////////////", "_initMarkdownAndPreviewSection() {\n this.$mdEditorContainerEl = this.$containerEl.find('.te-md-container .te-editor');\n this.$previewEl = this.$containerEl.find('.te-md-container .te-preview');\n }", "switchToWYSIWYG() {\n this.$containerEl.removeClass('te-md-mode');\n this.$containerEl.addClass('te-ww-mode');\n }", "function $(el){\n\tif ($type(el) == 'string') el = document.getElementById(el);\n\tif ($type(el) == 'element'){\n\t\tif (!el.extend){\n\t\t\tUnload.elements.push(el);\n\t\t\tel.extend = Object.extend;\n\t\t\tel.extend(Element.prototype);\n\t\t}\n\t\treturn el;\n\t} else return false;\n}", "setHtml(element, html){\n element.html(html);\n }", "SetCompatibleWithEditor() {}", "function plugin_jquery_twitterTip($){\n /* ===========================================================\n * bootstrap-tooltip.js v2.0.2\n * http://twitter.github.com/bootstrap/javascript.html#tooltips\n * Inspired by the original jQuery.tipsy by Jason Frame\n * ===========================================================\n * Copyright 2012 Twitter, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ========================================================== */\n\n !function( $ ) {\n\n \"use strict\"\n\n /* TOOLTIP PUBLIC CLASS DEFINITION\n * =============================== */\n\n var Tooltip = function ( element, options ) {\n this.init('tooltip', element, options);\n }\n\n Tooltip.prototype = {\n\n constructor: Tooltip\n\n , init: function ( type, element, options ) {\n var eventIn\n , eventOut\n\n this.type = type\n this.$element = $(element)\n this.options = this.getOptions(options)\n this.enabled = true\n\n if (this.options.trigger != 'manual') {\n eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'\n eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'\n this.$element.bind(eventIn, this.options.selector, $.proxy(this.enter, this))\n this.$element.bind(eventOut, this.options.selector, $.proxy(this.leave, this))\n }\n\n this.options.selector ?\n (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :\n this.fixTitle()\n }\n\n , getOptions: function ( options ) {\n options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data())\n\n if (options.delay && typeof options.delay == 'number') {\n options.delay = {\n show: options.delay\n , hide: options.delay\n }\n }\n\n return options\n }\n\n , enter: function ( e ) {\n var self = $(e.currentTarget)[this.type](this._options).data(this.type)\n\n if (!self.options.delay || !self.options.delay.show) {\n self.show()\n } else {\n self.hoverState = 'in'\n setTimeout(function() {\n if (self.hoverState == 'in') {\n self.show()\n }\n }, self.options.delay.show)\n }\n }\n\n , leave: function ( e ) {\n var self = $(e.currentTarget)[this.type](this._options).data(this.type)\n\n if (!self.options.delay || !self.options.delay.hide) {\n self.hide()\n } else {\n self.hoverState = 'out'\n setTimeout(function() {\n if (self.hoverState == 'out') {\n self.hide()\n }\n }, self.options.delay.hide)\n }\n }\n\n , show: function () {\n var $tip\n , inside\n , pos\n , actualWidth\n , actualHeight\n , placement\n , tp\n\n if (this.hasContent() && this.enabled) {\n $tip = this.tip()\n this.setContent()\n\n if (this.options.animation) {\n $tip.addClass('ant_tw_fade')\n }\n\n placement = typeof this.options.placement == 'function' ?\n this.options.placement.call(this, $tip[0], this.$element[0]) :\n this.options.placement\n\n inside = /ant_tw_in/.test(placement)\n\n $tip\n .remove()\n .css({ top: 0, left: 0, display:\"block\" })\n .appendTo(inside ? this.$element : document.body)\n\n pos = this.getPosition(inside)\n\n actualWidth = $tip[0].offsetWidth\n actualHeight = $tip[0].offsetHeight\n\n switch (inside ? placement.split(' ')[1] : placement) {\n case 'bottom':\n tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}\n break\n case 'top':\n tp = {top: pos.top - actualHeight - 5, left: pos.left + pos.width / 2 - actualWidth / 2}\n break\n case 'left':\n tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}\n break\n case 'right':\n tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}\n break\n }\n\n $tip\n .css(tp)\n .addClass('ant_tw_'+placement)\n .addClass('ant_tw_in')\n }\n }\n\n , setContent: function () {\n var $tip = this.tip()\n $tip.find('.ant_twtooltip-inner').html(this.getTitle())\n $tip.removeClass('ant_tw_fade ant_tw_in ant_tw_top ant_tw_bottom ant_tw_left ant_tw_right')\n }\n\n , hide: function () {\n var that = this\n , $tip = this.tip()\n\n $tip.removeClass('ant_tw_in')\n\n function removeWithAnimation() {\n var timeout = setTimeout(function () {\n $tip.off($.support.transition.end).remove();\n }, 500)\n\n $tip.one($.support.transition.end, function () {\n clearTimeout(timeout)\n $tip.remove()\n })\n }\n\n $.support.transition && this.$tip.hasClass('ant_tw_fade') ?\n removeWithAnimation() :\n $tip.remove();\n if ( $.support.transition && this.$tip.hasClass('ant_tw_fade') ) {\n } else {\n }\n }\n\n , fixTitle: function () {\n var $e = this.$element\n if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {\n $e.attr('data-original-title', $e.attr('title') || '').removeAttr('title')\n }\n }\n\n , hasContent: function () {\n return this.getTitle()\n }\n\n , getPosition: function (inside) {\n return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {\n width: this.$element[0].offsetWidth\n , height: this.$element[0].offsetHeight\n })\n }\n\n , getTitle: function () {\n var title\n , $e = this.$element\n , o = this.options\n\n title = $e.attr('data-original-title')\n || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)\n\n title = (title || '').toString().replace(/(^\\s*|\\s*$)/, \"\")\n\n return title\n }\n\n , tip: function () {\n return this.$tip = this.$tip || $(this.options.template)\n }\n\n , validate: function () {\n if (!this.$element[0].parentNode) {\n this.hide()\n this.$element = null\n this.options = null\n }\n }\n\n , enable: function () {\n this.enabled = true\n }\n\n , disable: function () {\n this.enabled = false\n }\n\n , toggleEnabled: function () {\n this.enabled = !this.enabled\n }\n\n , toggle: function () {\n this[this.tip().hasClass('ant_tw_in') ? 'hide' : 'show']()\n }\n\n }\n\n\n /* TOOLTIP PLUGIN DEFINITION\n * ========================= */\n\n $.fn.tooltip = function ( option ) {\n return this.each(function () {\n var $this = $(this)\n , data = $this.data('tooltip')\n , options = typeof option == 'object' && option\n if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))\n if (typeof option == 'string') data[option]()\n })\n }\n\n $.fn.tooltip.Constructor = Tooltip\n\n $.fn.tooltip.defaults = {\n animation: true\n , delay: 0\n , selector: false\n , placement: 'top'\n , trigger: 'hover'\n , title: ''\n , template: '<div class=\"ant ant_twtooltip\"><div class=\"ant_twtooltip-arrow\"></div><div class=\"ant_twtooltip-inner\"></div></div>'\n }\n }( $ );\n }", "function styles_ptags(){\n $(\"#modu_main\").find(\"p\").each(function(){\n if($(this).attr(\"class\")===undefined)\n {\n $(this).css(\"padding\",\"0px\");\n $(this).css(\"margin\",\"0px\");\n }else{\n if($(this).attr(\"class\").search(\"bexi_editor\")!==-1){\n $(this).css(\"padding\",\"0px\");\n $(this).css(\"margin\",\"0px\");\n }\n }\n });\n}", "function preserveWrapperATag(newMarkup) {\r\n var range = scope.editor.getRange();\r\n var anchor = getAnchorElement(range);\r\n if (anchor) {\r\n $(anchor).html(newMarkup);\r\n return anchor.outerHTML;\r\n }\r\n else {\r\n return newMarkup;\r\n }\r\n }", "function generateEditors() {\n for (var i=0; i<editorInstances.length; i++) {\n var editInst = editorInstances[i];\n editInst.ReplaceTextarea();\n }\n}", "function editorNewContent(content, container, activity)\n{\n editorDirty = true;\n activity.contents.push(content);\n addContentElement(content, container, activity);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get GUID of the Current Record
function GetGuidOfTheRecord(executionContext) { try { //Get the form context var formContext = executionContext.getFormContext(); //Get the current Record Guid var recordGuid = formContext.data.entity.getId(); Xrm.Utility.alertDialog(recordGuid); } catch (e) { Xrm.Utility.alertDialog(e.message); } }
[ "findUniqueIdentifier() {\n const metadataId = this.attributes[\"unique-identifier\"];\n if (metadataId) {\n const uidMetadata = this.metadata.findItemWithId(\n \"dc:identifier\",\n metadataId\n );\n if (uidMetadata) {\n return uidMetadata.value;\n }\n }\n }", "function getRecord() {\n return recordName;\n }", "get hashId()\n\t{\n\t\t//this.id;\n\t\t//this.recurrenceId;\n\t\t//this.calendar;\n\t\treturn this._calEvent.hashId;\n\n/*\t\t this._hashId = [encodeURIComponent(this.id),\n\t\t\tthis.recurrenceId ? this.recurrenceId.getInTimezone(exchGlobalFunctions.ecUTC()).icalString : \"\",\n\t\t\tthis.calendar ? encodeURIComponent(this.calendar.id) : \"\"].join(\"#\");\n\n\t\t//dump(\"get hashId: title:\"+this.title+\", value:\"+this._hashId);\n\t\treturn this._hashId;*/\n\t}", "static generateId() {\n return cuid_1.default();\n }", "function getId(dbEntity){\n return dbEntity.entity.key.path[0].id ||\n dbEntity.entity.key.path[0].name;\n}", "id() {\n \n // implementation should be inside the child class, but below implementation\n // if for simplicity in many occasions\n if (typeof this.data.id != 'undefined') return this.data.id;\n\n // no ID\n return null;\n }", "getMSID() {\n const streamId = this.getStreamId();\n const trackId = this.getTrackId();\n\n return streamId && trackId ? `${streamId} ${trackId}` : null;\n }", "@api get assetId(){\n return this.recordId;\n }", "getById(id) {\n return FieldLink(this).concat(`(guid'${id}')`);\n }", "getID() {\r\n return this.id.toString().padStart(3, '0');\r\n }", "function getDeviceDataId() {\n if (_deviceData._deviceDataId === undefined) {\n _deviceData._deviceDataId = sjcl.codec.base64.fromBits(sjcl.random.randomWords(6, 0)).replace(/[\\+\\/]/g,'0');\n }\n return _deviceData._deviceDataId;\n }", "function getUser(){\n if(!mixpanelUid){\n mixpanelUid = Date.now();\n identifyUser(mixpanelUid);\n }\n return mixpanelUid;\n}", "generatePrivateId()\n\t{\n\t\tvar nanotime = process.hrtime();\n\t\treturn String(nanotime[0]) + nanotime[1] + '-' + this.name;\n\t}", "get patientId() {\n\t\t// subject.reference = 'Patient/{patientId}'\n\t\treturn (\n\t\t\tthis._subject\n\t\t\t&& this._subject.reference\n\t\t\t&& this._subject.reference.split('/')[1]\n\t\t);\n\t}", "function generateMongoObjectId() {\n var timestamp = (new Date().getTime() / 1000 | 0).toString(16);\n return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() {\n return (Math.random() * 16 | 0).toString(16);\n }).toLowerCase();\n }", "get uuid()\n\t{\n\t\treturn this._abCard.uuid;\n\t}", "generateChatId() {\n if (this.myUser.uid > this.uidFriend)\n return this.myUser.uid + \"-\" + this.uidFriend;\n // return `${this.myUser.uid}-${this.uidFriend}`;\n else return this.uidFriend + \"-\" + this.myUser.uid;\n // return `${this.uidFriend}-${this.myUser.uid}`;\n }", "function _randId() {\n\t\t// Return a random number\n\t\treturn (new Date().getDate())+(''+Math.random()).substr(2)\n\t}", "function generateGuid() {\n var buf = new Uint16Array(8);\n buf = crypto.randomBytes(8);\n var S4 = function(num) {\n var ret = num.toString(16);\n while(ret.length < 4){\n ret = \"0\"+ret;\n }\n return ret;\n };\n\n return (\n S4(buf[0])+S4(buf[1])+\"-\"+S4(buf[2])+\"-\"+S4(buf[3])+\"-\"+\n S4(buf[4])+\"-\"+S4(buf[5])+S4(buf[6])+S4(buf[7])\n );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runtime helper for merging vbind="object" into a VNode's data.
function bindObjectProps(data,tag,value,asProp){if(value){if(!isObject(value)){process.env.NODE_ENV!=='production'&&warn('v-bind without argument expects an Object or Array value',this);}else{if(Array.isArray(value)){value=toObject(value);}var hash;for(var key in value){if(key==='class'||key==='style'){hash=data;}else{var type=data.attrs&&data.attrs.type;hash=asProp||config.mustUseProp(tag,type,key)?data.domProps||(data.domProps={}):data.attrs||(data.attrs={});}if(!(key in hash)){hash[key]=value[key];}}}}return data;}
[ "function bindElement(element, object) {\n setPropertyOnElement(element, DATA_BINDING_ID, object);\n}", "function applyData(object, data) {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n object[key] = data[key];\n }\n }\n }", "function mergeUniforms(obj1,obj2){\n var obj3 = {};\n for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }\n for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }\n return obj3;\n }", "deepAssign(orig,obj) {\n var v;\n for( var key in obj ) {\n v=obj[key];\n if( typeof v===\"object\" ) {\n orig[key]=Array.isArray(v)?[]:{};\n this.deepAssign(orig[key],v);\n } else {\n orig[key]=v;\n }\n }\n }", "function deepUpdate(obj, up, level) { //**should change this to use new objects with prototypes of object instead of copying all members... ****done, but not tested.\r\n\t\tif (level) {\r\n\t\t\t// <level> should start with a \"[\" or a \".\" -- if both missing prepend a \".\"\r\n\t\t\tif (level.search(/^\\.|^\\[/) === -1) {\r\n\t\t\t\tlevel = \".\" + level;\r\n\t\t\t}\r\n\t\t\tobj = eval(\"obj\" + level);\r\n\t\t}\r\n\t\tif (up) {\r\n\t\t\tfor (var i in up) {\r\n\t\t\t\tif (isObject(up[i])) {\r\n\t\t\t\t\tobj[i] = deepProto(up[i]);\t\t\t\r\n\t\t\t\t} else {\r\n\t\t\t\t\tobj[i] = up[i];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn obj;\r\n\t}", "updateBoundVariable(value) {\n let binddatavalue = this.binddatavalue;\n // return if the variable bound is not static.\n if (this.datavaluesource && this.datavaluesource.execute(DataSource.Operation.IS_API_AWARE)) {\n return;\n }\n else if (this.datavaluesource && !this.datavaluesource.twoWayBinding) {\n return;\n }\n // return if widget is bound.\n if (!binddatavalue || binddatavalue.startsWith('Widgets.') || binddatavalue.startsWith('itemRef.currentItemWidgets')) {\n return;\n }\n binddatavalue = binddatavalue.replace(/\\[\\$i\\]/g, '[0]');\n // In case of list widget context will be the listItem.\n if (_.has(this.context, binddatavalue.split('.')[0])) {\n _.set(this.context, binddatavalue, value);\n }\n else {\n _.set(this.viewParent, binddatavalue, value);\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}", "function extendWith(name, object) {\n this[name] = {};\n var obj = object[name];\n\n angular.extend(this[name], obj);\n}", "function ObjectFieldTransfer(from, target) {\n for (const key in from) {\n if (key != \"__proto__\" &&\n Object.prototype.hasOwnProperty.call(from, key)\n && typeof from[key] !== \"function\") {\n const element = from[key];\n target[key] = element;\n }\n }\n}", "function toDataAttrs(object) {\n const convObject = {};\n Object.entries(object).forEach(entry => {\n const [name, value] = entry;\n convObject[`data-${toDashString(name)}`] = value;\n });\n return convObject;\n}", "function update_obj(dest, key, data, keys, context)\n{\n // There are further instructions remaining - we will need to recurse\n if (keys.length) {\n // There is a pre-existing destination object. Recurse through to the object key\n if (dest !== null && typeof dest !== 'undefined') {\n let o = update(dest[key.name], data, keys, context)\n if (o !== null && typeof o !== 'undefined')\n dest[key.name] = o\n }\n // There is no pre-existing object. Check to see if data exists before creating a new object\n else {\n // Check to see if there is a value before creating an object to store it\n let o = update(null, data, keys, context)\n if (o !== null) {\n dest = {}\n dest[key.name] = o\n }\n }\n }\n // This is a leaf. Set data into the dest\n else\n dest = set_data(dest, key, data, context)\n\n return dest\n}", "function shallowUpdate(obj, up, level) {\r\n\t\tif (level) {\r\n\t\t\t// <level> should start with a \"[\" or a \".\" -- if both missing prepend a \".\"\r\n\t\t\tif (level.search(/^\\.|^\\[/) === -1) {\r\n\t\t\t\tlevel = \".\" + level;\r\n\t\t\t}\r\n\t\t\tobj = eval(\"obj\" + level);\r\n\t\t}\r\n\t\tif (up) {\r\n\t\t\tfor (var i in up) {\r\n\t\t\t\tobj[i] = up[i];\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn obj;\t\t\t\r\n\t}", "function copyObjectJQuery (obj) {\n return jQuery.extend(true, {}, obj);\n}", "function extendWithAndListen(name, object) {\n var oldObj = this[name];\n\n //if it already exists under the same structure, don't readd, do it only when we have a different object structure\n if (oldObj != undefined && angular.equals(Object.keys(oldObj), Object.keys(object)))\n return;\n\n this[name] = {};\n var obj = object[name];\n \n angular.extend(this[name], obj);\n\n console.log(\"Watching child object, \" + name);\n\n $scope = this;\n\n //deregister listener\n if ($scope.objectWatchers[name] != undefined && $scope.objectWatchers[name].constructor == Function)\n $scope.objectWatchers[name]();\n\n //watch a whole object\n var listener = this.$watch(name, function (newval, oldval) {\n if (newval == oldval || newval == undefined || oldval == undefined || angular.equals(newval, oldval))\n return;\n\n console.log(\"Child object changed... \");\n\n doPageParametersPost($scope);\n }, true);\n\n $scope.objectWatchers[name] = listener;\n \n if ($scope.httpPostParameters.indexOf(name) == -1)\n $scope.httpPostParameters.push(name);\n}", "static wrap(gl, object) {\n return object instanceof VertexArrayObject ?\n object :\n new VertexArrayObject(gl, {handle: object.handle || object});\n }", "function deepExtend(target, source) {\n if (!(source instanceof Object)) {\n return source;\n }\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n var dateValue = source;\n return new Date(dateValue.getTime());\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n for (var prop in source) {\n if (!source.hasOwnProperty(prop)) {\n continue;\n }\n target[prop] = deepExtend(target[prop], source[prop]);\n }\n return target;\n }", "toWindow (fromObj) {\n Object.assign(window, fromObj)\n }", "function deepCopy (obj, up, level) { //** With changes made to deepUpdate, is this now the same as deepProto??? ****I think it's a little different... I think the copy has no prototype at the top level, so a shallowClear will result in an empty object.\r\n\t//**I think there's a problem here now. Changing <obj> will change the copy.... ****I think we need to bring back the old deepUpdate that doesn't use deepProto... we want to keep the new version to. How do we name them?\r\n\t//**For deep copy... first use new deepUpdate, then re-update the result with the old deepUpdate. Or maybe deepUpdate should do both of these always??? No... I don't think so...\r\n\t\tvar copy = deepUpdate({}, obj);\t\t\r\n\t\treturn up?\r\n\t\t\tdeepUpdate(copy, up, level):\r\n\t\t\tcopy;\r\n\t}", "function merge_objeto(objFirst,objSecond)\r\n{\r\n\r\n\treturn $.extend({}, objFirst,objSecond);\t\t\r\n}", "function addReachableVref(vref) {\n const { type, virtual, allocatedByVat } = parseVatSlot(vref);\n if (type === 'object') {\n if (allocatedByVat) {\n if (virtual) {\n incRefCount(vref);\n } else {\n // exported non-virtual object: Remotable\n const remotable = requiredValForSlot(vref);\n if (remotableRefCounts.has(remotable)) {\n /** @type {number} */\n const oldRefCount = (remotableRefCounts.get(remotable));\n remotableRefCounts.set(remotable, oldRefCount + 1);\n } else {\n remotableRefCounts.set(remotable, 1);\n }\n }\n } else {\n // We refcount imports, to preserve their vrefs against\n // syscall.dropImport when the Presence itself goes away.\n incRefCount(vref);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new button.
function createButton(inrTxt) { const elem = document.createElement(`button`); elem.classList.add(`buttons`); elem.innerText = `${inrTxt}`; active.buttons.push({ e: elem }); box.appendChild(elem); }
[ "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 _createButton(label, name, action, disabled) {\n var retorno = {};\n retorno.buttonAction = action;\n retorno.disabled = disabled;\n retorno.label = label;\n retorno.name = name;\n retorno.type = \"button\";\n return retorno;\n }", "function createButton(label, func)\n{\n\tvar button = document.createElement(\"button\");\n\tbutton.textContent = label;\n\tbutton.addEventListener(\"click\", func);\n\tdocument.body.appendChild(button);\n}", "button(x, y, content, opts){\n\n let button = new Button(x, y, content, opts);\n this.layer.buttons.push(button);\n return button;\n\n }", "function createBtnRestart() {\n var btnRestart = document.createElement('button');\n btnRestart.setAttribute('class','btn btn-primary');\n btnRestart.style.height = '50px';\n btnRestart.setAttribute('id','btnRestart');\n btnRestart.innerText = 'Restart';\n btnRestart.style.fontSize = '26px';\n btnRestart.style.marginTop = '50px';\n return btnRestart;\n}", "function createButton(text, clickFunction, args){\n let btn = document.createElement('button');\n btn.innerHTML = text;\n btn.addEventListener('click', () => {\n clickFunction.apply(this, args);\n });\n return btn;\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}", "function Button(label, size = ImVec2.ZERO) {\r\n return bind.Button(label, size);\r\n }", "function createButton(){\n javamonDiv = document.getElementById('javamon-div');\n javamon.forEach(function(e, i){\n newButton = document.createElement('button');\n newButton.id = e.name;\n newButton.className = 'javamon-button';\n newButton.innerHTML = e.name;\n javamonDiv.appendChild(newButton);\n // console.log(document.getElementsByTagName('button')[i]);\n })\n // document.getElementById('play').className = 'display-none';\n // document.getElementsByTagName('h1')[0].className = 'display-none';\n // document.getElementsByTagName('p')[0].className = 'display-none';\n // document.getElementById('next').className = '';\n}", "function make_button(text, hover, click) {\n var btn = buttons.append('g').classed('button', true);\n \n var bg = btn.append('ellipse')\n .attr(\"rx\", rx).attr(\"ry\", ry)\n .attr(\"cx\", cx).attr(\"cy\", cy);\n var txt = btn.append('text').text(text)\n .attr(\"text-anchor\", \"middle\")\n .attr(\"x\", cx).attr(\"y\", function () {\n var height = d3.select(this).style(\"height\").split(\"px\")[0];\n return height / 3 + cy;\n });\n \n // Setup Event Handlers\n btn.on(\"mouseover\", function () {\n btn.classed(\"hover\", true);\n txt.text(hover);\n bg.transition().duration(250).attr(\"ry\",\n function () {\n return d3.select(this).attr(\"rx\");\n });\n }).on(\"mouseout\", function () {\n btn.classed(\"hover\", false);\n txt.text(text);\n bg.transition().duration(250).ease('linear').attr(\"ry\", ry);\n }).on(\"click\", click);\n return btn;\n }", "function elemAddTrackButton(track_element) {\n var create_track_button = document.createElement(\"button\");\n create_track_button.id = \"track_create_\" + track_element.track_num;\n create_track_button.textContent = \"Create New Track\";\n create_track_button.onclick = () => createTrackClicked(track_element);\n return create_track_button;\n}", "function CreateSubmitButton(CLID, isAsync)\n{\n DW(CreateSubmitButton_(CLID, isAsync));\n}", "function addUplinkButton() {\r\n\tvar upBtn = document.createElement('button');\r\n\tupBtn.setAttribute('type', 'button');\r\n\tupBtn.setAttribute('class', 'btn btn-default btn-sm');\r\n\r\n\tvar upBtnIcn = document.createElement('i');\r\n\tupBtnIcn.setAttribute('class', 'fa fa-level-up');\r\n\tupBtnIcn.setAttribute('aria-hidden', 'true');\r\n\r\n\tupBtn.appendChild(upBtnIcn);\r\n\r\n\tdocument.getElementById('kapitel-btn').innerHTML = \"\";\r\n\tdocument.getElementById('kapitel-btn').appendChild(upBtn);\r\n}", "function makeButton(text) {\n var button = $('<a />')\n .text(text)\n .attr('data-role', 'button')\n .attr('data-theme', 'a')\n .buttonMarkup();\n if (arguments[1]) {\n button.attr('id', arguments[1]);\n }\n return button;\n}", "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 }", "createMoveButton(index) {\n let scope = this;\n let modifyButtonElement = document.createElement('button');\n modifyButtonElement.className = cssConstants.ICON + ' ' + cssConstants.EDITOR_FEATURE_MODIFY;\n modifyButtonElement.title = langConstants.EDITOR_FEATURE_MODIFY;\n modifyButtonElement.setAttribute('feat_id', index);\n jQuery(modifyButtonElement).click(function(event) {\n scope.modifyFeatureFunction(event);\n });\n return modifyButtonElement;\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 }", "addButton(char) {\n //Create an input type dynamically.\n let element = document.createElement(\"button\");\n //Assign different attributes to the element.\n element.textContent = char;\n element.setAttribute(\"id\", char);\n element.setAttribute(\"value\", char);\n element.setAttribute(\"type\", \"button\");\n element.setAttribute(\"name\", char);\n element.setAttribute(\"onclick\", \"game.guess(this)\");\n //Append the element in page (in span).\n buttonsDisplay.appendChild(element);\n }", "createEditButton(index) {\n let scope = this;\n let editButtonElement = document.createElement('button');\n editButtonElement.className = cssConstants.ICON + ' ' + cssConstants.BUTTON_EDIT_DATA;\n editButtonElement.title = langConstants.METADATA_EDIT;\n editButtonElement.setAttribute('feat_id', index);\n jQuery(editButtonElement).click(function(event) {\n scope.handleEditFeatureEvent(event);\n });\n return editButtonElement;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a query from the state.
function removeQuery(state, queryId) { const new_order = []; for(const id of state.order) { if(id !== queryId) { new_order.push(id); } } const new_state = Object.assign({}, state, {order: new_order}); delete new_state[queryId]; return new_state; }
[ "function clearCurrentQuery() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy || pastQueries.length == 0)\n return;\n\n pastQueries.splice(currentQueryIndex,1);\n if (currentQueryIndex >= pastQueries.length)\n currentQueryIndex = pastQueries.length - 1;\n\n lastResult.copyIn(pastQueries[currentQueryIndex]);\n\n saveStateToStorage(); // save current history\n }", "function delete_search_query(query, $q) \n{\n\tvar q \t\t= $q.defer();\n\n\tvar request = twitter_search_queries_db.transaction([\"twitter_search_queries\"], \"readwrite\")\n .objectStore(\"twitter_search_queries\")\n\t .delete(query);\n\n\trequest.onsuccess \t= function(event) {\n \t // It's gone!\n \t\tq.resolve(\"Deleted\");\n\t}\n\trequest.onerror \t= function (event) {\n\t\tq.reject(\"Error in deleting\");\n\t}\n\n\treturn q.promise;\n\n} // delete_search_query", "function clearHistory() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy)\n return;\n\n lastResult.copyIn(dummyResult);\n pastQueries.length = 0;\n currentQueryIndex = 0;\n\n saveStateToStorage(); // save current history\n }", "updateQuery(query) {\n this.setState(() => ({\n cursor: null\n }));\n this.props.queryFilter(query.trim());\n }", "function cancelQuery() {\n if (cwQueryService.currentQueryRequest != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(cwQueryService.currentQueryRequest);\n queryInFly && queryInFly.canceler(\"test\");\n\n // prepare cancel request\n var queryIdParam = cwConstantsService.queryIdParam + \"=\" + cwQueryService.currentQueryRequestID;\n var cancelQueryRequest = {\n url: cwConstantsService.canelQueryURL + \"?\" + queryIdParam,\n method: \"DELETE\"\n };\n\n // submit request\n $http(cancelQueryRequest)\n .then(function success(resp) {\n },\n function error(resp) {\n logWorkbenchError(\"Error cancelling query: \" + JSON.stringif(resp));\n });\n }\n }", "function handleRemove() {\n const newGraphParams = Object.assign({}, graphParams);\n newGraphParams.secondDateRange = null;\n\n const currentType = typeForPage(props.currentPage);\n\n props.dispatch({\n type: currentType,\n payload: graphParams, // not affected by date changes\n query: fullQueryFromParams(newGraphParams),\n });\n }", "handleRemoveQuestion(e, position) {\n const newState = {questions: this.state.questions.slice()};\n console.log('Removing question: ',newState.questions[position].text);\n console.log('position removed is ', position);\n newState.questions.splice(position, 1);\n this.setState(newState);\n }", "removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }", "function removeRecentSearchTerm( term ){\n recent.remove( term, function(){\n populateRecentSeachTerms();\n });\n}", "eraseEvent(state, num) {\n state.events.splice(num, 1);\n\n }", "function clear_old_state() {\n\t\t// Clear any existing matches\n\t\tdb.client.del(week_key, function(err,reply) {\n\t\t\tif (err) return _error(err);\n\t\t\treturn create_this_weeks_matches();\n\t\t});\n\t}", "function delete_tweets_by_query(query, $q) {\n\tvar q \t \t\t\t= $q.defer();\n\tvar index \t\t\t= tweets_db.transaction([\"tweets\"], \"readwrite\").objectStore(\"tweets\").index(\"query, status_id\");\n\tvar boundedKeyRange = IDBKeyRange.bound([query, \"\"], [query, \"Z\"]);\n\tindex.openCursor(boundedKeyRange).onsuccess = function(event) {\n\t\tvar tweet_cursor = event.target.result;\n\t\tif (tweet_cursor) {\n\t\t \t// Delete Request for deleting tweet\n\t\t var request = tweet_cursor.delete();\n\t\t request.onsuccess = function() {\n\t\t \tconsole.log(\"Nemam Amma Bhagavan Sharanam -- Deleted Tweet\");\n\t\t };\n\t\t // Move to the next tweet\n\t\t tweet_cursor.continue();\n\t \t} // if cursor is valid\n\t \telse {\n\t \t\t// All tweets are deleted\n\t \tconsole.log(\"Nemam Amma Bhagavvan Sharanam -- No more entries!\");\n\t \tq.resolve(\"All Tweets are deleted\");\n\t \t} // Else cursor is null\n\n\t} // OpenCursor\n\treturn q.promise;\n} // delete_tweets_by_query", "clearTargetSearch() {\n this.targetQuery = '';\n this.targetCategoryResults.length = 0;\n }", "function clear() {\n resetStore();\n }", "function removeQuestion() {\n removeQuestionID = questions.indexOf(selectedQuestion);\n questions.splice(removeQuestionID, 1);\n answerList.splice(removeQuestionID, 1);\n}", "function remove(id) {\n return db(\"todos\")\n .where({ id })\n .del();\n}", "ClearSearch () {\n return { type: types.CLEAR_SEARCH }\n }", "async discard() {\n const tx = this.database.transaction(\n ['states', 'changes', 'contents'], 'readwrite')\n const states = tx.objectStore('states')\n const changes = tx.objectStore('changes').index('document')\n const contents = tx.objectStore('contents')\n\n await Promise.all([\n iterate(changes, this.id, cursor => {\n cursor.delete()\n cursor.continue()\n }),\n promisify(states.delete(this.id)),\n promisify(contents.delete(this.id)),\n ])\n\n this.dirty = false\n }", "remove(element) {\n this.set.splice(this.set.indexOf(element), 1);\n console.log(\"element removed successfully\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
setLeafletMap :: (Map, L.Map) > Map
function setLeafletMap(self, map) { _private(self).leafletMap = map; getOptions(self).setLeafletMap(map); return self; }
[ "function setMap(linkMap) {\n $('.map-google iframe').attr('src', linkMap);\n}", "function afterMapInit(map) {\n $scope.mapObj.yaMap = map;\n }", "function Map() {\n _classCallCheck(this, Map);\n\n this[map] = {};\n this[zoom] = 16;\n this[init]();\n }", "function initOpenLayersMap() {\r\n map = new OpenLayers.Map('map', mapInitParams);\r\n \r\n }", "set LightmapStatic(value) {}", "function mapSetup()\n{\n mapInit[\"lat\"] = 51.0;\n mapInit[\"lon\"] = -114.0;\n mapInit[\"zoom\"] = 11;\n return mapInit;\n}", "function setZoomLevel(value=0){\n map.setZoom(value);\n}", "function createMap(myLatitude, myLongitude) {\n\n\n// Leaflet Map on index page\n L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZW5qb3ltcmJhbiIsImEiOiJjam5hY3EwcDQwZ2hiM3BwYWQ2dWt4a2x1In0.nlX1GeaPE2DQn3aZH0IJaA', {\n maxZoom: 18,\n minZoom: 4,\n attribution: 'Map data &copy; <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 id: 'mapbox.streets'\n }).addTo(map);\n\n placeEventsOnMap();\n\n //set map center after all events are placed\n map.setView([myLatitude, myLongitude], endZoom);\n}", "function setItem(map, key, value) {\n if (typeof (Storage) !== \"undefined\") {\n window.localStorage.setItem(key, value);\n } else {\n // No web storage Support.\n map.setItem(key, value);\n }\n}", "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 &copy; Esri &mdash; 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 updateMap(data, canvas) {\n\t//TODO\n}", "function MapChild({center}){\n const map=useMap();\n map.setView(center);\n return null;\n}", "function reloadMap() {\n map.invalidateSize();\n}", "componentDidMount() {\n this.setState({ mapRef: this.mapRef });\n }", "function BvGMapViewMap() {\n BvGMapView.call(this);\n}", "function setMapLevel(data) {\n\tvar lat_max = 0, lat_min = 1000, lng_max = 0, lng_min = 1000;\n\tvar lat_range = 0, lng_range = 0, level;\n\n\t$.each( data.restaurants, function( i, restaurant ) {\n\t\tlat_max = Math.max(lat_max, restaurant.lat);\n\t\tlat_min = Math.min(lat_min, restaurant.lat);\n\t\tlng_max = Math.max(lng_max, restaurant.lng);\n\t\tlng_min = Math.min(lng_min, restaurant.lng);\n\t});\n\n\tlat_range = lat_max - lat_min;\n\tlng_range = lng_max - lng_min;\n\n\tif ( lat_range > 0.28 || lng_range > 0.18 ) {\n\t\tlevel = 5;\n\t} else if ( lat_range > 0.15 || lng_range > 0.09 ) {\n\t level = 6;\n\t} else if ( lat_range > 0.075 || lng_range > 0.04 ) {\n\t level = 7;\n\t} else if ( lat_range > 0.035 || lng_range > 0.02 ) {\n\t level = 8;\n\t} else if ( lat_range > 0.02 || lng_range > 0.013 ) {\n\t level = 9;\n\t} else if ( lat_range > 0.01 || lng_range > 0.005 ) {\n\t level = 10;\n\t} else {\n\t level = 11;\n\t};\n\t\n\toMap.setLevel(level);\n}", "resetMapAndVars(){\n controller.infoWindow.close();\n model.map.setZoom(13);\n model.map.setCenter(model.athensCenter);\n }", "function PuplishMap(){}", "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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
:: Display user greetings or terminal signature
function show_greetings() { if (settings.greetings === undefined) { // signature have ascii art so it's not suite for screen readers self.echo(self.signature, {finalize: a11y_hide}); } else if (settings.greetings) { var type = typeof settings.greetings; if (type === 'string') { self.echo(settings.greetings); } else if (type === 'function') { settings.greetings.call(self, self.echo); } else { self.error(strings().wrongGreetings); } } }
[ "function massage() {\n console.log(\"****************************************************************\")\n console.log(\"Sorry honey, that service isn't digital\")\n console.log(\"But I'd recommend going to a really nice hotel spa & resort\")\n console.log(\"and request their relaxing massage package\")\n console.log(\"****************************************************************\")\n}", "function showWelcome() {\n\n\tconst welcomeHeader = `\n\n=================================================================\n|| ||\n| Employee Summary Generator |\n|| ||\n=================================================================\n\n`\n\n\tconst welcomeMessage = `\n\nWelcome to the Employee Summary Generator!\nThis application will generate a roster of employee details based on information you provide.\n\n`\n\n\tconsole.clear();\n\n\tconsole.log(colors.brightCyan(welcomeHeader));\n\tconsole.log(colors.brightCyan(welcomeMessage));\n\n}", "function greeter (name) {\n return \"hoi \" + name + \"!\";\n}", "function promptUsername() {\n setInputFlow(submitUsername, true);\n\n print('Please enter your username in the box below');\n}", "greet() {\n return (`${this.name} offers a greeting in ${this.language}`);\n }", "function greeting(name){\n return \"Welcome \" + name\n}", "function greet (name, owner){\n if(name === owner){\n return `Hello boss`\n } else {\n return `Hello guest`\n }\n}", "function printCommand(cmd) {\r\n\r\n\t// Get the command to show\r\n\tvar command = cmd || submit.value;\r\n\r\n\t// Pull from the global namespace\r\n\tterminal.innerHTML += Filesystem.user + '@' + Filesystem.host + ':' + Filesystem.path + '$ ' + command + '\\n';\r\n\r\n}", "function say(text) {\n twiml.say(text, { voice: 'alice'});\n }", "function win() {\n displayText(`YOU WIN!`);\n}", "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 lookAtMe()\n{\n\t// First, the variable newText is created to hold all of the required text to print.\n\tvar newText = \"\";\n\t// The player's basic information is concatenated into newText.\n\tnewText += yourAppearance[0];\n\t// Space is added.\n\tnewText += \"<br>\";\n\t// The player's current clothing is concatenated into newText.\n\tnewText += yourAppearance[1];\n\t// Space is added.\n\tnewText += \"<br>\";\n\t// The player's current damage is concatenated into newText.\n\tnewText += yourAppearance[2];\n\t// The total body of text is printed.\n\tprintText(newText);\n}", "function printSentence() {\n if (this[\"isChallenging\"] === true && this[\"isRewarding\"] === true) {\n console.log(`Learning the programming languages: \"${this[\"languages\"].join(\", \")}\" is rewarding and challenging.`);\n } else {\n console.log(\"Hä?\")\n };\n}", "function journalEntry() {\r\n let journalEntry = prompt(` Okay ${userName} , Reflect on why you chose what you did. Describe how that rating makes you feel,why you chose that, how it makes you feel to have that rating, and plans for the upcoming days either change it or keep it the same! Please press the button under PRESS Here to log your answer !`, \" Please press the button under PRESS HERE after completing this entry!\");\r\n console.log(` You journal entry was: ${journalEntry}`);\r\n return journalEntry;\r\n // Enter in as much text as necessary about what you learned, how you felt, and plans for the upcoming days\r\n\r\n // what do I do with what I have here, \r\n}", "function ksfHelp(){}", "function dialog(speaker) {\n\treturn function(speech) {\n\t\treturn speaker + \" says \\\"\" + speech + \"\\\"\";\n\t}\n}", "function introResponse() {\n var commands = {\n \"What is it like being an AI\": function() {\n beingAnAI();\n },\n \"Are you a human\": function() {\n humanQuestion();\n },\n \"I don't want to be here\": function() {\n doNotWant();\n }\n };\n\n // can only say the phrases as they appear on screen and can only say one phrase\n annyang.start({\n autoRestart: false,\n continuous: false\n });\n // show the commands and let player say one when function is triggered\n annyang.addCommands(commands);\n $('#intro').show();\n}", "function displayText(message) {\n push();\n fill(255);\n textSize(32);\n textAlign(CENTER, CENTER);\n text(message, width / 2, height / 2);\n pop();\n}", "function StartUp(){\n dispHelp();\n hangmanGame.newGameWord();\n askForPlayer();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes worldData.emoScores and generates a bundle of usable data: flattenedArr (array) A version of emoScores that is magnified, padded, smoothed and flattened so that it maps to the correct number of veritices for the terrain later used to generate geometry. In sum, a 1d array in which each element represents the height of the vertex, as derived from the emotional score. helperArrFlat (array) A helper array of the dimensions of flattenedArr. However, instead of containing the emotional score, each element contains at array with the original 2d coordinates [pathNum,chunkNum]. So an entry marked [0,5] corresponds to the anger path (0) and the 5th chunk of text. numChunks (Number) the total number of chunks (of journal entries) used to generate the terrain wS and hS (Numbers) the width and height of the segments that will connect the vertices in the terrain terrainWidth and terrainHeight (Numbers) height and width of the terrain paddingX and paddingZ (Numbers) the padding on the terrain that will be generated, in X (forward/back from camera) and Z (left/right) dimensions xBound, zBound (Numbers) These numbers and their negatives represent the location of the invisible wall that will stop the player from going too far from the interesting part of the terrain.
function generateTerrainData(emoScores,paddingSize,scaleUp,smoothingRadius){ //Make sure emoScores contains only numbers emoScores=numifyData(emoScores); //Create a helper array that will undergo the same transformations as the main array, //but preserve its path number (anger=0/joy=1/fear=2) and chunk number var helperArr=generateHelperArr(emoScores); //Pad both arrays padArray(emoScores,paddingSize); padArray(helperArr,paddingSize,[-1,-1]); //get terrainWidth and terrainHeight var terrainWidth=emoScores.length*250; var terrainHeight=emoScores[0].length*200; //get wS and hS var wS=(emoScores[0].length*scaleUp)-1; var hS=(emoScores.length*scaleUp)-1; //Establish padding and bounds var paddingX=(paddingSize/(emoScores[0].length+paddingSize))*terrainWidth; var paddingZ=(paddingSize/(emoScores.length+paddingSize))*terrainHeight; var xBound=terrainWidth/2-(paddingX/2); var zBound=terrainHeight/2-(paddingZ/2); //Magnify both arrays var scaledArr=magnifyArray(emoScores,scaleUp); var helperArr=magnifyArray(helperArr,scaleUp); //Smooth both arrays to prevent blocky terrain var smoothedArr=smoothArray(scaledArr,smoothingRadius); //Flatten both arrays var flattenedArr=flattenArray(smoothedArr); var helperArrFlat=flattenArray(helperArr); //Determine total number of chunks var numChunks=scaledArr[0].length; return {flattenedArr: flattenedArr, numChunks:numChunks, helperArrFlat:helperArrFlat,wS:wS,hS:hS,terrainWidth:terrainWidth, terrainHeight:terrainHeight, paddingX:paddingX, paddingZ:paddingZ,xBound:xBound,zBound:zBound}; }
[ "function makeTerrain(){\n //Parameters affecting terrain generation\n var paddingSize=5;\n var scaleUp=4;\n var smoothingRadius=3;\n //Get terrain data\n var terrainData=generateTerrainData(worldData.emoScores,paddingSize,scaleUp,smoothingRadius);\n //Unpack terrain data\n var flattenedArr=terrainData.flattenedArr;\n var helperArrFlat=terrainData.helperArrFlat;\n var wS=terrainData.wS;\n var hS=terrainData.hS;\n var numChunks=terrainData.numChunks;\n //Set variables in exported object\n globalTerrainData.terrainWidth=terrainData.terrainWidth;\n globalTerrainData.terrainHeight=terrainData.terrainHeight;\n globalTerrainData.playerStartX=terrainData.xBound-terrainData.paddingX/4;\n globalTerrainData.xBound=terrainData.xBound;\n globalTerrainData.zBound=terrainData.zBound;\n //Generate and return mesh\n return generateMesh(globalTerrainData.terrainWidth,globalTerrainData.terrainHeight,wS,hS,numChunks,flattenedArr,helperArrFlat)\n}", "function Waveform2Score(wave_start, wave_end, measure_start, measure_end) {\n var wavesegment_options = {\n container: '#waveform',\n waveColor: '#dddddd',\n progressColor: '#3498db',\n loaderColor: 'purple',\n cursorColor: '#e67e22',\n cursorWidth: 1,\n selectionColor: '#d0e9c6',\n backend: 'WebAudio',\n normalize: true,\n loopSelection: false,\n renderer: 'Canvas',\n partialRender: true,\n waveSegmentRenderer: 'Canvas',\n waveSegmentHeight: 50,\n height: 100,\n barWidth: 2,\n plotTimeEnd: wavesurfer.backend.getDuration(),\n wavesurfer: wavesurfer,\n ELAN: elan,\n wavesSegmentsArray,\n scrollParent: false\n };\n\n var measure_duration = (wave_end - wave_start) / (measure_end - measure_start);\n\n for (var i = measure_start; i < measure_end; i++) {\n var msr = createMeasureDIV(i);\n var rect = msr.getBoundingClientRect();\n\n var waveSegmentPos = {\n left: rect.left + \"px\",\n top: rect.top + \"px\",\n width: rect.width,\n container: msr.getAttribute('id')\n }\n\n\n wavesSegmentsArray.push(waveSegmentPos);\n\n var repris = tixlb[i][2];\n var bpm = (60 / measure_duration) * tixbts[i - 1];\n console.log(\"tixbts:\" + tixbts[i - 1]);\n elan.addAnnotation(ANNO_ID + i, wave_start + (i - measure_start) * measure_duration,\n wave_start + (i - measure_start + 1) * measure_duration,\n \"Bar \" + i + \" Rep \" + repris,\n \"BPM: \" + bpm);\n\n\n }\n elanWaveSegment.init(wavesegment_options);\n highlightSelectedDIVs();\n\n}", "function renderHighScores(){\n\t\n\tvar node = document.getElementById('scores');\n\tnode.innerHTML = '';\n\tnode.innerHTML = '<br/>'\n\tfor(var i = 0; i < highScores.length; i++){\t\n\t\tnode.innerHTML += highScores[i]+'<br/>';\t\n\t}\n}", "function normalizeMeasures(part) {\n const measuresLengths = part.measures.map(a => a.beat.length);\n console.log(\"12121212121212122\", measuresLengths);\n const lcmOfBeatLength = Util.lcm(...measuresLengths);\n // 1.转换成对0 2.把track内所有小节beat统一长度\n\n // 不能用foreach,foreach会直接bypass掉empty的(稀疏数组遍历)\n // part.measures.forEach((measure, measureIndex) => {});\n for (\n let measureIndex = 0;\n measureIndex <= part.measures.length - 1;\n measureIndex += 1\n ) {\n // console.log(\"measure::::::::::\", part.measures[measureIndex]);\n if (!part.measures[measureIndex]) {\n //建一个空小节\n //potential bug here\n part.measures[measureIndex] = {\n measure: measureIndex + 1,\n sequence: \"\",\n beat: Util.createUnderScores(lcmOfBeatLength),\n matchZero: true\n };\n } else {\n // 对位处理成对0\n if (!part.measures[measureIndex].matchZero) {\n // 对位转成对0,抽出对应的音//potential bug here, super mario....seemingly solved\n // const sequenceArray = JSON.parse(\n // `[${part.measures[measureIndex].sequence}]`.replace(\n // /([ABCDEFG]#*b*[1-9])/g,\n // '\"$1\"'\n // )\n // );\n let newSeqArray = part.measures[measureIndex].beat\n .split(\"\")\n .map((beatDigit, index) => {\n if (beatDigit.match(/\\d/g)) {\n return part.measures[measureIndex].sequence[index];\n } else {\n return \"\";\n }\n });\n newSeqArray = newSeqArray.filter(seq => !!seq); // 排掉空的\n console.log(\"bbbbbbbbbbb\", newSeqArray);\n\n // TO FIX HERE!!!\n // let s = JSON.stringify(newSeqArray.filter(note => note != \"\")).replace(\n // /\"/g,\n // \"\"\n // );\n // s = s.substring(1, s.length - 1); // 去掉数组的前后方括号\n // part.measures[measureIndex].sequence = s;\n part.measures[measureIndex].sequence = newSeqArray;\n part.measures[measureIndex].matchZero = true;\n }\n // console.log(\"jjjjjjjjjjjjjj\", part.measures[measureIndex].sequence);\n //对0的,beat延展就行了,原来000的可能变成0--0--0-- (根据最小公倍数)\n if (part.measures[measureIndex].beat.length < lcmOfBeatLength) {\n const ratio = lcmOfBeatLength / part.measures[measureIndex].beat.length;\n // console.log(\"[][][]\");\n // console.log(lcmOfBeatLength);\n // console.log(part.measures[measureIndex].beat.length);\n const append = Util.createScores(ratio - 1);\n part.measures[measureIndex].beat = part.measures[measureIndex].beat\n .split(\"\")\n .join(append);\n part.measures[measureIndex].beat += append;\n }\n }\n }\n\n console.log(\"=== measure after normalization===\");\n console.log(part.measures);\n\n //把所有measure合成一大段 应了老话「不要看小节线」\n part.tonepart = part.measures.reduce((a, b) => {\n // console.log(\"?\", a.sequence);\n return {\n // potential bug: if a/b is empty string, no comma here, seemingly solved\n // sequence: `${a.sequence}${a.sequence && b.sequence ? \",\" : \"\"}${\n // b.sequence\n // }`,\n sequence: a.sequence.concat(b.sequence),\n beat: `${a.beat}${b.beat}`\n };\n });\n console.log(\"=== final part in this part ===\");\n console.log(part.tonepart);\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}", "function esGenCube ( scale, vertices, normals,\n texCoords, indices )\n{\n var shape = new ESShape();\n var i;\n var numVertices = 24;\n var numIndices = 36;\n\n var cubeVerts =\n [\n -0.5, -0.5, -0.5,\n -0.5, -0.5, 0.5,\n 0.5, -0.5, 0.5,\n 0.5, -0.5, -0.5,\n -0.5, 0.5, -0.5,\n -0.5, 0.5, 0.5,\n 0.5, 0.5, 0.5,\n 0.5, 0.5, -0.5,\n -0.5, -0.5, -0.5,\n -0.5, 0.5, -0.5,\n 0.5, 0.5, -0.5,\n 0.5, -0.5, -0.5,\n -0.5, -0.5, 0.5,\n -0.5, 0.5, 0.5,\n 0.5, 0.5, 0.5,\n 0.5, -0.5, 0.5,\n -0.5, -0.5, -0.5,\n -0.5, -0.5, 0.5,\n -0.5, 0.5, 0.5,\n -0.5, 0.5, -0.5,\n 0.5, -0.5, -0.5,\n 0.5, -0.5, 0.5,\n 0.5, 0.5, 0.5,\n 0.5, 0.5, -0.5,\n ];\n \n var cubeNormals =\n [\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n ];\n\n var cubeTex =\n [\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0,\n 1.0, 0.0,\n 1.0, 1.0,\n 0.0, 1.0,\n 0.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0,\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0,\n ];\n\n // Allocate memory for buffers\n if ( vertices )\n {\n shape.vertices = new Float32Array(cubeVerts.length);\n for ( i = 0; i < cubeVerts.length; i++)\n {\n shape.vertices[i] = cubeVerts[i];\n shape.vertices[i] *= scale;\n }\n }\n\n if ( normals )\n {\n shape.normals = new Float32Array(cubeNormals.length);\n for ( i = 0; i < cubeNormals.length; i++)\n {\n shape.normals[i] = cubeNormals[i];\n }\n }\n\n if ( texCoords )\n {\n shape.texCoords = new Float32Array(cubeTex.length);\n for ( i = 0; i < cubeTex.length; i++)\n {\n shape.texCoords[i] = cubeTex[i];\n }\n }\n\n\n // Generate the indices\n if ( indices )\n {\n var cubeIndices =\n [\n 0, 2, 1,\n 0, 3, 2,\n 4, 5, 6,\n 4, 6, 7,\n 8, 9, 10,\n 8, 10, 11,\n 12, 15, 14,\n 12, 14, 13,\n 16, 17, 18,\n 16, 18, 19,\n 20, 23, 22,\n 20, 22, 21\n ]\n\n shape.indices = new Uint16Array(cubeIndices.length);\n for ( i = 0; i < cubeIndices.length; i++)\n {\n shape.indices[i] = cubeIndices[i];\n }\n shape.numIndices = cubeIndices.length;\n }\n\n return shape;\n}", "function weaponHit(e, m, ei, mi) {\n\n if(m.x <= (e.x + e.w) && (m.x + m.w) >= e.x && m.y <= (e.y + e.h) && (m.y + m.h) >= e.y) {\n enemyArray.splice(ei,1)\n weaponArray.splice(mi,1)\n new enemyExplosion(\"./sfx/enemyExplosion.wav\")\n score += 100\n\n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 3) + 1\n let dx = (Math.random() - 0.5) * 20;\n let dy = (Math.random() - 0.5) * 20;\n let color = colorArray[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n \n for(let d=0; d < 15; d++) {\n let size = Math.floor(Math.random() * 1) + 1\n let dx = (Math.random() - 0.5) * 30;\n let dy = (Math.random() - 0.5) * 30;\n let color = colorArray2[Math.floor(Math.random()*colorArray.length)]\n debrisArray.push(new enemyDestroyed(e.x, e.y , size, dx, dy, color))\n }\n }\n}", "function loadScores()\n{\n\tvar highscoresElement = document.getElementById(\"highscores\");\n\thighscoresElement.innerHTML = \"Highscores\";\n\tvar scores = new Array(LIST_SIZE);\n\t\n\tfor(var i = 0; i < scores.length; ++i){\n\t\tvar tmp;\n\t\tif(tmp = localStorage.getItem(SAVE_NAME + i)){\n\t\t\tscores[i] = tmp;\n\t\t}\n\t\telse{\n\t\t\tscores[i] = Math.floor(500/(i+1));\n\t\t}\n\t\t\n\t\thighscoresElement.innerHTML += \"<li>\" + (i + 1) + \". \" + scores[i] + \"</li>\";\n\t}\n\t\n\treturn scores;\n}", "displayScores() {\r\n for (let i = 1; i <= this.total; i += 1) {\r\n const data = this.data.get(i);\r\n const div = this.createContent(data.name, data.level, Utils.formatNumber(data.score, \",\"));\r\n\r\n div.className = \"highScore\";\r\n this.scores.appendChild(div);\r\n }\r\n }", "constructor(chunkxpos, chunkypos) {\n if(typeof chunklist[chunkypos] === 'undefined') {\n console.log('Generating 1d array...');\n chunklist = [];\n chunklist[chunkypos] = [];\n }\n if(typeof chunklist[chunkypos][chunkxpos] === 'undefined') {\n console.log('Generating 2d array...');\n chunklist[chunkypos] = [];\n }\n \n chunklist[chunkypos][chunkxpos] = this;\n this.map = [];\n for(let y=0; y<chunksize; y++) {\n this.map[y] = [];\n for(let x=0; x<chunksize; x++) {\n this.map[y][x] = new maptile(this, x, y);\n } }\n \n this.biomepoints = [];\n // Now check to see if there are any neighboring chunks to use for generating biomepoints\n // start with the top direction\n if((typeof chunklist[chunkypos-1] != 'undefined') && (typeof chunklist[chunkypos-1][chunkxpos] != 'undefined')) {\n // At this point, we can assume that chunklist[y-1][x] is another mapchunk. Run across its bottom edge and generate new biomepoints\n console.log('New chunk has a northern neighbor');\n let sourcechunk = chunklist[chunkypos-1][chunkxpos];\n let lastcolormatch = -1;\n let lastpoint = 0;\n for(let x=0; x<chunksize; x++) {\n if(sourcechunk.map[chunksize][x].tile == lastcolormatch) {\n lastpoint.stretchcount++; // Same color as last square. Expand that point's range\n }else{\n if(lastpoint!=0) { // Finished with this biomepoint - but we need to wrap that one up.\n lastpoint.x = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n lastpoint = new biomepoint(this, x, 0, sourcechunk.map[chunksize][x].tile);\n this.biomepoints.push(lastpoint);\n lastpoint.stretchcount = 1;\n lastcolormatch = lastpoint.c;\n }\n }\n // We will also need to adjust the last new biomepoint\n lastpoint.x = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n // now do the bottom direction\n if((typeof chunklist[chunkypos+1] != 'undefined') && (typeof chunklist[chunkypos+1][chunkxpos] != 'undefined')) {\n console.log('New chunk has a southern neighbor');\n let sourcechunk = chunklist[chunkypos+1][chunkxpos];\n let lastcolormatch = -1;\n let lastpoint = 0;\n for(let x=0; x<chunksize; x++) {\n if(sourcechunk.map[0][x].tile == lastcolormatch) {\n lastpoint.stretchcount++;\n }else{\n if(lastpoint!=0) { // adjust the last point\n lastpoint.x = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n lastpoint = new biomepoint(this, x, chunksize, sourcechunk.map[0][x].tile);\n this.biomepoints.push(lastpoint);\n lastpoint.stretchcount = 1;\n lastcolormatch = lastpoint.c;\n }\n }\n lastpoint.x = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n // left side... we can assume that chunklist[chunkypos] already exists\n if(typeof chunklist[chunkypos][chunkxpos-1] != 'undefined') {\n console.log('New chunk has a western neighbor');\n let sourcechunk = chunklist[chunkypos][chunkxpos-1];\n let lastcolormatch = -1;\n let lastpoint = 0;\n for(let y=0; y<chunksize; y++) {\n if(sourcechunk.map[y][chunksize].tile == lastcolormatch) {\n lastpoint.stretchcount++;\n }else{\n if(lastpoint!=0) {\n lastpoint.y = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n lastpoint = new biomepoint(this, 0, y, sourcechunk.map[y][chunksize].tile);\n this.biomepoints.push(lastpoint);\n lastpoint.stretchcount = 1;\n lastcolormatch = lastpoint.c;\n }\n }\n lastpoint.y = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n // right side\n if(typeof chunklist[chunkypos][chunkxpos+1] != 'undefined') {\n console.log('New chunk has an eastern neighbor');\n let sourcechunk = chunklist[chunkypos][chunkxpos+1];\n let lastcolormatch = -1;\n let lastpoint = 0;\n for(let y=0; y<chunksize; y++) {\n if(sourcechunk.map[y][0].tile == lastcolormatch) {\n lastpoint.stretchcount++;\n }else{\n if(lastpoint!=0) {\n lastpoint.y = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n lastpoint = new biomepoint(this, chunksize, y, sourcechunk.map[y][0].tile);\n this.biomepoints.push(lastpoint);\n lastpoint.stretchcount = 1;\n lastcolormatch = lastpoint.c;\n }\n }\n lastpoint.y = Math.floor(lastpoint.stretchcount/2);\n lastpoint.points = [{\"x\": lastpoint.x, \"y\": lastpoint.y}];\n }\n \n // With all the sides considered, we can now generate points for inside the chunk\n let count = Math.floor(chunksize * chunksize / mapkinddensity);\n console.log('We have '+ count +' new points to generate');\n for(let i=0; i<count; i++) {\n this.biomepoints.push(new biomepoint(this, Math.floor(Math.random()*(chunksize-2))+1, Math.floor(Math.random()*(chunksize-2))+1, Math.floor(Math.random()*4)+1));\n }\n \n // With all our biomepoints generated, we can start filling in our area, until they are all finished.\n while(this.biomepoints.length>0) {\n for(let i=0; i<this.biomepoints.length; i++) {\n //console.log('Processing point '+ i +\" of \"+ this.biomepoints.length);\n //console.log(this.biomepoints[i].x);\n if(this.biomepoints[i].advance()==0) {\n this.biomepoints.splice(i, 1); // This one has no work left. Remove it\n i--; // Also, back up the iterator, so we will still see the next one in line\n }\n }\n }\n }", "setEmotion(data) {\n\n // If there are no faces on the screen, let our emotion be 'empty'.\n if (!Array.isArray(data) || data.length === 0) {\n return this.setState({ emotion: 'empty' });\n }\n\n const { scores } = data[0]; // Check only the largest face\n const emotions = Object.keys(scores); // Get a list of possible emotions\n const results = []; // Create an array to contain our list of emotions\n\n // Push each emotion value to the 'results' array.\n for (const emotion of emotions) {\n results.push({\n emotion: emotion,\n value: scores[emotion],\n });\n }\n\n // Sort the 'results' array to find the strongest emotion.\n const sortedResults = results.sort((a, b) => b.value - a.value);\n\n // Return the strongest emotion.\n return this.setState({ emotion: sortedResults[0].emotion });\n }", "function genMEDigestion(enzyArray) {\r\n //max emzymes == 3\r\n var array = [];\r\n\r\n //at least have 2 enzymes\r\n if (enzyArray.length > 1) {\r\n if (enzyArray.length == 2) {\r\n array.push([enzyArray[0], enzyArray[1]]);\r\n }\r\n else {\r\n //3 enzymes\r\n //combine all enzymes into the first array\r\n var firstArray = [];\r\n $.each(enzyArray, function (i, e) {\r\n firstArray.push(e);\r\n });\r\n array.push(firstArray);\r\n //2 emzymes combination\r\n array.push([enzyArray[0], enzyArray[1]]);\r\n array.push([enzyArray[0], enzyArray[2]]);\r\n array.push([enzyArray[1], enzyArray[2]]);\r\n } \r\n }\r\n \r\n return array;\r\n}", "function update_document_scores() {\n\tfor (article in file_entity_map) {\n\t\tvar entity_sum = 0;\n\t\tvar article_score = 0;\n\t\tfor (cur_entity in file_entity_map[article]) {\n\t\t\tunformatted_entity = unformat_name(cur_entity);\n// \t\t\tarticle_score += (file_entity_map[article][cur_entity] * entity_weight_map[unformatted_entity]);\n// \t\t\tentity_sum += file_entity_map[article][cur_entity];\n\t\t\tarticle_score += entity_weight_map[unformatted_entity];\n\t\t\tentity_sum += 1;\n\t\t}\n\n\t\tif (entity_sum != 0)\n\t\t\tarticle_score /= entity_sum;\n\n\t\tif (article_score > 1)\n\t\t\tarticle_score = 1;\n\n\t\tarticle_weight_map[article] = article_score;\n\t}\n\n\tupdate_timeline();\n\tupdate_doc_table();\n}", "function mergeGeneratedEcqmData(measures) {\n const generatedEcqmStrataJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../../util/measures/generated-ecqm-data.json'), 'utf8'));\n\n measures.forEach(function(qppItem, index) {\n if (qppItem.category !== 'quality') return;\n const ecqmInfo = _.find(generatedEcqmStrataJson, {'eMeasureId': qppItem.eMeasureId});\n if (!ecqmInfo) return;\n measures[index].eMeasureUuid = ecqmInfo.eMeasureUuid;\n measures[index].metricType = ecqmInfo.metricType;\n measures[index].strata = ecqmInfo.strata;\n });\n\n // This is a manually created file from from the eCQM_EP_EC_May2017.zip for the 4 missing measures.\n const manuallyAddedEcqmStrataJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../../../util/measures/2018/manually-created-missing-measures.json'), 'utf8'));\n measures.forEach(function(qppItem, index) {\n if (qppItem.category !== 'quality') return;\n const manualEcqmInfo = _.find(manuallyAddedEcqmStrataJson, {'eMeasureId': qppItem.eMeasureId});\n if (!manualEcqmInfo) return;\n measures[index].eMeasureUuid = manualEcqmInfo.eMeasureUuid;\n measures[index].metricType = manualEcqmInfo.metricType;\n measures[index].strata = manualEcqmInfo.strata;\n if (manualEcqmInfo.overallAlgorithm) {\n measures[index].overallAlgorithm = manualEcqmInfo.overallAlgorithm;\n }\n });\n}", "function calcModernChunks(viewDistance, maxPlayers) {\n return roundMemory((viewDistance * maxPlayers) / 2205);\n}", "getNormalizedIntensityAndAdjustedEnvelopes(totDistributionList, modifiedPeakList) {\n let len = totDistributionList.length;\n let peakListLen = modifiedPeakList.length;\n let count = 0;\n let maxinte = 0;\n let mininte = 100;\n let peakMaxinte = 0;\n let peakMininte = 10000000;\n let maxMz = 0;\n let minMz = 10000000;\n let matchedPeakList = [];\n for (let i = 0; i < len; i++) { //iterating through actual peaks in this envelope\n for (let j = 0; j < peakListLen; j++) { //iterating through theo peaks in the data \t\n let mzDifference = Math.abs(totDistributionList[i].mass - modifiedPeakList[j].getPos());\n if (mzDifference <= this.toleraceMassDiff) {\n if (maxMz < totDistributionList[i].mass) {\n maxMz = totDistributionList[i].mass;\n }\n if (minMz > totDistributionList[i].mass) {\n minMz = totDistributionList[i].mass;\n }\n matchedPeakList.push([i, j]); //i is env index, j is peak index\n count = count + 1;\n }\n }\n }\n maxMz = maxMz + this.toleraceMassDiff;\n minMz = minMz - this.toleraceMassDiff;\n /*previous function skews the result if there are > 1 peaks in the mz range and later one has high intensity\nmake sure the max min value changed when it is the peak that is closest to the given env\nfor now, will check if the peak has any envelopes within error tolerance\n*/\n for (let j = 0; j < peakListLen; j++) {\n if (modifiedPeakList[j].getPos() >= minMz && modifiedPeakList[j].getPos() <= maxMz) {\n if (peakMaxinte < modifiedPeakList[j].getIntensity()) {\n //for all env dots, check if this peak really belongs to this envelope\n for (let env = 0; env < totDistributionList.length; env++) {\n if (Math.abs(totDistributionList[env].mass - modifiedPeakList[j].getPos()) <= this.toleraceMassDiff) {\n peakMaxinte = modifiedPeakList[j].getIntensity();\n }\n }\n }\n if (peakMininte > modifiedPeakList[j].getIntensity()) {\n for (let env = 0; env < totDistributionList.length; env++) {\n if (Math.abs(totDistributionList[env].mass - modifiedPeakList[j].getPos()) <= this.toleraceMassDiff) {\n peakMininte = modifiedPeakList[j].getIntensity();\n }\n }\n }\n }\n }\n for (let i = 0; i < len; i++) {\n if (minMz <= totDistributionList[i].mass && totDistributionList[i].mass <= maxMz) {\n if (maxinte < totDistributionList[i].intensity) {\n maxinte = totDistributionList[i].intensity;\n }\n if (mininte > totDistributionList[i].intensity) {\n mininte = totDistributionList[i].intensity;\n }\n }\n }\n /*when calculating new y pos, when a later envelope has higher y pos, evaluate again after reducing peak inte\n based on that higher envelope, not in the previous left-to-right order.\n \n keep marking peak as shared peak as moving from left to right, and when an envelope meets a shared peak,\n check if the previous envelope with which it shares the peak had higher intensity at that peak.\n In order to compare, save the original intensity value in each envelope property for envelopes with shared\n peak. Then compare, and rewrite the previous y pos if needed. */\n if (count != 0) {\n let avg;\n let distributionAvgInte;\n avg = (peakMaxinte + peakMininte) / 2;\n distributionAvgInte = (maxinte + mininte) / 2;\n for (let i = 0; i < totDistributionList.length; i++) {\n if (avg == 0) {\n avg = 1;\n }\n totDistributionList[i].intensity = (avg * totDistributionList[i].intensity) / distributionAvgInte;\n if (totDistributionList[i].intensity < 0 || distributionAvgInte <= 0) {\n totDistributionList[i].intensity = 0;\n }\n ;\n for (let j = 0; j < matchedPeakList.length; j++) {\n if (matchedPeakList[j][0] == i) {\n let p = matchedPeakList[j][1];\n //store original peak intensity value only when it is evaluted for the first time\n //not going to run when called from peakData because it is already evaluated ther\n let newInte = modifiedPeakList[p].getIntensity() - totDistributionList[i].intensity;\n modifiedPeakList[p].setIntensity(newInte);\n if (modifiedPeakList[p].getIntensity() < 0) {\n modifiedPeakList[p].setIntensity(0);\n }\n //modifiedPeakList[p][\"isPeakShared\"] = true;\n }\n }\n }\n }\n //convert aminoDist to peaks\n let newDistList = this.aminoDistToPeaks(totDistributionList);\n //remove envelopes without matching peaks\n this.removeEnvelopes(newDistList, matchedPeakList);\n return newDistList;\n }", "function buildPartWithScoreQueue(scoreThreshold, localMaximumRadius, scores) {\n var _a = scores.shape, height = _a[0], width = _a[1], numKeypoints = _a[2];\n var queue = new max_heap_1.MaxHeap(height * width * numKeypoints, function (_a) {\n var score = _a.score;\n return score;\n });\n for (var heatmapY = 0; heatmapY < height; ++heatmapY) {\n for (var heatmapX = 0; heatmapX < width; ++heatmapX) {\n for (var keypointId = 0; keypointId < numKeypoints; ++keypointId) {\n var score = scores.get(heatmapY, heatmapX, keypointId);\n // Only consider parts with score greater or equal to threshold as\n // root candidates.\n if (score < scoreThreshold) {\n continue;\n }\n // Only consider keypoints whose score is maximum in a local window.\n if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores)) {\n queue.enqueue({ score: score, part: { heatmapY: heatmapY, heatmapX: heatmapX, id: keypointId } });\n }\n }\n }\n }\n return queue;\n}", "prepareData (data, needBottomBody) {\n const topCount = this.topBodyList.length\n const bottomCount = this.bottomBodyList.length\n const index = topCount + bottomCount\n\n if (index > data.length - 1) return \n\n const maxSize = Math.max(...data.map(m => m[1]))\n const minSize = Math.min(...data.map(m => m[1]))\n const size = parseInt(data[index][1], 10)\n const val = MathUtils.map(size, minSize, maxSize, this.minFontSize, this.maxFontSize)\n\n let colorVal = Math.floor(MathUtils.map(size, minSize, maxSize, this.minColor, 255))\n\n // rgb(169, 134, 103)\n // rgb(184, 190, 150)\n // const color = 'rgb(' + colorVal + ',' + colorVal + ',' + colorVal + ')'\n const color = 'rgba(' + 184 + ',' + 190 + ',' + 150 + ',' + colorVal / 255 + ')'\n // const color = 'rgba(' + 169 + ',' + 134 + ',' + 103 + ',' + colorVal / 255 + ')'\n // NOTE: Create word bodies\n const World = Matter.World\n const wordData = {}\n wordData.word = data[index][0]\n wordData.size = val\n wordData.link = data[index][2]\n wordData.color = color\n\n\n const propotion = this.isMobile ? 5 : 2\n const isTopBody = needBottomBody ? Math.floor(Math.random() * propotion) === 0 : true\n const wordBody = this.createWordBody(wordData, isTopBody)\n const angle = Math.floor(Math.random() * 20) - 10\n const radian = angle * ( Math.PI / 180 )\n Matter.Body.rotate(wordBody, radian)\n World.add(this.engine.world, wordBody)\n\n if (isTopBody) {\n this.topBodyList.push(wordBody)\n } else {\n this.bottomBodyList.push(wordBody)\n }\n \n this.creationTimerId = setTimeout(() => {\n this.prepareData(data, needBottomBody)\n }, this.createDuration) \n }", "function genMEBands(digestArray, enzymes, seqCount) {\r\n var bands = [];\r\n //loop the digestArray\r\n $.each(digestArray, function (i, d) {\r\n //enzymes are all the cuts for the current plasmid\r\n var cuts = $.grep(enzymes, function (sd, si) {\r\n //return all the cuts in d, array of digesiton enzymes\r\n return $.inArray(sd.name, d) != -1;\r\n })\r\n //sort cuts by the cut position from small to big\r\n cuts.sort(sortByProperty('cut'));\r\n \r\n var hasMethylation = false; //tag for methylation later on\r\n if (cuts.length > 0) {\r\n //-------------------------first ignore the methylation\r\n var curBands = [];\r\n for (var i = 0; i < cuts.length; i++) {\r\n if (cuts[i].methylation == true) {\r\n //tag this to add an extra lane on gel\r\n hasMethylation = true;\r\n }\r\n var obj = {};\r\n obj.label = d.reverse().join(\"-\");\r\n obj.type = \"cut\";\r\n if (i == cuts.length - 1) {\r\n obj.name = cuts[cuts.length - 1].name + '-' + cuts[0].name;\r\n obj.clockwise = cuts[cuts.length - 1].clockwise + '-' + cuts[0].clockwise;\r\n obj.bandRange = cuts[cuts.length - 1].cut == seqCount ? '1-' + cuts[0].cut : cuts[cuts.length - 1].cut + '-' + cuts[0].cut;\r\n obj.Size = cuts[cuts.length - 1].cut == seqCount ? cuts[0].cut : (seqCount - cuts[cuts.length - 1].cut + cuts[0].cut);\r\n obj.Mass = 100;\r\n }\r\n else {\r\n obj.name = cuts[i].name + '-' + cuts[i + 1].name;\r\n obj.clockwise = cuts[i].clockwise + '-' + cuts[i+1].clockwise;\r\n obj.bandRange = cuts[i].cut + '-' + cuts[i + 1].cut;\r\n obj.Size = cuts[i + 1].cut - cuts[i].cut;\r\n obj.Mass = 100;\r\n }\r\n obj.logSize = +Math.log10(obj.Size).toFixed(3);\r\n curBands.push(obj);\r\n }//end of for loop\r\n if (curBands.length > 0) {\r\n bands.push(curBands);\r\n }\r\n\r\n //---------------------------- deal with methylation\r\n if (hasMethylation) {\r\n var methyBands = []; //final return array\r\n //remove all the cuts in cuts that has methylation ==true\r\n var cutsCopy = []; //temp array, for removing completely blocked\r\n cutsCopy = $.grep(cuts, function (v) {\r\n return v.methylation != true;\r\n });\r\n\r\n if (cutsCopy.length === 0) {\r\n //nothing left, generate the circular plasmid\r\n var obj = {};\r\n obj.clockwise = null;\r\n obj.name = d.reverse().join(\"-\") + ':' + 'methy';\r\n obj.label = d.reverse().join(\"-\") + ':' + 'methy';\r\n obj.type = \"cut\";\r\n obj.bandRange = \"0-0\"; //if \"0-0\", then it is circular\r\n obj.Size = seqCount;\r\n obj.Mass = 100;\r\n obj.logSize = +Math.log10(obj.Size).toFixed(3);\r\n methyBands.push(obj);\r\n }\r\n else {\r\n //assume always completely cut\r\n for (var i = 0; i < cutsCopy.length; i++) {\r\n var obj = {};\r\n obj.clockwise = cutsCopy[i].clockwise;\r\n obj.label = d.reverse().join(\"-\") + ':' + 'methy';\r\n obj.type = \"cut\";\r\n if (i == cutsCopy.length - 1) {\r\n obj.name = cuts[cuts.length - 1].name + '-' + cuts[0].name;\r\n obj.clockwise = cuts[cuts.length - 1].clockwise + '-' + cuts[0].clockwise;\r\n obj.bandRange = cutsCopy[cutsCopy.length - 1].cut == seqCount ? '1-' + cutsCopy[0].cut : cutsCopy[cutsCopy.length - 1].cut + '-' + cutsCopy[0].cut;\r\n obj.Size = cutsCopy[cutsCopy.length - 1].cut == seqCount ? cutsCopy[0].cut : (seqCount - cutsCopy[cutsCopy.length - 1].cut + cutsCopy[0].cut);\r\n obj.Mass = 100;\r\n }\r\n else {\r\n obj.name = cuts[i].name + '-' + cuts[i + 1].name;\r\n obj.clockwise = cuts[i].clockwise + '-' + cuts[i + 1].clockwise;\r\n obj.bandRange = cutsCopy[i].cut + '-' + cutsCopy[i + 1].cut;\r\n obj.Size = cutsCopy[i + 1].cut - cutsCopy[i].cut;\r\n obj.Mass = 100;\r\n }\r\n obj.logSize = +Math.log10(obj.Size).toFixed(3);\r\n methyBands.push(obj);\r\n }\r\n }//end of cutsCopy.length\r\n if (methyBands.length > 0) {\r\n bands.push(methyBands);\r\n }\r\n\r\n }//end of hasMethylation\r\n } //end of cuts.length\r\n }) // end of looping digestarray\r\n\r\n return bands;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get timeout for token refresh
function getTokenRefreshTimeout(token) { if (token) { var decoded = jwt.decode(token); // expiry date in future? if (decoded.exp && 1000 * decoded.exp > Date.now()) { // refresh once a day or halfway to expiry var timeout = Math.min(24 * 3.6e6, Math.ceil((1000 * decoded.exp - Date.now()) / 2)); return timeout; } } // retry in 1s return 1000; }
[ "setupTokenReconnectTimer(){\n log.debug('[PageSharedDB] setting up timer for token refresh')\n let reconnectInMilliseconds = (this.expires_at * 1000) - Date.now() - 5000\n clearTimeout(this.tokenReconnectTimer)\n\n this.tokenReconnectTimer = setTimeout(() => {\n this.tokenReconnect()\n }, reconnectInMilliseconds)\n }", "async getRefreshToken () {\n return this.client.auth.refresh_token\n }", "getTimeout(){cov_50nz68pmo.f[2]++;cov_50nz68pmo.s[6]++;return this.timeout;}", "checkToken() {\n if(localStorage.getItem(\"token_time\") != null) {\n if(new Date().getTime() - new Date(localStorage.getItem(\"token_time\")).getTime() > 60000) {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n console.log(\"update token\");\n this.updateToken();\n }\n } else {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n this.updateToken();\n }\n }", "function timeUntilActivationTimeout() {\n // use same timeout logic as `@adobe/node-openwhisk-newrelic`: https://github.com/adobe/node-openwhisk-newrelic/blob/master/lib/metrics.js#L38-L44\n return (process.env.__OW_DEADLINE - Date.now()) || DEFAULT_METRIC_TIMEOUT_MS;\n}", "function setAutoRefreshTimeout() {\n clearTimeout(autoRefreshTimeoutId);\n if (auth.autoRefresh && typeof auth.expires !== 'undefined') {\n autoRefreshTimeoutId = setTimeout(auth.refresh, auth.expires + 1000);\n }\n }", "function resetSecretLinkTimeout() {\n timeout = 0;\n}", "function getTimeout(timeout) {\n if (!isFinite(timeout) || !util.isPositiveNumber(timeout)) {\n timeout = 0;\n }\n \n return timeout;\n }", "isTokenExpired(token){\n try {\n const decoded = decode(token);\n return (decoded.exp < Date.now() / 1000);\n } catch (err) {\n console.log(\"expired check failed!\");\n return true;\n }\n }", "function updateTimeout() {\n $timeout(function () {\n if ($scope.remainingAuthSeconds > 0) {\n $scope.remainingAuthSeconds--;\n $scope.$digest();\n //recurse\n updateTimeout();\n }\n\n }, 1000, false); // 1 second, do NOT execute a global digest \n }", "async setRefreshToken (token) {\n this.client.auth.refresh_token = token\n }", "function setRefreshTimeout() {\r\n clearRefreshTimeout();\r\n _highlightTimeout = setTimeout( refreshCallback, 500 );\r\n }", "get maxIdleTime() { return 60 * 60 * 1000; }", "function updateSLSessionTimeout() {\n //Calculates and store when session will be expired\n console.log(\"Updating SL Session Expiration date in cache\")\n redisClient.hget(hash_Timeout, hash_Timeout, function (error, reply) {\n if (error) {\n console.error(\"Can't Update Session Timeout in Redis \" + error)\n } else {\n var expire = moment(moment.now()).add(reply, 'minutes')\n redisClient.hset(hash_Timeout, timout_exp, expire.format())\n }\n })\n}", "revToken (topic) {\n if (!topic || !topic.endsWith('token')) return // donot care this topic\n clearTimeout(this.waitTimer)\n this.counter = 0\n clearTimeout(this.timer)\n this.timer = setTimeout(() => { // refresh every 2 hours\n this.refreshToken()\n }, this.refreshTokenTime)\n }", "get realmAccessToken() {\n return this.realmUser.then(\n // refresh access_token\n // TODO: should optimally call only when the access_token is close to expiration?\n (user) => user.refreshCustomData().then(() => user.accessToken)\n );\n }", "static makeTimeoutError() {\n const timeoutErr = new TypeError(HttpClient.TIMEOUT_ERROR_CODE);\n timeoutErr.code = HttpClient.TIMEOUT_ERROR_CODE;\n return timeoutErr;\n }", "checkIdToken() {\r\n console.log('check Id token expiration')\r\n let user = this.user();\r\n if (user) {\r\n const expirationDateSecs = user.idTokenClaims.exp\r\n const expDate = new Date(expirationDateSecs * 1000)\r\n console.log('expDateSecs: '+expDate);\r\n\r\n if ((new Date()).getTime() >= expirationDateSecs * 1000) {\r\n console.log('IdToken expired. Clearing internal cache')\r\n this.clearLocal()\r\n return false \r\n } else {\r\n console.log('ID token is still valid')\r\n return true\r\n } \r\n } else {\r\n return false\r\n }\r\n }", "function callbackTimeout() {\n clearInterval(botCallBackTimer);\n botCallback = null;\n setBotButtonStates(true);\n logMessage('wrn', 'BOT TIMEOUT', 'Your bot timed out. It may have forgotten to call SendAction() before it exited or returned.');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write `value` as an 8bit signed integer and move pointer forward by 1 byte.
writeInt8(value) { this.ensureAvailable(1); this._data.setInt8(this.offset++, value); this._updateLastWrittenByte(); return this; }
[ "pushByte(value) {\n this.write(\">\" + \"+\".repeat(value));\n this.stack.push(StackEntry(DataType.Byte, 1));\n }", "function UInt32toUInt8(value) {\n console.log(value);\n t = [\n value >> 24,\n (value << 8) >> 24,\n (value << 16) >> 24,\n (value << 24) >> 24\n ];\n console.log(t);\n return t;\n}", "function parseToSignedByte(value) {\n value = (value & 127) - (value & 128);\n return value;\n}", "writeValue(buffer, value) {\n assert.isBuffer(buffer);\n assert.instanceOf(value, [ArrayBuffer, Uint8Array]);\n buffer\n .addAll(flexInt.makeValueBuffer(value.byteLength))\n .addAll(value);\n }", "static bytes8(v) { return b(v, 8); }", "function swap8Bytes (val) {\n return (\n (((val) >> 56) & 0x00000000000000FF) | (((val) >> 40) & 0x000000000000FF00) |\n (((val) >> 24) & 0x0000000000FF0000) | (((val) >> 8) & 0x00000000FF000000) |\n (((val) << 8) & 0x000000FF00000000) | (((val) << 24) & 0x0000FF0000000000) |\n (((val) << 40) & 0x00FF000000000000) | (((val) << 56) & 0xFF00000000000000)\n );\n}", "function UInt8toUInt32(value) {\n return (new DataView(value.buffer)).getUint32();\n}", "pushWord(value) {\n this.pushByte(hi(value));\n this.pushByte(lo(value));\n }", "writeValue(buffer, value) {\n assert.isBuffer(buffer);\n const convertedValue = str_to_num_1.default(value);\n if (convertedValue !== undefined)\n value = convertedValue;\n assert.instanceOf(value, Number);\n const byteBuffer = new ArrayBuffer(4);\n new DataView(byteBuffer).setFloat32(0, value);\n buffer.addAll(byteBuffer);\n }", "function getByteN(value, n) {\n return ((value >> (8 * n)) & 0b11111111);\n}", "function rotateLeft8Bit(value, n) {\n return ((value << n) | (value >> (8 - n))) & 0xFF;\n}", "writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }", "static uint8(v) { return n(v, 8); }", "static int8(v) { return n(v, -8); }", "function encodeUint8(num) {\n if (num > 255) {\n throw new Error(\"overflow\");\n }\n var encoded = new Uint8Array(8);\n encoded[0] = num;\n return encoded;\n}", "function s16(val) {\n return (val << 16) >> 16;\n}", "function limitOctetNumber(value) {\r\n\r\n if (value > 255) {\r\n\r\n return Math.floor(value / 10);\r\n } else {\r\n return value;\r\n }\r\n}", "static bytes7(v) { return b(v, 7); }", "setByte(depth) {\n this.write(\"<\".repeat(depth) + \"[-]\"); // go the value, and zero it\n this.write(\">\".repeat(depth)); // go back to the top of the stack\n this.write(\"[\"); // repeat until the value at tope is 0\n this.write(`-${\"<\".repeat(depth)}+${\">\".repeat(depth)}`); // decrement the stack-top and increment the target byte\n this.write(\"]\"); // end loop.\n this.write(\"<\"); // move pointer one step back.\n }", "function encode_int(v) {\n if (!(v instanceof BigInteger) ||\n v.compareTo(BigInteger.ZERO) < 0 ||\n v.compareTo(LARGEST_NUM_PLUS_ONE) >= 0) {\n throw new Error(\"BigInteger invalid or out of range\");\n }\n return intToBigEndian(v);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Chapter 101 RopeGroup Introduction done
function C101_KinbakuClub_RopeGroup_Introduced() { C101_KinbakuClub_RopeGroup_IntroDone = true; }
[ "function gotHamletTestamentData () {\n // Join the two texts together into a single string\n let allText = hamletText + ' ' + oldTestamentText;\n // Create a Markov chain generator\n markov = new RiMarkov(4);\n // Load the string of both books into the Markov generator\n markov.loadText(allText);\n // Generate a paragraph of text\n generateParagraph();\n console.log('generated');\n}", "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_HelplessStruggle() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteStruggle\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}", "function automatedReadabilityIndex(letters, numbers, words, sentences) {\n    return (4.71 * ((letters + numbers) / words))\n        + (0.5 * (words / sentences))\n        - 21.43;\n}", "function generateMadlibsIntro(product) {\n var numVariants = \"one size\";\n if (product.sizes.data.length === 2) {\n numVariants = `two sizes (${product.sizes.data.join(\", \")})`;\n }\n if (product.sizes.data.length === 3) {\n numVariants = `three sizes (${product.sizes.data.join(\", \")})`;\n }\n\n var segment = \"midrange\";\n if (product.volume.data.length !== 0) {\n const cpl = product.price / product.volume.data[0].val;\n if (cpl < CPL_MIDRANGE) segment = \"budget\";\n if (cpl > CPL_PREMIUM) segment = \"premium\";\n }\n\n const bestUsedFor = (product.best_used_for == 'Hiking') ? \"hiking\" : \"backpacking\";\n return `<p>The ${product.name} is a ${segment} ${bestUsedFor} backpack that comes in ${numVariants}.</p>`;\n}", "function C101_KinbakuClub_RopeGroup_CassiContinue() {\n\tActorAddOrgasm();\n\tC101_KinbakuClub_RopeGroup_PlayerArousal = C101_KinbakuClub_RopeGroup_PlayerArousal - 200;\n\tC101_KinbakuClub_RopeGroup_ForcingCassi = false;\n\tC101_KinbakuClub_RopeGroup_PressingCassi = false;\n\tC101_KinbakuClub_RopeGroup_CanPressCassi = true;\n\tif (ActorGetValue(ActorLove) <= 2) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 686;\n\t\tif (ActorHasInventory(\"Cuffs\")) {\n\t\t\tOverridenIntroText = GetText(\"CassiDoneUnCuff\");\n\t\t\tActorRemoveInventory(\"Cuffs\");\n\t\t} else OverridenIntroText = GetText(\"CassiDone\");\n\t} else {\n\t\tC101_KinbakuClub_RopeGroup_OrgasmCount++\n\t\tif (C101_KinbakuClub_RopeGroup_OrgasmCount >= 2) {\n\t\t\tC101_KinbakuClub_RopeGroup_AnkleGrab = false;\n\t\t\tC101_KinbakuClub_RopeGroup_fingerinsertion = false;\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 685;\n\t\t\tOverridenIntroText = GetText(\"CassiAsks\");\n\t\t}\n\t}\n}", "function initializeExercise() {\n\t\t\n\t }", "function C101_KinbakuClub_RopeGroup_AddedExtras(ExtraNumber) {\n\tif (ExtraNumber == 1 && ActorGetValue(ActorSubmission) >= 3) {\n\t\tOverridenIntroText = GetText(\"NotBelted\");\n\t\tC101_KinbakuClub_RopeGroup_PlayerFreed()\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 691;\n\t} else {\n\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\") && !PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t} else {\n\t\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\")) {\n\t\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueEggNBelted\");\n\t\t\t\telse OverridenIntroText = GetText(\"EggNBelted\");\n\t\t\t} else {\n\t\t\t\tif (!PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArguePlugNBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"PlugNBelted\");\n\t\t\t\t} else {\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueJustBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"JustBelted\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tC101_KinbakuClub_RopeGroup_FullyExposed = false;\n\t\tPlayerLockInventory(\"ChastityBelt\");\n\t}\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}", "function describeTextbook() {\n\tvar textbookString = brackets.currentTextbook.name;\n\ttextbookString += \" by \" + brackets.currentTextbook.author + \"\\n\";\n\tvar numberOfElements = brackets.currentTextbook.elements.length;\n\tfor (var i = 0; i < length; i++) {\n\t\ttextbookString += \"\\n\" + i + \": \";\n\t\tswitch(brackets.currentTextbook.elements[i].type) {\n\t\t\tcase 'pdfRectangle':\n\t\t\t\ttextbookString += \"Rectangle from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'pdfHorizontal':\n\t\t\t\ttextbookString += \"Horizontal clip from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'youtube':\n\t\t\t\ttextbookString += \"YouTube clip from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'text' :\n\t\t\t\ttextbookString += \"Some text\";\n\t\t\tcase 'wikipedia':\n\t\t\t\ttextbookString += \"Wikipedia clip from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tcase 'image':\n\t\t\t\ttextbookString += \"Image from \" + brackets.currentTextbook.elements[i].source;\n\t\t\tdefault:\n\t\t\t\ttextbookString += \"Undefined type\";\n\t\t}\n\t} \n}", "function C101_KinbakuClub_RopeGroup_HelplessKnot() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteKnot\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}", "function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// During Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 660) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t}\n\t// Suspended5\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 661 && C101_KinbakuClub_RopeGroup_CurrentStage <= 662) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5BallGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5ClothGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"TapeGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5TapeGag.jpg\", 865, 126);\n\t}\n\n\t//Suspended\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 642) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 650 && C101_KinbakuClub_RopeGroup_CurrentStage <= 690)) {\n\t\t// Player images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 672 && C101_KinbakuClub_RopeGroup_PlayerPose != \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_PlayerPose + \".jpg\", 835, 75);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t\tif (C101_KinbakuClub_RopeGroup_TsuriFrogTied) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5FrogTie.png\", 769, 231);\n\t\tif (C101_KinbakuClub_RopeGroup_FullyExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Pantieless.jpg\", 880, 294);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5LookUp.png\", 864, 136);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 671 && PlayerHasLockedInventory(\"SockGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended8S.jpg\", 888, 157);\n\t\t\n\t\t// Cassi iamges\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Cassi1.png\", 948, 65);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 666) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 667) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectKey.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 668) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_RemovingBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 672) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_LeftHoldingTape.jpg\", 608, 70);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 673) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Scissors.png\", 700, 77);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDown.png\", 660, 120);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674 && ActorGetValue(ActorSubmission) >= 0) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDownCuffs.png\", 776, 403);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 686){\n\t\t\tif (C101_KinbakuClub_RopeGroup_PressingCassi) {\n\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedPressed.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFingerPressed.png\", 770, 230);\n\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniPressed.png\", 770, 230);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (C101_KinbakuClub_RopeGroup_ForcingCassi) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedStruggle.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_AnkleGrab) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniAnkleHold.png\", 770, 230);\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffed.png\", 825, 251);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFinger.png\", 825, 251);\n\t\t\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Cunni.png\", 825, 251);\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\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Done.png\", 835, 73);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687 && ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneCuffs.png\", 874, 193);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 688 && C101_KinbakuClub_RopeGroup_CurrentStage <= 689) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelt.png\", 835, 63);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 690) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelted.png\", 835, 66);\n\t\t\n\n\t\t// Lucy images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 662 && C101_KinbakuClub_RopeGroup_CurrentStage <= 665) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Lucy.png\", 629, 51);\n\t\t\n\t\t// Player arousal\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 680) {\n\t\t\tif (C101_KinbakuClub_RopeGroup_PreviousTime == 0) C101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\tif (CurrentTime > (C101_KinbakuClub_RopeGroup_PreviousTime + 1000)) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (ActorGetValue(ActorSubmission) < 0) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (PlayerHasLockedInventory(\"VibratingEgg\")) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t}\n\t\t\tif (C101_KinbakuClub_RopeGroup_PlayerArousal > 500) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal = 500;\n\t\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 681\n\t\t\t\tOverridenIntroText = GetText(\"SuspendedOrgasm\");\n\t\t\t}\n\t\t}\n\t\t// Draw the players arousal level\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 681) {\n\t\t\tDrawRect(638, 48, 14, 504, \"white\");\n\t\t\tDrawRect(640, 50, 10, (500 - C101_KinbakuClub_RopeGroup_PlayerArousal), \"#66FF66\");\n\t\t\tDrawRect(640, (550 - C101_KinbakuClub_RopeGroup_PlayerArousal), 10, C101_KinbakuClub_RopeGroup_PlayerArousal, \"red\");\n\t\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 300) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Gushing.png\", 601, 2);\n\t\t}\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}", "function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// Images during Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 636) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}", "function main()\n{\t\n\ttale = new Tale();\n\n\t// process title, subtitle, author passages\n\n\tsetPageElement('storyMenu', 'StoryMenu', '');\n\tsetPageElement('storyTitle', 'StoryTitle', 'Untitled Story');\n\tsetPageElement('storySubtitle', 'StorySubtitle', '');\t\t\n\tsetPageElement('storyAuthor', 'StoryAuthor', '');\n\t\n\tif (tale.has('StoryTitle'))\n\t{\t\t\n\t\tdocument.title = tale.get('StoryTitle').text;\n\t\n\t\tif (tale.has('StorySubtitle'))\n\t\t\tdocument.title += ': ' + tale.get('StorySubtitle').text;\n\t};\n\n\t// initialize macros\n\t\n\tfor (macro in macros)\n\t\tif (typeof macro.init == 'function')\n\t\t\tmacro.init();\n\t\n\t// process passages tagged 'stylesheet'\n\t\n\tvar styles = tale.lookup('tags', 'stylesheet');\n\t\n\tfor (var i = 0; i < styles.length; i++)\n\t\taddStyle(styles[i].text);\n\t\t\n\t// process passages tagged 'script'\n\t\n\tvar scripts = tale.lookup('tags', 'script');\n\t\t\n\tfor (var i = 0; i < scripts.length; i++)\n\t\ttry\n\t\t{\n\t\t\t eval(scripts[i].text);\n\t\t}\n\t\tcatch (e)\n\t\t{\t\t\n\t\t\talert('There is a technical problem with this story (' +\n\t\t\t\t\t\tscripts[i].title + ': ' + e.message + '). You may be able ' +\n\t\t\t\t\t\t'to continue reading, but all parts of the story may not ' +\n\t\t\t\t\t\t'work properly.');\n\n\t\t};\n\t\t\t\n\t// initialize history and display initial passages\n\t\n\tstate = new History();\n\tstate.init();\n\t\t\n\tconsole.log('init complete', tale, state);\n}", "function main() {\n slideEls = document.querySelectorAll('.presentation > div')\n\n // Set up\n getSlideNumberFromUrlFragment()\n showSlide(true, true)\n onSlideEntry(slideEls[currentSlideNumber], false)\n\n // Specific slide preparations\n prepareFillLoupe()\n underlinePlaygroundPosition({ target: document.querySelector('#upo-p') })\n underlinePlaygroundSize({ target: document.querySelector('#upo-s') })\n underlinePlaygroundClearing({ target: document.querySelector('#upo-c') })\n underlinePlaygroundOpacity({ target: document.querySelector('#upo-o') })\n document.querySelectorAll('label').forEach(function(el) { el.classList.remove('visible') })\n\n // Slide manipulation\n hyphenateSlides()\n setUpBetterPunctuation()\n\n document.body.addEventListener('keydown', onKeyDown)\n document.body.focus()\n}", "function programIntro() {\n\t// member varables\n\tthis.m_programList = [];\n\tthis.m_programCount = 0;\n}", "function SimpleStoryCreator() {\n // ************************************************************\n // * All required lists *\n // ************************************************************\n\n // List of all possible story plots\n var rPlotList = [\n\t\"destroy\",\n\t\"kidnap\",\n\t\"witch\",\n\t\"revenge\"\n ];\n\n // List of story intros\n var rIntroList = [\n\t\"Once Upon a Time\",\n\t\"In a land far away\",\n\t\"Before you were born\",\n\t\"In a little village\"\n ];\n\n // List of possible endings for the story\n var rPlotEndList = [\n\t\"flee\",\n\t\"kill\",\n\t\"kill_weapon\"\n ];\n\n // List of all good people (read: Heros)\n var rHeroList = [\n\t{ Article: \"a\" , Name: \"trader\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"merchant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesperson\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesman\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"peasant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"farmer\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"farmer's wife\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"hero\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"heroine\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"blacksmith\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"poet\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"programmer\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"musician\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"princess\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"prince\", Gender: \"male\" }\n ];\n\n // List of all adjectives of the Hero\n var rHeroMainAdjectiveList = [\n\t{ Article: \"a\", Word: \"brave\" },\n\t{ Article: \"a\", Word: \"wealthy\" },\n\t{ Article: \"a\", Word: \"rich\" },\n\t{ Article: \"a\", Word: \"poor\" }\n ];\n\n var rHeroSecondaryAdjectiveList = [\n\t{ Male: \"kind to everyone\", Female: \"kind to everyone\" },\n\t{ Male: \"madly in love with his wife\", Female: \"madly in love with her husband\" },\n\t{ Male: \"handsome\", Female: \"beautiful\" }\n ];\n\n // List of all bad people (read: Villains)\n var rVillainList = [\n\t{ Article: \"a\" , Name: \"warlock\" },\n\t{ Article: \"a\" , Name: \"necromancer\" },\n\t{ Article: \"a\" , Name: \"ghost\" },\n\t{ Article: \"a\" , Name: \"demon\" },\n\t{ Article: \"a\" , Name: \"goblin\" },\n\t{ Article: \"a\" , Name: \"troll\" },\n\t{ Article: \"a\" , Name: \"monster\" },\n\t{ Article: \"a\" , Name: \"dwarf\" },\n\t{ Article: \"a\" , Name: \"giant\" },\n\t{ Article: \"a\" , Name: \"barbarian\" },\n\t{ Article: \"a\" , Name: \"grook\" },\n\t{ Article: \"a\" , Name: \"rogue\" },\n\t{ Article: \"a\" , Name: \"bandit\" },\n\t{ Article: \"a\" , Name: \"rascal\" },\n\t{ Article: \"a\" , Name: \"scoundrel\" },\n\t{ Article: \"an\", Name: \"orc\" },\n\t{ Article: \"an\", Name: \"ogre\" },\n\t{ Article: \"a\" , Name: \"soldier\" },\n\t{ Article: \"a\" , Name: \"warrior\" },\n\t{ Article: \"a\" , Name: \"fighter\" },\n\t{ Article: \"a\" , Name: \"viking\" },\n\t{ Article: \"a\" , Name: \"mage\" },\n\t{ Article: \"a\" , Name: \"villain\" },\n\t{ Article: \"an\", Name: \"archer\" },\n\t{ Article: \"a\" , Name: \"phantom\" }\n ];\n\n // List of possible wording for \"kill\"\n var rKillList = [\n\t\"killed\",\n\t\"murdered\",\n\t\"slayed\",\n\t\"assassinated\"\n ];\n\n // List of possible wording for \"flee\"\n var rFleeList = [\n\t\"fled\",\n\t\"fled in terror\",\n\t\"escaped\",\n\t\"manged to escape\",\n\t\"was able to flee\"\n ];\n\n // List of possible wording for \"cheat\"\n var rCheatList = [\n\t\"cheated\",\n\t\"tricked\",\n\t\"was able to trick\",\n\t\"managed to cheat\",\n\t\"fooled\"\n ];\n\n\n // Plot: Destroy; List of ways to destroy an object\n var rDestroyList = [\n\t\"destroy\",\n\t\"ruined\",\n\t\"wrecked\",\n\t\"smashed\",\n\t\"demolished\"\n ];\n\n // Plot: Destroy; List of objects that can be destroyed\n var rDestroyObjectList = [\n\t\"house\",\n\t\"garden\",\n\t\"doghouse\",\n\t\"temple\",\n\t\"clock\",\n\t\"field\",\n\t\"farm\",\n\t\"tower\",\n\t\"building\",\n\t\"residence\",\n\t\"domicile\",\n\t\"place of birth\",\n\t\"home\",\n\t\"hovel\",\n\t\"hut\",\n\t\"flat\",\n\t\"flatlet\",\n ];\n\n\n // Plot: Witch; List of ways to cast the spell\n var rWitchList = [\n\t\"enchanted\",\n\t\"spellbound\",\n\t\"bewitched\",\n\t\"entranced\"\n ];\n\n // Plot: Witch; List of ways to end the spell\n var rWitchEndList = [\n\t\"freed\",\n\t\"ended the spell casted on\",\n\t\"ended the enchantment of\"\n ];\n\n // Plot: Kidnap; List of ways to be kidnaped\n var rKidnapList = [\n\t\"kidnapped\",\n\t\"abducted\",\n\t\"carried off\"\n ];\n\n // List of final moments\n var rFinalMoment = [\n\t\"Then\",\n\t\"Finally\",\n\t\"Ultimately\",\n\t\"In the end\",\n\t\"Thereupon\",\n\t\"Thereat\",\n\t\"After that\"\n ];\n\n // List of \"One day\" events\n var rOneDayList = [\n\t\"One day\",\n\t\"There came a day\",\n\t\"One night\"\n ];\n\n // List of all possible relatives\n var rRelativeList = [\n\t\"dog\",\n\t\"cat\",\n\t\"mother\",\n\t\"father\",\n\t\"grandfather\",\n\t\"grandmother\",\n\t\"brother\",\n\t\"son\",\n\t\"sister\",\n\t\"daughter\",\n\t\"friend\",\n\t\"mate\",\n\t\"uncle\",\n\t\"aunt\",\n\t\"son-in-law\",\n\t\"dauther-in-law\",\n\t\"goldfish\",\n\t\"lover\",\n\t\"lawyer\",\n\t\"helper\"\n ];\n\n // List of possible weapons\n var rWeaponList = [\n\t\"bastard sword\",\n\t\"dagger\",\n\t\"shovel\",\n\t\"rifle\",\n\t\"magnum\",\n\t\"UZI\",\n\t\"AK-47\"\n ];\n\n\n var rStory = []; // Stores the actual story and is returned by GetStoryText\n\n // Name : sprintf\n // Parameters : At least 2 parameters are required. 1 as the actual message, and another for the content.\n // More values have to be added in case of more placeholders.\n // Description: This function replaces placeholders acording to their type. This way it's possible\n // to format a string the way the user wants it.\n // Disclaimer : This function is (C) 2006 by Naden Badalgogtapeh. The source can be found at\n // http://www.naden.de/blog/javascript-printf\n function sprintf() {\n\tif (sprintf.arguments.length < 2) {\n\t return;\n\t}\n\n\tvar data = sprintf.arguments[0];\n\n\tfor (var k = 1; k < sprintf.arguments.length; ++k) {\n\n\t switch (typeof (sprintf.arguments[k])) {\n\t case 'string':\n\t\tdata = data.replace(/%s/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'number':\n\t\tdata = data.replace(/%d/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'boolean':\n\t\tdata = data.replace(/%b/, sprintf.arguments[k] ? 'true' : 'false');\n\t\tbreak;\n\t default:\n\t\t/// function | object | undefined\n\t\tbreak;\n\t }\n\t}\n\treturn data;\n }\n\n\n // Name : rRandom\n // Parameters : This function requires 2 parameters:\n // - aMin (Integer); The lowest possible number\n // - aMax (Integer); The highest possible number\n // Description: Generates a random number and returning it.\n // Disclaimer : Exchanged this function with a more reliable solution.\n // The new version is taken from\n // http://www.naden.de/blog/zufallszahlen-in-javascript-mit-mathrandom\n // Authors are:\n // - (C) 2006 by Naden Badalgogtapeh\n // - (C) 2008 by batzee\n // - (C) 2012 by MHN\n function rRandom(aMin, aMax) {\n\tvar lMin = Math.floor( parseInt( aMin ) );\n\tvar lMax = Math.floor( parseInt( aMax ) );\n\n\tif ( lMin > lMax) {\n\t return rRandom( lMax, lMin ); // This is a suggestion from MHN\n\t}\n\n\tif ( lMin == lMax ) {\n\t return lMin;\n\t}\n\n\tvar lRandomNumber;\n\n\t// Prevent that we go over the destined area\n\tdo {\n\t lRandomNumber = Math.random();\n\t}\n\twhile( lRandomNumber == 1.0 );\n\t// End of prevention\n\n\treturn lMin + parseInt( lRandomNumber * ( lMax-lMin + 1 ) );\n }\n\n\n // Name : NewStory\n // Parameters : aStoryMode (optional; string) - In case you want\n // a specific kind of story. Can be ignored otherwise.\n // Description: Creates a plot and builds a story upon the plot.\n // Uses a random hero and a random villain for this.\n // The story is stored in the private variable rStory and can\n // be called by using the GetStoryText-routine\n this.createStory = function ( aStoryMode ) {\n\t// General information about the story\n\tvar lPlotMode = rPlotList[ rRandom( 1, rPlotList.length ) - 1 ];\n\tvar lIntro = rIntroList[ rRandom( 1, rIntroList.length ) - 1 ];\n\tvar lSubIntro = rRandom( 1, 99 );\n\tvar lPlotEndMode = rPlotEndList[ rRandom( 1, rPlotEndList.length ) - 1 ];\n\tvar lHeroID = rRandom( 1, rHeroList.length ) - 1;\n\tvar lVillainID = rRandom( 1, rVillainList.length ) - 1;\n\n\tvar lKill = rKillList[ rRandom( 1, rKillList.length ) - 1 ]; // Plot-End: kill\n\tvar lWeapon = rWeaponList[ rRandom( 1, rWeaponList.length ) - 1 ]; // Plot-End: kill_weapon\n\tvar lFlee = rFleeList[ rRandom( 1, rFleeList.length ) - 1 ]; // Plot-End: flee\n\tvar lDayMode = rRandom( 1, rOneDayList.length ) - 1;\n\tvar lFinal = rFinalMoment[ rRandom( 1, rFinalMoment.length ) - 1 ];\n\n\tvar lKidnapWay = rRandom( 1, rKidnapList.length ) - 1; // Plot: Kidnap\n\tvar lDestroyWay = rRandom( 1, rDestroyList.length ) - 1; // Plot: Destroy\n\tvar lWitchWay = rRandom( 1, rWitchList.length ) - 1; // Plot: Witch\n\tvar lWitchEnd = rWitchEndList[ rRandom( 1, rWitchEndList.length ) - 1 ];\n\n\tvar lObjectID = rRandom( 1, rDestroyObjectList.length ) - 1; // Plot: Destroy\n\tvar lRelativeID = rRandom( 1, rRelativeList.length ) - 1; // Plot: Revenge\n\n\tvar lHeroGender = rHeroList[lHeroID].Gender;\n\tvar lHeroAlternateGender;\n\tvar lHeroName = rHeroList[lHeroID].Name;\n\tvar lHeroArticle = rHeroList[lHeroID].Article;\n\tvar lHeroMainAdjective = rHeroMainAdjectiveList[ rRandom( 1, rHeroMainAdjectiveList.length ) - 1 ];\n\tvar lHeroSecondaryAdjective;\n\tvar lHeroSecondary = rHeroSecondaryAdjectiveList[ rRandom( 1, rHeroSecondaryAdjectiveList.length ) - 1 ];\n\tvar lCheatWord = rCheatList[ rRandom( 1, rCheatList.length ) - 1 ];\n\n\tvar lVillainName = rVillainList[lHeroID].Name;\n\tvar lVillainArticle = rVillainList[lHeroID].Article;\n\n\tif ( aStoryMode == \"destroy\" ) lPlotMode = \"destroy\";\n\tif ( aStoryMode == \"kidnap\" ) lPlotMode = \"kidnap\";\n\tif ( aStoryMode == \"mindcontrol\" ) lPlotMode = \"witch\";\n\tif ( aStoryMode == \"revenge\" ) lPlotMode = \"revenge\";\n\n\n\tswitch ( lHeroGender ) {\n\tcase \"both\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t if ( rRandom( 1, 100 ) > 50 ) {\n\t\tlHeroGender = \"She\";\n\t\tlHeroSecondaryAdjective = lHeroSecondary.Female;\n\t }\n\t break;\n\tcase \"female\":\n\t lHeroGender = \"She\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Female;\n\t break;\n\tcase \"male\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t break;\n\t}\n\tlHeroAlternateGender = \"his\";\n\tif ( lHeroGender.toLowerCase() == \"she\" ) lHeroAlternateGender = \"her\";\n\n\n\t// Preparing the story and the plot\n\trStory = [];\n\tvar lPlot = [];\n\tswitch ( lPlotMode ) {\n\tcase \"destroy\":\n\t lPlot.push( \"destroy\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"kidnap\":\n\t lPlot.push( \"kidnap\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"witch\":\n\t lPlot.push(\"witch\");\n\t lPlot.push(\"cheat\");\n\t lPlot.push(\"entwitch\");\n\t break;\n\n\tcase \"revenge\":\n\t lPlot.push( \"revenge\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\t}\n\tlPlot.push( lPlotEndMode );\n\n\n\t// Adding the intro\n\tvar lPlotLine = sprintf(\"%s there lived %s %s.\", lIntro, lHeroArticle, lHeroName);\n\tif ( lSubIntro > 33 ) lPlotLine = sprintf(\"%s there was %s %s %s.\", lIntro, lHeroMainAdjective.Article, lHeroMainAdjective.Word, lHeroName );\n\tif ( lSubIntro > 66 ) lPlotLine = sprintf(\"%s there was %s %s who was %s.\", lIntro, lHeroArticle, lHeroName, lHeroSecondaryAdjective );\n\trStory.push( lPlotLine );\n\n\t// Adding the rest of the plot\n\tfor (var lIndex = 0; lIndex < lPlot.length; lIndex++) {\n\n\t switch ( lPlot[ lIndex ] ) {\n\t case \"cheat\":\n\t\tlPlotLine = sprintf(\"%s %s the %s.\", lHeroGender, lCheatWord, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"The %s %s the %s.\", lHeroName, lCheatWord, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"destroy\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, rDestroyList[ lDestroyWay ], rDestroyObjectList[ lObjectID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"entwitch\":\n\t\tlPotLine = sprintf(\"The %s %s the %s.\", lVillainName, lWitchEnd, lHeroName);\n\t\t//if ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"flee\":\n\t\tlPotLine = sprintf(\"%s %s %s.\", lFinal, lHeroGender.toLowerCase(), lFlee );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kidnap\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill_weapon\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s with %s %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName, lHeroAlternateGender, lWeapon );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"revenge\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, lKill, rRelativeList[ lRelativeID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"witch\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\t };\n\t}\n };\n\n // Name : GetStoryText\n // Parameters : None\n // Description: Returns the stored story as an array where each line is an entry\n this.getStoryText = function () {\n\treturn rStory;\n };\n\n\n // Name : AddHero\n // Parameters : This function requires 3 parameters:\n // - aArticle (string); The article of the hero; Can either be \"a\", \"an\", \"the\"or \"\"\n // - aName (string); the nma or job of the hero\n // - aGender (string); the gender of the hero; Can either be \"male\", \"female\" or \"both\"\n // Description: Adds a new possible hero to the list of heros. The user can define the name/job, the gender and an article\n // which is to be used with the name.\n this.addHero = function (aArticle, aName) {\n\tvar lArticle = aArticle.toLowerCase();\n\tvar lGender = aGender.toLowerCase();\n\n\trHeroList.push( { Article: lArticle, Name: aName, Gender: lGender } );\n };\n\n this.createStory(); // Creatinng a story in advance\n}", "function startIntro(){\n\tvar intro = introJs();\n\t\tintro.setOptions({\n\t\t\tsteps: [\n\t\t\t\t{\n\t\t\t\t\tintro: \"Welcome! This webpage will help you explore unemployment data in different areas of Münster.\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#settingsBox',\n\t\t\t\t\tintro: \"Use this sidebar to customize the data that is displayed on the map.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#yearSection',\n\t\t\t\t\tintro: \"You can move this slider to get data from 2010 to 2014.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#criteriaSection',\n\t\t\t\t\tintro: \"Choose a criterion to select a specific group of unemployed.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#boundarySection',\n\t\t\t\t\tintro: \"You can also switch to districts to get finer granularity.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#legendBox',\n\t\t\t\t\tintro: \"This legend will tell how many unemployed are represented by each color.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#map',\n\t\t\t\t\tintro: \"Check the map to view your selected data! You can also click on all boundaries. A popup will show you a timeline to compare data of recent years and links to additional information.\",\n\t\t\t\t\tposition: 'left'\n\t\t\t\t}\n\t\t\t]\n\t\t});\n\n\t\tintro.start();\n}", "buildHpiNarrative(patient) {\n let hpiText = this.buildInitialPatientDiagnosisPreamble(patient);\n \n // Staging\n const staging = this.getMostRecentStaging();\n if (staging) {\n if (staging.stage) {\n hpiText += ` Stage ${staging.stage}`;\n }\n if (!Lang.isUndefined(staging.t_Stage) && !Lang.isNull(staging.t_Stage)) {\n hpiText += ` ${staging.t_Stage}`;\n }\n if (!Lang.isUndefined(staging.n_Stage) && !Lang.isNull(staging.n_Stage)) {\n hpiText += ` ${staging.n_Stage}`;\n }\n if (!Lang.isUndefined(staging.m_Stage) && !Lang.isNull(staging.m_Stage) && staging.m_Stage !== 'M0') { // don't show m if it is 0\n hpiText += ` ${staging.m_Stage}`;\n }\n if (staging.mitoticRate) {\n hpiText += `. Mitotic rate ${staging.mitoticRate}`;\n }\n hpiText += '.';\n }\n\n // Tumor Size and HistologicGrade\n const tumorSize = this.getObservationsOfType(FluxTumorDimensions);\n const histologicGrade = this.getObservationsOfType(FluxHistologicGrade);\n if (tumorSize.length > 0) {\n hpiText += ` Primary tumor size ${tumorSize[tumorSize.length - 1].quantity.number} ${tumorSize[tumorSize.length - 1].quantity.unit}.`;\n }\n if (histologicGrade.length > 0) {\n hpiText += ` ${histologicGrade[0].grade}.`;\n }\n\n // genetics\n const geneticpanels = patient.getGastrointestinalStromalTumorCancerGeneticAnalysisPanelsChronologicalOrder();\n //const geneticspanelMostRecent = geneticpanels[geneticpanels.length - 1];\n if (geneticpanels && geneticpanels.length > 0) {\n const panel = geneticpanels.pop();\n hpiText += \" \" + panel.members.map((item) => {\n const v = item.value === 'Positive' ? '+' : '-';\n return item.abbreviatedName + v;\n }).join(\",\");\n }\n\n hpiText = this.buildEventNarrative(hpiText, patient, this.code);\n \n return hpiText;\n }", "function practice(ninja, weapon, technique) {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recover child by username.
function getChildByUsername(username) { return new Promise((resolve, reject) => { httpClient .get(`${ACCOUNT_URL_BASE}/v1/children?limit=1&username=${username}`) .then((result) => { if (result.data && result.data.length >= 1) { return resolve(result.data[0]) } resolve(undefined) }) .catch(reject) }) }
[ "async function unregisterNfcByUsername(req, res) {\n try {\n // 1. Check if the child exists\n const child = await getChildByUsername(req.params.username)\n if (!child) { // child not found by given username\n return res.status(400).send(msgChildNotFoundUsername(req.params.username))\n }\n\n // 2. Unregisters an NFC tag to a child.\n await httpClient.delete(`${ACCOUNT_URL_BASE}/v1/children/${child.id}/nfc`, req.body)\n res.status(204).send()\n } catch (err) {\n if (err.response && err.response.status) {\n return res.status(err.response.status).send(err.response.data)\n }\n errorHandler(500, res, req)\n }\n}", "async function registerNfcByUsername(req, res) {\n try {\n // 1. Check if the child exists\n const child = await getChildByUsername(req.params.username)\n if (!child) { // child not found by given username\n return res.status(400).send(msgChildNotFoundUsername(req.params.username))\n }\n\n // 2. Registers an NFC tag to a child.\n await httpClient.post(`${ACCOUNT_URL_BASE}/v1/children/${child.id}/nfc`, req.body)\n res.status(204).send()\n } catch (err) {\n if (err.response && err.response.status) {\n return res.status(err.response.status).send(err.response.data)\n }\n errorHandler(500, res, req)\n }\n}", "async loadUser(username) {\n return this.UserModel.findOne({ username });\n }", "function findUsername(bookshelf, username) {\n let name = Object.keys(bookshelf.users).filter((e) => e === `${username}`);\n return !name ? errorMessage() : name;\n}", "function handleLoginNombreUsuario(agent) {\n const nickname = agent.parameters.nickname;\n let refUsuario = db.ref(`users/${nickname}`);\n return refUsuario.once('value').then((snapshot) => {\n var aux = snapshot.exists();\n if (nickname === \"Cancelar\" || nickname === \"Salir\") {\n agent.setFollowupEvent({ \"name\": \"Welcome\", \"lifespan\": 1 });\n } else if (!aux) {\n agent.add(`Vaya, parece que ${nickname} no es un nombre de usuario registrado. Por favor, inténtalo de nuevo con otro nombre de usuario válido.`);\n agent.setContext({ \"name\": \"InicioLogin-followup\", \"lifespan\": 1 });\n }\n else {\n agent.add(`Perfecto, ${nickname}. Introduce ahora tu contraseña.`);\n agent.setContext({ \"name\": \"LoginNombreUsuario-followup\", \"lifespan\": 1, \"parameters\": { \"nickname\": nickname } });\n\n }\n });\n\n }", "function fetchUUID(username) {\n return fetch('https://playerdb.co/api/player/minecraft/' + username)\n .then(res => res.json());\n }", "async updateUser(id, childId){\n if (!id) throw \"You must provide an id to search for\";\n if (!childId) throw \"Invalid Input.\";\n \n await this.get(id)\n const userCollection = await users();\n const updatedUser = {\n children: childId\n };\n \n const updatedInfo = await userCollection.updateOne({ _id: id }, {$set:updatedUser});\n if (updatedInfo.modifiedCount === 0) {\n throw \"could not update successfully\";\n }\n return await this.get(id);\n }", "function findAndGetChild(childName, parent) {\n for (var _i = 0, _a = parent.children; _i < _a.length; _i++) {\n var child = _a[_i];\n if (child.name === childName) {\n return child;\n }\n }\n return null;\n}", "getUserByUsername(username) {\n for (var id in this.users) {\n if (username === this.users[id].username)\n return this.users[id];\n }\n return null;\n }", "async function postWeightByUsername(req, res) {\n try {\n // 1. Check if the child exists\n const child = await getChildByUsername(req.params.username)\n if (!child) { // child not found by given username\n return res.status(400).send(msgChildNotFoundUsername(req.params.username))\n }\n\n // 2. Compare child.tag_ass_time with req.body.timestamp\n if (child.tag_ass_time && req.body.timestamp){\n const tagTime = new Date(child.tag_ass_time).getTime()\n const weightTime = new Date(req.body.timestamp).getTime()\n if ( tagTime > weightTime ) return res.status(400).send(msgDivergeTimeNfcTag(req.params.username))\n }\n\n // 3. Post the measurement based on the ID retrieved by username\n const responseWeight = await httpClient\n .post(`${IOT_URL_BASE}/v1/children/${child.id}/weights`, req.body)\n res.status(responseWeight.status).send(responseWeight.data)\n } catch (err) {\n if (err.response && err.response.status) {\n return res.status(err.response.status).send(err.response.data)\n }\n errorHandler(500, res, req)\n }\n}", "function load(req, res, next, username) {\n User.getByUsername(username).then((user) => {\n if (!user) {\n const error = new APIError('no such user exists', 400, true);\n return next(error);\n }\n req.user = user;\t\t// eslint-disable-line no-param-reassign\n return next();\n }).error((e) => next(e));\n}", "function findGuestMasterUser()\n {\n if (userList.length == 0 || guestMasterUser.length > 0 || giveMasterToUser)\n {\n return;\n }\n \n var index = Math.floor(Math.random() * userList.length);\n var guest = userList[index].name;\n guestMasterUser = guest;\n console.log(\"Guest master user is now \" + guest);\n io.sockets.emit('guestMasterUserSync', guest);\n }", "function initializeUser(){\n database.ref(\"users\").once(\"value\").then(function(snapshot){\n\n if(snapshot.child(user).exists()){\n //do nothing\n console.log(\"username exists\");\n }\n else{\n console.log(\"created username\");\n console.log(user);\n database.ref(\"users/\" + user).set({\n playlists : {\n Favorites : {\n name: \"Favorites\"\n }\n }\n }); \n }\n\n initializeSelection();\n });\n}", "function usernameChanged() {\n socket.emit('username', {\n username: this.value()\n });\n}", "visitUser_object_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "ensureParentExist() {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n const collection = this.database.collection('choices');\n const parent = yield collection.findOne({\n id: this.parentId\n });\n if (!parent) {\n reject(new Error(`Unable to find the parent '${this.parentId}'`));\n return;\n }\n resolve();\n }));\n });\n }", "function showUser(user)\n{\n\tuser.promiseData(['path'])\n\t .then(function()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar panel = new PathlinesPanel(user, true);\n\t\t\t\tpanel.pathtree.setUser(user.path());\n\t\t\t\tpanel.showLeft().then(unblockClick);\n\t\t\t}\n\t\t\tcatch(err)\n\t\t\t{\n\t\t\t\tcr.syncFail(err);\n\t\t\t}\n\t\t},\n\t\tcr.syncFail);\n}", "function GetBookshelf(username) {\n return lib.BookshelfJSON2Obj(bookshelf.LayRaMotTuSach(username));\n}", "function getChildByNfcTag(tag) {\n return new Promise((resolve, reject) => {\n httpClient\n .get(`${ACCOUNT_URL_BASE}/v1/children/nfc/${tag}`)\n .then((result) => {\n if (result.data) {\n return resolve(result.data)\n }\n resolve(undefined)\n })\n .catch(err => {\n if (err.response && err.response.status === 404) {\n resolve(undefined)\n }\n reject(err)\n })\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function extracts a zone (which is a cells array) from a point array Mainly to help rmgen compatibility.
function pointsToZone(points) { let zone = []; for(let p of points) { zone.push(g_TOMap.gCells[p.x][p.y]); } return zone; }
[ "function zoneToPoints(zone)\n{\n\tlet points = [];\n\tfor(let c of zone) {\n\t\tpoints.push(new Vector2D(c.x,c.y));\n\t}\n\treturn points;\n}", "static from(array) {\n return new Point(array[0], array[1]);\n }", "extractPoints(e) {\n return {\n shape: this.getPoints(e),\n holes: this.getPointsHoles(e)\n };\n }", "parse(array = [[0, 0]]) {\n var points = []; // if it is an array\n\n if (array instanceof Array) {\n // and it is not flat, there is no need to parse it\n if (array[0] instanceof Array) {\n return array;\n }\n } else {\n // Else, it is considered as a string\n // parse points\n array = array.trim().split(delimiter).map(parseFloat);\n } // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints\n // Odd number of coordinates is an error. In such cases, drop the last odd coordinate.\n\n\n if (array.length % 2 !== 0) array.pop(); // wrap points in two-tuples\n\n for (var i = 0, len = array.length; i < len; i = i + 2) {\n points.push([array[i], array[i + 1]]);\n }\n\n return points;\n }", "static FromArray(array) {\n return new Plane(array[0], array[1], array[2], array[3]);\n }", "getRegionForPos(p) {\n let x = p.x;\n let y = p.y;\n return {\n x: Math.floor(x / CELLS_IN_REGION),\n y: Math.floor(y / CELLS_IN_REGION)\n };\n }", "function zoneFinder(zoneStrings,circles) {\n\tvar ret = [];\n\tfor (var i = 0; i < zoneStrings.length; i++) {\n\t\tvar zoneString = zoneStrings[i];\n\t\tvar nextZone = [];\n\t\tfor (var j = 0; j < zoneString.length; j++) {\n\t\t\tvar circleLabel = zoneString[j];\n\t\t\tvar circle = circleWithLabel(circleLabel,circles);\n\t\t\tnextZone.push(circle);\n\t\t}\n\t\tret.push(nextZone);\n\t}\n\treturn ret;\n}", "function getZone(axios$$1, zoneToken) {\n return restAuthGet(axios$$1, '/zones/' + zoneToken);\n }", "function parsePanoramaArray(pArray){\n trimNull(pArray);\n removeRepeats(pArray);\n createStreetViewPoints(pArray);\n \n //global function\n // retrieveSVPArray();\n updatePage(svpArray);\n }", "function parseWaypoints(waypoints){\n var wpArray=[]\n \twaypoints.forEach(function(WP){\n \t\twpArray.push({\n \t\t\tlocation: \"\" + WP.location.A + \" \" + WP.location.F\n \t\t})\n \t})\n return wpArray;\n }", "function batchDecodePoints(pointArr) {\n let decPointArr = [];\n for (let i=0; i<pointArr.length; i++) {\n decPointArr.push(sec1DecodePoint(pointArr[i]));\n }\n return decPointArr;\n}", "static FromArray(array, offset = 0) {\n return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }", "function buildZonesDict(helperArrFlat,geometry){\n var vertexDictZ;\n var vertexDictX;\n //iterate through vertices\n for(var i=0; i<geometry.vertices.length; i++){\n vertexDictZ=customFloor(geometry.vertices[i].x,globalTerrainData.distanceZ);\n vertexDictX=customFloor(geometry.vertices[i].y,globalTerrainData.distanceX);\n //Fill in vertexDict with appropriate value from helperArrFlat\n globalTerrainData.vertexDict[[vertexDictZ,vertexDictX]]=[helperArrFlat[i][0],helperArrFlat[i][helperArrFlat[i].length-1]];\n //The first time we hit a certain Z zone (i.e. path), record its Z coordinate\n if(!globalTerrainData.zZones[helperArrFlat[i][0]]){\n globalTerrainData.zZones[helperArrFlat[i][0]]=vertexDictX;\n }\n else if(vertexDictX<globalTerrainData.zZones[helperArrFlat[i][0]]){\n globalTerrainData.zZones[helperArrFlat[i][0]]=vertexDictX;\n }\n //The first time we hit a certain X zone (i.e. chunk), record its XCoordinate\n if(!globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]){\n globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]=vertexDictZ; \n }\n else if(vertexDictZ<globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]){\n globalTerrainData.xZones[helperArrFlat[i][helperArrFlat[i].length-1]]=vertexDictZ;\n }\n }\n //Get last padding zones\n var toAdd=globalTerrainData.zZones[0]-globalTerrainData.zZones[1];\n globalTerrainData.zZones[999]=globalTerrainData.zZones[0]+toAdd;\n globalTerrainData.zZones[-1] = globalTerrainData.zZones[2] - toAdd;\n var keys=Object.keys(globalTerrainData.xZones);\n toAdd=globalTerrainData.xZones[1]-globalTerrainData.xZones[0];\n globalTerrainData.xZones[999]=globalTerrainData.xZones[keys.length-2]+toAdd;\n globalTerrainData.xZones[-1] = globalTerrainData.xZones[0] - toAdd;\n}", "function closestSafeZone(personLong, personLat){\r\n var targetPoint = turf.point([personLat, personLong])\r\n var points;\r\n var poly = turf.polygon(zones[0])\r\n var line = turf.polygonToLine(poly)\r\n return turf.nearestPointOnLine(line, targetPoint)\r\n}", "function findZoneEntries(zone, millis, pad) {\n if (pad === undefined) pad = 24*3600*1000;\n\n var entries = zone.filter(function(e){ return millis+pad >= e.from && millis-pad < e.to });\n\n if (entries.length > 0)\n\treturn entries;\n\n throw \"Time zone info not available for \"\n\t+ zone.name + \", \" \n\t+ new Date(millis).getFullYear() +\".\";\n}", "function positionArray(keypoints){\r\n var keypointArray = new Array();\r\n sortByKey(keypoints,'part');\r\n for (let i = 0; i < keypoints.length; i++) {\r\n const keypoint = keypoints[i];\r\n keypointArray.push(keypoint.position.x, keypoint.position.y);\r\n }\r\n return keypointArray;\r\n}", "function RegionQuery(point, epsilon, dataSet) {\n var neighBourPoints = []\n for (var j = 0; j < dataSet.length; j++) {\n var distance = Math.sqrt(Math.pow(dataSet[j][x] - point[x], 2) + Math.pow(dataSet[j][y] - point[y], 2));\n if (distance < epsilon) {\n neighBourPoints.push(dataSet[j]);\n }\n }\n return neighBourPoints;\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}", "function findStreetViews(pointsArray){\n var paLength = pointsArray.length;\n var currentIteration = 0;\n var panoArray = [];\n for (var i = 0; i < (paLength > LIMIT ? LIMIT : paLength); i++){\n findPanorama(pointsArray[i], i, paLength, panoArray, currentIteration);\n }\n\n //findPanorama()\n //==============\n //Find a single panoramic image at a point, and puts it into the specified index.\n //If no result is found, it puts null into the array.\n function findPanorama(point, index, paLength, panoArray){\n webService.getPanoramaByLocation(point, RADIUS, function(result, status){\n console.log('index', index);\n currentIteration++;\n panoArray[index] = result;\n\n //Conditional to check if we move on can only be done in here\n //by incrementing currentIteration until it matches\n //the limit, or the length of routes[0].overview_path\n //If we're on the last iteration, parse the entire array\n if (currentIteration == (paLength > LIMIT ? LIMIT : paLength)){\n parsePanoramaArray(panoArray);\n }\n });\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function verifies the validity of OTP (token) entered by the user from an authenticator app, for example, the Google Authenticator app. The secret passed here as argument must match with the secret in the authenticator app.
function verifyTOTP(otp, secret, window = 1, timeStepInSeconds = 30, initialTime = 0, otpLength = 6) { try { otp = parseInt(otp, 10); if (isNaN(otp)) { throw new Error(); } } catch (e) { throw new Error('Invalid OTP'); } if (Math.abs(+window) > 10) { throw new Error('Window size is too large'); } for (let errorWindow = -window; errorWindow <= +window; errorWindow++) { const totp = generateTOTP(secret, errorWindow, timeStepInSeconds, initialTime, otpLength); if (otp === totp) { return true; } } return false; }
[ "function onVerifyOTPClicked (event) {\n let isValid = true;\n let { userType } = event.target.dataset;\n if (!userType) {\n userType = 'student'\n }\n\n const phoneNumber = window.sentOTPtoPhoneNumber;\n const otp = $('.otp-input').toArray().map((input) => input.value).join('');\n if (otp.length !== 6) {\n $(getClassName(userType, 'otpCodeError')).text('Please provide valid OTP');\n isValid = false;\n }\n if (isValid) {\n verifyOtpAPI(userType, phoneNumber, otp);\n }\n}", "function checkSecret(req, res, callback) {\n if (!req.body || !req.body.secret) {\n callback('Missing secret');\n return;\n }\n bcryptjs.compare(req.body.secret, settings.sharedSecretHash, (err, result) => {\n if (err || !result) {\n logger.warn('Invalid secret sent from '+req.remoteAddress);\n callback('Invalid secret');\n return;\n }\n callback();\n });\n}", "function validate_otp() {\n console.log(\"OTP validation function starts\");\n var otpvalue = document.getElementById(\"otpvalue\").value.trim();\n\n if ((otpvalue.length) == 0 || (otpvalue.length) == undefined) {\n document.getElementById(\"error_otpvalue\").innerHTML = \"Please Enter OTP\";\n console.log(\"OTP has not been entered\");\n return false;\n }\n\n if (isNaN(otpvalue)) {\n document.getElementById(\"error_otpvalue\").innerHTML = \"Please Enter only number\";\n console.log(\"OTP are not in numbers\");\n return false;\n }\n if ((otpvalue.length) != 6) {\n document.getElementById(\"error_otpvalue\").innerHTML = \"Please Enter all 6 digits of OTP\";\n console.log(\"all digits of OTP has not been entered\");\n return false;\n\n } else {\n console.log(\"OTP has been entered\");\n document.getElementById(\"error_otpvalue\").innerHTML = \"\";\n\t\treturn true;\n }\n\n}", "function authenticateToken(checkAppUuid) {\n return function(token, callback) {\n var authenticAppUuid = !checkAppUuid || this.applicationUUID === getPath(token, 'application.auth.uuid');\n var authenticated = token.expiry > Date.now() && authenticAppUuid;\n\n return callback(null, authenticated ? token : null);\n }\n}", "function checkToken(_token, currentUserId) {\n try {\n //ayth6) server decodes token and compares the user's userid with the token's decoded userid\n //ayth6a) if good then can continue with action\n //ayth6b) else ??? return u failed\n const token = _token;\n // next will keep any fields created\n const decodedToken = jwt.verify(token, \"my super duper secret code\");\n if (currentUserId == decodedToken.userId) {\n return true;\n } else {\n return false;\n }\n } catch (error) {\n console.log(error)\n // res.status(401).json({ message: \"You are not authenticated!\" });\n }\n}", "function tokenAuthentication(token, callback) {\n if (token === CAM_MOCKS.validToken) {\n callback(true);\n } else {\n callback(false);\n }\n}", "isTokenExpired(token){\n try {\n const decoded = decode(token);\n return (decoded.exp < Date.now() / 1000);\n } catch (err) {\n console.log(\"expired check failed!\");\n return true;\n }\n }", "function verifyAccessToken(token, authType) {\n switch (authType) {\n case AUTH_TYPE.PASSWORD:\n winston.debug('Verifing Password access token');\n // Verify password access token\n return user.verifyPasswordAccessToken(token);\n case AUTH_TYPE.GOOGLE:\n winston.debug('Verifing Google access token');\n // Verify google access token\n return user.verifyGoogleAccessToken(token, true);\n case AUTH_TYPE.FACEBOOK:\n winston.debug('Verifing Facebook access token');\n // Verify facebook access token\n return user.verifyFacebookAccessToken(token, true, false);\n default:\n let responseData = {payload: {}};\n responseData.success = false;\n responseData.payload.dataPath = 'authentication';\n responseData.payload.message = 'invalid auth type';\n let errorCode = ERROR.INVALID_AUTHTYPE;\n winston.error('errorCode', errorCode);\n return Promise.reject({errorCode: errorCode, responseData: responseData});\n }\n}", "function submitSignupOTPVerify(form) {\n //console.info(form);\n\n vm.invalidOTPMsgFlag = false;\n vm.showForgotPwdPanel = false;\n vm.showForgotPwdSuccessPanel = false;\n // vm.showSignupResendOTPPanel = true; //show when successful signup callback fired in submitSignup method\n\n /*Starting countdown timer */\n startCountDownTimer();\n\n var postObj = {\n otp: parseInt(vm.modSignupOTP),\n mobile: vm.modSignup.mobileno,\n req_end: 'L'\n };\n\n if ((form.$valid && vm.OTPTimer !== 0) || form.$valid && !vm.showSignupResendOTPPanel) {\n\n // Show processing loader\n vm.processing = true;\n\n /* Verify OTP */\n return dataservice.postData(REGISTER_VERIFY_OTP_API, postObj).then(function(data, status) {\n\n console.info('register verify otp api hit response ', data);\n\n if (data) {\n\n /* If request successfuly and found status valid/true */\n if (data.verified) {\n console.info('signup otp form validated');\n\n vm.showSignupResendOTPPanel = true;\n\n // if(parseInt(vm.modSignupOTP) == 1234){\n\n vm.nonTabActive = true;\n vm.showVerifyEmailPanel = true;\n vm.validOTPMsgFlag = true;\n\n /* Stop the countdown timer if successfuly passed the OTP */\n stopCountDownTimer();\n\n // }else{\n /*vm.invalidOTPMsgFlag = true;\n \n Starting countdown timer \n startCountDownTimer(); \n }*/\n } else if (!data.verified) {\n vm.invalidOTPMsgFlag = true;\n\n $timeout(function() {\n vm.invalidOTPMsgFlag = false;\n },3000)\n\n } else {\n console.error('Error, looking for key in data object not found ', data);\n }\n\n //Hide processing loader\n hideProcessing();\n\n } else {\n\n //Hide processing loader\n hideProcessing();\n\n console.error('Error, object');\n }\n\n }, function() {\n console.info('verify otp api connecting error', data, status);\n });\n\n\n }\n }", "function validateToken(req, res) {\r\n var token = getToken(req);\r\n var user = users.getUserByToken(token);\r\n var isValidToken = user != undefined && user != '';\r\n console.log('[validToken] req=' + req.url);\r\n console.log('[validToken] Is Valid Token=%s User=%s', isValidToken, user);\r\n if (!isValidToken) {\r\n invalidToken(req, res);\r\n }\r\n return token;\r\n}", "function secret(user) {\n\tvar target = new XMLHttpRequest();\n\ttarget.onreadystatechange = function() {\n \tif (this.readyState == 4 && this.status == 200) {\n \t\tdocument.getElementById(\"qr\").src = 'https://chart.googleapis.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/' + user + '%3Fsecret%3D' + this.response + '%26issuer%3Dauthentication';\n \t}\n }\ntarget.open(\"GET\", \"/returnSecret\", true);\ntarget.send();\n}", "async function checkOreAccessToken(oreAccessToken, req) {\n let errHead = `invalid ore-access-token `\n let errMsg = ''\n try {\n let requestParams = {}\n if (!process.env.VERIFIER_PUBLIC_KEY) {\n errMsg = `verifier public key is missing. Provide a valid verifier public key as environment variable`;\n throw new Error(`${errMsg}`);\n }\n\n const verifierPublicKey = process.env.VERIFIER_PUBLIC_KEY.replace(/\\\\n/g, '\\n')\n\n const payload = await jwt.verify(oreAccessToken, verifierPublicKey, {\n algorithms: [\"ES256\"]\n })\n if (req.query && req.body && Object.keys(req.query).length > 0 && Object.keys(req.body).length > 0) {\n requestParams[\"http-url-params\"] = req.query\n requestParams[\"http-body-params\"] = req.body\n } else if (Object.keys(req.query).length > 0) {\n requestParams = req.query\n } else {\n requestParams = req.body\n }\n\n const isValid = await checkRequestParams(payload.reqParamHash, requestParams)\n return isValid\n } catch (error) {\n if (error.message == 'jwt expired') {\n errMsg = ` Expired ore-access-token. Provide a valid token.`\n }\n\n if (error.message == 'invalid signature') {\n errMsg = ` Invalid signature for ore-access-token. Make sure ore-access-token is signed with a valid key`\n }\n\n if (error.message == 'jwt malformed') {\n errMsg = ` Malformed ore-access-token. Make sure the ore-access-token has the valid right name and voucher.`\n }\n\n logError(\"Error\", `${errHead}:${errMsg}:${error.message}`)\n throw new Error(`${errHead}:${errMsg}:${error.message}`)\n }\n}", "async function checkToken() {\n const tokenNameResponse = await rpcClient.invokeFunction(\n inputs.tokenScriptHash,\n \"symbol\"\n );\n\n if (tokenNameResponse.state !== \"HALT\") {\n throw new Error(\n \"Token not found! Please check the provided tokenScriptHash is correct.\"\n );\n }\n\n vars.tokenName = u.HexString.fromBase64(\n tokenNameResponse.stack[0].value\n ).toAscii();\n\n console.log(\"\\u001b[32m ✓ Token found \\u001b[0m\");\n}", "async function ensureToken(req, res, next) {\n try {\n var bearerHeader = req.headers['authorization']\n if (typeof bearerHeader == 'undefined') {\n console.log('undefined, gak ada token');\n return res.status(403).send({\n 'message': 'token not provided'\n })\n }\n var bearerToken = bearerHeader.split(' ')\n var tokenBracket = bearerToken[0]\n var tokenProvided = bearerToken[1]\n\n if (tokenBracket !== 'bearer')\n return res.status(403).send({'message': 'worng format header Authorization'})\n\n const user = await jwt.verify(tokenProvided, process.env.SECRET_KEY)\n\n if(user.isActive==false)\n return res.status(403).send({\"message\":\"need activation user.\"})\n \n req.body.user = user\n next()\n } catch (error) {\n console.log(error);\n return res.status(403).send({\n 'message': 'token is not valid'\n })\n }\n}", "async function comparePassword(originalSecret, storedHashedPassword) {\n // call compare method that triggers a promise and returns a bool\n const isMatch = await bcrypt.compare(originalSecret, storedHashedPassword);\n if (isMatch) {\n console.log('Matched');\n } else {\n console.log('Not a Match... Sorry!');\n }\n}", "static validatePassword(password, hash, salt) {\n var hashVerify = crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');\n return hash === hashVerify;\n }", "function VerificationConfirmation() {\n const confirmation = document.getElementById(\"confirmation\");\n const pwd = document.getElementById(\"pwd\");\n const LMINI = 8; // DP LMINI = longueur minimale du mot de passe\n\n //DP si le mot de passe comporte moins de 8 lettres et que la confirmation est differente au mot de passe alors erreur\n if ((confirmation.value.length < LMINI) || (confirmation.value !== pwd.value)) {\n console.log(\"longueur confirmation NOK\", pwd.value.length, confirmation.value.length);\n return false;\n } else {\n console.log(\"longueur confirmation OK\", pwd.value.length, confirmation.value.length);\n return true;\n }\n}", "function hasStoredToken() {\n //const vault = await this.getVault();\n return authVault.hasStoredToken();\n }", "function isActiveToken () {\n const url = `${baseURl}/api/user/verifyToken`\n return localforage.getItem('token').then((jwt) => {\n return axios.post(url, { params: jwt })\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is the Mover in the Liquid?
boolean contains(Mover m) { PVector l = m.location; if (l.x > x && l.x < x + w && l.y > y && l.y < y + h) { return true; } else { return false; } }
[ "isOnTheWater() {\n return this.y <= 0;\n }", "function PopUp_Hover() {\n var _return = false;\n\n\n if ((_mouse[\"x\"] > _popUp.offset().left) && _mouse[\"x\"] < (_popUp.offset().left + _popUp.outerWidth())) {\n if ((_mouse[\"y\"] > _popUp.offset().top) && _mouse[\"y\"] < (_popUp.offset().top + _popUp.outerHeight())) {\n _return = true\n }\n }\n\n return _return;\n }", "function isNotColiding(obj){\n\tvar s = obj.scale;\n\tvar p = obj.position;\n\tvar cp = {'x':newPosX,'z':newPosZ};\n\tif(cp.x < (s.x+0.5)/2.25+p.x && cp.x > p.x-(s.x+0.5)/2.25 && cp.z < (s.z+0.75)/2.25+p.z && cp.z > p.z-(s.z+0.75)/2.25){\n\t\treturn false;\n\t}else{\n\t\treturn true;\n\t}\n}", "_isHovering() {\n if (this._dock.hover) {\n return true;\n } else {\n return false;\n }\n }", "isCollide(potato) {\n\n\n // Helper Function to see if objects overlap\n const overLap = (objectOne, objectTwo) => {\n\n // Check X-axis if they dont overlap\n if (objectOne.left > objectTwo.right || objectOne.right < objectTwo.left) {\n return false;\n }\n // Check y-axis if they dont overlap\n // 100 \n // 200 ObjectTwo Bottom\n // 300 ObjectOne Top\n if (objectOne.top > objectTwo.bottom || objectOne.bottom < objectTwo.top) {\n return false;\n }\n return true;\n }\n\n let collision = false;\n\n this.eachObject((object) => {\n if (overLap(object, potato)) {\n collision = true\n }\n\n });\n\n return collision\n\n\n }", "function hasHoverTooltips(state) {\n return state.facet(showHoverTooltip).some((x) => x)\n }", "function insideSelector(event) {\n var offset = $qsBody.position();\n offset.right = offset.left + $qsBody.outerWidth();\n offset.bottom = offset.top + $qsBody.outerHeight();\n \n return event.pageY < offset.bottom &&\n event.pageY > offset.top &&\n event.pageX < offset.right &&\n event.pageX > offset.left;\n }", "function is_large( vp_width ) {\n return vp_width > $(58.75).toCleanPx(); \n}", "reachedTargetPosition() {\n if (this.target !== undefined) {\n let targetCenter = this.getTargetCenter();\n let ownCenter = this.getCenter();\n // console.log(ownCenter);\n // console.log(targetCenter);\n var distance = Phaser.Math.Distance.Between(\n ownCenter.x,\n ownCenter.y,\n targetCenter.x,\n targetCenter.y\n );\n if (distance < 10) {\n return true;\n }\n // console.log(distance);\n }\n return false;\n }", "hasReachedDestination() {\r\n\t\tvar destinationTiles = this.levelGrid.getDestination();\r\n\t\tfor (var i = 0; i < destinationTiles.length; i++) {\r\n\t\t\tvar destinationRow = destinationTiles[i].row;\r\n\t\t\tvar destinationColumn = destinationTiles[i].column;\r\n\t\t\tif ( this.currentTileRow === destinationRow\r\n\t\t\t\t && this.currentTileColumn === destinationColumn ) {\r\n\t\t\t\tthis.speed = 0;\r\n\t\t\t\treturn true;\r\n\t\t\t} \t\t\r\n\t\t}\r\n\t\treturn false;\r\n\t}", "checkEat() {\n let x = convert(this.snake[0].style.left);\n let y = convert(this.snake[0].style.top);\n\n let check = false;\n if (x === this.bait.x && y === this.bait.y) check = true;\n\n return check;\n }", "inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}", "isMouseOver() {\n return this.button.isMouseOver()\n }", "function checkPosition() {\n\tconst heart = document.getElementById(\"profile-heart\");\n\tconst cross = document.getElementById(\"profile-cross\");\n\tconst qmark = document.getElementById(\"qmark\");\n\n\tif (this.x > 0) {\n\t\tcross.style.opacity = 0;\n\t\theart.style.opacity = 0.5;\n\t\tqmark.style.opacity = 0.5;\n\t\theart.style.animationPlayState = \"running\";\n\t}\n\tif (this.x < 0) {\n\t\theart.style.opacity = 0;\n\t\tcross.style.opacity = 0.5;\n\t\tqmark.style.opacity = 0.5;\n\t\tcross.style.animationPlayState = \"running\";\n\t}\n}", "setHoverMode() {\n this.hoverMode = !this.items.some(item => item.$toggle && item.$toggle.is(':visible'));\n }", "function checkHit() {\r\n \"use strict\";\r\n // if torp left and top fall within the ufo image, its a hit!\r\n let ymin = ufo.y;\r\n let ymax = ufo.y + 65;\r\n let xmin = ufo.x;\r\n let xmax = ufo.x + 100;\r\n\r\n\r\n console.log(\"torp top and left \" + torpedo.y + \", \" + torpedo.x);\r\n console.log(\"ymin: \" + ymin + \"ymax: \" + ymax);\r\n console.log(\"xmin: \" + xmin + \"xmax: \" + xmax);\r\n console.log(ufo);\r\n\r\n if (!bUfoExplode) {\r\n // not exploded yet. Check for hit...\r\n if ((torpedo.y >= ymin && torpedo.y <= ymax) && (torpedo.x >= xmin && torpedo.x <= xmax)) {\r\n // we have a hit.\r\n console.log(\" hit is true\");\r\n\r\n bUfoExplode = true; // set flag to show we have exploded.\r\n }// end if we hit\r\n\r\n }// end if not exploded yet\r\n\r\n // reset fired torp flag\r\n bTorpFired = false;\r\n\r\n // call render to update.\r\n render();\r\n\r\n}// end check hit", "function isMovable(tile) {\n var currentX = tile.style.left;\n var currentY = tile.style.top;\n if (currentX == emptyX && Math.abs(parseInt(currentY) - parseInt(emptyY)) == SIZE ||\n currentY == emptyY && Math.abs(parseInt(currentX) - parseInt(emptyX)) == SIZE){\n return true;\n } else {\n return false;\n }\n }", "isInViewport() {\n const vm = this;\n\n if(vm.firstTime) {\n // first time set postion of element outside monitor\n vm.firstTime = false\n return true\n } else {\n return vm.offset + vm.height > vm.scroll &&\n vm.offset < vm.scroll + vm.wheight\n }\n\n }", "Reveal() {\n if (!(this.Revealed || this.Flagged)) {\n if (this.Mine) {\n return true;\n } else {\n this.Revealed = true;\n return false;\n }\n }\n return false;\n }", "onCurrent(element) {\n\t\tvar slide = _.getSlide(element);\n\n\t\tif (slide) {\n\t\t\treturn \"#\" + slide.id === location.hash;\n\t\t}\n\n\t\treturn false;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function: preventFileActivity Description: Standard report API, gets called just before report is to be run. We check here to see if any report wants to prevent file activity during its run.
function preventFileActivity() { return true; }
[ "function beginReporting()\n{\n if (site.serverActivity())\n {\n alert(MSG_CantRun_FileActivity);\n return false;\n }\n return true;\n}", "function eventLogRecordingsFileSelectionCancelled() {\n dumpCreator.disableEventLogRecordings();\n}", "function ActivityDeclined(){\n\n\tif (g_bFullScreen) {\n\t\tfor (i=0; i<=g_nNumButs+7; i++) {\n\t\t\tMFBar.SetObjectPosition(g_strButID[i]+\"Full\", \t\n\t\t\tg_nButPos[i][0], g_nButPos[i][1] -1000,\n\t\t\tg_nButPos[i][2], g_nButPos[i][3]);\n\t\t}\n\t\tDVD.CursorType = -1;\n\t}\n\n\tg_bActivityDeclined = true;\n\t//MFBar.MessageBox(\"Activity Declined\", \"Status\");\n}", "function stopAttLink() {\n require(['io.ox/core/extPatterns/links'], function (links) {\n new links.Action('io.ox/mail/compose/attachment/shareAttachmentsEnable', {\n id: 'stop',\n index: 1,\n requires: function (e) {\n try {\n if (e.baton.view.model.get('encrypt')) { // Do not offer shareAttachments if encrypted\n console.log('stopping');\n e.stopPropagation();\n return false;\n }\n } catch (f) {\n console.log(f);\n }\n return false;\n }\n });\n });\n }", "function test_can_cancel_upload() {\n const kFilename = \"testFile1\";\n gServer.setupUser();\n let provider = gServer.getPreparedBackend(\"someNewAccount\");\n let file = getFile(\"./data/\" + kFilename, __file__);\n gServer.planForUploadFile(kFilename, 2000);\n assert_can_cancel_uploads(mc, provider, [file]);\n}", "function unlockfile() {\n \t\n }", "function removeDummyFiles() {\n var fileIt = \n DriveApp.getFilesByName('duplicate spreadsheet'),\n file;\n while(fileIt.hasNext()) {\n file = fileIt.next();\n file.setTrashed(true);\n }\n}", "function startReportingActivity() {\n var id = Web.setInterval(function () {\n if (self.active()) {\n ucwa.send('POST', { rel: 'reportMyActivity' }, {\n nobatch: true\n }).catch(function (err) {\n // After a long period of inactivity, the connection with UCWA is usually lost.\n // While the connection is being restored, MePerson resends POST /makeMeAvailable.\n // However this periodic timer doesn't know about that logic and keeps sending\n // POST /reportMyActivity as usual. If the timer happens to wake up before the\n // /makeMeAvailable is completed, UCWA will reject this /reportMyActivity with a\n // 409.MakeMeAvailableRequired error.\n if (err && err.code == 'RequestFailed' && err.rsp.status == 409)\n return;\n debug.log('%c reportMyActivity stopped', 'color:red;font-weight:bold', err);\n Web.clearInterval(id);\n self.active(false, err);\n });\n }\n }, 3 * 60 * 1000);\n }", "function disableReportDatePeriod(){\n\ttoggleErrorMessage(\"#account_created_period_error_text\", true, \"\");\n\t\n\tdisableField(\"#selectRange1Value\");\n\t\n\t//Clear create account period\n\tresetSelect(\"#selectRange1Value\");\n\t\n\t//Reset datePicker\n\tenableField(\"#date-picker-start\");\n\tenableField(\"#date-picker-end\");\n}", "function _shouldIgnore(pattern /*: Function | RegExp*/, filename /*: string*/) {\n if (typeof pattern === \"function\") {\n return pattern(filename);\n } else {\n return pattern.test(filename);\n }\n}", "function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }", "function exclusionaryTests() {\n\tlet exclusionary = danger.git.created_files\n\t\t.filter(filepath => filepath.endsWith('.test.js'))\n\t\t.map(filepath => ({filepath, content: readFile(filepath)}))\n\t\t.filter(\n\t\t\t({content}) =>\n\t\t\t\tcontent.includes('it.only') || content.includes('describe.only'),\n\t\t)\n\n\tif (!exclusionary.length) {\n\t\treturn\n\t}\n\n\tmarkdown(\n\t\th.details(\n\t\t\th.summary(\n\t\t\t\t'An <code>only</code> was left these file(s) – no other tests can run.',\n\t\t\t),\n\t\t\th.ul(...exclusionaryTests.map(file => h.li(h.code(file)))),\n\t\t),\n\t)\n}", "function test_can_cancel_uploads() {\n const kFiles = [\"testFile2\", \"testFile3\", \"testFile4\"];\n gServer.setupUser();\n let provider = gServer.getPreparedBackend(\"someNewAccount\");\n let files = [];\n for each (let [, filename] in Iterator(kFiles)) {\n gServer.planForUploadFile(filename, 2000);\n files.push(getFile(\"./data/\" + filename, __file__));\n }\n assert_can_cancel_uploads(mc, provider, files);\n}", "hideAndroidDownload() {\n this.addFilter('android_download', entry => {\n if (entry.filesystem && entry.filesystem.name === 'android_files' &&\n entry.fullPath === '/Download') {\n return false;\n }\n return true;\n });\n }", "filter (file) {\n return file.name.includes(\"watch\");\n }", "function scanFiles(){\n\tlet fileList = new Array();\n\n\tfor(let file of trackedFiles.values()){\n\t\tfileList.push(file);\n\t}\n\n\t$('#dev-scan-files-loading-modal').modal({closable: false}).modal('show');\n\tipcRenderer.send('dev-scan-files:find-difference', fileList);\n}", "removeTemporaryFile() {\n // Only proceed if this AddonInstall owns its XPI file\n if (!this.ownsTempFile) {\n this.logger.debug(`removeTemporaryFile: ${this.sourceURI.spec} does not own temp file`);\n return;\n }\n\n try {\n this.logger.debug(`removeTemporaryFile: ${this.sourceURI.spec} removing temp file ` +\n this.file.path);\n this.file.remove(true);\n this.ownsTempFile = false;\n } catch (e) {\n this.logger.warn(`Failed to remove temporary file ${this.file.path} for addon ` +\n this.sourceURI.spec,\n e);\n }\n }", "onUseBaseRunClick () {\n if (!this.useBaseRun && !this.runOpts.csvDir && this.isUseCurrentAsBaseRun()) {\n this.$q.notify({ type: 'warning', message: this.$t('Input scenario should include all parameters otherwise model run may fail') })\n }\n }", "visitTrace_file_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
F U N C T I O N S This function updates the letters already pressed field on the HTML page. Array g_LettersAlreadyPressed contains the letters entered by the user, so far.
function updateLettesAlreadyPressedField() { var lettersAlreadyPressedId = document.getElementById('letters-already-pressed'); var word2Display = ""; // building a string, so as to have a space between the guessed characters for (var i = 0; i < g_LettersAlreadyPressed.length; i++) { word2Display += (g_LettersAlreadyPressed[i] + ' '); } lettersAlreadyPressedId.textContent = word2Display; }
[ "function clearLettersAlreadyPressedField() {\n\n // First Clear the array holding the letters already pressed \n g_LettersAlreadyPressed = [];\n\n // update the Card Area on the HTML page where these letters are displayed\n updateLettesAlreadyPressedField();\n\n}", "function updateLetters(words, keyPressed) {\n // pressed key is in secretWord - display the letter and continue.\n // since a word can have more than one instance of a letter, loop through\n // entire word to capture all instances.\n\n let indexArr = [];\n for (let i = 0; i < words.secretWord.length; i++) {\n if (words.secretWord[i] === keyPressed) {\n indexArr.push(i);\n }\n }\n console.log(`indexes for ${keyPressed} in ${words.secretWord} are ${indexArr}`);\n\n for (let i = 0; i < indexArr.length; i++) { //Loop through indexArr to replace all instances of correct letter\n words.blankWord[indexArr[i]] = keyPressed;\n }\n let solvedWord = words.blankWord.join(''); //join blankWord array to display correctly and to compare to the secretWord string correctly to check for win condition.\n\n blankWordP.textContent = solvedWord;\n if (solvedWord === words.secretWord) { // after blankWord updates, check if it was the last missing letter\n // window.setTimeout(window.alert, 500, `Winner winner chicken dinner!`);\n makeMeme();\n wins++;\n winsDisplaySpan.textContent = wins;\n\n words = window.setTimeout(restartGame, 3500);\n window.setTimeout(destroyMeme, 3500);\n return words\n }\n}", "function outputUsedLetters(){\n\tdocument.getElementById(\"usedLetters\").innerHTML = gameStringForm(usedLetters);\n}", "function enableButtons() {\n\t//event listener for the guess button\n\t$(\"#guess\").click(function () { \n\t\t//calls the guesser function and passes the value of the input box to the function \n\t\tguesser($(\"#letterHolder\").val()); \n\t\t//and clears the letter input box after guess button is clicked\n\t\t$(\"#letterHolder\").val(\"\"); \n\t});\n\t\n\t$(\"#letterHolder\").removeAttr(\"disabled\");\n\t//initializes the letter holder for the first game\n\t//after the first game the code below is turned on and off\n\t//by removing or adding the the disabled css attribute\n\t//applied to the letterholder id \n\twindow.onload = () => {\n\t\t//does the same thing as as above but with the enter key while in the input box\n\t\t$(\"#letterHolder\").keypress(function (enterButton) { \n\t\t\tvar key = enterButton.which;\n\n\t\t\tif (key === 13) {\n\t\t\t\tguesser($(\"#letterHolder\").val());\n\t\t\t\t$(\"#letterHolder\").val(\"\");\n\t\t\t}\n\t\t});\n\t}\n\n\t$(\"#hintButton\").click(function () {\t\t\n\t\t$(\"#hint\").html(hintArray[hangManArray.indexOf(newWord)]);\n\t\thintUsed = true;\n\t})\n}", "displayKey() {\n var keyVal = key;\n //checks if the key prseed is a char\n if (keyVal.toUpperCase() != keyVal.toLowerCase() && keyVal.length == 1) {\n this.lastKey = keyVal.toUpperCase();\n this.isChar = true;\n textAlign(CENTER)\n text(keyVal.toUpperCase(), 219, 180)\n textAlign(LEFT)\n this.counter = 0;\n\n }\n if (keyIsPressed && !keyIsDown(13)){\n this.isChar = false;\n } \n \n //check when the enter key is pressed; when it is it check if the letter is in the phrase or not\n if (keyIsDown(13) && this.counter == 0 && !this.lost && this.isChar) {\n var repeat = false\n var inPhrase = false;\n //checks if the letter is in the phrase or not\n for (var i = 0; i < this.splitedPhrase.length; i++) {\n if (this.splitedPhrase[i] == this.lastKey) {\n this.blanks[i] = this.splitedPhrase[i];\n text(this.blanks[i], (i * 30), 340)\n inPhrase = true;\n }\n }\n for (var j = 0; j <= this.lettersUsed.length; j++) {\n if (this.lastKey != this.lettersUsed[j]) {\n this.counter++;\n } else repeat = true\n }\n if (inPhrase == false && repeat == false) {\n this.numOfWrongs++;\n }\n if (this.counter != 0 && !repeat && !inPhrase) {\n this.lettersUsed.push(this.lastKey);\n }\n }\n //displays the wrong letters\n textSize(20);\n var Ypos = 70;\n var Xpos = 213;\n textAlign(CENTER);\n for (var i = 0; i < this.lettersUsed.length; i++) {\n if (i % 7 == 0 && i != 0) {\n Ypos += 23;\n Xpos -= 175;\n }\n text(this.lettersUsed[i], Xpos + i * 25, Ypos);\n }\n textAlign(LEFT);\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 updateUsedWords(){\n \t$('.js-used-words').html(\"\");\n\n $.each(usedLetters, function(i, val){\n\t\t\t$('.js-used-words').append(val + \" \");\n \t});\n }", "function UpdateUserHand() {\r\n\r\n for (let i = 0; i < game.alphabet_size; i++)\r\n game.userHand[i] = 0;\r\n\r\n\tfor (let i = 0; i < configuration.maximum_number_of_letters; i++) {\r\n\t\tlet ascii_code = user_letters_DOM.eq(i).attr(\"letter\");\r\n\r\n\t\t//Check if the current user letter container is empty or not, if not empty add the corresponding letter\r\n //to the user userHand in the game object.\r\n\t\tif (ascii_code) {\r\n let letter_index = ascii_to_letter_index[parseInt(ascii_code)];\r\n game.userHand[letter_index]++;\r\n }\r\n\t}\r\n}", "function setLetterPicker(){\n\tvar totalLetters = 0;\n\tletterPickerArray = [];\n\tintPickerArray = [];\n\tfor(var i = 0; i < wordsArray.length; i++){\n\t\tfor(var j = 0; j < wordsArray[i].length; j++){\n\t\t\tletterPickerArray[totalLetters] = wordsArray[i].charAt(j);\n\t\t\tintPickerArray[totalLetters] = 1;\n\t\t\ttotalLetters++;\n\t\t}\n\t}\n\tfor(var x = 0; x < intPickerArray.length; x++){\n\t\tinitialIntValues[x] = intPickerArray[x];\n\t}\n}", "handleInteraction(input) {\n this.activePhrase.checkLetter(input);\n Array.from(document.getElementsByClassName('key')).forEach(key => { //Creating an array of the QWERTY keys to loop through.\n if (key.textContent === input && key.disabled !== true) {\n if (this.activePhrase.checkLetter(input) !== true) {\n key.disabled = true;\n key.classList.add('wrong');\n this.removeLife();\n } else {\n key.disabled = true;\n key.classList.add('chosen');\n this.activePhrase.showMatchedLetter(input);\n this.checkForWin();\n if (this.checkForWin()) {\n this.gameOver('win'); //If the checkForWin method returns true, the gameOver method is called and passed the 'win' parameter.\n }\n }\n }\n });\n }", "function checkLetter(ltr) {\n if (currentWord.indexOf(ltr) !== -1 || playerWord.indexOf(ltr) !== -1) {\n for (var i = 0; i < currentWord.length; i++) {\n if (currentWord[i] === ltr) {\n playerWord[i] = ltr;\n currentWord[i] = \"\";\n lettersLeft--;\n }\n }\n } else {\n if (pastLetters.indexOf(ltr) == -1) {\n decGuesses();\n pastLetters.push(ltr);\n }\n }\n}", "function storeLetters(letters) {\n let letterContainer = document.getElementById(\"letterContainer\");\n for (const char of letters) {\n let underlined = document.createElement(\"div\");\n underlined.setAttribute(\"class\", \"underlined\");\n letterContainer.appendChild(underlined);\n var charContainer = document.createElement(\"div\");\n charContainer.setAttribute(\"hidden\", \"\");\n charContainer.setAttribute(\"class\", \"hiddenChar\");\n charContainer.innerHTML = char;\n underlined.appendChild(charContainer);\n }\n}", "function isLetterCorrect(userInput, currentLetter) {\n if (userInput === currentLetter) {\n message.innerHTML = \"Correct\";\n\n correctKeystrokes++;\n return true;\n } else {\n message.innerHTML = \"Incorrect\";\n incorrectKeystrokes++;\n return false;\n }\n}", "function selectLetter(a: number) {\r\n let alfabet: string = \".ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\r\n\r\n basic.showString(alfabet.charAt(a));\r\n\r\n input.onButtonPressed(Button.A, function () {\r\n selectLetter(a + 1)\r\n })\r\n\r\n input.onButtonPressed(Button.B, function () {\r\n basic.clearScreen();\r\n mesaj += alfabet.charAt(a);\r\n selectLetter(0);\r\n })\r\n\r\n if (input.buttonIsPressed(Button.A) && input.buttonIsPressed(Button.B))\r\n while (true) {\r\n for (let a = 0; a < mesaj.length; a++) {\r\n switch (mesaj.charAt(a)) {\r\n case 'A':\r\n wDot(1)\r\n wLine(1)\r\n break;\r\n\r\n case 'B':\r\n wLine(1)\r\n wDot(3)\r\n break;\r\n\r\n case 'C':\r\n wLine(1)\r\n wDot(1)\r\n wLine(1)\r\n wDot(1)\r\n break;\r\n\r\n case 'D':\r\n wLine(1)\r\n wDot(2)\r\n break;\r\n\r\n case 'E':\r\n wDot(1)\r\n break;\r\n\r\n case 'F':\r\n wDot(2)\r\n wLine(1)\r\n wDot(1)\r\n break;\r\n\r\n case 'G':\r\n wLine(2)\r\n wDot(1)\r\n break;\r\n\r\n case 'H':\r\n wDot(4)\r\n break;\r\n\r\n case 'I':\r\n wDot(2)\r\n break;\r\n\r\n case 'J':\r\n wDot(1)\r\n wLine(3)\r\n break;\r\n\r\n case 'K':\r\n wLine(1)\r\n wDot(1)\r\n wLine(1)\r\n break;\r\n\r\n case 'L':\r\n wDot(1)\r\n wLine(1)\r\n wDot(2)\r\n break;\r\n\r\n case 'M':\r\n wLine(2)\r\n break;\r\n\r\n case 'N':\r\n wLine(1)\r\n wDot(1)\r\n break;\r\n\r\n case 'O':\r\n wLine(3)\r\n break;\r\n\r\n case 'P':\r\n wDot(1)\r\n wLine(2)\r\n wDot(1)\r\n break;\r\n\r\n case 'Q':\r\n wLine(2)\r\n wDot(1)\r\n wLine(1)\r\n break;\r\n\r\n case 'R':\r\n wDot(1)\r\n wLine(1)\r\n wDot(1)\r\n break;\r\n\r\n case 'S':\r\n wDot(3)\r\n break;\r\n\r\n case 'T':\r\n wLine(1)\r\n break;\r\n\r\n case 'U':\r\n wDot(2)\r\n wLine(1)\r\n break;\r\n\r\n case 'V':\r\n wDot(3)\r\n wLine(1)\r\n break;\r\n\r\n case 'W':\r\n wDot(1)\r\n wLine(2)\r\n break;\r\n\r\n case 'X':\r\n wLine(1)\r\n wDot(2)\r\n wLine(1)\r\n break;\r\n\r\n case 'Y':\r\n wLine(1)\r\n wDot(1)\r\n wLine(2)\r\n break;\r\n\r\n case 'Z':\r\n wLine(2)\r\n wDot(2)\r\n break;\r\n\r\n default:\r\n pins.digitalWritePin(DigitalPin.P0, 0)\r\n break;\r\n }\r\n basic.pause(300)\r\n }\r\n basic.pause(700)\r\n }\r\n\r\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 checkForLetter(letter) {\n // Create local var to be used for non correct keys\n let foundLetter = false;\n\n // For loop for correct letters\n for (let i = 0, x = nameToMatch.length; i < x; i++) {\n if (letter === nameToMatch[i]) {\n guessingName[i] = letter;\n foundLetter = true;\n\n // Increment wins and update screen\n if (guessingName.join('') === nameToMatch) {\n const element = document.getElementById('pokemonImg');\n element.classList.add('pokemonShow');\n wins++;\n setTimeout(resetPokemon, 3000);\n }\n }\n updateScreen();\n }\n\n // If wrong letter, decrement remaining guesses\n if (!foundLetter) {\n if (!guessedLetters.includes(letter)) {\n guessedLetters.push(letter);\n numGuesses--;\n }\n\n // If remaining guesses equals 0, increment losses and update screen\n if (numGuesses === 0) {\n guessingName = nameToMatch.split();\n losses++;\n setTimeout(resetPokemon, 3000);\n }\n }\n updateScreen();\n}", "function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}", "function revealLetter() {\n\t\t\tuserGuessIndex = word.indexOf(userGuess);\n\t\t\tfor (i=0; i < word.length; i++) {\n\t\t\t\tif (word[i] === userGuess) {\n\t\t\t\t\thide = hide.split(\"\");\n\t\t\t\t\thide[i] = userGuess;\n\t\t\t\t\thide = hide.join(\"\");\n\t\t\t\t\ttargetA.innerHTML = hide;\n\n\t\t\t\t}\n\t\t\t}\t\n\t\t}", "function printPlayerWord() {\n document.getElementById(\"playerWord\").innerHTML = \"\";\n for (var i = 0; i < playerWord.length; i++) {\n document.getElementById(\"playerWord\").innerHTML += playerWord[i];\n }\n document.getElementById(\"guessed\").innerHTML = pastLetters;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
used to clear the shoes state object after average is calculated
handleClearShoes() { this.setState({ shoes: [] }) }
[ "reset() {\r\n\t\tthis.number = this.props.index + 1\r\n\t\tthis.counters = {\r\n\t\t\tfigure: 0\r\n\t\t}\r\n\t\t// TODO: Incorporate equation numbers.\r\n\t}", "function reset() {\n svg_g.selectAll(\".brush\").call(brush.move, null);\n svg_g.selectAll(\".brushMain\").call(brush.move, null);\n }", "reset() {\r\n\t\tthis.changeState(this.initial);\r\n\t}", "function resetVars(state) {\n keepBallAttached = false;\n ballIsUp = false;\n fired = false;\n }", "resetSquare(square, newState) {\n square.directionalCost = \"\";\n square.direction = \"\";\n square.state = newState;\n square.parent = \"\";\n square.startDistance = 0;\n square.goalDistance = 0;\n square.total = 0;\n }", "reset() {\n /**\n * The overall error.\n */\n this.globalError = 0;\n /**\n * The size of a set.\n */\n this.setSize = 0;\n\n this.sum = 0;\n }", "resetStats() {\n\t\tthis.gameDataList = [];\n\t\tthis.curGameData = null;\n\t}", "function resetGame() {\n ships._ships = [];\n currentState = states.Splash;\n score = 0;\n shipGap = shipGapMax;\n}", "function resetCalculations() {\n calculatedBogoMips = null;\n clientEffectsLevel = null;\n calculateJsBogoMips();\n }", "function clearCalculation() {\n calculation = [];\n displayCalculation();\n }", "clearAllObject() {\r\n this.m_drawToolList.length = 0;\r\n this.clearTechToolMousePos();\r\n }", "function clear() {\n clearCalculation();\n clearEntry();\n resetVariables();\n operation = null;\n }", "function clearSelection() {\n currentPizza = undefined;\n $('input[name=\"e-item\"]').prop('checked', false);\n $('input[name=\"psize\"]').prop('checked', false);\n $(\".lists-wrapper\").hide();\n\n currentBeverage = undefined;\n $('input[name=\"bsize\"]').prop('checked', false);\n $(\".beverage-size-list\").hide();\n\n currentOrder = undefined;\n\n }", "function reset() {\n Caman(\"#canvas\", img, function () {\n this.revert();\n })\n}", "reset() {\n\t\tthis.ready = false;\n\t\tthis.states = [];\n\t\tthis.battles = [];\n\t\tthis.fighters = [];\n\t}", "resetGrid() {\n this.createGridArray();\n\n // reinitializing the saved start and goal squares\n startSquareIndex = 0;\n goalSquareIndex = this.gridArray.length - 1;\n this.startSquare = this.getSquareByIndex(startSquareIndex);\n this.startSquare.state = start;\n this.goalSquare = this.getSquareByIndex(goalSquareIndex);\n this.goalSquare.state = goal;\n\n this.colorGrid(); // recolor the grid\n this.updateSquareCosts(); // update the costs for HTML\n this.isShowingCost = false;\n this.toggleCosts();\n }", "function resetMain(){\n\tfor (var i = 0; i < leveldata.length; i++){\n\t\tleveldata[i].posX = leveldata[i].resetX;\n\t\tleveldata[i].spawned = false;\n\t\tleveldata[i].despawned = false;\n\t\tleveldata[i].removed = false;\n\t}\n\t\n\tscore = 0;\n\tspeed = 0;\n\teggsSaved = 0;\n\tcurrentGameState = gameStates[2];\n}", "function clear() {\n resetStore();\n }", "function EmptyState() {\n return;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is first given the select menu object who's options are being set. Secondly, an array of all options is passed and finally, an array of options not to be included in the menu is passed. Each item in the first array is compaired to each item in the second array. If the item from the first array is found in the second array, that item is not included as an option in the given select object. If it is not found, then that item is written to the select object as an option
function setOptions(select_menu, main_array, subtract_array) { // Get the value of the currently selected item. var selected_value = select_menu.options[select_menu.selectedIndex].value; // Clear the select menu except for the first option. select_menu.length = 1; // Loop through all the values in the main array. for (i = 0; i < main_array.length; i++) { var found = 0; var string = main_array[i].value; var split_at = string.indexOf(","); var value = string.substring(0, split_at); var text = string.substring(split_at + 1); // If the subtract array is undefined, skip this. if (subtract_array !== undefined) { // Loop through the values in the subtract_array. for (i2 = 0; i2 < subtract_array.length; i2++) { var subtract_string = subtract_array[i2].value; var subtract_split_at = subtract_string.indexOf(","); var subtract_value; // If the value has a delimeter, split the value to get only the first // string before the delimeter. Otherwise, keep the value as it is. if (subtract_split_at > -1) { subtract_value = subtract_string.substring(0, subtract_split_at); } else { subtract_value = subtract_string; } // If the value equals the subtract value set found to 1. if (value === subtract_value) { found = 1; break; } } } // Write the main array values to the menu options only if // the value is not found in the subtract array. if (found === 0) { var option = document.createElement("option"); option.value = value; option.text = text; select_menu.options.add(option); } } // Loop through the select menu options after they have been written. // If the value of the option equals the selected value saved at the // beginning of the script, set it to the selected option. for (i = 0; i < select_menu.options.length; i++) { if (select_menu.options[i].value === selected_value) { select_menu.selectedIndex = i; break; } } }
[ "function copySelectedOptions(from,to) {\n\tvar options = new Object();\n\tfor (var i=0; i<to.options.length; i++) {\n\t\toptions[to.options[i].value] = to.options[i].text;\n\t\t}\n\tfor (var i=0; i<from.options.length; i++) {\n\t\tvar o = from.options[i];\n\t\tif (o.selected) {\n\t\t\tif (options[o.value] == null || options[o.value] == \"undefined\" || options[o.value]!=o.text) {\n\t\t\t\tto.options[to.options.length] = new Option( o.text, o.value, false, false);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tif ((arguments.length<3) || (arguments[2]==true)) {\n\t\tsortSelect(to);\n\t\t}\n\tfrom.selectedIndex = -1;\n\tto.selectedIndex = -1;\n\t}", "function _move_between_selects(block, myForm, multiselect1, multiselect2) {\n\n\tvar ida = (block ? multiselect1 : multiselect2);\n\tvar idb = (block ? multiselect2 : multiselect1);\n\n\tvar sa = myForm.getSelect(ida);\n\tvar sb = myForm.getSelect(idb);\n\n\tvar t = myForm.getItemValue(ida);\n\tif (t.length == 0)\n\t\treturn;\n\teval(\"var k={'\" + t.join(\"':true,'\") + \"':true};\");\n\n\tvar w = 0;\n\tvar ind = -1;\n\twhile (w < sa.options.length) {\n\t\tif (k[sa.options[w].value] && sa.options[w].value != 'rhumanos@silencor.pt' && sa.options[w].value != 'administracao@silencor.pt') {\n\t\t\tsb.options.add(new Option(sa.options[w].text, sa.options[w].value));\n\t\t\tsa.options.remove(w);\n\t\t\tind = w;\n\t\t} else {\n\t\t\tw++;\n\t\t}\n\t}\n\n\tif (sa.options.length > 0 && ind >= 0)\n\t\tif (sa.options.length > 0)\n\t\t\tsa.options[t.length > 1 ? 0 : Math.min(ind, sa.options.length - 1)].selected = true;\n}", "_mergeOptions(oldOptions, newOptions) {\n const origKeys = new Set(Object.keys(oldOptions))\n const mergedOptions = { ...oldOptions, ...newOptions }\n\n Object.keys(mergedOptions).forEach( (key) => {\n if (!origKeys.has(key)) {\n console.error(`Unexpected options parameter \"${key}\" will be removed. This should never happen - please investigate.`) // this should not happen\n }\n const value = mergedOptions[key]\n if (!origKeys.has(key) || !value || (Array.isArray(value) && value.length == 0)) delete mergedOptions[key];\n })\n return mergedOptions\n }", "function ClearSelectOptions( obj )\n{\n if( obj == undefined || obj == null ) return ;\n try\n {\n for( var i = obj.options.length - 1; i >= 0 ; i -- )\n obj.options.remove(i) ;\n return ;\n }\n catch(err)\n {\n return ;\n }\n}", "function setWidgetOptions($obj, data) { \r\n var exclude = [];\r\n if ($obj.hasClass('dependent-select-last')) {\r\n $obj.next().find('option').each(function(i, option) {\r\n exclude[exclude.length] = parseInt($(option).val());\r\n });\r\n }\r\n unsetWidgetOptions($obj);\r\n $.each(data, function(i, settings) {\r\n if ($.inArray(parseInt(settings.value), exclude) == -1) {\r\n $obj.append(\r\n $('<option></option>').val(settings.value).html(settings.text)\r\n );\r\n }\r\n });\r\n }", "clear_selects_after_and_including(select) {\n let next;\n select.empty().html('<option></option>');\n if (next = this.next_select(select)) { return this.clear_selects_after_and_including(next); }\n }", "function transferSelection(id1, id2) {\n obj1 = document.getElementById(id1).options;\n obj2 = document.getElementById(id2).options;\n for (var i=0; i<obj1.length; i++) {\n if (!obj1[i].selected) continue;\n found = false;\n for (var j=0; j<obj2.length; j++) {\n if (obj2[j].value==obj1[i].value) {\n found = true;\n break;\n }\n }\n if (!found) {\n obj2[obj2.length] = new Option(obj1[i].text, obj1[i].value, false, false);\n }\n }\n}", "_getInvalidOptionValues(values) {\n const isEqual = this.compareWith || Object.is;\n const validValues = (this.options || []).map(option => option.value);\n return values.filter(value => !validValues.some(validValue => isEqual(value, validValue)));\n }", "_verifyNoOptionValueCollisions() {\n this.options.changes.pipe(startWith(this.options), takeUntil(this.destroyed)).subscribe(() => {\n var _a;\n const isEqual = (_a = this.compareWith) !== null && _a !== void 0 ? _a : Object.is;\n for (let i = 0; i < this.options.length; i++) {\n const option = this.options.get(i);\n let duplicate = null;\n for (let j = i + 1; j < this.options.length; j++) {\n const other = this.options.get(j);\n if (isEqual(option.value, other.value)) {\n duplicate = other;\n break;\n }\n }\n if (duplicate) {\n // TODO(mmalerba): Link to docs about this.\n if (this.compareWith) {\n console.warn(`Found multiple CdkOption representing the same value under the given compareWith function`, {\n option1: option.element,\n option2: duplicate.element,\n compareWith: this.compareWith,\n });\n }\n else {\n console.warn(`Found multiple CdkOption with the same value`, {\n option1: option.element,\n option2: duplicate.element,\n });\n }\n return;\n }\n }\n });\n }", "function aSelectEnables(selectSelector, itemsSelectors, hideItemsSelectors)\n{\n $(selectSelector).data('aSelectEnablesItemsSelectors', itemsSelectors);\n $(selectSelector).data('aSelectEnablesHideItemsSelectors', hideItemsSelectors);\n $(selectSelector).change(function() {\n update(this);\n });\n\n function update(select)\n {\n var itemsSelectors = $(select).data('aSelectEnablesItemsSelectors');\n var hideItemsSelectors = $(select).data('aSelectEnablesHideItemsSelectors');\n if (itemsSelectors !== undefined)\n {\n for (var option in itemsSelectors)\n {\n $(itemsSelectors[option]).attr('disabled', 'disabled');\n }\n var option = select.value;\n if (itemsSelectors[option])\n {\n $(itemsSelectors[option]).removeAttr('disabled');\n }\n }\n if (hideItemsSelectors !== undefined)\n {\n for (var option in hideItemsSelectors)\n {\n $(hideItemsSelectors[option]).hide();\n }\n var option = select.value;\n if (hideItemsSelectors[option])\n {\n $(hideItemsSelectors[option]).show();\n }\n }\n }\n $(function() {\n $(selectSelector).each(function() { update(this) });\n });\n}", "function build_your_own_different_dvd_options(optionSet1, optionSet2){\n var focus = 'selectboxit-focus';\n var selected = 'selectboxit-selected'; \n window.firstDvdSelection = false;\n window.seconDDvdSelection = false;\n\n // Find element in first select\n optionSet1.children().each(function(){\n if($(this).hasClass(focus)){\n window.firstDvdSelection = $(this);\n } \n });\n // Find element in second select\n optionSet2.children().each(function(){\n if($(this).hasClass(focus)){\n window.seconDDvdSelection = $(this);\n } \n });\n\n // If they are not undefined and if they are the same\n if(window.firstDvdSelection != false && window.seconDDvdSelection != false){\n if(window.firstDvdSelection.text() == window.seconDDvdSelection.text()){\n // Initialize selectboxit\n var selectBox = $('#build-your-own-two select').selectBoxIt().data('selectBox-selectBoxIt');\n selectBox.selectOption(0);\n } \n }\n }", "_unselectedOptions() {\n return this._optionsDiv.get().querySelectorAll('div.multi-select__option:not(.multi-select__option--selected):not(.multi-select__option--hidden)');\n }", "function addToSelect(values) {\nvalues.sort();\nvalues.unshift('None'); // Add 'None' to the array and place it to the beginning of the array\nvalues.forEach(function(value) {\n var option = document.createElement(\"option\");\n option.text = value;\n municipalSelect.add(option);\n});\nreturn setLotMunicipalExpression(municipalSelect.value);\n}", "function setOptionLabels(mthis) {\n var products = [];\n var optVal = mthis.val();\n var attrId = parseInt(mthis.prop(\"id\").replace(/[^\\d.]/g, \"\"));\n var data = JSON.parse(getAllData());\n var options = data.attributes[attrId].options;\n options.forEach(function (cObj) {\n if (cObj.id == optVal) {\n cObj.products.forEach(function (cPro) {\n var selectIndex = jQuery(\"select\").index(mthis);\n if (selectIndex > 0) {\n var prevSelect = jQuery(\"select\").eq(selectIndex - 1);\n var prevSelectAttrId = parseInt(\n prevSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n if (!isNaN(prevSelectAttrId)) {\n var prevSelectOptions = data.attributes[prevSelectAttrId].options;\n prevSelectOptions.forEach(function (subObj) {\n if (subObj.id == prevSelect.val()) {\n if (subObj.products.indexOf(cPro) != -1) {\n products.push(cPro);\n }\n }\n });\n }\n } else {\n products.push(cPro);\n }\n });\n }\n });\n var selectIndex = jQuery(\".input-box select\").index(mthis);\n var nextSelect = jQuery(\".input-box select\").eq(selectIndex + 1);\n if (nextSelect.length > 0) {\n var nextSelectAttrId = parseInt(\n nextSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n var nextSelectOptions = data.attributes[nextSelectAttrId].options;\n nextSelect.empty();\n nextSelect.append(\"<option value>Choose an Option...</option>\");\n nextSelect.removeAttr(\"disabled\");\n nextSelectOptions.forEach(function (cObj) {\n cObj.products.forEach(function (cPro) {\n if (products.indexOf(cPro) != -1) {\n if (jQuery(\"option[value=\" + cObj.id + \"]\").length <= 0) {\n nextSelect.append(\n '<option value=\"' + cObj.id + '\">' + cObj.label + \"</option>\"\n );\n }\n }\n });\n });\n }\n}", "renderSelects(optObject, multipleSelect){\n let selects = [];\n for(let key in optObject){\n let keyLength = optObject[key].length;\n let opts = [];\n opts.push(<option key=\"dummy\" value='unselected'>Select...</option>)\n for(let i = 0; i < keyLength; i++){\n opts.push(<option key={optObject[key][i][0]} value={optObject[key][i][0]}>{optObject[key][i][1]}</option>);\n }\n if(!multipleSelect){\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control'>{opts}</select></div>);\n }\n else {\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength + 1} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control' multiple>{opts}</select></div>);\n }\n }\n return selects;\n }", "prepareSelectTypes() {\n let items_buffer = getReferencesOfType('AGItem');\n let that = this;\n let types_buffer = [];\n let append_buffer = \"<option item_type = ''></option>\";\n if (items_buffer.length > 0) {\n items_buffer.forEach(function (element) {\n let type_buffer = getReferenceById(element).type;\n if (!types_buffer.includes(type_buffer)) {\n types_buffer.push(type_buffer);\n append_buffer += \"<option item_type = \" + type_buffer + \">\" + type_buffer + \"</option>\";\n }\n });\n }\n return append_buffer;\n }", "function rebuildSelect(users, flagSelected, selectedValue) {\n // store my team in global var an then check it\n var optGroupMy = document.createElement('OPTGROUP'),\n optGroupNotMy = document.createElement('OPTGROUP');\n selectResolver = document.getElementById('selectResolver'),\n counterOfArguments = arguments.length,\n oldValue = selectResolver.value;\n\n optGroupMy.label = 'My Team';\n optGroupNotMy.label = 'Other Users';\n\n if (checkAccessControl(TASK_ACL.MODIFY_RESOLVER)) {\n me.getMyTeam().then(function(myTeam) {\n var otherUsers = _.differenceWith(users, myTeam, function(user, myTeamPlayer) {\n return user.id === myTeamPlayer.id;\n });\n otherUsers = _.sortBy(otherUsers, 'name');\n myTeam = _.sortBy(myTeam, 'name');\n\n // todo: refactor me\n // rm all inside select\n selectResolver.options.length=0;\n var ogl=selectResolver.getElementsByTagName('optgroup');\n for (var i = ogl.length-1 ; i >= 0 ; i-- ){\n selectResolver.removeChild(ogl[i])\n }\n\n selectResolver.options.add(new Option('select', 0));\n if (myTeam.length) {\n selectResolver.appendChild(optGroupMy);\n }\n for (var i = 0; i < myTeam.length ; i++) {\n optGroupMy.appendChild(new Option(myTeam[i].name, myTeam[i].id));\n }\n\n if (otherUsers.length) {\n selectResolver.appendChild(optGroupNotMy);\n }\n for (var j = 0; j < otherUsers.length ; j++) {\n optGroupNotMy.appendChild(new Option(otherUsers[j].name, otherUsers[j].id));\n }\n\n // selectedValue was passed\n if (counterOfArguments === 3) {\n selectedValue = selectedValue || 0;\n selectResolver.value = selectedValue;\n return;\n }\n\n if (flagSelected) {\n selectResolver.value = oldValue;\n }\n\n }, errorCather);\n } else {\n selectResolver.options.add(new Option('select', 0));\n for (var i = 0; i < users.length ; i++) {\n selectResolver.options.add(new Option(users[i].name, users[i].id));\n }\n\n if (flagSelected) {\n selectResolver.value = oldValue;\n }\n }\n }", "function copySelectedItems(src, dest) {\r\n var i;\r\n\r\n deselectAllItems(dest);\r\n for (i = 0; i < src.options.length; ++i) {\r\n var thisoption = src.options[i];\r\n if (thisoption.selected == true) {\r\n var option = findItemByValue(dest, thisoption.value);\r\n if (option != null) {\r\n option.selected = true;\r\n } else {\r\n appendNewItem(dest, thisoption.text, thisoption.value, true);\r\n }\r\n }\r\n }\r\n}", "resetOptions(){\r\n\t\t// reset all extras;\r\n\t\tconst $selects = $('.sm-box').find('select');\r\n\t\t$($selects).each((i, el) => {\r\n\t\t\tconst name = $(el).attr('id');\r\n\t\t\t$(`#${name}`).prop('selectedIndex', 0);\r\n\t\t\tthis.resetSheetValues(name);\r\n\t\t});\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mark the KalturaDrmPolicy object as deleted.
static deleteAction(drmPolicyId){ let kparams = {}; kparams.drmPolicyId = drmPolicyId; return new kaltura.RequestBuilder('drm_drmpolicy', 'delete', kparams); }
[ "deletePolicy(callback) {\n return this.deletePolicyRequest().sign().send(callback);\n }", "function deleteTablePolicy(table, name, options, _) {\n var deletePolicySettings = createTablePolicySetting(options);\n deletePolicySettings.resourceName = interaction.promptIfNotGiven($('Table name: '), table, _);\n deletePolicySettings.policyName = interaction.promptIfNotGiven($('Policy name: '), name, _);\n deletePolicySettings.tips = util.format($('Deleting the stored access policy %s on the table %s'), deletePolicySettings.policyName, deletePolicySettings.resourceName);\n\n var policies = StorageUtil.deletePolicy(deletePolicySettings, _);\n cli.interaction.formatOutput(policies, function(outputData) {\n if (outputData) {\n logger.info(util.format($('The stored access policies on table %s are: '), deletePolicySettings.resourceName));\n StorageUtil.showPolicyResults(outputData);\n } else {\n logger.info(util.format($('There is no stored access policy on the table %s'), deletePolicySettings.resourceName));\n }\n });\n }", "function AM_policy_delete(amServer, inputAccountIntentId){\n\n var result = {};\n var ssoToken = amServer.ssoToken;\n\n restCall = {};\n restCall.url = constructAmUri(amServer) + \"/json/realms/\" + amServer.policyRealm + \"/policies/\" + inputAccountIntentId;\n\n\tconsole.log(\"[DEBUG]: url to delete - \" + restCall.url);\n\n restCall.headers = { \"contentType\" : \"application/json\",\n \"Accept-API-Version\" : \"protocol=1.0\",\n \"iPlanetDirectoryPro\" : ssoToken};\n restCall.method = \"DELETE\";\n\n executeRest(restCall);\n\n return;\n\n}", "deleteRecord() {}", "async delete() {\n await this.pouchdb.destroy();\n await this.database.removeCollectionDoc(this.dataMigrator.name, this.schema);\n }", "function deleteButtonPressed(entity) {\n db.remove(entity);\n }", "function confirmDelete(data) {\n var policyId = data.id;\n var policyName = \"\";\n\n // Determines the policy's name by checking the list\n for (var i = 0; i < policyList.length; i++) {\n if (policyId === policyList[i].id) {\n policyName = policyList[i].name;\n break;\n }\n }\n\n // Show the alert to the user and return the resulting promise\n return Swal.fire({\n title: 'Delete Policy',\n type: 'warning',\n html: \"Are you sure you want to delete policy \\\"\" + policyName + \"\\\"?\",\n showCancelButton: true,\n confirmButtonText: 'Delete',\n confirmButtonClass: 'bg-red',\n focusConfirm: false,\n cancelButtonText: 'Cancel'\n });\n }", "async delete(req, doc, options = {}) {\n options = options || {};\n const m = self.getManager(doc.type);\n await m.emit('beforeDelete', req, doc, options);\n await self.deleteBody(req, doc, options);\n await m.emit('afterDelete', req, doc, options);\n }", "function markDeleted(initialComment) {\n initialComment.deleted = true;\n if (initialComment.replies) {\n initialComment.replies.forEach(function(reply) {\n markDeleted(reply);\n });\n }\n }", "function deletePubKey() {\n ctrl.pubKey.$remove(\n {id: ctrl.pubKey.id},\n function() {\n raiseAlert('success',\n '', 'Public key deleted successfully');\n $uibModalInstance.close(ctrl.pubKey.id);\n },\n function(httpResp) {\n raiseAlert('danger',\n httpResp.statusText, httpResp.data.title);\n ctrl.cancel();\n }\n );\n }", "deleteLifecycle(callback) {\n return this.deleteLifecycleRequest().sign().send(callback);\n }", "function deletePaymentGroup() {\n Merchant.delete('payment_group', vm.delete_payment_group.id).then(function(response){\n vm.payment_groups.splice(delete_payment_group_index, 1);\n $(\"#delete-payment_group-modal\").modal('toggle');\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}", "deleteDoc(doc) {\n this.docs.delete(doc.getIdentifier());\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}", "function soft_delete_middleware(next) {\n\n var cons = this._conditions, add_clause = true;\n\n // if the supplied query has specified any type of deleted, don't add\n if (detect_deleted(cons)) {\n add_clause = false;\n } else {\n [\"$or\", \"$and\"].forEach(function(key) {\n if (!cons[key] || !Array.isArray(cons[key])) return;\n cons[key].forEach(function(con) {\n if (detect_deleted(con)) add_clause = false;\n });\n });\n }\n\n if (add_clause) this.find({ deleted : false });\n\n next();\n}", "delete() {\n return spPost(WebPartDefinition(this, \"DeleteWebPart\"));\n }", "async delete(objectStoreName, key) {\n let store = await this.getStore(objectStoreName, \"readwrite\");\n let request = store.delete(key);\n return this.handleRequest(request);\n }", "function deleteDeviceAssignment(axios$$1, token, force) {\n var query = '';\n if (force) {\n query += '?force=true';\n }\n return restAuthDelete(axios$$1, 'assignments/' + token + query);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to fetch the next generation; if not cached, wait till we receive an alert from `calculatorListener`
fetchNextGeneration() { // helper to resolve the promise and start a new batch of generations to compute if need be const resolveGeneration = (resolve, i, currState) => { resolve({i, nextGen: currState}); // we are at the end of the batch, generate a new one if (i % 10 == 0) { this.generate(i + 1, 10, this.states[i]); } }; return new Promise(resolve => { let currState = this.states[++this.iteration]; const i = this.iteration; // if result already cached, return it if (currState) { resolveGeneration(resolve, i, currState); return; } // current generation is not cached, wait until it has been computed this.calculatorListener.on(`${this.iteration}-generated`, state => { resolveGeneration(resolve, i, state); }, true); }); }
[ "async getNextGeneration() {\n const {i, nextGen} = await this.fetchNextGeneration();\n canvasScript.displayNewGeneration(i, nextGen);\n }", "_checkGeneratorIsAlive() {\n this._log('Checking generator is alive...');\n this._client.existsAsync(LAST_GENERATOR_TIME).then((reply) => {\n if (reply === 0) {\n this._client.watch(LAST_GENERATOR_TIME);\n const multiQuery = this._client.multi()\n .set(LAST_GENERATOR_TIME, 1)\n .expire(LAST_GENERATOR_TIME, 10);\n return multiQuery.execAsync()\n } else {\n Promise.resolve(null);\n }\n }).then((reply) => {\n if (reply == null) {\n this._getMessages();\n } else {\n this._isGenerator = true;\n this._generateMessage();\n }\n }).catch((err) => { throw err });\n }", "function getNext(){\r\n // Don't do this if the user asked us not to\r\n if (!forward_fill) return;\r\n\r\n debug(d_med, \"We're getting the next 10!\");\r\n\r\n // Here we want to calculate the url of the next 10 reports\r\n\r\n // If we're on the initial report/message page\r\n if (latest_url.indexOf('s=')==-1){\r\n\tdebug(d_low, \"'s=' not found in url; append '?s=10'\");\r\n\tif (latest_url.indexOf('?')!=-1){\r\n\t latest_url += '&s=10';\r\n\t}\r\n\telse {\r\n\t latest_url += '?s=10';\r\n\t}\r\n }\r\n // Else we should extract and incriment that value by 10 to get the next page\r\n else {\r\n\tdebug(d_low, \"'s=' found in url; increment by 10\");\r\n\r\n\t// Strip off any troublesome #'s...\r\n\tif (latest_url.indexOf('#') != -1) latest_url = latest_url.split('#')[0];\r\n\r\n\ta = latest_url.split('s=')[1];\r\n\t// Hack to avoid infinite recursion, just in case...\r\n\tif (parseInt(a) > 300){\r\n\t updateArrows(true);\r\n\t return;\r\n\t}\r\n\tlatest_url = latest_url.split('s=')[0] + 's='+(parseInt(a)+10);\r\n }\r\n\r\n debug(d_low, latest_url);\r\n\r\n GM_xmlhttpRequest({\r\n\t method: 'GET',\r\n\t\turl: latest_url,\r\n\t\theaders: null,\r\n\t\tonload: onNextLoad});\r\n}", "function evaluate_generator(gen) {\r\n let next = gen.next();\r\n while (!next.done) {\r\n next = gen.next(); \r\n }\r\n return next.value;\r\n }", "async function getInitialValue() {\n try {\n const previousValue = await IDB.getItem(database, storeName, key);\n if (previousValue) {\n setPrivateValue(previousValue);\n } else if (initialValue) {\n await IDB.setItem(database, storeName, key, initialValue);\n setPrivateValue(initialValue);\n }\n } catch (error) {\n console.error('getInitialValue failed:', error);\n }\n }", "async function getNextMeetupV3() {\n const meetingCache = cache.get('nextMeeting');\n if (meetingCache) {\n return meetingCache[0];\n } else {\n const response = await fetch('https://api.meetup.com/2/events?&sign=true&group_id=10250862&page=20&key=' + process.env.meetupapi_key);\n const json = await response.json();\n const meetingArray = json.results;\n setTimeToNewYork(meetingArray);\n cache.put('nextMeeting', meetingArray, 3600000);\n return meetingArray[0]; \n }\n}", "function evaluateNextGenome() {\n //increment index in genome array\n currentGenome++;\n //If there is none, evolves the population.\n if (currentGenome == genomes.length) {\n evolve();\n }\n //load current gamestate\n loadState(roundState);\n //reset moves taken\n movesTaken = 0;\n //and make the next move\n makeNextMove();\n }", "function nextGen(matrix) {\n if (!isInitialized){\n drawGrid(matrix); // use hard-coded matrix first time\n } else {\n // already initialized\n var tempMatrix = matrix;\n\n for(var i=0; i<tempMatrix.length; i++){\n for (var j=0; j<tempMatrix[i].length; j++){\n if (tempMatrix[i][j].liveNeighborCount === 2 || tempMatrix[i][j].liveNeighborCount === 3){\n tempMatrix[i][j].state = true;\n // console.log(tempMatrix[i][j], ' is alive');\n } else if (tempMatrix[i][j].liveNeighborCount < 2 || tempMatrix[i][j].liveNeighborCount >= 4 ) { \n tempMatrix[i][j].state = false;\n // console.log(tempMatrix[i][j], ' is dead');\n }\n }\n }\n \n clearBoard(tempMatrix);\n var newMatrix = countLiveNeighbors(tempMatrix);\n \n drawGrid(newMatrix);\n } // end of else. isInitialized === true\n\n generationCount++;\n if (generationCount > 1){\n $(\"#goback\").css('display', 'inline-block');\n } else {\n $(\"#goback\").css('display', 'none'); \n }\n $(\"#genCount\").html('<h4>Generation: ' + generationCount + '</h4>');\n // console.log(neighborArray);\n}", "refreshNow() {\n return __awaiter(this, void 0, void 0, function* () {\n this.refreshNeeded = true;\n // When forcing a refresh, always sleep with a random jitter\n // to prevent coding errors that could be calling refreshNow\n // in a loop.\n let max = SecretCacheObject.FORCE_REFRESH_JITTER_SLEEP + 1;\n let min = SecretCacheObject.FORCE_REFRESH_JITTER_SLEEP / 2;\n let sleep = Math.floor(Math.random() * (max - min)) + min;\n // Make sure we are not waiting for the next refresh after an\n // exception. If we are, sleep based on the retry delay of\n // the refresh to prevent a hard loop in attempting to refresh a\n // secret that continues to throw an exception such as AccessDenied.\n if (null != this.exception) {\n let wait = this.nextRetryTime - (+new Date());\n sleep = Math.max(wait, sleep);\n }\n setTimeout(() => __awaiter(this, void 0, void 0, function* () {\n yield this.refresh();\n }), sleep);\n return (null == this.exception);\n });\n }", "function getRandomNumber(){\n return new Promise (resolve => {setTimeout(function(){\n //Multiply Math.random() by 10\n resolve (Math.random()*10);\n }, 500);\n \n });\n }", "generate_completion_code() {\n return Math.round(Math.random() * 1e12);\n }", "checkNextGame (){\n\n }", "function cacheNewKeyPairs () {\n if(pregeneratedKeyPairs.length < desiredCacheLength && !pending) {\n pending = true;\n generateKeyPair(function (err, pemKeyPair) {\n pending = false;\n pregeneratedKeyPairs.push(pemKeyPair);\n cacheNewKeyPairs();\n });\n }\n }", "if (_cacheRepoAssure.lastAssured + 5 * 1000 * 60 >= Date.now()) {\n return _cacheRepoAssure.pendingAssure;\n }", "function _getNewRuffles(){\n\t\t\t// if we are currently getting new ruffles, queue up another grab\n\t\t\tif(state.getting){\n\t\t\t\tstate.getQueued = true;\n\t\t\t}else{\n\t\t\t\tstate.getting = true;\n\n\t\t\t\t// first grab\n\t\t\t\treturn grab();\n\t\t\t}\n\t\t}", "_findNextChangedRunner(id) {\n const {plan} = this._plan;\n const findRunners = plan.filter((_pi) => _pi.size === '2.5x7');\n let findCurrentRunnerIndex = plan.findIndex((_pi) => _pi.id === id);\n let nextRunner = null;\n if (findCurrentRunnerIndex > -1) {\n /* eslint-disable-next-line no-constant-condition */\n while (true) {\n if (findCurrentRunnerIndex > findRunners.length - 1) break;\n const findNextRunner = findRunners[findCurrentRunnerIndex];\n if (findNextRunner.hasChanged) {\n nextRunner = findNextRunner;\n break;\n }\n\n findCurrentRunnerIndex++;\n }\n }\n return nextRunner;\n }", "function updateGenerationCounter() {\n \t\t$('#generation span').html(++generation);\n \t}", "async function callRan(){\n const num = getRandomNumber();\n console.log(num);\n }", "function getNextMeetupV2() {\n return new Promise((resolve, reject) => {\n const meetingCache = cache.get('nextMeeting');\n if (meetingCache) {\n resolve(meetingCache[0]);\n } else {\n fetch('https://api.meetup.com/2/events?&sign=true&group_id=10250862&page=20&key=' + process.env.meetupapi_key).then(response => {\n return response.json();\n }).then(json => {\n const meetingArray = json.results;\n setTimeToNewYork(meetingArray);\n cache.put('nextMeeting', meetingArray, 3600000);\n resolve(meetingArray[0]);\n }).catch(err => {\n reject(err);\n });\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called by InputAdapter before an InputEvent begins. Returns true if the event should be consumed. If consumed, the event will not begin.
onPreInputEvent(pointer) { return false; }
[ "function atBeginning() {\n\treturn currentSceneIndex === 0;\n}", "preStep() {\n if (this.controls) {\n if (this.controls.activeInput.up) {\n this.sendInput('up', { movement: true })\n }\n\n if (this.controls.activeInput.left) {\n this.sendInput('left', { movement: true })\n }\n\n if (this.controls.activeInput.right) {\n this.sendInput('right', { movement: true })\n }\n }\n }", "function runPrevKeyDownEvent() {\n /*\n Check to see if the current playlist has been set\n or null and set the previous song.\n */\n if (config.active_playlist == \"\" || config.active_playlist == null) {\n AudioNavigation.setPrevious();\n } else {\n AudioNavigation.setPreviousPlaylist(config.active_playlist);\n }\n }", "isStart(editor, point, at) {\n // PERF: If the offset isn't `0` we know it's not the start.\n if (point.offset !== 0) {\n return false;\n }\n\n var start = Editor.start(editor, at);\n return Point.equals(point, start);\n }", "_onPinchStart(event) {\n const pos = this.getCenter(event);\n\n if (!this.isPointInBounds(pos, event)) {\n return false;\n }\n\n const newControllerState = this.controllerState.zoomStart({\n pos\n }).rotateStart({\n pos\n }); // hack - hammer's `rotation` field doesn't seem to produce the correct angle\n\n pinchEventWorkaround._startPinchRotation = event.rotation;\n pinchEventWorkaround._lastPinchEvent = event;\n this.updateViewport(newControllerState, NO_TRANSITION_PROPS, {\n isDragging: true\n });\n return true;\n }", "function reportDelayIfReady() {\n if (firstInputDelay && firstInputEvent && firstInputCallbacks.length > 0) {\n firstInputCallbacks.forEach(function(callback) {\n callback(firstInputDelay, firstInputEvent);\n });\n firstInputCallbacks = [];\n }\n }", "function doCheck() {\n if (hasStarted === false) {\n // The test has not started, but the user is typing already -- maybe we should start?\n beginTest(); // Yes, we should -- consider it done!\n }\n}", "function testEvent_pre() {\n delegate.addRoot(document.body);\n\n delegate.registerHandlers({\n 'mousedown .foo': f1,\n 'mousemove .quix': f2\n }, {});\n\n el1.dispatchEvent(createMouseEvent('mousedown'));\n el2.dispatchEvent(createMouseEvent('mousedown'));\n\n thermo.scheduler.runFrameDebugDebug();\n assertEvents(f1, ['mousedown']);\n assertEvents(f2, []);\n}", "function KeyboardInfoPre(/**\n * Defines the type of event (BABYLON.KeyboardEventTypes)\n */type,/**\n * Defines the related dom event\n */event){var _this=_super.call(this,type,event)||this;_this.type=type;_this.event=event;_this.skipOnPointerObservable=false;return _this;}", "function should_call(event_def) {\n\t\tif (typeof event_def.should_call !== 'function') {\n\t\t\treturn true;\n\t\t}\n\t\treturn event_def.should_call();\n\t}", "wasRecentlyScanned(barcode) {\n\t\treturn barcode && barcode === this.state.previousBarcode\n\t}", "function expectedEventsDispatched()/* : Boolean*/\n {\n for (var i/*:uint*/ = 0; i < this._expectedEventTypes$_LKQ.length; ++i )\n {\n var expectedEvent/* : String*/ = this._expectedEventTypes$_LKQ[i];\n \tif ( this.expectedEventDispatched( expectedEvent ) == false )\n \t\treturn false;\n }\n return true;\n }", "isPreceding(node) {\n var nodePos, thisPos;\n nodePos = this.treePosition(node);\n thisPos = this.treePosition(this);\n if (nodePos === -1 || thisPos === -1) {\n return false;\n } else {\n return nodePos < thisPos;\n }\n }", "function skipAhead(event) {\n var skipTo = event.target.dataset.seek\n ? event.target.dataset.seek\n : event.target.value;\n moveTo(skipTo);\n }", "prependToGameState(tileArr){\n let canPrepend = this.canPrepend(tileArr);\n if(canPrepend)\n {\n this.gameState.unshift(tileArr);\n }\n \n return canPrepend;\n }", "beforeChangeSearchKey(event) {\n let now = Date.now();\n let diffTime = this.lastChangeKey ? (now - this.lastChangeKey.timeStamp) : -1;\n this.lastChangeKey = {\n key: event.key,\n timeStamp: now\n };\n let is_scan_barcode = false;\n if (\n diffTime > 0 &&\n diffTime < SearchConstant.MAX_DIFF_TIME_WITH_SCAN_BARCODE &&\n this.lastChangeKey.key === SearchConstant.ENTER_KEY\n ) {\n is_scan_barcode = true;\n }\n this.is_scan_barcode = is_scan_barcode;\n this.setState({search_key: event.target.value});\n if (event.target.value) {\n this.setState({is_searching: true});\n this.searchItem(event.target.value);\n } else {\n\n }\n }", "handleInput() {\n this.calculateInputOutput(true);\n }", "function processPreState() {\n oresult.bpre = true;\n bok = true;\n sstate = '';\n }", "checkGameStart(event) {\n\t\tif (this.props.finalizeStartButton !== 'Ready!' && this.props.finalizeEndButton !== 'Ready!') {\n\t\t\talert('You must select and ready both start and end movies')\n\t\t\tevent.preventDefault();\n\t\t} else if (this.props.finalizeStartButton !== 'Ready!') {\n\t\t\talert('You must select and ready a start movie')\n\t\t\tevent.preventDefault();\n\t\t} else if (this.props.finalizeEndButton !== 'Ready!') {\n\t\t\talert('You must select and ready an end movie')\n\t\t\tevent.preventDefault();\n\t\t}\n\t}", "function IsBeginSaveEvent( actionDescriptor ) {\n\tvar usingStartSave = false;\n\tif ( undefined != actionDescriptor ) {\n\t\tif ( \"ActionDescriptor\" == actionDescriptor.typename ) {\n\t\t\tvar keySaveStage = stringIDToTypeID( \"saveStage\" );\n\t\t\tif ( actionDescriptor.hasKey( keySaveStage ) ) {\n\t\t\t\tvar typeSaveStage = actionDescriptor.getEnumerationType( keySaveStage );\n var typeSaveStageType = stringIDToTypeID( \"saveStageType\" );\n var enumSaveStage = actionDescriptor.getEnumerationValue( keySaveStage );\n var enumSaveStageBegin = stringIDToTypeID( \"saveBegin\" );\n usingStartSave = enumSaveStage == enumSaveStageBegin && typeSaveStage == typeSaveStageType;\n\t\t\t}\n\t\t}\n\t}\n\treturn usingStartSave;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
override the rotation for the editor(w,a,s,d)
function calibrateMovementEditor() { if(Input.GetKey("w")){ RotateUpDown(1.5); } if(Input.GetKey("s")){ RotateUpDown(-1.5); } if(Input.GetKey("a")){ RotateRightLeft(1.5); } if(Input.GetKey("d")){ RotateRightLeft(-1.5); } }
[ "setRotations() {\n this.r3a1_exitDoor.angle = 270;\n }", "startRotation() {\n this._options.rotation.enable = true;\n }", "function rotationLeft() {\n var deg = 36;\n rotation = rotation - deg;\n //wheel.style.transform = rotate(\"rotation\" - \"deg\")\n wheel.style.transform =`rotate(${rotation}deg)`;\n}", "rotate() {\r\n //each piece has a different center of rotation uhoh, see image for reference\r\n //https://vignette.wikia.nocookie.net/tetrisconcept/images/3/3d/SRS-pieces.png/revision/latest?cb=20060626173148\r\n for (let c in this.coords) {\r\n this.coords[c][0] += this.rotationIncrements[this.rotationIndex][c][0]\r\n this.coords[c][1] += this.rotationIncrements[this.rotationIndex][c][1]\r\n }\r\n this.rotationIndex = (this.rotationIndex + 1) % 4\r\n }", "function onSliderRotationPlanet(slider) {\r\n\tangle[0] = parseFloat(slider.value);\r\n\tchanged=true; //Marco que hubo un cambio, lo cual habilita el reset\r\n\tupdateTextInput(1,slider.value);//Actualizo el valor del campo de texto asociado al slider\r\n}", "rotate270() {\n const { x } = this;\n this.x = this.y;\n this.y = -x;\n }", "function faireTourner(){\n var positionInitial = maVoiture.style.transform; \n document.querySelector('.voiture').style.transform = positionInitial + 'rotate(90deg)';\n voitureRotate = !voitureRotate \n }", "stopRotation() {\n this._options.rotation.enable = false;\n }", "function rotateBoard(){\n ui.rotateBoard();\n}", "_updateInitialRotation() {\n this.arNodeRef.getTransformAsync().then((retDict)=>{\n let rotation = retDict.rotation;\n let absX = Math.abs(rotation[0]);\n let absZ = Math.abs(rotation[2]);\n \n let yRotation = (rotation[1]);\n \n // if the X and Z aren't 0, then adjust the y rotation.\n if (absX > 1 && absZ > 1) {\n yRotation = 180 - (yRotation);\n }\n this.setState({\n rotation : [0,yRotation,0],\n nodeIsVisible: true,\n });\n });\n }", "rotation(value) {\n if (typeof value !== 'number' || isNaN(Number(value)) || !Number.isFinite(value)) {\n return;\n }\n\n let finalDegreeRot = value.mod(360); // this should handle negative rotations automatically (ex: -90 MOD 360 = 270) and over-rotations (ex: 370 MOD 360 = 10)\n this.options.rotation = Math.floor(finalDegreeRot); // see my notes in the Number.mod() function for why I wrote a custom modulo operation instead of using \"%\"\n\n return this;\n }", "resetTranslationRotation() {\n _wl_object_reset_translation_rotation(this.objectId);\n }", "setCorrectRotation (raoad) {\r\n var pointBefore = this._lastRoad.children[0].children\r\n\r\n var SlopEndPosition2 = pointBefore[\r\n pointBefore.length - 1\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 1].position)\r\n var SlopEndPosition1 = pointBefore[\r\n pointBefore.length - 2\r\n ].parent.convertToWorldSpace(pointBefore[pointBefore.length - 2].position)\r\n\r\n var slopEndY = SlopEndPosition2.y - SlopEndPosition1.y\r\n var slopEndX = SlopEndPosition2.x - SlopEndPosition1.x\r\n\r\n var point = raoad.children[0].children\r\n var SlopStartPosition2 = point[1].parent.convertToWorldSpace(\r\n point[1].position\r\n )\r\n var SlopStartPosition1 = point[0].parent.convertToWorldSpace(\r\n point[0].position\r\n )\r\n\r\n var slopeStartY = SlopStartPosition2.y - SlopStartPosition1.y\r\n var slopeStartX = SlopStartPosition2.x - SlopStartPosition1.x\r\n\r\n var angleBefore = Math.atan2(slopEndX, slopEndY)\r\n var angleStart = Math.atan2(slopeStartX, slopeStartY)\r\n\r\n raoad.rotation = cc.radiansToDegrees(angleBefore - angleStart)\r\n }", "handleRotateClick() {\n this.player.setSetUpRotate(!this.player.getSetUpRotate());\n }", "rotate(axis, angle) {\n var state = this.cam.state;\n if(angle) {\n var new_rotation = Rotation.create({axis:axis, angle:angle});\n Rotation.applyToRotation(state.rotation, new_rotation, state.rotation);\n }\n }", "rotarDerecha(mueble){\n mueble.rotation.y -= this.ANGULO;\n\n var res = this.colisionaParedes(mueble);\n if(res[0]){\n mueble.rotation.y += this.ANGULO;\n }\n else{\n mueble.position.y = res[1];\n }\n }", "function changeAlign(align) {\n gMeme.currText.align = align;\n gMeme.currText.x = gFontlocation[align].x\n}", "function keyTyped() {\n textRotation = !textRotation;\n}", "function rotate(){\r\n unDraw();\r\n currentRotation++;\r\n if(currentRotation === current.length){ // so it doesn't go higher that array\r\n currentRotation = 0;\r\n }\r\n current = piecesArray[random][currentRotation];\r\n draw();\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is for reading the GP data from local JSON file and insert it to MongoDB.
function insertData(){ var obj = JSON.parse(fs.readFileSync('C:\\Users\\Tiankun\\Downloads\\doctors2.json', 'utf8')); mdb.collection('gp').insertMany(obj); }
[ "function uploadLocalJsonCollectionToDB(client, dataBaseName, collectionName) {\n\t\t\n\t\t//////////////////////////// Read json by nodejs fs (start) ////////////////////\n\t\t// var jsonObject;\n\t\tfs.readFile('db/sportsDB.json', 'utf8', function (err, data) {\n\t\tif (err) {\n\t\t\tconsole.error(\"Unable to read the json file\");\n\t\t\tthrow err;\n\t\t}\n\t\tconsole.error(\"Read the local json successfully\");\n\t\tconst jsonObject = JSON.parse(data);\n\t\tconsole.log(jsonObject);\n\t\tcreateMultipleDocuments(client, dataBaseName, collectionName, [jsonObject]);\n\t\t});\n\t\t//////////////////////////// Read json by nodejs fs (end) //////////////////////\n\t}", "function SaveToDB()\r\n{\r\n fs.readFile('listings.json', 'utf8', function (err, data)\r\n {\r\n let listings = JSON.parse(data).entries;\r\n listings.forEach(listing =>\r\n {\r\n let tmpVar = new Listing(listing).save(function (err, listing)\r\n {\r\n if (err)\r\n {\r\n console.log(err);\r\n }\r\n itr++;\r\n console.log(\"Saved listing item \" + itr);\r\n });\r\n });\r\n }\r\n );\r\n}", "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 }", "function readGeoJSON(dataPath, collection, next) {\n fs.readFile(dataPath, 'utf-8', function(err, data) {\n //console.log(\"I'm changing the database\");\n if(err) return next(err);\n var newData = JSON.parse(data);\n var type = newData.type;\n var points = 0;\n if (type === \"FeatureCollection\") {\n var features = newData.features;\n //TODO: check these error codes again\n if (features === null) { throw(err); }\n var length = features.length;\n for (var i = 0; i < length; i++) {\n var ft = features[i];\n var geoType = ft.geometry.type;\n if (geoType === \"Polygon\") { \n getDoc(dataPath, collection, ft, null, null, null, \n function(err, id) {\n if (err) return next(err);\n next(null);\n });\n }\n if (geoType === \"MultiPolygon\") {\n var cLength = ft.geometry.coordinates.length;\n var forRes = new Array(cLength);\n getDoc(dataPath, collection, ft, cLength, true, false, \n function(err, id) {\n if (err) return next(err);\n //console.log(id);\n for (var j = 0; j < cLength; j++) {\n getDoc(dataPath, collection, ft, j, false, id, \n function(err, id) {\n points++;\n if (points === cLength) next(null);\n });\n }\n });\n }\n if (geoType === \"Point\") {\n getCity(dataPath, collection, ft, function(err, id) {\n if (err) return next(err);\n //console.log(\"updated city\");\n points++;\n if (points === length) {\n next(null);\n //console.log(\"response should have been sent\");\n }\n });\n }\n } // for (var i = 0; i < length; i++) {}\n } // if (type === \"FeatureCollection\") {\n // if an error occurs here, please notify mark92fillmore\n else next(404);\n }); // fs.readFile(dataPath, 'utf-8', function(err, data) {\n}", "function loadCountries(){\n\tvar currline = [];\n\tfs.readFile('./countryList.txt', 'utf-8', function(err, data){\n\t\tif (err) throw err;\n\t\t\n\t\tvar lines = data.toString().trim().split('\\n');\n\t\t\n\t\tfor (var i = 0; i < lines.length; i++){\n\t\t\tcurrline = lines[i].split(',');\n\t\t database.create({ code: currline[0], country: currline[1]}, function(err, doc){\n\t\t \tif(!err){\n \t\t\t\tconsole.log(doc.toString());\n \t\t\t} else {\n \t\t\t\tconsole.log(\"Database error: \" + err);\n \t\t\t}\n \t\t});\n\t\t}\n\t});\n}", "load() {\n let database = fs.readFileSync(__dirname + '/database.json', 'utf8');\n return JSON.parse(database);\n }", "function loadBatches(){\n let batch_data = fs.readFileSync('./batches.txt');\n batches = JSON.parse(batch_data);\n //console.log(batches);\n}", "function handleFile(err, data){\n if(err){\n console.log(err);\n }\n\n obj = JSON.parse(data);\n console.log(\"JSON FILE: \"+ obj.main.temp);\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 readStartingData(){\n readUser = JSON.parse(fs.readFileSync('data/user.json'));\n listDoc = JSON.parse(fs.readFileSync('data/documents.json'));\n}", "function appendJSON(obj) {\n\n // Read in a JSON file\n var JSONfile = fs.readFileSync('Appointments.json', 'utf8');\n\n // Parse the JSON file in order to be able to edit it\n var JSONparsed = JSON.parse(JSONfile);\n\n //Geolocation\n //var address = obj.where.toString().split(' ').join('+');\n\n googleMapsClient.geocode({\n address: obj.where\n }, function(err, response) {\n if (!err) {\n //Getting the longitude and latitude object and add it to the object\n obj.coords = response.json.results[0].geometry.location;\n obj.who = parseInt(obj.who);\n obj.id = JSONparsed.appointment.length+1;\n // Add a new record into country array within the JSON file\n JSONparsed.appointment.push(obj);\n\n // Beautify the resulting JSON file\n var JSONformated = JSON.stringify(JSONparsed, null, 4);\n\n // Write the updated JSON file back to the system\n fs.writeFileSync('Appointments.json', JSONformated);\n\n // Convert the updated JSON file to XML\n var XMLformated = js2xmlparser.parse(\"appointments\", JSON.parse(JSONformated));\n\n // Write the resulting XML back to the system\n fs.writeFileSync('Appointments.xml', XMLformated);\n\n } else {console.log('Error:'+err)}\n return res.redirect('/');\n });\n }", "function readProiectJson() \n{\n return JSON.parse(fs.readFileSync(\"proiect.json\"))[\"DetaliiContact\"];\n}", "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 }", "function importiereJsonObjekt(JsonObjekt) {\n\tvar Doc;\n\tDoc = '{ \"docs\":' + JSON.stringify(JsonObjekt) + '}';\n\t$.ajax({\n\t\ttype: \"post\",\n\t\turl: \"http://127.0.0.1:5984/artendb/_bulk_docs\",\n\t\tcontentType: \"application/json\",\n\t\tdata: Doc\n\t});\n}", "_handleEventGeodata(event) {\n //Handle text/plain as WKT: DragAndDrop and CopyPaste\n {\n let eventData = event.clipboardData !== undefined ? event.clipboardData : event.dataTransfer;\n if (eventData.types.indexOf(\"text/plain\") >= 0) {\n console.log(\"ImportHandler: got text. Trying to interpret as WKT.\");\n\n //let content = event.dataTransfer.getData(\"text/plain\");\n let content = eventData.getData(\"text/plain\");\n console.log(content);\n\n let features = TheKarteHelperDataImport_loadGeoFromText(\"wkt\", content);\n this._theKarte.layerActive_addFeatures(features);\n }\n }\n\n //Handle files by extension\n if (event.dataTransfer !== undefined && event.dataTransfer.types.indexOf(\"Files\") >= 0) {\n const files = event.dataTransfer.files;\n\n //Check how multiple files are handled.\n for (let i = 0; i < files.length; i++) {\n const fileSuffix = files[i].name.split('.').pop();\n\n console.log(\"ImportHandler: got file (\" + files[i].name + \").\");\n\n const reader = new FileReader();\n reader.onload = function() {\n let features = TheKarteHelperDataImport_loadGeoFromText(fileSuffix, reader.result);\n\n console.log(\"ImportHandler: Adding to current layer.\");\n\n this._theKarte.layerActive_addFeatures(features);\n }.bind(this);\n reader.onerror = function() {\n console.error(\"ImportHandler: error reading (\" + files[i].name + \"): \" + reader.error);\n };\n reader.readAsText(files[i]);\n }\n }\n }", "function parseAudioJson() {\n fs.readFile(audioJson, 'utf8', function (err, data) {\n if (err) throw err;\n let newJson = JSON.parse(data);\n if (audio) {\n compareJson(audio, newJson);\n }\n audio = newJson;\n });\n}", "function uploadJSON() {\r\n\r\n}", "readStudentData(){\r\n let url=\"https://maeyler.github.io/JS/data/Students.txt\";\r\n fetch(url)\r\n .then(res => res.text())\r\n .then(res => this.addStudentsToMap(res,this.students));\r\n }", "function LoadJson(){}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Walk the input `node` and statically evaluate if it's truthy. Returning `true` when we're sure that the expression will evaluate to a truthy value, `false` if we're sure that it will evaluate to a falsy value and `undefined` if we aren't sure. Because of this please do not rely on coercion when using this method and check with === if it's false. For example do: if (t.evaluateTruthy(node) === false) falsyLogic(); AND NOT if (!t.evaluateTruthy(node)) falsyLogic();
function evaluateTruthy() { var res = this.evaluate(); if (res.confident) return !!res.value; }
[ "function assertIsTruthy(a){\n return a_is_truthy(a);\n }", "function falsy_QMRK_(a) {\n return ((a === null) || (a === false));\n}", "function TrueNode() {\n}", "isBool(expression) {\n doCheck(\n this.typesAreEquivalent(expression.type, BoolType),\n \"Not a boolean\"\n );\n }", "function isEmptyNode(node) {\n if (node && node.textContent) {\n return false;\n }\n if (!node ||\n !node.childCount ||\n (node.childCount === 1 && isEmptyParagraph(node.firstChild))) {\n return true;\n }\n var block = [];\n var nonBlock = [];\n node.forEach(function (child) {\n child.isInline ? nonBlock.push(child) : block.push(child);\n });\n return (!nonBlock.length &&\n !block.filter(function (childNode) {\n return (!!childNode.childCount &&\n !(childNode.childCount === 1 && isEmptyParagraph(childNode.firstChild))) ||\n childNode.isAtom;\n }).length);\n}", "function checkExpressionAnalysisMode(node) {\n return t.ifStatement(markMemberToNotBeRewritten(t.memberExpression(nonRewritableIdentifier('self'), nonRewritableIdentifier('__expressionAnalysisMode__'))), t.expressionStatement(node\n // ,t.unaryExpression(\"void\", t.numericLiteral(0), true)\n ));\n }", "visitUnary_logical_expression(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_BooleanExpr(){\n\t\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_BooleanExpr()\" + '\\n';\n\t\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 (tempDesc == '('){\n\t\tmatchSpecChars('(',parseCounter);\n\t\t\n\t\tCSTREE.addNode('BooleanExpr', 'branch');\n\t\t\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t\t\n\t\tparse_Expr();\n\t\n\t\t\n\t\tparse_boolop();\n\t\n\t\t\n\t\tparse_Expr();\n\t\n\t\tmatchSpecChars(')',parseCounter);\n\t\tparseCounter = parseCounter + 1;\n\t\t\n\t}\n\telse{\n\t\tparse_boolval();\n\t\n\t}\n\n\t\n}", "function isNodeEntering(state, interpreter) {\n var updateNeeded = false;\n\n function isSupportedFunctionCall(state) {\n // won't show stepping into and out of member methods (e.g array.slice)\n // because these are built-ins with black-boxed code.\n // User functions may also be object properties, but I am not considering\n // this for this exercise.\n return state.node.type === 'CallExpression' && !state.doneCallee_ && !(state.node.callee && state.node.callee.type === 'MemberExpression');\n }\n\n if (isSupportedFunctionCall(state)) {\n\n var enterNode = {\n name: state.node.callee.name || state.node.callee.id.name,\n parentNode: (0, _lodash.last)(scopeChain) || null,\n paramNames: [],\n interpreterComputedArgs: [],\n // variable information and warnings\n // populated once the interpreter\n // generates scope\n variablesDeclaredInScope: null,\n warningsInScope: new Set(),\n type: 'function',\n status: 'normal'\n };\n\n // set up string tokens for display text\n enterNode.recursion = enterNode.parentNode && enterNode.name === enterNode.parentNode.name;\n enterNode.displayTokens = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].getInitialDisplayTokens(enterNode.name, state.node.arguments, enterNode.parentNode, interpreter);\n enterNode.displayName = _DisplayTextHandlerStringTokenizerStringTokenizerJs2['default'].joinAndFormatDisplayTokens(enterNode.displayTokens, enterNode.recursion);\n\n // the root node carries through information to d3 about overall progress.\n if (nodes.length === 0) {\n enterNode.type = 'root';\n enterNode.errorCount = 0;\n enterNode.status = ''; //d3 manually assigns color to rootNode\n rootNode = enterNode;\n }\n\n // add nodes and links to d3\n nodes.push(enterNode);\n var callLink = getCallLink(enterNode.parentNode, enterNode, 'calling');\n if (callLink) {\n links.push(callLink);\n }\n\n /* Tracking by scope reference allows for\n displaying nested functions and recursion */\n scopeChain.push(enterNode);\n updateNeeded = true;\n }\n return updateNeeded;\n }", "function isEmpty(tree) {\n\treturn tree == null;\n}", "function evaluate_if_statement(stmt,env) {\n if (is_true(evaluate(if_predicate(stmt),env))) {\n return evaluate(if_consequent(stmt),env);\n } else {\n return evaluate(if_alternative(stmt),env);\n }\n}", "static bool(v) { return new Typed(_gaurd, \"bool\", !!v); }", "_add_boolean_expression_subtree_to_ast(boolean_expression_node, parent_var_type) {\n this.verbose[this.verbose.length - 1].push(new NightingaleCompiler.OutputConsoleMessage(SEMANTIC_ANALYSIS, INFO, `Adding ${boolean_expression_node.name} subtree to abstract syntax tree.`) // OutputConsoleMessage\n ); // this.verbose[this.verbose.length - 1].push\n let open_parenthesis_or_boolean_value_node = boolean_expression_node.children_nodes[0];\n // Enforce type matching in boolean expressions\n let valid_type = false;\n // If, no parent type was given to enforce type matching...\n if (parent_var_type === UNDEFINED) {\n // Enforce type matching using the current type from now on.\n parent_var_type = BOOLEAN;\n } // if\n // Else, there is a parent type to enforce type matching with.\n else {\n valid_type = !this.check_type(parent_var_type, open_parenthesis_or_boolean_value_node, BOOLEAN);\n } // else\n // Boolean expression ::== ( Expr BoolOp Expr )\n if (boolean_expression_node.children_nodes.length > 1) {\n // Ignore Symbol Open Argument [(] and Symbol Close Argument [)]\n // let open_parenthisis_node = boolean_expression_node.children_nodes[0];\n // let open_parenthisis_node = boolean_expression_node.children_nodes[4];\n let boolean_operator_value_node = boolean_expression_node.children_nodes[2].children_nodes[0];\n let left_expression_node = boolean_expression_node.children_nodes[1];\n let right_expression_node = boolean_expression_node.children_nodes[3];\n // FIRST Add the Boolean Operator\n this._current_ast.add_node(boolean_operator_value_node.name, NODE_TYPE_BRANCH, valid_type, false, boolean_operator_value_node.getToken()); // this._current_ast.add_node\n // Start by recursively evaluating the left side...\n // Note the type as it will be used to enforce type matching with the right side.\n let left_expression_type = this._add_expression_subtree(left_expression_node, UNDEFINED);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (left_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the left side of the \n // boolean expression and climb if it's an expression and not some value.\n if (left_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n // Then recursively deal with the right side...\n // To enforce type matching, use the left sides type as the parent type.\n let right_expression_type = this._add_expression_subtree(right_expression_node, left_expression_type);\n // If it was an integer expression climb back up to the parent boolean expression node\n if (right_expression_node.children_nodes[0].name === NODE_NAME_INT_EXPRESSION) {\n while ((this._current_ast.current_node !== undefined || this._current_ast.current_node !== null)\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n && this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n if (this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_EQUALS\n || this._current_ast.current_node.name !== AST_NODE_NAME_BOOLEAN_NOT_EQUALS) {\n this._current_ast.climb_one_level();\n } // if\n } // while\n } // if\n // Ensures the correct order of nested operators in the ast.\n //\n // Look ahead in the tree on the right side of the \n // boolean expression and climb if it's an expression and not some value.\n if (right_expression_node.children_nodes[0].children_nodes[0].name == \"(\") {\n this._climb_ast_one_level();\n } // if\n } // if\n // Boolean expression is: boolval\n else if (boolean_expression_node.children_nodes.length === 1) {\n this._current_ast.add_node(open_parenthesis_or_boolean_value_node.children_nodes[0].name, NODE_TYPE_LEAF, valid_type, false);\n } // else if\n // Boolean expression is neither: ( Expr BoolOp Expr ) NOR boolval...\n else {\n // Given a valid parse tree, this should never happen...\n throw Error(\"You messed up Parse: Boolean expression has no children, or negative children.\");\n } // else \n }", "function short_circuiting_predicate(predicate, args) {\n var previous = args[0];\n for(var i = 1; i < args.length; i++) {\n if(!predicate(previous, args[i])) {\n return false; // short circuit\n }\n }\n return true; // no short circuit, all true\n }", "function helper(node, runningSum, targetSum){\n if (node === null) {\n return false;\n }\n // let currentSum = runningSum + node.val;\n console.log(node.val, runningSum + node.val)\n if(node.right===null && node.left===null && (runningSum + node.val) ==targetSum){\n console.log('true', runningSum)\n return true;\n }\n return (helper(node.left, (runningSum + node.val), targetSum) || helper(node.right, (runningSum + node.val), targetSum));\n}", "function xPathEval(xpath){\r\n rtn = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);\r\n if (!rtn) debug(d_hi, \"Evaluation of xpath '\" + xpath + \"' failed!\");\r\n return rtn;\r\n}", "function findTruthy(array, { start, step }) {\n for (let i = start; i > 0 && i < array.length; i += step) {\n const item = array[i];\n if (!!item) return item;\n }\n}", "function evaluate(stmt, env) {\n if (is_self_evaluating(stmt)) {\n return stmt;\n } else if (is_empty_list_expression(stmt)) {\n return evaluate_empty_list_expression(stmt);\n } else if (is_variable(stmt)) {\n return lookup_variable_value(variable_name(stmt), \n env);\n } else if (is_assignment(stmt)) {\n return evaluate_assignment(stmt,env);\n } else if (is_var_definition(stmt)) {\n return evaluate_var_definition(stmt, env);\n } else if (is_if_statement(stmt)) {\n return evaluate_if_statement(stmt, env);\n } else if (is_while_statement(stmt)) {\n return evaluate_while_statement(stmt, env);\n } else if (is_for_statement(stmt)) {\n return evaluate_for_statement(stmt, env);\n } else if (is_array_literal(stmt)) {\n return evaluate_array_literal(stmt, env);\n } else if (is_sequence(stmt)) {\n return evaluate_sequence(stmt, env);\n } else if (is_boolean_op(stmt)) {\n return evaluate_boolean_op(stmt, env);\n } else if (is_ternary(stmt)) {\n return evaluate_ternary(stmt, env);\n } else if (is_function_definition(stmt)) {\n return evaluate_function_definition(stmt, env);\n } else if (is_application(stmt)) {\n return apply(evaluate(operator(stmt), env),\n list_of_values(operands(stmt), \n env));\n } else if (is_return_statement(stmt)) {\n return evaluate_return_statement(stmt, env); \n // object-oriented programming\n } else if (is_object_literal(stmt)) {\n return evaluate_object_literal(stmt, env);\n } else if (is_property_access(stmt)) {\n return evaluate_property_access(stmt, env);\n } else if (is_property_assignment(stmt)) {\n return evaluate_property_assignment(stmt, env);\n } else if (is_object_method_application(stmt)) {\n return evaluate_object_method_application(stmt, \n env);\n } else if (is_new_construction(stmt)) {\n return evaluate_new_construction(stmt, env);\n } else {\n error(\"Unknown expression type - - evaluate: \" + \n stmt.tag);\n }\n}", "function isValidFunctionExpression(node) {\n if (node && node.type === 'FunctionExpression' && node.body) {\n return true;\n }\n return false;\n}", "function isEmptyStmt(expr) {\r\n\r\n // for a if/elseif or a foreach statement, if only the root expression\r\n // is present without any children, then it is treated as an \r\n // empty stmt. Note: Forever and Else don't need children.\r\n //\r\n if ((expr.isIf() || expr.isElseIf() || expr.isForeach()) &&\r\n (!expr.exprArr || !expr.exprArr.length)) {\r\n return true;\r\n }\r\n\r\n return false;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates the vine array with chosen vines below.
function addVine(vineSentence, vineAnswer, vinePossibleAnswers, vinePhoto, vineGif) { var vineObject = { sentence: "", answer: "", possibleAnswers: [], photo: "", gif: ""}; vineObject.sentence = vineSentence; vineObject.answer = vineAnswer; vineObject.possibleAnswers = vinePossibleAnswers; vineObject.photo = vinePhoto; vineObject.gif = vineGif; vinesArray.push(vineObject); }
[ "function InitMvvLva() {\n\tvar Attacker;\n\tvar Victim;\n\t\n\tfor(Attacker = PIECES.wP; Attacker <= PIECES.bK; ++Attacker) {\n\t\tfor(Victim = PIECES.wP; Victim <= PIECES.bK; ++Victim) {\n\t\t\tMvvLvaScores[Victim * 14 + Attacker] = MvvLvaValue[Victim] + 6 - (MvvLvaValue[Attacker]/100); // Gives a higher score the lower the attackers value is\n\t\t}\n\t}\n}", "function getVassals(){\r\n g_vassals = [];\r\n\r\n var v = GM_getValue(vassal_key, '').split(\"||\");\r\n\r\n if (v=='') return;\r\n \r\n for (var i=0; i < v.length; i++){\r\n\tg_vassals[i] = makeVassal(v[i]);\r\n\tg_paid[v[i]] = [];\r\n }\r\n}", "function randomizeVel() {\n\n for (i = 0; i < verticies.length; i++) {\n var xVel = Math.random();\n //Binary coin flip\n var xSign = Math.floor(Math.random() * 10) % 2;\n if (xSign) { xVel = xVel * -1; }\n\n var yVel = Math.random();\n //Binary coin flip\n var ySign = Math.floor(Math.random() * 10) % 2;\n if (ySign) { yVel = yVel * -1; }\n\n velocities.push([xVel, yVel]);\n }\n}", "_renderVitamins () {\n this._emptyContainer();\n this.vitamins.forEach(vit => this._container.appendChild(vit.element));\n console.log(Texts.RENDERING_VITAMINS);\n }", "splitV(vk) {\n let r = this.v_degree;\n // Count number of times vk already occurs in the v-knot vector\n // We have to add vk until it occurs r-times in the v-knot vector,\n // where r is the v-degree of the curve\n // In case there are knots in the v-knot vector that are equal to vk\n // within the error tolerance, then we replace them with vk\n // Such v-knot vector is named safe_vknots\n let safe_vknots = [];\n for (let i = 0; i < this.v_knots.data.length; i++) {\n if (common_1.isequal(this.v_knots.getN(i), vk)) {\n safe_vknots.push(vk);\n r--;\n }\n else {\n safe_vknots.push(this.v_knots.getN(i));\n }\n }\n let add_vknots = [];\n for (let i = 0; i < r; i++) {\n add_vknots.push(vk);\n }\n let copy = this.clone();\n copy.setVKnots(common_1.arr(safe_vknots));\n copy.refineKnotsV(add_vknots);\n // Find the index of the first vk knot in the new knot vector\n let ibreak = -1;\n for (let i = 0; i < copy.v_knots.data.length; i++) {\n if (common_1.isequal(copy.v_knots.getN(i), vk)) {\n ibreak = i;\n break;\n }\n }\n console.assert(ibreak >= 0);\n // The V-control points of the surface where the split will happen are\n // at the index *ibreak-1* in the V-direction of control points array\n // The left surface will have *ibreak* v-control point columns\n // The right surface will have *N-ibreak+1* v-control point columns \n // (where N is the number of control points rows in V direction\n // in the original surface)\n // The control point at *ibreak-1* will be repeated in left and right\n // surfaces. It will be the last v-control point of the left surface\n // and first v-control point of the right surface\n let lcpoints = copy.cpoints.getA(':', ':' + ibreak);\n let rcpoints = copy.cpoints.getA(':', (ibreak - 1) + ':');\n let l_vknots = copy.v_knots.getA(':' + ibreak).toArray();\n // Scale the internal v knot values to fit into the left surface's 0-1\n // v parameter range\n for (let i = copy.v_degree + 1; i < l_vknots.length; i++) {\n l_vknots[i] = l_vknots[i] / vk;\n }\n // Append clamped knots to the left curve at 1\n for (let i = 0; i <= copy.v_degree; i++) {\n l_vknots.push(1);\n }\n let r_vknots = copy.v_knots.getA((ibreak + copy.v_degree) + ':').toArray();\n // Scale the internal knot values to fit into the right surface's\n // 0-1 v parameter range\n for (let i = 0; i < r_vknots.length - copy.v_degree; i++) {\n r_vknots[i] = (r_vknots[i] - vk) / (1 - vk);\n }\n // Prepend clamped knots to the right curve at 0\n for (let i = 0; i <= copy.v_degree; i++) {\n r_vknots.unshift(0);\n }\n // TODO : Rational\n let lsurf = new BSplineSurface(copy.u_degree, copy.v_degree, copy.u_knots, l_vknots, lcpoints);\n let rsurf = new BSplineSurface(copy.u_degree, copy.v_degree, copy.u_knots, r_vknots, rcpoints);\n return [lsurf, rsurf];\n }", "buildInvadersRow1() {\n\t for (let x = 150; x < 551; x += 50) {\n\t this.invaderRow1.push(new Invaders(x, 40, this.invaderLevelSpeed, .05));\n\t }\n\t }", "function _loadVenders()\n {\n //instantiate variables local to function\n var tempData = []\n \n //loop through every file in the menus folder\n fs.readdir( menusFolder, function(err, files)\n {\n var pending = files.length\n \n //read each file\n files.map(function(file)\n {\n var filePath = menusFolder + file\n \n fs.readFile(filePath, 'utf8', function(err, data)\n {\n if(err)\n console.log(\"Failed to open menu: \"+ err)\n else\n {\n //push the loaded data onto tempData\n try { tempData.push(JSON.parse(data)) }\n catch(err)\n {\n console.log(\"Failed to parse menu '\"+ file + \"': \" + err)\n }\n }\n if(--pending <= 0)\n venderData = tempData\n }) \n }) \n \n })\n }", "function updateVerticies(count, size, fps) {\n\n //There are \"count\" many verticies each of dimension \"size\"\n //For each we update their position based on their velocity\n for (i = 0; i < count; i++) {\n for (j = 0; j < size; j++) {\n\n //The average velocity is .5\n //So if we update the a vertex position by ~.5/fps\n //the vertex will cross about half of the screen in one second\n //multiplying this update by 2/speed causes the vertex to cross \n //the screen in speed # of seconds \n //Note: We add 1 to fps in the case that fps approaches zero\n var newPosition = verticies[i][j] + ((2 / SPEED) * ((1 / (fps + 1)) * velocities[i][j]));\n \n //New position out of bounds => reverse velocity\n //Else update position as normal\n if (Math.abs(newPosition) >= 1) {\n velocities[i][j] = velocities[i][j] * -1;\n } else {\n verticies[i][j] = newPosition;\n }\n }\n }\n}", "function addBoxesToLineIds(id){\n var BoxesNumber = Number(Boxes);\n var BoxesArray = [];\n var someNumber = 0;\n if (id<BoxesNumber){\n /**\n * fill only Horizontal lines\n */\n for (var i=(id*BoxesNumber);i<(BoxesNumber+(id*BoxesNumber));i++){\n BoxesArray.push(GameBoxes[i]);\n }\n } else if ((id>=BoxesNumber)&&(id<BoxesNumber*2)){\n /**\n * fill only Vertical lines\n */\n for (var i=0;i<BoxesNumber;i++){\n someNumber = (i*BoxesNumber)+(id-BoxesNumber);\n BoxesArray.push(GameBoxes[someNumber]);\n }\n } else if (id==BoxesNumber*2) {\n for (var i=0;i<BoxesNumber;i++){\n someNumber = (BoxesNumber+1)*i;\n BoxesArray.push(GameBoxes[someNumber]);\n }\n } else {\n for (var i=0;i<BoxesNumber;i++){\n someNumber = (BoxesNumber-1)*(i+1);\n BoxesArray.push(GameBoxes[someNumber]);\n }\n }\n GameLines[id].boxesIds = BoxesArray;\n }", "get allMillennialVampires() {\n let vampires = [];\n if (this.yearConverted > 1980) {\n vampires.push(this);\n }\n for (let child of this.offspring) {\n vampires = vampires.concat(child.allMillennialVampires);\n }\n return vampires;\n }", "addVaccine() {\n let name = this.state.vaccineName\n if (name === \"\") return\n this.setState(prevState => ({\n vaccineName: \"\",\n vaccines: [...prevState.vaccines, {\n name,\n effectivity: 0.50\n }],\n }))\n }", "function makeCVNArray() {\n for (var i = 0; i < itemArray.length; i++) {\n clickedArray.push(itemArray[i].clicked);\n viewedArray.push(itemArray[i].viewed);\n nameArray.push(itemArray[i].title);\n }\n }", "function draw_travels() {\n removeLines();\n for (var i = 0, len = data.length; i < len; i++) {\n drawLine(data[i])\n }\n}", "addViking(viking) {\n this.vikingArmy.push(viking);\n }", "_calculateVoisins(nbCases = 10) {\n let currentGroupe = null;\n let totalCases = nbCases * 4;\n // Parcourt les fiches. On enregistre le groupe courant, quand changement, on defini le groupe precedent et calcule le suivant du precedent\n for (let i = 0; i < totalCases + 2; i++) {\n let axe = Math.floor(i / nbCases) % 4;\n let pos = i % totalCases - (axe * nbCases);\n let fiche = GestionFiche.get({\n axe: axe,\n pos: pos\n });\n if (fiche != null && fiche.groupe != null && fiche.isTerrain()) {\n if (currentGroupe == null) {\n // initialisation\n currentGroupe = fiche.groupe;\n }\n if (!currentGroupe.equals(fiche.groupe)) { // Changement de groupe\n fiche.groupe.groupePrecedent = currentGroupe;\n currentGroupe.groupeSuivant = fiche.groupe;\n currentGroupe = fiche.groupe;\n }\n }\n }\n }", "function addVeggies(runningPrice) {\n var veggiePrice = 0;\n var veggieCount = 0;\n var veggieText = \"\";\n var veggieOptions = document.getElementsByClassName('veggie');\n for (var i = 0; i < veggieOptions.length; i++) {\n if (veggieCount >= 1) {\n if (veggieOptions[i].checked) {\n veggieText += \"<p>\" + veggieOptions[i].value + \" +$1.00</p>\";\n veggieCount += 1;\n veggiePrice += 1;\n }\n } else {\n if (veggieOptions[i].checked) {\n veggieText += \"<p>\" + veggieOptions[i].value +\"</p>\";\n veggieCount += 1;\n }\n }\n }\n document.getElementById('selectedVeggies').innerHTML = veggieText;\n runningPrice += veggiePrice;\n updateRunning(runningPrice);\n}", "function boozePositions(){\n\tthis.boozeLocs = [];\n\t\t\n\tthis.boozeLocs.push(new booze(flight,75,50,50));\n\tthis.boozeLocs.push(new booze(pitcher,50,50,50));\n\tthis.boozeLocs.push(new booze(mug,50,50,50));\n\tthis.boozeLocs.push(new booze(flight,75,50,50));\n\tthis.boozeLocs.push(new booze(pitcher,50,50,50));\n\tthis.boozeLocs.push(new booze(mug,50,50,50));\n\tthis.boozeLocs.push(new booze(tequila,25,25,50));\n\tthis.boozeLocs.push(new booze(whiskey,25,30,50));\t\n}", "function addSegments() {\n for (let i = 0; i < newSegments; i++){\n // We're just taking the very last element of our snake and\n // duplicating that onto the end of our snake.\n snakeBody.push({ ...snakeBody[snakeBody.length - 1] })\n }\n // The snake needs to stop growing.\n newSegments = 0;\n}", "function fillStatPointsArray(){\n stat_points_per_level.push(0);\n for(var i=1;i<185;i++){\n stat_points_per_level.push(stat_points_per_level[i-1]+calcStatGain(i+1));\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Battery status for Android
function getBatteryStatusForAndroid() { var BatteryStatus = {}; var KonyMain = java.import("com.konylabs.android.KonyMain"); var Intent = java.import("android.content.Intent"); var IntentFilter = java.import("android.content.IntentFilter"); var BatteryManager = java.import("android.os.BatteryManager"); var context = KonyMain.getActivityContext(); var ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); var batteryStatusIntent = context.registerReceiver(null, ifilter); var BatteryLevel = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); BatteryStatus.BatteryLevel = BatteryLevel; var status = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); var isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; BatteryStatus.isCharging = isCharging; setValues(BatteryStatus); }
[ "function getBatteryStatusForIphone()\n{ \n var BatteryStatus = {};\n\n var UIDevice = objc.import(\"UIDevice\");\n\n var currentDevice = UIDevice.currentDevice();\n currentDevice.batteryMonitoringEnabled = true;\n\n var batteryLevel = currentDevice.batteryLevel;\n\n // BatteryStatus.BateryLevel=BateryLevel;\n var state = currentDevice.batteryState;\n batteryLevel = (batteryLevel * 100).toFixed(1);\n batteryLevel = Math.round(batteryLevel);\n BatteryStatus.BatteryLevel = batteryLevel;\n \n if (state==1) \n {\n BatteryStatus.isCharging = false;\n }\n else\n {\n BatteryStatus.isCharging = true;\n }\n\n setValues(BatteryStatus);\n}", "function getBatteryState() {\n var batteryLevel = Math.floor(battery.level * 10),\n batteryFill = document.getElementById(\"battery-fill\");\n\n batteryLevel = batteryLevel + 1;\n batteryFill.style.width = batteryLevel + \"%\";\n }", "function updateBatteryStatus(battery) {\n\n var batteryString = Math.round(battery.level * 100) + '%';\n\n // if we can display \"time to empty\"\n if (!battery.charging && (battery.dischargingTime !== Number.POSITIVE_INFINITY)) {\n batteryString += ' (' + formatTime(battery.dischargingTime) + ' until empty)';\n }\n\n // if we can display \"time to full\"\n else if (battery.charging && (battery.chargingTime !== 0) && (battery.chargingTime !== Number.POSITIVE_INFINITY)) {\n batteryString += ' (' + formatTime(battery.chargingTime) + ' until full)';\n\n }\n\n // update graphic etc\n document.querySelector('p').textContent = batteryString;\n document.querySelector('.batterylevel').style.transform = 'scaleY(' + battery.level + ')';\n var chargeSymbolOpacity = (battery.charging) ? 1 : 0;\n document.querySelector('.chargingsymbol').style.opacity = chargeSymbolOpacity;\n\n }", "handleCharging(battery) {\n //Calculate distance from this player to the firstaid kit\n let d3 = dist(this.x, this.y, battery.x, battery.y);\n //Check if the distance is less than their two radius(an overlap)\n if (d3 < this.radius + battery.radius) {\n this.batteryLevel += this.batteryGainPerEat * 5;\n this.batteryLevel = constrain(this.batteryLevel, 0, this.maxBatteryLevel);\n //Decrease battery's health by the same amount\n battery.health -= this.batteryGainPerEat * 5;\n }\n //Check if the battery died and reset it if so\n if (battery.health < 2) {\n chargeSound.play();\n battery.reset();\n }\n }", "function updateCounter(){\n\t//subtracts one from battery percentage \n\tbatteryPercentage -= 1;\n\t//changes text to match the new battery percentage \n\t\n\t\n}", "function lightStatus(brightness) {\n let result = brightness;\n\n if (brightness == 0) {\n result = \"off\";\n } else if (brightness > 0 && brightness < 200) {\n result = \"dimmed\";\n } else if (brightness >= 200) {\n result = \"on\";\n }\n\n return result;\n}", "deviceStatusOffline(device) {\n\t\t\tconst difference = this.getTimeDifference(device.updated_at);\n\n\t\t\treturn (difference > 60);\n\t\t}", "_getAVRVolumeStatus() {\n this._volumeCommand( \"volume_request\", \"\" );\n }", "function toggleStatus(ref) {\n\tvar flagRef = ref.child(\"STATUS\");\n\tflagRef.once(\"value\", function(snapshot) {\n\t\tif (snapshot.val().FLAG === \"ON\") {\n\t\t\tvar message = prompt(\"Custom status message (leave blank and press 'OK' for no custom status message):\", \"\");\n\t\t\tif (message != null) {\n\t\t\t\tif (message === \"\") {\n\t\t\t\t\tmessage = \"\";\n\t\t\t\t} else {\n\t\t\t\t\tvar date = new Date()\n\t\t\t\t\tstringDate = (date.getMonth() + 1) + \"/\" + date.getDate() + \"/\" + date.getFullYear() + \" \" + calculateETA(0)\n\t\t\t\t\tmessage = stringDate + \"\\n\" + message\n\t\t\t\t}\n\t\t\t\tflagRef.update({\"MESSAGE\" : message});\n\t\t\t\tflagRef.update({\"FLAG\" : \"OFF\"});\n\t\t\t} //else do not turn off\n\t\t} else {\n\t\t\tflagRef.update({\"FLAG\" : \"ON\"});\n\t\t\tflagRef.update({\"MESSAGE\" : \"\"});\n\t\t}\n\t});\n}", "deviceStatusWarning(device) {\n\t\t\tconst difference = this.getTimeDifference(device.updated_at);\n\n\t\t\treturn (difference <= 60);\n\t\t}", "function getBalanceStatus(balance) {\n if (balance < 0) {\n console.log('YOU ARE OVERDRAWN');\n } else if (balance < 20) {\n console.log('Warning! Your balance is almost 0!');\n } else {\n console.log('Normal')\n }\n}", "function constructStatus(ref, div) {\n\tvar statusText = document.createElement(\"b\");\n\tstatusText.innerHTML = \"<h3>Status: </h3>\";\n\tdiv.appendChild(statusText);\n\tvar status = document.createElement(\"BUTTON\");\n\tstatus.addEventListener(\"click\", function() { toggleStatus(ref); });\n\tdiv.appendChild(status);\n\tvar flagRef = ref.child(\"STATUS\");\n\tflagRef.on(\"value\", function(snapshot) {\n\t\tif(snapshot.val().FLAG === \"ON\") {\n\t\t\tstatus.innerHTML = \"ONLINE\";\n\t\t\tstatus.style.background = \"#008000\";\n\t\t} else {\n\t\t\tstatus.innerHTML = \"OFFLINE\";\n\t\t\tstatus.style.background = \"#ff0000\";\n\t\t}\n\t});\n}", "function getLightBulbStatusDisplayString(status) {\n let result = status;\n\n switch (status) {\n case \"on\":\n return \"The house is bright!\";\n break;\n case \"off\":\n return \"The house is dark\";\n break;\n case \"dimmed\":\n return \"The house is nice and dim\";\n break;\n case \"missing\":\n case \"offline\":\n return \"The house is dark and we can't find the lightbulb!\";\n break;\n case \"deleted\":\n return \"The lightbulb has been removed from the system\";\n break;\n case \"broken\":\n return \"The house is dark and we can't turn the light on!\";\n break;\n default:\n return \"Something is wrong!\";\n }\n\n return result;\n}", "function poll()\n{\n\tsetTimeout( function() {\n\t\t\t$.ajax(\"/alarmHeartbeat.html\").success( function(data) {\n\t\t\t\t\tconsole.log('HB:'+data);\n\t\t\t\t\tvar milliseconds = Math.floor( Date.now() / 1000 );\n\t\t\t\t\tconsole.log('MS:'+milliseconds);\n\t\t\t\t\tvar diff = milliseconds - data;\n\t\t\t\t\tconsole.log('DIFF:'+diff);\n\t\t\t\t\tif(diff < 20)\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.statusicon.src=\"images/on_sm.png\";\n\t\t\t\t\t\tconsole.log(\"running\");\n\t\t\t\t\t}else{\n\t\t\t\t\t\tdocument.statusicon.src=\"images/off_sm.png\";\n\t\t\t\t\t\tconsole.log(\"stalled\");\n\t\t\t\t\t}\n\t\t\t\t\tpoll();\n\t\t\t\t});\n\t\t\t}, 2000);\n}", "function statusCB(){\n var doorStatus = door.getStatus();\n // console.log(\"CB called: status: \" + doorStatus);\n io.sockets.emit('doorStatus', doorStatus);\n}", "function updateStatus() {\n\tchrome.extension.sendRequest(\n\t\t\t{type: \"status?\"}\n\t\t, function(response) {\n\t\t\t$(\"ws_status\").textContent=response.ws_status;\n\t\t\t$(\"pn_status\").textContent=response.pn_status;\n\t\t\t});\t\t\n}", "deviceStatusLive(device) {\n\t\t\tconst difference = this.getTimeDifference(device.updated_at);\n\n\t\t\treturn (difference <= 15);\n\t\t}", "formatForOnOff(status) {\n if (status === true) {\n return 'on'\n } else {\n return 'off'\n }\n }", "async sendLocalState () {\n if (!this.device) throw new Error('Controller not initialized. You must call .init() first!')\n\n if (this.state.interface === 'usb') \n {\n const report = new Uint8Array(16);\n\n // Report ID\n report[0] = 0x05;\n\n // Enable Rumble (0x01), Lightbar (0x02)\n report[1] = 0xF0 | 0x01 | 0x02;\n\n // Light rumble motor\n report[4] = this.rumble.light;\n // Heavy rumble motor\n report[5] = this.rumble.heavy;\n \n // Lightbar Red\n report[6] = this.lightbar.r\n // Lightbar Green\n report[7] = this.lightbar.g\n // Lightbar Blue\n report[8] = this.lightbar.b\n\n this.lastSentReport = report.buffer\n\n return this.device.sendReport(report[0], report.slice(1))\n } \n else if (this.state.interface === 'bt') {\n const report = new Uint16Array(79)\n const crcBytes = new Uint8Array(4)\n const crcDv = new DataView(crcBytes.buffer)\n\n // Header\n report[0] = 0xA2\n // Report ID\n report[1] = 0x11\n\n // Poll Rate\n report[2] = 0x80\n // Enable rumble and lights\n report[4] = 0xFF\n\n // Light rumble motor\n report[7] = this.rumble.light\n // Heavy rumble motor\n report[8] = this.rumble.heavy\n\n // Lightbar Red\n report[9] = this.lightbar.r\n // Lightbar Green\n report[10] = this.lightbar.g\n // Lightbar Blue\n report[11] = this.lightbar.b\n\n crcDv.setUint32(0, this.crc32(new String(report.slice(0, 75))))\n report[75] = crcBytes[3]\n report[76] = crcBytes[2]\n report[77] = crcBytes[1]\n report[78] = crcBytes[0]\n \n this.lastSentReport = report.buffer\n\n return this.device.sendReport(report[1], report.slice(2))\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
WRITE A NEW TWITTER NAME AND HANDLE
function writeTwitter(nam,handl){ // takes twitter name from link area box and writes it // check for blanks if ((nam=="") || (handl=="")){ alert("Real name and Twitter handle are both required. Quitting."); return } // check for dupes var i; var found = -1; for (i=0; i < tweeters_anchors.length; i++){ if (tweeters_anchors[i].toUpperCase() == nam.toUpperCase()){ found = i; } } if (found > -1) { // if name already there, then quit return } // not already there // add to array tweeters_anchors.push(nam); tweeters_tweetnames.push(handl); // save the twitter $.post('writetwitter.php', { newline: "\n" + nam + "|" + handl, async: false, success: function(){ alert('Success updating link file!'); }, error: function(){ alert('Error writing link file'); } }) }
[ "function createTweet(input) {\n\tif (!input.quoteAuthor.length) { //czyli jeśli autor cytatu jest pusty, to wejdziemy do treści warunku\n\t\tinput.quoteAuthor = \"Unknown author\";\n\t}\n\tvar tweetText = \"Quote of the day - \" + input.quoteText + \" Author: \" + input.quoteAuthor;\n\tif (tweetText.length > 140) {\n\tgetQuote();\n\t} else {\n\t\tvar tweet = tweetLink + encodeURIComponent(tweetText); // link do generowania i sam tekst tweeta\n\t\t$('.quote').text(input.quoteText); // tu wyświetlamy tresc\n\t\t$('.author').text(\"Author: \" + input.quoteAuthor); // tu autora\n\t\t$('.tweet').attr('href', tweet); // wybieramy elem z klasą tweet i modyfikujemy za atrybutu na URL tweeta, ktory jest w zmiennej tweet\n\t}\n}", "function saveName() {\n\tlocalStorage.setItem('receivedName', userName)\n}", "function respondName() {\r\n let nameResponse = document.createElement('p');\r\n nameResponse.textContent = `It's a pleasure to meet you,\r\n ${capitalise(firstName.value)}. Welcome to my little app experiment.`;\r\n nameElement.after(nameResponse);\r\n }", "function getTwitterTweets(screen_name) {\n socket.emit('user_tweets', { screen_name: screen_name });\n }", "function changeLocalUsername(name) {\n if(name) {\n username = name;\n addCookie('chatname', name);\n if(getCookie('chatboxOpen')==='1')\n $username.text(username);\n }\n }", "function postToTwitter(markovHeadline)\n{\n\tT.post('statuses/update', { status: markovHeadline }, function(err, data, response) {\n\t\tconsole.log(data);\n\t})\n}", "function BindWeChatName(token, wechat, suc_func, error_func) {\n let api_url = 'bnd_wechat.php',\n post_data = {\n 'token': token,\n 'wechat': wechat\n };\n CallApi(api_url, post_data, suc_func, error_func);\n}", "function updateScreenName() {\n if (typeof settings.screenName === 'string' && settings.screenName.length) {\n ChatSocket.emit('screenname update', settings.screenName);\n }\n }", "function tweetEvent(tweet) {\n\n // Who is this in reply to?\n var reply_to = tweet.in_reply_to_screen_name;\n // Who sent the tweet?\n var name = tweet.user.screen_name;\n // What is the text?\n var txt = tweet.text;\n // If we want the conversation thread\n var id = tweet.id_str;\n\n // Ok, if this was in reply to me\n // Tweets by me show up here too\n if (reply_to === 'InatorBot') {\n\n // Get rid of the @ mention\n txt = txt.replace(/@InatorBot/g,'');\n\n //reply back to the sender\n var replyText = '@'+name + ' thx for doing the twit at me XD';\n\n // Post that tweet\n T.post('statuses/update', { status: replyText, in_reply_to_status_id: id}, tweeted);\n\n // Make sure it worked!\n function tweeted(err, reply) {\n if (err) {\n console.log(err.message);\n } else {\n console.log('Tweeted: ' + reply.text);\n }\n }\n }\n}", "static sNewWord(key) {\n Signals.emit(rooms[key].users[rooms[key].speaker].sids[0], \"sNewWord\", {\"word\": rooms[key].word});\n }", "addToken() {\n\t\t//Do nothing if there is no input.\n\t\tif (!this.newNameField.value) {\n\t\t\treturn;\n\t\t}\n\n\t\tvar newName = this.newNameField.value;\n\n\t\t//Truncate the name.\n\t\twhile (newName.endsWith(\" \")) {\n\t\t\tnewName = newName.substring(0, newName.length - 1);\n\t\t}\n\t\twhile (newName.startsWith(\" \")) {\n\t\t\tnewName = newName.substring(1, newName.length);\n\t\t}\n\n\t\tthis.newNameField.value = \"\";\n\t\tthis.addName(newName);\n\t}", "function ShareTweet(tab) {\n var share_text = encodeURIComponent(tab.title)\n\n var get_sync_storage = getSyncStorage()\n get_sync_storage.then(function (items) {\n if (items.prefixAvailable) {\n share_text = items.prefixText + share_text\n }\n\n if (encodeURIComponent(tab.url)) {\n share_text += '%0a' + encodeURIComponent(tab.url)\n }\n\n chrome.windows.create({\n url: `https://twitter.com/intent/tweet?text=${share_text}`,\n type: 'popup',\n width: 600,\n height: 400,\n })\n })\n}", "function name_updater(){\n console.log(\"I entered her hihihi\");\n if(oldview_number != view_number){ //Condition used to prevente Discord API rate limit\n var final_name = channel_name[0].concat('-',channel_name[1],'-', view_number.toString());\n client.guilds.cache.get(serverId).channels.cache.get(textChannelId).edit({name: final_name}) //Changes Name of the channel specified with the id textChannelID\n .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`));\n oldview_number = view_number;\n }\n}", "function thingTweet() {\n request({\n url:\t 'https://api.thingspeak.com/apps/thingtweet/1/statuses/update',\n method: 'POST',\n\tform:\t { api_key: 'EQZMJ3E1FFOZOQE8', status: name } \n }, function (error, response, body) {\n if (!error && response.statusCode == 200) {\n console.log(body)\n }\n }\n);\n}", "function changeName(){\n\n const newName = prompt(\"What would you like the new name to be?\");\n \n if(newName !=\"\"){\n\n hero.name=newName;\n const dispName = document.querySelector(\"#showName\");\n dispName.innerText = hero.name;\n\n }\n\n}", "function saveUsersName(text) {\n localStorage.setItem(USERS_LS, text);\n}", "function saveHeadline(plainText) {\n\tconsole.log(plainText);\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout\n\t});\n\t\n\trl.question('\\n\\nPost to Twitter and Save? (1 for Yes, 2 for No)\t', \n\t(answer) => \n\t{\n\t\t// TODO: Log the data in a database\n\t\tif(answer == '1')\n\t\t{\n\t\t\tfs.appendFile(savePath, plainText + \"\\n\", function(err) {\n\t\t\t\tif(err) {\n\t\t\t\t\treturn console.log(err);\n\t\t\t\t}\n\t\t\t\tpostToTwitter(plainText);\n\t\t\t\trl.close();\n\t\t\t});\n\t\t}\n\t\telse\n\t\t{\n\t\t\trl.close();\n\t\t}\n\t});\n}", "function insert(name) {\n\t\tvar id = 'message', quote = '';\n\n\t\tif (typeof clickableEditor != 'undefined') {\n\t\t\tid = clickableEditor.textarea;\n\t\t}\n\n\t\t// find an appropriate quote character based on whether or not the\n\t\t// mentioned name includes that character\n\t\tif (name.indexOf('\"') == -1) {\n\t\t\tquote = '\"';\n\t\t} else if (name.indexOf(\"'\") == -1) {\n\t\t\tquote = \"'\";\n\t\t} else if (name.indexOf(\"`\") == -1) {\n\t\t\tquote = \"`\";\n\t\t}\n\n\t\t$(id).value += '@' + quote + name + quote + ' ';\n\t\t$(id).focus();\n\t}", "function setPassword(personalSentence, password)\n{\n return (personalSentence + ' ' + password);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CSS styles for the track fill element.
_getTrackFillStyles() { const percent = this.percent; const axis = this.vertical ? 'Y' : 'X'; const scale = this.vertical ? `1, ${percent}, 1` : `${percent}, 1, 1`; const sign = this._shouldInvertMouseCoords() ? '' : '-'; return { // scale3d avoids some rendering issues in Chrome. See #12071. transform: `translate${axis}(${sign}${this._getThumbGap()}px) scale3d(${scale})`, // iOS Safari has a bug where it won't re-render elements which start of as `scale(0)` until // something forces a style recalculation on it. Since we'll end up with `scale(0)` when // the value of the slider is 0, we can easily get into this situation. We force a // recalculation by changing the element's `display` when it goes from 0 to any other value. display: percent === 0 ? 'none' : '' }; }
[ "setStyle() {\n this.lineStyle = {\n color: globalStore.getData(keys.properties.trackColor),\n width: globalStore.getData(keys.properties.trackWidth)\n }\n }", "function colorCheckMark()\n{\n document.getElementById(\"mood-logged-checkmark\").style[\"fill\"] = moodColorsList[currentMood].color;\n}", "function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}", "render() {\n if (this.selected) {\n // If selected, fill the note as such and ignore everything else.\n this.fill(SELECTED);\n this.opacity(1);\n } else {\n if (this.playing) {\n // If the note is playing, fill the note as such.\n this.fill(PLAYING);\n } else {\n // Otherwise, check if the note is suggested.\n if (this.suggested) {\n this.fill(SUGGESTED, true);\n } else {\n this.fill(NORMAL);\n }\n }\n // If the note is being hovered over, alter its opacity.\n if (this.hovered) {\n this.opacity(0.65);\n } else {\n this.opacity(1);\n }\n }\n }", "function Filler(props) {\n return (React.createElement(\"div\", { className: progressBar_1.fillerItem, style: {\n width: `${props.percentage}px`\n } }));\n}", "calculateTrackWidth(trackDetails) {\r\n if (Object.keys(trackDetails).length >= 9) {\r\n this.percDecrement = 5;\r\n this.innerRadiusMod = 0;\r\n this.trackWidth = this.narrowTrackWidth;\r\n } else {\r\n this.percDecrement = 10;\r\n this.innerRadiusMod = 0;\r\n this.trackWidth = this.wideTrackWidth;\r\n }\r\n }", "fill(colour) {\r\n this.ctx.fillStyle = colour;\r\n this.ctx.fillRect(0, 0, this.width, this.height);\r\n }", "_colorUpdate() {\n if(this.value){\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': this.value,\n '--l2t-paper-color-indicator-icon-display': 'block',\n });\n } else {\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': 'transparent',\n '--l2t-paper-color-indicator-icon-display': 'none',\n });\n }\n }", "styleAxisCanvas() {\n const originalStyle = this.visualizer.canvas.style;\n const style = {\n 'z-index': 1,\n 'pointer-events': 'none',\n position: 'absolute',\n top: 0,\n left: 0,\n };\n\n const cssText = Object.entries(style).map((entry) =>\n `${entry[0]} : ${entry[1]}`).join('; ');\n this.canvas.setAttribute(\n 'style',\n `${originalStyle.cssText} ${cssText}`,\n );\n }", "function styleFn(fg) {\n const s = grid.getSource().getSize();\n // Calculate indicator\n let fac=0, ind = 0;\n switch (param.indice) {\n case 'ind_c': {\n fg.get('features')[0].get('data').forEach((d) => {\n ind += d[param.indices[param.indice].index];\n });\n ind *= param.valmax / (s*s);\n break;\n }\n case 'ind_srf': {\n fg.get('features')[0].get('data').forEach((d) => {\n ind += d[param.indices[param.indice].index];\n fac += d[9];\n });\n ind *= param.valmax / fac / (s*s);\n break;\n }\n }\n // Set color\n const color = [];\n for (let i=0; i<3; i++){\n color.push(param.colorMax[i]*ind + param.colorMin[i]*(1-ind));\n }\n color.push(.7);\n fill.getFill().setColor(color);\n return fill;\n}", "cssVariables() {\n const elementStyle = getComputedStyle(this)\n \n this._positionColor = elementStyle.getPropertyValue('--position-color')\n this._positionLineWidth = elementStyle.getPropertyValue('--position-line-width')\n this._positionRadius = elementStyle.getPropertyValue('--position-radius')\n \n this._gridSections = elementStyle.getPropertyValue('--grid-sections')\n this._gridColor = elementStyle.getPropertyValue('--grid-color')\n this._gridLineWidth = elementStyle.getPropertyValue('--grid-line-width')\n }", "function mxShapeGmdlProgressBar(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n\tthis.dx1 = 0.8;\n}", "function paintPercentCap() {\n if (percentCap >= 80) {\n return 'bg-success text-dark rounded';\n } else if (percentCap < 80 && percentCap >= 50) {\n return 'bg-warning text-dark rounded';\n } else if (percentCap < 50) {\n return 'bg-danger rounded';\n }\n }", "draw() {\n\t\tconst output = this.buffer.join(\",\");\n\t\tthis.style.applyCSS(output);\n\t}", "function updateScaleCSS(scale) {\n\n var width = 180 * scale;\n var height = 180 * scale;\n\n var gaugeStyle = generate_gauge_css(width, height);\n\n var st = document.getElementById(\"gauge_style\");\n st.innerHTML = gaugeStyle;\n}", "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 }", "__updateStyles() {\n // Chrome returns default value if property is not set\n // check if flex is defined for chart, and different than default value\n const isFlex = getComputedStyle(this).flex != '0 1 auto';\n\n // If chart element is a flexible item the chartContainer should be flex too\n if (isFlex) {\n this.$.chart.setAttribute('style', 'flex: 1; ');\n let style = '';\n if (this.hasAttribute('style')) {\n style = this.getAttribute('style');\n if (style.charAt(style.length - 1) !== ';') {\n style += ';';\n }\n }\n style += 'display: flex;';\n this.setAttribute('style', style);\n } else {\n this.$.chart.setAttribute('style', 'height:100%; width:100%;');\n }\n }", "layoutThumb(checked, thumbRadius, trackLength, trackSize) {\n trackSize = trackSize || defaultTrackSize;\n trackLength = trackLength || defaultTrackLength;\n const thumbRadii = thumbRadius || defaultThumbRadius;\n const rippleRadii = trackLength - trackSize;\n const trackRadii = trackSize / 2;\n const trackMargin = rippleRadii - trackRadii; // make room for ripple\n const thumbLeft = checked ? trackMargin + trackRadii : 0;\n this.animatedThumbLeft.setValue(thumbLeft);\n return {\n thumbFrame: {\n padding: rippleRadii - thumbRadii,\n r: thumbRadii,\n rippleRadii,\n x: thumbLeft,\n },\n trackLength,\n trackMargin,\n trackRadii,\n trackSize,\n };\n }", "setColorQuiescent(){\n\t this.color = colorQuie;\t \n }", "function changeColor(id, color) {\n\t// haal path dmv id en zet die naar kleur\n document.getElementById(id).style.fill = color;\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
showHudForSchematic function. Takes in a schematic and prepares it to be shown
function showHudForSchematic(newSchematic : Schematic, newObjectWithSchematic : GameObject) { objectWithSchematic = newObjectWithSchematic; schematic = newSchematic; slotOrigin = new Vector2(Screen.width / 2, Screen.height / 2); toolOrigin = new Vector2(slotOrigin.x, slotOrigin.y - 50); setTiles(); setToolOriginInPlayerHand(); }
[ "function showViz() {\n viz.show();\n}", "function displayHud() {\n // 2D screen-aligned rendering section\n easycam.beginHUD()\n // this._renderer._enableLighting = false // fix for issue #1\n let state = easycam.getState()\n\n // Get number of points\n let numPoints = 0\n\n if (letters) {\n numPoints = letters.points.length\n }\n if (drawingLetters) {\n numPoints = drawingLetters.points.length\n }\n if (disappearingLetters) {\n numPoints = disappearingLetters.points.length\n }\n\n // Render the background box for the HUD\n noStroke()\n fill(0)\n rect(x, y, 20, 140)\n fill(50, 50, 52, 20) // a bit of transparency\n rect(x + 20, y, 450, 140)\n\n // Render the labels\n fill(69, 161, 255)\n text(\"Distance:\", x + 35, y + 25)\n text(\"Center: \", x + 35, y + 25 + 20)\n text(\"Rotation:\", x + 35, y + 25 + 40)\n text(\"Framerate:\", x + 35, y + 25 + 60)\n text(\"GPU Renderer:\", x + 35, y + 25 + 80)\n text(\"Total Points:\", x + 35, y + 25 + 100)\n\n // Render the state numbers\n fill(0, 200, 0)\n text(nfs(state.distance, 1, 2), x + 160, y + 25)\n text(nfs(state.center, 1, 2), x + 160, y + 25 + 20)\n text(nfs(state.rotation, 1, 3), x + 160, y + 25 + 40)\n text(nfs(frameRate(), 1, 2), x + 160, y + 25 + 60)\n text(nfs(getGLInfo().gpu_renderer, 1, 2), x + 163, y + 25 + 80)\n text(nfs(numPoints, 1, 0), x + 160, y + 25 + 100)\n easycam.endHUD()\n}", "function showSimulation() {\r\n document.getElementById(\"simulationView\").style.display = \"block\";\r\n document.getElementById(\"propertiesInput\").style.display = \"none\";\r\n updateRestart();\r\n if (simulationParameters[\"interleaver\"]) {\r\n document.getElementById(\"interleaverSection\").style.display = \"block\";\r\n document.getElementById(\"deinterleaverSection\").style.display = \"block\";\r\n } else {\r\n document.getElementById(\"interleaverSection\").style.display = \"none\";\r\n document.getElementById(\"deinterleaverSection\").style.display = \"none\";\r\n\r\n }\r\n hideTransitionText();\r\n\r\n}", "function displayTable() {\r\n displayOnly(\"#tableOfContents\");\r\n traverseAndUpdateTableHelper();\r\n prepareText(heirarchy.tree[0].sections[0].id);\r\n activePart = 0;\r\n iconEventListeners();\r\n settingsEventListeners();\r\n scrollEventListener();\r\n}", "function drawSusceptibility(tid, oid){\n\t\t$.getJSON('/susceptibility/saveSusceptibility', { testId: tid, organismId: oid, action: \"results\"}, \n\t\t\tfunction(data){\n\n\t\t\t\tvar tableRow =\"\";\n\t\t\t\tvar tableBody =\"\";\n\t\t\t\t$.each(data, function(index, elem){\n\t\t\t\t\ttableRow += \"<tr>\"\n\t\t\t\t\t+\" <td>\"+elem.drugName+\" </td>\"\n\t\t\t\t\t+\" <td>\"+elem.zone+\"</td>\"\n\t\t\t\t\t+\" <td>\"+elem.interpretation+\"</td>\"\n\t\t\t\t\t+\"</tr>\";\n\t\t\t\t\t$(\".sense\"+tid).val($(\".sense\"+tid).val()+elem.drugName+\" - \"+elem.sensitivity+\", \");\n\t\t\t\t});\n\t\t\t\t//tableBody +=\"<tbody>\"+tableRow+\"</tbody>\";\n\t\t\t\t$( \"#enteredResults_\"+oid).html(tableRow);\n\t\t\t\t$(\"#submit_drug_susceptibility_\"+oid).hide();\n\t\t\t}\n\t\t);\n\t}", "_buildDisplay(locale, displaySize) {\n $(this._containerHtmlElems.get(locale)).empty();\n\n let resource = this._controller.dialogResource(locale);\n if (typeof resource === 'undefined') {\n this._svgDisplays.delete(locale);\n } else {\n this._svgDisplays.set(\n locale,\n SvgLayout._makeDisplay(\n displaySize,\n this._displayMargin,\n this._containerHtmlElems.get(locale),\n resource,\n this\n )\n );\n }\n }", "function displayCircuit(data) {\n\t\t\t\n\t\t\ttry {\n\t\t\t\tpreProcessData(data);\n\t\t\t} catch (err) {\n\t\t\t\tlog(\"Failed preProcessData: \" + err.message);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// add the 'addCommas' function to the 'data' object so the HTML templates can use it\n\t\t\tdata.addCommas = addCommas;\n\t\t\t// add the 'roundNumber' function to the 'data' object so the HTML templates can use it\n\t\t\tdata.roundNumber = roundNumber;\n\t\t\t// add the 'getInstanceAverage' function to the 'data' object so the HTML templates can use it\n\t\t\tdata.getInstanceAverage = getInstanceAverage;\n\t\t\t\n\t\t\tvar addNew = false;\n\t\t\t// check if we need to create the container\n\t\t\tif(!$('#CIRCUIT_' + data.escapedName).length) {\n\t\t\t\t// args for display\n\t\t\t\tif(self.args.includeDetailIcon != undefined && self.args.includeDetailIcon) {\n\t\t\t\t\tdata.includeDetailIcon = true;\n\t\t\t\t}else {\n\t\t\t\t\tdata.includeDetailIcon = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// it doesn't exist so add it\n\t\t\t\tvar html = tmpl(hystrixTemplateCircuitContainer, data);\n\t\t\t\t// remove the loading thing first\n\t\t\t\t$('#' + containerId + ' span.loading').remove();\n\t\t\t\t// now create the new data and add it\n\t\t\t\t$('#' + containerId + '').append(html);\n\t\t\t\t\n\t\t\t\t// add the default sparkline graph\n\t\t\t\td3.selectAll('#graph_CIRCUIT_' + data.escapedName + ' svg').append(\"svg:path\");\n\t\t\t\t\n\t\t\t\t// remember this is new so we can trigger a sort after setting data\n\t\t\t\taddNew = true;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t// now update/insert the data\n\t\t\t$('#CIRCUIT_' + data.escapedName + ' div.monitor_data').html(tmpl(hystrixTemplateCircuit, data));\n\t\t\t\n\t\t\tvar ratePerSecond = data.ratePerSecond;\n\t\t\tvar ratePerSecondPerHost = data.ratePerSecondPerHost;\n\t\t\tvar ratePerSecondPerHostDisplay = ratePerSecondPerHost;\n\t\t\tvar errorThenVolume = isNaN( ratePerSecond )? -1: (data.errorPercentage * 100000000) + ratePerSecond;\n\t\t\t// set the rates on the div element so it's available for sorting\n\t\t\t$('#CIRCUIT_' + data.escapedName).attr('rate_value', ratePerSecond);\n\t\t\t$('#CIRCUIT_' + data.escapedName).attr('error_then_volume', errorThenVolume);\n\t\t\t\n\t\t\t// update errorPercentage color on page\n\t\t\t$('#CIRCUIT_' + data.escapedName + ' a.errorPercentage').css('color', self.circuitErrorPercentageColorRange(data.errorPercentage));\n\t\t\t\n\t\t\tupdateCircle('circuit', '#CIRCUIT_' + data.escapedName + ' circle', ratePerSecondPerHostDisplay, data.errorPercentage);\n\t\t\t\n\t\t\tif(data.graphValues) {\n\t\t\t\t// we have a set of values to initialize with\n\t\t\t\tupdateSparkline('circuit', '#CIRCUIT_' + data.escapedName + ' path', data.graphValues);\n\t\t\t} else {\n\t\t\t\tupdateSparkline('circuit', '#CIRCUIT_' + data.escapedName + ' path', ratePerSecond);\n\t\t\t}\n\n\t\t\tif(addNew) {\n\t\t\t\t// sort since we added a new circuit\n\t\t\t\tself.sortSameAsLast();\n\t\t\t}\n\t\t}", "function displayCard(tsv, prepend=false) {\n let curId = idCounter++\n let node = createCard(tsv, curId, true)\n if (prepend) {\n $(\"#deck-display\").prepend(node)\n } else {\n $(\"#deck-display\").append(node)\n }\n cards.set(curId, new Card(tsv[0], tsv[1], node))\n }", "function set_display(value)\n{\n\t//value can be: wireframe, hiddenvis, hiddeninvis, or shade //\n\tenv_stat=document.wm.pwlConfigoptSet('display', value);\n}", "function updateDisplay(){\n\t\t// Update any changes the Hero element\n\t\t$(\".hero\").html(\n\t\t\t\t\"<p>\" + hero.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + hero.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + hero.hitPoints + \"</p>\"\n\t\t);\n\t\t// Update any changes the Defender element\n\t\t$(\".defender\").html(\n\t\t\t\t\"<p>\" + defender.name + \"</p>\" +\n\t\t\t\t\"<img src='\" + defender.img + \"' >\" +\n\t\t\t\t\"<p> HP: \" + defender.hitPoints + \"</p>\"\n\t\t);\n\t}", "function setupHud() {\n setAttributes(\"antialias\", true)\n easycam = createEasyCam()\n document.oncontextmenu = function () {\n return false\n }\n\n // set initial camera state\n easycam.setState(state)\n easycam.state_reset = state // state to use on reset\n\n // use the loaded font\n textFont(f)\n textSize(16)\n}", "function displayObservation(obs) {\n bilirubin.innerHTML = obs.hdl;\n creatinine.innerHTML = obs.ldl;\n INR.innerHTML = obs.sys;\n Sodium.innerHTML = obs.dia;\n}", "function renderSquare() {\n let side = document.getElementById(\"square-value\").value;\n let areaOfSquare = shapeFactory(side);\n let areaResult = areaOfSquare.printsquareArea();\n document.getElementById(\"step-2\").style.display = \"none\";\n document.getElementById(\"step-3\").style.display = \"block\";\n document.getElementById(\n \"result-para\"\n ).innerHTML = `You have calculated the area of a <b>square</b> with side of ${side}. Below is your result`;\n document.getElementById(\n \"result-heading\"\n ).innerHTML = `The area is ${areaResult}`;\n}", "function displayHelp() {\n\tlet helpText = require('../html/help.html.js');\n\tcreateDialog('show-dialog', 'Help', helpText['helpDialog'], undefined, true);\n}", "function display(shuffled) {\n $deck.empty()\n initTime()\n // shuffled = shuffle(cards);\n\n for (let i = 0; i < shuffled.length; i++) {\n $card = memoryCard(shuffled[i]);\n $deck.append($card);\n }\n}", "function getSpeechDisplay(speech) {\n //var speechRow = $(\"<div class='m-0 p-0'><span class='quote'></span><span class='speech'></span><span class='quote'></span><div>\");\n var speechRow = $(\"<div class='m-0 p-0'><span class='speech'></span><div>\");\n //speechRow.find(\".quote\").text('\"');\n speechRow.find(\".speech\").text(speech);\n return speechRow;\n }", "display_hand() {\n console.log(\"\\n\\n\");\n console.log(\"My hand:\");\n console.log(this.mycards);\n console.log(\"\\n\\n\");\n console.log(\"My points:\");\n console.log(this.mypoints);\n console.log(\"\\n\\n\");\n }", "function displayChart(){\n //check if this is the first time the addChartButton has been pressed. If it isn't then destroy the chart. Destroying the chart resets all data.\n if(!firstRound){\n myChart.destroy();\n };\n // after destroying the chart we make a new chart with getNewChart\n getNewChart();\n // check if the chart collapsible is active. if it isn't we make it active by clicking on it.\n if(!$('#chartCollapsible').hasClass('active')){\n $('#chartCollapsible').click();\n }\n // we remove the glow effect from addChartButton\n $('#addChartButton').removeClass('glowEffect');\n $('.progress').hide();\n\n // We set first round to false.\n firstRound = false;\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares documents as specified in ReQL. Treats undefined as maxval (because we want missing columns to be at the end).
static compareReqlDocs(a, b) { // Handle undefined case, which may happen. if (a === undefined) { return b === undefined ? 0 : -1; } else if (b === undefined) { return 1; } // The logic here is cribbed from datum_t::cmp_unchecked_stack. const a_ptype = this.is_ptype(a) && !this.pseudo_compares_as_obj(a); const b_ptype = this.is_ptype(b) && !this.pseudo_compares_as_obj(b); if (a_ptype && b_ptype) { const a_reql_type = this.get_reql_type(a); const b_reql_type = this.get_reql_type(b); if (a_reql_type !== b_reql_type) { return a_reql_type < b_reql_type ? -1 : a_reql_type > b_reql_type ? 1 : 0; } return this.pseudo_cmp(a, b); } if (a_ptype || b_ptype) { const a_name_for_sorting = this.get_type_name(a); const b_name_for_sorting = this.get_type_name(b); return a_name_for_sorting < b_name_for_sorting ? -1 : a_name_for_sorting > b_name_for_sorting ? 1 : 0; } const a_type = this.get_type_name(a); const b_type = this.get_type_name(b); if (a_type !== b_type) { return a_type < b_type ? -1 : a_type > b_type ? 1 : 0; } switch (a_type) { case 'NULL': return 0; case 'BOOL': return a < b ? -1 : a > b ? 1 : 0; case 'NUMBER': return a < b ? -1 : a > b ? 1 : 0; case 'STRING': return this.reqlCompareStrings(a, b); case 'ARRAY': return this.reqlCompareArrays(a, b); case 'OBJECT': return this.reqlCompareArrays(this.sorted_keyvals(a), this.sorted_keyvals(b)); default: console.error("Unhandled type in switch in compareReqlDocs", a_type, a, b); throw "compareReqlDocs: unhandled type"; } }
[ "static pseudo_cmp(a, b) {\n if (a['$reql_type$'] === 'BINARY') {\n if (!('data' in a && 'data' in b)) {\n console.error(\"BINARY ptype doc lacking data field\", a, b);\n throw \"BINARY ptype doc lacking data field\";\n }\n const aData = rethinkdbGlobal.binary_to_string(a['data']);\n const bData = rethinkdbGlobal.binary_to_string(b['data']);\n return aData < bData ? -1 : aData > bData ? 1 : 0;\n }\n if (a['$reql_type$'] === 'TIME') {\n if (!('epoch_time' in a && 'epoch_time' in b)) {\n console.error(\"TIME ptype doc lacking epoch_time field\", a, b);\n throw \"TIME ptype doc lacking epoch_time field\";\n }\n // These are both numbers. And if they aren't, we'll just compare them.\n const aEpoch = a['epoch_time'];\n const bEpoch = b['epoch_time'];\n return aEpoch < bEpoch ? -1 : aEpoch > bEpoch ? 1 : 0;\n }\n console.error(\"pseudo_cmp logic error\", a, b);\n throw \"pseudo_cmp encountered unhandled type\";\n }", "function multivalentField (sortedRecords, f) {\n const haveVals = sortedRecords.filter(r => r[f] !== undefined && r[f] !== null)\n if (haveVals.length === 0)\n return { value: undefined }\n const maxPriority = Math.max(...haveVals.map(r => r.priority || 0))\n\n const candidates = haveVals.\n filter(r => (r.priority || 0) === maxPriority)\n\n if (candidates.length === 1)\n return { value: candidates[0][f], source: candidates[0].source }\n\n // Multiple equal priority.\n const values = candidates.map(c => c[f])\n const max = Math.max(...values)\n const min = Math.min(...values)\n\n // Arbitrarily picking the first source with the max value as the\n // source used.\n const bySource = (a, b) => (a.source < b.name ? -1 : 1)\n const maxSource = candidates.sort(bySource).\n find(c => c[f] === max).source\n\n // Arbitrarily using the maximum value returned by any sources.\n const result = {\n value: max,\n source: maxSource\n }\n\n if (min !== max) {\n const conflicts = candidates.map(c => `${c.source}: ${c[f]}`)\n result.warning = `conflict (${conflicts.join(', ')})`\n }\n return result\n}", "function compauthor(a, b) {\n return a.author > b.author;\n}", "Ln(t, e, n, s) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n if (n.size !== e.size) return !0; // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n\n const i = \"F\"\n /* First */\n === t ? e.last() : e.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);\n }", "function isCompatibleProperty(a, b) {\n\tif (a.blockStructure === b) {\n\t\treturn a.version > b.version ? 1 : 0\n\t}\n\tif (a.code === b.code && a.extendedType === b.extendedType) {\n\t\tvar sharedLength = Math.min(a.length, b.length)\n\t\tvar compatibility = 0\n\t\tfor (var i = 0; i < sharedLength; i++) {\n\t\t\tif (a[i].key !== b[i].key)\n\t\t\t\treturn -2\n\t\t\tvar childCompatibility = isCompatibleProperty(a[i], b[i])\n\t\t\tif (childCompatibility === -2)\n\t\t\t\treturn -2\n\t\t\tif (childCompatibility === -1) {\n\t\t\t\tif (compatibility === 1)\n\t\t\t\t\treturn -2\n\t\t\t\tcompatibility = -1\n\t\t\t}\n\t\t\tif (childCompatibility === 1) {\n\t\t\t\tif (compatibility === -1)\n\t\t\t\t\treturn -2\n\t\t\t\tcompatibility = 1\n\t\t\t}\n\t\t}\n\t\tvar sharedValuesLength = Math.min(a.values ? a.values.length : 0, b.values ? b.values.length : 0)\n\t\tfor (var i = 0; i < sharedValuesLength; i++) {\n\t\t\tif (a.values[i] !== b.values[i]) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t}\n\t\tif (a.length < b.length) {\n\t\t\tif (compatibility === 1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = -1\n\t\t} else if (a.length < b.length) {\n\t\t\tif (compatibility === -1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = 1\n\t\t}\n\t\t/*if (a.values.length < b.values.length) {\n\t\t\tif (compatibility === 1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = -1\n\t\t} else if (a.values.length < b.values.length) {\n\t\t\tif (compatibility === -1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = 1\n\t\t}*/\n\t\treturn compatibility\n\t} else {\n\t\treturn -2\n\t}\n}", "relevance(that){cov_25grm4ggn6.f[9]++;let total=(cov_25grm4ggn6.s[47]++,0);let words=(cov_25grm4ggn6.s[48]++,Object.keys(this.count));cov_25grm4ggn6.s[49]++;words.forEach(w=>{cov_25grm4ggn6.f[10]++;cov_25grm4ggn6.s[50]++;total+=this.rank(w)*that.rank(w);});//return the average rank of my words in the other vocabulary\ncov_25grm4ggn6.s[51]++;return total/words.length;}", "static compare(oldSets, newSets, textDiff, comparator) {\n var _a;\n let minPoint = (_a = comparator.minPointSize) !== null && _a !== void 0 ? _a : -1;\n let a = oldSets.filter(set => set.maxPoint >= BigPointSize ||\n set != RangeSet.empty && newSets.indexOf(set) < 0 && set.maxPoint >= minPoint);\n let b = newSets.filter(set => set.maxPoint >= BigPointSize ||\n set != RangeSet.empty && oldSets.indexOf(set) < 0 && set.maxPoint >= minPoint);\n let sharedChunks = findSharedChunks(a, b);\n let sideA = new SpanCursor(a, sharedChunks, minPoint);\n let sideB = new SpanCursor(b, sharedChunks, minPoint);\n textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));\n if (textDiff.empty && textDiff.length == 0)\n compare(sideA, 0, sideB, 0, 0, comparator);\n }", "function yearComparator( auto1, auto2)\n{\n if (auto1.year > auto2.year) // If the year of the first automobile is > than that of the second:\n {\n return true; \n }\n else // The year of the second automobile is > than that of the first:\n {\n return false;\n }\n}", "function compareValues(val1, val2){\r\n\tif (val1 > val2) {\r\n\t\treturn -1;\r\n\t} else if(val2 > val1) {\r\n\t\treturn 1;\r\n\t} else {\r\n\t\treturn 0;\r\n\t}\r\n}", "function findBestMatchingIndex(selector, userFields, sortOrder, indexes) {\n\n var matchingIndexes = findMatchingIndexes(selector, userFields, sortOrder, indexes);\n\n if (matchingIndexes.length === 0) {\n //return `all_docs` as a default index;\n //I'm assuming that _all_docs is always first\n var defaultIndex = indexes[0];\n defaultIndex.defaultUsed = true;\n return defaultIndex;\n }\n if (matchingIndexes.length === 1) {\n return matchingIndexes[0];\n }\n\n var userFieldsMap = arrayToObject(userFields);\n\n function scoreIndex(index) {\n var indexFields = index.def.fields.map(pouchdbSelectorCore.getKey);\n var score = 0;\n for (var i = 0, len = indexFields.length; i < len; i++) {\n var indexField = indexFields[i];\n if (userFieldsMap[indexField]) {\n score++;\n }\n }\n return score;\n }\n\n return max(matchingIndexes, scoreIndex);\n}", "function compareResults(result1, result2) {\n return(result2.score - result1.score) ||\n result1.name.localeCompare(result2.name); \n}", "function mostProlificAuthor(authors) {\n // Your code goes here\n\n let x = bookCountsByAuthor(authors);\n // console.log(x);\n\n const compare = (a, b) => {\n let comparison = 0;\n if (a.bookCount > b.bookCount) {\n comparison = 1;\n } else if (a.bookCount < b.bookCount) {\n comparison = -1;\n }\n return comparison;\n };\n let y = x.sort(compare);\n console.log(y);\n\n return y.pop();\n\n // let x = authors.map(author => author.books.length);\n // console.log(x);\n // // let y = Math.max(...x);\n // // return authors.forEach(author => {\n // // if (author.books.length === y) {\n // // console.log(author.name);\n // // }\n // // });\n\n // if (bookCountsByAuthor(authors).bookCount)\n}", "modificar_compartimento(user, marca, medicamento, Npastilla, Ntratamiento, temp_max, hum_max, hora) {\n try {\n const compar1 = {\n marca: marca,\n medicamento: medicamento,\n Npastilla: Npastilla,\n Ntratamiento: Ntratamiento,\n temp_max: temp_max,\n hum_max: hum_max,\n hora: hora\n };\n this.compar1$ = compar1;\n const dataRef = this.db.collection('Compartimento1').doc(user.uid);\n dataRef.set({\n marca: marca,\n medicamento: medicamento,\n Npastilla: Npastilla,\n Ntratamiento: Ntratamiento,\n temp_max: temp_max,\n hum_max: hum_max,\n hora: hora,\n }, { merge: true });\n }\n catch (error) {\n console.log('Error->', error);\n }\n }", "function best( dict ) {\n\t\tvar id, result, max = -Infinity;\n\t\tfor ( id in dict ) {\n\t\t\tif ( dict[id] > max ) {\n\t\t\t\tresult = id;\n\t\t\t\tmax = dict[ id ];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}", "function compare(a, b) {\n var countA = wordTable[a];\n var countB = wordTable[b];\n return countB - countA;\n}", "ngramSearch(doc, ngram, fallback = false, norm = false) {\n\n if(!fallback)\n fallback = ngram.length;\n\n var maxLength = ngram.length;\n\n ngram = ngram.slice(0); // max local, mutable copy\n\n var matches = [ ];\n\n for(var i = 0; i <= ngram.length; i++)\n matches[i] = [ ];\n\n var content = this._docs[doc].content;\n\n for(var len = ngram.length; len >= fallback; len--) { // loop through allowed ngram lengths\n\n // At this level, we are looping through shorter and shorter ngrams\n // within the limits imposed by fallback. We start by trimming the\n // beginning of the ngram array until it equals the current value of\n // len.\n\n var subgram = ngram.slice(0);\n while(subgram.length > len)\n subgram.shift();\n\n\n // If we're allowing normalized matches, we go ahead and create a\n // normalized version of the ngram.\n\n if(norm) {\n var normgram = this._dict.idxToNormIdx(subgram);\n }\n\n var end = content.length - subgram.length;\n for(var t = 0; t < end; t++) {\n\n // At this level, we're looping through the array of indices\n // encoded in the doc. In the inner loop(s) below, we check\n // at each position to see if we have a match with the ngram\n // and, if norm is enabled, the normalized ngram.\n\n // The search is a brute-force linear search that can and should\n // be optimized to use something like a Boyer-Moore search later.\n\n var match = true;\n for(var m = 0; m < subgram.length; m++) {\n if(content[t + m] != subgram[m] && (!norm || content[t + m] != normgram[m])) {\n match = false;\n break;\n }\n }\n if(match) {\n matches[subgram.length].push(t);\n }\n\n }\n }\n\n for(var i = 0; i < matches.length; i++)\n if(matches[i].length == 0)\n matches[i] = null;\n\n return matches;\n }", "function eqSets_QMRK_(s1, s2) {\n let ok_QMRK_ = true;\n if( (s1.size === s2.size) ) {\n if (true) {\n s1.forEach(function(v, k) {\n return ((!s2.has(v)) ?\n (ok_QMRK_ = false) :\n null);\n });\n }\n }\n return ok_QMRK_;\n}", "function relevantFieldsMatch(a, b) {\n\n // flat values\n if (a.id != b.id ||\n a.title != b.title ||\n a.status != b.status ||\n a.privacy != b.privacy) {\n return false;\n }\n\n function compareNotNull(prop) {\n let ap = a[prop];\n let bp = b[prop];\n return (ap && !bp || !ap && bp ||\n (typeof(ap) == 'object' && ap && bp &&\n ap.compare && ap.compare(bp)));\n }\n\n // Object flat values\n if (compareNotNull(\"recurrenceInfo\") ||\n compareNotNull(\"alarmLastAck\") ||\n /* Compare startDate and endDate */\n compareNotNull(\"startDate\") ||\n compareNotNull(\"endDate\") ||\n (a.startDate.isDate != b.startDate.isDate) ||\n (a.endDate.isDate != b.endDate.isDate)) {\n return false;\n }\n\n // Properties\n const kPROPERTIES = [\"DESCRIPTION\", \"TRANSP\", \"X-GOOGLE-EDITURL\",\n \"LOCATION\", \"X-MOZ-SNOOZE-TIME\"];\n\n for each (let p in kPROPERTIES) {\n // null and an empty string should be handled as non-relevant\n if ((a.getProperty(p) || \"\") != (b.getProperty(p) || \"\")) {\n return false;\n }\n }\n\n // categories\n let aCat = a.getCategories({});\n let bCat = b.getCategories({});\n if ((aCat.length != bCat.length) ||\n aCat.some(function notIn(cat) { return (bCat.indexOf(cat) == -1); })) {\n return false;\n }\n\n // attendees and organzier\n let aa = a.getAttendees({});\n let ab = b.getAttendees({});\n if (aa.length != ab.length) {\n return false;\n }\n\n if ((a.organizer && !b.organizer) ||\n (!a.organizer && b.organizer) ||\n (a.organizer && b.organizer && a.organizer.id != b.organizer.id)) {\n return false;\n }\n\n // go through attendees in a, check if its id is in b\n for each (let attendee in aa) {\n let ba = b.getAttendeeById(attendee.id);\n if (!ba ||\n ba.participationStatus != attendee.participationStatus ||\n ba.commonName != attendee.commonName ||\n ba.isOrganizer != attendee.isOrganizer ||\n ba.role != attendee.role) {\n return false;\n }\n }\n\n // Alarms\n aa = a.getAlarms({});\n ab = b.getAlarms({});\n\n if (aa.length != ab.length) {\n return false;\n }\n\n let alarmMap = {};\n for each (let alarm in aa) {\n alarmMap[alarm.icalString] = true;\n }\n let found = 0;\n for each (let alarm in ab) {\n if (alarm.icalString in alarmMap) {\n found++;\n }\n }\n\n if (found != ab.length) {\n return false;\n }\n\n // Recurrence Items\n if (a.recurrenceInfo) {\n let ra = a.recurrenceInfo.getRecurrenceItems({});\n let rb = b.recurrenceInfo.getRecurrenceItems({});\n\n // If we have more or less, it definitly changed.\n if (ra.length != rb.length) {\n return false;\n }\n\n // I assume that if the recurrence pattern has not changed, the order\n // of the recurrence items should not change. Anything more will be\n // very expensive.\n for (let i = 0; i < ra.length; i++) {\n if (ra[i].icalProperty.icalString !=\n rb[i].icalProperty.icalString) {\n return false;\n }\n }\n }\n\n return true;\n}", "function compareArrays(existingCostArr, runnningCostArr) {\n let index = 0;\n while (true) {\n let existingCost = existingCostArr[index], runnningCost = runnningCostArr[index];\n if (existingCost === undefined && runnningCost === undefined)\n return 0;\n else if (existingCost === undefined)\n return -1;\n else if (runnningCost === undefined)\n return 1;\n\n if (existingCost < runnningCost)\n return -1;\n else if (existingCost > runnningCost)\n return 1;\n\n index++;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A manifold point is a contact point belonging to a contact / manifold. It holds details related to the geometry and dynamics / of the contact points. / The local point usage depends on the manifold type: / e_circles: the local center of circleB / e_faceA: the local center of cirlceB or the clip point of polygonB / e_faceB: the clip point of polygonA / This structure is stored across time steps, so we keep it small. / Note: the impulses are used for internal caching and may not / provide reliable contact forces, especially for high speed collisions.
function b2ManifoldPoint() { this.localPoint = new b2Vec2(); ///< usage depends on manifold type this.normalImpulse = 0; ///< the non-penetration impulse this.tangentImpulse = 0; ///< the friction impulse this.id = new b2ContactID(); ///< uniquely identifies a contact point between two shapes }
[ "function b2CollidePolygonAndCircle(manifold,\n\t\t\t\t\t\t\t polygonA, xfA,\n\t\t\t\t\t\t\t circleB, xfB)\n{\n\tmanifold.pointCount = 0;\n\n\t// Compute circle position in the frame of the polygon.\n\tvar c = b2Mul_t_v2(xfB, circleB.m_p);\n\tvar cLocal = b2MulT_t_v2(xfA, c);\n\n\t// Find the min separating edge.\n\tvar normalIndex = 0;\n\tvar separation = -b2_maxFloat;\n\tvar radius = polygonA.m_radius + circleB.m_radius;\n\tvar vertexCount = polygonA.m_count;\n\tvar vertices = polygonA.m_vertices;\n\tvar normals = polygonA.m_normals;\n\n\tfor (var i = 0; i < vertexCount; ++i)\n\t{\n\t\tvar s = normals[i].x * (cLocal.x - vertices[i].x) + normals[i].y * (cLocal.y - vertices[i].y);//b2Dot_v2_v2(normals[i], b2Vec2.Subtract(cLocal, vertices[i]));\n\n\t\tif (s > radius)\n\t\t{\n\t\t\t// Early out.\n\t\t\treturn;\n\t\t}\n\n\t\tif (s > separation)\n\t\t{\n\t\t\tseparation = s;\n\t\t\tnormalIndex = i;\n\t\t}\n\t}\n\n\t// Vertices that subtend the incident face.\n\tvar vertIndex1 = normalIndex;\n\tvar vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0;\n\tvar v1 = vertices[vertIndex1];\n\tvar v2 = vertices[vertIndex2];\n\n\t// If the center is inside the polygon ...\n\tif (separation < b2_epsilon)\n\t{\n\t\tmanifold.pointCount = 1;\n\t\tmanifold.type = b2Manifold.e_faceA;\n\t\tmanifold.localNormal.x = normals[normalIndex].x;//.Assign(normals[normalIndex]);\n\t\tmanifold.localNormal.y = normals[normalIndex].y;\n\t\tmanifold.localPoint.x = 0.5 * (v1.x + v2.x);//.Assign(b2Vec2.Multiply(0.5, b2Vec2.Add(v1, v2)));\n\t\tmanifold.localPoint.y = 0.5 * (v1.y + v2.y);\n\t\tmanifold.points[0] = new b2ManifoldPoint();\n\t\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\t\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\t\tmanifold.points[0].id.Reset();\n\t\treturn;\n\t}\n\n\t// Compute barycentric coordinates\n\tvar u1 = (cLocal.x - v1.x) * (v2.x - v1.x) + (cLocal.y - v1.y) * (v2.y - v1.y);//b2Dot_v2_v2(b2Vec2.Subtract(cLocal, v1), b2Vec2.Subtract(v2, v1));\n\tvar u2 = (cLocal.x - v2.x) * (v1.x - v2.x) + (cLocal.y - v2.y) * (v1.y - v2.y);//b2Dot_v2_v2(b2Vec2.Subtract(cLocal, v2), b2Vec2.Subtract(v1, v2));\n\tif (u1 <= 0.0)\n\t{\n\t\tif (b2DistanceSquared(cLocal, v1) > radius * radius)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tmanifold.pointCount = 1;\n\t\tmanifold.type = b2Manifold.e_faceA;\n\t\tmanifold.localNormal.x = cLocal.x - v1.x;//.Assign(b2Vec2.Subtract(cLocal, v1));\n\t\tmanifold.localNormal.y = cLocal.y - v1.y;\n\t\tmanifold.localNormal.Normalize();\n\t\tmanifold.localPoint.x = v1.x;\n\t\tmanifold.localPoint.y = v1.y;\n\t\tmanifold.points[0] = new b2ManifoldPoint();\n\t\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\t\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\t\tmanifold.points[0].id.Reset();\n\t}\n\telse if (u2 <= 0.0)\n\t{\n\t\tif (b2DistanceSquared(cLocal, v2) > radius * radius)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tmanifold.pointCount = 1;\n\t\tmanifold.type = b2Manifold.e_faceA;\n\t\tmanifold.localNormal.x = cLocal.x - v2.x;//.Assign(b2Vec2.Subtract(cLocal, v2));\n\t\tmanifold.localNormal.y = cLocal.y - v2.y;\n\t\tmanifold.localNormal.Normalize();\n\t\tmanifold.localPoint.x = v2.x;\n\t\tmanifold.localPoint.y = v2.y;\n\t\tmanifold.points[0] = new b2ManifoldPoint();\n\t\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\t\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\t\tmanifold.points[0].id.Reset();\n\t}\n\telse\n\t{\n\t\tvar faceCenterx = 0.5 * (v1.x + v2.x);//b2Vec2.Multiply(0.5, b2Vec2.Add(v1, v2));\n\t\tvar faceCentery = 0.5 * (v1.y + v2.y);\n\t\tvar separation = (cLocal.x - faceCenterx) * normals[vertIndex1].x + (cLocal.y - faceCentery) * normals[vertIndex1].y;//b2Dot_v2_v2(b2Vec2.Subtract(cLocal, faceCenter), normals[vertIndex1]);\n\t\tif (separation > radius)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tmanifold.pointCount = 1;\n\t\tmanifold.type = b2Manifold.e_faceA;\n\t\tmanifold.localNormal.x = normals[vertIndex1].x;\n\t\tmanifold.localNormal.y = normals[vertIndex1].y;\n\t\tmanifold.localPoint.x = faceCenterx;\n\t\tmanifold.localPoint.y = faceCentery;\n\t\tmanifold.points[0] = new b2ManifoldPoint();\n\t\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\t\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\t\tmanifold.points[0].id.Reset();\n\t}\n}", "get center() {\n\n // Check if the face is bound to a mesh and if not throw an error\n if (!this.mesh) throw new Error(`Cannot compute the face center - the face is not bound to a Mesh`);\n\n // Calculate the center of the face\n return new Point(divide(add(this.a, this.b, this.c), 3));\n }", "function b2CollideCircles(manifold,\n\t\t\t\t\t circleA, xfA,\n\t\t\t\t\t circleB, xfB)\n{\n\tmanifold.pointCount = 0;\n\n\tvar pA = b2Mul_t_v2(xfA, circleA.m_p);\n\tvar pB = b2Mul_t_v2(xfB, circleB.m_p);\n\n\tvar dx = pB.x - pA.x;//b2Vec2.Subtract(pB, pA);\n\tvar dy = pB.y - pA.y;\n\tvar distSqr = dx * dx + dy * dy;//b2Dot_v2_v2(d, d);\n\tvar rA = circleA.m_radius, rB = circleB.m_radius;\n\tvar radius = rA + rB;\n\tif (distSqr > radius * radius)\n\t{\n\t\treturn;\n\t}\n\n\tmanifold.type = b2Manifold.e_circles;\n\tmanifold.localPoint.x = circleA.m_p.x;\n\tmanifold.localPoint.y = circleA.m_p.y;\n\tmanifold.localNormal.x = manifold.localNormal.y = 0;\n\tmanifold.pointCount = 1;\n\n\tmanifold.points[0] = new b2ManifoldPoint();\n\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\tmanifold.points[0].id.Reset();\n}", "pointRef(editor, point) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var {\n affinity = 'forward'\n } = options;\n var ref = {\n current: point,\n affinity,\n\n unref() {\n var {\n current\n } = ref;\n var pointRefs = Editor.pointRefs(editor);\n pointRefs.delete(ref);\n ref.current = null;\n return current;\n }\n\n };\n var refs = Editor.pointRefs(editor);\n refs.add(ref);\n return ref;\n }", "function createPoint(transform, latDeg, lonDeg) {\n var lat = latDeg * Math.PI/180;\n var lon = lonDeg * Math.PI/180;\n var r = 200;\n var p = new THREE.Vector3(\n -r * Math.cos(lat) * Math.cos(lon),\n r * Math.sin(lat),\n r * Math.cos(lat) * Math.sin(lon)\n );\n var m = transform;\n p = m.multiplyVector3(p);\n var geometry = new THREE.Cube(0.1,0.1,0.01,4,4,4);\n var point = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({\n color: 0xff0000\n }));\n point.lookAt(p);\n point.position = p;\n point.is_a_point = true;\n return point;\n }", "function b2CollideEdgeAndCircle(manifold,\n\t\t\t\t\t\t\t edgeA, xfA,\n\t\t\t\t\t\t\t circleB, xfB)\n{\n\tmanifold.pointCount = 0;\n\n\t// Compute circle in frame of edge\n\tvar Q = b2MulT_t_v2(xfA, b2Mul_t_v2(xfB, circleB.m_p));\n\n\tvar A = edgeA.m_vertex1, B = edgeA.m_vertex2;\n\tvar ex = B.x - A.x;//b2Vec2.Subtract(B, A);\n\tvar ey = B.y - A.y;\n\n\t// Barycentric coordinates\n\tvar u = ex * (B.x - Q.x) + ey * (B.y - Q.y);//b2Dot_v2_v2(e, b2Vec2.Subtract(B, Q));\n\tvar v = ex * (Q.x - A.x) + ey * (Q.y - A.y);//b2Dot_v2_v2(e, b2Vec2.Subtract(Q, A));\n\n\tvar radius = edgeA.m_radius + circleB.m_radius;\n\n\tvar cf = new b2ContactID();\n\tcf.indexB = 0;\n\tcf.typeB = b2ContactID.e_vertex;\n\n\t// Region A\n\tif (v <= 0.0)\n\t{\n\t\tvar P = A;\n\t\tvar dx = Q.x - P.x;//b2Vec2.Subtract(Q, P);\n\t\tvar dy = Q.y - P.y;\n\t\tvar dd = dx * dx + dy * dy;//b2Dot_v2_v2(d, d);\n\t\tif (dd > radius * radius)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t// Is there an edge connected to A?\n\t\tif (edgeA.m_hasVertex0)\n\t\t{\n\t\t\tvar A1 = edgeA.m_vertex0;\n\t\t\tvar B1 = A;\n\t\t\tvar e1x = B1.x - A1.x;//b2Vec2.Subtract(B1, A1);\n\t\t\tvar e1y = B1.y - A1.y;\n\t\t\tvar u1 = e1x * (B1.x - Q.x) + e1y * (B1.y - Q.y);//b2Dot_v2_v2(e1, b2Vec2.Subtract(B1, Q));\n\n\t\t\t// Is the circle in Region AB of the previous edge?\n\t\t\tif (u1 > 0.0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tcf.indexA = 0;\n\t\tcf.typeA = b2ContactID.e_vertex;\n\t\tmanifold.pointCount = 1;\n\t\tmanifold.type = b2Manifold.e_circles;\n\t\tmanifold.localNormal.x = manifold.localNormal.y = 0;\n\t\tmanifold.localPoint.x = P.x;\n\t\tmanifold.localPoint.y = P.y;\n\t\tmanifold.points[0] = new b2ManifoldPoint();\n\t\tmanifold.points[0].id.Assign(cf);\n\t\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\t\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\t\treturn;\n\t}\n\n\t// Region B\n\tif (u <= 0.0)\n\t{\n\t\tvar P = B;\n\t\tvar dx = Q.x - P.x;//b2Vec2.Subtract(Q, P);\n\t\tvar dy = Q.y - P.y;\n\t\tvar dd = dx * dx + dy * dy;//b2Dot_v2_v2(d, d);\n\t\tif (dd > radius * radius)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\t// Is there an edge connected to B?\n\t\tif (edgeA.m_hasVertex3)\n\t\t{\n\t\t\tvar B2 = edgeA.m_vertex3;\n\t\t\tvar A2 = B;\n\t\t\tvar e2x = B2.x - A2.x;//b2Vec2.Subtract(B2, A2);\n\t\t\tvar e2y = B2.y - A2.y;\n\t\t\tvar v2 = e2x * (Q.x - A2.x) + e2y * (Q.y - A2.y);//b2Dot_v2_v2(e2, b2Vec2.Subtract(Q, A2));\n\n\t\t\t// Is the circle in Region AB of the next edge?\n\t\t\tif (v2 > 0.0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tcf.indexA = 1;\n\t\tcf.typeA = b2ContactID.e_vertex;\n\t\tmanifold.pointCount = 1;\n\t\tmanifold.type = b2Manifold.e_circles;\n\t\tmanifold.localNormal.x = manifold.localNormal.y = 0;\n\t\tmanifold.localPoint.x = P.x;\n\t\tmanifold.localPoint.y = P.y;\n\t\tmanifold.points[0] = new b2ManifoldPoint();\n\t\tmanifold.points[0].id.Assign(cf);\n\t\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\t\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n\t\treturn;\n\t}\n\n\t// Region AB\n\tvar den = ex * ex + ey * ey;//b2Dot_v2_v2(e, e);\n'#if @DEBUG';\n\tb2Assert(den > 0.0);\n'#endif';\n\tvar Px = (1.0 / den) * ((u * A.x) + (v * B.x));\n\tvar Py = (1.0 / den) * ((u * A.y) + (v * B.y));//b2Vec2.Multiply((1.0 / den), b2Vec2.Add(b2Vec2.Multiply(u, A), b2Vec2.Multiply(v, B)));\n\tvar dx = Q.x - Px;//b2Vec2.Subtract(Q, P);\n\tvar dy = Q.y - Py;\n\tvar dd = dx * dx + dy * dy;//b2Dot_v2_v2(d, d);\n\tif (dd > radius * radius)\n\t{\n\t\treturn;\n\t}\n\n\tvar nx = -ey;//new b2Vec2(-ey, ex);\n\tvar ny = ex;\n\tif (nx * (Q.x - A.x) + ny * (Q.y - A.y) < 0.0)//b2Dot_v2_v2(n, b2Vec2.Subtract(Q, A)) < 0.0)\n\t{\n\t\tnx = -nx;//.Set(-n.x, -n.y);\n\t\tny = -ny;\n\t}\n\t//n.Normalize();\n\n\tcf.indexA = 0;\n\tcf.typeA = b2ContactID.e_face;\n\tmanifold.pointCount = 1;\n\tmanifold.type = b2Manifold.e_faceA;\n\tmanifold.localNormal.x = nx;\n\tmanifold.localNormal.y = ny;\n\tmanifold.localNormal.Normalize();\n\tmanifold.localPoint.x = A.x;\n\tmanifold.localPoint.y = A.y;\n\tmanifold.points[0] = new b2ManifoldPoint();\n\tmanifold.points[0].id.Assign(cf);\n\tmanifold.points[0].localPoint.x = circleB.m_p.x;\n\tmanifold.points[0].localPoint.y = circleB.m_p.y;\n}", "function Point() {\n\t\tthis.pos\t= new Vector(0, 0);\n\t\tthis.oldPos\t= new Vector(0, 0);\n\t\tthis.a\t\t= new Vector(0, 0);\n\t\tthis.length\t= 0;\n\t}", "function ShapePoint( options )\r\n{\r\n\tthis.instanceType = \"ShapePoint\";\r\n\tthis.x = 0 ;\r\n\tthis.y = 0 ;\r\n\t\r\n\tfor( let prop in options )\r\n\t{\r\n\t\tif( this[prop] != options[prop] )\r\n\t\t\tthis[prop] = options[prop];\r\n\t\t\t\r\n\t}\r\n\t\r\n\tfunction setPoints(x, y){\r\n\t\tthis.x = x ;\r\n\t\tthis.y = y ;\r\n\t}\r\n\tfunction getPoints()\r\n\t{\r\n\t\treturn [this.x, this.y] ;\r\n\t}\r\n}", "assign(centrs) {\n\n let APoints = [],\n BPoints = [];\n\nlet points = this.points;\n points.forEach((val, i) => {\n\n let zerox = points[i].x - centrs[0].x; // distance to 1st centroid\n let zeroy = points[i].y - centrs[0].y;\n let onex = points[i].x - centrs[1].x; // distance to 2nd centroid\n let oney = points[i].y - centrs[1].y;\n\n\n // get posititive of each point from each centroid\n let sqzerox = Math.sqrt(zerox * zerox);\n let sqzeroy = Math.sqrt(zeroy * zeroy);\n let sqonex = Math.sqrt(onex * onex);\n let sqoney = Math.sqrt(oney * oney);\n\n // if the point is within the range (all points have less distance than 110 px to all points) push it to according array\n let ranges = this.getRanges();\n (sqzerox || sqzeroy) < ranges.xrange / 3 ? APoints.push(points[i]) : 0;\n (sqonex || sqoney) < ranges.xrange / 3 ? BPoints.push(points[i]) : 0;\n });\n\n return {\n AP: APoints,\n BP: BPoints\n };\n }", "dotCoordinate(point) {\n return (this.normal.x * point.x +\n this.normal.y * point.y +\n this.normal.z * point.z +\n this.d);\n }", "function pointsToMesh() {\n\n // Sphere radius\n var radius = 0.2;\n\n // Creates the sphere\n var geometry = new THREE.SphereGeometry(radius, 32, 32);\n\n // Empty the global array that holds the mesh objects\n measureObjectsMesh = [];\n\n // Loops through objects, and converts them\n for (var i = 0; i < measureObjects.length; i++) {\n var pointPos = measureObjects[i],\n sx = pointPos.x,\n sy = pointPos.y,\n sz = pointPos.z;\n\n // Sets the material of the sphere, i.e. a default color\n var material = new THREE.MeshBasicMaterial({color: 0x2ae300});\n\n // Creates the mesh, combination of geometry and material\n var sphere = new THREE.Mesh(geometry, material);\n\n // Sets the position\n sphere.position.set(sx, sy, sz);\n\n // Adds the sphere to the array holding the mesh objects\n measureObjectsMesh.push(sphere);\n\n // Adds the sphere to the global group\n group.add(sphere);\n }\n\n // Adds the group to the scene\n scene.add(group);\n}", "function calculateCircle(points) {\n var solVector, a, b, c, circleProp = {};\n \n if (points.length !== 3) {\n return null;\n }\n \n /* Consider the general conic equation:\n *\n * Ax**2 + Bxy + Cy**2 + Dx + Ey + F = 0\n *\n * For a circle, A == C, and B == 0. We can also normalize by dividing by\n * -F. Therefore, the equation of a circle can be expressed as follows\n * (with new A, B, and C):\n *\n * Ax**2 + Ay**2 + Bx + Cy = 1\n *\n * Given three points (x_i, y_i) for 0 <= i < 3, we can create a system of\n * equations to solve for all three coefficients.\n */ \n solVector = solveNormalizedSystem([\n [points[0][0] * points[0][0] + points[0][1] * points[0][1],\n points[0][0], points[0][1]],\n [points[1][0] * points[1][0] + points[1][1] * points[1][1],\n points[1][0], points[1][1]],\n [points[2][0] * points[2][0] + points[2][1] * points[2][1],\n points[2][0], points[2][1]]\n ], 3);\n \n if (!solVector) {\n return null;\n }\n \n /* Extract the coefficients from the solution vector. */\n a = solVector[0]; // x ** 2 and y ** 2 coefficient\n if (!a) {\n // That's a line, silly!\n return null;\n }\n b = solVector[1]; // x coefficient\n c = solVector[2]; // y coefficient\n \n /* Complete the squares to find (h, k)--i.e., the center point. */\n circleProp.xOrigin = -b / (2.0 * a);\n circleProp.yOrigin = -c / (2.0 * a);\n\n /* We complete the square on the RHS. This results in\n * 1 + A(B / (2A)) ** 2 + A(C / (2A)) ** 2\n * Normalizing the equation by dividing A gives the square of the radius\n * on the RHS.\n */\n circleProp.radius = Math.sqrt((1.0 / a + (b * b + c * c) / (4.0 * a * a)));\n if (circleProp.radius > 1e15) {\n // A rare but nasty occurrence where a is almost-but-not-quite zero,\n // resulting in a ridiculously large circle.\n return null;\n }\n circleProp.diameter = circleProp.radius * 2.0;\n \n return circleProp;\n }", "function point(xx,yy){\nthis.x = xx;\nthis.y = yy;\n}", "addPointToPointEntities(name, position) {\n var pointEntity = new Entity({\n name: name,\n position: new ConstantPositionProperty(position),\n billboard: {\n image: this.svgPoint,\n eyeOffset: new Cartesian3(0.0, 0.0, -50.0)\n }\n });\n this.pointEntities.entities.add(pointEntity);\n this.dragHelper.updateDraggableObjects(this.pointEntities);\n if (isDefined(this.onPointClicked)) {\n this.onPointClicked(this.pointEntities);\n }\n }", "transform (m) {\r\n const points = [];\r\n\r\n for (let i = 0; i < this.length; i++) {\r\n const point = this[i];\r\n // Perform the matrix multiplication\r\n points.push([\r\n m.a * point[0] + m.c * point[1] + m.e,\r\n m.b * point[0] + m.d * point[1] + m.f\r\n ]);\r\n }\r\n\r\n // Return the required point\r\n return new PointArray(points)\r\n }", "extractPoints(e) {\n return {\n shape: this.getPoints(e),\n holes: this.getPointsHoles(e)\n };\n }", "function PHSK_MutateSinglePoint( mutationParallelPoint) {\n\twireM[mutationParallelPoint] = GMTR_MutateVector(wire[mutationParallelPoint], muteRange);\n\treturn 0;\n}", "function find_perfect_center(xy_data){\n let x = Vector.transpose(Vector.pull(xy_data,[0,xy_data.length-1], [0, 0]))\n let y = Vector.transpose(Vector.pull(xy_data,[0,xy_data.length-1], [1, 1]))\n let x_bounds = [Vector.min(x), Vector.max(x)]\n let y_bounds = [Vector.min(y), Vector.max(y)]\n let mesh = generate_mesh(x_bounds, y_bounds, 6)\n //out(mesh)\n //out(xy_data)\n let inside_mesh = []\n for(let i = 0; i < mesh.length; i++){\n if(is_inside(xy_data, mesh[i])){\n inside_mesh.push(mesh[i])\n }\n }\n //out(inside_mesh)\n\n return center_calc(xy_data, inside_mesh)\n}", "function calculateEllipse(points) {\n var solVector, a, b, c, d, e, aPrime, cPrime, dPrime, ePrime,\n theta, xOffset, yOffset, cosTheta, sinTheta, cosThetaSquared,\n sinThetaSquared, normalizer, tmp, ellipseProp = {},\n xOriginPrime, yOriginPrime, hypotenuse;\n\n if (points.length !== 5) {\n return null;\n }\n\n /* Set up a system of five linear systems based on the set of\n * five provided points. Each equation has the following form:\n *\n * Ax**2 + Bxy + Cy**2 + Dx + Ey = 1\n *\n * Given a defined (x, y) = (x_n, y_n), each equation resolves to a\n * linear equation (and system homogeneity enables us to normalize the\n * unshown constant onto the right side to correlate with the canonical\n * ellipse equation).\n */\n solVector = solveNormalizedSystem([ \n [points[0][0] * points[0][0], points[0][0] * points[0][1],\n points[0][1] * points[0][1], points[0][0], points[0][1]],\n [points[1][0] * points[1][0], points[1][0] * points[1][1],\n points[1][1] * points[1][1], points[1][0], points[1][1]],\n [points[2][0] * points[2][0], points[2][0] * points[2][1],\n points[2][1] * points[2][1], points[2][0], points[2][1]],\n [points[3][0] * points[3][0], points[3][0] * points[3][1],\n points[3][1] * points[3][1], points[3][0], points[3][1]],\n [points[4][0] * points[4][0], points[4][0] * points[4][1],\n points[4][1] * points[4][1], points[4][0], points[4][1]]\n ], 5);\n\n if (!solVector) {\n return null;\n }\n \n /* Extract the coefficients from the solution vector. */\n a = solVector[0]; // x ** 2 coefficient\n b = solVector[1]; // x * y coefficient\n c = solVector[2]; // y ** 2 coefficient\n d = solVector[3]; // x coefficient\n e = solVector[4]; // y coefficient\n \n /* Quickly test whether the object is an ellipse or degenerate\n * variant, based on the discriminant. There's a more thorough\n * test for degenerates, too. (See Wikipedia's Ellipse article.)\n * However, I do not deem it optimal here since that would be\n * the minority of applied cases.\n */\n if (!a || !c || b * b - 4.0 * a * c >= 0) {\n return null;\n }\n\n /* If B != 0, then the ellipse in question is not in its canonical\n * orientation; that is, it is rotated. The canonical equation of\n * the ellipse can be achieved from a rotated coordinated system,\n * corresponding to the equation A'x'**2 + C'y'**2 + D'x' + E'y' = 1.\n * From right-angle trigonometry, the following transforms are\n * derived for all (x, y) in the original coordinate system and for\n * all (x', y') in the rotated coordinate system:\n *\n * x = x' * cos(theta) - y' * sin(theta)\n * y = x' * sin(theta) + y' * cos(theta)\n *\n * When one returns to the original equation with the original five\n * coefficients, x and y may be substituted with the above. In the\n * transformed equation, the x'y' term has an implied zero coefficient.\n * (That is, B' = 0.) When the x'y' terms are combined, the following\n * equation is derived.\n *\n * 0 = -2 * A * sin(theta) * cos(theta) + 2 * C * sin(theta) +\n * cos(theta) + B * (cos(theta))**2 - B * (sin(theta))**2\n * = (C - A) * sin(2 * theta) + B * cos(2 * theta)\n * => (A - C) * sin(2 * theta) = B * cos(2 * theta)\n * => tan(2 * theta) = B / (A - C)\n *\n * Therefore:\n * theta = atan(b / (a - c)) / 2 for a - c != 0.\n *\n * If a - c = 0, we take the principal limit of atan(x) / 2\n * as x -> Infinity and find theta = PI / 4.\n */\n theta = ellipseProp.theta =\n (a - c) ? Math.atan(b / (a - c)) / 2.0 : Math.PI / 4.0;\n\n /* Use right-triangle derived-identities relating the arctangent to\n * the sine and cosine of theta, and combine with the half-angle\n * identities. It probably does just as well just to call\n * Math.cos() and Math.sin(), but this looks cooler (and is\n * theoretically a bit more precise, in particular for the squares).\n */\n hypotenuse = Math.sqrt((a - c) * (a - c) + b * b);\n tmp = Math.abs((a - c) / (2.0 * hypotenuse)); // cos(theta * 2) / 2\n cosThetaSquared = 0.5 + tmp;\n cosTheta = Math.sqrt(cosThetaSquared);\n sinThetaSquared = 0.5 - tmp;\n sinTheta = Math.sqrt(sinThetaSquared);\n if (theta < 0) {\n sinTheta = -sinTheta;\n }\n\n /* With the aforementioned coordinate system transform, we are now\n * poised to find the major and minor axis lengths for the ellipse in\n * question. We first determine the values of A', D', C', and E' in\n * the above equation. This can be straightforwardly done by combining\n * like terms and comparing coefficients as before.\n */\n tmp = b * cosTheta * sinTheta; // B * sin(theta) * cos(theta)\n aPrime = a * cosThetaSquared + c * sinThetaSquared + tmp;\n dPrime = d * cosTheta + e * sinTheta;\n cPrime = a * sinThetaSquared + c * cosThetaSquared - tmp;\n ePrime = -d * sinTheta + e * cosTheta;\n\n /* We are now poised to calculate the ellipse's canonical form. We\n * complete the squares to calculate the offsets and then convert\n * back to the previous coordinate system.\n */\n xOriginPrime = -dPrime / (2.0 * aPrime);\n yOriginPrime = -ePrime / (2.0 * cPrime);\n ellipseProp.xOrigin = xOriginPrime * cosTheta -\n yOriginPrime * sinTheta;\n ellipseProp.yOrigin = xOriginPrime * sinTheta +\n yOriginPrime * cosTheta;\n\n /* We now balance the equation with the squares of the origins and\n * divide. The coefficients of the x ** 2 and y ** 2 terms are the\n * inverse of a ** 2 and b ** 2 in the canonical ellipse formula. The\n * principal square roots are therefore half of the width and half of\n * the height, respectively. xOrigin ** 2 * aPrime and\n * yOrigin ** 2 * cPrime are expanded here for precision.\n */\n normalizer = 1.0 + dPrime * dPrime / (4.0 * aPrime) + \n ePrime * ePrime / (4.0 * cPrime);\n ellipseProp.halfWidth = Math.sqrt(normalizer / aPrime);\n ellipseProp.halfHeight = Math.sqrt(normalizer / cPrime);\n ellipseProp.width = ellipseProp.halfWidth * 2.0;\n ellipseProp.height = ellipseProp.halfHeight * 2.0;\n\n return ellipseProp;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Div element for all the midi options for the track
function elemTrackMidiOptions(track_element) { var track_midi_options = document.createElement("div"); track_midi_options.id = "track_midi_options_" + track_element.track_num; // create a list of output midi device names var device_names = [] for (const device of track_element.device_list) { device_names.push(device.name); } // create the device selector var track_device_element = "track_device_" + track_element.track_num; track_device_element = _createSelectionList( track_device_element, device_names, track_element.deviceSelectedCallback, "Choose a MIDI device." ) track_midi_options.appendChild(track_device_element); // create the channel selector var track_channel_element = "track_channel_" + track_element.track_num; track_channel_element = _createSelectionList( track_channel_element, midi_channel_options, track_element.deviceSelectedCallback, ) track_midi_options.appendChild(track_channel_element); return track_midi_options; }
[ "function trackMidiSelected(track_element) {\n // get the selectede midi options\n const device_idx = getUserSelection(\"track_device_\" + track_element.track_num) - 1;\n const channel_idx = getUserSelection(\"track_channel_\" + track_element.track_num);\n const device = track_element.device_list[device_idx];\n const channel = midi_channel_options[channel_idx];\n\n // now apply it to the track object\n track_element.track.setDevice(device);\n track_element.track.setChannel(channel);\n}", "function immediateRenderChord(MIDINumbers, duration = \"\"){\n\tmusicalElements = \"[\";\n\tfor(var i = 0; i < MIDINumbers.length; i++){\n\t\tmusicalElements += MIDINotes.MIDINoteToABCNote(MIDINumbers[i]) + duration + \" \";\n\t}\n\tmusicalElements += \"]\";\n\t\n\trenderNotation();\n}", "function setMIDIChord(MIDINumbers, duration = \"\"){\n\tmusicalElements += \"[\"\n\tfor(var i = 0; i < MIDINumbers.length; i++){\n\t\tmusicalElements += MIDINotes.MIDINoteToABCNote(MIDINumbers[i]) + duration + \" \";\n\t}\n\tmusicalElements += \"] \";\n}", "initMidi() {\n this.midi = new WebMIDIInterface({_outputSelector:\n this.midiOutputSelector});\n this.midi.init();\n }", "function setHtmlSlider(){\n\t\t\n\t\t//get if the slide has controls\n\t\tvar loaderClass = getLoaderClass();\n\t\tvar galleryOptions = g_gallery.getOptions();\n\t\t\n\t\tvar html = \"<div class='ug-slider-wrapper'>\";\n\t\t\n\t\thtml += \"<div class='ug-slider-inner'>\";\n\t\thtml += getHtmlSlide(loaderClass,1);\n\t\thtml += getHtmlSlide(loaderClass,2);\n\t\thtml += getHtmlSlide(loaderClass,3);\n\t\t\t\t\n\t\thtml += \"</div>\";\t//end inner\n\t\t\n\t\t//----------------\n\t\t\t\t\n\t\t//add arrows\n\t\tif(g_options.slider_enable_arrows == true){\n\t\t\thtml += \"<div class='ug-slider-control ug-arrow-left ug-skin-\"+g_options.slider_arrows_skin+\"'></div>\";\n\t\t\thtml += \"<div class='ug-slider-control ug-arrow-right ug-skin-\"+g_options.slider_arrows_skin+\"'></div>\";\n\t\t}\n\t\t\n\t\t//add play button\n\t\tif(g_options.slider_enable_play_button == true){\n\t\t\thtml += \"<div class='ug-slider-control ug-button-play ug-skin-\"+g_options.slider_play_button_skin+\"'></div>\";\n\t\t}\n\t\t\n\t\t//add fullscreen button\n\t\tif(g_options.slider_enable_fullscreen_button == true){\n\t\t\thtml += \"<div class='ug-slider-control ug-button-fullscreen ug-skin-\"+g_options.slider_fullscreen_button_skin+\"'></div>\";\n\t\t}\n\t\t\n\t\t\n\t\thtml +=\t\"</div>\";\t//end slider\n\t\t\n\t\t\n\t\tg_objWrapper.append(html);\n\t\t\n\t\t//----------------\n\t\t\n\t\t//set objects\n\t\tg_objSlider = g_objWrapper.children(\".ug-slider-wrapper\");\n\t\tg_objInner = g_objSlider.children(\".ug-slider-inner\");\n\t\t\n\t\t\n\t\tg_objSlide1 = g_objInner.children(\".ug-slide1\");\n\t\tg_objSlide2 = g_objInner.children(\".ug-slide2\");\n\t\tg_objSlide3 = g_objInner.children(\".ug-slide3\");\n\t\t\n\t\t//set slides data\n\t\tg_objSlide1.data(\"slidenum\",1);\n\t\tg_objSlide2.data(\"slidenum\",2);\n\t\tg_objSlide3.data(\"slidenum\",3);\n\t\t\t\t\n\t\t//add bullets\n\t\tif(g_objBullets)\n\t\t\tg_objBullets.appendHTML(g_objSlider);\n\t\t\n\t\t//----------------\n\t\t\n\t\t//get arrows object\n\t\tif(g_options.slider_enable_arrows == true){\n\t\t\tg_objArrowLeft = g_objSlider.children(\".ug-arrow-left\");\n\t\t\tg_objArrowRight = g_objSlider.children(\".ug-arrow-right\");\n\t\t}\n\t\t\t\t\n\t\t//get play button\n\t\tif(g_options.slider_enable_play_button == true){\n\t\t\tg_objButtonPlay = g_objSlider.children(\".ug-button-play\");\n\t\t}\n\t\t\n\t\t//get fullscreen button\n\t\tif(g_options.slider_enable_fullscreen_button == true){\n\t\t\tg_objButtonFullscreen = g_objSlider.children(\".ug-button-fullscreen\");\n\t\t}\n\t\t\n\t\t\n\t\t//----------------\n\t\t\n\t\t//add progress indicator\n\t\tif(g_options.slider_enable_progress_indicator == true){\n\t\t\t\n\t\t\tg_objProgress = g_functions.initProgressIndicator(g_options.slider_progress_indicator_type, g_options, g_objSlider);\n\t\t\t\n\t\t\tvar finalType = g_objProgress.getType();\n\t\t\t\n\t\t\t//change options in case of type change\n\t\t\tif(finalType == \"bar\" && g_options.slider_progress_indicator_type == \"pie\"){\n\t\t\t\tg_options.slider_progress_indicator_type = \"bar\";\n\t\t\t\tg_options = jQuery.extend(g_options, g_defaultsProgressBar);\n\t\t\t}\t\n\t\t\t\n\t\t\tg_gallery.setProgressIndicator(g_objProgress);\n\t\t}\n\t\t\n\t\t//----------------\n\t\t\n\t\t//add text panel (hidden)\n\t\tif(g_options.slider_enable_text_panel == true){\n\t\t\t\n\t\t\t//add panel to controls:\n\t\t\tif(g_options.slider_textpanel_always_on == false && hasControls == true && g_options.slider_controls_always_on == false)\n\t\t\t\tg_objTextPanel.appendHTML(g_objSlider);\n\t\t\telse{\t//add panel to slider\n\t\t\t\t\n\t\t\t\tg_objTextPanel.appendHTML(g_objSlider);\n\t\t\t\t\t\t\t\t\n\t\t\t\t//hide panel saparatelly from the controls object\n\t\t\t\tif(g_options.slider_textpanel_always_on == false){\n\t\t\t\t\t\n\t\t\t\t\t//hide the panel\n\t\t\t\t\tvar panelElement = g_objTextPanel.getElement();\n\t\t\t\t\tpanelElement.hide().data(\"isHidden\", true);\n\n\t\t\t\t\tg_temp.isTextPanelSaparateHover = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t//----------------\n\t\t\n\t\t//add zoom buttons panel:\n\t\tif(g_options.slider_enable_zoom_panel == true){\n\t\t\tg_objZoomPanel.appendHTML(g_objSlider);\n\t\t}\n\t\n\t\t\n\t\t//add video player\n\t\tg_objVideoPlayer.setHtml(g_objSlider);\n\t}", "pulse_midi_clock() {\n this.midi_clock.send([0xf8]);\n }", "render() {\n let html = \"<div class=\\\"smarthome-device\\\" id='\" + this.id + \"'>\" + this.getInnerHtml() + \"</div>\";\n this.controlPanel.append(html);\n this.self = this.controlPanel.find(this.selector);\n }", "function showTrackDuration(audioId) {\n var oO = \"\";\n if((document.getElementById(audioId).duration % 60) < 10) {\n oO = \"0\";\n }\n var dur = document.getElementById(audioId).duration;\n var mins = Math.floor(dur / 60);\n var secs = Math.floor(dur % 60);\n document.getElementById(\"track1Duration\").innerHTML = mins + \":\" + oO + secs;\n}", "function showInfo() {\n\tif (DEFDESCR) {\n\t\taddedby=$(\".queue_active\").attr(\"title\");\n\t\tduration=$(\".queue_active .qe_time\").html();\n\t\t$_mediainfo.html(addedby+' ['+duration+']');\t\n\t} else {\n\t\tvar arr=new Array();\n\t\ttext='Playing Next:';\n\t\tli1=$(\".queue_active\").next();\n\t\tli2=li1.next();\n\t\tli3=li2.next();\n\t\tli1.length>0 ? arr.push(' • [1]▸ '+li1.children(\"a\").html()) : '';\n\t\tli2.length>0 ? arr.push(' • [2]▸ '+li2.children(\"a\").html()) : '';\n\t\tli3.length>0 ? arr.push(' • [3]▸ '+li3.children(\"a\").html()) : '';\n\t\ttext+=arr.join(\"\");\n\t\tarr.length<3 ? text+=' • END OF PLAYLIST' : '';\n\t\t$_mediainfo.html('<marquee scrollamount=\"5\">'+text+'</marquee>');\n\t}\t\n}", "function createControlElement(detailsDiv, title, waveformURL, previewURL){\n\tvar controlDiv = $('<div id=\"controlDiv\"></div>').appendTo(detailsDiv);\n\t//create play stop and fav buttons and append to controlDiv\n\t$('<button class=\"controlButtons playIco\" onclick=\"playAudio(0)\" alt=\"Play\"><i class=\"fas fa-play\"></i></button>').appendTo(controlDiv);\n\t$('<button class=\"controlButtons stopIco\" onclick=\"stopAudio(0)\" alt=\"Stop\"><i class=\"fas fa-stop\"></i></button>').appendTo(controlDiv);\n\t$('<button class=\"controlButtons favIco\" onclick=\"favAudio()\" alt=\"Fav\"><i class=\"fas fa-star\"></i></button>').appendTo(controlDiv);\n\t//store variables in session - for use in favourite\n\tsessionStorage.setItem(\"title\", title);\n\tsessionStorage.setItem(\"image\", waveformURL);\n\tsessionStorage.setItem(\"sound\", previewURL);\n}", "function show_diy_note()\n{\n\tvar current_step = $(\".chalk_player video\").attr(\"data-diy-step\");\n\t/*pause video*/\n\tcp_mediaPlayer.pause();\n\t/*show note*/\n\t$(\".chalk_player .diy_wrapper .content_wrapper,.chalk_player .diy_wrapper .diy_content[data-diy-step='\"+current_step+\"'],.chalk_player .diy_wrapper .steps_container\").removeClass(\"hidden\");\n\t$(\".chalk_player video\").attr(\"data-diy-step-show\",\"1\");\n}", "render() {\n if (this.selected) {\n // If selected, fill the note as such and ignore everything else.\n this.fill(SELECTED);\n this.opacity(1);\n } else {\n if (this.playing) {\n // If the note is playing, fill the note as such.\n this.fill(PLAYING);\n } else {\n // Otherwise, check if the note is suggested.\n if (this.suggested) {\n this.fill(SUGGESTED, true);\n } else {\n this.fill(NORMAL);\n }\n }\n // If the note is being hovered over, alter its opacity.\n if (this.hovered) {\n this.opacity(0.65);\n } else {\n this.opacity(1);\n }\n }\n }", "function drawOptions() {\n\t\t\tvar ui = newElement('div', { id: 'adi-opts-view', class: 'adi-hidden' }),\n\t\t\t\thead1 = newElement('span', { class: 'adi-opt-heading' }),\n\t\t\t\thead2 = newElement('span', { class: 'adi-opt-heading' }),\n\t\t\t\tclose = newElement('span', { class: 'adi-opt-close' });\n\n\t\t\thead1.textContent = 'General options';\n\t\t\thead2.textContent = 'Observed nodes';\n\n\t\t\tui.appendChild(head1);\n\t\t\tui.appendChild(drawOptionRow('saving', 'Enable saving of settings'));\n\t\t\tui.appendChild(drawOptionRow('makeVisible', 'Scroll to the active element in DOM View'));\n\t\t\tui.appendChild(drawOptionRow('omitEmptyText', 'Hide empty text nodes'));\n\t\t\tui.appendChild(drawOptionRow('foldText', 'Fold the text nodes'));\n\t\t\tui.appendChild(drawOptionRow('transparent', 'Enable transparent background'));\n\t\t\tui.appendChild(head2);\n\t\t\tui.appendChild(drawOptionRow('nodeTypes-3', 'Text node'));\n\t\t\tui.appendChild(drawOptionRow('nodeTypes-8', 'Comment node'));\n\t\t\t// ui.appendChild(drawOptionRow('nodeTypes-1', 'Element node'));\n\t\t\t// ui.appendChild(drawOptionRow('nodeTypes-9', 'Document node'));\n\t\t\tui.appendChild(close);\n\n\t\t\treturn ui;\n\t\t}", "function MediaPlayer(config){ \n this.media = config.el;\n }", "render() {\n\t\treturn (\n\t\t\t<div className=\"note\">\n\t\t\t\t{this.state.notes}\n\t\t\t</div>\n\t\t);\n\t}", "createItems () {\n let items = []\n // if there's only one audio track, there no point in showing it\n this.hideThreshold_ = 1;\n\n const tracks = this.player_.audioTracks();\n\n for (let i = 0; i < tracks.length; i++) {\n const track = tracks[i];\n\n items.push(new AudioTrackMenuItem(this.player_, {\n track,\n // MenuItem is selectable\n selectable: true\n }));\n }\n\n return items;\n\n /*let items = []\n items.push(new AudioTrackMenuItem(this.player_, {\n label: this.controlText_,\n selectable: false\n }))\n\n let tracks = this.player_.audioTracks()\n\n if (!tracks) {\n return items\n }\n\n if (tracks.length < 2) {\n this.hide()\n return items\n }\n\n for (let i = 0; i < tracks.length; i++) {\n let track = tracks[i]\n\n // only add tracks that are of the appropriate kind and have a label\n if (track['kind'] === 'main') {\n items.push(new AudioTrackMenuItem(this.player_, {\n // MenuItem is selectable\n 'selectable': true,\n 'track': track\n }))\n }\n }\n\n return items*/\n }", "function iq_display_config_html()\n{\n ext_config_html(iq, 'iq_display', 'IQ', 'IQ display configuration');\n}", "setActionOptions() {\n const actionUuid = this.actionUuid;\n log(`Setting visibility for \"${actionUuid}\" elements, if necessary.`);\n\n const showElements = [];\n\n if(!this.globalSettings || !this.globalSettings.roonHostname || !this.globalSettings.roonPort) {\n document.getElementById(\"roon-core\").open = true;\n }\n\n switch(actionUuid) {\n case \"net.bliny.roon.play-pause\":\n case \"net.bliny.roon.play\":\n showElements.push(document.getElementById(\"roon-play-options-item\"));\n break;\n case \"net.bliny.roon.play-item\":\n this.onPlayItemTypeChanged(this.settings.itemType);\n showElements.push(document.getElementById(\"roon-play-item-item\"));\n showElements.push(document.getElementById(\"play-item-title-item\"));\n showElements.push(document.getElementById(\"play-item-type-album\"));\n showElements.push(document.getElementById(\"play-item-type-artist\"));\n showElements.push(document.getElementById(\"play-item-type-composer\"));\n showElements.push(document.getElementById(\"play-item-type-radio\"));\n showElements.push(document.getElementById(\"play-item-type-genre\"));\n showElements.push(document.getElementById(\"play-item-type-playlist\"));\n showElements.push(document.getElementById(\"play-item-type-tag\"));\n break;\n case \"net.bliny.roon.play-this\":\n this.onPlayItemTypeChanged(this.settings.itemType);\n showElements.push(document.getElementById(\"roon-play-item-item\"));\n showElements.push(document.getElementById(\"play-item-type-album\"));\n showElements.push(document.getElementById(\"play-item-type-artist\"));\n break;\n case \"net.bliny.roon.mute\":\n case \"net.bliny.roon.mute-unmute\":\n case \"net.bliny.roon.volume-up\":\n case \"net.bliny.roon.volume-down\":\n this.setVolumeOptions();\n break;\n case \"net.bliny.roon.volume-set\":\n showElements.push(document.getElementById(\"roon-volume-set-item\"));\n this.setVolumeSetOptions();\n this.setVolumeOptions();\n break;\n }\n\n showElements.forEach((showElement) => showElement.classList.remove(\"hidden\"));\n }", "labelCurrentTrack() {\n\t\tlet labl = 'empty';\n\t\tif (this.trks[tpos].usedInstruments.length === 1) {\n\t\t\tif (this.trks[tpos].hasPercussion) {\n\t\t\t\tlabl = 'Percussion';\n\t\t\t} else {\n\t\t\t\tlabl = getInstrumentLabel(this.trks[tpos].usedInstruments[0]);\n\t\t\t}\n\t\t} else if (this.trks[tpos].usedInstruments.length > 1) {\n\t\t\tlabl = 'Mixed Track';\n\t\t}\n\t\tthis.trks[tpos].label = `${labl} ${this.getLabelNumber(labl)}`;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new stock data for redrawing chart
addStockToChart(symbol, data) { this.stockChart.addSeries({ name: symbol, data: data }); }
[ "getStock(stockSymbol) {\n stockService.data(stockSymbol, (err, data) => {\n if (err) return this.handleError(err);\n\n const stock = JSON.parse(data);\n let stockData = stock.data.reverse().map(info => {\n return [\n (new Date(info[0])).getTime(),\n info[1]\n ]\n });\n\n // update chart with new data\n this.addStockToChart(stockSymbol, stockData);\n\n this.addStockToStockTable(stock.company, stock.symbol);\n });\n }", "function addDataToCharts(data)\n{\n\t// Probably a better way to do this\n\tif (data.length != 0) {\n\tif (data[data.length-1].timekey.substring(11,16) == totalChart.datasets[0].points[totalChart.datasets[0].points.length-1].label)\n\t{\n\t\t/*console.log(\"den siste labelen er : \" + totalChart.datasets[0].points[totalChart.datasets[0].points.length-1].label)*/\n\t\ttotalChart.update();\n\t}\n\telse\n\t{\n\t\ttotalChart.addData([data[data.length-1].total],data[data.length-1].timekey.substring(11,16));\n\t\tvar totalDataLength = totalChart.datasets[0].points.length-2;\n\t\ttotalChart.datasets[0].points[totalDataLength].value = data[data.length-2].total;\n\t\ttotalChart.update();\n\t\t/*totalChart.removeData();*/\n\t}\n}\n\t//FABFIVE: try to update labels automatically when new data arrives.\n\t//updateLabels(data);\n}", "function addStockRefresh(beverage) {\n addBeverage(beverage);\n loadMgrEditStock();\n loadCategoryDropdown();\n}", "function onRefresh3() {\n\tconfig3.data.datasets.forEach(function (dataset) {\n\t\tdataset.data.push({\n\t\t\tx: Date.now(),\n\t\t\ty: powerGenerate_real_2\n\t\t});\n\t});\n}", "function setLineChart(stockData) {\n const lineChart = echarts.init(document.querySelector('#lineChartContainer'));\n let volData = [];\n let closeData = [];\n let dates = [];\n for (let i = 0; i < stockData.length; i += 1) {\n volData.push(stockData[i].volume);\n closeData.push(stockData[i].close);\n dates.push(stockData[i].date);\n }\n const chart = {\n tooltip: {},\n legend: { data: ['Volume', 'Close'] },\n xAxis: { data: dates},\n yAxis: [{\n type: 'value',\n name: 'Volume',\n }, {\n type: 'value',\n name: 'Close',\n splitLine: {\n show: false\n }\n }],\n grid: {\n containLabel: true,\n left: 20,\n top: 40,\n right: 20,\n bottom: 0\n },\n series: [{\n name: 'Volume',\n type: 'line',\n data: volData\n }, {\n name: 'Close',\n type: 'line',\n yAxisIndex: 1,\n data: closeData\n }],\n };\n lineChart.setOption(chart);\n window.addEventListener('resize', () => { lineChart.resize() });\n }", "function setCandlestickChart(stockData) {\n const candlestickChart = echarts.init(document.querySelector('#candlestickChartContainer'));\n const openData = stockData.map(stock => stock.open);\n const closeData = stockData.map(stock => stock.close);\n const lowData = stockData.map(stock => stock.low);\n const highData = stockData.map(stock => stock.high);\n const chart = {\n tooltip: {},\n xAxis: {\n data: ['Average', 'Minimum', 'Maximum']\n },\n yAxis: {},\n grid: { \n containLabel: true,\n left: 0,\n top: 40,\n right: 0,\n bottom: 0\n },\n series: [{\n type: 'k',\n data: [\n [average(openData), average(closeData), average(lowData), average(highData)],\n [minimum(openData), minimum(closeData), minimum(lowData), minimum(highData)],\n [maximum(openData), maximum(closeData), maximum(lowData), maximum(highData)]\n ]\n }]\n }\n candlestickChart.setOption(chart);\n window.addEventListener('resize', () => { candlestickChart.resize() });\n }", "function updateChart(x,y) {\n // add new point\n var style = 'point { size: 10; fill-color: #4a148c; }' ;\n var point=[ x , y , style ];\n data.addRow([ x, y, style ]);\n // if too many points, remove oldest one\n var numPoints = data.getNumberOfRows();\n if (numPoints > 1) data.removeRow(0);\n // redraw chart\n chart.draw(data, options);\n}", "function trend_periodically_update_graph () {\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/dashboard/trend_data',\n\t\tdataType: 'json',\n\t\tsuccess: trend_generate_graph\n\t});\n}", "function updateBidChart() {\r\n\t\t\t\t\tupdateBidChart2();\r\n\t\t\t\t}", "function chartPoint(data, symbol) {\n chartsymbol = symbol + '_updatedchart';\n if (Number(data)) {\n chartentry[symbol] = [time, Number(data)];\n io.sockets.emit(chartsymbol, chartentry[symbol]);\n //console.log(chartsymbol + ':' + chartentry[symbol]);\n }\n}", "function chartUpdate(config) {\n // Is it valid?\n if (config == null)\n return;\n\n // Generate the URL\n var base_url = config.data_url || window.location + \"/data.json\";\n var call_url = base_url + \"?resume=\" + config.resume\n if (config.last_id != \"\") {\n call_url = call_url + \"&last=\" + config.last_id;\n }\n if (config.points_limit != undefined) {\n call_url += \"&limit=\" + config.points_limit\n }\n\n // Do the API call\n $.getJSON(call_url).success(function(data){\n if (config.chart.series[0].data.length == 0) {\n var chartData = [];\n\n for (var i = data.length-1; i >= 0; i--)\n chartData.push([data[i].date*1000, data[i].result]);\n\n var chart = $(config.container).highcharts();\n chart.series[0].setData(chartData);\n }\n else {\n for (var i = 0; i < data.length-1; i++) {\n // Do we need to remove the first point in the chart?\n if ((config.points_limit != undefined) && (config.chart.series[0].data.count > config.points_limit))\n config.chart.series[0].addPoint([data[i].date*1000, data[i].result], false, true);\n else\n config.chart.series[0].addPoint([data[i].date*1000, data[i].result], false);\n }\n }\n\n // If there is data received, save the lastest id.\n if (data.length > 0)\n config.last_id = data[0].id;\n\n // 10 msec later, print the latest point.\n // This code is to solve a bug with the rangeSelector of HighStock\n setTimeout(function() {\n if (data.length > 0)\n config.chart.series[0].addPoint([data[data.length-1].date*1000, data[data.length-1].result], false);\n\n config.chart.redraw();\n config.chart.hideLoading();\n }, 10);\n });\n\n // Redraw the chart\n config.chart.redraw();\n}", "function fillJsonDataTimeseries(financeDataJson, _div_id, _text_id) {\n\n var financeData = toDataJsonTimeseries(financeDataJson, true);\n var container = document.getElementById(_div_id), options;\n\n $('#' + _text_id).text(financeDataJson.dataset.name + \":\");\n\n options = {\n container : container,\n data : {\n detail : financeData.price,\n summary : financeData.price\n },\n // An initial selection\n selection : {\n data : {\n x : {\n min : 100,\n max : 200\n }\n }\n }\n };\n\n chart = new envision.templates.TimeSeries(options);\n\n window.onresize = function (event) {\n chart.vis.components.forEach(function(component){\n component.draw();\n $(\".envision-timeseries-connection\").find(\"canvas\").hide();\n $('#' + _div_id).css(\"background\",\"none\");\n });\n };\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}", "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 }", "isAdded(stockSymbol) {\n return this.stockChart.series.some((series) => {\n return series.name === stockSymbol.toUpperCase();\n });\n }", "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 }", "init() {\n const series = this.chartData.series;\n const seriesKeys = Object.keys(series);\n\n for (let ix = 0, ixLen = seriesKeys.length; ix < ixLen; ix++) {\n this.addSeries(seriesKeys[ix], series[seriesKeys[ix]]);\n }\n\n if (this.chartData.data.length) {\n this.createChartDataSet();\n }\n }", "removeStockFromChart(symbol) {\n for (let i = 0, n = this.stockChart.series.length; i < n; i++) {\n const series = this.stockChart.series[i];\n if (series.name === symbol) {\n this.stockChart.series[i].remove();\n return;\n }\n }\n }", "function createVolumeChart() {\n $('#AlertsPerformance_WeekViews_VolumeChart').highcharts('StockChart', {\n chart: {\n height: 250,\n marginLeft: 35,\n marginRight: 45\n },\n title:{\n text: 'Overall Trend'\n },\n credits: {\n enabled: false\n },\n navigator: {\n enabled: true\n },\n scrollbar: {\n enabled: false\n },\n rangeSelector: {\n enabled: false\n },\n colors: ['#e69900', '#9c3', '#69c', '#669', '#d9534f'],\n navigation: {\n buttonOptions: {\n enabled: true\n }\n },\n plotOptions: {\n series: {\n shadow: true\n }\n },\n // xAxis: {\n // type: 'datetime',\n // dateTimeLabelFormats: {\n // day: '%m/%d/%y'\n // },\n // },\n yAxis: [{\n min: 0,\n // max: 30,\n labels: {\n formatter: function() {\n return (this.value);\n },\n align: 'right',\n x: -3,\n y: 3\n },\n gridLineColor: '#efefef',\n lineWidth: 1,\n lineColor: '#efefef',\n // tickPositions: [0, 5, 10, 15, 20, 25, 30],\n minPadding: 0,\n maxPadding: 0.15,\n showFirstLabel: false,\n showLastLabel: false,\n startOnTick: false,\n endOnTick: false\n }],\n tooltip: {\n pointFormat: '<span style=\"color:{series.color};font-weight:bold;\">{series.name}</span>: {point.y} Cases<br/>',\n valueDecimals: 0\n },\n series: volumeWeekSeriesOptions\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================== Patching ================================ [ patchStyleSheet() ] Scans the passed cssText for selectors that require emulation and creates one or more patches for each matched selector.
function patchStyleSheet( cssText ) { return cssText.replace(RE_PSEUDO_ELEMENTS, PLACEHOLDER_STRING). replace(RE_SELECTOR_GROUP, function(m, prefix, selectorText) { var selectorGroups = selectorText.split(","); for (var c = 0, cs = selectorGroups.length; c < cs; c++) { var selector = normalizeSelectorWhitespace(selectorGroups[c]) + SPACE_STRING; var patches = []; selectorGroups[c] = selector.replace(RE_SELECTOR_PARSE, function(match, combinator, pseudo, attribute, index) { if (combinator) { if (patches.length>0) { applyPatches( selector.substring(0, index), patches ); patches = []; } return combinator; } else { var patch = (pseudo) ? patchPseudoClass( pseudo ) : patchAttribute( attribute ); if (patch) { patches.push(patch); return "." + patch.className; } return match; } } ); } return prefix + selectorGroups.join(","); }); }
[ "function applyPatches(uniDiff, options) {\n\t if (typeof uniDiff === 'string') {\n\t uniDiff = (0, _parse.parsePatch) (uniDiff);\n\t }\n\t\n\t var currentIndex = 0;\n\t function processIndex() {\n\t var index = uniDiff[currentIndex++];\n\t if (!index) {\n\t return options.complete();\n\t }\n\t\n\t options.loadFile(index, function (err, data) {\n\t if (err) {\n\t return options.complete(err);\n\t }\n\t\n\t var updatedContent = applyPatch(data, index, options);\n\t options.patched(index, updatedContent, function (err) {\n\t if (err) {\n\t return options.complete(err);\n\t }\n\t\n\t processIndex();\n\t });\n\t });\n\t }\n\t processIndex();\n\t}", "setSelector(selectorText){\n if (typeof selectorText !== \"string\") throw new TypeError(\"Your selectorText is not a string\");\n let head = super.getHead();\n\n this.patch({\n action: VirtualActions.PATCH_REPLACE,\n start: head.startOffset,\n end: head.endOffset,\n value: selectorText,\n patchDelta: selectorText.length - head.endOffset\n })\n }", "function reinjectStyles() {\n if (!styleElements) {\n orphanCheck();\n return;\n }\n ROOT = document.documentElement;\n docRootObserver.stop();\n const imported = [];\n for (const [id, el] of styleElements.entries()) {\n const copy = document.importNode(el, true);\n el.textContent += \" \"; // invalidate CSSOM cache\n imported.push([id, copy]);\n addStyleElement(copy);\n }\n docRootObserver.start();\n styleElements = new Map(imported);\n }", "function updatePageStyles(sheetIndex, styleRules, restorePlace) {\n return changingStylesheet(function () {\n p.stylesheets[sheetIndex] = styleRules;\n if (typeof styleRules.join == \"function\") {\n styleRules = styleRules.join(\"\\n\");\n }\n\n var i = 0, cmpt = null;\n while (cmpt = p.reader.dom.find('component', i++)) {\n var doc = cmpt.contentDocument;\n var styleTag = doc.getElementById('monStylesheet'+sheetIndex);\n if (!styleTag) {\n console.warn('No such stylesheet: ' + sheetIndex);\n return;\n }\n if (styleTag.styleSheet) {\n styleTag.styleSheet.cssText = styleRules;\n } else {\n styleTag.replaceChild(\n doc.createTextNode(styleRules),\n styleTag.firstChild\n );\n }\n }\n }, restorePlace);\n }", "function applyingTableCellandTextColor(textXpath, cellXpath){\r\n try{\r\n var myDoc = app.activeDocument;\r\n var xmlElements, xmlElementsLen, textXpathValue, RGB, rValue, gValue, bValue;\r\n if(proof_type == \"online\"){\r\n var xmlElements = myDoc.xmlElements[0].evaluateXPathExpression(textXpath);\r\n var xmlElementsLen = xmlElements.length; //Attributes total count\r\n for(var i=0; i<xmlElementsLen; i++){\r\n textXpathValue = xmlElements[i].xmlAttributes.itemByName(\"data-text-color\").value; //Attributes value. \r\n RGB = textXpathValue.split(','); //Here with split input RGB color values.\r\n rValue = parseInt(textXpathValue.split(',')[0]);\r\n gValue = parseInt(textXpathValue.split(',')[1]);\r\n bValue = parseInt(textXpathValue.split(',')[2]);\r\n colrName = rValue+'-'+gValue+'-'+bValue; //Here with create color nameing.\r\n MakeColor(colrName, ColorSpace.RGB, ColorModel.process, [rValue, gValue, bValue], proof_type);\r\n xmlElements[i].texts[0].fillColor = colrName; //applied for text color.\r\n }\r\n var xmlElements = myDoc.xmlElements[0].evaluateXPathExpression(cellXpath);\r\n var xmlElementsLen = xmlElements.length; //Attributes total count\r\n for(var j=0; j<xmlElementsLen; j++){\r\n textXpathValue = xmlElements[j].xmlAttributes.itemByName(\"data-table-background-color\").value; //Attributes value. \r\n RGB = textXpathValue.split(','); //Here with split input RGB color values.\r\n rValue = parseInt(textXpathValue.split(',')[0]);\r\n gValue = parseInt(textXpathValue.split(',')[1]);\r\n bValue = parseInt(textXpathValue.split(',')[2]);\r\n colrName = rValue+'-'+gValue+'-'+bValue;\r\n MakeColor(colrName, ColorSpace.RGB, ColorModel.process, [rValue, gValue, bValue], proof_type);\r\n xmlElements[j].cells[0].fillColor = colrName; //applied for cell background color.\r\n }\r\n }\r\n else if(proof_type == \"print\"){\r\n var xmlElements = myDoc.xmlElements[0].evaluateXPathExpression(textXpath);\r\n var xmlElementsLen = xmlElements.length; //Attributes total count\r\n for(var i=0; i<xmlElementsLen; i++){\r\n textXpathValue = xmlElements[i].xmlAttributes.itemByName(\"data-text-color\").value; //Attributes value. \r\n RGB = textXpathValue.split(','); //Here with split input RGB color values.\r\n rValue = parseInt(textXpathValue.split(',')[0]);\r\n gValue = parseInt(textXpathValue.split(',')[1]);\r\n bValue = parseInt(textXpathValue.split(',')[2]);\r\n colrName = rValue+'-'+gValue+'-'+bValue; //Here with create color nameing.\r\n MakeColor(colrName, ColorSpace.RGB, ColorModel.process, [rValue, gValue, bValue], proof_type);\r\n xmlElements[i].texts[0].fillColor = colrName; //applied for text color.\r\n }\r\n var xmlElements = myDoc.xmlElements[0].evaluateXPathExpression(cellXpath);\r\n var xmlElementsLen = xmlElements.length; //Attributes total count\r\n for(var j=0; j<xmlElementsLen; j++){\r\n textXpathValue = xmlElements[j].xmlAttributes.itemByName(\"data-table-background-color\").value; //Attributes value. \r\n RGB = textXpathValue.split(','); //Here with split input RGB color values.\r\n rValue = parseInt(textXpathValue.split(',')[0]);\r\n gValue = parseInt(textXpathValue.split(',')[1]);\r\n bValue = parseInt(textXpathValue.split(',')[2]);\r\n colrName = rValue+'-'+gValue+'-'+bValue;\r\n MakeColor(colrName, ColorSpace.RGB, ColorModel.process, [rValue, gValue, bValue], proof_type);\r\n xmlElements[j].cells[0].fillColor = colrName; //applied for cell background color.\r\n }\r\n }\r\n function MakeColor(colorName, colorSpace, colorModel, colorValue, proof_type) { //Adding color values in the inDesign file.\r\n var doc = app.activeDocument;\r\n var color = doc.colors.item(colorName); //color name\r\n if (!color.isValid) {\r\n color = doc.colors.add({name: colorName, space: colorSpace, model: colorModel, colorValue: colorValue});\r\n if(proof_type == \"print\"){ //Importan: Here with applied for color mode CMYK or RGB based on the Template.\r\n myDoc.colors.itemByName(colrName).properties = {space:ColorSpace.CMYK}; //RGB convert to CMYK mode.\r\n }\r\n }\r\n return color;\r\n }\r\n }catch(e){};\r\n}//Function End ", "parse(cssText) {\n return this.parseStylesheet(new tokenizer_1.Tokenizer(cssText));\n }", "function docEdits_apply()\n{\n // DEBUG var DEBUG_FILE = dw.getSiteRoot() + \"dwscripts_DEBUG.txt\";\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits_apply()\\n-----------------\\n\");\n var maintainSelection = arguments[0] || false; //optional: if true we will attempt maintain the current selection\n var dontReformatHTML = arguments[1] || false; //optional: if true we will prevent the code reformatter from running\n var tagSelection = null;\n\n var dom = dw.getDocumentDOM();\n\n docEdits.allSrc = dom.documentElement.outerHTML;\n docEdits.strNewlinePref = dwscripts.getNewline();\n \n try\n {\n if (maintainSelection)\n {\n tagSelection = extUtils.getTagSelection();\n }\n\n // Make sure weights are in order\n docEdits.sortWeights();\n\n // Process the queued edits\n for (var i=0; i < docEdits.editList.length; i++) //with each object with something to insert\n {\n var editObj = docEdits.editList[i];\n\n // set the properties of the DocEdit object needed for apply\n editObj.processForApply(i);\n \n } // end loop\n\n // We are now ready to create the new outerHTML string\n\n if (docEdits.editList.length > 0)\n {\n // Make sure our edits are in order\n docEdits.sortInserts();\n\n dw.useTranslatedSource(false);\n\n newSrc = new Array();\n\n var info = new Object();\n info.lastInsert = 0;\n info.bPendingMerge = false;\n info.bDoMergeNow = false;\n\n for (var i=0; i < docEdits.editList.length; i++)\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits.editList[\" + i + \"] = \" + docEdits.editList[i].toString() + \"\\n--\\n\",\"append\");\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits.editList[\" + i + \"].weight = \" + docEdits.editList[i].weight + \"\\n--\\n\",\"append\");\n\n if (docEdits.editList[i].insertPos != null)\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"insert at \"+info.lastInsert+\",\"+docEdits.editList[i].insertPos+\":\"+docEdits.allSrc.substring(info.lastInsert, docEdits.editList[i].insertPos)+\": plus :\"+ docEdits.editList[i].text+ \"\\n\\ndontPreprocessText = \" + docEdits.editList[i].dontPreprocessText + \"\\n\\n--\\n\",\"append\");\n\n if (docEdits.editList[i].insertPos > info.lastInsert)\n {\n // add the text between the end of the last edit, and our new edit\n var betweenEditsStr = docEdits.allSrc.substring(info.lastInsert, docEdits.editList[i].insertPos);\n \n // if we deleted all the content of a table cell, add &nbsp; back in.\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n if ((newSrc.length > 0) && (betweenEditsStr.search(/^\\s*<\\/td>/i) != -1))\n {\n var prevSource = \"\";\n for (var j = newSrc.length - 1; j >= 0 && prevSource == \"\"; --j)\n {\n if (newSrc[j].search(/^\\s*$/) == -1)\n {\n prevSource = newSrc[j];\n }\n }\n\n if (prevSource.search(/<td>\\s*$/i) != -1)\n {\n newSrc.push(\"&nbsp;\");\n }\n }\n RegExp.multiline = oldMultiline;\n\n newSrc.push(betweenEditsStr);\n\n if (info.bPendingMerge)\n {\n // merge the last two source blocks added to newSrc\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[info.iPendingMerge].mergeDelims[0], docEdits.editList[info.iPendingMerge].mergeDelims[1]);\n info.bPendingMerge = false;\n }\n }\n\n if (!docEdits.editList[i].text && docEdits.editList[i].mergeDelims)\n {\n info.bDoMergeNow = false;\n\n docEdits.deleteCodeBlock(newSrc, docEdits.editList[i]);\n }\n else\n {\n // set the bPendingMerge and bDoMergeNow flags\n docEdits.analyzeMerge(info, i);\n }\n\n\n if (docEdits.editList[i].text.length > 0)\n {\n // When inserting HTML along with server markup, attempt to\n // convert to XHTML if necessary. The \"if necessary\" part is \n // determined by four criteria, each of which must be met:\n // 1. The doctype of the user's document is XHTML Transitional\n // or XHTML Strict;\n // The weight of the edit we're performing:\n // 2. Must NOT be aboveHTML;\n // 3. Must NOT be nodeAttribute;\n // 4. Must NOT be belowHTML.\n // (Any of the above weights indicates server code, which must\n // not be converted because characters such as \" will be entity-\n // encoded.)\n \n // Get the weight of the edit\n var weight = docEdits.editList[i].weight;\n if (!weight) weight = \"\";\n \n // Sometimes it's a word that follows the plus\n // sign, not a number. Check for that case.\n var plus = weight.indexOf('+');\n if (plus != -1)\n weight = weight.substring(0,plus);\n \n // Do a final check for any digits or + signs (e.g., \"aboveHTML+30\"\n // will become \"aboveHTML\")\n var weightType = weight.replace(/[\\d\\+]/g,\"\");\n\n //DEBUG DWfile.write(DEBUG_FILE,\"\\n--\\ndocEdits.editList[i].weight = \" + docEdits.editList[i].weight + \"\\nweightType = \" + weightType + \"\\n--\\n\",\"append\"); \n if (newSrc.length == 0)\n {\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n // if we are adding the first text to newSrc, then remove\n // any newlines from the start of the text.\n var insertStr = docEdits.editList[i].text.replace(/^[\\r\\n]+/, \"\");\n //DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [before conversion] = '\" +insertStr + \"'\",\"append\"); \n if (dom.getIsXHTMLDocument() && weightType != \"aboveHTML\" && weightType != \"nodeAttribute\" && weightType != \"belowHTML\")\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [after conversion] = '\" + dwscripts.convertStringToXHTML(insertStr, null, false) + \"'\",\"append\"); \n // convert the string to XHTML *without converting entities*\n newSrc.push(dwscripts.convertStringToXHTML(insertStr, null, false));\n }\n else\n newSrc.push(insertStr);\n RegExp.multiline = oldMultiline;\n }\n else\n {\n var insertStr = docEdits.editList[i].text;\n // DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [before conversion] = '\" + insertStr + \"'\",\"append\"); \n if (dom.getIsXHTMLDocument() && weightType != \"aboveHTML\" && weightType != \"nodeAttribute\" && weightType != \"belowHTML\")\n {\n //DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [after conversion] = '\" + dwscripts.convertStringToXHTML(insertStr, null, false) + \"'\",\"append\"); \n // convert the string to XHTML *without converting entities*\n newSrc.push(dwscripts.convertStringToXHTML(insertStr, null, false));\n }\n else\n newSrc.push(insertStr);\n }\n }\n\n\n if (info.bDoMergeNow)\n {\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[i].mergeDelims[0], docEdits.editList[i].mergeDelims[1]);\n }\n\n if (docEdits.editList[i].replacePos)\n {\n info.lastInsert = docEdits.editList[i].replacePos;\n }\n else\n {\n info.lastInsert = docEdits.editList[i].insertPos;\n }\n }\n\n } // end loop\n\n if (info.lastInsert < docEdits.allSrc.length)\n {\n // add the rest of the original source\n var restOrigSource = docEdits.allSrc.substring(info.lastInsert);\n\n // if we deleted all the content of a table cell, add &nbsp; back in.\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n if ((newSrc.length > 0) && (restOrigSource.search(/^\\s*<\\/td>/i) != -1))\n {\n var prevSource = \"\";\n for (var j = newSrc.length - 1; j >= 0 && prevSource == \"\"; --j)\n {\n if (newSrc[j].search(/^\\s*$/) == -1)\n {\n prevSource = newSrc[j];\n }\n }\n \n if (prevSource.search(/<td>\\s*$/i) != -1)\n {\n newSrc.push(\"&nbsp;\");\n }\n }\n RegExp.multiline = oldMultiline;\n\n newSrc.push(restOrigSource);\n\n \n if (info.bPendingMerge)\n {\n // merge the last two source blocks added to newSrc\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[info.iPendingMerge].mergeDelims[0], docEdits.editList[info.iPendingMerge].mergeDelims[1]);\n }\n }\n \n // DEBUG\n // alert(\"The new document source is:\\n\\n\" + newSrc.join(\"\"));\n \n //dom.documentElement.outerHTML = newSrc.join(\"\");\n if (dontReformatHTML)\n dom.setOuterHTML(newSrc.join(\"\"), false);\n else\n\t\tdom.setOuterHTML(newSrc.join(\"\"), true);\n\n\n // alert(\"After source formatting:\\n\\n\" + dom.documentElement.outerHTML );\n\n if (tagSelection)\n {\n extUtils.setTagSelection(tagSelection);\n }\n }\n }\n finally\n {\n // The commit of edits is complete or we encountered an exception. In either case,\n // clear out the class members to prepare for the next set of edits.\n docEdits.clearAll();\n }\n}", "function changeCSS(oldCss,newCss){\n //changeCSS(\"main.css\",\"main2.css\");\n\n var oldLink = $('link[rel=stylesheet][href*=\"'+oldCss+'\"]');\n if(oldLink.length < 1){\n console.log(\"computer said nnnoooo\");\n return;\n }\n //get path of old css\n var path = oldLink.attr(\"href\");\n var pathArray = path.split('/');\n var filename = pathArray.pop();\n path = pathArray.join(\"/\")+\"/\";\n\n //remove old css\n $('link[rel=stylesheet][href=\"'+path+oldCss+'\"]').remove();\n\n //add new css\n var script_tag = document.createElement('link');\n script_tag.setAttribute(\"href\",path+newCss);\n script_tag.setAttribute(\"type\",\"text/css\");\n script_tag.setAttribute(\"rel\",\"stylesheet\");\n\n var headElement = (document.getElementsByTagName(\"head\")[0] || document.documentElement);\n headElement.appendChild(script_tag);\n\n}", "function _setTextColors() {\n if (!styles.shepherdThemeTextPrimary) {\n styles.shepherdThemeTextPrimary = curriedTransparentize(0.25, readableColor(styles.shepherdThemePrimary));\n }\n\n if (!styles.shepherdThemeTextSecondary) {\n styles.shepherdThemeTextSecondary = curriedTransparentize(0.25, readableColor(styles.shepherdThemeSecondary));\n }\n\n if (!styles.shepherdThemeTextHeader) {\n styles.shepherdThemeTextHeader = curriedTransparentize(0.25, readableColor(styles.shepherdHeaderBackground));\n }\n\n if (!styles.shepherdThemeTextColor) {\n styles.shepherdThemeTextColor = curriedTransparentize(0.25, readableColor(styles.shepherdTextBackground));\n }\n}", "function pregReplaceElements($regexp, $Elements, $text)\n\t{\n\t\tlet $newElements = array();\n\t\tlet $matches;\n\t\t\n\t\twhile (preg_match($regexp, $text, ($matches = []), 'PREG_OFFSET_CAPTURE'))\n\t\t{\n\t\t\tlet $offset = $matches[0][1];\n\t\t\tlet $before = substr($text, 0, $offset);\n\t\t\tlet $after = substr($text, $offset + strlen($matches[0][0]));\n\t\t\t\n\t\t\t$newElements.push({ 'text': $before });\n\t\t\t\n\t\t\tfor (let $Element of $Elements)\n\t\t\t{\n\t\t\t\t$newElements.push( $Element );\n\t\t\t}\n\t\t\t\n\t\t\t$text = $after;\n\t\t}\n\t\t\n\t\t$newElements.push({ 'text': $text });\n\t\t\n\t\treturn $newElements;\n\t}", "function defineDocumentStyles() {\r\n for (var i = 0; i < document.styleSheets.length; i++) {\r\n var mysheet = document.styleSheets[i],\r\n myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;\r\n config.documentStyles.push(myrules);\r\n }\r\n }", "function createStyleSheet() {\n\tvar stylesheet = Banana.Report.newStyleSheet();\n\n var pageStyle = stylesheet.addStyle(\"@page\");\n pageStyle.setAttribute(\"margin\", \"20mm 10mm 20mm 20mm\");\n\n stylesheet.addStyle(\"body\", \"font-family : Helvetica\");\n\n\tstyle = stylesheet.addStyle(\".footer\");\n\tstyle.setAttribute(\"text-align\", \"right\");\n\tstyle.setAttribute(\"font-size\", \"8px\");\n\tstyle.setAttribute(\"font-family\", \"Courier New\");\n\n\tstyle = stylesheet.addStyle(\".heading1\");\n\tstyle.setAttribute(\"font-size\", \"16px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\t\n\tstyle = stylesheet.addStyle(\".heading2\");\n\tstyle.setAttribute(\"font-size\", \"14px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".heading3\");\n\tstyle.setAttribute(\"font-size\", \"12px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".heading4\");\n\tstyle.setAttribute(\"font-size\", \"9px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".bold\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".italic\");\n\tstyle.setAttribute(\"font-style\", \"italic\");\n\n\tstyle = stylesheet.addStyle(\".alignRight\");\n\tstyle.setAttribute(\"text-align\", \"right\");\n\n\t//Warning message.\n\tstyle = stylesheet.addStyle(\".warningMsg\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\tstyle.setAttribute(\"color\", \"red\");\n\tstyle.setAttribute(\"font-size\", \"10\");\n\n\t//Tables\n\tstyle = stylesheet.addStyle(\"table\");\n\tstyle.setAttribute(\"width\", \"100%\");\n\tstyle.setAttribute(\"font-size\", \"8px\");\n\tstylesheet.addStyle(\"table.table td\", \"border: thin solid black\");\n\n\treturn stylesheet;\n}", "function applyRules( languageNode, contextNode, sString, parsedCodeNode)\n{\n\tvar regExp, arr,sRegExp;\n\tvar ruleNode,newNode, newCDATANode;\n\n\t// building regExp \n\tsRegExp=contextNode.attributes.getNamedItem(\"regexp\").value;\n\tvar regExp = new RegExp( sRegExp, \"m\" );\n\n\twhile (sString.length > 0)\n\t{\n\t\t// apply\n\t\tarr = regExp.exec( sString );\n\t\tif (arr == null)\n\t\t{\n\t\t\taddChildCDATAElem( parsedCodeNode,\n\t\t\t\t\t\t\tcontextNode.attributes.getNamedItem(\"attribute\").value, \n\t\t\t\t\t\t\tsString );\n\t\t\t\n\t\t\t// finished parsing\n\t\t\tregExp=null;\n\t\t\treturn null;\n\t\t}\n\t\telse\n\t\t{\n\t\t//alert( contextNode.attributes.getNamedItem(\"attribute\").nodeTypedValue ) ;\n\t\t\t// adding text\n\t\t\taddChildCDATAElem(parsedCodeNode, \n\t\t\t\t\t\t\tcontextNode.attributes.getNamedItem(\"attribute\").value,\n\t\t\t\t\t\t\tsString.substring(0, arr.index ) );\n\t\t\t\n\t\t\t// find rule...\n\t\t\truleNode = findRule( languageNode, contextNode, arr[0] );\n\t\t\tif (ruleNode == null)\n\t\t\t\tthrow \"Didn't matching rule, regular expression false ? ( context: \" + contextNode.attributes.getNamedItem(\"id\").value;\n\t\t\t\n\t\t\t// check if rule nees to be added to result...\n\t\t\tattributeNode=ruleNode.attributes.getNamedItem(\"attribute\");\n\t\t\tif (attributeNode != null && attributeNode.value!=\"hidden\" )\n\t\t\t{\n\t\t\t\taddChildCDATAElem(parsedCodeNode,\n\t\t\t\t\t\t\t\truleNode.attributes.getNamedItem(\"attribute\").value ,\n\t\t\t\t\t\t\t\tarr[0]);\n\t\t\t}\n\t\t\t\n\t\t\t// update context if necessary\n\t\t\tif ( contextNode.attributes.getNamedItem(\"id\").value != ruleNode.attributes.getNamedItem(\"context\").value )\n\t\t\t{\n\t\t\t\t// return new context \n\t\t\t\tvar xpContext = \"contexts/context[@id=\\\"\" \n\t\t\t\t\t\t\t\t+ ruleNode.attributes.getNamedItem(\"context\").value\n\t\t\t\t\t\t\t\t+ \"\\\"]\";\n\t\t\t\tcontextNode = languageNode.selectSingleNode( xpContext);\n\t\t\t\tif (contextNode == null)\n\t\t\t\t\tthrow \"Didn't matching context, error in xml specification ?\";\n\t\t\t\t\t\n\t\t\t\t// build new regular expression\n\t\t\t\tsRegExp=contextNode.attributes.getNamedItem(\"regexp\").value;\n\t\t\t\tregExp = new RegExp( sRegExp, \"m\" );\n\t\t\t}\n\t\t\tsString = sString.substring(arr.index+arr[0].length, sString.length);\t\t\t\n\t\t}\n\t}\n\tregExp = null;\n}", "function injectHighlightStyles() {\n const oldStyleTag = Data.Svg.Node.getElementById(STYLE_ID);\n if (oldStyleTag) Data.Svg.Node.removeChild(oldStyleTag);\n\n // TODO: Make these configurable?\n const drawWidth = '5px'; // ${drawWidth}\n const textSize = '2.5em'; // ${textSize}\n const textWeight = 'bold'; // ${textWeight}\n const textFontFamily = 'Arial'; // ${textFontFamily}\n\n const styleTag = document.createElement('style');\n styleTag.id = STYLE_ID;\n\n styleTag.textContent = `.${HIGH_CLASS_1}{fill:${Settings.Highlight1};}\n.${HIGH_CLASS_2}{fill:${Settings.Highlight2};}\n.${HIGH_CLASS_3}{fill:${Settings.Highlight3};}\n.${HIGH_CLASS_4}{fill:${Settings.Highlight4};}\n.${DRAW_CLASS}{stroke-width:${drawWidth};stroke-linecap:round;stroke-linejoin:round;fill-opacity:25%;stroke-opacity:80%;}\n.${TEXT_CLASS}{font-family:${textFontFamily};font-size:${textSize};font-weight:${textWeight};}\n.${SELECT_CLASS}{filter:drop-shadow(0 0 10px #ff0);}`;\n\n Data.Svg.Node.appendChild(styleTag);\n}", "setDescendentCssGridStyles_() {\n const elementsToUpgradeStyles = scopedQuerySelectorAll(\n this.element,\n SUPPORTED_CSS_GRID_ATTRIBUTES_SELECTOR\n );\n\n elementsToUpgradeStyles.forEach((element) => {\n this.setCssGridStyles_(element);\n });\n }", "function createStyleSheet() {\n \n //Create stylesheet\n var stylesheet = Banana.Report.newStyleSheet();\n \n //Set page layout\n var pageStyle = stylesheet.addStyle(\"@page\");\n\n //Set the margins\n pageStyle.setAttribute(\"margin\", \"10mm 5mm 10mm 5mm\");\n pageStyle.setAttribute(\"size\", generalParam.pageSize);\n\n\n /*\n General styles\n */\n stylesheet.addStyle(\"body\", \"font-family : Times New Roman; font-size:10pt; color:\" + generalParam.frameColor);\n stylesheet.addStyle(\".font-size-digits\", \"font-size:6pt\");\n stylesheet.addStyle(\".text-green\", \"color:\" + generalParam.frameColor);\n stylesheet.addStyle(\".text-black\", \"color:black\");\n\n stylesheet.addStyle(\".border-top\", \"border-top: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-right\", \"border-right: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-bottom\", \"border-bottom: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-left\", \"border-left: thin solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-left-1px\", \"border-left: 1px solid \" + generalParam.frameColor);\n stylesheet.addStyle(\".border-top-double\", \"border-top: 0.8px double black\");\n\n stylesheet.addStyle(\".border-top-black\", \"border-top: 0.5px solid black\");\n stylesheet.addStyle(\".border-right-black\", \"border-right: thin solid black\");\n stylesheet.addStyle(\".border-bottom-black\", \"border-bottom: thin solid black\");\n stylesheet.addStyle(\".border-left-black\", \"border-left: thin solid black\");\n\n stylesheet.addStyle(\".padding-left\", \"padding-left:5px\");\n stylesheet.addStyle(\".padding-right\", \"padding-right:5px\");\n stylesheet.addStyle(\".underLine\", \"border-top:thin double black\");\n\n stylesheet.addStyle(\".heading1\", \"font-size:16px;font-weight:bold\");\n stylesheet.addStyle(\".heading2\", \"font-size:12px\");\n stylesheet.addStyle(\".bold\", \"font-weight:bold\");\n stylesheet.addStyle(\".alignRight\", \"text-align:right\");\n stylesheet.addStyle(\".alignCenter\", \"text-align:center\");\n\n \n /* \n Info table style\n */\n style = stylesheet.addStyle(\"table_info\");\n style.setAttribute(\"width\", \"100%\");\n style.setAttribute(\"font-size\", \"8px\");\n stylesheet.addStyle(\"table.table_info td\", \"padding-bottom: 2px; padding-top: 5px;\");\n\n //Columns for the info table\n stylesheet.addStyle(\".col1\", \"width:37%\");\n stylesheet.addStyle(\".col2\", \"width:5%\");\n stylesheet.addStyle(\".col3\", \"width:5%\");\n stylesheet.addStyle(\".col4\", \"width:2%\");\n stylesheet.addStyle(\".col5\", \"width:5%\");\n stylesheet.addStyle(\".col6\", \"width:2%\");\n stylesheet.addStyle(\".col7\", \"width:5%\");\n stylesheet.addStyle(\".col8\", \"width:2%\");\n stylesheet.addStyle(\".col9\", \"width:15%\");\n stylesheet.addStyle(\".col10\", \"width:15%\");\n stylesheet.addStyle(\".col11\", \"width:%\");\n\n /*\n Transactions table style\n */\n style = stylesheet.addStyle(\"table\");\n style.setAttribute(\"width\", \"100%\");\n style.setAttribute(\"font-size\", \"8px\");\n stylesheet.addStyle(\"table.table td\", \"padding-bottom: 4px; padding-top: 6px\");\n\n //Columns for the transactions table\n stylesheet.addStyle(\".c1\", \"width:25%\");\n stylesheet.addStyle(\".c2\", \"width:25%\");\n stylesheet.addStyle(\".c3\", \"width:25%\");\n stylesheet.addStyle(\".cs1\", \"width:0.4%\");\n stylesheet.addStyle(\".c4\", \"width:10%\");\n stylesheet.addStyle(\".cs2\", \"width:0.4%\");\n stylesheet.addStyle(\".c5\", \"width:10%\");\n stylesheet.addStyle(\".cs3\", \"width:0.4%\");\n stylesheet.addStyle(\".c6\", \"width:3.2%\");\n\n stylesheet.addStyle(\".ct1\", \"width:20%\");\n stylesheet.addStyle(\".ct2\", \"width:20%\");\n stylesheet.addStyle(\".ct3\", \"width:10%\");\n stylesheet.addStyle(\".ct4\", \"width:10%\");\n stylesheet.addStyle(\".ct5\", \"width:10%\");\n stylesheet.addStyle(\".ct6\", \"width:10%\");\n stylesheet.addStyle(\".cts1\", \"width:0.4%\");\n stylesheet.addStyle(\".ct7\", \"width:10%\");\n stylesheet.addStyle(\".cts2\", \"width:0.4%\");\n stylesheet.addStyle(\".ct8\", \"width:10%\");\n stylesheet.addStyle(\".cts3\", \"width:0.4%\");\n stylesheet.addStyle(\".ct9\", \"width:3.2%\");\n\n /*\n Signatures table style\n */\n style = stylesheet.addStyle(\"table_signatures\");\n style.setAttribute(\"width\", \"100%\");\n style.setAttribute(\"font-size\", \"8px\");\n stylesheet.addStyle(\"table.table_signatures td\", \"padding-bottom: 5px; padding-top: 5px;\");\n\n //Column for the signatures table\n stylesheet.addStyle(\".colSig1\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig2\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig3\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig4\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig5\", \"width:16.6%\");\n stylesheet.addStyle(\".colSig6\", \"width:16.6%\");\n\n return stylesheet;\n}", "function changeSelectorStyle(selector) {\n var selector = document.querySelectorAll(selector);\n for (var i = 0; i < selector.length; i++) {\n selector[i].style.fontStyle = \"italic\";\n selector[i].style.fontWeight = \"bold\";\n selector[i].style.textDecoration = \"underline\";\n }\n}", "function compareFiles() {\n var css = new Hashset.string();\n var dups = new Hashset.string();\n\n var rules = getRules(program.args[0]);\n\n for (var i = 0; i < rules.length; i++) {\n for (var j=0; j < rules[i].selectors.length; j++) {\n css.add(rules[i].selectors[j]);\n }\n }\n\n rules = getRules(program.args[1]);\n\n for (var i = 0; i < rules.length; i++) {\n for (var j=0; j < rules.length; j++) {\n var sel = rules[i].selectors[j];\n if (css.contains(sel)) {\n dups.add(sel);\n }\n }\n }\n\n var iter = dups.iterator();\n while (iter.hasNext()) {\n console.log(iter.next());\n }\n\n}", "reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }", "function applyPatch(patchObject, graph, url) {\n debug('PATCH -- Applying patch')\n patchObject.deleted = []\n patchObject.inserted = []\n return new Promise((resolve, reject) =>\n graph.applyPatch(patchObject, graph.sym(url), (err) => {\n if (err) {\n const message = err.message || err // returns string at the moment\n debug(`PATCH -- FAILED. Returning 409. Message: '${message}'`)\n return reject(error(409, `The patch could not be applied. ${message}`))\n }\n resolve(graph)\n })\n )\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
INSTRUCCION DECLARACION DE VECTOR CON TIPO Y VALOR
function declaracionArrayCTV(ele, mod, ambi) { var encontreError = false; //BUSCANDO VECTOR EN LOS AMBITOS SI NO ESTA SE REALIZA DECLARACION if (!buscarVariable(ele.identificador)) { //VERIFICAR EXPRESIONES var v = []; //console.log(ele); //VERIFICANDO TAMAñO DE VECTOR DE VALORES PARA SABER SI ES NECESARIO ASIGNAR VALORES if (ele.valor.length > 0) { //console.log("traigo valores"); //AGREGANDO VALORES for (var e of ele.valor) { var exp = leerExp(e); if (e.tipo != "Error Semantico") { if (ele.tipoDato == exp.tipo) { v.push(exp.valor); } else { encontreError = true; errorSemantico.push({ tipo: "Error Semantico", Error: "Problema al insertar valores que no coinciden con tipo de vector " + exp.valor, Fila: ele.fila, Columna: 0, }); break; } } else { encontreError = true; errorSemantico.push(exp); break; } } //SI NO SE ENCONTRO UN ERROR SE HACE LA CREACION DE LA VARIABLE if (encontreError == false) { insertarAmbito({ tipo: ele.tipo, ambito: rNomAmbito(), modificador: mod, identificador: ele.identificador, tipoDato: ele.tipoDato, valor: v, fila: ele.fila, }); } else { errorSemantico.push({ tipo: "Error Semantico", Error: "Problema al declarar vector con valores no validos -> " + ele.identificador, Fila: ele.fila, Columna: 0, }); } } else { //SI NO ES NECESARIO AGREGAR VALORES //console.log("no traigo valores"); insertarAmbito({ tipo: ele.tipo, ambito: rNomAmbito(), modificador: mod, identificador: ele.identificador, tipoDato: ele.tipoDato, valor: v, fila: ele.fila, }); } } else { //SI HAY UNA VARIABLE DECLARADA CON EL MISMO NOMBRE SE REPORTA ERROR errorSemantico.push({ tipo: "Error Semantico", Error: "variable ya declarada -> " + ele.identificador, Fila: ele.fila, Columna: 0, }); } }
[ "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}", "static vAdd(a,b) { return newVec(a.x+b.x,a.y+b.y,a.z+b.z); }", "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}", "ones_vector() {\n\t \n\t return Matrix_ones_vector( this )\n\t}", "function vector_3(xs) /* forall<a> (xs : list<a>) -> vector<a> */ {\n return _unvlist(xs);\n}", "function vectorOperation(v1, v2, op) {\n let minLength = Math.min(v1.length, v2.length);\n let newV = [];\n for (let i = 0; i < minLength; i++) {\n newV.push(op(v1[i] * 1.0, v2[i]));\n }\n return newV;\n}", "function vectorLength([[x1, y1],[x2, y2]]){\n return Math.sqrt(Math.pow((x1-x2),2) + Math.pow((y1-y2),2))\n}", "function vector_2(n, default0) /* forall<a> (n : int, default : a) -> vector<a> */ {\n return vector_init32($std_core._int_to_int32(n), function(__i /* int32 */ ) {\n return default0;\n });\n}", "getVector() {\n if (this.parent) {\n let dx = this.parent.loc.x - this.loc.x;\n let dy = this.parent.loc.y - this.loc.y;\n let v = new JSVector(dx, dy);\n return v;\n }\n else return (JSVector(0, 0));\n }", "static getVectorEndPoint(startPoint, vec){\n\t\treturn [vec[0] + startPoint[0], vec[1] + startPoint[1]];\n\t}", "function vector_description(name, v, i) {\n describe(name, function() {\n var e = 1e-10;\n it(\"Should equal based on x and y\", function() {\n assert.isOk(v.equals(i));\n });\n it(\"Gets x and y\", function() {\n assert.closeTo(v.x(), i.x(), e);\n assert.closeTo(v.y(), i.y(), e);\n });\n it(\"Gets radius\", function() {\n assert.closeTo(v.radius(), i.radius(), e);\n });\n it(\"Gets radius squared\", function() {\n assert.closeTo(v.radiusSq(), i.radiusSq(), e);\n });\n it(\"Gets angle\", function() {\n assert.closeTo(v.angle(), i.angle(), e);\n });\n it(\"Adds to X\", function() {\n assert.closeTo(v.addX(1).x(), i.x() + 1, e);\n });\n it(\"Adds to Y\", function() {\n assert.closeTo(v.addY(1).y(), i.y() + 1, e);\n });\n it(\"Should sum vectors\", function() {\n assert.isOk(v.add(Vector.create(1, 1)).equals(i.add(Vector.create(1, 1))));\n });\n it(\"Should difference vectors\", function() {\n assert.isOk(v.subtract(Vector.create(1, 1)).equals(Vector.create(2, 3)));\n });\n it(\"Should multiply vectors\", function() {\n assert.isOk(v.multiply(Vector.create(2, 3)).equals(Vector.create(6, 12)));\n });\n it(\"Should divide vectors\", function() {\n assert.isOk(v.divide(Vector.create(3, 4)).equals(Vector.create(1, 1)));\n });\n it(\"Should scalar multiply\", function() {\n assert.isOk(v.scalarMultiply(2).equals(Vector.create(6, 8)));\n });\n it(\"Should scalar divide\", function() {\n assert.isOk(v.scalarDivide(2).equals(Vector.create(1.5, 2)));\n });\n it(\"Should invert\", function() {\n assert.isOk(v.invert().equals(Vector.create(-3, -4)));\n });\n it(\"Should rotate\", function() {\n assert.isOk(v.rotate(Math.PI / 2).equals(Vector.create(-4, 3)));\n });\n it(\"Should normalize\", function() {\n assert.isOk(v.normalize().equals(Vector.create(0.6, 0.8)));\n });\n it(\"Should dot product\", function() {\n assert.closeTo(v.dot(Vector.create(2, 3)), 18, e);\n });\n it(\"Should measure distance\", function() {\n assert.closeTo(v.distance(Vector.create(0, 0)), 5, e);\n });\n });\n}", "assignVector( name ) {\n\n let Vector;\n\n switch( name ) {\n case 'menu' : Vector = <Menu />; break;\n case 'close' : Vector = <Close />; break;\n case 'my-rewards' : Vector = <MyRewards />; break;\n case 'shop' : Vector = <Shop />; break;\n case 'programs' : Vector = <Programs />; break;\n case 'scorecard' : Vector = <Scorecard />; break;\n case 'leaderboard' : Vector = <Leaderboard />; break;\n case 'quickhits' : Vector = <QuickHits />; break;\n case 'recognition' : Vector = <Recognition />; break;\n case 'videos' : Vector = <Videos />; break;\n case 'agenda' : Vector = <Agenda />; break;\n case 'agenda-new' : Vector = <AgendaNew />; break;\n case 'extras' : Vector = <Extras />; break;\n case 'tools' : Vector = <Tools />; break;\n case 'right-arrow' : Vector = <RightArrow />; break;\n case 'left-arrow' : Vector = <LeftArrow />; break;\n case 'up-arrow' : Vector = <UpArrow />; break;\n case 'down-arrow' : Vector = <DownArrow />; break;\n case 'right-arrow-circled' : Vector = <RightArrowCircled />; break;\n case 'list' : Vector = <List />; break;\n case 'pie-chart' : Vector = <PieChart />; break;\n case 'flip-arrow' : Vector = <FlipArrow />; break;\n case 'comments' : Vector = <Comments />; break;\n case 'smiley' : Vector = <Smiley />; break;\n case 'static-arrow' : Vector = <StaticArrow />; break;\n case 'positive-arrow' : Vector = <PositiveArrow />; break;\n case 'negative-arrow' : Vector = <NegativeArrow />; break;\n case 'info' : Vector = <Info />; break;\n case 'share' : Vector = <Share />; break;\n case 'check' : Vector = <Check />; break;\n case 'plus' : Vector = <Plus />; break;\n case 'minus' : Vector = <Minus />; break;\n case 'socialhub': Vector = <SocialHub />; break;\n case '2016-base-plan' : Vector = <DollarSign/>; break;\n case 'recognition-travel' : Vector = <Travel />; break;\n case 'goal-quest-2015-managers' : Vector = <Warehouse />; break;\n case 'goal-quest' : Vector = <Warehouse />; break;\n case 'e-recognition': Vector = <ERecognition />; break;\n case 'vz-badges': Vector = <VzBadges />; break;\n case 'quizzes-and-surveys': Vector = <Quiz />; break;\n case 'multi-media': Vector = <MultiMedia />; break;\n case 'help-center': Vector = <HelpCenter />; break;\n case 'taxes': Vector = <Taxes />; break;\n case 'miscellaneous': Vector = <Miscellaneous />; break;\n case 'awardperqs-issuance': Vector = <AwardperqsIssuance />; break;\n case 'etickets-issuance': Vector = <ETicketsIssuance />; break;\n case 'user-management-tools': Vector = <UserManagementTools />; break;\n case 'web-trend-reports': Vector = <WebTrendReports />; break;\n case 'instant-win-management': Vector = <InstantWinManagement />; break;\n case 'download': Vector = <Download />; break;\n case 'print': Vector = <Print />; break;\n case 'big-arrow': Vector = <BigArrow />; break;\n case 'mail': Vector = <Mail />; break;\n case 'customer-support': Vector = <CustomerSupport />; break;\n case 'calling': Vector = <Calling />; break;\n case 'profile-icon': Vector = <ProfileIcon />; break;\n }\n\n return Vector;\n }", "static vConv(a,b) { return newVec(a.x*b.x,a.y*b.y,a.z*b.z); }", "static yAxis() { return newVec(0.0,1.0,0.0); }", "static newVCopy(it) { \r\n\t\tvar res = new mVec3(); \r\n\t\tres.copy(it.x, it.y, it.z); \r\n\t\treturn res; \r\n\t}", "function getVector(pt1, pt2) {\n\n return {\n x: pt2.x - pt1.x,\n y: pt2.y - pt1.y\n }\n}", "function evj( x , ne , en )\n {\n\n const evc = ( this.nc - 1 ) ;\n\n if( ! en ) en = 1.0e-8 ;\n if( ! ne ) ne = 100 ;\n\n let se = undefined ;\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let n = undefined ;\n\n let lij = undefined ;\n let p = undefined ;\n let sp = undefined ;\n let ps = undefined ;\n\n let ip = undefined ;\n let jq = undefined ;\n\n let c = undefined ;\n let s = undefined ;\n\n let w = undefined ;\n let t = undefined ;\n let tt = undefined ;\n\n let vipk = undefined ;\n let vjqk = undefined ;\n\n let xipip = undefined ;\n let xjqjq = undefined ;\n let xipjq = undefined ;\n\n let xipk = undefined ;\n let xjqk = undefined ;\n \n let evn = undefined ;\n \n let evv = new Array( x.nv ) ;\n\n\n for( i = 0; i < x.nv; evv[ i ] = x.v[ i++ ] ) ;\n\n\n if( ! this.nd )\n\n for( i = 0; i < this.nr; this.v[ this.idx( i , i++ ) ] = 1 )\n \n for( j = 0; j < this.nr; this.v[ this.idx( i , j++ ) ] = 0 ) ;\n\n\n for( se = 1 , n = 0; (n < ne) && (Math.abs( se ) > en); ++n )\n {\n\n for( ip = 0; (ip < (x.nr - 1)); ++ip )\n\n for( jq = (ip + 1); (jq < x.nr); ++jq )\n {\n\n xipip = evv[ x.idx( ip , ip ) ] ;\n xjqjq = evv[ x.idx( jq , jq ) ] ;\n xipjq = evv[ x.idx( ip , jq ) ] ;\n\n if( xipjq )\n {\n\n w = ( (xjqjq - xipip) / (2 * xipjq) ) ;\n\n [ t , s , tt , c ] = srt( (2 * w) , (- 1) ) ;\n\n if( Math.abs( t ) > Math.abs( tt ) ) t = tt ;\n\n\n tt = ( t * t );\n\n s = ( t / Math.sqrt( 1 + tt ) ) ;\n\n c = ( 1 / Math.sqrt( 1 + tt ) );\n\n tt = ( s / (1 + c) ) ;\n\n\n evv[ x.idx( ip , ip ) ] = ( xipip - (t * xipjq) ) ;\n\n evv[ x.idx( jq , jq ) ] = ( xjqjq + (t * xipjq) ) ;\n\n evv[ x.idx( ip , jq ) ] = 0 ;\n\n evv[ x.idx( jq , ip ) ] = 0 ;\n\n\n if( ! x.d )\n {\n\n \n for( k = 0; k < x.nc; ++k )\n {\n\n if( (k != ip) && (k != jq) )\n {\n\n xipk = evv[ x.idx( ip , k ) ] ;\n\n xjqk = evv[ x.idx( jq , k ) ] ;\n\n evv[ x.idx( ip , k ) ] = ( xipk - (s * (xjqk + (tt * xipk))) ) ;\n\n evv[ x.idx( jq , k ) ] = ( xjqk + (s * (xipk - (tt * xjqk))) ) ;\n\n } ; // end if{} -\n\n\n } ; // end for()\n\n\n for( k = 0; k < x.nr; ++k )\n {\n\n if( (k != ip) && (k != jq) )\n {\n\n xipk = evv[ x.idx( k , ip ) ] ;\n\n xjqk = evv[ x.idx( k , jq ) ] ;\n\n evv[ x.idx( k , ip ) ] = ( xipk - (s * (xjqk + (tt * xipk))) ) ;\n\n evv[ x.idx( k , jq ) ] = ( xjqk + (s * (xipk - (tt * xjqk))) ) ;\n\n } ; // end if{} -\n\n\n } ; // end for()\n\n\n } ; // end if{} -\n\n\n if( ! this.nd )\n\n for( k = 0; k < this.nr; ++k )\n { \n\n vipk = this.v[ this.idx( ip , k ) ] ;\n\n vjqk = this.v[ this.idx( jq , k ) ] ;\n\n this.v[ this.idx( ip , k ) ] = ( (c * vipk) - (s * vjqk) ) ;\n\n this.v[ this.idx( jq , k ) ] = ( (s * vipk) + (c * vjqk) ) ;\n\n } ; // end if{}-\n\n\n } ; // end if{} -\n\n\n // console.log( 'n=' , n , 'ip=' , ip , 'jq=' , jq , 'evv=' , evv ) ;\n\n\n } ; // end for()\n\n\n for( se = 0 , i = 0; i < x.nr; ++i )\n\n for( j = (i + 1); j < x.nc; se += Math.abs( evv[ x.idx( i , j++ ) ] ) ) ;\n\n\n for( i = 0; i < this.nr; ++i )\n\n this.v[ this.idx( i , evc ) ] = evv[ x.idx( i , i ) ] ;\n\n\n } ; // end for()\n\n\n return( n ) ;\n\n\n }", "function Vector4(/** x value of the vector */x,/** y value of the vector */y,/** z value of the vector */z,/** w value of the vector */w){this.x=x;this.y=y;this.z=z;this.w=w;}", "function formVector(p, q)\n{\n var pq = {lantitude: 0.0, longitude: 0.0, height: 0.0};\n pq.lantitude = q.lantitude - p.lantitude;\n pq.longitude = q.longitude - p.longitude;\n pq.height = q.height - p.height;\n return pq;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called when the bing map module has completely loaded It will attempt to recreate the geocodeCallback but will only succeed if the geocodeCallback had previously occoured prematurely
function bingCallback() { bingLoaded=true; if (resultRef) { MapPlugIn.geocodeCallback(resultRef); } }
[ "onMapsReady(){\n\n }", "function afterMapInit(map) {\n $scope.mapObj.yaMap = map;\n }", "function mapLoaded(map) {\n console.debug('map has been loaded', map);\n }", "function geocode(e) {\n //prevent actual submit\n e.preventDefault();\n var location = document.getElementById('location-input').value;\n $.ajax(\"https://maps.googleapis.com/maps/api/geocode/json?\", {\n method: \"get\",\n data: {\n address: location,\n key: \"AIzaSyD2vYz71KVg4PUiyae7M21lCA1Wkh0b8RY\"\n },\n success: function (data) {\n if(data.results.length===0){\n geo_info_object = {\n lat: null,\n lon: null,\n city: null,\n state: null\n };\n callApi();\n return;\n }\n //geometry\n var city;\n var state;\n var addressComponentArray = data.results[0].address_components;\n var updatedLocation= data.results[0].geometry.location;\n for (var i = 0; i < addressComponentArray.length; i++) {\n for(var j =0; j<addressComponentArray[i].types.length; j++){\n if (addressComponentArray[i].types[j] === 'administrative_area_level_1') {\n state = addressComponentArray[i].long_name;\n }\n if (addressComponentArray[i].types[j] === 'locality') {\n city = addressComponentArray[i].long_name;\n }\n }\n }\n geo_info_object = {\n lat: (updatedLocation.lat),\n lon: (updatedLocation.lng),\n city: city,\n state: state\n };\n callApi();\n }\n });\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 handleMapsError() {\n alert(\"Sorry, Google maps Can't be loaded right now !\");\n}", "function geocode( address, callback ) {\n\tnew gm.Geocoder().geocode({\n\t\taddress: address\n\t}, callback );\n}", "function googleSuccess() {\n if (typeof google !== 'undefined') {\n initMap();\n ko.applyBindings(new ViewModel());\n } else {\n googleLoadError();\n }\n}", "function init(){\n const address = localStorage.getItem('address')\n if(address){\n userLocation = JSON.parse(address)\n } else {\n geolocalizeUser() \n }\n loadMap(userLocation)\n}", "function geocodeAddress(geocoder, address, place_name) {\r\n geocoder.geocode({ address: address }, function(results, status) {\r\n if (status === google.maps.GeocoderStatus.OK) {\r\n var iconBase = \"https://maps.google.com/mapfiles/kml/pushpin/\";\r\n map.setCenter(results[0].geometry.location);\r\n var marker2 = new google.maps.Marker({\r\n map: map,\r\n position: results[0].geometry.location,\r\n title: address,\r\n icon: iconBase + \"red-pushpin.png\"\r\n });\r\n\r\n markers.push(marker2);\r\n var infowindow2 = new google.maps.InfoWindow({\r\n content: place_name + \"<br>\" + address\r\n });\r\n\r\n google.maps.event.addListener(\r\n marker2,\r\n \"click\",\r\n createWindow(map, infowindow2, marker2)\r\n );\r\n } else {\r\n alert(\"Geocode was not successful for the following reason: \" + status);\r\n } //end if-then-else\r\n }); // end call to geocoder.geocode function\r\n} // end geocodeAddress function", "function geocodeAddress(geocoder) {\n var address = document.getElementById('addressBox').value;\n var city = document.getElementById('cityBox').value;\n var province = document.getElementById('provinceBox').value;\n var country = document.getElementById('countryBox').value;\n var totalAddress=address+\", \"+city+ \", \"+province+\", \"+country;\n \n //google geocode api call\n geocoder.geocode({'address': totalAddress}, function(results, status) {\n if (status === 'OK') {\n text.innerHTML=\"<h4>Your Location is:</h4> \"+\"Latitude: \" + results[0].geometry.location.lat() + \n \"<br>Longitude: \" + results[0].geometry.location.lng();\n latitudeInput.value=results[0].geometry.location.lat();\n longitudeInput.value=results[0].geometry.location.lng();\n\n } else {\n alert('Geocode was not successful for the following reason: ' + status);\n }\n });\n}", "onMapReady(mapProps, map){\n this.setState({mapProps: mapProps, map: map})\n this.props.onMapLoaded(mapProps, map);\n }", "function geocode(cityName, callback) {\n // Here we are building the URL we need to query the database\n let geocodeAPIKey = \"5WFYsGYGsWMThn7qZ95yH1P1s8Euc6uK\";\n let geocodeQueryURL = \"https://www.mapquestapi.com/geocoding/v1/address?key=\" + geocodeAPIKey + \"&location=\" + cityName;\n\n // Here we run our AJAX call to the mapquest API\n $.ajax({\n url: geocodeQueryURL,\n method: \"GET\"\n })\n // We store all of the retrieved data inside of an object called \"response\"\n .then(function (response) {\n //store the latitude and longitude in variables to be used in hiking api to convert city input to lat lon\n let lat = response.results[0].locations[0].latLng.lat\n let lon = response.results[0].locations[0].latLng.lng\n\n //since chaining two ajax together have to use call back so that geocode can pass lat and lon to other functions\n callback(lat, lon);\n });\n }", "function mapStopped(){\n\t\t\tclearInterval(service.intervalHandle);\n\n\t\t\t// TODO fire off our event?\n\t\t\t//service.bounds.extent;\n\n\t\t\tconsole.log(\"stopped\");\n\t\t}", "init() {\n this.worldMap.parseMap();\n }", "function processAddress()\n{\n\tvar address = getAddress();\n\n\t//creating a geocoder object\n\tvar geocoder = new google.maps.Geocoder();\n\n\tgeocoder.geocode({'address': address}, function(results, status)\n\t{\n\t\t//If this was successful, then...\n\t\tif (status === 'OK')\n\t\t{\n\t\t\t//get the latitude and longitude: Note this is part of what I would store to the database or session\n\t\t\tvar latitude = results[0].geometry.location.lat();\n\t\t\tvar longitude = results[0].geometry.location.lng();\n\t\t\tsetMarker(results[0].geometry.location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else if (status==\"ZERO_RESULTS\")\n\t\t{\n\t\t\t//get the latitude and longitude in case when coordinates are provided in the address field and set the marker as well as string to the database or session\n\t\t\tvar location=address.replace(/[()]/g, '').split(',');\n\t\t\tvar latitude = location[0];\n\t\t\tvar longitude = location[1];\n\t\t\tvar new_location = {lat: parseFloat(latitude), lng: parseFloat(longitude)};\n\t\t\tsetMarker(new_location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else \n\t\t{\n\t\t\tconsole.error('Geocode was not successful for the following reason: ' + status);\n\t\t}\n\t});\n}", "function addAddressToMap(results, status) {\n //map.clearOverlays();\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n marker = new google.maps.Marker({\n map: map,\n position: results[0].geometry.location\n });\n //reverseGeocode(point.y,point.x);\n var CountryNameCode = \"\";\n var i = 0;\n while(results[0].address_components[i])\n {\n if(results[0].address_components[i].types[0] == \"country\")\n {\n CountryNameCode = results[0].address_components[i].short_name;\n break;\n }\n i++;\n }\n var contentString = results[0].formatted_address + '<br/>' +\n '<b>Country code:</b> ' + CountryNameCode;\n\n var infowindow = new google.maps.InfoWindow({content: contentString});\n infowindow.open(map,marker);\n\n } else {\n alert(\"Sorry, we were unable to geocode that address\");\n }\n return;\n }", "function initialize() {\n\t\t\tconsole.log('Initializing Home Controller');\n\n $scope.state.doneInitializing = false;\n\t\t\t// Make sure the Google Places API is loaded before continueing.\n\t\t\tbaLibraryStore.load('googleplaces')\n\t\t\t\t.then(function() {\n\t\t\t\t\tconsole.log('Loaded Google Places');\n\n initAutocomplete();\n initializePosition();\n\t\t\t\t}, function(response) {\n\t\t\t\t\tconsole.log('Failed to load the Google Places API.', response);\n\t\t\t\t});\n }", "function geocodeRequest(key, address, callback)\r\n{\r\n let script = document.createElement('script');\r\n script.src = \"https://api.opencagedata.com/geocode/v1/json?q=\" + encodeURIComponent(address) + \"&key=\" + key + \"&jsonp=\" + callback;\r\n document.body.appendChild(script);\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
resetCalculations To optimize the calculations, these functions work like singletons and simply return the last value if already calculated. However, since it's possible that the original caluclation was incorrect (due to system load, etc.), this function is placed in a timed interval to preiodically reset the calculations in order to be more accurate if the system load changes.
function resetCalculations() { calculatedBogoMips = null; clientEffectsLevel = null; calculateJsBogoMips(); }
[ "function clearCalculation() {\n calculation = [];\n displayCalculation();\n }", "reset () {\n this.total = this.seconds * 1000.0;\n this._remaining = this.total;\n this._clearInterval();\n this.tick();\n }", "function resetCacheInterval() {\n const hourDiff = dayjs().diff(cacheResetTime, 'hours')\n log('LOG (temp): Last Reset', cacheResetTime.format())\n if (hourDiff >= 12) {\n log('LOG: reset full cache timer')\n // empty cache\n cache = {}\n // reset start time\n cacheResetTime = dayjs()\n }\n}", "resetCurrentRoundScore() {\n\t\t\tthis.currentRoundScore.first = 0;\n\t\t\tthis.currentRoundScore.second = 0;\n\t\t}", "reset() {\n /**\n * The overall error.\n */\n this.globalError = 0;\n /**\n * The size of a set.\n */\n this.setSize = 0;\n\n this.sum = 0;\n }", "reset() {\r\n\t\tthis.number = this.props.index + 1\r\n\t\tthis.counters = {\r\n\t\t\tfigure: 0\r\n\t\t}\r\n\t\t// TODO: Incorporate equation numbers.\r\n\t}", "function resetAll() {\n exports.results.forEach((cache) => cache.reset());\n}", "resetTimer() {\n this.timer = 0;\n this.spawnDelay = GageLib.math.getRandom(\n this.spawnRate.value[0],\n this.spawnRate.value[1]\n );\n }", "reset() {\n\t\tclearInterval(this.timer);\n\t\tthis.setState(this.initialState);\n\t}", "function calcfalse()\r\n\t{\r\n\t\tcalculating = false;\r\n\t}", "reset(){\n this.setSpeed();\n this.setStartPosition();\n }", "function resetResults() {\n correct = 0;\n incorrect = 0;\n unanswered = 0;\n }", "function recomputeSchedule1() {\n changeSpecialTaxRate();\n\n computePg3Sc1I1();\n computePg3Sc1I2();\n computePg3Sc1I4();\n computePg3Sc1I7();\n computePg3Sc1I6();\n computePg3Sc1I8();\n computePg3Sc1I12();\n }", "function resetEquation() {\n let initial_html = `<span class=\"nonterminal\">${initialNonterminal_}</span>`;\n $('#cfg-equation').html(initial_html);\n reapplyNonterminalClickEvent();\n testMatchingEquations();\n historyStack_ = [];\n historyListElem_.innerHTML = '';\n addHistoryElement(initial_html, null);\n $('#undo-button').prop('disabled', true);\n}", "lapReset() {\n // condition for being the lap status\n if (this.isRunning === true && this.timeElapsed > 0 ) {\n this.lap()\n } else {\n // funtion the reset\n this.reset()\n }\n }", "function reset() {\n\t\tclearInterval(timerId);\n\t\ttimeId = null;\n\t\tindex = 0;\n\t\tid(\"output\").textContent = \"\";\n\t\tid(\"input-text\").value = \"\";\n\t\tid(\"input-text\").disabled = false;\n\t}", "function resetAll () {\n resetOutput();\n resetRegisters();\n updateRegisterOutput();\n error = false;\n}", "function clearScreen() {\n calculator.displayValue = '0';\n calculator.firstOperand = null;\n calculator.waitForNextOperand = false;\n calculator.operator = null;\n calculator.inBaseTen = true;\n}", "resetStats() {\n\t\tthis.gameDataList = [];\n\t\tthis.curGameData = null;\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recibe un codigo de curso, compara y devuelve los datos del curso del codigo
function buscarCursoPorCod(codCurso) { let listaCursos = getListaCursos(); let cursoEncontrado = []; for (let i = 0; i < listaCursos.length; i++) { if (listaCursos[i][0] == codCurso) { cursoEncontrado = listaCursos[i]; } } return cursoEncontrado; }
[ "function obtenerValoresProteccion(cod_usuario,cod_inspeccion){\n db.transaction(function (tx) {\n var query = \"SELECT k_coditem,v_sele_inspector,v_sele_empresa,o_observacion FROM escaleras_valores_proteccion WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [cod_usuario,cod_inspeccion], function (tx, resultSet) {\n for(var x = 0, i = 1; x < resultSet.rows.length; x++,i++) {\n $(\"input[name=sele_protec_person\"+i+\"][value='\"+resultSet.rows.item(x).v_sele_inspector+\"']\").prop(\"checked\",true);\n $(\"input[name=sele_protec_person\"+i+\"_\"+i+\"][value='\"+resultSet.rows.item(x).v_sele_empresa+\"']\").prop(\"checked\",true);\n $('#text_obser_protec_person'+i).val(resultSet.rows.item(x).o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}", "function leerDatosCurso(curso){\n\n\t\t\tconst infoCurso ={\n\t\t\t\t\t\timagen: curso.querySelector('img').src,\n\t\t\t\t\t\ttitulo: curso.querySelector('h4').textContent,\n\t\t\t\t\t\tprecio: curso.querySelector('.precio span').textContent,\n\t\t\t\t\t\tid: curso.querySelector('a').getAttribute('data-id')\n\n\t\t\t}\n\n\t\t\tinsertarCarrito(infoCurso);\n\n\n\n\n\t\t\t\n\t}", "function leerDatosCurso (curso) {\n //Crear objeto del curso\n const infoCurso = {\n imagen: curso.querySelector('img').src,\n titulo: curso.querySelector('h4').textContent,\n precio: curso.querySelector('.precio span').textContent,\n id: curso.querySelector('a').getAttribute('data-id')\n }\n insetarCarrito(infoCurso);\n}", "function llenarTablaAscensorValoresCabina(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_cabina.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var k_coditem = item.k_coditem_cabina;\n var n_calificacion = item.n_calificacion;\n var v_calificacion = item.v_calificacion;\n var o_observacion = item.o_observacion;\n var cantidad_filas = item.cantidad_filas;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_cabina WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n if (resultSet.rows.length == 0) {\n //alert(\"Agregar -> \"+resultSet.rows.length);\n addItemsAscensorValoresCabina(k_codusuario,codigo_inspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion); \n }else{\n //alert(\"Actualizar -> \"+resultSet.rows.length);\n updateItemsAscensorValoresCabina(k_codusuario,codigo_inspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n\n });\n }\n });\n}", "function getStatiCrescita() {\n colturaService.getStatiCrescita().then(function (result) {\n vm.statiCrescitaDisponibili = result;\n for (var i = 0; i < vm.statiCrescitaDisponibili.length; i++) {\n if (vm.statiCrescitaDisponibili[i] == vm.colturaCorrente.statoCrescita) {\n //tolgo gli stati passati\n vm.statiCrescitaDisponibili = vm.statiCrescitaDisponibili.slice(i + 1, vm.statiCrescitaDisponibili.length);\n break;\n }\n }\n });\n }", "function obtenerValoresDefectos(cod_usuario,cod_inspeccion){\n db.transaction(function (tx) {\n var query = \"SELECT k_coditem,v_calificacion,o_observacion,n_calificacion FROM escaleras_valores_defectos WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [cod_usuario,cod_inspeccion], function (tx, resultSet) {\n for(var x = 0, i = 1; x < resultSet.rows.length; x++,i++) {\n $(\"input[name=sele_defectos\"+i+\"][value='\"+resultSet.rows.item(x).v_calificacion+\"']\").prop(\"checked\",true);\n $('#text_lv_valor_observacion_'+i).val(resultSet.rows.item(x).o_observacion);\n }\n $('#text_calificacion77').val(resultSet.rows.item(76).n_calificacion); //se obtiene la calificacion de la posicion 76 en este caso 76 ya que se empieza a contar desde cero\n $('#cal_item_defectos77').val(resultSet.rows.item(76).n_calificacion);\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}", "static async findCourseByCode(courseCode){\n const result=await pool.query('SELECT * FROM course WHERE coursecode=?',courseCode);\n return result;\n }", "function obtenerValoresPreliminar(cod_usuario,cod_inspeccion){\n db.transaction(function (tx) {\n var query = \"SELECT k_coditem_preli,v_calificacion,o_observacion FROM escaleras_valores_preliminar WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [cod_usuario,cod_inspeccion], function (tx, resultSet) {\n for(var x = 0, i = 1; x < resultSet.rows.length; x++,i++) {\n $(\"input[name=seleval\"+i+\"][value='\"+resultSet.rows.item(x).v_calificacion+\"']\").prop(\"checked\",true);\n $(\"#text_obser_item\"+i+\"_eval_prel\").val(resultSet.rows.item(x).o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}", "function llenarTablaAscensorValoresIniciales(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_iniciales.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var n_cliente = item.n_cliente;\n var n_equipo = item.n_equipo;\n var n_empresamto = item.n_empresamto;\n var o_tipoaccion = item.o_tipoaccion;\n var v_capacperson = item.v_capacperson;\n var v_capacpeso = item.v_capacpeso;\n var f_fecha = item.f_fecha;\n var v_codigo = item.v_codigo;\n var v_paradas = item.v_paradas;\n var o_consecutivoinsp = item.o_consecutivoinsp;\n var ultimo_mto = item.ultimo_mto;\n var inicio_servicio = item.inicio_servicio;\n var ultima_inspeccion = item.ultima_inspeccion;\n var h_hora = item.h_hora;\n var o_tipo_informe = item.o_tipo_informe;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_iniciales WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n //alert(resultSet.rows.length);\n if (resultSet.rows.length == 0) {\n addItemsAscensorValoresIniciales(k_codusuario,codigo_inspeccion,n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe);\n }else{\n updateItemsAscensorValoresIniciales(n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe, k_codusuario,codigo_inspeccion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n \n });\n }\n });\n}", "function llenarTablaAscensorValoresAuditoriaAscensores(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_auditoria_ascensores.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var o_consecutivoinsp = item.o_consecutivoinsp;\n var o_estado_envio = item.o_estado_envio;\n var o_revision = item.o_revision;\n var v_item_nocumple = item.v_item_nocumple;\n var k_codcliente = item.k_codcliente;\n var k_codinforme = item.k_codinforme;\n var k_codusuario_modifica = item.k_codusuario_modifica;\n var o_actualizar_inspeccion = item.o_actualizar_inspeccion;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM auditoria_inspecciones_ascensores WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n if (resultSet.rows.length == 0) {\n //alert(\"agregar -> \"+resultSet.rows.length);\n addItemsAscensorValoresAuditoriaAscensores(k_codusuario,codigo_inspeccion,o_consecutivoinsp,o_estado_envio,o_revision,v_item_nocumple,k_codcliente,k_codinforme,k_codusuario_modifica,o_actualizar_inspeccion);\n }else{\n //alert(\"actualizar -> \"+resultSet.rows.length);\n /* Se actualizan la tabla de auditoria del servidor */\n actualizarTablaAuditoriaAscensorServidor(k_codusuario,k_codinspeccion);\n updateItemsAuditoriaInspeccionesAscensores(k_codusuario,codigo_inspeccion,o_consecutivoinsp,o_estado_envio,o_revision,v_item_nocumple,k_codcliente,k_codinforme,k_codusuario_modifica,o_actualizar_inspeccion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n\n });\n }\n });\n}", "function obtenerCodigoInspeccionesPendientesAscensores(estado){\n $('#ascensores').show('fast');\n db.transaction(function (tx) {\n var query = \"SELECT * FROM auditoria_inspecciones_ascensores WHERE o_estado_envio = ?\";\n tx.executeSql(query, [estado], function (tx, resultSet) {\n for(var x = 0; x < resultSet.rows.length; x++) {\n var k_codusuario = resultSet.rows.item(x).k_codusuario;\n var codigo_inspeccion = resultSet.rows.item(x).k_codinspeccion;\n var cantidad_nocumple = resultSet.rows.item(x).v_item_nocumple;\n var consecutivo_inspe = resultSet.rows.item(x).o_consecutivoinsp;\n visualizarInspeccionesAscensores(k_codusuario,codigo_inspeccion,cantidad_nocumple,consecutivo_inspe);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}", "function llenarTablaAscensorValoresProteccion(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_proteccion.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var k_coditem = item.k_coditem;\n var v_sele_inspector = item.v_sele_inspector;\n var v_sele_empresa = item.v_sele_empresa;\n var o_observacion = item.o_observacion;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_proteccion WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n if (resultSet.rows.length == 0) {\n addItemsAscensorValoresProteccion(k_codusuario,codigo_inspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion);\n }else{\n updateItemsAscensorValoresProteccion(k_codusuario,codigo_inspeccion,k_coditem,v_sele_inspector,v_sele_empresa,o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n\n });\n }\n });\n}", "async function cargarProveedores()\n{\n // Se obtienen los proveedores de la pagina web usando el modulo axios\n const proveedoresJSON = await axios.get('https://gist.githubusercontent.com/josejbocanegra/d3b26f97573a823a9d0df4ec68fef45f/raw/66440575649e007a9770bcd480badcbbc6a41ba7/proveedores.json');\n\n // Se obtiene la informacion requerida de los proveedores\n const dataProveedores = proveedoresJSON.data.map(function (act) {\n return [act.idproveedor, act.nombrecompania, act.nombrecontacto];\n })\n\n escribirHTML(\"proveedores\", dataProveedores);\n}", "function obtenerValoresElementos(cod_usuario,cod_inspeccion){\n db.transaction(function (tx) {\n var query = \"SELECT k_coditem,v_selecion FROM escaleras_valores_elementos WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [cod_usuario,cod_inspeccion], function (tx, resultSet) {\n for(var x = 0, i = 1; x < resultSet.rows.length; x++,i++) {\n $(\"input[name=sele_element_inspec\"+i+\"][value='\"+resultSet.rows.item(x).v_selecion+\"']\").prop(\"checked\",true);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}", "function buscarCoincidencias(palabra) {\n\t elegidos=[];\n\t if (palabra == \"Todas las rutas\") {\n\t elegidos = rutas;\n\t }else {\n\t for (var i = 0; i < rutas.length; i++) {\n\t if (rutas[i].categoria.indexOf(palabra) !== -1) {\n\t elegidos.push(rutas[i]);\n\t }\n\t }\n\t }\n\t return elegidos;\n\t}", "function llenarTablaAscensorValoresMaquinas(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_maquinas.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var k_coditem = item.k_coditem;\n var n_calificacion = item.n_calificacion;\n var v_calificacion = item.v_calificacion;\n var o_observacion = item.o_observacion;\n var cantidad_filas = item.cantidad_filas;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_maquinas WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n if (resultSet.rows.length == 0) {\n addItemsAscensorValoresMaquinas(k_codusuario,codigo_inspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion);\n }else{\n updateItemsAscensorValoresMaquinas(k_codusuario,codigo_inspeccion,k_coditem, n_calificacion,v_calificacion,o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n\n });\n }\n });\n}", "function solicitacaoEstaBloqueada(solicitacao) {\n var solicitacaoBloqueada = false;\n var idSolicitacao = \"\";\n\n //procura a sollicitacao na lista e retorna 'true' se encontrar\n for (var cont = 0; cont < solicitacoesBloqueadas.length; cont++) {\n idSolicitacao = solicitacoesBloqueadas[cont].split(\"/\")[0];\n\n if (solicitacao == idSolicitacao) {\n solicitacaoBloqueada = true;\n }\n }\n return solicitacaoBloqueada;\n}", "function llenarTablaAscensorValoresFoso(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_foso.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var k_coditem = item.k_coditem;\n var n_calificacion = item.n_calificacion;\n var v_calificacion = item.v_calificacion;\n var o_observacion = item.o_observacion;\n var cantidad_filas = item.cantidad_filas;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_foso WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n if (resultSet.rows.length == 0) {\n addItemsAscensorValoresFoso(k_codusuario,codigo_inspeccion,k_coditem,n_calificacion,v_calificacion,o_observacion);\n }else{\n updateItemsAscensorValoresFoso(k_codusuario,codigo_inspeccion,k_coditem, n_calificacion,v_calificacion,o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n \n });\n }\n });\n}", "function llenarTablaAscensorValoresPreliminar(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_preliminar.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var k_coditem_preli = item.k_coditem_preli;\n var v_calificacion = item.v_calificacion;\n var o_observacion = item.o_observacion;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_preliminar WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n if (resultSet.rows.length == 0) {\n addItemsAscensorValoresPreliminar(k_codusuario,codigo_inspeccion,k_coditem_preli,v_calificacion,o_observacion);\n }else{\n updateItemsAscensorValoresPreliminar(k_codusuario,codigo_inspeccion,k_coditem_preli,v_calificacion,o_observacion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n\n });\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Leftalign a string to width `width` using `fill` (default is a space) to fill on the right.
function pad_right(s, width, fill) /* (s : string, width : int, fill : ?char) -> string */ { var _fill_23035 = (fill !== undefined) ? fill : 0x0020; var w = $std_core._int_to_int32(width); var n = s.length; if ((w <= n)) { return s; } else { return (s + (repeat32(string(_fill_23035), ((w - n)|0)))); } }
[ "function leftPad(string, length, fillCharacter) {\n var newString = \"\";\n if (string.length < length) {\n for (let i = 0; i < (length - string.length); i++) {\n newString += fillCharacter\n }\n return newString + string;\n } else {\n return string\n }\n}", "align(text, length, alignment, filler) {\n if (!filler) filler = SPACE;\n if (!alignment)\n ArgumentNullException(\"alignment\");\n switch (alignment) {\n case \"c\":\n case \"center\":\n return S.center(text, length, filler);\n case \"l\":\n case \"left\":\n return S.ljust(text, length, filler);\n break;\n case \"r\":\n case \"right\":\n return S.rjust(text, length, filler);\n default:\n ArgumentException(\"alignment: \" + alignment);\n }\n }", "function zeroPad(val, width) {\n width = width || 2;\n while (String(val).length < 2) {\n val = '0' + String(val);\n }\n return val;\n }", "function leftPadWithWrapping(input, pad, colsAvail)\n{\n // safety-inits, and check for edge cases\n if(pad==null) pad = '';\n if(input==null)\n input = '';\n else\n input = trim(input);\n\n // if colsAvail not longer than pad, we will never get through input.\n // input just gets truncated in this case and we return one line of pad\n if( colsAvail <= pad.length )\n return pad.substring(0,colsAvail);\n\n\n var newlen = pad.length+input.length; // len after padding\n if( newlen <= colsAvail ) { // we need not wrap\n return pad+input;\n }\n else{ // we must wrap\n var i = input.length- (newlen-colsAvail);\n return (pad+input.substring(0,i)) + '\\n' + leftPadWithWrapping(input.substring(i), pad, colsAvail);\n }\n}", "function pad (str) {\n \"use strict\";\n var max = 0;\n\n for (var i = 0, l = levels.length; i < l; i++)\n max = Math.max(max, levels[i].length);\n\n if (str.length < max)\n return str + new Array(max - str.length + 1).join(' ');\n\n return str;\n}", "function pad(input, length, padWith)\n{\n var blank = \"\";\n for (var i=0; i<length; i++)\n {\n blank += String(padWith);\n }\n return (blank + String(input)).slice(length * -1);\n}", "function padStringArray(keys, longest, prefixSpacing) {\n keys.forEach(function(key, idx) {\n missing = longest - key.length\n keys[idx] += prefixSpacing || \"\"\n if (missing > 0)\n for (var i = 0; i < missing; i++)\n keys[idx] += \" \"\n })\n}", "function leftPad(pinCode, targetLength) {\n var count = pinCode.length;\n var output = pinCode;\n\n while (count < targetLength) {\n output = '0' + output;\n count++;\n }\n return output;\n}", "function padEnd(str,num, pad){\n if (num < str.length) return str;\n if (str.length < num){\n if (arguments.length === 3){\n let diff = Math.ceil((num-str.length)/pad.length);\n for (let i = 0; i < diff; i++){\n str += pad;\n }\n }\n else if ( arguments.length === 2) {\n let diff2 = num-str.length;\n for (let k = 0; k < diff2; k++){\n str += \" \";\n }\n }\n }\n \n if (str.length > num) str = str.slice(0,num);\n return str;\n}", "function integerToStringOfFixedWidth(number, width) {\n number = number.toString();\n \n if(width <= number.length) {\n return number.slice(number.length - width);\n } else {\n const numZeroes = width - number.length;\n for(let i = 0; i < numZeroes; i++) {\n number = '0' + number;\n }\n return number;\n }\n}", "static pad(x, length, padding, before) {\n while (x.length < length) {\n before ? x = padding + x : x = x + padding;\n }\n return x;\n }", "function limitWidth(string, len) {\n var lines = string.split('\\n');\n len = (typeof len === 'number') ? len : 80;\n var chars;\n for (var i = 0; i < lines.length; i++) {\n if (lines[i].length > len) {\n chars = lines[i].split('');\n lines[i] = lines[i].slice(0, len - 1);\n lines.splice(i + 1, 0, chars.slice(len - 1).join(''));\n }\n }\n return lines.join('\\n');\n}", "function joinString(string, strlength){\n let result = \"\";\n\n for(let i = 0; i < strlength;i++){\n if(string[i] === ' '){\n result += ('%20');\n } else{\n result += (string[i]);\n }\n\n }\n\n return result;\n\n\n}", "function fixup(prefix, name, width, index=undefined) {\n let r = `${prefix}\"${name}\"`;\n if (index !== undefined) r+= `[${index}]`;\n return r.padEnd(width)\n }", "function underline (count, leadingSpaces) {\n result = \"\";\n for (let i = 0; i < leadingSpaces; i++) {\n result += \" \";\n }\n for (let i=0 ; i < count; i++) {\n result += \"-\";\n }\n return result;\n}", "[resetRowWidth]() {\n\t\tconst self = this;\n\t\tself.width(self[CURRENT_AVAILABLE_WIDTH] - self[INDENT_WIDTH]);\n\t}", "function alignment(val) {\n\n // check if date\n var parsedDate = Date.parse(val);\n if (isNaN(val) && (!isNaN(parsedDate))) {\n return \"center\";\n }\n\n // check if numeric (remove $ and , and then check if numeric)\n var possibleNum = val.replace(\"$\", \"\");\n possibleNum = possibleNum.replace(\",\", \"\");\n if (isNaN(possibleNum)) {\n return \"left\";\n }\n return \"right\"; // it's a number\n\n }", "function validateHorizontalAlignment(align) {\n var ALIGNMENTS = ['left', 'center', 'right'];\n var DEFAULT = acf.get('rtl') ? 'right' : 'left';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }", "function padPartial(iotaAreaCode) {\r\n let padded = iotaAreaCode;\r\n if (padded.length < 8) {\r\n padded = padded + \"A\".repeat(8 - padded.length);\r\n }\r\n if (padded.length < 9) {\r\n padded = `${padded}9`;\r\n }\r\n return padded;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fires a warning toast message.
showWarningToast(title = 'Warning', message = 'A warning occurred during the operation.') { this.showToast(title, message, 'warning'); }
[ "function myWarning( _msg )\n{\n\tif( _msg.length != 0 )\n\t{\n\t\t$('#alert-warnings').html('<div style=\"margin-top: 6px; margin-bottom: 0px;\" class=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button><strong>Warning!</strong> ' + _msg + '</div>' )\n\t\t$('#alert-warnings').css('display','block')\n\t\t$('#divider-warnings').css('display','block')\n\t}\n\telse\n\t{\n\t\t$('#alert-warnings').css('display','none')\n\t\t$('#divider-warnings').css('display','none')\n\t}\n}", "function flashWarn( warning ){\n indicator.innerHTML += '<br>' + warning + '!';\n indicator.classList.add('indicator-red');\n window.setTimeout( function(){ indicator.classList.remove('indicator-red'); } , 250);\n window.setTimeout( function(){ indicator.classList.add('indicator-red'); } , 500);\n window.setTimeout( function(){ indicator.classList.remove('indicator-red'); } , 750);\n}", "function showToastMessage() {\n const toast = localStorage.getItem('showToast');\n if (localStorage.length <= 0) return;\n if (data.shouldShowToast === false) return;\n\n switch (toast) {\n case 'profile-info':\n new Toast('Updated profile info');\n localStorage.removeItem('showToast');\n break;\n case 'profile-password':\n new Toast('Updated profile password');\n localStorage.removeItem('showToast');\n break;\n default:\n localStorage.removeItem('showToast');\n }\n }", "function showToastError (error = 'networkError', duration = 1500)\n{\n const localeStrings = wx.T.getLanguage()\n wx.showToast({\n title: localeStrings[error],\n icon: 'none',\n duration,\n })\n}", "function showToast(message, duration){\n Materialize.toast(message, duration, 'rounded');\n }", "function notify_anomaly_type_wrong() {\n if (DEBUG) {\n console.log(\"FUNCTION : notify_anomaly_type_wrong\");\n }\n $.notify({\n title: \"<strong>anomaly_type</strong>\",\n message: 'wrong',\n }, {\n type: \"danger\",\n placement: {\n from: \"bottom\",\n align: \"center\"\n }\n });\n}", "isWarning(id) {\r\n $(id).removeClass('shake-normal');\r\n setTimeout(() => {\r\n $(id).addClass('shake-normal');\r\n }, 0);\r\n }", "function displayWarning(text) {\n\tvar warning = document.getElementById(\"warning\");\n\t\n\tif(text) warning.style.display = \"block\";\n\telse warning.style.display = \"none\";\n\t\n\twarning.innerHTML = text;\n}", "showInfoToast(title = 'Info', message = '') {\n this.showToast(title, message, 'info');\n }", "showMessage(type,title,message){\n\t\tsetTimeout(function() {\n\t\t\tvar html = message;\n\t\t\t\t\t\tif(type == \"error\"){\n\t\t\t\t\t\t\tvar html = '<span style=\"color:#ef5350;\">'+message+'</span>'\n\t\t\t\t\t\t}\n\t\t\t\t\t\tM.toast({html: html})\n }, 1000);\n\t}", "function displayItemMessage(msg) {\n document.getElementById('warning-mess').innerHTML = msg;\n}", "function write_html_warning(text)\n{\n\tL_html = L_html + \"<span style='color:darkorange'>\" + \"WARNING : \" + text + \"</span></br>\";\n\t$(\"#sync_report\").html(L_html);\t\n}", "warn(entry) {\n this.write(entry, 'WARNING');\n }", "function mensaje(titulo, mensaje){\n swal(titulo, mensaje); \n }", "function mensaje_advertencia(titulo, mensaje){\n swal({ title: titulo, text: mensaje, type: \"error\", confirmButtonText: \"Aceptar\" });\n }", "function notify_risk_type_wrong() {\n if (DEBUG) {\n console.log(\"FUNCTION : notify_risk_type_wrong\");\n }\n $.notify({\n title: \"<strong>risk_type</strong>\",\n message: 'wrong',\n }, {\n type: \"danger\",\n placement: {\n from: \"bottom\",\n align: \"center\"\n }\n });\n}", "function Toast() {\n}", "function emptyWarning() {\n \n user_warning.innerHTML = validate.required((user.value == \"\")? \"user\" : 0)\n phone_warning.innerHTML = validate.required((phone.value == \"\")? \"phone\" : 0)\n email_warning.innerHTML = validate.required((email.value == \"\")? \"email\" : 0)\n pass_warning.innerHTML = validate.required((pass.value == \"\") ? \"password\" : 0)\n c_pass_warning.innerHTML = validate.required((c_pass.value == \"\") ? \"confirm password\" : 0)\n \n \n \n \n \n }", "function errorFlash(){\n\n cc_tip.raiseModalBackdrop.css('display', 'none');\n cc_tip.raiseModalButton.stop().animate({opacity: 0}, 1000);\n cc_tip.closeButtonBackdrop.css('display', 'none');\n cc_tip.closeButton.stop().animate({opacity: 0}, 1000);\n\n cc_tip.tooltipBg.stop().animate({opacity: 0}, 1000);\n cc_tip.tooltipBgFailure.stop().animate({opacity: 1}, 1000);\n cc_tip.tooltipCont.stop().animate({opacity: 0}, 1000);\n cc_tip.tooltipContFailure.stop().animate({opacity: 1}, 1000);\n setTimeout(function () {\n\n cc_tip.successFadeout = true;\n cc_tip.fade(true, null, function () {\n\n resetTooltip();\n });\n }, 1000);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: isSiteRootSane DESCRIPTION: Check to see if site root is writable or unlocked if it exists. RETURNS: folderSane Boolean of whether or not the folder is OK to copy assets into.
function isSiteRootSane() { var siteRoot = dw.getSiteRoot(); var folderSane = true; //Is site root defined? if (siteRoot != "file:///") { //Is defined site root writable/unlocked? folderSane = dwscripts.isFileWritable(siteRoot); } return folderSane; }
[ "function checkSite()\n{\n var path = \"./public\";\n var ok = fs.existsSync(path);\n if(ok) path = \"./public/index.html\";\n if(ok) ok = fs.existsSync(path);\n if(!ok) console.log(\"Can't find\", path);\n return(ok);\n}", "function browseFolder() \n{\n\t//Is the folder writable/unlocked?\n\tif (isSiteRootSane()) {\n\t\t//Set lib source folder\n\t\tvar libFolder = settings.cssType == SPLIT_CSS ? PREF_SPLIT_JQLIB_SOURCE_FOLDER : PREF_JQLIB_SOURCE_FOLDER;\n\t\t\n\t\t// Call Dw to bring up the browse for folder dialog\n\t\tvar browseRoot = dw.getPreferenceString(PREF_SECTION, libFolder, dw.getConfigurationPath()+\"/\"+assetDir);\n\t\tvar jQuerySourceFolder = dw.browseForFolderURL(dw.loadString(\"Commands/jQM/files/alert/browseFile\"), browseRoot, false);\n\t \n\t\tfindjQMFiles(jQuerySourceFolder);\n\t} else {\n\t\talert(dw.loadString(\"Commands/jQM/files/alert/lockedFolder\"));\n\t}\n}", "function isInCurrentSite(path) {\n\tvar siteRoot = dw.getSiteRoot();\n\tvar inCurSite = false;\n\t\n\tif (siteRoot) {\n\t\tvar siteRootForURL = dwscripts.filePathToLocalURL(site.getSiteRootForURL(path));\n\t\tinCurSite = (siteRoot == siteRootForURL);\n\t}\n\t\n\treturn inCurSite;\n}", "function isPublicSite() {\n return (window.objConfig.sitetype.indexOf('public') > -1) ? true : false;\n}", "function checkFolder(path, device) {\n\tvar sep = air.File.separator;\n\t//If device is iphone, check if the folder has www folder\n\tvar iphoneCheck = new air.File(path + sep + 'www');\n\t//If device is android, check if the folder has assets/www\n\tvar androidCheck = new air.File(path + sep + 'assets' + sep + 'www');\n\tif(device == 'iphone')\n\t\treturn iphoneCheck.exists;\n\telse \n\t\treturn androidCheck.exists;\t\n}", "isDirExists() {\t\n\t\ttry\t{\n\t\t\tfs.statSync(this.options.dir);\n\t\t} catch(e) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}", "isValid() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.R_OK | fs.constants.W_OK);\n return true;\n } catch (err) {\n return false;\n }\n }", "function test_smart_subfolder() {\n assert_folder_mode(\"smart\");\n collapse_folder(smartFolderA);\n assert_folder_collapsed(smartFolderA);\n assert_folder_not_visible(subfolderA);\n\n expand_folder(smartFolderA);\n assert_folder_expanded(smartFolderA);\n assert_folder_visible(subfolderA);\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}", "isRoot() {\n\n return this.type == 'module';\n }", "get folderPaneVisible() {\n // Early return if the user wants to use Thunderbird without an email\n // account and no account is configured.\n if (\n Services.prefs.getBoolPref(\"app.use_without_mail_account\", false) &&\n !MailServices.accounts.accounts.length\n ) {\n return false;\n }\n\n if (this._active) {\n let folderPaneBox = document.getElementById(\"folderPaneBox\");\n if (folderPaneBox) {\n return !folderPaneBox.collapsed;\n }\n } else {\n return this._folderPaneVisible;\n }\n\n return null;\n }", "function checkOutbox() {\r\n\tif (Folder(c_outbox).exists) {\r\n\t\treturn true;\r\n\t}\r\n\telse {\r\n\t\t// Folder doesn't exist: try to create it\r\n\t\ttry {\r\n\t\t\tvar tF = new Folder(c_outbox);\r\n\t\t\ttF.create();\r\n\t\t\talert(\"New folder \" + c_outbox +\r\n\t\t\t\t\"\\nI have created this folder as an out-tray for Silver Bullet .EPS files...\")\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tcatch (err) {\r\n\t\t\t// Error returns false\r\n\t\t\talert(\"EPS output folder \" + c_outbox + \"doesn't exist and I failed \" +\r\n\t\t\t\t\" to create it. Please create the folder manually and try again\", \"Folder error\")\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n}", "function checkUploadFolder() {\n\tconsole.log('--checking for upload folder...');\n\tif (!fs.existsSync(paths.uploadFolder)) {\n\t\tfs.mkdirSync(paths.uploadFolder);\n\t}\n}", "get isRoot() {\n return this.name === '/';\n }", "isInitable() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.F_OK);\n return false;\n } catch (err) {\n return true;\n }\n }", "function CheckSystemFiles()\r\n{\r\n\tvar fld = FSO.GetFolder(swapRootDir);\r\n var folderCount = fld.SubFolders.Count;\r\n if (folderCount > 0)\r\n\t\t{\r\n\t\tConsole.PrintLine(\"\");\r\n\t\tConsole.PrintLine(\"\");\r\n\t\tConsole.PrintLine(\"**** Checking Saved Systems: ****\");\r\n\t\tvar e = new Enumerator(fld.SubFolders); \r\n\t\tvar converted = 0; // Only enumerates subFolders\r\n\t\tfor(; !e.atEnd(); e.moveNext())\r\n\t\t\t{\r\n\t\t\tvar sysFilePath = swapRootDir + \"\\\\\" + e.item().Name + \".txt\";\r\n\t\t\tif (!CheckFileExists(sysFilePath))\r\n\t\t\t\t{\r\n\t\t\t\tconverted++;\r\n\t\t\t\tConsole.PrintLine(\" \" + e.item().Name + \" needs conversion\");\r\n\t\t\t\tCreateSystemFile (sysFilePath);\r\n\t\t\t\t\r\n\t\t\t\t// Copy RotatorConfig.txt file if found\r\n\t\t\t\tvar Rotsrc = ACPApp.Path + \"\\\\RotatorConfig.txt\";\r\n\t\t\t\tvar Rottar = swapRootDir + \"\\\\\" + e.item().Name + \"\\\\ACP Settings\\\\RotatorConfig.txt\";\r\n\t\t\t\tif (FSO.FileExists(Rotsrc))\r\n\t\t\t\t\t{ // Copy FilterInfo.txt\r\n\t\t\t\t\tFSO.CopyFile(Rotsrc, Rottar);\r\n\t\t\t\t\tConsole.PrintLine(\" RotatorConfig.txt saved\");\r\n\t\t\t\t\t}\r\n\t\t\t\tConsole.PrintLine(\" Done.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\tif (converted == 0)\r\n\t\t {\r\n\t\t Console.PrintLine(\"All systems OK.\");\r\n\t\t }\r\n\t\t}\r\n}", "function is_super_admin(user)\n{\n if(admins.admins.indexOf(user) != -1)\n return true; // super admin\n\n return false; // NOT super admin\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 verifyPermission() {\n let user = JSON.parse(localStorage.getItem(USER_KEY));\n if (user == \"\")\n {\n // Should be denied access\n document.getElementsByTagName(\"body\")[0].innerText = \"Access Denied\";\n }\n\n else\n {\n var url = window.location.pathname;\n var permissionsLst = ACCESSIBLE_PAGES[user.permission];\n if (!permissionsLst.includes(url)){\n // Should be denied access\n document\n .getElementsByTagName(\"body\")[0]\n .innerText = \"Access Denied\";\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compacts either a particular folder, or all folders
compactFolder(aCompactAll, aFolder) { let folder = aFolder || GetSelectedMsgFolders()[0]; let isImapFolder = folder.server.type == "imap"; // Can't compact folders that have just been compacted if (!isImapFolder && !folder.expungedBytes && !aCompactAll) return; // Reset thread pane for non-imap folders. if (!isImapFolder && gDBView && (gDBView.msgFolder == folder || aCompactAll)) { this._resetThreadPane(); } if (aCompactAll) folder.compactAll(null, msgWindow, isImapFolder || folder.server.type == "nntp"); else folder.compact(null, msgWindow); }
[ "function folderCleanUp() {\n DriveApp.getFoldersByName('test1').next().setTrashed(true);\n DriveApp.getFoldersByName('test2').next().setTrashed(true);\n}", "onUpdateFolder() {\n this.store.query(\"folder\", {})\n .then((results) => {\n // Rebuild the tree\n this.send('buildTree', { folders: results });\n })\n .catch(() => {\n this.growl.error('Error', 'Error while retrieving folders');\n });\n }", "function test_return_to_all_folders() {\n assert_folder_mode(\"smart\");\n mc.folderTreeView.mode = \"all\";\n assert_folder_mode(\"all\");\n}", "removeFolder(path){\n // remove the path from the array\n let updatedPaths = this._folderPaths.filter(currPath => currPath !== path);\n\n // update object\n this._folderPaths = updatedPaths;\n\n // update file \n return this.update();\n }", "static apply (zip, folder, folderCopy, debug = false) {\n this.lastLogTime = 0\n let l = debug ? this.log : () => 1\n return new Promise((resolve, reject) => {\n zip += zip.includes('.zip') ? '' : '.zip'\n\n // if folderCopy is provided do not apply on original folder\n if (folderCopy) {\n l('Copying folder', folder, 'to', folderCopy)\n ncp(folder, folderCopy, (err) => {\n if (err) {\n reject(err)\n return\n }\n folder = folderCopy\n go(this)\n })\n } else {\n go(this)\n }\n\n function go (that) {\n let tempFolder = folder + '_temp' + (Math.random() + '').split('.')[1]\n l('Unzipping ', zip, 'to temporary folder', tempFolder)\n fs.createReadStream(zip)\n .pipe(unzip.Extract({ path: tempFolder }))\n .on('close', (err) => {\n if (err) {\n reject(err)\n return\n }\n let innerFolder = path.join(tempFolder, (fs.readdirSync(tempFolder))[0])\n l('Reading manifest file')\n let manifest = require(path.join(innerFolder, 'manifest.json'))\n if (manifest && manifest[0] === 'create:::all') {\n that.applyFromBlank(resolve, reject, zip, folder, tempFolder, innerFolder, debug)\n return\n }\n let co = manifest.length\n l('Applying changes to', folder)\n for (let i = 0; i < manifest.length; i++) {\n let file = manifest[i]\n if (file.indexOf('remove:') !== 0) {\n ncp(\n path.join(innerFolder, i + ''),\n path.join(folder, file.split(':', 2)[1]),\n (err) => {\n if (err) {\n reject(err)\n return\n }\n co--\n co === 0 && rimraf(tempFolder, (err) => {\n if (err) {\n reject(err)\n return\n }\n l('Removed temporary folder', tempFolder)\n l('Done applying diffs to', folder)\n resolve(manifest)\n })\n }\n )\n } else {\n rimraf(path.join(folder, file.split(':', 2)[1]), (err) => {\n if (err) {\n reject(err)\n return\n }\n co--\n co === 0 && rimraf(tempFolder, (err) => {\n if (err) {\n reject(err)\n return\n }\n l('Removed temporary folder', tempFolder)\n l('Done applying diffs to', folder)\n resolve(manifest)\n })\n })\n }\n }\n })\n }\n })\n }", "resetFolders(){\n // clear folder paths \n this._folderPaths = [];\n\n // update file\n return this.update();\n }", "function browseFolder() \n{\n\t//Is the folder writable/unlocked?\n\tif (isSiteRootSane()) {\n\t\t//Set lib source folder\n\t\tvar libFolder = settings.cssType == SPLIT_CSS ? PREF_SPLIT_JQLIB_SOURCE_FOLDER : PREF_JQLIB_SOURCE_FOLDER;\n\t\t\n\t\t// Call Dw to bring up the browse for folder dialog\n\t\tvar browseRoot = dw.getPreferenceString(PREF_SECTION, libFolder, dw.getConfigurationPath()+\"/\"+assetDir);\n\t\tvar jQuerySourceFolder = dw.browseForFolderURL(dw.loadString(\"Commands/jQM/files/alert/browseFile\"), browseRoot, false);\n\t \n\t\tfindjQMFiles(jQuerySourceFolder);\n\t} else {\n\t\talert(dw.loadString(\"Commands/jQM/files/alert/lockedFolder\"));\n\t}\n}", "function optimizeMore() {\r\n recursive(buildDir, function (err, files) {\r\n files.forEach(function(file) {\r\n if(/.css$/.test(file)) {\r\n fs.writeFileSync(file, new CleanCSS().minify(fs.readFileSync(file).toString()).styles);\r\n } else if(/.handlebars/.test(file)) {\r\n fs.unlinkSync(file);\r\n }\r\n });\r\n });\r\n}", "extractToFolder(rootFolder, options, callback) {\n\tconst { join } = require('path');\n\tconst fs = require('fs');\n\tconst createFolderPromises = []\n\tconst createFilePromises = [];\n\tconst { zip } = this;\n\tconst { dryRun, clearFolder, debug, deleteFilter } = options || {};\n\tdebug && console.log(inyellow(`extractToFolder: dryRun=${!!dryRun}, `\n\t\t\t\t + `clearFolder=${!!clearFolder}`));\n\tObject.keys(zip.files).forEach(filename => {\n\t let zfile = zip.file(filename);\n\t if (!zfile) {\n\t\tlet zfolder = zip.folder(filename);\n\t\tif (zfolder) {\n\t\t //console.log(`${filename} is a folder.`);\n\t\t let dest = join(rootFolder, filename);\n\t\t let p1 = () => new Promise((resolve, reject) => {\n\t\t\tdebug && console.log(inblue(`creating folder \"${dest}\"...`));\n\t\t\tif (dryRun) {\n\t\t\t debug && console.log('[dry run; nothing created]');\n\t\t\t resolve(dest);\n\t\t\t return;\n\t\t\t}\n\t\t\tfs.mkdir(dest, { recursive: true }, err => {\n\t\t\t if (err) {\n\t\t\t\tconsole.error(err);\n\t\t\t\t//return reject(err);\n\t\t\t }\n\t\t\t debug && console.log(inmagenta(`folder created: ${dest}`))\n\t\t\t return resolve(dest);\n\t\t\t});\n\t\t });\n\t\t createFolderPromises.push(p1);\n\t\t}\n\t\treturn;\n\t }\n\t //console.log(zfile);\n\t let p2 = () => new Promise((resolve, reject) => {\n\t\tzfile.async('nodebuffer')\n\t\t .then(content => {\n\t\t\tdebug && console.log(`content with length ${content.length} retrieved `\n\t\t\t\t + `for file \"${filename}\".`);\n\t\t\tlet dest = join(rootFolder, filename);\n\t\t\tdebug && console.log(` --> writing into ${dest}...`);\n\t\t\tif (dryRun) {\n\t\t\t debug && console.log('[dry run; nothing written]');\n\t\t\t resolve(dest);\n\t\t\t return;\n\t\t\t}\n\t\t\tlet { unixPermissions } = zfile;\n\t\t\tlet options = { mode: unixPermissions };\n\t\t\t//console.log(`permissions ${options.mode} for ${filename}`)\n\t\t\tfs.writeFile(dest, content, options, err => {\n\t\t\t if (err) {\n\t\t\t\treturn reject(err);\n\t\t\t }\n\t\t\t debug && console.log(incyan(`file created: ${dest}`))\n\t\t\t resolve(dest);\n\t\t\t});\n\t\t })\n\t\t .catch(err => {\n\t\t\treject(err);\n\t\t });\t \n\t });\n\t createFilePromises.push(p2);\n\t});\n\n\t// prepend the removeFolder operations if specified\n\tconst clearFolderPromise = clearFolder\n\t ? removeFolderRecursively(rootFolder, { dryRun, debug, deleteFilter })\n\t : Promise.resolve(null);\n\n\tconst promiseChain = [clearFolderPromise, ...createFolderPromises, ...createFilePromises];\n\t//const promiseChain = [clearFolderPromise];\n\t\n\treturn PromiseChain(promiseChain)\n\t .then(() => {\n\t\tcallback(null);\n\t })\n\t .catch(err => {\n\t\tcallback(err);\n\t });\n }", "function cleanTemp() {\n cleanFolder(uploadFolder);\n}", "function cleanup(dir) {\n console.log('Removing temporarily extracted zip contents ...');\n\n // cf. http://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty\n var deleteFolderRecursive = function(path) {\n if( fs.existsSync(path) ) {\n fs.readdirSync(path).forEach(function(file,index){\n var curPath = path + \"/\" + file;\n if(fs.lstatSync(curPath).isDirectory()) { // recurse\n deleteFolderRecursive(curPath);\n } else { // delete file\n fs.unlinkSync(curPath);\n }\n });\n fs.rmdirSync(path);\n }\n };\n\n deleteFolderRecursive(dir);\n return Promise.resolve();\n}", "function test_switch_to_smart_folder_mode() {\n mc.folderTreeView.mode = \"smart\";\n assert_folder_mode(\"smart\");\n \n smartFolderA = get_smart_folder_named(smartParentNameA);\n mc.folderTreeView.selectFolder(smartFolderA);\n}", "function onFolderIconClick() {\n const folderId = $(this).siblings('a').attr(\"data-id\");\n if (fileSystem.hasSubfoldersById(folderId)) {\n $(this).parent().toggleClass(\"collapsed\");\n }\n }", "function outputFolderTree()\n\t\t{\n\t\t\tOutput.folder('user', 3, true)\n\t\t}", "function DistClean(){\n\t// return del([delHtml,delStatic]);\n}", "function toggleFolderSelection(folderElement) {\n const index = currentSet.ids.indexOf(folderElement.dataset.id);\n\n if (index > -1) {\n currentSet.ids.splice(index, 1);\n }\n else {\n currentSet.ids.push(folderElement.dataset.id);\n }\n\n displayFolderCount();\n giveSaveBtnFeedback();\n folderElement.classList.toggle('selected', index === -1);\n }", "function minifyDir(from, to) {\n // init `to` directory\n del.sync(to, {force:true});\n mkdir(to);\n\n // process\n iterateFiles(from, function (filename) {\n var extname = filename.match('\\.[a-zA-Z0-9]*$')[0];\n var basename = path.basename(filename);\n var destdir = path.join(to, path.dirname(filename.replace(from, '')));\n var destname = path.join(destdir, basename);\n\n mkdir(destdir, function(err) {\n if (err && err.code !== 'EEXIST') {\n console.log('[ERROR] mkdir:', destdir, ':', err);\n } else {\n switch(extname) {\n case '.css':\n processCSS(filename, destname);\n break;\n case '.lua':\n processLUA(filename, destname);\n break;\n case '.div':\n case '.html':\n case '.xhtml':\n processHTML(filename, destname);\n break;\n default:\n fs.createReadStream(filename).pipe(fs.createWriteStream(destname));\n break;\n }\n }\n });\n }, function (err) {\n if (err) {\n console.log('sorry, fatal error found:', err)\n }\n });\n}", "deleteFromTree({ state, commit, getters, dispatch }, directories) {\n directories.forEach((item) => {\n // find this directory in the tree\n const directoryIndex = getters.findDirectoryIndex(item.path);\n\n if (directoryIndex !== -1) {\n // add directory index to array for deleting\n commit('addToTempArray', directoryIndex);\n\n // if directory has subdirectories\n if (state.directories[directoryIndex].props.hasSubdirectories) {\n // find subDirectories\n dispatch('subDirsFinder', state.directories[directoryIndex].id);\n }\n }\n });\n\n // filter directories\n const temp = state.directories.filter((item, index) => {\n if (state.tempIndexArray.indexOf(index) === -1) {\n return item;\n }\n return false;\n });\n\n // replace directories\n commit('replaceDirectories', temp);\n\n // clear temp array\n commit('clearTempArray');\n }", "function dirReduc(arr) {\n if (arr.length === 0) return;\n var directions = { \n NORTH: -1,\n SOUTH: 1,\n EAST: -2,\n WEST: 2,\n }\n var i;\n for (i = 0; i < arr.length; i++) {\n if (directions[arr[i]] + directions[arr[i + 1]] === 0) {\n arr.splice(i, 2);\n dirReduc(arr);\n }\n }\n return arr;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An animation step is called on each animation interval.
function animationStep() { if (_currentInterval === _noOfIntervals) { document.dispatchEvent(new Event('animation.finished')); window.clearInterval(_interval); _currentInterval = 0; _isPlaying = false; _visualization.next(_currentInterval); document.querySelector('.current-step').textContent = _currentInterval+1; document.querySelector('.step-progress').setAttribute('value', 0); } else { _visualization.next(++_currentInterval); document.querySelector('.current-step').textContent = _currentInterval+1; document.querySelector('.step-progress').setAttribute('value', _currentInterval); } }
[ "animate () {\n if (this.multiStep) this.animateSteps()\n this.animateDraws()\n }", "run() {\n this.pid = setInterval(animate, 200, this);\n //let pathInterval = null;\n //animates the visit portion of the animation then passes on to path\n function animate(animation) {\n //if no more steps\n if(!animation.steps) {\n clearInterval(animation.id);\n return;\n }\n const cur = animation.popStep();\n cur.run();\n }\n }", "function animateGame(){\n var i = 0;\n var intervalId = setInterval(function() {\n if(i >= sequenceArray.length) {\n clearInterval(intervalId);\n }\n animate(i);\n i++;\n }, 800);\n }", "step() {\n\t\tfor(var i=0;i<this.actors.length;i++) {\n\t\t\tthis.actors[i].step();\n\t\t}\n\t}", "step() {\n if (!this.running) return;\n this.calculate();\n this.print();\n }", "function runn_animation(target_animation_engine,deltatime)\n{\n target_animation_engine.runn(deltatime);\n}", "function tick() {\n current_animation_frame = requestAnimFrame(tick);\n draw();\n animate();\n}", "function timeStepBtn(){\n console.log(\"time stepped\");\n arr = getNextIteration(arr);\n drawCanvas(arr);\n}", "function nextSlide(step) {\n pos = Math.min(pos + step, 0);\n setTransform();\n }", "once () { this.step(); this.draw() }", "function _nextFrame() {\n \n // Increment (or decrement) the frame counter based on animation direction\n _frame += _direction;\n\n // Test if requested frame lies outside specified array of frames\n if (_frames.length > 1 && (_frame >= _frames.length -1 || _frame < 0)) {\n \n // Varies depending on desired loop behaviour\n switch (_options.loopbehaviour) {\n\n // Loop (default) the animation from the other end\n case 'loop':\n _frame = _frames.length - (_direction * _frame) -1;\n break;\n\n // Stop the animation\n case 'stop':\n _stop();\n _frame -= _direction;\n break;\n\n // Continue by reversing direction of animation\n case 'bounce':\n _direction *= -1;\n _frame = _frame + (2 * _direction);\n break;\n }\n }\n // Push the next frame onto the queue\n _redraw();\n }", "function animate() {\n requestAnimationFrame(animate);\n // Insert animation frame to update here.\n }", "function onAnimationStep(progress, data) {\n var profileProgress, profileRemaining,\n idLayer, lg, attr, ps;\n\n for (idLayer in data) {\n if (data.hasOwnProperty(idLayer)) {\n lg = display.layers[idLayer].geometry;\n \n profileProgress = data[idLayer].profile(progress);\n profileRemaining = 1 - profileProgress;\n \n for (attr in data[idLayer].initialState) {\n if (data[idLayer].initialState.hasOwnProperty(attr)) {\n if (typeof data[idLayer].initialState[attr] === \"number\" && typeof data[idLayer].finalState[attr] === \"number\") {\n lg[attr] = data[idLayer].finalState[attr] * profileProgress + data[idLayer].initialState[attr] * profileRemaining;\n }\n }\n }\n\n if (data[idLayer].zoomWidth && data[idLayer].zoomWidth.k !== 0) {\n ps = progress - data[idLayer].zoomWidth.ts;\n lg.width = data[idLayer].zoomWidth.k * ps * ps + data[idLayer].zoomWidth.ss;\n }\n\n if (data[idLayer].zoomHeight && data[idLayer].zoomHeight.k !== 0) {\n ps = progress - data[idLayer].zoomHeight.ts;\n lg.height = data[idLayer].zoomHeight.k * ps * ps + data[idLayer].zoomHeight.ss;\n }\n\n lg.clip = data[idLayer].finalState.clip;\n }\n }\n \n display.update();\n }", "function loopAnim() {\n // flake.animate({\n // top: 0,\n // left: thisLeft + Math.floor(Math.random() * (max - min + 1)) + min\n // }, 0)\n // .animate({\n // top: '100%',\n // left: thisLeft + Math.floor(Math.random() * (max - min + 1)) + min\n // }, thisSpeed, 'linear', function() {\n // loopAnim();\n // });\n // console.log(1111);\n flake.css({ \"transform\": \"translate(\" + (thisLeft + Math.floor(Math.random() * (max - min + 1)) + min) + \"px,\" + 0 + \"px)\", \"transition-duration\": \"0ms\", \"transition-timing-function\": \"linear\" });\n flake.timer = setTimeout(function() {\n loopAnim2();\n }, 16)\n }", "function repeatAnims() {\n missileInterval = setInterval(beginDroppingMissiles, 500)\n}", "_startAnimationLoop() {\n\t\t\tconst xTermMaterials = Array.from(this._xTermLayerMap.values());\n\t\t\tconst timeUniforms = this._shaderPasses.filter(pass => {\n\t\t\t\treturn pass.getFullscreenMaterial().uniforms.time !== undefined;\n\t\t\t}).map(pass => {\n\t\t\t\treturn pass.getFullscreenMaterial().uniforms.time;\n\t\t\t});\n\n\t\t\tconst xTermMaterialsLength = xTermMaterials.length;\n\t\t\tconst timeUniformsLength = timeUniforms.length;\n\n\t\t\tconst that = this;\n\n\t\t\t(function render() {\n\t\t\t\tthat._animationId = window.requestAnimationFrame(render);\n\n\t\t\t\tfor (let i = 0; i < timeUniformsLength; i++) {\n\t\t\t\t\ttimeUniforms.value = that._clock.getElapsedTime();\n\t\t\t\t}\n\n\t\t\t\tfor (let i = 0; i < xTermMaterialsLength; i++) {\n\t\t\t\t\txTermMaterials[i].map.needsUpdate = true;\n\t\t\t\t}\n\n\t\t\t\tthat._composer.render(that._clock.getDelta());\n\t\t\t})();\n\t\t}", "function tweenIteration() {\n var iteration = d3.interpolateNumber(+label.text(), maxIteration);\n return function (t) {\n displayIteration(iteration(t));\n };\n }", "function playAnimations() {\n animator.start();\n}", "startRandomAnimation() {\n this.clearPrevious();\n try {\n let n = this.getN();\n let parameterObject = this.generateParameter(n);\n this.startAnimation(parameterObject);\n } catch (e) {\n\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for a selected pattern, set disabled on the inputs for each exported feature
function set_features_enabled(){ var featuresmap = { color: '.form-group:has(input#colorinput)', period: '.form-group:has(input#period)', intensity: '.form-group:has(input#intensity)' }; for (feature in featuresmap) { var selector = $(featuresmap[feature]); var enabled = false; if (data.pattern != null) { enabled = (patterns[data.pattern]['features'][feature]); } if (enabled) { //$(selector).removeAttr('disabled'); if (!selector.is(':visible')){ selector.show(); } } else { //$(selector).attr('disabled', true); if (selector.is(':visible')){ selector.hide(); } } } }
[ "enable() {\n const eqs = this.equations;\n for (let i = 0; i < eqs.length; i++) {\n eqs[i].enabled = true;\n }\n }", "onDisabled() {\n this.updateInvalid();\n }", "function hideInputs() {\n var selectedDistribution = jQuery(\"#distribution\").val();\n for (inputName in fEnableObj) {\n var inputField = jQuery(`input[name='${inputName}']`);\n if (fEnableObj[inputName] === selectedDistribution)\n inputField.parent(\"label\").removeClass(\"hidden\");\n else\n inputField.parent(\"label\").addClass(\"hidden\");\n }\n if (selectedDistribution === \"parcel\") {\n jQuery(\"#geometry-box\").prop(\"checked\", true);\n jQuery(\"select#geometry\").attr(\"disabled\", true);\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n } else {\n jQuery(\"select#geometry\").attr(\"disabled\", false)\n if (jQuery(\"#geometry\").val() == \"box\") {\n jQuery(\".inputfield.maxsize\").removeClass(\"hidden\");\n } else {\n jQuery(\".inputfield.maxsize\").addClass(\"hidden\");\n }\n }\n}", "enable() {\n this._enabled = true;\n this._model = new SelectionModel(this._bufferService);\n }", "inactivatePatternCreation() {\n this.chartBody.on('mousedown', null);\n this.chartBody.on('mousemove', null);\n this.chartBody.on('mouseup', null);\n this.chartBody.on('mousemove', null);\n this.chartBody.on('click', null);\n d3.select(\"#fixedPattern\").remove();\n }", "function MEXQ_validate_and_disable() {\n console.log(\" ----- MEXQ_validate_and_disable ----\")\n //console.log(\"mod_MEX_dict\", mod_MEX_dict)\n\n let disable_save_btn = false;\n\n const is_locked = mod_MEX_dict.is_locked;\n const no_subject = !mod_MEX_dict.subject_pk;\n // no_level is only true when vsbo and no level\n const no_level = (setting_dict.sel_dep_level_req && !mod_MEX_dict.lvlbase_pk);\n // when has_partex: show el_MEXQ_input_scalelength, otherwise: show amount\n const show_input_scalelength = (mod_MEX_dict.has_partex);\n let multiple_exams_found = false;\n// --- disable save_btn when is_locked or no subject\n if (is_locked || no_subject) {\n disable_save_btn = true;\n\n// --- disable save_btn when amount has no value, only when not has_partex\n // because of secret exams you can save exam without questions PR2022-05-16\n } else if (!mod_MEX_dict.amount && !mod_MEX_dict.has_partex) {\n //disable_save_btn = true;\n\n// --- disable save_btn when level has no value - only when level required\n } else if(no_level){\n disable_save_btn = true;\n\n } else {\n// --- check if there are multiple exams of this subject and this level\n\n // skip when there are no other exams yet\n for (const data_dict of Object.values(ete_exam_dicts)) {\n // loop through exams\n // skip the current exam\n if(data_dict.map_id !== mod_MEX_dict.map_id){\n // skip other levels - only when level required\n if(!!columns_hidden.lvl_abbrev || data_dict.lvlbase_pk !== mod_MEX_dict.lvlbase_pk){\n multiple_exams_found = true;\n }}}};\n if (multiple_exams_found){\n// --- disable save_btn when multiple exams are found and version has no value\n // TODO give message, it doesnt work yet\n disable_save_btn = !el_MEXQ_input_version.value;\n };\n\n// --- disable level_select when no subject or when not add_new\n if (el_MEXQ_select_level){\n el_MEXQ_select_level.disabled = (is_locked || no_subject || !mod_MEX_dict.is_addnew);\n };\n if (el_MEXQ_input_version){\n el_MEXQ_input_version.disabled = (is_locked || no_subject || no_level);\n };\n// --- disable partex checkbox when no subject or no level\n if (el_MEXQ_input_version){\n el_MEXQ_input_version.disabled = (is_locked || no_subject || no_level);\n };\n if (el_MEXQ_input_amount){\n el_MEXQ_input_amount.disabled = (is_locked || no_subject || no_level);\n };\n if (el_MEXQ_input_scalelength){\n el_MEXQ_input_scalelength.disabled = (is_locked || no_subject || no_level);\n };\n const msg_txt = (mod_MEX_dict.has_partex) ? loc.Awp_calculates_amount : loc.err_list.amount_mustbe_between_1_and_100;\n add_or_remove_class(el_MEX_err_amount, \"text-danger\", false, \"text-muted\" );\n\n //if (el_MEX_err_amount){\n el_MEX_err_amount.innerHTML = msg_txt;\n //};\n add_or_remove_attr(el_MEXQ_input_amount, \"readOnly\", mod_MEX_dict.has_partex, true);\n\n// --- disable save button on error\n if (el_MEXQ_btn_save){\n el_MEXQ_btn_save.disabled = disable_save_btn;\n };\n// --- disable tab buttons\n if (el_MEX_btn_tab_container){\n const btns = el_MEX_btn_tab_container.children;\n for (let i = 0, btn; btn = btns[i]; i++) {\n const data_btn = get_attr_from_el(btn, \"data-btn\");\n if ([\"tab_assign\", \"tab_minscore\", \"tab_keys\"].includes(data_btn)){\n //add_or_remove_attr(btn, \"disabled\", disable_save_btn);\n };\n };\n };\n }", "updateOptionsDisabledState() {\n this.options.forEach((option) => option.setDisabledByGroupState(this.disabled));\n }", "function DisableTranspOptionalLayers(index, id_minus, id_plus, checkboxId)\n{\n\n\tvar checkid = document.getElementById(checkboxId);\n\n\n\tif (checkid.checked == true)//check if the layer is selected\n\t{\n\t\tvar optionOpacity = optionalArray[index];//localte which global opacity layer it is\n\n\t\t//Disables the buttons.\n\t\tif (optionOpacity < maxOpacity) {\n\t\t\tdocument.getElementById(id_minus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_minus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_minus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\t\t}\n\n\t\tif (optionOpacity > minOpacity) {\n\t\t\tdocument.getElementById(id_plus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_plus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_plus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\t\t}\n\t}\n\telse\n\t{\n\t\t//Disables the buttons.\n\t\tdocument.getElementById(id_minus).disabled = true;\n\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\n\t\tdocument.getElementById(id_plus).disabled = true;\n\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\n\t}\n\n}", "function disableInput() {\n if (turn === \"player 1\") {\n document.getElementById(\"ci1a\").disabled = false;\n document.getElementById(\"ci1b\").disabled = false;\n document.getElementById(\"ci1c\").disabled = false;\n document.getElementById(\"ci1d\").disabled = false;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n } else {\n document.getElementById(\"ci2a\").disabled = false;\n document.getElementById(\"ci2b\").disabled = false;\n document.getElementById(\"ci2c\").disabled = false;\n document.getElementById(\"ci2d\").disabled = false;\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n }\n }", "function disableOnlyCheckbox(){\n\tlet totalChecked = [lowercaseInput, uppercaseInput, numbersInput, specialCharsInput].filter(el => el.checked)\n\ttotalChecked.forEach(el => {\n\t\tif(totalChecked.length == 1){\n\t\t\tel.disabled = true;\n\t\t}else{\n\t\t\tel.disabled = false;\n\t\t}\n\t})\n}", "function refreshPasscodeQueryEditability() {\n $(\".passcode-query-edit\").prop(\"disabled\", passcodeQueryIndex >= 0);\n }", "function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}", "disableSelect() {\n this.select = false;\n }", "function disableAgencySubmit(disable) {\n $('#agencySubmit').attr('disabled', disable);\n}", "function setButtons() {\n hitButton.disabled = false;\n standButton.disabled = false;\n continueButton.disabled = true;\n }", "function enable(){\n Array.prototype.filter.call(tiles, function(tile){\n tile.classList.remove('disabled');\n for(let i = 0; i < matchedTile.length; i++){\n matchedTile[i].classList.add(\"disabled\");\n }\n });\n}", "function disable(div_name, title){\n div_name.disabled = true;\n add_class(div_name,'disabled');\n add_class(title,'disabled-light');\n /*var nodes = div_name.getElementsByTagName('*');\n for(var i = 0; i < nodes.length; i++){\n nodes[i].disabled = true;\n }*/\n }", "__disableInput() {\n if (!this.readonly && this.disableTextInput) {\n this.$.display.set('readonly', true);\n }\n }", "function disable_button() {\n allow_add = false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This object is responsible for managing the keys for a proxy.
function ProxyKeystore(config) { // Define this property so it doesn't show up as enumerable or writable. Object.defineProperty(this, 'oauth_secret_dir', { value: config.oauth_secret_dir }); // The count property will keep count of the valid keys exposed by this object. Object.defineProperty(this, 'count', { value: 0, writable: true }); // The quota property stores the configured quota for this project. This is used to validate // that keys do not exceed defined usage thresholds. Object.defineProperty(this, 'quotas', { value: new ProxyQuotas(config) }); // Store the keys managed by this object. Object.defineProperty(this, 'keys', { value: {}, enumerable: true }); }
[ "createProxy() {\n\t\treturn new Proxy(this, {\n\t\t\tget(target, prop, receiver) {\n\t\t\t\tlet x = +prop;\n\t\t\t\treturn new Proxy(target, {\n\t\t\t\t\tget(target, prop, receiver) {\n\t\t\t\t\t\tlet z = +prop;\n\t\t\t\t\t\tlet { zSize, data} = target;\n\t\t\t\t\t\treturn data[ x*zSize + z];\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}", "function sectionProxy(sectionName){\n this.name = sectionName;\n this.add = function(key, value){\n biro.sections[this.name].add(key, value);\n }\n this.currentState = function(){\n return biro.sections[this.name].currentState;\n }\n this.clear = function(){\n biro.sections[this.name].clear();\n }\n this.length = function(){\n return biro.sections[this.name].length();\n }\n this.nextState = function(){\n return biro.sections[this.name].nextState();\n }\n this.transition = function(toState){\n biro.sections[this.name].transition(toState);\n }\n}", "function addPoliciesToDescriptor(apiProxy, policyNames){\n fs.readFile(__dirname + '/' +apiProxy+ '/apiproxy/'+apiProxy+'.xml', function(err, data) {\n parser.parseString(data, function (err, result) {\n result.APIProxy.Policies = {\n \"Policy\": policyNames\n };\n var xml = builder.buildObject(result);\n fs.writeFile(__dirname + '/' +apiProxy+ '/apiproxy/'+apiProxy+'.xml', xml, function(err, data){\n if (err) console.log(err);\n console.log(\"Successfully update Proxy descriptor\");\n });\n });\n });\n}", "function Keymap(keys, options) {\n\t this.options = options || {}\n\t this.bindings = Object.create(null)\n\t if (keys) this.addBindings(keys)\n\t }", "function SongProxy() {\n var songws = new SongWS();\n return {\n getSong: function(songInput) {\n //cache miss -> add to cache\n if (!songcache[songInput]) \n songcache[songInput] = songws.getSong(songInput);\n return songcache[songInput]; \n },\n getCount: function() {\n var count = 0;\n for (var song in songcache) { count++; }\n return songcache.count;\n }\n };\n}", "updateProxyOverlays() {\n const chart = this.chart;\n // Always start with a clean slate\n this.proxyProvider.clearGroup('zoom');\n if (chart.resetZoomButton) {\n this.createZoomProxyButton(chart.resetZoomButton, 'resetZoomProxyButton', chart.langFormat('accessibility.zoom.resetZoomButton', { chart: chart }));\n }\n if (chart.drillUpButton &&\n chart.breadcrumbs &&\n chart.breadcrumbs.list) {\n const lastBreadcrumb = chart.breadcrumbs.list[chart.breadcrumbs.list.length - 1];\n this.createZoomProxyButton(chart.drillUpButton, 'drillUpProxyButton', chart.langFormat('accessibility.drillUpButton', {\n chart: chart,\n buttonText: chart.breadcrumbs.getButtonText(lastBreadcrumb)\n }));\n }\n }", "function proxy(){\n\n var proxyFactory = function(){\n\n //The wrapped function to call.\n var fnToCall = arguments.length === 2 ? arguments[0][arguments[1]] : arguments[0];\n\n //A counter used to note how many times proxy has been called.\n var xCalled = 0;\n\n //An array whose elements note the context used to calll the wrapped function.\n var contexts = [];\n\n //An array of arrays used to note the arguments that were passed to proxy.\n var argsPassed = [];\n\n //An array whose elements note what the wrapped function returned.\n var returned = [];\n\n ///\n ///Privileged functions used by API\n ///\n\n //Returns the number of times the wrapped function was called.\n var getCalledCount = function(){\n return xCalled;\n };\n\n //If n is within bounds returns the context used on the nth \n //call to the wrapped function, otherwise returns undefined.\n var getContext = function(n){\n if(n >= 0 && n < xCalled){\n return contexts[n];\n }\n };\n\n //If called with 'n' and 'n' is within bounds then returns the \n //array found at argsPassed[n], otherwise returns argsPassed.\n var getArgsPassed = function(){\n if(arguments.length === 1 && arguments[0] >= 0 && arguments[0] < argsPassed.length){\n return argsPassed[arguments[0]];\n }else{\n return argsPassed;\n }\n };\n\n //If called with 'n' and 'n' is within bounds then returns \n //value found at returned[n], otherwise returns returned.\n var getReturned = function(){\n if(arguments.length === 1 && arguments[0] >= 0 && arguments[0] < returned.length){\n return returned[arguments[0]];\n }else{\n return returned;\n }\n };\n\n //If 'n' is within bounds then returns an \n //info object, otherwise returns undefined.\n var getData= function(n){\n if(n >= 0 && n < xCalled){\n var args = getArgsPassed(n);\n var context = getContext(n);\n var ret = getReturned(n);\n var info = {\n count: n + 1,\n argsPassed: args,\n context: context,\n returned: ret\n };\n return info;\n }\n };\n\n //If you just want to know if the wrapped function was called \n //then call wasCalled with no args. If you want to know if the \n //callback was called n times, pass n as an argument.\n var wasCalled = function(){\n return arguments.length === 1 ? arguments[0] === xCalled : xCalled > 0;\n };\n\n //A higher order function - iterates through the collected data and \n //returns the information collected for each invocation of proxy.\n var dataIterator = function(callback){\n for(var i = 0; i < xCalled; i++){\n callback(getData(i));\n }\n };\n\n //The function that is returned to the caller.\n var fn = function(){\n //Note the context that the proxy was called with.\n contexts.push(this);\n //Note the arguments that were passed for this invocation.\n var args = [].slice.call(arguments);\n argsPassed.push(args.length ? args : []);\n //Increment the called count for this invocation.\n xCalled += 1;\n //Call the wrapped function noting what it returns.\n var ret = fnToCall.apply(this, args);\n returned.push(ret);\n //Return what the wrapped function returned to the caller.\n return ret;\n };\n\n ///\n ///Exposed Lovwer level API - see Privileged functions used by API above.\n ///\n\n fn.getCalledCount = getCalledCount;\n\n fn.getContext = getContext;\n\n fn.getArgsPassed = getArgsPassed;\n\n fn.getReturned = getReturned;\n\n fn.getData = getData;\n\n ///\n ///Exposed Higher Order API - see Privileged functions used by API above.\n ///\n \n fn.wasCalled = wasCalled;\n\n fn.dataIterator = dataIterator;\n\n //Replaces object's method property with proxy's fn.\n if(arguments.length === 2){\n arguments[0][arguments[1]] = fn; \n }\n\n //Return fn to the caller.\n return fn;\n };\n\n //Convert arguments to an array, call factory and returns its value to the caller.\n var args = [].slice.call(arguments);\n return proxyFactory.apply(null, args);\n\n }", "function saveproxyRule() {\n\tvar rules = {};\n\tvar co = 0;\n\n\t$(\"#proxy_rules_list .proxy_rule_boxes\").each(function() {\n\t\tvar url = stripHTMLTags($(this).find('.url').text());\n\t\tvar proxy_type = stripHTMLTags($(this).find('.proxy_type').prop(\"selectedIndex\"));\n\t\tvar proxy_location = stripHTMLTags($(this).find('.proxy_location').text());\t\t\n\t\tvar proxy_port = stripHTMLTags($(this).find('.proxy_port').text());\t\t\n\n\t\tvar active = stripHTMLTags($(this).find('.active').prop('checked'));\n\t\tvar global = stripHTMLTags($(this).find('.global').prop('checked'));\n\t\tvar caseinsensitive = stripHTMLTags($(this).find('.caseinsensitive').prop('checked'));\n\t\t// prepare the object\n\t\trules[co] = {id: co, url:url, proxy_type:proxy_type, proxy_location:proxy_location, proxy_port:proxy_port, active: active, global:global, caseinsensitive:caseinsensitive}\n\t\tco++;\n\t});\n\t\t\n\tlocalStorage.proxy_rules = JSON.stringify(rules);\n}", "function ProxyBase(receiver) {\n this[kProxyProperties] = new ProxyProperties(receiver);\n\n // TODO(hansmuller): Temporary, for Chrome backwards compatibility.\n if (receiver instanceof Router)\n this.receiver_ = receiver;\n }", "addProxy(id, options) {\n return new proxy_1.DatabaseProxy(this, id, {\n proxyTarget: proxy_1.ProxyTarget.fromCluster(this),\n ...options,\n });\n }", "function initAll(handler){\r\n let overrideProxy=new Proxy({},{\r\n has:function(target,prop){\r\n return true\r\n },\r\n get:function(target,prop){\r\n return newElementHolderProxy()[prop](handler)\r\n }\r\n }\r\n )\r\n return newElementHolderProxy(undefined,overrideProxy)\r\n }", "function Keymap(){\r\n this.map = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\r\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'backspace', 'enter', 'shift', 'delete'];\r\n }", "constructor(options) {\n // Proxy options\n this.options = Object.assign({\n serverAddress: '127.0.0.1',\n serverPort: 16567,\n // proxyAddress: 'THIS CAN NOT HAVE SENSIBLE DEFAULT',\n socketTimeout: 10000,\n banTimeout: 10 * 60000\n }, options);\n // Component logger\n this.logger = new Logger('PROXY', this.options.debug);\n // Public proxy SOCKET\n this.socket = null;\n // Local client SOCKETs\n this.clients = {};\n // IP bans\n this.bans = {};\n }", "createProxy() {\n const self = this;\n this._proxy = new Proxy(console, {\n get: (target, property) => {\n if ( typeof target[property] === 'function' ) {\n return function(args) {\n self.send(property, args);\n return target[property](args);\n }\n }\n },\n });\n }", "function getHubProxy(proxyName, proxyConfig) {\n var hubProxy;\n if (registeredProxies[proxyName]) {\n var client = registeredProxies[proxyName].client;\n for (var propName in client) {\n if (SJ.isFunction(proxyConfig.client[propName]) && client[propName] === SJ.emptyFn) {\n client[propName] = proxyConfig.client[propName];\n }\n }\n for (var propName in proxyConfig.client) {\n if (SJ.isFunction(proxyConfig.client[propName]) && !client[propName]) {\n client[propName] = proxyConfig.client[propName];\n }\n }\n hubProxy = registeredProxies[proxyName];\n } else {\n hubProxy = {\n name: proxyName,\n client: proxyConfig.client,\n server: getProxyServer(proxyName)\n };\n registeredProxies[proxyName] = hubProxy;\n }\n proxyClientsConfig.change(function (data) {\n data = data || {};\n data[proxyName] = data[proxyName] || { windows: [], methods: [] };\n\n var windows = data[proxyName].windows;\n var thisWindowId = SJ.iwc.WindowMonitor.getThisWindowId();\n if (windows.indexOf(thisWindowId) === -1) {\n windows.push(thisWindowId);\n }\n\n var methods = data[proxyName].methods;\n for (var propName in proxyConfig.client) {\n if (proxyConfig.client.hasOwnProperty(propName) && SJ.isFunction(proxyConfig.client[propName])) {\n if (methods.indexOf(propName) === -1) {\n methods.push(propName);\n }\n }\n }\n return data;\n });\n return hubProxy;\n }", "proxy(aProxy = undefined) {\n if (!this._proxy) {\n assert(!this._runPromise); // do not create agents after run()\n assert(arguments.length === 1); // do not ask before setting\n assert(aProxy);\n this._proxy = aProxy;\n } else {\n assert(arguments.length === 0); // do not set twice\n }\n return this._proxy;\n }", "setupHoverProxy () {\n const hoverClass = 'ps-container-hover'\n const bodyLeftSelector = this.get('_bodyLeftSelector')\n const bodyMiddleSelector = this.get('_bodyMiddleSelector')\n const bodyRightSelector = this.get('_bodyRightSelector')\n\n ;[bodyLeftSelector, bodyMiddleSelector].forEach((selector) => {\n const $element = this.$(selector)\n $element.on('mouseenter', () => {\n this.$(bodyRightSelector).addClass(hoverClass)\n })\n $element.on('mouseleave', () => {\n this.$(bodyRightSelector).removeClass(hoverClass)\n })\n })\n\n const headerMiddleSelector = this.get('_headerMiddleSelector')\n const $headerMiddle = this.$(headerMiddleSelector)\n $headerMiddle.on('mouseenter', () => {\n this.$(bodyMiddleSelector).addClass(hoverClass)\n })\n\n $headerMiddle.on('mouseleave', () => {\n this.$(bodyMiddleSelector).removeClass(hoverClass)\n })\n }", "function hijack(){\n\t\t// The current global GA object (could be GA command queue or loaded GA object).\n\t\tvar gaOrig = window.ga;\n\t\t// Replace global GA object with a proxy.\n\t\twindow.ga = proxy;\n\t\t// Maintain references to GA's public interface. \n\t\tfor( k in gaOrig )\n\t\t\tif( gaOrig.hasOwnProperty( k ) )\n\t\t\t\tproxy[k] = gaOrig[k];\n\t}", "async function recreateProxy (serviceName, listenPort, proxyToPort) {\n try {\n await rp.delete({\n url: `${toxicli.host}/proxies/${serviceName}`\n })\n } catch (err) {}\n\n const proxy = await toxicli.createProxy({\n name: serviceName,\n listen: `0.0.0.0:${listenPort}`,\n upstream: `${serviceName}:${proxyToPort}`\n })\n\n // add some network latency simulation\n await proxy.addToxic(new toxiproxy.Toxic(proxy, {\n type: 'latency',\n attributes: {latency: 1, jitter: 1}\n }))\n\n // cause connections to be closed every some transferred bytes\n await proxy.addToxic(new toxiproxy.Toxic(proxy, {\n type: 'limit_data',\n attributes: {bytes: 5000}\n }))\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function converts text into an entry
function toEntry(text) { let lines = text .split('\n') .map(line => trim(line)) .filter(line => line !== ''); if (lines.length === 0) { throw new Error('Reminder deleted'); } else if (lines.length < 2) { throw new Error('Invalid reminder format'); } let main = trim(lines[0]); let subs = lines.slice(1, lines.length - 1); let footer = lines[lines.length - 1]; if (main[0] !== '+' && main[0] !== '-') { throw new Error('Tasks should start with +/-'); } let entry = { task: trim(main.slice(1)), completed: main[0] === '+', subtasks: [] }; if (entry.task.length === 0) { throw new Error('No description for a task was specified'); } let split = footer.split('-'); entry.tag = trim(split[0]).toLowerCase(); if (entry.tag.length === 0) { throw new Error('No tag specified'); } if (split.length === 2) { /* Scheduled */ entry.scheduled = true; if (isNaN(Date.parse(split[1]))) { throw new Error('Invalid date. Format: mm/dd/yy hh:mm'); } entry.date = new Date(split[1]); } else { /* No time */ entry.scheduled = false; } subs.forEach(line => { line = trim(line); if (line[0] !== '+' && line[0] !== '-') { throw new Error('Tasks should start with +/-'); } let item = { content: trim(line.slice(1)), completed: line[0] === '+' }; if (item.content.length === 0) { throw new Error('No description for a subtask was specified'); } entry.subtasks.push(item); }); return entry; }
[ "function bibtexFormat(entry, config) {\r\n let s = '';\r\n s += '@' + entry.entryType + '{' + (entry.internalKey ? entry.internalKey : '');\r\n // Find the longest field name in entry\r\n let maxFieldLength = 0;\r\n entry.content.forEach(field => {\r\n maxFieldLength = Math.max(maxFieldLength, field.name.length);\r\n });\r\n entry.content.forEach(field => {\r\n s += ',\\n' + config.tab + (config.case === 'lowercase' ? field.name : field.name.toUpperCase());\r\n s += ' '.repeat(maxFieldLength - field.name.length) + ' = ';\r\n s += fieldToString(field.value, config.left, config.right);\r\n });\r\n s += '\\n}';\r\n return s;\r\n}", "function journalEntry(entryDate, conceptLearned, journalText, mood) {\n const newEntry = {\n date: `${entryDate}`,\n concept: `${conceptLearned}`,\n entry: `${journalText}`,\n mood: `${mood}`,\n };\n return newEntry;\n}", "function processData(text, trie) {\n var lines = text.split('\\n');\n for(i=0; i < lines.length; i++) {\n trie.add(lines[i].trim());\n }\n }", "parseEntries() {}", "function textArea(){\r\n\tvar text = document.getElementById(\"info\").value;\r\n\tvar splitValue = [];\r\n\tsplitValue = text.split(\"\\n\");\r\n\timportLatLng(splitValue);\r\n}", "'entries.get' (entryId) {\n console.log('get text for entry');\n\n // If no user is logged in, throw an error\n if (!Meteor.user()) {\n console.log(\"No user is logged in!\");\n throw Error(\"User is not logged in\");\n }\n \n // Locate the entry\n let entry = JournalEntryCollection.findOne({_id: entryId});\n\n // If no entry exists, the logged in user can't access it\n if (!entry) {\n console.log(`entry with ID ${entryId} wasn't found`);\n throw Error(\"Unable to find entry with given ID\");\n }\n\n console.log(`Entry found: ${entry._id}, ${entry.text}`);\n\n // If the entry's owner is not the logged in user, they\n // can't access it\n if (entry.ownerId != Meteor.userId()) {\n console.log(`This entry belongs to ${entry.ownerId} but the logged in user is ${Meteor.userId()}`);\n throw Error(\"Logged in user does not have permission to view this entry\");\n }\n\n // The entry exists and the logged in user is the owner,\n // so they can access it\n return entry;\n }", "function scrubEntry(translation) {\n if(typeof translation === 'string') {\n if(translation.indexOf('DONE') !== -1) {\n translation = translation.replace('DONE', '').trim()\n }\n if(translation.indexOf('TODO') !== -1) {\n translation = translation.replace('DONE', '').trim()\n }\n } else if(typeof translation === 'object') {\n for(i in translation) {\n translation[i] = scrubEntry(translation[i])\n }\n }\n return translation\n}", "function editEntry(ENTRY){\n // making entry the variable that represents the entry id which includes amount, name,type\n let entry = ENTRY_LIST[ENTRY.id];\n // if the entry type is an input, we are going to update the item name and cost in the input section\n if (entry.type == \"inputs\"){\n itemName.value = entry.title;\n itemCost.value = entry.amount;\n }\n // run the delete entry function again so you can delete the previous entry before you add a new edited entry\n deleteEntry(ENTRY);\n }", "_entryWidgetFromModel(entry) {\n const options = this._createMarkdownCellOptions(entry.text);\n const cellWidget = this.contentFactory.createCell(options);\n this._disposables.add(cellWidget);\n cellWidget.readOnly = true;\n cellWidget.rendered = true;\n const isMe = this._model\n ? this._model.modelDB.collaborators.localCollaborator.userId ===\n entry.author.userId\n : false;\n const entryWidget = new entry_1.ChatEntry({\n model: entry,\n cell: cellWidget,\n isMe\n });\n return entryWidget;\n }", "function MakePost(text){\nreturn {\n\ttext: text,\n\tdate: new Date()\n}\n}// this function will display posts in the posts div", "function makeDiaryItemList(journalEntries, newEntry, entryDate, subject) {\n \n var d = new Date(); //current time\n var entryId = d.getTime(); // current time in milliseconds\n console.log(entryId);\n var entryTexts = journalEntries;\n var subject = subject;\n\n var newEntryText = { \"date\": entryDate, \"subject\": subject, \"diaryText\": newEntry, \"textID\": entryId };\n entryTexts.push(newEntryText); //new entry is pushed to an array of old entries\n\n return entryTexts;\n}", "function processEntry(entry) {\n\t\t/* Feed entry types. */\n\t\tconst isActivity = !!entry.querySelector('[class*=\"ActivityEntry\"]');\n\t\tconst isGroupActivity = !!entry.querySelector('[class*=\"GroupActivity\"]');\n\t\tconst isClubJoin = !!(entry.querySelector('[class*=\"AthleteJoinEntry\"]') && entry.querySelector('[class*=\"ClubJoin\"]'));\n\t\tconst isChallengeJoin = !!(entry.querySelector('[class*=\"AthleteJoinEntry\"]') && entry.querySelector('[class*=\"ChallengeJoin\"]'));\n\t\tconst isPromo = !!entry.querySelector('[class*=\"PromoEntry\"]');\n\n\t\tconst firstActivityFromGroup = isGroupActivity && entry.querySelector('[class*=\"GroupActivityEntry\"]');\n\n\t\t/* Tags/special properties. */\n\t\tconst isOwnActivity = !!entry.querySelector('[class*=\"Owner\"]')?.querySelector(`a[href=\"${ownProfileHref}\"]`);\n\n\t\tconst isCommute = !!document.evaluate('.//*[@data-testid=\"tag\"][contains(., \"Commute\")]', entry, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n\n\t\tconst isVirtual = !!document.evaluate('.//*[@data-testid=\"tag\"][contains(., \"Virtual\")]', entry, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n\n\t\tconst activityName = entry.querySelector('[data-testid=\"activity_name\"]')?.textContent;\n\n\t\t/* Activity types, based on the activity icon’s SVG. (Super robust, yeah.) */\n\t\tconst svgIcon = entry.querySelector('[class*=\"activity-icon\"] path');\n\t\tconst svgHash = svgIcon\n\t\t\t? calculateHash(svgIcon.outerHTML)\n\t\t\t: '';\n\n\t\tconst activityType = svgHashesToActivityTypes[svgHash];\n\n\t\t/* Log unknown activity types so we can update our svgHashesToActivityTypes table. */\n\t\tif (isActivity) {\n\t\t\tconst svg = svgIcon?.closest('svg');\n\t\t\tconst svgTitle = svg?.getAttribute('title')?.replace(/[ -]/g, '');\n\n\t\t\tif (typeof activityType === 'undefined') {\n\t\t\t\tif (typeof svgTitle === 'undefined') {\n\t\t\t\t\tconsole.warn(`⚠️ Activity “${activityName}”: Unknown activity type for SVG with checksum “${svgHash}” but without SVG title; svg: `, svg, '; entry: ', entry);\n\t\t\t\t} else {\n\t\t\t\t\tsvgHashesToActivityTypes[svgHash] = svgTitle;\n\t\t\t\t\tconsole.info(`🆕 Activity “${activityName}”: Updated svgHashesToActivityTypes with checksum “${svgHash}” for title “${svgTitle}”`);\n\t\t\t\t\tconsole.log(`const svgHashesToActivityTypes = ${JSON.stringify(svgHashesToActivityTypes)};\\n\\n`, svgHashesToActivityTypes);\n\t\t\t\t}\n\t\t\t} else if (typeof svgTitle !== 'undefined' && svgHashesToActivityTypes[svgHash] !== svgTitle && !isVirtual) {\n\t\t\t\tconsole.error(`⚠️ ⚠️ ⚠️ Activity “${activityName}”: SVG CHECKSUM COLLISION?! “${svgHash}” already is “${svgHashesToActivityTypes[svgHash]}”, not “${svgTitle}”! ⚠️ ⚠️ ⚠️ ; svg: `, svg, '; entry: ', entry)\n\t\t\t}\n\t\t\twindow.svgHashesToActivityTypes = svgHashesToActivityTypes;\n\t\t}\n\n\t\tconst isRide = activityType === 'Ride';\n\n\t\tconst isMountainBikeRide = activityType === 'MountainBikeRide';\n\n\t\tconst isGravelRide = activityType === 'GravelRide';\n\n\t\tconst isEBikeRide = activityType === 'EBikeRide';\n\n\t\tconst isRun = activityType === 'Run';\n\n\t\tconst isTrailRun = activityType === 'TrailRun';\n\n\t\tconst isHike = activityType === 'Hike';\n\n\t\tconst isWalk = activityType === 'Walk';\n\n\t\tconst isSwim = activityType === 'Swim';\n\n\t\tconst isWaterSport = activityType === 'WaterSport'\n\t\t\t|| activityType === 'Surfing'\n\t\t\t|| activityType === 'Kitesurf'\n\t\t\t|| activityType === 'Windsurf'\n\t\t\t|| activityType === 'Canoeing'\n\t\t\t|| activityType === 'Kayaking'\n\t\t\t|| activityType === 'Rowing'\n\t\t\t|| activityType === 'StandUpPaddling';\n\n\t\tconst isWinterSport = activityType === 'WinterSport'\n\t\t\t|| activityType === 'AlpineSki'\n\t\t\t|| activityType === 'BackcountrySki'\n\t\t\t|| activityType === 'NordicSki'\n\t\t\t|| activityType === 'RollerSki' /* Hm, not exactly “winter”, but hey… */\n\t\t\t|| activityType === 'CrossCountrySkiing'\n\t\t\t|| activityType === 'Snowboard'\n\t\t\t|| activityType === 'Snowshoe'\n\t\t\t|| activityType === 'IceSkate';\n\n\t\t/* Pretty much equal to: Workout || Crossfit || Elliptical || RockClimbing || StairStepper || WeightTraining || Yoga */\n\t\tconst isOther = !isCommute\n\t\t\t&& !isRide\n\t\t\t&& !isMountainBikeRide\n\t\t\t&& !isGravelRide\n\t\t\t&& !isVirtual\n\t\t\t&& !isEBikeRide\n\t\t\t&& !isRun\n\t\t\t&& !isTrailRun\n\t\t\t&& !isHike\n\t\t\t&& !isWalk\n\t\t\t&& !isSwim\n\t\t\t&& !isWaterSport\n\t\t\t&& !isWinterSport;\n\n\t\t/* Media. */\n\t\tconst hasPhotos = !!entry.querySelector('[data-testid=\"photo\"]');\n\n\t\tconst hasMap = !!entry.querySelector('[data-testid=\"map\"]');\n\n\t\t/* Kudos and comments. */\n\t\tconst numKudos = parseInt((firstActivityFromGroup || entry).querySelector('[data-testid=\"kudos_count\"]')?.textContent, 10);\n\t\tconst hasKudos = numKudos > 0;\n\n\t\tconst numComments = parseInt((firstActivityFromGroup || entry).querySelector('[data-testid=\"comments_count\"]')?.textContent, 10);\n\t\tconst hasComments = numComments > 0;\n\n\t\t/* Statistics. */\n\t\tlet distanceInKm;\n\t\tlet hasDistanceInKm = false;\n\n\t\tlet elevationInM;\n\t\tlet hasElevationInM = false;\n\n\t\tlet durationInS;\n\t\tlet hasDurationInS = false;\n\n\t\tconst stats = [];\n\n\t\t(firstActivityFromGroup || entry).querySelectorAll('[class*=\"list-stats\"] > li, [class*=\"listStats\"] > li').forEach(statContainer => {\n\t\t\tconst statLabelContainer = statContainer.querySelector('[class*=\"stat-label\"], [class*=\"statLabel\"]');\n\t\t\tconst statValueContainer = statContainer.querySelector('[class*=\"stat-value\"], [class*=\"statValue\"]');\n\n\t\t\tif (statLabelContainer && statValueContainer) {\n\t\t\t\tstats.push({label: statLabelContainer.textContent, value: statValueContainer.textContent});\n\t\t\t}\n\t\t});\n\n\t\tstats.forEach(stat => {\n\t\t\tconst label = stat.label;\n\t\t\tconst value = stat.value;\n\n\t\t\t/* TODO: add support/conversion for backwards non-SI units <https://i.redd.it/o093x6j57dk41.jpg> */\n\t\t\tif (label.match(/^(distan|afstand|distância)/i)) {\n\t\t\t\tconst parsedValue = parseDistance(value);\n\t\t\t\tif (Number.isFinite(parsedValue)) {\n\t\t\t\t\thasDistanceInKm = true;\n\t\t\t\t\tdistanceInKm = parsedValue;\n\t\t\t\t}\n\t\t\t} else if (label.match(/^(elev\\S* gain|hoogteverschil|höhenmeter|desnivel|dislivello|ganho de elevação)/i)) {\n\t\t\t\tconst parsedValue = parseElevation(value);\n\t\t\t\tif (Number.isFinite(parsedValue)) {\n\t\t\t\t\thasElevationInM = true;\n\t\t\t\t\televationInM = parsedValue;\n\t\t\t\t}\n\t\t\t} else if (label.match(/^(time|tijd|zeit|tiempo|tempo)/i)) {\n\t\t\t\tlet tmpDurationInS = 0;\n\t\t\t\tlet hasParsedDuration = true;\n\n\t\t\t\tvalue.split(/\\s([0-9]+\\s*[^0-9]+)\\s*/).forEach(durationPart => {\n\t\t\t\t\tlet matches;\n\t\t\t\t\tif (durationPart.trim() === '') {\n\t\t\t\t\t} else if ((matches = durationPart.match(/^\\s*([0-9]+)s/))) {\n\t\t\t\t\t\ttmpDurationInS += parseInt(matches[1], 10);\n\t\t\t\t\t} else if ((matches = durationPart.match(/^\\s*([0-9]+)m/))) {\n\t\t\t\t\t\ttmpDurationInS += parseInt(matches[1], 10) * 60;\n\t\t\t\t\t} else if ((matches = durationPart.match(/^\\s*([0-9]+)[hu]/))) {\n\t\t\t\t\t\ttmpDurationInS += parseInt(matches[1], 10) * 3600;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log(`“${value}”: did not understand duration part “${durationPart}” for entry `, entry);\n\t\t\t\t\t\thasParsedDuration = false;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (hasParsedDuration) {\n\t\t\t\t\thasDurationInS = true;\n\t\t\t\t\tdurationInS = tmpDurationInS;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\t/* Decide whether or not to hide the entry. */\n\t\tlet shouldHide = false;\n\t\tlet reasonForHiding = null;\n\n\t\tif (!isActivity && !isGroupActivity) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Not an activity';\n\t\t} else if (isEBikeRide && !hasPhotos) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'E-bike ride without photos';\n\t\t} else if (isVirtual) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Virtual ride';\n\t\t} else if (!hasMap && !isGroupActivity) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'No map/GPS data (and not a group activity)';\n\t\t} else if (isRide && !hasPhotos && (!hasDistanceInKm || distanceInKm < 30) && (!hasElevationInM || elevationInM < 400)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short ride without photos and without noteworthy elevation gain';\n\t\t} else if (isMountainBikeRide && !hasPhotos && (!hasDistanceInKm || distanceInKm < 20) && (!hasElevationInM || elevationInM < 300)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short mountain bike ride without photos and without noteworthy elevation gain';\n\t\t} else if (isGravelRide && !hasPhotos && (!hasDistanceInKm || distanceInKm < 30) && (!hasElevationInM || elevationInM < 300)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short gravel ride without photos and without noteworthy elevation gain';\n\t\t} else if (isRun && !hasPhotos && (!hasDistanceInKm || distanceInKm < 20)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short run without photos';\n\t\t} else if (isTrailRun && !hasPhotos && (!hasDistanceInKm || distanceInKm < 10)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short trail run without photos';\n\t\t} else if (isHike && !hasPhotos && (!hasDistanceInKm || distanceInKm < 15)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short hike without photos';\n\t\t} else if (isWalk && !hasPhotos && (!hasDistanceInKm || distanceInKm < 10)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short walk without photos';\n\t\t} else if (isSwim && !hasPhotos && (!hasDurationInS || durationInS < 3600)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short swim without photos';\n\t\t} else if (isWinterSport && !hasPhotos) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Winter sports without photos';\n\t\t} else if (isOther && !hasPhotos && (!hasDurationInS || durationInS < 3600)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Other short activity without photos';\n\t\t} else if (isCommute && !hasPhotos && (!hasDistanceInKm || distanceInKm < 30)) {\n\t\t\tshouldHide = true;\n\t\t\treasonForHiding = 'Short commute without photos';\n\t\t}\n\n\t\tif (shouldHide) {\n\t\t\tentry.classList.add('xxxJanStravaHidden');\n\t\t}\n\n\t\t/* Show the parsed information we use to decide the fate of the entry. */\n\t\tentry.title = [\n\t\t\t'Decision:',\n\t\t\t`shouldHide = ${shouldHide}`,\n\t\t\treasonForHiding\n\t\t\t\t? `reasonForHiding = ${reasonForHiding}`\n\t\t\t\t: null,\n\n\t\t\t'Feed entry types:',\n\t\t\t`isActivity = ${isActivity}`,\n\t\t\t`isGroupActivity = ${isGroupActivity}`,\n\t\t\tisClubJoin\n\t\t\t\t? `isClubJoin = ${isClubJoin}`\n\t\t\t\t: null,\n\t\t\tisChallengeJoin\n\t\t\t\t? `isChallengeJoin = ${isChallengeJoin}`\n\t\t\t\t: null,\n\t\t\tisPromo\n\t\t\t\t? `isPromo = ${isPromo}`\n\t\t\t\t: null,\n\n\t\t\t'Tags/special properties:',\n\t\t\t`isOwnActivity = ${isOwnActivity}`,\n\t\t\t`isCommute = ${isCommute}`,\n\t\t\t`isVirtual = ${isVirtual}`,\n\n\t\t\t'Activity type:',\n\t\t\tisRide\n\t\t\t\t? `isRide = ${isRide}`\n\t\t\t\t: null,\n\t\t\tisMountainBikeRide\n\t\t\t\t? `isMountainBikeRide = ${isMountainBikeRide}`\n\t\t\t\t: null,\n\t\t\tisGravelRide\n\t\t\t\t? `isGravelRide = ${isGravelRide}`\n\t\t\t\t: null,\n\t\t\tisEBikeRide\n\t\t\t\t? `isEBikeRide = ${isEBikeRide}`\n\t\t\t\t: null,\n\t\t\tisRun\n\t\t\t\t? `isRun = ${isRun}`\n\t\t\t\t: null,\n\t\t\tisTrailRun\n\t\t\t\t? `isTrailRun = ${isTrailRun}`\n\t\t\t\t: null,\n\t\t\tisHike\n\t\t\t\t? `isHike = ${isHike}`\n\t\t\t\t: null,\n\t\t\tisWalk\n\t\t\t\t? `isWalk = ${isWalk}`\n\t\t\t\t: null,\n\t\t\tisSwim\n\t\t\t\t? `isSwim = ${isSwim}`\n\t\t\t\t: null,\n\t\t\tisWaterSport\n\t\t\t\t? `isWaterSport = ${isWaterSport}`\n\t\t\t\t: null,\n\t\t\tisWinterSport\n\t\t\t\t? `isWinterSport = ${isWinterSport}`\n\t\t\t\t: null,\n\t\t\tisOther\n\t\t\t\t? `isOther = ${isOther}`\n\t\t\t\t: null,\n\n\t\t\t'Media:',\n\t\t\t`hasPhotos = ${hasPhotos}`,\n\t\t\t`hasMap = ${hasMap}`,\n\n\t\t\t'Kudos and comments:',\n\t\t\thasKudos\n\t\t\t\t? `numKudos = ${numKudos}`\n\t\t\t\t: `hasKudos = ${hasKudos}`,\n\t\t\thasComments\n\t\t\t\t? `numComments = ${numComments}`\n\t\t\t\t: `hasComments = ${hasComments}`,\n\n\t\t\t'Statistics:',\n\t\t\thasDistanceInKm\n\t\t\t\t? `distanceInKm = ${distanceInKm}`\n\t\t\t\t: `hasDistanceInKm = ${hasDistanceInKm}`,\n\t\t\thasElevationInM\n\t\t\t\t? `elevationInM = ${elevationInM}`\n\t\t\t\t: null,\n\t\t\thasDurationInS\n\t\t\t\t? `durationInS = ${durationInS}`\n\t\t\t\t: null,\n\t\t\thasDistanceInKm && hasDurationInS\n\t\t\t\t? `calculatedAverageSpeed = ${(distanceInKm / durationInS * 3600).toFixed(1)} km/h`\n\t\t\t\t: null,\n\n\t\t\t`${entry.title ? '\\n\\n======\\n\\n' + entry.title : ''}`\n\t\t].filter(_ => _).join('\\n').replace(/^([A-Z])/gm, '\\n$1').trim();\n\t}", "function journalEntry() {\r\n let journalEntry = prompt(` Okay ${userName} , Reflect on why you chose what you did. Describe how that rating makes you feel,why you chose that, how it makes you feel to have that rating, and plans for the upcoming days either change it or keep it the same! Please press the button under PRESS Here to log your answer !`, \" Please press the button under PRESS HERE after completing this entry!\");\r\n console.log(` You journal entry was: ${journalEntry}`);\r\n return journalEntry;\r\n // Enter in as much text as necessary about what you learned, how you felt, and plans for the upcoming days\r\n\r\n // what do I do with what I have here, \r\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 themeFeedEntry(entry) {\n\t\tclasses = [ 'entry', 'well' ];\n\t\tif (new Date(entry.publishedDate).isToday()) {\n\t\t\tclasses.push('today');\n\t\t}\n\t\toutput = '<div class=\"' + classes.join(' ') + '\">';\n\t\toutput += '<h2 class=\"title\"><a href=\"' + entry.link + '\" data-eid=\"' + entry.eid + '\" rel=\"external\" target=\"_blank\">' + entry.title + '</a></h2>';\n\t\toutput += '<h2><small>' + entry.author + '</small></h2>';\n\t\toutput += '<p><small>' + entry.publishedDate + '</small></p>';\n\t\toutput += '<p>' + entry.contentSnippet + '</p>';\n\t\toutput += '<p><small>Tagged under ' + entry.categories.join(', ') + '</small></p>';\n\t\toutput += '<div class=\"actions\"><a class=\"btn twitter-share-button\" href=\"http://twitter.com/intent/tweet?text=' + encodeURIComponent(entry.title + ' ' + entry.link) + '&related=pennolson,amarnus\">Share on Twitter</a></div>';\n\t\toutput += '</div>';\n\t\treturn output;\n\t}", "function translate(text, dictionary){\n\t// TODO: implementați funcția\n\t// TODO: implement the function\n}", "function formatOsmEntitiesToLink(text){\n if (text) {\n var shortCodeRegex = /\\[\\w+\\/\\d+(,?\\s*\\w+\\/\\d+)*\\]/g;\n var entityRegex = /(\\w+)\\/(\\d+)/;\n var entityMap = {\n n: 'node',\n node: 'node',\n w: 'way',\n way: 'way',\n r: 'relation',\n rel: 'relation',\n relation: 'relation'\n };\n\n var shortCodeMatch = null;\n while (shortCodeMatch = shortCodeRegex.exec(text)) {\n // There could be multiple entities in a combo code, so split them up\n // and expand each one. Entities must be comma or space separated.\n var entities = shortCodeMatch[0].slice(1, -1).split(/,\\s*|\\s+/);\n\n var expandedEntities = entities.map(function(entity) {\n var entityMatch = entityRegex.exec(entity);\n // Ignore short codes we don't explicitly support\n if (!entityMap[entityMatch[1]]) {\n return null;\n }\n\n return {\n linkText: entityMap[entityMatch[1]] + '/' + entityMatch[2],\n linkTitle: entityMap[entityMatch[1]] + ' ' + entityMatch[2],\n overpassQuery: entityMap[entityMatch[1]] + '(' + entityMatch[2] + ');'\n };\n });\n\n // If there are any null entity expansions, we have an unsupported code, so ignore it.\n if (expandedEntities.indexOf(null) !== -1) {\n continue;\n }\n\n // Combine expansion data from all entities into final link\n var linkText = expandedEntities.map(function(e) { return e.linkText; }).join(', ');\n var linkTitle = expandedEntities.map(function(e) { return e.linkTitle; }).join(', ');\n var overpassQuery =\n '(' +\n expandedEntities.map(function(e) { return e.overpassQuery; }).join('') +\n ');(._;>;);out;';\n var linkUrl='http://overpass-turbo.eu/map.html?Q=' + encodeURIComponent(overpassQuery);\n var link = '<a target=\"_blank\" title=\"' + linkTitle + '\" href=\"' + linkUrl + '\">' + linkText + '</a>';\n\n // Replace short code in comment with generated link\n text = text.replace(shortCodeMatch[0], link);\n }\n }\n\n return text;\n }", "function PrepareNewPostForAdding(text) {\r\n //Remove extra spaces\r\n text = $.trim(text);\r\n\r\n //Get youtube video id instead of full link\r\n text = text.replace(/\\[[^\\/].*?\\]/g, function(item) {\r\n if (item.indexOf(\"video\") > -1) {\r\n var attrData = GetYoutubeVideoId(GetAtrrData(item, \"src\"));\r\n item = SetAttrData(item, \"src\", attrData);\r\n }\r\n\r\n return item;\r\n });\r\n\r\n return text;\r\n}", "function puttext(identity)\n{\n\tvar btn_alphabet=String(identity.innerHTML);\n\tbtn_alphabet=btn_alphabet.split(/>|</);\n\tdocument.getElementById(\"enteredText\").value += String(btn_alphabet[2]);\n}", "function createTextPost(template, post) {\n template.content.querySelector('.postTitle').innerHTML = post.title || 'Post Title';\n template.content.querySelector('.postBody').innerHTML = post.body;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constraint equation GaussSeidel solver.
function GSSolver(){Solver.call(this);/** * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations. * @property iterations * @type {Number} * @todo write more about solver and iterations in the wiki */this.iterations=10;/** * When tolerance is reached, the system is assumed to be converged. * @property tolerance * @type {Number} */this.tolerance=1e-7;}
[ "function gauss(x, s) {\n // 2.5066282746310005 is sqrt(2*pi)\n return Math.exp(-0.5 * x*x / (s*s)) / (s * 2.5066282746310005);\n}", "deleteVertex(vertex) {\n\t\t\tlet freeOfConstraint;\n\t\t\tlet iterEdges = new FromVertexToOutgoingEdges();\n\t\t\titerEdges.fromVertex = vertex;\n\t\t\titerEdges.realEdgesOnly = false;\n\t\t\tlet edge;\n\t\t\tlet outgoingEdges = [];\n\t\t\tfreeOfConstraint = vertex.fromConstraintSegments.length == 0 ? true : false;\n\t\t\tlet bound = [];\n\t\t\tlet realA = false;\n\t\t\tlet realB = false;\n\t\t\tlet boundA = [];\n\t\t\tlet boundB = [];\n\n\t\t\tif (freeOfConstraint) {\n\t\t\t\t//while(edge = iterEdges.next()) {\n\t\t\t\twhile ((edge = iterEdges.next()) != null) {\n\t\t\t\t\toutgoingEdges.push(edge);\n\t\t\t\t\tbound.push(edge.nextLeftEdge);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// we check if the vertex is an end point of a constraint segment\n\t\t\t\tlet edges;\n\t\t\t\tlet _g1 = 0;\n\t\t\t\tlet _g = vertex.fromConstraintSegments.length;\n\n\t\t\t\twhile (_g1 < _g) {\n\t\t\t\t\tlet i1 = _g1++;\n\t\t\t\t\tedges = vertex.fromConstraintSegments[i1].edges; //if(edges[0].originVertex == vertex || edges[edges.length - 1].destinationVertex == vertex) return false;\n\n\t\t\t\t\tif (edges[0].originVertex.id === vertex.id || edges[edges.length - 1].destinationVertex.id === vertex.id) return false;\n\t\t\t\t} // we check the count of adjacent constrained edges\n\n\n\t\t\t\tlet count = 0; //while(edge = iterEdges.next()) {\n\n\t\t\t\twhile ((edge = iterEdges.next()) != null) {\n\t\t\t\t\toutgoingEdges.push(edge);\n\n\t\t\t\t\tif (edge.isConstrained) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t\tif (count > 2) return false;\n\t\t\t\t\t}\n\t\t\t\t} // if not disqualified, then we can process\n\n\n\t\t\t\tboundA = [];\n\t\t\t\tboundB = [];\n\t\t\t\tlet constrainedEdgeA = null;\n\t\t\t\tlet constrainedEdgeB = null;\n\t\t\t\tlet edgeA = new Edge();\n\t\t\t\tlet edgeB = new Edge();\n\n\t\t\t\tthis._edges.push(edgeA);\n\n\t\t\t\tthis._edges.push(edgeB);\n\n\t\t\t\tlet _g11 = 0;\n\t\t\t\tlet _g2 = outgoingEdges.length;\n\n\t\t\t\twhile (_g11 < _g2) {\n\t\t\t\t\tlet i2 = _g11++;\n\t\t\t\t\tedge = outgoingEdges[i2];\n\n\t\t\t\t\tif (edge.isConstrained) {\n\t\t\t\t\t\tif (constrainedEdgeA == null) {\n\t\t\t\t\t\t\tedgeB.setDatas(edge.destinationVertex, edgeA, null, null, true, true);\n\t\t\t\t\t\t\tboundA.push(edgeA);\n\t\t\t\t\t\t\tboundA.push(edge.nextLeftEdge);\n\t\t\t\t\t\t\tboundB.push(edgeB);\n\t\t\t\t\t\t\tconstrainedEdgeA = edge;\n\t\t\t\t\t\t} else if (constrainedEdgeB == null) {\n\t\t\t\t\t\t\tedgeA.setDatas(edge.destinationVertex, edgeB, null, null, true, true);\n\t\t\t\t\t\t\tboundB.push(edge.nextLeftEdge);\n\t\t\t\t\t\t\tconstrainedEdgeB = edge;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (constrainedEdgeA == null) boundB.push(edge.nextLeftEdge);else if (constrainedEdgeB == null) boundA.push(edge.nextLeftEdge);else boundB.push(edge.nextLeftEdge);\n\t\t\t\t} // keep infos about reality\n\n\n\t\t\t\trealA = constrainedEdgeA.leftFace.isReal;\n\t\t\t\trealB = constrainedEdgeB.leftFace.isReal; // we update the segments infos\n\n\t\t\t\tedgeA.fromConstraintSegments = constrainedEdgeA.fromConstraintSegments.slice(0);\n\t\t\t\tedgeB.fromConstraintSegments = edgeA.fromConstraintSegments;\n\t\t\t\tlet index;\n\t\t\t\tlet _g12 = 0;\n\t\t\t\tlet _g3 = vertex.fromConstraintSegments.length;\n\n\t\t\t\twhile (_g12 < _g3) {\n\t\t\t\t\tlet i3 = _g12++;\n\t\t\t\t\tedges = vertex.fromConstraintSegments[i3].edges;\n\t\t\t\t\tindex = edges.indexOf(constrainedEdgeA);\n\n\t\t\t\t\tif (index != -1) {\n\t\t\t\t\t\tedges.splice(index - 1, 2, edgeA); //edges.splice(index - 1,2);\n\t\t\t\t\t\t//edges.splice(index - 1,0,edgeA);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tedges.splice(edges.indexOf(constrainedEdgeB) - 1, 2, edgeB); //let index2 = edges.indexOf(constrainedEdgeB) - 1;\n\t\t\t\t\t\t//edges.splice(index2,2);\n\t\t\t\t\t\t//edges.splice(index2,0,edgeB);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} // Deletion of old faces and edges\n\n\n\t\t\tlet faceToDelete;\n\t\t\tlet _g13 = 0;\n\t\t\tlet _g4 = outgoingEdges.length;\n\n\t\t\twhile (_g13 < _g4) {\n\t\t\t\tlet i4 = _g13++;\n\t\t\t\tedge = outgoingEdges[i4];\n\t\t\t\tfaceToDelete = edge.leftFace;\n\n\t\t\t\tthis._faces.splice(this._faces.indexOf(faceToDelete), 1);\n\n\t\t\t\tfaceToDelete.dispose();\n\t\t\t\tedge.destinationVertex.edge = edge.nextLeftEdge;\n\n\t\t\t\tthis._edges.splice(this._edges.indexOf(edge.oppositeEdge), 1);\n\n\t\t\t\tedge.oppositeEdge.dispose();\n\n\t\t\t\tthis._edges.splice(this._edges.indexOf(edge), 1);\n\n\t\t\t\tedge.dispose();\n\t\t\t}\n\n\t\t\tthis._vertices.splice(this._vertices.indexOf(vertex), 1);\n\n\t\t\tvertex.dispose(); // finally we triangulate\n\n\t\t\tif (freeOfConstraint) this.triangulate(bound, true);else {\n\t\t\t\tthis.triangulate(boundA, realA);\n\t\t\t\tthis.triangulate(boundB, realB);\n\t\t\t}\n\t\t\treturn true;\n\t\t}", "gaussJordanEliminate() {\n // Simplify all rows\n let cells = this.cells = this.cells.map(Matrix.simplifyRow);\n // Compute row echelon form (REF)\n let numPivots = 0;\n for (let i = 0; i < this.numCols; i++) {\n // Find pivot\n let pivotRow = numPivots;\n while (pivotRow < this.numRows && cells[pivotRow][i] == 0)\n pivotRow++;\n if (pivotRow == this.numRows)\n continue;\n const pivot = cells[pivotRow][i];\n this.swapRows(numPivots, pivotRow);\n numPivots++;\n // Eliminate below\n for (let j = numPivots; j < this.numRows; j++) {\n const g = gcd(pivot, cells[j][i]);\n cells[j] = Matrix.simplifyRow(Matrix.addRows(Matrix.multiplyRow(cells[j], pivot / g), Matrix.multiplyRow(cells[i], -cells[j][i] / g)));\n }\n }\n // Compute reduced row echelon form (RREF), but the leading coefficient need not be 1\n for (let i = this.numRows - 1; i >= 0; i--) {\n // Find pivot\n let pivotCol = 0;\n while (pivotCol < this.numCols && cells[i][pivotCol] == 0)\n pivotCol++;\n if (pivotCol == this.numCols)\n continue;\n const pivot = cells[i][pivotCol];\n // Eliminate above\n for (let j = i - 1; j >= 0; j--) {\n const g = gcd(pivot, cells[j][pivotCol]);\n cells[j] = Matrix.simplifyRow(Matrix.addRows(Matrix.multiplyRow(cells[j], pivot / g), Matrix.multiplyRow(cells[i], -cells[j][pivotCol] / g)));\n }\n }\n }", "function vgge(FI,LA) \n{//* PRETVORBA GEOGRAFSKIH KOORDINAT T(FI,LA) V RAVNINSKE\n//* GAUSS-KRUGERJEVE MODULIRANE KOORDINATE T(Y,X) NA\n//* BESSELOVEM ELIPSOIDU\n// double,longint - za pascal in fortran\nvar FI, LA,\n A1,A2,A3,A4,A5,A6,T,X,Y,XG,YG,LAM,XX,\n E2,PI,AA,E4,E6,E8,E10,A,B,C,D,E,F,BB,EE,POP,\n FSEK,LSEK,B1,B2,B3,\n FMIN,LMIN,LST,FST,CONA, name,\n \n\n // FI=1*gsstr+(gsmr*60+1*gsser)/3600;\n // LA=1*gdstr+(gdmr*60+1*gdser)/3600;\n \n CONA = 5;\n B1 = 0.9999;\n B2 = 500000.0;\n B3 = 1000000.0;\n// VELJA ZA PETO CONO AA,BB elementi besselovega elipsoida\n\n\n\n AA = 6377397.155;\n BB = 6356078.962818;\n EE = (AA*AA-BB*BB)/(BB*BB);\n PI = 4.0 * Math.atan(1.0);\n E2 = (AA*AA-BB*BB)/(AA*AA);\n E4 = E2*E2;\n E6 = E4*E2;\n E8 = E4*E4;\n E10 = E6*E4;\n A = 1.0+3.0*E2/4.0+45.0*E4/64.0+175.0*E6/256.0+11025.0*\n E8/16384.0+43659.0*E10/65536.0;\n B = 3.0*E2/4.0+15.0*E4/16.0+525.0*E6/512.0+2205.0*E8/2048.0+\n 72765.0*E10/65536.0;\n C = 15.0*E4/64.0+105.0*E6/256.0+2205.0*E8/4096.0+10395.0*E10/16384.0;\n D = 35.0*E6/512.0+315.0*E8/2048.0+31185.0*E10/131072.0;\n E = 315.0*E8/16384.0+3465.0*E10 /65536.0;\n F = 693.0*E10/131072.0;\n\n \n FI = FI*PI/180;\n LA = LA*PI/180;\n T = Math.sin(FI)/Math.cos(FI);\n A1 = AA*AA/Math.sqrt(AA*AA+BB*BB*(T*T));\n A2 = A1*Math.sin(FI)/2.0;\n A3 = A1*(Math.cos(FI)*Math.cos(FI))/6.0*(1.0-T*T+EE*Math.cos(FI)*Math.cos(FI));\n A4 = A1*Math.sin(FI)*(Math.cos(FI)*Math.cos(FI))/24.0*(5.0-T*T+9.0*EE*(Math.cos(FI)*Math.cos(FI)) );\n A5 = A1*Math.sin(FI)*Math.cos(FI)*Math.cos(FI)*Math.cos(FI)*Math.cos(FI)/120.0*(5.0-18.0*T*T+(T*T*T*T)\n +EE*(14.0-72.0*(Math.sin(FI)*Math.sin(FI)) ));\n\n A6 = A1*Math.sin(FI)*Math.cos(FI)*Math.cos(FI)*Math.cos(FI)*Math.cos(FI)/720.0*(61.0-58.0*(T*T)+(T*T*T*T) );\n LAM = LA-CONA*3.0*PI/180.0;\n XX = AA*(1.0-E2)*(A*FI-B/2.0*Math.sin(2.0*FI)+C/4.0*Math.sin(4.0*FI)-\n D/6.0*Math.sin(6.0*FI)+E/8.0*Math.sin(8.0*FI)-F/10.0*Math.sin(10.0*FI));\n\n XG = 1*XX+A2*(LAM*LAM)+A4*LAM*LAM*LAM*LAM+A6*(LAM*LAM*LAM*LAM)*(LAM*LAM);\n YG = A1*LAM+A3*(LAM*LAM)*LAM+A5*(LAM*LAM*LAM*LAM)*LAM;\n Y = YG*B1+1*B2+CONA*B3;\n X = XG*B1;\n\n \n\n // ix := Trunc(x/10)*10;\n // iy := Trunc(y/10)*10;\n \n //ix = Trunc(X);\n //iy = Trunc(Y);\n //ix = Math.round(X);\n //iy = Math.round(Y);\n ix = 1*X;\n iy = 1*Y;\n\n//if (racun==1) {return ix;}\n//if (racun==2) {return iy;}\n\n// spodaj konec funkcije iz lam in fi v vgaussk\n}", "function calcSuper(gSal) {\r\n return (gSal * .095)\r\n}", "function LUDecomp(k) {\n\t\t// Assuming k is square matrix in Yale format\n\t\t// k = [A,IA,JA]\n\t\t// U =k;\n\t\tvar N = k[1].length-1;\n\t\t/**var U_A = k[0];\n\t\tvar U_IA = k[1];\n\t\tvar U_JA = k[2];**/\n\t\tvar upper = k;\n\t\t//alert(\"N = \"+N);\n\t\t//set first 1 in place\n\t\tvar L_A = new Array();\n\t\tvar L_IA = new Array(N+1);\n\t\tL_IA[N]=0;\n\t\tvar L_JA = new Array();\n\t\tvar lower = [L_A,L_IA,L_JA];\n\t\t/**var n = 0; \n\t\twhile(n < N){\n\t\t\t// Insert ones along the diagonal in L_A \n\t\t\t// L_IA to be formed later\n\t\t\t\n\t\t}**/\n\t\t// Do decomposition\n\t\tfor(var j=0; j<N; j++){\n\t\t\t\n\t\t\tlower = yaleInsert(lower, 1, j, j);\n\t\t\tfor(var i=(j+1);i<N; i++){\n\t\t\t\t\n\t\t\t\t\tvar U_ij = yaleGet(upper,i,j);\n\t\t\t\t\tif(U_ij!=0){\n\t\t\t\t\t\t// L[i][j] = U[i][j] / U[j][j];\n\t\t\t\t\t\tvar U_jj = yaleGet(upper,j,j);\n\t\t\t\t\t\t//alert(\"denominator = \"+xD);\n\t\t\t\t\t\tvar L_ij=U_ij/U_jj;\n\t\t\t\t\t\tlower = yaleInsert(lower, L_ij, i, j);\n\t\t\t\t\t\t//alert(\"made it\"+lower[0]);\n\t\t\t\t\t\tfor(var z=j; z<N; z++){\n\t\t\t\t\t\t\t//U[i][z] = U[i][z]-L[i][j]*U[j][z];\n\t\t\t\t\t\t\t//alert(\"z = \"+z);\n\t\t\t\t\t\t\tvar U_iz=yaleGet(upper,i,z);\n\t\t\t\t\t\t\t//alert(\"U_iz = \"+U_iz);\n\t\t\t\t\t\t\tvar U_jz = yaleGet(upper,j,z);\n\t\t\t\t\t\t\t//alert(\"U_jz = \"+U_jz);\n\t\t\t\t\t\t\tU_iz-=L_ij*U_jz;\n\t\t\t\t\t\t\t//alert(\"new U_iz = \"+U_iz);\n\t\t\t\t\t\t\tupper = yaleInsert(upper,U_iz, i, z);\t\n\t\t\t\t\t\t}\t\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t\t/** // Do decomposition\n\t\t\tfor(var j=0; j<(N-1); j++){\n\t\t\t\tfor(var i=(j+1);i<N; i++){\n\t\t\t\t\tif(U[i][j] != 0){\n\t\t\t\t\t\tL[i][j] = U[i][j] / U[j][j];\n\t\t\t\t\t\tfor(var z=j; z<N; z++){\n\t\t\t\t\t\t\tU[i][z] = U[i][z]-L[i][j]*U[j][z];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse{ L[i][j]=0;}\n\t\t\t\t}\n\t\t\t} **/\n\t\t//L & U should be done\n\t\t// create an object to return upper and lower matrices\n\t\t\tvar ULpair = new Object();\n\t\t\t\n\t\t\tvar L = lower;\n\t\t\tvar U = upper;\n\t\t\t//alert(\"end U_A = \"+U_A);\n\t\t\t//alert(\"end U_IA = \"+U_IA);\n\t\t\t//alert(\"end U_JA = \"+U_JA);\n\t\t\tULpair.L = L;\n\t\t\tULpair.U = U;\n\t\t\treturn ULpair;\n\t\t\n\t}", "function VxEuclideanRythm ()\n{\n\tthis.k = 4;\n\tthis.N = 16;\n\tthis.R = 0;\n\tthis.algorithm = 'bjorklund';\n\tthis.integermode = 0;\n}", "visitAdd_constraint_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "insertKnotU(un, r) {\n let p = this.u_degree;\n // Knot will be inserted between [k, k+1)\n let k = helper_1.findSpan(p, this.u_knots.data, un);\n // If un already exists in the knot vector, s is its multiplicity\n let s = common_1.count(this.u_knots, un, 0);\n if (r + s > p) {\n throw new Error('Knot insertion exceeds knot multiplicity beyond degree');\n }\n let mU = this.u_knots.length - 1;\n let nU = mU - this.u_degree - 1;\n let mV = this.v_knots.length - 1;\n let nV = mV - this.v_degree - 1;\n let P = this.cpoints;\n let Q = common_1.empty([nU + 1 + r, nV + 1, this.dimension]);\n let UP = this.u_knots;\n let UQ = common_1.empty([UP.length + r]);\n let VP = this.v_knots;\n let VQ = common_1.empty([VP.length]);\n // Load u-vector\n for (let i = 0; i < k + 1; i++) {\n UQ.set(i, UP.get(i));\n }\n for (let i = 1; i < r + 1; i++) {\n UQ.set(k + i, un);\n }\n for (let i = k + 1; i < mU + 1; i++) {\n UQ.set(i + r, UP.get(i));\n }\n // Copy v-vector\n VQ.copyfrom(VP);\n let alpha = common_1.empty([p + 1, r + 1]);\n let R = common_1.empty([p + 1, this.dimension]);\n let L = 0;\n // Pre-calculate alphas\n for (let j = 1; j < r + 1; j++) {\n L = k - p + j;\n for (let i = 0; i < p - j - s + 1; i++) {\n alpha.set(i, j, (un - UP.get(L + i)) / (UP.get(i + k + 1) - UP.get(L + i)));\n }\n }\n for (let row = 0; row < nV + 1; row++) {\n // Save unaltered control points\n for (let i = 0; i < k - p + 1; i++) {\n Q.set(i, row, P.get(i, row));\n }\n for (let i = k - s; i < nU + 1; i++) {\n Q.set(i + r, row, P.get(i, row));\n }\n // Load auxiliary control points\n for (let i = 0; i < p - s + 1; i++) {\n R.set(i, P.get(k - p + i, row));\n }\n for (let j = 1; j < r + 1; j++) {\n L = k - p + j;\n for (let i = 0; i < p - j - s + 1; i++) {\n R.set(i, common_1.add(common_1.mul(alpha.get(i, j), R.get(i + 1)), common_1.mul(1.0 - alpha.get(i, j), R.get(i))));\n }\n Q.set(L, row, R.get(0));\n Q.set(k + r - j - s, row, R.get(p - j - s));\n }\n // Load the remaining control points\n for (let i = L + 1; i < k - s; i++) {\n Q.set(i, row, R.get(i - L));\n }\n }\n this.cpoints = Q;\n this.v_knots = VQ;\n }", "function evj( x , ne , en )\n {\n\n const evc = ( this.nc - 1 ) ;\n\n if( ! en ) en = 1.0e-8 ;\n if( ! ne ) ne = 100 ;\n\n let se = undefined ;\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let n = undefined ;\n\n let lij = undefined ;\n let p = undefined ;\n let sp = undefined ;\n let ps = undefined ;\n\n let ip = undefined ;\n let jq = undefined ;\n\n let c = undefined ;\n let s = undefined ;\n\n let w = undefined ;\n let t = undefined ;\n let tt = undefined ;\n\n let vipk = undefined ;\n let vjqk = undefined ;\n\n let xipip = undefined ;\n let xjqjq = undefined ;\n let xipjq = undefined ;\n\n let xipk = undefined ;\n let xjqk = undefined ;\n \n let evn = undefined ;\n \n let evv = new Array( x.nv ) ;\n\n\n for( i = 0; i < x.nv; evv[ i ] = x.v[ i++ ] ) ;\n\n\n if( ! this.nd )\n\n for( i = 0; i < this.nr; this.v[ this.idx( i , i++ ) ] = 1 )\n \n for( j = 0; j < this.nr; this.v[ this.idx( i , j++ ) ] = 0 ) ;\n\n\n for( se = 1 , n = 0; (n < ne) && (Math.abs( se ) > en); ++n )\n {\n\n for( ip = 0; (ip < (x.nr - 1)); ++ip )\n\n for( jq = (ip + 1); (jq < x.nr); ++jq )\n {\n\n xipip = evv[ x.idx( ip , ip ) ] ;\n xjqjq = evv[ x.idx( jq , jq ) ] ;\n xipjq = evv[ x.idx( ip , jq ) ] ;\n\n if( xipjq )\n {\n\n w = ( (xjqjq - xipip) / (2 * xipjq) ) ;\n\n [ t , s , tt , c ] = srt( (2 * w) , (- 1) ) ;\n\n if( Math.abs( t ) > Math.abs( tt ) ) t = tt ;\n\n\n tt = ( t * t );\n\n s = ( t / Math.sqrt( 1 + tt ) ) ;\n\n c = ( 1 / Math.sqrt( 1 + tt ) );\n\n tt = ( s / (1 + c) ) ;\n\n\n evv[ x.idx( ip , ip ) ] = ( xipip - (t * xipjq) ) ;\n\n evv[ x.idx( jq , jq ) ] = ( xjqjq + (t * xipjq) ) ;\n\n evv[ x.idx( ip , jq ) ] = 0 ;\n\n evv[ x.idx( jq , ip ) ] = 0 ;\n\n\n if( ! x.d )\n {\n\n \n for( k = 0; k < x.nc; ++k )\n {\n\n if( (k != ip) && (k != jq) )\n {\n\n xipk = evv[ x.idx( ip , k ) ] ;\n\n xjqk = evv[ x.idx( jq , k ) ] ;\n\n evv[ x.idx( ip , k ) ] = ( xipk - (s * (xjqk + (tt * xipk))) ) ;\n\n evv[ x.idx( jq , k ) ] = ( xjqk + (s * (xipk - (tt * xjqk))) ) ;\n\n } ; // end if{} -\n\n\n } ; // end for()\n\n\n for( k = 0; k < x.nr; ++k )\n {\n\n if( (k != ip) && (k != jq) )\n {\n\n xipk = evv[ x.idx( k , ip ) ] ;\n\n xjqk = evv[ x.idx( k , jq ) ] ;\n\n evv[ x.idx( k , ip ) ] = ( xipk - (s * (xjqk + (tt * xipk))) ) ;\n\n evv[ x.idx( k , jq ) ] = ( xjqk + (s * (xipk - (tt * xjqk))) ) ;\n\n } ; // end if{} -\n\n\n } ; // end for()\n\n\n } ; // end if{} -\n\n\n if( ! this.nd )\n\n for( k = 0; k < this.nr; ++k )\n { \n\n vipk = this.v[ this.idx( ip , k ) ] ;\n\n vjqk = this.v[ this.idx( jq , k ) ] ;\n\n this.v[ this.idx( ip , k ) ] = ( (c * vipk) - (s * vjqk) ) ;\n\n this.v[ this.idx( jq , k ) ] = ( (s * vipk) + (c * vjqk) ) ;\n\n } ; // end if{}-\n\n\n } ; // end if{} -\n\n\n // console.log( 'n=' , n , 'ip=' , ip , 'jq=' , jq , 'evv=' , evv ) ;\n\n\n } ; // end for()\n\n\n for( se = 0 , i = 0; i < x.nr; ++i )\n\n for( j = (i + 1); j < x.nc; se += Math.abs( evv[ x.idx( i , j++ ) ] ) ) ;\n\n\n for( i = 0; i < this.nr; ++i )\n\n this.v[ this.idx( i , evc ) ] = evv[ x.idx( i , i ) ] ;\n\n\n } ; // end for()\n\n\n return( n ) ;\n\n\n }", "function solveHomogeneous() {\n // No free variables - so we've got only trivial solution\n if(boundVariables.length == n)\n return null;\n\n // Get basis vectors corresponding to free variables\n var basis = [];\n for(var x = 0, i = 0; x < n; x++) {\n // Since boundVariables is strictly monotonic increasing sequence,\n // it is easy to get indices of free variables from it. (missing numbers)\n if(i >= boundVariables.length || boundVariables[i] != x) {\n var v = math.zeros(n, 1);\n v.set([x, 0], 1);\n\n basis.push(v);\n }\n\n else\n i++;\n }\n\n // Gauss backward substitution\n // Loop through rows corresponding to bound variables\n for(var row = boundVariables.length - 1; row >= 0; row--) {\n var x = boundVariables[row];\n var col = x;\n\n console.assert(math.equal(r.get([row, col]), 1), 'Pivot point must be 1');\n\n // Solve variable in each basis vector\n basis.map(function(v) {\n // We got a row:\n // 0 0 ... 0 1 A B C ... = 0, where 1 is in x column and A B C are in solved variables columns\n // so express bound variable x via solved variables\n\n // Multiply row by solved variables\n var value = math.multiply(\n r.subset(math.index(row, math.range(0, columns))),\n v.subset(math.index(math.range(0, n), 0))\n );\n\n // It seems value may turn out to be 1x1 matrix, so get rid of this wrap\n if(math.typeof(value) == 'Matrix')\n value = value.get([0, 0]);\n\n // Finally solve this variable\n v.set([x, 0], math.multiply(-1, value)); // Should be divided by 1 as well (pivot point)\n\n return v;\n });\n }\n\n return basis;\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 }", "addpathcost(q, x) { this.dmin(q, this.dmin(q) + x); }", "static gaussRand() {\n return Math.sqrt(2 * Ex.expRand()) * Math.sin(2 * Math.PI * Math.random());\n }", "insertKnotV(vn, r) {\n let q = this.v_degree;\n // Knot will be inserted between [k,k+1)\n let k = helper_1.findSpan(this.v_degree, this.v_knots.data, vn);\n // If v already exists in knot vector, s is its multiplicity\n let s = common_1.count(this.v_knots, vn, 0);\n if (r + s > q) {\n throw new Error('Knot insertion exceeds knot multiplicity beyond degree');\n }\n let mU = this.u_knots.length - 1;\n let nU = mU - this.u_degree - 1;\n let mV = this.v_knots.length - 1;\n let nV = mV - this.v_degree - 1;\n let P = this.cpoints;\n let Q = common_1.empty([nU + 1, nV + r + 1, this.dimension]);\n let UP = this.u_knots;\n let UQ = common_1.empty([UP.length]);\n let VP = this.v_knots;\n let VQ = common_1.empty([VP.length + r]);\n // Copy u knot vector\n UQ.copyfrom(UP);\n // Load v knot vector\n for (let i = 0; i < k + 1; i++) {\n VQ.set(i, VP.get(i));\n }\n for (let i = 1; i < r + 1; i++) {\n VQ.set(k + i, vn);\n }\n for (let i = k + 1; i < mV + 1; i++) {\n VQ.set(i + r, VP.get(i));\n }\n let alpha = common_1.empty([q + 1, r + 1]);\n let R = common_1.empty([q + 1, this.dimension]);\n let L = 0;\n // Pre-calculate alphas\n for (let j = 1; j < r + 1; j++) {\n L = k - q + j;\n for (let i = 0; i < q - j - s + 1; i++) {\n alpha.set(i, j, (vn - VP.get(L + i)) / (VP.get(i + k + 1) - VP.get(L + i)));\n }\n }\n for (let col = 0; col < nU + 1; col++) {\n // Save unaltered control points\n for (let i = 0; i < k - q + 1; i++) {\n Q.set(col, i, P.get(col, i));\n }\n for (let i = k - s; i < nV + 1; i++) {\n Q.set(col, i + r, P.get(col, i));\n }\n // Load auxiliary control points\n for (let i = 0; i < q - s + 1; i++) {\n R.set(i, P.get(col, k - q + i));\n }\n for (let j = 1; j < r + 1; j++) {\n L = k - q + j;\n for (let i = 0; i < q - j - s + 1; i++) {\n R.set(i, common_1.add(common_1.mul(alpha.get(i, j), R.get(i + 1)), common_1.mul((1.0 - alpha.get(i, j)), R.get(i))));\n }\n Q.set(col, L, R.get(0));\n Q.set(col, k + r - j - s, R.get(q - j - s));\n }\n // Load remaining control points\n for (let i = L + 1; i < k - s; i++) {\n Q.set(col, i, R.get(i - L));\n }\n }\n this.cpoints = Q;\n this.v_knots = VQ;\n }", "function solveEquation(params, x, y) {\n\n\n console.log(\"Solving equation\");\n //gets x values from global\n\n decaycurve = function(x, P) {\n\n return x.map(\n function(xi) {\n return getPareto(xi, P[0], P[1])\n }\n\n )\n };\n\n\n //Parms=fminsearch(fun,[100,30,10,5000],x,y);\n // Returns an array of coeffcients\n Parms = fminsearch(decaycurve, [.1, .1], x, y, {\n maxIter: 10000,\n display: true\n });\n\n\n //Math.round(original*100)/100 \n\n ra1 = Parms[0];\n ra2 = Parms[1];\n //rb1 = Parms[2];\n a1 = Math.round(Parms[0] * 1000) / 1000;\n a2 = Math.round(Parms[1] * 1000) / 1000;\n //b1 = Math.round(Parms[2]*1000)/1000;\n\n /*\n for (i = 0; i < x.length; i++) {\n roascurve.push(getPareto(x[i], Parms[0], Parms[1]));\n\n }\n*/\n return Parms; // Returns Array of Co-Efficients\n\n\n}", "getMinMaxAccel(chassisVel, curvature, maxAbsVolts) {\n let minmax = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY];\n let wheelVel = this.solveInverseKinematics(chassisVel);\n\n // Math:\n // (Tl + Tr) / r_w = m*a\n // (Tr - Tl) / r_w * r_wb - drag*w = i*(a * k + v^2 * dk)\n // 2 equations, 2 unknowns.\n // Solve for a and (Tl|Tr)\n let linearTerm, angularTerm;\n if (Number.isFinite(curvature)) {\n linearTerm = this.mass * this.effWheelbaseRad;\n angularTerm = this.moi * curvature;\n }\n else {\n // turning in place\n linearTerm = 0;\n angularTerm = this.moi;\n }\n\n const dragTorque = chassisVel.angular * this.angularDrag;\n\n // Check all four cases and record the min and max valid accelerations.\n for (let left of [false, true]) {\n for (let sign of [1, -1]) {\n const fixedTrans = left ? this.leftTrans : this.rightTrans;\n const variableTrans = left ? this.rightTrans : this.leftTrans;\n const fixedTorque = fixedTrans.getTorqueForVolts(wheelVel.get(left),\n sign * maxAbsVolts);\n let variableTorque;\n // NOTE: variableTorque is wrong. Units don't work out correctly. \n // We made a math error somewhere... Leaving this \"as is\" for \n // code release so as not to be disingenuous, but this whole \n // function needs revisiting in the future...\n if (left) {\n variableTorque =\n ((/*-moi_ * chassis_velocity.linear * chassis_velocity.linear * dcurvature*/ -dragTorque) * this.mass * this.wheelRadius,\n + fixedTorque * (linearTerm + angularTerm))\n / (linearTerm - angularTerm);\n }\n else {\n variableTorque =\n ((/* moi_ * chassis_velocity.linear * chassis_velocity.linear * dcurvature */ +dragTorque) * this.mass * this.wheelRadius,\n + fixedTorque * (linearTerm - angularTerm))\n / (linearTerm + angularTerm);\n }\n const variableVolts = variableTrans.getVoltsForTorque(wheelVel.get(!left),\n variableTorque);\n if (Math.abs(variableVolts) <= (maxAbsVolts + kEpsilon)) {\n let accel = 0.0;\n if (!Number.isFinite(curvature)) {\n // turn in place\n accel = (left ? -1.0 : 1.0) *\n (fixedTorque - variableTorque) * this.effWheelbaseRad\n / (this.moi * this.wheelRadius) - dragTorque / this.moi /*- chassis_velocity.linear * chassis_velocity.linear * dcurvature*/;\n }\n else {\n accel = (fixedTorque + variableTorque) /\n (this.mass * this.wheelRadius);\n }\n minmax[0] = Math.min(minmax[0], accel);\n minmax[1] = Math.max(minmax[1], accel);\n }\n }\n }\n return minmax;\n }", "solve() {\n let edgeLength, edge;\n let dx, dy, fx, fy, springForce, distance;\n const edges = this.body.edges;\n const factor = 0.5;\n\n const edgeIndices = this.physicsBody.physicsEdgeIndices;\n const nodeIndices = this.physicsBody.physicsNodeIndices;\n const forces = this.physicsBody.forces;\n\n // initialize the spring force counters\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n forces[nodeId].springFx = 0;\n forces[nodeId].springFy = 0;\n }\n\n // forces caused by the edges, modelled as springs\n for (let i = 0; i < edgeIndices.length; i++) {\n edge = edges[edgeIndices[i]];\n if (edge.connected === true) {\n edgeLength =\n edge.options.length === undefined\n ? this.options.springLength\n : edge.options.length;\n\n dx = edge.from.x - edge.to.x;\n dy = edge.from.y - edge.to.y;\n distance = Math.sqrt(dx * dx + dy * dy);\n distance = distance === 0 ? 0.01 : distance;\n\n // the 1/distance is so the fx and fy can be calculated without sine or cosine.\n springForce =\n (this.options.springConstant * (edgeLength - distance)) / distance;\n\n fx = dx * springForce;\n fy = dy * springForce;\n\n if (edge.to.level != edge.from.level) {\n if (forces[edge.toId] !== undefined) {\n forces[edge.toId].springFx -= fx;\n forces[edge.toId].springFy -= fy;\n }\n if (forces[edge.fromId] !== undefined) {\n forces[edge.fromId].springFx += fx;\n forces[edge.fromId].springFy += fy;\n }\n } else {\n if (forces[edge.toId] !== undefined) {\n forces[edge.toId].x -= factor * fx;\n forces[edge.toId].y -= factor * fy;\n }\n if (forces[edge.fromId] !== undefined) {\n forces[edge.fromId].x += factor * fx;\n forces[edge.fromId].y += factor * fy;\n }\n }\n }\n }\n\n // normalize spring forces\n springForce = 1;\n let springFx, springFy;\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n springFx = Math.min(\n springForce,\n Math.max(-springForce, forces[nodeId].springFx)\n );\n springFy = Math.min(\n springForce,\n Math.max(-springForce, forces[nodeId].springFy)\n );\n\n forces[nodeId].x += springFx;\n forces[nodeId].y += springFy;\n }\n\n // retain energy balance\n let totalFx = 0;\n let totalFy = 0;\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n totalFx += forces[nodeId].x;\n totalFy += forces[nodeId].y;\n }\n const correctionFx = totalFx / nodeIndices.length;\n const correctionFy = totalFy / nodeIndices.length;\n\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n forces[nodeId].x -= correctionFx;\n forces[nodeId].y -= correctionFy;\n }\n }", "solveKeplers(t) {\n // 1) from r0Vec, v0Vec, determine r0 and a\n // these are used within other functions used below\n\n // 2) given t-t0 (usually t0 is assumed to be zero), solve the universal\n // time of flight equation for x using a Newton iteration scheme\n // const x = this.x(t);\n const x = this.xNewton(t);\n\n // 3) Evaluate f and g from quations (4.4-31) and (4.4-34); then compute\n // rVec and r from equation (4.4-18).\n const f = this.f(x);\n const g = this.g(x, t);\n const rVec = new THREE.Vector3();\n\n rVec.addScaledVector( this.r0Vec, f );\n rVec.addScaledVector( this.v0Vec, g );\n\n this.rVec.copy(rVec);\n\n // 4) Evaluate fPrime and gPrime from equations (4.4-35) and (4.4-36);\n // then compute vVec from equation (4.4-19).\n const r = this.rVec.length();\n const fPrime = this.fPrime(x, r);\n const gPrime = this.gPrime(x, r);\n const vVec = new THREE.Vector3();\n\n vVec.addScaledVector( this.r0Vec, fPrime );\n vVec.addScaledVector( this.v0Vec, gPrime );\n\n this.vVec.copy(vVec);\n }", "function Constraint(vtx1, vtx2)\n{\n this.vtx1 = vtx1;\n this.vtx2 = vtx2;\n this.length = VERTEX_MARGIN;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
whoss Utility to parse npm packages used in a project and generate an attribution file to include in your product.
function whoss(options) { taim_1.default('Total Processing', bluebird_1.default.all([ taim_1.default('Npm Licenses', npm_1.getNpmLicenses(options)), ])) .catch(function (err) { console.log(err); process.exit(1); }) .spread(function (npmOutput) { var o = {}; npmOutput = npmOutput || {}; lodash_1.default.concat(npmOutput).forEach(function (v) { o[v.name] = v; }); var userOverridesPath = path_1.default.join(options.outputDir, 'overrides.json'); if (fs_jetpack_1.default.exists(userOverridesPath)) { var userOverrides = fs_jetpack_1.default.read(userOverridesPath, 'json'); console.log('Using overrides:', userOverrides); // foreach override, loop through the properties and assign them to the base object. o = lodash_1.default.defaultsDeep(userOverrides, o); } return o; }) .catch(function (e) { console.error('ERROR processing overrides', e); process.exit(1); }) .then(function (licenseInfos) { var attributionSequence = lodash_1.default(licenseInfos) .filter(function (licenseInfo) { return licenseInfo && !licenseInfo.ignore && licenseInfo.name !== undefined; }) .sortBy(function (licenseInfo) { return licenseInfo.name.toLowerCase(); }) .map(function (licenseInfo) { return [ licenseInfo.name, licenseInfo.version + " <" + licenseInfo.url + ">", licenseInfo.licenseText || "license: " + licenseInfo.license + os_1.default.EOL + "authors: " + licenseInfo.authors ].join(os_1.default.EOL); }) .value(); var attribution = attributionSequence.join(constants_1.DEFAULT_SEPARATOR); var headerPath = path_1.default.join(options.outputDir, 'header.txt'); if (fs_jetpack_1.default.exists(headerPath)) { var template = fs_jetpack_1.default.read(headerPath); console.log('using template', template); attribution = template + os_1.default.EOL + os_1.default.EOL + attribution; } fs_jetpack_1.default.write(path_1.default.join(options.outputDir, 'licenseInfos.json'), JSON.stringify(licenseInfos)); return fs_jetpack_1.default.write(path_1.default.join(options.outputDir, 'attribution.txt'), attribution); }) .catch(function (e) { console.error('ERROR writing attribution file', e); process.exit(1); }) .then(function () { console.log('done'); process.exit(); }); }
[ "_installNPMPackages() {\n\n var done = this.async();\n\n // Spawn dev dependencies\n this.npmInstall(['install',\n 'handlebars-template-loader'\n ], [\n '--save-dev',\n '--no-shrinkwrap'\n ]);\n\n // Spawn dependencies\n this.npmInstall(\n [\n 'install',\n 'handlebars',\n '@types/handlebars',\n ], [\n '--save',\n '--no-shrinkwrap'\n ]);\n\n done();\n\n }", "async function warmNpmCache() {\n console.log(' Warm NPM cache for project template deps.');\n\n // cwd is the root dir where snapp-cli's package.json is located.\n const jsProj = fs.readFileSync('templates/project/package.json', 'utf8');\n const tsProj = fs.readFileSync('templates/project-ts/package.json', 'utf8');\n\n let jsProjDeps = {\n ...JSON.parse(jsProj).dependencies,\n ...JSON.parse(jsProj).devDependencies,\n };\n\n let tsProjDeps = {\n ...JSON.parse(tsProj).dependencies,\n ...JSON.parse(tsProj).devDependencies,\n };\n\n for (prop in tsProjDeps) {\n if (jsProjDeps[prop] && jsProjDeps[prop] === tsProjDeps[prop]) {\n delete tsProjDeps[prop];\n }\n }\n\n const allUniqueDeps = { ...jsProjDeps, ...tsProjDeps };\n\n let toCache = [];\n for (const pkgName in allUniqueDeps) {\n toCache.push(`${pkgName}@${allUniqueDeps[pkgName]}`);\n }\n\n try {\n await shExec(`npm cache add ${toCache.join(' ')}`);\n console.log(' Done.');\n } catch (err) {\n console.error(err);\n }\n}", "addPackages(...packages) {\n for (let pkg of packages) {\n if (pkg.startsWith('#')) {\n this.packages.push(pkg);\n }\n else {\n const { name, version } = deps_1.Dependencies.parseDependency(pkg);\n if (version) {\n this.packages.push(`${name}${semver_1.toPythonVersionRange(version)}`);\n }\n else {\n this.packages.push(name);\n }\n }\n }\n }", "function concatPackages (packages, outDir, minified) {\n if (! outDir) outDir = path.join('.', 'build');\n\n if (!fs.existsSync(outDir)) fs.mkdirSync(outDir);\n var jsFileName = path.join(outDir, 'build.js');\n if (fs.existsSync(jsFileName)){\n fs.truncateSync(jsFileName, 0);\n }\n var cssFileName = path.join(outDir, 'build.css');\n if (fs.existsSync(cssFileName)){\n fs.truncateSync(cssFileName, 0);\n }\n _.each(packages, function (pack, i, l) {\n concatPackage(pack, outDir, minified);\n });\n}", "async function generatePackageJson() {\n const original = require('../package.json')\n const result = {\n name: original.name,\n author: original.author,\n version: original.version,\n license: original.license,\n description: original.description,\n main: './index.js',\n dependencies: Object.entries(original.dependencies).filter(([name, version]) => original.external.indexOf(name) !== -1).reduce((object, entry) => ({ ...object, [entry[0]]: entry[1] }), {})\n }\n await writeFile('dist/package.json', JSON.stringify(result))\n}", "function updateModulesPackages() {\n return through2.obj(function(file, enc, cb) {\n if (file.isNull()) {\n cb(null, file);\n return;\n }\n\n if (file.isStream()) {\n cb(new gulputil.PluginError('convertPackageMain', 'Streaming not supported'));\n return;\n }\n\n const pkg = JSON.parse(file.contents.toString());\n\n // Update package.main to point at babel-renamed files\n if (pkg.main && path.extname(pkg.main) === '.jsx') {\n pkg.main = pkg.main.substr(0, pkg.main.length - 1);\n }\n\n // Update dependencies to load shrine modules locally\n pkg.dependencies = Object.keys(pkg.dependencies || {}).reduce(\n (dependencies, dependencyName) => {\n if (dependencyName.indexOf(`${MODULE_PREFIX}/`) === 0) {\n dependencies[dependencyName] = path.resolve(path.join(MODULES_BUILD_DIR, dependencyName));\n } else {\n dependencies[dependencyName] = pkg.dependencies[dependencyName];\n }\n\n return dependencies;\n },\n {}\n );\n\n file.contents = new Buffer(JSON.stringify(pkg, null, 2));\n this.push(file);\n\n cb();\n });\n}", "async function changePackages() {\n const packages = await getPackages()\n\n await Promise.all(\n packages.map(async ({ pkg, path: pkgPath }) => {\n // you can transform the package.json contents here\n\n if (\n pkg.files &&\n pkg.files.includes('lib') &&\n pkg.name !== 'babel-plugin-emotion'\n ) {\n pkg.files = pkg.files.map(file => (file === 'lib' ? 'dist' : file))\n }\n\n await writeFile(\n path.resolve(pkgPath, 'package.json'),\n JSON.stringify(pkg, null, 2) + '\\n'\n )\n })\n )\n}", "function packagesNpmInstall (source) {\n var packages = path.join(process.cwd(), source)\n npm.load({\n loglevel: 'error'\n }, function (err, npm) {\n if (!err) {\n fs.readdir(packages, function (err, files) {\n if (err && err.code !== 'ENOENT') throw Error(err)\n\n if (!files || !files.length) return\n console.log('Auto installing package dependencies')\n\n files.forEach(function (file) {\n var pkgPath = path.join(packages, file)\n\n loadPackageJson(path.join(pkgPath, 'package.json'), function (err, data) {\n if (err || !data.mean) return\n\n var installDeps = []\n\n if (data.dependencies) {\n for (var dep in data.dependencies) {\n installDeps.push(dep + '@' + data.dependencies[dep])\n }\n if (process.env === 'development' && data.devDependencies) {\n for (var devDep in data.devDependencies) {\n installDeps.push(devDep + '@' + data.devDependencies[devDep])\n }\n }\n }\n if (installDeps.length) {\n npm.commands.install(installDeps, function (err) {\n if (err) {\n console.log('Error: npm install failed')\n return console.error(err)\n } else {\n console.log(' Dependencies installed for package ' + file)\n }\n })\n }\n })\n })\n })\n }\n })\n}", "function getPackageInfoUrl(packageName) {\n const parts = packageName.split('/')\n if (parts.length !== 2) {\n throw new Error(`Invalid package name: \"${ packageName }\"`)\n }\n const vendor = parts[0]\n const name = parts[1]\n return `https://packagist.org/packages/${ vendor }/${ name }.json`\n}", "function getUserNpmInput() {\n\n console.log('');\n\n const npmrcPath = __dirname + '/../.npmrc';\n const yarnPath = __dirname + '/../.yarnrc';\n\n const npmRegExp = {\n name: /init[.-]author[.-]name =? ?[\"']?([^\"']*)[\"']?\\n/,\n email: /init[.-]author[.-]email =? ?[\"']?([^\"']*)[\"']?\\n/,\n url: /init[.-]author[.-]url =? ?[\"']?([^\"']*)[\"']?\\n/,\n license: /init[.-]license =? ?[\"']?([^\"']*)[\"']?\\n/,\n version: /init[.-]version =? ?[\"']?([^\"']*)[\"']?\\n/\n }\n\n let npmrc = '';\n\n if (fs.existsSync(npmrcPath)) {\n npmrc = fs.readFileSync(npmrcPath, 'utf8');\n } else if (fs.existsSync(yarnPath)) {\n npmrc = fs.readFileSync(yarnPath, 'utf8');\n }\n\n if (npmrc !== '') {\n\n let name = npmrc.match(npmRegExp.name) === null ? 'Author Name' :\n npmrc.match(npmRegExp.name)[1];\n let email = npmrc.match(npmRegExp.email) === null ? 'author.name@authordomain.com' :\n npmrc.match(npmRegExp.email)[1];\n let url = npmrc.match(npmRegExp.url) === null ? 'https://authordomain.com' :\n npmrc.match(npmRegExp.url)[1];\n let license = npmrc.match(npmRegExp.license) === null ? 'MIT' :\n npmrc.match(npmRegExp.license)[1];\n let version = npmrc.match(npmRegExp.version) === null ? '0.0.0' :\n npmrc.match(npmRegExp.version)[1];\n\n npmData = {\n name: name,\n email: email,\n url: url,\n license: license,\n version: version\n }\n } else {\n npmData = {\n name: 'Author Name',\n email: 'author.name@authordomain.com',\n url: 'https://authordomain.com',\n license: 'MIT',\n version: '0.0.0'\n }\n }\n\n let adjustedNpmPrompts = [];\n\n if (promptFlag) {\n for (let i = 0; i < config.npmConfigPrompts.length; i++) {\n if (npmData[config.npmConfigPrompts[i].name] !== undefined) {\n adjustedNpmPrompts.push(config.npmConfigPrompts[i]);\n adjustedNpmPrompts[i].default =\n npmData[adjustedNpmPrompts[i].name];\n }\n }\n }\n\n cli.prompt(adjustedNpmPrompts, function (answers) {\n\n Object.assign(npmData, answers);\n generate();\n\n });\n}", "function concatPackage (pack, outDir, minified) {\n if (_.contains(concatedPkgs, path.basename(pack))) return;\n\n var bowerFile = 'bower.json';\n\n if (! fs.existsSync(path.join(pack, bowerFile)))\n bowerFile = '.bower.json';\n\n var regularJSON = JSON.parse(\n fs.readFileSync(path.join(pack, bowerFile))\n );\n var bowerJSON = json.normalize(regularJSON);\n var deps = bowerJSON.dependencies || {};\n var mains = bowerJSON.main || [];\n\n concatedPkgs.push(path.basename(pack));\n\n _.each(Object.keys(deps), function (pkg, i, l) {\n var components = pack.split(path.sep);\n var pkgpath = components.slice(0, -1).join(path.sep);\n\n concatPackage(path.join(pkgpath, pkg), outDir, minified);\n });\n\n debug('concatenating package ' + path.basename(pack) + '...');\n\n var files = constructFileList(pack, mains, minified);\n var concatJS = '', concatCSS = '';\n\n _.each(files, function (filepath, i, l) {\n var contents = fs.readFileSync(filepath) + '\\n';\n var ext = filepath.split('.')[filepath.split('.').length - 1];\n\n if (ext === 'js' || ext === 'css')\n debug('including file ' + filepath + '...');\n\n if (ext === 'js')\n concatJS += contents;\n else if (ext === 'css')\n concatCSS += contents;\n });\n\n if (concatJS !== '' || concatCSS !== '')\n debug('writing files...');\n\n if (concatJS !== '')\n fs.appendFileSync(path.join(outDir, 'build.js'), concatJS);\n\n if (concatCSS !== '')\n fs.appendFileSync(path.join(outDir, 'build.css'), concatCSS);\n}", "function package_info() {\n try {\n var pkg = require('../../package.json');\n return pkg;\n }\n catch (err) {\n return {\n name: 'aws-crt-nodejs',\n version: 'UNKNOWN'\n };\n }\n}", "convertUrl(url) {\n if (PackageUrlHandler.isUrlInternalToPackage(url)) {\n // TODO(fks): Revisit this format? The analyzer returns URLs without this\n return ('./' + url);\n }\n const newUrl = url.replace('bower_components/', 'node_modules/');\n const newUrlPieces = newUrl.split('/');\n const bowerPackageName = newUrlPieces[1];\n if (bowerPackageName === this.bowerPackageName) {\n newUrlPieces[1] = this.npmPackageName;\n }\n else {\n const depInfo = package_manifest_1.lookupDependencyMapping(bowerPackageName);\n if (depInfo) {\n newUrlPieces[1] = depInfo.npm;\n }\n }\n return ('./' + newUrlPieces.join('/'));\n }", "function getPackageInfo(installPackage) {\n if (installPackage.match(/^.+\\.(tgz|tar\\.gz)$/)) {\n return getTemporaryDirectory()\n .then(obj => {\n let stream;\n if (/^http/.test(installPackage)) {\n stream = hyperquest(installPackage);\n } else {\n stream = fs.createReadStream(installPackage);\n }\n return extractStream(stream, obj.tmpdir).then(() => obj);\n })\n .then(obj => {\n const { name, version } = require(path.join(obj.tmpdir, 'package.json'));\n obj.cleanup();\n return { name, version };\n })\n .catch(err => {\n // The package name could be with or without semver version, e.g. init-nose-server-0.2.0-alpha.1.tgz\n // However, this function returns package name only without semver version.\n log(`Could not extract the package name from the archive: ${err.message}`);\n const assumedProjectName = installPackage.match(/^.+\\/(.+?)(?:-\\d+.+)?\\.(tgz|tar\\.gz)$/)[1];\n log(`Based on the filename, assuming it is \"${chalk.cyan(assumedProjectName)}\"`);\n return Promise.resolve({ name: assumedProjectName });\n });\n } else if (installPackage.startsWith('git+')) {\n // Pull package name out of git urls e.g:\n // git+https://github.com/MohamedJakkariya/ins-template.git\n // git+ssh://github.com/mycompany/ins-template.git#v1.2.3\n return Promise.resolve({\n name: installPackage.match(/([^/]+)\\.git(#.*)?$/)[1]\n });\n } else if (installPackage.match(/.+@/)) {\n // Do not match @scope/ when stripping off @version or @tag\n return Promise.resolve({\n name: installPackage.charAt(0) + installPackage.substr(1).split('@')[0],\n version: installPackage.split('@')[1]\n });\n } else if (installPackage.match(/^file:/)) {\n const installPackagePath = installPackage.match(/^file:(.*)?$/)[1];\n const { name, version } = require(path.join(installPackagePath, 'package.json'));\n return Promise.resolve({ name, version });\n }\n return Promise.resolve({ name: installPackage });\n}", "async function update_package_jsons() {\n const pkg = JSON.parse(fs.readFileSync(\"./package.json\"));\n pkg.version = NEW_VERSION;\n const pkg_json = `${JSON.stringify(pkg, undefined, 4)}\\n`;\n fs.writeFileSync(\"../package.json\", pkg_json);\n const packages = {};\n for (const ws of pkg.workspaces) {\n for (const path of glob(`${ws}/package.json`, {\n sync: true,\n })) {\n const pkg = JSON.parse(fs.readFileSync(path));\n pkg.version = NEW_VERSION;\n packages[pkg.name] = {\n pkg,\n path,\n };\n }\n }\n for (const pkg_name of Object.keys(packages)) {\n const { pkg, path } = packages[pkg_name];\n for (const deptype of [\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n ]) {\n if (pkg[deptype]) {\n for (const dep of Object.keys(pkg[deptype])) {\n if (packages[dep] !== undefined) {\n pkg[deptype][dep] = `^${NEW_VERSION}`;\n }\n }\n }\n }\n const pkg_json = `${JSON.stringify(pkg, undefined, 4)}\\n`;\n fs.writeFileSync(path, pkg_json);\n sh`git add ${path}`.runSync();\n }\n}", "function bower() {\n console.log(chalk.green(\"Starting to collect Bower packages...\"));\n bowerCollector.fetchFromBower();\n process.exit(0);\n}", "async function packageScripts() {\n await runCommand(\n \"mkdir dist/lib/scripts\",\n \"creating the dist/lib/scripts directory if it doesn't exist\"\n );\n await runCommand(\n \"cp lib/scripts/* dist/lib/scripts/.\",\n \"copy the contents of scripts to dist/sripts\"\n );\n}", "function getNpmPackagesFromRunfiles() {\n // Path to the Bazel runfiles manifest if present. This file is present if runfiles are\n // not symlinked into the runfiles directory.\n const runfilesManifestPath = process.env.RUNFILES_MANIFEST_FILE;\n const workspacePath = 'angular_material/src';\n if (!runfilesManifestPath) {\n const packageRunfilesDir = join(process.env.RUNFILES, workspacePath);\n return readdirSync(packageRunfilesDir)\n .map(name => ({name, pkgPath: join(packageRunfilesDir, name, 'npm_package/')}))\n .filter(({pkgPath}) => existsSync(pkgPath));\n }\n const workspaceManifestPathRegex = new RegExp(`^${workspacePath}/[\\\\w-]+/npm_package$`);\n return readFileSync(runfilesManifestPath, 'utf8')\n .split('\\n')\n .map(mapping => mapping.split(' '))\n .filter(([runfilePath]) => runfilePath.match(workspaceManifestPathRegex))\n .map(([runfilePath, realPath]) => ({\n name: relative(workspacePath, runfilePath).split(sep)[0],\n pkgPath: realPath,\n }));\n}", "function parseManifest(bom, manifest) {\n let buildroot = JSON.parse(fs.readFileSync(manifest, 'utf8'));\n for (let key in buildroot) {\n let lib = buildroot[key];\n if (lib.virtual === true) {\n continue; // Do not include virtual packages\n }\n // Create a new CycloneDX component and populate identity information\n let component = new Component();\n component.type = \"library\"; // Must be a valid CycloneDX component type\n component.name = key;\n component.version = (lib.version) ? lib.version : \"unknown\"; // Version is required. Not all packages have one.\n\n // Set the component PackageURL, CPE, and SWID\n // See: https://cyclonedx.org/use-cases/#known-vulnerabilities\n component.purl = new PackageURL(\"hex\", null, component.name, component.version, null, null).toString();\n component.cpe = \"cpe:2.3:o:linux:linux_kernel:2.6.30.1:*:*:*:*:*:*:*\"; // TODO: Possible to determine?\n component.swid = new Swid(\"tagId-goes-here\", component.name, component.version); // TODO: Possible to determine?\n\n // TODO: Possible future work - Download packages and calculate hash values of each package. Add them to BOM.\n // See: https://cyclonedx.org/use-cases/#integrity-verification\n\n // Process licenses and add the unresolved license name to CycloneDX\n // See: https://cyclonedx.org/use-cases/#license-compliance\n if (lib.licenses) {\n let license = new License();\n license.name = lib.licenses;\n let licenseChoice = new LicenseChoice();\n licenseChoice.licenses = [license];\n component.licenses = licenseChoice;\n }\n\n // Process downloads and create CycloneDX external references\n let externalReferenceList = new ExternalReferenceList();\n if (lib.downloads) {\n for (let index in lib.downloads) {\n let download = lib.downloads[index];\n if (download.uris) {\n let reference = new ExternalReference(\"distribution\", download.uris[0]\n .replace(\"ftp+ftp\", \"ftp\").replace(\"http+http\", \"http\").replace(\"https+https\", \"https\"));\n externalReferenceList.externalReferences.push(reference);\n }\n }\n }\n component.externalReferences = externalReferenceList;\n\n // Add the component to the BOM.\n bom.addComponent(component);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the number of exhausted votes
updateExhaustedVotes() { const votesSum = this.count[this.round].reduce((a, b) => a + b); const exhausted = (this.p * this.numBallots) - votesSum; this.exhausted[this.round] = exhausted; }
[ "function election(votes) {\n for(var student in votes) { \n var votesCast = votes[student];\n \n var counter = 1;\n for(var officer in votesCast) { //targeting the officer position and voted name\n var officerName = votesCast[officer];\n if (voteCount[officer][officerName]) {\n voteCount[officer][officerName] += 1\n }\n else {\n voteCount[officer][officerName] = 1\n }\n }\n }\n}", "function getNumVotersPerElection() {\n return numVotersPerElection;\n } // getNumVoters", "function increaseFinalVote(value)\n {\n setGame(\"final\");\n setVotes(true);\n }", "function presidentVote(){\n for (var voterName in votes) {\n var candidate = votes[voterName][\"president\"]\n if (voteCount[\"president\"].hasOwnProperty(candidate)) {\n voteCount[\"president\"][candidate] += 1\n } else {\n voteCount[\"president\"][candidate] = 1\n }}\n}", "function tallyVote(lobby) {\n getGame(lobby).votes++;\n}", "function vote() {\n for (party in total_votes_per_party) {\n if (total_votes_per_party[party] > 0) {\n // Calculate the increment for this party\n var increment = Math.round(multiplier * Math.random());\n // Vote and then remove those votes from the counters\n var votes_left = total_votes_per_party[party];\n var votes_to_cast = (votes_left > increment) ? increment : votes_left;\n var inc = {};\n inc['votes.' + party] = votes_to_cast;\n db.votetotals.update({\n constituency: \"uk\"\n }, {\n $inc: inc\n }, {\n upsert: true\n }, {});\n total_votes_per_party[party] = votes_left - votes_to_cast;\n }\n }\n}", "function countVotes(votos, nvotos, n, mu, lambda, npartidos) {\n /*\n http://security.hsr.ch/msevote/seminar-papers/HS09_Homomorphic_Tallying_with_Paillier.pdf\n */\n\n\n var producto = 1;\n var n2 = bignum(n).pow(2);\n\n console.log(votos[0]);\n console.log(n);\n console.log(mu);\n console.log(lambda);\n console.log(bignum(mu).invertm(n));\n\n\n for (var i = 0; i < nvotos; i++) {\n console.log(\"Votante \" + i + \" \" + votos[i]);\n producto = bignum(producto).mul(bignum(votos[i]));\n }\n\n console.log(producto);\n\n var tally = bignum(producto).mod(n2);\n\n console.log(\"N: \" + n);\n console.log(\"N^2: \" + n2);\n\n var resultado_f1 = bignum(tally).powm(lambda, n2);\n var resultado_f2 = (bignum(resultado_f1).sub(1)).div(n);\n var resultados = bignum(resultado_f2).mul(mu).mod(n);\n\n console.log(\"RESULTADOS: \" + resultados);\n\n var resultado = {};\n\n for (var i = 1; i <= npartidos; i++) {\n\n resultado[i + 'partido'] = Math.floor((resultados / Math.pow(10, i - 1)) % 10);\n }\n\n /*var resultado = {\n '1partido' : Math.floor((resultados / 1) % 10),\n '2partido' : Math.floor((resultados / 10) % 10),\n '3partido' : Math.floor((resultados / 100) % 10),\n '4partido' : Math.floor((resultados / 1000) % 10)\n };*/\n\n return resultado;\n\n }", "moreQuestionsAvailable() {\n\treturn (this.progress.qAnswered < this.progress.qTotal);\n }", "function voterResults (arr){\n let result = arr.reduce(function(final,voterAge){\n if (voterAge.age >= 18 && voterAge.age <= 25){\n final.youth++\n if (voterAge.voted){\n final.youngVotes++\n }\n }else if (voterAge.age >= 26 && voterAge.age <= 35){\n final.mids++\n if (voterAge.voted){\n final.midVotes++\n }\n }else if (voterAge.age >= 36 && voterAge.age <= 55){\n final.olds++\n if (voterAge.voted){\n final.oldVotes++\n }\n }\n return final\n },{youngVotes:0, youth:0, midVotes:0, mids:0, oldVotes:0, olds:0})\n \n return result\n}", "function getNumCandidates() {\n return numCandidates;\n } // getNumCandidates", "async getNumberOfCoinsPicked() {\n return Math.random() < 0.5 ? 1 : 2;\n }", "count() {\n const values = utils.removeMissingValuesFromArray(this.values);\n return values.length;\n }", "function getNumberOfToppingsSelected() {\n var selections = document.getElementsByClassName(\"form-check-input\")\n var count = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i].type === \"checkbox\" && selections[i].checked === true) {\n count++;\n }\n }\n return count;\n}", "_countPlayedUsers() {\n let played = 0\n let remaining = 0\n for (let i = 0; i < this.users.length; i++) {\n if (this.users[i].checked) played++\n if (this.users[i].left !== true) remaining++\n }\n\n return { played, remaining }\n }", "async incrementDownvote(reviewId, authenticateduser) {\n const downvoteAdded = await addDownvoter(reviewId, authenticateduser)\n if (downvoteAdded !== null) {\n let upvotes = await getUpvoters(this.props.reviewId)\n let downvotes = await getDownvoters(this.props.reviewId)\n upvotes = upvotes.data.length\n downvotes = downvotes.data.length\n this.setState({upvotes: upvotes})\n this.setState({downvotes: downvotes})\n }\n }", "function countMatches() {\n\tnumberOfMatches += 1;\n\treturn numberOfMatches;\n}", "function Acount (sQid)\r\n {\r\n // local variables\r\n var bVyy; // current answer object already has version qualifying as correct\r\n var bVnn; // current answer object already has version qualifying as wrong\r\n \r\n // default result\r\n gnAyy=0;\r\n gnAnn=0;\r\n \r\n // Loop through answer objects\r\n for (i=0; i<gaoA.length; i++)\r\n {\r\n\t // Process question only if inclusion probability not 0\r\n\t if (gaoA[i].p>0)\r\n\t {\r\n\t // Loop through versions. If at least one version qualifying as correct or incorret\r\n\t\t // is found, the corresponding counters are incremented. \r\n\t\t bVyy=false;\r\n\t\t bVnn=false;\r\n\t\t for (j=0; j<gaoA[i].tx.length; j++)\r\n\t {\r\n\t\t\t// Look for versions qualifying as correct only until the first one has been found\r\n\t\t\tif(gaoA[i].qy[j].indexOf(sQid)>-1 && bVyy==false)\r\n\t\t\t {\r\n\t\t\t gnAyy+=1;\r\n\t\t\t bVyy=true;\r\n\t\t\t if (bVnn==true) break; // done with this object if a version qualifying as wrong has also been found\r\n\t\t\t }\r\n\t\t\t// Look for versions qualifying as wrong only until the first one has been found\r\n\t else if(gaoA[i].qn[j].indexOf(sQid)>-1 && bVnn==false)\r\n\t\t\t {\r\n\t gnAnn+=1;\r\n\t\t\t bVnn=true;\r\n\t\t\t if (bVyy=true) break; // done with this object if a version qualifying as correct has also been found\r\n\t\t\t }\r\n\t\t }\r\n\t\t }\r\n\t }\r\n }", "function pointsSixes(player) {\n\n var diceCount = countDices(player);\n return diceCount[5] * 6;\n}", "function numOfTotalEnemies() {\n\tconst totalEnemies = gameState.enemies.getChildren().length;\n return totalEnemies;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
THREEcap EffectComposer pass for capturing and encoding a Three.js app's render output Supports jpg, png, gif, and mp4 output Video encoding capabilities provided by FFmpeg, crosscompiled to JavaScript using Emscripten
function THREEcap(args) { this.settings = { width: 320, height: 240, fps: 25, time: 5, srcformat: 'raw', format: 'mp4', quality: 'ultrafast', useWorker: true, inWorker: false, scriptbase: '', canvas: false, composer: false, renderpass: false }; // Update settings with passed-in values this.settings = this.getSettings(args); if (this.settings.composer) { this.attachComposer(this.settings.composer); } }
[ "setupEffectComposer() {\n if (this.nature.WebGLRendererParameters) {\n if (this.nature.WebGLRendererParameters.effectComposer) {\n if (this.SceneDispatcher.currentVLabScene) {\n /**\n * Postprocessing EffectComposer\n * @see https://www.npmjs.com/package/postprocessing\n * @inner\n * @public\n */\n if (this.effectComposer == undefined) {\n this.effectComposer = new EffectComposer(this.WebGLRenderer);\n }\n\n this.effectComposer.reset();\n\n if (this.effectComposer.renderer !== this.WebGLRenderer) {\n this.effectComposer.replaceRenderer(this.WebGLRenderer);\n }\n\n if (this.outlineEffect !== undefined) {\n this.outlineEffect.dispose();\n }\n this.outlineEffect = new OutlineEffect(this.SceneDispatcher.currentVLabScene, this.SceneDispatcher.currentVLabScene.currentCamera, {\n edgeStrength: 2.0,\n visibleEdgeColor: 0xffff00,\n hiddenEdgeColor: 0xffff00,\n });\n\n\n if (this.renderPass != undefined) {\n this.renderPass.dispose();\n }\n this.renderPass = new RenderPass(this.SceneDispatcher.currentVLabScene, this.SceneDispatcher.currentVLabScene.currentCamera);\n this.renderPass.renderToScreen = true;\n this.effectComposer.addPass(this.renderPass);\n\n if (this.outlinePass != undefined) {\n this.outlinePass.dispose();\n THREEUtils.completeDispose(this.outlinePass.scene);\n }\n this.outlinePass = new EffectPass(this.SceneDispatcher.currentVLabScene.currentCamera, this.outlineEffect);\n this.outlinePass.renderToScreen = false;\n }\n }\n }\n }", "function generalSetup() {\n // Scene\n scene = new THREE.Scene();\n // Camera setup\n camera = new THREE.PerspectiveCamera(75, canvasSize.width / canvasSize.height, 0.1, 1000);\n camera.position.set(1, 0, 0);\n // Renderer setup\n renderer = new THREE.WebGLRenderer({antialias: true});\n renderer.setSize(canvasSize.width, canvasSize.height);\n cv.appendChild(renderer.domElement);\n // Post processing setup\n composer = new POSTPROCESSING.EffectComposer(renderer);\n composer.addPass(new POSTPROCESSING.RenderPass(scene, camera));\n const effectPass = new POSTPROCESSING.EffectPass(camera, new POSTPROCESSING.BloomEffect());\n effectPass.renderToScreen = true;\n composer.addPass(effectPass);\n}", "function ThreeJsState() {\n // create the renderer\n this.renderer = new THREE.WebGLRenderer({\n antialias : true, // to get smoother output\n preserveDrawingBuffer : true // to allow screenshot\n });\n this.renderer.setClearColor( 0x000000, 1 );\n this.renderer.setSize( innerWidth, innerHeight );\n\n this.composer = new THREE.EffectComposer(this.renderer);\n\n // put a camera in the scene\n\n this.camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, .01, 100000 );\n this.camera.position.set(-4, 2, 4);\n\n // transparently support window resize\n window.addEventListener('resize', function(){\n this.renderer.setSize( window.innerWidth, window.innerHeight );\n this.camera.aspect = window.innerWidth / window.innerHeight;\n this.camera.updateProjectionMatrix();\n }.bind(this), false);\n\n // create a camera contol\n this.controls = new THREE.OrbitControls( this.camera, this.renderer.domElement );\n this.controls.noPan = false;\n\n // create a scene\n this.scene = new THREE.Scene();\n this.scene.add(this.camera);\n\n this.renderpass = new THREE.RenderPass(this.scene, this.camera);\n this.composer.passes.push(this.renderpass);\n\n this.shaderpass_default = new THREE.ShaderPass({\n uniforms: {\n \"input_texture\": { type: \"t\", value: null },\n },\n vertexShader: vertexShaders.passthrough,\n fragmentShader: fragmentShaders.passthrough,\n }, 'input_texture');\n this.shaderpass_default.renderToScreen = true;\n this.composer.passes.push(this.shaderpass_default);\n}", "function init_threeScene(spec) {\n // grab a reference to our canvas\n CANVAS = document.getElementById('jeeFaceFilterCanvas')\n\n // INIT THE THREE.JS context\n THREERENDERER = new THREE.WebGLRenderer({\n context: spec.GL,\n canvas: spec.canvasElement\n });\n\n // COMPOSITE OBJECT WHICH WILL FOLLOW THE HEAD\n // in fact we create 2 objects to be able to shift the pivot point\n THREEFACEOBJ3D = new THREE.Object3D();\n THREEFACEOBJ3D.frustumCulled = false;\n THREEFACEOBJ3DPIVOTED = new THREE.Object3D();\n THREEFACEOBJ3DPIVOTED.frustumCulled = false;\n THREEFACEOBJ3DPIVOTED.position.set(0, -SETTINGS.pivotOffsetYZ[0], -SETTINGS.pivotOffsetYZ[1]);\n THREEFACEOBJ3DPIVOTED.scale.set(SETTINGS.scale, SETTINGS.scale, SETTINGS.scale);\n THREEFACEOBJ3D.add(THREEFACEOBJ3DPIVOTED);\n\n let frameMesh;\n let lensesMesh;\n let branchesMesh;\n let decoMesh;\n\n const loadingManager = new THREE.LoadingManager();\n\n // CREATE OUR FRAME\n const loaderFrame = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderFrame.load(\n './models/glasses/frame.json',\n (geometry) => {\n const mat = new THREE.MeshPhongMaterial({\n color: 0x000000,\n shininess: 2,\n specular: 0xffffff,\n transparent: true\n });\n\n frameMesh = new THREE.Mesh(geometry, mat);\n frameMesh.scale.multiplyScalar(0.0067);\n frameMesh.frustumCulled = false;\n frameMesh.renderOrder = 10000;\n }\n )\n\n // CREATE OUR LENSES\n const loaderLenses = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderLenses.load(\n './models/glasses/lenses.json',\n (geometry) => {\n const mat = new THREE.MeshBasicMaterial({\n map: new THREE.TextureLoader().load('./models/glasses/texture_mp.jpg')\n });\n\n lensesMesh = new THREE.Mesh(geometry, mat);\n lensesMesh.scale.multiplyScalar(0.0067);\n lensesMesh.frustumCulled = false;\n lensesMesh.renderOrder = 10000;\n }\n )\n // CREATE OUR BRANCHES\n const loaderBranches = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderBranches.load(\n './models/glasses/branches.json',\n (geometry) => {\n const mat = new THREE.MeshBasicMaterial({\n alphaMap: new THREE.TextureLoader().load('./models/glasses/alpha_branches.jpg'),\n map: new THREE.TextureLoader().load('./models/glasses/textureBlack.jpg'),\n transparent: true\n });\n\n branchesMesh = new THREE.Mesh(geometry, mat);\n branchesMesh.scale.multiplyScalar(0.0067);\n branchesMesh.frustumCulled = false;\n branchesMesh.renderOrder = 10000;\n }\n )\n\n // CREATE OUR DECO\n const loaderDeco = new THREE.BufferGeometryLoader(loadingManager);\n\n loaderDeco.load(\n './models/glasses/deco.json',\n (geometry) => {\n const mat = new THREE.MeshBasicMaterial({\n color: 0xffffff\n });\n\n decoMesh = new THREE.Mesh(geometry, mat);\n decoMesh.scale.multiplyScalar(0.0067);\n \n decoMesh.frustumCulled = false;\n decoMesh.renderOrder = 10000;\n }\n )\n\n loadingManager.onLoad = () => {\n GLASSESOBJ3D.add(branchesMesh);\n GLASSESOBJ3D.add(frameMesh);\n GLASSESOBJ3D.add(lensesMesh);\n \n GLASSESOBJ3D.add(decoMesh);\n GLASSESOBJ3D.position.setY(0.05);\n\n addDragEventListener(GLASSESOBJ3D);\n\n THREEFACEOBJ3DPIVOTED.add(GLASSESOBJ3D);\n }\n\n // ADD OUR BEES\n const beeLoader = new THREE.JSONLoader();\n\n beeLoader.load(\n './models/bee/bee.json',\n (geometry) => {\n\n const materialBee = new THREE.MeshLambertMaterial({\n map: new THREE.TextureLoader().load('./models/bee/texture_bee.jpg'),\n transparent: true,\n morphTargets: true\n });\n\n BEEMESH = new THREE.Mesh(geometry, materialBee);\n\n // let butterFlyInstance\n // let action;\n let clips;\n let clip;\n let xRand;\n let yRand;\n let zRand;\n\n BEEOBJ3D = new THREE.Object3D();\n\n for (let i = 1; i < NUMBERBEES; i++) {\n const sign = i % 2 === 0 ? 1 : -1;\n const beeInstance = BEEMESH.clone();\n\n\n\n xRand = Math.random() * 1.5 - 0.75;\n yRand = Math.random() * 2 - 1 + 1;\n zRand = Math.random() * 0.5 - 0.25;\n\n beeInstance.position.set(xRand, yRand, zRand);\n beeInstance.scale.multiplyScalar(0.1);\n animateFlyBees(beeInstance, sign * ((i + 1) * 0.005 + 0.01), sign);\n let BEEINSTANCEOBJ3D = new THREE.Object3D();\n BEEINSTANCEOBJ3D.add(beeInstance);\n\n // CREATE BATTEMENT D'AILE ANIMATION\n if (!ISANIMATED) {\n // This is where adding our animation begins\n const mixer = new THREE.AnimationMixer(beeInstance);\n\n clips = beeInstance.geometry.animations;\n\n clip = clips[0];\n\n\n const action = mixer.clipAction(clip);\n\n\n ACTIONS.push(action);\n MIXERS.push(mixer);\n }\n\n BEEOBJ3D.add(BEEINSTANCEOBJ3D);\n }\n\n // We play the animation for each butterfly and shift their cycles\n // by adding a small timeout\n ACTIONS.forEach((a, index) => {\n setTimeout(() => {\n a.play();\n }, index*33);\n });\n\n \n THREEFACEOBJ3DPIVOTED.add(BEEOBJ3D);\n }\n )\n\n // CREATE THE SCENE\n THREESCENE = new THREE.Scene();\n THREESCENE.add(THREEFACEOBJ3D);\n\n // init video texture with red\n THREEVIDEOTEXTURE = new THREE.DataTexture(new Uint8Array([255,0,0]), 1, 1, THREE.RGBFormat);\n THREEVIDEOTEXTURE.needsUpdate = true;\n\n // CREATE THE VIDEO BACKGROUND\n function create_mat2d(threeTexture, isTransparent){ //MT216 : we put the creation of the video material in a func because we will also use it for the frame\n return new THREE.RawShaderMaterial({\n depthWrite: false,\n depthTest: false,\n transparent: isTransparent,\n vertexShader: \"attribute vec2 position;\\n\\\n varying vec2 vUV;\\n\\\n void main(void){\\n\\\n gl_Position=vec4(position, 0., 1.);\\n\\\n vUV=0.5+0.5*position;\\n\\\n }\",\n fragmentShader: \"precision lowp float;\\n\\\n uniform sampler2D samplerVideo;\\n\\\n varying vec2 vUV;\\n\\\n void main(void){\\n\\\n gl_FragColor=texture2D(samplerVideo, vUV);\\n\\\n }\",\n uniforms:{\n samplerVideo: { value: threeTexture }\n }\n });\n }\n const videoMaterial =create_mat2d(THREEVIDEOTEXTURE, false);\n const videoGeometry = new THREE.BufferGeometry()\n const videoScreenCorners = new Float32Array([-1,-1, 1,-1, 1,1, -1,1]);\n videoGeometry.addAttribute('position', new THREE.BufferAttribute( videoScreenCorners, 2));\n videoGeometry.setIndex(new THREE.BufferAttribute(new Uint16Array([0,1,2, 0,2,3]), 1));\n const videoMesh = new THREE.Mesh(videoGeometry, videoMaterial);\n videoMesh.onAfterRender = function () {\n // replace THREEVIDEOTEXTURE.__webglTexture by the real video texture\n THREERENDERER.properties.update(THREEVIDEOTEXTURE, '__webglTexture', spec.videoTexture);\n THREEVIDEOTEXTURE.magFilter = THREE.LinearFilter;\n THREEVIDEOTEXTURE.minFilter = THREE.LinearFilter;\n delete(videoMesh.onAfterRender);\n };\n videoMesh.renderOrder = -1000; // render first\n videoMesh.frustumCulled = false;\n THREESCENE.add(videoMesh);\n\n //MT216 : create the frame. We reuse the geometry of the video\n const calqueMesh = new THREE.Mesh(videoGeometry, create_mat2d(new THREE.TextureLoader().load('./images/frame.png'), true))\n calqueMesh.renderOrder = 999; // render last\n calqueMesh.frustumCulled = false;\n THREESCENE.add(calqueMesh);\n\n // CREATE THE CAMERA\n const aspecRatio = spec.canvasElement.width / spec.canvasElement.height;\n THREECAMERA = new THREE.PerspectiveCamera(SETTINGS.cameraFOV, aspecRatio, 0.1, 100);\n\n // CREATE A LIGHT\n const ambient = new THREE.AmbientLight(0xffffff, 1);\n THREESCENE.add(ambient)\n\n var dirLight = new THREE.DirectionalLight(0xffffff);\n dirLight.position.set(100, 1000, 100);\n\n THREESCENE.add(dirLight)\n} // end init_threeScene()", "function PostProcessRenderEffect(engine,name,getPostProcesses,singleInstance){this._name=name;this._singleInstance=singleInstance||true;this._getPostProcesses=getPostProcesses;this._cameras={};this._indicesForCamera={};this._postProcesses={};}", "startEncode() {\n\n var option = indexedApp.getCurrentSelectedExportSizeOption();\n\n var cmdArgs = [];\n cmdArgs.push(\"-y\");\n cmdArgs.push(\"-i\");\n cmdArgs.push(this.file.path);\n if (option.ffmpegArg) {\n cmdArgs.push(\"-s\");\n cmdArgs.push(option.ffmpegArg);\n }\n cmdArgs.push(`${indexedApp.getCurrentPathForSaving()}/${this._fileNameWithoutExtension}.mp4`);\n\n var process = child_process.execFile(Config.ffmpegFile, cmdArgs);\n process.stderr.on(\"data\", data=> {\n\n // console.log(data);\n\n this.checkToGetVideoLength(data);\n let result = this._regExpCurrentTime.exec(data);\n if (result) {\n var currentTime = this.getMsByRegExpResult(result);\n if (currentTime) {\n if (this._videoLength) {\n this._progressBarText.html(`${Math.round(currentTime / this._videoLength * 100)}%`);\n this._progressBar.progressbar({value: currentTime, max: this._videoLength});\n } else {\n this._progressBarText.html(`${result[1]}:${result[2]}:${result[3]}`);\n }\n }\n }\n });\n process.on('close', (code) => {\n console.log(`child process exited with code ${code}`);\n if (!code) {\n this._progressBarText.html(\"完成\");\n }\n });\n }", "function EffectLayer(/** The Friendly of the effect in the scene */name,scene){this._vertexBuffers={};this._maxSize=0;this._mainTextureDesiredSize={width:0,height:0};this._shouldRender=true;this._postProcesses=[];this._textures=[];this._emissiveTextureAndColor={texture:null,color:new BABYLON.Color4()};/**\n * The clear color of the texture used to generate the glow map.\n */this.neutralColor=new BABYLON.Color4();/**\n * Specifies wether the highlight layer is enabled or not.\n */this.isEnabled=true;/**\n * An event triggered when the effect layer has been disposed.\n */this.onDisposeObservable=new BABYLON.Observable();/**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */this.onBeforeRenderMainTextureObservable=new BABYLON.Observable();/**\n * An event triggered when the generated texture is being merged in the scene.\n */this.onBeforeComposeObservable=new BABYLON.Observable();/**\n * An event triggered when the generated texture has been merged in the scene.\n */this.onAfterComposeObservable=new BABYLON.Observable();/**\n * An event triggered when the efffect layer changes its size.\n */this.onSizeChangedObservable=new BABYLON.Observable();this.name=name;this._scene=scene||BABYLON.Engine.LastCreatedScene;var component=this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);if(!component){component=new BABYLON.EffectLayerSceneComponent(this._scene);this._scene._addComponent(component);}this._engine=this._scene.getEngine();this._maxSize=this._engine.getCaps().maxTextureSize;this._scene.effectLayers.push(this);// Generate Buffers\nthis._generateIndexBuffer();this._genrateVertexBuffer();}", "upload3DTexture () {\n\n }", "function y4mcal(i,length,breadth,outputVideoFile,y4mOutput,psnrBitrateCounter) {\n var y4mConversion = ffmpeg(outputVideoFile)\n .addOption('-pix_fmt')\n .addOption('yuv420p')\n .addOptions('-vsync', '0', '-s', resolution) //need to change the resolution everytime;cant hardcode\n .outputOption('-sws_flags lanczos')\n .on('start', function (commandLine) {\n console.log('Spawned Ffmpeg with command: ' + commandLine);\n })\n .on('progress', function (progress) {\n console.log(JSON.stringify(progress));\n })\n .on('data', function (data) {\n var frame = new Buffer(data).toString('base64');\n console.log(frame);\n })\n .on('error', function (err) {\n console.log('An error occurred: ' + err.message);\n })\n .on('end', function (err, stdout, stderr) {\n console.log('Processing CRF encoding finished !');\n console.log(JSON.stringify(stdout, null, \" \"));\n rawTomp4(i,length,breadth,y4mOutput,outputVideoFile,psnrBitrateCounter);\n })\n\n .save(y4mOutput);\n}", "function createAMO(name, vb, nb, ub, ib, jb, wb, animation) {\n // Header\n let AMO = \"#Generated by editamo\\n\";\n AMO += `ao ${name}\\n\\n`;\n\n // Vertexbuffer aka v\n for(let i = 0; i < vb.count; i++) {\n AMO += `v ${vb.data[i*3]} ${vb.data[i*3+1]} ${vb.data[i*3+2]}\\n`;\n }\n AMO += \"\\n\";\n\n // Normalbuffer aka vn\n for(let i = 0; i < nb.count; i++) {\n AMO += `vn ${nb.data[i*3]} ${nb.data[i*3+1]} ${nb.data[i*3+2]}\\n`;\n }\n AMO += \"\\n\";\n\n // UVbuffer aka vt\n for(let i = 0; i < ub.count; i++) {\n AMO += `vt ${ub.data[i*2]} ${ub.data[i*2+1]}\\n`;\n }\n AMO += \"\\n\";\n\n // Jointbuffer aka vj\n for(let i = 0; i < jb.count; i++) {\n AMO += `vj ${jb.data[i*4]+1} ${jb.data[i*4+1]+1} ${jb.data[i*4+2]+1} ${jb.data[i*4+3]+1}\\n`;\n }\n AMO += \"\\n\";\n\n // Weightbuffer aka vw\n for(let i = 0; i < wb.count; i++) {\n AMO += `vw ${wb.data[i*4]} ${wb.data[i*4+1]} ${wb.data[i*4+2]} ${wb.data[i*4+3]}\\n`;\n }\n AMO += \"\\n\";\n\n // Indexbuffer aka f\n for(let i = 0; i < ib.count/3; i++) {\n AMO += `f ${ib.data[i*3]+1}/${ib.data[i*3]+1}/${ib.data[i*3]+1}/${ib.data[i*3]+1}/${ib.data[i*3]+1} `;\n AMO += `${ib.data[i*3+1]+1}/${ib.data[i*3+1]+1}/${ib.data[i*3+1]+1}/${ib.data[i*3+1]+1}/${ib.data[i*3+1]+1} `;\n AMO += `${ib.data[i*3+2]+1}/${ib.data[i*3+2]+1}/${ib.data[i*3+2]+1}/${ib.data[i*3+2]+1}/${ib.data[i*3+2]+1}\\n`;\n }\n AMO += \"\\n\";\n\n // Joints aka j\n for(let i = 0; i < animation.joints.length; i++) {\n if(animation.joints[i].parent != undefined) {\n AMO += `j ${animation.joints[i].name} ${animation.joints[i].parent}\\n`;\n } else {\n AMO += `j ${animation.joints[i].name} -1\\n`;\n }\n }\n AMO += \"\\n\";\n\n // Animation\n if(animation.name != undefined) {\n AMO += `a ${animation.name}\\n\\n`;\n for(let i = 0; i < animation.channels.length; i++) {\n let sampler = animation.samplers[animation.channels[i].sampler];\n for(let j = 0; j < sampler.timeBuffer.count; j++) {\n // Position aka ap\n if(animation.channels[i].path == \"translation\") {\n AMO += `ap ${sampler.timeBuffer.data[j]} ${animation.channels[i].joint+1} ${sampler.valueBuffer.data[j*3]} ${sampler.valueBuffer.data[j*3+1]} ${sampler.valueBuffer.data[j*3+2]}\\n`;\n // Rotation aka ar\n } else if(animation.channels[i].path == \"rotation\") {\n AMO += `ar ${sampler.timeBuffer.data[j]} ${animation.channels[i].joint+1} ${sampler.valueBuffer.data[j*4]} ${sampler.valueBuffer.data[j*4+1]} ${sampler.valueBuffer.data[j*4+2]} ${sampler.valueBuffer.data[j*4+3]}\\n`;\n }\n }\n }\n }\n return AMO;\n}", "function EngineCore(){\n this.State = new EngineState();\n this.TimeKeeper = new TimeKeeper();\n this.Matrices = {};\n this.MatStack = new Stack();\n this.Shaders = {};\n this.Objects = {};\n this.Textures = {};\n this.ShaderVars = {};\n this.Fonts = {};\n this.Extensions = {};\n this.World = {};\n this.Cameras = [];\n this.AnimPlayer = new AnimPlayer();\n //==============================================================================\n //Initializes the Graphics Engine\n //==============================================================================\n this.init = function(){\n canvas = document.getElementById('WebGL', {antialias:true});\n try{\n gl = canvas.getContext(\"experimental-webgl\");\n //Extensions====================================================================\n this.Extensions.aniso = gl.getExtension(\"EXT_texture_filter_anisotropic\");\n //==============================================================================\n //Event Listeners here==========================================================\n document.addEventListener(\"visibilitychange\", Engine.pause, false);\n //==============================================================================\n this.LoadShaders(['Unlit', 'Lit']);\n this.LoadMeshData(['Monkey']);\n this.LoadExtraTex(['CalibriWhite', 'VerdanaWhite']);\n Engine.Fonts['Calibri'] = new fontInfo('Calibri');\n Engine.Fonts['Verdana'] = new fontInfo('Verdana');\n this.Cameras.push(new Camera(this.Cameras.length));\n this.Cameras[0].transform.position = vec3.fromValues(0,0,3);\n this.Matrices.ModelMatrix = mat4.create();\n this.Matrices.NormalMatrix = mat4.create();\n this.Matrices.MVPMatrix = mat4.create();\n this.Matrices.TempMatrix = mat4.create();\n gl.clearColor(0.3,0.3,0.3,1);\n gl.enable(gl.CULL_FACE);\n gl.enable(gl.DEPTH_TEST);\n this.State.initialized = true;\n doneLoading();\n }\n catch(e){\n canvas.style.display = 'none';\n doneLoading();\n }\n }\n //==============================================================================\n //Draws current frame on canvas\n //Avoid all 'this' references, as this function is part of update which uses callbacks\n //==============================================================================\n this.renderFrame = function(){\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n //Reset matrices\n mat4.identity(Engine.Matrices.ModelMatrix);\n //Set view to current active camera\n Engine.Cameras[Engine.State.ActiveCamera].setView();\n //Push default matrices to top of stack\n Engine.MatStack.push(Engine.Matrices.ModelMatrix);\n Engine.MatStack.push(Engine.Matrices.MVPMatrix);\n\n for (var obj in Engine.World){\n if(Engine.World.hasOwnProperty(obj) && Engine.Shaders[Engine.World[obj].Shader].compiled!=false && Engine.World[obj].initialized){\n //Pop fresh model and mvp Matrices\n Engine.Matrices.MVPMatrix = Engine.MatStack.pop();\n Engine.Matrices.ModelMatrix = Engine.MatStack.pop();\n Engine.MatStack.push(Engine.Matrices.ModelMatrix);\n Engine.MatStack.push(Engine.Matrices.MVPMatrix);\n //Create an alias for the current object\n var obj = Engine.World[obj];\n //Set shader for current object\n gl.useProgram(Engine.Shaders[obj.Shader].Program);\n //Perform per object transformations here\n Engine.evalTransform(obj);\n //Apply perspective distortion\n mat4.multiply(Engine.Matrices.MVPMatrix, Engine.Matrices.MVPMatrix, Engine.Matrices.ModelMatrix);\n //Bind attributes\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.position);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_Position, 3, gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.uv);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_UV, 2, gl.FLOAT, false, 0, 0);\n if(Engine.Shaders[obj.Shader].Attributes.a_Normal >= 0){\n gl.bindBuffer(gl.ARRAY_BUFFER, obj.Buffer.normal);\n gl.vertexAttribPointer(Engine.Shaders[obj.Shader].Attributes.a_Normal, 3, gl.FLOAT, false, 0, 0);\n }\n //Call draw\n obj.draw();\n }}\n }\n //==============================================================================\n //Primary render loop\n //Avoid all 'this' references, as this function uses a callback\n //==============================================================================\n var inter = window.performance.now();\n this.Update = function(){\n var begin = window.performance.now();\n inter = window.performance.now() - inter;\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n //Call any runtime logic here\n frame = requestAnimationFrame(Engine.Update, canvas);\n Engine.renderFrame();\n Engine.TimeKeeper.update();\n Engine.AnimPlayer.update();\n Engine.TimeKeeper.frameTime = (window.performance.now()-begin).toFixed(2);\n Engine.TimeKeeper.interFrameTime = inter.toFixed(2);\n inter = window.performance.now();\n }\n //==============================================================================\n //Download And Compile Shader Code From Server.\n //Shaders must use the (shaderName)_(f/v).glsl naming convention\n //==============================================================================\n this.LoadShaders = function(ShaderNames){\n console.group(\"Shader Loading\");\n ShaderNames.forEach(function(element){\n console.log(\"Requesting Shader: \"+element);\n this.Shaders[element] = new Shader(element);\n }, this);\n console.groupEnd();\n }\n //==============================================================================\n //Download and bind mesh data from server\n //==============================================================================\n this.LoadMeshData = function(MeshNames){\n console.group(\"Mesh Loading\");\n MeshNames.forEach(function(element){\n console.groupCollapsed(\"Mesh: \"+element);\n this.Objects[element] = new Mesh(element);\n this.Objects[element].load();\n console.groupEnd();\n }, this);\n console.groupEnd();\n }\n //==============================================================================\n //Dowload and bind extra textures form server\n //==============================================================================\n this.LoadExtraTex = function(TexNames){\n TexNames.forEach(function(element){\n LoadTex((\"Resources/Textures/\"+element+\".png\"), element, Engine);\n }, this);\n }\n //==============================================================================\n //Pause the engine when window has lost focus\n //==============================================================================\n this.pause = function(){\n if(document.hidden){\n cancelAnimationFrame(frame);\n }\n else{\n Engine.TimeKeeper.lastFrame = window.performance.now();\n requestAnimationFrame(Engine.Update, canvas);\n }\n }\n //==============================================================================\n //Take an object and instance it into the world\n //==============================================================================\n this.Instantiate = function(obj, trans = null){\n var instanceName = (obj.tag)+'.'+((obj.numinstances)++).toString();\n obj.instances.push(instanceName);\n this.World[instanceName] = this.Duplicate(obj, instanceName, trans);\n return instanceName;\n }\n //==============================================================================\n //Duplicate an object. Return duplicate.\n //==============================================================================\n this.Duplicate = function(obj, name, trans){\n var newObj = new Mesh(name);\n newObj.Buffer = obj.Buffer;\n newObj.Textures = obj.Textures;\n if(trans != undefined){newObj.transform.copy(trans);}\n else{newObj.transform.copy(obj.transform);}\n newObj.Shader = obj.Shader;\n newObj.initialized = obj.initialized;\n return newObj;\n }\n //==============================================================================\n //recursive function to evaluate an object's tranform based on its parent\n //==============================================================================\n this.evalTransform = function(obj){\n if(obj.parent != null){\n this.evalTransform(obj.parent);\n }\n obj.transform.applyParent(Engine.Matrices.ModelMatrix);\n obj.transform.apply(Engine.Matrices.ModelMatrix);\n }\n}", "function RenderFrameContext( o )\r\n{\r\n\tthis.width = 0; //0 means the same size as the viewport, negative numbers mean reducing the texture in half N times\r\n\tthis.height = 0; //0 means the same size as the viewport\r\n\tthis.precision = RenderFrameContext.DEFAULT_PRECISION; //LOW_PRECISION uses a byte, MEDIUM uses a half_float, HIGH uses a float, or directly the texture type (p.e gl.UNSIGNED_SHORT_4_4_4_4 )\r\n\tthis.filter_texture = true; //magFilter: in case the texture is shown, do you want to see it pixelated?\r\n\tthis.format = GL.RGB; //how many color channels, or directly the texture internalformat \r\n\tthis.use_depth_texture = true; //store the depth in a texture\r\n\tthis.use_stencil_buffer = false; //add an stencil buffer (cannot be read as a texture in webgl)\r\n\tthis.num_extra_textures = 0; //number of extra textures in case we want to render to several buffers\r\n\tthis.name = null; //if a name is provided all the textures will be stored in the ONE.ResourcesManager\r\n\r\n\tthis.generate_mipmaps = false; //try to generate mipmaps if possible (only when the texture is power of two)\r\n\tthis.adjust_aspect = false; //when the size doesnt match the canvas size it could look distorted, settings this to true will fix the problem\r\n\tthis.clone_after_unbind = false; //clones the textures after unbinding it. Used when the texture will be in the 3D scene\r\n\r\n\tthis._fbo = null;\r\n\tthis._color_texture = null;\r\n\tthis._depth_texture = null;\r\n\tthis._textures = []; //all color textures (the first will be _color_texture)\r\n\tthis._cloned_textures = null; //in case we set the clone_after_unbind to true\r\n\tthis._cloned_depth_texture = null;\r\n\r\n\tthis._version = 1; //to detect changes\r\n\tthis._minFilter = gl.NEAREST;\r\n\r\n\tif(o)\r\n\t\tthis.configure(o);\r\n}", "_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {\n weights\n } = opts;\n const {\n numCol,\n numRow\n } = opts;\n const framebufferSize = {\n width: numCol,\n height: numRow\n };\n\n for (const id in weights) {\n const {\n needMin,\n needMax,\n combineMaxMin,\n operation\n } = weights[id];\n textures[id] = weights[id].aggregationTexture || textures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-texture`,\n width: numCol,\n height: numRow\n });\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_5__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] = meanTextures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-mean-texture`,\n width: numCol,\n height: numRow\n });\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n\n if (framebuffers[id]) {\n framebuffers[id].attach({\n [_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0__[\"default\"].COLOR_ATTACHMENT0]: texture\n });\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"].SUM; // For min/max framebuffers will use default size 1X1\n\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxMinFb`,\n texture\n });\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }", "createClip(options, cb) {\n let filePath = options.filePath;\n let fileName = StringHelper.randomString(5) + '_clip_' + StringHelper.getFileName(filePath, true) + '.mp4';\n let savePath = path.join(StringHelper.getFilePath(filePath), fileName);\n\n let command = new ffmpeg(filePath)\n // set target codec\n // https://gist.github.com/nikhan/26ddd9c4e99bbf209dd7\n //ffmpeg -i in.mkv -pix_fmt yuv420p -vcodec libx264 -vf scale=640:-1 -acodec aac -vb 1024k -minrate 1024k -maxrate 1024k -bufsize 1024k -ar 44100 -ac 2 -strict experimental -r 30 out.mp4\n //ffmpeg -i test.mov -vcodec libx264 -vf 'scale=640:trunc(ow/a/2)*2' -acodec aac -vb 1024k -minrate 1024k -maxrate 1024k -bufsize 1024k -ar 44100 -strict experimental -r 30 out.mp4s\n .videoCodec('libx264')\n .addOption('-ss', options.fromTime || '0')\n .addOption('-t', '20')\n .addOption('-pix_fmt', 'yuv420p')\n .addOption('-vf', 'scale=640:-1')\n .addOption('-acodec', 'aac')\n .addOption('-vb', '1024k')\n .addOption('-minrate', '1024k')\n .addOption('-maxrate', '1024k')\n .addOption('-bufsize', '1024k')\n .addOption('-ar', '44100')\n .addOption('-ac', '2')\n .addOption('-r', '24')\n .size('360x?')\n .outputOptions('-strict experimental')\n .on('end', function() {\n cb(null, fileName);\n })\n .on('error', cb)\n .toFormat('mp4');\n if (options.size) {\n command.size(options.size);\n }\n // save to file\n command.save(savePath);\n }", "texImage3D(ctx, funcName, args) {\n let [target, level, internalFormat, width, height, depth, border, format, type] = args;\n const info = getTextureInfo(target);\n updateMipLevel(info, target, level, internalFormat, width, height, depth, type);\n }", "_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {weights} = opts;\n const {numCol, numRow} = opts;\n const framebufferSize = {width: numCol, height: numRow};\n for (const id in weights) {\n const {needMin, needMax, combineMaxMin, operation} = weights[id];\n textures[id] =\n weights[id].aggregationTexture ||\n textures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-texture`, width: numCol, height: numRow});\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_3__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] =\n meanTextures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-mean-texture`, width: numCol, height: numRow});\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n if (framebuffers[id]) {\n framebuffers[id].attach({[_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0___default.a.COLOR_ATTACHMENT0]: texture});\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"].SUM;\n // For min/max framebuffers will use default size 1X1\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {id: `${id}-maxMinFb`, texture});\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }", "render(program, renderParameters, textures){\n //renders the media source to the WebGL context using the pased program\n let overriddenElement;\n for (let i = 0; i < this.mediaSourceListeners.length; i++) {\n if (typeof this.mediaSourceListeners[i].render === 'function'){\n let result = this.mediaSourceListeners[i].render(this, renderParameters);\n if (result !== undefined) overriddenElement = result;\n }\n }\n\n this.gl.useProgram(program);\n let renderParametersKeys = Object.keys(renderParameters);\n let textureOffset = 1;\n for (let index in renderParametersKeys){\n let key = renderParametersKeys[index];\n let parameterLoctation = this.gl.getUniformLocation(program, key);\n if (parameterLoctation !== -1){\n if (typeof renderParameters[key] === \"number\"){\n this.gl.uniform1f(parameterLoctation, renderParameters[key]);\n }\n else if( Object.prototype.toString.call(renderParameters[key]) === '[object Array]'){\n let array = renderParameters[key];\n if(array.length === 1){\n this.gl.uniform1fv(parameterLoctation, array);\n } else if(array.length === 2){\n this.gl.uniform2fv(parameterLoctation, array);\n } else if(array.length === 3){\n this.gl.uniform3fv(parameterLoctation, array);\n } else if(array.length === 4){\n this.gl.uniform4fv(parameterLoctation, array);\n } else{\n console.debug(\"Shader parameter\", key, \"is too long and array:\", array);\n }\n }\n else{\n //Is a texture\n this.gl.activeTexture(this.gl.TEXTURE0 + textureOffset);\n this.gl.uniform1i(parameterLoctation, textureOffset);\n this.gl.bindTexture(this.gl.TEXTURE_2D, textures[textureOffset-1]);\n }\n }\n }\n \n this.gl.activeTexture(this.gl.TEXTURE0);\n let textureLocation = this.gl.getUniformLocation(program, \"u_image\");\n this.gl.uniform1i(textureLocation, 0);\n this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture);\n if (overriddenElement !== undefined){\n this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, overriddenElement);\n } else {\n this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.element);\n }\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);\n }", "function setFlags() {\n\n var WEBGL_VERSION = 2\n var WASM_HAS_SIMD_SUPPORT = false\n var WASM_HAS_MULTITHREAD_SUPPORT = false\n var WEBGL_CPU_FORWARD = true\n var WEBGL_PACK = true\n var WEBGL_FORCE_F16_TEXTURES = false\n var WEBGL_RENDER_FLOAT32_CAPABLE = true\n var WEBGL_FLUSH_THRESHOLD = -1\n var CHECK_COMPUTATION_FOR_ERRORS = false\n\n wasmFeatureDetect.simd().then(simdSupported => {\n if (simdSupported) {\n // alert(\"simd supported\")\n WASM_HAS_SIMD_SUPPORT = true\n } else {\n // alert(\"no simd\")\n }\n });\n wasmFeatureDetect.threads().then(threadsSupported => {\n if (threadsSupported) {\n // alert(\"multi thread supported\")\n WASM_HAS_MULTITHREAD_SUPPORT = true;\n } else {\n // alert(\"no multi thread\")\n }\n });\n switch (getOS()) {\n case 'Mac OS':\n // alert('Mac detected')\n WEBGL_VERSION = 1\n break;\n case 'Linux':\n // alert('linux detected')\n break;\n case 'iOS':\n // alert('ios detected')\n WEBGL_VERSION = 1\n WEBGL_FORCE_F16_TEXTURES = true //use float 16s on mobile just incase \n WEBGL_RENDER_FLOAT32_CAPABLE = false\n break;\n case 'Android':\n WEBGL_FORCE_F16_TEXTURES = true\n WEBGL_RENDER_FLOAT32_CAPABLE = false\n line_width = 3\n radius = 4\n // alert('android detected')\n break;\n default:\n // alert('windows detected')\n break;\n\n }\n\n var flagConfig = {\n WEBGL_VERSION: WEBGL_VERSION,\n WASM_HAS_SIMD_SUPPORT: WASM_HAS_SIMD_SUPPORT,\n WASM_HAS_MULTITHREAD_SUPPORT: WASM_HAS_MULTITHREAD_SUPPORT,\n WEBGL_CPU_FORWARD: WEBGL_CPU_FORWARD,\n WEBGL_PACK: WEBGL_PACK,\n WEBGL_FORCE_F16_TEXTURES: WEBGL_FORCE_F16_TEXTURES,\n WEBGL_RENDER_FLOAT32_CAPABLE: WEBGL_RENDER_FLOAT32_CAPABLE,\n WEBGL_FLUSH_THRESHOLD: WEBGL_FLUSH_THRESHOLD,\n CHECK_COMPUTATION_FOR_ERRORS: CHECK_COMPUTATION_FOR_ERRORS,\n }\n\n setEnvFlags(flagConfig)\n\n}", "function running() {\n background(0);\n\n if (slider.value() < 1) {\n introText();\n } else if (slider.value() > 1 && slider.value() < 6) {\n background(255);\n }\n\n if (videoReady) {\n // Display the webcam\n let flippedVideo = ml5.flipImage(video);\n image(flippedVideo, 50, 50, w - 100, h);\n\n if (slider.value() > 1) {\n filter(INVERT);\n drawPosts();\n // if (slider.value() < 6) {\n // tint(255, 127);\n // image(facePost, 50, 50, w - 100, h);\n // }\n }\n\n if (slider.value() > 5 && slider.value() < 8) {\n push();\n tint(255, 127);\n image(flippedVideo, 0, 0, width / 2, height); //video on canvas, position, dimensions\n translate(width, 0); // move to far corner\n scale(-1.0, 1.0); // flip x-axis backwards\n image(flippedVideo, 0, 0, width / 2, height); //video on canvas, position, dimensions\n pop();\n }\n\n if (slider.value() > 7) {\n filter(INVERT);\n filter(THRESHOLD, slider.value() / 50);\n }\n\n if (slider.value() > 15) {\n title();\n }\n }\n\n // Check if there currently predictions to display\n if (predictions) {\n // If so run through the array of predictions\n for (let i = 0; i < predictions.length; i++) {\n // Get the object predicted\n let object = predictions[i];\n // Highlight it on the canvas\n if (slider.value() > 1 && slider.value() < 16) {\n highlightObject(object);\n }\n }\n }\n}", "function DepthRenderer(scene,type,camera){if(type===void 0){type=BABYLON.Engine.TEXTURETYPE_FLOAT;}if(camera===void 0){camera=null;}var _this=this;/**\n * Specifiess that the depth renderer will only be used within\n * the camera it is created for.\n * This can help forcing its rendering during the camera processing.\n */this.useOnlyInActiveCamera=false;this._scene=scene;// Register the G Buffer component to the scene.\nvar component=scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);if(!component){component=new BABYLON.DepthRendererSceneComponent(scene);scene._addComponent(component);}this._camera=camera;var engine=scene.getEngine();// Render target\nthis._depthMap=new BABYLON.RenderTargetTexture(\"depthMap\",{width:engine.getRenderWidth(),height:engine.getRenderHeight()},this._scene,false,true,type);this._depthMap.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE;this._depthMap.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE;this._depthMap.refreshRate=1;this._depthMap.renderParticles=false;this._depthMap.renderList=null;// Camera to get depth map from to support multiple concurrent cameras\nthis._depthMap.activeCamera=this._camera;this._depthMap.ignoreCameraViewport=true;this._depthMap.useCameraPostProcesses=false;// set default depth value to 1.0 (far away)\nthis._depthMap.onClearObservable.add(function(engine){engine.clear(new BABYLON.Color4(1.0,1.0,1.0,1.0),true,true,true);});// Custom render function\nvar renderSubMesh=function renderSubMesh(subMesh){var mesh=subMesh.getRenderingMesh();var scene=_this._scene;var engine=scene.getEngine();var material=subMesh.getMaterial();if(!material){return;}// Culling and reverse (right handed system)\nengine.setState(material.backFaceCulling,0,false,scene.useRightHandedSystem);// Managing instances\nvar batch=mesh._getInstancesRenderList(subMesh._id);if(batch.mustReturn){return;}var hardwareInstancedRendering=engine.getCaps().instancedArrays&&batch.visibleInstances[subMesh._id]!==null;var camera=_this._camera||scene.activeCamera;if(_this.isReady(subMesh,hardwareInstancedRendering)&&camera){engine.enableEffect(_this._effect);mesh._bind(subMesh,_this._effect,BABYLON.Material.TriangleFillMode);_this._effect.setMatrix(\"viewProjection\",scene.getTransformMatrix());_this._effect.setFloat2(\"depthValues\",camera.minZ,camera.minZ+camera.maxZ);// Alpha test\nif(material&&material.needAlphaTesting()){var alphaTexture=material.getAlphaTestTexture();if(alphaTexture){_this._effect.setTexture(\"diffuseSampler\",alphaTexture);_this._effect.setMatrix(\"diffuseMatrix\",alphaTexture.getTextureMatrix());}}// Bones\nif(mesh.useBones&&mesh.computeBonesUsingShaders&&mesh.skeleton){_this._effect.setMatrices(\"mBones\",mesh.skeleton.getTransformMatrices(mesh));}// Draw\nmesh._processRendering(subMesh,_this._effect,BABYLON.Material.TriangleFillMode,batch,hardwareInstancedRendering,function(isInstance,world){return _this._effect.setMatrix(\"world\",world);});}};this._depthMap.customRenderFunction=function(opaqueSubMeshes,alphaTestSubMeshes,transparentSubMeshes,depthOnlySubMeshes){var index;if(depthOnlySubMeshes.length){engine.setColorWrite(false);for(index=0;index<depthOnlySubMeshes.length;index++){renderSubMesh(depthOnlySubMeshes.data[index]);}engine.setColorWrite(true);}for(index=0;index<opaqueSubMeshes.length;index++){renderSubMesh(opaqueSubMeshes.data[index]);}for(index=0;index<alphaTestSubMeshes.length;index++){renderSubMesh(alphaTestSubMeshes.data[index]);}};}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the parent directory of a filename, if it does not already exist
mkParentPath(dir, cb) { var segs = dir.split(/[\\\/]/); segs.pop(); if (!segs.length) { return cb && cb(); } dir = segs.join(path.sep); return this.mkpath(dir, cb); }
[ "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}", "function createDirectoryForFile(source, output, filePath, verbose) {\n var relativeFilePath = _path[\"default\"].relative(source, filePath);\n\n var relativeDirectoryPath = _path[\"default\"].dirname(relativeFilePath);\n\n var outputDirectoryPath = _path[\"default\"].join(output, relativeDirectoryPath);\n\n if (verbose) {\n console.info(\"Making sure directory \" + source + \" exists\\u2026\");\n }\n\n return new Promise(function (resolve, reject) {\n (0, _mkdirp[\"default\"])(outputDirectoryPath, function (err) {\n if (err) {\n reject(Error(\"Failed to create directory \" + outputDirectoryPath));\n }\n\n var fileName = _path[\"default\"].basename(filePath);\n\n var outputFilePath = _path[\"default\"].join(outputDirectoryPath, fileName);\n\n resolve(outputFilePath);\n });\n });\n}", "function safeCreateFileDir(path) {\n var dir = pathAPI.dirname(path);\n if (!fileSystem.existsSync(dir)) {\n wrenchTool.mkdirSyncRecursive(dir);\n }\n}", "function insertNode(currentPath, remainingPath, parent, firstLevel) {\n var remainingDirectories = remainingPath.split('/');\n var nodeName = remainingDirectories[0];\n var newPath = firstLevel ? nodeName : (currentPath + '/' + nodeName);\n // console.log('=== inserting: '+ nodeName);\n if (remainingDirectories.length === 1) { // actual file to insert\n // console.log('last item');\n var node = createNode(nodeName, newPath, parent, [], 0);\n parent.children.push(node);\n return;\n }\n else {\n // path consists of multiple directories and a file\n // console.log('not last item')\n var node = findAndGetChild(nodeName, parent);\n remainingDirectories.shift();\n var pathToGo = remainingDirectories.join('/');\n if (node) {\n // directory already exists\n insertNode(newPath, pathToGo, node, false);\n return;\n }\n else {\n // create the directory and insert on it\n node = createNode(nodeName, newPath, parent, [], 0);\n parent.children.push(node);\n insertNode(newPath, pathToGo, node, false);\n return;\n }\n }\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 }", "function createNewFolder() {\n var id = $(this).parent().attr(\"data-id\");\n fileSystem.createFileOrFolder(id, \"folder\");\n updateUI();\n }", "function parentDir (path) {\n var lastSlash = path.lastIndexOf('/');\n return lastSlash > 0 ? path.substring(0, lastSlash + 1) : undefined;\n }", "function safeCreateFileDir(path) {\n if (!WRITE_ENABLED) {\n return;\n }\n var dir = pathAPI.dirname(path);\n if (!fileSystem.existsSync(dir)) {\n wrenchTool.mkdirSyncRecursive(dir);\n }\n}", "function create_logs_dir() { \n if (!fs.existsSync(logs_dir)) {\n fs.mkdirSync(logs_dir);\n }\n else {\n console.log(\"Already exists!\");\n }\n}", "function createDir(cb) {\n if (\n process.env.UPLOADPATH == undefined ||\n process.env.OUTPUTPATH == undefined\n ) {\n console.log(\"please specify upload path and output path\");\n process.exit(1);\n } else {\n if (!fs.existsSync(process.env.UPLOADPATH)) {\n fs.mkdirSync(process.env.UPLOADPATH, (err) => {\n if (!err) {\n cb(err);\n } else {\n cb(null);\n }\n });\n }\n if (!fs.existsSync(process.env.OUTPUTPATH)) {\n fs.mkdirSync(process.env.OUTPUTPATH, (err) => {\n if (!err) {\n cb(err);\n } else {\n cb(null);\n }\n });\n }\n }\n}", "function getChampionDir(championName, create) {\n var dir = Settings.getLeagueRoot();\n\n if (create) try { FS.mkdirSync(dir); } catch(e) {};\n dir = Path.join(dir, \"Config\");\n if (create) try { FS.mkdirSync(dir); } catch(e) {};\n dir = Path.join(dir, \"Champions\");\n if (create) try { FS.mkdirSync(dir); } catch(e) {};\n dir = Path.join(dir, ChampionTable.nameToDir(championName));\n if (create) try { FS.mkdirSync(dir); } catch(e) {};\n dir = Path.join(dir, \"Recommended\");\n if (create) try { FS.mkdirSync(dir); } catch(e) {};\n\n return dir;\n}", "function createPath(parent, path)\n {\n if (!path.length) // never do \"path == []\"\n {\n return parent;\n }\n else\n {\n var head = path[0];\n var pathrest = path.slice(1, path.length);\n var target = null;\n var nextRoot = null;\n\n // check children\n var children = parent.getChildren();\n\n for (var i=0; i<children.length; i++)\n {\n if (children[i].label == head)\n {\n nextRoot = children[i];\n break;\n }\n }\n\n // else create new\n if (nextRoot == null)\n {\n nextRoot = new demobrowser.Tree(head);\n parent.add(nextRoot);\n }\n\n // and recurse with the new root and the rest of path\n target = createPath(nextRoot, pathrest);\n return target;\n }\n }", "function onstatparent(error) {\n if (error) {\n next(new Error('Cannot read parent directory. Error:\\n' + error.message))\n } else {\n done(false)\n }\n }", "async createWorkingDirectory (path: string): Promise<string> {\n console.log(`Creating Pijin working directory at ${path}`)\n\n return this.fs.mkdir(path)\n }", "function createDirectory(index, path) {\n\n //update path\n path = path + '/' + index.prefix + '-' + index.num;\n\n //create a directory\n if (!fs.existsSync(path)){\n fs.mkdirSync(path);\n }\n\n //save index file\n fs.writeFile(path + '/index.json', JSON.stringify(index, null, 2));\n\n return path;\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 }", "addToTree({ state, commit, getters }, { parentPath, newDirectory }) {\n // If this directory is not the root directory\n if (parentPath) {\n // find parent directory index\n const parentDirectoryIndex = getters.findDirectoryIndex(parentPath);\n\n if (parentDirectoryIndex !== -1) {\n // add a new directory\n commit('addDirectories', {\n directories: newDirectory,\n parentId: state.directories[parentDirectoryIndex].id,\n });\n\n // update parent directory property\n commit('updateDirectoryProps', {\n index: parentDirectoryIndex,\n props: {\n hasSubdirectories: true,\n showSubdirectories: true,\n subdirectoriesLoaded: true,\n },\n });\n } else {\n commit('fm/messages/setError', { message: 'Directory not found' }, { root: true });\n }\n } else {\n // add a new directory to the root of the disk\n commit('addDirectories', {\n directories: newDirectory,\n parentId: 0,\n });\n }\n }", "mkdirIf(cond, ...args) {\n if (isTrue(cond)) this.mkdir(...args);\n }", "function createDestructiveChangeFolder() { \n try {\n var yn = stdin.question(`WARNING: This command will destroy the component in the specified org Y/N: `);\n if(yn === 'y') {\n if(!fs.existsSync(tempPath)) {\n fs.mkdirSync(tempPath); \n console.log(`Folder has been created..`); \n \n }\n else {\n console.log(`No folder exists..`); \n }\n return true;\n }\n }\n catch(err) {\n console.log(`Failed to create the destructive changes folder: ` + err); \n }\n\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refreshes content queries for all directives in the given view.
function refreshContentQueries(tView) { if (tView.contentQueries != null) { for (var i = 0; i < tView.contentQueries.length; i += 2) { var directiveDefIdx = tView.contentQueries[i]; var directiveDef = tView.data[directiveDefIdx]; directiveDef.contentQueriesRefresh(directiveDefIdx - HEADER_OFFSET, tView.contentQueries[i + 1]); } } }
[ "function notifyObservers() {\n _.each(views, function (aView) {\n aView.update();\n });\n } // notifyObservers", "function refresh_content() {\n $('.refresh').on('click', function() {\n show_content();\n });\n }", "function refreshFields(view,focus,changes,path,iserror) {\n // to improve: find scroll parent better.\n var fields = getRefreshFields(view.form.children,changes,path,iserror);\n if (fields.length) {\n var callback = makeCountCallback(fields.length,function(){\n restoreFocus(view,focus);\n });\n fields.forEach(function(el){\n adaptChildrenLength(el,changes[el.propertyId]);\n el.setValue(changes[el.propertyId]);\n el.refresh(callback);\n });\n }\n }", "reload() {\n this.requestWebsites();\n }", "repaintViews() {\n\n for (let viewport of this.viewports) {\n if (viewport.isVisible()) {\n viewport.repaint()\n }\n }\n\n if (typeof this.track.paintAxis === 'function') {\n this.paintAxis()\n }\n\n this.repaintSampleInfo()\n\n this.repaintSamples()\n }", "updateView() {\n if (!this.view) {\n this.initDialog();\n }\n\n this.view.updateView();\n }", "_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }", "function createContentQueriesRefreshFunction(meta) {\n if (meta.queries.length > 0) {\n const statements = [];\n const typeName = meta.name;\n const parameters = [\n new o.FnParam('dirIndex', o.NUMBER_TYPE),\n new o.FnParam('queryStartIndex', o.NUMBER_TYPE),\n ];\n const directiveInstanceVar = o.variable('instance');\n // var $tmp$: any;\n const temporary = temporaryAllocator(statements, TEMPORARY_NAME);\n // const $instance$ = $r3$.ɵload(dirIndex);\n statements.push(directiveInstanceVar.set(o.importExpr(R3.load).callFn([o.variable('dirIndex')]))\n .toDeclStmt(o.INFERRED_TYPE, [o.StmtModifier.Final]));\n meta.queries.forEach((query, idx) => {\n const loadQLArg = o.variable('queryStartIndex');\n const getQueryList = o.importExpr(R3.loadQueryList).callFn([\n idx > 0 ? loadQLArg.plus(o.literal(idx)) : loadQLArg\n ]);\n const assignToTemporary = temporary().set(getQueryList);\n const callQueryRefresh = o.importExpr(R3.queryRefresh).callFn([assignToTemporary]);\n const updateDirective = directiveInstanceVar.prop(query.propertyName)\n .set(query.first ? temporary().prop('first') : temporary());\n const refreshQueryAndUpdateDirective = callQueryRefresh.and(updateDirective);\n statements.push(refreshQueryAndUpdateDirective.toStmt());\n });\n return o.fn(parameters, statements, o.INFERRED_TYPE, null, typeName ? `${typeName}_ContentQueriesRefresh` : null);\n }\n return null;\n}", "function refresh() {\n $scope.award = {};\n $scope.awardLocation = {};\n\n getAwardList(personReferenceKey);\n\n\n\n\n }", "function refreshAll() {\r\n\tgenerateNotes();\r\n\tdetermineInterval();\r\n\tsetTimeout(function() {\r\n\tplayNotes();\r\n\t}, 100)\r\n}", "rebuild(basePath) {\r\n this.build(basePath);\r\n\r\n setTimeout(() => {\r\n this.renderPartials();\r\n }, 10);\r\n }", "refreshIndex () {\n\t\tvar self = this;\n\n\t\tbefore( function (done){\n\t\t\telastic.manualRefresh('kt_' + self.glossary._id)\n\t\t\t.then(function (res) {\n\t\t\t\tdone();\n\t\t\t})\n\t\t\t.catch(done);\n\n\t\t})\n\n\t}", "function refresh_all_action_items() {\n\tconsole.log(\"now refreshing\");\n\t$(\"div#projects div.project\").each( function() {\n\t\trefresh_action_items(this);\n\t});\n}", "function redrawAllEditor() {\n const event = new Event('resize')\n window.dispatchEvent(event)\n } // CONCATENATED MODULE: ./src/lib/component/SettingDialog/reflectImmediately/bindChangeLineHeight.js", "onDialogLoadedNotification() {\n this._refresh();\n }", "requestContentUpdate() {\n if (this._columnTree) {\n // header and footer renderers\n this._columnTree.forEach((level) => {\n level.forEach((column) => {\n column._renderHeaderAndFooter();\n });\n });\n\n // body and row details renderers\n this.__updateVisibleRows();\n }\n }", "async refresh() {\n // Ensure model is registered before fetching model data\n assert.instanceOf(this.constructor.__db, DbApi, 'Model must be registered.');\n\n // Ensure this Model instance is stored in database\n assert.isNotNull(this.__id, 'Model must be stored in database to refresh.');\n\n // Replace this Model instance's internal data with fetched data from the database\n this.__data = await this.constructor.__db.findDataById(this.constructor, this.__id);\n\n // Reset internally stored updates\n this.__updates = new Set();\n }", "async refresh() {\n this.locations = await this.getLocations();\n this.weatherModels = [];\n\n if (this.locations.length > 0) {\n document.getElementById('no-locations').style.display = 'none';\n }\n\n _util.default.displayLoading(true);\n\n if (this.locations.length) {\n _util.default.clearDivContents('weather');\n\n for (let i = 0; i < this.locations.length; i++) {\n if (this.locations[i]) {\n let model = new WeatherModel(this.locations[i].lat, this.locations[i].lng, i, this.locations[i].full_name);\n await model.init();\n new WeatherView(model).render();\n this.weatherModels.push(model);\n }\n }\n\n this.updateLastUpdated();\n }\n\n _util.default.displayLoading(false);\n }", "function refresh_iframe($codemirror) {\n $codemirror.each(function() {\n var $this = $(this);\n $this.get(0).CodeMirror.refresh();\n $this.children('iframe').trigger('_resize');\n });\n}", "refreshAllBuffers() {\n\t\tfor (const attributeName in this.attributes)\n\t\t\tthis.refreshAttribData(attributeName);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an item by primary key (User ID and SN)
async get(userID, sn) { const params = { Key: { user_id: userID, sn: sn }, TableName: devicesTable }; const res = await this.db.get(params).promise(); return res; }
[ "getUserFromUhId(uhID) {\n check(uhID, String);\n return this._collection.findOne({ uhID });\n }", "function getRowId(req, res) {\n db.data.get(`SELECT rowid FROM users WHERE username = '${req.username}'`, function(err, user) {\n if (err) {\n console.error(\"There was an error retrieving the user from the database\");\n } else {\n res.json({id: user.rowid});\n }\n });\n}", "function SearchUserById(userId) {\n for (var i = 0; i < Users.length; i++) {\n if (Users[i].id === userId) {\n return Users[i];\n }\n }\n return null;\n}", "getUserByUsername(username) {\n for (var id in this.users) {\n if (username === this.users[id].username)\n return this.users[id];\n }\n return null;\n }", "function readPerson(req, res, next) {\n let stmt = new PS({name: 'read-person', text: \"SELECT * FROM Person WHERE emailPrefix = $1\", values: [req.params.id]})\n db.oneOrNone(stmt)\n .then(data => {\n res.send(data);\n })\n .catch(err => {\n next(err);\n });\n}", "getSingleUserEvent(db, user_id, id){\n return db\n .from('events')\n .select('*')\n .where({user_id, id});\n }", "function findRecipeByUser(userId) {\n return RecipeModel.find({ username: username });\n}", "getUserBySocketID(socketID) {\n if (this.users.hasOwnProperty(socketID))\n return this.users[socketID];\n }", "function findEntry(resultId, db) {\n for (const page of db) {\n if (page.id === resultId) {\n return page;\n }\n }\n return resultId;\n}", "function findByIsbn(isbn){\n return db('books')\n .where({ isbn })\n .first()\n}", "function findKey(record, predicate) {\n for (const a in record) {\n if (predicate(record[a]))\n return a;\n }\n return undefined;\n}", "function getUser(uid) {\n for (var i = 0; i < chatUsers.length; i++) {\n if (chatUsers[i].uid == uid) return chatUsers[i];\n }\n}", "function getItemInfo(id) {\n if (id in item)\n return item[id]\n else\n throw new Error (\"No item with id \" + id)\n }", "get(nodeId) {\n if (nodeId) {\n var node = this.db.database.get(nodeId)\n if (node.length === 1) {\n return node[0]\n }\n }\n }", "static async fetchProductById(productId) {\n const product = storage\n .get(\"products\")\n .find({ id: Number(productId) })\n .value()\n return product\n }", "async getBagItemById(req, res) {\n const bagItemId = req.params.bagItemId;\n\n var { error } = Joi.validate(bagItemId, Joi.objectId().required());\n\n if (error) {\n return res.status(404).send(error.details[0].message);\n }\n\n const bag = await Bag.findById(bagItemId)\n .populate(\"customer\")\n .populate(\"product\");\n\n if (!bag) {\n return res.status(404).send(\"Bag Item not found\");\n }\n\n res.send(bag);\n }", "function findItemKey (itemId) {\n for (var key = 0; key < items.length; key++) {\n if (items[key].id == itemId) {\n return key;\n }\n }\n}", "getRecipeByUserId(knex, userLoginToken) {\n return knex\n .select('id')\n .select('recipe_name')\n .select('recipe_image_link')\n .select('serving_size')\n .select('total_calories')\n .select('cook_time')\n .select('cooking_instruction_link')\n .from('whats_to_eat_recipe_table')\n .where(\n \"user_id\",\n knex\n .select('login_table_user_id')\n .from('whats_to_eat_login_table')\n .where(\"id\", userLoginToken)\n )\n \n }", "getUser(userId) {\n return this.state.allUsers.find((user) => user.id === userId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives a number and returns its CSS pixel value.
function pixelValue(value) { return value + 'px'; }
[ "function toCSSPixels(number) {\r\n if (Object.isString(number) && number.endsWith('px'))\r\n return number;\r\n return number + 'px'; \r\n }", "function rgbToCmy(n) {\n return Math.round((rgbInvert(n) / 255) * 100);\n}", "function setNumber(value, element)\n {\n var percentage = (value - 1) * 11.2;\n\n element.style.backgroundPosition = percentage + \"% 0\";\n }", "function percentToPixel(size, max)\n{\n let percentRegexp = /^[0-9]{1,3}%$/;\n let pixelRegexp = /^[0-9]*px$/;\n\n if (pixelRegexp.exec(size))\n {\n return parseInt(size);\n }\n else if (percentRegexp.exec(size))\n {\n return (parseInt(size) / 100.0) * max;\n }\n else\n return parseInt(size);\n}", "function toFloat(x) {\n return x / 255;\n}", "function getColor(grid, x, y) {\n var idx = round((y * grid.width + x) * 4);\n var c = [grid.pixels[idx], grid.pixels[idx+1], grid.pixels[idx+2]];\n return c;\n}", "function getColor(number) {\n return number > 10 ? \"blue\" : \"red\";\n}", "function pixelsToTileUnits(tile, pixelValue, z) {\n return pixelValue * (__chunk1_js.default$9 / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));\n }", "getColor(value) {\n if (undefined == value) { return 'lightgrey'; }\n if (value < 0) {\n return this.negativeColorScale(value);\n } else {\n return this.selectedPosColorScale(value);\n }\n }", "function colour_scale(x) {\r\n return \"rgb(0,0,\"+((x-min_colour)/(max_colour-min_colour)*256).toString() +\")\"\r\n }", "function TileXYToPixelXY( tileXY )\n\t{\n\t\treturn [ tileXY[0] * 256, tileXY[1] * 256 ];\n\t}", "function sixToRgb(s) {\n return s * 51;\n}", "function get_pixel(piece, x, y)\n{\n\tvar index = x + y * piece.width;\n\tpixel = piece.map[index];\n\tif(pixel == undefined)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn pixel;\n\t}\n}", "function getYPixel(index) {\n return pixelsPerCellSide * Math.floor((index/ (svgW/pixelsPerCellSide)));\n }", "function intCss(elem, prop) {\r\n return parseInt(vendorCss(elem, prop), 10);\r\n}", "function set_board_pixel(board, x, y, value)\n{\n\tvar index = x + y * get_game_width();\n\tboard[index] = value;\n}", "function get_color_value(selector, i) {\n return self.get_css_color($root.find(selector + \" .color_sample\")[i]);\n }", "function rgbToSix(r) {\n return r / 51;\n}", "pixelToPercent(x)\n {\n if (!this.field || !this.field.offsetWidth)\n {\n return 0;\n }\n\n const percent = x / this.field.offsetWidth;\n\n if (this.props.steps)\n {\n const oneStep = 1 / this.props.steps;\n return Math.round(percent / oneStep) * oneStep;\n }\n\n return percent;\n }", "function pointsToPixel(points) {\n\treturn points * 96 / 72;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a module, print a skylark `node_module` rule.
function printNodeModule(mod) { const deps = mod.deps; print(``); printJson(mod); print(`node_module(`); print(` name = "${mod.yarn ? mod.yarn.label : mod.name}",`); // SCC pseudomodule wont have 'yarn' property if (mod.yarn) { const url = mod.yarn.url || mod.url; const sha1 = mod.yarn.sha1; const executables = mod.executables; print(` module_name = "${mod.name}",`); print(` version = "${mod.version}",`); print(` package_json = "node_modules/${mod.name}/package.json",`); // Exclude filenames with spaces: Bazel can't cope with them (we just have to hope they aren't needed later...) print(` srcs = glob(["node_modules/${mod.name}/**/*"], exclude = [ "node_modules/${mod.name}/package.json", "**/* *", ]),`); if (url) { print(` url = "${url}",`); } if (sha1) { print(` sha1 = "${sha1}",`); } if (executables.size > 0) { print(` executables = {`); for (const [name, val] of executables.entries()) { print(` "${name}": "${val}",`); } print(` },`); } } if (deps && deps.size) { print(` deps = [`); deps.forEach(dep => { print(` ":${dep.yarn ? dep.yarn.label : dep.name}",`); }); print(` ],`); } print(`)`); }
[ "function printNodeModuleAll(modules) {\n print(``);\n print(`# Pseudo-module that basically acts as a module collection for the entire set`);\n print(`node_module(`);\n print(` name = \"_all_\",`);\n print(` deps = [`);\n modules.forEach(module => {\n print(` \":${module.yarn ? module.yarn.label : module.name}\",`);\n });\n print(` ],`);\n print(`)`);\n}", "function printNodeBinary(module, key, path) {\n let name = module.name === key ? key : `${module.name}_${key}`;\n // escape special characters like '@' and '/'\n name = name.replace('@', '').replace('/', '_')\n print(``);\n print(`node_binary(`);\n print(` name = \"${name}_bin\",`);\n print(` entrypoint = \":${module.name}\",`);\n print(` executable = \"${key}\", # Refers to './${path}' inside the module`);\n print(`)`);\n}", "function generateNodes (packageName, node) {\n // draw a node\n const nameVersion = `${packageName}@${node.version}`\n let score = scoreMap.get(nameVersion)\n if (score == null) score = NoScoreAvailable\n const url = `https://platform.nodesource.io/registry?name=${packageName}${Amp}version=${node.version}`\n\n const scoreString = score === NoScoreAvailable ? NoScoreAvailable : `${score}%`\n\n let color\n if (score === NoScoreAvailable) {\n color = '#CFCFCF'\n } else if (score === 100) {\n color = '#9FFF9F'\n } else if (score > config.score) {\n color = '#FFFF7F'\n } else {\n color = '#FF9F9F'\n }\n\n // const level = `${packageName}\\\\l${node.version}\\\\lscore: ${scoreString}\\\\l`\n const label = `<font point-size=\"20\">${packageName}</font><br align='left'/>${node.version}<br align='left'/>score: ${scoreString}<br align='left'/>`\n\n out.push(` \"${nameVersion}\" [`)\n out.push(' shape = box,')\n out.push(' style = filled,')\n out.push(` fillcolor = \"${color}\",`)\n out.push(` URL = \"${url}\",`)\n out.push(` tooltip = \"${packageName} @ ${node.version} - score: ${scoreString}\",`)\n out.push(` label = <${label}>,`)\n out.push(' ]')\n\n // recurse\n const deps = node.dependencies || {}\n for (let depName in deps) {\n generateNodes(depName, deps[depName])\n }\n }", "function getReformattedModule(module)\n{\n var ports= toArray(module.ports);\n var inputPorts = _.filter(ports, function(p) {\n return p.direction=='input';\n });\n var outputPorts = _.filter(ports, function(p){\n return p.direction=='output';\n });\n var cells = toArray(module.cells);\n inputPorts.forEach(function(p){p.type= '$_inputExt_';});\n outputPorts.forEach(function(p){p.type='$_outputExt_';});\n cells.forEach(function(c)\n {\n c.inputPorts = getCellPortList(c,'input');\n c.outputPorts = getCellPortList(c,'output');\n });\n inputPorts.forEach(function(p)\n {\n p.inputPorts = [];\n p.outputPorts = [{'key':'Y','value':p.bits}];\n });\n outputPorts.forEach(function(p)\n {\n p.inputPorts = [{'key':'A','value':p.bits}];\n p.outputPorts = [];\n });\n var flatModule = {\n nodes :\n inputPorts\n .concat(outputPorts)\n .concat(cells)\n };\n return flatModule;\n}", "printNodes() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n document.writeln(this.nodes[layer][node].number + \" | \");\n }\n document.writeln(\"</br>\");\n }\n document.writeln(\n \"----------------------------------------------------------------</br>\"\n );\n }", "function getLabel(module) {\n let label = '';\n if (typeof module === 'string') {\n label = module;\n } else if (typeof module === 'object') {\n label = module.filename.split('/').slice(-2).join('/');\n }\n return label;\n}", "function display_nodes_info( node ) \n{\n\twhile( node != null )\n\t{\n\t\tconsole.log( \"Data : \",node.data )\n\t\tnode = node.next\n\t}\n}", "function nr_basicRenderNode(node,divid,titleid)\n{\n\tvar div = $('#'+divid);\n\tdiv.empty();\n\tvar title = $('#'+titleid);\n\tvar ttext = su_getNodeShortLabel(node);\n\ttitle.text(ttext);\n\tdocument.title=ttext;\n\n\t// loop over properties\n\tparr = su_getNodePropertyAndDisplayNames(node.type,node);\n\tvar len = parr.length;\n\tvar prop = null;\n\tvar disp = null;\n\tvar val = null;\n\tvar row = null;\n\tvar lc = null;\n\tvar rc = null;\n\tfor(var i=0; i<len; i++)\n\t{\n\t\tprop = parr[i][0];\n\t\tdisp = parr[i][1];\n\t\tval = node[prop];\n\t\tif(isEmpty(val)) val = node[prop.toLowerCase()];\n\t\tif(isEmpty(val)) continue;\n\t\t\n\t\trow = $('<div class=\"w3-row\"></div>');\n\t\tlc = $('<div class=\"w3-col s1 w3-theme-d3 w3-center\"><p>'+disp+'</p></div>');\n\t\trc = $('<div class=\"w3-col s5 w3-theme-l3\"><p>&nbsp;&nbsp;'+val+'</p></div>');\n\t\trow.append(lc);\n\t\trow.append(rc);\n\t\tdiv.append(row);\n\t}\n} // end nr_basicRenderNode", "function addModule() {\n $('<section>')\n .attr('id', 'rsw-discord')\n .addClass('rsw-custom-module rail-module')\n .append(\n $('<a>')\n .attr('href', 'https://discord.gg/98hqjRg')\n .append(\n $('<img>')\n .attr('src', 'https://vignette.wikia.nocookie.net/dendro/images/9/94/WikiIcon.png/revision/latest/scale-to-width-down/240?cb=20190217055247')\n ),\n $('<div>')\n .append(\n $('<p>')\n .append(\n 'The Infinite Dendrogram Wiki has an Official Discord Server! Click the button below to join and chat with fellow fans live, or click ',\n $('<a>')\n .attr('href', mw.util.wikiGetlink('Infinite Dendrogram Wiki:Discord_Policy'))\n .text('here'),\n ' to read our chat rules.'\n ),\n $('<a>')\n .attr('href', 'https://discord.gg/98hqjRg')\n .addClass('wds-button')\n .text('Get invite')\n )\n )\n .insertBefore('#wikia-recent-activity');\n }", "function showNode(node, color) {\r\n if (color) { \r\n setColor(node, color);\r\n }\r\n resetNode(node, 0);\r\n }", "print() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++)\n this.nodes[layer][node].print();\n }\n }", "renderPorts(node) {\n var nodeNoodle = node.noodle;\n for (var i in node.core.inPorts)\n nodeNoodle.port.render(node, node.core.inPorts[i]);\n\n for (var i in node.core.outPorts)\n nodeNoodle.port.render(node, node.core.outPorts[i]);\n\n nodeNoodle.node.forEachPort(node.core, nodeNoodle.port.renderVal);\n }", "async writeLinksOnNodeModules() {\n const links = await this.manyComponentsWriter._getAllLinks();\n const nodeModulesLinks = links.filterByPath(filePath => filePath.startsWith('node_modules'));\n await nodeModulesLinks.persistAllToCapsule(this.capsule);\n }", "function printPreorder(node) {\n\t\tif (node == null)\n\t\t\treturn;\n\n\t\t/* first print data of node */\n\t\t// document.write(node.key + \" \");\n preorder = preorder + node.key + \" \"\n\n\t\t/* then recur on left sutree */\n\t\tprintPreorder(node.left);\n\n\t\t/* now recur on right subtree */\n\t\tprintPreorder(node.right);\n\t\t\n\t}", "function TrueNode() {\n}", "function define_module(id) {\n return define_module_under(cObject, id);\n}", "layoutHandler(node) {\n\t\tconst category = get(node, \"app_data.explain_data.category\");\n\t\tconst index = get(node, \"app_data.explain_data.index\");\n\t\tconst cost = get(node, \"app_data.explain_data.cost\");\n\n\t\tconst className = this.getClassNameForCategory(category);\n\t\tconst { bodyPath, selectionPath, width } = this.getPaths(node);\n\n\t\tconst nodeFormat = {\n\t\t\tdefaultNodeWidth: width, // Override default width with calculated width\n\t\t\tlabelPosX: (width / 2), // Specify center of label as center of node Note: text-align is set to center in the CSS for this label\n\t\t\tlabelWidth: width, // Set big enough so that label is not truncated and so no ... appears\n\t\t\tellipsisPosX: width - 25, // Always position 25px in from the right side\n\t\t\tbodyPath: bodyPath,\n\t\t\tselectionPath: selectionPath,\n\t\t\tclassName: className,\n\t\t\tdecorations: [\n\t\t\t\t{\n\t\t\t\t\tid: \"labelDecoration1\",\n\t\t\t\t\tx_pos: 10,\n\t\t\t\t\ty_pos: 15,\n\t\t\t\t\twidth: 28,\n\t\t\t\t\tlabel: \"(\" + index + \")\",\n\t\t\t\t\tclass_name: \"small_text\",\n\t\t\t\t\ttemporary: true\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tid: \"labelDecoration2\",\n\t\t\t\t\tposition: \"bottomCenter\",\n\t\t\t\t\tx_pos: -25,\n\t\t\t\t\ty_pos: -19,\n\t\t\t\t\twidth: 50,\n\t\t\t\t\tlabel: cost,\n\t\t\t\t\tclass_name: \"small_text\",\n\t\t\t\t\ttemporary: true\n\t\t\t\t}\n\t\t\t]\n\t\t};\n\n\t\treturn nodeFormat;\n\t}", "function mangleNode(node, o)\n{\n\t// Don't mangle nodes more than once\n\tif (o.alreadyMangledNodes.has(node))\n\t\treturn;\n\t\n\tnode.name = mangleName(node.name, o);\n\to.alreadyMangledNodes.add(node);\n}", "printDebug()\n {\n console.log(\"Tree contents\");\n this.iterateTree(function(node)\n {\n console.log(node);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear Clears the session from local storage and cookies
function _clear() { // Delete from localStorage delete localStorage['_session']; // Delete the cookie Cookies.remove('_session', '.' + window.location.hostname, '/'); }
[ "clearSession() {\n ['accessToken', 'expiresAt', 'idToken'].forEach(key => {\n sessionStorage.removeItem(key);\n });\n\n this.accessToken = '';\n this.idToken = '';\n this.expiresAt = '';\n }", "function clearWebStorage(){\r\n\t\t\t//Clearing session storage\r\n\t\t\tsessionStorage.clear();\r\n\t\t\t//Clearing local storage \r\n\t\t\tlocalStorage.clear();\r\n\t\t\t//Removing localstorage data from browser cache\r\n\t\t\tstore.remove('loggedonuser');\r\n\t\t\tstore.remove('authtoken');\r\n\t\t\tstore.remove('IsRememberMe');\r\n\t\t}", "function clear() {\n localStorage.clear();\n location.reload();\n}", "function logout() {\n sessionStorage.removeItem(\"userId\");\n sessionStorage.removeItem(\"jwt\");\n }", "logout() {\n this._mealPlan = null\n this._userId = null\n this._token = null\n this._diet = null\n this._intolerances = null\n\n sessionStorage.removeItem('mealPlan')\n sessionStorage.removeItem('userId')\n sessionStorage.removeItem('token')\n sessionStorage.removeItem('diet')\n sessionStorage.removeItem('intolerances')\n }", "vaciarLocalStorage() {\n localStorage.clear();\n }", "function clearStorage() {\n Object.keys(localStorage).filter(function (key) {\n return key.startsWith(options.name);\n }).forEach(function (key) {\n return localStorage.removeItem(key);\n });\n}", "function clearIdToken() {\n localStorage.removeItem(ID_TOKEN_KEY);\n}", "function clearCityStorage() {\n window.localStorage.clear();\n location.reload();\n}", "logout() {\n debug(\"=== Hotjar logout running... ===\")\n debug(\"Remove local storage and cookie with: %s\", this.hjSessionKeyName)\n removeLocalStorageItem(this.hjSessionKeyName)\n removeLocalItem(this.hjSessionKeyName)\n debug(\"=== Hotjar logout finished... ===\")\n }", "function logout() {\n // clear the token\n AuthToken.setToken();\n }", "function clearSavedState()\n{\n localStorage.clear(); // nuclear option\n console.info(\"All saved states have been cleared.\");\n}", "function spotifyLogout() {\n // Wipe localStorage values.\n localStorage.removeItem(SPOTIFY_ACCESS_TOKEN_KEY);\n localStorage.removeItem(SPOTIFY_REFRESH_TOKEN_KEY);\n localStorage.removeItem(SPOTIFY_VOLUME_KEY);\n\n // Refresh the page.\n window.location.href = window.location.href;\n}", "function logout() {\n window.localStorage.removeItem(\"authToken\");\n delete axios.defaults.headers[\"Authorization\"];\n}", "static clearCookie() {\n var cookies = document.cookie.split(\";\");\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;\n if (name.trim().toLowerCase() == 'voting-username')\n document.cookie = name + \"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n }\n \n }", "function logout() {\r\n $window.localStorage.removeItem('jwtToken');\r\n delete $window.localStorage['jwtToken'];\r\n $rootScope.$broadcast('loggedOut');\r\n }", "logoutUser() {\n this.get('session').invalidate();\n }", "function clearRedirect() {\n redirectState = null;\n spLocalStorage.removeItem(redirectStateKey);\n }", "clearDataFromLocalStorage() {\n localStorage.db = [];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
implementation of District Population Chart
function createDistrictPopulationChart(district_data_object){ // let try_var = district_data_object; // console.log(try_var); //array for chart dataset usage let district_array = district_data_object["Districts"]; let male_array = []; let female_array = []; //remove district array from the district data object let data_for_chart_use = district_data_object; delete data_for_chart_use["Districts"]; //convert the object to and arry data_for_chart_use = Object.values(data_for_chart_use); //add values to male and female array for(let i = 0; i < data_for_chart_use.length; i++){ male_array.push(data_for_chart_use[i].male); female_array.push(data_for_chart_use[i].female); } // feed chart with data district_chart_data = new Chart(district_chart_ctx, { type: 'bar', data: { labels: district_array, datasets: [ { label: "Male", backgroundColor: "#519872", data: male_array }, { label: "Female", backgroundColor: "#B1D2C2", data: female_array } ] }, options: { title: { display: true, text: 'Population growth (millions)' } } }); }
[ "function undergradbyCollegeChart() {\r\n\t\t\tvar undergradData = getundergradbyCollegeChart(ualbyCollege);\r\n\r\n\t\t\tvar data = google.visualization.arrayToDataTable([\r\n\t\t\t\t['College', 'Student Enrollment'],\r\n\t\t\t\t['College of Arts and Sciences', undergradData.artsAndScience],\r\n\t\t\t\t['College of Bible', undergradData.bible],\r\n\t\t\t\t['College of Business', undergradData.business],\r\n\t\t\t\t['College of Education', undergradData.education]\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' },\r\n\t\t\t\tis3D: true\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.visualization.PieChart(document.getElementById('undergradAdultByCollegeChart'));\r\n\t\t\tchart.draw(data, options);\r\n\r\n\t\t}", "function createPie(provinceName, peopleData) {\n var dataset = [];\n var percentage = [];\n var peopleNum; //提升变量为了检测是否为无数据,以便于不显示饼图\n peopleData.forEach(function (d, i) {\n if (d.provinceName == provinceName) {\n peopleNum = d.peopleNum\n var menNum = parseInt(d.menNum)\n var womenNum = parseInt(d.womenNum)\n dataset.push(womenNum);\n dataset.push(menNum);\n var menPercentage = (menNum / (menNum + womenNum) * 100).toFixed(2) + \"%\";\n var womenPercentage = (womenNum / (menNum + womenNum) * 100).toFixed(2) + \"%\";\n percentage.push(womenPercentage);\n percentage.push(menPercentage);\n }\n });\n var height = 200;\n var width = 200;\n var pie = d3.layout.pie();\n var pieData = pie(dataset);\n var outerRadius = 100; //外半径\n var innerRadius = 0; //内半径\n\n d3.selectAll(\".svg-area\").remove();\n var svg = d3.select(\".pie\")\n .append(\"svg\")\n .attr(\"class\", \"svg-area\")\n .attr(\"width\", width)\n .attr(\"height\", height);\n var arc = d3.svg.arc()\n .innerRadius(innerRadius)\n .outerRadius(outerRadius)\n var arcs = svg.selectAll(\"g\")\n .data(pieData)\n .enter()\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\")\n\n arcs.append(\"path\")\n .attr(\"fill\", function (d, i) {\n if (i == 0) {\n return \"rgb(253, 177, 242)\";\n } else {\n return \"rgb(163, 208, 241)\";\n }\n\n })\n .attr(\"d\", function (d) {\n return arc(d);\n });\n arcs.append(\"text\")\n .attr(\"transform\", function (d) {\n return \"translate(\" + arc.centroid(d) + \")\";\n })\n .attr(\"text-anchor\", \"middle\")\n .text(function (d, i) {\n return percentage[i];\n })\n if (peopleNum == 0) { //无数据时候把饼图隐藏\n d3.selectAll(\".svg-area\").remove();\n }\n\n}", "function styleDistrict() {\n return {\n fillColor: randomPresetColor(pastelPresets),\n weight: districtStyle.weight,\n opacity: districtStyle.opacity,\n color: districtStyle.color,\n fillOpacity: districtStyle.fillOpacity,\n };\n}", "function statepensionChart(statePensionAge){\n var value=0;\n var statePensionElem=new Array();\n var statePensionLine=new Array();\n\n //Before State Pension Year value = 0\n if($rootScope.stateValue==true){\n\n for (var i = parseInt($rootScope.about_ret); i <= parseInt($rootScope.timeline.upto); i++) {\n\n var labelPension = 'State Pension';\n if(statePensionAge.statePensionAge <= i){\n value=parseInt(statePensionAge.statePensionYear);\n }else{\n value=0;\n }//0 if sires less then State Pension\n //create chart Array\n //statePensionElem=[i,value];\n statePensionElem={\"x\":i,\"y\":value};\n statePensionLine.push(statePensionElem);\n }//foreach years\n }//Include\n //assemble return\n var statePensionChart={\n 'key':'State Pension',\n 'values':statePensionLine,\n 'color':'#8d8d8d',\n 'annualy':parseInt(statePensionAge.statePensionYear)\n }\n\n\n return statePensionChart;\n}", "function undergradAdultDataChart() {\r\n\t\t\tvar undergradData = getUndergradAdultData(galbyClassAndGen);\r\n\t\t\tvar maleUGData = undergradData[0];\r\n\t\t\tvar femaleUGData = undergradData[1];\r\n\r\n\t\t\tvar undergradAdultChart = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Male', 'Female', { role: 'annotation' }],\r\n\t\t\t\t['Freshman', maleUGData.freshman, femaleUGData.freshman, ''],\r\n\t\t\t\t['Sophomore', maleUGData.sophomore, femaleUGData.sophomore, ''],\r\n\t\t\t\t['Junior', maleUGData.junior, femaleUGData.junior, ''],\r\n\t\t\t\t['Senior', maleUGData.senior, femaleUGData.senior, '']\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' },\r\n\t\t\t\tisStacked: true\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('undergradAdultByClassificatioinGenderChart'));\r\n\t\t\tchart.draw(undergradAdultChart, google.charts.Bar.convertOptions(options));\r\n\t\t}", "function fn_concat (barChartGroup, geogroupArray, this_dim) {\n objArray = [];\n count = 0; //for gap id labels\n \n for (idx=0; idx < geogroupArray.length; idx++) { \n //Extract data by region\n ghg_extract = sortByRegion(geogroupArray[idx]);\n\n //Sort by this_dim in descending order\n ghg_extract.sort((a, b) => d3.descending(a[this_dim], b[this_dim]));\n\n //Rotterdam, Kaohsiung, Taoyuan, Lagos -- special cases that do not fit on scale\n //Reduce bar height and indicate true value graphically on the chart\n if (geogroupArray[idx] === \"groupEurope\" && this_dim === \"per capita\") { \n var selectedCity = data_GHG.find(x => x.city === \"Rotterdam\");\n \n //Store actual value for later display. Store only once!!!\n if (storeFlagCap === 0) {\n rotterdamEmissionsPerCap = formatDecimalSci(selectedCity[label_dataPerCap]);\n storeFlagCap = 1;\n }\n \n //Assign a smaller value FOR SCALE PURPOSES ONLY\n selectedCity[label_dataPerCap] = 11;\n } else if (geogroupArray[idx] === \"groupAsia\" && this_dim === \"per GDP\") { \n var selectedCity1 = data_GHG.find(x => x.city === \"Kaohsiung\");\n var selectedCity2 = data_GHG.find(x => x.city === \"Taoyuan\"); \n\n //Store actual value for later display.Store only once!!!\n if (storeFlagGDP === 0) {\n kaohsiungEmissionsPerGDP = formatDecimalSci(selectedCity1[label_dataPerGDP]);\n taoyuanEmissionsPerGDP = formatDecimalSci(selectedCity2[label_dataPerGDP]); \n storeFlagGDP = 1;\n }\n \n //Assign a smaller value FOR SCALE PURPOSES ONLY\n selectedCity1[label_dataPerGDP] = 0.114;\n selectedCity2[label_dataPerGDP] = 0.114; \n\n } else if (geogroupArray[idx] === \"groupAfrica\" && this_dim === \"per GDP\") {\n var selectedCity = data_GHG.find(x => x.city === \"Lagos\");\n\n //Store actual value for later display.Store only once!!!\n if (storeFlagGDPAfrica === 0) {\n lagosEmissionsPerGDP = formatDecimalSci(selectedCity[label_dataPerGDP]);\n storeFlagGDPAfrica = 1;\n } \n\n //Assign a smaller value FOR SCALE PURPOSES ONLY\n selectedCity[label_dataPerGDP] = 0.23;\n }\n\n //Concatenate with a gap obj in between\n if (idx % 2 == 0) {\n objArray = objArray.concat(ghg_extract);\n } else {\n objArray = objArray.concat(\n [{ \"city\":\"gap\" + barChartGroup + count, \n \"region\": barChartGroup,\n \"per capita\":0, \n \"per GDP\": 0 }]\n );\n count++;\n }\n } //.for\n\n //save cityOrder\n if (this_dim === \"per capita\") {\n if (barChartGroup === \"groupUSAAsia\") cityOrder_row1 = objArray.map(x => x[\"city\"]);\n else cityOrder_row2 = objArray.map(x => x[\"city\"]);\n }\n\n\n return objArray;\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}", "function generate3WComponent(config,data,geom){ \n \n $('#title').html(config.title);\n $('#description').html(config.description);\n\n var whoChart = dc.rowChart('#hdx-3W-who');\n var whatChart = dc.rowChart('#hdx-3W-what');\n var whereChart = dc.leafletChoroplethChart('#hdx-3W-where');\n var whereChart2 = dc.leafletChoroplethChart('#hdx-3W-where2');\n var statusChart = dc.rowChart('#hdx-3W-status');\n\n var cf = crossfilter(data);\n\n var whoDimension = cf.dimension(function(d){ return d[config.whoFieldName]; });\n var whatDimension = cf.dimension(function(d){ return d[config.whatFieldName]; });\n var whereDimension = cf.dimension(function(d){ return d[config.whereFieldName]; });\n var whereDimension2 = cf.dimension(function(d){ return d[config.whereFieldName2]; });\n var statusDimension = cf.dimension(function(d){ return d[config.statusFieldName]; });\n\n var whoGroup = whoDimension.group().reduceSum(function(d) {return d.Nov_Change ;});\n var whatGroup = whatDimension.group();\n var whereGroup = whereDimension.group().reduceSum(function(d) {return d.Nov_Change ;});\n var whereGroup2 = whereDimension2.group().reduceSum(function(d) {return d.Nov_Change ;});\n var statusGroup = statusDimension.group().reduceSum(function(d) {return d.Nov_Change ;});\n var all = cf.groupAll();\n\n whoChart.width($('#hdx-3W-who').width()).height(200)\n .dimension(whoDimension)\n .group(whoGroup)\n .elasticX(true)\n .data(function(group) {\n return group.top(5);\n })\n .labelOffsetY(13)\n .colors(config.colors)\n .colorDomain([0,7])\n .colorAccessor(function(d, i){return 2;})\n .xAxis().ticks(5);\n\n whatChart.width($('#hdx-3W-what').width()).height(250)\n .dimension(whatDimension)\n .group(whatGroup)\n .elasticX(true)\n .data(function(group) {\n return group.top(15);\n })\n .labelOffsetY(13)\n .colors(config.colors)\n .colorDomain([0,7])\n .colorAccessor(function(d, i){return 0;})\n .xAxis().ticks(5);\n \n statusChart.width($('#hdx-3W-status').width()).height(200)\n .dimension(statusDimension)\n .group(statusGroup)\n .elasticX(true)\n .data(function(group) {\n return group.top(5);\n }) \n .labelOffsetY(13)\n .colors(config.colors)\n .colorDomain([0,7])\n .colorAccessor(function(d, i){return 6;})\n .xAxis().ticks(5); \n\n dc.dataCount('#count-info')\n .dimension(cf)\n .group(all);\n \n \n whereChart2.width($('#hxd-3W-where2').width()).height(100)\n .dimension(whereDimension2)\n .group(whereGroup2)\n .center([35.8, 38])\n .zoom(7) \n .geojson(geom)\n .colors(['#CCCCCC', config.colors[0],config.colors[1], config.colors[2], config.colors[3]])\n .colorDomain([0, 1, 2, 3, 4])\n .colorAccessor(function (d) {\n if(d>10000){\n return 4;\n } else if (d>3000) {\n return 3;\n } else if (d>1000) {\n return 2;\n } else if (d>1) {\n return 1;\n }\n else {\n return 0;\n }\n }) \n .featureKeyAccessor(function(feature){\n return feature.properties[config.joinAttribute];\n });\n \n whereChart.width($('#hxd-3W-where').width()).height(100)\n .dimension(whereDimension)\n .group(whereGroup)\n .center([35.8, 38])\n .zoom(7) \n .geojson(geom)\n .colors(['#CCCCCC', config.colors[4],config.colors[5], config.colors[6], config.colors[7]])\n .colorDomain([0, 1, 2, 3, 4])\n .colorAccessor(function (d) {\n if(d>4000){\n return 4;\n } else if (d>1000) {\n return 3;\n } else if (d>500) {\n return 2;\n }\n else if (d>1) {\n return 1;\n }\n else {\n return 0;\n }\n }) \n .featureKeyAccessor(function(feature){\n return feature.properties[config.joinAttribute];\n });\n \n \n dc.renderAll();\n \n var g = d3.selectAll('#hdx-3W-who').select('svg').append('g');\n \n g.append('text')\n .attr('class', 'x-axis-label')\n .attr('text-anchor', 'middle')\n .attr('x', $('#hdx-3W-who').width()/2)\n .attr('y', 510)\n .text('XXX1');\n\n var g = d3.selectAll('#hdx-3W-what').select('svg').append('g');\n \n g.append('text')\n .attr('class', 'x-axis-label')\n .attr('text-anchor', 'middle')\n .attr('x', $('#hdx-3W-what').width()/2)\n .attr('y', 250)\n .text('XXX2');\n\n var g = d3.selectAll('#hdx-3W-status').select('svg').append('g');\n\n g.append('text')\n .attr('class', 'x-axis-label')\n .attr('text-anchor', 'middle')\n .attr('x', $('#hdx-3W-status').width()/2)\n .attr('y', 160)\n .text(''); \n\n}", "function displayLineGraph_DomConsumption(Data, countryName) {\n\n // Filter Consumption Data to return only data for matching country name\n let consumptionData = Data.filter(consumption => consumption.Attribute == \"Domestic Consumption\");\n let countryConsumption = consumptionData.filter(country => country.Country_Name == countryName);\n countryConsumption = countryConsumption.filter(country => country.Year >= 1990);\n\n // Filter Roast,Ground Consumption to return only data for matching country name\n let roastData = Data.filter(consumption => consumption.Attribute == \"Rst,Ground Dom. Consum\");\n let roastConsumption = roastData.filter(country => country.Country_Name == countryName);\n roastConsumption = roastConsumption.filter(country => country.Year >= 1990);\n\n // Filter Soluble Consumption Data to return only data for matching country name\n let solubleData = Data.filter(consumption => consumption.Attribute == \"Soluble Dom. Cons.\");\n let solubleConsumption = solubleData.filter(country => country.Country_Name == countryName);\n solubleConsumption = solubleConsumption.filter(country => country.Year >= 1990);\n\n\n let yearsC = [];\n let consumptionValues = [];\n\n for (let i=0; i < countryConsumption.length; i++) {\n yearsC.push(countryConsumption[i].Year);\n consumptionValues.push(countryConsumption[i].Value);\n }\n\n let yearsRG = [];\n let roastValues = [];\n\n for (let i=0; i < roastConsumption.length; i++) {\n yearsRG.push(roastConsumption[i].Year);\n roastValues.push(roastConsumption[i].Value);\n }\n\n let yearsS = [];\n let solubleValues = [];\n\n for (let i=0; i < solubleConsumption.length; i++) {\n yearsS.push(solubleConsumption[i].Year);\n solubleValues.push(solubleConsumption[i].Value);\n }\n\n\n\n\n // Plot Consumption data points\n let lineData_cons = {\n x: yearsC,\n y: consumptionValues,\n line: { color: \"gray\"},\n name: \"Total Domestic Consumption\",\n type: \"scatter\",\n mode: \"lines+markers\"\n };\n \n\n // Plot Roast Consumption points\n let lineData_roast = {\n x: yearsRG,\n y: roastValues,\n line: { color: \"brown\"},\n name: \"Roast, Ground\",\n type: \"line\"\n };\n\n // Plot Soluble Consumption points\n let lineData_soluble = {\n x: yearsS,\n y: solubleValues,\n line: { color: \"black\"},\n name: \"Soluble\",\n type: \"line\"\n };\n\n\n // // Place both data sets together in array\n let lineData2 = [lineData_cons, lineData_roast, lineData_soluble]; \n\n // Set title for line graph and x and y axes\n let lineLayout2 = {\n title: countryName + \" - Coffee Domestic Consumption Total, Roast-Ground and Soluble Separate 1990 to 2020\",\n xaxis: { title: \"Years\" },\n yaxis: { title: \"Domestic Consumption (1000 * 60 Kg Bags)\" }\n };\n \n // Use plotly to display line graph at div with lineData and lineLayout\n Plotly.newPlot('consLine', lineData2, lineLayout2);\n}", "function showAccidentsRoad(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"road_type\"));\n let totalAccByRoad = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n\n dc.pieChart(\"#rd-type-split\")\n .width(320)\n .height(360)\n .slicesCap(8)\n .innerRadius(95)\n .dimension(dim)\n .group(totalAccByRoad)\n .transitionDuration(500)\n .renderLabel(true)\n .legend(dc.legend().x(85).y(125).itemHeight(13).gap(5))\n .title(function(d) {\n return d.key + \": \" + ((d.value / d3.sum(totalAccByRoad.all(),\n function(d) { return d.value; })) * 100).toFixed(2) + \"%\";\n })\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"text.pie-slice\").text(function(d) {\n if (dc.utils.printSingleValue(\n (d.endAngle - d.startAngle) /\n (2 * Math.PI) * 100) >= 5) {\n return dc.utils.printSingleValue(\n (d.endAngle - d.startAngle) /\n (2 * Math.PI) * 100) + \"%\";\n }\n });\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 320 360\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"fill\", \"#ffffff\")\n .text(\"\")\n .append(\"tspan\")\n .text(function(d) { return d.name; })\n .append(\"tspan\")\n .attr(\"x\", 150)\n .attr(\"text-anchor\", \"end\")\n .text(function(d) {\n return d.data.toLocaleString();\n });\n });\n}", "function add_bar_chart(props) {\n console.log(props);\n\n const data = [ {'origin': 'asian',\n 'percent': props.asian_percent},\n {'origin': 'black',\n 'percent': props.black_percent},\n {'origin': 'hispanic',\n 'percent': props.hispanic_percent},\n // {'origin': 'native american',\n // 'percent': props.native_percent},\n // {'origin': 'pacific islander',\n // 'percent': props.pacific_percent},\n {'origin': 'white',\n 'percent': props.white_percent},\n {'origin': 'other',\n 'percent': props.other_percent + props.native_percent + props.pacific_percent},\n ];\n\n // Remove previous svg element, if any\n d3.select(\".tooltip\")\n .selectAll(\"svg\")\n .remove();\n\n // Dimensions\n const m = {top: 10, right: 5, bottom: 5, left: 5},\n p = {top: 0, right: 15, bottom: 0, left: 33},\n width = 150 - m.left - m.right,\n height = 110 - m.top - m.bottom;\n\n // Initialize svg element\n const popup_svg = d3.select(\".tooltip\")\n .append(\"svg\")\n .attr(\"width\", width + m.left + m.right)\n .attr(\"height\", height + m.top + m.bottom)\n .append('g')\n .attr('transform', \"translate(\" + m.left + \",\" + m.top + \")\");\n\n\n // Scales\n const color = d3.scaleOrdinal([\"#98abc5\", \"#8a89a6\", \"#7b6888\", \"#6b486b\", \"#a05d56\", \"#d0743c\", \"#ff8c00\"]);\n \n const x = d3.scaleLinear()\n .rangeRound([0, width - p.left - p.right])\n .domain([0, 1]);\n\n const y = d3.scaleBand()\n .rangeRound([0, height])\n .paddingInner(0.2)\n .domain(data.map(d => d.origin));\n\n const yAxis = d3.axisLeft(y).tickSize(0);\n\n const format = d3.format(\".0%\");\n\n // y-Axis\n popup_svg.append(\"g\")\n .attr(\"class\", \"axis axis-y\")\n .call(yAxis)\n .attr('transform', \"translate(\" + p.left + \",0)\");\n\n // Bar + percent text group\n const bars = popup_svg.selectAll('g.bar')\n .data(data)\n .enter()\n .append('g')\n .attr('class', 'bar')\n .attr('transform', d => ('translate(' + p.left + ',' + y(d.origin) +')'));\n\n // Bars\n bars.append('rect')\n .attr('height', y.bandwidth())\n .attr('width', d => x(d.percent))\n .attr('fill', (d, i) => color(i))\n\n // Percent text\n bars.append('text')\n .attr('class', 'value')\n .attr('x', d => x(d.percent))\n .attr('y', d => (y.bandwidth() / 2))\n .attr('dx', 2)\n .attr('dy', '0.35em')\n .text(d => format(d.percent))\n \n }", "function gradEnrollmentChart() {\r\n\t\t\tvar gradData = getGradData(gabyClassAndGen);\r\n\t\t\tvar maleGradData = gradData[0];\r\n\t\t\tvar femaleGradData = gradData[1];\r\n\r\n\t\t\tvar chartData = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Type', 'Male', 'Female', { role: 'annotation' }],\r\n\t\t\t\t['Master', maleGradData.master, femaleGradData.master, ''],\r\n\t\t\t\t['Docotorate', maleGradData.doctorate, femaleGradData.doctorate, ''],\r\n\t\t\t\t['JSL', maleGradData.jsl, femaleGradData.jsl, '']\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' },\r\n\t\t\t\tisStacked: true\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('gradChart'));\r\n\r\n\t\t\tchart.draw(chartData, google.charts.Bar.convertOptions(options));\r\n\t\t}", "function showLandLockedPercent(ndx, element, colorScale) {\n //Creating custom reduce to display climates.\n var countryDim = ndx.dimension(dc.pluck(\"Climate\"));\n var climate = countryDim.group().reduce(\n function(p, v) {\n p.count++;\n if (v.Climate == 1 || v.Climate == 1, 5) {\n p.climateOne++;\n return p;\n }\n else if (v.Climate == 2 || v.Climate == 2, 5) {\n p.climateTwo++;\n return p;\n }\n else if (v.Climate == 3 || v.Climate == 3, 5) {\n p.climateThree++;\n return p;\n }\n else if (v.Climate == 4 || v.Climate == 4, 5) {\n p.climateFour++;\n return p;\n }\n },\n function(p, v) {\n p.count--;\n if (v.Climate == 1 || v.Climate == 1, 5) {\n p.climateOne--;\n return p;\n }\n else if (v.Climate == 2 || v.Climate == 2, 5) {\n p.climateTwo--;\n return p;\n }\n else if (v.Climate == 3 || v.Climate == 3, 5) {\n p.climateThree--;\n return p;\n }\n else if (v.Climate == 4 || v.Climate == 4, 5) {\n p.climateFour--;\n return p;\n }\n },\n function() {\n return { climateOne: 0, climateTwo: 0, climateThree: 0, climateFour: 0, count: 0 };\n }\n\n\n );\n dc.pieChart(element)\n .height(330)\n .radius(100)\n .transitionDuration(1000)\n .dimension(countryDim)\n .group(climate)\n .valueAccessor(function(d) {\n return d.value.climateOne;\n })\n .colors(colorScale);\n}", "function displayLineGraph_Production(Data, countryName) {\n\n // Filter production Data to return only data for matching country name\n let productionData = Data.filter(production => production.Attribute == \"Production\");\n let countryProduction = productionData.filter(country => country.Country_Name == countryName);\n countryProduction = countryProduction.filter(country => country.Year >= 1990);\n\n // Filter Arabica Data to return only data for matching country name\n let ArabicaData = Data.filter(production => production.Attribute == \"Arabica Production\");\n let ArabicaProduction = ArabicaData.filter(country => country.Country_Name == countryName);\n ArabicaProduction = ArabicaProduction.filter(country => country.Year >= 1990);\n\n // Filter Robusta Data to return only data for matching country name\n let RobustaData = Data.filter(production => production.Attribute == \"Robusta Production\");\n let RobustaProduction = RobustaData.filter(country => country.Country_Name == countryName);\n RobustaProduction = RobustaProduction.filter(country => country.Year >= 1990);\n\n\n\n\n let yearsP = [];\n let productionValues = [];\n\n for (let i=0; i < countryProduction.length; i++) {\n // Extract years and production values from data \n yearsP.push(countryProduction[i].Year);\n productionValues.push(countryProduction[i].Value);\n }\n\n let yearsA = [];\n let ArabicaValues = [];\n\n for (let i=0; i < ArabicaProduction.length; i++) {\n // Extract years and production values from data \n yearsA.push(ArabicaProduction[i].Year);\n ArabicaValues.push(ArabicaProduction[i].Value);\n }\n\n let yearsR = [];\n let RobustaValues = [];\n\n for (let i=0; i < RobustaProduction.length; i++) {\n // Extract years and production values from data \n yearsR.push(RobustaProduction[i].Year);\n RobustaValues.push(RobustaProduction[i].Value);\n }\n\n\n\n\n // Plot Production data points\n let lineData_prod = {\n x: yearsP,\n y: productionValues,\n name: \"Total Production\",\n type: \"scatter\",\n mode: \"lines+markers\"\n };\n \n\n // Plot Arabica Production points\n let lineData_arabica = {\n x: yearsA,\n y: ArabicaValues,\n color: \"orange\",\n name: \"Arabica Production\",\n type: \"line\"\n };\n\n // Plot Robusta Production points\n let lineData_robusta = {\n x: yearsR,\n y: RobustaValues,\n color: \"green\",\n name: \"Robusta Production\",\n type: \"line\"\n };\n\n\n // // Place both data sets together in array\n let lineData = [lineData_prod, lineData_arabica, lineData_robusta]; // , lineData_predicted\n\n // Set title for line graph and x and y axes\n let lineLayout = {\n title: countryName + \" - Coffee Production Total, Arabica and Robusta Separate 1990 to 2020\",\n xaxis: { title: \"Years\" },\n yaxis: { title: \"Production (1000 * 60 Kg Bags)\" }\n };\n \n // Use plotly to display line graph at div ID \"line2\" with lineData and lineLayout\n Plotly.newPlot('prodLine', lineData, lineLayout);\n}", "function gradEnrollChart() {\r\n\t\t\tvar gradData = getGradEnrollmentCout(studentEnrollment);\r\n\t\t\tvar count = gradData[1];\r\n\t\t\tvar year = gradData[0];\r\n\r\n\t\t\tvar chartData = google.visualization.arrayToDataTable([\r\n\t\t\t\t['Year', 'Enrollment'],\r\n\t\t\t\t[year.year5, count.year5],\r\n\t\t\t\t[year.year4, count.year4],\r\n\t\t\t\t[year.year3, count.year3],\r\n\t\t\t\t[year.year2, count.year2],\r\n\t\t\t\t[year.year1, count.year1]\r\n\t\t\t]);\r\n\r\n\t\t\tvar options = {\r\n\t\t\t\tchartArea: { width: '100%', height: '100%' }\r\n\t\t\t};\r\n\r\n\t\t\tvar chart = new google.charts.Bar(document.getElementById('gradEnrollChart'));\r\n\t\t\tchart.draw(chartData, google.charts.Bar.convertOptions(options));\r\n\t\t}", "function drawChart() {\n\n let data = google.visualization.arrayToDataTable([\n ['City', 'Number of Employees'],\n ['Boston', boston],\n ['Orlando', orlando],\n ['Chicago', chicago],\n ['San Francisco', sanfran]\n ]);\n\n let options = {\n title: 'Number & Percentage of Employees',\n pieHole: 0.5,\n pieSliceText: 'value'\n };\n\n let chart = new google.visualization.PieChart(document.getElementById('donutchart'));\n chart.draw(data, options);\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}", "function SVGStackedRowChart() {\n}", "function drawDiffGexp(i) {\n var gexp = getCol(dataPro,i)\n var group = dataPro.map(function(d) { return d.group })\n gexp.map(function(d, i) { d.group = group[i] })\n\n var g = document.getElementById('gexp_panel2'),\n\twindowWidth = g.clientWidth,\n\twindowHeight = g.clientHeight;\n\n var margin = {top: 30, right: 0, bottom: 30, left: 30},\n\twidth = windowWidth - margin.left - margin.right,\n\theight = windowHeight - margin.top - margin.bottom;\n\n var chart1;\n chart1 = makeDistroChart({\n\tdata: gexp,\n\txName:'group',\n\tyName:'value',\n//\taxisLabels: {xAxis: 'Group', yAxis: 'Values'},\n\tselector:\"#gexp-chart-distro2\",\n\tsvg:\"gexp-chart-distro2-svg\", \n\tchartSize:{height:height, width:width},\n\tmargin:margin,\n\tconstrainExtremes:true});\n chart1.renderBoxPlot();\n chart1.renderDataPlots();\n chart1.renderNotchBoxes({showNotchBox:false});\n chart1.renderViolinPlot({showViolinPlot:false});\n \n var pt = document.getElementById(\"gexp_plottype\").value;\n if(pt == \"box_plot\") {\n\tchart1.boxPlots.show({reset:true});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"notched_box_plot\") {\n\tchart1.notchBoxes.show({reset:true});chart1.boxPlots.show({reset:true, showBox:false,showOutliers:true,boxWidth:20,scatterOutliers:true});chart1.violinPlots.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"violin_plot\") {\t \n\tchart1.violinPlots.show({reset:true, resolution:12});chart1.boxPlots.show({reset:true, showWhiskers:false,showOutliers:false,boxWidth:10,lineWidth:15,colors:['#555']});chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"bean_plot\") {\t \n\tchart1.violinPlots.show({reset:true, width:100, resolution:12});chart1.dataPlots.show({showBeanLines:true,beanWidth:15,showPlot:false,colors:['#555']});chart1.boxPlots.hide();chart1.notchBoxes.hide()\n }\n if(pt == \"beeswam_plot\") {\t \t \n\tchart1.dataPlots.show({showPlot:true, plotType:'beeswarm',showBeanLines:false, colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n if(pt == \"scatter_plot\") {\t \n\tchart1.dataPlots.show({showPlot:true, plotType:40, showBeanLines:false,colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
/ The Rules class ///////////////////////////////////////////////////////////
function Rules() { var rules = this; Rules.METHODS.forEach(function (name) { rules[name] = function () {}; }); }
[ "function genRule() {\n\t//Rule is an object storing these three properties.\n\tvar rule = {\n\t\trType,\n\t\trNumber,\n\t\trColor,\n\t\tcompareColor: function(item) {\n\t\t\t\treturn ((rColor == item.color) || (rColor == 0));\n\t\t},\n\t\tcompareNumber: function(item) {\n\t\t\t\treturn ((rNumber == item.number) || (rNumber == 0));\n\t\t},\n\t};\n\n\tgenerateRule();\n\n\tthis.rType=ruleType;\n\tthis.rNumber=ruleNumber;\n\tthis.rColor=ruleColor;\n\t\n\treturn rule;\n}", "function RulesEvaluationEngine(ruleset,askcallback,solcallback,logcallback,withSteps)\r\n{\r\n // Current question\r\n\r\n this.__currentQuestion = -1;\r\n \r\n // Stack evaluation\r\n \r\n this.__stack = null;\r\n \r\n if (withSteps){\r\n this.__stack = new Array();\r\n }\r\n \r\n // Ask callback\r\n this.__askcallback = askcallback; \r\n\r\n // Questions\r\n this.__questions = new Array();\r\n for (var i=0;i<ruleset.questions.length;i++){\r\n this.__questions[i] = new Question(ruleset.questions[i].qid,\r\n\t ruleset.questions[i].qtext,\r\n\t\t\t\t\t\t\t\t\t\truleset.questions[i].qdesc,\r\n\t\t\t\t\t\t\t\t\t\truleset.questions[i].qtype,\r\n\t\t\t\t\t\t\t\t\t\truleset.questions[i].info);\r\n }\r\n \r\n // Facts\r\n this.__facts = new Array();\r\n for(var i=0;i<ruleset.facts.length;i++){\r\n this.__facts[i] = new Fact(ruleset.facts[i].fid,ruleset.facts[i].ftext); \r\n }\r\n \r\n // Rules\r\n \r\n this.__rules = new Array();\r\n for(var i=0;i<ruleset.rules.length;i++){\r\n this.__rules[i] = new Rule(ruleset.rules[i].rid,\r\n\t ruleset.rules[i].cond,\r\n\t\t\t\t\t\t ruleset.rules[i].iftrue,\r\n\t\t\t\t\t\t ruleset.rules[i].iffalse,\r\n\t\t\t\t\t\t\t this.__askcallback,\r\n\t\t\t\t\t\t\t this.__stack); \r\n }\r\n \r\n // Starting questions\r\n \r\n this.__askfirst = new Array();\r\n this.__askfirst = ruleset.askfirst;\r\n \r\n // Starting facts\r\n \r\n this.__statefirst = new Array();\r\n this.__statefirst = ruleset.statefirst;\r\n \r\n // Solution\r\n\r\n this.__solution = new Array();\r\n this.__solutionFound = false;\r\n this.__solutionCallback = solcallback;\r\n this.__logicaCallback = logcallback;\r\n}", "visitModel_rules_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function drawRule() {\n\t\n\tif (ruleImage != null) {\n\t\t\n\t\tswitch (ruleType) {\n\t\t\tcase 1:\n\t\t\t\tctx.drawImage(ruleImage, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/20, canvas.width/10, canvas.height/4);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tctx.drawImage(ruleImage, canvas.width / 100 * 45, canvas.height/20 + canvas.height/20, canvas.width/10, canvas.height/4);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tctx.drawImage(ruleImage, canvas.width / 100 * 45, -canvas.height/30 + canvas.height/20, canvas.width/10, canvas.height/4);\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tctx.drawImage(ruleImage, canvas.width / 100 * 45, -canvas.height/10 + canvas.height/20, canvas.width/10, canvas.height/4);\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tctx.drawImage(ruleImage, canvas.width / 100 * 45, -canvas.height/6 + canvas.height/20, canvas.width/10, canvas.height/4);\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tctx.drawImage(ruleImage, canvas.width / 100 * 45, -canvas.height/9 + canvas.height/20, canvas.width/10, canvas.height/4);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}", "visitModel_rules_element(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function Rule(props) {\n return __assign({ Type: 'AWS::WAFRegional::Rule' }, props);\n }", "validate()\n {\n //Reset errors\n this._errors.length = 0;\n //Check if rules are valid\n for (const rule of this.getRules())\n {\n if (!this.isRuleValid(rule))\n {\n this._errors.push(new Error(rule.toString() + ' is an invalid rule'));\n }\n }\n //Check if there is a startVariable, if at least one rule has it on the LHS, and it is in the variables\n if (!this.getStartVariable())\n {\n this._errors.push(new Error('No start variable'));\n }\n else\n {\n let startVariableOnLHS = false;\n for (const rule of this.getRules())\n {\n if (rule.getLHS() == this.getStartVariable())\n {\n startVariableOnLHS = true;\n }\n }\n if (!startVariableOnLHS)\n {\n this._errors.push(new Error('No rule where startVariable is on the LHS'));\n }\n }\n if (!this.hasVariable(this.getStartVariable()))\n {\n this._errors.push(new Error('Start Variable isn\\'t in the set of variables'));\n }\n\n //Check that there is no intersection between terminals and variables\n let intersection = new Set([...this.getVariables()].filter(x => this.getTerminals().has(x)));\n if (intersection.size > 0)\n {\n this._errors.push(new Error('The set of Terminals and Variables should be disjoint'));\n }\n\n //TODO Check if its a proper CFG(unreachable symbols, cycles, etc)????? Ehhhh?\n return this.isValid();\n }", "function Ruler(rules){\n if (!(this instanceof Ruler)) return new Ruler(rules);\n this.stack = [];\n if (Array.isArray(rules)) {\n rules.forEach(function(obj){\n if ('function' == typeof obj) this.stack.push(obj)\n else this[obj.cmp](obj.path, obj.value)\n }, this);\n }\n\n this.path = null;\n this.parent = null;\n this.assertStack = [];\n}", "visitModel_rules_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function buildRules( languageNode )\n{\n\tvar contextList, contextNode, sRegExp, rootNode;\t\n\tvar rulePropList, rulePropNode, rulePropNodeAttributes, ruleList, ruleNode;\n\n\trootNode = languageNode.selectSingleNode(\"/*\");\n\t\n\t// first building keyword regexp\n\tbuildKeywordRegExp( languageNode );\t\n\t\n\tcontextList = languageNode.selectNodes(\"contexts/context\");\n\t// create regular expressions for context\n\tfor (contextNode = contextList.nextNode(); contextNode != null; contextNode = contextList.nextNode())\n\t{\n\t\tsRegExp = buildRuleRegExp( languageNode, contextNode );\n\t\t// add attribute\n\t\tcontextNode.setAttribute( \"regexp\", sRegExp );\t\n\t}\n}", "async run(rules, data) {\n \n try {\n \n data = await this.validate(data);\n return await this.runRules(rules, data);\n\n } catch(error) {\n return error\n }\n }", "rulesLoad(filename) {\n var fp = new File(filename, \"r\");\n if(!fp.open)\n error(\"fatal\", \"Unable to open grammar file \\\"\" + filename + \"\\\" for reading.\", \"SimpleGrammar.rulesLoad\");\n var tmp = fp.read();\n tmp = tmp.split(/\\n+/);\n var lines = [ ];\n while(tmp.length) {\n var line = tmp.shift().replace(/\\/\\/.*/g, \"\").trim();\n if(line.length)\n lines.push(line);\n }\n\n var nonterminal = /^\\[([^\\]]+)\\]/;\n var replacement = /^(([0-9]+):)?\\s*(.*)/;\n\n var currentNonterminal = null;\n var currentReplacements = [ ];\n\n for(var i = 0, match; i < lines.length; i++) {\n if(match = lines[i].match(nonterminal)) {\n if(currentNonterminal !== null && currentReplacements.length)\n this.ruleSet(currentNonterminal, currentReplacements);\n currentNonterminal = match[1];\n currentReplacements = [ ];\n\n } else if((match = lines[i].match(replacement)) && currentNonterminal !== null) {\n var weight = match[2] === undefined ? 1 : parseInt(match[2]);\n var str = this.textParse(match[3]);\n\n if(isNaN(weight) || weight < 1)\n error(\"fatal\", \"Invalid weight: \" + lines[i], \"SimpleGrammar.rulesLoad\");\n\n currentReplacements.push([str, weight]);\n }\n }\n if(currentNonterminal !== null && currentReplacements.length)\n this.ruleSet(currentNonterminal, currentReplacements);\n }", "function createSubrules(conditionsTree, conclusionTree) {\n\n\tfunction simplifyTrees(rule) {\n\t\tsyntaxTree.simplifyOperators(rule.conditionsTree)\n\t\tsyntaxTree.simplifyOperators(rule.conclusionTree)\n\t}\n\tcreateSubrulesFromConclusionTree()\n\tcreateSubrulesFromConditionsTree()\n\n\tfunction createSubrulesFromConclusionTree() {\n\t\tif (conclusionTree.type == 'OPERATOR')\n\t\t\thandleOperators()\n\t\telse if (conclusionTree.type == 'NOT')\n\t\t\thandleNot()\n\n\t\tfunction handleOperators() {\n\t\t\tif (conclusionTree.value == '+')\n\t\t\t\thandleAnd()\n\t\t\telse if (conclusionTree.value == '|')\n\t\t\t\thandleOr()\n\t\t\telse if (conclusionTree.value == '^')\n\t\t\t\thandleXor()\n\n\t\t\tfunction handleAnd() {\n\t\t\t\tconclusionTree.children.forEach(child => {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\tsimplifyTrees(rule)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t\tfunction handleOr() {\n\t\t\t\tconclusionTree.children.forEach(child => {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(child)\n\t\t\t\t\t})\n\n\t\t\t\t\tlet node = new Node({value: '+', type: 'OPERATOR'})\n\t\t\t\t\tnode.children = [syntaxTree.duplicateNode(conditionsTree)]\n\t\t\t\t\tconclusionTree.children.forEach(subchild => {\n\t\t\t\t\t\tif (subchild != child) {\n\t\t\t\t\t\t\tsubchild.parent = node\n\t\t\t\t\t\t\tnode.children.push(syntaxTree.negateNode(subchild))\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\trule.conditionsTree = node\n\t\t\t\t\tsimplifyTrees(rule)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t})\n\n\t\t\t\t// handle A|A in conclusion\n\t\t\t\tlet children = conclusionTree.children\n\t\t\t\tchildren.forEach(child => child.key = syntaxTree.createKeyFromNode(child))\n\t\t\t\tif (children.every(child => child.key == children[0].key)) {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(children[0])\n\t\t\t\t\t})\n\t\t\t\t\tsimplifyTrees(rule)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfunction handleXor() {\n\t\t\t\tconclusionTree.children.forEach(child => {\n\t\t\t\t\tlet rule1 = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.negateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\tlet node1 = new Node({value: '+', type: 'OPERATOR'})\n\t\t\t\t\tnode1.children = [rule1.conditionsTree, conclusionTree.children.find(el => el != child)]\n\t\t\t\t\tnode1.children.forEach(el => el.parent = node1)\n\t\t\t\t\trule1.conditionsTree = node1\n\n\t\t\t\t\tlet rule2 = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\tlet node2 = new Node({value: '+', type: 'OPERATOR'})\n\t\t\t\t\tnode2.children = [rule2.conditionsTree, syntaxTree.negateNode(conclusionTree.children.find(el => el != child))]\n\t\t\t\t\tnode2.children.forEach(el => el.parent = node2)\n\t\t\t\t\trule2.conditionsTree = node2\n\n\t\t\t\t\tsimplifyTrees(rule1)\n\t\t\t\t\tsimplifyTrees(rule2)\n\t\t\t\t\trules.push(rule1)\n\t\t\t\t\trules.push(rule2)\n\t\t\t\t\tcreateSubrules(rule1.conditionsTree, rule1.conclusionTree)\n\t\t\t\t\tcreateSubrules(rule2.conditionsTree, rule2.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tfunction handleNot() {\n\t\t\tlet node = syntaxTree.duplicateNode(conclusionTree.children[0])\n\n\t\t\tif (node.value == '+')\n\t\t\t\thandleAnd()\n\t\t\telse if (node.value == '|')\n\t\t\t\thandleOr()\n\t\t\telse if (node.value == '^')\n\t\t\t\thandleXor()\n\n\t\t\tfunction handleAnd() {\n\t\t\t\tnode.children.forEach(child => {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.negateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\tlet node1 = new Node({value: '+', type: 'OPERATOR'})\n\t\t\t\t\tnode1.children = [rule.conditionsTree, ...node.children.filter(el => el != child)]\n\t\t\t\t\tnode1.children.forEach(el => el.parent = node1)\n\t\t\t\t\trule.conditionsTree = node1\n\t\t\t\t\tsimplifyTrees(rule)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t\tfunction handleOr() {\n\t\t\t\tnode.children.forEach(child => {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\trule.conclusionTree = syntaxTree.negateNode(rule.conclusionTree)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t\tfunction handleXor() {\n\t\t\t\tnode.children.forEach(child => {\n\t\t\t\t\tlet rule1 = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\tlet node1 = new Node({value: '+', type: 'OPERATOR'})\n\t\t\t\t\tnode1.children = [rule1.conditionsTree, node.children.find(el => el != child)]\n\t\t\t\t\tnode1.children.forEach(el => el.parent = node1)\n\t\t\t\t\trule1.conditionsTree = node1\n\n\t\t\t\t\tlet rule2 = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.duplicateNode(conditionsTree),\n\t\t\t\t\t\tconclusionTree: syntaxTree.negateNode(child)\n\t\t\t\t\t})\n\t\t\t\t\tlet node2 = new Node({value: '+', type: 'OPERATOR'})\n\t\t\t\t\tnode2.children = [rule2.conditionsTree, syntaxTree.negateNode(node.children.find(el => el != child))]\n\t\t\t\t\tnode2.children.forEach(el => el.parent = node2)\n\t\t\t\t\trule2.conditionsTree = node2\n\n\t\t\t\t\tsimplifyTrees(rule1)\n\t\t\t\t\tsimplifyTrees(rule2)\n\t\t\t\t\trules.push(rule1)\n\t\t\t\t\trules.push(rule2)\n\t\t\t\t\tcreateSubrules(rule1.conditionsTree, rule1.conclusionTree)\n\t\t\t\t\tcreateSubrules(rule2.conditionsTree, rule2.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction createSubrulesFromConditionsTree() {\n\t\tif (conditionsTree.type == 'OPERATOR')\n\t\t\thandleOperators()\n\t\telse if (conditionsTree.type == 'NOT')\n\t\t\thandleNot()\n\n\t\tfunction handleOperators() {\n\t\t\tif (conditionsTree.value == '+')\n\t\t\t\thandleAnd()\n\t\t\telse if (conditionsTree.value == '|')\n\t\t\t\thandleOr()\n\t\t\telse if (conditionsTree.value == '^')\n\t\t\t\thandleXor()\n\n\t\t\tfunction handleAnd() {}\n\t\t\tfunction handleOr() {\n\t\t\t\tlet nodes = createNodeTreeCombinations(conditionsTree, 1)\n\n\t\t\t\tnodes.forEach(node => {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: node,\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(conclusionTree)\n\t\t\t\t\t})\n\t\t\t\t\tsimplifyTrees(rule)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t\tfunction handleXor() {}\n\t\t}\n\n\t\tfunction handleNot() {\n\t\t\tlet node = syntaxTree.duplicateNode(conditionsTree.children[0])\n\n\t\t\tif (node.value == '+')\n\t\t\t\thandleAnd()\n\t\t\telse if (node.value == '|')\n\t\t\t\thandleOr()\n\t\t\telse if (node.value == '^')\n\t\t\t\thandleXor()\n\n\t\t\tfunction handleAnd() {\n\t\t\t\tlet nodes = createNodeTreeCombinations(node, 1)\n\t\t\t\tnodes.forEach(node => {\n\t\t\t\t\tlet rule = new Rule({\n\t\t\t\t\t\tconditionsTree: syntaxTree.negateNode(node),\n\t\t\t\t\t\tconclusionTree: syntaxTree.duplicateNode(conclusionTree)\n\t\t\t\t\t})\n\t\t\t\t\tsimplifyTrees(rule)\n\t\t\t\t\trules.push(rule)\n\t\t\t\t\tcreateSubrules(rule.conditionsTree, rule.conclusionTree)\n\t\t\t\t})\n\t\t\t}\n\t\t\tfunction handleOr() {}\n\t\t\tfunction handleXor() {}\n\t\t}\n\n\t\tfunction createNodeTreeCombinations(tree, min) {\n\t\t\tlet indexLists = createIndexCombinations(tree.children.length, min)\n\t\t\treturn indexLists.map(indexList => {\n\t\t\t\tif (indexList.length == 1) return tree.children[indexList[0]]\n\t\t\t\tlet node = new Node({type: 'OPERATOR', value: '|'})\n\t\t\t\tlet children = indexList.map(i => {\n\t\t\t\t\tlet child = syntaxTree.duplicateNode(tree.children[i])\n\t\t\t\t\tchild.parent = node\n\t\t\t\t\treturn child\n\t\t\t\t})\n\t\t\t\tnode.children = children\n\t\t\t\treturn node\n\t\t\t})\n\t\t}\n\n\t\t/*\n\t\t * return a table of tables of indices to find all combinations for case A | B | C => D\n\t\t */\n\t\tfunction createIndexCombinations(total, min) {\n\t\t\tmin = min || 2\n\t\t\tlet combinations = []\n\t\t\tfor (let size = min; size < total; size++) {\n\t\t\t\tlet list = []\n\t\t\t\tfor (let i = 0; i < size; i++) {\n\t\t\t\t\tlist.push(i)\n\t\t\t\t}\n\t\t\t\tcombinations.push(list.slice())\n\t\t\t\twhile (increment(list, list.length - 1)) {\n\t\t\t\t\tcombinations.push(list.slice())\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn combinations\n\n\t\t\tfunction increment(list, index) {\n\t\t\t\tlet updated = false\n\t\t\t\tif (list[index] < total - 1) {\n\t\t\t\t\tlist[index]++\n\t\t\t\t\tfor (let i = 1; index + i < list.length; i++) {\n\t\t\t\t\t\tlist[index + i] = list[index] + i\n\t\t\t\t\t\tif (list[index + i] >= total) {\n\t\t\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\t\t\treturn increment(list, index - 1)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn false\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\treturn true\n\t\t\t\t} else if (index - 1 >= 0) {\n\t\t\t\t\treturn increment(list, index - 1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "clearRules()\n {\n this._rules.length = 0;\n }", "function setRuleType(x, n){\n\t\n\tswitch (x) {\n\t\tcase 1:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 2:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 3:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 4:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 5:\n\t\t\tcreateRules(n);\n\t\t\tbreak;\t\n\t\tcase 6:\n\t}\n\t\n}", "function assignObjectToRule(ObjectToAssign){\n //all properties of Rule class\n var RuleProperties = Object.getOwnPropertyNames((new Rule).toJSON());\n\n //check if the ObjectToAssign has all properties of a Rule\n RuleProperties.forEach(property => {\n //if a property is missing throw an error.\n if(!ObjectToAssign.hasOwnProperty(property)){\n throw \"rule object missing property: \"+ property;\n }\n });\n\n //assign object to rule\n var newRule = Object.assign(new Rule, ObjectToAssign);\n var assingedECSs = {};\n let ecskeys = Object.keys(newRule.ExistentialClauses);\n\n // assign all ecs in rule to ExistentialClause\n ecskeys.forEach(ecskey => {\n assingedECSs[ecskey] = assignObjectToECS(newRule.ExistentialClauses[ecskey], ecskey);\n });\n newRule.ExistentialClauses = assingedECSs;\n //check if each logical expression is valid\n //console.log(newRule.LogicalExpression);\n newRule.LogicalExpression = assignObjectToLogicalExpression(newRule.LogicalExpression);\n\n //return valid assinged rule object\n return newRule;\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 }", "validations(body,objectRules){\n console.log('body',body);\n let data = [];\n data['status'] = true;\n data['errors'] = [];\n let validation = [];\n for (const iterator of objectRules) {\n console.log('campo a evaluar ',iterator.field);\n //si empty es false, el campo es requerido\n if(!iterator.empty){\n if(body[`${iterator.field}`] == undefined || body[`${iterator.field}`] == null ){\n console.log(body[`${iterator.field}`],' es vacio');\n data.status = false;\n data['errors'].push({\n 'message': 'El campo '+iterator.field+' es requerido'\n });\n }\n }\n //se llama a funcion que valida el campo evaluado\n if(iterator.function != null && iterator.function !=undefined) {\n if (body[iterator.field] != null && body[iterator.field] != undefined){\n validation = this[iterator.function](body[iterator.field])\n if (!validation.status){\n data.status = false;\n data['errors'].push({\n 'message': validation.message\n });\n }\n }\n \n }\n }\n return data;\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 }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the training status of a person group (completed or ongoing). Training can be triggered by the Person Group Train Person Group API. The training will process for a while on the server side.. Http Method GET
personGroupGetPersonGroupTrainingStatusGet(queryParams, headerParams, pathParams) { const queryParamsMapped = {}; const headerParamsMapped = {}; const pathParamsMapped = {}; Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonGroupGetPersonGroupTrainingStatusGetQueryParametersNameMap)); Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonGroupGetPersonGroupTrainingStatusGetHeaderParametersNameMap)); Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonGroupGetPersonGroupTrainingStatusGetPathParametersNameMap)); return this.makeRequest('/persongroups/{personGroupId}/training', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped); }
[ "getVersionTrainingStatus(params) {\n return this.createRequest('', params, 'get');\n }", "get participantStatus() {\n\t\treturn this.__participantStatus;\n\t}", "function getTraining() {\n if ($(\"#lblTrainingName\").size() > 0) {\n return $(\"#lblTrainingName\")\n .text()\n .replace(/[^a-zA-Z0-9]/g, \"\");\n }\n}", "function getTrainingModeLabel(x)\n{\n\tswitch(x)\n\t{\n\t\tcase TRAININGOFF:\n\t\treturn TRAININGOFF_ID;\n\t\tbreak;\n\t\t\n\t\tcase TRAININGON:\n\t\treturn TRAININGON_ID;\n\t\tbreak;\n\t}\n}", "function trainFace(username_email, cb) {\n var trained = false;\n console.log('training started>>>>>');\n // lighting\n var a = 180;\n var a2 = 0;\n var l = setInterval(function() {\n matrix.led([{\n arc: Math.round(180 * Math.sin(a)),\n color: 'blue',\n start: a2\n }, {\n arc: -Math.round(180 * Math.sin(a)),\n color: 'blue',\n start: a2 + 180\n }]).render();\n a = (a < 0) ? 180 : a - 0.1;\n }, 25);\n function stopLights() {\n clearInterval(l);\n }\n\n console.log(username_email);\n // starts training \n matrix.service('recognition').train(''+username_email).then(function(data) {\n stopLights();\n //continue if training is not finished\n if (!trained && data.hasOwnProperty('count')) {\n // means it's partially done\n matrix.led({\n arc: Math.round(360 * (data.count / data.target)),\n color: 'blue',\n start: 0\n }).render();\n }\n //training is finished\n else {\n trained = true;\n matrix.led('green').render();\n console.log('trained!', data);\n matrix.service('recognition').stop();\n setTimeout(function() {\n matrix.led('black').render();\n }, 2000);\n cb();\n //io.emit('TrainSuccess', true); //SEND DATA TO CLIENT\n return true;\n }\n });\n}", "function handle_bp_check_payment_group_status(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function trainModel() {\n app.models.train(\"pets\").then(\n (response) => {\n console.log(response);\n },\n (error) => {\n console.error(error);\n } \n );\n}", "function trainingMode(x)\n{\n\tvar err;\n\terr = parseTrainingMode(x);\n\t//displaysGlobalVariables();\n}", "saveStatus() {\n if (XIBLE.stopping) {\n return;\n }\n\n const statuses = Flow.getStatuses();\n const startedInstances = this.instances\n .filter(\n (instance) => instance.state === XIBLE.FlowInstance.STATE_STARTED && !instance.directed\n );\n\n if (!startedInstances.length) {\n delete statuses[this._id];\n } else {\n statuses[this._id] = startedInstances.map((instance) => {\n const status = {\n _id: instance._id,\n state: instance.state\n };\n\n if (instance.params && Object.keys(instance.params).length) {\n status.params = instance.params;\n }\n\n return status;\n });\n }\n\n Flow.saveStatuses(statuses);\n }", "function getData() {\n dataService.getData().then(function(response) {\n $scope.programs = response.programs;\n $scope.degreeGroup = response.filterGroups.degree;\n $scope.formatGroup = response.filterGroups.format;\n $scope.levelGroup = response.filterGroups.level;\n $scope.dataLoaded = true;\n $scope.loadError = false;\n }, function(err) {\n $scope.dataLoaded = false;\n $scope.loadError = true;\n console.error(err);\n });\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 checkLeadershipLevel() {\n var i, resourceInstance, newLeadershipLevel, leadershipPoints,\n listResources = Variable.findByName(gm, 'resources'),\n weekMaxValue = parseInt(Variable.findByName(gm, 'week').getMaxValue()),\n pointsMinToLlvl2 = 10 * (weekMaxValue - 1) + 75,\n pointsMinToLlvl3 = 15 * (weekMaxValue - 1) + 85;\n for (i = 0; i < listResources.items.size(); i++) {\n resourceInstance = listResources.items.get(i).getInstance(self);\n if (resourceInstance.getActive() == true) {\n leadershipPoints = parseInt(resourceInstance.getConfidence()) + parseInt(resourceInstance.getProperty('totalExperienceGained'));\n switch (true) {\n case leadershipPoints >= pointsMinToLlvl2 && leadershipPoints < pointsMinToLlvl3 :\n newLeadershipLevel = 2;\n break;\n case leadershipPoints >= pointsMinToLlvl3 :\n newLeadershipLevel = 3;\n break;\n default :\n newLeadershipLevel = 1;\n }\n resourceInstance.setProperty('leadershipLevel', newLeadershipLevel);\n }\n }\n}", "static get STATUS_RUNNING () {\n return 0;\n }", "training() {\n const trainingOpponentSelection = TRAINING_SELECTION;\n\n this.setState({\n mode: Modes.ShipSelection,\n trainingOpponentSelection,\n trainingOpponentCommander: 0,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n });\n }", "function status(){\n if(!_.isEmpty(env)){\n console.log(\"Currently in the following environment:\");\n console.log(columnify(env));\n console.log(\" \"); \n }\n \n var ret = model.checkStatus();\n if(ret === false){\n console.log(\"You currently do not have any timers running\");\n }else{\n console.log(columnify(ret));\n }\n }", "function updateWorkflowStatus(workflowResponse) {\n\n var JSONresponse = JSON.parse(workflowResponse);\n var statusIndicator = document.getElementById(\"myWorkflowStatus\");\n var statusLoader = document.getElementById(\"myLoader\");\n var statusLoaderBar = document.getElementById(\"myLoaderBar\");\n var status = JSONresponse.status;\n statusIndicator.innerHTML = status;\n\n var workflowButton = document.getElementById(\"myWorkflowButton\");\n var tasks = JSONresponse.tasks;\n var numTasks = JSONresponse.workflowDefinition.tasks.length;\n \n if (status == \"RUNNING\") {\n statusLoader.style.visibility = \"visible\";\n workflowButton.disabled = true;\n\n for (var i = 0; i < tasks.length; i++) {\n \n if (tasks[i].status == \"SCHEDULED\" || (tasks[i].status == \"COMPLETED\" && typeof tasks[i + 1] == 'undefined') || (tasks[i].status == \"FAILED\" && typeof tasks[i + 1] == 'undefined')) {\n if (tasks[0].status == \"SCHEDULED\") {\n updateStatusBar(statusLoaderBar, 0);\n }\n statusIndicator.innerHTML = status + \": \" + tasks[i].referenceTaskName;\n } else if (tasks[i].status == \"COMPLETED\") {\n updateStatusBar(statusLoaderBar, (i + 1) / numTasks);\n }\n }\n\n } else if (status == \"COMPLETED\") {\n updateStatusBar(statusLoaderBar, 1);\n workflowButton.disabled = false;\n\n //update series table\n var series_url = URL.eis_qido + \"/EIS.DCM/studies/\" + selectedStudyUID + \"/series?includeField=0008103E,0020000E,00200011,00201209\";\n getSeries(series_url);\n clearInterval(interval);\n\n //update results\n for (var i = 0; i < tasks.length; i++) {\n if (tasks[i].referenceTaskName == \"ai_inferencing\") {\n statusIndicator.innerHTML = status + \" \" + tasks[i].outputData.response.body.prediction[0].geClass + \": Probability = \" + tasks[i].outputData.response.body.prediction[0].probability;\n }\n }\n \n } else {\n updateStatusBar(statusLoaderBar, 1);\n workflowButton.disabled = false;\n clearInterval(interval);\n for (var i = 0; i < tasks.length; i++) {\n if (tasks[i].outputData.response.reasonPhrase == \"BAD REQUEST\") {\n alert(status + \": \" + tasks[i].outputData.response.body.message);\n }\n }\n }\n}", "get status() {\n this._status = getValue(`cmi.objectives.${this.index}.status`);\n return this._status;\n }", "function getStatus() {\n return __state.activitySubmitted || __state.activityPariallySubmitted;\n }", "function getCompPartProposedTeamGradingAction(yearRefId, competitionId, divisionId) {\n const action = {\n type: ApiConstants.API_GET_COMPETITION_PART_PROPOSED_TEAM_GRADING_LIST_LOAD,\n yearRefId,\n competitionId,\n divisionId,\n };\n return action;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }