query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
listlengths
19
20
metadata
dict
Validation alarm text input
function validation() { userInputHours = document.getElementById("userInputHours").value; userInputMinutes = document.getElementById("userInputMinutes").value; userInputSeconds = document.getElementById("userInputSeconds").value; // Validates blank fields if (userInputHours == "" || userInputMinutes == "" || userInputSeconds == "") { console.log("A field is left blank"); alert("Please fill in all fields!") return false; } // Validates non-digit characters if ( (isNaN(userInputHours)) || (isNaN(userInputMinutes)) || (isNaN(userInputSeconds)) ) { console.log("One of the fields contains a non-number character"); return false; } // Validates hours digits (max 23). if (userInputHours > 23) { console.log("Max hours is 23!"); x = document.getElementById("userInputHours").style; x.color = ("red"); return false; } // Validates minutes digits (max 59). if (userInputMinutes > 59) { console.log("Max minutes is 59!"); x = document.getElementById("userInputMinutes").style; x.color = ("red"); return false; } // Validates seconds digits (max 59). if (userInputSeconds > 59) { console.log("Max seconds is 59!"); x = document.getElementById("userInputSeconds").style; x.color = ("red"); return false; } else { alarmTimeSetInFrontend = (userInputHours + ":" + userInputMinutes + ":" + userInputSeconds); console.log("Alarm set in front-end to: " + alarmTimeSetInFrontend); //console.log("Alarm set in front-end: " + userInputHours + ":" + userInputMinutes + ":" + userInputSeconds); document.getElementById("info-box-text").innerHTML = alarmTimeSetInFrontend; return false; } }
[ "textInputCheck(txtInput, emptyMessage) {\n // var regex = /^[a-zA-Z ]+$/;\n // console.log(\"TXTInput-->\" + txtInput);\n\n if (txtInput !== null && txtInput.trim().length > 0) {\n return true\n } else {\n // Alert.alert(globals.appName, emptyMessage)\n return false\n }\n }", "function validation(text, date, time) {\n const currentDate = new Date()\n const parsedDate = date.split(\"-\")\n const currentHour = currentDate.getHours();\n const currentMinutes = currentDate.getMinutes();\n const currentDateStruct = {\n year: parseInt(currentDate.getFullYear()),\n month: parseInt(currentDate.getMonth() + 1),\n day: parseInt(currentDate.getDate())\n }\n const inputDateStruct = {\n year: parseInt(parsedDate[0]),\n month: parseInt(parsedDate[1]),\n day: parseInt(parsedDate[2])\n }\n if (date === \"\") {\n alert(\"date cannot be empty\\nif you want to add note you must choose date\")\n return false;\n }\n if (inputDateStruct.year < currentDateStruct.year) {\n alert(\"Time cannot be in past\")\n return false;\n } else if (inputDateStruct.year === currentDateStruct.year) {\n if (inputDateStruct.month < currentDateStruct.month) {\n alert(\"month cannot be in past\")\n return false;\n } else if (inputDateStruct.month === currentDateStruct.month) {\n if (inputDateStruct.day < currentDateStruct.day) {\n alert(\"day cannot be in past\")\n return false;\n }\n }\n }\n if (text === \"\") {\n alert(\"text cannot be empty\\nPlease enter some text in the text box\")\n return false;\n }\n\n const [hour, minutes] = time.split(\":\");\n const [intHour, intMinutes] = [parseInt(hour), parseInt(minutes)];\n if (time === \"\") {\n\n } else {\n\n if (currentHour > intHour) {\n alert(`invalid hour\\nhour cannot be in past\\n${text}`)\n return false;\n } else if (currentHour == intHour) {\n if (currentMinutes > intMinutes) {\n alert(\"invalid minute \\nminute cannot be in past\")\n return false;\n }\n }\n }\n console.log(\"Validation succeeded \")\n return true;\n}", "function checkValidAlarm(x)\n{\n if(x == null || x == \"\")\n {\n alert(\"not a valid alarm\")\n }\n}", "htmlCheckInputInvoiceInfo(event){\n var input = event.target.value;\n if (input.length > 0 && input.length <= 80){\n var regex = /^[a-zA-Z0-9;!@#\\$%\\^\\&*\\)\\(+=._-]+$/g;\n if(!regex.test(input)){\n showError(\"InvoiceInfoFormatKO\", 2);\n return false;\n }else{\n $('#error').hide();\n }\n }else if(input.length == 0){\n showError(\"InvoiceInfoFormatNull\", 1);\n return false;\n }else{\n showError(\"InvoiceInfoFormatKO\", 2);\n return false;\n }\n }", "function validiraj_ime(){\n\n var pattern = /^[A-Za-z ]{1,75}$/;\n var tekst = document.getElementById(\"forma\").ime_input.value;\n var test = tekst.match(pattern);\n\n if (test == null) {\n document.getElementById(\"ime_error\").classList.remove(\"hidden\");\n valid_test = false;\n } else{\n console.log(\"validirano ime\");\n document.getElementById(\"ime_error\").classList.add(\"hidden\");\n }\n }", "function validateInput(val, textType) {\n switch(textType) {\n case \"dp1-amount\": \n return /^[0-9]+$/.test(val) && val >= 25 && val <= 1000;\n case \"dp2-amount\": \n return /^[0-9]+$/.test(val) && val >= 25 && val <= 1000;\n case \"mp-offTime\":\n return /^[0-9]+$/.test(val) && val >= 5 && val <= 120;\n case \"mp-onTime\":\n return /^[0-9]+$/.test(val) && val >= 5 && val <= 120;\n default: return false;\n }\n}", "function validateFirstTrain () {\n var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])?$/.test(firstTrain);\n console.log(isValid)\n if (isValid) {\n $(\"#first-train-input\").css(\"background-color\", \"white\");\n }\n else {\n $(\"#first-train-input\").css(\"background-color\", \"pink\");\n alert(\"First Train input is not valid. Please enter a time in 24-hour format(HH:MM)!\");\n };\n }", "function CheckValidTime(obj) {\r\n var blnComplete = true;\r\n for (i = 0; i < obj.value.length; i++) {\r\n var ch = obj.value.charCodeAt(i);\r\n if ((ch < 48) || (ch > 58))\r\n blnComplete = false;\r\n }\r\n\r\n if (!blnComplete) {\r\n alert('Time format is not correct');\r\n obj.focus();\r\n }\r\n else {\r\n var arrChar = obj.value.split(\":\");\r\n if ((arrChar[0] > 23) || (arrChar[1] > 59)) {\r\n alert('Time format is not correct');\r\n obj.focus();\r\n blnComplete = false;\r\n }\r\n }\r\n return blnComplete;\r\n}", "function validateInput(val, textType) {\n switch (textType) {\n case \"dp1-amount\":\n return (/^[0-9]+$/.test(val) && val >= 25 && val <= 1000\n );\n case \"dp2-amount\":\n return (/^[0-9]+$/.test(val) && val >= 25 && val <= 1000\n );\n case \"mp-offTime\":\n return (/^[0-9]+$/.test(val) && val >= 5 && val <= 120\n );\n case \"mp-onTime\":\n return (/^[0-9]+$/.test(val) && val >= 5 && val <= 120\n );\n default:\n return false;\n }\n}", "function checkAlarm() {\n let timeString = currentTime.substring(0, 5) + currentTime.substring(8);\n if (timeString.valueOf() === alarmTime.valueOf()) {\n window.alert(\"Alarm is going off! Alarm will be reset upon closing this alert.\");\n resetAlarmBtn.disabled = true;\n alarmTime = \"\";\n document.getElementById(\"alarm-time\").innerText = \"No alarm is currently set.\";\n }\n}", "function validarTexto(campo) {\n\t\t\n\t\tif(\n\t\t campo.value.indexOf(\"@\") != -1 ||\n\t\t campo.value.indexOf(\"?\") != -1 ||\n\t\t campo.value.indexOf(\"¿\") != -1 ||\n\t\t campo.value.indexOf(\"{\") != -1 ||\n\t\t campo.value.indexOf(\"}\") != -1) {\n\t\t\n\t\t\t\tcampo.select();\n\t\t\t\tif(typeof swal != 'undefined')\n\t\t\t\t\talert(\"El campo actual no debe contener ninguno de los siguientes simbolos:\\n\\n@\\t?\\t¿\\t{\\t}\");\n\t\t\t\telse\n\t\t\t\t\tswal(\"El campo actual no debe contener ninguno de los siguientes simbolos:\\n\\n@\\t?\\t¿\\t{\\t}\")\n\t\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\t\t\t\t\t\t\t \n\t}", "function validarEnunciado() {\n\n var enunciado_pregunta = $(\"#textEnunciado\").val().trim();\n\n if (enunciado_pregunta.length < 10) {\n alert(\"El enunciado debe tener 10 caracteres minimo\");\n return false;\n }\n else {\n return true;\n }\n}", "function validate(time) {\n var regex = /^(1[0-2])|0[1-9]:[0-5][0-9]$/;\n console.log(time);\n if (!regex.test(time)) {\n alert(\"Please use 24 hour format: ex. 03:00\");\n } else {\n }\n return true;\n}", "function createAlarm(e) {\r\n if (e.keyCode !== 13)\r\n return;\r\n input = document.getElementById(\"alarmCreate\").value;\r\n var duration = parseFloat(input);\r\n if (isNaN(duration))\r\n alert(\"Invalid time duration entered!\");\r\n else {\r\n var name = \"Alarm \" + Date.now(); // Generate unique alarm name\r\n chrome.alarms.create(name, { delayInMinutes: duration });\r\n console.log(\"Alarm set. (\" + duration + \" minutes)\");\r\n }\r\n}", "function setAlarm(time) {\n console.log(\"Setting an alarm for: \" + time);\n var timeWithoutAmPm = time;\n\n // Format string for speaking back to the user\n if (time.includes('.')) {\n var timeWithoutAmPm = time.replace('.', '');\n timeWithoutAmPm = timeWithoutAmPm.replace('.', '');\n }\n\n \n var timeArray = time.split(\":\");\n //alert(timeArray[0]);\n //alert(timeArray[1]);\n\n\n // No minutes included (ex. '11 o'clock' or '11 pm')\n if (timeArray[1] == null) {\n\n var hour = timeArray[0][0] + timeArray[0][1];\n var origHour = hour;\n\n if (origHour[1] == \" \") {\n origHour = origHour[0];\n }\n\n // Special case: \"12 o'clock\"\n if (hour == \"12\") {\n if (timeArray[0].includes(\"a.m.\")) {\n hour = \"00\";\n }\n else {\n hour = \"12\";\n }\n }\n else {\n // Switch to military time\n if (timeArray[0].includes(\"p.m.\")) {\n hour = parseInt(hour) + 12;\n }\n\n // Concatenate the \"0\" before it if it's in the single digits\n if (hour < 10) {\n hour = \"0\" + hour[0];\n }\n }\n\n // Set values\n document.getElementById(\"hour\").value = hour;\n document.getElementById(\"min\").value = \"00\";\n document.getElementById(\"sec\").value = \"00\";\n\n var amOrPm = \"PM\";\n if (hour < 12) {\n amOrPm = \"AM\";\n }\n // Tell the user that the alarm has been set\n responsiveVoice.speak(\"Ok, I have set an alarm for \" + origHour + \":00 \" + amOrPm);\n\n // Click to set the alarm\n document.getElementById(\"submitbutton\").click();\n\n // Indicate that the alarm has been set\n alarmIsSet = true;\n displayAlarm(origHour + \":00 \" + amOrPm);\n }\n else {\n var hour = parseInt(timeArray[0]);\n var origHour = hour;\n\n // Special case: \"12 o'clock\"\n if (hour == 12) {\n if (timeArray[1].includes(\"a.m.\")) {\n hour = \"00\";\n }\n else {\n hour = \"12\";\n }\n }\n else {\n // Switch to military time\n if (timeArray[1].includes(\"p.m.\") && (parseInt(timeArray[0]) != 12)) {\n hour = hour + 12;\n }\n\n // Concatenate the \"0\" before it if it's in the single digits\n if (hour < 10) {\n hour = \"0\" + hour;\n }\n }\n\n // if (isInt(hour)) {\n // alert('Was not an Int');\n // }\n\n // Set values\n document.getElementById(\"hour\").value = hour;\n document.getElementById(\"min\").value = timeArray[1][0] + timeArray[1][1];\n document.getElementById(\"sec\").value = \"00\";\n\n var amOrPm = \"PM\";\n if (hour < 12) {\n amOrPm = \"AM\";\n }\n\n // Tell the user that the alarm has been set\n responsiveVoice.speak(\"Ok, I have set an alarm for \" + origHour + \":\" + timeArray[1][0] + timeArray[1][1] + \" \" + amOrPm);\n\n // Click to set the alarm\n document.getElementById(\"submitbutton\").click();\n\n // Indicate that the alarm has been set\n alarmIsSet = true;\n displayAlarm(origHour + \":\" + timeArray[1][0] + timeArray[1][1] + \" \" + amOrPm);\n }\n}", "function validate(tweetText) {\n if (!tweetText) {\n alert(\"You must have more to say!\")\n return false;\n }\n if (tweetText.length > 140) {\n alert(\"Your Tweet is too long Twit!\")\n return false;\n }\n return true;\n }", "function checkValidAppointments(input) {\n const schema = {\n patientName: Joi.string(),\n doctorName: Joi.string(),\n appointDate: Joi.date().format(\"YYYY-MM-DD\"),\n appointTime: Joi.string().regex(time)\n };\n const result = Joi.validate(input, schema);\n if (result.error) {\n return false;\n }\n return true;\n}", "validateExpectation(text, radios, message_radio, message_text) {\n console.log('validateExpectation...')\n let expectInterval = null;\n if (validators.radiosChecked(radios)) { // Radios checked\n if ($(text).val() != \"\") { // Text filled\n $(message_radio).stop().text('').hide();\n $(message_text).stop().text('').hide();\n clearInterval(expectInterval);\n } else { // Text not filled\n $(message_radio).stop().text('').hide();\n $(message_text).delay('600').text('Please list your expectation').fadeIn();\n }\n } else { // Radios not checked\n if (!$(text).is(':focus') && $(text).val() != \"\") { // Text filled\n $(message_radio).delay('600').text('Please select your level of satisfaction').fadeIn();\n $(message_text).stop().text('').hide();\n } else { // Text not filled\n $(message_radio).stop().text('').hide();\n $(message_text).stop().text('').hide();\n }\n }\n }", "function checkSaisie(nInput, iInput){\n //nInput : input name\n var regEx = /^.{10,100}$/;;\n var val = iInput.value;\n var minChar;\n switch (nInput) {\n case \"ct-nom\":\n case \"ct-prenom\":\n case \"ct-entreprise\":\n minChar = 2;\n regEx = /^[a-zA-Z-éèàùïöüëäöïüäç ]{2,50}$/;\n break;\n case \"ct-email\":\n case \"ct-email2\":\n minChar = 2;\n regEx = /[a-z0-9]+(?:\\.[a-z0-9]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;\n break;\n case \"ct-msg\":\n minChar = 10;\n //Tous les caractères. nombre entre 10 et 2000.\n regEx = /^[\\w|\\d|\\s|\\n|\\r\"'-_#,;:!§{}&²€$£%µéèàùïöüëäöïüäç°]{10,2000}$/;\n break;\n case \"ct-objet\":\n minChar = 10;\n //Tous les caractères. nombre entre 10 et 100.\n regEx = /^[\\w|\\d|\\s|\\n|\\r\"'-_#,;:!§{}&²€$£%µéèàùïöüëäöïüäç°]{1,100}$/;\n break; \n default:\n minChar = 2;\n break;\n }\n // console.log(\"val.length : \"+ val.length);\n if (val.length >= minChar) {\n if (regEx.test(val)) {\n // console.log(nInput + \" correct!\");\n setUi(iInput, false);\n }else{\n // console.log(nInput + \" Incorrect\");\n setUi(iInput, true);\n }\n }\n // console.log(val + \" | \" + regEx.test(val));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch a list of ETH transactions for the user's wallet
static getEthTransactions() { const { walletAddress } = store.getState(); return fetch( `https://${this.getEtherscanApiSubdomain()}.etherscan.io/api?module=account&action=txlist&address=${walletAddress}&sort=desc&apikey=${ Config.ETHERSCAN_API_KEY }`, ) .then(response => response.json()) .then(data => { if (data.message !== 'OK') { return []; } return data.result.filter(t => t.value !== '0').map(t => ({ from: t.from, timestamp: t.timeStamp, transactionHash: t.hash, value: (parseInt(t.value, 10) / 1e18).toFixed(2), })); }); }
[ "static async getEthTransactions(walletAddress, offset) {\n const fetchString = 'https://' + this.getEtherscanApiSubdomain() + '.etherscan.io/api?module=account&action=txlist&address=' + walletAddress + '&sort=desc&apikey=' + ETHERSCAN_API_KEY; \n return fetch(fetchString)\n .then(response => response.json())\n .then(data => {\n if (data.message === \"OK\") { \n data.result = data.result.filter(function(item) {\n return (item.value !== '0' && item.from !== item.to)\n });\n if (data.result.length > 0) {\n data.message = \"OK\";\n if (offset !== 0 && offset !== null) {\n data.result = data.result.slice(0,offset)\n }\n } else {\n data.message = \"NO_TRANSACTIONS_FOUND\"; \n }\n } else if (data.message === \"No transactions found\") {\n data.message = \"NO_TRANSACTIONS_FOUND\"; \n } else {\n data.message = \"ERROR\"; \n }\n return data; \n });\n }", "getUnconfirmedTransactions() {\n // Reset to initial page\n this.currentPage = 0;\n // \n nem.com.requests.account.transactions.unconfirmed(this._Wallet.node, this._Wallet.currentAccount.address).then((res) => {\n this._$timeout(() => {\n this.unconfirmed = res.data;\n for (let i = 0; i < res.data.length; i++) {\n this.unconfirmed[i].meta.innerHash = {\n \"data\": res.data[i].meta.data\n }\n this.unconfirmed[i].meta.height = 9007199254740991;\n }\n });\n },\n (err) => {\n this._$timeout(() => {\n if(err.code < 0) {\n this._Alert.connectionError();\n } else {\n this._Alert.errorGetTransactions(err.data.message);\n }\n });\n });\n }", "async getAllTransactions() {\n const response = await this.fetchPage('myGlobalTransfers.htm');\n const transactions = scrape.allTransactions(response.data);\n return transactions;\n }", "async getTransactions (bchAddress) {\n const addr = bchAddress || this.walletInfo.cashAddress\n const data = await this.bchjs.Electrumx.transactions(addr)\n\n const transactions = data.transactions.map(x => x.tx_hash)\n return transactions\n }", "async getTransactions(progressBar) {\n //get transaction list\n let wallet = await this.getWalletInfo();\n console.log(wallet.transactions);\n let transactions = [];\n if (progressBar) {\n progressBar.max = wallet.transactions.length;\n progressBar.value = 0;\n }\n //loop through list and get info about each transaction from api, very inefficient\n for (var i = 0; i < wallet.transactions.length; i++) {\n if (progressBar) {\n progressBar.value += 1;\n }\n console.log(i + \"/\" + wallet.transactions.length);\n let transactionInfo = await this.getTransactionInfo(\n wallet.transactions[i]\n );\n transactions.push(transactionInfo);\n }\n if (progressBar) {\n progressBar.remove();\n }\n return transactions;\n }", "async getTransactions(user) {\n // TODO: not yet implemented\n }", "async getFiatTransactions() {\n if (this.exchange === 'COINBASE') {\n let accounts = await this.api.getAccounts({})\n var accountTransactionsCalls = []\n accounts[0].forEach(async function (acct) {\n if (acct != undefined) {\n accountTransactionsCalls.push(acct.getTransactions({}))\n }\n })\n let accountTransactions = await Promise.all(accountTransactionsCalls)\n return accountTransactions\n }\n }", "async getReceivedTransactions() {\n const response = await this.fetchPage('myGlobalTransfers.htm');\n const transactions = scrape.receivedTransactions(response.data);\n return transactions;\n }", "function getAllWallets(req, res, next) {\n db.collection('wallets').find({}).sort({createdAt: -1}).toArray(function (err, wallets) {\n if (err) {\n next(err);\n return;\n }\n \n // Get balance for each wallet\n for (var i = 0; i < wallets.length; i++) {\n var wallet = wallets[i];\n if (wallet.walletAddress) {\n // Get its balance as it may change between queries\n var walletContractInstance = web3.eth.contract(WALLET_CONTRACT_ABI).at(wallet.walletAddress);\n wallet.balance = getBalanceInEther(parseFloat(walletContractInstance._eth.getBalance(wallet.walletAddress)));\n }\n }\n res.send(wallets);\n });\n}", "async function getAllTransactions() {\n try {\n const res = await fetch('/api/v1/transactions');\n const response = await res.json();\n\n dispatch({\n type: 'GET_ALL_TRANSACTIONS',\n payload: response.data,\n });\n } catch (err) {}\n }", "async getSentTransactions() {\n const response = await this.fetchPage('myGlobalTransfers.htm');\n const transactions = scrape.sentTransactions(response.data);\n return transactions;\n }", "async function list_All_Unconfirmed_Transaction(maxPage=1){\n let path = url+\"/transactions/unconfirmed?\"\n let res = await template.retrieve_with_limitation_template(path, maxPage)\n return res\n}", "listTransactions (account_number, page){\n const transactions = Api.post(this.base_url + '/listtransactions',\n { virtualaccount: account_number, page: page },\n { 'Authorization': this.apiKey}\n );\n return accoutransactionsnts;\n }", "async getTransactions (addr) {\n try {\n if (typeof addr !== 'string' || !addr.length) {\n throw new Error('The provided avax address is not valid')\n }\n\n const transactions = []\n let res = []\n // Get transaction history for the address.\n const query = this.getQuery(addr)\n const request = await _this.axios.post(query)\n\n if (request.status >= 400) {\n throw new Error(`No transaction history could be found for ${addr}`)\n }\n\n res = request.data.transactions\n transactions.push(...res)\n\n return transactions\n } catch (err) {\n console.error('Error in avax.js/getTransactions(): ', err)\n throw err\n }\n }", "async function getTxListFromEtherscan(account){\n let txUrl = `https://api.etherscan.io/api?module=account&action=tokentx&address=${account}&startblock=0&endblock=latest&sort=asc&apikey=${API_KEY}`;\n return await axios.get(txUrl)\n .then(async (res) => {\n //filter out token duplicates\n let txs = res.data.result;\n txs = await filterDuplicates(txs);\n\n //loop through api call results\n return txs.map((item) => {\n if(item.tokenSymbol != \"\"){\n return formatTokenObject(item);\n }\n })\n })\n}", "transactions(address, params, token) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n return yield this.send(\"/payment/address/transactions/\" + address, \"get\", params, token);\n }\n catch (error) {\n return error;\n }\n });\n }", "getFullTxList () {\n return this.store.getState().transactions\n }", "getUserTransactions(id) {\n return Api().get(`/transactions/user/${id}`);\n }", "function getTransactionsOfAccount(iCOWalletTokenAddress, iCOWalletDiscount1Address, iCOWalletDiscount2Address, startBlockNumber, endBlockNumber, onlyTokenSend) {\n if (endBlockNumber == null) {\n endBlockNumber = eth.blockNumber;\n logger.info(\"Using endBlockNumber: \" + endBlockNumber);\n }\n if (startBlockNumber == null) {\n startBlockNumber = endBlockNumber - 1000;\n logger.info(\"Using startBlockNumber: \" + startBlockNumber);\n }\n logger.info(\"Searching for transactions to/from account \\\"\" + ICOWalletTokenAddress + \"\\\" within blocks \" + startBlockNumber + \" and \" + endBlockNumber);\n \n var toSCTransactionsArray = [];\n var fromSenderTransactionsArray = [];\n \n // parse block range\n for (var b = startBlockNumber; b <= endBlockNumber; b++) {\n if (b % 10 == 0) {\n logger.info(\"Parsing block range: \" + b + \" to block: \" + Math.min(endBlockNumber, b + 9));\n }\n var block = web3.eth.getBlock(b, true);\n if (block != null && block.transactions != null) {\n for( var t = 0 ; t < block.transactions.length; ++t) {\n var e = block.transactions[t];\n // account is the receip of transaction\n if (e.to !== null && (iCOWalletTokenAddress.toLowerCase() === e.to.toLowerCase() || iCOWalletDiscount1Address.toLowerCase() === e.to.toLowerCase() || iCOWalletDiscount2Address.toLowerCase() === e.to.toLowerCase()) && onlyTokenSend === false) {\n fromSenderTransactionsArray.push(e);\n }\n \n // account is emiter of transaction\n if (iCOWalletTokenAddress.toLowerCase() == e.from.toLowerCase()) {\n if (e.to !== null && e.to.toLowerCase() === tokenContractInstance.address.toLowerCase())\n {\n toSCTransactionsArray.push(e);\n }\n }\n }\n }\n }\n\n return [toSCTransactionsArray, fromSenderTransactionsArray];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Methode die de index van de select data teruggeeft, op basis van het toernooi type.
function getIndexByType(type) { for (var i=0; i<$scope.select_data.length; i++) { if ($scope.select_data[i].type == type) return i; } return 0; }
[ "get indexType()\n {\n return 'text';\n }", "setQuery(type, sql, data){\n\t\t//si vamos a insertar primero hacemos un select, de ahi si es 0 resultados, hacemos un insert si hay resultados hacemos un update\n\t\t\n\t}", "function biquad_type_select(table, handler) {\n var row = table.insertRow(-1);\n var col_name = row.insertCell(-1);\n var col_menu = row.insertCell(-1);\n\n col_name.appendChild(document.createTextNode('Type'));\n\n var select = document.createElement('select');\n select.className = 'biquad_type_select';\n var options = [\n 'lowpass',\n 'highpass',\n 'bandpass',\n 'lowshelf',\n 'highshelf',\n 'peaking',\n 'notch'\n /* no need: 'allpass' */\n ];\n\n for (var i = 0; i < options.length; i++) {\n var o = document.createElement('option');\n o.appendChild(document.createTextNode(options[i]));\n select.appendChild(o);\n }\n\n select.value = INIT_EQ_TYPE;\n col_menu.appendChild(select);\n\n function onchange() {\n handler(select.value);\n }\n select.onchange = onchange;\n\n function update(v) {\n select.value = v;\n }\n\n this.update = update;\n}", "function pasarDatos(index,id){\n\t\talert(\"ya esta en el pasar datos\");\n\t\talert(\"este es el id=\"+id+\" y este es el index=\"+index);\n\t\t\n\t\tparent.document.getElementById(id).options[2].selected;\n\t\t//parent.document.getElementById( id ).options[].value = index;\n\t\t//parent.document.getElementById('fechaCita').value=index;\n\t\t\n}", "function in_CreateSelectTd(indexDiv) {\r\n\tvar td = document.createElement(\"td\");\r\n\r\n\t//\r\n\t// select\r\n\t//\r\n\tvar select = document.createElement(\"select\");\r\n\t\tselect.onchange = in_IndexChosen;\r\n\r\n\t\t// some default values\r\n\t\tvar opt = document.createElement(\"option\");\r\n\t\t\topt.value = \"\";\r\n\t\t\topt.innerText = \"\";\r\n\t\tselect.appendChild(opt);\r\n\r\n\t\tvar opt = document.createElement(\"option\");\r\n\t\t\topt.value = TG_NEW_INDEX;\r\n\t\t\topt.innerText = TG_NEW_INDEX;\r\n\t\tselect.appendChild(opt);\r\n\r\n\r\n\t//\r\n\t// for known indexes\r\n\t//\r\n\tvar columnHashTable = indexDiv.columnHashTable;\r\n\t\r\n\tif (columnHashTable == null) {\r\n\t\tsy_logError(\"ERD-index\", \r\n\t\t\t\t\"in_CreateSelectTd\", \r\n\t\t\t\t\"columnHashTable is null!!\"\r\n\t\t\t\t+ \" indexDivId: \" + indexDiv.id);\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\t//\r\n\t// sort the indexe names\r\n\t//\r\n\tvar indexNameArray = new Array();\r\n\ti=0;\r\n\tfor (var property in columnHashTable) {\r\n\t\tindexNameArray[i] = property;\r\n\t\ti++;\r\n\t}\t\r\n\tvar indexNameArray = bubbleSort(indexNameArray, 0, indexNameArray.length - 1);\r\n\r\n\r\n\t// primary keys first\r\n\tfor (var i=0;i<indexNameArray.length;i++) {\r\n\t\r\n\t\tif (in_IsPKeyIndex(indexNameArray[i])) {\r\n\t\t\r\n\t\t\tvar opt = document.createElement(\"option\");\r\n\t\t\t\topt.value = indexNameArray[i];\r\n\t\t\t\topt.innerText = indexNameArray[i];\r\n\t\t\tselect.appendChild(opt);\r\n\t\t}\r\n\t}\r\n\r\n\t// foreign key\r\n\tfor (var i=0;i<indexNameArray.length;i++) {\r\n\t\r\n\t\tif (in_IsFKeyIndex(indexNameArray[i])) {\r\n\t\t\r\n\t\t\tvar opt = document.createElement(\"option\");\r\n\t\t\t\topt.value = indexNameArray[i];\r\n\t\t\t\topt.innerText = indexNameArray[i];\r\n\t\t\tselect.appendChild(opt);\r\n\t\t}\r\n\t}\r\n\t\r\n\t// then, others\r\n\tfor (var i=0;i<indexNameArray.length;i++) {\r\n\t\r\n\t\tif (!in_IsPKeyIndex(indexNameArray[i]) \r\n\t\t\t\t\t&& !in_IsFKeyIndex(indexNameArray[i])) {\r\n\t\t\t\t\t\r\n\t\t\tvar opt = document.createElement(\"option\");\r\n\t\t\t\topt.value = indexNameArray[i];\r\n\t\t\t\topt.innerText = indexNameArray[i];\r\n\t\t\tselect.appendChild(opt);\r\n\t\t}\r\n\t}\r\n\r\n\ttd.appendChild(select);\r\n\t\r\n\treturn td;\r\n}", "function getIndex(dataIndex, id) {\n\n // get the array of Ids\n var idNames = getIdNames(dataIndex);\n\n // get the index value for id of interest\n var idIndex = idNames.indexOf(id);\n\n // return the index value of selected id\n return idIndex;\n}", "updateType(type) {\n\t\tif (type === \"Meteorites\") this.category = \"meteors\";\n\t\telse if (type === \"Fireballs\") this.category = \"fireballs\";\n\t\telse if (type === \"Future Events\") this.category = \"futureEvents\";\n\t\telse this.category = \"default\";\n\t\tlet selectedData = this.selectionData[this.category]; //this.allData[this.category];\n\t\t\n\t\tlet options = d3.select(\"#columnSelect\")\n\t\t\t.selectAll(\"option\")\n\t\t\t.data(selectedData);\n\t\t\n\t\toptions.exit().remove();\n\t\toptions = options.enter().append(\"option\").merge(options);\n\t\toptions.attr(\"value\", function(d) { return d; })\n\t\t\t.text(function(d) { return d; });\n\t}", "setIndexAndType(model) {\n if (!this.options.index) {\n this.options.index = model.collection.name;\n }\n\n if (!this.options.type) {\n this.options.type = model.modelName;\n }\n\n if (!this._model) {\n this._model = model;\n }\n }", "function filterBySelect() {\n if ($(\"#tipo\").val() != 0) {\n var arr = segundoParcial.empleados.filter(function (e) {\n if (e.tipo == $(\"#tipo\").val()) {\n var tipoSelect = $(\"#tipo\").val();\n var tipoObtained = e.tipo;\n return e;\n }\n });\n arr = JSON.stringify(arr);\n arr = JSON.parse(arr);\n armarTabla(arr);\n }\n else {\n armarTabla(segundoParcial.empleados);\n }\n }", "indexType() {\n let index_name = '';\n CSchema.INDEX_TYPES.map(idtype => {\n if (idtype.val === this.index_type) {\n index_name = idtype.display;\n }\n });\n return index_name;\n }", "get selectedIndex() {\n let item = this.itemData.filter((i) => i.id === this.selection);\n return item && item[0] ? item[0].index : 0;\n }", "get db_type()/*:metavisuo.schema.db_type*/{return /*<metavisuo.schema.db_type>*/this.type_selector.value;}", "function indexFinder(id){var isPoint=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var ids=['NaN','NaN'];if(id.indexOf('_Point_')>-1){ids=id.split('_Series_')[1].split('_Point_');}else if(id.indexOf('_shape_')>-1&&(!isPoint||isPoint&&id.indexOf('_legend_')===-1)){ids=id.split('_shape_');ids[0]='0';}else if(id.indexOf('_text_')>-1&&(!isPoint||isPoint&&id.indexOf('_legend_')===-1)){ids=id.split('_text_');ids[0]='0';}return new Index(parseInt(ids[0],10),parseInt(ids[1],10));}", "function Event_ChangeColumnType(data) {\r\n datamoduleTable.GetColumns(Callback_ShowColumns, dropdown_Table.GetValue(), dropdown_ColumnType.GetValue(), dropdown_ColumnSubType.GetValue());\r\n datamoduleType.GetColumSubType(data, Callback_QueryGetSubType);\r\n}", "get_type_index(type) {\n\t\tif (type === 'int') {\n\t\t\treturn this.int\n\t\t} else if (type === 'float') {\n\t\t\treturn this.float\n\t\t} else {\n\t\t\treturn this.char\n\t\t}\n\t}", "function initIndexSelectMode() {\n if (select.length == 0) {\n return;\n }\n var index = select.val();\n $(\"#mode-selection\").hide();\n if (index === \"lucene\") {\n $(\"#mode-selection\").show();\n }\n }", "onSelectOperator(event, type){\n let { callback, idx } = this.props;\n this.filterData.operator = type;\n callback(this.filterData, idx, false);\n }", "indexObject(opts = {}) {\n const { type, id } = opts;\n\n return this.axios.post(`${this.api}/index/${type}/${id}`);\n }", "function indexFinder(id, isPoint) { if (isPoint === void 0) { isPoint = false; } var ids = ['NaN', 'NaN']; if (id.indexOf('_Point_') > -1) { ids = id.split('_Series_')[1].split('_Point_'); } else if (id.indexOf('_shape_') > -1 && (!isPoint || isPoint && id.indexOf('_legend_') === -1)) { ids = id.split('_shape_'); ids[0] = '0'; } else if (id.indexOf('_text_') > -1 && (!isPoint || isPoint && id.indexOf('_legend_') === -1)) { ids = id.split('_text_'); ids[0] = '0'; } return new Index(parseInt(ids[0], 10), parseInt(ids[1], 10)); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function will check weather a number is empty or not, means 0 values are not allowed here.
function checkEmptyNumber(id_d,message) { var data_d = getValue(id_d); if(checkEmptyAll(id_d,message)) { if(parseFloat(data_d)<=0) { takeCareOfMsg(message); return false; } else { return true; } } return false; }
[ "function validNumber(n) {return ( n != 0.0 && !isNaN(parseFloat(n))); }", "function isBlankOrZeroOrAPositiveInteger(theVal)\n{\n var retVal = true;\n \n if (theVal)\n {\n if (parseInt(theVal) != theVal || theVal<0)\n {\n retVal = false;\n }\n }\n \n return retVal;\n}", "isNumberValid(number) {\n return typeof number !== 'undefined' && null !== number && !isNaN(number);\n }", "function isEmpty(num){\n return (!num || /^\\s*$/.test(num));\n}", "checkNumbers(params, length) {\n for(var i=0;i<length;i++) {\n if (typeof params[i] !== 'number' || params[i] <= 0)\n return false;\n }\n return true;\n }", "function validNumber(value) {\n const intNumber = Number.isInteger(parseFloat(value));\n const sign = Math.sign(value);\n\n if (intNumber && (sign === 1)) {\n return true;\n } else {\n return 'Please use whole non-zero numbers only.';\n }\n}", "function isNum(v,maybenull) {\n var n = new Number(v.value);\n if (isNaN(n)) {\n return false;\n }\n if (maybenull==0 && v.value=='') {\n\n\n return false;\n }\n return true;\n}", "function notZero(num){\n var checkZero = parseInt(num);\n return checkZero !== 0;\n}", "function validaNumero(valorIngresado){\r\n if(valorIngresado == \"\" || valorIngresado == null){\r\n console.log(\"El valor ingresado es nulo\");\r\n return false;\r\n }else{\r\n if(isNaN(valorIngresado)){\r\n console.log(\"El valor ingresado no es un numero\");\r\n return false;\r\n }else{\r\n if(parseInt(valorIngresado) < 0){\r\n console.log(\"Numero negativo\");\r\n alert(\"El valor ingresado no puede ser menor a 0\");\r\n return false;\r\n }else{\r\n return true; \r\n } \r\n } \r\n }\r\n}", "function isNaN(value){return value!==value}", "function checkNumeric(data) {\n return data.every(function(x) {\n return x === null || $.isNumeric(x);\n });\n}", "static checkIsNumber(number) {\n if (number !== null && number !== undefined && typeof number == \"number\") {\n return true;\n }\n return false;\n }", "validNumber(num) {\n return !_.isNaN(num) && _.isNumber(num);\n }", "function validateNonNumber(value) {\n\treturn isNaN(value);\n}", "function checkIfOnlyNumbers(field) {\n if (/^[0-9]+$/.test(field.value)) {\n setValid(field);\n return true;\n } else {\n setInvalid(field, `${field.dataset.helper} must contain only numbers`);\n return false;\n }\n}", "function hasAZero(num) {\n return num.toString().split('').some(function(val) {\n return val === '0';\n }); \n }", "numericValidate(num){\n num = parseInt(num, 10)\n if (isNaN(num)){num = 0}\n return num\n }", "function is_blank_or_zero(s)\n{\n\tif (is_blank(s)==true) return true;\n\tif (is_digit(s))\n\t{\n\t\tvar i = parseInt(s, 10);\n\t\tif (i==0) return true;\n\t}\n\treturn false;\n}", "function testNumber(value) {\r\n return (value && value != null && value != \"undefined\") ? value : 0;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
put voronoi edges into a vbo
function voronoiToEdgeVBO() { vboMesh.clear(voronoiEdges); for(var i=0;i<voronoi.triangles.length;++i) { var tri = voronoi.triangles[i]; if(false || tri.interior_) { if(tri.neighbors_[0] && (false || tri.neighbors_[0].interior_)) { vboMesh.addVertex(voronoiEdges,tri.circumcenter); vboMesh.addVertex(voronoiEdges,tri.neighbors_[0].circumcenter); } if(tri.neighbors_[1] && (false || tri.neighbors_[1].interior_)) { vboMesh.addVertex(voronoiEdges,tri.circumcenter); vboMesh.addVertex(voronoiEdges,tri.neighbors_[1].circumcenter); } if(tri.neighbors_[2] && (false || tri.neighbors_[2].interior_)) { vboMesh.addVertex(voronoiEdges,tri.circumcenter); vboMesh.addVertex(voronoiEdges,tri.neighbors_[2].circumcenter); } } } vboMesh.buffer(voronoiEdges); }
[ "generateVoronoi() {\n this.voronoi = new Voronoi()\n let bbox = { xl: 0, xr: this.width, yt: 0, yb: this.height }\n this.diagram = this.voronoi.compute(this.points, bbox)\n }", "buildFromVoronoiDiagram( vd ){\n var vCells = vd.cells;\n\n // for each cell\n for(var i=0; i<vCells.length; i++){\n var cellhes = vCells[i].halfedges;\n var points = [];\n\n for(var j=0; j<cellhes.length; j++){\n points.push( cellhes[j].edge.va );\n points.push( cellhes[j].edge.vb );\n }\n\n // build a cell\n var cell = new Cell( points, vCells[i].site );\n if( cell.isValid() ){\n this._cells[ cell.getHash() ] = cell;\n this._cellArray.push( cell );\n }\n }\n }", "function plot_voronoi() {\n d3.select(\"#chartbox\")\n .append(\"path\")\n .attr(\"d\", vor.render())\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"black\");\n\n d3.select(\"#chartbox\")\n .append(\"path\")\n .attr(\"d\", del.renderPoints())\n .attr(\"fill\", \"black\");\n}", "function fill_voronoi() {\n for(i=0;i<dset.length;i++) {\n d3.select(\"#chartbox\")\n .append(\"path\")\n .attr(\"d\", vor.renderCell(i))\n .attr(\"fill\", function() {return d3.interpolateRdYlBu(color(dset[i].vel));});\n }\n plot_voronoi();\n}", "function voronoi(){\n voropoly=[];\n for(var i=0;i<points.length;i++){//for each point\n //console.log('-----new point-----');\n if(points[i].type!='supertriangle'){//that isn't a supertriangle point\n var neighbortris=findneighbortris(i);//find neighboring tris (indices)\n var voropolyentry=[];\n for(var j=0;j<neighbortris.length;j++) {//for each neighboring tri\n var sc=supercount(tri[neighbortris[j]]);\n if(sc===0){//if the neighboring tri doesn't contain a supertriangle point\n /*\n if(tri[neighbortris[j]].cc.x>600 || tri[neighbortris[j]].cc.x<0 || tri[neighbortris[j]].cc.y>600 || tri[neighbortris[j]].cc.y<0){\n console.log('cc outside, how bout that');\n }else{voropolyentry.push(tri[neighbortris[j]].cc);\n console.log('cc added: '+tri[neighbortris[j]].cc.x+','+tri[neighbortris[j]].cc.y);\n }//then add the circumcenter to the voronoi cell\n */\n voropolyentry.push(tri[neighbortris[j]].cc);\n //console.log('cc added: '+tri[neighbortris[j]].cc.x+','+tri[neighbortris[j]].cc.y);\n }\n else if(sc===1){//if neighbor tri does contain one supertriangle point\n //find the edge\n var legaledge=[];\n var superpoint=[];\n if(points[tri[neighbortris[j]].p1].type=='supertriangle'){superpoint.push(points[tri[neighbortris[j]].p1]);}else{legaledge.push(points[tri[neighbortris[j]].p1]);}\n if(points[tri[neighbortris[j]].p2].type=='supertriangle'){superpoint.push(points[tri[neighbortris[j]].p2]);}else{legaledge.push(points[tri[neighbortris[j]].p2]);}\n if(points[tri[neighbortris[j]].p3].type=='supertriangle'){superpoint.push(points[tri[neighbortris[j]].p3]);}else{legaledge.push(points[tri[neighbortris[j]].p3]);}\n superpoint=superpoint[0];\n var temppt;\n //find slope of legaledge\n if(legaledge[0].y-legaledge[1].y===0){//horizontal legaledge\n var horimidpt={x:(legaledge[0].x+legaledge[1].x)/2,y:(legaledge[0].y+legaledge[1].y)/2};\n var vertydir=(superpoint.y-horimidpt.y)>0?600:0;\n //console.log('sc1 (hori) added: '+horimidpt.x+','+vertydir);\n temppt={x:horimidpt.x,y:vertydir};\n }else if(legaledge[0].x-legaledge[1].x===0){//vertical legaledge\n var vertmidpt={x:(legaledge[0].x+legaledge[1].x)/2,y:(legaledge[0].y+legaledge[1].y)/2};\n var vertxdir=(superpoint.x-vertmidpt.x)>0?600:0;\n //console.log('sc1 (vert) added: '+vertxdir+','+vertmidpt.y);\n temppt={x:vertxdir,y:vertmidpt.y};\n }else{\n var tm=(legaledge[0].y-legaledge[1].y)/(legaledge[0].x-legaledge[1].x);//m=y2-y1/x2-x1;\n var tb=legaledge[0].y-tm*legaledge[0].x;//b=y-mx;\n var m=-1/tm;//find perpendicular slope\n var midpt={x:(legaledge[0].x+legaledge[1].x)/2,y:(legaledge[0].y+legaledge[1].y)/2};\n var b=midpt.y-m*midpt.x;//b=y-mx\n var xdir=(((superpoint.y-tb)/tm)-superpoint.x)<0?600:0;\n temppt={x:xdir,y:m*xdir+b};\n //console.log(temppt);\n if(temppt.y<0){\n temppt.y=0;\n temppt.x=(temppt.y-b)/m;\n }\n if(temppt.y>600){\n temppt.y=600;\n temppt.x=(temppt.y-b)/m;\n }\n\n //console.log('sc1 added: '+temppt.x+','+temppt.y);\n }\n //find the legal triangle attached to the legal edge\n //find the cc for that legal triangle\n //if temppt lies within the triangle formed by the legal edge and cc, then discard the temppt\n var legalcc;\n for(var o=0;o<neighbortris.length;o++) {\n if(points[tri[neighbortris[o]].p1].type!='supertriangle' && points[tri[neighbortris[o]].p2].type!='supertriangle' && points[tri[neighbortris[o]].p3].type!='supertriangle'){//legal triangle\n if((points[tri[neighbortris[o]].p1]==legaledge[0] || points[tri[neighbortris[o]].p2]==legaledge[0] || points[tri[neighbortris[o]].p3]==legaledge[0]) &&\n (points[tri[neighbortris[o]].p1]==legaledge[1] || points[tri[neighbortris[o]].p2]==legaledge[1] || points[tri[neighbortris[o]].p3]==legaledge[1])){\n legalcc=tri[neighbortris[o]].cc;\n }\n }\n }\n //console.log(temppt+' in '+legaledge[0]+','+legaledge[1]+','+legalcc);\n //console.log('ptintriangle: '+ptInTriangle(temppt,legaledge[0],legaledge[1],legalcc));\n //console.log(legalcc);\n if((!legalcc) || !ptInTriangle(temppt,legaledge[0],legaledge[1],legalcc)){voropolyentry.push(temppt);}\n\n }\n }\n\n\n //begin fit to box\n //order the points\n voropolyentry=lorder(voropolyentry,i);\n //fit to box\n var realvoropolyentry=voropolyentry.slice(0);\n for(var r=0;r<voropolyentry.length;r++){\n //if out of bounds\n if(voropolyentry[r].x<0 || voropolyentry[r].x>600 || voropolyentry[r].y<0 || voropolyentry[r].y>600){\n //find the r-1 and r+1 points\n var before,after;\n if(r===0){before=(voropolyentry.length-1);}else{before=r-1;}\n if(r===(voropolyentry.length-1)){after=0;}else{after=r+1;}\n //see when it intersects (except when x or y is 0 or 600)\n var tempm1,tempb1,y1,y2,x1,x2;\n tempm1=(voropolyentry[before].y-voropolyentry[r].y)/(voropolyentry[before].x-voropolyentry[r].x);\n tempb1=voropolyentry[r].y-tempm1*voropolyentry[r].x;\n var tempm2,tempb2;\n tempm2=(voropolyentry[after].y-voropolyentry[r].y)/(voropolyentry[after].x-voropolyentry[r].x);\n tempb2=voropolyentry[r].y-tempm2*voropolyentry[r].x;\n if(voropolyentry[r].x<0){\n y1=tempm1*0+tempb1;if(y1>0 && y1<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[before].x>0){realvoropolyentry=safepush({x:0,y:y1},realvoropolyentry);}}\n y2=tempm2*0+tempb2;if(y2>0 && y2<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[after].x>0){realvoropolyentry=safepush({x:0,y:y2},realvoropolyentry);}}\n }if(voropolyentry[r].x>600){\n y1=tempm1*600+tempb1;if(y1>0 && y1<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[before].x<600){realvoropolyentry=safepush({x:600,y:y1},realvoropolyentry);}}\n y2=tempm2*600+tempb2;if(y2>0 && y2<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[after].x<600){realvoropolyentry=safepush({x:600,y:y2},realvoropolyentry);}}\n }if(voropolyentry[r].y<0){\n if((voropolyentry[before].x-voropolyentry[r].x)===0){x1=voropolyentry[r].x;}//vertical line\n else{x1=(0-tempb1)/tempm1;}if(x1>0 && x1<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[before].y>0){realvoropolyentry=safepush({x:x1,y:0},realvoropolyentry);}}\n if((voropolyentry[after].x-voropolyentry[r].x)===0){x2=voropolyentry[r].x;}\n else{x2=(0-tempb2)/tempm2;}if(x2>0 && x2<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[after].y>0){realvoropolyentry=safepush({x:x2,y:0},realvoropolyentry);}}\n }if(voropolyentry[r].y>600){\n if((voropolyentry[before].x-voropolyentry[r].x)===0){x1=voropolyentry[r].x;}\n else{x1=(600-tempb1)/tempm1;}if(x1>0 && x1<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[before].y<600){realvoropolyentry=safepush({x:x1,y:600},realvoropolyentry);}}\n if((voropolyentry[after].x-voropolyentry[r].x)===0){x2=voropolyentry[r].x;}\n else{x2=(600-tempb2)/tempm2;}if(x2>0 && x2<600){removefromlist(voropolyentry[r],realvoropolyentry);if(voropolyentry[after].y<600){realvoropolyentry=safepush({x:x2,y:600},realvoropolyentry);}}\n }\n }\n }\n //re-order the points\n\n realvoropolyentry=lorder(realvoropolyentry,i);\n voropolyentry=realvoropolyentry.slice(0);\n //end fit to box\n\n\n\n //console.log(voropoly);\n //determine border situation\n\n var border={top:false,bottom:false,left:false,right:false};\n for(var q=0;q<voropolyentry.length;q++){\n if(voropolyentry[q].x<=0){border.left=voropolyentry[q];}//if(border.left){border.left=false;}else{border.left=voropolyentry[q];}}\n else if(voropolyentry[q].x>=600){border.right=voropolyentry[q];}//if(border.right){border.right=false;}else{border.right=voropolyentry[q];}}\n else if(voropolyentry[q].y<=0){border.top=voropolyentry[q];}//if(border.top){border.top=false;}else{border.top=voropolyentry[q];}}\n else if(voropolyentry[q].y>=600){border.bottom=voropolyentry[q];}//if(border.bottom){border.bottom=false;}else{border.bottom=voropolyentry[q];}}\n }\n\n var tempm,tempb,tempp1,tempp2,safesides;\n var tl={x:0,y:0};\n var tr={x:600,y:0};\n var bl={x:0,y:600};\n var br={x:600,y:600};\n if(border.top && border.left){\n tempp1=border.top;tempp2=border.left;tempm=(tempp1.y-tempp2.y)/(tempp1.x-tempp2.x);tempb=tempp1.y-tempm*tempp1.x;safesides=safeside(points[i],tempm,tempb);\n if(safesides.top && safesides.left){voropolyentry.push(tl);}else if(safesides.right && safesides.bottom){voropolyentry.push(tr);voropolyentry.push(bl);voropolyentry.push(br);}\n }\n if(border.top && border.right){\n tempp1=border.top;tempp2=border.right;tempm=(tempp1.y-tempp2.y)/(tempp1.x-tempp2.x);tempb=tempp1.y-tempm*tempp1.x;safesides=safeside(points[i],tempm,tempb);\n if(safesides.top && safesides.right){voropolyentry.push(tr);}else if(safesides.bottom && safesides.left){voropolyentry.push(bl);voropolyentry.push(br);voropolyentry.push(tl);}\n }\n if(border.bottom && border.left){\n tempp1=border.bottom;tempp2=border.left;tempm=(tempp1.y-tempp2.y)/(tempp1.x-tempp2.x);tempb=tempp1.y-tempm*tempp1.x;safesides=safeside(points[i],tempm,tempb);\n if(safesides.bottom && safesides.left){voropolyentry.push(bl);}else if(safesides.top && safesides.right){voropolyentry.push(br);voropolyentry.push(tl);voropolyentry.push(tr);}\n }\n if(border.bottom && border.right){\n tempp1=border.bottom;tempp2=border.right;tempm=(tempp1.y-tempp2.y)/(tempp1.x-tempp2.x);tempb=tempp1.y-tempm*tempp1.x;safesides=safeside(points[i],tempm,tempb);\n if(safesides.bottom && safesides.right){voropolyentry.push(br);}else if(safesides.top && safesides.left){voropolyentry.push(tl);voropolyentry.push(tr);voropolyentry.push(bl);}\n }\n if(border.right && border.left){\n tempp1=border.right;tempp2=border.left;tempm=(tempp1.y-tempp2.y)/(tempp1.x-tempp2.x);tempb=tempp1.y-tempm*tempp1.x;safesides=safeside(points[i],tempm,tempb);\n if(safesides.top){voropolyentry.push(tl);voropolyentry.push(tr);}else if(safesides.bottom){voropolyentry.push(bl);voropolyentry.push(br);}\n }\n if(border.top && border.bottom){\n tempp1=border.top;tempp2=border.bottom;\n if((tempp1.x-tempp2.x)===0){\n safesides=safesideline(points[i],tempp1.x);\n if(safesides.right){voropolyentry.push(tr);voropolyentry.push(br);}\n else if(safesides.left){voropolyentry.push(tl);voropolyentry.push(bl);}\n }\n else{\n tempm=(tempp1.y-tempp2.y)/(tempp1.x-tempp2.x);tempb=tempp1.y-tempm*tempp1.x;safesides=safeside(points[i],tempm,tempb);\n if(safesides.left){voropolyentry.push(tl);voropolyentry.push(bl);}else if(safesides.right){voropolyentry.push(tr);voropolyentry.push(br);}\n }\n }\n\n //end border situation\n\n voropolyentry=lorder(voropolyentry,i);\n\n\n //console.log(voropolyentry);\n voropoly.push({voropolyentry:voropolyentry,player:points[i].player});\n //console.log('-------------');\n }\n }\n }", "setVoronoi() {\n this.voronoi = d3\n .voronoi()\n .extent([\n [\n -1, -1\n ],\n [\n this.width + 1,\n this.height + 1\n ]\n ]);\n return this;\n }", "function voronoi() {\n var x = pointX,\n y = pointY,\n extent = null;\n\n function voronoi(data) {\n return new Diagram(data.map(function(d, i) {\n var s = [Math.round(x(d, i, data) / epsilon) * epsilon, Math.round(y(d, i, data) / epsilon) * epsilon];\n s.index = i;\n s.data = d;\n return s;\n }), extent);\n }\n\n voronoi.polygons = function(data) {\n return voronoi(data).polygons();\n };\n\n voronoi.links = function(data) {\n return voronoi(data).links();\n };\n\n voronoi.triangles = function(data) {\n return voronoi(data).triangles();\n };\n\n voronoi.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), voronoi) : x;\n };\n\n voronoi.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), voronoi) : y;\n };\n\n voronoi.extent = function(_) {\n return arguments.length ? (extent = _ == null ? null : [[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]], voronoi) : extent && [[extent[0][0], extent[0][1]], [extent[1][0], extent[1][1]]];\n };\n\n voronoi.size = function(_) {\n return arguments.length ? (extent = _ == null ? null : [[0, 0], [+_[0], +_[1]]], voronoi) : extent && [extent[1][0] - extent[0][0], extent[1][1] - extent[0][1]];\n };\n\n return voronoi;\n}", "voronoi() {\n let tris = this.tris\n\n this.circumcenters = []\n\n if (tris.length === 0) {\n this.delaunay()\n }\n\n for (let i = 0, len = tris.length; i < len; i++) {\n if (tris[i][2] == null) {\n this.circumcenters[i] = null\n } else {\n this.circumcenters[i] = circumcenter(tris[i])\n\n }\n }\n }", "function calculateVoronoi(vx, vy, nx, ny, ax, ay) {\n for (var i = 0; i < nx.length; i++) {//loop over nodes\n //tested point\n var bx = nx[i];\n var by = ny[i];\n //midway point\n var cx = (bx + ax) / 2;\n var cy = (by + ay) / 2;\n //second point on perpendicular bisector\n var dx = (ay - cy) + cx;\n var dy = (cx - ax) + cy;\n\n var discarded = [];\n var j = 0;\n while (j < vx.length) {//insert intersections and flag deletions\n var ex = vx[j];\n var ey = vy[j];\n var fx = vx[(j+1) % vx.length];\n var fy = vy[(j+1) % vx.length];\n var inE = ((dx - cx)*(ey - cy) - (ex - cx)*(dy - cy)) >= 0;\n var inF = ((dx - cx)*(fy - cy) - (fx - cx)*(dy - cy)) >= 0;\n\n if (inE && inF) {//E in, F in\n j++;\n } else if (inE && !inF) {//E in, F out\n gx = ((cx*dy - cy*dx)*(ex - fx) - (cx - dx)*(ex*fy - ey*fx)) / ((cx - dx)*(ey - fy) - (cy - dy)*(ex - fx));\n gy = ((cx*dy - cy*dx)*(ey - fy) - (cy - dy)*(ex*fy - ey*fx)) / ((cx - dx)*(ey - fy) - (cy - dy)*(ex - fx));\n vx.splice(j+1, 0, gx);\n vy.splice(j+1, 0, gy);\n j += 2;\n } else if (!inE && inF) {//E out, F in\n gx = ((cx*dy - cy*dx)*(ex - fx) - (cx - dx)*(ex*fy - ey*fx)) / ((cx - dx)*(ey - fy) - (cy - dy)*(ex - fx));\n gy = ((cx*dy - cy*dx)*(ey - fy) - (cy - dy)*(ex*fy - ey*fx)) / ((cx - dx)*(ey - fy) - (cy - dy)*(ex - fx));\n vx.splice(j+1, 0, gx);\n vy.splice(j+1, 0, gy);\n discarded.push(j);\n j += 2;\n } else {//E out, F out\n discarded.push(j);\n j++;\n }\n }\n\n while (discarded.length != 0) {//discard flagged vertices\n j = discarded.pop();\n vx.splice(j, 1);\n vy.splice(j, 1);\n }\n }\n}", "function makeMesh(pts, extent) {\n extent = extent || defaultExtent;\n\n // compute the Voronoi polygons\n var vor = voronoi(pts, extent);\n var vxs = [];\t// vertex locations\n var vxids = {};\t// vertex ID #s\n var adj = [];\t// adjacent vertices\t\n var edges = [];\t// list of vertex IDs and positions\n var tris = [];\t// coordinates of neighbors of this vertex\n\n // for each edge of each Voronoi polygon\n for (var i = 0; i < vor.edges.length; i++) {\n\t// get the two end points of this edge\n var e = vor.edges[i];\n if (e == undefined) continue;\n\n\t// lookup (or assign) their vertex IDs\n var e0 = vxids[e[0]];\n if (e0 == undefined) {\n e0 = vxs.length;\t\n vxids[e[0]] = e0;\n vxs.push(e[0]);\n }\n var e1 = vxids[e[1]];\n if (e1 == undefined) {\n e1 = vxs.length;\n vxids[e[1]] = e1;\n vxs.push(e[1]);\n }\n\n\t// note that each end-point is adjacent to the other\n adj[e0] = adj[e0] || [];\n adj[e0].push(e1);\n adj[e1] = adj[e1] || [];\n adj[e1].push(e0);\n\n\t// add indices and coordinates to known edges\n edges.push([e0, e1, e.left, e.right]);\n\n\t// note all edges entering the left end point\n tris[e0] = tris[e0] || [];\n if (!tris[e0].includes(e.left)) tris[e0].push(e.left);\n if (e.right && !tris[e0].includes(e.right)) tris[e0].push(e.right);\n\n\t// note all edges entering the right end point\n tris[e1] = tris[e1] || [];\n if (!tris[e1].includes(e.left)) tris[e1].push(e.left);\n if (e.right && !tris[e1].includes(e.right)) tris[e1].push(e.right);\n }\n\n // the new mesh contains all of these things\n var mesh = {\n pts: pts,\t// a set of nicely spaced random points\n vor: vor,\t// Voronoi tesselation of those points\n vxs: vxs,\t// locations of each vertex\n adj: adj,\t// indices of neighbors\n tris: tris,\t// coordinates of neighbors\n edges: edges,\t// the set of all edges\n extent: extent\t// the scale \n }\n\n /*\n * mesh.map(f) applies f to every vertex in mesh\n */\n mesh.map = function (f) {\n var mapped = vxs.map(f);\n mapped.mesh = mesh;\n return mapped;\n }\n return mesh;\n}", "function voronoi(pts, extent) {\n extent = extent || defaultExtent;\n var w = extent.width/2;\n var h = extent.height/2;\n return d3.voronoi().extent([[-w, -h], [w, h]])(pts);\n}", "function pushToBoundary() {\r\n var rectangle = [[0,0],[0,height],[width,height],[width,0]],\r\n temp,\r\n j,\r\n boundaryPolygons = [];\r\n\t\r\n\t// loop through each region and move vertices of regions that intersect\r\n\t// the boundaries\r\n\tfor (var i = 0; i < voronoiNew.length; i++) {\r\n\t\tj = 0;\r\n\t\twhile (j < voronoiNew[i].length && inBoundary(voronoiNew[i][j][0],voronoiNew[i][j][1])) {\r\n\t\t\tj++;\r\n\t\t}\r\n\t\tif (j < voronoiNew[i].length && !inBoundary(voronoiNew[i][j][0],voronoiNew[i][j][1])) {\r\n\t\t\tverticesNew[i] = projectToBoundary(verticesNew[i][0],verticesNew[i][1],voronoiNew[i],rectangle);\r\n\t\t\tboundaryPolygons.push(i);\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn boundaryPolygons;\r\n}", "function simplifyCells(){\n cells = [];\n for (var i = 0; i < voronoiDiagram.cells.length; i++) {\n var vertices = [];\n for (var j = 0; j < voronoiDiagram.cells[i].halfedges.length; j++) {\n vertices.push([voronoiDiagram.cells[i].halfedges[j].getStartpoint().x, voronoiDiagram.cells[i].halfedges[j].getStartpoint().y]);\n }\n cells.push(vertices);\n }\n }", "relax(diagram, idEdges){\n // Given voronoi diagram, adjust sites\n let newSites = [];\n let cells = diagram.cells;\n for(let cell of cells){\n let site = cell.site;\n let id = site.voronoiId;\n let verticies = idEdges[id].edges;\n \n let sumX = 0;\n let sumY = 0;\n \n for(let vertex of verticies){\n sumX += vertex.x;\n sumY += vertex.y;\n }\n \n let midX = sumX / verticies.length;\n let midY = sumY / verticies.length;\n \n newSites.push({x: midX, y: midY});\n }\n return newSites;\n }", "function createVertices(vertices) {\n\n //For each vertice in the graph\n $.each(vertices, function () {\n\n //create vertex and append it to drawing area\n var tempVertex = jQuery('<div/>',{\n id: this.label,\n text: this.label\n }).appendTo('#drawing-area');\n\n //add vertex-class\n tempVertex.addClass('component');\n\n //Set appropriate coordinates of vertex\n tempVertex.css({\n 'left': this.xCoordinate*100,\n 'top' : this.layer*100\n });\n\n if (this.dummy) {\n tempVertex.addClass('invisiburu')\n }\n\n //Update references in jsPlumb\n jsPlumb.setIdChanged(this.label, this.label);\n });\n}", "nodeEdges(v,w){var inEdges=this.inEdges(v,w);if(inEdges){return inEdges.concat(this.outEdges(v,w))}}", "constructor(){\n\t\tthis.voronoi = new Voronoi();\n\t\tthis.sites = [];\n\n\t\tthis.diagram = undefined;\n\n\t\tthis.dist = 0;\n\t\tthis.coop_cost = 0;\n\t\tthis.totalNumberOfCells = 0;\n\t\tthis.percentOfDefectingCells = 0;\n\t\tthis.cooperatingChance = 0.5;\n\t\tthis.height = 1000;\n\t\tthis.width = 1000;\n\n\t\tthis.chart = {};\n\t\tthis.sitesList = [];\n\t\tthis.bbox = {\n\t\t\txl: 0,\n\t\t\txr: this.height,\n\t\t\tyt: 0,\n\t\t\tyb: this.width\n\t\t};\n\t}", "function Test_Voronoi ( testenv ) { \n var ctx; \n var vertexbuffer, indexbuffer, program; \n var ntess = 16; // == triangles per point\n \n var allpoints = { red:[], green:[], blue:[] };\n \n\tfunction addRandomPoint ( points ) {\n var point = {\n x:Math.random()*2-1, y:Math.random()*2-1, radius:1,\n r:1,g:1,b:1,a:1,\n dx:Math.random()-.5,dy:Math.random()-.5, \n ddx:0, ddy:0 \n };\n points.push ( point );\n }\n \n\tfunction animatePoints ( points, dt ) {\n dt*=.2;\n\t\tfor ( var i= 0; i<points.length; i++ ) {\n var p = points[i];\n if ( p.x < -1 || p.x > 1 ) p.dx = -p.dx;\n if ( p.y < -1 || p.y > 1 ) p.dy = -p.dy;\n\t\t\tp.x += p.dx * dt;\n p.y += p.dy * dt; \n\t\t}\n } \n\t\t \n function renderCircles ( points ) {\n ctx.clear( 1, 1, 1, 1, 0, 0, Context3DClearMask.DEPTH | Context3DClearMask.STENCIL ); // only clear depth and stencil\n\t\t\t\n ctx.setProgram ( program );\n ctx.setVertexBufferAt ( 0, vertexbuffer, 0, \"float4\" ); \t\t\t\t\t\n ctx.setDepthTest ( true, \"greater\" ); \n\n // scale and aspect\n ctx.setProgramConstants ( \"vertex\", 16, 1, testenv.w/testenv.h, 3/Math.sqrt(points.length), 0 );\n \n for ( var i = 0; i<points.length; i++ ) {\n var p = points[i]; \n ctx.setProgramConstants ( \"vertex\", 0, p.x, p.y, 1, p.radius, \n p.r, p.g, p.b, p.a, \n p.dx, p.dy, 0, 0,\n p.ddx, p.ddy, 0, 0 ); \n ctx.drawTriangles( indexbuffer, 0, ntess );\n }\n }\n \n function OnEnterFrame ( t ) { \t\n ctx.clear( 1, 1, 1, 1, 0, 0, Context3DClearMask.COLOR ); // only clear color\t\n \n ctx.setColorMask( true, false, false, false );\n animatePoints ( allpoints.red, testenv.dt );\n renderCircles ( allpoints.red );\n \n ctx.setColorMask( false, true, false, false );\n animatePoints ( allpoints.green, testenv.dt );\n renderCircles ( allpoints.green );\n \n ctx.setColorMask( false, false, true, false );\n animatePoints ( allpoints.blue, testenv.dt );\n renderCircles ( allpoints.blue ); \n\t\t\t\t\t \n ctx.present ( ); \n }\n \n function OnContext3DCreated ( newctx ) {\n ctx = newctx; \n \n // buffer that holds a circle\n var r = 1.0; \n indexbuffer = ctx.createIndexBuffer ( ntess*3 );\n vertexbuffer = ctx.createVertexBuffer ( ntess+1, 4 ); // 4 floats per vertex xy, r, angle\n // center vertex, first vertex\n var vdata = new ByteArray; \n vdata.writeFloat ( 0 ); \n vdata.writeFloat ( 0 ); \n vdata.writeFloat ( 1 ); \n vdata.writeFloat ( 0 ); \n \n var idata = new ByteArray; \n for ( var tess = 0; tess < ntess; tess++ ) {\n var tn = tess/ntess; \t\t\t\t\t\t\t\t\t\n vdata.writeFloat ( Math.sin(tn*2*Math.PI)*r ); \n vdata.writeFloat ( Math.cos(tn*2*Math.PI)*r );\n vdata.writeFloat ( 0 ); \n vdata.writeFloat ( tn );\t\t\t\t\t\t\t\t \t\t\t\t\n idata.writeUnsignedShort( 0 );\n if ( tess!=0 ) {\n idata.writeUnsignedShort( tess );\n idata.writeUnsignedShort( tess+1 );\t\t\t\t\t\n } else {\n idata.writeUnsignedShort( tess+1 );\n idata.writeUnsignedShort( ntess );\t\t\t\t\t\t\t\t\t\t\n }\t\t\t\t\n }\n indexbuffer.uploadFromByteArray(idata,0,0,ntess*3);\n vertexbuffer.uploadFromByteArray(vdata,0,0,ntess+1); \t\t \n \n // program\n program = ctx.createProgram ( )\t \n var agalbytes = AssembleAGAL ( \n \"part fragment 1 \\n\"+ \n \" mul ft0, vi0, vi0 \t \\n\" +\t\t// square color\n \" mov fo0, ft0\t\t\t \\n\" + \t\t// output \n \"endpart \\n\\n\"+\n \"part vertex 1 \\n\"+\n \" mul vt0.xy, va0.xy, vc16.z\t\t\\n\" +\t // c0=posx,posy,1,strength va0 = dx,dy,r,angle\n \" add vt0.xy, vt0.xy, vc0.xy\t\t\\n\" +\t // \n \" mul vt0.xy, vt0.xy, vc16.xy \\n\" + // scale by screen aspect\n \" mov vt0.z, va0.z \\n\" + // z==r \n \" mov vt0.w, vc0.z \\n\" + // w==1\t\t\t\t\n \" sub vt1.x, vc0.z, va0.z \\n\" + // invert dist\n \" mul vi0, vc1, vt1.x\t \\n\" +\t // copy color\t\t\t\t\t\t\t\n \" mov vo0, vt0 \\n\" + \n \"endpart \\n\" \n ); \n program.uploadFromAGALByteArray ( agalbytes.vertex.data, agalbytes.fragment.data ); \n \n // some initial random points\n for ( var np = 0; np<256; np++ ) {\n addRandomPoint ( allpoints.red );\n addRandomPoint ( allpoints.green );\t\n\t\t\taddRandomPoint ( allpoints.blue );\t\n } \n \n // anim handling\n testenv.startOnEnterFrame ( OnEnterFrame ); \n }\n \n function OnAbortTest ( ) {\n // automatically removes frame handler \n if ( ctx ) \n ctx.dispose(); \n else throw \"No WebGL context.\";\n }\n \n testenv.abortcallback = OnAbortTest; \n RequestContext3D ( testenv.canvas, OnContext3DCreated, testenv.testmode );\n}", "copyUvs() {\n this.eachPoint((point, indexOfVertexInFace) => {\n point.uvs.add(this.myFaceUvs[indexOfVertexInFace]);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loop through the answers nodeList using array's foreach method and assign the createOverlay function as a click event for every answer. // get the child nodes of definitionTest
function bindAnswers(){ answers = document.getElementById('definitionTest').childNodes; Array.prototype.forEach.call(answers, function(answer){ answer.addEventListener('click', createOverlay); }); }
[ "function addAnswersEventListeners(){\ndocument.querySelectorAll('.answer').forEach(item => {\n item.addEventListener('click', event => { \n checkAnswer(item); \n fillAnswersSection();\n })\n})\n}", "function dispQuestion(question) { qNameElement.textContent=question.question\n question.answers.forEach(answer => {\n answerItem=document.createElement(\"li\")\n myAns=document.createElement(\"a\")\n myAns.classList.add(\"anchor\")\n myAns.setAttribute('href',\"#\")\n myAns.textContent=answer.text\n answerItem.appendChild(myAns)\n // Check if the correct property is true, if so, then assign it to the answer \n if(answer.correct){\n myAns.dataset.correct=answer.correct\n }\n // adding eventListener to our answers\n myAns.addEventListener(\"click\",selectAnswer)\n lAnsElement.appendChild(answerItem)\n }) \n }", "createQuiz () {\r\n // Get question list\r\n let questions = this.xml.getElementsByTagName('question')\r\n // Loop the question list to get \"labely\", \"labelX\", \"tagetX\", \"tagetY\" to set the location of labels and tagetPoints\r\n Array.from(questions).forEach(question => {\r\n let labelY = question.attributes.getNamedItem('labely').value\r\n let labelX = question.attributes.getNamedItem('labelx').value\r\n let width = question.attributes.getNamedItem('width').value\r\n let height = question.attributes.getNamedItem('height').value\r\n let labelEntry = {\r\n labelY: labelY,\r\n labelX: labelX,\r\n width: width,\r\n height:height\r\n }\r\n\r\n this.labels.push(labelEntry)\r\n })\r\n\r\n let boxes = this.xml.getElementsByTagName('pair')\r\n Array.from(boxes).forEach(aBox => {\r\n let label = aBox.getElementsByTagName('question')[0].innerHTML\r\n let targetX = aBox.attributes.getNamedItem('targetx').value\r\n let targetY = aBox.attributes.getNamedItem('targety').value\r\n let width = aBox.attributes.getNamedItem('width').value\r\n let height = aBox.attributes.getNamedItem('height').value\r\n let dir = 'images/' + aBox.attributes.getNamedItem('imgName').value\r\n let contentsXml = aBox.getElementsByTagName('answer')\r\n let contents = Array.from(contentsXml).map(element => element.innerHTML)\r\n let answers = []\r\n\r\n contents.forEach(aContent => {\r\n let newAnswer = new Answer(aContent,dir,width,height)\r\n answers.push(newAnswer)\r\n })\r\n\r\n let questionAnswerSet = {\r\n question: label,\r\n answers: answers,\r\n targetX: targetX,\r\n targetY: targetY\r\n }\r\n this.quiz.push(questionAnswerSet)\r\n })\r\n }", "function generateAnswers() {\n isGameOver()\n var question = questionsList[questionsIndex].question\n $(\"#question\").text(question)\n $(\"#question\").show()\n for (var i = 0; i < 4; i++) {\n var answerSelectList = questionsList[questionsIndex].answerChoices[i]\n var correctChoice = questionsList[questionsIndex].correctChoice\n var answerSelect = $(\"<div>\");\n\n answerSelect.addClass(\"answer-detail\")\n answerSelect.attr(\"answer-select\", answerSelectList)\n answerSelect.attr(\"data-answer-detail\", [i])\n answerSelect.text(answerSelectList)\n\n $(\"#answer-box\").append(answerSelect)\n $(\"#answer-detail\").addClass(\"name\")\n $(\"#answer-detail\").attr(\"answer-select\", answerSelectList)\n $(\"#answer-detail\").attr(\"answer-index\", correctChoice)\n }\n onClick()\n }", "function buildQuestionsChoices(questionNum){\n // pulls question element with a question from quizQuestionsAnswers\n quizQuestionEl.innerHTML = quizQuestionsAnswers[questionNum].question;\n // loop that adds the questions as children to the quiz-choice class\n for (var i = 0; i < quizChoiceEl.length; i++){\n quizChoiceEl[i].innerHTML = quizQuestionsAnswers[questionNum].answers[i];\n quizChoiceEl[i].firstElementChild.addEventListener(\"click\", selectAnswer);\n }\n}", "function addAnswerBtn() {\n for (i = 1; i < 5; i++) {\n const answerButtons = document.getElementById('box' + `${i}`)\n answerButtons.addEventListener('click', chooseAnswer)\n }\n}", "function showAnswers(answers) {\n // clean up and old buttons \n cleanupButtons();\n\n\n answers.forEach(function(answer) {\n\n var answerButton = document.createElement('button');\n\n answerButton.classList.add(\"btn\");\n answerButton.classList.add(\"btn-primary\");\n answerButton.classList.add(\"m-2\");\n // answerButton.classList.add(\"col-md-2\");\n answerButton.innerText = answer.possibleAnswer;\n\n // mark the button as correct in its data-set attribute if correct=true on the answer object\n if (answer.correct) {\n answerButton.dataset.correct = \"true\";\n }\n\n answerButton.addEventListener('click', function(event) {\n event.stopPropagation();\n checkAnswer(event);\n }\n\n )\n buttonAreaElement.appendChild(answerButton);\n\n\n });\n\n\n}", "function addOnclickListeners(total) {\n for (var i = 0; i < total; i++) {\n document.querySelectorAll('.answer-block')[i].onclick = showPopUp; // add listener on ans-blocks\n }\n\n document.getElementsByClassName('quest-block__header')[0].onclick = showPopUp; // add listener on header\n\n\n document.getElementById('close-icon').onclick = hidePopUp; // add onclick on close-icon\n document.getElementById('backgr-pop-up').onclick = hidePopUp; // add onclick on backgr\n}", "processAnswers(childIndex) {\n var totalElements = this.document.body.childNodes.length;\n var oldIndex = this.questionIndex;\n this.questionIndex = 0;\n\n for (var i = childIndex + 1; i < totalElements; i++) {\n var node = this.document.body.childNodes[i];\n console.log(this.questionIndex);\n if (node.tagName == \"OL\") {\n for (var j = 0; j < node.children.length; j++) {\n var answers = node.children[j].textContent.split(/[,\\/]/);\n for (var k = 0; k < answers.length; k++) {\n this.questions[this.questionIndex].addAnswer(answers[k].trim());\n }\n this.questionIndex++;\n }\n break;\n }\n }\n this.questionIndex = oldIndex;\n }", "function createQuestion(e){\n\tif (a === allQuestions.length){\n\t\ta = 0; // \n\t}\n\t// Check which question we are on, if at last question, then reset.\n\tvar question = allQuestions[a].question;\n\tvar choices = allQuestions[a].choices;\n\tvar answer = allQuestions[a].answer;\n\n\t// 1.\n\t/*\n\n\t*/\n\t// 2. \n\n\tvar newQuestionDiv = document.createElement('div'); // Div for questions\n\t\tnewQuestionDiv.id = \"questions\"; // Div id \n\t\tquestionPlace.appendChild(newQuestionDiv);\n\tvar theQuestion = document.getElementById('questions');\n\t\ttheQuestion.innerHTML = question;\n\n\n\t// 3. \n\n\tvar newChoicesDiv = document.createElement('div'); // separate DIV for \"choices\";\n\t\tnewChoicesDiv.id = \"choices\";\n\t\tquestionPlace.appendChild(newChoicesDiv);\n\n\n\t\tfor (var i = 0; i < choices.length; i++){\n\t\t\tvar singleChoice = document.createElement('div'); // creating a separate DIV for each button so I can style them individually\n\t\t\t\tsingleChoice.id = \"choice\" + i;\n\t\t\t\tnewChoicesDiv.appendChild(singleChoice);\n\n\n\t\t\tvar newNode = document.createElement(\"input\");\n\t\t\tvar newLabel = document.createElement(\"label\");\n\t\t\tvar newBr = document.createElement(\"br\");\n\t\t\tvar newParagraph = document.createElement('p');\n\t\t\t\tnewNode.type = \"radio\";\n\t\t\t\tnewNode.value = i + 1; //want the value to start at 1 since we want our answer values to start at 1\n\t\t\t\tnewNode.name = \"test\";\n\t\t\t\tnewNode.id = \"button\" + i;\n\t\t\t\tnewNode.label = \"button\";\n\t\t\t\tnewLabel.setAttribute('for', 'button' + i);\n\t\t\t\tnewLabel.textContent = choices[i];\n\t\t\t\tsingleChoice.appendChild(newNode);\n\t\t\t\tsingleChoice.appendChild(newLabel);\n\t\t\t}\n\n\t\t\t// For fading pictures in and out\n\n\t\t\tvar newPic = $('#choices div');\n\t\t\t$('#choices div').mouseenter(function(){ // when mouse enters the button\n\t\t\tvar thisImage = this.id;\n\t\t\t$('#steve').fadeOut(changeImage).fadeIn();\n\t\t\tfunction changeImage(){\n\t\t\t\t\tswitch(thisImage){\n\t\t\t\t\t\tcase 'choice0':\n\t\t\t\t\t\t\t$('#steve').attr('src', allQuestions[a].pictures[0]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'choice1':\n\t\t\t\t\t\t\t$('#steve').attr('src', allQuestions[a].pictures[1]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'choice2':\n\t\t\t\t\t\t\t$('#steve').attr('src', allQuestions[a].pictures[2]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'choice3':\n\t\t\t\t\t\t\t$('#steve').attr('src', allQuestions[a].pictures[3]);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function answEvents() {\n var buttons = document.getElementsByClassName(\"button\");\n for (var i = 0; i < buttons.length; i++) {\n buttons[i].addEventListener(\"click\", function() {\n // if the question is answered, nothing will happen to the buttons\n if (this.parentNode.className != \"answered\") {\n if (this.id == \"correct\") {\n this.style.backgroundColor = \"Lightgreen\";\n score++;\n scoreText.innerHTML = score;\n }\n else {\n this.style.backgroundColor = \"Lightcoral\";\n var siblings = this.parentNode.children;\n var corr = siblings.correct;\n corr.style.backgroundColor = \"rgba(144, 238, 144, 0.5)\";\n corr.style.transition = \"1s\"\n }\n this.parentNode.setAttribute(\"class\", \"answered\");\n }\n });\n }\n }", "function createQuestionContainer() {\n //Append to article.collection\n //Clone article.collection > section.question\n var collection = $(\"article.collection\");\n var template = collection.find(\"template.template.question\").html();\n //console.log(template);\n collection.append(template);\n\n //Then add event listener(s) as template doesnt retain them\n selectAnswerTypeListener();\n removeThisQuestionListener();\n collapseQuestionListener();\n attachTextareaListener();\n}", "function setupClicks(areas){\n for (var i = 0; i < areas.length; i++) {\n let the_area = areas[i];\n areas[i].path.click(\n function(area){\n quiz.checkClick(the_area.name);\n }\n );\n }\n return areas\n}", "function init() {\n // Loop through the array and set the elements into the DOM\n answers.forEach(function(answer, index) {\n createAnswerItem(answer, index, false);\n });\n}", "answerButtonListener() {\n const btnContainer = document.querySelector('.answer_buttons');\n btnContainer.addEventListener('click', e => app.checkAnswer(e.target.dataset.art));\n }", "addEventListeners() {\n if (this.question.type === 'simple') {\n const okButton = this.shadowRoot.querySelector('.ok');\n okButton.addEventListener('click', (e) => {\n this.handleAnswer('yes');\n });\n\n const noButton = this.shadowRoot.querySelector('.no');\n noButton.addEventListener('click', (e) => {\n this.handleAnswer('no');\n });\n const skipButton = this.shadowRoot.querySelector('.skip');\n skipButton.addEventListener('click', (e) => {\n this.handleAnswer('skip');\n });\n }\n if (this.question.type === 'multi') {\n const nextButton = this.shadowRoot.querySelector('.next');\n nextButton.addEventListener('click', (e) => {\n this.handleAnswer('next');\n });\n }\n // Add back button if available\n if (this.qNumber !== 1) {\n const previousButton = this.shadowRoot.querySelector('.previous');\n previousButton.addEventListener('click', (e) => {\n this.handleAnswer('previous');\n });\n }\n }", "function initiateGame(playerName) {\n document.getElementById(\"name\").innerText = playerName;\n \n let newLives = \"5\";\n document.getElementById(\"lives\").innerText = newLives;\n\n let newScore = \"0\";\n document.getElementById(\"score\").innerText = newScore;\n\n for (let element of elements) {\n \n element.addEventListener(\"click\", afterClickElements, true);\n\n let eleName = element.getAttribute(\"data-element-name\");\n let eleNum = element.getAttribute(\"data-element-number\");\n let eleSym = element.getAttribute(\"data-element-symbol\");\n addToArray(eleName, eleNum, eleSym);\n }\n\n shuffleArray();\n runQuiz();\n}", "function createTitleAnswers(obj,count) {\r\n if(questionIndex < count){\r\n //create h2\r\n let QTitle = document.createElement('h2');\r\n //create title text\r\nlet titleText = document.createTextNode(obj['title']);\r\n //append title text inton q-title\r\nQTitle.appendChild(titleText);\r\n //append q-title into title parent div\r\nquestionTitle.appendChild(QTitle);\r\n //create input answers\r\nfor(let i = 1; i < 5 ; i++){\r\n //create mainDiv\r\n let mainDiv = document.createElement('div');\r\n //add class\r\n mainDiv.className = \"Q-answer\";\r\n //create input answer\r\n let inputAnswer = document.createElement('input');\r\n //create or add name id dataset type\r\n inputAnswer.type = \"radio\";\r\n inputAnswer.name = \"question\";\r\n inputAnswer.id = `answer_${i}`;\r\n //to deal with q-answer\r\n inputAnswer.dataset.answer = obj[`answer_${i}`];\r\n //add focus on first answer\r\n if(i === 1){\r\n inputAnswer.checked = true;\r\n } \r\n //create label\r\n let labelAnswer = document.createElement('label');\r\n //add for attr\r\n labelAnswer.htmlFor = `answer_${i}`;\r\n //create label text\r\n let labelText = document.createTextNode(obj[`answer_${i}`]);\r\n //append label text into label answer\r\n labelAnswer.appendChild(labelText);\r\n //append input-answer and label-answer into main-div\r\n mainDiv.appendChild(inputAnswer);\r\n mainDiv.appendChild(labelAnswer);\r\n //append main-div into q-area\r\n questionArea.appendChild(mainDiv);\r\n} \r\n }\r\n \r\n}", "function display(i,event,k) {\n if($(event.target).attr('class') == 'square stop'){\n return\n }\n $(event.target).css('color', 'blue')\n $(event.target).css('text-shadow', '3px 3px #0000FF')\n $(event.target).addClass('stop')\n $('.modal').css('display','block')\n const $div = $('<div>').text(question[k][i].toUpperCase()).addClass('question')\n const $ul = $('<ul>').addClass('qList')\n \n for(let j = 0; j < answers[k][i].length; j++){\n const $li = $('<li>').text(answers[k][i][j].name.toUpperCase())\n $li.on('click',() => checkAnswer(i,j,k))\n $ul.append($li)\n }\n $('.text_box').append($div)\n $('.text_box').append($ul)\n \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bnodes aren't good for tpf clients so would need to give the reactionparticipant a URI
async function processReactant(node, s, nParticipant) { if(node.name() !== 'reactant') throw new Error('expected reactant, got ' + node.name()) let participantUri = s + '#participant' + nParticipant let chebiID = node.get('cml:molecule/cml:identifier', { cml: 'http://www.xml-cml.org/schema/cml2/react' }).attr('value').value() .split(':')[1] let chebiURI = 'http://purl.obolibrary.org/obo/CHEBI_' + chebiID let compoundERI = await urisToERI([ chebiURI ], 'Compound') return [ { s, p: 'http://w3id.org/synbio/ont#hasReactionParticipant', o: participantUri }, { s: participantUri, p: 'http://w3id.org/synbio/ont#compound', o: compoundERI }, { s: participantUri, p: 'http://w3id.org/synbio/ont#reactionSide', o: 'http://w3id.org/synbio/ont#LeftSide' } ] }
[ "function rtcommPresenceNode(n) {\r\n RED.nodes.createNode(this,n);\r\n\t var subtopic = n.subtopic;\r\n this.topic = (n.topic || '/rtcomm/')+'sphere/'+subtopic;\r\n this.broker = n.broker;\r\n this.brokerConfig = RED.nodes.getNode(this.broker);\r\n this.rtcConnector = null;\r\n\t var endpoint = n.fromendpoint; \r\n\t var unique = n.unique || false;\r\n\r\n var node = this;\r\n if (this.brokerConfig) {\r\n this.status({fill:\"red\",shape:\"ring\",text:\"disconnected\"});\r\n //this.client = connectionPool.get(this.brokerConfig.broker,this.brokerConfig.port,this.brokerConfig.clientid,this.brokerConfig.username,this.brokerConfig.password);\r\n var config = {\r\n 'server': this.brokerConfig.broker,\r\n 'port': this.brokerConfig.port,\r\n 'eventPath': this.topic,\r\n 'unique': unique};\r\n var rtcConnector = this.rtcConnector = rtcommPresence.get(config);\r\n rtcConnector.on('connected',function(){\r\n node.log('connected');\r\n node.status({fill:\"green\",shape:\"dot\",text:\"connected\"});\r\n });\r\n rtcConnector.on('disconnected',function(){\r\n node.log('disconnected');\r\n node.status({fill:\"red\",shape:\"ring\",text:\"disconnected\"});\r\n });\r\n rtcConnector.on('error',function(){\r\n node.log('error');\r\n node.status({fill:\"red\",shape:\"ring\",text:\"error\"});\r\n });\r\n\r\n // Start the monitor\r\n rtcConnector.start();\r\n\r\n // Filter Callback\r\n var processMessage = function processMessage(topic, message) {\r\n\t\t \r\n\t\t var endpointStr = /([^\\/]+$)/.exec(topic);\r\n\t\t var filter = endpoint; \r\n\t\t \r\n\t\t\tfilter = filter.replace(\"*\",\".*\");\r\n\t\t var reEx = new RegExp(\"(\" +filter+\")\");\r\n\t\t var filterMatch = reEx.exec(endpointStr);\r\n\t\t \r\n\t\t if(filterMatch){\r\n var msg = {};\r\n \r\n\t\t if(message.length == 0){\r\n\t\t\t msg.payload = {\"state\":\"unavailable\", 'endpointID': endpointStr[1]};\r\n\t\t\t msg.topic = topic;\r\n\t\t\t node.send(msg);\r\n\t\t\t \r\n\t\t }\r\n\t\t else{\t\t \r\n\t\t\t try {\r\n msg.payload = JSON.parse(message);\r\n } catch(e) {\r\n node.error(\"Message cannot be parsed as an Object: \"+message);\r\n }\r\n\t\t \r\n if ( \r\n typeof msg.payload === 'object' &&\r\n msg.payload.method === 'DOCUMENT' ) {\t \r\n \r\n msg.topic = topic;\r\n\t\t\tmsg.payload = {\r\n\t\t\t\t'addressTopic': msg.payload.addressTopic,\r\n\t\t\t\t'appContext': msg.payload.appContext,\r\n\t\t\t\t'state': msg.payload.state,\r\n\t\t\t\t'alias': msg.payload.alias,\r\n\t\t\t\t'userDefines': msg.payload.userDefines,\r\n\t\t\t\t'endpointID': endpointStr[1]\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n } else {\r\n node.error('Unable to form message for topic:'+topic+' and message: '+message); \r\n msg = null;\r\n }\r\n node.send(msg);\r\n\t\t }\r\n\t\t }\r\n };\r\n this.filter = rtcConnector.allPresenceEvents(processMessage);\r\n\t\t this.log('Added Filter - '+this.filter.subscriptions);\r\n } else {\r\n this.error(\"missing broker configuration\");\r\n }\r\n }", "getLink() {\n switch(this.note.verb) {\n case 'requested':\n case 'invited':\n return '/narrative/' + this.note.object.id;\n default:\n return '';\n }\n }", "function RtcommRtcConnectorNode(n) {\r\n RED.nodes.createNode(this,n);\r\n this.topic = (n.topic || '/rtcomm/')+'event';\r\n this.broker = n.broker;\r\n this.brokerConfig = RED.nodes.getNode(this.broker);\r\n this.rtcConnector = null;\r\n\r\n //\tThis defines the event filter\r\n \r\n this.started = n.started || false;\r\n this.failed = n.failed || false;\r\n this.modified = n.modified || false;\r\n this.stopped = n.stopped || false;\r\n this.fromEndpoint = n.fromendpoint;\r\n this.toEndpoint = n.toendpoint;\r\n var unique = n.unique || false;\r\n\r\n var node = this;\r\n if (this.brokerConfig) {\r\n this.status({fill:\"red\",shape:\"ring\",text:\"disconnected\"});\r\n //this.client = connectionPool.get(this.brokerConfig.broker,this.brokerConfig.port,this.brokerConfig.clientid,this.brokerConfig.username,this.brokerConfig.password);\r\n var config = {\r\n 'server': this.brokerConfig.broker,\r\n 'port': this.brokerConfig.port,\r\n 'eventPath': this.topic,\r\n 'unique': unique};\r\n var rtcConnector = this.rtcConnector = rtcommRtcConnector.get(config);\r\n rtcConnector.on('connected',function(){\r\n node.log('connected');\r\n node.status({fill:\"green\",shape:\"dot\",text:\"connected\"});\r\n });\r\n rtcConnector.on('disconnected',function(){\r\n node.log('disconnected');\r\n node.status({fill:\"red\",shape:\"ring\",text:\"disconnected\"});\r\n });\r\n rtcConnector.on('error',function(){\r\n node.log('error');\r\n node.status({fill:\"red\",shape:\"ring\",text:\"error\"});\r\n });\r\n\r\n // Start the monitor\r\n rtcConnector.start();\r\n\r\n // Filter Callback\r\n var processMessage = function processMessage(topic, message) {\r\n var msg = {};\r\n //node.log('.processMessage('+topic+')+ '+message);\r\n try {\r\n msg.payload = JSON.parse(message);\r\n\t\t\tvar timestamp = msg.payload.timestamp;\r\n } catch(e) {\r\n node.error(\"Message cannot be parsed as an Object: \"+message);\r\n }\r\n var match = /\\/(session)\\/(started|stopped|modified|failed)\\/(.+$)/.exec(topic);\r\n if (match &&\r\n typeof msg.payload === 'object' &&\r\n msg.payload.method === 'RTCOMM_EVENT_FIRED' ) {\r\n //console.log('MATCH ARRAY'+match);\r\n msg.payload={};\r\n msg.topic = topic;\r\n\t\t\tmsg.payload.timestamp=timestamp;\r\n msg.payload.action = match[2]|| 'unknown';\r\n\r\n var m = /\\//.test(match[3]) ? /(.+)\\/(.+)/.exec(match[3]) : [null, match[3], null];\r\n msg.payload.fromendpointid = m[1] || 'unknown';\r\n if (m[2]) { \r\n msg.payload.toendpointid = m[2];\r\n }\r\n\r\n } else {\r\n node.error('Unable to form message for topic:'+topic+' and message: '+message); \r\n msg = null;\r\n }\r\n node.send(msg);\r\n };\r\n this.filter = rtcConnector.addFilter({\r\n 'category': {\r\n 'session': true,\r\n\t\t\t'registration': false\r\n },\r\n 'action': {\r\n 'started':this.started,\r\n 'modified':this.modified,\r\n 'stopped':this.stopped, \r\n 'failed':this.failed },\r\n 'toendpointid': this.toEndpoint,\r\n 'fromendpointid':this.fromEndpoint},\r\n processMessage);\r\n\r\n this.log('Added Filter - '+this.filter.subscriptions);\r\n } else {\r\n this.error(\"missing broker configuration\");\r\n }\r\n }", "function convertRelationshipUrl() {\n}", "function getClickHandlerNubRelLink() {\n \n/* at some point we will probably want to retain a history of preferred altrelationships, etc.\n * these should be stored/retrieved from a base-level query info object that is passed back\n * and forth from the server. for now we are just keeping things simple and not remembering\n * anything about previous relationships.\n * var altrelids = new Array(); */\n\n var focalnodeid = nub.nodes[j].parentid; // inherit this, passed to parent function\n var domsource = nub.nodes[j].source;\n\n var jsonargs = {\"domsource\": domsource}; \n var jsonquerystr = buildJSONQuery(jsonargs);\n\n return function() {\n paper.clear();\n var loadargs = {\"url\": buildUrl(focalnodeid),\n \"method\": \"POST\",\n \"jsonquerystring\": jsonquerystr};\n// alert(jsonquerystr);\n paper.remove();\n loadData(loadargs);};\n }", "constructor(msgNodeURL) {\n this._msgNodeURL = msgNodeURL;\n }", "function amqpReceiverNode(config) {\n\n RED.nodes.createNode(this, config);\n\n // get endpoint configuration\n this.endpoint = RED.nodes.getNode(config.endpoint);\n // get all other configuration\n this.address = config.address;\n this.autoaccept = config.autoaccept;\n this.creditwindow = config.creditwindow;\n this.dynamic = config.dynamic;\n this.sndsettlemode = config.sndsettlemode;\n this.rcvsettlemode = config.rcvsettlemode;\n this.durable = config.durable;\n this.expirypolicy = config.expirypolicy;\n\n if (this.dynamic)\n this.address = undefined;\n\n var node = this;\n // node not yet connected\n this.status({ fill: 'red', shape: 'dot', text: 'disconnected' });\n\n if (this.endpoint) {\n\n node.endpoint.connect(function(connection) {\n setup(connection);\n });\n\n /**\n * Node setup for creating receiver link\n *\n * @param connection Connection instance\n */\n function setup(connection) {\n\n node.connection = connection;\n\n // node connected\n node.status({ fill: 'green', shape: 'dot', text: 'connected' });\n\n // build receiver options based on node configuration\n var options = {\n source: {\n address: node.address,\n dynamic: node.dynamic,\n durable: node.durable,\n expiry_policy: node.expirypolicy\n },\n credit_window: node.creditwindow,\n autoaccept: node.autoaccept,\n snd_settle_mode: node.sndsettlemode,\n rcv_settle_mode: node.rcvsettlemode\n };\n\n node.receiver = node.connection.open_receiver(options);\n\n node.receiver.on('message', function(context) {\n var msg = {\n payload: context.message,\n delivery: context.delivery\n };\n delete msg.delivery.link;\t\t// some attributes of link cannot be cloned and it will throw exceptions here. so I delete this attributes.\n node.send(msg);\n });\n\n node.connection.on('disconnected', function(context) {\n // node disconnected\n node.status({fill: 'red', shape: 'dot', text: 'disconnected' });\n });\n\n node.on('input', function(msg) {\n if (msg.credit) {\n node.receiver.flow(msg.credit);\n }\n });\n\n node.on('close', function() {\n if (node.receiver != null)\n node.receiver.detach();\n node.connection.close();\n });\n }\n\n }\n }", "function EnumCB_ChangeRelationshipRS_POST() {\n try {\n var isDKRefVisible = ENUMCB.getIsDKRefVisible();\n\n if (isDKRefVisible == \"true\") {\n ENUMCB.Required(\"pyWorkPage.HouseholdMemberTemp.ChangeRelationshipRS\", \"pyWorkPage.HouseholdMemberTemp.DKRefused.ChangeRelationshipRS\");\n } \n else {\n ENUMCB.Required(\"pyWorkPage.HouseholdMemberTemp.ChangeRelationshipRS\");\n }\n var workPage = pega.ui.ClientCache.find(\"pyWorkPage\");\n if (!workPage.hasMessages()) {\n\n ENUMCB.setDKRefResponse(\"pyWorkPage.HouseholdMemberTemp.DKRefused.ChangeRelationshipRS\", \"pyWorkPage.HouseholdMemberTemp.Response.P_REL_DK_IND\", \"pyWorkPage.HouseholdMemberTemp.Response.P_REL_REF_IND\"); \n\n var memberTempPage = pega.ui.ClientCache.find(\"pyWorkPage.HouseholdMemberTemp\");\n var respProp = memberTempPage.get(\"ChangeRelationshipRS\");\n if(respProp) {\n respProp = respProp.getValue();\n }\n else {\n respProp = \"\";\n }\n var questFlags = pega.ui.ClientCache.find(\"pyWorkPage.QuestFlags\");\n var householdRoster = pega.ui.ClientCache.find(\"pyWorkPage.HouseholdRoster\");\n if(respProp == \"SD\") {\n questFlags.put(\"NextSurveyQuestion\", \"ChangeRelationSD_QSTN\");\n var curMemberIndex = parseInt(householdRoster.get(\"CurrentHHMemberIndex\").getValue());\n CB.setMemberInRoster(curMemberIndex,false);\n }\n else if(respProp == \"OT\") {\n questFlags.put(\"NextSurveyQuestion\", \"ChangeRelationOT_QSTN\");\n var curMemberIndex = parseInt(householdRoster.get(\"CurrentHHMemberIndex\").getValue());\n CB.setMemberInRoster(curMemberIndex,false);\n }\n else{\n var respPage = pega.ui.ClientCache.find(\"pyWorkPage.HouseholdMemberTemp.Response.P_REL_CODE\");\n respPage.setValue(respProp);\n questFlags.put(\"NextSurveyQuestion\", \"\");\n\n var cpHouseholdRoster = pega.ui.ClientCache.find(\"pyWorkPage.HouseholdRoster\");\n var currentHHMemberIndex = parseInt(cpHouseholdRoster.get(\"CurrentHHMemberIndex\").getValue());\n ENUMCB.setRelTextInHouseholdMemberTemp(\"ChangeRelationshipRS\",\"D_RelationshipOptions_ALL\",\"ChangeRelationshipRS\");\n CB.setMemberInRoster(currentHHMemberIndex,false);\n\n var relationshipSexIndex = questFlags.get(\"RelationshipSexIndex\");\n if (relationshipSexIndex) {\n relationshipSexIndex = relationshipSexIndex.getValue();\n } else {\n relationshipSexIndex = 0;\n } \n\n relationshipSexIndex = relationshipSexIndex+1;\n questFlags.put(\"RelationshipSexIndex\", relationshipSexIndex);\n }\n } \n }\n catch (e) {\n /*alert(\"ENUMCB Error - EnumCB_ChangeRelationshipRS_POST:\" + e.message);*/\n }\n}", "async function listenFFReactions(bot, msg, db) {\n console.log(`${msg.guild.id}::::::::are you is here`);\n const handleReaction = async (reaction, user, add) => {\n if (user.id === botID) {\n return;\n }\n const emoji = await reaction._emoji.name;\n const { guild } = await reaction.message\n let configFile = await jsonManip.jsonFileReader(`./servers/${msg.guild.id}/server_config.json`);\n\n var role = await msg.guild.roles.cache.find(role => role.id === configFile[roleIDAttribute]);\n var member = await msg.guild.members.fetch(user.id);\n\n if (role == null) {\n console.log(`${msg.guild.id} role does not exist`);\n } else {\n if (add) {\n await member.roles.add(role)\n db.all(`SELECT userID \n FROM users \n WHERE userID=${user.id}`, [], (err, rows) => {\n if (rows.length == 0) {\n db.run(`INSERT INTO users VALUES(${user.id}, 1)`)\n } else {\n db.run(`UPDATE users \n SET status = 1 \n WHERE userID=${user.id}`)\n }\n })\n }\n else {\n await member.roles.remove(role)\n db.all(`SELECT userID \n FROM users \n WHERE userID='${user.id}'`, [], (err, rows) => {\n if (rows.length != 0) {\n db.run(`UPDATE users \n SET status = 0 \n WHERE userID='${user.id}'`)\n }\n })\n }\n }\n\n }\n\n let configFile = await jsonManip.jsonFileReader(`./servers/${msg.guild.id}/server_config.json`);\n\n bot.on('messageReactionAdd', async (reaction, user) => {\n if (configFile[chIDAttribute] == reaction.message.channel.id) {\n handleReaction(reaction, user, true);\n }\n })\n\n bot.on('messageReactionRemove', async (reaction, user) => {\n if (configFile[chIDAttribute] == reaction.message.channel.id) {\n handleReaction(reaction, user, false);\n }\n })\n}", "getLink() {\n switch (this.note.verb) {\n case 'requested':\n case 'invited':\n return '/#orgs';\n default:\n return '';\n }\n }", "function replyBrain(reply) {\n const replyStr = JSON.stringify(reply);\n nats.request(CH_RES_TO_BRAIN, replyStr);\n console.log(`Reply to brain: ${replyStr}`);\n}", "function requestInviteLink(arg, args, message)\n{\n\tsendBotString(\"onInviteLinkRequest\", (msg) => message.author.send(msg));\n}", "function getActionUrl(action) {\n return config.host+'/twiml/'+action;\n}", "function createBlockLink () {\r\n \r\n /*Create new element in DOM*/\r\n var childItemAction = document.createElement('a');\r\n /*Set identifier from global variables*/\r\n childItemAction.id = switchActionBlockId;\r\n /*Add event listener - we cant just add onclick,\r\n it is feature of Greasemonkey*/\r\n childItemAction.addEventListener(\r\n 'click',\r\n function (evt) {\r\n onclickRTBanButton();\r\n return false;\r\n },\r\n false\r\n ); \r\n /*Set right caption on the link*/\r\n childItemAction.innerHTML = blockTextBlock;\r\n /*Set hand-like cursor*/\r\n childItemAction.style.cursor = 'pointer';\r\n return childItemAction;\r\n}", "reactInvitation(){\n this.message.react(inviteEmojis[0]).then(_ =>\n this.message.react(inviteEmojis[1])\n .catch(console.error)\n ).catch(console.error);\n }", "rsvp(attending) {\n this.props.rsvp(this.props.party._id, attending);\n }", "function openMoneroWalletCLIsend(href) {\n var parsed_href = parseMoneroURI(href);\n var href_json = {\n address: parsed_href.address,\n amount: (parsed_href.hasOwnProperty(\"amount\") ? parsed_href.amount : 0),\n payment_id: (parsed_href.hasOwnProperty(\"payment_id\") ? parsed_href.payment_id : \"\"),\n mixin: (parsed_href.hasOwnProperty(\"mixin\") ? parsed_href.mixin : 3)\n };\n\n var request = {greeting: \"Electronero electronero-wallet-rpc Payment Request\", href: href_json};\n chrome.runtime.sendMessage(request, function(resp) { console.log(resp); });\n}", "function customVehicles(e){\n\t//channel = client.Channels.get(CUSTOM_GAMES_CHANNEL);\n\te.message.channel.sendMessage(\"Should there be vehicles?\").then(function (message) {\n\t\tmessage.addReaction(\":YES:318081582579712000\");\n\t\tmessage.addReaction(\":NO:318081582344830979\");\n\t}).catch(function() {\n\t\tconsole.log(\"sending message failed\");\n });\n}", "function linked(status) {\n //'this' is now a connection object\n var conn = this; \n console.log(\"ok... linked \"+status);\n if (status == 5) {\n //announcing ourselves\n console.log(\"[000]\");\n\n var pres = $pres({type:'available',priority: 10});\n console.log(\"[00]\");\n\n conn.send(pres); \n console.log(\"[0]\");\n console.log(conn.group_name+\" [0a]\");\n console.log(\"[0b1]\"+conn.bl.me);\n console.log(\"[0b2]\"+conn.bl.me.name);\n\n //join group.\n if(conn.group_name && conn.bl.me.name){\n conn.join_group();\n console.log(\"joining \"+conn.group_name);\n }else{\n console.log(\"no group name - use set_group_name\");\n }\n \n console.log(\"[1]\");\n this.bl.blink = new Blink({\"status\":status,\"group_name\":conn.group_name});\n console.log(\"[2]\");\n\n //trigger connected\n $(document).trigger('connected',[this.bl.blink]);\n console.log(\"[3]\");\n\n\n\n //handlers \n\n //handler for presence messages\n conn.addHandler(function(presence){\n\n event = Strophe.getText(presence.firstChild);\n var fr = $(presence).attr('from');\n var ty = $(presence).attr('type');\n var role = $(presence).find('item').attr('role');//make sure it's the particpant or owner, not the thing itself\n\n //if nick is already taken in the room, choose another\n if(ty==\"error\"){\n var code = $(presence).find('error').attr('code')\n console.log(\"code is \"+code);\n if(code && code==\"409\"){\n conn.bl.me.name=conn.bl.me.name+\"_\";\n conn.join_group();\n }\n } \n\n if(role){\n var name = tidy_from(fr);\n if(name!=conn.bl.me.name){//i.e. not me\n\n //roster has changed - a person has left - so trigger\n if(ty && ty==\"unavailable\"){\n delete conn.bl.blink.items[name];\n $(document).trigger('items_changed',[conn.bl.blink]);\n }else{\n \n //we have a new joiner\n //initially we don't know the kind of thing is is, until we get a message\n var p = new Unknown(name,name);\n conn.bl.blink.items[name]=p;\n\n //send info to the new joiner\n conn.bl.share(conn.bl.me,p);\n\n //trigger items changed\n $(document).trigger('items_changed',[conn.bl.blink]);\n }\n }else{\n\n //me\n conn.bl.blink.items[\"me\"]=conn.bl.me;\n\n //sigh - simpler if we put me in as well\n conn.bl.blink.items[name]=conn.bl.me;\n $(document).trigger('items_changed',[conn.bl.blink]);\n }\n }\n\n\n return true;\n },\"\", \"presence\");\n\n\n\n //handler for private messages and group messages\n conn.addHandler(function(msg){ \n\n var elems = msg.getElementsByTagName('body');\n var type = msg.getAttribute('type');\n var fr = $(msg).attr('from')\n var name = tidy_from(fr);\n\n if (type == \"chat\" || type == \"groupchat\" && elems.length > 0) {\n var body = elems[0];\n var text = Strophe.getText(body);\n\n //if the message has been delayed, we ignore it as we have already seen it\n //here we just note how large the delay is\n var delay = msg.getElementsByTagName('delay');\n if(delay){\n delay = delay[0];\n }\n\n try{\n\n var j = JSON.parse(text);\n\n\n//case 1): a group message generated by dropping onto 'share with group'\n//case 2): a chat message generated by dropping onto tv\n//case 3): a chat message generated by dropping on to person\n//case 4); also I might be getting a message that the TV has changed\n//if *I'm* a TV then I need to do stuff\n//I need to change nowp\n//case 5): finally, it could just be a message saying what sort of thing I am\n//the note we distinguish who shared something from the source of it\n//the sharer need not be the source\n\n//ignore delays\n\n if(!delay){\n\n if(j[\"obj_type\"]){\n\n//case 5): presence doesn't allow custom elements or attributes\n//so to announce the sort of thing we are, we need to send a message\n//this includes an obj_type\n//when we find these we update our roster to reflect the typing\n//so that we can display it appropriately\n//Unknown typed objects are not displayed\n\n var n = j[\"name\"];\n\n if(n){\n\n //if we know about it already\n //update its type\n if(conn.bl.blink.items[n]){\n conn.bl.blink.items[n].obj_type=j[\"obj_type\"]\n\n if(j.obj_type==\"tv\"){\n console.log(\"found a tv\");\n //update nowp if it's a tv\n conn.bl.blink.items[n].nowp=j[\"nowp\"];\n }\n\n //if the obj has changed type then we trigger a roster change\n $(document).trigger('items_changed',[conn.bl.blink]);\n\n }else{\n console.log(\"nok: we don't know about this item already\");\n }\n }else{\n console.log(\"nok no name for the item\");\n }\n }else{\n\n//case 2: I'm the Tv and I need to change\n//I play it and add to history\n\n if(conn.bl.me.obj_type==\"tv\" && type==\"chat\"){//i.e. not group chats\n\n conn.bl.me.nowp = j;\n\n//this is kind of messy and untested\n var action = j[\"action\"];\n switch(action){\n\n case \"play\":\n var item = conn.bl.blink.items[name];\n delete j[\"action\"];\n j[\"state\"] = \"play\";\n item.nowp=j;\n\n $(document).trigger('tv_changed',[item]);\n console.log(\"TRIGGEREd play_video\");\n if(name!=conn.bl.me.name){//not from me or we get a loop\n j[\"shared_by\"]=name; //keep track of who controlled it\n conn.bl.share(j,null);//shares with group\n }\n break;\n\n case \"pause\":\n var item = conn.bl.blink.items[name];\n delete j[\"action\"];\n j[\"state\"] = \"pause\";\n item.nowp=j;\n $(document).trigger('tv_changed',[item]);\n console.log(\"TRIGGEREd pause_video\");\n if(name!=conn.bl.me.name){//not from me or we get a loop\n j[\"shared_by\"]=name; //keep track of who controlled it\n conn.bl.share(j,null);//shares with group\n }\n break;\n\n case \"display\":\n var item = conn.bl.blink.items[name];\n delete j[\"action\"];\n item.nowp=j;\n $(document).trigger('tv_changed',[item]);\n console.log(\"TRIGGEREd show text\");\n break;\n\n default:\n console.log(\"unknown or no action \"+action);\n break;\n } \n\n }else{ \n var sender_type = null;\n var item = conn.bl.blink.items[name];\n if(item){\n sender_type = item.obj_type;\n if(sender_type ==\"tv\"){\n\n//case 4: TV has changed\n//or if it came from a tv, I just update my tv\n if(item.item_type==\"programme\"){\n item.nowp=j;\n $(document).trigger('tv_changed',[item]);\n console.log(\"TRIGGEREd update tv\");\n }else{\n $(document).trigger('shared_changed',[j,name,type]);\n }\n }else{\n//case 1 / 3:\n//I add it to my history if it came from a non-tv\n var p = conn.bl.me;\n p.shared.unshift(j);\n\n $(document).trigger('shared_changed',[j,name,type]);\n }\n }else{\n console.error(\"Unknown object\");\n }\n\n }\n\n }\n \n }\n }catch(e){\n console.log(\"unable to parse json \"+e);\n }\n\n\n }\n\n return true;\n },\"\", \"message\");\n\n\n //////end handlers\n }\n\n if (status == 6 || status ==7){\n console.log(\"disconnecting or disconnected\");\n if(conn.bl.auto_reconnect){\n console.log(\"trying to reconnect with a 3 second delay\");\n try{\n setTimeout(function() { \n conn.bl.connect(conn.person,conn.group_name);\n }, 3000 );\n }catch(e){\n console.log(\"reconnection failed \"+e);\n $(document).trigger('disconnected');\n }\n }else{\n $(document).trigger('disconnected');\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
makes button for RGB color
function makeRGB() { const boxes = container.querySelectorAll('.box'); rgb.textContent = "RGB"; rgb.addEventListener('click', () => { boxes.forEach(box => box.addEventListener('mouseover', () => { let R = Math.floor(Math.random() * 256); let G = Math.floor(Math.random() * 256); let B = Math.floor(Math.random() * 256); const RGB = `rgb(${R},${G},${B})`; box.style.background = RGB; })) }) buttons.appendChild(rgb).classList.add('btn'); }
[ "function colorThemOwn() {\n button.style.background = buttonValue;\n }", "getButtonColor() {\n if (this.mixed) return color(76, 199, 79); // green - finished\n else if (this.mixing) return color(255, 218, 101); // yellow - mixing\n return color(102, 153, 204); // blue - normal\n }", "function newColorButton(){\n var r=Math.floor(Math.random()*256);\n var g=Math.floor(Math.random()*256);\n var b=Math.floor(Math.random()*256);\n\n rrggbb= `rgb(` + r + `,` + g + `,` + b + `)`;\n\n document.style.getElementById(\"loadQuote\").id.background = rrggbb;\n\n\n}", "addColorButton(red, green, blue, opacity) {\n if (!opacity)\n opacity = 255;\n\n\n red = Math.min(255, red + 50);\n green = Math.min(255, green + 50);\n blue = Math.min(255, blue + 50);\n\n let mode = new Mode();\n let buttonPositions = this.getButtonPosition(this.buttons.length);\n let tempColor = color(red, green, blue, opacity);\n let newButton = new colorHotBarButton(buttonPositions.x, buttonPositions.y, buttonPositions.w, buttonPositions.h, tempColor, mode, this.buttons.length, this.x, this.x + this.w);\n this.buttons.push(newButton);\n\n }", "function clickRGBSwatch ()\r\n\t{\r\n var hex = Number(this.value).toString(16)\r\n hex = \"0x000000\".substr(0, 8 - hex.length) + hex\r\n var rgb = $.colorPicker(hex)\r\n if (rgb < 0)\r\n return;\r\n hex = Number(rgb).toString(16)\r\n hex = \"0x000000\".substr(0, 8 - hex.length) + hex\r\n this.value = hex\r\n \r\n setSwatchColor(this, hex)\r\n //alert (\"Selected RGB color: \" + hex);\r\n \r\n //alert('old ' + this.oldValue + \" new \" + this.value)\r\n if (isPreview)\r\n if (this.value != this.oldValue)\r\n {\r\n setPresetList (1)\r\n doPreview (this.parent)\r\n }\r\n \t}", "addColorButtons() {\n this.addColorButton(0, 0, 0); //black\n\n this.addColorButton(105, 105, 105);\n this.addColorButton(128, 128, 128);\n this.addColorButton(169, 169, 169);\n this.addColorButton(192, 192, 192);\n this.addColorButton(211, 211, 211);\n this.addColorButton(220, 220, 220);\n this.addColorButton(245, 245, 245);\n\n this.addColorButton(255, 255, 255); //white\n\n\n this.addColorButton(255, 0, 0); //red\n this.addColorButton(255, 69, 0);\n this.addColorButton(255, 99, 71);\n this.addColorButton(250, 128, 114);\n this.addColorButton(255, 140, 0);\n this.addColorButton(255, 165, 0);\n this.addColorButton(255, 215, 0);\n\n\n this.addColorButton(0, 255, 0); //Green\n this.addColorButton(127, 255, 0);\n this.addColorButton(173, 255, 47);\n this.addColorButton(152, 251, 152);\n this.addColorButton(50, 205, 50);\n this.addColorButton(0, 255, 127);\n\n this.addColorButton(0, 0, 255); //Blue\n this.addColorButton(65, 105, 225);\n this.addColorButton(135, 206, 250);\n this.addColorButton(0, 191, 255);\n this.addColorButton(127, 255, 212);\n\n\n this.addColorButton(255, 219, 172); //Skin\n\n\n //add like 200 other colors\n for (let i = 0; i < commonColors.length; i++) {\n this.addColorButton(commonColors[i][0], commonColors[i][1], commonColors[i][2]);\n }\n }", "function setButtonColor(button, red, green, blue) {\n button.setAttribute('style', 'background-color:rgb('+ red +', '+ green +', '+ blue +')');\n}", "function setupColorButton(buttonID) {\n\t$(buttonID).colorpicker().on('changeColor', function(e) {\n $(buttonID).css(\"background\", e.color.toString(\"rgba\"));\n applyChanges();\n });\n}", "function getRandomColourButton() {\n //create array of HEXADECIMAL characters\n var hexadecscale = '0123456789ABCDEF'.split('');\n // initialize hexadecimal string\n var hexadec = '#';\n var i = 0;\n while (i<6) {\n //pick a hexadecimal character and add it to the hexadec string\n hexadec += hexadecscale[Math.floor(Math.random() * 16)];\n i += 1;\n }\n //console.log colour to ensure that it's working\n console.log(hexadec);\n //set button background colour\n document.getElementById(\"loadQuote\").style.backgroundColor = hexadec;\n }", "function ColorButton(color, propname) {\r\n if (!propname) propname = \"color\";\r\n return $(go.Shape,\r\n {\r\n width: 16, height: 16, stroke: \"lightgray\", fill: color,\r\n margin: 1, background: \"transparent\",\r\n mouseEnter: function(e, shape) { shape.stroke = \"dodgerblue\"; },\r\n mouseLeave: function(e, shape) { shape.stroke = \"lightgray\"; },\r\n click: ClickFunction(propname, color), contextClick: ClickFunction(propname, color)\r\n });\r\n }", "function updateDrawColor(e)\n{\n if (e.target.tagName === 'BUTTON')\n DRAW_COLOR = \"RANDOM\";\n else\n DRAW_COLOR = e.target.value;\n}", "function coloredRaisedButton() {\n\t return new ButtonBuilder().withStyle({\n\t borderRadius: 2,\n\t shadowRadius: 1,\n\t shadowOffset: { width: 0, height: .5 },\n\t shadowOpacity: .7,\n\t shadowColor: 'black'\n\t }).withTextStyle({\n\t color: 'white',\n\t fontWeight: 'bold'\n\t });\n\t}", "function changeBtnColor(color)\n{\n if(color.value === \"red\")\n {\n btnsRed();\n }\n else if(color.value === \"green\")\n {\n btnsGreen();\n }\n else if(color.value === \"reset\")\n {\n reset();\n }\n else if(color.value === \"random\")\n {\n random();\n }\n}", "function buttonpush(butid){\r\n alloff();\r\n setbuttonstate(butid,'on');\r\n colorize();\r\n}", "function buildColorButtons() {\n const colorButtonsName = [\"Red\",\"Green\",\"Blue\",\"Orange\",\"Purple\",\"Cyan\",\"Yellow\",\"LEDs Off\",\"Default\"]\n const colorCodes = [\"#800000\",\"#008000\",\"#000080\",\"#ff6600\",\"#800080\",\"#008888\",\"#ffff00\",\"#000000\",\"#808080\"]\n const bgColors = [\"#880000\",\"#008800\",\"#000088\",\"#ff6600\",\"#880088\",\"#00ffff\",\"#ffff00\",\"#000000\",\"#ffffff\"]\n const styleBtnIds = [\"btnRed\",\"btnGreen\",\"btnBlue\",\"btnOrange\",\"btnPurple\",\"btnCyan\",\"btnYellow\",\"btnOff\",\"btnDefault\"]\n const colorButtonsId = document.getElementById(\"colorButtons\")\n\n for(let counter = 0; counter < colorCodes.length; counter++) {\n let button = document.createElement(\"button\")\n let node = colorButtonsName[counter]\n let value = colorCodes[counter]\n\n button.setAttribute(\"class\", \"btn m-1\")\n button.setAttribute(\"id\", `${styleBtnIds[counter]}`)\n button.setAttribute(\"style\", `background-color: ${bgColors[counter]};`)\n button.setAttribute(\"type\", \"button\")\n button.setAttribute(\"value\", value)\n button.appendChild(document.createTextNode(node))\n colorButtonsId.appendChild(button)\n }\n}", "function buttonColor(button, mode) {\n\n mode = mode || 0;\n var buttoncolor = \"\";\n if ( mode )\n buttoncolor = \"#B3B2B2\";\n if ( document.getElementById(button) )\n document.getElementById(button).style.backgroundColor = buttoncolor;\n }", "function rgb(r, g, b){\n\n}", "function setupButtonColor() {\n\tfor(var i = 0; i<allButtons.length; i++) {\n\t\tallButtons[i].style.color = h1Display.style.backgroundColor;\n\t}\n}", "function RGBColor(b){this.ok=!1;\"#\"==b.charAt(0)&&(b=b.substr(1,6));b=b.replace(/ /g,\"\");b=b.toLowerCase();var k={aliceblue:\"f0f8ff\",antiquewhite:\"faebd7\",aqua:\"00ffff\",aquamarine:\"7fffd4\",azure:\"f0ffff\",beige:\"f5f5dc\",bisque:\"ffe4c4\",black:\"000000\",blanchedalmond:\"ffebcd\",blue:\"0000ff\",blueviolet:\"8a2be2\",brown:\"a52a2a\",burlywood:\"deb887\",cadetblue:\"5f9ea0\",chartreuse:\"7fff00\",chocolate:\"d2691e\",coral:\"ff7f50\",cornflowerblue:\"6495ed\",cornsilk:\"fff8dc\",crimson:\"dc143c\",cyan:\"00ffff\",darkblue:\"00008b\",\ndarkcyan:\"008b8b\",darkgoldenrod:\"b8860b\",darkgray:\"a9a9a9\",darkgreen:\"006400\",darkkhaki:\"bdb76b\",darkmagenta:\"8b008b\",darkolivegreen:\"556b2f\",darkorange:\"ff8c00\",darkorchid:\"9932cc\",darkred:\"8b0000\",darksalmon:\"e9967a\",darkseagreen:\"8fbc8f\",darkslateblue:\"483d8b\",darkslategray:\"2f4f4f\",darkturquoise:\"00ced1\",darkviolet:\"9400d3\",deeppink:\"ff1493\",deepskyblue:\"00bfff\",dimgray:\"696969\",dodgerblue:\"1e90ff\",feldspar:\"d19275\",firebrick:\"b22222\",floralwhite:\"fffaf0\",forestgreen:\"228b22\",fuchsia:\"ff00ff\",\ngainsboro:\"dcdcdc\",ghostwhite:\"f8f8ff\",gold:\"ffd700\",goldenrod:\"daa520\",gray:\"808080\",green:\"008000\",greenyellow:\"adff2f\",honeydew:\"f0fff0\",hotpink:\"ff69b4\",indianred:\"cd5c5c\",indigo:\"4b0082\",ivory:\"fffff0\",khaki:\"f0e68c\",lavender:\"e6e6fa\",lavenderblush:\"fff0f5\",lawngreen:\"7cfc00\",lemonchiffon:\"fffacd\",lightblue:\"add8e6\",lightcoral:\"f08080\",lightcyan:\"e0ffff\",lightgoldenrodyellow:\"fafad2\",lightgrey:\"d3d3d3\",lightgreen:\"90ee90\",lightpink:\"ffb6c1\",lightsalmon:\"ffa07a\",lightseagreen:\"20b2aa\",lightskyblue:\"87cefa\",\nlightslateblue:\"8470ff\",lightslategray:\"778899\",lightsteelblue:\"b0c4de\",lightyellow:\"ffffe0\",lime:\"00ff00\",limegreen:\"32cd32\",linen:\"faf0e6\",magenta:\"ff00ff\",maroon:\"800000\",mediumaquamarine:\"66cdaa\",mediumblue:\"0000cd\",mediumorchid:\"ba55d3\",mediumpurple:\"9370d8\",mediumseagreen:\"3cb371\",mediumslateblue:\"7b68ee\",mediumspringgreen:\"00fa9a\",mediumturquoise:\"48d1cc\",mediumvioletred:\"c71585\",midnightblue:\"191970\",mintcream:\"f5fffa\",mistyrose:\"ffe4e1\",moccasin:\"ffe4b5\",navajowhite:\"ffdead\",navy:\"000080\",\noldlace:\"fdf5e6\",olive:\"808000\",olivedrab:\"6b8e23\",orange:\"ffa500\",orangered:\"ff4500\",orchid:\"da70d6\",palegoldenrod:\"eee8aa\",palegreen:\"98fb98\",paleturquoise:\"afeeee\",palevioletred:\"d87093\",papayawhip:\"ffefd5\",peachpuff:\"ffdab9\",peru:\"cd853f\",pink:\"ffc0cb\",plum:\"dda0dd\",powderblue:\"b0e0e6\",purple:\"800080\",red:\"ff0000\",rosybrown:\"bc8f8f\",royalblue:\"4169e1\",saddlebrown:\"8b4513\",salmon:\"fa8072\",sandybrown:\"f4a460\",seagreen:\"2e8b57\",seashell:\"fff5ee\",sienna:\"a0522d\",silver:\"c0c0c0\",skyblue:\"87ceeb\",slateblue:\"6a5acd\",\nslategray:\"708090\",snow:\"fffafa\",springgreen:\"00ff7f\",steelblue:\"4682b4\",tan:\"d2b48c\",teal:\"008080\",thistle:\"d8bfd8\",tomato:\"ff6347\",turquoise:\"40e0d0\",violet:\"ee82ee\",violetred:\"d02090\",wheat:\"f5deb3\",white:\"ffffff\",whitesmoke:\"f5f5f5\",yellow:\"ffff00\",yellowgreen:\"9acd32\"},e;for(e in k)b==e&&(b=k[e]);var f=[{re:/^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/,example:[\"rgb(123, 234, 45)\",\"rgb(255,234,245)\"],process:function(a){return[parseInt(a[1]),parseInt(a[2]),parseInt(a[3])]}},{re:/^(\\w{2})(\\w{2})(\\w{2})$/,\nexample:[\"#00ff00\",\"336699\"],process:function(a){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]}},{re:/^(\\w{1})(\\w{1})(\\w{1})$/,example:[\"#fb0\",\"f0f\"],process:function(a){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}}];for(e=0;e<f.length;e++){var n=f[e].process,g=f[e].re.exec(b);g&&(channels=n(g),this.r=channels[0],this.g=channels[1],this.b=channels[2],this.ok=!0)}this.r=0>this.r||isNaN(this.r)?0:255<this.r?255:this.r;this.g=0>this.g||isNaN(this.g)?0:\n255<this.g?255:this.g;this.b=0>this.b||isNaN(this.b)?0:255<this.b?255:this.b;this.toRGB=function(){return\"rgb(\"+this.r+\", \"+this.g+\", \"+this.b+\")\"};this.toHex=function(){var a=this.r.toString(16),c=this.g.toString(16),d=this.b.toString(16);1==a.length&&(a=\"0\"+a);1==c.length&&(c=\"0\"+c);1==d.length&&(d=\"0\"+d);return\"#\"+a+c+d};this.getHelpXML=function(){for(var a=[],c=0;c<f.length;c++)for(var d=f[c].example,b=0;b<d.length;b++)a[a.length]=d[b];for(var e in k)a[a.length]=e;d=document.createElement(\"ul\");\nd.setAttribute(\"id\",\"rgbcolor-examples\");for(c=0;c<a.length;c++)try{var l=document.createElement(\"li\"),h=new RGBColor(a[c]),m=document.createElement(\"div\");m.style.cssText=\"margin: 3px; border: 1px solid black; background:\"+h.toHex()+\"; color:\"+h.toHex();m.appendChild(document.createTextNode(\"test\"));var g=document.createTextNode(\" \"+a[c]+\" -> \"+h.toRGB()+\" -> \"+h.toHex());l.appendChild(m);l.appendChild(g);d.appendChild(l)}catch(n){}return d}}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a JSON representation of this line
getJSONRepresentation() { return { type: "LineEnv", lineStartingX: this.startingX, lineStartingY: this.startingY, lineEndingX: this.endingX, lineEndingY: this.endingY, lineColour: this.colour, lineWidth: this.lineWidth } }
[ "json() {\n var pos = this.input.pos(this.start)\n return {\"input\":this.input.id, \"start\":this.start,\n \"row\":pos[0], \"column\":pos[1]}\n }", "json() {\n var pos = this.input.location(this.start)\n return {\"input\":this.input.id, \"start\":this.start,\n \"row\":pos[0], \"column\":pos[1]}\n }", "function linesToJSON(string) {\n return \"[\" + string.replace(/\\}\\s+\\{/g, \"}, {\") + \"]\";\n}", "getJSON() {\r\n\t\tlet s = \"\";\r\n\t\ts += \"Filter = \" + this.string + \"\\n\";\r\n\t\ts += \"Valid? = \" + this.isValid + \"\\n\";\r\n\t\tif ( this.errorHint ) {\r\n\t\t\ts += \"Error Hint = \" + this.errorHint + \"\\n\";\r\n\t\t}\r\n\t\ts += JSON.stringify(this.syntax);\r\n\t\t// add enters after commas\r\n\t\ts = s.replace(/\",/g, '\",\\n');\r\n\t\treturn s;\r\n\t}", "function Line(name_line, description_line,description_url_line, img_url_line, video_url_line, start_line, end_line, type_line, theLineCoords){//here\n var that = this;\n that.name_line = name_line;\n that.description_line = description_line;\n that.description_url_line = description_url_line;\n that.img_url_line = img_url_line;\n that.video_url_line = video_url_line;\n that.start_line = start_line;\n that.end_line = end_line;\n that.type_line = type_line;\n that.theLineCoords = theLineCoords;\n\n return '{\"type\":'+'\"Feature\",\"properties\":{\"name\":\"'+name_line+'\",'+'\"description\":'+'\"'+description_line+'\"'+','+'\"description_url\":'+'\"'+description_url_line+'\"'+','+'\"img_url\":'+'\"'+img_url_line+'\"'+','+'\"video_url\":'+'\"'+video_url_line+'\"'+','+'\"start\":'+'\"'+start_line+'\"'+\",\"+'\"end\":'+'\"'+end_line+'\"'+\"},\"+'\"geometry\"'+':{\"type\":\"'+type_line +'\",'+'\"coordinates\":['+theLineCoords+']}},'\n }", "toJSON() {\n return {\n r: this.r,\n g: this.g,\n b: this.b,\n a: this.a,\n };\n }", "function _toJSON()\n {\n return {\"x\": _x, \"y\": _y};\n }", "function JSONFormatter() { }", "parsedLinesToJSON(log_arr) {\n return log_arr.map(el => JSON.stringify(el)).join('\\n') + '\\n';\n }", "toString() {\n return JSON.stringify(this.toJSON());\n }", "toJSON() {\n return super.toJSON();\n }", "toString() {\r\n return \"{ \\\"brand\\\": \\\"\" + this.brand + \"\\\", \\\"model\\\": \\\"\" + this.model + \"\\\", \\\"color\\\": \\\"\" + this.color + \"\\\", \\\"year\\\": \" + this.year + \", \\\"km\\\": \" + this.km + \" }\";\r\n }", "toJSON() {\n return {\n type: this.type,\n state: this.state,\n source: this.source,\n zone: this.zone.name,\n runCount: this.runCount\n };\n }", "toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }", "toJSON() {\n return {\n termType: this.termType,\n value: this.value,\n };\n }", "get line() {\n return this._lineStyle;\n }", "getLineData() {\r\n let lineData = { style: ['','-',''], points: [] };\r\n if (!this.lt) {\r\n this.lt = \"-\";\r\n }\r\n // Get our style of line. Returned array should have three elements that map to the left arrow, the middle line, and the right arrow respectively.\r\n lineData.style = this.lt.match(/([^-.]*)([^>]*)(.*)/).slice(1);\r\n // Get coordinates as pairs\r\n let points = this.attrs.split(';');\r\n for (let i = 0; i < points.length; i+= 2) {\r\n lineData.points.push(points.slice(i, i+2));\r\n }\r\n for (let i = 0; i < lineData.points.length; i++) {\r\n lineData.points[i][0] = parseInt(lineData.points[i][0]);\r\n lineData.points[i][1] = parseInt(lineData.points[i][1]);\r\n }\r\n return lineData;\r\n }", "get line() {\n return this._line;\n }", "toJSON() {\n return this.toHexString();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the channel name to listen on
setChannelName (/*callback*/) { throw 'stream channels are deprecated'; /* // listening on the stream channel for this stream this.channelName = 'stream-' + this.stream.id; callback(); */ }
[ "setChannelName (callback) {\n\t\t// we'll listen on our me-channel, but no message should be received since we're not a member of the stream\n\t\tthis.channelName = `user-${this.currentUser.user.id}`;\n\t\tcallback();\n\t}", "setChannelName (callback) {\n\t\t// expect on the \"everyone\" team channel\n\t\tthis.channelName = `user-${this.users[this.listeningUserIndex].user.id}`;\n\t\tcallback();\n\t}", "setChannelName (callback) {\n\t\t// listen on the current user's me-channel, they should get a message that they have been\n\t\t// added to the team\n\t\tthis.channelName = `user-${this.currentUser.user.id}`;\n\t\tcallback();\n\t}", "setChannelName (callback) {\n\t\t// expect on the user's me-channel \n\t\tthis.channelName = `user-${this.currentUser.user.id}`;\n\t\tcallback();\n\t}", "handleChannelName(event) {\n this.channelName = event.target.value;\n }", "setChannelName (callback) {\n\t\t// when posted to a team stream, it is the team channel\n\t\tthis.channelName = `team-${this.team.id}`;\n\t\tcallback();\n\t}", "setChannelName (callback) {\n\t\t// for the user we expect to receive the confirmation email, we use their me-channel\n\t\t// we'll be sending the data that we would otherwise send to the outbound email\n\t\t// service on this channel, and then we'll validate the data\n\t\tthis.channelName = `user-${this.currentUser.user.id}`;\n\t\tcallback();\n\t}", "function caml_ml_set_channel_name() {\n return 0\n}", "function SetLogChannel(name) { _TUTORIAL_LOGCHANNEL = name; }", "set serverName (value) {\n this._serverName = value\n /**\n * @event IrcUser#serverName\n */\n this.emit('serverName')\n }", "set name(v) {\r\n this.tag('ChannelName').patch({ y: 94, text: { fontSize: 30, text: v } })\r\n }", "get name() {\n return `${this._channel}`;\n }", "handleChannelName(event) { \n this.channelName = event.target.value; \n }", "set nickName (value) {\n this._nickName = value\n /**\n * @event IrcUser#nickName\n */\n this.emit('nickName')\n }", "function channel(c){\nthisChannel = c;\n}", "channel(name) {\n if (!this.channels[name]) {\n this.channels[name] = new SocketIoChannel(this.socket, name, this.options);\n }\n return this.channels[name];\n }", "channel(channel_name) {\n this.stub_channel.channel_name = channel_name\n return this.stub_channel\n }", "function SetModChannel(){\n modchannel = client.channels.find(\"name\", config.modchat);\n modChannelID = modchannel.id;\n}", "listen(name, event, callback) {\n return this.channel(name).listen(event, callback);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=== Use this to add score and trigger animation
function addScore(amount) { score += amount; scoreAnimTimer = 0; }
[ "function createScoreAnimation(x, y, message, score){\n \n var me = this;\n \n var scoreFont = \"90px Arial\";\n \n //Create a new label for the score\n var scoreAnimation = this.game.add.text(x, y, message, {font: scoreFont, fill: \"#39d179\", stroke: \"#ffffff\", strokeThickness: 15});\n scoreAnimation.anchor.setTo(0.5, 0);\n scoreAnimation.align = 'center';\n \n //Tween this score label to the total score label\n var scoreTween = this.game.add.tween(scoreAnimation).to({x:SCORE_X, y: SCORE_Y}, 800, Phaser.Easing.Exponential.In, true);\n \n //When the animation finishes, destroy this score label, trigger the total score labels animation and add the score\n scoreTween.onComplete.add(function(){\n scoreAnimation.destroy();\n scoreLabelTween.start();\n scoreBuffer += score;\n }, this);\n }", "function createScoreAnimation(x, y, vmessage, vscore){\n\n \n var scoreFont = \"90px Arial\";\t\n \n //Create a new label for the score\n var scoreAnimation = vGame.add.text(x, y, vmessage, {font: scoreFont, fill: \"#39d179\", stroke: \"#ffffff\", strokeThickness: 15});\n scoreAnimation.anchor.setTo(0.5, 0);\n scoreAnimation.align = 'center';\n \n //Tween this score label to the total score label\n var scoreTween = vGame.add.tween(scoreAnimation).to({x: score._scoreXPos, y: score._scoreYPos}, 800, Phaser.Easing.Exponential.In, true);\n \n //When the animation finishes, destroy this score label, trigger the total score labels animation and add the score\n scoreTween.onComplete.add(function(){\n scoreAnimation.destroy();\n scoreLabelTween.start();\n\t\t score._scoreBuffer += vscore;\n\t }, this);\n\t}", "function createScoreAnimation(x, y, vmessage, vscore){\n\n \n var scoreFont = \"90px Arial\";\t\n \n //Create a new label for the score\n var scoreAnimation = vGame.add.text(x, y, vmessage, {font: scoreFont, fill: \"#39d179\", stroke: \"#ffffff\", strokeThickness: 15});\n scoreAnimation.anchor.setTo(0.5, 0);\n scoreAnimation.align = 'center';\n \n //Tween this score label to the total score label\n var scoreTween = vGame.add.tween(scoreAnimation).to({x: score._scoreXPos, y: score._scoreYPos}, 800, Phaser.Easing.Exponential.In, true);\n \n //When the animation finishes, destroy this score label, trigger the total score labels animation and add the score\n scoreTween.onComplete.add(function(){\n scoreAnimation.destroy();\n score._scoreLabelTween.start();\n\t\t score._scoreBuffer += vscore;\n\t }, this);\n\t}", "updateScore(targetName, score){\n this.backScore = this.getScoreText( score ); // this is currently on the other side\n this.backScore.rotation.y = Math.PI;\n this.scoreContainer.add(this.backScore);\n this.future(500).spinScore(0);\n }", "function score_animation(sel)\n {\n sel.animate({'font-size': '10vw', 'opacity': '0.2'}, 250)\n .animate({'font-size': '5vw', 'opacity': '1'}, 250);\n }", "function AnimateVisibleScore () {\n\n iTween.ValueTo ( gameObject,\n {\n \"from\" : visibleScore,\n \"to\" : currentScore,\n \"onupdate\" : \"ChangeVisibleScore\",\n \"time\" : 1\n }\n );\n\n}", "function AnimateVisibleScore () {\n\n iTween.ValueTo ( gameObject,\n {\n \"from\" : visibleScore,\n \"to\" : currentScore,\n \"onupdate\" : \"ChangeVisibleScore\",\n \"time\" : 0.2\n }\n );\n\n}", "increaseScore() {\n this.score++;\n this.displayScore();\n }", "updateScore() {\n this.currentScore = this.currentScore + 600;\n }", "UpdateScore(newScore){\n this.currentScore += newScore;\n }", "function hit(){\n score += 10;\n updateScore();\n}", "function updateScore () {\n score++;\n $('.js-showScore').text(score);\n }", "updateScore(score, force) {\n if (force) {\n this.score = score;\n } else {\n this.score = this.score + score;\n }\n animateValue(this.scoreContainer, this.score, 1500);\n }", "function updateScore() {\n score++;\n $('.score').text(score);\n }", "function _incrScore() {\n _setScore(_getScore() + 1);\n $('#score').html(_getScore());\n }", "AddScore(score) {\n this.m_score += score;\n }", "setScore(value) {\n\t\tthis.$element.find('.score').html(value + ' points')\n\t}", "function updateScore() {\n\t\t$('#score').html(myScore);\n\t\tcheckforWin();\n\t}", "AddScore(score) {\n this.m_score += score;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calcule le prix de la prochaine amelioration de l autoclic
function autoclickprix(){ return Math.round(200 * (nbMultiplicateurAmelioAutoclick * 0.40)); }
[ "function prix() {\n return 50 * (nbMultiplicateur * nbMultiplicateur * 0.2);\n}", "function calculerPrixTotal(nounours) {\n prixPanier = prixPanier += nounours.price;\n}", "calcularIva() {\n this.precio = this.precio * 1.21;\n }", "calculaCashback(valor,porcentagem){\n return (valor * porcentagem)\n }", "precioTotal () {\n return this.precioBase() + this.calcularAdicionales() - this.calcularDescuentos();\n }", "calcularPrecioFinal() {\n let precioFinal = 0;\n precioFinal = this.calcularPrecioBase() + this.totalizadorAdicionales() - this.totalizadorDescuentos();\n return precioFinal;\n }", "function peso_p_mulher(paciente){\n\t return parseFloat(45.5 + 0.91 * (paciente.altura -152.4));\n\t}", "calculatePercantage() {\n var difference = this.maxAdi - this.minAdi;\n var precentage = Number((this.props.ADI * 100 / difference) + 50);\n return precentage;\n }", "function sumaPremio(slot) {\r\n\tbanco.setPremio(banco.getPremio() > 0 ? banco.getPremio() * slot.premio : banco.getPremio() + slot.premio);\r\n\treturn banco.getPremio();\r\n}", "calculPerimetru() {\n console.log('aici am suprascris functia calculPerimetru al parintelui');\n return this.l1 * 3;\n }", "function calculePrixTotal() {\n let prixTotal = 0;\n let coefficient = 0;\n let nbCopies = Math.round(Number(document.getElementById(\"copies\").value));\n if (nbCopies > 0) {\n if (nbCopies < 10)\n coefficient = 0.5;\n else if (nbCopies >= 10 && nbCopies <= 20)\n coefficient = 0.4;\n else\n coefficient = 0.3;\n }\n\n prixTotal = coefficient * nbCopies\n document.getElementById(\"coefficient\").innerHTML = \"Coefficient : \" + coefficient;\n document.getElementById(\"prixtotal\").innerHTML = \"Prix total : \" + prixTotal;\n\n if (prixTotal > 10)\n document.getElementById(\"prixtotal\").style.backgroundColor = \"yellow\";\n else\n document.getElementById(\"prixtotal\").style.backgroundColor = \"white\";\n}", "function PesoPaquete(payasos, munecas){\n let pesoTotal = (payasos * 112) + (munecas * 75);\n return pesoTotal\n}", "function calcularTotal() {\n // Limpiamos precio anterior\n total = 0;\n // Recorremos el array del carrito\n carrito.forEach((item) => {\n // De cada elemento obtenemos su precio\n const miItem = baseDeDatos.filter((itemBaseDatos) => {\n return itemBaseDatos.id === parseInt(item);\n });\n total = total + (miItem[0].Prezioa-(miItem[0].Prezioa * miItem[0].Portzentaia /100));\n });\n // Renderizamos el precio en el HTML\n DOMtotal.textContent = total.toFixed(2);\n }", "function custoFinal(custoFabrica, percDistribuidor, percImpostos ){\n let custoFinal = custoFabrica + ((custoFabrica * percDistribuidor) / 100 ) + ((custoFabrica * percImpostos ) / 100)\n\n return custoFinal;\n}", "function prixTotal() {\n let total = 0;\n for (let j= 0; j < objPanier.length; j++) {\n total = total + objPanier[j].price * objPanier[j].number;\n }\n let afficheTotal = document.querySelector(\"#total\");\n afficheTotal.textContent=(\"Total : \" + (total / 100).toLocaleString(\"fr\") + \" €\");\n}", "function calcularPropina(porcentaje){\t\t\n\t\tdocument.getElementById(\"propinax\").value = \"\";\n\t\t// valor del subtotal\n\t\tvar subtotalFactura = formatoNumerico($('#valorSubtotal').html());\t\n\t\tsubtotalFactura = subtotalFactura.substring(1);\n\t\t// calcula el porcentaje sobre el subtotal\n\t\tvar valorPorcentaje = subtotalFactura*(porcentaje/100);\n\t\t//\n\t\tvar valorIvaFatura = formatoNumerico($('#valorIva').html());\t\n\t\tvalorIvaFatura = valorIvaFatura.substring(1);\n\t\t//\n\t\tvar valorTotalFactura = parseFloat(valorIvaFatura) + parseFloat(valorPorcentaje) + parseFloat(subtotalFactura);\n\n\t\tdocument.getElementById(\"valorPropina\").innerHTML = '$'+formatoMoneda(valorPorcentaje.toString());\t\n\t\tdocument.getElementById(\"totalFactura\").innerHTML = '$'+formatoMoneda(valorTotalFactura.toString());\t\t\n\t}", "function calcModalPremium (modalFactor, basePremium){\n \tvar modalPremium = commonFormulaSvc.round(basePremium*modalFactor,0);\n $log.debug('modalPremium',modalPremium);\n return modalPremium;\n\n \t}", "function calculTotalPrixArticle(idAlbum, nbArticle) {\n return parseFloat(albums.get(idAlbum).prix) * nbArticle;\n}", "function calcularPrecioItem(cantidad, precio){\n precio = cantidad * precio;\n return precio;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares two ArrayBuffer or ArrayBufferView objects. If bitCount is omitted, the two values must be the same length and have the same contents in every byte. If bitCount is included, only that leading number of bits have to match.
function equalBuffers(a, b, bitCount) { var remainder; if (typeof bitCount === "undefined" && a.byteLength !== b.byteLength) { return false; } var aBytes = new Uint8Array(a); var bBytes = new Uint8Array(b); var length = a.byteLength; if (typeof bitCount !== "undefined") { length = Math.floor(bitCount / 8); } for (var i=0; i<length; i++) { if (aBytes[i] !== bBytes[i]) { return false; } } if (typeof bitCount !== "undefined") { remainder = bitCount % 8; return aBytes[length] >> (8 - remainder) === bBytes[length] >> (8 - remainder); } return true; }
[ "function equalBuffers(a, b, bitCount) {\n var remainder;\n\n if (typeof bitCount === \"undefined\" && a.byteLength !== b.byteLength) {\n return false;\n }\n\n var aBytes = new Uint8Array(a);\n var bBytes = new Uint8Array(b);\n\n var length = a.byteLength;\n if (typeof bitCount !== \"undefined\") {\n length = Math.floor(bitCount / 8);\n }\n\n for (var i=0; i<length; i++) {\n if (aBytes[i] !== bBytes[i]) {\n return false;\n }\n }\n\n if (typeof bitCount !== \"undefined\") {\n remainder = bitCount % 8;\n return aBytes[length] >> (8 - remainder) === bBytes[length] >> (8 - remainder);\n }\n\n return true;\n }", "function buffersEqual(a, b) {\n if(!isBuffer(a) || !isBuffer(b)) {\n return false\n }\n\n if(a.length !== b.length) {\n return false\n }\n\n for(var i = 0; i < a.length; i++) {\n if(a[i] !== b[i]) {\n return false\n }\n }\n\n return true\n}", "bufferEquals(a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b))\n return undefined;\n\n if (typeof a.equals === 'function')\n return a.equals(b);\n\n if (a.length !== b.length)\n return false;\n\n for (var i = 0; i < a.length; i++)\n if (a[i] !== b[i])\n return false;\n\n return true;\n }", "function equalBuffers(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n var aBytes = new Uint8Array(a);\n var bBytes = new Uint8Array(b);\n\n for (var i=0; i<a.byteLength; i++) {\n if (aBytes[i] !== bBytes[i]) {\n return false;\n }\n }\n\n return true;\n }", "function equal (bufferA, bufferB) {\n //walk by all the arguments\n if (arguments.length > 2) {\n for (var i = 0, l = arguments.length - 1; i < l; i++) {\n if (!equal(arguments[i], arguments[i + 1])) return false;\n }\n return true;\n }\n\n validate(bufferA);\n validate(bufferB);\n\n if (bufferA.length !== bufferB.length || bufferA.numberOfChannels !== bufferB.numberOfChannels) return false;\n\n for (var channel = 0; channel < bufferA.numberOfChannels; channel++) {\n var dataA = bufferA.getChannelData(channel);\n var dataB = bufferB.getChannelData(channel);\n\n for (var i = 0; i < dataA.length; i++) {\n if (dataA[i] !== dataB[i]) return false;\n }\n }\n\n return true;\n}", "function equal$1 (bufferA, bufferB) {\r\n\t//walk by all the arguments\r\n\tif (arguments.length > 2) {\r\n\t\tfor (var i = 0, l = arguments.length - 1; i < l; i++) {\r\n\t\t\tif (!equal$1(arguments[i], arguments[i + 1])) return false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvalidate(bufferA);\r\n\tvalidate(bufferB);\r\n\r\n\tif (bufferA.length !== bufferB.length || bufferA.numberOfChannels !== bufferB.numberOfChannels) return false;\r\n\r\n\tfor (var channel = 0; channel < bufferA.numberOfChannels; channel++) {\r\n\t\tvar dataA = bufferA.getChannelData(channel);\r\n\t\tvar dataB = bufferB.getChannelData(channel);\r\n\r\n\t\tfor (var i = 0; i < dataA.length; i++) {\r\n\t\t\tif (dataA[i] !== dataB[i]) return false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}", "function arrayBufferEquals(b1, b2) {\n\tif (\n\t\t!(b1 instanceof ArrayBuffer) ||\n\t\t!(b2 instanceof ArrayBuffer)\n\t) {\n\t\treturn false;\n\t}\n\n\tif (b1.byteLength !== b2.byteLength) {\n\t\treturn false;\n\t}\n\tb1 = new Uint8Array(b1);\n\tb2 = new Uint8Array(b2);\n\tfor (let i = 0; i < b1.byteLength; i++) {\n\t\tif (b1[i] !== b2[i]) return false;\n\t}\n\treturn true;\n}", "equals(otherBuffer) {\n if (!isInstance(otherBuffer, Uint8Array)) {\n throw new TypeError(\n // eslint-disable-next-line max-len\n `The \"otherBuffer\" argument must be an instance of Buffer or Uint8Array. Received type ${typeof otherBuffer}`\n );\n }\n\n if (this === otherBuffer) {\n return true;\n }\n if (this.byteLength !== otherBuffer.byteLength) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this[i] !== otherBuffer[i]) {\n return false;\n }\n }\n\n return true;\n }", "function buffersMatch(a, b) {\n for (var i = 0, l = a.length; i < l; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n\n return true;\n}", "function _isEqualBuffer(buf1, buf2) {\n if(buf1.length !== buf2.length) {\n return false;\n }\n for(let i = 0; i < buf1.length; i++) {\n if(buf1[i] !== buf2[i]) {\n return false;\n }\n }\n return true;\n}", "sameBinaryAs(other) {\n if (this.binary.length !== other.binary.length) {\n return false;\n }\n for (let i = 0; i < this.binary.length; i++) {\n if (this.binary[i] !== other.binary[i]) {\n return false;\n }\n }\n return true;\n }", "assertSameNumberOfBits(other) {\n if (other.bits.length !== this.bits.length) {\n throw new Error(`Bit mismatch (a = ${this.bits.length}, b = ${other.bits.length})`);\n }\n }", "function safeBufferEquals (a, b) {\n if (!a) return !b\n if (!b) return !a\n return equals(a, b)\n}", "function bigstring_memcmp_stub(v_s1, v_s1_pos, v_s2, v_s2_pos, v_len){\n for (var i = 0; i < v_len; i++) {\n var a = caml_ba_get_1(v_s1,v_s1_pos + i);\n var b = caml_ba_get_1(v_s2,v_s2_pos + i);\n if (a < b) return -1;\n if (a > b) return 1;\n }\n return 0;\n}", "function equalsBytes(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}", "function deepEqual (t, a, b) {\n function clone (src) {\n let dest = {}\n for (let [ key, value ] in Object.entries(src)) {\n if (Buffer.isBuffer(value)) {\n dest[key] = ':Buffer:' + value.toString('hex')\n } else if (typeof value === 'object' && value != null) {\n dest[key] = clone(value)\n } else {\n dest[key] = value\n }\n }\n return dest\n }\n\n let a2 = clone(a)\n let b2 = clone(b)\n return t.deepEqual(a2, b2)\n}", "function eqfile( f1, f2 ) {\n return f1.sum == f2.sum && f1.size == f2.size;\n}", "function compareArrays(array1, array2, dontConvert) { // 256\n var len = Math.min(array1.length, array2.length), // 257\n lengthDiff = Math.abs(array1.length - array2.length), // 258\n diffs = 0, // 259\n i; // 260\n for (i = 0; i < len; i++) { // 261\n if ((dontConvert && array1[i] !== array2[i]) || // 262\n (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { // 263\n diffs++; // 264\n } // 265\n } // 266\n return diffs + lengthDiff; // 267\n } // 268", "function compare(a, b) {\n var first = a;\n var second = b;\n var shadow = false;\n if (b.length < a.length) {\n first = b;\n second = a;\n shadow = true;\n }\n for (var i = 0; i < first.length; i++) {\n if (first[i].equals(second[i]) === false) {\n return KeySequence.CompareResult.NONE;\n }\n }\n if (first.length < second.length) {\n if (shadow === false) {\n return KeySequence.CompareResult.PARTIAL;\n }\n else {\n return KeySequence.CompareResult.SHADOW;\n }\n }\n return KeySequence.CompareResult.FULL;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing OpenIdConnectProvider resource's state with the given name, ID, and optional extra properties used to qualify the lookup.
static get(name, id, opts) { return new OpenIdConnectProvider(name, undefined, Object.assign(Object.assign({}, opts), { id: id })); }
[ "static get(name, id, state, opts) {\n return new RegistryPolicy(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new ExternalKey(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new SourceCredential(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new SecurityConfiguration(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new ResourcePolicy(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new KeyPair(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new Insight(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new NamedQuery(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static getOrCreateProvider(scope, uniqueid, props) {\n var _b;\n const id = `${uniqueid}CustomResourceProvider`;\n const stack = stack_1.Stack.of(scope);\n const provider = (_b = stack.node.tryFindChild(id)) !== null && _b !== void 0 ? _b : new CustomResourceProvider(stack, id, props);\n return provider;\n }", "function read ( provider, id, callback ) {\n logger.debug( 'OctopusIdentity Alias:read ' + provider + ' ' + id );\n AliasModel.findOne( {\n provider : provider,\n id : id\n }, function ( err, object ) {\n if ( err ) {\n return callback( err, null );\n }\n callback( null, object );\n } );\n}", "static get(name, id, state, opts) {\n return new Association(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new TagOptionResourceAssociation(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new Organization(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "function getStateDetails(id) {\r\n\treturn fetch(`${URL}/states/${id}/?ws_key=${API_KEY}&${FORMAT}`)\r\n\t\t.then((res) => {\r\n\t\t\treturn res.json();\r\n\t\t})\r\n\t\t.then((res) => {\r\n\t\t\treturn {\r\n\t\t\t\tstate: res.state.name\r\n\t\t\t};\r\n\t\t});\r\n}", "static get(name, id, state, opts) {\n return new WebAclAssociation(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new InfrastructureConfiguration(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "static get(name, id, state, opts) {\n return new EventSourceMapping(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }", "getState(id) {\n // Convert the id to a name\n const stateName = this.state.names[id];\n\n for (let i = 0; i < this.state.states.length; i++) {\n const state = this.state.states[i];\n\n // The state names match\n if (slugName('', state.name) === slugName('', stateName)) {\n return state;\n }\n }\n\n return undefined;\n }", "static get(name, id, state, opts) {\n return new Function(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
======================================================================================================= Follow table : =======================================================================================================
function _getTableFollowResult() { var limit = gtableProfileParams.data.limit; //var offset = params.data.offset + 1; var offset = gtableProfileParams.data.offset; var contract = { "function": "sm_get_followed_users", "args": JSON.stringify([limit, offset, gUserAddress]) } return neb.api.call(getAddressForQueries(), gdAppContractAddress, gNasValue, gNonce, gGasPrice, gGasLimit, contract); }
[ "function processCurrentTable()\n{\n\tlet firstRow = table.rows[0],\n\t\tlastRow = table.rows[table.rows.length - 1];\n\tcreateTableTags(firstRow.pos, lastRow.pos + lastRow.line.length);\n\n\taddTableHead();\n\tcreateSeparatorTag(table.rows[1]);\n\taddTableBody();\n}", "getTable() {\n const eos = Eos();\n eos.getTableRows({\n \"json\": true,\n \"code\": \"notechainacc\", // contract who owns the table\n \"scope\": \"notechainacc\", // scope of the table\n \"table\": \"notestruct\", // name of the table as specified by the contract abi\n \"limit\": 100,\n }).then(result => {\n if (result.rows > 0) {\n this.setState({ showMarker: true })\n }\n this.setState({ noteTable: result.rows })\n });\n }", "function pageTable() {\n methods.tableTpl_2_content({\n table: nheap.content_data\n [\"Page 2\"]\n [\"OverallSummaryAndFamilyMember.txt\"]\n [\"Table1\"],\n caption: \"Family Members\",\n columnsWithTriangleDecoration: { \"3\": true, \"4\": true, \"5\": true },\n columns:\n [\n { \"Family_Member\": { \"caption\": \"Name\" } },\n { \"Invested_Value\": { \"caption\": \"Invested Value (Crs.)\" } },\n { \"Current_Value\": { \"caption\": \"Current Value (Crs.)\" } },\n { \"Gain_Loss\": { \"caption\": \"Gain (Crs.)\", \"green mark\": true } },\n { \"IRR\": { \"caption\": \"XIRR (%)\", \"green mark\": true } },\n { \"Benchmark_IRR\": { \"caption\": \"BM XIRR (%)\", \"green mark\": true } }\n ]\n });\n }", "static loadNextPageInTable() {\n let table = document.getElementById('table').components[\"table\"];\n table.loadNextPage();\n }", "following () {\n return this.belongsToMany(\n 'App/Models/User',\n 'follower_id',\n 'user_id'\n ).pivotTable('followers')\n }", "getTable() {\n const eos = Eos();\n eos.getTableRows({\n \"json\": true,\n \"code\": \"notechainacc\", // contract who owns the table\n \"scope\": \"notechainacc\", // scope of the table\n \"table\": \"notestruct\", // name of the table as specified by the contract abi\n \"limit\": 100,\n }).then(result => this.setState({ noteTable: result.rows }));\n }", "getTable() {\n const eos = Eos();\n eos.getTableRows({\n \"json\": true,\n \"code\": \"notechainacc\", // contract who owns the table\n \"scope\": \"notechainacc\", // scope of the table\n \"table\": \"notestruct\", // name of the table as specified by the contract abi\n \"limit\": 100,\n }).then(result => this.setState({ searchResultsTable: result.rows }));\n\n const result = [\n {\n \"title\": \"Google\",\n \"link\": \"https://google.com/reiarosa\",\n \"timestamp\": \"1537646320\",\n \"details\": \"some details and text about this search result\"\n },\n {\n \"title\": \"Google\",\n \"link\": \"https://google.com/reiarosa\",\n \"timestamp\": \"1537646320\",\n \"details\": \"some details and text about this search result\"\n },\n ];\n\n result => this.setState({ searchResultsTable: result.rows });\n\n }", "function addRowsLeader(table, data) {\n data.forEach(d => tableRowsLeader(d).forEach(r => table.append(r)));\n return table;\n}", "function formatFirstFollow(grammar) {\n var result = \"<table class='table table-bordered'>\";\n\n if (Item.prototype.grammarType == \"SLR\") {\n result +=\n '<thead><tr><th colspan=\"3\" style=\"background-color:#e89ab17d\">Table First / Follow </th></tr><tr><th>Non-terminal</th><th>FIRST</th><th>FOLLOW</th></thead>';\n result += \"<tbody>\";\n\n for (var i in grammar.nonterminals) {\n var nonterminal = grammar.nonterminals[i];\n\n result +=\n \"<tr><td>\" +\n nonterminal +\n \"</td><td>{\" +\n grammar.firsts[nonterminal] +\n \"}</td><td>{\" +\n grammar.follows[nonterminal] +\n \"}</td></tr>\";\n }\n } else {\n result +=\n '<thead><tr><th colspan=\"2\">Table First</th></tr><tr><th>Nonterminal</th><th>FIRST</th></thead>';\n result += \"<tbody>\";\n\n for (var i in grammar.nonterminals) {\n var nonterminal = grammar.nonterminals[i];\n\n result +=\n \"<tr><td>\" +\n nonterminal +\n \"</td><td>{\" +\n grammar.firsts[nonterminal] +\n \"}</td></tr>\";\n }\n }\n\n result += \"</tbody>\";\n result += \"</table>\";\n\n return result;\n}", "function table_maker(datasets) {\n reset_table();\n for (var i = 0; i < datasets.length; i++) {\n $('#summary').append('<tr style=\"text-align: center\">' + data(datasets[i]) + '</tr>');\n }\n totals_row_maker(datasets);\n $('#table-div').slideDown();\n }", "function TablesList() {}", "function pageTable() {\n methods.tableTpl_2_content({\n table: nheap.content_data\n [\"Page 16\"]\n [\"EquityPortfolioPerformance(DistributorWisePerformance).txt\"]\n [\"Table\"],\n caption: \"Distributor Wise Performance\",\n\n\n columnsWithTriangleDecoration: { \"5\": true, \"6\": true },\n columns:\n [\n /*\n \"FAMILY_ID\":16382,\n \"Name\":\"Direct\",\n \"Weight\":28.82,\n \"Current_Value\":577.89,\n \"Invested_Value\":615.03,\n \"Gain\":38.22,\n \"XIRR\":2.67\n */\n { \"Name\": { \"caption\": \"Name\" } },\n { \"Weight\": { \"caption\": \"Weight (%)\" } },\n { \"Invested_Value\": { \"caption\": \"Current Value (Crs.)\" } },\n { \"Current_Value\": { \"caption\": \"Invested Value (Crs.)\" } },\n { \"Gain\": { \"caption\": \"Gain (Crs.)\" } },\n { \"XIRR\": { \"caption\": \"XIRR (%)\" } }\n ]\n });\n }", "function attachTableHead(table) {\n var fields = [\n \"id\",\n \"email\",\n \"status\",\n \"first_name\",\n \"last_name\",\n \"display_name\",\n \"photo_url\",\n \"created_at\",\n \"updated_at\",\n \"last_login_at\"\n ];\n var tr = document.createElement(\"TR\");\n var td;\n\n for(var i = 0; i < fields.length; i++) {\n td = document.createElement(\"TD\");\n\n td.innerHTML = fields[i].toUpperCase();\n\n tr.appendChild(td);\n }\n\n table.appendChild(tr);\n }", "function updateTable(){\n\t// get tables dom\n\tlet table = document.querySelector(\".results\");\n\t// must startt from second on loop as first is header\n\tlet rows = table.querySelectorAll(\"tr\");\n\tfor(let i = 1; i < rows.length; i++){\n\t\tlet tableData = rows[i].querySelectorAll(\"td\");\n\t\ttableData[1].innerText = rolledAudioVisualObjects[i - 1][\"correct\"];\n\t\ttableData[2].innerText = rolledAudioVisualObjects[i - 1][\"winnerObject\"][\"description\"];\n\t}\n}", "function formatFirstFollow(grammar) {\n\tvar result = \"<table class='table table-bordered'>\";\n\t\n\tif (Item.prototype.grammarType == 'SLR') {\n\t\tresult += \"<thead><tr><th colspan=\\\"3\\\">Tabela First / Follow </th></tr><tr><th>Não-terminal</th><th>FIRST</th><th>FOLLOW</th></thead>\"\n\t\tresult += \"<tbody>\";\n\t\t\n\t\tfor (var i in grammar.nonterminals) {\n\t\t\tvar nonterminal = grammar.nonterminals[i];\n\t\t\t\n\t\t\tresult += \"<tr><td>\" + nonterminal + \"</td><td>{\" + grammar.firsts[nonterminal] + \"}</td><td>{\" + grammar.follows[nonterminal] + \"}</td></tr>\";\n\t\t}\n\t} else {\n\t\tresult += \"<thead><tr><th colspan=\\\"2\\\">Tabela First</th></tr><tr><th>Nonterminal</th><th>FIRST</th></thead>\"\n\t\tresult += \"<tbody>\";\n\t\t\n\t\tfor (var i in grammar.nonterminals) {\n\t\t\tvar nonterminal = grammar.nonterminals[i];\n\t\t\t\n\t\t\tresult += \"<tr><td>\" + nonterminal + \"</td><td>{\" + grammar.firsts[nonterminal] + \"}</td></tr>\";\n\t\t}\n\t}\n\t\n\tresult += \"</tbody>\"\n\tresult += \"</table>\";\n\t\n\treturn result;\n}", "function handleNextButtonClick() {\n count++;\n renderTable(); \n}", "followers () {\n return this.belongsToMany(\n 'App/Models/User',\n 'user_id',\n 'follower_id'\n ).pivotTable('followers')\n\n }", "function updateTable() {\n tablePageSize = parseInt(d3.select(\"#recShowVal\").property(\"value\"));\n // Ensure Prev/Next bounds are correct, especially after filters applied to dc charts\n var totFilteredRecs = cf.groupAll().value();\n // Adjust values of start and end record numbers for edge cases\n tableOffset = tableOffset < 0 ? 0 : tableOffset; // In case of zero entries\n var end = tableOffset + tablePageSize > totFilteredRecs ? totFilteredRecs : tableOffset + tablePageSize;\n tableOffset = tableOffset >= totFilteredRecs ? Math.floor((totFilteredRecs - 1) / tablePageSize) * tablePageSize : tableOffset;\n // Grab data for current page from the dataTable object\n dataTable.beginSlice(tableOffset);\n dataTable.endSlice(tableOffset + tablePageSize);\n // Update Table paging buttons and footer text\n d3.select('span#begin')\n .text(end === 0 ? tableOffset : tableOffset + 1); // Correct for \"Showing 1 of 0\" bug\n d3.select('span#end')\n .text(end);\n d3.select('#Prev.btn')\n .attr('disabled', tableOffset - tablePageSize <= -tablePageSize ? 'true' : null);\n d3.select('#Next.btn')\n .attr('disabled', tableOffset + tablePageSize >= totFilteredRecs ? 'true' : null);\n d3.select('span#size').text(totFilteredRecs);\n dataTable.redraw();\n }", "getTable() {\n const eos = Eos();\n eos.getTableRows({\n \"json\": true,\n \"code\": \"notechainacc\", // contract who owns the table\n \"scope\": \"notechainacc\", // scope of the table\n \"table\": \"notestruct\", // name of the table as specified by the contract abi\n \"limit\": 100,\n }).then(result => {\n console.log(result);\n this.setState({ noteTable: result.rows });\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ai functions fn(unit, map) > commandlist TODO: actually perform actions on the given map for better lookaheads TODO: more reliable indexing; prone to breaking as units are removed stay in one place, but attack if an enemy is in direct attack range
function wait(unit, map) { let cmd = [] let targets = nbrhd(unit.cell, unit.wpn.rng) .map(cell => map.units.find(unit => Cell.equals(cell, unit.cell))) .filter(target => !!target && !Unit.allied(unit, target)) let target = targets[0] if (target) { let attack = Unit.attackData(unit, target) Unit.attack(unit, target, { map, data: attack }) cmd.push({ type: "attack", attack }) console.log(unit.name, "can target", targets.map(target => target.name).join(", ")) console.log("Chose", target.name, attack) } return cmd }
[ "startUnitTurn(unit) {\n var aiType = unit.aiType || aiTypeEnum.Normal;\n var tauntInRange = this.isTauntInRange(unit);\n\n // Bring to front while selected\n this._map.selectedOrigX = unit.xTile;\n this._map.selectedOrigY = unit.yTile;\n unit.increaseDepth(10);\n this._map.selectedUnit = unit;\n\n this.debugAI(null, \"-------------- \" + unit.name + \" --------------\");\n this.debugAI(unit, \"AI Type is \" + aiType);\n\n // ==============================\n // Zone\n // ==============================\n if (aiType == aiTypeEnum.Zone) {\n var tile = this._map.getTile(unit.xTile, unit.yTile);\n\n // No zone - act normally\n if (!tile.zone) {\n aiType = aiTypeEnum.Normal;\n unit.aiType = aiType;\n }\n\n // Look for enemy units in zone\n // - Ignore hidden units\n for (const bankUnit of this._map._unitBank) {\n if (!unit.isEnemy(bankUnit)) { continue; }\n if (bankUnit.hasStatus(\"Presence Concealment\") || bankUnit.hasStatus(\"Disguise\")) { continue; }\n\n var otherTile = this._map.getTile(bankUnit.xTile, bankUnit.yTile);\n if (tile.zone == otherTile.zone) {\n // Found an enemy in zone\n this.debugAI(unit, \"[Zone] Found enemy in zone. Switching to Normal.\");\n aiType = aiTypeEnum.Normal;\n unit.aiType = aiType;\n break;\n }\n }\n\n // Act defensive otherwise\n if (aiType == aiTypeEnum.Zone) {\n this.debugAI(unit, \"[Zone] No enemies in zone. Defensive.\");\n aiType = aiTypeEnum.Defensive;\n }\n }\n\n\n // ==============================\n // Noble Phantasm\n // ==============================\n if (this.checkNPuse(unit)) { return; }\n\n\n // ==============================\n // Defensive\n // ==============================\n if ((aiType == aiTypeEnum.Defensive) && !tauntInRange) {\n // Prioritize enemies in attack range without moving\n var attackRange = [];\n this._map.enemyList.length = 0;\n this._map.checkEnemiesInRange(unit, this._map.enemyList, attackRange, unit.xTile, unit.yTile, unit.attackRange, 0, null, null);\n\n if (this._map.enemyList.length > 0) {\n\n // Potentially use a skill\n var skillReturn = this.checkSkillUse(unit, aiType);\n if (skillReturn) {\n if (skillReturn.endedTurn) { return; }\n if (skillReturn.delay) {\n this._map._game.time.delayedCall(800, () => {\n\n // Check NP use in case NP Charge skill was used\n if (this.checkNPuse(unit)) { return; }\n\n // Attack\n this._map._attacker = unit;\n var targetUnit = this.selectEnemyTarget(unit, this._map.enemyList);\n this.debugAI(unit, \"[Defensive] Attacking enemy in range without moving\");\n\n if (targetUnit) {\n this._map.attack(targetUnit);\n }\n\n });\n return;\n }\n }\n\n // Attack normally\n this._map._attacker = unit;\n var targetUnit = this.selectEnemyTarget(unit, this._map.enemyList);\n this.debugAI(unit, \"[Defensive] Attacking enemy in range without moving\");\n\n if (targetUnit) {\n this._map.attack(targetUnit);\n }\n return;\n }\n }\n\n\n // ==============================\n // Support\n // ==============================\n // Check for Ally-targeting skills or NP\n var supportSkill = this.getSupportSkill(unit);\n if (supportSkill && !tauntInRange) {\n // Single Target\n if (supportSkill.skillType == skillTypeEnum.Ally) {\n this.debugAI(unit, \"Support skill \" + supportSkill.name + \" available.\");\n\n var allyList = [];\n var unitRange = this._map.getUnitRange(unit);\n var moveSkillRange = this._map.getMovementAttackRange(unit, unitRange, true, allyList, supportSkill.range, true);\n\n var usedSkill = false;\n if (allyList.length > 0) {\n usedSkill = this.useSingleSupportSkill(unit, supportSkill, allyList);\n }\n if (usedSkill) { return; }\n }\n\n\n // Burst\n if (supportSkill.skillType == skillTypeEnum.AllyBurst) {\n\n\n }\n }\n\n\n // ==============================\n // Move & Attack\n // ==============================\n // Check for enemies within movement + attack range\n this.debugAI(unit, \"Searching for enemies in range...\");\n this._map.enemyList.length = 0;\n var unitRange = this._map.getUnitRange(unit);\n var moveAttackRange = this._map.getMovementAttackRange(unit, unitRange, null, this._map._enemyList);\n this.debugAI(unit, [...this._map.enemyList]);\n\n if (this._map.enemyList.length > 0) {\n\n // Potentially use a skill\n var skillReturn = this.checkSkillUse(unit, aiType);\n if (skillReturn) {\n if (skillReturn.endedTurn) { return; }\n if (skillReturn.delay) {\n this._map._game.time.delayedCall(800, () => {\n\n // Check NP use in case NP Charge skill was used\n if (this.checkNPuse(unit)) { return; }\n\n // Move to attack\n this._map._attacker = unit;\n var targetUnit = this.selectEnemyTarget(unit, this._map.enemyList);\n\n if (targetUnit) {\n this.debugAI(unit, \"Moving to attack \" + targetUnit.name);\n this._map.moveToAttack(targetUnit);\n }\n\n });\n return;\n }\n }\n\n // Move to attack\n this._map._attacker = unit;\n var targetUnit = this.selectEnemyTarget(unit, this._map.enemyList);\n\n if (targetUnit) {\n this.debugAI(unit, \"Moving to attack \" + targetUnit.name);\n this._map.moveToAttack(targetUnit);\n }\n return;\n }\n\n\n // ==============================\n // Move Only\n // ==============================\n if (aiType != aiTypeEnum.Defensive) {\n // Otherwise, figure out where to move to\n var targetUnit = this.enemytoFollow(unit);\n this.debugAI(unit, \"No enemies in range. Trying to follow \" + targetUnit.name + \"...\");\n var xyPoint = this.pathToEnemy(unit, targetUnit);\n\n\n // Handle cases where there was nowhere to go\n if (!xyPoint) {\n this.debugAI(unit, \"Nowhere to go. Waiting.\");\n this._map.waitUnit(unit, true);\n return;\n }\n\n\n // Move as far as possible along the path\n this.debugAI(unit, \"Moving to \" + xyPoint.x + \"-\" + xyPoint.y + \".\");\n this._map.moveUnit(unit, xyPoint.x, xyPoint.y, null, () => {\n this.useMoveSkill(unit);\n this._map.waitUnit(unit, true); });\n return;\n }\n else {\n // Defensive - use a move skill of available\n this.useMoveSkill(unit);\n }\n\n\n // ==============================\n // Nothing\n // ==============================\n // If no applicable options, end unit's turn\n this.debugAI(unit, \"Waiting.\");\n this._map.waitUnit(unit, true);\n }", "executeAction(action) {\n switch (action.type) {\n case Action.STAIR:\n this.map.generateMap();\n\n this.generateTurns();\n this.nextTurn();\n break;\n case Action.MOVE:\n this.map.player.move(action.target.gridX, action.target.gridY);\n break;\n case Action.ATTACK:\n this.attackUnit(this.map.player, action.target, this.nextTurn);\n break;\n case Action.SPELL:\n switch (action.spell) {\n // DASH: Move in the last position until an enemy (and attack) or a wall and stop\n // DIG: Break walls around (but not the borders)\n // KINGMAKER: Heal all monster and generate a chest under them\n // ALCHEMY: Add a chest in all floor tiles surrounding us\n // POWER: Make the attack do more damage (6)\n // BRAVERY: Stun all enemies (allow another turn)\n // BOLT: Generate a bolt in the last direction (4 damage)\n // CROSS: Generate a bolt in all direction for 2 damage\n // https://nluqo.github.io/broughlike-tutorial/stage8.html\n case \"WARP\":\n // Randomly warp the player\n let effect = this.add.sprite(this.map.player.x + (this.map.player.width * this.map.player.scaleX) / 2, this.map.player.y + (this.map.player.height * this.map.player.scaleY) / 2, \"tileset:effectsSmall\");\n this.map.add(effect);\n\n effect.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n\n let tile = this.map.pickEmptyTile();\n\n let effect = this.add.sprite(tile.x, tile.y, \"tileset:effectsSmall\");\n effect.x += (effect.width/2);\n effect.y += (effect.height/2);\n this.map.add(effect);\n effect.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n\n this.map.placeUnit(this.map.player, tile.gridX, tile.gridY);\n\n this.nextTurn();\n\n }, this);\n effect.anims.play(\"warp\", true);\n\n }, this);\n\n effect.anims.play(\"warp\", true);\n break;\n case \"QUAKE\":\n // Hit enemies depending on how much walls are around them\n let duration = 500;\n\n // Shake the camera\n this.cameras.main.shake(duration);\n\n // Wait until the camera stopped shaking to resume the turn\n this.time.addEvent({\n delay: duration,\n callback: function() {\n this.nextTurn();\n },\n callbackScope: this\n });\n\n // Hit each enemies depending on the walls surrounding them\n this.map.enemies.forEach(single_enemy => {\n if (single_enemy.isAlive()) {\n let neighboors = this.map.getAdjacentTiles(single_enemy.gridX, single_enemy.gridY);\n let damage = 4;\n neighboors.forEach(single_neighboor => {\n if (this.map.isFloorAt(single_neighboor.x, single_neighboor.y)) {\n damage--;\n }\n });\n\n if (damage > 0) {\n single_enemy.damage(damage);\n }\n }\n });\n break;\n case \"MAELSTROM\":\n // Randomly move all enemies\n this.map.enemies.forEach(single_enemy => {\n let effect = this.add.sprite(single_enemy.x + (single_enemy.width * single_enemy.scaleX) / 2, single_enemy.y + (single_enemy.height * single_enemy.scaleY) / 2, \"tileset:effectsSmall\");\n this.map.add(effect);\n single_enemy.is_moving = true;\n\n effect.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n\n let tile = this.map.pickEmptyTile();\n\n let effect = this.add.sprite(tile.x, tile.y, \"tileset:effectsSmall\");\n effect.x += (effect.width/2);\n effect.y += (effect.height/2);\n this.map.add(effect);\n effect.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n\n this.map.placeUnit(single_enemy, tile.gridX, tile.gridY);\n\n single_enemy.is_moving = false;\n let remaining_animations = this.map.enemies.filter(single_enemy => single_enemy.is_moving);\n if (remaining_animations.length == 0) {\n this.nextTurn();\n }\n\n }, this);\n effect.anims.play(\"warp\", true);\n\n }, this);\n\n effect.anims.play(\"warp\", true);\n });\n break;\n case \"MULLIGAN\":\n // Reset the map, and reduce the player health by 50% (min at 1)\n this.player.health = Math.max(1, Math.floor(this.map.player.health / 2)); \n this.player.updateBar();\n this.map.generateMap();\n\n /* Since the player will always be first, remove the first turn to allow the enemy to have the next move */\n this.generateTurns();\n this.turns.shift();\n\n this.nextTurn();\n break;\n case \"AURA\":\n // Heal the player and any adjacent enemies\n let neighboors = this.map.getAdjacentTiles(this.map.player.gridX, this.map.player.gridY);\n neighboors.forEach(single_neighboor => {\n let enemy_around = null;\n\n this.map.enemies.forEach(single_enemy => {\n if (single_enemy.gridX == single_neighboor.x && single_enemy.gridY == single_neighboor.y) {\n enemy_around = single_enemy;\n }\n });\n\n if (enemy_around != null) {\n let effect2 = this.add.sprite(enemy_around.x + (enemy_around.width * enemy_around.scaleX) / 2, enemy_around.y + (enemy_around.height * enemy_around.scaleY) / 2, \"tileset:effectsSmall\");\n this.map.add(effect2);\n effect2.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n\n enemy_around.heal(1);\n });\n effect2.anims.play(\"heal\", true);\n }\n });\n\n let effect2 = this.add.sprite(this.map.player.x + (this.map.player.width * this.map.player.scaleX) / 2, this.map.player.y + (this.map.player.height * this.map.player.scaleY) / 2, \"tileset:effectsSmall\");\n this.map.add(effect2);\n\n effect2.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n\n this.map.player.heal(1);\n this.nextTurn();\n\n }, this);\n\n effect2.anims.play(\"heal\", true);\n break;\n }\n break;\n }\n }", "attack(location){ //CHANGE TO ATTACK LOCATION RATHER THAN ATTACK DIRECTION\n //iterates through enemylist and if it encounters an enemy in the target location attacks them\n enemyUnits.forEach(enemy => {\n if(enemy.location.x==location.x && enemy.location.y==location.y){\n log('enemy attacked');\n this.attackFunction(enemy);\n }\n });\n }", "function initAi(screen) {\n\tlet cmd = []\n\tlet game = screen.data\n\tlet map = game.map\n\tlet phase = game.phase\n\tlet strategy = analyze(map, phase.pending)\n\tlet stratmap = new Map()\n\tfor (let i = 0; i < strategy.length; i++) {\n\t\tlet commands = strategy[i]\n\t\tlet unit = phase.pending[i]\n\t\tstratmap.set(unit, commands)\n\t}\n\tfor (let [ unit, commands ] of stratmap) {\n\t\tconsole.log(unit.name, ...commands)\n\t\tif (!commands.length) {\n\t\t\tconsole.log(\"no commands for\", unit.name)\n\t\t\tendTurn(unit, screen)\n\t\t} else {\n\t\t\tcmd.push(...commands)\n\t\t}\n\t}\n\treturn cmd\n}", "attack({enemies}, mousePos, mapSize, mapPos, scale, tileSize=32) {\n const tilePos = this.getTilePos(mousePos, mapSize, mapPos, scale, tileSize);\n\n // TODO: Add player attacking later\n // Get the enemy or player at position\n Object.keys(enemies).forEach((id) => {\n if (enemies[id].pos[0] == tilePos[0] && enemies[id].pos[1] == tilePos[1])\n this.socket.emit('attack', id);\n });\n }", "onSpecialAttack(src, weapon, targets) { }", "aoeBurstSpace(unit, unitRange, range, targetAllies, isHeal) {\n var xySpace;\n var mostEnemies = 0;\n\n // Check for taunt\n var tauntEnemy = null;\n if (!targetAllies) {\n for (const enemy of this._map.enemyList) {\n if (enemy.hasStatus(\"Taunt\")) {\n tauntEnemy = enemy;\n break;\n }\n }\n }\n\n\n // Add current space too\n unitRange.push([unit.xTile, unit.yTile]);\n\n // Go through each movement space\n for (var i = 0; i < unitRange.length; i++) {\n var x = unitRange[i][0];\n var y = unitRange[i][1];\n var tile = this._map.getTile(x, y);\n\n // Check each range\n var atkRange = [];\n var atkEnemy = [];\n this._map.checkEnemiesInRange(unit, atkEnemy, atkRange, x, y, range, 0, null, null, true, null, targetAllies);\n\n if (targetAllies) { atkEnemy.push(unit); }\n\n\n // If healing, remove enemies at full HP from the count\n if (isHeal) {\n var temp = [...atkEnemy];\n atkEnemy.length = 0;\n\n for (const enemy of temp) {\n if (enemy.curHP < enemy.maxHP) {\n console.log(\"Cur HP: \" + enemy.curHP + \" / \" + enemy.maxHP)\n atkEnemy.push(enemy); }\n }\n }\n\n\n // Make sure taunting enemy is in range\n var tauntContinue = true;\n if (tauntEnemy) {\n tauntContinue = false;\n for (const enemy of atkEnemy) {\n if (enemy == tauntEnemy) { tauntContinue = true; break; }\n }\n }\n if (!tauntContinue) { continue; }\n\n\n if ((atkEnemy.length > 0) && (atkEnemy.length > mostEnemies)) {\n mostEnemies = atkEnemy.length;\n xySpace = { x: x, y: y };\n }\n\n }\n return xySpace;\n }", "move(map) {\n //if the ant is dead then exit the method\n if (!this.alive) {\n return;\n }\n\n\n //apply all the rules in order\n for (let i=0; i < this.rules.length; i++) {\n if (this.rules[i].matches(map, this.pos, this.direction)) {\n //rotate the direction based on the active rule\n if (!eightDirections) {\n this.direction = (this.direction + this.rules[i].turn) % 4;\n } else {\n this.direction = (this.direction + this.rules[i].turn) % 8;\n }\n\n\n //change the tile type \n map[this.pos.x][this.pos.y].setTile(this.rules[i].newType, this);\n //add the new tile to the list of tiles it's changed\n this.claimed.push(map[this.pos.x][this.pos.y]);\n\n\n //draw changed tiles\n if (displayColor) {\n //draw the new tiles as the color of the ant\n fill(this.hue, 255, 255, opacity);\n //fill(hue, 255, (tiles[pos.x][pos.y].type+1)*255/tileTypes,opacity);\n } else {\n //draw the new tiles as their real color\n fill(tiles[this.pos.x][this.pos.y].type*255/tileTypes, opacity);\n }\n noStroke();\n rect(this.pos.x*zoom, this.pos.y*zoom, Math.max(zoom,1), Math.max(zoom,1));\n\n\n break;\n }\n }\n\n\n //move in the direction the ant is facing\n if (!eightDirections) {\n //four directional movement\n if (this.direction == 0) {\n this.pos.x++;\n } else if (this.direction == 1) {\n this.pos.y++;\n } else if (this.direction == 2) {\n this.pos.x--;\n } else if (this.direction == 3) {\n this.pos.y--;\n }\n } else {\n //eight directional movement\n if (this.direction == 0) {\n this.pos.x++;\n } else if (this.direction == 1) {\n this.pos.x++;\n this.pos.y++;\n } else if (this.direction == 2) {\n this.pos.y++;\n } else if (this.direction == 3) {\n this.pos.y++;\n this.pos.x--;\n } else if (this.direction == 4) {\n this.pos.x--;\n } else if (this.direction == 5) {\n this.pos.y--;\n this.pos.x--;\n } else if (this.direction == 6) {\n this.pos.y--;\n } else if (this.direction == 7) {\n this.pos.y--;\n this.pos.x++;\n }\n }\n\n\n //if it goes off the map's edge loop it around to the other side\n if (this.pos.x < 0) {\n this.pos.x = map.length-1;\n }\n if (this.pos.x >= map.length) {\n this.pos.x = 0;\n }\n if (this.pos.y < 0) {\n this.pos.y = map[this.pos.x].length-1;\n }\n if (this.pos.y >= map[this.pos.x].length) {\n this.pos.y = 0;\n }\n\n\n //if it is on food eat the food and make a child\n if (map[this.pos.x][this.pos.y].type == tileTypes) {\n map[this.pos.x][this.pos.y].type = 0;\n spawnAnt(ants, this, this.pos);\n\n\n //re-draw the food tile as empty\n fill(0, opacity);\n noStroke();\n rect(this.pos.x * zoom, this.pos.y * zoom, Math.max(zoom, 1), Math.max(zoom, 1));\n }\n\n\n //cause ant to age\n this.age--;\n //cause ant to age faster depending on the amount of empty tiles around it, this makes it harder for ants to spread\n //keep in mind food only spawns in tiles with space around them\n this.age -= abs(getSurround(map, 0));\n\n\n //if it's age reaches 0 kill the ant\n if (this.age < 0) {\n this.alive = false;\n\n\n //if the ant is on a tile it is weak to die\n } else if (map[this.pos.x][this.pos.y].die(this, this.weakness)) {\n this.alive = false;\n }\n }", "function battle(cmd){\n objects[cmd[2]][3] -= objects[cmd[1]][6];\n objects[cmd[1]][3] -= objects[cmd[2]][6];\n if (objects[cmd[2]][3] <= 0 || objects[cmd[1]][3] <= 0){\n commands[cmd[1]] = [null];\n commands[cmd[2]] = [null];\n }\n if (objects[cmd[2]][3] <= 0){\n commands.splice(cmd[2] , 1);\n objects.splice(cmd[2], 1);\n console.log(\"Unit id:\" + cmd[2] + \" has been slain.\")\n }\n else if (objects[cmd[1]][3] <= 0){\n commands.splice(cmd[1], 1);\n objects.splice(cmd[1], 1);\n console.log(\"Unit id:\" + cmd[1] + \" has been slain.\")\n }\n }", "applyTankActions(){\n\t\tlet action;\n\t\tObject.map(this.tanks, (tank, id) => {\n\t\t\tif(tank.hasCooldown(this.currentTankActions[id].type)){\n\t\t\t\tthis.currentTankActions[id] = {\n\t\t\t\t\ttype: TankEnums.Actions.noop,\n\t\t\t\t\tid: id\n\t\t\t\t};\n\t\t\t}\n\n\t\t\taction = this.currentTankActions[id];\n\t\t\tif(action.type == TankEnums.Actions.shoot){\n\t\t\t\taction.bulletID = nanoid(6);\n\t\t\t}\n\n\t\t\tlet bullet = tank.applyAction(action);\n\t\t\tif(bullet){\n\t\t\t\tif(Number.between(bullet.x, 0, this.map.width - 1) && Number.between(bullet.y, 0, this.map.height - 1)) {\n\t\t\t\t\tthis.bullets[bullet.id] = bullet;\n\t\t\t\t} else {\n\t\t\t\t\tdelete this.currentTankActions[id];\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "followEnemy() {\n let enemyDistance;\n let enemyBaseDistance = 0;\n let enemiesInAttackRange = 0;\n for (let enemy of TowerDefenseGame.enemies) {\n // If this is a acid tower, search only enemies that are not poisoned, since an acid tower only attacks enemies one time\n if (this.towerType == 3 && !enemy.isDotted) {\n enemyDistance = ƒ.Vector3.DIFFERENCE(enemy.mtxWorld.translation, this.mtxWorld.translation).magnitude;\n // Check if the enemy, which is not posioned, is in attack range\n if (enemyDistance < this.range) {\n enemiesInAttackRange++;\n this.target = enemy;\n if (this.target == null) {\n return;\n }\n this.top.cmpTransform.lookAt(this.target.mtxLocal.translation);\n }\n }\n // If its not an acid tower, search for every enemy that is close and focus him\n else {\n enemyDistance = ƒ.Vector3.DIFFERENCE(enemy.mtxWorld.translation, this.mtxWorld.translation).magnitude;\n if (this.range >= enemyDistance) {\n enemiesInAttackRange++;\n if (enemy.nextWaypoint > enemyBaseDistance) {\n enemyBaseDistance = enemy.nextWaypoint;\n this.target = enemy;\n if (this.target == null) {\n return;\n }\n this.top.cmpTransform.lookAt(this.target.mtxLocal.translation);\n }\n }\n }\n }\n if (enemiesInAttackRange == 0) {\n this.target = null;\n }\n }", "attackUnit(attacker, defender, callback) {\n // Save the original position (to get back there after the attack)\n let attacker_original_position = {\n x: attacker.x,\n y: attacker.y\n };\n\n // Face the right direction before attacking\n if (attacker.gridX < defender.gridX) {\n attacker.face(1);\n } else if (attacker.gridX > defender.gridX) {\n attacker.face(-1);\n }\n\n // Move to the defender's position\n this.tweens.add({\n targets: attacker,\n x: defender.x,\n y: defender.y,\n ease: 'Cubic',\n duration: 150,\n onComplete: function() {\n // Start the ATTACK animation\n let effect = this.add.sprite(defender.x + (defender.width * defender.scaleX) / 2, defender.y + (defender.height * defender.scaleY) / 2, \"tileset:effectsLarge\");\n this.map.add(effect);\n effect.on(\"animationcomplete\", function(tween, sprite, element) {\n element.destroy();\n defender.damage(attacker.attack);\n // Move the attacker's back to its orignal position\n this.tweens.add({\n targets: attacker,\n x: attacker_original_position.x,\n y: attacker_original_position.y,\n ease: 'Cubic',\n duration: 150,\n onCompleteScope: this,\n onComplete: callback\n });\n }, this);\n effect.anims.play(\"attack\", true);\n },\n onCompleteScope: this\n });\n }", "function checkForAttacks() {\n for (let x = 0; x < mapArr.length; x++) {\n for (let y = 0; y < mapArr[x].length; y++) {\n if (isCenter(mapArr, x, y)) {\n let adjEntities = [];\n if (numWords(mapArr[x][y]) === 2 && entityValues[nthWord(mapArr[x][y], 2)]) adjEntities.push(nthWord(mapArr[x][y], 2));\n for (let v = 0; v < 8; v++) {\n let xo = x + adjVectors[v][0];\n let yo = y + adjVectors[v][1];\n if (numWords(mapArr[xo][yo]) === 2 && entityValues[nthWord(mapArr[xo][yo], 2)]) adjEntities.push(nthWord(mapArr[xo][yo], 2));\n }\n adjEntities.forEach(entity => {\n if (chance(entityValues[entity].aggroChance)) {\n actionPromptModal.style.display = \"block\";\n sleepTimer.style.display = \"\";\n attackResults.innerHTML = `<p>A ${entity} attacked!</p>`\n if (chance(entityValues[entity].winChance)) {\n attackResults.innerHTML += `<p>You scared it away!</p>`\n } else {\n attackResults.innerHTML += `<p>You were injured!</p>`\n changePlayerMeters(entityValues[entity].damage, 0, 0);\n }\n printPlayerAdjVectors(searchPreview);\n printPlayerAdjVectors(attackPreview);\n addEventListenerList(searchTargets, 'click', search);\n addEventListenerList(attackTargets, 'click', attack);\n toggleDrawer(attackLootDrawer);\n }\n });\n }\n }\n }\n}", "onRegularAttack(src, weapon, targets) { }", "function RunAI(enemy) {\n\t//attack AI\n\tif (enemy.attackAI == 'calm') {\n\t\tif (enemy.weapon.type == 'charger' && menu == false) {\n\t\t\tif (enemy.charge < enemy.weapon.max_charge) {\n\t\t\t\tenemy.charge += 0.5;\n\t\t\t}\n\n\t\t\tenemy.cooldown -= 1;\n\t\t\t//console.log(enemy.cooldown);\n\n\t\t\tif ((enemy.direction == 'DOWN' && (X == enemy.pos.x || X == enemy.pos.x - 1) && Y >= enemy.pos.y) || (enemy.direction == 'LEFT' && (Y == enemy.pos.y || Y == enemy.pos.y - 1) && X <= enemy.pos.x) || (enemy.direction == 'UP' && (X == enemy.pos.x || enemy.pos.x + 1) && Y <= enemy.pos.y) || (enemy.direction == 'RIGHT' && (Y == enemy.pos.y || Y == enemy.pos.y + 1) && X >= enemy.pos.x)) {\n\t\t\t\tif (menu == false && textBox == undefined && enemy.weapon != undefined && enemy.cooldown <= 0) {\n\t\t\t\t\tlet xx = enemy.pos.x;\n\t\t\t\t\tlet yy = enemy.pos.y;\n\n\t\t\t\t\tlet x;\n\t\t\t\t\tlet y;\n\t\t\t\t\tif (enemy.direction == 'UP') {\n\t\t\t\t\t\tx = xx;\n\t\t\t\t\t\ty = yy - 2;\n\t\t\t\t\t} else if (enemy.direction == 'DOWN') {\n\t\t\t\t\t\tx = xx - 1;\n\t\t\t\t\t\ty = yy;\n\t\t\t\t\t} else if (enemy.direction == 'RIGHT') {\n\t\t\t\t\t\tx = xx + 1;\n\t\t\t\t\t\ty = yy;\n\t\t\t\t\t} else if (enemy.direction == 'LEFT') {\n\t\t\t\t\t\tx = xx - 2;\n\t\t\t\t\t\ty = yy - 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tlet data = {\n\t\t\t\t\t\tdmg: enemy.charge + enemy.weapon.dmg,\n\t\t\t\t\t\tid: enemy.id,\n\t\t\t\t\t\tdirection: enemy.direction,\n\t\t\t\t\t\tpos: {\n\t\t\t\t\t\t\tx: x,\n\t\t\t\t\t\t\ty: y,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttype: 'bullet',\n\t\t\t\t\t}\n\n\t\t\t\t\tentities.push(data);\n\t\t\t\t\t//socket.emit('attack', data);\n\t\t\t\t\tcharge = 0;\n\t\t\t\t\tenemy.cooldown = 100;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//movement AI\n\tif (enemy.moveAI == 'stationary') {\n\t\tif (enemy.timer <= 0) {\n\t\t\tlet num = Random(4);\n\t\t\tif ((num == 0 && enemy.preset == undefined) || enemy.preset == 'LEFT') {\n\t\t\t\tenemy.direction = 'LEFT';\n\t\t\t\tenemy.timer = 100;\n\t\t\t\tif ((Y == enemy.pos.y || Y == enemy.pos.y - 1 || Y == enemy.pos.y + 1) && X <= enemy.pos.x) {\n\t\t\t\t\tenemy.preset = 'LEFT';\n\t\t\t\t} else {\n\t\t\t\t\tenemy.preset = undefined;\n\t\t\t\t}\n\n\t\t\t} else if ((num == 1 && enemy.preset == undefined) || enemy.preset == 'DOWN') {\n\t\t\t\tenemy.direction = 'DOWN';\n\t\t\t\tenemy.timer = 100;\n\t\t\t\tif ((X == enemy.pos.x || X == enemy.pos.x - 1 || X == enemy.pos.x + 1) && Y >= enemy.pos.y) {\n\t\t\t\t\tenemy.preset = 'DOWN';\n\t\t\t\t} else {\n\t\t\t\t\tenemy.preset = undefined;\n\t\t\t\t}\n\n\t\t\t} else if ((num == 2 && enemy.preset == undefined) || enemy.preset == 'RIGHT') {\n\t\t\t\tenemy.direction = 'RIGHT';\n\t\t\t\tenemy.timer = 100;\n\t\t\t\tif ((Y == enemy.pos.y || Y == enemy.pos.y - 1 || Y == enemy.pos.y + 1) && X >= enemy.pos.x) {\n\t\t\t\t\tenemy.preset = 'RIGHT';\n\t\t\t\t} else {\n\t\t\t\t\tenemy.preset = undefined;\n\t\t\t\t}\n\n\t\t\t} else if ((num == 3 && enemy.preset == undefined) || enemy.preset == 'UP') {\n\t\t\t\tenemy.direction = 'UP';\n\t\t\t\tenemy.timer = 100;\n\t\t\t\tif ((X == enemy.pos.x || X == enemy.pos.x - 1 || X == enemy.pos.x + 1) && Y <= enemy.pos.y) {\n\t\t\t\t\tenemy.preset = 'UP';\n\t\t\t\t} else {\n\t\t\t\t\tenemy.preset = undefined;\n\t\t\t\t}\n\n\t\t\t} else if (enemy.preset != undefined) {\n\t\t\t\tswitch (enemy.preset) {\n\t\t\t\t\tcase 'UP':\n\t\t\t\t\t\tenemy.direction = 'UP';\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'DOWN':\n\t\t\t\t\t\tenemy.direction = 'DOWN';\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'LEFT':\n\t\t\t\t\t\tenemy.direction = 'LEFT';\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'RIGHT':\n\t\t\t\t\t\tenemy.direction = 'RIGHT';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tenemy.preset = undefined;\n\t\t\t}\n\t\t\t//console.log(num);\n\t\t}\n\t\tenemy.timer -= 1;\n\t}\n\n\tif (enemy.moveAI == 'basic') {\n\t\tx = enemy.pos.x + 2;\n\t\ty = enemy.pos.y + 2;\n\n\t\tlet z = X;\n\t\tlet w = Y;\n\t\tconsole.log(`you: ${z}, ${w}`);\n\t\tconsole.log(`them: ${x}, ${y}`);\n\n\t\tif(x < z){\n\t\t\tif(y < w){\n\t\t\t\tif(y + 8 > x){\n\t\t\t\t\tenemy.direction = 'RIGHT';\n\t\t\t\t}else if(y < x){\n\t\t\t\t\tenemy.direction = 'DOWN';\n\t\t\t\t}\n\t\t\t}else if(y > w){\n\t\t\t\tif(y - 8 < x){\n\t\t\t\t\tenemy.direction = 'RIGHT';\n\t\t\t\t}else if(y > x){\n\t\t\t\t\tenemy.direction = 'UP';\n\t\t\t\t}\n\t\t\t}\n\t\t}else if(x > z){\n\t\t\tif(y < w){\n\t\t\t\tif(y > x){\n\t\t\t\t\tenemy.direction = 'LEFT';\n\t\t\t\t}else if(y < x){\n\t\t\t\t\tenemy.direction = 'DOWN';\n\t\t\t\t}\n\t\t\t}else if(y > w){\n\t\t\t\tif(y < x){\n\t\t\t\t\tenemy.direction = 'LEFT';\n\t\t\t\t}else if(y > x){\n\t\t\t\t\tenemy.direction = 'UP';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "attack(forwardSteps,rightSteps,damage,type = null,statuses = null){\r\n let attackX = this.x;\r\n let attackY = this.y;\r\n switch (this.direction) {\r\n case 0: attackY -= forwardSteps;\r\n attackX += rightSteps;\r\n break;\r\n case 90: attackX += forwardSteps;\r\n attackY += rightSteps;\r\n break;\r\n case 180: attackY += forwardSteps;\r\n attackX -= rightSteps;\r\n break;\r\n case 270: attackX -= forwardSteps;\r\n attackY -= rightSteps;\r\n break;\r\n }\r\n let attackedTile = this.field.getTile(attackX, attackY);\r\n if(attackedTile) attackedTile.attacked(damage,type,statuses);\r\n }", "enemytoFollow(unit) {\n var unitX = unit.xTile;\n var unitY = unit.yTile;\n var shortestDistance = 999999;\n var selectedTarget;\n\n // Look at each enemy unit left\n for (const targetUnit of this._map.unitBank) {\n if (!unit.isEnemy(targetUnit)) { continue; }\n if (targetUnit.hasStatus(\"Presence Concealment\") || targetUnit.hasStatus(\"Disguise\")) { continue; }\n\n var targetX = targetUnit.xTile;\n var targetY = targetUnit.yTile;\n var distance = Math.abs(unitX - targetX) + Math.abs(unitY - targetY);\n\n // Randomly alternate between accepting equal-distance spots and not\n if (getRandomInt(0, 2)) {\n if (distance < shortestDistance) {\n shortestDistance = distance;\n selectedTarget = targetUnit;\n }\n }\n else {\n if (distance <= shortestDistance) {\n shortestDistance = distance;\n selectedTarget = targetUnit;\n }\n }\n\n }\n\n return selectedTarget;\n }", "function mmove(aa, bb, cc, dd) {\n if ((cc == player.x) && (dd == player.y)) {\n hitplayer(aa, bb);\n return;\n }\n\n var item = itemAt(cc, dd);\n var monster = player.level.monsters[aa][bb];\n\n player.level.monsters[cc][dd] = monster;\n\n if (item.matches(OPIT) || item.matches(OTRAPDOOR)) {\n switch (monster.arg) {\n case BAT:\n case EYE:\n case SPIRITNAGA:\n case PLATINUMDRAGON:\n case WRAITH:\n case VAMPIRE:\n case SILVERDRAGON:\n case POLTERGEIST:\n case DEMONLORD:\n case DEMONLORD + 1:\n case DEMONLORD + 2:\n case DEMONLORD + 3:\n case DEMONLORD + 4:\n case DEMONLORD + 5:\n case DEMONLORD + 6:\n case DEMONPRINCE:\n break;\n\n default:\n player.level.monsters[cc][dd] = null; /* fell in a pit or trapdoor */\n };\n }\n\n if (item.matches(OANNIHILATION)) {\n if (monster.arg >= DEMONLORD + 3) /* demons dispel spheres */ {\n cursors();\n updateLog(`The ${monster} dispels the sphere!`);\n rmsphere(cc, dd); /* delete the sphere */\n } else {\n player.level.monsters[cc][dd] = null;\n setItem(cc, dd, OEMPTY);\n }\n }\n\n monster.awake = true;\n player.level.monsters[aa][bb] = null;\n\n if (monster.matches(LEPRECHAUN) && (item.matches(OGOLDPILE) || item.isGem())) {\n player.level.items[cc][dd] = OEMPTY; /* leprechaun takes gold */\n }\n\n if (monster.matches(TROLL)) { /* if a troll regenerate him */\n if ((gtime & 1) == 0)\n if (monsterlist[monster.arg].hitpoints > monster.hitpoints) monster.hitpoints++;\n }\n\n var what;\n var flag = 0; /* set to 1 if monster hit by arrow trap */\n if (item.matches(OTRAPARROW)) /* arrow hits monster */ {\n what = `An arrow`;\n if ((monster.hitpoints -= rnd(10) + level) <= 0) {\n player.level.monsters[cc][dd] = null;\n flag = 2;\n } else flag = 1;\n }\n if (item.matches(ODARTRAP)) /* dart hits monster */ {\n what = `A dart`;\n if ((monster.hitpoints -= rnd(6)) <= 0) {\n player.level.monsters[cc][dd] = null;\n flag = 2;\n } else flag = 1;\n }\n if (item.matches(OTELEPORTER)) /* monster hits teleport trap */ {\n flag = 3;\n fillmonst(monster.arg);\n player.level.monsters[cc][dd] = null;\n }\n if (player.BLINDCOUNT) return; /* if blind don't show where monsters are */\n\n if (player.level.know[cc][dd] & HAVESEEN) {\n if (flag) {\n cursors();\n beep();\n }\n switch (flag) {\n case 1:\n updateLog(`${what} hits the ${monster}`);\n break;\n case 2:\n updateLog(`${what} hits and kills the ${monster}`);\n break;\n case 3:\n updateLog(`The ${monster} gets teleported`);\n break;\n };\n }\n\n if (player.level.know[aa][bb] & HAVESEEN) show1cell(aa, bb);\n if (player.level.know[cc][dd] & HAVESEEN) show1cell(cc, dd);\n\n}", "function fighter(player) {\n var y = player.y - 1;\n\tvar x = player.x - 1;\n\n for(var idx = y; idx < y+3; idx++) {\n \tfor(var idx2 = x; idx2 < x+3; idx2++) {\n if(idx === player.y && idx2 === player.x) {\n } else {\n var area = mapArrays[idx][idx2];\n if(area.terrainType === \"monster\") {\n if(area.monsterType === \"super golem\") {\n currentEnemy = superGolem;\n } else if(area.monsterType === \"dragon\") {\n currentEnemy = dragon;\n } else if(area.monsterType === \"random\") {\n currentEnemy = getMonster();\n }\n combatStarter(currentEnemy);\n if(area.monsterType === \"dragon\") {\n userCommands = [\"attack\", \"potion\", \"equip\"];\n commandDisplayer();\n }\n placedMonsterCombat = true;\n currentEnemyY = area.y;\n currentEnemyX = area.x;\n break;\n }\n }\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the count of the available pins.
function getPinCount(){ return this.cachedPinInfo.length; }
[ "async available(provider_id = null) {\n let m = 0;\n if (provider_id) {\n m = await this.get_n_available_pp(provider_id);\n }\n\n let n = await this.get_n_available();\n\n return m+n;\n }", "get availableConnectionCount() {\n return this[kConnections].length;\n }", "get count() {\n return this.markers.filter((m) => m.getVisible())\n .length;\n }", "get count() {\r\n return this.markers.filter((m) => m.getVisible())\r\n .length;\r\n }", "function countAvailableNodes() {\r\n\tvar availableNodes = 0;\r\n\tif (nodesPayload != null) {\r\n\t\tfor (var i = 0; i < nodesPayload.length; i++) {\r\n\t\t\tif (nodesPayload[i].isAvailable) {\r\n\t\t\t\tavailableNodes++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn availableNodes;\r\n}", "get count() {\n return this.ranges.length;\n }", "function countMarkers() {\n const ne = rectangle.getBounds().getNorthEast();\n const sw = rectangle.getBounds().getSouthWest();\n let bounds = new window.google.maps.LatLngBounds(sw, ne);\n let count = 0;\n for (let i = 0; i < restaurants.length; i++) {\n let loc = restaurants[i].geometry.location;\n if (bounds.contains(new window.google.maps.LatLng(loc.lat, loc.lng))) {\n count++;\n }\n }\n return \"<b>\" + count + \" restaurant/s in this area.</b><br>\";\n}", "getAvailableSeatCount () {\n return (this.capacity - this.passengerList.length);\n }", "_countNeighboringMines() {\n\t\tlet mineCount = 0;\n\t\tthis.surroundingCells((cell, coord) => {\n\t\t\tif(cell.mine) mineCount++;\n\t\t});\n\t\treturn mineCount;\n\t}", "get_total_num_trackers() {\n var total_num = (Object.keys(data['snitch_map']).length);\n return total_num;\n }", "count() {\n return this.availableTasks().length\n }", "get nbRegisters() { return this._registers.map(r => r.nbNativeRegisters).reduce((p, c) => p + c); }", "function getMinesCount() { \n let count = 0;\n for (let i = 0; i < ROWS; i++)\n for (let j = 0; j < COLS; j++) \n if(isMine(i, j)) count++;\n return count;\n }", "function inning(){\n\t\t\treturn inningCount;\n\t\t}", "countAvailableRows () {\n return this.availableRows.length\n }", "function countAvailableSensors() {\r\n\tvar availableSensors = 0;\r\n\tif (nodesPayload != null) {\r\n\t\tfor (var i = 0; i < nodesPayload.length; i++) {\r\n\t\t\tif (nodesPayload[i].sensors != null) {\r\n\t\t\t\tfor (var j = 0; j < nodesPayload[i].sensors.length; j++) {\r\n\t\t\t\t\tif (nodesPayload[i].sensors[j].isAvailable) {\r\n\t\t\t\t\t\tavailableSensors++;\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}\r\n\treturn availableSensors;\r\n}", "function MarkerCount () {\n return (NextMarkerPos);\n}", "function GetNumTiles() {\n var tileCount = 0;\n\n for (var key in ScrabbleTiles) {\n tileCount += ScrabbleTiles[key].number_remaining;\n }\n\n return tileCount;\n}", "countActiveNeighbours() {\n // returns number of active neighbours\n this.activecount=0;\n for (let i = 0; i < 3; i++) {\n if (this.neighbours[i] && this.neighbours[i].active) {\n this.activecount++;\n }\n }\n return this.activecount;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dispose all Tensors in an UnresolvedLogs object.
function disposeTensorsInLogs(logs) { if (logs == null) { return; } for (var key in logs) { var value = logs[key]; if (typeof value !== 'number') { value.dispose(); } } }
[ "function disposeTensorsInLogs(logs) {\n if (logs == null) {\n return;\n }\n for (var key in logs) {\n var value = logs[key];\n if (typeof value !== 'number') {\n value.dispose();\n }\n }\n}", "function disposeTensorsInLogs(logs) {\n if (logs == null) {\n return;\n }\n for (const key in logs) {\n const value = logs[key];\n if (typeof value !== 'number') {\n value.dispose();\n }\n }\n}", "clearAndClose() {\n this.tensors.forEach(tensor => tensor.tensor.dispose());\n this.tensors = [];\n this.closed_ = true;\n }", "clearAndClose() {\n this.tensorMap.forEach(value => value.dispose());\n this.tensorMap.clear();\n this.handle.dispose();\n }", "function dispose() {\r\n APEAssetTracker.assetRefs.forEach((assetRef, uuid) => {\r\n const asset = assetRef.asset;\r\n untrack(asset);\r\n if (asset instanceof Object3D) {\r\n if (asset.parent) {\r\n asset.parent.remove(asset);\r\n }\r\n }\r\n if ('dispose' in asset) {\r\n asset.dispose();\r\n }\r\n });\r\n APEAssetTracker.assetRefs = new Map();\r\n APEAssetTracker.snapshots = [];\r\n internalUUIDs = new Map();\r\n }", "function dispose() {\n delete filters[dimensionName];\n delete datasets[dimensionName];\n }", "dispose() {\n Object.keys(this._streams).forEach((key) => {\n this._streams[key].forEach((stream) => stream.close());\n });\n this._streams = {}\n }", "dispose() {\n logger.warn('Disposing of analytics adapter.');\n\n if (this.analyticsHandlers && this.analyticsHandlers.size > 0) {\n this.analyticsHandlers.forEach(handler => {\n if (typeof handler.dispose === 'function') {\n handler.dispose();\n }\n });\n }\n\n this.setAnalyticsHandlers([]);\n this.disposed = true;\n }", "dispose() {\n Object.keys(this.weightMap)\n .forEach(key => this.weightMap[key].forEach(tensor => tensor.dispose()));\n }", "clear() {\n {\n for ( let tensor of this.tensors.values() ) {\n tensor.dispose();\n }\n this.tensors.clear();\n }\n\n {\n for ( let numberImage of this.images.values() ) {\n numberImage.disposeResources_and_recycleToPool();\n }\n this.images.clear();\n }\n }", "dispose() {\n this._isDisposed = true;\n for (const d of this._disposables) {\n d.dispose();\n }\n this._disposables.length = 0;\n }", "function deep_dispose() {\n if (instrument != undefined && instrument != null) {\n instrument.dispose();\n instrument = null;\n }\n }", "dispose() {\n logger.debug('Disposing of analytics adapter.');\n\n if (this.analyticsHandlers && this.analyticsHandlers.size > 0) {\n this.analyticsHandlers.forEach(handler => {\n if (typeof handler.dispose === 'function') {\n handler.dispose();\n }\n });\n }\n\n this.setAnalyticsHandlers([]);\n this.disposed = true;\n }", "disposeTiles() {\n this.m_disposedTiles.forEach(tile => {\n tile.dispose();\n });\n this.m_disposedTiles.length = 0;\n }", "dispose () {\n if (this.localStream) {\n this.localStream.getTracks().forEach(track => {\n track.stop();\n });\n this.localStream = undefined;\n }\n }", "cleanup() {\n debug(\"cleanup\");\n this.subs.forEach((subDestroy) => subDestroy());\n this.subs.length = 0;\n this.decoder.destroy();\n }", "dispose() {\n // TODO: Check performance of values(). Probably a generator function,\n // TODO: but should check we don't need a second array\n for (const materialQueue of this.materialMap.values()) {\n materialQueue.dispose();\n }\n\n this.materialMap.clear();\n this.renderPhase = null;\n }", "dispose() {\n cacheAnalytics.drainCachedEvents();\n this.analyticsHandlers.clear();\n }", "dispose() {\n if (!this.isDisposed) {\n this.isDisposed = true;\n const len = this.disposables.length;\n const currentDisposables = new Array(len);\n for (let i = 0; i < len; i++) {\n currentDisposables[i] = this.disposables[i];\n }\n this.disposables = [];\n for (let i = 0; i < len; i++) {\n currentDisposables[i].dispose();\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a description string for a `ComponentHarness` query.
function _getDescriptionForComponentHarnessQuery(query) { const harnessPredicate = query instanceof HarnessPredicate ? query : new HarnessPredicate(query, {}); const { name, hostSelector } = harnessPredicate.harnessType; const description = `${name} with host element matching selector: "${hostSelector}"`; const constraints = harnessPredicate.getDescription(); return (description + (constraints ? ` satisfying the constraints: ${harnessPredicate.getDescription()}` : '')); }
[ "function _getDescriptionForHarnessLoaderQuery(selector) {\n return `HarnessLoader for element matching selector: \"${selector}\"`;\n}", "function _getDescriptionForTestElementQuery(selector) {\n return `TestElement for element matching selector: \"${selector}\"`;\n}", "function _getDescriptionForLocatorForQueries(queries) {\n return queries.map(query => typeof query === 'string'\n ? _getDescriptionForTestElementQuery(query)\n : _getDescriptionForComponentHarnessQuery(query));\n}", "function createComponentHTML() {\n var query = readQueryString();\n setHtmlRootClass(query);\n var component = findByName(components, query.component);\n if(component) return window.html_beautify(generate(component, query));\n return '';\n}", "get description() {\n var _this$props$get;\n\n const value = (_this$props$get = this.props.get('description')) === null || _this$props$get === void 0 ? void 0 : _this$props$get.value;\n if (!value) return '';\n return value;\n }", "get humanDescription() {}", "getDescription() {\n return this.cl_.getDescription();\n }", "getDescription(name) {\n return rxjs_1.concat(this._getInternalDescription(name).pipe(operators_1.map(x => x && x.jobDescription)), rxjs_1.of(null)).pipe(operators_1.first());\n }", "function getDescription(){\n\t\tvar str = \"Draw Tool\";\n\n\t\treturn str;\n\t}", "get htmlDescription(){\n var desc = \"\";\n if(Object.keys(this.inventory).length == 0){\n return '<p>! Gather Resources !</p>';\n }\n else{\n for(var key in this.inventory){\n var value = this.inventory[key];\n desc += \"<p class='resource'>\" + key + \": \" + value + \"</p>\";\n }\n return desc;\n }\n }", "describe(){\n let description = super.describe();\n if(this.hasMajor()){\n description += ` His major is ${this.major}`;\n }\n\n return description;\n }", "description () {}", "async getDescription(bandName){\n var description = await resource.getWikiInfo();\n return description;\n }", "function getDescription(){\n\t\tvar str = \"Move Tool\";\n\n\t\treturn str;\n\t}", "function getSpecName() {\n let spec = _.last(specs);\n let suite = _.last(suites);\n if (spec) {\n return spec.fullName;\n } else if (suite) {\n return suite.description;\n }\n throw new Error('Not currently in a spec or a suite');\n}", "get describe() {\n return `${this.color} ${this.name}: ${this.description} (${this.formattedPrice})`\n }", "function getComponentDisplayName(Component) {\n return Component.displayName || Component.name || 'Unknown'\n}", "describeTable(t) {\n return this.query(`DESCRIBE ${t};`);\n }", "function getDescription() {\n return @tal_plug_desc;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used to calculate shortest route and return the route.
function shortestRoute(source, target, roadMapGraph){ var previous = []; var dist = []; //contains the value from the var targetNode = roadMapGraph.getNodeByName(target); //initialize the dist and previous arrays. for (var i = 0; i < roadMapGraph.nodes.length; i++) { dist.push(Number.MAX_VALUE); previous.push(null); } //Used in the first run in dijkstra's dist[roadMapGraph.nodes.indexOf(roadMapGraph.getNodeByName(source))] = 0; //Q is the datastrukture that controls the visited nodes. it is identical with roadMapGraph. var Q = []; Q = Q.concat(roadMapGraph.nodes); //Main loop in dijkstra's while (areAllNodesVisited(Q) === false){ var u = smallestDistanceNotVisited(Q, dist); var uIndex = Q.indexOf(u); Q[uIndex].visited = true; //if node is unavaible then quit the alorithm. if(dist[uIndex] == Number.MAX_VALUE){ break; } for (var k = 0; k < u.getAllNeighbours().length; k++) { var v = u.getAllNeighbours()[k]; var vIndex = roadMapGraph.nodes.indexOf(v); var alt = dist[uIndex] + distBetween(u, v); if(alt < dist[vIndex]){ dist[vIndex] = alt; previous[vIndex] = u; } } } //Get the whole node path (from -> to) var path = makePath(targetNode, previous, Q); return path; }
[ "function shortest() {\n if(!this.routes.length) { return NO_SUCH_ROUTE; }\n\n return _.min(_.map(this.routes, function(route) {\n return _.sumBy(route, 'weight');\n }));\n}", "function getShortestDistance(){ \n for(var i = 0; i < routes.length; i++){\n var path = routes[i];\n var distance = 0;\n for(var j = 0; j < routes[i].length - 1; j++){\n var point1 = routes[i][j];\n var point2 = routes[i][j+1];\n distance += calculateDistance(point1,point2);\n }\n routeDistances[i] = distance;\n }\n\n var leastDistance = routeDistances[0];\n var bestPath = 0;\n for(var key in routeDistances){\n if(routeDistances[key] < leastDistance){\n leastDistance = routeDistances[key];\n bestPath = key;\n }\n }\n\n var outputPath = '';\n for(var k = 0; k < routes[bestPath].length; k++){\n outputPath += routes[bestPath][k];\n }\n console.log(\"The best path is \" + outputPath + \" with a distance of \" + leastDistance);\n}", "function findShortest() {\n\t\tvar i = googleApiRouteResults.length;\n\t\tvar shortestIndex = 0;\n\t\tvar shortestLength = googleApiRouteResults[0].routes[0].legs[0].distance.value;\n\n\t\twhile (i--) {\n\t\t if (googleApiRouteResults[i].routes[0].legs[0].distance.value < shortestLength) {\n\t\t\tshortestIndex = i;\n\t\t\tshortestLength = googleApiRouteResults[i].routes[0].legs[0].distance.value;\n\t\t }\n\t\t}\n\t\tdirectionsDisplay.setDirections(googleApiRouteResults[shortestIndex]);\n\t }", "cheapestRoute(source, destination) {\n if (!isString(source) || !isString(destination)) {\n throw new Error('Please enter valid data');\n }\n\n let possibleRoutes = this.allPossibleRoutes(source, destination);\n \n let cheapestRoute = [];\n let minWeight = Infinity;\n possibleRoutes.forEach(r => {\n let weight = this.directRoute(r.join('-'));\n if (weight < minWeight) {\n cheapestRoute = r;\n minWeight = weight\n }\n });\n\n return {\n route: cheapestRoute,\n weight: minWeight\n }\n }", "getShortestRoute(city1, city2){\n var dijkstraInfo = this.dijkstra(city1);\n var shortestDistances = dijkstraInfo[0];\n var prevVertex = dijkstraInfo[1];\n var curr = city2;\n var pathSoFar = [];\n\n if (shortestDistances.get(city2) == Infinity){\n return \"NO SUCH ROUTE\";\n }\n else{\n //get the shortest route from prevVertex\n while (curr != city1)\n {\n pathSoFar.push(curr);\n curr = prevVertex.get(curr);\n }\n pathSoFar.push(city1);\n return pathSoFar.reverse();\n }\n }", "function findShortestPath(pointsArray) {\n // Door is at A1\n pointsArray.push('A1');\n var dict = {}, route, totalDistance, shortestRoute = 999999, finalroute;\n for (var j = 0; j < 20000; j++) {\n dict = buildDict(pointsArray);\n //route = calculateRoute2(pointsArray, dict);\n route = calculateRoute3(pointsArray);\n // console.log(route);\n totalDistance = calculateDistance(route, dict);\n // console.log('Total distance travelled: ' + totalDistance);\n if (totalDistance < shortestRoute) {\n shortestRoute = totalDistance;\n finalRoute = route;\n }\n }\n console.log('The shortest route calculated is: ');\n console.log(finalRoute);\n console.log('With a distance traveled of: ');\n console.log(shortestRoute);\n return finalRoute;\n}", "shortestCourierTrip() {\n\n return new Promise((resolve, reject) => {\n\n this.validateConstraints().then((data) => {\n\n let startArr = data.canTravelMap.get(this.start);\n\n // check for -1 route not found\n // when data.canTravelMap has values like { 0 => [ 2 ], 2 => [ 0 ] }\n if (startArr.length === 1 && data.canTravelMap.get(startArr[0]).length === 1 &&\n data.canTravelMap.get(startArr[0])[0] === this.start) {\n\n resolve(-1); // route not found\n\n } else if (this.start === this.dest) {\n resolve(0.0); // start airport same as dest airport\n } else {\n this.canTravelMap = data.canTravelMap;\n this.distanceMap = this.calcTravelDistanceForAllRoutes();\n\n let currTravelPath = this.start;\n\n // as this method is call recursively ,\n // 1st param denotes current airport,2nd param denotes current traveled path\n this.traverseCanTravelMap(this.start, currTravelPath);\n\n resolve(this.milesTraveled);\n }\n\n }).catch(err => {\n reject(err);\n });\n });\n }", "function route(map) {\n // Implement Dijkstra's weighted by trafficLevel\n var inters = map.intersections;\n var startName = document.getElementById('start').value;\n var endName = document.getElementById('end').value;\n var start = getInterWithName(startName, inters);\n var end = getInterWithName(endName, inters);\n var dist = {};\n var prev = {};\n var unvisited = [];\n var infinity = 100000;\n\n dist[start.name] = 0;\n prev[start.name] = null;\n\n if (start && end) {\n for (var i = 0; i < inters.length; i++) {\n var v = inters[i];\n\n if (v !== start) {\n dist[v.name] = infinity;\n prev[v.name] = null;\n }\n unvisited.push(v);\n }\n\n while (unvisited.length > 0) {\n var closestIndex = minDist(dist, unvisited);\n var u = unvisited[closestIndex];\n //console.log(closestIndex);\n if (u === end) {\n var s = [];\n\n while (u !== null) {\n s.push(u);\n u = prev[u.name];\n }\n //console.log(dist);\n return s;\n }\n\n var neighbors = getNeighbors(u);\n unvisited.splice(closestIndex, 1);\n\n for (var j = 0; j < neighbors.length; j++) {\n var v = neighbors[j];\n\n if (unvisited.indexOf(v) < 0) {\n neighbors.splice(j, 1); // Remove neighbors which do not exist in unvisited\n }\n else {\n var currStreet = findStreet(u, v);\n var alt = dist[u.name] + currStreet.trafficLevel;\n\n if (alt < dist[v.name]) {\n dist[v.name] = alt;\n prev[v.name] = u;\n }\n }\n }\n }\n }\n else {\n console.log(\"Bad start/end input - cannot compute shortest path.\");\n }\n\n return;\n}", "function getShortestRoute(startPoint, endPoint, answerObject) {\n\n var currentPath = {\n 'pathString' : \"\",\n 'pathLength' : 0\n };\n\n depthFirstSearch(startPoint, endPoint, 0, 0, true, 0, 0, answerObject, currentPath);\n\n if (answerObject.paths.length > 0) {\n\n var min = answerObject.paths[0].pathLength,\n minIndex = 0;\n\n for (var x in answerObject.paths) {\n\n if (answerObject.paths[x].pathLength < min) {\n\n min = answerObject.paths[x].pathLength;\n minIndex = x;\n\n }\n\n }\n\n answerObject.answerNumber = min;\n answerObject.answerString = answerObject.paths[minIndex].pathString;\n\n } else {\n\n answerObject.answerNumber = -1;\n answerObject.answertString = \"NO SUCH ROUTE\";\n\n }\n\n\n }", "function shortestRoute(position, station) {\n var coordinates = [\n {lat: position.coords.latitude, lng: position.coords.longitude},\n markers[station][\"position\"]\n ]\n\n var route = new google.maps.Polyline({\n path: coordinates,\n geodesic: true,\n strokeColor: '#000000',\n strokeOpacity: 2.0,\n strokeWeight: 4\n });\n\n route.setMap(map);\n}", "function shortest_path(to_x, to_y, use_stations) {\n\t// {{{\n\tvar route = \"<br>\";\n\tvar from_x = current_x;\n\tvar from_y = current_y;\n\n\tvar dist_by_foot = distance_AP(from_x, from_y, to_x, to_y);\n\tvar dist_to_station = places_station[0][3];\n\n\tif (dist_by_foot == 0) {\n\t\troute += \"You are already there ! No need to move.<br>\";\n\t\t// generate_direction() is used to update the direction arrows\n\t\tgenerate_direction(current_x, current_y, to_x, to_y, enable_hud, true);\n\t\treturn route;\n\t}\n\n\tif ((!use_stations) || (dist_by_foot < dist_to_station)) {\n\t\troute += \"Walk to your destination (\" + dist_by_foot + action_point_str + \": \" +\n\t\t\t generate_direction(current_x, current_y, to_x, to_y, enable_hud, true) + \")<br>\";\n\t\treturn route;\n\t}\n\n\tvar places_station_tmp = new Array();\n\tfor (var i = 0; i < places_station.length; ++i) {\n\t\tplaces_station_tmp[i] = new Array();\n\t\tplaces_station_tmp[i][0] = places_station[i][0];\n\t\tplaces_station_tmp[i][1] = places_station[i][1];\n\t\tplaces_station_tmp[i][2] = places_station[i][2];\n\t\tplaces_station_tmp[i][3] = -1;\n\t}\n\t// Compute the distance from to_x, to_y to stations and sort them\n\tsort_places(to_x, to_y, places_station_tmp);\n\n\tvar best_dist_to_dest = dist_to_station + transit_cost_action_point + places_station_tmp[0][3];\n\n\t// Same AP cost ? then walk\n\tif (best_dist_to_dest >= dist_by_foot) {\n\t\troute += \"Walk to your destination (\" + dist_by_foot + action_point_str + \": \" +\n\t\t\t generate_direction(current_x, current_y, to_x, to_y, enable_hud, true) + \")<br>\";\n\t\treturn route;\n\t}\n\n\tif (dist_to_station > 0) {\n\t\troute += \"Walk to the \" + places_station[0][0] + \" station (\" + dist_to_station + action_point_str + \": \"+\n\t\t\t generate_direction(current_x, current_y, places_station[0][1], places_station[0][2], enable_hud, true) + \")<br>\";\n\t}\n\tif (dist_to_station == 0) {\n\t\tgenerate_direction(current_x, current_y, places_station[0][1], places_station[0][2], enable_hud, true, '*&nbsp;' + places_station_tmp[0][0]);\n\t}\n\troute += \"Take the train up to \" + places_station_tmp[0][0] + \" station (\" + transit_cost_action_point + action_point_str + \" + \"+transit_cost_coins+\" \"+ money_unit_str + \").<br>\";\n\troute += \"Walk to your destination (\" + places_station_tmp[0][3] + action_point_str + \": \"+\n\t\t generate_direction(places_station_tmp[0][1], places_station_tmp[0][2], to_x, to_y, false, false) + \")<br>\";\n\n\troute += \"Total travel cost: \" + (parseint(dist_to_station) + transit_cost_action_point + parseint(places_station_tmp[0][3])) + action_point_str + \" & \" + transit_cost_coins + \" \" + money_unit_str + \".<br>\";\n\n\treturn route;\n\t// }}}\n}", "function shortest_path(to_x, to_y, use_stations) {\n\t// {{{\n\tvar route = \"<br>\";\n\tvar from_x = current_x;\n\tvar from_y = current_y;\n\n\tvar dist_by_foot = distance_AP(from_x, from_y, to_x, to_y);\n\tvar dist_to_station = places_station[0][3];\n\n\tif (dist_by_foot == 0) {\n\t\troute += \"You are already there ! No need to move.<br>\";\n\t\t// generate_direction() is used to update the direction arrows\n\t\tgenerate_direction(current_x, current_y, to_x, to_y, enable_hud, true);\n\t\treturn route;\n\t}\n\n\tif ((!use_stations) || (dist_by_foot < dist_to_station)) {\n\t\troute += \"Walk to your destination (\" + dist_by_foot + action_point_str + \": \" +\n\t\t\t generate_direction(current_x, current_y, to_x, to_y, enable_hud, true) + \")<br>\";\n\t\treturn route;\n\t}\n\n\tvar places_station_tmp = new Array();\n\tfor (var i = 0; i < places_station.length; ++i) {\n\t\tplaces_station_tmp[i] = new Array();\n\t\tplaces_station_tmp[i][0] = places_station[i][0];\n\t\tplaces_station_tmp[i][1] = places_station[i][1];\n\t\tplaces_station_tmp[i][2] = places_station[i][2];\n\t\tplaces_station_tmp[i][3] = -1;\n\t}\n\t// Compute the distance from to_x, to_y to stations and sort them\n\tsort_places(to_x, to_y, places_station_tmp);\n\n\tvar best_dist_to_dest = dist_to_station + transit_cost_action_point + places_station_tmp[0][3];\n\n\t// Same AP cost ? then walk\n\tif (best_dist_to_dest >= dist_by_foot) {\n\t\troute += \"Walk to your destination (\" + dist_by_foot + action_point_str + \": \" +\n\t\t\t generate_direction(current_x, current_y, to_x, to_y, enable_hud, true) + \")<br>\";\n\t\treturn route;\n\t}\n\n\tif (dist_to_station > 0) {\n\t\troute += \"Walk to the \" + places_station[0][0] + \" station (\" + dist_to_station + action_point_str + \": \"+\n\t\t\t generate_direction(current_x, current_y, places_station[0][1], places_station[0][2], enable_hud, true) + \")<br>\";\n\t}\n\troute += \"Take the train up to \" + places_station_tmp[0][0] + \" station (\" + transit_cost_action_point + action_point_str + \" + \"+transit_cost_coins+\" \"+ money_unit_str + \").<br>\";\n\troute += \"Walk to your destination (\" + places_station_tmp[0][3] + action_point_str + \": \"+\n\t\t generate_direction(places_station_tmp[0][1], places_station_tmp[0][2], to_x, to_y, false, false) + \")<br>\";\n\n\troute += \"Total travel cost: \" + (parseInt(dist_to_station) + transit_cost_action_point + parseInt(places_station_tmp[0][3])) + action_point_str + \" & \" + transit_cost_coins + \" \" + money_unit_str + \".<br>\";\n\n\treturn route;\n\t// }}}\n}", "function getShortestPath(ways, startLocation, destinationLocation) {\n var path = [];\n _ways = ways;\n if (ways) {\n if (startLocation && destinationLocation) {\n //find start and end point\n var startPoint = findNearestWayPoint(startLocation);\n var endPoint = findNearestWayPoint(destinationLocation);\n //find all possible navigation paths\n var routePoints = [];\n path.push(startLocation);\n navigationPaths = [];\n if (calculateDistance(startPoint, endPoint) != 0) {\n findNavigationPaths(-1, startPoint, endPoint, routePoints);\n }\n if (navigationPaths.length > 0) {\n //find shortest navigation path\n var shortestPath = { points: [], distance: Number.POSITIVE_INFINITY };\n for (var i = 0; i < navigationPaths.length; i++) {\n if (navigationPaths[i].distance < shortestPath.distance) {\n shortestPath = navigationPaths[i];\n }\n }\n for (var j = 0; j < shortestPath.points.length; j++) {\n path.push(shortestPath.points[j]);\n }\n }\n else {\n path.push(startPoint);\n path.push(endPoint);\n }\n path.push(destinationLocation);\n }\n }\n return path;\n }", "shortestPath(source){\n let distances = [];\n let visitedVertices = [];\n let size = this.graph.length;\n // initialize distances as infinity and visitedVertices as false\n\n for(let i = 0; i < size; i++){\n distances[i] = Infinity;\n visitedVertices[i] = false;\n }\n\n // min distance of source from itself is 0\n distances[source] = 0;\n\n for(let i = 0; i < size - 1; i++){\n let minDistanceVertexIndex = this.findMinDistanceVertexIndex(distances, visitedVertices);\n\n visitedVertices[minDistanceVertexIndex] = true;\n\n for (let j = 0; j < size; j++){\n if(!visitedVertices[j] && this.graph[minDistanceVertexIndex][j] != 0 && distances[minDistanceVertexIndex] != Infinity && distances[minDistanceVertexIndex] + this.graph[minDistanceVertexIndex][j] < distances[j]){\n distances[j] = distances[minDistanceVertexIndex] + this.graph[minDistanceVertexIndex][j];\n }\n }\n }\n return distances;\n }", "searchShortestPathToEnds() {\n let shortest = null;\n let shortestDistance = Number.MAX_SAFE_INTEGER\n for (let i = 0; i < this.graph.nodes.length; i++) {\n let node = this.graph.nodes[i]\n if (node.id == 2 && node.distance < shortestDistance) {\n shortest = node;\n shortestDistance = node.distance\n }\n }\n if (shortest == null) {\n return null\n }\n return shortest\n }", "route(s, t) {\n var source = this.nodes[s], target = this.nodes[t];\n this.obstacles = this.siblingObstacles(source, target);\n var obstacleLookup = {};\n this.obstacles.forEach(o => obstacleLookup[o.id] = o);\n this.passableEdges = this.edges.filter(e => {\n var u = this.verts[e.source], v = this.verts[e.target];\n return !(u.node && u.node.id in obstacleLookup\n || v.node && v.node.id in obstacleLookup);\n });\n // add dummy segments linking ports inside source and target\n for (var i = 1; i < source.ports.length; i++) {\n var u = source.ports[0].id;\n var v = source.ports[i].id;\n this.passableEdges.push({\n source: u,\n target: v,\n length: 0\n });\n }\n for (var i = 1; i < target.ports.length; i++) {\n var u = target.ports[0].id;\n var v = target.ports[i].id;\n this.passableEdges.push({\n source: u,\n target: v,\n length: 0\n });\n }\n var getSource = e => e.source, getTarget = e => e.target, getLength = e => e.length;\n var shortestPathCalculator = new shortestpaths_1.Calculator(this.verts.length, this.passableEdges, getSource, getTarget, getLength);\n var bendPenalty = (u, v, w) => {\n var a = this.verts[u], b = this.verts[v], c = this.verts[w];\n var dx = Math.abs(c.x - a.x), dy = Math.abs(c.y - a.y);\n // don't count bends from internal node edges\n if (a.node === source && a.node === b.node || b.node === target && b.node === c.node)\n return 0;\n return dx > 1 && dy > 1 ? 1000 : 0;\n };\n // get shortest path\n var shortestPath = shortestPathCalculator.PathFromNodeToNodeWithPrevCost(source.ports[0].id, target.ports[0].id, bendPenalty);\n // shortest path is reversed and does not include the target port\n var pathPoints = shortestPath.reverse().map(vi => this.verts[vi]);\n pathPoints.push(this.nodes[target.id].ports[0]);\n // filter out any extra end points that are inside the source or target (i.e. the dummy segments above)\n return pathPoints.filter((v, i) => !(i < pathPoints.length - 1 && pathPoints[i + 1].node === source && v.node === source\n || i > 0 && v.node === target && pathPoints[i - 1].node === target));\n }", "function updateShortestRoute() {\n \n pts = selectedEndpts();\n now = selectedTime();\n\n if (pts.length == 2) { // get route from backend, store metadata, display route\n $.ajax({\n url: '/route/shortest',\n type: 'get',\n data: {lat0: pts[0].lat, lon0: pts[0].lng, lat1: pts[1].lat, lon1: pts[1].lng,\n hour: now.hour, minute: now.minute},\n dataType: 'json',\n error: function(result) {console.log('Failed to fetch route, result:', result);},\n success: function(result) {\n shortestRouteLength = result.length;\n shortestRouteSun = result.sun;\n }\n });\n }\n}", "function shortestWay(origin, destination, locations, colleages) {\n return optimalWay(origin, destination, locations, colleages, distanceRelation);\n}", "shortestPath(src)\n\t{\n\t\t// Create a priority queue to store vertices that\n\t\t// are being preprocessed. This is weird syntax in C++.\n\t\t// Refer below link for details of this syntax\n\t\t// https://www.geeksforgeeks.org/implement-min-heap-using-stl/\n\t\tlet pq = [];\n\n\t\t// Create a vector for distances and initialize all\n\t\t// distances as infinite (INF)\n\t\tlet dist = new Array(V).fill(INF);\n\n\t\t// Insert source itself in priority queue and initialize\n\t\t// its distance as 0.\n\t\tpq.push([0, src]);\n\t\tdist[src] = 0;\n\n\t\t/* Looping till priority queue becomes empty (or all\n\t\tdistances are not finalized) */\n\t\twhile (pq.length > 0) {\n\t\t\t// The first vertex in pair is the minimum distance\n\t\t\t// vertex, extract it from priority queue.\n\t\t\t// vertex label is stored in second of pair (it\n\t\t\t// has to be done this way to keep the vertices\n\t\t\t// sorted distance (distance must be first item\n\t\t\t// in pair)\n\t\t\tlet u = pq[0][1];\n\t\t\tpq.shift();\n \n\t\t\t// 'i' is used to get all adjacent vertices of a\n\t\t\t// vertex\n\t\t\tfor(let i = 0; i < this.adj[u].length; i++){\n\t\t\t\t\n\t\t\t\t// Get vertex label and weight of current\n\t\t\t\t// adjacent of u.\n\t\t\t\tlet v = this.adj[u][i][0]; //u se jude hue adjency vertex ka label\n\t\t\t\tlet weight = this.adj[u][i][1]; //u ka weight\n\n\t\t\t\t// If there is shorted path to v through u.\n\t\t\t\tif (dist[v] > dist[u] + weight) {\n\t\t\t\t\t// Updating distance of v\n\t\t\t\t\tdist[v] = dist[u] + weight;\n\t\t\t\t\tpq.push([dist[v], v]);\n\t\t\t\t\tpq.sort((a, b) =>{\n\t\t\t\t\t\tif(a[0] == b[0]) return a[1] - b[1];\n\t\t\t\t\t\treturn a[0] - b[0];\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Print shortest distances stored in dist[]\n\t\tdocument.write(\"Vertex Distance from Source\");\n\t\tfor (let i = 0; i < V; ++i)\n\t\t\tdocument.write(i, \"\t \", dist[i]);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
hovers the correspoinding position on the map/ the height profile
function handleHeightProfileHover(atts) { map.hoverPosition(atts.lon, atts.lat); }
[ "function handleHover(centered, d){\n mediumlightBar(mapObj[d.properties.ID].realname);\n}", "function hoverPositions(){\n if(board === \"Player\"){\n if(!handleHover) return\n handleHover(coords)\n } else if(board === \"Ai\"){\n if(!handleHover) return\n handleHover(coords)\n }\n }", "function activateHoverInfo() {\n mapImplementation.ActivateHoverInfo();\n }", "function markerMouseoverCallback(event) {\n document.getElementById(\"bottom-left-coordinates-lat\").innerHTML = $.i18n('coordinates-hover-container-latitude') + \": \" + parseFloat(event.feature.getProperty(\"Latitud\").toFixed(4)) + \"°\";\n document.getElementById(\"bottom-left-coordinates-lng\").innerHTML = $.i18n('coordinates-hover-container-longitude') + \": \" + parseFloat(event.feature.getProperty(\"Longitud\").toFixed(4)) + \"°\";\n fadeInElements([\"map-bottom-left-container\"], 350);\n}", "handleHover(e) {\n this.setState({ mousePos: e.lngLat });\n }", "function initHover() {\r\n\t\t$('#map-hover-box').show();\r\n\t\t$(document).bind('mousemove', getPosition);\r\n\t}", "function changeShipHoverPos(event) {\r\n if (state.phase !== 'setup') {\r\n return;\r\n }\r\n shipHoverEl.style.left = `calc(${event.pageX}px - 2vw)`;\r\n shipHoverEl.style.top = `calc(${event.pageY}px - 2vw)`;\r\n}", "hover() {\n this.y -= 5;\n }", "function mapHoverHandler(eventObject) {\n console.log('event object', eventObject);\n cosnole.log('mouse lat/lng', evenObject.latlng)\n //update mouse coordinates HTML element with event latlng\n \n document.getElementById(\"mouseCoordinatesBox\").innerHTML=\"newtext\";\n \n \n}", "function hoverTile(elem, r, c) {\n \n}", "function mapMouseover(d) {\n\n\t\t// check if country has data to display\n\t\tif (d3.select(this).attr(\"class\") == \"notActive\") return;\n\n\t\t// make tooltip visible and display values\n\t\ttooltip.transition()\n\t\t.duration(100)\n\t\t.style(\"opacity\", .9);\n\t\ttooltip.html(\"Country: <span style='color:red'>\" + d.properties.admin \n\t\t\t+ \"</span> <br/>GDP: <span style='color:red'>$\" \n\t\t\t+ GDPdata.filter(x => x.countrycode == d.properties.iso_a2)[0].GDP + \"</span>\")\n\t\t\t.style(\"left\", (d3.event.pageX - 90) + \"px\") \n\t\t\t.style(\"top\", (d3.event.pageY - 77) + \"px\");\n\t}", "function setProfilePointer(p) {\n var rect = canvas.getRect();\n var x = (pathDistance / pathLength) * rect.width;\n\n var rect2 = heightPointer.getRect();\n p = map.convertCoordsFromPhysToPublic(p); \n\n heightPointer.setStyle('display', 'block');\n heightPointer.setStyle('left', (rect.left + x -(rect2.width*0.5)) + 'px');\n heightPointer.setStyle('top', (rect.top) + 'px');\n heightPointer.setHtml((p[2]).toFixed(2) + \" m\");\n\n heightPointer2.setStyle('display', 'block');\n heightPointer2.setStyle('left', (rect.left + x - 1) + 'px');\n heightPointer2.setStyle('top', (rect.top) + 'px');\n}", "onHover() {\n const gl = this.gl;\n gl.bindFramebuffer(gl.FRAMEBUFFER, this.fbo);\n // convert position to pixel space -- only applies if client width is different than the cavas size\n const pixelX = (this.x * gl.canvas.width) / gl.canvas.clientWidth;\n const pixelY =\n gl.canvas.height -\n (this.y * gl.canvas.height) / gl.canvas.clientHeight -\n 1;\n const id = this.readPixels(pixelX, pixelY);\n if (id === this.BACKGROUND_ID) {\n // clean up\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n return;\n }\n this.callbacks[EVENT_TYPES.MOUSE_HOVER].forEach((cb) => {\n cb(id);\n });\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n }", "function mapHover() {\r\n $('path').hover( \r\n function(e) {\r\n //check whether chosen path has class (is this region in SET)\r\n if ( $(e.target).attr('class') ) {\r\n let code = $(e.target).attr('class');\r\n // if area is in SET and there is no other effects (area wasn't under search or click effects),\r\n // set to all code areas to HOVER_COLOR\r\n if (this.style.fill == DEFAULT_COLOR) {\r\n setCountryColor(code, HOVER_COLOR);\r\n }\r\n //in case area is not in database set NOT_IN_DB_HOVER_COLOR\r\n } else if (this.style.fill == DEFAULT_COLOR) {\r\n this.style.fill = NOT_IN_DB_HOVER_COLOR;\r\n }\r\n \r\n },\r\n function(e) {\r\n //check whether chosen path has class (is this region in SET)\r\n if ( $(e.target).attr('class') ) {\r\n let code = $(e.target).attr('class');\r\n // if area is in SET and there is no other effects but HOVER_COLOR (area wasn't under search or click effects),\r\n // set to all code areas to DEFAULT_COLOR\r\n if (this.style.fill == HOVER_COLOR) {\r\n setCountryColor(code, DEFAULT_COLOR);\r\n }\r\n //in case area is not in database set DEFAULT_COLOR back\r\n } else if (this.style.fill == NOT_IN_DB_HOVER_COLOR) {\r\n this.style.fill = DEFAULT_COLOR;\r\n }\r\n \r\n });\r\n }", "function drawHouseHover() {\n if (withinGrid() && getCurrentTile()[2] != 0 && player.holding[0] == 0) {\n var startX = (window.innerWidth/2)+100;\n var startY = window.innerHeight/2;\n\n ctx.strokeStyle = \"#fff\";\n ctx.lineWidth = 5;\n ctx.beginPath();\n ctx.moveTo(mouse[0],mouse[1]);\n ctx.lineTo(startX,startY);\n ctx.stroke();\n ctx.fillStyle = \"rgba(244,66,232,0.8)\";\n ctx.fillRect(startX,startY,250,180);\n ctx.strokeRect(startX,startY,250,180);\n ctx.fillStyle = \"#fff\";\n\n var family = 0;\n\n //Search through family array for the family living in this tile\n for (i=0;i<families.length;i++) {\n if (families[i][\"home\"] == getArrayPosFromMouse()) {\n family = families[i];\n break;\n }\n }\n //Draw the name at the top of the box\n ctx.textAlign = \"right\";\n ctx.font = \"30px Orbitron\";\n startY+=25;\n ctx.fillText(family[\"surname\"],startX+240,startY);\n //Draw the white underline\n startX+=20;\n startY+=15;\n ctx.fillRect(startX,startY,220,5);\n //Draw the number of adults and children\n startX = (window.innerWidth/2)+340;\n ctx.font = \"20px Orbitron\";\n startY+=30;\n ctx.fillText(\"Adults: \"+family[\"adults\"].length+\" Kids: \"+family[\"children\"].length,startX,startY);\n\n startY+=30;\n //Combine the happiness level of every family member\n var familyHappiness = 0;\n var noFamilyMembers = 0;\n for (i=0;i<family[\"adults\"].length;i++) {\n familyHappiness+=family[\"adults\"][i].happiness;\n noFamilyMembers++;\n }\n for (i=0;i<family[\"children\"].length;i++) {\n familyHappiness+=family[\"children\"][i].happiness;\n noFamilyMembers++;\n }\n //Draw the happiness bar for the family\n ctx.fillText(\"Happiness\",startX,startY);\n startY+=20;\n ctx.fillStyle = \"#c132b8\";\n ctx.fillRect(startX-220,startY,220,30);\n ctx.fillStyle = \"#3fbfe2\";\n var happinessLength = (familyHappiness/noFamilyMembers)*220;\n ctx.fillRect(startX-220,startY,happinessLength,30);\n }\n}", "function mpMouseover() {\n // Get mouse positions from the main canvas.\n var mousePos = d3.mouse(this)\n // Get the data from our map!\n if (typeof (transform) !== \"undefined\") {\n var nodeData = quadtree.find((mousePos[0] - margin.left - transform[\"x\"]) / transform[\"k\"],\n (mousePos[1] - margin.top - transform[\"y\"]) / transform[\"k\"], 50)\n } else {\n nodeData = quadtree.find(mousePos[0] - margin.left, mousePos[1] - margin.top, 50)\n }\n\n // Only show mouseover if hovering near a point\n if (typeof (nodeData) !== \"undefined\") {\n // If we're dealing with mp nodes\n if (typeof (nodeData.id) !== \"undefined\") {\n slide5_show_mp_tooltip(nodeData, mousePos)\n } else {\n median_mouseover(nodeData, mousePos)\n }\n }\n d3.event.preventDefault()\n\n }", "function mouseOverGraphic(ev) {\n map.setMapCursor(\"crosshair\");\n}", "onPointHoverOff() {\n this.props.actions.setPointHovered(false);\n this.toggleGlobeVisibility(0, 0.99, 1);\n }", "function getPosition(event) {\r\n\t\tposX = event.clientX;\r\n\t\tposY = event.clientY;\r\n\t\t$('#map-hover-box').css({\r\n\t\t\t'left': posX - ($('#map-hover-box').outerWidth(true) / 2),\r\n\t\t\t'top': posY + 15\r\n\t\t});\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show the navigation element dialog
function showNavigationElementDialog(options) { return spNavigationElementDialog.showDialog(options); }
[ "function open(){\n\t\tresizePopin();\n\t\toptions.show(domElement);\n\t}", "function navigateToFrmOptions(){\n\tfrmOptions.show();\n}", "showHyperlinkDialog() {\n if (this.hyperlinkDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.hyperlinkDialogModule.show();\n }\n }", "function showSelection() {\n navigationBrowse(memSelection);\n}", "function showNavigation(choice){\n\tvar diagnosisShown=0;\n\t$( \".clickLocate\" ).each( function(){\n\t\t$(this).showChoices(choice);\n\t})\n\n\tif(disp==\"Base\"){\n\t\t$('#diagnoses').hide();\n\t\treturn;\n\t}\n\n\t$('#diagnoses').show();\n\t$( \".clickDiagnose\" ).each( function (){\n\tdiagnosisShown+=$(this).showChoices(choice);\t\t\n\t\t})\n\tif(diagnosisShown==0){\n\t\t$('#diagnoses').hide();\n\t}\n\t$('#diagnosehader').text(\"Select which \" +disp);\n\treturn;\n\n}", "function showRelsParentes(){\n\t$( '#RELS_PARENTES' ).dialog( 'open' );\n}", "show() {\n this.style.pointerEvents = 'none'; // To \"allow interaction outside dialog\"\n this.open = true;\n }", "function IDialogShow() {}", "function navigateTofrmMenu(){\n\t\tfrmMenu.show();\n}", "function OpenMultipleLocations()\n{\n document.getElementById('multiple-location-dialog').style.display = 'block'; \n}", "function showSetOpsView() {\n var genomeId = getQueryVariable(\"genomeId\");\n var projectId = getQueryVariable(\"projectId\");\n var dtitle = \"Set Operations on Genome: \" + genomeId;\n var link = \"index.php?id=28&projectId=\" + projectId + \"&genomeId=\" + genomeId;\n var dialog = $('<div></div>')\n .load(link)\n .dialog({\n autoOpen: true,\n title: dtitle,\n width: 400,\n height: 'auto',\n resizable: false,\n modal: true,\n stack: true,\n position: 'center',\n close: function(ev, ui) { $(this).remove();}\n });\n}", "function openDialog(ev) {\n var element = document.getElementById(\"dialogWrapper\");\n element.style.zIndex = 99;\n element.style.opacity = 1;\n\n var details = document.getElementById(\"details\");\n details.style.visibility = \"hidden\";\n\n var dialog = document.getElementById(\"dialog\");\n dialog.style.visibility = \"visible\";\n dialog.style.zIndex = 100;\n dialog.style.opacity = 1;\n}", "function openNav() {\n\t//document.getElementById(\"ControlPanel\").style.display = \"block\";//show control pannel\n\tShowOf(ControlPanel, true);\n\t//document.getElementById(\"buttonOpenControlPanel\").style.display = \"none\";//hide open control pannle button\n\tShowOf(buttonOpenControlPanel, false);\n}", "function ShowDetailsDialog(){\n $('#DetailsDialog').dialog('open');\n}", "enable() {\n this.navigation.open(this);\n }", "function show(id)\n{\n let element = null;\n if (this instanceof Element)\n element = this;\n else\n if (id instanceof Element)\n element = id;\n else\n element = document.getElementById(id);\n element.style.display = 'block';\n element.style.visibility = 'visible';\n element.scrollIntoView();\n\n // set the focus on the first button in the dialog\n // displayDialog ensures that even if the dialog designer forgot\n // to include any buttons at least one is always present\n let buttons = element.getElementsByTagName('BUTTON');\n if (buttons.length > 0)\n buttons[0].focus();\n}", "showAdditionalTosDialog() {\n this.$.additionalToS.showDialog();\n this.$.closeAdditionalTos.focus();\n }", "showListDialog() {\n if (this.listDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.listDialogModule.showListDialog();\n }\n }", "open() {\n\t\t$('body').append(this.$dialog)\n\t\tthis.$dialog.show()\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a file from the git index (aka staging area) Note that this does NOT delete the file in the working directory.
async function remove ({ dir, gitdir = path__WEBPACK_IMPORTED_MODULE_0___default.a.join(dir, '.git'), fs: _fs, filepath }) { const fs = new FileSystem(_fs); await GitIndexManager.acquire( { fs, filepath: `${gitdir}/index` }, async function (index) { index.delete({ filepath }); } ); // TODO: return oid? }
[ "function removeFile(index){\r\n\t\tdelete(files.local[index]);\r\n\t}", "async function remove ({\n core = 'default',\n dir,\n gitdir = join(dir, '.git'),\n fs: _fs = cores.get(core).get('fs'),\n filepath\n}) {\n try {\n const fs = new FileSystem(_fs);\n await GitIndexManager.acquire(\n { fs, filepath: `${gitdir}/index` },\n async function (index) {\n index.delete({ filepath });\n }\n );\n // TODO: return oid?\n } catch (err) {\n err.caller = 'git.remove';\n throw err\n }\n}", "remove(filePath) {\n filePath = this.normalizeSlashToUnix(filePath);\n debug('removing source file \"%s\"', filePath);\n delete this.projectFiles[filePath];\n }", "function removeFile() {\n var root = getFileSystemRoot();\n var remove_file = function(entry) {\n entry.remove(function() {\n navigator.notification.alert(entry.toURI(), null, 'Entry deleted'); \n }, onFileSystemError);\n };\n \n // retrieve a file and truncate it\n root.getFile('bbgap.txt', {create: false}, remove_file, onFileSystemError);\n }", "function deleteFile(pays, fileName){\n repo.remove(BRANCH, pays+'/'+fileName, function(err) {});\n}", "function removeFile(idx) {\n\t\t// Remove preview tag\n\t\tvar currentPreview = currentFiles[idx].preview;\n\t\tvar parentTag = currentPreview.parentNode;\n\t\tparentTag.removeChild(currentPreview);\n\t\t\n\t\t// Remove the element in the array\n\t\tcurrentFiles.splice(idx, 1);\n\t}", "function delFile(file){\r\n if(fs.existsSync(file)){\r\n fs.unlink(file, (err) => {\r\n if(err){\r\n console.log(err);\r\n }else {\r\n console.log('File Deleted!');\r\n }\r\n })\r\n}\r\n}", "_removeFile(filename) {\n let index = this._files.indexOf(filename)\n\n if (index !== -1) {\n this._files.splice(index, 1)\n\n if (this.options.load) {\n this._list.splice(index, 1)\n }\n\n filename = this._toGroup(filename)\n this._removeID(filename.group, filename.ID)\n }\n }", "deleteScriptFile(state, fileName) {\n const index = state.scriptFileList.indexOf(fileName);\n state.scriptFileList.splice(index, 1);\n }", "rm(path, opts = {}) {\n Files.assertInRepo();\n Config.assertNotBare();\n\n // Get the paths of all files in the index that match `path`.\n const filesToRm = Index.matchingFiles(path);\n\n // Abort if `-f` was passed. The removal of files with changes is\n // not supported.\n if (opts.f) {\n throw new Error('unsupported');\n\n // Abort if no files matched `path`.\n } else if (filesToRm.length === 0) {\n throw new Error(`${Files.pathFromRepoRoot(path)} did not match any files`);\n\n // Abort if `path` is a directory and `-r` was not passed.\n } else if (fs.existsSync(path) && fs.statSync(path).isDirectory() && !opts.r) {\n throw new Error(`not removing ${path} recursively without -r`);\n } else {\n // Get a list of all files that are to be removed and have also\n // been changed on disk. If this list is not empty then abort.\n const changesToRm = Util.intersection(Diff.addedOrModifiedFiles(), filesToRm);\n if (changesToRm.length > 0) {\n throw new Error(`these files have changes:\\n${changesToRm.join('\\n')}\\n`);\n\n // Otherwise, remove the files that match `path`. Delete them\n // from disk and remove from the Index.\n } else {\n filesToRm.map(Files.workingCopyPath).filter(fs.existsSync).forEach(fs.unlinkSync);\n filesToRm.forEach((p) => { Gitlet.update_index(p, { remove: true }); });\n }\n }\n }", "function delFile(filepath){\n\n var fileName = filepath.substring(5, filepath.length - 4);\n try {\n //file removed\n fs.unlinkSync(fileName + '.html')\n fs.unlinkSync(filepath);\n console.log(\"Del\");\n \n } catch(err) {\n console.error(err)\n }\n\n}", "function removeAssetFile() {\n\t\treturn removeFiles(\n\t\t\tpath.join(\n\t\t\t\tprojectRoot,\n\t\t\t\toutput.storeAssetsJsonTo,\n\t\t\t\tASSETS_JSON_FILE_NAME\n\t\t\t),\n\t\t\tpermissions.allowForceRemove,\n\t\t\tpermissions.dryRun\n\t\t);\n\t}", "function deleteFile(filename) {\n var filePath = path.relative(WORKING_DIRECTORY, filename);\n //Send file information to server along with project name\n socket.emit('fileDelete', {\n 'path': filePath,\n 'project': PROJECT\n });\n}", "function removeFile(file) {\n if (!file) return;\n files.value = files.value.filter((f) => f.value.name !== file.name);\n }", "removeFile(path){\n if(!this.hasFile(path)){\n console.log('File not added to watcher. File: ' + path);\n return;\n }\n const watches = this._watches;\n for(var i = 0, len = watches.length; i < len; ++i){\n if(watches[i].file.path == path){\n watches.splice(i,1);\n return;\n }\n }\n }", "_removeFile(name) {\n let index = this.indexOf(name)\n\n if (index !== -1) {\n this._files.splice(index, 1)\n\n if (this.options.load) {\n this._list.splice(index, 1)\n }\n }\n }", "function removeFile(fileEntry) {\n\t\tfunction success(fileEntry) {\n \t\tconsole.log(\"Removal succeeded\");\n \t\talert(\"Removal succeeded\");\n\t\t}\n\t\tfunction fail(error) {\n \t\talert('Error removing file: ' + error.code);\n\t\t}\n\t\t// remove the file\n\t\tentry.remove(success, fail);\n\t}", "function removeFile(fileName) {\n if (projectFilesSet[fileName]) {\n getReferencedOrImportedFiles(fileName).forEach(function (referencedFileName) {\n removeReference(fileName, referencedFileName);\n });\n delete projectFilesSet[fileName];\n languageServiceHost.removeScript(fileName);\n }\n }", "function removeFile(file) {\n if (file.hash ===\n crypto\n .createHash(file.hashType)\n .update(file.name + 'LOG_FILE' + file.date)\n .digest('hex')) {\n try {\n if (fs.existsSync(file.name)) {\n fs.unlinkSync(file.name);\n }\n }\n catch (e) {\n debug(new Date().toLocaleString(), '[FileStreamRotator] Could not remove old log file: ', file.name);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a Random Number between 0 and upper. (e.g. 0255)
function getRandomNum(upper){ return Math.floor( Math.random() * upper ); }
[ "function randomNumber(upper) {\n return Math.floor( Math.random() * upper);\n}", "function randint(lower, upper) { return Math.floor(Math.random() * (upper-lower) + lower); }", "function randomInt(upper) {\n with(Math) {\n return floor(random() * upper);\n };\n}", "function randValue (upper) {\n let randomValue = (Math.floor(Math.random() * upper))\n return randomValue\n}", "function rng(lower, upper) {\r\n\treturn Math.floor(Math.random() * (upper - lower)) + lower;\r\n}", "_getRandomValue(lower, upper) {\n return Math.floor(Math.random() * (upper - lower)) + lower;\n }", "_getRandomValue(lower, upper) {\n return Math.floor(Math.random() * (upper - lower)) + lower;\n }", "function randUpTo255() {\n return Math.floor(Math.random() * 256)\n}", "function randomNumber(lower, upper) {\n return Math.floor(Math.random() * (upper - lower + 1)) + lower;\n}", "function randomNumberGenerator(upperLimit){\n return (Math.floor(Math.random()*upperLimit));\n}", "function randomNum (){\n\treturn Math.floor(Math.random() * 255);\n}", "function rand(lower, upper) {\n\treturn Math.floor(Math.random() * (upper - lower + 1)) + lower;\n}", "function randomNumber(upperRange) {\n console.log(\"randomNumber\", upperRange);\n\n return Math.floor(Math.random() * upperRange);\n}", "function getRandomNumber(lower, upper)\n{\n return Math.floor((Math.random() * (upper - lower)) + lower);\n}", "function randInt(lower, upper) {\n return Math.floor(Math.random() * (upper - lower)) + lower;\n}", "function generateBetweenZeroAndNum(num) {\n return Math.floor(Math.random() * num);\n }", "function randomFrom(lowerValue,upperValue){\n\tvar choises = upperValue - lowerValue + 1;\n\treturn Math.floor(Math.random() * choises + lowerValue);\n}", "function randomInt(ub)\n{\n return Math.floor(Math.random() * ub)\n}", "function randint(int) { return Math.floor((lcg.rand()*int)); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scrape new article and then udpate HTML page
function getNewArticles() { // update table to notify we are loading new items $("#articleList").html(processingArticlesHTML) // scrape for new stories $.get("/api/scrapeNotSaved") .then(function (data) { console.log(data) if (data.length > 0) { console.log("I have data! Will call update list function!") updateArticleList(data) } else { console.log("I do not have data! will call no New articles function!") noNewArticles() } }) }
[ "function populateArticle(html, article) {\n if (html.length > 1) {\n html = $(html[0]);\n }\n if (!article.seen) {\n html.find(\".breaking-news\").removeClass(\"hidden\");\n } else {\n html.find(\".breaking-news\").addClass(\"hidden\");\n }\n article.seen = true;\n html.find(\".network-icon\").attr(\"src\", article.network_image);\n html.find(\".network-icon\").attr(\"alt\", article.network_short);\n html.find(\".network-name\").text(article.network_full);\n html.find(\".title\").text(article.title);\n html.find(\".author\").text(\"By \" + article.author);\n html.find(\".image\").attr(\"src\", article.img_url);\n html.find(\".article-text\").text(article.article_body);\n}", "function updateHtmlContentWithTheRetrievedArticleData(article) {\n\n // 3) CREATE AND UPDATE HTML ELEMENTS AND APPEND THEM TO THE DOCUMENT\n // 3.1 create the HTML elements to be appended, and set their content\n var title = document.createElement('h1');\n // 3.2 update the HTML 'article-view.html' contents with the contents of the article retrieved from the mockup database\n title.innerText = article.title;\n\n // 3.1 create the HTML elements to be appended, and set their content\n var description = document.createElement('h3');\n // 3.2 update the HTML 'article-view.html' contents with the contents of the article retrieved from the mockup database\n description.innerText = article.description;\n\n // 3.1 create the HTML elements to be appended, and set their content\n var content = document.createElement('p');\n // 3.2 update the HTML 'article-view.html' contents with the contents of the article retrieved from the mockup database\n content.innerText = article.content;\n\n // 3.3 append all the HTML elements to the HTML document\n document.getElementById('media-body').appendChild(title);\n document.getElementById('media-body').appendChild(description);\n document.getElementById('media-body').appendChild(content);\n}", "function handleArticleScrape() {\n // Call to the scrape API route, will add new articles to the database \n $.get(\"/api/fetch\").then(function(data){\n // After scraping new articles to the database, check if any are already in the collection, and then re-render articles on the page \n console.log(\"scraped articles\")\n initPage();\n bootbox.alert($(\"<h3 class ='text-center m-top-80'>\").text(data.message));\n });\n location.reload();\n }", "function articleScrape() {\n $.get(\"/api/fetch\")\n .then(function(data) {\n page();\n });\n }", "function scrapeArticles() {\n console.log(\"New Articles being scrapped..\");\n $.ajax({\n method: \"GET\",\n url: \"/scrape\"\n }).then(function (data) {\n displayArticles()\n })\n }", "function scrapeArticles(){\n $.get('/api/fetch').then(function(data){\n clearPage();\n });\n }", "function scrapeNew() {\n $.get('/articles/scrape')\n // TODO: implement a modal instead of using alert\n .done(function (data, status, response) {\n if (response.status === 200) {\n alert(data.length + ' articles were added');\n\n // load root page\n window.location.href = '/';\n } else { alert('unexpected response: ' + response.status); }\n })\n .fail(function (response) {\n alert('unable to process request at this time');\n console.log(response);\n });\n}", "function parsePage(html, siteRoot) {\n \n var $ = cheerio.load(html);\n\n //Parse html data\n $('div.story-content').each(function(i, element) {\n var dataElem = {\n title: $(element).find('h3.story-title').text(),\n byline: $(element).find('p').html(),\n url: siteRoot + $(element).find('h3.story-title').find('a').attr('href')\n }\n\n //Check to see if same article exists in database and add it if it doesn't exist\n Article.update({ \"title\": dataElem.title.trim()},{$setOnInsert: dataElem},{upsert: true}, function(err, results) {\n if (err) {\n console.log(err);\n }\n });\n });\n}", "function goToArticles(update) {\n var json = getAllArticlesBrief();\n\n document.getElementsByTagName('h2')[0].innerHTML = 'Bitte waehlen Sie Ihre Bestellung';\n\n var container = document.getElementsByTagName('article')[0];\n\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n\n for (var i = 0; i < json.articles.length; i++) {\n var img = document.createElement('IMG');\n img.setAttribute('src', json.articles[i].thumb_img_url);\n img.setAttribute('onclick', 'changeToScreen(2, false,' + json.articles[i].id + ')');\n\n var section = document.createElement('SECTION');\n section.setAttribute('id', json.articles[i].id);\n section.setAttribute('class', 'tooltip');\n\n var tooltip = document.createElement('SPAN');\n tooltip.setAttribute('class', 'tooltiptext');\n tooltip.innerHTML = json.articles[i].name;\n section.appendChild(tooltip);\n\n section.appendChild(img);\n container.appendChild(section);\n }\n\n if (update) {\n return;\n }\n\n setNewUrl('/articles', 'articles');\n}", "function loadPage() {\n \n scrapedContainer.empty();\n $.get(\"/api/headlines?saved=true\").then(function(data) {\n // render headlines\n if (data && data.length) {\n loadArticles(data);\n }\n else {\n // or let know there is nothing new\n renderEmpty();\n }\n });\n }", "function handleScrape() {\n // This function handles the user clicking any \"scrape new article\" buttons\n $.get(\"/api/article/scrape\").then(function (data) {\n location.reload();\n });\n }", "function buildWebPage(result){\n document.getElementById('article').innerHTML = result.description;\n document.getElementById('article-title').innerHTML = result.title;\n}", "function page() {\n $.get(\"/api/headlines?saved=false\").then(function(data) {\n containterToStoreArticle.empty();\n if (data && data.length) {\n renderArticles(data);\n }\n else {\n renderEmpty();\n }\n });\n }", "function scrapeArticles() {\n $.ajax({\n method: \"GET\",\n url: \"/scrape/\"\n })\n .then(getArticles);\n }", "function getArticles() {\n $.getJSON(\"/articles\", function (data) {\n for (var i = 0; i < data.length; i++) {\n $(\"#articles\").append(\"<p data-id='\" + data[i]._id + \"'><b>\" + data[i].title + \"</b><br />\" + data[i].summary + \"<br />\" + data[i].byline + \"<br /><a href=\" + data[i].link + \">View Article </a>\" + \"|\" + \"<a class=\" + \"save-article\" + \"> Save Article</a></p>\");\n }\n });\n }", "function scrape(callback) {\n request(\"http://www.time.com/\", function(error, response, html) {\n var articles = [];\n // Then, we load that into cheerio and save it to $ for a shorthand selector\n var $ = cheerio.load(html);\n\n \n // Now, we grab every article elemnt with 'border-separated-article' class:\n $(\"article.border-separated-article\").each(function(i, element) {\n \n //the article title is extracted from div h2 a element\n var link = $(element).find($(\"div h2 a\"));\n var title = link.text();\n if(title) {\n var href = link.attr('href');\n //the article content is extracted from div p element\n var content = $(element).find($(\"div p\")).text();\n\n articles.push({\n 'title':title,\n 'link':href,\n 'content':content,\n })\n }\n });\n\n callback(articles);\n })\n\n}", "function getNews(article) {\n // variable to hold the New York Times apiKey\n var newsApiKey = \"y9hgElnn7nwF3TNGuAv89poiSSqIlw4X\";\n\n fetch(\"https://api.nytimes.com/svc/search/v2/articlesearch.json?q=\" + article + \"&api-key=\" + newsApiKey)\n .then(function (response) {\n return response.json()\n })\n .then(function (response) {\n\n newsContainer.innerHTML = \"\";\n // variable that pulls in user searched article headline\n var articleHeadline = response.response.docs[0].headline.main;\n\n // variable that pulls in user searched article NYT url\n var articleUrl = response.response.docs[0].web_url;\n\n // varialble that pulls in user searchd article date\n var articleDate = response.response.docs[0].pub_date;\n var formatDate = moment(articleDate).format(\"ll\");\n\n // variable that pulls in user searched article snippet\n var articleSnippet = response.response.docs[0].snippet;\n\n // dynamically created news container\n var newsCard = document.createElement(\"div\");\n newsCard.classList = \"card grey lighten-1\";\n newsContainer.appendChild(newsCard);\n\n var newsContent = document.createElement(\"div\");\n newsContent.classList = \"card-content white-text\";\n newsCard.appendChild(newsContent);\n\n var newsTag = document.createElement(\"a\");\n newsTag.classList = \"card-title red-text\"\n newsTag.innerHTML = articleHeadline;\n newsContent.appendChild(newsTag);\n\n var newsDate = document.createElement(\"p\");\n newsDate.classList = \"black-text\";\n newsDate.innerHTML = formatDate;\n newsContent.appendChild(newsDate);\n\n var newsSnippet = document.createElement(\"p\");\n newsSnippet.classList = \"black-text\";\n newsSnippet.innerHTML = articleSnippet;\n newsContent.appendChild(newsSnippet);\n\n var newsLink = document.createElement(\"a\");\n newsLink.setAttribute(\"href\", articleUrl);\n newsLink.setAttribute(\"target\", \"_blank\");\n newsLink.innerHTML = \"Click here to read full article\";\n newsLink.classList = \"red-text text-spacing\"\n newsContent.appendChild(newsLink);\n })\n}", "function renderArticles(data){\n\n\t//creates a new div for each article scraped\n\tfor(let i = 0; i < data.length; i++){\n\t\tvar articleDiv = $(\"<div>\");\n\t\tarticleDiv.addClass(\"well\");\n\t\tarticleDiv.addClass(\"articleDiv\");\n\t\tarticleDiv.append(\"<a href=\" + data[i].link + \" target='_blank' id=title>\" + data[i].title + \"</a>\");\n\t\tif(data[i].description != \"\"){\n\t\t\tarticleDiv.append(\"<p id=description>\" + data[i].description + \"</p>\");\n\t\t};\n\t\tarticleDiv.append(\"<button id=save>Save Article</button>\");\n\n\t\t$(\".article-container\").append(articleDiv);\n\t};\n}", "function displayAllArticles(){\n $.get('/unArt', function(articles){\n for (let ind of articles){\n $('.article-container')\n .append('<article >'\n + '<h1 class=\"article-title\">'\n + ind.title\n + '<button id=\"save\"' + 'data-id=\"' + ind._id + '\">Save</button>'\n + '</h1>'\n + '<p class=\"article-summary\">'\n + ind.description\n + '<br>'\n + '<a href=\"https://www.nps.gov' + ind.link + '\">' + 'https://www.nps.gov' + ind.link + '</a>'\n + '</p>' \n + '</article>');\n }\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destructively modify MDAST to rename all footnote ids to be unique and based on the contents of the footnote. Id is short and friendly id including a hash of the contents, e.g. the text " ends up with footnote id "^investoped.dreyz4".
function normalizeFootnoteIds(mdast) { const footnoteIdMapping = {}; const newFootnoteIds = new Set(); const missingFootnoteIds = new Set(); const orphanedFootnoteIds = new Set(); const footnoteTextSet = new Set(); let footnoteRefCount = 0; // Calculate new footnote ids based on present definitions and and assemble old->new id mapping. visit(mdast, 'footnoteDefinition', node => { assert(node.identifier, 'All footnote definitions should have an id'); const definitionText = nodeText(node); footnoteTextSet.add(definitionText); const newId = generateFootnoteId(definitionText); footnoteIdMapping[node.identifier] = newId; newFootnoteIds.add(newId); console.log( `Mapping footnote id: ${node.type} ^${node.identifier} -> ^${ footnoteIdMapping[node.identifier] }` ); }); assert( newFootnoteIds.size === footnoteTextSet.size, 'Footnote hash id collision, which should be very unlikely' ); // Apply the old->new mapping on ids, also dropping duplicate definitions. const referencesSeen = new Set(); const definitionsSeen = new Set(); visit( mdast, ['footnoteReference', 'footnoteDefinition'], (node, index, parent) => { let newId = footnoteIdMapping[node.identifier]; if (node.type === 'footnoteReference') { if (!newId) { missingFootnoteIds.add(node.identifier); newId = node.identifier + '.missing'; } node.identifier = newId; node.label = newId; footnoteRefCount++; referencesSeen.add(newId); } else { assert(node.type === 'footnoteDefinition'); assert(newId); if (!referencesSeen.has(newId)) { orphanedFootnoteIds.add(newId); newId += '.orphan'; } if (definitionsSeen.has(newId)) { console.log( `Removing duplicate footnote definition for ^${node.identifier}` ); parent.children.splice(index, 1); return index; } // For clarity, we un-wrap footnote definitions so they are on a single line. // Not essential to do this, but seems a little clearer here to really "normalize" and we can wrap them later. normalizeTextNodes(node); definitionsSeen.add(newId); node.identifier = newId; node.label = node.identifier; } return null; } ); atom.notifications.addInfo( `Found ${footnoteRefCount} footnotes and ${ newFootnoteIds.size } unique footnote definitions (${Object.keys(footnoteIdMapping).length - newFootnoteIds.size} duplicates dropped)` ); if (missingFootnoteIds.size) { // These are a problem! atom.notifications.addWarning( `Found ${ missingFootnoteIds.size } footnotes missing definitions (search for .missing): ${[ ...missingFootnoteIds ] .sort() .join(', ')}` ); } if (orphanedFootnoteIds.size) { // Orphaned definitions are technically harmless but probably are the result of some error or mistake so should be highlighted. atom.notifications.addWarning( `Leaving ${ orphanedFootnoteIds.size } orphaned definitions in place (search for .orphan): ${[ ...orphanedFootnoteIds ] .sort() .join(', ')}` ); } }
[ "function normalizeTitlesId() {\n var titles = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];\n var ids = [];\n var counter;\n\n titles.forEach(function(title) {\n $(title).each(function() {\n // Compute new id\n var oldId = $(this).attr('id');\n var textId = normalizeId($(this).text());\n\n var newId = textId;\n counter = 0;\n while (_.includes(ids, newId)) {\n newId = textId+'-'+counter;\n counter++;\n }\n // Prevent obtaining the same id twice\n ids.push(newId);\n\n // Replace id in href links\n $('*[href=\"#'+oldId+'\"]').each(function() {\n $(this).attr('href', '#'+newId);\n });\n // Replace title id\n $(this).attr('id', newId);\n });\n });\n}", "fixId() {\n\n const meta = this.wiki.getTiddlerData(env.ref.sysMeta, {});\n\n this.executeUpgrade('0.9.2', meta.dataStructureState, () => {\n\n if (utils.isLeftVersionGreater('0.9.2', meta.originalVersion)) {\n // path of the user conf at least in 0.9.2\n const userConf = '$:/plugins/felixhayashi/tiddlymap/config/sys/user';\n const nodeIdField = utils.getEntry(userConf, 'field.nodeId', 'tmap.id');\n utils.moveFieldValues(nodeIdField, 'tmap.id', true, false);\n }\n });\n\n }", "function transformer(ast) {\n slugs.reset()\n\n visit(ast, 'heading', visitor)\n\n function visitor(node) {\n var data = node.data || (node.data = {})\n var props = data.hProperties || (data.hProperties = {})\n var id = props.id\n \n if (id) {\n id = slugs.slug(replaceUmlaute(id), true)\n } else {\n id = slugs.slug(replaceUmlaute(toString(node)))\n }\n\n data.id = id\n props.id = id\n }\n}", "function addIDsToTOC (toc) {\n\t\tfor (var i = 0; i < toc.length; i++) {\n\t\t\tvar t = toc[i];\n\t\t\tif (t.id == undefined) {\n\t\t\t\tt.id = i;\n\t\t\t}\n\t\t}\n\t}", "function populateTitleToIdMap(paperIDFile, idToTitleFile, delimeter) {\n var paperIDSubset = fs.readFileSync(paperIDFile, 'utf8').split('\\n');\n var paperIDAndTitle = fs.readFileSync(idToTitleFile, 'utf8').split('\\n');\n for (var i = 0; i < paperIDAndTitle.length; i++) {\n var tokens = paperIDAndTitle[i].split(delimeter);\n var id = tokens[0];\n var title = tokens[1];\n if (title !== undefined && id !== undefined && paperIDSubset.indexOf(id) > -1) {\n titleToID[title.toLowerCase()] = id;\n }\n }\n}", "function resolvePandocId(id) {\n id = deHyphenateWords(id);\n return capitalize(id);\n }", "function originalId(id) {\n if (id.slice(0, 3) == 'mm-') {\n return id.slice(3);\n }\n return id;\n}", "function fixId(id) {\n if (id.length === 23 && id.startsWith(\"c\")) {\n return id.slice(1)\n }\n}", "function transformer(ast) {\n slugs.reset()\n\n visit(ast, 'heading', visitor)\n\n function visitor(node) {\n var data = node.data || (node.data = {})\n var props = data.hProperties || (data.hProperties = {})\n var id = props.id\n\n id = id ? slugs.slug(id, true) : slugs.slug(toString(node))\n\n data.id = id\n props.id = id\n }\n}", "function PrettifyID(id)\r\n{\r\n //Removing _MT\r\n id = id.slice(0, -3);\r\n\r\n //Splitting by uppercase\r\n var split = id.split(/(?=[A-Z]+|[1-9])/);\r\n\r\n //Composing the new formatted string\r\n var formatted = \"\";\r\n for (var i = 0; i < split.length; i++)\r\n {\r\n formatted += (split[i] + \" \");\r\n }\r\n id = formatted;\r\n\r\n return id[0].toUpperCase() + id.substr(1);\r\n}", "function fixMyID(id) {\r\n return id.replace(/\\W/g,'_');\r\n}", "function getID(noteId) {\r\n let leng = noteId.id.length\r\n return noteId.id.substr(2, leng - 2)\r\n}", "function uniquifyHeadingIds(headings) {\n const uniqueIDs = populateIds();\n for (let heading of headings) {\n const uniqueID = uniquifyHeadingId(heading.id, uniqueIDs);\n uniqueIDs.push(uniqueID);\n heading.id = uniqueID;\n }\n}", "function TransformShortUniqueIDToRealUniqueID(uniqueid) {\n var parts = uniqueid.split(\"#\").reverse();\n var partsReal = [];\n var currentContext = parts[0];\n partsReal.push(parts[0]);\n for (var i = 0; i < parts.length - 1; i++) {\n var currentParent = window[\"$cache\"][currentContext];\n partsReal.push(getNameFromAlias(currentParent[\"@k\"], parts[i + 1]));\n currentContext = parts[i + 1] + \"#\" + currentContext;\n }\n return partsReal.reverse().join(\"#\");\n }", "function normalizeId(txt) /* (txt : string) -> string */ {\n return $std_core.toLower($std_regex.replaceAll_1($std_regex.replaceAll_1(txt, $std_regex.regex(\"[^\\\\w\\\\-_:\\\\*\\\\s]+\", undefined, undefined), \"\", undefined), $std_regex.regex(\"\\\\s+|[:\\\\*]\", undefined, undefined), \"-\", undefined));\n}", "function replaceIds(input, dMap, idTag){\n (!dMap || !(input)) && (function(){\n console.log('links were broken');\n return '';\n }());\n\n var output = input;\n for( var key in dMap){\n //console.log('key is' + key);\n var re = new RegExp('docName=' + key, 'g');\n if (dMap.hasOwnProperty(key)){\n output = output.replace(re, idTag + dMap[key]);\n //console.log(output);\n }\n }\n //console.log('final output');\n //console.log(output);\n return output;\n }", "nodeNormalizeIDs(node) {\n if (\n node.tagName &&\n node.getAttribute(\"id\") == null &&\n [\"H1\", \"H2\", \"H3\", \"H4\", \"H5\", \"H6\"].includes(node.tagName)\n ) {\n if (node.getAttribute(\"resource\")) {\n node.setAttribute(\"id\", node.getAttribute(\"resource\"));\n } else {\n let id =\n node.tagName.toLowerCase() + \"-\" + this.hashCode(node.innerText);\n node.setAttribute(\"id\", id);\n }\n }\n }", "function htmlID(id) {\n return \"item\" + id.replace(/[^A-Za-z 0-9]+/g,'');\n }", "function replace_tranid_in_xtb(file, id_map) {\n const contents = FS.readFileSync(file, 'utf8')\n let output = ''\n let found = false\n const len = contents.length\n const starttag = '<translation '\n const endtag = '</translation>'\n const regexp = new RegExp(`\\s*id=\"(?<id>[^\"]*)\"`)\n const all_ids = []\n let i = 0\n while (i < len) {\n // get until <translation\n while (i < len && !contents.startsWith(starttag, i)) {\n output += contents[i]\n i++\n }\n if (i == len)\n break\n\n // get line until >\n let line = ''\n while (i < len && contents[i] != '>') {\n line += contents[i]\n i++\n }\n if (i != len) {\n // skip >\n line += contents[i]\n i++\n }\n\n // filter line with id\n const obj = regexp.exec(line)\n if (obj && obj.groups && obj.groups.id) {\n const id = obj.groups.id\n const new_id = id_map.has(id) ? id_map.get(id) : id\n if (all_ids.includes(new_id)) {\n // skip to </translation>, ignore this dup id\n // warn(`ignore dup id ${new_id}`)\n while (i < len && !contents.startsWith(endtag, i)) {\n i++\n }\n if (i != len) {\n i += endtag.length\n }\n continue\n }\n\n if (id_map.has(id)) {\n found = true\n line = line.replace(id, new_id)\n }\n all_ids.push(new_id)\n }\n output += line\n }\n if (found) {\n FS.writeFileSync(file, output)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process each lines in dictionary and compare with words_to_find contents
async function processLineByLine(){ const rl = createInterface({ input: dictionaryFile, crlfDelay: Infinity }); for await(const line of rl){ let currentWord = line.split(','); let regx = new RegExp('\\b' + currentWord[0] + '\\b', 'g'); let foundCount = wordsToFind.split(',')[0].match(regx).length; // matching only engligh words to find multiple occurrence wordsToFind = wordsToFind.replace(regx, currentWord[1], 'g'); frequencyFile.write(`${currentWord[0]},${currentWord[1]},${foundCount}\n`); } return wordsToFind; }
[ "find(terms) {\n let names, score, lines;\n let resultsArray = [];\n\n if (terms.length > 1) {\n let bothTermsExist = true;\n // Check if the words exist in the same sentence.\n for (let term of terms) {\n term = normalize(term);\n if (!this.contentMap.has(term)) {\n bothTermsExist = false;\n break;\n }\n }\n let multiWordMap = new Map();\n // Create multi word map\n for (let term of terms) {\n term = normalize(term);\n if (this.contentMap.has(term) && term !== \"\") {\n let docKeys = this.contentMap.get(term).keys();\n for (let key of docKeys) {\n if (multiWordMap.has(key)) {\n let existingKey = [];\n existingKey = multiWordMap.keys();\n multiWordMap.get(key).push({\n tm: term,\n occurrences: this.contentMap.get(term).get(key).numberOfOccurrence,\n line: this.contentMap.get(term).get(key).ln,\n lineNo: this.contentMap.get(term).get(key).lineNumber\n });\n } else {\n multiWordMap.set(key, [{\n tm: term,\n occurrences: this.contentMap.get(term).get(key).numberOfOccurrence,\n line: this.contentMap.get(term).get(key).ln,\n lineNo: this.contentMap.get(term).get(key).lineNumber\n }]);\n }\n }\n }\n }\n // Fill in the results array.\n for (let termKey of multiWordMap.keys()) {\n let score = 0;\n let line = [];\n multiWordMap.get(termKey).sort(function (a,b){return (a.lineNo - b.lineNo);});\n for (let entry of multiWordMap.get(termKey)) {\n score = score + parseInt(entry.occurrences);\n //Checking lines\n if (!line.includes(entry.line)) {\n line = line + entry.line + \"\\n\";\n }\n }\n\n resultsArray.push(new Result(termKey, score, line));\n }\n } else if (terms.length === 1) {\n let term = terms[0];\n if (this.contentMap.has(term.toLowerCase()) && term !== \"\") {\n let documents = new Map(this.contentMap.get(term.toLowerCase()));\n names = documents.keys();\n for (let name of names) {\n score = documents.get(name).numberOfOccurrence;\n lines = (typeof documents.get(name).ln === 'undefined') ? \"\" : documents.get(name).ln + \"\\n\";\n resultsArray.push(new Result(name, score, lines));\n }\n }\n }\n resultsArray.sort(compareResults);\n return resultsArray;\n }", "function contains(key, value)\n {\n var output = [];\n //console.log(output);\n for (var i = 0; i < lines.length; i++) // iterate through lines (56 in total) arrays\n {\n if (lines[i].words[key] === value) // every word with (key = int) that equals the string i pass to function, return\n {\n output.push(i); // add all strings that match to array \"output\"\n // console.log(i + \" true\");\n }\n else\n {\n // console.log(i + \" false\");\n }\n }\n return output;\n }", "find(terms) {\n //@TODO\n\tlet mapResult = new Map();\n \tconst _this=this;\t\n\tlet resultArray=[]; \n\tterms.forEach(function(x){\n\t\tlet docs = new Map();\n\t\tdocs=_this.AllWords.get(x[0]);\n\t\n\t\tif(docs!==undefined)\t\t\n\t\tfor(let [docName,info] of docs.entries()){\n\n\t\t\tlet score = info[1];\t//count\n\t\t\tlet offset = info[0];\n\t\t\tlet tempoffset;\n\t\t\tlet match;\n\t\t\tconst MYWORD_REGEX = /\\n/g;\n\t\t\tlet line;\n\t\t\tlet lineSet = new Set();\n\t\t\tlet lineMap = new Map();\n\n\t\t\tlet content = _this.filesContent.get(docName);\n\t\t\twhile ((match = MYWORD_REGEX.exec(content)) !== null)\n\t\t\t{ \n \t let offset1=MYWORD_REGEX.lastIndex;\n \t if(offset1>offset){\n \t line = content.slice(tempoffset,offset1-1);\n\t\t\t\t break;\n\t\t\t\t}\n \t else\n \t\t tempoffset = offset1; \n\t\t\t}\n\t\t\t\n\t\t\tif(!mapResult.has(docName))\n\t\t\t{\n//\t\t\t\tlineSet.add(line);\n\t\t\t\tlineMap.set(tempoffset,line);\n\t\t\t\tmapResult.set(docName,[score,lineMap]);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlet x = mapResult.get(docName);\n\t\t\t\tlet rcount = x[0];\n//\t\t\t\tlet rlineset = x[1];\n\t\t\t\tlet rlineMap= x[1];\n//\t\t\t\tlineSet = rlineset.add(line);\n\t\t\t\tlineMap = rlineMap.set(tempoffset,line);\n\t\t\t\tmapResult.set(docName,[rcount+score,lineMap]);\n\t\t\t}\n\t\t}\n\t});\n\n\t\n\tfor(let [rKey,rVal] of mapResult.entries()){\n\t\tlet offsetArray = Array.from(rVal[1].keys()).sort((a,b)=> a==b? 0 : a>b?1:-1);\n\t\tlet str='';\n//\t\tfor(let i of rVal[1]) str=str+i+'\\n';\n\t\t\n\t\toffsetArray.forEach((x)=>{\n\t\t\tstr = str + rVal[1].get(x)+'\\n';\n\t\t});\t\n\n\t\tresultArray.push(new Result(rKey,rVal[0],str));\n\t}\n\tresultArray.sort(compareResults);\n\n\treturn resultArray;\n }", "find(terms) {\n //@TODO\n\tlet return_list = [];\n\tlet return_set = new Set();\n\t\n\t// Loop through search terms\n\tfor (let i = 0; i < terms.length; i++)\n\t{\n\t\t// Loop through individual documents\n\t\tfor (let key in this.content_dict)\n\t\t{\n\t\t\tlet temp_dict = this.index_dict[key];\n\t\t\tlet lis = temp_dict[terms[i]];\n\n\t\t\tif (lis != undefined && terms[i] != \"\")\n\t\t\t{\n\t\t\t\t// Snippet to extract the occurences of new line before and after the specified index \n\t\t\t\tlet index = lis[1];\n\t\t\t\tlet f_half = this.content_dict[key].substring(0, index).lastIndexOf(\"\\n\") + 1;\n\t\t\t\tlet s_half = (this.content_dict[key].substr(f_half).search(\"\\n\")) + f_half;\n\t\t\t\tlet first_occurence = this.content_dict[key].substring(f_half, s_half) + \"\\n\";\n\t\t\t\t\n\t\t\t\t// Entry found in a new document - New Result record\n\t\t\t\tif (!return_set.has(key))\n\t\t\t\t{\n\t\t\t\t\tlet res = new Result(key, lis[0], first_occurence);\n\t\t\t\t\treturn_set.add(key);\n\t\t\t\t\treturn_list.push(res);\n\t\t\t\t}\n\t\t\t\t// New entry found in a previously stored document - Edit existing Result record\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tfor (let x in return_list)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Search for matching document\n\t\t\t\t\t\tif (return_list[x].name === key)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Sum the scores and look for a former occurence among the two words\n\t\t\t\t\t\t\treturn_list[x].score = return_list[x].score + lis[0];\n\t\t\t\t\t\t\tif ((this.content_dict[key]).search(return_list[x].lines) > lis[1])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn_list[x].lines = first_occurence;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t\tSorting the result list in descending order based on the scores\n\t\tIf Scores tie up; Sorting them based on the alphabetical order of the document name\n\t*/\n\treturn_list.sort(function(a, b){\n\t\tif (b.score != a.score)\n\t\t{\n\t\t\treturn (b.score - a.score);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn (b.name < a.name);\n\t\t}\n\t})\n\n return return_list;\n }", "findAllWords(dict, pattern)\n {\n // code here\n if (dict.length < 1) {\n console.log(\"No match found\")\n return\n }\n const result = []\n const uppers =[]\n // insert only uppercases of each of the string\n for (let i = 0; i < dict.length; i++) {\n // go through each char in current string\n let temp = \"\"\n for (let j = 0; j < dict[i].length; j++) {\n let asciiNum = dict[i].charCodeAt(j)\n if (asciiNum < 65 || asciiNum > 90) continue;\n temp += dict[i][j]\n }\n uppers.push(temp)\n }\n for (let i = 0; i < uppers.length; i++) {\n if (uppers[i].includes(pattern)) {\n result.push(dict[i])\n }\n }\n if (result.length < 1) {\n console.log(\"No match found\")\n return\n }\n result.sort()\n console.log(result.join(\" \"))\n return\n }", "find(terms) {\n let results = [];\n for (let term of terms) {\n let res = this.keyWordsMap.get(term.toLowerCase());\n for (let i = 0; i < res.titles.length; i++) {\n results.push(new Result(res.titles[i], res.occurrences[i], this.findLine(res.titles[i], res.offset[i])));\n }\n }\n for(let i=0; i<results.length-1; i++){\n for(let j=i+1; j<results.length; j++) {\n if (results[i].lines == results[j].lines && results[i].name == results[j].name) {\n results[i].score += results[j].score;\n results.splice(j, 1);\n j--;\n }\n }\n }\n return results.sort(compareResults);\n }", "function wordStats(lines) {\n\t\tlet words = {};\n\n\t\tif (!lines) {\n\t\t\tlines = savedLines;\n\t\t}\n\n\t\tfor (let item of lines) {\n\t\t\tlet line;\n\n\t\t\t// Use .displayText or .text\n\t\t\tif (item.displayText) {\n\t\t\t\tline = item.displayText.toLowerCase();\n\t\t\t }\n\t\t\t else {\n\t\t\t \tline = item.text.toLowerCase();\n\t\t\t }\n\n\t\t\t//console.log(line);\n\n\t\t\t// remove all <tags>\n\t\t\tline = line.replace(/<[^<>]+>/g, \"\");\n\n\t\t\t// remove all [ bracets content ]\n\t\t\tline = line.replace(/\\[[^\\]]+\\]/g, \"\");\n\n\t\t\t// remove punctuation and common special characters\n\t\t\t// TODO use set of special char that we already have for filters, do not duplicate them here\n\t\t\tline = line.replace(/[-–♪(),\"“”„:;.?!¡¿…()!?:,、\\u061f\\u060c]/g, \"\");\n\n\t\t\t// after all that replacing there could be some surrounding spaces, trim them\n\t\t\tline = line.trim();\n\n\t\t\tif (line == \"\") { continue; } // is there anything left?\n\n\t\t\t//console.log(line);\n\n\t\t\t// cycle all words in a given cue\n\t\t\tlet fragments = line.split(/\\s+/);\n\n\t\t\tfor (let fragment of fragments) {\n\n\t\t\t\tif (fragment == \"\") { continue; }\n\n\t\t\t\t// if fragment is a word in apostrophes, remove apostrophes; 'word' => word\n\t\t\t\tif (fragment.match(/^'.*'$/)) {\n\t\t\t\t\tfragment = fragment.replace(/^'/, \"\").replace(/'$/, \"\");\n\t\t\t\t}\n\n\t\t\t\tif (!(fragment in words)) {\n\t\t\t\t\twords[fragment] = 0;\n\t\t\t\t}\n\n\t\t\t\twords[fragment]++;\n\t\t\t}\n\t\t}\n\n\t\t// To sort we need to create list first, then sort it\n\t\tlet wordsArray = [];\n\n\t\tfor (let item in words) {\n\t\t\twordsArray.push([item, words[item]]);\n\t\t}\n\n\t\twordsArray.sort(function(a,b) { return b[1] - a[1]; });\n\n\t\treturn wordsArray;\n\t}", "function processLine(str){\n let temp = {};\n keywords.forEach((key)=>{\n if(str.includes(key)){\n temp[key] = str.indexOf(key);\n } else {\n return;\n }\n });\n if(temp && Object.keys(temp).length)\n extract(str, temp);\n else\n return;\n}", "function dictonary(args) {\n\n let initialDict = args.shift().split(\" | \")\n let wordsToCheck = args.shift().split(\" | \")\n let command = String(args)\n\n let dictionaryMap = new Map();\n\n for (const line of initialDict) {\n wordsToDict = line.split(\": \")[1]\n let theKey = line.split(\": \")[0]\n\n if (dictionaryMap.has(theKey)) {\n let moreMeanings = [wordsToDict];\n let theResult = dictionaryMap.get(theKey)\n moreMeanings.push(wordsToDict)\n moreMeanings = moreMeanings.concat(theResult)\n moreMeanings.sort((a, b) => b.length - a.length);\n dictionaryMap.set(theKey, moreMeanings)\n\n } else {\n let definition = wordsToDict[1]\n dictionaryMap.set(theKey, definition)\n }\n }\n\n let dictMapEntries = [...dictionaryMap.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n\n\n if (command === \"List\") {\n let stringifying = \"\"\n for (const word of dictMapEntries) {\n stringifying += `${word[0]} `\n }\n console.log(stringifying)\n } else if (command === \"End\") {\n for (let word of dictMapEntries) {\n let wordToCompare = String(wordsToCheck.shift())\n\n if (word[0] === wordToCompare) {\n console.log(wordToCompare)\n word.shift()\n if (typeof word[0] === \"object\") {\n word[0].forEach(element => console.log(` -${element}`))\n } else {\n console.log(` -${word}`)\n }\n }\n\n if (wordsToCheck.length === 0) {\n break\n }\n }\n }\n\n\n}", "function compareValues() {\n // start with offset 0. assume first words will match. update offset if mismatch found.\n let keyIndex = 0;\n let userIndex = 0;\n\n const test = document.getElementById(\"test\");\n const keySentenceElmnt = document.getElementById(\"keySentence\");\n const userElmnt = document.getElementById(\"comparedSentence\");\n\n let userSentence = document.getElementById(\"userText\").value;\n let keySentence = getNextSentence();\n if (keySentence == \"(end of document)\") {\n document.getElementById(\"test\").textContent = \"end of document\";\n return;\n }\n keySentenceElmnt.textContent = keySentence;\n userSentence = userSentence.replace(/\\.com/g, \"\\~com\");\n let userWordsPunc = userSentence.split(' ');\n let keyWordsPunc = keySentence.split(' ');\n const punctuation = [\".\", \"?\", \"!\", \",\", \";\", \":\"];\n\n let keyUnpunc = keySentence.replace(/[.,!?;:()]/g,\"\");\n let keyWords = keyUnpunc.split(' ');\n let userUnpunc = userSentence.replace(/[.,!;:()]/g,\"\");\n let userWords = userUnpunc.split(' ');\n\n /*\n compare at current indices\n if match found, compare next pair\n if no match found\n look ahead for match: indexOf.\n check for current word of key in user sentence\n check for current word of user sentence in key\n if found, adjust offset\n if not found, skip this index\n */\n\n while (keyIndex < keyWords.length && userIndex < userWords.length) {\n let keyCurrent = keyWords[keyIndex], userCurrent = userWords[userIndex];\n\n // compare at current indices. if match found, compare next pair.\n if (keyCurrent === userCurrent) {\n // match found. no lookahead\n } else {\n // if no match found, look ahead for match in user sentence\n let matchInUser = userWords.indexOf(keyCurrent, userIndex);\n\n // if no match found, look ahead for match in key sentence\n let matchInKey = keyWords.indexOf(userCurrent, keyIndex);\n\n if ((matchInKey == -1) && (matchInUser == -1)) {\n // aligned mismatch\n } else if (matchInKey == -1) {\n // unaligned mismatch. user added words.\n while (userIndex < matchInUser) {\n test.textContent += \" \" + \"\\{\" + \"\\-\" + \"\\}\" + '<span class=\"added\">' + userWordsPunc[userIndex] + '</span>';\n userIndex++;\n userCurrent = userWords[userIndex];\n }\n } else if (matchInUser == -1) {\n // unaligned mismatch. user missed words.\n while (keyIndex < matchInKey) {\n test.textContent += \" \" + \"\\{\" + \"\\+\" + \"\\}\" + '<span class=\"missed\">' + keyWordsPunc[keyIndex] + '</span>';\n keyIndex++;\n keyCurrent = keyWords[keyIndex];\n }\n } else {\n // match found ahead\n if (userWords[userIndex] == keyWords[keyIndex+1]) {\n test.textContent += \" \" + \"\\{\" + \"\\+\" + \"\\}\" + '<span class=\"missed\">' + keyWordsPunc[keyIndex] + '</span>';\n keyIndex++;\n keyCurrent = keyWords[keyIndex];\n } else if (keyWords[keyIndex] == userWords[userIndex+1]) {\n test.textContent += \" \" + \"\\{\" + \"\\-\" + \"\\}\" + '<span class=\"added\">' + userWordsPunc[userIndex] + '</span>';\n userIndex++;\n userCurrent = userWords[userIndex];\n } else {\n }\n }\n }\n\n // get index of keyCurrent and userCurrent. use index to print puncutated forms\n let keyCurrentPunc = keyWordsPunc[keyWords.indexOf(keyCurrent, keyIndex)];\n let userCurrentPunc = userWordsPunc[userWords.indexOf(userCurrent, userIndex)];\n\n keyCurrentPunc = keyCurrentPunc.replace(/\\~com/g, \"\\.com\");\n userCurrentPunc = userCurrentPunc.replace(/\\~com/g, \"\\.com\");\n\n test.textContent += \" \" + (keyCurrentPunc == userCurrentPunc ? keyCurrentPunc : keyCurrentPunc + \"|\" + userCurrentPunc);\n keyIndex++;\n userIndex++;\n }\n\n // print any remaining words\n while (keyIndex < keyWords.length) {\n test.textContent += \" \" + \"\\{\" + \"\\+\" + \"\\}\" + '<span class=\"missed\">' + keyWordsPunc[keyIndex] + '</span>';\n keyIndex++;\n }\n while (userIndex < userWords.length) {\n test.textContent += \" \" + \"\\{\" + \"\\-\" + \"\\}\" + '<span class=\"added\">' + userWordsPunc[userIndex] + '</span>';\n userIndex++;\n }\n}", "function findMatchedWords(dict, pattern) {\n var output = [];\n // len is length of the pattern\n var len = pattern.length;\n \n // encode the string\n var hash = encodeString(pattern);\n \n // for each word in the dictionary array\n for (word of dict) {\n // If size of pattern is same\n // as size of current\n // dictionary word and both\n // pattern and the word\n // has same hash, print the word\n if (word.length == len && encodeString(word) == hash){\n output.push(word);\n } \n }\n return output;\n }", "find(terms) {\n //@TODO\n var resultSet = [];\n for(const doc of this.docArray) {\n let count = 0;\n let line = '';\n for(var term of terms) {\n if(doc.docWords.includes(term)) {\n //console.log(doc.docName);\n doc.docWords.forEach(function(element) {\n if(element === term){\n\t count++;\n }\n }); // forEach\n\n //for the lines content\n if(line === ''){\n let temp = doc.docPairs.findIndex(function (element){\n return element[0] === term;\n });\n\n let tempIndexPair = doc.docPairs[temp];\n\n //adding the previous content into the line\n for(let i=tempIndexPair[1]; (doc.docContent[i] != '\\n') && (i!=-1) && (i!=doc.docContent.length); i--){\n line = doc.docContent[i] + line;\n }\n\n //adding the after content into the line\n for(let i=tempIndexPair[1]+1; (doc.docContent[i] != '\\n') && (i!=-1) && (i!=doc.docContent.length); i++){\n line = line + doc.docContent[i];\n }\n\n }// if lines\n\n let findObj = false;\n\n resultSet.forEach(function(element) {\n if(element.name === doc.docName) {\n findObj = true;\n element.score = count;\n }\n });\n\n if(!findObj){\n resultSet.push({ name: doc.docName,\n score: count,\n lines: line + '\\n'});\n }\n }\n }\n }\n //with the reference of \"https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript\" for sorting the objects in arrays\n\n resultSet.sort(function(obj1, obj2) {\n if(obj1.score > obj2.score){\n return -1;\n }\n else if(obj1.score < obj2.score){\n return 1;\n }\n else if(obj1.score === obj2.score){\n if(obj1.name < obj2.name){\n return -1;\n }\n else{\n return 1;\n }\n }\n });\n return resultSet;\n }", "function getAllMatches(textObj, keyWords){\n var matchCounter = [] ;\n// var textObj = sortParagraphs();\n// var keyWord = /Drum/gi;\n// var keyWords = getKeyWords();//return array []\n\n // Iterate All Keywords\n keyWords.forEach(function(item, ind){\n var keyWord = new RegExp(item, 'gi');\n //Logger.log(keyWord);\n\n //Iterate keys from textObj\n for(var keyName in textObj){\n var counter = 0; // count matches for each paragraph type\n //check if the index exists in the outer array\n if (!(ind in matchCounter)) {\n //if it doesn't exist, we need another array to fill\n matchCounter.push([]);\n }\n //Logger.log(keyName);\n\n // Iterate All paragraphs in obj\n textObj[keyName].forEach(function(paragraph, index){\n // Find all matches of keywords in paragraph\n var match = paragraph.match(keyWord);\n// Logger.log(keyWord);\n// Logger.log(match);\n// Logger.log(paragraph);\n if(match != null){\n counter = counter + match.length ;\n }\n })\n matchCounter[ind].push(counter);\n }\n })\n return matchCounter;\n// Logger.log(matchCounter);\n}", "function import_keywords_matching(file) {\n\n jQuery.ajax({ \n url: file,\n async: false,\n cache: false,\n dataType: 'text',\n success: function(data) {\n file_contents = data.split(\"\\n\");\n\n keywords_to_match = []\n new_key = 'BEGIN';\n \n for (line of file_contents) {\n // Lines starting with '-' are comments, so we ignore them\n if (line.indexOf('-') !== 0) {\n // If there's a #, it's a new entry\n if (line.indexOf('#') === 0) {\n\n // EXCEPT IF it was the beginning of the file\n if (new_key !== 'BEGIN') {\n global.keywords_matching[new_key] = keywords_to_match;\n }\n\n // We reset the array of words and save the name\n // of the global matching (unclear?)\n keywords_to_match = []\n new_key = line.substr(1);\n \n } \n\n // Else, it's a word to add to the entry\n else {\n keywords_to_match.push(line.trim());\n }\n }\n\n else {\n if (DEBUG)\n console.log(\"Comment from keywords_matching.txt: \" + line.substring(1).trim());\n }\n\n }\n\n // Don't forget to add the last entry\n // (the last word is an empty one, so, meh, it'll work)\n global.keywords_matching[new_key] = keywords_to_match.slice(0, keywords_to_match.length - 1);\n },\n });\n}", "async function findBreaks() {\n console.log(\"Process text\");\n var result = await browser.runtime.sendMessage({request: 'findBreaks',\n text: text, forcedBreaks: forcedBreaks});\n console.log(\" Done\");\n words = result.words;\n indices = result.indices;\n breaks = result.breaks;\n uWords = result.uWords;\n oWords = result.oWords;\n\n // Clear previous tags\n clearMarking(content);\n updateTooltip();\n\n console.log(\"Matching words against user dictionary...\");\n uNodes = [];\n oNodes = [];\n var start = performance.now();\n\n var oBreaks = [], uBreaks = [], oLengths = [], uLengths = [], i = null;\n for (i of uWords) {\n uBreaks.push(breaks[i]); uLengths.push(words[i].length);\n }\n for (i of oWords) {\n oBreaks.push(breaks[i]); oLengths.push(words[i].length);\n }\n oNodes.push(...hlTexts(content.childNodes[0], oBreaks, oLengths));\n uNodes.push(...markTexts(content.childNodes[0], uBreaks, uLengths));\n\n console.log(\"\\tDone in \" + (performance.now() - start) + \"ms\");\n}", "async find(aUserInputWords) {\n //all terms regex.\n let sAllTermsRegex = \"\";\n aUserInputWords.forEach(function (sUserInputWord, iIndex) {\n sAllTermsRegex += (iIndex === 0 ? \"\" : \"|\") + \"(\\\\b\" + sUserInputWord + \"\\\\b)\";\n });\n let oAllTermsRegex = new RegExp(sAllTermsRegex, \"g\");\n\n //search logic\n let aSearchResult = [];\n let aAllDocs = await this.getDataFromDbByColNameAndFindQuery('textDocuments', {});\n\n aAllDocs.forEach(oElement => {\n let sDocName = oElement.name;\n let oDocData = oElement.data;\n let aOriginalDocData = oDocData.originalData;\n let aProcessedDocData = oDocData.processedData;\n\n let iCount = 0;\n let sLine = \"\";\n aProcessedDocData.forEach(function (sLineData, iIndex) {\n let aTempWhile = null;\n while ((aTempWhile = oAllTermsRegex.exec(sLineData)) !== null) {\n if (iCount === 0) {\n sLine = aOriginalDocData[iIndex] + \"\\n\";\n }\n iCount++;\n }\n });\n\n if (iCount) {\n aSearchResult.push(new Result(sDocName, iCount, sLine));\n }\n });\n\n\n //sort searched result\n aSearchResult.sort(compareResults);\n\n return aSearchResult;\n }", "function search_paragraph(query) {\r\n\tvar obj=new Object();\r\n\tconst array_raw=[]\r\n obj.markedString=\"\";\r\n obj.matches=[];\r\n obj.flagArray=[];\r\n if(query.length<=0) return obj;\r\n\r\n var splitPoints=[];\r\n var flagArray=query.split('').fill(-1);\r\n \r\n var query_low = query.toLowerCase();\r\n for(const term of dictionary){\r\n \tvar term_low = term[0].toLowerCase();\r\n \tvar term_syn = term_low.search(\",\")!=-1? term_low.split(\",\"):[term_low];\r\n \tfor (var term_s of term_syn){\r\n \t\tterm_s=strip(term_s)\r\n \t\tvar position=query_low.search(term_s);\r\n\t \tif(position!=-1)\r\n\t \t\tif(term_s.length <= 4 && (isLetter(query_low.charAt(position-1)) || isLetter(query_low.charAt(position+term_s.length))))\r\n\t \t\t\tcontinue;\r\n\t \t\telse {\r\n\t \t\t\tsplitPoints.push([position,position+term_s.length,term]); break;}\r\n \t}\r\n \t\r\n }\r\n\t\r\n\tvar len=splitPoints.length;\r\n if(len==0) return obj;\r\n\r\n var markedString=\"\";\r\n\tvar matches = []\r\n splitPoints.sort(numCompare);\r\n var start=0;\r\n for(var i=0;i<len;i++){\r\n \tconst match=splitPoints[i];\r\n \tmatches.push(match[2]);\r\n \tflagArray.fill(i,match[0],match[1]);\r\n \tif(match[0]>=start){\r\n\t \tmarkedString=markedString+query.substring(start,match[0])+\"\\<mark\\>\"+query.substring(match[0],match[1])+\"\\<\\/mark\\>\";\r\n\t \tstart=match[1];\r\n\t }\r\n\t}\r\n markedString=markedString+query.substring(start);\r\n obj.markedString=markedString;\r\n obj.matches=matches;\r\n obj.flagArray=flagArray;\r\n \r\n return obj;\r\n}", "function findMatches() {\n if (!this.value) { \n suggestions.innerHTML = \"\";\n return; \n }\n const wordToMatch = this.value;\n const finalEndpoint = `${endpoint}&per_page=${pages}&with_people=${with_people}&with_paywall=${with_paywall}&c=${wordToMatch}&t=${new Date().getTime()}`;\n fetch(finalEndpoint)\n .then(blob => blob.json())\n .then(data => displayMatches(data));\n }", "recurringLines(wordsNotLowercase) {\n // change psalm to array\n let arr = this.state.wholeChapter.replace(/[.,;:!?“”‘\\b’\\b]/g, '').split(/\\s/).filter(word => word !== '');\n // console.log(arr)\n // make everything lowercase except a few words\n const notLower = ['God', 'Lord', 'LORD'];\n for (let i = 0; i < arr.length; i++) {\n if (notLower.includes(arr[i])) {}\n else {\n arr[i] = arr[i].toLowerCase();\n // console.log(w.toLowerCase())\n } \n }\n // console.log(arr)\n let tempArr = [];\n let phrases = [];\n let indexOfPhrases = [];\n // loop through all once, comparing each word to all the others\n for (let i=0; i<arr.length; i++) {\n // loop all second time to find matches\n for (let j=0; j<arr.length; j++) {\n // check if three words in a row match and that the word isn't checking itself\n if (i!== j && arr[i] === arr[j] && arr[i+1] === arr[j+1] && arr[i+2] === arr[j+2]) {\n tempArr = [];\n let t2 = [];\n\n // a match of 3 words in a row gets pushed to tempArr\n tempArr.push(arr[i], arr[i+1], arr[i+2]);\n // check to see if 3 or more words match and push to tempArr if so\n let k = 3;\n while (arr[i+k] === arr[j+k]) {\n tempArr.push(arr[i+k]);\n k++;\n } \n t2 = tempArr.join(' ');\n\n // check if the phrase is already included and if the index of either of them are already included\n function check() {\n if (phrases.indexOf(t2) === -1 && indexOfPhrases.includes(i) === false && indexOfPhrases.includes(j) === false) {\n return true;\n }\n }\n if (check()) {phrases.push(t2)}; \n\n // if the index of the word wasn't already there, it gets pushed to indexOfPhrases to know which words were already included\n for (let l = 0; l < 3; l++) {\n if (indexOfPhrases.includes(i + l) === false) {\n indexOfPhrases.push(i + l);\n }\n }\n for (let l = 0; l < 3; l++) {\n if (indexOfPhrases.includes(j + l) === false) {\n indexOfPhrases.push(j + l);\n }\n }\n }\n }\n }\n for (let i = 0; i< phrases.length; i++) {\n let p = phrases[i].split(' ');\n let change = [];\n for (let i=0; i<p.length; i++ ) {\n let newp2 = p[i].charAt(0).toUpperCase()+p[i].slice(1);\n if (wordsNotLowercase.includes(newp2)) {\n change.push(i)\n }\n }\n change.forEach(e => {\n p[e] = p[e].charAt(0).toUpperCase()+p[e].slice(1)\n })\n phrases[i] = p.join(' ');\n }\n\n // call the func in the parent 'individualPsalm' component to pass the data to it so it can get displayed\n this.props.frequentPhrases(phrases);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
accountObject will have below property name, balance createaccount(accountObject) push onto accounts array return account object (on which we added)
function createAccount(account){ accounts.push(account); return account; }
[ "function createAccount(account){\n accounts.push(account);\n return account;\n}", "function createAccount (account) {\r\n\taccounts.push(account);\r\n\treturn account;\r\n}", "function createAccount(account) {\n accounts.push(account);\n return account;\n}", "function createAccount(balance, userName){\n\tconst account = new Account(balance, userName);\n\taccounts.push(account);\n\treturn account;\n}", "addAccount() {}", "createAccount (name) {\r\n name = cleanTextInput(name);\r\n if (typeof name === 'string' && this.findAccountIndex(name) === -1) {\r\n this._accountList.push(new Account(name));\r\n return this._accountList[this._accountList.length-1];\r\n } else {\r\n console.log('Error creating an account.'+\r\n ' Account name was not a string or a duplicate');\r\n }\r\n }", "addAccount (state, account) {\n state.accounts.push(account);\n }", "function createAcount (account) {\n accounts.push(account);\n return account;\n}", "function newAccount(name,acc,bal)\n{\n this.name = name;\n this.accNo = acc;\n this.balance = bal;\n}", "addBalanceTo(account, amount) {\n const foundAccount = this.accounts.find(obj => obj.id === account);\n if (foundAccount === undefined) {\n this.accounts.push({ id: account, balance: amount });\n }\n else {\n foundAccount.balance += amount;\n }\n }", "function BankAccount(name,balance) {\n this.name = name;\n this.balance = balance;\n}", "function addAccount(account) {\n if (accounts_json != null) {\n let newlist = [];\n for (let acc of accounts_json.list) {\n if (acc != undefined) {\n newlist.push(acc);\n }\n }\n accounts_json.list = newlist;\n }\n let saved_accounts = accounts_json;\n if (saved_accounts == undefined || saved_accounts == null || saved_accounts.list == 0)\n accounts = {\n list: [account]\n };\n else {\n saved_accounts.list.push(account)\n accounts = saved_accounts;\n }\n chrome.storage.local.set({\n accounts: encryptJson(accounts, mk)\n });\n initializeMainMenu();\n}", "constructor(accountName, accountBalance)\n {\n this.accountName = accountName;\n this.accountBalance = accountBalance;\n }", "createAccount() {\n const { privateKey } = this.web3.eth.accounts.create();\n return new Account_1.default(this.web3, privateKey);\n }", "function addAccountsToWallet(accounts){\n console.log(\"Adding Accounts to Wallet\");\n\n for(var key in accounts){\n web3.eth.accounts.wallet.add(accounts[key].privateKey);\n console.log(\"Added Private Key \"+accounts[key].privateKey+\" to Wallet\");\n }\n\n console.log(\"Added All Accounts to Wallet\");\n //web3.eth.accounts.wallet;\n return;\n}", "function addAccount() {\n db.addAccount(getDBResponse);\n}", "function addAccount(accountInfo, callback){\r\n\r\n\r\n\t\tcurrentTwitterAccount = getTwitterAccess({\r\n\t\t\tconsumer_key: CONSUMER_KEY,\r\n\t\t\tconsumer_secret: CONSUMER_SECRET,\r\n\t\t\taccess_token: accountInfo.oauth_access_token,\r\n\t\t\taccess_token_secret: accountInfo.oauth_access_token_secret\r\n\t\t});\r\n\r\n\t\t//get account info from Twitter\r\n\t\tgetAccountInfo(function(twitterData){\r\n\r\n\r\n\t\t\tvar newAccount = {\r\n\t\t\t\taccess_token: accountInfo.oauth_access_token,\r\n\t\t\t\taccess_token_secret: accountInfo.oauth_access_token_secret,\r\n\t\t\t\tscreen_name: twitterData.screenName,\r\n\t\t\t\timage_url: twitterData.picture\r\n\t\t\t};\r\n\r\n\r\n\t\t\t// add data to database\r\n\t\t\tdatabase.getModels(function(models){\r\n\t\t\t\tmodels.User.update(\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_id: userId\r\n\t\t\t\t\t},\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t$addToSet: {\r\n\t\t\t\t\t\t\t'accounts': newAccount\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t},\r\n\t\t\t\t\tfunction(error, result){\r\n\t\t\t\t\t\tif(error){\r\n\t\t\t\t\t\t\tconsole.log(\"error adding account: \"+error);\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\tcallback();\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\r\n\t\t});\r\n\r\n\t}", "function BankAccount (firstName, lastName, balance){\n this.firstName= firstName;\n this.lastName= lastName;\n this.balance= balance;\n}", "function personAccount()\n{\n let firstname='Snigdha',lastname='Sharma',income,expense\n let incomes=[1000,2000,1340,5670],expenses=[100,56,789]\n function totalIncome()\n {\n return incomes.reduce((total,income)=>total+income,0)\n }\n function totalExpense()\n {\n return expenses.reduce((total,expense)=>total+expense,0)\n }\n function accountInfo()\n {\n return 'Account belongs to '+firstname+' '+lastname+'. The total income is '+totalIncome()+'. The total expenses are '+totalExpense()+'. The account balance is '+(totalIncome()-totalExpense())\n }\n function addIncome(income)\n {\n incomes.push(income)\n }\n function addExpense(expense)\n {\n expenses.push(expense)\n }\n function accountBalance()\n {\n return totalIncome()-totalExpense()\n }\n return {\n totalIncome:totalIncome(),\n totalExpense:totalExpense(),\n accountInfo:accountInfo(),\n addIncome:addIncome(2000)\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts hours to milliseconds
function hoursToMs(hours) { return minutesToMs(hours * 60); }
[ "function fullTimeToMilliseconds(hours, minutes, seconds, milliseconds){\n hoursInMilli = hours * 3600000;\n minutesInMilli = minutes * 60000;\n secondsInMilli = seconds * 1000;\n return hoursInMilli + minutesInMilli + secondsInMilli + milliseconds;\n}", "function hrTimeToMilliseconds(time) {\n return Math.round(time[0] * 1e3 + time[1] / 1e6);\n}", "function convertMilliseconds(time_in_milliseconds){\n var time_in_seconds = time_in_milliseconds / 1000;\n var seconds = Math.floor(time_in_seconds % 60);\n var minutes = Math.floor((time_in_seconds / 60) % 60);\n var hours = Math.floor(time_in_seconds / (60 * 60));\n\n return hours + ' hours ' + minutes + ' minutes';\n }", "function CalculatTimeMilliseconds(time){\n var ms = time;\n var seconds = Math.floor(ms / 1000);\n var minutes = Math.floor(seconds / 60);\n seconds = seconds % 60;\n var hours = Math.floor(minutes / 60);\n minutes = minutes % 60;\n\n return hours + \" hours, \" + minutes + \" minutes, \" + seconds + \" seconds\";\n}", "function toMillis(time){\r\n return Number(time.split(':')[0])*60*60*1000+Number(time.split(':')[1])*60*1000;\r\n}", "function hrTimeToMilliseconds(hrTime) {\n return Math.round(hrTime[0] * 1e3 + hrTime[1] / 1e6);\n}", "function secondsToHms(d) {\n d = Number(d);\n var h = Math.floor(d / 3600);\n var m = Math.floor(d % 3600 / 60);\n var s = Math.floor(d % 3600 % 60);\n return ((h > 0 ? h + \":\" : \"0:\") + (m > 0 ? (h > 0 && m < 10 ? \"0\" : \"\") + m + \":\" : \"0:\") + (s < 10 ? \"0\" : \"\") + s); \n}", "function millisecondsToTime(milli) {\n\tvar milliseconds = milli % 1000;\n\tvar seconds = Math.floor((milli / 1000) % 60);\n\tvar minutes = Math.floor((milli / (60 * 1000)) % 60);\n\t\n\tif(seconds<10){\n\t\tseconds = '0'+seconds; \n\t}\n\t\n\tif(minutes<10){\n\t\tminutes = '0'+minutes; \n\t}\n\t\n\treturn minutes+':'+seconds;\n}", "function milliToTime (milliseconds) {\n var seconds = addAZero(Math.round(milliseconds / 1000));\n var minutes = addAZero(Math.round(seconds / 60));\n if (seconds >= 60){\n seconds = addAZero((seconds%60));\n }\n return ((minutes) + \":\" + (seconds));\n }", "function hrtimeMillisec(a){assertHrtime(a);return Math.floor(a[0]*1e3+a[1]/1e6);}", "function msConversion(millis) {\n var minutes = Math.floor(millis / 60000);\n var seconds = ((millis % 60000) / 1000).toFixed(0);\n return (seconds == 60 ? (minutes+1) + \":00\" : minutes + \":\" + (seconds < 10 ? \"0\" : \"\") + seconds);\n}", "function millisecondsToTime(milli) {\r\n var milliseconds = milli % 1000;\r\n var seconds = Math.floor((milli / 1000) % 60);\r\n var minutes = Math.floor((milli / (60 * 1000)) % 60);\r\n\t \r\n\t if(seconds<10){\r\n\t\tseconds = '0'+seconds; \r\n\t }\r\n\t \r\n\t if(minutes<10){\r\n\t\tminutes = '0'+minutes; \r\n\t }\r\n\t return seconds+' SEC';\r\n}", "function msConversion(millis) {\n let sec = Math.floor(millis / 1000);\n let hrs = Math.floor(sec / 3600);\n sec -= hrs * 3600;\n let min = Math.floor(sec / 60);\n sec -= min * 60;\n\n sec = '' + sec;\n sec = ('00' + sec).substring(sec.length);\n\n if (hrs > 0) {\n min = '' + min;\n min = ('00' + min).substring(min.length);\n return hrs + \":\" + min + \":\" + sec;\n }\n else {\n return min + \":\" + sec;\n }\n\n /**\n let minutes = Math.floor(millis / 60000);\n let seconds = ((millis % 60000) / 1000).toFixed(0);\n return (seconds == 60 ? (minutes+1) + \":00\" : minutes + \":\" + (seconds < 10 ? \"0\" : \"\") + seconds);\n **/\n}", "function msToHMS( ms ) {\n var seconds = ms / 1000; // 1- Convert to seconds\n var hours = parseInt( seconds / 3600 ); // 2- Extract hours\n seconds = seconds % 3600;\n var minutes = parseInt( seconds / 60 ); // 3- Extract minutes\n seconds = seconds % 60; // 4- Keep only seconds not extracted to minutes\n if(hours)\n return ( hours+\" hr \"+minutes+\" min \");\n else\n return ( minutes+\"m \"+parseInt(seconds)+\"s\" );\n}", "timeConvert(data) {\n let minutes = data % 60\n let hours = (data - minutes) / 60\n return `${hours}h ${minutes}m`\n }", "get timeWithMilliseconds() {\n return (\n `${this.twelveHour}:${this.fullMinutes}:${this.fullSeconds}` +\n `.${this.milliseconds}${this.meridiem}`\n );\n }", "function past(h, m, s){\n // Your code here!\n let hToMil = h * 60 * 60 *1000;\n let mToMil = m * 60 *1000;\n let sToMil = s * 1000;\n let convetedToMillisecond = hToMil+mToMil+sToMil;\n\n return convetedToMillisecond;\n}", "timeInHours(minutes){\r\n minutes*=Min\r\n console.log(Hr)\r\n return minutes/Hr\r\n }", "function minutesToMilliseconds (minutes){\n return minutes * 60000;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
handles the names bouncing left and right
function updateNamePositions() { name_trackers.forEach((v, k) => { v.vx = v.vx + DEFAULT_ACCELERATION v.x = v.x + v.vx if (v.x < 0 || v.x > v.max_x) { if (v.x < 0) { v.x = 0; } else { v.x = v.max_x; } v.vx = -0.5 * v.vx; } v.elem.style.paddingLeft = `${v.x}px` }) }
[ "animateName(direction){\n if(direction === \"in\"){\n const nameContainer = document.getElementById(\"name_container\");\n nameContainer.style.pointerEvents = \"none\";\n nameContainer.classList.remove(\"name_bounce_out\");\n nameContainer.classList.add(\"name_bounce_in\");\n }\n else{\n const nameContainer = document.getElementById(\"name_container\");\n nameContainer.classList.remove(\"name_bounce_in\");\n nameContainer.classList.add(\"name_bounce_out\");\n }\n }", "function animateName() {\n\n\tfunction swapLetters() {\n\n\t\t$(\".swap-letters\").each( function() {\n\t\t\tvar nameLen = $(this).children().length,\n\t\t\t\tdashLen = $(this).find( \".name-dash\" ).length,\n\t\t\t\trandomChar = $(this).children().eq( rando( 0, nameLen ) ),\n\t\t\t\trandomDash = $(this).find( \".name-dash\" ).eq( rando( 0, dashLen ) );\n\n\t\t\trandomChar.before( randomDash );\n\t\t});\n\t\t\n\t}\n\t\n\tvar int = setInterval( swapLetters, 200 );\n\n}", "function alignName(name, block) {\n\tvar offset = $(block).offset();\n\tif (name === 'a') {\n\t\toffset.left += 5;\n\t} else if (name === 'b') {\n\t\toffset.left += 20\n\t} else if (name === 'c') {\n\t\toffset.left += 35;\n\t}\n\t$('#' + name).offset(offset);\n}", "function moveBallShare(ball, left) {\n // Set lower limits\n var slider = $(ball)[0].parentElement;\n var sLeft = 250.5;\n var sRight = -10.5;\n $(slider).find('.slider_ball').each(function(){\n if ( $(this).position().left < sLeft ) {\n sLeft = $(this).position().left;\n }\n if ( $(this).position().left > sRight ) {\n sRight = $(this).position().left;\n }\n });\n // Handle left bound\n // console.log($(ball).position().left == sLeft,$(ball).position().left,sLeft);\n if ( $(ball).position().left == sLeft && left < -10.5 ) {\n left = -10.5;\n } else if ( $(ball).position().left == sLeft && left >= sRight ) {\n left = sRight - 5;\n }\n // Handle right bound\n if ( $(ball).position().left == sRight && left <= sLeft ) {\n left = sLeft + 5;\n } else if ( $(ball).position().left == sRight && left > 250.5 ) {\n left = 250.5;\n }\n\n // Move the label\n if ( $(ball).position().left == sLeft ) {\n if ( left > 50 ) {\n $(ball).addClass('sideLabelL');\n } else {\n $(ball).removeClass('sideLabelL');\n }\n } else if ( $(ball).position().left == sRight ) {\n if ( left < 200.5 ) {\n $(ball).addClass('sideLabelR');\n } else {\n $(ball).removeClass('sideLabelR');\n }\n }\n\n // Move the ball\n $(ball).css('left', left);\n\n // Style the bar\n // Get the extremes\n var sLeft = 250.5;\n var sRight = -10.5;\n $(slider).find('.slider_ball').each(function(){\n if ( $(this).position().left < sLeft ) {\n sLeft = $(this).position().left;\n }\n if ( $(this).position().left > sRight ) {\n sRight = $(this).position().left;\n }\n });\n // Calculations and styling\n var length = 265;\n var sLeftPerc = Math.round((sLeft + 10.5) / length * 100);\n var sRightPerc = Math.round((sRight + 10.5) / length * 100);\n $(slider).css('background','linear-gradient(to right, #cccccc 0%, #cccccc ' + sLeftPerc + '%, #3098ff ' + sLeftPerc + '%, #3098ff ' + sRightPerc + '%, #cccccc ' + sRightPerc + '%, #cccccc 100%)');\n\n // Calculate average\n var low = shareSlider(sLeft + 10.5);\n var high = shareSlider(sRight + 10.5);\n var avg = (low + high) / 2;\n var avgPos = (sLeft + sRight + 21) / 2;\n\n // Flip the average if too close\n if ( Math.abs(sRight - sLeft) < 140 ) {\n $(slider).find('.slider_avg_caret').addClass('invert');\n } else {\n $(slider).find('.slider_avg_caret').removeClass('invert');\n }\n\n // Move the average slider\n $(slider).find('.slider_avg_caret').each(function(){\n $(this).css('left',(avgPos - 3) + 'px');\n });\n\n // Insert values\n var ballVal = shareSlider(left + 10.5);\n if ( (ballVal % 1) != 0 ) {\n ballVal = ballVal + '0';\n } else if ( ballVal < 10 ) {\n ballVal = ballVal + '.00';\n }\n $(ball).find('.slider_ball_label').html('$' + ballVal);\n if ( avg < 10 ) {\n avg = Math.round(10 * avg) / 10;\n if ( avg % 1 != 0 ) {\n avg = avg + '0';\n } else {\n avg = avg + '.00';\n }\n } else {\n avg = Math.round(avg);\n }\n $(slider).find('.slider_avg').html('$' + avg + ' Average');\n}", "bounce(){\n // left to right movement\n if (this.x_location >= width || this.x_location <= 0){\n this.delta_x *= -1;\n }\n\n // up and down movement\n if (this.y_location >= height -100 || this.y_location <= 0){\n this.delta_y *= -1;\n }\n }", "function moveAliensRight() {\n //* remove aliens from current positions\n currentAlienPositions.forEach((alien) => {\n cells[alien].classList.remove('alien')\n })\n //* Redefine Positions\n currentAlienPositions = currentAlienPositions.map((alien) => {\n return alien += 1\n })\n //* Add aliens to new positions\n currentAlienPositions.forEach((alien) => {\n cells[alien].classList.add('alien')\n })\n}", "function moveBallCap(ball, left) {\n // Set lower limits\n var slider = $(ball)[0].parentElement;\n var sLeft = 250.5;\n var sRight = -10.5;\n $(slider).find('.slider_ball').each(function(){\n if ( $(this).position().left < sLeft ) {\n sLeft = $(this).position().left;\n }\n if ( $(this).position().left > sRight ) {\n sRight = $(this).position().left;\n }\n });\n // Handle left bound\n if ( $(ball).position().left == sLeft && left < -10.5 ) {\n left = -10.5;\n } else if ( $(ball).position().left == sLeft && left >= sRight ) {\n left = sRight - 5;\n }\n // Handle right bound\n if ( $(ball).position().left == sRight && left <= sLeft ) {\n left = sLeft + 5;\n } else if ( $(ball).position().left == sRight && left > 250.5 ) {\n left = 250.5;\n }\n\n // Move the label\n if ( $(ball).position().left == sLeft ) {\n if ( left > 50 ) {\n $(ball).addClass('sideLabelL');\n } else {\n $(ball).removeClass('sideLabelL');\n }\n } else if ( $(ball).position().left == sRight ) {\n if ( left < 200.5 ) {\n $(ball).addClass('sideLabelR');\n } else {\n $(ball).removeClass('sideLabelR');\n }\n }\n\n // Move the ball\n $(ball).css('left', left);\n\n // Style the bar\n // Get the extremes\n var sLeft = 250.5;\n var sRight = -10.5;\n $(slider).find('.slider_ball').each(function(){\n if ( $(this).position().left < sLeft ) {\n sLeft = $(this).position().left;\n }\n if ( $(this).position().left > sRight ) {\n sRight = $(this).position().left;\n }\n });\n // Calculations and styling\n var length = 265;\n var sLeftPerc = Math.round((sLeft + 10.5) / length * 100);\n var sRightPerc = Math.round((sRight + 10.5) / length * 100);\n $(slider).css('background','linear-gradient(to right, #cccccc 0%, #cccccc ' + sLeftPerc + '%, #3098ff ' + sLeftPerc + '%, #3098ff ' + sRightPerc + '%, #cccccc ' + sRightPerc + '%, #cccccc 100%)');\n\n // Calculate average\n var low = capSlider(sLeft + 10.5);\n var high = capSlider(sRight + 10.5);\n var avg = (low + high) / 2;\n var avgPos = (sLeft + sRight + 21) / 2;\n\n // Flip the average if too close\n if ( Math.abs(sRight - sLeft) < 140 ) {\n $(slider).find('.slider_avg_caret').addClass('invert');\n } else {\n $(slider).find('.slider_avg_caret').removeClass('invert');\n }\n\n // Move the average slider\n $(slider).find('.slider_avg_caret').each(function(){\n $(this).css('left',(avgPos - 3) + 'px');\n });\n\n // Insert values\n var ballVal = capSlider(left + 10.5);\n if ( ballVal >= 1000000000 ) {\n ballVal = (ballVal / 1000000000) + 'B';\n } else if ( ballVal >= 1000000 ) {\n ballVal = (ballVal / 1000000) + 'M';\n } else if ( ballVal >= 1000 ) {\n ballVal = (ballVal / 1000) + 'K';\n }\n $(ball).find('.slider_ball_label').html('$' + ballVal);\n if ( avg < 10 ) {\n avg = Math.round(10 * avg) / 10;\n if ( avg % 1 != 0 ) {\n avg = avg + '0';\n } else {\n avg = avg + '.00';\n }\n } else {\n avg = Math.round(avg);\n }\n if ( avg >= 1000000000 ) {\n avg = Math.round(avg / 1000000000) + 'B';\n } else if ( avg >= 1000000 ) {\n avg = Math.round(avg / 1000000) + 'M';\n } else if ( avg >= 1000 ) {\n avg = Math.round(avg / 1000) + 'K';\n } else {\n avg = Math.round(avg);\n }\n $(slider).find('.slider_avg').html('$' + avg + ' Average');\n}", "function wordsFloat () {\n // Setting the position to be relative keeps the original position of each letter\n $(this).css({\n position:'relative'\n });\n // This animates each letter to 80px above its original position\n $(this).animate({\n top: '-80px'\n });\n // Once the above animation is finished, this animation sends each letter back to its starting location\n $(this).animate({\n top:'0'\n });\n}", "function bouncePaddles() {\n\tif ((rectangB >= paddleRTop) && (rectangTop <= paddleRB)) {\n\tif (rectangR >= paddleRleftside) {\n\t\t rectangxVel = -rectangxVel\n\t\t}\n }\n if ((rectangB >= paddleLTop) && (rectangTop <= paddleLB)) {\n\tif (rectangL <= paddleLrightside) {\n\t\t rectangxVel = -rectangxVel\n\t\t}\n }\n}", "function BounceToMouse(ABall) {\r\n if (ABall.y >= 785) {\r\n ABall.v = ABall.v - (ABall.v*2) - 0.1;\r\n\r\n } \r\n ABall.v = ABall.v + 0.1;\r\n ABall.y += ABall.v;\r\n}", "function sliderBounce() {\n \n if( ballY > rectY && ballY < rectY + 100){ \n ballXV = ballXV * -1;\n }\n \n}", "function moveLeftTargetsAnimation() {\n //Target 2\n realDuckModelArray[2].position.x -= 2;\n}", "changeDirectionEW() {\n this.y = this.leader.y;\n this.direction = this.leader.direction;\n this.update();\n }", "flip(toOrigin = false) {\n if (this.backside == null) return;\n else if (toOrigin) {\n this.currentName = this.name;\n this.text_color = \"black\";\n }\n else {\n if (this.currentName == this.name) {\n this.currentName = this.backside;\n this.text_color = \"red\";\n } else {\n this.currentName = this.name;\n this.text_color = \"black\";\n }\n }\n }", "function left(x) { \n currentAlignment = alignLeft \n}", "function right(x) { \n currentAlignment = alignRight \n}", "function fireLeft(){\n\t\tconsole.log(\"firing\");\n\t\tdart1.style.left = \"-200px\";\n\t\tdart2.style.left = \"-400px\";\n\t\tdart3.style.left = \"-600px\";\n\t\tdart4.style.left = \"-550px\";\n\t}", "moveBird(direction)\r\n {\r\n switch(direction)\r\n {\r\n case 'up':\r\n if ( this.birdPositionHeight < this.maxHeight)\r\n this.birdPosition = this.birdPosition.times(Mat4.translation([0, 1, 0]))\r\n break;\r\n\r\n\r\n case 'down':\r\n if ( this.birdPositionHeight > -1 * this.maxHeight)\r\n this.birdPosition = this.birdPosition.times(Mat4.translation([0, -1, 0]))\r\n break;\r\n\r\n\r\n case 'jump':\r\n var offset = 0.0005 * this.birdPositionHeight // Offset intended to make the jump less excessive as it approaches max height \r\n // and more excessive as it approaches -max height\r\n this.birdSpeed += 0.3 - offset\r\n this.playSound(\"birdflap\")\r\n break;\r\n\r\n\r\n case 'gravity':\r\n if ( this.birdPositionHeight < this.maxHeight && this.birdPositionHeight > this.groundLevel + 2)\r\n {\r\n var offset = 0 // Meant to increase the acceleration(gravity) as bird approaches max height to make game feel more dynamic\r\n if (this.birdPositionHeight > -5)\r\n offset = -0.0015 * Math.abs(this.birdPositionHeight)\r\n\r\n this.birdSpeed += this.birdAcceleration + offset;\r\n this.birdPosition = this.birdPosition.times(Mat4.translation([0, this.birdSpeed, 0]))\r\n }\r\n\r\n else if (this.birdPositionHeight >= this.maxHeight)\r\n {\r\n this.birdSpeed = 0\r\n this.birdPosition = this.birdPositionOriginal.times(Mat4.translation([0, 9.9, 0]))\r\n this.playSound('bounce', 0.2)\r\n }\r\n\r\n else\r\n { this.endGame(); this.playSound('crashWater'); }\r\n\r\n break;\r\n }\r\n \r\n }", "function followTarget(a,b)\r\n{\t\t\t\r\n\tif (a.x > b.x) { a.x -= a.speed * modifier; }\r\n\tif (a.x < b.x) { a.x += a.speed * modifier; }\r\n\tif (a.y < b.y) { a.y += a.speed * modifier; }\r\n\tif (a.y > b.y) { a.y -= a.speed * modifier; }\r\n\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds keys that matches `alwaysShowRegExp` to `alwaysShow`. Passes `alwaysShowRegExp` down to children so that it is applied recursively.
fixAlwaysShowRegExp(schema) { if (!schema.alwaysShow) { schema.alwaysShow = []; } Object.keys(schema.properties) .forEach(key => { // pass alwaysShowRegExp down to apply it recursively. const subSchema = schema.properties[key]; if (subSchema.type === 'object') { subSchema.alwaysShowRegExp = schema.alwaysShowRegExp; } if (key.search(schema.alwaysShowRegExp) > -1) { schema.alwaysShow.push(key); } }); return schema; }
[ "fixAlwaysShow(schema) {\n const alwaysShow = schema.alwaysShow;\n schema.alwaysShow = alwaysShow.filter(key => {\n if (schema.properties[key]) {\n return true;\n }\n else {\n console.warn(`${key} is configured as alwaysShow but it is not in ${JSON.stringify(Object.keys(schema.properties))}`);\n }\n });\n return schema;\n }", "function initOptionsFieldsShows() {\n let set = new Set(this.showingOptionalFields);\n this.optionalFields.forEach(item => {\n this[\"show\" + item.value] = set.has(item.value);\n });\n}", "__registerShowCondition(field) {\n const { expression, expressions = [] } = field.showCondition;\n\n const addExpressionToTriggerMap = exp => {\n if (ExpressionService.isFormResponseExpression(exp)) {\n let list = this.showConditionTriggerMap[exp[FIELD.ID]];\n if (!list) {\n list = [];\n this.showConditionTriggerMap[exp[FIELD.ID]] = list;\n }\n list.push(field[FIELD.ID]);\n }\n };\n\n addExpressionToTriggerMap(expression);\n\n if (!isEmpty(expressions)) {\n expressions.forEach(exp => {\n addExpressionToTriggerMap(exp);\n });\n }\n }", "function updateKeyItemTitles() {\n $('.colorkey-item-exclusivetoggle').each(function() {\n var attrVal = $(this).parent().attr(\"attrval\");\n var showingVal = $(this).parent().attr(\"showing-exclusively\");\n if (showingVal == \"true\") {\n $(this).attr(\"title\", \"Show everything\");\n } else {\n $(this).attr(\"title\", \"Show only \" + attrVal + \"\");\n }\n });\n $('.colorkey-item-maintoggle').each(function() {\n var attrVal = $(this).parent().attr(\"attrval\");\n var showingVal = $(this).parent().attr(\"hiding-this-val\");\n if (showingVal == \"true\") {\n $(this).attr(\"title\", \"Show \" + attrVal + \"\");\n } else {\n $(this).attr(\"title\", \"Hide \" + attrVal + \"\");\n }\n });\n}", "function showOptions (Layout, key, debugOpts) {\n\tvar data = Layout.options;\n\tjQuery.each(key.split(\".\"), function() {\n\t\tdata = data[this]; // recurse through multiple key-levels\n\t});\n\tdebugData( data, 'options.'+key, debugOpts );\n}", "function showOptions (Layout, key, debugOpts) {\n\tvar data = Layout.options;\n\t$.each(key.split(\".\"), function() {\n\t\tdata = data[this]; // recurse through multiple key-levels\n\t});\n\tdebugData( data, 'options.'+key, debugOpts );\n}", "function expandAndShowDescendants(selector) {\n selector.find('.category, .main-category').each(function() {\n expandAndShowSelf($(this));\n });\n\n selector.find('.keyword').each(function() {\n $(this).show();\n });\n}", "function showLevelChildren() {\r\n if (activeGroup) {\r\n for (var i = 3; i < activeGroup.children.length; i++) {\r\n activeGroup.children[i].visible = true;\r\n }\r\n }\r\n}", "showProps(automationNode, sourceName) {\n this.lastKey = automationNode.key;\n\n const remainingProps = this.getPropsToShow(automationNode);\n const childrenToAdd = [];\n const propMap = this.getPropMap();\n\n $('#props-legend-source-name').text(sourceName || '');\n\n // Organize the properties by intuitive groupings\n for (let groupName in propMap) {\n if (!propMap.hasOwnProperty(groupName)) {\n continue;\n }\n let props;\n if (propMap[groupName] === '*') {\n // ** Other **\n // Show remaining properties not in another group\n props = remainingProps;\n }\n else if (propMap[groupName] === '()') {\n // ** Function **\n props = Array.from(remainingProps).filter((name) =>\n automationNode[name].isFunction);\n }\n else if (typeof propMap[groupName] === 'string') {\n // ** String ** -> Remap to a different property\n props = automationNode[propMap[groupName]];\n }\n else {\n // ** General ** -> Group the set of properties provided\n props = new Set(propMap[groupName]);\n }\n\n // Add props to |group| and remove from |remainingProps|\n const group = {};\n for (let prop of props) {\n if (remainingProps.has(prop)) { // Only use each prop once\n group[prop] = automationNode[prop];\n remainingProps.delete(prop);\n }\n }\n\n // Get view initialization data for the group\n const groupTreeChildren =\n this.toTreeData(group);\n if (groupTreeChildren.length) {\n childrenToAdd.push({\n title: groupName,\n children: groupTreeChildren,\n expanded: !this.isCollapsedByDefault(groupName)\n });\n }\n }\n\n this.clearAll();\n this.getViewRootNode().addChildren(childrenToAdd);\n }", "onBeforeShow() {\n traceFirstScreenShown();\n this.propagateOnBeforeShow();\n }", "function addHotkey(node, i) {\n node[\"text\"] = node[\"text\"] + (i < hotkeys.length ? '<span>' + hotkeys[i] + '</span>' : '<span class=\"hide\"></span>');\n for(var i in node.children) {\n addHotkey(node.children[i], i);\n } \n }", "function setShowHighlights(show) {\n return { type: actions.SET_HIGHLIGHTS_VISIBLE, visible: show };\n}", "__registerShowCondition(field) {\n const { expression, expression1, expression2 } = field.showCondition;\n [expression, expression1, expression2].forEach(_expression => {\n if (ExpressionService.isFormResponseExpression(_expression)) {\n let list = this.showConditionTriggerMap.find(_expression.id);\n if (!list) {\n list = [];\n this.showConditionTriggerMap.add(_expression.id, list);\n }\n list.push(field[FIELD.ID]);\n }\n });\n }", "function showHideAdvancedSearch(doShow) {\n var advDiv = $(\"div#advancedSearch\");\n //console.log(\"showHideAdvancedSearch\", doShow);\n //if ($(advDiv).css(\"display\") == \"none\") {\n if (doShow) {\n // advanced hash detected...\n $(\"#extendedOptions\").slideToggle('slow', function(){\n // change plus/minus icon when transition is complete\n $(this).prev(\".toggleTitle\").toggleClass('toggleTitleActive');\n });\n }\n}", "function showSuggestions(forceShow) {\n resetSelection();\n\n matches = false;\n\n var data = (options.filter) ? filterResults(context.val()) : jsonData;\n\n\n if (data) {\n if (data) {\n var $suggestions = createSuggestionsList(data);\n }\n }\n\n // Check for focus before showing suggestion box. User could have clicked outside before request finished.\n if (active || forceShow) {\n\n if (matches && (context.val().length > 0 || forceShow)) {\n // we have exactly 1 exact match and have set the hideOnExactMatch option to true, so hide the suggestion box\n if (options.hideOnExactMatch && exactMatch) {\n hideSuggestionBox();\n } else {\n // we have some suggestions, so show them\n $suggestionBox.html($suggestions);\n setSuggestionBoxWidth();\n showSuggestionBox();\n }\n } else if (forceShow) {\n // We don't have any suggestions, but we are forcing display, show it regardless.\n if (options.showNoSuggestionsMessage) {\n getNoSuggestionMarkup();\n }\n setSuggestionBoxWidth();\n showSuggestionBox();\n } else if (options.showNoSuggestionsMessage && context.val().length > 0) {\n // We don't have any suggestions for input and want to display no suggestion message\n setSuggestionBoxWidth();\n showSuggestionBox();\n getNoSuggestionMarkup();\n } else {\n // Nope,no matches, hide the suggestion box\n hideSuggestionBox();\n }\n } else {\n // The search box no longer has focus, hide the suggestion box\n hideSuggestionBox();\n }\n }", "function additionalOptionsShow() {\n $(\"#carCategoryGroup\").slideDown(\"slow\");\n $('#musicStyleGroup').slideDown(\"slow\");\n $('#freeWifiCh').slideDown(\"slow\");\n $('#nonSmokingDriverCh').slideDown(\"slow\");\n $('#airConditionerCh').slideDown(\"slow\");\n $('#animalTransportationCh').slideDown(\"slow\");\n }", "function showFastLoadMenu() {\n E.showMenu();\n E.showAlert(/*LANG*/\"WARNING! Only enable fast loading for apps that use widgets.\").then(() => {\n E.showMenu({\n '': {\n 'title': 'Shortcuts',\n 'back': showMainMenu\n },\n 'Top first': {\n value: config.fastLoad.shortcuts[0],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[0] = value;\n saveSettings();\n }\n },\n 'Top second': {\n value: config.fastLoad.shortcuts[1],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[1] = value;\n saveSettings();\n }\n },\n 'Top third': {\n value: config.fastLoad.shortcuts[2],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[2] = value;\n saveSettings();\n }\n },\n 'Top fourth': {\n value: config.fastLoad.shortcuts[3],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[3] = value;\n saveSettings();\n }\n },\n 'Bottom first': {\n value: config.fastLoad.shortcuts[4],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[4] = value;\n saveSettings();\n }\n },\n 'Bottom second': {\n value: config.fastLoad.shortcuts[5],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[5] = value;\n saveSettings();\n }\n },\n 'Bottom third': {\n value: config.fastLoad.shortcuts[6],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[6] = value;\n saveSettings();\n }\n },\n 'Bottom fourth': {\n value: config.fastLoad.shortcuts[7],\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.shortcuts[7] = value;\n saveSettings();\n }\n },\n 'Swipe up': {\n value: config.fastLoad.swipe.up,\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.swipe.up = value;\n saveSettings();\n }\n },\n 'Swipe down': {\n value: config.fastLoad.swipe.down,\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.swipe.down = value;\n saveSettings();\n }\n },\n 'Swipe left': {\n value: config.fastLoad.swipe.left,\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.swipe.left = value;\n saveSettings();\n }\n },\n 'Swipe right': {\n value: config.fastLoad.swipe.right,\n format: value => value ? 'Fast' : 'Slow',\n onchange: value => {\n config.fastLoad.swipe.right = value;\n saveSettings();\n }\n }\n });\n })\n }", "function applyCustomShows() {\n if (! fromPreview) {\n cloga('showHideTags');\n// if (perm.yk) {\n// showHideTags(!! lu_console.showAdminTags);\n// }\n cloga('showHideFreeTags');\n if (showFT) {\n showHideFreeTags();\n }\n cloga('showHideHeader');\n showHideHeader(!! lu_console.showHeader);\n }\n}", "function expandAll() {\r\n const allNodesLen = monthKeys.length + yearKeys.length;\r\n if (expandedKeys.length === allNodesLen) {\r\n return;\r\n }\r\n setExpandedKeys(monthKeys.concat(yearKeys));\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search for products by subcategory from params
async getProductsBySubcategory() { try { const subcategory = Number(this.props.match.params.subcategory.split('+')[1]); const collection = await gameApi.getProductsBySubcategory(subcategory); // const title = await gameApi.getTitle({subcategory}); // if (this.is_mounted) { this.setState({ subcategory, collection, pending: false, // title }); // } } catch { if (this.is_mounted) { this.setState({ collection: [], pending: false }) } } }
[ "getItemsInSubCategory(subcategory, items = this.items) {\n // assume items array is a value from getItemsInCategory\n const categoryName = this.getCategories(items)[0];\n return items.filter((item) => item.category[categoryName][0] === subcategory);\n }", "filteredProducts(){\n const allProductsinCategory = this.props.data.allAirtable.nodes\n\n // if \"All\" is checked, return everything\n if (this.state.subCategories[0].checked){\n return allProductsinCategory\n }\n // filter all subCategories which are checked, returns an array of subc which are checked\n const allCheckedSubcategories = this.state.subCategories.filter((subCategory) => {\n return subCategory.checked === true\n })\n // we are mapping thru the above array and getting just strings with names\n const allCheckedSubcategoryNames = allCheckedSubcategories.map(element => {\n return element.name\n })\n // final logic, all the objects are being filtered based on the subcategory match\n const allMatchingProducts = allProductsinCategory.filter((product) => {\n const match = product.data.Sub_Categories.some(subcategory => allCheckedSubcategoryNames.includes(subcategory))\n return match\n })\n return allMatchingProducts\n }", "subCategoryFilter(category, selectedSubCategory) {\n let vm = this;\n let { $rootScope, $state, $scope, SearchBarService, $stateParams } = vm.DI();\n delete sessionStorage.categoryHint;\n vm.categoryHint = \"\";\n /*if(selectedSubCategory.select){\n return;\n }*/\n /* angular.forEach(category.children, function(obj){ \n if(selectedSubCategory.id == obj.id){\n selectedSubCategory.select = !selectedSubCategory.select;\n }else{\n obj.select = false;\n }\n });*/\n\n /*angular.forEach(vm.categoryPristine, function (obj) {\n if (category.id == obj.id) {\n if (category.select) {\n } else {\n SearchBarService.productClass = 0;\n }\n angular.forEach(obj.children, function (child) {\n if (selectedSubCategory.id == child.id) {\n selectedSubCategory.select = !selectedSubCategory.select;\n child.select = selectedSubCategory.select;\n } else {\n child.select = false;\n }\n });\n } else {\n obj.select = false;\n angular.forEach(obj.children, function (child) {\n child.select = false;\n });\n }\n });*/\n SearchBarService.listPreviousFilter = [];\n SearchBarService.sort = null;\n $rootScope.$broadcast(\"categoryFilterApplied\");\n selectedSubCategory.select = !selectedSubCategory.select;\n if (selectedSubCategory.select) {\n SearchBarService.productCategory = selectedSubCategory;\n let paramObj = { 'filters': \"\", 'filterObject': \"\", \"cat2\": category.id, \"cat3\": selectedSubCategory.id, \"from\": \"\", \"size\": \"\", \"y\": $stateParams.y, \"mk\": $stateParams.mk, \"md\": $stateParams.md, \"sort\": \"\" };\n $state.go(\"searchResults\", paramObj);\n } else {\n SearchBarService.productCategory = 0;\n let paramObj = { 'filters': \"\", 'filterObject': \"\", \"cat1\": $stateParams.cat1, \"cat2\": category.id, \"cat3\": \"\", \"from\": \"\", \"size\": \"\", \"y\": $stateParams.y, \"mk\": $stateParams.mk, \"md\": $stateParams.md, \"sort\": \"\" };\n $state.go(\"searchResults\", paramObj);\n }\n\n\n //$scope.$emit(\"searchLaunched\");\n\n\n }", "function getSubCategory(){\n loading.startLoading();\n var category=$(\"#filterServiceCategory\").val();\n var categoryArr=category.split(\"|\");\n \n dbmanager.getProfile(function(returnData){\n if(returnData.rows.length>0){\n var token=returnData.rows.item(0).token;\n postServiceSearchCriteriaSubCategory(token, categoryArr[1]);\n }\n else{\n var token=\"\";\n postServiceSearchCriteriaSubCategory(token, categoryArr[1], \"\");\n }\n });\n}", "function search(searchQuery)\n{\n showProducts(\"s\",null,null,searchQuery,categories);\n}", "function selectProducts() {\n // If no search term has been entered, just make the finalGroup array equal to the categoryGroup\n // array — we don't want to filter the products further — then run updateDisplay().\n if(searchTerm.value.trim() === '') {\n finalGroup = categoryGroup;\n updateDisplay();\n } else {\n // Make sure the search term is converted to lower case before comparison. We've kept the\n // product names all lower case to keep things simple\n let lowerCaseSearchTerm = searchTerm.value.trim().toLowerCase();\n // For each product in categoryGroup, see if the search term is contained inside the product name\n // (if the indexOf() result doesn't return -1, it means it is) — if it is, then push the product\n // onto the finalGroup array\n for(let i = 0; i < categoryGroup.length ; i++) {\n if(categoryGroup[i].name.indexOf(lowerCaseSearchTerm) !== -1) {\n finalGroup.push(categoryGroup[i]);\n }\n }\n\n // run updateDisplay() after this second round of filtering has been done\n updateDisplay();\n }\n\n }", "function searchProductCategory() {\n\n productCategoryService.searchProductCategory($scope.productCategorySearch, $scope.pageLimit, $scope.currentPage)\n .then(function success(response) {\n\n $scope.categoryLists = response.data.data;\n $scope.totalItems = response.data.dataCount;\n $scope.catCount = response.data.dataCount;\n\n }, function error(error) {\n toastr.error('ERROR!', 'Replacement has been Create failed.');\n });\n }", "function searchElectronicProducts(req, res) {\n baseRequest.searchCategoryForProduct(req,res,Electronics);\n}", "onSubcategoryCheck(category, subcategory) {\n if (this.getSubcategoryFromConfig() === subcategory) {\n this.setListingFilters({\n category: null,\n subCategory: null\n })\n } else {\n this.setListingFilters({\n category: category[0],\n subCategory: subcategory[0]\n })\n }\n }", "function findByKeywordAndCategory() {\n // escape special chars from keyword\n _keyword = stringHelper.escapeSpecialCharacters(_keyword);\n getSubByCategoryId()\n .then(subcate_ids => {\n // Check pagination\n _findQuery = _pageNumber === undefined ? Course.find({ 'name': { $regex: new RegExp(_keyword, \"i\") }, $or: [{ 'categoryid': _categoryId }, { 'categoryid': { $in: subcate_ids } }] }).sort('name').limit(_pageSize)\n : Course.find({ 'name': { $regex: new RegExp(_keyword, \"i\") }, $or: [{ 'categoryid': _categoryId }, { 'categoryid': { $in: subcate_ids } }] }).sort('name').skip((_pageNumber - 1) * _pageSize).limit(_pageSize);\n var countQuery = Course.count({ 'name': { $regex: new RegExp(_keyword, \"i\") }, $or: [{ 'categoryid': _categoryId }, { 'categoryid': { $in: subcate_ids } }] });\n\n // Execute the queries\n executeCountQuery(countQuery)\n .then(totalRecord => {\n executeFindQuery(totalRecord);\n })\n .catch(err => {\n logger.error(\"Error at function: CourseController.findAll->findByKeywordAndCategory\", err);\n return res.send({ code: 400, message: \"Data not found!\" });\n })\n })\n .catch(err => {\n logger.error(\"Error at function: CourseController.findAll->findByKeywordAndCategory\", err);\n return res.send({ code: 400, message: \"Data not found!\" });\n })\n }", "function getSearchProducts(searchRecord) {\n kony.print(\"########## Selected searchRecord:\" + JSON.stringify(searchRecord));\n // Let's first check that the user picked a valid value\n if (!kony.string.equalsIgnoreCase(searchRecord.searchText, \"none\")) {\n // Populating the input params for the service call and invoking the service\n var operationName = mobileFabricConfiguration.integrationServices[0].operations[2];\n var inputParams = {\n \"key\": mobileFabricConfiguration.bestByAPIKey,\n \"searchText\": searchRecord.searchText,\n \"pageNo\": searchRecord.pageNo\n };\n if (!mobileFabricConfiguration.isKonySDKObjectInitialized) {\n initializeMobileFabric(getSearchProducts, searchRecord);\n } else if (mobileFabricConfiguration.isKonySDKObjectInitialized) {\n getServiceResponse(operationName, inputParams, \"getting search Products result\", getCatProductsSuccessCallback);\n }\n } else {\n // The user didn't pick a value so we'll show the alert\n kony.ui.Alert({\n message: \"Please select a valid text \",\n alertType: constants.ALERT_TYPE_INFO,\n alertTitle: \"Categories\",\n yesLabel: \"OK\"\n }, {});\n }\n}", "function SearchByCategoty() {\n var catsFinder = \"\";\n $('#click-cat .category-content input[type=checkbox]:checked').each(function () {\n catsFinder += $(this).next().text().replaceAll(\" \", \"-\") + \",\";\n });\n catsFinder = catsFinder.slice(0, -1);\n const url = new URL(window.location);\n if (catsFinder != undefined)\n url.searchParams.set('catsFinder', catsFinder);\n else\n url.searchParams.delete('catsFinder', catsFinder);\n GetData(\"/Search/AllBussiness\" + url.search, \"AllBussiness\");\n window.history.replaceState({}, '', url);\n $(\"#click-cat\").modal('hide');\n $('.modal-backdrop').remove();\n findInUrlAndCheck();\n}", "search() {\n\n\t\tif (this.filter_term.length > 2) {\n\t\t\tthis.productsSvc.search(this.filter_term).then(data => this.refreshProducts(data));\n\t\t}\n\t}", "function search () {\n\n var params = {\n name: getProductName(),\n category_id: getSelectedCategoryId(),\n min_price: getMinPrice(),\n max_price: getMaxPrice()\n }\n\n params = $.extend({}, params);\n\n var url = getUrl();\n //var queryString = $.param(params);\n var queryString = buildQueryString(params);\n\n // Reload the page with the newly built query string\n window.location = url + '?' + queryString;\n }", "loadProductsBasedOnQuery() {\n let productsToShow;\n\n // load products default\n if (this.props.search === '' || this.props.search == undefined) {\n productsToShow = this.props.products.slice(0, this.props.perPage);\n } else {\n // check and return the product that's name or category contains the search query\n productsToShow = this.props.products.filter((element) => {\n let elementName = element.name.toLowerCase();\n let elementCategory = element.category.toLowerCase();\n return `${elementName}${elementCategory}`.includes(this.props.search)\n });\n\n if (productsToShow.length > (this.props.perPage)) {\n productsToShow = productsToShow.slice(0, this.props.perPage)\n }\n }\n\n return productsToShow;\n }", "function filterPopulatedSubCategories(){\n //generate all the subcategories the store products belong to\n \n let storeProductSubCat = []\n let populatedSubCats = []\n particularStoreProducts.forEach((e)=>{\n storeProductSubCat.push(e.product.subCategory)\n })\n\n //to display onlysubcategories that have products we compare\n subCategories.forEach((i)=>{\n if(storeProductSubCat.includes(i)){\n populatedSubCats.push(i)\n }\n })\n\n setPopulatedSubCategoryList(populatedSubCats)\n }", "searchCategories(searchText) \n {\n const result = CategoryModel.searchCategories({\n searchText: searchText\n });\n return result;\n }", "async filterByCategory({ commit, rootState }, payload) {\n commit(types.SET_CURRENT_PAGE, 1);\n let products = await axiosInstance(`/products/category/${payload}`);\n if (errorHandle(products)) {return}\n commit(types.SET_ALL_PRODUCTS, products);\n if (rootState.sortingvalue === \"asc\") {\n commit(types.SORT_PRODUCTS, \"asc\");\n } else if (rootState.sortingvalue === \"desc\") {\n commit(types.SORT_PRODUCTS, \"desc\");\n }\n let totalPageSection = paginate(products, pageSize);\n commit(types.SET_TOTAL_PAGE_SECTION, totalPageSection);\n commit(\n types.SET_SHOW_PRODUCTS,\n totalPageSection[rootState.currentPage - 1]\n );\n }", "function getSearchProducts(searchRecord){\n \n\tkony.print (\"########## Selected searchRecord:\" + JSON.stringify(searchRecord));\n\t// Let's first check that the user picked a valid value\n\tif (!kony.string.equalsIgnoreCase(searchRecord.searchText, \"none\"))\n {\n // Populating the input params for the service call and invoking the service\n var operationName = mobileFabricConfiguration.integrationServices[0].operations[2];\n var inputParams={\"key\":mobileFabricConfiguration.bestByAPIKey,\"searchText\":searchRecord.searchText,\"pageNo\":searchRecord.pageNo};\n \n if (!mobileFabricConfiguration.isKonySDKObjectInitialized)\n {\n\t\t\tinitializeMobileFabric(getSearchProducts,searchRecord);\n }\n else if (mobileFabricConfiguration.isKonySDKObjectInitialized)\n {\n getServiceResponse(operationName,inputParams,\"getting search Products result\",getCatProductsSuccessCallback);\n }\n\t}\n\telse{\n\t\t\t// The user didn't pick a value so we'll show the alert\n\t\t kony.ui.Alert({ message: \"Please select a valid text \",alertType:constants. ALERT_TYPE_INFO, alertTitle:\"Categories\",yesLabel:\"OK\"}, {});\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function anneal( ... ) args: get_proposal: proposed_cost = f(iter, epoch) set_proposal: f(is_accepted) num_iters, num_epochs params: .schedule: temperature = f(iter/num_iters)
function anneal( get_proposal, set_proposal, num_iters, num_epochs ) { if (!num_iters) num_iters = 100 if (!num_epochs) num_epochs = 1 // ensure first proposal always accepted var cost = Infinity // epochs (outer loop) for (let epoch = 0; epoch < num_epochs; epoch++) { // iterations (inner loop) for (let iter = 1; iter <= num_iters; iter++) { // get new proposal and corresponding cost const proposed_cost = get_proposal(iter, epoch) // compute probability of accepting proposal: // if cost decreases, prob > 1 and will always accept. // if cost increases, the greater the increase, the lower the accept probability. // the later the iteration, the larger the multiplier, causing to a lower "annealing temperature". // hence, the lower the probability of moving to a higher cost later on in the annealing process. const accept_probability = Math.exp((cost - proposed_cost) * anneal.schedule(iter / num_iters)) // if chance decides, accept proposal const random_probability = Math.random() const is_accepted = random_probability < accept_probability // update cost; set proposal as accepted/rejected if (is_accepted) cost = proposed_cost set_proposal(is_accepted) } } }
[ "function anneal() {\n let currentCost = computeCost(currentSolution);\n let candidate = swapRandom(currentSolution.slice());\n let candidateCost = computeCost(candidate);\n \n let delta = candidateCost - currentCost;\n let acceptDecrease = acceptance(delta);\n let is_better = true;\n if (delta < 0 || (acceptDecrease && delta !== 0)) {\n currentSolution = candidate;\n currentCost = candidateCost;\n if (delta > 0) {\n is_better = false;\n }\n }\n \n // update user interface, by no means vital to the algorithm\n notifyOverlayCanvas(currentSolution, is_better);\n notifyChart(currentCost, temperature)\n\n temperature *= relativeTemperatureRetention;\n}", "function SimulatedAnnealing() {\n\n\tthis.INITIAL_TEMPERATURE = 5000 ;\n\tthis.COOLING_STEPS = 5000 ;\n\tthis.COOLING_FRACTION = 0.95 ;\n\tthis.STEPS_PER_TEMP = 1000 ;\n\tthis.BOLTZMANNS=1.3806485279e-23; \n\n\tthis.anneal = function() {\t\n\n\t\tconsole.log( \"Annealing...\" ) ;\n\n\t\tvar temperature = this.INITIAL_TEMPERATURE;\n\t\tvar current_solution = this.initial_solution() ;\t\t\n\t\tvar current_cost = this.solution_cost( current_solution ) ;\n\t\tvar m = 0 ;\n\t\tvar n = 0 ;\n\t\tfor (var i=0; i<this.COOLING_STEPS; i++) {\n\t\t\tvar start_cost = current_cost ;\n\t\t\tfor (var j=0; j<this.STEPS_PER_TEMP; j++) {\n\t\t\t\tvar new_solution = this.random_transition( current_solution ) ;\n\t\t\t\tvar new_cost = this.solution_cost( new_solution ) ;\n\n\t\t\t\tif( new_cost < current_cost ) {\n\t\t\t\t\tcurrent_cost = new_cost ;\n\t\t\t\t\tcurrent_solution = new_solution ;\n\t\t\t\t} else {\n\t\t\t\t\tvar minus_delta = current_cost - new_cost ;\n\t\t\t\t\tvar merit = Math.exp( minus_delta / (this.BOLTZMANNS*temperature) ) ;\n\t\t\t\t\tif (merit > Math.random() ) {\n\t\t\t\t\t\tm++ ;\n\t\t\t\t\t\tcurrent_cost = new_cost ;\n\t\t\t\t\t\tcurrent_solution = new_solution ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tn++ ;\n\t\t\t\t// exit if we're not moving\n\t\t\t\tif( start_cost === current_cost ) { break ; }\n\t\t\t}\n\t\t\ttemperature *= this.COOLING_FRACTION;\n\t\t} \n\t\tconsole.log( \"Iterations:\", n, \"using\", m, \"jumps.\" ) ;\n\t\treturn current_solution ;\n\t} ; \n}", "async function execute () {\r\n // no hidden layers...\r\n var network = new Network(2,1);\r\n\r\n // XOR dataset\r\n var trainingSet = [\r\n { input: [0,0], output: [0] },\r\n { input: [0,1], output: [1] },\r\n { input: [1,0], output: [1] },\r\n { input: [1,1], output: [0] }\r\n ];\r\n\r\n await network.evolve(trainingSet, {\r\n mutation: methods.mutation.FFW,\r\n equal: true,\r\n error: 0.0000005,\r\n elitism: 5,\r\n mutation_rate: 0.5,\r\n // cost: () => {\r\n // console.warn('The custom error function is running!!!!');\r\n // return 0;\r\n // }\r\n // cost: (targets, outputs) => {\r\n // const error = outputs.reduce(function(total, value, index) {\r\n // return total += Math.pow(targets[index] - outputs[index], 2);\r\n // }, 0);\r\n //\r\n // return error / outputs.length;\r\n // }\r\n cost: (targets, outputs) => {\r\n const error = outputs.reduce(function(total, value, index) {\r\n return total += Math.abs(value);\r\n }, 0);\r\n\r\n return error / outputs.length;\r\n }\r\n });\r\n\r\n // and it works!\r\n console.log(network.activate([0,0])); // 0.2413\r\n console.log(network.activate([0,1])); // 1.0000\r\n console.log(network.activate([1,0])); // 0.7663\r\n console.log(network.activate([1,1])); // 0.008\r\n}", "closure(input, config, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {\n if (LexerATNSimulator.debug) {\n console.log(\"closure(\" + config.toString(this.recog, true) + \")\");\n }\n if (config.state instanceof RuleStopState_1.RuleStopState) {\n if (LexerATNSimulator.debug) {\n if (this.recog != null) {\n console.log(`closure at ${this.recog.ruleNames[config.state.ruleIndex]} rule stop ${config}`);\n }\n else {\n console.log(`closure at rule stop ${config}`);\n }\n }\n let context = config.context;\n if (context.isEmpty) {\n configs.add(config);\n return true;\n }\n else if (context.hasEmpty) {\n configs.add(config.transform(config.state, true, PredictionContext_1.PredictionContext.EMPTY_FULL));\n currentAltReachedAcceptState = true;\n }\n for (let i = 0; i < context.size; i++) {\n let returnStateNumber = context.getReturnState(i);\n if (returnStateNumber === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) {\n continue;\n }\n let newContext = context.getParent(i); // \"pop\" return state\n let returnState = this.atn.states[returnStateNumber];\n let c = config.transform(returnState, false, newContext);\n currentAltReachedAcceptState = this.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n }\n return currentAltReachedAcceptState;\n }\n // optimization\n if (!config.state.onlyHasEpsilonTransitions) {\n if (!currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision) {\n configs.add(config);\n }\n }\n let p = config.state;\n for (let i = 0; i < p.numberOfOptimizedTransitions; i++) {\n let t = p.getOptimizedTransition(i);\n let c = this.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon);\n if (c != null) {\n currentAltReachedAcceptState = this.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\n }\n }\n return currentAltReachedAcceptState;\n }", "closure(input, config, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon) {\r\n if (LexerATNSimulator.debug) {\r\n console.log(\"closure(\" + config.toString(this.recog, true) + \")\");\r\n }\r\n if (config.state instanceof RuleStopState_1.RuleStopState) {\r\n if (LexerATNSimulator.debug) {\r\n if (this.recog != null) {\r\n console.log(`closure at ${this.recog.ruleNames[config.state.ruleIndex]} rule stop ${config}`);\r\n }\r\n else {\r\n console.log(`closure at rule stop ${config}`);\r\n }\r\n }\r\n let context = config.context;\r\n if (context.isEmpty) {\r\n configs.add(config);\r\n return true;\r\n }\r\n else if (context.hasEmpty) {\r\n configs.add(config.transform(config.state, true, PredictionContext_1.PredictionContext.EMPTY_FULL));\r\n currentAltReachedAcceptState = true;\r\n }\r\n for (let i = 0; i < context.size; i++) {\r\n let returnStateNumber = context.getReturnState(i);\r\n if (returnStateNumber === PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY) {\r\n continue;\r\n }\r\n let newContext = context.getParent(i); // \"pop\" return state\r\n let returnState = this.atn.states[returnStateNumber];\r\n let c = config.transform(returnState, false, newContext);\r\n currentAltReachedAcceptState = this.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\r\n }\r\n return currentAltReachedAcceptState;\r\n }\r\n // optimization\r\n if (!config.state.onlyHasEpsilonTransitions) {\r\n if (!currentAltReachedAcceptState || !config.hasPassedThroughNonGreedyDecision) {\r\n configs.add(config);\r\n }\r\n }\r\n let p = config.state;\r\n for (let i = 0; i < p.numberOfOptimizedTransitions; i++) {\r\n let t = p.getOptimizedTransition(i);\r\n let c = this.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon);\r\n if (c != null) {\r\n currentAltReachedAcceptState = this.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon);\r\n }\r\n }\r\n return currentAltReachedAcceptState;\r\n }", "iteration() {\n EncogLog.info(\"Performing Simulated Annealing iteration.\");\n\n this.preIteration();\n this.anneal.iteration();\n this.error = this.calculateScore();\n this.postIteration();\n }", "set learningRate (alpha) {\n this.params.learning_rate = alpha\n }", "evaluateIndividual(index) {\n let inputs = [];\n for (var i in this.population[index].trainingData) {\n inputs.push(this.population[index].trainingData[i]);\n }\n let outputs = neat.population[index].activate(inputs);\n //evaluate neat and get its outputs here\n this.step(this.population[index], outputs);\n return score;\n }", "function train() {    \n for (var i = 0; i < trainingData.length; i++) {        \n input.activate(trainingData[i][\"input\"]);        \n output.activate();        \n output.propagate(learningRate, trainingData[i][\"output\"]);    \n }\n}", "function train(data){\r\n initInputAndObjective(data);\r\n propagate();\r\n backpropagate();\r\n}", "function whileTrainingamzn(epoch, loss) {\r\n console.log(epoch);\r\n}", "learn() {\n // alphaNearestFood [-pi, pi]\n let out = this.net.feedForward(nj.array([[this.alphaNearestFood]]))\n this.alpha += out.get(0, 0)\n this.alpha = degToRad((radToDeg(this.alpha)) % 360)\n this.v += out.get(0, 1)\n this.v = this.v > config.mouseMaxSpeed ? config.mouseMaxSpeed : this.v\n this.v = this.v < config.mouseMinSpeed ? config.mouseMinSpeed : this.v\n }", "function act () \r\n{\r\n fann.create_standard_array( parseInt( num_layers ), layers );\r\n\r\n\r\n fann.set_training_algorithm( 2 );\r\n fann.set_learning_momentum(0.1)\r\n\r\n fann.set_activation_function_hidden( 13 );\r\n fann.set_activation_function_output( 5 );\t// FANN_SIGMOID_STEPWISE\t\r\n \r\n fann.train_on_data( train_data, 100, 50, 0.01 );\r\n var MSE = fann.get_MSE();\r\n var result = fann.run( testdata );\r\n\r\n/************************\r\n console.log( 'training algorithm function : ', training_algorithm_list[train_algo] )\r\n console.log( ' activation_function : ', activation_function_list[i] )\r\n console.log( ' activation_function : ', activation_function_list[j] )\r\n*******************/\r\n console.log( ' num_layers = ', num_layers) ;\r\n console.log( ' num_neurons_hidden = ', num_neurons_hidden );\r\n console.log( ' desired_error = ', desired_error );\r\n console.log( ' MSE : ', MSE );\r\n console.log( ' result : ', result );\r\n\r\n if( parseFloat(MSE) < 0.1 )\r\n {\r\n console.log( ' --- save ann model --- ' );\r\n fann.save('./bmw_'+ activation_function_list[i] + '.net');\r\n }\r\n console.log( );\r\n\r\n fann.destroy();\r\n\r\n\r\n}", "giveFeedback(feedback) {\n // Just because this means it doesn't have any experience at all!\n // Ya can't learn from feedback if you haven't done anything!\n if (this.experienceSinceFeedback.length == 0) return;\n\n //-------------------------------------------------------------------------------------------------\n // Update some variables.\n\n this.targetNetwork.neuronActivation = this.neuronActivation;\n this.targetNetwork.ouputNeuronActivation = this.ouputNeuronActivation;\n\n if (this.averageFeedback === undefined) {\n this.averageFeedback = feedback;\n }\n else {\n this.averageFeedback = this.averageFeedback * this.averageFeedbackDecay + feedback * (1 - this.averageFeedbackDecay);\n }\n\n //-------------------------------------------------------------------------------------------------\n // Create learning batch.\n\n let learningBatch = [];\n for (let a = 0; a < Math.min(this.experience[this.experience.length - 1].length, this.maxLearningBatchSize); a++) {\n let selectedExperience;\n let randomValue = Math.floor(Math.random() * this.experience[0][0]);\n let index = [0, 0];\n let left, right;\n while (selectedExperience == undefined) {\n index = [index[0] + 1, index[1] * 2];\n left = this.experience[index[0]][index[1]];\n if (this.experience[index[0]].length > index[1] + 1) {\n right = this.experience[index[0]][index[1] + 1];\n }\n\n if (typeof left == \"object\") {\n if (randomValue <= left.priority) {\n selectedExperience = left;\n }\n else {\n selectedExperience = right;\n }\n }\n else {\n if (randomValue > left) {\n randomValue -= left;\n index[1]++;\n }\n }\n }\n selectedExperience.targetQ = this.getTargetQ(selectedExperience);\n learningBatch.push(selectedExperience);\n }\n\n //-------------------------------------------------------------------------------------------------\n // Set target Qs for the new experiences, add them to the \n // learning batch and give feedback to the newest experience\n\n for (let a = this.experienceSinceFeedback.length - 2; a >= 0; a--) {\n this.experienceSinceFeedback[a].state_1 = this.experienceSinceFeedback[a + 1].state_0;\n this.experienceSinceFeedback[a].targetQ = this.getTargetQ(this.experienceSinceFeedback[a]);\n learningBatch.push(this.experienceSinceFeedback[a]);\n }\n this.experienceSinceFeedback.splice(0, this.experienceSinceFeedback.length - 1);\n this.experienceSinceFeedback[0].feedback = feedback;\n\n //-------------------------------------------------------------------------------------------------\n // Learn from these experiences by doing backpropagation\n // and gradient descent with experience.targetQ as target\n // output for the action in that experience.\n\n this.resetLossSlopes();\n let experience, neuron;\n for (let i_experience = 0; i_experience < learningBatch.length; i_experience++) {\n experience = learningBatch[i_experience];\n\n this.forwardPropagate(experience.state_0);\n\n for (let i_neuronLayer = this.neurons.length - 1; i_neuronLayer > 0; i_neuronLayer--) {\n for (let i_neuron = 0; i_neuron < this.neurons[i_neuronLayer].length; i_neuron++) {\n neuron = this.neurons[i_neuronLayer][i_neuron];\n\n if (i_neuronLayer == this.neurons.length - 1) {\n if (i_neuron == experience.action) {\n neuron.lossSlope = neuron.output - experience.targetQ;\n\n if (experience.index == undefined) {\n experience.priority = Math.max(this.minExperiencePrioritization, Math.pow(Math.abs(neuron.lossSlope), this.experiencePrioritization));\n experience.index = this.experience[this.experience.length - 1].length;\n\n this.experience[this.experience.length - 1].push(experience);\n for (let a = this.experience.length - 1; a > 0; a--) {\n if (this.experience[a].length > this.experience[a - 1].length * 2) {\n this.experience[a - 1].push(experience.priority);\n }\n else {\n this.experience[a - 1][this.experience[a - 1].length - 1] += experience.priority;\n }\n }\n if (this.experience[0].length == 2) {\n this.experience.unshift([this.experience[0][0] + this.experience[0][1]]);\n }\n }\n else {\n let difference = Math.max(this.minExperiencePrioritization, Math.pow(Math.abs(neuron.lossSlope), this.experiencePrioritization)) - experience.priority;\n experience.priority += difference;\n\n let index = experience.index;\n for (let a = this.experience.length - 2; a >= 0; a--) {\n index = Math.floor(index * 0.5);\n this.experience[a][index] += difference;\n }\n }\n // neuron.lossSlope *= Neuralt.getActivationDerivative(neuron.output_beforeActivation, this.outputNeuronActivation);\n }\n else {\n neuron.lossSlope = 0;\n }\n }\n else {\n neuron.lossSlope = 0;\n for (let a = 0; a < this.neurons[i_neuronLayer + 1].length; a++) {\n neuron.lossSlope += this.neurons[i_neuronLayer + 1][a].parameters[i_neuron].value * this.neurons[i_neuronLayer + 1][a].lossSlope;\n }\n neuron.lossSlope *= Neuralt.getActivationDerivative(neuron.output_beforeActivation, this.neuronActivation);\n }\n\n for (let i_parameter = 0; i_parameter < neuron.parameters.length; i_parameter++) {\n if (i_parameter < neuron.parameters.length - 1) {\n neuron.parameters[i_parameter].lossSlope += this.neurons[i_neuronLayer - 1][i_parameter].output * neuron.lossSlope;\n }\n else {\n neuron.parameters[i_parameter].lossSlope += neuron.lossSlope;\n }\n\n if (i_experience == learningBatch.length - 1) {\n neuron.parameters[i_parameter].adjust();\n if (this.updateCount % this.targetNetworkUpdateFrequency == 0) {\n this.targetNetwork.neurons[i_neuronLayer][i_neuron].parameters[i_parameter].value = neuron.parameters[i_parameter].value;\n }\n }\n }\n }\n }\n }\n if (this.experience[this.experience.length - 1].length == (this.memoryLength << 1)) {\n for (let a = 1; a < this.experience.length; a++) {\n this.experience[a].splice(0, 1 << (a - 1));\n }\n for (let a = 0; a < this.experience[this.experience.length - 1].length; a++) {\n this.experience[this.experience.length - 1][a].index = a;\n }\n this.experience.splice(0, 1);\n }\n\n this.updateCount++;\n }", "_propogate(input) {\n\n\t\tlet cost= 1;\n\t\tconst MIN_COST= 0.1;\n\n\t\tfor(let i= 0; cost >= MIN_COST && i< this.maxIterationCount; i++) {\n\n\t\t\tconst prediction= this.predict(input);\n\n\t\t\t// Propogate backwards through the net and correct the weights\n\t\t\tcost= this._backwardPropogation(prediction);\n\n\t\t\tif(i%1000 === 0 || cost <= MIN_COST) {\n\t\t\t\tconsole.log('\\n+ SYNAPSE +\\n');\n\t\t\t\tthis.printSynapse();\n\t\t\t\tconsole.log('Cost: ', cost);\n\t\t\t\tconsole.log('\\n+ SYNAPSE +\\n');\n\t\t\t}\n\t\t}\n\n\t\tconsole.log('------');\n\t}", "train() {\n // it's possible that we'll never come across appropriate values for m and b\n for (let i = 0; i < this.options.iterations; i++) {\n this.gradientDescent()\n }\n }", "function act_function () \r\n{\r\n\r\n for( var train_algo = 0; train_algo < 5; train_algo++ )\r\n {\r\n for( var i = 2; i < 16; i++ )\r\n {\r\n\r\n for( var j = 2; j < 16; j++ )\r\n {\r\n fann.create_standard_array( parseInt( num_layers ), layers );\r\n\r\n\r\n fann.set_training_algorithm( train_algo );\r\n fann.set_learning_momentum(0.1)\r\n\r\n fann.set_activation_function_hidden( i );\r\n fann.set_activation_function_output( j );\t \r\n\t\r\n fann.set_activation_steepness_hidden( 0.1 );\r\n fann.set_activation_steepness_output( 0.2 );\r\n\r\n\r\n fann.train_on_data( train_data, 100, 50, 0.01 );\r\n var MSE = fann.get_MSE();\r\n var result = fann.run( testdata );\r\n\r\n console.log( Date() );\r\n console.log( 'training algorithm function : ', training_algorithm_list[train_algo] , ' ', train_algo)\r\n console.log( ' hidden activation_function : ', activation_function_list[i] , ' ', i )\r\n console.log( ' output activation_function : ', activation_function_list[j] , ' ', j )\r\n console.log( ' num_layers = ', num_layers) ;\r\n console.log( ' num_neurons_hidden = ', num_neurons_hidden );\r\n console.log( ' desired_error = ', desired_error );\r\n console.log( ' MSE : ', MSE );\r\n console.log( ' desiredResult : ', desiredResult );\r\n console.log( ' result : ', result );\r\n if( parseFloat(MSE) < 0.02 )\r\n {\r\n var error = parseFloat( result[0] ) - parseFloat( desiredResult[0] );\r\n if( Math.abs( error ) < 0.07 ) \r\n {\r\n console.log( ' ---- save ann model ---- ' );\r\n fann.save('./bmw_'+ activation_function_list[i] + '.net');\r\n }\r\n }\r\n console.log( );\r\n fann.destroy();\r\n \r\n } // j\r\n } // i\r\n } // train_algo\r\n}", "function training()\n{\n // Progress percentage on outlet 4\n if (t < trainingLength)\n {\n trainingStep(t, trainingLength, rStep, alpha, winTimeStamp);\n outlet(3, math.ceil(100 * (t / trainingLength)));\n t++;\n }\n else\n {\n post('Training done.\\n');\n findBestMatches();\n outputDataCoordinatesOnMap();\n // post(neurons + '\\n');\n arguments.callee.task.cancel();\n }\n}", "function train() {\n // gets net and training data\n var net = new brain.NeuralNetwork();\n var trainingDataRaw = fs.readFileSync('./excerpts.js');\n var trainingData = JSON.parse(trainingDataRaw);\n \n // gets a few excerpts\n var selectData = [];\n for (i = 0; i < 20; i++) {\n var next = trainingData[Math.floor((Math.random() * trainingData.length))];\n selectData.push(next);\n }\n // maps encoded training data\n selectData = compute(selectData);\n \n // trains network and returns it\n net.train(selectData, {\n log: true\n });\n \n return net;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this disables and grays out the demo portions except for loading a video
function DisableDemoExceptLoadVideo() { $(".grayNoVideo a, .grayNoVideo button, .grayNoVideo input, .grayNoVideo textarea").prop("disabled", true); $(".grayNoVideo, .grayNoVideo a").css("color", "rgb(153,153,153)"); }
[ "function EnableDemoAfterLoadVideo() {\r\n $(\".grayNoVideo, .grayNoVideo a\").removeAttr(\"style\");\r\n $(\".grayNoVideo a, .grayNoVideo button, .grayNoVideo input, .grayNoVideo textarea\").prop(\"disabled\", false);\r\n $(\"#pauseButton, #saveCaptionAndPlay, #justSaveCaption\").prop(\"disabled\", true); // these are still disabled\r\n $(\"#textCaptionEntry\").prop(\"readonly\", true);\r\n }", "function hidePlayerUi() {\r\n vidBar.style.background = '';\r\n vidPlayed.style.background = '';\r\n vidLoaded.style.background = '';\r\n }", "function hideVideoControl() {\n teaserCtrlTl.to(videoControl[0], 1, {opacity: 0});\n trailerCtrlTl.to(videoControl[1], 1, {opacity: 0});\n}", "static enableVideo() {\n Agora.enableVideo();\n }", "function showInitializationVideo() {\r\n $('#videoPlayerOverlay').hide();\r\n\r\n initializationVideoVisible = true;\r\n }", "configureVideoJS(){\n\t\t// Disable tracking\n\t\twindow.HELP_IMPROVE_VIDEOJS = false;\t\n\t}", "function hideVideoControl() {\n videoCtrlTl.to(videocontrol, 1, {opacity: 0});\n }", "function showContentUnderVideo()\n {\n \tvar cText = \"#\"+ $.boeSettings.nextPrefix + \"-text\",\n \t cBack=\"#\"+ $.boeSettings.nextPrefix+\"-bg\";\n \t$(cText).removeClass(\"makeinvisible\");\n \t$(cBack).removeClass(\"makeinvisible\");\n }", "function showVideoControl() {\n TweenLite.to(videocontrol, 1, {opacity: 1});\n }", "_stopLoader () {\n this._videoLoader.style.display = 'none'\n }", "defaultVideo(enable) {\n RNVoxeetConferencekit.defaultVideo(enable);\n return true;\n }", "function iframes () {\n hero.justHit = false\n}", "_idle_video() {\n\t\t\tthis.video_panel.attr('loop', true);\n\t\t\tthis.video_src.attr('src', this.resource_path + 'idle.mp4');\n\t\t}", "disable() {\n\n\t\tqueryAll( this.Reveal.getSlidesElement(), '.fragment' ).forEach( element => {\n\t\t\telement.classList.add( 'visible' );\n\t\t\telement.classList.remove( 'current-fragment' );\n\t\t} );\n\n\t}", "function launchVideo() {\r\n var mapAnim = $(\"#particles-js\");\r\n mapAnim.css(\"opacity\", 0);\r\n $(\".panel\").replaceWith(\"<div id='containerVideo'><div id='uiBox'><p id='uiTitle'>DATA DOWNLOAD : MONITORING</p> <div id='uiSubtitle'><p>ACCESSING CAMERAS : TIME SQUARE</p></div><div id='uiLoading'><div id='uiBar'></div><p id='uiCounter'>LOADING</p></div></div></div>\");\r\n videoAnimation();\r\n }", "function initBackgroundVideo() {\n\t\tif ($('.js-html-bg-video').length) {\n\t\t\t$('.js-html-bg-video').bgVideo({\n\t\t\t\tshowPausePlay: false,\n\t\t\t\tpauseAfter: 0\n\t\t\t});\n\t\t}\n\t}", "function showVideoPage() {\n $(\"#overlay\").hide(\"fade\");\n activity.notifyStage('Calibration', 'Finish');\n activity.notifyStage('Video', 'Start');\n }", "function onStopVideo(){\n\n\t\tif(g_objTopPanel){\n\t\t\tshowTopPanel();\n\t\t\thandlePanelHeight(\"onStopVideo\");\n\t\t}else{\n\t\t\t\n\t\t\tif(g_objNumbers)\n\t\t\t\tg_objNumbers.show();\n\t\t}\n\t\t\n\t\tif(g_objArrowLeft && g_options.lightbox_hide_arrows_onvideoplay == true){\n\t\t\tg_objArrowLeft.show();\n\t\t\tg_objArrowRight.show();\t\t\t\n\t\t}\n\t\t\n\t}", "function stopAndHideVideo(){\n ci.vid.pause()\n ci.ctx.clearRect(ci.vidX, ci.vidY, ci.vidW, ci.vidH)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
copy zIndex style from theme element to mover
function setZIndex() { if (vm.element.fullscreen) { vm.moverStyle['z-index'] = vm.themeStyle['z-index']; } else { vm.moverStyle['z-index'] = vm.themeStyle['z-index'] + 10; } }
[ "function\nBayRaiseZIndex\n(InBay)\n{\n InBay.style.zIndex = 30;\n}", "function zIndexControl(elem) {\n zIndexCount++;\n elem.css(\"z-index\", zIndexCount);\n}", "function\nBayLowerZIndex\n(InBay)\n{\n InBay.style.zIndex = 30;\n}", "updateZindexHandler () {\n this.style.zIndex = zIndex\n zIndex++\n }", "_moveElementToTop(el){\n el.style.zIndex = heighestZIndex+1;\n heighestZIndex += 1;\n }", "setLayerOrder() {\n const { index } = this.props;\n const zIndex = 600 - index * 10;\n\n if (this.pane) {\n this.pane.style.zIndex = zIndex;\n }\n\n if (this.areaPane) {\n this.areaPane.style.zIndex = zIndex - 1;\n }\n\n if (this.labelPane) {\n this.labelPane.style.zIndex = zIndex + 1;\n }\n }", "lower() {\n this.preview.style.zIndex = 0;\n }", "_setZIndex() {\n const totalModals = document.querySelectorAll('.modal.active').length + 1;\n\n this.options.overlay ? (this.overlayElement.style.zIndex = 800 + totalModals * 6) : '';\n this.el.style.zIndex = 800 + totalModals * 10;\n }", "setZ (element, howMuch) {\n $(element).css({\n 'z-index': howMuch\n })\n }", "function setZIndexValue() {\r\r\n var elements = $(\".element:not([sharedstimulusdiv='true'],[sharedstimulus='true'])\") /*$(\".element\")*/ ,\r\r\n id, ele;\r\r\n for (var index = 0; index < elements.length; index++) {\r\r\n ele = elements.eq(index);\r\r\n if (ele.parents(\"div.divbox[interactiontype=4]\").length == 0) {\r\r\n id = parseInt(ele.attr(\"id\").split(\"_\")[1], 10);\r\r\n ele.css(\"z-index\", id + 1);\r\r\n }\r\r\n }\r\r\n}", "bringToFront(){let zIndex='';const frontmost=OverlayElement.__attachedInstances.filter(o=>o!==this).pop();if(frontmost){const frontmostZIndex=frontmost.__zIndex;zIndex=frontmostZIndex+1;}this.style.zIndex=zIndex;this.__zIndex=zIndex||parseFloat(getComputedStyle(this).zIndex);}", "function setEltZIndex (elt, z) \n{ if (is.nav4) elt.zIndex = z;\n else if (elt.style) elt.style.zIndex = z;\n}", "function resetZindex(x) {\n x.style.zIndex = 10;\n}", "_updateZIndex() {\n HSystem.updateZIndexOfChildren(this.viewId);\n }", "updateZIndices()\n {\n for (let i = 0; i < this.windows.length; i++)\n {\n this.windows[i].element.style.zIndex = Z_INDEX_OFFSET + i\n }\n }", "set zIndex (index) {\n this._zIndex = index\n this.shadowRoot.querySelector('div.windowContainer').style.zIndex = this._zIndex\n }", "function updateZIndex(styles) {\n return angular.isString(styles)? styles.replace(/z-index/g,\"zIndex\") : styles;\n }", "function updateZindex(){\n\n // The CSS method can take a function as its second argument.\n // i is the zero-based index of the element.\n\n ul.find('li').css('z-index',function(i){\n return cnt-i;\n });\n }", "function setZindex(e) {\n\tif (e.id) {\n\t var elem = document.getElementById(e.id);\n\t if (elem) {\n\t\telem.style.zIndex = e.zIndex;\n\t };\n\t} else if (e.tagName) {\n\t var elems = document.getElementsByTagName(e.tagName); \n\t for (var i = 0; i < elems.length; i++) {\n\t\telems[0].style.zIndex = e.zIndex;\n\t };\n\t} else if (e.className) {\n\t var elems = document.getElementsByClassName(e.className); \n\t for (var i = 0; i < elems.length; i++) {\n\t\telems[0].style.zIndex = e.zIndex;\n\t };\n\t};\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove edge connect to this vertexs
removeAllEdgeConnectToVertex(vertex) { this.findEdgeRelateToVertex(vertex.id).forEach(edge=>{ edge.remove() }) }
[ "removeAllEdgeConnectToTheseVertex(lstVertex)\n\t{\n\t\tlstVertex.forEach(e=>{\n\t\t\tthis.findEdgeRelateToVertex(e.id).forEach(edge=>{\n\t\t\t\tedge.remove()\n\t\t\t})\n\t\t})\n\t}", "removeEdge(vertex1, vertex2) {\n this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(\n val => val !== vertex2\n );\n this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(\n val => val !== vertex1\n );\n }", "removeVertex(vertex) {\n for(let adj of vertex.adjacent) {\n adj.adjacent.delete(vertex);\n }\n this.nodes.delete(vertex);\n }", "removeVertex(vertex) {\n for(let node of vertex.adjacent){\n node.adjacent.delete(vertex);\n }\n vertex.adjacent.clear()\n this.nodes.delete(vertex);\n }", "removeEdge(v1, v2) {\n for (let node of this.nodes) {\n if (node === v1) {\n node.adjacent.delete(v2);\n }\n if (node === v2) {\n node.adjacent.delete(v1);\n }\n }\n }", "removingEdge(vertex1, vertex2) {\n this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(\n (v) => v !== vertex2\n );\n this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(\n (v) => v !== vertex1\n );\n }", "removeEdge(fromVertex, toVertex) {\r\n let index = fromVertex.edges.findIndex(v => v === toVertex);\r\n if (index >= 0) {\r\n fromVertex.edges.splice(index, 1);\r\n if (fromVertex.numberOfEdges === 0) {\r\n this.removeVertex(fromVertex.value);\r\n }\r\n }\r\n index = toVertex.edges.findIndex(v => v === fromVertex);\r\n if (index >= 0) {\r\n toVertex.edges.splice(index, 1);\r\n if (toVertex.numberOfEdges === 0) {\r\n this.removeVertex(toVertex.value);\r\n }\r\n }\r\n }", "removeVertex(vertex) { \n for (let node of this.nodes) {\n if (node.adjacent.has(vertex)) {\n node.adjacent.delete(vertex);\n }\n }\n this.nodes.delete(vertex);\n }", "disconnect() {\n if (this.from) {\n this.from.detachEdge(this);\n this.from = undefined;\n }\n if (this.to) {\n this.to.detachEdge(this);\n this.to = undefined;\n }\n\n this.connected = false;\n }", "disconnect() {\n if (this.from) {\n this.from.detachEdge(this);\n this.from = undefined;\n }\n if (this.to) {\n this.to.detachEdge(this);\n this.to = undefined;\n }\n\n this.connected = false;\n }", "removeEdge(v1, v2) {\n v1.adjacent.delete(v2);\n v2.adjacent.delete(v1);\n }", "removeVertex(vertex) {\n for (let node of this.nodes) {\n if (node.adjacent.has(vertex)) {\n node.adjacent.delete(vertex);\n }\n }\n this.nodes.delete(vertex);\n }", "removeEdge(g, e) { }", "removeVertex(vertex) {\n for (let v of vertex.adjacent) {\n this.removeEdge(vertex, v);\n };\n this.nodes.delete(vertex)\n }", "clearEdges() {\n\t\tfor (let [from, to] of this.edges()) { this.removeEdge(from, to) }\n\t}", "removeVertex(vertex) {\n this.nodes.delete(vertex);\n vertex.adjacent.forEach(node => node.adjacent.delete(vertex));\n // for(let node of this.nodes) {\n // node.adjacent.delete(vertex);\n // }\n }", "removeEdge(v1, v2) {\r\n // ignoring input validation and checks for simplicity\r\n this.adjacencyList[v1] = this.adjacencyList[v1].filter(v => v !== v2);\r\n this.adjacencyList[v2] = this.adjacencyList[v2].filter(v => v !== v1);\r\n }", "removeEdge(v, w) {\n let vertex = this.AdjList.get(v);\n for(var i=0; i< vertex.length; i++) {\n if(vertex[i] === w) {\n vertex.splice(i, 1);\n }\n }\n //because this is an undirected graph we remove both v to w and w to v\n let vertex1 = this.AdjList.get(w);\n for(var i=0; i< vertex1.length; i++) {\n if(vertex1[i] === v) {\n vertex1.splice(i, 1);\n }\n }\n }", "removeEdge(g,e){\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A cell's children must be "block"s. If they're not then we wrap them within a block with a type of opts.typeContent
function onlyBlocksInCell(opts: Options, editor: Editor, error: SlateError) { const block = Block.create({ type: opts.typeContent }); editor.insertNodeByKey(error.node.key, 0, block); const inlines = error.node.nodes.filter(node => node.object !== 'block'); inlines.forEach((inline, index) => { editor.moveNodeByKey(inline.key, block.key, index); }); }
[ "function onlyBlocksInCell(opts, change, context) {\n var block = _slate.Block.create({\n type: opts.typeContent\n });\n change.insertNodeByKey(context.node.key, 0, block, { normalize: false });\n\n var inlines = context.node.nodes.filter(function (node) {\n return node.object !== 'block';\n });\n inlines.forEach(function (inline, index) {\n change.moveNodeByKey(inline.key, block.key, index, {\n normalize: false\n });\n });\n}", "function wrapContent() {\n canvas.find('.column').each(function() {\n var col = $(this);\n var contents = $();\n col.children().each(function() {\n var child = $(this);\n if (child.is('.row, .ge-tools-drawer, .ge-content')) {\n doWrap(contents);\n } else {\n contents = contents.add(child);\n }\n });\n doWrap(contents);\n });\n }", "function isBlockContent(node) {\n return (Paragraph_1.isParagraph(node) ||\n Heading_1.isHeading(node) ||\n ThematicBreak_1.isThematicBreak(node) ||\n Blockquote_1.isBlockquote(node) ||\n List_1.isList(node) ||\n Table_1.isTable(node) ||\n HTML_1.isHTML(node) ||\n Code_1.isCode(node));\n}", "function blockifier_cheerio($, global_block_list, parent, node){ \n if(node.type == \"text\"){\n parent.text += node.data\n return;\n }\n else if (node.type == \"tag\" || node.type == \"root\"){\n if (BLOCK_TAGS.has(node.tagName)){\n let new_block = new Block(node, parent)\n global_block_list.push(new_block)\n $(node).contents().each((i, e) => {\n blockifier_cheerio($, global_block_list, new_block, e)\n })\n parent.children.push(new_block)\n }\n else{\n parent.tags.push(node)\n $(node).contents().each((i, e) => {\n blockifier_cheerio($, global_block_list, parent, e)\n })\n }\n }\n}", "function wrapChildrenInDefaultBlock(opts, change, node) {\n change.wrapBlockByKey(node.nodes.first().key, opts.typeDefault, {\n normalize: false\n });\n\n var wrapper = change.value.document.getDescendant(node.key).nodes.first();\n\n // Add in the remaining items\n node.nodes.rest().forEach(function (child, index) {\n return change.moveNodeByKey(child.key, wrapper.key, index + 1, {\n normalize: false\n });\n });\n\n return change;\n}", "function wrapChildrenInDefaultBlock(opts, change, node) {\n change.wrapBlockByKey(node.nodes.first().key, opts.typeDefault, {\n normalize: false\n });\n\n var wrapper = change.value.document.getDescendant(node.key).nodes.first();\n\n // Add in the remaining items\n node.nodes.rest().forEach(function (child, index) {\n return change.moveNodeByKey(child.key, wrapper.key, index + 1, {\n normalize: false\n });\n });\n\n return change;\n}", "recursiveLayout(current, first, parentTagName) {\n\n if (!current) {\n return;\n }\n let locationInLayout = current.locationInLayout;\n\n // Ignore html, head, body\n const blockTypesToIgnore = {\n 'html': true,\n 'head': true,\n 'body': true\n };\n\n // the overall block doesn't have anything in it, but its 0th child is the HTML root.\n if (first === true) {\n if (current.children !== undefined && current.children[0] !== undefined) {\n current = current.children[0];\n first = 0;\n } else {\n return;\n }\n }\n\n // Will contain the block's contents\n let b = (<span></span>);\n\n // Label for the block\n let blockname = this.state.bricksByName[current.blocktype];\n\n let that = this;\n\n // If the current child's block type is an unallowed child of the parent's block type\n let badStyleClass = ''; // Red outline box\n let badStyleMessage = ''; // \"Oh no! [blocktype] shouldn't be placed inside [parent blocktype]'\n\n if (parentTagName !== undefined) {\n if (that.state.bricksByName[parentTagName].unallowed_children.includes(current.blocktype)) {\n badStyleClass = 'bad-style-block';\n badStyleMessage = 'Oh no! \"' + current.blocktype + '\"' + \" shouldn't be placed inside \" + '\"' + parentTagName + '\"!';\n }\n }\n\n // Copy children since we're modifying it\n let currentChildren = Object.assign({}, current.children);\n\n if (blockname != undefined &&\n (blockname.type == 'wrapper' || blockname.type == 'textwrapper')) {\n\n // After all children, the last slot is a slot that doesn't do any recursion, but allows blocks to be inserted here\n if (current.blocktype !== 'html') {\n currentChildren[Object.keys(currentChildren).length] = {\n 'emptySlot': true\n };\n }\n\n let kids = Object.keys(currentChildren);\n\n // Has children\n for (let i = 0; i < kids.length; i++) {\n let child = currentChildren[kids[i]];\n\n if (blockTypesToIgnore[child.blocktype] !== true) {\n // Place a dropspace before each child\n let index = i;\n b = (<span>\n {b}\n <ExistingDropSlot handle={function () { that.moveBlock(current.id, index, locationInLayout) }}>\n <DropSlot handle={function () { that.drop(current.id, index, locationInLayout) }}>\n <div className=\"drop-slot-space\">\n &nbsp;\n </div>\n </DropSlot>\n </ExistingDropSlot>\n {child.emptySlot !== true &&\n this.recursiveLayout(child, i, current.blocktype)\n }\n </span>);\n } else {\n b = (<span>{b}{this.recursiveLayout(child, i, current.blocktype)}</span>);\n }\n }\n }\n\n if (blockname !== undefined && blockname.type === \"content\") {\n let content = current.children;\n //console.log(\"current content: \" + JSON.stringify(content));\n b = (<span></span>);\n }\n\n var blockclass;\n if (blockname !== undefined) {\n //console.log(blockname.type);\n if (blockname.type == 'wrapper') {\n blockclass = 'primary-brick layout-block';\n }\n if (blockname.type == 'text-content' || blockname.type == 'image') {\n blockclass = 'secondary-brick layout-block';\n }\n if (blockname.type == 'textwrapper') {\n blockclass = 'third-brick layout-block';\n }\n }\n if (current.blocktype !== 'text-content') {\n let startTag = '<' + current.blocktype + '>';// + current.id;\n let endTag = '</' + current.blocktype + '>';\n\n if (current.blocktype === 'img' || that.state.bricksByName[current.blocktype] !== undefined && that.state.bricksByName[current.blocktype].self_closing === true) {\n startTag = '<' + current.blocktype + ' />';\n endTag = '';\n }\n\n\n if (current.blocktype === undefined) {\n setTimeout(function () {\n that.makeLayout();\n }, 300);\n return;\n }\n\n let isHeadBodyTitleOrHtml = (['head', 'body', 'title', 'html'].includes(current.blocktype));\n\n //console.log(current);\n\n function showStyles() {\n let block = document.getElementById(\"img-\" + current.id);\n block.classList.remove('edit-img-hidden');\n }\n\n function hideStyles() {\n let block = document.getElementById(\"img-\" + current.id);\n block.classList.add('edit-img-hidden')\n }\n\n b = (\n <ul className=\"layout-block\">\n <li className={blockclass + ' ' + badStyleClass} id={'layoutBlock_' + current.id}>\n\n {/* <div className=\"disable-select tag-block-span\" onDoubleClick={function (e) { let curcontent = current; that.cssModalToggleOn(curcontent) }}>\n <div className=\"bad-style\">{badStyleMessage}</div>\n {startTag}\n </div> */}\n\n <div className=\"bad-style\">{badStyleMessage}</div>\n <div className=\"disable-select tag-block-span\" onMouseOver={showStyles} onMouseLeave={hideStyles} onDoubleClick={function (e) { let curcontent = current; that.cssModalToggleOn(curcontent) }}>\n\n <div className=\"start-tag\">{startTag}</div>\n <img src={editimg} id={\"img-\" + current.id} className=\"edit-img edit-img-hidden\" draggable=\"false\" onClick={function (e) { let curcontent = current; that.cssModalToggleOn(curcontent) }} />\n\n </div>\n {((!isHeadBodyTitleOrHtml || current.blocktype === 'title') && Object.keys(current.children).length === 0 && (current.blocktype === 'li' || that.state.bricksByName[current.blocktype].type === 'textwrapper')) &&\n <button className=\"black-text\" onClick={function (e) { e.stopPropagation(); that.createBlock('text-content', current.id, 0, false, true); }}>Write...</button>\n }\n {b}\n {(current.blocktype === 'ul' || current.blocktype === 'ol') &&\n <button className=\"black-text\" onClick={function (e) { e.stopPropagation(); that.createBlock('li', current.id, Object.keys(current.children).length, false, true); }}>Add &lt;li&gt;</button>\n }\n {endTag.length > 0 &&\n <div className=\"disable-select tag-block-span\" onDoubleClick={function (e) { let curcontent = current; that.cssModalToggleOn(curcontent) }}>\n {endTag}\n </div>\n }\n </li>\n </ul>\n );\n\n if (!isHeadBodyTitleOrHtml) {\n b = (\n <ExistingBlock id={current.id} handle={function (id) { that.pickupBlock(id, current.parentid, current.index, locationInLayout) }}>\n {b}\n </ExistingBlock>\n );\n }\n }\n else {\n let text = '';\n if (current.textContent !== undefined) {\n text = current.textContent;\n }\n if (current.children[0] !== undefined) {\n text = current.children[0];\n }\n\n // Expand block to show all text and allow user to type\n function expandEditText(blockId, newText) {\n let blockShow = document.getElementById('expanded-edit-text-' + blockId);\n let blockHide = document.getElementById('collapsed-edit-text-' + blockId);\n blockHide.classList.add('hidden')\n blockShow.classList.remove('hidden');\n }\n // Collapse text to be what it was before\n function collapseEditText(blockId, newText) {\n let blockHide = document.getElementById('expanded-edit-text-' + blockId);\n let blockShow = document.getElementById('collapsed-edit-text-' + blockId);\n if (newText) {\n document.getElementById('input-preview-edit-text-' + blockId).value = newText;\n }\n blockHide.classList.add('hidden')\n blockShow.classList.remove('hidden');\n }\n\n let cIndex = current.index;\n\n // Change text of block in database\n function saveEditedText(blockId) {\n let expandedDiv = document.getElementById('expanded-edit-text-' + blockId)\n let value = document.getElementById('input-edit-text-' + blockId);\n\n // Make sure the block's input area exists (value), and the expanded div is not hidden\n if (!value || expandedDiv.classList.contains('hidden')) {\n return;\n }\n\n that.lockEditor();\n\n value = value.value;\n\n console.log(value);\n if (value.length > 1000) {\n return;\n }\n // sanitize this?\n collapseEditText(blockId, value);\n\n that.changeTextContent(blockId, value)\n\n\n }\n\n let currentId = current.id;\n\n b = (\n\n <div>\n <ul className=\"layout-block\">\n <ExistingBlock id={currentId} handle={function (id) { that.pickupBlock(id, current.parentid, current.index, locationInLayout) }}>\n <li className={blockclass} id={'layoutBlock_' + current.id}>\n {b}\n {/* Collapsed div */}\n <div id={'collapsed-edit-text-' + currentId}>\n <input type=\"text\" id={'input-preview-edit-text-' + currentId} readOnly value={text} title=\"Click to change text\" className=\"editor-text-content\"\n onClick={function () {\n expandEditText(currentId);\n that.setState({\n forbidDrag: true\n });\n }} />\n </div>\n </li>\n </ExistingBlock>\n </ul>\n {/* Expanded div */}\n <OutsideAlerter handler={() => saveEditedText(currentId)}>\n <div id={'expanded-edit-text-' + currentId} className=\"hidden text-expanded-container\">\n <textarea rows=\"4\" cols=\"20\" maxLength=\"900\" className=\"editor-text-content editor-text-expanded\" id={'input-edit-text-' + currentId} defaultValue={text} />\n\n {/* Save edited text to DB*/}\n <div className=\"edit-text-button btn-success\" onClick={function () {\n saveEditedText(currentId);\n that.setState({\n forbidDrag: false\n });\n }}>Save</div>\n\n {/* Cancel editing text */}\n <div className=\"edit-text-button btn-danger\" onClick={function () {\n collapseEditText(currentId);\n that.setState({\n forbidDrag: false\n });\n }}>Cancel</div>\n\n </div>\n </OutsideAlerter>\n </div>\n );\n }\n return b;\n }", "isBlock() {\n const parentNode = this.parentNode\n return (parentNode && parentNode.isContainer())\n }", "function createchildblock(title, content) {\n return [{\n object: 'block',\n type: 'heading_2',\n heading_2: {\n text: [\n {\n type: 'text',\n text: {\n content: title\n }\n },\n ],\n },\n },\n {\n object: 'block',\n type: 'paragraph',\n paragraph: {\n text:\n content,\n },\n }]\n}", "function setBlockType(nodeType, attrs) {\n return function (state, dispatch) {\n var ref = state.selection;\n var from = ref.from;\n var to = ref.to;\n var applicable = false;\n state.doc.nodesBetween(from, to, function (node, pos) {\n if (applicable) {\n return false;\n }\n\n if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) {\n return;\n }\n\n if (node.type == nodeType) {\n applicable = true;\n } else {\n var $pos = state.doc.resolve(pos),\n index = $pos.index();\n applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);\n }\n });\n\n if (!applicable) {\n return false;\n }\n\n if (dispatch) {\n dispatch(state.tr.setBlockType(from, to, nodeType, attrs).scrollIntoView());\n }\n\n return true;\n };\n}", "function wrapInList(opts, change, type, data) {\n var selectedBlocks = getHighestSelectedBlocks(change.value);\n type = type || opts.types[0];\n\n // Wrap in container\n change.wrapBlock({\n type: type,\n data: _slate.Data.create(data)\n }, { normalize: false });\n\n // Wrap in list items\n selectedBlocks.forEach(function (node) {\n if ((0, _utils.isList)(opts, node)) {\n // Merge its items with the created list\n node.nodes.forEach(function (_ref) {\n var key = _ref.key;\n return change.unwrapNodeByKey(key, { normalize: false });\n });\n } else {\n change.wrapBlockByKey(node.key, opts.typeItem, {\n normalize: false\n });\n }\n });\n\n return change;\n}", "function wrapInList(opts, change, type, data) {\n var selectedBlocks = getHighestSelectedBlocks(change.value);\n type = type || opts.types[0];\n\n // Wrap in container\n change.wrapBlock({\n type: type,\n data: _slate.Data.create(data)\n }, { normalize: false });\n\n // Wrap in list items\n selectedBlocks.forEach(function (node) {\n if ((0, _utils.isList)(opts, node)) {\n // Merge its items with the created list\n node.nodes.forEach(function (_ref) {\n var key = _ref.key;\n return change.unwrapNodeByKey(key, { normalize: false });\n });\n } else {\n change.wrapBlockByKey(node.key, opts.typeItem, {\n normalize: false\n });\n }\n });\n\n return change.normalize();\n}", "function wrapInList(opts, change, type, data) {\n var selectedBlocks = getHighestSelectedBlocks(change.value);\n type = type || opts.types[0];\n\n // Wrap in container\n change.wrapBlock({\n type: type,\n data: _slate.Data.create(data)\n }, { normalize: false });\n\n // Wrap in list items\n selectedBlocks.forEach(function (node) {\n if ((0, _utils.isList)(opts, node)) {\n // Merge its items with the created list\n node.nodes.forEach(function (_ref) {\n var key = _ref.key;\n return change.unwrapNodeByKey(key, { normalize: false });\n });\n } else {\n change.wrapBlockByKey(node.key, opts.typeItem, {\n normalize: false\n });\n }\n });\n\n return change.normalize();\n}", "function wrapChildNodes(parentNode) {\n var groups = Array.prototype.reduce.call(parentNode.childNodes, function (accumulator, binChildNode) {\n var group = last(accumulator);\n if (! group) {\n startNewGroup();\n } else {\n var isBlockGroup = isBlockElement(group[0]);\n if (isBlockGroup === isBlockElement(binChildNode)) {\n group.push(binChildNode);\n } else {\n startNewGroup();\n }\n }\n\n return accumulator;\n\n function startNewGroup() {\n var newGroup = [binChildNode];\n accumulator.push(newGroup);\n }\n }, []);\n\n var consecutiveInlineElementsAndTextNodes = groups.filter(function (group) {\n var isBlockGroup = isBlockElement(group[0]);\n return ! isBlockGroup;\n });\n\n consecutiveInlineElementsAndTextNodes.forEach(function (nodes) {\n var pElement = scribe.targetWindow.document.createElement('p');\n nodes[0].parentNode.insertBefore(pElement, nodes[0]);\n nodes.forEach(function (node) {\n pElement.appendChild(node);\n });\n });\n\n parentNode._isWrapped = true;\n }", "serialize(obj, children) {\n if (obj.object === 'block') {\n switch (obj.type) {\n case 'paragraph':\n return <p className={obj.data.get('className')}>{children}</p>;\n case 'quote':\n return <blockquote>{children}</blockquote>;\n case 'code':\n return (\n <pre>\n <code>{children}</code>\n </pre>\n );\n default:\n throw new Error('block serialize: obj type not valid');\n }\n }\n }", "function createBlock(type,props,children,patchFlag,dynamicProps){return setupBlock(createVNode(type,props,children,patchFlag,dynamicProps,true/* isBlock: prevent a block from tracking itself */));}", "_unwrapBlockInTable() {\n const blocks = domUtils.findAll(this.wwe.getBody(), 'td div,th div,tr>br,td>br,th>br');\n\n blocks.forEach(node => {\n if (domUtils.getNodeName(node) === 'BR') {\n const parentNodeName = domUtils.getNodeName(node.parentNode);\n const isInTableCell = /TD|TH/.test(parentNodeName);\n const isEmptyTableCell = node.parentNode.textContent.length === 0;\n const isLastBR = node.parentNode.lastChild === node;\n\n if (parentNodeName === 'TR' || (isInTableCell && !isEmptyTableCell && isLastBR)) {\n domUtils.remove(node);\n }\n } else {\n domUtils.unwrap(node);\n }\n });\n }", "function createBlock(type, props, children, patchFlag, dynamicProps) {\n const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true\n /* isBlock: prevent a block from tracking itself */\n ); // save current block children on the block vnode\n\n vnode.dynamicChildren = currentBlock || EMPTY_ARR; // close block\n\n closeBlock(); // a block is always going to be patched, so track it as a child of its\n // parent block\n\n if (currentBlock) {\n currentBlock.push(vnode);\n }\n\n return vnode;\n}", "function createBlock(type,props,children,patchFlag,dynamicProps){var vnode=createVNode(type,props,children,patchFlag,dynamicProps,true/* isBlock: prevent a block from tracking itself */);// save current block children on the block vnode\nvnode.dynamicChildren=currentBlock||EMPTY_ARR;// close block\ncloseBlock();// a block is always going to be patched, so track it as a child of its\n// parent block\nif(shouldTrack$1>0&&currentBlock){currentBlock.push(vnode);}return vnode;}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets all categories for a given userID
function getCategories(userID) { return new Promise ((resolve, reject) => { connection.query('SELECT name FROM Categories WHERE user_fk = ?', [userID], function(err, result) { if (err) { reject(err) } else { resolve(result) } }) }) }
[ "categories(user) {\n\t\treturn UserModel.getCategories(getDBDriver(), user.id)\n\t\t\t.then(res => res)\n\t\t\t.catch(err => [])\n\t}", "getCategories(userId) {\n\t\treturn this._getObjects(\n\t\t\t(\n\t\t\t\t'SELECT DISTINCT c.name FROM category c ' + \n\t\t\t\t'JOIN message_category mc ON c.id = mc.categoryId ' +\n\t\t\t\t'JOIN message m ON mc.messageId = m.id ' + \n\t\t\t\t'WHERE m.senderId = :id OR m.recipientId = :id'\n\t\t\t),\n\t\t\t{\n\t\t\t\tid: userId\n\t\t\t}\n\t\t);\n\t}", "static getCategoriesByUserId(id) {\n let tempArray = []\n\n for (let i = 0; i < wishlists.length; i++) {\n if (wishlists[i].userId == id) {\n tempArray = wishlists[i].categoryList\n }\n }\n return tempArray\n }", "async getUserCategories(request, response) {\n let userId = request.params.userId;\n let userCategories = await Category.find({ creator: userId, addedBy: \"user\" }).sort({ createdAt: -1 });\n if (!userCategories) {\n response.status(204).json({ success: false, message: \"No category yet!\" });\n } else {\n response.status(200).json({ success: true, categories: userCategories });\n }\n }", "static getBooksByCategoryUserId(id) {\n for (let i = 0; i < wishlists.length; i++) {\n if (wishlists[i].userId == id) {\n return wishlists[i].notificationsCategories\n }\n }\n return []\n }", "async getAllCategories() {\n return await apiService.get('categories');\n }", "function makeListByCategory(userID, category) {\n return new Promise((resolve, reject) => {\n knex('users').select('item.id', 'item.item_name', 'list.cat_code')\n .join('list', 'list.user_id', '=', 'users.id')\n .join('list_item', 'list_item.list_id', '=', 'list.id')\n .join('item', 'item.id', '=', 'list_item.item_id')\n .where({ 'users.id': userID })\n .where({ 'item.cat_code': category })\n .then((list) => {\n return resolve(list);\n })\n .catch(err => reject(err));\n });\n }", "function getCategory(req,res){\n var userId = req.query.userId,\n query = \"select * from rdc01hn4hfiuo1rv.usercate where user_id = \"+userId+';';\n updateLoginTime(userId);\n function usercateQueryCB(err,data){\n var userSelected = data,\n query = \"select * from rdc01hn4hfiuo1rv.category;\";\n function cateQueryCB(err,data){\n var categories = data.filter(function(value, index, arr){\n for (var i=0;i<userSelected.length;i++){\n if (userSelected[i].cate_id == value.cate_id){\n return false;\n }\n }\n return true;\n });\n var rdmCate = [];\n while(rdmCate.length<4){\n if(rdmCate.length == categories.length){\n break;\n }\n var rng = Math.floor(Math.random() * categories.length),\n used = false;\n for (var i=0;i<rdmCate.length;i++){\n if (rdmCate[i].cate_id == categories[rng].cate_id){\n used = true;\n }\n }\n if (!used){\n rdmCate.push(categories[rng]);\n }\n }\n res.send(JSON.stringify(rdmCate));\n }\n util.queryDB(query, cateQueryCB);\n\n }\n util.queryDB(query, usercateQueryCB);\n\n}", "function getCategories() {\n \n var repoConn = repoLib.getRepoConnection(repoConfig.name, repoConfig.branch);\n var hits = repoConn.query({\n count: 1000,\n query: \"data.type = 'category'\"\n }).hits;\n if (!hits || hits.length < 1) {\n return hits;\n }\n\n var categories = hits.map(function (hit) {\n return repoConn.get(hit.id);\n });\n\n if (categories) {\n return categories;\n } else {\n return \"NOT_FOUND\";\n } \n}", "computeSuggestedCategories(userAnswers, userID) {\n return listOfOrderedCategories;\n }", "function getCategories() {\n \n // API call to get categories\n fetch(\"https://my-store2.p.rapidapi.com/catalog/categories\", {\n \"method\": \"GET\",\n \"headers\": {\n \"x-rapidapi-key\": \"ef872c9123msh3fdcc085935d35dp17730cjsncc96703109e1\",\n \"x-rapidapi-host\": \"my-store2.p.rapidapi.com\"\n }\n })\n .then(response => {\n return response.json();\n })\n .then(response => {\n\n // call display catgories to display it on screen\n displayCategories(response);\n })\n .catch(err => {\n console.error(err);\n });\n }", "async fetch() {\n // should request go to all categories or user preferred categories.\n const url = AuthService.isLoggedIn()\n ? USER_CATEGORY_FETCH_API\n : ALL_CATEGORY_FETCH_API;\n const headers = AuthService.isLoggedIn()\n ? { Authorization: AuthService.accessToken }\n : {};\n const categories = await super.makeRequest(url, { headers: headers });\n return categories;\n }", "function getCategories(user, listId, listName) {\n var list = getList(user, listId, listName);\n var allCategories = list[CATEGORIES];\n var rv = [];\n if (allCategories !== undefined) {\n \tfor (var i=0; i<allCategories.length; i++){\n \t\tif (allCategories[i].status === ACTIVE_STATUS) {\n \t\t\trv.push(allCategories[i]);\n \t\t}\n \t}\n }\n rv.sort(compareHashesByName);\n return (rv);\n}//getCategories", "async getAllCategories() {\n const data = await this.get('jokes/categories');\n return data;\n }", "function readCategories() {\n connection.query('SELECT DISTINCT category FROM auctions',\n (err,res) => {\n if (err) throw err;\n categories = [];\n for (let i = 0; i < res.length; i++) {\n categories.push(res[i].category);\n }\n if (selectedCategory) {\n readItems(selectedCategory);\n } else {\n prompt();\n }\n });\n}", "function fetchCategories() {\n server.get('categories')\n .then((response) => {\n setCategories(response.data.categories);\n });\n }", "static async getAllCategoriesAndQuestions() {\n categories = [];\n let categoryIds = await Category.getCategoryIds();\n for ( let categoryId of categoryIds ) {\n let fullCategory = await Category.getCategory(categoryId);\n categories.push(fullCategory);\n }\n return categories;\n }", "getCategories() {\n return fetch(this.baseURL + '/categories').then(res => res.json()\n );\n }", "function getCategories(callback) {\n wiki.find().distinct('categories', function (err, categories) {\n if (err) {\n callback(err);\n } else if (categories.length == 0) {\n callback();\n } else {\n callback(null, categories);\n }\n })\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Place text labels within an atlas of the given max size
setTextureTextPositions (texts, max_texture_size) { let texture = { cx: 0, cy: 0, width: 0, height: 0, column_width: 0, texture_id: 0, texcoord_cache: {} }, textures = []; for (let style in texts) { let text_infos = texts[style]; for (let text in text_infos) { let text_info = text_infos[text]; let texture_position; if (text_info.text_settings.can_articulate) { text_info.textures = []; texture.texcoord_cache[style] = texture.texcoord_cache[style] || {}; for (let t = 0; t < text_info.type.length; t++) { let type = text_info.type[t]; if (type === 'straight') { let word = (text_info.isRTL) ? text.split().reverse().join() : text; if (!texture.texcoord_cache[style][word]) { let size = text_info.size.texture_size; texture_position = this.placeText(size[0], size[1], style, texture, textures, max_texture_size); texture.texcoord_cache[style][word] = { texture_id: texture.texture_id, texture_position }; } text_info.textures[t] = texture.texture_id; } else if (type === 'curved') { text_info.textures[t] = []; for (let w = 0; w < text_info.segment_sizes.length; w++) { let word = text_info.segments[w]; if (!texture.texcoord_cache[style][word]) { let size = text_info.segment_sizes[w].texture_size; let width = 2 * size[0]; // doubled to account for side-by-side rendering of fill and stroke texture_position = this.placeText(width, size[1], style, texture, textures, max_texture_size); texture.texcoord_cache[style][word] = { texture_id: texture.texture_id, texture_position }; } text_info.textures[t].push(texture.texture_id); } } } } else { // rendered size is same for all alignments let size = text_info.size.texture_size; // but each alignment needs to be rendered separately for (let align in text_info.align) { texture_position = this.placeText (size[0], size[1], style, texture, textures, max_texture_size); text_info.align[align].texture_id = texture.texture_id; text_info.align[align].texture_position = texture_position; } } } } // save final texture if (texture.column_width > 0 && texture.height > 0) { textures[texture.texture_id] = { texture_size: [texture.width, texture.height], texcoord_cache: texture.texcoord_cache }; } // return computed texture sizes and UV cache return textures; }
[ "placeText (text_width, text_height, style, texture, textures, max_texture_size) {\n let texture_position;\n\n // TODO: what if first label is wider than entire max texture?\n\n if (texture.cy + text_height > max_texture_size) {\n // start new column\n texture.cx += texture.column_width;\n texture.cy = 0;\n texture.column_width = text_width;\n }\n else {\n // expand current column\n texture.column_width = Math.max(texture.column_width, text_width);\n }\n\n if (texture.cx + texture.column_width <= max_texture_size) {\n // add label to current texture\n texture_position = [texture.cx, texture.cy];\n\n texture.cy += text_height;\n\n // expand texture if needed\n texture.height = Math.max(texture.height, texture.cy);\n texture.width = Math.max(texture.width, texture.cx + texture.column_width);\n }\n else {\n // start new texture\n // save size and cache of last texture\n textures[texture.texture_id] = {\n texture_size: [texture.width, texture.height],\n texcoord_cache: texture.texcoord_cache\n };\n texture.texcoord_cache = {}; // reset cache\n texture.texcoord_cache[style] = {};\n\n texture.texture_id++;\n texture.cx = 0;\n texture.cy = text_height;\n texture.column_width = text_width;\n texture.width = text_width;\n texture.height = text_height;\n texture_position = [0, 0]; // TODO: allocate zero array once\n }\n\n return texture_position;\n }", "function drawScaleLabel(font, units){\n let interval = scaleIntervals[scaleIntervals.length - 1];\n for (let scaleInterval of scaleIntervals){\n if (parseFloat(maxHeight*mult/scaleInterval) <= 10) {\n interval = scaleInterval;\n break;\n }\n };\n for (var i=interval; i <= (parseFloat(maxHeight*mult) + interval); i+=interval) {\n var geometry = new THREE.TextGeometry( (i).toString() + \" \" + units, {\n font: font,\n size: scaleLabelSize,\n height: 0.0001\n });\n var material = new THREE.MeshPhongMaterial( { color: scaleLabelColor } );\n var text = new THREE.Mesh(geometry, material);\n var box = new THREE.Box3().setFromObject( text );\n var size = new THREE.Vector3();\n text.position.y = i/mult - maxHeight/2 - box.getCenter(size).y;\n text.position.z = - maxWidth/2;\n text.position.x = padding + maxLength/2;\n scene.add(text);\n }\n }", "setTextureTextPositions (texts, max_texture_size, tile_key) {\n if (!CanvasText.texcoord_cache[tile_key]) {\n CanvasText.texcoord_cache[tile_key] = {};\n }\n\n // Keep track of column width\n let column_width = 0;\n\n // Layout labels, stacked in columns\n let cx = 0, cy = 0; // current x/y position in atlas\n let height = 0; // overall atlas height\n for (let style in texts) {\n if (!CanvasText.texcoord_cache[tile_key][style]) {\n CanvasText.texcoord_cache[tile_key][style] = {};\n }\n\n let text_infos = texts[style];\n\n for (let text in text_infos) {\n let text_info = text_infos[text];\n\n if (text_info.text_settings.can_articulate){\n let texture_position;\n\n for (let i = 0; i < text_info.type.length; i++){\n let type = text_info.type[i];\n switch (type){\n case 'straight':\n let size = text_info.total_size.texture_size;\n let word = text_info.segments.reduce((text_info.isRTL) ? reduceLeft : reduceRight);\n\n if (size[0] > column_width) {\n column_width = size[0];\n }\n if (cy + size[1] < max_texture_size) {\n texture_position = [cx, cy];\n\n cy += size[1];\n if (cy > height) {\n height = cy;\n }\n }\n else { // start new column if taller than texture\n cx += column_width;\n column_width = 0;\n cy = 0;\n texture_position = [cx, cy];\n }\n\n CanvasText.texcoord_cache[tile_key][style][word] = {\n texture_position: texture_position\n };\n break;\n case 'curved':\n for (let i = 0; i < text_info.size.length; i++) {\n let word = text_info.segments[i];\n\n if (!CanvasText.texcoord_cache[tile_key][style][word]) {\n\n let size = text_info.size[i].texture_size;\n let width = 2 * size[0];\n if (width > column_width) {\n column_width = width;\n }\n if (cy + size[1] < max_texture_size) {\n texture_position = [cx, cy];\n\n cy += size[1];\n if (cy > height) {\n height = cy;\n }\n }\n else { // start new column if taller than texture\n cx += column_width;\n column_width = 0;\n cy = 0;\n texture_position = [cx, cy];\n }\n\n CanvasText.texcoord_cache[tile_key][style][word] = {\n texture_position: texture_position\n };\n }\n }\n break;\n }\n }\n }\n else {\n // rendered size is same for all alignments\n let size = text_info.size.texture_size;\n if (size[0] > column_width) {\n column_width = size[0];\n }\n\n // but each alignment needs to be rendered separately\n for (let align in text_info.align) {\n if (cy + size[1] < max_texture_size) {\n text_info.align[align].texture_position = [cx, cy]; // add label to current column\n cy += size[1];\n if (cy > height) {\n height = cy;\n }\n }\n else { // start new column if taller than texture\n cx += column_width;\n column_width = 0;\n cy = 0;\n text_info.align[align].texture_position = [cx, cy];\n }\n }\n }\n }\n }\n\n return [cx + column_width, height]; // overall atlas size\n }", "function updateTextSize() {\n if (label.width > cell.width)\n label.scale = cell.width / label.width * 0.9\n}", "function drawDimensionsText(){\n for (let i = 0; i < beam.locations.length - 1; i++) {\n const location = beam.locations[i];\n const nextLocation = beam.locations[i+1];\n const cx = getXCanvasLocation((location + nextLocation)/2);\n const dimension = Math.round((nextLocation - location)*100)/100;\n text = draw.text(dimension.toString() + \" m\").cx(cx).cy(DIMENSION_Y*1.05)\n text.font({ size: FONT_SIZE, anchor: 'right' }); \n }\n}", "addStaticText(x, y, msg, scene) {\n var variable = scene.add.bitmapText(x, y-6, 'bigFontB', msg, 24);\n variable.setDepth(1);\n }", "function drawMaxHeightLabel() {\n const maxHeightLabel = `max_height = ${maxHeight.toFixed(2)}m`;\n context.font = '14pt Arial';\n context.textAlign = 'left';\n context.fillText(maxHeightLabel, base.x + 650, base.y + (height - 75));\n}", "function createTextSprites(gl, extents, spacing, font, padding, labelNames) {\n\n //Create scratch canvas object\n var canvas = document.createElement(\"canvas\")\n canvas.width = 1024\n canvas.height = 1024\n\n //Get 2D context\n var context = canvas.getContext(\"2d\")\n\n //Initialize canvas\n context.font = font\n context.textAlign = \"center\"\n context.textBaseLine = \"middle\"\n\n //Pack all of the strings into the texture map\n var textures = []\n var data = []\n var bin\n\n function beginTexture() {\n bin = boxpack({\n width: canvas.width,\n height: canvas.height\n })\n context.clearRect(0, 0, canvas.width, canvas.height)\n }\n\n function endTexture() {\n var tex = createTexture(gl, canvas)\n tex.generateMipMaps()\n textures.push(tex)\n }\n\n //Use binpack to stuff text item in buffer, continue looping\n function addItem(t, text) {\n var dims = drawContext.measureText(str)\n var location = bin.pack({ width: dims.width + 2*padding, \n height: dims.height + 2*padding })\n if(!location) {\n endTexture()\n beginTexture()\n location = bin.pack({ width: dims.width + 2*padding, \n height: dims.height + 2*padding })\n }\n\n //Render the text into the canvas\n drawContext.fillText(text, location.x+padding+dims.width/2, location.y+padding+dims.height/2)\n\n //Calculate vertex data\n var textureId = textures.length\n var coord = [ (location.x + padding)/canvas.width, (location.y + padding)/canvas.height ]\n var shape = [ dims.width/canvas.width, dims.height/canvas.height ]\n var aspect_2 = 0.5 * dims.width / dims.height\n\n //Append vertices\n data.push(\n t, textureId, coord[0], coord[1], -aspect_2, -0.5,\n t, textureId, coord[0]+shape[0], coord[1], aspect_2, -0.5,\n t, textureId, coord[0], coord[1]+shape[1], -aspect_2, 0.5,\n t, textureId, coord[0], coord[1]+shape[1], -aspect_2, 0.5,\n t, textureId, coord[0]+shape[0], coord[1]+shape[1], aspect_2, 0.5,\n t, textureId, coord[0]+shape[0], coord[1], aspect_2, -0.5)\n }\n\n //Generate sprites for all 3 axes, store data in texture atlases\n beginTexture()\n var axesStart = []\n var axesCount = []\n var labelOffset = []\n for(var d=0; d<3; ++d) {\n\n //Generate sprites for tick marks\n axesStart.push((data.length/VERTEX_SIZE)|0)\n var m = 0.5 * (extents[d][0] + extents[d][1])\n for(var t=m; t<=extents[d][1]; t+=spacing[d]) {\n addItem(t, prettyPrint(t))\n }\n for(var t=m-spacing[d]; t>=extents[d][0]; t-=spacing[d]) {\n addItem(t, prettyPrint(t))\n }\n axesCount.push(((data.length/VERTEX_SIZE)|0) - axesStart[d])\n\n //Also generate sprite for axis label\n labelOffsets.push(data.length)\n addItem(m, labels[i])\n }\n endTexture()\n\n //Create vetex buffers\n var buffer = createBuffer(gl, data)\n var vao = createVAO(gl, [ \n { //t\n \"buffer\": buffer,\n \"offset\": 0,\n \"size\": 1,\n \"stride\": VERTEX_STRIDE\n }, \n { //textureId\n \"buffer\": buffer,\n \"offset\": 4,\n \"size\": 1,\n \"stride\": VERTEX_STRIDE\n },\n { //texCoord\n \"buffer\": buffer,\n \"offset\": 8,\n \"size\": 2,\n \"stride\": VERTEX_STRIDE\n },\n { //screenOffset\n \"buffer\": buffer,\n \"offset\": 16,\n \"size\": 2,\n \"stride\": VERTEX_STRIDE\n }\n ])\n\n //Create text object shader\n var shader = createShader(gl)\n\n //Store all the entries in the texture map\n return new TextSprites(gl, shader, buffer, vao, textures, axesStart, axesCount, labelOffset)\n}", "function scaleText(self) {\n d3.select(self).selectAll('.node-label')\n .each(function(d) {\n // Available width depends on size of icon\n var iconNode = this.parentNode.querySelector('.node-icon:not(.hide)'),\n iconWidth = iconNode ? iconNode.getBoundingClientRect().width : 0;\n\n // There are two cases that width is equal to 0: a div or an img without src.\n // a div with non yet loaded css always has width of 20px.\n if (!iconWidth && iconNode && iconNode.tagName.toLowerCase() === 'div') iconWidth = 20;\n\n // For any reason makes the icon's width 0, set it to the max 20\n if (icon(d) && !iconWidth) iconWidth = 20;\n\n var marginPadding = iconWidth ? 12 : 6,\n w = zoomLevel.width - iconWidth - marginPadding;\n d3.select(this).style('max-width', w + 'px');\n });\n }", "autosize_domain_labels() {\n var maxLabelWidth = this.radius_middle - this.radius_inner - this.rotated_label_start_padding - this.rotated_label_end_padding;\n\n var autosizeFields = $(\"text.autosized\");\n autosizeFields.each(function() {\n var fld =$(this);\n if (fld[0].getBBox().width > maxLabelWidth) {\n var choppedText = fld.html().slice(0, -3);\n while (choppedText.length > 0) {\n var abbreviatedText = choppedText + \"...\";\n fld.html(abbreviatedText);\n\n // getBBox needs to be fetched after each content update\n if (fld[0].getBBox().width <= maxLabelWidth) {\n break;\n } else {\n choppedText = choppedText.slice(0, -1);\n }\n }\n }\n });\n }", "function labelHands(playerList) {\n\t// finding the width of the longest player name\n\tvar longestName = \"\";\n\tfor (i = 0; i < playerList.length; i++) {\n\t\tif (playerList[i].name.length > longestName.length) {\n\t\t\tlongestName = playerList[i].name;\n\t\t};\n\t};\n\tctx.font = \"20px Arial\";\n\tnameWidth = ctx.measureText(longestName).width;\n\tvar y = 100;\n var x = 1050 - nameWidth;\n\tfor (var i = 0; i < playerList.length; i++) {\n\t\tctx.font = \"20px Arial\";\n\t\tctx.textAlign = \"center\";\n\t\tctx.fillStyle = 'black'\n\t\tctx.fillText(playerList[i].name, x, y);\n\t\ty += 150;\n\t};\n}", "function fitWithPointLabels(scale){/*\n\t\t * Right, this is really confusing and there is a lot of maths going on here\n\t\t * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9\n\t\t *\n\t\t * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif\n\t\t *\n\t\t * Solution:\n\t\t *\n\t\t * We assume the radius of the polygon is half the size of the canvas at first\n\t\t * at each index we check if the text overlaps.\n\t\t *\n\t\t * Where it does, we store that angle and that index.\n\t\t *\n\t\t * After finding the largest index and angle we calculate how much we need to remove\n\t\t * from the shape radius to move the point inwards by that x.\n\t\t *\n\t\t * We average the left and right distances to get the maximum shape radius that can fit in the box\n\t\t * along with labels.\n\t\t *\n\t\t * Once we have that, we can find the centre point for the chart, by taking the x text protrusion\n\t\t * on each side, removing that from the size, halving it and adding the left x protrusion width.\n\t\t *\n\t\t * This will mean we have a shape fitted to the canvas, as large as it can be with the labels\n\t\t * and position it in the most space efficient manner\n\t\t *\n\t\t * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif\n\t\t */var plFont=getPointLabelFontOptions(scale);// Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.\n// Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points\nvar largestPossibleRadius=Math.min(scale.height/2,scale.width/2);var furthestLimits={r:scale.width,l:0,t:scale.height,b:0};var furthestAngles={};var i,textSize,pointPosition;scale.ctx.font=plFont.font;scale._pointLabelSizes=[];var valueCount=getValueCount(scale);for(i=0;i<valueCount;i++){pointPosition=scale.getPointPosition(i,largestPossibleRadius);textSize=measureLabelSize(scale.ctx,plFont.size,scale.pointLabels[i]||'');scale._pointLabelSizes[i]=textSize;// Add quarter circle to make degree 0 mean top of circle\nvar angleRadians=scale.getIndexAngle(i);var angle=helpers.toDegrees(angleRadians)%360;var hLimits=determineLimits(angle,pointPosition.x,textSize.w,0,180);var vLimits=determineLimits(angle,pointPosition.y,textSize.h,90,270);if(hLimits.start<furthestLimits.l){furthestLimits.l=hLimits.start;furthestAngles.l=angleRadians;}if(hLimits.end>furthestLimits.r){furthestLimits.r=hLimits.end;furthestAngles.r=angleRadians;}if(vLimits.start<furthestLimits.t){furthestLimits.t=vLimits.start;furthestAngles.t=angleRadians;}if(vLimits.end>furthestLimits.b){furthestLimits.b=vLimits.end;furthestAngles.b=angleRadians;}}scale.setReductions(largestPossibleRadius,furthestLimits,furthestAngles);}", "function fitWithPointLabels(scale) {\n // Right, this is really confusing and there is a lot of maths going on here\n // The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9\n //\n // Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif\n //\n // Solution:\n //\n // We assume the radius of the polygon is half the size of the canvas at first\n // at each index we check if the text overlaps.\n //\n // Where it does, we store that angle and that index.\n //\n // After finding the largest index and angle we calculate how much we need to remove\n // from the shape radius to move the point inwards by that x.\n //\n // We average the left and right distances to get the maximum shape radius that can fit in the box\n // along with labels.\n //\n // Once we have that, we can find the centre point for the chart, by taking the x text protrusion\n // on each side, removing that from the size, halving it and adding the left x protrusion width.\n //\n // This will mean we have a shape fitted to the canvas, as large as it can be with the labels\n // and position it in the most space efficient manner\n //\n // https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif\n var plFont = helpers$1.options._parseFont(scale.options.pointLabels); // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.\n // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points\n\n\n var furthestLimits = {\n l: 0,\n r: scale.width,\n t: 0,\n b: scale.height - scale.paddingTop\n };\n var furthestAngles = {};\n var i, textSize, pointPosition;\n scale.ctx.font = plFont.string;\n scale._pointLabelSizes = [];\n var valueCount = getValueCount(scale);\n\n for (i = 0; i < valueCount; i++) {\n pointPosition = scale.getPointPosition(i, scale.drawingArea + 5);\n textSize = measureLabelSize(scale.ctx, plFont.lineHeight, scale.pointLabels[i] || '');\n scale._pointLabelSizes[i] = textSize; // Add quarter circle to make degree 0 mean top of circle\n\n var angleRadians = scale.getIndexAngle(i);\n var angle = helpers$1.toDegrees(angleRadians) % 360;\n var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);\n var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);\n\n if (hLimits.start < furthestLimits.l) {\n furthestLimits.l = hLimits.start;\n furthestAngles.l = angleRadians;\n }\n\n if (hLimits.end > furthestLimits.r) {\n furthestLimits.r = hLimits.end;\n furthestAngles.r = angleRadians;\n }\n\n if (vLimits.start < furthestLimits.t) {\n furthestLimits.t = vLimits.start;\n furthestAngles.t = angleRadians;\n }\n\n if (vLimits.end > furthestLimits.b) {\n furthestLimits.b = vLimits.end;\n furthestAngles.b = angleRadians;\n }\n }\n\n scale.setReductions(scale.drawingArea, furthestLimits, furthestAngles);\n }", "createLabels() {\n if (this.settings.labelsConfig.areSpritesUsed) {\n this.createLabelsAsSprites();\n } else {\n this.createLabelsAsPoints();\n }\n this.render();\n }", "createLocationText() {\n let obj = {\n x: 35,\n y: 65,\n align: \"center\",\n text: this.location,\n origin: { x: 0, y: 0 },\n style: {\n fontSize: '6vw',\n fontFamily: 'Noto-Serif',\n color: 'white',\n align: 'center',\n }\n }\n let caption = this.make.text(obj);\n caption.setStroke('black', 3);\n }", "function resize_legend_text(width)\n{\n d3.select(\"#svg-legend\")\n .selectAll(\"text\")\n .attr(\"x\",function (d,i) {\n return 0.35*width + 100*i + 40;\n })\n .attr(\"y\",0.1 * window.innerHeight + 7.5)\n .text(function (d) {\n return d;\n })\n\n}", "function drawLabel(x, y) {\n var subPolygonLabel = doc.layers['sub-polygon labels'].textFrames.add(); \n subPolygonLabel.contents = subPolygonNumber; \n subPolygonLabel.textRange.characterAttributes.fillColor = hexToRGB(textColor);\n subPolygonLabel.textRange.characterAttributes.size = textSize;\n var expanded = subPolygonLabel.createOutline();\n expanded.top = y + expanded.height/2;\n expanded.left = x - expanded.width/2;\n subPolygonLabelCounter += 1; \n}", "function Label(fontname, fontsize, layer, id) {\r\n myLibrary.GameObject.call(this, layer, id);\r\n\r\n this.color = myLibrary.Color.black;\r\n this.origin = myLibrary.Vector2.zero;\r\n this._fontname = typeof fontname !== 'undefined' ? fontname : \"Courier New\";\r\n this._fontsize = typeof fontsize !== 'undefined' ? fontsize : \"20px\";\r\n this._contents = \"\";\r\n this._align = \"left\";\r\n \r\n /* I declare this variable in oreder to calculate the size of the text (widht and height in pixels) which is very handy to write text\r\n in the spot.*/\r\n this._size = myLibrary.Vector2.zero;\r\n }", "function fitWithPointLabels(scale) {\n /*\n * Right, this is really confusing and there is a lot of maths going on here\n * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9\n *\n * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif\n *\n * Solution:\n *\n * We assume the radius of the polygon is half the size of the canvas at first\n * at each index we check if the text overlaps.\n *\n * Where it does, we store that angle and that index.\n *\n * After finding the largest index and angle we calculate how much we need to remove\n * from the shape radius to move the point inwards by that x.\n *\n * We average the left and right distances to get the maximum shape radius that can fit in the box\n * along with labels.\n *\n * Once we have that, we can find the centre point for the chart, by taking the x text protrusion\n * on each side, removing that from the size, halving it and adding the left x protrusion width.\n *\n * This will mean we have a shape fitted to the canvas, as large as it can be with the labels\n * and position it in the most space efficient manner\n *\n * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif\n */\n \n var plFont = getPointLabelFontOptions(scale);\n \n // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.\n // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points\n var largestPossibleRadius = Math.min(scale.height / 2, scale.width / 2);\n var furthestLimits = {\n r: scale.width,\n l: 0,\n t: scale.height,\n b: 0\n };\n var furthestAngles = {};\n var i, textSize, pointPosition;\n \n scale.ctx.font = plFont.font;\n scale._pointLabelSizes = [];\n \n var valueCount = getValueCount(scale);\n for (i = 0; i < valueCount; i++) {\n pointPosition = scale.getPointPosition(i, largestPossibleRadius);\n textSize = measureLabelSize(scale.ctx, plFont.size, scale.pointLabels[i] || '');\n scale._pointLabelSizes[i] = textSize;\n \n // Add quarter circle to make degree 0 mean top of circle\n var angleRadians = scale.getIndexAngle(i);\n var angle = helpers.toDegrees(angleRadians) % 360;\n var hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180);\n var vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270);\n \n if (hLimits.start < furthestLimits.l) {\n furthestLimits.l = hLimits.start;\n furthestAngles.l = angleRadians;\n }\n \n if (hLimits.end > furthestLimits.r) {\n furthestLimits.r = hLimits.end;\n furthestAngles.r = angleRadians;\n }\n \n if (vLimits.start < furthestLimits.t) {\n furthestLimits.t = vLimits.start;\n furthestAngles.t = angleRadians;\n }\n \n if (vLimits.end > furthestLimits.b) {\n furthestLimits.b = vLimits.end;\n furthestAngles.b = angleRadians;\n }\n }\n \n scale.setReductions(largestPossibleRadius, furthestLimits, furthestAngles);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function `averageOfFour(num1, num2, num3, num4)` that takes in four numbers. The function should return the average of all of the numbers. Examples: averageOfFour(10, 10, 15, 5); // => 10 averageOfFour(3, 10, 11, 4); // => 7 averageOfFour(1, 2, 3, 4); // => 2.5
function averageOfFour(num1, num2, num3, num4) { return (num1 + num2 + num3 + num4) / 4; }
[ "function averageOfFour(num1, num2, num3, num4) {\n var sum = num1 + num2 + num3 + num4\n var avg = sum / 4\n return avg\n}", "function averageOfFour(num1, num2, num3, num4) {\n return ((num1 + num2 + num3 + num4) / 4);\n}", "function mean(num1,num2,num3,num4) {\n var sum = num1 + num2 + num3 + num4;\n var avg = sum/4;\n return avg;\n}", "function arithmeticMean(num1, num2, num3, num4) {\n return ((num1 + num2 + num3 + num4) / 4);\n}", "function arithmeticMean(num1, num2, num3, num4) {\n return (num1 + num2 + num3 + num4) / 4\n}", "function average4 (a, b, c, d) {\n\n}", "function aritmeticMeanOfFourNumbers(a, b, c, d){\n var sum = a + b + c + d;\n var aritmeticMean = sum / 4;\n console.log(aritmeticMean);\n}", "function average(num1, num2, num3, num4, num5) {\n\treturn (num1 + num2 + num3 + num4 + num5) / 5;\n}", "function mean(a, b, c, d) {\n return (a + b + c + d) / 4;\n\n}", "function average(number1, number2, number3, number4, number5) {\r\n return (number1 + number2 + number3 + number4 + number5) / 5;\r\n}", "function calculateAverage(num1, num2, num3, num4, num5) {\n return Math.round((num1 + num2 + num3 + num4 + num5) / 5);\n}", "function average(num1, num2, num3, num4, num5){\r\n console.log((num1 + num2 + num3 + num4 + num5) / 5);\r\n}", "function averageOfFive(num1, num2, num3, num4, num5) {\n console.log((num1 + num2 + num3 + num4 + num5) / 5);\n}", "function average(num1,num2,num3,num4,num5)\n {\n\n sum=(num1+num2+num3+num4+num5)/5;\n return sum;\n }", "function calculateAverage(num1, num2, num3, num4, num5) {\n // code here\n let sum = num1+num2+num3+num4+num5;\n return Math.round(sum/5);\n}", "function average(number1,number2,number3,number4,number5,number6){\n\treturn (number1 + number2 + number3 + number4 + number5 + number6)/6;\n}", "function avg(num1, num2, num3) {\n return (num1+num2+num3)/3;\n}", "function avg(num1, num2, num3) {\n return (num1 + num2 + num3)/3;\n}", "function avg(num1, num2, num3) {\n return (num1 + num2 + num3)/3;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the clone URL for a protocol.
function makeCloneUrl(stack, repositoryName, protocol, region) { switch (protocol) { case 'https': case 'ssh': return `${protocol}://git-codecommit.${region !== null && region !== void 0 ? region : stack.region}.${stack.urlSuffix}/v1/repos/${repositoryName}`; case 'grc': return `codecommit::${region !== null && region !== void 0 ? region : stack.region}://${repositoryName}`; } }
[ "function getRepoCloneUrl () {\n var gitExt = '.git';\n var urlConfig = {\n protocol : 'https',\n hostname : cred.repo.hostname,\n auth : cred.repo.auth,\n pathname : '/' + cred.user.login + '/' + cred.repo.name + gitExt\n };\n return url.format(urlConfig);\n}", "function getCloneUrl() {\n const modalEl = getModalEl();\n // const httpsCloneEl = modalEl.getElementsByClassName(\"https-clone-options\")[0];\n // const httpsCloneUrl = httpsCloneEl.getElementsByClassName(\"input-sm\")[0]\n // .value;\n\n const sshCloneEl = modalEl.getElementsByClassName(\"ssh-clone-options\")[0];\n const sshCloneUrl = sshCloneEl.getElementsByClassName(\"input-sm\")[0].value;\n\n return sshCloneUrl;\n}", "get cloneUrlHttp() {\n return this.getStringAttribute('clone_url_http');\n }", "get cloneUrlSsh() {\n return this.getStringAttribute('clone_url_ssh');\n }", "get protocol() {\n return this.parsedUrl.protocol;\n }", "function getUrlWithProtocol(url){\n if (url.substring(0, 4).toLowerCase() != 'http'){\n return protocolAdded+url;\n }\n return url;\n }", "function generateUrl (protocol, urlPath) {\n return protocol === 'http' ? HTTP_SERVER_BASE + urlPath : HTTPS_SERVER_BASE + urlPath;\n}", "clone(path, url) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n let response = yield httpGitRequest('/git/clone', 'POST', {\n current_path: path,\n clone_url: url\n });\n if (response.status !== 200) {\n const data = yield response.json();\n throw new services_1.ServerConnection.ResponseError(response, data.message);\n }\n return response.json();\n }\n catch (err) {\n throw services_1.ServerConnection.NetworkError;\n }\n });\n }", "function getURLConnectionForHTTPS() {\n var url = '' + window.location;\n var ipAddress = url.split('/l');\n var nouvelleURL = ipAddress[0];\n \n return nouvelleURL;\n}", "function getURL(){\r\n var dprefix;\r\n dprefix = (useSSL) ? \"https://\" : \"http://\";\r\n \r\n return dprefix + NEWSBLUR_DOMAIN;\r\n}", "createPath(protocol, host, port) {\n return (protocol + \"://\" + host + \":\" + port);\n }", "getLinkProtocol() {\n if (this.linkURI) {\n return this.linkURI.scheme; // Can be |undefined|.\n }\n\n return null;\n }", "getUrl() {\n if (!this._url) {\n this._url = new URL(location + \"\");\n }\n\n return this._url;\n }", "static npmUrlToGitUrl(npmUrl) {\n // Expand shortened format first if needed\n npmUrl = npmUrl.replace(/^github:/, 'git+ssh://[email protected]/');\n\n // Special case in npm, where ssh:// prefix is stripped to pass scp-like syntax\n // which in git works as remote path only if there are no slashes before ':'.\n const match = npmUrl.match(/^git\\+ssh:\\/\\/((?:[^@:\\/]+@)?([^@:\\/]+):([^/]*).*)/);\n // Additionally, if the host part is digits-only, npm falls back to\n // interpreting it as an SSH URL with a port number.\n if (match && /[^0-9]/.test(match[3])) {\n return {\n hostname: match[2],\n protocol: 'ssh:',\n repository: match[1]\n };\n }\n\n const repository = npmUrl.replace(/^git\\+/, '');\n const parsed = url.parse(repository);\n return {\n hostname: parsed.hostname || null,\n protocol: parsed.protocol || 'file:',\n repository\n };\n }", "function clone(url){\n \n if(shell.exec('git clone '+ url)==0)\n console.log(\"Successfully Clonned \"+url);\n else\n console.log(\"ERROR! Clonning \"+url);\n \n}", "function getURL( repository ) {\n var repourl;\n\n if (typeof repository === 'object') {\n repourl = repository.url;\n } else {\n repourl = repository\n };\n\n return repourl;\n}", "function getRepoName() {\n // Repo url might have more than just the repo name\n var repoParts = window.location.href.split(/[\\/#]+/);\n // 0: http(s)\n // 1: Hostname\n scheme = repoParts[0];\n var repo = repoParts[2] + '/' + repoParts[3];\n\n return repo;\n}", "static npmUrlToGitUrl(npmUrl: string): GitUrl {\n // Expand shortened format first if needed\n npmUrl = npmUrl.replace(/^github:/, 'git+ssh://[email protected]/');\n\n // Special case in npm, where ssh:// prefix is stripped to pass scp-like syntax\n // which in git works as remote path only if there are no slashes before ':'.\n const match = npmUrl.match(/^git\\+ssh:\\/\\/((?:[^@:\\/]+@)?([^@:\\/]+):([^/]*).*)/);\n // Additionally, if the host part is digits-only, npm falls back to\n // interpreting it as an SSH URL with a port number.\n if (match && /[^0-9]/.test(match[3])) {\n return {\n hostname: match[2],\n protocol: 'ssh:',\n repository: match[1],\n };\n }\n\n const repository = npmUrl.replace(/^git\\+/, '');\n const parsed = url.parse(repository);\n return {\n hostname: parsed.hostname || null,\n protocol: parsed.protocol || 'file:',\n repository,\n };\n }", "function getUrl(options) {\n var _a, _b, _c;\n let path = getOption('baseUrl') || '/';\n const mode = (_a = options.mode) !== null && _a !== void 0 ? _a : getOption('mode');\n const workspace = (_b = options.workspace) !== null && _b !== void 0 ? _b : getOption('workspace');\n const labOrDoc = mode === 'multiple-document' ? 'lab' : 'doc';\n path = url_1.URLExt.join(path, labOrDoc);\n if (workspace !== PageConfig.defaultWorkspace) {\n path = url_1.URLExt.join(path, 'workspaces', encodeURIComponent(getOption('workspace')));\n }\n const treePath = (_c = options.treePath) !== null && _c !== void 0 ? _c : getOption('treePath');\n if (treePath) {\n path = url_1.URLExt.join(path, 'tree', url_1.URLExt.encodeParts(treePath));\n }\n return path;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the MySQL database, and call output_actors on the results res = HTTP result object sent back to the client year = Year to query for rate = new rating from user
function query_db_mascot(res,year,rate) { query = "SELECT * FROM Mascot WHERE Mascot.Year = '"+year+"'"; connection.query(query, function(err, rows) { if (err) console.log(err); else { var x = rows[0]; console.log(x.Rating); console.log(x.numOfUser); var newAvg = (x.Rating * x.numOfUser); console.log(newAvg); newAvg = newAvg + parseInt(rate); console.log(newAvg); newAvg = Math.round(newAvg / (x.numOfUser + 1)); console.log(newAvg); console.log(x.numOfUser); var num = x.numOfUser+1; update_db(res, year,newAvg, num); } }); }
[ "function query_db(res,name) {\n oracle.connect(connectData, function(err, connection) {\n if ( err ) {\n \tconsole.log(err);\n } else {\n\t \t// selecting rows\n\t \tconnection.execute(\t\"SELECT m.name, m.rank, m.year, a.first_name, a.last_name \" + \n\t \t\t\t\t\t\t\"FROM actors a, movies m, roles r \" + \n\t \t\t\t\t\t\t\"WHERE a.id = r.actor_id AND m.id = r.movie_id AND a.last_name='\" + name + \n\t \t\t\t\t\t\t\"' AND rownum <= 10\", \n\t \t\t\t [], \n\t \t\t\t function(err, results) {\n\t \t if ( err ) {\n\t \t \tconsole.log(err);\n\t \t \tconsole.log('SQL querry is wrong');\n\t \t } else {\n\t \t \tconnection.close(); // done with the connection\n\t \t \toutput_movies(res, name, results);\n\t \t }\n\t\n\t \t}); // end connection.execute\n }\n }); // end oracle.connect\n}", "function movie(){\nvar movieName=nameInput || \"Mr.Nobody\";\nvar rottenTomatoRating, imdbRating;\nvar movieQueryUrl=\"http://www.omdbapi.com/?t=\" + movieName + \"&y=&plot=short&apikey=trilogy\";;\nrequest(movieQueryUrl,function(error, response, body) {\n // If the request is successful\n if (!error && response.statusCode === 200) {\n //declare a variable to store the result result\n var data=JSON.parse(body);\n //Make a if statement to obtain values of matching rating sources as required\nfor (var i = 0; i < data.Ratings.length; i++) {\n if (data.Ratings[i].Source === \"Rotten Tomatoes\") {\n rottenTomatoRating = data.Ratings[i].Value;\n }\n if (data.Ratings[i].Source === \"Internet Movie Database\") {\n imdbRating = data.Ratings[i].Value;\n }\n}\nconsole.log(\"\\n ++++++++++++++++++++Moive Ouput Start+++++++++++++++++++++++++++++++++++++++++++\")\nconsole.log(\"\\nMovie Title: \"+ data.Title);\nconsole.log(\"Movie Released in: \"+ data.Year);\nconsole.log(\"IMDB Rating is: \"+ imdbRating);\nconsole.log(\"Rotten Tomatoes Rating is: \"+ rottenTomatoRating);\nconsole.log(\"Country: \"+ data.Country);\nconsole.log(\"Available Languages: \"+ data.Language);\nconsole.log(\"Plot: \"+ data.Plot);\nconsole.log(\"Actors: \"+ data.Actors);\nconsole.log(\"\\n+++++++++++++++++++Moive Output End++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\");\n} else{\n console.log(\"Sorry, we have an issue.\")\n}\n });//end of irequest\n}", "function getEmployeeRating(req, res) {\n // console.log('Inside getEmployeeRating');\n var employeeno = req.query.emp_no;\n console.log('employeeno:' + employeeno);\n pool.getConnection(function (err, connection) {\n if (err) throw err;\n var sql =\n 'select PunctualityAndDiscipline, ExecutionOfDuties, LearningAndDevelopment, TeamCooperation, ResponsibilityTaken from employees.emp_ratings where EmpNo = ' +\n employeeno;\n console.log(sql);\n connection.query(sql, function (err, result, fields) {\n connection.release();\n if (err) console.log('error' + err);\n else {\n console.log(typeof JSON.stringify(result));\n var index = 0;\n // console.log('employee rating' + result);\n Object.entries(result).forEach(([key, value]) =>\n console.log(key, value)\n );\n return res.status(200).json(result);\n }\n });\n });\n}", "function query_db(res) {\n\tquery = \"SELECT SQL_CACHE m.name, da.origin_country, c.code, m.game_location, m.sport, m.medal, m.year FROM medalist m JOIN doping_athletes da ON da.name=m.name JOIN country_codes c ON da.origin_country=c.country GROUP BY name, year;\";\n\n\tconnection.query(query, function(err, rows, fields) {\n\t\tif (err) console.log(err);\n\t\telse {\n\t\t\toutput_persons(res, rows);\n\t\t}\n\t});\n}", "function query_db(res,search_tag,user) {\n\t//user = req.session.user;\n\t\n oracle.connect(connectData, function(err, connection) {\n if ( err ) {\n \tconsole.log(err);\n } else {\n \tquery = \"select distinct O.OBJECTID, O.OBJECTURL, O.OBJECTNAME, O.OBJECTSOURCE, (select avg(score) from rating where objectid = O.objectid) AS AVG, \" + \n\t\t\t\"(case when exists(select * from PIN where objectid=O.objectid and login ='\"+user+\"') then 'Unpin' else 'Pin' end ) as ISPINNED\"\n \t\t\t+\" from OBJECTS O, OBJECT_TAGS T where O.objectid = T.objectid and T.tag='\"+search_tag+\"'\";\n\t \t// selecting rows\n \t//SELECT objecturl FROM objects where objectid in (select objectid from pin where login='\"+name+\"'\n\t \tconnection.execute(query, \n\t \t\t\t [], \n\t \t\t\t function(err, results) {\n\t \t if ( err ) {\n\t \t \tconsole.log(err);\n\t \t } else {\n\t \t \tconnection.close(); // done with the connection\n\t \t \tconsole.log(results);\n\t \t \toutput_actors(res, search_tag, results);\n\t \t }\n\t\n\t \t}); // end connection.execute\n }\n }); // end oracle.connect\n}", "function updateImdbRatings()\n{\n Log.verbose(\"Starting IMDb rating update...\");\n\n let successFunc = function()\n {\n Log.verbose(\"Started IMDb update process\");\n startImdbUpdateStatusQuery();\n };\n\n let failureFunc = function(response)\n {\n Log.verbose(`Failed to update IMDb ratings :(`);\n if (response.Error == \"Refresh already in progress!\" && !updateInterval)\n {\n startImdbUpdateStatusQuery();\n }\n };\n\n sendHtmlJsonRequest(\"process_request.php\", { type : ProcessRequest.UpdateImdbRatings }, successFunc, failureFunc);\n}", "function getFacultyRating(faculty, index) {\n //make url for search using first name and last name.\n var rmpUrl = 'http://www.ratemyprofessors.com/search.jsp?query='+faculty[index].firstName + '+' + faculty[index].lastName;\n request(rmpUrl, function(error, response, body){\n //make html into JSDOM object so we can manipulate it\n var searchPage = new JSDOM(body);\n\n /*\n All search results have the class 'listing' and 'PROFESSOR'.\n Use function querySelectorAll which takes a css selector as\n arguments to get all elements matching this description.\n */\n var results = searchPage.window.document.querySelectorAll('.listing.PROFESSOR');\n\n if(results.length > 0) {\n //querySelectorAll returns a node last, use Array.from to conver it to an array\n var rmuResults = Array.from(results).filter(function(element){\n /*\n The div containing university name has class 'sub'.\n In each of the results, get the first element with class 'sub'.\n Check if that element contains Robert Morris University, and add it to array if it does.\n */\n return element.getElementsByClassName('sub')[0].innerHTML.indexOf('Robert Morris University') >= 0;\n });\n \n if(rmuResults.length > 0) {\n /*\n For the first element in the filtered array, get the location that its link is going to.\n Navigate to that location and get the HTML.\n */\n request('http://www.ratemyprofessors.com' + rmuResults[0].getElementsByTagName('a')[0].href, function(error, response, body) {\n var rmpPage = new JSDOM(body);\n\n //all ratings have the class grade. Since it returns an array take only the first element.\n var overallQuality = rmpPage.window.document.getElementsByClassName('grade')[0].textContent;\n var levelOfDifficulty = rmpPage.window.document.getElementsByClassName('grade')[2];\n var topTags = rmpPage.window.document.getElementsByClassName('tag-box-choosetags');\n\n //if some do not have a rating, their entire profile may return, filter them out\n if(overallQuality.length < 5) {\n //if we got their rating, set the rating property of this faculty\n faculty[index].overallQuality = overallQuality.trim();\n faculty[index].levelOfDifficulty = (levelOfDifficulty) ? levelOfDifficulty.textContent.trim() : null;\n faculty[index].topTags = [];\n for(var tag of topTags) {\n faculty[index].topTags.push(tag.textContent.split(' (')[0].trim());\n }\n var req = https.request({ \n hostname: //firebase Hostname, \n method: \"POST\", \n path: \"/faculty.json\"\n });\n req.end(JSON.stringify(faculty[index]), function(err) {\n if(err)\n console.log(err);\n else\n console.log(faculty[index].firstName + ' ' + faculty[index].lastName + ' posted to firebase.');\n });\n }\n \n });\n }\n }\n });\n}", "function query1(req, res) {\n var con = makeConnection();\n con.query(\"SELECT title, price, age_rating FROM audio_book\", function (err, result) {\n if (err) throw err;\n console.log(\"query1\");\n res.render('query1.ejs', {results: result});\n });\n}", "function setScore(userInput,result,hideTable,sessionid, alg, callback) {\n\tsearch(sessionid,function(idx) {\n\t\tif(idx > -1) { \n\t\t\tif(hideTable !=null)\n\t\t\t\tsessions[idx]['hideTable'] = hideTable;\n\t\t\tif(result=='win') \n\t\t\t\tsessions[idx]['userscore'] = Number(sessions[idx]['userscore']) + 1;\n\t\t\telse if(result == 'loose')\n\t\t\t\tsessions[idx]['aiscore'] = Number(sessions[idx]['aiscore']) + 1;\n\t\t\talg.registerFeedBack(sessions[idx]['username'],sessions[idx]['userage'],userInput);\n\t\t\tvar jsonRes = {};\n\t\t\tjsonRes['pscore'] = sessions[idx]['userscore'];\n\t\t\tjsonRes['cscore'] = sessions[idx]['aiscore'];\n\t\t\tjsonRes['hideTable'] = sessions[idx]['hideTable'];\n\t\t\tcallback(jsonRes);\n\t\t}\n\t});\n}", "function rateBooking (req, res) {\n if(!req.body.rating || parseInt(req.body.rating) > 5 || parseInt(req.body.rating) < 1)\n {\n res.status(400).json({error: \"bad request, enter a proper rating!\"});\n return;\n }\n\n Booking.findOne({ _id: req.params.id }, function (err, booking) {\n if (err) {\n res.status(400).json({error: err.message});\n return;\n }\n if (!booking)\n return res.status(404).json({error: \"booking not found\"});\n\n\n if(req.user.type == 'Player'){\n booking.arena_rating = parseInt(req.body.rating);\n\n //save arena rating at booking\n booking.save(function (err) {\n if (err) {\n res.status(400).json({error: err.message});\n return;\n }\n });\n Arena.findOne({ name: booking.arena }, function (err, arena) {\n var rating = parseInt(req.body.rating);\n if (err) {\n\n res.status(400).json({error: err.message});\n return;\n }\n if (!arena) {\n res.status(404).json({error: \"arena not found!\"});\n return;\n }\n\n if (!arena.ratings_count)\n arena.ratings_count = 0;\n\n if (!arena.avg_rating)\n arena.avg_rating = 0;\n\n // update rating\n\n arena.avg_rating = (arena.avg_rating * arena.ratings_count + rating) / (arena.ratings_count + 1);\n arena.ratings_count++;\n // save rating at arena\n arena.save(function (err) {\n\n if (err) {\n res.status(400).json({error: err.message});\n return;\n }\n });\n return res.json(arena);\n });\n }\n else{\n\n booking.player_rating = parseInt(req.body.rating);\n booking.save(function (err) {\n if (err) {\n res.status(400).json({error: err.message});\n return;\n }\n });\n res.json(booking);\n // find player\n Player.findOne({ _id: booking.player }, function (err, player) {\n var rating = parseInt(req.body.rating);\n if (err) {\n res.status(400).json({error: err.message});\n return;\n }\n if (!player) {\n res.status(404).json({error: \"player not found!\"});\n return;\n }\n // update rating\n if (!player.ratings_count)\n player.ratings_count = 0;\n\n if (!player.avg_rating)\n player.avg_rating = 0;\n\n player.avg_rating = ((player.avg_rating * player.ratings_count) + rating) / (player.ratings_count + 1);\n\n player.ratings_count++;\n // save rating at player\n player.save(function (err) {\n if (err) {\n res.status(400).json({error: err.message});\n return;\n }\n });\n });\n }\n });\n }", "function callOmdb() {\n request(\"http://www.omdbapi.com/?apikey=trilogy&t=\" + searchParams, function(error, response, body) {\n\n // If the request is successful (i.e. if the response status code is 200)\n if (!error && response.statusCode === 200) {\n var movieObj = JSON.parse(body);\n\n console.log(` -============= Movie Results =========================-\n The title of the movie is: ${movieObj.Title}\n This movie was released in: ${movieObj.Year}\n The IMDB Rating of the movie is: ${movieObj.imdbRating}\n The Rotten Tomatoes Rating of the movie is: ${movieObj.Ratings[1]}\n This movie was produced in: ${movieObj.Country}\n This movie is in: ${movieObj.Language}\n The plot of the movie is: ${movieObj.Plot}\n Actors: ${movieObj.Actors}\n -=====================================================-`);\n }\n});\n}", "* overviewPrint (request, response) {\n const categories = yield Category.all(),\n result = yield Result.get(request.param('id')),\n user = yield request.auth.getUser(),\n type = request.input('type'),\n date = moment().format('YYYY-mm-DD hh:mm:ss')\n\n result.sortCandidates((a, b) => {\n return result.getJudgesAverage(b.id) - result.getJudgesAverage(a.id)\n })\n\n if (type == 'winner') {\n result.sliceTop(1)\n }\n\n if (type == 'top-5') {\n result.sliceTop(5)\n }\n\n yield response.sendView('dashboard/score/overview_print', {\n categories, result, user, date\n })\n }", "function query_db(res,name) {\n oracle.connect(connectData, function(err, connection) {\n if ( err ) {\n \tconsole.log(err);\n } else {\n\t \t// selecting rows\n\t \tconnection.execute(\"SELECT * FROM directors D INNER JOIN movies_directors\" +\n\t \t\t\t\" md ON D.id=md.director_id INNER JOIN movies m ON md.movie_id=m.id \" +\n\t \t\t\t\"WHERE D.last_name = '\"+ name + \"' ORDER BY m.rank DESC\", [],\n\t \t\t\t function(err, results) {\n\t \t if ( err ) {\n\t \t \tconsole.log(err);\n\t \t } else {\n\t \t \tconnection.close(); // done with the connection\n\t \t \toutput_director(res, name, results);\n\t \t }\n\t\n\t \t}); // end connection.execute\n }\n }); // end oracle.connect\n}", "function getRatings(app, callback) {\n pool.query(SQL`SELECT gururatings.GuruId, applications.Application, gururatings.Certified, employee_info.Full_Name, gururatings.Rating \n FROM gururatings\n INNER JOIN applications ON applications.AppId = gururatings.AppId\n INNER JOIN employee_info ON employee_info.Id = gururatings.EmpId\n WHERE gururatings.AppId = ${ app }\n AND employee_info.Active = 1\n ORDER BY gururatings.Rating DESC;`,\n (err, result)=>{\n if(err) {\n console.log(err);\n callback(err);\n } else {\n callback(null, result);\n }\n });\n\n}", "function fetchUserRating() {\n fetch(`/api/getuserRate?id=${data.id}`, {\n method: \"get\",\n headers: {\n Authorization: `Bearer ${\n localStorage.getItem(\"login\")\n ? JSON.parse(localStorage.getItem(\"login\")).token\n : \"\"\n }`,\n Accept: \"application/json, text/plain, */*\",\n \"Content-Type\": \"application/json\",\n },\n })\n .then((res) => res.json())\n .then((obj) => {\n setUserRating(obj.score);\n });\n }", "function getRatings(response, param) {\n handler_ratings.start(response, param);\n}", "function parseOMDBResponse(data) {\r\n\r\n logContent(\"Title: \" + data.Title);\r\n logContent(\"Year: \" + data.Year);\r\n\r\n // Loop, format and print the movie ratings\r\n var ratings = data.Ratings;\r\n ratings.forEach(rating => {\r\n switch (rating.Source) {\r\n case \"Internet Movie Database\":\r\n logContent(\"IMDB Rating: \" + rating.Value);\r\n break;\r\n case \"Rotten Tomatoes\":\r\n logContent(\"Rotton Tomatoes Rating: \" + rating.Value);\r\n break;\r\n }\r\n });\r\n\r\n logContent(\"Country Produced: \" + data.Country);\r\n logContent(\"Language: \" + data.Language);\r\n logContent(\"Plot: \" + data.Plot);\r\n\r\n // Loop, format and print the actors on their own lines\r\n var actors = data.Actors.split(\", \");\r\n logContent(\"Actors:\");\r\n logContent(\"=======\");\r\n actors.forEach(actor => {\r\n logContent(\" \" + actor);\r\n });\r\n logContent(\"------------------------------------\");\r\n}", "function handleResults(url, results) {\n // *** Add code here if you want to save complete Lighthouse reports ***\n // Provide scores for categories: Performance, PWA, etc.\n // Each category provides a single aggregate score based on individual audits.\n addCategoryScores(url, results);\n // If flag set, provide scores for Web Vitals audits.\n if (outputWebVitals) {\n addWebVitalsScores(url, results);\n }\n // If flag set, provide data for all invididual audits (not just categories).\n if (outputAllAudits) {\n addAuditScores(url, results);\n }\n}", "function getRating(docID, rating,res){\n database.db.query(\"select AVG(rating) as avg from RATING where doc_id = \" + docID + \";\", function(err, rows) {\n if (err){\n res.statusCode = 500;\n res.json({\n statusCode: 500,\n message: \"get average rating failed\"\n });\n }\n else {\n rating = rows[0].avg;\n updateDocRating(docID, rating, res);\n }\n\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove chat from firebase if no players exists
function removeChat() { if (!player1Name && !player2Name) { chatRef.remove(); $("#chat-log").empty(); $(".post-login").hide(); $(".pre-login").show(); } }
[ "emptyMatches() {\n firebaseApp.database().ref('Matches').once(\"value\").then(function (snapshot) {\n snapshot.forEach(function (childSnapshot) {\n childSnapshot.forEach(function (grandChildSnapshot) {\n if (childSnapshot.key = friend_uid.key && grandChildSnapshot.key === uid) {\n firebaseApp.database().ref('Matches/' + childSnapshot.key).child(grandChildSnapshot.key).remove();\n }\n if (childSnapshot.key = uid && grandChildSnapshot.key === friend_uid.key) {\n firebaseApp.database().ref('Matches/' + childSnapshot.key).child(grandChildSnapshot.key).remove();\n }\n });\n });\n });\n firebaseApp.database().ref(\"PendingMatches/\" + uid).child(friend_uid.key).remove();\n }", "function remove_players_ans_ansduration(){\n var stationPlayers_ref = new Firebase(FB_STATIONPLAYERS_URL);\n stationPlayers_ref.once(\"value\", function(AllPlayerssnapshot){\n AllPlayerssnapshot.forEach(function(PlayerSnapshot){\n stationPlayers_ref.child(PlayerSnapshot.key()).child(\"answer\").remove();\n stationPlayers_ref.child(PlayerSnapshot.key()).child(\"answering_duration\").remove();\n stationPlayers_ref.child(PlayerSnapshot.key()).child(\"score_gained\").set(0);\n stationPlayers_ref.child(PlayerSnapshot.key()).child(\"is_correct_answer\").set(false);\n });\n });\n}", "deleteChatThread(deleteChatThreadId) {\n var urlRef = firebase.database().ref('Chat/'+deleteChatThreadId).remove();\n }", "removeUser(username) {\n for (let i = this.chatUsersDB.length - 1; i >= 0; --i) {\n if (chatUsersDB[i].username === username) {\n chatUsersDB.splice(i, 1);\n }\n }\n }", "deleteMessage() {\n firebase.database().ref('comments/' + this.props.movieId + '/' + this.props.messageId).remove();\n }", "function findUserID_delete_messages(tableName,user_id){\r\n db.ref(tableName).once(\"value\", function (returnUser_room_messages){\r\n room_messages = returnUser_room_messages.val();\r\n for (rooms in room_messages){\r\n for (messages in room_messages[rooms]){\r\n if( room_messages[rooms][messages].user_id == user_id){\r\n db.ref(tableName).child(rooms).child(messages).remove()\r\n }\r\n } \r\n }\r\n \r\n });\r\n}", "checkCloseRoom () {\n if (this.players.size === 0) {\n this.needToDeleted = true\n }\n }", "removeChat(message) {\n this.chats.splice(\n this.chats.findIndex(chat => chat.chat_id === message.chat_id), 1\n )\n }", "function clearChat() {\n if(currentChat.firstChild != null) {\n while(currentChat.firstChild) {\n currentChat.removeChild(currentChat.lastChild);\n }\n }\n}", "function destroyChat() {\n document.getElementById('twitch-chat').remove();\n}", "deleteChatRoom(event) {\n var room = this.collection.findWhere({'id': event.target.dataset.id});\n room.destroy({\n wait: true\n });\n return false;\n }", "function resetplayers() {\n database.ref(\"user1/player\").set(\"\");\n database.ref(\"user2/player\").set(\"\");\n} // End reset function", "function removeChatContainer(){\n if (!chatContainerHasVisibleContent()){\n const container = $(\"#main\");\n \n container.parent().append(\"<h4 style='color: white; font-weight: 300; text-align: center'>You don't have chats</h4>\");\n container.remove();\n } \n}", "function deleteChat(id) {\n return db.query(('DELETE FROM chats WHERE id=?', id));\n}", "function cleanupChat () {\n var len\n while ((len = y.share.chat.length) > 7) {\n y.share.chat.delete(0) \n }\n }", "async deleteChatroom(room_info) {\n\n //Retrieve an instance of our Firestore Database\n const db = firebase.firestore()\n \n //Delete messages(documents in subcollection) in the chatroom\n let messagesRef = await db.collection('chat-rooms').doc(room_info.creator_uid).collection('messages')\n await messagesRef.get().then(async (messages) => {\n if (messages.size !== 0) {\n const batch = db.batch()\n messages.forEach(message => {\n batch.delete(message.ref)\n })\n await batch.commit()\n\n //Prevents exploding the stack\n process.nextTick(() => {\n this.deleteChatroom(room_info)\n })\n }\n });\n\n //Delete chatroom(document)\n let roomRef = await db.collection('chat-rooms').doc(room_info.creator_uid)\n roomRef.update({\n delete: true\n })\n roomRef.delete();\n\n //Delete anon-user(document)\n let userRef = await db.collection('anon-users').doc(room_info.creator_uid)\n userRef.delete();\n }", "function deleteDuplicates() {\n database.ref(\"/userList/\" + currentUser).once(\"value\").then(function(snapshot) {\n var testArray = [];\n snapshot.forEach(function(snapshotChild) {\n if (testArray.indexOf(snapshotChild.val().game) < 0) {\n testArray.push(snapshotChild.val().game);\n } else { \n // Alert user that the game they tried to add is already on the list\n $(\"#gameMessage\").html(toTitleCase(snapshotChild.val().game) + \" is already on your list\");\n database.ref(\"/userList/\" + currentUser).child(snapshotChild.key).remove();\n }\n });\n });\n }", "function deleteChatData() {\n\t$.ajax({\n\t\ttype: \"PUT\",\n\t\turl: \"https://comm-app-d4cad.firebaseio.com/chat.json\",\n\t\tdata: \"\\\"null\\\"\",\n\t\tsuccess: function (msg) {\n\t\t //do something\n\t\t //console.log(\"PUT DELETE: \" + JSON.stringify(msg));\n\t\t},\n\t\terror: function (errormessage) {\n\t\t\t//do something else\n\t\t\tconsole.log(\"PUT DELETE ERROR: \" + JSON.stringify(errormessage));\n\t\t}\n\t});\n}", "function pushEmptyDataStructureToFirebase(){\n database.ref().set({\n playerOneName: \"\",\n playerOneChoice:\"\",\n playerTwoName: \"\",\n playerTwoChoice:\"\",\n lastChatPlayer:\"\",\n lastChatText:\"\"\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns whether a native element can be inserted into the given parent. There are two reasons why we may not be able to insert a element immediately. Projection: When creating a child content element of a component, we have to skip the insertion because the content of a component will be projected. `delayed due to projection` Parent container is disconnected: This can happen when we are inserting a view into parent container, which itself is disconnected. For example the parent container is part of a View which has not be inserted or is mare for projection but has not been inserted into destination.
function canInsertNativeNode(tNode,currentView){var currentNode=tNode;var parent=tNode.parent;if(tNode.parent){if(tNode.parent.type===4/* ElementContainer */){currentNode=getHighestElementContainer(tNode);parent=currentNode.parent;}else if(tNode.parent.type===5/* IcuContainer */){currentNode=getFirstParentNative(currentNode);parent=currentNode.parent;}}if(parent===null)parent=currentView[HOST_NODE];if(parent&&parent.type===2/* View */){return canInsertNativeChildOfView(parent,currentView);}else{// Parent is a regular element or a component return canInsertNativeChildOfElement(currentNode);}}
[ "function canInsertNativeNode(parent, currentView) {\n // We can only insert into a Component or View. Any other type should be an Error.\n ngDevMode && assertNodeOfPossibleTypes(parent, 3 /* Element */, 2 /* View */);\n if (parent.tNode.type === 3 /* Element */) {\n // Parent is an element.\n if (parent.view !== currentView) {\n // If the Parent view is not the same as current view than we are inserting across\n // Views. This happens when we insert a root element of the component view into\n // the component host element and it should always be eager.\n return true;\n }\n // Parent elements can be a component which may have projection.\n if (parent.data === null) {\n // Parent is a regular non-component element. We should eagerly insert into it\n // since we know that this relationship will never be broken.\n return true;\n }\n else {\n // Parent is a Component. Component's content nodes are not inserted immediately\n // because they will be projected, and so doing insert at this point would be wasteful.\n // Since the projection would than move it to its final destination.\n return false;\n }\n }\n else {\n // Parent is a View.\n ngDevMode && assertNodeType(parent, 2 /* View */);\n // Because we are inserting into a `View` the `View` may be disconnected.\n var grandParentContainer = getParentLNode(parent);\n if (grandParentContainer == null) {\n // The `View` is not inserted into a `Container` we have to delay insertion.\n return false;\n }\n ngDevMode && assertNodeType(grandParentContainer, 0 /* Container */);\n if (grandParentContainer.data[RENDER_PARENT] == null) {\n // The parent `Container` itself is disconnected. So we have to delay.\n return false;\n }\n else {\n // The parent `Container` is in inserted state, so we can eagerly insert into\n // this location.\n return true;\n }\n }\n}", "function canInsertNativeNode(parent, currentView) {\n var parentIsElement = parent.type === 3;\n return parentIsElement &&\n (parent.view !== currentView || parent.data === null /* Regular Element. */);\n}", "function canInsertNativeChildOfView(viewTNode,view){// Because we are inserting into a `View` the `View` may be disconnected.\nvar container=getLContainer(viewTNode,view);if(container==null||container[RENDER_PARENT]==null){// The `View` is not inserted into a `Container` or the parent `Container`\n// itself is disconnected. So we have to delay.\nreturn false;}// The parent `Container` is in inserted state, so we can eagerly insert into\n// this location.\nreturn true;}", "function canInsertNativeNode(tNode, currentView) {\n var currentNode = tNode;\n var parent = tNode.parent;\n if (tNode.parent) {\n if (tNode.parent.type === 4 /* ElementContainer */) {\n currentNode = getHighestElementContainer(tNode);\n parent = currentNode.parent;\n }\n else if (tNode.parent.type === 5 /* IcuContainer */) {\n currentNode = getFirstParentNative(currentNode);\n parent = currentNode.parent;\n }\n }\n if (parent === null)\n parent = currentView[HOST_NODE];\n if (parent && parent.type === 2 /* View */) {\n return canInsertNativeChildOfView(parent, currentView);\n }\n else {\n // Parent is a regular element or a component\n return canInsertNativeChildOfElement(currentNode);\n }\n}", "function hasParent(element, parent) {\n let elem = element;\n while (elem) {\n if (elem === parent) {\n return true;\n }\n else if (elem.parentNode) {\n elem = elem.parentNode;\n }\n else {\n return false;\n }\n }\n return false;\n }", "hasParent(...$p) {\n const tests = $p.map(p => p._el);\n let parent = this._el.parentNode;\n while (parent) {\n if (isOneOf(parent, ...tests))\n return true;\n parent = parent.parentNode;\n }\n return false;\n }", "function hasParent(element, parent) {\n if (element.tagName.toLowerCase() === 'html') {\n return false; }\n \n if (element.parentNode.tagName.toLowerCase() === parent.toLowerCase()) {\n return true;\n } else {\n return hasParent(element.parentNode, parent);\n }\n }", "function isNodeContainedBy(parent) {\n var cursor = node.parent;\n while (cursor) {\n if (cursor == parent)\n return true;\n cursor = cursor.parent;\n }\n return false;\n }", "function isInView(child, parent)\n{\n var cRect = child[0].getBoundingClientRect();\n var pRect = parent[0].getBoundingClientRect();\n \n if(cRect.top > pRect.top && cRect.bottom < pRect.bottom)\n return true;\n else\n return false;\n}", "insert(element){\n //Does this QTree boundary contain this element\n if(!this.boundary.contains(element.position.x, element.position.y)){\n return false;\n }\n\n //Add element if max capacity hasn't been reached.\n if((this.elements != null) && (this.elements.length < this.capacity)){\n this.elements.push(element);\n\n //Set elements group to this tree\n element.setGroup(this);\n\n return true;\n }\n\n //If get to here, then max capacity has been reached\n //Subdivide if not divided already.\n if(!this.isParent){\n this.subdivide();\n }\n\n //Pass this element to child QuadTree\n if(this.northeast.insert(element)){ return true; }\n else if(this.northwest.insert(element)){ return true; }\n else if(this.southeast.insert(element)){ return true; }\n else if(this.southwest.insert(element)){ return true; }\n }", "function hasParent(element, parent) {\n var elem = element;\n\n while (elem) {\n if (elem === parent) {\n return true;\n } else if (elem.parentNode) {\n elem = elem.parentNode;\n } else {\n return false;\n }\n }\n\n return false;\n}", "_hasLeftChild(parentIndex) {\n const leftChildIndex = (parentIndex * 2) + 1;\n return leftChildIndex < this.size();\n }", "tryToPlaceInContainer(\n\t\tv: Vec, \n\t\tblockToPlace: CasusBlock, \n\t\tctx: ?CanvasRenderingContext2D,\n\t\tisOuterContainer: boolean = false\n\t): boolean {\n\t\tif (!this.boundingBox.contains(v)) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (const child of this.getChildBlocks()) {\n\t\t\tif (child.tryToPlaceInContainer(v, blockToPlace, ctx)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "function mutation_ensurePreInsertionValidity(node, parent, child) {\n const parentNodeType = parent._nodeType;\n const nodeNodeType = node._nodeType;\n const childNodeType = child ? child._nodeType : null;\n /**\n * 1. If parent is not a Document, DocumentFragment, or Element node,\n * throw a \"HierarchyRequestError\" DOMException.\n */\n if (parentNodeType !== interfaces_1.NodeType.Document &&\n parentNodeType !== interfaces_1.NodeType.DocumentFragment &&\n parentNodeType !== interfaces_1.NodeType.Element)\n throw new DOMException_1.HierarchyRequestError(`Only document, document fragment and element nodes can contain child nodes. Parent node is ${parent.nodeName}.`);\n /**\n * 2. If node is a host-including inclusive ancestor of parent, throw a\n * \"HierarchyRequestError\" DOMException.\n */\n if (TreeAlgorithm_1.tree_isHostIncludingAncestorOf(parent, node, true))\n throw new DOMException_1.HierarchyRequestError(`The node to be inserted cannot be an inclusive ancestor of parent node. Node is ${node.nodeName}, parent node is ${parent.nodeName}.`);\n /**\n * 3. If child is not null and its parent is not parent, then throw a\n * \"NotFoundError\" DOMException.\n */\n if (child !== null && child._parent !== parent)\n throw new DOMException_1.NotFoundError(`The reference child node cannot be found under parent node. Child node is ${child.nodeName}, parent node is ${parent.nodeName}.`);\n /**\n * 4. If node is not a DocumentFragment, DocumentType, Element, Text,\n * ProcessingInstruction, or Comment node, throw a \"HierarchyRequestError\"\n * DOMException.\n */\n if (nodeNodeType !== interfaces_1.NodeType.DocumentFragment &&\n nodeNodeType !== interfaces_1.NodeType.DocumentType &&\n nodeNodeType !== interfaces_1.NodeType.Element &&\n nodeNodeType !== interfaces_1.NodeType.Text &&\n nodeNodeType !== interfaces_1.NodeType.ProcessingInstruction &&\n nodeNodeType !== interfaces_1.NodeType.CData &&\n nodeNodeType !== interfaces_1.NodeType.Comment)\n throw new DOMException_1.HierarchyRequestError(`Only document fragment, document type, element, text, processing instruction, cdata section or comment nodes can be inserted. Node is ${node.nodeName}.`);\n /**\n * 5. If either node is a Text node and parent is a document, or node is a\n * doctype and parent is not a document, throw a \"HierarchyRequestError\"\n * DOMException.\n */\n if (nodeNodeType === interfaces_1.NodeType.Text &&\n parentNodeType === interfaces_1.NodeType.Document)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert a text node as a child of a document node. Node is ${node.nodeName}.`);\n if (nodeNodeType === interfaces_1.NodeType.DocumentType &&\n parentNodeType !== interfaces_1.NodeType.Document)\n throw new DOMException_1.HierarchyRequestError(`A document type node can only be inserted under a document node. Parent node is ${parent.nodeName}.`);\n /**\n * 6. If parent is a document, and any of the statements below, switched on\n * node, are true, throw a \"HierarchyRequestError\" DOMException.\n * - DocumentFragment node\n * If node has more than one element child or has a Text node child.\n * Otherwise, if node has one element child and either parent has an element\n * child, child is a doctype, or child is not null and a doctype is\n * following child.\n * - element\n * parent has an element child, child is a doctype, or child is not null and\n * a doctype is following child.\n * - doctype\n * parent has a doctype child, child is non-null and an element is preceding\n * child, or child is null and parent has an element child.\n */\n if (parentNodeType === interfaces_1.NodeType.Document) {\n if (nodeNodeType === interfaces_1.NodeType.DocumentFragment) {\n let eleCount = 0;\n for (const childNode of node._children) {\n if (childNode._nodeType === interfaces_1.NodeType.Element)\n eleCount++;\n else if (childNode._nodeType === interfaces_1.NodeType.Text)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert text a node as a child of a document node. Node is ${childNode.nodeName}.`);\n }\n if (eleCount > 1) {\n throw new DOMException_1.HierarchyRequestError(`A document node can only have one document element node. Document fragment to be inserted has ${eleCount} element nodes.`);\n }\n else if (eleCount === 1) {\n for (const ele of parent._children) {\n if (ele._nodeType === interfaces_1.NodeType.Element)\n throw new DOMException_1.HierarchyRequestError(`The document node already has a document element node.`);\n }\n if (child) {\n if (childNodeType === interfaces_1.NodeType.DocumentType)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert an element node before a document type node.`);\n let doctypeChild = child._nextSibling;\n while (doctypeChild) {\n if (doctypeChild._nodeType === interfaces_1.NodeType.DocumentType)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert an element node before a document type node.`);\n doctypeChild = doctypeChild._nextSibling;\n }\n }\n }\n }\n else if (nodeNodeType === interfaces_1.NodeType.Element) {\n for (const ele of parent._children) {\n if (ele._nodeType === interfaces_1.NodeType.Element)\n throw new DOMException_1.HierarchyRequestError(`Document already has a document element node. Node is ${node.nodeName}.`);\n }\n if (child) {\n if (childNodeType === interfaces_1.NodeType.DocumentType)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert an element node before a document type node. Node is ${node.nodeName}.`);\n let doctypeChild = child._nextSibling;\n while (doctypeChild) {\n if (doctypeChild._nodeType === interfaces_1.NodeType.DocumentType)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert an element node before a document type node. Node is ${node.nodeName}.`);\n doctypeChild = doctypeChild._nextSibling;\n }\n }\n }\n else if (nodeNodeType === interfaces_1.NodeType.DocumentType) {\n for (const ele of parent._children) {\n if (ele._nodeType === interfaces_1.NodeType.DocumentType)\n throw new DOMException_1.HierarchyRequestError(`Document already has a document type node. Node is ${node.nodeName}.`);\n }\n if (child) {\n let elementChild = child._previousSibling;\n while (elementChild) {\n if (elementChild._nodeType === interfaces_1.NodeType.Element)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert a document type node before an element node. Node is ${node.nodeName}.`);\n elementChild = elementChild._previousSibling;\n }\n }\n else {\n let elementChild = parent._firstChild;\n while (elementChild) {\n if (elementChild._nodeType === interfaces_1.NodeType.Element)\n throw new DOMException_1.HierarchyRequestError(`Cannot insert a document type node before an element node. Node is ${node.nodeName}.`);\n elementChild = elementChild._nextSibling;\n }\n }\n }\n }\n}", "checkParent(child, parent) {\n if (this.heap[child].f < this.heap[parent].f)\n return true;\n return false;\n }", "hasParent(){\n return this.getParent() != null;\n }", "function Browser_IsValidParent(html)\n{\n\t//only if it has a parent and the parent is a valid node\n\treturn html.parentNode != null && (html.parentNode.nodeType == 1 || html.parentNode.nodeType == 11);\n}", "hasLeftChild(parentIndex) {\n return this.getLeftChildIndex(parentIndex) < size;\n }", "function _hasNonUiChildren(parent) {\n return Array.from(parent.getChildren()).some(\n (child) => !child.is('uiElement')\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert suit to entity code
translateSuitToEntityCode(){ return this.suitObjects[`${this.randomSuitName0 }`]; }
[ "function ecode(entity) /* (entity : entity) -> int */ {\n return entity.ecode;\n}", "function mapGadQuestion4ToCode(entity){\n\n\tswitch(entity){\n\t\tcase 'not at all':\n\t\t\treturn 'at0024';\n\t\t\tbreak;\n\t\tcase 'several days':\n\t\t\treturn 'at0025';\n\t\t\tbreak;\n\t\tcase 'more than half the days':\n\t\t\treturn 'at0026';\n\t\t\tbreak;\n\t\tcase 'nearly every day':\n\t\t\treturn 'at0027';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn 'at0024';\n\t}\n}", "function mapGadQuestion5ToCode(entity){\n\n\tswitch(entity){\n\t\tcase 'not at all':\n\t\t\treturn 'at0029';\n\t\t\tbreak;\n\t\tcase 'several days':\n\t\t\treturn 'at0030';\n\t\t\tbreak;\n\t\tcase 'more than half the days':\n\t\t\treturn 'at0031';\n\t\t\tbreak;\n\t\tcase 'nearly every day':\n\t\t\treturn 'at0032';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn 'at0029';\n\t}\n}", "getSuit(){\n\n\t\tif (this.suit=='Spades'){\n\t\t\treturn '♠';\n\t\t}\n\n\t\telse if (this.suit=='Hearts'){\n\t\t\treturn '♥';\n\t\t}\n\t\telse if (this.suit=='Diamonds'){\n\t\t\treturn '♦';\n\t\t}\n\n\t\telse if (this.suit=='Clubs'){\n\t\t\treturn'♣';\n\t\t}\n\n\n\t}", "function determineSuitSymbol(suit) {\n switch(suit) {\n case 's':\n return \"&#9824\";\n case 'c':\n return \"&#9827\";\n case 'd':\n return \"&#9830\";\n case 'h':\n return \"&#9829\";\n }\n}", "function suit(cardId) {\n\n var fl = Math.floor(cardId / 13);\n \n if (fl == 0) {\n return 'C';\n } \n else if (fl == 1) {\n return 'D';\n }\n else if (fl == 2) {\n return 'H';\n }\n else {\n return 'S';\n }\n\n return false;\n}", "function entityNameEncode(origStr) {\r\r var i,j, retStr;\r\r retStr = origStr; \r\r var charCode, hasEntity = false;\r\r for (i=0; i<retStr.length && !hasEntity; i++) {\r charCode = retStr.charCodeAt(i);\r // if high-ASCII, \", &, <, or >\r hasEntity = (charCode > 127 || charCode == \"\\x22\" || charCode == \"\\x26\" || charCode == \"\\x3C\" || charCode == \"\\x3E\");\r //DEBUG: for Japanese, don't encode if high-ASCII. Need to modify the previous line for the J release.\r }\r\r if (hasEntity) { // iff entity found, entity-encode string\r oldStr = retStr; //copy string\r retStr = \"\"; //and build new one\r for (i=0; i<oldStr.length; i++) {\r charCode = oldStr.charCodeAt(i);\r theChar = oldStr.charAt(i);\r if (charCode > 127 || charCode == \"\\x22\" || charCode == \"\\x26\" || charCode == \"\\x3C\" || charCode == \"\\x3E\") { \r for (j=0; j<ENTITY_MAP.length-1; j+=2) { //search map\r if (ENTITY_MAP[j] == theChar) { //if found\r theChar = ENTITY_MAP[j+1]; //set theChar to matching entity\r break;\r }\r }\r if (j >= ENTITY_MAP.length) { //if not found in map\r theChar = '&#' + parseInt(charCode) + ';'; //set to integer\r }\r }\r retStr += theChar; //append char to string\r }\r }\r\r return retStr;\r}", "_convertEntity(entity) {\n // Return IRIs and blank nodes as-is\n if (entity.type !== 'literal')\n return entity.value;\n else {\n // Add a language tag to the literal if present\n if ('language' in entity)\n return '\"' + entity.value + '\"@' + entity.language;\n // Add a datatype to the literal if present\n if (entity.datatype !== 'http://www.w3.org/2001/XMLSchema#string')\n return '\"' + entity.value + '\"^^' + entity.datatype;\n // Otherwise, return the regular literal\n return '\"' + entity.value + '\"';\n }\n }", "function sfenToPieceCode (piece) {\n // if promoted, put promotion sign in front\n if (piece.length === 2) {\n piece = piece[1] + piece[0];\n }\n\n // white piece\n if (piece.toLowerCase() === piece) {\n return 'w' + piece.toUpperCase();\n }\n\n // black piece\n return 'b' + piece;\n }", "static convertEntity (entity)\n {\n // Return IRIs and blank nodes as-is\n if (entity.type !== 'literal')\n return JsonLdParser.isValid(entity.value);\n\n // Add a language tag to the literal if present\n if ('language' in entity)\n return '\"' + entity.value + '\"@' + entity.language;\n // Add a datatype to the literal if present\n if (entity.datatype !== 'http://www.w3.org/2001/XMLSchema#string')\n return '\"' + entity.value + '\"^^' + entity.datatype;\n // Otherwise, return the regular literal\n return '\"' + entity.value + '\"';\n }", "function convertEntity(entity) {\n // Return IRIs and blank nodes as-is\n if (entity.type !== 'literal')\n return entity.value;\n else {\n // Add a language tag to the literal if present\n if ('language' in entity)\n return '\"' + entity.value + '\"@' + entity.language;\n // Add a datatype to the literal if present\n if (entity.datatype !== 'http://www.w3.org/2001/XMLSchema#string')\n return '\"' + entity.value + '\"^^' + entity.datatype;\n // Otherwise, return the regular literal\n return '\"' + entity.value + '\"';\n }\n}", "function pieceCodetoSfen (piece) {\n let pieceCodeLetters = piece.split('');\n let promoted = pieceCodeLetters[2] || \"\";\n\n // white piece\n if (pieceCodeLetters[0] === 'b') {\n return promoted + pieceCodeLetters[1].toUpperCase();\n } \n\n // black piece\n return promoted + pieceCodeLetters[1].toLowerCase();\n }", "function convertEntity(entity) {\n // Return IRIs as-is\n if (entity.type === 'IRI')\n return entity.value;\n // Add a language tag to the literal if present\n if ('language' in entity)\n return '\"' + entity.value + '\"@' + entity.language;\n // Add a datatype to the literal if present\n if (entity.datatype !== 'http://www.w3.org/2001/XMLSchema#string')\n return '\"' + entity.value + '\"^^<' + entity.datatype + '>';\n // Otherwise, return the regular literal\n return '\"' + entity.value + '\"';\n}", "function CardSuitToCss(suit) {\n switch(suit) {\n case CONSTANTS.CLUBS_SUIT:\n return \"C\";\n case CONSTANTS.SPADES_SUIT:\n return \"P\";\n case CONSTANTS.DIAMONDS_SUIT:\n return \"D\";\n case CONSTANTS.HEARTS_SUIT:\n return \"H\";\n }\n return null;\n}", "function getSuitSymbol(suit) {\r\n\tswitch (suit) {\r\n\t\tcase \"diams\":\r\n\t\t\treturn \"♦\";\r\n\t\tcase \"hearts\":\r\n\t\t\treturn \"♥\"\r\n\t\tcase \"clubs\":\r\n\t\t\treturn \"♣\";\r\n\t\tcase \"spades\":\r\n\t\t\treturn \"♠\";\r\n\t\tdefault:\r\n\t\t\treturn \"\";\r\n\t}\r\n}", "function fenToPieceCode(piece) {\n // black piece\n if (piece.toLowerCase() === piece) {\n return 'b' + piece.toUpperCase();\n }\n // white piece\n return 'w' + piece.toUpperCase();\n}", "function fenToPieceCode(piece) {\n // black piece\n if (piece.toLowerCase() === piece) {\n return 'b' + piece.toUpperCase();\n }\n\n // white piece\n return 'w' + piece.toUpperCase();\n}", "function fenToPieceCode(piece) {\n // black piece\n if (piece.toLowerCase() === piece) {\n return 'b' + piece.toUpperCase();\n }\n\n // white piece\n return 'w' + piece.toUpperCase();\n}", "_normalizeEntities(ex) {\n let renameMap = Object.create(null);\n let countMap = Object.create(null);\n \n let inString = false;\n let anyRename = false;\n const newCode = [];\n const code = ex.target_code.split(' ');\n for (let i = 0; i < code.length; i++) {\n const token = code[i];\n if (token === '\"') {\n inString = !inString;\n newCode.push(token);\n continue;\n }\n if (inString) {\n newCode.push(token);\n continue;\n }\n if (token in renameMap) {\n newCode.push(renameMap[token]);\n \n // if we renamed a number into a measure, skip the unit\n if (token.startsWith('NUMBER_') && renameMap[token].startsWith('MEASURE_'))\n i++;\n }\n \n const match = ENTITY_MATCH_REGEX.exec(token);\n if (match === null) {\n newCode.push(token);\n continue;\n }\n \n let [,type,] = match;\n \n // collapse NUMBER_ followed by unit into measure or duration\n if (type === 'NUMBER' && i < code.length-1 && code[i+1].startsWith('unit:')) {\n const unit = code[i+1].substring('unit:'.length);\n const baseunit = new ThingTalk.Type.Measure(unit).unit;\n if (baseunit === 'ms')\n type = 'DURATION';\n else\n type = 'MEASURE_' + baseunit;\n // skip the unit\n i++;\n }\n \n let newIdx;\n if (type in countMap)\n newIdx = countMap[type] + 1;\n else\n newIdx = 0;\n countMap[type] = newIdx;\n \n const newToken = type + '_' + newIdx;\n if (newToken !== token)\n anyRename = true;\n renameMap[token] = newToken;\n newCode.push(newToken);\n }\n ex.target_code = newCode.join(' ');\n if (!anyRename)\n return;\n ex.preprocessed = ex.preprocessed.split(' ').map((token) => {\n if (token in renameMap)\n return renameMap[token];\n else\n return token;\n }).join(' ');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given object is an instance of Assessment. This is designed to work even when multiple copies of the Pulumi SDK have been loaded into the same process.
static isInstance(obj) { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Assessment.__pulumiType; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Association.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RoleAssignment.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PermissionSetInlinePolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PrincipalAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Organization.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === AccountAssignment.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DomainAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Authorizer.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RolePolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === AttestationAtResourceGroup.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === AggregateAuthorization.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === WebAclAssociation.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === AnalyticsApplication.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Policy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ResourcePolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PolicyDefinitionAtManagementGroup.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === OrganizationManagedRule.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Analyzer.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PolicyAttachment.__pulumiType;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to filter through the venue object and only keep the necessary fields Retrive the venue fields by: id,name,price,rating,category,location and url
function parse_venue_object(venues) { var venues_list=[]; for (var i=0;i<venues.length;i++) { var venue_id = venues[i]['id']; var venue_name = venues[i]['name']; //not all vendors have prices information included, but the data object always a tag of price var venue_price = venues[i]['price']; if(typeof venue_price != "undefined") { venue_price = venues[i]['price']['tier']; } else { venue_price = ""; } var venue_rating = venues[i]['rating']; if(typeof venue_rating =="undefined") { venue_rating = ""; } venue_url = venues[i]['url']; //some vendors don't have a specifed category and some have more than one category //find the first category that matches one of the ids within the bar sub-category var venue_categoryName; var venue_category = venues[i]['categories']; for (var j=0;j<venue_category.length;j++) { if(typeof venue_category[j]!="undefined") { var categoryId = venue_category[j].id; if(_.values(categories).indexOf(categoryId)!=-1) { venue_categoryName = venue_category[j].name; } } } if(typeof venue_categoryName == "undefined") { venue_categoryName = "Nightlife Spot"; } var venue_location = venues[i]['location']; var venue_info= { id:venue_id, name:venue_name, price:venue_price, rating:venue_rating, category:venue_categoryName, location:venue_location, url:venue_url }; venues_list.push(venue_info); } return venues_list; }
[ "function venue_with_price_and_rating(venues,price,rating)\n{\n filtered_list=[];\n \n var isValid = function(param) {\n \treturn typeof param!='undefined' && param!=\"\";\n }; \n \n _.each(venues,\n \tfunction(venue,i,venues) {\n \tvenue_price = venues[i]['price'];\n \tvenue_rating = venues[i]['rating'];\n \t\n \tif ( (!isValid(price) || (isValid(price) && (!isValid(venue_price) || venue_price.tier == price)))\n \t\t\t&&\n \t\t (!isValid(rating) || (isValid(rating) && (!isValid(venue_rating) || venue_rating >= rating))) ) {\n \t\t\tfiltered_list.push(venues[i]);\n \t}\t\t \t\t\n \t}\n );\n \n final_list = parse_venue_object(filtered_list);\n return final_list;\n}", "function filterVenues() {\n var venueName;\n var search = self.filterQuery().toLowerCase();\n\n self.venues().forEach(function (venue) {\n venueName = venue.name.toLowerCase();\n\n if (venueName.indexOf(search) >= 0) {\n venue.visible(true);\n venue.marker.setMap(self.map);\n } else {\n venue.visible(false);\n venue.marker.setMap(null);\n }\n });\n }", "function filterByVenue() {\n\t\tvar href;\n\t\tvar venue = document.getElementById('venue-filter').value;\n\t\t// IE Fix - window.location.origin doesn't exist.\n\t\tif (window.location.origin === undefined) {\n\t\t window.location.origin = window.location.protocol + \"//\" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');\n\t\t}\n\t\tvar base = window.location.origin + window.location.pathname;\n\n\t\tif (venue !== 'default' && venue) {\n\t\t\tif (venue !== 'all') {\n\t\t\t\thref = base + '?venue=' + venue;\n\t\t\t} else {\n\t\t\t\thref = base;\n\t\t\t}\n\t\t}\n\n\t\twindow.location.href = href;\n\t}", "doFiltering()\n {\n // Result Object.\n let notPossible = [];\n let results = new Results();\n\n // Process Venues.\n for (let i=0; i<this._venues.length; i++) {\n let venue = this._venues[i];\n let venuestatus = true;\n let tmpvenues = [];\n\n venue.drinks = this.caseFix(venue.drinks);\n venue.food = this.caseFix(venue.food);\n\n // Process People.\n for (let k=0; k<this._people.length; k++) {\n let caneat = false;\n let candrink = false;\n let person = this._people[k];\n\n person.drinks = this.caseFix(person.drinks);\n person.wont_eat = this.caseFix(person.wont_eat);\n\n // More food at the venue than they wont eat, sorted\n //if (!notPossible[venue.name]) {\n if (venue.food.length>person.wont_eat.length || venue.food.length == 0) {\n caneat = true;\n } else if (venue.food){\n /* Only now where venue has same option count as person dislike count */\n for (let i=0;i<venue.food.length;i++) {\n if (!person.wont_eat.includes(venue.food[i])) {\n caneat = true;\n }\n }\n }\n //}\n\n // We can futher improve performance by not testing\n // if the user is already not allowed via eating. For More\n // data we would inlcude it.\n //if (caneat) {\n candrink = venue.drinks.some(v => person.drinks.includes(v));\n //}\n\n /* Avoid or not? */\n if (!caneat||!candrink) {\n venuestatus = false;\n notPossible[venue.name] = 1;\n results.addAvoidVenue({\n name: person.name,\n restaurant: venue.name,\n cant_eat: !caneat,\n cant_drink: !candrink\n });\n }\n }\n\n // Good venue!\n if (venuestatus) {\n results.addAcceptableVenue({\n venue: venue\n });\n }\n }\n\n return results.getDetails();\n }", "function getVenueInfo (data) {\n const venueWrapperList = data.response.groups[0].items\n return venueWrapperList\n .map(venueWrapper => venueWrapper.venue)\n .map(venue => {\n return { name: venue.name, rating: venue.rating}\n })\n }", "function filterVenues() {\n let result = [];\n\n venues.forEach((venue) => {\n //Store the venue's location\n let v_lat = venue.location.lat;\n let v_lon = venue.location.lng;\n\n //Calculate the distance between the user's position and the venue\n let distance = getDistance(lat, lon, v_lat, v_lon);\n\n //If the venue lies within the radius push it to the resulting array\n if (distance <= radius) {\n result.push(venue);\n }\n });\n\n return result;\n}", "_getVenueDetails(venueId) {\n return axios.get(Constant.BASEURL+venueId+\"?v=20170101&client_id=\"+Constant.CLIENTID+\"&client_secret=\"+Constant.CLIENTSECRETID);\n }", "static filterLocationData(data) {\n return {\n 'name': data.name,\n 'city': data.city,\n 'hours': data.hours,\n 'description': data.description,\n 'supervisors': data.supervisors,\n 'timestamp': data.timestamp,\n };\n }", "function _generateVenueModel(venue) {\n var NO_ADDRESS_FOUND = WinJS.Resources.getString(\"addFsMenuSearchResultStep_noAdressFound\").value;\n var NO_IMG_BACKGROUND_COLOR = '#fff';\n var IMG_BACKGROUND_COLOR = 'transparent';\n return {\n name: venue.name,\n address: (venue.location.address) ? venue.location.address : NO_ADDRESS_FOUND,\n bgColor: (venue.categories[0] && venue.categories[0].icon && venue.categories[0].icon.prefix && venue.categories[0].icon.suffix) ? IMG_BACKGROUND_COLOR : NO_IMG_BACKGROUND_COLOR,\n bgImg: (venue.categories[0] && venue.categories[0].icon) ? 'url(' + venue.categories[0].icon.prefix + 'bg_32' + venue.categories[0].icon.suffix + ')' : '',\n }\n }", "onFilterFull() {\n this.lots = this.lots.filter(lot => lot.vehicle);\n }", "async function getEventfulVenues() {\n const defaultSearchCoords = \"38.9072,-77.0369\";\n const queryURL = \"http://api.eventful.com/json/venues/search\"\n const queryString = `${queryURL}?app_key=${eventfulApiKey}&category=bar_nightlife&page_size=999&location=${encodeURIComponent(\"washington, dc\")}`;\n console.log(\"Querying eventful\", queryString);\n return axios.get(queryString)\n .then( (results) => {\n results.data.venues.venue.forEach( (item) => {\n let images = [];\n if (item.image && item.image.medium)\n images.push(item.image.medium.url)\n if (item.image && item.image.url)\n images.push(item.image.url)\n if (item.image && item.image.small)\n images.push(item.image.small.url)\n if (item.image && item.image.thumb)\n images.push(item.image.thumb.url)\n\n const venueObj = {\n name: item.venue_name,\n event_count: item.event_count,\n description: item.description,\n type: item.venue_type,\n eventful_id: item.id,\n address: {\n street: item.address,\n city: item.city_name,\n state: item.region_abbr,\n zipcode: item.postal_code,\n longitude: item.longitude,\n latitude: item.latitude,\n },\n images: images,\n url: item.url, // NOTE: This is the evenful URL, not venue\n staff: (item.owner) ? [{ name: item.owner, role: \"owner\"}] : [],\n };\n Venue.create(venueObj, (doc) => console.log('item added', doc) );\n });\n return results;\n });\n}", "function filterProperties(url) {\n\tvar low = $(\"#lowPriceId\").val();\n\tvar high = $(\"#highPriceId\").val();\n\tif (low && high) {\n\t\tvar request = {};\n\t\trequest.lowPrice = low;\n\t\trequest.highPrice = high;\n\t\tmakeJsonAjaxCall({\n\t\t\turl : url,\n\t\t\trequestObj : request,\n\t\t\tonSuccess : function(req, status, res) {\n\t\t\t\tif (res != null && res != '' && res != undefined) {\n\t\t\t\t\tpopulateData(res.data);\n\t\t\t\t}\n\t\t\t},\n\t\t\tonError : function(req, status, error) {\n\t\t\t}\n\t\t});\n\t}\n\n}", "function populateVenueFilter(venues) {\n\t\tvar venueFilter = document.getElementById('venue-filter');\n\t\t\t\tvenueFilter.addEventListener('change', filterByVenue);\n\n\t\tfor (var i = 0; i < venues.length; i++) {\n\t\t\tvar option = document.createElement('option');\n\t\t\t\t\toption.value = venues[i].toLowerCase();\n\t\t\t\t\toption.innerHTML = venues[i];\n\n\t\t\tvenueFilter.appendChild(option);\n\t\t}\n\t}", "function filterPopulate(parsedData)\n{\n\tvar key = parsedData.vehicles; \t//determine value for populate \n\n\tif (key == undefined)\n\t\tkey = 'x';\n\n\tif (key == 'x')\n\t\tpassPopulate(parsedData, key); \t\n\t\n\n\telse \n\t\tvehPopulate(parsedData, key);\n}", "getVenue({ venue_id }) {\n const urlString =\n this.apiUrl +\n this.apiFeature +\n \"/\" +\n venue_id +\n \"?\" +\n querystring.stringify(this.credentials);\n return request(urlString);\n }", "function filterVolunteers(volunteer) {\n console.log('volunteer: ' + volunteer.firstName + \" \" + volunteer.lastName);\n\n // By default, remove subscriber from list. Tests will change to true\n var keep_volunteer = false;\n\n // Subscriber Filter\n if ( (req.query.subscribers == \"on\") && (volunteer.subscribe == false) ) {\n return false;\n }\n\n // Driver Filter\n if ( (req.query.drivers == \"on\") && (volunteer.reliableTransportation == false) ) {\n return false;\n }\n\n // Family Participation\n if ( (req.query.family_participation == \"on\") && (volunteer.familyParticipation == false) ) {\n return false;\n }\n\n // Opportunity\n if ( (req.query.opportunity != undefined) && (req.query.opportunity != \"\") ){\n console.log('this includes an opp query: ', req.query.opportunity);\n // console.log('volunteer.opportunityCategories:', volunteer.opportunityCategories);\n for (var i=0; i < volunteer.opportunityCategories.length; i++) {\n // if it matches, keep this volunteer in the list\n if (volunteer.opportunityCategories[i] == req.query.opportunity) {\n console.log('keeping for opportunity: ', req.query.opportunity);\n keep_volunteer = true;\n }\n }\n\n // no match! Remove volunteer from list\n if (keep_volunteer == false) {\n console.log('throwing out: didnt match opportunity ', req.query.opportunity);\n return false;\n }\n }\n\n // Language\n if ( (req.query.language != undefined) && (req.query.language != \"\") ){\n console.log('this includes a language query: ', req.query.language);\n for (var i=0; i < volunteer.languages.length; i++) {\n // if it matches, keep this volunteer in the list\n if (volunteer.languages[i] == req.query.language) {\n console.log('keeping for language: ', req.query.language);\n keep_volunteer = true;\n }\n }\n\n // no match! Remove volunteer from list\n if (keep_volunteer == false) {\n console.log('throwing out: didnt match language ', req.query.language);\n return false;\n }\n }\n\n // Hear Abouts\n if ( (req.query.hear_about != undefined) && (req.query.hear_about != \"\") ) {\n if (volunteer.hearAboutUs == req.query.hear_about) {\n console.log('keeping for hear_about: ', req.query.hear_about)\n keep_volunteer = true;\n }\n // no match! Remove volunteer from list\n console.log('throwing out: didnt match anything hear_about: ', req.query.hear_about);\n if (keep_volunteer == false) {\n return false;\n }\n }\n\n // Affiliation\n if ( (req.query.affiliation != undefined) && (req.query.affiliation != \"\") ) {\n if (volunteer.affiliation == req.query.affiliation) {\n console.log('keeping for affiliation: ', req.query.affiliation);\n keep_volunteer = true;\n }\n // no match! Remove volunteer from list\n if (keep_volunteer == false) {\n console.log('throwing out: didnt match anything affiliation: ', req.query.affiliation);\n return false;\n }\n }\n\n\n // no query\n else {\n return true;\n }\n\n // queries but didn't return yet\n console.log('done filtering. keep_volunteer: ', keep_volunteer);\n return keep_volunteer;\n }", "static filterLocationInputData(data) {\n return {\n 'name': data.name,\n 'city': data.city,\n 'hours': data.hours,\n 'description': data.description,\n 'supervisors': data.supervisors,\n };\n }", "function filterSurvey(survey) {\n var filteredSurvey = {};\n filteredSurvey.name = survey.name;\n filteredSurvey.slug = survey.slug;\n filteredSurvey.id = survey.id;\n return filteredSurvey;\n}", "salongsFilter(salongs, filters = {\n price: {\n start: '',\n end: ''\n },\n type: {\n text: ''\n }\n }) {\n let salongsTemp = salongs;\n\n // Filter on price\n if(filters.price.start !== '') {\n salongsTemp = _.filter(salongs, (o) => { \n return (o.price >= filters.price.start && o.price <= filters.price.end);\n });\n }\n\n // Filter on type\n if(filters.type.text !== '') {\n salongsTemp = _.filter(salongsTemp, (t) => { \n return (t.types.indexOf(filters.type.text) > -1);\n });\n }\n\n return salongsTemp;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the globals currentProblemIndex, partialProblems, and currentProblem from the currentproblemindex and partialproblems fields of the currently logged in student in order to preserve the problem state for the student.
function getStudentInfo () { //get the currentProblemIndex currentProblemIndex = StudentModel.find({_id: Meteor.userId()}).fetch()[0].currentproblemindex; if (currentProblemIndex == undefined) { currentProblemIndex == 0; Meteor.call('updateStudentModel', 'currentproblemindex', 0); } //get the partialProblems partialProblems = StudentModel.find({_id: Meteor.userId()}).fetch()[0].partialproblems; if (partialProblems == undefined) { makeProblems(); Meteor.call('updateStudentModel', 'partialproblems', partialProblems); } //get the currentProblem currentProblem = partialProblems[currentProblemIndex]; //get the partialproofcolor colorIndex = StudentModel.find({_id: Meteor.userId()}).fetch()[0].partialproofcolor; if (colorIndex == undefined) { colorIndex = 0; Meteor.call('updateStudentModel', 'partialproofcolor', 0); } document.getElementById('colorSelectPartial').selectedIndex = colorIndex; var currentdragcolorname = colorSchemes[colorIndex].dragcolorname; var currentdropcolorname = colorSchemes[colorIndex].dropcolorname; var currentrulecolorname = colorSchemes[colorIndex].rulecolorname; changeColors(colorSchemes[colorIndex]); var currenthtml = $('#ruleInstructionsPartial').html(); var newhtml = currenthtml.replace(currentdragcolorname, colorSchemes[colorIndex].dragcolorname); newhtml = newhtml.replace(currentdropcolorname, colorSchemes[colorIndex].dropcolorname); newhtml = newhtml.replace(currentrulecolorname, colorSchemes[colorIndex].rulecolorname) $('#ruleInstructionsPartial').html(newhtml); }
[ "function loadSavedProblems(lesson, currSet){\n var problems = currSet.problems;\n // Update problemNum variable so numbering appears correctly when adding problems\n problemNum = problems.length;\n\n // Add input fields for the saved problems\n for(var i = 1; i < problems.length; i++){\n newProblemField(i);\n }\n\n // Insert saved data into the fields\n for(var i = 0; i < problems.length; i++){\n $(\"#problem-\" + i + \"-input\").val(problems[i].question);\n $(\"#solution-\" + i + \"-input\").val(problems[i].solution);\n }\n }", "function setProblem(new_problem)\n{\n current_problem = new_problem;\n var problems = document.getElementById(\"problems\").getElementsByTagName(\"a\");\n for (var p in problems) {\n problems[p].className = ((problems[p].id == (\"problem_\" + new_problem)) ? \"active\" : \"\");\n }\n\n updateSolutionTab();\n updateProblemTab();\n}", "function updateProblem() {\n stateProblem.currentProblem = generateProblem();\n problemElement.innerHTML = `${stateProblem.currentProblem.firstNumber} ${stateProblem.currentProblem.operator} ${stateProblem.currentProblem.secondNumber}`;\n\n //clear up the input to make empty\n ourField.value = \"\";\n ourField.focus();\n}", "function setState() {\n console.log('setting state');\n // Make sure we're getting the right thing from edX.\n stateStr = arguments.length === 1 ? arguments[0] : arguments[1];\n // edX stores the state as stringified JSON. Parse it.\n JSProblemState = JSON.parse(stateStr);\n // Set the live state to the stored state (the learner's previous answer).\n let d = window.parent.document;\n d.querySelectorAll('.multianswer').forEach(function (e, i) {\n e.value = JSProblemState.answers[i];\n console.log(e.value);\n });\n }", "function setNextProblem()\n{\n\t//\tincrementar nro de problema\n\tif(++nProblema > CANTPROBLEMAS ) {\n\t\t//\treset nProblema \n\t\tnProblema = 1;\n\t}\n\tsetStorage(\"nroProblema\", nProblema);\n}", "function resetSyncVars(){\n //nullify the project add vars\n $scope.addProjectConfig = {};\n $scope.selectedProject = {};\n $scope.selectedIteration = {};\n vstsTeamsArray =[];\n nextTeamsPage = 0;\n loadedAreaPaths = [];\n areaPathsFlattened = false;\n }", "function unMarkCurrentProblem_reload(){\n unMarkCurrentProblem();\n location.reload();\n}", "function initProblem()\n\t{\n\t\tif (reloading)\n\t\t{\n\t\t\tapp.loadingBox(app.style.probCreateText, app.style.probCreateBg, app.style.probCreateTime);\n\t\t\treloading = false;\n\t\t}\n\t\telse\n\t\t\tapp.loadingBox();\n\n\t\tpromise = view.assignmentManager();\n\t\tprobId = view.getProbId();\n\t}", "function markCurrentProblem_reload(){\n markCurrentProblem();\n location.reload();\n}", "setProblem() {\n // change this to position !!!!!\n if (board[config.current].hasOwnProperty(this.props.owner)) {\n if (this.data.Session === undefined) {\n this.data.Session = [];\n }\n\n var sess =\n this.props.qrt +\n '/' +\n this.week +\n '/' +\n this.session.toString();\n\n // if adding a new session\n var sess_names = this.data.Session.map(v => v.Name);\n if (sess_names.indexOf(sess) === -1) {\n this.data.Session.push({\n Name:\n this.props.qrt +\n '/' +\n this.week +\n '/' +\n this.session.toString(),\n Ratings: {\n like: 0,\n dislike: 0\n },\n SolutionViews: 0,\n HintViews: 0,\n Clicks: 0\n });\n var updates = {};\n updates[\n '/' +\n this.props.qrt +\n '/' +\n this.week +\n '/' +\n this.session.toString() +\n '/' +\n this.props.x\n ] = {\n tag: ''\n };\n updates[\n '/submissions/' + this.props.x + '/Session'\n ] = this.data.Session;\n firebase\n .database()\n .ref()\n .update(updates);\n\n this.setState({\n modal: [false, false, false, false, false]\n });\n } else {\n this.msg = (\n <Alert color=\"warning\">\n Sorry! This problem is already used in that session! ^^\n </Alert>\n );\n\n this.setState({\n modal: this.state.modal\n });\n }\n } else {\n this.msg = (\n <Alert color=\"warning\">\n Sorry! Only board members can set problems!\n </Alert>\n );\n this.setState({\n modal: this.state.modal\n });\n }\n }", "function setCurrent() {\n\t\tcurrentQ = allQ[iQ];\n\t\tcurrentA = allAns[iQ];\n\t\ttotal = iQ;\n\t\tpercentCorrect = parseInt((numCorrect/total)*100);\n}", "setBlankProblem(problemName) {\n // Create blank project (deep copy clone) and name\n this.problem = null;\n this.problem = jQuery.extend(true, {}, Problem);\n this.problem.name = problemName;\n // Add single category\n this.addCategory('');\n // Add two alternatives\n this.addAlternative('');\n this.addAlternative('');\n }", "function initStates()\n\t{\n\t\t// @FIXME/DG: This really needs to be moved out of this module!\n\t\t// Create a new state for each question. We're trying to limit memory allocation, but there's\n\t\t// no clean way to get around this.\n\t\tapp.problemList.each(function(val, key) {\n\t\t\tvar state = new app.pState();\n\n\t\t\t// Doubly link problem to state. This is a bit messy, but prevents a ton of\n\t\t\t// info from being duplicated. Should have an isolation layer instead.\n\t\t\tstate.set({\n\t\t\t\tproblem: val,\t// Link problem to state\n\t\t\t\tcorrectInARow: val.get('curStreak'),\n\t\t\t\tmaxStreak: val.get('maxStreak'),\n\t\t\t\tstatus: val.get('status')\n\t\t\t});\n\n\t\t\tval.set({state: state}, {silent:true});\t// Link state to problem\n\t\t});\n\t}", "function updateVariables() {\n currentScheduleIndex = getCurrentScheduleIndex();\n currentClassPeriodIndex = getCurrentClassPeriodIndex();\n}", "function updateProfileProblemStatus(data){\n\tconsole.log(\"update learner profile problem\");\n\tajax(APP.LEARNER_PROFILE_STATUS_UPDATE + \"?problem=\" + escape(JSON.stringify(APP.currentProblem)));\n}", "function updateProgress() {\n sportQuestionsIndex = localStorage.getItem('SportsQuestionsIndex');\n\n historyQuestionsIndex = localStorage.getItem('HistoryQuestionsIndex');\n\n scienceQuestionsIndex = localStorage.getItem('ScienceQuestionsIndex');\n\n religionQuestionsIndex = localStorage.getItem('ReligionQuestionsIndex');\n\n gamesQuestionsIndex = localStorage.getItem('GamesQuestionsIndex');\n}", "function setIndividualStudent(student) {\n\t\t\t\t\t\t\tvar data = filterDataByStudent(jsonData, student);\n\t\t\t\t\t\t\t$scope.individualStudent = ((data[0] !== null) && (data[0] !== undefined)) ? data[0]\n\t\t\t\t\t\t\t\t\t: null;\n\t\t\t\t\t\t}", "SET_CURRENT_QUESTION (state, currentQuestion) {\n state.currentQuestion = currentQuestion + 1;\n }", "saveLocal() {\n localStorage.setObject('problemData', this.problem);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close the MicroChain register process
function registerClose(subchainaddr) { logger.info("registerClose", subchainaddr); sendtx(baseaddr, subchainaddr, '0', '0x69f3576f'); }
[ "function handleCloseRegister() {\n setOpenRegister(false);\n }", "async function closeI2C() {\n await writeDemodReg(1, 1, 0x10, 1);\n }", "close() {\n /* Disconnect Trueno session */\n process.exit();\n }", "close() {\n this.api.destroyBuffer(this.wasmInputPtr);\n this.api.closeDecoder(this.decoder);\n\n this.decoder = null;\n this.wasmInputPtr = null;\n this.initialized = false;\n }", "listenOnRegisterClose() {\n\t\tthis.application.register.on('close', () => {\n\t\t\tthis.server.registerClosed(this.application.register);\n\t\t});\n\t}", "destroy() {\n if (this.socket && typeof this.socket.close === 'function')\n this.socket.close()\n delete Wire.register[this.id]\n }", "close() {\n if (phantom_instance != null) {\n phantom_instance.exit();\n phantom_instance = null;\n }\n }", "async close() {\n await this.exchangeBusyPromise;\n await this.device.releaseInterface(this.interfaceNumber);\n await gracefullyResetDevice(this.device);\n await this.device.close();\n }", "function sipUnRegister() {\n if (oSipStack) {\n oSipStack.stop(); // shutdown all sessions\n }\n}", "close () {\n this._registry.closeKey(this);\n }", "function sipUnRegister() {\n if (oSipStack) {\n oSipStack.stop(); // shutdown all sessions\n }\n }", "exitSpecialRegister(ctx) {\n\t}", "close()\n {\n gl.deleteProgram(this.handle);\n this.handle = null;\n }", "function closeHouseDetails(){\n ipc.send('ipc-close-house-detail', undefined);\n}", "function exit() {\n console.log(\"Quitting... \");\n i2c1.closeSync();\n process.exit();\n}", "function Close_Instruction() {\r\n}", "shutdown() {\n this.unload();\n }", "close() {\n if (!this.connectionId) return\n\n disconnect(this.connectionId)\n .then(()=>this.emit(\"close\"))\n .catch(err=>this.emit(\"error\", err))\n\n this.connectionId = null\n this.writeBuffer = null\n chrome.serial.onReceiveError.removeListener(this._recvErr)\n chrome.serial.onReceive.removeListener(this._recv)\n }", "function closeAll() {\n\t ftp.end();\n modbusInverterClient.close(callback=>{logger.log('info','RS485 serial port is closed');});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add tracks to the playlist that now exists in user's account
function addTracksToPlaylist(data, callback){ sessionStorage.songs = JSON.stringify(MASTER_TRACKLIST); sessionStorage.spotifyUserId = JSON.stringify(spotifyUserId); playlistId = data.id; sessionStorage.playlistId = JSON.stringify(playlistId); var tracks = []; for(var i = 0; i < MASTER_TRACKLIST.length; i++){ tracks.push(MASTER_TRACKLIST[i].id); } var tracksString = tracks.join(",spotify:track:"); var url = 'https://api.spotify.com/v1/users/' + spotifyUserId + '/playlists/' + playlistId + '/tracks?uris='+encodeURIComponent("spotify:track:"+tracksString); $.ajax(url, { method: 'POST', dataType: 'text', headers: { 'Authorization': 'Bearer ' + AUTHORIZATION_CODE, 'Content-Type': 'application/json' }, success: function(d) { callback(d, data.external_urls.spotify); }, error: function(r) { callback(null, null); } }); }
[ "async function syncPlaylist (playlist, tracks) {\n try {\n const results = { added: 0, removed: 0 }\n // Exit early on empty tracks.\n if (!tracks.length) return results\n const spotify = createSpotify()\n const uid = playlist.user\n const name = playlist.name\n\n // Search for user playlist.\n const result = await searchUserPlaylists(uid, name)\n\n // Store playlist ID if available.\n let pid = result[0] ? result[0].id : null\n\n if (!pid) {\n // Create user playlist if it doesn't exist.\n pid = await spotify.createPlaylist(uid, name)\n .then(response => response.body.id)\n .catch(e => console.log(e))\n }\n\n // Exit early if playlist couldn't be created.\n if (!pid) return\n\n // Get all track IDs from user playlist.\n const playlistTracks = await getAllUserPlaylistTracks(uid, pid)\n .then(response => response.map(item => item.track.id))\n .catch(e => console.log(e))\n\n if (playlistTracks) {\n // Build remove array to store tracks in playlist that are not included\n // within tracks argument.\n const remove = playlistTracks.reduce((items, item) => {\n const index = tracks.indexOf(item)\n if (index < 0) {\n results.removed = results.removed + 1\n tracks.splice(index, 1)\n items.push({ uri: `spotify:track:${item}` })\n }\n return items\n }, [])\n\n if (remove) {\n // Remove tracks from playlist.\n await removeAllTracksFromPlaylist(uid, pid, remove)\n .catch(e => console.log(e))\n }\n }\n\n if (tracks.length) {\n // Build tracks to add that are not present in playlist, so duplicated\n // tracks aren't added.\n const add = tracks.reduce((items, item) => {\n const index = playlistTracks.indexOf(item)\n if (index < 0) {\n results.added = results.added + 1\n items.push(`spotify:track:${item}`)\n }\n return items\n }, [])\n\n if (add.length) {\n // Add tracks to playlist.\n await addAllTracksToPlaylist(uid, pid, add)\n .catch(e => console.log(e))\n }\n }\n\n return results\n } catch (e) {\n throw e\n }\n}", "_addTrackToPlaylist(){\n let channel_id = this.query.channel_id;\n let track = this.query.track;\n\n DB.getChannelInfoByChannelId(channel_id, (info) => {\n if(info){\n let user_id = info.user_id;\n let playlist_id = info.playlist_id;\n let token = info.master_token;\n this.spotifyApi.setAccessToken(token);\n this.spotifyApi.addTracksToPlaylist(user_id, playlist_id, [track], {}, (err, data) => {\n if(err){\n console.log(err);\n }\n this.end();\n });\n }else{\n console.log(\"Error loading channel info: \" + channel_id);\n this.end();\n }\n });\n }", "function addUserPlaylist(userID, playlistObj){}", "addToPlaylist(track, playlistName) {\n let self = this;\n // If playlist exists\n if(this.playlists.indexOf(playlistName) > -1) {\n this.db.playlists.find({ name: playlistName }).exec(function(err, docs) {\n if (!err) {\n let newPlaylist = docs[0];\n newPlaylist.tracks.push(track._id);\n newPlaylist.count++;\n newPlaylist.duration += track.duration;\n self.db.playlists.update({ name: playlistName }, newPlaylist, {}, function(err) {\n if (!err) {\n self.db.playlists.persistence.compactDatafile();\n console.log(\"Track \" + track.title + \" added to playlist \" + playlistName);\n }\n });\n }\n });\n }\n }", "addTracks() {\n let { playlistId, tracks } = this.state;\n spotifyApi.addTracksToPlaylist(playlistId, tracks);\n }", "function addTrackToPlaylist (trackId, playlistId) {\n library.playlists[playlistId].tracks[-1] = trackId;\n}", "async function addAllTracksToPlaylist (uid, pid, tracks) {\n try {\n const spotify = createSpotify()\n // Batch size.\n const limit = 100\n while (tracks.length) {\n const batch = tracks.splice(0, limit)\n // Add tracks.\n await spotify.addTracksToPlaylist(uid, pid, batch)\n .catch(e => console.log(e))\n }\n } catch (e) {\n throw e\n }\n}", "savePlaylist(user_id, data, accessToken, tracks){\n //trigger the Spotify object's savePlaylist method\n Spotify.savePlaylist(user_id, data, accessToken, tracks).then(() => {\n //clear the Apps playlist state once the playlist has been saved to Spotify\n this.setState({\n playlist: []\n });\n });\n }", "function helper_addTrackToPlaylist(playlistId){\n for (var i in library.playlists[playlistId].tracks){\n console.log(\"tracks in the passed playlist:\",library.playlists[playlistId].tracks[i]);\n }\n }", "async addSongsToPlaylist(playlistID, trackURIs) {\n\n const accessToken = this.getAccessToken();\n const headers = {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json'\n };\n const body = JSON.stringify({\n uris: trackURIs\n });\n\n const response = await fetch(`https://api.spotify.com/v1/playlists/${playlistID}/tracks`, {\n method: 'POST',\n headers: headers,\n body: body\n });\n const jsonResponse = await response.json();\n\n if (jsonResponse.error) {\n console.log('addSongsToPlaylist Error:', jsonResponse.error.message);\n return;\n }\n console.log('Successfully added songs to playlist. Snapshot ID:', jsonResponse.snapshot_id);\n\n }", "addTrack(track) {\n //Retrieve tracks currently in the playlist\n let tracks = this.state.playlistTracks;\n //Add new track to the end of the existing playlist\n tracks.push(track);\n //Reset state to represent new playlist\n this.setState({\n playlistTracks: tracks\n });\n }", "async function addTracksToPlaylist(playlist, trackPositions) {\n for (const { pos, ids } of trackPositions) {\n for (const tracks of chunk(ids.map(id => `spotify:track:${id}`), 100).reverse()) {\n await request(\"POST\", `https://api.spotify.com/v1/users/${playlist.owner.id}/playlists/${playlist.id}/tracks`, {\n uris: tracks,\n position: pos,\n });\n }\n }\n }", "function add_to_playlist({\n dom_list, tracklist, playlist, album_playlist=[], \n title_list, album_title_list=[], list_name, index, is_owner=false\n} = {}) {\n const item_id = dom_list[index].getAttribute('data-itemid'),\n dom_id = dom_list[index].id,\n // these data objects contain the sequential keys of every item available\n item_key = list_name.indexOf('search') > -1 ? getItemKey(dom_list[index]) :\n list_name.indexOf('wish') > -1 ? window.WishlistData.sequence[index] :\n window.CollectionData.sequence[index],\n fave_node = dom_list[index].querySelector('.fav-track-link'),\n is_subscriber_only = dom_list[index].classList.contains('subscriber-item');\n \n // console.log(item_key, tracklist);\n let track = tracklist[item_key] ? tracklist[item_key][0] : undefined;\n\n // if a favorite track is set use that instead of first track in the set\n if (is_owner && fave_node && list_name.indexOf('search') === -1 && tracklist[item_key]) {\n const fave_track = get_fave_track(fave_node, tracklist[item_key]);\n if (fave_track) track = fave_track;\n }\n\n // trackData.title is null when an item has no streamable track\n // dom item data-trackid attribute is \"\" when no streamable track\n // bc also has a zombie entry for subscriber only items which gets stuck in an endless fetch loop\n let can_push = track && \n track.trackData.title !== null && \n dom_list[index].getAttribute('data-trackid') &&\n (is_owner || !is_subscriber_only);\n // console.log('list', list_name, 'can push', can_push);\n\n if (!can_push) {\n console.log(\"missing track\", item_key, track?.trackData?.title);\n if (list_name === 'wish') {\n colplayer.wish_missing++; \n console.log('total missing from wish playlist', colplayer.wish_missing);\n } else if (list_name.indexOf('search') > -1) {\n colplayer.missing_search_tracks++;\n } else if (list_name === 'collection') {\n colplayer.col_missing++;\n console.log('total missing from collection playlist', colplayer.col_missing);\n }\n } else if (list_name === 'wishlist-search') {\n dom_list[index].setAttribute('data-searchnum', index - colplayer.missing_search_tracks);\n }\n\n // owner search should be processed as an album since if searching own collection all album tracks are included\n if (list_name !== 'collection-search' || !is_owner) {\n if (can_push) {\n push_track({track, item_id, dom_id, playlist, title_list, list_name});\n } else {\n console.log(`couldn't find playable track for item ${item_key}`, tracklist[item_key]);\n }\n }\n\n // build album playlist \n if (can_push && is_owner && (list_name === 'collection' || list_name === 'collection-search')) {\n let album = tracklist[item_key];\n album_playlist = list_name === 'collection-search' ? playlist : album_playlist;\n album_title_list = list_name === 'collection-search' ? title_list : album_title_list;\n dom_list[index].setAttribute('data-firsttrack', album_playlist.length);\n\n if (album.length >= 1) {\n album.forEach((t) => {\n push_track({\n track: t,\n item_id,\n dom_id,\n playlist: album_playlist,\n title_list: album_title_list,\n list_name: list_name === 'collection-search' ? 'collection-search' : 'albums'\n });\n });\n }\n console.log(`pushed album ${album[0].title} by ${album[0].trackData.artist}, playlist length now ${album_playlist.length}`);\n }\n}", "function addSongs (songsToAdd, currentUserId, playlistID) {\n\t\tvar url = 'https://api.spotify.com/v1/users/' + currentUserId + '/playlists' + \n\t\t playlistID + '/tracks?uris=';\n\t\tfor (i = 0; i < songsToAdd.length; i++) {\n\t\t\tif (i != 0) url += ',';\n\t\t\turl += songsToAdd[i]['id'];\n\t\t}\n\t\t//TODO add get request to add songs to playlist using url\n\t\t$.ajax({type: \"POST\",\n\t\t\turl: url,\n\t\t\t//data: data, //?????????????????????????\n\t\t\tsuccess: function (data) {\n\t\t\t\talert (data);\n\t\t\t}\n\t\t});\n\t}", "function addToPlaylist(trackId, playlist) {\n spotifyApi.addTracksToPlaylist(playlist, [`spotify:track:${trackId}`])\n .then(function (data) {\n console.log('Added tracks to playlist!');\n }, function (err) {\n console.log('Something went wrong!', err);\n });\n}", "function addTracks(playlistID, tracks, access_token){\n\tvar createAddOptions = {\n\t\turl: `https://api.spotify.com/v1/playlists/${playlistID}/tracks`,\n\t\tcont_type: 'application/json'\n\t}\n\taxios({\n\t\tmethod: 'post',\n\t\turl: createAddOptions.url,\n\t\theaders: {\n\t\t\t'Authorization': 'Bearer ' + access_token,\n\t\t\t'Content-Type': createAddOptions.cont_type,\n\t\t},\n\t\tparams: {\n\t\t\t'uris': tracks.join(\",\") //formatting tracks array for API use\n\t\t}\n\t})\n\t.then((response) => {\n\t\t//playlist successfully created!\n\t})\n\t.catch((error) => {\n\t\tconsole.log(error);\n\t})\n}", "function putTracksOnTrackList(id) {\n var playlist;\n\n //Check if id is a list[] or a number\n if(isNaN(id)){\n playlist = id;\n tracks = playlist;\n }\n else{\n playlist = playlists[id];\n tracks = getTracks(playlist);\n }\n \n clearAndAddNewTrackList(tracks);\n showNrOfTracklisted(tracks.length);\n changePlayButton(\"pause\");\n play = true;\n\n var addr = new addRow();\n for(var i = 0; i<tracks.length; i++){\n addr.add(tracks[i].name, \n tracks[i].album.artists[0].name, \n secondsToString(tracks[i].length), \n tracks[i].album.name,\n tracks[i],\n (i+1));\n }\n}", "addPlaylistSongs(playlistUris) {\n let parsed = queryString.parse(window.location.search);\n let accessToken = parsed.access_token;\n if (!accessToken)\n return;\n fetch(`https://api.spotify.com/v1/playlists/${this.state.playlistId}/tracks`, {\n headers: {\"Accept\": \"application/json\", \"Content-Type\": \"application/json\", 'Authorization': 'Bearer ' + accessToken},\n method: 'post',\n body: JSON.stringify({uris: playlistUris})\n })\n .then(this.startPlaylist);\n }", "addTrack(track)\n {\n // check if the track is already present in the playlist.\n let trackPresent = this.state.playList.tracks.some(playLisTrack=>{\n return playLisTrack.id === track.id;\n });\n if(!trackPresent)\n {\n this.state.playList.tracks.push(track);\n this.setState({playList: this.state.playList});\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the iterator of the tree from the given root node. This will iterate the nodes like they were traversed in a preorder fashion
function getPreOrderIterable(rootNode) { if (!(rootNode instanceof Node)) { throw new TypeError('Parameter rootNode must be of Node type') } // to generate an iterator, a stack data structure will be created // the nodes will be pushed to this stack as if they were traversed in pre order // initially add the root node to the top of stack let nodeStack = [rootNode] return { [Symbol.iterator]: () => { return { next: () => { // process the "current parent" let nextNode = nodeStack.pop() // check if there are children to be processed next if (nextNode && !nextNode.isLeaf()) { let childrenReversed = [...nextNode.children].reverse() nodeStack.push(...childrenReversed) } if (nextNode) { return {value: nextNode, done: false} } else { return {done: true} } } } } } }
[ "function BSTIterator(root) {\n //do in order traversal, have result queue\n //keep track of current index in i\n //each time you call next, you will increase index i\n\n this.result = []\n this.i = 0\n var traverse = (curr) => {\n if(!curr) return\n\n if(curr.left !== null) traverse(curr.left)\n this.result.push(curr.data)\n if(curr.right !== null) traverse(curr.right)\n }\n\n traverse(root)\n} // implement this", "iterate() {\n return walker(this.root);\n }", "function fnTraversal(root, node, preorder, postorder) {\n\t\tnode.childnodes.forEach((child, i) => { //iterate over next deep level\n\t\t\tpreorder(root, node, child, i) && fnTraversal(root, child, preorder, postorder); //preorder = cut/poda\n\t\t\tpostorder(root, node, child, i);\n\t\t});\n\t\treturn self;\n\t}", "*nodesAscending(){\n let i = 0;\n let node = this.root && this.root.getLeftmostChild();\n while(node){\n yield node;\n node = node.getSuccessor();\n }\n }", "*generator(){\n const it = this._tree.iterator();\n let i;\n while((i = it.next()) !== null) {\n yield i;\n }\n }", "* depth_first() {\n for(let i of this.iterate(true))\n yield i;\n }", "function iterItems(node) {\n var leaf = firstLeaf(node);\n return new ForwardIterator(leaf, 0, -1);\n }", "function iterItems(node) {\n var leaf = firstLeaf(node);\n return new ForwardIterator(leaf, 0, -1);\n }", "getChildNodeIterator() {}", "*descendants(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n for (var [node, path] of Node.nodes(root, options)) {\n if (path.length !== 0) {\n // NOTE: we have to coerce here because checking the path's length does\n // guarantee that `node` is not a `Editor`, but TypeScript doesn't know.\n yield [node, path];\n }\n }\n }", "nodeIterator() {\n\t\tlet next = this.head\n\t\treturn () => {\n\t\t\tif (next) {\n\t\t\t\tlet t = next\n\t\t\t\tnext = next.next\n\t\t\t\treturn t\n\t\t\t}\n\t\t}\n\t}", "iterate() {\n return (0, walker_1.walker)(this.root);\n }", "function create_nodeIterator(root, reference, pointerBeforeReference) {\n return NodeIteratorImpl_1.NodeIteratorImpl._create(root, reference, pointerBeforeReference);\n}", "function NodeIteratorImpl(root, reference, pointerBeforeReference) {\n var _this = _super.call(this, root) || this;\n _this._iteratorCollection = undefined;\n _this._reference = reference;\n _this._pointerBeforeReference = pointerBeforeReference;\n algorithm_1.nodeIterator_iteratorList().add(_this);\n return _this;\n }", "*nodes(){\n if(!this.root) return;\n let stack = [this.root];\n while(stack.length){\n const node = stack.pop();\n if(node.left) stack.push(node.left);\n if(node.right) stack.push(node.right);\n yield node;\n }\n }", "function RedBlackTreeIterator(tree, stack) {\n this.tree = tree\n this._stack = stack\n}", "traverse(fn) {\n const inOrder = (node) => {\n if (node) {\n if (node.left) {\n inOrder(node.left)\n }\n fn.call(this, node)\n if (node.right) {\n inOrder(node.right)\n }\n }\n }\n return inOrder(this.root)\n }", "*iter_subtrees_topdown() {\r\n let node;\r\n let stack = [this];\r\n while (stack.length) {\r\n node = stack.pop();\r\n if (!(node instanceof Tree)) {\r\n continue;\r\n }\r\n\r\n yield node;\r\n for (const n of [...node.children].reverse()) {\r\n stack.push(n);\r\n }\r\n }\r\n }", "function getNextTree(self){\n var visitor = new NodeVisitor();\n var currentId = self.id;//-1 to offset first iteration\n visitor.visit = function(node) {\n currentId += 1;\n /** Visit a node. **/\n var method_name = 'visit_' + node._astname;\n return this.generic_visit(node);\n }\n visitor.visit(flatTree[currentId]);\n if(currentId >= flatTree.length){\n return Sk.ffi.remapToPy(null);\n }\n return Sk.misceval.callsimOrSuspend(mod.AstNode, currentId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the query after the specified search delay.
updateQueryDelayed(query, callback = () => { }) { this._query = query; clearTimeout(this._searchDelayTimeout); this._searchDelayTimeout = window.setTimeout(() => { this.updateQuery(query, callback); }, this.searchDelay); }
[ "function afterDelay() {\n\t\t\t\tvar currentTime = new Date().getTime();\n\t\t\t\t\n\t\t\t\t// Check if enough time has elapsed since latest keyup event\n\t\t\t\tif (currentTime >= this.__searchKeyUpTime + SEARCH_DELAY) {\n\t\t\t\t\tvar keyword = $(this.options.searchInput).val();\n\t\t\t\t\t\n\t\t\t\t\t// Perform search only if current keyword is not the same as previous\n\t\t\t\t\tif (keyword.toLowerCase() !== this.__lastSearchKeyword.toLowerCase()|| okButton==true) {\n\t\t\t\t\t\tthis.__lastSearchKeyword = keyword;\n\t\t\t\t\t\tthis.search(keyword);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "function afterDelay() {\n\t\t\t\tvar currentTime = new Date().getTime();\n\t\t\t\t\n\t\t\t\t// Check if enough time has elapsed since latest keyup event\n\t\t\t\tif (currentTime >= this.__searchKeyUpTime + SEARCH_DELAY) {\n\t\t\t\t\tvar keyword = $(this.options.searchInput).val();\n\t\t\t\t\t\n\t\t\t\t\t// Perform search only if current keyword is not the same as previous\n\t\t\t\t\tif (keyword.toLowerCase() !== this.__lastSearchKeyword.toLowerCase()|| okButton==true) {\n\t\t\t\t\t\tthis.__lastSearchKeyword = keyword;\n\t\t\t\t\t\tthis.search(keyword);\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t}", "function searchTimer() {\n if (!TriggerSearch) return;\n TriggerSearch = false;\n\n applySearch();\n}", "search() {\n this.searchDelay_.start();\n }", "function delayedSearch() {\n let delayTimer;\n clearTimeout(delayTimer);\n delayTimer = setTimeout(function() {\n findRecipe(1);\n }, 500);\n \n}", "function debounceSearch() {\n var now = new Date().getMilliseconds();\n lastSearch = lastSearch || now;\n return ((now - lastSearch) < 300);\n }", "function debounceSearch() {\n var now = new Date().getMilliseconds();\n lastSearch = lastSearch || now;\n return ((now - lastSearch) < 300);\n }", "function debounceSearch() {\n var now = new Date().getMilliseconds();\n lastSearch = lastSearch || now;\n\n return ((now - lastSearch) < 300);\n }", "function searchByTimeout() {\n\t\tvar e = $( this );\n\t\tclearTimeout( e.data( 'search-timeout' ) );\n\n\t\tvar timeout = setTimeout( function() {\n\t\t\tsearch.apply( e );\n\t\t}, 1000 );\n\n\t\te.data( 'search-timeout', timeout );\n\t}", "function debounceSearch() {\n var now = new Date().getMilliseconds();\n lastSearch = lastSearch || now;\n\n return ((now - lastSearch) < 300);\n }", "function debounceSearch() {\n var now = new Date().getMilliseconds();\n lastSearch = lastSearch || now;\n return ((now - lastSearch) < 300);\n }", "function debounceSearch() {\n var now = new Date().getMilliseconds();\n lastSearch = lastSearch || now;\n return ((now - lastSearch) < 300);\n }", "function queueSearch(query){\n if (searching){\n clearTimeout(pendingSearch);\n pendingSearch = setTimeout(function(){checkTimer(query)}, 100);\n } else {\n searching = true;\n setTimeout(function(){searching=false;}, 400);\n lastSearched = query;\n runSearch(query);\n }\n }", "function delayedSearch(newVal, oldVal){\n if ($scope.searchText === oldSearchText) {\n getItems();\n oldSearchText = null;\n } else if (newVal !== oldVal) { // if not init phase\n oldSearchText = newVal;\n $timeout(delayedSearch, 800);\n }\n }", "setSearchTimer(onTimeout) {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(onTimeout, DEFAULT_TIMEOUT);\n }", "function triggerSearch()/*:void*/ {\n this.fireUpdateEventEventually$DDyr();\n }", "onSearchInput () {\n //showhide(\"content-results\") \n clearTimeout(this.searchDebounce)\n this.searchDebounce = setTimeout(async () => {\n this.searchOffset = 0\n this.searchResults = await this.search()\n }, 100)\n }", "function getSearches(query){\n clearTimeout(searchTimer);\n searchTimer = setTimeout(function(){searcher.searchYouTube(query,MAX_RESULTS,\"\")},500);\n}", "function searchTimeoutHandler () {\n searchTimerID = null;\n searchStr = \"\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Objects Code Challenge: Create an object named "Box" with 3 properties, height, width, volume. Create 2 buttons for Height. The first button decreases the Box Height by 1. The second button increases the Box Height by 1. Create a button that prints the object and its attributes to the page (use the span "output". Extra credit Create interactive buttons to decrease or increase the Width and Volume
function Box(width, height, volume) { this.width = width; this.height = height; this.volume = volume; }
[ "function DiagramObject(container, name, width, height, fillColor, strokeColor) {\n // create diagram \n $(\"<div id='\" + name + \"'>\").css({\n position: 'absolute',\n width: width + 'px',\n height: height + 'px'\n }).appendTo(container);\n // make diagram draggable\n $(\"#\" + name + \"\").draggable( { \n cursor:'crosshair'\n }).mouseout(function() {\n $(this).css('border-color', strokeColor);\n }).resizable( {\n 'maxHeight':78,\n 'minHeight':78\n });\n \n (function __init() {\n for (var i = 0; i < 3; i += 1) {\n // create each interactive box.\n var ib = new InteractiveBox(\"#\" + name,\n name+\"__obj\" + i,\n 150,\n 25,\n \"#F4C8FF\",\n \"#BB6891\",\n null,\n getDefaultName(i));\n \n // subscribe to update event\n $('#'+name+'__obj'+i).bind('update', function() {\n updatePosition();\n });\n positionIABox(i); \n }\n })();\n \n function updatePosition() {\n for ( var i = 0; i < 3; i+=1) {\n positionIABox(i);\n }\n }\n \n function positionIABox(index) {\n if (index > 0) {\n var num = index - 1;\n\n var newTopPos = Number(\n extractPX(\n $(\"#\"+name+\"__obj\" + (num)).css(\n \"top\"\n )));\n\n var newHeight = Number(\n extractPX(\n $(\"#\"+name+\"__obj\" + (num)).css(\n \"height\"\n )));\n\n var lastObjPos = (newTopPos + newHeight);\n\n $(\"#\"+name+\"__obj\" + index).css({\n \"top\": lastObjPos\n });\n }\n }\n \n function getDefaultName(index) {\n var value = 'Class'\n switch(index) {\n case 0:\n value = 'Class';\n break;\n case 1:\n value = 'Properties';\n break;\n case 2:\n value = 'Methods';\n break;\n }\n return value;\n }\n \n function extractPX(value) {\n var len = 2;\n if (value.length == 3) {\n len = 1\n }\n return value.substr(0, len);\n }\n \n \n return {\n x: function (value) {\n var newPos = $('#'+ name ).css({left:value+'px'});\n return newPos;\n },\n getX: function() {\n return $('#'+name).offset().left;\n },\n y: function (value) {\n var newPos = $('#'+ name ).css({top:value+'px'})\n return newPos;\n },\n getY: function() {\n return $('#'+name).offset().top;\n }\n }\n}", "function changeBox() {\n quickColor();\n\n //sub-box with similar design\n rect(125, 85, width - 50 - 85, 225);\n\n quickTextColor();\n type = sortType.value();\n textSize(12);\n textAlign(LEFT);\n textStyle(BOLD);\n text(type, 130, 100);\n textStyle(NORMAL);\n\n switch (type) {\n case 'Selection Sort':\n text('This is a type of sorting where...\\n-Looks at the very first bar (we could call it \\'n\\')\\n-Then it looks at all the bars to the right of \\'n\\' and looks for the\\n shortest bar say \\'x\\'.\\n-After finding it the bar \\'n\\' and \\'x\\' switch positions.\\n-After that it goes to the next bar. Looks for the shortest bar to the\\n right of it. Swaps positions with it. This step keeps on repeating till\\n all are sorted.', 132, 115);\n index = 0;\n break;\n case 'Insertion Sort':\n text('This is a type of sorting where...\\n-Looks at the second bar (we could call it \\'n\\')\\n-Then looks to the bar to the left \\'n\\' and if its lower in it, pushes it to\\nthe right and takes it place.\\n-Keeps on doing this till bar to the left is lower than itself.\\n-These steps repeat till looped though every bar.', 132, 115);\n index = 1;\n break;\n case 'Merge Sort':\n text('This is a type of sorting where...\\n-Splits the list of bars into individual bars.\\n-\\\"Merges\\\" two bars next to each other to form a list with two bars.\\n-The new list is sorted so that the sorted bar is first.\\n-Then two lists (of two bars) are merged together so that all bars\\nare in order.\\n-Repeat until back to one list.', 132, 115);\n index = 0;\n break;\n case 'Heap Sort':\n text('This is a type of sorting where...\\n-A max heap (binary tree). This is a structure where a parent\\nelement has two other child elements connected to it. The parent\\nelement is always bigger then the child element.\\n-After this the last bar of the unsorted area and the first bar is \\nswapped.\\n-After the flip, the original first bar (the one that\\'s last now) is part of\\nthe sorted area.\\n-Then remake the max heap for the unsorted area and repeat!', 132, 115);\n break;\n case 'Quick Sort':\n text('This is a type of sorting where...\\n-Looks at the last bar and moves any bars that are shorter then it to\\n its left and bars taller then it to the right.\\n-Repeat for left and right side.', 132, 115);\n index = 0;\n break;\n case 'Shellsort':\n text('This is a type of sorting where...\\n-Initial Gap sequence is determined. In this case the first gap is the\\namount of bars / 2\\n-Makes a new smaller group of bars that have values from the\\noriginal array seperated by the gap. Sorts each subarray\\nindependently.\\n-Reflects that corrected order in the original list of bars.\\n-Divides gap by 2 and repeat.', 132, 115);\n break;\n }\n}", "function previewBox () {\n\t\tvar el = document.createElement(\"div\");\n\t\tel.setAttribute(\"id\", \"R2D2C3P0\");\n\t\tel.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\n\t\tvar preview = document.createElement(\"div\");\n\t\tpreview.id = \"preview\";\n\t\tpreview.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\n\t\tvar toolBar = document.createElement(\"div\");\n\t\ttoolBar.id = \"toolbar\";\n\t\ttoolBar.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\n\t\tvar cb1 = document.createElement(\"input\");\n\t\tcb1.id = \"imageAsSprite\";\n\t\tcb1.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tcb1.setAttribute(\"type\", \"checkbox\");\n\n\t\tvar cb_label1 = document.createElement(\"span\");\n\t\tcb_label1.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tcb_label1.innerHTML = \"RIS\";\n\n\t\tvar cb = document.createElement(\"input\");\n\t\tcb.id = \"parentLevel\";\n\t\tcb.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tcb.setAttribute(\"type\", \"checkbox\");\n\t\tcb.setAttribute(\"checked\", \"checked\");\n\n\t\tvar cb_label = document.createElement(\"span\");\n\t\tcb_label.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tcb_label.innerHTML = \"1 level\";\n\n\t\tvar colorBox = document.createElement(\"input\");\n\t\tcolorBox.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tcolorBox.setAttribute(\"type\", \"text\");\n\t\tcolorBox.addEventListener(\"change\", function(e) {\n\t\t\tchangeBgColor(e.currentTarget.value);\n\t\t}, false);\n\n\t\tvar btn = document.createElement(\"input\");\n\t\tbtn.setAttribute(\"id\", \"r2d2c3p0-send\");\n\t\tbtn.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tbtn.setAttribute(\"type\", \"button\");\n\t\tbtn.setAttribute(\"value\", \"Save\");\n\t\tbtn.disabled = true;\n\t\tbtn.addEventListener(\"click\", function () {\n\t\t\tsendData();\n\t\t}, false);\n\n\t\tvar btn1 = document.createElement(\"input\");\n\t\tbtn1.id = \"r2d2c3p0-activate\";\n\t\tbtn1.setAttribute(\"data-r2d2c3p0\", \"r2d2c3p0\");\n\t\tbtn1.setAttribute(\"type\", \"button\");\n\t\tbtn1.setAttribute(\"value\", \"A\");\n\t\tbtn1.style.backgroundColor = \"blue\";\n\t\t\n\t\tbtn1.addEventListener(\"click\", function(e){\n\t\t\tif ( activated ) {\n\t\t\t\tdeactivate();\n\t\t\t\te.currentTarget.value = \"D\";\n\t\t\t\tbtn1.style.backgroundColor = \"red\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tactivate();\n\t\t\t\te.currentTarget.value = \"A\";\n\t\t\t\tbtn1.style.backgroundColor = \"blue\";\n\t\t\t}\n\t\t\tconsole.log(activated);\n\t\t\tactivated = !activated;\n\t\t}, false);\n\n\t\ttoolBar.appendChild(cb1);\n\t\ttoolBar.appendChild(cb_label1);\n\t\ttoolBar.appendChild(cb);\n\t\ttoolBar.appendChild(cb_label);\n\t\ttoolBar.appendChild(colorBox);\n\t\ttoolBar.appendChild(btn);\n\t\ttoolBar.appendChild(btn1);\n\n\t\tel.appendChild(preview);\n\t\tel.appendChild(toolBar);\n\t\tdocument.body.appendChild(el);\n\t}", "function budget()\n{\n x = 20\n y = 50\n \n indkomst = new box(x,y, \"\")\n \n bolig = new box(x, y + 80, \"\") \n \n mad = new box(x, y + 160, \"\") \n \n fasteUdgifter = new box(x, y + 240, \"\") \n \n transport = new box(x, y + 320, \"\") \n \n diverse = new box(x, y + 400, \"\") \n \n galdsafvikling = new box(x, y + 480, \"\") \n \n //resten = new box (515,170,forbrug1)\n \n indkomst.createInput()\n bolig.createInput()\n mad.createInput()\n fasteUdgifter.createInput()\n transport.createInput()\n diverse.createInput()\n galdsafvikling.createInput()\n //resten.createInput()\n \n textSize(32);\n text(forbrug1 + \"Kr\", 550, 190);\n \n \n}", "function Box() {\n this.type = 'rect';\n this.text = '';\n this.x = 0;\n this.y = 0;\n this.w = 1; // default width and height?\n this.h = 1;\n this.id = '';\n this.nextObjGuids = [];\n this.fill = '#444444';\n this.tag = '';\n this.state = '';\n}", "function initiate() {\n // Create boxes and push to array \"arrObjects\"\n for (var i = 0; i < 9; i++) {\n var id = document.getElementById(i+1).id;\n var newBox = new boxObject(id, \"empty\", getX(i), getY(i));\n arrObjects.push(newBox);\n }\n console.log(arrObjects);\n \n inputSideBoxID = randomLocation();\n input = temp;\n input.highlight = true;\n while (input == temp) {\n outputSideBoxID = randomLocation();\n }\n output = temp;\n console.log(\"Input Box ID: \" + input.id + \n \"\\nOutput Box ID: \" + output.id +\n \"\\nInput Side Box ID: \" + inputSideBoxID + \n \"\\nOutput Side Box ID: \" + outputSideBoxID);\n \n highlightBoxes();\n \n randomProcessCond();\n\n // Highlight and display input and output process conditions\n var inputSideBox = document.getElementById(inputSideBoxID);\n inputSideBox.classList.add(\"sideHighlighted\");\n inputSideBox.innerHTML = \"<h3>Input<br>P: \" + inputPressure + \"<br>T: \" + inputTemperature + \"</h3>\";\n \n var outputSideBox = document.getElementById(outputSideBoxID);\n outputSideBox.classList.add(\"sideHighlighted\");\n outputSideBox.innerHTML = \"<h3>Output<br>P: \" + outputPressure + \"<br>T: \" + outputTemperature + \"</h3>\";\n \n}", "function boxMaker(length,width,height,contents){\n\tvar objBox = {\n\t\tlength: length,\n\t\twidth: width,\n\t\theight: height,\n\t\tcontents: contents\n\t}\n\treturn objBox\n}", "function Box() {\n this.x = 0;\n this.y = 0;\n this.w = 1; // default width and height?\n this.h = 1;\n this.fill = '#444444';\n this.sector = '0';\n this.pricenum = '0';\n this.state= 0;\n this.place= 0;\n this.line = 0;\n this.cell = 0;\n}", "function SmokeBox() {\n\tthis.element;\n\t\n\t/* Constructing starter functions */\n\tthis.create = function( id ) {//Create a new Smoke Box\n\t\tvar div = document.createElement( 'div' );\n\t\tdiv.id = id;\n\t\t\n\t\tthis.element = div;\n\t\treturn div;\n\t};\n\t\n\tthis.read = function( id ) {//Create a smoke box by reading an existing element\n\t\tvar div = document.getElementById( id );\n\t\tthis.element = div;\n\t\t\n\t}\n\t\n\tthis.createRoundedBox = function( id, title ) {\n\t\tthis[ id ] = new Object();\n\t\t//RoundedBox\n\t\tvar div = document.createElement( 'div' );\n\t\tdiv.id = id;\n\t\tdiv.className = 'roundedDiv';\n\t\tthis[ id ][ 'container' ] = div;\n\t\t//RoundTop\n\t\tvar top = this.makeRound( true );\n\t\tdiv.appendChild( top );\n\t\tthis[ id ][ 'top' ] = top;\n\t\t//Content Area\n\t\tvar c = document.createElement( 'div' );\n\t\tc.className = 'r_boxContent';\n\t\tdiv.appendChild( c );\n\t\tthis[ id ][ 'content' ] = c;\n\t\t//Header\n\t\tvar h = null;\n\t\tif( title != null ) {\n\t\t\th = document.createElement( 'div' );\n\t\t\th.className = 'boxHeader';\n\t\t\th.appendChild( document.createTextNode( title ) );\n\t\t\tc.appendChild( h );\n\t\t}\n\t\tthis[ id ][ 'header' ] = h;\n\t\t//OtherParts\n\t\tthis[ id ][ 'sections' ] = null;\n\t\tthis[ id ][ 'left' ] = null;\n\t\tthis[ id ].leftElement = null;\n\t\tthis[ id ][ 'right' ] = null;\n\t\tthis[ id ].rightElement = null;\n\t\t//Break\n\t\tvar br = document.createElement( 'div' );\n\t\tbr.style.clear = 'both';\n\t\tdiv.appendChild( br );\n\t\tthis[ id ][ 'break' ] = br;\n\t\t//RoundBottom\n\t\tvar bottom = this.makeRound( false );\n\t\tdiv.appendChild( bottom );\n\t\tthis[ id ][ 'bottom' ] = bottom;\n\t\treturn div;\n\t};\n\t/* Add Boxes */\n\tthis.appendRoundedBox = function( id, title ) {\n\t\tvar b = this.createRoundedBox( id, title );\n\t\tthis.element.appendChild( b );\n\t\treturn b;\n\t};\n\tthis.insertRoundedBoxBefore = function( old, id, title ) {\n\t\tvar b = this.createRoundedBox( id, title );\n\t\tthis.element.insertBefore( b, old );\n\t\treturn b;\n\t};\n\tthis.insertRoundedBoxAfter = function( old, id, title ) {\n\t\tvar b = this.createRoundedBox( id, title );\n\t\tif( this.element.nextSibbling != null )\n\t\t\tthis.element.insertBefore( b, old.nextSibbling );\n\t\telse this.element.appendChild( b );\n\t\treturn b;\n\t};\n\t\n\t/* List Altering */\n\tthis.addListItem = function( id, side, href, text ) {\n\t\tif( this.isSectional( id ) ) return null;//We cant add lists to sectional boxes.\n\t\tif( !this.isLeftRight( id ) && !this.isSingleList( id ) ) {//Create list if there is none.\n\t\t\tif( side == 'left' ) {\n\t\t\t\tthis[ id ][ 'left' ] = new Array();\n\t\t\t\tthis[ id ].leftElement = document.createElement( 'div' );\n\t\t\t\tthis[ id ].leftElement.className = 'listLeft';\n\t\t\t\tif( this[ id ].rightElement != null )\n\t\t\t\t\tthis[ id ][ 'content' ].insertBefore( this[ id ].leftElement, this[ id ].rightElement );\n\t\t\t\telse\n\t\t\t\t\tthis[ id ][ 'content' ].appendChild( this[ id ].leftElement );\n\t\t\t} else if( side == 'right' ) {\n\t\t\t\tthis[ id ][ 'right' ] = new Array();\n\t\t\t\tthis[ id ][ 'right' ] = new Array();\n\t\t\t\tthis[ id ].rightElement = document.createElement( 'div' );\n\t\t\t\tthis[ id ].rightElement.className = 'listRight';\n\t\t\t\tthis[ id ][ 'content' ].appendChild( this[ id ].rightElement );\n\t\t\t} else {\n\t\t\t\tthis[ id ][ 'list' ] = new Array();\n\t\t\t}\n\t\t}\n\t\t//Create List item\n\t\tvar item = new Object();\n\t\titem[ 'block' ] = document.createElement( 'div' );\n\t\titem[ 'link' ] = document.createElement( 'a' );\n\t\titem[ 'href' ] = href;\n\t\titem[ 'text' ] = text;\n\t\titem[ 'link' ].href = href;\n\t\titem[ 'link' ].appendChild( document.createTextNode( text ) );\n\t\titem[ 'block' ].className = 'boxLink';\n\t\titem[ 'block' ].appendChild( item[ 'link' ] );\n\t\t//Add item depending on settings\n\t\tif( this.isLeftRight( id ) ) {//Is this a double (Left/Right Columns) list\n\t\t\tif( side == 'left' ) {//We want it on the left\n\t\t\t\tthis[ id ][ 'left' ][ this[ id ][ 'left' ].length ] = item;\n\t\t\t\tthis[ id ].leftElement.appendChild( item[ 'block' ] );\n\t\t\t} else if( side == 'right' ) {//We want it on the right\n\t\t\t\tthis[ id ][ 'right' ][ this[ id ][ 'right' ].length ] = item;\n\t\t\t\tthis[ id ].rightElement.appendChild( item[ 'block' ] );\n\t\t\t} else {//We don't have a preference on side, so add it to the sortest side.\n\t\t\t\tif( this[ id ][ 'right' ].length < this[ id ][ 'left' ].length ) {\n\t\t\t\t\t//Left is larger, add to Right\n\t\t\t\t\tthis[ id ][ 'right' ][ this[ id ][ 'right' ].length ] = item;\n\t\t\t\t\tthis[ id ].rightElement.appendChild( item[ 'block' ] );\n\t\t\t\t} else {\n\t\t\t\t\t//Right is larger or both are same size, add to Left\n\t\t\t\t\tthis[ id ][ 'left' ][ this[ id ][ 'left' ].length ] = item;\n\t\t\t\t\tthis[ id ].leftElement.appendChild( item[ 'block' ] );\n\t\t\t\t}\n\t\t\t}\n\t\t} else {//This must be a single list.\n\t\t\t//Append item to list\n\t\t\tthis[ id ][ 'list' ][ this[ id ][ 'list' ].length ] = item;\n\t\t\tthis[ id ][ 'content' ].appendChild( item[ 'block' ] );\n\t\t}\n\t};\n\t\n\t/* Type tests */\n\tthis.isSingleList = function( id ) {\n\t\treturn this[ id ][ 'list' ] != null;\n\t};\n\tthis.isSectional = function( id ) {\n\t\treturn this[ id ][ 'sections' ] != null;\n\t};\n\tthis.isLeftRight = function( id ) {\n\t\treturn this[ id ][ 'left' ] != null || this[ id ][ 'right' ] != null;\n\t};\n\t\n\t/* Get & Set */\n\tthis.getHeader = function( id ) {\n\t\tif( this[ id ][ 'header' ] != null )\n\t\t\tthis[ id ][ 'header' ].firstChild.data;\n\t\treturn null;\n\t};\n\tthis.setHeader = function( id, title ) {\n\t\tif( this[ id ][ 'header' ] != null ) {\n\t\t\tif( title == null ) {\n\t\t\t\tthis[ id ][ 'header' ].parentNode.removeChild( this[ id ][ 'header' ] );\n\t\t\t\tthis[ id ][ 'header' ] = null;\n\t\t\t} else {\n\t\t\t\tthis[ id ][ 'header' ].firstChild.data = title;\n\t\t\t}\n\t\t} else {\n\t\t\tvar h = null;\n\t\t\tif( title != null ) {\n\t\t\t\th = document.createElement( 'div' );\n\t\t\t\th.className = 'boxHeader';\n\t\t\t\th.appendChild( document.createTextNode( title ) );\n\t\t\t\tthis[ 'content' ].appendChild( h );\n\t\t\t}\n\t\t\tthis[ id ][ 'header' ] = h;\n\t\t}\n\t};\n\t\n\t/* Private Builders */\n\tthis.makeRound = function( isTop ) {\n\t\tvar e = document.createElement( 'b' );\n\t\te.className = isTop ? 'xtop' : 'xbottom';\n\t\tfor( var xb = isTop ? 1 : 4;\n\t\t\t\t( isTop && xb <= 4 ) ||\n\t\t\t\t( !isTop && xb >= 1 );\n\t\t\t\txb += isTop ? 1 : -1 ) {\n\t\t\tvar b = document.createElement( 'b' );\n\t\t\tb.className = 'xb' + xb;\n\t\t\te.appendChild( b );\n\t\t}\n\t\treturn e;\n\t};\n\t\n}", "function createBox(percentage,odd){\n optioncontainer = document.getElementById(\"optionContainer\")\n //option div\n optionnode = document.createElement('div')\n optionnode.className=\"option\"\n optioncontainer.append(optionnode)\n //prob div\n probnode = document.createElement('div')\n probnode.textContent = \"Probability: \"+percentage+\"%\"\n probnode.className = \"prob\"\n optionnode.append(probnode)\n //return div\n returnnode = document.createElement('div')\n returnnode.textContent = \"Odds: \"+odd\n returnnode.className = \"return\"\n optionnode.append(returnnode)\n //input div\n inputnode = document.createElement(\"input\")\n optionnode.append(inputnode)\n updateInputChangeEvent()\n}", "function addBox(width, height, center = [0, 0, 1]) {\n let object = {\n name: '',\n type: 'box',\n width: width,\n height: height,\n center: center,\n fill: '#FFFFFF',\n stroke: '#000000',\n actualStroke: '#000000',\n T: Math.identity(),\n R: Math.identity(),\n S: Math.identity(),\n angleRotation: 0\n }\n objectSelected = objects.push(object)\n drawObjects()\n return objectSelected\n }", "function printBox(width, height) {\n let emptyString = \"\";\n // creates top and bottom parts of box made of *\n for (let i = 0; i<width; i++) {\n emptyString += \"*\";\n }\n // prints top * of the bxo\n console.log(emptyString);\n // prints middle line of box\n for (let j = 0; j<(height - 2); j++) {\n // starts the * with an initial *\n let middleString = \"*\";\n // adds the correct amount of empty space\n for (let h = 0; h<width - 2; h++) {\n middleString += \" \";\n }\n // adds the last * on the far side\n middleString += \"*\";\n // prints the actual middle line each time\n console.log(middleString);\n }\n // prints the bottom of the box\n console.log(emptyString);\n}", "function drawBox(height, width, x = 0, y = 0) {\n\t\tterm.terminal.moveTo(x, y);\n\t\tconst leftSpaces = new Array(y).fill(\" \").join(\"\");\n\t\tconst horizLine = new Array(width - 2).fill(pipes.horizLine).join(\"\");\n\t\tconst top = pipes.topLeft + horizLine + pipes.topRight;\n\t\tconst bot = pipes.botLeft + horizLine + pipes.botRight;\n\t\tconst middleSpaces = new Array(top.length - 2).fill(\" \").join(\"\");\n\t\tconst middleRow = leftSpaces + pipes.vertLine + middleSpaces + pipes.vertLine + \"\\n\";\n\t\tconst middle = new Array(height - 1).fill(middleRow).join(\"\");\n\t\treturn \"\\n\" + leftSpaces + top + \"\\n\" + middle + leftSpaces + bot + \"\\n\";\n\t}", "function createInitialStage() {\n //create a copy of the initial properties\n objectProperties = JSON.parse(JSON.stringify(initialObjectProperties));\n\n $(\"#Window3\").html(\"<input id=\\\"gotoWindow2\\\" type=\\\"button\\\" \" +\n \" value=\\\"Return to Options Input Screen\\\"\" +\n \" onclick=\\\"switchToInputWindow();\\\" style=\\\"position:absolute;z-index:99\\\">\" +\n \"</input><input id=\\\"play\\\" type=\\\"button\\\" \" +\n \" value=\\\"Play Animation\\\"\" +\n \" onclick=\\\"scheduleAnimations(0);\\\" style=\\\"position:absolute;top:15px;z-index:99;\\\"></input>\" +\n \"<div id=\\\"stage\\\">\" +\n \"</div>\");\n\n console.log(globalOptions.css);\n\n //apply typeOptions (shit these are overriding the specific inputs, which\n //inverts the desired heirarchy. I should do this first, then write over everything)\n var typekeys = Object.keys(typeOptions);\n for (var i = 0; i < typekeys.length; i++) {\n var object_type = typekeys[i];\n var targets = getObjectListFromType(object_type);\n for (var j = 0; j < targets.length; j++) {\n var object_name = targets[j];\n if (typeof(objectProperties[object_name].css) == \"undefined\" || objectProperties[object_name].css === \"\") {\n objectProperties[object_name].css = typeOptions[object_type].css;\n }\n if (typeof(objectProperties[object_name].image) == \"undefined\" || objectProperties[object_name].image === \"\") {\n objectProperties[object_name].image = typeOptions[object_type].image;\n }\n if (typeof(objectProperties[object_name].size) == \"undefined\" || objectProperties[object_name].size === \"\") {\n objectProperties[object_name].size = typeOptions[object_type].size;\n }\n }\n }\n\n //1. Place them on the stage\n var object_keys = Object.keys(objectProperties);\n var objectshtml = \"\";\n for (var i = 0; i < object_keys.length; i++) {\n var key = object_keys[i];\n var object = objectProperties[key];\n var objectcontainer = \"\";\n objectcontainer += \"<div id=\\\"\" + object.name + \"\\\" class=\\\"objectImage\\\" style=\\\"position:absolute;background-image:url(\\'\" + object.image + \"\\');\\\">\";\n if (globalOptions.labelled === \"true\") {\n console.log(globalOptions.labelled);\n objectcontainer += key;\n }\n objectcontainer += \"</div>\";\n objectshtml += objectcontainer;\n }\n\n $(\"#stage\").html(objectshtml);\n\n //apply user defined CSS to the stage\n if (typeof(globalOptions.css) != \"undefined\") {\n console.log(globalOptions);\n applyCSS(globalOptions.css, \"Window3\");\n }\n\n for (var i = 0; i < object_keys.length; i++) {\n var key = object_keys[i];\n stageLocation[key] = objectProperties[key].location;\n }\n\n for (var i = 0; i < object_keys.length; i++) {\n var key = object_keys[i];\n //2. set their size\n var size = getWidthAndHeight(key, objectProperties);\n // console.log(\"Size of \"+key+\" :\" + size[0] +\" , \"+ size[1]);\n stageLocation[key] = getStageLocation(key, objectProperties, stageLocation, 0);\n var x = stageLocation[key][0];\n var y = stageLocation[key][1]\n if (typeof(size) != \"undefined\") {\n console.log(\"Applying dimensions to \" + key + \" to \" + size[0] + \",\" + size[1]);\n $(\"#\" + key).css(\"min-width\", size[0] + globalOptions.units);\n //NOTE: Height is currently useless. object-fit doesnt work. need to fix\n $(\"#\" + key).css(\"min-height\", size[1] + globalOptions.units);\n }\n\n var mleft = x.toString() + globalOptions.units;\n var mtop = y.toString() + globalOptions.units;\n $(\"#\" + key).css(\"left\", mleft);\n $(\"#\" + key).css(\"bottom\", mtop);\n //4. apply any custom CSS\n applyCSS(objectProperties[key].css, key);\n }\n}", "updateBox () {\n // if the user haven't enabled advanced dimens' input, return.\n if (!this.enableAdvanced.checked) {\n return\n }\n\n // else, set css properties according to the data entered into the application\n let styleHeight = this.state.height == '' ? '' : this.state.height + 'px'\n let styleWidth = this.state.width == '' ? '' : this.state.width + 'px'\n this.boxContainer.style.height = styleHeight\n this.boxContainer.style.width = styleWidth\n this.heightInput.value = this.state.height\n this.widthInput.value = this.state.width\n }", "function Box(options){\n options = options || {};\n EventEmitter.call(this);\n this.diagram = options.diagram || null;\n this.position = new Vec2(options.x||0 , options.y||0);\n this.width = options.width || 150;\n this.height = options.height || 100;\n this.margin = options.margin || 10;\n this.connectors = [];\n}", "function Box() {\n this.x = 0;\n this.y = 0;\n this.w = 0;\n this.h = 0;\n\n this.margin = {\n 'n': 0,\n 'e': 0,\n 's': 0,\n 'w': 0,\n };\n\n this.getFullWidth = function() {\n return this.w + this.margin.w + this.margin.e;\n };\n\n this.getFullHeight = function() {\n return this.h + this.margin.n + this.margin.s;\n };\n}", "function Box(value, hoist) {\n this.value = value;\n this.hoist = hoist;\n }", "function ElementBox(){/**\n * @private\n */this.x=0;/**\n * @private\n */this.y=0;/**\n * @private\n */this.width=0;/**\n * @private\n */this.height=0;/**\n * @private\n */this.margin=new Margin(0,0,0,0);/**\n * @private\n */this.padding=new Margin(0,0,0,0);/**\n * @private\n */this.characterFormat=undefined;/**\n * @private\n */this.isRightToLeft=false;/**\n * @private\n */this.canTrigger=false;/**\n * @private\n */this.ischangeDetected=false;/**\n * @private\n */this.isVisible=false;/**\n * @private\n */this.isSpellChecked=false;/**\n * @private\n */this.revisions=[];/**\n * @private\n */this.canTrack=false;/**\n * @private\n */this.removedIds=[];/**\n * @private\n */this.isMarkedForRevision=false;this.characterFormat=new WCharacterFormat(this);this.margin=new Margin(0,0,0,0);}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a function called printVacations whose input is an array of arrays. Each subarray should have two strings as elements: The 0th element should be a person's name and the 1st element should be that person's most desired vacation destination. Include a minimum of 3 subarrays in your input array, like so: [ ['Tammy', 'Tahiti'], ['Erin', 'Banff, Alberta, Canada'], ['Janet', 'London'] ] Your function should print each person's name and desired destination in a complete sentence, like this: Tammy really wants to go to Tahiti. Erin really wants to go to Banff, Alberta, Canada. Janet really wants to go to London.
function printVacations(input_array) { output = "" for (i = 0; i < input_array.length; i++) { // item_array = `input_array[i] output+= `${input_array[i][0]} really wants to go to ${input_array[i][1]}. \n` } return output }
[ "function printVacations(arr) {\n return arr.map(subarr => {\n return (`${subarr[0]} really wants to go to ${subarr[1]}.`);\n }\n )\n}", "function printVacations2(input_array) {\n output = \"\";\n for (i = 0; i < input_array.length; i++) {\n // item_array = `input_array[i] \n var lastvalue = input_array[i][1][input_array[i][1].length -1]\n output+= `${input_array[i][0]} is willing to go to ${input_array[i][1].slice(0,-1)} or ${lastvalue}. \\n` \n }\n return output\n}", "function printVacationsTwo(arr) {\n\n return arr.map(subarr => {\n if (subarr[1].length === 3)\n return (`${subarr[0]} is willing to go to ${subarr[1][0]}, ${subarr[1][1]}, or ${subarr[1][2]}.`);\n else if (subarr[1].length === 2) {\n return (`${subarr[0]} is willing to go to ${subarr[1][0]} or ${subarr[1][1]}.`);\n } else {\n return (`${subarr[0]} is willing to go to ${subarr[1]}.`);\n }\n }\n )\n}", "function Work_2(foodArray, adjectiveArray){\n var school = foodArray[foodArray.length - 1];\n console.log(school);\n for(var i = 0; i < foodArray.length; i++){\n console.log(foodArray[i] + 'are/is' + adjectiveArray[i])\n }\n}", "function displayArrays(resEnzyme, subLength, subArray, posFound, count)\n\t{\n\t\tdocument.writeln(\"Your restriction enzyme: <br />\" + resEnzyme + \"<br /> <br />\");\n\t\n\t\tdocument.writeln(\"Your cut site:<br />\");\n\t\t\n\t\t//goes through length of subArray[]\n\t\tfor (h=0; h<subLength; h++)\n\t\t{\n\t\t\tdocument.write(subArray[h]); //writes the current character of the loop\n\t\t}\n\t\tdocument.writeln(\"<br /><br />\"); \n\t\t\n\t\tdocument.writeln(\"Instances of cut site found at indexes:<br />\");\n\t\t\n\t\t//if one or more instances of the subString were found\n\t\tif (count > 0)\n\t\t{\n\t\t\t//goes through length of posFound[]\n\t\t\tfor (h=0; h<count; h++)\n\t\t\t{\n\t\t\t\tdocument.write(posFound[h] + \"&nbsp;&nbsp;&nbsp;\"); //&nbsp; = space\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//writes the current position of the loop\n\t\t\t}\n\t\t}\n\t\t\n\t\t//if no instances of the subString are found\n\t\telse\n\t\t{\n\t\t\t//tells the user the enzyme could not cut anywhere in the DNA sequence\n\t\t\tdocument.writeln(\"No instances of the subString were found in the sequence below.\");\n\t\t}\n\t\t\n\t\tdocument.writeln(\"<br /><br />\");\n\t}", "function foodPrinter() {\n const wholeOrder = [];\n let foodString = '';\n for (let i = 0; i < foodOrder.length; i++) {\n wholeOrder.push(foodOrder[i].innerText);\n }\n if (wholeOrder.length === 1) {\n return wholeOrder[0];\n }\n else if (wholeOrder.length === 2){\n return `${wholeOrder[0]} and ${wholeOrder[1]}`;\n }\n else {\n for (let x = 0; x < wholeOrder.length; x++) {\n if (x !== wholeOrder.length - 1) {\n foodString += ` ${wholeOrder[x]},`;\n }\n else {\n foodString += ` and ${wholeOrder[x]}`;\n }\n }\n return foodString;\n }\n }", "function printArray (ArrayName)\n{\n let anyArray = [\"Autumn\", \"Kevin\", \"Kenn\"];\n\n console.log(\"Autumn\", \"Kevin\", \"Kenn\");\n}", "function printArray (chosenArray) {\n\tfor (i=0; i<chosenArray.length; i++) {\n\t\tconsole.log(chosenArray[i]);\n\t}\n}", "function valuta( array ) {\n let tekst2 = \" and jou can pay with: \"\n for( let i = 0; i < array.length; i++ ) {\n // console.log( array[i].name )\n tekst2 = tekst2 + array[i].name\n if( i === array.length - 2 ) {\n tekst2 = tekst2 + \" and \"\n } else if( i < array.length -2 ) {\n tekst2 = tekst2 + \", \"\n }\n }\n tekst2 = tekst2 + \".\";\n return tekst2;\n //\n // if( array.length === 1 ) {\n // return \" and you can pay with \" + array[0].name + \".\";\n // } else return \" and you can pay with \" + array[0].name + \" and \" + array[1].name + \".\";\n}", "function serviceVehicles() {\n let str = \"Amazing Joe's Garage, we service \";\n for (let i of listVehicles) {\n if (i !== listVehicles[0] && i !== listVehicles[listVehicles.length - 1])\n str += ', ';\n else if (i === listVehicles[listVehicles.length - 1])\n str += ' and ';\n i = addPlural(i);\n str += i;\n if (i === listVehicles[listVehicles.length - 1])\n str += '.';\n }\n return str;\n}", "function printVoterTurnout(voters) {\n // If we want we can write more pseudo-code to create a plan for sorting.\n // First start by creating an arrays where our sorted voters will live:\n var ageGroup1 = [];\n var ageGroup2 = [];\n var ageGroup3 = [];\n // Next we'll write a for loop that iterates over our voters and sorts them into those arrays:\n for (var i = 0; i < voters.length; i++) {\n var voter = voters[i];\n if (voter.age >= 18 && voter.age <= 25) {\n ageGroup1.push(voter);\n } else if (voter.age >= 26 && voter.age <= 35) {\n ageGroup2.push(voter);\n } else {\n ageGroup3.push(voter);\n }\n }\n}", "function print_to_html( innerHTML_element, arr, name_display )\n{\n if (arr.length > 0)\n {\n innerHTML_element.innerHTML += \"Your selection from \" + name_display + \": \";\n for (var i = 0; i < arr.length; i++)\n {\n if (i+1 == arr.length)\n {\n innerHTML_element.innerHTML += arr[i] + \"<br/>\";\n }\n else\n {\n innerHTML_element.innerHTML += arr[i] + \", \";\n }\n }\n }\n}", "function logTowns(town) {\n console.log(town[0]); //nameOfTown\n console.log(`Arrivals: ${town[1][0]}`);\n console.log(`Departures: ${town[1][1]}`);\n console.log(\"Planes:\");\n town[1][2]\n .sort((p1, p2) => p1.localeCompare(p2)) //sorts all elements of the planeArray alphabetical\n .forEach(p => console.log(`-- ${p}`)); //and logs them in the way that's intended\n }", "formatArray(arrayInfo) {\n // To store the final, desired string displaying all the author names\n let stringInfo = '';\n\n if (arrayInfo === undefined) {\n stringInfo = 'Unknown'\n } else if (arrayInfo.length === 1) {\n stringInfo = arrayInfo[0]\n } else if (arrayInfo.length === 2) {\n stringInfo = `${arrayInfo[0]} and ${arrayInfo[1]}`\n } else {\n for (let i=0; i<arrayInfo.length-1; i++) {\n stringInfo += `${arrayInfo[i]}, `;\n }\n stringInfo += `and ${arrayInfo[arrayInfo.length-1]}`\n }\n\n return stringInfo;\n }", "function vacation(name, destination) {\n console.log(`${name} would love to visit ${destination}.`)\n}", "function tellFortune (numOfchilden, partner, location, jobTitle){\n var x = jobTitle;\n var y = location;\n var z = partner;\n var n = numOfchilden;\n return console.log('You will be a', x, 'in', y, 'and married to ', z,'with', n, 'kids.');\n}", "function tellFortune(number_of_children, partner_name, location, job_title) {\n console.log (\"You will be a \" + job_title + \" in \" + location + \", and married to \" + partner_name + \" \" + \"with\" + \" \" + number_of_children + \" \" + \"kids.\");\n}", "function formattedFriendListForBabyStep(babyStep, friends) {\n // check for possible error\n if (isNaN(babyStep)) {\n return 'Not a Number!';\n }\n\n // select friends on same step and sort by name\n const friendsOnMyStep = friends.filter(friend => friend[2] == babyStep)\n .sort(( a, b ) => { // sort by name\n let i = a[1] == b[1] ? 0 : 1; // check to see if last names are equal and change i to use first name to compare\n return a[i] < b[i] ? -1 : 1; \n });\n\n // create string to return\n return (() => {\n if (friendsOnMyStep.length == 0) {\n return `None of your friends is in Baby Step ${babyStep}.`\n } \n else if (friendsOnMyStep.length == 1) {\n return `${friendsOnMyStep[0][0]} ${friendsOnMyStep[0][1]} is also in Baby Step ${babyStep}.`\n } \n else if (friendsOnMyStep.length == 2) {\n return `${friendsOnMyStep[0][0]} ${friendsOnMyStep[0][1]} and ${friendsOnMyStep[1][0]} ${friendsOnMyStep[1][1]} are also in Baby Step ${babyStep}.`\n } \n else if (friendsOnMyStep.length == 3) {\n return `${friendsOnMyStep[0][0]} ${friendsOnMyStep[0][1]} and ${friendsOnMyStep[1][0]} ${friendsOnMyStep[1][1]}, and 1 other friend are also in Baby Step ${babyStep}`\n } \n else if (friendsOnMyStep.length > 3) {\n return `${friendsOnMyStep[0][0]} ${friendsOnMyStep[0][1]} and ${friendsOnMyStep[1][0]} ${friendsOnMyStep[1][1]}, and ${friendsOnMyStep.length - 2} other friends are also in Baby Step ${babyStep}.`\n } \n })();\n\n}", "function formattedFriendListForBabyStep2(babyStep, friends) {\n if (isNaN(babyStep)) {\n return 'Not a Number!';\n }\n \n // arrange friends as objects for clarity\n const friendsList = friends.map(friend => {\n return {\n firstName: friend[0],\n lastName: friend[1],\n babyStep: friend[2]\n }\n });\n\n // select friends on same step\n const friendsOnMyStep = friendsList.filter(friend => friend.babyStep == babyStep)\n .sort(( a, b ) => {\n\n if ( a.lastName < b.lastName ){\n return -1;\n }\n else if ( a.lastName > b.lastName ){\n return 1;\n }\n else if ( a.lastName == b.lastName ){\n if ( a.firstName < b.firstName ){\n return -1;\n }\n if ( a.firstName > b.firstName ){\n return 1;\n }\n }\n return 0;\n });\n\n // create string to return\n let string = '';\n switch (friendsOnMyStep.length) {\n case 0: \n string = `None of your friends is in Baby Step ${babyStep}.`\n break;\n case 1:\n string = `${friendsOnMyStep[0].firstName} ${friendsOnMyStep[0].lastName} is also in Baby Step ${babyStep}.`\n break;\n case 2:\n string = `${friendsOnMyStep[0].firstName} ${friendsOnMyStep[0].lastName} and ${friendsOnMyStep[1].firstName} ${friendsOnMyStep[1].lastName} are also in Baby Step ${babyStep}.`\n break;\n case 3:\n string = `${friendsOnMyStep[0].firstName} ${friendsOnMyStep[0].lastName}, ${friendsOnMyStep[1].firstName} ${friendsOnMyStep[1].lastName}, and 1 other friend are also in Baby Step ${babyStep}.`\n break;\n default:\n string = `${friendsOnMyStep[0].firstName} ${friendsOnMyStep[0].lastName}, ${friendsOnMyStep[1].firstName} ${friendsOnMyStep[1].lastName}, and ${friendsOnMyStep.length - 2} other friends are also in Baby Step ${babyStep}.`\n break;\n }\n console.log(friendsOnMyStep);\n return string;\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that add our personal rating to the hospital array
function addRatings(){ if(choice == 0){ ratingFields = [ {field:"averageTotalPayments",weight:3,order:"dsc"}, {field:"center_distance",weight:2,order:"dsc"}, {field:"totalDischarges",weight:1,order:"dsc"} ]; }else{ ratingFields = [ {field:"averageTotalPayments",weight:3,order:"dsc"}, {field:"totalDischarges",weight:1,order:"dsc"} ]; } tempActualLocation = Object.create(actualLocation); totalWeights = getTotalWeights(); for(var i=0;i<actualLocation.length;i++){ actualLocation[i]["rating"] = getOverallRating(actualLocation[i]); } }
[ "addRating(newRating) {\n this._ratings.push(newRating)\n }", "addRating(ratings) {\n this._rating.push(ratings)\n }", "addRating(ratings) {\n this._ratings.push(ratings);\n }", "function setWeightsForRecommendedInsurance(){\n weighted_recommendedInsurance.essential = [];\n weighted_recommendedInsurance.additional = [];\n let seventyfiveAboveScores =[] , fiftyScores = [], twentyFiveScores=[], fiftyScoreslength = 0, seventyfiveAboveScoresLength =0;\n for(var index in $scope.recommendation){\n let score = $scope.recommendation[index].score;\n switch (score) {\n case 100:\n case 75:\n seventyfiveAboveScores.push(index);\n break;\n case 50:\n fiftyScores.push(index);\n break;\n case 25:\n twentyFiveScores.push(index);\n break;\n default:\n break;\n }\n }\n weighted_recommendedInsurance.essential.push(...seventyfiveAboveScores);\n weighted_recommendedInsurance.additional.push(...twentyFiveScores);\n\n fiftyScoreslength = fiftyScores.length;\n seventyfiveAboveScoresLength = seventyfiveAboveScores.length;\n\n if(seventyfiveAboveScoresLength + fiftyScoreslength <= 3)\n weighted_recommendedInsurance.essential.push(...fiftyScores);\n else\n weighted_recommendedInsurance.additional.push(...fiftyScores);\n }", "function setWeightsForRecommendedInsurance(){\n weighted_recommendedInsurance.essential = [];\n weighted_recommendedInsurance.additional = [];\n let seventyfiveAboveScores =[] , fiftyScores = [], twentyFiveScores=[], fiftyScoreslength = 0, seventyfiveAboveScoresLength =0;\n for(var index in $scope.recommendation){\n let score = $scope.recommendation[index].score;\n switch (score) {\n case 100:\n case 75:\n seventyfiveAboveScores.push(index);\n break;\n case 50:\n fiftyScores.push(index);\n break;\n case 25:\n twentyFiveScores.push(index);\n break;\n default:\n break;\n }\n }\n weighted_recommendedInsurance.essential.push(...seventyfiveAboveScores);\n weighted_recommendedInsurance.additional.push(...twentyFiveScores);\n \n fiftyScoreslength = fiftyScores.length;\n seventyfiveAboveScoresLength = seventyfiveAboveScores.length;\n \n if(seventyfiveAboveScoresLength + fiftyScoreslength <= 3)\n weighted_recommendedInsurance.essential.push(...fiftyScores);\n else\n weighted_recommendedInsurance.additional.push(...fiftyScores);\n }", "function addRatings() {\n OMDBProvider.getMovie(vm.film.imdb_id).then(movie => {\n vm.film.ratings = movie.Ratings;\n getTrailers();\n })\n }", "function giveRating(rating)\t{\n\n\t\tvar i = 0;\n\t\tfor (i=0; i<ratingEstimators.length; i++){\n\t\t\t\n\t\t\tratingEstimators[i].addRating(rating);\n\t\t}\n\t\tactualRatingHistory.addRating(rating);\n\t\tlatestInteractionDate = rating.getDate();\n\t}", "function add_item(p, v) {\n p.count++;\n p.total += v.salary;\n p.average = p.total / p.count;\n return p;\n }", "addRating(arg) {\n this._ratings.push(arg);\n }", "static rateBookById(id) {\n for (let i = 0; i < ratings.length; i++) {\n if (ratings[i].bookId == id) {\n ratings[i].bookRatings.push(parseInt(modalRatingInput.value))\n ratings[i].usersId.push(parseInt(userCurrent))\n }\n }\n }", "function getSingleRating(hospital,ratingField){\n sort(ratingField[\"field\"],ratingField[\"order\"]);\n\n var position = getPosition(tempActualLocation,hospital);\n\n var singleRating = position/actualLocation.length*ratingField[\"weight\"]*10;\n //alert(position/actualLocation.length);\n return singleRating;\n}", "function setRating ( newRating ) {\n \n}", "function updatePersonality() {\n\t\t\n\t\tfor (i = 0; i < userStats.length ; i++) {\n\t\t\tuserStats[i] += tempStats[i];\n\t\t}\n\t}", "function calcNewBonusArray(singleEmployee) {\n console.log('in calcNewBonusArray singleEmployee ->', singleEmployee);\n\n var empRating = singleEmployee[3];\n\n var bonusPercentage = 0;\n\n // determine base bonus using emp rating\n switch (empRating) {\n case 2:\n bonusPercentage = 0.0;\n break;\n case 3:\n bonusPercentage = 0.04;\n break;\n default:\n }\n\n // adjust based on empNum\n\n // adjust based on salary\n\n // check that they are not above a percentage\n\n // contain name, bonus percentage, adjustedComp, bonus\n var newEmpArray = [];\n\n // DO STUFF?\n\n // return new array\n return newEmpArray;\n}", "function computeBonus(employee){\n let employeeBonus={\n name: employee.name,\n bonusPercentage: 0,\n totalCompensation: 0,\n totalBonus:0\n };\n\n//compute base bonus percentage\n if(employee.reviewRating<=2){\n employeeBonus.bonusPercentage=0;\n }else if (employee.reviewRating===3){\n employeeBonus.bonusPercentage=.04\n }else if (employee.reviewRating===4){\n employeeBonus.bonusPercentage=.06\n }else if (employee.reviewRating===5){\n employeeBonus.bonusPercentage=.10\n }\n\n//compute additional bonus percentage, if applicable\n if(employee.employeeNumber.toString().length===4){\n employeeBonus.bonusPercentage= employeeBonus.bonusPercentage+.05\n }\n if (Number(employee.annualSalary)>65000){\n employeeBonus.bonusPercentage= employeeBonus.bonusPercentage-.01\n }\n\n if(employeeBonus.bonusPercentage>.13){\n employeeBonus.bonusPercentage=.13\n }else if (employeeBonus.bonusPercentage<0){\n employeeBonus.bonusPercentage=0;\n }\n //calculate final bonus and compensation\n employeeBonus.totalBonus=Math.round(employee.annualSalary*employeeBonus.bonusPercentage);\n employeeBonus.totalCompensation= employeeBonus.totalBonus+Number(employee.annualSalary);\n //employeeBonus.bonusPercentage=employeeBonus.bonusPercentage*10;\n\n return employeeBonus;\n}", "enhanceProductRatings(productObj) {\n var roundedRating = parseInt(productObj.RoundedRating); \n var reviewFullStars = [];\n var reviewEmptyStars = [];\n\n // If there are no reviews, make some up!\n if (!productObj.ReviewCount) {\n productObj.ReviewCount = Math.floor(Math.random() * Math.floor(20));\n roundedRating = Math.floor(Math.random() * Math.floor(4)) + 1;\n }\n\n for (var i = 0; i < 5; i++) {\n if (i < roundedRating) {\n reviewFullStars.push(1);\n } else {\n reviewEmptyStars.push(1);\n }\n }\n\n productObj.ReviewFullStars = reviewFullStars;\n productObj.ReviewEmptyStars = reviewEmptyStars;\n productObj.ReviewCount = productObj.ReviewCount || 0;\n }", "addAverageRating(reviews) {\r\n\t\treturn reviews.map((review) => {\r\n\t\t\tlet avg = Math.round((review.food + review.service + review.ambience)/3);\r\n\t\t\treview.stars = avg;\r\n\t\t\treview.overall = avg;\r\n\t\t\treturn review;\r\n\t\t})\r\n\t}", "function bonusCalculation(arrEmployees){\n var employeeBonus = [];\n var bonus = 0;\n employeeBonus[0] = arrEmployees.name;\nswitch(arrEmployees.reviewRating) {\n case 1:\n bonus = 0;\n break;\n case 2:\n bonus = 0;\n break;\n case 3:\n bonus = .04;\n break;\n case 4:\n bonus = .06;\n break;\n case 5:\n bonus = .10;\n break;\n default: return false;\n }\n if (arrEmployees.employeeNumber.length == 4) {\n bonus += .05;\n }\n if (arrEmployees.salary > 65000) {\n bonus -= .01;\n }\n if (bonus > .13) {\n bonus = .13;\n }\n if (bonus < 0) {\n bonus = 0;\n }\n var bonusPercent = bonus * 100;\n employeeBonus[1] = bonusPercent;\n employeeBonus[2] = (arrEmployees.salary * (1 + bonus)).toFixed(2);\n employeeBonus[3] = Math.round(arrEmployees.salary * bonus);\n return employeeBonus;\n }", "function get_ratings(){\r\n\t\t\t \tvar value = parseInt(this.attributes[\"value\"].value);\r\n\t\t\t \tvar id = parseInt(this.attributes[\"id\"].value);\r\n\t\t\t \tclient_votes.push(value);\r\n\t\t\t \tids.push(id)\r\n\t\t\t \t//console.log(client_votes, ids);\r\n\t\t\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Xuice is the XML full framework upgrade from Juice This is a tech test, it should be the next exi framework base
function Xuice() { }
[ "function XUtils() { }", "static createAllureXML() {\n const allureReporter = require(\"cucumberjs-allure-reporter\");\n const xmlReports = process.cwd() + \"/reports/xml\";\n Reporter.createDirectory(xmlReports);\n allureReporter.config({\n targetDir: xmlReports\n })\n }", "xmlGenerator() {\n if (!Strophe._xmlGenerator) {\n Strophe._xmlGenerator = shims[\"b\" /* getDummyXMLDOMDocument */]();\n }\n\n return Strophe._xmlGenerator;\n }", "function PackageXRef() {\n\n}", "function KupuXhtmlTestCase() {\n this.name = 'KupuXhtmlTestCase';\n\n this.incontext = function(s) {\n return '<html><head><title>test</title></head><body>'+s+'</body></html>';\n }\n this.serializeNode = function(n) {\n var serializer = new XMLSerializer();\n return serializer.serializeToString(n);\n }\n this.verifyResult = function(newdoc, exp) {\n var expected = this.incontext(exp);\n var actual = this.serializeNode(newdoc);\n actual = actual.replace('\\xa0', '&nbsp;');\n actual = actual.replace(/^<html[^>]*>/, '<html>');\n if (actual == expected)\n return;\n\n var context = /<html[^>]*><head><title>test<\\/title><\\/head><body>(.*)<\\/body><\\/html>/i;\n if (context.test(actual) && context.test(expected)) {\n var a = context.exec(actual)[1];\n var e = context.exec(expected)[1];\n throw('Assertion failed: ' + a + ' != ' + e);\n }\n throw('Assertion failed: ' + actual + ' != ' + expected);\n }\n\n this.conversionTest = function(data, expected) {\n var doc = this.doc.documentElement;\n var editor = this.editor;\n this.body.innerHTML = data;\n var xhtmldoc = Sarissa.getDomDocument();\n var newdoc = editor._convertToSarissaNode(xhtmldoc, this.doc.documentElement);\n this.verifyResult(newdoc, expected);\n }\n\n this.setUp = function() {\n var iframe = document.getElementById('iframe');\n this.doc = iframe.contentWindow.document;\n this.body = this.doc.getElementsByTagName('body')[0];\n this.doc.getElementsByTagName('title')[0].text = 'test';\n this.editor = new KupuEditor(null, {}, null);\n };\n\n this.arrayContains = function(ary, test) {\n for (var i = 0; i < ary.length; i++) {\n if (ary[i]==test) {\n return true;\n }\n }\n return false;\n }\n\n this.testExclude = function() {\n // Check that the exclude functions work as expected.\n var validator = new XhtmlValidation(this.editor);\n var events = ['onclick', 'ondblclick', 'onmousedown',\n 'onmouseup', 'onmouseover', 'onmousemove',\n 'onmouseout', 'onkeypress', 'onkeydown',\n 'onkeyup'];\n var expected = ['onclick', 'ondblclick', 'onmousedown', 'onmouseup', 'onmouseout', 'onkeypress', 'onkeyup'];\n\n var actual = validator._exclude(events, 'onmouseover|onmousemove|onkeydown');\n this.assertEquals(actual.toString(), expected.toString());\n\n // check is also works with arrays.\n actual = validator._exclude(events, ['onmouseover','onmousemove','onkeydown']);\n this.assertEquals(actual.toString(), expected.toString());\n\n // Check we have a bgcolor attribute\n this.assertTrue(this.arrayContains(validator.tagAttributes.thead, 'charoff'));\n this.assertTrue(validator.attrFilters['charoff'] != null);\n validator.excludeAttributes(['charoff']);\n this.assertTrue(validator.attrFilters['charoff']==null);\n this.assertTrue(!this.arrayContains(validator.tagAttributes.thead, 'charoff'));\n this.assertTrue(this.arrayContains(validator.tagAttributes.td, 'height'));\n this.assertTrue(this.arrayContains(validator.tagAttributes.th, 'height'));\n validator.excludeTagAttributes(['table','th'], ['width','height']);\n this.assertTrue(this.arrayContains(validator.tagAttributes.td, 'height'));\n this.assertFalse(this.arrayContains(validator.tagAttributes.th, 'height'));\n }\n\n this.testSet = function() {\n var validator = new XhtmlValidation(this.editor);\n\n var set1 = new validator.Set(['a','b','c']);\n this.assertTrue(set1.a && set1.b && set1.c);\n var set2 = new validator.Set(set1);\n this.assertTrue(set2.a && set2.b && set2.c);\n }\n this.testValidator = function() {\n var validator = new XhtmlValidation(this.editor);\n var table = validator.States['table'];\n var tags = [];\n for (var tag in table) {\n this.assertEquals(table[tag], 1);\n tags.push(tag);\n }\n this.assertEquals(tags.toString(),\n ['caption','col','colgroup',\n 'thead','tfoot','tbody','tr'].toString());\n };\n\n this.testConvertToSarissa = function() {\n var data = '<p class=\"blue\">This is a test</p>';\n this.conversionTest(data, data);\n };\n \n this.testRemoveTrailingBr = function() {\n var data = '<p class=\"blue\">This is a test<br></p>';\n var expected = '<p class=\"blue\">This is a test</p>';\n this.conversionTest(data, expected);\n };\n this.testRemoveTrailingBr2 = function() {\n var data = '<p class=\"blue\">This is a test<br>with more text<br></p>';\n var expected = '<p class=\"blue\">This is a test<br/>with more text</p>';\n this.conversionTest(data, expected);\n };\n this.testRemoveTrailingBr3 = function() {\n // If someone is trying to do spacing by inserting extra breaks\n // we shouldn't remove any of them.\n var data = '<p class=\"blue\">This is a test<br><br>with more text<br><br></p>';\n var expected = '<p class=\"blue\">This is a test<br/><br/>with more text<br/><br/></p>';\n this.conversionTest(data, expected);\n };\n this.testFixTopLevelBr = function() {\n var data = '<p>alpha</p>beta<br><p>gamma</p>';\n var expected = '<p>alpha</p><p>beta</p><p>gamma</p>';\n this.conversionTest(data, expected);\n };\n this.testNakedBr = function() {\n var data = '<p>alpha</p><br><p>gamma</p>';\n var expected = '<p>alpha</p><p/><p>gamma</p>';\n this.conversionTest(data, expected);\n };\n this.testMultipleNakedBr = function() {\n var data = '<p>alpha</p><br><br><br><br><p>gamma</p>';\n var expected = '<p>alpha</p><p/><p/><p/><p/><p>gamma</p>';\n this.conversionTest(data, expected);\n };\n this.testXmlAttrs = function() {\n var data = '<pre xml:space=\"preserve\" xml:lang=\"fr\">This is a test</pre>';\n var expected1 = '<pre xml:lang=\"fr\" xml:space=\"preserve\">This is a test</pre>';\n this.conversionTest(data, expected1);\n var expected2 = '<pre>This is a test</pre>';\n this.editor.xhtmlvalid.excludeAttributes(['xml:lang','xml:space']);\n this.conversionTest(data, expected2);\n }\n this.testConvertToSarissa2 = function() {\n var data = '<div id=\"div1\">This is a test</div>';\n this.conversionTest(data, data);\n }\n this.testbadTags = function() {\n var data = '<div><center>centered</center><p>Test</p><o:p>zzz</o:p></div>';\n var expected = '<div>centered<p>Test</p>zzz</div>';\n this.conversionTest(data, expected);\n }\n this.testnbsp = function() {\n var data = '<p>Text with&nbsp;<strong>non-break</strong> space</p>';\n this.conversionTest(data, data);\n };\n this.teststyle = function() {\n var data = '<p style=\"text-align:right; mso-silly: green\">Text aligned right</p>';\n var expected = '<p style=\"text-align: left;\">Text aligned right</p>';\n var doc = this.doc.documentElement;\n var editor = this.editor;\n this.body.innerHTML = data;\n this.body.firstChild.style.textAlign = 'left';\n this.body.firstChild.style.display = 'block';\n //alert(this.body.firstChild.style.cssText);\n var xhtmldoc = Sarissa.getDomDocument();\n var newdoc = editor._convertToSarissaNode(xhtmldoc, this.doc.documentElement);\n this.verifyResult(newdoc, expected);\n };\n this.testclass = function() {\n var data = '<div class=\"MsoNormal fred\">This is a test</div>';\n var expected = '<div class=\"fred\">This is a test</div>';\n this.conversionTest(data, expected);\n }\n this.testclass2 = function() {\n var data = '<div class=\"MsoNormal\">This is a test</div>';\n var expected = '<div>This is a test</div>';\n this.conversionTest(data, expected);\n }\n this.testTable = function() {\n // N.B. This table contains text and a <P> tag where they\n // aren't legal. Mozilla strips out the <P> tag but lets the\n // text through, IE lets both through.\n \n var data = '<TABLE class=\"listing\">BADTEXT!<THEAD><TR><TH>Col 01</TH><TH class=align-center>Col 11</TH>'+\n '<TH class=align-right>Col 21</TH></TR></THEAD>'+\n '<TBODY><TR>'+\n '<TD>text</TD>'+\n '<TD class=align-center>a</TD>'+\n '<TD class=align-right>r</TD></TR>'+\n '<TR>'+\n '<TD>more text</TD>'+\n '<TD class=align-center>aaa</TD>'+\n '<TD class=align-right>rr</TD></TR>'+\n '<TR>'+\n '<TD>yet more text</TD>'+\n '<TD class=align-center>aaaaa</TD>'+\n '<TD class=align-right>rrr</TD></TR></TBODY><P></TABLE>';\n var expected = '<table class=\"listing\"><thead><tr><th>Col 01</th><th class=\"align-center\">Col 11</th>'+\n '<th class=\"align-right\">Col 21</th></tr></thead>'+\n '<tbody><tr>'+\n '<td>text</td>'+\n '<td class=\"align-center\">a</td>'+\n '<td class=\"align-right\">r</td></tr>'+\n '<tr>'+\n '<td>more text</td>'+\n '<td class=\"align-center\">aaa</td>'+\n '<td class=\"align-right\">rr</td></tr>'+\n '<tr>'+\n '<td>yet more text</td>'+\n '<td class=\"align-center\">aaaaa</td>'+\n '<td class=\"align-right\">rrr</td></tr></tbody></table>';\n\n this.editor.xhtmlvalid.filterstructure = true;\n this.conversionTest(data, expected);\n }\n this.testCustomAttribute = function() {\n var validator = this.editor.xhtmlvalid;\n var data = '<div special=\"magic\">This is a test</div>';\n this.assertTrue(validator.tagAttributes.td===validator.tagAttributes.th);\n this.editor.xhtmlvalid.includeTagAttributes(['div','td'],['special']);\n // Check that shared arrays are no longer shared...\n this.assertFalse(validator.tagAttributes.td===validator.tagAttributes.th);\n this.assertTrue(this.arrayContains(validator.tagAttributes.td, 'special'));\n this.assertFalse(this.arrayContains(validator.tagAttributes.th, 'special'));\n this.editor.xhtmlvalid.setAttrFilter(['special']);\n this.conversionTest(data, data);\n }\n\n this.testXHTML10Strict = function() {\n // Some XHTML 1.0 Strict tags\n var data = '<hr/>'+\n '<bdo>bdo</bdo>'+\n '<big>big</big>'+\n '<del>del</del>'+\n '<ins>ins</ins>'+\n '<small>small</small>'+\n '<tt>tt</tt>';\n this.editor.xhtmlvalid.filterstructure = true;\n this.conversionTest(data, data);\n };\n\n this.testXHTML10Transitional = function() {\n // Some XHTML 1.0 Transitional tags\n var data = '<dir><li>dir</li></dir>'+\n '<menu><li>menu</li></menu>'+\n '<s>s</s>'+\n '<strike>strike</strike>'+\n '<basefont size=\"2\"/>';\n this.editor.xhtmlvalid.filterstructure = true;\n this.conversionTest(data, data);\n }\n\n // Some tests to ensure that we don't put anything in a <p> tag\n // which isn't allowed in a <p> tag.\n // Can't test with <p><div>x</div></p> as Firefox DOM fixes that\n // for us (but not as we want it fixed) so we use something FF doesn't already fix.\n this.testPcleanup = function() {\n var data = '<p><table><tbody><tr><td>oops</td></tr></tbody></table></p>';\n var expected = '<table><tbody><tr><td>oops</td></tr></tbody></table>';\n this.conversionTest(data, expected);\n };\n\n this.testPcleanup2 = function() {\n var data = '<p class=\"blue\">some text<br/><table><tbody><tr><td>oops</td></tr></tbody></table>more text<br/></p>';\n var expected = '<p class=\"blue\">some text</p><table><tbody><tr><td>oops</td></tr></tbody></table><p class=\"blue\">more text</p>';\n this.conversionTest(data, expected);\n };\n\n this.testPWithCaptionedImg = function() {\n // Captioned images are converted to block tags so they must\n // not be inside a paragraph.\n var data = '<p>some text<br/><img class=\"image-inline captioned\" src=\"data:\" alt=\"xyzzy\" height=\"1\" width=\"1\"/>blah</p>';\n var expected = '<p>some text</p><img class=\"image-inline captioned\" src=\"data:\" alt=\"xyzzy\" height=\"1\" width=\"1\"/><p>blah</p>';\n this.conversionTest(data, expected);\n // If there is no surrounding text we don't want empty paras.\n var data = '<p><img class=\"image-inline captioned\" src=\"data:\" alt=\"xyzzy\" height=\"1\" width=\"1\"/></p>';\n var expected = '<img class=\"image-inline captioned\" src=\"data:\" alt=\"xyzzy\" height=\"1\" width=\"1\"/>';\n this.conversionTest(data, expected);\n // But ordinary images are fine.\n var data = '<p>some text<br/><img class=\"image-inline\" src=\"data:\" alt=\"xyzzy\" height=\"1\" width=\"1\"/>blah</p>';\n var expected = '<p>some text<br/><img class=\"image-inline\" src=\"data:\" alt=\"xyzzy\" height=\"1\" width=\"1\"/>blah</p>';\n this.conversionTest(data, expected);\n };\n\n // Firefox is broken wrt to <br> tags and newlines inside <pre>.\n // It thinks that <br>\\n is two newlines but in fact the HTML spec\n // says it should ignore any whitespace following a <br>.\n this.testBrInsidePre = function() {\n }\n this.tearDown = function() {\n this.body.innerHTML = '';\n };\n}", "function exposeTestFunctionNames()\n{\nreturn ['XPathEvaluator_createNSResolver_all'];\n}", "function hc_domimplementationfeaturenoversion() {\n var success;\n var doc;\n var domImpl;\n var state;\n doc = load(\"hc_staff\");\n domImpl = doc.implementation;\n\n\tif(\n\t\n\t(builder.contentType == \"text/html\")\n\n\t) {\n\tstate = domImpl.hasFeature(\"HTML\",\"\");\n\n\t}\n\t\n\t\telse {\n\t\t\tstate = domImpl.hasFeature(\"XML\",\"\");\n\n\t\t}\n\tassertTrue(\"hasFeatureBlank\",state);\n\n}", "function XML() {\n}", "function readAXMLsrc(){\nif(checkAXMLVersion(axml)!=\"unknown\"){\nresetDefaults()\nif(checkAXMLVersion(axml)<2){\nmsg(\"Warning!\",\"Attempting Backwards Compatability Mode\")\naxml1read(axml)\n}else{\naxml2read(axml)\n}\n}else{\nmsg(\"Error\",\"Unknown/Invalid Project File\")\n}\n}", "_exposeWiris() {\n\n window.WirisPlugin = {\n Core: core_src_Core,\n Parser: parser_Parser,\n Image: src_image_Image,\n MathML: mathml_MathML,\n Util: util_Util,\n Configuration: Configuration,\n Listeners: Listeners,\n IntegrationModel: integrationmodel_IntegrationModel,\n CurrentInstance: currentInstance,\n Latex: latex_Latex\n }\n\n }", "function verifySupport(xFile) {\r\n if (document.implementation && document.implementation.createDocument) {\r\n // this is the W3C DOM way, supported so far only in NN6\r\n xDoc = document.implementation.createDocument(\"\", \"theXdoc\", null);\r\n } else if (typeof ActiveXObject != \"undefined\") {\r\n // make sure real object is supported (sorry, IE5/Mac)\r\n if (document.getElementById(\"msxml\").async) {\r\n xDoc = new ActiveXObject(\"Msxml.DOMDocument\");\r\n }\r\n }\r\n if (xDoc && typeof xDoc.load != \"undefined\") {\r\n // load external file (from same domain)\r\n xDoc.load(xFile);\r\n return true;\r\n } else {\r\n var reply = confirm(\"This example requires a browser with XML support, such as IE5+/Windows or Netscape 6+.\\n \\nGo back to previous page?\");\r\n if (reply) {\r\n history.back();\r\n }\r\n }\r\n return false;\r\n}", "function ZMTB_AjxXmlDoc() {\n\tif (!ZMTB_AjxXmlDoc._inited)\n\t\tZMTB_AjxXmlDoc._init();\n}", "function findUberXID(products, next) {\n if ($.isArray(products) && products.length > 0) {\n // find uberX product id\n products.forEach(function(value) {\n if (value.display_name === 'uberX') {\n selectedProduct = value.product_id;\n if (next) {\n next();\n }\n return;\n }\n });\n }\n }", "function USX(node) {\n\tthis.version = node.version;\n\tthis.emptyElement = node.emptyElement;\n\tthis.usxParent = null;\n\tthis.children = []; // includes books, chapters, and paragraphs\n\tObject.seal(this);\n}", "function xml$1() {\n var language = assign(html$1(), {\n id: 'xml',\n name: 'XML',\n alias: []\n });\n language.grammar.main.unshift([CATEGORY_PROLOG, /<\\?[\\s\\S]*?\\?>/]);\n return language;\n}", "function getDummyXMLDOMDocument() {\n // nodejs\n if (typeof document === 'undefined') {\n try {\n var DOMImplementation = require('xmldom').DOMImplementation;\n\n return new DOMImplementation().createDocument('jabber:client', 'strophe', null);\n } catch (err) {\n throw new Error('You must install the \"xmldom\" package to use Strophe in nodejs.');\n }\n } // IE < 10\n\n\n if (document.implementation.createDocument === undefined || document.implementation.createDocument && document.documentMode && document.documentMode < 10) {\n var doc = _getIEXmlDom();\n\n doc.appendChild(doc.createElement('strophe'));\n return doc;\n } // All other supported browsers\n\n\n return document.implementation.createDocument('jabber:client', 'strophe', null);\n }", "is_xml() {\n return (Object.keys(this.xmljs).length > 0)\n }", "static addElementSupport(name, cb) {\r\n if (!UXFCanvas.umlElements) UXFCanvas.umlElements = {};\r\n UXFCanvas.umlElements[name] = cb;\r\n }", "function zXMLSerializer() {\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render Template Friends List
function renderFriendList(friends, $container){ $playlistFriends.children[0].remove(); friends.forEach((friend) => { let HTMLString = friendsTemplate(friend); let friendElement = createTemplate(HTMLString); $container.append(friendElement); }); }
[ "render(){\n\t\tif(this.props.loggedIn && !this.props.loadedFriends &&this.props.token){\n\t\t\tthis.props.getFriends(this.props.userId, this.props.token); \n\t\t}\n\t\t//const [dense, setDense] = this.setDense();\n\t\treturn(\n\t\t\t<div className={this.classes.root}>\n\t\t\t\t<Grid container justify = \"center\">\n\t\t\t\t\t<Typography variant=\"h4\" className={this.classes.title}>\n\t\t\t\t\t\tFriend List</Typography>\n\t\t\t\t</Grid>\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.props.loadedFriends ?\n\t\t\t\t\t\t\t<div>\n\t\t\t\t\t\t\t\t<List>\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tthis.props.friends.map(friend => {\n\t\t\t\t\t\t\t\t\t\t\tconst fullName = friend.firstName + ' ' + friend.lastName;\n\t\t\t\t\t\t\t\t\t\t\treturn(\n\t\t\t\t\t\t\t\t\t\t\t\t<StyledListItem className={this.classes.friendList}>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<ListItemText button onClick={e => this.selectFriend(\n\t\t\t\t\t\t\t\t\t\t\t\t\te,friend)} primary={fullName}/>\n\t\t\t\t\t\t\t\t\t\t\t\t\t<DeleteIcon className={this.classes.rightIcon} \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tonClick={e => this.removeFriend(friend)}/>\n\t\t\t\t\t\t\t\t\t\t\t\t</StyledListItem>\n\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t})\t\t\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t</List>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t:\n\t\t\t\t\t\t\t<p></p>\n\t\t\t\t\t}\t\n\t\t\t</div>\t\t\n\t\t);\n\t}", "function renderFriend(friend) {\n console.log(friend.fullName());\n var output = `<h2>${friend.fullName()}</h2>`;\n\n // super gross...\n document.body.innerHTML += output;\n}", "function renderUserList() {\n let htmlHead = `\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>List Of Users</title>\n</head>`;\n let bodyOpen = `\n<body>\n <div style=\"margin:0 auto; border:1px solid gray; width:90%; height:100%; padding:32px;\">\n <p><a href=\"/\">Go Back</a></p>\n <h1>List Of Users</h1>\n <ul>`;\n let bodyClose = `\n </ul>\n </div>\n</body>\n</html>`;\n if (USERS.length === 0) {\n bodyOpen += '<li>There are no users in the database</li>';\n }\n else { \n USERS.forEach(user => {\n let {userid, name, email, age} = user;\n let listItem = `<li>User ID: ${userid} Name: ${name} Email Address: ${email} Age: ${age} <a href=\"/edit/${userid}\">Edit This User</a></li>`;\n bodyOpen += listItem;\n });\n }\n let htmlBody = bodyOpen + bodyClose;\n return htmlHead + htmlBody;\n}", "function renderFriendList(data) {\n // Using array.map to create an array of HTML contents, then use \n // join function to merge them together\n if (data.length === 0) {\n dataPanel.innerHTML = `\n <img class=\"my-5 w-75 mx-auto\" src=\"https://webmarketingschool.com/wp-content/uploads/2018/03/nojobsfound.png\">\n `\n } else {\n dataPanel.innerHTML = data.map(({ avatar, id, name, surname }) => {\n return `\n <div class=\"col-12 col-sm-6 col-md-4 col-lg-3 pb-3\">\n <div class=\"card\">\n <div class=\"card-image-wrapper\">\n <img src=\"${avatar}\" alt=\"friend-image\" data-bs-toggle=\"modal\" data-bs-target=\"#friend-modal\" data-id=${id}>\n </div>\n <div class=\"card-body\">\n <h5 class=\"card-title\">${name} ${surname}</h5>\n </div>\n </div>\n </div>\n `\n }).join('')\n }\n return true\n}", "function renderList() {\n main.innerHTML = people.map((person, idx) => {\n return `<article class=\"dt w-100 bb b--black-05 pb2 mt2\" data-index=\"${idx}\" href=\"#0\">\n <div class=\"dtc w2 w3-ns v-mid\">\n <img src=\"${person.picture.large}\" class=\"ba b--black-10 db br-100 w2 w3-ns h2 h3-ns\"/>\n </div>\n <div class=\"dtc v-mid pl3\">\n <h1 class=\"f6 f5-ns fw6 lh-title black mv0\">${person.name.first} ${person.name.last}</h1>\n <h2 class=\"f6 fw4 mt0 mb0 black-60\">@${person.login.username}</h2>\n </div>\n <div class=\"dtc v-mid\">\n <form class=\"w-100 tr\">\n <button data-index=\"${idx}\" class=\"follow f6 button-reset bg-white ba b--black-10 dim pointer pv1 black-60\" type=\"submit\">${person.isFollowing ? '- Following' : '+ Follow'}</button>\n </form>\n </div>\n </article>`\n }).join('');\n}", "function FriendsList() {\n //***NEEDS IMPLEMENTATION***\n}", "function generateFriend(friendData) {\n var str = '';\n str += '<div class=\"friendTile\">';\n str += '<h3 class=\"friendTileName\">' + friendData.Username + '</h3>';\n str += '<p class=\"friendTileBio\">' + friendData.Bio + '</p>';\n str += '</div>';\n return str;\n}", "function showMemberInfo(array)\n{\n //concat html tags to array data\n var html = ''; \n\thtml += '<ul>';\n\t\n //for each row data \n for (var i = 0 ; i < array.length ; i++) {\n \tif ($j('#ownerId').val() == array[i].uid) {\n \thtml += '<li class=\"own\">';\n }\n else {\n \thtml += '<li class=\"friend\">';\n }\n \n html += '<p class=\"pic\"><img src=\"' + array[i].thumbnailUrl + '\" width=\"30\" height=\"30\" class=\"userPic\" alt=\"' + array[i].displayName + '\" /><span class=\"frame\"></span></p>';\n html += '<p class=\"name\">' + array[i].displayName + '</p>';\n html += '</li>';\n \n }\n html += '</ul>';\n return html;\n}", "function renderUserProfileList(data){\n //clear previous user search\n $(\"#userProfileList\").html('');\n if(data.user){\n var followers_count = data.user.followers;\n var following_count = data.user.following;\n var email = data.user.email;\n var userProfileCard = createDomUserProfile(email,following_count,followers_count);\n $(\"#userProfileList\").append(userProfileCard);\n\t\tvar followerListDiv = \"#followerList\";\n\t\tvar followingListDiv = \"#followingList\";\n\t\tvar followerLink = \"#linkFollowerInfo\";\n\t\tvar followingLink = \"#linkFollowingInfo\";\n\t\tlinkFollowerInfoHandler(followerLink,followerListDiv,\"#followerHeader\");\n\t\tlinkFollowerInfoHandler(followingLink,followingListDiv,\"#followingHeader\");\n }\n}", "function generateFriend(friendData) {\n var str = '';\n str += '<div class=\"friendTile\">';\n str += '<h3 class=\"friendTileName\">' + friendData.Username + '</h3>';\n str += '<p class=\"friendTileBio\">' + friendData.Bio + '</p>';\n str += '</div>';\n return str;\n}", "function createContentFriendsListElement(friendsData) {\r\n // create div\r\n const mainContentDiv = document.createElement(\"div\");\r\n mainContentDiv.setAttribute = (\"class\", \"pure-menu custom-restricted-width\");\r\n mainContent.appendChild(mainContentDiv);\r\n // create span\r\n const mainContentSpan = document.createElement(\"span\");\r\n const mainContentSpanTxt = document.createTextNode(\"Friends\");\r\n mainContentSpan.setAttribute(\"class\", \"pure-menu-heading\");\r\n mainContentDiv.appendChild(mainContentSpan);\r\n mainContentSpan.appendChild(mainContentSpanTxt);\r\n // create ul\r\n const mainContentUl = document.createElement(\"ul\");\r\n mainContentUl.setAttribute(\"class\", \"pure-menu-list\");\r\n mainContentDiv.appendChild(mainContentUl); // ul \r\n\r\n // Create friends link: li and a\r\n friendsData.forEach(friends => {\r\n // To load each object in an Array\r\n const friendList = document.querySelector(\".content ul\");\r\n // Li for friends list\r\n friendList.innerHTML += `<li class=\"pure-menu-item\">\r\n <a href=\"#\" class=\"pure-menu-link\" data-id=${friends.id}>${friends.firstName} ${friends.lastName}</a>\r\n </li>`;\r\n })\r\n}", "renderUserList() {\n // clear user list element\n this.userListElement.innerHTML = \"\";\n\n // for each user in userList\n for(const userKey in this.userList) {\n // get current user\n const currUser = this.userList[userKey];\n // create LI element for user\n const userDiv = document.createElement(\"li\");\n // user LI text to user name\n userDiv.innerText = currUser\n // append LI to user list element\n this.userListElement.appendChild(userDiv);\n }\n }", "function displayFriends(){\n\t// declare variables\n\tvar callback = function(json){\n\t\tvar friends = json.friends;\n\t\t// put all data in its proper place\n\t\t$('.baby-step').each(function(){\n\t\t\tvar id = $(this).attr('id');\n\t\t\tvar babyStep = id.split('-')[3];\n\t\t\tvar msg = buildMessage(friends, babyStep);\n\t\t\t$(\"#\"+id).find('.baby-step-friends').html(msg);\n\t\t});\n\t};\n\t// get friends list\n\tgetFriends(callback);\n}", "displayMembersList(){\n let memberListDiv = document.querySelector(\"#members-list\");\n let membersHeading = document.createElement(\"strong\");\n membersHeading.textContent = \"Members: \"\n memberListDiv.append(membersHeading)\n for(var i = 0; i < this.members.length; i++){\n let memberListItem = document.createElement(\"span\");\n memberListItem.textContent = ` ${this.members[i].name} |`\n memberListDiv.append(memberListItem);\n }\n\n }", "function renderUserList(data) {\n if (!data.length) {\n window.location.href = \"/users\";\n }\n $(\".hidden\").removeClass(\"hidden\");\n }", "function friendList(value) {\n friendListInitialize();\n let ulSelector = document.querySelector('div.content > ul');\n //Loops for each friend and displays the data\n value.forEach(item => {\n console.log(item.firstName);\n let li = document.createElement('li');\n let a = document.createElement('a');\n a.setAttribute('class', 'pure-menu-link');\n a.setAttribute('data-id', item.id);\n let friendName = document.createTextNode(`${item.firstName} ${item.lastName}`);\n li.setAttribute('class', 'pure-menu-item');\n a.appendChild(friendName);\n li.appendChild(a);\n ulSelector.appendChild(li);\n });\n}", "function getFriendHtml() {\n var result = '';\n result += '<div style=\"width: 60%\" class=\"text\">' + getInformalName(owner) + ' is one of your friends.</div>';\n result += '<div class=\"inviteOption\">' + getGroupInviteHtml(owner) + '</div>';\n return result;\n}", "function renderizarUsuarios(personas) {\n\n console.log(personas);\n\n var html = ''\n\n html += '<li>';\n html += '<a href=\"javascript:void(0)\" class=\"active\"> Chat de <span>' + urlParams.get('sala') + '</span></a>';\n html += '</li>';\n\n for (var i = 0; i < personas.length; i++) {\n html += '<li>';\n html += ' <a data-id=\"' + personas[i].id + '\" href=\"javascript:void(0)\"><img src=\"assets/images/users/1.jpg\" alt=\"user-img\" class=\"img-circle\"> <span>' + personas[i].nombre + '<small class=\"text-success\">online</small></span></a>';\n html += '</li>';\n\n }\n\n divUsuarios.html(html);\n}", "render() {\n // destructure friendlist from state\n const { friendList } = this.state;\n\n console.log(friendList);\n\n return (\n <Wrapper>\n <h1 className=\"title\">Friends List</h1>\n <h2 className=\"score\"></h2>\n {/* Use .map to render friendlist */}\n {friendList.map(friend => {\n return (\n <FriendCard\n key={friend.id}\n friendId={friend.id}\n name={friend.name}\n image={friend.image}\n location={friend.location}\n occupation={friend.occupation}\n removeFriend={this.removeFriend}\n />\n );\n })}\n </Wrapper>\n );\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes the random item and inserts it into the css class image destination
function getRandomImage() { var jumbo = document.getElementById("jumbotron"); var randomItem = randomList[Math.floor(Math.random()*randomList.length)]; jumbo.style.backgroundImage = "url(../javapic/images/" + randomItem +")"; }
[ "setRandomImg(item, lstImgs) {\n var h = $(item).height();\n var w = $(item).width();\n $(item).css(\"width\", w + \"px\").css(\"height\", h + \"px\");\n $(item).attr(\"src\", lstImgs[Math.floor(Math.random() * lstImgs.length)]);\n }", "setRandomImg(item, lstImgs) {\n const imageWidth = item.clientWidth;\n const imageHeight = item.clientHeight;\n item.style.width = `${imageWidth}px`;\n item.style.height = `${imageHeight}px`;\n item.style.objectFit = 'cover';\n item.style.objectPosition = '0 0';\n item.src = lstImgs[Math.floor(Math.random() * lstImgs.length)];\n }", "setRandomImg(item, lstImgs) {\n const imageWidth = item.clientWidth;\n const imageHeight = item.clientHeight;\n item.style.width = `${imageWidth}px`;\n item.style.height = `${imageHeight}px`;\n item.style.objectFit = 'cover';\n item.style.objectPosition = '0 0';\n item.src = lstImgs[Math.floor(Math.random() * lstImgs.length)];\n }", "function placeItem(){\r\n \r\n items.forEach(function(obj){\r\n coord=rightCoordinate(); // generate random coordinates \r\n obj.actualPosition = coord;\r\n var itemImage = $(\"<img>\").attr(\"src\", obj.image).addClass('items ' + obj.name);\r\n var row = $($(\"#tableGame tr\")[coord.row]);\r\n var cell = $($(\"td\", row)[coord.cell]);\r\n var tile = $(\".tile\", cell); \r\n tile.prepend(itemImage);\r\n });\r\n}", "function randImg(el) {\n return 'url(https://source.unsplash.com/category/nature/' + el.width() + 'x' + el.height() + ')';\n }", "function insertImg() {\n\n var randomPairs = getRandomPairs();\n\n randomPairs.forEach(function (item, i) {\n\n document.querySelector('#square' + item.posId + ' .squareImg').setAttribute('src', './img/' + item.imgId + '.png');\n });\n}", "function replacementImgBanner () {\n\t\tvar numbTotalImg = 3;\n\t\tvar num = Math.ceil(Math.random() * numbTotalImg);\n\t\t$( \".libraryInsperLogin\" ).css( \"background\", \"transparent url('../img/campus\" + num + \".jpg') no-repeat 10px center\" );\n\t}", "function generateImagesMainPage() {\n\t\tfor (i = 0; i < totalNumberOfItems; i++) {\n\t\t\tvar insertPlace = $(\".flowersandleaves\"); //all over the page\n\t\t\tvar insertedDiv = $(\"<div> </div>\");\n\t\t\tvar insertElement = $(\"<img> </img>\");\n\t\t\tinsertedDiv.append(insertElement);\n\t\t\tinsertedDiv.addClass(\"randomElement\");\n\t\t\tinsertPlace.append(insertedDiv);\n\t\t\tvar x = ramdomNumberWhat();\n\t\t\tvar randomAngle = Math.floor((Math.random() * 45) - 65);\n\t\t\tvar randomAngleSmall = Math.floor((Math.random() * 45) - 25);\n\t\t\t//top image left and right \n\t\t\tif (x === 0) {\n\t\t\t\tinsertedDiv.css(\"top\", ramdomLeft() + \"%\");\n\t\t\t\tinsertedDiv.css(\"left\", ramdomLeft() + \"%\");\n\t\t\t\tinsertedDiv.addClass(\"mediumItems\");\n\t\t\t\tinsertedDiv.addClass(\"farLeft\");\n\t\t\t\tinsertElement.attr(\"src\", theItems[x]);\n\n\n\n\t\t\t} else {\n\t\t\t\tinsertedDiv.css(\"top\", bottomBottom() + \"%\");\n\t\t\t\tinsertedDiv.css(\"left\", ramdomLeft() + \"%\");\n\t\t\t\tinsertedDiv.addClass(\"bottomItems\");\n\t\t\t\tinsertElement.attr(\"src\", theItems[x]);\n\t\t\t\tinsertElement.css({\n\t\t\t\t\t'-webkit-transform': 'rotate(' + randomAngle + 'deg)',\n\t\t\t\t\t'-moz-transform': 'rotate(' + randomAngle + 'deg)'\n\t\t\t\t});\n\t\t\t}\n\n\n\t\t}\n\t}", "function pickImage() {\n\n var index = Math.floor(Math.random() * 7);\n iconImg.setAttribute(\"src\", image[index] + \".png\");\n iconImg.setAttribute(\"alt\", descreption[index]);\n}", "function pickImage()\n{\n var index = Math.floor( Math.random() * 7 );\n iconImg.setAttribute( \"src\", pictures[ index ] + \".png\" );\n iconImg.setAttribute( \"alt\", descriptions[ index ] );\n} // end function pickImage", "function randomBGImage(){\r\n\t\t$('.wc-random-bg-image').each(function(){\r\n\t\t\ttry{\r\n\t\t\t\tvar images = $(this).data('bgImages');\r\n\t\t\t\tvar i = WcFun.randomInt(0,images.length - 1 );\r\n\t\t\t\t$(this).css({'background-image':'url(\"'+images[i]+'\")'});\r\n\t\t\t\t$(this).css('visibility', 'visible');\r\n\t\t\t}\r\n\t\t\tcatch(e){\r\n\t\t\t\tlog('randomBGImage() error: ' + e);\r\n\t\t\t}\r\n\t\t});\r\n\t}", "function assignImg(drop_m, drop_v, img_num){\n if (drop_m.type === true){\n drop_v.css('background-image', 'url(\"https://dl.dropboxusercontent.com/u/57018847/dropb.png\")');\n } else {\n drop_v.css('background-image', drop_m.randImageSrc(img_num));\n }\n}", "function outputImage() {\n\n emptyImageArr = [];\n\n //for loop that pushes characterList.images into empty ImageArr\n for (i = 0; i < characterList.length; i++) {\n emptyImageArr.push(characterList[i]);\n };\n\n //grabs random array that contains information object from emptyImageArr\n rand = emptyImageArr[Math.floor(Math.random() * emptyImageArr.length)];\n\n //displays image in HTML using JQuery\n $(\"#image\").attr(\"src\", rand.image);\n\n\n }", "function pickImage()\n{\n var index = Math.floor(Math.random() * 7 );\n iconImg = document.getElementById(\"image\");\n iconImg.setAttribute( \"src\", pictures[ index ] + \".png\" );\n iconImg.setAttribute( \"alt\", descriptions[ index ] );\n} // end function pickImage", "generateItem() {\n this.framesCounter % Math.floor(150 + (Math.random() * 10)) === 0 &&\n this.item.push(new Item(this.ctx, this.canvasSize.w, this.canvasSize.h))\n\n }", "function addImage() {\n // eslint-disable-next-line prefer-const\n let imageDiv = $(\"#added-artwork\");\n\n // eslint-disable-next-line prefer-const\n let randomNumber = Math.floor(Math.random() * 12) + 1;\n\n imageDiv.css(\n \"background-image\",\n `url(./assets/images/art${randomNumber}.jpg)`\n );\n }", "function randomAddressImage(){\n var folderPath = \"images/\";\n var fishes = [\"cuttlefish.jpg\", \"killerwhale.jpg\", \"mandarinfish.jpg\", \"lionfish.jpg\", \"piranha.jpg\", \"tigershark.jpg\"];\n var randomFish = fishes[Math.floor(Math.random() * fishes.length)];\n\n document.getElementById(\"addressImg\").src = folderPath + randomFish;\n} // end randomAddressImage", "function getRandomImage(){\n\t// Get random image\n\tvar imageIndex= Math.floor(Math.random()*images.length);\n\tvar image= images[imageIndex];\n\tconsole.log(image)\n\tvar body = document.getElementById(\"body\");\n\tbody.style.backgroundImage = \"url('\" + image + \"')\";\n\n\t// Get random quote\n\tvar quoteIndex= Math.floor(Math.random()*quotes.length);\n\tvar quote = quotes[quoteIndex];\n\tvar quoteHeader = document.getElementById(\"quote\");\n\tquoteHeader.innerHTML = quote;\n\n}", "function backGroundImage() {\n bgImageTotal = 5;\n randomNumber = Math.round(Math.random() * (bgImageTotal - 1)) + 1;\n $('.reveal-wrapper').addClass('image' + randomNumber);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
join csv and topoJ data
function joinData(b, data){ //loop through csv to assign each set of csv attribute values to geojson region for (var i=0; i<data.length; i++){ var csvRegion = data[i]; //the current region var csvKey = data[i].Country; //the CSV primary key //console.log(data[i].Country) //loop through geojson regions to find correct region for (var a=0; a<b.features.length; a++){ var geojsonProps = b.features[a].properties; //gj props var geojsonKey = geojsonProps.ADMIN; //the geojson primary key //where primary keys match, transfer csv data to geojson properties object if (geojsonKey == csvKey){ //assign all attributes and values attrArray.forEach(function(attr){ var val = parseFloat(csvRegion[attr]); //get csv attribute value geojsonProps[attr] = val; //assign attribute and value to geojson properties }); }; }; }; return b; }
[ "function joinData(data){\n \n dataset = data[0];\n //Convert topojson into geojson format\n counties = topojson.feature(data[1],data[1].objects.SouthCarolina_Counties).features;\n \n //Join the csv file to the geojson file\n //variables for data join\n \n //loop through csv to assign each set of csv attribute values to geojson region\n for (var i=0; i < dataset.length; i++){\n var csvCounty = dataset[i]; //the current region\n var csvKey = csvCounty.GEO_ID; //the CSV primary key\n\n //loop through geojson regions to find correct region\n for (var a=0; a < counties.length; a++){\n var geojsonProps = counties[a].properties; //the current region geojson properties\n var geojsonKey = geojsonProps.FIPS; //the geojson primary key\n\n //where primary keys match, transfer csv data to geojson properties object\n if (geojsonKey == csvKey){\n\n //assign all attributes and values\n attrArray.forEach(function(attr){\n if (attr === \"NAME\"){\n var val = csvCounty[attr];\n geojsonProps[attr] = val; //assign attribute and value to geojson properties\n }else {\n var val = parseFloat(csvCounty[attr]); //get csv attribute value\n geojsonProps[attr] = val; //assign attribute and value to geojson properties\n }\n \n \n });\n };\n };\n \n };\n return counties;\n}", "function joinData(countries, csvData){\r\n for (var i=0; i < csvData.length; i++){\r\n var csvRegion = csvData[i];\r\n var csvKey = csvRegion.State_Name;\r\n\r\n //loop through geojson to identify matching item from csv\r\n for (var a=0; a<countries.length; a++){\r\n var geojsonProps = countries[a].properties; //the current region geojson properties\r\n var geojsonKey = geojsonProps.STUSPS; //the geojson primary key\r\n //where there is primary key match, transfer csv data to geojson\r\n if (geojsonKey == csvKey){\r\n //assign attributes and values\r\n attrArray.forEach(function(attr){\r\n var val = parseFloat(csvRegion[attr]); //get csv attribute value\r\n geojsonProps[attr] = val; //assign attribute and value to geojson properties\r\n });\r\n //console.log(geojsonProps);\r\n };\r\n };\r\n };\r\n return countries;\r\n}", "function joinData(USfeatures, csvData){\n for (var i=0; i<csvData.length; i++){\n var csvState = csvData[i]; //the current state\n var csvKey = csvState.State; //the CSV primary key\n \n //loop through geojson regions to find correct region\n for (var a=0; a<USfeatures.length; a++){\n var geojsonProps = USfeatures[a].properties; //the current region geojson properties\n var geojsonKey = geojsonProps.State; //the geojson primary key\n \n //where primary keys match, transfer csv data to geojson properties object\n if (geojsonKey == csvKey){\n //assign all attributes and values\n attrArray.forEach(function(attr){\n console.log(typeof(attr));\n var val = parseFloat(csvState[attr]); //get csv attribute value\n geojsonProps[attr] = val; //assign attribute and value to geojson properties\n });\n };\n };\n };\n return USfeatures;\n }", "function joinData(eventCounties, csvData) {\n //loop through csv to assign attribute values to the counties\n for (var i=0; i<csvData.length; i++){\n //variable for the current county in topo\n var csvCounty = csvData[i];\n //variable for the csv primary key\n var csvKey = csvCounty.GEOID;\n //loop through geojson regions to find correct region\n for (var a=0; a<eventCounties.length; a++){\n //the current county geojson properties\n var geojsonProps = eventCounties[a].properties;\n //the geojson primary key\n var geojsonKey = geojsonProps.GEOID;\n //if primary keys match, transfer csv data to geojson properties object\n if (geojsonKey == csvKey){\n //assign all attributes and values\n attrArray.forEach(function(attr){\n //get csv attribute value, take it in as a string and return as a float\n var val = parseFloat(csvCounty[attr]);\n //assign the attribute and its value to geojson properties\n geojsonProps[attr] = val;\n\n \t\t\t\t\t\tconsole.log(geojsonProps[attr]);\n });\n };\n };\n };\n\n\n console.log(csvData);\n console.log(eventCounties);\n\n return eventCounties;\n }", "function joinData(SovietRepublics, csvData){\r\n \r\n for (var i=0; i<csvData.length; i++){\r\n var csvRegion = csvData[i];\r\n var csvKey = csvRegion.ADMIN;\r\n for(var a=0; a< SovietRepublics.length; a++){\r\n var geojsonProps = SovietRepublics[a].properties;\r\n var geojsonKey = geojsonProps.ADMIN;\r\n //console.log(geojsonKey);\r\n if(geojsonKey == csvKey){\r\n \r\n attrArray.forEach(function(attr){\r\n var val = parseFloat(csvRegion[attr]);\r\n geojsonProps[attr] = val;\r\n });\r\n };\r\n };\r\n };\r\n}", "function make_csv () {\n header = \"from domain,from zone,to domain,to zone,severity,access type,services,rule properties,flows\";\n ta = $(\"#output\");\n ta.val('');\n ta.val(header);\n domain = '\\\"'+$(\"#default_domain\").val()+'\\\"';\n $('#uspgrid tr td:not(:first-child)').each(function(index, value) {\n //Start array that we'll join later\n r = [];\n //console.log(value);\n //Grab the cell were on\n c = usp_table.cell(this);\n //Parse the JSON out\n cd = JSON.parse(c.data());\n //Grab the zones based on cell\n to = '\\\"'+$(usp_table.column(this).header()).text()+'\\\"';\n from = '\\\"'+$(usp_table.row(this).node()).find('td:eq(0)').text()+'\\\"';\n //console.log(\"From:\" + from + \" To: \" + to);\n //Start pushing\n r.push(domain,from,domain,to,severity[cd.severity], zone_types[cd.zonetype]);\n //Services\n r.push(cd.services)\n //Props\n p = [];\n cd.rule_props.forEach(function(item, index) {\n p.push(rule_props[item]);\n });\n r.push(p.join(\";\"));\n //flows\n r.push(flow_types[cd.flow_types])\n //console.log(r);\n //Output line\n ta.val(ta.val() + \"\\n\" + r.join(\",\"));\n });\n\n tb = $(\"#output2\");\n tb.val('');\n tb.val(tb.val() + \"#Zone Properties\\nzone name,domain, is_shared, description\\n\");\n $('#uspgrid tr td:first-child').each(function() {\n z = $(this).text();\n if (server_zones.indexOf(z) === -1) {\n console.log(\"Exporting \"+z+\" from grid\");\n tb.val(tb.val() + z + \",\" + domain + \",,\" + z + \"\\n\");\n }\n });\n tb.val(tb.val() + \",,\\n#Zone Hierarchy\\nparent,child\\n,,\\n#Zone Subnets\\nzone name,subnet,description\\n\");\n\n//#Zone Properties,,\n//zone name,domain, is_shared, description\n//local_zones[i]+','+domain+','+local_zones[i]\n//,,\n//#Zone Hierarchy\n//parent,child\n//,,\n//#Zone Subnets\n//zone name,subnet,description\n//,,\n\n }", "function joinData(allTracts, csvData){\n\t\t// loop through csv to assign each set of csv attribute values to geojson tract\n\t\tfor (var i=0; i<csvData.length; i++){\n\n\t\t\t// current tract\n\t\t\tvar csvTract = csvData[i];\n\n\t\t\t// csv primary key\n\t\t\tvar csvKey = csvTract.GEOID;\n\n\t\t\t// loop through geojson tracts to find correct tract\n\t\t\tfor (var a=0; a<allTracts.length; a++){\n\n\t\t\t\t// current tract geojson properties\n\t\t\t\tvar geojsonProps = allTracts[a].properties;\n\n\t\t\t\t// geojson primary key\n\t\t\t\tvar geojsonKey = geojsonProps.GEOID;\n\n\t\t\t\t// where primary keys match, transfer csv data to geojson properties object\n\t\t\t\tif (geojsonKey === csvKey){\n\n\t\t\t\t\t// assign all attributes and values\n\t\t\t\t\tattrArray.forEach(function(attr){\n\n\t\t\t\t\t\t// get csv attribute value\n\t\t\t\t\t\tvar val = parseFloat(csvTract[attr]);\n\n\t\t\t\t\t\t// assign attribute and value to geojson properties\n\t\t\t\t\t\tgeojsonProps[attr] = val;\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\t// where primary keys match, transfer csv infodata to geojson properties object\n\t\t\t\tif (geojsonKey === csvKey){\n\n\t\t\t\t\t// assign all attributes and values\n\t\t\t\t\tinfoArray.forEach(function(info){\n\n\t\t\t\t\t\t// get csv attribute value\n\t\t\t\t\t\tvar val = parseFloat(csvTract[info]);\n\n\t\t\t\t\t\t// assign attribute and value to geojson properties\n\t\t\t\t\t\tgeojsonProps[info] = val;\n\t\t\t\t\t});\n\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\treturn allTracts;\n\t}", "function joinData(states, csvData) {\n //loop through csv to assign each set of csv attribute values to geojson state\n for (var i = 0; i < csvData.length; i++) {\n var csvRegion = csvData[i]; //the current region\n var csvKey = csvRegion.Name; //the CSV primary key\n //loop through geojson regions to find correct state\n for (var a = 0; a < states.length; a++) {\n //the current region geojson properties\n var geojsonProps = states[a].properties;\n //the geojson primary key \n var geojsonKey = geojsonProps.woe_name; \n\n //where primary keys match, transfer csv data to geojson properties object\n if (geojsonKey == csvKey) {\n //assign all attributes and values\n attrArray.forEach(function (attr) {\n //get csv attribute value\n var val = parseFloat(csvRegion[attr]); \n //assign attribute and value to geojson properties\n geojsonProps[attr] = val; \n });\n }\n }\n }\n //returns states to be utilized\n return states;\n}", "function joinData(usaStates, csvData) {\n\n //Loop through csv to assign csv attributes to geojson region\n for (var i = 0; i < csvData.length; i++) {\n\n var usaState = csvData[i]; //THE CURRENT REGION\n var usaKey = usaState.name; //CSV PRIMARY KEY\n\n //Loop Through JSON regions to detect correct region\n for (var a = 0; a < usaStates.length; a++) {\n\n var geojsonProps = usaStates[a].properties; //Current Region JSON Properties\n var geojsonKey = geojsonProps.name //geoJSON primary key\n\n //If the JSON key matches the CSV key, the CSV data is appended to the JSON\n if (geojsonKey == usaKey) {\n\n //Assign all attributes and values\n attrArray.forEach(function (attr) {\n var val = parseFloat(usaState[attr]); //Get CSV value as float\n geojsonProps[attr] = val //Assign attribute and change string to float to geojson properties\n\n });\n };\n };\n };\n return usaStates;\n}", "function joinData (files) {\n console.log(\"This appears to work!\");\n \n var nonSpatialData = files[0];\n var spatialData = files[1].features;\n \n console.log(\"logging non-spatial data\");\n console.log(nonSpatialData);\n console.log(\"logging spatial data\");\n console.log(spatialData);\n \n //join the spatial and non spatial data together\n for (var i=0; i < nonSpatialData.length; i++) {\n var nonSpatialRecord = nonSpatialData[i];\n var nonSpatialKey = nonSpatialRecord.AFFGEOID;\n \n for (var a=0; a < spatialData.length; a++){\n \n var spatialRecord = spatialData[a];\n var spatialKey = spatialRecord.properties.AFFGEOID;\n \n if (spatialKey == nonSpatialKey){\n console.log(\"The Keys Match!\");\n \n spatialRecord.name = nonSpatialRecord.name;\n spatialRecord.AFFGEOID = \"G\" + nonSpatialRecord.AFFGEOID;\n \n //join the two datasets together and push the object into the new master array\n attrArray.forEach(function (attr){\n var val = parseFloat(nonSpatialRecord[attr]);\n spatialRecord[attr] = val;\n });\n \n dataList.push(spatialRecord);\n }\n }\n }\n \n console.log(\"Logging joined data!\");\n console.log(dataList);\n }", "function joinData(statesData, csvData){\n for (var i=0; i<csvData.length; i++) {\n var csvState = csvData[i];\n var csvKey = csvState.name;\n \n for (var a=0; a<statesData.length; a++) {\n var geojsonProps = statesData[a].properties;\n var geojsonKey = geojsonProps.name;\n \n if (geojsonKey == csvKey){\n attrArray.forEach(function(attr){\n var val = parseFloat(csvState[attr]);\n \n geojsonProps[attr] = val;\n });\n };\n };\n \n }; \n \n return statesData;\n }", "function joinData(tahoeBlockgroup, csvData){\n //loop through csv to assign each set of csv attribute values to geojson block group\n for (var i=0; i<csvData.length; i++){\n var csvBlocks = csvData[i]; //the current block group\n var csvKey = csvBlocks.GEOID; //the CSV primary key\n\n //loop through geojson block groups to find correct block\n for (var a=0; a<tahoeBlockgroup.length; a++){\n\n var geojsonProps = tahoeBlockgroup[a].properties; //the current block group geojson properties\n var geojsonKey = geojsonProps.GEOID; //the geojson primary key\n\n //where primary keys match, transfer csv data to geojson properties object\n if (geojsonKey == csvKey){\n\n //assign all attributes and values\n attrArray.forEach(function(attr){\n var val = parseFloat(csvBlocks[attr]); //get csv attribute value\n geojsonProps[attr] = val; //assign attribute and value to geojson properties\n console.log(val)\n });\n };\n };\n };\n return tahoeBlockgroup;\n}", "function joinData(franceRegions, csv){\n //loop through each csv to assign each set of csv attributes to geojson regions\n for (i=0; i<csv.length; i++){\n var csvRegion = csv[i];\n var csvKey = csvRegion.adm1_code;\n \n for (var a=0; a<franceRegions.length; a++){\n var geojsonProps = franceRegions[a].properties;\n var geojsonKey = geojsonProps.adm1_code;\n \n if (geojsonKey == csvKey){\n \n attrArray.forEach(function(attr){\n var val = parseFloat(csvRegion[attr]);\n geojsonProps[attr] = val;\n });\n }; //end of if statement\n }; //end of inner for loop\n }; //end of outer for loop\n return franceRegions;\n }", "function joinData(italyRegions, wineData) {\n //loop through csv to assign each set of csv attribute values to geojson region\n for (var i=0; i<wineData.length; i++) {\n var csvRegion = wineData[i]; //current regions\n var csvKey = csvRegion.adm1_code; //the CSV primary key\n\n //loop through geojson regions to find correct region\n for (var a=0; a<italyRegions.length; a++) {\n\n var geojsonProps = italyRegions[a].properties; //the current region geojson properties\n var geojsonKey = geojsonProps.adm1_code; //the geojson primary csvKey\n\n //where primary keys match, transfer csv data to geojson properties objects\n if (geojsonKey == csvKey) {\n\n //assing all attributes and values\n attrArray.forEach(function(attr){\n var val = parseFloat(csvRegion[attr]); //get csv attribute value\n geojsonProps[attr] = val; //assign attribute and value to geojson properties\n });\n };\n };\n };\n console.log(italyRegions);\n\n return italyRegions;\n }", "function joinData(usStates,csvData){\n\t\t//loop through the csv file to assign each set of csv attribute to geojson regions\n\t\tfor (var i=0; i<csvData.length; i++){\n\t\t\tvar csvRegion= csvData[i]; //access the current indexed region\n\t\t\tvar csvKey=csvRegion.code_local;//the csv primary key \n\n\t\t\t//loop through the geojson regions to find the correct regions \n\t\t\tfor (var a=0; a<usStates.length;a++){\n\t\t\t\tvar geojsonProps=usStates[a].properties;//the current indexed region geojson properties\n\t\t\t\tvar geojsonKey=geojsonProps.code_local;//the geojson primary key \n\n\t\t\t\t//when the csv primary key matches the geojson primary key, transfer the csv data to geojson objects' properties\n\t\t\t\tif (geojsonKey==csvKey){\n\t\t\t\t\t//assign all attributes and values \n\t\t\t\t\tattrArray.forEach(function(attr){\n\t\t\t\t\t\tvar val=parseFloat(csvRegion[attr]); //get all the csv attribute values\n\t\t\t\t\t\tgeojsonProps[attr]=val;//assign the attribute and values to geojson properties\n\t\t\t\t\t\t//console.log(geojsonProps[attr]);\n\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\t//returning the enumeration units with attrbite values joined\n\t\treturn usStates;\n\t}", "function joinData(usStates,csvData){\n\t\t//loop through the csv file to assign each set of csv attribute to geojson regions\n\t\tfor (var i=0; i<csvData.length; i++){\n\t\t\tvar csvRegion= csvData[i]; //access the current indexed region\n\t\t\tvar csvKey=csvRegion.code_local;//the csv primary key \n\n\t\t\t//loop through the geojson regions to find the correct regions \n\t\t\tfor (var a=0; a<usStates.length;a++){\n\t\t\t\tvar geojsonProps=usStates[a].properties;//the current indexed region geojson properties\n\t\t\t\tvar geojsonKey=geojsonProps.code_local;//the geojson primary key \n\n\t\t\t\t//when the csv primary key matches the geojson primary key, transfer the csv data to geojson objects' properties\n\t\t\t\tif (geojsonKey==csvKey){\n\t\t\t\t\t//assign all attributes and values \n\t\t\t\t\tattrArray.forEach(function(attr){\n\t\t\t\t\t\tvar val=parseFloat(csvRegion[attr]); //get all the csv attribute values\n\t\t\t\t\t\t\tgeojsonProps[attr]=val;//assign the attribute and values to geojson properties\n\t\t\t\t\t\t//console.log(geojsonProps[attr]);\n\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t\t//returning the enumeration units with attrbite values joined\n\t\treturn usStates;\n\t}", "function joinData(usStates, csvData){\n\t//loop through csv to assign each set of csv attribute values to geojson region\n\tfor (var i=0; i<csvData.length; i++){\n\t\tvar csvstates = csvData[i]; //the current region\n\t\tvar csvKey = csvstates.STATEFP; //the CSV primary key\n\n\t\t//loop through geojson regions to find correct region\n\t\tfor (var a=0; a<usStates.length; a++){\n\t\t\t\n\t\t\tvar geojsonProps = usStates[a].properties; //the current region geojson properties\n\t\t\tvar geojsonKey = geojsonProps.STATEFP; //the geojson primary key\n\n\t\t\t//where primary keys match, transfer csv data to geojson properties object\n\t\t\tif (geojsonKey == csvKey){\n\n\t\t\t\t//assign all attributes and values\n\t\t\t\tattrArray.forEach(function(attr){\n\t\t\t\t\tvar val = parseFloat(csvstates[attr]); //get csv attribute value\n\t\t\t\t\tgeojsonProps[attr] = val; //assign attribute and value to geojson properties\n\t\t\t\t});\n\t\t\t};\n\t\t};\n\t};\n\n\treturn usStates;\n}", "function combine() {\n var L = [];\n for (var i = 1; i <= 3668; ++i) {\n data = JSON.parse(fs.readFileSync('responses/' + i + '.json').toString())\n L = L.concat(data.d.Result);\n }\n console.log(L.length);\n json2csv({ data: L, fields: Object.keys(L[0]).filter(function (x) { return ['Icons', 'Zonages', 'Brokers'].indexOf(x) === -1; }) }, function(err, csv) {\n if (err) console.log(err);\n fs.writeFile('data/listings.csv', csv, function(err) {\n if (err) throw err;\n console.log('DONE');\n });\n });\n}", "function populateCsv() {\n resetCsvTxt();\n\n if (do_BFS) {\n\tdebug('Bredth First');\n\tvar queue = Array();\n\tcrawlTreeBf(queue, 1);\n } else {\n\tdebug('Depth First');\n\tcrawlTreeDf(1);\t\t\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define a Penguin class
function Penguin(name) { this.name = name; }
[ "function Penguin(name){\r\n this.name = name;\r\n this.numLegs = 2;\r\n }", "function Penguin (name) {\r\n\t\tthis.name = name;\r\n\t\tthis.numLegs = 2;\r\n\t}", "function Penguin(name){\r\n this.name = name;\r\n this.numLegs = 2;\r\n}", "function Penguin(name){\n\n this.name = name;\n this.numLegs = 2;\n}", "function Penguin(name) {\n this.name = name;\n this.numLegs = 2;\n}", "function subclass() {}", "function Trivia () {}", "function Computer() {\n this.paddle = new Paddle(width-20, height/2, paddleWidth, paddleHeight);\n}", "function PrototypeBasedClass () {\n}", "function ClassDefinition() {\n}", "function MolBase() {\n\n}", "function makeClass() {\n \"use strict\";\n /* Alter code below this line */\n class Vegetable {\n constructor(Vegetable){\n this.name = Vegetable;\n \n }\n }\n /* Alter code above this line */\n return Vegetable;\n }", "function River() {\n \n}", "function BlueDiv(color){} // function creates class definition", "constructor ( name, uniCellular, mobile, heterotroph ) {\n super ( name, uniCellular, true, mobile, heterotroph );\n this._name = name;\n this._uniCellular = uniCellular;\n this._mobile = mobile;\n this._heterotroph = heterotroph;\n }", "function Ninja() {\n this.swung = true;\n}", "function Sprite_VirtualPad() {\n this.initialize.apply(this, arguments);\n}", "function Spacepolice_game2() {\n this.type = 'Spacepolice';\n}", "function Vehicle() {}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple helper that gets a single screen (React component or navigator) out of the navigator config.
function getScreenForRouteName( // eslint-disable-line consistent-return routeConfigs, routeName) { var routeConfig = routeConfigs[routeName]; if (!routeConfig) { throw new Error('There is no route defined for key ' + routeName + '.\n' + ('Must be one of: ' + Object.keys(routeConfigs).map(function (a) { return '\'' + a + '\''; }).join(','))); } if (routeConfig.screen) { return routeConfig.screen; } if (typeof routeConfig.getScreen === 'function') { var screen = routeConfig.getScreen(); (0, _invariant2.default)(typeof screen === 'function', 'The getScreen defined for route \'' + routeName + ' didn\'t return a valid ' + 'screen or navigator.\n\n' + 'Please pass it like this:\n' + (routeName + ': {\n getScreen: () => require(\'./MyScreen\').default\n}')); return screen; } throw new Error('Route ' + routeName + ' must define a screen or a getScreen.'); }
[ "function getCurrentScreen(getStateFn) {\n const navigationState = getStateFn()[navigationStateKey];\n // navigationState can be null when exnav is initializing\n if (!navigationState) return null;\n\n const { currentNavigatorUID, navigators } = navigationState;\n if (!currentNavigatorUID) return null;\n\n const { index, routes } = navigators[currentNavigatorUID];\n const { routeName } = routes[index];\n return routeName;\n}", "function getScreenForRouteName(routeConfigs, routeName) {\n var routeConfig = routeConfigs[routeName];\n\n invariant(routeConfig, 'There is no route defined for key ' + routeName + '.\\n' + ('Must be one of: ' + Object.keys(routeConfigs).map(function (a) {\n return '\\'' + a + '\\'';\n }).join(',')));\n\n if (routeConfig.screen) {\n return routeConfig.screen;\n }\n\n if (typeof routeConfig.getScreen === 'function') {\n var screen = routeConfig.getScreen();\n invariant(typeof screen === 'function', 'The getScreen defined for route \\'' + routeName + ' didn\\'t return a valid ' + 'screen or navigator.\\n\\n' + 'Please pass it like this:\\n' + (routeName + ': {\\n getScreen: () => require(\\'./MyScreen\\').default\\n}'));\n return screen;\n }\n\n invariant(false, 'Route ' + routeName + ' must define a screen or a getScreen.');\n}", "function getScreenForRouteName(routeConfigs, routeName) {\n var routeConfig = routeConfigs[routeName];\n\n if (!routeConfig) {\n throw new Error('There is no route defined for key ' + routeName + '.\\n' + ('Must be one of: ' + (0, _keys2.default)(routeConfigs).map(function (a) {\n return '\\'' + a + '\\'';\n }).join(',')));\n }\n\n if (routeConfig.screen) {\n return routeConfig.screen;\n }\n\n if (typeof routeConfig.getScreen === 'function') {\n var screen = routeConfig.getScreen();\n (0, _invariant2.default)(typeof screen === 'function', 'The getScreen defined for route \\'' + routeName + ' didn\\'t return a valid ' + 'screen or navigator.\\n\\n' + 'Please pass it like this:\\n' + (routeName + ': {\\n getScreen: () => require(\\'./MyScreen\\').default\\n}'));\n return screen;\n }\n\n throw new Error('Route ' + routeName + ' must define a screen or a getScreen.');\n}", "function getCurrentScreen(getStateFn) {\n const navigationState = getStateFn().nav;\n if (!navigationState) { return null; }\n return navigationState.routes[navigationState.index].routeName;\n}", "getDisplayedScreen()\n {\n return this._currentScreen?.screenType;\n }", "function getElectronScreen(){\n const screens = electron.screen.getAllDisplays();\n if(!screens.length){\n throw new Error('No connected screens (according to electron)');\n }\n\n const selectedScreen = screens[0];\n if(selectedScreen.scaleFactor !== 1){\n throw new Error('This test only works with screens that have scaleFactor = 1');\n }\n return selectedScreen;\n}", "static get(id) {\n return this.screens.get(id);\n }", "function get_current_screen (filesystem) {\n\treturn get_folder(filesystem, filesystem.currentDirectory).screen;\n}", "function getScreenFromLocation(location) {\n const fragparts = parseQsFromFragment(location);\n return {\n screen: fragparts.location.substring(1),\n params: fragparts.params,\n }\n }", "function displayScreens() {\n if(screenDisplay==='orderHistory') return (<UserOrders/>)\n if(screenDisplay==='accountConfig') return (<UserInfo user={user} />)\n if(screenDisplay==='wishlist') return (<Wishlist/>)\n }", "function getCurrentScreen() { return hwc.getCurrentScreen(); }", "renderScene(route, navigator) {\n // if route id is 1, the screen will show the Home scene\n if (route.id === 1) {\n return <Home navigator={navigator} />\n }\n // otherwise, if route id is 2, the screen will show the Movie scene\n // ... and pass the Props to it (Props in this case will be the movie title that the user clicks on in Home; Movie needs to know which movie to search OMDB for\n else if (route.id === 2) {\n return <Movie navigator={navigator} {...route.passProps} />\n }\n // otherwise, if the route id is 3, the screen will show the Splash scene\n else if (route.id === 3) {\n return <Splash navigator={navigator} />\n }\n }", "function BestStack() {\n return (\n <Stack.Navigator\n initialRouteName=\"Best\"\n screenOptions={{\n headerStyle: { backgroundColor: '#F4A259' },\n headerTintColor: '#fff',\n headerTitleStyle: { fontWeight: 'bold' },\n }}>\n <Stack.Screen\n name=\"Top\"\n component={HomeScreen}\n options={{ title: 'Top Stories' }}\n />\n <Stack.Screen\n name=\"Best\"\n component={BestScreen}\n options={{ title: 'Best Stories' }}\n />\n <Stack.Screen\n name=\"Job\"\n component={JobScreen}\n options={{ title: 'Job Stories' }}\n />\n </Stack.Navigator>\n );\n}", "function mapScreenConfig(config) {\n var defaultConfig = defaultSeatPickerConfig.screen;\n if (config === undefined)\n return defaultConfig;\n var validatedConfig = getValidatedScreenConfig(config);\n return __assign({}, defaultConfig, validatedConfig);\n}", "renderScene(route, navigator) {\n if (route.id === 1) {\n return <Home navigator={navigator} />\n }\n else if (route.id === 2) {\n return <NewGame navigator={navigator} />\n }\n else if (route.id === 3) {\n return <Splash navigator={navigator} />\n }\n else if (route.id === 4) {\n return <GamePlay navigator={navigator} />\n }\n else if (route.id === 5) {\n return <JoinGame navigator={navigator} />\n }\n else if (route.id === 6) {\n return <Root navigator={navigator} />\n }\n else if (route.id === 7) {\n return <JudgeView navigator={navigator} />\n }\n }", "function MyDrawer(){\n\n return(\n\n <Drawer.Navigator initialRouteName=\"Locations\">\n <Drawer.Screen name=\"Add or Edit a Review\" component={Review} />\n <Drawer.Screen name=\"Locations\" component={Locations} />\n </Drawer.Navigator>\n\n )\n}", "function JobStack() {\n return (\n <Stack.Navigator\n initialRouteName=\"Job\"\n screenOptions={{\n headerStyle: { backgroundColor: '#BC4B51' },\n headerTintColor: '#fff',\n headerTitleStyle: { fontWeight: 'bold' },\n }}>\n <Stack.Screen\n name=\"Top\"\n component={HomeScreen}\n options={{ title: 'Top Stories' }}\n />\n <Stack.Screen\n name=\"Best\"\n component={BestScreen}\n options={{ title: 'Best Stories' }}\n />\n <Stack.Screen\n name=\"Job\"\n component={JobScreen}\n options={{ title: 'Job Stories' }}\n />\n </Stack.Navigator>\n );\n}", "renderScene(route, navigator) {\n if (route.id === 1) {\n return <Home navigator={navigator} />\n } \n else if (route.id === 2) {\n return <Weather navigator={navigator} {...route.passProps} />\n } \n else if (route.id === 3) {\n return <Splash navigator={navigator} />\n }\n }", "render () {\n return (\n <Navigator\n configureScene={ this.configureScene }\n style={{ flex:1 }}\n initialRoute={{ name: 'Welcome' }}\n renderScene={ this.renderScene }\n />\n )\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify a game result.
notifyGameResult(result, ownHand, opponentsHand) { // ˅ switch (result) { case GameResultType.Win: this.winCount++; this.gameCount++; break; case GameResultType.Loss: this.lossCount++; this.gameCount++; break; case GameResultType.Draw: this.gameCount++; break; } this.strategy.notifyGameResult(result, ownHand, opponentsHand); // ˄ }
[ "notifyTournamentOver(gameResults) {\n }", "notifyGameResult(result, ownHand, opponentsHand) {\n throw new Error(`An abstract method has been executed.`);\n }", "function setGameResult() {\n\n\n }", "function result() {\n\n Swal.fire( {\n title: 'Good Job! you got',\n text: document.getElementById('score').innerHTML + ' / 7',\n showCancelButton: true,\n confirmButtonColor: \"#D5212E\"\n }).then((result) => {\n if(result.isConfirmed) {\n startGame();\n }\n });\n}", "notifyGameOver(gameResult) {\n // Nothing to do here for now.\n return Promise.resolve();\n }", "function trigger(result){\n\n //console.log('pushing ', result)\n\n // if(logger) logger('triggered '+name)\n\n // save result\n pending.push(result);\n\n // trigger (async use)\n if(!sync) fireAll();\n\n }", "finishGame(result) {\n this.socket.emit('finish', result);\n }", "function setResults(result) {\n const info = document.querySelector('#infoMessage');\n const scores = document.querySelector('#scores');\n console.log(result);\n if (result == 1) {\n playerScore++;\n info.textContent = 'You have won';\n } else if (result == 2) {\n aiScore++;\n info.textContent = 'You have lost';\n } else {\n info.textContent = 'tied, try again';\n }\n\n scores.textContent = `${playerScore} - ${aiScore}`;\n}", "function displayGameResult(result) {\n // Define an array of text labels for the choices 0, 1, 2;\n // Create a message for the player\n var message = \"Your choice was \" + choices[playerChoice] + \" and the computer's choice was \" + choices[computerChoice] + \".\";\n // Add to the base message if it was a win, loss, or tie\n if (result === \"win\") {\n // Display that it was a win\n document.getElementById(\"result\").textContent = message + \"Congrats my friend! You won!\";\n document.getElementById(\"result\").className = \"alert alert-success\";\n } else if (result === \"lose\") {\n // Display that it was a loss\n document.getElementById(\"result\").textContent = message + \"I'm sorry, but you lost this round.\";\n document.getElementById(\"result\").className = \"alert alert-danger\";\n } else {\n // Display that it was a tie\n document.getElementById(\"result\").textContent = message + \"You tied, so... try again!\";\n document.getElementById(\"result\").className = \"alert alert-info\";\n }\n\n updateScoreBoard();\n updateMatchScore();\n }", "function notifyResults() {\n if (results.length > 0) {\n onIncrementalFulfilled(results);\n }\n firstResultTS = null;\n timeout = null;\n results = [];\n }", "function outcome(result) {\n if (result === 'win') {\n player.win++;\n displayWinSpan.textContent = player.win;\n showMessage('You Win!', currentDate, currentTime);\n showWinLossImage('win');\n } else if (result === 'loss') {\n player.loss++;\n displayLossSpan.textContent = player.loss;\n showMessage('You Lose!', currentDate, currentTime);\n showWinLossImage('loss');\n } else if (result === 'draw') {\n player.draw++;\n displayDrawSpan.textContent = player.draw;\n showMessage('Draw!', currentDate, currentTime);\n hideWinLossImage();\n }\n}", "_setResult(newResult) {\n\n const oldResult = this._result;\n\n if (oldResult != newResult) {\n // Update the cached result.\n this._result = newResult;\n\n // Notify clients - asynchronously.\n setTimeout((caller, resultOld, resultNew) => {\n caller.emit('result_changed', resultOld, resultNew, caller);\n }, 0, this, oldResult, newResult);\n }\n }", "notifyTournamentOver(gameResults) {\n // Nothing to do here for now.\n return Promise.resolve();\n }", "notifyPlayersOfResult() {\n let matchResults = this.matchTable.getAllMatchResults();\n this.donePlayers.forEach(player => {\n let matchResultsCopy = matchResults.map(gr => gr.copy());\n player.notifyTournamentOver(matchResultsCopy);\n });\n }", "notifyLoserPostSuccess(winner, loser, gameResult) {\n if (gameResult.reason === BROKEN_RULE) {\n // Don't notify loser if they already broke.\n return Promise.resolve(gameResult);\n } else {\n return loser.notifyGameOver(gameResult).then(() => {\n return gameResult;\n }).catch(() => {\n // Loser broke, so the end game reason must change to broken rule\n return new GameResult(gameResult.winner, gameResult.loser, BROKEN_RULE);\n });\n }\n }", "function publishResult(player, ai, result) { \n //wybór gracza, komputera i kto wygrał\n document.querySelector('[data-summary=\"your-choice\"]').textContent = player;\n document.querySelector('[data-summary=\"ai-choice\"]').textContent = ai;\n document.querySelector('[data-summary=\"who-win\"]').textContent = result;\n \n gameSummary.numbers++; //liczba gier\n document.querySelector('p.numbers span').textContent = +gameSummary.numbers; //publikacja liczby gier\n\n //publikacja wyniku\n if(result === \"win\") {\n document.querySelector('p.wins span').textContent = ++gameSummary.wins;\n document.querySelector('[data-summary=\"who-win\"]').textContent = \"Ty wygrałeś!!!\";\n document.querySelector('[data-summary=\"who-win\"]').style.color = \"green\";\n } else if(result === \"loss\") {\n document.querySelector('p.losses span').textContent = ++gameSummary.losses;\n document.querySelector('[data-summary=\"who-win\"]').textContent = \"Komputer wygrał :(\";\n document.querySelector('[data-summary=\"who-win\"]').style.color = \"red\";\n } else {\n document.querySelector('p.draws span').textContent = ++gameSummary.draws;\n document.querySelector('[data-summary=\"who-win\"]').textContent = \"remis :\\\\\";\n document.querySelector('[data-summary=\"who-win\"]').style.color = \"gray\";\n }\n\n}", "setResult(result) {\n this.getFrame().result = result;\n }", "notifyPlayersOfEndGame(finishedGameResult) {\n let winner = finishedGameResult.winner === this.player1.getId() ? this.player1 : this.player2;\n let loser = this.flip(winner);\n\n let winnerNotified = winner.notifyGameOver(finishedGameResult).then(() => {\n return this.notifyLoserPostSuccess(winner, loser, finishedGameResult);\n }).catch(() => {\n return this.notifyLoserPostFailure(loser, finishedGameResult);\n });\n\n return winnerNotified.then((gameResult) => {\n this.notifyAllObservers(o => { return o.gameOver(gameResult.copy()) });\n this.board = null;\n return gameResult;\n });\n }", "function sendResult(passed, errorMessage) {\n lastExecutionResult = passed ? 'passed' : errorMessage;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Battery stack Extends mxShape.
function mxShapeElectricalBatteryStack(bounds, fill, stroke, strokewidth) { mxShape.call(this); this.bounds = bounds; this.fill = fill; this.stroke = stroke; this.strokewidth = (strokewidth != null) ? strokewidth : 1; }
[ "function mxShapeBasicBendingArch(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.startAngle = 0.25;\n\tthis.endAngle = 0.75;\n\tthis.arcWidth = 0.5;\n}", "provideBatteryIcon(batteryLevel,charging = false) {\n if (charging) { return SFSymbol.named(\"battery.100.bolt\").image }\n\n const batteryWidth = 87\n const batteryHeight = 41\n\n const draw = new DrawContext()\n draw.opaque = false\n draw.respectScreenScale = true\n draw.size = new Size(batteryWidth, batteryHeight)\n\n draw.drawImageInRect(SFSymbol.named(\"battery.0\").image, new Rect(0, 0, batteryWidth, batteryHeight))\n\n const x = batteryWidth*0.1525\n const y = batteryHeight*0.247\n const width = batteryWidth*0.602\n const height = batteryHeight*0.505\n\n let level = batteryLevel\n if (level < 0.05) { level = 0.05 }\n\n const current = width * level\n let radius = height/6.5\n\n // When it gets low, adjust the radius to match.\n if (current < (radius * 2)) { radius = current / 2 }\n\n const barPath = new Path()\n barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)\n draw.addPath(barPath)\n draw.setFillColor(Color.black())\n draw.fillPath()\n return draw.getImage()\n }", "function draw_battery(xpos, ypos, orientation, length, height, num_bats) {\n \"use strict\";\n\n ctx.lineWidth = 2;\n ctx.lineCap = \"butt\";\n ctx.strokeStyle = \"#000000\";\n\n var num_spaces, space_length, i, horizontal_motion = [], vertical_motion = [], stroke_directions = [], minus_sign_length, x_movements, y_movements;\n\n num_spaces = 2 * num_bats - 1;\n// number of spaces between batteries\n space_length = length / (4 + num_spaces);\n// length of space between batteries\n// the leading length is twice the space_length\n\n\n/// horizontal_motion and vertical_motion show the x and y directiosn\n/// if the orientation is RIGHT\n// step_direction is a boolean vector, if TRUE that step is a stroke,\n// if FALSE that step is a movement\n\n// position for minus sign\n horizontal_motion.push(1.65 * space_length);\n vertical_motion.push(-0.25 * height);\n stroke_directions.push(false);\n\n minus_sign_length = 0.75 * space_length;\n/// draw minus sign\n horizontal_motion.push(-1.0 * minus_sign_length);\n vertical_motion.push(0);\n stroke_directions.push(true);\n\n// return to original spot\n horizontal_motion.push(-1.65 * space_length + minus_sign_length);\n vertical_motion.push(+0.25 * height);\n stroke_directions.push(false);\n\n\n\n// draw leading wire\n horizontal_motion.push(2 * space_length);\n vertical_motion.push(0);\n stroke_directions.push(true);\n\n// position for the first battery draw\n horizontal_motion.push(0);\n vertical_motion.push(0.25 * height);\n stroke_directions.push(false);\n\n\n for (i = 0; i < num_bats; i += 1) {\n \n // draw short battery line\n horizontal_motion.push(0);\n vertical_motion.push(-0.5 * height);\n stroke_directions.push(true);\n\n // position for long battery line\n horizontal_motion.push(space_length);\n vertical_motion.push(0.75 * height);\n stroke_directions.push(false);\n\n\n // draw long battery line\n horizontal_motion.push(0);\n vertical_motion.push(-1.0 * height);\n stroke_directions.push(true);\n\n\n if (i !== num_bats - 1) {\n // if there are more batteries, position for next battery\n horizontal_motion.push(space_length);\n vertical_motion.push(0.75 * height);\n stroke_directions.push(false);\n } else {\n // if there are no more batteries, position to center to finish\n horizontal_motion.push(0);\n vertical_motion.push(0.5 * height);\n stroke_directions.push(false);\n }\n }\n\n\n// draw the trailing wire\n horizontal_motion.push(2 * space_length);\n vertical_motion.push(0);\n stroke_directions.push(true);\n\n\n\n// final step: draw the + sign\n// positioning\n horizontal_motion.push(-1.65 * space_length);\n vertical_motion.push(-0.5 * height);\n stroke_directions.push(false);\n\n// horizontal swipe\n horizontal_motion.push(minus_sign_length);\n vertical_motion.push(0);\n stroke_directions.push(true);\n\n// repositioning\n horizontal_motion.push(-0.5 * minus_sign_length);\n vertical_motion.push(+0.5 * minus_sign_length);\n stroke_directions.push(false);\n\n//vertical swipe\n horizontal_motion.push(0);\n vertical_motion.push(-1.0 * minus_sign_length);\n stroke_directions.push(true);\n\n// reposition correct end spot\n horizontal_motion.push(-0.5 * minus_sign_length + 1.65 * space_length);\n vertical_motion.push(+0.5 * minus_sign_length + 0.5 * height);\n stroke_directions.push(false);\n \n// reorient the moition vectors to the correct orientation\n if (orientation === 'right') {\n x_movements = horizontal_motion;\n y_movements = vertical_motion;\n } else if (orientation === 'left') {\n x_movements = multiply_vector(horizontal_motion, -1);\n y_movements = multiply_vector(vertical_motion, 1);\n } else if (orientation === 'up') {\n x_movements = vertical_motion;\n y_movements = multiply_vector(horizontal_motion, -1);\n } else if (orientation === 'down') {\n x_movements = multiply_vector(vertical_motion, -1);\n y_movements = multiply_vector(horizontal_motion, 1);\n }\n\n// drawing the actual battery\n ctx.moveTo(xpos, ypos);\n for (i = 0; i < x_movements.length; i += 1) {\n xpos += x_movements[i];\n ypos += y_movements[i];\n if (stroke_directions[i]) {\n ctx.lineTo(xpos, ypos);\n ctx.stroke();\n } else {\n ctx.moveTo(xpos, ypos);\n }\n }\n}", "provideBatteryIcon(batteryLevel,charging = false) {\n\n // If we're charging, show the charging icon.\n if (charging) { return SFSymbol.named(\"battery.100.bolt\").image }\n\n // Set the size of the battery icon.\n const batteryWidth = 87\n const batteryHeight = 41\n\n // Start our draw context.\n let draw = new DrawContext()\n draw.opaque = false\n draw.respectScreenScale = true\n draw.size = new Size(batteryWidth, batteryHeight)\n\n // Draw the battery.\n draw.drawImageInRect(SFSymbol.named(\"battery.0\").image, new Rect(0, 0, batteryWidth, batteryHeight))\n\n // Match the battery level values to the SFSymbol.\n const x = batteryWidth*0.1525\n const y = batteryHeight*0.247\n const width = batteryWidth*0.602\n const height = batteryHeight*0.505\n\n // Prevent unreadable icons.\n let level = batteryLevel\n if (level < 0.05) { level = 0.05 }\n\n // Determine the width and radius of the battery level.\n const current = width * level\n let radius = height/6.5\n\n // When it gets low, adjust the radius to match.\n if (current < (radius * 2)) { radius = current / 2 }\n\n // Make the path for the battery level.\n let barPath = new Path()\n barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)\n draw.addPath(barPath)\n draw.setFillColor(Color.black())\n draw.fillPath()\n return draw.getImage()\n }", "battery(column) {\n const batteryStack = this.align(column)\n batteryStack.layoutHorizontally()\n batteryStack.centerAlignContent()\n batteryStack.setPadding(this.padding/2, this.padding, this.padding/2, this.padding)\n\n const batteryIcon = batteryStack.addImage(this.provideBatteryIcon(Device.batteryLevel(),Device.isCharging()))\n batteryIcon.imageSize = new Size(30,30)\n\n const batteryLevel = Math.round(Device.batteryLevel() * 100)\n if (batteryLevel > 20 || Device.isCharging() ) { this.tintIcon(batteryIcon,this.format.battery,true) }\n else { batteryIcon.tintColor = Color.red() }\n\n batteryStack.addSpacer(this.padding * 0.6)\n this.provideText(batteryLevel + \"%\", batteryStack, this.format.battery)\n }", "function Bumper(x, y, shape) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.isGrowing = true;\n\t\tthis.size = 0;\n\t\tshape.call(this);\n\t}", "function mxLeanBoatShipment(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}", "function PowerBar() {\n let powerBarFill = map(powerEnergy, 0, 100, 0, 500);\n fill(255, 160, 136);\n rect(40, 200, 40, 500);\n fill(240, 248, 255);\n rect(40, 200, 40, 500 - powerBarFill);\n}", "function mxRackCabinetLeg(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}", "function powerBar() {\n //the text that is above the power level meter\n text('Power Level', width / 4 * 3 + 15, height / 4 - 5)\n //the background rectangle \n noStroke()\n fill('gray')\n rect(width / 4 * 3, height / 4, 100, 10)\n //the rectangle that updates with the speed changes\n fill('red')\n rect(width / 4 * 3, height / 4, ballSpeed * 5, 10)\n}", "createBrick(){\r\n fill(this.brickColor);\r\n rect(this.xPos, this.yPos, 100, 50);\r\n }", "function provideBatteryIcon() {\n \n // If we're charging, show the charging icon.\n if (Device.isCharging()) { return SFSymbol.named(\"battery.100.bolt\").image }\n \n // Set the size of the battery icon.\n const batteryWidth = 87\n const batteryHeight = 41\n \n // Start our draw context.\n let draw = new DrawContext()\n draw.opaque = false\n draw.respectScreenScale = true\n draw.size = new Size(batteryWidth, batteryHeight)\n \n // Draw the battery.\n draw.drawImageInRect(SFSymbol.named(\"battery.0\").image, new Rect(0, 0, batteryWidth, batteryHeight))\n \n // Match the battery level values to the SFSymbol.\n const x = batteryWidth*0.1525\n const y = batteryHeight*0.247\n const width = batteryWidth*0.602\n const height = batteryHeight*0.505\n \n // Prevent unreadable icons.\n let level = Device.batteryLevel()\n if (level < 0.05) { level = 0.05 }\n \n // Determine the width and radius of the battery level.\n const current = width * level\n let radius = height/6.5\n \n // When it gets low, adjust the radius to match.\n if (current < (radius * 2)) { radius = current / 2 }\n\n // Make the path for the battery level.\n let barPath = new Path()\n barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)\n draw.addPath(barPath)\n draw.setFillColor(Color.black())\n draw.fillPath()\n return draw.getImage()\n}", "spawnBattery() {\n const position = this.randomiseInitialPos();\n const velocity = this.randomiseInitialVelocity(50);\n\n // Add the sprite\n const battery = this.physics.add.sprite(\n position.xx,\n position.yy,\n \"battery\"\n );\n Align.scaleToGameWidth(battery, 0.03);\n this.batteryGroup.add(battery);\n\n // Set the interaction collision of the battery\n battery.body.setVelocity(velocity.x, velocity.y);\n battery.body.bounce.setTo(1, 1);\n battery.body.angularVelocity = 1;\n battery.body.collideWorldBounds = true;\n\n this.setBatteryColliders();\n }", "function mxShapeInfographicRibbonBackFolded(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.dx = 0.5;\n\tthis.dy = 0.5;\n\tthis.notch = 0.5;\n}", "showBrick(){\n fill('#edeffa')\n rect(this._posX, this._posY, this._width, this._height);\n }", "function Bat(x,y,cnv) {\n\tActor.call(this,x,y,\"bat.png\",cnv,null,null,null,60);\n\tthis.debugColor = \"#DD4400\";\n\tthis.state = \"wander\";\n}", "function AntiMissileBattery(position){\n\tthis.active = true;\n\tthis.missiles = 10;\n this.position = position;\n\tthis.x = position[0];\n\tthis.y = position[1];\n\tthis.width = 20;\n this.height = 25;\n\tthis.missilesPositions = [[-10,10],[-5,10],[0,10],[5,10],[10,10],\n\t [-10,25],[-5,25],[0,25],[5,25],[10,25]];\n\t//draw missiles in the battery\n\tthis.draw = function(){\n\t\tctx.fillStyle = \"blue\";\n\t\tvar x = this.x;\n\t\tvar y = this.y;\n\t\tthis.missilesPositions.forEach(function(mPosition){\n var mX = x + mPosition[0];\n var mY = y + mPosition[1]; \n ctx.fillRect(mX,mY,2,12); \n\t\t}); \n\t};\n\n\tthis.fire = function(){\n\t\tthis.missiles--;\n\t\tthis.missilesPositions.pop();\n\t};\n\n}", "function drawPlantBattery() {\n //console.log(\"Inside Draw battery\");\n\n let x = plant.x + plant.x * (4 / 100);\n let y = plant.y - 25;\n //console.log(y);\n\n ctx.beginPath();\n ctx.lineWidth = \"2\";\n ctx.strokeStyle = \"black\";\n //console.log((8 * timerLimit) / 60);\n //loop to draw the battery\n for (let i = 1; i <= 8; i++) {\n ctx.rect(x, y, 7, 20);\n ctx.fillStyle = \"white\";\n ctx.fillRect(x, y, 7, 20);\n x += 7;\n }\n\n //reset battery x,y coordinates\n x = plant.x + plant.x * (4 / 100);\n y = plant.y - 25;\n //console.log(timerLimit);\n //loop to fill battery progress based on the remaining timer\n for (let i = 0; i < (8 * timerLimit) / 60; i++) {\n ctx.rect(x, y, 7, 20);\n ctx.fillStyle = \"#FF0000\";\n ctx.fillRect(x, y, 7, 20);\n\n x += 7;\n }\n\n ctx.stroke();\n}", "constructor(weighBoat){\n super(weighBoat);\n this.chemFill = createGraphics(this.width() * WEIGH_BOAT_CHEM_WIDTH, this.height() * WEIGH_BOAT_CHEM_HEIGHT);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set the home screen product screen selected option based on the user choice (popular, best, new)
function setPopularSectionSelected(btnName){ $('#popular').removeClass('active'); $('#best').removeClass('active'); $('#new').removeClass('active'); $('#'+btnName).addClass('active'); }
[ "function updateProductSelection() {\n var flavor = document.querySelectorAll(\".flavor-selected\")[0];\n var glazing = document.querySelectorAll(\".glazing-selected\")[0];\n\n if (flavor != null && glazing == null) {\n var flavorText = flavor.innerHTML;\n document.getElementById(\"flavor\").innerHTML = \"Select Flavor:\" + flavorText;\n } else if (glazing != null && flavor == null) {\n var glazingText = glazing.innerHTML;\n document.getElementById(\"glazing\").innerHTML =\n \"Select Glazing:\" + glazingText;\n } else if (flavor != null && glazing != null) {\n var flavorText = flavor.innerHTML;\n var glazingText = glazing.innerHTML;\n document.getElementById(\"flavor\").innerHTML = \"Select Flavor:\" + flavorText;\n document.getElementById(\"glazing\").innerHTML =\n \"Select Glazing:\" + glazingText;\n } else {\n document.getElementById(\"flavor\").innerHTML = \"Select Flavor: Original\";\n document.getElementById(\"glazing\").innerHTML = \"Select Glazing: None\";\n }\n}", "function changeProduct(){\r\n\r\n toolbox.product_selected = true;\r\n \t\r\n\t\t$('#pi_product_name').html(\r\n\t\t\ttoolbox.selected_client_name + ' - ' +\r\n\t\t\ttoolbox.selected_manufacturer_name + ' - ' +\r\n\t\t\ttoolbox.selected_product_name\r\n\t\t);\r\n\r\n\t\tif (toolbox.selected_language_id) {\r\n \t\tloadProductImages();\r\n \t}\r\n \t\r\n }", "selectProduct(product) {\n Shared.selectProduct = product;\n }", "function setProductInView() {\n $scope.presentPercentageOff = $scope.product.percentage_off ? true : false;\n $scope.presentOriginalPrice = $scope.product.original_price ? true : false;\n $scope.changePercentageOff();\n $scope.changeOriginalPrice();\n fillOptionMenus();\n setProductPhotos();\n }", "function updateProdAvailability(product, selected, availability) {\n var label=\"\";\n var availability1;\n \n if ((availability-selected)>5)\n {\n label= product + \" are available\";\n availability1=AVAILABLE;\n }\n else if (selected==availability){\n label= product + \" are out of stock\";\n availability1=OUT_OF_STOCK;\n } \n else if ((availability-selected)<=5){ \n label= product + \" limited Supply\";\n availability1=LIMITED_SUPPLY;\n }\n updateProdAvailabilityLabel(product, label, availability1);\n return;\n}", "function updateSelected() {\n selected = Number.parseInt(elements.laptopSelect.value, 10);\n updateUI();\n }", "function setSelected( index ){\n _selected = _product.variants[ index ];\n}", "function randomiseOptions() {\n // TODO randomiation turned off, need to fix\n if (Math.random() > 0.5) {\n console.log(\"Switching!\");\n state.isSwitched = true;\n var tmp = state.products[0];\n state.products[0] = state.products[1];\n state.products[1] = tmp;\n }\n\n}", "function setSelected(index){\n\t_selected = _product.variants[index];\n}", "function setSelected(index) {\n _selected = _product.variants[index];\n}", "function userSelection() {\n\t\t$(\".animal-choice__one\").on(\"click touchstart\", function() {\n\t\t\tuserChoice = \"choice--one\";\n\n\t\t\t$(\".animal-choice__two\").removeClass(\"choice-selected\");\n\t\t\t$(this).addClass(\"choice-selected\");\n\t\t});\n\n\t\t// if user selects cat, change class name of choice--two to userChoice in the generateChoiceTwo() function.\n\t\t$(\".animal-choice__two\").on(\"click touchstart\", function() {\n\t\t\tuserChoice = \"choice--two\";\n\n\t\t\t$(\".animal-choice__one\").removeClass(\"choice-selected\");\n\t\t\t$(this).addClass(\"choice-selected\");\n\t\t});\n\t}", "function selectActivity() {\n inquirer.prompt([{\n name: 'options',\n type: 'list',\n message: 'Select',\n choices: ['View Products for Sale', 'View Low Inventory', 'Add to Inventory', 'Add New Product']\n }]).then(function (res) {\n switch (res.options) {\n case 'View Products for Sale':\n viewProducts();\n break;\n case 'View Low Inventory':\n viewLow();\n break;\n case 'Add to Inventory':\n getInventory();\n break;\n case 'Add New Product':\n addNewProduct();\n break;\n }\n });\n}", "function changeProductType() {\r\n\r\n //TSM global var\r\n product_type_selected = true;\r\n\t\ttoolbox.navigation.setCanonical();\r\n\r\n $('#tsm_product_type_name')\r\n .html(toolbox.selected_client_name + \" &mdash; \" + toolbox.selected_product_type_name + \" &mdash; \" + toolbox.selected_language_name)\r\n .attr('client_product_type_id', toolbox.selected_client_product_type_id)\r\n .attr('language_id', toolbox.selected_language_id);\r\n\r\n if (toolbox.selected_client_id) {\r\n loadTechSpecCategoryList();\r\n }\r\n }", "function instantiateCurrentObject() {\n var product = $(\"select#products option:selected\").val();\n \"mdx2\" === product ? menuObj.mdx2 = currentItems : \"sas\" === product ? menuObj.sas = currentItems : \"newDsp\" === product ? menuObj.newDsp = currentItems : \"dsp\" === product ? menuObj.dsp = currentItems : \"dmp\" === product ? menuObj.dmp = currentItems : \"supportKb\" === product && (menuObj.supportKb = currentItems);\n }", "function pickGenre() {\n if ($(\"#select\").val() === \"action\") {\n genre = action;\n }\n if ($(\"#select\").val() === \"comedy\") {\n genre = comedy;\n }\n if ($(\"#select\").val() === \"documentary\") {\n genre = documentary;\n }\n if ($(\"#select\").val() === \"drama\") {\n genre = drama;\n }\n if ($(\"#select\").val() === \"family\") {\n genre = family;\n }\n if ($(\"#select\").val() === \"horror\") {\n genre = horror;\n }\n if ($(\"#select\").val() === \"scifi\") {\n genre = scifi;\n }\n}", "function onProductChanged() {\n // Need to update license info and hide the row containing version\n // selection if apsoil is selected.\n updateLicense();\n var product = $('#Product').find('option:selected').text();\n\n // If user has selected apsim (ng), show the Linux/MacOS platforms.\n // Otherwise, hide them.\n if (product == apsimName) {\n $('#platformLinux').show();\n $('#platformMacOS').show();\n } else {\n $('#platformLinux').hide();\n $('#platformMacOS').hide();\n $('#platform-selector').prop('selectedIndex', 0);\n }\n\n // If user has selected old apsim, show the version dropdown.\n // (This allows them to select historical major releases such as 7.9).\n // Otherwise, hide the version selector.\n $('#version-selector option').each(function() { $(this).hide(); });\n $('#version-selector option.latest-version').each(function() { $(this).show(); });\n var productClass = product.replaceAll(' ', '');\n $(`#version-selector option.${productClass}`).each(function() {\n $(this).show();\n });\n}", "function differentStorePickupSelected() {\n differentStoreSelectedForPickup = true;\n updateTabStates();\n}", "chooseDefault () {\n this.choose(this.ui.effectSelector.items[0].value);\n }", "function setSelectedVariant(variant, isBundle) {\n \n \t// update the elements\n\t\t$('#price').text(variant.price); // update the price\n\t\t$('.product-details__finish').text(variant.title); // update the title\n\t\t$('.sku').text(variant.sku); // update the sku\n\n\t\t// update bundle selection UI\n \tRCB.bundle.updateBundleUI(variant.title);\n \n \t// check if bundle\n if(isBundle) {\n\t\t\tvar bundleId = RCB.bundle.getBundle();\n \n \tvar bundleVariant = RCB.bundle.getBundleVariant(bundleId, variant.title);\n \n \t$('#id').val(bundleVariant.id); // update the variant id\n \t$('#id').attr('base-id', variant.id); // update the base variant id\n }\n else {\n\t\t\t$('#id').val(variant.id); // update the variant id\n \t$('#id').attr('base-id', '');\n }\n \n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if view,edit,delete & add is true the update selectAll is true
function updateSelectAllValue(data) { if (data.view && data.edit && data.add && data.delete) data.selectAll = true; else data.selectAll = false; }
[ "function updateDataTableSelectAllCtrl(table){\n var $table = table.table().node();\n var $chkbox_all = $('tbody input[type=\"checkbox\"]', $table);\n var $chkbox_checked = $('tbody input[type=\"checkbox\"]:checked', $table);\n var chkbox_select_all = $('thead input[name=\"select_all\"]', $table).get(0);\n\n // If none of the checkboxes are checked\n if($chkbox_checked.length === 0){\n chkbox_select_all.checked = false;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = false;\n }\n\n // If all of the checkboxes are checked\n } else if ($chkbox_checked.length === $chkbox_all.length){\n chkbox_select_all.checked = true;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = false;\n }\n\n // If some of the checkboxes are checked\n } else {\n chkbox_select_all.checked = true;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = true;\n }\n }\n }", "function updateDataTableSelectAllCtrl(table){\n var $table = table.table().node();\n var $chkbox_all = $('tbody input[type=\"checkbox\"]', $table);\n var $chkbox_checked = $('tbody input[type=\"checkbox\"]:checked', $table);\n var chkbox_select_all = $('thead input[name=\"select_all\"]', $table).get(0);\n\n if($chkbox_checked.length === 0){\n chkbox_select_all.checked = false;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = false;\n }\n\n } else if ($chkbox_checked.length === $chkbox_all.length){\n chkbox_select_all.checked = true;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = false;\n }\n\n } else {\n chkbox_select_all.checked = true;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = true;\n }\n }\n}", "function updateSelectAll() {\n\t var visibleRows = scope.rows;\n\t if (!visibleRows) {\n\t var numVisibleRows = 0;\n\t var checkedCnt = 0;\n\t } else {\n\t var numVisibleRows = visibleRows.length;\n\t var checkedCnt = visibleRows.filter(hzTableCtrl.isSelected).length;\n\t }\n\t\n\t if (numVisibleRows == 0) {\n\t element.prop('checked', false);\n\t } else {\n\t element.prop('checked', numVisibleRows > 0 && numVisibleRows == checkedCnt);\n\t }\n\t }", "function updateDataTableSelectAllCtrl(table){\r\n var $table = table.table().node();\r\n var $chkbox_all = $('tbody input[type=\"checkbox\"]', $table);\r\n var $chkbox_checked = $('tbody input[type=\"checkbox\"]:checked', $table);\r\n var chkbox_select_all = $('thead input[name=\"select_all\"]', $table).get(0);\r\n\r\n // If none of the checkboxes are checked\r\n if($chkbox_checked.length === 0){\r\n chkbox_select_all.checked = false;\r\n if('indeterminate' in chkbox_select_all){\r\n chkbox_select_all.indeterminate = false;\r\n }\r\n\r\n // If all of the checkboxes are checked\r\n } else if ($chkbox_checked.length === $chkbox_all.length){\r\n chkbox_select_all.checked = true;\r\n if('indeterminate' in chkbox_select_all){\r\n chkbox_select_all.indeterminate = false;\r\n }\r\n\r\n // If some of the checkboxes are checked\r\n } else {\r\n chkbox_select_all.checked = true;\r\n if('indeterminate' in chkbox_select_all){\r\n chkbox_select_all.indeterminate = true;\r\n }\r\n }\r\n}", "function editSelected(){\n // todo \n }", "function addAllOption() {\n if ($scope.showAllOption && $user.instance().role && $user.instance().role.length > 1) {\n var allcompanies = [],\n already = _.findIndex($scope.companies, function(row) {\n return row.company.name === 'Todas Empresas';\n });\n if (already === -1) {\n $user.instance().current('companies').forEach(function(row) {\n allcompanies.push(row.company._id)\n })\n $scope.companies.push({\n company: {\n name: 'Todas Empresas',\n _id: allcompanies\n }\n });\n }\n }\n }", "function updateSelectAll() {\n var visibleRows = scope.rows;\n var numVisibleRows = visibleRows.length;\n var checkedCnt = visibleRows.filter(hzTableCtrl.isSelected).length;\n element.prop('checked', numVisibleRows > 0 && numVisibleRows === checkedCnt);\n }", "function update_all(){\r\n\t\t\talert('updating all hyjacks');\r\n\t\t\t$.hyjack_select.update();\r\n\t\t\t$.hyjack_select.update_all();\t\t\r\n\t\t}", "function updateDataTableSelectAllCtrl(table){\n var $table = table.table().node();\n var $chkbox_all = $('tbody input[type=\"checkbox\"]', $table);\n var $chkbox_checked = $('tbody input[type=\"checkbox\"]:checked', $table);\n var chkbox_select_all = $('thead input[name=\"select_all\"]', $table).get(0);\n\n // If none of the checkboxes are checked\n if($chkbox_checked.length === 0){\n chkbox_select_all.checked = false;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = false;\n }\n\n // If all of the checkboxes are checked\n } else if ($chkbox_checked.length === $chkbox_all.length){\n chkbox_select_all.checked = true;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = false;\n }\n\n var table = $('#example').DataTable({ \n // If some of the checkboxes are checked\n } else {\n chkbox_select_all.checked = true;\n if('indeterminate' in chkbox_select_all){\n chkbox_select_all.indeterminate = true;\n }\n }\n}", "function updateList() {\n selectWithSearchDatasource.getSelectOptions(selectWithSearchModalController.datasourceName, {\n query: selectWithSearchModalController.query,\n page: selectWithSearchModalController.page,\n params: selectWithSearchModalController.params,\n fullModel: selectWithSearchModalController.fullModel\n }).then(function (data) {\n selectWithSearchModalController.searchResults = data;\n setNonSelectedResults();\n });\n }", "CHANGE_SELECT_ALL_STATUS (state, newValBoolen) {\n state.select_all = newValBoolen\n state.table_row_status = newValBoolen\n }", "function changeSelectionStatusAll() {\n\n var keys = Object.keys(self.selectedRows);\n\n if(self.allToggled) {\n for(var x=0; x<Object.keys(self.selectedRows).length; x++) {\n self.selectedRows[keys[x]] = false;\n }\n }\n else {\n for(var x=0; x<Object.keys(self.selectedRows).length; x++) {\n self.selectedRows[keys[x]] = true;\n }\n }\n }", "function updateSelectAllCheckbox () {\n var unselectedRows = $(element).find('.select-row:not(:checked)');\n\n if (unselectedRows.length == 0) {\n selectAllCheckbox.prop('checked', true);\n } else {\n selectAllCheckbox.prop('checked', false)\n }\n }", "function toggleAllSelection(){\n\t\t\tif(areAllContactsSelected()){\n\t\t\t\t//deselectall\n\t\t\t\t$scope.selectedContacts.length=0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$scope.selectedContacts=$scope.receivedContacts.concat($scope.addedContacts);\n\t\t\t}\n\t\t}", "function updateSelectAll(filterName) {\n\tvar checkSum = 0;\n\tif (filterName == \"tooltip\") {\n\t\tvar checkMax = $(\".tooltip_display\").length;\n\t\t$(\".tooltip_display\").each(function(d){ checkSum += this.checked;});\n\t} else {\n\t\tvar checkMax = $(\".checkbox[name='\" + filterName + \"']\").length;\n\t\t$(\".checkbox[name='\" + filterName + \"']\").each(function(d){ checkSum += this.checked;});\n\t}\n\tif (checkSum == checkMax) {\n\t\t$(\"#\" + filterName.replace(/,|\\.|-| /g, \"\") + \"_selectall\").prop(\"checked\", true).button(\"refresh\");\n\t} else {\n\t\t$(\"#\" + filterName.replace(/,|\\.|-| /g, \"\") + \"_selectall\").prop(\"checked\", false).button(\"refresh\");\n\t}\n}", "toggleSelectAll () {\n if (this.selectedObjects.length < this.objects.length) {\n this.selectedObjects.replace(this.objects);\n } else {\n this.selectedObjects.replace([]);\n }\n }", "function actionSelectAll() {\n editor.selectAll();\n }", "function updateSelectAllButtonState(){\r\n\t\t\r\n\t\tvar objButton = g_objPanel.find(\".uc-button-select-all\");\r\n\t\t\r\n\t\tvar numItems = getNumItems();\r\n\t\t\r\n\t\tif(numItems == 0){\r\n\t\t\tobjButton.addClass(\"button-disabled\");\r\n\t\t\t\r\n\t\t\tobjButton.html(objButton.data(\"textselect\"));\r\n\t\t\treturn(false);\r\n\t\t}\r\n\t\t\r\n\t\tobjButton.removeClass(\"button-disabled\");\r\n\t\t\r\n\t\tvar numSelected = getNumSelectedItems();\r\n\t\tif(numSelected != numItems){\r\n\t\t\tobjButton.html(objButton.data(\"textselect\"));\r\n\t\t}else{\r\n\t\t\tobjButton.html(objButton.data(\"textunselect\"));\r\n\t\t}\r\n\t\t\r\n\t}", "toggleSelectAll(e) {\n e.preventDefault()\n\n if (this.selectAllChecked) {\n this.clearResourceSelections()\n } else {\n this.selectAllResources()\n }\n\n this.getActions()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clear options on select by parameter
function clearSelect(selectElement) { //selectElement.find('option').remove(); $(selectElement.find("option")).each(function (index, element) { if (element.value != "0") element.remove() }); // selectElement.append(new Option("---" + selectElement.attr("data-text") + " Seçiniz ---", 0)) }
[ "function clearOptions(select)\n{\n for(let i = 0; i < select.length; i++)\n {\n select.remove(i);\n }\n}", "function clearSelect() {\r\n for (var i = 0; i < arguments.length; i++) {\r\n var element = arguments[i];\r\n\r\n if (typeof element == 'string')\r\n element = document.getElementsByName(element)[0];\r\n\r\n if (element && element.options) {\r\n element.options.length = 0;\r\n element.selectedIndex = -1;\r\n }\r\n }\r\n}", "function clearSelect(select) {\n var i = select.options.length;\n while(i > 0) {\n select.remove(i);\n i--;\n }\n}", "function selectRemoveAll(select_field) {\n\n var select_size = select_field.options.length\n\n while (select_field.options.length > 0) {\n select_field.options[0] = null;\n }\n\n}", "function clearOptions(select) {\n select = getObject(select);\n var ret = new Array();\n if (select != null) {\n for (var i = 0; i < select.options.length; i++) {\n var option = select.options[i];\n ret[ret.length] = new Option(option.text, option.value);\n }\n select.options.length = 0;\n }\n return ret;\n}", "function clearOptions(theSelectObj) {\n\n // Clear all the dropdown fields\n if (bw.ns4 || bw.ns6) {\n theSelectObj.options.length = 0;\n } else {\n for (x = theSelectObj.length -1; x >= 0; x--) {\n theSelectObj.remove(x);\n }\n }\n}", "function clearSelectMesPkg() {\n var select = document.getElementById(\"mesPkgId\");\n var length = select.options.length;\n for (i = length - 1; i >= 0; i--) {\n select.options[i] = null;\n }\n}", "function clearList(){\n if(document.getElementById('mySelect').options.length > 0){\n document.getElementById('mySelect').options.length = 0;\n }\n else{return}\n }", "function clearSelectOptions(select_array) {\n $.each(select_array, function() {\n $(this).empty();\n });\n}", "function clearSelectBox(){\n\tvar id_value = $m.getPref(\"id_Value\");\n\tif(id_value != undefined){\n\t\t$m.juci.getControl(id_value).value(null);\t\t\n\t}\n}", "function DeselectAllOptions(campo_select) {\n if (!campo_select) {\n return;\n }\n var j = campo_select.options.length;\n for (var i = 0; i < j; i++) {\n campo_select.options[i].selected = false;\n }\n}", "function clearDropdownFilterValues(){\n\t\n\tdocument.getElementById('opt-portfolio').innerHTML = '<option value=\"all\">(All)</option>';\n\tdocument.getElementById('opt-manDirector').innerHTML = '<option value=\"all\">(All)</option>';\n\tdocument.getElementById('opt-lead').innerHTML = '<option value=\"all\">(All)</option>';\n\tdocument.getElementById('opt-manager').innerHTML = '<option value=\"all\">(All)</option>';\n\tdocument.getElementById('opt-servTier').innerHTML = '<option value=\"all\">(All)</option>';\n\tdocument.getElementById('opt-appName').innerHTML = '<option value=\"all\">(All)</option>';\n\n}", "function clearCombo(selectbox)\n{\n for(var i = 0; i < selectbox.options.length;) {\n selectbox.remove(i);\n }\n}", "function clearCriterias(){\n\t$(\"input\").each(function(){\n\t $(this).attr(\"value\", $(this).val());\n\t});\n\t$('select option').each(function(){ this.defaultSelected = this.selected; });\n\tvar queryForm = $(\"#queryForm\").html()\n\t\n\tclear_criterias(queryForm);\n}", "function clearOptions() {\n while (classSelect.firstChild) {\n classSelect.removeChild(classSelect.firstChild);\n }\n}", "function clear_select_options(element) {\n for (var i = element.options.length - 1; i >= 0; i--) {\n element.remove(i);\n }\n}", "function reset()\n{\n\tvar select = document.getElementById(this.containerId).getElementsByTagName(\"select\");\n\n\t// NONE MODE\n\tthis.setMode(3);\n\t// set to default values\n\tthis.setCountry(\"all countries\");\t\n\tselect[0].value = \"all countries\";\n\tselect[1].value = \"0\";\n\tselect[1].disabled = \"disabled\";\n\t// delete all nodes and links\n\tthis.clear();\n}", "function removeSelectedOptions(from) { \r\n\t//if (!hasOptions(from)) { return; }\r\n\t document.getElementById(\"resum\").innerHTML = '';\r\n\tif (from.type==\"select-one\") {\r\n\t\tfrom.options[from.selectedIndex] = null;\r\n\t\t}\r\n\telse {\r\n\t\tfor (var i=(from.options.length-1); i>=0; i--) { \r\n\t\t\tvar o=from.options[i]; \r\n\t\t\tif (o.selected) { \r\n\t\t\t\tfrom.options[i] = null; \r\n\t\t\t\t} \r\n\t\t\t}\r\n\t\t}\r\n\tfrom.selectedIndex = -1; \r\n\t}", "function selectRemoveAll(select_input) {\n\n var linesNumber = select_input.options.length;\n for(i=0; i < linesNumber; i++) {\n\t\tselect_input.options[0] = null;\n }\n\tselect_input.selectedIndex = -1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clear the previous search results by removing all the children of the "searchResultsList" ul element
function clearSearchResultsList() { var ul = document.getElementById("searchResultsList"); while (ul.firstChild) { ul.removeChild(ul.firstChild); } }
[ "function clearList(){\r\n while(searchList.firstChild){\r\n searchList.removeChild(searchList.firstChild);\r\n }\r\n }", "function clearResults() {\n $results.children().remove();\n }", "function clearSearchResults() {\n $(\".search-results\").empty();\n }", "function clearSearchList() {\n\t\n\twhile (searchResults.length > 0) {\n\t\tsearchResults.pop();\n\t}\n}", "function clearSearchResults() {\n searchResultsCache.length = 0;\n // Remove all existing search results\n while (resultsSectionElem.firstChild) {\n resultsSectionElem.removeChild(resultsSectionElem.firstChild);\n }\n }", "function clearResults(){\n $(settings.results).children().remove();\n }", "function clearList(){\r\n while(searchList.firstChild){\r\n searchList.removeChild(searchList.firstChild);\r\n }\r\n}", "function clearResults() {\r\n $('#searchresults').empty();\r\n}", "function emptySearchResults()\n {\n searchList.innerHTML='';\n searchResults=[];\n }", "function resetSearchList() {\n\t\t$('#itemsList').html('');\n\t}", "function clearResults() {\n $(RESULTS_CONTAINER).add(SEARCH_RESULTS).removeClass('open');\n $(RESULTS_CONTAINER).height('');\n $(SEARCH_RESULTS).html('');\n}", "function clearResults(){\n searchResults.innerHTML = '';\n}", "function clearTable() {\n if (searchResultsList.children().length > 0) {\n searchResultsList.empty();\n }\n }", "function clearResults() {\n\t\t$(\"#results\").empty();\n\n\t}", "function cleanSearchResults() {\n cleanMarkers();\n cleanSearchResultsPane();\n}", "function clearResults(wrapper, my_override_tag) {\n function dump(my_parent, my_tag_name) {\n var child_list = my_parent.children,\n i,\n i_len,\n child;\n\n // XXX: now that link (\"A\") stays, rewrite the whole element clearing!\n for (i = 0, i_len = child_list.length; i < i_len; i += 1) {\n child = child_list[i];\n if (child && child.tagName === my_tag_name) {\n if (my_tag_name === \"A\") {\n child.className += \" ui-disabled\";\n } else {\n my_parent.removeChild(child);\n }\n }\n }\n }\n\n // always clear autocomplete results (UL), the create new record input (DIV)\n // will only be removed on new searches, while the plane (A) is disabled\n dump(wrapper, \"UL\");\n dump(wrapper, my_override_tag || \"DIV\");\n dump(wrapper.parentElement, my_override_tag || \"A\");\n }", "function resetSearchResults() {\n\t\tsearchresults.listD.length = 0;\t searchresults.listSL.length = 0; searchresults.listWC.length = 0; \n\t\tsearchresults.listSI.length = 0; searchresults.listLBM.length = 0; searchresults.listGEN.length = 0; \n\t}", "clearSearchResults() {\n this.searchResults = [];\n this.searchSelection = 0;\n }", "function emptyResults() {\n $('#search-results').empty();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Darken a color based on its HSV value with a percent
darkenColor(h, s, v, percent) { h = (v * (1 + percent) > 1) ? 1 : v * (1 + percent); return { h, s, v }; }
[ "function darkenColor(color, percentage) {\n return d3.hsl(color).darker(percentage);\n}", "function darkenColor(color) {\n const re = /(hsl\\(\\d{1,3}, \\d{1,3}%, )(\\d{1,3})%\\)/;\n let light = parseInt(color.match(re)[2]);\n\n if (light - 10 > 0) light -= 10;\n else light = 0;\n\n let darkendedColor = color.replace(re, `$1${light}%)`);\n\n return darkendedColor;\n}", "getDarkerColor(step){\n const newLightness = (this.lightness-step >= 10) ? this.lightness-step : 10\n return new Color(this.hue, this.saturation, newLightness)\n }", "changeColorBasedonPercentage(percentage){\n let r, g, b = 0 //We set each channel to 0\n let hue\n if(percentage < 50) { //If the percentage is less than 50%, we set the red to max and update multiply the green channel by a color index, to create a \"gradient\" from red to orange/yellow\n r = 255;\n g = Math.round(5.1 * percentage)\n }\n else { // Same as above but we reverse the channels\n g = 255;\n r = Math.round(510 - 5.10 * percentage)\n }\n hue = r * 0x10000 + g * 0x100 + b * 0x1 // We calculate the hue by multiplying each channel by an hexadecimal index to specify the strongest colors in the gradients\n\n //We convert the value of the hue an hexadecimal value the css can understand\n return '#' + ('000000' + hue.toString(16)).slice(-6)\n }", "function lighten(color, percent) {\n\t\tvar n = parseInt(color.slice(1), 16),\n\t\ta = Math.round(2.55 * percent || 0),\n\t\t// Bitshift 16 bits to the left\n\t\tr = (n >> 16) + a,\n\t\t// Bitshift 8 bits to the left based on blue\n\t\tb = (n >> 8 & 0x00FF) + a,\n\t\t//\n\t\tg = (n & 0x0000FF) + a;\n\t\t// Calculate\n\t\treturn '#' + (\n\t\t\t\t0x1000000 + (r < 255 ? r < 1 ? 0 : r : 255) * 0x10000 +\n\t\t\t\t(b < 255 ? b < 1 ? 0 : b : 255) * 0x100 + (g < 255 ? g < 1 ? 0 : g : 255)\n\t\t\t).toString(16).slice(1).toUpperCase();\n\t}", "function darken(color,percentage){\n var local_color = color;\n var deduction = Math.round(255 * (percentage / 100));\n if (color.charAt(0)=='#'){\n local_color = hex2rgb(color.substring(1));\n }\n var parts = new Array();\n parts = local_color.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/);\n var r = (parts[1] - deduction > 0) ? parts[1] - deduction : 0;\n var g = (parts[2] - deduction > 0) ? parts[2] - deduction : 0;\n var b = (parts[3] - deduction > 0) ? parts[3] - deduction : 0;\n return 'rgb('+r+','+g+','+b+')';\n }", "function HSV(h, s, v) {\n var r = 0,\n \tg = 0,\n \tb = 0;\n if (h < 60) {\n r = 255;\n g = h * 255 / 60;\n } else if (h < 120) {\n g = 255;\n r = (120 - h) * 255 / 60;\n } else if (h < 180) {\n g = 255;\n b = (h - 120) * 255 / 60;\n } else if (h < 240) {\n b = 255;\n g = (240 - h) * 255 / 60;\n } else if (h < 300) {\n b = 255;\n r = (h - 240) * 255 / 60;\n } else {\n r = 255;\n b = (360 - h) * 255 / 60;\n }\n // Scale to same total luminance; assumes each colour is similarly bright\n var lum = r + g + b;\n r = r * 255 / lum;\n g = g * 255 / lum;\n b = b * 255 / lum;\n \n // Scale for saturation and value\n var minv = (255 - s) * v / 255;\n var maxv = v;\n \n red = r * (maxv - minv) / 255 + minv;\n green = g * (maxv - minv) / 255 + minv;\n blue = b * (maxv - minv) / 255 + minv;\n\n return rgb2Int(red, green, blue);\n}", "function darkerColor(rgb){\n \n\t rgb = rgb.split(\"rgb(\")[1].split(\")\")[0];\n\t rgb = rgb.replace(/ /g,'').split(\",\");\n\t \n\t //10% of 255 = 25 rounded\n\t rgb[0] = rgb[0] - 25 < 0 ? 0 : rgb[0] - 25;\n\t rgb[1] = rgb[1] - 25 < 0 ? 0 : rgb[1] - 25;\n\t rgb[2] = rgb[2] - 25 < 0 ? 0 : rgb[2] - 25;\n\n\t //Return new color\n\t return \"rgb(\" + rgb[0] + \", \" + rgb[1] + \", \" + rgb[2] + \")\";\n\n\t}", "static HSV(h, s, v) {\n let max = v * 0xff / 100,\n min = max - s * max / 100;\n\n if (h < 60) {\n return new Color(max, h * (max - min) / 60 + min, min);\n } else if (h < 120) {\n return new Color((120 - h) * (max - min) / 60 + min, max, min);\n } else if (h < 180) {\n return new Color(min, max, (h - 120) * (max - min) / 60 + min);\n } else if (h < 240) {\n return new Color(min, (240 - h) * (max - min) / 60 + min, max);\n } else if (h < 300) {\n return new Color((h - 240) * (max - min) / 60 + min, min, max);\n } else {\n return new Color(max, min, (360 - h) * (max - min) / 60 + min);\n }\n }", "function shadeColor(color, percent) { \n var num = parseInt(color.slice(1),16),\n amt = Math.round(2.55 * percent),\n R = (num >> 16) + amt,\n G = (num >> 8 & 0x00FF) + amt,\n B = (num & 0x0000FF) + amt;\n return \"#\" + (0x1000000 + (R<255?R<1?0:R:255)*0x10000 + (G<255?G<1?0:G:255)*0x100 + (B<255?B<1?0:B:255)).toString(16).slice(1);\n}", "function convertRGB(pctX, pctY, hsl) {\n\tconst hue = pctX * 360\n\tconst split = 60\n\tconst bracket = Math.floor(hue / split)\n\tconst isEven = bracket % 2\n\tconst l = hsl[2].split('%')[0]\n\tconst value = () => {\n\t\t\n\t\t\n\t\t// const main = ((pctX * (255 * 6)) - (bracket * 255))\n\t\t\n\t\t\n// \t\tconst hueRemaining = val => ((255 - val) / 255) * 255\n\t\t\n// \t\tconst tintChange = change => {\n// \t\t\tif (lighterPct) {\n// \t\t\t\tconsole.log(lighterPct, lighter, hueRemaining(change))\n// \t\t\t\treturn Math.floor(lighter + (hueRemaining(change) * lighterPct))\n// \t\t\t} else if (darkerPct) {\n// \t\t\t\treturn Math.floor(darker - (hueRemaining(change) * lighterPct))\n// \t\t\t}\n// \t\t\treturn 0\n// \t\t}\n\t\n\t\t// console.log(tintChange())\n\n\t\t// const change = Math.floor((l / 100) * ((pctX * (255 * 6)) - (bracket * 255))) + lighter\n\t\t// const change = Math.floor(isEven ? 255 - newChange + tintChange(newChange) : newChange + tintChange(newChange)) \n\t\t\n\t\t// console.log({ change, lighter, darker })\n\t\t// let light = Math.floor((pctY - 0.5) * (255 * 2))\n\t\t// light = light < 0 ? 0 : light\n\t\t// light = light > 255 ? 255 : light\n\t\t// let dark = Math.floor(((0.5 - pctY) * (255)))\n\t\t// dark = dark < 0 ? 0 : dark\n\t\t// dark = dark > 255 ? 255 : dark\n\t\t// console.log({ bracket, change, dark, light })\n\t\t// let lighter = 0\n\t\t// let darker = 255\n\n\t\t\n\t\tconst lighterPct = l > 50 ? 1 - (l - 50) / 50 : false\n\t\tconst darkerPct = l < 50 ? (l / 50) : false\n\t\tconsole.log({ lighterPct, darkerPct })\n\t\tconst colorDiff = color => {\n\t\t\tconst shade = lighterPct || darkerPct || 0\n\t\t\treturn Math.floor((255 - color) * shade)\n\t\t}\n\n\t\tlet lighter = Math.floor(0 + ((l > 50 ? (l - 50) / 100 * (255 * 2) : 0) ))\n\t\tlet darker = Math.floor(255 + ((l < 50 ? (l-50) / 100 * (255 * 2) : 0) ))\n\t\tconst modifier = 0\n\t\t// let newChange = ((l / 100) * ((pctX * (255 * 6)) - (bracket * 255)) * 2)\n\t\tlet newChange = (pctX * 255 * 5) - (bracket * 255)\n\t\tlet main = Math.floor(isEven ? 255 - newChange : newChange)\n\t\tconst change = main\n\t\t// console.log(colorDiff(newChange))\n\t\treturn [\n\t\t\t`(${darker}, ${change}, ${lighter})`,\n\t\t\t`(${change}, ${darker}, ${lighter})`,\n\t\t\t`(${lighter}, ${darker}, ${change})`,\n\t\t\t`(${lighter}, ${change}, ${darker})`,\n\t\t\t`(${change}, ${lighter}, ${darker})`,\n\t\t\t`(${darker}, ${lighter}, ${change})`,\n\t\t]\n\t}\n\treturn value()[bracket]\n}", "function Colors_brighten(rgb, percent) {\n if (rgb) {\n var base = Math.min(Math.max(rgb.r, rgb.g, rgb.b), 230);\n //let base = Math.max(rgb.r, rgb.g, rgb.b);\n var step = getLightnessStep(base, percent);\n return {\n r: Math.max(0, Math.min(255, Math.round(rgb.r + step))),\n g: Math.max(0, Math.min(255, Math.round(rgb.g + step))),\n b: Math.max(0, Math.min(255, Math.round(rgb.b + step))),\n a: rgb.a\n };\n }\n else {\n // TODO is this correct ?\n return rgb;\n }\n}", "function hsv2hsl(h, s, v) {\n s /= _consts__WEBPACK_IMPORTED_MODULE_0__.MAX_COLOR_SATURATION;\n v /= _consts__WEBPACK_IMPORTED_MODULE_0__.MAX_COLOR_VALUE;\n var l = (2 - s) * v;\n var sl = s * v;\n sl /= l <= 1 ? l : 2 - l;\n sl = sl || 0;\n l /= 2;\n return { h: h, s: sl * 100, l: l * 100 };\n}", "function LightenDarkenColor(col, amt) {\n \n var usePound = false;\n \n if (col[0] == \"#\") {\n col = col.slice(1);\n usePound = true;\n }\n \n var num = parseInt(col,16);\n \n var r = (num >> 16) + amt;\n \n if (r > 255) r = 255;\n else if (r < 0) r = 0;\n \n var b = ((num >> 8) & 0x00FF) + amt;\n \n if (b > 255) b = 255;\n else if (b < 0) b = 0;\n \n var g = (num & 0x0000FF) + amt;\n \n if (g > 255) g = 255;\n else if (g < 0) g = 0;\n \n return (usePound?\"#\":\"\") + (g | (b << 8) | (r << 16)).toString(16);\n \n}", "function getHslColor(value, max) {\n\tvar percentage = value / max;\n\tvar hue = (percentage * (0 - 120)) + 120;\n\treturn 'hsl(' + hue + ', 100%, 50%)';\n}", "lighten(amount = 10) {\n const hsl = this.toHsl();\n hsl.l += amount / 100;\n hsl.l = Object(_util__WEBPACK_IMPORTED_MODULE_3__[\"clamp01\"])(hsl.l);\n return new TinyColor(hsl);\n }", "calculateInfectionColour(percent) {\n var r, g, b = 0;\n var divisor = 0;\n\n if (percent < 21) { //0% - 20%: Green - Yellow\n divisor = 21; //Comprises 20% of values\n g = 255;\n r = (255 / divisor) * percent; //How yellow it is\n }\n else if (percent < 71) { //21% - 70% Yellow - Red \n divisor = 1 - ((percent - 20) / 100) / 0.5; //Comprises 50% of values\n r = 255;\n g = 255 * divisor; //How yellow it is\n }\n else { //71% - 100% - Red - Dark Red\n divisor = (100 - percent) / 30;\n r = 255 - (100 * (1 - divisor)); //155 - 255\n g = 0;\n }\n\n r = Math.round((Math.min(r, 255)));\n g = Math.round((Math.min(g, 255)));\n\n var h = r * 0x10000 + g * 0x100 + b * 0x1;\n return \"#\" + (\"000000\" + h.toString(16)).slice(-6);\n }", "function perc2color(percent) {\n var r, g = 0;\n const b = Math.round((1 - Math.abs(50 - percent)/50) * 255);\n if (percent < 50) {\n r = 255;\n g = Math.round(5.1 * percent);\n }\n else {\n g = 255;\n r = Math.round(510 - 5.10 * percent);\n }\n const h = r * 0x10000 + g * 0x100 + b * 0x1;\n return '#' + ('000000' + h.toString(16)).slice(-6) + \"55\";\n}", "darker(){\n\t\tthis.addColorValue(\"red\", -30);\n\t\tthis.addColorValue(\"green\", -30);\n\t\tthis.addColorValue(\"blue\", -30);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ajoute un eveenement sans ecraser l'existant. param obj => element sur lequel appliquer l'evenement param eventType => 'click', 'dblclick', 'mouseover', 'mouseout', 'focus' ...... param fn => script ? executer
function addEventToElement(obj,eventType,fn){ if(obj.addEventListener) obj.addEventListener(eventType,fn,false); // NS6+ else if(obj.attachEvent) obj.attachEvent("on"+eventType,fn); // IE 5+ else return false; return true; }
[ "function addEvent(obj, eventType, fn){\n\n\t\tif (typeof obj === \"string\") {\n\t\t\tobj = document.getElementById(obj);\n\t\t}\n\n\t /* Written by Scott Andrew: nice one, Scott */\n\t if (eventType === \"load\") {\n\t //hack me\n\t loadEventList.addLoadEvent(fn);\n\t return true;\n\t }\n\t\tif (!obj) {\n\t\t\treturn null;\n\t\t}\n\n\t if (obj.addEventListener) {\n\t obj.addEventListener(eventType, fn, false);\n\t return true;\n\t }\n\t else\n\t if (obj.attachEvent) {\n\t var r = obj.attachEvent(\"on\" + eventType, fn);\n\t return r;\n\t }\n\t else {\n\t return false;\n\t }\n\t}", "function createObjClickFunction(obj, objId) {\n var correlationLinks = '';\n if (obj.onclick != null) {\n obj.oldfunction = obj.onclick;\n }\n if (s_omntr.prop19 && s_omntr.prop19 != '') {\n correlationLinks = ',prop19';\n }\n\n if (objId == \"addToCartBtn\") {\n correlationLinks = 'events,products,prop2,prop19,prop21,prop22,prop51' + correlationLinks;\n obj.onclick = function () {\n s_objectID = s_omntr.formatTrackingName(objId);\n s_omntr.prop21 = s_omntr.pageName;\n s_omntr.prop22 = s_omntr.channel;\n s_omntr.linkTrackVars = correlationLinks;\n s.linkTrackEvents = \"scAdd\";\n s_omntr.tl();\n obj.oldfunction ? obj.oldfunction() : true;\n return false;\n };\n } else if ($(obj).attr('data-analytics-id')) {\n correlationLinks = 'prop20,prop2,prop21,prop22,prop37,eVar37,prop38,eVar38,prop39,eVar39,prop51,prop70,prop71' + correlationLinks;\n var linkSubSection = $(obj).attr('data-analytics-pagesubsection');\n var linkContainer = $(obj).attr('data-analytics-parentcontainername');\n var linkPosition = $(obj).attr('data-analytics-position');\n if (linkSubSection == \"dashboard\") {\n linkPosition = s_omntr.currrDashPanel;\n }\n obj.onclick = function () {\n s_objectID = s_omntr.formatTrackingName(objId);\n s_omntr.prop21 = s_omntr.pageName;\n s_omntr.prop22 = s_omntr.channel;\n s_omntr.prop37 = linkSubSection;\n s_omntr.eVar37 = \"D=c37\";\n s_omntr.prop38 = linkContainer;\n s_omntr.eVar38 = \"D=c38\";\n s_omntr.prop39 = linkPosition;\n s_omntr.eVar39 = \"D=c39\";\n s_omntr.prop70 = \"D=oid\"; //clickmap oid\n s_omntr.prop71 = \"D=pid\"; //clickmap pid\n s_omntr.linkTrackVars = correlationLinks;\n s_omntr.tl(obj, 'o', s_omntr.formatTrackingName(objId), null, this.target != '_blank' ? 'navigate' : '');\n this.target == '_blank' ? window.open(this.href) : true;\n obj.oldfunction ? obj.oldfunction() : true;\n return false;\n };\n } else {\n correlationLinks = 'prop20,prop2,prop21,prop22,prop51,prop70,prop71' + correlationLinks;\n obj.onclick = function () {\n s_objectID = s_omntr.formatTrackingName(objId);\n s_omntr.prop21 = s_omntr.pageName;\n s_omntr.prop22 = s_omntr.channel;\n s_omntr.prop70 = \"D=oid\"; //clickmap oid\n s_omntr.prop71 = \"D=pid\"; //clickmap pid\n s_omntr.linkTrackVars = correlationLinks;\n s_omntr.tl(obj, 'o', s_omntr.formatTrackingName(objId), null, this.target != '_blank' ? 'navigate' : '');\n this.target == '_blank' ? window.open(this.href) : true;\n obj.oldfunction ? obj.oldfunction() : true;\n return false;\n };\n }\n }", "function addEvent(elemento,nomevento,funcion,captura)\r\n{\r\n if (elemento.attachEvent)\r\n {\r\n elemento.attachEvent('on'+nomevento,funcion);\r\n return true;\r\n }\r\n else \r\n if (elemento.addEventListener)\r\n {\r\n elemento.addEventListener(nomevento,funcion,captura);\r\n return true;\r\n }\r\n else\r\n return false;\r\n}", "function addClickListener(objectId, fce) {\r\n var object = document.getElementById(objectId);\r\n object.onclick = fce;\r\n}", "function addEvent(_elem) {\n if (p.text) {\n $(_elem)\n .off('mouseover mouseout click ', clickedEvent)\n .on('mouseover mouseout click', clickedEvent)\n .css('cursor', 'pointer');\n } else {\n $(_elem)\n .off('click', clickedEvent)\n .on('click', clickedEvent)\n .css('cursor', 'pointer');\n }\n }", "function addEvent(elemento,nomevento,funcion,captura)\n{\n if (elemento.attachEvent)\n {\n elemento.attachEvent('on'+nomevento,funcion);\n return true;\n }\n else \n if (elemento.addEventListener)\n {\n elemento.addEventListener(nomevento,funcion,captura);\n return true;\n }\n else\n return false;\n}", "function agregarEvento(elemento, nombre_evento, funcion, captura){\n // para IE\n if (elemento.attachEvent){\n elemento.attachEvent('on' + nombre_evento, funcion);\n return true;\n }else // para navegadores respetan Estándares DOM(Firefox,safari)\n if (elemento.addEventListener){\n elemento.addEventListener(nombre_evento, funcion, captura);\n return true;\n }else\n return false;\n}", "function addEvent(obj,event_name,func_name){\r\n\tif (obj.attachEvent){\r\n\t\tobj.attachEvent(\"on\"+event_name, func_name);\r\n\t}else if(obj.addEventListener){\r\n\t\tobj.addEventListener(event_name,func_name,true);\r\n\t}else{\r\n\t\tobj[\"on\"+event_name] = func_name;\r\n\t}\r\n}", "function addEvent(obj,event_name,func_name){\n if (obj.attachEvent){\n obj.attachEvent(\"on\"+event_name, func_name);\n }else if(obj.addEventListener){\n obj.addEventListener(event_name,func_name,true);\n }else{\n obj[\"on\"+event_name] = func_name;\n }\n }", "function addEvent(obj,event_name,func_name){\n\n\tif (obj.attachEvent){\n\t\tobj.attachEvent(\"on\"+event_name, func_name);\n\t}else if(obj.addEventListener){\n\t\tobj.addEventListener(event_name,func_name,true);\n\t}else{\n\t\tobj[\"on\"+event_name] = func_name;\n\t}\n}", "function addHandler(obj, type, fn) {\n 'use strict';\n if (obj && obj.addEventListener) {\n obj.addEventListener(type, fn, false);\n } else if (obj && obj.attachEvent) {\n obj.attachEvent('on' + type, fn);\n }\n}", "function addHandler(obj, type, fn) {\n 'use strict';\n if (obj && obj.addEventListener) {\n obj.addEventListener(type, fn, false);\n } else if (obj && obj.attachEvent) {\n obj.attachEvent('on' + type, fn);\n }\n}", "function addNewElement(clickObject) {\n //checking whether the element is window or not\n if (clickObject.element === window) {\n return;\n }\n\n let tag = clickObject.element.tagName;\n if (tag && (tag.toLowerCase() === \"body\" || tag.toLowerCase() === \"document\" || tag.toLowerCase() === \"window\" || tag.toLowerCase() === \"html\")) {\n return;\n }\n\n for (var i = 0; i < clickObjects.length; i++) {\n if (clickObjects[i].element === clickObject.element) {\n //todo, discuss , how better to call actions, if multiple actions should be stored, or selector better.\n return;\n }\n }\n clickObject.text = clickObject.element.innerText;\n if (clickObject.text === undefined || clickObject.text.length === 0) {\n //return;\n }\n clickObject.id = clickObjects.length;\n clickObjects.push(clickObject);\n}", "function addEvent(obj, evt, fn) {\n if (obj == document && evt == \"DOMContentLoaded\") {\n // Support adding listeners for DOMContentLoaded event\n if (document.ready) fn.apply(obj, []);\n else addEvent.listeners.push(fn);\n }\n else if (obj.addEventListener) obj.addEventListener(evt, fn, false);\n else if (obj.attachEvent)\n \tobj.attachEvent('on' + evt, obj[\"e\" + evt + fn] = function() {\n return fn.apply(obj, [addEvent.fix(window.event)]);\n \t});\n }", "function tswUtilsAddEventHandler(obj, eventName, funct)\n{\n\tif(obj.addEventListener)\n\t{\n\t\tobj.addEventListener(eventName, funct, false);\n\t}\n\telse if(obj.attachEvent)\n\t{\n\t\tobj.attachEvent('on'+eventName, funct);\n\t}\n}", "click(elemento,funzione){\r\n if(elemento.length > 0 ) {\r\n document.querySelector(elemento).addEventListener(\"click\", funzione);\r\n // document.querySelector(elemento).addEventListener(\"click\", funzione); //prendi elementi come css\r\n }else{\r\n return false;\r\n }\r\n return true;\r\n\r\n }", "function addEventToObject(oObj,sEvt,fFunc) {\n\tvar oldhandler = oObj[sEvt];\n\toObj[sEvt] = (typeof oObj[sEvt] != 'function') ? fFunc : function(){ oldhandler(); fFunc(); };\n}", "function createElements(object)\n {\n var i = 0, element, number, j, k;\n number = object.number;\n if (isNaN(number))//checking for number of instance to create of the same type pf element with the same style\n number = 0;\n for (j = 0; j <= number; j++)\n {\n element = document.createElement(object.element);\n //applying the attributes,style and eventlistener\n for (i = 2; i < Object.keys(object).length; i++) \n {\n var temp = Object.keys(object)[i];\n\n var typeproperty = typeof (object[temp]);\n if (typeproperty == \"object\" && temp != 'style' && temp != 'addEventListener')\n element[temp] = object[temp][j];\n else if (temp == 'style') \n {\n for (k in object[temp])\n element[temp][k] = object[temp][k];\n }\n else if (temp == 'addEventListener') \n {\n var event = object[temp][j][0];\n var func = object[temp][j][1];\n element[temp](event, func);\n }\n\n\n else\n element[temp] = object[temp];\n\n }\n\n var parentelement = document.getElementById(object.parentelement);\n parentelement.appendChild(element);//adding the child node to the parent\n\n }\n }", "function fireevent(oEle,strEvent, strParams)\r\n{\r\n\tswitch(strEvent)\r\n\t{\r\n\t\tcase \"click\":\r\n\t\t\tif(isIE)oEle.click(strParams)\r\n\t\t\telse oEle.onclick(strParams);\r\n\t\t\tbreak;\r\n\t\tcase \"dblclick\":\r\n\t\t\tif(isIE)oEle.dblclick(strParams)\r\n\t\t\telse oEle.ondblclick(strParams);\r\n\t\t\tbreak;\r\n\t\tcase \"mouseover\":\r\n\t\t\tif(isIE)oEle.mouseover(strParams)\r\n\t\t\telse oEle.onmouseover(strParams);\r\n\t\t\tbreak;\r\n\t\tcase \"mouseout\":\r\n\t\t\tif(isIE)oEle.mouseout(strParams)\r\n\t\t\telse oEle.onmouseout(strParams);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\talert(\"portal.control.js-fireevent : Unhandled element event(\" + strEvent + \").\")\r\n\t}\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the index of an element amongst sibling nodes of the same type
function nodeIndex(el, amongst) { if (!el) return -1; amongst = amongst || el.nodeName; var i = 0; while (el = el.previousElementSibling) { if (el.matches(amongst)) { i++; } } return i; }
[ "function siblingIndex(aNode){\n var siblings = aNode.parentNode.childNodes;\n var allCount = 0;\n var position;\n\n if (aNode.nodeType==Node.ELEMENT_NODE){\n var name = aNode.nodeName;\n for (var i=0; i<siblings.length; i++){\n var node = siblings.item(i);\n if (node.nodeType==Node.ELEMENT_NODE){\n if (node.nodeName == name) allCount++; //nodeName includes namespace\n if (node == aNode) position = allCount;\n }\n }\n }\n else if (aNode.nodeType==Node.TEXT_NODE){\n for (var i=0; i<siblings.length; i++){\n var node = siblings.item(i);\n if (node.nodeType==Node.TEXT_NODE){\n allCount++;\n if (node == aNode) position = allCount;\n }\n }\n }\n if (allCount>1) return position;\n return null\n}", "function siblingIndex(aNode){\n\t\tvar siblings = aNode.parentNode.childNodes;\n\t\tvar allCount = 0;\n\t\tvar position;\n\n\t\tif (aNode.nodeType==1){ //Node.ELEMENT_NODE\n\t\t\tvar name = aNode.nodeName;\n\t\t\tfor (var i=0; i<siblings.length; i++){\n\t\t\t\tvar node = siblings.item(i);\n\t\t\t\tif (node.nodeType==1){ //Node.ELEMENT_NODE\n\t\t\t\t\tif (node.nodeName == name) allCount++; //nodeName includes namespace\n\t\t\t\t\tif (node == aNode) position = allCount;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (aNode.nodeType==3){ //Node.TEXT_NODE\n\t\t\tfor (var i=0; i<siblings.length; i++){\n\t\t\t\tvar node = siblings.item(i);\n\t\t\t\tif (node.nodeType==3){ //Node.TEXT_NODE\n\t\t\t\t\tallCount++;\n\t\t\t\t\tif (node == aNode) position = allCount;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (allCount>1) return position;\n\t}", "function getNodeIndex( elm ){\n var c = elm.parentNode.children, i = 0;\n for(; i < c.length; i++ )\n if( c[i] == elm ) return i;\n }", "function getNodeIndex( elm ){\n var c = elm.parentNode.children, i = 0;\n for(; i < c.length; i++ )\n if( c[i] == elm ) return i;\n }", "function getIndexOfType(element) {\n var index = 0;\n var child = void 0;\n while (child = element.previousElementSibling) {\n if (child.tagName === element.tagName) {\n index++;\n }\n }\n return index;\n }", "function getIndex(element) {\n\treturn Array.prototype.indexOf.call(element.parentNode.children, element);\n}", "function getIndex(node) {\n let children = node.parentNode.children;\n let index;\n for (let i = 0; i < children.length; i++) {\n if (node === children[i]) index = i;\n }\n return index;\n}", "function get_index_of_el(el) {\n for (var i = 0, len = children_num; i < len; i++) {\n if (self.el.children[i] == el) {\n return i;\n }\n }\n }", "function getIndexOfType(element) {\n let index = 0;\n let child;\n while ((child = element.previousElementSibling)) {\n if (child.tagName === element.tagName) {\n index++;\n }\n }\n return index;\n }", "function indexInParent(node) {\n var children = node.parentNode.childNodes;\n var num = 0;\n for (var i = 0; i < children.length; i++) {\n if (children[i] == node) return num;\n if (children[i].nodeType == 1) num++;\n }\n return -1;\n}", "function getIndex(node) {\n var i = 0\n node = $(node);\n while(node.length != 0){\n node = $(node).prev();\n i++;\n }\n return i - 1;\n }", "function get_element_index(elem)\n\t\t{\n\t\t\tvar elements = doc.getElementsByTagName(elem.nodeName);\n\t\t\tfor (var i = 0; i < elements.length; i++) {\n\t\t\t\tif (elements[i] == n)\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t}", "function get_child_index(child) {\n cs = child.parentElement.children// get all the siblings to the child\n index = undefined//declare the index and set it to undefined\n for(c in cs){// loop through all the children until we find a child that is equal to the child\n tar = cs[c]\n if(tar == child){\n index = c;\n break;\n }\n }\n\n return index\n}", "function get_child_index(child) {\n cs = child.parentElement.children// get all the siblings to the child\n index = undefined//declare the index and set it to undefined\n for(c in cs){// loop through all the children until we find a child that is equal to the child\n tar = cs[c]\n if(tar == child){\n index = c;\n break;\n }\n }\n\n return parseInt(index)\n}", "childIndex(node, parentNode) {\n let seen = 0\n for (const e of this.getEdges()) {\n const [src, dst] = e\n if (src == parentNode) {\n if (dst == node) return seen\n seen++\n }\n }\n return -1;\n }", "function parentIndex(element) {\r\n\tvar i = 0;\r\n\twhile ((element = element.previousSibling) != null) {\r\n\t\ti++;\r\n\t}\r\n\treturn i;\r\n}", "function index(parentNode, reverse, ofType) {\n parentNode._countedByFuse = Fuse.emptyFunction;\n var node, nodes = parentNode.childNodes, nodeIndex = 1;\n if (reverse) {\n var length = nodes.length;\n while (length--) {\n node = nodes[length];\n if (node.nodeType == 1 && (!ofType || typeof node._countedByFuse !== 'undefined'))\n node.nodeIndex = nodeIndex++;\n }\n } else {\n for (var i = 0; node = nodes[i++]; )\n if (node.nodeType == 1 && (!ofType || typeof node._countedByFuse !== 'undefined'))\n node.nodeIndex = nodeIndex++;\n }\n }", "_getChildNodeIndex(child, selector) {\n\n\t\t\tlet index = 0;\n\t\t\twhile(child.previousSibling) {\n\t\t\t\tif (child.previousSibling.matches(selector)) index++;\n\t\t\t\tchild = child.previousSibling;\n\t\t\t}\n\t\t\treturn index;\n\n\t\t}", "function getNodeIndex(evt) {\n const {\n nativeEvent: {pageX, pageY}\n } = evt;\n const target = document.elementFromPoint(pageX, pageY);\n if (!target) {\n return -1;\n }\n const {parentNode} = target;\n return Array.prototype.indexOf.call(parentNode.childNodes, target);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reset counter and score
function resetCounter() { score = 0; questionNum = 1; $('.score').text(0); $('.questionCounter').text(0); console.log('reset counter processed'); }
[ "function resetScore() {\r\n score = 0;\r\n}", "function resetScore() {\n score = 0;\n}", "function totalScoreReset(){\n totalScore = 0;\n }", "resetScore() {\n this.score = INITIAL_SCORE;\n }", "function resetScore() {\n scoreValues = _getEmptyScore();\n _saveScoreValues();\n }", "function clearScore() {\n score = 0;\n }", "resetScore() {\n this.score.value = 0;\n }", "function resetStats() {\n score = 0;\n questionNumber = 0;\n $('.score').text(0);\n $('.questionNumber').text(0);\n }", "function resetScore2() {\n score2 = 0;\n}", "function reset(){\n score=0;\n gameTime=0;\n updateScore();\n}", "function resetScores() {\n humanScore = 0;\n computerScore = 0;\n }", "function resetCounters(){\n correct = 0;\n incorrect = 0;\n unanswered = 0;\n }", "function resetCounters()\n{\n\t//reset questionCounter and counterCorrectAnswers\n\tquestionCounter = 0;\n\tcounterCorrectAnswers = 0;\n}", "function reset() {\n currentScore = 0;\n $(\"#currentScore\").text(\"Current Score: \" + currentScore);\n bluePoints = 0;\n greenPoints = 0;\n redPoints = 0;\n orangePoints = 0;\n }", "clearScore() {\n\t\tthis.roundScore = 0;\n\t}", "function resetScore() {\n $('#wins').text(0);\n $('#losses').text(0);\n }", "function clearScore() {\n playerScore = 0;\n computerScore = 0;\n}", "function restartScore(){\n score = 0;\n}", "function reset() {\n score = 0;\n\n gameDuration = 0;\n gameSecElapsed = 0;\n gameInterval;\n\n questionDuration = 15;\n questionSecElapsed = 0;\n questionInterval;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the most recently saved opinion for a user/topic
function getOpinionByUserTopic (userId, topicId) { return cq.query(qb.opinionDraftByUserTopic(userId, topicId)) .then(transformer.opinion) .then(opinion => opinion || models.opinion); }
[ "function requeryMostOverdueTopic() {\n store\n .dispatch('fetchFromStorage', 'topics')\n .then(() => {\n const topics = store.getters.topics;\n const overdueTopics = topics.filter(topic => {\n let isOverdue = false; // default to not overedue\n if (topic.custom.enabled) {\n const interval = topic.custom.qInterval;\n const lastRequest = topic.custom.qLastRequest;\n const nextQuery = lastRequest + interval * 60 * 1000;\n isOverdue = nextQuery < Date.now();\n }\n return isOverdue;\n });\n\n if (overdueTopics.length === 0) return; // nothing to do get out\n overdueTopics.sort(function(a, b) {\n return a.custom.qLastRequest - b.custom.qLastRequest;\n });\n utils.reQueryById(store, overdueTopics[0].id);\n // utils.logMsg({\n // \"overdue topic id\": overdueTopics[0].id,\n // \"overdue topic name\": overdueTopics[0].captured.name,\n // })\n })\n .catch(err => { utils.logErr(err); });\n}", "function latest() {\n var defer = $q.defer();\n scoreAnswers($http, $q).collection()\n .then(function(res) {\n defer.resolve(res[res.length-1]);\n });\n return defer.promise;\n }", "function whoIsFollowedMost() {}", "function getLatestRecommendation(userData1) {\n var latestRec = userData.Recommendation.filter(\n (value) => Object.keys(value).length !== 0\n ).slice(-1)[0];\n if (latestRec == null || latestRec.HIITCurrentCardioSession == null) {\n return null;\n } else if (latestRec.ModifiedDate) {\n return latestRec;\n } else {\n return null;\n }\n}", "function tellLatestTip (app) {\n db.collection(FirestoreNames.TIPS)\n .orderBy(FirestoreNames.CREATED_AT, 'desc')\n .limit(1)\n .get()\n .then(function (querySnapshot) {\n const tip = querySnapshot.docs[0];\n const screenOutput = app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT);\n if (!screenOutput) {\n return app.tell(tip.get(FirestoreNames.TIP));\n }\n const card = app.buildBasicCard(tip.get(FirestoreNames.TIP))\n .addButton('Learn More!', tip.get(FirestoreNames.URL));\n const richResponse = app.buildRichResponse()\n .addSimpleResponse(tip.get(FirestoreNames.TIP))\n .addBasicCard(card);\n /**\n * We ask only once to show that this should be limited to avoid annoying the user.\n * In a real world app you want to be more sophisticated about this, for example\n * re-ask after a certain period of time or number of interactions.\n */\n if (!app.userStorage[PUSH_NOTIFICATION_ASKED]) {\n richResponse.addSuggestions('Alert me of new tips');\n app.userStorage[PUSH_NOTIFICATION_ASKED] = true;\n }\n app.ask(richResponse);\n }).catch(function (error) {\n throw new Error(error);\n });\n }", "async mostLiked() {\n return await this.redisClient.zrevrange(keyBuilder.mostLiked(), 0, -1);\n }", "get mostActiveUser() {\n }", "function getTopTodo() {\n let topTodo = todos.reduce((acc, cur) => {\n if (Object.keys(acc).length === 0) {\n acc = cur;\n }\n if (cur.priority < acc.priority) {\n acc = cur;\n }\n return acc;\n }, {});\n console.log(topTodo);\n return topTodo;\n }", "function getTopInfo() {\n\t\t\tvar reply = articleFactory.getLatestInfo();\n\t\t\treply.then(function (response) {\n\t\t\t\tif (response.data.mostViewed && response.data.latest) {\n\t\t\t\t\tvm.topViews = response.data.mostViewed;\n\t\t\t\t\tvm.recent = response.data.latest;\n\t\t\t\t}\n\t\t\t});\n\t\t}", "function getTopScore(correctAnswers){\n return sessionStorage.getItem(\"topScore\");\n}", "function getHighestScore() {\n return window.localStorage.getItem(\"memory-app-time\");\n // console.log(\"best time: \", bestTime);\n}", "function getMostPopularFood() {\n return rest.one(\"popularfood\").get();\n }", "async getMostRecentUserLoc() {\n const locData = this.getLocationData();\n return locData[locData.length - 1];\n }", "async getLatest() {\n const result = await this.ctx.model.TrainScheduleUser.findOne({\n order: [[\"CreateTime\", 'DESC']]\n });\n return result;\n }", "function latestAnnouncement() {\n return Announcement.findOne()\n .sort({timestamp:-1})\n .populate({ path: 'sender', select: ['username', 'displayname'] })\n .exec();\n}", "getMostRecentDoc(uploadedAppraisalDocs) {\n try {\n return uploadedAppraisalDocs.slice(-1).get(0);\n } catch (e) {\n return null;\n }\n }", "async getMostRecentUserLoc() {\n const locData = await this.getLocationData();\n return locData[locData.length - 1];\n }", "async getLatest() {\n const result = await this.ctx.model.SysUserDutyRoster.findOne({\n order: [[\"CreateTime\", 'DESC']]\n });\n return result;\n }", "function getRecentlyAccessed(){\n\t\tif (__token) {\n\t\t\treturn $http(__host+'/recentlyaccessedbyme')\n\t\t\t\t.get();\n\t\t} else {\n\t\t\tthrow __noTokenIsSetError;\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function _hiLightBottomOfSebTree(eTR) this function hilights the last node on a sub tree, internal use only
function _hiLightBottomOfSebTree(eTR) { var eTBody=eTR.cells(1).firstChild.firstChild; var eTRBottom=eTBody.rows(eTBody.rows.length-1); if(eTRBottom.style.display !='none') _hiLightBottomOfSebTree(eTRBottom); else eTBody.rows(eTBody.rows.length-2).cells(1).fireEvent("onclick"); }
[ "function _hiLightTopOfSebTree(eTR)\n\t{\n\t\tvar eTBody=eTR.cells(1).firstChild.firstChild;\n\t\teTBody.rows(0).cells(1).fireEvent(\"onclick\");\n\t}", "function hiLightDown(currentElement)\n\t{\n\t\tvar eTR=currentElement.parentNode;\n\t\t\n\t\tif(eTR.tagName != \"TR\")\n\t\t\treturn;\n\t\n\t\tvar nRowIndex=eTR.rowIndex;\n\t\tvar nTotalRows=eTR.parentNode.rows.length;\n\t\tvar bJumpOutOfSubTree=false;\n\t\t\n\t\tif(nRowIndex%2!=0)\n\t\t{\n\t\t\tif(nRowIndex+1 <= nTotalRows-1)\n\t\t\t\teTR.parentNode.rows(nRowIndex+1).cells(1).fireEvent(\"onclick\");\n\t\t\telse\n\t\t\t\tbJumpOutOfSubTree=true;\t\n\t\t}\t\t\n\t\telse\n\t\t{\n\t\t\tif( (nRowIndex < nTotalRows-1) && (eTR.parentNode.rows(nRowIndex+1).style.display !='none'))\n\t\t\t\t_hiLightTopOfSebTree(eTR.parentNode.rows(nRowIndex+1));\n\t\t\telse if (nRowIndex < nTotalRows-2)\n\t\t\t\t\teTR.parentNode.rows(nRowIndex+2).cells(1).fireEvent(\"onclick\");\n\t\t\telse\n\t\t\t\tbJumpOutOfSubTree=true;\t\t\t\n\t\t}\t\n\t\n\t\tif(bJumpOutOfSubTree)\n\t\t{\n\t\t\tvar eTD=eTR.parentNode.parentNode.parentNode;\n\t\t\thiLightDown(eTD);\n\t\t}\n\t}", "function lastTree() {\n hideAllWindows();\n if (currentTreeIndex != treesArray.length - 1) {\n moveToTreeHelper(treesArray.length-1);\n }\n}", "function hiLightUp(currentElement)\n\t{\n\t\tvar eTR=currentElement.parentNode;\n\t\tif(eTR.TMB=='top')\n\t\t\treturn;\n\t\t\n\t\tvar nRowIndex=eTR.rowIndex;\n\t\n\t\tif(nRowIndex>=1)\n\t\t{\t\n\t\t\tif(nRowIndex%2!=0)\n\t\t\t\teTR.parentNode.rows(nRowIndex-1).cells(1).fireEvent(\"onclick\");\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(eTR.parentNode.rows(nRowIndex-1).style.display !='none')\n\t\t\t\t\t_hiLightBottomOfSebTree(eTR.parentNode.rows(nRowIndex-1));\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\teTR.parentNode.rows(nRowIndex-2).cells(1).fireEvent(\"onclick\");\n\t\t\t}\n\t\t}\t\n\t\telse\n\t\t{\n\t\t\tvar eTD=eTR.parentNode.parentNode.parentNode;\n\t\t\thiLightUp(eTD);\n\t\t}\n\t}", "function hdBottomView(root){\n\n //plan\n // do a breath first search\n // keep and object of each lowest node at each horizontal distance \n // update object as the tree is traversed\n\n}", "function getLastLeaf(node) {\n while (node.lastChild && getSelectionOffsetKeyForNode(node.lastChild)) {\n node = node.lastChild;\n }\n return node;\n }", "function getLastLeaf(node) {\r\n for (;node.lastChild && getSelectionOffsetKeyForNode(node.lastChild); ) node = node.lastChild;\r\n return node;\r\n }", "function getLastLeaf(node) {\n for (;node.lastChild && getSelectionOffsetKeyForNode(node.lastChild); ) node = node.lastChild;\n return node;\n }", "function getLastLeaf(node) {\n while (node.lastChild && getSelectionOffsetKeyForNode(node.lastChild)) {\n node = node.lastChild;\n }\n return node;\n}", "lastIn(b) { return this.#bsf.lastLeaf(b); }", "function boustrophedon(biTree){\n //plan\n // traverse tree in bousrophedon order\n\n}", "function fixLeafNodes(g){\r\n\r\n}", "function highLight(espan) {\n\tespan.className = \"highlightedNorloge\";\n\tif (espan.tolight != null) {\n\t\tvar indexNorl = getNorlogeIndex(espan.timeValue);\n\t\tfor (var i=0;i<espan.tolight.length;i++) {\n\t\t\tvar elem = espan.tolight[i];\n\t\t\tif (elem == null) continue;\n\t\t\tif (elem.parentElem.className == \"boardleftmsg\" && \n\t\t\t espan.parentElem.className != \"boardleftmsg\") {\n\t\t\t\tif (indexNorl != null) {\n\t\t\t\t\tvar velem = elem;\n\t\t\t\t\twhile (velem.nextt != null)\n\t\t\t\t\t\tvelem = velem.nextt;\n\t\t\t\t\tfor (var j = 1;j<indexNorl;j++) {\n\t\t\t\t\t\tvelem = velem.old;\n\t\t\t\t\t\tif (velem == null) break;\n\t\t\t\t\t}\n\t\t\t\t\tif (velem != elem) {\n\t\t\t\t\t\tespan.tolight[i] = null;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar boardrightmsg = elem.parentElem.nextElem;\n\t\t\t\t//boardrightmsg.style.backgroundColor = \"#8B9BBA\";\n\t\t\t\tboardrightmsg.firstChild.className = \"highlightedNorloge\";\n\t\t\t}\n\t\t\tif (elem != espan)\n\t\t\t\t{\n\t\t\t\t//elem.style.backgroundColor = \"#8B9BBA\";\n\t\t\t\telem.className = \"highlightedNorloge\";\n\t\t\t\t}\n\t\t}\n\t}\n}", "function toggle_leaf(d) {\n\tif (d._leaf){\n\t\td._leaf = false;\n\t} else {\n\t\td._leaf = true;\n\t}\n}", "function tightTree(t,g){function dfs(v){_.forEach(g.nodeEdges(v),function(e){var edgeV=e.v,w=v===edgeV?e.w:edgeV;if(!t.hasNode(w)&&!slack(g,e)){t.setNode(w,{});t.setEdge(v,w,{});dfs(w)}})}_.forEach(t.nodes(),dfs);return t.nodeCount()}", "MarkAsLastVisitedChild() {\n var parent = this.GetParent();\n if (parent) {\n parent.SetLastVisitedChild(this);\n }\n }", "function TreeNode_getLastLeaf() {\n if (debug) alert(\"TreeNode@\"+this.identifier+\".getLastLeaf()\");\n\tvar node = this;\n\n\twhile (! node.isLeaf()) {\n\t\tnode = node.getLastChild();\n\t}\n\n\treturn node;\n}", "function getLastLeaf(node) {\n while (node.lastChild && (\n // data-blocks has no offset\n node.lastChild instanceof Element && node.lastChild.getAttribute('data-blocks') === 'true' || getSelectionOffsetKeyForNode(node.lastChild))) {\n node = node.lastChild;\n }\n return node;\n}", "clearLeaf() {\n this.isWordEnd = false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recieve and add message to array
function addmessagestoarray(data) { if (filteredmessages.length !== 0) { messagestore = filteredmessages } messagestore.push(data) setchats([messagestore]) scrollmessages(); }
[ "function appendReceived(msg) {\n console.log([\"chat:appendReceived\"]);\n\n x = that.messages.shift(); // pop the oldest off the front\n that.messages.push('<i>' + msg + '</i><br>');\n\n console.log([\"chat:appendReceived2\"]);\n notifyUpdate(true);\n }", "_newMessage(message) {\n this.messages.push(message);\n this.emitChange();\n }", "function addMessage(username, msg, room){\n let time = moment().format('h:mm a');\n let message = {user:username, text:msg, time, room};\n // Check array message length\n // console.log(messagesArr.length)\n if(messagesArr.length > 1000){\n messagesArr.length = 0;\n messagesArr.push(message);\n return messagesArr\n }\n messagesArr.push(message);\n // console.log(messagesArr)\n return messagesArr\n}", "recieve(msg) {\n cues = msg.cues;\n }", "push(message){\n assert(is_valid_message(message));\n\n let new_message_id = this.__new_message_id();\n message.msg_id = new_message_id;\n\n this.messages_to_send.push(message);\n }", "addMsg(index) {\n if (this.msgUtente.length > 0) {\n this.contacts[index].messages.push({\n text: this.msgUtente,\n status: \"sent\",\n date: dayjs().format(\"DD/MM/YYYY HH:mm:ss\"),\n });\n this.msgUtente = \"\";\n // imposto un messaggio standard con status received che compare dopo 1 secondo\n setTimeout(() => {\n this.contacts[index].messages.push({\n text: this.risposte[\n Math.floor(Math.random() * this.risposte.length)\n ],\n status: \"received\",\n date: dayjs().format(\"DD/MM/YYYY HH:mm:ss\"),\n });\n }, 1000);\n }\n }", "function appendSent(msg) {\n x = that.messages.shift(); // pop the oldest off the front\n that.messages.push(msg + '<br>');\n notifyUpdate(false);\n }", "addMessage(message) {\n //PESAN YANG DITERIMA AKAN DITAMBAHKAN KE VARIABLE MESSAGE\n this.messages.push(message);\n\n //KEMUDIAN AKAN DISIMPAN KE DATABASE SEBAGAI LOG\n axios.post('/messages', message).then(response => {\n console.log(response.data);\n });\n }", "addCustomMessage(message){\n this.currentMessages.push(message);\n }", "inviaMessaggio(){\n if(this.messaggioInputUtente != ''){\n this.contacts[this.contattoAttivo].messages.push({\n date: dayjs().format('YYYY/MM/DD HH:MM:SS'),\n text: this.messaggioInputUtente,\n status: 'sent',\n stileMessaggio: 'message-sent'});\n this.messaggioInputUtente = '';\n setTimeout(()=>{\n this.contacts[this.contattoAttivo].messages.push({\n date: dayjs().format('YYYY/MM/DD HH:MM:SS'),\n text: 'ok',\n status: 'received',\n stileMessaggio: 'message-received'});\n }, 1000);\n }\n }", "handleNewMessage(data) {\n const msg = data.message\n this.webContents.send(\"msg-res\", {\n type: \"add\",\n id: msg._id,\n content: this.crypto.decryptContent(msg.content),\n to: msg.to,\n from: msg.from\n })\n }", "function insMsgArray(insnick, insdata, instime) {\n // limitamos mensajes guardados a 20\n if (mensajes.length == 20 ) {\n mensajes.splice(0, 1);\n };\n var arraymsg = new Array();\n arraymsg[0] = insnick;\n arraymsg[1] = insdata;\n arraymsg[2] = instime;\n mensajes.push(arraymsg);\n}", "[NEW_MESSAGE] (state, msg) {\n state.items.push(msg)\n }", "addMessage(str) {\n this.messages.push(str);\n }", "function subscribe() {\r\n var message = document.getElementById('message');\r\n var channel = document.getElementById('channel').value;\r\n var host = window.document.location.host.replace(/:.*/, '');\r\n var ws = new WebSocket('ws://' + host + ':8080');\r\n ws.onopen = function () {\r\n ws.send(JSON.stringify({\r\n request: 'SUBSCRIBE',\r\n message: '',\r\n channel: channel\r\n }));\r\n ws.onmessage = function(event){\r\n data = JSON.parse(event.data); \r\n messageAja.push(data.message); //push ke array\r\n message.innerHTML = messageAja; //display ke array\r\n };\r\n }; \r\n}", "function onMessage(event) {\n \n var messageFromServer = JSON.parse(event.data);\n \n if(messageFromServer.action === \"someOneIsTyping\") {\n processSomeOneIsTyping(messageFromServer);\n }\n \n if (messageFromServer.action === \"receiveMessage\") { \n processReceivedMsg(messageFromServer);\n }\n \n if(messageFromServer.action === \"recieveNewUser\") {\n processNewAddedUser(messageFromServer);\n }\n \n if(messageFromServer.action === \"showFailedToAddUserMsg\") {\n processFailedToAddUser(messageFromServer);\n }\n \n if(messageFromServer.action === \"userDeleted\") {\n processRemovedUser(messageFromServer);\n }\n \n if(messageFromServer.action === \"appendSentMessage\") {\n //var messageText = messageFromServer.messageText;\n appendMessage(messageFromServer);\n }\n \n if (messageFromServer[0].action === \"processSenders\") { \n var receivedArrOfSenders = []\n receivedArrOfSenders = messageFromServer;\n processReceivedSenders(receivedArrOfSenders);\n }\n \n}", "updateReceivedMessage() {\n var message = [];\n if (this.level.packetsHaveNumbers) {\n for (var j=0; j < this.level.message.length; j++) {\n message.push('');\n }\n }\n var packet;\n for (var i=0; i < this.receivedPackets.length; i++) {\n packet = this.receivedPackets[i];\n if (this.level.packetsHaveNumbers) {\n if (packet.isCorrupt) {\n if (message[packet.number] == '') {\n // We don't want to overwrite good data\n message[packet.number] = '?';\n }\n } else {\n message[packet.number] = packet.char;\n }\n } else {\n if (packet.isCorrupt) {\n message.push('?');\n } else {\n message.push(packet.char);\n }\n }\n }\n message = message.join('');\n this.receivedMessage = message;\n this.registry.set('receivedMessage', message);\n }", "sendNewMessages () {\n if (this.socket) {\n const serializeJobs = this.messages.map(message => message.toTransferObject())\n Promise.all(serializeJobs)\n .then(serializedMessages => {\n this.socket.emit('messages', {\n hasMessages: this.hasMessages(),\n messages: serializedMessages\n })\n })\n .catch(e => console.error('Failed to send new messages: ', e))\n }\n }", "_onMessage(topicUint8Array, messageUint8Array) {\n const topic = topicUint8Array.toString();\n let message\n if (messageUint8Array.length > 0) {\n message = JSON.parse(messageUint8Array.toString());\n } else {\n message = undefined;\n }\n \n if (this._watches.has(topic)) {\n const subscription = this._watches.get(topic);\n subscription.lastValue = message;\n for (const callback of subscription.callbacks) {\n callback(topic, message);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates, or attempts to evaluate, a BooleanLiteral
function evaluateBooleanLiteral({ node, typescript }) { return node.kind === typescript.SyntaxKind.TrueKeyword; }
[ "function BooleanLiteralExpression() {\n}", "eval_bool(input) {\n const rs = this.evaluate(input);\n return (rs && rs.length === 1 && rs[0] === true)\n }", "BooleanLiteral(value) {\n this._eat(value ? 'true' : 'false');\n return {\n type: 'BooleanLiteral',\n value,\n };\n }", "function evalBoolean(string) {\n return (string.toLowerCase() === 'true');\n}", "function truthyEval(str) {\n checkGlobals();\n return truthyCall(function() { return eval(str); });\n }", "function BooleanValue() {}", "boolean_expr() {\n const startToken = this.currentToken;\n\n // boolean_expr : boolean_term ((AND | OR | XOR) boolean_term)*\n try {\n return this.binaryProduction(this.expr, OperatorsBooleanExpr);\n } catch (e) {\n throw new ParserException('Error processing BOOLEAN_EXPR', startToken, e);\n }\n }", "function evaluateTemplateExpression(expr, valueFunction = (() => null)) {\n\tif (expr == \"_TRUE_\")\n\t\treturn true;\n\n\tif (expr == \"_FALSE_\")\n\t\treturn false;\n\n\treturn evaluateTemplateExpressionConstant(expr.replace(\n\t\t//\tBrackets.\n\t\t/\\s*\\[\\s*(.+?)\\s*\\]\\s*/g,\n\t\t(match, bracketedExpr) =>\n\t\t(evaluateTemplateExpression(bracketedExpr, valueFunction)\n\t\t ? \"_TRUE_\"\n\t\t : \"_FALSE_\")\n\t).replace(\n\t\t//\tBoolean AND, OR.\n\t\t/^\\s*([^&|]+?)\\s*([&|])\\s*(.+?)\\s*$/,\n\t\t(match, leftOperand, operator, rightOperand) => {\n\t\t\tlet leftOperandTrue = evaluateTemplateExpression(leftOperand, valueFunction);\n\t\t\tlet rightOperandTrue = evaluateTemplateExpression(rightOperand, valueFunction);\n\t\t\tlet expressionTrue = operator == \"&\"\n\t\t\t\t\t\t\t\t ? (leftOperandTrue && rightOperandTrue)\n\t\t\t\t\t\t\t\t : (leftOperandTrue || rightOperandTrue);\n\t\t\treturn expressionTrue ? \"_TRUE_\" : \"_FALSE_\";\n\t\t}\n\t).replace(\n\t\t//\tBoolean NOT.\n\t\t/^\\s*!\\s*(.+?)\\s*$/,\n\t\t(match, operand) =>\n\t\t(evaluateTemplateExpression(operand, valueFunction)\n\t\t ? \"_FALSE_\"\n\t\t : \"_TRUE_\")\n\t).replace(/^\\s*(.+)\\s*$/g,\n\t\t(match, fieldName) =>\n\t\t(/^_(.*)_$/.test(fieldName)\n\t\t ? fieldName\n\t\t : (valueFunction(fieldName) == null\n\t\t\t? \"_FALSE_\"\n\t\t\t: \"_TRUE_\"))\n\t));\n}", "get boolean() {\n this.eval(\n this.is('boolean', this.firstOperand),\n 'Variable is not a type \\'boolean\\'', \n 'Variable is a type \\'boolean\\''\n );\n return this;\n }", "function isBooleanLiteral(node, typescript) {\n return node.kind === typescript.SyntaxKind.TrueKeyword || node.kind === typescript.SyntaxKind.FalseKeyword;\n}", "function toBoolean() {\n return operator_1.or(stringToBoolean(), finiteNumberToBoolean());\n}", "function isTrue(val) {\n return(val);\n}", "function evalBoolExpr(node, sTable) {\n Log.GenMsg(\"Evaulating Bool_Expr...\");\n let expr1 = node.children[0];\n let boolOp = node.children[1];\n let expr2 = node.children[2];\n let addr = null;\n let addr2 = null;\n if (expr1.name === \"BOOL_EXPR\") {\n addr = evalStoreBool(expr1, sTable);\n }\n if (expr2.name === \"BOOL_EXPR\") {\n addr2 = evalStoreBool(expr2, sTable);\n }\n //Check there are no strings literals in expression\n //TODO: Implement string literal comparison\n /*\n if (expr1.name === \"CHARLIST\" || expr2.name === \"CHARLIST\") {\n throw error(\"String literals comparison not currently supported.\");\n }\n */\n if (addr === null && addr2 === null) {\n //No nested boolExpr, carry on as usual\n if (/^[0-9]$/.test(expr1.name)) {\n loadX(expr1, sTable);\n addr = getSetMem(expr2, sTable);\n }\n else {\n addr = getSetMem(expr1, sTable);\n loadX(expr2, sTable);\n }\n }\n else {\n if (addr === null) {\n //Expr1 is not a boolExpr, load its value into X\n loadX(expr1, sTable);\n if (addr2 === null) {\n addr = getSetMem(expr2, sTable);\n }\n else {\n addr = addr2;\n }\n }\n else {\n if (addr2 === null) {\n //Expr1 is a BoolExpr, but not Expr2\n loadX(expr2, sTable);\n }\n else {\n //Both Exprs are BoolExprs\n //Load result of second BoolExpr into X from memory\n byteCode.push(\"AE\", addr2[0], addr2[1]);\n }\n //Allow result of sub-boolean expressions to be overwrriten\n memManager.allowOverwrite(addr);\n }\n //Allow result of sub-boolean expressions to be overwrriten\n memManager.allowOverwrite(addr2);\n }\n //Compare X and memory location, setting Z with answer\n byteCode.push(\"EC\", addr[0], addr[1]);\n //Return if the boolOperation was \"equals\" (otherwise \"not equals\")\n return boolOp.name === \"==\";\n }", "visitBooleanLiteral(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_boolval() {\n tree.addNode('boolval', 'branch');\n if (foundTokensCopy[parseCounter][1] == 'false') {\n match('false', parseCounter);\n parseCounter++;\n } else if (foundTokensCopy[parseCounter][1] == 'true') {\n match('true', parseCounter);\n parseCounter++;\n }\n tree.endChildren();\n}", "function evaluateTruthy() {\n var res = this.evaluate();\n if (res.confident) return !!res.value;\n}", "function _BooleanLiteralExpressionEmitter() {\n}", "static isBooleanLiteral(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.FalseKeyword:\r\n case typescript_1.SyntaxKind.TrueKeyword:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }", "parseSimpleBooleanExpression(tokens) {\n const lhs = tokens.shift()\n const lhNode = this.parseBooleanVal(lhs)\n if (tokens.length === 0) {\n return lhNode\n }\n let op = tokens[0]\n switch (op.val) {\n case '==': {\n tokens.shift()\n const rhNode = this.parseBooleanVal(tokens.shift())\n return new EqualsNode(lhNode, rhNode)\n }\n case '!=': {\n tokens.shift()\n const rhNode = this.parseBooleanVal(tokens.shift())\n return new NotEqualsNode(lhNode, rhNode)\n }\n case 'exists': {\n tokens.shift()\n return new NotEqualsNode(lhNode, new VariableNode('undefined'))\n }\n default:\n // Note that a \"boolean expression\" may be simply a string literal, number, or variable, since we expose\n // JavaScript's native boolean punning\n return lhs\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
draw ascending diagonal lines in reference to center point
function diagonalAscending(x, y, s) { line(x - s / 2, y + s / 2, x + s / 2, y - s / 2); }
[ "function drawDiagonal (lineCount) {\n // how many lines?\n for (let i = 1; i <= lineCount; i++) {\n // for each line\n if (i === 1 || i === lineCount) {\n console.log(drawOneline(lineCount));\n } else {\n console.log(drawDiagonalBorder(lineCount, i));\n }\n }\n}", "function diagPrincAbs() {\n for (i = 0; i < nrLines; i++) {\n for ( j= 0; j < nrCols; j++) {\n\n xpos = (elemWidth + hDist) * j;\n ypos = (elemHeight + vDist) * i;\n\n if (i == j) {\n eachElem = drawElemAbs(\"culoareBlue\", i, j);\n } \n else {\n eachElem = drawElemAbs(\"culoareVerde\", i, j);\n }\n\n eachElem.style.top = ypos + \"px\";\n eachElem.style.left = xpos + \"px\";\n }\n }\n }", "_setDiagonal () {\n this._diagonal = d3.svg.diagonal().projection((d) => {\n return [d.y, d.x];\n });\n }", "function diagonal(d, i) {\n var source = {\n x: d.source.x,\n y: d.source.y + NODE_WIDTH\n };\n var target = {\n x: d.target.x,\n y: d.target.y - 20\n };\n var p0 = {\n x: source.y,\n y: source.x\n };\n var p3 = {\n x: (source.y + NODE_WIDTH) < target.y ? (source.y + NODE_WIDTH) : target.y,\n y: target.x\n };\n var p4 = {\n x: target.y,\n y: target.x\n };\n var k = (p0.x + p3.x) / 2;\n var p = [p0, {\n x: k,\n y: p0.y\n }, {\n x: k,\n y: p3.y\n }, p3, p4];\n return \"M\" + p[0].x + \",\" + p[0].y + \"C\" + p[1].x + \",\" + p[1].y + \" \" + p[2].x + \",\" + p[2].y + \" \" + p[3].x + \",\" + p[3].y + \"L\" + p[4].x + \",\" + p[4].y;\n }", "function overDiagPrincAbs() {\n for (i = 0; i < nrLines; i++) {\n for ( j= 0; j < nrCols; j++) {\n\n xpos = (elemWidth + hDist) * j;\n ypos = (elemHeight + vDist) * i;\n\n if (j>i) {\n eachElem = drawElemAbs(\"culoareBlue\", i, j);\n } \n else {\n eachElem = drawElemAbs(\"culoareVerde\", i, j);\n }\n\n eachElem.style.top = ypos + \"px\";\n eachElem.style.left = xpos + \"px\";\n }\n }\n }", "function drawOtherHorizontalLines() {\n ctx.strokeStyle = `#a9a9a9`;\n ctx.beginPath();\n for (let i = 0; i < 400; i += 40) {\n ctx.moveTo(0, i);\n ctx.lineTo(400, i);\n }\n ctx.stroke();\n}", "function drawLineWithArrows(x0, y0,x1,y1,aWidth,aLength,arrowStart,arrowEnd){\n var dx=x1-x0;\n var dy=y1-y0;\n var angle=Math.atan2(dy,dx);\n var length=Math.sqrt(dx*dx+dy*dy);\n \n ctx.translate(x0,y0);\n ctx.rotate(angle);\n ctx.beginPath();\n ctx.moveTo(0,0);\n ctx.lineTo(length,0);\n if(arrowStart){\n ctx.moveTo(aLength,-aWidth);\n ctx.lineTo(0,0);\n ctx.lineTo(aLength,aWidth);\n }\n if(arrowEnd){\n ctx.moveTo(length-aLength,-aWidth);\n ctx.lineTo(length,0);\n ctx.lineTo(length-aLength,aWidth);\n }\n\n ctx.lineWidth = 5;\n ctx.strokeStyle = 'white';\n ctx.stroke();\n ctx.setTransform(1,0,0,1,0,0);\n }", "line(start, end)\n {\n let path = [];\n\n // Common case where start == end\n if (start.x === end.x && start.y === end.y)\n path.push(start);\n\n // Common case where start.x == end.x\n else if (start.x === end.x)\n {\n if (start.y < end.y) {\n for (let y = start.y; y <= end.y; y ++)\n path.push(new Vector(start.x, y));\n } else {\n for (let y = start.y; y >= end.y; y --)\n path.push(new Vector(start.x, y));\n }\n }\n\n // Common case where start.y == end.y\n else if (start.y === end.y)\n {\n if (start.x < end.x) {\n for (let x = start.x; x <= end.x; x ++)\n path.push(new Vector(x, start.y));\n } else {\n for (let x = start.x; x >= end.x; x --)\n path.push(new Vector(x, start.y));\n }\n }\n\n // Other cases\n else\n {\n let n = Vector.diagonalDistance(start, end);\n for (let i = 0; i <= n; i ++)\n {\n var t = i === 0 ? 0 : i / n;\n path.push(Vector.lerp(start, end, t).round());\n }\n }\n\n return path.map(position => this.positionInfo(position));\n }", "CalcDiagonals() {\n return [\n this.CalcOffset(2, -1, -1), // NORTH EAST\n this.CalcOffset(1, 1, -2), // NORTH\n this.CalcOffset(-1, 2, -1), // NORTH WEST\n this.CalcOffset(-2, 1, 1), // SOUTH WEST\n this.CalcOffset(-1 ,-1, 2), // SOUTH\n this.CalcOffset(1, -2, 1), // SOUTH EAST\n ];\n }", "static DrawDottedLines() {}", "diagonal1(d) {\n var src = d.source,\n node = d3.select(`#n-${this.id}-${src.id}`)[ 0 ][ 0 ],\n dia,\n width = 0;\n\n if (node) {\n width = node.getBBox().width;\n }\n\n dia = 'M' + (src.y + width) + ',' + src.x +\n 'H' + (d.target.y - 30) + 'V' + d.target.x +\n //+ (d.target.children ? '' : 'h' + 30);\n ('h' + 30);\n\n return dia;\n }", "function overDiagSecAbs() {\n for (i = 0; i < nrLines; i++) {\n for ( j= 0; j < nrCols; j++) {\n\n xpos = (elemWidth + hDist) * j;\n ypos = (elemHeight + vDist) * i;\n\n if (i+j<(Math.max(nrCols, nrLines) - 1)) {\n eachElem = drawElemAbs(\"culoareBlue\", i, j);\n } \n else {\n eachElem = drawElemAbs(\"culoareVerde\", i, j);\n }\n\n eachElem.style.top = ypos + \"px\";\n eachElem.style.left = xpos + \"px\";\n }\n }\n }", "diagonalStripes(design, { w, h, colors }) {\n const [, clrs] = design;\n const parts = [];\n let x = w / 5;\n let y = h / 5;\n const xi = x;\n const yi = y;\n let clr = 0;\n // The first stripe - just a triangle.\n parts.push(`<path fill=\"${getColor(clrs[0], colors)}\"`);\n parts.push(` d=\"M0,0H${x}L0,${y}Z\"/>\\n`);\n // Second, third, fourth and fifth stripes.\n for (let i = 0; i < 4; i++) {\n clr = 1 - clr;\n parts.push(`<path fill=\"${getColor(clrs[clr], colors)}\"`);\n parts.push(` d=\"M${x},0H${x + xi}L0,${y + yi}V${y}Z\"/>\\n`);\n x += xi;\n y += yi;\n }\n /*\n clr = 1 - clr;\n y = h / 10;\n parts.push(`<path d=\"M${x},0H${w}V${y}L${w / 10},${h}H0V${h - y}Z`);\n parts.push(`\" fill=\"${getColor(clrs[clr], colors)}\"/>\\n`);\n x = w / 10;\n */\n x = 0;\n y = 0;\n // Seventh, eighth, ninth and tenth stripes.\n for (let i = 0; i < 4; i++) {\n clr = 1 - clr;\n parts.push(`<path fill=\"${getColor(clrs[clr], colors)}\"`);\n parts.push(` d=\"M${w},${y}V${y + yi}L${x + xi},${h}H${x}Z\"/>\\n`);\n x += xi;\n y += yi;\n }\n // The final triangle.\n parts.push(`<path fill=\"${getColor(clrs[1], colors)}\"`);\n parts.push(` d=\"M${w},${y}V${h}H${x}Z\"/>\\n`);\n return parts.join('');\n }", "function overDiagPrinc() {\n for (i = 0; i < nrLines; i++) {\n for ( j= 0; j < nrCols; j++) {\n if (j>i) {\n drawSquare(\"culoareBlue\");\n } \n else {\n drawSquare(\"culoareDefault\");\n }\n }\n }\n }", "function diagonal(s, d) {\n var path = 'M ' + s.y + ' ' + s.x + ' C ' + ((s.y + d.y) / 2) + ' ' + s.x + ' ' + (s.y + d.y) / 2 + ' ' + d.x + ' ' + d.y + ' ' + d.x;\n return path\n }", "function line_pixel_length(d, theta, n) {\n // for angle in [pi/4,3*pi/4],\n // flip along diagonal (transpose) and call recursively\n if(theta > Math.PI /4 && theta < 3/4*Math.PI) {\n return numeric.transpose(line_pixel_length(d, Math.PI/2-theta, n));\n }\n\n // for angle in [3*pi/4,pi],\n // redefine line to go in opposite direction\n if(theta > Math.PI/2) {\n d =-d;\n theta = theta-Math.PI;\n }\n\n // for angle in [-Math.PI/4,0],\n // flip along x-axis (up/down) and call recursively\n if(theta < 0) {\n // flip up down with reverse\n return flipud(line_pixel_length(-d,-theta,n));\n }\n\n if(theta > Math.PI/2 || theta < 0) {\n console.log(\"invalid angle\")\n return;\n }\n\n var L = zeros(n,n);\n\n var ct = Math.cos(theta);\n var st = Math.sin(theta);\n\n var x0 = n/2 - d*st;\n var y0 = n/2 + d*ct;\n\n var y = y0 - x0*st/ct;\n var jy = Math.ceil(y);\n var dy = (y+n) % 1;\n\n for(var jx=1; jx <= n; jx++){\n var dynext = dy + st/ct;\n if(dynext < 1){\n if (jy >= 1 && jy <= n){\n L[n-jy][jx-1] = 1/ct;\n }\n dy = dynext;\n }else{\n if (jy>=1 && jy<=n) L[n-jy][jx-1] = (1 - dy)/st ;\n if (jy+1>=1 && jy+1<=n) L[n-(jy+1)][jx-1] = (dynext - 1)/st; \n dy = dynext - 1;\n jy = jy + 1;\n }\n }\n return L;\n}", "function drawLineWithArrows(x0,y0,x1,y1,aWidth,aLength,arrowStart,arrowEnd){\n var dx=x1-x0;\n var dy=y1-y0;\n var angle=Math.atan2(dy,dx);\n var length=Math.sqrt(dx*dx+dy*dy);\n //\n ctx.save();\n ctx.translate(x0,y0);\n ctx.rotate(angle);\n ctx.beginPath();\n ctx.moveTo(0,0);\n ctx.lineTo(length,0);\n if(arrowStart){\n ctx.moveTo(aLength,-aWidth);\n ctx.lineTo(0,0);\n ctx.lineTo(aLength,aWidth);\n }\n if(arrowEnd){\n ctx.moveTo(length-aLength,-aWidth);\n ctx.lineTo(length,0);\n ctx.lineTo(length-aLength,aWidth);\n }\n //\n ctx.stroke();\n ctx.restore();\n}", "function Drawfixation() {\n\tcrossVertical = paper.path(\"M 200 195 l 0 10 z\");\n\tcrossVertical.attr({stroke: \"white\", 'stroke-width':2});\n\tcrossHorizontal = paper.path(\"M 195 200 l 10 0 z\");\n\tcrossHorizontal.attr({stroke: \"white\", 'stroke-width':2});\n}", "_drawLine(startX, startY, endX, endY){\n var headlen = 15; // length of head in pixels\n var angle = Math.atan2(endY-startY,endX-startX);\n context.beginPath();\n context.strokeStyle = \"#000\";\n context.lineWidth=this.state.innerLineWidth;\n //Calculate the starting point on the edge of the starting node and \n //the ending point on the ending node\n var edgeStartX = startX + this.state.nodeRadius * Math.cos(angle);\n var edgeStartY = startY + this.state.nodeRadius * Math.sin(angle);\n var edgeEndX = endX - this.state.nodeRadius * Math.cos(angle);\n var edgeEndY = endY - this.state.nodeRadius * Math.sin(angle);\n \n //Draw line from start to end\n context.moveTo(edgeStartX, edgeStartY);\n context.lineTo(edgeEndX, edgeEndY);\n context.strokeStyle = \"#000\";\n context.stroke();\n \n //Draw a circle\n context.beginPath();\n context.lineWidth=this.state.innerLineWidth/2;\n \tcontext.arc(edgeEndX, edgeEndY, this.state.nodeRadius/1.75, \n 0, 2 * Math.PI);\n \tcontext.fillStyle = \"#eee\";\n \tcontext.fill();\n \n //Previously used to show dependency, now using circle dependency ^\n //Draw an arrow\n// context.lineTo(edgeEndX-headlen*Math.cos(angle-Math.PI/6), \n// edgeEndY-headlen*Math.sin(angle-Math.PI/6));\n// context.moveTo(edgeEndX, edgeEndY);\n// context.lineTo(edgeEndX-headlen*Math.cos(angle+Math.PI/6), \n// edgeEndY-headlen*Math.sin(angle+Math.PI/6));\n \n \tcontext.strokeStyle = \"#000\";\n context.stroke();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
let v: void = 10; // error TS2322: Type '10' is not assignable to type 'void' void is only really useful for functions:
function voidFunction() { // i don't return a value // return 10; // error TS2322: Type '10' is not assignable to type 'void' }
[ "function foo(x: void) { }", "function showVoid() {\n console.log(\"Void type\");\n}", "function myVoid() {\n return;\n}", "function VoidType() {\n}", "Void(options = {}) {\r\n return { ...options, type: 'void', kind: exports.VoidKind };\r\n }", "function Pair$AssignmentExpression$function$$$$Expression$$$$void$E() {\n}", "function Triple$LocalVariable$AssignmentExpression$function$$$$Expression$$$$void$E() {\n}", "function voidAction() {\r\n\r\n}", "function playWithVoid() {\n let unusable;\n console.log(unusable);\n unusable = undefined;\n console.log(unusable);\n unusable = null;\n console.log(unusable);\n}", "static isVoidExpression(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.VoidExpression;\r\n }", "function isVoid(value) {\n return value === null || value === undefined || Object.is(value, NaN);\n}", "function evaluateVoidExpression({ node, environment, evaluate, statementTraversalStack }) {\n evaluate.expression(node.expression, environment, statementTraversalStack);\n // The void operator evaluates the expression and then returns undefined\n return undefined;\n}", "function create__voidType(gScp){\n\t//create dummy type void\n\tvar tmp_void_type = new type(\"void\", OBJ_TYPE.VOID, gScp);\n\t//create symbol 'this'\n\ttmp_void_type.createField(\n\t\t\"this\", \t\t\t\t\t\t\t//variable name\n\t\ttmp_void_type, \t\t\t\t\t\t//variable type\n\t\ttmp_void_type._scope._start\t\t\t//first block in the type's scope\n\t);\n\t//reset command library to avoid cases when NULL command that initializes fields\n\t//\tof one type, also gets to initialize fields from another type, since it is\n\t//\tfound to be a similar NULL command.\n\tcommand.resetCommandLib();\n\t//create fundamental functions\n\t//tmp_void_type.createReqMethods();\n}", "function Void(Compartment){\n this.compartment = Compartment;\n}", "function isVoid (type) {\n return type.size === 0 && type.indirection === 1;\n}", "Void(options = {}) {\r\n return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null' });\r\n }", "isVoid(editor, value) {\n return Element2.isElement(value) && editor.isVoid(value);\n }", "function takes_any(x: any): void {}", "isVoid(editor, value) {\n return Element.isElement(value) && editor.isVoid(value);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts the paint color master data.
function insertMasterData() { PaintColor.create(paintColors, function (err, paintColors) { if (err) { throw err; } log.info('Number of PaintColors created: %d', Object.keys(paintColors).length); endScript(callback); }); }
[ "function addColor () {\n painter = $('#paintGrid');\n\n painter.click(function (event) {\n var target = $(event.target);\n if (target.hasClass('cell')) {\n target.css('background-color', targetColor);\n }\n });\n }", "function _addCanvasColor() {\n background_color = document.getElementById('background_color_export').value;\n if (background_color == \"white\") {\n _backgroundColor = \"#ffffff\";\n draw(geojson.features, 'draw');\n var backgroundColorDiv = document.getElementById('backgroundColorDiv');\n backgroundColorDiv.hidden = true;\n }\n else if (background_color == \"color\") {\n var backgroundColorDiv = document.getElementById('backgroundColorDiv');\n backgroundColorDiv.hidden = false;\n }\n else if (background_color == \"transparent\") {\n var backgroundColorDiv = document.getElementById('backgroundColorDiv');\n backgroundColorDiv.hidden = true;\n _backgroundColor = null;\n draw(geojson.features, 'draw');\n }\n}", "function addColor() {\n\t// change background color to draw\n\t$('.grid_sq').css({'background-color': '#7D7C7C'});\n}", "add(color) {\n if(!this.contains(color)){\n this._coloring.push(color);\n }\n }", "addPaintOptions() {\n const colors = [ '0x000000', '0xff0000', '0xff9500', '0xf7d305','0x009914', '0x1500d1', '0x7e00cc', '0xFFFFFF' ];\n const colorHexs = [ '#000000', '#ff0000', '#ff9500', '#f7d305','#009914', '#1500d1', '#7e00cc', '#FFFFFF' ];\n\n let offset = 0;\n\n for (let i = 0; i <= colors.length - 1; i++) {\n // CSS style string.\n const styleString = `background-color: ${colorHexs[i]}; border-color: ${colorHexs[i]};`;\n const colorButton = this.add.dom(this.camera.centerX + 300, this.camera.centerY - 180 + offset, 'button', styleString);\n colorButton.setClassName('color-button');\n colorButton.addListener('click');\n\n // Change the color of the brush when clicked.\n colorButton.on('click', () => {\n this.selectedColorOption = colors[i];\n });\n\n offset += 50;\n }\n }", "function initColorPalette() {\n $colorButtons.on('touchstart click', applyColor)\n $applyColorButton.on('touchstart click', clearSelected)\n $colorPalette.on('changeSet', function(e) {\n // Update color set\n colorSet = e.colorData\n selectedSet.value = $paletteSelectons.filter(':checked').val()\n _.forEach(colourAreas, setColor)\n view.draw()\n });\n }", "function setDataColors(data) {\n\t\n\tvar dataTypeIs = data.type;\n\n\tif(dataTypeIs == 0) {\n\t\t//### Nominal data\n\t\tTheApp.getDataAt(TheApp.noOfData() - 1).style.dataColor(\"#222222\");\n\t}\n\telse if(dataTypeIs == 1) {\n\t\t//### Ordinal data\n\t\tvar noOfOrdinalKeys = Object.keys(data.valueInfo).length;\n\t\t\n\t\tfor(var i = 0; i < noOfOrdinalKeys; i++) {\n\t\t\tvar color = ordinalColors[totalOrdinalData][i % 7];\n\t\t\tTheApp.getDataAt(TheApp.noOfData() - 1).styles.push(color);\n\t\t}\n\t\t\n\t\tTheApp.getDataAt(TheApp.noOfData() - 1).style.dataColor(ordinalColors[totalOrdinalData][2]);\n\t\t\n\t\ttotalOrdinalData++;\n\t}\t\t\t\t\n\telse if(dataTypeIs == 2) {\n\t\t//### Sensor data\n\t\tvar color = sensorColors[totalSensorData % 8];\n\t\tTheApp.getDataAt(TheApp.noOfData() - 1).style.dataColor(color);\n\t\t\n\t\ttotalSensorData++;\n\t}\t\t\t\t\n\telse if(dataTypeIs == 3) {\n\t\t//### GPS data\n\t\tvar color = mapColors[totalSensorData % 6];\n\t\tTheApp.getDataAt(TheApp.noOfData() - 1).style.dataColor(color);\n\t\t\n\t}\n\t\n\t\n}", "addElementToStore(x, y, color) {\n this.store[this.getBoxKey(x, y)] = color;\n }", "addColor() {\r\n this.groundColor++;\r\n }", "function assignColors(callback){\n replay.server_green = replay.rawmapdata[0]['obj56'];\n replay.server_blue = replay.rawmapdata[0]['obj29'];\n replay.server_red = replay.rawmapdata[0]['obj39'];\n callback();\n }", "function processColor(sensorData) {\n color = sensorData\n //console.log(color)\n server.write(objectName, TOOL_NAME, \"color\", color, \"f\")\n}", "function trackColor(){\n if(colorTracker === 3){\n colorTracker = 0\n colorSwatches[colorTracker].style.backgroundColor = brushBox.style.backgroundColor\n colorTracker++\n }else{\n colorSwatches[colorTracker].style.backgroundColor = brushBox.style.backgroundColor\n colorTracker++\n }\n}", "function ColorSelection() {\n\n selectedColor = color(`rgba(${c.map((dat) => dat)})`);\n hueVarr = Math.round(hue(selectedColor));\n\n //h % 180\n fill(color(`rgba(${c.map((dat) => dat)})`));\n push();\n fill(100,0,100);\n textSize(12);\n text(\"Primary Secondary\", width/4 * 3, height/20, 120, 25);\n fill(255, 255, 255, 51);\n pop();\n rect(width/4 * 3, height/10, 50, 50);\n\n fill(hueVarr > 180 ? hueVarr / 2 : hueVarr * 2, 100, 100)\n rect(width/4 * 3 + 50, height/10, 50, 50);\n\n bColorsPicked = true;\n //PaintButton.show();\n}", "'submit .pickColor'(event) {\n event.preventDefault(); \n\n const color = event.target.color2.value; \n lineColor = '#' + String(color); \n colorHistory.push('#' + String(color)); \n Session.set('penColor', lineColor);\n Session.set('colorHistory', colorHistory);\n Session.set('colorChange', false);\n }", "function setGridColor1(data, row, column){\n data.color_history.push(\n {column: column, row: row, color: data.current_color}\n )\n}", "function importColors(currentEditor) {\n if (currentEditor) {\n var mode = currentEditor.document.language._mode,\n str = \"\";\n\n $('#swatcher-colordefine-define tr').each(function() {\n if ($(this).data('hex')) {\n str += $(this).find('input').val() + \":\" + $(this).data('hex') + \"; \\n\";\n }\n });\n\n switch (mode) {\n case 'css':\n str = '/* Generated by Brackets Swatcher' + \"\\n\" + str + '*/';\n break;\n\n case 'text/x-less':\n str = '/* Generated by Brackets Swatcher */' + \"\\n\" + str;\n break;\n\n default:\n messages.dialog('MAIN_WRONGFILE');\n return false;\n }\n\n Utils.insert(currentEditor, str);\n return SwatchPanel.update(currentEditor);\n \n } else { \n messages.dialog('ACO_NOFILE');\n return false;\n }\n }", "function drawCurrentColor() {\n\t$('#selected').html(' ');\n\tlet div = '<div id=\"colorSelected\"></div>';\n\t$('#selected').append(div);\n\t$('#colorSelected').css('background', squareColors[colorIndexWeAreDrawing]);\n}", "function updateExprRectColors(){\n d3.select('#exprPlot').selectAll('.exprPlot_data_point_rect')\n .attr('fill', function(){\n return this.parentNode.__data__.meta.color;\n });\n}", "setColor (typedColor) {\n this.patches.pixels.data[this.id] = typedColor.getPixel()\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display function, sets up various matrices, binds data to the GPU, and displays it.
function display() { // Clear the color buffer gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT ); // Set the model-view matrix to the current CameraController rotation quat4.toMat4( controller.currentOrientation, mvmat ); // Get the normal matrix from the model-view matrix (for lighting) mat4.toInverseMat3( mvmat, nmat ); mat3.transpose( nmat ); // Use the created shader program gl.useProgram(gl_program); // Upload the projection matrix and the model-view matrix to the shader gl.uniformMatrix4fv(gl_program_loc.uPMatrix, false, projmat); gl.uniformMatrix4fv(gl_program_loc.uMVMatrix, false, mvmat); gl.uniformMatrix3fv(gl_program_loc.uNMatrix, false, nmat); gl.uniform3fv(gl_program_loc.uColor, new Float32Array([0.5, 0.5, 0.5])); gl.uniform1i(gl_program_loc.uLighting, lighting ? 1 : 0 ); // If there is a model loaded if( vbo.length > 0 ) { // Bind vbo to be the current array buffer gl.bindBuffer(gl.ARRAY_BUFFER, vbo); // Enables a vertex attribute array for vertex positions gl.enableVertexAttribArray(gl_program_loc.aPosition); // Setup the pointer to the position data gl.vertexAttribPointer(gl_program_loc.aPosition, 3, gl.FLOAT, false, 12, 0); if( line ) { // Bind lineIndices to be the current index array buffer gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, lineIndices); // Finally, draw the data as lines using all of the current settings gl.drawElements(gl.LINES, lineIndices.length, gl.UNSIGNED_SHORT, 0); } else { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, triIndices); gl.drawElements(gl.TRIANGLES, triIndices.length, gl.UNSIGNED_SHORT, 0); } } }
[ "function display() {\n displayer({\n destination: null,\n source: buffers[bufferID],\n count: count,\n viewport: {x:0, y:0, width: canvas.width, height: canvas.height}\n });\n }", "display() {\n this.scene.pushMatrix();\n this.scene.rotate(-Math.PI / 2, 1, 0, 0);\n let timeFactor = (Math.sin((this.scene.currTime / 10000) % 512 * 2));\n this.testShader.setUniformsValues({ time: timeFactor });\n this.scene.setActiveShader(this.testShader);\n this.scene.pushMatrix();\n this.texture.bind(2);\n this.wavemap.bind(1);\n this.plane.display();\n this.scene.popMatrix();\n this.scene.setActiveShader(this.scene.defaultShader);\n this.scene.popMatrix();\n }", "function renderDisplay() {\r\n\r\n DISPLAY.drawImage(BUFFER.canvas, 0, 0);\r\n\r\n }", "display(){\n this.scene.pushMatrix();\n\n this.heightmap.bind(0);\n this.texture.bind(1);\n \n this.scene.setActiveShader(this.shader);\n this.terrain.display();\n this.scene.setActiveShader(this.scene.defaultShader);\n\n this.scene.popMatrix();\n }", "display()\n {\n \n this.scene.setActiveShader(this.shader);\n var time = Math.sin(Date.now() * 0.00001) * 20; \n this.shader.setUniformsValues({timeFactor:time,heightmap: 1});\n\n this.texture.bind(0);\n \n this.wavemap.bind(1);\n \n this.plane.display();\n \n this.scene.setActiveShader(this.scene.defaultShader);\n \n }", "display() {\n this.tile.scene.pushMatrix()\n\n this.tile.gameboard.orchestrator.tileMaterial.apply()\n if (this.tile.texture)\n this.tile.texture.bind()\n\n this.tile.obj.display()\n\n this.tile.scene.popMatrix()\n\n if (this.tile.piece) {\n this.tile.piece.display()\n }\n }", "function display() {\n //clear screen\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n //only draws active cells (misses still lifes)\n /*\n for(var cell = 0; cell < activeCells; cell++) {\n var x = activeCoords[2*cell];\n var y = activeCoords[2*cell + 1];\n drawCell(x, y, false, Math.floor(grid[y*cols + x]/2)%2);\n }\n //*/\n\n //loop through all cells and draw\n for(var y = 0; y < rows; y++) {\n for(var x = 0; x < cols; x++) {\n drawCell(x, y, false, Math.floor(grid[y*cols + x]/2)%2);\n }\n }\n\n //display grid lines if present\n if(gridlines) {\n for(var y = 0; y < rows; y++) {\n for(var x = 0; x < cols; x++) {\n drawCell(x, y, true, false);\n }\n }\n }\n}", "function Display() {\n if (ready) {\n ready = false;\n // Get the canvas set up\n var context = setupCanvas();\n var canvasData = context.createImageData(screen_width, screen_height);\n // Now initialise the variables need for our calculations\n var length = (screen_memory.length / screen_planes);\n var memory_pointer = 0;\n var start_plane = 0;\n var word_length = 16 - 1;\n var i, j, k, l, pixel_colour, mask;\n // Set up a temporary buffer for the plane data for a 16 pixel area\n var plane_data = new Array(screen_planes);\n // Now we start going through the screen buffer (array of words)\n for (i = 0; i < length; i++) {\n // Get the planar data for a 16 pixel length of screen\n for (k = 0; k < screen_planes; k++)\n plane_data[k] = screen_memory[start_plane++];\n // Now we have the plane data for a 16 pixel area, start\n // iterating over each of the 16 pixels.\n for (j = word_length; j > -1; --j) { // Starting with the last plane, the HSB of the colour value of the pixel, and going downwards...\n pixel_colour = 0; // Initialise pixel colour value\n mask = (1 << j);\n for (l = 0; l < screen_planes; l++) // Iterate over each of the planes\n if (plane_data[l] & mask) // If the masked pixel exists in plane data\n pixel_colour += 1 << l; // Add the plane's binary digit value to the pixel colour value\n canvasData.data[memory_pointer++] = pixel_palette[pixel_colour][0]; // Copy RGB of pixel to canvas memory\n canvasData.data[memory_pointer++] = pixel_palette[pixel_colour][1];\n canvasData.data[memory_pointer++] = pixel_palette[pixel_colour][2];\n canvasData.data[memory_pointer++] = 255; // Pixel is fully opaque\n }\n }\n context.putImageData(canvasData, 0, 0);\n if (scale)\n context.drawImage(canvas, 0, 0);\n ready = true;\n }\n return ready;\n }", "function setupDisplay() {\r\n displayCanvas = document.createElement( 'canvas' );\r\n displayCanvas.id = \"display\";\r\n displayCanvas.style.cursor = \"crosshair\";\r\n\r\n // Should change this to be less free-function linking.\r\n displayCanvas.addEventListener( \"mousedown\", onMouseDown );\r\n displayCanvas.addEventListener( \"mouseup\", onMouseUp );\r\n displayCanvas.addEventListener( \"mousemove\", onMouseMove );\r\n\r\n // Cache this for everything that needs it.\r\n displayContext = displayCanvas.getContext(\"2d\");\r\n\r\n // #board is an empty div at the top of the body, set to fill the entire\r\n // region.\r\n let board = document.getElementById( \"board\" );\r\n board.appendChild( displayCanvas );\r\n \r\n // Hook window resizing to call our refresh function.\r\n window.addEventListener( \"resize\", () => {\r\n resizeDisplayToWindow();\r\n });\r\n\r\n // Initial grid drawing and such.\r\n resizeDisplayToWindow();\r\n}", "function refreshDisplay(){\n env.disp.render() ;\n env.plot.render() ;\n}", "display()\n {\n build.scene.pushMatrix();\n build.scene.multMatrix(this.transformations);\n build.display();\n build.scene.popMatrix();\n }", "function display() {\n\tdividePrimitive();\n\n\tgl.viewport(0, 0, canvas.width, canvas.height);\n\tgl.clearColor(1.0, 1.0, 1.0, 1.0);\n\t\n\tvar program = initShaders( gl, \"vertex-shader\", \"fragment-shader\");\n\tgl.useProgram( program );\n\tvar bufferId = gl.createBuffer();\n\tgl.bindBuffer(gl.ARRAY_BUFFER, bufferId);\n\tgl.bufferData(gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW);\n\n\tvar vPosition = gl.getAttribLocation( program, \"vPosition\");\n\tgl.vertexAttribPointer( vPosition, 2, gl.FLOAT, false, 0, 0);\n\tgl.enableVertexAttribArray( vPosition);\n\n\trender();\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 // Render the background box for the HUD\n noStroke()\n fill(0)\n rect(x, y, 20, 120)\n fill(50, 50, 52, 20) // a bit of transparency\n rect(x + 20, y, 450, 120)\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\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 + 160, y + 25 + 80)\n easycam.endHUD()\n}", "display() {\n this.scene.pushMatrix();\n\n // Display tile itself\n this.selected ? this.selectedMaterial.apply() : this.material.apply()\n this.plane.display();\n \n if (this.selected)\n this.scene.translate(0,0.2,0);\n\n // Display pieces\n this.scene.pushMatrix();\n for (let i = 0; i < this.pieces.length; i++) {\n this.pieces[i].display();\n this.scene.translate(0, 0.2, 0);\n }\n this.scene.popMatrix();\n\n this.scene.popMatrix();\n }", "function refreshDisplay(){\n env.disp.render() ;\n}", "display(){\n this.scene.setActiveShader(this.shader);\n this.textureRTT.bind(0);\n \n this.rectangle.display();\n\n this.textureRTT.unbind(0);\n this.scene.setActiveShader(this.scene.defaultShader);\n }", "display() {\r\n this.inputHandle();\r\n let deg2rad = Math.PI / 180.0;\r\n\r\n // ---- BEGIN Background, camera and axis setup\r\n\r\n // Clear image and depth buffer everytime we update the scene\r\n this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);\r\n this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);\r\n\r\n // Initialize Model-View matrix as identity (no transformation\r\n this.updateProjectionMatrix();\r\n this.loadIdentity();\r\n\r\n // Apply transformations corresponding to the camera position relative to the origin\r\n this.applyViewMatrix();\r\n\r\n // Update all lights used\r\n this.updateLights();\r\n\r\n //Draw axis\r\n if (this.axisState) this.axis.display();\r\n\r\n // ---- END Background, camera and axis setup\r\n\r\n //display terrain\r\n this.terrain.display();\r\n\r\n //display vehicle\r\n let textString = '';\r\n switch (this.currVehicleAppearance) {\r\n case 0:\r\n textString = 'BLUE';\r\n break;\r\n case 1:\r\n textString = 'PURPLE';\r\n break;\r\n case 2:\r\n textString = 'CAMOUFLAGE';\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n // Update the vehicle's appearance\r\n if (this.vehicleAppearances[this.currVehicleAppearance] instanceof CGFappearance)\r\n this.vehicle.setAppearance(this.vehicleAppearances[this.currVehicleAppearance], textString);\r\n\r\n this.vehicle.display();\r\n\r\n for (let i = 0; i < this.oldVehiclesIndex; i++) {\r\n this.oldVehicles[i].setAppearance(this.vehicleAppearances[this.currVehicleAppearance], textString);\r\n this.oldVehicles[i].display();\r\n }\r\n\r\n }", "display() \n { \n this.scene.pushMatrix();\n this.semiSphere2.display();\n this.scene.popMatrix();\n }", "display()\n\t{\t\n\t\tthis.scene.pushMatrix();\n\t\tthis.scene.translate(this.x,-0.5,this.z);\t\n\t\tif(this.scene.pickIndex == this.scene.pickedIndex)\n\t\t\tthis.selected = !this.selected;\n\t\tif(this.selected)\n\t\t\tthis.texture.bind();\n\t\telse{\n\t\t\tif(this.valid)\n\t\t\t\tthis.validText.bind();\n\t\t\telse\n\t\t\t\tthis.texture.bind();\n\t\t}\n\t\tthis.cell.display();\n\t\tthis.texture.unbind();\n \tthis.scene.popMatrix();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sort an array by the reg expression or default by number
sortByReg(arr, reg) { var defaultReg = /\d/; if (reg) { defaultReg = reg; } return arr.sort(function(a, b) { return a.match(defaultReg) - b.match(defaultReg); }); }
[ "function extractsort (a, b) {\n const pattern = />\\d+</\n const pattern2 = /\\d+/\n var a_val = pattern2.exec(pattern.exec(a))\n var b_val = pattern2.exec(pattern.exec(b))\n return b_val - a_val\n }", "function sort(array) {\n\n}", "function getSortFunctionByData(values) {\n var testToRange = function (value) {\n var reg = /(\\d-)|(\\d+-\\d+)|(\\d+\\+)/;\n var match = value.match(reg);\n if (match && match.length) {\n return true;\n }\n return false;\n };\n if (values.length > 0) {\n var testResult = values\n .map(function (val) { return testToRange(val); })\n .reduceRight(function (a, b) { return a && b; });\n if (testResult) {\n return function (a, b) {\n if (a && b) {\n var aNum = a.match(/\\d+/)[0];\n var bNum = b.match(/\\d+/)[0];\n return +aNum < +bNum\n ? 1\n : +a.split(\"-\").pop() < +b.split(\"-\").pop()\n ? 1\n : -1;\n }\n };\n }\n }\n return function (a, b) { return (a < b ? -1 : 1); };\n}", "function sortArrayBy( array, key, opt ) {\r\n\topt = opt || {};\r\n\t// TODO: use code generation instead of multiple if statements?\r\n\tvar sep = unescape('%uFFFF');\r\n\t\r\n\tvar i = 0, n = array.length, sorted = new Array( n );\r\n\tif( opt.numeric ) {\r\n\t\tif( typeof key == 'function' ) {\r\n\t\t\tfor( ; i < n; ++i )\r\n\t\t\t\tsorted[i] = [ ( 1000000000000000 + key(array[i]) + '' ).slice(-15), i ].join(sep);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfor( ; i < n; ++i )\r\n\t\t\t\tsorted[i] = [ ( 1000000000000000 + array[i][key] + '' ).slice(-15), i ].join(sep);\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tif( typeof key == 'function' ) {\r\n\t\t\tfor( ; i < n; ++i )\r\n\t\t\t\tsorted[i] = [ key(array[i]), i ].join(sep);\r\n\t\t}\r\n\t\telse if( opt.caseDependent ) {\r\n\t\t\tfor( ; i < n; ++i )\r\n\t\t\t\tsorted[i] = [ array[i][key], i ].join(sep);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfor( ; i < n; ++i )\r\n\t\t\t\tsorted[i] = [ array[i][key].toLowerCase(), i ].join(sep);\r\n\t\t}\r\n\t}\r\n\t\r\n\tsorted.sort();\r\n\t\r\n\tvar output = new Array( n );\r\n\tfor( i = 0; i < n; ++i )\r\n\t\toutput[i] = array[ sorted[i].split(sep)[1] ];\r\n\t\r\n\treturn output;\r\n}", "function alphabetical (arr){\n const restult11 = arr.sort ()\n console.log (restult11)\n}", "function multiSort(arr) {\n\n}", "function sortOn(arr) {\n var comparators = [];\n for (var i=1; i<arguments.length; i+=2) {\n comparators.push(getKeyComparator(arguments[i], arguments[i+1]));\n }\n arr.sort(function(a, b) {\n var cmp = 0,\n i = 0,\n n = comparators.length;\n while (i < n && cmp === 0) {\n cmp = comparators[i](a, b);\n i++;\n }\n return cmp;\n });\n return arr;\n }", "function sorter()\n{\n var arr = this, i, args = arguments, l = args.length,\n a, b, avar, bvar, variables, step, lt, gt,\n field, filter_args, sorter_args, desc, dir, sorter;\n // + or nothing before a (nested) field indicates ascending sorting (default),\n // example \"+a.b.c\", \"a.b.c\"\n // - before a (nested) field indicates descending sorting,\n // example \"-b.c.d\"\n if (l)\n {\n step = 1;\n sorter = [];\n variables = [];\n sorter_args = [];\n filter_args = [];\n for (i=l-1; i>=0; --i)\n {\n field = args[i];\n // if is array, it contains a filter function as well\n filter_args.unshift('f' + i);\n if (field.push)\n {\n sorter_args.unshift(field[1]);\n field = field[0];\n }\n else\n {\n sorter_args.unshift(null);\n }\n dir = field.charAt(0);\n if ('-' === dir)\n {\n desc = true;\n field = field.slice(1);\n }\n else if ('+' === dir)\n {\n desc = false;\n field = field.slice(1);\n }\n else\n {\n // default ASC\n desc = false;\n }\n field = field.length ? '[\"' + field.split(SEPARATOR).join('\"][\"') + '\"]' : '';\n a = \"a\"+field; b = \"b\"+field;\n if (sorter_args[0])\n {\n a = filter_args[0] + '(' + a + ')';\n b = filter_args[0] + '(' + b + ')';\n }\n avar = 'a_'+i; bvar = 'b_'+i;\n variables.unshift(''+avar+'='+a+','+bvar+'='+b+'');\n lt = desc ?(''+step):('-'+step); gt = desc ?('-'+step):(''+step);\n sorter.unshift(\"(\"+avar+\" < \"+bvar+\" ? \"+lt+\" : (\"+avar+\" > \"+bvar+\" ? \"+gt+\" : 0))\");\n step <<= 1;\n }\n // use optional custom filters as well\n return (newFunc(\n filter_args.join(','),\n ['return function(a,b) {',\n ' var '+variables.join(',')+';',\n ' return '+sorter.join('+')+';',\n '};'].join(\"\\n\")\n ))\n .apply(null, sorter_args);\n }\n else\n {\n a = \"a\"; b = \"b\"; lt = '-1'; gt = '1';\n sorter = \"\"+a+\" < \"+b+\" ? \"+lt+\" : (\"+a+\" > \"+b+\" ? \"+gt+\" : 0)\";\n return newFunc(\"a,b\", 'return '+sorter+';');\n }\n}", "function sortNumbers(arr){\n return arr.sort(function(a, b){ return a - b; });\n }", "function sortAlphaNumericPrepareData(tdNode, innerText){\n var aa = innerText.toLowerCase().replace(\" \", \"\");\n var reg = /((\\-|\\+)?(\\s+)?[0-9]+\\.([0-9]+)?|(\\-|\\+)?(\\s+)?(\\.)?[0-9]+)([a-z]+)/;\n\n if(reg.test(aa)) {\n var aaP = aa.match(reg);\n return [aaP[1], aaP[8]];\n };\n\n // Return an array\n return isNaN(aa) ? [\"\",aa] : [aa,\"\"];\n}", "function sortExpression(expression){\n var flag = true;\n var dummy = expression[0];\n while(flag){\n flag = false;\n for(var i = 1; i < expression.length; i++){\n if(expression[i-1] > expression[i]){\n dummy = expression[i-1];\n expression[i-1] = expression[i];\n expression[i] = dummy;\n flag = true;\n }\n }\n }\n\n return expression;\n}", "sortRomanNum(arr) {\n if (arr.length == 1)\n return arr;\n\n let numArr = [];\n arr.forEach((a, i) => {\n numArr.push(this.roman_to_Int(a.split(\" \")[a.split(\" \").length - 1]));\n })\n numArr.sort(function (a, b) { return a - b });\n return this.fixSortRoman(numArr, arr);\n }", "function sortNumbers(arr) {\n //to sort numbers (a-b)\n return arr.sort((function(a, b){return a-b}));\n\n}", "function getRegNos(regNos)\n{\n regNos.sort(function(a, b){return parseInt(a) - parseInt(b)});\n \n var regNos2 = regNos.map(function (x) { \n return parseInt(x, 10); \n });\n \n return regNos2;\n}", "function sort (expressions) {\n return expressions.slice().sort((a, b) => (a.start_pos < b.start_pos) ? -1 : 1)\n}", "function groupSort(groups) {\n groups = groups || [\n AlloyType.Signature,\n AlloyType.Atom,\n AlloyType.Field,\n AlloyType.Tuple,\n AlloyType.Skolem\n ];\n return (a, b) => {\n return groups.indexOf(a.expressionType()) - groups.indexOf(b.expressionType());\n };\n }", "function sortAlphaNumopen(a, b) \r\n {\r\n var aA = a.replace(reA, \"\");\r\n var bA = b.replace(reA, \"\");\r\n if (aA === bA) \r\n {\r\n var aN = parseInt(a.replace(reN, \"\"), 10);\r\n var bN = parseInt(b.replace(reN, \"\"), 10);\r\n return aN === bN ? 0 : aN > bN ? 1 : -1;\r\n } \r\n else \r\n {\r\n return aA > bA ? 1 : -1;\r\n }\r\n }", "function alphaSort (arr){\n\n return arr.sort()\n\n}", "function Numsort(a,b) { return a - b; }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An event listener to start card entry flow
async onStartCardEntry() { const cardEntryConfig = { collectPostalCode: false, }; //callback to start card entry await SQIPCardEntry.startCardEntryFlow( cardEntryConfig, this.onCardNonceRequestSuccess, this.onCardEntryCancel, ); }
[ "addcard(){\n console.log(\"enter details pressed\");\n Actions.addcard();\n }", "addCardClickHandler() {\n this.deckElement.addEventListener('click', (event) => {\n if (event.target.className === 'card') {\n const card = event.target;\n deck.run(card);\n }\n });\n }", "function StartCardReader(){\r\n app.startCardReader();\r\n}", "function trackCard() {\n if (!$scope.userPlan || !$scope.selectedPlan ||\n !$scope.userPlan.name || !$scope.selectedPlan.name) {\n return;\n }\n var evtData = {\n currentPlan: $scope.userPlan.name,\n selectedPlan: $scope.selectedPlan.name\n };\n creditCardCompletionMonitor.track('EnterCard', evtData);\n }", "onEnter(event) {\r\n if (event.charCode === 13) {\r\n this.onAddCard();\r\n }\r\n }", "addHandCardNodeEvent (cardInstance) {\n cardInstance.fetchNode().on('click', () => {\n //returns card name to prompt\n this.renderPrompt(`you selected <span class='orange'> ${cardInstance.fetchNode().attr('data-name')} </span> `);\n //returns card object to global selection monitor \n this.currentCard = this.players['1'].hand.find(handCardInstance => handCardInstance.nodeID === cardInstance.fetchNode().attr('id'));\n this.checkTurnCompletion();\n });\n }", "onCardReceived(card, source) {\n \n }", "function startListening() {\n\tconst allCards = Array.prototype.slice.call(document.querySelectorAll(\".card\"));\n\tfor (let i=0; i<allCards.length; i++) {\n\t\tallCards[i].addEventListener(\"click\", respondToTheClick);\n\t}\n\t// showTimer();\n}", "function handleCardClick() {\n cardClickBehaviour(this);\n }", "function addListener() {\n flipContainer.addEventListener('click', clickCard);\n flipContainer.addEventListener('keypress', clickCard);\n }", "function evtListener() {\n debug(\"evtListener\");\n cards().forEach(function(node) {\n node.addEventListener('click', cardMagic);\n })\n }", "cardOnClickEvent(card, e) {\n // [TODO] Introduce a dialogue window to allow players to choose which action\n // they'd like to use the card for (bank it, play it)\n switch (card.type) {\n case \"money\":\n this.game.network.moveCardFromHandToBank(card);\n break;\n case \"property\":\n this.game.network.moveCardFromHandToProperties(card);\n break;\n case \"action\":\n this.game.network.moveCardFromHandToDiscard(card);\n break;\n }\n }", "function startButton() {\r\n gameStarted = true;\r\n setTurnColor();\r\n addCardEvents();\r\n}", "function addCardEvents() {\r\n for(let index = 0; index < cards.length; index++)\r\n {\r\n cards[index].addEventListener(\"click\", function() {\r\n discoverCard(index);\r\n });\r\n }\r\n}", "handleCardClick (card) {\n switch (card.source) {\n case CARDSOURCE_METADATA:\n this.trackMetadataCardClick(card);\n this.metadataDispatcher.logCardClick(card.id);\n break;\n case CARDSOURCE_CUSTOM:\n this.trackCustomCardClick(card);\n break;\n default:\n throw new Error('Invalid card source type');\n }\n }", "function handleStart() {\n console.log(\"handleStart called.\");\n\n $('.board').on('click', '.js-start-button', \n event => {\n console.log('js-start-button clicked.');\n renderBoard(BOARD_TYPE.QUESTION);\n });\n}", "function onEnableCards(e) {\n\t\tuserInterface.enableRestartBtn();\n\n\t\tcards.forEach(card => {\n\t\t\tcard.enableMe();\n\t\t});\n\n\t\t// If game is resetting or over reset the card positions and run start game\n\t\tif (currentState == gameState.resetting || currentState == gameState.over) {\n\t\t\tcardCount++;\n\n\t\t\tif (cardCount == 17) {\n\t\t\t\tcardCount = 1;\n\t\t\t\tresetCardPositions();\n\t\t\t\tonStartGame(e);\n\t\t\t}\n\t\t}\n\t}", "function getClickedCards() {\n document.getElementById(\"deck\").addEventListener(\"click\", showCard);\n}", "continueCards() {\n this.$emit('continue-cards');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function provides the recursion and is synchronous May not be strictly needed as aliases are supposedly without chains
recurseAlias(tag) { //This is for if recursive alias retrieval has already gotten the alias if (tag in this.tag_aliases) { return;} this.async_requests++; const resp = $.getJSON('/tag_aliases',{'search':{'antecedent_name':tag}},data=>{ //Only process active aliases if ((data.length > 0) && (data[0].status == 'active')) { let consequent = data[0].consequent_name; this.tag_aliases[tag] = consequent; //Add negative of applicable consequents to assist with tag replacements later on if (this.isNegative(tag)) { this.negative_list.push(consequent); } this.recurseAlias(consequent); } }).always(()=>{ this.async_requests--; }); }
[ "function recurse(list, out, level) {\n if (level >= 256) throw \"Plug-in alias recursion detected.\";\n list = list.filter(pred);\n list.forEach(function (name) {\n const alias = aliases[name];\n if (!alias) {\n out.push(name);\n } else {\n out = out.concat(recurse(alias, [], level + 1));\n }\n });\n return out;\n }", "function recurse(list, out, level) {\n if (level >= 256) throw \"Plug-in alias recursion detected.\";\n list = _.filter(list, filter);\n _.each(list, function (name) {\n var alias = aliases[name];\n if (!alias) {\n out.push(name);\n }\n else {\n out = out.concat(recurse(alias, [], level + 1));\n }\n });\n return out;\n }", "visitAlias(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "printIndirects() {\n const storage = this.storage;\n let all = [];\n let length = Object.keys(storage).length;\n\n /// Inner recursion to create all permutations for indirect relationships\n const generateIndirect = (total, node, currentArr) => {\n currentArr.push(node);\n let keys = Object.keys(storage[node[0]][node].edges);\n\n //Push when there's no more indirect or when max jump hits 5\n if (currentArr.length === 6 || !keys.length || keys.every(elem => currentArr.indexOf(elem) > -1)) {\n all.push(currentArr);\n return;\n }\n for (let i = 0; i < keys.length; i++) {\n if (currentArr.indexOf(keys[i]) >= 0) {\n continue;\n } else {\n generateIndirect(total, keys[i], currentArr.concat());\n }\n }\n }\n for (let node in storage) {\n for (let name in storage[node]){\n generateIndirect(all, name, []);\n }\n }\n return all;\n }", "[_resolveLinks] () {\n for (const link of this[_linkNodes]) {\n this[_linkNodes].delete(link)\n\n // link we never ended up placing, skip it\n if (link.root !== this.idealTree) {\n continue\n }\n\n const tree = this.idealTree.target\n const external = !link.target.isDescendantOf(tree)\n\n // outside the root, somebody else's problem, ignore it\n if (external && !this[_follow]) {\n continue\n }\n\n // didn't find a parent for it or it has not been seen yet\n // so go ahead and process it.\n const unseenLink = (link.target.parent || link.target.fsParent) &&\n !this[_depsSeen].has(link.target)\n\n if (this[_follow] &&\n !link.target.parent &&\n !link.target.fsParent ||\n unseenLink) {\n this.addTracker('idealTree', link.target.name, link.target.location)\n this[_depsQueue].push(link.target)\n }\n }\n\n if (this[_depsQueue].length) {\n return this[_buildDepStep]()\n }\n }", "function getAliasMap(node, parentAliasMap) {\n\t var applicationName = node.getApplicationName();\n\t var hash = node.getShallowHash();\n\t var children = parentAliasMap.children;\n\t\n\t if (!children.hasOwnProperty(applicationName)) {\n\t children[applicationName] = {\n\t children: {},\n\t hash: hash\n\t };\n\t } else if (children[applicationName].hash !== hash) {\n\t console.error('`%s` is used as an alias more than once. Please use unique aliases.', applicationName);\n\t }\n\t return children[applicationName];\n\t }", "visitAliasName(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getAliasMap(node, parentAliasMap) {\n\t var applicationName = node.getApplicationName();\n\t var hash = node.getShallowHash();\n\t var children = parentAliasMap.children;\n\n\t if (!children.hasOwnProperty(applicationName)) {\n\t children[applicationName] = {\n\t children: {},\n\t hash: hash\n\t };\n\t } else if (children[applicationName].hash !== hash) {\n\t console.error('`%s` is used as an alias more than once. Please use unique aliases.', applicationName);\n\t }\n\t return children[applicationName];\n\t }", "function resolveAlias(name) {\n var aliasInfo = null;\n var xname = name;\n while ((aliasInfo = aliases.get(xname)) != null && xname !== aliasInfo.name) {\n xname = aliasInfo.name;\n } \n if (xname !== name) {\n //console.log(\"resolve alias final: \" + name + \" -> \" + xname); \n }\n return xname;\n}", "linkChain() {\n for (const arg in arguments) {\n try{\n if (shortid.isValid(arguments[arg][0].id) && shortid.isValid(arguments[arg][0].id)){\n this.linkNext(arguments[arg][0].id, arguments[arg][1].id);\n }\n else if(shortid.isValid(arguments[arg][0]) && shortid.isValid(arguments[arg][0])){\n this.linkNext(arguments[arg][0], arguments[arg][1]);\n }\n else {\n throw new Error(`FLOWMAP :: LINKCHAIN :: Argumento ${arguments[arg][0]} e ${arguments[arg][1]} deve ser do mesmo tipo. Aceita 'Node'(object) ou 'id'(string)`)\n }\n }\n catch(e) {\n console.log(e);\n\n // console.log(`FLOWMAP :: LINKCHAIN :: Error conectando os nodes ${arguments[arg][0]} e ${arguments[arg][1]}`);\n }\n }\n }", "referenceWalk(expression, extension) {\n let path;\n let refs = new Set();\n if (extension === undefined || !extension(expression)) {\n const children = expression.children;\n if (expression.type === expressionType_1.ExpressionType.Accessor) {\n const prop = children[0].value;\n if (children.length === 1) {\n path = prop;\n }\n if (children.length === 2) {\n ({ path, refs } = this.referenceWalk(children[1], extension));\n if (path !== undefined) {\n path = path.concat('.', prop);\n }\n // if path is null we still keep it null, won't append prop\n // because for example, first(items).x should not return x as refs\n }\n }\n else if (expression.type === expressionType_1.ExpressionType.Element) {\n ({ path, refs } = this.referenceWalk(children[0], extension));\n if (path !== undefined) {\n if (children[1] instanceof constant_1.Constant) {\n const cnst = children[1];\n if (cnst.returnType === ReturnType.String) {\n path += `.${cnst.value}`;\n }\n else {\n path += `[${cnst.value}]`;\n }\n }\n else {\n refs.add(path);\n }\n }\n const result = this.referenceWalk(children[1], extension);\n const idxPath = result.path;\n const refs1 = result.refs;\n refs = new Set([...refs, ...refs1]);\n if (idxPath !== undefined) {\n refs.add(idxPath);\n }\n }\n else if (expression.type === expressionType_1.ExpressionType.Foreach ||\n expression.type === expressionType_1.ExpressionType.Where ||\n expression.type === expressionType_1.ExpressionType.Select) {\n let result = this.referenceWalk(children[0], extension);\n const child0Path = result.path;\n const refs0 = result.refs;\n if (child0Path !== undefined) {\n refs0.add(child0Path);\n }\n result = this.referenceWalk(children[2], extension);\n const child2Path = result.path;\n const refs2 = result.refs;\n if (child2Path !== undefined) {\n refs2.add(child2Path);\n }\n const iteratorName = children[1].children[0].value;\n var nonLocalRefs2 = Array.from(refs2).filter((x) => !(x === iteratorName || x.startsWith(iteratorName + '.') || x.startsWith(iteratorName + '[')));\n refs = new Set([...refs, ...refs0, ...nonLocalRefs2]);\n }\n else {\n for (const child of expression.children) {\n const result = this.referenceWalk(child, extension);\n const childPath = result.path;\n const refs0 = result.refs;\n refs = new Set([...refs, ...refs0]);\n if (childPath !== undefined) {\n refs.add(childPath);\n }\n }\n }\n }\n return { path, refs };\n }", "optimizeAliasesOrder() {\n\t\t\tthis.aliases.sort((a, b) => {\n\t\t\t\tlet c = addSlashes(b.path).split(\"/\").length - addSlashes(a.path).split(\"/\").length;\n\t\t\t\tif (c == 0) {\n\t\t\t\t\t// Second level ordering (considering URL params)\n\t\t\t\t\tc = a.path.split(\":\").length - b.path.split(\":\").length;\n\t\t\t\t}\n\n\t\t\t\tif (c == 0) {\n\t\t\t\t\tc = a.path.localeCompare(b.path);\n\t\t\t\t}\n\n\t\t\t\treturn c;\n\t\t\t});\n\t\t}", "visitNamespaceAlias(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function expandRefs(refs) {\n refs = _cloneJSON(refs);\n Object.keys(refs).forEach(function(key) {\n var ref = refs[key];\n if (ref.aliasOf) {\n var obj = ref,\n lastKey = key;\n while (obj && refs[obj.aliasOf]) {\n lastKey = obj.aliasOf;\n obj = refs[lastKey];\n }\n }\n if (obj && key !== lastKey) {\n obj.aliases = obj.aliases || [];\n obj.aliases.push(key);\n }\n });\n\n Object.keys(refs).forEach(function(key) {\n var ref = refs[key];\n var versions = ref.versions\n if (versions) {\n Object.keys(versions).forEach(function(subKey) {\n var ver = versions[subKey];\n if (ver.aliasOf) {\n refs[key + '-' + subKey] = ver;\n } else {\n var obj = {\n versionOf: key\n };\n // Props fallback to main entry.\n _copyProps(ref, obj);\n _copyProps(ver, obj);\n delete obj.versions;\n delete obj.obsoletes;\n refs[key + '-' + subKey] = obj;\n }\n });\n if (ref.aliases) {\n ref.aliases.forEach(function(aliasKey) {\n Object.keys(versions).forEach(function(subKey) {\n // Watch out not to overwrite existing aliases.\n if (!refs[aliasKey + '-' + subKey]) {\n refs[aliasKey + '-' + subKey] = { aliasOf: key + '-' + subKey };\n }\n });\n });\n }\n }\n });\n return refs;\n}", "_setChildren(item,data){// find all children\nconst children=data.filter(d=>item.id===d.parent);item.children=children;if(0<item.children.length){item.children.forEach(child=>{// recursively call itself\nthis._setChildren(child,data)})}}", "function printMemberChain(path,options,print){// The first phase is to linearize the AST by traversing it down.\n//\n// a().b()\n// has the following AST structure:\n// CallExpression(MemberExpression(CallExpression(Identifier)))\n// and we transform it into\n// [Identifier, CallExpression, MemberExpression, CallExpression]\nvar printedNodes=[];function rec(path){var node=path.getValue();if(node.type===\"CallExpression\"&&isMemberish(node.callee)){printedNodes.unshift({node:node,printed:comments$3.printComments(path,function(){return concat$2([printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)]);},options)});path.call(function(callee){return rec(callee);},\"callee\");}else if(isMemberish(node)){printedNodes.unshift({node:node,printed:comments$3.printComments(path,function(){return node.type===\"MemberExpression\"?printMemberLookup(path,options,print):printBindExpressionCallee(path,options,print);},options)});path.call(function(object){return rec(object);},\"object\");}else{printedNodes.unshift({node:node,printed:path.call(print)});}}// Note: the comments of the root node have already been printed, so we\n// need to extract this first call without printing them as they would\n// if handled inside of the recursive call.\nprintedNodes.unshift({node:path.getValue(),printed:concat$2([printFunctionTypeParameters(path,options,print),printArgumentsList(path,options,print)])});path.call(function(callee){return rec(callee);},\"callee\");// Once we have a linear list of printed nodes, we want to create groups out\n// of it.\n//\n// a().b.c().d().e\n// will be grouped as\n// [\n// [Identifier, CallExpression],\n// [MemberExpression, MemberExpression, CallExpression],\n// [MemberExpression, CallExpression],\n// [MemberExpression],\n// ]\n// so that we can print it as\n// a()\n// .b.c()\n// .d()\n// .e\n// The first group is the first node followed by\n// - as many CallExpression as possible\n// < fn()()() >.something()\n// - then, as many MemberExpression as possible but the last one\n// < this.items >.something()\nvar groups=[];var currentGroup=[printedNodes[0]];var i=1;for(;i<printedNodes.length;++i){if(printedNodes[i].node.type===\"CallExpression\"){currentGroup.push(printedNodes[i]);}else{break;}}for(;i+1<printedNodes.length;++i){if(isMemberish(printedNodes[i].node)&&isMemberish(printedNodes[i+1].node)){currentGroup.push(printedNodes[i]);}else{break;}}groups.push(currentGroup);currentGroup=[];// Then, each following group is a sequence of MemberExpression followed by\n// a sequence of CallExpression. To compute it, we keep adding things to the\n// group until we has seen a CallExpression in the past and reach a\n// MemberExpression\nvar hasSeenCallExpression=false;for(;i<printedNodes.length;++i){if(hasSeenCallExpression&&isMemberish(printedNodes[i].node)){// [0] should be appended at the end of the group instead of the\n// beginning of the next one\nif(printedNodes[i].node.computed&&isLiteral(printedNodes[i].node.property)){currentGroup.push(printedNodes[i]);continue;}groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}if(printedNodes[i].node.type===\"CallExpression\"){hasSeenCallExpression=true;}currentGroup.push(printedNodes[i]);if(printedNodes[i].node.comments&&printedNodes[i].node.comments.some(function(comment){return comment.trailing;})){groups.push(currentGroup);currentGroup=[];hasSeenCallExpression=false;}}if(currentGroup.length>0){groups.push(currentGroup);}// There are cases like Object.keys(), Observable.of(), _.values() where\n// they are the subject of all the chained calls and therefore should\n// be kept on the same line:\n//\n// Object.keys(items)\n// .filter(x => x)\n// .map(x => x)\n//\n// In order to detect those cases, we use an heuristic: if the first\n// node is just an identifier with the name starting with a capital\n// letter, just a sequence of _$ or this. The rationale is that they are\n// likely to be factories.\nvar shouldMerge=groups.length>=2&&!groups[1][0].node.comments&&groups[0].length===1&&(groups[0][0].node.type===\"ThisExpression\"||groups[0][0].node.type===\"Identifier\"&&groups[0][0].node.name.match(/(^[A-Z])|^[_$]+$/));function printGroup(printedGroup){return concat$2(printedGroup.map(function(tuple){return tuple.printed;}));}function printIndentedGroup(groups){if(groups.length===0){return\"\";}return indent$2(group$1(concat$2([hardline$2,join$2(hardline$2,groups.map(printGroup))])));}var printedGroups=groups.map(printGroup);var oneLine=concat$2(printedGroups);var cutoff=shouldMerge?3:2;var flatGroups=groups.slice(0,cutoff).reduce(function(res,group){return res.concat(group);},[]);var hasComment=flatGroups.slice(1,-1).some(function(node){return hasLeadingComment(node.node);})||flatGroups.slice(0,-1).some(function(node){return hasTrailingComment(node.node);})||groups[cutoff]&&hasLeadingComment(groups[cutoff][0].node);// If we only have a single `.`, we shouldn't do anything fancy and just\n// render everything concatenated together.\nif(groups.length<=cutoff&&!hasComment&&// (a || b).map() should be break before .map() instead of ||\ngroups[0][0].node.type!==\"LogicalExpression\"){return group$1(oneLine);}var expanded=concat$2([printGroup(groups[0]),shouldMerge?concat$2(groups.slice(1,2).map(printGroup)):\"\",printIndentedGroup(groups.slice(shouldMerge?2:1))]);// If there's a comment, we don't want to print in one line.\nif(hasComment){return group$1(expanded);}// If any group but the last one has a hard line, we want to force expand\n// it. If the last group is a function it's okay to inline if it fits.\nif(printedGroups.slice(0,-1).some(willBreak)){return group$1(expanded);}return concat$2([// We only need to check `oneLine` because if `expanded` is chosen\n// that means that the parent group has already been broken\n// naturally\nwillBreak(oneLine)?breakParent$2:\"\",conditionalGroup$1([oneLine,expanded])]);}", "function getAliasMap(node, parentAliasMap) {\n var applicationName = node.getApplicationName();\n var hash = node.getShallowHash();\n var children = parentAliasMap.children;\n\n if (!children.hasOwnProperty(applicationName)) {\n children[applicationName] = {\n children: {},\n hash: hash\n };\n } else if (children[applicationName].hash !== hash) {\n console.error('`%s` is used as an alias more than once. Please use unique aliases.', applicationName);\n }\n return children[applicationName];\n }", "spiderChildren(item,data,start,end,parent,parentFound,noDynamicLevel){// see if we have the parent... or keep going\nif(item.id===parent||parentFound){// set parent to current so it's gaurenteed to match on next one\nif(!parentFound){parentFound=!0;// support sliding scales, meaning that start / end is relative to active\nif(!noDynamicLevel&&item.indent>=start){start+=item.indent;end+=item.indent}}// only add on what we're between\nif(item.indent>=start&&item.indent<=end){data.push(item)}// we've found it. Now everyone below here should match\nif(0<item.children.length){item.children.forEach(child=>{// recursively call itself\nthis.spiderChildren(child,data,start,end,parent,parentFound,noDynamicLevel)})}}else{if(0<item.children.length){item.children.forEach(child=>{// recursively call itself\nthis.spiderChildren(child,data,start,end,parent,parentFound,noDynamicLevel)})}}}", "dealias(path, history) {\n\n history = history || [];\n\n if (history.length >= 10) {\n throw new Error('Followed 10 aliases, possible infinite loop');\n }\n\n // Follow aliases to real provider\n for (let prefix of Object.getOwnPropertyNames(this.aliases)) {\n\n if (path.startsWith(prefix)) {\n\n var next = path.replace(prefix, this.aliases[prefix]);\n\n if (history.indexOf(next) > -1) {\n throw new Error('Alias loop detected: ' + history);\n }\n\n history.push(next);\n\n return this.dealias(path.replace(prefix, this.aliases[prefix]), history);\n\n }\n\n }\n\n return path;\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for pagininating userRailActivity results
function userRailActivity(page_no, results_per_page) { $('#user_rail_activity_container').load('/opengraph/paginateUserRailActivity', { page_no: page_no, results_per_page: results_per_page }); }
[ "function userRailActivityLog(page_no, results_per_page) {\n $('#activity_box').load('/opengraph/paginateUserRailActivityLog', {\n page_no: page_no, \n results_per_page: results_per_page\n });\n}", "function pagination(data) {\n $(\"#userPaging\").empty();\n\n var li = \"\";\n\n for (index = 0; index < data.total; index++) {\n var isActive = data.start-1 == index ? 'active' : '';\n\n if (isActive != \"\") {\n li = li + \"<li><a href='#' class=\" + isActive + \">\" + Number(index + 1) + \"</a></li>\";\n } else {\n li = li + \"<li><a href='#' onClick='getUsers(\" + Number(index + 1)+ \")'>\" + Number(index + 1) + \"</a></li>\";\n }\n\n }\n if (data.start < data.total - 1) {\n li = li + \"<li><a href='#' onClick='getUsers(\" + Number(data.start + 1) + \")'>Next <i class='fa fa-angle-double-right' aria-hidden='true'></i></a></li>\";\n } else {\n li = li + \"<li><a href='#' >Next <i class='fa fa-angle-double-right' aria-hidden='true'></i></a></li>\";\n }\n\n $(\"#userPaging\").append(li);\n\n}", "function paginate() {\r\n // determine which results to show on the current page\r\n let pageStart = (currentPage - 1) * RESULTS_PER_PAGE;\r\n let pageEnd = pageStart + RESULTS_PER_PAGE;\r\n pagedResults = fullResults.slice(pageStart, pageEnd);\r\n // calcalate the total number of pages\r\n numOfPages = Math.ceil(fullResults.length / RESULTS_PER_PAGE);\r\n}", "function pagination() {\n if(paginationRequired()) {\n console.log(`There are ${totalItems} results`)\n makePagButtons();\n }\n }", "function pagingForAllResults() {\n return \"page=1&pageSize=0\";\n}", "function pagination() {\n\n let result = list.slice(startIndex, endIndex);\n return result;\n }", "function paginate() {\n if (self.hasMore()) {\n self.paginate(options);\n } else {\n if (success) {\n success(self, options);\n }\n if (complete) {\n complete(self, options);\n }\n }\n }", "displayRecordByPage() {\n this.showSpinner = true;\n this.startingRecord = (this.currentPage - 1) * this.pageSize;\n this.endingRecord = this.pageSize * this.currentPage;\n\n this.endingRecord =\n this.endingRecord > this.totalRecountCount\n ? this.totalRecountCount\n : this.endingRecord;\n\n this.data = this.items.slice(this.startingRecord, this.endingRecord);\n this.showSpinner = false;\n }", "getActivitiesPage(pageNum) {\n\n // logger.debug(\"got: \" + res.map(activity => activity.id))\n return res\n }", "function makePagination(data) {\n pagination(data,'load');\n}", "function nextTenResults(value){\n adjustPageCounter(value)\n showPagination()\n fetchImgs()\n}", "getUserRecords(startIDX,endIDX)\n {\n console.log(`startIDX=${startIDX}, endIDX=${endIDX}`);\n this.usersService.getUserRecordsForPagination(startIDX,endIDX)\n .then(response => response.json())\n .then(data => {\n console.log(data);\n this.userRecordCount = data.recordCount;\n this.userRecords = data.users;\n });\n }", "getPublishsByCampaignIdPagination(data){\nreturn this.post(Config.API_URL + Constant.PUBLISH_GETPUBLISHSBYCAMPAIGNIDPAGINATION, data);\n}", "function paginate(param) {\n $('.' + itemClassName).hide() //hide all items\n for (let i = param.start; i <= param.stop; i++) {\n $('.' + itemClassName + '-' + i).show() // show items within the page boundary\n }\n\n // shown page details eg. items-boundary in page total\n if (data.pageDetail === true) {\n $('.crumbDetail-' + autoBtnClass).html('<p>showing items ' + param.start + ' - ' + param.stop + ' of ' + itemCount + '</p>')\n }\n }", "function pagination() {\n let addedToList = list.slice(startIndex, endIndex);\n return addedToList; \n }", "getNextUsers(event) {\n if (this.serchValue) {\n this.page += 1;\n this.getUsers(event);\n }\n }", "function _requestPaginatedScreenData() {\n isScreenPaginationRequested.current = true;\n CoreRequestService.cmwNextGet(nextVerticallyPaginatedRibbonsUrl, {\n paging: true\n }).then(function (results) {\n if (_completeLoad(screenId)) loadMoreRibbons(results);\n })[\"catch\"](function () {\n if (!_completeLoad(screenId)) return;\n CoreErrorService.reportPlatformError({\n error_key: _app[\"default\"].SCREENS.ERROR_CMW_FAILED_LOADING\n });\n })[\"finally\"](function () {\n isScreenPaginationRequested.current = false;\n _completeLoad(screenId) && setTriggerPaginationEffect(!triggerPaginationEffect);\n });\n }", "function userlist_slice(number) {\n const startindex = (number - 1) * PerPageNum;\n //console.log(startindex);\n return users.slice(startindex, startindex + PerPageNum);\n}", "loadNext() {\n if (this.nextResults === true) {\n this.page++;\n this.refresh();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set styles of body background color, font style, image selection, and paragraph font color using the getItem() method to retrieve their values from local storage.
function setStyles() { let currentBgColor = localStorage.getItem('bgcolor'); let currentFont = localStorage.getItem('fontfamily'); let currentImage = localStorage.getItem('image'); let currentFontColor = localStorage.getItem('fontcolor'); document.getElementById('bgcolor').value = currentBgColor; document.getElementById('font').value = currentFont; document.getElementById('image').value = currentImage; document.getElementById('fontcolor').value = currentFontColor; document.querySelector('.font-color').value = currentFontColor; htmlElem.style.backgroundColor = '#' + currentBgColor; pElem.style.fontFamily = currentFont; fontStyleElem.style.color = '#' + currentFontColor; imageElem.setAttribute('src', currentImage); }
[ "function checkStyles(){\r\n\tdocument.body.style.backgroundColor = localStorage.getItem(\"backgroundColour\");\r\n\tdocument.body.style.color = localStorage.getItem(\"fontColour\");\r\n\tdocument.body.style.fontSize = localStorage.getItem(\"fontSize\");\r\n\t\r\n}", "storeStyles( pStyles ){\r\n \r\n var props = pStyles;\r\n var prefs = {\r\n fontFamily : props.fontFamily,\r\n fontSize : props.fontSize,\r\n lineHeight: props.lineHeight,\r\n margin : props.margin,\r\n theme : props.theme \r\n };\r\n \r\n window.localStorage.setItem(this.localStorageKey,\r\n JSON.stringify( prefs ));\r\n }", "function addEntryContent() {\n let bg;\n\n if (redBtn.classList.contains('selected')) {\n bg = 'rgb(240, 217, 217)'\n }\n else if (blueBtn.classList.contains('selected')) {\n bg = 'rgb(214, 227, 240)'\n }\n else if (yellowBtn.classList.contains('selected')) {\n bg = 'rgb(247, 240, 204)'\n }\n else if (greyBtn.classList.contains('selected')) {\n bg = 'rgb(80, 80, 80)'\n }\n else if (greenBtn.classList.contains('selected')) {\n bg = 'rgb(214, 240, 234)'\n }\n\n storageArr.push({subject: subjectArea.value, text: entryArea.value, time: new Date().toLocaleString(), color: bg})\n localStorage.setItem('localItems', JSON.stringify(storageArr)) \n}", "function loadInPalettes(){\n\t\n\tvar colorCodeItems = null;\n\t\n\t//if list exists in storage:\n\tif(localStorage.getItem(\"TaskList\")!= null){\n\t\t\n\t\t//retrieve task list in storage\n\t\ttaskArray = JSON.parse(localStorage.getItem(\"TaskList\"));\n\t\t\n\t\t//get html list items, from class name colorcode\n\t\tcolorCodeItems = document.getElementsByClassName(\"colorcode\");\n\t\t\n\t\t//loop through task array of objects\n\t\tfor( var x = 0; x < taskArray.length; x++){\n\t\t\t\n\t\t\t//store current object\n\t\t\tvar currentObject = taskArray[x];\n\t\t\t\n\t\t\t//store current color code\n\t\t\tvar currentObjectColor = currentObject[\"colorcode\"];\n\t\t\t\n\t\t\t//store current html element\n\t\t\tvar currentHtml = colorCodeItems[x];\n\t\t\t\n\t\t\t//set current html elements background color to currentObjectColor\n\t\t\tcurrentHtml.style.backgroundColor = currentObjectColor; \n\t\t\t\n\t\t}\n\t}\n}", "function applyStyleOnLoad() {\n addDefaulsStyles(); // add FMG system styles to localStorage\n svg.select(\"defs\").append(\"style\").text(armiesStyle()); // add armies style\n\n const preset = localStorage.getItem(\"presetStyle\");\n const style = preset ? localStorage.getItem(preset) : null;\n\n if (preset && style && JSON.isValid(style)) {\n applyStyle(JSON.parse(style));\n updateMapFilter();\n loadDefaultFonts();\n stylePreset.value = preset;\n stylePreset.dataset.old = preset;\n } else {\n stylePreset.value = \"styleDefault\";\n stylePreset.dataset.old = preset;\n applyDefaultStyle();\n }\n}", "function setari() {\n localStorage.setItem('fontsize', document.getElementById('fontInput').value);\n localStorage.setItem('bgcolor', document.getElementById('colorInput').value);\n fonload();\n}", "function loadTheme(){\n checkLanguage();\n changeLanguageLayout(localStorage.getItem('lang'));\n setStyleColor(localStorage.getItem('styleColor'));\n changeBodySkinColor(localStorage.getItem('bodyColor'));\n }", "function get_style()\n\t\t\t{\n\t\t\t\tif (window.localStorage.getItem(\"Style\"))\n\t\t\t\t{\n\t\t\t\t\tStyleValue = window.localStorage.getItem(\"Style\");\n\t\t\t\t\tconsole.log(\"get_style Style: \" + StyleValue);\n\t\t\t\t}\n\t\t\t\telse {get_style_();}\n\t\t\t}", "function updateStylesInDataStore() {\n var jsonString = JSON.stringify(elements.styles);\n localStorage['sunjer_styles'] = jsonString;\n}", "function applyFontSize() {\n // save the font size value to a key \"fontSize\" in the localStorage\n window.localStorage.setItem(\"fontSize\", slider.value);\n // get the saved fontSize value from the localStorage and apply it to the body of the html\n // basically sets the <body style=\"font-size:fontSize\"> html tags with the style changed\n document.body.style.fontSize = window.localStorage.getItem(\"fontSize\") + \"px\";\n}", "function setBG(){\r\n setBGBtn.style.borderLeft = '1px solid #4db6ac';\r\n generateBGBtn.style.borderLeft = '1px solid transparent';\r\n generateBGBtn.style.opacity = '.6'\r\n setBGBtn.style.opacity = '1'\r\n\r\n var categoryItems = Array.from(BGCategories.children)\r\n categoryItems.forEach(function(category){\r\n category.style.color = 'rgb(235, 235, 235)'\r\n category.style.fontWeight = '400'\r\n category.style.opacity = '.7'\r\n });\r\n\r\n localStorage.setItem('isBGSet', true)\r\n let BGInfo;\r\n\r\n if(localStorage.getItem('BGInfo') == null) {\r\n BGInfo = {category: 'Wallpapers', url: ''};\r\n } else {\r\n BGInfo = JSON.parse(localStorage.getItem('BGInfo'));\r\n }\r\n BGInfo.url = urlBG\r\n localStorage.setItem('BGInfo', JSON.stringify(BGInfo));\r\n notifModal('Current background set to default.')\r\n}", "function setBookmarkBackground()\n{\n\tvar color = document.getElementById(\"bookmarkscolorcode\").value;\n\tvar bookmarks = document.querySelectorAll(\".bookmark\");\n\tfor(var i=0;i<bookmarks.length;i++)\n\t{\n\t\tbookmarks[i].style.backgroundColor=color;\n\t}\n\tvar color_storage = JSON.parse(localStorage.getItem('colors'));\n\tif(color_storage===null)\n\t{\n\t\tcolor_storage=[];\n\t\tcolor_storage[1]=color;\n\t\tlocalStorage.setItem('colors',JSON.stringify(color_storage));\n\t}\n\telse\n\t{\n\t\tcolor_storage[1]=color;\n\t\tlocalStorage.setItem('colors',JSON.stringify(color_storage));\n\t}\n\n}", "function getStoragedStyles() {\n return new Promise((resolve, reject) => {\n try {\n AsyncStorage.getItem('STYLES', (error, result) => {\n if (error) {\n reject(Error(error))\n }\n if (result !== null) {\n resolve(JSON.parse(result))\n } else {\n const styles = {\n backgroundColor: 'rgb(0, 0 ,0)'\n }\n resolve(styles)\n }\n })\n } catch (err) {\n reject(Error(err))\n }\n })\n}", "function setItemBody() {\n item.body.getTypeAsync(\n function (result) {\n if (result.status == Office.AsyncResultStatus.Failed) {\n app.showNotification(result.error.message);\n }\n else {\n // Successfully got the type of item body.\n // Set data of the appropriate type in body.\n if (result.value == Office.MailboxEnums.BodyType.Html) {\n // Body is of HTML type.\n // Specify HTML in the coercionType parameter\n // of setSelectedDataAsync.\n item.body.setSelectedDataAsync(\n '<b> Kindly note we now open 7 days a week.</b>',\n {\n coercionType: Office.CoercionType.Html,\n asyncContext: { var3: 1, var4: 2 }\n },\n function (asyncResult) {\n if (asyncResult.status ==\n Office.AsyncResultStatus.Failed) {\n app.showNotification(result.error.message);\n }\n else {\n // Successfully set data in item body.\n // Do whatever appropriate for your scenario,\n // using the arguments var3 and var4 as applicable.\n app.showNotification(\"HTML text added.\");\n }\n });\n }\n else {\n // Body is of text type. \n item.body.setSelectedDataAsync(\n ' Kindly note we now open 7 days a week.',\n {\n coercionType: Office.CoercionType.Text,\n asyncContext: { var3: 1, var4: 2 }\n },\n function (asyncResult) {\n if (asyncResult.status ==\n Office.AsyncResultStatus.Failed) {\n app.showNotification(result.error.message);\n }\n else {\n // Successfully set data in item body.\n // Do whatever appropriate for your scenario,\n // using the arguments var3 and var4 as applicable.\n app.showNotification(\"Plain text added.\");\n }\n });\n }\n }\n });\n }", "[MUTATIONS.SET_DESCRIPTION_FONT_STYLE] (state, payload) {\n state.currentSlide.description.fontStyle = payload\n state.isCurrentSlideDirty = true\n }", "function loadStylesIntoelements() {\n if (localStorage['sunjer_styles']) {\n try {\n elements.styles = JSON.parse(localStorage['sunjer_styles']);\n }\n catch(e) {\n console.log(e);\n elements.styles = {};\n }\n }\n}", "function loadDefaultColor(){\n// check to see if our localStorage object has a key of bg-color:\t\n\tif (window.localStorage.getItem(\"bg-color\")){\n// then,load it into a variable, and change the background's CSS:\t\t\n\t\tvar savedColor = window.localStorage.getItem(\"bg-color\");\n \t$(\"body\").css(\"background-color\", savedColor);\n }\n} // => end of loadDefaultColor", "function updateAndSaveStyles() {\n style.innerHTML = (checkbox.checked) ? textarea.value : \"\";\n saveStyles();\n }", "function renderNewSave () {\n renderNewQuote();\n renderNewFont();\n \n var fontInfo = {\n fontFamily: currentFontFamily,\n fontLink: currentFontLink,\n }\n\n if (!localStorage.getItem(\"favorite\")){\n var fontArray=[];\n localStorage.setItem(\"favorite\", JSON.stringify(fontArray))\n }\n\n var storedFavorites = JSON.parse(localStorage.getItem(\"favorite\"));\n storedFavorites.push(fontInfo);\n localStorage.setItem(\"favorite\", JSON.stringify(storedFavorites));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ajax delete the configuration
function deleteConf($id){ if($id==""){ alert("Please select a configuration range to delete"); return false; }else if(confirm("Are you sure you want to delete the configuration?")) { $.ajax({ type: "POST", url: "../ajax_common.php", data: { 'id': $id, 'codeBlock': 'del_conf', }, success: function($succ){ if($succ==1){ $('#'+$id).closest('tr').remove(); $('.green, .red').hide(); }else{ alert("Cannot delete the selected configuration, Please try again."); $('.green, .red').hide(); } } }); } return false; }
[ "function configDelete(cfId, cfName, ev) {\n if (window.confirm(\"Delete '\" + cfName + \"'?\")) {\n var d = loadJSONDoc(cfId + \"/delete/\")\n d.addCallback(partial(alertConfigDelete, cfName, ev.src()));\n }\n}", "function deletePreviewConfiguration(url) {\n $http.delete(url).then(function (response) {\n // load the component editor after the configuration has been removed\n vm.changeSiteUrl($rootScope.siteUrl);\n console.log(url);\n });\n }", "function ajax_reportDelete() {\n var arr = getSelElementArr();\n var json_string = JSON.stringify( arr );\n // Changing ajax settings:\n var as = ajax_settings();\n as.url = \"/folders/ajax-report-delete\" + \"/\" + arr.id + \"/\"; // pk added to url as argument for decorator\n as.data = {\n client_request : json_string,\n csrfmiddlewaretoken: csrf_token\n };\n $.ajax( as );\n return false;\n}", "function loadDeleteConfigOk(confName,mainid,fileType,all){\n\tloading('show');\n\tif(all == true){\n\t\tvar qry = \"ConfigName=\"+confName+\"&MainId=\"+mainid;\n\t}else{\n\t\tvar qry = \"ConfigName=\"+confName+\"&MainId=\"+mainid+\"&FileType=\"+fileType;\n\t}\n\t$.ajax({\n url: \"http://\"+CURRENT_IP+\"/cgi-bin/Final/AutoCompleteCgiQuerry_withDb/querYCgi.fcgi\",\n\t\tdata : {\n\t\t\t\"action\": \"delete\",\n\t\t\t\"query\": qry\n\t\t},\n\t\tmethod: 'POST',\n proccessData: false,\n dataType: 'html',\n success: function(data) {\n\t\t\tif(data){\n alert(\"Configuration successfully deleted.\");\n }else{\n\t\t\t\talert(\"Something went wrong, config deletion failed.\");\n\t\t\t}\n\t\t\tloading('hide');\n\t\t\t$(\"#deleteConfig\").dialog(\"close\");\n\t\t}\n\t});\n}", "delete(arg) {\n return this.httpClient\n .url(`/endpoint_configurations/${arg.id}`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }", "function deleteajax(route, event, callback) {\n var obj = $(this);\n var datareponse;\n if (!event.id) {\n var id = null;\n } else {\n var id = event.id;\n }\n var dataAjax = {\n 'id': id, action: 'delete'\n };\n console.log(\"delete ajax\");\n $.ajax({\n async: false,\n url: Routing.generate(route),\n type: \"POST\",\n dataType: \"json\",\n data: dataAjax,\n success: function(reponse) {\n datareponse = reponse;\n\n },\n error: function(e) {\n console.log(e.message);\n datareponse = e.message;\n\n }\n });\n callback(datareponse);\n\n } //Eof:: fucntion remplirSelect", "function deletes(url, success){\n $.ajax({\n url: url,\n type: 'delete',\n contentType: false,\n processData: false,\n success: success,\n error: function (jqXhr, textStatus, errorMessage) {\n console.log(jqXhr)\n console.log(textStatus)\n console.log(errorMessage)\n }\n });\n}", "function ajax_folderDelete() {\n var arr = getSelElementArr();\n var json_string = JSON.stringify( arr );\n // Changing ajax settings:\n var as = ajax_settings();\n as.url = \"/folders/ajax-folder-delete\";\n as.data = {\n client_request : json_string,\n csrfmiddlewaretoken: csrf_token\n };\n $.ajax( as );\n return false;\n}", "function DeleteOption(data){\r\n\tvar stuid=$(data).attr(\"stuid\");\r\n\t$.post(\"delete.sarin\", {\r\n\t\tstu_id : stuid,\r\n\t}, function(data) {\r\n\t\tlists();\r\n\t\tListcombo();\r\n\t});\r\n}", "function delete_cad(id_cad){\n console.log(id_cad)\n $.ajax({\n url: '/jb/ajax/delete-cad/',\n data:{\n 'id_cad':id_cad,\n },\n dataType:'json',\n success:function(data){\n if (data.result){\n location.reload();\n console.log(data.result)\n }\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"Status: \" + textStatus); alert(\"Error: \" + errorThrown);\n }\n\n });\n }", "function deleteHoroscope(){\n $.ajax(\n {\n url: \"./deleteHoroscope.php\",\n method: 'DELETE',\n success: function(data){\n $(\".result\").html(data);\n }\n }\n );\n }", "deleteHttpEndpointConfig(arg) {\n return this.httpClient\n .url(`/reserved_domains/${arg.id}/http_endpoint_configuration`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }", "function delete_cad2d(id_cad2d){\n console.log(id_cad2d)\n $.ajax({\n url: '/jb/ajax/delete-cad2d/',\n data:{\n 'id_cad2d':id_cad2d,\n },\n dataType:'json',\n success:function(data){\n if (data.result){\n location.reload();\n console.log(data.result)\n }\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"Status: \" + textStatus); alert(\"Error: \" + errorThrown);\n }\n\n });\n }", "deleteEndpointConfig(arg) {\n return this.httpClient\n .url(`/reserved_addrs/${arg.id}/endpoint_configuration`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }", "function DeleteDevice (devId) {\n\tif (confirm(\"Удалить устройство из базы данных?\")){\n\t\t\t$.ajax({\n\t\t\t\tdataType : 'json',\n\t\t\t\ttype: 'DELETE',\n\t\t\t\turl : path + 'device/' + devId,\n\t\t\t\tsuccess : function(jsondata) {\n\t\t\t\t\t$('#'+devId).remove();\n\t\t\t\t},\n\t\t\t\terror : function(request, error) {\n\t\t\t\t\tconsole.log(arguments);\n\t\t\t\t\talert(\" Error: \" + error);\n\t\t\t\t},\n\t\t\t\tcomplete : function(data) {\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}", "function axiosDelete(url,config) {\n\treturn $nuxt.$axios.delete(url,config)\n}", "function delete_content()\n{\n\t// Setup variable\n\tvar checked\t= $('tbody').find('input[type=checkbox]:checked');\n\tvar url\t\t= URL_SERVER + $('#config_uri_delete').val();\n\tvar id\t\t= new Array();\n\t\n\tchecked.each(function(index) \n\t{\n\t\tid.push($(this).val());\n\t});\n\t\n\tvar data = {\n\t\t\t\t\t'id' : id\n\t\t\t };\n\t\n\t// Setup ajax\n\t$.post(url, data, function(response)\n\t{\n\t\tget_content();\n\t})\n\t.success(function() { $('#dialog_delete').dialog('close'); })\n\t.error(function() \n\t{ \n\t\tvar msg = 'Error: delete_content(' + url + ')';\n\t\t$('#dialog_alert_message').html(msg);\n\t\t$('#dialog_alert').dialog('open');\n\t});\n}", "function DeleteSensor(){\n\n if(!window.confirm(document.getElementById(\"hidMsgConfirmDelete\").value))\n return;\n \n //Prepare call url\n var idComboProcess = parseInt($(\"#cmbWorkflows\").val());\n var sUrl = _sensorEdit_AjaxGatewayUrl \n + \"?action=\" + _sensorEdit_AjaxActionCode \n + \"&idWorkflow=\" + idComboProcess\n + \"&op=delete\";\n\n //All sensor object members are atached to the url\n var oSensorToDelete = GetSelectedSensorCopy();\n jQuery.each(oSensorToDelete, function(keyName, keyValue) {\n sUrl += \"&\" + keyName + \"=\" + keyValue;\n });\n \n callAjaxMethod(sUrl, DeleteSensor_CallBack);\n}", "function delete_3mf(id_3mf){\n console.log(id_3mf)\n $.ajax({\n url: '/jb/ajax/delete-3mf/',\n data:{\n 'id_3mf':id_3mf,\n },\n dataType:'json',\n success:function(data){\n if (data.result){\n location.reload();\n console.log(data.result)\n }\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"Status: \" + textStatus); alert(\"Error: \" + errorThrown);\n }\n\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates current state with new comment
updateComment(event) { this.setState({ comment: event.target.value }); }
[ "_updateFromComment() {\n const oldComment = this.previous('comment');\n const comment = this.get('comment');\n\n if (oldComment) {\n oldComment.destroyIfEmpty();\n }\n\n if (comment) {\n const defaultRichText = this.defaults().richText;\n\n /*\n * Set the attributes based on what we know at page load time.\n *\n * Note that it is *possible* that the comments will have changed\n * server-side since loading the page (if the user is reviewing\n * the same diff in two tabs). However, it's unlikely.\n *\n * Doing this before the ready() call ensures that we'll have the\n * text and state up-front and that it won't overwrite what the\n * user has typed after load.\n *\n * Note also that we'll always want to use our default richText\n * value if it's true, and we'll fall back on the comment's value\n * if false. This is so that we can keep a consistent experience\n * when the \"Always edit Markdown by default\" value is set.\n */\n this.set({\n dirty: false,\n extraData: comment.get('extraData'),\n openIssue: comment.get('issueOpened') === null\n ? this.defaults().openIssue\n : comment.get('issueOpened'),\n requireVerification: comment.requiresVerification(),\n richText: defaultRichText || !!comment.get('richText'),\n });\n\n /*\n * We'll try to set the one from the appropriate text fields, if it\n * exists and is not empty. If we have this, then it came from a\n * previous save. If we don't have it, we'll fall back to \"text\",\n * which should be normalized content from the initial page load.\n */\n const textFields = (comment.get('richText') || !defaultRichText\n ? comment.get('rawTextFields')\n : comment.get('markdownTextFields'));\n\n this.set('text',\n !_.isEmpty(textFields)\n ? textFields.text\n : comment.get('text'));\n\n comment.ready({\n ready: this._updateState,\n }, this);\n }\n }", "addComment(postId, comment){\n let newComment = { ...comment, postId, id: uuid() }\n\n this.setState(state => ({\n comments: [ ...state.comments, newComment ]\n }));\n }", "function newComment() {\n const newComment = {\n name: nameInput.val(),\n title: titleInput.val(),\n content: commentInput.val()\n };\n console.log(newComment);\n comment = newComment;\n submitComment(comment);\n }", "handleAppendComment(id, comment) {\n this.setState(prevState => {\n const section = prevState.assignment.sections.custom.find(x => x.id == id);\n // Check if the section has an empty line, or doesn't end in a paragraph, and add the new comment\n // The rich text editor leaves <p><br></p> when all text is removed, or there is an empty line.\n if (section.value.endsWith(\"<p><br></p>\")) {\n // Remove <p><br></p> and add a new paragraph with the comment to the end\n section.value = section.value.substring(0, section.value.length - 11) + \"<p>\" + comment.text + \"</p>\";\n } else if (!section.value.endsWith(\"</p>\")) {\n // If the section's doesn't end with a paragraph, add a new paragraph with the comment\n section.value += \"<p>\" + comment.text + \"</p>\";\n } else {\n // Otherwise if it ends with a paragraph, apped the new comment in a span inside the last paragraph\n section.value = section.value.substring(0, section.value.length - 4) + \"<span> \" + comment.text + \"</span></p>\";\n }\n\n // Add comment to comments used in session\n prevState.commentsUsedInSession.push(comment.id);\n\n return prevState;\n });\n }", "async _requestState(comment, state) {\n await comment.ready();\n\n const oldIssueStatus = comment.get('issueStatus');\n\n comment.set('issueStatus', state);\n const rsp = await comment.save({\n attrs: ['issueStatus'],\n });\n\n this._notifyIssueStatusChanged(comment, rsp, oldIssueStatus);\n }", "addOrUpdateComment(state, comment) {\n if ((comment.Parent === comment.Post &&\n state.postMap[comment.Parent] == null) ||\n (comment.Parent !== comment.Post &&\n state.commentMap[comment.Parent] == null)) {\n // parent is not currently inserted yet, put into buffer\n state.commentBuffer.push(comment);\n return;\n }\n // comment already exists, no need to set child pointers of parents\n if (state.commentMap[comment.Hash] != null) {\n state.commentMap[comment.Hash].Score = comment.Score;\n state.commentMap[comment.Hash].Flag = comment.Flag;\n return;\n }\n if (comment.Parent === comment.Post) {\n if (!state.postMap[comment.Parent].ChildComments) {\n Vue.set(state.postMap[comment.Parent], ChildComments, {});\n }\n Vue.set(state.postMap[comment.Parent].ChildComments,\n comment.Hash, comment);\n } else {\n if (!state.commentMap[comment.Parent].ChildComments) {\n Vue.set(state.commentMap[comment.Parent], ChildComments, {});\n }\n Vue.set(state.commentMap[comment.Parent].ChildComments,\n comment.Hash, comment);\n }\n Vue.set(state.commentMap, comment.Hash, comment);\n }", "function updateComment() {\n\treturn {type: 'commentUpdate'}\n}", "addComment(comment) {\n if (comment.type === 'positive') {\n this.setState(prevState => prevState.posComments.push(comment));\n } else if (comment.type === 'negative') {\n this.setState(prevState => prevState.negComments.push(comment));\n }\n }", "_requestState(comment, state) {\n comment.ready({\n ready: () => {\n const oldIssueStatus = comment.get('issueStatus');\n\n comment.set('issueStatus', state);\n comment.save({\n attrs: ['issueStatus'],\n success: (comment, rsp) => {\n const rspComment = (rsp.diff_comment ||\n rsp.file_attachment_comment ||\n rsp.screenshot_comment ||\n rsp.general_comment);\n this.trigger('issueStatusUpdated', comment,\n oldIssueStatus, rspComment.timestamp);\n },\n });\n },\n });\n }", "commentChanged(event){\n\t\tthis.setState({\n\t\t\tcommentInput: event.target.value\n\t\t});\n\t}", "function createComment(state: State, author: ?string, text: ?string): State {\r\n\t\r\n\tlet newState = $.extend({}, state);\r\n\t\r\n\tif (!author || !text) {\r\n\t\treturn newState;\r\n\t}\r\n\r\n\tnewState.status = 'ok';\r\n\tvar newComment = new Comment(author, text);\r\n\tnewState.comments = newState.comments.set(newComment.id, newComment);\r\n\t\r\n\treturn newState;\r\n}", "componentWillReceiveProps(nextProps) {\n this.setState({\n comments: nextProps.comments,\n });\n }", "onUpdateComment(data) {\n const updateField = data.updateField;\n const comment = JSON.parse(data.comment);\n\n // replace old comment with the new one in the same index so it doesn't affect sorting order.\n let newComments = this.state.comments\n .update(this.state.comments.findIndex(c => c.id == comment.id), existingComment => comment);\n newComments = this.filterAndSort(newComments, this.state.sortSettings.comparator, this.state.commentFilter.filterFn);\n\n const serverResponse = this.onServerReplySuccess(\"comment update\", comment.id, updateField);\n\n if (this.state.commentFilter.filterName == null) {\n // the updateCache isn't created here as initial state sets it up and is recreated every time filter is cleared\n this.setState({\n comments: newComments,\n serverResponse: serverResponse\n });\n } else {\n // filter is on, cache the deleted comment so it can be merged back when filter is removed.\n this.setState({\n comments: newComments,\n serverResponse: serverResponse,\n updatedCommentsForCache: this.state.updatedCommentsForCache.set(comment.id, comment)\n });\n }\n\n if (updateField === 'reports') {\n const message = `+1 comment reported with \\'title ${comment.title}\\'`;\n this.notificationHandler.showNotification(message);\n } else {\n const message = `+1 updated comment with \\'title ${comment.title}\\'`;\n this.notificationHandler.showNotification(message);\n }\n }", "async handleAddComment(ev) {\n ev.preventDefault();\n const { content } = ev.target;\n const comment_content = content.value;\n\n const thoughtId = this.state.thoughtId;\n\n // Make POST request to server to add a post\n await ActionsService.postComment(thoughtId, comment_content);\n // Clear the comment input\n content.value = \" \";\n\n // Re-fetch the comments to update existing comments with the comment just posted\n const comments = await ActionsService.getComments(thoughtId);\n if (comments) {\n this.setState({\n comments,\n });\n }\n }", "selectComment(comment){\n this.setState({ selectedComment: comment });\n this.toggleComments();\n }", "updateNewCommentsData() {\n /**\n * List of new comments in the section. (\"New\" actually means \"unseen at the moment of load\".)\n *\n * @type {import('./Comment').default[]}\n */\n this.newComments = this.comments.filter((comment) => comment.isSeen === false);\n\n this.addNewCommentCountMetadata();\n }", "commentChanged(comment) {\n AppDispatcher.dispatch({\n actionType: ProductConstants.COMMENT_CHANGED,\n data: comment,\n });\n }", "function bwChangeStateComment( sId ) {\r\n var o = document.getElementById( sId );\r\n var jQNode = $jQ( o );\r\n var oComment = new bwClassComment( o, o.childNodes[0] )\r\n var bVisible = !oComment.visible;\r\n var sUserType = oComment.type;\r\n\r\n if ( bVisible ) {\r\n jQNode.children( '.articleBody:first' ).slideDown('fast');\r\n }\r\n else {\r\n jQNode.children( '.articleBody:first' ).slideUp( 'fast' );\r\n }\r\n \r\n if ( bVisible ) bwRemovePathList( '_bw_cI', oComment.nodeId ); else bwAppendPathList( '_bw_cI', oComment.nodeId );\r\n \r\n oComment.visible = bVisible;\r\n oComment.save();\r\n }", "async function updateCommentCache(comment) {\n var parent\n // Initial update for quick access\n toggleLoadStatus()\n parent = await expandComment(comment, 5)\n commentCache = parent.replies\n updateButtonDisplay()\n // Secondary update for larger number of comments\n if (commentCache.length == 5) {\n parent = await expandComment(comment, 20)\n commentCache = parent.replies\n updateButtonDisplay()\n }\n if (commentCache.length > 10) {\n parent = await expandComment(comment, maxReplies)\n commentCache = parent.replies\n updateButtonDisplay()\n }\n toggleLoadStatus()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles the browser mouseDown event and removes the pressed button from the activeCommands list.
mouseUp(event) { var button = event.which || event.button; delete this.activeCommands[button]; }
[ "mouseDown(event) {\n var button = event.which || event.button;\n this.activeCommands[button] = true;\n }", "static _HandleButtonDown(e) {\n if (!Mouse._button_down.includes(e.button))\n Mouse._button_down.push(e.button)\n }", "function handleMouseUp() {\n oscillator.disconnect(audioContext.destination);\n isMouseDown = false;\n buttons.forEach(button => button.classList.remove('active'));\n}", "keyUp(event) {\n var keyCode = event.which || event.keyCode;\n delete this.activeCommands[keyCode];\n }", "function onMouseDown(event) {\n if (event.shiftKey) {\n (0, _clearSelection2.default)();\n }\n}", "static mouseReleased() {\n UI.selected = null;\n }", "removeCommands () {\r\n this.commandHandler.removeAllListeners();\r\n }", "static mouseReleased() {\n Drag.selected = null;\n }", "function clearMouseDown() {\n globals.mouseDownCoords = undefined;\n if (globals.mouseDownNote) {\n var note = globals.mouseDownNote;\n globals.mouseDownNote = undefined;\n drawNote(note, globals.noteCanvas.getContext(\"2d\"));\n }\n if (globals.mouseDownNoteEdge) {\n var note = globals.mouseDownNoteEdge.note;\n globals.mouseDownNoteEdge = undefined;\n drawNote(note, globals.noteCanvas.getContext(\"2d\"));\n }\n }", "function onKeyDownHandler(e) {\n console.log(e.keyCode);\n switch (e.keyCode) {\n case 46: // delete\n console.log(\"delete\");\n var activeObject = canvas.getActiveObject();\n if (activeObject) {\n canvas.remove(activeObject);\n }\n window.sync();\n return;\n case 27:\n console.log(\"go back\");\n window.currentAction = drawComponents.selectButton;\n window.canvas.isDrawingMode = false;\n window.canvas.deactivateAll().renderAll();\n window.sync();\n return;\n }\n}", "function mouseUpHandler(e) {\n //middle button\n if (e.which == 2) {\n container.off(\"mousemove\");\n }\n }", "function mouseUpHandler(e) {\n //middle button\n if (e.which == 2) {\n container.off('mousemove');\n }\n }", "function mouseUpHandler(e){\n //middle button\n if (e.which == 2){\n container.off('mousemove');\n }\n }", "function mouseUp(event) {\n mousePressed = false;\n }", "function mouseReleased() {\r\n mouseIsDown = false;\r\n}", "pop() {\n this.client.switchWindow(this.handles[0]);\n this.handles.splice(-1, 1);\n }", "function mouseDown(event) {\n mousePressed = true;\n }", "function onmouseup(event){\n\t\tif(ContextMenu.visible){\n\t\t\tvar target = event.target || event.srcElement;\n\n\t\t\tif(target.className == \"contextMenu-btn\"){\n\t\t\t\t/** uses the identifier of the current context menu to get the content. */\n\t\t\t\tvar content = memory[currentId].content;\n\t\t\t\t\n\t\t\t\t/** treats the pressed label */\n\t\t\t\tfor(var i = 0; i < content.length; i++){\n\t\t\t\t\tvar label = content[i];\n\t\t\t\t\tif(label instanceof Function){\n\t\t\t\t\t\tlabel = label();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(target.textContent == label){\n\t\t\t\t\t\t/** \n\t\t\t\t\t\t * applies the defined action\n\t\t\t\t\t\t * then remove the context menu.\n\t\t\t\t\t\t */\n\t\t\t\t\t\tvar onPress = memory[currentId].onPress;\n\t\t\t\t\t\tfor(var k = 0; k < onPress.length; k++){\n\t\t\t\t\t\t\tvar onPressLabel = onPress[k].label;\n\t\t\t\t\t\t\tif(onPressLabel instanceof Function){\n\t\t\t\t\t\t\t\tonPressLabel = onPressLabel();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(onPressLabel == label){\n\t\t\t\t\t\t\t\tonPress[k].action();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tContextMenu.hide();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "keyDown(event) {\n var keyCode = event.which || event.keyCode;\n this.activeCommands[keyCode] = true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
dim This function returns the inner dimensions of the current window. If any of the optional dimension arguments are supplied, the window will be resized before its dimensions are returned. Prototype: Dim dim([[Dim d][int w, int h]]) Arguments: d ... An optional Dim object representing w and h w ... An optional width h ... An optional height Results: A Dim object representing the current window's inner width and height.
function dim() { var d = _dfa(arguments); if (d) { if (ie) { // The resizeBy can throw an exception if the user clicks too fast (PR39015); // catch and do nothing since the window is ultimately resized correctly anyway. try { var ow = document.body.clientWidth; var oh = document.body.clientHeight; self.resizeBy(d.w - ow, d.h - oh); } catch (e) { ; } } else { self.innerWidth = d.w; self.innerHeight = d.h; } } return new Dim(ie ? document.body.clientWidth : self.innerWidth, ie ? document.body.clientHeight : self.innerHeight); }
[ "function dim( w, h ) {\n return { w: w, h: h };\n}", "function objDim(o) {\r\n var w, h;\r\n if (arguments.length == 3) {\r\n w = arguments[1];\r\n h = arguments[2];\r\n } else if (arguments.length == 2) {\r\n w = arguments[1].w;\r\n h = arguments[1].h;\r\n }\r\n\r\n var d = new Dim(objW(o, w), objH(o, h));\r\n return d;\r\n}", "function _dim() {\r\n var d = _dfa(arguments);\r\n if (d) {\r\n this.d = objDim(this, d);\r\n }\r\n return objCss(this, \"position\") == \"absolute\" ? this.d : objDim(this);\r\n}", "function Dim(a,c){this.w=a;this.h=c;return true}", "calcElementDimensions(w, h) {}", "function getWindowDimensions() {\r\n const { innerWidth: width, innerHeight: height } = window;\r\n return {\r\n width,\r\n height\r\n };\r\n}", "function getWindowDimensions() {\n const { innerWidth: width, innerHeight: height } = window;\n return { width, height };\n }", "function Dim(w, h) {\r\n this.w = w;\r\n this.h = h;\r\n\r\n this.toString = function() {\r\n return this.w + 'x' + this.h;\r\n };\r\n}", "function getWindowDimensions() {\n var dimensions = {\n width: window.innerWidth,\n height: window.innerHeight\n };\n\n return dimensions;\n}", "function GetInnerWindowDimensions() {\r\n \r\n windowWidthPara.textContent = 'Inner Viewport Width: ' + window.innerWidth + 'px';\r\n windowHeightPara.textContent = 'Inner Viewport Height: ' + window.innerHeight + 'px';\r\n}", "function Dim(a, c) {\n\tthis.w = a;\n\tthis.h = c;\n\treturn true\n}", "function getDimensions() {\n return Dimensions.init(viewWidth, viewHeight);\n }", "function getSize() {\n\tvar dimension = [];\n\tvar width = window.innerWidth || document.body.clientWidth;\n\tvar height = window.innerHeight || document.body.clientHeight;\n\tdimension.push(width);\n\tdimension.push(height);\n\treturn dimension;\n}", "_getDimensions() {\n let width = window.innerWidth;\n let height = window.innerHeight;\n if (width < height) {\n return width;\n } else {\n return height;\n }\n }", "function getSize() {\n return GDimension(width, height);\n }", "function getDimCanavs() {\n w = canvas.width;\n h = canvas.height;\n }", "function getScreenDimensions (){return Dimensions.get('window');}", "function getWindowDimensions() {\r\n return [$(window).width(), $(window).height()];\r\n }", "function getDimension(dim) {\n switch (dim) {\n case \"container.left\":\n case \"container.top\":\n return 0;\n case \"container.width\":\n case \"container.right\":\n return availableWidth;\n case \"container.height\":\n case \"container.bottom\":\n return availableHeight;\n case \"interactive.left\":\n return paddingLeft;\n case \"interactive.top\":\n return paddingTop;\n case \"interactive.width\":\n case \"interactive.right\":\n return availableWidth - paddingLeft;\n case \"interactive.height\":\n case \"interactive.bottom\":\n return availableHeight - paddingTop - paddingBottom;\n default:\n dim = dim.split(\".\");\n return getDimensionOfContainer($containerByID[dim[0]], dim[1]);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the symlink when running as root
function createRootSymLink() { var li1 = process.argv[1].lastIndexOf('\\'), li2 = process.argv[1].lastIndexOf('/'); if (li2 > li1) { li1 = li2; } var AppPath = process.argv[1].substring(0,li1); var p1 = resolve(AppPath + "/" + nativescriptAppPath); var p2 = resolve(AppPath + "/" + webAppPath); if (debugging) { console.log("Path: ", p1, p2); } fs.symlinkSync(p2, p1, 'junction'); p1 = resolve(AppPath + "/" + nativescriptAssetsPath); p2 = resolve(AppPath + "/" + webAssetsPath); if (debugging) { console.log("Path: ", p1, p2); } fs.symlinkSync(p2,p1,'junction'); }
[ "createSymboliclink(target, link, done) {\n const commands = [\n 'mkdir -p ' + link, // Create the parent of the symlink target\n 'rm -rf ' + link,\n 'mkdir -p ' + utils.realpath(link + '/../' + target), // Create the symlink target\n 'ln -nfs ' + target + ' ' + link\n ];\n\n this.execMultiple(commands, done);\n }", "function AttemptRootSymlink() {\n\n if (process.platform === 'win32') {\n var curPath = resolve(\"./\");\n if (debugging) {\n console.log(\"RootSymlink Base path is\", curPath);\n }\n cp.execSync(\"powershell -Command \\\"Start-Process 'node' -ArgumentList '\"+curPath+\"/install.js symlink' -verb runas\\\"\");\n } else { \n console.log(\"To automatically create a SymLink between your web app and NativeScript, we need root for a second.\");\n cp.execSync(\"sudo \"+process.argv[0] + \" \" + process.argv[1] +\" symlink\");\n }\n}", "function AttemptRootSymlink() {\n\n if (process.platform === 'win32') {\n var curPath = resolve(\"./\");\n if (debugging) {\n console.log(\"RootSymlink Base path is\", curPath);\n }\n cp.execSync(\"powershell -Command \\\"Start-Process 'node' -ArgumentList '\"+curPath+\"/install.js symlink' -verb runas\\\"\");\n } else {\n console.log(\"To automatically create a SymLink between your web app and NativeScript, we need root for a second.\");\n cp.execSync(\"sudo \"+process.argv[0] + \" \" + process.argv[1] +\" symlink\");\n }\n}", "function AttemptRootSymlink() {\n\n if (process.platform === 'win32') {\n var curPath = resolve(\"./\");\n if (debugging) {\n console.log(\"RootSymlink Base path is\", curPath);\n }\n cp.execSync(\"powershell -Command \\\"Start-Process 'node' -ArgumentList '\"+curPath+\"/install.js symlink' -verb runas\\\"\");\n } else {\n\t\tconsole.log(\"To automatically create a SymLink between your web app and NativeScript, we need root for a second.\");\n\t\tcp.execSync(\"sudo \"+process.argv[0] + \" \" + process.argv[1] +\" symlink\");\n }\n}", "function createSymlink(src_path, dst_path) {\n if (!fs.existsSync(dst_path)) {\n execSyncNoCmdTrace(\"mkdir -p \" + dst_path);\n }\n execSyncNoCmdTrace(\"rm -rf \" + dst_path);\n execSync(\"ln -s \" + src_path + \" \" + dst_path);\n}", "function symlink() {\n fs.symlinkSync(root, link, 'junction');\n console.log(\"linked successfully\");\n process.exit(0)\n}", "function unix_symlink() { unix_ll(\"unix_symlink\", arguments); }", "symlink(glob) {\n this.globs.push({\n glob: path_1.toUnixString(glob),\n action: 'symlink'\n });\n }", "function createSymLinks() {\n fsMod.symlinkSync(\n pathMod.resolve(pathMod.join(args.library, 'closure')),\n pathMod.join(tempPath, 'closure'),\n 'junction');\n SYMLINKS.forEach(function(link) {\n fsMod.symlinkSync(\n pathMod.resolve(pathMod.join(__dirname, '../' + link)),\n pathMod.join(tempPath, 'lovefield/' + link),\n 'junction');\n });\n}", "static createSymbolicLinkJunction(options) {\n FileSystem._wrapException(() => {\n return FileSystem._handleLink(() => {\n // For directories, we use a Windows \"junction\". On POSIX operating systems, this produces a regular symlink.\n return fsx.symlinkSync(options.linkTargetPath, options.newLinkPath, 'junction');\n }, options);\n });\n }", "function writeSymlink () {\n readStream.pipe(concat(function (data) {\n var link = data.toString()\n debug('creating symlink', link, dest)\n fs.symlink(link, dest, function (err) {\n if (err) cancelled = true\n done(err)\n })\n }))\n }", "function createSymlinks(localPackageMap){\n Object.values(localPackageMap).forEach (packageName => {\n if (!fs.existsSync(`./${packageName}/node_modules`)) return;\n Object.keys(localPackageMap).forEach (localPackageName => {\n var packageDependencyPath = path.resolve(`./${packageName}/node_modules/${localPackageName}`);\n if (process.argv.includes(\"--verbose\")) {\n console.log (`[mpm link] checking module: ${packageDependencyPath}`);\n }\n if (!fs.existsSync(packageDependencyPath)) return;\n runCommandSync(`rm -rf ${packageDependencyPath}`);\n fs.symlinkSync(path.resolve(`./${packageName}`), packageDependencyPath);\n console.log (`[mpm link] Created symlink: '${packageDependencyPath}' --> ${packageName}'`);\n });\n })\n}", "makeVirtualSymlink(file, link) {\n fs.symlinkSync(file, link);\n }", "function symbolicLink( source, target ) {\n target.replace(/\\//g, function() { source = '../' + source });\n if ( ! fs.isLink(target) ) {\n if ( system.os.name == 'windows' ) {\n childProcess.execFile('mklink', [target,source] );\n } else {\n childProcess.execFile('ln', [\"-s\",source,target] );\n }\n }\n}", "createSymlink(id, remote) {\n const symlink = new (_models().Symlink)({\n // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!\n scope: id.scope,\n name: id.name,\n realScope: remote\n });\n return this.objects.add(symlink);\n }", "function symlinkNodeModules() {\n Object.keys(requiredNodeModules).forEach(importName => {\n const outputPath = path.join(tmpDir, 'node_modules', importName);\n const moduleDir = requiredNodeModules[importName];\n shx.mkdir('-p', path.dirname(outputPath));\n fs.symlinkSync(moduleDir, outputPath, 'junction');\n });\n}", "static createHardLink(options) {\n FileSystem._wrapException(() => {\n return FileSystem._handleLink(() => {\n return fsx.linkSync(options.linkTargetPath, options.newLinkPath);\n }, Object.assign(Object.assign({}, options), { linkTargetMustExist: true }));\n });\n }", "function unix_link() { unix_ll(\"unix_link\", arguments); }", "function makeLink() {\n if (_TEST)\n return;\n if (!retPgn.bonus) {\n let makeLink = '/scratch/tcec/Commonscripts/Divlink/makelnk.sh';\n exec(`${makeLink} ${retPgn.abb}`, (error, stdout, stderr) => {\n LS(`Error is: ${stderr}`);\n LS(`Output is: ${stdout}`);\n });\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bearish Price Flip occurs when the market records a close greater than the close four bars earlier, immediately followed by a close less than the close four bars earlier.
function findCandlesSinceBearishFlip(candles) { // is close of current candle greater than 4 candles previous // is previousClose less than current minus 5 let currentCandleIndex = 0; let bearishFound = false; const candleDataLength = candles.length; return _.reduce(candles, (acc, currentCandle) => { if(bearishFound) { return acc; } const indicesNeeded = (currentCandleIndex + 5); if( indicesNeeded < candleDataLength ){ const isBearishPriceFlip = isCandleBearish( currentCandle, candles[currentCandleIndex + 1], candles[currentCandleIndex + 4], candles[currentCandleIndex + 5] ); bearishFound = isBearishPriceFlip ? true : false; const updatedCandle = _.merge({}, {isBearishPriceFlip}, currentCandle); currentCandleIndex=currentCandleIndex+1; return acc.concat(updatedCandle); } else { return acc; } }, []); }
[ "function checkStockDelta (stockArray) {\n if (stockArray[1] > stockArray[2]) {\n // console.log(stockArray[0] + ' open is higher than close')\n stockTickerHTML = stockTickerHTML + `\n <div class=\"ticker__item__down\">${stockArray[0]}</div>\n <div class=\"ticker__image\"><img src=\"img/sad-trump-face.png\" alt=\"Sad Trump Face\"></div>\n <div class=\"ticker__value__down\">${stockArray[2]}</div>\n `\n } else {\n // console.log(stockArray[0] + ' close is higher than open')\n stockTickerHTML = stockTickerHTML + `\n <div class=\"ticker__item__up\">${stockArray[0]}</div>\n <div class=\"ticker__image\"><img src=\"img/happy-trump-face.png\" alt=\"Happy Trump Face\"></div>\n <div class=\"ticker__value__up\">${stockArray[2]}</div>\n `\n }\n}", "predictHighBid(state) {\n return (state.visibleCards.last() - state.visibleCards.pop().last()) / 2 + .5;\n }", "function aboveOpenF(stock, stockAwayPctF) { \n if (stock.popn > stock.last) {\n return true;\n }\n }", "function stratagy(lastPrice, nowPrice, callback) {\n\t\t// 振幅,根据历史值可以确定一个合理的振幅,\n\t\tlog(\"Stratagy start\");\n\t\tvar stepFactor = 1;\n\t\tvar lastPrice;\n\t\tvar salePrice = lastPrice * (1 + stepFactor / 100);\n\t\tvar buyPrice = lastPrice * (1 - stepFactor / 100);\n\t\tlog(\"SalePrice = \" + salePrice);\n\t\tlog(\"BuyPrice = \" + buyPrice);\n\t\tif (salePrice <= nowPrice) {\n\t\t\tcallback(\"sell\");\n\t\t}\n\t\tif (buyPrice >= nowPrice) {\n\t\t\tcallback(\"buy\");\n\t\t}\n\t\tlog(\"Stratagy over\");\n\t\tlog(\"\");\n\t}", "function snowballer() {\n reset(); // snowballer() has to work with a fresh version of the model.\n\n // Sort the debts by shortest to longest payoff based on the payment and balance.\n model.debts.sort(function(a, b) {\n return (a.balance / a.payment) - (b.balance / b.payment);\n });\n\n // This loop is what does the snowballing.\n while(model.balance > 0) {\n var overflow = model.extra;\n\n model.debts.forEach(function(debt) {\n var amount = debt.payment;\n overflow += debt.pay(amount, false).overflow;\n });\n\n while(overflow > 0) {\n var lowest = findLowestDebt();\n\n model.debts.forEach(function(debt) {\n if(lowest === -1) {\n overflow = 0;\n } else if(debt.id === lowest) {\n overflow -= debt.pay(overflow, true).payment;\n }\n });\n }\n }\n}", "function orderThanMarket(order, ticker, marketSide) {\r\n if (marketSide == \"bid\") var diff = ((ticker.bid / order.price) - 1) * 100;\r\n else if (marketSide == \"ask\") var diff = ((ticker.ask / order.price) - 1) * 100;\r\n else {}\r\n\t//console.log(\"diff ask =\" + ticker.ask+\"/\"+order.price);\r\n return diff;\r\n}", "function orderThanMarket(order, ticker, marketSide) {\r\n if (marketSide === \"bid\") var diff = ((ticker.bid / order.price) - 1) * 100;\r\n else if (marketSide === \"ask\") var diff = ((ticker.ask / order.price) - 1) * 100;\r\n else {}\r\n console.log(\"diff ask =\" + ticker.ask+\"/\"+order.price);\r\n\tconsole.log(\"diff bid =\" + ticker.bid+\"/\"+order.price);\r\n return diff;\r\n}", "_shouldAdjust(diffDecimal, quotes) {\n return quotes.find((_el, _i) => {\n if(_i === 0) {\n return false;\n }\n const prevClose = quotes[_i - 1].close;\n //console.log(`comparing ${_el.close} to ${prevClose}`);\n return Math.abs((_el.close - prevClose)) / prevClose >= diffDecimal;\n });\n }", "checkClosing() {\n let ret = false;\n if (\n (this.type === PositionType.LONG &&\n (/* this.pair.currentPrice >= this.takeProfitPrice || */\n this.pair.currentPrice <= this.stopLossPrice)) ||\n (this.type === PositionType.SHORT &&\n (/* this.pair.currentPrice <= this.takeProfitPrice || */\n this.pair.currentPrice >= this.stopLossPrice))\n ) {\n ret = true;\n }\n return ret;\n }", "depreciateStock() {\n // For every item that is above its base price, reduce its price.\n for (let i = 0; i < this.stock.length; i += 1) {\n const item = this.stock[i];\n if (item.price > item.basePrice) {\n item.price -= 5;\n // Make sure it doesn't go below the base price.\n if (item.price < item.basePrice) {\n item.price = item.basePrice;\n }\n // Update the price list.\n this.prices[i] = item.price;\n }\n }\n }", "function BackTestSimpleTrade(histData){\r\n\tvar histCtr = 1, minCtr = 0, position = 0;// position 0=none, 1= long, -1 = short\r\n\tvar trades = [], SL = -1;\r\n\t//get the position for the 1 Min Data for evaluation\r\n\twhile(minCtr < min1Data.length && min1Data[minCtr].time <= histData[0].time){\r\n\t\tminCtr++;\r\n\t}\r\n\t//\r\n\tvar prevLow = 0, prevHigh = 0, SLDiff = 5, SLBuff = .5, AmountRisked = 200000, qty=0;\r\n\tfor(histCtr=1;histCtr < histData.length; histCtr++)\r\n\t{\t\t\r\n\t\tprevLow = (Math.abs(prevLow-(histData[histCtr-1].low - SLBuff))<=SLDiff) ? Math.min(prevLow, (histData[histCtr-1].low - SLBuff)):\r\n\t\t\t\t\t\t(histData[histCtr-1].low - SLBuff);\r\n\t\tprevHigh = (Math.abs(prevHigh-(histData[histCtr-1].high + SLBuff))<=SLDiff) ? Math.max(prevHigh, (histData[histCtr-1].high + SLBuff)):\r\n\t\t\t\t\t\t(histData[histCtr-1].high + SLBuff);\r\n\t\twhile(minCtr < min1Data.length && min1Data[minCtr].time <= histData[histCtr].time){\t\t\t\r\n\t\t\tvar open = min1Data[minCtr].open, \r\n\t\t\t\thigh = min1Data[minCtr].high, \r\n\t\t\t\tlow = min1Data[minCtr].low, \r\n\t\t\t\tclose = min1Data[minCtr].close;\r\n\t\t\tif (position != 0) {//already in a Trade\r\n\t\t\t\tctr = trades.length - 1;\r\n\t\t\t\tvar ret = null;\r\n\t\t\t\tif (position < 0){ //In short trade, lets check for StopLoss\r\n\t\t\t\t\tSL = prevHigh; // SL should be the high of previous candle\r\n\t\t\t\t\tif (open - SL >= 0){// in case of gap up opening, compare the open of this minute candle with the SL\r\n\t\t\t\t\t\ttrades[ctr].exit = open;\r\n\t\t\t\t\t\tqty = Math.round(AmountRisked / (25 * trades[ctr].entryRisk)) * 25;\r\n\t\t\t\t\t\tret = CalculateReturns(trades[ctr].exit, trades[ctr].entry, qty);\r\n\t\t\t\t\t\tposition = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if ((high - SL) >= 0){// compare the high of this minute candle with the SL\r\n\t\t\t\t\t\ttrades[ctr].exit = SL;\r\n\t\t\t\t\t\tqty = Math.round(AmountRisked / (25 * trades[ctr].entryRisk)) * 25;\r\n\t\t\t\t\t\tret = CalculateReturns(trades[ctr].exit, trades[ctr].entry, qty);\r\n\t\t\t\t\t\tposition = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if (position > 0){ //In long trade, lets check for StopLoss\r\n\t\t\t\t\tSL = prevLow; // SL should be the low of previous candle\r\n\t\t\t\t\tif ((open - SL) <= 0){ // compare the low of this minute candle with the SL\r\n\t\t\t\t\t\ttrades[ctr].exit = open;\r\n\t\t\t\t\t\tqty = Math.round(AmountRisked / (25 * trades[ctr].entryRisk)) * 25;\r\n\t\t\t\t\t\tret = CalculateReturns(trades[ctr].entry, trades[ctr].exit, qty);\r\n\t\t\t\t\t\tposition = 0;\r\n\t\t\t\t\t}else if ((low - SL) <= 0){ // compare the low of this minute candle with the SL\r\n\t\t\t\t\t\ttrades[ctr].exit = SL;\r\n\t\t\t\t\t\tqty = Math.round(AmountRisked / (25 * trades[ctr].entryRisk)) * 25;\r\n\t\t\t\t\t\tret = CalculateReturns(trades[ctr].entry, trades[ctr].exit, qty);\r\n\t\t\t\t\t\tposition = 0;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif (position == 0){//StopLoss has been hit\r\n\t\t\t\t\ttrades[ctr].endTime = min1Data[minCtr].time;\r\n\t\t\t\t\ttrades[ctr].endCandle = histCtr;\r\n\t\t\t\t\t//\t\t\t\t\t\r\n\t\t\t\t\ttrades[ctr].brokerage = ret[0];\r\n\t\t\t\t\ttrades[ctr].profit = ret[1];\r\n\t\t\t\t\tSL = -1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//\r\n\t\t\tif (position == 0){ // not In Trade\r\n\t\t\t\t//lets check for the open first for gap opening \r\n\t\t\t\tif ((open - prevLow)<=0 ){//if price hits prevLow, then go Short\r\n\t\t\t\t\tSL = prevHigh;\r\n\t\t\t\t\tif (Math.abs(SL-open) <= maxRiskPoints){\r\n\t\t\t\t\t\tposition = -1;\r\n\t\t\t\t\t\ttrades.push({type:\"S\", startTime:min1Data[minCtr].time, entry: open, endTime:0, exit:0, startCandle:histCtr, endCandle:0, \r\n\t\t\t\t\t\tbrokerage:0, profit:0, entryRisk: Math.abs(SL-open), EMADiff: -1});\r\n\t\t\t\t\t}\r\n\t\t\t\t}else if ((open - prevHigh) >= 0){//if price hits prevHigh, then go Long\r\n\t\t\t\t\tSL = prevLow;\r\n\t\t\t\t\tif (Math.abs(SL-open) <= maxRiskPoints){\r\n\t\t\t\t\t\tposition = 1;\r\n\t\t\t\t\t\ttrades.push({type:\"L\", startTime:min1Data[minCtr].time, entry: open, endTime:0, exit:0, startCandle:histCtr, endCandle:0, \r\n\t\t\t\t\t\t\tbrokerage:0, profit:0, entryRisk: Math.abs(SL-open), EMADiff: -1});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if ((high - prevHigh) >= 0){//if price hits prevHigh, then go Long\r\n\t\t\t\t\tSL = prevLow;\r\n\t\t\t\t\tif (Math.abs(SL-prevHigh) <= maxRiskPoints){\r\n\t\t\t\t\t\tposition = 1;\r\n\t\t\t\t\t\ttrades.push({type:\"L\", startTime:min1Data[minCtr].time, entry:prevHigh, endTime:0, exit:0, startCandle:histCtr, endCandle:0, \r\n\t\t\t\t\t\t\tbrokerage:0, profit:0, entryRisk: Math.abs(SL-prevHigh), EMADiff: -1});\r\n\t\t\t\t\t}\r\n\t\t\t\t}else if ((low - prevLow)<=0){ //if price hits prevLow, then go Short\r\n\t\t\t\t\tSL = prevHigh;\r\n\t\t\t\t\tif (Math.abs(SL-prevLow) <= maxRiskPoints){\r\n\t\t\t\t\t\tposition = -1;\r\n\t\t\t\t\t\ttrades.push({type:\"S\", startTime:min1Data[minCtr].time, entry: prevLow, endTime:0, exit:0, startCandle:histCtr, endCandle:0, \r\n\t\t\t\t\t\t\tbrokerage:0, profit:0, entryRisk: Math.abs(SL-prevLow), EMADiff: -1});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\t\t\t\t\r\n\t\t\t}\r\n\t\t\tminCtr++;\r\n\t\t}\r\n\t}\r\n\t//remove the last trade if it wasn't completed.\r\n\tif (position != 0){\r\n\t\ttrades.pop();\r\n\t}\t\r\n\treturn trades;\r\n}", "function checkForTrendReversal () {\n let prevCandle = candleData[candleData.length - 2];\n let lastCandle = candleData[candleData.length - 1];\n\n if (prevCandle.trend !== lastCandle.trend) {\n moduleEvents.emit('cross', lastCandle);\n } else {\n console.log('Markets still trending', lastCandle.trend);\n }\n }", "function findDateBuyLow(stockData, dateArr, percentDecrease) {\n console.log(\"activeTradingDates percent = \" + parseInt(percentDecrease));\n console.log('findBuyDateLow running');\n var highPrice = 0;\n var buyPrice;\n // const dateArr = dateArr;\n \n var percentOf = calcPercentChangeDown(percentDecrease);\n // console.log('percentOf dateUtils = ' + percentOf);\n \n // iterate through dates\n for (const date of dateArr) {\n \n // find the price for each day\n const currentPrice = eval(stockData[date][\"markPrice\"]);\n console.log('currentDay = ' + date + ' currentPrice = ' + currentPrice + ' highPrice = ' + highPrice + ' buyPrice = ' + buyPrice);\n \n // if that price is greater than the previous day, make new high\n if (currentPrice > highPrice) {\n highPrice = currentPrice;\n buyPrice = (highPrice * percentOf).toFixed(2);\n }\n \n // if the current price is 5% less than high price - push date\n if (currentPrice <= buyPrice) {\n \n \n // once it finds the first dip date, stop searching\n console.log(\"buy date Utils = \" + date);\n return [date, buyPrice];\n }\n \n }\n return endDate;\n }", "function CalcBid(desired_sell_orn)\n{\n return (ORN_SUPPLY * QUOTE_ORN_USDT / (ORN_SUPPLY + desired_sell_orn)) // y / (x - v)\n * FEE_DIVIDER;\n}", "function calcChikouCross(s, previousVal) {\n\n s.period.leadline = s.lookback[s.options.displacement].close//offset(s.period.close, s.options.displacement)\n let bullish = crossover(s, 'close', 'leadline')\n let bearish = crossunder(s, 'close', 'leadline')\n\n let score = resolve(previousVal, 0)\n if (bullish && s.priceBelowKumo) {score = s.options.weakPoints} //A weak bullish signal occurs if the current price is below the Kumo.\n if (bullish && s.priceInsideKumo) {score = s.options.neutralPoints} //A neutral bullish signal occurs if the current price is inside the Kumo.\n if (bullish && s.priceAboveKumo) {score = s.options.strongPoints} //A strong bullish signal occurs if the current price is above the Kumo.\n if (bearish && s.priceBelowKumo) {score = -s.options.strongPoints} //A weak bearish signal occurs if the current price is above the Kumo.\n if (bearish && s.priceInsideKumo) {score = -s.options.neutralPoints} //A neutral bearish signal occurs if the current price is inside the Kumo.\n if (bearish && s.priceAboveKumo) {score = -s.options.weakPoints} //A strong bearish signal occurs if the current price is below the Kumo.\n\n return (score)\n\n}", "maxBuy(changes) {\n return changes.filter(([side, price, size]) => side === 'buy' && size !== '0')\n .map(([s, price]) => price)\n .sort(this.sortPrices)[0];\n }", "function sellLow() {\n bittrex.getorderbook({market: coin,type: 'buy'}, (data,err) => {\n if(err) {\n console.log(`something went wrong with getOrderBook: ${err.message}`);\n return false;\n } else {\n sellPrice = data.result[0].Rate * 0.8;\n console.log(`Panic selling at Ƀ${displaySats(sellPrice)}`);\n bittrex.selllimit({market: coin, quantity: shares, rate: sellPrice}, (data,err) => {\n if(err) {\n exit(`something went wrong with sellLimit: ${err.message}`);\n } else {\n clearInterval(sellPoll);\n pollForSellComplete(data.result.uuid);\n }\n });\n }\n });\n}", "function stockBuyAndSell(arr){\n\n\tlet profit = 0;\n\n\tfor(let i=1;i<arr.length;i++){\n\t\tif(arr[i] - arr[i-1] > 0){\n\t\t\tprofit = profit + (arr[i] - arr[i-1]);\n\t\t}\n\t}\n\treturn profit;\n}", "function sortClose(data) {\r\n const sortedClose = data.sort((a, b) => {\r\n if (sortBool)\r\n return a.close < b.close ? -1 : 1;\r\n else\r\n return a.close > b.close ? -1 : 1;\r\n });\r\n swapBool();\r\n createStockTable(sortedClose);\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function for checking highScores
function checkForHighscore(score) { if (score >= highScores[0].score || score >= highScores[1].score) { console.log(chalk.bgYellowBright("Congratulations you have got a highscre please send me a screenshot so that i can update the highScores")); } else { console.log(chalk.bgBlueBright("Highscores: \n" + `1.Name:${highScores[0].name}` + '\n' + `score:${highScores[0].score}\n`)); console.log(chalk.bgBlueBright(`2.Name:${highScores[1].name}` + '\n' + `score:${highScores[1].score}\n`)); } }
[ "function checkHighScore(score) {\n if(score>highScore[1].finalScore){\n console.log(chalk.yellow(\"Congragulations! You have made a highscore.\"));\n }\n \n }", "function checkHighScore()\n{\n if(score > highScores.scored)\n {\n\t console.log(chalk.bold.bgCyan(\"\\n Hurray ! 🍾 You beaten \" + highScores.name +\" With Margin of \" + (score-highScores.scored)+\" Marks \"));\n\t console.log(chalk.bold.bgMagenta(\" highest score was : \"+highScores.scored+\" \"));\n\t console.log(chalk.bold.bgRedBright(\" Send me the screenshot of your score 😀 \"));\n }\n}", "function checkHighScore() {\n\tconst record = retrieveHighScore();\n\tdetailsText.innerHTML = 'Your score: ' + score;\n\tdetailsText.innerHTML += '<br>';\n\tdetailsText.innerHTML += 'High score: ' + record;\n\tif (score > record) {\n\t\tstoreHighScore(score);\n\t}\n}", "checkForHighScore(score) {\r\n const highScores = this.state.topTen;\r\n for (let data of highScores) {\r\n if (score >= data.score) {\r\n return true; \r\n }\r\n }\r\n }", "function CheckHighestScore(highScorers){\nfor(var i = 0;i<highScorers.length;i++){\n if(score >= highScorers[i].highScore){\n console.log(\"Congratulations.You are Among Top Scorers\\nSend me the Screenshot of your score and i will update it in High Score List\");\n break;\n }\n}\n}", "function hasUserBeatenHighScore() {\n var maxScore = 0;\n for (var i = 0; i < highScores.length; i++) {\n var currentHighScore = highScores[i].score;\n if (currentHighScore > maxScore) {\n maxScore = currentHighScore;\n }\n }\n if (score > maxScore) {\n return \"CONGRATULATIONS AGAIN! You have broken the HIGH SCORE RECORDS. 👏\\n\" + \n \"Kindly, send me the screenshot of your score to update the scoreboard.\\n\";\n } else {\n return \"\";\n }\n}", "function isHighScoreReached() {\n return score === highScore;\n}", "function newHighScore()\n{\n if(score>highScores[0].score||score>highScores[1].score||score>highScores[2].score)\n {\n console.log((\"\\n \")+chalk.bold.bgRed(\" Wow! You have made a new high score! \\n Send me a screenshot and I'll update it. \"));\n }\n}", "function isHighScore() {\n if (highScores.length < 10) return true;\n for (let i = 0; i < highScores.length; i++) {\n if (highScores[i].score < score) return true;\n }\n return false;\n}", "function checkHighScore(){\n console.log('Previous High Score: ' + previousHscore);\n console.log('Current High Score ' + highScore);\n\n if (currentHighscore > previousHscore){\n highScore = currentHighscore;\n return highPoint.textContent = highScore;\n }\n else if(previousHscore === undefined){\n return highPoint.textContent = currentHighscore;\n }\n else{\n highScore = previousHscore;\n return highPoint.textContent = highScore;\n }\n\n}", "checkHscore() {\n if (this.score > this.Hscore) {\n this.Hscore = this.score\n console.log(`\\n\\n~~~Congratulations~~~\\n\\n${this.name} has a new HIGH SCORE of ${this.Hscore}!!!`)\n }\n }", "function displayScore(){\n console.log(\"Your final score is: \",score)\n console.log(\"High Scorer's: \")\n for(var i=0;i<highScore.length;i++){\n console.log(highScore[i].name,\":\",highScore[i].score)\n }\n //if user score is equal or greater than high scorer congrats user\n if(score >= highScore[0].score || score >= highScore[1].score){\n console.log(chalk.bgGrey(\"Congrats! You made it to the high score chart.\\nSend screenshot of your score.\"))\n }\n}", "function checkScore() {\n if (score === targetScore) {\n alert(\"You clicked \" + clicks + \" times and collected the perfect amount of mushrooms!\");\n wins++;\n $(\"#wins\").html(wins);\n shuffledNums = valueOptions.reduce(shuffle);\n reset();\n changeBcg();\n \n } else if (score > targetScore) {\n alert(\"Oh no, you collected too many mushrooms. Try again!\");\n losses++;\n $(\"#losses\").html(losses);\n shuffledNums = valueOptions.reduce(shuffle);\n reset();\n changeBcg();\n }\n }", "function checkPossibleScores(){\n disableScoreButtons()\n const tempHash = buildTempDiceHash()\n enableScoringButton(12, 'Lower')\n checkForNumbers(tempHash)\n checkForSmallStraight(tempHash)\n checkForLargeStraight(tempHash)\n checkForFullHouse(tempHash)\n checkForRuns(tempHash)\n}", "function IsHighScore(playerHighScore, playerScore){\n if(playerHighScore == 0 || playerHighScore < playerScore){\n return true;\n }\n return false;\n}", "function highestScoreChecker(currentScore, currentHighScore) {\n if (currentScore > currentHighScore) {\n return currentScore;\n } else {\n return currentHighScore;\n }\n}", "function checkHighScore() {\r\n var highScore = localStorage.getItem(\"high-score\");\r\n if (!highScore || score > highScore) {\r\n localStorage.setItem(\"high-score\", score);\r\n return true;\r\n }\r\n return false;\r\n}", "function isUserWin(score) { return score < -50; }", "function isBeat(score)\n{\n for(let i=0;i<highScores.length;i++)\n {\n if(score>highScores[i].score)\n {\n console.log(\"You have beaten the score of \"+highScores[i].name);\n console.log(\"To update your name send me a screenshot\");\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves containers list of an Azure Storage account.
function GetContainersList(blobService, continuationToken, options) { if (options === void 0) { options = {}; } return tslib_1.__awaiter(this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) { return [2 /*return*/, new Promise(function (resolve, reject) { // TODO: remove `as common.ContinuationToken` when `azure-storage` updated. blobService.listContainersSegmented(continuationToken, options, function (error, results) { if (error) { reject(error); } else { resolve(results); } }); })]; }); }); }
[ "function listContainers(accountID){\n var request = gapi.client.tagmanager.accounts.containers.list({\n 'accountId' : accountID\n });\n request.execute(printContainers);\n}", "function listContainers(accountId) {\n return new Promise((resolve, reject) => {\n var request = gapi.client.tagmanager.accounts.containers.list({\n 'parent': \"accounts/\" + accountId\n });\n return requestPromise(request)\n .then((response) => {\n var containers = response.container || [];\n resolve(containers);\n });\n }\n )\n}", "async function listBlobs(accessToken, storageAccountName, containerName) {\n\tlet myHeaders = new fetch.Headers();\n\tmyHeaders.append('Authorization', 'Bearer ' + accessToken);\n\tmyHeaders.append('x-ms-version', '2017-11-09');\n\n\tlet url = `https://${storageAccountName}.blob.core.windows.net/${containerName}?restype=container&comp=list`;\n\n\tlet options = {\n\t\tmethod: 'GET',\n\t\theaders: myHeaders\n\t};\n\n\treturn fetch(url, options)\n\t\t.then(handleErrors)\n\t\t.then(res => res.text())\n\t\t.catch(error => console.log(error));\n}", "function listBlobsInContainer() {\n blobService.listBlobsSegmented(sContainer, null, function(err, result) {\n if (err) {\n log(\"Couldn't list containers\");\n log.error(err);\n } else {\n log('Successfully listed containers');\n log(result.entries);\n log(result.continuationToken);\n }\n });\n}", "async function listContainers(blobService){\n return new Promise((resolve, reject) => {\n blobService.listContainersSegmented(null, (err, data) => {\n if (err) {\n reject(err);\n } else {\n resolve({ message: `${data.entries.length} containers`, containers: data.entries });\n }\n });\n });\n}", "function listBlobsInContainer(data) {\n //Check if the blob service is undefined or not\n if (typeof blobSvc === 'undefined') {\n blobSvc = azure.createBlobService();\n }\n\n blobSvc.listBlobsSegmented(data.containerName, null, function (error, result, response) {\n //Send up the result\n if (!error) {\n sendResponseToClient(data.id, LIST_BLOBS, { list: result });\n } else {\n sendResponseToClient(data.id, LIST_BLOBS, { Message: \"Error Listing Blobs\", Error: error, Result: result, Response: response });\n }\n });\n\n}", "function getContainers(callback) {\n //TODO: move url to a setting\n var request = Soup.Message.new('GET', 'http://127.0.0.1:5555/containers/json');\n _httpSession.queue_message(request, function(_httpSession, message) {\n if (message.status_code !== 200) {\n callback(message.status_code, null);\n return;\n }\n var containersData = request.response_body.data;\n var containers = JSON.parse(containersData);\n callback(null, containers);\n });\n}", "list_containers() {\n const time_UTC_str = new Date().toUTCString();\n const path = '/?comp=list';\n const signature = this.create_signature('GET', time_UTC_str, path);\n\n const req_params = {\n method: 'GET',\n hostname: this.hostname,\n path: path,\n headers: {\n 'Authorization': signature,\n 'x-ms-date': time_UTC_str,\n 'x-ms-version': this.version\n }\n }\n\n let req = http.request(req_params, this.res_handler);\n req.end();\n }", "async function listContainers(networkId) {\n let accessToken = await getAccessToken(OIDC_ENDPOINTT);\n let res = await request.get(listContainersUrl + '/' + networkId)\n .set('Authorization', accessToken)\n if (res.statusCode !== 200) {\n throw new Error('network with id:' + networkId + \" not found!\" + res.statusCode + '' + res.text)\n }\n let containersTable = res.text;\n let containerRawRows = containersTable.split('\\n');\n let re = new RegExp(/\\[(.*)\\]/);\n let containerRows = [];\n for (let rawRow of containerRawRows) {\n let r = rawRow.match(re);\n if (r) {\n let row = r[1].replace(/<.*?>/g, '').replace(/\\\"/g, '').split(',')\n row.splice(8)\n if (row.length === 8) {\n containerRows.push(row)\n }\n }\n }\n if (containerRows.length < 1) {\n throw new Error(\"No containers found with network id:\" + networkId)\n }\n return containerRows\n}", "function listAzureBlob(container, blobName, options, _) {\n var blobService = getBlobServiceClient(options);\n var specifiedContainerName = interaction.promptIfNotGiven($('Container name: '), container, _);\n var tips = util.format($('Getting blobs in container %s'), specifiedContainerName);\n var operation = getStorageBlobOperation(blobService, 'listAllBlobs');\n var storageOptions = getStorageBlobOperationDefaultOption();\n var useWildcard = false;\n var inputBlobName = blobName;\n if (Wildcard.containWildcards(inputBlobName)) {\n storageOptions.prefix = Wildcard.getNonWildcardPrefix(inputBlobName);\n useWildcard = true;\n } else {\n storageOptions.prefix = inputBlobName;\n }\n storageOptions.include = 'snapshots,metadata,copy';\n var blobs = [];\n\n startProgress(tips);\n\n try {\n blobs = performStorageOperation(operation, _, specifiedContainerName, storageOptions);\n } finally {\n endProgress();\n }\n\n var outputBlobs = [];\n\n if (useWildcard) {\n for (var i = 0, len = blobs.length; i < len; i++) {\n var blob = blobs[i];\n if (Wildcard.isMatch(blob.name, inputBlobName)) {\n outputBlobs.push(blob);\n }\n }\n } else {\n outputBlobs = blobs;\n }\n\n cli.interaction.formatOutput(outputBlobs, function(outputData) {\n if (outputData.length === 0) {\n logger.info($('No blobs found'));\n } else {\n outputData.contentSettings = outputData.contentSettings || {};\n logger.table(outputData, function(row, item) {\n item.contentSettings = item.contentSettings || {};\n row.cell($('Name'), item.name);\n row.cell($('Blob Type'), item.blobType);\n row.cell($('Length'), item.contentLength);\n row.cell($('Content Type'), item.contentSettings.contentType);\n row.cell($('Last Modified'), item.lastModified);\n row.cell($('Snapshot Time'), item.snapshot || '');\n });\n }\n });\n }", "function GetBlobsList(blobService, containerName, continuationToken, options) {\r\n if (options === void 0) { options = {}; }\r\n return tslib_1.__awaiter(this, void 0, void 0, function () {\r\n return tslib_1.__generator(this, function (_a) {\r\n return [2 /*return*/, new Promise(function (resolve, reject) {\r\n // TODO: remove `as common.ContinuationToken` when `azure-storage` updated.\r\n blobService.listBlobsSegmented(containerName, continuationToken, options, function (error, results) {\r\n if (error) {\r\n reject(error);\r\n }\r\n else {\r\n resolve(results);\r\n }\r\n });\r\n })];\r\n });\r\n });\r\n}", "function listBlobs (prefix) {\n blobService.listBlobsSegmentedWithPrefix(container, prefix, null, {\n include: 'metadata'\n }, function (error, results) {\n if (error) {\n console.log('Failed to list objects')\n } else {\n var listResult = ''\n for (var i = 0, blob; blob = results.entries[i]; i++) {\n var metadata = ''\n metadata = blob.metadata.caption ? blob.metadata.caption : 'Processing...'\n var thumbUri, fullUri, duration = ''\n if (prefix === 'videos') {\n thumbUri = blobUri + container + '/thumbnails/' + blob.name.split('/').pop() + '.jpg'\n fullUri = blobUri + container + '/transcoded/' + blob.name.split('/').pop()\n duration = blob.metadata.duration ? blob.metadata.duration + ' sec' : ''\n } else {\n thumbUri = blobUri + container + '/' + blob.name\n fullUri = thumbUri\n }\n listResult += '<div class=\"col-md-4\"><div class=\"card mb-4 box-shadow\"><img class=\"card-img-top placeholder\" alt=\"' + metadata + '\" src=\"' + thumbUri + '\" onerror=\"this.src=\\'style/no-image.jpg\\'\"><div class=\"card-body\"><p class=\"card-text\">' + metadata + '</p><div class=\"d-flex justify-content-between align-items-center\"><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#viewMedia\" data-src=\"' + fullUri + '\">View</button><button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" onClick=\"deleteBlob(\\'' + blob.name + '\\', \\'' + prefix + '\\');\">Delete</button></div><i>' + duration + '</i></div></div></div></div>'\n }\n grid = $('#' + prefix)\n grid.html(listResult)\n Holder.run({\n images: '.placeholder'\n })\n }\n })\n}", "function listBuckets () {\n // Instantiates a client\n const storage = Storage();\n\n // Lists all buckets in the current project\n return storage.getBuckets()\n .then((results) => {\n const buckets = results[0];\n\n console.log('Buckets:');\n buckets.forEach((bucket) => console.log(bucket.name));\n\n return buckets;\n });\n}", "function listObjects() {\n var request = gapi.client.storage.objects.list({\n 'bucket': BUCKET\n });\n request.execute(function(resp) {\n console.log(resp);\n });\n //executeRequest(request, 'listObjects');\n }", "function listObjects() {\n var request = gapi.client.storage.objects.list({\n 'bucket': BUCKET\n });\n executeRequest(request, 'listObjects');\n}", "function listBuckets() {\n var request = gapi.client.storage.buckets.list({\n 'project': PROJECT\n });\n executeRequest(request, 'listBuckets');\n}", "function listBlobDirectoriesSegmentedWithPrefix(container, prefix, currentToken, optionsOrCallback, callback) {\n /* tslint:disable: no-string-literal */\n var options = optionsOrCallback;\n var webResource = new azureStorage.WebResource();\n webResource[\"path\"] = container;\n webResource[\"method\"] = \"GET\";\n webResource.queryString[\"restype\"] = \"container\";\n webResource.queryString[\"comp\"] = \"list\";\n webResource.queryString[\"maxresults\"] = options.maxResults;\n // include with delimeter isn't supported\n if (options.include) {\n webResource.queryString[\"include\"] = options.include;\n }\n else {\n webResource.queryString[\"delimiter\"] = options.delimiter;\n }\n if (currentToken) {\n webResource.queryString[\"marker\"] = currentToken[\"nextMarker\"];\n }\n if (prefix) {\n webResource.queryString[\"prefix\"] = prefix;\n }\n options.requestLocationMode = getNextListingLocationMode(currentToken);\n function processResponseCallback(responseObject, next) {\n responseObject.listBlobsResult = null;\n if (!responseObject.error) {\n responseObject.listBlobsResult = {\n entries: null,\n continuationToken: null\n };\n responseObject.listBlobsResult.entries = [];\n var results = [];\n if (responseObject.response.body.EnumerationResults.Blobs.BlobPrefix) {\n results = results.concat(responseObject.response.body.EnumerationResults.Blobs.BlobPrefix);\n }\n if (responseObject.response.body.EnumerationResults.Blobs.Blob) {\n results = results.concat(responseObject.response.body.EnumerationResults.Blobs.Blob);\n }\n results.forEach(function (currentBlob) {\n var blobResult = parseXmlBlob(currentBlob);\n responseObject.listBlobsResult.entries.push(blobResult);\n });\n if (responseObject.response.body.EnumerationResults.NextMarker) {\n responseObject.listBlobsResult.continuationToken = {\n nextMarker: null,\n targetLocation: null\n };\n responseObject.listBlobsResult.continuationToken.nextMarker = responseObject.response.body.EnumerationResults.NextMarker;\n responseObject.listBlobsResult.continuationToken.targetLocation = responseObject.targetLocation;\n }\n }\n var finalCallback = function (returnObject) {\n callback(returnObject.error, returnObject.listBlobsResult, returnObject.response);\n };\n next(responseObject, finalCallback);\n }\n ;\n this.performRequest(webResource, null, options, processResponseCallback);\n /* tslint:enable */\n}", "get containers() {\n try {\n return JSON.parse(this._get('/containers/json?all=1'));\n } catch(e) {\n throw e;\n }\n }", "function listarImagenesPorContenedor(req, res) {\n\n var urls = [];\n blobService.listBlobsSegmented(req.params.containername, null, function (error, results) {\n if (error) {\n // List blobs error\n res.status(500).send({message: error });\n } else {\n for (var i = 0, blob; blob = results.entries[i]; i++) {\n var startDate = new Date();\n var expiryDate = new Date(startDate);\n expiryDate.setMinutes(startDate.getMinutes() + 100);\n startDate.setMinutes(startDate.getMinutes() - 100);\n\n var sharedAccessPolicy = {\n AccessPolicy: {\n Permissions: azure.BlobUtilities.SharedAccessPermissions.READ,\n Start: startDate,\n Expiry: expiryDate\n }\n };\n\n var token = blobService.generateSharedAccessSignature(req.params.containername, results.entries[i].name, sharedAccessPolicy);\n var sasUrl = blobService.getUrl(req.params.containername, results.entries[i].name, token);\n urls.push(sasUrl);\n }\n res.status(200).send({blobs: urls });\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the heatmap as a layer values: [[longitude:float, latitude:float, weight:float]] A list of coordinates with a weight. The higher the weight, the hotter this point is:) Values for the weight must be in the range from 01.
function heatmapLayer(values) { var data = new ol.source.Vector(); for (var i = 0; i< values.length; i++) { var v = values[i]; var coord = ol.proj.transform([v[0], v[1]],'EPSG:4326', 'EPSG:3857'); var lonLat = new ol.geom.Point(coord); var pointFeature = new ol.Feature({ geometry: lonLat, weight:v[2] }); data.addFeature(pointFeature); } //building the heatmap layer var heatmapLayer = new ol.layer.Heatmap({ source:data, radius:50, opacity:0.9 }); return heatmapLayer; }
[ "function createHeatMapData(heatWeights) {\n var heatMapData = []\n i = 0\n for(const county in heatWeights) {\n const location = heatWeights[county].location;\n const newPoint = {\n location: new google.maps.LatLng(location.lat, location.lng),\n weight: heatWeights[county].weight\n }\n heatMapData.push(newPoint);\n i += 1;\n }\n return heatMapData;\n}", "function getHeatMapData() {\n\tvar heatMapData = [];\n\tfor (var i = 0; i < crimes.length; i++) {\n\t\theatMapData.push(new google.maps.LatLng(crimes[i].lat, crimes[i].lng));\n\t}\n\treturn heatMapData;\n}", "function create_wind_heatmap(data, lpane){\n var heatData = {\n max: 200.00,\n data: []\n };\n\n var data_array = data;\n for( var i = 0; i < data.length; i++ ){\n heatData.data.push({\n lat: data[i][0],\n lng: data[i][1],\n value: Math.max(data[i][2], 0.0),\n });\n }\n\n var cfg = {\n // radius should be small ONLY if scaleRadius is true (or small radius is intended)\n // if scaleRadius is false it will be the constant radius used in pixels\n \"radius\": 0.0075,\n \"opacity\": 0.65,\n \"maxOpacity\": 0.75,\n // scales the radius based on map zoom\n \"scaleRadius\": true,\n \"gradient\": {\n '0.37': '#ffffcc',\n '0.475': '#ffe775',\n '0.555': '#ffc140',\n '0.65': '#ff8f20',\n '0.785': '#ff6060',\n },\n // if set to false the heatmap uses the global maximum for colorization\n // if activated: uses the data maximum within the current map boundaries\n // (there will always be a red spot with useLocalExtremas true)\n \"useLocalExtrema\": false,\n // which field name in your data represents the latitude - default \"lat\"\n latField: 'lat',\n // which field name in your data represents the longitude - default \"lng\"\n lngField: 'lng',\n // which field name in your data represents the data value - default \"value\"\n valueField: 'value',\n pane: lpane\n };\n\n var hLayer = new HeatmapOverlay(cfg);\n hLayer.setData(heatData);\n\n return hLayer;\n}", "addHeatMapLayer() {\n\n let coordinates = this.data.filter(location => location.markerIsDisplayed === true)\n .map(location => [location.longitude, location.latitude])\n\n this.map.addSource('my-data', {\n \"type\": \"geojson\",\n \"data\": {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiPoint\",\n \"coordinates\": coordinates\n }\n }\n });\n\n this.map.addLayer({\n id: 'heatmap',\n source: 'my-data',\n type: 'heatmap',\n paint: {\n 'heatmap-radius': {\n stops: [\n [10, 15]\n ]\n }\n }\n })\n\n this.isHeatMapLayered = true;\n }", "function expand_heatmap_values(info) {\n var data = info.data, scales = info.scales, offsets = info.offsets,\n heatmap_values = [];\n for(var i = 0; i < data.lat.length; i++) {\n heatmap_values[i] = [\n data.lat[i] * scales.lat + offsets.lat,\n data.lng[i] * scales.lng + offsets.lng,\n data.val[i]\n ];\n }\n return heatmap_values;\n}", "function drawHeatmap(map, layer){\n\t\n\tvar heatmap = new L.TileLayer.WebGLHeatMap({ \n \tsize: 500,\n \tautoresize: true,\n \topacity: .4,\n \t});\n\n\tvar dataPoints = [];\n\n\tfor (var i = layer.data.length - 1; i >= 0; i--) {\n\t\tvar point = layer.data[i]\n\t\tdataPoints.push([point.latitude, point.longitude, point.value / 40000]);\n\t};\n\n\theatmap.setData(dataPoints);\n\n\treturn heatmap;\n}", "@withDefinedData()\n @cacheable('heatmap')\n getScreenGridLayer() {\n const screenGridData = this.data\n .filter(({ accuracy }) => accuracy <= this.accuracyThreshold)\n .map(({ latitude, longitude }) => ({ position: [longitude, latitude] }));\n\n return new ScreenGridLayer({\n id: 'location-screen-grid',\n data: screenGridData,\n minColor: [0, 0, 0, 0],\n cellSizePixels: 35,\n });\n }", "function drawHeatmap(){\n heatmap.setData(pointsArr);\n heatmap.set('radius', 40);\n}", "updateHeatmap(locations)\r\n {\r\n let that = this;\r\n const scaled_locations = locations.map(function(location, index) {\r\n let scaled_location = Object.create(location);\r\n scaled_location.difference = that.scalingMethod.scaleDifference(Math.abs(location.difference));\r\n return scaled_location;\r\n });\r\n this.layer.setData(this.buildConfig(scaled_locations));\r\n }", "function createHeatCoords() {\n\n\theatCoords = [];\n\n\tfor (var i=0; i < eventCoords.length; i++) {\n\n\t\tvar cap = eventCoords[i][3];\n\n\t\tvar lat = eventCoords[i][0];\n\n\t\tvar lng = eventCoords[i][1];\n\t\t\n\t\tfor (var i2=0; i2 < cap/6; i2++) {\n\n\t\theatCoords.push([Number(lat), Number(lng)]);\n\t\t\n\t\t}\n\t};\n\n\theat.setLatLngs(heatCoords);\n\n}", "getHeatMap() {\n\n if(this.activePollutant == null || this.stateDataArray == null || this.stateDataArray.length == 0) return null;\n\n switch(this.activePollutant.toUpperCase()) {\n\n case 'CARBON MONOXIDE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['CO'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#f9fbe7\",\"#c0ca33\"]);\n break;\n\n case 'SULPHUR DIOXIDE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['SO2'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#ffeda0\",\"#f03b20\"]);\n break;\n\n case 'NITROUS OXIDE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['NO2'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#fde0dd\",\"#c51b8a\"]);\n break;\n\n case 'OZONE' :\n return d3.scaleLinear()\n .domain([0,d3.max(this.stateDataArray, function(d) { if(d) return d['O3'] })])\n .interpolate(d3.interpolateRgb)\n .range([\"#ece2f0\",\"#1c9099\"]);\n\n default: return null;\n }\n \n }", "function generate_heat_map() {\r\n var cmap = [];\r\n for (var i = 0; i < 256; i++) {\r\n var color = [i, Math.floor(.4 * i), Math.floor(.2 * i)];\r\n for (var j = 0; j < 4; j++) {\r\n cmap.push(color)\r\n }\r\n }\r\n return cmap;\r\n}", "getData() {\n this._assertInitialized();\n return this.heatmap.getData();\n }", "updateHeatmap(locations)\r\n {\r\n let that = this;\r\n const scaled_locations = locations.map(function(location, index) {\r\n let scaled_location = Object.create(location);\r\n scaled_location.refugees = that.scalingMethod.scale(location.refugees);\r\n return scaled_location;\r\n });\r\n this.layer.setData(this.buildConfig(scaled_locations));\r\n }", "function createHeatmap() {\n\tvar config = {\n\t\t\"width\": 5000,//window.screen.width,//$('#pane-center').width(),\n\t\t\"height\": 5000,//window.screen.height,//$('#pane-center').height(),\n\t\t\"radius\": 40,\n\t\t\"element\": document.getElementById(\"background\"),\n\t\t\"visible\": true,\n\t\t\"opacity\": 40,\n\t\t\"gradient\": { 0.0: \"rgb(0,0,197)\", 0.3: \"rgb(0,255,255)\", 0.6: \"rgb(0,255,0)\", 0.8: \"yellow\", 1: \"rgb(255,0,0)\" }\n\t};\n\n\theatmap = h337.create(config);\n\n\theatmap.store.setDataSet({ max: 100, data: []});\n\n}", "function drawBixiDataonMap(data)\n{\n //console.log(\"drawBixiDataonMap received data as: \", data);\n var numberOfStations = data.length;\n //console.log(\"numberOfStations is: \", numberOfStations);\n\n // Formatting the data to send to heatmap\n var i;\n var j;\n for(i = 0; i < numberOfStations; i++)\n {\n var latitude = data[i][\"coordinates\"][1];\n var longitude = data[i][\"coordinates\"][0];\n var bikes = data[i][\"bikes\"];\n\n // Shows concentration to show number of bikes\n var entry = {location: new google.maps.LatLng(latitude, longitude), weight: bikes};\n bixiStations.push(entry);\n }\n\n //console.log(\"bixiStations is: \", bixiStations);\n initBixiHeatMap();\n}", "function heatMap(map, data) {\n var heatmap = new nokia.maps.heatmap.Overlay({\n\tmax: 20,\n\topacity: 1,\n\ttype: \"density\",\n\tcoarseness: 2\n });\n heatmap.addData(data); // Add the heat map data to the map\n map.overlays.add(heatmap);\n}", "function drawHeatMap() {\n clearLayers();\n var points = [];\n eventMarkers.eachLayer(function (marker) {\n points.push(marker.getLatLng());\n });\n heatmap = L.heatLayer(points, {\n radius: 15,\n blur: 20\n });\n map.addLayer(heatmap);\n }", "function updateMap() {\n const center = new google.maps.LatLng(40.736071, -73.888207);\n map = new google.maps.Map(\n document.getElementById('map'), {\n zoom: 11,\n center: center\n });\n\n heatMap = new google.maps.visualization.HeatmapLayer({\n data: coords,\n map: map\n })\n\n heatMap.setMap(map);\n heatMap.set('radius', 60)\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
On mouse out: Set style class of element id to class
function doMouseOut(id, mclass) { if (dragdropongoing) return; if (id!=overId) return; stopHigh = false; obj = document.getElementById(id); if (sel_edit_areas[id]) { obj.className = "il_editarea_selected"; } else { //obj.className = mclass; obj.className = edit_area_original_class[id]; } var typetext = document.getElementById("label_" + id); if (typetext) { typetext.style.display = 'none'; } }
[ "function doMouseOut(id, mclass)\n{\n\tif (dragdropongoing) return;\n\tif (id!=overId) return;\n\tstopHigh = false;\n\tobj = document.getElementById(id);\n//\tif (oldclass[id])\n//\t{\n//\t\tobj.className = oldclass[id];\n//\t}\n//\telse\n//\t{\n\t\tobj.className = mclass;\n//\t}\n}", "function handleMouseOutElement(e) {\n\t\t\te.currentTarget.removeClassName('highlight');\n\t\t\ttheInterface.emit('ui:deEmphElement', {\n\t\t\t\tid : e.currentTarget.getAttribute('id'),\n\t\t\t\tlayer : e.currentTarget.getAttribute('data-layer')\n\t\t\t});\n\t\t}", "function blogMouseOut(){\n\tthis.removeClassName(\"blog-highlight\");\n}", "function rowMouseOut()\n{\n var c=this.className;\n this.className = c.replace(/hovered/,'');\n}", "function cellMouseOut() {\r\n /*\r\n var parts = this.className.split(\" \");\r\n var newClass = parts[0];\r\n if (parts.length > 2) {\r\n newClass = newClass + \" \" + parts[1];\r\n }\r\n this.className = newClass;\r\n */\r\n }", "function mouseOut() {\n this.style.color = \"burlywood\";\n this.style.cursor = \"default\";\n this.style.borderColor = \"black\";\n}", "function mouseoutFunction(event) {\n event.target.classList.remove('hover');\n }", "function doMouseOver (id, mclass)\n{\n\tif (dragdropongoing) return;\n\t\n\tif(stopHigh) return;\n\tstopHigh=true;\n\toverId = id;\n\tsetTimeout(\"stopHigh=false\",10);\n\tobj = document.getElementById(id);\n//\toldclass[id] = obj.className;\n\tobj.className = mclass;\n\tcurrent_mouse_over_id = id;\n}", "function mouseoutFunction(event) {\n GS.triggerEvent(event.target.parentNode, evt.mouseout);\n event.target.parentNode.classList.remove('hover');\n }", "function mouseout() {\n\t\tthis.classList.remove(\"hover\");\n\t\tthis.classList.add(\"tile\");\n\t}", "handleMouseOut(event) {\n if (Control.active == null) {\n event.target.classList.remove('highlight');\n }\n }", "function unhighlightHover(id) {\n var clickedTab = document.getElementById(id);\n clickedTab.setAttribute(\"class\", \"\");\n}", "function highlight(th){\r\nvar clas = th.parentNode.className.animVal;\r\ndocument.getElementsByClassName(clas)[0].style.stroke = \"yellow\";\r\n}//on mouse out of a building on the map return to default (black border)", "function over(item)\n{\n document.getElementById(item).className += \" shadow-black\";\n}", "function run_MouseLeave(){\n $(this).css(\"background-color\", \"lightblue\");\n }", "function handleMouseOverElement(e) {\n\t\t\te.currentTarget.addClassName('highlight');\n\t\t\ttheInterface.emit('ui:emphElement', {\n\t\t\t\tid : e.currentTarget.getAttribute('id'),\n\t\t\t\tlayer : e.currentTarget.getAttribute('data-layer')\n\t\t\t});\n\t\t}", "function tileMouseout() {\n $(this).css(\"background-color\", \"white\");\n $(this).css(\"border\", \"4px solid black\");\n}", "function mouseOut() {\n\t\tif (canMove(this)) {\n\t\t\tthis.className = \"piece normal\";\n\t\t}\n\t}", "_mouseOut(self) {\n delete self.nodeUnderMouse;\n self.svg.selectAll('.highlighted').classed('highlighted', false);\n for (let elem of self.detail) {\n elem.innerHTML = '';\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display plaintext in the helperTV
function displayHelperPlaintext(text) { loc = document.getElementById("helperTV"); htmldata = '<div class="plaintext">' + text + '</div>'; loc.innerHTML += htmldata; MathJax.Hub.Queue(["Typeset",MathJax.Hub]); }
[ "showText(currentText) {\n console.log(currentText)\n }", "function displayPlaintext(text,loc=mainTV) {\n\thtmldata = '<div class=\"plaintext\">' + text + '</div>';\n\t\n\tloc.innerHTML += htmldata;\n\tMathJax.Hub.Queue([\"Typeset\",MathJax.Hub]);\n}", "function display(text) {\n $(\"#infotext\").text(text)\n\n}", "function show_user_text(txt) {\n var e = document.getElementById('th-user');\n e.innerHTML = txt;\n}", "function riddle2Text(){\n\t\t$('.display-message').html('One Score - Dancing Queen = ?');\n\t}", "function showText(level :int) {\n PermanentVariables.CLevel = level;\n help.SetActive(true);\n helptext.text=textforhelp.returnText(); // = \"Moi = Hello \\nNäkemiin = Good bye\";\n}", "function riddle1Text(){\n\t\t$('.display-message').html('\"What goes up the chimney down, but can\\'t go down the chimney up? \"');\n\t}", "function displayToInput(txt) {\n inputBox.innerHTML = txt\n }", "function displayText(text) {\n var display_text=$(\".display-box\");\n display_text.html(text);\n }", "buildText() {\n\tthis.text += this.title + \"\\n\" + this.answerOptions[0].answer + \"\\n\" + this.answerOptions[1].answer;\n}", "function display(text) {\n\t\tvar resultNode = document.createElement(\"p\"); //create a paragraph tag to store and display result\n\t\tresultNode.innerHTML = text; //store that result\n\t\tvar resultParent = document.getElementById(\"biases\"); //find place to attach result\n\t\tresultParent.appendChild(resultNode); //actually attach value to that div tag thing\n\t}", "function renderText() {\n var title = doSuperscriptAndSubscript($('#chart-title').val());\n var subtitle = doSuperscriptAndSubscript($('#chart-subtitle').val());\n $('#chart-source-preview').html($('#chart-source').val());\n $('#chart-title-preview').html(title);\n $('#chart-subtitle-preview').html(subtitle);\n $('#chart-notes-preview').html(toMarkdown($('#chart-notes').val()));\n }", "function updateExaminedText(product){\n var outputString = \"Product Id: \" + product.id;\n outputString += \"<br> Price: \" + product.price;\n outputString += \"<br> Type: \" + product.type;\n document.getElementById(\"productText\").innerHTML = outputString;\n}", "function DisplayText()\r\n\t{\r\n\t\tdocument.getElementById(\"editText\").innerHTML = document.editor.text.value;\r\n\t}", "function displayText(myText){\n document.getElementById(\"myText\").innerHTML = myText;\n}", "exuentText() { return helper.playbill_title(this.title) + \"*A game of text-based intrigue and betrayal has been cancelled successfully.*\"; }", "function setTextOutput(){\n\ttextOutput.innerText = descField.value;\n}", "renderText() {\n const reviewRequest = this.model.get('parentObject').get('parentObject');\n\n if (this.$editor) {\n RB.formatText(this.$editor, {\n newText: this.model.get('text'),\n richText: this.model.get('richText'),\n isHTMLEncoded: true,\n bugTrackerURL: reviewRequest.get('bugTrackerURL'),\n });\n }\n }", "setDisplay(text) {\n document.getElementById(\"display\").innerHTML = text;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The JavaScript function that is set to the value of KoolOnLoadCallFunction. This function calls the two functions, setLayout() and setData(). The two functions (setLayout() and setData()) set the layout and data on the chart. Parameters: id The chart identifier that is used as the first parameter of KoolChart.create().
function chartReadyHandler(id) { document.getElementById(id).setLayout(layoutStr); document.getElementById(id).setData(chartData); }
[ "function loadchart(id) {\n const sensorDiv = document.createElement('div');\n const chartsDiv = document.querySelector('#charts');\n const content = document.createElement(\"div\");\n const chartDiv = document.createElement('div');\n const chart = document.createElement(\"canvas\")\n\n let sensorData;\n sensorsData.forEach(sensor => {\n if (sensor.id == id) {\n sensorData = sensor;\n }\n });\n\n sensorDiv.classList.add('col-md-6');\n content.classList.add(\"border\");\n content.classList.add('rounded')\n sensorDiv.classList.add(\"p-0\");\n content.classList.add('m-3');\n content.classList.add('p-3');\n chartDiv.classList.add(\"col-12\");\n chartDiv.classList.add(\"chart-container\");\n content.classList.add('row')\n\n chartDiv.appendChild(chart);\n content.appendChild(createDeleteButton(id));\n content.appendChild(chartDiv);\n content.appendChild(createInfoDiv(sensorData));\n\n sensorDiv.appendChild(content);\n chartsDiv.appendChild(sensorDiv);\n if (typeof sensorData !== \"undefined\") addDataToChart(chart, sensorData);\n}", "function createSpecificChart(id) {\n if (id == 0) {\n chartLabels = [];\n chartDataTemp = [];\n chartDataPressure = [];\n chartDataO3 = [];\n chartDataPM1 = []\n }\n if (id != 0) {\n getData(id);\n }\n setTimeout(createChart, 100, chartLabels, chartDataTemp, tempChart, 'SO2', 'rgba(255, 255, 0, 0.58)', true, '#989800');\n setTimeout(createChart, 100, chartLabels, chartDataPressure, pressureChart, 'NO2', 'rgba(255, 0, 0, 0.58)', true, '#980000');\n setTimeout(createChart, 100, chartLabels, chartDataO3, O3Chart, 'O3', 'rgba(0, 255, 10, 0.58)', true, '#009806');\n setTimeout(createChart, 100, chartLabels, chartDataPM1, PM1Chart, 'PM1', 'rgba(0, 245, 255, 0.58)', true, '#009298');\n}", "function setCanvasFromId(id, hiDPI = true) {\n setCanvas(document.getElementById(id), hiDPI);\n}", "function embedPivotTable(id){\r\n\tExt.onReady(function() {\r\n\r\n\t\tDHIS.getTable({\r\n\t\t\turl: 'http://localhost:8181/dhis/',\r\n\t\t\t//url: 'https://dhis2.jsi.com/dss/',\r\n\t\t\tel: \"graphx\"+id,\r\n\t\t\t//\"id\": \"kqFYaIXuTn1\",\r\n\t\t\t\"id\": \"T9cw92kNiDI\",\r\n\t\t\tfontSize: \"normal\",\r\n\t\t\tlegendSet: {\"id\": \"s50spdzKeSU\"}\r\n\t\t\t//legendSet: {\"id\": \"LrxfadsFqch\"}\r\n\t\t});\r\n\t});\r\n}", "function load_chart(strDivID, strType, strDataUrl)\r\n{\r\n\t//-- get body with and height\r\n\tvar oDiv = oControlFrameHolder.document.getElementById(strDivID);\r\n\tif(oDiv!=null)\r\n\t{\r\n\t\tvar myChart = new FusionCharts(_root + \"fusioncharts/\"+strType+\".swf\", \"myChartId\", oDiv.offsetWidth+10, oDiv.offsetHeight);\r\n\t\tmyChart.setDataURL(_root + strDataUrl + \"?swsessionid=\"+_swsessionid);\r\n\t\tmyChart.render(oDiv);\r\n\t}\r\n}", "function setTabCharts(tabId){\n\t// load all this tab's charts (together) only on the first time.\n\tif (loadedTabs[tabId] == null){\n\t\tvar noAjax = false;\n\t\tchartsData[tabId] = {};\n\t}\n\tif (loadedTabs[tabId] == true){\n\t\tnoAjax = true;\n\t}\n\n\tvar design = tabsList[tabId].design;\n\tvar jqxhr = $.get(\"tabs/\" + design + \".html\", function() {\n\t\t$(\"#tabInner\").html(jqxhr.responseText);\n\n\t});\n\n\n\tsetTimeout(function() {\n\t\t// wait till the tab's content be loaded\n\n\t\t$(\"#tabSubTitle\").html(tabsList[tabId].title);\n\t\t$(\".DividerText\").html(tabsList[tabId].divider);\n\n\t\tif(design == \"map\"){\n\t\t\tsetMapData();\n\t\t} else {\n\t\t\t$.each(tabsList[tabId].charts, function(boxNumber, chartObj){\n\t\t\t\tchkChartData(boxNumber,tabId,null,noAjax);\n\t\t\t});\n\t\t}\n\t}, 500);\n\n\tloadedTabs[tabId] = true;\n}", "setChartIdContainer() {\n\t\tthis.chart.setChartIDContainer();\n\t}", "function addElement(id) {\r\n\t\tvar chartsDivId = Ext.DomHelper.append(document.body, [{\r\n\t\t\tid : id,\r\n\t\t\tcls: 'chartContainer'\r\n\t\t\t}]);\r\n}", "function drawChart(id, chart) {\n document.getElementById(id).setAttribute(\"class\", \"chart\");\n chart.render();\n document.getElementById(id+\"Export\").setAttribute(\"class\", \"exportButton\");\n document.getElementById(id+\"Export\").setAttribute(\"onclick\", \"exportChart(charts[0])\");\n}", "function initCharts(model_id, view_id) {\n let chart_model = document.getElementById(model_id);\n for (let i = 1, row; row = chart_model.rows[i]; i++) {\n let [id, title, type, memo] = ['NA', 'NA', 'line', 'MEMO'];\n for (let j = 0, col; col = row.cells[j]; j++) {\n switch (j) {\n case 0:\n id = col.innerText;\n break;\n case 1:\n title = col.innerText;\n break;\n case 2:\n type = col.innerText;\n break;\n case 3:\n memo = col.innerText;\n break;\n default:\n break;\n }\n }\n // console.log(id, title, type, memo);\n let data = [];\n for (let i = 0; i < chart_data_buff_size; i++) {\n data.push(0);\n }\n let t = {\n 'id': id,\n 'title': title,\n 'type': type,\n 'memo': memo,\n 'data': data\n };\n chart_data_buff.push(t);\n }\n for (let i = 0; i < chart_data_buff_size; i++) {\n time_axis.push(null);\n }\n drawCharts(view_id, chart_data_buff);\n}", "function loadLibrariesArea(id)\r\n{\r\n\t//alert(id);\r\n\tmakeButtonsInactive(id);\t\r\n\tloadToolArea('libraries.do','AJAXVIEW');\r\n}", "function drawChart(id, chart) {\n document.getElementById(id).setAttribute(\"class\", \"chart\");\n chart.render();\n document.getElementById(id+\"Export\").setAttribute(\"class\", \"exportButton\");\n document.getElementById(id+\"Export\").setAttribute(\"onclick\", \"exportChart(charts[\" + id.replace(\"chart\", \"\") + \"])\");\n}", "function loadLineChart (div_id, dataset, chart_title, var_x, var_y, var_group, label_format = null, y_range = null) {\n\t// chart object\n\tvar chart = null;\n\t\n\t$.getJSON(dataset, function(jsonData) {\n\t\t// converts narrow data to wide\n\t\t// use an object as an intermediate step\n \t\tvar obj_data = {};\n\t\tvar categories = [];\t// categories for var_group\n\t\tjsonData.forEach(function(e) {\n\t\t\tif (e[var_x] in obj_data) {\n\t\t\t\tobj_data[e[var_x]][e[var_group]] = e[var_y];\n\t\t\t} else {\n\t\t\t\tobj_data[e[var_x]] = {\n\t\t\t\t\t[var_x]: e[var_x],\n\t\t\t\t\t[e[var_group]]: e[var_y]\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\tif (!(categories.includes(e[var_group]))) {\n\t\t\t\tcategories.push(e[var_group]);\n\t\t\t}\n\t\t}); \n\t\t\n\t\t// construct data array\n\t\tvar data = [];\n\t\tObject.keys(obj_data).forEach(function(e) {\n\t\t\tdata.push(obj_data[e]);\n\t\t});\n\t\t\n \t\t// colors\n\t\tvar chart_colors = {};\n\t\tcategories.forEach(function(e, i) {\n\t\t\tchart_colors[e] = calPalette[i];\n\t\t})\n\t\t\n\t\t// Y axis\n\t\tvar y_min = null;\n\t\tvar y_max = null;\n\t\tvar y_padding = null;\n\t\tif (y_range != null) {\n\t\t\ty_min = y_range[0];\n\t\t\ty_max = y_range[1];\n\t\t\ty_padding = {\n\t\t\t\ttop: 0,\n\t\t\t\tbottom: 0\n\t\t\t};\n\t\t}\n\n\t\t// generate chart\n\t\tchart = c3.generate({\n\t\t\tbindto: \"#\" + div_id,\n\t\t\tsize: {\n\t\t\t\twidth: chart_width,\n\t\t\t\theight: chart_height,\n\t\t\t},\n\t\t\tdata: {\n\t\t\t\tjson: data,\n\t\t\t\tkeys: {\n\t\t\t\t\tx: var_x,\n\t\t\t\t\tvalue: categories\n\t\t\t\t},\n\t\t\t\ttype: 'line',\n\t\t\t\tlabels: formatLabelObject(label_format),\n\t\t\t\torder: null\n\t\t\t},\n\t\t\taxis: {\n\t\t\t\tx: {\n\t\t\t\t\ttype: 'category'\n\t\t\t\t},\n\t\t\t\ty: {\n\t\t\t\t\tmin: y_min,\n\t\t\t\t\tmax: y_max,\n\t\t\t\t\tpadding: y_padding\n\t\t\t\t},\n\t\t\t\trotated: false\n\t\t\t},\n\t\t\ttooltip: {\n\t\t\t\tformat : {\n\t\t\t\t\tvalue: function (value, ratio, id) {\n\t\t\t\t\t\tif (formatLabel(label_format) == null) {\n\t\t\t\t\t\t\treturn value;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn (formatLabel(label_format))(value);\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\ttitle: {\n\t\t\t\ttext: chart_title\n\t\t\t},\n\t\t\tcolor: {\n\t\t\t\tpattern: calPalette\n\t\t\t},\n\t\t\tonrendered: function () {\n\t\t\t\td3.selectAll('.c3-chart-texts text').style('fill', 'black');\n\t\t\t}\n\t\t});\n\t})\n\t.done(function() {\n\t\t// store the object so that it can be destroyed later\n\t\tchart_objs.push(chart);\n\t});\n}", "function initLineCharts1(id, dataList1, dataList2, dataList3, dataX) {\n\t\tvar myChart = echarts.init(document.getElementById(id));\n\t\tvar option = {\n\t\t\ttooltip: {\n\t\t\t\ttrigger: 'axis',\n\t\t\t\taxisPointer: {\n\t\t\t\t\ttype: 'cross',\n\t\t\t\t\tlabel: {\n\t\t\t\t\t\tbackgroundColor: '#6a7985'\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tlegend: {\n\t\t\t\ttextStyle: {\n\t\t\t\t\tcolor: 'rgba(255, 255, 255, 0.8)',\n\t\t\t\t\tfontSize: fontSize(0.12)\n\t\t\t\t},\n\t\t\t\tdata: ['今日在线', '今日离线', '今日故障']\n\t\t\t},\n\t\t\tgrid: { // 设置图形大小\n\t\t\t\tleft: '3%',\n\t\t\t\tright: '4%',\n\t\t\t\tbottom: '3%',\n\t\t\t\ttop: '25%',\n\t\t\t\tcontainLabel: true\n\t\t\t},\n\t\t\txAxis: [{\n\t\t\t\ttype: 'category',\n\t\t\t\tdata: dataX,\n\t\t\t\taxisLabel: {\n\t\t\t\t\tfontSize: fontSize(0.12),\n\t\t\t\t\ttextStyle: {\n\t\t\t\t\t\tcolor: 'rgba(255, 255, 255, 0.8)' //坐标值得具体的颜色\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}],\n\t\t\tyAxis: [{\n\t\t\t\ttype: 'value',\n\t\t\t\tname: '单位:个',\n\t\t\t\tnameTextStyle: {\n\t\t\t\t\tcolor: 'rgba(255, 255, 255, 0.8)',\n\t\t\t\t\tfontSize: fontSize(0.12)\n\t\t\t\t},\n\t\t\t\tsplitNumber: '4',\n\t\t\t\taxisLabel: {\n\t\t\t\t\tfontSize: fontSize(0.12),\n\t\t\t\t\ttextStyle: {\n\t\t\t\t\t\tcolor: 'rgba(255, 255, 255, 0.8)'\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsplitLine: {\n\t\t\t\t\tshow: true,\n\t\t\t\t\t// 改变轴线颜色\n\t\t\t\t\tlineStyle: {\n\t\t\t\t\t\ttype: 'dashed', //设置网格线类型 dotted:虚线 solid:实线\n\t\t\t\t\t\t// 使用深浅的间隔色\n\t\t\t\t\t\tcolor: ['#9ba2ac']\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}],\n\t\t\tseries: [{\n\t\t\t\t\tname: '今日在线',\n\t\t\t\t\ttype: 'line',\n\t\t\t\t\tcolor: \"#4AFEA3\",\n\t\t\t\t\tdata: dataList1\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: '今日离线',\n\t\t\t\t\ttype: 'line',\n\t\t\t\t\tcolor: \"#00FFFF\",\n\t\t\t\t\tdata: dataList2\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: '今日故障',\n\t\t\t\t\ttype: 'line',\n\t\t\t\t\tcolor: \"#FD9D02\",\n\t\t\t\t\tdata: dataList3\n\t\t\t\t},\n\t\t\t]\n\t\t};\n\t\tmyChart.setOption(option);\n\t}", "function _loadLayout(id, onLoadedCallback) {\n var url = 'layouts/' + id + '.html';\n _loadHtml(url, function () {\n onLoadedCallback(new Layout(id));\n });\n }", "function initializeChart(tree_id) {\n\tquery = new google.visualization.Query(\"https://www.google.com/fusiontables/gvizdata?tq=\");\n var query_string = \"SELECT 'Date', '\"+tree_id+\"' FROM 1-UxIFELz001J7cR2JCWN8EJDf7nXTrstXKaSUb5t ORDER BY 'Date'\";\n\tquery.setQuery(query_string);\n\n\tquery.send(handleQueryResponse);\n}", "function setLayout(){\n\n}", "setLayout(layout, data, settings, runID) {\n // Refresh data\n this._data = new GraphData(data);\n // Construct new layout\n switch(layout) {\n case 'force':\n this._layout = new ForceLayout(this._svg, this._data, runID, settings);\n if (this._meta.particles) this._layout.enableParticles();\n break;\n case 'circle': this._layout = new CircleLayout(this._svg, this._data, runID, settings); break;\n case 'scatter': this._layout = new ScatterPlot(this._svg, this._data, runID, settings); break;\n default: throw 'view.js - invalid layout for view';\n }\n }", "function intialize(){\r\n\tuniqueid = getUniqueId() ;\r\n\tonClickOnNode=function(){};\r\n\tonClickOnFlowLine=function(){};\r\n\tonMouseOverOnNode=function(){};\r\n\tonMouseOverOnFlowLine=function(){};\r\n\tonMouseOutOnNode=function(){};\r\n\tonMouseOutOnFlowLine=function(){};\r\n\tonDblClickOnNode=function(){};\r\n\tonDblClickOnFlowLine=function(){};\r\n\tonNodeContextClick=function(){};\r\n\tnodeRenderer=function(text,b,nid){ \r\n\t\t\tvar htmlStr = \"\" ; \r\n\t\t\tvar template_NodeText = new Ext.Template(\r\n\t\t\t\t\t'<div name=\"acctNodeText\" class = \"nodeText\">',\r\n\t\t\t\t\t\t'Node',\r\n\t\t\t\t\t'</div>'\r\n\t\t\t);\t\t\t\t \t\t\t\t\t\t\r\n\t\t\t\r\n\t\t\t\thtmlStr += template_NodeText.apply(text);\r\n\t\t\t\r\n\t\t\t\r\n\t\t\treturn htmlStr ; \r\n\t}\t\r\n\tchartid = \"ChartsApi\";//+ uniqueid ;\r\n\tdivid=chartid;\r\n\taddElement(divid);\r\n\t//height = 400;\r\n\t//width = 400;\r\n\t\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createCartView() / createCartItemView() Creates a view for a single cart item. This exists so that we can attach the item to the remove button so that when it's clicked, we know what item to remove.
function createCartItemView(config) { var view = createTemplateView(config); view.afterRender = function(clonedTemplate, model) { clonedTemplate.find('.remove-item').click(function(){ view.cartModel.removeItem(model); }); }; //view.afterRender() return view; }
[ "function createCartView(config) {\n config.cartModel = config.model;\n config.templateView = createCartItemView(config);\n\n var view = createTemplateListView(config);\n\n view.afterRender = function() {\n this.subtotalPrice.html(this.model.getSubtotalPrice());\n this.taxPrice.html(this.model.getTaxPrice());\n this.totalPrice.html(this.model.getTotalPrice());\n }; //afterRender()\n\n return view;\n}", "addCartItem(item) {\n // Here we create the item to be added with a div\n const div = document.createElement(\"div\");\n div.classList.add(\"cart-item\");\n div.innerHTML = `\n <img src=${item.image} alt=\"product\" />\n <div>\n <h4>${item.title}</h4>\n <h5>${item.price}$</h5>\n <span class=\"remove-item\" data-id =${item.id}>remove</span>\n </div>\n <div>\n <i class=\"fa fa-chevron-up\" data-id =${item.id}></i>\n <p class=\"item-amount\">${item.amount}</p>\n <i class=\"fa fa-chevron-down\" data-id =${item.id}></i>\n </div>\n `;\n // Here we appendChild the newly created div to the cartContent variable declared earlier.\n // The appendChild method appends a node as the last child of a node\n cartContent.appendChild(div);\n }", "function showCartItem(item, index) {\n var cart = $(\".cart\");\n cart.append(\"<div class=cart-item id=\" + index + \"><div class=main-content id=wrapper><div class=right-section><h2 class=product-name>\" + item.name + \"</h2><h3 class=product-price>$\" + item.currentState[0] + \".00</h3><h4><span>\" + item.currentState[2] + \"</span> | <span>\" + item.currentState[1] + \"</span></h4><button class=delete-item>Remove - X</button></div><div class=left-section><img alt=pillow class=product-image height=200 src='../\" + item.currentState[3] + \"' width=200></div><div id=cleared></div></div><span class=horizontal-line></span></div>\");\n}", "function addItemToCart(itemNumber)\n{\n\t// Get the value of the quantity field for the add button that was clicked \n\tlet quantityValue = trim(document.getElementById(\"qty\" + itemNumber).value);\n\n\t// Determine if the quantity value is valid\n\tif ( !isNaN(quantityValue) && quantityValue != \"\" && quantityValue != null && quantityValue != 0 && !document.getElementById(\"cartItem\" + itemNumber) )\n\t{\n\t\t// Hide the parent of the quantity field being evaluated\n\t\tdocument.getElementById(\"qty\" + itemNumber).parentNode.style.visibility = \"hidden\";\n\n\t\t// Determine if there are no items in the car\n\t\tif ( numberOfItemsInCart == 0 )\n\t\t{\n\t\t\t// Hide the no items in cart list item \n\t\t\tdocument.getElementById(\"noItems\").style.display = \"none\";\n\t\t}\n\n\t\t// Create the image for the cart item\n\t\tlet cartItemImage = document.createElement(\"img\");\n\t\tcartItemImage.src = \"images/\" + itemImage[itemNumber - 1];\n\t\tcartItemImage.alt = itemDescription[itemNumber - 1];\n\n\t\t// Create the span element containing the item description\n\t\tlet cartItemDescription = document.createElement(\"span\");\n\t\tcartItemDescription.innerHTML = itemDescription[itemNumber - 1];\n\n\t\t// Create the span element containing the quanitity to order\n\t\tlet cartItemQuanity = document.createElement(\"span\");\n\t\tcartItemQuanity.innerHTML = quantityValue;\n\n\t\t// Calculate the subtotal of the item ordered\n\t\tlet itemTotal = quantityValue * itemPrice[itemNumber - 1];\n\n\t\t// Create the span element containing the subtotal of the item ordered\n\t\tlet cartItemTotal = document.createElement(\"span\");\n\t\tcartItemTotal.innerHTML = formatCurrency(itemTotal);\n\n\t\t// Create the remove button for the cart item\n\t\tlet cartItemRemoveButton = document.createElement(\"button\");\n\t\tcartItemRemoveButton.setAttribute(\"id\", \"removeItem\" + itemNumber);\n\t\tcartItemRemoveButton.setAttribute(\"type\", \"button\");\n\t\tcartItemRemoveButton.innerHTML = \"Remove\";\n\t\tcartItemRemoveButton.addEventListener(\"click\",\n\t\t\t// Annonymous function for the click event of a cart item remove button\n\t\t\tfunction()\n\t\t\t{\n\t\t\t\t// Removes the buttons grandparent (li) from the cart list\n\t\t\t\tthis.parentNode.parentNode.removeChild(this.parentNode);\n\n\t\t\t\t// Deteremine the quantity field id for the item being removed from the cart by\n\t\t\t\t// getting the number at the end of the remove button's id\n\t\t\t\tlet itemQuantityFieldId = \"qty\" + this.id.charAt(this.id.length - 1);\n\n\t\t\t\t// Get a reference to quanitity field of the item being removed form the cart\n\t\t\t\tlet itemQuantityField = document.getElementById(itemQuantityFieldId);\n\t\t\t\t\n\t\t\t\t// Set the visibility of the quantity field's parent (div) to visible\n\t\t\t\titemQuantityField.parentNode.style.visibility = \"visible\";\n\n\t\t\t\t// Initialize the quantity field value\n\t\t\t\titemQuantityField.value = \"\";\n\n\t\t\t\t// Decrement the number of items in the cart\n\t\t\t\tnumberOfItemsInCart--;\n\n\t\t\t\t// Decrement the order total\n\t\t\t\torderTotal -= itemTotal;\n\n\t\t\t\t// Update the total purchase in the cart\n\t\t\t\tdocument.getElementById(\"cartTotal\").innerHTML = formatCurrency(orderTotal);\n\n\t\t\t\t// Determine if there are no items in the car\n\t\t\t\tif ( numberOfItemsInCart == 0 )\n\t\t\t\t{\n\t\t\t\t\t// Show the no items in cart list item \n\t\t\t\t\tdocument.getElementById(\"noItems\").style.display = \"block\";\n\t\t\t\t}\t\t\t\t\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\n\t\t// Create a div used to clear the floats\n\t\tlet cartClearDiv = document.createElement(\"div\");\n\t\tcartClearDiv.setAttribute(\"class\", \"clear\");\n\n\t\t// Create the paragraph which contains the cart item summary elements\n\t\tlet cartItemParagraph = document.createElement(\"p\");\n\t\tcartItemParagraph.appendChild(cartItemImage);\n\t\tcartItemParagraph.appendChild(cartItemDescription);\n\t\tcartItemParagraph.appendChild(document.createElement(\"br\"));\n\t\tcartItemParagraph.appendChild(document.createTextNode(\"Quantity: \"));\n\t\tcartItemParagraph.appendChild(cartItemQuanity);\n\t\tcartItemParagraph.appendChild(document.createElement(\"br\"));\n\t\tcartItemParagraph.appendChild(document.createTextNode(\"Total: \"));\n\t\tcartItemParagraph.appendChild(cartItemTotal);\t\t\n\n\t\t// Create the cart list item and add the elements within it\n\t\tlet cartItem = document.createElement(\"li\");\n\t\tcartItem.setAttribute(\"id\", \"cartItem\" + itemNumber);\n\t\tcartItem.appendChild(cartItemParagraph);\n\t\tcartItem.appendChild(cartItemRemoveButton);\n\t\tcartItem.appendChild(cartClearDiv);\n\n\t\t// Add the cart list item to the top of the list\n\t\tlet cart = document.getElementById(\"cart\");\n\t\tcart.insertBefore(cartItem, cart.childNodes[0]);\n\n\t\t// Increment the number of items in the cart\n\t\tnumberOfItemsInCart++;\n\n\t\t// Increment the total purchase amount\n\t\torderTotal += itemTotal;\n\n\t\t// Update the total puchase amount in the cart\n\t\tdocument.getElementById(\"cartTotal\").innerHTML = formatCurrency(orderTotal);\n\t}\t\t\n}", "function renderCart () {\n\n\t\t// Get variables.\n\t\tvar cartEl = document.querySelector('#cart .cart__content'),\n\t\t\tcartItem = '',\n\t\t\titems = '';\n\n\t\tcart.items.forEach(function (item) {\n\n\t\t\t// Use template literal to create our cart item content.\n\t\t\tcartItem = `<div id=\"item${item.id}\" class=\"cart__row cart-item text--black\">\n\t\t\t\t<div class=\"cart-col--1 flex align-center\">\n\t\t\t\t\t<img src=\"${item.image}\" alt=\"${item.name}\" class=\"cart-item__image\">\n\t\t\t\t\t<h3 class=\"cart-item__heading\">${item.name}</h3>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"cart-col--2\">\n\t\t\t\t\t<span class=\"cart-item__price\">$${item.price}</span>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"cart-col--3\">\n\t\t\t\t\t<div class=\"increment flex justify-between\">\n\t\t\t\t\t\t<button class=\"button button--outline text--aluminum minus\" type=\"button\">&minus;</button>\n\t\t\t\t\t\t<label for=\"cart-${item.id}\" class=\"hide-text\">Quantity</label>\n\t\t\t\t\t\t<input class=\"qty\" type=\"number\" id=\"cart-${item.id}\" name=\"cart-${item.id}\" value=\"${item.quantity}\">\n\t\t\t\t\t\t<button class=\"button button--outline text--aluminum plus\" type=\"button\">&plus;</button>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"cart-col--4\">\n\t\t\t\t\t<span class=\"cart-item__total\">$${item.quantity * item.price}</span>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"cart-col--5\">\n\t\t\t\t\t<button type=\"button\" class=\"button button--close button--remove\">\n\t\t\t\t\t\t<span class=\"hide-text\">Remove</span>\n\t\t\t\t\t\t<span class=\"close close--1\"></span>\n\t\t\t\t\t\t<span class=\"close close--2\"></span>\n\t\t\t\t\t</button>\n\t\t\t\t</div>\n\t\t\t</div>`;\n\n\t\t\titems += cartItem;\n\t\t} );\n\n\t\t// Add the item to the cart.\n\t\tcartEl.innerHTML = items;\n\t}", "function createCheckoutCartRow(items) {\n\t\tlet cartRow = $(\"<li>\");\n\t\tcartRow.addClass(\n\t\t\t\"list-group-item d-flex justify-content-between lh-condensed\"\n\t\t);\n\n\t\tcartRow.html(`\n <div>\n <h6 class=\"my-0\">${items.name}</h6>\n <small class=\"text-muted\">${\n\t\t\t\t\t\titems.size\n\t\t\t\t\t} | </small>\n <small class=\"text-muted\">Quantity: ${\n\t\t\t\t\t\titems.quantity\n\t\t\t\t\t} | </small>\n <span class=\"text-muted\">Price: ${\n\t\t\t\t\t\titems.price\n\t\t\t\t\t}</span>\n </div>\n <span class=\"text-muted\">Total Item Price: $${\n\t\t\t\t\titems.totalPrice\n\t\t\t\t}</span>\n `);\n\n\t\t//generating total cart price by adding current cartTotalPrice value to 'this' item's totalPrice\n\t\tcartTotalPrice += parseFloat(items.totalPrice);\n\n\t\treturn cartRow;\n\t}", "renderCartItem(item) {\n\t\t// DEFINE A SINGLE ITEM (using the CART ITEM data)\n\t\tconst element = CartItem(item);\n\t\t// CART ITEM \"DOM\" APPENDS \"ELEMENT\"\n\t\tCART_CONTENT.innerHTML += element;\n\t}", "function removeFromCart(item) {\n order.removeItem(item);\n vm.openModal.hide();\n }", "createNewItem() {\n let view = new EditableListItem(this.style);\n let controller = new ListItemController(this.itemDao, view);\n controller.createItem();\n FrontController.bindViewWithController(\n this.parentElement,\n view,\n controller\n );\n }", "function createCartItem(itemId) {\n return {\n itemId: itemId,\n quantity: 1\n };\n}", "function addItemToCart() {}", "_createCart() {\n var self = this;\n if (self.storage.getItem(self.cartName) == null) {\n var cart = {};\n cart.items = [];\n self.storage.setItem(self.cartName, self._toJSONString(cart));\n self.storage.setItem(self.total, \"0.00\");\n }\n }", "function createCartItems(item) {\n return `\n <div class=\"row d-flex justify-content-between\" id=\"${item.id}\" data-quantity-type=\"${item.qty}\">\n <div class=\"item-name\" data-toggle=\"popover\" data-placement=\"left\" data-html=\"true\" title=\"Change quantity below:\" data-content='\n <div id=\"${item.id}\">\n <button class=\"decrease-quantity\">\n <i class=\"fal fa-minus\"></i>\n </button>\n <input type=\"text\" class=\"cart-quantity-value col-3 text-center\" value=\"${item.qty}\" data-value=\"${item.qty}\"></input>\n <button class=\"increase-cart-quantity\">\n <i class=\"fal fa-plus\"></i>\n </button>\n <button class=\"quantity-change-btn\">Save changes</button>\n </div>\n '>\n ${item.qty} x\n ${item.name}\n <p>${item.description}</p>\n </div>\n <div class=\"item-price pt-2\">\n $${item.lineTotal}\n <button class=\"pl-2 remove-item-btn\"><i class=\"fal fa-times\"></i></button>\n </div>\n </div>\n `;\n }", "function removeCartItem(event) {\n\tvar buttonClicked = event.target;\n\tbuttonClicked.parentElement.parentElement.remove();\n\tupdateCartTotal()\n}", "function renderNewCartItem(item) {\n let $cartItem = createCartElement(item);\n orderTotal += item.price;\n console.log(orderTotal);\n $('#order-items').append($cartItem);\n $('#orderTotalHere').text(`Total: $${orderTotal}.00`);\n }", "function removeFromCart (item) {\n console.log('Убран продукт: ' + item.name);\n for (let i = 0; i < cartItem.instances.length; i++) {\n if (cartItem.instances[i]['id'] == item.id) {\n cartItem.instances.splice(i, 1);\n break;\n };\n };\n // console.log(cart1.countCartPrice());\n cartContent.innerHTML = cart1.create();\n cartBtnContent.innerHTML = 'Open cart [' + cartItem.instances.length + ']' //update cart button inner HTML\n}", "function removeCartItem(event) {\n var buttonClicked = event.target\n buttonClicked.parentElement.parentElement.parentElement.remove();\n //Update the cart total after the cart item has been removed.\n updateCartTotal()\n }", "createCard(item) {\n return (\n <Card style={cardWrapper}>\n <Card.Img variant=\"top\" src={item.image} />\n <Card.Body>\n <Card.Title>{item.name}</Card.Title>\n <Card.Subtitle> Price: ${item.price} </Card.Subtitle>\n <br />\n <Card.Subtitle> Shelf Life: {item.shelf_life} </Card.Subtitle>\n <br />\n <Card.Subtitle> Category: {item.type} </Card.Subtitle>\n <br />\n <Button onClick={() => this.props.addToCart(item)} variant=\"primary\">Add to Cart</Button>\n <br />\n <Button className=\"mt-1\" onClick={() => this.props.removeFromCart(item)} variant=\"primary\">Remove 1 from Cart</Button>\n </Card.Body>\n </Card>\n )\n }", "function removeCartItem(event) {\n let buttonClicked = event.target;\n buttonClicked.parentElement.parentElement.remove();\n updateCartTotal();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When an incoming mutation is applied to HEAD, this is called to remove the mutation from the unresolved state. If the newly applied patch is the next upcoming unresolved mutation, no rebase is needed, but we might have the wrong idea about the ordering of mutations, so in that case we are given the flag `needRebase` to tell us that this mutation arrived out of order in terms of our optimistic version, so a rebase is needed.
consumeUnresolved(txnId) { // If we have nothing queued up, we are in sync and can apply patch with no // rebasing if (this.submitted.length == 0 && this.pending.length == 0) { return false; } // If we can consume the directly upcoming mutation, we won't have to rebase if (this.submitted.length != 0) { if (this.submitted[0].transactionId == txnId) { (0, _debug.default)("Remote mutation %s matches upcoming submitted mutation, consumed from 'submitted' buffer", txnId); this.submitted.shift(); return false; } } else if (this.pending.length > 0 && this.pending[0].transactionId == txnId) { // There are no submitted, but some are pending so let's check the upcoming pending (0, _debug.default)("Remote mutation %s matches upcoming pending mutation, consumed from 'pending' buffer", txnId); this.pending.shift(); return false; } (0, _debug.default)('The mutation was not the upcoming mutation, scrubbing. Pending: %d, Submitted: %d', this.pending.length, this.submitted.length); // The mutation was not the upcoming mutation, so we'll have to check everything to // see if we have an out of order situation this.submitted = this.submitted.filter(mut => mut.transactionId != txnId); this.pending = this.pending.filter(mut => mut.transactionId != txnId); (0, _debug.default)("After scrubbing: Pending: %d, Submitted: %d", this.pending.length, this.submitted.length); // Whether we had it or not we have either a reordering, or an unexpected mutation // so must rebase return true; }
[ "removeMutation() {\n this.setState({\n externalMutations: undefined\n });\n }", "function rebase(toHEAD) {\n return function (store) {\n var sceneGraph = store.get('sceneGraph');\n var HEAD = sceneGraph.refs.HEAD;\n\n return store.dispatch(saveIndex()).then(function () {\n var INDEX = sceneGraph.refs.INDEX;\n\n return ensureObjectsFor(store, toHEAD).then(function () {\n if (HEAD === INDEX) {\n return store.dispatch(setToCommit({ toHEAD: toHEAD, options: {} }));\n } else {\n // checkout common ancestor, then merge upstream HEAD and INDEX on top.\n store.dispatch(setToCommit({ toHEAD: HEAD, options: {} }));\n return store.dispatch(setToCommit({\n toHEAD: toHEAD,\n fromHEAD: HEAD,\n secondHEAD: INDEX,\n options: {}\n }));\n }\n });\n });\n };\n}", "forceCommit() {\n let nextState = this.state;\n nextState = this.applyDecorators(nextState);\n this.execAsyncMutations(nextState);\n this.replaceState(nextState);\n }", "rebase(newBasis) {\n this.stashStagedOperations();\n\n if (newBasis === null) {\n // If document was just deleted, we must throw out local changes\n this.out = [];\n this.PRESTAGE = this.BASIS = newBasis;\n } else {\n this.BASIS = newBasis;\n\n if (this.out) {\n this.PRESTAGE = new _Mutation.default({\n mutations: this.out\n }).apply(this.BASIS);\n } else {\n this.PRESTAGE = this.BASIS;\n }\n }\n\n return this.PRESTAGE;\n }", "hasUnresolvedMutations() {\n return this.submitted.length > 0 || this.pending.length > 0;\n }", "anyUnresolvedMutations() {\n return this.submitted.length > 0 || this.pending.length > 0;\n }", "[_moveBackRetiredUnchanged] () {\n // get a list of all unchanging children of any shallow retired nodes\n // if they are not the ancestor of any node in the diff set, then the\n // directory won't already exist, so just rename it over.\n // This is sort of an inverse diff tree, of all the nodes where\n // the actualTree and idealTree _don't_ differ, starting from the\n // shallowest nodes that we moved aside in the first place.\n const moves = this[_retiredNodes]\n this[_retiredUnchanged] = {}\n return promiseAllRejectLate(this.diff.children.map(diff => {\n const realFolder = (diff.actual || diff.ideal).path\n const retireFolder = moves[realFolder]\n this[_retiredUnchanged][retireFolder] = []\n return promiseAllRejectLate(diff.unchanged.map(node => {\n // no need to roll back links, since we'll just delete them anyway\n if (node.isLink)\n return mkdirp(dirname(node.path)).then(() => this[_reifyNode](node))\n\n if (node.inBundle) {\n // will have been moved/unpacked along with bundler\n return\n }\n\n this[_retiredUnchanged][retireFolder].push(node)\n\n const rel = relative(realFolder, node.path)\n const fromPath = resolve(retireFolder, rel)\n // if it has bundleDependencies, then make node_modules. otherwise\n // skip it.\n const bd = node.package.bundleDependencies\n const dir = bd && bd.length ? node.path + '/node_modules' : node.path\n return mkdirp(dir).then(() => this[_moveContents](node, fromPath))\n }))\n }))\n .catch(er => this[_rollbackMoveBackRetiredUnchanged](er))\n }", "conflicted ({ created, mutation }) {\n if (mutation.conflicted) {\n return true\n }\n for (const version of mutation.competitors) {\n if (mutation.version != version) {\n const group = this._groupByVersion(version)\n const competitor = group.mutations.get(version)\n assert(competitor)\n if (competitor.completed > created && ! competitor.rolledback) {\n mutation.conflicted = true\n mutation.rolledback = true\n break\n }\n }\n }\n return mutation.conflicted\n }", "function remove_redundant_modified_entry(me) {\n // Delete Previous Overwrite: remove from delta.modified[]\n for (var i = 0; i < me.delta.modified.length; i++) {\n var op_path = me.delta.modified[i].op_path;\n if (subarray_elements_match(op_path, me.op_path, \"K\")) {\n me.delta.modified.splice(i, 1); // remove entry from modified[]\n return; // there will only be one\n }\n }\n}", "addRemoteMutation(entry){if(this._trace)this._trace.push({type:\"addRemoteMutation\",event:entry});const pending=this._possiblePendingTransactions.get(entry.transactionId);const transaction=pending?pending.transaction:{index:0,id:entry.transactionId,timestamp:entry.timestamp.toISOString(),author:entry.author};if(entry.version===\"draft\"){transaction.draftEffect=entry.effects;}else{transaction.publishedEffect=entry.effects;}if(pending){this._possiblePendingTransactions.delete(entry.transactionId);this._invalidateTransactionFrom(pending.idx);}else{this._transactions.addToEnd(transaction);this._possiblePendingTransactions.set(entry.transactionId,{transaction,idx:this._transactions.lastIdx});}}", "[CURRENT_DRAFT_ISSUE_REMOVE](state, issue) {\n const stateCopy = state.issues;\n const filteredState = stateCopy.filter(item => {\n return item.id !== issue.id;\n });\n state.issues = filteredState;\n }", "firebaseRemovePending({ state, commit }, payload) {\n let otherUserId = payload\n commit('removePending', payload) // remove from store\n firebaseDb.ref('friends/' + state.userDetails.userId + '/pending/' + otherUserId).remove() // remove drom db\n }", "async rebase() {\n const diff =\n (await this._wallet.getLowestLiquidNonce()) - this._lowestLiquidNonce;\n this._queue.splice(0, diff); // Could log confirmed txs via returned array slice\n this._lowestLiquidNonce += diff;\n }", "_mutationHandler() {\n // Ignore the mutation if using autobuild\n if (this.autobuild) return;\n\n this.update = true;\n this.rebuild();\n }", "function queueMutation(mutation) {\n\t\t// for single-node updates, merge into pending updates\n\t\tif (mutation.type==='characterData' || mutation.type==='attributes') {\n\t\t\tfor (let i=MUTATION_QUEUE.length; i--; ) {\n\t\t\t\tlet m = MUTATION_QUEUE[i];\n\t\t\t\t// eslint-disable-next-line eqeqeq\n\t\t\t\tif (m.type==mutation.type && m.target.__id==mutation.target.__id) {\n\t\t\t\t\tif (m.type==='attributes') {\n\t\t\t\t\t\tMUTATION_QUEUE.splice(i+1, 0, mutation);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tMUTATION_QUEUE[i] = mutation;\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (MUTATION_QUEUE.push(mutation)===1) {\n\t\t\tdoProcessMutationQueue();\n\t\t}\n\t}", "checkCanPlaceCurrent () {\n const { preferDedupe, explicitRequest, current, target, edge, dep } = this\n\n if (dep.matches(current)) {\n if (current.satisfies(edge) || this.edgeOverride) {\n return explicitRequest ? REPLACE : KEEP\n }\n }\n\n const { version: curVer } = current\n const { version: newVer } = dep\n const tryReplace = curVer && newVer && semver.gte(newVer, curVer)\n if (tryReplace && dep.canReplace(current)) {\n // It's extremely rare that a replaceable node would be a conflict, if\n // the current one wasn't a conflict, but it is theoretically possible\n // if peer deps are pinned. In that case we treat it like any other\n // conflict, and keep trying.\n const cpp = this.canPlacePeers(REPLACE)\n if (cpp !== CONFLICT) {\n return cpp\n }\n }\n\n // ok, can't replace the current with new one, but maybe current is ok?\n if (current.satisfies(edge) && (!explicitRequest || preferDedupe)) {\n return KEEP\n }\n\n // if we prefer deduping, then try replacing newer with older\n if (preferDedupe && !tryReplace && dep.canReplace(current)) {\n const cpp = this.canPlacePeers(REPLACE)\n if (cpp !== CONFLICT) {\n return cpp\n }\n }\n\n // Check for interesting cases!\n // First, is this the deepest place that this thing can go, and NOT the\n // deepest place where the conflicting dep can go? If so, replace it,\n // and let it re-resolve deeper in the tree.\n const myDeepest = this.deepestNestingTarget\n\n // ok, i COULD be placed deeper, so leave the current one alone.\n if (target !== myDeepest) {\n return CONFLICT\n }\n\n // if we are not checking a peerDep, then we MUST place it here, in the\n // target that has a non-peer dep on it.\n if (!edge.peer && target === edge.from) {\n return this.canPlacePeers(REPLACE)\n }\n\n // if we aren't placing a peer in a set, then we're done here.\n // This is ignored because it SHOULD be redundant, as far as I can tell,\n // with the deepest target and target===edge.from tests. But until we\n // can prove that isn't possible, this condition is here for safety.\n /* istanbul ignore if - allegedly impossible */\n if (!this.parent && !edge.peer) {\n return CONFLICT\n }\n\n // check the deps in the peer group for each edge into that peer group\n // if ALL of them can be pushed deeper, or if it's ok to replace its\n // members with the contents of the new peer group, then we're good.\n let canReplace = true\n for (const [entryEdge, currentPeers] of peerEntrySets(current)) {\n if (entryEdge === this.edge || entryEdge === this.peerEntryEdge) {\n continue\n }\n\n // First, see if it's ok to just replace the peerSet entirely.\n // we do this by walking out from the entryEdge, because in a case like\n // this:\n //\n // v -> PEER(a@1||2)\n // a@1 -> PEER(b@1)\n // a@2 -> PEER(b@2)\n // b@1 -> PEER(a@1)\n // b@2 -> PEER(a@2)\n //\n // root\n // +-- v\n // +-- a@2\n // +-- b@2\n //\n // Trying to place a peer group of (a@1, b@1) would fail to note that\n // they can be replaced, if we did it by looping 1 by 1. If we are\n // replacing something, we don't have to check its peer deps, because\n // the peerDeps in the placed peerSet will presumably satisfy.\n const entryNode = entryEdge.to\n const entryRep = dep.parent.children.get(entryNode.name)\n if (entryRep) {\n if (entryRep.canReplace(entryNode, dep.parent.children.keys())) {\n continue\n }\n }\n\n let canClobber = !entryRep\n if (!entryRep) {\n const peerReplacementWalk = new Set([entryNode])\n OUTER: for (const currentPeer of peerReplacementWalk) {\n for (const edge of currentPeer.edgesOut.values()) {\n if (!edge.peer || !edge.valid) {\n continue\n }\n const rep = dep.parent.children.get(edge.name)\n if (!rep) {\n if (edge.to) {\n peerReplacementWalk.add(edge.to)\n }\n continue\n }\n if (!rep.satisfies(edge)) {\n canClobber = false\n break OUTER\n }\n }\n }\n }\n if (canClobber) {\n continue\n }\n\n // ok, we can't replace, but maybe we can nest the current set deeper?\n let canNestCurrent = true\n for (const currentPeer of currentPeers) {\n if (!canNestCurrent) {\n break\n }\n\n // still possible to nest this peerSet\n const curDeep = deepestNestingTarget(entryEdge.from, currentPeer.name)\n if (curDeep === target || target.isDescendantOf(curDeep)) {\n canNestCurrent = false\n canReplace = false\n }\n if (canNestCurrent) {\n continue\n }\n }\n }\n\n // if we can nest or replace all the current peer groups, we can replace.\n if (canReplace) {\n return this.canPlacePeers(REPLACE)\n }\n\n return CONFLICT\n }", "function rebase(args) {\n return cmd_1.cmd.executeRequired(git.info.path, ['rebase', args.onto.name, args.branch.name]);\n }", "async removeRequiredStatusCheck(user, repo, branch, check, accessToken) {\n const url = API_URL_TEMPLATES.REQUIRED_STATUS_CHECKS\n .replace('${owner}', user)\n .replace('${repo}', repo)\n .replace('${branch}', branch)\n const settings = await this.getRequiredStatusChecks(user, repo, branch, accessToken)\n const requiredChecks = getIn(settings, 'contexts', [])\n if (requiredChecks.indexOf(check) !== -1) {\n const payload = {\n \"include_admins\": true,\n \"contexts\": requiredChecks.filter(required => check !== required)\n }\n debug(`${user}/${repo}: Removing status check ${check}`)\n await this.fetchPath('PATCH', url, payload, accessToken, {'Accept': BRANCH_PREVIEW_HEADER})\n }\n }", "'CallExpression[callee.name=commitMutation]:not([typeArguments])'(node) {\n // Get mutation config. It should be second argument of the `commitMutation`\n const mutationConfig = node.arguments && node.arguments[1];\n if (\n mutationConfig == null ||\n mutationConfig.type !== 'ObjectExpression'\n ) {\n return;\n }\n // Find `mutation` property on the `mutationConfig`\n const mutationNameProperty = mutationConfig.properties.find(\n prop => prop.key != null && prop.key.name === 'mutation'\n );\n if (\n mutationNameProperty == null ||\n mutationNameProperty.value == null\n ) {\n return;\n }\n const mutationName = getDefinitionName(mutationNameProperty.value);\n context.report({\n node: node,\n message:\n 'The `commitMutation` must be used with an explicit generated Flow type, e.g.: commitMutation<{{mutationName}}>(...)',\n data: {\n mutationName: mutationName || 'ExampleMutation'\n },\n fix:\n mutationName != null && options.fix\n ? createTypeImportFixer(node, mutationName, mutationName)\n : null\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transmit the message and rearm the timer
function txandrerun(msg) { node.send(msg); timerRef = setTimeout(testSource, 30 * 1000); }
[ "function sendTimerStop() {\n emitEvent(constants.socketEvents.timerStop, '0');\n }", "function socketSendTimer() {\n ws.send(\"Socket Refreshed\");\n}", "function sentTimer() {\n pubsub.publish(\"serverClock\");\n}", "function sendTimerPause() {\n // Make sure timer is running\n if (vm.timer.run) {\n emitEvent(constants.socketEvents.timerPause, '0');\n }\n }", "function alarm() {\n\n /* set new status */\n status();\n\n /* send new msg */\n send();\n }", "function timerMOTD(client, server) { setInterval(function() { sendMOTD(client, server); }, 500); }", "_scheduleSendResponseMessage() {\n\n }", "async triggerOnReceive() {\n await this._modbusClient.writeRegister(this._typeParams.registers.startAddress, \n this._typeParams.triggerOnReceive);\n console.log(\"Watchdog: timer is now set to trigger on receiving telegrams.\");\n }", "send(lag_ms,message) {\n this.messages.push({recv_ts:+ new Date() + lag_ms,payload:message});\n }", "send(lagMs, message) {\n this.messages.push({\n recvTs: Date.now() + lagMs,\n payload: message\n });\n }", "function sendHeartBeat () {\n sendMessage(\"heartbeat\");\n}", "messageTimeout () {\n\t\tthis.messageCallback();\n\t}", "function sendTimerStart() {\n var end;\n if (vm.timeMode === 1) {\n // Countdown mode\n if (vm.timer.pause) {\n // Paused timer\n // Add pause time to current time\n end = moment().add(vm.timer.pauseTime, 'milliseconds');\n // Clear pause time\n vm.timer.pauseTime = 0;\n } else {\n // Regular start\n // Calculate from Hrs Min Sec\n end = moment().add(vm.time.hours, 'hours')\n .add(vm.time.minutes, 'minutes')\n .add(vm.time.seconds, 'seconds');\n }\n } else {\n // End time mode\n end = moment().startOf('day').add(vm.time.end);\n if (end < moment()) {\n logger.warning('End time is less than start time');\n return;\n }\n }\n emitEvent(constants.socketEvents.timerStart, {end: end});\n }", "startMusicTimer() {\n setTimeout(() => {\n console.log(\"Sending music\")\n if(this.state.state === this.StateSelectMusic) {\n console.log(\"Music sent\")\n this.serial.sendHex(this.state.music);\n this.serial.read(64);\n this.startMusicTimer();\n } else {\n console.log(\"invalid state\")\n }\n }, 100);\n }", "function\nWebSocketIFHandleSetTimeResponse\n(InResponse)\n{\n MainDisplayMessage(InResponse.message);\n}", "function startTimer () {\n timerInt = setInterval(function () {\n document.getElementById('timer').textContent = \"Time Left: \" + secondsLeft;\n secondsLeft--;\n if(secondsLeft === -2) {\n clearInterval(timerInt);\n sendMessage();\n} \n}, 1000);\n}", "txTick() {\n var t = this;\n if (!t.lastTxSuccess) {\n if (t.lastCmdSendMs == null) { // If command has already been received\n if (t.nextTxAttMs != null) {\n if (Date.now() > t.nextTxAttMs && t.port.canWrite()) {\n t.nextTxAttMs = null;\n // If it's been long enough, try re-sending it\n t.port.write(t.writeLastSend);\n t.lastTxSuccess = false;\n t.lastCmdSendMs = Date.now();\n }\n }\n else {\n t.nextTxAttMs = Date.now() + t.QUEUE_FULL_DELAY;\n }\n }\n return;\n }\n\n // TODO this is where we handle station identification auto-command-sending\n\n if (t.writeBuffer.length == 0 && t.writeQueue.length > 0)\n t.writeBuffer = t.createWriteBuffer(t.writeQueue.pop())\n\n if (t.writeBuffer.length > 0) {\n var toSend = t.writeBuffer;\n if (t.writeBuffer.length > t.MAX_PACKET_LEN) {\n toSend = t.writeBuffer.substring(0, t.MAX_PACKET_LEN);\n t.writeBuffer = t.writeBuffer.substring(t.MAX_PACKET_LEN);\n if(toSend.endsWith(\"\\xFF\") && toSend.charAt(toSend.length - 2) != \"\\xFF\"){\n toSend = toSend.slice(0, -1); // if toSend ends with a single 255, stuff it back in writeBuffer\n t.writeBuffer = \"\\xFF\" + t.writeBuffer;\n }\n } else {\n t.writeBuffer = \"\";\n }\n // Escaping of spaces doesn't change the LoRa packet length, so is performed here\n t.writeLastSend = \"T \" + toSend.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(' ', \"\\\\ \") + \"\\n\";\n t.port.write(t.writeLastSend);\n t.lastTxSuccess = false;\n t.lastCmdSendMs = Date.now();\n }\n }", "setSentMessage() {\n if (!this.state.isBroadcasting) {\n this.resetTimeout();\n }\n }", "function continousSendRemoteCommand(){\n setInterval(function() {\n process.stdout.write('sending IR command: BTN_MUTING to SONY_RM device..')\n sendIrCommand('SONY_RM-AAU014','BTN_MUTING') // check LED on MATRIX\n console.log('done.')\n }, 3000);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
inactivate a relationship and add new relationships for children
function inactivateRelationship(rel, axiom, newTargets) { angular.forEach(newTargets, function (parent) { var newRel = angular.copy(rel); newRel.relationshipId = null; newRel.effectiveTime = null; newRel.released = false; newRel.target.conceptId = parent.conceptId; newRel.target.fsn = parent.fsn; newRel.new = true; axiom.relationships.push(newRel); }); }
[ "setRelations () {\n this[hasMany].forEach(relation => {\n this[relation] = (new Blueprint(relation)).belongsTo(this)\n })\n }", "function addRelationship(){\n\n if(vm.relationshipFrom ==undefined || vm.relationshipTo == undefined || vm.relation == undefined){\n logError('All fields should be selected to create a relationship'); \n return; \n }\n datacontext.createRelationshipByNodeId(vm.relationshipFrom.n.id, vm.relationshipTo.n.id, vm.relation, vm.relationshipDescription)\n .then(function(result){\n getAllRelationships();\n log('Relationship created');\n vm.relationshipFrom = null; vm.relationshipTo = null; vm.relation = null;\n });\n \n }", "setRelations () {\n this.config.hasMany.forEach(relation => {\n this[relation] = app.model(relation, false).belongsTo(this)\n })\n }", "_associateWithNewInverses(association) {\n if (!this.__isSavingNewChildren) {\n let modelOrCollection = this[association.name];\n\n if (modelOrCollection instanceof Model) {\n this._associateModelWithInverse(modelOrCollection, association);\n } else if (modelOrCollection instanceof Collection || modelOrCollection instanceof PolymorphicCollection) {\n modelOrCollection.models.forEach(model => {\n this._associateModelWithInverse(model, association);\n });\n }\n\n delete this._tempAssociations[association.name];\n }\n }", "rebuildRelationships(children, parent) {\n parent.suspendRelationshipObservers(function() {\n // TODO: figure out a way to preserve ordering (or screw ordering and use sets)\n for(var i = 0; i < children.length; i++) {\n var child = children[i];\n \n child.eachLoadedRelationship(function(name, relationship) {\n // TODO: handle hasMany's for non-relational databases...\n if(relationship.kind === 'belongsTo') {\n var value =child[name],\n inverse = child.constructor.inverseFor(name);\n \n if(inverse) {\n if(!(parent instanceof inverse.parentType)) {\n return;\n }\n // if embedded then we are certain the parent has the correct data\n if(this.embeddedType(inverse.parentType, inverse.name)) {\n return;\n }\n \n if(inverse.kind === 'hasMany' && parent.isFieldLoaded(inverse.name)) {\n var parentCollection =parent[inverse.name];\n if(child.isDeleted) {\n parentCollection.removeObject(child);\n } else if(value && value.isEqual(parent)) {\n // TODO: make sure it doesn't already exists (or change model arrays to sets)\n // TODO: think about 1-1 relationships\n parentCollection.addObject(child);\n }\n }\n \n }\n }\n }, this);\n }\n }, this);\n }", "function resolveRelated(np) {\n\n var fkNames = np.foreignKeyNames;\n if (fkNames.length === 0) return;\n\n var parentEntityType = np.parentType;\n var fkProps = fkNames.map(function (fkName) {\n return parentEntityType.getDataProperty(fkName);\n });\n var fkPropCollection = parentEntityType.foreignKeyProperties;\n\n fkProps.forEach(function (dp) {\n __arrayAddItemUnique(fkPropCollection, dp);\n dp.relatedNavigationProperty = np;\n // now update the inverse\n __arrayAddItemUnique(np.entityType.inverseForeignKeyProperties, dp);\n if (np.relatedDataProperties) {\n __arrayAddItemUnique(np.relatedDataProperties, dp);\n } else {\n np.relatedDataProperties = [dp];\n }\n });\n }", "addRelationship(node, type) {\n // Don't add duplicates are itself to relationships.\n if (!this.hasRelationship(node) && node.id !== this.id) {\n this.relationships.push({\n id : node.id,\n features: node.features,\n type : type\n });\n\n // Every relationship is two way.\n node.addRelationship(this, type);\n }\n }", "async setRelationship(property, ref, optionalValue = true) {\n this._errorIfNothasOneReln(property, \"setRelationship\");\n const mps = this.db.multiPathSet(\"/\");\n this._relationshipMPS(mps, ref, property, optionalValue, new Date().getTime());\n this.dispatch(this._createRecordEvent(this, index_1.FMEvents.RELATIONSHIP_ADDED_LOCALLY, mps.payload));\n await mps.execute();\n this.dispatch(this._createRecordEvent(this, index_1.FMEvents.RELATIONSHIP_ADDED, this.data));\n }", "function updateRelation(){\n}", "reAddDescendants(){\n this.mapOverChildren(c=>{\n this.addChild(c);\n c.reAddDescendants();\n });\n }", "addToRelationship(type, id, relationshipPath, newLinkage) {\n let model = this.getModel(this.constructor.getModelName(type));\n let update = {\n $addToSet: {\n [relationshipPath]: { $each: newLinkage.value.map(it => it.id)}\n }\n };\n let options = {runValidators: true};\n\n return Q.ninvoke(model, \"findOneAndUpdate\", {\"_id\": id}, update, options)\n .catch(util.errorHandler);\n }", "function re_AddRelationship(relationType, parentTableName, childTableName, init) {\r\n\r\n\tif (parentTableName == null || childTableName == null) {\r\n\t\tvar errMsg = \"One of the following string is null:\"\r\n\t\t\t\t+ \" parentTableName: \" + parentTableName\r\n\t\t\t\t+ \", childTableName: \" + childTableName\r\n\t\t\t\t+ \"\\n\";\r\n\t\t\t\t\r\n\t\tsy_logError(\"ERD-relationship\", \r\n\t\t\t\t\"re_AddRelationship\", \r\n\t\t\t\terrMsg);\r\n\t\t\t\t\r\n\t\treturn false;\r\n\t}\r\n\t\t\r\n\t//\t\r\n\t// create a relationDiv\r\n\t//\r\n\tvar relationID = parentTableName + \"__\" + childTableName;\r\n\trelationDiv = document.createElement(\"div\");\r\n\t\trelationDiv.id = relationID;\r\n\t\trelationDiv.className = CL_DB_RELATION;\r\n\r\n\t\t// random number between -25 and 25\r\n\t\trelationDiv.fromRandom = Math.floor((Math.random()-0.5)*50);\r\n\t\trelationDiv.toRandom = Math.floor((Math.random()-0.5)*50);\r\n\t\t\r\n\t\t//var relationType = sysModeField;\r\n\t\trelationDiv.relationType = relationType;\r\n\t\r\n\tdocument.body.appendChild(relationDiv);\r\n\r\n\t//\r\n\t// add table names to the parent/child arrays \r\n\t//\t\t\t\t\t\t\t\t\t ^^^^^^\r\n\tif (!tb_AddRelationshipToTables(parentTableName, childTableName)) {\r\n\t\tsy_logError(\"ERD-relationship\", \r\n\t\t\t\t\t\"re_AddRelationship\", \r\n\t\t\t\t\t\"Error adding relationship for: \"\r\n\t\t\t\t\t\t+ \"parentTableName: \" + parentTableName\r\n\t\t\t\t\t\t+ \", childTableName: \" + childTableName);\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t\r\n\t//\r\n\t// when we read the data from xml file, we don't want to \r\n\t//\t\tcreate any foreign key since it's in the table already\r\n\t//\r\n\tif (!init) {\r\n\t\r\n\t\t//\r\n\t\t// adding foreign key column(s) to the child table\r\n\t\t// \t\t(MOD_ONE2ONE or MOD_ONE2MANY)\r\n\t\t//\r\n\t\tvar pKeyColumnArray = co_GetPKeyTrArray(parentTableName);\r\n\r\n\t\tif (!co_AddFKeyTrArray(relationType, childTableName, pKeyColumnArray)) {\r\n\t\t\tsy_logError(\"ERD-mouseEvent\", \r\n\t\t\t\t\t\t\t\"ev_MouseDown\", \r\n\t\t\t\t\t\t\t\"Error adding foreing key for html table body: \"\r\n\t\t\t\t\t\t\t\t+ \"parentTableName: \" + parentTableName\r\n\t\t\t\t\t\t\t\t+ \", childTableName: \" + childTableName);\r\n\t\t}\r\n\r\n\t\t// if one to one, \r\n\t\t//\ta new primary key for the child table\r\n\t\t//\t\t--> need new foreign key for the grand children\r\n\t\t//\t\t\t\t\t\t\t\t\t\t ^^^^^^^^^^^^^^\r\n\t\tif (relationType == MOD_ONE2ONE) {\r\n\r\n\t\t\t// NOTE: one to many for the children!!!\r\n\r\n\t\t\tvar childTableDiv = tb_GetTableObj(childTableName);\t\r\n\t\t\tvar childPKeyArray = co_GetPKeyTrArray(childTableName);\r\n\r\n\t\t\tvar grandChildrenArray = childTableDiv.childArray;\r\n\r\n\t\t\tfor (var i=0;i<grandChildrenArray.length;i++) {\r\n\r\n\t\t\t\tvar grandChidlTable = grandChildrenArray[i];\r\n\r\n\t\t\t\tif (!co_AddFKeyTrArray(MOD_ONE2MANY, grandChidlTable, childPKeyArray)) {\r\n\t\t\t\t\tsy_logError(\"ERD-mouseEvent\", \r\n\t\t\t\t\t\t\t\t\"ev_MouseDown\", \r\n\t\t\t\t\t\t\t\t\"Error adding foreing key for html table body: \"\r\n\t\t\t\t\t\t\t\t\t\t+ \"parentTableName: \" + childTableName\r\n\t\t\t\t\t\t\t\t\t\t+ \", childTableName: \" + grandChidlTable);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// @@@ can we move this to somewhere else????\r\n\t\t\t\t// RE-create a short view\r\n\t\t\t\trefreshShortView(grandChidlTable);\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t}\t\r\n\t\r\n\t//\r\n\t// points for the relationship relationDiv\r\n\t//\r\n\tif (re_GetPoints(parentTableName, childTableName) == null) {\r\n\t\tsy_logError(\"ERD-relationship\", \r\n\t\t\t\t\t\"re_AddRelationship\", \r\n\t\t\t\t\t\"Error getting relationship from and to points for: \"\r\n\t\t\t\t\t\t+ \"parentTableName: \" + parentTableName\r\n\t\t\t\t\t\t+ \", childTableName: \" + childTableName);\r\n\t\treturn false;\r\n\t}\r\n\r\n\t/*\r\n\t// poly line\r\n\tvar p = document.createElement(\"v:polyline\");\r\n\t\tp.strokeweight = .1+\"pt\";\r\n\t\tp.strokecolor = \"green\";\r\n\t\tp.points = \"50,235,50,145,12,123\";\r\n\t\tdocument.body.appendChild(p);\r\n\t*/\r\n\t\r\n\t //line\r\n\t var l = document.createElement(\"v:line\");\r\n\t \tl.id = \"LN\" + relationID;\r\n//\t\tl.className = CL_DB_RELATION;\t \r\n\t\tl.strokeweight = .1+\"pt\";\r\n\t\tl.strokecolor = \"black\";\r\n\t\tl.from = fromX + \"px, \" + fromY + \"px\";\r\n\t\tl.to = (toX-2) + \"px, \" + (toY-2) + \"px\";\r\n\t\t\tl.style.position = \"absolute\";\r\n\t\t\tl.style.left = 0;\r\n\t\t\tl.style.top = 0;\r\n\r\n\t\t// MOD_ONE2MANY\r\n\t\tif (relationType == MOD_ONE2MANY) {\r\n\t\t\tl.strokeweight = .5+\"pt\";\r\n\t\t\tvar stroke = document.createElement(\"v:stroke\");\r\n\t\t\tstroke.dashstyle=\"longdash\" \r\n\t\t\tl.appendChild(stroke);\r\n\t\t}\r\n\t\t\r\n\trelationDiv.appendChild(l);\r\n\t\r\n\t var circle = document.createElement(\"v:oval\");\r\n\t \tcircle.id = \"CR\" + relationID;\r\n//\t\tcircle.className = CL_DB_RELATION;\t \r\n\t\tif (relationType == MOD_ONE2MANY)\r\n\t\t\tcircle.fillcolor = \"gray\";\r\n\t\tcircle.style.width=\"4pt\";\r\n\t\tcircle.style.height=\"4pt\";\r\n\t\tcircle.style.left = (toX-4) + \"px\";\r\n\t\tcircle.style.top = (toY-4) + \"px\";\r\n\t\tcircle.style.position = \"absolute\";\r\n\r\n\trelationDiv.appendChild(circle);\r\n\t\r\n\t\r\n\treturn true;\r\n}", "set(newCollection) {\n this.args.model.relationships[this.args.reflectionName] = newCollection\n }", "loadRelations() {\n this.__loadRelations();\n }", "set(models) {\n models = models ? _compact(models) : [];\n\n if (this.isNew()) {\n association._cachedChildren = models instanceof Collection ? models : new Collection(association.modelName, models);\n\n } else {\n\n // Set current children's fk to null\n let query = { [foreignKey]: this.id };\n schema[toCollectionName(association.modelName)].where(query).update(foreignKey, null);\n\n // Save any children that are new\n models.filter((model) => model.isNew())\n .forEach((model) => model.save());\n\n // Associate the new children to this model\n schema[toCollectionName(association.modelName)].find(models.map((m) => m.id)).update(foreignKey, this.id);\n\n // Clear out any old cached children\n association._cachedChildren = new Collection(association.modelName);\n }\n }", "setRelation(relation) {\n this.relations.length = 0; // avoid the issue originated by the referece sharing\n this.relations.push(relation);\n }", "addRelation(relation) {\n this.relations.push(relation);\n }", "activate() {\n this.active = true\n this.contacts.forEach(contact => contact.parentActivated())\n }", "addChildAttributeForExplicitRelation(event) {\n\t\t//console.log(event.target.value)\n\t\t//console.log(event.target)\n\t\tif (this.state[this.state.selectedObject.objectID].relation.type !== '') {\n\t\t\talert('A relation already exists on this object')\n\t\t\treturn\n\t\t}\n\t\t// * SAVING PARENT OBJECT TO RELATION DETAILS OF SELECTED OBJECT\n\n\n\n\t\tvar attributeName = event.target.value.object + '.' + event.target.value.attributeName\n\t\tthis.setState({\n\t\t\t...this.state,\n\t\t\texplicitRelation: {\n\t\t\t\t...this.state.explicitRelation,\n\t\t\t\tattribute: {\n\t\t\t\t\t...event.target.value\n\t\t\t\t},\n\t\t\t\texpression: this.state.explicitRelation.expression !== undefined ? this.state.explicitRelation.expression + attributeName : attributeName\n\t\t\t}\n\t\t})\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }