query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Function that shuffles cards based on css order | function shuffle(cards) {
cards.forEach(card => {
let randomize = Math.floor(Math.random() * 10);
card.style.order = randomize;
});
} | [
"function shuffle() {\n cards.forEach(card => {\n let randPos = Math.floor(Math.random() * 12);\n card.style.order = randPos;\n })\n}",
"function shuffleCards() {\n removeCards();\n const shuffleArray = cards.sort(() => Math.random() - 0.5);\n displayCards(shuffleArray);\n styleCards();\n}",
"function rearrange() {\n cards = shuffle(cards);\n for (var i = 0; i < cards.length; i++) {\n deck.innerHTML = \"\";\n [].forEach.call(cards, function(item) {\n deck.appendChild(item);\n });\n cards[i].classList.remove(\"show\", \"open\", \"match\", \"disabled\");\n }\n}",
"shuffleCards(cards, checkNames) {\n let j = 0;\n cards.forEach((card, index) => {\n let random = Math.floor(Math.random() * 12);\n\n card.style.order = random;\n index % 2 == 0 ? j++ : (j = j);\n card.type = checkNames[j];\n });\n }",
"function shuffleCards() {\n var shuffledCards = shuffle(cards);\n $(shuffledCards).each(function(index, value) {\n $(\".cards\").append($(value));\n });\n }",
"function shuffleDeckFrench() {\n $(\".game-card-fr\").each(function () {\n let shuffleDeckFrench = Math.floor(Math.random() * 21);\n this.style.order = shuffleDeckFrench;\n });\n }",
"function shuffle_Cards(){\n symbols = shuffle(symbols);\n\n // to make the shuffling appear in Markup also not just inside the symbols array\n let i=0;\n allcards.forEach(card => {\n let icon = card.children[0];\n icon.className = symbols[i];\n i++;\n });\n }",
"function shuffle(x) {\n var tarjetas = document.querySelectorAll('.tarjetas');\n\n for (i = 0; i < x; i++) {\n posicion = Math.floor(Math.random() * 16);\n tarjetas[i].style.order = posicion;\n }\n}",
"shuffle() {\n for (let i = this.cards.length - 1; i > 0; i--) {\n const newIndex = Math.floor(Math.random() * (i + 1)); //get random index before the current card to swap with\n const oldValue = this.cards[newIndex];\n this.cards[newIndex] = this.cards[i];\n this.cards[i] = oldValue;\n //Looping through all of our cards and swapping them with another card to get a random shuffle\n }\n }",
"shuffle() {\n this.activeCards = _.shuffle(this.activeCards);\n }",
"function shuffleCards() {\n\t\t\tvar curr_index = cards.length, \n\t\t\t\ttemp_value, \n\t\t\t\trand_index;\n\t\t\twhile (0 !== curr_index){\n\t\t\t\t// Pick random value\n\t\t\t\trand_index = Math.floor(Math.random() * curr_index);\n\t\t\t\tcurr_index--;\n\t\t\t\t// Swap the randomly picked value with the current one\n\t\t\t\ttemp_value = cards[curr_index];\n\t\t\t\tcards[curr_index] = cards[rand_index];\n\t\t\t\tcards[rand_index] = temp_value;\n\t\t\t}\n\t\t}",
"function shuffleDeck() {\n const shuffleCards = shuffle(cardsList);\n for(card of shuffleCards) {\n deck.appendChild(card);\n }\n}",
"function randomOrder(){\n for(let i = 0; i < flipCard.length; i++){ \n randomNum = Math.floor(Math.random() * 16);\n flipCard[i].style.order = randomNum;\n }\n }",
"function shufflePlayCards() {\r\n shuffle(numArray4);\r\n shuffle(numArray6);\r\n shuffle(iconArray4);\r\n shuffle(iconArray6);\r\n}",
"function arrangeCards() {\n shuffledCards = shuffle(cards);\n const fragment = document.createDocumentFragment();\n for(let card of shuffledCards) {\n let li = document.createElement(`li`);\n li.setAttribute(`class`,`card`);\n li.setAttribute(`data-card`,`${card}`)\n cardcounter++;\n li.setAttribute(`index`,`${cardcounter}`);\n let i = document.createElement(`i`);\n i.setAttribute(`class`,`fa ${card}` );\n li.appendChild(i);\n fragment.appendChild(li);\n }\n cardcounter = 0;\n\n // Removing the existing cards in the deck and re populating the shuffled\n // cards\n const deck = document.querySelector(`.deck`);\n deck.remove();\n const containerDiv = document.querySelector(`.container`);\n let ul = document.createElement(`ul`);\n ul.setAttribute(`class`,`deck`);\n containerDiv.insertAdjacentElement(`beforeend`,ul);\n const newDeck = document.querySelector(`.deck`);\n newDeck.appendChild(fragment);\n}",
"shuffleItems() {\r\n this.items.sort(() => Math.random() - 0.5);\r\n this.items.forEach((item, index) => {\r\n item.div.style.order = index;\r\n });\r\n }",
"function randomGenerateCards() {\n $(\".cards\").html($(\".cards .card\").sort(function () {\n return Math.random() - 0.5;\n }));\n }",
"function shuffleCards(ulElement)\n{\n\t// get the number of elements present in the list(i.e. number of cards).\n\tvar length = ulElement.children.length;\n\t\n\t/*\n\t\tCreate an array containing all the cards. \n\t\tchildNodes returns a NodeList and we cannot manipulate it.\n\t\tHence we need an array to swap the positions.\n\t*/\n\tvar liArray = Array.from(ulElement.childNodes);\n\t\n\t//Iterate through the array and swap the ith element with random element.\n\tfor(var i = 0; i < length; i++)\n\t{\n\t\t//Generate a random number between i and the length of array.\n\t\tvar randomNumber = Math.floor(Math.random() * (length - i)) + i;\n\t\t\n\t\t//Perform the swapping\n\t\tvar temp = liArray[i];\n\t\tliArray[i] = liArray[randomNumber];\n\t\tliArray[randomNumber] = temp;\n\t}\n\t\n\t//Create a new unordered list\n\tvar newULElement = document.createElement(\"UL\");\n\tnewULElement.classList.add(\"deck\");\n\t\n\t//Add all the array elements to the unordered list.\n\tliArray.forEach(function(li) {\n\t\tnewULElement.appendChild(li);\n\t})\n\treturn newULElement\n}",
"function shuffle(card) {\n TweenLite.fromTo(\n card, // target element\n 0.5, // time\n {\n // sets first position\n x:410, \n y:-15, \n ease: Expo.easeOut}, // animation configuraton\n {\n // final position\n x:0,\n y:0,\n ease: Expo.easeIn});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sort the deliquents by percentLogged | function percentLoggedDesc(a,b) {
if (a.percentLogged < b.percentLogged) {
return -1;
} else if (a.percentLogged > b.percentLogged) {
return 1;
} else {
return 0;
}
} | [
"function sortChartData() {\n chartData.sort((element1, element2) => {\n return element2.percentUnique - element1.percentUnique;\n });\n }",
"function filterAndSort(langs) {\n return langs.filter(function(e) { return e.language })\n .sort(function(a,b) { return b.percent - a.percent })\n}",
"function sortByImportance(e) {\n sorting(\"importent\");\n}",
"function sortByPopularity() {\n let list = Trackster.list;\n\n if(Trackster.filter.listeners ==='ascending'){\n var $t = list.sort((a, b) => a.listeners - b.listeners); // For ascending sort\n Trackster.filter.listeners = 'descending';\n $('#sortButton3b').show();\n $('#sortButton3a').hide();\n }\n else if (Trackster.filter.listeners ==='descending'){\n var $t = list.sort((a, b) => b.listeners - a.listeners); // For descending sort \n Trackster.filter.listeners = 'ascending';\n $('#sortButton3a').show();\n $('#sortButton3b').hide();\n }\n Trackster.list = $t; // add newly sorted list to the current list.\n $('#track-list').empty(); // empty the DOM list items.\n Trackster.PopulateTrackRows(Trackster.list);\n}",
"function sortItems(items) {\n\titems.sort(function (a, b) {\n\t\treturn (a.percentage < b.percentage) ?\n\t\t\t// if percentage A is less than B return -1\n\t\t\t-1 :\n\t\t\t// if percentage A is NOT less than B we make another comparation\n\t\t\t((a.percentage > b.percentage) ?\n\t\t\t\t// if percentage A is more than B return 1\n\t\t\t\t1 :\n\t\t\t\t// if percentage A is NOT more than B means that are equials\n\t\t\t\t// We make another comparation, we take in count the counter value\n\t\t\t\t(a.counter < b.counter ? -1 : 1));\n\t});\n\treturn items;\n}",
"function ratioSort(user1, user2){\n\t\t\tif (user1[1] > user2[1]) return 1;\n\t\t\telse if (user2[1] > user1[1]) return -1;\n\t\t\telse return 0;\n\t\t}",
"function sortTrackCount()\n{\n\ttracks.sort( function(a,b) { if (a.playCount < b.playCount) return -1; else return 1; } );\n\tclearTable();\n\tfillTracksTable();\n}",
"function sortPlayers(){\n parsedlclStrgObjArr.sort(function(a, b) {\n if (a.totalPoints === b.totalPoints) {\n return (b.percentWon) - (a.percentWon);\n } else {\n return (b.totalPoints) - (a.totalPoints);\n }\n });\n}",
"static sortFloors(floors) {\n const sorted = [...floors];\n sorted.sort(\n (a, b) => parseInt(b.iabp_name, 10) - parseInt(a.iabp_name, 10),\n );\n\n return sorted;\n }",
"function sortByWealth() {\r\n data = data.sort((a, b) => b.money - a.money);\r\n\r\n updateDOM();\r\n}",
"sortCaptured() {\n this.aiCaptured.sort(sortPieces);\n this.playerCaptured.sort(sortPieces);\n }",
"function sortByWealth() {\n data = data.sort((a, b) => b.money - a.money);\n updateDOM();\n}",
"function percentile(products, perc){\n\n if (products.length>0){\n //first order the products by descending price\n products.sort(price_desc);\n //get the index of needed product\n let index=Math.trunc(products.length/100*perc); //returns the integer truncature of a number\n return products[index].price;}\n}",
"function TOP10 (arr, percentage){\n const salarioOrder = arr.sort ((a,b) => a - b )\n console.log (salarioOrder)\n const space = (percentage/100) * salarioOrder.length;\n const top10Salary = salarioOrder.slice ( -space );\n const MedianaTOP10 = MedianaSalarios (top10Salary)\n return MedianaTOP10\n}",
"function histSorter(a,b) {\n if (a.outcome > b.outcome) { return 1; }\n else if (a.outcome < b.outcome) { return -1; }\n else if (a.trial > b.trial) { return 1; }\n else if (a.trial < b.trial) { return -1 }\n else { return 0; }\n }",
"mostEngagedTable() {\r\n this.stats.mostEngaged = this.members.sort(compareMissed);\r\n\r\n for (var i = 0; i < this.members.length * this.stats.showTablePercent; i++) {\r\n this.stats.engagedTop.push(this.stats.mostEngaged[i]);\r\n };\r\n }",
"function sortData() {\n\tattractions.sort((a,b) => a[\"Visitors\"] - b[\"Visitors\"]);\n\n\t// creates bar chart with the top five attractions\n\tlet data = attractions.slice(-5);\n\trenderBarChart(data);\n}",
"function percentile(arr,index){\n\tvar x = (arr.length*index)/100;\n\tvar ordArr = arr.slice(0);\n\tordArr = ordArr.sort(sortNumber);\n\tif(x%1==0){\n\t\treturn ordArr[Math.floor(x)+1];\n\t}else{\n\t\treturn (ordArr[Math.floor(x)]+ordArr[Math.floor(x)+1])/2;\n\t}\n}",
"sortAndPrint() {\n /*Resets the errand container*/\n $(\"#errandContainer\").empty();\n\n /*Sorts errand by time*/\n this.activeErrands.sort(function (a, b) {\n return Number(a.getElementsByTagName(\"div\")[2].innerHTML.replace(/[^0-9]/g, '')) - Number(b.getElementsByTagName(\"div\")[2].innerHTML.replace(/[^0-9]/g, ''));\n });\n\n /*Sorts errand by date*/\n this.activeErrands.sort(function (a, b) {\n return Number(a.getElementsByTagName(\"div\")[1].innerHTML.replace(/[^0-9]/g, '')) - Number(b.getElementsByTagName(\"div\")[1].innerHTML.replace(/[^0-9]/g, ''));\n });\n\n /*Apends errand to the errand container*/\n for (let errand of this.activeErrands) {\n $(\"#errandContainer\").append(errand);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the debug window exists, then close it | function hideDebug() {
if (window.top.debugWindow && ! window.top.debugWindow.closed) {
window.top.debugWindow.close();
window.top.debugWindow = null;
}
} | [
"function closeHelpDesk() {\n window.close();\n}",
"function __zdbCloseWorkWindow(myWindowId){\n if(myWindowId == null) return false;\n application.activeWindow.close();\n application.activateWindow(myWindowId);\n return;\n}",
"function onClose() {\n\tdebug( 'Window closed. Dereferencing window object to allow for GC...' );\n\tmainWindow = null;\n}",
"function CloseWindow() {\n if( satellite != null && satellite.open ) {\n satellite.close();\n satellite = null;\n }\n}",
"function closeDetail() {\n\n\tif (!currentDetailWindow) {\n\t\treturn;\n\t}\n\n\t$.tab.close(currentDetailWindow);\n\n\tcurrentDetailWindow = null;\n}",
"function onClosed() {\n\t// Dereference the window\n\t// for multiple windows store them in an array\n\tmainWindow = null;\n}",
"function closeWindow(){\n\tipcRenderer.send('close:window');\n}",
"function mainWindowClose () {\n module.exports.internal.mainWindow = null\n}",
"hideWindow() {\n\t\tfin.desktop.Window.getCurrent().hide();\n\t}",
"function onClosed() {\n\tmainWindow = null;\n}",
"function CloseWin () \n{\n\tif (WindowID)\n\t\tif (!WindowID.closed)\n\t\t\tWindowID.close ();\n\tWindowID = '';\n}",
"function exit () {\n windowStack.forEach(function(window){\n window.hide();\n });\n}",
"closeWindow() {\n console.log('Canceling gitignore creation...')\n this.panel.hide()\n }",
"function close() {\n\tif (Navigator === null) return;\n\n\twindows = {};\n\twindowsId = [];\n\tNavigator.close();\n}",
"function closeWindow() {\n\tif (confirm(\"Do you really want to close window and exit program ?\")) {\n\t\tclose();\n\t}\n}",
"function closeWin(s) {\n dir = exec(\"ps -ef | grep ./gl | grep -v grep | awk '{print $2}' | xargs kill \", function(err, stdout, stderr) { console.log(stderr); });\n if (calWindow)\n calWindow.close();\n status = s;\n size();\n}",
"function onClosed() {\n mainWindow = null;\n}",
"function closeWindow(win = BrowserWindow.getFocusedWindow()) {\n if (!win) throw new Error('No focused window.');\n else win.close();\n}",
"function closeDetails() {\n\n\tif (!Alloy.Globals.detailsWindow) {\n\t\treturn;\n\t}\n\n\t$.tab.closeWindow(Alloy.Globals.detailsWindow);\n\n\tAlloy.Globals.detailsWindow = null;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that gets the number input | function getNumber() {
// store the input as an integer in num
num = parseInt(input.value());
} | [
"function getInputNumber(input){\n if(inputNum == undefined){\n inputNum = input;\n }else{\n inputNum = (inputNum * 10) + (input * 1);\n }\n calcDisplay.value = inputNum; \n }",
"function getInputNumber(id){\n const Amount = document.getElementById(id).value;\n const AmountNumber = parseFloat(Amount);\n return AmountNumber;\n}",
"function numero(){\n var input = prompt('Introduzca un numero decimal')\n input = parseFloat(input);\n input = Math.ceil(input);\n return input;\n}",
"function getNumber(num){\n const number = document.getElementById(\"num\"+num);\n const parsed = parseInt(number.innerText);\n return parsed\n}",
"function getNumber()\n\t{\n\t\tif(this.value == \".\" && acc.includes(\".\"))\n\t\t\treturn;\n\t\t\n\t\tacc = acc + this.value;\n\t\tdocument.getElementById(\"output\").value = acc;\n\t}",
"function readNumber() { //Repeat until the input is a number\n \n let num;\n do {\n const input = prompt(\"Enter a number please?\", 0);\n num = parseFloat(input);\n } while ( isNaN(num) );\n return num;\n }",
"function numberOne() {\n return parseInt(userNumber.value);}",
"function getNumberInput() {\r\n let pH = READLINE.question(\"Enter in a phone number! \");\r\n\r\n while (checkNumber(pH) == false) {\r\n pH = READLINE.question(\"Enter in a VALID phone number! \");\r\n }\r\n return pH;\r\n}",
"function getNumber(id){\r\n return Number(document.getElementById(id).value);\r\n}",
"function getNum(question) {\n\n //Ask out question for our number\n var num = prompt(question);\n\n //Validate it!\n while(true) {\n if(isNaN(num) || num === \"\") {\n num = prompt(\"Invalid Input! \" + question);\n } else {\n break;\n }\n }\n\n //return our number\n return parseInt(num);\n}",
"function convertInputToNum(expression){\n\treturn math.compile(prompt(expression)).evaluate();\n}",
"function validateNumberInput(input){\n\tif(isNaN(+input))\n\t{\n\t\tgenerateError(\"Please enter a number!\");\n\t\treturn false;\n\t}\n\tvar num=Number(input); //get an int value from text input\n\tif(num<0||num>200)\n\t{\n\t\tgenerateError(\"Please enter a number between 0-200!\");\n\t\treturn false;\n\t}\n\treturn num;\t\t\n\n}",
"function askNumber(question){\n let res = read.questionInt(question + \"\\n\");\n if(isNaN(res) == true) {\n\t aff('ERROR '+ res +' isn\\'t a number');\n }\n return parseInt(res);\n}",
"function getNum() {\n if (afterCalc) {\n displayStr.lower = this.value;\n display.value = displayStr.lower;\n displayStr.upper = \"\";\n display_upper.value = displayStr.upper;\n afterCalc = false;\n }\n if (this.value === \"+/-\") {\n (displayStr.lower.includes(\"-\")) ? displayStr.lower = displayStr.lower.slice(1, displayStr.lower.length): displayStr.lower = \"-\" + displayStr.lower;\n display.value = displayStr.lower;\n } else if (display.value === \"0\" || display.value === \"\" || clear || display.value === ERROR) {\n displayStr.lower = this.value;\n display.value = displayStr.lower; // first digit when user clicked\n if (this.value === \".\") {\n displayStr.lower = \"0.\";\n // when user clicked \".\", make it to \"0.\"\n display.value = \"0.\";\n }\n clear = false;\n } else if (validation.number.test(display.value + this.value)) {\n // when user contructed a valid number, add it to it\n displayStr.lower += this.value;\n display.value = displayStr.lower;\n currentValue = display.value;\n } else {\n // otherwise, replace it with pervious value\n display.value = currentValue;\n }\n // disableButton(/\\./, \".\");\n}",
"function input(n){\n // make sure n is Valid\n if(!String(n).match(/^[1-3]$/)){\n throw new Error('invalid arguments - pbs.input() requires one argument - 1, 2, or 3');\n }\n\n var rawVal = parent.$('#pbs_input_' + n).val();\n if(rawVal.length){\n return rawVal;\n }\n return undefined;\n }",
"function inputNumBees() {\n beeN = document.getElementById('beeInput').value;\n}",
"get inputNumber () { \n return $('#number'); \n }",
"function getUserInput() {\n\tvar rawValue = document.getElementById('userInput').value.trim();\n\n //evaluates for any input\n\tif (rawValue.length === 0) {\n\t\tthrow \"You must enter a number.\"\n\t}\n //evaluates if input is a number, if not, error is thrown via an alert box.\n\tvar num = Number(rawValue);\n\tif (isNaN(num)) {\n\t\tthrow rawValue + \" is not a number.\"\n\t}\n\n\treturn num;\n}",
"function getInputValue(inputId) {\n const currentValue = document.getElementById(inputId).value;\n const currentValueNum = parseInt(currentValue);\n return currentValueNum;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
$g by JoeSimmons. Supports ID, Class, and XPath (full with types) in one query Supports multiple id/class grabs in one query (split by spaces), and the ability to remove all nodes regardless of type See script page for syntax examples: | function $g(que, obj) {
if(!que || !(que=que.replace(/^\s+/,''))) return;
var obj=(obj?obj:({del:false,type:6,node:document})), r,
class_re=/^\.[A-Za-z0-9-_]/, id_re=/^\#[^\s]/, xp_re=/^\.?(\/\/|count|id)\(?[A-Za-z0-9\'\"]/;
if(!que || typeof que!='string' || que=='') return false;
else if(id_re.test(que)) {
var s=que.split(' '), r=new Array();
for(var n=0;n<s.length;n++) r.push(document.getElementById(s[n].substring(1)));
if(r.length==1) r=r[0];
} else if(xp_re.test(que)) {
r = document.evaluate(que,(obj['node']||document),null,(obj['type']||6),null);
switch((obj['type']||6)){case 1:r=r.numberValue;break;case 2: r=r.stringValue;break;case 3:r=r.booleanValue;break;case 8:case 9:r=r.singleNodeValue;break;}
} else if(class_re.test(que)) {
var expr='', s=que.split(' ');
for(var n=0;n<s.length && s[n].indexOf('.')==0;n++) expr+="@class='"+s[n].substring(1)+"' or ";
r = document.evaluate("//*["+expr.replace(/( or )$/,'')+"]",document,null,6,null);
if(r.snapshotLength==1) r=r.snapshotItem(0);
} else return null;
if(obj['del']===true && r) {
if(r.nodeType==1) r.parentNode.removeChild(r);
else if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);
else if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);
} else return r;
} | [
"function removeNodes (cssClass) {\n let selector = 'div.' + cssClass;\n let elements = document.querySelectorAll(selector);\n Array.prototype.forEach.call(elements, function (element) {\n document.body.removeChild(element);\n });\n}",
"function $g(que, O) {\r\nif(!que||typeof(que)!='string'||que==''||!(que=que.replace(/^\\s+/,''))) return false;\r\nvar obj=O||({del:false,type:6,node:document}), r, t,\r\n\tidclass_re=/^[#\\.](?!\\/)[^\\/]/, xp_re=/^\\.?(\\/{1,2}|count|id)/;\r\nif(idclass_re.test(que)) {\r\nvar s=que.split(' '), r=new Array(), c;\r\nfor(var n=0; n<s.length; n++) {\r\nswitch(s[n].substring(0,1)) {\r\ncase '#': r.push(document.getElementById(s[n].substring(1))); break;\r\ncase '.': c=document.getElementsByClassName(s[n].substring(1));\r\n\t\t if(c.length>0) for(var i=0; i<c.length; i++) r.push(c[i]); break;\r\n}\r\n}\r\nif(r.length==1) r=r[0];\r\n} else if(xp_re.test(que)) {\r\nr = (obj['doc']||document).evaluate(que,(obj['node']||document),null,((t=obj['type'])||6),null);\r\nif(typeof t==\"number\" && /[12389]/.test(t)) r=r[(t==1?\"number\":(t==2?\"string\":(t==3?\"boolean\":\"singleNode\")))+\"Value\"];\r\n}\r\nif(r && obj['del']===true) {\r\nif(r.nodeType==1) r.parentNode.removeChild(r);\r\nelse if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\nelse if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);\r\n} return r;\r\n}",
"function removeElemByClass(cl, tag) {\r\nif(array=document.evaluate(\"//\"+(tag||'*')+\"[@class='\"+cl+\"']\", document, null, 6, null))\r\nfor(var i=array.snapshotLength-1; (item=array.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\n}",
"function BuildXPath(tag_val, id_val, class_val, attr_name, attr_val){\r\n\tvar\ttag = '';\r\n\tvar\tquery = '';\r\n\tvar\tcount = 0;\r\n\tvar\tcond = new Array(3);\r\n\r\nLOG.output(\"tag_val:\"+tag_val);\r\n\tif(tag_val) {\r\n\t\ttag = tag_val;\r\n\t} else {\r\n\t\ttag = '*';\r\n\t}\r\nLOG.output(\"id_val:\"+id_val);\r\n\tif(id_val) {\r\n\t\tcond[count] = '@id=\"'+id_val+'\"';\r\n\t\tcount++;\r\n\t}\r\nLOG.output(\"class_val:\"+class_val);\r\n\tif(class_val) {\r\n\t\tcond[count] = '@class=\"'+class_val+'\"';\r\n\t\tcount++;\r\n\t}\r\nLOG.output(\"attr_name:\"+attr_name);\r\nLOG.output(\"attr_val:\"+attr_val);\r\n\tif(attr_name) {\r\n\t\tcond[count] = '@'+attr_name+'='+\"'\"+attr_val+\"'\";\r\n\t\tcount++;\r\n\t}\r\n\tquery = '//'+tag;\r\n\tif(count) {\r\n\t\tquery = query + '[';\r\n\t\tfor(var i = 0; i < count; i++) {\r\n\t\t\tquery = query + cond[i];\r\n\t\t\tif(i+1 < count) {\r\n\t\t\t\tquery = query + ' and ';\r\n\t\t\t}\r\n\t\t}\r\n\t\tquery = query + ']';\r\n\t}\r\nLOG.output(\"query:\"+query);\r\n\treturn query;\r\n}",
"function $g(que, obj) {\r\nif(!que || !(que=que.replace(/^\\s+/,''))) return;\r\nvar obj=obj||({del:false,type:6,node:document}), r,\r\n\tidclass_re=/^[#\\.][^\\/]/, xp_re=/^\\.?(\\/\\/|count|id)/;\r\nif(typeof que!='string' || que=='') return false;\r\nelse if(idclass_re.test(que)) {\r\nvar s=que.split(' '), r=new Array(), c;\r\nfor(var n=0; n<s.length; n++) {\r\nswitch(s[n].substring(0,1)) {\r\ncase '#': r.push(document.getElementById(s[n].substring(1))); break;\r\ncase '.': c=document.getElementsByClassName(s[n].substring(1));\r\n\t\t if(c.length>0) for(var i=0; i<c.length; i++) r.push(c[i]); break;\r\n}\r\n}\r\nif(r.length==1) r=r[0];\r\n} else if(xp_re.test(que)) {\r\nr = document.evaluate(que,(obj['node']||document),null,(obj['type']||6),null);\r\nswitch((obj['type']||6)){\r\ncase 1: r=r.numberValue; break;\r\ncase 2: r=r.stringValue; break;\r\ncase 3: r=r.booleanValue; break;\r\ncase 8: case 9: r=r.singleNodeValue; break;\r\n}\r\n}\r\nif(r && obj['del']===true) {\r\nif(r.nodeType==1) r.parentNode.removeChild(r);\r\nelse if(r.snapshotItem) for(var i=r.snapshotLength-1; (item=r.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\nelse if(!r.snapshotItem) for(var i=r.length-1; i>=0; i--) if(r[i]) r[i].parentNode.removeChild(r[i]);\r\n} return r;\r\n}",
"function deldiv(id) {\r\n\tdelitem('//div[@id=\\\"' + id + '\\\"]' );\r\n}",
"removeItemsByClass (className, exceptID=null) {\n // console.log(exceptID)\n for (var i of $(`.${className}`)) {\n if ( $(i).attr(\"id\") != exceptID) {\n $(i).remove();\n }\n }\n }",
"function remove_class_all(class_name) {\n\n var elm_arr = document.getElementsByClassName(class_name);\n var i;\n elm_arr = [].slice.call(elm_arr);\n for (i = 0; i < elm_arr.length; i++) {\n remove_class(class_name,elm_arr[i].id)\n }\n}",
"function _cleanUp (){\n $('.json2htmlIdAdded').each( function(index){\n \t\tvar classname = $(this).attr('class') ;\n \t\tif(classname == 'json2htmlIdAdded'){\n \t\t\t$(this).removeAttr(\"class\");\n \t\t}else{\n \t\t\t$(this).removeClass('json2htmlIdAdded');\n \t\t}\n \t\t$(this).removeAttr('id');\n \t});\n }",
"function removeClasses(theElements, ...theClasses){\n // Test to see if \"theElements\" is a single node or a node list. Credit to Tim Pietrusky https://twitter.com/jackrugile/status/435539724774547456. NodeList has a method called item() that node does not. If the type of something.item is undefined, then you're not dealing with a NodeList.\n if( typeof theElements.item === 'undefined' ) {\n // Iterate over the \"theClasses\" rest parameter\n for(const theClass of theClasses){\n // Use classList.remove() to remove each class\n theElements.classList.remove(theClass);\n } \n } else {\n // When dealing with a node list, iterate over each node\n for(const theElement of theElements){\n // Iterate over the \"theClasses\" rest parameter\n for(const theClass of theClasses){\n // Use classList.remove() to remove each class\n theElement.classList.remove(theClass);\n }\n }\n }\n}",
"function querySelectorParser(selector){\n var first, second, third;\n //check to see what the first element in the string is\n switch(selector[0]){\n case \".\" : //if class, check if it has an id element # in the string\n var result = setClassAndIDObject(selector, \"#\", first, second)\n first = result.first;\n second = result.second;\n break;\n case \"#\" :\n var result = setClassAndIDObject(selector, \".\", first, second)\n first = result.first;\n second = result.second;\n break;\n default: //assumption: you know that it starts with a tag\n //check to see if string has both class and id\n if(selector.indexOf(\"#\") !== -1 && selector.indexOf(\".\") !== -1){\n //determine which comes first\n var firstElemToSplit, secondElemToSplit, thirdElemName, secondElemName;\n var classIndex = selector.indexOf(\".\");\n var idIndex = selector.indexOf(\"#\");\n if(classIndex < idIndex){\n firstElemToSplit= \"#\", thirdElemName = \"id\", secondElemToSplit = \".\", secondElemName = \"class\";\n }else{\n firstElemToSplit = \".\"; thirdElemName = \"class\"; secondElemToSplit = \"#\"; secondElemName = \"id\"\n }\n // to-do: set the right first, second, third object\n var firstSplitArr = selector.split(firstElemToSplit)\n third = { name: firstElemToSplit + firstSplitArr[1], element: thirdElemName };\n var secondSplitArr = firstSplitArr[0].split(secondElemToSplit);\n second = {name: secondElemToSplit + secondSplitArr[1], element: secondElemName}\n first = {name : secondSplitArr[0], element: \"tag\"}\n }else if(selector.indexOf(\".\") !== -1){\n //parse string based on .\n var selectorArr = selector.split(\".\");\n first = { name : selectorArr[0] , element: \"tag\"};\n second = { name : \".\" + selectorArr[1], element: \"class\"}\n } else if (selector.indexOf(\"#\") !== -1){\n var selectorArr = selector.split(\"#\");\n first = { name : selectorArr[0] , element: \"tag\"};\n second = { name : \"#\" + selectorArr[1], element: \"id\"}\n } else {\n first = {name : selector, element: \"tag\"}\n }; break;\n }\n\n var resultObj = {\n first: first, second: second, third: third\n };\n console.log(\"Selector parser for \"+ selector +\":\", resultObj);\n return resultObj\n}",
"function removeCssClassForID(elementID, cssClass) {\n var realID = checkIfID(elementID);\n if (cssClass.constructor === Array) {\n cssClass.forEach(function(element) {\n $(realID).removeClass(element);\n });\n } else {\n $(realID).removeClass(cssClass);\n }\n }",
"function deleteNodes(xPath, params) {\r\n\t\t\tparams = params || {};\r\n\t\t\tvar o = selectNodes(xPath, params);\r\n\t\t\tif (o) {\r\n\t\t\t\tif (o.snapshotItem)\r\n\t\t\t\t\tfor (var i = o.snapshotLength - 1; (item = o.snapshotItem(i)); i--)\r\n\t\t\t\t\t\titem.parentNode.removeChild(item);\r\n\t\t\t\telse\r\n\t\t\t\t\tfor (var i = o.length - 1; i >= 0; i--)\r\n\t\t\t\t\t\tif (o[i])\r\n\t\t\t\t\t\t\to[i].parentNode.removeChild(o[i]);\r\n\t\t\t}\r\n\t\t\to = null;\r\n\t\t}",
"function SelectByID(type, endPart) {\n return element = $(type + \"[id$=\" + endPart + \"]\");\n}",
"function remCssO(c,objetos){\n\tvar i=1;\n\twhile (i<arguments.length){\n\t\tdocument.querySelector(arguments[i]).classList.remove(c);\n\t\ti++;\n\t}\n}",
"function remove(id) {\n return db('classes').where({ id }).delete()\n}",
"function process()\r\n\r\n{\r\n\r\n\tvar xpath;\r\n\r\n xpath ='//div[starts-with(@id,\"ad\")]';\r\n killAds(xpath);\r\n xpath ='//div[starts-with(@id,\"google_ads\")]';\r\n\r\n \tkillAds(xpath);\r\n xpath ='//div[starts-with(@class,\"ad\")]';\r\n killAds(xpath);\r\n xpath ='//div[contains(@class,\" ad\")]';\r\n killAds(xpath);\r\n xpath='//div[contains(@class,\"topic_ad\")]';\r\n killAds(xpath);\r\n\r\n xpath = '//div[contains(@id,\"divplay\")]';\t\r\n killAds(xpath);\r\n\r\n}",
"function removeXPath(xpathexpr) {\n dactyl.open(`javascript:var elts=document.evaluate(${xpathexpr},document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);for (var i=0; i < elts.snapshotLength; i++){var elt=elts.snapshotItem(i);elt.parentNode.removeChild(elt);}; void(0)`)\n}",
"function deleteClass(id) {\n return db(\"classes\").where({ id }).del();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch to the video to the right in the playlist from the current one. | function shiftRight() {
right_video = current_video - 1;
if(right_video < 1) {
right_video = vid_array.length-1;
}
switchToVideo(right_video);
} | [
"function shiftLeft() {\n\tleft_video = current_video + 1;\n\tif (left_video >= vid_array.length) {\n\t\tleft_video = 1;\n\t}\n\tswitchToVideo(left_video);\n}",
"function forwardButtonTrigger() {\n if (window.currentVideoSelectedForPlayback) {\n setCurrentlyPlaying(false)\n const currentNode = window.currentVideoSelectedForPlayback\n const currentTime = currentNode.data.videoCore.currentTime\n const currentVideoEnd = currentNode.data.metadata.endTime\n\n if (currentTime + 1 < currentVideoEnd) {\n currentNode.data.videoCore.currentTime += 1\n } else if (currentNode.next) {\n const remainingTime = 1 - currentTime\n window.currentVideoSelectedForPlayback = currentNode.next\n const nextStartTime = window.currentVideoSelectedForPlayback.data.metadata.startTime\n window.currentVideoSelectedForPlayback.data.videoCore.currentTime = nextStartTime + remainingTime\n } else {\n window.currentVideoSelectedForPlayback.data.videoCore.currentTime = currentVideoEnd\n }\n renderUIAfterFrameChange(window.currentVideoSelectedForPlayback)\n }\n}",
"function NextVideo()\n{\n // subtract 0 to cast currentVideoIndex as a number - otherwise it concatenates with \"1\" as a string.\n ChangeVideoToTarget(currentPlaylist[(currentVideoIndex - 0) + 1].url);\n currentVideoIndex++;\n\n CheckPrevAndNext(currentVideoIndex);\n}",
"function PreviousVideo()\n{\n ChangeVideoToTarget(currentPlaylist[currentVideoIndex - 1].url);\n currentVideoIndex--;\n\n CheckPrevAndNext(currentVideoIndex);\n}",
"function gotoAndPlayNextSong() {\n if (playlist.length > 1) {\n playlist.shift();\n player.loadVideoById(playlist[0]);\n } else {\n player.clearVideo();\n }\n}",
"function playNextVideo() {\n if (firstTime) {\n loadPlaylist();\n firstTime = false;\n } else {\n if (currentVideoIndex >= playlistLength - 1) {\n playlistDone = true;\n }\n myPlayer.playlist.currentItem(currentVideoIndex);\n myPlayer.play();\n }\n currentVideoIndex += 1;\n }",
"_playPreviousVideo(){\n var currentVideo = this.state.videoIndex;\n if (currentVideo - 1 > -1){\n this.setState({\n videoIndex: (currentVideo - 1),\n videoPaused: false\n });\n }\n }",
"function rewindTwoSeconds() {\n var video = $(\".main-video\").get(0);\n video.currentTime = video.currentTime - 2;\n}",
"jumpBackward() {\n\t\t\tvar videoContainer = paella.player.videoContainer;\n\t\t\tvideoContainer.currentTime().then(function(currentTime) {\n\t\t\t\tpaella.player.videoContainer.seekToTime(currentTime - 10);\n\t\t\t});\n\t\t}",
"function setCurrentVideo() {\n if (videos.length > 0) {\n player.loadVideoById(videos[currentVideo].id, 0, \"large\");\n selectNthPlaylistElement(currentVideo);\n sendCurrentVideo(currentVideo, videos[currentVideo]);\n }\n}",
"function playPrevVideo() {\n var index\n if (position < 0) {\n position = position + 62\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition =\"all 1s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n } else if (position === 0) {\n position = (ids.length-1) * (-62)\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition = \"left 0.5s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n }\n}",
"function playNextVideo() {\n // remove current video\n const $oldVideo = videoElements[0];\n $oldVideo.off('ended'); // sometimes it gets called again\n $oldVideo.off('timeupdate');\n $oldVideo.remove();\n\n if (earlyFail()) {\n submitData(); // fail\n return;\n }\n\n // play next video\n videoElements.shift();\n window.focus()\n if (videoElements.length > 0) {\n // queue up another video\n if (counter < videos.length) {\n newVideo(videos[counter]);\n }\n counter += 1;\n checked = false;\n // play the next video\n playWhenReady(videoElements[0]);\n // update progress bar\n $progressBar.progress(\"set progress\", counter - NUM_LOAD_AHEAD);\n // update state\n } else {\n submitData(); // done\n }\n }",
"function playCurrentVideo() {\n \tisPlaying = true;\n \tvideo.playVideo();\n }",
"previousChannel() {\n const newIndex =\n this.currentIndex > 0 ? this.currentIndex - 1 : this.playlist.length - 1;\n\n this.playChannel(newIndex);\n }",
"function GoToVideoByPlaylistId(id)\n{\n ChangeVideoToTarget(currentPlaylist[id].url);\n CheckPrevAndNext(id);\n}",
"playFirstVideo() {\n this.currentPos_ = 0;\n this.reloadCurrentVideo_(this.onFirstVideoReady_.bind(this));\n }",
"nextChannel() {\n const newIndex =\n this.currentIndex < (this.playlist.length - 1) ? (this.currentIndex + 1) : 0;\n\n this.playChannel(newIndex);\n }",
"function playNextVideo() {\n var index\n if (position === (ids.length-1) * (-62)) {\n position = 0\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition = \"left 0.5s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n } else if (position <= 0) {\n position = position - 62\n imageHolder.style.left = String(position) + \"vw\"\n imageHolder.style.transition =\"all 1s ease\"\n index = position / (-62)\n videoTitle.textContent = ids[index][\"title\"]\n description.textContent = ids[index][\"info\"]\n }\n}",
"function landingPlayVideo(e) {\n\n\t\t\t// play all videos\n\t\t\tvideoOne.play();\n\t\t\tvideoTwo.play();\n\t\t\tvideoThree.play();\n\n\t\t\taudioThree.play();\n\t\t\taudioOne.play();\n\n\t\t\taudioThree.volume = 0.15;\n\n\t\t\tvideoWindow.classList.add(\"move-content\");\n\n\t\t\t// change videoPlay button text to pause\n\t\t\tvideoPlay.innerHTML = \"Pause\";\n\t\t\t// add \"playing\" class to video play button\n\t\t\tvideoPlay.classList.add(\"playing\");\n\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find closest panel and scroll to it | function findClosestPanel() {
var differences = [],
lowestDiff = Infinity
if (lowestDiff !== 0) {
// work out closest element
for (var i = 0; i < sections.length; i++) {
var difference = window.scrollY - sections[i].offsetTop
if (difference < 0) {
// turn any negative number into a positive
negativeDiff = true
difference = Math.abs(difference)
}
else {
negativeDiff = false
}
// if less than the last number, compare this with lowestDiff
// if smaller, updated difference and closestPanel
if (difference < lowestDiff) {
lowestDiff = difference
closestPanel = sections[i]
}
// briefly remove scrollInit
window.onscroll = null
scroll()
setTimeout(function(){
scrollInit()
}, 500)
}
}
} | [
"function panelScroll() {\n\t\"use strict\";\n\t$('.panel-group').one('shown.bs.collapse', function () {\n\t\tvar panelExpanded = $(this).find('.in');\n\t\t\n\t\t$('html, body').animate({\n\t\t\tscrollTop: panelExpanded.offset().top - 105\n\t\t}, 400);\n\t});\n}",
"function scrollSub(id){\n var topPos = document.getElementById(id).parentNode.parentNode.offsetTop;\n $(\".panel\").animate({\n scrollTop : topPos\n },250)\n}",
"function scrollToPanel(panel)\n{\n\tvar parent = $(\".right\");\n\tif($(panel).size() > 0)\n\t{\n\t\t$(parent).scrollTo(panel, 350, {easing:'easeInOutBack', onAfter: function(){\n\t\t\t$(panel).scrollTo(0, 250);\n\t\t}});\n\t}\n\telse\n\t{\n\t\t//default panel\n\t\tvar defaultPanel = $(\".panel#about\");\n\t\tscrollToPanel(defaultPanel);\n\t\treturn false;\n\t}\n\t\n\tvar selectedId = $(panel).attr(\"id\");\n\tupdateNav(selectedId);\n}",
"function onPanelExpanded() {\n // if necessary, re-position panel to account for the larger size\n positionPanel();\n\n // if necessary, scroll down to bring first highlighted element into view\n $(\"#options-list\").animate({\n scrollTop: computeScrollOffset()\n }, 300)\n }",
"function scrollMenuTo(panelToScroll, targetY) {\n console.log(\"Scrolling \" + panelToScroll + \" to: \" + targetY);\n $(panelToScroll).scrollTop(targetY);\n }",
"function treeMenuScroll() {\n\tif(currentItem == null)\n\t\treturn;\n\tvar trObj = showTreeWindow.document.getElementById(currentItem.index);\t\n\tif(trObj == null)\n\t\treturn;\n\ttrObj.scrollIntoView(false);\n}",
"function _slideToElement() {\n var module_name = this.getAttribute('data-module');\n\n $('html, body').animate({\n scrollTop: $('#' + module_name).offset().top\n }, 500);\n}",
"function set_scroll(){\n\t\tvar parent_row = this.current_details_box.previousSibling,\n\t\t\tscroll_amount = parent_row.offsetTop;\n\t\tif(scroll_amount)\n\t\t\twindow.scrollTo(0,scroll_amount);\n\t\t//TODO Add smooth scrolling here\n\t}",
"function scrollToWebElement(el){\r\n return browser.executeScript('arguments[0].scrollIntoView()', el.getWebElement());\r\n}",
"function scrollToCurrentlySelectedMatch_() {\n let match = getCurrentSelectedMatch_();\n if (!match) {\n return;\n }\n\n match.nodes[0].scrollIntoView({block: \"center\", inline: \"center\"});\n}",
"function scrollToElement()\n{\n // after creating the tree, we need to go give the selected node focus\n if(selectedNodeId != null)\n {\n var sElement = getLinkElement(escapeQuotes(selectedNodeId));\n\t if(sElement != null)\n\t \tsElement.focus();\n }\n}",
"function scrollWindowTo()\n {\n if (targetRow === null) return;\n var offsetY = 0;\n var element = targetRow;\n if (element.offsetParent)\n {\n offsetY = element.offsetTop;\n while (element = element.offsetParent)\n {\n offsetY += element.offsetTop;\n }\n }\n window.scrollTo(0, offsetY);\n }",
"function lsd_scrollToContentName(name) {\n\tvar body = document.getElementById('body');\n\tvar target = document.getElementById('content_'+lsd_alphaNumericOnly(name));\n\tvar container = document.getElementById(\"lsd_contentPanel\");\n\t\n\tif(target) {\n\t\tif( $(body).outerWidth() == $(container).outerWidth() ) {\n\t\t\t// Mobile mode? : Scroll the window itself\n\t\t\twindow.scrollTo( 0, target.offsetTop - 10 + container.offsetTop );\n\t\t} else {\n\t\t\t// Desktop mode? : Scroll the container\n\t\t\tcontainer.scrollTop = target.offsetTop - 10;\n\t\t}\n\t}\n\n\t// var scrollTopTarget = $(\"#content_\"+lsd_alphaNumericOnly(name)).offset().top; // - $('#lsd_contentBox').offset().top;\n\t// console.log(scrollTopTarget);\n\t// $('#lsd_contentPanel').animate({\n\t// \tscrollTop: scrollTopTarget\n\t// }, 2000);\n}",
"function scrollPage(e,el,o) {\n\t// get the element we're basing the scroll on (the target)\n\tvar el = Ext.get(this.dom.hash.replace(/#/,''));\n\t// get the container\n\tvar ct = Ext.query(\"#bodypanel .x-panel-body\")[0];\n\tct = Ext.get(ct);\n\t// calculate y position of target element; this is how far we need to scroll\n\tvar yoffset = el.getOffsetsTo(ct)[1];\n\t// do the scroll\n\tct.scrollTo(\"top\",yoffset,true);\n\t// call preventDefault on the original click event to prevent anchor jump\n\te.preventDefault();\n}",
"scrollToTopOfDiscussion() {\n const scrollPaneTop = ELEMENT_DISCUSSION.offsetTop;\n const elementTop = this.offsetTop;\n const offset = elementTop - scrollPaneTop;\n ELEMENT_DISCUSSION.scrollTop = offset;\n }",
"function goToDivScroll(id){\n\t\t // Scroll\n\t\t $('html,body').animate({\n\t\t \tscrollTop: $(\"#tabs\").offset().top\n\t\t \t}, 'slow');\n\t\t}",
"function updateScroll() {\n var elements = container.getElementsByClassName(\"selected\");\n if (elements.length > 0) {\n var element = elements[0];\n // make group visible\n var previous = element.previousElementSibling;\n if (previous && previous.className.indexOf(\"group\") !== -1 && !previous.previousElementSibling) {\n element = previous;\n }\n if (element.offsetTop < container.scrollTop) {\n container.scrollTop = element.offsetTop;\n }\n else {\n var selectBottom = element.offsetTop + element.offsetHeight;\n var containerBottom = container.scrollTop + container.offsetHeight;\n if (selectBottom > containerBottom) {\n container.scrollTop += selectBottom - containerBottom;\n }\n }\n }\n }",
"function faqScrolltodiv(divname) {\n\t\t\tvar element = document.getElementById(\"physiotherapy\");\n\t element.scrollIntoView();\n\t\t}",
"_scrollToSelected() {\n let form = $('.form.list-form-constructor .panel-wrapper');\n let selectColumn = $('.fd-selected:first');\n let firstSelectedOffsetLeft = selectColumn.length > 0 ? selectColumn.offset().left : 0;\n let scrollLeft = firstSelectedOffsetLeft + form.scrollLeft() - (form.offset().left + 10);\n\n form.animate({ scrollLeft });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get date and time to start according to service window for current workrequest Calls WFR AbBldgOpsHelpDeskgetServiceWindowStartFromSLA Fills in date and time started | function getDateAndTimeStarted(){
var panel = View.panels.get('tool_form');
var wrId = panel.getFieldValue("wrtl.wr_id");
var result = {};
try {
result = Workflow.callMethod("AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA", 'wr','wr_id',wrId);
}
catch (e) {
Workflow.handleError(e);
}
if (result.code == 'executed') {
var start = eval('(' + result.jsonExpression + ')');
//split isodate yyyy-mm-dd
temp = start.date_start.substring(1, start.date_start.length - 1).split("-");
date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);
//split isotime hh:mm:ss
tmp = start.time_start.substring(1, start.time_start.length - 1).split(":");
if (tmp[0] > 12) {
time = FormattingTime(tmp[0], tmp[1], "PM", timePattern);
}
else {
time = FormattingTime(tmp[0], tmp[1], "AM", timePattern);
}
$("tool_form_wrtl.date_start").value = date;
$("tool_form_wrtl.time_start").value = time;
$("Storedtool_form_wrtl.time_start").value = tmp[0] + ":" + tmp[1] + ".00.000";
}
else {
Workflow.handleError(result);
}
} | [
"function getDateAndTimeStarted(){\n var panel = View.getControl('', 'sched_wr_cf_cf_form');\n var wrId = panel.getFieldValue(\"wrcf.wr_id\");\n\n //kb:3024805\n\tvar result = {};\n\t//Retrieves service window start for SLA, next working day for this SLA after today ,file=\"ServiceLevelAgreementHandler\"\n try {\n result = Workflow.callMethod(\"AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA\", 'wr','wr_id',wrId);\n } \n catch (e) {\n Workflow.handleError(e);\n }\n if (result.code == 'executed') {\n var start = eval('(' + result.jsonExpression + ')');\n //split isodate yyyy-mm-dd\n temp = start.date_start.substring(1, start.date_start.length - 1).split(\"-\");\n date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);\n //split isotime hh:mm:ss\n tmp = start.time_start.substring(1, start.time_start.length - 1).split(\":\");\n if (tmp[0] > 12) {\n time = FormattingTime(tmp[0], tmp[1], \"PM\", timePattern);\n }\n else {\n time = FormattingTime(tmp[0], tmp[1], \"AM\", timePattern);\n }\n \n $(\"sched_wr_cf_cf_form_wrcf.date_start\").value = date;\n $(\"sched_wr_cf_cf_form_wrcf.time_start\").value = time;\n \n $(\"Storedsched_wr_cf_cf_form_wrcf.time_start\").value = tmp[0] + \":\" + tmp[1] + \".00.000\";\n }\n else {\n Workflow.handleError(result);\n }\n}",
"function getDateAndTimeStarted(){\n var panel = View.getControl('', 'sched_wr_tl_tool_form');\n var wrId = panel.getFieldValue(\"wrtl.wr_id\");\n var result = {};\n\t//Retrieves service window start for SLA, next working day for this SLA after today ,file=\"ServiceLevelAgreementHandler\"\n try {\n result = Workflow.callMethod(\"AbBldgOpsHelpDesk-SLAService-getServiceWindowStartFromSLA\", 'wr','wr_id',wrId);\n } \n catch (e) {\n Workflow.handleError(e);\n }\n if (result.code == 'executed') {\n var start = eval('(' + result.jsonExpression + ')');\n //split isodate yyyy-mm-dd\n temp = start.date_start.substring(1, start.date_start.length - 1).split(\"-\");\n date = FormattingDate(temp[2], temp[1], temp[0], strDateShortPattern);\n //split isotime hh:mm:ss\n tmp = start.time_start.substring(1, start.time_start.length - 1).split(\":\");\n if (tmp[0] > 12) {\n time = FormattingTime(tmp[0], tmp[1], \"PM\", timePattern);\n }\n else {\n time = FormattingTime(tmp[0], tmp[1], \"AM\", timePattern);\n }\n \n $(\"sched_wr_tl_tool_form_wrtl.date_start\").value = date;\n $(\"sched_wr_tl_tool_form_wrtl.time_start\").value = time;\n $(\"Storedsched_wr_tl_tool_form_wrtl.time_start\").value = tmp[0] + \":\" + tmp[1] + \".00.000\";\n }\n else {\n Workflow.handleError(result);\n }\n}",
"function setServiceWindow(){\n if (responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_days\") == \"\") { // new, set default values\n responsePanel.setFieldValue(\"helpdesk_sla_response.serv_window_days\", \"0,1,1,1,1,1,0\");\n }\n \n var serv_days = responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_days\");\n var days = serv_days.split(\",\", 7);\n for (var i = 0; i < 7; i++) {\n if (days[i] == 1) {\n var check = document.getElementById(\"days\" + i);\n check.checked = true;\n }\n }\n \n if (responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_start\") == \"\") \n responsePanel.setFieldValue(\"helpdesk_sla_response.serv_window_start\", \"09:00\");\n if (responsePanel.getFieldValue(\"helpdesk_sla_response.serv_window_end\") == \"\") \n responsePanel.setFieldValue(\"helpdesk_sla_response.serv_window_end\", \"17:00\");\n}",
"function getStartTime() {\n if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {\n Office.cast.item.toItemCompose(item).start.getAsync(\n function (asyncResult) {\n if (asyncResult.status == Office.AsyncResultStatus.Failed) {\n app.showNotification(asyncResult.error.message);\n }\n else {\n // Successfully got the start time, display it, first in UTC and \n // then convert the Date object to local time and display that.\n app.showNotification('The start time in UTC is: ' + asyncResult.value.toString());\n app.showNotification('The start time in local time is: ' + asyncResult.value.toLocaleString());\n }\n });\n }\n else {\n app.showNotification(\"Message items don't have start times.\");\n }\n }",
"function getNewClockingStartTime() {\n // Start time inside dialog depends upon current clocking status\n var currentClockingStatus = JSONData.getCurrentClockingStatus( null );\n var startTime = null;\n if ( currentClockingStatus === \"technicianStatusLoggedIn\" ) {\n startTime = JSONData.getCurrentClockingStartTime( null );\n } else {\n startTime = Util.getISOCurrentTime();\n }\n debug && console.log( \"JSONData.getNewClockingStartTime: New clocking start time = \" + startTime );\n return startTime;\n }",
"get windowStart () {\n\t\treturn this._windowStart;\n\t}",
"function getThisWeekStart() {\r\n const weekStart = new Date()\r\n weekStart.setDate(weekStart.getDate() - weekStart.getDay())\r\n weekStart.setHours(0, 0, 0, 0)\r\n return weekStart\r\n}",
"function windowStart(num) {\n if (num < 12) {\n timeStart = num + \":00 AM\"; //Morning\n } else if (num == 12) {\n timeStart = num + \":00 PM\"; //Midday\n } else if (num > 12) {\n num = num - 12;\n timeStart = num + \":00 PM\"; //afternoon\n }\n return timeStart;\n}",
"function updateCalendarStart(){\n //alert(max_time_range);\n updateCalendarOpts(owgis.constants.startcal);\n // When updateing the 'current' layer by changing the start cal, we should\n // close the popup\n owgis.ol3.popup.closePopUp();\n}",
"function mondayMetricsStart(){\n var windowDeputy = window.open(\"https://2390fa18082540.na.deputy.com/#report\");\n var windowSalesforce = window.open(\"https://na74.salesforce.com/00O1J000005qXny?cancelURL=%2F00O1J000005qXny\");\n var windowTalkdesk = window.open(\"https://campaignmonitor.mytalkdesk.com/#monitoring/schedules/5b9bad188fd0250009ff4431/executions\");\n var windowReportSheet = window.open(\"https://docs.google.com/spreadsheets/d/1tfMcQE9C-hOnw0YWYVwVCyoRtlfcGOcFEqllgk16mPk/edit?usp=drive_web&ouid=108962795010392363253\");\n windowInstructions.focus;\n}",
"static getCurrentWeekStartDate() {\n try {\n let currentDate = new Date();\n let firstDayOfWeek = currentDate.getDate() - currentDate.getDay();\n currentDate.setDate(firstDayOfWeek-7);//added -7 to fetch the test data remove it later\n return libSup.formatDate(currentDate);\n } catch (error) {\n alert(\"getCurrentWeekStartDate-\" + error)\n }\n }",
"StartAppt(s){\n if(!s){\n this.started = new Date()\n } else {\n let duration = this.secondsToTime((new Date().getTime() - this.started.getTime()) / 1000)\n console.log(\"HOUR: \" + duration.h + \" MIN: \" + duration.m + \" SEC: \" + duration.s)\n }\n }",
"function onChangeToolType(){\n //get estimation\n getEstimationFromToolType();\n //fill in date and time started according to service window\n getDateAndTimeStarted();\n}",
"function sendLaunchTimeRequest() {\n\t// wrap the summand and addend as XAL doubles and send the request to the server\n\tmessage_session.sendRequest( \"getLaunchTime\", function( response ) {\n\t\tvar result = response.result;\t\t// get the result\n\t\tvar launch_time_elem = document.getElementById( \"launchtime\" );\t// get the output HTML field\n\t\tlaunch_time_elem.innerHTML = result.from_xal();\n\t} );\n}",
"function mondayMetricsStartSecond() {\n var windowStaffingCalc = window.open(\"https://docs.google.com/spreadsheets/d/16SQoyuG6OZFXiys5yISt0IvNYRD3-eL8pE9Xp20Udkc/edit#gid=0\");\n var surveyResponses = window.open(\"https://www.getfeedback.com/surveys/677515/summary\");\n var managerSlides = window.open(\"https://docs.google.com/presentation/d/1uvvDSunbkUNSS2eU0pjZRqBvJRVBjf3UG-YoMcpZ-pA/edit\");\n var windowDeputy = window.open(\"https://2390fa18082540.na.deputy.com/#roster\");\n var windowCasesClosed = window.open(\"https://campaignmonitor.my.salesforce.com/00O1J000005qXny?cancelURL=%2F00O1J000005qXny\");\n windowInstructions.focus;\n}",
"get startTimeToShow() {\n\t\tvar time = this.eventClass.start.dateTime ? moment(this.eventClass.start.dateTime) : moment(this.eventClass.start.date).startOf('day')\n\t\tif (moment(time).isBefore(moment().startOf('day')))\n\t\t\treturn moment().startOf('day')\n\t\telse return time\n\t}",
"function determineMonitorStartDateTime( dbp, centosMoment, aixMoment ) {\n\n var workDateTime;\n\n // On start up look at last processed entry and if found start monitoring from there.\n\n pdfprocessqueue.getLatestQueueEntry( dbp, function( err, result ) {\n\n if ( err ) {\n\n log.e( 'Unable to access the F559811 for last processed entry' + err );\n unexpectedDatabaseError( err );\n\n } else {\n\n // If table Empty then use System Date and Time from Oracle Host to begin Monitoring\n if ( result === null ) {\n\n lastJdeJob = 'unknown'; \n monitorFromDate = audit.getJdeJulianDateFromMoment( aixMoment );\n monitorFromTime = aixMoment.format( 'HHmmss' );\n \n\n } else {\n\n // Track last PDF procesed and its last Activity Date and Time i.e. when the UBE Job finished\n lastJdeJob = result[ 0 ];\n workDateTime = result[ 1 ].split(' ');\n monitorFromDate = workDateTime[ 0 ];\n monitorFromTime = workDateTime[ 1 ];\n\n }\n\n // Found latest entry in F559811 JDE Post PDF Handling Process Queue - so start monitoring from there\n log.d( 'Begin Monitoring from : ' + monitorFromDate + ' ' + monitorFromTime ); \n\n pollJdePdfQueue( dbp );\n\n }\n });\n}",
"function getTaskStart () {\n return taskSetting.features[0].properties.task_start;\n }",
"function wmsTimeSpan() {\r\n\ttimeSpan();\r\n\tif (td > 604800) {\r\n\t alert(\"Time span for WMS has been reduced to 1 week\");\r\n\t $(\"#duration\").val(\"604800\");\r\n\t timeSpan();\r\n\t}\r\n\tvar wmsStart = new Date(t0);\r\n\tvar wmsEnd = new Date(t1);\r\n\t /// !!!Currently for HFR, only takes time w/ mins, secs set to zero\r\n wmsStart.setUTCMinutes(0);\r\n wmsStart.setUTCSeconds(0);\r\n wmsStart.setUTCMilliseconds(0);\r\n wmsEnd.setUTCMinutes(0);\r\n wmsEnd.setUTCSeconds(0);\r\n wmsEnd.setUTCMilliseconds(0);\r\n\tvar wmsTimeStr = wmsStart.toISOString()+'/'+wmsEnd.toISOString(); \r\n\t// console.log(wmsTimeStr);\r\n\treturn wmsTimeStr;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the jsTree for the given selector | function updateTreeStructure(selector) {
$.getJSON(tree_url + '?dir=' + dir_url, function(data) {
if (data.html) {
/*
* Remove the existing tree, update the content and build the new tree.
* Need to do it this way, otherwise the tree doesn't open to the correct folder.
*/
$(selector).jstree('destroy');
$(selector).html(data.html);
createTree(selector);
}
});
} | [
"updateTreeSelection_() {\n if (angular.isUndefined(this.tree_)) {\n return;\n }\n\n this.tree_['deselect_all']();\n this.tree_['select_node'](this.selectionName_);\n }",
"function updateJSTree( updateJSTreeAction ) {\n //alert(\"JSTreeAction : \" + updateJSTreeAction);\n\n var objClassValue, nodeTitle, nodeId;\n\n if ( top.details.document.forms.nodeForm ) {\n objClassValue = top.details.document.forms.nodeForm.elements.objectClass.value;\n }\n\n if ( objClassValue && objClassValue != \"\" && top.details.detailsMainFrame.document.forms[objClassValue] ) {\n nodeTitle = top.details.detailsMainFrame.document.forms[objClassValue].elements.cn.value;\n nodeID = top.details.detailsMainFrame.document.forms[objClassValue].elements.nodeDN.value;\n }\n\n var actionData = top.navigation.jQuery.tree.plugins.arcorectxmenu.privdata;\n \n switch ( updateJSTreeAction ) {\n\n case \"create\" :\n if ( objClassValue === \"propertyObject\") { \n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle, icon : 'icons/key-icon.png'} }, actionData.REF_NODE, actionData.TYPE);\n } else {\n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle } }, actionData.REF_NODE, actionData.TYPE);\n } \n break;\n\n case \"move\" :\n if ( objClassValue === \"propertyObject\") { \n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle, icon : 'icons/key-icon.png'} }, actionData.REF_NODE, actionData.TYPE);\n } else {\n actionData.TREE_OBJ.create({ attributes : { 'class' : 'leaf', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle } }, actionData.REF_NODE, actionData.TYPE);\n }\n actionData.TREE_OBJ.remove(actionData.NODE);\n break;\n\n case \"link\" :\n actionData.TREE_OBJ.create({ attributes : { 'class' : 'link', 'state' : 'leaf', 'id' : nodeID }, data: { title : nodeTitle, icon : 'icons/link.png'} }, actionData.REF_NODE, actionData.TYPE);\n break;\n\n case \"remove\" :\n actionData.TREE_OBJ.remove(actionData.NODE);\n break;\n }\n}",
"function updateTree(data, select_node_id)\n {\n function initTree(data, select_node_id) {\n $tree.treeview({\n data: data,\n expandIcon: 'glyphicon glyphicon-folder-close',\n collapseIcon: 'glyphicon glyphicon-folder-open',\n emptyIcon: 'glyphicon glyphicon-file'\n });\n\n $tree.treeview('expandAll');\n $tree.on('nodeSelected', onSelect);\n $tree.on('nodeUnselected', onUnselect);\n\n if (typeof(select_node_id) !== 'undefined')\n {\n $tree.treeview('selectNode', select_node_id);\n if (!options['readOnly'])\n {\n updateControls();\n }\n }\n\n if (!options['readOnly'])\n {\n initMovable();\n }\n\n if ( typeof(options['onTreeUpdate']) === 'function' )\n {\n options['onTreeUpdate']($tree);\n }\n\n }\n\n enableControls();\n\n if (typeof(data) !== 'undefined')\n {\n $tree.treeview('remove');\n initTree(data, select_node_id);\n }\n else\n {\n request('refresh', null, function(data)\n {\n if ($tree.hasClass('treeview'))\n {\n $tree.treeview('remove');\n }\n initTree(data);\n });\n }\n }",
"function updateDOM() {\n\tvar newTree = render(data);\n\tvar patches = diff(tree, newTree);\n\trootNode = patch(rootNode, patches);\n\ttree = newTree;\n}",
"function TreeView_UpdateContent(theHTML, theObject)\n{\n\t//now recreate the TreeView Data\n\ttheHTML.TreeData = new TreeViewData_TreeViewData(theObject);\n\t//finally select the data\n\ttheHTML.TreeData.Select(theObject.Properties[__NEMESIS_PROPERTY_SELECTION]);\n}",
"function _updateSelectedObject() {\n var data = $('.listTree').data('listTree');\n // Filter the context to the selected parents.\n var selected = _.filter($.extend(true, {}, data.context), function (parent) {\n return $('.listTree > ul > li > span > input[value=\"' + parent.key + '\"]').prop('checked')\n });\n // For each parent in the working context...\n _.each(selected, function (parent) {\n // Filter the children to the selected children.\n parent.values = _.filter(parent.values, function (child) {\n return $('.listTree > ul > li > ul > li > span > input[value=\"' + child.key +'\"]').prop('checked');\n });\n });\n // Update the plugin's selected object.\n $('.listTree').data('listTree', {\n \"target\": data.target,\n \"context\": data.context,\n \"options\": data.options,\n \"selected\": selected\n });\n }",
"function reloadTreeWithData(jsonData){\n $('#jsTree').tree('loadData', []);\n $('#jsTree').tree('loadData',jsonData);\n}",
"_updateTreeData() {\n let dataTree = this.get('model.rightTreeNodes');\n restorationNodeTree(dataTree, {}, A(['folder', 'desk']), true);\n\n this.get('jstreeActionReceiverRight').send('redraw');\n }",
"function _updateSelectedObject() {\n var data = $('.listTree').data('listTree');\n\n // Filter the context to the selected parents.\n var selected = _.filter($.extend(true, {}, data.context), function(parent) {\n return $('.listTree > ul > li > span > input[value=\"' + parent.key + '\"]').prop('checked')\n });\n \n // For each parent in the working context...\n _.each(selected, function(parent) {\n\n // Filter the children to the selected children.\n parent.values = _.filter(parent.values, function(child) {\n return $('.listTree > ul > li > ul > li > span > input[value=\"' + child.key + '\"]').prop('checked');\n });\n });\n\n // Update the plugin's selected object.\n $('.listTree').data('listTree', {\n \"target\": data.target,\n \"context\": data.context,\n \"options\": data.options,\n \"selected\": selected\n });\n }",
"update() {\n this.lifecycleListeners.beforeUpdate.call(this, this.context);\n if (!this.lifecycleListeners.shouldUpdate.call(this, this.context)) {\n return;\n }\n const vtree = this.render();\n patch(this.node, this.tree, vtree);\n this.lifecycleListeners.afterUpdate.call(this, this.context);\n }",
"function updateRulesFileTree() {\n\n\t\t$.ajax({\n\t\t\ttype: \"GET\",\n\t\t\turl: \"/getJsonRulesTree\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: \"json\"\n\t\t})\n\n\t\t.done(function(d) {\n\t\t\t$('#rulesContainer').jstree(true).settings.core.data = d.rulesTree;\n\t\t\t$('#rulesContainer').jstree(true).refresh();\n\t\t\tgetTotalRulesCount();\n\t\t\tchartTypeRules();\n\t\t})\n\n\t\t.fail(function(d) {\n\t\t\tconsole.log(\"updateRulesFileTree - fail!\")\n\t\t\tconsole.log(d)\n\t\t});\n\t}",
"function pwi_tree_select(path) {\n\tif (pwi_current_path) {\n\t\tlet selected = document.getElementById(pwi_current_path);\n\t\tif (selected) selected.classList.remove(\"filelist-selected\");\n\t}\n\t\n\tlet tree = document.getElementById(\"phpwebide_tree\");\n\tlet node = pwi_find_node(path, tree);\n\tconsole.log(\"pwi_tree_select \"+path+\" found node\");\n\tconsole.log(node);\n\tif (node) node.classList.add(\"filelist-selected\");\n\tpwi_current_path = path;\n}",
"function updateCompiledSelectorView(fileSearch, selection, callback) {\n var hasText = selectionHasText(selection);\n var compiledSelectors = hasText ? getCompiledSelector(fileSearch, selection) : [];\n\n if (!hasText) {\n getCompiledSelector(false);\n }\n\n callback(compiledSelectors);\n}",
"function refreshCurrentTreeNode() {\n var node = $(\"#collection-tree-tree\").dynatree(\"getActiveNode\");\n\trefreshTreeNode(node);\n}",
"function updateInnerHTML(selector, newValue) {\n document.querySelector(selector).innerHTML = newValue;\n}",
"function changeNode() {\n if (selectedCacheNode) {\n var node = cachedTree.findNode(selectedCacheNode);\n if (node && !node.isElementDeleted) {\n //var node = cachedTree.findNode(selectedCacheNode);\n var value = document.getElementById('changingValue').value;\n value.trim() != '' ? node.setData(value) : alert('Please, input smth');\n render(cachedTree, \"CachedTreeView\");\n document.getElementById('addon').innerHTML = node.value + ' value change to: ';\n document.getElementById('addonAdd').innerHTML = 'Add child to ' + node.value + ':';\n document.getElementById('changingValue').value = '';\n } else if (node.isElementDeleted)\n alert('Element has been deleted, you cannot change its value');\n } else\n alert('You should select a node to change')\n}",
"function updateControls()\n {\n $tree.find('.node-selected').each(function(index, element) {\n addUpdateControls($(element));\n });\n }",
"function selectNodeById(id, old_id){\n if (typeof old_id != \"undefined\") { // remove old node if requested to do so\n $('#tree_'+old_id).removeClass('selected');\n }\n build.selected_node = id; // store new node in master array\n var $new_node = $('#tree_'+id); // ...and select the actual tree node\n $new_node.addClass('selected');\n build.tree_actions.appendTo($new_node).show();\n}",
"function updateInnerHTML(selector, newValue) {\n document.querySelector(selector).innerHTML = newValue;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the image (get the buffer and offset) into a new zipLoaderInstance | function parseImageFromZip(doSkipJPG, offsetInReader) {
return new Promise(function(resolve){
var zipLoaderInstance2 = ZipLoader.unzip( MLJ.core.Scene._zipFileArrayBuffer, doSkipJPG, offsetInReader );
resolve(zipLoaderInstance2);
});
} | [
"zipParser(blob){\n var zip = O.esri.zip;\n var _this = this;\n /*O.esri.*/zip.createReader(new /*O.esri.*/zip.BlobReader(blob), function (zipReader) {\n zipReader.getEntries(function (entries) {\n _this.initMap(entries);\n //if(entries)alert(\"TPK downloaded and unzipped!\");\n zipReader.close(function(evt){\n console.log(\"Done reading zip file.\" + evt);\n _this.set(\"loading\", false);\n });\n }, function (err) {\n alert(\"There was a problem reading the file!: \" + err);\n });\n });\n }",
"async function skinParser(zipFileBuffer, JSZip) {\n const zip = await JSZip.loadAsync(zipFileBuffer);\n\n const [\n colors,\n playlistStyle,\n images,\n cursors,\n region,\n genTextSprites,\n genExColors\n ] = await Promise.all([\n genVizColors(zip),\n genPlaylistStyle(zip),\n genImages(zip),\n genCursors(zip),\n genRegion(zip),\n genGenTextSprites(zip),\n genGenExColors(zip)\n ]);\n\n const [genLetterWidths, genTextImages] = genTextSprites || [null, {}];\n\n return {\n colors,\n playlistStyle,\n images: { ...images, ...genTextImages },\n genLetterWidths,\n cursors,\n region,\n genExColors\n };\n}",
"function extract(imageBuffer) {\n return Promise\n .fromCallback((cb) => new exif.ExifImage({image: imageBuffer}, cb))\n .then(pickFields);\n}",
"parseImg() {\n var height = this.mapHead.readUInt32LE(12);\n var width = this.mapHead.readUInt32LE(16);\n let pixels = {\n floor: [],\n obstacle_strong: [],\n rooms: {}\n };\n if (height > 0 && width > 0) {\n for (let i = 0; i < height * width; i++) {\n const val = this.buf.readUInt8(this.offset++);\n let coords;\n if (val !== 0) {\n coords = [i % width, height - 1 - Math.floor(i / width)];\n switch (val) {\n case 0:\n // non-floor, do nothing\n break;\n case 255:\n pixels.obstacle_strong.push(coords[0], coords[1]);\n break;\n case 1: // non-room\n pixels.floor.push(coords[0], coords[1]);\n break;\n default:\n if (!Array.isArray(pixels.rooms[val])) {\n pixels.rooms[val] = [];\n }\n\n pixels.rooms[val].push(coords[0], coords[1]);\n pixels.floor.push(coords[0], coords[1]);\n }\n }\n }\n }\n this.img = {\n position: {\n top: 0,\n left: 0,\n },\n dimensions: {\n height: height,\n width: width,\n },\n pixels: pixels,\n };\n }",
"function GraFlicArchive(zipDataUint8, paramz){\n\t//'this' object will be returned to the caller with contents of the ZIP.\n\tthis.f = {};//each file will have potentially .d (data) containing the files, extracted and decompressed. The filename will be the key to access the file object in files. JSON will have .json containing the reconstituted JSON object. Text will have .t (text) containing the text string. JSON and text do not currently fill the .d property because it would not be very useful and would waste resources.\n\tthis.j = {};//short links to .json ( JS-parsed and ready live JSON for stuff.json would be accessed at .j.stuff )\n\t//Images(PNG/JPG/GIF/WEBP) will have their raw binary appear in files in case metadata needs examining, and will also have an ObjectURL put here in images for easy loading by DOM elements in .b (blob link).\n\t//Other properties may be added to this result object later if needed.\n\t\n\tGraFlicArchive.archives.push(this);//Each archive created will be tracked here so that a file can be looked up if the path exists in any archive in memory with static getFileFromAny()\n\t\n\tvar v_loadedFilename = '**__Unknown__**';\n\tif(paramz){\n\t\tif(paramz.filename){\n\t\t//If the filename is provided, it can be used to check for the common ZIP repackaging mistake of packaging the extracted folder inside of itself and correct it.\n\t\t//This often happens because ZIP extractors will extract the contents into a folder with the folder name based on the filename(without extension). 'A_file.zip' extracts into folder 'A_file/'. Naturally, after editing some of the ZIP contents, the user may context-click the folder and choose to compress. This seems like how it should work, but that will put everything in the new ZIP file into another layer of extra folder that was not in the original. A contained file 'images/example.png' would become 'A_file/images/example.png';\n\t\tv_loadedFilename = paramz.filename.replace(/\\.[^\\.\\/]+$/, '');\n\t\t//TODO: Another approach that may be more reliable since the user may rename the zip after doing this: Detect if the root is empty except for one folder. If that is the case, then strip off the first folder from the extracted filename strings. Do note however, if the developer for some reason designed a save format to have a root that is empty except one folder, this could mess it up.\n\t\t}\n\t\t/*\n\t\tif(paramz.globalAsset){\n\t\t\t//being called with globalAsset true will tell it to keep the files in memory and set up the linkage so that the file can be used to fill custom zip links within the page with the images once they are extracted.\n\t\t\t//This is used when the custom:link rel=\"archive\" element is detected to say that the page uses images/files stored in a zip file.\n\t\t}\n\t\t*/\n\t}//end if paramz defined.\n\tif(!zipDataUint8){\n\t\t//If called without a binary ZIP to load, make a blank GraFlicArchive that can be filled with files programmatically and saved.\n\t\treturn;\n\t}\n//Note when reading, other ZIP builders may insert data descriptor after local file header and payload, which apparently may or may not use a signature...\n\t//Writing data descriptors is turned of in the save function used here with general purpose bit 3 set to 0.\n\tvar v_oct = zipDataUint8;\n\tvar v_pos;\n\tvar v_i;\n\tvar v_entrySize;\n\tvar v_filename;\n\tvar v_filenameSize;\n\tvar v_cdFilenameSize;\n\tvar v_extraFieldSize;\n\tvar v_cdExtraFieldSize;\n\tvar v_commentSize;\n\tvar v_payloadCompression;\n\tvar v_payloadSize;\n\tvar v_extractedBytes;\n\tvar v_fileHeadStart;\n\tvar v_startCRC;\n\tvar v_calcCRC32;\n\tvar v_readCRC32;\n\tvar v_decompressor;\n\tvar v_compSig;//component signature\n\tvar v_bitFlags;\n\tvar v_relOffset;\n\tvar v_offsetMode = 0;//0 for normal, 1 for undocumented mode some writers use that store the offset from the start of the file.\n\tconsole.log('Starting ZIP read. size: ' + v_oct.length);\n\t//First find the start of the end of central directory, it has a variable length comment field so may not be in a set spot.\n\tvar v_cdPos = v_oct.length - 1;//Read the zip starting with the central directory at the end. This is more reliable, since the length and CRC may not be available in the local file header.\n\t//IT MUST start by reading the End of Central Directory section. since there is only a comment field with in the EoCD the chances of collisions with the signature are near-zero when going in reverse to find the start of it.\n\t//reading thru the files from the start will not work because the length fields are not guaranteed to be filled in. In that case, one would have to scan for the start of Data Descriptor signature after the file to get the length. With large sections of binary there are high chances of collisions with the Data Descriptor signature.\n\tvar v_cdSig = 0;\n\twhile(v_cdSig != 0x06054B50){\n\t\tv_cdPos--;\n\t\tv_cdSig = GraFlicEncoder.readUint32(v_oct, v_cdPos, true);\n\t\t//console.log(v_cdSig.toString(16));\n\t}\n\tvar v_filesCountZIP = GraFlicEncoder.readUint16(v_oct, v_cdPos + 10, true);//Number of entries in central directory.\n\tvar v_filesRead = 0;\n\tvar v_cdStart = GraFlicEncoder.readUint32(v_oct, v_cdPos + 16, true);//Where the central directory starts\n\tv_cdPos = v_cdStart;\n\twhile(v_filesRead < v_filesCountZIP){\n\t\tconsole.log('CentDir pos: ' + v_cdPos + ' sig: ' + GraFlicEncoder.readUint32(v_oct, v_cdPos, true).toString(16));\n\t\tv_relOffset = GraFlicEncoder.readUint32(v_oct, v_cdPos + 42, true);\n\t\tif(v_relOffset == 0){v_offsetMode = 1;}\n\t\t//0 is never valid for the offset from central directory defined in the spec. If the first offset is 0, it must use the undocumented mode that uses the offset from the start of the file.\n\t\tif(v_offsetMode == 1){\n\t\t\tv_fileHeadStart = v_relOffset;\n\t\t}else{\n\t\t\tv_fileHeadStart = v_cdPos - v_relOffset;//go backwards by the offset bytes to locate the local file header.\n\t\t}\n\t\tconsole.log('version made by, version: ' + v_oct[v_cdPos + 4] + ' OS: ' + v_oct[v_cdPos + 5]);\n\t\tconsole.log('version needed to extract, version: ' + v_oct[v_cdPos + 6] + ' OS: ' + v_oct[v_cdPos + 7]);\n\t\tconsole.log('rel offset: ' + v_relOffset + ' starting at: ' + v_fileHeadStart);\n\t\tv_pos = v_fileHeadStart;\n\t\tv_payloadSize = GraFlicEncoder.readUint32(v_oct, v_cdPos + 20, true);//Read size out of central directory where it should be calculated. In the local file header it may be undefined if bit 3 of the flags is set. So far, this seems to reliably work to get payload size.\n\t\tv_cdFilenameSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 28, true);\n\t\tv_cdExtraFieldSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 30, true);//The extra field on central directory might be different from local file header.\n\t\tv_commentSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 32, true);//Comment ONLY appears on central directory header, NOT the local file header.\n\n\t\tconsole.log('local file header sig: ' + GraFlicEncoder.readUint32(v_oct, v_pos, true).toString(16));\n\t\tv_bitFlags = GraFlicEncoder.readUint16(v_oct, v_pos + 6, true);\n\t\tv_payloadCompression = GraFlicEncoder.readUint16(v_oct, v_pos + 8, true);\n\t\tv_filenameSize = GraFlicEncoder.readUint16(v_oct, v_pos + 26, true);\n\t\tv_extraFieldSize = GraFlicEncoder.readUint16(v_oct, v_pos + 28, true);\n\t\tv_pos += 30;\n\t\t\n\t\tv_filename = GraFlicEncoder.readStringUTF8(v_oct, v_pos, v_filenameSize);\n\t\t//OLD only ASCII compatible: v_filename = String.fromCharCode.apply(null, v_oct.subarray(v_pos, v_pos + v_filenameSize));\n\t\tv_pos += v_filenameSize;\n\t\tv_pos += v_extraFieldSize;//This app does not use extra field, but check for it in case the ZIP was edited and repackaged by another ZIP writer.\n\t\t\n\t\tv_cdPos += 46 + v_cdFilenameSize + v_cdExtraFieldSize + v_commentSize;//Advance to the next central directory header for the next file.\n\t\t\n\t\tconsole.log('Central Directory sizes: filename: ' + v_cdFilenameSize + ' comment: ' + v_commentSize + ' extra: ' + v_cdExtraFieldSize);\n\t\tconsole.log('Reading ' + v_filename + ' out of ZIP.');\n\t\tconsole.log('Local File Header sizes: payload: ' + v_payloadSize + ' filename: ' + v_filenameSize + ' extra: ' + v_extraFieldSize);\n\t\tconsole.log('bit flags: 0x' + v_bitFlags.toString(16));\n\t\tv_decompressor = GraFlicUtil.noCompression;//default to 0, no compression\n\t\tconsole.log('compression mode: ' + v_payloadCompression);\n\t\tif(v_payloadCompression == 8){//DEFLATE\n\t\t\tv_decompressor = window.pako.inflateRaw;\n\t\t}\n\t\tif(v_filename.match(/(^|\\/)\\./)){ // || v_filename.match(/\\..*\\./)){\n\t\t\t//Throw out files that start with a dot.\n\t\t\t//These are probably system generated junk files, the save format does not use files named this way.\n\t\t\t//In *nix operating systems starting with a dot(.) is a hidden file, often some kind of system file.\n\t\t\tconsole.log('Skipping apparent junk file: ' + v_filename);\n\t\t}else{\n\t\t\tv_extractedBytes = v_oct.subarray(v_pos, v_pos + v_payloadSize);\n\t\t\tif(v_filename.match(/\\//) && v_filename.split('/')[0].indexOf(v_loadedFilename) == 0){\n\t\t\t\t\t\t\t//(Remember, extra things like (2) may get appended to the filename if it gets renamed due to existing file that it was extracted from.)\n\t\t\t\t//If the files are in a folder with the same name as the loaded file, the user probably re-packed them\n\t\t\t\t//incorrectly which is easy to do, given the unintuitive way ZIPs extract out to a folder, but if you\n\t\t\t\t//compress the folder again, it puts the folder within the ZIP, so in that case, strip these out.\n\t\t\t\tv_filename = v_filename.replace(/^[^\\/]+\\//, '');\n\t\t\t\tconsole.log('The folder was repackaged inside of itself it seems. Filename fixed to: ' + v_filename);\n\t\t\t}\n\t\t\tvar xFile = {};\n\t\t\txFile.p = v_filename;//keep a reference for what the path is in case object referenced elsewhere.\n\t\t\ttry{//-----------------------------------------------------------------------------------\n\t\t\tif(v_filename.match(/\\.gz$/i)){\n\t\t\t\t//If .gz first decompress it with whatever compression method is defined in the ZIP entry (usually 0 none),\n\t\t\t\t//then set the decompressor to ungzip because .gz has internal compression of its own.\n\t\t\t\tv_extractedBytes = v_decompressor(v_extractedBytes);\n\t\t\t\tv_decompressor = window.pako.ungzip;\n\t\t\t\tconsole.log('.gz file, setting decompression to GZip, gz payload size: ' + v_extractedBytes.length);\n\t\t\t}\n\t\t\t//JSON and text will not have .d (data) populated since it is pretty useless in most cases and would waste resources.\n\t\t\tif(v_filename.match(/\\.json(\\.gz)?$/i)){\n\t\t\t\t//JSON needs extra logic to JSONize it into memory.\n\t\t\t\txFile.j = JSON.parse(v_decompressor(v_extractedBytes, {'to':'string'}));\n\t\t\t\t//alert('extracted JSON(' + v_filename + '): ' + JSON.stringify(xFile));\n\t\t\t\tthis.j[v_filename.replace(/\\.json(\\.gz)?$/i, '')] = xFile.j;//Set up a quick link for accessing JSON.\n\t\t\t\t\t\t\t//JSON files will typically contain the main configuration, parameters, and settings of a format\n\t\t\t\t\t\t\t//and need to be accessed often so .j.config.valX is less cluttered than: .f['config.json'].valX\n\t\t\t\t\t\t\t//do this after the file was successfully extracted\n\t\t\t}else if(v_filename.match(/\\.txt(\\.gz)?$/i)){\n\t\t\t\txFile.t = v_decompressor(v_extractedBytes, {'to':'string'});\n\t\t\t}else{\n\t\t\t\txFile.d = v_decompressor(v_extractedBytes);\n\t\t\t\t//Some browser may truncate the array text when tracing to debug and look like all zeroes.\n\t\t\t\tconsole.log('extracted U8Array(' + v_filename + '): ' + xFile + ' size: ' + xFile.d.length);\n\t\t\t}\n\t\t\t}catch(fileError){\n\t\t\t\tconsole.log('error reconstituting ' + v_filename + ', it may be a junk or auto-generated file.');\n\t\t\t}//-------------------------------- end try/catch ----------------------------------------\n\n\t\t\t//else if(v_filename.match(/\\.(a*png|jpe*g|giff*|webp)(\\.gz)?$/i)){\n\t\t\t//}\n\t\t\t\t//Keep image Uint8Array linked in case it needs to be examined for metadata such as EXIF rotation.\n\t\t\t\t//Also make a loadable BLOB ObjectURL so it can easily be loaded into images in the DOM.\n\t\t\t\t//Since the Uint8Array is used to build the BLOB for the ObjectURL, it would seem that dereferencing\n\t\t\t\t//it would probably not save any runtime resources, may as well keep it alive for analysis if needed.\n\t\t\t//make BLOBs for all files too\n\t\t\txFile.d = v_decompressor(v_extractedBytes);\n\t\t\tthis.fileToBLOB(xFile);\n\t\t\tthis.f[v_filename] = xFile;//if completed with no errors, include it in the files object\n\t\t\tconsole.log('----------------------');\n\t\t}\n\t\tv_filesRead++;\n\t}//end while\n}",
"async parseExifBlock() {\n\t\tif (this.exifOffset === undefined) return\n\t\tthis.exif = await this.parseTiffTags(this.tiffOffset + this.exifOffset, tags.exif)\n\t}",
"function Image2DParser() {\n _super.call(this, URLLoaderDataFormat.BLOB);\n }",
"async function parseFramesFromZip(name, fwidth, fheight, zip, nframes){\n\n if (name + \"-Anim.png\" in zip.files){ //check if the file exists\n let b64 = await zip.file(name + \"-Anim.png\").async(\"base64\")\n let img = await getImgfromB64(b64);\n\n //sanity check file size\n if (img.width != nframes * fwidth || !(img.height == fheight || img.height == fheight * 8)){\n addWarning(\"Warning\", \"sprite\", \"The file \" + name + \"-Anim.png has different dimensions than expected, check the frame sizes or the image dimesions. Sprites in that animation may look wrong or some might be missing.\");\n }\n\n return await parseFramesfromIMG(fwidth, fheight, img, nframes);\n }else {\n\n addWarning(\"Error\", \"sprite\", \"The file \" + name + \"-Anim.png is missing or broken (name is Case Sensitive). Generating an empty/transparent spritesheet.\");\n frames = generateEmptyFrames(fwidth, fheight, nframes, 8);\n return null;\n }\n}",
"function Image2DParser() {\n return _super.call(this, URLLoaderDataFormat.BLOB) || this;\n }",
"parse(buffer){\r\n this.buffer = buffer;\r\n this.type = buffer.toString('utf-8', 0, 2);\r\n this.pixelOffset = buffer.readInt32LE(_PIXEL_OFFSET);\r\n this.colorArray = buffer.slice(_COLOR_TABLE_OFFSET, Bitmap.pixelOffset);\r\n }",
"_insertFromCbz(){\n var self = this;\n self._zip = new StreamZip({\n file: self._comic,\n storeEntries: true\n });\n self._zip.on('error', function(err) {\n self._callError(err);\n });\n\n self._zip.on('ready', function() {\n var files = self._zip.entries();\n var total = self._zip.entriesCount, index = 0;\n var q = queue();\n q.concurrency = 1;\n for (let prop in files) {\n\n if (!files.hasOwnProperty(prop)) {\n continue;\n }\n\n let ext = path.extname(prop);\n let name = path.basename(prop)\n if( ext == \".jpg\" || ext == \".png\" ){\n q.push(function(cb) {\n self._data.images.push({\n \"file\" : name,\n \"page\" : (index < 10)?0+index:index\n })\n self._zip.stream(prop, function(err, stream) {\n if ( err) self._callError(err);\n var imageSizeStream = ImageSizeStream()\n .on('size', function(dimensions) {\n self._data.images[index].mimeType = mime.lookup(dimensions.type);\n self._data.images[index].width = dimensions.width;\n self._data.images[index].height = dimensions.height;\n });\n stream.pipe(imageSizeStream);\n self._archive.entry(stream, { name: path.join(self._model.imagePath,name) , date: self._date}, function(err) {\n index++;\n if ( err) self._callError(err);\n cb();\n });\n });\n })\n }\n }\n q.start(function(err) {\n if ( err) self._callError(err);\n if(self._data.images.length < 1){\n self._callError(\"No images found\");\n }else{\n self._insertInteractive(0, 0);\n }\n });\n })\n }",
"function loader(func,str,arr,exp,cb) {\n var\n p=function(){return func([],str(pakoOffsetStart,pakoOffsetEnd))();},\n z=function(){return func([],exp.pako.inflate(arr(JSZipOffsetStart,JSZipOffsetEnd),{to:'string'}))();};\n try {\n p();\n z();\n var zip = new exp.JSZip();\n zip.loadAsync(arr(ZipFileOffsetStart,ZipFileOffsetEnd))\n .then(function(zip){cb(null,zip);})\n .catch(cb);\n } catch(err) {\n cb(err);\n }\n p=z=null;\n }",
"function GraFlicArchive(zipDataUint8, paramz){\n\t//'this' object will be returned to the caller with contents of the ZIP.\n\tthis.files = {};//each file will have potentially .d (data) containing the files, extracted and decompressed. The filename will be the key to access the file object in files. JSON will have .json containing the reconstituted JSON object. Text will have .t (text) containing the text string. JSON and text do not currently fill the .d property because it would not be very useful and would waste resources.\n\t//Images(PNG/JPG/GIF/WEBP) will have their raw binary appear in files in case metadata needs examining, and will also have an ObjectURL put here in images for easy loading by DOM elements in .b (blob link).\n\t//Other properties may be added to this result object later if needed.\n\t\n\tGraFlicArchive.archives.push(this);//Each archive created will be tracked here so that a file can be looked up if the path exists in any archive in memory with static getFileFromAny()\n\tvar jAM = null;//will be populated if archive-metadata.json type validator found.\n\tvar bloatFolder = null;//null for N/A, will be used to fix a common packaging mistake that wraps an extra folder around everything.\n\tif(!paramz){\n\t\tparamz = {};//makes handling undefined vars easier if paramz.x is undefined it can just send undefined for optional x if needed without getting 'paramz is undefined'\n\t}\n\t\t/*\n\t\tif(paramz.globalAsset){\n\t\t\t//being called with globalAsset true will tell it to keep the files in memory and set up the linkage so that the file can be used to fill custom zip links within the page with the images once they are extracted.\n\t\t\t//This is used when the custom:link rel=\"archive\" element is detected to say that the page uses images/files stored in a zip file.\n\t\t}\n\t\t*/\n\tif(!zipDataUint8){\n\t\t//If called without a binary ZIP to load, make a blank GraFlicArchive that can be filled with files programmatically and saved.\n\t\t/*\n\t\tvar paramApps = undefined;\n\t\tif(paramz.app){//Single app string, convert to array for archive-metadata.json\n\t\t\tparamApps = [paramz.app];\n\t\t}\n\t\tif(paramz.apps){\n\t\t\tparamApps = paramz.apps;//.apps plural sent should be sent as array\n\t\t}\n\t\t//Note that these extra parameters and logic may not be needed. It may be better to just set the properties of the archive-metadata.json object after the GraFlicArchive is initialized to match what the given software or format needs. This would simplify the constructor. Falling back to the generic application/octet-stream type will probably not be devastating if properties are not customized after creation.\n\t\t\t//paramz.mime, paramz.type, paramApps);\n\t\t*/\n\t\tthis.addArchiveMetadata();\n\t\treturn;\n\t}\n//Note when reading, other ZIP builders may insert data descriptor after local file header and payload, which apparently may or may not use a signature...\n\t//Writing data descriptors is turned of in the save function used here with general purpose bit 3 set to 0.\n\tvar v_oct = zipDataUint8;\n\tvar v_pos;\n\tvar v_i;\n\tvar v_entrySize;\n\tvar v_filename;\n\tvar v_filenameSize;\n\tvar v_cdFilenameSize;\n\tvar v_extraFieldSize;\n\tvar v_cdExtraFieldSize;\n\tvar v_commentSize;\n\tvar v_payloadCompression;\n\tvar v_payloadSize;\n\tvar v_payloadUncompressedSize;\n\tvar v_extractedBytes;\n\tvar v_fileHeadStart;\n\t//var v_calcCRC32;\n\tvar v_readCRC32;\n\tvar v_compSig;//component signature\n\tvar v_bitFlags;\n\tvar v_relOffset;\n\t//OLD, incorrect: var v_offsetMode = 0;//0 for normal, 1 for undocumented mode some writers use that store the offset from the start of the file.\n\tconsole.log('Starting ZIP read. size: ' + v_oct.length);\n\t//First find the start of the end of central directory, it has a variable length comment field so may not be in a set spot.\n\tvar v_cdPos = v_oct.length - 1;//Read the zip starting with the central directory at the end. This is more reliable, since the length and CRC may not be available in the local file header.\n\t//IT MUST start by reading the End of Central Directory section. since there is only a comment field with in the EoCD the chances of collisions with the signature are near-zero when going in reverse to find the start of it.\n\t//reading thru the files from the start will not work because the length fields are not guaranteed to be filled in. In that case, one would have to scan for the start of Data Descriptor signature after the file to get the length. With large sections of binary there are high chances of collisions with the Data Descriptor signature.\n\tvar v_cdSig = 0;\n\twhile(v_cdSig != 0x06054B50){\n\t\tv_cdPos--;\n\t\tv_cdSig = GraFlicEncoder.readUint32(v_oct, v_cdPos, true);\n\t\t//console.log(v_cdSig.toString(16));\n\t}\n\tvar v_filesCountZIP = GraFlicEncoder.readUint16(v_oct, v_cdPos + 10, true);//Number of entries in central directory.\n\tvar v_filesRead = 0;\n\tvar v_cdStart = GraFlicEncoder.readUint32(v_oct, v_cdPos + 16, true);//Where the central directory starts\n\tv_cdPos = v_cdStart;\n\twhile(v_filesRead < v_filesCountZIP){\n\t\tconsole.log('CentDir pos: ' + v_cdPos + ' sig: ' + GraFlicEncoder.readUint32(v_oct, v_cdPos, true).toString(16));\n\t\tv_relOffset = GraFlicEncoder.readUint32(v_oct, v_cdPos + 42, true);\n\t\t//if(v_relOffset == 0){v_offsetMode = 1;}\n\t\t//0 is never valid for the offset from central directory defined in the spec. If the first offset is 0, it must use the undocumented mode that uses the offset from the start of the file.\n\t\t//if(v_offsetMode == 1){\n\t\tv_fileHeadStart = v_relOffset;//In ZIP 2.0, it is always the position from the beginning of the file, the other way was incorrect.\n\t\t//}else{\n\t\t//\tv_fileHeadStart = v_cdPos - v_relOffset;//go backwards by the offset bytes to locate the local file header.\n\t\t//}\n\t\tconsole.log('version made by, version: ' + v_oct[v_cdPos + 4] + ' OS: ' + v_oct[v_cdPos + 5]);\n\t\tconsole.log('version needed to extract, version: ' + v_oct[v_cdPos + 6] + ' OS: ' + v_oct[v_cdPos + 7]);\n\t\tconsole.log('rel offset: ' + v_relOffset + ' starting at: ' + v_fileHeadStart);\n\t\tv_pos = v_fileHeadStart;\n\t\tv_readCRC32 = GraFlicEncoder.readInt32(v_oct, v_cdPos + 16, true);\n\t\tv_payloadSize = GraFlicEncoder.readUint32(v_oct, v_cdPos + 20, true);//Read size out of central directory where it should be calculated. In the local file header it may be undefined if bit 3 of the flags is set. So far, this seems to reliably work to get payload size.\n\t\tv_payloadUncompressedSize = GraFlicEncoder.readUint32(v_oct, v_cdPos + 24, true);\n\n\t\tv_cdFilenameSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 28, true);\n\t\tv_cdExtraFieldSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 30, true);//The extra field on central directory might be different from local file header.\n\t\tv_commentSize = GraFlicEncoder.readUint16(v_oct, v_cdPos + 32, true);//Comment ONLY appears on central directory header, NOT the local file header.\n\n\t\t//console.log('i att(L): ' + GraFlicEncoder.readUint16(v_oct, v_cdPos + 36, true).toString(2));\n\t\t//console.log('x att(L): ' + GraFlicEncoder.readUint32(v_oct, v_cdPos + 38, true).toString(2));\n\n\t\tconsole.log('local file header sig: ' + GraFlicEncoder.readUint32(v_oct, v_pos, true).toString(16));\n\t\tv_bitFlags = GraFlicEncoder.readUint16(v_oct, v_pos + 6, true);\n\t\tv_payloadCompression = GraFlicEncoder.readUint16(v_oct, v_pos + 8, true);\n\t\tv_filenameSize = GraFlicEncoder.readUint16(v_oct, v_pos + 26, true);\n\t\tv_extraFieldSize = GraFlicEncoder.readUint16(v_oct, v_pos + 28, true);\n\t\tv_pos += 30;\n\t\t\n\t\tv_filename = GraFlicEncoder.readStringUTF8(v_oct, v_pos, v_filenameSize);\n\t\t//OLD only ASCII compatible: v_filename = String.fromCharCode.apply(null, v_oct.subarray(v_pos, v_pos + v_filenameSize));\n\t\tv_pos += v_filenameSize;\n\t\tv_pos += v_extraFieldSize;//This app does not use extra field, but check for it in case the ZIP was edited and repackaged by another ZIP writer.\n\t\t\n\t\tv_cdPos += 46 + v_cdFilenameSize + v_cdExtraFieldSize + v_commentSize;//Advance to the next central directory header for the next file.\n\t\t\n\t\tconsole.log('Central Directory sizes: filename: ' + v_cdFilenameSize + ' comment: ' + v_commentSize + ' extra: ' + v_cdExtraFieldSize);\n\t\tconsole.log('Reading ' + v_filename + ' out of ZIP.');\n\t\tconsole.log('Local File Header sizes: payload: ' + v_payloadSize + ' filename: ' + v_filenameSize + ' extra: ' + v_extraFieldSize);\n\t\tconsole.log('bit flags: 0x' + v_bitFlags.toString(16));\n\t\t\n\t\t\n\t\tif(v_filename.match(/desktop\\.ini$/) || v_filename.match(/__MACOSX\\//) || v_filename.match(/\\.DS_Store$/)){\n\t\t\t\t// || v_filename.match(/(^|\\/)\\./)){ // || v_filename.match(/\\..*\\./)){\n\t\t\t//Detect and throw out apparent non-user, OS-generated files.\n\t\t\t//If a user repackages or builds a ZIP-based file with another packaging tool, these can end up creeping into the archive and they are not needed for the ZIP-based formats.\n\t\t\t//Throw out files that start with a dot??\n\t\t\t//These are probably system generated junk files, the save format does not use files named this way.\n\t\t\t//However some users may have designed archives specifically using these types of files for some reason...\n\t\t\t//In *nix operating systems starting with a dot(.) is a hidden file, often some kind of system file.\n\t\t\tconsole.log('Skipping apparently irrelevant file: ' + v_filename);\n\t\t}else{\n\t\t\tv_extractedBytes = v_oct.subarray(v_pos, v_pos + v_payloadSize);\n\t\t\t\t//CRC is based on BEFORE being compressed, it will not be uncompressed until accessed...\n\t\t\t\t//incorrect v_calcCRC32 = GraFlicEncoder.getCRC32(v_extractedBytes, 0, v_payloadSize);\n\t\t\t\t//console.log('CRC calculated: ' + v_calcCRC32 + ' CRC read: ' + v_readCRC32);\n\t\t\tvar xFile = {};\n\t\t\txFile.reconst = false;//Has not been reconstituted. This will be done as needed if the file is accessed via .f('filepath'). That way resources are saved by not making every file live on load when not all files may be used right away, if even used at all.\n\t\t\txFile.compression = v_payloadCompression;//Compression method code as defined by ZIP.\n\t\t\txFile.uncompressed_size = v_payloadUncompressedSize;//Will need to know what size the original file is if re-packaging it.\n\t\t\txFile.zip_crc = v_readCRC32;//save the CRC that was generated over the full uncompressed payload by the ZIP packager.\n\t\t\t//console.log('uncompressed size: ' + uncompressed_size);\n\t\t\txFile.p = v_filename;//keep a reference for what the path is in case object referenced elsewhere.\n\t\t\t\n\t\t\txFile.d = v_extractedBytes;//These bytes will be decompressed later if the archived file entry is reconstituted.\n\t\t\tthis.files[v_filename] = xFile;//if completed with no errors, include it in the files object\n\t\t\tconsole.log('----------------------');\n\t\t\t\n\t\t\tvar partsAM = v_filename.match(/^(.*\\/)archive-metadata\\.json$/);//detect a bloat folder if packaging mistake was made.\n\t\t\tif(partsAM){//If matches at all\n\t\t\t\tconsole.log('.-.-.-.-. archive metadata (validate file type) .-.-.-.-.-.');\n\t\t\t\tjAM = this.f(v_filename).j;\n\t\t\t\t//The archive-metadata.json filename is long and unique enough that it out to block most collisions with other files out there on its own.\n\t\t\t\t//however, an additional check can optionally be done with .signature in case some archive somewhere has an archive-metadata.json that does something different.\n\t\t\t\tif(jAM.archiveMetadata && jAM.archiveMetadata.signature == 'archive metadata'){//verify it is for this purpose\n\t\t\t\t\tconsole.log('confirmed to be metadata/type validator: archive-metadata.json');\t\n\t\t\t\t\tif(jAM.archiveMetadata.version){//Already checked .archiveMetadata in previous if.\n\t\t\t\t\t\t//The version number is optional and merely a hint for what properties might be defined.\n\t\t\t\t\t\tconsole.log('archive-metadata.json version: ' + jAM.archiveMetadata.version);\n\t\t\t\t\t}\n\t\t\t\t\tif(partsAM && partsAM[1] && partsAM[1].length){\n\t\t\t\t\t\tbloatFolder = partsAM[1];\n\t\t\t\t\t\tconsole.log('User apparently made common mistake of packaging everything wrapped in an extra bloat folder. The bloat folder(' + bloatFolder + ') will be stripped from paths.');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconsole.log('.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.');\n\t\t\t}\n\t\t}\n\t\tv_filesRead++;\n\t}//end while\n\tif(bloatFolder){//Remove the bloat folder portion from paths if a packaging mistake resulted in things being wrapped in a bloat folder. The next time this is saved by an app using GraFlicArchive, it will be properly packaged without the bloat folder.\n\t\tvar unbloatedFiles = {};\n\t\tfor(var key in this.files){\n\t\t\tvar bRepFile = this.files[key];\n\t\t\tbRepFile.p = bRepFile.p.replace(new RegExp('^' + bloatFolder), '');\n\t\t\tunbloatedFiles[bRepFile.p] = bRepFile;\n\t\t}\n\t\tthis.files = unbloatedFiles;\n\t}\n}",
"function zillowRunner(zip) {\n zillowGetter(zip);\n }",
"constructor(packData) {\n this.name = name;\n if (packData instanceof ArrayBuffer) {\n // zip with bops uses Uint8Array data view\n packData = new Uint8Array(packData);\n }\n this.zip = new ZIP.Reader(packData);\n\n this.zipEntries = {};\n this.zip.forEach((entry) => {\n this.zipEntries[entry.getName()] = entry;\n });\n\n this.namespaces = this.scanNamespaces();\n }",
"function readZipFile(codeVar){\r\n\r\n\tvar zip = new JSUnzip(window.atob(codeVar));\r\n\t//read archive\r\n\tzip.readEntries();\r\n\r\n\t// read files\r\n\tfor (var i = 0; i < zip.entries.length; i++) {\r\n\t\tvar entry = zip.entries[i];\r\n\t\tstimuliAllInfo[i] = imageProcess(entry);\r\n\t}\r\n\r\n}",
"async function parseToImage(arrayBuffer, options) {\n // Note: image parsing requires conversion to Blob (for createObjectURL).\n // Potentially inefficient for not using `response.blob()` (and for File / Blob inputs)...\n // But presumably not worth adding 'blob' flag to loader objects?\n\n // TODO - how to determine mime type? Param? Sniff here?\n const mimeType = 'image/jpeg';\n const blob = new Blob([arrayBuffer], {type: mimeType});\n const URL = self.URL || self.webkitURL;\n const objectUrl = URL.createObjectURL(blob);\n try {\n return await loadToImage(objectUrl, options);\n } finally {\n URL.revokeObjectURL(objectUrl);\n }\n}",
"function Image2DParser(factory, alphaChannel) {\n if (factory === void 0) { factory = null; }\n if (alphaChannel === void 0) { alphaChannel = null; }\n var _this = _super.call(this, _awayjs_core__WEBPACK_IMPORTED_MODULE_1__[\"URLLoaderDataFormat\"].BLOB) || this;\n _this._factory = factory || new _factories_DefaultGraphicsFactory__WEBPACK_IMPORTED_MODULE_4__[\"DefaultGraphicsFactory\"]();\n _this._alphaChannel = alphaChannel;\n return _this;\n }",
"*buildImageMetadata(){\n if(this.type !== 'image') return;\n\n const image = yield _p(lwip.open)(lwip, this.path);\n this.width = image.width();\n this.height = image.height();\n this.size = fs.lstatSync(this.path).size;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets if the provided structure is a JSDocableNodeStructure. | static isJSDocable(structure) {
switch (structure.kind) {
case StructureKind_1.StructureKind.Class:
case StructureKind_1.StructureKind.Constructor:
case StructureKind_1.StructureKind.ConstructorOverload:
case StructureKind_1.StructureKind.GetAccessor:
case StructureKind_1.StructureKind.Method:
case StructureKind_1.StructureKind.MethodOverload:
case StructureKind_1.StructureKind.Property:
case StructureKind_1.StructureKind.SetAccessor:
case StructureKind_1.StructureKind.Enum:
case StructureKind_1.StructureKind.EnumMember:
case StructureKind_1.StructureKind.Function:
case StructureKind_1.StructureKind.FunctionOverload:
case StructureKind_1.StructureKind.CallSignature:
case StructureKind_1.StructureKind.ConstructSignature:
case StructureKind_1.StructureKind.IndexSignature:
case StructureKind_1.StructureKind.Interface:
case StructureKind_1.StructureKind.MethodSignature:
case StructureKind_1.StructureKind.PropertySignature:
case StructureKind_1.StructureKind.Namespace:
case StructureKind_1.StructureKind.VariableStatement:
case StructureKind_1.StructureKind.TypeAlias:
return true;
default:
return false;
}
} | [
"static isJSDoc(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JSDoc;\r\n }",
"static isJSDocableNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.ClassDeclaration:\r\n case typescript_1.SyntaxKind.ClassExpression:\r\n case typescript_1.SyntaxKind.Constructor:\r\n case typescript_1.SyntaxKind.GetAccessor:\r\n case typescript_1.SyntaxKind.MethodDeclaration:\r\n case typescript_1.SyntaxKind.PropertyDeclaration:\r\n case typescript_1.SyntaxKind.SetAccessor:\r\n case typescript_1.SyntaxKind.EnumDeclaration:\r\n case typescript_1.SyntaxKind.EnumMember:\r\n case typescript_1.SyntaxKind.ArrowFunction:\r\n case typescript_1.SyntaxKind.FunctionDeclaration:\r\n case typescript_1.SyntaxKind.FunctionExpression:\r\n case typescript_1.SyntaxKind.CallSignature:\r\n case typescript_1.SyntaxKind.ConstructSignature:\r\n case typescript_1.SyntaxKind.IndexSignature:\r\n case typescript_1.SyntaxKind.InterfaceDeclaration:\r\n case typescript_1.SyntaxKind.MethodSignature:\r\n case typescript_1.SyntaxKind.PropertySignature:\r\n case typescript_1.SyntaxKind.ImportEqualsDeclaration:\r\n case typescript_1.SyntaxKind.ModuleDeclaration:\r\n case typescript_1.SyntaxKind.ExpressionStatement:\r\n case typescript_1.SyntaxKind.LabeledStatement:\r\n case typescript_1.SyntaxKind.VariableStatement:\r\n case typescript_1.SyntaxKind.TypeAliasDeclaration:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isJSDocType(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.JSDocFunctionType:\r\n case typescript_1.SyntaxKind.JSDocSignature:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"function hasJSDocNodes(node) {\n return !!node.jsDoc && node.jsDoc.length > 0;\n }",
"function hasJSDocNodes(node) {\n return !!node.jsDoc && node.jsDoc.length > 0;\n }",
"static isJSDocTag(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.JSDocAugmentsTag:\r\n case typescript_1.SyntaxKind.JSDocClassTag:\r\n case typescript_1.SyntaxKind.JSDocParameterTag:\r\n case typescript_1.SyntaxKind.JSDocPropertyTag:\r\n case typescript_1.SyntaxKind.JSDocReturnTag:\r\n case typescript_1.SyntaxKind.JSDocTypedefTag:\r\n case typescript_1.SyntaxKind.JSDocTypeTag:\r\n case typescript_1.SyntaxKind.JSDocTag:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"static isJSDoc(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.JSDocComment;\r\n }",
"function isJSDocNode(node) {\n return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */;\n }",
"function isJSDocNode(node) {\n return node.kind >= 271 /* FirstJSDocNode */ && node.kind <= 289 /* LastJSDocNode */;\n }",
"static isNode(obj) {\n\t\treturn obj.type;\n\t}",
"static isJSDocTypeTag(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.JSDocTypeTag;\r\n }",
"static isJsxElement(structure) {\r\n return structure.kind === StructureKind_1.StructureKind.JsxElement;\r\n }",
"function sc_isStruct(o) {\n return (o instanceof sc_Struct);\n}",
"function isNode(o){\n return (\n typeof Node === \"object\" ? o instanceof Node :\n o && typeof o === \"object\" && typeof o.nodeType === \"number\" && typeof o.nodeName===\"string\"\n );\n}",
"function _isNode(x){\n\treturn !!(x.tree && x.statusNodeType !== undefined);\n}",
"function isJSDocCommentContainingNode(node) {\n return node.kind === 279 /* JSDocComment */ || isJSDocTag(node);\n }",
"function getJSDocNode(node, ts) {\n var _a, _b, _c;\n var parent = (_b = (_a = ts.getJSDocTags(node)) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.parent;\n if (parent != null && ts.isJSDoc(parent)) {\n return parent;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (_c = node.jsDoc) === null || _c === void 0 ? void 0 : _c.find(function (n) { return ts.isJSDoc(n); });\n}",
"function isNodeLike(obj) {\n return obj && (obj.nodeType === 1 || obj.nodeType === 9);\n }",
"static isTyped(structure) {\r\n switch (structure.kind) {\r\n case StructureKind_1.StructureKind.Property:\r\n case StructureKind_1.StructureKind.Parameter:\r\n case StructureKind_1.StructureKind.PropertySignature:\r\n case StructureKind_1.StructureKind.VariableDeclaration:\r\n case StructureKind_1.StructureKind.TypeAlias:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
do invoice transition on save activity | function saveActivityAndDoTransition() {
Y.doccirrus.jsonrpc.api.activity.read( { query: { _id: ko.unwrap( activities[0] ) } } )
.then(function( res ) {
var
data = res.data && res.data[0],
isCorrectTransition = false;
// checking if transition is allowed
if( 'INVOICEREF' === data.actType || 'INVOICE' === data.actType ) {
fsm[data.status].forEach(function( item ) {
if( item.transition === transition.transition ) {
isCorrectTransition = true;
}
});
}
if( !isCorrectTransition ) {
Y.doccirrus.DCWindow.notice( {
type: 'info',
message: i18n( 'InCaseMojit.ActivityDetailsVM.error.not_correct_status' ),
window: {
width: 'medium'
}
} );
return null;
}
return data;
}).then(function( res ) {
if( res ) {
// test transition
activityDetailsVM.saveAttachmentsAndTransition( transitionArgs )
.then(function( res ) {
return res;
}).then(function() {
roundReceiptAmount = parseFloat( currentActivity && currentActivity.amount ? currentActivity.amount() : 0 ).toFixed( 2 );
roundOutstanding = parseFloat( res.totalReceiptsOutstanding ).toFixed( 2 );
if ( currentActivity && ( roundReceiptAmount !== roundOutstanding ) && ( 'pay' === transition.transition || 'derecognize' === transition.transition ) ) {
willBalanceInvoice = true;
}
if( !willBalanceInvoice ) {
Y.doccirrus.api.activity
.transitionActivity( {
activity: res,
transitionDescription: transition,
letMeHandleErrors: true,
isTest: true
} );
}
}).then(function() {
if( !willBalanceInvoice ) {
res.notCreateNew = true;
return Y.doccirrus.api.activity
.transitionActivity( {
activity: res,
transitionDescription: transition,
letMeHandleErrors: true,
isTest: false
} ).then( function() {
var patientId = unwrap( currentPatient._id() );
if( patientId ) {
caseFolders.load( { patientId: patientId } );
}
});
}
});
}
}).fail( function( error ) {
Y.Array.invoke( Y.doccirrus.errorTable.getErrorsFromResponse( error ), 'display' );
} );
} | [
"function saveInvoiceNumber( itcb ) {\n // this step only applies to invoices\n if ( 'INVOICE' !== activity.actType && 'RECEIPT' !== activity.actType ) { return itcb( null ); }\n\n var\n setArgs = {\n 'content': activity.content,\n 'timestamp': activity.timestamp\n };\n\n if ( 'INVOICE' === activity.actType ) {\n setArgs.invoiceNo = activity.invoiceNo;\n mapFields.invoiceNo = activity.invoiceNo;\n mapFields.date = moment( activity.timestamp + '' ).format( 'DD.MM.YY' );\n }\n\n if ( Y.doccirrus.schemas.activity.isInvoiceCommunicationActType( activity.actType ) ) {\n setArgs.receiptNo = activity.receiptNo || '';\n mapFields.receiptNo = activity.receiptNo || '';\n mapFields.invoiceNo = activity.invoiceNo || '';\n mapFields.content = activity.content || '';\n mapFields.date = moment( activity.timestamp + '' ).format( 'DD.MM.YY' );\n }\n\n // NOTE: these always have a form, so reporting will be updated with these fields during the full\n // save when the PDF is complete.\n\n Y.doccirrus.mongodb.runDb( {\n user,\n action: 'update',\n model: 'activity',\n query: { _id: activity._id + '' },\n data: { $set: setArgs },\n options: { multi: false }\n }, itcb );\n }",
"onSaving() {\n if (this._saving) {\n this._saving.raise();\n }\n }",
"onSaved() {\n this.saved.raise();\n }",
"function continueSave() {\n notify(_L('Address successfully saved.'));\n $.customer_address.fireEvent('route', {\n page : 'addresses'\n });\n}",
"finishSave() {\n }",
"function saveClicked() {\n _save(false);\n }",
"onSaved() {\n if (this._saved) {\n this._saved.raise();\n }\n }",
"function doSave() {\n //This is a new 'virtual object' that has not been persisted\n // yet.\n if (!domainObject.getModel().persisted){\n return getParent(domainObject)\n .then(doWizardSave)\n .then(persistObject)\n .then(getParent)//Parent may have changed based\n // on user selection\n .then(locateObjectInParent)\n .then(persistObject)\n .then(function(){\n return fetchObject(domainObject.getId());\n })\n .catch(doNothing);\n } else {\n return domainObject.getCapability(\"editor\").save()\n .then(resolveWith(domainObject.getOriginalObject()));\n }\n }",
"async save() {\n const transaction = this.openmct.objects.getActiveTransaction();\n await transaction.commit();\n this.editing = false;\n this.emit('isEditing', false);\n this.openmct.objects.endTransaction();\n }",
"handleSave() {\n this.showLoadingSpinner = true;\n //Set ScheduleC Doc Complete if no value is entered in Line 12 and ScheduleC\n if ((this.objInputFields.dLine12 === null || this.objInputFields.dLine12 === undefined) &&\n (this.dLine3Total === 0) && (this.dLine31Total === 0)) {\n this.objInputFields.bScheduleCDocComplete = true;\n }\n this.objInputFields.idCareApp = this.idCareApp;\n this.objInputFields.idCareHouseholdDetail = this.idHouseholdMember;\n this.objInputFields.idCareHouseholdmemberIncome = this.idMemberIncome;\n this.objInputFields.dDiscountLength = this.dDiscountLength;\n this.objInputFields.sIncomeSourceType = this.sIncomeSource;\n this.objInputFields.sDocumentType = this.sDocumentType;\n this.objInputFields.sFormType = this.sFormType;\n this.objInputFields.listHouseholdMemberIncomeC = this.scheduleCList;\n\n saveHouseholdIncome({\n objWrapperFormInput: this.objInputFields\n })\n .then(result => {\n if (result) {\n this.showToastMessage(this.label.SuccessHeader, this.label.IncomeDocSuccessMsg, 'success');\n this.refreshData(); //refresh document section \n this.showLoadingSpinner = false;\n this.refreshIncomeInfo(); //refresh Parent income info section \n } else {\n this.showToastMessage(this.label.ErrorHeader, this.label.TransactionErrorMsg, 'error');\n this.showLoadingSpinner = false;\n console.log('error' + error);\n }\n })\n .catch(error => {\n this.showToastMessage(this.label.SuccessHeader, this.label.TransactionErrorMsg, 'error');\n this.showLoadingSpinner = false;\n });\n }",
"function onSave() {\n\tdispatcher.on(\"closeAdd\", function onCloseAdd() {\n\t\tdispatcher.off(\"closeAdd\", onCloseAdd);\n\t\tanimateClose();\n\t});\n\tvar eventStr = \"saveAlarm\";\n\tif (isEdit) {\n\t\teventStr = \"updateAlarm\";\n\t}\n\tmainCont.trigger(eventStr, {\n\t\tlabel : label,\n\t\tsnooze : snooze,\n\t\tduration : duration,\n\t\tvibration : vibration,\n\t\tsounds : sounds,\n\t\tshuffle : shuffle,\n\t\tisEdit : isEdit,\n\t});\n}",
"function saveDraft() {\n showNotification('The draft is saved.');\n draftIsSaved = true;\n}",
"function saveItem() {\n\t\t\t// here's some code for that\n\t\t}",
"function onInvoiceApproved() {\n\n Y.log('invoice approved, loading new invoice number...', 'debug', NAME);\n\n function onActivityReloaded(err, data) {\n if (err || !data) {\n Y.log('Could not load new invoice number of approved activity: ' + currentActivity._id, 'warn', NAME);\n return;\n }\n\n data = data.data ? data.data : data;\n\n Y.log('New invoice number: ' + data[0].invoiceNo, 'debug', NAME);\n\n // this may be a quotation, which would not have an invoice number\n\n mapData = {\n 'invoiceNo': (data[0].invoiceNo || ''),\n 'date': _moment( data[0].timestamp ).format( 'DD.MM.YY' )\n };\n\n // update the loaded form, do not rerender yet, doing so uses settimeout which breaks event order\n template.map(mapData, false, onMapInvoiceNo );\n }\n\n function onMapInvoiceNo(err) {\n if (err) {\n Y.log('Could not map invoice number: ' + JSON.stringify(err), 'warn', NAME);\n }\n\n context.attachments.updateFormDoc( context, template, onFormDocUpdated );\n }\n\n function onFormDocUpdated(err) {\n if (err) {\n Y.log('Could not update form document: ' + currentActivity._id, 'warn', NAME);\n return;\n }\n\n template.render(onReRender);\n }\n\n function onReRender() {\n template.raise('mapcomplete', template.toDict());\n }\n\n var mapData;\n Y.doccirrus.comctl.privateGet('1/activity/' + _k.unwrap( currentActivity._id ), {}, onActivityReloaded);\n }",
"function onInvoiceSave(doc) {\n //getLineItems, it will have delete, inserted and noChange, and updated\n //user should make a query to find required values\n\n\n var invoice = {no:12, lineitems:[\n {deliveryid:\"xxx\"},\n {delivery:\"yyyyy\"},\n {_id:\"l11\", deliveryid:\"xxxx\"},\n {_id:\"xxx\", __type__:\"delete\"}\n ]}\n\n var requiredREsult = [\n {deliveryid:\"xxx\", productuid:{accountid:{account:\"cash\"}}},\n {_id:\"l11\", deliveryid:\"xxxx\", productid:{}}\n ]\n\n\n }",
"function assignAndSaveInvoiceNumber( itcb ) {\n Y.doccirrus.invoiceserverutils.assignAndSaveInvoiceNumber( user, activity, currState, itcb );\n }",
"function save() {\n\t\tsources.userFood.save({\n\t\t\tonSuccess: function(event) {\n\t\t\t\t$comp.hide();\n\t\t\t\tWAKL.qtyAddArea.setAndGotoQty();\n\t\t\t},\n\t\t\tonError: function(event) {\n\t\t\t\tcancel();\n\t\t\t\tWAKL.err.handler(event);\n\t\t\t}\n\t\t});\n\t}",
"updateCreatedInvoice(invoice) {\n this.createdInvoice = invoice;\n this.emit('change');\n }",
"function onSave() {\n const saveData = {\n id: new Date().getTime(),\n hospitalName,\n doctorName,\n reason,\n doctorStatement,\n dateOfVisit: dateOfVisit.getTime(),\n medication,\n };\n props.addVisit(saveData);\n Realm.write(() => {\n const visitInfo = Realm.create('Visit', saveData);\n console.log(`Data written successfully ${visitInfo}`);\n props.navigation.goBack();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize the map of all resources in JSON | entitiesToJSON(){
let res = {
"id": this.id,
"resources": {}
};
(this.entitiesByID||{})::entries().forEach(([id,obj]) => res.resources[id] = (obj instanceof Resource) ? obj.toJSON(): obj);
return res;
} | [
"toJSON(depth = 0, initDepth = depth){\n\n /**\n * Converts a resource object into serializable JSON.\n * May fail to serialize recursive objects which are not instances of Resource\n * @param value - resource object\n * @param depth - depth of nested resources to output\n * @param initDepth - initial depth of nested resources used in a recursive call to compute the remaining depth\n * @returns {*} JSON object without circular references *\n */\n function valueToJSON(value, depth, initDepth) { return (value instanceof Resource)? ((depth > 0)? value.toJSON(depth - 1, initDepth): value.id): value.id? value.id: value }\n\n /**\n * Serializes field value: array or object\n * @param value - resource field value\n * @param depth - depth of nested resources to output\n * @param initDepth - initial depth of nested resources used in a recursive call to compute the remaining depth\n * @returns {*} JSON object or an array of JSON objects without circular references\n */\n function fieldToJSON(value, depth, initDepth) { return value::isArray()? value.filter(e => !!e).map(e => valueToJSON(e, depth, initDepth)): valueToJSON(value, depth, initDepth); }\n\n let omitKeys = this::keys()::difference(this.constructor.Model.fieldNames).concat([\"viewObjects\", \"infoFields\", \"labels\"]);\n let res = {};\n this::keys().filter(key => !!this[key] && !omitKeys.includes(key)).forEach(key => {\n let fieldDepth = (key === \"border\" || key === \"borders\")? initDepth: depth;\n res[key] = fieldToJSON(this[key], fieldDepth, initDepth);\n });\n return res;\n }",
"function serializeMap(map) {\n\t\t\t\tif (map === null || map === undefined) return null;\n\n\t\t\t\tvar meta = {\n\t\t\t\t\tgeometries: {},\n\t\t\t\t\tmaterials: {},\n\t\t\t\t\ttextures: {},\n\t\t\t\t\timages: {}\n\t\t\t\t};\n\n\t\t\t\tvar json = map.toJSON(meta);\n\t\t\t\tvar images = extractFromCache(meta.images);\n\t\t\t\tif (images.length > 0) json.images = images;\n\t\t\t\tjson.sourceFile = map.sourceFile;\n\n\t\t\t\treturn json;\n\t\t\t}",
"function serializeMap( map ) {\n\n\t\t\tif ( map === null || map === undefined ) return null;\n\n\t\t\tconst meta = {\n\t\t\t\tgeometries: {},\n\t\t\t\tmaterials: {},\n\t\t\t\ttextures: {},\n\t\t\t\timages: {}\n\t\t\t};\n\n\t\t\tconst json = map.toJSON( meta );\n\t\t\tconst images = extractFromCache( meta.images );\n\t\t\tif ( images.length > 0 ) json.images = images;\n\t\t\tjson.sourceFile = map.sourceFile;\n\n\t\t\treturn json;\n\n\t\t}",
"serializeJSON() {\n\n let nodes = [];\n let serializer = new SceneSerializer();\n\n for (let child of this.children) {\n child.walkAll(function (node) {\n nodes.push(node.serializeJSON(serializer));\n });\n }\n\n let resources = serializer.resources.map(x => x[0].name +\";\" + x[1]);\n\n return {\n background: Serialize.color(this.background),\n ambientColor: Serialize.color(this.ambientColor),\n\n fogEnabled: this.fogEnabled,\n fogMode: this.fogMode,\n fogColor: Serialize.color(this.fogColor),\n fogStart: this.fogStart,\n fogDistance: this.fogDistance,\n\n resources: resources,\n nodes: nodes,\n };\n }",
"function serializeMap(map) {\r\n\t\t\t\tif (map === null || map === undefined) return null;\r\n\r\n\t\t\t\tvar meta = {\r\n\t\t\t\t\tgeometries: {},\r\n\t\t\t\t\tmaterials: {},\r\n\t\t\t\t\ttextures: {},\r\n\t\t\t\t\timages: {}\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar json = map.toJSON(meta);\r\n\t\t\t\tvar images = extractFromCache(meta.images);\r\n\t\t\t\tif (images.length > 0) json.images = images;\r\n\t\t\t\tjson.sourceFile = map.sourceFile;\r\n\r\n\t\t\t\treturn json;\r\n\t\t\t}",
"function serializeMap(map) {\n if (map === null || map === undefined) return null;\n\n var meta = {\n geometries: {},\n materials: {},\n textures: {},\n images: {}\n };\n\n var json = map.toJSON(meta);\n var images = extractFromCache(meta.images);\n if (images.length > 0) json.images = images;\n json.sourceFile = map.sourceFile;\n\n return json;\n }",
"toJson() {\n const map = {\n concepts: [],\n propositions: []\n };\n // Efforts to avoid id collisions - not sure whether necessary :/\n const ids = new Set();\n const conceptIDs = new Map();\n this.concepts.forEach(c => {\n let id = this.getID();\n while (ids.has(id)) {\n id = this.getID();\n }\n ids.add(id);\n conceptIDs.set(c, id);\n map.concepts.push({ text: c.text, x: c.x, y: c.y, id: id, resources: c.resources });\n });\n this.propositions.forEach(p => {\n map.propositions.push({\n text: p.text,\n from: conceptIDs.get(p.from),\n to: conceptIDs.get(p.to)\n });\n });\n return JSON.stringify(map);\n }",
"getAllResources() {\n return Object.values(this._resources);\n }",
"function serializeMap(map) {\n\t if (map === null || map === undefined) return null;\n\t var meta = {\n\t geometries: {},\n\t materials: {},\n\t textures: {},\n\t images: {}\n\t };\n\t var json = map.toJSON(meta);\n\t var images = extractFromCache(meta.images);\n\t if (images.length > 0) json.images = images;\n\t json.sourceFile = map.sourceFile;\n\t return json;\n\t } // Note: The function 'extractFromCache' is copied from Object3D.toJSON()",
"get resources() {\n return this._resource.copy();\n }",
"function serializeResource(resource, api) {\n var resourceJson = {};\n if (resource.description())\n resourceJson[\"description\"] = \"\" + resource.description().value();\n if (resource.relativeUri()) {\n resourceJson[\"relativeUri\"] = \"\" + resource.relativeUri().value();\n }\n if (resource.relativeUri()) {\n var relativeUriPathSegments = resource.relativeUri().value().split('/');\n var segments = relativeUriPathSegments.splice(1, relativeUriPathSegments.length);\n if (segments) {\n var pathSegments = [];\n for (var s = 0; s < segments.length; s++) {\n if (segments[s] != \"\")\n pathSegments.push(segments[s]);\n }\n resourceJson[\"relativeUriPathSegments\"] = pathSegments;\n }\n }\n serializeNodeDisplayName(resource, resourceJson);\n if (resource.type()) {\n serializeTypeProperty(resource.type(), resourceJson);\n }\n if (resource.is()) {\n if (resource.is().length > 0) {\n var values = [];\n for (var k = 0; k < resource.is().length; k++) {\n var is = resource.is()[k].value();\n var traitParameters = {};\n is.toHighLevel().attrs().forEach(function (attribute) {\n if (isKeyAttribute(attribute))\n return;\n traitParameters[\"\" + attribute.name()] = \"\" + attribute.value();\n });\n if (Object.keys(traitParameters).length > 0) {\n var isJson = {};\n isJson[\"\" + is.valueName()] = traitParameters;\n values.push(isJson);\n }\n else\n values.push(is.valueName());\n }\n resourceJson[\"is\"] = values;\n }\n }\n if (resource.securedBy()) {\n var values = [];\n if (resource.securedBy().length > 0) {\n resource.securedBy().forEach(function (x) {\n if (x.value().valueName() == \"null\" || x.value().valueName() == null)\n values.push(null);\n else\n values.push(\"\" + x.value().valueName());\n });\n resourceJson[\"securedBy\"] = values;\n }\n }\n var params = serializeParameters(resource.allUriParameters(), 'uriParameters');\n if (Object.keys(params).length > 0) {\n resourceJson[\"uriParameters\"] = params;\n }\n //var baseUriParams = serializeParameters(resource.baseUriParameters(),\"uriParameters\");\n //if (Object.keys(baseUriParams).length > 0){\n // resourceJson[\"baseUriParameters\"] = baseUriParams;\n //}\n //else{\n // var isBaseUriParams = isDefined(resource, 'baseUriParameters');\n // if (isBaseUriParams) {\n // resourceJson[\"baseUriParameters\"] = null ;\n // }\n //}\n serializeBaseUriParameters(resource, resourceJson);\n if (resource.methods().length > 0) {\n resourceJson[\"methods\"] = serializeActions(resource.methods(), api, true);\n }\n if (resource.resources().length > 0) {\n resourceJson[\"resources\"] = serializeResources(resource.resources(), api);\n }\n return resourceJson;\n}",
"function JsonGenerate(rootJson) {\n //console.log(rootJson['resources'][0]['methods'][0]['securedBy'][0]['settings']['scopes'])\n\n for (var i in rootJson['resources']) {\n\tif (debug) console.error('top resource '+i+': '+rootJson['resources'][i]);\n\tresource = rootJson['resources'][i];\n\tResource(resource);\n }\n\n console.log(JSON.stringify(scopeMap));\n}",
"serialize() {\n let data = {};\n\n // save area's metadata\n data = Object.assign(data, {\n title: this.title,\n script: this.script,\n metadata: this.metadata\n });\n\n // serialize rooms\n if (this.rooms instanceof Map) {\n for (let [ id, room ] of this.rooms) {\n // serialize each room\n data[id] = room.serialize();\n }\n }\n\n // serialize behaviors\n let behaviors = {};\n for (const [key, val] of this.behaviors) {\n // serialize each behavior\n behaviors[key] = val;\n }\n data.behaviors = behaviors;\n\n return data;\n }",
"get resources() {\n return this.getListAttribute('resources');\n }",
"async write_resources(file, resources) {\n const file_content = _.map(resources, resource => JSON.stringify(resource)).join('\\n');\n await fs.promises.writeFile(file, file_content);\n }",
"renderResources(){\n let rsc = []\n for(let key in this.resources){\n rsc.push(`${key}: ${this.resources[key]}<br> `)\n }\n return rsc.map(e => e).join('')\n }",
"static populateResources(resources) {\n let result = {};\n _.each(resources, (resource, name) => {\n // Only include the resource if it's NOT disabled\n if (!resource.disable) {\n delete resource.disable;\n let config = {};\n _.extend(config, resource);\n result[name] = { config: config };\n }\n });\n return result;\n }",
"toJSON() {\n\n var json = {\n name: this.name,\n content: this.content,\n contentType: this.contentType\n };\n\n if (this.contentId) {\n json.contentId = this.contentId;\n }\n \n if (this.customHeaders.length > 0) {\n var _ch = [];\n this.customHeaders.forEach(element => { \n _ch.push(toCustomHeader.convert(element).toJSON()); \n });\n json.customHeaders = _ch; \n } \n \n return json;\n }",
"getAll() {\n return this._resources !== undefined ? _.map(this._resources, resource => resource) : this._loadAll();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Byteswap an arbitrary buffer, flipping from one endian to the other, returning a new buffer with the resultant data | function byteswap64(buf) {
var swap = Buffer.alloc(buf.length);
for (var i = 0; i < buf.length; i++) {
swap[i] = buf[buf.length -1 - i];
}
return swap;
} | [
"function byteswap64(buf) {\n var swap = new Buffer(buf.length);\n for (var i = 0; i < buf.length; i++) {\n swap[i] = buf[buf.length -1 - i];\n }\n return swap;\n}",
"function to_little_endian(){\n\tbinary_input.reverse();\n\tbinary_key.reverse();\n}",
"function _swapEndian(val, length) {\n if (length <= 8) {\n return val\n } else if (length <= 16) {\n return (val & 0xFF00) >> 8 | (val & 0xFF) << 8\n } else if (length <= 32) {\n return ((val & 0xFF000000) >> 24 |\n (val & 0x00FF0000) >> 8 |\n (val & 0x0000FF00) << 8 |\n (val & 0x000000FF) << 24)\n }\n throw new Error('Cannot swap endianness for length ' + length)\n}",
"function _reverseBuffer(buffer) {\n var tmp, len = buffer.length - 1, half = Math.floor(buffer.length / 2);\n for (var i = len; i >= half; i--) {\n tmp = buffer[i];\n buffer[i] = buffer[len - i];\n buffer[len - i] = tmp;\n }\n }",
"function flipEndianness( array, chunkSize ) {\n\n \t\t\tvar u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );\n \t\t\tfor ( var i = 0; i < array.byteLength; i += chunkSize ) {\n\n \t\t\t\tfor ( var j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {\n\n \t\t\t\t\tvar tmp = u8[ k ];\n \t\t\t\t\tu8[ k ] = u8[ j ];\n \t\t\t\t\tu8[ j ] = tmp;\n\n \t\t\t\t}\n\n \t\t\t}\n\n \t\t\treturn array;\n\n \t\t}",
"reverseBits(buf) {\n for (let x = 0; x < buf.length; x++) {\n let newByte = 0;\n newByte += buf[x] & 128 ? 1 : 0;\n newByte += buf[x] & 64 ? 2 : 0;\n newByte += buf[x] & 32 ? 4 : 0;\n newByte += buf[x] & 16 ? 8 : 0;\n newByte += buf[x] & 8 ? 16 : 0;\n newByte += buf[x] & 4 ? 32 : 0;\n newByte += buf[x] & 2 ? 64 : 0;\n newByte += buf[x] & 1 ? 128 : 0;\n buf[x] = newByte;\n }\n }",
"function flipEndianness( array, chunkSize ) {\n\n\t\t\tvar u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );\n\t\t\tfor ( var i = 0; i < array.byteLength; i += chunkSize ) {\n\n\t\t\t\tfor ( var j = i + chunkSize - 1, k = i; j > k; j--, k++ ) {\n\t\t\t\t\tvar tmp = u8[ k ];\n\t\t\t\t\tu8[ k ] = u8[ j ];\n\t\t\t\t\tu8[ j ] = tmp;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn array;\n\t\t}",
"function swap32(b) {\n return ((b & 0xff) << 24)\n | ((b & 0xff00) << 8)\n | ((b >> 8) & 0xff00)\n | ((b >> 24) & 0xff);\n }",
"function endianSwap(hexStr, lengthInBytes)\n{\n while (hexStr.length < 2 * lengthInBytes)\n {\n\thexStr = '0' + hexStr;\n }\n if (hexStr.length >= 4)\n\thexStr = hexStr.substring(2, 4) + hexStr.substring(0, 2);\n if (hexStr.length >= 8)\n\thexStr = hexStr.substring(6, 8) + hexStr.substring(4, 6);\n if (hexStr.length >= 12)\n\tlogger.warn(\"endianSwap() not implemented for 12 bytes\");\n return hexStr.toUpperCase();\n}",
"function byteSwap16(val) {\n return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF);\n }",
"reverseBytes() {\n\t\t//region Reverse bits order in each byte in the stream\n\t\tfor (let i = 0; i < this.view.length; i++) {\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[i] = (this.view[i] * 0x0802 & 0x22110 | this.view[i] * 0x8020 & 0x88440) * 0x10101 >> 16;\n\t\t}\n\t\t//endregion\n\n\t\t//region Shift \"most significant\" byte\n\t\tif (this.bitsCount % 8) {\n\t\t\t// noinspection ConditionalExpressionJS\n\t\t\tconst currentLength = (this.bitsCount >> 3) + (this.bitsCount % 8 ? 1 : 0);\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[this.view.length - currentLength] >>= 8 - (this.bitsCount & 0x07);\n\t\t}\n\t\t//endregion\n\t}",
"reverseBytes()\n\t{\n\t\t//region Reverse bits order in each byte in the stream\n\t\tfor(let i = 0; i < this.view.length; i++)\n\t\t{\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[i] = ((this.view[i] * 0x0802 & 0x22110) | (this.view[i] * 0x8020 & 0x88440)) * 0x10101 >> 16;\n\t\t}\n\t\t//endregion\n\t\t\n\t\t//region Shift \"most significant\" byte\n\t\tif(this.bitsCount % 8)\n\t\t{\n\t\t\t// noinspection ConditionalExpressionJS\n\t\t\tconst currentLength = (this.bitsCount >> 3) + ((this.bitsCount % 8) ? 1 : 0);\n\t\t\t// noinspection MagicNumberJS, NonShortCircuitBooleanExpressionJS\n\t\t\tthis.view[this.view.length - currentLength] >>= (8 - (this.bitsCount & 0x07));\n\t\t}\n\t\t//endregion\n\t}",
"function swapBuffers() {\n swapReprojectBuffer();\n swapGBuffer();\n swapHdrBuffer();\n }",
"function invert_endian(a, inpl) {\n var t = inpl ? a : Array(a.length);\n for (var i = 0; i < a.length; ++i) {\n\tvar t1 = (a[i] & 0xff) << 24;\n\tvar t2 = ((a[i] >> 8) & 0xff) << 16;\n\tvar t3 = ((a[i] >> 16) & 0xff) << 8;\n\tvar t4 = (a[i] >> 24) & 0xff;\n\tt[i] = t1 | t2 | t3 | t4;\n }\n return t;\n}",
"converseToBuffer(): Buffer {\n const bign = this._bn.toArrayLike(Buffer);\n if (bign.length === 32) {\n return bign;\n }\n\n const zeroPad = Buffer.alloc(32);\n bign.copy(zeroPad, 32 - bign.length);\n return zeroPad;\n }",
"function reverse (buffer, target) {\n validate(buffer);\n\n if (target) {\n validate(target);\n copy(buffer, target);\n }\n else {\n target = buffer;\n }\n\n for (var i = 0, c = target.numberOfChannels; i < c; ++i) {\n target.getChannelData(i).reverse();\n }\n\n return target;\n}",
"function swapEndianC(string){\n var data = \"\";\n for (var i = 1; i <= string.length; i++){\n data += string.substr(0 - i, 1);\n }\n return data;\n}",
"get endian()\n {\n\t\tvar b = new ArrayBuffer(4);\n\t\tvar a = new Uint32Array(b);\n\t\tvar c = new Uint8Array(b);\n\t\ta[0] = 0xdeadbeef;\n\t\tif (c[0] === 0xef) return Endian.LITTLE_ENDIAN;\n\t\tif (c[0] === 0xde) return Endian.BIG_ENDIAN;\n }",
"function swapEndianC(string) {\n var data = \"\";\n for (var i = 1; i <= string.length; i++) {\n data += string.substr(0 - i, 1);\n }\n return data;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the selected values are allowed, IE we have resources named after it | function check_allowed() {
var material = $(select_div+" "+"#pd-material-type").find("option[selected]").attr("value");
var material_dict = get_material_dict(data, material);
var allowed = material_dict.allowed;
for(var i = 0; i < allowed.length; i++) {
var good = true;
var chem = allowed[i];
for(var j = 0; j < elements_nums.length; j++) {
if(chem[elements_nums[0]] != elements_nums[1]){
good = false;
break;
}
}
if(good){
return true
}
}
return false
} | [
"function validation_for_select_boxes(element){\n\tif(element.value != \"Default\")\n\t\treturn true;\n\telse{\n\t\talert(\"please select \"+ element.name);\n\t\treturn false;\n\t}\n}",
"function requireSelects ( form, requiredSelect ) {\n for ( var i = 0; i < requiredSelect.length; i++ ) {\n element = requiredSelect[i];\n if ( form[element].selectedIndex <= 0 ) {\n alert( \"Please select a value for \" + element + \".\" );\n return false;\n }\n }\n return true;\n}",
"function validateSelect(select) {\n var selectedValue = getSelectedValue(select);\n return (typeof(selectedValue) == 'string' && selectedValue != '') ? true : false;\n}",
"function getOptionsVisibilityRuleValues() {\n return [\"alfresco/forms/controls/Select\",\"alfresco/forms/controls/RadioButtons\"];\n}",
"function validate_selectionList( selList_element )\n{\n var isOk = false;\n for (var i = 0; i < selList_element.length; i++)\n {\n if (selList_element[i].selected)\n {\n isOk = true;\n break;\n }\n }\n return isOk;\n}",
"function isValidDropDownListSelection(element)\n {\n var isValidDDLSelection = false;\n try {\n if (parseInt(element.val(), 10) != -1) {\n isValidDDLSelection = true;\n }\n }\n catch (exception)\n {\n isValidDDLSelection = true; // means a wording selection on ddl\n } \n return isValidDDLSelection;\n }",
"function enableSelectorItems(validValuesRange, selector) {\n for (var i = 0; i < selector.options.length; ++i) {\n if (($.grep(validValuesRange, function (e) {\n return e == selector.options[i].innerText;\n }).length) != 0) {\n selector[i].style.color = \"Black\";\n selector[i].disabled = false;\n } else {\n selector[i].style.color = \"LightGrey\";\n selector[i].disabled = true;\n }\n }\n var selectedStr = selector[selector.selectedIndex].innerText;\n if (($.grep(validValuesRange, function (e) {\n return e == selectedStr;\n }).length) == 0) {\n selector.selectedIndex = 0;\n // we should call this functions to update controls\n // as programmaticality change selector's value not cause change event\n executionInstructionChanged(null);\n orderDurationChanged(null);\n }\n}",
"function validateSelects(formObj){\r\n\tvSSResult = true;\r\n\tfor(vSSCounter=1; vSSCounter<arguments.length; vSSCounter++){\r\n\t\tvSSObj = formObj[arguments[vSSCounter]];\r\n\t\tif( vSSObj && vSSObj.selectedIndex == 0 ){\r\n\t\t\talert( \"Please choose another option from '\" +convertVariable(vSSObj.name)+ \"'\" );\r\n\t\t\tvSSObj.focus();\r\n\t\t\tvSSResult = false;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn vSSResult;\r\n}",
"function checkRestrictedFields(q) {\n\t\tvar attemptedSet = ' ';\n\t\tvar unmodifiable = sncStdChg.unmodifiable;\n\t\tif (q && unmodifiable) {\n\t\t\tfor (var i = 0; i < q.names.length; i++) {\n\t\t\t\tvar f = q.names[i];\n\t\t\t\tvar idx = containsName(unmodifiable, f);\n\t\t\t\tif (idx !== -1)\n\t\t\t\t\tattemptedSet = attemptedSet + unmodifiable[idx].label + ', ';\n\t\t\t}\n\t\t}\n\t\tif (attemptedSet !== ' ') {\n\t\t\tvar msg = formatMessage(getMessage('The following \"Change Request values\" are not allowed to be set in a template:{0}'), attemptedSet.substring(0, attemptedSet.length - 2));\n\t\t\talert(msg);\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}",
"function validatePersonSupportSelection(){\n\tvar msg='';\n\tif($('#personId').val() == ''){\n\t\tmsg += 'You must select a person from the dropdown.';\n\t}\n\tif($('#supportRole').val() == ''){\n\t\tmsg += 'You must select a support role from the dropdown.';\n\t}\n\tif(msg != ''){\n\t\talert(msg);\n\t\treturn false;\n\t}else{\n\t\treturn true;\n\t}\n}",
"function test_ownership_dropdown_values() {}",
"requiredSelect(val) {\n const typeOfValue = typeof val;\n let value;\n switch (typeOfValue) {\n case 'string':\n value = val.replace(/^\\s+|\\s+$/g, '');\n return !(value === '-1' || value === '');\n\n case 'number':\n return val !== -1;\n\n default:\n return false;\n }\n }",
"isSelectionValid(selection) {\n return selection === null\n || (this.virtDir && selection.hasOwnProperty('value') && selection.hasOwnProperty('index'))\n || (selection instanceof IgxDropDownItemComponent && !selection.isHeader);\n }",
"function validateSelections()\n {\n var isValid = false;\n \n isValid = validateDDLsOnProductSearch($('#selectCategory'), 'product category');\n isValid = isValid == true ? validateDDLsOnProductSearch($('#selectCondition'), 'product condition') : isValid;\n isValid = isValid == true ? validateDDLsOnProductSearch($('#selectBrand'), 'brand') : isValid;\n isValid = isValid == true ? validateDDLsOnProductSearch($('#selectModel'), 'model') : isValid;\n \n return isValid;\n }",
"function restrictResources(uncheck){\n\t\tvar selectedLocation=getSelectedLocation(),\n\t\trows=$(\"#resourceTable\").find(\"td[data-restrict]\");\n\t\trows.find(\"input\").attr({\"disabled\": true});\n\t\tif(uncheck){\n\t\t\trows.find(\"input\").attr({\"checked\": false});\n\t\t}\n\t\t$.each(rows, function(i, val){\n\t\t\tvar restrict=$(val).data(\"restrict\");\n\t\t\tif(restrict.length > 1){\n\t\t\t\tif ($.inArray(selectedLocation, restrict.replace(/,\\s+/g, ',').split(',')) >= 0) {\n\t\t\t\t\t$(val).find(\"input\").attr({\"disabled\": false});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function validateForm() {\n let validCandidates = 0;\n optionNames.forEach((e) => {\n if (e !== null || e !== undefined || e !== \"\") validCandidates += 1;\n });\n return validCandidates >= 2;\n }",
"function validate_form_multiple_csv_essources(){\n console.log(\"validate_form_multiple_csv_essources()\");\n\n var err = false; \n existing_categories_csv_text = $(\"#existing_categories_csv :selected\").text();\n //if( existing_categories_csv_text.includes(\"cat_id\")){ unsupported by IE\n if( existing_categories_csv_text.indexOf(\"cat_id\") !== -1){\n console.log(\"ok. cat_id exists.\");\n } else {\n console.log(\"BAD. cat_id does not exist.\");\n //colour dropdown box\n $(\"#existing_categories_csv\").css('background-color', 'yellow');\n err = true; \n\t}\n\n //check if global array of files is empty\n console.log(csv_values.length);\n if(csv_values.length == 0){\n console.log(\"no file loaded or file empty.\");\n $(\"#label_filename\").css('background-color', 'yellow');\n err = true;\n }\n\n if(err){alert(\"Sorry some fields not filled.\");\n return \"no\";\n } else {return \"ok\";}\n \n}",
"function hasSelectedValue(object, value)\n{\n\tvalue = trim(value);\n\tif ((value.length == 0) || (value == '-136'))\n\t\treturn false;\n\n\treturn true;\n}",
"function ValidateSel( Inp, name, def=-1 )\n {\n var val = Inp.val();\n\n var sErr = \"\";\n if( val == null ) sErr = \"Debe seleccionar \";\n else if( val == def ) sErr = \"Debe cambiar \";\n else return true;\n\n alert( sErr + name );\n Inp.focus();\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if this relates to the active query being executed then immediately send the cancel, else the query can be removed from the queue and never submitted to the driver. | function cancel (notify, callback) {
const qid = notify.getQueryId()
if (workQueue.length() === 0) {
setImmediate(() => {
callback(new Error(`Error: [msnodesql] cannot cancel query (empty queue) id ${qid}`))
})
return
}
const first = workQueue.first((_idx, currentItem) => {
if (currentItem.commandType !== driverCommandEnum.QUERY) {
return false
}
const args = currentItem.args
const not = args[0]
const currentQueryId = not.getQueryId()
return qid === currentQueryId
})
if (first) {
if (first.paused) {
execCancel(qid, first, () => {
freeStatement(notify, () => {
workQueue.dropItem(first)
callback(null)
})
})
} else {
execCancel(qid, first, callback)
}
} else {
setImmediate(() => {
callback(new Error(`Error: [msnodesql] cannot cancel query (not found) id ${qid}`))
})
}
} | [
"function cancelQuery() {\n// console.log(\"Cancelling query, currentQuery: \" + qwQueryService.currentQueryRequest);\n if (qwQueryService.currentQueryRequest != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(qwQueryService.currentQueryRequest);\n queryInFly && queryInFly.canceler(\"test\");\n\n //\n // also submit a new query to delete the running query on the server\n //\n\n var query = 'delete from system:active_requests where clientContextID = \"' +\n qwQueryService.currentQueryRequestID + '\";';\n\n// console.log(\" queryInFly: \" + queryInFly + \"\\n query: \" + query);\n\n executeQueryUtil(query,false)\n\n// .success(function(data, status, headers, config) {\n// console.log(\"Success cancelling query.\");\n// console.log(\" Data: \" + JSON.stringify(data));\n// console.log(\" Status: \" + JSON.stringify(status));\n// })\n\n\n // sanity check - if there was an error put a message in the console.\n .error(function(data, status, headers, config) {\n console.log(\"Error cancelling query.\");\n console.log(\" Data: \" + JSON.stringify(data));\n console.log(\" Status: \" + JSON.stringify(status));\n });\n\n }\n }",
"function cancelQuery(queryResult) {\n // if this is a batch query, with multiple child queries, we need to find which one\n // is currently running, and cancel that.\n if (queryResult.batch_results)\n for (i=0; i<queryResult.batch_results.length; i++) if (queryResult.batch_results[i].busy) {\n queryResult = queryResult.batch_results[i]; // cancel this child\n break;\n }\n\n //console.log(\"Cancelling query, currentQuery: \" + queryResult.client_context_id);\n if (queryResult && queryResult.client_context_id != null) {\n var queryInFly = mnPendingQueryKeeper.getQueryInFly(queryResult.client_context_id);\n queryInFly && queryInFly.canceler(\"test\");\n\n //\n // also submit a new query to delete the running query on the server\n //\n\n var query = 'delete from system:active_requests where clientContextID = \"' +\n queryResult.client_context_id + '\";';\n\n executeQueryUtil(query,false)\n\n .then(function success() {\n// console.log(\"Success cancelling query.\");\n },\n\n // sanity check - if there was an error put a message in the console.\n function error(resp) {\n logWorkbenchError(\"Error cancelling query: \" + JSON.stringify(resp));\n// console.log(\"Error cancelling query.\");\n });\n\n }\n }",
"cancelQuery()\t{ this._behavior('cancel query'); }",
"function cancelQuery() {\n if (!timer) return;\n\n clearTimeout(timer);\n timer = null;\n }",
"cancel() {\n this.end();\n queryManager.cancelQuery(this);\n return this;\n }",
"cancelExecution(queryToken) {}",
"cancel(req, err) {\n\t\tif (typeof req === 'object') {\n\t\t\treq = req.request_id; // unwrap request\n\t\t}\n\t\terr = wrap_error(err, 'user cancelled');\n\t\tconst query = this.req_map[req];\n\t\tif (!query) return;\n\t\tthis.reject_query(query, err);\n\t\tthis.schedule_idle();\n\t\treturn query.sent;\n\t}",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"function cancel() {\n\t /**\n\t We need to check both Running and Cancelled status\n\t Tasks can be Cancelled but still Running\n\t **/\n\t if (iterator._isRunning && !iterator._isCancelled) {\n\t iterator._isCancelled = true;\n\t taskQueue.cancelAll();\n\t /**\n\t Ending with a Never result will propagate the Cancellation to all joiners\n\t **/\n\n\t end(TASK_CANCEL);\n\t }\n\t }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"abort () {\n while (this.length > 0) {\n const dial = this._queue.shift()\n dial.callback(DIAL_ABORTED())\n }\n this.stop()\n }",
"function cancel() {\n\t /**\n\t We need to check both Running and Cancelled status\n\t Tasks can be Cancelled but still Running\n\t **/\n\t if (iterator._isRunning && !iterator._isCancelled) {\n\t iterator._isCancelled = true;\n\t taskQueue.cancelAll();\n\t /**\n\t Ending with a Never result will propagate the Cancellation to all joiners\n\t **/\n\t end(TASK_CANCEL);\n\t }\n\t }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n\n end(TASK_CANCEL);\n }\n }",
"function cancel() {\n /**\n We need to check both Running and Cancelled status\n Tasks can be Cancelled but still Running\n **/\n if (iterator._isRunning && !iterator._isCancelled) {\n iterator._isCancelled = true;\n taskQueue.cancelAll();\n /**\n Ending with a Never result will propagate the Cancellation to all joiners\n **/\n end(TASK_CANCEL);\n }\n }",
"cancel () {\r\n this.cancelRequested = true;\r\n this.append('Cancel requested.');\r\n if (this.state === 'waiting') {\r\n this.setState('cancelled');\r\n this.append('Job cancelled.');\r\n } else {\r\n state.port.postMessage({\r\n topic: 'cancel-job',\r\n data: {\r\n jobId: this.id,\r\n }\r\n }); \r\n } \r\n }",
"abort () {\n while (this.length > 0) {\n let dial = this._queue.shift()\n dial.callback(DIAL_ABORTED())\n }\n this.stop()\n }",
"abort() {\n while (this.length > 0) {\n let dial = this._queue.shift();\n\n dial.callback(DIAL_ABORTED());\n }\n\n this.stop();\n }",
"cancel() {\n if (this._activeSearch) {\n this._activeSearch.abort();\n }\n\n this._cancelSearch = true;\n later(() => (this._cancelSearch = false), 400);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns memory usage as a percentage of total memory available (0100) | function getMemUsage() {
var total = os.totalmem(),
usage = total - os.freemem(),
perc = usage / total * 100;
return {
usage : usage
, total : total
, percentage : perc
};
} | [
"function calcPhysicalMem()\n{\n\tvar os = require('os');\n\n\tvar totalm = (os.totalmem() / 1024 / 1024).toFixed(2);\n\tvar freem = (os.freemem() / 1024 / 1024).toFixed(2) ;\n\tvar usedm = (totalm - freem);\n\n\n\tmetrics[\"phys_mem_used\"].value = usedm;\n\tmetrics[\"phys_mem_free\"].value = freem;\n\tmetrics[\"phys_mem_usage\"].value = (100*usedm/totalm).toFixed(2);\n\n\n\toutput();\n}",
"function available_memory() {\n // var value = process.memoryUsage().heapUsed / 1000000;\n const percentageMemUsed = (os.freemem() / os.totalmem()) * 100.0\n return percentageMemUsed\n}",
"memoryStats() {\n const total = Math.round(osUtils.totalmem());\n const percentUse = Math.round(100 - (osUtils.freememPercentage() * 100));\n this.manager.logger.detail(`Memory stats checked - ${percentUse}% of ${total}MB used.`);\n return {percentUse, total};\n }",
"metricMemoryUtilization(props) {\n return this.metric('MemoryUtilization', props);\n }",
"metricMemoryUtilization(props) {\n return this.cannedMetric(ecs_canned_metrics_generated_1.ECSMetrics.memoryUtilizationAverage, props);\n }",
"function calculateBasedMem() {\n\t//var theForm = document.forms[\"capacity_form\"];\n var qtyAppNode = document.getElementById('qtyAppNode').value;\n var appNodeMem = document.getElementById('memNodeSize').value;\n var memPodSize = document.getElementById('memPodSize').value;\n var totalAppNodeMem = appNodeMem * qtyAppNode;\n var totalPodPerMem = totalAppNodeMem / memPodSize;\n return totalPodPerMem;\n\t//display the result\n //document.getElementById('ccapacity').innerHTML = \"Total pod por Mem: \"+totalPodPerMem;\n}",
"function getUsageLinux(cb) {\n // TODO: throw error\n if (!isFunction(cb)) { return; }\n\n function calcFree(data) {\n return (data[\"cached\"] + data[\"buffers\"] + data[\"memfree\"]) / data[\"memtotal\"];\n }\n\n function calcUsage(data) {\n return 1 - calcFree(data);\n }\n\n fs.readFile(\"/proc/meminfo\", function(err, data) {\n if (err) { return cb(err); }\n\n var meminfo = data.toString().split(\"\\n\");\n var data = {};\n\n for (var i in meminfo) {\n var line = meminfo[i].split(\":\");\n // Ignore invalid lines, if any\n if (line.length == 2) {\n data[line[0].trim().toLowerCase()] = parseInt(line[1].trim(), 10);\n }\n }\n\n cb(null, calcUsage(data) * 100);\n });\n}",
"function getTotalMemory(prof) {\n return d3.max(prof, function(d) { return d.memalloc; });\n }",
"function collectMemoryStats() {\n var memUsage = process.memoryUsage();\n metrics.gauge('memory.rss', memUsage.rss);\n metrics.gauge('memory.heapTotal', memUsage.heapTotal);\n metrics.gauge('memory.heapUsed', memUsage.heapUsed);\n metrics.increment('memory.statsReported');\n}",
"function getStats() {\n var procMem = process.memoryUsage();\n var stats = {\n mem: {\n total: os.totalmem(),\n free: os.freemem(),\n heap: procMem.rss\n },\n cpu: os.loadavg()\n };\n for(var i=0; i < stats.cpu.length; i++) {\n stats.cpu[i] = stats.cpu[i].toFixed(3);\n }\n stats.cpu = stats.cpu.join(\",\");\n // We convert from bytes to mb\n stats.mem.total = Math.ceil(stats.mem.total / 1000000) + \"MB\";\n stats.mem.free = Math.ceil(stats.mem.free / 1000000) + \"MB\";\n stats.mem.heap = (stats.mem.heap / 1000000).toFixed(3) + \"MB\";\n return stats;\n}",
"function getCpuUsage() {\n return cpu.getCpuUsage();\n}",
"function populateMemoryStatus(){\n settingsMemoryTotal.innerHTML = Number((os.totalmem()-1073741824)/1073741824).toFixed(1) + 'G'\n settingsMemoryAvail.innerHTML = Number(os.freemem()/1073741824).toFixed(1) + 'G'\n}",
"function populateMemoryStatus(){\n settingsMemoryTotal.innerHTML = Number((os.totalmem()-1000000000)/1000000000).toFixed(1) + 'G'\n settingsMemoryAvail.innerHTML = Number(os.freemem()/1000000000).toFixed(1) + 'G'\n}",
"function getUsageWin32(cb) {\n // TODO: throw error\n if (!isFunction(cb)) { return; }\n\n var wmicCommand = [\n \"wmic os get TotalVisibleMemorySize\",\n \"wmic os get FreePhysicalMemory\"\n ];\n\n function calcUsage(data) {\n return (data[\"TotalVisibleMemorySize\"] - data[\"FreePhysicalMemory\"]) / data[\"TotalVisibleMemorySize\"];\n }\n\n exec(concatWmicCommands(wmicCommand), function(error, stdout, stderr) {\n if (error || stderr) { return cb(error || stderr); }\n\n var meminfo = stdout.split(\"\\r\\r\\n\");\n var data = {};\n var key = null;\n\n for (var i in meminfo) {\n var value = meminfo[i].trim();\n if (!isNaN(value) && +value > 0) {\n data[key] = +value;\n } else if (value.length > 0) {\n key = value;\n }\n }\n\n cb(null, calcUsage(data) * 100);\n });\n}",
"function memory() {\n if (!u.isNode())\n return {};\n return process.memoryUsage();\n}",
"function jvmTotalMemory_macro(param) {\n var m = java.lang.Runtime.getRuntime().totalMemory();\n return (param && param.hr) ? formatBytes(m) : m;\n}",
"function getHeapUsage() {\n return process.memoryUsage().heapUsed / 1024 / 1024;\n}",
"function mem(callback) {\n\tif (_windows) {\n\t\tcallback(NOT_SUPPORTED);\n\t}\n\n\tvar result = {\n\t\ttotal : os.totalmem(),\n\t\tfree : os.freemem(),\n\t\tused : os.totalmem() - os.freemem(),\n\n\t\tactive : os.totalmem() - os.freemem(),\n\t\tbuffcache : 0,\n\n\t\tswaptotal : 0,\n\t\tswapused : 0,\n\t\tswapfree : 0\n\t};\n\n\tif (_linux) {\n\t\texec(\"free -b\", function(error, stdout) {\n\t\t\tif (!error) {\n\t\t\t\tvar lines = stdout.toString().split('\\n');\n\n\t\t\t\tvar mem = lines[1].replace(/ +/g, \" \").split(' ');\n\t\t\t\tresult.total = parseInt(mem[1]);\n\t\t\t\tresult.free = parseInt(mem[3]);\n\t\t\t\tresult.buffcache = parseInt(mem[5]) + parseInt(mem[6]);\n\t\t\t\tresult.active = result.total - result.free - result.buffcache;\n\n\t\t\t\tmem = lines[3].replace(/ +/g, \" \").split(' ');\n\t\t\t\tresult.swaptotal = parseInt(mem[1]);\n\t\t\t\tresult.swapfree = parseInt(mem[3]);\n\t\t\t\tresult.swapused = parseInt(mem[2]);\n\n\t\t\t}\n\t\t\tcallback(result);\n\t\t});\n\t}\n\tif (_darwin) {\n\t\texec(\"vm_stat | grep 'Pages active'\", function(error, stdout) {\n\t\t\tif (!error) {\n\t\t\t\tvar lines = stdout.toString().split('\\n');\n\n\t\t\t\tresult.active = parseInt(lines[0].split(':')[1]) * 4096;\n\t\t\t\tresult.buffcache = result.used - result.active;\n\t\t\t}\n\t\t\texec(\"sysctl -n vm.swapusage\", function(error, stdout) {\n\t\t\t\tif (!error) {\n\t\t\t\t\tvar lines = stdout.toString().split('\\n');\n\t\t\t\t\tif (lines.length > 0) {\n\t\t\t\t\t\tvar line = lines[0].replace(/,/g, \".\").replace(/M/g, \"\");\n\t\t\t\t\t\tline = line.trim().split(' ');\n\t\t\t\t\t\tfor (var i = 0; i < line.length; i++) {\n\t\t\t\t\t\t\tif(line[i].toLowerCase().indexOf('total') != -1) result.swaptotal = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024;\n\t\t\t\t\t\t\tif(line[i].toLowerCase().indexOf('used') != -1) result.swapused = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024;\n\t\t\t\t\t\t\tif(line[i].toLowerCase().indexOf('free') != -1) result.swapfree = parseFloat(line[i].split('=')[1].trim()) * 1024 * 1024;\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcallback(result);\n\t\t\t});\n\t\t});\n\t}\n}",
"function totalToMemory(){\n addHistoryItem(\"total to memory\",total);\n memory = total;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluates, or attempts to evaluate, a ForInStatement | function evaluateForInStatement({ node, environment, evaluate, logger, reporting, typescript, statementTraversalStack }) {
// Compute the 'of' part
const expressionResult = evaluate.expression(node.expression, environment, statementTraversalStack);
// Ensure that the initializer is a proper VariableDeclarationList
if (!typescript.isVariableDeclarationList(node.initializer)) {
throw new UnexpectedNodeError({ node: node.initializer, typescript });
}
// Only 1 declaration is allowed in a ForOfStatement
else if (node.initializer.declarations.length > 1) {
throw new UnexpectedNodeError({ node: node.initializer.declarations[1], typescript });
}
for (const literal in expressionResult) {
// Prepare a lexical environment for the current iteration
const localEnvironment = cloneLexicalEnvironment(environment);
// Define a new binding for a break symbol within the environment
setInLexicalEnvironment({ env: localEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });
// Define a new binding for a continue symbol within the environment
setInLexicalEnvironment({ env: localEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });
// Evaluate the VariableDeclaration and manually pass in the current literal as the initializer for the variable assignment
evaluate.nodeWithArgument(node.initializer.declarations[0], localEnvironment, literal, statementTraversalStack);
// Evaluate the Statement
evaluate.statement(node.statement, localEnvironment);
// Check if a 'break' statement has been encountered and break if so
if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) {
logger.logBreak(node, typescript);
break;
}
else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) {
logger.logContinue(node, typescript);
// noinspection UnnecessaryContinueJS
continue;
}
else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) {
logger.logReturn(node, typescript);
return;
}
}
} | [
"function ForInStatement() {\n}",
"function evaluateForOfStatement({ node, environment, evaluate, logger, reporting, typescript, statementTraversalStack }) {\n // Compute the 'of' part\n const expressionResult = evaluate.expression(node.expression, environment, statementTraversalStack);\n // Ensure that the initializer is a proper VariableDeclarationList\n if (!typescript.isVariableDeclarationList(node.initializer)) {\n throw new UnexpectedNodeError({ node: node.initializer, typescript });\n }\n // Only 1 declaration is allowed in a ForOfStatement\n else if (node.initializer.declarations.length > 1) {\n throw new UnexpectedNodeError({ node: node.initializer.declarations[1], typescript });\n }\n // As long as we only offer a synchronous API, there's no way to evaluate an async iterator in a synchronous fashion\n if (node.awaitModifier != null) {\n throw new AsyncIteratorNotSupportedError({ typescript });\n }\n else {\n for (const literal of expressionResult) {\n // Prepare a lexical environment for the current iteration\n const localEnvironment = cloneLexicalEnvironment(environment);\n // Define a new binding for a break symbol within the environment\n setInLexicalEnvironment({ env: localEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });\n // Define a new binding for a continue symbol within the environment\n setInLexicalEnvironment({ env: localEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });\n // Evaluate the VariableDeclaration and manually pass in the current literal as the initializer for the variable assignment\n evaluate.nodeWithArgument(node.initializer.declarations[0], localEnvironment, literal, statementTraversalStack);\n // Evaluate the Statement\n evaluate.statement(node.statement, localEnvironment);\n // Check if a 'break' statement has been encountered and break if so\n if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, BREAK_SYMBOL)) {\n logger.logBreak(node, typescript);\n break;\n }\n else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, CONTINUE_SYMBOL)) {\n logger.logContinue(node, typescript);\n // noinspection UnnecessaryContinueJS\n continue;\n }\n else if (pathInLexicalEnvironmentEquals(node, localEnvironment, true, RETURN_SYMBOL)) {\n logger.logReturn(node, typescript);\n return;\n }\n }\n }\n}",
"function evaluateForStatement({ node, environment, evaluate, reporting, statementTraversalStack, typescript }) {\n // Prepare a lexical environment for the ForStatement\n const forEnvironment = cloneLexicalEnvironment(environment);\n // Evaluate the initializer if it is given\n if (node.initializer !== undefined) {\n if (typescript.isVariableDeclarationList(node.initializer)) {\n for (const declaration of node.initializer.declarations) {\n evaluate.declaration(declaration, forEnvironment, statementTraversalStack);\n }\n }\n else {\n evaluate.expression(node.initializer, forEnvironment, statementTraversalStack);\n }\n }\n while (true) {\n // Prepare a lexical environment for the current iteration\n const iterationEnvironment = cloneLexicalEnvironment(forEnvironment);\n // Define a new binding for a break symbol within the environment\n setInLexicalEnvironment({ env: iterationEnvironment, path: BREAK_SYMBOL, value: false, newBinding: true, reporting, node });\n // Define a new binding for a continue symbol within the environment\n setInLexicalEnvironment({ env: iterationEnvironment, path: CONTINUE_SYMBOL, value: false, newBinding: true, reporting, node });\n // Evaluate the condition. It may be truthy always\n const conditionResult = node.condition == null ? true : evaluate.expression(node.condition, forEnvironment, statementTraversalStack);\n // If the condition doesn't hold, return immediately\n if (!conditionResult)\n return;\n // Execute the Statement\n evaluate.statement(node.statement, iterationEnvironment);\n // Check if a 'break' statement has been encountered and break if so\n if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, BREAK_SYMBOL)) {\n break;\n }\n else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, RETURN_SYMBOL)) {\n return;\n }\n // Run the incrementor\n if (node.incrementor != null) {\n evaluate.expression(node.incrementor, forEnvironment, statementTraversalStack);\n }\n // Always run the incrementor before continuing\n else if (pathInLexicalEnvironmentEquals(node, iterationEnvironment, true, CONTINUE_SYMBOL)) {\n // noinspection UnnecessaryContinueJS\n continue;\n }\n }\n}",
"function visitForInStatement(node){var savedEnclosingBlockScopedContainer=enclosingBlockScopedContainer;enclosingBlockScopedContainer=node;node=ts.updateForIn(node,visitForInitializer(node.initializer),ts.visitNode(node.expression,destructuringAndImportCallVisitor,ts.isExpression),ts.visitNode(node.statement,nestedElementVisitor,ts.isStatement,ts.liftToBlock));enclosingBlockScopedContainer=savedEnclosingBlockScopedContainer;return node;}",
"function forstatementnode(state, node, ast){\n\t switch(ast[0]){\n\t case 'FORNODE':\n\t\t\t if(eval(state, node, ast[2])==true){\n\t\t\t temp = funceval(state, node, ast[4]);\n\t\t\t if(temp == \"EXIT\"){\n\t\t\t\t return;\n\t\t\t\t} else if(temp != undefined){\n\t\t\t\t return temp;\n\t\t\t } else {\n\t\t\t\t valasgn(state, node, ast[3]);\n\t\t\t\t forstatementnode(state, node, ast);\n\t\t\t }\n\t\t\t }\n\t\t\t break;\n\t }\n\t}",
"visitForInStatement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function visitForInStatement(node) {\n var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;\n enclosingBlockScopedContainer = node;\n node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));\n enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;\n return node;\n }",
"function visitForInStatement(node) {\n var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;\n enclosingBlockScopedContainer = node;\n node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, /*optional*/false, ts.liftToBlock));\n enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;\n return node;\n }",
"function visitForInStatement(node) {\n var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;\n enclosingBlockScopedContainer = node;\n node = ts.updateForIn(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, ts.liftToBlock));\n enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;\n return node;\n }",
"function iterizeForOf(node,path) {\n node.type = 'ForStatement';\n if (node.body.type!=='BlockStatement') {\n node.body = {type:'BlockStatement',body:[node.body]} ;\n }\n \n var index,iterator,initIterator = {\n \"type\": \"ArrayExpression\",\n \"elements\":[{\n \"type\": \"CallExpression\",\n \"callee\": {\n \"type\": \"MemberExpression\",\n \"object\": node.right,\n \"property\": {\n \"type\": \"MemberExpression\",\n \"object\": ident(\"Symbol\"),\n \"property\": ident(\"iterator\"),\n \"computed\": false\n },\n \"computed\": true\n },\n \"arguments\": []\n }]} ;\n \n if (node.left.type==='VariableDeclaration') {\n index = node.left.declarations[0].id ;\n iterator = ident(\"$iterator_\"+index.name) ;\n node.left.declarations.push({\n type:\"VariableDeclarator\",\n id:iterator,\n init:initIterator\n }) ;\n node.init = node.left ;\n } else {\n index = node.left ;\n iterator = ident(\"$iterator_\"+index.name) ;\n var declaration = {\n type:'VariableDeclaration',\n kind:'var',\n declarations:[{\n type:\"VariableDeclarator\",\n id:iterator,\n init:initIterator\n }]\n } ;\n path[0].parent.body.splice(path[0].index,0,declaration) ;\n node.init = null;\n }\n \n node.test = {\n \"type\": \"LogicalExpression\",\n \"left\": {\n \"type\": \"UnaryExpression\",\n \"operator\": \"!\",\n \"prefix\": true,\n \"argument\": {\n \"type\": \"MemberExpression\",\n \"object\": {\n \"type\": \"AssignmentExpression\",\n \"operator\": \"=\",\n \"left\": {\n \"type\": \"MemberExpression\",\n \"object\": iterator,\n \"property\": literal(1),\n \"computed\": true\n },\n \"right\": {\n \"type\": \"CallExpression\",\n \"callee\": {\n \"type\": \"MemberExpression\",\n \"object\": {\n \"type\": \"MemberExpression\",\n \"object\": iterator,\n \"property\": literal(0),\n \"computed\": true\n },\n \"property\": ident('next'),\n \"computed\": false\n },\n \"arguments\": []\n }\n },\n \"property\": ident('done'),\n \"computed\": false\n }\n },\n \"operator\": \"&&\",\n \"right\": {\n type:'LogicalExpression',\n \"operator\": \"||\",\n left:{\n \"type\": \"AssignmentExpression\",\n \"operator\": \"=\",\n \"left\": index,\n \"right\": {\n \"type\": \"MemberExpression\",\n \"object\": {\n \"type\": \"MemberExpression\",\n \"object\": iterator,\n \"property\": literal(1),\n \"computed\": true\n },\n \"property\": ident('value'),\n \"computed\": false\n }\n },\n right:literal(true)\n }\n } ;\n \n delete node.left ;\n delete node.right ;\n }",
"function _ForInStatementEmitter() {\n}",
"static isForInStatement(node) {\r\n return node.getKind() === typescript_1.SyntaxKind.ForInStatement;\r\n }",
"function noassignmentsallowedinforinhead() {\n try {\n eval('for (var i = 0 in {}) {}');\n }\n catch(e) {\n return true;\n }\n}",
"function ForStatement() {\n}",
"function visitForOfStatement(node,outermostLabeledStatement){var ancestorFacts=enterSubtree(0/* IterationStatementExcludes */,2/* IterationStatementIncludes */);if(node.initializer.transformFlags&16384/* ContainsObjectRestOrSpread */){node=transformForOfStatementWithObjectRest(node);}var result=node.awaitModifier?transformForAwaitOfStatement(node,outermostLabeledStatement,ancestorFacts):ts.restoreEnclosingLabel(ts.visitEachChild(node,visitor,context),outermostLabeledStatement);exitSubtree(ancestorFacts);return result;}",
"function ForStatement(init, test, update, body) {\n this.type = \"ForStatement\";\n this.init = init;\n this.test = test;\n this.update = update\n this.body = body;\n \n if (test.typeof !== 'bool' || test.isArray)\n error('boolean expression expected');\n}",
"function parseForStatement(node) {\n\t next();\n\t labels.push(loopLabel);\n\t expect(_parenL);\n\t if (tokType === _semi) return parseFor(node, null);\n\t if (tokType === _var || tokType === _let) {\n\t var init = startNode(), varKind = tokType.keyword, isLet = tokType === _let;\n\t next();\n\t parseVar(init, true, varKind);\n\t finishNode(init, \"VariableDeclaration\");\n\t if ((tokType === _in || (options.ecmaVersion >= 6 && tokType === _name && tokVal === \"of\")) && init.declarations.length === 1 &&\n\t !(isLet && init.declarations[0].init))\n\t return parseForIn(node, init);\n\t return parseFor(node, init);\n\t }\n\t var init = parseExpression(false, true);\n\t if (tokType === _in || (options.ecmaVersion >= 6 && tokType === _name && tokVal === \"of\")) {\n\t checkLVal(init);\n\t return parseForIn(node, init);\n\t }\n\t return parseFor(node, init);\n\t }",
"function ForIn_1( object) {\n with ( object ) {\n for ( property in object ) {\n new TestCase(\n\tSECTION,\n\t\"with loop in a for...in loop. (\"+object+\")[\"+property +\"] == \"+\n\t\"eval ( \" + property +\" )\",\n\ttrue,\n\tobject[property] == eval(property) );\n }\n }\n}",
"function testForInOfLoop(node) {\n if (node.left && node.left.kind === 'let') {\n context.report(node.left, msg);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
yesterday(thisDate) / /All my troubles seemed so far away. | function yesterday(thisDate) {
// adjustForLeapYears(thisDate);
if (thisDate[2]!=1) {
return [thisDate[0],thisDate[1],thisDate[2]-1];
} else if (thisDate[1]!=0) {
return [thisDate[0],thisDate[1]-1,monthLength[thisDate[1]-1]];
} else {
var tempYear = thisDate[0]-1;
adjustForLeapYears('yesterday()',tempYear);
return [tempYear,11,31];
}
} | [
"function getYesterday(){\n\treturn getDate(-1);\n}",
"getYesterday() {\n let yesterday = new Date();\n yesterday.setDate(yesterday.getDate() - 1);\n return this.format(yesterday);\n }",
"function dateForYesterday() {\n var date = new Date().toMidnight();\n date.setDate(date.getDate() - 1);\n return date;\n}",
"function getYesterday() {\n \n var now = new Date()\n var yesterday = new Date(now.getTime() - (24 * 3600 * 1000))\n yesterday.setHours(12)\n return yesterday\n \n} // DateTime_.getYesterday()",
"function getMixpanelDateYesterday(){\n var today = new Date();\n var yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 1);\n \n //Logger.log(yesterday);\n var dd = yesterday.getDate();\n //Logger.log(yesterday);\n var mm = yesterday.getMonth() + 1;\n var yyyy = yesterday.getFullYear();\n \n if (dd < 10) {\n dd = '0' + dd;\n }\n if (mm < 10) {\n mm = '0' + mm;\n }\n \n yesterday = yyyy + '-' + mm + '-' + dd;\n //Logger.log(yesterday);\n return yesterday;\n}",
"checkIfYesterday(timestamp) {\n let other_date = new Date(timestamp);\n if ((this.today.getDate() - 1) == other_date.getDate()) {\n return true;\n } else {\n return false;\n }\n }",
"function yesterdayDateTime()\n\n {\n\n var date=new Date();//object of Date\n\n date.setHours(date.getHours()-24)//setHours() -24\n\n //display yesterday date and time\n\n alert(\"Yesterday date and time is \"+date.toLocaleString());\n\n }",
"setDate() {\n this.yesterday = new Date(this.today.setDate(this.today.getDate() - 1));\n if (this.past) {\n this.pastString = \"Past \";\n }\n }",
"function is_yesterday(lw_date) {\n is_yesterday_bool = false;\n if (lw_date === undefined || lw_date === \"\" || typeof lw_date != \"object\") {\n console.log(\"last_workout_date not defined\")\n return is_yesterday_bool\n }\n\n let today = new Date();\n let yesterday_epoch_seconds = Math.floor(today.getTime() / 1000.0) - 86400 //getTime gets epoch time in millisonds; 86400 is seconds in a day\n let yesterday = new Date(yesterday_epoch_seconds * 1000)\n\n if (parseInt(lw_date.month) === yesterday.getMonth() &&\n parseInt(lw_date.day) === yesterday.getDate() &&\n parseInt(lw_date.year) === yesterday.getFullYear()) {\n is_yesterday_bool = true\n console.log(\"good. you worked out yesterday\")\n }\n\n return is_yesterday_bool;\n\n}",
"function getYesterday() {\n const start = moment().subtract(1, \"day\").startOf(\"day\").unix();\n const end = start + ONE_DAY_SEC;\n return { start, end };\n}",
"function isYesterday(date)\r\n\t{\r\n\t\tvar yesterday = new com.actional.util.TDate();\r\n\t\tyesterday.setDate(yesterday.getDate() - 1);\r\n\r\n\t\treturn (yesterday.getFullYear() == date.getFullYear()\r\n\t\t\t\t&& yesterday.getMonth() == date.getMonth()\r\n\t\t\t\t&& yesterday.getDate() == date.getDate());\r\n\t}",
"function checkBeforeToday(date) {\n var today = new Date();\n var yesterday = new Date();\n yesterday.setDate(today.getDate() - 1);\n yesterday.setHours(23, 59, 59, 999);\n return date < yesterday;\n}",
"function isYesterday(date) {\n var today = new Date();\n var yesterday = new Date();\n yesterday.setDate(today.getDate() - 1);\n return date.getFullYear() == yesterday.getFullYear() &&\n date.getMonth() == yesterday.getMonth() &&\n date.getDate() == yesterday.getDate();\n}",
"function setHeaderPrevDate(date){\n var currentDate = moment(date);\n currentDate.subtract(1, \"day\");\n var year = currentDate.get(\"year\");\n var month = parseInt(currentDate.get(\"month\")) +1;\n var day = currentDate.get(\"date\");\n\n // Check to see if the month and day have a length of 1\n if(month.toString().length ==1){\n month = \"0\" + month;\n }\n\n if(day.toString().length == 1){\n day = \"0\" + day;\n }\n\n\n var yesterdayDate = year + \"\" + month + \"\" + day;\n var yesterdayButton = document.getElementById(\"prevDayButton\");\n\n // we can get the different formats from moment js - format\n var dateDay = currentDate.format('dddd');\n var dateMonth = currentDate.format('MMMM');\n var dateNumber = currentDate.format('Do');\n\n yesterdayButton.innerHTML = dateDay + \" \" + dateMonth + \" \" + dateNumber;\n yesterdayButton.href = \"/schedule/\" + yesterdayDate;\n\n}",
"function getYesterdaysDate() {\n const d = new Date();\n d.setDate(d.getDate() - 1);\n\n let month = (d.getMonth() + 1);\n let day = d.getDate();\n const year = d.getFullYear();\n\n if (month.length < 2) month = `0${month}`;\n if (day.length < 2) day = `0${day}`;\n\n return [year, month, day].join('-');\n}",
"function isValidDate(current) {\n let yesterday = DateTime.moment().subtract(1, 'day');\n return current.isBefore(yesterday);\n}",
"function handlePrevDay() {\n setDate(subDays(date, 1));\n }",
"function getMixpanelDateLastWeek(){\n var today = new Date();\n var yesterday = new Date(today);\n yesterday.setDate(today.getDate() - 7);\n \n //Logger.log(yesterday);\n var dd = yesterday.getDate();\n //Logger.log(yesterday);\n var mm = yesterday.getMonth() + 1;\n var yyyy = yesterday.getFullYear();\n \n if (dd < 10) {\n dd = '0' + dd;\n }\n if (mm < 10) {\n mm = '0' + mm;\n }\n \n yesterday = yyyy + '-' + mm + '-' + dd;\n //Logger.log(yesterday);\n return yesterday;\n}",
"dateHandler(date) {\n const product_date = new Date(date);\n const current_date = new Date();\n const difference_time = Math.abs(current_date - product_date);\n const difference_days = Math.ceil(difference_time / (1000 * 60 * 60 * 24)); \n if (difference_days < 7){\n return difference_days +\" days ago\"\n }\n return date.substr(0, 15);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The AnimationMixer is a player for animations on a particular object in the scene. When multiple objects in the scene are animated independently, one AnimationMixer may be used for each object. | function AnimationMixer() {
this._clips = {};
this._bindings = {};
this._activeClips = {};
} | [
"animationMixer(root) {\r\n const mixer = new AnimationMixer(root);\r\n this.mixers.add(mixer);\r\n return mixer;\r\n }",
"animationMixer(root) {\r\n const mixer = new types_1.AnimationMixer(root);\r\n this.mixers.add(mixer);\r\n return mixer;\r\n }",
"setupMixer() {\n const armature = this.el.getObject3D('armature');\n const mesh = this.el.getObject3D('mesh');\n // Bail if we are missing anything.\n if (!armature || !mesh) { return; }\n\n const { enableEvents } = this.data;\n\n // Create the mixer to use the new armature.\n this.mixer = new THREE.AnimationMixer(armature);\n // Listen to events.\n if (enableEvents) {\n this.mixer.addEventListener('loop', this);\n this.mixer.addEventListener('finished', this);\n }\n // Tell the mesh to allow animations.\n mesh.material.skinning = true;\n mesh.material.needsUpdate = true;\n }",
"setMixer(mixer) { \n this.mixer = mixer;\n }",
"function Mixer(audioContext) {\n\t'use strict';\n\n\tvar output = audioContext.createGain();\n\tvar faders = [];\n\tvar numFaders = 8;\n\t\n EventDispatcher.call(this);\n\n\tinitFaders();\n\n\tvar that = this;\n\n\tObject.defineProperties(this, {\n\t\tfaders: {\n\t\t\tget: function() { return faders; }\n\t\t},\n\t\tgain: {\n\t\t\tget: function() { return output.gain.value; },\n\t\t\tset: function(v) {\n\t\t\t\toutput.gain.value = v;\n\t\t\t\tthat.dispatchEvent({ type: 'gain_change', gain: v });\n\t\t\t}\n\t\t}\n\t});\n\n\n\t//\n\n\tfunction initFaders() {\n\t\twhile(faders.length < numFaders) {\n\t\t\tvar fader = new Fader(audioContext);\n\t\t\tfader.output.connect(output);\n\t\t\tfader.gain = 0.7;\n\t\t\tfader.label = 'CH ' + (faders.length + 1);\n\t\t\tfaders.push(fader);\n\t\t}\n\t}\n\n\t// ~~~\n\t\n\tthis.guiTag = 'gear-mixer';\n\n\tthis.output = output;\n\n\tthis.plug = function(faderNumber, audioOutput) {\n\n\t\tif(faderNumber > faders.length) {\n\t\t\tconsole.error('Mixer: trying to plug into a fader that does not exist', faderNumber);\n\t\t\treturn;\n\t\t}\n\n\t\tvar faderInput = faders[faderNumber].input;\n\t\taudioOutput.connect(faderInput);\n\t};\n\n\tthis.setFaderGain = function(faderNumber, value) {\n\t\tfaders[faderNumber].gain = value;\n\t};\n}",
"set outputAudioMixerGroup(value) {}",
"get outputAudioMixerGroup() {}",
"function AudioMixer() {\n\n AudioMixer.superclass.constructor.call(this);\n\n \n\n this.sounds = {};\n\n \n\n // If AudioMixer is disabled, do not do anything else\n\n if(!AudioMixer.enabled) {\n\n console.log(\"AudioMixer is currently disabled\");\n\n return;\n\n }\n\n \n\n this.crossFadeComplete = this.crossFadeComplete.bind(this);\n\n\n\n var a = document.createElement('audio');\n\n // Detect <audio> capability\n\n if(a.canPlayType) {\n\n this.availible = true;\n\n \n\n // Detect ogg/oga capability\n\n var check = a.canPlayType('audio/ogg; codecs=\"vorbis\"');\n\n if(check != '' && check != 'no') {\n\n this.ogg = true;\n\n }\n\n \n\n // Detect mp3 capability\n\n check = a.canPlayType('audio/mpeg;')\n\n if(check != '' && check != 'no') {\n\n this.mp3 = true;\n\n }\n\n }\n\n}",
"function playSodaBottleAnim() {\n console.warn(`playSodaBottleAnim`);\n\n // let doorUpRightMesh = mesh.children.find(c => c.name === 'axi_door_up_R');\n\n playSodaBottleMixer_1 = new THREE.AnimationMixer(doorUpRightGroup.children[6]);\n let clip_1 = mesh.animations[9];\n let action_1 = playSodaBottleMixer_1.clipAction(clip_1);\n action_1.setDuration(1.5);\n action_1.clampWhenFinished = true;\n action_1.loop = THREE.LoopRepeat;\n action_1.play();\n\n playSodaBottleMixer_1.addEventListener('finished', () => {\n console.warn(`SODA BOTTLE 1 PLAY END`);\n });\n\n playSodaBottleMixer_2 = new THREE.AnimationMixer(doorUpRightGroup.children[7]);\n let clip_2 = mesh.animations[9];\n let action_2 = playSodaBottleMixer_2.clipAction(clip_2);\n action_2.setDuration(1.5);\n action_2.clampWhenFinished = true;\n action_2.loop = THREE.LoopRepeat;\n action_2.play();\n\n playSodaBottleMixer_2.addEventListener('finished', () => {\n console.warn(`SODA BOTTLE 2 PLAY END`);\n });\n\n playSodaBottleMixer_3 = new THREE.AnimationMixer(doorUpRightGroup.children[8]);\n let clip_3 = mesh.animations[9];\n let action_3 = playSodaBottleMixer_3.clipAction(clip_3);\n action_3.setDuration(1.5);\n action_3.clampWhenFinished = true;\n action_3.loop = THREE.LoopRepeat;\n action_3.play();\n\n playSodaBottleMixer_3.addEventListener('finished', () => {\n console.warn(`SODA BOTTLE 3PLAY END`);\n });\n}",
"function playObjectAnimations() {\r\n powerUps.playAnimation(\"cherryAnims\", true);\r\n jewels.playAnimation(\"jewelAnims\", true);\r\n}",
"play(name) {\n\n // Check if currently playing animation name matches this one\n if (name == this.currentAnimation)\n return\n\n // Find new animation\n var anim = this.clips.find(c => c.name == name)\n if (!anim)\n return console.warn(`[Animation Manager] Unable to find animation with the name ${name}. Ignoring.`)\n\n // Stop all current animations\n this.mixer.stopAllAction()\n\n // HACK: For some reason the animation just won't play if you call play() a second time? Let's just remove all\n // cached actions until this can be sorted.\n for (let clip of this.clips)\n this.mixer.uncacheClip(clip)\n\n // Play this one\n console.log(`[Animation Manager] Playing ${name}`)\n this.currentAnimation = name\n let action = this.mixer.clipAction(anim)\n action.clampWhenFinished = true\n action.setLoop(THREE.LoopOnce)\n action.reset()\n action.play()\n\n }",
"function mix_skeletal_animation(obj, elapsed) {\n var render = obj.render;\n var mix_factor = render.anim_mix_factor;\n\n var skeletal_slots = render.blend_skel_slots;\n\n var ind_0 = skeletal_slots[0];\n var ind_1 = skeletal_slots[1];\n\n // no skeletal anim assigned to armature\n if (ind_1 == -1)\n return;\n\n if (ind_0 != -1) {\n // penult anim\n var skeletal_slot_0 = obj.anim_slots[ind_0];\n\n if (skeletal_slot_0.play || elapsed == 0 || render.mix_with_current) {\n\n var finfo_0 = action_anim_finfo(skeletal_slot_0);\n\n var frame_0 = finfo_0[0];\n var frame_next_0 = finfo_0[1];\n render.frame_factor = finfo_0[2];\n\n var quats_prev_0 = skeletal_slot_0.quats[frame_0];\n var quats_next_0 = skeletal_slot_0.quats[frame_next_0];\n var trans_prev_0 = skeletal_slot_0.trans[frame_0];\n var trans_next_0 = skeletal_slot_0.trans[frame_next_0];\n } else\n mix_factor = 1;\n } else\n mix_factor = 1;\n\n // last anim\n var skeletal_slot_1 = obj.anim_slots[ind_1];\n\n if (skeletal_slot_1.play || elapsed == 0 || render.mix_with_current) {\n\n var finfo_1 = action_anim_finfo(skeletal_slot_1);\n\n var frame_1 = finfo_1[0];\n var frame_next_1 = finfo_1[1];\n\n // frame_factor is common for two animations as they are synced when applied\n render.frame_factor = finfo_1[2];\n } else if (ind_0 != -1 && skeletal_slot_0.play) {\n mix_factor = 0;\n } else {\n return;\n }\n\n var quats_prev_1 = skeletal_slot_1.quats[frame_1];\n var quats_next_1 = skeletal_slot_1.quats[frame_next_1];\n var trans_prev_1 = skeletal_slot_1.trans[frame_1];\n var trans_next_1 = skeletal_slot_1.trans[frame_next_1];\n if (mix_factor == 1 && !render.mix_with_current) {\n render.quats_before.set(quats_prev_1);\n render.quats_after.set(quats_next_1);\n render.trans_before.set(trans_prev_1);\n render.trans_after.set(trans_next_1);\n } else if (mix_factor == 0 && !render.mix_with_current) {\n render.quats_before.set(quats_prev_0);\n render.quats_after.set(quats_next_0);\n render.trans_before.set(trans_prev_0);\n render.trans_after.set(trans_next_0);\n } else {\n var bone_pointers = render.bone_pointers;\n if (render.mix_with_current && !render.trans_curr && !render.quats_curr) {\n render.trans_curr = new Float32Array(render.trans_before.length);\n render.quats_curr = new Float32Array(render.quats_before.length);\n for (var bone_name in bone_pointers) {\n var bone_pointer = bone_pointers[bone_name];\n if (!bone_pointer.parent_bone_ptr)\n check_mix_with_current(render, bone_pointer);\n }\n }\n for (var bone_name in bone_pointers) {\n var bone_pointer = bone_pointers[bone_name];\n if (!bone_pointer.parent_bone_ptr)\n blend_two_anim(render, bone_pointer, skeletal_slot_0, skeletal_slot_1,\n frame_0, frame_next_0, frame_1, frame_next_1);\n }\n }\n m_trans.update_transform(obj);\n m_armat.update_skinned_renders(obj);\n}",
"set mixer(id) {\n this.config.last = id || this.config.last;\n if(this._mixer === undefined) {\n let container = $('<div/>', {'class': 'ui-flex flex-vertical', 'id': 'mixer-container'}),\n logo = $('<div/>', {'css': {'min-height': '32px', 'flex': '0 0 0%', 'background-repeat': 'no-repeat', 'background-attachement': 'fixed', 'background-position': 'center', 'background-color': '#141828', 'background-image': 'url(\"data:image/svg+xml;base64,' + this.mixerText + '\")'}});\n\n this._mixer = container.append(logo, this.chat.attr('src', id));\n } else {\n this.chat.attr('src', id);\n this.video.attr('src', id);\n }\n }",
"_playAnimation() {\n if (this._animationLast === undefined && this._animationQueue.length > 0) {\n this._animationLast = this._animationCurrent;\n this._animationCurrent = this._animationQueue.shift();\n console.log(\"New: \" + this._animationCurrent.name);\n this._animationCurrent.runCount = 0;\n }\n this._serviceAnimation(this._animationCurrent, true);\n this._serviceAnimation(this._animationLast, false);\n if (this._animationLast && this._animationLast.cleanup) {\n this._animationLast.animation.stop();\n this._animationLast.animation = undefined;\n this._animationLast = undefined;\n }\n }",
"function mix(){\n var args = Array.prototype.slice.call(arguments);\n var obj = args.shift();\n for(var i = 0; i < args.length; ++i)\n mixin.call(obj, args[i]);\n }",
"play(){\r\n this.cardTop.effect(this);\r\n if(combatController.simulating) this.cardBottom.effect(this);\r\n else setTimeout(this.cardBottom.effect.bind(null,this),300);\r\n }",
"function PlayerMixin(Target) {\r\n var PlayerMixinClass = /** @class */ (function (_super) {\r\n __extends(PlayerMixinClass, _super);\r\n function PlayerMixinClass() {\r\n return _super !== null && _super.apply(this, arguments) || this;\r\n }\r\n Object.defineProperty(PlayerMixinClass.prototype, \"renderer\", {\r\n // Mixin needs to re-define all the normal player properties, but most should be made readonly anyway...\r\n get: function () {\r\n return this.player.renderer;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"audio\", {\r\n get: function () {\r\n return this.player.audio;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"canvasEl\", {\r\n get: function () {\r\n return this.player.canvasEl;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"note\", {\r\n get: function () {\r\n return this.player.note;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"noteFormat\", {\r\n get: function () {\r\n return this.player.noteFormat;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"meta\", {\r\n get: function () {\r\n return this.player.meta;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"duration\", {\r\n get: function () {\r\n return this.player.duration;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"layerVisibility\", {\r\n get: function () {\r\n return this.player.layerVisibility;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n Object.defineProperty(PlayerMixinClass.prototype, \"autoplay\", {\r\n get: function () {\r\n return this.player.autoplay;\r\n },\r\n set: function (value) {\r\n this.player.autoplay = value;\r\n },\r\n enumerable: false,\r\n configurable: true\r\n });\r\n return PlayerMixinClass;\r\n }(Target));\r\n var _loop_1 = function (key) {\r\n var desc = Object.getOwnPropertyDescriptor(Player.prototype, key);\r\n // don't override stuff that already exists, and ignore JS prototype junk\r\n if (key in Target.prototype || key === 'constructor' || key === 'name' || key === 'prototype') {\r\n return \"continue\";\r\n }\r\n // override methods to call e.g. `this.player.methodName()` when `methodName()` is called\r\n else if (desc.value && typeof desc.value === 'function') {\r\n Object.defineProperty(PlayerMixinClass.prototype, key, __assign(__assign({}, desc), { value: function () {\r\n var _a;\r\n var args = [];\r\n for (var _i = 0; _i < arguments.length; _i++) {\r\n args[_i] = arguments[_i];\r\n }\r\n return (_a = this.player)[key].apply(_a, args);\r\n } }));\r\n }\r\n // override getters and setters so that e.g. `property` will always reflect `this.player.property`\r\n else if (desc.get || desc.set) {\r\n Object.defineProperty(PlayerMixinClass.prototype, key, __assign(__assign({}, desc), { set: function (value) {\r\n this.player[key] = value;\r\n }, get: function () {\r\n return this.player[key];\r\n } }));\r\n }\r\n };\r\n // add all Player API methods and getter/setter props to target\r\n for (var _i = 0, _a = Reflect.ownKeys(Player.prototype); _i < _a.length; _i++) {\r\n var key = _a[_i];\r\n _loop_1(key);\r\n }\r\n return PlayerMixinClass;\r\n }",
"function EffectsManager(gameObj) {\n\n\t// keep track of the game object\n\tthis.gameObj = gameObj;\n\t\n}",
"getModelMixer (modelType, instanceNumber) {\n return this.getCharacterGroup(modelType, instanceNumber).mixer\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
promap :: Profunctor p => (a > b, c > d, p b c) > p a d . . Function wrapper for [`fantasyland/promap`][]. . . `fantasyland/promap` implementations are provided for the following . builtin types: Function. . . ```javascript . > promap (Math.abs, x => x + 1, Math.sqrt) (100) . 11 . ``` | function promap(f, g, profunctor) {
return Profunctor.methods.promap (profunctor) (f, g);
} | [
"function promap(f, g, profunctor) {\n return Profunctor.methods.promap(profunctor)(f, g);\n }",
"function Function$prototype$promap(f, g) {\n var profunctor = this;\n return function(x) { return g (profunctor (f (x))); };\n }",
"function Function$prototype$promap(f, g) {\n var profunctor = this;\n return function(x) { return g(profunctor(f(x))); };\n }",
"function isProfunctor(m) {\n return isFunctor(m)\n && isContravariant(m)\n && hasAlg('promap', m)\n}",
"function partialPmap(callback) {\n return function(iterable) {\n return pmap(iterable, callback);\n };\n}",
"function map(p, g) {\n if (isPromise(p)) {\n return p.then(g);\n } else {\n return g(p);\n }\n}",
"function Prelude__Functor__Elm__Html___64_Prelude__Functor__Functor_36_Html_58__33_map_58_0($_0_arg, $_1_arg, $_2_arg, $_3_arg){\n return (A2(_elm_lang$virtual_dom$Native_VirtualDom.map, ($_2_arg), ($_3_arg)));\n}",
"function projector(mapping){\n return lenz(\n function(obj){\n return _.object(_.map(_.pairs(mapping), function(x){return [x[0], x[1].get(obj)];}));\n },\n function(obj, val){\n return _.reduce(_.pairs(mapping), function(acc, x){\n return x[1].set(acc, val[x[0]]);\n }, obj);\n }\n );\n }",
"function map (array, predicate) {\n}",
"function fprop(a,p){return a.filter(function(x){return x[p]})}",
"function ProdFunc(num1,num2){\r\n\treturn num1 *num2;\r\n}",
"function map(func, map) {\r\n return reduce(function (acc, value, point) { return set(point, func(value), acc); }, map, from([]));\r\n}",
"function map_map(project, thisArg) {\n return function mapOperation(source) {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}",
"function mapTransform(args, math, scope) {\n var x, callback;\n\n if (args[0]) {\n x = args[0].compile().evaluate(scope);\n }\n\n if (args[1]) {\n if (Object(is[\"J\" /* isSymbolNode */])(args[1]) || Object(is[\"q\" /* isFunctionAssignmentNode */])(args[1])) {\n // a function pointer, like filter([3, -2, 5], myTestFunction)\n callback = args[1].compile().evaluate(scope);\n } else {\n // an expression like filter([3, -2, 5], x > 0)\n callback = compileInlineExpression(args[1], math, scope);\n }\n }\n\n return map(x, callback);\n }",
"function mapTransform(args, math, scope) {\n\t var x, callback;\n\n\t if (args[0]) {\n\t x = args[0].compile().evaluate(scope);\n\t }\n\n\t if (args[1]) {\n\t if (isSymbolNode(args[1]) || isFunctionAssignmentNode(args[1])) {\n\t // a function pointer, like filter([3, -2, 5], myTestFunction)\n\t callback = args[1].compile().evaluate(scope);\n\t } else {\n\t // an expression like filter([3, -2, 5], x > 0)\n\t callback = compileInlineExpression(args[1], math, scope);\n\t }\n\t }\n\n\t return map(x, callback);\n\t }",
"function filterMap(filterFn, mapFn, array) {\n //your code here\n}",
"function map (data, predicates) {\n assert.object(data);\n\n if (isFunction(predicates)) {\n return mapSimple(data, predicates);\n }\n\n assert.object(predicates);\n\n return mapComplex(data, predicates);\n }",
"function mapTo(value) {\n return function (source) { return source.lift(new MapToOperator(value)); };\n}",
"function _map(f, xs) {\n return (\n Array.isArray(xs) ? _map.array(f, xs)\n : xs['@@fantasy-land/map'] ? _map.functor(f, xs)\n : typeof xs === 'function' ? _map.func(f, xs)\n : xs['@@transducer/step'] ? _map.transducer(f, xs)\n : _map.unknown(f, xs) // idk what to do now? so here are your xs back. Throw?\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Topic: BST, recursion For a Binary Search Tree find the 'kth' largest element Runtime: O(n) Space: O(h) | function findKthBiggest(root, k) {} | [
"function findLargest(root) {\n let current = root\n\n while(current) {\n if (!current.right) {\n return current.value\n }\n current = current.right\n }\n}",
"function largestNodeBST(root) {\n if (root == null) return null;\n else if (root.right == null) return root;\n else return largestNodeBST(root.right)\n}",
"function findSecondLargest(rootNode) {\n\n var current = rootNode;\n\n while (current) {\n\n if (current.left && !current.right) {\n return findLargest(current.left);\n }\n\n if (current.right && !current.right.left && !current.right.right) {\n return current.value;\n }\n\n current = current.right;\n }\n}",
"function kthSmallestInBST(t, k) {\n\n function dfs(node) {\n if (node) {\n var current = node\n return [current.value]\n .concat(dfs(current.left))\n .concat(dfs(current.right))\n .filter(a => a || a == 0)\n .sort((a, b) => a - b)\n\n }\n }\n return dfs(t)[k - 1]\n}",
"function find_kth_element_BST(rootNode, k) {\n\n if (!rootNode) {\n return;\n }\n const stack = [];\n\n stack.push(rootNode);\n\n while(stack.length) {\n const node = stack[stack.length - 1];\n if (node.left) {\n stack.push(node.left);\n continue;\n }\n\n if (k == 0) return node;\n stack.pop();\n k--;\n\n if (node.right) {\n stack.push(node.right);\n }\n }\n return null;\n}",
"findMax() {\n if (this.root === null) {\n throw new Error('tree is empty');\n }\n\n let max = this.root.value;\n let _traverse = (node) => {\n if (node.left) {\n let lmax = node.left.value;\n max = lmax > max ? lmax : max;\n _traverse(node.left);\n }\n if (node.right) {\n let rmax = node.right.value;\n max = rmax > max ? rmax : max;\n _traverse(node.right);\n }\n };\n _traverse(this.root);\n return max;\n }",
"function findSecondLargest(root) {\n let current = root\n\n if (!root || !root.left && !root.right) {\n throw Error ('tree must have at least 2 nodes')\n }\n\n while (current) {\n //1st case: current is largest and has subtree, second largest within subtree\n\n if (current.left && !current.right) {\n return findLargest(current.left)\n }\n\n //2nd case: if current is parent of largest and largest has no children\n //current is 2nd largest\n if (current.right && !current.right.left && !current.right.right) {\n return current.value\n }\n current = current.value\n }\n}",
"function secondLargestBinary(){\n //define largest and 2nd largest elements as dummy nodes\n var largest = {\n value:null,\n };\n var secondLargest = {\n value:null,\n };\n //define inner function that takes node as parameter\n function search(node){\n //if current node is greater than largest node\n if(node.value > largest.value){\n //set 2nd largest equal to largest\n secondLargest = largest;\n //set current node equal to the largest\n largest = node;\n //else if current node is greater than 2nd largest\n }else if(node.value > secondLargest.value){\n //set 2nd largest equal to current value\n secondLargest = node;\n }\n //base case\n //if current value has no child nodes\n if(!node.left && !node.right){\n return\n }\n //recursive case\n //if current node has a right node\n if(node.right){\n //search right node\n search(node.right);\n }else{\n search(node.left);\n }\n };\n //call search with the root node as the argument\n search(this.root);\n return secondLargest;\n}",
"findMaximumValueBT(){\n if(!this.root){return 'Its empty!!';}\n let max=0;\n function _walk(node){\n console.log(node.value,max)\n if(node.value>max){max= node.value; }\n if(node.left){_walk(node.left)} \n if(node.right){_walk(node.right)} \n }\n _walk(this.root)\n return max\n }",
"findMaximumValue() {\n if(!this.root) {\n return 'There is no tree! Please tree again!'\n }\n\n let biggerValue = this.root.value;\n const _traverse = (node) =>{\n if(node.left) _traverse(node.left);\n if(node.right) _traverse(node.right);\n if(node.value > biggerValue) {\n biggerValue = node.value\n }\n }\n _traverse(this.root)\n return biggerValue;\n }",
"findSecondHighest() {\n if(!this.root) return undefined\n let highest = 0\n let secondHighest = 0\n const stack = [this.root]\n while(stack.length) {\n const node = stack.pop()\n if(node.val > highest) {\n secondHighest = highest\n highest = node.val\n }\n else if(node.val > secondHighest) {\n secondHighest = node.val\n }\n else {\n return secondHighest\n }\n if(node.right) stack.push(node.right)\n if(node.left) stack.push(node.left)\n }\n return secondHighest || this.root.val\n }",
"function secondLargest(root) {\n if (!root || (!root.left && !root.right)) {\n throw new Error('tree must have at least 2 nodes');\n }\n\n let current = root;\n while (current) {\n //case 1: current is the largest and has a left subtree\n if (current.left && !current.right) {\n return largestElement(root.left);\n }\n //case 2: we have a right child but that right child doesn't have any children (we're at the second largest)\n if (current.right && !current.right.right && !current.right.left) {\n return current.value;\n }\n //case 3: we have a right subtree with more than one element so we have to traverse right again\n current = current.right;\n }\n}",
"function kthSmallest(root, k) {\n let stack = [];\n let count = 0; // To keep track of kth element \n let node = root;\n\n while (true) {\n if (node) {\n stack.push(node);\n node = node.left;\n } else {\n if (stack.length === 0) break;\n node = stack.pop();\n count += 1;\n if (count === k) return node.val;\n node = node.right;\n }\n }\n}",
"function BSTMax(){\n var walker = this.root;\n while (walker.right != null){\n walker = walker.right;\n }\n return walker.val;\n }",
"findSmallest() {\n //let current be the root node\n let current = this.root,\n max;\n //if no root return undefined\n if (!this.root) return undefined;\n //true untill current is not null\n while (current) {\n //set max to current and update current to current's left child \n max = current;\n current = current.left;\n }\n //return the max value\n return max === undefined ? undefined : max.value;\n }",
"function findMaxBT(root) {\n // Write your code here.\n \n}",
"findSecondLargestNode() {\n if (!this.root) {\n return undefined;\n }\n let count = 0;\n let found;\n\n function helper(node) {\n if (count >= 2 || node === null) { // base case\n return;\n }\n helper(node.right);\n count++;\n if (count === 2) {\n found = node;\n console.log('current', node.value);\n }\n helper(node.left);\n }\n helper(this.root);\n return found;\n }",
"findSecondHighest(current = this.root) {\n // if the tree is too small, return\n if (!this.root || (!this.root.left && !this.root.right)) return;\n\n while (current) {\n // Current is largest and has a left subtree and 2nd largest is the largest in that subtree\n if (current.left && !current.right) {\n return this.findSecondHighest(current.left);\n }\n // Current is parent of largest and largest has no children so current is 2nd largest\n if (current.right && (!current.right.left && !current.right.right)) {\n return current.val;\n }\n current = current.right;\n }\n }",
"findSecondHighest(node=this.root) {\n let highest = 0;\n let secondHighest = 0;\n const toVisistQueue = [node];\n\n while(toVisistQueue.length){\n const current = toVisistQueue.shift();\n\n if(current.val > highest){\n secondHighest = highest;\n highest = current.val;\n }\n\n if(current.left && current.right){\n toVisistQueue.push(current.left)\n toVisistQueue.push(current.right)\n } else if(current.left && !current.right){\n toVisistQueue.push(current.left)\n } else if(!current.left && current.right) {\n toVisistQueue.push(current.right)\n }\n }\n return secondHighest;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fix roles when only one role is missing Valid is an array of json objects for players Player is a json object for a player Returns the updated valid array for the team | function fixSingleRole(valid, player, role) {
//slot 1:1 except when we have to fix jungle issues
if(role === 'Jungle' && !player['Smite']) {
var jungler = findJungler(valid);
if(!jungler) { // nobody has smite so we're jungle by default
player['Role'] = role;
valid.push(player);
return valid;
}
player['Role'] = jungler['Role'];
jungler['Role'] = 'Jungle';
valid.push(jungler);
valid.push(player);
}
else {
player['Role'] = role;
valid.push(player);
}
return valid;
} | [
"function verifyOneOfEachRoleInRecommendedTeam(){\n //Figure out what roles are missing\n var rolesToBeAdded = new Array();\n for (var i in classesMap)\n if (classesMap[i] == 0)\n rolesToBeAdded.push(i);\n\n //Starting from the rear, find the lowest scoring hero with more than 1 other hero in it's role, and replace it with the highest scoring hero from the unfilled role\n rolesToBeAdded.forEach(function (role, index) {\n for (i = 5; i >= 0; i--) {\n var potentialHeroToReplace = recommendedTeam[i];\n if (role == \"Healer\")\n var roleHeroes = getHealersArray();\n else\n var roleHeroes = getSortedRoleByName(role);\n if (classesMap[potentialHeroToReplace.role] > 1) {\n recommendedTeam[i] = getHeroByName(roleHeroes[0].name)\n i = -1; //Kill the loop since the missing role has been filed\n }\n }\n });\n}",
"function assignRoles() { // TODO: Figure out what to do in games of more than 6 players\n rng();\n\n players[arr[0]].TEAM = 'Mafia';\n players[arr[0]].ROLE = 'Mafia';\n\n players[arr[1]].TEAM = 'Mafia';\n players[arr[1]].ROLE = 'Mafia';\n \n players[arr[2]].TEAM = 'Village';\n players[arr[2]].ROLE = 'Doctor';\n\n players[arr[3]].TEAM = 'Village';\n players[arr[3]].ROLE = 'Sheriff';\n\n players[arr[4]].TEAM = 'Village';\n players[arr[4]].ROLE = 'Villager';\n\n players[arr[5]].TEAM = 'Village';\n players[arr[5]].ROLE = 'Villager';\n}",
"assignRoles() {\n const available = roles[this.players.length];\n\n shuffle(available);\n\n this.players.forEach((player, i) => {\n player.role = available[i];\n });\n }",
"playerRoleAttribution() {\r\n const blueTeam = this.getBlueTeam();\r\n const redTeam = this.getRedTeam();\r\n\r\n for (let i=0; i<blueTeam.length; i++) {\r\n blueTeam[i].role = 'Agent';\r\n }\r\n for (let i=0; i<redTeam.length; i++) {\r\n redTeam[i].role = 'Agent';\r\n }\r\n\r\n this.redTeam = shuffle(redTeam);\r\n this.blueTeam = shuffle(blueTeam);\r\n this.redTeam[0].role = 'Spy';\r\n this.blueTeam[0].role = 'Spy';\r\n }",
"removeUsersFromTeamRoles(users, roles) {\n if (typeof users === 'string') {\n users = [users];\n }\n if (typeof roles === 'string') {\n roles = [roles];\n }\n\n //if removing the 'member' role from users, completely remove them from all roles and from the group\n if (roles.indexOf('member') !== -1) {\n this.removeUsers(users)\n }\n\n for (let i = 0; i < users.length; i++) {\n }\n }",
"initRoles() {\n const roles = []\n const n = this.players.length\n if (n < 4) {\n this.end()\n }\n let setup\n if (SETUP == 'default') {\n setup = _.find(setups[n], { id: 'default' })\n } else if (SETUP == 'random') {\n setup = _.sample(setups[n])\n } else {\n setup = _.find(setups[n], { id: SETUP })\n if (!setup) {\n setup = _.find(setups[n], { id: 'default' })\n }\n }\n\n if (!setup) {\n this.postMessage(this.getTownRoom(), str.noSetup(n))\n .then(() => this.end())\n }\n\n _.forEach(setup.roles, role => {\n roles.push(new Role(_.find(arrayRoles, { name: role })))\n })\n _.forOwn(setup.configurations, (count, category) => {\n let possibleRoles = _.filter(arrayRoles, { category: category })\n for (let i = 0; i < count; i++) {\n let role = _.sample(possibleRoles)\n while (!this.validateRole(role, roles)) {\n role = _.sample(possibleRoles)\n }\n role = new Role(role)\n roles.push(role)\n }\n })\n if (roles.length < n)\n roles.fill(new Role(_.find(arrayRoles, { name: 'Citizen'}) ,roles.length - 1, n))\n return _.shuffle(roles)\n }",
"static fromJSON(roles) {\n let result = [];\n \n if (Array.isArray(roles)) {\n roles.forEach((s) => {\n Object.setPrototypeOf(s, Role.prototype);\n result.push(s);\n })\n }\n // it's a single object and not an array\n else {\n let s = roles;\n Object.setPrototypeOf(s, Role.prototype);\n result.push(s);\n }\n \n return result;\n }",
"firstArrayOfInnocent(){\n for(let i = 0; i < (this.totalPlayers); i++){\n this.arrayOfRoles.push(RolesEnum.INNOCENT);\n this.arrayOfGroupForEachRole.push(1);\n }\n }",
"updateTeamData(teamData) {\n const teams = JSON.parse(teamData);\n\n this.setState((state, props) => {\n return state.teams\n ? {\n teams: state.teams.map(stateTeam => {\n const t = teams.find(t => stateTeam.id === t.id);\n return {\n ...stateTeam,\n ...t,\n players: (stateTeam.players || []).map(statePlayer => ({\n ...statePlayer,\n ...t.players.find(player => player.id === statePlayer.id)\n })),\n }\n }),\n }\n : {teams}\n });\n }",
"function assignRoles(list) {\n let roleList = [\"Godfather\", \"Jailor\"],\n playerList = Object.keys(list)\n \n // Fill role arrays with each type and subtype (so role assignment can pull randomly from the lists)\n for (var i = 0, index; i < Object.keys(roles).length; i++) {\n index = roles[Object.keys(roles)[i]]\n \n if (index.team === \"town\") {\n if (index.type === \"necessary\") continue\n if (index.type === \"protection\") townProtective.push(index.name)\n if (index.type === \"support\") townSupport.push(index.name)\n if (index.type === \"killing\") townKilling.push(index.name)\n if (index.type === \"investigative\") townInvestigative.push(index.name)\n }\n if (index.team === \"mafia\") {\n if (index.name === \"Godfather\") continue\n else mafia.push(index.name)\n }\n if (index.team === \"neutral\") {\n if (index.type === \"benign\") neutralBenign.push(index.name)\n if (index.type === \"evil\") neutralEvil.push(index.name)\n if (index.type === \"killing\") neutralKilling.push(index.name)\n }\n }\n \n // Loop through the given array and add a random index to roleList\n function addRandomRole(arr) {\n // If trying to pull a role from an empty array. Currently set to doctor since I believe the only way this is possible is with a town array\n if (arr.length === 0) {\n console.log(\"[ Empty array ], Doctor\")\n roleList.push('Doctor')\n }\n else {\n var rand = getRandomInt(0, arr.length - 1)\n console.log(arr + \", \" + rand)\n roleList.push(arr[rand])\n arr.splice(rand, 1)\n }\n }\n \n // Add roles to list (per number of players)\n if (playerList.length >= 7) {\n addRandomRole(townProtective)\n addRandomRole(townSupport)\n addRandomRole(townInvestigative)\n addRandomRole(neutralEvil)\n addRandomRole(mafia)\n }\n if (playerList.length >= 8) {\n var j = getRandomInt(0, 3)\n if (j === 0) addRandomRole(townProtective)\n else if (j === 1) addRandomRole(townSupport)\n else if (j === 2) addRandomRole(townKilling)\n else if (j === 3) addRandomRole(townInvestigative)\n }\n if (playerList.length >= 9) addRandomRole(mafia)\n if (playerList.length >= 10) addRandomRole(townKilling)\n if (playerList.length >= 11) addRandomRole(neutralKilling)\n if (playerList.length >= 12) addRandomRole(townInvestigative)\n if (playerList.length >= 13) {\n var j = getRandomInt(0, 3)\n if (j === 0) addRandomRole(townProtective)\n else if (j === 1) addRandomRole(townSupport)\n else if (j === 2) addRandomRole(townKilling)\n else if (j === 3) addRandomRole(townInvestigative)\n }\n if (playerList.length >= 14) addRandomRole(neutralBenign)\n if (playerList.length >= 15) {\n var j = getRandomInt(0, 3)\n if (j === 0) addRandomRole(townProtective)\n else if (j === 1) addRandomRole(townSupport)\n else if (j === 2) addRandomRole(townKilling)\n else if (j === 3) addRandomRole(townInvestigative)\n }\n if (playerList.length >= 16) addRandomRole(mafia)\n if (playerList.length >= 17) {\n var j = getRandomInt(0, 3)\n if (j === 0) addRandomRole(townProtective)\n else if (j === 1) addRandomRole(townSupport)\n else if (j === 2) addRandomRole(townKilling)\n else if (j === 3) addRandomRole(townInvestigative)\n }\n if (playerList.length >= 18) {\n var j = getRandomInt(0, 3)\n if (j === 0) addRandomRole(townProtective)\n else if (j === 1) addRandomRole(townSupport)\n else if (j === 2) addRandomRole(townKilling)\n else if (j === 3) addRandomRole(townInvestigative)\n }\n if (playerList.length >= 19) addRandomRole(mafia)\n if (playerList.length === 20) {\n var j = getRandomInt(0, 1)\n if (j === 0) addRandomRole(neutralBenign)\n else addRandomRole(neutralEvil)\n }\n \n // Log roles\n game.roles = roleList\n console.log(game.roles)\n \n // Randomly assign roles to players\n for (var i = roleList.length - 1, rand; i > -1; i--) {\n rand = getRandomInt(0, i)\n list[playerList[i]].role = roleList[rand]\n roleList.splice(rand, 1)\n }\n}",
"validateResponse (data) {\n\t\tconst myTeams = [this.team];\n\t\tthis.validateMatchingObjects(myTeams, data.teams, 'teams');\n\t\tthis.validateSanitizedObjects(data.teams, TeamTestConstants.UNSANITIZED_ATTRIBUTES);\n\t}",
"function createRoleArray() {\n\n //Initiate default values\n randomSetter = numPlayers-1;\n roleArray = ['.','.','.','.','.','.','.'];\n tempArray = ['0','1','2','3','4','5','6'];\n\n //Account for extra players\n for(var i = 7; i < numPlayers; i++ ) {\n tempArray.push(i);\n roleArray.push('.');\n }\n //set mordred\n var mordIndex = getRandomInt(0,randomSetter);\n mordred = tempArray[mordIndex];\n roleArray[tempArray[mordIndex]] = 'Mordred';\n tempArray.splice(mordIndex,1);\n numSpies--;\n randomSetter--;\n\n //set morgana if needed\n if(morgana != null) {\n var morgIndex = getRandomInt(0,randomSetter);\n roleArray[tempArray[morgIndex]] = 'Morgana';\n morgana = tempArray[morgIndex];\n tempArray.splice(morgIndex,1);\n numSpies--;\n randomSetter--;\n\n }\n\n //set oberon if needed\n if(oberon != null) {\n var obIndex = getRandomInt(0,randomSetter);\n roleArray[tempArray[obIndex]] = 'Oberon';\n oberon = tempArray[obIndex];\n tempArray.splice(obIndex,1);\n numSpies--;\n randomSetter--;\n }\n\n //set remaining spies\n for(var i = 0; i < numSpies; i++) {\n var spyIndex = getRandomInt(0,randomSetter);\n roleArray[tempArray[spyIndex]] = 'Spy'+(i);\n tempArray.splice(spyIndex,1);\n randomSetter--;\n }\n\n //set merlin\n var merlinIndex = getRandomInt(0,randomSetter);\n roleArray[tempArray[merlinIndex]] = 'Merlin';\n merlin = tempArray[merlinIndex];\n tempArray.splice(merlinIndex,1);\n numResistance--;\n randomSetter--;\n\n //set percival\n var percIndex = getRandomInt(0,randomSetter);\n roleArray[tempArray[percIndex]] = 'Percival';\n percival = tempArray[percIndex];\n tempArray.splice(percIndex,1);\n numResistance--;\n\n //set remaining civs\n for(var i = 0; i < numResistance; i++) {\n roleArray[tempArray[0]] = 'Civilian';\n tempArray.splice(0,1);\n }\n\n}",
"function getMissingRoles(data) {\n var roles = ['Top', 'Jungle', 'Mid', 'ADC', 'Support'];\n for(var i = 0; i < data.length; i++) {\n for(var j = 0; j < roles.length; j++) {\n if(roles[j] === data[i]['Role']) {\n roles.splice(j, 1);\n break;\n }\n }\n }\n return roles;\n}",
"function validateRoles(roles) { return roles; }",
"function reorganize_team(old_team) {\n\n var new_team = old_team;\n\n //leader, member, member, leader, member, member ....\n\n var leader_identity; //players becoming members will be tied to this leader\n var i = 0;\n\n while (i < new_team.IDs.length) {\n var roleDecider = i % 3;\n //this player will become a leader\n if (roleDecider == 0) {\n new_team[new_team.IDs[i]].role = \"LEADER\";\n new_team[new_team.IDs[i]].leader = null;\n new_team[new_team.IDs[i]].radius = determine.player_radius(\"LEADER\");\n //save this player's details as this will be the leader for following players\n leader_identity = {\n id: new_team[new_team.IDs[i]].id,\n name: new_team[new_team.IDs[i]].name\n };\n }\n //this player will become a member\n else if (roleDecider == 1 || roleDecider == 2) {\n new_team[new_team.IDs[i]].role = \"MEMBER\";\n new_team[new_team.IDs[i]].leader = leader_identity;\n new_team[new_team.IDs[i]].radius = determine.player_radius(\"MEMBER\");\n }\n i++;\n }\n\n return new_team;\n}",
"function one_night(original_roles,inputs){\n var roles = original_roles.slice()\n var output = Array(inputs.length).fill(\"\")\n var temp = 0\n var werewolf = []\n var mason = []\n var string = \"\"\n for(i = 0; i<inputs.length;i++){ \n if(original_roles[i]==\"Robber\"){\n roles[i] = roles[inputs[i][0][0]]\n roles[inputs[i][0][0]] = \"Robber\"\n //console.log(inputs[i][0][0])\n output[i]=`You have changed your roles with ${inputs[i][0][0]}`\n }else if(original_roles[i]==\"Werewolf\"){\n werewolf.push(i)\n }else if(original_roles[i]==\"Mason\"){\n mason.push(i)\n }\n }\n for(i = 0; i<inputs.length;i++){\n switch(original_roles[i]) {\n case \"Villager\":\n output[i]=\"You're a lazy fuck that didn't do anything but masturbate at night\"\n break\n case \"Werewolf\":\n string = \"The Werewolves are:\"\n output[i]= string.concat(werewolf.toString())\n break\n case \"Minion\":\n string = \"The Werewolves are:\"\n output[i]= string.concat(werewolf.toString())\n break\n case \"Seer\":\n if(inputs[i][0][0] != null){\n output[i] = `The role of (${inputs[i][0][0]}) is ${roles[inputs[i][0][0]]} and The role of (${inputs[i][0][1]}) is ${roles[inputs[i][0][1]]}`\n }else if(inputs[i][1][0] != null){\n output[i] = `The role of (${inputs[i][1][0]}) is ${original_roles[inputs[i][1][0]]}`\n }else{\n console.log(\"Seer didn't have inputs?\")\n }\n break\n case \"Troublemaker\":\n temp = roles[inputs[i][0][0]]\n roles[inputs[i][0][0]] = roles[inputs[i][0][1]]\n roles[inputs[i][0][1]] = temp\n output[i]=`Roles (${inputs[i][0][0]}) and (${inputs[i][0][1]}) have been changed`\n break\n case \"Tanner\":\n output[i]=\"Time to die\"\n break\n case \"Drunk\":\n roles[i] = roles[inputs[i][1][0]]\n roles[inputs[i]] = \"Drunk\"\n output[i]=\"You have no idea what the fuck you are\"\n break\n case \"Hunter\":\n output[i]=\"Wow, a hunter that's too scared to hunt at night\"\n break\n case \"Mason\":\n string = \"The Masons are:\"\n output[i]= string.concat(mason.toString())\n break\n }\n }\n \n for(i = 0; i<inputs.length;i++){\n switch(original_roles[i]) {\n case \"Insomniac\":\n output[i]=`Your role is ${roles[i]}`\n break\n }\n }\n return output,roles;\n}",
"validTeamComps(number_of_players = 6) {\n // Get all permutations of team\n let valid = utils.permutations([...Array(number_of_players).keys()]);\n\n // Can person even play the role given to them\n valid = valid.filter(comp => {\n for (let i = 0; i < 6; i++) {\n let p = comp[i];\n if (p < this.players.length) {\n if (utils.getRole(this.players[p].role, i) == 0) {\n return false;\n }\n }\n }\n return true;\n });\n\n return valid;\n }",
"refreshAvailableRoles() {\n if (this.state.roles.all.length === 0) {\n return;\n }\n\n actors.forEach((actor) => {\n const roles = this.state.roles[actor];\n roles.available = this.state.roles.all.slice();\n roles.current.forEach((role) => {\n const idx = roles.available.indexOf(role);\n if (idx !== -1) {\n roles.available.splice(idx, 1);\n }\n });\n });\n }",
"createRoles(players, roles) {\n let playersRandomized;\n let rolesRandomized;\n\n playersRandomized = this.shuffleArray(players);\n rolesRandomized = this.shuffleArray(roles);\n\n return [playersRandomized, rolesRandomized];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether saved data and form data are different to avoid unnecessary popup. | function isSavedDataAndFormDataDifferent(){
var savedData = getSavedData();
var formData = getFormData();
delete(savedData._autosaveTime);
delete(formData.item);
return JSON.stringify(savedData) !== JSON.stringify(formData);
} | [
"function isSavedDataAndFormDataDifferent(){\n var savedData = getSavedData();\n var formData = getFormData();\n\n delete(savedData._autosaveTime);\n delete(formData.item);\n\n return JSON.stringify(savedData) !== JSON.stringify(formData);\n }",
"function hasDataChanged() {\n if (!$scope.submissionLoaded) {\n return false;\n }\n\n var inputData = getInputData();\n if (!originalData || typeof originalData.title == 'undefined') {\n // There is no original data, assume it hasn't changed.\n return false;\n }\n\n if (originalData.title != inputData.title || originalData.text != inputData.content) {\n return true;\n }\n\n return $mmFileUploaderHelper.areFileListDifferent(inputData.attachmentfiles, originalData.attachmentfiles);\n }",
"function checkFormState (){ \n\tif (formModified)\n\t\treturn 'There are unsaved changes';\n}",
"function checkChange(){\n var currentVars = new Array();\n var form;\n var ret = true;\n var oldValue;\n var newValue;\n\n arrayOmitItems = omitInput.split(';');\n arrayOmitForms = omitForm.split(';');\n\n for (index = 0; index < document.forms.length; index++) {\n\n currentVars[index] = $(document.getElementById(document.forms[index].id)).serialize();\n\n if(existOmitForm(document.forms[index].id) == true){\n continue;\n }\n tmp1 = arrayInputVar[index];\n oldValue = cutElement(tmp1);\n tmp2 = currentVars[index];\n newValue = cutElement(tmp2);\n\n if(compareInputVar(oldValue, newValue) == false){\n ret = false;\n break;\n }\n }\n return ret;\n}",
"function isDirty(){\n if(this.dataBkp && this.data){\n //TODO:\n //HACK:\n //For now \"photo\" is ignored, as its dataURI changes when redrawing on canvas. I don't know why yet.\n //Just opening a object with a photo and then leaving it results in \"Leaving unsaved changes\" which is wrong\n //Removing \"photo\" before comparison won't detect changes in photo, but it gets rid of this error.\n var dataBkp = angular.copy(this.dataBkp);\n var data = angular.copy(this.data);\n delete dataBkp.photo;\n delete data.photo;\n\n var dataBkpStr = angular.toJson(dataBkp);\n var dataStr = angular.toJson(data);\n\n //Ignore empty objects by removing them before comparison:\n //This is a hack to handle Patient's related-contact's contact-number's dummy object\n //This dummy is added when a related contact tab is opened (by then patien's dataBkp is already set)\n dataStr = removeSubstring(dataStr, ',{}', '');\n dataBkpStr = removeSubstring(dataBkpStr, ',{}', '');\n\n return dataBkpStr !== \"\" && dataBkpStr !== dataStr;\n }else{\n //if we have no way of saying, we assume it is\n console.debug('No way of saying if tab is dirty, assume it is.');\n return true;\n }\n }",
"function CheckEditedFields() {\n var edited = $('.edited_field');\n var form = $('.unsaved_form');\n\n if (edited.length != 0 || form.length != 0) {\n return 'Warning: Uncommitted data detected. Please confirm.';\n }\n }",
"function isPopupDirty()\n{\n var popupDirty = false;\n // Get the current state of the form\n newPopupState = getPopupFormState();\n // Compare it to the old state\n for (var key in newPopupState)\n {\n if (newPopupState[key] != initialPopupFormState[key])\n {\n popupDirty = true;\n break;\n }\n }\n return popupDirty;\n}",
"function observedFormsStatusHasChanged(){\n var unsaved_changes = false;\n observedForms().each(function(){\n if ( !$(this).data(\"being-submitted\") ) {\n if (serializedFormStatus($(this)) != formSerialization($(this))) {\n unsaved_changes = true;\n }\n }\n });\n return unsaved_changes;\n}",
"function isSame() {\r\n\t\t\t/*when the input_A is currect and input_B.val>0 ,then compare*/\r\n\t\t\tif (input_el_A.val().match(reg) && input_el_B.val().length > 0) {\r\n\t\t\t\tif (input_el_A.val() == input_el_B.val()) {\r\n\t\t\t\t\tel_B_currect.show();\r\n\t\t\t\t\tel_B_msg.hide();\r\n\t\t\t\t\tpassAll = true;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tel_B_msg.show().find('span').text(validate_txt.vtxt_8);\r\n\t\t\t\t\tel_B_currect.hide();\r\n\t\t\t\t\tpassAll = false;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tel_B_currect.hide();\r\n\t\t\t}\r\n\t\t}",
"function dirtyForm() {\n\t/* If cleanForm() has not run we assume that user has not modified the\n\t form. This only occurs when the user changes pages before the\n page loads. */\n\tif (formClean == null) { \n\t\treturn true;\n\t}\n\n\tvar c = 0;\n\n\tfor(var i = 0; i < formCollection.length; i++) {\n\t\tthisForm = formCollection[i];\n\t\t\n\t\tfor(var x = 0; x < thisForm.elements.length; x++) { \n\t\t\tif (formClean[c] != getFormElementValue(thisForm, x)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tc = c+1;\n\t\t}\n\t}\t\n\treturn true;\n}",
"function checkAbsenceSaveButton() {\n\n\tvar saveDisabled=_controls.saveButton.disabled;\n\tvar continueChecking=true;\n\t\n\tif (_controls.userName != undefined) {\n\t\t// manage absence page active, check if userName is set \n\t\tif (_controls.userName.value == \"\") {\n\t\t\tsaveDisabled = true;\n\t\t\tcontinueChecking = false; // no more checking needed, save button disabled \n\t\t} else {\n saveDisabled = false; \t\n\t\t}\t\n\t}\n\t\n\tif (continueChecking==true) {\n\t\tvar fromDate=null, toDate=null;\n\t\tif (_controls.rbPermanently.checked){\n\t\t\tfromDate=getDatePickerValue(_controls.fromDatePicker);\n\t\t\tif (fromDate==null) {\n\t\t\t\tsaveDisabled = true;\n\t\t\t} else {\n\t\t\t\tsaveDisabled = false; \t\n\t\t\t}\t\n\t\t} else if (_controls.rbTemporary.checked){\n\t\t\tfromDate=getDatePickerValue(_controls.fromDatePicker);\n\t\t\ttoDate=getDatePickerValue(_controls.toDatePicker);\n\t\t\tif (fromDate==null || toDate==null) {\n\t\t\t\tsaveDisabled = true;\n\t\t\t} else {\n\t\t\t\tsaveDisabled = false; \t\n\t\t\t}\t\n\t\t} else {\n\t\t\tsaveDisabled = false;\n\t\t}\t\n\t}\t\n\t\n\t// toggle okButton?\n\tif (saveDisabled!=_controls.saveButton.disabled) {\n\t\t_controls.saveButton.disabled=saveDisabled;\n\t}\n\t// hide the message areas, since changes are done by user \n\tshowMessages(false);\n}",
"function checkUnsavedChanges()\n{\n\tif(store && store.isDirty && store.isDirty())\n\t\t{\n\t\tif(confirm(config.messages.unsavedChangesWarning))\n\t\t\tsaveChanges();\n\t\t}\n}",
"function IsDirty() {\r\n if (!hrefDirtyBypass) {\r\n // Variable to hold all the forms on a page\r\n var booDirtyForm = false;\r\n booDirtyForm = isPageChanged();\r\n /*\r\n * If the form is dirty prompt the user before leaving the page.\r\n */\r\n if (( pageDirtyFlag || booDirtyForm ) && !isDirtyCalled) {\r\n event.returnValue = \"Your unsaved data will be lost.\";\r\n //MessageBox.show(\"Version: Visual J++ 6.0\", \"MyNotepad\");\r\n }\r\n isDirtyCalled = false;\r\n }\r\n hrefDirtyBypass = false;\r\n}",
"function checkUnsavedChanges()\n{\n\tif(store && store.isDirty && store.isDirty() && window.hadConfirmExit === false) {\n\t\tif(confirm(config.messages.unsavedChangesWarning))\n\t\t\tsaveChanges();\n\t}\n}",
"function validateUnsavedProperties() {\n if ($(\"#properties_ename\").val() !== '' && !saveClicked) {\n alert(\"Please save entered properties first\");\n return false;\n } else {\n saveClicked = false;\n return true;\n }\n }",
"checkLocalStorage() {\n FormFunctsObj.setCategoryFromStorage();\n FormFunctsObj.updateFormFromStorage();\n }",
"function isTableSaved()\n{\n\tif(masterFormString != $(\"#form\").serialize())\n\t{\n\t\tif(hasTableBeenSaved)\n\t\t{\n\t\t\tchangeTableSaveStatusIcon($('#results'), false);\n\t\t\tsetGridTableSaveStatusToolTip($('#results'), 'Current showing table has been modified since retrieving it from the server.');\n\t\t\thasTableBeenSaved = false;\n\t\t\t// this is needed here because in order to generate the dendogram, we use the values\n\t\t\t// that are stored, and if the table is saved which means that the values shown are\n\t\t\t// the same as in the database, then we can generate\n\t\t\tisGridComplete();\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(!hasTableBeenSaved)\n\t\t{\n\t\t\tchangeTableSaveStatusIcon($('#results'), true);\n\t\t\tsetGridTableSaveStatusToolTip($('#results'), 'Current showing table has not been modified since retrieving it from the server.');\n\t\t\thasTableBeenSaved= true;\n\t\t\tisGridComplete();\n\t\t}\n\t}\n}",
"function _isDataModified()\r\n {\r\n var dataMod = false;\r\n\r\n //alert(\"htmldata.js -> _isDataModified \\n chgFlds: \" + this._mChangedFields);\r\n for (var index = 0; index < this._mChangedFields.length; ++index)\r\n {\r\n var item = this._mChangedFields[index];\r\n var obj = getElemnt(item);\r\n\r\n // alert(obj.outerHTML + \" \\n \" + _isChangeFieldNotify(obj));\r\n\r\n if(obj && _isChangeFieldNotify(obj))\r\n {\r\n\r\n dataMod = true;\r\n break;\r\n }\r\n }\r\n //alert(\"isDataModified \" + dataMod);\r\n return dataMod;\r\n }",
"function checkFormChanged(objForm) {\r\n\r\n\tvar localForm;\r\n\tvar showMessage = false;\r\n\tvar recalcVariableDefined = false;\r\n\tif (objForm != null) {\r\n\t\tlocalForm = objForm;\r\n\t} else {\r\n\t\tlocalForm = currentOmniForm;\r\n\t}\r\n\tif (localForm != null) {\r\n\t\t<!-- Bug fix: OMNI00003444 -->\r\n\t\tif (localForm.needsRecalc) {\r\n\t\t\tif (localForm.needsRecalc.value == 'true') {\r\n\t\t\t\tvar confirmMessage = \"If you have entered, updated or modified any data that will calculate or change the ERD, you must invoke the calculate process before leaving this page.\\n\";\r\n\t\t\t\tconfirmMessage += \" ** Sentence calculations are not up-to-date **\\n\\n\";\r\n\t\t\t\tconfirmMessage += \"Click Cancel to return to the screen to recalculate before navigating from this page.\\n\\n\";\r\n\t\t\t\tconfirmMessage += \"Click OK to proceed without recalculating.\";\r\n\t\t\t\tshowMessage = true;\r\n\t\t\t}\r\n\t\t\trecalcVariableDefined = true;\r\n\t\t}\r\n\t\tif ((localForm.isDirty && localForm.isDirty.value == 'true') || (!recalcVariableDefined && hasFormChanged(localForm))) {\r\n\t\t\t//debug stuff\r\n\t\t\t//alert(\"localForm.isDirty: \"+localForm.isDirty);\r\n\t\t\t//alert(\"localForm.isDirty.value: \"+localForm.isDirty.value);\r\n\t\t\t//alert(\"recalcVariableDefined: \"+recalcVariableDefined);\r\n\t\t\t//alert(\"hasFormChanged(localForm): \"+hasFormChanged(localForm));\r\n\r\n\t\t\tvar confirmMessage = getIsDirtyConfirmMessage();\r\n\t\t\tshowMessage = true;\r\n\t\t}\r\n\t\tif (showMessage == true) {\r\n\t\t\thasWarningMessageForFormChangedOccurred = true;\r\n\t\t\tif (window.confirm(confirmMessage)) {\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checkDate (yearField, monthField, dayField, STRING labelString [, OKtoOmitDay==false]) Check that yearField.value, monthField.value, and dayField.value form a valid date. If they don't, labelString (the name of the date, like "Birth Date") is displayed to tell the user which date field is invalid. If it is OK for the day field to be empty, set optional argument OKtoOmitDay to true. It defaults to false. | function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{ // Next line is needed on NN3 to avoid "undefined is not a number" error
// in equality comparison below.
if (checkDate.arguments.length == 4) OKtoOmitDay = false;
if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
else if (!isDay(dayField.value))
return warnInvalid (dayField, iDay);
if (isDate (yearField.value, monthField.value, dayField.value))
return true;
alert (iDatePrefix + labelString + iDateSuffix)
return false
} | [
"function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)\r\n{ // Next line is needed on NN3 to avoid \"undefined is not a number\" error\r\n // in equality comparison below.\r\n if (checkDate.arguments.length == 4) OKtoOmitDay = false;\r\n if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);\r\n if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);\r\n if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;\r\n else if (!isDay(dayField.value))\r\n return warnInvalid (dayField, iDay);\r\n if (isDate (yearField.value, monthField.value, dayField.value))\r\n return true;\r\n alert (iDatePrefix + labelString + iDateSuffix)\r\n return false\r\n}",
"function checkDateX(yearField, monthField, dayField, labelString, OKtoOmitDay) { // Next line is needed on NN3 to avoid 'undefined is not a number' error\r\n // in equality comparison below.\r\n if (checkDate.arguments.length == 4) OKtoOmitDay = false;\r\n if (!isYear(yearField.value)) return warnInvalid(yearField, iYear);\r\n if (!isMonth(monthField.value)) return warnInvalid(monthField, iMonth);\r\n if ((OKtoOmitDay == true) && isEmpty(dayField.value)) return true;\r\n else if (!isDay(dayField.value))\r\n return warnInvalid(dayField, iDay);\r\n if (isDate(yearField.value, monthField.value, dayField.value))\r\n return true;\r\n alert(iDatePrefix + labelString + iDateSuffix)\r\n return false\r\n}",
"function SP_CheckValidDate(day,month,year)\n{\n\tvar showErrMsg = false;\n\t\n\t// check entered year should be greater than 1900 and less than 2200. And check entered month value is in between 1 - 12\n\tif((year*1 < 1900 || year*1 >2200) || (month*1 < 1 || month*1 > 12))\n\t{\n\t\tshowErrMsg = true;\n\t\treturn showErrMsg;\n\t}\n\t\n\t//Create Date, month decremented because in JS date object month are from (0 - 11)\n\tvar oDate = new Date(year,--month);\n\tmonth = oDate.getMonth();\n\toDate.setDate(day);\n\t\n\t// Check entered day is correct as per selected month\n\t// Feburary case. total days in month are 28 or 29\n\tif(!(month*1 == oDate.getMonth()*1))\n\t{\n\t\tshowErrMsg = true;\n\t}\n\treturn showErrMsg;\n}",
"function DateValidation(dd, mm, yy, msg) {\n\t\n\t \n\t if(NumValidation(dd,'Date','','num') == 0)\n\t return 0;\n\t \n\t if(NumValidation(mm,'Month','','num') == 0)\n\t return 0;\n\t \n\t if(NumValidation(yy,'Year','','num') == 0)\n\t return 0;\n\t \n\t\n\t \n\t d = parseInt(dd.value);\n\t m = parseInt(mm.value);\n\t y = parseInt(yy.value);\n\t \n\t if(m > 12 || m == 0) {\n\t\talert(\"Invalid month selected for \" + msg);\n\t\tmm.focus();\n\t\treturn 0;\n\t }\n\t else {\n\t \n\t var vDays = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];\n\t var flag = 0;\n\t if(m == 2) {\n\t\tif(isLeapYear(y)) {\n\t\t if( d > 29 || d < 1 ) {\n\t\t flag = 0;\n\t\t }\n\t\t else {\n\t\t flag = 1;\n\t\t }\n\t\t}\n\t\telse if( d > vDays[m] || d < 1 ) {\n\t\t flag = 0;\n\t\t}\n\t\telse {\n\t\t\t flag = 1;\n\t\t}\n\t }\n\t else {\n\t\tif( d > vDays[m] || d < 1 ) {\n\t\t flag = 0;\n\t\t}\n\t\telse {\n\t\t flag = 1;\n\t\t} \n\t }\n\t }\n\t if(flag == 0) {\n\t\n\t\talert(\"Invalid day selected for \" + msg);\n\t\n\t\tdd.focus();\n\t\treturn 0;\n\t }\n\t else {\n\t\treturn 1;\n\t }\n\t \n\t \n\t} // closing the function DateValidation() ",
"function isDate(gField,minYear,maxYear) { \n\tvar inputStr = gField.value; \n\t// convert hyphen delimiters to slashes \n\twhile (inputStr.indexOf(\"-\") != -1) { \n\t\tvar regexp = /-/;\n\t\tinputStr = inputStr.replace(regexp,\"/\"); }\n\tvar delim1 = inputStr.indexOf(\"/\")\n\tvar delim2 = inputStr.lastIndexOf(\"/\")\n\tif (delim1 != -1 && delim1 == delim2) { \n\t\t// there is only one delimiter in the string\n\t\talert(\"The date entry is not in an acceptable format.\\n\\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy. (If the month or date data is not available, enter \\'01\\' in the appropriate location.)\")\n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false }\n\tif (delim1 != -1) { \n\t\t// there are delimiters; extract component values\n\t\tvar mm = parseInt(inputStr.substring(0,delim1),10)\n\t\tvar dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)\n\t\tvar yyyy = parseInt(inputStr.substring(delim2 + 1, inputStr.length),10)\n\t} else { \n\t\t// there are no delimiters; extract component values\n\t\tvar mm = parseInt(inputStr.substring(0,2),10)\n\t\tvar dd = parseInt(inputStr.substring(2,4),10)\n\t\tvar yyyy = parseInt(inputStr.substring(4,inputStr.length),10)\n\t}\n\tif (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) { \n\t\t// there is a non-numeric character in one of the component values\n\t\talert(\"The date entry is not in an acceptable format.\\n\\nYou can enter dates in the following formats: mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy.\") \n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false\n\t}\n\tif (mm < 1 || mm > 12) { \n\t\t// month value is not 1 thru 12 \n\t\talert(\"Months must be entered between the range of 01 (January) and 12 (December).\")\n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false\n\t} \n\tif (dd < 1 || dd > 31) { \n\t\t// date value is not 1 thru 31 \n\t\talert(\"Days must be entered between the range of 01 and a maximum of 31 (depending on the month and year).\")\n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false\n\t} \n\t// validate year, allowing for checks between year ranges \n\t// passed as parameters from other validation functions\n\tif (yyyy < 100) { \n\t\t// entered value is two digits, which we allow for 1930-2029\n\t\talert(\"Year must be entered in four-digit format. Please try again!\")\n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false\n\t}\n\tif (yyyy < minYear || yyyy > maxYear) {\n\t\talert(\"Year must be entered between the range of \" + minYear + \" and \" + maxYear + \".\"); \n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false\n\t}\t\n\tif (!checkMonthLength(mm,dd)) {\n\t\tgField.focus()\n\t\tgField.select()\n\t\treturn false\n\t}\n\tif (mm == 2) {\n\t\tif (!checkLeapMonth(mm,dd,yyyy)) {\n\t\t\tgField.focus() \n\t\t\tgField.select()\n\t\t\treturn false\n\t\t}\n\t}\n\tgField.value = mm + \"/\" + dd + \"/\" + yyyy;\n\treturn true;\n}",
"function chkDate(obj,format,checkFlag) \n{\n var strDatestyle = format; \n var strDate;\n var strDateArray;\n var strDay;\n var strMonth;\n var strYear;\n var intday;\n var intMonth;\n var intYear;\n var booFound = false;\n var datefield = eval(obj);\n var strSeparatorArray = new Array(\"-\",\"/\");\n var intElementNr;\n\n strDate = datefield.value;\n\n if (strDate.length < 1)\n {\n alert(\"Enter valid date\");\n return false;\n }\n if (strDate.length > strDatestyle.length)\n {\n alert(\"Enter valid date\");\n return false;\n }\n for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) \n {\n if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) \n {\n strDateArray = strDate.split(strSeparatorArray[intElementNr]);\n if (strDateArray.length != 3) \n {\n alert(\"Enter valid date\");\n return false;\n }\n else \n {\n strDay = strDateArray[0];\n strMonth = strDateArray[1];\n strYear = strDateArray[2];\n }\n booFound = true;\n }\n }\n if (booFound == false) \n {\n alert(\"Enter valid date\");\n return false;\n }\n \n if (strYear)\n {\n if (strYear.length == 2) \n {\n strYear = '20' + strYear;\n }\n if (strYear.length != 4) \n {\n alert(\"Enter valid year\");\n return false;\n }\n } \n \n // Check for date format\n if ( (strDatestyle.toUpperCase() ==\"MM/DD/YYYY\") || (strDatestyle.toUpperCase() ==\"MM-DD-YYYY\") ) \n {\n strTemp = strDay;\n strDay = strMonth;\n strMonth = strTemp;\n }\n \n intday = parseInt(strDay, 10);\n if (isNaN(intday)) \n {\n alert(\"Enter valid day\");\n return false;\n }\n \n intMonth = parseInt(strMonth, 10);\n if (isNaN(intMonth)) \n {\n alert(\"Enter valid month\");\n return false;\n }\n \n intYear = parseInt(strYear, 10);\n if (isNaN(intYear)) \n {\n alert(\"Enter valid year\");\n return false;\n }\n \n if (intMonth>12 || intMonth<1) \n {\n alert(\"Enter valid month\");\n return false;\n }\n if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) \n {\n alert(\"Enter valid day\");\n return false;\n }\n if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) \n {\n alert(\"Enter valid day\");\n return false;\n }\n if (intMonth == 2) \n {\n if (intday < 1) \n {\n alert(\"Enter valid day\");\n return false;\n }\n if (LeapYear(intYear) == true) \n {\n if (intday > 29) \n {\n alert(\"Enter valid day\");\n return false;\n }\n }\n else \n {\n if (intday > 28) \n {\n alert(\"Enter valid day\");\n return false;\n }\n }\n }\n //Check for entered date is less than Current Date.\n if(checkFlag && (checkFlag == 1))\n {\n var currDate = new Date();\n var sysDate = new Date(currDate.getFullYear(),currDate.getMonth(),currDate.getDate());\n if((Date.parse(new Date(strYear,strMonth-1,strDay ))) < (Date.parse(sysDate)))\n {\n alert(\"Date should not be less than current date\");\n return false;\n }\n }\n //Check for entered date is greater than Current Date.\n else if(checkFlag && (checkFlag == 0))\n {\n var currDate = new Date();\n var sysDate = new Date(currDate.getFullYear(),currDate.getMonth(),currDate.getDate());\n if((Date.parse(new Date(strYear,strMonth-1,strDay ))) > (Date.parse(sysDate)))\n {\n alert(\"Date should not be greater than current date\");\n return false;\n }\n }\n return true;\n }",
"function validate_date(year, month, day, hour, minute, second, millisecond, pastdateok, futuredateok, fulldatetime) {\n var returnvalue = \"\";\n var testdate;\n var months = new Array('', \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\");\n if (year.length < 4) {\n return (\"You must enter a 4 digit year.\");\n }\n if ((day < 1) || (day > 31)) {\n return (\"You have entered an invalid day.\");\n }\n if ((month < 1) || (month > 12)) {\n return (\"You have entered an invalid month.\");\n }\n switch (month) {\n case 4:\n case \"4\":\n case \"04\":\n case 6:\n case \"6\":\n case \"06\":\n case 9:\n case \"9\":\n case \"09\":\n case 11:\n case \"11\":\n if (day > 30) {\n returnvalue = \"Invalid day (31st) for the month of \" + months[month] + \".\";\n }\n break;\n case 2:\n case \"2\":\n case \"02\":\n if (isleapyear(year)) {\n returnvalue = (day > 29) ? \"Cannot have more than 29 days in February of \" + year + \".\" : \"\";\n }\n else {\n returnvalue = (day > 28) ? \"Cannot have more than 28 days in February of \" + year + \".\" : \"\";\n }\n break;\n default:\n if (day > 31) {\n returnvalue = \"Cannot have more than 31 days in the month of \" + months[month] + \".\";\n }\n }\n if (returnvalue != \"\") {\n // we do a return here because the following is invalid if we've determined we have an invalid date.\n return (returnvalue);\n }\n testdate = new Date(year, month-1, day, hour, minute, second, millisecond);\n today = new Date();\n if (!(fulldatetime)) {\n today = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0,0,0,0);\n }\n if ( (!(pastdateok)) && (testdate.getTime() < today.getTime() ) ) {\n returnvalue = \"You have selected a date from the past and the system will not accept past dates.\";\n }\n if ( (!(futuredateok)) && (testdate.getTime() > today.getTime() ) ) {\n returnvalue = \"You have selected a date from the future and the system will not accept future dates.\";\n }\n return (returnvalue);\n}",
"function checkDay (theField, emptyOK)\r\n{ if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;\r\n if ((emptyOK == true) && (isEmpty(theField.value))) return true;\r\n if (!isDay(theField.value, false))\r\n return warnInvalid (theField, iDay);\r\n else return true;\r\n}",
"function checkinputdate(thisDateField) \n{\n // add by charlie, 21-09-2003. trim the value before validation\n thisDateField.value = trim(thisDateField.value);\n // end add by charlie\n\tvar day = thisDateField.value.charAt(0).concat(thisDateField.value.charAt(1));\n\tvar month = thisDateField.value.charAt(3).concat(thisDateField.value.charAt(4));\n\tvar year = thisDateField.value.charAt(6).concat(thisDateField.value.charAt(7));\n\n\t// check input date is null or not\n\t//if (thisDateField.value.length==0) {\n\t\t//alert(\"Please provide the date\");\n\t\t//return false;\n\t//}\n\n // skip validation if no value is input\n\tif (thisDateField.value.length!=0){\n // check input length \n if (trim(thisDateField.value).length != 8) {\n alert(\"Input Date Format should be dd-mm-yy, ex: 01-04-01 for 1 April 2001\");\n thisDateField.focus(); \n return false;\n } \n\n // validate year input\n if (isNaN(year) || year < 0 || thisDateField.value.charAt(6)==\"-\") {\n alert(\"Year should between 00 to 99\");\n thisDateField.focus();\n return false;\n }\n\t\n // validate month input\n if (isNaN(month) || month <=0 || month > 12) {\n alert(\"Month should between 01 to 12\");\n thisDateField.focus();\n return false;\n }\n\n // validate day input\n if (isNaN(day) || day <= 0 || day > 31) {\n alert(\"Day range should between 01 to 31\");\n thisDateField.focus();\n return false;\n }\n\n // validate max day input allow according to the input month for (April, June, September, November)\n if ((month==4 || month==6 || month==9 || month==11) && day > 30) {\n alert(\"Day range should between 01 to 30\");\n thisDateField.focus(); \n return false;\n }\n\t\n // validate max day input allow for February according to input year (leap year)\n if (month==2) {\n if ( (parseInt(year) % 4 == 0 && parseInt(year) % 100 != 0 ) \n || parseInt(year) % 400 == 0 ){\n if (day > 29) {\n alert(\"Day range should between 0 to 29\");\n thisDateField.focus(); \n return false;\n }\n } else {\n if (day > 28) {\n alert(\"Day range should between 0 to 28\");\n thisDateField.focus();\n return false;\n }\n }\n }\n\t\n // validate is it a proper seperator between day and month, also between month and year\n if (thisDateField.value.charAt(2)!=\"-\" || thisDateField.value.charAt(5)!=\"-\") {\n alert(\"Invalid input for date, use - as a seperator\");\n thisDateField.focus();\n return false;\n }\n\n\n\n }\n\t\n\t// if input date is ok return true\n\treturn true;\n}",
"function checkDay (theField, emptyOK)\r\n{ if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;\r\n if ((emptyOK == true) && (isEmpty(theField.value))) return true;\r\n if (!isDay(theField.value, false))\r\n return warnInvalid (theField, iDay);\r\n else return true;\r\n}",
"function arq_isDate(fieldId, fieldAlias, formatPattern)\r\n{\r\n var fieldObject = document.getElementById(fieldId);\r\n var msg = \"El campo \" + fieldAlias + \"no contiene una fecha valida. (\" + formatPattern + \")\";\r\n\r\n if (fieldObject && fieldObject.value && fieldObject.value.length > 0)\r\n {\r\n var dateInMills = getDateFromFormat(fieldObject.value, formatPattern);\r\n if (dateInMills == 0)\r\n {\r\n _arq_insertValidationMsg(fieldId, msg);\r\n }\r\n }\r\n}",
"function isValidDate(entered_month,entered_day,entered_year)\n {\n \n if ((entered_year % 4) == 0) \n\t { \n\t\t var days_in_month = \"312931303130313130313031\";\n \t }\n \t else \n\t { \n\t\t var days_in_month = \"312831303130313130313031\";\n \t } \n\t var months = new Array(\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\");\n\t if (entered_month != -1)\n\t {\n\t alert(entered_day + \",\"+2*entered_month +\",\"+ (parseInt(2*entered_month)+parseInt('2')) + days_in_month.substring(parseInt(2*entered_month),parseInt(2*entered_month)+parseInt('2')));\n\t\t if (entered_day > days_in_month.substring(2*entered_month,2*entered_month+2))\n\t\t {\n\t\t\t alert (\"The Date is entered wrongly (the day field value exceeds the number of days for the month entered).\");\n\t\t\t return false;\n\t\t }\n\t }\n\t return true;\n }// End isValidDate",
"function checkYear (theField, emptyOK)\r\n{ if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;\r\n if ((emptyOK == true) && (isEmpty(theField.value))) return true;\r\n if (!isYear(theField.value, false))\r\n return warnInvalid (theField, iYear);\r\n else return true;\r\n}",
"function SP_CheckDateFormat(oField)\n{\n\tvar month,day,year,splitDate;\n\tvar alertMsg = \"\";\n\tvar showErrMsg = false;\n\t\n\tif(oField && SP_Trim(oField.value) != \"\")\n\t{\n\t\t// '-' is must for every date entry\n\t\tsplitDate = oField.value.split('-');\n\t\tif(splitDate.length != 3)\n\t\t{\n\t\t\t\n\t\t\tif(typeof message == \"object\")\n\t\t\t{\n\t\t\t\talert(message.date_format+\": \"+dateFormat);\n\t\t\t\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\talert(\"Enter Date in this format: \"+dateFormat);\n\t\t\t}\n\t\t\toField.value = \"\";\n\t\t\toField.focus();\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tswitch(dateFormat)\n\t\t{\n\t\t\tcase \"yyyy-mm-dd\":\n\t\t\t\tif(typeof message == \"object\")\n\t\t\t\t{\n\t\t\t\t\talertMsg = message.date_format+\": yyyy-mm-dd\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\talertMsg = \"Enter Date in this format: yyyy-mm-dd\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmonth = splitDate[1];\n\t\t\t\tyear = splitDate[0];\n\t\t\t\tday = splitDate[2];\n\t\t\t\t\n\t\t\t\tif(SP_CheckValidDate(day,month,year))\n\t\t\t\t{\n\t\t\t\t\tshowErrMsg = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmonth = (month.length < 2) ? \"0\"+month: month;\n\t\t\t\tday = (day.length < 2) ? \"0\"+day: day;\n\t\t\t\t\n\t\t\t\toField.value = year+ \"-\" + month + \"-\" + day;\n\t\t\t\t\t\n\t\t\t\tbreak;\n\t\t\tcase \"dd-mmm-yyyy\":\n\t\t\t\tif(typeof message == \"object\")\n\t\t\t\t{\n\t\t\t\t\talertMsg = message.date_format+\": dd-mmm-yyyy\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\talertMsg = \"Enter Date in this format: dd-mmm-yyyy\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmonth = SP_GetMonthNumber(splitDate[1])* 1 + 1;\n\t\t\t\tyear = splitDate[2];\n\t\t\t\tday = splitDate[0];\n\t\t\t\t\n\t\t\t\tif(SP_CheckValidDate(day,month,year))\n\t\t\t\t{\n\t\t\t\t\tshowErrMsg = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tmonth = SP_GetMonthName(--month);\n\t\t\t\tday = (day.length < 2) ? \"0\"+day: day;\n\t\t\t\t\n\t\t\t\toField.value = day + \"-\" + month + \"-\" + year;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif(showErrMsg)\n\t\t{\n\t\t\talert(alertMsg);\n\t\t\toField.value = \"\";\n\t\t\toField.focus();\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn true;\n\t\n\t}\n\t\n\t\n}",
"function checkYear (theField, emptyOK)\r\n{ if (checkYear.arguments.length == 1) emptyOK = defaultEmptyOK;\r\n if ((emptyOK == true) && (isEmpty(theField.value))) return true;\r\n if (!isYear(theField.value, false))\r\n return warnInvalid (theField, iYear);\r\n else return true;\r\n}",
"function datevalidation(date,flag_alert) \n{\n\n\t\t\tdatearrayentry = date.split(\"-\");\n\t\t\tday = datearrayentry[0];\n\t\t\tmonth = datearrayentry[1];\n\t\t\tyear = datearrayentry[2];\n\t\t\t\n\t\t\tif (date.match(\"^[0-9]{2}-[0-9]{2}-[0-9]{4}$\") == null)\n\t\t\t{\n\t\t\t\t\tif(flag_alert=='1')\n\t\t\t\t\t{\n\t\t\t\t\t\t\talert(\"You have specified an Invalid Date Format\");\n\t\t\t\t\t}\n\t\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\tif ((month==4 || month==6 || month==9 || month==11) && day==31) \n\t\t\t{\n\t\t\t\tif(month==4)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"April\";\n\t\t\t\t}\n\t\t\t\telse if(month==6)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"June\";\n\t\t\t\t}\n\t\t\t\telse if(month==4)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"September\";\n\t\t\t\t}\n\t\t\t\telse if(month==4)\n\t\t\t\t{\n\t\t\t\t\t\tmonth_desc=\"November\";\n\t\t\t\t}\n\n\t\t\t\tif(flag_alert=='1')\n\t\t\t\t{\n\t\t\t\t\talert(\"Month \"+month_desc+\" doesn't have 31 days!\");\n\t\t\t\t}\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tif (month == 2) \n\t\t\t{ // check for february 29th\n\t\t\t\tvar isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));\n\t\t\t\tif (day>29 || (day==29 && !isleap)) \n\t\t\t\t{\n\t\t\t\t\tif(flag_alert=='1')\n\t\t\t\t\t{\n\t\t\t\t\t\talert(\"February \" + year + \" doesn't have \" + day + \" days!\");\n\t\t\t\t\t}\n\t\t\t\t\treturn null; \n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (month < 1 || month > 12) // check month range\n\t\t\t{ \n\t\t\t\t\tif(flag_alert=='1')\n\t\t\t\t\t{\n\t\t\t\t\t\talert(\"Month must be between 1 and 12.\");\n\t\t\t\t\t}\n\t\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (day < 1 || day > 31) // check date range\n\t\t\t{\n\t\t\t\tif(flag_alert=='1')\n\t\t\t\t{\n\t\t\t\t\talert(\"Day must be between 1 and 31.\");\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\treturn \"dateisvalid\";\n\t\t\t\t\t\t\n}",
"function checkDay(theField, emptyOK) {\r\n if (checkDay.arguments.length == 1) emptyOK = defaultEmptyOK;\r\n if ((emptyOK == true) && (isEmpty(theField.value))) return true;\r\n if (!isDay(theField.value, false))\r\n return warnInvalid(theField, iDay);\r\n else return true;\r\n}",
"function dateValidation(date) {\n\tif (!date) {\n\t\treturn true;\n\t}\n\n\tvar currentDate = getCurrentDate();\n\n\tvar year = +date.substring(0, 4);\n\tvar month = +date.substring(5, 7);\n\tvar day = +date.substring(8, 10);\n\n\tif (date.length < 10 || date.substring(4,5) != '-' || date.substring(7,8) != '-') {\n\t\treturn 'Please enter your date in the format YYYY-MM-DD';\n\t\t//\t\t document.getElementById(dt).style.background ='#e35152';\n\n\t}\n\n\t if ( month > 12 || month < 1 || day > 31 || month < 1 || year > 2050 ) {\n\t\treturn 'You must enter a valid date. Please try again.';\n\t\t //\t\t document.getElementById(dt).style.background ='#e35152';\n\n\t}\n\telse if (year < currentDate['year'] || (month < currentDate['month'] && year == currentDate['year'])\n\t\t|| (month == currentDate['month'] && year == currentDate['year'] && day < currentDate['date'])) {\n\t\t return 'You cannot enter a date that is in the past.';\n\t\t // document.getElementById(dt).style.background ='#e35152';\n\n\t} \n\n\treturn true;\n}",
"function validateDate(monthval, dayval, yearval) {\n\tvar retVal = false;\n\tvar monthval = parseInt(monthval, 10);\n\tvar dayval = parseInt(dayval, 10);\n\tvar yearval = parseInt(yearval, 10);\n\t//alert('-' + monthval + '-' + dayval + '-' + yearval);\n\t\n\tswitch(monthval){\n\t\tcase 1:\n\t\tcase 3:\n\t\tcase 5:\n\t\tcase 7:\n\t\tcase 8:\n\t\tcase 10:\n\t\tcase 12:\n\t\t\tretVal = (dayval <= 31);\n\t\t\tbreak;\n\t\tcase 4:\n\t\tcase 6:\n\t\tcase 11:\n\t\tcase 9:\n\t\t\tretVal = (dayval <= 30);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tif(dayval == 29) {\n\t\t\t\tretVal = ( (((yearval % 4) == 0) && ((yearval % 100 ) != 0)) || (yearval % 400 == 0));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tretVal = (dayval <= 28 );\n\t\t\t}\n\t\t\tbreak;\n\t}\n\t\n\tif (dayval < 1) {\n\t\tretVal = false;\n\t}\n\tif (isNaN(yearval)) {\n\t\tretVal = false;\n\t}\n\t\n\treturn retVal\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loadJSON Function: Parm 1: file path of the json file Return: No return Description: Load the JSON for our animals, and rebuild the DOM using renderAll after it has been retrieved. | function loadJSON(fileUrl) {
// Declare our xhr object
const xhr = new XMLHttpRequest();
// Set up the callback for our successful request
xhr.onload = function() {
// Parse the JSON
arry = JSON.parse(xhr.responseText);
console.log(arry);
renderAll(arry);
};
// Open the request
xhr.open('GET', fileUrl, true);
// Send the request
xhr.send();
} | [
"function loadJsonFile() {\n loadFile();\n}",
"function load_json() {\n var file = document.getElementById('file');\n \n if(file.files.length) {\n var reader = new FileReader();\n \n reader.onload = function(e) {\n //document.getElementById('outputDiv').innerHTML = e.target.result;\n main_templating(null, JSON.parse(e.target.result));\n };\n \n reader.readAsText(file.files[0]);\n }\n }",
"function loadJson() {\n let file_loader = new THREE.FileLoader();\n file_loader.load(jsonPath,\n function (data) {\n font_json = JSON.parse(data);\n loadImg();\n })\n }",
"function loadJSON() {\n let xhr = new XMLHttpRequest();\n\n xhr.onreadystatechange = function() {\n if (xhr.readyState === 4 && xhr.status === 200) {\n let jsonData = JSON.parse(xhr.responseText);\n displayContent(jsonData);\n }\n };\n\n xhr.open('GET', 'content.json', true);\n xhr.send();\n }",
"function readJsonFile() {\r\n loadJSON(function(response) {\r\n // Parse JSON string into object\r\n actual_JSON = JSON.parse(response);\r\n });\r\n}",
"function loadJSON() {\n // Get the data from the JSON file\n $.getJSON(\"data/projects_data.json\")\n .fail((request, textStatus, error) => {\n // Display the error in the console\n console.error(error);\n })\n .done((data) => {\n // Store the projects in an array\n projects = data.projects;\n // update boolean\n jsonLoaded = true;\n });\n}",
"static loadMainJson() {\n console.log(\"Loading main json...\");\n let request = new XMLHttpRequest();\n request.open('GET', novelPath + '/novel.json', true);\n request.onload = function() {\n if (request.status >= 200 && request.status < 400) {\n let json = JSON.parse(request.responseText);\n return NovelManager.loadExternalJson(json);\n }\n };\n request.onerror = function() {\n\n };\n request.send();\n return UI.showContinueButton(false);\n }",
"function getJSONFile() {\n var xhttp = new XMLHttpRequest();\n xhttp.open(\"GET\", \"/JSON/ThegooniesList.html\", true);\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n //Convert the JSON text back to an object\n goonies = JSON.parse(this.responseText);\n showGoonies();\n }\n }\n xhttp.send(); \n}",
"function loadJson(url) {\n $.ajax({\n url: url,\n dataType: 'json',\n success: function(data) {\n setJsonData(data);\n },\n error: function(e) {\n console.log(e);\n }\n });\n }",
"function LoadJson(){\n\t/* functionality for allow user to choose json DISABLED: json file is load with search a local specific file\n\t//create a reader\n\tvar reader = new FileReader();\n reader.onload = onReaderLoad; //Call an internal function when reading text\n reader.readAsText(event.target.files[0]);\n\t \n\t//internal fonction for create an json obj with file and launch treatment if it's ok\n\tfunction onReaderLoad(event){\n\t\ttry{\n\t\t\tconsole.log(event.target.result);\n\t\t\tjson = JSON.parse(event.target.result);\n\t\t}catch(e)\n\t\t{\n\t\t\talert(\"Erreur lors du chargement: Veuillez utiliser un fichier json valide\");\n\t\t}\n\t\tGenerateFilter(json);\n\t\tGenerate(json);\t\n }\n\t*/\n\t//Serch a specific json file in local repository\n\t//if parse fail an error message appear\n\t//if parse succes we call function for generate filters and chart\n\t$.get(\"../../json/generation.json\").success(function(file){\t\n\t\tjson = file;\n\t\tGenerateFilter(json); //generate filters\n\t\tGenerate(json);\t //generate chart\n\t})\n\t.fail(function(jqXHR, status, error){\n alert(\"Erreur lors du chargement: Veuillez utiliser un fichier json valide.Message: \"+ error);\n });\n\n}",
"function getAnimals() {\n $.ajax({\n method: \"GET\",\n url: \"data/animals.json\"\n }).done(function(data) {\n console.log(\"animals\", data.animals);\n });\n}",
"function getAnimals() {\n\n\t$.ajax({\n\t\turl: \"data/animals.json\"\n\t}).done(function(animals){\n\n\t\tconsole.log(\"the contents of animals.json\");\n\t\tconsole.log(animals);\n\n\t});\n}",
"function _load(path) {\n var actual_JSON = {};\n _loadJSON(path||'', function(response) {\n try{\n actual_JSON = JSON.parse(response); \n }catch(ex){\n debuglog('MenuBuilder._load: Error parse JSON file.');\n }\n });\n return actual_JSON;\n }",
"function loadJSON(file) {\n $.ajaxSetup({'async': false}); // Want to make sure we get all the quotes\n var objects = [];\n $.getJSON(file, function(json) {\n $.each(json, function( key, val ) {\n objects.push( val );\n });\n\n });\n return objects;\n }",
"function loadJSON(filepath, callback) {\n $.getJSON(filepath, function (data) {\n callback(data);\n })\n}",
"preloadJson()\n {\n currentScene.load.json('dialogues', 'data/SingleDialogues.json');\n currentScene.load.json('notes', 'data/Notes.json');\n }",
"function loadJSON(jsonFile, actionOnLoad) {\n $.getJSON(jsonFile, function (data) {\n try {\n actionOnLoad(data);\n } catch (err) {\n alert(err);\n }\n });\n}",
"function loadJSON()\r\n{\r\n var project = current_project.split(\"/\")[1];\r\n \r\n $.ajax({\r\n dataType: \"json\",\r\n url: \"litefile/files/\" + current_user + \"/projects/\" + project + '.json',\r\n success:function(data)\r\n {\r\n if(APP.parseJSON)\r\n {\r\n // GET PROJECT DATA\r\n APP.parseJSON(data);\r\n // get data from DATA variable and fill any gap\r\n if(parseDATA)\r\n parseDATA(null);\r\n }\r\n },\r\n error: function(err)\r\n {\r\n console.error(err)\r\n }\r\n });\r\n}",
"function loadJSON(filePath) {\n\t// Load JSON file;\n\tvar json = loadTextFileAjaxSync(filePath, \"application/json\");\n\t// Parse JSON\n\treturn JSON.parse(json);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if value falls between first and last. | function between(first, last, value)
{
return (first < last ? value >= first && value <= last : value >= last && value <= first);
} | [
"function valueInRange(start, value, finish) {\n return start <= value && value <= finish;\n}",
"function valueInRange (start, value, finish) {\n\t return (start <= value) && (value <= finish);\n\t}",
"function valueInRange (start, value, finish) {\n return (start <= value) && (value <= finish);\n}",
"function inRange(start, end, value) {\n\t\t\treturn (value>= start && value <= end);\n\t\t}",
"function checkBetween(str, first, last) {\r\n if (str < first || str > last) {\r\n return true;\r\n }\r\n return false;\r\n}",
"between( between, dependentVal){\n if( dependentVal > between[0] && dependentVal < between[1]){\n return true;\n }else{\n return false;\n }\n\n}",
"function isBetween(lowerBound, upperBound, value)\n{\n\treturn (lowerBound < value && value < upperBound);\n}",
"function checkBetween(start, middle, end) {\n if (start > end) {\n return end <= middle && middle <= start;\n } else {\n return start <= middle && middle <= end;\n }\n}",
"function isStart(value, start, end) {\n return end !== null && start !== end && value < end && value === start;\n}",
"function isBetween(value, [min, max]) {\n return value >= min && value <= max;\n}",
"function isBetween(first, last, word) {\n return word >= first && word <= last ;\n}",
"function isEnd(value, start, end) {\n return start !== null && start !== end && value >= start && value === end;\n}",
"function isBetween(vals, range ) {\n vals.forEach( (val, index) => {\n if ( val<range[0] || val>range[1]) {\n throw `val ${val} is outside the bounds [${range[0]} , ${range[1]}]`\n }\n })\n return true\n}",
"function isBetween(val, lo, hi) {\n\tif ((val < lo) || (val > hi)) {\n\t\treturn (false);\n\t} else {\n\t\treturn (true);\n\t}\n}",
"function isInRange(value, start, end) {\n return (value >= start && value < end);\n }",
"inRange(num, start, end = 0) {\n // switch start and end if start > end, incl with default end value of 0\n if (start > end) [start, end] = [end, start];\n return num >= start && num < end;\n }",
"function inrange (value, range, left, right) {\n let r0 = range[0],\n r1 = range[range.length - 1],\n t;\n\n if (r0 > r1) {\n t = r0;\n r0 = r1;\n r1 = t;\n }\n\n left = left === undefined || left;\n right = right === undefined || right;\n return (left ? r0 <= value : r0 < value) && (right ? value <= r1 : value < r1);\n }",
"function inrange(value, range, left, right) {\n let r0 = range[0], r1 = range[range.length - 1], t;\n if (r0 > r1) {\n t = r0;\n r0 = r1;\n r1 = t;\n }\n left = left === undefined || left;\n right = right === undefined || right;\n return (left ? r0 <= value : r0 < value) && (right ? value <= r1 : value < r1);\n }",
"function inrange(value, range, left, right) {\n var r0 = range[0], r1 = range[range.length-1], t;\n if (r0 > r1) {\n t = r0;\n r0 = r1;\n r1 = t;\n }\n left = left === undefined || left;\n right = right === undefined || right;\n\n return (left ? r0 <= value : r0 < value) &&\n (right ? value <= r1 : value < r1);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Code below contains a closure related to the variable 'fact', but does not contain a closure relative to the variable 'data'. Note: Inner functions do not remember everything from outer functions. | function outerFn() {
var data = "Something from outer";
var fact = "Remember me!";
return function innerFn() {
// in debugger console, value
// of data is reference error
// while fact is string
// This is because, innerFn()
// is evaluated and fact is
// consequently able to be
// established as a variable
debugger
return fact;
}
} | [
"function outerFn(){\n\tvar data = \"something from outerFn\";\n\tvar fact = \"Remember me!\"\n\treturn function innerFn(){\n\t\t// if you keep the chrome dev tools open\n\t\t// this will pause our code and place us\n\t\t// in the sources tab where we can \n\t\t// examine variables\n\t\tdebugger\n\t\treturn fact;\n\t}\n}",
"function fact(n, ret){\n tail_fact(n, 1, ret); //PASS the continuation along to the next function that is called\n}",
"function fa() {\r\n\t\t\t\t// fa scope = VO:{a: undefined, x: undefined, fb: <reference to function>}-->Global\r\n\t\t\t\t// fb scope = Closure:{a: undefined}-->Global\r\n\t\t\t\tvar a = 100;\r\n\t\t\t\tvar x = 'wwq';\r\n\r\n\t\t\t\tfunction fb() {\r\n\t\t\t\t\t// fb scope = VO:{b: undefined, y: undefined, fc: <reference to function>}-->Closure:{a: 100}-->Global\r\n\t\t\t\t\t// fc scope = Closure:{b: undefined}-->Closure:{a: 100}-->Global\r\n\t\t\t\t\tvar b = 1;\r\n\t\t\t\t\tvar y = 'wwl';\r\n\r\n\t\t\t\t\tfunction fc() {\r\n\t\t\t\t\t\t// fc scope = VO:{z: undefined}-->Closure:{b: 1}-->Closure:{a: 100}-->Global\r\n\t\t\t\t\t\tvar z = 'wmm';\r\n\t\t\t\t\t\treturn a + b;\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn fc;\r\n\t\t\t\t}\r\n\t\t\t\treturn fb();\r\n\t\t\t}",
"function innerFunc (/* Nah */) {\n // Hey memory! Do you know about a person inside of innerFunc?\n // It thinks it might be right here.\n // Memory: 'Nah bruh.'\n // let person = 'Bob';\n\n // Hey! Memory, did you get passed an argument named person?\n // Nope!\n function finalFunc (/* person */) {\n // Hey memory! Do you know about a person inside of finalFunc?\n // It thinks it might be right here.\n // Memory: 'Nah bruh.'\n // Scenario 1: Ask for data.\n // console.log(`Help me ${person}!`);\n // Scenario 2: Set data\n // Im suggesting to javascript that 'person' already ecists in an upper scope.\n person = 'Jenna';\n // console.log(person);\n }\n\n finalFunc();\n }",
"function outerFn() {\n var data = \"something from outer\";\n return function innerFn() {\n return \"Just returned from the inner function\";\n }\n}",
"function let_func() {\n var data = [];\n for (var k = 0; k< 3; k++) {\n data[k] = function () {\n console.log(k);\n return k\n };\n }\n return data\n}",
"function Closure() {\r\n}",
"function outerFn() {\n \tvar name = function() {\n \t\treturn \"catherine\";\n \t }\n return name;\n }",
"function outerFn() {\n\n return function() {\n return \"Gloria\";\n }\n }",
"function testClosures() {\n console.log(arguments.callee.name);\n function myNewClosure() {\n console.log(arguments.callee.name);\n function myThirdClosure() {\n console.log(arguments.callee.name);\n function myFourthClosure() {\n console.log(arguments.callee.name);\n function myFifthClosure() {\n console.log('DONE');\n }\n return myFifthClosure();\n }\n }\n }\n}",
"function testClosure(){\n\tvar x = 4;\n\t\n\tfunction closeX(){\n\t\treturn x;\n\t}\n\treturn closeX\n}",
"function test_rule_6() {\n \n var f1 = function() {\n var g1 = 1;\n \n f2(); // Although False, it might seem reasonable to think that f2 (which mentions the g1 variable), have access \n // to the 'g1' variable, since it's being called here from within the scope where the variable is decleared.\n };\n \n var f2 = function() {\n v4 = g1;\n };\n \n f3 = function() {\n f2();\n };\n \n f3(); // of course calling f2() should throw an error in this case, since f2() doesn't have access\n // to the g1 variable.\n \n // In addition, calling the f1 (which in turns call f2()) should also throw since it the calling context\n // of f2() has no infulence over its scope access rules\n f1();\n \n}",
"function Bal3A(x,y,z) {\n print(\"Bal3A called, this.name=\" + this.name +\n \", x=\" + x + \", y=\" + y + \", z=\" + z);\n\n function f(x,y) {\n print(\"Bal3A/f called, this.name=\" + this.name +\n \", x=\" + x + \", y=\" + y);\n print(\"z is from outer scope: z=\" + z);\n\n function g(a,b) {\n print(\"Bal3A/f/g called, this.Number.POSITIVE_INFINITY=\" + this.Number.POSITIVE_INFINITY +\n \", a=\" + a + \", b=\" + b);\n print(\"the following are from outer scope: \" +\n \"x=\" + x + \", y=\" + y + \", z=\" + z);\n\n return \"Bal3A/f/g return value\";\n }\n\n // replace created object with function g\n return g;\n }\n f.prototype = { 'name': 'Bal3A/f' };\n\n return f;\n}",
"function eagerFoo(data)\n {\n equal(data, 'foo fun', 'eagerFoo - string moreToCome value hook');\n equal(sequence, 9, 'Our execution sequence should be 9');\n ok(ready, 'Ready should be true');\n sequence++;\n }",
"function numberFact(number, func){\n\treturn func(number);\n}",
"evaluate(func=null){\n const copy = this.createDeepCopy();\n return copy.consume(null, null, func);\n }",
"function funClosureMemo(cb) {\n const cache = {};\n return function (n, ...args) {\n if (n in cache) {\n console.log('finding from cache');\n return cache[n];\n } else {\n console.log('new calculate');\n let res = cb(n, ...args);\n cache[n] = res;\n return res;\n }\n };\n}",
"function outerFn(){\n\treturn function(){\n\t\treturn \"Mike Larrabee\";\n\t}\n}",
"function hideCache () {\n // \"Middle scope\" where we hide cache\n var cache = {};\n\n function factorial (x) {\n // Inner scope\n if (x < 2) return 1;\n if (!(x in cache)) {\n cache[x] = x * factorial(x - 1);\n }\n return cache[x];\n }\n\n return factorial;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interface function for computing shape of output tensor. | computeOutputShape() {
throw new Error('Unimplemented.');
} | [
"computeOutputShape(inputShape) {\n const inputShapes = _utils_types_utils__WEBPACK_IMPORTED_MODULE_6__[\"normalizeShapeList\"](inputShape);\n if (inputShapes.length !== this.inputLayers.length) {\n throw new _errors__WEBPACK_IMPORTED_MODULE_2__[\"ValueError\"](`Invalid inputShape argument ${inputShape}: ` +\n `model has ${this.inputLayers.length} tensor inputs.`);\n }\n // TODO(michaelterry): Add caching\n const layersToOutputShapes = {};\n for (let i = 0; i < inputShapes.length; i++) {\n const layer = this.inputLayers[i];\n const inputShape = inputShapes[i];\n // It's an input layer: computeOutputShape is identity,\n // and there is only one node and one tensor output.\n const shapeKey = layer.name + '_0_0';\n layersToOutputShapes[shapeKey] = inputShape;\n }\n const depthKeys = Object.keys(this.nodesByDepth)\n .map(x => parseInt(x, 10))\n .sort(_utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__[\"reverseNumberCompare\"]);\n // Iterate over nodes, by depth level.\n if (depthKeys.length > 1) {\n for (const depth of depthKeys) {\n const nodes = this.nodesByDepth[depth];\n for (const node of nodes) {\n // This is always a single layer, never a list.\n const layer = node.outboundLayer;\n if (this.inputLayers.map(x => x.id).indexOf(layer.id) !== -1) {\n // We've already covered the input layers a few lines above.\n continue;\n }\n // Potentially redundant list, same size of node.inputTensors.\n const inputShapes = [];\n for (let j = 0; j < node.inboundLayers.length; j++) {\n const inboundLayer = node.inboundLayers[j];\n const nodeIndex = node.nodeIndices[j];\n const tensorIndex = node.tensorIndices[j];\n const shapeKey = `${inboundLayer.name}_${nodeIndex}_${tensorIndex}`;\n const inputShape = layersToOutputShapes[shapeKey];\n inputShapes.push(inputShape);\n }\n const outputShape = layer.computeOutputShape(_utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__[\"singletonOrArray\"](inputShapes));\n const outputShapes = _utils_types_utils__WEBPACK_IMPORTED_MODULE_6__[\"normalizeShapeList\"](outputShape);\n const nodeIndex = layer.inboundNodes.indexOf(node);\n for (let j = 0; j < outputShapes.length; j++) {\n const shapeKey = `${layer.name}_${nodeIndex}_${j}`;\n layersToOutputShapes[shapeKey] = outputShapes[j];\n }\n }\n }\n }\n // Read final output shapes from layersToOutputShapes.\n const outputShapes = [];\n const outputShapeKeys = [];\n for (let i = 0; i < this.outputLayers.length; i++) {\n const layer = this.outputLayers[i];\n const nodeIndex = this.outputLayersNodeIndices[i];\n const tensorIndex = this.outputLayersTensorIndices[i];\n const shapeKey = `${layer.name}_${nodeIndex}_${tensorIndex}`;\n outputShapeKeys.push(shapeKey);\n }\n for (let i = 0; i < outputShapeKeys.length; i++) {\n const key = outputShapeKeys[i];\n _utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__[\"assert\"](key in layersToOutputShapes);\n outputShapes.push(layersToOutputShapes[key]);\n }\n // TODO(michaelterry): Update cache\n return _utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__[\"singletonOrArray\"](outputShapes);\n }",
"computeOutputShape(inputShape) {\n const inputShapes = _utils_types_utils__WEBPACK_IMPORTED_MODULE_6__.normalizeShapeList(inputShape);\n if (inputShapes.length !== this.inputLayers.length) {\n throw new _errors__WEBPACK_IMPORTED_MODULE_2__.ValueError(`Invalid inputShape argument ${inputShape}: ` +\n `model has ${this.inputLayers.length} tensor inputs.`);\n }\n // TODO(michaelterry): Add caching\n const layersToOutputShapes = {};\n for (let i = 0; i < inputShapes.length; i++) {\n const layer = this.inputLayers[i];\n const inputShape = inputShapes[i];\n // It's an input layer: computeOutputShape is identity,\n // and there is only one node and one tensor output.\n const shapeKey = layer.name + '_0_0';\n layersToOutputShapes[shapeKey] = inputShape;\n }\n const depthKeys = Object.keys(this.nodesByDepth)\n .map(x => parseInt(x, 10))\n .sort(_utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__.reverseNumberCompare);\n // Iterate over nodes, by depth level.\n if (depthKeys.length > 1) {\n for (const depth of depthKeys) {\n const nodes = this.nodesByDepth[depth];\n for (const node of nodes) {\n // This is always a single layer, never a list.\n const layer = node.outboundLayer;\n if (this.inputLayers.map(x => x.id).indexOf(layer.id) !== -1) {\n // We've already covered the input layers a few lines above.\n continue;\n }\n // Potentially redundant list, same size of node.inputTensors.\n const inputShapes = [];\n for (let j = 0; j < node.inboundLayers.length; j++) {\n const inboundLayer = node.inboundLayers[j];\n const nodeIndex = node.nodeIndices[j];\n const tensorIndex = node.tensorIndices[j];\n const shapeKey = `${inboundLayer.name}_${nodeIndex}_${tensorIndex}`;\n const inputShape = layersToOutputShapes[shapeKey];\n inputShapes.push(inputShape);\n }\n const outputShape = layer.computeOutputShape(_utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__.singletonOrArray(inputShapes));\n const outputShapes = _utils_types_utils__WEBPACK_IMPORTED_MODULE_6__.normalizeShapeList(outputShape);\n const nodeIndex = layer.inboundNodes.indexOf(node);\n for (let j = 0; j < outputShapes.length; j++) {\n const shapeKey = `${layer.name}_${nodeIndex}_${j}`;\n layersToOutputShapes[shapeKey] = outputShapes[j];\n }\n }\n }\n }\n // Read final output shapes from layersToOutputShapes.\n const outputShapes = [];\n const outputShapeKeys = [];\n for (let i = 0; i < this.outputLayers.length; i++) {\n const layer = this.outputLayers[i];\n const nodeIndex = this.outputLayersNodeIndices[i];\n const tensorIndex = this.outputLayersTensorIndices[i];\n const shapeKey = `${layer.name}_${nodeIndex}_${tensorIndex}`;\n outputShapeKeys.push(shapeKey);\n }\n for (let i = 0; i < outputShapeKeys.length; i++) {\n const key = outputShapeKeys[i];\n _utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__.assert(key in layersToOutputShapes);\n outputShapes.push(layersToOutputShapes[key]);\n }\n // TODO(michaelterry): Update cache\n return _utils_generic_utils__WEBPACK_IMPORTED_MODULE_4__.singletonOrArray(outputShapes);\n }",
"tensorSize() {\n return _tensorflow_tfjs_core_dist_ops_ops_for_converter__WEBPACK_IMPORTED_MODULE_1__.scalar(this.size(), 'int32');\n }",
"function computeOutShape(begin, end, strides) {\n const size = [];\n for (let axis = 0; axis < begin.length; axis++) {\n size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);\n }\n return size;\n}",
"function computeOutShape(begin, end, strides) {\n const size = [];\n for (let axis = 0; axis < begin.length; axis++) {\n size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);\n }\n return size;\n}",
"function computeOutShape(begin, end, strides) {\n const size = [];\n\n for (let axis = 0; axis < begin.length; axis++) {\n size[axis] = Math.ceil((end[axis] - begin[axis]) / strides[axis]);\n }\n\n return size;\n} // Creates full selection at the elided dimensions. If the dimension matches",
"function shape(x) {\n if (Array.isArray(x)) {\n if (Array.isArray(x[0])) {\n return [x.length].concat(shape(x[0]));\n } else {\n // 1D vector\n return [x.length];\n }\n } else {\n // 0D scalar\n return [];\n }\n}",
"tensorSize() {\n return tfOps.scalar(this.size(), 'int32');\n }",
"size() {\n return this.tensors.length;\n }",
"function _getOutputLength(node) {\n\n // Handle constant values\n\n if (typeof node === 'number') return 1;\n if (Array.isArray(node)) return node.length;\n\n // Handle materials\n\n var output = node.chunk.output;\n if (typeof output === 'number') return output;\n\n // Handle polymorphic output\n\n var key = node.inputs.map(function recurse(node) {\n return _getOutputLength(node);\n }).join(',');\n\n return output[key];\n}",
"function extractOutputShapes(attr) {\n var result = null;\n // We don't know anything about the output tensors.\n if (!attr) {\n return null;\n }\n for (var i = 0; i < attr.length; i++) {\n var _a = attr[i], key = _a.key, value = _a.value;\n if (key === OUTPUT_SHAPES_KEY) {\n // Map all output tensors into array of numbers denoting their shape.\n var result_1 = value.list.shape.map(function (shape) {\n if (shape.unknown_rank) {\n // This output tensor is of unknown rank. We don't know if it is a\n // scalar, or a tensor, or of what shape it is.\n return null;\n }\n if (shape.dim == null ||\n (shape.dim.length === 1 && shape.dim[0].size == null)) {\n // This output tensor is a scalar.\n return [];\n }\n // This output tensor has a known rank. Map each dimension size\n // into a number.\n return shape.dim.map(function (dim) {\n // Size can be -1 if this particular dimension is unknown.\n return dim.size;\n });\n });\n // Since we already processed it, remove the entry from the attribute\n // list (saves memory).\n attr.splice(i, 1);\n return result_1;\n }\n }\n // We didn't find OUTPUT_SHAPES_KEY in attributes, so we don't know anything\n // about the output tensors.\n return null;\n }",
"get dimension() {\r\n return this.cpoints.shape[1];\r\n }",
"split(length, tensor) {\n if (tensor.dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`);\n }\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n if (!this.dynamicSize && length.length !== this.maxSize) {\n throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${length.length}), ` +\n 'and the TensorArray is not marked as dynamically resizeable');\n }\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors = [];\n Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"tidy\"])(() => {\n tensor = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"reshape\"])(tensor, [1, totalLength, elementPerRow]);\n for (let i = 0; i < length.length; ++i) {\n const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"reshape\"])(Object(_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"slice\"])(tensor, indices, sizes), this.elementShape);\n }\n return tensors;\n });\n const indices = [];\n for (let i = 0; i < length.length; i++) {\n indices[i] = i;\n }\n this.writeMany(indices, tensors);\n }",
"split(length, tensor) {\n if (tensor.dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`);\n }\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n if (!this.dynamicSize && length.length !== this.maxSize) {\n throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${length.length}), ` +\n 'and the TensorArray is not marked as dynamically resizeable');\n }\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors = [];\n (0,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.tidy)(() => {\n tensor = (0,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.reshape)(tensor, [1, totalLength, elementPerRow]);\n for (let i = 0; i < length.length; ++i) {\n const previousLength = (i === 0) ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = (0,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.reshape)((0,_tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.slice)(tensor, indices, sizes), this.elementShape);\n }\n return tensors;\n });\n const indices = [];\n for (let i = 0; i < length.length; i++) {\n indices[i] = i;\n }\n this.writeMany(indices, tensors);\n }",
"get numberOfOutputs() {\n if (isDefined(this.output)) {\n return this.output.numberOfOutputs;\n }\n else {\n return 0;\n }\n }",
"compute(inputs, which_output) {\n if (inputs === undefined) {\n inputs = new Array(this.network.num_neurons[0]);\n for (let ii=0; ii < this.dims.length; ii++){\n inputs[this.dims[ii]] = 0;\n }\n }\n\n if (typeof(inputs) !== 'object' || inputs.length !== this.network.num_neurons[0]) {\n throw(\"Bad inputs: expected array of length \" + this.network.num_neurons[0]);\n }\n\n return this.map_one(inputs, this.ndim - 1, which_output);\n }",
"get numberOfOutputs() {\n if (Object(_util_TypeCheck__WEBPACK_IMPORTED_MODULE_1__[\"isDefined\"])(this.output)) {\n return this.output.numberOfOutputs;\n } else {\n return 0;\n }\n }",
"split(length, tensor) {\n if (tensor.dtype !== this.dtype) {\n throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${tensor.dtype}`);\n }\n\n let totalLength = 0;\n const cumulativeLengths = length.map(len => {\n totalLength += len;\n return totalLength;\n });\n\n if (totalLength !== tensor.shape[0]) {\n throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${totalLength}, and tensor's shape is: ${tensor.shape}`);\n }\n\n if (!this.dynamicSize && length.length !== this.maxSize) {\n throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${length.length}), ` + 'and the TensorArray is not marked as dynamically resizeable');\n }\n\n const elementPerRow = totalLength === 0 ? 0 : tensor.size / totalLength;\n const tensors = [];\n (0, _tfjsCore.tidy)(() => {\n tensor = tensor.reshape([1, totalLength, elementPerRow]);\n\n for (let i = 0; i < length.length; ++i) {\n const previousLength = i === 0 ? 0 : cumulativeLengths[i - 1];\n const indices = [0, previousLength, 0];\n const sizes = [1, length[i], elementPerRow];\n tensors[i] = (0, _tfjsCore.slice)(tensor, indices, sizes).reshape(this.elementShape);\n }\n\n return tensors;\n });\n const indices = [];\n\n for (let i = 0; i < length.length; i++) {\n indices[i] = i;\n }\n\n this.writeMany(indices, tensors);\n }",
"function get_outputs_length (node_id) {\n\treturn dataset.steps[node_id].outputs.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handlers for scrolling on the left hand panel (i.e. y axis). | function addLeftScrollbarHandlers() {
$(".scroll_y").bind("touchmove", function(event) {
// One event only, get position of touch as a percentage.
var that = $(this);
var touches = event.originalEvent.touches;
if (touches.length != 1) return;
var touch = touches[0];
// Compute position of touch as a percentage.
var yaxis = that.attr("id") == "vscroll";
var y = (touch.pageY - that.offset().top) / that.height();
var percent = y;
var temp = parseFloat(LEFTSCROLLNUB/100).toFixed(1);
var clampUpper = parseFloat(1-temp).toFixed(1);
percent = percent.clamp(0, (clampUpper));// 1 - (windowsize / (xaxis ? dDataSet.columns.length : dDataSet.rows.length) )
// Update scrollbars.
that.find(".nub_y").css("top", (percent * 100) + "%");
// Adjust the percentage relative to the window size.
if (yaxis) target_wRow = Math.floor(_ROWLENGTH * percent);
else target_wcOL = Math.floor(_COLLENGTH * percent);
scrollAnimate_Y();
});
$('#downarrow').bind("touchstart", function(event) {
var that = $(this);
that.attr("src", "images/arrowdn_sel.png");
if(target_wRow < parseInt(_ROWLENGTH)-windowsize && target_wRow > -1) {
target_wRow += 1;
scrollAnimate_Y();
}
});
$('#uparrow').bind("touchstart", function(event) {
var that = $(this);
that.attr("src", "images/arrow_sel.png");
if(target_wRow > -1) {
target_wRow -= 1;
scrollAnimate_Y();
}
});
$('#downarrow').bind("touchend", function(event) { var that = $(this); that.attr("src", "images/arrowdn.png"); });
$('#uparrow').bind("touchend", function(event) { var that = $(this); that.attr("src", "images/arrow.png"); });
} | [
"function eltdSideAreaScroll(){\n\n\n }",
"function addLeftNavigationScrollbar() {\n\taddLeftGraphicalScrollbar();\n\tadjustLeftScrollbarSize();\n\taddLeftScrollbarHandlers();\n}",
"handleMouseScroll(e) {\n //\n }",
"function edgtfSideAreaScroll(){\n\t\tvar sideMenu = $('.edgtf-side-menu');\n\t\t\n\t\tif(sideMenu.length){\n sideMenu.perfectScrollbar({\n wheelSpeed: 0.6,\n suppressScrollX: true\n });\n\t\t}\n\t}",
"function qodefSideAreaScroll(){\n\t\tvar sideMenu = $('.qodef-side-menu');\n\t\t\n\t\tif(sideMenu.length){\n sideMenu.perfectScrollbar({\n wheelSpeed: 0.6,\n suppressScrollX: true\n });\n\t\t}\n\t}",
"function dd_content_init_hover_scroll_horiz() {\n //hovering on the left side of horiz menu\n $(\"#dd_content_horiz_menu_wrapper .dd_content_left, #dd_content_bot_menu_wrapper .dd_content_left\").hover(\n \n //enter the scroll left element\n function(event) {\n \n //get content\n var container = $(this).siblings(\".dd_content_container\");\n\n //get the total amount scrolled away from the left\n var scroll_left = $(container).scrollLeft();\n \n //1 sec per 100 pxs\n //#pxs / 100px/sec * 1000 ms/sec\n var time = (scroll_left) / 250 * 1000;\n \n //animate movement to 0 from left in above time\n $(container).animate({scrollLeft: 0}, time);\n \n //exit the scroll left element\n }, function(){\n //get container that scrolling is occuring on\n var container = $(this).siblings(\".dd_content_container\");\n //stop the scrolling\n $(container).stop();\n });\n \n //hovering on the right side of horiz menu\n $(\"#dd_content_horiz_menu_wrapper .dd_content_right, #dd_content_bot_menu_wrapper .dd_content_right\").hover(\n \n //enter right element\n function(event) {\n //get container\n var container = $(this).siblings(\".dd_content_container\");\n \n //get full width of container including hidden\n var full_width = $(container).get(0).scrollWidth;\n \n //get total amount scrolled left\n var scroll_left = $(container).scrollLeft();\n \n //1 sec per 100 pxs\n //#pxs / 100px/sec * 1000 ms/sec\n var time = (full_width - scroll_left) / 250 * 1000;\n \n //start scroll right\n $(container).animate({scrollLeft: full_width}, time);\n \n //leave scroll right animation\n }, function(){\n //get container\n var container = $(this).siblings(\".dd_content_container\");\n //stop animation\n $(container).stop();\n });\n}",
"function bindLeftPanelEvents() {\n //tap left to show/hide left panel\n bindTapEvtHandler(roleSelector(SWIPE_ELEM_CLASS_NAME), function () {\n var leftPanel = getLeftPanelScope(),\n searchEl = WM.element(roleSelector(HEADER_CLASS_NAME) + \" \" + classSelector(SEARCH_CONTAINER_CLASS_NAME)),\n leftPanelEl;\n leftPanel && leftPanel.toggle();\n leftPanelEl = WM.element(roleSelector(LEFT_PANEL_CLASS_NAME));\n //Hide search container when left panel is open\n if (leftPanelEl.length && leftPanelEl.hasClass('visible')) {\n if (searchEl.length) {\n searchEl.hide();\n }\n }\n });\n }",
"function handleMenuScroll(e) {\n doScroll(e);\n }",
"function setupScrollbarEvents(isHorizontal) {\n var scrollbarVars = getScrollbarVars(isHorizontal);\n var scrollbarVarsInfo = scrollbarVars._info;\n var insideIFrame = _windowElementNative.top !== _windowElementNative;\n var xy = scrollbarVars._x_y;\n var XY = scrollbarVars._X_Y;\n var scroll = _strScroll + scrollbarVars._Left_Top;\n var strActive = 'active';\n var strSnapHandle = 'snapHandle';\n var scrollDurationFactor = 1;\n var increaseDecreaseScrollAmountKeyCodes = [ 16, 17 ]; //shift, ctrl\n var trackTimeout;\n var mouseDownScroll;\n var mouseDownOffset;\n var mouseDownInvertedScale;\n \n function setupEvent(element, eventNames, listener) {\n var collected = type(eventNames) == TYPES.a && type(listener) == TYPES.a;\n var i = 0;\n \n if(collected) {\n for (; i < eventNames[LEXICON.l]; i++)\n setupEvent(element, eventNames[i], listener[i]);\n }\n else {\n if(_supportPassiveEvents)\n setupPassiveEventListener(element, eventNames, listener, false, true);\n else\n element.on(eventNames, listener);\n }\n }\n function getPointerPosition(event) {\n return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames.\n }\n function getPreparedScrollbarsOption(name) {\n return _currentPreparedOptions.scrollbars[name];\n }\n function increaseTrackScrollAmount() {\n scrollDurationFactor = 0.5;\n }\n function decreaseTrackScrollAmount() {\n scrollDurationFactor = 1;\n }\n function documentKeyDown(event) {\n if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)\n increaseTrackScrollAmount();\n }\n function documentKeyUp(event) {\n if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)\n decreaseTrackScrollAmount();\n }\n function onMouseTouchDownContinue(event) {\n var originalEvent = event.originalEvent || event;\n var isTouchEvent = originalEvent.touches !== undefined;\n return _sleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;\n }\n function documentDragMove(event) {\n if(onMouseTouchDownContinue(event)) {\n var trackLength = scrollbarVarsInfo._trackLength;\n var handleLength = scrollbarVarsInfo._handleLength;\n var scrollRange = scrollbarVarsInfo._maxScroll;\n var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale;\n var scrollDeltaPercent = scrollRaw / (trackLength - handleLength);\n var scrollDelta = (scrollRange * scrollDeltaPercent);\n scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0;\n if (_isRTL && isHorizontal && !_rtlScrollBehavior.i)\n scrollDelta *= -1;\n\n _viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta));\n\n if(_scrollbarsHandlesDefineScrollPos)\n refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta);\n\n if (!_supportPassiveEvents)\n COMPATIBILITY.prvD(event);\n }\n else\n documentMouseTouchUp(event);\n }\n function documentMouseTouchUp(event) {\n event = event || event.originalEvent;\n\n _documentElement.off(_strMouseTouchMoveEvent, documentDragMove)\n .off(_strMouseTouchUpEvent, documentMouseTouchUp)\n .off(_strKeyDownEvent, documentKeyDown)\n .off(_strKeyUpEvent, documentKeyUp)\n .off(_strSelectStartEvent, documentOnSelectStart);\n\n if(_scrollbarsHandlesDefineScrollPos)\n refreshScrollbarHandleOffset(isHorizontal, true);\n\n _scrollbarsHandlesDefineScrollPos = false;\n removeClass(_bodyElement, _classNameDragging);\n removeClass(scrollbarVars._handle, strActive);\n removeClass(scrollbarVars._track, strActive);\n removeClass(scrollbarVars._scrollbar, strActive);\n\n mouseDownScroll = undefined;\n mouseDownOffset = undefined;\n mouseDownInvertedScale = 1;\n\n decreaseTrackScrollAmount();\n\n if (trackTimeout !== undefined) {\n _base.scrollStop();\n clearTimeout(trackTimeout);\n trackTimeout = undefined;\n }\n\n if(event) {\n var rect = _hostElementNative.getBoundingClientRect();\n var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;\n\n //if mouse is outside host element\n if (!mouseInsideHost)\n hostOnMouseLeave();\n\n if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)\n refreshScrollbarsAutoHide(false);\n }\n }\n function onHandleMouseTouchDown(event) {\n if (onMouseTouchDownContinue(event))\n onHandleMouseTouchDownAction(event);\n }\n function onHandleMouseTouchDownAction(event) {\n mouseDownScroll = _viewportElement[scroll]();\n mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll;\n if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL)\n mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll;\n\n mouseDownInvertedScale = getHostElementInvertedScale()[xy];\n mouseDownOffset = getPointerPosition(event);\n\n _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);\n addClass(_bodyElement, _classNameDragging);\n addClass(scrollbarVars._handle, strActive);\n addClass(scrollbarVars._scrollbar, strActive);\n\n _documentElement.on(_strMouseTouchMoveEvent, documentDragMove)\n .on(_strMouseTouchUpEvent, documentMouseTouchUp)\n .on(_strSelectStartEvent, documentOnSelectStart);\n\n if(_msieVersion || !_documentMixed)\n COMPATIBILITY.prvD(event);\n COMPATIBILITY.stpP(event);\n }\n function onTrackMouseTouchDown(event) {\n if (onMouseTouchDownContinue(event)) {\n var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h]);\n var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top];\n var ctrlKey = event.ctrlKey;\n var instantScroll = event.shiftKey;\n var instantScrollTransition = instantScroll && ctrlKey;\n var isFirstIteration = true;\n var easing = 'linear';\n var decreaseScroll;\n var finishedCondition;\n var scrollActionFinsished = function(transition) {\n if(_scrollbarsHandlesDefineScrollPos)\n refreshScrollbarHandleOffset(isHorizontal, transition);\n };\n var scrollActionInstantFinished = function() {\n scrollActionFinsished();\n onHandleMouseTouchDownAction(event);\n };\n var scrollAction = function () {\n if(!_destroyed) {\n var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale;\n var handleOffset = scrollbarVarsInfo._handleOffset;\n var trackLength = scrollbarVarsInfo._trackLength;\n var handleLength = scrollbarVarsInfo._handleLength;\n var scrollRange = scrollbarVarsInfo._maxScroll;\n var currScroll = scrollbarVarsInfo._currentScroll;\n var scrollDuration = 270 * scrollDurationFactor;\n var timeoutDelay = isFirstIteration ? MATH.max(400, scrollDuration) : scrollDuration;\n var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent\n var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache);\n var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset;\n var scrollObj = { };\n var animationObj = {\n easing : easing,\n step : function(now) {\n if(_scrollbarsHandlesDefineScrollPos) {\n _viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340\n refreshScrollbarHandleOffset(isHorizontal, now);\n }\n }\n };\n instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0;\n instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;\n\n //_base.scrollStop();\n\n if(instantScroll) {\n _viewportElement[scroll](instantScrollPosition); //scroll instantly to new position\n if(instantScrollTransition) {\n //get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position\n //and the animation stops at the correct point\n instantScrollPosition = _viewportElement[scroll]();\n //scroll back to the position before instant scrolling so animation can be performed\n _viewportElement[scroll](currScroll);\n\n instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;\n instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition;\n\n scrollObj[xy] = instantScrollPosition;\n _base.scroll(scrollObj, extendDeep(animationObj, {\n duration : 130,\n complete : scrollActionInstantFinished\n }));\n }\n else\n scrollActionInstantFinished();\n }\n else {\n decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll;\n finishedCondition = rtlIsNormal\n ? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset)\n : (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset);\n\n if (finishedCondition) {\n clearTimeout(trackTimeout);\n _base.scrollStop();\n trackTimeout = undefined;\n scrollActionFinsished(true);\n }\n else {\n trackTimeout = setTimeout(scrollAction, timeoutDelay);\n\n scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance;\n _base.scroll(scrollObj, extendDeep(animationObj, {\n duration: scrollDuration\n }));\n }\n isFirstIteration = false;\n }\n }\n };\n if (ctrlKey)\n increaseTrackScrollAmount();\n\n mouseDownInvertedScale = getHostElementInvertedScale()[xy];\n mouseDownOffset = COMPATIBILITY.page(event)[xy];\n\n _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);\n addClass(_bodyElement, _classNameDragging);\n addClass(scrollbarVars._track, strActive);\n addClass(scrollbarVars._scrollbar, strActive);\n\n _documentElement.on(_strMouseTouchUpEvent, documentMouseTouchUp)\n .on(_strKeyDownEvent, documentKeyDown)\n .on(_strKeyUpEvent, documentKeyUp)\n .on(_strSelectStartEvent, documentOnSelectStart);\n\n scrollAction();\n COMPATIBILITY.prvD(event);\n COMPATIBILITY.stpP(event);\n }\n }\n function onTrackMouseTouchEnter(event) {\n //make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is \"scroll\" or \"move\".\n _scrollbarsHandleHovered = true;\n if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)\n refreshScrollbarsAutoHide(true);\n }\n function onTrackMouseTouchLeave(event) {\n _scrollbarsHandleHovered = false;\n if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)\n refreshScrollbarsAutoHide(false);\n }\n function onScrollbarMouseTouchDown(event) {\n COMPATIBILITY.stpP(event);\n }\n \n setupEvent(scrollbarVars._handle, \n _strMouseTouchDownEvent, \n onHandleMouseTouchDown);\n setupEvent(scrollbarVars._track,\n [_strMouseTouchDownEvent, _strMouseTouchEnter, _strMouseTouchLeave], \n [onTrackMouseTouchDown, onTrackMouseTouchEnter, onTrackMouseTouchLeave]);\n setupEvent(scrollbarVars._scrollbar, \n _strMouseTouchDownEvent, \n onScrollbarMouseTouchDown);\n\n if (_supportTransition) {\n scrollbarVars._scrollbar.on(_strTransitionEndEvent, function(event) {\n if (event.target !== scrollbarVars._scrollbar[0])\n return;\n refreshScrollbarHandleLength(isHorizontal);\n refreshScrollbarHandleOffset(isHorizontal);\n });\n }\n }",
"function eltdfSideAreaScroll() {\n\n var sideMenu = $('.eltdf-side-menu');\n\n if (sideMenu.length) {\n sideMenu.niceScroll({\n scrollspeed: 60,\n mousescrollstep: 40,\n cursorwidth: 0,\n cursorborder: 0,\n cursorborderradius: 0,\n cursorcolor: \"transparent\",\n autohidemode: false,\n horizrailenabled: false\n });\n }\n }",
"function OCM_scrolling() {\r\n\t\t\t\t\t\r\n\t\t\t\t\t$offCanvasEl.mousewheel(function (event, delta) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.scrollTop -= (delta * 30);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t}",
"function mkdfSideAreaScroll(){\n\n var sideMenu = $('.mkdf-side-menu');\n\n if(sideMenu.length){ \n sideMenu.niceScroll({ \n scrollspeed: 60,\n mousescrollstep: 40,\n cursorwidth: 0, \n cursorborder: 0,\n cursorborderradius: 0,\n cursorcolor: \"transparent\",\n autohidemode: false, \n horizrailenabled: false \n });\n }\n }",
"function mkdOnWindowScroll() {\n \n }",
"function leftbarScrollShow () {\n if ($(\"body\").hasClass(\"show-leftbar\")) {\n $(\"#sidebar\").getNiceScroll().show();\n } else {\n $(\"#sidebar\").getNiceScroll().hide();\n }\n $(\"#sidebar\").getNiceScroll().resize();\n}",
"_horizontalScrollbarHandler(event) {\n const that = this;\n\n event.stopPropagation();\n\n if (that.isVirtualized) {\n that._recycle();\n }\n else {\n that.$.itemsContainer.scrollLeft = event.detail.value;\n }\n }",
"function edgtfSideAreaScroll(){\n\t\tvar sideMenu = $('.edgtf-side-menu');\n\t\t\n\t\tif(sideMenu.length){\n\t\t\tsideMenu.niceScroll({\n\t\t\t\tscrollspeed: 60,\n\t\t\t\tmousescrollstep: 40,\n\t\t\t\tcursorwidth: 0,\n\t\t\t\tcursorborder: 0,\n\t\t\t\tcursorborderradius: 0,\n\t\t\t\tcursorcolor: \"transparent\",\n\t\t\t\tautohidemode: false,\n\t\t\t\thorizrailenabled: false\n\t\t\t});\n\t\t}\n\t}",
"function setupScrollbarEvents(isHorizontal) {\n var scrollbarVars = getScrollbarVars(isHorizontal);\n var scrollbarVarsInfo = scrollbarVars._info;\n var insideIFrame = _windowElementNative.top !== _windowElementNative;\n var xy = scrollbarVars._x_y;\n var XY = scrollbarVars._X_Y;\n var scroll = _strScroll + scrollbarVars._Left_Top;\n var strActive = 'active';\n var strSnapHandle = 'snapHandle';\n var strClickEvent = 'click';\n var scrollDurationFactor = 1;\n var increaseDecreaseScrollAmountKeyCodes = [16, 17]; //shift, ctrl\n var trackTimeout;\n var mouseDownScroll;\n var mouseDownOffset;\n var mouseDownInvertedScale;\n\n function getPointerPosition(event) {\n return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames.\n }\n function getPreparedScrollbarsOption(name) {\n return _currentPreparedOptions.scrollbars[name];\n }\n function increaseTrackScrollAmount() {\n scrollDurationFactor = 0.5;\n }\n function decreaseTrackScrollAmount() {\n scrollDurationFactor = 1;\n }\n function stopClickEventPropagation(event) {\n COMPATIBILITY.stpP(event);\n }\n function documentKeyDown(event) {\n if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)\n increaseTrackScrollAmount();\n }\n function documentKeyUp(event) {\n if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)\n decreaseTrackScrollAmount();\n }\n function onMouseTouchDownContinue(event) {\n var originalEvent = event.originalEvent || event;\n var isTouchEvent = originalEvent.touches !== undefined;\n return _sleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;\n }\n function documentDragMove(event) {\n if (onMouseTouchDownContinue(event)) {\n var trackLength = scrollbarVarsInfo._trackLength;\n var handleLength = scrollbarVarsInfo._handleLength;\n var scrollRange = scrollbarVarsInfo._maxScroll;\n var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale;\n var scrollDeltaPercent = scrollRaw / (trackLength - handleLength);\n var scrollDelta = (scrollRange * scrollDeltaPercent);\n scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0;\n if (_isRTL && isHorizontal && !_rtlScrollBehavior.i)\n scrollDelta *= -1;\n\n _viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta));\n\n if (_scrollbarsHandlesDefineScrollPos)\n refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta);\n\n if (!_supportPassiveEvents)\n COMPATIBILITY.prvD(event);\n }\n else\n documentMouseTouchUp(event);\n }\n function documentMouseTouchUp(event) {\n event = event || event.originalEvent;\n\n setupResponsiveEventListener(_documentElement,\n [_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],\n [documentDragMove, documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart],\n true);\n COMPATIBILITY.rAF()(function() {\n setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, true, { _capture: true });\n });\n \n \n if (_scrollbarsHandlesDefineScrollPos)\n refreshScrollbarHandleOffset(isHorizontal, true);\n\n _scrollbarsHandlesDefineScrollPos = false;\n removeClass(_bodyElement, _classNameDragging);\n removeClass(scrollbarVars._handle, strActive);\n removeClass(scrollbarVars._track, strActive);\n removeClass(scrollbarVars._scrollbar, strActive);\n\n mouseDownScroll = undefined;\n mouseDownOffset = undefined;\n mouseDownInvertedScale = 1;\n\n decreaseTrackScrollAmount();\n\n if (trackTimeout !== undefined) {\n _base.scrollStop();\n clearTimeout(trackTimeout);\n trackTimeout = undefined;\n }\n\n if (event) {\n var rect = _hostElementNative[LEXICON.bCR]();\n var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;\n\n //if mouse is outside host element\n if (!mouseInsideHost)\n hostOnMouseLeave();\n\n if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)\n refreshScrollbarsAutoHide(false);\n }\n }\n function onHandleMouseTouchDown(event) {\n if (onMouseTouchDownContinue(event))\n onHandleMouseTouchDownAction(event);\n }\n function onHandleMouseTouchDownAction(event) {\n mouseDownScroll = _viewportElement[scroll]();\n mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll;\n if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL)\n mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll;\n\n mouseDownInvertedScale = getHostElementInvertedScale()[xy];\n mouseDownOffset = getPointerPosition(event);\n\n _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);\n addClass(_bodyElement, _classNameDragging);\n addClass(scrollbarVars._handle, strActive);\n addClass(scrollbarVars._scrollbar, strActive);\n\n setupResponsiveEventListener(_documentElement,\n [_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strSelectStartEvent],\n [documentDragMove, documentMouseTouchUp, documentOnSelectStart]);\n COMPATIBILITY.rAF()(function() {\n setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, false, { _capture: true });\n });\n \n\n if (_msieVersion || !_documentMixed)\n COMPATIBILITY.prvD(event);\n COMPATIBILITY.stpP(event);\n }\n function onTrackMouseTouchDown(event) {\n if (onMouseTouchDownContinue(event)) {\n var handleToViewportRatio = scrollbarVars._info._handleLength / Math.round(MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]) * scrollbarVars._info._trackLength);\n var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h] * handleToViewportRatio);\n var scrollBaseDuration = 270 * handleToViewportRatio;\n var scrollFirstIterationDelay = 400 * handleToViewportRatio;\n var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top];\n var ctrlKey = event.ctrlKey;\n var instantScroll = event.shiftKey;\n var instantScrollTransition = instantScroll && ctrlKey;\n var isFirstIteration = true;\n var easing = 'linear';\n var decreaseScroll;\n var finishedCondition;\n var scrollActionFinsished = function (transition) {\n if (_scrollbarsHandlesDefineScrollPos)\n refreshScrollbarHandleOffset(isHorizontal, transition);\n };\n var scrollActionInstantFinished = function () {\n scrollActionFinsished();\n onHandleMouseTouchDownAction(event);\n };\n var scrollAction = function () {\n if (!_destroyed) {\n var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale;\n var handleOffset = scrollbarVarsInfo._handleOffset;\n var trackLength = scrollbarVarsInfo._trackLength;\n var handleLength = scrollbarVarsInfo._handleLength;\n var scrollRange = scrollbarVarsInfo._maxScroll;\n var currScroll = scrollbarVarsInfo._currentScroll;\n var scrollDuration = scrollBaseDuration * scrollDurationFactor;\n var timeoutDelay = isFirstIteration ? MATH.max(scrollFirstIterationDelay, scrollDuration) : scrollDuration;\n var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent\n var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache);\n var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset;\n var scrollObj = {};\n var animationObj = {\n easing: easing,\n step: function (now) {\n if (_scrollbarsHandlesDefineScrollPos) {\n _viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340\n refreshScrollbarHandleOffset(isHorizontal, now);\n }\n }\n };\n instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0;\n instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;\n\n //_base.scrollStop();\n\n if (instantScroll) {\n _viewportElement[scroll](instantScrollPosition); //scroll instantly to new position\n if (instantScrollTransition) {\n //get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position\n //and the animation stops at the correct point\n instantScrollPosition = _viewportElement[scroll]();\n //scroll back to the position before instant scrolling so animation can be performed\n _viewportElement[scroll](currScroll);\n\n instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;\n instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition;\n\n scrollObj[xy] = instantScrollPosition;\n _base.scroll(scrollObj, extendDeep(animationObj, {\n duration: 130,\n complete: scrollActionInstantFinished\n }));\n }\n else\n scrollActionInstantFinished();\n }\n else {\n decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll;\n finishedCondition = rtlIsNormal\n ? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset)\n : (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset);\n\n if (finishedCondition) {\n clearTimeout(trackTimeout);\n _base.scrollStop();\n trackTimeout = undefined;\n scrollActionFinsished(true);\n }\n else {\n trackTimeout = setTimeout(scrollAction, timeoutDelay);\n\n scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance;\n _base.scroll(scrollObj, extendDeep(animationObj, {\n duration: scrollDuration\n }));\n }\n isFirstIteration = false;\n }\n }\n };\n if (ctrlKey)\n increaseTrackScrollAmount();\n\n mouseDownInvertedScale = getHostElementInvertedScale()[xy];\n mouseDownOffset = COMPATIBILITY.page(event)[xy];\n\n _scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);\n addClass(_bodyElement, _classNameDragging);\n addClass(scrollbarVars._track, strActive);\n addClass(scrollbarVars._scrollbar, strActive);\n\n setupResponsiveEventListener(_documentElement,\n [_strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],\n [documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart]);\n\n scrollAction();\n COMPATIBILITY.prvD(event);\n COMPATIBILITY.stpP(event);\n }\n }\n function onTrackMouseTouchEnter(event) {\n //make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is \"scroll\" or \"move\".\n _scrollbarsHandleHovered = true;\n if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)\n refreshScrollbarsAutoHide(true);\n }\n function onTrackMouseTouchLeave(event) {\n _scrollbarsHandleHovered = false;\n if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)\n refreshScrollbarsAutoHide(false);\n }\n function onScrollbarMouseTouchDown(event) {\n COMPATIBILITY.stpP(event);\n }\n\n addDestroyEventListener(scrollbarVars._handle,\n _strMouseTouchDownEvent,\n onHandleMouseTouchDown);\n addDestroyEventListener(scrollbarVars._track,\n [_strMouseTouchDownEvent, _strMouseEnter, _strMouseLeave],\n [onTrackMouseTouchDown, onTrackMouseTouchEnter, onTrackMouseTouchLeave]);\n addDestroyEventListener(scrollbarVars._scrollbar,\n _strMouseTouchDownEvent,\n onScrollbarMouseTouchDown);\n\n if (_supportTransition) {\n addDestroyEventListener(scrollbarVars._scrollbar, _strTransitionEndEvent, function (event) {\n if (event.target !== scrollbarVars._scrollbar[0])\n return;\n refreshScrollbarHandleLength(isHorizontal);\n refreshScrollbarHandleOffset(isHorizontal);\n });\n }\n }",
"function scrollLeftRight() {\n\n // checking if thumbs are in the view of screen or not\n if (thumbRef.current.getBoundingClientRect().left < document.getElementById(listId).getBoundingClientRect().right\n ) {\n if (thumbRef.current.getBoundingClientRect().right < document.getElementById(listId).getBoundingClientRect().left)\n setAddRevealThumb(false)\n else\n setAddRevealThumb(true)\n } else {\n setAddRevealThumb(false)\n }\n }",
"function _bindScrollClicks() {\n $('#scroll-right').click(function() {\n $('.feature-list').animate( {scrollLeft: '+=780' }, 500);\n });\n $('#scroll-left').click(function() {\n $('.feature-list').animate( {scrollLeft: '-=780' }, 500);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
' Name : verifyPromocode ' Return type : Boolean ' Input Parameter(s) : none ' Purpose : This method is used to call check the state of Promo code. ' History Header : Version Date Developer Name ' Added By : 1.0 19 Feb 2014 UmamaheswaraRao ' | function verifyPromocode() {
var visiblePromoCodeInputId = getVisiblePromoCodeBoxId();
var promocodeEntryValue = $("#" + visiblePromoCodeInputId).val();
if(promocodeEntryValue) {
if(validationTracking === NOTVALIDATED){
promoCodeErrorHandling(messages['promocode.state.error1'], visiblePromoCodeInputId);
activateCheckoutPayButton();
return false;
} else if(validationTracking === UNVALIDATED){
promoCodeErrorHandling(messages['promocode.state.error2'], visiblePromoCodeInputId);
activateCheckoutPayButton();
return false;
}
}
return true;
} | [
"function $checkIfValidPromocode(){\n\t\t if(window.console){if(!console.trace) {console.trace = console.log;}}\n\t\t/*\n\t\tIf the promo code is valid, update the price, add logic here via regex or API\n\n\t\tExample :*/\n\t\tvar discountCodeInputValue = $('#discount_coupon').val();\n\t\t\n\t\t//this API call would return a JSON response with a falid attribute (string) = \"true\"|\"false\"\n\t\tvar discountCodeCheck = $.post( \"index.php?action=checkdiscountcode\", { discountCodeToCheck: discountCodeInputValue } )\n\t\t\t\t.done(function(data) {\n\t\t\t\t\tif (data === 'FALSE'){\n //console.log('invalid coupon code');\n\t\t\t\t\t\t$('#discountCodeMatchError').slideDown().delay(3000).slideUp('slow');\n updatePriceEl( getPrice('price-regular',0));\n\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\tupdatePriceEl( getPrice('price-discount-1',data));\n\t\t\t\t\t}\n\t\t\t\t\treturn data.valid;\n\t\t\t\t})\n\t\t\t\t.fail(function(data) {\n\t\t\t\t\tpromoCodeIsValid = 'error';\n\t\t\t\t\t//alert( \"error validating discount coupon\" );\n\t\t\t\t});\n\t\t\t\t\t\t\n\n\t\t//Demo only\n\t\t\n}",
"function checkPinCodeValidated() {\r\n button_enable('pinrequired_button_apply', '0');\r\n\r\n getAjaxData('api/pin/status', function($xml) {\r\n var pincode_validate_ret = xml2object($xml);\r\n if (pincode_validate_ret.type == 'response') {\r\n if (MACRO_PUK_REQUIRED == pincode_validate_ret.response.SimState) {\r\n gotoPageWithoutHistory(PUK_REQUIRED_PAGE + window.location.search);\r\n } else if (MACRO_PIN_READY == pincode_validate_ret.response.SimState) {\r\n showInfoDialog(pin_has_been_validated);\r\n setTimeout( function() {\r\n if (('.html' == g_postfix) || ('' == g_postfix)) {\r\n gotoPageWithoutHistory(HOME_PAGE_URL);\r\n } else {\r\n gotoPageWithoutHistory(g_postfix);\r\n }\r\n return false;\r\n }, 1500);\r\n } else {\r\n onApply();\r\n }\r\n } else {\r\n showInfoDialog(pin_code_validate_failed);\r\n setTimeout( function() {\r\n initPage();\r\n return false;\r\n }, 1500);\r\n }\r\n });\r\n}",
"async verifyCode () {\n\t\t// we give the user 3 attempts to enter a confirmation code, after that, they'll\n\t\t// have to get a new confirmation email sent to them\n\t\tlet confirmFailed = false;\n\t\tif (this.request.body.confirmationCode !== this.user.get('confirmationCode')) {\n\t\t\tconfirmFailed = true;\n\t\t\tif (this.user.get('confirmationAttempts') === MAX_CONFIRMATION_ATTEMPTS) {\n\t\t\t\tthis.maxConfirmationAttempts = true;\n\t\t\t}\n\t\t\tthis.trackFailureEvent('Incorrect Code');\n\t\t}\n\t\telse if (Date.now() > this.user.get('confirmationCodeExpiresAt')) {\n\t\t\tconfirmFailed = true;\n\t\t\tthis.confirmationExpired = true;\n\t\t\tthis.trackFailureEvent('Expired');\n\t\t}\n\t\treturn confirmFailed; // if true, shortcuts and prepares for failure response\n\t}",
"function check_verification(code, callback){\n\tconsole.log('checking verification');\n\tvar test_code = '123456';\n\t\n\tif( test_code == code ){\n\t\tcallback('1');\n\t}else{\n\t\tcallback('0');\n\t}\n}",
"verify(code) {\n\t\tconst { pendingEmailAddress: email } = this.state\n\t\tthis.props.verifyEmail({\n\t\t\temail,\n\t\t\ttoken: code\n\t\t})\n\t}",
"verifyCode({\n\t\tcommit,\n\t\tstate\n\t}, params) {\n\t\tcommit(mutationTypes.UPDATE_REQUSET_STATE, true);\n\t\tcommit(mutationTypes.HNADLE_ERROR, null);\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tfetch('/patron/password/completeReset', {\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbody: {\n\t\t\t\t\ttoken: state.token,\n\t\t\t\t\tphoneVerifyCode: params.code\n\t\t\t\t}\n\t\t\t}).then(res => {\n\t\t\t\tcommit(mutationTypes.UPDATE_REQUSET_STATE, false);\n\t\t\t\treturn res.json();\n\t\t\t}).then(data => {\n\t\t\t\tcommit(mutationTypes.SAVE_TOKEN, data.data);\n\n\t\t\t\tconst code = data.bizCode;\n\t\t\t\tif (code === 10000) {\n\t\t\t\t\tcommit(mutationTypes.UPDATE_MODULE_NAME, 'sucsess');\n\t\t\t\t} else {\n\t\t\t\t\tif (code === 11810) {\n\t\t\t\t\t\t// 过期回到首页\n\t\t\t\t\t\tcommit(mutationTypes.HNADLE_ERROR, {\n\t\t\t\t\t\t\ttype: 'dialog',\n\t\t\t\t\t\t\tisTimeout: true,\n\t\t\t\t\t\t\tmsg: 'Your session has timed out. Please try again.'\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcommit(mutationTypes.HNADLE_ERROR, {\n\t\t\t\t\t\t\ttype: '',\n\t\t\t\t\t\t\tmsg: data.message || defaultError,\n\t\t\t\t\t\t\tisCodeError: [11700, 11701, 11702].includes(code) || false\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\treject(data);\n\t\t\t\t}\n\t\t\t}).catch(err => {\n\t\t\t\tcommit(mutationTypes.UPDATE_REQUSET_STATE, false);\n\t\t\t\tcommit(mutationTypes.HNADLE_ERROR, {\n\t\t\t\t\ttype: '',\n\t\t\t\t\tmsg: err.message || defaultError\n\t\t\t\t});\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t}",
"function checkPromoCode(req) {\n var promoCode = req.body.promoCode; //JSON.parse(req.body).promoCode;\n console.log(\"promoCode received : \" + promoCode);\n\n if (promoCode) {\n var match = promoCode.match(/^X([\\d]{1,2})$/);\n if (match != null) {\n return parseInt(match[1], 10);\n }\n }\n return null;\n}",
"function validatePromoCode(req, res) {\n // Validate the user role as instructor\n if(!(req && req.user && req.user.id && req.user.role === \"instructor\")) {\n this.requestUtil.errorResponse(res, {key: \"lic.access.invalid\"});\n return;\n }\n\n var acceptInvalid = req.query.acceptInvalid || false;\n // Verify a promo code was passed in\n var code;\n if( req.params &&\n req.params.code ) {\n code = req.params.code;\n }\n else {\n // no code was supplied\n this.requestUtil.errorResponse(res, {key: \"lic.promoCode.missing\"});\n return;\n }\n\n // Attempt to retrieve the associated \"coupon\" from Stripe\n this.serviceManager.stripe.retrieveCoupon( code )\n .then(function(coupon) {\n // sanitize the coupon and ensure it's valid\n // then only return the amount off and percent off\n var promoCodeInfo = {};\n if( coupon.valid === true || acceptInvalid ) {\n promoCodeInfo.id = coupon.id;\n promoCodeInfo.percent_off = coupon.percent_off;\n promoCodeInfo.amount_off = coupon.amount_off;\n promoCodeInfo.duration = coupon.duration;\n promoCodeInfo.valid = coupon.valid;\n }\n else {\n this.requestUtil.errorResponse(res, {key: \"lic.promoCode.noMoreRedemptions\"});\n return;\n }\n this.requestUtil.jsonResponse(res, promoCodeInfo);\n }.bind(this))\n .then(null, function(err) {\n console.errorExt(\"LicService\", \"Validate Promo Code Error -\",err);\n this.requestUtil.errorResponse(res, {key: \"lic.promoCode.invalid\"});\n }.bind(this));\n}",
"function validateVerificationCode(verificationCode) {\n //\n // initially a no-op\n //\n return verificationCode;\n}",
"verify(mobile, code) {\n if (!this.hashMobileCodes.hasOwnProperty(mobile)) \n return false;\n else \n return this.hashMobileCodes[mobile] == code;\n }",
"function onVerifyPasswordResetCode() {\n const code = $('#password-reset-code').val();\n verifyPasswordResetCode(auth, code).then(() => {\n alertSuccess('Password reset code is valid!');\n }, onAuthError);\n}",
"function phoneVerificationVerify(token){\n\tauthy.verifyPhone({ \n\t\tcountryCode: 'US', \n\t\tphone: phone_number, \n\t\ttoken: token }, function(err, res) {\n\t\t\tif (err){\n\t\t\t\tconsole.log(JSON.stringify(reporting));\n\t\t\t}else{\n\t\t\t\tlogger.info(res.message);\n\t\t\t\treporting[0].status = true;\n\t\t\t\treporting[0].description = 'Phone Verification Tests Executed Successfully';\n\t\t\t\tif(config.onecode == false){\n\t\t\t\t\tconsole.log(JSON.stringify(reporting));\t\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\tif(config.remove_number == true){\n\t\tremoveTwilioNumber();\t\n\t}\n\ttryOneCode();\n}",
"function detectCode(button){\n\n\tfalse;\n\tif (debug===true) {\n\t\tconsole.log('button Check =', button);\n\t\tconsole.log('code in analisys =', codeValid[codePos]);\n\t}\n\n\t// detect button by button if the code is corect\n\tvar sendAnswer= checkValidity(button)\n\tif (debug === true)\n\t\tconsole.log('Code Analyzed', sendAnswer);\n\n\tif (sendAnswer!==NO_CODE){\n\t\tif (sendAnswer===GOOD_CODE) {\n\t\t\tif (debug===true) {\n\t\t\t\tconsole.log('OPEN');\n\t\t\t}\n\t\t}else{\n\t\t\tconsole.log('Warning');\n\t\t}\n\t}\n}",
"verifyOneCode(phone, code){\r\n //Take the expected code by phone number\r\n const expected = cache.get(phone);\r\n if(code == expected){\r\n return true;\r\n }else{\r\n return false;\r\n }\r\n }",
"function promoCodeVerify() {\n //Accepted\n var promoCode1 = \"WESHOPSWIFT\";\n var promoCode2 = \"IAMSWIFT\";\n var attempt = document.getElementById(\"promo\").value;\n\n if ((attempt == promoCode1) || (attempt == promoCode2)) {\n document.getElementById(\"charge\").innerHTML = \"FREE DELIVERY\";\n } else {\n }\n}",
"async verify() {\n\t\tconst { hardwareWallet } = this._store;\n\t\tif (hardwareWallet.identifying === true && hardwareWallet.verify === true) {\n\t\t\t//code here for verification part\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"function testSendVerificationCode_success() {\n var expectedRequest = {\n 'phoneNumber': '+15551234567',\n 'recaptchaToken': 'RECAPTCHA_TOKEN'\n };\n var expectedResponse = {\n 'sessionInfo': 'SESSION_INFO'\n };\n asyncTestCase.waitForSignals(1);\n assertSendXhrAndRunCallback(\n 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/sendVerifi' +\n 'cationCode?key=apiKey',\n 'POST',\n goog.json.serialize(expectedRequest),\n fireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_,\n delay,\n expectedResponse\n );\n rpcHandler.sendVerificationCode(expectedRequest).then(function (sessionInfo) {\n assertEquals(expectedResponse['sessionInfo'], sessionInfo);\n asyncTestCase.signal();\n });\n}",
"function verifyCode(vercode) {\n var vercodekey = '777';\n var regexDigit = /\\D/;\n\n if (vercodekey == vercode && !regexDigit.test(vercode))\n return true;\n else\n console.log(\"failed code number\");\n return false;\n}",
"async function validateCode(contract_address){\n var chain_code;\n\n chain_code = await this.chain.eth.getCode(contract_address);\n return this.contract.runtime_bytecode == chain_code;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recieves nativeParams from an adUnit. If the params were not of type 'type', passes them on directly. If they were of type 'type', translate them into the predefined specific asset requests for that type of native ad. | function processNativeAdUnitParams(params) {
if (params && params.type && typeIsSupported(params.type)) {
return SUPPORTED_TYPES[params.type];
}
return params;
} | [
"function buildNativeRequest(nativeReq) {\n let request = {ver: '1.1', assets: []};\n for (let k of Object.keys(nativeReq)) {\n let v = nativeReq[k];\n let desc = NATIVE_INDEX[k];\n if (desc === undefined) {\n continue;\n }\n let assetRoot = {\n id: desc.id,\n required: ~~v.required,\n };\n if (desc.assetType === 'img') {\n assetRoot[desc.assetType] = buildImageAsset(desc, v);\n } else if (desc.assetType === 'data') {\n assetRoot.data = cleanObj({type: desc.type, len: v.len});\n } else if (desc.assetType === 'title') {\n assetRoot.title = {len: v.len || 90};\n } else {\n return;\n }\n request.assets.push(assetRoot);\n }\n return request;\n}",
"function resolveParams(params) {\n var resolved = {};\n\n resolved[\"x\"] = params['x'] || globalParams['x'];\n resolved[\"y\"] = params['y'] || globalParams['y'];\n resolved[\"z\"] = params['z'] || globalParams['z'];\n resolved[\"size\"] = params['size'] || (globalParams['size'] || 50);\n var size = resolved[\"size\"];\n resolved[\"texture\"] = params['texture'] || globalParams['texture'];\n if(params['transparent'] == undefined) {\n resolved[\"btrans\"] = convertWordToBoolean(globalParams['transparent']);\n }\n else {\n resolved[\"btrans\"] = convertWordToBoolean(params['transparent']);\n }\n resolved[\"amount\"] = params['amount'] || globalParams['amount'];\n resolved[\"endx\"] = params['endx'] || (globalParams['endx'] || resolved[\"x\"]);\n resolved[\"endy\"] = params['endy'] || (globalParams['endy'] || resolved[\"y\"]);\n resolved[\"endz\"] = params['endz'] || (globalParams['endz'] || resolved[\"z\"]);\n resolved[\"endsize\"] = params['endsize'] || (globalParams['endsize'] || size);\n resolved[\"spin\"] = params['spin'] || (globalParams['spin'] || false);\n resolved[\"spinx\"] = params['spinx'] || (globalParams['spinx'] || 0);\n resolved[\"spiny\"] = params['spiny'] || (globalParams['spiny'] || 0);\n resolved[\"spinz\"] = params['spinz'] || (globalParams['spinz'] || 0);\n resolved[\"move\"] = params['move'] || (globalParams['move'] || false);\n resolved[\"movexspeed\"] = params['movexspeed'] || globalParams['movexspeed'];\n resolved[\"moveyspeed\"] = params['moveyspeed'] || globalParams['moveyspeed'];\n resolved[\"movezspeed\"] = params['movezspeed'] || globalParams['movezspeed'];\n resolved[\"width\"] = params['width'] || globalParams['width'];\n resolved[\"height\"] = params['height'] || (globalParams['height'] || size);\n resolved[\"depth\"] = params['depth'] || (globalParams['depth'] || size);\n resolved[\"material\"] = params['material'] || globalParams['material'];\n if(params['solid'] == undefined) {\n resolved[\"solid\"] = convertWordToBoolean(globalParams['solid']);\n if(globalParams['solid'] == undefined) {\n resolved[\"solid\"] = false;\n }\n }\n else {\n resolved[\"solid\"] = convertWordToBoolean(params['solid']);\n }\n resolved[\"orbit\"] = params['orbit'] || (globalParams['orbit'] || false);\n resolved[\"orbitx\"] = params['orbitx'] || (globalParams['orbitx'] || 0);\n resolved[\"orbity\"] = params['orbity'] || (globalParams['orbity'] || 0);\n resolved[\"orbitz\"] = params['orbitz'] || (globalParams['orbitz'] || 0);\n resolved[\"orbitxradius\"] = params['orbitxradius'] || (globalParams['orbitxradius'] || defaultOrbitRadius);\n resolved[\"orbityradius\"] = params['orbityradius'] || (globalParams['orbityradius'] || defaultOrbitRadius);\n resolved[\"orbitzradius\"] = params['orbitzradius'] || (globalParams['orbitzradius'] || defaultOrbitRadius);\n \n return resolved;\n}",
"static setPossibleNamesForCustomParameters(params) {\n _.each(params, p => {\n Adobe.setPossibleValuesForCustomParameter(p);\n });\n }",
"function fetchParams() {\n params = {\n mediaId: NativeVideoBridge.getMediaId(),\n mute: NativeVideoBridge.getMute(),\n volume: NativeVideoBridge.getVolume(),\n loop: NativeVideoBridge.getLoop(),\n startSeconds: NativeVideoBridge.getStartSeconds(),\n endSeconds: NativeVideoBridge.getEndSeconds()\n };\n}",
"function buildNativeAd(nativeResp) {\n const {assets, link, imptrackers, jstracker, privacy} = nativeResp.native;\n let nativeAd = {\n clickUrl: link.url,\n impressionTrackers: imptrackers,\n javascriptTrackers: jstracker ? [jstracker] : undefined,\n privacyLink: privacy,\n };\n _each(assets, asset => {\n let assetName = NATIVE_MODEL[asset.id].name;\n let assetType = NATIVE_MODEL[asset.id].assetType;\n nativeAd[assetName] = asset[assetType].text || asset[assetType].value || cleanObj({\n url: asset[assetType].url,\n width: asset[assetType].w,\n height: asset[assetType].h\n });\n });\n return cleanObj(nativeAd);\n}",
"injectCustomParams() {\n // Get all paramTypes that require substitution.\n const subParamTypes = this.paramTypes\n ? this.paramTypes.filter(paramType => paramType.isSubstitution === true)\n : [];\n subParamTypes.forEach(paramType => {\n // Replace key value in param with param value.\n this.query = this.query.replace(\n paramType.key,\n this.params[paramType.key]\n );\n // Remove from params prior to Dgraph mutation submission.\n delete this.params[paramType.key];\n });\n }",
"function processParams(params) {\r\n var newParams = {};\r\n Object.keys(params).forEach(function (key) {\r\n var param = params[key];\r\n if (param && param.toParam) {\r\n param = param.toParam();\r\n }\r\n if (!param &&\r\n param !== 0 &&\r\n typeof param !== \"boolean\" &&\r\n typeof param !== \"string\") {\r\n return;\r\n }\r\n var type = param.constructor.name;\r\n var value;\r\n // properly encodes objects, arrays and dates for arcgis.com and other services.\r\n // ported from https://github.com/Esri/esri-leaflet/blob/master/src/Request.js#L22-L30\r\n // also see https://github.com/Esri/arcgis-rest-js/issues/18:\r\n // null, undefined, function are excluded. If you want to send an empty key you need to send an empty string \"\".\r\n switch (type) {\r\n case \"Array\":\r\n // Based on the first element of the array, classify array as an array of objects to be stringified\r\n // or an array of non-objects to be comma-separated\r\n value =\r\n param[0] &&\r\n param[0].constructor &&\r\n param[0].constructor.name === \"Object\"\r\n ? JSON.stringify(param)\r\n : param.join(\",\");\r\n break;\r\n case \"Object\":\r\n value = JSON.stringify(param);\r\n break;\r\n case \"Date\":\r\n value = param.valueOf();\r\n break;\r\n case \"Function\":\r\n value = null;\r\n break;\r\n case \"Boolean\":\r\n value = param + \"\";\r\n break;\r\n default:\r\n value = param;\r\n break;\r\n }\r\n if (value || value === 0 || typeof value === \"string\") {\r\n newParams[key] = value;\r\n }\r\n });\r\n return newParams;\r\n }",
"validateAndParseAdParams_(eventData) {\n if (this.creativeData.adParameters == \"\") {\n this.simidProtocol.reject(eventData, {errorCode: CreativeErrorCode.UNSPECIFIED, \n message: \"Ad parameters not found\"});\n return;\n }\n\n let adParams = \"\";\n try {\n adParams = JSON.parse(this.creativeData.adParameters);\n } catch (exception) {\n this.simidProtocol.reject(eventData, {errorCode: CreativeErrorCode.CREATIVE_INTERNAL_ERROR, \n message: \"Invalid JSON input for ad parameters\"});\n return;\n }\n this.buttonLabel_ = adParams[AdParamKeys.BUTTON_LABEL]; \n this.query_ = adParams[AdParamKeys.SEARCH_QUERY];\n this.markerUrl_ = adParams[AdParamKeys.MARKER];\n this.coordinates_ = adParams[AdParamKeys.COORDINATES];\n\n if (!this.query_) {\n this.simidProtocol.reject(eventData, {errorCode: CreativeErrorCode.UNSPECIFIED, \n message: `Required field ${AdParamKeys.SEARCH_QUERY} not found`});\n return;\n }\n this.simidProtocol.resolve(eventData, {});\n }",
"function pj_param(params, code) {\n var type = code[0],\n name = code.substr(1),\n obj = params[name],\n isset = obj !== void 0,\n val, param;\n\n if (type == 't') {\n val = isset;\n } else if (isset) {\n param = obj.param;\n obj.used = true;\n if (type == 'i') {\n val = parseInt(param);\n } else if (type == 'd') {\n // Proj.4 handles locale-specific decimal mark\n // TODO: what to do about NaNs\n val = pj_atof(param);\n } else if (type == 'r') {\n val = dmstor(param);\n } else if (type == 's') {\n val = String(param);\n } else if (type == 'b') {\n if (param == 'T' || param == 't' || param === true) {\n val = true;\n } else if (param == 'F' || param == 'f') {\n val = false;\n } else {\n pj_ctx_set_errno(-8);\n val = false;\n }\n }\n } else {\n // value is not set; use default\n val = {\n i: 0,\n b: false,\n d: 0,\n r: 0,\n s: ''\n }[type];\n }\n if (val === void 0) {\n fatal(\"invalid request to pj_param, fatal\");\n }\n return val;\n}",
"getAd() {\n let adunit = {}\n if (arguments.length == 2) {\n\n adunit = {\n id: arguments[1] + '',\n minPrice: this.minPrice + '',\n creativeRestrictions: {\n acceptedCreativeMimeTypes: ['image/jpeg', 'image/png'],\n allowScaling: this.allowScaling\n }\n }\n } else if (arguments.length == 3) {\n this.width = arguments[1];\n this.height = arguments[2];\n adunit = {\n minPrice: this.minPrice + '',\n creativeRestrictions: {\n acceptedCreativeMimeTypes: ['image/jpeg', 'image/png'],\n width: arguments[1] + '',\n height: arguments[2] + '',\n allowScaling: this.allowScaling\n }\n }\n }\n\n\n this.play(arguments[0], null, adunit, null)\n }",
"parseParams() {\n\n let parms = this.omniJsonDef.propSetMap.customAttributes;\n\n // Find the values in the list (don't want to be fussy about the order)\n parms.forEach((val) => {\n if (val.name === \"headers\") {\n this.parms_headers = val.source;\n console.log('Headers = ' + this.parms_headers);\n }\n\n if (val.name === 'values') {\n this.parms_values = val.source;\n console.log('Values = ' + this.parms_values);\n }\n\n if (val.name === 'input') {\n this.parms_input = val.source;\n console.log('Input @ ' + this.parms_input);\n }\n\n if (val.name === 'select') {\n // Note that select defaults to true\n let s = val.source.toUpperCase();\n if (s === 'F' || s === 'FALSE' || s === 'N' || s === \"NO\") {\n this.parms_showSelect = false;\n }\n console.log('Select = ' + String(this.parms_showSelect));\n }\n\n });\n\n }",
"function parseParams(owner, params) {\n\tparams = (isArray(params) ? params : params.split(';'));\n\towner._simple = true;\n\tfor (var i = 0; i < params.length; i++) {\n\t\tvar nameValue = params[i].split('=');\n\t\towner[nameValue[0].toLowerCase()] = checkDate(nameValue[1] || '');\n\t\towner._simple = false;\n\t}\n}",
"function AppletCaller_addParam(name, value)\n{\n var type = \"embed\";\n if(is_safari || (is_ie == true && is_mac == true))\n type = \"applet\";\n else if(is_ie == true)\n type = \"object\";\n if(isTagAttrib(type, name))\n {\n if(type == \"object\")\n {\n if(name.toLowerCase() == \"codebaseattr\")\n name = \"codebase\";\n if(name.toLowerCase() == \"typeattr\")\n name = \"type\";\n }\n if(type == \"embed\")\n {\n if(name.toLowerCase() === \"codebaseattr\" || name.toLowerCase() === \"typeattr\" || name.toLowerCase() === \"classid\" || name.toLowerCase() === \"id\")\n return;\n if(is_mozilla == true && name.toLowerCase() == \"type\")\n value = \"application/x-java-applet\";\n }\n var idx = this.attribs.length;\n for(i = 0; i < this.attribs.length; i++)\n {\n if(this.attribs[i].name.toLowerCase() == name.toLowerCase())\n idx = i;\n }\n this.attribs[idx] = new NVPair(name, value);\n } \n else\n {\n if(name.toLowerCase() == \"classid\" || name.toLowerCase() == \"codebaseattr\" || name.toLowerCase() == \"typeattr\")\n return; \n var idx1 = this.params.length;\n for(i = 0; i < this.params.length; i++)\n {\n if(this.params[i].name.toLowerCase() == name.toLowerCase())\n idx1 = i;\n }\n this.params[idx1] = new NVPair(name, value);\n }\n}",
"addCustomParams(params) {\r\n if (typeof params !== 'object') {\r\n logger.error('addCustomParams error: Parameter is not an object.');\r\n } else {\r\n this.saveCustomParams(Object.assign(this.getCustomParams(), params));\r\n }\r\n }",
"function initParameters() {\r\n //Retrieve all formal parameters for this component\r\n let requiredParams = componentDetails.operator.parameters;\r\n\r\n\r\n //Iterate over all parameters\r\n for (let i = 0; i < requiredParams.length; i++) {\r\n //Set empty default values for these parameters\r\n let value = \"\";\r\n\r\n if (requiredParams[i].type === \"Switch\") {\r\n value = false;\r\n }\r\n if (requiredParams[i].name === \"device_code\") {\r\n console.log(\"Requesting code for required parameter device_code.\");\r\n value = getDeviceCode();\r\n continue;\r\n }\r\n\r\n //For each parameter, add a tuple (name, value) to the globally accessible parameter array\r\n vm.parameterValues.push({\r\n \"name\": requiredParams[i].name,\r\n \"value\": value\r\n });\r\n }\r\n }",
"setRequestType(type) { this.setParam(WPConst.TYPE, type.key); }",
"async order_params_standard(type, params) {\n\n // Cancel open orders if requested\n if (params.hasOwnProperty('cancelall') && String(params.cancelall) == 'true') {\n await this.cancelall(params);\n delete params.cancelall;\n }\n\n // Check if close order with no position\n if (type == 'close') {\n var position = await this.get_position(params.stub, params.symbol);\n if (position == false) {\n return this.output.error('position_none', [params.symbol]);\n }\n }\n\n // Calculate order sizing and direction (side)\n let order_sizes = await this.convert_size(type, params);\n \n if (order_sizes === false)\n return this.output.error('order_size_unknown');\n \n var [sizing, size, side, flags] = order_sizes;\n params[sizing] = size;\n params.side = side;\n\n if (sizing == 'usd')\n delete params.size\n\n // Extract params\n params = this.utils.lower_props(params);\n var [stub, symbol, side, price, post, ioc, reduce, tag] = this.utils.extract_props(params, ['stub', 'symbol', 'side', 'price', 'post', 'ioc', 'reduce', 'tag']);\n \n // Get parameters from the normalizer\n this.param_map = await this.exchange_get(stub, 'param_map');\n this.order_sizing = await this.exchange_get(stub, 'order_sizing');\n this.stablecoins = await this.exchange_get(stub, 'stablecoins');\n\n //Check if an order is an advanced order (layered orders, relative pricing, etc)\n if (this.order_is_advanced(price)) {\n if (['long','short'].includes(type)) {\n type = side;\n }\n var level_params = await this.order_params_advanced(type, params);\n //if (this.utils.is_array(level_params) && level_params.length > 1)\n // params['is_layered'] = true;\n return level_params;\n }\n\n // Get market info\n\n const market = await this.exchange_execute(stub, 'get_market_by_id_or_symbol',symbol);\n\n // Base order params object\n\n var amount = await this.get_amount(params, type);\n\n if (Math.abs(amount) < (market.precision.amount * 1)) {\n return this.output.error('order_too_small')\n }\n\n var order_params = {\n symbol : symbol.toUpperCase(),\n type : this.param_map[(price == undefined ? 'market' : 'limit')],\n side : side,\n amount : amount,\n price : (price != undefined ? price : null),\n params : {}\n }\n \n // Add additional parameters\n order_params.params[this.param_map.post] = (String(post) == \"true\" ? true : undefined);\n order_params.params[this.param_map.ioc] = (String(ioc) == \"true\" ? true : undefined);\n order_params.params[this.param_map.tag] = tag;\n\n if (type == 'close') {\n order_params.params[this.param_map.reduce] = (String(reduce) == \"true\" ? true : undefined);\n }\n\n var custom_params = {\n tag : tag\n }\n\n // Get normalizer custom params (if defined)\n order_params = await this.exchange_execute(stub, 'custom_params',[type, order_params, custom_params]);\n\n return this.utils.remove_values(order_params, [null, undefined]);\n\n }",
"function parseParams(params) {\n var map = Object.create(null);\n var param = PARAM.exec(params);\n while (param) {\n var values = [];\n var value = PARAM_VALUE.exec(param[2]);\n while (value) {\n values.push(value[1].replace(/^\"(.*)\"$/, '$1'));\n value = PARAM_VALUE.exec(param[2]);\n }\n map[param[1].toLowerCase()] = (values.length > 1 ? values : values[0]);\n param = PARAM.exec(params);\n }\n return map;\n }",
"function _processParams(req, handler, params) {\n var handler_params = handler.params,\n len = handler_params.length;\n \n req.params = {};\n \n if (len > 0) {\n params.reverse();\n for (var i=0; i < len; i+=1) {\n req.params[ handler_params[i] ] = params[i];\n }\n }\n \n return req;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of cards in the deck. | function getNumCards(deck)
{
return deck.length;
} | [
"function cardCount(_deck) {\r\n if (!_deck) {\r\n console.log(\"cardCount: no deck id specified\");\r\n return;\r\n }\r\n \r\n console.log(\"cardCount for deck \" + _deck);\r\n \r\n var deck = $(\"#\"+_deck);\r\n if (deck.length == 0) {\r\n console.log(\"cardCount error: deck element for \" + _deck + \" not found.\");\r\n return 0;\r\n }\r\n\r\n var iCard = 0;\r\n \r\n $(deck.children()).each(function() {\r\n var card = $(this);\r\n iCard++;\r\n });\r\n\r\n return iCard;\r\n } // cardCount",
"function numCards() {\r\n\t\t\tvar size = 0;\r\n\t\t\t_.each(Cards, function() {\r\n\t\t\t\tsize++;\r\n\t\t\t})\r\n\t\t\treturn size;\r\n\t\t}",
"function getNumCards() {\n return numCards;\n }",
"deckSize() {\n\t\t// Check if the deck is undefined\n\t\tif (undefined == this.mCardDeck) {\n\t\t\t// There are no cards in the deck, return size of 0\n\t\t\treturn 0;\n\t\t}\n\t\t// There are cards in the deck\n\t\telse {\n\t\t\t// Return the length of the deck\n\t\t \treturn this.mCardDeck.length;\n\t\t}\n \t}",
"function getDeckLength(deck) {\n if (deck in Decks) {\n return Object.keys(Decks[deck]).length;\n }\n return 0;\n }",
"numOfCards() {\n\t\treturn this.cards.length;\n\t}",
"countCards() {\n let counts = Array(6).fill(0);\n for (const card of this.cards) {\n counts[card - 1]++;\n }\n return counts;\n }",
"static countDeck(remainingCards, deck) {\n remainingCards.innerHTML = deck.length;\n }",
"cardsLeft() {\n return this._deck.length;\n }",
"numCardsRemaining() {\n return this.deck.numCardsRemaining();\n }",
"numCardsRemaining() {\n return this.cards.length;\n }",
"function cardsLeft() {\n document.getElementById('deckcount').textContent = deck.length;\n}",
"getNumCards(state) {\r\n return state.cards.length;\r\n }",
"function totalCardInDeck(){\n let totalCardCount = 0;\n Object.keys(cardDeck).map((item)=>{\n totalCardCount += cardDeck[item];\n });\n return totalCardCount;\n}",
"DeckSize() {\n return this.cartes.length;\n }",
"function stackCardCount() {\n\n return this.cards.length;\n}",
"countSuit(suit = 0)\n\t{\t\n\t\t// 0-3 values accepted for 4 suits of cards.\n\t\tlet counter = 0;\n\t\tfor (let card of this.cards)\n\t\t{\n\t\t\tif (card.intSuit === suit)\n\t\t\t{\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t}\n\t\treturn counter;\n\t}",
"function getFullDeckLength() {\n let deck_length = 0;\n for (let deck in Decks) {\n deck_length += Object.keys(Decks[deck]).length;\n }\n return deck_length;\n }",
"function cardsLeft() {\n\t\treturn cards.length;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find image from instagram | function findPictureOf(keyword){
var response = getResultsFromSite(keyword);
//loop through the responses and find the ones with location
for (var i = 0; i < response.length; i++){
//can create a function out side and call it
//encapsulated anonymous function - put in a function because the part with the marker is async and takes longer, so you will be done with the for loop before you reach
if (response[i].images.standard_resolution.url){
console.log("Image found at index " + i);
console.log(response[i].images.standard_resolution.url);
(function(i){
image = '<img src='+response[i].images.standard_resolution.url+' />';
})(i);
break;
}
}
return image;
} | [
"function findImg(search, cb) {\n \n // add `+animated+filetype:gif` to the search for maximum funtimes\n \n $.getJSON(\"http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=\"+search+\"+moustache&callback=?\",\n function(data){\n // TRY ME LATER: What about storing the whole doc in the the Mustaches collection?\n // TRY ME LATER: Use the additional results as a backup in case the first image fails to load...\n $.each(data.responseData.results, function(i,item){\n cb(item.unescapedUrl);\n if ( i == 0 ) return false;\n });\n });\n}",
"function parseInstagram(url,isLast) {\n\t\t/* Defining regexes for instagram */\n\t\tvar regex = /<img class=\"photo\" [^>]*>/m;\n\t\tvar httpregex = /http[^\"]*/;\n\t\t/*\n\t\t* Requesting Web URL, parsing the HTML code, looking for the required image url\n\t\t*/\n\t\tvar options = { url: url, pool:{maxSockets: 500 }};\n\t\trequest(options,\n \tfunction(error, response, body){\n \t\tif (!error && response.statusCode == 200) {\t\n \t\t\tif ( regex.test(body) ) { \t\t\n \t\t\t\timageurls.push(body.match(regex)[0].match(httpregex)[0]);\n \t\t\t}\n \t\t}\n \t\tcounter++;\n \t\tisLast || counter==goal?callback(imageurls):counter--;\n \t\t\n \t\t}\n \t);\n }",
"function getImage(raw_data) {\r\n var ind = 0;\r\n for (let i = 0; i < raw_data.length; i++) {\r\n if (raw_data[i].url.includes('articleInline.jpg')) {\r\n ind = i;\r\n }\r\n }\r\n return raw_data[ind][\"url\"];\r\n}",
"function fnInstagram(word) {\n\t\tvar address = \"https://api.instagram.com/v1/tags/\" + word + \n\t\t\t\"/media/recent?callback=?&client_id=d51f6ee392ba41dfa0c28e580e9fa5da&min_id=10\";\n\t\t$.getJSON(address, fnDisplayPics);\n\t}",
"function printImages(hashtagSearch) {\n\n var searchUrl = \"https://api.instagram.com/v1/tags/\" + hashtagSearch + \"/media/recent\";\n var array = [];\n var output;\n var result = [];\n\n $.ajax({\n url: searchUrl,\n type: 'GET',\n data: {client_id:'61f8b631abd34732a3bcd8c73d0d73a9'},\n dataType:'jsonp',\n success:function(data){\n for (var i = 0; i <= 15; i++) {\n output = data.data[i].images.low_resolution;\n array.push(output);\n }\n shuffle(array,result);\n for (var j = 0; j<result.length - 7; j++) {\n $('.row1').append('<img src=' + result[j].url + '>');\n }\n }\n });\n}",
"function fetchImage(searchQuery){\r\n const endpoint = `https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles=${searchQuery}&origin=*`;\r\n fetch(endpoint)\r\n .then(response => response.json())\r\n .then(data => {\r\n const result = data.query.pages;\r\n const id = Object.keys(result)[0];\r\n if(result[id].original){\r\n const imgURL = result[id].original.source;\r\n console.log(imgURL); \r\n displayImage(imgURL);\r\n }\r\n })}",
"function fetchImage(searchQuery){\n const endpoint = `https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles=${searchQuery}&origin=*`;\n fetch(endpoint)\n .then(function(response){return response.json();})\n .then(function(response) {\n const result = response.query.pages;\n const id = Object.keys(result)[0];\n if(result[id].original){\n const imgURL = result[id].original.source;\n console.log(imgURL); \n displayImage(imgURL);\n }\n})}",
"function getInstaPhotos(_callback) {\n var hex = [];\n var color = [];\n var instaPhotos = [];\n\n //get width and height of the original image\n var w = getWidth();\n var h = getHeight();\n var area = numPixels();\n\n //Call image data to get an array of RGBA values for the uploaded image\n var imgData = getImageData();\n\n // enumerate all pixels\n // each pixel's r,g,b,a datum are stored in separate sequential array elements\n for (var i = 0; i < imgData.length; i += 4) {\n var rgb = [];\n rgb[0] = imgData[i]; //red\n rgb[1] = imgData[i + 1]; //green\n rgb[2] = imgData[i + 2]; //blue\n rgb[3] = imgData[i + 3]; //alpha\n\n // convert RGBA color data from the original image to hex values\n hex[hex.length] = ((rgb && rgb.length === 4) ? \"#\" \n + (\"0\" + parseInt(rgb[0],10).toString(16)).slice(-2) \n + (\"0\" + parseInt(rgb[1],10).toString(16)).slice(-2) \n + (\"0\" + parseInt(rgb[2],10).toString(16)).slice(-2) : '');\n \n //match hex to closest text string color name - this is the name that will be used to search for the tag on Instagram\n var n_match = ntc.name(hex[hex.length-1]);\n\n //Pull tagged images from Instgram, but do not display them yet - save their data in images JSON array\n //More information about the input here can be found at http://instafeedjs.com/\n var feed = new Instafeed({\n get: 'tagged',\n sortBy: 'random',\n tagName: n_match[1].replace(/\\s+/g, ''),\n clientId: myClientId,\n limit: 1,\n resolution: 'thumbnail',\n mock: true,\n success: function(data) {\n var images = data.data;\n var hashImage = images[0].images.low_resolution.url;\n instaPhotos[instaPhotos.length] = hashImage;\n //console.log(area);\n //console.log(instaPhotos.length);\n \n //Checks to make sure the Instaphoto array is the same number of pixels that are in the pixelated image\n if (area == instaPhotos.length) {\n //console.log(instaPhotos);\n //console.log('done!');\n drawMosaic(w,h,area,instaPhotos);\n return instaPhotos;\n }\n },\n //If no image is returned from Instagram, place in a placeholder error image\n error: function() {\n instaPhotos[instaPhotos.length] = errorImage;\n if (area == instaPhotos.length) {\n drawMosaic(w,h,area,instaPhotos);\n return instaPhotos;\n }\n },\n });\n feed.run();\n }\n}",
"findImage(url) {\n const imageItem = this.m_images.get(url);\n if (imageItem !== undefined) {\n return imageItem.imageItem;\n }\n return undefined;\n }",
"function fetchInstagramPosts(){\n\tvar feed = new Instafeed({\n\t\tget: 'user',\n\t\tuserId: 227012267,\n\t\taccessToken: '283823831.ee2c8fb.d8276e2ea678489f9a2d283b720dc64a',\n\t\tresolution: 'low_resolution',\n\t\ttemplate: '<img class=\"instagramPhotoFormatting\" onclick=OpenUrlInMobileOrWebpage(\"{{link}}\",\"{{id}}\") class=\"instagram\" src=\"{{image}}\"/>'\n\t});\n\tfeed.run();\t\n}",
"function extractImages(html){\r\n var regex = /<img[^>]*>/g; \r\n var img = html.match(regex);\r\n if (img != [] && img != null){\r\n return img[0]\r\n }\r\n else {return \"\";}\r\n }",
"function parseInstagramMediaUrl(instagramImgUrl) {\n // Doing something special here because there is a query string on the end of the\n // file name for the ig_cache_key. This cache key can have a . in it\n var ext = path.extname(url.parse(instagramImgUrl).pathname);\n return {\n url: instagramImgUrl,\n // Strip out the leading period\n ext: ext.substr(1)\n };\n}",
"function getImages(LAT, LNG) {\n $('.retry').show();;\n console.log(LAT, LNG);\n var client_id = '813efa314de94e618290bc8bfcbbb1ac';\n // URL for API request to find recent media by location\n var imagesUrl = 'https://api.instagram.com/v1/media/search?lat='+LAT+'&lng='+LNG+'&distance=5000&client_id='+client_id;\n console.log(imagesUrl);\n\n var result = $.ajax({\n url: imagesUrl,\n dataType: \"jsonp\",\n type: \"GET\",\n })\n .done(function(result){\n console.log(result);\n $('#results').html('');\n if (result.data.length > 0) {\n for (var i = 0; i < result.data.length; i++) {\n var photos = result.data[i].images.thumbnail.url;\n $('#results').append('<img src=\"'+photos+'\" alt=\"photo\" style=\"border-radius:10%\" class=\"hover\">');\n hoverAnimations();\n }\n }\n else {\n $('#results').append(\"Hmm. I couldn’t find anything!\");\n }\n\n });\n }",
"function queryInsta(tag) {\n instagram_url=\"https://api.instagram.com/v1/tags/\"+ tag +\"/media/recent\" + getcount + instragram_key + callback;\n\tgrabInsta();\n\t//addnewtoDB(instagram_url);\t\t\t\t// Ask instagram for tag name\n \n}",
"function getImage(tag, returnTo){\n request\n .get('api/v1/images')\n .query({method: \"flickr.photos.search\", tags: tag, format: \"json\", nojsoncallback: 1})\n .end(function(err, res){\n var response = JSON.parse(res.body.text)\n var urlData= {\n farm: response.photos.photo[0].farm,\n server: response.photos.photo[0].server,\n id: response.photos.photo[0].id,\n secret: response.photos.photo[0].secret\n }\n var url = \"//c\"+urlData.farm+\".staticflickr.com/\"+urlData.server+\"/\"+urlData.id+\"_\"+urlData.secret+\".jpg\"\n $(returnTo).attr('src', url)\n })\n }",
"function instagramAPI(){\n const instagramURL = 'https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,permalink,thumbnail_url,timestamp&access_token=';\n const url = instagramURL + authKey;\n fetch(url)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayResults(responseJson))\n .catch(err => {\n $('#errorMessage').text(`Something went wrong: ${err.message}`);\n });\n}",
"function image_adder(match, offset, string) {\n\t\t\tif(offset.startsWith(\"image.base64/\")){\n\t\t\t\tif(IPython.notebook.metadata.hasOwnProperty(\"image.base64\") && IPython.notebook.metadata[\"image.base64\"].hasOwnProperty(offset)){\n\t\t\t\t\toffset = IPython.notebook.metadata[\"image.base64\"][offset];//Set offset\n\t\t\t\t\tmatch = match.replace(/src=\"(.*?)\"/g, 'src=\"'+ offset +'\"');//Replaces source in match\n\t\t\t\t}\n\t\t\t\telse{//If image is not in notebook metadata\n\t\t\t\t\tconsole.log('Image \"'+offset+'\" could not be loaded.');\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn match;\n\t\t}",
"function getImg(query) {\n let url = `https://api.unsplash.com/search/photos?query=${query}&client_id=WC50gXbaEOyoD0ivn2KKie6Zi92i4yqvzKxDJxVgUqs`;\n getRequest(url, (data) => {\n mainImgTop.src = data.results[0].urls.regular;\n removeChild(containerImgs);\n for (let i = 1; i < 10; i++) {\n let img = document.createElement(\"img\");\n img.src = data.results[i].urls.regular;\n containerImgs.appendChild(img);\n }\n });\n}",
"function scrapeimg(name,element){\n var globalurl;\n var scraperes = [];\n element.forEach(function(img){\n scraperes.push($(document).find(img));\n });\n var search=name.split(\"-\")[0].split(\"&\")[0].trim().split(\",\")[0].trim().split(\"ft.\")[0].trim().split(\"vs\")[0].trim().split(\"Ft.\")[0].trim().split(\"feat.\")[0].trim().split(\"Feat.\")[0].trim().split(' ').join('-');\n search = deUmlaut(search);\n var url = encodeURIComponent('https://genius.com/artists/' + search);\n ////console.log(search);\n ////console.log(url);\n ////////console.log(name);\n ////////console.log(search);\n ////////console.log(url);\n fetch(`https://api.allorigins.win/get?url=${url}`)\n .then(response => {\n if (response.ok) return response.json()\n throw new Error('Network response was not ok.')\n })\n .then(function(data){\n //var res = data.find();\n var base64;\n var quick = data.contents;\n ////////console.log(quick);\n var index = quick.search(\"user_avatar\");\n var quick = quick.substring(index,quick.lenght);\n index = quick.search(\"url\\\\('\");\n quick = quick.substring(index+5,quick.lenght);\n var imgurl = quick.split(\"'\")[0];\n //imgurl='https://api.allorigins.win/get?url=${url' + imgurl + '}';\n ////////console.log(imgurl);\n globalurl = imgurl;\n /*\n try{\n toDataURL(\n imgurl,\n function(dataUrl) {\n base64 = dataUrl;\n scraperes.forEach(image => {\n if(dataUrl){\n image.attr(\"src\",dataUrl);\n //console.log(\"base64\");\n }\n else{\n image.attr(\"src\",imgurl);\n //console.log(\"img source\");\n }\n\n }); \n });\n }\n catch(e){\n //console.log(\"getting dominant color failed\");\n }\n */\n scraperes.forEach( image => image.attr(\"src\",imgurl) ); \n //////console.log(scraperes);\n\n ////console.log(imgurl);\n //scraperes.each(function() {\n // $(this).prop(\"src\",imgurl))\n // $(this).children('.time').after($('.inner'));\n //});\n //$(scraperes).prop(\"src\",imgurl);\n });\n $(element[0])\n .on('load', function() { \n\n })\n .on('error', function(){\n setTimeout(function(){\n $(this).prop(\"src\",\"https://cdn.discordapp.com/attachments/331151226756530176/725817255484719124/AURFavicon.webp\");\n },5000);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get books Local Storage | static getBooks() {
let books;
if (localStorage.getItem("books") === null) {
books = [];
} else {
books = JSON.parse(localStorage.getItem("books"));
}
return books;
} | [
"static getBooks() {\n let books = JSON.parse(localStorage.getItem('books')) || [];\n return books;\n }",
"static getBooksFromLS() {\n let books;\n if (localStorage.getItem('books') === null) {\n books = [];\n } else {\n books = JSON.parse(localStorage.getItem('books'));\n }\n\n return books;\n }",
"static getBooks() {\n let books;\n if (localStorage.getItem('books') === null) {\n books = [];\n } else {\n books = JSON.parse(localStorage.getItem('books'));\n }\n return books;\n }",
"static getBooks() {\n let books;\n if (localStorage.getItem(\"books\") === null) {\n books = [];\n } else {\n books = JSON.parse(localStorage.getItem(\"books\"));\n }\n\n return books;\n }",
"static getBook() {\n let books;\n if (localStorage.getItem('books') === null) {\n books = [];\n } else {\n books = JSON.parse(localStorage.getItem('books'));\n }\n\n return books;\n }",
"static getBooks() {\n let books;\n\n if(localStorage.getItem('books') === null) {\n books = [];\n }else{\n books = JSON.parse(localStorage.getItem('books'));\n }\n\n return books;\n }",
"static getBooks(){\n \n let books;\n\n if(localStorage.getItem('book') === null){\n books = [];\n } else{\n let temp = localStorage.getItem('book');\n books = JSON.parse(temp,0);\n }\n\n return books;\n }",
"function getBookList() {\n return JSON.parse(localStorage.getItem(\"books\"));\n}",
"static getBook(){\n let books;\n if(localStorage.getItem('books')===null){\n books=[];\n }else{\n books=JSON.parse(localStorage.getItem('books'));\n }\n return books;\n\n }",
"function getBookList(){\n books = readfile.getData(bookDataPath);\n return books;\n}",
"function _readBook() {\n var temp = window.localStorage[\"book\"]\n\n if (!temp) _data = [];\n else _data = JSON.parse(temp);\n\n return _data;\n }",
"function getBooksData() {\n const bookCards = JSON.parse(localStorage.getItem('book cards'));\n return bookCards === null ? [] : bookCards;\n}",
"function getLocalMemory() {\n let getBookArray = JSON.parse(localStorage.getItem(\"bookData\"));\n\n if (getBookArray == null) {\n return null;\n } else {\n for (let i = 0; i < getBookArray.books.length; i++) {\n\n let book = getBookArray.books[i].bookName;\n let author = getBookArray.books[i].authorName;\n let type = getBookArray.books[i].bookType;\n let dateti = getBookArray.books[i].dateTime;\n addBook(book, author, type, dateti);\n }\n return getBookArray;\n }\n}",
"function getLibraryFromLocal() {\n let lib_arr = localStorage.getItem('library_arr');\n if (lib_arr !== null) {\n lib_arr = lib_arr.substring(2, lib_arr.length - 2).split('},{');\n lib_arr.forEach(entry => {\n entry = entry.replace(/\"/g, \"\");\n let values = entry.split(',');\n let name = values[0].substring(5);\n let author = values[1].substring(7);\n let pages = values[2].substring(6);\n let read = values[3].substring(5);\n addBookToLibrary(new Book(name, author, pages, read));\n });\n }\n}",
"function getBooksFromSessionStorage() {\n\treturn JSON.parse(sessionStorage.getItem(\"books\"));\n}",
"static addBooks(book) {\n\t\t// Fetch the books from the local storage\n\t\tconst books = LocalStorage.getBooks();\n\n\t\t// Add the newly added data to the array by PUSHing\n\t\tbooks.push(book);\n\n\t\t// Set the local storage with the newly fetched item\n\t\tlocalStorage.setItem('books', JSON.stringify(books));\n\t}",
"static addBookToLocalStorage(book){\n\n const books = Store.getBooks();\n books.push(book);\n\n localStorage.setItem('book',JSON.stringify(books));\n }",
"restoreSavedBooks() {\n const savedBooks = localStorage.getItem(storageKey);\n savedBooks && this.setBooks(JSON.parse(savedBooks));\n }",
"function storeBookList(books) {\n let json_bookList = JSON.stringify(books);\n localStorage.setItem(\"books\", json_bookList);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws democratic words onto the layout | function drawDem(words) {
svgDem.append("g")
.attr("transform", "translate(" + layoutDem.size()[0] / 2 + "," + layoutDem.size()[1] / 2 + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("fill", "#4682B4")
.style("font-family", "Impact")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.word; });
} | [
"function drawWords() {\n\tctx.font = \"18px Arial\";\n\tctx.fillStyle = \"white\";\n\tctx.textAlign = \"center\";\n\tfor(var i = 0; i < words.length; i++) {\n\t\tctx.fillText(words[i], xPos[i], yPos[i]);\n\t}\n}",
"function drawWords() {\n\n\t// Draw out each word in the array of word objects\n\tfor (object in wordState) {\n\t\tvar word = wordState[object];\n\t\tconsole.log(word.string); \n\t\tcontext.font = word.size + \"px Arial\";\n\t context.fillText(word.string, word.x, word.y);\n\t}\n}",
"function drawWords() {\n let centerX = (leftWristX + rightWristX)/2;\n let centerY = (leftWristY + rightWristY)/2;\n \n let leftHeight = abs(leftWristY - leftHipY);\n let rightHeight = abs(rightWristY - rightHipY);\n \n let avgHeight = (leftHeight + rightHeight)/2\n let handXDiff = int(leftWristX - rightWristX);\n let lineCount = constrain(int(avgHeight/fontSize), 1, 6);\n yWaveSize = constrain(abs(handYDiff)/4, 20, 80);\n \n translate(centerX, centerY);\n // Reposition matrix depending on width & height of the grid\n translate(-(inpText.length-1)*tracking/2,0);\n noStroke();\n textFont(fontGenerator);\n textSize(fontSize);\n \n for(var j = 0; j<lineCount; j++){\n for(var i = 0; i < inpText.length; i++){\n yWave = sin(frameCount*yWaveSpeed + i*yWaveLength) * yWaveSize;\n yWavePost = sin(frameCount*yWaveSpeed + (i+1)*yWaveLength) * yWaveSize;\n let angleAdjust = atan2(yWavePost-yWave,tracking);\n \n fill(255);\n push();\n tracking = (handXDiff/inpText.length)\n let offSet = 1.5;\n translate(i*tracking,j*fontSize*offSet);\n let fontHeight = 7/10 * fontSize;\n \n translate(0,yWave);\n //ellipse(0,0,5,5);\n rotate(angleAdjust);\n // Reposition matrix to place the rotation point of the type in the middle of the X-Height (err... cap height) \n translate(0,fontHeight/2);\n text(inpText.charAt(i),0,0);\n pop();\n }\n }\n pop();\n \n }",
"function draw(words) {\r\n $(\"div.spanner\"). removeClass(\"show\");\r\n $(\"div.overlay\"). removeClass(\"show\");\r\n focus.selectAll(\"text\")\r\n .data(words)\r\n .enter()\r\n .append('text')\r\n .style('font-size', function (d) {\r\n return d.size + 'px'\r\n })\r\n .style('font-family', 'Impact')\r\n .attr('text-anchor', 'middle')\r\n .style('fill', fillColor)\r\n .attr('transform', function (d) {\r\n return 'translate(' + [d.x, d.y] + ')rotate(' + d.rotate + ')'\r\n })\r\n .text(function (d) {\r\n return d.text\r\n })\r\n .on('click', Click)\r\n }",
"displayWords(word) {\n push();\n fill(0, 255, 90);\n textSize(32);\n textFont('DotGothic16')\n text(word.string, word.x, word.y);\n pop();\n }",
"function drawRep(words) {\n svgRep.append(\"g\")\n .attr(\"transform\", \"translate(\" + layoutRep.size()[0] / 2 + \",\" + layoutRep.size()[1] / 2 + \")\")\n .selectAll(\"text\")\n .data(words)\n .enter().append(\"text\")\n .style(\"font-size\", function(d) { return d.size + \"px\"; })\n .style(\"fill\", \"#FF0000\")\n .style(\"font-family\", \"Impact\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"transform\", function(d) {\n return \"translate(\" + [d.x, d.y] + \")rotate(\" + d.rotate + \")\";\n })\n .text(function(d) { return d.word; });\n}",
"function drawWord(svg, elemWidth, elemHeight, word, loc, size) {\n\n\tvar x = loc.x;\n\tvar y = loc.y;\n\n\t// Draw draft of word to get height\n\tvar textDraft = svg.append(\"text\")\n\t\t\t\t\t .attr(\"id\", \"textDraft\")\n\t\t\t\t\t .attr(\"x\", x)\n\t\t\t\t\t .attr(\"y\", y)\n\t\t\t\t\t .text(word)\n\t\t\t\t\t .attr(\"font-family\", \"sans-serif\")\n\t\t \t\t .attr(\"font-size\", size + \"px\")\n\t\t\t\t\t .attr(\"fill\", WORD_COLOR)\n\n\tvar bounds = textDraft.node().getBoundingClientRect();\n\tvar w = bounds.right - bounds.left;\n\tvar h = bounds.bottom - bounds.top;\n\tsvg.selectAll(\"#textDraft\").remove();\n\n\t// Right side of page, draw hugging left side of bounding rect\n\tif (loc.x >= elemWidth / 2) {\n\t\tx += getRandomInt(0, RECT_MARGIN);\n\t} \n\t// Left side of page, draw hugging right side of bounding rect\n\telse {\n\t\t// x = loc.x + loc.width - w - RECT_MARGIN;\n\t\tx = loc.x + loc.width - w - getRandomInt(0, RECT_MARGIN);\n\t}\n\t// Bottom of page, draw hugging top of bounding rect\n\tif (loc.y >= elemHeight / 2) {\n\t\t// y += (3/4 * h);\n\t\ty += getRandomInt((3/4 * h), h);\n\t}\n\t// Top of page, draw hugging bottom of bounding rect\n\telse {\n\t\t// y = loc.y + loc.height - (1/4 * h);\n\t\ty = loc.y + loc.height - getRandomInt((1/4 * h), (1/2 * h));\n\t}\n\n\t// Draw \t\n\tvar textDraft = svg.append(\"text\")\n\t\t\t\t\t .attr(\"id\", \"textDraft\")\n\t\t\t\t\t .attr(\"x\", x)\n\t\t\t\t\t .attr(\"y\", y)\n\t\t\t\t\t .text(word)\n\t\t\t\t\t .attr(\"font-family\", \"sans-serif\")\n\t\t \t\t .attr(\"font-size\", size + \"px\")\n\t\t\t\t\t .attr(\"fill\", WORD_COLOR)\n\n\treturn [textDraft, x, y];\n}",
"function draw(words) {\n\t\td3.select(\"div#draw-word-cloud\").append(\"svg\")\n\t\t\t.attr(\"width\", width)\n\t\t\t.attr(\"height\", height)\n\t\t.append(\"g\")\n\t\t\t.attr(\"transform\", \"translate( \"+ width / 2 + \",\" + height / 2 + \")\")\n\t\t.selectAll(\"text\")\n\t\t\t.data(words)\n\t\t.enter().append(\"text\")\n\t\t\t.style(\"font-size\", function(d) { return getFontSize(d) + \"px\"; })\n\t\t\t.style(\"font-family\", \"Impact\")\n\t\t\t.style(\"fill\", function(d, i) { return fill(i); })\n\t\t\t.style(\"cursor\", \"pointer\")\n\t\t\t.attr(\"text-anchor\", \"middle\")\n\t\t\t.attr(\"transform\", function(d) {\n\t\t\t\treturn \"translate(\" + [d.x, d.y] + \")rotate(\" + d.rotate + \")\";\n\t\t\t})\n\t\t\t.text(function(d) { return d.name; })\n\t\t .on(\"mouseover.tooltip\", ns.sev.mouseoverShowTooltip)\n\t\t\t.on(\"mouseout.tooltip\", ns.sev.mouseoutHideTooltip)\n\t\t\t.on(\"click.tooltip\", ns.sev.mouseoutHideTooltip)\n\t\t\t.on(\"click.solr\", function(d) {\n\t\t\t\ttagConcat(d);\n\t\t\t\tajaxSolrFaceting();\n\t\t\t});\n\t}",
"function narration_newWord(phraseID, wordID){\n\n\tvar currentPhrase = phrases[phraseID][0];\n\tvar currentWord = currentPhrase[wordID];\n\n\tdummyText.text = currentWord; //crucial - takes the word and renders it in text_page's font and sizing\n\n\t//fix for word-highlighting: if l\\n line break is added to a word, do not increase narrationMask height to include it\n\tvar textHeight = dummyText.getMeasuredHeight();\n\tif(textHeight > 50) textHeight = textHeight/2;\n\n\t//make word-by-word text topmost (over definition words)\n // commented by @leio\n\t// world_current.addChild(text_page2);\n narrTextContainer.addChild(text_page2);\n\n\tnarrationMask.graphics.clear();\n\tnarrationMask.graphics.beginFill(\"white\").drawRect(0,0, dummyText.getMeasuredWidth(), textHeight + 1);\n\n\t//first check for linebreak, if yes.. move narrationMask to left start and down one text line\n\tfor(var i = 0; i < linebreaks.length; i++) {\n\t\tif (wordID == linebreaks[i])\n\t\t{\n\t\t\tnarrationMask.x = text_page.x;\n\t\t\tnarrationMask.y += text_page.lineHeight;\n\n\t\t\treturn;\n\t\t}\n\t}\n\t//if no linebreak, move narrationMask if currentWord is second or later word.\n\tif(wordID > 0) {\n\t\tvar prevWord = currentPhrase[wordID-1];\n\t\tdummyText.text = prevWord;\n\t\tnarrationMask.x += dummyText.getMeasuredWidth();\n\t}\n\n\t//FIX for any case where a _ was added to phrase, to later replace with a space char. highlight needs to move left a few px\n\tif(dummyText.text.indexOf('_') != -1){\n\t\tnarrationMask.x -= 15;\n\t}\n\n}",
"function renderNarration(sndID, defWords){\n\t//1) render text first:\n\t//need to do a check here to gather which words will be the line breaks (using incrementing string rendered in proper style in dummyText)\n\twholeString = \"\";\n\n \t//CRUCIAL- used to render current word *and prev word* in exact font style as text_page. useful for getting needing width measurements for mask\n\tdummyText = text_page.clone();\n\tdummyText.text = \"\";\n\n\tdefinitionMask = new createjs.Shape();\n\n\t//clear definitionBoxes on each page\n\tdefinitionBoxes = [];\n\n\tvar word= \"\";\n\tfor (var h=0; h < phrases[sndID][0].length; h++) {\n\t\tword = phrases[sndID][0][h];\n\t\tif(word.indexOf(\"_\") != -1 ){\n\t\t\tword = word.replace('_', ' ');\n\t\t}\n wholeString += word;\n\t}\n\n\ttext_page.text = wholeString;\n\n\t//after the complete text is rendered on page in proper style\n\t//check for line breaks , add word index to array linebreaks\n\t//CLEAR linebreaks each time a new phrase is rendered\n\tlinebreaks = [];\n\t//definitions = []; //hold all definition Containers\n\tlineString = \"\";\n\n\tdefWords1 = [];\n\tdefWords2 = [];\n\n\tif(defWords){\n\t\tdefWords1 = defWords.slice();\n\t\tdefWords2 = defWords.slice();\n\t}\n\n\tfor (var i=0; i < phrases[sndID][0].length; i++) {\n\t\tlineString += phrases[sndID][0][i];\n\n\t\tdummyText.text = lineString;\n\n\t\tif (dummyText.getMeasuredWidth() > (text_page.lineWidth + 10) ) //+10 is some extra pixels threshold to allow before considering linebreak\n\t\t{\n //Need to store this for use in narration_newWord (so it knows when to move narrationMask to down a line & back to left start)\n\t\t\tlinebreaks.push(i);\n\t\t\tlineString = phrases[sndID][0][i];\n\t\t}\n\n\t\t//def test:\n\t\tif(defWords1.length>0){\n\t\t\tfor (var h=0;h<defWords1.length;h++){\n\t\t\t\tvar theDef = defWords1[h] + ' ';\n\t\t\t\tif(theDef == phrases[sndID][0][i]){\n\t\t\t\t\tvar firstlinephrase;\n\t\t\t\t\tif(linebreaks.length == 0 ) firstlinephrase = phrases[sndID][0][0];\n\t\t\t\t\telse firstlinephrase = phrases[sndID][0][linebreaks.length-1];\n\n\t\t\t\t\tdefWords1.remove(h);\n\n\t\t\t\t\tgetDefPosition(sndID, theDef, lineString, linebreaks.length);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//if more than 4 or more lines (3 or more linebreaks, use smaller font size and line height\n\t//CRUCIAL- need to recaculate # of line breaks, have dummy text and text_page2 reset to match properites of text_page, recreate definitions and definitionMask\n\tif(linebreaks.length > 2){\n\t\ttext_page.font = \"24px Nunito\";\n\t\ttext_page.lineHeight = 30;\n\n\t\tdummyText = text_page.clone();\n\t\tdummyText.text = \"\";\n\n\t\t//RE-CALCULATING # of line breaks with smaller font size\n\t\tlinebreaks = [];\n\t\t//definitions = []; //hold all definition Containers\n\t\tlineString = \"\";\n\n\t\t//resetting already created definitions from default text rendering.\n\t\tdefinitionMask.graphics.clear();\n\t\tdefinitionBoxes = [];\n\n\t\tfor (var i=0; i < phrases[sndID][0].length; i++) {\n\t\t\tlineString += phrases[sndID][0][i];\n\n\t\t\tdummyText.text = lineString;\n\n\t\t\tif (dummyText.getMeasuredWidth() > (text_page.lineWidth + 0) ) //OLD: +10 is some extra pixels threshold to allow before considering linebreak\n\t\t\t{\n\t\t\t\t//Need to store this for use in narration_newWord (so it knows when to move narrationMask to down a line & back to left start)\n\t\t\t\tlinebreaks.push(i);\n\t\t\t\tlineString = phrases[sndID][0][i];\n\t\t\t}\n\n\t\t\t//def test, again:\n\t\t\tif(defWords2.length>0){\n\t\t\t\tfor (var h=0;h<defWords2.length;h++){\n\t\t\t\t\tvar theDef = defWords2[h] + ' ';\n\t\t\t\t\tif(theDef == phrases[sndID][0][i]){\n\t\t\t\t\t\tvar firstlinephrase;\n\t\t\t\t\t\tif(linebreaks.length == 0 ) firstlinephrase = phrases[sndID][0][0];\n\t\t\t\t\t\telse firstlinephrase = phrases[sndID][0][linebreaks.length-1];\n\n\t\t\t\t\t\tdefWords2.remove(h);\n\n\t\t\t\t\t\tgetDefPosition(sndID, theDef, lineString, linebreaks.length);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttext_page2 = text_page.clone();\n\ttext_page2.color = \"#0090ad\";\n\n // commented by @leio\n\t//world_current.addChild(text_page); \n narrTextContainer.addChild(text_page);\n\t//world_current.addChild(text_page2);\n\n\tnarrationMask = new createjs.Shape();\n\ttext_page2.mask = narrationMask;\n}",
"function draw(words) {\n var wordcloud = svg_wordcloud1\n // without the transform, words words would get cutoff to the left and top, they would\n // appear outside of the SVG area\n .attr(\"transform\", \"translate(200,200)\")\n .selectAll(\"text\")\n .data(words);\n\n wordcloud.enter().append(\"text\");\n\n wordcloud\n .style(\"font-size\", function(d) {\n return d.size + \"px\"; \n })\n .transition()\n .duration(1000)\n .style(\"fill\", function(d, i) { return color2(i); })\n .attr(\"transform\", function(d) {\n return \"translate(\" + [d.x, (d.y-38)] + \")rotate(\" + d.rotate + \")\";\n })\n .text(function(d) { return d.text; });\n\n wordcloud\n .on('mouseover', function(d) {\n tip.select('.text').html(\"Word: \" + d.text + \"<br>Occurrences: \" + (d.size - 10) + \" (\"\n + (((d.size - 10)/(filteredData.length)) * 100).toFixed(2) + \"%)\");\n tip.style('display', 'block');\n })\n .on('mouseout', function() {\n tip.style('display', 'none');\n });\n\n wordcloud.exit()\n .transition()\n .duration(1000)\n .remove();\n }",
"function drawDashes(chosenWord) {\n\t\tfor (var i = 0; i < chosenWord.length; i++) {\n\t\t\t$($wordContainer).append('<div class=\"blank\"> _ </div>')\n\t\t}\n\t}",
"function wordle(div, words, pattern) { \n // 'div' is the div that renders the svg; 'words' is the bag of words for the word cloud; 'pattern' is the macro patter, i.e., if you want your word cloud to be \"CLOUD\", pattern should be \"CLOUD\".\n // words = shuffle(words);\n var divToRender = $('#' + div);\n var wordsList = processWords(words, pattern);\n var numOfLetters = pattern.length;\n var cloudColors = [\"#fff\", \"#F5D76E\", \"#c8d6e5\", \"#9AECDB\", \"#55E6C1\", \"#9AECDB\", \"#25CCF7\"];\n // assign divs\n var numOfSpaces = 0;\n var numOfValidChars = countValidChars(pattern);\n for (var i = 0; i < numOfLetters; i++) {\n var letter = pattern.charAt(i);\n if (letter == ' ') {\n numOfSpaces++;\n if (i != 0 && pattern.charAt(i - 1) == ' ') {\n } else {\n numOfValidChars++;\n var spaceDivId = numOfSpaces - 1;\n var newLetterDiv = '<div class=\"'+ div + '-letter letter-block\" style=\"width:' + 100.0/numOfValidChars + '%;\" id=\"space-' + spaceDivId + '\"></div>';\n divToRender.append(newLetterDiv);\n }\n continue;\n }\n var correctInd = i - numOfSpaces;\n var newLetterDiv = '<div class=\"'+ div + '-letter letter-block\" style=\"width:' + 100.0/numOfValidChars + '%;\" id=\"' + div + '-letter-' + correctInd + '\"></div>';\n divToRender.append(newLetterDiv);\n var components = letterComponent[letter];\n for (var j = 0; j < wordsList[correctInd].length; j++) {\n var newComponent = '<div class=\"cloud-components component-' + components[j] + '\" id=\"' + div + '-part-' + correctInd + '-' + j + '\"></div>';\n $('#' + div + '-letter-' + correctInd).append(newComponent);\n d3.wordcloud(div + '-part-' + correctInd + '-' + j)\n .size(componentDiv[components[j]])\n .fill(d3.scale.ordinal().range(cloudColors))\n .words(wordsList[correctInd][j])\n .onwordclick(function(d, i) {\n if (d.href) { window.location = d.href; }\n })\n .start();\n }\n }\n if (numOfValidChars > 3) {\n $('.' + div + '-letter').each(function(){\n $(this).css('zoom', 3/numOfValidChars);\n });\n }\n}",
"function updateText() {\n\n\t// Convert everyone to 2D space from 3D node position\n\tfor (var i=0; i<words.length; i++){\n\t\tvar vec = toXYCoords(words[i].coordinates)\n\t\twords[i].html.style.top = -25 + vec.y + 'px'\n\t\twords[i].html.style.left = 5 + vec.x + 'px'\n\t}\n\n\t//redraw() redrawing here destroys performance\n\n}",
"function drawEliminated(ctx) {\n const namesPerColumn = 14;\n const nameHeight = 20;\n const numColumns = 3;\n const columnWidth = (WIDTH - 100) / numColumns;\n ctx.save();\n\n ctx.translate(50, 97);\n ctx.font = '18px sans-serif';\n STATE.eliminated.forEach((name, i) => {\n const dx = Math.floor(i / namesPerColumn);\n const dy = i % namesPerColumn;\n ctx.fillText(name, dx * columnWidth, dy * nameHeight);\n });\n\n ctx.restore();\n}",
"function updateKWIC() {\n // kwic = RiTa.kwic(theText.join('\\n'), word, {\n // ignorePunctuation: true,\n // ignoreStopWords: true,\n // wordCount: 200\n // });\n kwic = RiTa.kwic(theTextCopy, word, {\n ignorePunctuation: true,\n // ignoreStopWords: true,\n wordCount: 10\n });\n // console.log(kwic);\n if (kwic.length == 0) {\n // textAlign(CENTER);\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textSize(14);\n text(\"Context word not found\", width / 1.7, height / 4);\n } else {\n\n var tw = textWidth(word);\n\n for (var i = 0; i < kwic.length; i++) {\n\n //console.log(display[i]);\n var parts = kwic[i].split(word);\n var x = width / 1.7,\n y = i * 20 + 115;\n\n if (y > height - 20) return;\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textSize(14);\n // fill(0);\n textAlign(RIGHT);\n text(parts[0], x - tw/1.5, y);\n\n fill(200, 0, 0);\n textFont(\"Lucida Console\");\n textAlign(CENTER);\n text(word, x, y);\n\n fill(255, 255, 255);\n textFont(\"Lucida Console\");\n textAlign(LEFT);\n text(parts[1], x + tw/1.5, y);\n }\n }\n}",
"function textFlow(myText,textToAppend,maxWidth,maxHeight,x,ddy,justified) {\n \n var svgNS = \"http://www.w3.org/2000/svg\";\n var xlinkNS = \"http://www.w3.org/1999/xlink\";\n var cartoNS = \"http://www.carto.net/attrib\";\n var attribNS = \"http://www.carto.net/attrib\";\n var batikNS = \"http://xml.apache.org/batik/ext\";\n \n //extract and add line breaks for start\n var dashArray = new Array();\n var dashFound = true;\n var indexPos = 0;\n var cumulY = 0;\n while (dashFound == true) {\n var result = myText.indexOf(\"-\",indexPos);\n if (result == -1) {\n //could not find a dash\n dashFound = false;\n }\n else {\n dashArray.push(result);\n indexPos = result + 1;\n }\n }\n //split the text at all spaces and dashes\n var words = myText.split(/[\\s-]/);\n var line = \"\";\n var dy = 0;\n var dx = \"0.15em\"\n var curNumChars = 0;\n var computedTextLength = 0;\n var myTextNode;\n var tspanEl;\n var lastLineBreak = 0;\n\n for (i=0;i<words.length;i++) {\n var word = words[i];\n curNumChars += word.length + 1;\n if (computedTextLength > maxWidth || i == 0) {\n if (computedTextLength > maxWidth) {\n var tempText = tspanEl.firstChild.nodeValue;\n tempText = tempText.slice(0,(tempText.length - words[i-1].length - 2)); //the -2 is because we also strip off white space\n tspanEl.firstChild.nodeValue = tempText;\n if (justified) {\n //determine the number of words in this line\n var nrWords = tempText.split(/\\s/).length;\n computedTextLength = tspanEl.getComputedTextLength();\n var additionalWordSpacing = (maxWidth - computedTextLength) / (nrWords - 1);\n tspanEl.setAttributeNS(null,\"word-spacing\",additionalWordSpacing);\n //alternatively one could use textLength and lengthAdjust, however, currently this is not too well supported in SVG UA's\n }\n }\n if(cumulY > maxHeight){\n return;\n }\n tspanEl = document.createElementNS(svgNS,\"tspan\");\n tspanEl.setAttributeNS(null,\"x\",x);\n tspanEl.setAttributeNS(null,\"dx\",dx);\n tspanEl.setAttributeNS(null,\"dy\",dy);\n myTextNode = document.createTextNode(line);\n tspanEl.appendChild(myTextNode);\n textToAppend.appendChild(tspanEl);\n\n if(checkDashPosition(dashArray,curNumChars-1)) {\n line = word + \"-\";\n }\n else {\n line = word + \" \";\n }\n if (i != 0) {\n line = words[i-1] + \" \" + line;\n }\n dy = ddy;\n cumulY += dy + parseInt(d3.select(textToAppend).style(\"font-size\").replace(\"px\", \"\"));\n }\n \n else {\n if(checkDashPosition(dashArray,curNumChars-1)) {\n line += word + \"-\";\n }\n else {\n line += word + \" \";\n }\n }\n tspanEl.firstChild.nodeValue = line;\n computedTextLength = tspanEl.getComputedTextLength();\n if (i == words.length - 1) {\n if (computedTextLength > maxWidth) {\n var tempText = tspanEl.firstChild.nodeValue;\n tspanEl.firstChild.nodeValue = tempText.slice(0,(tempText.length - words[i].length - 1));\n if(cumulY > maxHeight){\n return;\n }\n tspanEl = document.createElementNS(svgNS,\"tspan\");\n tspanEl.setAttributeNS(null,\"x\",x);\n tspanEl.setAttributeNS(null,\"dx\",dx);\n tspanEl.setAttributeNS(null,\"dy\",dy);\n myTextNode = document.createTextNode(words[i]);\n tspanEl.appendChild(myTextNode);\n textToAppend.appendChild(tspanEl);\n }\n\n }\n }\n return cumulY;\n }",
"function drawWordCloud(words) {\n \t\ttooltipWordcloud.selectAll(\".word-cloud\")\n \t\t\t.remove();\n\t\ttooltipWordcloud.selectAll(\".word-cloud\")\n\t .data(words)\n\t \t.enter().append(\"text\")\n\t .attr(\"class\",\"word-cloud\")\n\t .style(\"font-size\", function(d) { return d.size + \"px\"; })\n\t .style(\"font-family\", function(d) { return d.font; })\n\t .style(\"fill\", function(d) { return colorScale(d.score); })\n\t .attr(\"transform\", function(d) { return \"translate(\" + [d.x, d.y] + \")rotate(\" + d.rotate + \")\"; })\n\t .text(function(d) { return d.text; });\n \t}//function drawWordCloud",
"function democratOnly() {\nbackground(250);\nfill(2,27,189);\nfor(var i = 0; i < democrats.length; i++){\n var rand1 = random(50,1150);\nvar rand2 = random(50,600);\n voteCount = countDemVotes(democrats[i]);\n //changes size of vote depending on total number of votes\n if(voteCount > 50){\n textSize(35);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 40) {\n textSize(30);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 30){\n textSize(25);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 20){\n textSize(20);\n text(democrats[i], rand1 , rand2);\n }else if(voteCount > 10){\n textSize(15);\n text(democrats[i], rand1 , rand2);\n }else{\n textSize(10);\n text(democrats[i], rand1 , rand2);\n }\n \n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit book status we will call this funciton inside of the click handler function in order to pass the book ID and statusChange | function changeReadStatus(bookID, currentStatus) {
$.ajax({
method: 'PUT',
// need the book ID in the url
// can grab with data-id
// will get with the click handler
url: `/books/isRead/${bookID}`,
data: {
currentStatus: currentStatus,
},
})
.then(function (response) {
refreshBooks();
})
.catch(function (err) {
console.log('error', err);
alert('Error! Try again later');
});
} | [
"function changeStatus(e) {\n let bookIndex = e.target.dataset.index;\n let chosenBook = library[bookIndex];\n\n if (chosenBook.readStatus == \"already read\") {\n chosenBook.readStatus = \"unread\";\n } else {\n chosenBook.readStatus = \"already read\";\n }\n createTable();\n saveLibrary(library);\n }",
"function changeBookingStatus(booking){\n console.log('Booking status of ' + booking.id + ' changed to: ' + booking.status);\n }",
"function changeStatus(event) {\n\tlet x=event.target.getAttribute(\"data-index\");\n\t\n\tif (library[x].status===\"read\"){\n\t\tlibrary[x].status=\"not read\";\n\t\t}\n\telse {\n\t\tlibrary[x].status=\"read\"\n\t\t}\n\tdisplayBook(library);\n\t}",
"function updateBookingStatus() {\n\n }",
"function editBook() {\n helper.fadeBetweenElements(\"#bookContent, #dataPreview\", \"#bookForm\");\n newPreviousBook = helper.clone(globalVars.book);\n showProperButton(\"editBook\");\n\n // Below the above setters so previous value doesn't change descLength\n limitDescriptionLength(true);\n imageUploadListeners();\n bookBackButtonListener(true);\n\n $('#save').unbind().click(function() {\n if (bookFormIsValid() && editBookDetails()) {\n // Update the global book with the data in the fields\n globalVars.book.image = helper.getById(\"bookImage\").src;\n globalVars.book.name = helper.getById(\"bookName\").value;\n globalVars.book.description = helper.getById(\"bookDescription\").value;\n\n // Saves the edits from the page immediately\n updateBook(true);\n fadeToBookContent();\n }\n });\n\n $(\"#bookImage\").unbind().click(function() {\n $(\".cloudinary-button\").click();\n });\n}",
"function handleEditButtonClick(event) {\r\n editBookID = event.target.parentNode.parentNode.parentNode.getAttribute('data-id');\r\n showEditBookModal();\r\n for (let book of allBooks) {\r\n if (Number(book.id) === Number(editBookID)) {\r\n initializeEditBookModalValues(book);\r\n }\r\n }\r\n}",
"function handleEdit() {\n console.log('clicked edit');\n editID = $(this).data(\"id\");\n console.log('edit ID: ', editID);\n editMode = true;\n console.log('edit mode activated');\n $('#cancel-button-zone').append(`\n <button class=\"cancel-button\">Cancel</button>\n `)\n $('#edit-change-h3').text('Edit Book')\n \n}",
"function editBook(e) {\n const formElement = document.querySelector('form');\n if (formElement.lastElementChild.textContent === 'EDIT') {\n return;\n }\n let bookRow = e.target.parentElement.parentElement;\n // 'curr' means the data for the book we want to edit \n let currTitle = bookRow.children[0].textContent;\n let currAuthor = bookRow.children[1].textContent;\n let currIsbn = bookRow.children[2].textContent;\n\n titleInput.value = currTitle;\n authorInput.value = currAuthor;\n isbnInput.value = currIsbn;\n\n let id = bookRow.dataset.id;\n\n const temporaryEditBtn = document.createElement('button');\n temporaryEditBtn.textContent = 'EDIT';\n createBtn.style.display = 'none';\n formElement.appendChild(temporaryEditBtn);\n\n temporaryEditBtn.addEventListener('click', () => {\n let editedTitle = titleInput.value;\n let editedAuthor = authorInput.value;\n let editedIsbn = isbnInput.value;\n\n fetch(exactBookUrl + `${id}.json`, {\n method: 'PUT',\n body: JSON.stringify({\n title: editedTitle,\n author: editedAuthor,\n isbn: editedIsbn\n })\n })\n .then(res => {\n if (res.ok) {\n loadBooks();\n } else {\n throw res;\n }\n })\n .catch(err => console.log(err));\n\n createBtn.style.display = 'block';\n temporaryEditBtn.remove();\n\n titleInput.value = '';\n authorInput.value = '';\n isbnInput.value = '';\n });\n }",
"editStatus(parcelId, status) {\n const apiKey = this.getApiKey();\n const parcelInfo = {\n status,\n };\n\n return HttpRequest.putWithHeader(`${endPoint}/parcels/${parcelId}/status`, parcelInfo, apiKey)\n .then(result => result);\n }",
"static setCurrentBook(bookToEdit) {\n currentBook = bookToEdit;\n // console.log(currentBook);\n }",
"function changeStatus(booking, choice){\n booking.status = choice;\n bookingAdminService.convertStatus(booking);\n bookingAdminDataService.changeBookingStatus(booking);\n }",
"function onClickEdit(id) {\n var eBk = {};\n bookings.map(bk => {\n if (bk._id === id) {\n eBk = bk;\n }\n });\n setBookingEdit(eBk);\n }",
"function changeStatus(offer_uid, status, callback, err_call){\n requestService.updateData([prefix, offer_uid], {status:status}, callback, err_call);\n }",
"openChangeStatusClick(fileNumber, newStatus){\n\t this.setState({updateStatus:true});\n\t this.setState({currentFile:fileNumber});\n\t this.setState({currentStatus: newStatus});\n }",
"function changeOrdStatus(){\r\n\t\tif(confirm('Do you want to change the order status?')){\r\n\t\t\torid = $('[name=\"ordstatusid\"]').val();\r\n\t\t\tstatus = $('[name=\"orderstatus\"]').val();\r\n\t\t\tstatusname = $('[name=\"statusname\"]').val();\r\n\t\t\t$.ajax({\r\n\t\t\t\turl:'ajax.php',\r\n\t\t\t\tdata:{\"status\":status,\"orderid\":orid},\r\n\t\t\t\ttype:'POST'\r\n\t\t\t});\r\n\t\t\tif(status==3){\r\n\t\t\t\tunpaidstyle(orid);\r\n\t\t\t}else if(status<=2){\r\n\t\t\t\tnormalstyle(orid,status);\r\n\t\t\t}\r\n\t\t\t$('#status'+orid).html(statusname)\r\n\t\t\tif(status==2){\r\n\t\t\t\t$('#status'+orid).html(\"<i class='fa fa-spinner fa-spin'></i> \"+statusname)\r\n\t\t\t}\r\n\t\t}$('#modal-status').click()\r\n\t}",
"function updateBook() {\n let id = $('#updatebookId').text();\n let title = $('#updatebookTitle').val();\n let author = $('#updatebookAuthor').val();\n let isbn = $('#updatebookIsbn').val();\n\n let book = { title, author, isbn };\n request.put(id, JSON.stringify(book), updateCurrentBookInList, onError);\n\n $('#updatebookId').text('');\n $('#updatebookTitle').val('');\n $('#updatebookAuthor').val('');\n $('#updatebookIsbn').val('');\n\n showAddForm();\n}",
"function updateBookStatusClosed(orderId, db){\n\tlogger.info(\"ordersUtil>> updateBookStatusClosed start...\");\n\n\tvar collection = db.collection('orders');\n\tvar query = {orderId: orderId};\n\tcollection.find(query).toArray(function(err, docs){\n\t\tif(docs.length == 0){\n\t\t\tlogger.info(\"ordersUtil>> this shall not happen, orderId not found: \" + orderId);\n\t\t} else {\n\t\t\tvar order = docs[0];\n\t\t\tlogger.info(\"ordersUtil>> order: \" + JSON.stringify(order));\n\n var username = order[\"username\"];\n\n\t\t\tvar books = order[\"books\"];\n\t\t\tlogger.info(\"ordersUtil>> # of books in order: \" + books.length);\n\n\t\t\tfor(var i=0; i<books.length; i++){\n\t\t\t\tlogger.info(\"ordersUtil>> found book id: \" + books[i][\"book_id\"]);\n\t\t\t\tvar curBookId = books[i][\"_id\"];\n\t\t\t\tvar query2 = {_id: ObjectId(curBookId)};\n\t\t\t\tlogger.info(\"ordersUtil>> query2: \" + JSON.stringify(query2));\n\n\t\t\t\tvar hold_by = username;\n\t\t\t\tvar status = \"可借閱\";\n\t\t\t\tvar update = {$set: {hold_by: hold_by, status: status}};\n\t\t\t\tlogger.info(\"ordersUtil>> update: \" + JSON.stringify(update));\n\n\t\t\t\tvar collectionBooks = db.collection('books');\n\t\t\t\tcollectionBooks.update(query2, update, function(err, docs){\n\t\t\t\t\tlogger.info(\"ordersUtil>> book status updated: \" + curBookId);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n}",
"function ChangeDocumentStatusByID() {\r\n if (requiredValidator(\"dvManageDocumentStatus\", false)) {\r\n $(\"#loadingPage\").fadeIn();\r\n var stat = '';\r\n stat = decodeURI($(\"input:radio[name=DocumentStatus]:checked\").val());\r\n if (stat != \"\" && changedocumentstatusbyid != '') {\r\n if (stat.trim() != '' && changedocumentstatusbyid.trim() != '') {\r\n $.ajax({\r\n url: vApiBaseSiteUrl +'/api/accounts/' + localStorage.AccountID + '/documents/changestatus?documentid=' + changedocumentstatusbyid.trim() + '&status=' + stat,\r\n type: 'PUT',\r\n dataType: 'json',\r\n headers: {\r\n 'eContracts-ApiKey': localStorage.APIKey, 'eContracts-RestrictionHeader': localStorage.RestrictHighSecurityTagging, username: localStorage.UserName\r\n },\r\n contentType: false,\r\n cache: false,\r\n success: function (result) {\r\n $(\"#dvManageDocumentStatus\").dialog(\"close\");\r\n if ($(\"#hdIsPrimaryDoc\").val() == \"Yes\") {\r\n try {\r\n BindContractDetails(vContractID, \"allow\");\r\n } catch (ex) {\r\n }\r\n } else {\r\n //BindDocument(vContractID);\r\n refreshdocuemnt();\r\n }\r\n changedocumentstatusbyid = '';\r\n $(\"#loadingPage\").fadeOut();\r\n },\r\n error: function (person) {\r\n $(\"#loadingPage\").fadeOut();\r\n },\r\n });\r\n }\r\n }\r\n }\r\n}",
"function changeTableStatus(event, status) {\n event.stopPropagation();\n const btn = document.getElementById(event.currentTarget.id);\n post(\"/api/authStaff/changeTableStatus\",\n JSON.stringify({newStatus: status, tableId: btn.dataset.tableid.toString()}),\n null);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The description of the directory. If this directory is not a mailing list, then setting this attribute will send round a "DirName" update via nsIAddrBookSession. attribute AString dirName; | get dirName()
{
//exchWebService.commonAbFunctions.logInfo("exchangeAbFolderDirectory: get dirName\n");
var result = exchWebService.commonAbFunctions.getDescription(this.uuid);
if (this.useGAL) {
result = result + " (+GAL)";
}
return result;
} | [
"get directory() {\n return this._directory;\n }",
"get description()\n\t{\n\t\texchWebService.commonAbFunctions.logInfo(\"exchangeAbFolderDirectory: get description\\n\");\n\t\treturn this._description;\n\t}",
"get dir(){\r\n\t\treturn path2lst(this.path).slice(0, -1).join('/') }",
"get dirPrefId()\n\t{\n\t\texchWebService.commonAbFunctions.logInfo(\"exchangeAbFolderDirectory: get dirPrefId: \"+this.uuid);\n\t\treturn this._dirPrefId;\n\t}",
"get dirType()\n\t{\n\t\texchWebService.commonAbFunctions.logInfo(\"exchangeAbFolderDirectory: get dirType\\n\");\n\t\treturn 2;\n\t}",
"setDirname( dirname )\n\t{\n\t\tsuper.setDirname( dirname );\n\n\t\tthis.nodes.forEach( node =>\n\t\t{\n\t\t\tnode.setDirname( this.path );\n\t\t});\n\t}",
"function getNewDirName() {\n\tvar pname;\n\tvar params;\n\n\tpname = window.prompt('Enter new directory name.', '');\n\tif (pname == null || pname == '') return null;\n\tparams = 'dirname=' + encodeURIComponent(pname);\n\treturn params;\n}",
"set entry(value) {\n this.dirEntry_ = value;\n\n // Set helper attribute for testing.\n if (window.IN_TEST) {\n this.setAttribute('full-path-for-testing', this.dirEntry_.fullPath);\n }\n }",
"get entry() {\n return this.dirEntry_;\n }",
"get isDirectory() {\r\n return true\r\n }",
"get fileName()\n\t{\n\t\texchWebService.commonAbFunctions.logInfo(\"exchangeAbFolderDirectory: get fileName\\n\");\n\t\treturn \"filename\";\n\t}",
"function DisplayDownloadDirPref()\n{\n var folderListPref = document.getElementById(\"browser.download.folderList\");\n var currentDirPref = IndexToFolder(folderListPref.value); // file\n var prefutilitiesBundle = document.getElementById(\"bundle_prefutilities\");\n var iconUrlSpec = gFPHandler.getURLSpecFromFile(currentDirPref);\n var downloadFolder = document.getElementById(\"downloadFolder\");\n downloadFolder.image = \"moz-icon://\" + iconUrlSpec + \"?size=16\";\n\n // Display a 'pretty' label or the path in the UI.\n switch (FolderToIndex(currentDirPref)) {\n case kDesktop:\n downloadFolder.label = prefutilitiesBundle.getString(\"desktopFolderName\");\n break;\n case kDownloads:\n downloadFolder.label = prefutilitiesBundle.getString(\"downloadsFolderName\");\n break;\n default:\n downloadFolder.label = currentDirPref ? currentDirPref.path : \"\";\n break;\n }\n}",
"function changePresentDirStatus(string){\n document.getElementById('dir').innerText = string;\n}",
"getDirItemName(dirItem) {\n let itemName = '';\n try {\n itemName = encryption.decryptName(dirItem.name);\n } catch(e) {\n logger.warn(`Cant decrypt directory item: ${dirItem.name}. Not added to file structure.`);\n return undefined;\n }\n return itemName;\n }",
"function getDirectory() {return App.DNA.Hash;}",
"function abDirTreeItem(aDirectory)\n{\n this._directory = aDirectory;\n}",
"function DirectoryEntry () {\n this.children = {};\n this.buffer = new Buffer(0);\n this.sha = \"\";\n}",
"function createDirectory() {\n\t\t// Check if create dir is posible\n\t\tif (!dirContent.inf.isWritable) {\n\t\t\treturn alert(messages.writeProtect);\n\t\t}\n\n\t\tvar newDir = prompt(messages.enterNewDirName, messages.defaultNewDirName);\n\t\tif (newDir) {\n\t\t\tshowLoading();\n\t\t\tsendXMLHttpReq(reqURL, {\n\t\t\t\tmode: 'POST',\n\t\t\t\tparameters: 'cmd=mkdir&dst=' + encodeURIComponent(curPath) + '&name=' + encodeURIComponent(newDir),\n\t\t\t\tonsuccess: function (req) {\n\t\t\t\t\thideLoading();\n\t\t\t\t\t// Get result code of operation\n\t\t\t\t\tvar result = (JSON.parse(req.responseText)).result;\n\t\t\t\t\tif (result != 0) {\n\t\t\t\t\t\talert(sprintf(messages.operationFailed, result));\n\t\t\t\t\t}\n\t\t\t\t\tgetDirContent(curPath);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}",
"function displayDirListing() {\n\t\t\tvar dir = sys.dirContents,\n\t\t\t\ttotal_size = 0,\n\t\t\t\tinfoStr;\n\n\t\t\t// show out progress\n\t\t\tdisplayDialog({\n\t\t\t\ttype: 'progress',\n\t\t\t\tstate: 'show',\n\t\t\t\tlabel: 'Displaying directory contents...'\n\t\t\t});\n\n\t\t\tif (dir.length > 0) {\n\n\t\t\t\t// init the sidebar list element\n\t\t\t\t$('#sidebar').append('<ul></ul>');\n\t\t\t\t$('#browser').append('<ul></ul>');\n\n\t\t\t\t// cycle through the json array and create our directory list items from each entry\n\t\t\t\t$.each(dir, function (intIndex, objValue) {\n\t\t\t\t\tvar lis, lib, info;\n\n\t\t\t\t\t// create our SIDEBAR list items\n\t\t\t\t\tlis = $('<li>').attr({\n\t\t\t\t\t\tid: 'sidebar_ID' + intIndex,\n\t\t\t\t\t\trel: objValue.type === 'FILE' ? 'File' : 'Directory'\n\t\t\t\t\t}).addClass(objValue.ext).html('<span rel=\"' + objValue.name + '\">' + doShortentFileName(objValue.name, 20) + '</span>');\n\n\t\t\t\t\t// create our BROWSER list items\n\t\t\t\t\tlib = $('<li>').attr({\n\t\t\t\t\t\tid: 'browser_ID' + intIndex,\n\t\t\t\t\t\trel: objValue.type === 'FILE' ? 'File' : 'Directory'\n\t\t\t\t\t}).addClass(objValue.ext);\n\n\t\t\t\t\t// add a special class to the LI if it's a viewable image\n\t\t\t\t\tif (opts.showImgPreview && (objValue.ext === 'GIF' || objValue.ext === 'JPG' || objValue.ext === 'PNG')) {\n\t\t\t\t\t\tlib.addClass('viewable');\n\t\t\t\t\t}\n\n\t\t\t\t\t// parse things that should be numeric\n\t\t\t\t\tobjValue.width = parseInt(objValue.width, 10);\n\t\t\t\t\tobjValue.height = parseInt(objValue.height, 10);\n\t\t\t\t\tobjValue.size = parseInt(objValue.size, 10);\n\n\t\t\t\t\t// create our info box\n\t\t\t\t\tinfo = $('<div>').addClass('diritem').addClass(objValue.ext).attr('rel', objValue.name).append(\n\t\t\t\t\t\t'<div class=\"icon\" rel=\"' + objValue.name + '\">' +\n\t\t\t\t\t\t\t(typeof objValue.width === 'number' && typeof objValue.height === 'number' ? '<div class=\"imgHolder\"></div><div class=\"mask\"></div>' : '') +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div class=\"name\">' + doShortentFileName(objValue.name, 20) + '</div>' +\n\t\t\t\t\t\t'<div class=\"namefull\">' + objValue.name + '</div>' +\n\t\t\t\t\t\t(objValue.type === 'FILE' ? '<div class=\"size\">' + displayFileSize(parseInt(objValue.size, 10)) + '</div>' : '') +\n\n\t\t\t\t\t\t(parseInt(objValue.width, 10) && parseInt(objValue.height, 10) ? '<div class=\"dimensions\"><span class=\"width\">' + parseInt(objValue.width, 10) + '</span> x <span class=\"height\">' + parseInt(objValue.height, 10) + '</span> pixels</div>' : '') +\n\n\t\t\t\t\t\t(objValue.date.length > 0 ? '<div class=\"modified\">' + dateFormat(objValue.date, 'mmm dS, yyyy, h:MM:ss TT') + '</div>' : '') +\n\t\t\t\t\t\t'<div class=\"mimeType\">' + objValue.mime + '</div>'\n\t\t\t\t\t);\n\n\t\t\t\t\t// add the file size to the directories total\n\t\t\t\t\ttotal_size += parseInt(objValue.size, 10);\n\n\t\t\t\t\t// append out info string to the list items\n\t\t\t\t\tinfoStr = objValue.name + ' \\n' + (objValue.type === 'FILE' ? displayFileSize(parseInt(objValue.size, 10)) + ' \\n' : '') + (parseInt(objValue.width, 10) && parseInt(objValue.height, 10) ? parseInt(objValue.width, 10) + ' x ' + parseInt(objValue.height, 10) + ' pixels \\n' : '') + dateFormat(objValue.date, 'mmm dS, yyyy, h:MM:ss TT');\n\t\t\t\t\t$(lis).attr('title', infoStr);\n\t\t\t\t\t$(lib).attr('title', infoStr).append(info);\n\n\t\t\t\t\t// add the direct list to the BROWSER and SIDEBAR windows\n\t\t\t\t\t$('#sidebar ul').append(lis);\n\t\t\t\t\t$('#browser ul').append(lib);\n\t\t\t\t});\n\n\t\t\t\t// set up our hover and click actions for the SIDEBAR window\n\t\t\t\t$('#sidebar ul li').on('mouseenter mousedown', function () {\n\t\t\t\t\t$(this).addClass('hovering');\n\t\t\t\t}).on('mouseleave mouseup', function () {\n\t\t\t\t\t$(this).removeClass('hovering');\n\t\t\t\t}).on('click', function (e) {\n\t\t\t\t\tvar $this = $(this),\n\t\t\t\t\t\t$twin = $('#browser #' + ($this.attr('id')).replace('sidebar_ID', 'browser_ID'));\n\t\t\t\t\tif ($this.attr('rel') === 'File') {\n\t\t\t\t\t\t$('#directoryIn').attr('disabled', true).off();\n\t\t\t\t\t\tif ($this.hasClass('selected')) {\n\t\t\t\t\t\t\t$this.removeClass('selected');\n\t\t\t\t\t\t\t$twin.removeClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect,#fileDelete').attr('disabled', true);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$('#sidebar ul li,#browser ul li').removeClass('selected');\n\t\t\t\t\t\t\t$this.addClass('selected');\n\t\t\t\t\t\t\t$twin.addClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect').attr('disabled', false);\n\t\t\t\t\t\t\tif ($.inArray('fileDelete', opts.actions) > -1) {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', false);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$('#browser').animate({\n\t\t\t\t\t\t\t\tscrollTop: $('#browser').scrollTop() + $twin.offset().top - $twin.height()\n\t\t\t\t\t\t\t}, 'fast');\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ($this.attr('rel') === 'Directory') {\n\t\t\t\t\t\tif ($this.hasClass('selected')) {\n\t\t\t\t\t\t\t$this.removeClass('selected');\n\t\t\t\t\t\t\t$twin.removeClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect').attr('disabled', true);\n\t\t\t\t\t\t\t$('#directoryIn').attr('disabled', true).off();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$('#sidebar ul li,#browser ul li').removeClass('selected');\n\t\t\t\t\t\t\t$this.addClass('selected');\n\t\t\t\t\t\t\t$twin.addClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect').attr('disabled', true);\n\t\t\t\t\t\t\tif ($.inArray('deleteDirectory', opts.actions) > -1) {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', false);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$('#browser').animate({\n\t\t\t\t\t\t\t\tscrollTop: $('#browser').scrollTop() + $twin.offset().top - $twin.height()\n\t\t\t\t\t\t\t}, 'fast');\n\t\t\t\t\t\t\t$('#directoryIn').attr('disabled', false).on('click', function (e) {\n\t\t\t\t\t\t\t\tif ($this.attr('disabled') !== 'disabled' && $this.attr('disabled') !== true) {\n\t\t\t\t\t\t\t\t\tvar path = $('#sidebar ul li.selected').find('span').attr('rel');\n\t\t\t\t\t\t\t\t\topts.baseRelPath.push(opts.baseRelPath[sys.currentPathIdx] + path + '/');\n\t\t\t\t\t\t\t\t\tsys.currentPathIdx += 1;\n\t\t\t\t\t\t\t\t\tupdateDirOptions();\n\t\t\t\t\t\t\t\t\tdoDirListing(function() {\n\t\t\t\t\t\t\t\t\t\tdisplayDirListing();\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\te.stopImmediatePropagation();\n\t\t\t\t}).on('dblclick', function (e) {\n\t\t\t\t\t// double-click action for directories, might allow this for files eventually.\n\t\t\t\t\tvar $this = $(this),\n\t\t\t\t\t\tpath = $this.find('span').attr('rel'),\n\t\t\t\t\t\tfileObj;\n\t\t\t\t\tif ($this.attr('rel') === 'File') {\n\t\t\t\t\t\tfileObj = sys.dirContents[parseInt(($this.attr('ID')).replace('sidebar_ID', ''), 10)];\n\t\t\t\t\t\tdoFileSelect(fileObj);\n\t\t\t\t\t} else if ($this.attr('rel') === 'Directory') {\n\t\t\t\t\t\topts.baseRelPath.push(opts.baseRelPath[sys.currentPathIdx] + path + '/');\n\t\t\t\t\t\tsys.currentPathIdx += 1;\n\t\t\t\t\t\tupdateDirOptions();\n\t\t\t\t\t\tdoDirListing(function() {\n\t\t\t\t\t\t\tdisplayDirListing();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\te.stopImmediatePropagation();\n\t\t\t\t});\n\n\t\t\t\t// set up our hover and click actions for the BROWSER window\n\t\t\t\t$('#browser ul li').on('mouseenter mousedown', function () {\n\t\t\t\t\t$(this).addClass('hovering');\n\t\t\t\t}).on('mouseleave mouseup', function () {\n\t\t\t\t\t$(this).removeClass('hovering');\n\t\t\t\t}).on('click', function (e) {\n\t\t\t\t\tvar $this = $(this),\n\t\t\t\t\t\t$twin = $('#sidebar #' + ($this.attr('id')).replace('browser_ID', 'sidebar_ID'));\n\t\t\t\t\tif ($this.attr('rel') === 'File') {\n\t\t\t\t\t\t$('#directoryIn').attr('disabled', true).off();\n\t\t\t\t\t\tif ($this.hasClass('selected')) {\n\t\t\t\t\t\t\t$this.removeClass('selected');\n\t\t\t\t\t\t\t$twin.removeClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect,#fileDelete').attr('disabled', true);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$('#sidebar ul li,#browser ul li').removeClass('selected');\n\t\t\t\t\t\t\t$this.addClass('selected');\n\t\t\t\t\t\t\t$twin.addClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect').attr('disabled', false);\n\t\t\t\t\t\t\tif ($.inArray('fileDelete', opts.actions) > -1) {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', false);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$('#sidebar').animate({\n\t\t\t\t\t\t\t\tscrollTop: $('#sidebar').scrollTop() + $twin.offset().top - 43\n\t\t\t\t\t\t\t}, 'fast'); // #sidebar css position top = 43px\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if ($this.attr('rel') === 'Directory') {\n\t\t\t\t\t\tif ($this.hasClass('selected')) {\n\t\t\t\t\t\t\t$this.removeClass('selected');\n\t\t\t\t\t\t\t$twin.removeClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect').attr('disabled', true);\n\t\t\t\t\t\t\t$('#directoryIn').attr('disabled', true).off();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$('#sidebar ul li,#browser ul li').removeClass('selected');\n\t\t\t\t\t\t\t$this.addClass('selected');\n\t\t\t\t\t\t\t$twin.addClass('selected');\n\t\t\t\t\t\t\t$('#fileSelect').attr('disabled', true);\n\t\t\t\t\t\t\tif ($.inArray('deleteDirectory', opts.actions) > -1) {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', false);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t$('#fileDelete').attr('disabled', true);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$('#sidebar').animate({\n\t\t\t\t\t\t\t\tscrollTop: $('#sidebar').scrollTop() + $twin.offset().top - 43\n\t\t\t\t\t\t\t}, 'fast'); // not sure why 43 is working here?!?\n\t\t\t\t\t\t\t$('#directoryIn').attr('disabled', false).on('click', function (e) {\n\t\t\t\t\t\t\t\tif ($this.attr('disabled') !== 'disabled' && $this.attr('disabled') !== true) {\n\t\t\t\t\t\t\t\t\tvar path = $('#browser ul li.selected').find('.diritem').attr('rel');\n\t\t\t\t\t\t\t\t\topts.baseRelPath.push(opts.baseRelPath[sys.currentPathIdx] + path + '/');\n\t\t\t\t\t\t\t\t\tsys.currentPathIdx += 1;\n\t\t\t\t\t\t\t\t\tupdateDirOptions();\n\t\t\t\t\t\t\t\t\tdoDirListing(function() {\n\t\t\t\t\t\t\t\t\t\tdisplayDirListing();\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\te.stopImmediatePropagation();\n\t\t\t\t}).on('dblclick', function (e) {\n\t\t\t\t\t// double-click action for directories, might allow this for files eventually.\n\t\t\t\t\tvar $this = $(this),\n\t\t\t\t\t\tpath = $this.find('.diritem').attr('rel'),\n\t\t\t\t\t\tfileObj;\n\t\t\t\t\tif ($this.attr('rel') === 'File') {\n\t\t\t\t\t\tfileObj = sys.dirContents[parseInt(($this.attr('ID')).replace('browser_ID', ''), 10)];\n\t\t\t\t\t\tdoFileSelect(fileObj);\n\t\t\t\t\t} else if ($this.attr('rel') === 'Directory') {\n\t\t\t\t\t\topts.baseRelPath.push(opts.baseRelPath[sys.currentPathIdx] + path + '/');\n\t\t\t\t\t\tsys.currentPathIdx += 1;\n\t\t\t\t\t\tupdateDirOptions();\n\t\t\t\t\t\tdoDirListing(function() {\n\t\t\t\t\t\t\tdisplayDirListing();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\te.stopImmediatePropagation();\n\t\t\t\t}).draggable({\n\t\t\t\t\tcursor: 'move',\n\t\t\t\t\thelper: 'clone',\n\t\t\t\t\topacity: 0.5,\n\t\t\t\t\tcontainment: '#browser',\n\t\t\t\t\tscroll: true,\n\t\t\t\t\tstart: function(event, ui) {\n\t\t\t\t\t\tvar $this = $(event.target).parents('li');\n\t\t\t\t\t\tsys.dragObjId = $this.attr('id');\n\t\t\t\t\t},\n\t\t\t\t\tstop: function(event, ui) {\n\t\t\t\t\t\tvar $this = $(event.target).parents('li');\n\t\t\t\t\t\tsys.dragObjId = null;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// setup droppable's for directories\n\t\t\t\t$('#browser ul li[rel=\"Directory\"]').droppable({\n\t\t\t\t\tover: function(event, ui) {\n\t\t\t\t\t\t$(this).addClass('hovering');\n\t\t\t\t\t},\n\t\t\t\t\tout: function(event, ui) {\n\t\t\t\t\t\t$(this).removeClass('hovering');\n\t\t\t\t\t},\n\t\t\t\t\tdrop: function(event, ui) {\n\t\t\t\t\t\tvar $this = $(this);\n\t\t\t\t\t\tmoveItem(sys.dragObjId, $this.attr('id'));\n\t\t\t\t\t\tsys.dragObjId = null;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tgetDirectoryImages();\n\n\t\t\t}\n\n\t\t\t// hide our progress bar\n\t\t\tdisplayDialog({\n\t\t\t\ttype: 'progress',\n\t\t\t\tstate: 'hide'\n\t\t\t});\n\n\t\t\t// update display stats info\n\t\t\tupdateDisplayStats(opts.baseRelPath[sys.currentPathIdx], dir.length, total_size);\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets a value on the control with the given name attribute | function setValue(name, value) {
var nameSelect = "[name='" + escapeName(name) + "']";
jq(nameSelect).val(value);
} | [
"function setValueByName (name, value) {\n\n}",
"function setValueByName(name, value) {\n document.getElementsByName(name)[0].value = value;\n}",
"function setAttrByName (attributename, value){\n var attribute = findAttribute(attributename);\n attribute.set(\"current\", value);\n}",
"setAttribute(name, value) {\n this.element.setAttribute(name, value)\n }",
"function setValueByName (name, value) {\nreturn $('[name=\"' + name + '\"]').val(\"\" +value);\n}",
"function setValueByName (name, value) {\n return document.getElementsByName(name)[0].value = value;\n}",
"set(name, value) {\r\n let input = this.findByName(name);\r\n\r\n if (Is.empty(input)) {\r\n input = DI.resolve('formBuilder').hidden(name);\r\n }\r\n\r\n input.val(value);\r\n\r\n this.form.append(input.node);\r\n\r\n return this;\r\n }",
"function setAttributeVal(element, atname, atvalue) {\n\telement.setAttribute(atname, atvalue);\n}",
"set(name, value) {\n this.uniformsByName[name].value = value;\n }",
"function setSliderValue(name, val) {\n document.getElementById(name + \"-slider\").value = val;\n}",
"setAttrValue (name, value) {\n value = toNullOrString(value);\n\n this.lastSetValues[name] = value;\n\n if (this.connected) {\n this._clearPendingValue(name);\n this._syncAttrValue(name, value);\n } else {\n this.pendingValues[name] = value;\n }\n }",
"setAttribute(name, value) {\n this._attribs[name] = value;\n return this;\n }",
"function setter(inputId, inputName, value, formId) {\n\t\t\t// check if input field already exist and change its value\n\t\t\tvar $input = $('#' + inputId);\n\t\t\tif ($input.length) {\n\t\t\t\t$input.val(value);\n\t\t\t}\n\t\t\t// else create input element and set the value\n\t\t\telse {\n\t\t\t\t\tvar inputField = '<input name=\"' + inputName + '\" id=\"' + inputId + '\" type=\"hidden\" value=\"' + value + '\" />';\n\t\t\t\t\t$('#' + formId).append(inputField);\n\t\t\t\t}\n\t\t}",
"function setLookupFromFieldName(tagName, fieldName, value, name) {\n if (value == undefined) return;\n var theInput = getTagFromIdentifierAndTitle(tagName,\"\",fieldName);\n if(theInput != null) {\n theInput.value = value;\n }\n else if(tagName==\"select\"){\n\t theInput = getTagFromIdentifierAndTitle(\"input\",\"\",fieldName);\n\t theInput.value = name;\n\t document.getElementById(theInput.optHid).value = value;\n \t\n }\n if(theInput != null) {\n// \ttheInput.parentElement.disabled = 'disabled';\n\t\t} \n }",
"function setVal(itemName, value)\n{\n \treturn get(itemName).setText(value);\n}",
"set name(name) {\n this.setRequiredChildProperty(this.inputSlot, 'name', name);\n }",
"function setName()\n{\n\tvm.name = _nameField.value;\n}",
"set name( name ){\n this._name = name;\n }",
"set keyname(keyname) {\n this.setAttribute('keyname', keyname);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for Quiz using title using fuzzy module | searchTitleFuzzy(input){
// Fuzzy Search the quiz title
let results = fuzzy.filter(input, this.quizList, {extract: (el) => {
return el.title;
}})
this.searchFuzzy(results);
} | [
"searchTitle(){\r\n let userQueryRegex = /.*\\S.*/; // Input cannot be blank\r\n let userQuery = read.question(\"Search Quiz Title: (-1 to exit)\\n>> \", {limit: userQueryRegex, limitMessage: \"Type something!\"});\r\n\r\n if(userQuery == -1) this.searchAQuiz();\r\n else this.searchTitleFuzzy(userQuery);\r\n }",
"searchUser(){\r\n let userQueryRegex = /.*\\S.*/; // Input cannot be blank\r\n let userQuery = read.question(\"Search Quiz User: (-1 to exit)\\n>> \", {limit: userQueryRegex, limitMessage: \"Type something!\"});\r\n\r\n if(userQuery == -1) this.searchAQuiz();\r\n else this.searchUserFuzzy(userQuery);\r\n }",
"function search(){\r\n\tvar fqas = [{\r\n\t\t\"Question\": \" Why do I have to pay a service fee?\",\r\n\t\t\"Answer\": \" A service fee is only charged for repairs to devices that are no longer under warran-ty. Business customers are not charged a service fee in accord with the terms of their contract \"\r\n\t},\r\n\t{\r\n\t\t\"Question\": \" What is the bond for?\",\r\n \t\t\"Answer\": \" The bond is to cover any damage done to the courtesy phone and/or charger. The bond will be refunded upon the safe and undamaged return of the phone and charger.\"\r\n \t},\r\n \t{\r\n \t\t\"Question\": \"Do I need a charger with my courtesy phone?\",\r\n \t\t\"Answer\" : \"No, a charger is optional. You can add one with the 'Add charger' button. If you don't want one but added one by accident, you can remove it by clicking on the 'Remove charger' button.\"\r\n \t},\r\n\r\n \t{\r\n \t\t\"Question\": \" Why isn't my phone under warranty?\",\r\n \t\t\"Answer\" : \" The length of your phone's warranty depends on the warranty package you chose upon purchase. The standard is 24 months and is calculated from its purchase date.\"\r\n \t},\r\n \t\r\n \t{\r\n \t\t\"Question\": \" How long will my repair take?\",\r\n \t\t\"Answer\" : \" Depends on your phone broken status. It takes normally 5 to 7 working days.\"\r\n \t},\r\n \t\r\n \t{\r\n \t\t\"Question\": \" How do you protect the private information in my phone?\",\r\n \t\t\"Answer\" : \" We comply with all relevant laws regarding privacy and client confidentiality.\"\r\n \t},\r\n \r\n \t{\r\n \t\t\"Question\": \" Where do you get your replacement parts?\",\r\n \t\t\"Answer\" : \" We will send you a quote of all possible vendors who supply replacement parts for your references and your choice.\"\r\n \t},\r\n \t\r\n \t{\r\n \t\t\"Question\": \" What happens if my phone is further damage after leaving it with you?\",\r\n \t\t\"Answer\" : \" We make sure that it never happens.\"\r\n \t},\r\n \t\r\n \t{\r\n \t\t\"Question\": \" What kind of warranty do you offer and what does it cover?\",\r\n \t\t\"Answer\" : \"1 month is the average warranty period. These warranties covers parts and service only.\"\r\n \t},\r\n \t\r\n \t{\r\n \t\t\"Question\": \" What does the repair estimate include?\",\r\n \t\t\"Answer\" : \" The repair price estimate includes both replacement parts and labor.\"\r\n \t}\r\n \t];\r\n\r\n \tvar search_term = document.getElementById(\"se\").value;\r\n \tvar results = fqas.filter(function(fqas) {\r\n \t\treturn fqas.Question.indexOf(search_term) > -1;\r\n \t});\r\n\r\n \t//printing the results to the html page. \r\n \tif(results.length == 0) {\r\n \t\tdocument.getElementById(\"searchResult\").innerHTML = \"Not found!\";\r\n \t} else {\r\n \t\tfor (var i=0; i< results.length; i++) {\r\n \t\t\tdocument.getElementById(\"searchResult\").innerHTML += results[i].Question + \"<br>\";//result.question\r\n \t\t\tdocument.getElementById(\"searchResult\").innerHTML += results[i].Answer + \"<br><br>\";//result.answer\r\n \t\t}\r\n \t}\r\n\r\n}",
"function fuzzySearch (text, query) {\n var hay = text.toLowerCase();\n var n = -1; // unclear what this does\n query = query.toLowerCase();\n for (var index in query) {\n var letter = query[index];\n if (!~(n = hay.indexOf(letter, n + 1))){\n return false;\n }\n }\n return true;\n}",
"function fuzzyUser(searchString) {\n for (i = 0; i < songDatabase.length; i++) {\n var fuzzNum = fuzzySearch(searchString, songDatabase[i].title);\n if (fuzzNum)\n console.log(songDatabase[i]);\n }\n return;\n}",
"function searchFaq() {\n var input, filter, q, i, qTxt, aTxt;\n input = document.getElementById(\"searchFaq\");\n filter = input.value.toUpperCase();\n q = document.getElementsByClassName(\"collapsible\");\n a = document.getElementsByClassName(\"answer\");\n for (i = 0; i < q.length; i++) {\n qTxt = q[i].textContent;\n aTxt = a[i].textContent;\n if (\n qTxt.toUpperCase().indexOf(filter) > -1 ||\n aTxt.toUpperCase().indexOf(filter) > -1\n ) {\n q[i].style.display = \"\";\n a[i].style.display = \"\";\n } else {\n q[i].style.display = \"none\";\n a[i].style.display = \"none\";\n }\n }\n}",
"searchFuzzy() {\n this.fuzzyResults = this.search.searchService(this.searchTerm);\n }",
"function queryForBookTitleSearchAsYouType(prefix, fuzziness) {\n return {\n \"suggest\": {\n \"book-suggest-fuzzy\": {\n \"prefix\": prefix,\n \"completion\": {\n \"field\": \"title.completion\",\n \"fuzzy\": {\n \"fuzziness\": fuzziness\n }\n }\n }\n }\n }\n}",
"fuzzySearch(sentence) {\n const searchFor = sentence.match(/^(?:\\bwho\\b|\\bwhat\\b) (?:is|are)(?: \\ban?\\b | \\bthe\\b | )([a-zA-Z0-9_ ]*)/i)[1].replace(/\\?/g, '').replace(/'/g, '');\n const instances = this.node.getInstances();\n let multipleSearch;\n let instancesFiltered = [];\n\n if (searchFor.indexOf(' ')) {\n multipleSearch = searchFor.split(' ');\n }\n\n if (multipleSearch) {\n for (let x = 0; x < multipleSearch.length; x += 1) {\n const instancesFilteredTemp = instances.filter((input) => {\n if (input.name.toUpperCase().includes(multipleSearch[x].toUpperCase())) {\n return input;\n }\n return null;\n });\n instancesFiltered = instancesFiltered.concat(instancesFilteredTemp);\n }\n } else {\n instancesFiltered = instances.filter((input) => {\n if (input.name.toUpperCase().includes(searchFor.toUpperCase())) {\n return input;\n }\n return null;\n });\n }\n\n const instancesSummary = instancesFiltered.reduce((previous, current) => {\n const prev = previous;\n if (!prev[current.type.name]) {\n prev[current.type.name] = [];\n }\n prev[current.type.name].push(current.name);\n return prev;\n }, {});\n\n return instancesSummary;\n }",
"function fuzzySearch(food, callback) {\n\n let getFood = \"SELECT * FROM foods WHERE FoodName LIKE '%\"\n + food +\"%';\";\n \n sql(getFood, (err, result) => {\n\n if (err) callback(err, null);\n callback(null, result);\n }); \n}",
"function fuzzySearch(item, query) {\n // Create the source text to be searched.\n var category = item.category.toLowerCase();\n var label = item.label.toLowerCase();\n var source = category + \" \" + label;\n // Set up the match score and indices array.\n var score = Infinity;\n var indices = null;\n // The regex for search word boundaries\n var rgx = /\\b\\w/g;\n // Search the source by word boundary.\n while (true) {\n // Find the next word boundary in the source.\n var rgxMatch = rgx.exec(source);\n // Break if there is no more source context.\n if (!rgxMatch) {\n break;\n }\n // Run the string match on the relevant substring.\n var match = StringExt.matchSumOfDeltas(source, query, rgxMatch.index);\n // Break if there is no match.\n if (!match) {\n break;\n }\n // Update the match if the score is better.\n if (match && match.score <= score) {\n score = match.score;\n indices = match.indices;\n }\n }\n // Bail if there was no match.\n if (!indices || score === Infinity) {\n return null;\n }\n // Compute the pivot index between category and label text.\n var pivot = category.length + 1;\n // Find the slice index to separate matched indices.\n var j = ArrayExt.lowerBound(indices, pivot, function (a, b) { return a - b; });\n // Extract the matched category and label indices.\n var categoryIndices = indices.slice(0, j);\n var labelIndices = indices.slice(j);\n // Adjust the label indices for the pivot offset.\n for (var i = 0, n = labelIndices.length; i < n; ++i) {\n labelIndices[i] -= pivot;\n }\n // Handle a pure label match.\n if (categoryIndices.length === 0) {\n return {\n matchType: 0 /* Label */,\n categoryIndices: null,\n labelIndices: labelIndices,\n score: score, item: item\n };\n }\n // Handle a pure category match.\n if (labelIndices.length === 0) {\n return {\n matchType: 1 /* Category */,\n categoryIndices: categoryIndices,\n labelIndices: null,\n score: score, item: item\n };\n }\n // Handle a split match.\n return {\n matchType: 2 /* Split */,\n categoryIndices: categoryIndices,\n labelIndices: labelIndices,\n score: score, item: item\n };\n }",
"function fuzzySearch(courses, substr){\n var matches = [];\n substr = substr.toLowerCase();\n substr = substr.replace(/\\s+/g, '');\n for(var i = 0; i < courses.length; i++){\n if(typeof courses[i].title != 'undefined' && typeof courses[i].subject != 'undefined' && typeof courses[i].catalog_num != 'undefined'){\n var fullString = courses[i].title.toLowerCase() + \" \" + courses[i].subject.toLowerCase() + \" \" + courses[i].catalog_num.toLowerCase()\n fullString = fullString.replace(/\\s+/g, '');\n if(fullString.indexOf(substr) >= 0){\n matches.push(courses[i]);\n }\n }\n }\n console.log(matches.length);\n return matches;\n}",
"search(database, quary) {\n return database\n .filter((elementSearched) => {\n return elementSearched.name.toLowerCase()\n .includes(quary.toLowerCase());\n })\n .map((protester) => protester.name);\n }",
"function fuzzySearch(item, query) {\r\n // Create the source text to be searched.\r\n var category = item.category.toLowerCase();\r\n var label = item.label.toLowerCase();\r\n var source = category + \" \" + label;\r\n // Set up the match score and indices array.\r\n var score = Infinity;\r\n var indices = null;\r\n // The regex for search word boundaries\r\n var rgx = /\\b\\w/g;\r\n // Search the source by word boundary.\r\n while (true) {\r\n // Find the next word boundary in the source.\r\n var rgxMatch = rgx.exec(source);\r\n // Break if there is no more source context.\r\n if (!rgxMatch) {\r\n break;\r\n }\r\n // Run the string match on the relevant substring.\r\n var match = algorithm_1.StringExt.matchSumOfDeltas(source, query, rgxMatch.index);\r\n // Break if there is no match.\r\n if (!match) {\r\n break;\r\n }\r\n // Update the match if the score is better.\r\n if (match && match.score <= score) {\r\n score = match.score;\r\n indices = match.indices;\r\n }\r\n }\r\n // Bail if there was no match.\r\n if (!indices || score === Infinity) {\r\n return null;\r\n }\r\n // Compute the pivot index between category and label text.\r\n var pivot = category.length + 1;\r\n // Find the slice index to separate matched indices.\r\n var j = algorithm_1.ArrayExt.lowerBound(indices, pivot, function (a, b) { return a - b; });\r\n // Extract the matched category and label indices.\r\n var categoryIndices = indices.slice(0, j);\r\n var labelIndices = indices.slice(j);\r\n // Adjust the label indices for the pivot offset.\r\n for (var i = 0, n = labelIndices.length; i < n; ++i) {\r\n labelIndices[i] -= pivot;\r\n }\r\n // Handle a pure label match.\r\n if (categoryIndices.length === 0) {\r\n return {\r\n matchType: 0 /* Label */,\r\n categoryIndices: null,\r\n labelIndices: labelIndices,\r\n score: score, item: item\r\n };\r\n }\r\n // Handle a pure category match.\r\n if (labelIndices.length === 0) {\r\n return {\r\n matchType: 1 /* Category */,\r\n categoryIndices: categoryIndices,\r\n labelIndices: null,\r\n score: score, item: item\r\n };\r\n }\r\n // Handle a split match.\r\n return {\r\n matchType: 2 /* Split */,\r\n categoryIndices: categoryIndices,\r\n labelIndices: labelIndices,\r\n score: score, item: item\r\n };\r\n }",
"autoCompleteSearch(str) {\n if (str.length == 0) {\n return [];\n }\n str = str.toLowerCase();\n return this.recipes.filter(x => x.title.toLowerCase().includes(str)).map(x => x.title).sort((a, b) => {\n\n // advanced\n // prioritize when finding the str\n // as a separate word\n let aIsSeparateWord = (' ' + a + ' ').toLowerCase().includes(' ' + str + ' ');\n let bIsSeparateWord = (' ' + b + ' ').toLowerCase().includes(' ' + str + ' ');\n\n // prioritize str early in name\n let aPos = a.toLowerCase().indexOf(str) - (\n aIsSeparateWord\n ? 1000\n : 0);\n let bPos = b.toLowerCase().indexOf(str) - (\n bIsSeparateWord\n ? 1000\n : 0);\n\n if (aPos === bPos) {\n // if same position\n // sort alphabetically by name\n return a < b\n ? -1\n : 1;\n }\n\n return aPos < bPos\n ? -1\n : 1;\n });\n }",
"function searchTitle(title) {\n const sql = `SELECT * FROM post WHERE title LIKE '%${title}%' ORDER BY timeposted DESC;`;\n return db.execute(sql);\n}",
"function matchResult(result, title) {\n\t// split title into tokens\n\tlet split = title.split(/\\W+/g);\n\tfor (let i = 0; i < split.length; i++) {\n\t\t// result must contain all tokens\n\t\tif (!result.title.toLowerCase().includes(split[i].toLowerCase())) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}",
"function FuzzySearchMapTitle(searchTerm, mapList) {\n return new Promise((resolve, reject) => {\n const searcher = new FuzzySearch(mapList, [], { sort: true });\n const searchResults = searcher.search(searchTerm);\n\n // Check for 0 matching map results, reject or resolve.\n if (searchResults.length < 1) {\n reject(new Error(`The search term \"${searchTerm}\" yielded no results.`));\n }\n resolve(searchResults[0]);\n });\n}",
"function generateQuiz() {\n var searchTags = ['root'] // tags with which to match\n var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();\n var inputSheet = spreadsheet.getSheetByName('Questions');\n var inputRows = inputSheet.getRange(2, 1, inputSheet.getLastRow() - 1, inputSheet.getLastColumn()).getValues();\n var form = FormApp.create(searchTags.join(' ') + ' Quiz').setIsQuiz(true).setShuffleQuestions(true).setRequireLogin(false).setPublishingSummary(true);\n \n // for each question/row\n for (var i = 0; i < inputRows.length; i++)\n {\n var tags = inputRows[i][3].split(' ');\n \n // for each tag in searchTags\n for (var j = 0; j < searchTags.length; j++)\n {\n if (tags.indexOf(searchTags[j]) >= 0){ // if tags of given row contains given tag in searchTag \n var feedback = FormApp.createFeedback().setText(inputRows[i][1]).build();\n form.addTextItem().setPoints(1).setTitle(inputRows[i][0]).setGeneralFeedback(feedback);\n break;\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::WAFv2::WebACL.TextTransformation` resource | function cfnWebACLTextTransformationPropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnWebACL_TextTransformationPropertyValidator(properties).assertSuccess();
return {
Priority: cdk.numberToCloudFormation(properties.priority),
Type: cdk.stringToCloudFormation(properties.type),
};
} | [
"renderProperties(x) { return ui.divText(`Properties for ${x.name}`); }",
"format() {\n if(this.properties[\"text\"]) {\n this.formattedText = this.addLineBreaks(this.properties[\"text\"], 27);\n }\n }",
"function TextProperty() {}",
"function displayText(text, x, y, properties){\n\tctx.save();\n\tfor(var p in properties){\n\t\tctx[p] = properties[p];\n\t}\n\tctx.fillText(text, x, y);\n\tctx.restore();\n}",
"function cfnRuleGroupTextTransformationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRuleGroup_TextTransformationPropertyValidator(properties).assertSuccess();\n return {\n Priority: cdk.numberToCloudFormation(properties.priority),\n Type: cdk.stringToCloudFormation(properties.type),\n };\n}",
"properties() {\n return this.display.show(\n this._section(\n Text(`Properties accessible from ${this.getSignature()}`),\n this._renderProperties(2, this.metadata.allProperties())\n )\n );\n }",
"function permissionResourcePropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n PermissionResourcePropsValidator(properties).assertSuccess();\n return {\n Action: cdk.stringToCloudFormation(properties.action),\n FunctionName: cdk.stringToCloudFormation(properties.functionName),\n Principal: cdk.stringToCloudFormation(properties.principal),\n EventSourceToken: cdk.stringToCloudFormation(properties.eventSourceToken),\n SourceAccount: cdk.stringToCloudFormation(properties.sourceAccount),\n SourceArn: cdk.stringToCloudFormation(properties.sourceArn),\n };\n }",
"function cfnWebACLCustomResponseBodyPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnWebACL_CustomResponseBodyPropertyValidator(properties).assertSuccess();\n return {\n Content: cdk.stringToCloudFormation(properties.content),\n ContentType: cdk.stringToCloudFormation(properties.contentType),\n };\n}",
"function writeTransformationControls(){\n\n document.writeln(\"<span style=\\\"color:#000000; font-family:arial; font-size:8pt; font-weight:bold;\\\">Transformations:</span>\");\n document.writeln(\"<a href=\\\"javascript:allMASHObjects[0].resize(300, 200);\\\" ><span style=\\\"color:#0000ff; font-family:arial; font-size:8pt; font-weight:bold;\\\">Resize</span></a>\");\n document.writeln(\"<a href=\\\"javascript:MASH_Object.setVisibility(allMASHObjects[0], true);\\\" ><span style=\\\"color:#0000bb; font-family:arial; font-size:8pt; font-weight:bold;\\\">Show</span></a>\");\n document.writeln(\"<a href=\\\"javascript:MASH_Object.setVisibility(allMASHObjects[0], false);\\\"><span style=\\\"color:#0000bb; font-family:arial; font-size:8pt; font-weight:bold;\\\">Hide</span></a>\");\n\n}//writeTransformationControls",
"renderText() {\n if (this.$editor) {\n const text = this.model.get(this.propertyName);\n\n if (text) {\n const reviewRequest = this.model.get('parentObject');\n\n this._$editorContainer.show();\n this._$linkContainer.hide();\n RB.formatText(this.$editor, {\n newText: text,\n richText: this.model.get(this.richTextPropertyName),\n isHTMLEncoded: true,\n bugTrackerURL: reviewRequest.get('bugTrackerURL')\n });\n } else {\n this._$editorContainer.hide();\n this._$linkContainer.show();\n }\n }\n }",
"function cfnWebACLLabelPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnWebACL_LabelPropertyValidator(properties).assertSuccess();\n return {\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}",
"function cfnWebACLPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnWebACLPropsValidator(properties).assertSuccess();\n return {\n DefaultAction: cfnWebACLWafActionPropertyToCloudFormation(properties.defaultAction),\n MetricName: cdk.stringToCloudFormation(properties.metricName),\n Name: cdk.stringToCloudFormation(properties.name),\n Rules: cdk.listMapper(cfnWebACLActivatedRulePropertyToCloudFormation)(properties.rules),\n };\n}",
"function cfnWebACLAssociationPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnWebACLAssociationPropsValidator(properties).assertSuccess();\n return {\n ResourceArn: cdk.stringToCloudFormation(properties.resourceArn),\n WebACLId: cdk.stringToCloudFormation(properties.webAclId),\n };\n}",
"function cfnWebACLPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnWebACLPropsValidator(properties).assertSuccess();\n return {\n DefaultAction: cfnWebACLDefaultActionPropertyToCloudFormation(properties.defaultAction),\n Scope: cdk.stringToCloudFormation(properties.scope),\n VisibilityConfig: cfnWebACLVisibilityConfigPropertyToCloudFormation(properties.visibilityConfig),\n CaptchaConfig: cfnWebACLCaptchaConfigPropertyToCloudFormation(properties.captchaConfig),\n ChallengeConfig: cfnWebACLChallengeConfigPropertyToCloudFormation(properties.challengeConfig),\n CustomResponseBodies: cdk.hashMapper(cfnWebACLCustomResponseBodyPropertyToCloudFormation)(properties.customResponseBodies),\n Description: cdk.stringToCloudFormation(properties.description),\n Name: cdk.stringToCloudFormation(properties.name),\n Rules: cdk.listMapper(cfnWebACLRulePropertyToCloudFormation)(properties.rules),\n Tags: cdk.listMapper(cdk.cfnTagToCloudFormation)(properties.tags),\n TokenDomains: cdk.listMapper(cdk.stringToCloudFormation)(properties.tokenDomains),\n };\n}",
"function createTextProperty(property, parent){\n\n var value = document.createElement('div')\n value.textContent = property.value\n value.title = property.value\n value.className = 'propertyValue'\n\n parent.appendChild(value)\n\n return value\n}",
"function styleText(json) {\n return {\n action_type: C.STYLE_TEXT,\n object_id: json[1],\n start_index: json[3],\n end_index: json[4],\n styles: _parseTextStyles(json[6])\n }\n}",
"function cfnWebACLAssociationPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnWebACLAssociationPropsValidator(properties).assertSuccess();\n return {\n ResourceArn: cdk.stringToCloudFormation(properties.resourceArn),\n WebACLArn: cdk.stringToCloudFormation(properties.webAclArn),\n };\n}",
"richTextAttr() {\n return this.allowRichText\n ? `${_.result(this, 'fieldName')}RichText`\n : null;\n }",
"textTransform(text) {\r\n return text;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method simplex2_out() search index for out from basis | simplex2_out() {
var ind = -1;
var a = 0;
for (let i=0; i<this.n; i++) {
if (this.b_numerator[i] >= 0) continue;
if (this.b_numerator[i] / this.b_denominator[i] < a) {
ind = i;
a = this.b_numerator[i] / this.b_denominator[i];
}
}
return ind;
} | [
"simplex_out(index_in) {\n\t\tvar ind = -1;\n\t\tvar min_a = 0;\n\t\tfor (let i=0; i<this.n; i++) {\n\t\t\tif (this.numerator[i][index_in] <= 0) continue;\nvar a = (this.b_numerator[i] / this.b_denominator[i]) * (this.denominator[i][index_in] / this.numerator[i][index_in]);\n\t\t\tif (a < 0) continue;\n\t\t\tif (ind == -1 || a < min_a) {\n\t\t\t\tind = i;\n\t\t\t\tmin_a = a;\n\t\t\t}\n\t\t}\n\t\treturn ind;\n\t}",
"simplex2_in(ind_out) {\n\t\tvar ind = -1;\n\t\tvar min_a = 0;\n\t\tfor (let i=0; i<this.m; i++) {\n\t\t\tif (this.f_numerator[i] > 0) continue;\n\t\t\tif (this.numerator[ind_out][i] >= 0) continue;\nvar a = (this.f_numerator[i] * this.denominator[ind_out][i]) / (this.numerator[ind_out][i] * this.f_denominator[i]);\n\t\t\tif (a < 0) continue;\n\n\t\t\tif (ind == -1 || a < min_a) {\n\t\t\t\tind = i;\n\t\t\t\tmin_a = a;\n\t\t\t}\n\t\t}\n\t\treturn ind;\n\t}",
"outEdges(v,w){var outV=this.#out[v];if(outV){var edges=Object.values(outV);if(!w){return edges}return edges.filter(edge=>edge.w===w)}}",
"dopusk_in(index_out) {\n\t\tvar ind = -1;\n\t\tvar a = 0;\n\t\tfor (let i=0; i<this.m; i++) {\n\t\t\tif (this.numerator[index_out][i] >= 0) continue;\n\t\t\tif (this.numerator[index_out][i]/this.denominator[index_out][i] < a) {\n\t\t\t\tind = i;\n\t\t\t\ta = this.numerator[index_out][i]/this.denominator[index_out][i];\n\t\t\t}\n\t\t}\n\t\treturn ind;\n\t}",
"exitXmlindex_clause(ctx) {\n\t}",
"resultIndices (inputNodeValuePairs) { return Client.resultIndices(this, inputNodeValuePairs) }",
"_getIndex() {}",
"function isOut(rule, index = 0) {\n let t;\n switch (rule.type) {\n case RuleTypes.min:\n case RuleTypes.s_min:\n case RuleTypes.max:\n case RuleTypes.s_max:\n //the first param is the param value. The second param is 'i' for in or 'o' for out\n t = rule.params[1];\n if (t)\n return t.toLowerCase() === 'o';\n return false;\n case RuleTypes.range:\n case RuleTypes.s_range:\n //the first 2 param are the boundaries. The 3rd param is ii io oi oo\n t = rule.params[2];\n if (t) {\n return t.toLowerCase()[index] === 'o';\n }\n return false;\n }\n return false;\n }",
"outEdges(v, w) {\n var outV = this.#out[v];\n if (outV) {\n var edges = Object.values(outV);\n if (!w) {\n return edges;\n }\n return edges.filter(edge => edge.w === w);\n }\n }",
"_findInIndex (index0, key0, key1, key2, name0, name1, name2, graph, callback, array) {\n let tmp, index1, index2\n\n // If a key is specified, use only that part of index 0.\n if (key0) {\n (tmp = index0, index0 = {})[key0] = tmp[key0]\n }\n\n for (const value0 in index0) {\n index1 = index0[value0]\n\n if (index1) {\n // If a key is specified, use only that part of index 1.\n if (key1) {\n (tmp = index1, index1 = {})[key1] = tmp[key1]\n }\n\n for (const value1 in index1) {\n index2 = index1[value1]\n\n if (index2) {\n // If a key is specified, use only that part of index 2, if it exists.\n const values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2)\n // Create quads for all items found in index 2.\n for (let l = 0; l < values.length; l++) {\n const parts = {\n [name0]: value0,\n [name1]: value1,\n [name2]: values[l]\n }\n\n const quad = this._getQuad(parts.subject, parts.predicate, parts.object, graph)\n\n if (array) {\n array.push(quad)\n } else if (callback(quad)) {\n return true\n }\n }\n }\n }\n }\n }\n\n return array\n }",
"function getBisectorIndex(outputVerts, newVertTable, i0, i1) {\r\n var i01;\r\n var s = i0 + '_' + i1;\r\n if (newVertTable.hasOwnProperty(s)) {\r\n i01 = newVertTable[s];\r\n } else {\r\n // Must create the new vertex and record its index [in both orders].\r\n var v = bisectAngle(getVertex(outputVerts, i0),\r\n getVertex(outputVerts, i1));\r\n i01 = newVertTable[i1 + '_' + i0] = newVertTable[s] =\r\n outputVerts.length / 3;\r\n outputVerts.push(v[0]);\r\n outputVerts.push(v[1]);\r\n outputVerts.push(v[2]);\r\n }\r\n return i01;\r\n }",
"_findInIndex (index0, key0, key1, key2, name0, name1, name2, graph, callback, array) {\n let tmp, index1, index2;\n\n // If a key is specified, use only that part of index 0.\n if (key0) {\n (tmp = index0, index0 = {})[key0] = tmp[key0];\n }\n\n for (const value0 in index0) {\n index1 = index0[value0];\n\n if (index1) {\n // If a key is specified, use only that part of index 1.\n if (key1) {\n (tmp = index1, index1 = {})[key1] = tmp[key1];\n }\n\n for (const value1 in index1) {\n index2 = index1[value1];\n\n if (index2) {\n // If a key is specified, use only that part of index 2, if it exists.\n const values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2);\n // Create quads for all items found in index 2.\n for (let l = 0; l < values.length; l++) {\n const parts = {\n [name0]: value0,\n [name1]: value1,\n [name2]: values[l]\n };\n\n const quad = this._getQuad(parts.subject, parts.predicate, parts.object, graph);\n\n if (array) {\n array.push(quad);\n } else if (callback(quad)) {\n return true\n }\n }\n }\n }\n }\n }\n\n return array\n }",
"exitLocal_xmlindex_clause(ctx) {\n\t}",
"exitBitmap_join_index_clause(ctx) {\n\t}",
"illegallyOut(af) {\n const result = [];\n for (let arg of this.out) {\n if (intersection(af.defeatermap[arg], this.in).length===0) {\n result.push(arg);\n }\n }\n return result;\n }",
"outputIdx(i) {\n if (i>=this.nOutputs) throw new Error(\"Accessing an invalid output: \"+i);\n return i+1;\n }",
"enterXmlindex_clause(ctx) {\n\t}",
"function advance_removed_out (index) {\r\n for (i = 0; i < removed.length; i++){\r\n if (removed[i][1] > index){\r\n removed[i][1] -= 1;\r\n }\r\n }\r\n}",
"exitSimpleIndexDeclaration(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
O(kn) time and O(n) space where K is the number of maxSteps and n is the height of the stairs and the size of the memoization structure | function staircaseTraversal(height, maxSteps) {
return stairsHelper(height, maxSteps, {0:1, 1:1});
// Write your code here.
function stairsHelper(height, maxSteps, memoize) {
if(height in memoize) return memoize[height];
let ways = 0;
for(let step = 1; step < Math.min(maxSteps, height) + 1; step++) {
ways += stairsHelper(height - step, maxSteps, memoize);
}
memoize[height] = ways;
return ways;
}
} | [
"function stepPerms(n) {\n // set a counter variable to keep track of how many ways\n // return the number of different ways to climb the stairs\n\n // find a base case\n // if the steps left is negative, return 0\n // if we have no steps left, return 1\n // memoization: if cache[n] exists, return the cache\n // call our function recursively\n //cache[n] = stepPerms(n-1)) + n-2 + n-3\n // return what's in our cache\n const hashTable = {};\n function stairs(n) {\n if (n === 0) return 1;\n if (n < 0) return 0;\n if (hashTable[n]) {\n return hashTable[n];\n } else {\n hashTable[n] = stairs(n - 1) + stairs(n - 2) + stairs(n - 3);\n return hashTable[n];\n }\n }\n\n return stairs(n);\n}",
"function climbStairsNstepsSkipRed(n, k, redSteps) {\n let hash = Array(k).fill(0);\n hash[0] = 1;\n\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j < k; j++) {\n if (i - j < 0) continue;\n // i - 1 because the boolean array is indexed zero\n // k is only 7 in this case but we iterate on the other loop 8 times\n if (redSteps[i - 1]) hash[i % k] = 0;\n else hash[i % k] += hash[(i - j) % k];\n }\n }\n\n return hash[n % k];\n}",
"function fillMemo(n, memo) {\n //console.log('memo', memo)\n if (memo.hasOwnProperty(n.toString())) return memo[n.toString()]\n if (n === 0) {\n memo['0'] = 0\n return 0\n }\n if (n === 1) {\n memo['0'] = 0\n memo['1'] = 1\n return 1\n }\n let nthValue = fillMemo(n - 1, memo) + fillMemo(n - 2, memo)\n memo[n.toString()] = nthValue\n return nthValue\n}",
"function CombinationSumIII(k, n) {\n let list = [];\n backtrack(list, [], k, n, 1);\n function backtrack(arrContainer, tempList, k, remain, start) {\n if (tempList.length > k) {\n\n } else if (tempList.length === k && remain === 0) {\n arrContainer.push(tempList);\n } else {\n for (let i = start; i <= 9; i++) {\n tempList.push(i);\n backtrack(arrContainer, [...tempList], k, remain - i, i + 1);\n tempList.pop();\n }\n }\n }\n return list;\n}",
"function resize(chains) {\n var temp = [];\n for (var i = 0; i < chains; i++) {\n temp[i] = SequentialSearchST();\n }\n\n for (var i = 0; i < m; i++) {\n var arr = st[i].printKey();\n arr.forEach(key => {\n var value = st[i].get(key);\n // new hash with new number of chains\n var j = (key & 0x7fffffff) % chains;\n temp[j].put(key, value);\n });\n }\n m = chains;\n st = temp;\n }",
"constructor({nway, size, k, memory, bits}) {\n this.size = size;\n this.k = k;\n this.nway = nway;\n this.bits = bits;\n this.statistics = { misses: 0, replacements: 0, total: 0 };\n this.cache = Array.from({length: nway},\n () => Array.from({length: size},\n () => Array.from({length: k},\n () => {\n return {\n data: '0'.repeat(bits+30), // bits for address + 32 bits for data\n time: 0\n }\n }))); // 3D array for n-way set association\n //this.printSnapshot();\n this.memory = memory;\n }",
"function steps(k) {\n let count = 0;\n while (k > 1) {\n if (k % 2 === 0) {\n k /= 2;\n } else if (k % 4 === 3 && k > 3) {\n // Numbers just below factors of 4 (2^2); except 3\n k++;\n } else {\n k--;\n }\n count++;\n }\n return count;\n}",
"function computeHash(){\n\tvar k = 6;\n\t//all permutations of length 6; compute the hash and story them\n\tvar allResult = regularComputerCombinations(storyBank, 6);\n}",
"e78() {\n let answer = 0;\n let n = 3;\n // memoized partition list MEM[i] = p(i)\n const MEM = [1, 1, 2];\n while (!answer) {\n let i = 1;\n let term = penta(i);\n let currentPartition = 0;\n // sum all terms p(n-1), p(n-2), p(n-5), etc.\n while (term <= n) {\n const sign = (i - 1) % 4 > 1 ? -1 : 1;\n currentPartition += sign * MEM[n - term];\n i++;\n term = penta(i);\n }\n currentPartition %= 1000000;\n if (currentPartition === 0) {\n answer = n;\n break;\n }\n MEM[n] = currentPartition;\n n++;\n }\n\n return answer;\n\n // generalized pentagonal number generator\n function penta(k) {\n if (k & 1) {\n const m = (k + 1) / 2;\n return m * (3 * m - 1) / 2;\n }\n const m = k / 2;\n return m * (3 * m + 1) / 2;\n }\n }",
"function sol(n, k, lamps) {\n // n = # of lamps\n // k = period\n // find min number of moves necessary to to make k periodic garland of lamps from given one\n\n // total 1s to right of index\n const total = Array(n).fill(0);\n // total 1s to right of index within k period\n const totalRight = Array(n).fill(0);\n // total 1s to left of an index\n const totalLeft = Array(n).fill(0);\n\n findTotals();\n\n const dp = Array(n).fill(Infinity);\n\n if (lamps[n - 1] === \"1\") {\n dp[n - 1] = 0;\n } else {\n dp[n - 1] = 1;\n }\n\n // scan from right\n\n for (let i = n - 2; i >= 0; i--) {\n if (lamps[i] === \"1\") {\n // convert to 0\n // (cost to convert to 0) + (# of 1s to right of i, OR cost to convert 1s to 0s)\n dp[i] = Math.min(dp[i], 1 + total[i]);\n // keep as 1\n // (cost to keep as 1) + (total 1s within k period) + (computed dp[i + k + 1], already computed value for the string outside of k period!!)\n dp[i] = Math.min(dp[i], 0 + totalRight[i] + (i + k < n ? dp[i + k] : 0));\n } else if (lamps[i] === \"0\") {\n // convert to 1\n dp[i] = Math.min(dp[i], 1 + totalRight[i] + (i + k < n ? dp[i + k] : 0));\n // keep as 0\n dp[i] = Math.min(dp[i], 0 + total[i]);\n }\n }\n\n // scan from left\n\n for (let i = 1; i < n; i++) {\n // assuming everything to right is k period\n // add # of 1s to left of i to dp[i]\n dp[i] += totalLeft[i];\n }\n\n return Math.min(...dp);\n\n function findTotals() {\n let sum = 0;\n for (let i = n - 1; i >= 0; i--) {\n total[i] = sum;\n\n if (lamps[i] === \"1\") {\n sum += 1;\n }\n }\n sum = 0;\n for (let i = n - 1; i >= 0; i--) {\n if (i + k < n) {\n totalRight[i] = sum - total[i + k - 1];\n } else {\n totalRight[i] = sum;\n }\n\n if (lamps[i] === \"1\") {\n sum += 1;\n }\n }\n sum = 0;\n for (let i = 0; i < n; i++) {\n totalLeft[i] = sum;\n if (lamps[i] === \"1\") {\n sum += 1;\n }\n }\n }\n}",
"function sol(nums, k) {\n // sum : index\n const map = {};\n map[0] = -1;\n let sum = 0;\n let maxLen = 0;\n for (let i = 0; i < nums.length; i++) {\n sum += nums[i];\n if (map[`${sum - k}`]) {\n maxLen = Math.max(maxLen, i - map[`${sum - k}`]);\n }\n if (!map[sum]) map[sum] = i;\n }\n\n return maxLen;\n}",
"function stepper(nums, memo={}) {\n\n // Tabulation: \n\n // let steppable = new Array(nums.length).fill(false);\n // steppable[0] = true;\n // for (let i = 0; i < nums.length; i++) {\n // if (steppable[i] === true) {\n // let howManySteps = nums[i];\n // for (let step = 1; step <= howManySteps; step++) {\n // steppable[i + step] = true;\n // }\n // }\n // }\n // return steppable[steppable.length-1];\n\n // Memoization\n\n let arrlengths = nums.length;\n if (arrlengths in memo) return memo[arrlengths];\n if (nums.length === 0) return true;\n for (let i = 1; i <= nums[0]; i++) {\n if (stepper(nums.slice(i), memo)) {\n memo[arrlengths] = true;\n return memo[arrlengths];\n };\n }\n memo[arrlengths] = false;\n return memo[arrlengths];\n}",
"function case9(n){\n\tstep=0\n\tfor(i=0; i<n ;i++){\n\t\tfor(j=1 ;j<n; j=j*2){\n\t\t\tstep++\n\t\t}\n\t\tstep++\n\t}\n\tconsole.log('steps taken:',step)\n\tconsole.log('Time complexity:',Math.ceil(n*Math.log2(n)))\n}",
"e55() {\n const lychrelNumbers = {}; // memoized table for all lychrel numbers (doesnt terminate)\n const nonLychrelNumbers = {}; // numbers which produce a palindrome through reverse add\n\n for (let n = 1; n <= 10000; n++) {\n testLychrel(n);\n }\n\n function testLychrel(n) {\n const encounteredNumbers = {};\n let sum = n;\n for (let i = 1; i <= 50; i++) {\n const flipped = utils.flip(sum);\n encounteredNumbers[sum] = true;\n if (sum % 10) {\n encounteredNumbers[flipped] = true;\n }\n if (nonLychrelNumbers[sum]) {\n Object.assign(nonLychrelNumbers, encounteredNumbers);\n break;\n }\n if (lychrelNumbers[sum] || i === 50) {\n Object.assign(lychrelNumbers, encounteredNumbers);\n break;\n }\n sum += flipped;\n if (utils.isPalindrome(sum)) {\n Object.assign(nonLychrelNumbers, encounteredNumbers);\n break;\n }\n }\n }\n\n return Object.keys(lychrelNumbers).filter(x => x <= 10000).length;\n }",
"function nump2(numberOfSteps,posibleSteps) {\n let total = { count: 0, paths: [] };\n let path = [];\n function findSteps(stepsToGo, nextSteps) {\n if (stepsToGo === 0) {\n total.count += 1\n let newP = [...path];\n total.paths.push(newP); //Send a copy of the current path to the output object array as a solution\n return;\n }\n nextSteps.map(step => {\n if (stepsToGo - step >= 0) {\n path.push(step);\n findSteps(stepsToGo - step, nextSteps);\n path.pop();\n }\n });\n };\n findSteps(numberOfSteps,posibleSteps);\n return total.count;\n}",
"function solution(K, M, A) {\n let sum = 0;\n let lower = 0;\n let upper = 0;\n let mid = 0;\n let i = 0;\n \n for(i=0; i<A.length; i++) {\n upper += A[i];\n lower = Math.max(lower, A[i]);\n }\n \n if(K === 1) {\n return upper;\n } else if(K >= A.length) {\n return lower;\n }\n \n while(lower <= upper) {\n let temp = mid;\n mid = parseInt((upper + lower) / 2);\n \n if(mid === temp) {\n break;\n }\n \n let blocks = neededBlocks(A, mid);\n \n console.log('max, min, mid, blocks, K:', upper, lower, mid, blocks, '<', K);\n \n if(blocks > K) {\n lower = mid+1;\n } else {\n upper = mid;\n }\n }\n \n return upper;\n}",
"function josephusSurvivor(n, k) {\n return n < 1 ? 1 : ((josephusSurvivor(n - 1, k) + --k) % n) + 1;\n}",
"function countSteps(n)\n{\n\treturn 0;\n}",
"function countSteps( n ) {\n return 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes the active camera | updateCamera() {
this.camera = this.cameras.get(this.currentCameraID);
this.interface.setActiveCamera(this.camera);
} | [
"updateCamera() {\n this.camera = this.cameras[this.selectedCamera];\n this.interface.setActiveCamera(this.camera);\n }",
"setCamera(camera) {\n this.activeCamera = camera;\n }",
"updateCurrentCamera() {\n this.camera = this.cameras[this.selectedCamera];\n this.camera.reset();\n this.interface.setActiveCamera(this.camera);\n }",
"updateCamera() {\n\n this.camera = this.cameras[Object.keys(this.cameras)[this.activeCamera]];\n this.camera.resetCamera();\n this.interface.setActiveCamera(this.camera);\n }",
"changeCamera(currentCamera){\n if(this.pente.active_game == false){\n this.camera = this.views[currentCamera];\n this.interface.setActiveCamera(this.camera);\n }\n }",
"function setActiveCamera()\n\t{\n\t\tif($('input[type=\"radio\"]:checked').attr('id') === 'perspective')\n\t\t{\n\t\t\tactiveCamera = perspectiveCamera;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tactiveCamera = orthoCamera;\n\t\t}\n\t}",
"set activeCamera(camera) {\n\t\t/* if (!this.isOwnCamera(camera) && !this.isSharedCamera(camera)) {\n\t\t\tconsole.error(\"Tried to set the camera that is managed by the camera manager as the active camera!\")\n\t\t\treturn\n\t\t} */\n\n\t\tthis._activeCamera = camera;\n\n\t\tif(this._cameras[camera._uuid] === undefined) this.addFullOrbitCamera(camera, new Vector3(0, 0, 0));\n\t}",
"updateCamera() {\n this.camera = this.themeGraphs[this.selectedTheme].views[this.cameraID];\n // if (this.cameraID != this.themeGraphs[this.selectedTheme].defaultCameraId) {\n // this.interface.setActiveCamera(this.camera);\n // } else {\n // this.interface.setActiveCamera(null);\n // }\n }",
"changeToGameCamera() {\n this.currentCameraID = 'game'\n this.currentGameCamera = 'game'\n this.camera.changeCamera(this.gameCameras.get('game'))\n }",
"updateCamera() {\n //this.camera = this.cameras[this.selectView];\n //this.interface.setActiveCamera(this.camera);\n this.gameOrchestrator.cameraAnimationTime = null;\n this.gameOrchestrator.changeCamera(this.cameras[this.selectView]);\n this.gameOrchestrator.state = this.gameOrchestrator.gameStates['Change Camera Position'];\n }",
"function setCamera() {\n\t\t//alert(cam);\n\t\t// cam should be set to the current model\n\t\t// also see todo in switchX3DomModel()\n\t\tdocument.getElementById(cam).setAttribute('set_bind', 'true');\n\t}",
"onCameraChanged() {\r\n this.camera = this.cameras[this.selectedCamera];\r\n }",
"function updateCamera() {\r\n realityBuilder.camera().update(cameraDataFromControls());\r\n }",
"function changeCamera(){\n cameraIndex = this.value;\n\n // update dat gui\n updateGUI(cameraInformationList[cameraIndex], controls, gui);\n\n //redraw camera model\n controls.updateDraw(); \n\n //fly to current camera\n var latlon = new VIZI.LatLon(cameraInformationList[cameraIndex].lat, cameraInformationList[cameraIndex].lon);\n \n world._controls[0].flyToLatLon(latlon, 3, 1);\n\n //update video player\n setupPlayer(settings_3d.playerDiv, cameraInformationList[cameraIndex].cameras[viewIndex].stream_id, 300, 280); \n\n controls.reDrawSegments(); \n\n}",
"static SetCamera() {}",
"function changeCameraMode() {\r\n\t\tembeddedCamera = !embeddedCamera;\r\n\t\tconsole.log('camera mode: ' + (embeddedCamera ? 'embedded' : 'fixed'));\r\n\t}",
"toggleGameCamera() {\n if(this.gameCameraActive) {\n this.scene.camera = this.gameCamera;\n this.scene.interface.setActiveCamera(null);\n } else {\n this.scene.camera = this.scene.cameras[this.scene.selectedViewIndex];\n this.scene.interface.setActiveCamera(this.scene.camera);\n }\n }",
"SET_SELECTED_CAMERA (state, camera) {\n state.selectedCamera = camera\n }",
"updateCamera() {\n this.camera = this.game.renderer.camera;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new CUBRID connection instance | function CUBRIDConnection(brokerServer, brokerPort, user, password, database, cacheTimeout) {
// Using EventEmitter.call on an object will do the setup of instance methods / properties
// (not inherited) of an EventEmitter.
// It is similar in purpose to super(...) in Java or base(...) in C#, but it is not implicit in Javascript.
// Because of this, we must manually call it ourselves:
EventEmitter.call(this);
this._queryCache = null;
if (typeof cacheTimeout !== 'undefined' && cacheTimeout > 0) {
this._queryCache = new Cache();
}
this._socket = new Net.Socket();
// Connection parameters
this.brokerServer = brokerServer || 'localhost';
this.initialBrokerPort = brokerPort || 33000;
this.connectionBrokerPort = -1;
this.user = user || 'public';
this.password = password || '';
this.database = database || 'demodb';
// Session public variables
this.autoCommitMode = null; //will be initialized on connect
this.sessionId = 0;
// Execution semaphore variables; prevent double-connect-attempts, overlapping-queries etc.
this.connectionOpened = false;
this.connectionPending = false;
this.queryPending = false;
// Driver events
this.EVENT_ERROR = 'error';
this.EVENT_CONNECTED = 'connect';
this.EVENT_ENGINE_VERSION_AVAILABLE = 'engine version';
this.EVENT_BATCH_COMMANDS_COMPLETED = 'batch execute done';
this.EVENT_QUERY_DATA_AVAILABLE = 'query data';
this.EVENT_SCHEMA_DATA_AVAILABLE = 'schema data';
this.EVENT_FETCH_DATA_AVAILABLE = 'fetch';
this.EVENT_FETCH_NO_MORE_DATA_AVAILABLE = 'fetch done';
this.EVENT_BEGIN_TRANSACTION = 'begin transaction';
this.EVENT_SET_AUTOCOMMIT_MODE_COMPLETED = 'set autocommit mode';
this.EVENT_COMMIT_COMPLETED = 'commit';
this.EVENT_ROLLBACK_COMPLETED = 'rollback';
this.EVENT_QUERY_CLOSED = 'close query';
this.EVENT_CONNECTION_CLOSED = 'close';
this.EVENT_LOB_READ_COMPLETED = 'lob read completed';
//Auto-commit constants
this.AUTOCOMMIT_ON = true;
this.AUTOCOMMIT_OFF = false;
//Database schema variables
this.SCHEMA_TABLE = CASConstants.CUBRIDSchemaType.CCI_SCH_CLASS;
this.SCHEMA_VIEW = CASConstants.CUBRIDSchemaType.CCI_SCH_VCLASS;
this.SCHEMA_ATTRIBUTE = CASConstants.CUBRIDSchemaType.CCI_SCH_ATTRIBUTE;
//Private variables
this._CASInfo = [0, 0xFF, 0xFF, 0xFF];
this._queriesPacketList = [];
this._INVALID_RESPONSE_LENGTH = -1;
this._PREVENT_CONCURRENT_REQUESTS = true;
this._LOB_MAX_IO_LENGTH = 128 * 1024;
//Database engine version
this._DB_ENGINE_VER = '';
//Uncomment the following lines if you will not always provide an 'error' listener in your consumer code,
//to avoid any unexpected exception. Be aware that:
//Error events are treated as a special case in node. If there is no listener for it,
//then the default action is to print a stack trace and exit the program.
//http://nodejs.org/api/events.html
//this.on('error',function(err){
// Helpers.logError(err.message);
// //... (add your own error-handling code)
//});
} | [
"function CUBRIDConnection(brokerServer, brokerPort, user, password, database, cacheTimeout) {\n // Using EventEmitter.call on an object will do the setup of instance methods / properties\n // (not inherited) of an EventEmitter.\n // It is similar in purpose to super(...) in Java or base(...) in C#, but it is not implicit in Javascript.\n // Because of this, we must manually call it ourselves:\n EventEmitter.call(this);\n\n this._queryCache = null;\n if (typeof cacheTimeout !== 'undefined' && cacheTimeout > 0) {\n this._queryCache = new Cache();\n }\n\n this._socket = new Net.Socket();\n\n // Connection parameters\n this.brokerServer = brokerServer || 'localhost';\n this.initialBrokerPort = brokerPort || 33000;\n this.connectionBrokerPort = -1;\n this.user = user || 'public';\n this.password = password || '';\n this.database = database || 'demodb';\n\n // Session public variables\n this.autoCommitMode = null; // Will be initialized on connect\n this.sessionId = 0;\n\n // Execution semaphore variables; prevent double-connect-attempts, overlapping-queries etc.\n this.connectionOpened = false;\n this.connectionPending = false;\n this.queryPending = false;\n\n // Driver events\n this.EVENT_ERROR = 'error';\n this.EVENT_CONNECTED = 'connect';\n this.EVENT_ENGINE_VERSION_AVAILABLE = 'engine version';\n this.EVENT_BATCH_COMMANDS_COMPLETED = 'batch execute done';\n this.EVENT_QUERY_DATA_AVAILABLE = 'query data';\n this.EVENT_SCHEMA_DATA_AVAILABLE = 'schema data';\n this.EVENT_FETCH_DATA_AVAILABLE = 'fetch';\n this.EVENT_FETCH_NO_MORE_DATA_AVAILABLE = 'fetch done';\n this.EVENT_BEGIN_TRANSACTION = 'begin transaction';\n this.EVENT_SET_AUTOCOMMIT_MODE_COMPLETED = 'set autocommit mode';\n this.EVENT_COMMIT_COMPLETED = 'commit';\n this.EVENT_ROLLBACK_COMPLETED = 'rollback';\n this.EVENT_QUERY_CLOSED = 'close query';\n this.EVENT_CONNECTION_CLOSED = 'close';\n this.EVENT_LOB_READ_COMPLETED = 'LOB read completed';\n this.EVENT_LOB_NEW_COMPLETED = 'LOB new completed';\n this.EVENT_LOB_WRITE_COMPLETED = 'LOB write completed';\n this.EVENT_SET_DB_PARAMETER_COMPLETED = 'set db parameter completed';\n this.EVENT_GET_DB_PARAMETER_COMPLETED = 'get db parameter completed';\n\n // Auto-commit constants\n this.AUTOCOMMIT_ON = true;\n this.AUTOCOMMIT_OFF = !this.AUTOCOMMIT_ON;\n\n // Database schema variables\n this.SCHEMA_TABLE = CASConstants.CUBRIDSchemaType.CCI_SCH_CLASS;\n this.SCHEMA_VIEW = CASConstants.CUBRIDSchemaType.CCI_SCH_VCLASS;\n this.SCHEMA_ATTRIBUTE = CASConstants.CUBRIDSchemaType.CCI_SCH_ATTRIBUTE;\n this.SCHEMA_CONSTRAINT = CASConstants.CUBRIDSchemaType.CCI_SCH_CONSTRAIT;\n this.SCHEMA_PRIMARY_KEY = CASConstants.CUBRIDSchemaType.CCI_SCH_PRIMARY_KEY;\n this.SCHEMA_IMPORTED_KEYS = CASConstants.CUBRIDSchemaType.CCI_SCH_IMPORTED_KEYS;\n this.SCHEMA_EXPORTED_KEYS = CASConstants.CUBRIDSchemaType.CCI_SCH_EXPORTED_KEYS;\n this.SCHEMA_CLASS_PRIVILEGE = CASConstants.CUBRIDSchemaType.CCI_SCH_CLASS_PRIVILEGE;\n\n // LOB types variables\n this.LOB_TYPE_BLOB = CASConstants.CUBRIDDataType.CCI_U_TYPE_BLOB;\n this.LOB_TYPE_CLOB = CASConstants.CUBRIDDataType.CCI_U_TYPE_CLOB;\n\n this._CASInfo = [0, 0xFF, 0xFF, 0xFF];\n this._queriesPacketList = [];\n this._INVALID_RESPONSE_LENGTH = -1;\n this._PREVENT_CONCURRENT_REQUESTS = true;\n this._LOB_MAX_IO_LENGTH = 128 * 1024;\n\n // Database engine version\n this._DB_ENGINE_VER = '';\n\n // Timeout values (msec.)\n this._CONNECTION_TIMEOUT = 0;\n\n // Enforce execute query using the old protocol\n this._ENFORCE_OLD_QUERY_PROTOCOL = false;\n\n // Each element in the queries queue array contains:\n // 0:query handle, 1:sql, 2:query status, 3:callback to call when done\n this._queriesQueue = [];\n this._QUERY_INFO = {\n HANDLE : 0,\n SQL : 1,\n STATUS : 2,\n CALLBACK : 3,\n SQL_TYPE : 4\n };\n\n this._QUERY_STATUS = {\n NOT_STARTED : 0,\n IN_EXECUTION : 1,\n CLOSED : 2\n };\n\n this._SQL_TYPE = {\n IS_QUERY : 0,\n IS_NON_QUERY : 1\n };\n\n // Queries queue check interval (msec.)\n // You can try to reduce this value to speed-up queries queue processing\n // However, a small value will introduce a memory overhead and potential queries collision side effects\n this._QUERIES_QUEUE_CHECK_INTERVAL = 1000;\n\n // Current active status of the queries queue background processor\n this._QUERIES_QUEUE_PROCESSOR_STARTED = false;\n\n // Used for standard callbacks 'err' parameter\n this._NO_ERROR = null;\n\n // Uncomment the following lines if you will not always provide an 'error' listener in your consumer code,\n // to avoid any unexpected exception. Be aware that:\n // Error events are treated as a special case in node. If there is no listener for it,\n // then the default action is to print a stack trace and exit the program.\n // http://nodejs.org/api/events.html\n // this.on('error',function(err){\n // Helpers.logError(err.message);\n //// ... (add your own error-handling code)\n //});\n}",
"function createConnection () {\n connection = App.models.endpoint({\n id: options.connectTo,\n client: client,\n onMessage: renderReply\n });\n }",
"function init_connection(){\n var connection = {}\n connection.client = new cassandra.Client({ \n cloud: { secureConnectBundle: SECURE_CONNECT_BUNDLE },\n keyspace: KEYSPACE,\n credentials: { username: USERNAME, password: PASSWORD } \n });\n return connection\n}",
"function createConnection() {\n var connection = new Connection(this.options);\n\n connection.observe(onObserve.bind(this));\n\n _connections.push(connection);\n}",
"async function buildConnection() {\n return index_1.api.specHelper.Connection.createAsync();\n }",
"function new_rserve_connection() {\n var connection = rserve.create();\n console.log('Made new rserve connection');\n return connection;\n}",
"async getNewConnection() {\n this.debug(\"Trying to get a new Connection\")\n const connIdx = this.connections.length\n const conn = new PoolConnection(this.config, this, connIdx)\n this.trace(\"New connection created\")\n\n if (this.nolog) {\n conn.disableLog()\n }\n this.connections.push(conn)\n this.trace(\"New connection pushed to pool\")\n\n await conn.initialize()\n return conn\n }",
"function create_connection()\n {\n client = require(\"mysql\").createConnection({\n host: config.host,\n user: config.user,\n port: config.port,\n password: config.pass,\n database: config.base,\n socketPath: config.sock,\n });\n }",
"function _conn() {\n return new Connector();\n}",
"function getConnection() {\n if (!connection) {\n connection = new web3.Connection(\n web3.clusterApiUrl(nodeType),\n commitment,\n );\n }\n return connection;\n}",
"function invokeConnection() {\n // Creating a Multi Statement AWS RDS Connection object\n var conn = mysql.createConnection({\n host: \"smartemail.cqugwibhbf4m.us-east-2.rds.amazonaws.com\",\n user: \"admin\",\n password: \"adminadmin\",\n database: \"smartemail\",\n multipleStatements: true\n });\n return conn;\n}",
"function RhoConnectClient() {\n var id = null;\n this.getId = function () {return id;};\n\n if (1 == arguments.length && arguments[0][rhoUtil.rhoIdParam()]) {\n if (moduleNS != arguments[0][rhoUtil.rhoClassParam()]) {\n throw \"Wrong class instantiation!\";\n }\n id = arguments[0][rhoUtil.rhoIdParam()];\n } else {\n id = rhoUtil.nextId();\n // constructor methods are following:\n \n }\n }",
"createConnection(config) {\n return new MySqlConnection(mysql.createConnection(config), config);\n }",
"constructConnection(cfg) {\n let driver = this._drivers[cfg.type];\n let connection = new driver.cls(cfg);\n return connection;\n }",
"get connection () {}",
"function newClient() {\n var client = redis.createClient(host.port, host.hostname)\n if (host.auth) {\n client.auth(host.auth.split(\":\")[1])\n }\n return client\n}",
"createConnection(req, res, next) {\n r\n .connect(config.rethinkdb)\n .then((conn) => {\n req._rdbConn = conn;\n next();\n })\n .error(err => next(err));\n }",
"async init() {\n try {\n this.connection = await amqplib.connect(AMQP_URL);\n this.channel = await this.connection.createChannel();\n return this;\n } catch (error) {\n console.log(error.message);\n }\n }",
"constructor(connection){\n this.connection = connection;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=================================================================== from functions/io/FlushOut.java =================================================================== Needed early: Builtin Needed late: IO ArcObject | function FlushOut() {
} | [
"_final(cb) {\n // flush outstream\n this.flushOutstream(true)\n .then(() => {\n cb();\n })\n .catch((err) => cb(err)); // cb and return\n }",
"_flush() {\n const centralDirectoryOffset = this._offset;\n let centralDirectorySize = 0;\n for (const i in this._files)\n this._writeCentralDirectoryHeader(this._files[i]);\n centralDirectorySize = this._offset - centralDirectoryOffset;\n this._writeEndOfCentralDirectory(\n centralDirectoryOffset,\n centralDirectorySize,\n );\n // Once this buffer is out, we're done with the output stream\n this.output.end();\n }",
"_flush(done) {\n let buf;\n if (this.lastByte === 0x0a) {\n buf = Buffer.from('.\\r\\n');\n } else if (this.lastByte === 0x0d) {\n buf = Buffer.from('\\n.\\r\\n');\n } else {\n buf = Buffer.from('\\r\\n.\\r\\n');\n }\n this.outByteCount += buf.length;\n this.push(buf);\n done();\n }",
"function writeDone() {\n}",
"end() {\n this.align();\n this.flush();\n this.emit('finish');\n delete this.buffer;\n }",
"function flush_char(outs) {\n if (a_count > 0) {\n outs.writeByte(a_count);\n outs.writeBytes(accum, 0, a_count);\n a_count = 0;\n }\n }",
"async flush() {\n if (this.err !== null)\n throw this.err;\n if (this.n === 0)\n return;\n let n = 0;\n try {\n n = await this.wr.write(this.buf.subarray(0, this.n));\n }\n catch (e) {\n this.err = e;\n throw e;\n }\n if (n < this.n) {\n if (n > 0) {\n this.buf.copyWithin(0, n, this.n);\n this.n -= n;\n }\n this.err = new Error(\"Short write\");\n throw this.err;\n }\n this.n = 0;\n }",
"function clearIO()\n{\n for(let i=0;i<256;i++)\n {\n out[i]=\"0\";\n }\n exec();\n}",
"closePath() {\n this._out.closePath();\n }",
"flush() {\n if (this.err !== null)\n throw this.err;\n if (this.usedBufferBytes === 0)\n return;\n try {\n Deno.writeAllSync(this.writer, this.buf.subarray(0, this.usedBufferBytes));\n }\n catch (e) {\n this.err = e;\n throw e;\n }\n this.buf = new Uint8Array(this.buf.length);\n this.usedBufferBytes = 0;\n }",
"_flush() {\n // Did we write the headers already? If not, start there.\n if (!this._wroteHeader) this._writeLocalFileHeader();\n\n // Is anything buffered? If so, flush it out to output stream and recurse.\n if (this._buffers) {\n for (const i in this._buffers) this._deflate.write(this._buffers[i]);\n this._buffers = [];\n }\n\n // Are we done writing to this file? Flush the deflated stream,\n // which triggers writing file descriptor.\n if (!this.writable) this._deflate.end();\n }",
"writeFlushMessage () {\n return this._begin(0x48)._end()\n // return this._writeBytes(FLUSH_MESSAGE)\n }",
"function FlushingStream() {\n BufferedStream.apply(this, arguments);\n}",
"function FlushingStream() {\n BufferedStream.apply(this, arguments);\n}",
"flush() {\n if (this.err !== null) throw this.err;\n if (this.usedBufferBytes === 0) return;\n try {\n Deno.writeAllSync(this.writer, this.buf.subarray(0, this.usedBufferBytes));\n } catch (e) {\n this.err = e;\n throw e;\n }\n this.buf = new Uint8Array(this.buf.length);\n this.usedBufferBytes = 0;\n }",
"writeTo(out) {\n out.writeBytesOffset(this.buf, 0, this.count);\n }",
"function queueOut(Rd) {\n }",
"async flush() {\n if (this.err !== null) throw this.err;\n if (this.usedBufferBytes === 0) return;\n try {\n await Deno.writeAll(this.writer, this.buf.subarray(0, this.usedBufferBytes));\n } catch (e) {\n this.err = e;\n throw e;\n }\n this.buf = new Uint8Array(this.buf.length);\n this.usedBufferBytes = 0;\n }",
"function writeend() {\n if (sync) {\n // _end has origin res.end\n // here we call origin res.end and pass this ans res, and two arguments chunk, encoding\n ret = _end.call(res, chunk, encoding);\n sync = false; // set to fals for not running second time this code\n return;\n }\n\n // if it call second time do without parameters\n _end.call(res);\n } // function writeend() {"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Raises "Not Implemented" exception | static notImplemented_() {
throw new Error('Not implemented');
} | [
"notImplemented () {\n throw new Error('Not Implemented')\n }",
"function notImplemented() {\n throw new Error(\"Not implemented\");\n }",
"function notImplemented(){throw new Error(\"Not implemented\");}",
"function notImplemented() {\n throw new Error(\"Not implemented\");\n }",
"function notImplemented() {\n return new Error('Not Implemented');\n }",
"function NotImplemented() {\n throw 'NotImplemented Exception.';\n }",
"function required(){\n\t\tthrow new Error(\"This method is required and no implementation has been provided\");\n\t}",
"function notImplementedOper(ctx) { ctx.complain(this.name, 'not implemented'); }",
"swim() {\n MxI.$raiseNotImplementedError(IFish, this);\n }",
"fallback() {\n\t\t\t// Could be implemented\n\t\t}",
"function yetToImplement() {\n\t alert(\"Not implemented in this Demo\");\n\t}",
"surprise(name) {\n throw new Error('This method to be implemented by the sub-class');\n }",
"function notSupportedError() {\n\t\t\treturn sendError('Trying to invoke unsupported response method (`res.foo`) in response to a request from socket.io!');\n\t\t}",
"create () {\n throw new Error(`Make sure to implement the \"create\" method in your ${this.constructor.name} mailable.`)\n }",
"init () {\n throw {\n name: \"NoImplException\",\n message: \"No init method provided in UIElement derived class!\"\n };\n }",
"dispatch() {\n throw new NotImplementedException();\n }",
"function AuthorizationRequiredException() {}",
"operation(operation_id, ...args) {\n MxI.$raiseNotImplementedError(IImplementor, this);\n }",
"interceptResolutionState() {\n throw new Error('Not implemented');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the global variable that holds the request Send the request to the server to get the last week questions | function processlastWeek() {
lastWeekClient = new XMLHttpRequest();
var url = 'http://developer.cege.ucl.ac.uk:'+ httpPortNumber + "/getlastWeek/";
lastWeekClient.open('GET',url,true);
lastWeekClient.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
lastWeekClient.onreadystatechange = lastWeekUploaded;
lastWeekClient.send();
} | [
"function informAboutQuiz(date) {\n var start_date = new Date(date)\n var end_date = new Date(date)\n end_date.setHours(end_date.getHours() + 1)\n request = `${DEADLINE_SCHEDULING_SUGGESTION_API}/${COLLEGE_NAME}/inform_about_event/quiz/${quiz_course_selection_dropdown.value}/${start_date.toISOString()}/${end_date.toISOString()}`\n console.log(request)\n fetch(request).then((response) => {\n console.log(response.data)\n }).then((res) => {\n })\n}",
"function getQuestions() {\r\n\tclient2 = new XMLHttpRequest();\r\n\tclient2.open('GET','http://developer.cege.ucl.ac.uk:30289/getquestions');\r\n\tclient2.onreadystatechange = questionResponse; \r\n\tclient2.send();\r\n}",
"function getRecentRespondentRequested() {\n\treturn dbQuery(\"SELECT * FROM RespondentRequest \\\n\tWHERE InsTime > DateADD(mi, -30, Current_TimeStamp)\");\n}",
"function reqSurvey() {\r\n jsonRequest(\r\n 'remote/' + getIntURL('survey', 'show_nps_survey'),\r\n function(jsonData) \r\n {\r\n updateUserFields(jsonData);\r\n updateStats();\r\n autoAttack();\r\n }\r\n );\r\n }",
"function nextQuestion(){\n\t\tvar baseurl = 'https://api.wunderground.com/api';\n\t\tvar krKey = '7ad17aca98534b07';\n\t\tvar finalurl = baseurl + '/' + krKey + '/geolookup/conditions' + currentQ.qSend ;\n\t\tconsole.log(finalurl);\n\t\t// using icon sets from https://www.wunderground.com/weather/api/d/docs?d=resources/icon-sets&MR=1\n\t\t// to change icon sets, change the url's last directory /i/ to /f/, /k/, ... etc\t\n\t\tvar iconurl = 'https://icons.wxug.com/i/c/i/';\n\n\t\t$.ajax({\n\t\t\turl: finalurl,\n\t\t\tcomplete: function(){\t\n\t\t\t\tswapPanel('#user-a, #user-p, .game-wel','#user-q, #user-p');\n\t\t\t\t$('#pos').text(userPos.pos + ' in ' + gameLen);\n\t\t\t\tswapBG();\n\t\t\t\tcurrentT.start();\n\t\t\t},\n\t\t\tsuccess: function( jP ){\n\t\t\t\t// currentQ.curr = Math.round(jP.current_observation.temp_f);\n\t\t\t\t// currentQ.currIcon = iconurl + jP.current_observation.icon + '.gif';\n\t\t\t\t// currentQ.updated = new Date(); \n\n\t\t\t\t// currentAns = changeTemp(currentQ.curr); \n\t\t\t\t// $('.weatherIn').text( currentQ.city + ', ' + currentQ.fullsc );\n\t\t\t\t// $('.weatherGuess').text( currentAns.showTemp );\n\t\t\t},\n\t\t\terror: function( jqXHR, textStatus, errorThrown ){\n\t\t\t\tconsole.log('error '+ errorThrown + ' : ' + textStatus);\n\t\t\t}\n\t\t}).then( function(jP){\n\t\t\tcurrentQ.curr = Math.round(jP.current_observation.temp_f);\n\t\t\t\tcurrentQ.currIcon = iconurl + jP.current_observation.icon + '.gif';\n\t\t\t\tcurrentQ.updated = new Date(); \n\n\t\t\t\tcurrentAns = changeTemp(currentQ.curr); \n\t\t\t\t$('.weatherIn').text( currentQ.city + ', ' + currentQ.fullsc );\n\t\t\t\t$('.weatherGuess').text( currentAns.showTemp );\n\t\t} );\n\n\t}",
"function newQuestion() {\n return $.get(\"http://jservice.io/api/random\", function(data) {\n // console.log(data[0]);\n nextcategory = data[0].category.title;\n nextquestion = data[0].question;\n valuepoints = data[0].value;\n rightanswer = data[0].answer;\n console.log(\"HINT, the answer is: \" + rightanswer);\n });\n }",
"function getNewQuestions() {\n $http.get(url2).\n success(function (unanswered) {\n $scope.unanswered = unanswered;\n $scope.show_new_questions = true;\n $scope.showFAQ = false;\n $scope.showQuestionForm = false;\n $scope.sentQuestion = false;\n $scope.categoryfaq = false;\n }).\n error(function (data, status) {\n console.log(status + data);\n });\n }",
"function requestWeek() {\n\tvar calendarIds = [];\n\t$.each($('input[name=\"calendar\"]:checked'), function() {\n\t\tcalendarIds.push($(this).val());\n\t});\n\tvar weekOf = $(\"#controls\").children('input[name=\"viewingWeek\"]').val();\n\tweekOf = moment(weekOf).format(\"M/D/YYYY\");\n\n\tstompClient.send(\"/app/calendar/viewWeek\", {}, JSON.stringify(\n\t\t\t{\n\t\t\t\t'calendarIds': calendarIds,\n\t\t\t\t'weekOf': weekOf\n\t\t\t}));\n}",
"function getQuizQuestions() {\n //Build the query url, if there is a selected currentCategory \n var queryURL = \"https://opentdb.com/api.php?amount=\" + numQuestions \n + (currentCategory ? \"&category=\" + currentCategory : '')\n + (currentDifficulty ? \"&difficulty=\" + currentDifficulty : '')\n\n //Actual ajax call\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function (response) {\n //Send the results to the questionArray\n questionArray = response.results;\n //Show the question\n showQuestion();\n })\n }",
"surveyQuestions (request) {\n return this._dashboardRequest('get', '/api/survey-questions', request)\n }",
"function checkLastQuestion(site) {\n // Get the page of the lastest questions\n axios.get('https://' + site + '/questions?sort=newest').then(rep => {\n // Load the HTML and get the ID of the first div with class .question-summary\n const $ = cheerio.load(rep.data);\n var question_summary = $(\".question-summary\")[0];\n var currentId = question_summary.attribs.id\n var summary = question_summary.children.find(c => c.attribs && c.attribs.class === \"summary\");\n var link = summary.children.find(c => c.name && c.name === \"h3\").children[0].attribs.href;\n\n var IDs = getIds();\n\n // If we have a new question update the IDs (in memory and on disk)\n // and send a notification\n if (currentId !== IDs[site]) {\n IDs[site] = currentId;\n setLastId(IDs);\n var message = \"New question on stackexchange \" + site + \" - \" + currentId;\n message += \"\\n\" + 'https://' + site + link;\n sendNotification(message);\n }\n });\n}",
"function getQuestion() {\n GS.hasGuessed = false;\n var questionButton = document.getElementById(\"reset-button\");\n questionButton.disabled = true;\n\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if(this.readyState == 4 && this.status == 200){\n var question = JSON.parse(this.response);\n document.getElementById(\"prompt-country\").innerHTML = question.Country; \n }\n }\n xhttp.open(\"GET\", \"/game/getQuestion\", true);\n xhttp.send();\n}",
"function getQData() {\r\n \tclient = new XMLHttpRequest();\r\n \tclient.open('GET','http://developer.cege.ucl.ac.uk:30273/getData');\r\n \tclient.onreadystatechange = DataResponse;\r\n \tclient.send();\r\n }",
"function seeCustomerRequestMade(){\n\tvar url='http://localhost:7070/Grabhouse/rest/api/pollRequest';\n\tmakeAjaxCalls(url,requestDoneHandler);\n}",
"function retrieveQuestion() {\r\n\t\t$.ajax({\r\n\t\t\ttype: 'GET',\r\n\t\t\turl: url + '/question',\r\n\t\t\tcontentType: 'application/json',\r\n\t\t\tdataType: 'json',\r\n\t\t\tdata:\tquestion,\r\n\t\t\tsuccess: function(question) {\r\n\t\t\t\tsocket.emit('get question id', question);\r\n\t\t\t\tsocket.emit('game start', question);\r\n\t\t\t},\r\n\t\t\tfail: function() {\r\n\t\t\t\talert('failed to retrieve question');\r\n\t\t\t}\r\n\t\t});\r\n\t}",
"surveyQuestion (request) {\n return this._dashboardRequest('get', '/api/survey-questions/' + request.questionId, request)\n }",
"function checkForPlaydateRequest() {\n\t\n\t$.getJSON(\n\t\t\"/playdate_requested\", \t\t\n\t\tfunction(data) {\n\t\t\tif (data) {\n\t\t\t\tshowPlaydateRequest(data);\n\t\t\t\t//join private playdate\n\t\t\t\tplaydateChannel = pusher.subscribe($('#pusher-channel-name').html());\n\t\t\t\tlistenForEndPlaydate();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlistenForPlaydateRequest();\n\t\t\t}\n\t\t}\n\t);\n\t\t\t\n}",
"function requestGetUnique_CompletedByDate(query, callback) {\n\n//\tvar url = hostUnique + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_region, slotValue_content, slotValue_date, slotValue_solution); \n\n//\tvar url = hostUnique_byDate + format.queryToURLForm(slotValue_name, slotValue_country, slotValue_region, slotValue_content, slotValue_date); \n\n\tvar url = hostUnique_CompletedByDate + query; \n\n request(url, function(error, response, body) { \n\n \tconsole.log(url); \n console.log('error: ', error); \n console.log('statusCode: ', response && response.statusCode); \n console.log('body: ', body); \n callback(JSON.parse(body)); \n\n }); \n\n\n}",
"function getReadyRequestOfBpHist(){\n\t /* To show the progress bar */\n\t showProgressBar();\n\t var request = {};\n\t var endDate = \"\";\n\t var startRow = \"\";\n\t /* we are getting maxBillPayHistoryDaysBack from the localStorage which is coming from INIT_APP */\n\t var daysBack = localStorage.getItem(\"maxBillPayHistoryDaysBack\");\n\t var today = new Date();\n\t var past = new Date();\n\t past.setDate(today.getDate() - daysBack);/* get the bills for the last 30 days(daysBack) */\n\t startDate = past.valueOf();\n\t request.userId = getCookie(\"userId\");\n\t request.count = localStorage.getItem(\"count\");\n\t request.startRow = startRow;\n\t request.startDate = startDate;\n\t request.endDate = endDate;\n\t request.applicationId = applicationId;\n\t request.locale = getCookie(\"locale\");\n\n\t return request;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Record a guest's order in DOM and in memory, clear the current order, prep for next guest | function completeGuest () {
if (currentOrder.length > 0) {
$("#checkButton").show();
$("#orderButton").text("Click an item to start another order");
var items = $("#currentOrder").children().clone();
$("#totalOrder,.guestOrder").append(items);
$("#currentOrder h2").remove();
$("#totalOrder h3").last().remove();
guest += 1;
order.push(currentOrder);
currentOrder = [];
$("#currentOrder h3").text("Guest" + guest);
};
} | [
"function resetActiveOrder () {\n activeOrder = {};\n}",
"function saveAndPrintOrderList() {\n orders.push(currentOrder);\n\n // Reset current order numbers\n currentOrderNumber = 1;\n for (var i=0; i<orders.length; i++) {\n currentOrder = orders[i];\n printCurrentOrder();\n currentOrderNumber++;\n }\n}",
"function prepOrder() {\n\tlet d = new Date();\n\tlet myDate = (d.getDate() < 10 ? '0' : '') + d.getDate();\n\tlet myMonth = (d.getMonth() < 10 ? '0' : '') + (d.getMonth() + 1);\n\tlet myYear = d.getFullYear();\n\tstore.currID += 1;\n\t\n\t//update global vars\n\tlet fulldate = myMonth+'/'+myDate+'/'+myYear;\n\tlet newOrder = [store.currID, fulldate, store.currDingusQuantity, store.currWidgetQuantity];\n\tstore.orderHistory.push(newOrder);\n\t\n\tclearForm();\n\tfillTable([newOrder]);\n\tpreserveTable();\n}",
"function prepOrder() {\n\tlet d = new Date();\n\tlet myDate = (d.getDate() < 10 ? '0' : '') + d.getDate();\n\tlet myMonth = (d.getMonth() < 10 ? '0' : '') + (d.getMonth() + 1);\n\tlet myYear = d.getFullYear();\n\tstore.currID += 1;\n\t\n\n\t//update global vars\n\tlet fulldate = myMonth+'/'+myDate+'/'+myYear;\n\tlet newOrder = [store.currID, fulldate, store.currDingusQuantity, store.currWidgetQuantity];\n\tstore.orderHistory.push(newOrder);\n\t\n\tclearForm();\n\tfillTable([newOrder]);\n\tpreserveTable();\n}",
"function rebuildGuests() {\n var guest = document.getElementById(\"guests\");\n\n if(guests.hasChildNodes())\n while (guests.childNodes.length > 0)\n guests.removeChild(guests.firstChild);\n buildGuests();\n}",
"function prepOrder() {\r\n\tlet d = new Date();\r\n\tlet myDate = (d.getDate() < 10 ? '0' : '') + d.getDate();\r\n\tlet myMonth = (d.getMonth() < 10 ? '0' : '') + (d.getMonth() + 1);\r\n\tlet myYear = d.getFullYear();\r\n\tstore.currID += 1;\r\n\tlet newOrder = [store.currID, myMonth+'/'+myDate+'/'+myYear, store.currDingusQuantity, store.currWidgetQuantity];\r\n\tstore.orderHistory.push(newOrder);\r\n\tclearForm();\r\n\tfillTable([newOrder]);\r\n\tpreserveTable();\r\n}",
"function clearLocalStorageOrder() {\n localStorage.setItem(\"orn:order\", \"[]\");\n}",
"function createOrder(unit, quantity) { // on submit, multiple times if multiple units increased\n var newOrder = new Object();\n newOrder.itemType = sessionStorage.getItem(\"itemType\"); // from previous page\n newOrder.unit = unit;\n newOrder.quantity = quantity;\n newOrder.description = document.getElementById(\"description\").value;\n\n if (sessionStorage.items) { // if orders list exists, parse it\n orders = JSON.parse(sessionStorage.getItem('items'));\n } else {\n orders = []; // if orders list doesn't exist, create it\n }\n orders.push(newOrder); // push new order to list\n sessionStorage.setItem('items', JSON.stringify(orders)); // reset new list in sessionstorage\n}",
"function clearOrdersDOM() {\n showDomRow(ui.ordDomPriceBid1, ui.ordBid1, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceBid2, ui.ordBid2, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceBid3, ui.ordBid3, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceBid4, ui.ordBid4, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceBid5, ui.ordBid5, 0, null, \"LightGrey\", null);\n\n showDomRow(ui.ordDomPriceAsk1, ui.ordAsk1, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceAsk2, ui.ordAsk2, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceAsk3, ui.ordAsk3, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceAsk4, ui.ordAsk4, 0, null, \"LightGrey\", null);\n showDomRow(ui.ordDomPriceAsk5, ui.ordAsk5, 0, null, \"LightGrey\", null);\n}",
"function resetOrders() {\n this.each(function (graph, index) {\n graph.set('order', index, {silent: true});\n });\n }",
"function renderOrder(order){\n // EXAMPLE of order:\n // namn: \"\",\n // namn2: \"\",\n // transaction_id: \"4086\",\n // user_id: \"2\",\n // beer_id: \"2259\",\n // timestamp: \"2017-03-06 15:54:19\",\n // price: \"100.00\",\n // first_name: \"Jory\",\n // last_name: \"Assies\",\n // username: \"jorass\"\n //create new div for the order list item\n var orderDiv = document.createElement('div');\n orderDiv.className=\"order-item\";\n //set transaction id to attribute of order item\n // so that we can access more info by clicking on it later\n orderDiv.setAttribute(\"data-order-id\",order.transaction_id);\n\n //creating subdiv for the list item\n //get the name of the customer\n var nameDiv = document.createElement('div');\n nameDiv.className = \"order-item-customer-name\";\n nameDiv.innerHTML = order.first_name + \" \" + order.last_name + \" [\" + order.username + \"]\";\n //add to div\n orderDiv.appendChild(nameDiv);\n\n //get name of the beer\n var beerDiv = document.createElement('div');\n beerDiv.className = \"order-item-drink-name\";\n beerDiv.innerHTML = order.namn;\n if(order.namn2 != \"\") {\n beerDiv.innerHTML += \" <br> \" + order.namn2;\n beerDiv.style.lineHeight = \"15px\";\n beerDiv.style.padding = \"5px 0 0 0\"\n }\n //add to div\n orderDiv.appendChild(beerDiv);\n\n //get time of order\n var timeDiv = document.createElement('div');\n timeDiv.className = \"order-item-time\";\n timeDiv.innerHTML = order.timestamp;\n //add to div\n orderDiv.appendChild(timeDiv);\n\n //get price of order\n var priceDiv = document.createElement('div');\n priceDiv.className = \"order-item-price\";\n priceDiv.innerHTML = order.price + \":-\";\n //add to div\n orderDiv.appendChild(priceDiv);\n\n document.getElementsByClassName(\"orders-grid\")[0].appendChild(orderDiv);\n}",
"function processOrder() {\r\n var cur_order = [];\r\n for(var i =0; i < 5; i++) {\r\n cur_order[i] = localStorage.getItem(i);\r\n localStorage.removeItem(i);\r\n }\r\n var orderString = cur_order.join('|');\r\n var pre_cookie = getPreviousOrder(orderName);\r\n if (pre_cookie === null) {\r\n addToOrders(orderName+\"_order\", [orderString].join(\",\"));\r\n } else {\r\n var pre_orders = pre_cookie.split(\",\");\r\n pre_orders[pre_orders.length] = orderString;\r\n pre_order = pre_orders.join(\",\");\r\n addToOrders(orderName+\"_order\", pre_order);\r\n }\r\n printTheOrder(cur_order, false);\r\n}",
"function prepareOrder(){\r\n\tappendElement(\"addressDiv\",\"INPUT\",false,\"destinationValidator\");\r\n\tappendElement(\"addressDiv\",\"INPUT\",false,\"pickupValidator\");\t\r\n}",
"_setOrder(item) {\n this._events.forEach((event, index) => {\n if (event.order > 0) {\n this.set(['_events', index, 'order'], event.order - 1);\n }\n });\n\n this.set(['_events', this._events.indexOf(item), 'order'], this._events.length);\n }",
"function createGuestOrder(req, res, next) {\n\n\t// Insert guest order, pulling all fields from request with null userId\n\tmodels.order\n\t\t.create({\n\t\t\tuserId: null,\n\t\t\tdateStamp: res.now.dateStamp,\n\t\t\trestaurantId: parseInt(req.body.restaurantId || \"0\", 10),\n\t\t\titem: (req.body.item || \"\").trim(),\n\t\t\tnotes: (req.body.notes || \"\").trim(),\n\t\t\tfirstName: (req.body.firstName || \"\").trim(),\n\t\t\tlastName: (req.body.lastName || \"\").trim(),\n\t\t\temail: (req.body.email || \"\").trim()\n\t\t})\n\t\t.then(function(order) {\n\n\t\t\t// Return created order\n\t\t\tres.send(order);\n\t\t});\n}",
"function resetOrderList () {\n orderList = [];\n}",
"function order(id, order) {\n id = parseInt(id);\n log.info(\"TURTLES - Reorder #\"+ id + \" (order: \"+ order +\")\");\n if (instances[id] == null){\n log.error(\"TURTLES - Unknown instance: #\" + id);\n return;\n }\n\n var turtle = instances[id];\n\n // change order attribute\n turtle.el.attr(\"data-order\", parseInt(order));\n\n // sort turtles in this group\n sort(turtle.el.parent().find(\".turtle\"));\n }",
"toggleOrder() {\n this.order = this.order === 'asc' ? 'desc' : 'asc';\n this.orderList();\n this.paintList();\n }",
"function storeOrder(orders) {\n localStorage.setItem('order',JSON.stringify(orders));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pull user can define a specific pool. if he defines 0 then all pools _places user can define a specific places in a pool. if 0 all places | function depositWithNodes(uint _pull, uint _places) external payable {
deposit();
if (_pull == 0 && _places == 0) {
return;
}
changePool(_pull, _places);
} | [
"function poolClickHandler(e) {\n let elm = $(e.target);\n\n if (elm.hasClass('deletePool')) {\n let name = elm.first().prev().text();\n let data = {name: name};\n log('/leavePool', name);\n $.post('/leavePool', data);\n elm.parent().remove();\n if ($('.pool').length == 0) {\n $('#poolGraph').hide();\n $('#poolInfo').hide();\n showEmptyMessage(false);\n } else {\n $('.pool').first().click();\n }\n return;\n }\n\n if (elm.hasClass('portName')) {\n elm = elm.parent();\n }\n\n\n // If already active we don't need to update\n if (elm.hasClass(\"active\")) {\n return;\n }\n\n if(poolGraph.graph) {\n poolGraph.graph.clear();\n }\n\n let name = elm.children('.portName')[0].innerText;\n let poolId = elm.attr('poolId');\n\n // Set pool id in info section\n $('#poolId').text(poolId);\n poolGraph.update(name, poolId);\n\n // Remove active from old\n \t$('.pool').removeClass('active');\n // Add active to new\n elm.addClass('active');\n // Remove old stocks\n $('#stocks').empty();\n // Get stocks for new pool portfolio\n getStocks(getCurrentPort());\n\n let data = { poolId: poolId };\n // Get leaderboard for pool\n log('/getLeaderboard', data);\n $.post('/getLeaderboard', data, (res) => {\n let data = JSON.parse(res);\n $leaderboard = $('#leaderboard')\n // Remove old leaderboard\n $('.position').remove();\n\n // Save last balance & place for when you have a tie\n let lastBalance = -1;\n let lastPlace;\n // Loop over each person in leaderboard\n for (var i = 0; i < data.length; i++) {\n let pic = data[i].pic;\n let name = data[i].user;\n let balance = Math.round(data[i].balance);\n let id = data[i].userId;\n let place;\n // Check for tie\n if (lastBalance == balance) {\n place = lastPlace;\n } else {\n place = i+1;\n }\n lastPlace = place;\n lastBalance = balance;\n // Add new person to leaderboard\n $leaderboard.append(`<li id=\"user${id}\" class='position list-group-item'>\n <img class=\"leaderPic rounded\" src='${pic}?sz=35'>\n <div>\n <div class=\"fullWidth\">${place}. <a href=\"/user/${id}\">${name}</a></div>\n <div><p class=\"balance\">$${balance}</p><div>\n <div>\n </li>`);\n getPoolInfo(getCurrentPort(), poolId);\n }\n });\n}",
"async createOrEditPool(options) {\n let type = options.type || options.algo;\n let getTime = await this.getTime();\n let body = {\n algorithm: type.toUpperCase(),\n name: options.name,\n username: options.user,\n password: options.pass,\n stratumHostname: options.host,\n stratumPort: options.port,\n id: options.id || '' //Pool id (Required only if editing pool data)\n\n };\n\n try {\n let response = await this.post('/main/api/v2/pool', {\n body\n });\n response.success = true;\n return response;\n } catch (e) {\n return {\n error: e.error\n };\n }\n }",
"choosePools (requiredBytes, mustNodes, shouldNodes) {\n let pools = this.getPool().filter((p) => {\n return (\n p.isAccessible() &&\n p.capacity - p.used >= requiredBytes &&\n (mustNodes.length === 0 || mustNodes.indexOf(p.node.name) >= 0)\n );\n });\n\n pools.sort((a, b) => {\n // Rule #1: User preference\n if (shouldNodes.length > 0) {\n if (\n shouldNodes.indexOf(a.node.name) >= 0 &&\n shouldNodes.indexOf(b.node.name) < 0\n ) {\n return -1;\n } else if (\n shouldNodes.indexOf(a.node.name) < 0 &&\n shouldNodes.indexOf(b.node.name) >= 0\n ) {\n return 1;\n }\n }\n\n // Rule #2: Avoid degraded pools whenever possible\n if (a.state === 'POOL_ONLINE' && b.state !== 'POOL_ONLINE') {\n return -1;\n } else if (a.state !== 'POOL_ONLINE' && b.state === 'POOL_ONLINE') {\n return 1;\n }\n\n // Rule #3: Use the least busy pool (with fewer replicas)\n if (a.replicas.length < b.replicas.length) {\n return -1;\n } else if (a.replicas.length > b.replicas.length) {\n return 1;\n }\n\n // Rule #4: Pools with more free space take precedence\n const aFree = a.capacity - a.used;\n const bFree = b.capacity - b.used;\n return bFree - aFree;\n });\n\n // only one pool from each node\n const nodes = [];\n pools = pools.filter((p) => {\n if (nodes.indexOf(p.node) < 0) {\n nodes.push(p.node);\n return true;\n } else {\n return false;\n }\n });\n\n return pools;\n }",
"function isPoolAccessible(pool) {\n return pool.state == 'ONLINE' || pool.state == 'DEGRADED';\n}",
"_updatePool(_pid, _pendingToken) {\n let pool = this._verifyPool(_pid)\n if (Blockchain.block.height <= pool.lastRewardBlock) {\n return\n }\n let lpSupply = this._balanceOf(pool.lpToken, this.config.poolProxy)\n if (new BigNumber(lpSupply).gt(0) && new BigNumber(_pendingToken).gt(0)) {\n let reward = new BigNumber(_pendingToken).times(pool.allocPoint).div(this._totalAllocPoint)\n pool.totalReward = new BigNumber(pool.totalReward).add(reward).toFixed(0, BigNumber.ROUND_DOWN)\n if (Blockchain.block.height > pool.lastRewardBlock) {\n pool.rewardPerBlock = new BigNumber(reward).div(Blockchain.block.height - pool.lastRewardBlock).toFixed(0, BigNumber.ROUND_DOWN)\n }\n pool.accPerShare = new BigNumber(pool.accPerShare).add(new BigNumber(reward).times(AccumulatedMultiple).div(lpSupply)).toFixed(0, BigNumber.ROUND_DOWN)\n }\n pool.lastRewardBlock = Blockchain.block.height\n this._poolInfo.setData(_pid, pool)\n }",
"function getPool(poolID) {\n\tfor (var i = 0; i < AFRL.pools.length; i++) {\n\t\tif (AFRL.pools[i].id == poolID) {\n\t\t\treturn AFRL.pools[i];\n\t\t}\n\t}\n}",
"initPool() {\n this.pool = [];\n for (let choice of this.choices) {\n for (let i = 0; i < choice[1].totalNumber; i++) this.pool.push(choice[0])\n }\n }",
"function Get(name : String) : BreedPool\n\t{\n\t\tfor ( var i : int = 0; i < pools.Length; i++ )\n\t\t{\n\t\t\tif ( (pools[i] as BreedPool).name == name )\n\t\t\t\treturn pools[i];\n\t\t}\n\t\treturn null;\n\t}",
"get pools() {\n return this.list()\n }",
"function getPoolAddress () {\n return config.networks[buidlerArguments.network].deployedContracts.pool\n}",
"checkPool(pool) {\n return pool ? true : false;\n }",
"function boidInitFn(boidPool, bounds, otherBoidPool) {\n boidPool.map(boid => {\n boid.position.x = (Math.random() - 0.5) * 120 + (bounds.width / 4);\n boid.position.y = (bounds.height / 2) * Math.random() + bounds.height / 4;\n })\n\n let points = [\n {position: {x: bounds.width / 5 * 0, y: bounds.height / 2}, step: _ => {}, isDone: false},\n {position: {x: bounds.width / 2, y: bounds.height / 2}, step: _ => {}, isDone: false},\n {position: {x: bounds.width / 5 * 5, y: bounds.height / 2}, step: _ => {}, isDone: false},\n {position: {x: bounds.width / 2, y: bounds.height / 2}, step: _ => {}, isDone: false},\n ]\n otherBoidPool.push(...points);\n}",
"updatePool(winner, winMove, lossMove) {\r\n if (winner === 'computer') {\r\n this.pool.push(winMove);\r\n } else if (winner === 'human') {\r\n if (this.pool.filter(ele => ele === lossMove).length > 1) {\r\n this.pool.splice(this.pool.indexOf(lossMove), 1);\r\n }\r\n }\r\n }",
"function Pool () \n{\n if (parentPool) parentPool.PoolObject(gameObject);\n else \n Debug.Log (\"parentPool is missing in SimplePoolObject component of \" + gameObject.name);\n}",
"function setBoundries() {\n var deferred = $q.defer();\n _.each(stateConfig.tools.map.supportingLayers, function (b) {\n if (b.admin_level || b.admin_level === 0) {\n switch (b.admin_level) {\n case 0:\n service.boundaries.admin0[b.function] = b;\n break;\n case 1:\n service.boundaries.admin1[b.function] = b;\n break;\n case 2:\n service.boundaries.admin2[b.function] = b;\n break;\n case 3:\n service.boundaries.admin3[b.function] = b;\n break;\n }\n service.boundaries.aliases[b.function].push(b.alias);\n }\n });\n deferred.resolve();\n return deferred.promise;\n }",
"function togglePool(e){\r\n\t\t\r\n\t\tvar id = $(e).attr('data-vsid');\r\n\t\t\r\n\t\t//Store the current window selection\r\n\t\tvar selection = window.getSelection();\r\n\t\t\r\n\t\t//If no text is selected, go ahead and expand or collapse the pool\r\n\t\tif(selection.type != \"Range\") {\r\n\t\t\tif($(\"#PoolInformation-\" + id).is(\":visible\")){\r\n\t\t\t\t$('#AssociatedPoolsInfo-' + id).show();\r\n\t\t\t\t$('#expand-' + id).show();\r\n\t\t\t\t$('#collapse-' + id).hide();\r\n\t\t\t\t$('#PoolInformation-' + id).hide();\r\n\t\t\t} else {\r\n\t\t\t\t$('#AssociatedPoolsInfo-' + id).hide();\r\n\t\t\t\t$('#expand-' + id).hide();\r\n\t\t\t\t$('#collapse-' + id).show();\r\n\t\t\t\t$('#PoolInformation-' + id).fadeIn(300);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}",
"function establishPool() {\n\n odb.createPool( processPool );\n\n}",
"function buildPools(data) {\n for (var i = 0; i < Number(data.pools); i++) {\n let pool = new Object();\n pool.name = 'Pool ' + (String.fromCharCode(65 + i));\n pool.teams = [];\n pool.games = [];\n pools.push(pool);\n }\n buildTeams(data);\n}",
"async function postToPool() {\n let userPicks = {\n uid: user.uid,\n userName: user.name,\n driver1: bracket.driver1,\n driver2: bracket.driver2,\n };\n // console.log(\"userPicks\", userPicks);\n axios\n .put(`http://localhost:5000/pools/${nextEvent.raceID}`, userPicks)\n .then((res) => {\n console.log(\"picks placed to pool\", res.data.brackets);\n })\n .catch(function (error) {\n console.log(error);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Step 3: when the add news button is clicked, set the state of addNews to true and display the component declared below | addNewsClick(){
this.setState({
addNews: true,
})
} | [
"render(){\n let addNews=\"\"\n if(this.state.addNews === true){\n addNews = <AddEditNews\n handleFieldChange={this.handleFieldChange}\n editNews={this.state.editNews}closeModal={this.closeModal}\n addNews={this.state.addNews} editArticleChanges={this.editArticleChanges} addNewArticle={this.addNewArticle}\n articleName={this.state.articleName} about={this.state.about} articleImage={this.state.articleImage} url={this.state.url} articleId={this.state.articleId} warningMessage={this.state.warningMessage} warningMessageAbout={this.state.warningMessageAbout} warningMessageImg={this.state.warningMessageImg} warningMessageURL={this.state.warningMessageURL}/>\n }\n return(\n <React.Fragment>\n <section className=\"container\">\n <div className=\"field is-grouped is-grouped-centered\">\n <h2 className=\"is-size-4\"><strong>News </strong></h2>\n <button className=\"button is-link\" onClick={()=>{\n this.addNewsClick()\n }}>+</button>\n </div>\n <div className=\"columns is-multiline\">\n <News showNews={this.state.showNews} showNewsClick={this.showNewsClick}\n addNews={this.state.addNews} handleFieldChange={this.handleFieldChange}\n news={this.state.news} editNews={this.state.editNews} articleName={this.state.articleName} about={this.state.about} articleImage={this.state.articleImage} url={this.state.url} closeModal={this.closeModal} editNewsClick={this.editNewsClick} editArticleChanges={this.editArticleChanges} addNewArticle ={this.addNewArticle} articleId={this.state.articleId} deleteArticle={this.deleteArticle} deleteNewsClick={this.deleteNewsClick} deleteNews={this.state.deleteNews} warningMessage={this.state.warningMessage} warningMessageAbout={this.state.warningMessageAbout} warningMessageImg={this.state.warningMessageImg} warningMessageURL={this.state.warningMessageURL} currentUserId={this.state.currentUserId} userId={this.state.userId} friends={this.props.friends} filteredFriends={this.state.filteredFriends}/>\n </div>\n </section>\n {addNews}\n </React.Fragment>\n )\n }",
"render(){\n let showNews = \"\"\n if(this.props.showNews === true){\n showNews= <NewsModule\n articleName={this.props.articleName} about={this.props.about} articleImage={this.props.articleImage} url={this.props.url} closeModal={this.props.closeModal} editNewsClick={this.props.editNewsClick} deleteArticle={this.props.deleteArticle} deleteNewsClick={this.props.deleteNewsClick} currentUserId={this.props.currentUserId} userId={this.props.userId}/>\n } else if(this.props.editNews === true){\n showNews= <AddEditNews\n handleFieldChange={this.props.handleFieldChange}\n editNews={this.props.editNews}closeModal={this.props.closeModal}\n addNews={this.props.addNews} editArticleChanges={this.props.editArticleChanges} addNewArticle={this.props.addNewArticle}\n articleName={this.props.articleName} about={this.props.about} articleImage={this.props.articleImage} url={this.props.url} articleId={this.props.articleId} warningMessage={this.props.warningMessage} warningMessageAbout={this.props.warningMessageAbout} warningMessageImg={this.props.warningMessageImg} warningMessageURL={this.props.warningMessageURL}/>\n } else if(this.props.deleteNews === true){\n showNews=<DeleteNews deleteArticle={this.props.deleteArticle} closeModal={this.props.closeModal}/>\n }\n\n return(\n <React.Fragment>\n {\n this.props.news.map((article, index)=>{\n return(\n <div className={this.createClass(index)}\n key={article.id} onClick={()=> this.props.showNewsClick(article.url, article.articleName, article.about, article.articleImage, article.id, article.userId)}>\n <div className=\"box\">\n <article className=\"media\">\n <figure className=\"media-left\">\n <p className=\"image is-64x64\">\n <img src={article.user.profilePic} alt=\"\" />\n </p>\n </figure>\n <div className=\"media-content\">\n <div className=\"content\">\n <p id=\"userInfo\" className=\"\">\n <strong>{article.user.firstName} {article.user.lastName}</strong> <small className={this.activeUserClass(article.userId)}>@{article.user.username}</small> <small className={this.activeUserClass(article.userId)}>{moment(`${article.dateSaved}`).fromNow()}</small>\n </p>\n <p className=\"\">{article.about}</p>\n </div>\n\n <article className=\"media\">\n <figure className=\"media-left\">\n <p className=\"image is-128x128\">\n <img src={article.articleImage} alt=\"\"/>\n </p>\n </figure>\n <div className=\"media-content\">\n <div className=\n {this.friendClassName(article.userId)}\n >\n <p>\n <strong>{article.articleName}</strong>\n </p>\n </div>\n </div>\n </article>\n </div>\n </article>\n </div>\n </div>\n\n )\n })\n }\n {showNews}\n </React.Fragment>\n )\n }",
"addNews(pTitle, pInfo, pDate, pCategory, pIsUrgent) {\n let newsObject = {\n title: pTitle,\n info: pInfo,\n date: pDate,\n category: pCategory,\n urgent: pIsUrgent,\n hasRead: false\n };\n this.events.push(newsObject);\n this.currentNews.push(newsObject);\n\n this.body.innerHTML += `<div class='ui-newsentry news-${pCategory}'>➤ [${pCategory.toUpperCase()}] ${pTitle}</div>`;\n\n }",
"newArticleListener() {\r\n let newArticleBtn = document.querySelector(\"button.article-button\")\r\n newArticleBtn.addEventListener(\"click\", () => {\r\n let newsCreator = new Form(\"Add Article\", \"news-editor\", newsInputs.articleInputs)\r\n let newsCreate = newsCreator.build()\r\n newsCreate.render(\".form-container\")\r\n newArticleBtn.classList.add(\"hide\")\r\n addNewArticle()\r\n })\r\n }",
"async renderNews() {\n this.addPageFunctionalities();\n const response = await this.controller.getTopNewsApi();\n let data = response.articles;\n this.createCards(data, \"Salvar\", (noticia) => {\n this.clickBotao(noticia);\n });\n }",
"mainNavNewsButtonAddEventListener() {\n const mainNavNewsBtn = document.getElementById(\"myNews\")\n\n mainNavNewsBtn.addEventListener(\"click\", () => {\n const mainContainer = document.getElementById(\"mainContainer\")\n mainContainer.innerHTML = \"\"\n domAdditionHandler.renderNewsContainers()\n\n domAdditionHandler.addArticlesToDOM()\n domAdditionHandler.renderFriendsNewsToDom()\n })\n }",
"addNew()\n {\n this.state.showAdd = 'true';\n this.state.showSearch = 'false';\n \n this.forceUpdate();\n }",
"showNews () {\n document.querySelector('#' + this.id + '-loader').classList.add('active')\n if (!document.querySelector('#' + this.id + '-extraContent').classList.contains('dimmer')) {\n document.querySelector('#' + this.id + '-extraContent').classList.add('dimmer')\n }\n Array.prototype.forEach.call(document.querySelectorAll('#' + this.id + '-newsDiv .card'), element => element.remove())\n this.channels.forEach(channel => {\n window.fetch(\n 'https://newsapi.org/v1/articles?source=' + channel + '&sortBy=top&apiKey=71f12b1d877b4b0882f1e2c2ce163a34'\n ).then(response => response.json())\n .then(response => {\n response.articles.forEach((article, index) => {\n setTimeout(() => {\n let news = this.cloneTemplate('#news')\n let element = news.firstElementChild\n element.firstElementChild.firstElementChild.setAttribute('src', article.urlToImage)\n element.children[1].firstElementChild.textContent = article.title\n element.children[1].lastElementChild.textContent = article.description\n element.children[1].children[1].firstElementChild.textContent = article.author\n element.children[1].children[1].lastElementChild.textContent = ('' + article.publishedAt).split('T')[0]\n if (element.children[1].children[1].lastElementChild.textContent === 'null') {\n element.children[1].children[1].lastElementChild.textContent = ''\n }\n element.onclick = () => window.open(article.url)\n document.querySelector('#' + this.id + '-newsDiv').appendChild(news)\n if (index === response.articles.length - 1) {\n document.querySelector('#' + this.id + '-loader').classList.remove('active')\n }\n }, 0)\n })\n }).catch(() => document.querySelector('#' + this.id + '-extraContent').classList.remove('dimmer'))\n })\n document.querySelector('#' + this.id + '-newsDiv').classList.remove('dimmer')\n document.querySelector('#' + this.id + '-settingsDiv').classList.add('ui', 'dimmer')\n }",
"function addNews(news) {\r\n const boardNews = document.querySelector('.board__news');\r\n \r\n // include the first five items of the input array\r\n // include the theme color as a solid border\r\n boardNews.innerHTML = news.slice().map(({ color, date, title }) => `\r\n <a class=\"news--item\" href=\"#\" style=\"border-left: 4px solid ${color}\">\r\n <p class=\"date\">\r\n ${date}\r\n </p>\r\n <p class=\"title\">\r\n ${title}\r\n </p>\r\n </a>\r\n `).join('');\r\n }",
"_collectNews() {\n this.api.getNews().then(data => {\n const newsContent = data.articles.map(obj => new NewsItem(obj, this.callbacks));\n this._setNewsButtonCounter(data.articles.length);\n newsContent.forEach(element => {\n this.newsContainer.append(element);\n });\n }).catch(err => console.error(err));\n }",
"async renderNews(){\n const response = await this.controller.getTopNewsApi();\n let data = response.articles\n this.createCards(data, \"Salvar\", (noticia) => {\n this.clickBotao(noticia);\n })\n }",
"function addNews(news) {\n var res = false;\n // if (isValid(news)){\n newsList.push(news);\n res = true;\n // }\n\n return res;\n}",
"function renderNews() {\n var url =\n \"https://newsapi.org/v2/top-headlines?\" +\n \"country=us&\" +\n \"apiKey=bb4227ec350a41dba251dadcd757dcae\";\n\n let widgetHeader = `\n <div class=\"grid-stack-item\" data-gs-x=\"0\" data-gs-y=\"4\" data-gs-width=\"5\" data-gs-height=\"4\" id=\"newsDiv\">\n <div class=\"grid-stack-item-content\">\n <div class=\"bor\">\n <div class=\"d-flex widget-header m-0 p-3 align-item-center\">\n <p class=\"m-0\"><b>Top US News</b></p>\n <span class=\"ml-auto newsClose\">✖️</span>\n </div>\n <div id=\"card-news\" class=\"innerDiv m-3\">\n `;\n let widgetFooter = `\n </div>\n </div>\n </div>\n </div>\n `;\n\n fetch(url)\n .then((response) => response.json())\n .then((json) => {\n // Render the top 3 US news stories to the <div id=\"card-news\"> element\n\n var numArticlesToRender = 3;\n var templateStr = ``;\n for (i = 0; i < numArticlesToRender; i++) {\n var arrNewsHeadline = json.articles[i].title.split(\" - \");\n var srcNewsHeadline = arrNewsHeadline.pop();\n var titleNewsHeadline = \"\".concat(arrNewsHeadline);\n let tempStr = `\n <div class=\"headline\">\n <a href=\"${json.articles[i].url}\" target=\"_blank\">${titleNewsHeadline}</a><br/>\n <span class=\"news-source\"><i>${srcNewsHeadline}</i></span>\n <br/> \n </div>\n `;\n templateStr += tempStr;\n }\n grid.addWidget(widgetHeader + templateStr + widgetFooter);\n });\n}",
"function NewsView () {\n return(\n <Canvas>\n <Container>\n <HeaderMain>\n <Header>FeatherCorp — All the News!</Header>\n </HeaderMain>\n \n <Header>In the Business of Doing Good</Header>\n <NewsBody>Congratulations to Kirpal Singh for being awarded the prestigious \"Outreach Community Partner of the Year\" last month. Kirpal, the VP of Community Relations at Feathercorp, is a consummate professional and we appreciate all his efforts to share our values and dedicate targeted resources to be a better civic partner.</NewsBody>\n <Header>Moving on Up</Header>\n <NewsBody>Cheryl Bautista has been tapped to head up our new Talent Retention division. Following extensive internal recruitment, she has already demonstrated the type of initiative that will be needed to overcome the built-in challenges of the position. \"Don’t forget the synergistic parallelism we’ll use to extend the dialogue,\" Bautista noted in her first department-wide video call. After numerous studies demonstrated the value of having employees remain active even after onboarding, exhaustive proposals lead to this revolutionary position. Real-time and historical reporting have already begun.</NewsBody>\n <Header>Welcome Aboard!</Header> \n <NewsBody>FeatherCorp welcomes Alexandra Brightley, Binh Nguyen, and Tyree Powers as this month's new hires. This brings us within spitting distance of our recruitment goals for Q3 in IT, Accounting and Operations. Pat Tortuga, VP of Engineering, had this to say regarding the new hires: \"Here at FeatherCorp, the get-it-done nature of our hires speaks for itself. We’re not afraid to run it up the flagpole or to get granular! And with this much design-driven mindshare, we don’t even need to run out the clock on our streamlined, cutting-edge skillsets.\"</NewsBody>\n </Container>\n </Canvas>\n ); \n }",
"_addCategory() {\r\n this.props.addCategory(this.text);\r\n this.setModalVisible(!this.state.modalVisible);\r\n }",
"function createNewsModule(newsSection, idNumb, title, imgLink, sourceLink) {\n let section, figure, img, figcaption, caption;\n section = document.createElement(\"div\");\n section.classList.add(\"minor-news\");\n section.id = `news${idNumb}`;\n\n figure = document.createElement(\"figure\");\n figure.addEventListener(\"click\", expandToggle);\n\n img = document.createElement(\"img\");\n img.src = imgLink;\n\n link = document.createElement(\"a\");\n link.classList.add(\"news-link\");\n link.id = `link${idNumb}`;\n link.innerHTML = \"SOURCE\";\n link.href = sourceLink;\n\n figure.appendChild(img);\n figure.innerHTML += title;\n\n section.appendChild(figure);\n\n document.getElementById(`new-section-${newsSection}`).appendChild(section);\n document.getElementById(`new-section-${newsSection}`).appendChild(link);\n console.log(\"z\");\n}",
"function readNewsClick() {\n\tconst defaultNewsObj= {\n\t\ttype : 'default',\n\t\tvalue: defaultSearch\n\t}\n\t$('.js_read_news').on('click', function () {\n\t\t$(this).closest('.js_newspaperImage').slideUp('fast');\n\t\t$('.js-grid-section').removeClass('remove-display');\n\t\theadlines.sendConfig(defaultNewsObj);\n\t});\n\treturn;\n}",
"function addNewsContainer(news, imgURL){\n\tn = $('<div\tclass=\"ne-news-container\">');\n\tn.data('title', news.headline);\n\tn.data('intro', news.intro);\n\tn.data('id', news.id);\n\tn.data('article', news.article);\n\tn.data('start', news.start_date);\n\tn.data('end', news.end_date);\n\tn.data('img-id', news.image_id);\n\tn.data('img-url', imgURL);\n\t$('#ne-list').prepend(n.append($('<div class=\"ne-container-title\">').text(news.headline)));\n\t$('#ne-list .ne-news-container').first().click();\n}",
"function NewsContainer (props) {\n return (\n <div className=\"news-container\">\n \n {props.news.map(localNews => <NewsArticle key={localNews.id} id={localNews.id} headline={localNews.headline} img={localNews.img} description={localNews.description} url={localNews.url}/>)}\n </div>\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates the SSN to 10 digit number | validateSSN(ssn) {
if (!this.isNumeric(ssn) || ssn.toString().length !== 10) {
return { numeric: false, error: "SSN can only be a 10 digit number" };
} else {
return { numeric: true, error: null };
}
} | [
"function SSNValidation(ssn) {\r\nvar matchArr = ssn.match(/^(\\d{3})-?\\d{2}-?\\d{4}$/);\r\nvar numDashes = ssn.split('-').length - 1;\r\nif (matchArr == null || numDashes == 1 || numDashes == 0) {\r\nalert('Invalid SSN. Must be 9 digits in the format (###-##-####).');\r\nmsg = \"does not appear to be valid\";\r\nreturn false;\r\n}\r\nelse \r\nif (parseInt(matchArr[1],10)==0) {\r\nalert(\"Invalid SSN: SSN's can't start with 000.\");\r\nreturn false;\r\n}\r\nreturn true;\r\n}",
"function checkSSN(value)\n{\n\tvar white_space = \" -+.\";\n\tvar ssc_string = \"\";\n\tvar check_char;\n\n\tif (value.length == 0)\n\t\treturn true;\n\n\t// check for sensitized data - four dots followed by 4 characters eg \"....3403\"\n\tif (isSensitized(value))\n\t\treturn true;\n\n\t// if SSN in xxx-xx-xxxx format\n\tif (value.length == 11)\n\t{\n\t\t// make sure white space is valid\n\t\tif (value.charAt(3) != \"-\" && value.charAt(3) != \" \")\n\t\t\treturn false;\n\n\t\tif (value.charAt(6) != \"-\" && value.charAt(6) != \" \")\n\t\t\treturn false;\n\n\t\t// squish out the white space\n\t\tfor (var i = 0; i < value.length; i++)\n\t\t{\n\t\t\tcheck_char = white_space.indexOf(value.charAt(i));\n\t\t\tif (check_char < 0)\n\t\t\t\tssc_string += value.substring(i, (i + 1));\n\t\t}\n\n\t\t// if all white space return error\n\t\tif (ssc_string.length != 9)\n\t\t\treturn false;\n\t}\n\t// if SSN in xxxxxxxxx format\n\telse\n\tif (value.length == 9)\n\t\tssc_string = value;\n\t// Does not support any other format\n\telse\n\t\treturn false;\n\n\t// make sure number is a valid integer\n\tif (!checkAllDigits(ssc_string))\n\t\treturn false;\n\n\t// Make sure it matches the regex pattern\n\tvar validRegex1 = /^([1-7]\\d{2}|(?:(?!000)\\d{3}))([ |-]?)(?:(?!00)\\d{2})([ |-]?)(?:(?!0000)\\d{4})$/;\n\tvar invalidRegex1 = /^111([ |-]?)11([ |-]?)1111|222([ |-]?)22([ |-]?)2222|333([ |-]?)33([ |-]?)3333|444([ |-]?)44([ |-]?)4444|555([ |-]?)55([ |-]?)5555|666([ |-]?)66([ |-]?)6666|777([ |-]?)77([ |-]?)7777$/;\n\tvar invalidRegex2 = /^123([ |-]?)45([ |-]?)6789$/;\n\tvar invalidRegex3 = /^[89]\\d{2}([ |-]?)\\d{2}([ |-]?)\\d{4}$/;\n\n\tif (invalidRegex1.test(ssc_string) ||\n\t\t\tinvalidRegex2.test(ssc_string) ||\n\t\t\tinvalidRegex3.test(ssc_string))\n\t\treturn false;\n\n\tif (!validRegex1.test(ssc_string))\n\t\treturn false;\n\n\treturn true;\n}",
"function isValidSSN(value) {\n if (value === '123456789' || value === '123-45-6789') {\n return false;\n } else if (/1{9}|2{9}|3{9}|4{9}|5{9}|6{9}|7{9}|8{9}|9{9}/.test(value)) {\n return false;\n } else if (/^0{3}-?\\d{2}-?\\d{4}$/.test(value)) {\n return false;\n } else if (/^\\d{3}-?0{2}-?\\d{4}$/.test(value)) {\n return false;\n } else if (/^\\d{3}-?\\d{2}-?0{4}$/.test(value)) {\n return false;\n }\n\n for (let i = 1; i < 10; i++) {\n const sameDigitRegex = new RegExp(`${i}{3}-?${i}{2}-?${i}{4}`);\n if (sameDigitRegex.test(value)) {\n return false;\n }\n }\n\n return /^\\d{3}-?\\d{2}-?\\d{4}$/.test(value);\n}",
"function ValidateSSN(ssn) {\n if((ssn.length == 11) || (ssn.length == 9)) { // Make sure it's a valid length\n var segments = ssn.split(\"-\") // Split the number into segments delimited by '-'\n if ((segments.length == 3)) {\n\t\t\tif ((segments[0].length == 3) && (segments[1].length == 2) && (segments[2].length == 4)) {\n\t\t\t\tfor (var i = 0; i < 3; i++) {\n\t\t\t\t\tif (isNaN(segments[i])) // Check to see if the number is a valid number\n\t\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n }\n else {\n if ((segments.length == 1) && (!isNaN(ssn))) // Check to see if the number is a valid number\n return true;\n }\n }\n return false;\n}",
"function validate_ssno(ssno) {\n if (ssno.length == 9 && /^[0-9]+$/i.test(ssno)) return;\n else return false;\n}",
"function isValidSSN(value) {\n if (value === '123456789' || value === '123-45-6789') {\n return false;\n } else if (/^0{3}-?\\d{2}-?\\d{4}$/.test(value)) {\n return false;\n } else if (/^\\d{3}-?0{2}-?\\d{4}$/.test(value)) {\n return false;\n } else if (/^\\d{3}-?\\d{2}-?0{4}$/.test(value)) {\n return false;\n }\n\n var noBadSameDigitNumber = (0, _range3.default)(0, 10).every(function (i) {\n var sameDigitRegex = new RegExp(i + '{3}-?' + i + '{2}-?' + i + '{4}');\n return !sameDigitRegex.test(value);\n });\n\n if (!noBadSameDigitNumber) {\n return false;\n }\n\n return (/^\\d{9}$/.test(value) || /^\\d{3}-\\d{2}-\\d{4}$/.test(value)\n );\n}",
"validateSSN() {\n var ssnregex = /^\\d{3}-?\\d{2}-?\\d{4}|XXX-XX-XXXX$/;\n var match = this.state.ssn.match(ssnregex);\n if (!match){\n //notification that pops up\n this.dropdown.alertWithType(\n 'error',\n '\\nError',\n 'Invalid SSN input. \\nFormat should be: XXX-XX-XXXX\\n');\n return false;\n }\n return true;\n }",
"function CheckSSNValidLength(source, args) {\n if (!args || !args.IsValid || args.Value.length == 0) {\n return;\n }\n\n var validChars = args.Value.replace(/-/g, '').replace(/ /g, '');\n\n if (validChars.length > 9) {\n args.IsValid = false;\n }\n}",
"function chkSSN(inSSN){\n\tvar ssnRegEx = /^\\d{3}-?\\d{2}-?\\d{4}$/;\n\tvar errorString = \"Please provide a valid social security number. For example 123-45-6789.\";\n\t\n\tif(inSSN.length == 0){\n\t\treturn true;\n\t}else{\n\t\tif(ssnRegEx.test(inSSN) !== true){\n\t\t\treturn errorString;\n\t\t}else{\n\t\t\treturn true;\n\t\t}\n\t}\n}",
"function isValidSerial(sn){\n\n}",
"function isSSN (s)\r\n{ if (isEmpty(s))\r\n if (isSSN.arguments.length == 1) return defaultEmptyOK;\r\n else return (isSSN.arguments[1] == true);\r\n return (isInteger(s) && s.length == digitsInSocialSecurityNumber)\r\n}",
"function validateSSNfield( element ) \n{\n\tvar labelList = new Array();\n\tvar errorMessage = \"\";\n\tvar errorText = \"\";\n\t\n\tif (isblank(getCorrectAttribute(element,\"value\",element.value))) {\n\t\treturn true;\n\t} else {\n\n\t\tif (checkSSN(getCorrectAttribute(element,\"value\",element.value)))\t{\n\n\n\n\t\t} else { //\telse it false validation and you need to tell the user what went wrong\n\t\t\t //\tcheck if there already is an error msg there\n\t\t\terrorText = makeErrorMsg('ERR007', labelList.concat(getCorrectAttribute(element,\"fieldLabel\",element.fieldLabel)));\n\t\t\t// errorText = (\"Please enter a valid SSN using this format: '000-00-0000'.\");\n\n\t\t\tsetText(tdErrorCell, errorText);\n\t\t\t\n\t\t\treturn false;\n\t\t}\n\t}\n}",
"function socialSecurityNumberValid(ssn) {\n\tssn = ssn.toUpperCase();\n\tvar checkSymbolArray = \"0123456789ABCDEFHJKLMNPRSTUVWXY\";\n\t\n\t// wrong length\n\tif(ssn.length != 11) {\n\t\treturn false;\n\t}\n\n\t// Finnish social security number is of format ddmmyyNxxxS, in which ddmmyy is birthday, N separator character, \n\t// xxx individual number and S checking symbol.\n\tvar separator = ssn.charAt(6);\n\n\t// - for those born in 20th century and A for those born in 21st\n\tif((separator == '-') || (separator == 'A')) {\n\t\tssnWithoutSeparatorAndCheck = ssn.substring(0, 6) + ssn.substring(7, ssn.length-1);\n\t} else {\n\t\treturn false;\n\t}\n\n\t// Must contain only numbers\n\tfor (var counter = 0; counter < ssnWithoutSeparatorAndCheck.length; counter++) { \n\t\tif ((ssnWithoutSeparatorAndCheck.charAt(counter) < '0') || (ssnWithoutSeparatorAndCheck.charAt(counter)>'9')) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// check symbol is calculated by treating everything else as a 9-digit number and taking a modulo 31\n\tvar numberToDivide = Number(ssnWithoutSeparatorAndCheck);\n\tvar checkSymbol = ssn.charAt(ssn.length-1);\n\tvar mod31= numberToDivide % 31;\n\n\tif(checkSymbol != checkSymbolArray.charAt(mod31)){\n\t\treturn false;\n\t} else {\n\t\treturn true;\n\t}\n}",
"function isSSN(pString)\n{\n // Establish a pattern: 3 digits, a dash, 2 digits, a dash, and 4 digits.\n var varPattern = /^\\d{3}-\\d{2}-\\d{4}$/;\n // Perform a regular expression match.\n var varMatch = pString.match(varPattern);\n if(varMatch == null)\n {\n // The match failed.\n // The string is not an SSN.\n return false;\n }\n // The match succeeded.\n // The string is an SSN.\n return true;\n}",
"function checkSSN (theField, emptyOK)\r\n{ if (checkSSN.arguments.length == 1) emptyOK = defaultEmptyOK;\r\n if ((emptyOK == true) && (isEmpty(theField.value))) return true;\r\n else\r\n { var normalizedSSN = stripCharsInBag(theField.value, SSNDelimiters)\r\n if (!isSSN(normalizedSSN, false))\r\n return warnInvalid (theField, iSSN);\r\n else\r\n { // if you don't want to reformats as 123-456-7890, comment next line out\r\n theField.value = reformatSSN(normalizedSSN)\r\n return true;\r\n }\r\n }\r\n}",
"function validatePincode(pincode)\n{\n /* should be at 6 digits */\n var result=(pincode!=null) && (pincode.length >= 6) && (pincode.match(\"^[0-9]*$\")!=null);\n if (result == false) displayMsg(\"Epincode\");\n return result;\n}",
"function validateNRIC(nric) {\n if(nric.length == 9 && nric.charAt(0).toLowerCase() == \"s\" && /^[a-zA-Z]+$/.test(nric.charAt(8)) == true)\n {\n var tempS = nric.substring(1, 7);\n if (tempS.match(/^[0-9]+$/) != null)\n {\n return true;\n }\n }\n else if(nric.length == 9 && nric.charAt(0).toLowerCase() == \"g\" && /^[a-zA-Z]+$/.test(nric.charAt(8)) == true)\n {\n var tempS = nric.substring(1, 7);\n if (tempS.match(/^[0-9]+$/) != null)\n {\n return true;\n }\n }\n else if(nric.length == 9 && nric.charAt(0).toLowerCase() == \"t\" && /^[a-zA-Z]+$/.test(nric.charAt(8)) == true)\n {\n var tempS = nric.substring(1, 7);\n if (tempS.match(/^[0-9]+$/) != null)\n {\n return true;\n }\n }\n else if(nric.length == 9 && nric.charAt(0).toLowerCase() == \"f\" && /^[a-zA-Z]+$/.test(nric.charAt(8)) == true)\n {\n var tempS = nric.substring(1, 7);\n if (tempS.match(/^[0-9]+$/) != null)\n {\n return true;\n }\n }\n return false;\n }",
"function valStNumber(msgError) {\n\n var srtNum = document.forms[\"signup\"][\"stNum\"].value;\n var srtNumChk = /^[0-9].*$/\n \n if (srtNum.match(srtNumChk)) {\n return true;\n \n }else{\n msgError.push(\"Street Number can only have numbers.\");\n }\n return msgError;\n}",
"function validateSRID() {\n var z = projectSRIDInput.value;\n if(/\\D/.test(z)) {\n alert(\"Only numbers are allowed for the SRID\")\n projectSRIDInput.value = \"\";\n projectSRIDInput.focus();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert strings to boolean | function toBoolean(string) {
if (string === 'true') {
return true;
} else if (string === 'false') {
return false;
}
} | [
"function stringToBoolean(str) {\n\tif (str == \"true\") {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function str2bool(str){\n return str===\"Y\" ? true : false;\n}",
"function stringToBoolean(string) {\n\tswitch(string.toLowerCase()) {\n\t\tcase \"true\":\n\t\tcase \"yes\":\n\t\tcase \"on\":\n\t\tcase \"1\":\n\t\t\treturn true;\n\t\tcase \"false\":\n\t\tcase \"no\":\n\t\tcase \"off\":\n\t\tcase \"0\":\n\t\tcase null:\n\t\t\treturn false;\n\t\tdefault:\n\t\t\treturn Boolean(string);\n\t}\n}",
"static strToBool(s)\n {\n // will match one and only one of the string 'true','1', or 'on' rerardless\n // of capitalization and regardless off surrounding white-space.\n //\n let regex=/^\\s*(true|1|on)\\s*$/i;\n\n return regex.test(s);\n }",
"function textToBool(str){\n if(str===\"true\"){\n str=true;\n }else if(str===\"false\"){\n str=false;\n }else{\n str=str;\n }\n return str;\n}",
"parseBoolean(str) {\n str = String(str).toLowerCase();\n if (str == \"true\") {\n return true;\n }\n else if (str == \"false\") {\n return false;\n }\n else {\n return undefined;\n }\n }",
"function parseBool(s){\n if (s === \"true\") return true;\n else return false;\n}",
"function parseBoolean(str) {\n return /^true$/i.test(str);\n }",
"function toBoolean() {\n return operator_1.or(stringToBoolean(), finiteNumberToBoolean());\n}",
"function evalBoolean(string) {\n return (string.toLowerCase() === 'true');\n}",
"function stringsToBool(object) {\n for (var property in object) {\n if (object.hasOwnProperty(property)) {\n if (object[property] === \"false\") {\n object[property] = false;\n }\n if (object[property] === \"true\") {\n object[property] = true;\n }\n }\n }\n }",
"function parseBoolean(string) {\n return /^true$/i.test(string);\n }",
"function parseBoolean(string) {\n return /^true$/i.test(string);\n}",
"function parseBoolean(val)\n {\n return val === 'true';\n }",
"function isBoolean(str) {\n return (\"\" + str).toLowerCase() == \"false\" || (\"\" + str).toLowerCase() == \"true\";\n}",
"function boolFunc(str) {\n return Function(\"return \" + str + \" === true\")();\n }",
"function booleanToString(b){\n // take input and convert to strings\n // return input as strings\n return b.toString()\n }",
"function boolify(value) {\n if(typeof value === 'boolean') {\n return value;\n }\n if(typeof value === 'string' && value) {\n switch(value.toLowerCase()) {\n case 'true':\n case 't':\n case '1':\n case 'yes':\n case 'y':\n return true;\n case 'false':\n case 'f':\n case '0':\n case 'no':\n case 'n':\n return false;\n }\n }\n // if here we couldn't parse it\n throw new Error('Invalid boolean:' + value);\n}",
"function myBooleanizer(v) {\r\n\t\treturn Boolean(v === 'true' | v);\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create puzzle piece divs row by row with correct portion of photo | function slicepuzzle()
{
// get number of pieces from input form
piecenumber = $("input[name=piecenumber]:checked").val();
// total number of pixels in the photo
totalpixels = photox * photoy;
// total number of pixels in each puzzle piece
piecepixels = totalpixels / piecenumber;
// x and y dimension of square piece
piecesize = Math.sqrt(piecepixels);
// number of rows and columns of pieces inside photo
piecerows = photoy / piecesize;
piececols = photox / piecesize;
// create puzzle pieces row by row
for (i = 0; i < piecerows; i++)
{
for (j = 0; j < piececols; j++)
{
// create piece and number it by id
$("#puzzlec").append("<div class='piece' id='piece" + i + j + "'></div>");
// set user-selected (or default) background-image of each piece and resize
$("#piece" + i + j).css("background-image", pic);
$("#piece" + i + j).css("background-size", bgsize);
// set position of imaage inside of piece
var xpos = (-1 * piecesize) * j;
var ypos = (-1 * piecesize) * i;
var bgpos = xpos + "px " + ypos + "px";
$("#piece" + i + j).css("background-position", bgpos);
// here's that amazing jQuery magic for dragging DIV's and snapping to grid
$("#piece" + i + j).draggable({containment: "#puzzlec"});
$("#piece" + i + j).draggable({snap: "#puzzlec"});
$("#piece" + i + j).draggable({snap: ".piece"});
}
}
// set the width and height for all pieces in the css class, including 1px border on each edge
$(".piece").css("width", piecesize-2);
$(".piece").css("height", piecesize-2);
// fade in completed puzzle
$("#puzzlec").animate({opacity: "1"},500,"linear");
// randomize piece placement!
shakepuzzle();
// start checking for solutions
$(".piece").mouseup(function(){solution();});
} | [
"function slicepuzzle()\n{\n\t// calculate number of pieces in each row and column based on total number of pieces\n\t// find middle factors of piecenum so rows and columns are even\n\tvar piecegrid = midfactors(piecenumber);\n\t\n\t// bigger number of grid pair goes for bigger photo dimension\n\tpiececols = ((photox > photoy) ? piecegrid[\"big\"] : piecegrid[\"small\"]);\n\tpiecerows = ((photox <= photoy) ? piecegrid[\"big\"] : piecegrid[\"small\"]);\n\t\n\t// calculate dimensions of each piece based on total photo size and number of pieces in grid\n\tpiecesizex = photox / piececols;\n\tpiecesizey = photoy / piecerows;\n\t\n\t// create puzzle pieces row by row\n\tfor (i = 0; i < piecerows; i++)\n\t{\n\t\tfor (j = 0; j < piececols; j++)\n\t\t{\n\t\t\t// create piece and number it by id\n\t\t\t$(\"#puzzlec\").append(\"<div class='piece' id='piece\" + i + j + \"'></div>\");\n\t\t\t\n\t\t\t// set user-selected (or default) background-image of each piece and resize\n\t\t\t$(\"#piece\" + i + j).css(\"background-image\", pic);\n\t\t\t$(\"#piece\" + i + j).css(\"background-size\", bgsize);\n\t\t\t\n\t\t\t// set position of imaage inside of piece\n\t\t\tvar xpos = (-1 * piecesizex) * j;\n\t\t\tvar ypos = (-1 * piecesizey) * i;\n\t\t\tvar bgpos = xpos + \"px \" + ypos + \"px\";\n\t\t\t$(\"#piece\" + i + j).css(\"background-position\", bgpos);\n\t\t\t\n\t\t\t// here's that amazing jQuery magic for dragging DIV's and snapping to grid\n\t\t\t$(\"#piece\" + i + j).draggable({containment: \"#puzzlec\"});\n\t\t\t$(\"#piece\" + i + j).draggable({snap: \"#puzzlec\"});\n\t\t\t$(\"#piece\" + i + j).draggable({snap: \".piece\"});\t\t\n\t\t}\n\t}\n\t\n\t// set the width and height for all pieces in the css class, including 1px border on each edge\n\t$(\".piece\").css(\"width\", piecesizex-2);\n\t$(\".piece\").css(\"height\", piecesizey-2);\n\t\n\t// fade in completed puzzle\n\t$(\"#puzzlec\").animate({opacity: \"1\"},500,\"linear\");\n\n\t// randomize piece placement!\n\tshakepuzzle();\n\n\t// start checking for solutions\n\t$(\".piece\").mouseup(function(){solution();});\n}",
"function makePuzzlePieces() {\n // Makes an array of left and right pieces containers names\n let piecesContainer = [\"leftSidePieces\", \"rightSidePieces\"];\n // Based on the puzzle chosen, gets the pieces of that puzzle from Json file\n for (let p = 0; p < puzzles.length; p++) {\n if (puzzleId === puzzles[p].id) {\n // Gets pieces images from Json file and assigns them to an array\n for (let j = 0; j < numPieces; j++) {\n let pieceImage = puzzles[p].pieces[j];\n allPiecesImgAddress.push(pieceImage);\n }\n }\n }\n // Gets the first image address length and assigns to a variable\n firstPieceLength = allPiecesImgAddress[0].length;\n\n // Makes two columns of puzzle pieces and displays them on the sides\n let numPiecesToShow = 0;\n let totalNumPiecesToShow = 24;\n let numPiecesContainers = 2;\n\n // Makes two columns of puzzle pieces\n for (var g = 0; g < numPiecesContainers; g++) {\n // Creates puzzle pieces\n for (let i = numPiecesToShow; i < totalNumPiecesToShow; i++) {\n // Defines a vertical rectangular area of display for the pieces\n displayableAreaHeight = Math.floor(($('.columns').height() / 2));\n displayableAreaWidth = Math.floor($('.columns').width() / 4.5);\n\n // According to the column chosen increases or decreases left border value\n if (g === 0) {\n borderLeft = -30;\n } else if (g === 1) {\n borderLeft = +30;\n }\n\n // Generates random x and y position\n let randPosX = borderLeft + Math.floor((Math.random() * (displayableAreaWidth)));\n let randPosY = Math.floor((Math.random() * (displayableAreaHeight)));\n\n // Gets random image from the array and assigns to the html element\n let pieceImgAddress = getRandomElement(allPiecesImgAddress);\n // Gets the number embeded in the image address in order to be used in the piece id name\n let pieceId = findPieceId(pieceImgAddress);\n // Creates the piece\n let piece = $('<img>').attr({\n id: `piece${pieceId}`,\n src: `${pieceImgAddress}`\n }).appendTo(`#${piecesContainer[g]}`);\n piece.css({\n \"width\": \"4.5vw\",\n \"left\": `${randPosX}px`,\n \"top\": `${randPosY}px`,\n \"position\": \"relative\"\n });\n // Makes it draggable\n piece.draggable();\n // makes an array of pieces\n puzzlePieces.push(piece);\n // Removes the current image from the images array so that it won't be used again\n removeRandomElement(pieceImgAddress);\n }\n // Goes for the next column\n numPiecesToShow += 24;\n totalNumPiecesToShow += 24;\n }\n}",
"function putPuzzle() {\n for (var i = 0; i < TOTAL_ROWS_COLS; i++) {\n for (var j = 1; j <= TOTAL_ROWS_COLS; j++) { // adds 16 pieces to the puzzle\n var piece = document.createElement(\"div\");\n piece.classList.add(\"piece\");\n var id = j + TOTAL_ROWS_COLS * i;\n piece.id = id;\n piece.innerHTML = id;\n \n // assigns background position using the row and column given and the piece size\n piece.style.backgroundPosition = -(PIECE_SIZE) * (j - 1) + \"px \"+ -(i * (PIECE_SIZE)) + \"px\";\n \n // assigns overall position in puzzle using row and column\n piece.style.top = (i * PIECE_SIZE) + \"px\";\n piece.style.left = PIECE_SIZE * (j - 1) + \"px\";\n \n document.getElementById(\"puzzlearea\").appendChild(piece);\n }\n }\n //removes the 16th piece of puzzle, leaving the empty space.\n document.getElementById(\"puzzlearea\").removeChild(document.getElementById('16'));\n }",
"function createPuzzle(){\n var counter = 1;\n for(var i = 0; i < SIZE; i++){\n for(var j = 0; j < SIZE && counter < SIZE * SIZE; j++){\n var puzzlePiece = document.createElement(\"div\");\n puzzlePiece.classList.add(\"puzzle\");\n puzzlePiece.id = i + \"_\" + j;\n puzzlePiece.style.left = j * SQUARE_HEIGHT + \"px\";\n puzzlePiece.style.top = i * SQUARE_HEIGHT + \"px\";\n puzzlePiece.style.backgroundPosition = (-j * SQUARE_HEIGHT + \"px \") + (-i * SQUARE_HEIGHT + \"px\");\n puzzlePiece.innerHTML = counter;\n counter += 1;\n $(\"puzzlearea\").appendChild(puzzlePiece);\n }\n }\n }",
"function InitPuzzle(){\r\n\t\t\t\tvar jPiece = null;\r\n\t\t\t\tvar intRowIndex, intColIndex, intI = 0;\r\n \r\n\t\t\t\t// Get the number of columns and rows.\r\n\t\t\t\tintColumns = Math.floor( jImg.width() / intSize );\r\n\t\t\t\tintRows = Math.floor( jImg.height() / intSize );\r\n \r\n\t\t\t\t// Get the puzzle width and height based on\r\n\t\t\t\t// the number of pieces (this may require some\r\n\t\t\t\t// cropping of the image).\r\n\t\t\t\tintPuzzleWidth = (intColumns * intSize);\r\n\t\t\t\tintPuzzleHeight = (intRows * intSize);\r\n \r\n\t\t\t\t// Empty the container element. We don't actually\r\n\t\t\t\t// want the image inside of it (or any of the\r\n\t\t\t\t// other elements that might be there).\r\n\t\t\t\tjContainer.empty();\r\n \r\n\t\t\t\t// Set the container CSS and dimensions.\r\n\t\t\t\tjContainer\r\n\t\t\t\t\t.css(\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tborder: \"1px solid black\",\r\n\t\t\t\t\t\t\toverflow: \"hidden\",\r\n\t\t\t\t\t\t\tdisplay: \"block\"\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t.width( intPuzzleWidth )\r\n\t\t\t\t\t.height( intPuzzleHeight )\r\n\t\t\t\t;\r\n \r\n\t\t\t\t// Check to see how the container is positioned.\r\n\t\t\t\t// If is relative or absolute, we can keep it,\r\n\t\t\t\t// but if it is not those, then we need to set\r\n\t\t\t\t// is to relative explicitly.\r\n\t\t\t\tif (\r\n\t\t\t\t\t(jContainer.css( \"position\" ) != \"relative\") &&\r\n\t\t\t\t\t(jContainer.css( \"position\" ) != \"absolute\")\r\n\t\t\t\t\t){\r\n \r\n\t\t\t\t\t// The container element is not explicitly\r\n\t\t\t\t\t// positioned, so position it to be relative.\r\n\t\t\t\t\tjContainer.css( \"position\", \"relative\" );\r\n \r\n\t\t\t\t}\r\n \r\n \r\n\t\t\t\t// Loop over the columns and row to create each\r\n\t\t\t\t// of the pieces. At this point, we are not going to worry\r\n\t\t\t\t// about the dimensions of the board - that will happen next.\r\n\t\t\t\tfor (var intRowIndex = 0 ; intRowIndex < intRows ; intRowIndex++){\r\n \r\n\t\t\t\t\t// For this row, add a new array.\r\n\t\t\t\t\tarr2DBoard[ intRowIndex ] = [];\r\n \r\n\t\t\t\t\tfor (var intColIndex = 0 ; intColIndex < intColumns ; intColIndex++){\r\n \r\n\t\t\t\t\t\t// Create a new Div tag. We are using a DIV tag as\r\n\t\t\t\t\t\t// opposed to an anchor tag to get around the IE\r\n\t\t\t\t\t\t// bug that has flickering background images on links\r\n\t\t\t\t\t\t// when the browser is not caching images.\r\n\t\t\t\t\t\tjPiece = $( \"<div><br /></div>\" );\r\n \r\n\t\t\t\t\t\t// Set the css properties. Since all of the\r\n\t\t\t\t\t\t// pieces have the same background image, they\r\n\t\t\t\t\t\t// all have to have different offset positions.\r\n\t\t\t\t\t\tjPiece\r\n\t\t\t\t\t\t\t.css(\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tdisplay: \"block\",\r\n\t\t\t\t\t\t\t\t\tfloat: \"left\",\r\n\t\t\t\t\t\t\t\t\tcursor: \"pointer\",\r\n\t\t\t\t\t\t\t\t\tbackgroundImage: \"url( '\" + jImg.attr( \"src\" ) + \"' )\",\r\n\t\t\t\t\t\t\t\t\tbackgroundRepeat: \"no-repeat\",\r\n\t\t\t\t\t\t\t\t\tbackgroundPosition: (\r\n\t\t\t\t\t\t\t\t\t\t(intColIndex * -intSize) + \"px \" +\r\n\t\t\t\t\t\t\t\t\t\t(intRowIndex * -intSize) + \"px\"\r\n\t\t\t\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\tposition: \"absolute\",\r\n\t\t\t\t\t\t\t\t\ttop: ((intSize * intRowIndex) + \"px\"),\r\n\t\t\t\t\t\t\t\t\tleft: ((intSize * intColIndex) + \"px\")\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t.width( intSize )\r\n\t\t\t\t\t\t\t.height( intSize )\r\n\t\t\t\t\t\t;\r\n \r\n\t\t\t\t\t\t// Set the HREF so that the click even registers.\r\n\t\t\t\t\t\t// Then, set up the click handler.\r\n\t\t\t\t\t\tjPiece\r\n\t\t\t\t\t\t\t.attr( \"href\", \"javascript:void( 0 );\" )\r\n\t\t\t\t\t\t\t.click( PieceClickHandler )\r\n\t\t\t\t\t\t;\r\n \r\n\t\t\t\t\t\t// Add the piece to the 2-D representation of the board.\r\n\t\t\t\t\t\tarr2DBoard[ intRowIndex ][ intColIndex ] = jPiece;\r\n \r\n\t\t\t\t\t\t// Add to DOM.\r\n\t\t\t\t\t\tjContainer.append( jPiece );\r\n \r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n \r\n \r\n\t\t\t\t// Make the last one opaque and give it a special \"rel\"\r\n\t\t\t\t// value so that we can easily loacate this one later on.\r\n\t\t\t\tarr2DBoard[ intRows - 1 ][ intColumns - 1 ]\r\n\t\t\t\t\t.css( \"opacity\", 0 )\r\n\t\t\t\t\t.attr( \"rel\", \"empty\" )\r\n\t\t\t\t;\r\n \r\n \r\n\t\t\t\t// In order to shuffle the board, we are going to simulate\r\n\t\t\t\t// a certain number of clicks. This is to ensure that any\r\n\t\t\t\t// state the board gets into, it is certain that the board\r\n\t\t\t\t// can get back into a \"winning\" state.\r\n\t\t\t\tfor (intI = 0 ; intI < 100 ; intI++){\r\n \r\n\t\t\t\t\t// Select the piece that we want to \"click\".\r\n\t\t\t\t\t// We will do this by randomly selecting a row\r\n\t\t\t\t\t// and a column to click.\r\n\t\t\t\t\tjPiece = arr2DBoard[\r\n\t\t\t\t\t\t(Math.floor( Math.random() * intRows * intRows ) % intRows)\r\n\t\t\t\t\t\t][\r\n\t\t\t\t\t\t(Math.floor( Math.random() * intColumns * intColumns ) % intColumns)\r\n\t\t\t\t\t\t];\r\n \r\n\t\t\t\t\t// Simulate the click.\r\n\t\t\t\t\tjPiece.click();\r\n\t\t\t\t}\r\n \r\n \r\n\t\t\t\t// Now that we have initialized, turn on the animation.\r\n\t\t\t\tblnShowAnimation = true;\r\n \r\n\t\t\t\t// Return out.\r\n\t\t\t\treturn( true );\r\n\t\t\t}",
"function createPuzzle(pieces) {\n\t\tvar area = document.getElementById('puzzlearea');\n\t\t\n\t\tfor (var i = 0; i < pieces; i++) {\n\t\t\tvar newPiece = document.createElement('div');\n \t\tvar posY = Math.floor((i / 4)) * 100;\n\t\t\tvar posX = (i % 4) * 100;\n\n\t\t\tnewPiece.className = 'piece';\n\t\t\tnewPiece.innerHTML = i + 1;\n\t\t\tnewPiece.style.top = posY + 'px';\n\t\t\tnewPiece.style.left = posX + 'px';\n\t\t\tnewPiece.style.backgroundPosition = (-posX) + 'px ' + (-posY) + 'px';\n\n\t\t\tarea.appendChild(newPiece);\n\t\t}\n\t}",
"function cutImageIntoPieces(difficulty){\n // reset elements array to prevent any previous element to stay there\n elements = [];\n // find width and height for each element\n elementWidth = canvas.width / difficulty;\n elementHeight = canvas.height / difficulty;\n // console.log(elementWidth)\n // console.log(canvas.width)\n // console.log(pixelRatio)\n cropStartX = 0;\n cropStartY = 0;\n for(var i = 0; i < difficulty * difficulty; i++){\n element = {};\n // save original position to be able to check for a won game\n element.originalX = cropStartX;\n element.originalY = cropStartY;\n elements.push(element);\n // draw each element in canvas\n //ctx.drawImage(originalCanvas, cropStartX, cropStartY, elementWidth, elementHeight, cropStartX, cropStartY, elementWidth, elementHeight);\n //ctx.strokeRect(cropStartX, cropStartY, elementWidth, elementHeight);\n cropStartX += elementWidth;\n if(cropStartX >= canvas.width){\n cropStartX = 0;\n cropStartY += elementHeight;\n }\n }\n //console.log(elements)\n \n }",
"function buildPieces(){\n var i;\n var piece;\n var xPos = 0;\n var yPos = 0;\n for(i = 0;i < difficulty * difficulty;i++){\n piece = {};\n piece.sx = xPos;\n piece.sy = yPos;\n pieces.push(piece);\n xPos += pieceWidth;\n if(xPos >= puzzleWidth){\n xPos = 0;\n yPos += pieceHeight;\n }\n }\n // shuffles puzzle on view\n shufflePuzzle();\n }",
"function placePuzzleImagesInPlace() {\n window.puzzleImagesList = puzzleImagesList;\n\n piecesMatrix = [];\n positionsList = [];\n\n let index = 0;\n for (let row=0; row<numRows; row++){\n let rowList = [];\n for (let col=0; col<numCols; col++){\n\n let image = puzzleImagesList[col+'-'+row].image;\n let move = document.createElement(\"DIV\");\n\n move.innerHTML = `<svg viewbox=\"0 0 180 180\" width=\"${sizeOfPieces * 180 / 100}\" height=\"${sizeOfPieces * 180 / 100}\"> \n <path d=\"${puzzleImagesList[col+'-'+row].path}\"></path>\n </svg>`;\n\n move.appendChild(image);\n\n move.className=\"move\";\n move.style.width = sizeOfPieces + \"px\";\n move.style.height = sizeOfPieces + \"px\";\n move.onmousedown=getPos;\n move.onclick=onDblClick;\n move.ontouchstart=getPos;\n move.angle=0;\n move.occupy= false;\n move.position=function(){return {left:this.offsetLeft+(sizeOfPieces/2),top:this.offsetTop +(sizeOfPieces/2)};};\n move.onmouseup=dropPiece;\n move.ontouchend=dropPiece;\n move.index=index;\n //position indicates the position on the board\n let position = document.createElement(\"DIV\");\n position.className=\"position\";\n position.style.width = sizeOfPieces + \"px\";\n position.style.height = sizeOfPieces + \"px\";\n position.index=index;\n position.occupied=false;\n document.querySelector(\"#container\").appendChild(position);\n position.appendChild(move);\n positionsList.push(position);\n\n move.style.zIndex = zIndex++;\n move.zIndexPrevi=move.style.zIndex;\n move.x = col;\n move.y = row;\n\n rowList.push(move);\n\n index++;\n }\n piecesMatrix.push(rowList);\n }\n\n document.getElementById('loading').style.display = 'none';\n document.getElementById('start').style.display = 'inline-block';\n}",
"function setupPieces(puzzle) {\n\t\tpuzzle.innerHTML = \"\";\n\t\tfor (var i = 1; i <= 15; i++) {\n\t\t\tvar piece = document.createElement(\"div\");\n\t\t\tpiece.className = \"piece normal\";\n\t\t\tpiece.id = \"x\" + i;\n\t\t\tpiece.innerHTML = i;\n\t\t\tpiece.onmouseover = mouseOver;\n\t\t\tpiece.onmouseout = mouseOut;\n\t\t\tpuzzle.appendChild(piece);\n\t\t}\n\n\t}",
"function puzzles() {\n var puzzles = document.getElementById(\"puzzlearea\");\n var counter = 1;\n for(var row = 0; row < SIZE; row++) {\n for(var col = 0; col < SIZE; col++) {\n if(counter < SIZE * SIZE) {\n var block = document.createElement(\"div\");\n puzzles.appendChild(block);\n block.id = \"square_\" + row + \"_\" + col;\n block.innerHTML = counter;\n block.style.top = row * TILE + \"px\";\n block.style.left = col * TILE + \"px\";\n block.style.backgroundPosition = col * (-TILE) + \"px \" + row * (-TILE) + \"px\";\n block.onclick = click;\n block.onmouseover = color;\n }\n counter++;\n }\n }\n }",
"function fifteenPuzzle(){\r\n let tilePos = 1;\r\n let puzzlearea = document.getElementById(\"puzzlearea\");\r\n for(let row = 0; row < ROW_SIZE; row++){\r\n for(let col = 0; col < COL_SIZE; col++){\r\n if(tilePos < 16){\r\n // adding a div in every iteration\r\n let tile = document.createElement(\"div\");\r\n // setting the same class name for every div\r\n tile.classList.add(\"tile\");\r\n // adding the position number of the tile\r\n tile.innerHTML = tilePos;\r\n // setting the left- and top-coordinates of the tile\r\n tile.style.left = col * TILE_SIZE + \"px\";\r\n tile.style.top = row * TILE_SIZE + \"px\";\r\n // setting the frame position of the background image that corresponds\r\n // to the tile's position\r\n tile.style.backgroundPosition = -col*TILE_SIZE+\"px \"+ -row*TILE_SIZE+\"px\";\r\n // setting an id of the div\r\n tile.id = \"tile_\" + row + \"_\" + col;\r\n // adding the tile into the puzzlearea\r\n puzzlearea.appendChild(tile);\r\n tilePos++;\r\n }\r\n }\r\n }\r\n }",
"function placePieces() {\r\n clearBoard();\r\n for (i = 0; i < 8; i++) {\r\n for (j = 0; j < 8; j++) {\r\n if (!pieces[i][j]) {\r\n continue;\r\n }\r\n let curPiece = document.createElement(\"img\");\r\n curPiece.className = \"Piece\";\r\n let pname = pieceName[pieces[i][j].piece];\r\n curPiece.id = pname + i + j;\r\n curPiece.src = \"Images/\" + colorName[pieces[i][j].color] + \"-\" + pname + \".png\";\r\n squares[i][j].appendChild(curPiece);\r\n }\r\n }\r\n}",
"function drawPieces(){\n\n for(i=0;i<(NUMBER_OF_COLS * NUMBER_OF_ROWS);i++){\n drawPiece(Math.floor(i/8), i%8);\n }\n\n}",
"async function setupPuzzle () {\n try {\n const puzzleImg = await puzzleService.getOne(id)\n setPuzzleImage(puzzleImg.puzzle)\n const xSize = Math.floor(puzzleImg.puzzle.width / pieceSize)\n const ySize = Math.floor(puzzleImg.puzzle.height / pieceSize)\n setXCount(xSize)\n setYCount(ySize)\n \n const temp = []\n const vEdgeBuilder = []\n const hEdgeBuilder = []\n\n for(let y = 0; y < ySize; y++) { \n vEdgeBuilder.push([])\n hEdgeBuilder.push([]) \n\n // Create all of the pieces\n for (let x = 0; x < xSize; x++) {\n\n let description = ''\n if (y === 0) description += 'top'\n else if (y === ySize - 1) description += 'bottom'\n if (x === 0) description += 'left'\n else if (x === xSize - 1) description += 'right'\n\n temp.push(\n {\n x: x,\n y: y,\n z: 0,\n xLoc: Math.floor(Math.random() * (window.innerWidth - pieceSize)),\n yLoc: Math.floor(Math.random() * (window.innerHeight - pieceSize - 100) + 100),\n description: description,\n connected: [ xSize * y + x]\n }\n )\n\n // Establish edges in-between polygon pieces\n if (type === 'poly' && x !== xSize - 1) {\n vEdgeBuilder[y].push([Math.floor(Math.random() * POLY_BUFFER) - POLY_BUFFER / 2, Math.floor(Math.random() * VERTEX_RANGE) + VERTEX_RANGE_OFFSET])\n }\n if (type === 'poly' && y !== ySize - 1) {\n hEdgeBuilder[y].push([Math.floor(Math.random() * POLY_BUFFER) - POLY_BUFFER / 2, Math.floor(Math.random() * VERTEX_RANGE) + VERTEX_RANGE_OFFSET])\n }\n }\n }\n\n setVEdges(vEdgeBuilder)\n setHEdges(hEdgeBuilder)\n\n if (type === 'tile')\n setBuffer(0)\n if (type === 'poly') {\n const PERCENT_OF_VISUAL_TILE = 70 // visual tiile will be 70% of total size with buffer\n const PERCENT_OF_BUFFER = (100 - PERCENT_OF_VISUAL_TILE) / 2\n setBuffer(pieceSize / PERCENT_OF_VISUAL_TILE * PERCENT_OF_BUFFER)\n }\n\n setThePuzzle(temp)\n } catch (err) {\n console.log(err)\n }\n }",
"function buildPieces(){\n var i;\n var piece;\n var xPos = 0;\n var yPos = 0;\n var numberOfPieces = (PUZZLE_DIFFICULTY * (canvas2.height/PUZZLE_DIFFICULTY)/10);\n for(i = 0;i < numberOfPieces;i++){\n piece = {};\n piece.sx = xPos;\n piece.sy = yPos;\n _pieces.push(piece);\n xPos += _pieceWidth;\n if(xPos >= _puzzleWidth){\n xPos = 0;\n yPos += _pieceHeight;\n }\n }\n}",
"function pieces(data) {\n // Creates the top arrow\n arrowTop = $('<img>').addClass('arrowTop').attr('src', 'assets/images/arrowTop.png').appendTo(`.content-slider`);\n\n // Stores puzzle id \n let getPuzzleId;\n // Based on the id of the puzzle, gets data from Json file\n for (let i = 0; i < puzzles.length; i++) {\n if (puzzleId === puzzles[i].id) {\n getPuzzleId = i;\n // Gets data from JSON file\n // Stores slide's length in a variable\n numSlides = puzzles[i].length;\n // Stores all images in an array\n for (var h = 0; h < numSlides; h++) {\n let imgAddress = puzzles[i].pieces[h];\n // Stores all images address in an array\n pieceImage.push(imgAddress);\n }\n }\n }\n\n // Stores the first piece image address length in a variable\n let firstPieceLength = puzzles[getPuzzleId].pieces[0].length;\n // Creates pieces and adds them to their relative slide\n for (let i = 0; i < numSlides; i++) {\n // Gets random image from the array\n let randomPieceImg = getRandomElement(pieceImage);\n // Gets the image Id\n let imageId;\n // As The number embeded in the images address is going to be used the address length matters\n if (randomPieceImg.length === firstPieceLength) {\n imageId = randomPieceImg.charAt(randomPieceImg.length - 5);\n } else if (randomPieceImg.length === (firstPieceLength + 1)) {\n imageId = randomPieceImg.substring(randomPieceImg.length - 6, randomPieceImg.length - 4);\n }\n\n // Creates slide\n slide = $('<li></li>').addClass(`slide${i}`).addClass(\"slideC\").appendTo('.content-slider');\n // Gets the piece's image address\n let imgAddress = randomPieceImg;\n // Creates the image element and assigns it to the slide\n puzzlePiece = $('<img>').addClass(`piece${imageId}Img`).css({\n \"width\": \"6vw\",\n \"padding\": \"14px\"\n }).attr('src', `${imgAddress}`).appendTo(`.slide${i}`);\n\n // Makes the piece draggable\n puzzlePiece.draggable();\n\n //SABINE EDIT\n //push the ENTIRE OBJECT to the pieceInSlide array\n piecesInSlide.push(puzzlePiece);\n\n // Removes the image used from the array so that it won't be picked again\n removeImageAfterAssignment(randomPieceImg);\n\n // Displays only the first four pieces\n if (i > numSlidesToShow) {\n $(`.slide${i}`).hide();\n }\n }\n\n // Creates spots on the puzzle template to place the pieces\n spotsToPositionPieces(data);\n // Makes bottom arrow\n arrowBottom = $('<img>').addClass('arrowBottom').attr('src', 'assets/images/arrowBottom.png').appendTo(`.content-slider`);\n // On click, moves the slides up or down\n arrowTop.on('click', goNext);\n arrowBottom.on('click', goPrev);\n}",
"displayPieces() {\n for (var i = 0; i < 8; i++) {\n for (var j = 0; j < 8; j++) {\n if (this.piecePositions[j][i] != null) {\n image(\n this.piecePositions[j][i],\n 8 + SQUARE_SIZE + i * SQUARE_SIZE,\n 7 + SQUARE_SIZE + j * SQUARE_SIZE,\n 50,\n 50\n );\n }\n }\n }\n\n this.pawnToQueen()\n }",
"function Puzzle(columns, rows, finalHole) {\n\n let kx, ky, nvTile, ctx;\n let container = 'game';\n const hSize = img.width;\n const vSize = img.height;\n if (typeof(container) == 'string') {\n container = document.getElementById(container);\n }\n this.container = container;\n // remove any previous contents\n emptyElement(container);\n\n// this.imagePath = imagePath;\n\n// resize container\n container.style.position = \"relative\";\n container.style.width = hSize + \"px\";\n container.style.height = vSize + \"px\";\n// create canvas to display solution\n this.solutionCanvas = document.createElement('canvas');\n this.solutionCanvas.style.position = \"absolute\";\n this.solutionCanvas.width = hSize;\n this.solutionCanvas.height = vSize;\n ctx = this.solutionCanvas.getContext('2d');\n ctx.drawImage (img, 0, 0); // full image\n container.appendChild(this.solutionCanvas);\n// size of tile\n this.hSide = hSize / columns;\n this.vSide = vSize / rows;\n\n this.columns = columns;\n this.rows = rows;\n finalHole = finalHole.toUpperCase();\n this.finalHole = finalHole;\n this.tbTiles = [];\n this.emptyTileSolution = {};\n this.emptyTileSolution.x = ((finalHole.charAt(1) == \"R\") ? columns - 1 : 0); // coordinates of hole in solution\n this.emptyTileSolution.y = ((finalHole.charAt(0) == \"B\") ? rows - 1 : 0);\n this.MoveInPrgrs = false; // no movement in progress\n this.emptyTile = {x: this.emptyTileSolution.x, y: this.emptyTileSolution.y}\n\n// mark hole place\n nvTile = document.createElement(\"div\");\n nvTile.style.width = this.hSide + \"px\";\n nvTile.style.height = this.vSide + \"px\";\n nvTile.style.position = \"absolute\";\n nvTile.style.padding = \"0\";\n nvTile.style.margin = \"0\";\n nvTile.style.position = \"absolute\";\n nvTile.className = \"emptyTileSolution\";\n nvTile.style.left = this.emptyTileSolution.x * this.hSide + \"px\";\n nvTile.style.top = this.emptyTileSolution.y * this.vSide + \"px\";\n container.appendChild(nvTile);\n\n// 'true' tiles\n for (ky = 0; ky < rows; ky++) {\n this.tbTiles[ky] = [];\n for (kx = 0; kx < columns; kx++) {\n if (kx == this.emptyTile.x && ky == this.emptyTile.y) continue; // no tile at the place of the hole\n nvTile = document.createElement(\"canvas\");\n nvTile.width = this.hSide;\n nvTile.height = this.vSide;\n nvTile.style.position = \"absolute\";\n nvTile.style.padding = \"0\";\n nvTile.style.margin = \"0\";\n nvTile.style.position = \"absolute\";\n ctx = nvTile.getContext(\"2d\");\n ctx.drawImage(img, kx * this.hSide, ky * this.vSide, this.hSide, this.vSide, 0, 0, this.hSide, this.vSide);\n addBorders(nvTile);\n\n nvTile.style.left = kx * this.hSide + \"px\";\n nvTile.style.top = ky * this.vSide + \"px\";\n nvTile.addEventListener(\"mousedown\" , (function(obj, x, y) {return function(e){ obj.enter(e, x, y); }})(this, kx, ky));\n nvTile.addEventListener(\"mouseup\" , (function(obj, x, y) {return function(e){ obj.leave(e, x, y); }})(this, kx, ky));\n nvTile.addEventListener(\"mouseout\" , (function(obj, x, y) {return function(e){ obj.leave(e, x, y); }})(this, kx, ky));\n\n container.appendChild(nvTile);\n this.tbTiles[ky][kx]= {tile: nvTile, currentPos: {x: kx, y: ky}}; // x, y = current position of tile in puzzle\n\n } // for kx\n } // for ky\n this.gameInProgress = false;\n this.hide();\n} // Puzzle constructor"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
init :: (Applicative f, Foldable f, Monoid (f a)) => f a > Maybe (f a) . . Returns Just all but the last of the given structure's elements if the . structure contains at least one element; Nothing otherwise. . . ```javascript . > S.init ([1, 2, 3]) . Just ([1, 2]) . . > S.init ([]) . Nothing . . > S.init (Cons (1) (Cons (2) (Cons (3) (Nil)))) . Just (Cons (1) (Cons (2) (Nil))) . . > S.init (Nil) . Nothing . ``` | function init(foldable) {
// Fast path for arrays.
if (Array.isArray (foldable)) {
return foldable.length > 0 ? Just (foldable.slice (0, -1)) : Nothing;
}
var empty = Z.empty (foldable.constructor);
return Z.map (Pair.snd, Z.reduce (function(m, x) {
return Just (Pair (x) (maybe (empty) (pair (append)) (m)));
}, Nothing, foldable));
} | [
"function init(xs) {\n return xs.length > 0 ? Just (xs.slice (0, -1)) : Nothing;\n }",
"function _init(array) {\n for (var i = 0, len = array.length; i < len; i++) {\n var value = array[i];\n if (Array.isArray(value)) {\n _init(value);\n }\n else if (value == undefined) {\n array[i] = 0;\n }\n }\n}",
"function inits(xs){\r\n if(!xs.length)\r\n return [emptyListOf(xs)];\r\n return append([emptyListOf(xs)], map(function(e){ return cons(x, e) }, inits(xs)));\r\n}",
"function _init(array) {\n for (var i = 0, len = array.length; i < len; i++) {\n var value = array[i];\n if (value instanceof Array) {\n _init(value);\n }\n else if (value == undefined) {\n array[i] = 0;\n }\n }\n}",
"function firstOrUndefined(array){return array.length===0?undefined:array[0];}",
"SET_EMPTY_LIST_STRUCTURE (state, o) { state.emptyList = o }",
"function emptyList(size)\n{\n return fillList(size, \"\");\n}",
"function make_empty_binary_tree() {\n return null\n}",
"function preFilled(num, element) {\n var result = [];\n for (var i = 0; i < num; i++) {\n if (element === undefined) {\n result[i] = null;\n }\n else {\n result[i] = element;\n }\n }\n return result;\n}",
"function singleOrUndefined(array){return array&&array.length===1?array[0]:undefined;}",
"function fillEmptyCollections(inCollection,dummyImage){ \r\n var dummyCollection = ee.ImageCollection([dummyImage.mask(ee.Image(0))]);\r\n var imageCount = inCollection.toList(1).length();\r\n return ee.ImageCollection(ee.Algorithms.If(imageCount.gt(0),inCollection,dummyCollection));\r\n\r\n}",
"function initialDocument(xmlStructure) {\n var ret = \"<\"+xmlStructure.root+\">\";\n var children = getFlatChildren(xmlStructure.elements.find(function(xe) {return xe.name==xmlStructure.root}));\n if (children != null) {\n children.forEach(function(chEl) {\n if (chEl.min > 0) {\n ret += initialElement(xmlStructure.elements.find(function(xe) {return xe.name==chEl.name}));\n }\n });\n }\n ret += \"</\"+xmlStructure.root+\">\";\n return ret;\n}",
"makeEmpty() {\r\n this.min = Number.POSITIVE_INFINITY;\r\n this.max = Number.NEGATIVE_INFINITY;\r\n }",
"function wrapOrEmpty(obj) {\n\t\tif(obj) {\n\t\t\treturn [obj];\n\t\t}\n\t\t\n\t\treturn [];\n\t}",
"function empty(obj) {\n // YOUR SOLUTION HERE\n return obj;\n}",
"function listToMaybe(l){\r\n if(!l.length)\r\n return emptyListOf(l);\r\n return Maybe.Just(l[0]);\r\n}",
"function maybe_2(xs) /* forall<a> (xs : list<a>) -> maybe<a> */ {\n return (xs == null) ? Nothing : Just(xs.head);\n}",
"function first(a) { return (a !== null && a.length > 0) ? a[0] : null; }",
"static empty(length) {\n return new ChangeSet(length ? [length, -1] : [], []);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculates the max possible sum from the midpoint up | function greatestRightMovingSum(nums, midPoint, end) {
let sum = 0;
let greatestSum = -Infinity;
for (let i = midPoint; i <= end; i++) {
sum += nums[i];
if (sum > greatestSum) greatestSum = sum;
}
return greatestSum;
} | [
"function greatestLeftMovingSum(nums, start, midPoint) {\n let sum = 0;\n let greatestSum = -Infinity;\n for (let i = midPoint; i >= 0; i--) {\n sum += nums[i];\n if (sum > greatestSum) greatestSum = sum;\n }\n return greatestSum;\n}",
"maxSum() {\n let maxResult = 0;\n\n const findMaxSum = node => {\n if (node === null) return 0;\n\n const leftSide = findMaxSum(node.left);\n const rightSide = findMaxSum(node.right);\n\n maxResult = Math.max(maxResult, node.val + leftSide + rightSide);\n\n return Math.max(0, leftSide + node.val, rightSide + node.val);\n };\n\n findMaxSum(this.root);\n return maxResult;\n }",
"maxSum() {\n\t\tif (!this.root) return 0;\n\t\tlet max = 0;\n\t\t\n\t\tfunction maxSumComp (curNode) {\n\t\t\tlet leftMaxS = curNode.left ? maxSumComp(curNode.left) : 0;\n\t\t\tlet rightMaxS = curNode.right ? maxSumComp(curNode.right) : 0;\n\t\t\tmax = Math.max(max, curNode.val + leftMaxS + rightMaxS);\n\t\t\treturn Math.max(0, leftMaxS + curNode.val, rightMaxS + curNode.val);\n\t\t}\n\n\t\tmaxSumComp(this.root);\n\t\treturn max;\n }",
"maxSum() {\n if (!this.root) return 0;\n let max = -Infinity;\n function getMaxSum(node) {\n if (!node) return 0;\n let lSum = getMaxSum(node.left);\n let rSum = getMaxSum(node.right);\n max = Math.max(max, lSum + rSum + node.val);\n return Math.max(0, lSum + node.val, rSum + node.val);\n }\n getMaxSum(this.root);\n return max;\n }",
"maxSum() {\n if(!this.root) return 0;\n \n function recursiveSum(node){\n if(!node.left && !node.right){\n return node.val;\n } else if(node.left && node.right){\n const left = node.val + recursiveSum(node.left);\n const right = node.val + recursiveSum(node.right);\n return left > right ? left : right;\n } else if(node.left && !node.right){\n const left = node.val + recursiveSum(node.left);\n return left;\n } else if(!node.left && node.right){\n const right = node.val + recursiveSum(node.left);\n return right;\n }\n }\n return recursiveSum(this.root) \n }",
"function getMaxCrossSum(nums, start, midPoint, end) {\n return greatestLeftMovingSum(nums, start, midPoint) +\n greatestRightMovingSum(nums, midPoint + 1, end);\n}",
"function getMaxSubSum(arr){\n let prev = 0; // save a prev value\n let max = -1/0; // the result we need!\n for (let i = 0; i < arr.length; i++) {\n prev = Math.max(prev + arr[i], arr[i]); \n max = Math.max(max, prev); \n }\n return max;\n}",
"function main() {\n const len = arr.length;\n let max = arr[0] || 0;\n\n function test(currentMax, index) {\n if (index > len) return;\n let nextSum = currentMax + arr[index];\n\n if (nextSum > currentMax) currentMax = nextSum;\n if (nextSum > max) max = nextSum;\n\n if (index + 2 < len) test(currentMax, index + 2);\n if (index + 3 < len) test(currentMax, index + 3);\n\n return;\n }\n return max;\n}",
"maxSum() {\n // Create list of all nodes in tree to be used as starting nodes\n let visited = [];\n function _traverse(node) {\n visited.push(node);\n node.children.forEach(child => _traverse(child));\n }\n _traverse(this.root);\n\n // Define function to calculate running sum of path and compare against running max\n let max;\n let sum = 0;\n function _maxSum(node) {\n sum += node.val;\n if (sum > max || max === undefined) {\n max = sum;\n }\n node.children.forEach(child => {\n _maxSum(child);\n sum -= child.val;\n });\n }\n\n // Run _maxSum on starting with each node in tree (reset running sum to 0 after every path)\n visited.forEach(node => {\n _maxSum(node);\n sum = 0;\n });\n return max;\n }",
"function maxSum(arr) {\n let max = arr[0];\n let follower = 0;\n let leader;\n let runningTotal;\n while (arr[follower] !== undefined) {\n runningTotal = arr[follower];\n // console.log(runningTotal);\n if (runningTotal > max) max = runningTotal;\n leader = follower + 1;\n\n while (arr[leader] !== undefined) {\n runningTotal += arr[leader];\n if (runningTotal > max) max = runningTotal;\n leader++;\n }\n\n follower++;\n }\n return max;\n}",
"maxSum() {\n\n let bestSum = 0\n\n const maxSumHelp = (node) => {\n if(!node) return 0\n\n const leftSum = maxSumHelp(node.left)\n const rightSum = maxSumHelp(node.right)\n\n bestSum = Math.max(bestSum, node.val + leftSum + rightSum)\n\n return Math.max(0, node.val + leftSum, node.val + rightSum)\n }\n\n maxSumHelp(this.root)\n\n return bestSum\n }",
"function findTheMaximumSumOfSubArr(list) {\n let currentMax = Number.NEGATIVE_INFINITY,\n totalMax = Number.NEGATIVE_INFINITY\n\n list.forEach(v => {\n currentMax = Math.max(currentMax, 0) + v\n\n totalMax = Math.max(totalMax, currentMax)\n })\n\n return totalMax\n}",
"maxSum() {\n let pathResult = 0; \n \n function maxSumHelper(node) {\n if (node === null) return 0; \n\n // calculate the left sub-tree at the current node.\n let leftSum = maxSumHelper(node.left);\n // calculate the right sub-tree at the current node. \n let rightSum = maxSumHelper(node.right);\n // update path. \n pathResult = Math.max(pathResult, node.val + leftSum + rightSum);\n\n // return the greatest sub-path from left/right.\n return Math.max(0, node.val + leftSum, node.val + rightSum);\n }\n maxSumHelper(this.root);\n\n return pathResult;\n }",
"function alternativeMaxSum(arr) {\n arr.sort((a, b) => a - b);\n\n let sum = arr.reduce((a,b) => a + b);\n let minSum = sum - arr[arr.length - 1];\n let maxSum = sum - arr[0];\n\n console.log(minSum + \" \" + maxSum);\n}",
"function maxmimumSubarraySum4_WithIndexes_KadaneAlgo(a){\n //Kadane's algo for maximum subarray sum\n let current_sum = 0;\n let max_sum = Number.MIN_SAFE_INTEGER;\n let start =0;\n let end = 0; \n let newStart=0; \n\n //Kadane's algo for maximum subarray sum\n for (let i = 0; i < a.length; i++) {\n current_sum = current_sum + a[i];\n\n if(current_sum > max_sum){\n max_sum = current_sum;\n\n start = newStart; \n end = i; \n }\n\n if (current_sum < 0) {\n current_sum = 0;\n\n newStart = i + 1; \n }\n }\n console.log(`Maximum Subarray Sum: ${max_sum}`);\n console.log(`Indices: ${start} - ${end}`);\n}",
"function summax(n){\n suman=0;\n i=1;\n\n while(suman<=n){\n suman += i;\n i++;\n }\n return i-2;\n }",
"function maxSubArraySum(arr, x) {\n //doSomething\n var max = 0\n var tempSum = 0;\n var maxSum = 0;\n var mover = 0;\n console.log(x + \"is x\")\n console.log(arr.length + \"is length\")\n console.log(arr.slice(mover, x + mover));\n\n while ((mover + x) <= arr.length) {\n tempSum = arr.slice(mover, x + mover).reduce((a, b) => a + b, 0);\n console.log(tempSum)\n if (max < tempSum) {\n max = tempSum\n }\n mover++;\n }\n console.log(max + \" this is max\");\n return max;\n}",
"function kadanesAlgorithm(array) {\n\tlet maxSum = array[0] // -2 \n\tlet currentSum = array[0] // -2 \n\tfor (let i = 1; i < array.length; i++ ) {\n\t\tcurrentSum += array[i]\n\t\tcurrentSum = Math.max(array[i], currentSum)\n\t\tmaxSum = Math.max(currentSum, maxSum) \n\t}\n\treturn maxSum\n}",
"function maxSubsetSumNoAdjacent(array) {\n // edge case, if the array has no length\n if (!array.length) return 0;\n if (array.length === 1) return array[0];\n // create an array that we will push values to as we iterate through the array\n const dynamicArr = array.slice()\n dynamicArr[1] = Math.max(array[0], array[1]) // make sure you start of with hte maximum value -- etch case where there is a skip later on\n // create for loop to iterate through the array, and add value based off the best case scenario (typic)\n for (let i = 2; i < array.length; i++) {\n // take the maximum off array[i] + array[i - 2] versus dynamicArr[i - 1]\n dynamicArr[i] = Math.max(dynamicArr[i] + dynamicArr[i - 2], dynamicArr[i - 1])\n console.log(dynamicArr)\n }\n return dynamicArr[dynamicArr.length - 1]\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the strength of the player | function set_player_strength(Player, hand) {
Player.player_strength = get_hand_strength(hand);
return Player;
} | [
"ChangeStrength(int, int, int) {\n\n }",
"set wavingGrassStrength(value) {}",
"set shadowStrength(value) {}",
"addStrength(num) {\n this.strength = lodash_1.clamp(this.strength + num, 1, this.game.maxWebStrength);\n if (this.load >= this.strength) {\n this.snap();\n }\n }",
"attack(player) {\r\n player.applyDamage(this.strength);\r\n }",
"function updateStrength() {\n\n for (var letter in gameState['usage']) {\n\n var usage = gameState['usage'][letter];\n\n if (usage >= constFactory.USAGE_TIER_0) {\n\n gameState['strength'][letter] = constFactory.STRENGTH_0;\n\n } else if (usage < constFactory.USAGE_TIER_0 &&\n usage >= constFactory.USAGE_TIER_1) {\n\n gameState['strength'][letter] = constFactory.STRENGTH_1;\n\n } else if (usage < constFactory.USAGE_TIER_1 &&\n usage >= constFactory.USAGE_TIER_2) {\n\n gameState['strength'][letter] = constFactory.STRENGTH_2;\n\n } else if (usage < constFactory.USAGE_TIER_2 &&\n usage >= constFactory.USAGE_TIER_3) {\n\n gameState['strength'][letter] = constFactory.STRENGTH_3;\n\n } else {\n\n gameState['strength'][letter] = constFactory.STRENGTH_4;\n\n }\n }\n }",
"function setVibration(strength) {\n if (connected) {\n socket.emit(\"vibration\", {strength: strength});\n }\n console.log(strength);\n}",
"function playerLevelChange() {\n updateProficiency();\n setSkills();\n enableFeats();\n setNewtypePowers();\n addNewtypePowers();\n setMaxMSStats();\n longRest();\n }",
"function useHealth() {\n playerHealth -= 1;\n playerHealth = constrain(playerHealth, 0, playerInitialHealth);\n}",
"function increaseDifficulty(){\n\t\tif(gravitationspeed > 100){\n\t\t\tscoremultiplier+=1;\n\t\t\tgravitationspeed-=100;\n\t\t\t\n\t\t\tAnimationHandler.setGravitationSpeed(gravitationspeed);\n\t\t\tupdateDifficulty();\n\t\t}\n\t}",
"function setDifficulty(){\n if (difficulty === \"easy\"){\n weight = .5\n }\n else if(difficulty === \"medium\"){\n weight = 1\n }\n else{\n weight = 1.5\n }\n}",
"function difficultyIncrease() {\n if (app.difficultyLevel === \"easy\") {\n app.difficultyLevel = \"normal\";\n } else if (app.difficultyLevel === \"normal\") {\n app.difficultyLevel = \"hard\";\n }\n}",
"function weaponstat() {\n damage = 5\n atkspeed = 1\n atkdelay = .1\n sharpness = 0\n strength = 0\n}",
"function changePlayer() {\n player = player + 1;\n }",
"function setupPlayer() {\n playerX = 4 * width / 5;\n playerY = height / 2;\n playerHealth = playerMaxHealth\n preyEaten = 0;\n}",
"function setPlayerHealth(newHealth)\n\t{\n\t\tvar damage = newHealth;\n\n\t\tif(spriteState == SPRITE_STATE.CROUCHING)\n\t\t\tdamage -= 4;\n\n\t\tif(damage < 0)\n\t\t\tdamage = 0;\n\n\t\tplayer.health -= damage;\n\t}",
"function varyPlayerSpeed() {\n if (preyEaten < 10) {\n player.maxSpeed === player.maxSpeed;\n }\n else if (preyEaten < 50) {\n player.maxSpeed += 1;\n }\n else {\n player.maxSpeed += 3;\n }\n}",
"function playerGainHealth(amount) {\r\n\tPLAYER_CURRENT_HEALTH = Math.min(PLAYER_MAX_HEALTH, PLAYER_CURRENT_HEALTH + amount);\r\n\thbCanvas.setVisibility(PLAYER_CURRENT_HEALTH);\r\n}",
"function setupPlayer() {\n playerX = 4 * width / 5;\n playerY = height / 2;\n playerHealth = playerInitialHealth;\n playerSpeed = playerMaxSpeed;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string describing the remote address of a socket. | function describeAddress(socket) {
if (socket.remoteFamily === "IPv6") {
return `[${socket.remoteAddress}]:${socket.remotePort}`;
}
return `${socket.remoteAddress}:${socket.remotePort}`;
} | [
"getMeaningfulIPTo(socket) {\n if (api.isLoopbackAddress(socket)) {\n return '127.0.0.1';\n } else if (api.isPrivateNetwork(socket)) {\n return api.getLocalIP();\n } else {\n return api.getExternalIP();\n }\n }",
"GetRemoteAddr()\n {\n if(this._SocketValid())\n {\n return this._Socket.remoteAddress;\n }\n }",
"get ip() {\n var _a;\n return (_a = this.socket) === null || _a === void 0 ? void 0 : _a.remoteAddress;\n }",
"getIPAddress() {\r\n var interfaces = require('os').networkInterfaces();\r\n for (var devName in interfaces) {\r\n var iface = interfaces[devName];\r\n \r\n for (var i = 0; i < iface.length; i++) {\r\n var alias = iface[i];\r\n if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)\r\n return alias.address;\r\n }\r\n }\r\n \r\n return '0.0.0.0';\r\n }",
"function getIPAddress() {\r\n var interfaces = require('os').networkInterfaces();\r\n for (var devName in interfaces) {\r\n var iface = interfaces[devName];\r\n for (var i = 0; i < iface.length; i++) {\r\n var alias = iface[i];\r\n if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)\r\n return alias.address;\r\n }\r\n }\r\n return '0.0.0.0';\r\n}",
"function getSocketName() {}",
"function getIPAddress() {\n var interfaces = require('os').networkInterfaces();\n for (var devName in interfaces) {\n var iface = interfaces[devName];\n for (var i = 0; i < iface.length; i++) {\n var alias = iface[i];\n if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)\n return alias.address;\n }\n }\n return '0.0.0.0';\n}",
"get address() {\n const state = this[kInternalState];\n if (state.state !== kSocketDestroyed) {\n try {\n return state.udpSocket.address();\n } catch (err) {\n if (err.code === 'EBADF') {\n // If there is an EBADF error, the socket is not bound.\n // Return empty object. Else, rethrow the error because\n // something else bad happened.\n return {};\n }\n throw err;\n }\n }\n return {};\n }",
"function getHostAddress() {\n var i, candidate, nets = require('os').networkInterfaces();\n function filterFunc(item) {\n return item.family === 'IPv4' && !item.internal;\n }\n for (i in nets) {\n if (nets.hasOwnProperty(i)) {\n candidate = nets[i].filter(filterFunc)[0];\n if (candidate) {\n return candidate.address;\n }\n }\n }\n return \"127.0.0.1\";\n }",
"getAddressString () {\n return secUtil.bufferToHex(this.getAddress())\n }",
"inspect() {\n return (\"<Multiaddr \" +\n this.buffer.toString(\"hex\") +\n \" - \" +\n codec.bufferToString(this.buffer) +\n \">\");\n }",
"function get_url() {\n\tswitch (config.socket.type) {\n\t\tcase 'path' :\n\t\t\treturn {\n\t\t\t\tpath : config.socket.path + '/' + app_name + '-' + app_intf + '.sock',\n\t\t\t};\n\n\t\tcase 'net' :\n\t\t\treturn {\n\t\t\t\thost : config.socket.host,\n\t\t\t\tport : config.socket.port,\n\t\t\t\tfamily : 4,\n\t\t\t};\n\t}\n}",
"address() {\n const address = this.server.address();\n const endpoint = typeof address !== \"string\"\n ? (address.address === \"::\" ? \"localhost\" : address.address) + \":\" + address.port\n : address;\n return `${this.protocol}://${endpoint}`;\n }",
"function unix_string_of_inet_addr() {\n unix_ll(\"unix_string_of_inet_addr\", arguments);\n return 0;\n}",
"getRemoteAddress() {\n return this.remoteAddress;\n }",
"function getSocketAddress(){\n if(location.port === '3000') {\n const host = location.host.split(':')[0];\n return 'http://'+host+':8080';\n } else {\n return location.origin;\n }\n}",
"function get_url() {\n\tswitch (config.socket.type) {\n\t\tcase 'path' :\n\t\t\treturn {\n\t\t\t\tpath : config.socket.path + '/bmwi-' + app_intf + '.sock',\n\t\t\t};\n\n\t\tcase 'net' :\n\t\t\treturn {\n\t\t\t\thost : config.socket.host,\n\t\t\t\tport : config.socket.port,\n\t\t\t\tfamily : 4,\n\t\t\t};\n\t}\n}",
"function externalIP() {\n var addrs = os.networkInterfaces();\n var address = '127.0.0.1';\n\n for (var key in addrs) {\n for (var k in addrs[key]) {\n if (addrs[key][k].family == 'IPv4') {\n // Check if loopback address\n var re = /^(127\\.[\\d.]+|[0:]+1|localhost)$/;\n var result = addrs[key][k].address.match(re);\n if (result == null) {\n return addrs[key][k].address;\n }\n }\n }\n }\n\n return address;\n}",
"get address() {\n return this.options.hostAddress.toString();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove product modifiers of specific cart item, based on cart item ID | function removeProductModifier(itemID){
itemModifiers = JSON.parse(window.localStorage.getItem('itemModifiers'))
if (itemID in itemModifiers) {
delete itemModifiers[itemID]
}
window.localStorage.setItem('itemModifiers',JSON.stringify(itemModifiers))
} | [
"function remove_from_cart(product_id) {\n removeProduct(product_id);\n}",
"cartMinusOne(product, id) {\r\n if (product.quantity == 1) {\r\n this.cartRemoveItem(id);\r\n } else {\r\n product.quantity = product.quantity - 1;\r\n }\r\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}",
"removeCartItem(item) {\n Cart.remove(item);\n }",
"function decrease_product_quantity(product_id) {\n let product = recommended_products[product_id];\n let product_quantity = shopping_cart.get(product);\n if (product_quantity != null) {\n product_quantity--;\n shopping_cart.set(product, product_quantity);\n }\n if (product_quantity == 0) {\n shopping_cart.delete(product);\n document.getElementById(`\"shopping-cart-list-item-id-${product_id}\"`).outerHTML = \"\";\n }\n update_cart();\n}",
"static removeCartItem(id) {\n let toBeRemoved = document.getElementById(`cart-item-id-${id}`);\n cartContents.removeChild(toBeRemoved);\n}",
"_initProductRemoveFromCart(event) {\n const product = {\n productId: $(event.currentTarget).data('product-id'),\n attributeId: $(event.currentTarget).data('attribute-id'),\n customizationId: $(event.currentTarget).data('customization-id'),\n };\n\n this.productManager.removeProductFromCart(this.cartId, product);\n }",
"function removeItemFromCart(e) {\n let indexOfProductInCart = itemsInCart.indexOf(products[e.target.dataset.id - 1]);\n\n itemsInCart[indexOfProductInCart].quantity--;\n if (itemsInCart[indexOfProductInCart].quantity === 0) {\n itemsInCart.splice(indexOfProductInCart, 1);\n }\n // Refresh cart\n displayItemsInCart();\n}",
"function rochester_CartRemoveItem() {\n\tjQuery('.woo-cart-item .remove-cart-item').unbind('click').click(function(){\n\t\tvar $this = jQuery(this);\n\t\tvar cart_id = $this.data(\"cart_id\");\n\t\t$this.parent().find('.ajax-loading').show();\n\n\t\tjQuery.ajax({\n\t\t\ttype: 'POST',\n\t\t\tdataType: 'json',\n\t\t\turl: rochester_js_vars.rochester_ajax_url,\n\t\t\tdata: { action: \"rochester_product_remove\",\n\t\t\t\tcart_id: cart_id\n\t\t\t},success: function( response ) {\n\t\t\t\tvar fragments = response.fragments;\n\t\t\t\tvar cart_hash = response.cart_hash;\n\n\t\t\t\tif ( fragments ) {\n\t\t\t\t\tjQuery.each(fragments, function(key, value) {\n\t\t\t\t\t\tjQuery(key).replaceWith(value);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\treturn false;\n\t});\n}",
"function removeQuantityProduct(obj, unity, id) {\n obj.products.forEach(el => {\n if(el.id === id){\n el.quantity -= unity;\n }\n });\n \n localStorage.setItem('allProducts', JSON.stringify(obj));\n}",
"function remove_product(product_id) {\n let product = recommended_products[product_id];\n let product_name = product.name;\n let product_quantity = shopping_cart.get(product);\n let removeConfirmed = confirm(`Confirmation: Remove ${ product_quantity } item(s) of ${ product_name } from cart?`);\n if (removeConfirmed == true) {\n shopping_cart.delete(product);\n document.getElementById(`\"shopping-cart-list-item-id-${product_id}\"`).outerHTML = \"\";\n update_cart();\n }\n}",
"function minusItem() {\n const productId = this.name;\n const cartList = JSON.parse(sessionStorage.getItem(\"shoppingCartItems\"));\n const index = cartList.findIndex(product => product.id == productId);\n cartList.splice(index, 1);\n sessionStorage.setItem(\"shoppingCartItems\", JSON.stringify(cartList));\n shoppingCartCount();\n populateShoppingCartPage();\n}",
"function removeFromCart(img) {\n setCartItems((prevItems) => prevItems.filter((item) => item.id !== img.id));\n }",
"removeFromCart(e) {\n var id = e.currentTarget.getAttribute('data-product-id'); // get product id\n this.toggleProductInCart(id);\n }",
"removeItemsFromCart(cartItem){\n var index = this.cart.items.indexOf(cartItem)\n if(index !== -1){\n this.cart.items.splice(index, 1)\n }\n }",
"function removeFromCart(item) {\n order.removeItem(item);\n vm.openModal.hide();\n }",
"removeItem(id) {\n // The filter method creates a new array with all elements that pass the test implemented by the provided function\n cart = cart.filter((item) => item.id !== id);\n // Change cart values (price and amount)\n this.setCartValues(cart);\n // Save the new cart to the local storage\n Storage.saveCart(cart);\n let button = this.getSingleButton(id);\n // Since we removed the item from the shopping cart, the add to bag button should be enabled and changed to add to cart\n button.disabled = false;\n button.innerHTML = `<i class=\"fa fa-shopping-cart\"></i>add to bag`;\n }",
"function removeItemFromCart(){\n\n}",
"function removePricingLineItemById(itemId) {\r\n InsPanelViewModel.Items.remove(function (item) {\r\n return item.ItemId() === itemId;\r\n });\r\n updateTotalsRow();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables or disables the UI. Typically while the image is uploading. | disableUploadUi(disabled){this.uploadButton.prop('disabled',disabled);this.addButton.prop('disabled',disabled);this.addButtonFloating.prop('disabled',disabled);this.imageCaptionInput.prop('disabled',disabled);this.overlay.toggle(disabled)} | [
"enable() {\r\n if (!this.isEnabled) {\r\n this.isEnabled = true;\r\n this.show();\r\n }\r\n }",
"function enableImageUI(layer) {\n $imageViewer.find('.imageLayers div[id=\"imageLayer_' + layer.id + '\"] ul')\n .find('button, input').each(function () {\n // Don't enable image processing for not fits files\n if (!$(this).hasClass('fitsUnavailable')) {\n $(this).removeAttr('disabled').button('refresh');\n }\n });\n }",
"enable() {\n if (this.toolbarBtn && this.toolbarBtnImage) {\n this.restoreState();\n }\n }",
"enable() {\n this.enabled = true;\n }",
"load() {\r\n if (this.isEnabled()) {\r\n this.addUi();\r\n }\r\n }",
"function uiEnableButtons() {\n const appendButtonElement = document.getElementById('selectfile-append');\n if (appendButtonElement) {\n appendButtonElement.classList.remove('disabled');\n }\n const replaceButtonElement = document.getElementById('selectfile-replace');\n if (replaceButtonElement) {\n replaceButtonElement.classList.remove('disabled');\n }\n}",
"enable () {\n this.triggerAll(function (formElement, UIElement) {\n formElement.disabled = false;\n UIElement.classList.remove(this.options.disabledClass);\n }.bind(this));\n }",
"function enableUploadButton() {\n $('#upload-button').prop(\"disabled\", false);\n}",
"function updateSaveButtonEnabledStatus() {\n\t\tif (getActiveTabType() == \"curated\" || (getActiveTabType() == \"custom\" && imageAcceptedStatus)) {\n\t\t\t$(\"#save\").prop(\"disabled\", false);\n\t\t} else {\n\t\t\t$(\"#save\").prop(\"disabled\", true);\n\t\t}\n\t}",
"enable() {\n this._status = true;\n }",
"enable() {\n if (this.ready) {\n this.disabled = false;\n this.$cropper.removeClass(CLASS_DISABLED);\n }\n }",
"editImages() {\n this.editDialogVisible = true;\n }",
"enable() {\n this.enabled = true;\n this.redrawTheme();\n }",
"enable() {\n this.setDisabled(false);\n if (this.getInputElement()) {\n this.getInputElement().removeAttribute('disabled');\n this.getInputElement().setAttribute('style', this.style);\n }\n }",
"function disableUploadBTN(){\n\t$('#uploadBTN').val(\"Uploading...\");\n\t$('#uploadBTN').prop(\"disabled\", true);\n\t$('#uploadBTN').removeClass(\"enabled\");\n\t$('#uploadBTN').addClass(\"disabled\");\n}",
"function ksfLayout_setUploadButtonDisabled(state)\n{\n\t$('#uploadModal').find('[value=\"upload\"]').prop('disabled', state);\n}",
"function toggleUploading(show) {\n uploadImageLabelEl.classList.toggle('uploading', show);\n }",
"function update_upload_button() {\n if (!selected_file || !$(\"#upload-type\").val())\n $(\"#upload-button\").attr(\"disabled\", \"disabled\");\n else\n $(\"#upload-button\").removeAttr(\"disabled\");\n }",
"enable() {\n this.fire_(Events.ENABLE);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the symbol with the given name. | function lisp_intern(name) {
var native_string = lisp_string_native_string(name);
var symbol = lisp_symbols_table[native_string];
if (typeof(symbol) !== "undefined") {
return symbol;
} else {
symbol = lisp_make_symbol_do_not_call(name);
lisp_symbols_table[native_string] = symbol;
return symbol;
}
} | [
"_getSymbol(name){\n if(!this.__symbols[name]){\n this.__symbols[name] = Symbol(name);\n }\n return this.__symbols[name];\n }",
"symbol(name, searchContext) {\r\n return this.symbols(searchContext)[name];\r\n }",
"function getSymbolValue(state, name) {\n if ((0, labels_1.isLocalLabel)(name)) {\n if (!state.currentLabel) {\n (0, errors_1.throwError)(\"Local label \" + name + \" cannot be referenced in the current scope\", state);\n }\n var localTable = state.localSymbols[state.currentLabel];\n if (localTable && Object.prototype.hasOwnProperty.call(localTable, name)) {\n return localTable[name];\n }\n return null;\n }\n if ((0, labels_1.isStaticLabel)(name)) {\n var staticTable = getCurrentStaticSymbols(state);\n if (Object.prototype.hasOwnProperty.call(staticTable, name)) {\n return staticTable[name];\n }\n return null;\n }\n if (Object.prototype.hasOwnProperty.call(state.symbols, name)) {\n return state.symbols[name];\n }\n return null;\n}",
"function symbol(name){\r\n return lexeme(string(name));\r\n}",
"static create(name) {\n return new TypedSymbol(name);\n }",
"static tryDecodeWellKnownSymbolName(name) {\n const match = TypeScriptHelpers._wellKnownSymbolNameRegExp.exec(name);\n if (match) {\n const identifier = match[1];\n return `[Symbol.${identifier}]`;\n }\n return undefined;\n }",
"getLocal(name) {\r\n const locals = this._getCompilerLocals();\r\n if (locals == null)\r\n return undefined;\r\n const tsSymbol = locals.get(name);\r\n return tsSymbol == null ? undefined : this._context.compilerFactory.getSymbol(tsSymbol);\r\n }",
"getSymbolByName(path, identifier) {\n if (!this.files.has(path)) {\n return null;\n }\n const file = this.files.get(path);\n if (!file.has(identifier)) {\n return null;\n }\n return file.get(identifier);\n }",
"getSymbol() {\r\n const boundSymbol = this.compilerNode.symbol;\r\n if (boundSymbol != null)\r\n return this._context.compilerFactory.getSymbol(boundSymbol);\r\n const typeChecker = this._context.typeChecker;\r\n const typeCheckerSymbol = typeChecker.getSymbolAtLocation(this);\r\n if (typeCheckerSymbol != null)\r\n return typeCheckerSymbol;\r\n const nameNode = this.compilerNode.name;\r\n if (nameNode != null)\r\n return this._getNodeFromCompilerNode(nameNode).getSymbol();\r\n return undefined;\r\n }",
"getSymbol(symbol) {\r\n return this.symbolCache.getOrCreate(symbol, () => new compiler_1.Symbol(this.context, symbol));\r\n }",
"function Sym(s) {\n if (!(s in symbol_table)) {\n symbol_table[s] = new Symb(s);\n }\n return symbol_table[s];\n}",
"function getSymbol(id) {\n // Get the symbol using Symbol.for (to avoid problems with multiple library copies in node_module),\n // and scope it with a prefix (to avoid name collisions).\n return Symbol.for(`github:robophred/node-microinject::${id}`);\n}",
"function getUniqueSymbol (symbolName = 'symbol') {\n if( typeof getUniqueSymbol.counter == 'undefined' ) {\n getUniqueSymbol.counter = 0;\n }\n return symbolName + '.' + getUniqueSymbol.counter++;\n}",
"function Symbol(namespace, name) {\n // If called as function, try to pull an existing interned symbol\n // from the pool\n if (!(this instanceof Symbol)) {\n var nsname = joinNamespace(namespace, name);\n var sym = pool[nsname];\n\n if (!sym) {\n /* jshint ignore:start */\n sym = new Symbol(namespace, name);\n /* jshint ignore:end */\n // Interned symbols are immutable\n Object.freeze(sym);\n pool[sym.valueOf()] = sym;\n }\n\n return sym;\n }\n\n var parts = splitNamespacedName(namespace, name);\n\n // Public: Returns the String namespace.\n this.namespace = parts[0];\n\n // Public: Returns the String name.\n this.name = parts[1];\n }",
"function lookup (name) {\n return globalScope[name];\n }",
"function symbol () {}",
"getMember(name) {\r\n if (this.compilerSymbol.members == null)\r\n return undefined;\r\n const tsSymbol = this.compilerSymbol.members.get(name);\r\n return tsSymbol == null ? undefined : this._context.compilerFactory.getSymbol(tsSymbol);\r\n }",
"function lookupSymbol(symbol) {\n var i;\n\n for (i = 1; i < element(1,\"max\"); i++) {\n if ( element(i,\"symbol\") == symbol )\n return i;\n }\n return 0;\n }",
"static getByName(_name) {\n return Character.characters.get(_name);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the kernelspec for a kernel. | function getKernelSpec(kernel, baseUrl, ajaxSettings) {
var url = utils.urlPathJoin(baseUrl, KERNELSPEC_SERVICE_URL, encodeURIComponent(kernel.name));
ajaxSettings = ajaxSettings || {};
ajaxSettings.dataType = 'json';
ajaxSettings.cache = false;
return utils.ajaxRequest(url, ajaxSettings).then(function (success) {
if (success.xhr.status !== 200) {
return utils.makeAjaxError(success);
}
var data = success.data;
try {
validate.validateKernelSpecModel(data);
}
catch (err) {
return utils.makeAjaxError(success, err.message);
}
return data.spec;
}, onKernelError);
} | [
"function getKernelSpecs(options) {\n if (options === void 0) { options = {}; }\n var baseUrl = options.baseUrl || utils.getBaseUrl();\n var url = utils.urlPathJoin(baseUrl, KERNELSPEC_SERVICE_URL);\n var ajaxSettings = utils.copy(options.ajaxSettings || {});\n ajaxSettings.method = 'GET';\n ajaxSettings.dataType = 'json';\n return utils.ajaxRequest(url, ajaxSettings).then(function (success) {\n if (success.xhr.status !== 200) {\n return utils.makeAjaxError(success);\n }\n var data = success.data;\n if (!data.hasOwnProperty('kernelspecs')) {\n return utils.makeAjaxError(success, 'No kernelspecs found');\n }\n var keys = Object.keys(data.kernelspecs);\n for (var i = 0; i < keys.length; i++) {\n var ks = data.kernelspecs[keys[i]];\n try {\n validate.validateKernelSpecModel(ks);\n }\n catch (err) {\n // Remove the errant kernel spec.\n console.warn(\"Removing errant kernel spec: \" + keys[i]);\n delete data.kernelspecs[keys[i]];\n }\n }\n keys = Object.keys(data.kernelspecs);\n if (!keys.length) {\n return utils.makeAjaxError(success, 'No valid kernelspecs found');\n }\n if (!data.hasOwnProperty('default') ||\n typeof data.default !== 'string' ||\n !data.kernelspecs.hasOwnProperty(data.default)) {\n data.default = keys[0];\n console.warn(\"Default kernel not found, using '\" + keys[0] + \"'\");\n }\n return data;\n });\n}",
"get defaultKernelName() {\n let spec = this.metadata.get('kernelspec');\n return spec ? spec.name : '';\n }",
"get defaultKernelName() {\r\n let spec = this.metadata.get('kernelspec');\r\n return spec ? spec.name : '';\r\n }",
"get defaultKernelName() {\n const spec = this.metadata.get('kernelspec');\n return spec ? spec.name : '';\n }",
"getSpec() {\n if (this._specPromise) {\n return this._specPromise;\n }\n this._specPromise = Private.findSpecs(this.serverSettings).then(specs => {\n return specs.kernelspecs[this._name];\n });\n return this._specPromise;\n }",
"_updateSpec(kernel) {\r\n kernel.getSpec().then(spec => {\r\n if (this.isDisposed) {\r\n return;\r\n }\r\n this.model.metadata.set('kernelspec', {\r\n name: kernel.name,\r\n display_name: spec.display_name,\r\n language: spec.language\r\n });\r\n });\r\n }",
"static get kernel() { return kernel_; }",
"get specs() {\n return this.manager.services.kernelspecs.specs;\n }",
"getKernelPreference(path, widgetName, kernel) {\n widgetName = widgetName.toLowerCase();\n let widgetFactory = this._widgetFactories[widgetName];\n if (!widgetFactory) {\n return void 0;\n }\n let modelFactory = this.getModelFactory(widgetFactory.modelName || 'text');\n if (!modelFactory) {\n return void 0;\n }\n let language = modelFactory.preferredLanguage(coreutils_1.PathExt.basename(path));\n let name = kernel && kernel.name;\n let id = kernel && kernel.id;\n return {\n id,\n name,\n language,\n shouldStart: widgetFactory.preferKernel,\n canStart: widgetFactory.canStartKernel\n };\n }",
"get kernelDisplayName() {\n let kernel = this.kernel;\n if (!kernel) {\n return 'No Kernel!';\n }\n let specs = this.manager.specs;\n if (!specs) {\n return 'Unknown!';\n }\n let spec = specs.kernelspecs[kernel.name];\n return spec ? spec.display_name : kernel.name;\n }",
"get kernel() {\n return this._kernel;\n }",
"get kernel() {\n return this._session ? this._session.kernel : null;\n }",
"function validateKernelSpec(info) {\n var err = new Error(\"Invalid KernelSpec Model\");\n if (!info.hasOwnProperty('name') || typeof info.name !== 'string') {\n throw err;\n }\n if (!info.hasOwnProperty('spec') || !info.hasOwnProperty('resources')) {\n throw err;\n }\n var spec = info.spec;\n if (!spec.hasOwnProperty('language') || typeof spec.language !== 'string') {\n throw err;\n }\n if (!spec.hasOwnProperty('display_name') ||\n typeof spec.display_name !== 'string') {\n throw err;\n }\n if (!spec.hasOwnProperty('argv') || !Array.isArray(spec.argv)) {\n throw err;\n }\n}",
"async getKernel() {\n const { serverSettings, kernelModel } = await this.getKernelModel()\n return await Kernel.connectTo(kernelModel, serverSettings)\n }",
"function getDefaultKernel(options) {\n var specs = options.specs, preference = options.preference;\n var name = preference.name, language = preference.language, shouldStart = preference.shouldStart, canStart = preference.canStart;\n if (shouldStart === false || canStart === false) {\n return null;\n }\n if (!name && !language) {\n return null;\n }\n // Look for an exact match of a spec name.\n for (var specName in specs.kernelspecs) {\n if (specName === name) {\n return name;\n }\n }\n // Bail if there is no language.\n if (!language) {\n return null;\n }\n // Check for a single kernel matching the language.\n var matches = [];\n for (var specName in specs.kernelspecs) {\n var kernelLanguage = specs.kernelspecs[specName].language;\n if (language === kernelLanguage) {\n matches.push(specName);\n }\n }\n if (matches.length === 1) {\n var specName = matches[0];\n console.log('No exact match found for ' + specName +\n ', using kernel ' + specName + ' that matches ' +\n 'language=' + language);\n return specName;\n }\n // No matches found.\n return null;\n }",
"function getKernelSearch(session) {\n return {\n specs: session.manager.specs,\n sessions: session.manager.running(),\n preference: session.kernelPreference\n };\n }",
"FindKernel() {}",
"get kernelName() {\n return this._kernelName;\n }",
"get kernelId() {\n return this.getStringAttribute('kernel_id');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PRIVATE MODULE METHODS An example of a private method. Feel free to remove this. | function modulePrivateMethod () {
return;
} | [
"function internalPrivateThing() {}",
"function Utils() {\n\t\n }",
"function LeathermanModule() {\n }",
"function _privateFn(){}",
"function Module(){}",
"function Helpers() {\r\n }",
"protected internal function m252() {}",
"function Helpers() {\n}",
"function constructor()\n {\n //write your code here\n\n //please note that it is a private function, so you can call the public fields or methods only\n //do the private visiting in the following {}\n }",
"_privateMethod() {\n\n }",
"init() {\n\t\t\t// Should be implemented\n\t\t}",
"function privateWithExample() {}",
"function SubProvider() {\n\n}",
"function _Util() {\n}",
"function SubProvider() {\n\n\t}",
"function FooBar() {\n // TODO: implement this module\n}",
"function SubProvider() { }",
"function SubProvider() {\n\t\n\t}",
"function ModulationSource() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the minimum axisaligned 3D boundary enclosing the given 3D points. | points3ToAABB3(points, aabb = math.AABB3()) {
let xmin = math.MAX_DOUBLE;
let ymin = math.MAX_DOUBLE;
let zmin = math.MAX_DOUBLE;
let xmax = -math.MAX_DOUBLE;
let ymax = -math.MAX_DOUBLE;
let zmax = -math.MAX_DOUBLE;
let x;
let y;
let z;
for (let i = 0, len = points.length; i < len; i++) {
x = points[i][0];
y = points[i][1];
z = points[i][2];
if (x < xmin) {
xmin = x;
}
if (y < ymin) {
ymin = y;
}
if (z < zmin) {
zmin = z;
}
if (x > xmax) {
xmax = x;
}
if (y > ymax) {
ymax = y;
}
if (z > zmax) {
zmax = z;
}
}
aabb[0] = xmin;
aabb[1] = ymin;
aabb[2] = zmin;
aabb[3] = xmax;
aabb[4] = ymax;
aabb[5] = zmax;
return aabb;
} | [
"function minimum3 (x,y,z) {\n return Math.min(x, y, z);\n}",
"function bezier_bounds(p0, p1, p2, p3, width)\n{\n\t// This computes the coefficients of the derivative of the bezier curve.\n\t// We will use this to compute the zeroes to get the maxima.\n\tlet a = -p0 + 3 * p1 - 3 * p2 + p3;\n\tlet b = 2 * p0 - 4 * p1 + 2 * p2;\n\tlet c = p1 - p0;\n\n\t// Compute the discriminant.\n\tlet d = b*b - 4*a*c;\n\t// If there are no maxima or minima, just return the end points.\n\tif(d < 0 || a == 0)\n\t{\n\t\treturn {min: Math.min(p0, p3) - width, max: Math.max(p0, p3) + width};\n\t}\n\t// Square root the discriminant so we don't need to recompute it.\n\td = Math.sqrt(d);\n\t// Compute the \"time\" of the critical points by solving the quadrating equation.\n\tlet crit1 = (-b + d) / (2*a);\n\tlet crit2 = (-b - d) / (2*a);\n\t// Use the \"time\" of the critical points to compute the critical points themselves..\n\tif(crit1 >= 0 && crit1 <= 1)\n\t{\n\t\tcrit1 = compute_bezier(p0, p1, p2, p3, crit1, 1 - crit1);\n\t}\n\telse\n\t{\n\t\tcrit1 = undefined;\n\t}\n\tif(crit2 >= 0 && crit2 <= 1)\n\t{\n\t\tcrit2 = compute_bezier(p0, p1, p2, p3, crit2, 1 - crit2);\n\t}\n\telse\n\t{\n\t\tcrit2 = undefined;\n\t}\n\n\t// Start by just using the end points as the bounds.\n\tlet m = Math.min(p0, p3);\n\tlet M = Math.max(p0, p3);\n\t// If the critical point is valid, ensure it is included in the bounds.\n\tif(crit1)\n\t{\n\t\tm = Math.min(m, crit1);\n\t\tM = Math.max(M, crit1);\n\t}\n\t// If the critical point is valid, ensure it is included in the bounds.\n\tif(crit2)\n\t{\n\t\tm = Math.min(m, crit2);\n\t\tM = Math.max(M, crit2);\n\t}\n\t// Return the bounds.\n\treturn {min: m - width, max: M + width};\n}",
"findClosestPoint(pt){\n let closestPt = vec3.create();\n let closestDist = Number.POSITIVE_INFINITY;\n for(let i = 0; i < this.boundaryList.length; ++i){\n let newPt = {pos: vec3.create()};\n let dist = this.distToSegmentSquared(pt, this.boundaryList[i][0], this.boundaryList[i][1], newPt);\n if(dist < closestDist){\n closestDist = dist;\n closestPt = newPt.pos;\n }\n }\n\n return closestPt;\n }",
"findLowestSurrounding(x, y, weight) {\n\n let lowestCoordinate = false;\n\n [{x: 0, y: -1}, {x: 1, y: 0}, {x: 0, y: 1}, {x: -1, y: 0}].forEach((offset) => {\n\n // Find coordinate on given point (if exists).\n const candidate = this.getCoordinateFromQueue(x + offset.x, y + offset.y);\n\n if (candidate) {\n if (candidate.weight < weight) {\n lowestCoordinate = candidate;\n }\n }\n\n });\n\n return lowestCoordinate;\n\n }",
"_clampInBounds() {\n const offsetMatrix = XR.getOffsetMatrix();\n const position = new Vector3().setFromMatrixPosition(offsetMatrix);\n\n let inBounds = false;\n\n const boundData = {\n distance: Number.MAX_SAFE_INTEGER,\n bound: null\n };\n\n for (let i = 0; i < this.bounds.length; i++) {\n const bound = this.bounds[i];\n const distance = bound.distanceToPoint(position);\n\n // If within a boundary, cease bounds checking\n if (distance === 0) {\n inBounds = true;\n break;\n }\n\n // Get closest boundary if out of bounds\n if (distance < boundData.distance) {\n boundData.distance = distance;\n boundData.bound = bound;\n }\n }\n\n // If user is out of bounds, clamp position to closest boundary\n if (!inBounds && boundData.bound) {\n const clampedPos = new Vector3();\n boundData.bound.clampPoint(position, clampedPos);\n offsetMatrix.setPosition(clampedPos);\n XR.setOffsetMatrix(offsetMatrix);\n }\n }",
"function getMidPointBetweenTwoPoints(x0,y0,z0, x1,y1,z1)\n{\n var x = (x0 + x1) / 2;\n var y = (y0 + y1) / 2;\n var z = (z0 + z1) / 2;\n\n var midPoint = new Array(x, y, z);\n // returns [x,y,z]\n return midPoint;\n //console.log(midPoint);\n}",
"function lower_bound(a, b, c, k) {\n let s = 0;\n let e = Math.ceil(Math.sqrt(k));\n while (s <= e) {\n let mid = s + Math.floor((e - s) / 2);\n if (poly(a, b, c, mid) >= k) {\n e = mid - 1;\n } else {\n s = mid + 1;\n }\n }\n return s;\n}",
"function findBoundary( x, lower, upper ) {\n\t\treturn x < lower? lower : x > upper? upper : false;\n\t}",
"static calcCenter(point1, point2, point3) {\n let ma = (point2[1] - point1[1]) / (point2[0] - point1[0])\n let mb = (point3[1] - point2[1]) / (point3[0] - point2[0])\n let counter = 3\n while (\n counter > 0 &&\n (!isFinite(ma) || !isFinite(mb) || ma === mb || ma === 0 || mb === 0)\n ) {\n let helpPoint = point1.slice(0)\n point1 = point2.slice(0)\n point2 = point3.slice(0)\n point3 = helpPoint\n ma = (point2[1] - point1[1]) / (point2[0] - point1[0])\n mb = (point3[1] - point2[1]) / (point3[0] - point2[0])\n counter--\n }\n let centerX =\n (ma * mb * (point1[1] - point3[1]) +\n mb * (point1[0] + point2[0]) -\n ma * (point2[0] + point3[0])) /\n (2 * (mb - ma))\n\n let centerY =\n -(centerX - (point1[0] + point2[0]) / 2) / ma +\n (point1[1] + point2[1]) / 2\n return [centerX, centerY]\n }",
"closestPoint(points) {\n var minDist = Infinity;\n var minPoint = null;\n for (var i = 0; i < points.length; i++) {\n var dist = this.minus(points[i]).length();\n if (dist <= minDist) {\n minDist = dist;\n minPoint = points[i];\n }\n }\n return minPoint;\n }",
"function minAreaRect(pt) {\n var u = [], c, numPts = pt.length;\n var minArea = Number.MAX_VALUE;\n\n // Loop through all edges; j trails i by 1, modulo numPts\n for (var i = 0, j = numPts - 1; i < numPts; j = i, i++) {\n // Get current edge e0 (e0x,e0y), normalized\n var e0 = vec3.subtract(pt[i], pt[j], vec3.create());\n e0 = vec3.normalize(e0);\n\n // Get an axis e1 orthogonal to edge e0\n var e1 = vec3.create([e0[1], e0[0], 0]); // = Perp2D(e0)\n\n // Loop through all points to get maximum extents\n var min0 = Number.MAX_VALUE,\n min1 = Number.MAX_VALUE,\n max0 = Number.MIN_VALUE,\n max1 = Number.MIN_VALUE;\n var min0d, min1d, max0d, max1d;\n\n for (var k = 0; k < numPts; k++) {\n // Project points onto axes e0 and e1 and keep track\n // of minimum and maximum values along both axes\n var d = vec3.subtract(pt[k], pt[j], vec3.create());\n\n var dot = vec3.dot(d, e0);\n\n if (dot < min0) {\n min0 = dot;\n min0d = d;\n }\n if (dot > max0) {\n max0 = dot;\n max0d = d;\n }\n\n dot = vec3.dot(d, e1);\n\n if (dot < min1) {\n min1 = dot;\n min1d = d;\n }\n if (dot > max1) {\n max1 = dot;\n max1d = d;\n }\n }\n var area = (max0 - min0) * (max1 - min1);\n\n // If best so far, remember area, center, and axes\n if (area < minArea) {\n minArea = area;\n\n c = vec3.add(vec3.scale(e0, (min0 + max0)), vec3.scale(e1, (min1 + max1)));\n c = vec3.add(pt[j], vec3.scale(c, 0.5));\n\n u[0] = e0;\n u[1] = e1;\n }\n }\n return [minArea, c, u, [min0d, max0d, min1d, max1d]];\n}",
"boundX(){\n if(this.bounds === null) return;\n if(this.pos[0] < this.bounds[0]) this.pos[0] = this.bounds[0];\n let edge = this.bounds[0] + this.bounds[2];\n if(this.pos[0] > edge) this.pos[0] = edge;\n }",
"function calcAABB(points) {\n if (points && points.length > 0) {\n var min = {x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY };\n var max = {x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY };\n for (var i = 0, l = points.length; i < l; i++) {\n var point = points[i];\n var x = point[0];\n var y = point[1];\n if (x < min.x) min.x = x;\n else if (x > max.x) max.x = x;\n\n if (y < min.y) min.y = y;\n else if (y > max.y) max.y = y;\n }\n\n var w = Math.abs(max.x - min.x);\n var h = Math.abs(max.y - min.y);\n\n return {\n x: min.x,\n y: min.y,\n center: {x: min.x + w / 2, y: min.y + h / 2},\n width: w,\n height: h\n };\n } else return null;\n }",
"function boundPoints(points) {\n\t var bounds = new Array(points.length)\n\t for(var i=0; i<points.length; ++i) {\n\t var p = points[i]\n\t bounds[i] = [ p[0], p[1], p[0], p[1] ]\n\t }\n\t return bounds\n\t}",
"function getGazevect(keypoints) {\n if(keypoints) {\n let xNose = keypoints[0*3];\n let yNose = keypoints[0*3+1];\n let xNeck = keypoints[1*3];\n let yNeck = keypoints[1*3+1];\n var xMid = keypoints[8*3];\n var yMid = keypoints[8*3+1];\n let bbox = getBBox(keypoints);\n let vect = createVector(xMid - xNeck,0).normalize();\n if(bbox && (bbox[2] - bbox[0]) > (bbox[3]- bbox[1])) {\n // console.log(p5.Vector.mult(createVector(xNose-xNeck, yNeck-yNeck),vect.x),createVector(xNose-xNeck, yNeck-yNeck));\n return createVector(0);\n }\n return createVector(xNose-xNeck, yNeck-yNeck);\n } else {\n return createVector(0);\n }\n}",
"ClosestPointOnBounds() {}",
"function calcConstrainedMinPoint(point, length, progress, constraints, elastic) {\n // Calculate a min point for this axis and apply it to the current pointer\n var min = point - length * progress;\n return constraints ? applyConstraints(min, constraints, elastic) : min;\n}",
"lowest(arr, x, radius) {\n let n = arr[x];\n let len = arr.length;\n let index = x;\n for (let i = -radius; i < radius; i++) {\n if (x + i >= 0 && x + i < len) {\n if (n >= arr[x + i]) {\n index = x + i;\n n = arr[index]\n }\n }\n }\n return { x: index, y: n };\n }",
"function calcConstrainedMinPoint(point, length, progress, constraints, elastic) {\n\t // Calculate a min point for this axis and apply it to the current pointer\n\t var min = point - length * progress;\n\t return constraints ? applyConstraints(min, constraints, elastic) : min;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the stops as an array of Stops object (array of Jsons) by reading the stops table | function getStops() {
stopsTableRows = getStopsTableRows()
stops = []
for (var i = 0; i < stopsTableRows.length; i++) {
row = stopsTableRows[i]
rowID = row.id
airportInputID = getAirportInputID(rowID)
daysInputID = getDaysInputID(rowID)
airport = $("#" + airportInputID).val()
days = $("#" + daysInputID).val()
var stopObject = Object()
stopObject.airport = airport
stopObject.days = days
stops.push(stopObject)
}
return stops
} | [
"function getStops () {\n return StopsForage.get();\n }",
"_getStops() {\n const properties = this._properties;\n const stopsProperties = properties.stops;\n const defaultStopCount = 10;\n let stops = null;\n\n // If stop properties are defined\n if (stopsProperties) {\n // Case: Stops are defined using dates\n if (stopsProperties.dates) {\n stops = {};\n const dates = [];\n let momentObj;\n stopsProperties.dates.forEach((dateString) => {\n momentObj = moment(dateString).utc();\n // Push valid dates\n if (momentObj?.isValid()) {\n dates.push(momentObj.toDate());\n }\n // Warn for invalid dates and skip date\n else {\n console.warn(\"Invalid date stop definition. Skip value.\");\n }\n });\n stops.dates = dates;\n }\n // Check if stops are defined using moments and calculations\n else if (stopsProperties.moment) {\n stops = {};\n const dates = [];\n let momentObj = moment().utc();\n stopsProperties.moment.forEach((timeStop) => {\n // Check if leading timeStop element is a string\n if (typeof timeStop === 'string') {\n momentObj = moment(timeStop).utc();\n if (momentObj?.isValid()) {\n dates.push(momentObj.toDate());\n } else {\n momentObj = moment.utc();\n console.warn(\"Invalid stop definition at start of the array. Use current time.\");\n }\n }\n // stop is an array\n else if (Array.isArray(timeStop)) {\n timeStop.forEach((time) => {\n try {\n momentObj[time.method].apply(momentObj, time.args);\n if (momentObj?.isValid()) {\n dates.push(momentObj.toDate());\n }\n } catch {\n console.warn(\"Invalid stop definition in moment array. Skip array entry.\");\n }\n });\n }\n // stop is a single object\n else {\n try {\n momentObj[timeStop.method].apply(momentObj, timeStop.args);\n if (momentObj?.isValid()) {\n dates.push(momentObj.toDate());\n }\n } catch {\n console.warn(\"Invalid stop definition in moment array. Skip array entry.\");\n }\n }\n });\n stops.dates = dates;\n }\n // Case: Stops are defined by count or interval\n else {\n // Case: Stops defined by count\n if (stopsProperties.count) {\n stops = {};\n stops.count = stopsProperties.count || defaultStopCount;\n }\n // Case: Stops defined by interval\n else if (stopsProperties.interval) {\n stops = {};\n stops.interval = {\n value: stopsProperties.interval.value || 1,\n unit: stopsProperties.interval.unit || \"years\"\n };\n }\n // Case: No definition provided. Use 10 stops instead\n else {\n stops = {};\n stops.count = defaultStopCount;\n }\n // Case: Stops defined by start and end time and interval/count\n if (stopsProperties.timeExtent && stops) {\n let start = null;\n let end = null;\n if (stopsProperties.timeExtent.start) {\n start = moment(stopsProperties.timeExtent.start);\n if (!start?.isValid()) {\n start = moment.utc();\n console.warn(\"No valid configuration for stop timeExtent start. Using current time.\");\n }\n }\n if (stopsProperties.timeExtent.end) {\n end = moment(stopsProperties.timeExtent.end);\n if (end && end.isValid() === false) {\n end = moment.utc();\n console.warn(\"No valid configuration for stop timeExtent end. Using current time.\");\n }\n }\n if (start && end) {\n stops.timeExtent = {\n start: start.toDate(),\n end: end.toDate()\n };\n }\n }\n }\n }\n return stops;\n }",
"function getStops(callback) {\n\tjQuery.getJSON(\"http://m.gatech.edu/api/buses/stop\",\n\t\tfunction(stopInfos) {\n\t\t\tfor (var i=0;i<stopInfos.length;i++) {\n stops.push(new RouteStop(stopInfos[i].route_id,stopInfos[i].stop_id,\n\t\t\t\t\tstopInfos[i].stop_name,L.latLng(stopInfos[i].stop_lat,\n\t\t\t\t\tstopInfos[i].stop_lon),stopInfos[i].trip_id,\n\t\t\t\t\tstopInfos[i].reference_stop_id));\n\t\t\t}\n\t\t\tfor (var i=0;i<stops.length;i++) {\n\t\t\t\tstops[i].draw(map);\n\t\t\t}\n //populateLayers\n callback();\n\t\t}\n\t).fail(function() {\n\t\terrLog(\"Unable to fetch Bus Stop info\");\n\t});\n}",
"async function stopsTxt () {\n const stops = []\n const stopsDir = `${__dirname}/chamonix/busstops`;\n const stopsFiles = await readdirPromise(stopsDir)\n\n for (const lineFile of stopsFiles) {\n const file = `${__dirname}/chamonix/busstops/${lineFile}`\n const lineExcel = xlsx.parse(file)\n const lineSheet = lineExcel[0].data\n // Remove header\n lineSheet.shift()\n const rows = lineSheet.filter((row) => row.length)\n\n for (const row of rows) {\n const hasStop = stops.find((stop) => stop[1].trim() === row[1].trim())\n if (!hasStop) stops.push(row)\n }\n }\n\n // const stopNames = stops.map((stop) => stop[1]).sort()\n // console.log(stopNames)\n\n return stops.map((stop, index) => {\n const [ , stop_name, stop_lat, stop_lon ] = stop\n return [\n index, // stop_id\n stop_name,\n '', // stop_desc\n stop_lat,\n stop_lon,\n '', //zone_id,\n '' //stop_url\n ]\n })\n}",
"function getStops(trainType) {\n let stations = [];\n // Kodama stops at all stops currently\n if (trainType === \"Kodama\") {\n stations = [\n \"Tokyo\",\n \"Shinagawa\",\n \"Shin-Yokohama\",\n \"Odawara\",\n \"Atami\",\n \"Mishima\",\n \"Shin-Fuji\",\n \"Shizouka\",\n \"Kakegawa\",\n \"Hamamatsu\",\n \"Toyohashi\",\n \"Mikawa-Anjō\",\n \"Nagoya\",\n \"Gifu-hashima\",\n \"Maibara\",\n \"Kyoto\",\n \"Shin-Ōsaka\"\n ];\n // Hikari stops at only certain stops currenty\n } else if (trainType === \"Hikari\") {\n stations = [\n \"Tokyo\",\n \"Shinagawa\",\n \"Shin-Yokohama\",\n \"Odawara\",\n \"Atami\",\n \"Mishima\",\n \"Shizouka\",\n \"Hamamatsu\",\n \"Nagoya\",\n \"Maibara\",\n \"Kyoto\",\n \"Shin-Ōsaka\"\n ];\n } else {\n // handle unknown trains\n stations = [];\n }\n // get all of the stops and their mile locations\n const stops = trainMap();\n // map the available stops into a train map\n let mappedStops = stations.reduce((acc, cur) => {\n if (stops[cur] !== undefined) {\n acc[cur] = stops[cur];\n }\n return acc;\n }, {});\n // return the new mapped stops\n return mappedStops;\n}",
"function listStops(subway, line) {\n for (i=0; i < subway.length; i++) {\n if (line === subway[i].name) {\n var stops = subway[i].stops;\n }\n };\n return stops.toString();\n}",
"function getStops(route,direction){\n return request('getstops', `rt=${route}&dir=${direction}`);\n }",
"function getStops(route) {\n\n var defer = $q.defer();\n\n var _handleRes = function _handleRes(tx, result) {\n\n var data = result.rows.item(0);\n var stops = [];\n\n // Get stop data fro every stop\n sortStops(data.stops).forEach(function (number) {\n get('stops', { number: number }).then(function (result) {\n return stops.push(result[0]);\n });\n });\n\n data.stops = stops;\n data.favourite = parseInt(data.favourite);\n return defer.resolve(data);\n };\n\n var _handleTx = function _handleTx(tx) {\n tx.executeSql('SELECT * FROM routes WHERE id = ?', [route.id], _handleRes, function (tx, err) {\n return defer.reject(err);\n });\n };\n\n db.transaction(_handleTx, function (tx, err) {\n return defer.reject(err);\n });\n return defer.promise;\n }",
"async function getListOfStops() {\n return await database.getStops();\n}",
"getStopRoutes(stopID) {\n let params = new URLSearchParams();\n params.set('key', key);\n params.set('stop_id', stopID);\n return this.http.get(base+`GetRoutesByStop`, {search: params})\n .map(res => res.json())\n .catch(this.doError);\n }",
"function parseStops(data, callback) {\n arrivalsObj = {};\n for (let bus of data.resultSet.arrival) {\n let arrival_time = new Date(bus.estimated);\n let full_minutes = function(){\n if (arrival_time.getMinutes() < 10) {\n return \"0\" + arrival_time.getMinutes()\n } else {\n return arrival_time.getMinutes()\n }\n };\n let time = arrival_time.getHours() - 12 + \":\" + full_minutes();\n //console.log(\"StopID: \" + bus.locid + \", \" + \"Arrival Time: \" + time);\n arrivalsObj[String(bus.locid)] = time\n }\n callback()\n}",
"function getAllRouteStops(callback){\n let routeStopList = {}\n const routes = example1.getRoutes( function(result) {\n let counter = 0\n result.forEach(object => {\n getRouteStops(object.id, function(response){\n routeStopList[object.long_name] = response.data.data\n counter++\n if(counter == result.length){\n callback(routeStopList)\n }\n })\n })\n })\n}",
"function _getRouteStops(routeId, direction) {\n console.log('building route stops list for ' + routeId + ':' + direction + '...');\n return new Promise(function (resolve, reject) {\n var stops = '';\n busTracker.stops(routeId, direction, function (err, data) {\n if (err) {\n console.log('Route: ' + routeId + ':' + direction + ' err', err);\n reject(err);\n }\n console.dir(data);\n _(data).forEach(function (val) {\n stops += val.stpnm + '\\r\\n';\n });\n console.log('route stops built for ' + routeId + ':' + direction);\n resolve(stops);\n });\n });\n}",
"function getAutoCompleteStops(data) {\n//\tdocument.getElementById(\"output\").innerHTML += \"start <br>\";\n\tautoCompleteResults = [];\n\t$.each(data, function(key, item) {\n\t\tvar id = item.stop_id;\n\t\tvar name = item.stop_name;\n//\t\t$.each(stop, function(key, item) {\n//\t\t\t\n////\t\t\tdocument.getElementById(\"output\").innerHTML += key + \"<br>\";\n//\t\t\t\n//\t\t\tif (key == \"stop_id\") { // obtain the stop id\n//\t\t\t\tid = item;\n//\t\t\t}\n//\t\t\t\n//\t\t\tif (key == \"stop_name\") { // obtain the stop name\n//\t\t\t\tname = item;\n//\t\t\t}\n//\t\t});\n\t\t\n\t\tautoCompleteResults.push({label: name, value: id});\n\t\t\n//\t\tif (autoCompleteResults.length == 10)\n//\t\t\tbreak;\n\t});\n}",
"function buildBusStop2(){\r\n for(var i=0; i<length; i++){\r\n allData[i] = new busStop(stopName[i], stopId[i], stopLat[i], stopLon[i], distance[i]);\r\n }\r\n }",
"getBusStopDescriptions(obj){\n console.log(\"On getBusStopDescriptions()\");\n console.log(obj);\n\n CONTENT.length = 0;\n\n try{\n var noOfTrips = obj.trips.length - 1;\n var noOfBusStops = obj.trips[noOfTrips].tripStops.length;\n\n for (var i = 0; i < noOfBusStops; i++){\n\n //get markers information\n var busStopNo = i + 1;\n var desc = obj.trips[noOfTrips].tripStops[i].stop.description;\n var lat = obj.trips[noOfTrips].tripStops[i].stop.coordinates.coordinates[1];\n var lng = obj.trips[noOfTrips].tripStops[i].stop.coordinates.coordinates[0];\n\n //create object and push markers info to markersArray\n var stop = new Object();\n stop.title = desc;\n var latlng = new Object;\n latlng.latitude = lat;\n latlng.longitude = lng;\n stop.coordinates = latlng;\n stop.id = busStopNo;\n markersArray.push(stop);\n\n //create object and push timings to CONTENT\n var newStop = new Object();\n newStop.title = busStopNo + \". \" + desc;\n if(stopsArray[i].timings != 'undefined'){\n newStop.content = stopsArray[i].timings;\n } else {\n newStop.content = \"Timing to be added\";\n }\n CONTENT.push(newStop);\n }\n }\n catch(err){\n console.log(\"error: \" + err);\n }\n }",
"function buildBusStop1(){\r\n for(var i=0; i<length; i++){\r\n allData[i] = new busStop(stopName[i], stopId[i], stopLat[i], stopLon[i], 0);\r\n }\r\n }",
"function loadStops() {\n // Get the Saved Places from the server\n var Stop = Parse.Object.extend(\"Stop\");\n var query = new Parse.Query(Stop);\n if ($scope.swm==\"\") {\n var usr = Parse.User.current();\n }else{\n var usr=new Parse.User();\n usr.id = $scope.swm;\n }\n\n query.equalTo('vendor', usr);\n\n query.limit(1000); /* default is 100, but we need as many results as we can */\n\n query.find({\n success: function(res) {\n console.log(\"Successfully retrieved \" + res.length + \" stops.\");\n $scope.$apply(function () {\n for (var i = 0; i < res.length; i++) {\n var object = res[i];\n var loc = object.get('location');\n var marker = {\n id: i,\n coords: {latitude: loc.latitude,\n longitude: loc.longitude},\n options: {\n labelContent: object.get('name'),\n icon: \"../markers/paleblue_MarkerS.png\", \n }\n };\n $scope.stopsMarkers.push( marker );\n }\n });\n },\n error: function(err) { alert(\"get stops error: \"+err.code+\" \"+err.message); }\n });\n }",
"function getStopsForRoute(route) {\n\tvar self = this;\n\tvar baseUrl = 'http://bustime.mta.info/api/where/stops-for-route/';\n\tvar jsonAndKey = '.json?key=791cb5ed-0cd7-44af-96b0-91fa6d781095&includePolylines=false&version=2';\n\n\t$.ajax({\n\t\tdataType: \"jsonp\",\n\t\turl: baseUrl + route.id + jsonAndKey,\n\t\tsuccess: populateStopsForRoute\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a feature set using a map object mapReq map request object callback function that will handle errors and array of features | function getFeatureInfo(mapReq, callback){
var getFeatureInfoError = validateMapQuery(mapReq);
if(!getFeatureInfoError){
createMap(mapReq, function(createMapError, map){
if(createMapError){
callback(createMapError);
}
else{
map.queryMapPoint(mapReq.i, mapReq.j, {}, function(err, results) {
if (err) throw err;
console.log(results)
var attributes = [];
for(var resultsIndex = 0; resultsIndex < results.length; ++resultsIndex){
if(mapReq.query_layers.indexOf(results[resultsIndex].layer) != -1){
var features = results[resultsIndex].featureset; // assuming you're just grabbing the first object in the array
var feature;
while ((feature = features.next())) {// grab all of the attributes and push to a temporary array
attributes.push(feature.attributes());
}
}
}
callback(null, attributes);
});
}
});
} else{
callback(getFeatureInfoError)
}
} | [
"_constructGeoJsonResponse(features) {\n var featureSet = features.map(this._constructGeoJson);\n\n var response = {\n type: 'FeatureCollection',\n features: featureSet\n };\n\n return response;\n }",
"function FeatureSet() {\n this.features = [];\n this.map = {};\n}",
"function createFeatures(earthquakeData, tectonicData) {\n console.log(\"EarthquakeData: \", earthquakeData);\n // console.log(\"EarthquakeData.geometry: \", earthquakeData.geometry);\n // console.log(\"EarthquakeData.geometry.coor: \", earthquakeData.geometry.coordinates);\n \n var earthquakePoints = [];\n for (var i=0; i<earthquakeData.length; i++) {\n earthquakePoints.push(earthquakeData[i].geometry.coordinates);\n }\n earthquakePoints = earthquakePoints.map(function (point) { return [point[1], point[0], point[2]]; });\n \n var tectonicLayer = L.geoJSON(tectonicData, {\n style: function (feature) {\n return {color: \"orange\",\n weight: 1,\n fillOpacity: 0\n };\n } \n });\n\n // Sending our earthquakes layer to the createMap function\n createMap(earthquakePoints, tectonicLayer);\n\n}",
"function initFeature(featureName, label) {\r\n // Get the feature, if future does not exist, feature = undefined\r\n feature = features.find(element => element.name == featureName);\r\n\r\n // Testing here to see if the feature has been created\r\n if (feature == undefined) {\r\n let featureConfig = {\r\n name: featureName,\r\n label: label,\r\n color: config.layouts.colors[label] || null,\r\n map: myApp.getMap()\r\n // forgot what to add here from thursday\r\n };\r\n\r\n // Set up the new feature\r\n feature = new MapFeature(featureConfig);\r\n }\r\n // Render the feature to the map\r\n feature.render();\r\n\r\n // Update the features array\r\n features = feature.getFeatures();\r\n\r\n // Console.log the features array to see new features as they're created\r\n console.log(features);\r\n}",
"function addMapFeatures(map, popup) {\n map.dragRotate.disable(); // Disable map rotation using right click + drag.\n map.touchZoomRotate.disableRotation(); // Disable map rotation using touch rotation gesture.\n\n map.addControl(\n new maplibregl.NavigationControl({\n showCompass: false,\n })\n );\n\n map.on(\"load\", async function () {\n let partnerHubs = await fetchData(\"assets/data_source/partner_hubs.json\");\n let sponsors = await fetchData(\"assets/data_source/sponsors.json\");\n //let stakeholders = await fetchData(\"assets/data_source/stakeholders.json\");\n let corePartners = await fetchData(\"assets/data_source/core_partners.json\");\n let countiesCentre = await fetchData(\n \"assets/data_source/counties_centre.json\"\n );\n\n let startupsSupported = await fetchData(\n \"assets/data_source/startups_supported_counties.json\"\n );\n let hubMembers = await fetchData(\n \"assets/data_source/members_counties.json\"\n );\n let networkConnections = await fetchData(\n \"assets/data_source/network_connections_counties.json\"\n );\n\n let startupsSupportedCount = countUniqueCounties(\n startupsSupported,\n \"Startups\"\n );\n\n let startups_supported_cluster_data = convertToClusterPoints(\n startupsSupportedCount,\n countiesCentre\n );\n\n addCluster(\n map,\n \"startups-supported\",\n \"startups_supported_cluster\",\n startups_supported_cluster_data,\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"#7CB9E8\", // Aero\n \"#7CB9E8\", // Aero\n \"#C0E8D5\", // Aero Blue\n \"#EFDECD\", // Almond\n \"#F19CBB\", // Amaranth Pink\n \"#3DDC84\", // Android Green\n \"#FBCEB1\", // Apricot\n \"#7FFFD4\" // Aquamarine\n );\n\n let hubMembersCount = countUniqueCounties(hubMembers, \"Members\");\n\n let hub_members_cluster_data = convertToClusterPoints(\n hubMembersCount,\n countiesCentre\n );\n\n addCluster(\n map,\n \"hub_members\",\n \"hub_members_cluster\",\n hub_members_cluster_data,\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"#E4D00A\", // Citrine\n \"#E4D00A\", // Citrine\n \"#E9D66B\", // Arylide yellow\n \"#FF9966\", // Atomic tangerine\n \"#A1CAF1\", // Baby blue eyes\n \"#FF91AF\", // Baker-Miller pink\n \"#FAE7B5\", // Banana Mania\n \"#F5F5DC\" // Beige\n );\n\n let networkConnectionsCount = countUniqueCounties(\n networkConnections,\n \"Connections\"\n );\n\n let network_connections_cluster_data = convertToClusterPoints(\n networkConnectionsCount,\n countiesCentre\n );\n\n addCluster(\n map,\n \"network_connections\",\n \"network_connections_cluster\",\n network_connections_cluster_data,\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\",\n \"#FFE4C4\", // Bisque\n \"#FFE4C4\", // Bisque\n \"#FE6F5E\", // Bittersweet\n \"#BFAFB2\", // Black shadows\n \"#DE5D83\", // Blush\n \"#D891EF\", // Bright lilac\n \"#5F9EA0\", // Cadet Blue\n \"#ACE1AF\" // Celadon\n );\n\n createHubMarkers(partnerHubs, map, \"partner-hub-markers\");\n\n createMarkers(\n sponsors,\n map,\n \"sponsor-markers\",\n \"sponsor-markers\",\n \"assets/images/sponsors_marker.svg\"\n );\n\n createCoreMarkers(corePartners, map, \"core-partner-markers\");\n\n hideAllLayers(map, [\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\",\n \"partner-hub-markers\",\n \"sponsor-markers\",\n \"core-partner-markers\",\n ]);\n });\n\n toggleInput(\"partner-hub-markers\", map);\n toggleInput(\"sponsor-markers\", map);\n toggleInput(\"core-partner-markers\", map);\n\n toggleLayers(\n map,\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"startups-supported\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\"\n );\n\n toggleLayers(\n map,\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"hub-members\",\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\"\n );\n\n toggleLayers(\n map,\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\",\n \"network-connections\",\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\"\n );\n\n hideLayer(\n map,\n \"show_basemap\",\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\"\n );\n\n addPopup(map, \"partner-hub-markers\", popup);\n addPopup(map, \"sponsor-markers\", popup);\n addPopup(map, \"core-partner-markers\", popup);\n}",
"function drawFeatures(featuresArray) {\n myMap.getSource(\"geojsonPOIs\").setData({\n type: \"FeatureCollection\",\n features: featuresArray\n });\n}",
"function create_feature(feature_or_feature_collection, callback_function) {\n dojo.xhrPost({\n \"url\": api_full_url + \"{% url api_feature %}\",\n \"handleAs\": \"json\",\n \"postData\": encodeURIComponent(dojo.toJson(feature_or_feature_collection)),\n \"headers\": {\"Content-Type\":\"application/json\",\n \"X-CSRFToken\": getCookie( CSRF_Cookie_Name )},\n \"handle\": function(response, ioArgs) {\n if(callback_function !== undefined) {\n callback_function({\"response\": response,\n \"ioArgs\": ioArgs});\n }\n }\n });\n}",
"function loadMapShapes() {\n // load US state outline polygons from a GeoJson file\n map.data.loadGeoJson('http://:8081', { idPropertyName: 'postcode' });\n\n // wait for the request to complete by listening for the first feature to be\n // added\n google.maps.event.addListenerOnce(map.data, 'addfeature', function() {\n google.maps.event.trigger(document.getElementById('census-variable'),\n 'change');\n });\n }",
"function addReqLayersFromCloud(){\n leafletData.getMap(\"mapabase\").then(function(map) {\n try{\n for(var z=0;z<$rootScope.capasreqDb.length;z++){\n var reqid=$rootScope.capasreqDb[z].nombre;\n if($rootScope.capasreqDb[z].isChecked){\n $.ajax({\n async: false,\n type: \"GET\",\n url: $rootScope.host+\"/api/requirements/\"+reqid,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (result) {\n //console.log(result);\n var returnOb = angular.fromJson(result);\n if(returnOb!=null){\n //var reqid=returnOb.reqid;\n\n if(isRequiredmentLayerAdded(reqid)==false){\n var id=returnOb.id;\n var companyid=returnOb.companyid;\n var dateTime=returnOb.fecha;\n $rootScope.drawnPointItems=new L.FeatureGroup();\n $rootScope.clcontrol.addOverlay($rootScope.drawnPointItems.addTo(map),reqid);\n var lastId = Object.keys($rootScope.clcontrol._layers)[Object.keys($rootScope.clcontrol._layers).length - 1];\n var jsonPts='';\n if(returnOb.features!=''){\n jsonPts=jQuery.parseJSON(JSON.stringify(eval(\"(\" + returnOb.features + \")\")));\n for(var j=0;j<jsonPts.points.length;j++){\n //Get Latitude/longitude that represents each requiriment from the selected requirement layer\n var nombre=jsonPts.points[j].point.nombre;\n var persona=jsonPts.points[j].point.persona;\n var empresa=jsonPts.points[j].point.empresa;\n var direccion=jsonPts.points[j].point.direccion;\n var telefono=jsonPts.points[j].point.telefono;\n var ciudad=jsonPts.points[j].point.ciudad;\n var pais=jsonPts.points[j].point.pais;\n var descripcion=jsonPts.points[j].point.descripcion;\n\n var x=Number(jsonPts.points[j].point.x);\n var y=Number(jsonPts.points[j].point.y);\n var status=jsonPts.points[j].point.status;\n var personadest=jsonPts.points[j].point.personadestino;\n var recogido=jsonPts.points[j].point.recogido;\n var device=jsonPts.points[j].point.client_id;\n var iconSize = [30, 70];\n var iconURL='';\n if(status=='asignado'){\n if(recogido=='X'){\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-marker+000000.png';\n }else{\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-marker+FF0000.png';\n }\n }else if(status=='cerrado'){\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-marker+000000.png';\n }else{\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-marker+00FF00.png';\n }\n //console.log(x+\" \"+y+\" \"+status+\" \"+iconURL);\n var geojsonFeature;\n if(device!=\"\"){\n geojsonFeature = {\n \"type\": \"Feature\",\n \"properties\": {\"nombre\":nombre,\"persona\":persona,\"empresa\":empresa,\"direccion\":direccion,\"telefono\":telefono,\"ciudad\":ciudad,\"pais\":pais,\"descripcion\":descripcion,\"dispositivo\":device},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [y, x]\n }\n };\n }else{\n geojsonFeature = {\n \"type\": \"Feature\",\n \"properties\": {\"nombre\":nombre,\"persona\":persona,\"empresa\":empresa,\"direccion\":direccion,\"telefono\":telefono,\"ciudad\":ciudad,\"pais\":pais,\"descripcion\":descripcion},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [y, x]\n }\n };\n }\n\n var geojson=L.geoJson(geojsonFeature, {\n style: function (feature) {\n /*return {stroke: true, color: '#000000', weight:4, opacity: 0.5, fill: false};*/\n },\n onEachFeature: function(feature, layer){\n layer.setIcon(new L.Icon({iconUrl: iconURL, iconSize: iconSize,\n iconAnchor: [iconSize[0] / 2, iconSize[1] / 2],\n popupAnchor: [0, -iconSize[1] / 2]}));\n var content='';\n if(personadest!=\"\"){\n content = '<table class=\"dropchop-table\"><tr><td rowspan=\"2\" align=\"center\"><strong>Origen</strong></td></tr><tr>';\n }else{\n content = '<table class=\"dropchop-table\"><tr>';\n }\n\n if (layer.feature.properties) {\n for (var prop in layer.feature.properties) {\n content += '<tr><td><strong>' + prop + '</strong></td><td>' + layer.feature.properties[prop] + '</td></tr>';\n }\n }\n content += '</table>';\n layer.bindPopup(L.popup({\n maxWidth: 450,\n maxHeight: 200,\n autoPanPadding: [45, 45],\n className: 'dropchop-popup'\n }, layer).setContent(content));\n }\n });\n // console.log(geojson);\n geojson.eachLayer(\n function(l){\n $rootScope.drawnPointItems.addLayer(l);\n });\n\n //It validates that the marker has a destination\n if(personadest!=\"\"){\n if(status=='asignado'){\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-triangle+FF0000.png';\n }else if(status=='cerrado'){\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-triangle+000000.png';\n }else{\n iconURL='http://api.tiles.mapbox.com/v3/marker/pin-m-triangle+00FF00.png';\n }\n var empresadest=jsonPts.points[j].point.empresadestino;\n var direcciondest=jsonPts.points[j].point.direcciondestino;\n var telefonodest=jsonPts.points[j].point.telefonodestino;\n var ciudaddest=jsonPts.points[j].point.ciudaddestino;\n var paisdest=jsonPts.points[j].point.paisdestino;\n var desdest=jsonPts.points[j].point.descripciondestino;\n\n var x1=Number(jsonPts.points[j].point.x1);\n var y1=Number(jsonPts.points[j].point.y1);\n var geojsonFeature2;\n if(device!=\"\"){\n geojsonFeature2 = {\n \"type\": \"Feature\",\n \"properties\": {\"nombre\":nombre+\"(d)\",\"persona\":personadest,\"empresa\":empresadest,\"direccion\":direcciondest,\"telefono\":telefonodest,\"ciudad\":ciudaddest,\"pais\":paisdest,\"descripcion\":desdest,\"dispositivo\":device},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [y1, x1]\n }\n };\n }else{\n geojsonFeature2 = {\n \"type\": \"Feature\",\n \"properties\": {\"nombre\":nombre+\"(d)\",\"persona\":personadest,\"empresa\":empresadest,\"direccion\":direcciondest,\"telefono\":telefonodest,\"ciudad\":ciudaddest,\"pais\":paisdest,\"descripcion\":desdest},\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [y1, x1]\n }\n };\n }\n\n var geojson2=L.geoJson(geojsonFeature2, {\n style: function (feature) {\n\n },\n onEachFeature: function(feature, layer){\n layer.setIcon(new L.Icon({iconUrl: iconURL, iconSize: iconSize,\n iconAnchor: [iconSize[0] / 2, iconSize[1] / 2],\n popupAnchor: [0, -iconSize[1] / 2]}));\n\n var content = '<table class=\"dropchop-table\"><tr><td rowspan=\"2\" align=\"center\"><strong>Destino</strong></td></tr><tr>';\n if (layer.feature.properties) {\n for (var prop in layer.feature.properties) {\n content += '<tr><td><strong>' + prop + '</strong></td><td>' + layer.feature.properties[prop] + '</td></tr>';\n }\n }\n content += '</table>';\n layer.bindPopup(L.popup({\n maxWidth: 450,\n maxHeight: 200,\n autoPanPadding: [45, 45],\n className: 'dropchop-popup'\n }, layer).setContent(content));\n }\n });\n geojson2.eachLayer(\n function(l){\n $rootScope.drawnPointItems.addLayer(l);\n });\n\n }\n\n map.invalidateSize();\n map.fitBounds(geojson.getBounds());\n }\n }\n\n $rootScope.capasreq.push({id:lastId,nombre:reqid,dateTime:dateTime,tipo:'requerimiento',capa:$rootScope.clcontrol._layers[lastId].layer,edit:false,enabled:true});\n //console.log($rootScope.capasreq);\n }else{\n alert(\"La capa de requerimientos \"+reqid+\" ya fue adicionada al mapa.\");\n }\n }\n }\n });\n $rootScope.capasreqDb[z].isChecked=false;\n }\n }\n }catch(err){\n\n }\n });\n }",
"function makerToFeature(mkr) {\n var coords = mkr.get(\"coordinates\").toJSON();\n if(mkr.get(\"classification\")) {\n var marker_classification_symbol = mkr.get(\"classification\").get(\"name\") \n }\n var obj = {\n id: mkr.id,\n geometry: {\n lng: coords.longitude,\n lat: coords.latitude\n },\n properties: {\n title: mkr.get(\"title\"),\n description: mkr.get(\"description\"),\n marker_color: mkr.get(\"marker_color\"),\n marker_size: mkr.get(\"marker_size\"),\n website: mkr.get(\"website\"),\n marker_symbol: marker_classification_symbol\n }\n };\n return new google.maps.Data.Feature(obj);\n }",
"function fetchFeatureLayers () {\n map.spin(true, {lines:9, length:40, width:24,radius:60});\n requests = {};\n requests[\"request\"] = \"fetch_data_layers\";\n $.ajax({\n url: \"./include/geoserver_requests.php\",\n type: \"post\",\n data: requests,\n success: function(data) {\n data = $.parseJSON(data);\n var features = data['featureTypes']['featureType'];\n var layer_array = [];\n features.forEach(function(feature) {\n layer_array.push(feature['name']);\n })\n layer_array.sort();\n layer_array.forEach(function(feature) {\n // ****Separate floor layers from asset layer and added to basemap layers\n if (/floor/.test(feature)) {\n window[feature] = L.geoJSON(false, {onEachFeature: onEachFloorFeature});\n layerControl.addBaseLayer(window[feature], String(feature).upperFirstChar());\n fetchFloorFeatures(feature);\n // ****Floor01 is displayed by default\n if (feature=='floor01') {\n window[feature].addTo(map);\n }\n }\n });\n map.spin(false);\n }\n });\n }",
"function loadMapShapes() {\n // load US state outline polygons from a GeoJson file\n map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/states.js', { idPropertyName: 'STATE' });\n\n // wait for the request to complete by listening for the first feature to be added\n google.maps.event.addListenerOnce(map.data, 'addfeature', function() {\n google.maps.event.trigger(document.getElementById('census-variable'),\n 'change');\n });\n}",
"function addFeatureCollection(map, features) {\n //GeoJSON srouce\n var layerSource = new ol.source.Vector({\n features: (new ol.format.GeoJSON()).readFeatures(features, { featureProjection: 'EPSG:3006' })\n });\n\n //Layer\n var layer = new ol.layer.Vector({\n source: layerSource,\n style: function (feature, resolution) {\n var name = feature.get('name');\n let styleObj = {\n fill: new ol.style.Fill({\n color: 'rgba(0, 255, 0, 0.1)'\n }),\n stroke: new ol.style.Stroke({\n color: 'rgba(0, 255, 0, 0.6)',\n width: 2\n }),\n image: new ol.style.Circle({\n radius: 7,\n fill: new ol.style.Fill({\n color: 'rgba(0, 255, 0, 0.9)'\n })\n })\n }\n\n let _name = name;\n if (resolution > 1000) {\n _name = \"\";\n }\n\n styleObj[\"text\"] = new ol.style.Text({\n text: _name\n })\n return new ol.style.Style(styleObj);\n }\n });\n map.addLayer(layer);\n}",
"function loadFeatures() {\n $.ajax({\n type: 'GET',\n dataType: 'json',\n url: placemarkJSON})\n .done(function (geojson) { \n // Load response GeoJSON into feature layer\n featureLayer.setGeoJSON(geojson);\n // Fit map to bounding coordinates of features, then zoom out a bit\n map.fitBounds(featureLayer.getBounds());\n // Todo: may want to add logic to zoom out one step, if the fitted view is extremely tight around the placemarks\n // map.setZoom(map.getZoom() - 1)\n // Build Table of Contents as features are loaded\n buildTableOfContents();\n });\n }",
"function loadMapShapes() {\n // load US state outline polygons from a GeoJson file\n map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/states.js', { idPropertyName: 'STATE' });\n\n // wait for the request to complete by listening for the first feature to be\n // added\n google.maps.event.addListenerOnce(map.data, 'addfeature', function() {\n google.maps.event.trigger(document.getElementById('census-variable'),\n 'change');\n });\n}",
"function createFeatures(earthquakeData) { \n // Define a function to run once for each feature in the features array\n // Give each feature a popup describing the place, date/time and magnitude of the earthquake \n var earthquakes = L.geoJSON(earthquakeData, {\n \n onEachFeature: function (feature, layer){\n layer.bindPopup(`<strong>Place:</strong> ${feature.properties.place}<br>\n <strong>Time:</strong> ${new Date(feature.properties.time)}<br>\n <strong>Magnitude:</strong> ${feature.properties.mag}`);\n },\n \n pointToLayer: function (feature, latlng) {\n return new L.circle(latlng,\n {radius: getRadius(feature.properties.mag),\n fillColor: getColor(feature.properties.mag),\n color: \"#000\",\n weight: .5,\n fillOpacity: .6,\n stroke: true\n })\n }\n });\n // Send earthquakes layer to the createMap function\n createMap(earthquakes); \n}",
"function createFeatures(earthquakeData) {\n console.log(earthquakeData);\n\tvar earthquakes = L.geoJSON(earthquakeData,{\n // Step 5 Create a function to run once for each feature in the features array\n // Give each feature a popup describing the magnitude(feature.properties.mag)\n //, place(feature.properties.place)\n // and time (feature.properties.time) of the earthquake\n\t\tonEachFeature: function(feature,layer){\n\n\t\t\tlayer.bindPopup(`<h3>Magnitude:${feature.properties.mag}</h3>\\\n\t\t\t\t<h3>Location:${feature.properties.place}</h3>\\\n <hr><p>${new Date(feature.properties.time)}</p>`);\n \n\t\t},\n\t\tpointToLayer:function(feature,latlng){\n\t\t\treturn new L.circle(latlng,{\n\t\t\t\tradius: markerRadius(feature.properties.mag),\n\t\t\t\tfillColor: markerColor(feature.properties.mag),\n\t\t\t\tfillOpacity:.9,\n\t\t\t\tstroke:false,\n\t\t\t})\n\t\t}\n\t});\n//Step 6 send the earthquakes layer to a createMap function\n\tcreateMap(earthquakes);\n}",
"function makeMap(features, attrib, colorScheme, params) {\n // Create an SVG image to hold the chart\n const map = d3.select(\"#choropleth\").append(\"svg\")\n .attr(\"viewBox\", \"0 0 \" + params.width + \" \" + params.height);\n\n const thresholds = getNaturalThresholds(\n features.map(d => d.properties[attrib]),\n colorScheme.length\n );\n\n // Define a threshold scale to color the map features\n const color = d3.scaleThreshold()\n .domain(thresholds).range(colorScheme);\n\n // Bind data and create one path per GeoJSON feature (i.e., NYS county)\n map.selectAll(\"path\")\n .data(features)\n .enter()\n .append(\"path\")\n .attr(\"d\", params.pathGen)\n .style(\"fill\", d => color(d.properties[attrib]))\n\n // Create and attach a legend for this map\n makeLegend(map, attrib, colorScheme, thresholds, params);\n}",
"function AddFeatureLayers() {\n if (operationalLayersCollection.length != 0) {\n for (var i = 0; i < operationalLayersCollection.length; i++) {\n var layerId = operationalLayersCollection[i].Key;\n\n if (operationalLayersCollection[i].hasDynamicMapService) {\n var mapserverURL = operationalLayersCollection[i].MapURL.substr(0, operationalLayersCollection[i].MapURL.lastIndexOf('/'));\n var visibleLayers = [operationalLayersCollection[i].MapURL.substr(operationalLayersCollection[i].MapURL.lastIndexOf('/') + 1)];\n var dynamicMapService = new esri.layers.ArcGISDynamicMapServiceLayer(mapserverURL,\n { id: \"dynamic\" + layerId });\n dynamicMapService.setVisibleLayers(visibleLayers);\n map.addLayer(dynamicMapService);\n }\n\n var featureLayer = CreateLineFeatureLayer(operationalLayersCollection[i], layerId, operationalLayersCollection[i].isLayerVisible);\n if (operationalLayersCollection[i].hasDynamicMapService) {\n var symbol = new esri.symbol.SimpleFillSymbol().setColor(new dojo.Color([0, 0, 0, 0]));\n var renderer = new esri.renderer.SimpleRenderer(symbol);\n featureLayer.setRenderer(renderer);\n }\n map.addLayer(featureLayer);\n if (operationalLayersCollection[i].BuildingAttribute) {\n dojo.connect(featureLayer, \"onClick\", function (evt) {\n outsideServiceRequest = false;\n ShowDetailsInfo(evt);\n });\n }\n }\n }\n else {\n HideLoadingMessage();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper to determine the 'relevant' controls for a set of field group names | function getControlsByFieldGroupId(vFieldGroups) {
return oVerticalLayout.getControlsByFieldGroupId(vFieldGroups).filter(function(ctrl) {
return /^input\d+(-\d\d)*$/.test(ctrl.getId());
});
} | [
"function _addFieldGroups() {\n var dialog = $('#perc-edit-section-dialog');\n var fieldGroups = [\n { groupName : \"perc-section-general-container\", groupLabel : \"Section\"},\n { groupName : \"perc-section-users-container\", groupLabel : \"Users\"},\n { groupName : \"perc-section-security-container\", groupLabel : \"Security\"}\n ];\n $.each(fieldGroups, function(index) {\n // Create HTML markup with the groupName minimizer/maximizer and\n // insert it before the 1st field in each group\n var minmaxClass = (index === 0) ? \"perc-items-minimizer\" : \"perc-items-maximizer\";\n var groupHtml =\n \"<div class='perc-section-header'>\" +\n \"<div class='perc-section-label' groupName='\" + this.groupName + \"'>\" +\n \"<span class='perc-min-max \" + minmaxClass + \"' ></span>\" + this.groupLabel +\n \"</div>\" +\n \"</div>\";\n dialog.find('#' + this.groupName).before(groupHtml);\n // The first group will be the only one expanded (hide all others)\n index !== 0 && dialog.find('#' + this.groupName).hide();\n });\n\n // Bind collapsible event\n dialog.find(\".perc-section-label\").off(\"click\").on(\"click\",function() {\n var self = $(this);\n self.find(\".perc-min-max\")\n .toggleClass('perc-items-minimizer')\n .toggleClass('perc-items-maximizer');\n dialog.find('#' + self.attr('groupName')).toggle();\n });\n }",
"function _addFieldGroups() {\n var dialog = $('#perc-folder-props-dialog');\n var fieldGroups = [\n { groupName : \"perc-folder-general-properties-container\", groupLabel : I18N.message(\"perc.ui.folder.properties.dialog@General\")},\n { groupName : \"perc-user-permissions-container\", groupLabel : I18N.message(\"perc.ui.folder.properties.dialog@Permissions\")},\n { groupName : \"perc-asset-folder-sites-container\", groupLabel : I18N.message(\"perc.ui.folder.properties.dialog@Security\")}\n ];\n\n $.each(fieldGroups, function(index) {\n // Create HTML markup with the groupName minimizer/maximizer and\n // insert it before the 1st field in each group\n var minmaxClass = (index === 0) ? \"perc-section-items-minimizer\" : \"perc-section-items-maximizer\";\n var groupHtml =\n \"<div class='perc-section-header'>\" +\n \"<div class='perc-section-label' data-group='\" + this.groupName + \"'>\" +\n \"<span class='perc-min-max \" + minmaxClass + \"' ></span>\" + this.groupLabel +\n \"</div>\" +\n \"</div>\";\n\n dialog.find('#' + this.groupName).before(groupHtml);\n\n // The first group will be the only one expanded (hide all others)\n index !== 0 && dialog.find('#' + this.groupName).hide();\n });\n\n // Bind collapsible event\n dialog.find(\".perc-section-label\").off(\"click\").on(\"click\",function() {\n var self = $(this);\n self.find(\".perc-min-max\")\n .toggleClass('perc-section-items-minimizer')\n .toggleClass('perc-section-items-maximizer');\n\n dialog.find('#' + self.attr('data-group')).toggle();\n });\n }",
"initControlGroups() {\n function checkSetValidity(controls) {\n if (controls.length <= 0) return false;\n\n const errorMessage = controls.some((control) => (control.input.checked)) ? '' : controls[0].el.dataset.controlGroupError;\n controls[0].input.setCustomValidity(errorMessage);\n }\n\n let controlGroups = {};\n\n // group controls by name\n this.controls.forEach((control) => {\n let controlGroup = control.controlGroup;\n if (controlGroup) {\n controlGroups[controlGroup] = controlGroups[controlGroup] || [];\n controlGroups[controlGroup].push(control);\n }\n });\n\n // set up validity check triggers\n Object.values(controlGroups).forEach((controls) => {\n const firstCheckbox = controls.length > 0 ? controls[0] : null;\n if (firstCheckbox) {\n controls.forEach((checkbox) => {\n checkbox.input.addEventListener('change', () => {\n checkSetValidity(controls);\n });\n });\n checkSetValidity(controls);\n }\n });\n }",
"@computed\n get completeGroups() {\n return Object.keys(this.fieldGroups).filter(group =>\n this.fieldGroups[group].every(fieldName => this.getMatchingFields(fieldName).every(field => field.valid))\n );\n }",
"function nlobjFieldGroup() {\n}",
"function updateFields()\n {\n for(var type in formGroups)\n formGroups[type].hide();\n formGroups[$typeSelect[0].value].show();\n\n }",
"groupFields() {\n \n var self = this;\n \n /**\n * Fields that are mapped with integer keys; not with a name or id.\n */\n let fieldNames = Object.getOwnPropertyNames(this.form.elements).filter(item => /\\D+/.test(item));\n \n fieldNames.forEach(fieldName => {\n \n let field = self.form.elements[fieldName];\n \n if (field instanceof HTMLElement) {\n \n let tagName = field.tagName.toLowerCase();\n \n if (field.name || field.id) {\n \n self.fields[fieldName] = field;\n \n if ([\"input\", \"textarea\", \"select\"].includes(tagName)) {\n \n if ([\"text\", \"number\", \"password\", \"email\", \"date\", \"tel\", \"textarea\", \"select-one\"].includes(field.type)) {\n self.textFields[fieldName] = field;\n }\n else if (field.type == \"hidden\") {\n self.hiddens[fieldName] = field;\n }\n else if (field.type == \"checkbox\") {\n self.checkboxes[fieldName] = field;\n }\n else if ([\"button\", \"submit\"].includes(field.type)) {\n self.buttons[fieldName] = field;\n }\n \n }\n else if (tagName == \"button\") {\n self.buttons[fieldName] = field;\n }\n \n }\n \n }\n else if (field instanceof RadioNodeList) {\n self.fields[fieldName] = field;\n self.radios[fieldName] = field;\n }\n \n });\n }",
"function ShowHideFieldGroup(name) {\n if ($(name + ' .fieldset-wrapper').is(':visible')) {\n $(name + ' .fieldset-wrapper').hide();\n $(name).addClass('collapsed');\n }\n else {\n $(name + ' .fieldset-wrapper').show();\n $(name).removeClass('collapsed');\n }\n }",
"function ValidateControls(messageControl, parentControl) {\n\n /*==========Sample Usage & Datatype Examples =============\n \n <input name=\"\" type=\"text\" required-field=\"true\" required-message=\"xxxxxxxxx\" datatype=\"number\" message=\"xxxxxxx\">\n <input name=\"\" type=\"text\" required-field=\"true\" required-message=\"xxxxxxxxx\" datatype=\"email\" message=\"xxxxxxx\">\n <input name=\"\" type=\"file\" required-field=\"true\" required-message=\"xxxxxxxxx\" datatype=\"image\" message=\"xxxxxxx\" allowed-formats=\"jpg.bmp.jpeg.gif.png\">\n <select name=\"\" required-field=\"true\" required-message=\"xxxxxxxxx\">\n\n if(ValidateControls($(selecter), $(selecter)) == false) return false;\n\n ==========================================================*/\n\n var errorMessage = \"\";\n parentControl = parentControl == undefined ? $(\"body\") : parentControl;\n\n $(parentControl).find(\"input[required-field=true]\").each(function () {\n\n if ($(this).attr(\"watermark\")) {\n if ($(this).val() == $(this).attr(\"watermark\")) {\n errorMessage += ($(this).attr(\"required-message\") + \"<br>\");\n }\n }\n else if (!$.trim($(this).val())) {\n errorMessage += ($(this).attr(\"required-message\") + \"<br>\");\n }\n });\n\n $(parentControl).find(\"input[confirm-field=true]\").each(function () {\n if ($.trim($(this).val()) != $(\"input[name=\" + $(this).attr(\"confirm-name\") + \"]\").val()) {\n errorMessage += ($(this).attr(\"confirm-message\") + \"<br>\");\n }\n });\n\n $(parentControl).find(\"textarea[required-field=true]\").each(function () {\n if ($(this).attr(\"watermark\")) {\n if ($(this).val() == $(this).attr(\"watermark\")) {\n errorMessage += ($(this).attr(\"required-message\") + \"<br>\");\n }\n }\n else if (!$(this).val()) {\n errorMessage += ($(this).attr(\"required-message\") + \"<br>\");\n }\n });\n\n $(parentControl).find(\"select[required-field=true]\").each(function () {\n if ($(this).val() == \"0\") {\n errorMessage += ($(this).attr(\"required-message\") + \"<br>\");\n }\n });\n\n $(parentControl).find(\"input[datatype=number]\").each(function () {\n if ($(this).attr(\"watermark\")) {\n if ($(this).val() != $(this).attr(\"watermark\")) {\n if (!IsNumeric($(this).val())) {\n errorMessage += ($(this).attr(\"message\") + \"<br>\");\n }\n }\n }\n else if ($(this).val()) {\n if (!IsNumeric($(this).val())) {\n errorMessage += ($(this).attr(\"message\") + \"<br>\");\n }\n }\n });\n\n $(parentControl).find(\"input[datatype=email]\").each(function () {\n if ($(this).attr(\"watermark\")) {\n if ($(this).val() != $(this).attr(\"watermark\")) {\n if (!IsEmail($(this).val())) {\n errorMessage += ($(this).attr(\"message\") + \"<br>\");\n }\n }\n }\n else if ($.trim($(this).val())) {\n if (!IsEmail($(this).val())) {\n errorMessage += ($(this).attr(\"message\") + \"<br>\");\n }\n }\n });\n\n $(parentControl).find(\"input[datatype=image]\").each(function () {\n if ($(this).val()) {\n var filetype = $(this).val().split(\".\");\n filetype = filetype[filetype.length - 1].toLowerCase();\n\n if ($(this).attr(\"allowed-formats\").indexOf(filetype) == -1) {\n $(this).val(\"\");\n errorMessage += ($(this).attr(\"message\") + \"<br>\");\n }\n }\n });\n $(parentControl).find(\"input[type=hidden][required-field=true]\").each(function () {\n if ($(this).val() == 0) {\n errorMessage += ($(this).attr(\"required-message\") + \"<br>\");\n }\n });\n\n if (errorMessage) {\n ShowMessage(messageControl, errorMessage, MessageType.Error);\n return false;\n }\n return true;\n}",
"function getUPFormControlNames(formObject)\n{\n var retList = new Array(), displayStr, node;\n fieldList = formObject.formControls;\n for (var i=0; fieldList.length && i < fieldList.length; i++) \n {\n node = fieldList[i];\n displayStr = \"\";\n if (node.obj)\n {\n displayStr = dwscripts.getNameOrId(node.obj,\"name\");\n } \n else if (!node.obj || !displayStr)\n {\n displayStr = MM.LABEL_Unnamed;\n }\n retList.push(displayStr);\n }\n return retList;\n}",
"function setPresetsForGrouping(data)\n\t\t{\n\t\t\t$wizardFields.find('p.row').filter('.values, .label, .wrap-p').show();\n\t\t\t$label.val(data.name + \":\");\n\t\t\tfieldName = 'GROUPINGS[' + data.id + ']';\n\t\t\taddGroupInputs(data.groups);\n\n\t\t\tswitch(data.form_field) {\n\t\t\t\tcase 'radio':\n\t\t\t\t\tfieldType = 'radio';\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'hidden':\n\t\t\t\t\t// hide all rows except value row\n\t\t\t\t\t$wizardFields.find('p.row').filter('.values, .label, .wrap-p').hide();\n\t\t\t\t\t$wizardFields.find('p.row.value').show();\n\n\t\t\t\t\t// add group name to hidden input value\n\t\t\t\t\tfor(var i = 0, groupsCount = data.groups.length; i < groupsCount; i++) {\n\t\t\t\t\t\t$value.val($value.val() + data.groups[i].name + ',');\n\t\t\t\t\t}\n\n\t\t\t\t\tfieldType = 'hidden';\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase 'dropdown':\n\t\t\t\t\tfieldType = 'select';\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tfieldType = 'checkbox';\n\n\t\t\t\t\t// turn field name into an array\n\t\t\t\t\tfieldName += '[]';\n\t\t\t\t\tbreak;\n\t\t\t}\t\n\n\t\t\t// update code preview\n\t\t\tupdateCodePreview();\n\t\t}",
"function ValidateGroup() {}",
"static generateGroups(fields, formData, disabled, onChange, canEdit) {\n // API sometimes returns null, sometimes undefined, sometimes empty string.\n // We need to sort this out before grouping:\n const consolidatedFields = fields.map(({\n group_name,\n ...others\n }) => ({ ...others,\n group_name: group_name || 'Ungrouped'\n })); //1. Group the types by group_name:\n\n const groupedFields = (0, _lo.groupBy)(consolidatedFields, 'group_name'); //2. For every group, we will generate the fields,\n\n return (0, _lo.map)(groupedFields, (group, groupName) => _react.default.createElement(_Card.default, {\n key: groupName,\n collapsible: true,\n collapsed: true,\n title: groupName,\n description: _react.default.createElement(\"div\", null, \" \", ClassificationFormBuilder.generateFieldComponents(group, formData, disabled, onChange), \" \"),\n footer: canEdit && _react.default.createElement(_Button.default, {\n color: \"primary\"\n }, \" Save \") || _react.default.createElement(\"div\", null)\n }));\n }",
"function relevantFields (rowChecks) {\n var fields = FIELD_MANAGEMENT_ENUMS.all;\n if (rowChecks.hasSubType) {\n if (rowChecks.countRequiredFieldsFilled == rowChecks.totalFieldsRequired && !rowChecks.countSubTypeRequiredFields) {\n fields = FIELD_MANAGEMENT_ENUMS.standard;\n } else if (rowChecks.countSubTypeRequiredFields == rowChecks.totalSubTypeFieldsRequired && !(rowChecks.countRequiredFields == rowChecks.totalFieldsRequired || rowChecks.subTypeIsBlocked) ) {\n fields = FIELD_MANAGEMENT_ENUMS.subType;\n }\n }\n return fields;\n}",
"function updateFieldControls(groupID) {\n\n var fieldData = pb.template().keyDoc[pb.passType()];\n var pass = pb.svg();\n ////rebuilds all the text field rects of svgType\n app.passBuilder.fields.set(fieldData[editGroup.dataType], editGroup.svgType);\n\n //Add the event back.\n pass.selectAll('rect.text-btn-rect')\n .on('click', onTextRectClick); //add event to new rect\n\n pass.select('g.logo rect')\n .on('click', onLogoRectClick); //add back event to logo as well!\n\n //set select group to the next or previous rectangle\n setEditGroup(pass.select('g#' + groupID + ' rect')[0][0]);\n\n configTextInputs();\n\n //highlight selected group\n setHighLight(editGroup.svgId);\n\n //enable all buttons\n tk.enable('button#btn-del-field', 'button#btn-add-field','#value-format');\n\n\n }",
"function getGroupCheckboxValues(groupName,inclGroupName) {\n\tvar delim = '';\n\t$.each($(\"input[name='\"+groupName+\"']:checked\"), function() {\n\t\tdelim=delim+$(this).val()+',';\n });\n if (inclGroupName == true) {\n\t delim = groupName+'='+delim;\n } \n return delim.slice(0, -1); //removes the last character that is a comma;\n}",
"static generateGroups(fields: Object[], formData: Object, disabled: boolean, onChange: Function, canEdit: boolean) {\n\n\n // API sometimes returns null, sometimes undefined, sometimes empty string.\n // We need to sort this out before grouping:\n const consolidatedFields = fields.map(({ group_name, ...others }) => ({ ...others, group_name: group_name || 'Ungrouped' }));\n\n //1. Group the types by group_name:\n const groupedFields = groupBy(consolidatedFields, 'group_name');\n\n //2. For every group, we will generate the fields,\n return map(groupedFields, (group, groupName) => (\n <Card\n key={groupName}\n collapsible\n collapsed\n title={groupName}\n description={\n <div> {ClassificationFormBuilder.generateFieldComponents(group, formData, disabled, onChange)} </div>\n }\n footer={(canEdit && <Button color=\"primary\"> Save </Button>) || <div />}\n />\n ));\n }",
"function processLegends(grp) {\r\t// Loop on legend sets:\r\tvar setCount = grp.groupItems.length;\r\tif (setCount === 0) {\r\t\t\treturn true;\r\t}\r\t// Still here? There's at least 1 legendSet\r\tfor (var i = 0; i < setCount; i++) {\r\t\tvar mySet = grp.groupItems[i];\r\t\t// Now: each legendSet should consist of:\r\t\t//\t- a header group\r\t\t//\t- 2 or more indexed legend groups--\r\t\t// \t\teach consisting of a rect and a string...\r\t\t// So the tricky bit is sorting these out...\r\t\tvar legCount = mySet.groupItems.length\t\r\t\t// Is this necessary?\r\t\tif (legCount < 2) { return false; }\r\t\t// Still here...\r\t\t// We're getting in deep, so farm out individual legend-key groups to a sub-handler:\r\t\tfor (var j = 0; j < legCount; j++) {\r\t\t\tvar oneGrp = mySet.groupItems[j];\r\t\t\tif (oneGrp.name.search('key') >= 0) {\r\t\t\t\t// I'm actually after rect/text sub-groups\r\t\t\t\t// NOTE: this has got pretty Byzantine!\r\t\t\t\tfor (var k = 0; k < oneGrp.groupItems.length; k++) {\r\t\t\t\t\tprocessOneLegend(oneGrp.groupItems[k]);\r\t\t\t\t}\r\t\t\t}\r\t\t\telse {\r\t\t\t\t// Header, in theory\r\t\t\t\tvar theHeader = setTextFrameAttributes(oneGrp.textFrames[0]);\r\t\t\t\talert(theHeader)\r\t\t\t}\r\t\t}\r\t}\r\treturn true;\r}",
"function TKR_exposeExistingLabelFields() {\n if ($('label3').value ||\n $('label4').value ||\n $('label5').value) {\n if ($('addrow1')) {\n _showID('LF_row2');\n _hideID('addrow1');\n }\n }\n if ($('label6').value ||\n $('label7').value ||\n $('label8').value) {\n _showID('LF_row3');\n _hideID('addrow2');\n }\n if ($('label9').value ||\n $('label10').value ||\n $('label11').value) {\n _showID('LF_row4');\n _hideID('addrow3');\n }\n if ($('label12').value ||\n $('label13').value ||\n $('label14').value) {\n _showID('LF_row5');\n _hideID('addrow4');\n }\n if ($('label15').value ||\n $('label16').value ||\n $('label17').value) {\n _showID('LF_row6');\n _hideID('addrow5');\n }\n if ($('label18').value ||\n $('label19').value ||\n $('label20').value) {\n _showID('LF_row7');\n _hideID('addrow6');\n }\n if ($('label21').value ||\n $('label22').value ||\n $('label23').value) {\n _showID('LF_row8');\n _hideID('addrow7');\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieves access token from page hash for use after user is redirected after logging in | function getAccessToken(){
var url = window.location.hash; // get full page url
var access_token = url.substring(url.indexOf("#")+14, url.indexOf("&")); // get access token from hash
console.log("access_token: " + access_token);
return(access_token);
} | [
"function getAccessTokenFromUrl() {\n return utils.parseQueryString(window.location.hash).access_token;\n }",
"function getAccessTokenFromUrl() {\n return utils.parseQueryString(window.location.hash).access_token;\n}",
"findYNABToken() {\n let token = null\n const search = window.location.hash.substring(2).replace(/&/g, '\",\"').replace(/=/g,'\":\"')\n if (search && search !== '' && \n search != 'home' && \n search != 'home/child' &&\n search != 'home/' &&\n search != 'home/child/grandchild'\n ) {\n // Try to get access_token from the hash returned by OAuth\n const params = JSON.parse('{\"' + search + '\"}', function(key, value) {\n return key === '' ? value : decodeURIComponent(value)\n })\n token = params.access_token\n sessionStorage.setItem('ynab_access_token', token)\n window.location.hash = ''\n } else {\n // Otherwise try sessionStorage\n token = sessionStorage.getItem('ynab_access_token')\n }\n return token\n }",
"function getToken() {\n\t//substring(1) to remove the '#'\n\thash = parseParms(document.location.hash.substring(1));\n\n\t// Return hash for parsing later\n\treturn hash\n}",
"function setAccessToken() {\n\tconst code = window.location.hash\n\tconst accessTokenFromUrl = code.match(/access_token=(.*?)&/)[1]\n\tsetLocalStorageItem('access_token', accessTokenFromUrl)\n}",
"function getAccessToken(ready) {\n var ret;\n\n if(typeof window.localStorage.access_token === 'undefined') {\n\n window.console.log('No access token stored!!!');\n\n var hash = window.location.hash;\n\n if(hash.length > 0) {\n if(hash.indexOf(ACC_T) === 1) {\n var end = hash.length;\n var expires = hash.indexOf('&');\n if(expires !== -1) {\n end = expires;\n }\n\n ret = hash.substring(ACC_T.length + 2,end);\n\n window.localStorage.access_token = ret;\n window.localStorage.expires = end * 1000;\n window.localStorage.token_ts = Date.now();\n\n window.console.log('Access Token %s. Expires: %s',ret,end);\n }\n } else {\n startOAuth();\n }\n }\n else {\n var timeEllapsed = Date.now() - window.localStorage.token_ts;\n\n if(timeEllapsed < window.localStorage.expires) {\n ret = window.localStorage.access_token;\n window.console.log('Reusing existing access token:',ret);\n }\n else {\n window.console.log('Access Token has expired');\n startOAuth();\n }\n }\n\n if(typeof ready === 'function' && typeof ret !== 'undefined') {\n ready(ret);\n }\n }",
"function getAccessTokenFromURL() {\n return getParameterByName('access_token');\n}",
"function getAccessToken(){\n return sessionStorage.getItem('accessToken');\n}",
"static getToken(){\r\n\t\tvar accessCode = OfficeAuth.getJsonFromUrl().code;\r\n\t\tvar params = { \r\n\t\t\tgrant_type: \"authorization_code\", \r\n\t\t\tcode: accessCode\r\n\t\t}; \r\n\r\n\t\t// Split the query string (after removing preceding '#'). \r\n\t\tvar queryStringParameters = OfficeAuth.splitQueryString(window.location.hash.substr(1)); \r\n\t\t\r\n\t\t// Extract token from urlParameterExtraction object. Show token for debug purposes\r\n\t\tvar token = queryStringParameters['access_token']; \r\n\t\treturn token;\r\n\t}",
"checkForToken() {\n let hash = this.props.location.hash || this.props.location.search;\n if (hash === \"\") return;\n\n const params = this.getParams(hash);\n if (params.access_token) this.attemptSignIn(params.access_token);\n if (params.error) {\n this.props.history.push(\"/\");\n }\n }",
"getAccessToken(){\n if (accessToken){\n return accessToken;\n }\n \n // check for access token and expire time match (returned in the URL from Spotify)\n const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);\n const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);\n\n // if both the access token and expiration time were retrieved form the URL\n if (accessTokenMatch && expiresInMatch){\n accessToken = accessTokenMatch[1];\n const expiresIn = Number(expiresInMatch[1]);\n \n // this clears the parameters, allowing us to grab a new access token when it expires\n window.setTimeout(() => accessToken = '', expiresIn * 1000);\n window.history.pushState('Access Token', null, '/');\n return accessToken;\n \n //if one or either the access token and expire time arent retreived, user is redirected\n } else {\n const accessURL = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`\n window.location = accessURL;\n }\n }",
"function getAccessToken() {\n /*\n *The access token is returned in the hash part of the document.location\n * #access_token=1234&response_type=token\n */\n\n const response = hash.replace(/^#/, '').split('&').reduce((result, pair) => {\n const keyValue = pair.split('=');\n result[keyValue[0]] = keyValue[1];\n return result;\n }, {});\n\n\n\n if (!localStorage.getItem(response.state)) {\n // We need to verify the random state we have set before starting the request,\n // otherwise this could be an access token belonging to someone else rather than our user\n document.getElementById('step-2').style.display = 'none';\n alert(\"CSRF Attack\");\n return;\n }\n\n if (response.access_token) {\n document.getElementById('step-1').style.display = 'none';\n } else {\n start();\n const error = document.createElement('p');\n error.innerHTML = response.error_description.split('+').join(' ');\n document.getElementById('step-1').appendChild(error);\n return;\n }\n\n localStorage.removeItem(response.state);\n\n // The token is removed from the URL\n document.location.hash = '';\n\n // The token is used to fetch the user's list of sites from the account API\n fetch('https://account-api.datocms.com/sites', {\n headers: {\n 'Authorization': 'Bearer ' + response.access_token,\n 'Accept': 'application/json',\n }\n }).then((response) => {\n return response.json();\n }).then((json) => {\n showOutput('Your sites: ' + json.data.map((site) => {\n const domain = site.attributes.domain || site.attributes.internal_domain;\n const url = `https://${domain}/`;\n const accessUrl = `${url}enter?access_token=${site.attributes.access_token}`;\n return `<a href=\"${accessUrl}\">${site.attributes.name}</a>`;\n }).join(', '));\n }).catch((error) => {\n showOutput(`Error fetching sites: ${error}`);\n });\n}",
"getAccessToken() {}",
"function getAuthInfoFromUrl() {\n if (window.location.hash) {\n var authResponse = window.location.hash.substring(1);\n var authInfo = JSON.parse(\n '{\"' + authResponse.replace(/&/g, '\",\"').replace(/=/g, '\":\"') + '\"}',\n function (key, value) { return key === \"\" ? value : decodeURIComponent(value); });\n return authInfo;\n }\n else {\n console.error(\"failed to receive auth token\");\n }\n}",
"getAccessToken() {\n\n\t\tvar accessToken = null;\n\n\t\t// check for access token in localStorage\n\t\tif (typeof (Storage) !== 'undefined') {\n\t\t\tvar storedToken = localStorage.getItem('ACCESS_TOKEN');\n\t\t\tif (typeof storedToken === 'string') {\n\t\t\t\taccessToken = storedToken;\n\t\t\t}\n\t\t}\n\n\t\t// check if access token is set within query params, and save it\n\t\tvar locationHash = window.location.hash;\n\t\tif (!accessToken && locationHash && locationHash.length > 0) {\n\t\t\tlocationHash.substr(1).split('&').forEach(param => {\n\t\t\t\tvar keyValue = param.split('=');\n\t\t\t\tif (keyValue[0] === 'access_token' && typeof keyValue[1] === 'string') {\n\t\t\t\t\taccessToken = keyValue[1];\n\t\t\t\t\tlocalStorage.setItem('ACCESS_TOKEN', accessToken);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\treturn accessToken;\n\t}",
"function getAccessTokenFromUrl() {\n // If the url has an access_token, it is returned. Else null.\n var URI = window.location.hash;\n var result = null;\n if (typeof URI === 'string') {\n // Remove leading and trialing white space\n URI.trim();\n\n // Replace the # sign at beginning\n URI.replace(/^#/)\n\n // Check that string exists\n if (URI.length == 0) {\n return null;\n }\n else {\n // split by & and find access_token\n var parts = URI.split(\"&\");\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n if (part.match('access_token=')){\n result = part.split('=')[1];\n return result;\n }\n else if (part.match('error=')) {\n result = part.split('=')[1];\n return result;\n }\n }\n }\n }\n return null;\n }",
"checkForAccessToken() {\n if (window.location.hash) {\n const accessToken = window.location.hash.replace(/.*access_token=([^&]+).*/, '$1');\n const timestamp = Date.now(); \n this.props.storeToken(accessToken, timestamp);\n this.saveTokenToLocalStorage({\n token: accessToken,\n timestamp: timestamp\n });\n return true;\n } else if (this.props.accessToken) {\n return true;\n }\n else {\n return false;\n }\n }",
"function isLoggingIn() {\n return window.location.hash.search(/access_token/) !== -1;\n}",
"function getToken(){\n return userService.$user.access_token;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set REDIS hash key(s) | async setHash(key, data) {
// this.log(`Caching hash ${key}`);
const fields = Object.keys(data);
if (fields.length > 1)
await this.client.hmset(key, ...fields.map((field) => [field, data[field]]).flat());
else
await this.client.hset(key, fields[0], data[fields[0]]);
} | [
"set (key, value) {\n let hashed = hash(key);\n this.buckets[hash % this.buckets.length].push({key : value});\n }",
"setKey(hash) {\n this[hashSym].set(hash);\n return this;\n }",
"function setRedisKey(key, value){\n client.set(key, value, function(err, response){\n if (err) console.log(err, err.stack);\n else {\n console.log(\"Response: \"+ response);\n client.expire(key, 30); // key expires in 30 seconds\n getRedisKey(key);\n }\n });\n}",
"async set(hash, key, value) {\n\n if (typeof value == 'object')\n value = JSON.stringify(value);\n\n return await this.client.hsetAsync(hash, key, value);\n }",
"function setToRedis(key, value) {\n client.SET(key, value, \"EX\", 60 * 60, function (err) {\n if (err) {\n console.error(\"Error Saving Data: \", err);\n }\n });\n}",
"static setData(hash, key, value) {\n let promise = new Promise((resolve, reject) => {\n connectRedis.HSET(JSON.stringify(hash), JSON.stringify(key), JSON.stringify(value), (err, reply) => {\n if (err) {\n console.log(err)\n reject(err.message)\n }\n resolve(reply)\n })\n })\n return promise\n }",
"set(key, value){\n let index = this._hash(key);\n if(!this.keyMap[index]){\n this.keyMap[index] = [];\n }\n this.keyMap[index].push([key, value]);\n }",
"set(key, value) {\n //*this variable will hash the key giving it an index\n let index = this._hash(key);\n //*Checking if there is any data in that index\n if (!this.keyMap[index]) {\n //*If the index is empty it will be set to an empty array\n this.keyMap[index] = [];\n }\n //*This will push the setted data into the array with a key-value pair even if it is the same index\n this.keyMap[index].push([key, value]);\n }",
"set(key,value){\n let index = this._hash(key)\n\n if(!this.keyMap[index]){\n this.keyMap[index] = []\n }\n this.keyMap[index].push([key,value])\n\n }",
"function setValues(key, set) {\n var setJson = JSON.stringify(set);\n redisClient.set(key, setJson, function (err, reply) {\n if (reply)\n console.log(key + ': ', reply);\n if (err)\n console.log('Error adding ' + key + ': ', err);\n });\n}",
"function setKey(key, data) {\n 'use strict';\n \n if (data !== undefined && data !== null && typeof(data) === 'string'\n && key !== undefined && key !== null && typeof(key) === 'string') {\n _redisConnection.set(key, data);\n }\n}",
"function setValue(key, value) {\n redis.set(key, value);\n}",
"function setHashKey(obj, h) {\n if (h) {\n obj.$$hashKey = h;\n } else {\n delete obj.$$hashKey;\n }\n }",
"function setHashKey(obj, h) {\n\t if (h) {\n\t obj.$$hashKey = h;\n\t } else {\n\t delete obj.$$hashKey;\n\t }\n\t}",
"function caml_ephe_set_key(x, i, v) {\n return caml_weak_set(x, i, [0, v])\n}",
"function setHashKey(obj, h) { // 407\n if (h) { // 408\n obj.$$hashKey = h; // 409\n } else { // 410\n delete obj.$$hashKey; // 411\n } // 412\n} // 413",
"function setKeySet() {\n // Sets a value on the keyset and on its given destination\n const START = log('\\n-- START EXAMPLE (SetKeySet) --\\n');\n const KeySetMap = new Map([\n ['example:set:one', { example: 'one' }],\n ['example:set:two', { example: 'two' }],\n ['example:set:three', { example: 'three' }],\n ]);\n return redis.msetkeyset('example:set', KeySetMap).then(result => {\n const END = log('Result Ready!', result);\n log('Time for Execution: ', END - START);\n });\n}",
"function setHashKey(obj, h) {\n\t\tif (h) {\n\t\t\tobj.$$hashKey = h;\n\t\t} else {\n\t\t\tdelete obj.$$hashKey;\n\t\t}\n\t}",
"set(key, value) {\n // 1. get my hash\n const hash = this.hash(key);\n\n // 2. make value entry\n const entry = {[key]: value};\n\n // 3. set the entry to the hash value in the map\n // 3.1 check to see if there is a hash there already - if not, I need to put in a LL\n if( !this.map[hash] ){ this.map[hash] = new LinkedList(); }\n // \n // 3.2 add the entry\n this.map[hash].add( entry );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads all of the selected patient's drawings to the cloud database | function sync(id) {
var uploaded = "No";
myDB.transaction(function(transaction) {
transaction.executeSql("SELECT * FROM drawings_local where pid=? AND uploaded=?", [id,uploaded], function(tx, results) {
if (results.rows.length == 0) {
navigator.notification.alert("Already synced");
} else {
var success = 1, i;
uploaded = "Yes";
for (i = 0; i < results.rows.length; i++) {
var dataString = "drawing=" + results.rows.item(i).drawing + "&score=" + results.rows.item(i).score + "&pid=" + results.rows.item(i).pid + "&uploaded=" + uploaded + "&insert=";
$.ajax({
type: "POST",
url: "https://aesthetics-tool.000webhostapp.com/upload_drawing.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
myDB.transaction(function(transaction) {
transaction.executeSql("UPDATE drawings_local SET uploaded=? WHERE pid=?", [uploaded,id], function(tx, result) {
},
function(error){success = 0;});
});
} else if (data == "error") {
success = 0;
}
}
});
}
if (success == 1) {
navigator.notification.alert("Sync complete");
} else {
navigator.notification.alert("Something went wrong");
}
}
},
function(error){ navigator.notification.alert('Something went Wrong');});
});
} | [
"function saveDrawing()\n{\n var ref = database.ref('drawings');\n var data = {\n \n drawing:drawing\n\n }\n ref.push(data);\n\n}",
"function loadDrawings() {\n while(i < 49) {\n drawing = \"drawings/\" + i + \".jpg\";\n drawingM = \"drawings/Mobile/\" + i + \".jpg\";\n i++;\n $scope.drawings.push(drawing);\n $scope.drawingsM.push(drawingM);\n }\n }",
"function saveDrawings(){\n\n\t// open up a progress bar (indicative, not accurate)\n\topenDialogProgress();\n\n\t// get data extent\n\tvar sightingsExt, routesExt;\n\n\n\tvar extent = polygon.getDataExtent().transform(map.getProjection(), new OpenLayers.Projection(\"EPSG:4326\"));\n\tsightingsExt = JSON.stringify(extent);\n\n\textent = polyline.getDataExtent().transform(map.getProjection(), new OpenLayers.Projection(\"EPSG:4326\"));\n\troutesExt = JSON.stringify(extent);\n\n\t// data json\n\tvar geoJsonWriter = new OpenLayers.Format.GeoJSON({\n \t\t'internalProjection': new OpenLayers.Projection(\"EPSG:900913\"),\n \t\t'externalProjection': new OpenLayers.Projection(\"EPSG:4326\")\n\t});\n\n\tvar prettyJson = false;\n\tpolygonGeoJSON = geoJsonWriter.write(polygon.features, prettyJson);\n\tpolylineGeoJSON = geoJsonWriter.write(polyline.features, prettyJson);\n\n\t/*\n\tconsole.log('GeoJson representation for sighting polygons:');\n\tconsole.log(polygonGeoJSON);\n\n\tconsole.log('GeoJson representation for activity routes:');\n\tconsole.log(polylineGeoJSON);\n\t*/\n\n\tvar sightingsFn = dataSaveInfo.sightingsFn;\n\tvar routesFn = dataSaveInfo.routesFn;\n\tvar egcEmail = dataSaveInfo.egcusrname;\n\n\tvar params = {\n\t\tSightingsFilename: sightingsFn,\n\t\tSightingsGeoJSON: polygonGeoJSON,\n\t\tSightingsExtent: sightingsExt,\n\t\tRoutesFilename: routesFn,\n\t\tRoutesGeoJSON: polylineGeoJSON,\n\t\tRoutesExtent: routesExt,\n\t\tEGCUsername: egcEmail,\n\t\tisLasha: false\n\t};\n\n\tif(mustWithinLashaArea){\n\t\tparams.isLasha = true;\n\t}\n\n\t/* HTTP POST request to save drawings on server */\n\tvar xmlhttp;\n\tif(window.XMLHttpRequest){\n\t\t// code for IE7+, Firefox, Chrome, Opera, Safari\n\t \txmlhttp=new XMLHttpRequest();\n\t }\n\telse{\n\t\t// code for IE6, IE5\n\t \txmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t }\n\txmlhttp.onreadystatechange=function(){\n\t\tif (xmlhttp.readyState==4){\n\t\t\tif(xmlhttp.status==200){\n\t\t\t\t// data were successfully processed and saved on server\n\t\t\t\tserverResponse = xmlhttp.responseText;\n\n\t\t\t\tif(dataSaveInfo.clearAfterSave){\n\t\t\t\t\tserverResponse = serverResponse + \" Your drawings will be cleared.\";\n\t\t\t\t}\n\n\t\t\t\topenDialogMessage(\"Server response\", serverResponse);\n\t\t\t\tserverSuccess = true;\n\n\t\t\t\t//alertify.success(serverResponse);\n\t\t\t\tconsole.log(serverResponse);\n\t\t\t\taddSuitabilityMap();\n\t\t\t}\n\t\t\telse{\n\t\t\t\t// error happened while saving data on server\n\t\t\t\tvar errmsg = \"Some thing went wrong. Please try again later.\";\n\t\t\t\topenDialogMessage(\"Server response\", errmsg);\n\t\t\t\tserverSuccess = false;\n\n\t\t\t\t//alertify.error(errmsg);\n\t\t\t\tconsole.log(errmsg);\n\t\t\t}\n\t\t}\n\t}\n\ttry{\n\t\txmlhttp.open(\"POST\", serverUrl, true);\n\t\txmlhttp.setRequestHeader(\"Content-type\",\"text/plain\");\n\t\txmlhttp.send(JSON.stringify(params));\n\t}\n\tcatch(e){\n\n\t\t// error happened while saving data on server\n\t\tvar errmsg = e.toString();\n\t\topenDialogMessage(\"Error message\", errmsg);\n\t\tserverSuccess = false;\n\n\t\t//alertify.error(errmsg);\n\t\tconsole.log(errmsg);\n\t}\n}",
"function draw() {\n let draw = snapshotFb[keys[index]];\n let imgSubmission = document.getElementById('imgSubmission');\n imgSubmission.src = draw.dataUrl;\n if (draw.accepted && !imgSubmission.classList.contains('accepted')) {\n imgSubmission.classList.add('accepted');\n } else {\n imgSubmission.classList.remove('accepted');\n }\n\n }",
"function saveSketchData(){\n // downsamplesketchpad before saving .png (backup to all stroke data)\n var canvas = document.getElementById(\"sketchpad\"),\n ctx=canvas.getContext(\"2d\");\n\n tmpCanvas = document.createElement(\"canvas\");\n tmpCanvas.width=150;\n tmpCanvas.height=150;\n destCtx = tmpCanvas.getContext('2d');\n destCtx.drawImage(canvas, 0,0,150,150)\n\n // what actually gets sent\n var dataURL = tmpCanvas.toDataURL();\n dataURL = dataURL.replace('data:image/png;base64,','');\n\n // change how we save condition/category depending on trial type \n if (stimList[curTrial].exp_phase=='T'){ // if this was a tracing trial...\n var condition = 'tracing';\n var category = stimList[curTrial].category; // what were they tracing\n var actor = 'none'\n var tracing_set = 'none' // relevant to what the child sees during upcoming videos, not to their own tracing trials\n }\n else if (stimList[curTrial].exp_phase=='D'){ // if this was a drawing trial\n var condition = stimList[curTrial].condition; // \n var category = 'none'\n var actor = stimList[curTrial].condition; // \n var tracing_set = stimList[curTrial].tracing_set; // \n }\n\n // now save the rest of the trial variables\n var exp_phase = stimList[curTrial].exp_phase; // tracing or drawing\n var CB = $('#CB').val(); // counterbalancing (1-8)\n var subID = $('#subID').val(); // subject ID\n var readable_date = new Date();\n\n // fill up the 'current data' structure with all this info to send\n current_data = {\n dataType: 'finalImage', // could be finalImage or stroke (see other function)\n sessionId: sessionId, // each children's session, independent of subject ID\n imgData: dataURL, // actual .pngs that we're saving\n category: category, // what kids were asked to trace/draw\n condition: condition, // selective vs. overpraise (if in drawing trial, just 'tracing' if not)\n actor: actor, // which actor they saw (if in drawing trial)\n tracing_set, tracing_set, // which set of tracings they saw (if in drawing trial)\n CB: CB, // counterbalancing\n redo_count: redo_count,\n subID: subID, // entered by experimenter at beginning\n date: readable_date, // today's date\n dbname:'kiddraw', // still in kiddraw database\n colname: version, // experiment name is \"version\", but praisedraw can have different versions\n trialNum: curTrial, // which trial number this was (including video/memory test, etc)\n startTrialTime: startTrialTime, // when this started (when sketchpad was shown)\n endTrialTime: Date.now()} // when trial was complete, e.g., now\n\n // send data to server to write to database\n socket.emit('current_data', current_data);\n}",
"function addDrugToPersonalDB(drugName, drugID, drugDosage)\n{\n\n//call API to save data\n\n}",
"function pullDancers(formation){\n database.ref(\"/\" + id + \"/\"+formation+\"/\").once('value', drawDancers);\n \n}",
"function saveMap() {\r\n\r\n // Loop through savedShapes and insert placeholder into \r\n // empty arrays in order to save it into Firebase\r\n for (var i = 0; i < savedShapes.length; i++) {\r\n if (savedShapes[i].name === \"building\") {\r\n for (var j = 0; j < savedShapes[i].internal.length; j++) {\r\n if (savedShapes[i].internal[j].length === 0) {\r\n savedShapes[i].internal[j].push(\"empty\");\r\n }\r\n }\r\n\r\n if (savedShapes[i].lifts.length === 0) {\r\n savedShapes[i].lifts.push(\"empty\");\r\n }\r\n if (savedShapes[i].stairs.length === 0) {\r\n savedShapes[i].stairs.push(\"empty\");\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n var nowDate = new Date();\r\n var date = nowDate.getDate() + '/' + (nowDate.getMonth() + 1) + '/' + nowDate.getFullYear();\r\n\r\n // Combine map name, categories and mapdata in to single object\r\n var mapData = {\r\n mapName: mapName,\r\n categories: objectCategories,\r\n mapData: savedShapes,\r\n userID: userID,\r\n active: true,\r\n updatedDate: date,\r\n }\r\n\r\n if (!editingMap) {\r\n mapData.createdDate = date;\r\n mapData.code = generateCode(6);\r\n }\r\n\r\n // Push data to database\r\n var db = firebase.database();\r\n if (editingMap) {\r\n db.ref(\"MapData/\" + mapToEdit[0]).update({\r\n mapName: mapName,\r\n categories: objectCategories,\r\n mapData: savedShapes,\r\n userID: userID,\r\n active: true,\r\n updatedDate: date,\r\n })\r\n }\r\n else {\r\n var ref = db.ref(\"MapData\");\r\n ref.push(mapData);\r\n }\r\n\r\n window.location.href='#/admin'\r\n }",
"async function saveAllRecordsToDB(){\n const datasets = await listDatasetsFileSystem();\n for (const dataset of datasets){\n const recordIds = await getDatasetRecordIdsFileSystem(\n 'review',\n dataset\n );\n for (const recordId of recordIds){\n const data = JSON.stringify({\n 'dataset': dataset,\n 'record_id':recordId\n });\n await $.post('/save-reocord-to-db', data);\n }\n }\n}",
"function updateDrawing()\n{\n // First, we need to get the selected index in the HTML drawing list.\n var HTMLDrawingList = $(\"#DrawingIDList\")[0];\n // The selectedIndex attribute belongs to any <select> tag.\n // It represents the current index of the selected item.\n var drawingIndex = HTMLDrawingList.selectedIndex;\n\n // Since the items in the drawinginfoList is the same order\n // as the drawings list, the index of the selected item also represents\n // the index of the drawing item in the array.\n var selectedDrawing = drawings[drawingIndex];\n selectedDrawing.BuildingName = $(\"#buildingNameInput\").val();\n selectedDrawing.ConstructedYear = $(\"#constructedYearInput\").val();\n selectedDrawing.Contractor = $(\"#contractorInput\").val();\n selectedDrawing.Floor = $(\"#floorInput\").val();\n selectedDrawing.Shop = $(\"#shopInput\").val();\n\n // After updating the attributes, set the object back to the same location in the drawing array.\n drawings[drawingIndex] = selectedDrawing;\n}",
"function uploadSelected() {\n var selected = $(\".mdl-checkbox__input:checked\"); // Determines if survey is marked for upload\n var surveys = []; // collection of all surveys to be uploaded\n var promises = []; // each callback is going to promise to return, used to prevent async uploading\n\n // check if any surveys selected\n if (selected.length == 0) {\n alert(\"No Surveys Selected\");\n return;\n }\n\n // for each survey marked for upload ...\n for (var i = 0; i < selected.length; i++) {\n var deferred = new $.Deferred();\n\n promises.push(deferred); // Add this to the list of pending callbacks\n\n // Retrieve survey from localforage and add it to surveys to be uploaded\n Surveys.getById(selected[i].parentElement.id, deferred, function(survey) {\n surveys.push(survey);\n });\n }\n\n // Once all promises have resolved, upload the surveys to the server\n Promise.all(promises).then(function() {\n window.survey_post.upload(surveys)\n });\n}",
"function drawPapers(signal_id, signal_cat_id) {\n // if we have an associated signal, filter by it\n let values = {\n selections: minimizeSelections(),\n query: currSearchQuery,\n increment: currIncrement,\n rangeLeft: sentenceRangeAbove,\n rangeRight: sentenceRangeBelow,\n lastRank: 0,\n nrank: nPaperLoad,\n signals: {},\n journalid: \"\"\n };\n\n // add a set of signals based on their category\n if (typeof signal_cat_id != \"undefined\") {\n for (let id in sentiment_signals) {\n let signal = sentiment_signals[id];\n if (signal.category == signal_cat_id) {\n values[\"signals\"][id] = signal;\n }\n }\n } else {\n // alternatively, filter by a single signal\n if (typeof signal_id != \"undefined\") {\n values[\"signals\"][signal_id] = sentiment_signals[signal_id];\n for(let f of sentiment_signals[signal_id].filters) {\n values[\"signals\"][f] = sentiment_signals[f];\n }\n for(let f of sentiment_signals[signal_id].restrictions) {\n values[\"signals\"][f] = sentiment_signals[f];\n }\n }\n }\n paperRequests.push(\n $.ajax({\n type: \"POST\",\n url: processURL + \"papers\",\n data: JSON.stringify(values),\n success: function(data) {\n paper_data = JSON.parse(data);\n drawPapersByIndex(paper_data);\n },\n async: true,\n timeout: 600000\n })\n );\n}",
"function saveSketchData(){\n\t// downsamplesketchpad before saveing\n\tvar canvas = document.getElementById(\"sketchpad\"),\n ctx=canvas.getContext(\"2d\");\n \n tmpCanvas = document.createElement(\"canvas\");\n tmpCanvas.width=150;\n tmpCanvas.height=150;\n destCtx = tmpCanvas.getContext('2d');\n\tdestCtx.drawImage(canvas, 0,0,150,150)\n\n var dataURL = tmpCanvas.toDataURL();\n //var dataURL = canvas.toDataURL();\n // console.log(dataURLTest.length)\n // console.log(\"should be longer\" +dataURL.length)\n \n \n dataURL = dataURL.replace('data:image/png;base64,','');\n var category = stimListTest[curTrial].category;\n var age = document.getElementById('years').value;\n\n // test stirng\n readable_date = new Date();\n current_data = {\n dataType: 'finalImage',\n sessionId: sessionId,\n imgData: dataURL,\n category: category,\n dbname:'kiddraw',\n colname:'E1d',\n trialNum: curTrial,\n time: Date.now(),\n date: readable_date,\n age: age}; \n\n // send data to server to write to database\n socket.emit('current_data', current_data);\n}",
"async function storeCravings(phoneNum, score, date) {\n // Find a patient by phone number \n const pt = await Patient.findOne({ 'personalData.phone': phoneNum }); \n const data = {\n score: score, \n date: date, \n }; \n\n pt.medicalData.textData.cravings.push(data); \n await pt.save(); \n\n}",
"function addDrawing()\n{\n // Ask the user to enter an ID for the new drawing.\n var newID = prompt(\"Please enter a new ID for the drawing\");\n if(newID==undefined)\n {\n alert(\"Please enter the new ID.\");\n return;\n }\n\n // Check whether this new ID exists in the drawing list.\n for(var i=0;i<drawings.length;i++)\n {\n if(drawings[i].DrawingID == newID)\n {\n alert(\"This ID exists.\");\n return;\n }\n }\n\n // If this ID does not exist, using the information from the current text boxes\n // to create the new drawing object.\n var buildingNameText = $(\"#buildingNameInput\").val();\n var constructedYearText = $(\"#constructedYearInput\").val();\n var contractorText = $(\"#contractorInput\").val();\n var floorText = $(\"#floorInput\").val();\n var shopText = $(\"#shopInput\").val();\n\n var newDrawing = new Drawing(newID, buildingNameText,constructedYearText,\n contractorText,floorText);\n\n newDrawing.Shop = shopText;\n\n // Add teh new drawing object to the list.\n drawings.push(newDrawing);\n\n // Reload the HTML drawing list tag.\n addDrawingInfoToList();\n}",
"startDrawing() {\n const url = this.editor.config.drawioUrl;\n if (!url) return;\n\n const selectionRange = this.#getSelectionRange();\n\n DrawIO.show(url, () => Promise.resolve(''), async pngData => {\n const data = {\n image: pngData,\n uploaded_to: Number(this.editor.config.pageId),\n };\n\n try {\n const resp = await window.$http.post('/images/drawio', data);\n this.#insertDrawing(resp.data, selectionRange);\n DrawIO.close();\n } catch (err) {\n this.handleDrawingUploadError(err);\n throw new Error(`Failed to save image with error: ${err}`);\n }\n });\n }",
"function drawImages() {\n if (counter < project.renderImages.length) {\n var imageForm = new FormData();\n ctx.clearRect(0, 0, canvasRender.width, canvasRender.height);\n var image = project.renderImages[counter];\n var posX = parseInt((res.width / 2) - (image.originalWidth / 2));\n var posY = parseInt((res.height / 2) - (image.originalHeight / 2));\n ctx.putImageData(image, posX, posY);\n var imgData = canvasRender.toDataURL(\"image/jpeg\", 1.0);\n // convert base64 string to blob\n var blobBin = atob(imgData.split(',')[1]);\n var array = [];\n for (var j = 0; j < blobBin.length; j++) {\n array.push(blobBin.charCodeAt(j));\n }\n var file = new Blob([new Uint8Array(array)], {\n type: 'image/jpeg'\n });\n\n var fieldname = filename = \"image\" + counter;\n console.log(\"making\", filename);\n imageForm.append('projectID', project.getProjectID());\n imageForm.append('currImageNum', counter + 1);\n imageForm.append(fieldname, file, filename + \".jpg\");\n\n var request = new XMLHttpRequest();\n request.open(\"POST\", \"/render\");\n request.send(imageForm);\n request.onreadystatechange = function() {\n if (request.readyState == 4) {\n if (request.status === 200) {\n drawImages();\n } else {\n swal(\"Error\", \"There was a problem with the image upload. Try again\", \"error\");\n }\n }\n }\n counter += 1;\n } else {\n done = true;\n formData.append('currImageNum', counter);\n }\n }",
"function save_click() {\n var points = [];\n var name = document.getElementById('disaster_name').value;\n var city = document.getElementById('disaster_city').value;\n var state = document.getElementById('disaster_state').value;\n var date = document.getElementById('disaster_date').value;\n var reason = document.getElementById('disaster_reason').value;\n var error = document.getElementById('error');\n\n //alert(reason);\n if (name == \"\" || city == \"\" || date == \"\") {\n\n error.innerHTML = \"Please Fill In Form Completely!\";\n\n }\n\n else {\n\n var result = JSON.stringify(polyPoints);\n var start = new Date().getTime();\n\n var Policies = sort_policies();\n $.post(\"ajax/saveAjax.php\", {\n name: name,\n date: date,\n city: city,\n state: state,\n polygon: result,\n reason: reason,\n properties: Policies\n\n })\n .done(function (data) {\n //console.log(data);\n location.reload();\n });\n\n }\n\n}",
"function draw() {\n ctx.clearRect(0, 0, getCanvasSize(0), getCanvasSize(1));\n var countries = $scope.countriesJSON[\"countries\"]\n for (var countryIndex=0; countryIndex < countries.length; countryIndex++){\n var country=countries[countryIndex];\n var areas=country[\"areas\"];\n \n for (var areaIndex=0; areaIndex < areas.length; areaIndex++){\n var area=areas[areaIndex];\n var drawingResult=drawArea(area, getAreaColor(country, area));\n\n if (isSelectedCountry(country)){\n var subAreas=$scope.selectedCountry[\"subareas\"];\n for (var subAreaIndex=0; subAreaIndex<subAreas.length; subAreaIndex++){\n var subArea = subAreas[subAreaIndex];\n var color;\n if (isSelectedArea(subArea)){\n color=selectedColor;\n }\n var subAreaDrawingResult = drawArea(subArea, color);\n writeName(subArea[\"name\"], subAreaDrawingResult);\n }\n }else if (area[\"substract\"] != 1){\n writeName(country[\"name\"], drawingResult);\n }\n }\n }\n \n if ($scope.addingRegion){\n if (newArea.length >= 1){\n if (newArea.length == 1){\n drawCross(newArea[0])\n }else {\n drawShape(newArea);\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes callback once every interval specified. Defaults to 1000ms. Will stop when executed for repeatCount times. Normally this will return an interval id integer, but if specified this may return a Timer object too. | function interval(callback, interval, repeatCount) {
if (typeof interval === "undefined") { interval = 1000; }
if (typeof repeatCount === "undefined") { repeatCount = 1; }
if (repeatCount === 0) {
return Runtime.getTimer().setInterval(callback, interval);
}
var ivl = Runtime.getTimer().setInterval(function () {
repeatCount--;
if (repeatCount < 0) {
Runtime.getTimer().clearInterval(ivl);
} else {
callback();
}
}, interval);
return ivl;
} | [
"setInterval(script, interval) {\n const timerId = this.getId();\n\n this.create(timerId, 0, interval, script);\n\n return () => sp.DeleteTimer(timerId);\n }",
"function setInterval(callBack, delay) {\n let a = {\n clear: function () {\n clearTimeout(a.timer)\n }\n };\n (function run() {\n callBack();\n a.timer = setTimeout(run, delay);\n })();\n\n return a;\n}",
"setInterval(listener, interval) {\n // eslint-disable-line bad-sim-text\n let elapsed = 0;\n const callback = dt => {\n elapsed += dt;\n\n // Convert seconds to ms and see if item has timed out\n while (elapsed * 1000 >= interval && this.hasListener(callback)) {\n listener();\n elapsed = elapsed - interval / 1000.0; // Save the leftover time so it won't accumulate\n }\n };\n\n this.addListener(callback);\n\n // Return the callback so it can be removed with removeListener\n return callback;\n }",
"function limitedRepeat() {\n let intervalId = setInterval(console.log(\"hi for now\"), 100);\n setTimeout(() => clearInterval(intervalId), 500);\n}",
"periodically (interval, name, fn) {\n setTimeout(async () => {\n while (!this._stop) {\n await this._runFunction(name, fn);\n await new Promise(resolve => setTimeout(resolve, interval));\n }\n }, interval);\n }",
"function makeClosureForTimer(element, interval) {\n\n var counter = 0;\n setInterval(timeIt, interval);\n function timeIt() {\n element.textContent = `${interval}ms per tick: ${counter}`;\n counter++;\n }\n}",
"function Interval(callback, delay) {\n var args = arguments,\n self = this,\n timer, start;\n\n this.log = function() {\n console.log(timer);\n }\n\n this.clear = function () {\n clearInterval(timer);\n };\n\n this.pause = function () {\n this.clear();\n };\n\n this.resume = function () {\n start = new Date();\n timer = setInterval(function () {\n callback.apply(self, Array.prototype.slice.call(args, 2, args.length));\n }, delay);\n };\n\n this.resume();\n}",
"function interval_example() {\n\tvar start_time = new Date();\n\tsys.puts('\\nStarting 2 seconds interval, stop after 5th tick');\n\tvar count = 1;\n\tvar interval = setInterval(function() {\n\t\tif (count == 5) {\n\t\t\tclearInterval(this);\n\t\t}\n\t\tvar end_time = new Date();\n\t\tvar difference = end_time.getTime() - start_time.getTime();\n\t\tsys.puts('Tick number: ' + count + ' after ' + Math.round(difference / 1000) + ' seconds.');\n\t\tcount++;\n\t}, 2000);\n}",
"function interval_example() {\r\n var start_time = new Date();\r\n sys.puts(\"\\nStarting 2 second interval, stopped after 5th tick\");\r\n var count = 1;\r\n var interval = setInterval(function() {\r\n if (count == 5) clearInterval(this);\r\n var end_time = new Date();\r\n var difference = end_time.getTime() - start_time.getTime();\r\n sys.puts(\"Tick no. \" + count + \" after \" + Math.round(difference/1000) + \" seconds\");\r\n count++;\r\n }, 2000);\r\n}",
"_tick () {\n this.milliseconds += this.interval\n if (this.callback) this.callback(this.seconds())\n }",
"function runTimer() {\n interval = setInterval(updateTimer, 1000);\n}",
"function AsyncTimer(interval, callback, callBackContext, enabled, callOnFirstStart) {\n if (callBackContext === void 0) { callBackContext = null; }\n if (enabled === void 0) { enabled = false; }\n if (callOnFirstStart === void 0) { callOnFirstStart = false; }\n this.interval = interval;\n this.callback = callback;\n this.callBackContext = callBackContext;\n this.enabled = enabled;\n this.callOnFirstStart = callOnFirstStart;\n //#region Properties\n this.tickCount = 0;\n this.timeout = 0;\n if (enabled && callback) {\n this.start();\n }\n }",
"function test6() {\n // repeat with the interval of 2 seconds\n let timerId = setInterval(() => console.log('tick'), 2000);\n\n // after 5 seconds stop\n setTimeout(() => {\n clearInterval(timerId);\n console.log('stop');\n }, 5000);\n}",
"function myInterval(){\nsetInterval(next(),3000);\n}",
"function interval( speed, ticks ) {\n\t\t\tvar newInterval,\n\t\t\t\toldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;\n\n\t\t\tif ( speed ) {\n\t\t\t\tswitch ( speed ) {\n\t\t\t\t\tcase 'fast':\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tnewInterval = 5000;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 15:\n\t\t\t\t\t\tnewInterval = 15000;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 30:\n\t\t\t\t\t\tnewInterval = 30000;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 60:\n\t\t\t\t\t\tnewInterval = 60000;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 120:\n\t\t\t\t\t\tnewInterval = 120000;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'long-polling':\n\t\t\t\t\t\t// Allow long polling, (experimental)\n\t\t\t\t\t\tsettings.mainInterval = 0;\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tnewInterval = settings.originalInterval;\n\t\t\t\t}\n\n\t\t\t\tif ( settings.minimalInterval && newInterval < settings.minimalInterval ) {\n\t\t\t\t\tnewInterval = settings.minimalInterval;\n\t\t\t\t}\n\n\t\t\t\tif ( 5000 === newInterval ) {\n\t\t\t\t\tticks = parseInt( ticks, 10 ) || 30;\n\t\t\t\t\tticks = ticks < 1 || ticks > 30 ? 30 : ticks;\n\n\t\t\t\t\tsettings.countdown = ticks;\n\t\t\t\t\tsettings.tempInterval = newInterval;\n\t\t\t\t} else {\n\t\t\t\t\tsettings.countdown = 0;\n\t\t\t\t\tsettings.tempInterval = 0;\n\t\t\t\t\tsettings.mainInterval = newInterval;\n\t\t\t\t}\n\n\t\t\t\t// Change the next connection time if new interval has been set.\n\t\t\t\t// Will connect immediately if the time since the last connection\n\t\t\t\t// is greater than the new interval.\n\t\t\t\tif ( newInterval !== oldInterval ) {\n\t\t\t\t\tscheduleNextTick();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;\n\t\t}",
"function run() {\n clearInterval(timer);\n timer = setInterval(timerFunc, 1000);\n }",
"async interval(L, T) {\n const secs = lauxlib.luaL_checknumber(L, 1);\n lua.lua_pop(L, 1);\n\n const timer = new pollable.PollableInterval(Math.floor(secs*1000));\n this.pushDeviceReference(T, timer);\n return 1;\n }",
"startInterval(){\n this.stopInterval();\n this.interval = setInterval(() => {\n this.dispatchMessageEvent();\n }, parseInt(this.repeat.value));\n }",
"createRepeater(delaySecs, interval) {\n return timerService.makeRepeater(delaySecs, interval);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a function to remove all null values from an array. | function removeNull(arr) {
return arr.filter(Boolean);
} | [
"function removeNull(array) {\n\t\t\t\treturn array.filter(x => x !== null)\n\t\t\t}",
"function filterNulls(arr){\n return arr.filter( x => x == null)\n}",
"function clean(arr) {\n return arr.filter(value => value !== null && value !== undefined);\n}",
"removeNullVals(A){\n return A.filter(elem => elem!=null)\n }",
"filterNull(arr){\n return arr.filter(i => i !== null);\n }",
"function trimNull(array){\n for(var i = 0; i<array.length; i++) {\n if(array[i] == null) {\n array.splice(i--, 1);\n }\n }\n // console.log('Trimmed array: ');\n // console.log(array)\n }",
"function compactArray( arr ) {\n\tvar compacted = arr.filter(function(elm){ return (elm != null);}); \n\treturn compacted;\n}",
"function removeNullsFromArray(arr) {\n var arr1 = arr;\n for (var k in arr1) {\n arr1[k] = removeNulls(arr1[k]);\n }\n return arr1;\n}",
"function compact(arr) {\n return filter(arr, function(val){\n return (val != null);\n });\n }",
"function filterArray(arr) {\n return arr.filter((ele) => ele !== null && ele !== undefined);\n}",
"function clean(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] === null || arr[i] === undefined) {\n arr.splice(i, 1);\n i--;\n }\n }\n return arr;\n}",
"function array_remove_undefined(arr) {\n var undef;\n arr=arr.concat([]);\n\n for(var i=0; i<arr.length; i++) {\n if((arr[i]===undef)||(arr[i]===null)) {\n arr=array_remove(arr, i);\n i--;\n }\n }\n\n return arr;\n}",
"function filterEmptyItem(array){\r\n const filteredArray = array.filter(item => item !== null);\r\n return filteredArray;\r\n}",
"function filtesFalsy(arr) {\r\n array = arr.slice();\r\n for (var i = 0; i < arr.length; i++) {\r\n switch (arr[i]) {\r\n case false:\r\n array.splice(i, 1);\r\n break;\r\n case null:\r\n array.splice(i, 1);\r\n break;\r\n case '':\r\n array.splice(i, 1);\r\n break;\r\n case 0:\r\n array.splice(i, 1);\r\n break;\r\n case 'undefined':\r\n array.splice(i, 1);\r\n break;\r\n }\r\n }\r\n return array;\r\n}",
"function emptyToNull(array) {\n if (array && array.length === 0) {\n return null;\n }\n return array;\n }",
"function cleanArray(arr) {\n var len = arr.length,\n i;\n\n for (i = 0; i < len; i++) {\n if (arr[i] && typeof arr[i] != \"undefined\") {\n arr.push(arr[i]); // copy non-empty values to the end of the array\n }\n }\n\n arr.splice(0, len); // cut the array and leave only the non-empty values\n\n return arr;\n }",
"function cutArrNullEnd(arr) {\n for (var i = (arr.length - 1); i >=0; i--) {\n if (1*arr[i] !== 0) {\n return arr;\n } else {\n arr.splice(i, 1);\n };\n };\n return arr;\n }",
"function removeFalsy(arr) {\r\n return arr.filter(a => !!a);\r\n }",
"function removeBlankValues(array) {\n\t\tvar splicedArray = array.slice(0);\n\t\twhile (splicedArray.indexOf(\"\") !== -1) {\n\t\t\tvar index = splicedArray.indexOf(\"\");\n\t\t\tsplicedArray.splice(index, 1);\n\t\t}\n\t\t\n\t\treturn splicedArray;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove the dead connections from the given connection list. | function cleanList(list) {
var prev;
var conn = list.first;
while (conn !== null) {
var next = conn.nextReceiver;
if (!conn.callback) {
conn.nextReceiver = null;
}
else if (!prev) {
list.first = conn;
prev = conn;
}
else {
prev.nextReceiver = conn;
prev = conn;
}
conn = next;
}
if (!prev) {
list.first = null;
list.last = null;
}
else {
prev.nextReceiver = null;
list.last = prev;
}
} | [
"function cleanupConnections(connections) {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }",
"function cleanupConnections(connections) {\n algorithm_1.ArrayExt.removeAllWhere(connections, isDeadConnection);\n }",
"function cleanupConnections(connections) {\r\n algorithm_1.ArrayExt.removeAllWhere(connections, isDeadConnection);\r\n }",
"cleanZombies(){\n let zombies = new CuteSet();\n for(let conn of this.connections){\n if (!this.connectionManager.isAlive(conn)){\n zombies.add(conn);\n }\n }\n if (zombies.length > 0){\n Logger.debug(`Found zombie connecions: ${JSON.stringify(zombies.toArray())}`, {cat: \"connection\"});\n this.connections = this.connections.minus(zombies);\n }\n }",
"removeActiveConnection(state, connection) {\n state.activeConnections = state.activeConnections.filter(existingConnection => existingConnection.id !== connection.id)\n }",
"function clearConnections() {\n\t that.connections.forEach(function (connection) {\n\t connection.getEndpoint().leftGroup();\n\t });\n\t that.connections = [];\n\t }",
"function unsubscribeAll(conn){\n\tfor (var service in subscriptions){\n\t\tvar index = subscriptions[service].indexOf(conn);\n\t\tif (index>-1)\n\t\t\tsubscriptions[service].splice(index, 1);\n\t}\n}",
"function removeFromSendersList(conn) {\n var receiver = conn.thisArg || conn.callback;\n var prev = conn.prevSender;\n var next = conn.nextSender;\n if (prev === null && next === null) {\n receiverMap.delete(receiver);\n }\n else if (prev === null) {\n receiverMap.set(receiver, next);\n next.prevSender = null;\n }\n else if (next === null) {\n prev.nextSender = null;\n }\n else {\n prev.nextSender = next;\n next.prevSender = prev;\n }\n conn.prevSender = null;\n conn.nextSender = null;\n}",
"disconnect(c) {\n const index = this.connections.indexOf(c);\n if (index > -1) {\n this.connections.splice(index, 1); // removes one element starting at index\n }\n }",
"function removeFromSendersList(conn) {\n var receiver = conn.thisArg || conn.callback;\n var prev = conn.prevSender;\n var next = conn.nextSender;\n if (prev === null && next === null) {\n receiverMap.delete(receiver);\n }\n else if (prev === null) {\n receiverMap.set(receiver, next);\n next.prevSender = null;\n }\n else if (next === null) {\n prev.nextSender = null;\n }\n else {\n prev.nextSender = next;\n next.prevSender = prev;\n }\n conn.prevSender = null;\n conn.nextSender = null;\n }",
"unregisterConnection(connection) {\n this.incomingConnections = this.incomingConnections.filter(element => {\n return element.id !== connection.id;\n });\n\n this.outgoingConnections = this.outgoingConnections.filter(element => {\n return element.id !== connection.id;\n });\n\n this.updateDependentActionStatus(connection);\n }",
"function remove_duplicates_between_lists(selectors_hash){\n var unused_conn;\n var other_list_items =$(selectors_hash['other_lists_arr'].join(\", \")).find(\"li\");\n $(selectors_hash['unused_list']).find('li').each(function(){\n unused_conn=$(this);\n //console.log(\"TESTING: \"+unused_conn.text()+\" is in collections\"+is_connection_already_in_collection(unused_conn, $(selectors_hash['other_lists_arr'].join(\", \")) ));\n if(is_connection_already_in_collection(unused_conn, other_list_items) ) {\n //console.log(\"removing\"+unused_conn.attr(\"id\"));\n unused_conn.remove();\n }\n }); \n}",
"function removeFromSendersList(conn) {\n\t var receiver = conn.thisArg || conn.callback;\n\t if (!receiver) {\n\t return;\n\t }\n\t var prev = conn.prevSender;\n\t var next = conn.nextSender;\n\t if (prev === null && next === null) {\n\t receiverMap.delete(receiver);\n\t }\n\t else if (prev === null) {\n\t receiverMap.set(receiver, next);\n\t next.prevSender = null;\n\t }\n\t else if (next === null) {\n\t prev.nextSender = null;\n\t }\n\t else {\n\t prev.nextSender = next;\n\t next.prevSender = prev;\n\t }\n\t conn.prevSender = null;\n\t conn.nextSender = null;\n\t}",
"function unregisterOnlineList(socket) {\r\n var data = \"\";\r\n \r\n for (var i=0; i<onlineList.length; i++) {\r\n for (var j=0; j<onlineList[i].length; j++) {\r\n if (onlineList[i][j].id == socket.id) {\r\n // remove from a match\r\n onlineList[i].splice(j, 1);\r\n for (var k=0; k<onlineList[i].length; k++) {\r\n data = JSON.stringify({\"type\":\"connection\", \"match\":i, \"message\":\"Online budy disconnected...\"});\r\n onlineList[i][k].send(data); \r\n }\r\n \r\n // remove from online list if match empty\r\n if (onlineList[i].length === 0) {\r\n onlineList.splice(i, 1);\r\n }\r\n return;\r\n }\r\n }\r\n } \r\n}",
"function removeHosts(hostsListToRemove) {\n _.each(hostsListToRemove, (host) => {\n hostile.remove(host.ip, host.domain);\n });\n}",
"modellrPruneConnections(connections) {\n connections.forEach((conn) => {\n if (conn && conn.error) {\n this.emit(\n 'warning',\n `A connection to \"${conn.alias}\" could not be established; ${conn.error.message}`\n );\n delete this.modellrSequelizeInstances[conn.alias];\n }\n });\n }",
"function remove(c) {\n delete connections[c.id];\n }",
"removeConnection(conn) {\n\t\tvar data = this._connMap.get(conn);\n\t\tif (!data) {\n\t\t\t// connection wasn't listed (shouldn't happen!)\n\t\t\tlogger.warn('Connection was not listed for wallet %s!', this.wallet);\n\t\t} else {\n\t\t\t// remove connection from list\n\t\t\tthis._connMap.delete(conn);\n\t\t}\n\t\treturn (this._connMap.size == 0);\n\t}",
"removeConnections() {\n for (let i = 0; i < this.inputNodes.length; i++) {\n this.localScope.Input[i]?.output1.disconnectWireLess(\n this.inputNodes[i]\n );\n }\n\n for (let i = 0; i < this.outputNodes.length; i++) {\n this.localScope.Output[i]?.inp1.disconnectWireLess(\n this.outputNodes[i]\n );\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
link a specific node in a certain direction | _linkTo(node, direction) {
if (direction <= 0) {
node.inputEdges.push(this);
}
if (direction >= 0) {
node.outputEdges.push(this);
}
node.edges.push(this);
return true;
} | [
"function makeLinkBetweenNode(node) {\n let temp = {};\n for (let i = 0; i < node.properties.pointsAdj.length; i++) {\n temp[node.properties.pointsAdj[i].name] = node.properties.pointsAdj[i].distance;\n }\n adjNodeArray[node.properties.name] = temp;\n }",
"connectNode (cell, direction) {\n direction = this.limPos(direction);\n\n if (typeof cell === 'undefined' || cell === null) {\n return;\n }\n\n let oppositeDirection = this.opposite(direction);\n\n if (typeof this.connections[direction] === 'undefined') {\n this.connections[direction] = cell;\n }\n\n if (typeof cell.connections[oppositeDirection] === 'undefined') {\n cell.connections[oppositeDirection] = this;\n }\n\n this.leftRightConnect(direction, cell);\n }",
"function setDirection(node1, node2) {\r\n const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]];\r\n for (let i = 0; i < 4; i++) {\r\n const row = node1.row + dir[i][0];\r\n const col = node1.col + dir[i][1];\r\n if (row === node2.row && col === node2.col) {\r\n switch (i) {\r\n case 0:\r\n node1.direction = \"down\";\r\n break;\r\n case 1:\r\n node1.direction = \"up\";\r\n break;\r\n case 2:\r\n node1.direction = \"right\";\r\n break;\r\n case 3:\r\n node1.direction = \"left\";\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n }\r\n}",
"function move_node(source_node, dest_node) {\n\n}",
"function position_links(link) {\n diagonal.projection(function(d) {return [xScale(d.x), d.y]; }) \n link.attr(\"d\", diagonal);\n }",
"function addLinkToForceGraph(node1, node2) {\n\t// First we need to find the index of each node\n\tvar n1 = getNodeIndexByName(node1);\n\tvar n2 = getNodeIndexByName(node2);\n\tforceGraphData.edges.push({source: n1, target: n2});\n\n\tupdateForceGraph();\n}",
"function turnNode(node, direction) {\n\tif (direction) {\n\t\tnode.setAttribute('direction', direction)\n\t\txDir = Math.sin((direction%360) * Math.PI/180)*10;\n\t\tyDir = Math.cos((direction%360) * Math.PI/180)*10;\n\t\tnode.setAttribute('phase',0)\n\t\tnode.setAttribute('xdir',xDir)\n\t\tnode.setAttribute('ydir',yDir)\n\n\t\treturn\n\t} else {\n\t\t// If no direction is given, find a random direction that isn't vastly different to current one\n\t\t// this difference is defined by angleThresh\n\t\twhile (true) {\n\t\t\tlet newDirection = Math.floor((Math.random() * 360) + 1);\n\t\t\t// Right to left\n\t\t\tif (newDirection > 270 && parseInt(node.getAttribute('direction')) < 90) { \n\t\t\t\tif ((Math.abs(newDirection%90) - parseInt(node.getAttribute('direction'))) < angleThresh) {\n\t\t\t\t\tnode.setAttribute('direction', newDirection)\n\t\t\t\t\txDir = Math.sin(newDirection * Math.PI/180)*10;\n\t\t\t\t\tyDir = Math.cos(newDirection * Math.PI/180)*10;\n\t\t\t\t\tnode.setAttribute('phase',0)\n\t\t\t\t\tnode.setAttribute('xdir',xDir)\n\t\t\t\t\tnode.setAttribute('ydir',yDir)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} \n\t\t\tif (Math.abs(newDirection - parseInt(node.getAttribute('direction'))) < angleThresh) {\n\t\t\t\tnode.setAttribute('direction', newDirection)\n\t\t\t\txDir = Math.sin(newDirection * Math.PI/180)*10;\n\t\t\t\tyDir = Math.cos(newDirection * Math.PI/180)*10;\n\t\t\t\tnode.setAttribute('phase',0)\n\t\t\t\tnode.setAttribute('xdir',xDir)\n\t\t\t\tnode.setAttribute('ydir',yDir)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}",
"function half_link(node,port,target,target_port){\n memory[node+1+port] = target_port;\n memory[node+4+port] = target;\n }",
"function SetLinkDirection(valueRegisterer) {\n let link = FindElementInGraph(valueRegisterer.element);\n let targetedValue = (link.source == valueRegisterer.newValue[0]) ? valueRegisterer.oldValue : valueRegisterer.newValue;\n\n link.source = targetedValue[0];\n link.target = targetedValue[1];\n\n force.start();\n}",
"function addLinkBetweenNodes(sourceNode,targetNode,isLeft,isRight){\n var link = findLink(sourceNode,targetNode);\n if (link != null){ //if link exists, set direction, return;\n link.left=isLeft;\n link.right=isRight;\n return link;\n }\n\n if (targetNode.type === xdi.constants.arctypes.LITERAL){\n var innerNode = addNode(sourceNode.fullName + \"&\", \"&\", Math.max(sourceNode.graphId,targetNode.graphId));\n var linkToInnerNode = addLink(sourceNode,innerNode,\"&\",false,true,false);\n var linkToTargetNode = addLink(innerNode,targetNode,\"&\",false,true,false);\n link = linkToInnerNode;\n targetNode.fullName = innerNode.fullName + \"/&/\" + targetNode.shortName;\n }\n else {\n var linkName = targetNode.shortName;\n link = addLink(sourceNode,targetNode,linkName, isLeft, isRight, false);\n targetNode.fullName = sourceNode.fullName + targetNode.shortName;\n }\n checkLinkValidity(link);\n\n return link;\n}",
"function addNodeOnto(x,y,name){\n var index = node_dataOnto.length;\n node_dataOnto.push({x:x,y:y,name:name,index:index});\n refreshGraphOnto(node_dataOnto,link_dataOnto);\n}",
"function changeDestination(edge, dest){\n edge.destination = dest;\n}",
"function moveNode(d) {\n // Create a function that returns the node's position at time t\n var interpolationX = d3.interpolateNumber(d.x, svgWidth/2);\n var interpolationY = d3.interpolateNumber(d.y, d.spine * rainbowNodeSpacing);\n \n // Get the links associated with the node\n var nodeLinks = getUpdateLinks(d.id);\n \n // Animate the node and its associated links\n return function(t) {\n d.y = interpolationY(t);\n d.py = interpolationY(t);\n d.x = interpolationX(t);\n d.px = interpolationX(t);\n nodeLinks.forEach(updateLinkNodes);\n \n return \"translate(\" + d.x + \",\" + d.y + \")\";\n }\n}",
"function lineToNodeLink(line) {\n var tokens = line.split(/->|:/) // split by arrow or colon\n return {\n \"src\": tokens[0],\n \"dst\": tokens[1],\n \"weight\": parseFloat(tokens[2])\n }\n}",
"function align (node) {\n\t\n\tlet nearNodes = getNear(node);\n\tif (nearNodes.length == 0) {\n\t\treturn false;\n\t}\n\tlet total = 0;\n\tfor (let i = 0; i < nearNodes.length; i++) {\n\t\ttotal += parseInt(nearNodes[i].getAttribute('direction'));\n\t}\n\tlet averageDirection = total/nearNodes.length;\n\n\t// TODO : Make the turning average between current direction and new, rather than instant\n\tturnNode(node, (parseInt(averageDirection) + parseInt(node.getAttribute('direction')))/2);\n\n}",
"leftRightConnect (direction, cell) {\n let oppositeDirection = this.opposite(direction);\n //connect existing adjacent cells to new cell\n let leftCell = this.connections[this.limPos(direction - 1)];\n let rightCell = this.connections[this.limPos(direction + 1)];\n\n if (typeof leftCell !== 'undefined' && typeof cell.connections[cell.limPos(oppositeDirection + 1)] === 'undefined') {\n cell.connectNode(leftCell, cell.limPos(oppositeDirection + 1));\n }\n\n if (typeof rightCell !== 'undefined' && typeof cell.connections[cell.limPos(oppositeDirection - 1)] === 'undefined') {\n cell.connectNode(rightCell, cell.limPos(oppositeDirection - 1));\n }\n }",
"attachNode(target, source) {\n switch (this.direction) {\n case Data.Directions.LEFT:\n target.attachLeft(source);\n break;\n case Data.Directions.NEXT:\n target.attachNext(source);\n break;\n case Data.Directions.RIGHT:\n target.attachRight(source);\n break;\n }\n }",
"function linkNodes(node1, node2) {\n\tnode1.next = node2;\n\tnode2.prev = node1; \n}",
"function updateLinkNodes(link) {\n updateLinkPath(link);\n \n // Update references to the node's position\n d3.select(link).attr(\"tx\", function(d) { return d.target.x; })\n .attr(\"ty\", function(d) { return d.target.y; });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UnloadContent will be called once per game and is the place to unload all content. | unloadContent() {
// TODO: Unload any non ContentManager content here
} | [
"unloadContent() {\n // TODO: Unload any non ContentManager content here\n }",
"unloadContent() {\n if (this.content && this.content.destroy) {\n this.content.destroy();\n }\n this.content = null;\n this.contentState = TILE_CONTENT_STATE.UNLOADED;\n return true;\n }",
"unloadContent() {\n if (this.content && this.content.destroy) {\n this.content.destroy();\n }\n this.content = null;\n this.contentState = _constants__WEBPACK_IMPORTED_MODULE_4__[\"TILE_CONTENT_STATE\"].UNLOADED;\n return true;\n }",
"unloadContent() {\n if (!this.tileset._debug[this.id]) {\n this.tileset._debug[this.id] = {\n load: 0,\n featureLoad: 0,\n geometryLoad: 0,\n unload: 0\n };\n }\n if (!this.hasRenderContent) {\n return false;\n }\n if (this._content && this._content.destroy) {\n this._content.destroy();\n }\n this._content = null;\n this._contentState = TILE_CONTENT_STATE.UNLOADED;\n this.tileset._debug[this.id].unload++;\n return true;\n }",
"function clearContent() {\n $('.content').html('');\n }",
"closeContent() {\n\t\tthis.ensureContentTabOpen(undefined);\n\t}",
"function clear_content() {\n $('#content').empty();\n }",
"function deletePageContents() {\n\n content.removeChild(content.lastChild);\n content.removeChild(content.lastChild);\n\n }",
"unload() {\n Management.emit(\"page-unload\", this);\n\n this.extension.views.delete(this);\n\n for (let obj of this.onClose) {\n obj.close();\n }\n }",
"unload(){this.document=void 0,this.contents=void 0,this.output=void 0}",
"function clearContent() {\n\tcontentBlock.innerHTML = '';\n}",
"unload() {\n\t\t\tthis.document = undefined;\n\t\t\tthis.contents = undefined;\n\t\t\tthis.output = undefined;\n\t\t}",
"function destroyWebContent() {\n $(\"#webControls\").remove();\n $(\".fullscreenContent\").remove();\n $(\"#mainContent\").show();\n}",
"async deleteContent () {\n\t\tawait this.deleteMarkers();\n\t\tawait this.deletePosts();\n\t\tawait this.deleteStreams();\n\t}",
"clearContent () {\n let titleEl = document.getElementById( 'pageTitle' ),\n contentEl = document.getElementById( 'pageContent' );\n\n titleEl.innerHTML = '';\n contentEl.innerHTML = '';\n }",
"clearContent() {\n this.document.getElementsByClassName(\"settings-content\").forEach(function (content) {\n content.removeChildren();\n });\n }",
"function clearContent() {\n\tcontent = document.getElementById(\"content\");\n\twhile (content.firstChild) {\n\t\tcontent.removeChild(content.firstChild);\n\t}\n\n\twindow.scrollTo(0, 0);\n}",
"function clearContent() {\n\t\twhile (modalTextContent.hasChildNodes()) {\n\t\t\tmodalTextContent.removeChild(modalTextContent.lastChild);\n\t\t}\n\t}",
"function clearScreen(){\n\t $('body .content').empty();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load the image inside a div with the maximum dimensions received as props so that the image assumes the div size and not its natural dimensions | nonResizedImage() {
return (
<div style={{ width: this.props.maxWidth, height: this.props.maxHeight }}>
<Image src={this.props.src} onLoad={this.handleImageLoaded} />
</div>
);
} | [
"function Image(props) {\r\n return (\r\n <img src={props.path}\r\n alt=\"\"\r\n style={{\r\n maxWidth: \"100%\",\r\n maxHeight: \"100%\",\r\n }} />\r\n );\r\n}",
"render(){\n return(\n <div>\n <img src={this.props.imagen} className={this.props.clases} alt=\"\" height={this.props.height} width={this.props.width}/>\n </div>\n )\n }",
"function ImageLarge({ imageId }) {\n const { data: image, loading } = useSWR(\n `${process.env.REACT_APP_SERVER}/files/${imageId}`\n );\n\n return (\n <Container>\n {loading && <IconLoad />}\n {image && (\n <Image\n src={`data:${image.contentType};base64,${Buffer.from(\n image.data\n ).toString(\"base64\")}`}\n alt={image.name}\n />\n )}\n </Container>\n );\n}",
"addImgContent() { //TODO - static div height; carousel\n const imgArr = this.props.missionInfo.links.flickr_images;\n if(imgArr[0] !== undefined) {\n return <div id='cardImgContrainer' className='col-md-4'>\n <img id='cardImg' className='rounded' alt='Failed to Load Image' src={imgArr[0]}/>\n </div>\n }\n else {\n return null\n }\n }",
"imgLoaded(event) {\n event = event || window.event;\n const element = event.target || event.srcElement;\n // Adjusts image size and position.\n if (element.width === element.height) {\n element.width = element.height = Mavelet.config.thumbCellSize;\n }\n if (element.height > element.width) {\n element.width = element.width * (Mavelet.config.thumbCellSize / element.height);\n element.height = Mavelet.config.thumbCellSize;\n }\n if (element.height < element.width) {\n element.height = element.height * (Mavelet.config.thumbCellSize / element.width);\n element.width = Mavelet.config.thumbCellSize;\n element.style.marginTop = 0 - (element.height - Mavelet.config.thumbCellSize) / 2 +\n 'px';\n }\n // Shows image.\n document.getElementById(Mavelet.config.k + '_thumb_' + Mavelet.attribute(element, 'src'))\n .className += ' visible';\n }",
"function createImgComponent(options) {\n // Initialize the fullsize image\n var img = $('<img />', {\n 'src': options.fullsize,\n }) \n\n // Set css styling\n img.css({\n 'max-height': '100%',\n 'max-width': '100%',\n 'position': 'relative',\n 'top': '50%',\n 'transform': 'translateY(-50%)',\n 'border': options.border,\n 'border-radius': options.radius,\n 'box-shadow': options.shadow,\n });\n \n return img; \n }",
"_setSizeFromImage(image) {\n if (image.complete) {\n this.width = image.naturalWidth;\n this.height = image.naturalHeight;\n } else {\n image.addEventListener(\"load\", () => {\n this.width = image.naturalWidth;\n this.height = image.naturalHeight;\n });\n }\n }",
"render () {\n const { fullImage, isLoading, thumbImage, giphyURL } = this.props;\n\n return (\n <a href={giphyURL} target=\"_blank\" title=\"View on Giphy\" className={styles.modal} tabIndex=\"-1\" ref=\"gifModal\">\n {isLoading\n ? <div>\n <div className={styles.loadingSpinner}></div>\n <img\n alt=\"Full Image\"\n className={styles.imgLoading}\n src={thumbImage.url}\n style={{ width: thumbImage.width, height: thumbImage.height }}\n />\n </div>\n : <img className={styles.img} src={fullImage} alt=\"Full Image\" />\n }\n </a>\n );\n }",
"function large_image(result){\n\tvar parsed = JSON.parse(result);\n\tvar image_url = parsed.collection.items[1].href;\n\tvar image_spot = document.getElementById('side_image');\n\t\n\tdocument.getElementById('loading_photo').style.display = \"none\";\n\t\n\tvar img = new Image(); \n\timg.src = image_url;\n\timg.setAttribute('width',\"100%\");\n\timage_spot.appendChild(img);\n}",
"render() {\n return (\n <img\n alt={\"img-\" + this.num}\n src={this.src}\n style={this.styles}\n onError={this.failedToLoad}\n />\n );\n }",
"render () {\n let imageStyles = this.getLazyImageUrl()\n\n return (\n <div className=\"payment-page__thumb\" style={imageStyles}></div>\n )\n\n }",
"calculateMaxImageDimensions() {\n const { imageLinks } = this.props;\n this.setState({\n widths: Array(imageLinks.length).fill(0),\n maxHeight: 0\n });\n\n // Calculate the widths[] and maxHeight of the images by loading them.\n imageLinks.forEach((imageLink, index) => {\n const img = new Image();\n img.onload = event => {\n const { naturalWidth, naturalHeight } = event.currentTarget;\n if (naturalHeight) {\n // Scale width from natural width to image link width.\n const width = imageLink.height / naturalHeight * naturalWidth;\n this.setState(prevState => ({\n widths: [\n ...prevState.widths.slice(0, index),\n width,\n ...prevState.widths.slice(index + 1)\n ],\n maxHeight: Math.max(imageLink.height, prevState.maxHeight)\n }));\n }\n }\n // Setting src after we have set the onload event will cause the event to be triggered after\n // the image has loaded.\n img.src = imageLink.src;\n });\n }",
"render () {\n let {src, alt, ...props} = this.props;\n src = src?.src || src; // image passed through import will return an object\n return <img {...props} src={addBasePath(src)} alt={alt}/>\n }",
"function ImageLoader(props) {\n const { fullsize, thumb } = props;\n // useState hook tracks loading status of fullsize image\n const [isLoading, setIsLoading] = useState(true);\n\n // onLoad event handler sets isLoading state to false\n const handleOnLoad = () => {\n setIsLoading(false);\n }\n\n return (\n <div className={'image-loader'}>\n <img\n src={fullsize}\n // onLoad event handler is called when image finishes loading\n onLoad={handleOnLoad}\n />\n {/* Condiditonal rendering will remove thumbnail when onLoad event updates state */}\n {isLoading &&\n <img\n src={thumb}\n />\n }\n </div>\n )\n}",
"function ImageComponent() {\n return (\n <div\n style={{\n marginTop: \"10%\",\n marginLeft: \"25%\",\n width: \"50%\",\n height: \"25%\",\n textAlign: \"center\",\n }}\n >\n {/* <img src=\"/images/ph.jpg\" style={{ width: \"100%\", height: \"100%\" }} /> */}\n {/* Width and Height required to give in PIXELS in NUMERIC format; not in STRING type */}\n <Image src=\"/images/ph.jpg\" width={500} height={500} />\n {/** image loads lazily in NextJS */}\n {/* \n -> There are many more properties, we can use on this <Image/> component to optimize this to advanced level\n -> refer the below link for more info -> https://nextjs.org/docs/api-reference/next/image\n */}\n </div>\n );\n}",
"_requestSize() {\n Image.getSize(\n this.props.sourceUri,\n (width, height) => {\n if (!this._isMounted) return;\n if (this.props.style.width && this.props.style.height) {\n width = this.props.style.width;\n height = this.props.style.height;\n } else if (this.props.style.width) {\n height = (this.props.style.width / width) * height;\n width = this.props.style.width;\n } else if (this.props.style.height) {\n width = (this.props.style.height / height) * width;\n height = this.props.style.height;\n }\n this.setState({\n width,\n height\n });\n },\n error => {\n console.warn(error);\n }\n );\n }",
"function ImageComponent(props) {\n return (\n <div\n className=\"imageComponent\"\n onClick={props.openModalProp}\n url={props.url}\n key={props.key}\n >\n <img\n src={props.thumbnailUrl}\n title={props.title}\n id={props.id}\n className=\"thumbnail\"\n alt={\"box number\" + props.id}\n />\n <Modal\n key={props.key}\n id={props.id}\n showModal={props.showModal}\n setShowModal={props.setShowModal}\n url={props.url}\n title={props.title}\n ></Modal>\n </div>\n );\n}",
"function CardMedia(props) {\n return (\n <figure className=\"main-card-image\">\n <img alt={props.src} src={props.src}/>\n {props.children}\n </figure>\n )\n}",
"function innerLoadHandler(event) {\n var imgElem = document.createElement('IMG');\n imgElem.setAttribute('alt', ImageParam.alt);\n imgElem.setAttribute('src', event.target.result);\n imgElem.setAttribute('title', file.name);\n imgElem.style.display = ImageParam.display;\n imgElem.style.height = ImageParam.height;\n imgElem.style.margin = ImageParam.margin;\n photoContainer.appendChild(imgElem);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a wrapped node from a compiler node. | function createWrappedNode(node, opts = {}) {
const { compilerOptions = {}, sourceFile, typeChecker } = opts;
const projectContext = new ProjectContext_1.ProjectContext(undefined, new fileSystem_1.FileSystemWrapper(new fileSystem_1.DefaultFileSystemHost()), compilerOptions, { createLanguageService: false, typeChecker });
const wrappedSourceFile = projectContext.compilerFactory.getSourceFile(getSourceFileNode(), { markInProject: true });
return projectContext.compilerFactory.getNodeFromCompilerNode(node, wrappedSourceFile);
function getSourceFileNode() {
return sourceFile == null ? getSourceFileFromNode(node) : sourceFile;
}
function getSourceFileFromNode(compilerNode) {
if (compilerNode.kind === typescript_1.SyntaxKind.SourceFile)
return compilerNode;
if (compilerNode.parent == null)
throw new errors.InvalidOperationError("Please ensure the node was created from a source file with 'setParentNodes' set to 'true'.");
let parent = compilerNode;
while (parent.parent != null)
parent = parent.parent;
if (parent.kind !== typescript_1.SyntaxKind.SourceFile)
throw new errors.NotImplementedError("For some reason the top parent was not a source file.");
return parent;
}
} | [
"function createWrappedNode(node, opts) {\n if (opts === void 0) { opts = {}; }\n var _a = opts.compilerOptions, compilerOptions = _a === void 0 ? {} : _a, sourceFile = opts.sourceFile, typeChecker = opts.typeChecker;\n var projectContext = new ProjectContext_1.ProjectContext(new fileSystem_1.FileSystemWrapper(new fileSystem_1.DefaultFileSystemHost()), compilerOptions, { createLanguageService: false, typeChecker: typeChecker });\n var wrappedSourceFile = projectContext.compilerFactory.getSourceFile(getSourceFileNode());\n return projectContext.compilerFactory.getNodeFromCompilerNode(node, wrappedSourceFile);\n function getSourceFileNode() {\n return sourceFile == null ? getSourceFileFromNode(node) : sourceFile;\n }\n function getSourceFileFromNode(compilerNode) {\n if (compilerNode.kind === typescript_1.SyntaxKind.SourceFile)\n return compilerNode;\n if (compilerNode.parent == null)\n throw new errors.InvalidOperationError(\"Please ensure the node was created from a source file with 'setParentNodes' set to 'true'.\");\n var parent = compilerNode;\n while (parent.parent != null)\n parent = parent.parent;\n if (parent.kind !== typescript_1.SyntaxKind.SourceFile)\n throw new errors.NotImplementedError(\"For some reason the top parent was not a source file.\");\n return parent;\n }\n}",
"function wrapNode(node) {\n if (bot.userAgent.isProductVersion(4)) {\n return node ? new XPCNativeWrapper(node) : null;\n }\n return node;\n }",
"getNodeFromCompilerNode(compilerNode, sourceFile) {\r\n if (compilerNode.kind === typescript_1.SyntaxKind.SourceFile)\r\n return this.getSourceFile(compilerNode, { markInProject: false });\r\n return this.nodeCache.getOrCreate(compilerNode, () => {\r\n const node = createNode.call(this);\r\n initializeNode.call(this, node);\r\n return node;\r\n });\r\n function createNode() {\r\n // todo: improve kind to wrapper mappings to handle this scenario\r\n if (isCommentNode(compilerNode)) {\r\n if (utils_1.CommentNodeParser.isCommentStatement(compilerNode))\r\n return new compiler_1.CommentStatement(this.context, compilerNode, sourceFile);\r\n if (utils_1.CommentNodeParser.isCommentClassElement(compilerNode))\r\n return new compiler_1.CommentClassElement(this.context, compilerNode, sourceFile);\r\n if (utils_1.CommentNodeParser.isCommentTypeElement(compilerNode))\r\n return new compiler_1.CommentTypeElement(this.context, compilerNode, sourceFile);\r\n if (utils_1.CommentNodeParser.isCommentObjectLiteralElement(compilerNode))\r\n return new compiler_1.CommentObjectLiteralElement(this.context, compilerNode, sourceFile);\r\n if (utils_1.CommentNodeParser.isCommentEnumMember(compilerNode))\r\n return new compiler_1.CommentEnumMember(this.context, compilerNode, sourceFile);\r\n return errors.throwNotImplementedForNeverValueError(compilerNode);\r\n }\r\n const ctor = kindToWrapperMappings_1.kindToWrapperMappings[compilerNode.kind] || compiler_1.Node;\r\n return new ctor(this.context, compilerNode, sourceFile);\r\n }\r\n function isCommentNode(node) {\r\n return node._commentKind != null;\r\n }\r\n function initializeNode(node) {\r\n // ensure the parent is created and increment its wrapped child count\r\n if (compilerNode.parent != null) {\r\n const parentNode = this.getNodeFromCompilerNode(compilerNode.parent, sourceFile);\r\n parentNode._wrappedChildCount++;\r\n }\r\n const parentSyntaxList = node._getParentSyntaxListIfWrapped();\r\n if (parentSyntaxList != null)\r\n parentSyntaxList._wrappedChildCount++;\r\n if (compilerNode.kind === typescript_1.SyntaxKind.SyntaxList) {\r\n let count = 0;\r\n for (const _ of node._getChildrenInCacheIterator())\r\n count++;\r\n node._wrappedChildCount = count;\r\n }\r\n }\r\n }",
"function NodeWrapper() {\n\t this._node = this.constructor.createNode();\n\t }",
"makeNodeWrapper(node, _stack = []) {\n const wrapper = this._nodeWrappers.get(node);\n if (wrapper !== undefined) {\n return wrapper;\n }\n // Turn string nodes into WatchedDir nodes\n const originalNode = node; // keep original (possibly string) node around so we can later deduplicate\n if (typeof node === 'string') {\n node = new broccoli_source_1.WatchedDir(node, { annotation: 'string node' });\n }\n // Call node.__broccoliGetInfo__()\n let nodeInfo;\n try {\n nodeInfo = broccoli_node_info_1.default.getNodeInfo(node);\n }\n catch (e) {\n if (!(e instanceof broccoli_node_info_1.default.InvalidNodeError))\n throw e;\n // We don't have the instantiation stack of an invalid node, so to aid\n // debugging, we instead report its parent node\n const messageSuffix = _stack.length > 0\n ? '\\nused as input node to ' +\n _stack[_stack.length - 1].label +\n _stack[_stack.length - 1].formatInstantiationStackForTerminal()\n : '\\nused as output node';\n throw new broccoli_node_info_1.default.InvalidNodeError(e.message + messageSuffix);\n }\n // Compute label, like \"Funnel (test suite)\"\n let label = nodeInfo.name;\n const labelExtras = [];\n if (nodeInfo.nodeType === 'source')\n labelExtras.push(nodeInfo.sourceDirectory);\n if (nodeInfo.annotation != null)\n labelExtras.push(nodeInfo.annotation);\n if (labelExtras.length > 0)\n label += ' (' + labelExtras.join('; ') + ')';\n // We start constructing the nodeWrapper here because we'll need the partial\n // nodeWrapper for the _stack. Later we'll add more properties.\n const nodeWrapper = nodeInfo.nodeType === 'transform' ? new transform_node_1.default() : new source_node_1.default();\n nodeWrapper.nodeInfo = nodeInfo;\n nodeWrapper.originalNode = originalNode;\n nodeWrapper.node = node;\n nodeWrapper.label = label;\n // Detect cycles\n for (let i = 0; i < _stack.length; i++) {\n if (_stack[i].node === originalNode) {\n let cycleMessage = 'Cycle in node graph: ';\n for (let j = i; j < _stack.length; j++) {\n cycleMessage += _stack[j].label + ' -> ';\n }\n cycleMessage += nodeWrapper.label;\n throw new builder_1.default(cycleMessage);\n }\n }\n // For 'transform' nodes, recursively enter into the input nodes; for\n // 'source' nodes, record paths.\n let inputNodeWrappers = [];\n if (nodeInfo.nodeType === 'transform') {\n const newStack = _stack.concat([nodeWrapper]);\n inputNodeWrappers = nodeInfo.inputNodes.map((inputNode) => {\n return this.makeNodeWrapper(inputNode, newStack);\n });\n }\n else {\n // nodeType === 'source'\n if (nodeInfo.watched) {\n this.watchedPaths.push(nodeInfo.sourceDirectory);\n }\n else {\n this.unwatchedPaths.push(nodeInfo.sourceDirectory);\n }\n }\n // For convenience, all nodeWrappers get an `inputNodeWrappers` array; for\n // 'source' nodes it's empty.\n nodeWrapper.inputNodeWrappers = inputNodeWrappers;\n nodeWrapper.id = this._nodeWrappers.size;\n // this._nodeWrappers will contain all the node wrappers in topological\n // order, i.e. each node comes after all its input nodes.\n //\n // It's unfortunate that we're mutating this._nodeWrappers as a side effect,\n // but since we work backwards from the output node to discover all the\n // input nodes, it's harder to do a side-effect-free topological sort.\n this._nodeWrappers.set(nodeWrapper.originalNode, nodeWrapper);\n return nodeWrapper;\n }",
"_compile(node) {\n\t\tswitch (node.type) {\n\t\t\tcase 'block':\n\t\t\t\treturn this.compileBlock(node, this.compile);\n\t\t\tcase 'const':\n\t\t\t\tthis.constants.set(node.name, this.compileValue(node.value));\n\t\t\t\treturn nodeVoid;\n\t\t\tcase 'declare':\n\t\t\t\tthis.compileDeclare(node);\n\t\t\t\treturn nodeVoid;\n\t\t\tcase 'rule':\n\t\t\t\treturn this.compileRule(node);\n\t\t\tcase 'usevar':\n\t\t\t\tif (node.scope === 'global') this.env.setUsing(node.var);\n\t\t\t\telse if (node.scope === 'player') this.playerVars.setUsing(node.var);\n\t\t\t\telse throw new Error(`Invalid scope '${node.scope}' for usevar`);\n\t\t\t\treturn nodeVoid;\n\t\t}\n\t}",
"function make_node(value_or_fn) {\n return new Node(value_or_fn).as_function()\n }",
"function nodeWrap(agent) {\n if (agent instanceof node_1.Node)\n return agent;\n return new NodeWrap(agent);\n}",
"static node(from2, to, attrs, spec) {\n return new Decoration(from2, to, new NodeType2(attrs, spec));\n }",
"WrapNode(node, node_type) {\n\n var wrapperNode = document.createElement(node_type);\n\n while(node.childNodes.length) {\n wrapperNode.appendChild(node.childNodes[0]);\n }\n\n node.appendChild(wrapperNode);\n return wrapperNode;\n }",
"cnode(elem) {\n let impNode;\n const xmlGen = Strophe.xmlGenerator();\n\n try {\n impNode = xmlGen.importNode !== undefined;\n } catch (e) {\n impNode = false;\n }\n\n const newElem = impNode ? xmlGen.importNode(elem, true) : Strophe.copyElement(elem);\n this.node.appendChild(newElem);\n this.node = newElem;\n return this;\n }",
"compile(sourceCtx) {\n\n return new CFNode(JS.assign(this.expr.compile(sourceCtx), JS.ID('undefined')));\n }",
"function TSNode()\n{\n\t\n}",
"function createNodeInjector() {\n return new NodeInjector(getCurrentTNode(), getLView());\n}",
"function Node() {}",
"function wrapNode(node, nodePath) {\n\t for (var ii = nodePath.length - 1; ii >= 0; ii--) {\n\t var parent = nodePath[ii];\n\t if (parent instanceof __webpack_require__(147).Field && parent.getInferredRootCallName()) {\n\t // We can make a \"ref query\" at this point, so stop wrapping.\n\t return new (__webpack_require__(270))(node, nodePath.slice(0, ii + 1));\n\t }\n\n\t var siblings = getRequisiteSiblings(node, parent);\n\t var children = [node].concat(siblings);\n\n\t // Cast here because we know that `clone` will never return `null` (because\n\t // we always give it at least one child).\n\t node = parent.clone(children);\n\t }\n\t __webpack_require__(9)(node instanceof __webpack_require__(147).Root, 'splitDeferredRelayQueries(): Cannot build query without a root node.');\n\t var identifyingArg = node.getIdentifyingArg();\n\t var identifyingArgName = identifyingArg && identifyingArg.name || null;\n\t var identifyingArgValue = identifyingArg && identifyingArg.value || null;\n\t var metadata = {\n\t identifyingArgName: identifyingArgName,\n\t identifyingArgType: __webpack_require__(141).ID_TYPE,\n\t isAbstract: true,\n\t isDeferred: true,\n\t isPlural: false\n\t };\n\t return __webpack_require__(147).Root.build(node.getName(), node.getFieldName(), identifyingArgValue, node.getChildren(), metadata, node.getType());\n\t}",
"function stringify(node, doc) {\n var file = vfile(doc)\n var Compiler\n\n freeze()\n Compiler = processor.Compiler\n assertCompiler('stringify', Compiler)\n assertNode(node)\n\n if (newable(Compiler, 'compile')) {\n return new Compiler(node, file).compile()\n }\n\n return Compiler(node, file) // eslint-disable-line new-cap\n }",
"compileNode(o) {\n var answer, compiledName, isValue, name, properties, prototype, ref1, ref2, ref3, ref4, ref5, val, varBase;\n isValue = this.variable instanceof Value;\n if (isValue) {\n // When compiling `@variable`, remember if it is part of a function parameter.\n this.variable.param = this.param;\n // If `@variable` is an array or an object, we’re destructuring;\n // if it’s also `isAssignable()`, the destructuring syntax is supported\n // in ES and we can output it as is; otherwise we `@compileDestructuring`\n // and convert this ES-unsupported destructuring into acceptable output.\n if (this.variable.isArray() || this.variable.isObject()) {\n // This is the left-hand side of an assignment; let `Arr` and `Obj`\n // know that, so that those nodes know that they’re assignable as\n // destructured variables.\n this.variable.base.lhs = true;\n if (!this.variable.isAssignable()) {\n if (this.variable.isObject() && this.variable.base.hasSplat()) {\n return this.compileObjectDestruct(o);\n } else {\n return this.compileDestructuring(o);\n }\n }\n }\n if (this.variable.isSplice()) {\n return this.compileSplice(o);\n }\n if ((ref1 = this.context) === '||=' || ref1 === '&&=' || ref1 === '?=') {\n return this.compileConditional(o);\n }\n if ((ref2 = this.context) === '//=' || ref2 === '%%=') {\n return this.compileSpecialMath(o);\n }\n }\n if (!this.context || this.context === '**=') {\n varBase = this.variable.unwrapAll();\n if (!varBase.isAssignable()) {\n this.variable.error(`'${this.variable.compile(o)}' can't be assigned`);\n }\n varBase.eachName((name) => {\n var commentFragments, commentsNode, message;\n if (typeof name.hasProperties === \"function\" ? name.hasProperties() : void 0) {\n return;\n }\n message = isUnassignable(name.value);\n if (message) {\n name.error(message);\n }\n // `moduleDeclaration` can be `'import'` or `'export'`.\n this.checkAssignability(o, name);\n if (this.moduleDeclaration) {\n return o.scope.add(name.value, this.moduleDeclaration);\n } else if (this.param) {\n return o.scope.add(name.value, this.param === 'alwaysDeclare' ? 'var' : 'param');\n } else {\n o.scope.find(name.value);\n // If this assignment identifier has one or more herecomments\n // attached, output them as part of the declarations line (unless\n // other herecomments are already staged there) for compatibility\n // with Flow typing. Don’t do this if this assignment is for a\n // class, e.g. `ClassName = class ClassName {`, as Flow requires\n // the comment to be between the class name and the `{`.\n if (name.comments && !o.scope.comments[name.value] && !(this.value instanceof Class) && name.comments.every(function(comment) {\n return comment.here && !comment.multiline;\n })) {\n commentsNode = new IdentifierLiteral(name.value);\n commentsNode.comments = name.comments;\n commentFragments = [];\n this.compileCommentFragments(o, commentsNode, commentFragments);\n return o.scope.comments[name.value] = commentFragments;\n }\n }\n });\n }\n if (this.value instanceof Code) {\n if (this.value.isStatic) {\n this.value.name = this.variable.properties[0];\n } else if (((ref3 = this.variable.properties) != null ? ref3.length : void 0) >= 2) {\n ref4 = this.variable.properties, [...properties] = ref4, [prototype, name] = splice.call(properties, -2);\n if (((ref5 = prototype.name) != null ? ref5.value : void 0) === 'prototype') {\n this.value.name = name;\n }\n }\n }\n if (this.csx) {\n this.value.base.csxAttribute = true;\n }\n val = this.value.compileToFragments(o, LEVEL_LIST);\n compiledName = this.variable.compileToFragments(o, LEVEL_LIST);\n if (this.context === 'object') {\n if (this.variable.shouldCache()) {\n compiledName.unshift(this.makeCode('['));\n compiledName.push(this.makeCode(']'));\n }\n return compiledName.concat(this.makeCode(this.csx ? '=' : ': '), val);\n }\n answer = compiledName.concat(this.makeCode(` ${this.context || '='} `), val);\n // Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assignment_without_declaration,\n // if we’re destructuring without declaring, the destructuring assignment must be wrapped in parentheses.\n // The assignment is wrapped in parentheses if 'o.level' has lower precedence than LEVEL_LIST (3)\n // (i.e. LEVEL_COND (4), LEVEL_OP (5) or LEVEL_ACCESS (6)), or if we're destructuring object, e.g. {a,b} = obj.\n if (o.level > LEVEL_LIST || isValue && this.variable.base instanceof Obj && !this.nestedLhs && !(this.param === true)) {\n return this.wrapInParentheses(answer);\n } else {\n return answer;\n }\n }",
"function createNode(...args) {\n return new Node(...args)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return initial (first) date to be displayed in the schedule | getInitialDate() {
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() - currentDate.getDay());
return currentDate;
} | [
"getEarliestDate() {\r\n // counting that dates were sorted in initialization\r\n var date = this.events[0].start_date;\r\n if (this.eras && this.eras.length > 0) {\r\n if (this.eras[0].start_date.isBefore(date)) {\r\n return this.eras[0].start_date;\r\n }\r\n }\r\n return date;\r\n\r\n }",
"getInitialDate() {\n if (this.batchInformation) {\n console.log(\"This is BATCH: \" + JSON.stringify(this.batchInformation, null, 2))\n let { population } = this.batchInformation;\n let { length } = population;\n let initialDate = population[(length - 1)].date;\n let date;\n if(isNaN(initialDate))\n date = new Date(population[(length - 1)].date);\n else\n date = new Date(Number(initialDate));\n\n return date.toDateString();\n } else {\n return \"\";\n }\n }",
"defineInitialDate() {\n let date = new Date();\n\n let todayYear = date.getFullYear();\n let todayMonth =\n date.getMonth() + 1 < 10\n ? `0${date.getMonth() + 1}`\n : date.getMonth() + 1;\n let todayDay = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();\n\n let initialDate = `${todayYear}-${todayMonth}-${todayDay}`;\n\n return initialDate;\n }",
"curMonthFirstDate() {\n return new Date(this.year, this.month - 1, 1)\n }",
"get defaultStartDate() {\n // get start date of effectiveFilter (this is fetched from activity store)\n // if it is null, return previous last timezone value that before one minute\n return this.effectiveFilter.startDate || currentPatientTime(this.patientTimeZone).minus({days: 1}).toJSDate()\n\n currentPatientTime(this.patientTimeZone(DateTime.local())).toJSDate()\n\n }",
"get firstRunDate() {\n return CommonUtils.getDatePref(this._prefs, \"firstRunTime\", 0, this._log,\n OLDEST_ALLOWED_YEAR);\n }",
"function getFirstDay() {\n // NOTE, whole pipeline should have a fixed 'today' date. Getting a time here\n // is furnelable although we get it always at noon.\n var min = null;\n var dates = getRelevantDates();\n for (var periodId in dates) {\n var first = dates[periodId].first_date;\n if (min === null || first < min) {\n min = first;\n }\n }\n return min;\n}",
"function getFirstDay() {\n var first = new Date();\n first.setMonth(month);\n first.setYear(year);\n first.setDate(1);\n return first.getDay();\n}",
"getFirstSprint(){\n return {\n sprintNumber : 136,\n sprintStartDate : new Date(\"August 9, 2017\")\n }\n }",
"function setInitialDate() {\n \n // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN \".\" IS USED AS A DELIMITER)\n // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)\n calDate = new Date(inDate);\n\n // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE\n if (isNaN(calDate)) {\n\n // ADD CUSTOM DATE PARSING HERE\n // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE\n calDate = new Date();\n }\n\n // KEEP TRACK OF THE CURRENT DAY VALUE\n calDay = calDate.getDate();\n\n // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES\n // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH\n // AND THE DAY WOULD CHANGE TO 2. SETTING THE DAY TO 1 WILL PREVENT THAT)\n calDate.setDate(1);\n}",
"get_oldest_starting_date() {\n return this.tasks\n .map(task => task._start)\n .reduce(\n (prev_date, cur_date) =>\n cur_date <= prev_date ? cur_date : prev_date\n );\n }",
"function getSprintStartDay() {\n return getValue(\"sprintStartDay\");\n}",
"get startDate() {\n var tmp;\n if (this.fiscalMonth === 0) {\n // TODO test this case\n tmp = new Date(this.fiscalYear, this.fiscalMonth);\n } else {\n tmp = new Date(this.fiscalYear - 1, this.fiscalMonth);\n }\n\n return tmp;\n }",
"function calStart() {\n newDate = new Date();\n return newDate.getFullYear() + \"-01-01\"\n}",
"get_oldest_starting_date() {\n return this.tasks\n .map(task => task._start)\n .reduce(\n (prev_date, cur_date) =>\n cur_date <= prev_date ? cur_date : prev_date\n );\n }",
"function minDate() {\n return new Date(0);\n }",
"function getStartDate() {\n return (new Date(theme.availability.start)).getDate();\n }",
"beginningOfThisMonth() {}",
"static getCurrentWeekStartDate() {\n try {\n let currentDate = new Date();\n let firstDayOfWeek = currentDate.getDate() - currentDate.getDay();\n currentDate.setDate(firstDayOfWeek-7);//added -7 to fetch the test data remove it later\n return libSup.formatDate(currentDate);\n } catch (error) {\n alert(\"getCurrentWeekStartDate-\" + error)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
enterNamespaceName() adds a namespaceName onto the namespace stack at the current index, 'entering' into that namespace (it is now the current namespace). The namespace object returned from this method also has a pointer to its parent | function enterNamespaceName(namespaceName) {
namespaceStack.unshift( namespaceName );
return fw.namespace( fw.utils.currentNamespaceName() );
} | [
"function enterNamespace(namespace) {\n namespaceStack.unshift( namespace.getName() );\n return namespace;\n}",
"function parse_namespace(state, parent)\n{\n\t// handle \"namespace\" keyword\n\tlet where = state.get();\n\tlet token = module.get_token(state);\n\tmodule.assert(token.type == \"keyword\" && token.value == \"namespace\", \"[parse_namespace] internal error\");\n\n\t// check the parent\n\tif (parent.petype != \"global scope\" && parent.petype != \"namespace\") state.error(\"/syntax/se-63\");\n\n\t// display name prefix\n\tlet prefix = \"\";\n\t{\n\t\tlet p = parent;\n\t\twhile (p.petype == \"namespace\")\n\t\t{\n\t\t\tprefix = p.name + \".\" + prefix;\n\t\t\tp = p.parent;\n\t\t}\n\t}\n\n\t// obtain namespace name\n\ttoken = module.get_token(state);\n\tif (token.type != \"identifier\") state.error(\"/syntax/se-64\");\n\tlet nname = token.value;\n\n\t// check namespace name\n\tif (module.options.checkstyle && ! state.builtin() && nname[0] >= 'A' && nname[0] <= 'Z')\n\t{\n\t\tstate.error(\"/style/ste-3\", [\"namespace\", nname]);\n\t}\n\n\t// obtain the named object corresponding to the namespace globally across instances\n\tlet global_nspace = null;\n\tif (parent.names.hasOwnProperty(nname))\n\t{\n\t\t// extend the existing namespace\n\t\tglobal_nspace = parent.names[nname];\n\t\tif (global_nspace.petype != \"namespace\") state.error(\"/name/ne-19\", [nname]);\n\t}\n\telse\n\t{\n\t\t// create the namespace\n\t\tglobal_nspace = { \"petype\": \"namespace\", \"parent\": parent, \"name\": nname, \"displayname\": prefix + nname, \"names\": {}, \"declaration\": true };\n\t\tparent.names[nname] = global_nspace;\n\t}\n\n\t// create the local namespace PE instance containing the commands\n\tlet local_nspace = { \"petype\": \"namespace\", \"where\": where, \"parent\": parent, \"names\": global_nspace.names, \"commands\": [], \"name\": nname, \"displayname\": prefix + nname, \"step\": scopestep, \"sim\": simfalse };\n\n\t// parse the namespace body\n\ttoken = module.get_token(state);\n\tif (token.type != \"grouping\" || token.value != '{') state.error(\"/syntax/se-40\", [\"namespace declaration\"]);\n\tstate.indent.push(-1 - token.line);\n\twhile (true)\n\t{\n\t\t// check for end-of-body\n\t\ttoken = module.get_token(state, true);\n\t\tif (token.type == \"grouping\" && token.value == '}')\n\t\t{\n\t\t\tstate.indent.pop();\n\t\t\tif (module.options.checkstyle && ! state.builtin())\n\t\t\t{\n\t\t\t\tlet indent = state.indentation();\n\t\t\t\tlet topmost = state.indent[state.indent.length - 1];\n\t\t\t\tif (topmost >= 0 && topmost != indent) state.error(\"/style/ste-2\");\n\t\t\t}\n\t\t\tmodule.get_token(state);\n\t\t\tbreak;\n\t\t}\n\n\t\t// parse sub-declarations\n\t\tlet sub = parse_statement_or_declaration(state, local_nspace);\n\t\tif (sub.hasOwnProperty(\"name\")) sub.displayname = prefix + nname + \".\" + sub.name;\n\t\tlocal_nspace.commands.push(sub);\n\t}\n\n\treturn local_nspace;\n}",
"function namespace(namespaceString) {\r\n var parts = namespaceString.split('.'),\r\n parent = window,\r\n currentPart = '';\r\n var k=0;\r\n\tif(parts[0] === 'TAG') {\r\n\tTAG = TAG || {};\r\n\tparent = TAG;\r\n\tk = 1;\r\n\t} else if (parts[0] === 'Worktop') {\r\n\tWorktop = Worktop || {};\r\n\tparent = Worktop;\r\n\tk = 1;\r\n\t}\r\n \r\n\tfor (var i = k, length = parts.length; i < length; i++) {\r\n currentPart = parts[i];\r\n parent[currentPart] = parent[currentPart] || {};\r\n parent = parent[currentPart];\r\n }\r\n\r\n return parent;\r\n }",
"function exitNamespace() {\n namespaceStack.shift();\n return fw.utils.currentNamespace();\n}",
"function XNamespace(name, parent) {\r\n this._name = name;\r\n this._parent = parent;\r\n}",
"enterOracle_namespace(ctx) {\n\t}",
"visitNamespaceName(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"enterNew_tablespace_name(ctx) {\n\t}",
"function nameSpace(name) {\n var nsName = name;\n\n if (currentNameSpace) {\n //nsName = camelCase(currentModule) + '.' + name;\n nsName = currentNameSpace + '_' + name;\n }\n\n return nsName;\n }",
"function createNamespaceEntry(namespace, value, options) {\n //split the namespace and get ready to loop\n var nameAr = namespace.split(\".\")\n , name = nameAr.pop() //remove the name from the namespace\n , scope = root\n , entry = {\n \"namespace\": namespace\n , \"name\": name\n , \"value\": value\n , \"type\": Array.isArray(value)\n ? \"array\"\n : typeof value\n , \"options\": options\n };\n\n //loop through the parts of the namespace, creating any iContainerEntrys\n nameAr.forEach(function forEachName(name, indx) {\n //ensure the scope entry has a children property\n if (!scope.children) {\n scope.children = {};\n }\n //if the scope is missing the name then add it\n if (!scope.children.hasOwnProperty(name)) {\n scope.children[name] = {\n \"namespace\": nameAr\n .slice(0, indx + 1)\n .join(\".\")\n , \"name\": name\n , \"parent\": scope\n , \"children\": {}\n };\n }\n //move down the tree\n scope = scope.children[name];\n });\n\n //update the entry with the parent object\n entry.parent = scope;\n\n //add the entry to the parent\n scope.children[name] = entry;\n\n return entry;\n }",
"enterNew_index_name(ctx) {\n\t}",
"function JSXNamespacedName(node, print) {\n\t print.plain(node.namespace);\n\t this.push(\":\");\n\t print.plain(node.name);\n\t}",
"async putNamespace(request) {\n return doFetch(request,\"NamespaceService\",\"PutNamespace\")\n\t}",
"function JSXNamespacedName(node, print) {\n print.plain(node.namespace);\n this.push(\":\");\n print.plain(node.name);\n}",
"enterPackage_name(ctx) {\n\t}",
"get namespaceName() {\n var _a;\n return (_a = this.findAncestor(reflection_1.isNamespaceStatement)) === null || _a === void 0 ? void 0 : _a.nameExpression;\n }",
"function startNode(node,name){var navNode=emptyNavigationBarNode(node,name);pushChild(parent,navNode);// Save the old parent\nparentsStack.push(parent);trackedEs5ClassesStack.push(trackedEs5Classes);parent=navNode;}",
"addNamespace(name, value) {\n Strophe.NS[name] = value;\n }",
"enterTablespace_group_name(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a desired bearing to a basic X image coordinate for a specific node bearing. Works only for a full 360 panorama. | function bearingToBasic(desiredBearing, nodeBearing) {
// 1. Take difference of desired bearing and node bearing in degrees.
// 2. Scale to basic coordinates.
// 3. Add 0.5 because node bearing corresponds to the center
// of the image. See
// https://mapillary.github.io/mapillary-js/classes/viewer.html
// for explanation of the basic coordinate system of an image.
var basic = (desiredBearing - nodeBearing) / 360 + 0.5;
// Wrap to a valid basic coordinate (on the [0, 1] interval).
// Needed when difference between desired bearing and node
// bearing is more than 180 degrees.
return wrap(basic, 0, 1);
} | [
"findAngle(bBox) {\n const ANGLE_CALIBRATION_MULTIPLIER = 0.75;\n \n // Find horizontal center of the object\n let centerX = parseFloat(bBox.x) + (parseFloat(bBox.w) / 2);\n // console.log(\"findAngle(): centerX=\" + centerX);\n \n // Find offset of the center of the object relative to the middle of the image\n // Negative offset means to the left, positive to the right\n \n // ------- This is if using pixels\n // Calculate angle of the object center relative to the image center\n // let offsetPixels = centerX - Settings.camera.HORIZONTAL_RESOLUTION_PIXELS / 2;\n // let angle = (Settings.camera.H_FIELD_OF_VIEW / 2) *\n // (offsetPixels / (Settings.camera.HORIZONTAL_RESOLUTION_PIXELS / 2));\n \n // -------- This is using relative coordinates\n // console.log(\"findAngle(): Settings.camera.H_FIELD_OF_VIEW=\" + parseFloat(Settings.camera.H_FIELD_OF_VIEW));\n let angle = (centerX - 0.5) * parseFloat(Settings.camera.H_FIELD_OF_VIEW) * ANGLE_CALIBRATION_MULTIPLIER;\n \n console.log(\"findAngle(): \" + angle.toFixed(0));\n return Math.round(angle);\n }",
"function xPan (entityX, pannerNode) {\n\n var width = canvas.width;\n var middle = floor(canvas.width / 2);\n var max = 22;\n var angle;\n\n if (entityX === middle) {\n angle = 0;\n }\n else if (entityX < middle) {\n angle = (middle - entityX) / middle * -max;\n }\n else if (entityX > middle) {\n angle = (entityX - middle) / middle * max;\n }\n\n var xDeg = angle;\n var zDeg = xDeg + 90;\n if (zDeg > 90) {\n zDeg = 180 - zDeg;\n }\n var x = Math.sin(xDeg * (Math.PI / 180));\n var z = Math.sin(zDeg * (Math.PI / 180));\n pannerNode.setPosition(x, 0, z);\n }",
"function _getMarkerWithBearing(vehicleType, bearing) {\r\n let vehicle = vehicleType.replace(\r\n '{svg-transform}',\r\n 'rotate(' + (bearing == null ? 0 : bearing) + ')'\r\n );\r\n return vehicle;\r\n }",
"function getHipBaseX() {\n var theta = body.torso.GetAngle();\n var x = body.torso.GetPosition().x;\n return x - 35*Math.sin(theta);\n}",
"bearing(p) {\n const ref = Point.create(p);\n const lat1 = Angle.toRad(this.y);\n const lat2 = Angle.toRad(ref.y);\n const lon1 = this.x;\n const lon2 = ref.x;\n const dLon = Angle.toRad(lon2 - lon1);\n const y = Math.sin(dLon) * Math.cos(lat2);\n const x = Math.cos(lat1) * Math.sin(lat2) -\n Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);\n const brng = Angle.toDeg(Math.atan2(y, x));\n const bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];\n let index = brng - 22.5;\n if (index < 0) {\n index += 360;\n }\n index = parseInt((index / 45), 10);\n return bearings[index];\n }",
"function getDirection(bearing){\n var direction = \"?\";\n if(bearing<=10 || bearing>=360){direction = \"N\"}\n else if(bearing>10 && bearing<30){direction = \"NNW\"}\n else if(bearing>=30 && bearing<=60){direction = \"NW\"}\n else if(bearing>60 && bearing<80){direction = \"NWW\"}\n else if(bearing>=80 && bearing<=100){direction = \"W\"}\n else if(bearing>100 && bearing<120){direction = \"SWW\"}\n else if(bearing>=120 && bearing<=150){direction = \"SW\"}\n else if(bearing>150 && bearing<170){direction = \"SSW\"}\n else if(bearing>=170 && bearing<=190){direction = \"S\"}\n else if(bearing>190 && bearing<210){direction = \"SSE\"}\n else if(bearing>=210 && bearing<=240){direction = \"SE\"}\n else if(bearing>240 && bearing<260){direction = \"SEE\"}\n else if(bearing>=260 && bearing<=280){direction = \"E\"}\n else if(bearing>280 && bearing<300){direction = \"NEE\"}\n else if(bearing>=300 && bearing<=330){direction = \"NE\"}\n else if(bearing>330 && bearing<350){direction = \"NNE\"}\n return direction;\n}",
"function calculateXandYNode(node) {\n var link = findLinkForMono(node.node); // Find the link which has the node as target\n if (typeof link != 'undefined') { // If the link exists\n var donorPosition = link.donorPosition.value; // Get linked carbon value\n var sourceX;\n var sourceY;\n var sourceId;\n\n // Calculate new coordinates for the wanted node\n for (var n of glycan.graph.nodes()) {\n if (n == link.sourceNode) {\n sourceId = n.id;\n var source = shapes[sourceId];\n sourceX = source[0];\n sourceY = source[1];\n }\n }\n\n // Modifications we have to do on the obtained value\n var modificationsXY = XYvalues[donorPosition];\n var newX = sourceX + modificationsXY[1]; // Apply the modification on x\n var newY = sourceY + modificationsXY[0]; // Apply the modification on y\n\n var availible = isAvailible(newX, newY);\n if (availible != \"\")\n {\n var newPos = findNewSpot(newX,newY, link.donorPosition.value, sourceId);\n newX = newPos[0];\n newY = newPos[1];\n }\n\n return [newX, newY]; // Return the obtained coordinates\n\n } else { // If the node is the root, just add 150 to the x and 900 to y to display it on the right of the svg\n return [origin[0], origin[1]];\n }\n}",
"function check_angleX(angle)\n{\n\tvar x = 0;\n\tdegrees = make_degrees();\n\n\tif (angle == 1) {\n\t\tx = Math.cos((Math.PI/180) * 90 - (Math.PI/180) * degrees) * roboHeight/2;\n\t\treturn x - (Math.cos((Math.PI/180) * degrees) * roboWidth/2);\n\t} else if (angle == 2) {\n\t\tx = Math.cos((Math.PI/180) * 90 - (Math.PI/180) * degrees) * roboHeight/2;\n\t\treturn x + (Math.cos((Math.PI/180) * degrees) * roboWidth/2);\n\t} else if (angle == 3) {\n\t\tx = -Math.sin((Math.PI/180) * degrees) * roboHeight/2;\n\t\treturn x + (Math.cos((Math.PI/180) * degrees) * roboWidth/2);\n\t} else if (angle == 4) {\t\t\t\t\n\t\tx = Math.sin((Math.PI/180) * degrees) * roboHeight/2;\n\t\treturn -(x + (Math.sin((Math.PI/180) * 90 - (Math.PI/180) * degrees) * roboWidth/2));\n\t}\n}",
"toXPolar(raio, angulo){\n return raio * Math.cos( angulo * Math.PI/180 );\n }",
"function leap2armX(x) {\n var leftmost = 2500;\n var rightmost = 650;\n var center = 1575;\n\n // Leftmost corner case\n if (x <= -250) {\n return leftmost;\n }\n\n // Between leftmost and center case\n if (x > -250 && x < 0) {\n var r = x / -250; // Percentage to left of center\n var rs = r * 925; // 925 = amount of space between leftmost and center\n return Math.round(1575 + rs);\n }\n\n // Center case\n if (x == 0)\n return center;\n\n // Between center and rightmost case\n if (x > 0 && x < 250) {\n var r = x / 250; // Percentage right of center\n var rs = r * 925; // 925 = amount of spce between center and rightmost\n return Math.round(1575 - rs);\n }\n\n // Rightmost corner case\n if (x >= 250) {\n return rightmost;\n }\n}",
"function getTransformOrigin(anchor) {\n\t var x = \"0\";\n\t switch (anchor.x) {\n\t case \"right\":\n\t case \"inner-left\":\n\t x = \"0\";\n\t break;\n\t case \"center\":\n\t x = \"50%\";\n\t break;\n\t case \"left\":\n\t case \"inner-right\":\n\t x = \"100%\";\n\t break;\n\t default:\n\t x = \"0\";\n\t }\n\t var y = \"0\";\n\t switch (anchor.y) {\n\t case \"above\":\n\t case \"bottom\":\n\t y = \"100%\";\n\t break;\n\t case \"center\":\n\t y = \"50%\";\n\t break;\n\t case \"below\":\n\t case \"top\":\n\t y = \"0\";\n\t break;\n\t default:\n\t y = \"0\";\n\t }\n\t return x + \" \" + y;\n\t}",
"static get xboxDeployKinectHeadPosition() {}",
"getBearing(facing) {\n switch (facing) {\n case \"north\":\n return 0;\n case \"east\":\n return 90;\n case \"south\":\n return 180;\n case \"west\":\n return 270;\n }\n }",
"function swapRelativeLocationValues(angle) {\n var tmpX = imgFrameAttrs.relativeLoc.x;\n \n if (parseInt(angle, 10) > 0) {\n imgFrameAttrs.relativeLoc.x = 1 - imgFrameAttrs.relativeLoc.y;\n imgFrameAttrs.relativeLoc.y = tmpX;\n } else {\n imgFrameAttrs.relativeLoc.x = imgFrameAttrs.relativeLoc.y;\n imgFrameAttrs.relativeLoc.y = 1 - tmpX; \n }\n }",
"function polar_x(radius, angle) {return(radius * Math.cos(Math.PI/180*angle + Math.PI/180*270));}",
"function camX(x) {\n return tx + (x - width/2) / zoom;\n }",
"getBearingToActiveWaypoint() {\n const lat = SimVar.GetSimVarValue('PLANE LATITUDE', 'degree latitude');\n const long = SimVar.GetSimVarValue('PLANE LONGITUDE', 'degree longitude');\n const ll = new LatLongAlt(lat, long);\n const waypoint = this.getActiveWaypoint();\n\n if (waypoint && waypoint.infos) {\n return Avionics.Utils.computeGreatCircleHeading(ll, waypoint.infos.coordinates);\n }\n\n return 0;\n }",
"function basinAngle(node) {\n var ax = node.point.x - node.next.next.point.x;\n var ay = node.point.y - node.next.next.point.y;\n return Math.atan2(ay, ax);\n}",
"function xDeg(rad)\r\n{\r\n return rad * (180 / Math.PI);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Example For a = [8, 4, 8, 4, 20], the output should be findDistinctNumbers(a) = [8, 4, 20]. | function findDistinctNumbers(a) {
return a.filter((num, i) => i === a.indexOf(num));
} | [
"function findUniques(a){\n let result = []\n for (num of a){\n let match = false;\n for (unum of result){\n if (num == unum){\n match = true;\n }\n }\n if (!match){\n result.push(num);\n }\n }\n return result;\n}",
"function findUniques(nums) {\n // Step 1 - count the appearcnce of each num\n var counts = [];\n for (var i = 0; i < nums.length; i++) {\n var num = nums[i];\n if (!counts[num]) {\n counts[num] = 0;\n }\n counts[num]++;\n }\n var uniques = [];\n for (var i = 0; i < counts.length; i++) {\n if ( counts[i] > 0 ) {\n uniques.push(i);\n }\n \n }\n return uniques;\n}",
"function showDistinctValList_Kata6(input) {\n var output = \"\";\n var inputArr = input.split(\" \");\n inputArr = inputArr.map(Number);\n inputArr.sort(function (a, b) { return a - b });\n for (let i = 0; i < inputArr.length; i++) {\n if (inputArr.indexOf(inputArr[i]) == i) {\n output += inputArr[i] + \" \";\n }\n }\n output = output.slice(0, -1);\n console.log(\"Return distinct values from a list including duplicates. Input : \", input, \" Output : \", output);\n return output;\n}",
"function findDisappearedNumbers(nums) {\n let result = [];\n let set = new Set(nums);\n console.log(set);\n for (let i = 1; i < nums.length; i++) {\n if (!set.has(i)) {\n result.push(i);\n }\n }\n return result;\n}",
"function lonelyinteger(a) {\n let answer;\n const removeDupArr = [...new Set(a)];\n removeDupArr.forEach((uniqElement) => {\n if (a.filter(element => element === uniqElement).length === 1) {\n answer = uniqElement;\n }\n })\n\n return answer\n}",
"function uniqueNumber(array) {\n const arr = array.filter((el, idx) => {\n if (array.indexOf(el) !== idx) return el;\n });\n const once = array.filter((el) => {\n if (!arr.includes(el)) return el;\n });\n return once.join();\n}",
"function removeDuplicates(numbers) {\n return numbers.reduce((accumulator, currentValue) => {\n if(accumulator.indexOf(currentValue) === -1) {\n accumulator.push(currentValue);\n }\n return accumulator;\n }, []);\n}",
"function findUniq(arr) {\n let checkNumber = arr[0];\n let filteredArray = arr.filter(currentNumber => {\n return checkNumber !== currentNumber;\n });\n\n if (filteredArray.length > 1) {\n return checkNumber;\n } else {\n return filteredArray[0];\n }\n}",
"function findUnrepeatedNumber(arr) {\n return arr.reduce(function(num, result) {\n // XOR all the numbers to return the non repeated number.\n return num^result;\n })\n}",
"function findMultipleDuplicates(numberArray) {\n var matches = [];\n var duplicates = [];\n for (var _i = 0, numberArray_2 = numberArray; _i < numberArray_2.length; _i++) {\n var num = numberArray_2[_i];\n if (matches.indexOf(num) == -1)\n matches.push(num);\n else\n duplicates.push(num);\n }\n return duplicates;\n}",
"function findDup(arr){\n return arr.sort((x,y)=>x-y).filter((v,i,arr)=>v===arr[i+1])*1;\n}",
"function findUniq(arr) {\n const unique = []\n const sortedArr = arr.sort((a, b) => a - b)\n \n for (let i = 0; i < sortedArr.length; i++) {\n if(sortedArr[i] !== sortedArr[+1] && sortedArr[i] !== sortedArr[i-1]) {\n unique.push(sortedArr[i])\n }\n }\n\n return unique[0]\n}",
"function findDuplicate(numberArray) {\n var matches = [];\n for (var _i = 0, numberArray_1 = numberArray; _i < numberArray_1.length; _i++) {\n var num = numberArray_1[_i];\n if (matches.indexOf(num) == -1)\n matches.push(num);\n else\n return num;\n }\n return undefined;\n}",
"function repeatedNumber(array){\n const repeatedNumbers = []\n for(var i=0;i<array.length;i++){\n if( array[i+1] === array[i]){\n repeatedNumbers.push(array[i])\n }\n }\n return repeatedNumbers;\n}",
"function findDuplicateNumbers(numberArray) {\n let object = {};\n let result = [];\n\n numberArray.forEach(function (item) {\n if (!object[item]) object[item] = 0;\n object[item] += 1;\n });\n for (let prop in object) {\n if (object[prop] >= 2) {\n result.push(prop);\n }\n }\n return result;\n}",
"function find2Unique(arr) {\n let diff = 0;\n let oneNo = 0;\n let ans = [];\n for (let i = 0; i < arr.length; i++) {\n diff = diff ^ arr[i]; // this will give the diff btw the 2 unique num\n }\n for (let i = 0; i < arr.length; i++) {\n if ((arr[i] & diff) > 0)\n // we'll check all the numbers that have the diff\n oneNo = oneNo ^ arr[i]; // and xor them to find one of the unique numbers\n }\n ans[0] = oneNo;\n ans[1] = oneNo ^ diff; // by applying xor to the number and the diff we get the second unique number\n return ans;\n}",
"function findOdd(A) {\n const uniqueNumsArray = [...new Set(A)]\n let indexOfOdd = 0\n arr = []\n let occurenceCount = Array(uniqueNumsArray.length).fill(0)\n\n A.forEach((item) => {\n if (item === item) {\n let counter = 0\n const itemIndex = uniqueNumsArray.indexOf(item)\n counter++\n occurenceCount[itemIndex] += counter\n }\n })\n occurenceCount.forEach(occurence => {\n arr.push(occurence % 2)\n })\n arr.forEach(odd => {\n if (odd === 1) {\n indexOfOdd += arr.indexOf(odd)\n }\n })\n return uniqueNumsArray[indexOfOdd]\n}",
"function duplicates(arr) {\n var dupe = [];\n for (var i = 0; i < arr.length; i++) {\n var n = arr[i];\n if (arr.indexOf(n, i + 1) >= 0 && dupe.indexOf(n) < 0) {\n dupe.push(n);\n }\n }\n\n return dupe;\n}",
"function findAllDuplicates(nums) {\n let ans = [];\n let s = new Set();\n for (let i = 0; i < nums.length; i++) {\n s.has(nums[i]) ? ans.push(nums[i]) : s.add(nums[i]);\n }\n return ans;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
25to44 2orMore 45to64 65Plus Asian Black Hawaiian Hispanic Married with Children Native Single Female with Children Single Male with Children Single or Cohabitating under 65 Total U25 White filter for total | function TotalFilter(feature) {
if ((feature.properties['STATEABV'] === st)&&(feature.properties['Group'] === "Total")) return true
} | [
"function filtertotal(num) {\n return num.Total > 50000;}",
"function ageU25Filter(feature) {\r\n if ((feature.properties['STATEABV'] === st)&&(feature.properties['Group'] === \"U25\")&&(feature.properties['TOTAL'] > 99)) return true\r\n}",
"TotalGHG(){\n return this.industries.map(i=>i.wwt_KPI_GHG().total).sum(); //kgCO2eq\n }",
"filterCountriesByMedalType(medalType) {\r\n const property = `total${medalType}`; // e.g. totalGold\r\n return this.state.rankCountries.filter(country => {\r\n return country[property] > 0;\r\n });\r\n }",
"function severity_anx(total) {\n const severityField = document.querySelector('#severityanx');\n\n\n if (total === 0){\n severity.innerText = \"All zero\"\n } else if (total > 0 && total < 5) {\n severityField.innerText = \"Minimal Anxiety\";\n } else if (total > 4 && total < 10) {\n severityField.innerText = \"Mild Anxiety\";\n } else if (total > 9 && total < 15) {\n severityField.innerText = \"Moderate Anxiety\";\n } else if (total > 14 && total < 20) {\n severityField.innerText = \"Moderately Severe Anxiety\";\n } else if (total > 19) {\n severityField.innerText = \"Severe Anxiety\";\n }\n}",
"TotalNRG(){\n return this.industries.map(i=>i.wwt_nrg_cons).sum(); //kWh\n }",
"function feet_filter(term, value, formatted, model) {\n if (term === 'tall') { return value > 70; }\n if (term === 'short') { return value < 69; }\n return true;\n }",
"function totalManaSymbols2() {\n var r = 0;\n for(var i=0;i<5;i++){\n r += getVal(getElementByColor2(gElements[i], false));\n }\n return r;\n}",
"function billTotal(subTotal){\n\treturn subTotal + subTotal*.095 + subTotal*.15;\n}",
"totalPanier(state) {\n let total = 0;\n state.panier.forEach((key, value) => {\n total += key.prix * state.quantite[value] / 100;\n })\n return total.toFixed(2);\n }",
"function totalWithNJSalesTax(){\n return (coffeeTotal*0.007) + coffeeTotal;\n}",
"function filterMag(value) {\n\n \n }",
"function loandeduct(incoming)\r\n{\r\n\t//Annual Pag-ibig Deduction\r\n\tvar pagibig = parseFloat(12 * incoming * 0.01375);\r\n\r\n\t//Annual Philhealth Deduction\r\n\tvar philhealth = parseFloat(12 * incoming * 0.035);\r\n\r\n\t// Sum of Philhealth and Pag-ibig\r\n\tvar total = pagibig + philhealth;\r\n\r\n\treturn total;\r\n}",
"function filterAggregated(data){\r\n\t\treturn data.filter(function(elem, idx){\r\n\t\t\treturn elem['Age'] == 'All (above 15)' && elem['Gender'] == 'All'\r\n\t\t});\r\n\t}",
"function maleCodersUnderTwentyFive(arr) {\n let filtered = arr.filter(n => n.gender === \"m\")\n return filtered.map( n => n.age).reduce((n, acc) => n+ acc, 0)\n}",
"function sumFreeColumn2() {\n sumFree2 = columnFree2.reduce(add);\n sumFree2 >= 60 ? (sumFree2 = sumFree2 + 30) : (sumFree2 = sumFree2);\n document.querySelector(\".sumFreeFirst2\").innerHTML = sumFree2;\n sumPartOne2();\n sumAllResult2();\n}",
"function calculateTotal(){\r\n const convertPhoneCount = getProductCount('phone');\r\n const convertCaseCount = getProductCount('case');\r\n //Calculate subtotal and display.\r\n const subTotal = convertPhoneCount * 1219 + convertCaseCount * 59;\r\n document.getElementById('subTotal').innerText = subTotal;\r\n //Calculate tax and display.\r\n const tax = Math.round(subTotal * 0.05);\r\n document.getElementById('tax').innerText = tax;\r\n //Calculate total and display.\r\n const total = subTotal + tax;\r\n document.getElementById('total').innerText = total;\r\n }",
"function treasure_render_gold(total_value) {\r\n\r\n // arranged in treasure pile draw order (Heroine Dusk behavior)\r\n\r\n if (total_value & 128) treasure_render_gold_icon(7);\r\n if (total_value & 512) treasure_render_gold_icon(9);\r\n if (total_value & 32) treasure_render_gold_icon(5);\r\n if (total_value & 16) treasure_render_gold_icon(4);\r\n if (total_value & 8) treasure_render_gold_icon(3);\r\n if (total_value & 1) treasure_render_gold_icon(0);\r\n if (total_value & 4) treasure_render_gold_icon(2);\r\n if (total_value & 64) treasure_render_gold_icon(6);\r\n if (total_value & 2) treasure_render_gold_icon(1);\r\n if (total_value & 256) treasure_render_gold_icon(8);\r\n\r\n \r\n //guesstimate amount (designed for Heroin Dusk)\r\n /*\r\n if(total_value < 2)\r\n\ttreasure_render_gold_icon(0);\r\n else if(total_value < 10)\r\n\ttreasure_render_gold_icon(1);\r\n else if(total_value < 20)\r\n\ttreasure_render_gold_icon(2);\r\n else if(total_value < 100)\r\n\ttreasure_render_gold_icon(3);\r\n else\r\n\ttreasure_render_gold_icon(4);\r\n\t*/\r\n\r\n}",
"function sumUberTotal(data) {\n let uberSum = 0;\n for (var i = 0; i < data.length; i++) {\n uberSum += parseFloat(access(data[i], d => d.Uber_Breakdown.Total));\n }\n return uberSum;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
7.1.11 ToUint8Clamp ( argument ) | function ToUint8Clamp(argument) {
var number = Number(argument);
if ($isNaN(number)) return 0;
if (number <= 0) return 0;
if (number >= 255) return 255;
var f = floor(number);
if ((f + 0.5) < number) return f + 1;
if (number < (f + 0.5)) return f;
if (f % 2) return f + 1;
return f;
} | [
"function clampUint8(value) {\n return Math.max(0, Math.min(255, Math.round(value)));\n}",
"function ToUint8(v) { return v & 0xFF; }",
"function floatToUint8Clamped(floatArray){\n\tvar uint8Array = new Uint8ClampedArray(floatArray);\n\tvar rgbaArray = new Uint8ClampedArray(uint8Array.length * 4);\n\tuint8Array.forEach((e, i)=>{\n\t\trgbaArray[i*4] = e;\n\t\trgbaArray[i*4 + 1] = e;\n\t\trgbaArray[i*4 + 2] = e;\n\t\trgbaArray[i*4 + 3] = 255;\n\t})\n\treturn rgbaArray;\n}",
"function floatToUint8Clamped(floatArray){\n\tvar uint8Array = new Uint8ClampedArray(floatArray);\n\tvar rgbaArray = new Uint8ClampedArray(uint8Array.length * 4);\n\n\tuint8Array.forEach((e, i)=>{\n\t\trgbaArray[i*4] = e;\n\t\trgbaArray[i*4 + 1] = e;\n\t\trgbaArray[i*4 + 2] = e;\n\t\trgbaArray[i*4 + 3] = 255;\n\t})\n\treturn rgbaArray;\n}",
"function ToInt8(v) { return (v << 24) >> 24; }",
"function convertUint8ArrayToArray(data) {\n return [...data];\n}",
"function fromS8U8(i) {\n return i / 256;\n}",
"function roundUint8ToNextPowerOfTwo(value) {\n\tvalue -= 1;\n\tvalue |= value >>> 1;\n\tvalue |= value >>> 2;\n\tvalue |= value >>> 4;\n\tvalue += 1;\n\treturn value;\n}",
"function forceUint8(value) {\n uint8ForceArray[0] = value;\n return uint8ForceArray[0];\n}",
"function clampToInt16(x) {\n return Math.max(Math.min(Math.round(x), 32767), -32768);\n}",
"function ToUInt8(argument) { // eslint-disable-line no-unused-vars\n\t// 1. Let number be ? ToNumber(argument).\n\tvar number = Number(argument);\n\t// 2. If number is NaN, +0, -0, +∞, or -∞, return +0.\n\tif (isNaN(number) || 1/number === Infinity || 1/number === -Infinity || number === Infinity || number === -Infinity) {\n\t\treturn 0;\n\t}\n\t// 3. Let int be the mathematical value that is the same sign as number and whose magnitude is floor(abs(number)).\n\tvar int = ((number < 0) ? -1 : 1) * Math.floor(Math.abs(number));\n\t// 4. Let int8bit be int modulo 2^8.\n\tvar int8bit = int % Math.pow(2,8);\n\t// 5. Return int8bit.\n\treturn int8bit;\n}",
"function _checkIsUint8ClampedImageData(){if(\"undefined\"==typeof Uint8ClampedArray)return!1;var elem=document.createElement(\"canvas\"),ctx=elem.getContext(\"2d\");if(!ctx)return!1;var image=ctx.createImageData(1,1);return image.data instanceof Uint8ClampedArray}",
"function fromS8U8(i) {\n return i / 256;\n }",
"function clamp(r)\n{\n\t r[3] &= 15;\n r[7] &= 15;\n r[11] &= 15;\n r[15] &= 15;\n r[4] &= 252;\n r[8] &= 252;\n r[12] &= 252;\n return r;\n}",
"function get1To255(){\n var output = [];\n for(var i = 0; i <= 255; i++){\n output.push(i);\n }\n return output;\n}",
"function from255(value) {\n return value/255.0;\n}",
"function u8(val) {\n return val & 0xFF;\n}",
"function decodeAndClamp(value, addend, coefficient, max) {\n\t value = addend + value * coefficient;\n\t // Clamp the value to the range\n\t return (value < 0 ? 0 : (value > max ? max : value));\n\t }",
"function isUint8ClampedImageData() {\n if (typeof Uint8ClampedArray === \"undefined\")\n return false;\n var elem = document.createElement('canvas');\n var ctx = elem.getContext('2d');\n if (!ctx) //bail out early..\n return false;\n var image = ctx.createImageData(1, 1);\n return image.data instanceof Uint8ClampedArray;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Go to the previous slide, either subslide or main slide, whichever is previous | function goToPreviousSlide() {
if (getCurrentSubSlide() != -1 && getCurrentSubSlide() > 0) {
goToSlide(getCurrentMainSlide(), getCurrentSubSlide() - 1);
return true;
}
if (getCurrentMainSlide() > 0) {
goToSlide(getCurrentMainSlide() - 1);
return true;
}
} | [
"function previousSlide() {\r\n var index = currentIndex == 0 ? (numSlides - 1) : (currentIndex - 1);\r\n gotoSlide(index);\r\n }",
"function goToPreviousSlide(){\n myPresentation.goToPreviousSlide();\n displayNumberCurrentSlide();\n selectOptionInSelector(myPresentation.getCurrentSlideIndex());\n updateNote();\n}",
"goToPrev () {\n\t\t\tif (this.canGoToPrev) {\n\t\t\t\tthis.goTo(this.currentSlide - 1)\n\t\t\t}\n\t\t}",
"function goPrevious() {\n slideTo(currentIndex - 1);\n }",
"function prevSlide () {\n if (model.slide - 1 >= 0) changeSlide(model.slide - 1);\n }",
"function callPreviousSlide(){\n\n if( currentSlide !== minSlides ){\n nextSlide = currentSlide - 1;\n goToSlide( nextSlide );\n }\n\n if( currentSlide === minSlides ){\n nextSlide = maxSlides;\n goToSlide( nextSlide );\n }\n }",
"function goPrevious() {\n updateTracker();\n if (pageNum <= 1)\n return;\n pageNum--;\n slideChange();\n renderPage(pageNum);\n\n}",
"function navigatePrevSlide() {\n\n\t\t// Prioritize revealing fragments\n\t\t//if( noFragments() === false ) {\n\t\t\tif( Reveal.availableRoutes().up ) {\n\t\t\t\tReveal.navigateUpSlide();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Fetch the previous horizontal slide, if there is one\n navigateLeftSlide()\n\t\t\t}\n\t\t//}\n\n\t}",
"function prevSlide() {\n if (currentIndex > 0) {\n scrollTo(currentIndex - 1);\n }\n }",
"function goToPreviousSlide() {\n\t\t\tvar hash = window.location.hash;\n\t\t\tvar slideNum = slideNumFromHash(hash) - 1;\n\t\t\tif (slideNum < 0) slideNum = 0;\n\t\t\t$('.slideshow').cycle( slideNum );\n\t\t}",
"function navigatePrev() {\n\n // Prioritize revealing fragments\n if (previousFragment() === false) {\n if (availableRoutes().up) {\n navigateUp();\n }\n else {\n // Fetch the previous horizontal slide, if there is one\n var previousSlide = document.querySelector(HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')');\n\n if (previousSlide) {\n var v = ( previousSlide.querySelectorAll('section').length - 1 ) || undefined;\n var h = indexh - 1;\n slide(h, v);\n }\n }\n }\n\n }",
"function previous() {\n\tslideN(i - 1);\t\t\t\t\t\t\t\t\t// Calls previous slide.\n}",
"prev() {\n\n if (this.currStep > -1) {\n\n this.prevStep();\n\n } else {\n\n this.prevSlide();\n\n }\n\n }",
"function navigatePrev() {\n\n\t\t\t// Prioritize revealing fragments\n\t\t\tif( previousFragment() === false ) {\n\t\t\t\tif( availableRoutes().up ) {\n\t\t\t\t\tnavigateUp();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// Fetch the previous horizontal slide, if there is one\n\t\t\t\t\tvar previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );\n\n\t\t\t\t\tif( previousSlide ) {\n\t\t\t\t\t\tvar v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;\n\t\t\t\t\t\tvar h = indexh - 1;\n\t\t\t\t\t\tslide( h, v );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}",
"function navigatePrev() {\n\n\t\t// Prioritize revealing fragments\n\t\tif( previousFragment() === false ) {\n\t\t\tif( availableRoutes().up ) {\n\t\t\t\tnavigateUp();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Fetch the previous horizontal slide, if there is one\n\t\t\t\tvar previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );\n\n\t\t\t\tif( previousSlide ) {\n\t\t\t\t\tvar v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;\n\t\t\t\t\tvar h = indexh - 1;\n\t\t\t\t\tslide( h, v );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}",
"function goPrevious() {\n goto(currentIndex - 1, \"\", true);\n}",
"function navigatePrev() {\n\n\t\t// Prioritize revealing fragments\n\t\tif( previousFragment() === false ) {\n\t\t\tif( availableRoutes().up ) {\n\t\t\t\tnavigateUp();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Fetch the previous horizontal slide, if there is one\n\t\t\t\tvar previousSlide;\n\n\t\t\t\tif( config.rtl ) {\n\t\t\t\t\tpreviousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.future' ) ).pop();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tpreviousSlide = toArray( dom.wrapper.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.past' ) ).pop();\n\t\t\t\t}\n\n\t\t\t\tif( previousSlide ) {\n\t\t\t\t\tvar v = ( previousSlide.querySelectorAll( 'section' ).length - 1 ) || undefined;\n\t\t\t\t\tvar h = indexh - 1;\n\t\t\t\t\tslide( h, v );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}",
"function previousSlide(responsive) {\n\t\tshowSlide((current-1) % content.length, responsive);\n\t}",
"function prevSlide() {\r\n positionSlide(currentSlide - 1);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks which page you are on, and runs the right functions | function WhatPage(){
if (window.location.href.includes("hackforums.net/member.php?action=profile&uid=")){
RunOnEveryPage();
RunOnProfile();
return;
}
if (window.location.href.includes("hackforums.net/managegroup.php?gid=")){
RunOnEveryPage();
HighlightUser();
return;
}
else{
RunOnEveryPage();
return;
}
} | [
"function checkPage() {\n console.log('CHECK PAGE RUN');\n let page = window.location.pathname.split('/')[6];\n\n switch (page) {\n case '8f003a39e5':\n getStoryContent();\n break;\n case '97cc350c5e':\n console.log('RUN SHIPPING FUNCTION TO GET MDE CONTENT');\n getShippingContent();\n break;\n case 'ed8c8f347e':\n console.log('RUN RETURNS FUNCTION TO GET MDE CONTENT');\n getReturnsContent();\n break;\n case '5d4b314e6d':\n console.log('RUN PAYMENTS FUNCTION TO GET MDE CONTENT');\n getPaymentsContent();\n break;\n case '649b879831':\n console.log('RUN ORDERS FUNCTION TO GET MDE CONTENT');\n getOrdersContent();\n break;\n case 'e7b6d56e22':\n console.log('RUN TERMS & COND FUNCTION TO GET MDE CONTENT');\n getTermscondContent();\n break;\n case 'b77bf5106e':\n console.log('RUN PRIVACY POLICY FUNCTION TO GET MDE CONTENT');\n getPrivacypolContent();\n break;\n default:\n\n }\n }",
"function checkPageOne() { \r\n\r\n// http://www.facebook.com/common/error.html\r\n\r\n\tif (url.search(\"error.html\")!=-1) {\r\n\t\twindow.history.back()\r\n\t} \r\n\r\n\tif (url.search(\"ViewTheShop.php\")!=-1) {\r\n\t\ttdisp = 0;\r\n checkGeneration();\t\r\n\t\tviewTheShop();\r\n\r\n\t\t\r\n\t\tfillEquipInfo();\r\n\t\tsetTimeout(fillEquipInfo,5000) \t\r\n\t \t\t\r\n\t} \r\n \r\n \tif (url.search(\"ViewRewards.php\")!=-1) {\r\n\t\ttdisp = 0;\r\n\t \tcheckGeneration();\t\r\n\t\tviewRewards();\t\r\n\t\taddRewardPowers();\t\r\n\t}\t\r\n\t\r\n \tif (url.search(\"ViewRetired.php\")!=-1) {\r\n\t\ttdisp = 0;\r\n\t \tcheckGeneration();\t\r\n\t\tviewRewards();\t\r\n\t\taddRewardPowers();\t\r\n\t}\t\r\n\t\t\r\n\t\r\n\t\r\n\r\n}",
"function main(){\n console.log(window.location.href);\n\n if (onLoginPageTest()){\n console.log(\"On a login page\")\n //initiate logic for login page (autofill and stuff)\n loginPageLogic();\n }\n\n if (onRegistrationPageTest()){\n console.log(\"On a registration page\")\n displayPasswordGenButton();\n modifyPageContent();\n }\n\n if (onChangePasswordPageTest()){\n console.log(\"On a change password page\");\n displayPasswordGenButton();\n changePasswordPageLogic();\n }\n\n\n}",
"function renderPage() {\r\n if (window.location.href.indexOf(\"adminStats.html\") > 0) renderAdmin();\r\n else if (window.location.href.indexOf(\"adminMembers.html\") > 0) renderMembers();\r\n else if (window.location.href.indexOf(\"myProfile.html\") > 0) renderProfile();\r\n else if (window.location.href.indexOf(\"proposals.html\") > 0) listProposals();\r\n else if (window.location.href.indexOf(\"adminProposals.html\") > 0) renderAdminProposals();\r\n else if (window.location.href.indexOf(\"delegations.htm\") > 0) renderMembers(\"delegate\");\r\n else if (window.location.href.indexOf(\"index.html?ref=true\") > 0) $(\"#modal-register\").modal();\r\n else if (window.location.href.indexOf(\"funding.html\") > 0) renderFunding();\r\n}",
"function checkPage(){\n\n\t\tvar page_id = $(\".navigation ul li.active a\").attr(\"href\").split(\"#\")[1];\n\n\t\tgoto_page(page_id);\n\n\t}",
"function _page1_page() {\r\n}",
"function _page1_page() {\n}",
"function pageloadcheck() {\n\t\n\tgethashvalues(window.location.hash);\n\n\tLoadScores(hashvalues['page']);\n\n}",
"function runMethod() {\n var getPage = getDOM(\"page\").getAttribute(\"title\")\n switch (getPage) {\n case \"select_bundle\":\n selectBundle()\n break;\n case \"personal\":\n personalInfo()\n break\n default:\n return;\n }\n }",
"function runpage(){\r\n console.log('Function runpage() initiated');\r\n console.log('Function Changepage initiating');\r\n changepage();\r\n console.log('Function changepage completed');\r\n console.log('Function wrapUp initiating');\r\n wrapUp();\r\n console.log('Function wrapUp completed');\r\n console.log('Function Array1');\r\n Array1();\r\n console.log('Function Array1 completed');\r\n console.log('Function gathername Initiating');\r\n gathername();\r\n console.log('Function gathername completed');\r\n console.log('Runpage checklist 100% complete')\r\n}",
"function identify() {\n console.log(\".. Identifying Web Page\");\n if (timeLineCName !== null && timeLineHLine !== null) {\n var selectedTab = \"Timeline\";//document.getElementsByClassName(fbstrings.selectedTab)[0].innerText;\n console.log(\".. .. selected tab is: \" + selectedTab);\n\n updateProfPic(false);\n addSidAnalyticsMenu();\n\n if (selectedTab === \"About\") {\n var subsection = document.getElementsByClassName(fbstrings.subSection)[0];\n if (subsection.innerText === \"Work and Education\") {\n //manipulateAboutWork();\t\t/*if an fb about work page, and haven't modified before, then add sid elements*/\n manipulateAbout(fbstrings.workClaim, \"Work\");\n }\n /**TODO add similar functionality to places lived, Basic info, family, and life events*/\n\n else if (subsection.innerText === \"Life Events\") {\n //manipulateLifeEvents();\t\t/*if an fb about work page, and haven't modified before, then add sid elements*/\n manipulateAbout(fbstrings.lifeEventClaim, \"Events\");\n }\n else if (subsection.innerText === \"Overview\") {\n //manipulateOverview();\n manipulateAbout(fbstrings.lifeEventClaim, \"Overview\");\n }\n\n } else if (selectedTab === \"Timeline\") {\n manipulateTimeLine();\n /*if an fb profile timeline, and haven't modified before, then add sid elements*/\n // updFrndsProfInTimeLine();\n }\n }\n}",
"function identify(){\n\tconsole.log(\".. Identifying Web Page\");\n\tif(timeLineCName!==null && timeLineHLine!==null){\n\t\tvar selectedTab = document.getElementsByClassName(fbstrings.selectedTab)[0].innerHTML;\n\t\tconsole.log(\".. .. selected tab is: \" + selectedTab);\n\t\t\n\t\tupdateProfPic(false);\n\t\taddSidAnalyticsMenu();\n\t\taddCommentSection(\"getComments\");\n\t\t\n\t\tif(selectedTab.indexOf(\"About\") === 0) {\n\t\t\tvar subSectionHolder = document.getElementsByClassName(fbstrings.subSection)[0];\n\t\t\tif(subSectionHolder){\n\t\t\t\tvar subsection = subSectionHolder.innerHTML;\n\t\t\t\tif(subsection.indexOf(\"Work and Education\") ===0 ){\n\t\t\t\t\t//manipulateAboutWork();\t\t\n\t\t\t\t\tmanipulateAbout(fbstrings.workClaim,\"Work\");\n\t\t\t\t}\t\t\t\t\n\t\t\t\telse if(subsection.indexOf(\"Life Events\") ===0 ){\n\t\t\t\t\t//manipulateLifeEvents();\t\t\n\t\t\t\t\tmanipulateAbout(fbstrings.lifeEventClaim,\"Events\");\n\t\t\t\t}\n\t\t\t\telse if(subsection.indexOf(\"Overview\") ===0 ){\n\t\t\t\t\t//manipulateOverview();\n\t\t\t\t\tmanipulateAbout(fbstrings.lifeEventClaim,\"Overview\");\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tconsole.log(\"Unable to access About subsection\");\n\t\t\t}\n\t\t}else if (selectedTab.indexOf(\"Timeline\") === 0){\n\t\t\tconsole.log(\"selectedTab: \"+ selectedTab);\n\t\t\tmanipulateTimeLine();\t\n\t\t\tupdFrndsProfInTimeLine();\n\t\t}\n\t}else{\n\t\tconsole.log(\"timeline if condition false\");\n\t}\n}",
"function pageCheck() {\n let urlCheck1 = document.URL.includes(userName);\n let urlCheck2 = document.URL.includes(\"tab=repositories\");\n\n if (urlCheck1 && urlCheck2) createDeleteButtons();\n}",
"function LoadPageContent() {\n switch (document.title) {\n case \"Home\":\n LoadHomePage();\n break;\n case \"Projects\":\n LoadProjectsPage();\n break;\n case \"Contact\":\n LoadContactPage();\n break;\n }\n }",
"function pageSaisie() {\n\n}",
"function detectPage() { \n\t\t\n\t\tswitch( pageName ) { \n\t\t\t\n\t\t\tcase \"home\":\n\t\t\t\tfiles.push({ name: \"iSee Home Page Class\", src: connectURL + \"js/isee/iSeeHome.js\" , type: \"class\" , active: true });\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"sobre\":\n\t\t\t\tfiles.push({ name: \"iSee About Page Class\", src: connectURL + \"js/isee/iSeeSobre.js\" , type: \"class\" , active: true });\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"solucoes\":\n\t\t\t\tfiles.push({ name: \"iSee Solucoes Page Class\", src: connectURL + \"js/isee/iSeeSolucoes.js\" , type: \"class\" , active: true });\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"update\":\n\t\t\t\tfiles.push({ name: \"iSee Update Page Class\", src: connectURL + \"js/isee/iSeeUpdate.js\" , type: \"class\" , active: true });\n\t\t\tbreak;\n\t\t\n\t\t}\n\t}",
"function triggerPage() {\n var i;\n\n for (i = 0; i < page_callbacks.length; i = i + 1) {\n page_callbacks[i]();\n }\n }",
"function start(){\n if(path.includes(\"/contact.html\")){\n getBrowserName();\n }\n else if(path.includes(\"/ourfleet.html\") || path.includes(\"/employees.html\")){\n imgPreloader();\n addClickEventToThumbnails();\n }\n else if(path.includes(\"/booking.html\")){\n initializeBookingPage();\n }\n}",
"function otherPage() { console.log('otherPage page'); addIframe(); getProjectedEarnings(); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Advanced Examples It might be best to master the basics first, but this is included to tease the many possibilies LeanTween provides. | function advancedExamples(){
LeanTween.delayedCall(gameObject, 14f, function(){
for(var i:int=0; i < 10; i++){
// Instantiate Container
var rotator:GameObject = new GameObject("rotator"+i);
rotator.transform.position = new Vector3(10.2f,2.85f,0f);
// Instantiate Avatar
var dude:GameObject = GameObject.Instantiate(prefabAvatar, Vector3.zero, prefabAvatar.transform.rotation ) as GameObject;
dude.transform.parent = rotator.transform;
dude.transform.localPosition = new Vector3(0f,1.5f,2.5f*i);
// Scale, pop-in
dude.transform.localScale = new Vector3(0f,0f,0f);
LeanTween.scale(dude, new Vector3(0.65f,0.65f,0.65f), 1f).setDelay(i*0.2f).setEase(LeanTweenType.easeOutBack);
// Color like the rainbow
var period:float = LeanTween.tau/10*i;
var red:float = Mathf.Sin(period + LeanTween.tau*0f/3f) * 0.5f + 0.5f;
var green:float = Mathf.Sin(period + LeanTween.tau*1f/3f) * 0.5f + 0.5f;
var blue:float = Mathf.Sin(period + LeanTween.tau*2f/3f) * 0.5f + 0.5f;
var rainbowColor:Color = new Color(red, green, blue);
LeanTween.color(dude, rainbowColor, 0.3f).setDelay(1.2f + i*0.4f);
// Push into the wheel
LeanTween.moveZ(dude, 0f, 0.3f).setDelay(1.2f + i*0.4f).setEase(LeanTweenType.easeSpring).setOnComplete(
function( rot:GameObject ){
LeanTween.rotateAround(rot, Vector3.forward, -1080f, 12f);
}
).setOnCompleteParam( rotator );
// Jump Up and back down
LeanTween.moveLocalY(dude,4f,1.2f).setDelay(5f + i*0.2f).setLoopPingPong().setRepeat(2).setEase(LeanTweenType.easeInOutQuad);
// Alpha Out, and destroy
LeanTween.alpha(dude, 0f, 0.6f).setDelay(9.2f + i*0.4f).setDestroyOnComplete(true).setOnComplete(
function(rot:GameObject){
Destroy( rot ); // destroying parent as well
}
).setOnCompleteParam( rotator );
}
}).setOnCompleteOnStart(true).setRepeat(-1); // Have the OnComplete play in the beginning and have the whole group repeat endlessly
} | [
"_makeTween () {\n // pass callbacks context\n this._o.callbacksContext = this._o.callbacksContext || this;\n this.tween = new Tween( this._o );\n // make timeline property point to tween one is \"no timeline\" mode\n ( this._o.isTimelineLess ) && ( this.timeline = this.tween );\n }",
"function onTweenComplete()\n{\n createjs.Tween.get(egg).to({y: 100, visible: false}, 500);\n \n}",
"function setupTween() {\n \n if (!script.api.manualStart) {\n var startRaw = getRawByName(\"start\");\n script.api.start = getValueFromRaw(startRaw);\n \n }\n\n if (!script.api.manualEnd) {\n var endRaw = getRawByName(\"end\");\n script.api.end = getValueFromRaw(endRaw);\n }\n\n var startValue = script.api.start;\n var endValue = script.api.end;\n \n var tween = null;\n\n // Reset object to start\n resetObject();\n script.onUpdateCallback = getCallbackFunction();\n // Create the tween\n tween = new TWEEN.Tween(startValue)\n .to(endValue, script.api.time * 1000.0)\n .delay(script.delay * 1000.0)\n .easing(global.tweenManager.getTweenEasingType(script.easingFunction, script.easingType))\n .onUpdate(updateValue);\n\n if (tween) {\n // Configure the type of looping based on the inputted parameters\n global.tweenManager.setTweenLoopType(tween, script.loopType);\n\n // Save reference to tween\n script.api.tween = tween;\n\n return tween;\n } else {\n return;\n }\n}",
"_makeTween() {\n\n // pass callbacks context\n this._o.callbacksContext = this._o.callbacksContext || this;\n this.tween = new Tween(this._o);\n\n // make timeline property point to tween one is \"no timeline\" mode\n (this._o.isTimelineLess) && (this.timeline = this.tween);\n }",
"tween(particle,axis,{\n o, //optional strength value\n d=particle.tweenDuration, //duration\n t=particle.tweenCurrent, //current time\n type=axis==='x'?particle.tweenTypeX:particle.tweenTypeY, //tween type\n b=axis==='x'?particle.startX:particle.startY, //beginning value\n c=axis==='x'?particle.endX-particle.startX:particle.endY-particle.startY\n }={}){\n let result; //returns computed x or y location\n\n if(type==='ease-in-quad'){\n result = c*(t/=d)*t+b;\n }else if(type==='ease-out-quad'){\n result = -c*(t/=d)*(t-2)+b;\n }else if(type==='ease-in-out-quad'){\n result = (t/=d/2)<1?c/2*t*t+b:-c/2*((--t)*(t-2)-1)+b;\n }else if(type==='ease-in-cubic'){\n result = c*(t/=d)*t*t+b;\n }else if(type==='ease-out-cubic'){\n result = c*((t=t/d-1)*t*t+1)+b;\n }else if(type==='ease-in-out-cubic'){\n result = ((t/=d/2)<1)?c/2*t*t*t+b:c/2*((t-=2)*t*t+2)+b;\n }else if(type==='ease-in-quart'){\n result = c*(t/=d)*t*t*t+b;\n }else if(type==='ease-out-quart'){\n result = -c*((t=t/d-1)*t*t*t-1)+b;\n }else if(type==='ease-in-out-quart'){\n result = ((t/=d/2)<1)?c/2*t*t*t*t+b:-c/2*((t-=2)*t*t*t-2)+b;\n }else if(type==='ease-in-quint'){\n result = c*(t/=d)*t*t*t*t+b;\n }else if(type==='ease-out-quint'){\n result = c*((t=t/d-1)*t*t*t*t+1)+b;\n }else if(type==='ease-in-out-quint'){\n result = ((t/=d/2)<1)?c/2*t*t*t*t*t+b:c/2*((t-=2)*t*t*t*t+2)+b;\n }else if(type==='ease-in-sine'){\n result = -c*Math.cos(t/d*(Math.PI/2))+c+b;\n }else if(type==='ease-out-sine'){\n result = c*Math.sin(t/d*(Math.PI/2))+b;\n }else if(type==='ease-in-out-sine'){\n result = -c/2*(Math.cos(Math.PI*t/d)-1)+b;\n }else if(type==='ease-in-exponential'){\n result = (t===0)?b:c*Math.pow(2,10*(t/d-1))+b;\n }else if(type==='ease-out-exponential'){\n result = (t===d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;\n }else if(type==='ease-in-out-exponential'){\n result =\n t===0? b:\n t===d? b+c:\n (t/=d/2)<1? c/2*Math.pow(2,10*(t-1))+b:\n c/2*(-Math.pow(2,-10*--t)+2)+b\n }else if(type==='ease-in-circular'){\n result = -c*(Math.sqrt(1-(t/=d)*t)-1)+b;\n }else if(type==='ease-out-circular'){\n result = c*Math.sqrt(1-(t=t/d-1)*t)+b;\n }else if(type==='ease-in-out-circular'){\n result = ((t/=d/2)<1)?-c/2*(Math.sqrt(1-t*t)-1)+b:c/2*(Math.sqrt(1-(t-=2)*t)+1)+b;\n }else if(type==='ease-in-elastic-weak'){\n result = this.tween(particle,axis,{o: 0.5,type: 'ease-in-elastic'});\n }else if(type==='ease-in-elastic'){\n result = (()=>{\n let s=1.70158,p=0,a=c;\n\n if(t===0) return b;\n if((t/=d)===1) return b+c;\n if(!p) p=d*(o||0.3);\n if(a < Math.abs(c+0.1)){\n a=c;s=p/4;\n }else{\n s = p/(2*Math.PI)*Math.asin(c/a);\n } //end if\n return -(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;\n })();\n }else if(type==='ease-in-elastic-strong'){\n result = this.tween(particle,axis,{o: 0.1,type: 'ease-in-elastic'});\n }else if(type==='ease-out-elastic-weak'){\n result = this.tween(particle,axis,{o: 0.5,type: 'ease-out-elastic'});\n }else if(type==='ease-out-elastic'){\n result = (()=>{\n var s=1.70158,p=0,a=c;\n\n if (t===0) return b;\n if ((t/=d)===1) return b+c;\n if (!p) p=d*(o||0.3);\n if(a < Math.abs(c+0.1)){\n a=c;s=p/4;\n }else{\n s = p/(2*Math.PI)*Math.asin(c/a);\n } //end if\n return a*Math.pow(2,-10*t)*Math.sin((t*d-s)*(2*Math.PI)/p)+c+b;\n })();\n }else if(type==='ease-out-elastic-strong'){\n result = this.tween(particle,axis,{o: 0.1,type: 'ease-out-elastic'});\n }else if(type==='ease-in-out-elastic-weak'){\n result = this.tween(particle,axis,{o: 0.5,type: 'ease-in-out-elastic'});\n }else if(type==='ease-in-out-elastic'){\n result = (()=>{\n var s=1.70158,p=0,a=c;\n\n if(t===0) return b;\n if((t/=d/2)===2) return b+c;\n if(!p) p=d*((o||0.3)*1.5);\n if(a < Math.abs(c+0.1)){\n a=c;s=p/4;\n }else{\n s = p/(2*Math.PI)*Math.asin(c/a);\n } //end if\n if(t < 1) return -0.5*(a*Math.pow(2,10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p))+b;\n return a*Math.pow(2,-10*(t-=1))*Math.sin((t*d-s)*(2*Math.PI)/p)*0.5+c+b;\n })();\n }else if(type==='ease-in-out-elastic-strong'){\n result = this.tween(particle,axis,{o: 0.1,type: 'ease-in-out-elastic'});\n }else if(type==='ease-in-back-weak'){\n result = this.tween(particle,axis,{o: 1.30158,type: 'ease-in-back'});\n }else if(type==='ease-in-back'){\n let s = o||1.70158;\n\n result = c*(t/=d)*t*((s+1)*t-s)+b;\n }else if(type==='ease-in-back-strong'){\n result = this.tween(particle,axis,{o: 2.40158,type: 'ease-in-back'});\n }else if(type==='ease-out-back-weak'){\n result = this.tween(particle,axis,{o:1.30158,type: 'ease-out-back'});\n }else if(type==='ease-out-back'){\n let s = o||1.70158;\n\n result = c*((t=t/d-1)*t*((s+1)*t+s)+1)+b;\n }else if(type==='ease-out-back-strong'){\n result = this.tween(particle,axis,{o:2.40158,type: 'ease-out-back'});\n }else if(type==='ease-in-out-back-weak'){\n result = this.tween(particle,axis,{o:1.30158,type: 'ease-in-out-back'});\n }else if(type==='ease-in-out-back'){\n let s = o||1.70158;\n\n if((t/=d/2)<1){\n result = c/2*(t*t*(((s*=(1.525))+1)*t-s))+b;\n }else{\n result = c/2*((t-=2)*t*(((s*=(1.525))+1)*t+s)+2)+b;\n } //end if\n }else if(type==='ease-in-out-back-strong'){\n result = this.tween(particle,axis,{o:2.40158,type: 'ease-in-out-back'});\n }else if(type==='ease-in-bounce'){\n result = c-this.tween(particle,axis,{t:d-t,b:0,c,d,type:'ease-out-bounce'})+b;\n }else if(type==='ease-out-bounce'){\n if ((t/=d) < (1/2.75)) {\n result = c*(7.5625*t*t) + b;\n } else if (t < (2/2.75)) {\n result = c*(7.5625*(t-=(1.5/2.75))*t+0.75)+b;\n } else if (t < (2.5/2.75)) {\n result = c*(7.5625*(t-=(2.25/2.75))*t+0.9375)+b;\n } else {\n result = c*(7.5625*(t-=(2.625/2.75))*t+0.984375)+b;\n } //end if\n }else if(type==='ease-in-out-bounce'){\n if(t<d/2){\n result = this.tween(particle,axis,{t:t*2,b:0,c,d,type:'ease-in-bounce'})*0.5+b;\n }else{\n result = this.tween(particle,axis,{t:t*2-d,b:0,c,d,type:'ease-out-bounce'})*0.5+c*0.5+b;\n } //end if\n }else{ //linear catch-all\n result = c*t/d+b;\n }//end if\n return result;\n }",
"function setupTween()\n{\n\t// \n\tvar update\t= function(){\n\t\tcube.position.x = current.x;\n\t}\n\tvar current\t= { x: -userOpts.range };\n\n\t// remove previous tweens if needed\n\tTWEEN.removeAll();\n\t\n\t// convert the string from dat-gui into tween.js functions \n\tvar easing\t= TWEEN.Easing[userOpts.easing.split('.')[0]][userOpts.easing.split('.')[1]];\n\t// build the tween to go ahead\n\tvar tweenHead\t= new TWEEN.Tween(current)\n\t\t.to({x: +userOpts.range}, userOpts.duration)\n\t\t.delay(userOpts.delay)\n\t\t.easing(easing)\n\t\t.onUpdate(update);\n\t// build the tween to go backward\n\tvar tweenBack\t= new TWEEN.Tween(current)\n\t\t.to({x: -userOpts.range}, userOpts.duration)\n\t\t.delay(userOpts.delay)\n\t\t.easing(easing)\n\t\t.onUpdate(update);\n\n\t// after tweenHead do tweenBack\n\ttweenHead.chain(tweenBack);\n\t// after tweenBack do tweenHead, so it is cycling\n\ttweenBack.chain(tweenHead);\n\n\t// start the first\n\ttweenHead.start();\n}",
"setupTween() {\n this.tween = this.getInitialTweenInstance(this.wall.position);\n this.tween.onStart(() => {\n this.onStart();\n if (this.debug) {\n console.log('Animation start');\n console.log(this.tween);\n }\n if (this.wall.position.distanceTo(this.tween._valuesEnd) > 0) {\n this.playAudio();\n }\n });\n this.tween.onComplete(() => this.onComplete());\n }",
"createTweens() {\n this.pinkTween = this.tweens.add({\n targets: this.pink,\n x: { from: game.config.width, to: -this.pink.width},\n ease: 'Sine.easeInOut',\n duration: 750,\n repeat: 1,\n onRepeat: function() {\n this.pinkTween.duration -= 250;\n },\n onRepeatScope: this,\n onComplete: function() {\n this.pinkMiddleStopTween.play();\n },\n onCompleteScope: this\n });\n this.pinkMiddleStopTween = this.tweens.add({\n targets: this.pink,\n x: { from: game.config.width, to: (game.config.width / 2) - this.pink.width},\n ease: 'Quint.easeOut',\n duration: 1500,\n paused: true\n });\n this.purpleTween = this.tweens.add({\n targets: this.purple,\n x: { from: game.config.width, to: -this.purple.width},\n ease: 'Sine.easeInOut',\n duration: 1000,\n repeat: 1,\n onRepeat: function() {\n this.pinkTween.duration -= 250;\n },\n onRepeatScope: this,\n onComplete: function() {\n this.purpleMiddleStopTween.play();\n },\n onCompleteScope: this\n });\n this.purpleMiddleStopTween = this.tweens.add({\n targets: this.purple,\n x: { from: game.config.width, to: (game.config.width / 2)},\n ease: 'Quint.easeOut',\n duration: 2000,\n paused: true,\n onComplete: function() {\n this.titleTween.play();\n this.titleNameTween.play();\n this.throneTween.play();\n },\n onCompleteScope: this\n });\n this.titleTween = this.tweens.add({\n targets: this.turnip_title,\n alpha: {from: 0, to: 1},\n y: {from: this.turnip_title.y, to: this.turnip_title.y + 20},\n ease: 'Quad.easeInOut',\n duration: 2000,\n paused: true,\n });\n this.titleNameTween = this.tweens.add({\n targets: this.birth_of_a_made_man,\n alpha: {from: 0, to: 1},\n y: {from: this.birth_of_a_made_man.y, to: this.birth_of_a_made_man.y + 20},\n ease: 'Quad.easeInOut',\n duration: 2000,\n paused: true,\n });\n this.throneTween = this.tweens.add({\n targets: this.turnip_throne,\n alpha: {from: 0, to: 1},\n y: {from: game.config.height + this.turnip_throne.height, to: 290},\n ease: 'Cubic.easeOut',\n duration: 3000,\n paused: true,\n onComplete: function() { \n //NOTE: phaser doesn't like calling several tweens at once\n //before I tried to tween their current values which make things jittery\n //using compile time calculable values helped solve this issue.\n this.throneLeftTween.play();\n this.titleLeftTween.play();\n this.titleNameLeftTween.play();\n this.pinkLeftTween.play();\n this.purpleLeftTween.play();\n },\n onCompleteScope: this\n });\n this.throneLeftTween = this.tweens.add({\n targets: this.turnip_throne,\n x: { from: this.turnip_throne.x, to: 180},\n ease: 'Sine.easeInOut',\n duration: 1250,\n paused: true,\n });\n this.titleLeftTween = this.tweens.add({\n targets: this.turnip_title,\n x: { from: this.turnip_title.x, to: 64},\n ease: 'Sine.easeInOut',\n duration: 1250,\n paused: true,\n });\n this.titleNameLeftTween = this.tweens.add({\n targets: this.birth_of_a_made_man,\n x: { from: this.birth_of_a_made_man.x, to: 420},\n ease: 'Sine.easeInOut',\n duration: 1250,\n paused: true,\n });\n this.pinkLeftTween = this.tweens.add({\n targets: this.pink,\n x: { from: (game.config.width / 2) - this.pink.width, to: 0},\n ease: 'Sine.easeInOut',\n duration: 1250,\n paused: true,\n });\n this.purpleLeftTween = this.tweens.add({\n targets: this.purple,\n x: { from: (game.config.width / 2), to: this.purple.width},\n ease: 'Sine.easeInOut',\n duration: 1250,\n paused: true,\n onComplete: function() {\n this.aGameByTween.play();\n },\n onCompleteScope: this\n });\n this.aGameByTween = this.tweens.add({\n targets: this.a_game_by,\n alpha: {from: 0, to: 1},\n y: {from: this.a_game_by.y, to: this.a_game_by.y + 20},\n ease: 'Sine.easeInOut',\n duration: 1500,\n paused: true,\n onComplete: function() {\n this.alexTween.play();\n },\n onCompleteScope: this\n });\n this.alexTween = this.tweens.add({\n targets: this.alex_robert,\n alpha: {from: 0, to: 1},\n ease: 'Sine.easeInOut',\n duration: 500,\n paused: true,\n onComplete: function() {\n this.fionaTween.play();\n },\n onCompleteScope: this\n });\n this.fionaTween = this.tweens.add({\n targets: this.fiona_hsu,\n alpha: {from: 0, to: 1},\n ease: 'Sine.easeInOut',\n duration: 500,\n paused: true,\n onComplete: function() {\n this.theaTween.play();\n },\n onCompleteScope: this\n });\n this.theaTween = this.tweens.add({\n targets: this.thea_gamez,\n alpha: {from: 0, to: 1},\n ease: 'Sine.easeInOut',\n duration: 500,\n paused: true,\n onComplete: function() {\n this.startTween.play();\n this.instructionsTween.play();\n this.creditsTween.play();\n },\n onCompleteScope: this\n });\n this.startTween = this.tweens.add({\n targets: this.buttonStart,\n x: {from: game.config.width + this.buttonStart.width, to: game.config.width - this.buttonStart.width},\n ease: 'Sine.easeOut',\n duration: 500,\n paused: true,\n });\n this.instructionsTween = this.tweens.add({\n targets: this.buttonInstructions,\n x: {from: game.config.width + this.buttonInstructions.width, to: game.config.width - this.buttonInstructions.width},\n ease: 'Sine.easeOut',\n duration: 500,\n paused: true,\n });\n this.creditsTween = this.tweens.add({\n targets: this.buttonCredits,\n x: {from: game.config.width + this.buttonCredits.width, to: game.config.width - this.buttonCredits.width},\n ease: 'Sine.easeOut',\n duration: 500,\n paused: true,\n onComplete: function() {\n this.initializeButtons();\n },\n onCompleteScope: this\n });\n //wow that was a lot of tweens!\n }",
"function Animator()\n\t{\n\t}",
"function introAnimation(){\n introTL\n .fromTo(heroImage, {opacity: 0, x: 20, y: -10, scale: 1.4}, {duration: 1, x: 0, y: 0, ease: Power4.easeInOut, opacity:1, scale: 1.3})\n .to(day, .9, {ease: Power4.easeInOut, y: 0}, \"sync-=.9\")\n .to(group1, .9, {y: -15, ease: Power4.easeInOut}, \"sync-=.9\")\n .to(menu, .9, {x: 0, ease: Power4.easeInOut}, \"sync-=.9\")\n .fromTo(credit, .9, {opacity: 0, x: 10}, {opacity: 1, x: 0, ease: Power4.easeInOut, onComplete: addEventListeners}, \"sync-=.8\")\n}",
"function customTween() {\r\n\t\treturn 0.5;\r\n\t}",
"function mainDemo() {\n \t// DEMO SCHEDULE:\n \t//\n \t// This a large JSON array of the form:\n \t// var schedule = [\n \t//\t\t{ trackPos: [module track position], patternPos: [module pattern position], \n \t//\t\t\tlayers: { effect1: [...], effect2: [...]\n \t//\t\t}, \n \t//\n \t//\t\t[...]\n \t// ];\n \t//\n \t// This allows us to turn on and off demo parts according to whether they \"fit\" the song at \n \t// the time. Note that the pattern position is actually the pattern position multipled by the\n \t// number of \"ticks\" per position. In the case of this demo, the module timing is 4 ticks, so\n \t// pattern position 64 is actually 64*4 = 256.\n \t// \n \t// Note that you only need to specify the demo layer that you want to show. We'll be going into\n \t// more detail about how those layers can be specified in the code for each of those demo layers.\n \t//\n \t// This schedule idea was really useful in making it easy to move demo parts around, and sync them\n \t// with the music, so it might end up in TSDADS (The Senior Dads Advanced Demo System) in some form\n \t// in the future.\n \t\n \t// First a couple of demo layers, we'll be using a number of times in the schedule.\n \tvar titleDefLayers = { \t\t\t// Scroller, starfield, colour, disty Dad, and \"'DEF\" logo\n \t\t\tscroller: true, \n\t \t \tstarfield: true,\n\t \t \ttitle:\t { def: true, demo: false },\n\t \t \tdisty: { animate: true },\n\t \t \tcolourBar: { top: true, bottom: true }\n\t \t};\n \tvar titleDemoLayers = { \t\t// Scroller, starfield, colour, disty Dad, and \"'DEMO\" logo\n \t\t\tscroller: true, \n\t \t \tstarfield: true,\n\t \t \ttitle:\t { def: false, demo: true },\n\t \t \tdisty: { animate: true },\n\t \t \tcolourBar: { top: true, bottom: true }\n\t \t};\n \tvar dadCubeLayers = { \t\t// Scroller, starfield, colour, non-disty Dad, and DadCube flying around\n \t\t\tscroller: true, \n\t \t \tstarfield: true,\n\t \t \tdisty: { animate: false },\n\t \t \tcolourBar: { top: true, bottom: true },\n\t \t \tcube:\t { hold: false }\n\t };\n \tvar dadCubeTrumpLayers = { \t\t// wobbly \"Trump Hot Air Ballon\" and scroller\n\t \t\tbackdrop: { name: \"trump\", wobble: true, animate: false },\n\t \t\tscroller: true\n\t };\n \tvar dadCubeHoldLayers = { \t// Scroller, starfield, colour, non-disty Dad, and DadCube stopping in mid air\n\t \t\tscroller: true,\n\t \t \tstarfield: true,\n\t \t \tdisty: { animate: false },\n\t \t \tcolourBar: { top: true, bottom: true },\n\t \t \tcube:\t { hold: { on: true, rot: false, bye: false } }\n\t };\n \tvar dadCubeHoldRotLayers = { \t// Scroller, starfield, colour, non-disty Dad, and DadCube wibbling about in fixed position\n\t \t\tscroller: true,\n\t \t \tstarfield: true,\n\t \t \tdisty: { animate: false },\n\t \t \tcolourBar: { top: true, bottom: true },\n\t \t \tcube:\t { hold: { on: true, rot: true, bye: false } }\n\t };\n \tvar endDefLayers = { \t\t\t// Scroller, diskfield, bottom beer rasters, non-disty Dad, and \"'DEF\" logo\n\t\t\t\tscroller:\t{ back: 1 }, \t\t\t\t\t// As the scroller was previously using background no. 7, this causes the scroller background to scroll through all the previous backgrounds!\n\t \t\tdisty:\t \t{ animate: false },\n\t \t \tbackGrad: \t{ top: false, bottom: true },\n\t \t \ttitle:\t \t{ def: true, demo: false },\n\t \t \tdiskfield: \ttrue\n \t};\n \tvar endDemoLayers = { \t\t// Scroller, diskfield, bottom beer rasters, non-disty Dad, and \"DEMO\" logo\n\t \t\tscroller: true,\n\t \t\tdisty:\t \t{ animate: false },\n\t \t \tbackGrad: \t{ top: false, bottom: true },\n\t \t \ttitle:\t \t{ def: false, demo: true },\n\t \t \tdiskfield: \ttrue\n \t};\n \tvar endSpriteDefLayers = { \t// Atari sprites, scroller, diskfield, bottom beer rasters, non-disty Dad, and \"'DEF\" logo\n\t \t\tscroller: true,\n\t \t\tdisty:\t \t{ animate: false },\n\t \t \tbackGrad: \t{ top: false, bottom: true },\n\t \t \ttitle:\t \t{ def: true, demo: false },\n\t \t \tsprites: \t{ bob: atariBob },\n\t \t \tdiskfield: \ttrue\n \t};\n \tvar endSpriteDemoLayers = { // Atari sprites, scroller, diskfield, bottom beer rasters, non-disty Dad, and \"DEMO\" logo\n\t \t\tscroller: true,\n\t \t\tdisty:\t \t{ animate: false },\n\t \t \tbackGrad: \t{ top: false, bottom: true },\n\t \t \ttitle:\t \t{ def: false, demo: true },\n\t \t \tsprites: \t{ bob: atariBob },\n\t \t \tdiskfield: \ttrue\n \t};\n \t\n \t// Now the actual main schedule. Here we go...\n \tvar schedule = [\n \t \t { trackPos: 0, patternPos: 0, layers: \t\t\t\t\t// As with the old Senior Dads Atari demos, it begins with the fanfare, and presents screen...\n \t \t \t{ \n \t \t \t \tpresents: true,\n \t \t \t \tloop: false\n \t \t \t} \n \t \t },\n \t \t { trackPos: 1, patternPos: 0, layers: \t\t\t\t\t// But what's this? A logo's just plopped on screen!\n\t\t \t \t{ \n\t\t \t \t\tpresents: true, \n\t\t \t \t \tlogo: { animate: false, wobble: false },\n \t \t \t \tloop: false\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 2, patternPos: 0, layers: \t\t\t\t\t// And now it's wobbling about!!!\n\t\t \t \t{ \n\t\t \t \t\tpresents: true, \n\t\t \t \t \tlogo: { animate: false, wobble: true }\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 3, patternPos: 0, layers: \t\t\t\t\t// Now it's bouncing up and down!\n\t\t \t \t{ \n\t\t \t \t\tpresents: true, \n\t\t \t \t \tlogo: { animate: true, wobble: true }\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 3, patternPos: 64, layers: \t\t\t\t\t// Now a wibbly scroller in funny colours has started to appear!\n\t\t \t \t{ \n\t\t \t \t\tpresents: true, \n\t \t \t\t\tscroller: { back: 1 }, \t\t\t\t\t\t// (The scroller's set to it's inital background of a gradient.)\n\t\t \t \t \tlogo: { animate: true, wobble: true }\n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 5, patternPos: 224, layers: \t\t\t\t// First appearance of the disty Dad, but the other logo's covering it's face!\n\t\t \t \t{ \n\t \t \t\t\tscroller: true, \n\t\t \t \t \tdisty: { animate: false },\n\t\t \t \t \tlogo: { animate: false, wobble: true }\n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 7, patternPos: 0, layers: titleDefLayers }, \t// Now the title screen. 'DEF...\n \t \t { trackPos: 7, patternPos: 32, layers: titleDemoLayers }, \t\t// DEMO...\n \t \t { trackPos: 7, patternPos: 64, layers: titleDefLayers }, \t\t// 'DEF...\n \t \t { trackPos: 7, patternPos: 96, layers: titleDemoLayers }, \t\t// DEMO...\n \t \t { trackPos: 7, patternPos: 128, layers: titleDefLayers }, \n \t \t { trackPos: 7, patternPos: 160, layers: titleDemoLayers }, \t\t// ... etc\n \t \t { trackPos: 7, patternPos: 192, layers: titleDefLayers }, \n \t \t { trackPos: 7, patternPos: 224, layers: titleDemoLayers }, \n \t \t { trackPos: 8, patternPos: 0, layers: titleDefLayers }, \n \t \t { trackPos: 8, patternPos: 32, layers: titleDemoLayers }, \t\t// Now you see why we defined these layers earlier!\n \t \t { trackPos: 8, patternPos: 64, layers: titleDefLayers }, \n \t \t { trackPos: 8, patternPos: 96, layers: titleDemoLayers }, \n \t \t { trackPos: 8, patternPos: 128, layers: titleDefLayers }, \n \t \t { trackPos: 8, patternPos: 160, layers: titleDemoLayers }, \n \t \t { trackPos: 8, patternPos: 192, layers: titleDefLayers }, \n \t \t { trackPos: 8, patternPos: 224, layers: titleDemoLayers },\n \t \t { trackPos: 9, patternPos: 0, layers: \t\t\t\t\t\t\t// Brief shot of both 'DEF and DEMO visible.\n\t\t \t \t{ \n \t \t\t\t\t\tscroller: { back: 2 }, \t\t\t\t\t\t\t\t// (Scroller set to go to new gradient background)\n\t\t \t \t \ttitle:\t { def: true, demo: true },\n\t\t \t \t \tdisty: { animate: false }\n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 10, patternPos: 0, layers: \t\t\t\t\t\t\t// COPPER PIPES!!!\n\t\t \t \t{ \n\t\t \t \t\tbackdrop: { name: \"netbest_back\", wobble: true, animate: true },\t// Fling up the \"NetBest\" background\n\t \t \t\t\tscroller: true, \n\t\t \t \t \tlogo: { animate: true, wobble: true },\t\t\t\t\t\t\t// Bounce the logo up and down\n\t\t \t \t \trasterBar: { wobble: true }\t\t\t\t\t\t\t\t\t\t\t// Copper pipes in the background\n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 12, patternPos: 0, layers: \t\t\t\t\t\t// DRUNKEN DAD!!!\n\t\t \t \t{ \n\t \t\t\t\t\t\tscroller: { back: 3 }, \t\t\t\t\t\t\t\t// Scroller goes to green (Groo!!) background\n\t\t \t \t \tbackGrad: { top: true, bottom: true },\t\t\t\t\t// switch on both halves of beer raster background\n\t\t \t \t \tdisty: { animate: true },\t\t\t\t\t\t\t// Disty Dad for drunken look!!\n\t\t \t \t \tdiskfield: true\t\t\t\t\t\t\t\t\t\t\t// Switch on diskfield. His mind is full of code as he staggers home from the pub!!!\n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 16, patternPos: 32, layers: \t\t\t\t\t\t// Quick pause for breath...\n\t\t \t \t{ \n \t\t\t\t\t\t\tscroller: { back: 4 }, \t\t\t\t\t\t\t\t// Cue up next scroller background.\n\t\t \t \t\tloop: false\n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 17, patternPos: 0, layers: \t\t\t\t\t\t\t// PHASE FOUR STEREO!!!\n\t\t \t \t{ \n\t\t \t \t\tbackdrop: { name: \"sad_back\", wobble: true, animate: true },\t// Fling up SD Website Background.\n\t\t \t \t\tsprites: true, \t\t\t\t\t\t\t\t\t\t\t\t// Switch on sprites, which as set to \"Phase 4 Stereo\" bobs.\n\t \t \t\t\tscroller: true, \n\t\t \t \t \tlogo: { animate: true, wobble: true }\t\t\t\t\t\t// Bounces goes the logo!\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 21, patternPos: 0, layers: \t\t\t\t\t\t// Another slight pause, before we go to...\n\t\t \t \t{ \n\t\t \t \t\tbackdrop: { name: \"sad_back\", wobble: false, animate: false },\t\n\t\t \t \t\tsprites: true, \n \t\t\t\t\t\t\tscroller: { back: 5 }, \t\t\t\t\t\t\t\t// (Cue up next scroller background.)\n\t\t \t \t \tlogo: { animate: false, wobble: false }\t\t\t// (Logo goes back up top and freezes)\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 22, patternPos: 0, layers: dadCubeLayers},\t\t// WE 'TRUMP' IN 3D!!!!!!! A 3d Dad-Mapped cube flying about a starfield!!!\n\t\t \t { trackPos: 22, patternPos: 48, layers: dadCubeTrumpLayers},\t// (BURP!)\n\t\t \t { trackPos: 22, patternPos: 64, layers: dadCubeLayers},\n\t\t \t { trackPos: 22, patternPos: 112, layers: dadCubeTrumpLayers},\t// (BURP!)\n\t\t \t { trackPos: 22, patternPos: 128, layers: dadCubeLayers},\n\t\t \t { trackPos: 22, patternPos: 208, layers: dadCubeHoldLayers},\t// 'I'm calling fo-o-o-o-o-o...' The cube suddenly stops and wobbles!!!\n\t\t \t { trackPos: 23, patternPos: 0, layers: dadCubeLayers},\t\t\t// And the cube is off again...\n\t\t \t { trackPos: 23, patternPos: 48, layers: dadCubeTrumpLayers},\t// (BURP!)\n\t\t \t { trackPos: 23, patternPos: 64, layers: dadCubeLayers},\n\t\t \t { trackPos: 23, patternPos: 112, layers: dadCubeTrumpLayers},\t// (BURP!)\n\t\t \t { trackPos: 23, patternPos: 128, layers: dadCubeLayers},\n\t\t \t { trackPos: 23, patternPos: 208, layers: dadCubeHoldLayers},\t// 'I'm calling fo-o-o-o-o-o...' The cube's stopped again!!!!\n\t\t \t { trackPos: 24, patternPos: 0, layers: dadCubeHoldRotLayers},\t// ...o-o-o-o-o-o-o-o-o-o-o...' Now it cube's spinning like a madman!!!\n\t\t \t { trackPos: 24, patternPos: 128, layers: \t\t\t\t\t\t// And it's tumbling away! Goodbye, cube!\n\t\t \t \t{ \n \t \t\t\t\tscroller: { back: 6 }, \t\t\t\t\t\t\t\t// (Set up next scroller background. It's actually the Trump Picture from the last section!!)\n\t\t\t \t \t \tcolourBar: { top: true, bottom: true },\n\t\t\t \t \t \tdiskfield: false,\n\t\t\t \t \t \tcube:\t { hold: { on: true, rot: true, bye: true } }\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 25, patternPos: 0, layers: \t\t\t\t\t\t\t// BURPY COPPER BARS!!!\n\t\t \t \t{ \n\t\t\t \t \t\tcoppers: true,\n \t \t\t\t\tscroller: true, \n\t\t\t \t \t \tlogo: { animate: true, wobble: true },\t\t\t\t// Bouncing logo is back!\n\t\t\t \t \t \tcolourBar: { top: true, bottom: true }\t\t\t\t\t// The colour bars remain from the previous section\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 27, patternPos: 0, layers: \t\t\t\t\t\t// But that's not all.. VECTOR DISKS as well!\n\t\t \t \t{ \n\t\t\t \t \t\tcoppers: true,\n\t\t\t \t \t\tscroller: true, \n\t\t\t \t \t \tlogo: { animate: true, wobble: true },\n\t\t\t \t \t \tcolourBar: { top: true, bottom: true },\n\t\t \t \t \tvectaDisk: true\t\t\t\t\t\t\t\t\t\t\t// Just start them off with the normal rotation\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 30, patternPos: 0, layers: \t\t\t\t\t\t// Hang on, they're starting to look agitated!\n\t\t \t \t{ \n\t\t\t \t \t\tcoppers: true,\n\t\t\t \t \t\tscroller: true, \n\t\t\t \t \t \tlogo: { animate: true, wobble: true },\n\t\t\t \t \t \tcolourBar: { top: true, bottom: true },\n\t\t \t \t \tvectaDisk: { wibble: true }\t\t\t\t\t\t\t\t// Turn on \"agitated\" wobble\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 32, patternPos: 0, layers: \t\t\t\t\t\t// Back to the cube, but with a different background.\n\t\t \t \t{ \n \t \t\t\t\t\tscroller: { back: 7 }, \t\t\t\t\t\t\t\t\t\t\t// Use the \"Presents\" background for the scroller background here\n\t\t \t \t\tbackdrop: { name: \"ptrail_bkg\", wobble: true, animate: true },\t\t// Fling up \"Press Trail\" background.\n\t\t\t \t \t\tcube: \t \ttrue\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 33, patternPos: 0, layers: \t\t\t\t\t\t// Wait a sec, a (non-disty) Dad has appeared!\n\t\t \t \t{ \n\t\t\t \t \t\tscroller: \ttrue, \n\t\t \t \t\tbackdrop: \t{ name: \"ptrail_bkg\", wobble: true, animate: true },\n\t\t \t \t\tdisty:\t\t{ animate: false },\n\t\t\t \t \t\tcube: \t \ttrue\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 34, patternPos: 0, layers: \t\t\t\t\t\t// Oh, it's gone away again!\n\t\t \t \t{ \n\t\t\t \t \t\tscroller: \ttrue, \n\t\t \t \t\tbackdrop: \t{ name: \"ptrail_bkg\", wobble: true, animate: true },\n\t\t\t \t \t\tcube: \t \ttrue\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 35, patternPos: 0, layers: \t\t\t\t\t\t// Now, it's back again, only with the 3D diskfield and top half of the beer rasters\n\t\t \t \t{ \n\t \t\t\t\t\t\tscroller:\ttrue, \n\t\t \t \t\tbackdrop: \t{ name: \"ptrail_bkg\", wobble: true, animate: true },\n\t\t \t \t\tdisty:\t \t{ animate: false },\n\t\t \t \t \tbackGrad: \t{ top: true, bottom: false },\n\t\t \t \t \tdiskfield: \ttrue,\n\t\t\t \t \t\tcube: \t \ttrue\n\t\t \t \t} \n\t\t \t },\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Back to the 'Def demo titles, only with the diskfield and (bottom half) beer rasters.\n\t\t \t { trackPos: 36, patternPos: 0, layers: endDefLayers },\t\t// 'DEF...\n\t\t \t { trackPos: 36, patternPos: 64, layers: endDemoLayers },\t// 'DEMO..\n\t\t \t { trackPos: 36, patternPos: 128, layers: endDefLayers },\t// 'DEF...\n\t\t \t { trackPos: 36, patternPos: 192, layers: endDemoLayers },\t// 'DEMO..\n\t\t \t { trackPos: 37, patternPos: 0, layers: endDefLayers },\n\t\t \t { trackPos: 37, patternPos: 64, layers: endDemoLayers },\t// .. etc. ...\n\t\t \t { trackPos: 37, patternPos: 128, layers: endDefLayers },\n\t\t \t { trackPos: 37, patternPos: 192, layers: endDemoLayers },\n\t\t \t { trackPos: 38, patternPos: 0, layers: endSpriteDefLayers },\t// Now, we're adding the \"Atari\" sprites!\n\t\t \t { trackPos: 38, patternPos: 64, layers: endSpriteDemoLayers },\n\t\t \t { trackPos: 38, patternPos: 128, layers: endSpriteDefLayers },\n\t\t \t { trackPos: 38, patternPos: 192, layers: endSpriteDemoLayers },\n\t\t \t { trackPos: 39, patternPos: 0, layers: endSpriteDefLayers },\n\t\t \t { trackPos: 39, patternPos: 64, layers: endSpriteDemoLayers },\n\t\t \t { trackPos: 39, patternPos: 128, layers: endSpriteDefLayers },\n\t\t \t { trackPos: 39, patternPos: 192, layers: endSpriteDemoLayers },\n\t\t \t { trackPos: 40, patternPos: 0, layers: \t\t\t\t\t// Take out the diskfield and 'DEF/DEMO, and replace with the vector disks\n\t\t \t \t{ \n\t \t\t\t\t\t\tscroller: { back: 7 }, \t\t\t\t\t\t\t// Go to \"Presents\" background. Background was previously no. 1, so this scrolls through all the backgrounds again! \n\t\t\t \t \t\tdisty:\t \t{ animate: false },\n\t\t\t \t \t \tbackGrad: \t{ top: false, bottom: true },\n\t\t\t \t \t \tsprite: \t{ bob: atariBob },\n\t\t\t \t \t \tvectaDisk: true\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 40, patternPos: 240, layers: \t\t\t\t// Fling up \"Presents\" background, which slightly mis-matches with scroller background!\n\t\t \t \t{ \n\t\t\t \t \t\tscroller: \ttrue, \n\t\t \t \t\tbackdrop: \t{ name: \"presents\", wobble: false, animate: true },\n\t\t\t \t \t \tsprite: \t{ bob: atariBob },\n\t\t \t \t \tlogo: \t{ animate: true, wobble: true },\n\t\t\t \t \t \tvectaDisk: true\n\t\t \t \t} \n\t\t \t },\n\t\t \t { trackPos: 41, patternPos: 0, layers: \t\t\t\t\t// Just leave the frozen logo, and frozen (mismatched) scroller\n\t\t \t \t{ \n\t\t \t \t\t\tscroller: \ttrue, \n\t\t \t \t\tpresents: true, \n\t\t \t \t \tlogo: { animate: false, wobble: false },\n\t\t \t \t \tloop: false \n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 42, patternPos: 0, layers: \t\t\t\t\t// Now, take everything away apart from the \"Presents\" screen. Now we're back at the start!\n\t\t \t \t{ \n\t\t \t \t\tpresents: \ttrue, \n\t\t \t \t\tloop: \tfalse \n\t\t \t \t} \n\t\t \t },\n \t \t { trackPos: 42, patternPos: 128, layers: \t\t\t\t// Whilst we're waiting for the music to restart, bring up the \"Any Key\" button.\n\t\t \t \t{ \n \t \t \t\tspacebar: \ttrue,\n\t\t \t \t\tpresents: \ttrue, \n\t\t \t \t\tloop: \ttrue \n\t\t \t \t} \n\t\t \t }\n \t];\n\n \t// MAIN DEMO INITIALISATION\n \tvar loopOn = true;\t\t\t\t\t\t\t\t// If true, the animation loop is on.\n \tvar logoY = 50;\t\t\t\t\t\t\t\t\t// Y-pos of wobbly logo\n \tvar logoPos = 1.8;\t\t\t\t\t\t\t\t// Sinewave position of wobbly logo\n \tvar backDropY = 405;\t\t\t\t\t\t\t// Current y-pos of backdrop\n \tvar backdropCleared = true;\t\t\t\t\t\t// True if we don't need to clear the backdrop canvas before drawing\n \tvar copperY = 0;\t\t\t\t\t\t\t\t// y-pos of \"burpy\" copper source\n \tvar currentScrollBackPos = 10;\t\t\t\t\t// Base y-position of scroller background\n \tvar nextScrollBackPos = currentScrollBackPos;\t// Next y-position of scroller background\n \tvar colourBarSpeed = 2;\t\t\t\t\t\t\t// Speed of movement of top and bottom colour bars\n \tvar colourbarXTop = 0;\t\t\t\t\t\t\t// X-position of colour bar soure for top colour bar\n \tvar colourbarXBottom = 0;\t\t\t\t\t\t// X-position of colour bar soure for bottom colour bar\n \tvar rasterBar1Y = 100; \t\t\t\t\t\t\t// Y-pos of copper pipes\n \tvar rasterBar2Y = rasterBar1Y;\n \tvar rasterBar3Y = rasterBar1Y;\n \tvar rasterBarSpacing = 0.60;\t\t\t\t\t// Spacing between copper pipes\n \tvar rasterBarSpeed = 0.050;\t\t\t\t\t\t// Speed of copper pipes movement\n \tvar rasterBar1Pos = 1.8;\t\t\t\t\t\t\t\t// Inital sinewave pos of copper pipes\n \tvar rasterBar2Pos = rasterBar1Pos + rasterBarSpacing;\n \tvar rasterBar3Pos = rasterBar2Pos + rasterBarSpacing;\n \tvar dadCubeX = 0;\t\t\t\t\t\t\t\t\t\t// Inital coordinates of DadCube\n \tvar dadCubeY = 0;\n \tvar dadCubeRotX = 0;\t\t\t\t\t\t\t\t\t// Inital rotation of DadCube\n \tvar dadCubeRotY = 0;\n \tvar dadCubeRotZ = 0;\n \tvar vectorDiskSX = vectorDiskS.group.position.x;\t\t// Inital coordinates of vector disks (We're not going to be fiddling with the z-coords in this case.)\n \tvar vectorDiskSY = vectorDiskS.group.position.y;\n \tvar vectorDiskDX = vectorDiskD.group.position.x;\n \tvar vectorDiskDY = vectorDiskD.group.position.y;\n \tvar vectorDiskSRotX = 0;\t\t\t\t\t\t\t\t// Inital rotation of vector disks\n \tvar vectorDiskSRotY = 0;\n \tvar vectorDiskSRotZ = 0;\n \tvar vectorDiskDRotX = 0;\n \tvar vectorDiskDRotY = 0;\n \tvar vectorDiskDRotZ = 0;\n \tvar currentBob = phase4bob;\t\t\t\t\t\t\t\t// Set the current bob for the Sprites screen\n \tvar spacebarOpactity = 0;\t\t\t\t\t\t\t\t// Opacity of the \"Any Key\" button. (We've set it to clear.)\n \t\n \t// OK, LET'S GO!!!!!!!!!!\n \tmusic_Sashy.play();\t\t\t\t\t\t\t// Start the music playing\n \tcurrentPart = schedule[currentPos].layers;\t// Get the inital demo part\n \tscheduleNextPart();\t\t\t\t\t\t\t// Schedule the next part \t\n \twindow.onkeypress = mainDemoAbort;\t\t\t// Set the \"any key\" to go to the end of this part, and then onto the credits screen\n \tdemo_loop();\t\t\t\t\t\t\t\t// Now start the demo loop!\n \t\n \t// MAIN DEMO LOOP\n \t//\n \t// This simply goes through all the effects layers, and checks if needs to continue. \n \t// If it does, this function will be called again in the next frame.\n function demo_loop(){\n \tdraw_mainScreen();\n \tdraw_presentsScreen();\n \tdraw_backDrop();\n \tdraw_coppers();\n \tdraw_sprites();\n \tdraw_backGradient();\n \tdraw_starfield();\n \tdraw_title();\n \tdraw_diskField();\n \tdraw_vectorDisks();\n \tdraw_distyDad();\n \t\tdraw_logo();\n \t\tdraw_rasterBar();\n \t\tdraw_dadCube();\n \t\tdraw_colourBar();\n \tdraw_scroller();\n \tdisplay_spacebar();\n \tif (DEBUG) updatestats();\t\t\t\t// If we're in debug mode, show the stats.\n \tcheckContinue();\t\t\t\t\t\t// If we're continuing, this will call the demo loop in the next frame.\n }\n \n // DEMO SCHEDULING\n //\n // This pops off the track and pattern positions for the next part, and uses it to set the next\n // part to occur when the music reaches that point. (The Senior Dads Music player class allows\n // to set a \"breakpoint\" so that a function is executed when a tracker module gets to a certain position.)\n function scheduleNextPart() {\n \tif ((currentPos+1) < schedule.length) {\t\t\t\t// If we're not at the end of schedule...\n\t \tSeniorDads.Music.SetBreakPoint(\t\t\t\t\t\t// Set the next part to execute at the next music breakpoint.\n\t \t\t\tschedule[currentPos+1].trackPos, \n\t \t\t\tschedule[currentPos+1].patternPos, \n\t \t\t\tdoNextPart\n\t \t);\n\t \tif (DEBUG) \t\t\t// If we're debugging, display when the next part is going to happen.\n\t\t \tdocument.getElementById('scheduleInfo').innerHTML = \"<br/><br/>Playing schedule part \" + currentPos + \" of \" + schedule.length +\n\t \t\t\". Next part will be played at module position track \" + SeniorDads.Music.BreakPoint_Track +\", position \" + SeniorDads.Music.BreakPoint_Pattern + \n\t \t\t\". \";\n \t}\n \telse {\t\t// If we're at the end of the schedule, reset schedule/\n \t\tif (DEBUG) document.getElementById('scheduleInfo').innerHTML = \"<br/><br/>End of schedule. Resetting. \";\t// If we're debugging, display that we're at the end of schedule\n \t\tresetContent();\t\t\t\t\t\t// Reset any content that needs reset\n\t\t\t\tcurrentPos = 0;\t\t\t\t\t\t// Reset schedule pointer\n\t \tSeniorDads.Music.SetBreakPoint(\t\t// And get ready to start the demo again as soon as the music re-starts\n\t\t \t\t\tschedule[currentPos+1].trackPos, \n\t\t \t\t\tschedule[currentPos+1].patternPos, \n\t\t \t\t\tdoNextPart\n\t\t \t);\n \t}\n }\n \n // This is call when the music breakpoint (Set the by the scheduler above) is reached.\n function doNextPart() {\n\t\t\tcurrentPos++;\t\t\t\t\t\t\t\t// Move schedule pointer onto next part of the schedule\n\t\t\tcurrentPart = schedule[currentPos].layers;\t// Set the current demo layers from the schedule\n\t\t\tif (currentPos == schedule.length) \t\t\t// If we're at the end of the schedule, reset pointer\n\t\t\t\tcurrentPos = 0;\n\t\t\tscheduleNextPart();\t\t\t\t\t\t\t// Schedule the next demo part\n \tif (!loopOn) requestAnimFrame( demo_loop );\t// If the demo loop was turned off, start it again.\n }\n \n // This checks if the demo loop is to continue, by checking the demo layers from the schedule.\n // In some parts of the schedule, we turn it off (eg for the \"freeze-frame\" bits.)\n //\n // LAYER OPTIONS:\n //\t\tloop: true/false (default is true)\n function checkContinue() {\n \t\tloopOn = defaultTrue( currentPart.loop );\n \tif ( loopOn ) requestAnimFrame( demo_loop );\n }\n\n // Reset any content that needs to be reset. (Mainly the scroller)\n function resetContent() {\n \tscrollLine.scroffset = 0;\n \tscrollOffScreen.clear();\n \tscrollScreen.clear();\n \tcurrentScrollBackPos = 10;\n }\n\n // DEMO LAYERS ===========================================================================================\n \n // MAIN SCREEN\n //\n // Basically clears the main screen canvas. Exciting, huh!\n //\n // LAYER OPTIONS:\n //\t\tmain: true/false (default is true)\n function draw_mainScreen() {\n \tif ( defaultTrue( currentPart.main ) )\t\t// If we're showing the main screen\n \t\t{\n\t \t\tmainScreen.clear(); \t\t\t\t\t// ... clear it.\n\t \t\tmainScreen.show();\n \t\t} \n \telse\n \t\tmainScreen.hide();\t\t\t\t\t\t// Otherwise, hide it.\n }\n \n // \"SENIOR DADS PRESENT\" SCREEN\n //\n // Show or hide \"Presents\" screen.\n //\n // LAYER OPTIONS:\n //\t\tpresents: true/false (default is false)\n function draw_presentsScreen() {\n \tif ( defaultFalse( currentPart.presents ) ) \t\n \t\tpresentsScreen.show();\n \telse \n \t\tpresentsScreen.hide();\n }\n \n // WIBBLY BACKDROP\n //\n // LAYER OPTIONS:\n //\t\tbackdrop: { \n //\t\t\tname: \"[name of image in backdrop hash array]\" , \n //\t\t\tanimate :true/false (default is false),\t\t\t\t<- Whether to fling in the image from the bottom of the screen or not\n //\t\t\twobble :true/false (default is false)\t\t\t\t<- Whether to do the wobble or not\n //\t\t}\n function draw_backDrop() {\n // Main backdrop code now moved outside, as it's also being used in the credits screen as well.\n \tvar backDropChanges = backDrop( currentPart.backdrop, backDropY, backdropCleared );\n \tbackDropY = backDropChanges.backDropY;\n \tbackdropCleared = backDropChanges.backdropCleared;\n }\n \n // \"BURPY\" COPPERS\n //\n // LAYER OPTIONS:\n //\t\tcoppers: true/false (default is false)\n function draw_coppers() {\n \tif ( defaultFalse( currentPart.coppers ) ) {\n \t// We're copying the copper source, from the current source y-pos, 20 times down the screen. \n \t// As we go down the screen, we're also increasing the y-pos, so as to give a \"Venetian blind\" effect!\n \tvar copperStart=0;\t\t\t\t\t\t\t\t\t\t\t\t// Venetian blind index!\n \tfor( var copperCopy = 0; copperCopy < 20; copperCopy++ ) {\t\n \t\tcopperStart++;\t\t\t\t\t\t\t\t\t\t\t\t// Start opening the Venetian blinds!!\n \t\tif ( copperStart > 10 ) copperStart++;\t\t\t\t\t\t// From half way down, open the Venetian blinds a bit more!\n \t\t// Copy from the copper source, and stretch across the width of the screen.\n \t\tcopperSource.drawPart( copperScreen, 0, copperCopy * 20, 0, copperStart + copperY, 1 , 20, 1, 0, 640, 1 );\n \t}\n \tcopperScreen.show();\n\t \tcopperY++;\t\t\t\t// Move onto next base position for the next frame\n\t \tif (copperY > 400)\t\t// If we're at the end\n\t \t\tcopperY = 0;\t\t// ... Reset the y-pos of the copper source\n \t}\n \telse {\n \t\tcopperY = 0;\n \tcopperScreen.hide();\n \t}\n }\n\n \n // BEER RASTERS\n //\n // LAYER OPTIONS:\n //\t\tbackGrad: { \n //\t\t\ttop :true/false (default is false),\t\t\t\t<- Show top half of beer rasters\n //\t\t\tbottom :true/false (default is false)\t\t\t<- Show bottom half of beer rasters\n //\t\t}\n function draw_backGradient() {\n\t\t\tbackGradientTopScreen.hide();\t\t\t\t\t\t\t\t\t// Hide both halves by default\n\t\t\tbackGradientBottomScreen.hide();\n \tif ( defaultFalse( currentPart.backGrad ) ) {\t\t\t\t\t// However, if they're specified in the schedule.\n \t\t// ... Show the canvases according to whether top and/or bottom is specified. (Easy, huh!)\n \t\t\tif ( defaultFalse( currentPart.backGrad.top ) ) backGradientTopScreen.show();\t\t\t\t\n \t\t\tif ( defaultFalse( currentPart.backGrad.bottom ) ) backGradientBottomScreen.show();\n \t}\n }\n \n // 2D STARFIELD\n //\n // LAYER OPTIONS:\n //\t\tstarfield: true/false (default is false)\n function draw_starfield() {\n \tif ( defaultFalse( currentPart.starfield ) ) SDStarfield.draw();\t// That was easy!\n }\n \n // 'DEF DEMO TITLE\n //\n // LAYER OPTIONS:\n //\t\ttitle: { \n //\t\t\tdef :true/false (default is false),\t\t\t<- Show \"'Def\" title\n //\t\t\tdemo :true/false (default is false)\t\t\t<- Show \"'Demo\" title\n //\t\t}\n function draw_title() {\n \ttitleDefScreen.hide();\t\t\t\t\t\t\t\t\t// Hide both title by default\n \ttitleDemoScreen.hide();\n \tif ( defaultFalse( currentPart.title ) ) {\t\t\t\t// Similar to the Beer Rasters- if we have something in the schedule...\n \t\t// ... Show the canvases according to whether \"def\" and/or \"demo\" is specified.\n \t\tif ( currentPart.title.def ) titleDefScreen.show();\n\t \t\tif ( currentPart.title.demo ) titleDemoScreen.show();\n \t}\n }\n \n // DISTY DAD\n //\n // Well, it *can* be disty, if you want.\n //\n // LAYER OPTIONS:\n //\t\tdisty: true \t\t\t\t\t\t\t\t\t<- Show disty Dad *without* the dist!\n //\t\tdisty: { \n //\t\t\tanimate :true/false (default is false)\t\t<- Turn dist on or off\n //\t\t}\n function draw_distyDad() {\n \tif ( defaultFalse( currentPart.disty ) )\t\t\t// If we've turned the Dads on...\n \t\tif ( currentPart.disty.animate )\t\t\t\t\t\t\t\t\t// If we're animating...\n \t\t\tSDDistyDadFX.sinx( 320 - (SDDistyDad.img.width / 2), 20);\t\t\t// Draw the disty version\n \t\telse\n \t\t\tSDDistyDad.draw(mainScreen, 320 - (SDDistyDad.img.width / 2), 20);\t// Otherwise, draw the static version\n }\n \n // WOBBLY LOGO\n //\n // LAYER OPTIONS:\n //\t\tlogo: true \t\t\t\t\t\t\t\t\t\t<- Show static logo at top of screen\n //\t\tlogo: { \n //\t\t\tanimate :true/false (default is false),\t\t\t\t<- Whether to bounce logo up and down or not\n //\t\t\twobble :true/false (default is false)\t\t\t\t<- Whether to do the wobble or not\n //\t\t}\n function draw_logo() {\n \tif ( defaultFalse( currentPart.logo ) )\t\t\t\t// If we're doing the logo...\n \t\t{\n \t\tvar logoX = 320 - (SDLogo.img.width /2);\t\t\t// Logo is in centre of screen\n \t\tif ( currentPart.logo.animate ) {\t\t\t\t\t// If it's bouncing...\n \t\t\tlogoY = 280 - Math.abs(Math.sin(logoPos) * 260);\t// ... Get latest position of bounce\n \t\t\tlogoPos += 0.025;\t\t\t\t\t\t\t\t\t// ... Set next position of bounce\n \t\t}\n \t\telse {\t\t\t\t\t\t\t\t\t\t\t\t// If it's static...\n \t \tlogoY = 20;\t\t\t\t\t\t\t\t\t\t\t// ... Put at top of screen\n \t \tlogoPos = 1.8;\t\t\t\t\t\t\t\t\t\t// ... and reset the bounce position\n \t\t}\n \t\tif ( currentPart.logo.wobble )\t\t\t\t\t\t// If it's wobbling...\n \t\t{\n \t\t\tlogoX += SDLogoWobbler.h();\t\t\t\t\t\t\t// ... Add the wobble differentials to the X,Y Coords\n \t\t\tlogoY += SDLogoWobbler.v();\n \t\t}\n \t\tSDLogoScreen.draw(mainScreen,logoX,logoY);\t\t\t// Now draw the logo on the screen at the coordinates calculated.\n \t\t}\n \telse \n \t\tSDLogoScreen.hide();\t\t\t\t\t\t\t// If we're not doing the logo, just hide it.\n }\n \n // 3D DISKFIELD\n //\n // This is unusual in that there's hardly any CODEF in it! We're calculating the 3D ourselves. \n // This function is partially based on a 3D spritefield routine by Mellow Man.\n //\n // LAYER OPTIONS:\n //\t\tdiskfield: true/false (default is false)\n function draw_diskField() {\n \tif ( defaultFalse( currentPart.diskfield ) ) {\n \t var halfWidth = 640 / 2;\t\t\t\t\t\t// Vanishing point in the centre of the screen\n \t var halfHeight = 480 / 2;\n \t var length = diskFieldCoordinates.length;\n \t \n \t for( var i = 0; i < length; i++ ) {\n \t \tdiskFieldCoordinates[i].z -= 0.2;\t\t\t\t\t// Move each disk a little towards the viewer\n \t \n \t \tif( diskFieldCoordinates[i].z <= 0 ) {\t\t\t\t// If it's past the viewer, generate a new random coordinate at the back\n \t \t\tdiskFieldCoordinates[i].x = random(-25,25);\n \t \t\tdiskFieldCoordinates[i].y = random(-25,25);\n \t \t\tdiskFieldCoordinates[i].z = maxDiskfieldDepth;\n \t \t}\n \t \n \t \t// Now convert the 3D coords to 2D\n \t \tvar k = 128 / diskFieldCoordinates[i].z;\t\t\t\t// Scale for 3D x,y coords accoring to z coordinate\n \t \tvar x = diskFieldCoordinates[i].x * k + halfWidth;\t\t// Scale 3D x-coord in relation to vanishing point to make Make 2D x-coord \n \t \tvar y = diskFieldCoordinates[i].y * k + halfHeight;\t\t// Scale 3D y-coord in relation to vanishing point to make Make 2D y-coord \n \t \n \t \t// If the coordinate are within the bounds of the screen, we can draw the disk\n \t \tif( x >= 0 && x <= 640 && y >= 0 && y <= 480 ) {\t\t\t\t\t\t\n \t \t\tvar size = ((1 - diskFieldCoordinates[i].z / 32.0)*5)/8;\t\t\t\t\t// Work out the image scale according to the z-coord.\n \t \t\tvar shade = (parseInt((1 - diskFieldCoordinates[i].z / 32.0)*255))/255;\t\t// Work out the image shade according to the z-coord.\n \t \t\tdiskbobScreen.draw( mainScreen, x, y, shade, 0, size, size );\t\t\t\t// Now we can put the scaled shaded image on the screen\n \t \t}\n \t }\n \t}\n }\n \n // VECTOR DISKS\n //\n // LAYER OPTIONS:\n //\t\tvectaDisk: true/false (default is false)\t\t\t\t<- \"Standard\" vectordisks\n //\t\tvectaDisk: { \n //\t\t\twibble :true/false (default is false)\t\t\t\t<- \"Agitated\" vectordisks\n //\t\t}\n function draw_vectorDisks() {\n \tif ( defaultFalse( currentPart.vectaDisk ) ) {\t\t\t// If vector disks are on...\n \t\tif ( defaultFalse( currentPart.vectaDisk.wibble ) ) {\t// If they're \"agitated\"...\n \t\t\t// Do tweening to \"base\" position if needed\n \t\t\tvectorDiskSRotX = tweenTo( vectorDiskSRotX );\t\t\t\n \t\t\tvectorDiskSRotY = tweenTo( vectorDiskSRotY );\n \t\t\tvectorDiskSRotZ = tweenTo( vectorDiskSRotZ );\n \t\t\tvectorDiskDRotX = tweenTo( vectorDiskDRotX );\n \t\t\tvectorDiskDRotY = tweenTo( vectorDiskDRotY );\n \t\t\tvectorDiskDRotZ = tweenTo( vectorDiskDRotZ );\n \t\t\t// Now apply \"agitated\" \"wibble\" to their rotation!\n\t \t\tvectorDiskS.group.rotation.x = vectorDiskSRotX + vectorDiskSWibble.h();;\n\t \t\tvectorDiskS.group.rotation.y = vectorDiskSRotY + vectorDiskSWibble.v();;\n\t \t\tvectorDiskS.group.rotation.z = vectorDiskSRotZ + vectorDiskSWibble.z();;\n\t \t\tvectorDiskD.group.rotation.x = vectorDiskDRotX + vectorDiskDWibble.h();;\n\t \t\tvectorDiskD.group.rotation.y = vectorDiskDRotY + vectorDiskDWibble.v();;\n\t \t\tvectorDiskD.group.rotation.z = vectorDiskDRotZ + vectorDiskDWibble.z();;\n \t\t}\n \t\telse {\t\t\t\t\t// If they're not \"agitated\", just apply normal uniform rotation to them\n\t \t\tvectorDiskS.group.rotation.x+=0.01;\t\n\t \t\tvectorDiskS.group.rotation.y+=0.02;\n\t \t\tvectorDiskS.group.rotation.z+=0.04;\n\t \t\tvectorDiskD.group.rotation.x-=0.01;\t\t\t\t// The D rotates in the opposite direction to the S\n\t \t\tvectorDiskD.group.rotation.y-=0.02;\n\t \t\tvectorDiskD.group.rotation.z-=0.04;\n\t \tvectorDiskSRotX = vectorDiskS.group.rotation.x;\t// Save the rotation (Sor when the \"tween\" is used.)\n\t \tvectorDiskSRotY = vectorDiskS.group.rotation.y;\n\t \tvectorDiskSRotZ = vectorDiskS.group.rotation.z;\n\t \tvectorDiskDRotX = vectorDiskD.group.rotation.x;\n\t \tvectorDiskDRotY = vectorDiskD.group.rotation.y;\n\t \tvectorDiskDRotZ = vectorDiskD.group.rotation.z;\n\t \t}\n \t\t// Now, wobble their x,y coordinates\n \t\tvectorDiskS.group.position.x = vectorDiskSX + vectorDiskSWobble.h();\n \t\tvectorDiskS.group.position.y = vectorDiskSY + vectorDiskSWobble.v();\n \t\tvectorDiskS.draw();\n \t\tvectorDiskD.group.position.x = vectorDiskDX + vectorDiskDWobble.h();\n \t\tvectorDiskD.group.position.y = vectorDiskDY + vectorDiskDWobble.v();\n \t\tvectorDiskD.draw();\n \t}\n \t\n \t// \"Tween\" for vector disks. This used when going into \"agitated\" mode, so \n \t// that the vector objects drift back to their \"base\" position (ie unrotated) \n \t// whilst wibbling!\n \tfunction tweenTo( value ) {\n \t\tvar speed = 0.04;\n \t\tif ( value < 0 )\n \t\t\tvalue += speed;\n \t\tif ( value > 0 )\n \t\t\tvalue -= speed;\n \t\treturn value;\n \t}\n \t\n }\n \n // COLOUR BARS\n //\n // LAYER OPTIONS:\n //\t\tcolourBar: { \n //\t\t\ttop :true/false (default is false),\t\t\t\t\t<- Top colour bar on/off\n //\t\t\tbottom :true/false (default is false)\t\t\t\t<- Bottom colour bar on/off\n //\t\t}\n function draw_colourBar() {\n \tif ( defaultFalse( currentPart.colourBar ) ) {\n\t \tif ( currentPart.colourBar.top ) {\t\t\t\t\t// If we're drawing the top bar\n\t \t\tcolourBar.draw(mainScreen, colourbarXTop, 11);\t\t// Copy it from it's current source position\n\t \t\tcolourbarXTop += colourBarSpeed;\t\t\t\t\t// ... and move it along a bit.\n\t \t\tif (colourbarXTop>=0) \t\t\t\t\t\t\t\t// If it's at the wrap point...\n\t \t\t\tcolourbarXTop=-640;\t\t\t\t\t\t\t\t// ... reset it\n\t \t}\n\t \tif ( currentPart.colourBar.bottom ) {\t\t\t\t// If we're drawing the bottom bar\n\t \t\tcolourBar.draw(mainScreen, colourbarXBottom, 391);\t// Copy it from it's current source position\n\t \t\tcolourbarXBottom-=colourBarSpeed;\t\t\t\t\t// ... and move it along a bit. (Opposite direction to top bar)\n\t \t\tif (colourbarXBottom<=-640)\t\t\t\t\t\t\t// If it's at the wrap point...\n\t \t\t\tcolourbarXBottom=0;\t\t\t\t\t\t\t\t// ... reset it\n\t \t}\n \t}\n }\n \n // COPPER PIPES\n //\n // LAYER OPTIONS:\n //\t\trasterBar: true/false (default is false)\n function draw_rasterBar() {\n \tif ( defaultFalse( currentPart.rasterBar ) ) {\t\t\t// If we're showing the copper pipes...\n \t\trasterBar1Screen.show();\n \t\trasterBar2Screen.show();\n \t\trasterBar3Screen.show();\n \t\trasterBar1Y = 330 - Math.abs(Math.sin(rasterBar1Pos) * 200);\t// Calculate their y-pos in the sinewave\n \t\trasterBar2Y = 330 - Math.abs(Math.sin(rasterBar2Pos) * 200);\n \t\trasterBar3Y = 330 - Math.abs(Math.sin(rasterBar3Pos) * 200);\n \t\tif ( currentPart.rasterBar.wobble ) {\t\t\t\t\t\t\t// If we're wobbling....\n \t\t\trasterBar1Y += rasterWobbler1.h();\t\t\t\t\t\t\t// ... Add in the wobble\n \t\t\trasterBar2Y += rasterWobbler2.h();\n \t\t\trasterBar3Y += rasterWobbler3.h();\n \t\t}\n \t\trasterBar1Pos += rasterBarSpeed;\t\t\t\t\t\t// Move sinewave along a bit for next frame\n \t\trasterBar2Pos += rasterBarSpeed;\n \t\trasterBar3Pos += rasterBarSpeed;\n \t\trasterBar1Screen.y = rasterBar1Y;\t\t\t\t\t\t// Now position the pipes!\n \t\trasterBar2Screen.y = rasterBar2Y;\n \t\trasterBar3Screen.y = rasterBar3Y;\n \t\t}\n \telse {\n \t\trasterBar1Screen.hide();\n \t\trasterBar2Screen.hide();\n \t\trasterBar3Screen.hide();\n \t}\n }\n \n // BIG SPRITES\n //\n // Pretty easy this- just get the x,y coords from each sprite's wave/wobble, and plot them.\n //\n // LAYER OPTIONS:\n //\t\tsprites: true/false (default is false)\n //\t\tsprites: {\n //\t\t\tbob: [Codef image of spriter bob you want to use]\n //\t\t}\n function draw_sprites() {\n \tif ( defaultFalse( currentPart.sprites ) ) {\t\t\t// If we're drawing the sprites...\n \t\tif ( defaultFalse( currentPart.sprites.bob ) ) \t\t\t// If we're changing the sprite bob\n \t\t\tif (currentBob != currentPart.sprites.bob )\t\t\t// ... Check that it's different\n \t\t\t\tcurrentBob = currentPart.sprites.bob;\t\t\t// ... Then change it\n \t\tfor (var i=0; i < noOfSprites; i++) {\n \t\t\tvar x = spriteWobblers[i].h() + ( ( 640 - currentBob.img.width ) / 2); \t// Work out position of wave/wobble in relation to the centre of the screen and bob\n \t\t\tvar y = spriteWobblers[i].v() + ( ( 400 - currentBob.img.height ) / 2); \n \t\t\tcurrentBob.draw(mainScreen, x, y);\t\t\t\t\t\t\t\t\t\t\t// Now draw it.\n \t\t}\n \t}\n }\n \n // DADCUBE\n //\n // LAYER OPTIONS:\n //\t\tcube: true/false (default is false)\t\t\t\t\t<- Standard flying around and wobbling\n //\t\tcube: {\n //\t\t\thold: true/false (default is false)\t\t\t\t<- Hold and wobble\n //\t\t}\n //\t\tcube: {\n //\t\t\thold: {\n //\t\t\t\trot: true/false (default is false),\t\t\t<- Hold and madman rotation!\n //\t\t\t\tbye: true/false (default is false)\t\t\t<- Madman rotation tumbling away!\n //\t\t\t}\n //\t\t}\n function draw_dadCube() {\n \tif ( defaultFalse( currentPart.cube ) ) {\t\t\t// If we're doing the cube\n \t\tif ( defaultFalse( currentPart.cube.hold ) ) {\t\t// If we're doing the hold...\n \t\t\tif (dadCubeX == 0) {\t\t\t\t\t\t\t\t// If this is the start of the hold...\n \t\t\t\tdadCubeX = dadCube3D.group.position.x;\t\t\t\t// ... Save the x,y coords \n \t\t\t\tdadCubeY = dadCube3D.group.position.y;\n \t\t\t\tdadCubeRotX = dadCube3D.group.rotation.x;\t\t\t// ... and the rotation\n \t\t\t\tdadCubeRotY = dadCube3D.group.rotation.y;\n \t\t\t\tdadCubeRotZ = dadCube3D.group.rotation.z;\n \t\t\t}\n \t\t\tif ( currentPart.cube.hold.rot ) {\t\t\t\t\t\t// If it's the mad rotation...\n \t\t\t\tdadCube3D.group.rotation.x = dadCubeRotX + dadCubeHoldRotWobble.h();\t// ... set the rotation via the wobbler\n \t\t\t\tdadCube3D.group.rotation.y = dadCubeRotY + dadCubeHoldRotWobble.v();\n \t\t\t\tdadCube3D.group.rotation.z = dadCubeRotZ + dadCubeHoldRotWobble.z();\n \t\t\t}\n \t\t\tif ( currentPart.cube.hold.bye ) {\t\t\t\t\t\t// If it's going away...\n \t\t\t\tdadCube3D.group.position.x -= 10 + dadCubeHoldWobble.h();\t\t// ... Have it sailing away towards the bottom right\n \t\t\t\tdadCube3D.group.position.y -= 10 + dadCubeHoldWobble.v();\n \t\t\t\tdadCube3D.group.position.z -= 20;\n \t\t\t}\n \t\t\telse {\t\t\t\t\t\t\t\t\t\t\t\t\t// Otherwise the standard hold is just to wobble the x,y coords\n \t\tdadCube3D.group.position.x = dadCubeX + dadCubeHoldWobble.h();\n \t\tdadCube3D.group.position.y = dadCubeY + dadCubeHoldWobble.v();\n \t\t\t}\n \t\t}\n \t\telse {\t\t\t\t\t\t\t\t\t// For normal flying around...\n \t\tdadCube3D.group.rotation.x+=0.01;\t\t// ... Normal uniform rotation\n \t\tdadCube3D.group.rotation.y+=0.02;\n \t\tdadCube3D.group.rotation.z+=0.04;\n\t \t\tdadCube3D.group.position.x = dadCubeMainWobble.h(); // Get next position in wave/wobble of cube \t\t\n\t \t\tdadCube3D.group.position.y = dadCubeMainWobble.v(); \t\t\n\t \t\tdadCube3D.group.position.z = dadCubeMainWobble.z(); \t\t\n\t \tdadCubeX = 0;\n\t \tdadCubeY = 0;\n \t\t}\n \t\t// Now that all the rotation and position has been set, we can draw the cube!\n \t\tdadCube3D.draw();\n \t}\n }\n \n // CHROMAKEY DISTYSCROLL\n //\n // This projects a background through a disty scroller. You can change the backgrounds, and it'll scroll\n // through all the backgrounds till it gets to the right one. The background also wobbles.\n //\n // This is definately the slowest part of the main demo, given that it does:\n // a) a scroller\n // b) dist on the scroller\n // c) a composite copy of the background on top of the dist\n // d) after all that, *then* it draws to the screen!\n // So there's probably a way to do it quicker!\n //\n // LAYER OPTIONS:\n //\t\tscroller: true/false (default is false)\t\t\t\t\t\t\t<- Run scroller with current background\n //\t\tscroller: {\n //\t\t\tback: [Number of background from background list (1-7)]\t\t<- Move to next background\n //\t\t}\n function draw_scroller() {\n \tif ( defaultFalse( currentPart.scroller ) ) {\n\t \tscrollOffScreen.clear();\n\t \tscrollScreen.clear();\n\t \tscrollLine.draw(0);\n\t \tscrollFx.siny(0,55);\n\t \tscrollScreen.contex.globalCompositeOperation='source-atop';\n\t \tscrollBackScreen.drawPart(scrollScreen,0,0,0,currentScrollBackPos+scrollBackWobbler.h(),640,scrollBackSegmentHeight);\n\t \tscrollScreen.draw(mainScreen,0,260);\n\t \tscrollScreen.contex.globalCompositeOperation='source-over';\n\t \tif (defaultFalse( currentPart.scroller.back )) \n\t \t\tnextScrollBackPos = ( ( currentPart.scroller.back - 1 ) * scrollBackSegmentHeight) + 10;\n\t \tif (currentScrollBackPos != nextScrollBackPos) {\n\t \t\tif (currentScrollBackPos < nextScrollBackPos)\n\t \t\t\tcurrentScrollBackPos += 5;\n\t \t\tif (currentScrollBackPos > nextScrollBackPos)\n\t \t\t\tcurrentScrollBackPos -= 5;\n\t \t}\n \t}\n }\n \t\n // The \"ANY KEY\" BUTTON\n //\n // This simply slowly fades on the button. (Which was always there, but was invisible.)\n \tfunction display_spacebar() {\n \t\tif (currentPart.spacebar)\t\t\t\t\t// If we've got the OK to show the button...\n\t \t\tif (spacebarOpactity<1) {\t\t\t\t// ... (Stop doing the fade, if the button is completely visible- opacity = 1)\n\t \tspacebarOpactity += 0.025;\t\t\t// ... Increase the opacity value a little each frame\n\t \tnextButton.style.opacity = spacebarOpactity;\t// ... and use to to fade up the button\n\t \t\t}\n \t}\n \t\n \t// END OF DEMO LAYERS ==========================================================================================\n }",
"function projector() {\nvar tl = new TimelineMax();\ntl.from(\"#supports\", 0.6, {scaleY:0, ease:Expo.easeInOut})\n .add(\"legExtension\")\n .to(\"#rightLeg\", 0.4, {rotation:0, x:0, ease:Power2.easeOut}, \"legExtension\")\n .to(\"#leftLeg\", 0.4, {rotation:0, x:0, ease:Power2.easeOut},\"legExtension\")\n .from(\"#screenBars\",0.6,{scaleX:0, ease:Expo.easeOut}, \"legExtension\")\n .to(\"#centerShadowBottom\",0.3,{autoAlpha:1}, \"legExtension\")\n .add(\"screenDown\",\"-=0.25\")\n .to(\"#screen\", 0.6, {scaleY:1, ease:Power4.easeOut},\"screenDown\")\n .from(\"#screenBottom, #centerShadowBottom\", 0.6, {y:-569, ease:Power4.easeOut},\"screenDown\")\n .to(\"#shadow\", 0.6, {scaleX:1, autoAlpha:.2, ease:Power4.easeOut},\"screenDown\")\n .to(\"#film\", 1.5, {autoAlpha:1});\nreturn tl;\n}",
"function main() {\r\n init();\r\n animate();\r\n}",
"createTweens(message) {\n let scene = this;\n this.tweens.add({\n targets: message,\n alpha: 0,\n duration: 700,\n yoyo: true,\n repeat: 5,\n onStart: () => this.scene.run(this.sceneToStart),\n onComplete: () => scene.scene.pause()\n });\n }",
"function SnowlTarget() {}",
"startTextboxTween(input) {\n\t\tconst { scene } = this;\n\t\tthis.state.blinkTween = scene.tweens.add({\n\t\t\ttargets: input,\n\t\t\tduration: 500,\n\t\t\tdelay: 300,\n\t\t\trepeat: -1,\n\t\t\tease: Phaser.Math.Easing.Expo.InOut,\n\t\t\talpha: 0,\n\t\t\tyoyo: true,\n\t\t});\n\t}",
"createTween() {\n // If more than one object exists on the frame, or if there is only one path, create a clip from those objects\n var numClips = this.clips.length;\n var numPaths = this.paths.length;\n\n if (numClips === 0 && numPaths === 1 || numClips + numPaths > 1) {\n var allObjects = this.paths.concat(this.clips);\n\n var center = this.project.selection.view._getObjectsBounds(allObjects).center;\n\n var clip = new Wick.Clip({\n objects: this.paths.concat(this.clips),\n transformation: new Wick.Transformation({\n x: center.x,\n y: center.y\n })\n });\n this.addClip(clip);\n } // Create the tween (if there's not already a tween at the current playhead position)\n\n\n var playheadPosition = this._getRelativePlayheadPosition();\n\n if (!this.getTweenAtPosition(playheadPosition)) {\n var clip = this.clips[0];\n this.addTween(new Wick.Tween({\n playheadPosition: playheadPosition,\n transformation: clip ? clip.transformation.copy() : new Wick.Transformation()\n }));\n }\n }",
"function lighthouse(){\r\n var $lighthouse = $('.lighthouse');\r\n var height = $lighthouse.height();\r\n var raiseIncrement = 34;\r\n var numIncrements = Math.round(height/raiseIncrement);\r\n var steps = Math.round(numIncrements/3);\r\n\r\n //show the lighthouse\r\n $lighthouse.toggle();\r\n TweenMax.from($lighthouse,2, {top:\"100%\",ease: SteppedEase.config(steps),onComplete:showBeam});\r\n\r\n //Beam is done with CSS tranisition\r\n function showBeam(){\r\n $beam = $(\".lighthouse-beam\");\r\n $beam.addClass('grow-beam');\r\n TweenMax.set($lighthouse,{clearProps: \"top\"});\r\n }\r\n\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an object containing various attributes for a given MIDI number. Throws error for invalid midiNumbers. | function getAttributes(midiNumber) {
var attrs = midiNumberAttributesCache[midiNumber];
if (!attrs) {
throw Error('Invalid MIDI number');
}
return attrs;
} // Returns all MIDI numbers corresponding to natural notes, e.g. C and not C# or Bb. | [
"function getAttributes(midiNumber) {\n const attrs = midiNumberAttributesCache[midiNumber];\n if (!attrs) {\n throw Error('Invalid MIDI number');\n }\n return attrs;\n}",
"midi_to_obj(_midi_data){\n\t\treturn {\n\t\t\ttype: _midi_data[0].toString(16).substr(0, 1).toLowerCase(),\n\t\t\t ch: parseInt(_midi_data[0].toString(16).substr(1, 1)),\n\t\t\t ctl: parseInt(_midi_data[1]),\n\t\t\t val: parseInt(_midi_data[2])\n\t\t};\n\t}",
"static fromMidi(midi) {\n\t\tif (midi < 21 || midi > 108) throw new Error(`invalid midi ${midi}`)\n\n\t\t// List all possible note to simplify the computation to a single modulo.\n\t\tconst names = this.names[(midi - 21) % 12]\n\n\t\t// Use the same method but move the change to the note between B and C\n\t\tconst octave = Math.floor((midi - 12) / 12)\n\n\t\treturn new Note(names[0], octave)\n\t}",
"function getMidi(n){\n\treturn this.v[(n)+this.offset]+(12 * this.octave)+this.key;\n}",
"static MIDIToNoteName(MIDINumber, nameType = 0){\n\t\tvar noteNumber = MIDINumber%12; //Note number in semitones/halfsteps relative to C\n\t\tvar noteName = this.noteNames[noteNumber]; //Mapped note name\n\t\tswitch(nameType){\n\t\t\tcase 1:\n\t\t\tnoteName = this.flippedNoteNames[noteNumber];\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\tnoteName = this.onlyFlatsNoteNames[noteNumber];\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\tnoteName = this.onlySharpsNoteNames[noteNumber];\n\t\t\tbreak;\n\t\t}\n\t\tvar octave = Math.floor(MIDINumber/12)-1;\n\t\treturn {\n\t\t\tnoteName: noteName,\n\t\t\tnoteNumber: noteNumber,\n\t\t\toctave: octave\n\t\t};\n\t}",
"static noteNumberToMIDI(noteNumber, octave = 4){\n\t\tif(noteNumber < 0 || octave < 0){\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\treturn (60 + noteNumber) + ((octave - 4)*12);\n\t}",
"function Note(midiNote) {\n if(midiNote < 0 || midiNote > 127) {\n throw new Error(\"MIDI notes are only defined between 0 and 127\");\n }\n\n this.midiNote = midiNote;\n this.octave = Math.floor(midiNote / 12);\n this.noteIndex = midiNote % 12;\n\n this.getDifferenceToNote = function (note) {\n return this.midiNote - note.midiNote;\n }\n}",
"function parseMidiMessage(message) {\n return {\n command: message.data[0] >> 4,\n channel: message.data[0] & 0xf,\n note: message.data[1],\n velocity: message.data[2] / 127\n }\n}",
"function getMidi(midi) {\n\n //GET CURRENT BPM\n let bpm = midi.header.tempos[0].bpm;\n\n //GET TIMESTEP (IN SECOND) => TO BE USED FOR CONVERTING THE TIME INTO STEPS INSTEAD, e.g. if 1 STEP = 0.2 second; then 5 STEP = 1 second\n let TS = 60 / bpm / STEP_FREQENCY;\n\n //timingObject: KEY-VALUE PAIR (KEY: TIMING, VALUE: NOTES TO PLAY)\n let timingObject = new Object();\n\n //LOOP THROUGH EACH TRACKS/INSTRUMENTS IN THE MIDI FILE\n midi.tracks.forEach((currentTrack, index) => {\n\n //GET ALL THE NOTES ON THE TRACK\n let notes = currentTrack.notes;\n\n //LOOP THROUGH EACH NOTE\n for (let i = 0; i < notes.length; i++) {\n\n //GET NOTE NAME e.g C4\n let note = notes[i].name;\n\n //GET NOTE OCTAVE e.g 4\n let noteOctave = parseInt(note.slice(-1));\n\n //GET NOTE PITCH e.g C\n let pitch = note.slice(0, -1);\n\n //SWITCH ALL SHARP NOTES TO ITS EQUIVALENT NOTES\n switch (pitch) {\n case \"C#\":\n pitch = \"Db\";\n break;\n case \"D#\":\n pitch = \"Eb\";\n break;\n case \"F#\":\n pitch = \"Gb\";\n break;\n case \"G#\":\n pitch = \"Ab\";\n break;\n case \"A#\":\n pitch = \"Bb\";\n break;\n }\n\n //PUT BACK TOGETHER THE NOTE NAME\n note = pitch + noteOctave;\n\n //GET TIMING OF THE NOTE (IN SECOND)\n let noteTimingS = Number(notes[i].time);\n\n //CONVERT THE TIMING INTO TIME STEP (TS) EQUIVALENTS\n //e.g. if 1 TS = 0.2 second; then 5 TS = 1 second\n let noteTimingTS = Math.round(noteTimingS / TS);\n\n //CREATE A NEW ARRAY OF NOTE IF NOTE DOES NOT EXIST IN THE TS\n if (!timingObject[noteTimingTS]) {\n timingObject[noteTimingTS] = [note];\n }\n\n //ELSE PUSH A NEW NOTE\n else {\n timingObject[noteTimingTS].push(note);\n }\n }\n });\n return timingObject;\n}",
"function MidiFile(data) {\n function readChunk(stream) {\n var id = stream.read(4);\n var length = stream.readInt32();\n return {\n 'id': id,\n 'length': length,\n 'data': stream.read(length)\n };\n }\n\n var lastEventTypeByte = void 0;\n\n function readEvent(stream) {\n var event = {};\n event.deltaTime = stream.readletInt();\n var eventTypeByte = stream.readInt8();\n if ((eventTypeByte & 0xf0) == 0xf0) {\n /* system / meta event */\n if (eventTypeByte == 0xff) {\n /* meta event */\n event.type = 'meta';\n var subtypeByte = stream.readInt8();\n var length = stream.readletInt();\n switch (subtypeByte) {\n case 0x00:\n event.subtype = 'sequenceNumber';\n if (length != 2) throw \"Expected length for sequenceNumber event is 2, got \" + length;\n event.number = stream.readInt16();\n return event;\n case 0x01:\n event.subtype = 'text';\n event.text = stream.read(length);\n return event;\n case 0x02:\n event.subtype = 'copyrightNotice';\n event.text = stream.read(length);\n return event;\n case 0x03:\n event.subtype = 'trackName';\n event.text = stream.read(length);\n return event;\n case 0x04:\n event.subtype = 'instrumentName';\n event.text = stream.read(length);\n return event;\n case 0x05:\n event.subtype = 'lyrics';\n event.text = stream.read(length);\n return event;\n case 0x06:\n event.subtype = 'marker';\n event.text = stream.read(length);\n return event;\n case 0x07:\n event.subtype = 'cuePoint';\n event.text = stream.read(length);\n return event;\n case 0x20:\n event.subtype = 'midiChannelPrefix';\n if (length != 1) throw \"Expected length for midiChannelPrefix event is 1, got \" + length;\n event.channel = stream.readInt8();\n return event;\n case 0x2f:\n event.subtype = 'endOfTrack';\n if (length != 0) throw \"Expected length for endOfTrack event is 0, got \" + length;\n return event;\n case 0x51:\n event.subtype = 'setTempo';\n if (length != 3) throw \"Expected length for setTempo event is 3, got \" + length;\n event.microsecondsPerBeat = (stream.readInt8() << 16) + (stream.readInt8() << 8) + stream.readInt8();\n return event;\n case 0x54:\n event.subtype = 'smpteOffset';\n if (length != 5) throw \"Expected length for smpteOffset event is 5, got \" + length;\n var hourByte = stream.readInt8();\n event.frameRate = {\n 0x00: 24,\n 0x20: 25,\n 0x40: 29,\n 0x60: 30\n }[hourByte & 0x60];\n event.hour = hourByte & 0x1f;\n event.min = stream.readInt8();\n event.sec = stream.readInt8();\n event.frame = stream.readInt8();\n event.subframe = stream.readInt8();\n return event;\n case 0x58:\n event.subtype = 'timeSignature';\n if (length != 4) throw \"Expected length for timeSignature event is 4, got \" + length;\n event.numerator = stream.readInt8();\n event.denominator = Math.pow(2, stream.readInt8());\n event.metronome = stream.readInt8();\n event.thirtyseconds = stream.readInt8();\n return event;\n case 0x59:\n event.subtype = 'keySignature';\n if (length != 2) throw \"Expected length for keySignature event is 2, got \" + length;\n event.key = stream.readInt8(true);\n event.scale = stream.readInt8();\n return event;\n case 0x7f:\n event.subtype = 'sequencerSpecific';\n event.data = stream.read(length);\n return event;\n default:\n // console.log(\"Unrecognised meta event subtype: \" + subtypeByte);\n event.subtype = 'unknown';\n event.data = stream.read(length);\n return event;\n }\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf0) {\n event.type = 'sysEx';\n var _length = stream.readletInt();\n event.data = stream.read(_length);\n return event;\n } else if (eventTypeByte == 0xf7) {\n event.type = 'dividedSysEx';\n var _length2 = stream.readletInt();\n event.data = stream.read(_length2);\n return event;\n } else {\n throw \"Unrecognised MIDI event type byte: \" + eventTypeByte;\n }\n } else {\n /* channel event */\n var param1 = void 0;\n if ((eventTypeByte & 0x80) == 0) {\n /* running status - reuse lastEventTypeByte as the event type.\n \teventTypeByte is actually the first parameter\n */\n param1 = eventTypeByte;\n eventTypeByte = lastEventTypeByte;\n } else {\n param1 = stream.readInt8();\n lastEventTypeByte = eventTypeByte;\n }\n var eventType = eventTypeByte >> 4;\n event.channel = eventTypeByte & 0x0f;\n event.type = 'channel';\n switch (eventType) {\n case 0x08:\n event.subtype = 'noteOff';\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n return event;\n case 0x09:\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n if (event.velocity == 0) {\n event.subtype = 'noteOff';\n } else {\n event.subtype = 'noteOn';\n }\n return event;\n case 0x0a:\n event.subtype = 'noteAftertouch';\n event.noteNumber = param1;\n event.amount = stream.readInt8();\n return event;\n case 0x0b:\n event.subtype = 'controller';\n event.controllerType = param1;\n event.value = stream.readInt8();\n return event;\n case 0x0c:\n event.subtype = 'programChange';\n event.programNumber = param1;\n return event;\n case 0x0d:\n event.subtype = 'channelAftertouch';\n event.amount = param1;\n return event;\n case 0x0e:\n event.subtype = 'pitchBend';\n event.value = param1 + (stream.readInt8() << 7);\n return event;\n default:\n throw \"Unrecognised MIDI event type: \" + eventType;\n /* \n console.log(\"Unrecognised MIDI event type: \" + eventType);\n stream.readInt8();\n event.subtype = 'unknown';\n return event;\n */\n }\n }\n }\n\n var stream = new Stream(data);\n var headerChunk = readChunk(stream);\n if (headerChunk.id != 'MThd' || headerChunk.length != 6) {\n throw \"Bad .mid file - header not found\";\n }\n var headerStream = new Stream(headerChunk.data);\n var formatType = headerStream.readInt16();\n var trackCount = headerStream.readInt16();\n var timeDivision = headerStream.readInt16();\n\n if (timeDivision & 0x8000) {\n throw \"Expressing time division in SMTPE frames is not supported yet\";\n }\n var ticksPerBeat = timeDivision;\n\n var header = {\n 'formatType': formatType,\n 'trackCount': trackCount,\n 'ticksPerBeat': ticksPerBeat\n };\n var tracks = [];\n for (var i = 0; i < header.trackCount; i++) {\n tracks[i] = [];\n var trackChunk = readChunk(stream);\n if (trackChunk.id != 'MTrk') {\n throw \"Unexpected chunk - expected MTrk, got \" + trackChunk.id;\n }\n var trackStream = new Stream(trackChunk.data);\n while (!trackStream.eof()) {\n var event = readEvent(trackStream);\n tracks[i].push(event);\n //console.log(event);\n }\n }\n\n return {\n 'header': header,\n 'tracks': tracks\n };\n}",
"function midiToPitchClass(midi) {\n var scaleIndexToNote = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n var note = midi % 12;\n return scaleIndexToNote[note];\n}",
"numToNote() {\n let charPart;\n let octave;\n\n // -1 is a sentinel value for silence which has no char part or octave\n if (this.midiVal === -1) {\n charPart = \"-\";\n octave = \"\";\n } else {\n const letters = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\"];\n charPart = letters[this.midiVal % letters.length];\n octave = this.getOctave(this.midiVal);\n }\n return { charPart, octave };\n }",
"function getNoteInfo(verovioToolkit) {\n\n let mei = getMEI(verovioToolkit.getMEI()),\n meiNotes = Array.from(mei.querySelectorAll('note')),\n notes = [], \n maxPitch = 0, \n minPitch = Number.POSITIVE_INFINITY, \n lastNoteTime = 0;\n\n meiNotes.forEach(meiNote => {\n\n let [dur, id, pitch] = ['dur', 'xml:id', 'pnum'].map(a => meiNote.getAttribute(a)),\n startTime = scaleTime(verovioToolkit.getTimeForElement(id));\n\n if (dur === 'long') dur = 0.5; // If note duration marked 'long', make it 8 beats\n let durTime = beatsToMilliseconds((1 / dur) * 4); // 1/4 note = 1 beat\n\n // Get voice number from staff position\n\n let ancestor = meiNote;\n\n do { \n ancestor = ancestor.parentElement \n } while (ancestor !== null && ancestor.nodeName !== 'staff');\n\n let voiceNumber = (ancestor !== null && ancestor.getAttribute('n') !== null) \n ? Number.parseInt(ancestor.getAttribute('n')) \n : 0; // If not specified, put into voice 0\n\n notes.push({ \n dur: durTime, \n id: id, \n pitch: pitch, \n startTime: startTime, \n voiceNumber: voiceNumber \n });\n\n maxPitch = (maxPitch < pitch) ? pitch : maxPitch;\n minPitch = (minPitch > pitch) ? pitch : minPitch;\n lastNoteTime = (lastNoteTime < startTime) ? startTime : lastNoteTime;\n });\n\n return {\n notes: notes,\n maxPitch: maxPitch,\n minPitch: minPitch,\n lastNoteTime: lastNoteTime\n }\n }",
"function getMIDIMessage(message) {\n \n var command = message.data[0];\n var note = message.data[1];\n var velocity = (message.data.length > 2) ? message.data[2] : 0; // a velocity value might not be included with a noteOff command\n \n switch (command) {\n case 144: // note on\n if (velocity > 0) {\n noteOn(note);\n } else {\n noteOff(note);\n }\n break;\n case 128:\n default:\n break;\n // we could easily expand this switch statement to cover other types of commands such as controllers or sysex\n }\n }",
"static smoIntToPitch(intValue) {\n let octave = 0;\n let accidental = '';\n let noteKey = null;\n const letterInt = intValue >= 0 ? intValue % 12 :\n 12 - (Math.abs(intValue) % 12);\n noteKey = (Object.keys(SmoMusic.noteValues).find((key) => SmoMusic.noteValues[key].int_val === letterInt && key.length === 1));\n if (!noteKey) {\n noteKey = (Object.keys(SmoMusic.noteValues).find((key) => SmoMusic.noteValues[key].int_val === letterInt && key.length === 2));\n }\n octave = Math.floor(intValue / 12);\n octave = octave >= 0 ? octave : 0;\n accidental = noteKey.substring(1, noteKey.length);\n // eslint-disable-next-line\n accidental = accidental ? accidental : 'n';\n return {\n letter: noteKey[0],\n accidental,\n octave\n };\n }",
"midi() {\n\t\treturn (\n\t\t\t// Change of octave happens between B and C, shift 9 semitones to reflect\n\t\t\t// that.\n\t\t\t((this.index + 9) % 12) +\n\t\t\t// Add the octave value\n\t\t\t12 * (this.octave + 1)\n\t\t)\n\t}",
"function parseMidiFile(midiFile) {\n var midiTime = 0;\n var notes = [];\n\n // For each MIDI event in first track\n // \n $.each(midiFile.tracks[0], function(index, midiEvent) {\n midiTime += midiEvent.deltaTime;\n\n // Check for noteOns\n // \n if (midiEvent.subtype == \"noteOn\") {\n notes.push({\n midiTime: midiTime,\n midiPitch: midiEvent.noteNumber\n });\n }\n });\n\n return notes;\n }",
"function getMIDIMessage(message) {\n let command = message.data[0];\n let note = message.data[1];\n let velocity = (message.data.length > 2) ? message.data[2] : 0; // a velocity value might not be included with a noteOff command\n// console.log('message=', message);\n\n// console.log('note =', note, 'command=', command);\n\n// clear Channel-Nr information \ncommand = command >> 4;\ncommand = command << 4;\n\n// console.log('command=', command);\n switch (command) {\n case 144: // note on\n if (velocity > 0) {\n // console.log('testcom=', testcom);\n noteOn(note);\n } else {\n // ;\n }\n break;\n case 128: // note off\n // noteOffCallback(note);\n break;\n // we could easily expand this switch statement to cover other types of commands such as controllers or sysex\n }\n}",
"function MusicItem() {\n\tthis.m_type = \"note\";\n\tthis.m_pname = C_PitchClass;\n\tthis.m_accid = 0;\n\tthis.m_oct = 4;\n\tthis.m_rhythm = 1;\n\tthis.m_dot = false;\n\tthis.m_line = -1;\n\tthis.m_text = \"\";\n\tthis.m_clefLine = 3;\n\n\treturn this;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fonction du choix des pages et d'affichage du top recent | function pageTop(item, offset, limit){
$.ajax({
method: "POST",
url: "functions/display-top-recent.php",
data: { id: 315, offset: offset, limit: limit }
})
.done(function( html ) {
$("#top-recent").html(html);
});
} | [
"function loadRecent() {\n if (paginationOptions.pageFirst > 0) {\n paginationOptions.pageFirst = 0;\n }\n viewsOptions.page = paginationOptions.pageFirst;\n\n return retreiveArticles(viewsOptions);\n }",
"function fetchRecent() {\n addAbout() \n fetchProjects(numRecentResponses, addProjectsToPage);\n if (includeBlogPosts) {\n fetchPosts(numRecentResponses, addPostsToPage);\n }\n}",
"function lastPage() {\n currentPage = numberOfPages;\n loadList();\n}",
"function filter_recent_pages()\n{\n var matches = null, v=0,\n url = window.location.href,\n $Obj = $('a:contains(Add page)'); // inject the filter next to this link.\n\n // validate environment.\n if ( $Obj.length && (matches = url.match( /\\/pages\\/?(p[0-9]+)?$/ )) )\n {\n var style = \"position: fixed; z-index: 10000001; padding: 20px; border: 1px solid #797979; \"\n +\"background-color: antiquewhite; cursor: move; border-radius: 3px; box-shadow: 3px 3px 10px -5px #200000;\";\n\n // take the link as positioning orientation.\n v = $Obj.position().left + $Obj.width() + 20;\n v = isNaN(v) ? 500 : v;\n style += \" left: \"+ v +\"px;\";\n\n v = $Obj.position().top - 15;\n v = isNaN(v) ? 200 : v;\n style += \" top: \"+ v +\"px;\";\n\n $Obj.after(\n '<fieldset class=\"wooden_drag\" style=\"'+ style +'\">'\n + '<select id=\"wooden_rp_filter\" size=\"1\" style=\"cursor: default;\"></select>'\n +'</fieldset>'\n );\n\n $Obj = $('#wooden_rp_filter');\n if ( $Obj.length ) // safety precaution\n {\n // get the categories that are present in the current recent Pages.\n // (Avoid duplicates).\n var Options = [], i, Out = \"\";\n $('.blockpage p:last-child').each(function(){\n var cat = $(this).text();\n if ( $.inArray( cat, Options ) == -1 ) {\n Options.push(cat);\n }\n });\n\n if ( opopSortFilters ) {\n Options.sort();\n }\n\n // display.\n Out = \"<option value='0'>Filter …</option>\";\n for ( i = 0; i < Options.length; i++ )\n Out += \"<option>\"+ Options[i] +\"</option>\";\n $Obj.html(Out);\n\n // make it work! (Add functionality afterwards).\n $Obj.change(function(){\n // reset\n if ( $(this).val() === \"0\" )\n reset_rp_filter();\n\n // highlight\n else\n {\n $('#wooden_rp_filter option:first:contains(Filter)').text(\"[RESET]\");\n\n var Category = $('#wooden_rp_filter :selected').text();\n if ( Category == \"\" ) // safety precaution\n alert(\"[Woodrow] Invalid category.\");\n\n else\n {\n // first hide everything …\n $('.blockpage').css('opacity','0.2')\n\n // … then get the ones needed …\n .filter(function(){\n return $('p:last-child', this).text() === Category;\n })\n\n // … and highlight them.\n .css('opacity','1');\n }\n }\n\n }); // end of ( filter on.change )\n\n\n // extra gimmick: make it draggable.\n\n // … enable this again because otherwise, the combobox won't work anymore.\n $Obj.mouseenter(function(){\n // undo.\n if ( $Obj.enableSelection )\n $Obj.enableSelection();\n\n }).mouseleave(function(){\n // prevent text selection on-drag.\n if ( $Obj.disableSelection )\n $Obj.disableSelection();\n });\n\n $Obj = $Obj.closest('fieldset.wooden_drag');\n if ( $Obj.length )\n {\n $Obj.mousedown(function(e)\n {\n // validate drag operation: only allow dragging with the left mouse button.\n // The combobox doesn't belong to the \"valid drag-start area\".\n if ( (e.which == 1)\n && ( ( e.srcElement && (e.srcElement.nodeName.toLowerCase() == \"fieldset\") ) // Opera\n || ( e.target && ( e.target.nodeName.toLowerCase() == \"fieldset\") ) ) ) // Chrome\n {\n\n // Make the fieldset mimick the cursor movement. For that, it is constantly\n // repositioned on-move, using the mouse cursor position and taking into account\n // where inside the fieldset the drag has started. That's why I'm forwarding the\n // x|y-coordinates from the time of the drag-start.\n\n $(window).mousemove( {x: e.offsetX, y: e.offsetY}, function(e)\n {\n hello_Im_dragging = true;\n\n var x = e.pageX - e.data.x - 21 - $(document).scrollLeft();\n var y = e.pageY - e.data.y - 21 - $(document).scrollTop();\n\n $Obj.css('left', x).css('top', y);\n\n }); // end of ( mouse move)\n } // end of ( left-click )\n }) // end of ( mouse down )\n .mouseup(function(e)\n {\n var Out = $('#output').text()+ ' :: up.';\n// $('#output').text(Out);\n var was_dragging = hello_Im_dragging;\n hello_Im_dragging = false;\n\n $(window).unbind('mousemove');\n\n // quick-fix, so that it doesn't cause error messages in other browsers.\n// widget.preferences.pos_rp_filter = {\n// 'top': $Obj.position().top,\n// 'left': $Obj.position().left\n// };\n\n if (!was_dragging) {\n // detect click. If I need it, that's how it works. But I don't need it.\n }\n }); // end of ( mouse up )\n\n// on-drop: save location in preferences object.\n\n\t } // end of ( drag functionality / found fieldset )\n } // end of ( found #wooden_rp_filter )\n\n// TODO:\n// · Force-reposition on-resize-window (i.e. to/from fullscreen).\n// · Save/load filter position to/from preferences.\n// · Code cleanup / merge with wooden_soc_filter.\n// · I should use $(window).mouseup() to end the drag. Instead of $Obj.mouseup(). Then it doesn't\n// matter *that* much that the box' position is sometimes off (it's perfect in Opera but now it's\n// not in Chrome).\n\n } // end of ( valid environment )\n}",
"function lerUltimaPagina() {}",
"function mostVisitedPage() {\n var pagemap = {};\n $.getJSON(\"__pageobjectdatabaseurl_placeholder__\", function (data) {\n // Iterate through the list of feedbacks and count each page entry\n $.each(data, function (key, value) {\n // Use a hashmap to tally the pages\n if (pagemap[value.docURI] == null) {\n //console.log(\"Adding [%s]\", value.page);\n pagemap[value.page] = 1;\n }\n else {\n console.log(\"Incrementing [%s]\", value.page);\n ++pagemap[value.docURI];\n }\n });\n $.each(pagemap, function (key, value) {\n //console.log(\"Page = %s\\nPage views = %s\", key, value);\n });\n });\n}",
"function reviewsPrevPage() {\n curPage = Math.max(1, curPage-1);\n loadReviews();\n}",
"recent() {\n this._loadPage('recent stories', API.newStories());\n }",
"function getPrev(){\n page--\n getSearch()\n}",
"function popularTvShowsHandler(){var page=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;if(page==1){state.popularTv=[];}discoverTvTMDB(page,function(resp){state.popularTv=state.popularTv.concat(resp.results);displayPopularTv();$(POPULAR_TV_TITLE).show();show(TV_MORE_BTN);});}// * * * * * * * * * * * * * * * * * * * * * * * * * ",
"function showPagination(count,current_page,offset,baseUrl, queryString,visibleNumbers) {\nlet output=\"\";\nlet fullUrl;\nif(queryString){\n fullUrl=baseUrl+\"?\"+queryString+\"&page=%page%\";\n}else{\n fullUrl=baseUrl+\"?page=%page%\";\n}\nif(count > offset){\n let lastPage=Math.ceil(count/offset);\n let endIndex,startIndex;\n output+=current_page > 1 ? '<li class=\"page-item\"><a class=\"page-link\" href=\"'+baseUrl+'\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"'+substitute(fullUrl,{\"%page%\":current_page-1})+'\" aria-label=\"Previous\">قبلی</a></li>' : \"\";\n if((current_page+(visibleNumbers-1)) > lastPage){\n \n endIndex=lastPage;\n startIndex=current_page-(visibleNumbers-(lastPage-current_page));\n }else{\n\n startIndex=current_page - (visibleNumbers-1);\n startIndex= startIndex<=0 ? 1:startIndex;\n endIndex=current_page+ (visibleNumbers-1);\n }\n\n for(pageNumber=startIndex;pageNumber<=endIndex;pageNumber++){\n output+= pageNumber==current_page ? \"<li class='page-item active'>\":\"<li class='page-item'>\";\n output+=\"<a class='page-link' href='\"+substitute(fullUrl,{\"%page%\":pageNumber})+\"'>\"+pageNumber+\"</a>\";\n }\n if(current_page != lastPage){\n output+='<li class=\"page-item\"><a class=\"page-link\" href=\"'+substitute(fullUrl,{\"%page%\":current_page+1})+'\" aria-label=\"Previous\">بعدی</a></li>';\n output+='<li class=\"page-item\"><a class=\"page-link\" href=\"'+substitute(fullUrl,{\"%page%\":lastPage})+'\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span></a></li>';\n }\n}\n$(\".pagination\").html(output);\n}",
"function displayTen() {\n firstPageDisplayed = false;\n hideAllPosts();\n showPosts(10);\n}",
"function previousPage() {\n currentPage -= 1;\n loadList();\n}",
"function reviewsNumPage(num) {\n curPage = num;\n loadReviews();\n}",
"function previousPage() { \n if(currentPage == 1) {\n return;\n }\n\n currentPage--;\n getArticlesForPage();\n}",
"function gallery_top()\n {\n // date and title\n\n if('date' in g) { $('span.date').text(g.date); }\n if('title' in g) { $('span.title').text(g.title); }\n\n // navigation elements\n\n if(!'navigate' in g) { return; }\n for(var nav in g.navigate) {\n if(nav) {\n $('a#nav-' + nav)\n .attr('href', g.navigate[nav])\n .css('display', 'inline-block');\n }\n }\n }",
"function showPagination(count, current_page, offset, visibleNumbers, queryString, baseUrl) {\n baseUrl = baseUrl === undefined ? window.location.origin + window.location.pathname : baseUrl;\n let output = \"\";\n let fullUrl;\n if (queryString) {\n fullUrl = baseUrl + \"?\" + queryString + \"&page=%page%\";\n } else {\n fullUrl = baseUrl + \"?page=%page%\";\n }\n if (count > offset) {\n\n let lastPage = Math.ceil(count / offset);\n let endIndex, startIndex;\n output += current_page > 1 ? '<li class=\"page-item\"><a class=\"page-link\" href=\"' + baseUrl + '\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span></a></li><li class=\"page-item\"><a class=\"page-link\" href=\"' + substitute(fullUrl, {\n \"%page%\": current_page - 1\n }) + '\" aria-label=\"Previous\">قبلی</a></li>' : \"\";\n if ((current_page + (visibleNumbers - 1)) > lastPage) {\n endIndex = lastPage;\n startIndex = current_page - (visibleNumbers - (lastPage - current_page));\n } else {\n startIndex = current_page - (visibleNumbers - 1);\n endIndex = current_page + (visibleNumbers - 1);\n }\n startIndex = startIndex <= 0 ? 1 : startIndex;\n for (pageNumber = startIndex; pageNumber <= endIndex; pageNumber++) {\n output += pageNumber == current_page ? \"<li class='page-item active'>\" : \"<li class='page-item'>\";\n output += \"<a class='page-link' href='\" + substitute(fullUrl, {\n \"%page%\": pageNumber\n }) + \"'>\" + pageNumber + \"</a>\";\n }\n if (current_page != lastPage) {\n output += '<li class=\"page-item\"><a class=\"page-link\" href=\"' + substitute(fullUrl, {\n \"%page%\": current_page + 1\n }) + '\" aria-label=\"Previous\">بعدی</a></li>';\n output += '<li class=\"page-item\"><a class=\"page-link\" href=\"' + substitute(fullUrl, {\n \"%page%\": lastPage\n }) + '\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span></a></li>';\n }\n }\n $(\".pagination\").html(output);\n}",
"function myPages(data, nbr_rslt = nbr_of_result_to_display, opt = null) { //ne pas changer nbr_rslt\r\n var pages = Math.ceil(data.length / nbr_rslt);\r\n $(\"#pages-container\").remove();\r\n $(\"#main-container\").append(\"<div id='pages-container'></div>\");\r\n if (nbr_rslt == data.length) {\r\n clearMoviePage();\r\n clearResult();\r\n allResultsWithNoButton(data);\r\n return;\r\n }\r\n //PAGE NUMBER BUTTON MAKER\r\n for (let i = 1; i <= pages; i++) {\r\n $(\"#pages-container\").append(\"<button id='page-\" + i + \"'>\" + i + \"</button>\");\r\n //AFFICHAGE DE PAGES\r\n $(\"#page-\" + i).on(\"click\", function () {\r\n $(\"#result\").html(\"\");\r\n if (i == 1) {\r\n for (let j = 0; j <= nbr_rslt - 1; j++) {\r\n if (opt == 'member') {\r\n if (data[j] && data[j] != undefined) {\r\n getMemberHistoric(data[j].split(\"|\"));\r\n }\r\n } else {\r\n $(\"#title-mem\").text() == \"\"\r\n ? myMovieCardWithAPI(data[j])\r\n : getMemberHistoric(data[j].split(\"|\"));\r\n }\r\n }\r\n } else {\r\n for (let j = (i - 1) * nbr_rslt; j <= (i - 1) * nbr_rslt + (nbr_rslt - 1); j++) {\r\n if (data[j] == null) {\r\n break;\r\n } else {\r\n $(\"#title-mem\").text() == \"\"\r\n ? myMovieCardWithAPI(data[j])\r\n : getMemberHistoric(data[j].split(\"|\"));\r\n }\r\n }\r\n }\r\n });\r\n }\r\n $(\"#page-1\").click();\r\n}",
"static get PAGE_ITEMS() {\n return 10;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pack meta data is the number and value of distinct symbols plus the length of the packed byte stream. | function DecodePackMeta(src) {
var nsym = src.ReadByte()
var P = new Array(nsym)
for (var i = 0; i < nsym; i++)
P[i] = src.ReadByte()
var len = src.ReadUint7()
return [P, nsym, len]
} | [
"pack(data) {\n return data;\n }",
"_packData(buf) {\n const objType = this._objType;\n if (objType.isCollection) {\n buf.writeUInt8(objType.collectionFlags);\n if (objType.collectionType === constants.TNS_OBJ_PLSQL_INDEX_TABLE) {\n this._ensureAssocKeys();\n buf.writeLength(this.unpackedAssocKeys.length);\n for (const index of this.unpackedAssocKeys) {\n buf.writeInt32BE(index);\n this._packValue(buf, objType.elementType, objType.elementTypeClass,\n this.unpackedAssocArray.get(index));\n }\n } else {\n buf.writeLength(this.unpackedArray.length);\n for (const value of this.unpackedArray) {\n this._packValue(buf, objType.elementType, objType.elementTypeClass,\n value);\n }\n }\n } else {\n for (const attr of objType.attributes) {\n this._packValue(buf, attr.type, attr.typeClass,\n this.unpackedAttrs.get(attr.name));\n }\n }\n }",
"function createMeta() {\n let meta = 0;\n if (envelope.payload instanceof Buffer === false) {\n meta = meta | MASK.TYPE;\n }\n if (envelope.contextId !== undefined) {\n meta = meta | MASK.CONTEXT;\n }\n if (envelope.subSource !== undefined) {\n meta = meta | MASK.SUB_CONTEXT;\n }\n if (header.length) {\n meta = meta | MASK.HEADER;\n }\n command = envelope.command;\n if (envelope.protocolCommand) {\n command = command | MASK.COMMAND_PROTOCOL;\n }\n if (envelope.subSource !== undefined) {\n meta = meta | MASK.SUB_CONTEXT;\n }\n return meta;\n }",
"function pack(items, labelKey, metadata) {\n var data = [items.length];\n var names = \"\";\n var offset = 0;\n for(var i=0; i<items.length; i++) {\n var item = items[i];\n data = data.concat([offset, metadata(item)]);\n names += cleanValue(item[labelKey]) + '\\0';\n offset = byteLength(names);\n }\n data.push(names);\n return data;\n}",
"function writeMetaAndCommand() {\n buffer.writeUInt8(meta, POSITION.META);\n buffer.writeUInt8(command, POSITION.COMMAND);\n position = POSITION.COMMAND + SIZE.COMMAND;\n }",
"function packData( ){\n \"use strict\";\n var data2, data3, datastr;\n data2 = {};\n data2[ translateStrTo( \"A\" ) ] = pieces.A.size;\n data2[ translateStrTo( \"B\" ) ] = pieces.B.size;\n data2[ translateStrTo( \"AuB\" ) ] = pieces.AuB.size;\n data2[ translateStrTo( \"U\" ) ] =\tpieces.U.size;\n data2[ translateStrTo( \"AB\" ) ] = pieces.AB.size;\n\n data3 = passedVals3;\n datastr = JSON.stringify( [ data2, data3, puzzleMode ] );\n return escape( datastr );\n}",
"function Pack(){}",
"function $pack(byte) {\n if ((version & 0xff) === byte) {\n version >>>= 8;\n return version ? $pack : $version;\n }\n throw new Error(\"Invalid packfile header\");\n }",
"function packRefData(p) {\n\tassert.equal(4, p.length, \"wrong array length\");\n\t// ensure all elements are converted to BNs\n\tp = p.map((a) => toBN(a));\n\t// pack issued, consumed, balance and owner\n\treturn p[0].shln(32).or(p[1]).shln(32).or(p[2]).shln(160).or(p[3]);\n}",
"deriveInfo(contentEncoding, senderPublic, receiverPublic) {\n const label = utf8Encode('P-256'); // always set to P-256\n\n let buffer = new Uint8Array(18 + contentEncoding.length + 1 + label.length + 1 + 2 * (2 + 65));\n let offset = 0;\n\n // Content-Encoding: |contentEncoding| || 0x00\n buffer.set(utf8Encode('Content-Encoding: '));\n buffer.set(utf8Encode(contentEncoding), 18);\n buffer.set([0x00], 18 + contentEncoding.length);\n\n offset += 18 + contentEncoding.length + 1;\n\n // label || 0x00\n buffer.set(label, offset);\n buffer.set([0x00], offset + label.length);\n\n offset += label.length + 1;\n\n // length(receiverPublic) || receiverPublic\n buffer.set([0x00, receiverPublic.byteLength], offset);\n buffer.set(receiverPublic, offset + 2);\n\n offset += 2 + receiverPublic.byteLength;\n\n // length(senderPublic) || senderPublic\n buffer.set([0x00, senderPublic.byteLength], offset);\n buffer.set(senderPublic, offset + 2);\n\n return buffer;\n }",
"_pack(num, len) {\n var o = [], len = ((typeof len == 'undefined') ? 4 : len);\n for (var i=0; i<len; ++i) {\n o.push(String.fromCharCode((num >> (i * 8)) & 0xff));\n }\n return o.join(\"\");\n }",
"function $pack(byte) {\n if ((version & 0xff) === byte) {\n version >>>= 8;\n return version ? $pack : $version;\n }\n throw new Error(\"Invalid packfile header\");\n }",
"function packRawObject(rawObject) {\r\n var strings = rawObject.strings;\r\n var numbers = rawObject.numbers;\r\n var booleans = rawObject.booleans;\r\n var nulls = rawObject.nulls;\r\n var maxStringBufferSize = 0;\r\n var extendedStringCount = 0;\r\n \r\n if (!Array.isArray(strings)) {strings = [];}\r\n if (!Array.isArray(numbers)) {numbers = [];}\r\n if (!Array.isArray(booleans)) {booleans = [];}\r\n if (!Array.isArray(nulls)) {nulls = [];}\r\n \r\n var nullCount = nulls.length;\r\n var booleanCount = booleans.length;\r\n var numberCount = numbers.length;\r\n var stringCount = strings.length;\r\n \r\n for (var i=0; i<stringCount; i++) {\r\n //strings longer than 255 bytes will be on the extended string list.\r\n //strings with character codes > 255 will also be on the extended string list.\r\n if (strings[i].length < 255) {\r\n maxStringBufferSize+=strings[i].length;\r\n }\r\n }\r\n \r\n //create some more typed arrays for the different data types\r\n var numberList = new Float32Array(numberCount);\r\n //var stringStartList = new Uint32Array(stringCount);\r\n var stringLengthList = new Uint8Array(stringCount);\r\n \r\n var stringBufferRaw = new ArrayBuffer(maxStringBufferSize);\r\n var stringBuffer = new Uint8Array(stringBufferRaw);\r\n var booleanList = new Uint8Array(booleanCount);\r\n \r\n var extendedStringBufferSize = 0;\r\n var extendedStringIndexes = []; //an array of the index of each extended string\r\n \r\n var stringBufferPosition = 0;\r\n var booleanIndex=0;\r\n var numberIndex=0;\r\n var stringIndex=0;\r\n \r\n for (var i=0; i<booleanCount; i++) {\r\n booleanList[i] = (booleans[i])?1:0;\r\n }\r\n \r\n for (var i=0; i<numberCount; i++) {\r\n numberList[i] = numbers[i];\r\n } \r\n \r\n for (var i=0; i<stringCount; i++) {\r\n var string = strings[i];\r\n var strlen = 0;\r\n if (typeof string == 'string') {\r\n strlen = string.length;\r\n }\r\n \r\n if (strlen < 255) {\r\n stringLengthList[stringIndex] = strlen;\r\n }\r\n \r\n var isExtendedString = false;\r\n \r\n if (strlen < 255) {\r\n for (var j=0; j<strlen; j++) {\r\n var charCode = string.charCodeAt(j);\r\n if (charCode <= 255) {\r\n stringBuffer[stringBufferPosition+j] = charCode;\r\n }\r\n else {\r\n j = strlen+1; //exit the loop\r\n isExtendedString = true;\r\n }\r\n }\r\n }\r\n else {\r\n isExtendedString = true;\r\n }\r\n \r\n if (!isExtendedString) {\r\n stringBufferPosition+=strlen; \r\n }\r\n else {\r\n //its either too long or contains complicated characters so make an extended string\r\n stringLengthList[stringIndex] = 255; //this will signify an extended length string\r\n extendedStringCount++;\r\n extendedStringBufferSize += strlen;\r\n extendedStringIndexes.push(i);\r\n }\r\n \r\n stringIndex++;\r\n\r\n }\r\n \r\n var stringBufferLength = stringBufferPosition;\r\n\r\n //finally encode extended strings\r\n var extendedStringBuffer = new Uint16Array(extendedStringBufferSize);\r\n var extendedStringLengthList = new Uint32Array(extendedStringCount);\r\n var extendedStringBufferPosition = 0;\r\n for (var j=0; j<extendedStringCount; j++) {\r\n \r\n var index = extendedStringIndexes[j];\r\n var extendedString = strings[index];\r\n var strlen = extendedString.length;\r\n \r\n extendedStringLengthList[j] = strlen;\r\n for (var k=0; k<strlen; k++) {\r\n var charCode = extendedString.charCodeAt(k);\r\n extendedStringBuffer[extendedStringBufferPosition+k] = charCode; \r\n }\r\n extendedStringBufferPosition += strlen;\r\n }\r\n var extendedStringBufferLength = extendedStringBufferPosition;\r\n \r\n //pack everything together into one buffer\r\n \r\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! \r\n //it appears we are missing the part where we store the type of each variable. How is that going to work?\r\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n \r\n //create a buffer\r\n //number of numbers (32 bit int), number of bools (32 bit int), number of strings (32 bit int), number of extended strings (32 bit int)\r\n //add some extra room on the end which will help when sending it. \r\n var dataSize = 4*7 + 4*numberCount + 2*Math.ceil(booleanCount/2) + 2*Math.ceil(stringCount/2) + 4*Math.ceil(stringBufferLength/4) + 4*extendedStringCount + 2*extendedStringBufferPosition;\r\n //add some extra room on the end which will help when sending it. \r\n var maxChunkSize = 16*1024;\r\n var additionalSize = (Math.ceil(dataSize / maxChunkSize) + 4) * 4 * 4;\r\n bufferSize = 4*Math.ceil(dataSize/4) + additionalSize;\r\n var buffer = new ArrayBuffer(bufferSize); \r\n console.log(\"dataSize:\", dataSize, \"bufferSize:\", bufferSize);\r\n \r\n //first fill out the 6 sizes\r\n var memOffset = 0; //start with some space for the header\r\n var sizeArray = new Int32Array(buffer, memOffset, 7*4);\r\n sizeArray[0] = dataSize;\r\n sizeArray[1] = numberCount;\r\n sizeArray[2] = booleanCount;\r\n sizeArray[3] = stringCount;\r\n sizeArray[4] = stringBufferLength;\r\n sizeArray[5] = extendedStringCount;\r\n sizeArray[6] = extendedStringBufferLength; \r\n memOffset += 7*4;\r\n \r\n //debugger;\r\n \r\n //now fill the numbers\r\n var floatView = new Float32Array(buffer, memOffset, numberCount);\r\n floatView.set(numberList); \r\n memOffset += numberCount*4;\r\n \r\n //now fill the bools (one byte per bool)\r\n var boolView = new Uint8Array(buffer, memOffset, booleanCount)\r\n boolView.set(booleanList);\r\n memOffset += 2*Math.ceil(booleanCount/2); //align to 2 bytes.\r\n \r\n //now fill the string length list\r\n var stringLengthView = new Uint8Array(buffer, memOffset, stringCount);\r\n stringLengthView.set(stringLengthList);\r\n memOffset += 2*Math.ceil(stringCount/2); //align to 2 bytes.\r\n \r\n //now fill the string data buffer\r\n var stringDataView = new Uint8Array(buffer, memOffset, stringBufferLength);\r\n //make sure we only use the minimum amount of the array since at first we used more than we needed\r\n var stringDataSource = new Uint8Array(stringBufferRaw,0,stringBufferLength);\r\n stringDataView.set(stringDataSource);\r\n memOffset += stringBufferLength; \r\n \r\n //align to 4 bytes.\r\n memOffset = 4*Math.ceil(memOffset/4);\r\n //now fill out the length of the extended string buffer\r\n var extendedStringLengthView = new Uint32Array(buffer, memOffset, extendedStringCount);\r\n extendedStringLengthView.set(extendedStringLengthList);\r\n memOffset += 4*extendedStringCount;\r\n \r\n //now fill the extended string buffer\r\n var extendedStringDataSource = new Uint16Array(buffer, memOffset, extendedStringBufferLength);\r\n extendedStringDataSource.set(extendedStringBuffer);\r\n \r\n //show the data\r\n var rawView = new Uint8Array(buffer);\r\n \r\n //console.log(JSON.stringify(values)); \r\n //console.log(\"Type list: \", typesList, numberList, stringLengthList, booleanList, stringBuffer);\r\n //console.log(typesList.length + numberList.length * 4 + stringLengthList.length * 2 + stringBuffer.length + booleanList.length, JSON.stringify(values).length);\r\n //console.log(rawView);\r\n \r\n return(buffer);\r\n}",
"wire (m, serial) {\n let headerBuf = Buffer.alloc(1024 * 1024)\n let headerLength = 0\n let bodyBuf = Buffer.alloc(1024 * 1024)\n let bodyLength = 0\n let header = new STRUCT('(yyyyuua(yv))')\n let fields = new ARRAY('a(yv)')\n let bodyWrap, bodyWrapSig\n\n header.push(new BYTE(LITTLE))\n header.push(new BYTE(this.encodeType(m.type)))\n header.push(new BYTE(this.encodeFlags(m.flags)))\n header.push(new BYTE(0x01))\n if (m.body) {\n bodyWrap = new STRUCT(m.body)\n bodyWrapSig = bodyWrap.signature()\n bodyLength = bodyWrap.marshal(bodyBuf, 0, LITTLE)\n }\n header.push(new UINT32(bodyLength))\n header.push(new UINT32(serial))\n if (m.path) fields.push(this.encodeField(1, m.path, OBJECT_PATH))\n if (m.interface) fields.push(this.encodeField(2, m.interface, STRING))\n if (m.member) fields.push(this.encodeField(3, m.member, STRING))\n if (m.errorName) fields.push(this.encodeField(4, m.errorName, STRING))\n if (m.replySerial) fields.push(this.encodeField(5, m.replySerial, UINT32))\n if (m.destination) fields.push(this.encodeField(6, m.destination, STRING))\n if (this.myName) fields.push(this.encodeField(7, this.myName, STRING))\n let sig = m.signature || bodyWrap && bodyWrapSig.slice(1, bodyWrapSig.length - 1)\n\n if (sig) fields.push(this.encodeField(8, sig, SIGNATURE))\n if (m.unixFds) fields.push(this.encodeField(9, m.unixFds, UINT32))\n header.push(fields)\n headerLength = header.marshal(headerBuf, 0, LITTLE)\n\n return Buffer.concat([\n headerBuf.slice(0, Math.ceil(headerLength / 8) * 8),\n bodyBuf.slice(0, bodyLength)\n ])\n }",
"metaDataLength() {\n return this.bb.readInt32(this.bb_pos + 8);\n }",
"function CreatePackedImage(Contents)\n{\n\tPop.Debug(\"Creating packed image\",Object.keys(Contents));\n\t\n\t//\textract meta & non-meta\n\tlet Meta = {};\n\tMeta.ImageMetas = [];\n\tlet Images = [];\n\t\n\tfunction PushImage(Name,Image)\n\t{\n\t\tImages.push( Image );\n\t\t\n\t\tlet ImageMeta = {};\n\t\tImageMeta.Width = Image.GetWidth();\n\t\tImageMeta.Height = Image.GetHeight();\n\t\tImageMeta.Format = Image.GetFormat();\n\t\tImageMeta.Name = Name;\n\t\tMeta.ImageMetas.push( ImageMeta );\n\t}\n\t\n\tfunction PushMeta(Name,Content)\n\t{\n\t\tMeta[Name] = Content;\n\t}\n\t\n\tfunction PushContent(Name)\n\t{\n\t\tconst Content = Contents[Name];\n\t\tif ( !Content )\n\t\t\treturn;\n\t\tif ( IsObjectInstanceOf(Content,Pop.Image) )\n\t\t\tPushImage( Name, Content );\n\t\telse\n\t\t\tPushMeta( Name, Content );\n\t}\n\tconst ContentKeys = Object.keys(Contents);\n\tContentKeys.forEach( PushContent );\n\t\n\t//\tencode meta into a line of pixels\n\tconst MetaString = JSON.stringify(Meta);\n\tconst MetaBytes = StringToBytes(MetaString);\n\t\n\t//\tmake image width the length of the byte array so row0 is always meta\n\tconst PackedChannels = GetChannelsFromPixelFormat(PackedImageFormat);\n\t//\tgotta pad the meta to align to channels\n\tPadArray( MetaBytes, PackedChannels, ' ' );\n\tconst PackedWidth = MetaBytes.length / PackedChannels;\n\n\tlet Pixels = [];\n\t//\twrite meta\n\tPixels.push( ...MetaBytes );\n\t//\twrite each image\n\tPop.Debug(\"Packing images: x\"+ Images.length);\n\tfor ( let i=0;\ti<Images.length;\ti++ )\n\t{\n\t\tconst Image = Images[i];\n\t\tconst ImagePixels = Image.GetPixelBuffer();\n\t\t\n\t\tfor ( let p=0;\tp<ImagePixels.length;\tp++ )\n\t\t\tPixels.push( ImagePixels[p] );\n\t\t//\tcausing callstack error\n\t\t//const ImagePixelsArray = Array.from(ImagePixels);\n\t\t//Pixels.push( ...ImagePixelsArray );\n\t}\n\t\n\t//\tpad with pattern we can read in a hex editor\n\tconst PackedStride = PackedWidth*PackedChannels;\n\tPadArray( Pixels, PackedStride, 'PAD!' );\n\t\n\tconst PackedHeight = Pixels.length / PackedStride;\n\tif ( !Number.isInteger(PackedHeight) )\n\t\tthrow \"We didn't create aligned pixel buffer!\";\n\t\n\tconst PackedImage = new Pop.Image();\n\tPixels = new Uint8Array(Pixels);\n\tPackedImage.WritePixels( PackedWidth, PackedHeight, Pixels, PackedImageFormat );\n\treturn PackedImage;\n}",
"function DataPack (Data) {\n if (!Data || !(Data instanceof Buffer)) { return null; }\n\n let PrxBfr; // prefox buffer.\n\n //==== data length info of package. ====\n\n if (Data.length <= 125) {\n PrxBfr = new Buffer(2);\n PrxBfr[1] = Data.length;\n }\n else if (Data.length <= 65535) {\n PrxBfr = new Buffer(4);\n PrxBfr[1] = 126;\n PrxBfr[2] = Math.floor(Data.length / 256);\n PrxBfr[3] = Data.length % 256;\n }\n else {\n PrxBfr = new Buffer(10);\n PrxBfr[1] = 127;\n\n for (let i = 0; i < 8; i++) { PrxBfr[2 + i] = Math.floor(Data.length / Math.pow(256, 8 - i)); }\n }\n\n PrxBfr[0] = 0x81;\n\n return Buffer.concat([PrxBfr, Data]);\n}",
"function data() {\n var version = this.produce(otr_short);\n var type = this.produce(otr_byte);\n var flags = this.produce(otr_byte);\n var sender_keyid = this.produce(otr_int);\n var recip_keyid = this.produce(otr_int);\n var dh_y = this.produce(otr_int);\n var ctr_init = this.produce(otr_ctr);\n var enc_msg = this.produce(otr_data);\n var authenticator = this.produce(otr_mac);\n var old_mac_keys = this.produce(otr_data);\n return FIXME;\n }",
"static pack(obj) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update a plugin via its github repo, using "data" in arguments for "release", "update" and "init" plugin's methods | updateViaGithub(plugin, ...data) {
let directory = "";
let key = -1;
// check plugin
return Promise.resolve().then(() => {
return (0, checkOrchestrator_1.default)("updateViaGithub/plugin", plugin).then(() => {
return (0, checkNonEmptyString_1.default)("updateViaGithub/github", (0, extractGithub_1.default)(plugin)).catch(() => {
return Promise.reject(new ReferenceError("Plugin \"" + plugin.name + "\" must be linked in the package to a github project to be updated"));
});
}).then(() => {
key = this.getPluginsNames().findIndex((pluginName) => {
return pluginName === plugin.name;
});
return -1 < key ? Promise.resolve() : Promise.reject(new Error("Plugin \"" + plugin.name + "\" is not registered"));
});
// check plugin directory
}).then(() => {
return (0, checkAbsoluteDirectory_1.default)("updateViaGithub/directory", this.directory).then(() => {
directory = (0, node_path_1.join)(this.directory, plugin.name);
return (0, checkAbsoluteDirectory_1.default)("updateViaGithub/plugindirectory", directory);
});
// release plugin
}).then(() => {
const pluginName = plugin.name;
return plugin.release(...data).then(() => {
this.emit("released", plugin, ...data);
return plugin.destroy();
}).then(() => {
this.emit("destroyed", pluginName, ...data);
this.plugins.splice(key, 1);
return Promise.resolve();
});
// download plugin
}).then(() => {
return (0, gitUpdate_1.default)(directory).then(() => {
return (0, createPluginByDirectory_1.default)(directory, this.externalRessourcesDirectory, this._logger, ...data);
});
// check plugin modules versions
}).then((_plugin) => {
return this.checkModules(_plugin).then(() => {
return Promise.resolve(_plugin);
});
}).then((_plugin) => {
// update dependencies & execute update script
return Promise.resolve().then(() => {
return !_plugin.dependencies ? Promise.resolve() : (0, npmUpdate_1.default)(directory);
}).then(() => {
return _plugin.update(...data);
}).then(() => {
this.emit("updated", _plugin, ...data);
return _plugin.init(...data);
// execute init script
}).then(() => {
this.emit("initialized", _plugin, ...data);
this.plugins[key] = _plugin;
return Promise.resolve(_plugin);
});
});
} | [
"function updatePluginJson() {\n // Read and parse content.\n var pkg = getPackage();\n var plugin = getPlugin();\n\n // Create assignments in plugin.json\n plugin.packageName = pkg.name;\n plugin.header.commitHash = getCommitHash();\n\n // Write the result.\n plugin = JSON.stringify(plugin, null, 2);\n fs.writeFileSync('./plugin.json', plugin, 'utf8');\n}",
"function checkForUpdates() {\n //git://github.com/USERNAME/REPO.git\n var repoURL = packageJSON.repository[0].url;\n //[ \"git:\", \"\", \"github.com\", \"USERNAME\", \"REPO.git\" ]\n var repoURLSplit = repoURL.split(\"/\");\n var helpMessage = 'Visit UGUI.io/api to learn how to use the \"Check for updates\" feature.';\n\n //If the first or third items in the array match the pattern of a github repo\n if (repoURLSplit[0].toLowerCase() == \"git:\" || repoURLSplit[2].toLowerCase() == \"github.com\") {\n //Grab the Username from the Repo URL\n var username = repoURLSplit[3];\n //Get the Repo name from the Repo URL\n var repoName = repoURLSplit[4].split(\".git\")[0];\n //Build the URL for the API\n var updateURL = \"https://api.github.com/repos/\" + username + \"/\" + repoName + \"/releases\";\n } else {\n console.info(º+'Unable to check for updates because your Repository ' +\n 'URL does not match expected pattern.', consoleNormal);\n console.info(º+helpMessage, consoleNormal);\n return;\n }\n\n //Hit the GitHub API to get the data for latest releases\n $.ajax({\n url: updateURL,\n error: function(){\n //Display a message in the About Modal informing the user they have the latest version\n $(\"#updateResults\").html(\n '<p class=\"text-center\">' +\n '<strong>Unable to reach update server. Try again later.</strong>' +\n '</p>'\n );\n console.info(º+'Unable to check for updates because GitHub cannot be reached ' +\n 'or your Repository URL does not match expected pattern.', consoleError);\n console.info(º+helpMessage, consoleNormal);\n return;\n },\n success: function(data){\n //0.2.5\n var remoteVersion = data[0].tag_name.split(\"v\")[1];\n var localVersion = appVersion;\n //[ \"0\", \"2\", \"5\" ]\n var rvs = remoteVersionSplit = remoteVersion.split(\".\");\n var lvs = localVersionSplit = localVersion.split(\".\");\n //Check if the Major, Minor, or Patch have been updated on the remote\n if (\n (rvs[0] > lvs[0]) ||\n (rvs[0] == lvs[0] && rvs[1] > lvs[1]) ||\n (rvs[0] == lvs[0] && rvs[1] == lvs[1] && rvs[2] > lvs[2])\n ) {\n //Display in the About Modal a link to the release notes for the newest version\n $(\"#updateResults\").html(\n '<p>' +\n '<strong>Update found!</strong> ' +\n '<a href=\"' + data[0].html_url + '\" class=\"external-link\">' +\n 'View latest release' +\n '</a>.' +\n '</p>'\n );\n //Make sure the link opens in the user's default browser\n ugui.helpers.openDefaultBrowser();\n //If there is not a new version of the app available\n } else {\n //Display a message in the About Modal informing the user they have the latest version\n $(\"#updateResults\").html(\n '<p class=\"text-center\">' +\n '<strong>You have the latest version of ' + appTitle + '.</strong>' +\n '</p>'\n );\n }\n }\n });\n}",
"installViaGithub(user, repo, ...data) {\n return (0, checkAbsoluteDirectory_1.default)(\"installViaGithub/directory\", this.directory).then(() => {\n return (0, checkNonEmptyString_1.default)(\"installViaGithub/user\", user);\n }).then(() => {\n return (0, checkNonEmptyString_1.default)(\"installViaGithub/repo\", repo);\n }).then(() => {\n const directory = (0, node_path_1.join)(this.directory, repo);\n return new Promise((resolve, reject) => {\n (0, checkAbsoluteDirectory_1.default)(\"installViaGithub/plugindirectory\", directory).then(() => {\n return reject(new Error(\"\\\"\" + repo + \"\\\" plugin already exists\"));\n }).catch(() => {\n return resolve(directory);\n });\n });\n }).then((directory) => {\n return Promise.resolve().then(() => {\n return (0, gitInstall_1.default)(directory, user, repo);\n }).then(() => {\n // install dependencies & execute install script\n return (0, createPluginByDirectory_1.default)(directory, this.externalRessourcesDirectory, this._logger, ...data);\n // check plugin modules versions\n }).then((plugin) => {\n return this.checkModules(plugin).then(() => {\n return Promise.resolve(plugin);\n });\n }).then((plugin) => {\n return Promise.resolve().then(() => {\n return !plugin.dependencies ? Promise.resolve() : (0, npmInstall_1.default)(directory);\n }).then(() => {\n return plugin.install(...data);\n // execute init script\n }).then(() => {\n this.emit(\"installed\", plugin, ...data);\n return plugin.init(...data);\n }).then(() => {\n this.emit(\"initialized\", plugin, ...data);\n this.plugins.push(plugin);\n return Promise.resolve(plugin);\n }).catch((err) => {\n return this.uninstall(plugin, ...data).then(() => {\n return Promise.reject(err);\n });\n });\n }).catch((err) => {\n return new Promise((resolve, reject) => {\n (0, checkAbsoluteDirectory_1.default)(\"installViaGithub/plugindirectory\", directory).then(() => {\n return (0, rmdirp_1.default)(directory).then(() => {\n return err ? reject(err) : resolve();\n });\n }).catch(() => {\n return err ? reject(err) : resolve();\n });\n });\n });\n });\n }",
"updateRepositoryBuildNumber(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n\n let apiInstance = new Bitbucket.PipelinesApi(); // String | The account // String | The repository // PipelineBuildNumber | The build number to update.\n /*let username = \"username_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ /*let body = new Bitbucket.PipelineBuildNumber();*/ apiInstance.updateRepositoryBuildNumber(\n incomingOptions.username,\n incomingOptions.repoSlug,\n incomingOptions.body,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"async function versionPlugin() {\n const pluginPath = path.join(__dirname, '../plugins/faustwp');\n const pluginFile = path.join(pluginPath, 'faustwp.php');\n const readmeTxt = path.join(pluginPath, 'readme.txt');\n const changelog = path.join(pluginPath, 'CHANGELOG.md');\n\n const version = await getNewVersion(pluginPath);\n\n if ( version ) {\n bumpPluginHeader(pluginFile, version);\n await bumpStableTag(readmeTxt, version);\n generateReadmeChangelog(readmeTxt, changelog);\n }\n}",
"function update() {\n var completion = new File('git-completion.sh');\n completion.curl('https://raw.github.com/git/git/master/contrib/completion/git-completion.bash');\n\n var gprompt = new File('git-prompt.sh');\n gprompt.curl('https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh');\n\n var pathogen = new File('pathogen.vim');\n pathogen.target = path.join(targets, 'vim/autoload/pathogen.vim');\n pathogen.curl('https://raw.github.com/tpope/vim-pathogen/master/autoload/pathogen.vim');\n\n var child;\n child = exec('git submodule update --init', function (err, stdout, stderr) {\n if (stdout) { console.log('git submodule update: ' + stdout); }\n if (stderr) { console.log('git submodule update error: ' + stderr); }\n if (err !== null) { console.log('git submodule update error: ' + err); }\n });\n}",
"function runUpdate()\n{\n var files = getJson(\"update url\");\n files.forEach(function (file) {\n update.updateFile(file.fileName, file.url);\n });\n}",
"[updateClickHandler]() {\n const { manualUpdateAvailable, hasAppUpdate } = this;\n if (manualUpdateAvailable) {\n const { updateVersion } = this;\n const base = 'https://github.com/advanced-rest-client/arc-electron/releases/tag';\n const url = `${base}/v${updateVersion}`;\n ipc.send('open-external-url', url);\n } else if (hasAppUpdate) {\n ipc.send('install-update');\n }\n }",
"function updatePlugin(pluginsource, callback){\n\tutil.checkDirSync(pluginsource.installeddir);\n\t\n\t// check if pluginsource is from database and hase information\n\tfs.writeFile(pluginsource.installeddir + '/plugin.json', JSON.stringify(pluginsource, null, '\\t'), function(error, data){\n\t\t// when a plugin is installed need to update the plugin loader.\n\t\tpluginsourceService.getPluginloader().emit('installed', { id:pluginsource.id, plugintype:pluginsource.plugintype, plugindir: pluginsource.installeddir});\n\t\t\n\t\tpluginsourceService.getStorageService().add_update({id:pluginsource.id}, {id:pluginsource.id, installed:true}, callback);\n\t\t\n\t\t// @TODO do this by plugin api not here\n\t\tpluginsourceService.getServiceloader().getService(\"plugin\").getStorageService().add_update({id:pluginsource.id}, pluginsource, function(error, data){});\n\t});\n}",
"updateUrl () {\n let self = this\n return new Promise(function (resolve) {\n loadJsonFile('./auto_updater.json').then(function (content) {\n content.url = self._releaseUrl\n writeJsonFile('./auto_updater.json', content).then(function () {\n resolve()\n })\n })\n .catch(function (err) {\n resolve()\n })\n })\n }",
"function editRepo(owner,repo)\r\n{\r\nvar options = {\r\n\t\turl: urlRoot + '/repos/' + owner + \"/\" + repo,\r\n\t\tmethod: 'PATCH',\r\n\t\theaders: {\r\n\t\t\t\"User-Agent\": \"EnableIssues\",\r\n\t\t\t\"content-type\": \"application/json\",\r\n\t\t\t\"Authorization\": token\r\n\t\t},\r\n\t\tjson: {\r\n \t\t\t \"name\": repo,\r\n \t\t \t \"description\": \"This is scyadav demo HW1 repository\",\r\n \t\t \t \"homepage\": \"https://github.com\",\r\n \t\t \"private\": true,\r\n\t\t\t \"has_wiki\": true\r\n \t\t }\r\n\t};\r\n\r\n\t// Send a http request to url and specify a callback that will be called upon its return.\r\n\trequest(options, function (error, response, body) \r\n\t{\r\n\t\tvar obj = body;\r\n\t\tconsole.log( obj );\r\n\t\tfor( var i = 0; i < obj.length; i++ )\r\n\t\t{\r\n\t\t\tvar name = obj[i].name;\r\n\t\t\tconsole.log( name );\r\n\t\t}\r\n\t});\r\n\t\r\n}",
"function doUpdate() {\n $ionicDeploy.update().then(function(res) {\n logger.success('Ionic Deploy: Update Success! ', res);\n }, function(err) {\n logger.error('Ionic Deploy: Update error! ', err);\n }, function(prog) {\n logger.info('Ionic Deploy: Progress... ', prog);\n });\n }",
"function populateReleaseNotes(){\n $.ajax({\n url: 'https://github.com/dscalzi/PixargonLauncher/releases.atom',\n success: (data) => {\n const version = 'v' + remote.app.getVersion()\n const entries = $(data).find('entry')\n \n for(let i=0; i<entries.length; i++){\n const entry = $(entries[i])\n let id = entry.find('id').text()\n id = id.substring(id.lastIndexOf('/')+1)\n\n if(id === version){\n settingsAboutChangelogTitle.innerHTML = entry.find('title').text()\n settingsAboutChangelogText.innerHTML = entry.find('content').text()\n settingsAboutChangelogButton.href = entry.find('link').attr('href')\n }\n }\n\n },\n timeout: 2500\n }).catch(err => {\n settingsAboutChangelogText.innerHTML = 'Sürüm notları yüklenemedi.'\n })\n}",
"updateRepositoryHostedPropertyValue(incomingOptions, cb) {\n const Bitbucket = require('./dist');\n\n let apiInstance = new Bitbucket.PropertiesApi(); // String | The account // String | The repository // String | The key of the Connect app // String | The name of the property.\n /*let username = \"username_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ /*let appKey = \"appKey_example\";*/ /*let propertyName = \"propertyName_example\";*/ apiInstance.updateRepositoryHostedPropertyValue(\n incomingOptions.username,\n incomingOptions.repoSlug,\n incomingOptions.appKey,\n incomingOptions.propertyName,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, '', response);\n }\n }\n );\n }",
"uninstall(plugin, ...data) {\n let directory = \"\";\n let key = -1;\n let pluginName = \"\";\n // check plugin\n return Promise.resolve().then(() => {\n return (0, checkOrchestrator_1.default)(\"uninstall/plugin\", plugin).then(() => {\n key = this.getPluginsNames().findIndex((name) => {\n return name === plugin.name;\n });\n return -1 < key ? Promise.resolve() : Promise.reject(new Error(\"Plugin \\\"\" + plugin.name + \"\\\" is not registered\"));\n });\n // check plugin directory\n }).then(() => {\n return (0, checkAbsoluteDirectory_1.default)(\"uninstall/directory\", this.directory).then(() => {\n pluginName = plugin.name;\n directory = (0, node_path_1.join)(this.directory, pluginName);\n return (0, checkAbsoluteDirectory_1.default)(\"uninstall/plugindirectory\", directory);\n });\n // release plugin\n }).then(() => {\n return plugin.release(...data).then(() => {\n return (0, rmdirp_1.default)((0, node_path_1.join)(this.externalRessourcesDirectory));\n }).then(() => {\n this.emit(\"released\", plugin, ...data);\n return plugin.destroy(...data);\n }).then(() => {\n this.emit(\"destroyed\", pluginName, ...data);\n this.plugins.splice(key, 1);\n return Promise.resolve();\n });\n // update dependencies & execute update script\n }).then(() => {\n return Promise.resolve().then(() => {\n return plugin.uninstall(...data);\n }).then(() => {\n this.emit(\"uninstalled\", pluginName, ...data);\n return (0, rmdirp_1.default)(directory);\n });\n }).then(() => {\n return Promise.resolve(pluginName);\n });\n }",
"function update(repo, callback) {\n var releaseNotes = 'release-notes.md';\n editor(repo + path.sep + releaseNotes, function(code, sig) {\n if (code === 0 && sig === null) {\n git.checkModified(repo, releaseNotes, function (err, modified) {\n if (!err && !modified) {\n callback('No release notes, aborting...');\n } else {\n callback(err);\n }\n });\n }\n });\n}",
"async function run() {\n try {\n const context = github.context;\n await status(\"pending\");\n\n const track = getInput(\"track\") || \"stable\";\n const appName = getInput(\"release\", required);\n const release = releaseName(appName, track);\n const namespace = getInput(\"namespace\", required);\n const chart = chartName(getInput(\"chart\", required));\n const chartVersion = getInput(\"chart_version\");\n const values = getValues(getInput(\"values\"));\n const task = getInput(\"task\");\n const version = getInput(\"version\");\n const valueFiles = getValueFiles(getInput(\"value_files\"));\n const removeCanary = getInput(\"remove_canary\");\n const helm = getInput(\"helm\") || \"helm\";\n const timeout = getInput(\"timeout\");\n const repository = getInput(\"repository\");\n const dryRun = core.getInput(\"dry-run\");\n const secrets = getSecrets(core.getInput(\"secrets\"));\n const atomic = getInput(\"atomic\") || true;\n\n core.debug(`param: track = \"${track}\"`);\n core.debug(`param: release = \"${release}\"`);\n core.debug(`param: appName = \"${appName}\"`);\n core.debug(`param: namespace = \"${namespace}\"`);\n core.debug(`param: chart = \"${chart}\"`);\n core.debug(`param: chart_version = \"${chartVersion}\"`);\n core.debug(`param: values = \"${values}\"`);\n core.debug(`param: dryRun = \"${dryRun}\"`);\n core.debug(`param: task = \"${task}\"`);\n core.debug(`param: version = \"${version}\"`);\n core.debug(`param: secrets = \"${JSON.stringify(secrets)}\"`);\n core.debug(`param: valueFiles = \"${JSON.stringify(valueFiles)}\"`);\n core.debug(`param: removeCanary = ${removeCanary}`);\n core.debug(`param: timeout = \"${timeout}\"`);\n core.debug(`param: repository = \"${repository}\"`);\n core.debug(`param: atomic = \"${atomic}\"`);\n\n\n // Setup command options and arguments.\n const args = [\n \"upgrade\",\n release,\n chart,\n \"--install\",\n \"--wait\",\n `--namespace=${namespace}`,\n ];\n\n // Per https://helm.sh/docs/faq/#xdg-base-directory-support\n if (helm === \"helm3\") {\n process.env.XDG_DATA_HOME = \"/root/.helm/\"\n process.env.XDG_CACHE_HOME = \"/root/.helm/\"\n process.env.XDG_CONFIG_HOME = \"/root/.helm/\"\n } else {\n process.env.HELM_HOME = \"/root/.helm/\"\n }\n\n if (dryRun) args.push(\"--dry-run\");\n if (appName) args.push(`--set=app.name=${appName}`);\n if (version) args.push(`--set=app.version=${version}`);\n if (chartVersion) args.push(`--version=${chartVersion}`);\n if (timeout) args.push(`--timeout=${timeout}`);\n if (repository) args.push(`--repo=${repository}`);\n valueFiles.forEach(f => args.push(`--values=${f}`));\n args.push(\"--values=./values.yml\");\n\n // Special behaviour is triggered if the track is labelled 'canary'. The\n // service and ingress resources are disabled. Access to the canary\n // deployments can be routed via the main stable service resource.\n if (track === \"canary\") {\n args.push(\"--set=service.enabled=false\", \"--set=ingress.enabled=false\");\n }\n\n // If true upgrade process rolls back changes made in case of failed upgrade.\n if (atomic === true) {\n args.push(\"--atomic\");\n }\n\n // Setup necessary files.\n if (process.env.KUBECONFIG_FILE) {\n process.env.KUBECONFIG = \"./kubeconfig.yml\";\n await writeFile(process.env.KUBECONFIG, process.env.KUBECONFIG_FILE);\n }\n await writeFile(\"./values.yml\", values);\n\n core.debug(`env: KUBECONFIG=\"${process.env.KUBECONFIG}\"`);\n\n // Render value files using github variables.\n await renderFiles(valueFiles.concat([\"./values.yml\"]), {\n secrets,\n deployment: context.payload.deployment,\n });\n\n // Remove the canary deployment before continuing.\n if (removeCanary) {\n core.debug(`removing canary ${appName}-canary`);\n await exec.exec(helm, deleteCmd(helm, namespace, `${appName}-canary`), {\n ignoreReturnCode: true\n });\n }\n\n // Actually execute the deployment here.\n if (task === \"remove\") {\n await exec.exec(helm, deleteCmd(helm, namespace, release), {\n ignoreReturnCode: true\n });\n } else {\n await exec.exec(helm, args);\n }\n\n await status(task === \"remove\" ? \"inactive\" : \"success\");\n } catch (error) {\n core.error(error);\n core.setFailed(error.message);\n await status(\"failure\");\n }\n}",
"checkout(version) {}",
"function updateRepository(devData) {\n console.log('6g. in updateRespository')\n if (devData) {\n let repoDevData = {\n repoName: devData.name,\n repoDesc: devData.description,\n activeFlag: false,\n archiveFlag: false,\n deploymentLink: \"\",\n imageLink: \"\",\n html_url: devData.html_url,\n repoID: devData.id,\n };\n db.Repository.insertMany(repoDevData);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
and finally a delete cookie function so we can reset the cookie | function deleteCookie(){
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
} | [
"function delete_cookie(){\n CookieUtil.unset(\"cookie_count\");\n window.location.reload();\n}",
"function removeCookie(cookie) {\n}",
"function deleteCookie(cname) { // cookie name\r\n \r\n document.cookie = cname + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\"; // Así es como se borra una cookie\r\n \r\n}",
"function deleteCookie () {\n\t\tsaveCookie('', { expires: -1 });\n\t}",
"function eraseCookie(c_name){\n createCookie(c_name,\"\",-1);\n}",
"function deleteCookie(){\n signOut();\n document.cookie = \"username=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n location.reload() \n}",
"function deleteCookie(name) {\n writeCookie(name, \"\");\n}",
"function delCookie(name) {\n var exp = new Date();\n FixCookieDate (exp); // Correct for Mac bug\n exp.setTime (exp.getTime() - 1); // This cookie is history\n var cval = getCookie (name);\n (cval != null)\n document.cookie = name + \"=\" + cval + \"; expires=\" + exp.toGMTString();\n}//endFunction",
"function eliminarCookie(nombre) {\n document.cookie = nombre + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n}",
"function fun_remove_cookie()\n{\n document.cookie = \"wdmusername=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;\";\n document.cookie = \"wdmuseremail=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;\";\n}",
"function cancella_cookie(nome_cookie){\r\n crea_cookie(nome_cookie,'',-1);\r\n}",
"function eraseCookie(nomeCookie){\n\tcreateCookie(nomeCookie,'');\n}",
"function eraseCookie(name) {\n createCookie(name,\"\",-1);\n}",
"function deleteACookie(){\n var cname = window.document.getElementById('cname').value;//Get the cookie name from the cname input element\n deleteCookie(cname);//Call the deleteCookie to delete the cookie\n window.location.reload();//Reload the page\n}",
"function eliminarCookie(){\n\tdeleteCookie(\"visitas\");\n}",
"function deleteCookie(szName)\n{\n \tvar tmp = \t \t\t\t \t getCookie(szName);\n\tif(tmp)\n\t{ setCookie(szName,tmp,(new Date(1))); }\n}",
"function delete_cookie(){\r\n document.cookie=\"hideAlert=;path=/\";\r\n document.cookie=\"away=;path=/\";\r\n}",
"function deleteAutosaveCookie(cookie) {\n if (cookie) {\n Cookie.dispose(cookie.key);\n cookie.empty();\n }\n }",
"function deleteUserIdCookie() {\n setCookie(\"userId\", \"\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert to native SVGPoint | native () {
// create new point
const point = new SVGPoint()
// update with current values
point.x = this.x
point.y = this.y
return point
} | [
"function svgPoint(element, x, y) {\n var pt = maincanvas.createSVGPoint();\n pt.x = x;\n pt.y = y;\n return pt.matrixTransform(element.getScreenCTM().inverse());\n}",
"function svgPoint(element, x, y) {\n var pt = svg.createSVGPoint();\n pt.x = x;\n pt.y = y;\n var output = pt.matrixTransform(element.getScreenCTM().inverse());\n return output;\n}",
"native () {\n // create new point\n const point = new _dom_svg_SVGPoint_js__WEBPACK_IMPORTED_MODULE_0__.SVGPoint()\n\n // update with current values\n point.x = this.x\n point.y = this.y\n\n return point\n }",
"function newSVGPoint( x, y ) {\n var point = svgRoot.createSVGPoint();\n point.x = x;\n point.y = y;\n return point;\n }",
"function createPoint(x, y) {\n var point = svgRoot.createSVGPoint();\n point.x = x;\n point.y = y;\n return point;\n }",
"function createPoint(x, y) {\n var point = element.viewportElement.createSVGPoint();\n point.x = x;\n point.y = y;\n return point;\n }",
"static convertToPlotPoint(jsonDataPoint) {\n return {\n x: new Date(jsonDataPoint[0] * 1000),\n y: parseFloat(jsonDataPoint[1]),\n };\n }",
"eventCoordsToSVGCoords(x, y) {\n const svg = this.svgSubjectArea;\n const newPoint = svg.createSVGPoint();\n newPoint.x = x;\n newPoint.y = y;\n const matrixForWindowCoordsToSVGUserSpaceCoords = this.getMatrixForWindowCoordsToSVGUserSpaceCoords();\n const pointforSVGSystem = newPoint.matrixTransform(matrixForWindowCoordsToSVGUserSpaceCoords);\n return pointforSVGSystem;\n }",
"function svgFromScreenPoint(pt, svgHtmlElement, svgRootHtmlElement) {\n let svgPt = svgRootHtmlElement.createSVGPoint();\n svgPt.x = pt.x;\n svgPt.y = pt.y;\n const transformedSvgPt = svgPt.matrixTransform(\n svgHtmlElement.getScreenCTM().inverse()\n );\n return new geom.Point(transformedSvgPt.x, transformedSvgPt.y);\n }",
"toSVG() {\n\t\t// first vertex\n\t\tlet points = this.points;\n\t\tlet first = points[0].getPoint();\n\t\tlet x = first.x;\n\t\tlet y = first.y;\n\t\tlet svg = \"M\" + x + (y<0? y : \" \" + y);\n\t\t// rest of the shape\n\t\tfor(let p=1; p<points.length; p++) {\n\t\t\t// since we have to work with point pairs, get \"prev\" and \"current\"\n\t\t\tlet prev = points[p-1];\n\t\t\tlet curr = points[p];\n\t\t\t// if both are plain, LineTo. Otherwise, Cubic bezier.\n\t\t\tif(curr.isPlain() && prev.isPlain()) {\n\t\t\t\tlet lx = curr.getPoint().x; let ly = curr.getPoint().y;\n\t\t\t\tsvg += \"L\" + lx + (ly<0? ly : \" \" + ly); }\n\t\t\telse {\n\t\t\t\tlet cx1 = prev.getRight().x; let cy1 = prev.getRight().y;\n\t\t\t\tlet cx2 = curr.getLeft().x; let cy2 = curr.getLeft().y;\n\t\t\t\tlet x2 = curr.getPoint().x; let y2 = curr.getPoint().y;\n\t\t\t\tsvg += \"C\" + cx1 + (cy1<0? cy1 : \" \" + cy1) +\n\t\t\t\t\t\t(cx2<0? cx2 : \" \" + cx2) + (cy2<0? cy2 : \" \" + cy2) +\n\t\t\t\t\t\t(x2<0? x2 : \" \" + x2) + (y2<0? y2 : \" \" + y2); }}\n\t\treturn svg + \"Z\"; }",
"toPoint() {\n\n // Return a new Point\n return new Point([this.x, this.y, this.z]);\n }",
"function toViewboxCoords( point ) {\n if ( ! svgRoot )\n return false;\n if ( typeof point.pageX !== 'undefined' ) {\n point = newSVGPoint(point.pageX, point.pageY);\n }\n return point.matrixTransform(svgRoot.getScreenCTM().inverse());\n }",
"_createPointElement() {\n const $point = document.createElementNS('http://www.w3.org/2000/svg', 'circle');\n $point.classList.add('acfImageMapPoly__point');\n $point.setAttribute('r', '5');\n return $point;\n }",
"function toPoint(x, y) {\n return { x: x, y: y };\n}",
"toPoint() {\n return new QPoint_1.QPoint(this.native.toPoint());\n }",
"function pointGeom() {\n return {\"type\": \"Point\", \"coordinates\": [_poly[0].lng(), _poly[0].lat()]}\n}",
"function geoToPoint(geoPoint) {\n return { x: geoPoint.longitude, y: geoPoint.latitude };\n}",
"function svgMoveTo(point) {\n return `M${point[0]},${point[1]}`;\n}",
"function Geo_geoToPoint(geoPoint) {\n return { x: geoPoint.longitude, y: geoPoint.latitude };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify duration to be in minutes | function durationInMinutes(duration) {
const match = duration.match(/((\d+)\shrs?)?\s?((\d+)\smin)?/);
const durationString = `${match[2] || '0'}:${match[4] || '00'}`;
return moment.duration(durationString).asMinutes();
} | [
"toMinutes() {\n return MINUTES.convert(this.duration, this.unit);\n }",
"convertSecondsToMinutes(songDuration) {\n const minutes = Math.floor(parseInt(songDuration) / 60000);\n const seconds = ((parseInt(songDuration % 60000) / 1000).toFixed(0));\n const duration = (seconds === 60 ? (minutes + 1) + \":00\" : minutes + \":\" + (seconds < 10 ? \"0\" : \"\") + seconds);\n\n return duration\n }",
"static minutes(amount) {\n return new Duration(amount, TimeUnit.Minutes);\n }",
"function updateDuration() {\n var duration = moment.duration(vm.quizExercise.duration, \"seconds\");\n vm.duration.minutes = 60 * duration.hours() + duration.minutes();\n vm.duration.seconds = duration.seconds();\n }",
"function refresh_time(duration) {\n var mm = Math.floor(Math.floor(duration) / 60) + \"\";\n var ss = Math.ceil(Math.floor(duration) % 60) + \"\";\n\n if (mm.length < 2) { mm = \"0\" + mm; }\n if (ss.length < 2) { ss = \"0\" + ss; }\n container.html(mm + \":\" + ss);\n\n }",
"get minutes() {\n switch (this.unit) {\n case Duration.Unit.MINUTES:\n return this.quantity;\n case Duration.Unit.SECONDS:\n return Math.round(this.quantity / Duration.SECONDS_IN_MINUTE);\n case Duration.Unit.MILLISECONDS:\n return Math.round(this.quantity / Duration.MILLIS_IN_SECONDS / Duration.SECONDS_IN_MINUTE);\n }\n }",
"function turnHoursToMinutes (movie){\n for (var i=0; i<movie.length;i++){\n var horas=parseInt(movie[i].duration.split(\" \")[0].toString().replace('h',''));\n var minutos=parseInt(movie[i].duration.split(\" \")[1].toString().replace('min',''));\n var tiempo=(horas*60)+minutos\n movie[i].duration=tiempo + ' mins';\n }\n return movie\n }",
"function convertDurationToMinutes (durationStr){\n\n var totalMinutes = 0; \n\n var numHours = getNumHours(durationStr);\n var numMinutes = getNumMinutes(durationStr); \n //alert ('h ' + numHours + ' m ' + numMinutes); \n\n totalMinutes = parseInt ((numHours * 60)) + parseInt (numMinutes); \n return totalMinutes; \n} // convertDurationToMinutes",
"function turnHoursToMinutes(movies){\n let moviesCopy = [...movies];\n for (let i=0; i<moviesCopy.length; i++){\n \n let justNumbers = moviesCopy[i].duration.replace(/\\D/g,'');\n let separated = justNumbers.slice(' ');\n moviesCopy[i].duration = (separated[0]*60) + (parseInt(separated[1])*10) + (parseInt(separated[2])); \n }\n return moviesCopy; \n }",
"static minutes(d) {\n return new Duration(d, MINUTES);\n }",
"function turnHoursToMinutes(movies) {\n let duration = \n\n movies.map((oldmovie) => {\n let movie = {...oldmovie};\n let minutes = 0;\n let hours = 0;\n let durationArray = movie.duration.split(\" \");\n \n if (durationArray.length > 1) {\n hours = durationArray[0].split(\"h\")[0] + '';\n hours = parseInt(hours);\n minutes = durationArray[1].split(\"min\")[0] + '';\n minutes = parseInt(minutes);\n } else {\n \n if (durationArray[0].split(\"h\").length > 1){\n hours = durationArray[0].split(\"h\")[0] + '';\n hours = parseInt(hours);\n }\n if (durationArray[0].split(\"min\").length > 1) {\n minutes = durationArray[0].split(\"min\")[0] + '';\n minutes = parseInt(minutes);\n }\n }\n\n let totalminutes = hours * 60 + minutes *1;\n \n let result = hours + \"-\" + minutes + \" = \" + totalminutes;\n movie.duration = totalminutes;\n return movie;\n });\n\n return duration;\n\n}",
"function movieHoursToMinutes(movie){\n let durationArray = movie.duration.split('h');\n let newDuration\n let minutes\n if (durationArray[1] === '') {\n newDuration = parseInt(durationArray[0])*60\n } else {\n if (durationArray.length < 2) {\n minutes = parseInt(durationArray[0]);\n newDuration = minutes;\n } else {\n minutes = parseInt(durationArray[1]);\n newDuration = parseInt(durationArray[0])*60 + minutes;\n }\n }\n let result = newDuration;\n let newMovie = Object.assign({}, movie);\n newMovie.duration = result;\n return newMovie;\n}",
"minutesChanged(v) {\n this.set(\"durationMinutes\",parseInt(v));\n this.validateInput('duration');\n }",
"function getDurationFromMinutes(minutes) {\n \n return ``;\n }",
"get minutes() {\n return Math.floor(this.currentTime / SECONDS_IN_MINUTE) % MINUTES_IN_HOUR;\n }",
"getMinutes() {\n return Math.floor(this.timer / 60);\n }",
"convertToMinutes() {\n let minutes = this._hour * 60 + this._minute;\n return minutes;\n }",
"get toMinutes() {\n const rem = this.toSeconds % this.conv.MINUTE\n return {\n remainderInSeconds: rem,\n numberOfMinutes: (this.toSeconds - rem) / this.conv.MINUTE\n }\n }",
"minutesToString(length) {\n const hours = Math.floor(length / 60);\n const minutes = length % 60;\n return hours.toString() + ' hr ' + minutes.toString() + ' min';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export state of the workspace Note: useful for tagging | export_state() {
let state_metadata = { 'color': {}, 'pinned': {}, 'visibility': {}, 'camera': { 'position': {}, 'up': {} }, 'target': {} };
state_metadata['camera']['position']['x'] = this.camera.position.x;
state_metadata['camera']['position']['y'] = this.camera.position.y;
state_metadata['camera']['position']['z'] = this.camera.position.z;
state_metadata['camera']['up']['x'] = this.camera.up.x;
state_metadata['camera']['up']['y'] = this.camera.up.y;
state_metadata['camera']['up']['z'] = this.camera.up.z;
state_metadata['target']['x'] = this.controls.target.x;
state_metadata['target']['y'] = this.controls.target.y;
state_metadata['target']['z'] = this.controls.target.z;
state_metadata['pinned'] = Array.from(this.uiVars.pinnedObjects);
for (let key in this.meshDict) {
if (this.meshDict.hasOwnProperty(key)) {
state_metadata['color'][key] = this.meshDict[key].object.children[0].material.color.toArray();
state_metadata['visibility'][key] = this.meshDict[key].visibility;
}
}
return state_metadata;
} | [
"export() {\n\t\tconsole.log(JSON.stringify(this.state.notes));\n\t\tconsole.log(this.state.notes);\n\t}",
"function dumpWorkspace (state) {\n const {key, wordCharIndex, wordCipherIndex} = state.workspace;\n return {key, wordCharIndex, wordCipherIndex};\n }",
"export() {\n // const log = this.entities.map(m => m.export()).join(\"\\n---------------------------\\n\");\n // let date = new Date().toDateString().replace(/\\s/g, \"-\");\n // const filename = `fvtt-log-${date}.txt`;\n // saveDataToFile(log, \"text/plain\", filename);\n }",
"saveState() {\n const stateFileName = prompt(\"Filename to save view state as\", 'saved.n2view');\n\n // Solver toggle state.\n let showLinearSolverNames = this.n2Diag.showLinearSolverNames;\n let showSolvers = this.n2Diag.showSolvers;\n\n // Zoomed node (subsystem).\n let zoomedElement = this.n2Diag.zoomedElement.id;\n\n // Expand/Collapse state of all nodes (subsystems) in model.\n let expandCollapse = Array()\n this.n2Diag.getSubState(expandCollapse);\n\n // Arrow State\n let arrowState = this.n2Diag.arrowMgr.savePinnedArrows();\n\n let dataDict = {\n 'showLinearSolverNames': showLinearSolverNames,\n 'showSolvers': showSolvers,\n 'zoomedElement': zoomedElement,\n 'expandCollapse': expandCollapse,\n 'arrowState': arrowState,\n 'md5_hash': this.n2Diag.model.md5_hash,\n };\n\n let link = document.createElement('a');\n link.setAttribute('download', stateFileName);\n let data_blob = new Blob([JSON.stringify(dataDict)],\n { type: 'text/plain' });\n\n // If we are replacing a previously generated file we need to\n // manually revoke the object URL to avoid memory leaks.\n if (stateFileName !== null) {\n window.URL.revokeObjectURL(stateFileName);\n }\n\n link.href = window.URL.createObjectURL(data_blob);\n document.body.appendChild(link);\n\n // wait for the link to be added to the document\n window.requestAnimationFrame(function () {\n var event = new MouseEvent('click');\n link.dispatchEvent(event);\n document.body.removeChild(link);\n })\n }",
"function saveState(state) {\n // Save a copy to the metadata\n utils.setCellMeta(\n cell,\n 'viewCell.outputWidgetState',\n JSON.parse(JSON.stringify(state))\n );\n }",
"function UISaveEngine () {\n const dumpedEngineState = utility.dumpEngine(engineState);\n const engineDataURI =\n 'data:text/plain;charset=utf-8,' + encodeURIComponent(dumpedEngineState);\n let download = document.createElement('a');\n download.setAttribute('href', engineDataURI);\n download.setAttribute('download', 'engine_state.chip8.txt');\n download.style.display = 'none';\n\n document.body.appendChild(download);\n download.click();\n document.body.removeChild(download);\n }",
"function save_and_export() {\r\n\r\n}",
"function saveAndExportCampaignState(){\n var campaign = buildCampaignState()\n var stateString = JSON.stringify(campaign);\n var file = new Blob([stateString], {type: 'application/json'});\n var fileName = `${campaign.campaignInfo.title}-${campaign.campaignInfo.version}.json`;\n promptFileDownload(file, fileName);\n}",
"export() {\n window.open('', null, 'status=yes,toolbar=no,menubar=no,location=no').document.write('<pre>' +\n JSON.stringify(this.state.storytellerData, null, 2) +\n '</pre>');\n }",
"saveState() {\n /**\n * A structure holding the state\n * @member {Object}\n * @property {Object} current current attributes\n * @property {Object} waiting waiting attributes\n * @property {Object} cursor current cursor position\n * @private\n */\n this.savedState = {\n current: Object.assign({}, this.current),\n waiting: Object.assign({}, this.waiting),\n cursor: this.vdu.cursor.saveState()\n }\n }",
"SaveSourceState() {\n\n }",
"function exportAll() {\n if (!outFolder.exists) outFolder.create();\n var savedState = app.activeDocument.activeHistoryState;\n\n // Stores saved layer info: name, coordinates, width and height\n var lyrInfo = \"\";\n\n // Define pixels as unit of measurement\n var defaultRulerUnits = preferences.rulerUnits;\n preferences.rulerUnits = Units.PIXELS;\n\n lyrInfo += scan(doc);\n\n // Resumes back to original ruler units\n preferences.rulerUnits = defaultRulerUnits;\n // Writes stored layer info into single file\n if (saveLyrInfo && lyrInfo != \"\") {\n writeFile(\"ASSET NAME, COORDINATE, WIDTH, HEIGHT\\n\" + lyrInfo, originPath + \"/out/\");\n }\n\n app.activeDocument.activeHistoryState = savedState;\n}",
"function saveState() {\n var currentPositions = map.getPositions();\n var serializedState = '';\n\n serializedState += '1;';\n serializedState += tempo;\n serializedState += ';9;9'; // map size. May be changeable eventually.\n\n currentPositions.positions.forEach(\n\t\t\tfunction (e, i, a) {\n serializedState += ';' + e.position.x + ';' + e.position.y + ';' + e.direction.deltaX + ';' + e.direction.deltaY;\n }\n );\n\n addSavedStateIntoContainers(serializedState);\n }",
"snapshotComponentState() {\n const store = ExperimentView.getLocalStore(this.props.experiment.experiment_id);\n store.saveComponentState(new ExperimentViewPersistedState(this.state.persistedState));\n }",
"function saveWorkspaceToLocalStorage()\n{\n localStorage.setItem(\"__dpt_ide_workspace\", saveCompleteWorkspace());\n}",
"saveState() {\n fs.writeFileSync(this.options.tmpFile, JSON.stringify(this.state));\n }",
"storeState(saveImages=false) {\n this.saveState=this.getElementState(saveImages);\n return;\n }",
"function saveOverviewState() {\n var collapsed = body.querySelectorAll('.todo .hide.hidden'),\n toCollapse = [],\n state = getOverview();\n \n if (collapsed) {\n for (var i = 0; i < collapsed.length; i++) {\n toCollapse.push(collapsed[i].parentNode.id.replace('project_', ''));\n }\n }\n \n state.collapse = toCollapse;\n setOverview(state);\n}",
"async captureCurrentState(data) {\n // double check list of files - not sure if this is necessary\n this.getFilePaths();\n if (!this.filePaths.includes(this.path)) {\n // remove the currently saved report\n this.RNFS.unlink(this.path);\n // writes new state to the path\n this.RNFS.writeFile(this.path, data, \"utf8\")\n .then((success) => {\n console.log(\"Current state saved to: \" + this.path);\n })\n .catch((err) => {\n console.log(\"file write error\");\n console.log(err.message);\n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CTA Change loupe and color button search | function changeColorBtn(e) {
e.preventDefault();
let element = document.getElementById('html').attributes;
if(element[2].value === 'dark') {
// change loupe
let loupe = document.getElementById('loupe');
loupe.src = '/assets/lupa_light.svg';
// change text color button
let textBtn = document.querySelector('#btn-search');
textBtn.style.color = '#FFFFFF';
// change background button search
let color = document.querySelector('.submit');
color.style.background = '#EE3EFE';
color.style.border = '1px solid #110038';
} else {
// change luope
let loupe = document.getElementById('loupe');
loupe.src = '/assets/lupa.svg';
// change text color button
let textBtn = document.querySelector('#btn-search');
textBtn.style.color = '#110038';
// change background button search
let color = document.querySelector('.submit');
color.style.background = '#F7C9F3';
color.style.border = '1px solid #110038';
}
} | [
"function searchColour(colour)\n\t{\n document.getElementById('txtSearch').style.backgroundColor = colour;\n\t}",
"function searchModeDisplay() {\n let colorCodeInput = document.getElementById(\"search-bar\").value;\n\n firstColorBox.style.backgroundColor = colorCodeInput;\n firstColorBox.style.borderBottomLeftRadius = \"0.5rem\";\n firstColorBox.style.borderBottomRightRadius = \"0.5rem\";\n firstColorBox.children[0].children[0].textContent = colorCodeInput;\n\n for (let i = 1; i < bgColors.length; i++) {\n bgColors[i].style.backgroundColor = \"white\";\n bgColors[i].children[0].children[0].textContent = \"\";\n //modify the following part.\n bgColors[i].children[0].children[1].style.backgroundColor = \"white\";\n bgColors[i].children[0].children[1].style.color = \"white\";\n }\n}",
"search() {\n\t\t\t\tconst self=this;\n this.el.querySelector('#global-style-search').addEventListener('input', function (e) {\n const filter = e.target.value.toUpperCase(),\n el=this.el,\n filterByValue=function(){\n const items = el.getElementsByClassName('tb_gs_list')[0].getElementsByClassName('global_style_item');\n for (let i = items.length-1; i>-1 ; --i) {\n let title = items[i].getElementsByClassName('global_style_title')[0];\n if (title) {\n items[i].style.display =title.innerHTML.toUpperCase().indexOf(filter) > -1?'':'none';\n }\n }\n };\n if(self.xhr!==null){\n self.xhr.abort();\n self.xhr=null;\n }\n if(!self.allLoaded){\n setTimeout(function(){\n self.loadMore(filter,filterByValue);\n },100);\n }\n filterByValue();\n }.bind(this),{passive:true});\n }",
"function changeButtonStyle(style) {\n const button = document.getElementById(\"btn-search\");\n const icon = button.querySelector(\".fa\");\n if (style === \"search\") {\n // change button to enable searching\n icon.classList.remove(\"fa-close\");\n icon.classList.add(\"fa-search\");\n button.classList.remove(\"grey\");\n button.classList.add(\"blue\");\n } else {\n // change button to enable canceling a search\n icon.classList.remove(\"fa-search\");\n icon.classList.add(\"fa-close\");\n button.classList.remove(\"blue\");\n button.classList.add(\"grey\");\n }\n}",
"searchButtonClicked() {}",
"function searchNhighlight(searchvalue, search, color)\r\n{\r\n var sub = searchvalue.toLowerCase();\r\n var elements = document.getElementsByClassName(search);\r\n if(sub != '') //if the text box is not empty\r\n for(var i = 0; i < elements.length; i++)\r\n {\r\n var searchin = elements[i].innerText;\r\n var index = searchin.toLowerCase().indexOf(sub);\r\n if( index !=-1)\r\n elements[i].style.backgroundColor= color;\r\n else\r\n elements[i].style.backgroundColor='';\r\n }\r\n else //if the value of text box is empty\r\n for(var i = 0; i < elements.length; i++)\r\n {\r\n elements[i].style.backgroundColor='';\r\n }\r\n}",
"static searchButton(){\n \n document.getElementById('search-button').addEventListener('click',function () {\n const searchText = document.getElementById('search-field').value;\n search.searchText(searchText);\n })\n\n\n }",
"function search() {\n\n\tlet bg_colour = getComputedStyle(document.documentElement).getPropertyValue('--background');\n\tlet title_colour = getComputedStyle(document.documentElement).getPropertyValue('--color7');\n\tlet desc_colour = getComputedStyle(document.documentElement).getPropertyValue('--color7');\n\tlet url_colour = getComputedStyle(document.documentElement).getPropertyValue('--color5');\n\tlet visited_colour = getComputedStyle(document.documentElement).getPropertyValue('--color4');\n\n\twindow.open('https://www.duckduckgo.com/' +\n\t\t\t\t\t\t\t'?q=' + document.getElementsByTagName(\"input\")[0].value +\n\t\t\t\t\t\t\t'&k7=' + bg_colour +\n\t\t\t\t\t\t\t'&kj=' + bg_colour +\n\t\t\t\t\t\t\t'&k9=' + title_colour +\n\t\t\t\t\t\t\t'&k8=' + desc_colour +\n\t\t\t\t\t\t\t'&kx=' + url_colour +\n\t\t\t\t\t\t\t'&kae=' + 't' +\n\t\t\t\t\t\t\t'&kaa=' + visited_colour, '_self');\n\t\n}",
"geosearch(placeholder=\"\") {\n const searchElem = this.search(placeholder);\n const locationButton = this.button(\"\", \"location\");\n const locationIcon = this.faIcon(\"fas\", \"fa-map-marker-alt\")\n\n locationButton.setAttribute(\"type\", \"button\");\n locationButton.append(locationIcon);\n locationButton.addEventListener(\"click\", Utility.getGeolocation);\n searchElem.querySelector(\".search\").before(locationButton);\n\n return searchElem;\n }",
"function search() {\n document.getElementById(\"block-search\").classList.toggle(\"show\");\n }",
"function showSearch() {\r\n // show search button\r\n $('.search-btn').addClass('show');\r\n // hide cancelsearch button\r\n $('.cancelsearch-btn').removeClass('show');\r\n}",
"function changeColor () {\n var searchEle = document.getElementById('search-button');\n searchEle.onmouseover = function() {\n searchEle.style.backgroundColor = '#ed4259';\n }\n searchEle.onmouseout = function() {\n searchEle.style.backgroundColor = '';\n }\n}",
"function setHighlight(value) {\n\n if(value == 0 && !checkClearButton())\n {\n document.getElementById(\"search-button\").style.background = \"none\";\n }\n else\n {\n document.getElementById(\"search-button\").style.background = \"#4d4d4d\";\n }\n}",
"function searchThemes(){\n\tlet filter, txtValue,\n\t\t\tlookup = {};\n\n\tfor(let i = 0; i<data.dataArray.length; i++){\n\t\tlookup[data.dataArray[i].id] = data.dataArray[i];\n\t}\n\n\tfilter = searchInput.value.toUpperCase();\n\n\tfor(let i = 0; i<themeEntries.length; i++){\n\t\ttxtValue = (themeEntries[i].firstChild.innerText || themeEntries[i].firstChild.textContent);\n\n\t\tif(txtValue.toUpperCase().indexOf(filter) > -1){\n themeEntries[i].classList.remove(\"search-hidden\");\n\t\t}else{\n themeEntries[i].classList.add(\"search-hidden\");\n\t\t}\n\t}\n updateNumberOfThemes();\n}",
"search(e) {\n\t\tlet selected = document.querySelector(\".nav__button.active\").innerText.toLowerCase();\n\t\tlet query = e.target.value.toLowerCase();\n\t\titemFunctions.populate(selected, query);\t\t\n\t}",
"clickOnSearchButton() {\n CommonKeywords.Click(this.searchBoxElement)\n }",
"function handleSearchClick() {\n // updateSearchModal(searchRadius, filterCode);\n toggleSearchGraphic();\n $('#searchModal').modal('show');\n}",
"function searchButton() {\n\tvar allOfPictures = document.querySelectorAll(\".picture\");\n\t//The searching keyword typed by the user\n\tvar searchKeyword = document.getElementById(\"searchKeyword\").value;\n\t//User does not type any searching keyword, nothing is highlighted\n\tif (searchKeyword == \"\") {\n\t\tfor (var i = 0; i < allOfPictures.length; i++) {\n\t\t\tmakeClean(allOfPictures[i]);\n\t\t}\n\t} else {\n\t\tfor (var i = 0; i < allOfPictures.length; i++) {\n\t\t\tvar tempNodelist = allOfPictures[i].querySelectorAll(\".title\");\n\t\t\tvar titleOfPicture = tempNodelist[0].innerHTML;\n\t\t\t//Check if the title of this picture contains the user's keyword\n\t\t\tif (titleOfPicture.indexOf(searchKeyword) != -1) {\n\t\t\t\tmakeGreen(allOfPictures[i]);\n\t\t\t} else {\n\t\t\t\tmakeClean(allOfPictures[i]);\n\t\t\t}\n\t\t}\n\t}\n}",
"function setBuddySearchBoxValue()\n{\n var searchBox = document.getElementById(\"buddySearch\");\n \n if(searchBox.value == 'Search Users')\n {\n searchBox.value = '';\n searchBox.style.color = 'black';\n }\n else if(searchBox.value == '')\n {\n searchBox.value = \"Search Users\";\n searchBox.style.color = 'grey';\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the AWS CloudFormation properties of an `AWS::Serverless::Function.DeploymentPreference` resource | function cfnFunctionDeploymentPreferencePropertyToCloudFormation(properties) {
if (!cdk.canInspect(properties)) {
return properties;
}
CfnFunction_DeploymentPreferencePropertyValidator(properties).assertSuccess();
return {
Enabled: cdk.booleanToCloudFormation(properties.enabled),
Type: cdk.stringToCloudFormation(properties.type),
Alarms: cdk.listMapper(cdk.stringToCloudFormation)(properties.alarms),
Hooks: cdk.listMapper(cdk.stringToCloudFormation)(properties.hooks),
};
} | [
"function cfnFunctionDeploymentPreferencePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnFunction_DeploymentPreferencePropertyValidator(properties).assertSuccess();\n return {\n Alarms: cdk.listMapper(cdk.stringToCloudFormation)(properties.alarms),\n Enabled: cdk.booleanToCloudFormation(properties.enabled),\n Hooks: cfnFunctionHooksPropertyToCloudFormation(properties.hooks),\n Type: cdk.stringToCloudFormation(properties.type),\n };\n}",
"renderProperties(x) { return ui.divText(`Properties for ${x.name}`); }",
"function functionResourceTracingConfigPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n FunctionResource_TracingConfigPropertyValidator(properties).assertSuccess();\n return {\n Mode: cdk.stringToCloudFormation(properties.mode),\n };\n }",
"function cfnDeploymentDeploymentCanarySettingsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeployment_DeploymentCanarySettingsPropertyValidator(properties).assertSuccess();\n return {\n PercentTraffic: cdk.numberToCloudFormation(properties.percentTraffic),\n StageVariableOverrides: cdk.hashMapper(cdk.stringToCloudFormation)(properties.stageVariableOverrides),\n UseStageCache: cdk.booleanToCloudFormation(properties.useStageCache),\n };\n}",
"function cfnDeploymentCanarySettingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeployment_CanarySettingPropertyValidator(properties).assertSuccess();\n return {\n PercentTraffic: cdk.numberToCloudFormation(properties.percentTraffic),\n StageVariableOverrides: cdk.hashMapper(cdk.stringToCloudFormation)(properties.stageVariableOverrides),\n UseStageCache: cdk.booleanToCloudFormation(properties.useStageCache),\n };\n}",
"function versionResourcePropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n VersionResourcePropsValidator(properties).assertSuccess();\n return {\n FunctionName: cdk.stringToCloudFormation(properties.functionName),\n CodeSha256: cdk.stringToCloudFormation(properties.codeSha256),\n Description: cdk.stringToCloudFormation(properties.description),\n };\n }",
"function cfnApiCanarySettingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnApi_CanarySettingPropertyValidator(properties).assertSuccess();\n return {\n DeploymentId: cdk.stringToCloudFormation(properties.deploymentId),\n PercentTraffic: cdk.numberToCloudFormation(properties.percentTraffic),\n StageVariableOverrides: cdk.hashMapper(cdk.stringToCloudFormation)(properties.stageVariableOverrides),\n UseStageCache: cdk.booleanToCloudFormation(properties.useStageCache),\n };\n}",
"function cfnDeploymentStageDescriptionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeployment_StageDescriptionPropertyValidator(properties).assertSuccess();\n return {\n AccessLogSetting: cfnDeploymentAccessLogSettingPropertyToCloudFormation(properties.accessLogSetting),\n CacheClusterEnabled: cdk.booleanToCloudFormation(properties.cacheClusterEnabled),\n CacheClusterSize: cdk.stringToCloudFormation(properties.cacheClusterSize),\n CacheDataEncrypted: cdk.booleanToCloudFormation(properties.cacheDataEncrypted),\n CacheTtlInSeconds: cdk.numberToCloudFormation(properties.cacheTtlInSeconds),\n CachingEnabled: cdk.booleanToCloudFormation(properties.cachingEnabled),\n CanarySetting: cfnDeploymentCanarySettingPropertyToCloudFormation(properties.canarySetting),\n ClientCertificateId: cdk.stringToCloudFormation(properties.clientCertificateId),\n DataTraceEnabled: cdk.booleanToCloudFormation(properties.dataTraceEnabled),\n Description: cdk.stringToCloudFormation(properties.description),\n DocumentationVersion: cdk.stringToCloudFormation(properties.documentationVersion),\n LoggingLevel: cdk.stringToCloudFormation(properties.loggingLevel),\n MethodSettings: cdk.listMapper(cfnDeploymentMethodSettingPropertyToCloudFormation)(properties.methodSettings),\n MetricsEnabled: cdk.booleanToCloudFormation(properties.metricsEnabled),\n Tags: cdk.listMapper(cdk.cfnTagToCloudFormation)(properties.tags),\n ThrottlingBurstLimit: cdk.numberToCloudFormation(properties.throttlingBurstLimit),\n ThrottlingRateLimit: cdk.numberToCloudFormation(properties.throttlingRateLimit),\n TracingEnabled: cdk.booleanToCloudFormation(properties.tracingEnabled),\n Variables: cdk.hashMapper(cdk.stringToCloudFormation)(properties.variables),\n };\n}",
"function cfnDeploymentPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeploymentPropsValidator(properties).assertSuccess();\n return {\n RestApiId: cdk.stringToCloudFormation(properties.restApiId),\n DeploymentCanarySettings: cfnDeploymentDeploymentCanarySettingsPropertyToCloudFormation(properties.deploymentCanarySettings),\n Description: cdk.stringToCloudFormation(properties.description),\n StageDescription: cfnDeploymentStageDescriptionPropertyToCloudFormation(properties.stageDescription),\n StageName: cdk.stringToCloudFormation(properties.stageName),\n };\n}",
"function permissionResourcePropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n PermissionResourcePropsValidator(properties).assertSuccess();\n return {\n Action: cdk.stringToCloudFormation(properties.action),\n FunctionName: cdk.stringToCloudFormation(properties.functionName),\n Principal: cdk.stringToCloudFormation(properties.principal),\n EventSourceToken: cdk.stringToCloudFormation(properties.eventSourceToken),\n SourceAccount: cdk.stringToCloudFormation(properties.sourceAccount),\n SourceArn: cdk.stringToCloudFormation(properties.sourceArn),\n };\n }",
"function spotFleetResourceSpotFleetMonitoringPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n SpotFleetResource_SpotFleetMonitoringPropertyValidator(properties).assertSuccess();\n return {\n Enabled: cdk.booleanToCloudFormation(properties.enabled),\n };\n }",
"function launchTemplateResourceSpotOptionsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n LaunchTemplateResource_SpotOptionsPropertyValidator(properties).assertSuccess();\n return {\n InstanceInterruptionBehavior: cdk.stringToCloudFormation(properties.instanceInterruptionBehavior),\n MaxPrice: cdk.stringToCloudFormation(properties.maxPrice),\n SpotInstanceType: cdk.stringToCloudFormation(properties.spotInstanceType),\n };\n }",
"function renderProperties(setup) {\n // print available exams\n var html = '';\n if (!('localStorage' in window)) {\n html += warning(getMessage('msg_options_change_disabled', 'Changing options is disabled, because your browser does not support localStorage.'));\n }\n for (var section in setup) {\n if (setup[section].opts.length) {\n html += '<p class=\"opts-header\">' + getMessage(section + '_label', setup[section].label) + '</p>';\n html += '<div class=\"list-group\">';\n for (var p in setup[section].opts) {\n html += prepareProperty(setup[section].opts[p]);\n }\n html += '</div>';\n }\n }\n renderElement('#app-properties', html);\n}",
"function cfnDeploymentMethodSettingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeployment_MethodSettingPropertyValidator(properties).assertSuccess();\n return {\n CacheDataEncrypted: cdk.booleanToCloudFormation(properties.cacheDataEncrypted),\n CacheTtlInSeconds: cdk.numberToCloudFormation(properties.cacheTtlInSeconds),\n CachingEnabled: cdk.booleanToCloudFormation(properties.cachingEnabled),\n DataTraceEnabled: cdk.booleanToCloudFormation(properties.dataTraceEnabled),\n HttpMethod: cdk.stringToCloudFormation(properties.httpMethod),\n LoggingLevel: cdk.stringToCloudFormation(properties.loggingLevel),\n MetricsEnabled: cdk.booleanToCloudFormation(properties.metricsEnabled),\n ResourcePath: cdk.stringToCloudFormation(properties.resourcePath),\n ThrottlingBurstLimit: cdk.numberToCloudFormation(properties.throttlingBurstLimit),\n ThrottlingRateLimit: cdk.numberToCloudFormation(properties.throttlingRateLimit),\n };\n}",
"function cfnDeploymentDeploymentPoliciesPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeployment_DeploymentPoliciesPropertyValidator(properties).assertSuccess();\n return {\n ComponentUpdatePolicy: cfnDeploymentDeploymentComponentUpdatePolicyPropertyToCloudFormation(properties.componentUpdatePolicy),\n ConfigurationValidationPolicy: cfnDeploymentDeploymentConfigurationValidationPolicyPropertyToCloudFormation(properties.configurationValidationPolicy),\n FailureHandlingPolicy: cdk.stringToCloudFormation(properties.failureHandlingPolicy),\n };\n}",
"function cfnStageCanarySettingPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStage_CanarySettingPropertyValidator(properties).assertSuccess();\n return {\n DeploymentId: cdk.stringToCloudFormation(properties.deploymentId),\n PercentTraffic: cdk.numberToCloudFormation(properties.percentTraffic),\n StageVariableOverrides: cdk.hashMapper(cdk.stringToCloudFormation)(properties.stageVariableOverrides),\n UseStageCache: cdk.booleanToCloudFormation(properties.useStageCache),\n };\n}",
"function cfnDeploymentPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeploymentPropsValidator(properties).assertSuccess();\n return {\n ApiId: cdk.stringToCloudFormation(properties.apiId),\n Description: cdk.stringToCloudFormation(properties.description),\n StageName: cdk.stringToCloudFormation(properties.stageName),\n };\n}",
"function cfnDeploymentStrategyPropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDeploymentStrategyPropsValidator(properties).assertSuccess();\n return {\n DeploymentDurationInMinutes: cdk.numberToCloudFormation(properties.deploymentDurationInMinutes),\n GrowthFactor: cdk.numberToCloudFormation(properties.growthFactor),\n Name: cdk.stringToCloudFormation(properties.name),\n ReplicateTo: cdk.stringToCloudFormation(properties.replicateTo),\n Description: cdk.stringToCloudFormation(properties.description),\n FinalBakeTimeInMinutes: cdk.numberToCloudFormation(properties.finalBakeTimeInMinutes),\n GrowthType: cdk.stringToCloudFormation(properties.growthType),\n Tags: cdk.listMapper(cfnDeploymentStrategyTagsPropertyToCloudFormation)(properties.tags),\n };\n}",
"function loadBalancerResourceAccessLoggingPolicyPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n LoadBalancerResource_AccessLoggingPolicyPropertyValidator(properties).assertSuccess();\n return {\n EmitInterval: cdk.numberToCloudFormation(properties.emitInterval),\n Enabled: cdk.booleanToCloudFormation(properties.enabled),\n S3BucketName: cdk.stringToCloudFormation(properties.s3BucketName),\n S3BucketPrefix: cdk.stringToCloudFormation(properties.s3BucketPrefix),\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run: calls itself every time the browser is ready for rendering a frame draws the Scene | function run() {
/**
tell the browser to call the function 'run' whenever it is ready to re-render the 'canvas'
this assures that the demo runs at a good framerate
and is only called when the browser-tap of the demo is in focus
*/
requestAnimationFrame( run, canvas );
/**
render the scene
*/
Scene.draw( gl );
} | [
"function renderScene() {\n if (m_initialized === false) {\n initScene();\n }\n m_viewer.render();\n }",
"draw() {\n this.renderScene();\n }",
"function renderLoop() {\r\n requestAnimFrame(renderLoop);\r\n drawScene();\r\n}",
"function render() {\n if (running) {\n worldRenderer.render(worldTrans);\n $window.requestAnimationFrame(render);\n }\n }",
"function render() {\n var now = Date.now();\n sceneContainer.render(now);\n}",
"function render()\n {\n sceneManager.render();\n }",
"_render() {\n\t\tthis._stats.begin();\n\t\tthis._renderer.render(this.stage);\n\t\tthis._stats.end();\n\t}",
"function runAnimation() {\r\n checkGameStatus();\r\n gameRunning = requestAnimationFrame(runAnimation);\r\n\r\n updatePos();\r\n\r\n paper.view.draw();\r\n }",
"draw() {\n // push the scene objects to the scene array\n this.prepareScene();\n\n // call each object's draw method\n this.drawSceneToCanvas();\n }",
"draw() {\n this.currentScene.draw()\n }",
"function run() {\n this.animation();\n if (this.id !== null) { this.id = requestAnimationFrame(run.bind(this)); }\n }",
"function renderFrame() {\n // add frame to time tracker\n frames++;\n\n applyAnimations();\n\n // render shadow maps\n renderShadowMap();\n\n // render all cube maps\n generateCubeMaps();\n\n // render scene\n renderScene(getView(), data.P, -1);\n\n requestAnimFrame(renderFrame);\n}",
"run() {\n this._timer.run();\n this.render();\n }",
"function runGame(){\n requestAnimationFrame(drawComponents);\n}",
"function render() {\n window.requestAnimFrame(render, canvas); // loop\n\n currentGame.render();\n animate();\n}",
"function render()\n{\n\trequestAnimationFrame(render);\n\tanimation();\n\trenderer.render(scene, camera);\n}",
"function run(){\n\n\ttheModel.update();\n\ttheView.draw();\n\n\tif (theModel.running)\n\t\twindow.requestAnimationFrame(run);\n}",
"function drawScene()\n\t{\n\t\t//Get ready to draw\n\t\tprepareForDrawing();\n\n\t\tdrawBodyScene();\n\t\tdrawHeadScene();\n\t\tdrawCookieScene();\n\t\tdrawGiveCookieScene();\n\t\tdrawLeftEyeScene();\n\t\tdrawRightEyeScene();\n\t\tdrawLeftForeArmScene();\n\t\tdrawLeftUpperArmScene();\n\t\tdrawRightForeArmScene();\n\t\tdrawRightUpperArmScene();\n\t}",
"render()\n\t\t{\n\t\t\tthis._renderer.render(this._scene, this._camera);\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CONCATENATED MODULE: ./src/components/Login/LoginSuccess.jsx / Copyright 2019 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | function LoginSuccess() {
return /*#__PURE__*/react_default.a.createElement(react_default.a.Fragment, null, /*#__PURE__*/react_default.a.createElement(components_LogoHero, null), /*#__PURE__*/react_default.a.createElement(design_src["j" /* CardSuccessLogin */], null));
} | [
"function Logout() {\r\n return (\r\n <div>\r\n This is the Logout component\r\n </div>\r\n )\r\n}",
"function AuthFailedPage () {\n return <div>Sorry! It looks like there was a problem trying to log in.</div>\n}",
"welcome() {\r\n if (this.props.user && this.props.user.displayName) {\r\n return <div>Welcome {this.props.user.displayName}</div>\r\n }\r\n }",
"render(){\n return (\n <form onSubmit={this.handleLogin}>\n <fieldset>\n <h3>Sign In</h3>\n <div className=\"login\">\n <label htmlFor=\"inputUsername\">Username</label>\n <input onChange={this.handleFieldChange} type=\"username\"\n id=\"username\"\n placeholder=\"Username\"\n required=\"\"\n autoFocus=\"\" />\n <label htmlFor=\"inputPassword\">Password</label>\n <input onChange={this.handleFieldChange} type=\"password\"\n id=\"password\"\n placeholder=\"Password\"\n required=\"\" />\n </div>\n <Button variant=\"light\" type=\"submit\">Sign In</Button>\n </fieldset>\n </form>\n )\n }",
"function Welcome() {\n return <div>Welcome to React!</div>;\n}",
"function LoginArea(){\n return(\n <div id=\"row\">\n <h4 id=\"log_sign\" name=\"login\" onClick={logging_in}>Login</h4><h4 id=\"log_sign\" name=\"signup\" onClick={signing_up}>Sign up</h4>\n </div>\n )\n}",
"render () {\n if (this.state.logInStatus) {\n return <Redirect to=\"/dashboard\" />;\n }\n return (\n <CardComponent info='You need to click on the button to login:)'>\n <div className=\"jumbotron\">\n <input className=\"form-control\" type=\"text\" onChange={this.handleLoginCredential}/> <br/>\n <button type=\"button\" className=\"btn btn-success\" onClick={this.logInChecker}>Login</button>\n </div>\n </CardComponent>\n );\n }",
"onLoginPressed() {\n if (!this.props.accsessToken) {\n this.props.authLoading(true);\n this.props.userLogin({\n email: this.state.email,\n password: this.state.password\n });\n } else {\n return Alert.alert('', 'Please logout first');\n }\n }",
"function Welcome(){\n return <h1>{t('welcome_page_title')}</h1>\n}",
"getComponent(nextState, next) {\n /* Webpack - use 'require.ensure' to create a split point\n and embed an async module loader (jsonp) when bundling */\n require.ensure([\n './containers/ResourcesContainer',\n // './modules/users'\n ], (require) => {\n /* Webpack - use require callback to define\n dependencies for bundling */\n const Resources = require('./containers/ResourcesContainer').default\n\n /* Return getComponent */\n next(null, permissionIsAuthenticated(Resources))\n })\n }",
"function StaffProfiles() {\n return (\n <div className=\"StaffProfiles\">\n <h1>StaffProfiles Component</h1>\n\n </div>\n );\n}",
"function SecretComponents() {\n return (\n <h1>Super secret infromation for authorized users only</h1>\n )\n}",
"function UserGreeting (props) {\n\treturn <h1>Welcome</h1>\n}",
"render () {\n\t\treturn <>\n\t\t\t<article className=\"modal bg-dark fade\" id=\"LoginModal\" tabIndex=\"-1\" role=\"dialog\" aria-labelledby=\"LoginModal\" aria-hidden=\"true\">\n\t\t\t\t<div className=\"modal-dialog modal-dialog-centered\" role=\"document\">\n\t\t\t\t\t<div className=\"modal-content\">\n\t\t\t\t\t\t<div className=\"modal-header\">\n\t\t\t\t\t\t\t<h5 className=\"h2 modal-title text-mariana\">Adventure Archive</h5>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div className=\"modal-body py-4\">\n\t\t\t\t\t\t\t<FloatingLabel\n\t\t\t\t\t\t\t\ttype=\"text\"\n\t\t\t\t\t\t\t\tlabel=\"Username\"\n\t\t\t\t\t\t\t\tid=\"loginInput\"\n\t\t\t\t\t\t\t\tclassName=\"form-control\" />\n\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div className=\"modal-footer\">\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\tclassName=\"btn btn-mariana\"\n\t\t\t\t\t\t\t\tdata-dismiss=\"modal\"\n\t\t\t\t\t\t\t\taria-label=\"close login\"\n\t\t\t\t\t\t\t\tonClick={() => this.props.loginCallback($(\"#loginInput\")[0].value)}>\n\t\t\t\t\t\t\t\t\tLogin\n\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</article>\n\t\t</>;\n\t}",
"checkLogin() {\n if(Auth.isUserAuthenticated()) {\n return (\n <CommentForm \n onSubmit={this.processForm}\n onChange={this.commentChange}\n successMessage={this.state.successMessage}\n errors={this.state.errors}\n commentData={this.state.commentData}\n />\n );\n } else {\n return (\n <div>\n <p>You must be logged in to post a comment. Login <a href=\"/login\">here</a>.</p> \n </div>\n );\n }\n }",
"displayVerifyError(){\n if (this.state.verifyErr) {\n return (<div className=\"errorMsg\">The account has not been verified.</div>)\n }\n }",
"async showLoginForm() {\n const ctx = this.ctx;\n await ctx.render('auth/login');\n }",
"render() {\n return (\n <h1>GitHub OAuth2</h1>\n );\n }",
"createWelcome() {\n return (\n <div className=\"welcome-message\">\n <div></div>\n <div className=\"center-white-text\">\n <div className=\"larger-font-size\">\n <span>Welcome to the </span>\n <span className=\"bold-text\">\n <span>Rubrik GraphQL Playground</span>\n </span>\n </div>\n </div>\n <div className=\"bottom-white-small-text\">\n <span className=\"thin-text\">\n <span>Don't Backup. </span>\n </span>\n <span>Go Forward.</span>\n </div>\n </div>\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
edit restaurant. only one update needed due to reference data. | function editRestaurant(req ,res) {
let _id = req.params.id;
let rest = req.body;
db.Restaurant.findOne({_id}, function(err, restaurant){
restaurant = rest;
restaurant.save();
res.json(restaurant);
});
} | [
"function editRestaurant(req, res, next) {\n var id = req.session.user.id;\n var restaurant = req.restaurant;\n DBController.editRestaurantById(id, restaurant, function(err, result) {\n if (err) throw err;\n next();\n });\n}",
"async edit ({ view, params, auth }) {\n /**\n * Find the restaurant with the `id` and was created\n * by the currently logged in user.\n */\n const restaurant = await auth.user.restaurants().where('id', params.id).firstOrFail()\n\n /**\n * Render the restaurant editing form\n */\n return view.render('restaurants.edit', { restaurant: restaurant.toJSON() })\n }",
"function updateRestaurant(self) {\n var name = $('#edit-restaurant-name').val();\n var location = $('#edit-restaurant-location').val();\n var desc = $('#edit-restaurant-desc').val();\n var image = $('#edit-restaurant-image').val();\n\n Restaurant.updateRestaurant(restaurantid, name, location, desc, image)\n .then(function success(result) {\n $('#restaurant-edit-form').css('top', '-300px');\n $('#restaurant-name').html(result.name);\n $('#restaurant-location').html(result.location);\n $('#restaurant-desc').html(result.description);\n if (result.image) {\n $('#restaurant-cover-img').attr('src', result.image);\n $('#restaurant-image').attr('src', result.image);\n } else {\n $('#restaurant-cover-img').attr('src',\n '/assets/img/default-restaurant-img.png');\n $('#restaurant-image').attr('src',\n '/assets/img/default-restaurant-img.png');\n }\n },\n function fail(xhr, statusText, error) {\n alert(error + ':' + xhr.responseText);\n });\n }",
"update(id, restaurant) {\n return 1;\n }",
"function edit() {\n\t\t\t$state.go('^.edit', {'id': vm.flight._id});\n\t\t}",
"function handleFoodEditClick(e) {\n var $foodRow = $(this).closest('.food');\n var foodId = $foodRow.data('food-id');\n // remove console logs from production\n console.log('edit food', foodId);\n console.log($foodRow);\n\n // show the save changes button\n $foodRow.find('.save-food').toggleClass('hidden');\n // hide the edit button\n $foodRow.find('.edit-food').toggleClass('hidden');\n\n\n // get the food name and replace its field with an input element\n var foodName = $foodRow.find('span.food-name').text();\n $foodRow.find('span.food-name').html('<input class=\"edit-food-name\" value=\"' + foodName + '\"></input>');\n\n // get the calories and replace its field with an input element\n var calories = $foodRow.find('span.calories').text();\n $foodRow.find('span.calories').html('<input class=\"edit-calories\" value=\"' + calories + '\"></input>');\n\n }",
"function editEntry(entryId, entry) {\n return Restangular.one(foodDiaryEndpoint, entryId).customPUT(entry);\n }",
"async update ({ request, view, params, response, session, auth }) {\n /**\n * Find the restaurant with the `id` and was created\n * by the currently logged in user.\n */\n const restaurant = await auth.user.restaurants().where('id', params.id).firstOrFail()\n\n /**\n * The data we want to consume for updating the restaurant\n */\n const payload = request.only(['name', 'address', 'min_price', 'max_price', 'url', 'opens_at', 'closes_at'])\n\n const coverImage = request.file('cover_image')\n\n /**\n * If new cover image was uploaded, then re-upload it\n */\n if (coverImage) {\n payload.cover_image = `${new Date().getTime()}.${coverImage.extname}`\n await coverImage.move(Helpers.tmpPath('uploads'), {\n name: payload.cover_image\n })\n }\n\n /**\n * The merge method does all the magic of finding if the values\n * were changed or not\n */\n restaurant.merge(payload)\n\n /**\n * Finally update the restaurant. The update query is only executed, if\n * something was changed\n */\n await restaurant.save()\n\n /**\n * Send a flash success message\n */\n session.flash({ notification: 'Restaurant updated successfully' })\n\n /**\n * Send the user back to the old page\n */\n response.redirect('back')\n }",
"async edit ({ params, request, response, view }) {\n }",
"handleEdit() {\n if (this.state.editable) {\n let dish = {\n id: this.props.dish.id,\n name: this.name.value,\n description: this.description.value\n }\n API.updateDish(dish).then(dish => {\n this.setState({ dish: dish });\n });\n }\n this.setState({\n editable: !this.state.editable\n });\n }",
"function update(req, res) {\n // find one restaurant by id, update it based on request body, and send it back as JSON\n db.Restaurant.findById(req.params.id, function(err, foundRestaurant) {\n if (err) { console.log('restaurantController.update error', err); }\n foundRestaurant.name = req.body.name;\n foundRestaurant.address = req.body.address;\n foundRestaurant.typeOfFood = req.body.typeOfFood;\n foundRestaurant.price = req.body.price;\n foundRestaurant.parking = req.body.parking;\n foundRestaurant.servesAlcohol = req.body.servesAlcohol;\n foundRestaurant.lateNight = req.body.lateNight;\n foundRestaurant.tags = req.body.tags;\n\n foundRestaurant.save(function(err, savedRestaurant) {\n if (err) { console.log('saving altered restaurant failed'); }\n res.json(savedRestaurant);\n });\n });\n}",
"function editTrip () {\n\t\t// Get data from selected trip from local storage\n\t\tvar value = localStorage.getItem(this.key);\n\t\tvar trip = JSON.parse(value);\n\n\t\t$('formTitle').innerHTML = \"Edit Trip\";\n\t\ttoggleDisplay(\"off\");\n\t\t\n\t\t$('travelMethod').value = trip.method[1];\n\t\t$('dest').value = trip.dest[1];\n\t\t$('date').value = trip.date[1];\n\t\t$('numPeople').value = trip.people[1];\n\t\t$('notes').value = trip.notes[1];\n\n\t\tvar radios = document.forms[0].tripType;\n\t\tfor (var i = 0; i < radios.length; i++){\n\t\t\tif (radios[i].value == \"Business\" && trip.type[1] == \"Business\") {\n\t\t\t\tradios[i].setAttribute(\"checked\", \"checked\");\n\t\t\t} else if (radios[i].value == \"Vacation\" && trip.type[1] == \"Vacation\") {\n\t\t\t\tradios[i].setAttribute(\"checked\", \"checked\");\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Remove the initial listener from 'Add Trip' button\n\t\taddButton.removeEventListener(\"click\", storeData);\n\t\t\n\t\t// Change 'Add Trip' button to 'Update Trip'\n\t\t$('addTrip').value = \"Update Trip\";\n\t\tvar updateTrip = $('addTrip');\n\t\tupdateTrip.addEventListener(\"click\", validateForm);\n\t\tupdateTrip.key = this.key;\t// Saves key value as property of update button event\n\t}",
"function editTrip () {\n\t\t// Get data from selected trip from local storage\n\t\tvar value = localStorage.getItem(this.key);\n\t\tvar trip = JSON.parse(value);\n\n\t\t$('formTitle').innerHTML = \"Edit Trip\";\n\t\t\n\t\t$('travelMethod').value = trip.method[1];\n\t\t$('dest').value = trip.dest[1];\n\t\t$('date').value = trip.date[1];\n\t\t$('numPeople').value = trip.people[1];\n\t\t$('notes').value = trip.notes[1];\n\n\t\tvar radios = document.forms[0].tripType;\n\t\tfor (var i = 0; i < radios.length; i++){\n\t\t\tif (radios[i].value == \"Business\" && trip.type[1] == \"Business\") {\n\t\t\t\tradios[i].setAttribute(\"checked\", \"checked\");\n\t\t\t} else if (radios[i].value == \"Vacation\" && trip.type[1] == \"Vacation\") {\n\t\t\t\tradios[i].setAttribute(\"checked\", \"checked\");\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Remove the initial listener from 'Add Trip' button\n\t\taddButton.removeEventListener(\"click\", storeData);\n\t\t\n\t\t// Change 'Add Trip' button to 'Update Trip'\n\t\t$('addTrip').value = \"Update Trip\";\n\t\tvar updateTrip = $('addTrip');\n\t\tupdateTrip.addEventListener(\"click\", validateForm);\n\t\tupdateTrip.key = this.key;\t// Saves key value as property of update button event\n\t}",
"static editSupplier(req, res) {\n\t\tlet idNum = parseInt(req.params.id.split('')[1]);\n\t\tconsole.log('idNum is ' + idNum);\n\t\tlet obj = {\n\t\t\tname: req.body.name,\n\t\t\tkota: req.body.kota\n\t\t};\n\t\tSupplier.update(obj, {\n\t\t\twhere: {\n\t\t\t\tid: idNum\n\t\t\t}\n\t\t})\n\t\t\t.then((data) => {\n\t\t\t\tconsole.log('succesfully updated Supplier');\n\t\t\t\tres.redirect('/suppliers');\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.log(err);\n\t\t\t});\n\t}",
"function editRoute(req, res) {\n Trip\n .findById(req.params.id)\n .exec()\n .then((trip) => {\n if(!trip) return res.notFound();\n res.render('trips/edit', { trip });\n })\n .catch((err) => {\n res.badRequest(500, err);\n });\n}",
"function editarEndereco(enderecoPesq) {\n\t\t\t$scope.novoEndereco = enderecoPesq;\n\t\t\tidEndereco = $scope.novoEndereco.Id;\n\n\t\t\tloadCidade(enderecoPesq.EstadoId);\n\n\t\t\tloadBairro(enderecoPesq.CidadeId);\n\n\t\t}",
"async editTripByID(req, res, next) {\n const { _id = null } = req.params;\n const places = req.body;\n\n const result = await tripModel.updateOne({ _id }, { places })\n if(result){\n res.status(200).send({\"edited\":_id})\n }\n else{\n res.status(404).send({\"error\":\"wrong params or not found\"})\n }\n }",
"function editRecipe() {\n displayEditForm();\n }",
"updateItin() {\n const { id, editItinerary } = this.props;\n\n editItinerary(id);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
findInArray() returns an array of strings ("matches") that do not have the inputed prefix | function findInArray(prefix, array) {
const matches = [];
for (let string of array) {
if (!string.startsWith(prefix)) matches.push(string);
}
returnMatches(matches);
} | [
"function findNoPrefix( prefix, haystack ) {\n var len = haystack.length,\n no_prefix = [];\n \n for( let n=0; n < len; n++ )\n if( !hasPrefix( prefix, haystack[n] ) ) no_prefix.push( haystack[n] );\n \n return no_prefix;\n}",
"startsWithInArray(prefix, array) {\n return array.find((element) => element.startsWith(prefix));\n }",
"function bSearchWords(arr, prefix) {\n if (!prefix) return arr;\n\n arr.sort();\n let low = 0;\n let high = arr.length - 1;\n\n while (low <= high) {\n if (arr[low].startsWith(prefix) && arr[high].startsWith(prefix)) return arr.slice(low, high + 1);\n\n if (!arr[low].startsWith(prefix)) {\n low += 1;\n }\n\n if (!arr[high].startsWith(prefix)) {\n high -= 1;\n }\n \n if (low > high) return [];\n\n let mid = Math.floor(low + (high - low) / 2);\n\n if (arr[mid].startsWith(prefix)) {\n // have to find new low and high\n } else if (arr[mid] > prefix && !arr[mid].startsWith(prefix)) {\n high = mid - 1;\n } else if (arr[mid] < prefix && !arr[mid].startsWith(prefix)) {\n low = mid + 1;\n }\n }\n\n return [];\n}",
"function arrayContainsPrefix( curArr, item )\n{\n var itemLength = item.length;\n var nElements = curArr.length;\n for( var i = 0; i < nElements; i++ )\n {\n var curItem = curArr[i];\n if ( curItem.length <= itemLength &&\n curItem == item.substring(0, curItem.length) )\n return true;\n }\n\n return false;\n}",
"function findAllMatches(prefix, arrayOfTerms) {\n arrayOfTermsCopy = arrayOfTerms.slice();\n matches = [];\n indexOfFound = 0;\n while (indexOfFound != -1) {\n indexOfFound = binaryIndexOf(prefix, arrayOfTermsCopy)\n if(indexOfFound != -1)\n matches.push(arrayOfTermsCopy.splice(indexOfFound, 1)[0]);\n }\n matches.sort(compareByReverseWeightOrder);\n return matches;\n}",
"function onlyIncludes (array, str) {\n\n}",
"static _arrayStartsWith(array, prefix)\n {\n if(array.length < prefix.length)\n return false;\n\n for(let i = 0; i < prefix.length; ++i)\n if(array[i] != prefix[i])\n return false;\n return true;\n }",
"function matchString(arr) {\n // construct a regexp to match the\n var prefixes = [];\n for each (var a in arr) {\n for (var i=1;i<=a.length;i++) {\n prefixes.push(a.slice(0,i));\n }\n }\n return prefixes.reverse().join('|');\n }",
"function onlyIncludes(array, str) {\n return array.filter((item) => item.indexOf(str) !== -1)\n}",
"function filterEmp (emps,prefix){\n let result = [];\n for (let i = 0; i < emps.length; i++){\n if(emps[i].startsWith(prefix)){\n result.push(emps[i]);\n }\n }\n return result;\n\n}",
"function hasPrefix(data) {\n var strings = [];\n for (var str in data.array) {\n if (!data.array[str].startsWith(data.prefix))\n strings.push(data.array[str]);\n }\n $.post(validatePrefixAPI, {\n token: key,\n array: strings\n }, function (data) {\n console.log(data);\n });\n }",
"function isStartInArray (array, string) {\n\tfor (var i in array) {\n\t\tif (string.indexOf(array[i]) == 0) {\n\t\t\treturn true;\n\t\t};\t\t\n\t}\n\treturn false;\n}",
"function match(prefixes, numbers) {\n let result = new Array(numbers.length).fill('')\n for (let i = 0; i < numbers.length ; i++) {\n for (let y = 0; y < prefixes.length ; y++) {\n let preLen = prefixes[y].length\n if (numbers[i].slice(0, preLen) === prefixes[y] && prefixes[y].length > result[i].length) result[i] = prefixes[y]\n }\n }\n return result\n}",
"static isPrefixArray(needle, haystack) {\n if (needle.length > haystack.length) {\n return false;\n }\n for (let i = 0; i < needle.length; i++) {\n if (needle[i] !== haystack[i]) {\n return false;\n }\n }\n return true;\n }",
"function match(word, array, caseSensitive) {\n\t\treturn $.grep(\n\t\t\tarray,\n\t\t\tfunction(w) {\n\t\t\t\tif (caseSensitive) {\n\t\t\t\t\treturn !w.indexOf(word);\n\t\t\t\t} else {\n\t\t\t\t\treturn !w.toLowerCase().indexOf(word.toLowerCase());\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}",
"function arraySubstring(words, str)\n{\n let itsIn = [];\n for (let i = 0; i < words.length; i++)\n {\n if (words[i].search(str) !== -1)\n {\n itsIn[i] = true;\n }\n else\n {\n itsIn[i] = false;\n }\n }\n return itsIn;\n}",
"function getUniqueName(prefix, arrayToSearch)\n{\n var retVal = prefix;\n var count = 0;\n \n if (arrayToSearch != null && arrayToSearch.length > 0)\n {\n var matchFn = new Function(\"object,searchValue\", \"return (object.name == searchValue);\");\n\n while (dwscripts.findInArray(arrayToSearch,retVal,matchFn) != -1)\n {\n count++;\n retVal = prefix + count.toString();\n }\n }\n \n return retVal;\n}",
"notIn(a, b, prefix = '') {\n let notIn = [];\n prefix = prefix.length > 0 ? `${prefix}.` : '';\n\n for (const key of Array.from(Object.keys(a))) {\n const thisPath = `${prefix}${key}`;\n\n if (b[key] === undefined) {\n notIn.push(thisPath);\n\n } else if ((typeof a[key] === 'object') && (!(a[key] instanceof Array))) {\n notIn = notIn.concat(this.notIn(a[key], b[key], thisPath));\n }\n }\n\n return notIn;\n }",
"function findInArray(array) {\n var arrays = array.map(str=>{\n return findInString(str)\n })\n return flatten(arrays)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |