query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Sorts through the questions and returns whether a question has the same id and uid as the parameters. | function questionPresent(uid,id){
let found = false
questions.forEach(function (question){
if (question.id === id && question.uid === uid){
found = true;
}
})
return found;
} | [
"function checkProvidedAnswer(question, answer){\n var checked = false\n if(answer.answerId == question.providedAnswer){\n checked = true\n }\n return checked\n }",
"function allAreAnswered(questions){\n if(questions.status===1){\n return true\n }\n}",
"function filterUnansweredQuestions(questions, currentUserId) {\n return Object.values(questions).filter(q => !q.optionOne.votes.includes(currentUserId)\n && !q.optionTwo.votes.includes(currentUserId))\n .sort((a, b) => b.timestamp - a.timestamp)\n}",
"function checkUniqueById(Student, id) {\n let i = 0;\n Student.forEach( student => {\n if ( id === student.id) {\n i = i + 1;\n } \n });\n\n if (i === 0) {\n return true;\n } else {\n return false;\n }\n}",
"compare(otherPost) {\n return (this.id === otherPost.id) ? true : false;\n }",
"studentInQueues(student) {\n const queueNames = Object.keys(this.queues);\n\n for (let i = 0; i < queueNames.length; i++) {\n const queueName = queueNames[i];\n if (this.queues[queueName].contains(student)) {\n return true;\n }\n }\n\n return false;\n }",
"function isDuplicatePlot(testPlotID){\n\tconsole.log(plantedQueue.length);\n\tfor(var i=0; i<plantedQueue.length;i++){\n\t\tif (plantedQueue[i].plotID == testPlotID){\n\t\t\treturn true;\n\t\t}\n\t}\n\tfor(var i=0; i<plantDecayQueue.length;i++){\n\t\tif (plantDecayQueue[i].plotID == testPlotID){\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}",
"function isAnswerActive(option){\n return selections.filter(selection => selection.questionId === question.id && selection.optionId.indexOf(option.id) > -1).length > 0\n }",
"function containsAnswer(helpfulAnswers, messageId) {\n return helpfulAnswers && helpfulAnswers.some(\n function(answer)\n {\n return answer.ID == messageId;\n });\n }",
"function validateUserAnswer(planet, id) {\n const position = planetToNumber(planet); // find planet position in array\n const userAnswer = $(\"input[name=user-answers]:checked\").parent('label').text().trim(); // find what answer the user picked\n let correctAnswer = ''; // placeholder for correct answer\n if (STORE.questionNumber === 0) {\n return true;\n }\n else {\n for (let i = 0; i <= 2; i++) { // loop through array until question is found\n currId = STORE.planets[position][planet][i].id; // current id to look at\n if (currId === id) { // if it matches passed id\n correctAnswer = STORE.planets[position][planet][i].correct; // set correct answer\n }\n }\n\n if (userAnswer === correctAnswer) { // if user answer is right return true, if it is not return false\n return true;\n }\n else\n return false;\n }\n\n}",
"moreQuestionsAvailable() {\n\treturn (this.progress.qAnswered < this.progress.qTotal);\n }",
"function isAnswer() {\r\n\tif (!answer.branches)\r\n\t\treturn false;\r\n\t\t\r\n\tvar i = 0;\r\n\tfor (i in answer.branches) {\r\n\t\tvar branch = answer.branches[i];\r\n\t\tbranch.any = true;\r\n\t\tif (branch.words) {\r\n\t\t\tvar nb = compareSet(branch,userInput.list);\r\n\t\t\t/* console.log(\"branch: \" + branch.words,\r\n\t\t\t\t\t\t\"input: \" + userInput.list,\r\n\t\t\t\t\t\t\"matched: \" + nb); */\r\n\t\t\tif(nb >= 0.5) {\r\n\t\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(!answer.wait){\r\n\t\tanswer = {};\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}",
"function isUnique() {\n if (threeOpt[0] !== threeOpt[1] && threeOpt[1] !== threeOpt[2] && threeOpt[2] !== threeOpt[0]) {\n return true;\n } else {\n return false;\n }\n}",
"function findUniqueAnswer(testAnswer , answers) {\n var duplicateAnswer;\n for(var testIteration = 0 ; testIteration < 100 ; testIteration++)\n {\n duplicateAnswer = 0; //start with a fresh duplicate boolean\n var evaluatedAnswerTest = eval(testAnswer); //try a new evaluated answer\n for(var testAgainstSlot = 0 ; testAgainstSlot < answers.length ; testAgainstSlot++)\n {\n if(evaluatedAnswerTest == answers[testAgainstSlot])\n {\n duplicateAnswer=1; //no good\n }\n }\n if(duplicateAnswer == 0)\n {\n return evaluatedAnswerTest; //this is a good answer\n }\n }\n return null; //too constrained\n}",
"function getQuestionsWithUserAnswers(data){\n var questions = data.questions;\n var userAnswers = data.userData.questions_answered;\n\n // maps question ids to user answers\n dictOfAnswers = {};\n \n // populate dictOfAnswers with ids of user answers and \n for (var i = 0; i < userAnswers.length; i++) {\n var userAnswer = userAnswers[i];\n if (userAnswer.response_data.length > 0){\n // get last answer object of the response_data array\n var currentAnswer = userAnswer.response_data[userAnswer.response_data.length - 1];\n dictOfAnswers[userAnswer.question_id] = currentAnswer.response;\n }\n \n }\n\n var newQuestionsArray = [];\n for (var i = 0; i < questions.length; i++) { \n var question = questions[i];\n\n question.userAnswer = null;\n if (question[\"_id\"] in dictOfAnswers){\n question.userAnswer = dictOfAnswers[question[\"_id\"]];\n }\n\n newQuestionsArray.push(question);\n }\n return newQuestionsArray;\n }",
"hasSaved(cardId) {\n\n for(const card of this.user.savedCards){\n\n if(card.cardID == cardId)return true;\n\n }\n return false;\n }",
"function areThereDuplicates(...args) {\n const frequency = {};\n for (let i = 0; i < args.length; i++) {\n if (frequency[args[i]]) {\n return true;\n } else {\n // don't assign this to 0 because 0 is falsey\n frequency[args[i]] = 1;\n }\n }\n return false;\n}",
"getUniqueRandomQnA() {\n // Return random trivia Q&A set\n var index;\n \n do {\n index = Math.floor(Math.random() * this.#dataset.length);\n }\n while(this.#questions.indexOf(index) > -1)\n\n this.#questions.push(index);\n\n return this.#dataset[index];\n }",
"function evaluate(userAnswer)\n{\n let correctAnswer = QUIZQUESTIONS[start].correct;\n\n if (userAnswer == correctAnswer)\n {\n return true;\n }\n else\n {\n return false;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collapse or Expands all services to show requirements. Changing the text content and the image icon when clicked. | function switchExpand(){
// Variables. Get expand button and image
let desc = document.getElementsByClassName("multi-collapse");
let btn = document.getElementById("expandButton");
let expand = document.getElementsByClassName("expand");
// console.log(btn.textContent);
// Changing text context of the expand button to Collapse or Expand
// and the image icon depending of the state of the button.
if(btn.textContent == "Expand All Services"){
btn.textContent = "Collapse All Services";
changePic(expand, "images/expand.png", desc, "collapse in multi-collapse");
} else{
btn.textContent = "Expand All Services";
changePic(expand, "images/unexpanded.png");
}
} | [
"function updateUI() {\n if (isSmall) {\n view.ui.add(expandLegend, 'top-right');\n view.ui.remove(legend);\n view.ui.components = [\"attribution\"];\n } else {\n view.ui.add(legend, 'top-right');\n view.ui.remove(expandLegend);\n view.ui.components = [\"attribution\", \"zoom\"];\n }\n }",
"function i2uiExpandContainer(id)\r\n{\r\n var nest = 1;\r\n var obj;\r\n\r\n obj = document.getElementById(id+\"_toggler\");\r\n if (obj != null)\r\n {\r\n var i2action = obj.getAttribute(\"onclick\")+\" \";\r\n if (i2action != null) \r\n {\r\n var at = i2action.indexOf(\"this,\");\r\n if (at != -1)\r\n nest = i2action.substring(at+5,at+6);\r\n }\r\n\r\n if (obj.tagName == 'IMG' &&\r\n obj.src.indexOf(\"container_expand.gif\") != -1)\r\n {\r\n // toggle the container\r\n i2uiToggleContent(obj, nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n }\r\n else\r\n {\r\n if (obj.tagName == 'A')\r\n {\r\n var len2 = obj.childNodes.length;\r\n for (var j=0; j<len2; j++)\r\n {\r\n if (obj.childNodes[j].tagName == 'IMG' &&\r\n obj.childNodes[j].src.indexOf(\"container_expand.gif\") != -1)\r\n {\r\n // toggle the container\r\n i2uiToggleContent(obj, nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.childNodes[j].src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n }\r\n }\r\n }\r\n }\r\n return;\r\n }\r\n obj = document.getElementById(id);\r\n //i2uitrace(1,'i2uiCollapseContainer obj='+obj);\r\n if (obj != null)\r\n {\r\n // IE allows onlick for IMGs while Netscape 6 does not.\r\n // therefore look for IMG directly in cell or as a child of\r\n // an A tag\r\n var len = obj.rows[0].cells[0].childNodes.length;\r\n\r\n // handle complex header in container\r\n if (len == 1 && obj.tagName == \"TABLE\")\r\n {\r\n obj = obj.rows[0].cells[0].childNodes[0];\r\n nest = 2;\r\n len = obj.rows[0].cells[0].childNodes.length;\r\n }\r\n\r\n for (var i=0; i<len; i++)\r\n {\r\n if (obj.rows[0].cells[0].childNodes[i].tagName == 'IMG' &&\r\n obj.rows[0].cells[0].childNodes[i].src.indexOf(\"container_expand.gif\") != -1)\r\n {\r\n // toggle the container\r\n i2uiToggleContent(obj.rows[0].cells[0].childNodes[i], nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.rows[0].cells[0].childNodes[i].src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n break;\r\n }\r\n else\r\n {\r\n if (obj.rows[0].cells[0].childNodes[i].tagName == 'A')\r\n {\r\n var len2 = obj.rows[0].cells[0].childNodes[i].childNodes.length;\r\n for (var j=0; j<len2; j++)\r\n {\r\n if (obj.rows[0].cells[0].childNodes[i].childNodes[j].tagName == 'IMG' &&\r\n obj.rows[0].cells[0].childNodes[i].childNodes[j].src.indexOf(\"container_expand.gif\") != -1)\r\n {\r\n // toggle the container\r\n i2uiToggleContent(obj.rows[0].cells[0].childNodes[i], nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.rows[0].cells[0].childNodes[i].childNodes[j].src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n}",
"function supplierExpanded() {\n var isFromSupplier = PPSTService.getAddingSupplier();\n if (isFromSupplier) {\n // Expand \n $scope.expandASection('suppliers-section', 8);\n PPSTService.setAddingSupplier(false);\n }\n }",
"function i2uiCollapseContainer(id)\r\n{\r\n var obj;\r\n var nest = 1;\r\n\r\n obj = document.getElementById(id+\"_toggler\");\r\n if (obj != null)\r\n {\r\n var i2action = obj.getAttribute(\"onclick\")+\" \";\r\n if (i2action != null) \r\n {\r\n var at = i2action.indexOf(\"this,\");\r\n if (at != -1)\r\n nest = i2action.substring(at+5,at+6);\r\n }\r\n if (obj.tagName == 'IMG' &&\r\n obj.src.indexOf(\"container_collapse.gif\") != -1)\r\n {\r\n // toggle the container\r\n i2uiToggleContent(obj, nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.src = i2uiImageDirectory+\"/container_expand.gif\";\r\n }\r\n else\r\n {\r\n if (obj.tagName == 'A')\r\n {\r\n var len2 = obj.childNodes.length;\r\n //i2uitrace(1,\"#children in A tag=\"+len2);\r\n for (var j=0; j<len2; j++)\r\n {\r\n //i2uitrace(1,'child #'+j+\" tag=\"+obj.rows[0].cells[0].childNodes[i].childNodes[j].tagName);\r\n if (obj.childNodes[j].tagName == 'IMG' &&\r\n obj.childNodes[j].src.indexOf(\"container_collapse.gif\") != -1)\r\n {\r\n // toggle the container\r\n i2uiToggleContent(obj, nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.childNodes[j].src = i2uiImageDirectory+\"/container_expand.gif\";\r\n }\r\n }\r\n }\r\n }\r\n return;\r\n }\r\n\r\n obj = document.getElementById(id);\r\n //i2uitrace(1,'i2uiCollapseContainer obj='+obj);\r\n if (obj != null)\r\n {\r\n // IE allows onlick for IMGs while Netscape 6 does not.\r\n // therefore look for IMG directly in cell or as a child of\r\n // an A tag\r\n var len = obj.rows[0].cells[0].childNodes.length;\r\n //i2uitrace(1,\"#children in first row's first cell=\"+len);\r\n\r\n // handle complex header in container\r\n if (len == 1 && obj.tagName == \"TABLE\")\r\n {\r\n //i2uitrace(1,\"obj.tagName=\"+obj.tagName);\r\n obj = obj.rows[0].cells[0].childNodes[0];\r\n nest = 2;\r\n len = obj.rows[0].cells[0].childNodes.length;\r\n //i2uitrace(1,\"COMPLEX HEADER #children in first row's first cell=\"+len);\r\n }\r\n\r\n for (var i=0; i<len; i++)\r\n {\r\n //i2uitrace(1,'child #'+i+\" tag=\"+obj.rows[0].cells[0].childNodes[i].tagName);\r\n if (obj.rows[0].cells[0].childNodes[i].tagName == 'IMG' &&\r\n obj.rows[0].cells[0].childNodes[i].src.indexOf(\"container_collapse.gif\") != -1)\r\n {\r\n //i2uitrace(1,'toggle 1 nest='+nest);\r\n // toggle the container\r\n i2uiToggleContent(obj.rows[0].cells[0].childNodes[i], nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.rows[0].cells[0].childNodes[i].src = i2uiImageDirectory+\"/container_expand.gif\";\r\n break;\r\n }\r\n else\r\n {\r\n if (obj.rows[0].cells[0].childNodes[i].tagName == 'A')\r\n {\r\n var len2 = obj.rows[0].cells[0].childNodes[i].childNodes.length;\r\n //i2uitrace(1,\"#children in A tag=\"+len2);\r\n for (var j=0; j<len2; j++)\r\n {\r\n //i2uitrace(1,'child #'+j+\" tag=\"+obj.rows[0].cells[0].childNodes[i].childNodes[j].tagName);\r\n if (obj.rows[0].cells[0].childNodes[i].childNodes[j].tagName == 'IMG' &&\r\n obj.rows[0].cells[0].childNodes[i].childNodes[j].src.indexOf(\"container_collapse.gif\") != -1)\r\n {\r\n //i2uitrace(1,'toggle 2 nest='+nest);\r\n // toggle the container\r\n i2uiToggleContent(obj.rows[0].cells[0].childNodes[i], nest);\r\n\r\n // now change the expand/collapse icon\r\n obj.rows[0].cells[0].childNodes[i].childNodes[j].src = i2uiImageDirectory+\"/container_expand.gif\";\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n}",
"function layerList_ExpandAll(expand) {\n //alert(layerListWidget.operationalItems.items[0].children.items[10].visible);\n var ctSpans = document.getElementsByClassName(\"esri-layer-list__child-toggle\");\n if (ctSpans.length > 0) {\n for (var i = 0; i < ctSpans.length; i++)\n if (ctSpans[i].hasOwnProperty(\"data-item\")) {\n if (ctSpans[i][\"data-item\"].open) // If root node already expanded, assume the rest is also expanded, and exit function\n return;\n ctSpans[i][\"data-item\"].open = expand;\n }\n }\n }",
"function selectItem(e) {\n removeBorder();\n removeShow();\n // Add Border to current feature\n this.classList.add('feature-border');\n // Grab content item from DOM\n const featureContentItem = document.querySelector(`#${this.id}-content`);\n // Add show\n featureContentItem.classList.add('show');\n}",
"function collapseExpandLayers(id, parentDisplayType) {\n var elements = document.getElementsByName(id);\n var displayType = getDisplayType(id, parentDisplayType);\n var layerLabel = displayType == 'block' ?\n getArrowImg('open') : getArrowImg('close');\n document.getElementById('collapse_' + id).innerHTML = layerLabel;\n for (var i = 0; i < elements.length; i++) {\n elements[i].style.display = displayType;\n }\n collapseChildLayers(id, displayType);\n}",
"async collapse() {\n if (await this.isExpanded()) {\n await this.toggle();\n }\n }",
"function toggleCompletedVisibility(element) {\n var lotRows = document.getElementsByClassName('lot-quantity-zero');\n\n if (element.textContent === ' Hide Completed Rows') {\n element.innerHTML = \"<i class=\\\"far fa-eye\\\"></i> Show Completed Rows\"\n for (var i = 0; i < lotRows.length; i++) {\n lotRows[i].classList.add('d-none');\n }\n } else {\n element.innerHTML = \"<i class=\\\"far fa-eye-slash\\\"></i> Hide Completed Rows\"\n for (var i = 0; i < lotRows.length; i++) {\n lotRows[i].classList.remove('d-none');\n }\n }\n}",
"function boxific_expand_all(){\n\t$('.boxific-rule').each(function(){\n\t\tvar rule = $(this);\n\t\tvar collapsed = rule.find('.boxific-rule-collapsed');\n\t\tvar fieldset = rule.find('fieldset');\n\n\t\tcollapsed.hide();\n\t\tfieldset.show();\n\t\trule.removeClass('collapsed');\n\t});\n}",
"function i2uiToggleContent(item, nest, relatedroutine)\r\n{\r\n // find the owning table for the item which received the event.\r\n // in this case the item is the expand/collapse image\r\n // note: the table may be several levels above as indicated by 'nest'\r\n var owningtable = item;\r\n //i2uitrace(1,\"nest=\"+nest+\" item=\"+item+\" tagname=\"+item.tagName);\r\n if (item.tagName == \"A\")\r\n {\r\n item = item.childNodes[0];\r\n //i2uitrace(1,\"new item=\"+item+\" parent=\"+item.parentNode+\" type=\"+item.tagName);\r\n }\r\n\r\n while (owningtable != null && nest > 0)\r\n {\r\n if (owningtable.parentElement)\r\n {\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentElement+\" level=\"+nest);\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentElement.tagName+\" level=\"+nest);\r\n owningtable = owningtable.parentElement;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentNode+\" level=\"+nest);\r\n //i2uitrace(1,\"tag=\"+owningtable.tagName+\" parent=\"+owningtable.parentNode.tagName+\" level=\"+nest);\r\n owningtable = owningtable.parentNode;\r\n }\r\n if (owningtable != null && owningtable.tagName == 'TABLE')\r\n {\r\n nest--;\r\n }\r\n }\r\n\r\n var ownerid = owningtable.id;\r\n\r\n // for tabbed container, the true owning table is higher.\r\n // continue traversal in order to get the container id.\r\n if (ownerid == \"\")\r\n {\r\n var superowner = owningtable;\r\n while (superowner != null && ownerid == \"\")\r\n {\r\n if (superowner.parentElement)\r\n {\r\n //i2uitrace(1,\"tag=\"+superowner.tagName+\" parent=\"+superowner.parentElement.tagName+\" level=\"+nest+\" id=\"+superowner.parentElement.id);\r\n superowner = superowner.parentElement;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"tag=\"+superowner.tagName+\" parent=\"+superowner.parentNode.tagName+\" level=\"+nest+\" id=\"+superowner.parentNode.id);\r\n superowner = superowner.parentNode;\r\n }\r\n if (superowner != null && superowner.tagName == 'TABLE')\r\n {\r\n ownerid = superowner.id;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"final id=\"+ownerid);\r\n\r\n // if found table, find child TBODY with proper id\r\n if (owningtable != null)\r\n {\r\n var pretogglewidth = owningtable.offsetWidth;\r\n\r\n //i2uitrace(1,owningtable.innerHTML);\r\n\r\n // can not simply use getElementById since the container\r\n // may itself contain containers.\r\n\r\n // determine how many TBODY tags are within the table\r\n var len = owningtable.getElementsByTagName('TBODY').length;\r\n //i2uitrace(1,'#TBODY='+len);\r\n\r\n // now find proper TBODY that holds the content\r\n var contenttbody;\r\n for (var i=0; i<len; i++)\r\n {\r\n contenttbody = owningtable.getElementsByTagName('TBODY')[i];\r\n //i2uitrace(1,'TBODY '+i+' id='+contenttbody.id);\r\n if (contenttbody.id == '_containerBody' ||\r\n contenttbody.id == '_containerbody' ||\r\n contenttbody.id == 'containerBodyIndent' ||\r\n contenttbody.id == 'containerbody')\r\n {\r\n //i2uitrace(1,'picked TBODY #'+i);\r\n\r\n var delta = 0;\r\n\r\n if (contenttbody.style.display == \"none\")\r\n {\r\n contenttbody.style.display = \"table\";\r\n\t\t contenttbody.style.width = \"100%\";\r\n item.src = i2uiImageDirectory+\"/container_collapse.gif\";\r\n delta = contenttbody.offsetHeight;\r\n }\r\n else\r\n {\r\n delta = 0 - contenttbody.offsetHeight;\r\n contenttbody.style.display = \"none\";\r\n item.src = i2uiImageDirectory+\"/container_expand.gif\";\r\n }\r\n if (i2uiToggleContentUserFunction != null)\r\n {\r\n\t\t eval(i2uiToggleContentUserFunction+\"('\"+ownerid+\"',\"+delta+\")\");\r\n }\r\n break;\r\n }\r\n }\r\n\r\n // restore width of container\r\n if (pretogglewidth != owningtable.offsetWidth)\r\n {\r\n owningtable.style.width = pretogglewidth;\r\n owningtable.width = pretogglewidth;\r\n }\r\n\r\n // call a related routine to handle any follow-up actions\r\n // intended for internal use. external use should use the\r\n // callback mechanism\r\n //i2uitrace(0,\"togglecontent related=[\"+relatedroutine+\"]\");\r\n if (relatedroutine != null)\r\n {\r\n // must invoke the routine 'in the future' to allow browser\r\n // to settle down, that is, finish rendering the effects of\r\n // the tree element changing state\r\n setTimeout(relatedroutine,200);\r\n }\r\n }\r\n}",
"_toggleShowAllLabel() {\n this._showAllToggleable.innerHTML = this._showAllToggleable.innerHTML === 'more' ? 'fewer' : 'more';\n }",
"function toggleCountries() {\n if (!countriesExpanded) {\n // open animation\n gsap.to('.country-options-wrapper', { duration: 0.5, height: 'auto' });\n gsap.to('.icon-countries-open-close', {\n rotation: 180,\n duration: 0.7,\n });\n if (analysisExpanded) toggleAnalysis();\n } else {\n // close animation\n gsap.to('.country-options-wrapper', { duration: 0.5, height: 0 });\n gsap.to('.icon-countries-open-close', {\n rotation: 0,\n duration: 0.7,\n });\n }\n setAnalysisExpanded(false);\n setCountriesExpanded(!countriesExpanded);\n }",
"function toggleIconToMinus() { \r\ndocument.getElementById(\"plus\").style.display=\"none\"; document.getElementById(\"minus\").style.display=\"block\"; \r\n}",
"function toggleInfo() {\n\tvar state = document.getElementById('description').className;\n\tif (state == 'hide') {\n\t\t// Info anzeigen\n\t\tdocument.getElementById('description').className = '';\n\t\tdocument.getElementById('descriptionToggle').innerHTML = text[1];\n\t}\n\telse {\n\t\t// Info verstecken\n\t\tdocument.getElementById('description').className = 'hide';\n\t\tdocument.getElementById('descriptionToggle').innerHTML = text[0];\n\t}\t\n}",
"function _toggleExpanded(e) {\n $(\"#categories\").toggleClass(\"expanded\")\n\n if ($(\"#categories\").hasClass(\"expanded\")) {\n $(e.target).text(\"Collapse All\")\n $(\".checkbox\").removeClass(\"hide\")\n } else {\n $(e.target).text(\"Expand All\")\n $(\".checkbox\").not(\".depth0\").not((i, el) => {\n var checkbox_input = $(el).children(\"input\")\n var sibling_checkboxes = $(el).parent().parent().children(\"ul li input\")\n return checkbox_input.prop(\"checked\") || sibling_checkboxes.prop(\"checked\")\n }).addClass(\"hide\")\n }\n }",
"function switchContent() {\n let nodeId= $(clickedNode).attr('id');\n let node = nodeMap.get(nodeId);\n $(clickedNode).children(\".node_inhalt\").toggleClass(\"invis\");\n if($(clickedNode).children(\".node_inhalt\").hasClass(\"invis\")){\n node.toggleToAbstract();\n node.focus(); }\n else{\n node.toggleToDetailed();\n }\n\n}",
"function showIconAddMenu() {\n var apps = FPI.apps.all, i, bundle, sel, name;\n clearinnerHTML(appList);\n showHideElement(appList, 'block');\n appList.appendChild(createDOMElement('li', 'Disable Edit', 'name', 'Edit'));\n\n for (i = 0; i < apps.length; i++) {\n bundle = apps[i].bundle;\n sel = FPI.bundle[bundle];\n name = sel.name;\n appList.appendChild(createDOMElement('li', name, 'name', bundle));\n }\n}",
"function hsCollapseAllVisible() {\n $('#content .hsExpanded:visible').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change a loop to a 'foreach' loop | function changeLoopToForeach() {
var sO = CurStepObj;
if (sO.activeParentExpr.isLoopStmt() &&
(sO.activeChildPos <= 0)) {
sO.activeParentExpr.str = 'foreach';
sO.activeParentExpr.type = ExprType.Foreach;
sO.activeParentExpr.deleted = DeletedState.None;
} else {
showTip(TipId.SelectKeyword);
}
drawCodeWindow(sO); // redraw code window
} | [
"each(visitor, context) {\n return this.items.forEach(visitor, context);\n }",
"function each( a, f ){\n\t\tfor( var i = 0 ; i < a.length ; i ++ ){\n\t\t\tf(a[i])\n\t\t}\n\t}",
"function for_each(){\n var param_len = arguments[0].length;\n var proc = arguments[0];\n while(!is_empty_list(arguments[1])){\n var params = [];\n for(var j = 1; j < 1+param_len; j++) {\n params.push(head(arguments[j]));\n arguments[j] = tail(arguments[j]);\n }\n proc.apply(proc, params);\n\t}\n}",
"for(iteration, forBody) {\n return this._for(new ForLoop(iteration), forBody)\n }",
"visitMulti_column_for_loop(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"forEach(cb) {\n for (var item = this._head; item; item = item.next) {\n cb(item.data);\n }\n }",
"function iterate(arr) {\n arr.forEach((el) => {\n if (Array.isArray(el)) {\n iterate(el);\n } else {\n result.push(el);\n }\n })\n }",
"function foreach_3(v, f) /* forall<a,e> (v : vector<a>, f : (a) -> e ()) -> e () */ {\n return _bind_foreach_3(v, f);\n}",
"each(a, b) {\n let typeArg = _Util_main_js__WEBPACK_IMPORTED_MODULE_0__.default.getType(a);\n switch (typeArg) {\n case \"Function\":\n this._state.forEach(elem=>{\n a(YngwieModel.init(elem));\n });\n break;\n case \"String\":\n let state = this.state(a);\n if (state instanceof Array) {\n state.forEach(elem=>{\n b(YngwieModel.init(elem));\n });\n } else {\n throw new yngwie__WEBPACK_IMPORTED_MODULE_1__.Error(\"Scope is not an array\", typeArg);\n }\n break;\n default:\n throw new yngwie__WEBPACK_IMPORTED_MODULE_1__.Error(\"Argument passed to YngwieModel.forEach is of an unsupported type\", typeArg);\n }\n }",
"forEachTarget(t, e) {\n t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.et.forEach((t, n) => {\n this.ht(n) && e(n);\n });\n }",
"function For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}",
"function foreach_indexed_1(v, f) /* forall<a,e> (v : vector<a>, f : (a, int) -> e ()) -> e () */ {\n return _bind_foreach_indexed_1(v, f);\n}",
"forEach(elements, thunk) {\n var index = 0;\n elements.forEach((function(element) {\n thunk(element, this, index++);\n }).bind(this));\n return this;\n }",
"function funcLoop1(item, index, array) {\n // console.log(rowNum);\n // console.log(index);\n\n\n // top of grid - only check left, right & down\n if (index === 0) {\n item.forEach(topRowLoop);\n } else if (index === gridsize - 1) {\n item.forEach(bottomRowLoop);\n } else {\n item.forEach(middleRowLoop);\n };\n rowNum ++;\n}",
"function forEachElement (func) {\n selectors.map((selector, count) => {\n if (!selectMultipleOfElement) {\n func(selector, document.querySelector(selector))\n } else {\n [...document.querySelectorAll(selector)].forEach(element => {\n func(`${selector}_${count}`, element)\n })\n }\n })\n }",
"visitFor_each_row(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function iterate(callback){\n let array = [\"dog\", \"cat\", \"squirrel\"]\n array.forEach(callback)\n return array\n}",
"generateEach (list, depth) {\n for (let node of list) {\n generate(this, node, depth);\n }\n return this;\n }",
"isForLoopOrComprehension(context) {\n let { previous, next } = context;\n return (previous.exists &&\n previous.type === 'keyword' &&\n previous.value === 'for' &&\n next.exists &&\n next.type === 'keyword' &&\n next.value === 'in');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes family member from a specific family. | async function deleteFamilyMember(current, email) {
let sql = `DELETE FROM family WHERE email = ? AND name = ?`;
await db.query(sql, [email, current]);
} | [
"function deleteMemberFromAppData(e, memberName) {\n\n let indexinAppData =0;\n appData.members.forEach((member, index)=> {\n if(member.name === memberName){\n indexinAppData = index;\n }\n })\n appData.members.splice(indexinAppData,1);\n}",
"async destroy({ params, request, response }) {\n const group = await Group.find(params.group_id)\n if (!group) return response.notFound({ message: 'group not found!' })\n\n const user = await User.find(params.id)\n if (!user) return response.notFound({ message: 'user does not exist!' })\n\n if (!await group.isMember(params.id)) {\n return response.forbidden({ message: `${user.name} is not member of ${group.title}` })\n }\n\n if (group.admin_id !== params.id) {\n return response.forbidden({ message: `Only admin of the ${group.title} can delete members` })\n }\n\n const res = await group.users()\n .detach([params.id])\n\n return {\n message: res,\n }\n }",
"delPerson( name ) {\n let delId = this.findPersonId( name );\n if (delId != null) {\n let idToDelete = this.edges.getIds( {\n filter : function(item) {\n return (item.from == delId || item.to == delId);\n }\n });\n console.log( \"Removing \", idToDelete );\n this.edges.remove( idToDelete );\n this.nodes.remove( delId );\n }\n }",
"function removeMemberFromCommunity(domainName, data, done) {\n /* const arr = [];\n const query = (`DELETE FROM ${MEMBERSHIP_TABLE} WHERE username =? AND domain = ? `);\n // console.log(data.length);\n // console.log(typeof (data));\n console.log(data);\n data.forEach((val) => {\n arr.push({ query, params: [val.username.toLowerCase(), domainName.toLowerCase()] });\n });\n return client.batch(arr, { prepare: true }, (err, res) => {\n if (err) {\n return done(err);\n }\n return done(undefined, res);\n });*/\n}",
"function cleanGroupMembers () {\n // first create the group if it doesnt exist\n var group = ContactsApp.getContactGroup(GROUP_NAME);\n \n // delete everyone on it\n if (group) {\n group.getContacts().forEach(function(d) {\n d.deleteContact();\n });\n \n // delete the group\n group.deleteGroup();\n }\n \n}",
"deleteInstance(instance) {\n this.instances.remove(instance)\n }",
"destroy () {\n this.group.remove(this.sprite, true, true);\n this.gameObjectsGroup.destroyMember(this);\n }",
"function deleteCollaborator(doc, collaborator, cb) {\n if (!authenticated()) return cb(\"Creating collaborator failed. Login first.\");\n $.ajax({\n type: 'DELETE',\n headers: {\n \"Authorization\": \"token \" + token()\n },\n url: Substance.settings.hub_api + '/documents/' + doc.id + '/collaborators/'+collaborator,\n success: function(result) {\n cb(null);\n },\n error: function() {\n cb(\"Deleting collaborator failed failed. Can't access server\");\n },\n dataType: 'json'\n });\n}",
"function delUserForMeeting( data, callback ) {\n\t\t\tvar url = '/meetingdelusers';\n\n\t\t\tnew IO({\n\t\t\t\turl: url,\n\t\t\t\ttype: 'post',\n\t\t\t\tdata: data,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\t\tcallback(data);\n\t\t\t\t}\n\t\t\t});\n\n\t\t}",
"removeSibling(sibling) {\n this.siblings.delete(sibling);\n }",
"function submitRemoveMember(e) {\n e.preventDefault()\n socket.emit('removeTeamMember', { id: socket.id })\n ownTeam.classList.toggle('joined')\n}",
"async delete() {\n\t\tawait this.reload();\n\t\treturn this.datahandler.removeGuild(this.guild);\n\t}",
"function targetDel(target) {\n var pings = pingTable.query({parentId : target.getId()});\n for (var i=0; i<pings.length; i+=1)\n pings[i].deleteRecord();\n target.deleteRecord();\n }",
"function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }",
"function conditionCheckedDeleteMembers(domainName, values, dataExistCheckResult, done) {\n logger.debug('condition checked to delete member');\n logger.debug('dataExistCheckResult', dataExistCheckResult);\n if (dataExistCheckResult === values.length) {\n communityMembershipService.removeMembersFromCommunity(domainName, values, (err) => {\n if (err) {\n done(err);\n }\n publishMessageToTopicForDeletion(domainName, values);\n return done(undefined, { message: 'Member deleted' });\n });\n // publishMessageToTopicForDeletion(domainName, values);\n } else {\n done({ error: 'Member details not available' });\n }\n}",
"function deleteRegimen(req, res, next) {\r\n var card = req.body.regimen;\r\n var card_id = req.body.test3;\r\n\r\n req.app.get('db').regimens.destroy({id: card_id}, function(err, result){\r\n //Array containing the destroyed record is returned\r\n if (err) {\r\n console.log(\"Could not delete card\");\r\n } else{\r\n console.log(\"Card successfully deleted\");\r\n res.json(result);\r\n }\r\n });\r\n\r\n}",
"function deleteNode() {\n nodeToDelete = deleteNodeInp.value();\n nodes.splice(nodeToDelete,1);\n numnodes -= 1;\n //nodes.remove[0];\n //numnodes -= 1;\n}",
"function removeHobby(hobby) {\n hobbyOutput.removeChild(hobby);\n}",
"personDeleteAPersonFaceDelete(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonDeleteAPersonFaceDeleteQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonDeleteAPersonFaceDeleteHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonDeleteAPersonFaceDeletePathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}', 'delete', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
AssetExists returns true when asset with given ID exists in world state. | async _AssetExists(ctx, id) {
const assetJSON = await ctx.stub.getState(id);
return assetJSON && assetJSON.length > 0;
} | [
"idAlreadyExistsInBundle(id) {\n for (let e of this.entry) {\n let resource = e.resource;\n if (resource['id'] === id)\n return true;\n }\n return false;\n }",
"function pixelIDExist(id) {\n for (var i = 0; i < pixelIDMap.length; i++) {\n if (pixelIDMap[i] == id) {\n return true;\n }\n }\n return false;\n}",
"function objectExists(type, id) {\n\tif (!metaData.hasOwnProperty(type)) return false;\n\t\n\tfor (var obj of metaData[type]) {\n\t\tif (obj && obj.hasOwnProperty(\"id\") && obj.id === id) return true;\n\t}\n\t\n\treturn false;\n}",
"function doesEntryExist(id, scope)\n\t{\n\t\t// Iterate reference table and return whether a match was found\n\t\tfor(key in referenceTable)\n\t\t{\n\t\t\t// Find the matching entry, and return true\n\t\t\tif(referenceTable[key].id === id && referenceTable[key].scope === scope)\n\t\t\t\treturn true;\n\t\t}\n\n\t\t// No entry was found...\n\t\treturn false;\n\t}",
"hasCache(identifier) {\n validation_1.CacheValidation.validateIdentifier(identifier);\n return this._resources.has(identifier);\n }",
"function odk_json_exists(filename, callback) {\n read_git_release_data(REGION_FS_STORAGE, function(files) {\n res = false\n _.each(files, function(f, i) {\n if (basename(f) + \".json\" == filename) {\n res = true\n return\n }\n });\n\n callback(res)\n });\n}",
"fileExists() {\n return fs.pathExists(this.location);\n }",
"exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }",
"function courseExists(id) {\n for (i in grades) {\n if (grades[i].courseId == id) {\n return true;\n }\n }\n return false;\n}",
"function manifestExists() {\n return fs.existsSync(testManifestPath);\n}",
"function movieExistsById(movieList, id){\r\n\r\n for(let i = 0; i < movieList.length; i++){\r\n if (movieList[i].id === id) {\r\n return true\r\n }\r\n }\r\n\r\n return false\r\n}",
"function exists(file) {\n\treturn fs.existsSync(file) && file;\n}",
"function achievements_has(id){\n\treturn this.achievements.achievements[id] ? 1 : 0;\n}",
"static checkForDuplicate(albumId) {\n const albums = Storage.getAlbums();\n let isDuplicate;\n\n albums.forEach((album) => {\n if(album.albumId === albumId) {\n isDuplicate = true;\n }\n })\n return isDuplicate;\n }",
"userExists(id) {\n /** find index of user with that id */\n let index = this.data.users.findIndex((user) => {\n return user.id === id\n })\n /** check if index is valid */\n if (index > -1) {\n return true\n } else {\n return false\n }\n }",
"async exists() {\n return $(this.rootElement).isExisting();\n }",
"isDirExists() {\t\n\t\ttry\t{\n\t\t\tfs.statSync(this.options.dir);\n\t\t} catch(e) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}",
"function doesPersonExist(personName){\r\n let exists = false;\r\n\r\n // Loop over id properties of people object\r\n for(let id in people){\r\n if(people[id].name === personName){\r\n exists = true;\r\n break;\r\n }\r\n }\r\n return exists;\r\n}",
"function achievements_check_in_inventory(id){\n\n\tvar ac = this.achievements_get(id);\n\t\n\tif (!ac || !num_keys(ac.conditions)) return false;\n\t\n\tfor (var condition in ac.conditions){\n\t\tvar data = ac.conditions[condition];\n\t\t\n\t\tif (data.type === null){\n\t\t\treturn false;\n\t\t}\n\t\telse if (data.type == 'counter' && data.group == 'in_inventory'){\n\t\t\tif (this.countItemClass(data.label) < intval(data.value)){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tlog.error('Undefined achievement condition for '+id+' in achievements_check_in_inventory(): '+data.type+' - '+data.group);\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
task 1.3 update task by id (BODY CAN INCLUDE description & done) | function updateTaskById(id, { description, done }) {
const task = getTaskById(id);
if (done !== undefined) {
task.done = !!done;
}
if (description) {
task.description = description;
}
return task; //注:这里的思路与拆分前的有差异,这里是直接更改原task的属性,拆分前的版本是新建task再替换。
} | [
"update(_task) {\n const { id, task, date, process } = _task\n let sql = `UPDATE tasks\n SET task = ?,\n date = ?,\n process = ?\n WHERE id = ?`;\n return this.dao.run(sql, [task, date, process, id])\n }",
"function task_update_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n }, 'item_update')\n}",
"taskUpdate(token, taskID, name, dueDate) {\n return fetch(`${this.url}/task/update`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n token: token,\n taskID: taskID,\n name: name,\n dueDate: dueDate\n })\n })\n }",
"function updateTaskInfo(opt){\n var title = $('#task-title');\n var description = $('#task-description');\n var initDate = $('#task-init-date');\n var endDate = $('#task-end-date');\n var status = $('#task-status');\n var currentOpt = $(\"#\" + opt.id);\n\n var statusBadges = {\n 'New' : $('#status-new'),\n 'In progress' : $('#status-in-prog'),\n 'Waiting' : $('#status-freeze'),\n 'Closed' : $('#status-done')\n };\n\n //Set the task data\n title.text(currentOpt.data(\"tname\"));\n description.text(currentOpt.data(\"tdescrp\"));\n initDate.text( currentOpt.data(\"indate\") );\n endDate.text( currentOpt.data(\"endate\") );\n\n //Set the current status\n if(currentStatus != null){\n currentStatus.addClass(\"d-none\");\n }\n\n statusBadges[currentOpt.data(\"status\")].removeClass(\"d-none\");\n currentStatus = statusBadges[currentOpt.data(\"status\")];\n}",
"onTaskUpdated(task, updatedData) {\n const tasks = this.tasks.slice();\n const oldTask = tasks.splice(tasks.indexOf(task), 1, Object.assign({}, task, updatedData))[0];\n this.tasksUpdated.next(tasks);\n // Creating an activity log for the updated task\n this.activityService.logActivity(\n this.activitySubject.id,\n 'tasks',\n 'A task was updated',\n `The task \"${limitWithEllipsis(oldTask.title, 30)}\" was updated on #${this.activitySubject.document.data._id}.`\n );\n }",
"function api_putTaskCompleted(token, task){\n\tvar delURL = \"https://www.googleapis.com/\";\n\tdelURL += \"tasks/v1/lists/@default/tasks/\";\n\tdelURL += task.id;\n\n\tvar xhr = new XMLHttpRequest();\n\txhr.responseType = 'json';\n\txhr.open('PUT', delURL);\n\txhr.setRequestHeader('Authorization', 'Bearer ' + token);\n\txhr.setRequestHeader('Content-Type', 'application/json');\n\n\txhr.onerror = function () {\n\t\tconsole.log(\"google_api: HTTP PUT ERROR [TASK]\");\n\t\tconsole.log(this);\n\t};\n\n\txhr.onload = function() {\n\t\tconsole.log(\"google_api: HTTP PUT SUCCESS [TASK]\");\n\t\tconsole.log(this.response);\n\t};\n\n\tvar body = JSON.stringify( { id: task.id, status: \"completed\" } );\n\n\tconsole.log(\"Put URL: \" + delURL);\n\tconsole.log(\" BODY: \" + body);\n\n\txhr.send(body);\n}",
"function task_complete_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n }, 'item_complete')\n}",
"static update(id, entryVendorTask){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entryVendorTask = entryVendorTask;\n\t\treturn new kaltura.RequestBuilder('reach_entryvendortask', 'update', kparams);\n\t}",
"async function updateTaskDeadline(user, group, modId, task, deadline) {\n await checkTaskEditPermission(user, group, modId, task);\n\n await db.collection(\"Tasks\").updateOne({ modId: ObjectId(modId), taskId: task }, {\n $set: { time: Date.now(), deadline, }\n });\n await db.collection(\"Modules\").updateOne( {_id: ObjectId(modId)}, {$set : {\"modDate\" : Date.now()} } );\n\n return await getTaskInfo(modId, task);\n}",
"static updateJob(id, entryVendorTask){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.entryVendorTask = entryVendorTask;\n\t\treturn new kaltura.RequestBuilder('reach_entryvendortask', 'updateJob', kparams);\n\t}",
"editSubtask (subtaskId, key, value) {\n console.log('editSubtask:', subtaskId, key);\n let user = Auth.requireAuthentication();\n \n // Validate the data is complete\n check(subtaskId, String);\n check(key, String);\n check(value, Match.Any);\n \n // Load the subtask to authorize the edit\n let subtask = Subtasks.findOne(subtaskId);\n \n // Validate that the current user is an administrator\n if (user.managesContributor(subtask.contributorId) || user.isAdmin() || user.contributorId() === subtask.contributorId) {\n let update = {};\n update[ key ] = value;\n \n // Tie the date completed to the completed flag\n if (key === 'isCompleted' && value === true) {\n update.dateCompleted = new Date();\n }\n \n // Update the subtask\n Subtasks.update(subtaskId, { $set: update });\n \n if (key === 'isCompleted' && value !== true) {\n Subtasks.update(subtaskId, { $unset: { dateCompleted: true } });\n }\n } else {\n console.error('Non-authorized user tried to edit a subtask:', user.username, key, value);\n throw new Meteor.Error(403);\n }\n }",
"function editGoal() {\n\t\tprops.editTask(props.goalId);\n\t}",
"function findAndUpdateTask(taskID, nextTeamID) {\n\n for (var updateCounter = 0; updateCounter < this.tasksArray.length; updateCounter++) {\n var tempTask = this.tasksArray[updateCounter];\n if (tempTask.taskID == taskID) {\n //alert(nextTeamID + \" \" + taskID);\n if (tempTask.numberOfUnitsCompleted != tempTask.maximumEstimatedUnits) {\n if (tempTask.numberOfUnitsCompleted < tempTask.maximumEstimatedUnits) {\n tempTask.Increment();\n }\n } else {\n /*\n Not convinced the update of unitOfWorkCompleted should be happening here\n */\n this.unitOfWorkCompleted = this.unitOfWorkCompleted + tempTask.maximumEstimatedUnits;\n tempTask.numberOfUnitsCompleted = 0;\n // It is already done ... move to next team\n this.tasksArray.splice(updateCounter, 1);\n return tempTask;\n }\n }\n }\n\n return null;\n}",
"async function updateDB() {\n for (let i = 0; i < tasks.length; i++) {\n await props.editSingleTask(tasks[i].id, tasks[i])\n }\n await props.getAllTasks(boardId)\n }",
"function putToDos(id, data) {\n\n var defer = $q.defer();\n\n $http({\n method: 'PUT',\n url: 'http://localhost:50341/api/ToDoListEntries/' + id,\n data: data\n }).then(function(response) {\n if (typeof response.data === 'object') {\n defer.resolve(response);\n toastr.success('Updated ToDo List Item!');\n } else {\n defer.reject(response);\n //error if found but empty\n toastr.warning('Failure! </br>' + response.config.url);\n }\n },\n // failure\n function(error) {\n //error if the file isn't found\n defer.reject(error);\n $log.error(error);\n toastr.error('error: ' + error.data + '<br/>status: ' + error.statusText);\n });\n\n return defer.promise;\n }",
"function updateTask() {\n\t$('#tasks-list').on('keyup', '#taskBox-title', function(){ \n\t\tvar title = this.value;\n\t\tvar ref = this.getAttribute('data-ref');\n\t\tTaskManager.update(ref, title, null);\n\t});\n\n\t$('#tasks-list').on('keyup', '#taskBox-body', function(){ \n\t\tvar body = this.value;\n\t\tvar ref = this.getAttribute('data-ref');\n\n\t\tTaskManager.update(ref, null, body);\n\t});\n\n}",
"function set_task_status(task_id, time_done){\n $('#'+task_id).attr('time_done', time_done)\n if (time_done > 0){\n $('#' + task_id).addClass('task-done');\n $('#rm_' + task_id).addClass('hidden');\n $('#checkbox_' + task_id).prop('checked', true)\n }\n else{\n $('#' + task_id).removeClass('task-done');\n $('#rm_' + task_id).removeClass('hidden');\n $('#checkbox_' + task_id).prop('checked', false)\n }\n}",
"function toggleComplete(taskName) {\n var task = TaskListNamespace.taskList.tasks[taskName];\n var calendar = TaskListNamespace.cal;\n\n var p = new promise.Promise();\n task.completed = !task.completed;\n\n var req = {\n 'calendarId': calendar.id,\n 'eventId': task.id\n },\n ev = {\n 'summary': task.name,\n 'description': window.btoa(JSON.stringify(task)),\n 'start': { 'dateTime' : task.start },\n 'end': { 'dateTime' : task.end }\n };\n\n req.resource = ev;\n\n console.log('Send req to flip completed bit');\n gapi.client.calendar.events.update(req).execute(function(x) {\n console.log('Toggled completed bit');\n p.done(false, x);\n });\n\n return p;\n}",
"function addTask({ description }) {\n\tconst task = { id: id++, description, done: false };\n\ttasks.push(task);\n\treturn task;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fills in the input box w/the first match (assumed to be the best match) q: the term entered sValue: the first matching result | function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
}
} | [
"searchOnChange(event) {\n const search = event.target.value.toLowerCase();\n\n const searchResults = names.filter( (val, index) => val.name.toLowerCase().startsWith(search) );\n const totalResults = searchResults.length;\n\n if (totalResults >= 1 && totalResults < names.length) {\n this.setState({\n totalResults: totalResults,\n matchFound: true,\n bestMatch: searchResults[0]\n });\n } else {\n this.setState({\n totalResults: totalResults,\n matchFound: false,\n bestMatch: null\n });\n }\n }",
"function do_search() {\n var query = input_box.val();\n\n if((query && query.length) || !$(input).data(\"settings\").minChars) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"function searchForMovie(movieTitle) {\n searchBarElem.val(movieTitle);\n searchBarElem.keyup(); // trigger search\n}",
"searchQuery (value) {\n let result = this.tableData\n if (value) result = this.fuseSearch.search(this.searchQuery)\n else result = []\n this.searchedData = result\n }",
"function do_search() {\n var query = input_box.val().toLowerCase();\n\n if (query && query.length) {\n if (selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if (query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function () {\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"function srQuery(container, search, replace, caseSensitive, wholeWord) {\r if (search) {\r var args = getArgs(caseSensitive, wholeWord);\r rng = document.body.createTextRange();\r rng.moveToElementText(container);\r clearUndoBuffer();\r while (rng.findText(search, 10000, args)) {\r rng.select();\r rng.scrollIntoView();\r if (confirm(\"Replace?\")) {\r rng.text = replace;\r pushUndoNew(rng, search, replace);\r }\r rng.collapse(false) ;\r } \r }\r}",
"function updateResultCap(elem){\n searchCap = elem.value;\n}",
"function findSearchValue() {\n return $('#search-input').val();\n}",
"function FuzzyFinder(opts, data) {\n \tvar data = data ? data : opts.data;\n \tvar ff = this;\n this.delay = 200;\n \t$.extend(this, opts);\n\n \t_fuzzyFinders.push(this);\n\n \t$.each( ['input', 'results', 'form', 'submit', 'ui'], \n \t\tfunction(k,v){\n \t\t\tif (!ff['$'+v]) ff['$'+v] = $(ff[v+'_selector']);\n \t\t});\n\n \t// setup ui\n \tff.$form.submit(function(){\n if (ff.$submit.val()) {\n if (ff.onSubmit) {\n ff.onSubmit(ff.$input.val());\n } else {\n ff.submit(ff.$input.val());\n }\n\n //ff.$ui.remove();\n }\n else {\n if (this.onSearch) {\n ff.onSearch(ff.$input.val());\n } else {\n\t ff.search(ff.$input.val());\n }\n }\n\n return false;\n });\n\n\n\n this.keymap = $.extend({\n return: function(){ ff.$submit.val(\"on\"); },\n\n escape: function(){ return; },\n\n down: function() { \n var n = ff.$results.find('li.selected');\n n.removeClass('selected');\n n = n.next();\n if (n.length) {\n n.addClass('selected');\n } else {\n ff.$results.find('li:first').addClass('selected');\n }\n },\n\n up: function() {\n var n = ff.$results.find('li.selected');\n n.removeClass('selected');\n n = n.prev();\n if (n.length) {\n n.addClass('selected');\n } else {\n ff.$results.find('li:last').addClass('selected');\n }\n },\n\n tab: function() { this.down(); },\n\n default: function(e){\n this.fuzzyFinder.triggerUpdate();\n },\n\n fuzzyFinder: this\n\n }, opts.keymap);\n\n \tff.$input.keymap(this.keymap);\n\n \t// initialize data\n\n \tthis.data = [];\n\n\n if (!this.search) {\n\n \tif (typeof(data) == \"string\") { // url\n\n \t\t// on update of input, there is posted a new ajax request, to\n \t\t// fill results.\n\n \t\t// this.dataType defaults to 'html', but can be also 'json'\n\n \t \tif (!this.getParam)\n \t \t\tthis.getParam = function(term){\n var x = {};\n $('input, select', ff.$form).each(function(){\n var $this = $(this);\n x[$this.attr('name')] = $this.val();\n\n });\n return x;\n };\n \n \t \tif (!this.onLoad)\n \t \t\tthis.onLoad = function(data){\n this.handleAjaxResponse(data);\n \t \t\t};\n\n this.data = data;\n \n \t \tthis.search = this.ajaxSearch;\n \t}\n \telse if (typeof(data) == \"function\") {\n \n \t\t\n \t}\n \n \telse {\n\n // setup cached_hits\n if (this.use_cached_hits) {\n if (this.hit_cacher == 'cookie') {\n $.cookie.json = true;\n this.cached_hits = $.cookie('findanything_hits');\n\n this.cached_hits_last_aged = $.cookie('findanything_last_aged');\n if (typeof(this.cached_hits_last_aged) == \"undefined\") {\n this.cached_hits_last_aged = Date.now();\n }\n }\n }\n\n if (typeof(this.cached_hits) == \"undefined\")\n this.cached_hits = {};\n\n // data is list of {href: ... name: ... info: ...}\n this.max_path_len = 0;\n this.max_name_len = 0;\n\n for (i in data) {\n var e = data[i];\n if (e.name.length > this.max_name_len) {\n this.max_name_len = e.name.length;\n }\n if (e.path.length > this.max_path_len) {\n this.max_path_len = e.path.length;\n }\n e.user_hits = 0;\n\n if (this.use_cached_hits) {\n if (this.cached_hits[e.href]) {\n // cached hits here\n\n // this only for migrating old numbers\n if (!$.isArray(this.cached_hits[e.href])) {\n this.cached_hits[e.href] = [];\n this.cached_hits[e.href].push(Date.now());\n }\n\n // assume we have following entries\n // 10s, 2min, 2.10min, 5min, 1.5h, 1.7h,\n // 3h, 4h, 10h, 11.5h, 1d, 1.5d, 2d, 2.2d,\n // 5d, 7d, 10d, 14d\n //\n // 13d\n //\n // within last hour: max(entries) = 6\n // within last 6h: max(entries) = 5\n // within last 12h: max(entries) = 4\n // within last 1d: max(entries) = 3\n // within last 7d: max(entries) = 2\n // within last 30d: max(entries) = 1\n //\n\n // age hits here\n var max_count = this.aging.length;\n var j = 0, // iterate over this.aging\n k = 0, // iterate over my_hits\n cnt = 0; // count \n var my_hits = this.cached_hits[e.href];\n\n var age = Date.now() - this.aging[j];\n\n var maxi = 0;\n for (var j=0; j<this.aging.length; j++) {\n maxi += j;\n }\n\n if (my_hits.length > maxi) {\n var new_hits = [];\n\n // my_hits is ascending\n for (var k in my_hits) {\n if (my_hits[k] > age) {\n if (cnt < max_count) {\n new_hits.push(my_hits[k])\n cnt += 1;\n } else {\n j += 1;\n cnt = 0;\n max_count -= 1;\n age = Date.now() - this.aging[j];\n }\n } else if (new_hits.length < maxi) {\n new_hits.push(my_hits[k])\n }\n }\n \n this.cached_hits[e.href] = new_hits;\n }\n e.user_hits = this.cached_hits[e.href].length;\n }\n }\n }\n\n // if maxmatch is used, order of entries is of essence, so\n // sort entries by user_hits descending\n\n if (this.use_cached_hits) {\n data.sort(function(a,b){\n return b.user_hits - a.user_hits;\n });\n }\n\n this.search = function(query){\n var selected = ff.$results.find('.selected').children('a').attr('href');\n\n var results = [];\n\n $.fuzzygrep(query, data, {\n getName: function(x){return x.name},\n getPath: function(x){return x.path || x.href},\n maxMatch: false,\n nameSelector: '.name',\n pathSelector: '.path',\n onMatch: function(d, p, m, i){\n results.push({entry: d, pattern: p, matches: m, index: i});\n\n // /var li = ff.renderResult($ul, d, i);\n // p.patternHighlight(li);\n },\n\n onNotMatch: null\n });\n\n // path query length and name query length\n var pql = 0, nql = 0;\n\n m = /(.*\\/)(.*)/.exec(query);\n if (m) {\n pql = m[1].length;\n nql = m[2].length;\n }\n else {\n pql = 0;\n nql = query.length;\n }\n var logged = 0;\n var mpl = this.max_path_len;\n var mnl = this.max_name_len;\n\n results.sort( function(a, b) {\n var _l, i, amin = Infinity, bmin = Infinity;\n\n var ma = a.matches;\n var mb = b.matches;\n\n var a_prate = 0, a_nrate = 0, b_prate = 0, b_nrate = 0;\n\n if (!b.matches[1]) {\n var xyz = 1;\n }\n\n var ampl = a.matches[0].length,\n aepl = a.entry.path.length,\n amnl = a.matches[1].length,\n aenl = a.entry.name.length,\n\n bmpl = b.matches[0].length,\n bepl = b.entry.path.length,\n bmnl = b.matches[1].length,\n benl = b.entry.name.length;\n\n if (0){\n\n var a_prate = (!ampl) ? 0 :\n (1 - (ampl - pql) / (mpl - aepl) )\n * (1 - aepl*0.0001);\n\n var a_nrate = (!amnl) ? 0 :\n (1 - (amnl - nql) / (mnl - aenl))\n * (1 - aenl*0.0001);\n\n var b_prate = (!bmpl) ? 0 :\n (1 - (bmpl - pql) / (mpl - bepl) )\n * (1 - bepl*0.0001);\n\n var b_nrate = (!bmnl) ? 0 :\n (1 - (bmnl - nql) / (mnl - benl) )\n * (1 - benl*0.0001);\n } else {\n var a_prate = (!ampl) ? 0 :\n (\n (1 - (ampl - pql)/ampl)*3 + \n (1 - (aepl - ampl)/aepl)*2 +\n ( (mpl - aepl)/mpl )*1 \n ) / 6;\n\n var b_prate = (!bmpl) ? 0 :\n (\n (1 - (bmpl - pql)/bmpl)*3 + \n (1 - (bepl - bmpl)/bepl)*2 +\n ( (mpl - bepl)/mpl )*1 \n ) / 6;\n var a_nrate = (!amnl) ? 0 :\n (\n (1 - (amnl - nql)/amnl)*3 + \n (1 - (aenl - amnl)/aenl)*2 +\n ( (mnl - aenl)/mnl )*1 \n ) / 6;\n var b_nrate = (!bmnl) ? 0 :\n (\n (1 - (bmnl - nql)/bmnl)*3 + \n (1 - (benl - bmnl)/benl)*2 +\n ( (mnl - benl)/mnl )*1 \n ) / 6;\n }\n\n var a_rate = (a_prate*pql + a_nrate*nql) / (pql+nql);\n\n var b_rate = (b_prate*pql + b_nrate*nql) / (pql+nql);\n\n // following is for debugging\n //a.entry.detail = \"ahits: \"+a.entry.user_hits+\", ampl: \"+ampl+\", pql: \"+pql+\", mpl: \"+mpl+\", aepl: \"+aepl+\"amnl: \"+amnl+\", nql: \"+nql+\", mnl: \"+mnl+\", aenl: \"+aenl+\", a_prate: \"+a_prate+\", a_nrate: \"+a_nrate+\", rate: \"+a_rate;\n //b.entry.detail = \"bhits: \"+b.entry.user_hits+\", bmpl: \"+bmpl+\", pql: \"+pql+\", mpl: \"+mpl+\", bepl: \"+bepl+\"bmnl: \"+bmnl+\", nql: \"+nql+\", mnl: \"+mnl+\", benl: \"+benl+\", b_prate: \"+b_prate+\", b_nrate: \"+b_nrate+\", rate: \"+b_rate;\n\n a.entry.rating = (a.entry.user_hits + a_rate).toFixed(4);\n b.entry.rating = (b.entry.user_hits + b_rate).toFixed(4);\n\n return (b.entry.user_hits + b_rate) - (a.entry.user_hits + a_rate);\n\n// 1 - (ml - ql) / ll (ml - ql) / (ll - ql)\n// q = \"CI\", in \"CI/\", ql = 2, ll = 3, ml = 2 1 - (2 - 2) / 3 = 1 * (1-3*0.0001)\n// q = \"CI\", in \"Machine Simulation\", ql = 2, ll = 18, ml = 14 1 - (14 - 2) / 18 = 1/3 * (1-18*0.0001)\n// q = \"CI\", in \"CI Serv\", ql = 2, ll = 7, ml = 2 1 - (2 - 2) / 7 = 1 * 0.9993\n// q = \"CI\", in \"foobar\", ql = 2, ll = 6, ml = 0 if ml == 0 : 0\n//\n// ci/sev (\"CI/CI Services Documentation\") => P: bmpl: 3, pql: 3, bepl: 3, bmnl: 4, nql: 3, benl: 25\n// ci/sev (\"CI/CI Services\") => P: bmpl: 3, pql: 3, bepl: 3, bmnl: 4, nql: 3, benl: 25\n\n// bmpl: x, pql: x, bepl: x => 1\n// bmpl: 6, pql: 5, bepl: 20 => \n// bmpl: 6, pql: 5, bepl: 50 => ?\n// bmpl: 50, pql: 5, bepl: 50 => ?\n// bmpl: 50, pql: 5, bepl: 50 => ?\n// bmpl: 45, pql: 40, bepl: 50 => ?\n// 18 * 0.0001\n\n// 1 - 0 => 1\n// \n// f(a,b,c) : a == b == c => 1\n// f(a,b,c) : a - b is small c is small is better\n// f(a,b,c) : a - b is small c is big is worse\n\n });\n\n console.debug(results.length + \" matches\");\n\n var result_html = '<ul></ul>';\n if (results.length > 1) {\n result_html = '<p class=\"num-results\">'+results.length+' hits</p><ul></ul>';\n }\n\n ff.$results.html(result_html);\n var $ul = ff.$results.find('ul');\n\n var i;\n for (i = 0 ; i < results.length; i++) {\n if (i > 9) break;\n var li = ff.renderResult($ul, results[i].entry, i, ff.url_prefix);\n results[i].pattern.patternHighlight(li);\n }\n\n var s = ff.$results.find('a[href=\"'+selected+'\"]');\n\n if (s.length) {\n s = s.parent();\n } else {\n s = ff.$results.find('li:first');\n }\n\n s.addClass('selected');\n\n $ul.find('a')/*.each(function(){\n $(this).attr('ref', $(this).attr('href'));\n $(this).attr('href', 'javascript:void(null);return false');\n })*/.click(function(){\n var $a = $(this);\n if (ff.use_cached_hits) {\n var href = $a.get(0).findanything_data.href;\n if (!ff.cached_hits[href])\n ff.cached_hits[href] = [];\n\n ff.cached_hits[href].push(Date.now());\n\n if (ff.hit_cacher == 'cookie') {\n $.cookie.json = true;\n $.cookie('findanything_hits', ff.cached_hits);\n $.cookie('findanything_last_aged', this.cached_hits_last_aged);\n }\n }\n return true;\n });\n\n // this must not be here! There must be rather a onSearch...\n $.modal.update(ff.$ui.outerHeight()+'px', ff.width);\n //$.modal.update(ff.$ui.height()+'px');\n }\n \t }\n }\n }",
"function findNextOccurrence(state, query) {\n let { main, ranges } = state.selection\n let word = state.wordAt(main.head),\n fullWord = word && word.from == main.from && word.to == main.to\n for (\n let cycled = false,\n cursor = new SearchCursor(\n state.doc,\n query,\n ranges[ranges.length - 1].to\n );\n ;\n\n ) {\n cursor.next()\n if (cursor.done) {\n if (cycled) return null\n cursor = new SearchCursor(\n state.doc,\n query,\n 0,\n Math.max(0, ranges[ranges.length - 1].from - 1)\n )\n cycled = true\n } else {\n if (cycled && ranges.some((r) => r.from == cursor.value.from))\n continue\n if (fullWord) {\n let word = state.wordAt(cursor.value.from)\n if (\n !word ||\n word.from != cursor.value.from ||\n word.to != cursor.value.to\n )\n continue\n }\n return cursor.value\n }\n }\n }",
"function autocomplete (index, query) {\n var reg, matches = [];\n\n query = query.trim();\n var queryItems = query.split(' ');\n\n // kindof hacky but supports input like 198:111\n if (query.indexOf(':') != -1) {\n var nums = query.split(':');\n if (tryNumber(nums[0])) {\n queryItems = [nums[0], nums[1]];\n }\n }\n\n // If the last token looks like a number and is the right length, don't use it\n // when looking for subjects because its probably a courseno\n\n // Also, if queryItems.length is 1 then this is a subjno, not a courseno\n\n var courseno = queryItems[queryItems.length - 1];\n if (tryNumber(courseno) && queryItems.length > 1) {\n queryItems.pop();\n query = queryItems.join(' ');\n } else courseno = null;\n\n var subjno = queryItems[0];\n if (tryNumber(subjno)) {\n if (index.ids[subjno]) matches.push({subj: subjno});\n }\n\n // fuzzy search of subject names\n if (query.length > 2) {\n var temp = fuzzy(index.names, query);\n\n matches = matches.concat(_.map(temp, function (item) {\n return {subj: item};\n }));\n } \n\n // Search subject abbreviations\n if (index.abbrevs[query.toUpperCase()]) {\n matches = matches.concat(_.map(index.abbrevs[query.toUpperCase()], function (id) {\n return {subj: id};\n }));\n }\n\n // if we have a courseno try to locate it in the subjects we found\n if (courseno) {\n if (matches.length > 0) {\n matches = _.reduce(matches, function (memo, item) {\n var idx;\n if (index.ids[item.subj].courses[courseno]) {\n memo.push({subj: item.subj, course: courseno});\n }\n return memo;\n }, []);\n }\n }\n\n // search all courses.. only do this if we couldn't find anything else\n if (matches.length === 0 && query.length > 2) {\n matches = fuzzy(index.courses, query);\n }\n\n return matches;\n}",
"function handleSearchTerm(event) {\n setSearchTerm(event.target.value);\n }",
"function search(treeName, searchTreeName, sbName, value) {\n\t\n\tif (value.length > 0) {\n\t\tif ($(sbName).searchbox('options').prompt == 'Search test suite') {\n\t\t\t$.messager.progress({text:'Searching test suite...'});\n\t\t\t$.post('src/testscript/searchTestSuites.php', {username:username, search:value}, function(result) {\n\t\t\t\t$.messager.progress('close');\n\t\t\n\t\t\t\t$(treeName).hide();\n\t\t\t\t$(searchTreeName).tree({\n\t\t\t\t\tdata:JSON.parse(result)\n\t\t\t\t});\n\t\t\t\t$(searchTreeName).show();\n\t\t\t});\n\t\t} else {\n\t\t\t$.messager.progress({text:'Searching test plan...'});\n\t\t\t$.post('src/testscript/searchTestPlan.php', {username:username, search:value}, function(result) {\n\t\t\t\t$.messager.progress('close');\n\t\t\n\t\t\t\t$(treeName).hide();\n\t\t\t\t$(searchTreeName).tree({\n\t\t\t\t\tdata:JSON.parse(result)\n\t\t\t\t});\n\t\t\t\t$(searchTreeName).show();\n\t\t\t});\n\t\t}\n\t} else {\n\t\talert('Please enter search word.');\n\t}\n}",
"function searchInput(parentNode, options) {\n var KEYCODE_ESC = 27;\n var KEYCODE_RETURN = 13;\n var $parentNode = $(parentNode);\n var firstSearch = true;\n\n var defaults = {\n initialVal: \"\",\n name: \"search\",\n placeholder: \"search\",\n classes: \"\",\n onclear: function() {},\n onfirstsearch: null,\n onsearch: function(inputVal) {},\n minSearchLen: 0,\n escWillClear: true,\n oninit: function() {}\n };\n\n // .................................................................... input rendering and events\n // visually clear the search, trigger an event, and call the callback\n function clearSearchInput(event) {\n var $input = $(this)\n .parent()\n .children(\"input\");\n $input\n .val(\"\")\n .trigger(\"searchInput.clear\")\n .blur();\n options.onclear();\n }\n\n // search for searchTerms, trigger an event, call the appropo callback (based on whether this is the first)\n function search(event, searchTerms) {\n if (!searchTerms) {\n return clearSearchInput();\n }\n $(this).trigger(\"search.search\", searchTerms);\n if (typeof options.onfirstsearch === \"function\" && firstSearch) {\n firstSearch = false;\n options.onfirstsearch(searchTerms);\n } else {\n options.onsearch(searchTerms);\n }\n }\n\n // .................................................................... input rendering and events\n function inputTemplate() {\n // class search-query is bootstrap 2.3 style that now lives in base.less\n return [\n '<input type=\"text\" name=\"',\n options.name,\n '\" placeholder=\"',\n options.placeholder,\n '\" ',\n 'class=\"search-query ',\n options.classes,\n '\" ',\n \"/>\"\n ].join(\"\");\n }\n\n // the search input that responds to keyboard events and displays the search value\n function $input() {\n return (\n $(inputTemplate())\n // select all text on a focus\n .focus(function(event) {\n $(this).select();\n })\n // attach behaviors to esc, return if desired, search on some min len string\n .keyup(function(event) {\n event.preventDefault();\n event.stopPropagation();\n\n // esc key will clear if desired\n if (event.which === KEYCODE_ESC && options.escWillClear) {\n clearSearchInput.call(this, event);\n } else {\n var searchTerms = $(this).val();\n // return key or the search string len > minSearchLen (if not 0) triggers search\n if (\n event.which === KEYCODE_RETURN ||\n (options.minSearchLen && searchTerms.length >= options.minSearchLen)\n ) {\n search.call(this, event, searchTerms);\n }\n }\n })\n .val(options.initialVal)\n );\n }\n\n // .................................................................... clear button rendering and events\n // a button for clearing the search bar, placed on the right hand side\n function $clearBtn() {\n return $(\n ['<span class=\"search-clear fa fa-times-circle\" ', 'title=\"', _l(\"clear search (esc)\"), '\"></span>'].join(\n \"\"\n )\n )\n .tooltip({ placement: \"bottom\" })\n .click(function(event) {\n clearSearchInput.call(this, event);\n });\n }\n\n // .................................................................... loadingIndicator rendering\n // a button for clearing the search bar, placed on the right hand side\n function $loadingIndicator() {\n return $(\n ['<span class=\"search-loading fa fa-spinner fa-spin\" ', 'title=\"', _l(\"loading...\"), '\"></span>'].join(\"\")\n )\n .hide()\n .tooltip({ placement: \"bottom\" });\n }\n\n // .................................................................... commands\n // visually swap the load, clear buttons\n function toggleLoadingIndicator() {\n $parentNode.find(\".search-loading\").toggle();\n $parentNode.find(\".search-clear\").toggle();\n }\n\n // .................................................................... init\n // string command (not constructor)\n if (jQuery.type(options) === \"string\") {\n if (options === \"toggle-loading\") {\n toggleLoadingIndicator();\n }\n return $parentNode;\n }\n\n // initial render\n if (jQuery.type(options) === \"object\") {\n options = jQuery.extend(true, {}, defaults, options);\n }\n //NOTE: prepended\n return $parentNode.addClass(\"search-input\").prepend([$input(), $clearBtn(), $loadingIndicator()]);\n}",
"function handleSearch(){\n var term = element( RandME.ui.search_textfield ).value;\n if(term.length){\n requestRandomGif( term, true);\n }\n}",
"function checkParcelSearchInput(defaultTextInput){\n\tvar inputTextVal = jQuery('.ptSearchCriteriaDiv').find('.ghostText').val();\n\tvar term=trim(inputTextVal);\n\tif (term!=defaultTextInput){ \n\t\tcallSearchParcel();\n\t} else {\n\t\treturn false;\n\t}\n}",
"searchMeal() {\n // Using fuse.js and defining searching key\n const options = {\n includeScore: true,\n keys: ['fields.strMeal']\n }\n const fuse = new Fuse(this.foodsArray, options)\n // Called createCards func for first initializing\n this.createCards(this.foodsArray)\n // Taking words from input to search meal\n let searchInputDOM = document.querySelector(\".search-input\")\n searchInputDOM.addEventListener(\"input\", (e) => {\n // setTimeout func was added to limit search operation by time for performance\n setTimeout(() => {\n\n let searchValue = e.target.value\n if (searchValue === \"\") {\n // If there is no word in input, it calls createCards func\n this.createCards(this.foodsArray)\n } else if(searchValue != \"\") {\n // If there is some words in input, it calls searchedCards func\n const result = fuse.search(searchValue)\n this.searchedCards(result)\n }\n }, 500)\n })\n }",
"function doSearch(){\n document.SearchCustomer.search.value = true;\n document.SearchCustomer.curpos.value=0;\n submit('SearchCustomer');\n }",
"function findNext(ctx, query) {\n doSearch(ctx, false, query);\n}",
"function search() {\n\t\tvar searchVal = searchText.getValue();\n\n\t\tsources.genFood.searchBar({\n\t\t\targuments: [searchVal],\n\t\t\tonSuccess: function(event) {\n\t\t\t\tsources.genFood.setEntityCollection(event.result);\n\t\t\t},\n\t\t\tonError: WAKL.err.handler\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the routes for this addon. Routes are defined in `config/routes.js`. The file should export a function that defines routes. See the Routing guide for details on how to define routes. | loadRoutes() {
this._routes = this.loadConfigFile('routes') || function() {};
} | [
"function getRoutes(folderName, file) {\n fs.readdirSync(folderName).forEach(function(file) {\n\n var fullName = path.join(folderName, file);\n var stat = fs.lstatSync(fullName);\n\n if (stat.isDirectory()) {\n getRoutes(fullName);\n } else if (file.toLowerCase().indexOf('.js')) {\n require('./' + fullName)(app);\n console.log(\"require('\" + fullName + \"')\");\n }\n });\n}",
"addRoutes (router, socket) {\n // get all routes\n // NOTE: make relative\n glob('./server/api/routes/**/*.js', (err, routes) => {\n if (err) console.log(err)\n // dynamically require all files\n _.each(routes, (routePath) => {\n var route = routePath\n route = route.replace('./server/api/routes', '').replace('.js', '/')\n require(path.resolve(routePath))(router, socket, route)\n })\n })\n }",
"mountRoutes() {}",
"function route_all(){\n\n /*\n Routing all\n */\n\n main_init()\n other_routes()\n\n}",
"get routes() {\n return JSON.parse(JSON.stringify(this._routes));\n }",
"collectRoutes(routeConfig, appConfig) {\n routeHelper.validateRouteConfig(routeConfig);\n middlewareHelper.requireMiddleware(appConfig);\n\n this._routes = routeHelper.collectRoutes(routeConfig, appConfig);\n }",
"function loadRoutes(routeConfigs, baseUrl, onDuplicateRoutes) {\n handleDuplicateRoutes(routeConfigs, onDuplicateRoutes);\n const res = {\n // To be written by `genRouteCode`\n routesConfig: '',\n routesChunkNames: {},\n registry: {},\n routesPaths: [(0, utils_1.normalizeUrl)([baseUrl, '404.html'])],\n };\n // `genRouteCode` would mutate `res`\n const routeConfigSerialized = routeConfigs\n .map((r) => genRouteCode(r, res))\n .join(',\\n');\n res.routesConfig = `import React from 'react';\nimport ComponentCreator from '@docusaurus/ComponentCreator';\n\nexport default [\n${indent(routeConfigSerialized)},\n {\n path: '*',\n component: ComponentCreator('*'),\n },\n];\n`;\n return res;\n}",
"_addStaticRoutes() {\n const app = this._app;\n\n if (Deployment.shouldServeClientCode()) {\n // Map Quill files into `/static/quill`. This is used for CSS files but\n // not for the JS code; the JS code is included in the overall JS bundle\n // file.\n app.use('/static/quill',\n express.static(path.resolve(Dirs.theOne.CLIENT_DIR, 'node_modules/quill/dist')));\n\n // Use the client bundler (which uses Webpack) to serve JS bundles. The\n // `:name` parameter gets interpreted by the client bundler to select\n // which bundle to serve.\n app.get('/static/js/:name.bundle.js', new ClientBundle().requestHandler);\n }\n\n // Use the configuration point to determine which directories to serve\n // HTML files and other static assets from. This includes (but is not\n // necessarily limited to) the top-level `index.html` and `favicon` files,\n // as well as stuff explicitly under `static/`.\n for (const dir of Deployment.ASSET_DIRS) {\n app.use('/', express.static(dir));\n }\n }",
"_initialize() {\n if ( this._initialized ) {\n return;\n }\n\n this._log(2, `Initializing Routes...`);\n\n //Add routing information to crossroads\n // todo: handle internal only routes\n // An internal only route can be used to keep track of UI state\n // But it will never update the URL\n // You can't use .go() to get to an internal route\n // You can only get it via directly calling dispatch(route, params)\n //\n let routes = this.routes;\n\n for (let route of routes) {\n this._log(3, `Initializing >> ${route.name}`);\n\n // Set basename\n route.set_basename(this._basename);\n // Set crossroads_route\n route._crossroads = this.crossroads.addRoute(route.path, this._make_crossroads_shim(route));\n }\n\n this._log(3, `Initialized ${routes.length} routes`);\n this._initialized = true;\n }",
"function loadAllRoutes() {\n for (let i = 0; i < routesNorth.length; i++) {\n createRouteThumbs(i, 'north-island-thumbs', routesNorth, northIslandThumbContainer);\n }\n for (let i = 0; i < routesSouth.length; i++) {\n createRouteThumbs(i, 'south-island-thumbs', routesSouth, southIslandThumbContainer);\n }\n for (let i = 0; i < routesBoth.length; i++) {\n createRouteThumbs(i, 'both-island-thumbs', routesBoth, bothIslandThumbContainer);\n }\n updateBadge();\n}",
"get_all_routes_action(req, res, next) {\n res.send(this.get('RouteRegistry').getAll().map(this._publishRoute));\n }",
"_setupRoutes() {\n // For requests to webhook handler path, make the webhook handler take care\n // of the requests.\n this.server.post(this.webhookOptions.path, (req, res, next) => {\n this.handler(req, res, error => {\n res.send(400, 'Error processing hook');\n this.logger.error({err: error}, 'Error processing hook');\n\n next();\n });\n });\n\n this.server.post('/builds/:bid/status/:context', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n this.server.post('/update', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n\n this.server.get('/pull-request/:owner/:repo/:pullRequestNumber', this.getPullRequest.bind(this));\n }",
"methodsAction(req, res) {\n const routes = [];\n const scenes = Object.keys(config.tradfri.scenes);\n\n for(let route = 0; route < scenes.length; route++) {\n routes.push(`/api/scene/${scenes[route]}`);\n }\n\n routes.push('/api/disco');\n\n this.jsonResponse(res, 200, { 'routes': routes });\n }",
"getRoutes() {\n let routes = [];\n this.getGroups().forEach(group => {\n routes = routes.concat(group.routes);\n });\n if (this.fallback) {\n routes = routes.concat(this.fallback.routes);\n }\n return routes;\n }",
"groupingRoutes() {\n if (!this.routes || this.routes.length <= 0) {\n throw Error(\"Route Names Data Not Found.\")\n }\n\n // Empty Routes File Content\n var moduleRoutes = \"\";\n\n moduleRoutes += \"<?php \\n\\n\";\n moduleRoutes += \"// \" + this.module + \" Module Routes\\n\";\n moduleRoutes += \"$routes->group('\" + this.routePrefix + \"', function($routes) {\";\n moduleRoutes += \"\\n\";\n\n for (const route of this.routes) {\n if (route.path !== undefined && route.method && route.controller) {\n moduleRoutes += \" $routes->\" + route.requestMethod + \"('\" + route.path.slice(1) + \"', '\" + route.controller + \"::\" + route.method + \"');\";\n moduleRoutes += \"\\n\";\n }\n }\n\n moduleRoutes += \"});\\n\";\n\n // Module API Routes\n if (this.apiContent === true) {\n moduleRoutes += \"\\n// \" + this.module + \" Module API Routes\\n\";\n moduleRoutes += \"$routes->group('\" + this.apiRoutePrefix + \"', function($routes) {\\n\";\n moduleRoutes += \" $routes->group('\" + this.routePrefix + \"', function($routes) {\\n\";\n for (const route of this.apiRoutes) {\n if (route.path !== undefined && route.method && route.controller) {\n moduleRoutes += \" $routes->\" + route.requestMethod + \"('\" + route.path.slice(1) + \"', '\" + route.controller + \"::\" + route.method + \"');\";\n moduleRoutes += \"\\n\";\n }\n }\n moduleRoutes += \" });\\n\";\n moduleRoutes += \"});\\n\";\n }\n\n return moduleRoutes;\n }",
"function populateAllRoutes(){\n Request.find({}).populate('headers mapping').exec(function(err, requestsList){\n if (err){\n console.error(\"Failed to find routes on startup: \" + JSON.stringify(err));\n }\n // Restore our router to it's previous state before we had mounted any user routes\n router.stack.splice(previousRouterStackLength, router.stack.length);\n // Now, re-mount every route to ensure we're up to date\n requestsList.forEach(populateSingleRoute);\n });\n }",
"function loadRoutes(modeID) {\n\tdisableSubmit();\n\tresetOptions(selectObjRoute);\n\tresetOptions(selectObjDirection);\n\tdisableSelector(selectObjRoute);\n\tdisableSelector(selectObjDirection);\n\t\n\t// If 'Select' is selected then reset everything below.\n\tif(modeID == -1) {\n\n\t} else {\n\t\tconsole.log('Mode is: ' + modeID);\n\t\txhr(linesByModeURL(modeID), linesByModeCallback);\n\t}\n}",
"function noRoutes() {\n fs.removeSync(path.join(__dirname, 'tmp', 'routes.js'));\n fs.copySync(path.join(__dirname, 'assets', 'ftlRoutes.js'), ftlRoutesFilePath);\n fs.removeSync(combinedFilePath);\n processor.process(filePaths, combinedFilePath, function() {\n t.ok(fs.existsSync(combinedFilePath), 'routes don\\'t exist, combined file exists');\n var mod = helper.loadModule(combinedFilePath);\n t.ok(mod['GET /ftl'], 'routes don\\'t exist, combined has ftl components');\n noFTL();\n });\n }",
"function Router (routes) {\n this._routes = [];\n this._not_found = null;\n this._not_found_path = '/404';\n \n if (arguments.length === 1) {\n this.addRoutes(routes);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when component mounts, activate axiosCall | componentDidMount() {
this.axiosCall();
} | [
"componentDidMount() {\n this.callAPI();\n}",
"componentDidMount() {\n this.getUserApi();\n }",
"componentWillMount () {\n // we store the interceptors to remove them in componentWillUnmount\n this.reqInterceptors = axios.interceptors.request.use(req => {\n // always clean possible previous errors\n this.setState({error: null});\n return req;\n });\n // we are interested in intercept only the errors here \n this.resInterceptors = axios.interceptors.response.use(res => res, error => {\n this.setState({error: error});\n });\n }",
"componentWillMount() {\n\n \n\n axios.get(`${ROOT_URL}/activities`).then(response => {\n this.setState({ activities: response.data });\n });\n }",
"get axios()\n {\n return this._axios\n }",
"callApi(method, url, header, data) {\n\t\t//Make a call to the API\n\t\taxios({\n\t\t\tmethod: method,\n\t\t\turl: url,\n\t\t\theaders: header,\n\t\t\tdata: data\n\t\t}) \n\t\t.then((response) => {\n\t\t\tconsole.log(response.data);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconsole.log(error);\n\t\t})\n\t}",
"get axios() {\n return this._axios;\n }",
"async componentDidMount() {\n const status = await QuizService.initialQuizStatus(\n TokenService.getAuthToken()\n );\n this.context.setQuizStatus(status);\n this.setState({ isLoading: false });\n }",
"componentDidMount() {\n axios.get(\"/api/customers\").then(response => {\n this.setState({ customerList: response.data });\n });\n }",
"componentWillMount(){\n if (!this.props.player.host){\n axios.get('https://mapboxwhereisit.herokuapp.com' + this.props.history.location.pathname)\n .then((json)=>{\n const data = json.data\n let {\n changeGameTitle,\n changeActiveStateAPI,\n setGameID\n } = this.props\n //If the game is active, not completed, then you can join and get basic data otherwise you cant\n if (data.active && !data.player && !data.completed){\n changeGameTitle(data.title)\n changeActiveStateAPI(data.active)\n setGameID(data._id)\n this.setState({loaded: true})\n } else {\n this.props.history.push('/')\n }\n })\n .catch((err)=>{\n this.props.history.push('/');\n console.log(err)\n })\n } else {\n this.setState({loaded: true})\n }\n }",
"function useAxios() {\n const [responses, setResponses] = useState([]);\n \n // name is not query (changed to resource) *******\n async function fetchData (url, resource=\"\") {\n try {\n const response = await axios(`${url}${resource}`);\n setResponses(resps => [...resps, {...response.data, id: uuid()}]);\n } catch {\n console.log('error happened in API call');\n }\n };\n \n return [responses, fetchData];\n}",
"componentDidMount() {\n if(this.mounted === true) {\n this.simulateUserActions()\n }\n }",
"componentDidMount() {\n fetch(\"/backendapiroute\")\n .then(rsp => rsp.json())\n .then(rsp => {\n window.apiHost = rsp.apiHost;\n this.setState({ apiHost: rsp.apiHost });\n })\n .catch(e => console.error(\"failed to get the api host\", e));\n }",
"async componentDidMount() {\n try {\n // returns a promise, rest of app will wait for this response\n // from amplify auth with cognito\n //await Auth.currentSession();\n // if 200 OK from above with session info then execute next\n //this.userHasAuthenticated(true);\n\n // if OK pull role from cognito custom attribute and store in state\n //this.userHasPermission(\"admin\");\n } catch ( err ) {\n\n /*\n if (err !== \"No current user\") {\n // eslint-disable-next-line\n alert(err);\n }\n */\n }\n // loading user session is asyn process, we need to make sure\n // that our app does not change state when it first loads\n // we wait to render until isAuthenticating is false\n this.setState({\n //isAuthenticating: false\n });\n }",
"componentDidMount() {\n // this.context.clearError()\n InitContentApiService.getAvatar()\n .then(res => this.setState({ currentAvatar: res }))\n // .catch(this.setState)\n }",
"componentDidMount(){\r\n this.getPlans();\r\n }",
"componentwillMount() {\n API.getEvent(this.props.match.params.id)\n .then(res => this.setState({ event: res.data }))\n .catch(err => console.log(err));\n }",
"componentDidMount() {\n const action = { type: 'FETCH_HOP_USAGE' };\n this.props.dispatch(action);\n }",
"componentDidMount(){\n axios.get('/projects').then( (res) =>{\n this.setState( () => {\n return {projects: res.data.projects};\n })\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: _fnScrollingWidthAdjust Purpose: Adjust a table's width to take account of scrolling Returns: Inputs: object:oSettings dataTables settings object node:n table node | function _fnScrollingWidthAdjust ( oSettings, n )
{
if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" )
{
/* When y-scrolling only, we want to remove the width of the scroll bar so the table
* + scroll bar will fit into the area avaialble.
*/
var iOrigWidth = $(n).width();
n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth );
}
else if ( oSettings.oScroll.sX !== "" )
{
/* When x-scrolling both ways, fix the table at it's current size, without adjusting */
n.style.width = _fnStringToCss( $(n).outerWidth() );
}
} | [
"updateWidth() {\n if (this.setupComplete) {\n let width = this.headerData.getWidth();\n this.width = '' + width;\n this.widthVal = width;\n $(`#rbro_el_table${this.id}`).css('width', (this.widthVal + 1) + 'px');\n }\n }",
"function i2uiShrinkScrollableTable(tableid)\r\n{\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null)\r\n {\r\n var newwidth = 100;\r\n //i2uitrace(1,\"==========\");\r\n //i2uitrace(1,\"tableitem clientwidth=\"+tableitem.clientWidth);\r\n //i2uitrace(1,\"tableitem offsetwidth=\"+tableitem.offsetWidth);\r\n //i2uitrace(1,\"tableitem scrollwidth=\"+tableitem.scrollWidth);\r\n //i2uitrace(1,\"headeritem clientwidth=\"+headeritem.clientWidth);\r\n //i2uitrace(1,\"headeritem offsetwidth=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"headeritem scrollwidth=\"+headeritem.scrollWidth);\r\n //i2uitrace(1,\"dataitem clientwidth=\"+dataitem.clientWidth);\r\n //i2uitrace(1,\"dataitem offsetwidth=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"dataitem scrollwidth=\"+dataitem.scrollWidth);\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n if (scrolleritem2 != null)\r\n {\r\n scrolleritem2.style.width = newwidth;\r\n scrolleritem2.width = newwidth;\r\n }\r\n scrolleritem.style.width = newwidth;\r\n scrolleritem.width = newwidth;\r\n tableitem.style.width = newwidth;\r\n tableitem.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n dataitem.width = newwidth;\r\n }\r\n}",
"function applyScrollCssRelationGrid() {\n\tvar tbodyObject = document.getElementById(\"entityGridTbody\");\n\tif (tbodyObject.scrollHeight > tbodyObject.clientHeight) {\n\t\t$(\"#mainRelationTable td:eq(2)\").css(\"width\", '23.3%');\n\t\t$(\"#mainRelationTable td:eq(4)\").css(\"width\", '15.05%');\n\t}\n}",
"function resizeTable (table, frameWidth) {\n\t\tvar data;\n\t\tvar columns = table.columns.everyItem().getElements();\n\t\tvar tableWidth = table.width + (table.columns[-1].rightEdgeStrokeWeight);\n\t\tvar excess = Math.abs (frameWidth - tableWidth);\n\t\tdata = adjustWidth (excess, columns);\n\t\tif (tableWidth > frameWidth) {\n\t\t\tdata.delta = -data.delta;\n\t\t}\n\t\tfor (var i = data.resizeable.length-1; i >= 0; i--) {\n\t\t\tdata.resizeable[i].width += data.delta;\n\t\t}\n\t}",
"function fixIndexWidth() {\n if ( jQuery( window ).width() >= 1230 ) {\n jQuery( '.indexes__item' ).each( function () {\n jQuery( this ).css( 'width', 'auto' );\n } );\n }\n }",
"function reassignWidth() {\n return data[accountGlobal.id].news[storyGlobal.id - 1].width;\n}",
"function i2uiResizeTable(mastertableid, minheight, minwidth, slavetableid, flag)\r\n{\r\n //i2uitrace(0,\"ResizeTable = \"+mastertableid);\r\n var tableitem = document.getElementById(mastertableid);\r\n var headeritem = document.getElementById(mastertableid+\"_header\");\r\n var dataitem = document.getElementById(mastertableid+\"_data\");\r\n var scrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(mastertableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n scrolleritem2 != null)\r\n {\r\n //i2uitrace(0,\"resizetable pre - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(0,\"resizetable pre - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(0,\"resizetable pre - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n scrolleritem2.width = \"100px\";\r\n scrolleritem2.style.width = \"100px\";\r\n scrolleritem.style.height = \"100px\";\r\n scrolleritem.width = \"100px\";\r\n scrolleritem.style.width = \"100px\";\r\n\r\n tableitem.style.width = \"100px\";\r\n dataitem.width = \"100px\";\r\n dataitem.style.width = \"100px\";\r\n headeritem.width = \"100px\";\r\n headeritem.style.width = \"100px\";\r\n\r\n //i2uitrace(0,\"resizetable post - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(0,\"resizetable post - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(0,\"resizetable post - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n var cmd = \"i2uiResizeScrollableArea('\"+mastertableid+\"', '\"+minheight+\"', '\"+minwidth+\"', '\"+slavetableid+\"', '\"+flag+\"')\";\r\n //setTimeout(cmd, 250);\r\n for (var i=0; i<4; i++)\r\n {\r\n eval(cmd);\r\n if (i2uiCheckAlignment(mastertableid))\r\n {\r\n break;\r\n }\r\n //i2uitrace(0,\"realigned after \"+i+\" attempts\");\r\n }\r\n }\r\n}",
"updateWidth() {\n if (!this.isMounted() || !controller.$contentColumn.length) return;\n\n const left = controller.$contentColumn.offset().left - $(window).scrollLeft();\n const padding = 18;\n let width = $(document.body).hasClass('ltr') ?\n left - padding :\n $(window).width() - (left + controller.$contentColumn.outerWidth()) - padding;\n if (cd.g.skin === 'minerva') {\n width -= controller.getContentColumnOffsets().startMargin;\n }\n\n // Some skins when the viewport is narrowed\n if (width <= 100) {\n this.$topElement.hide();\n this.$bottomElement.hide();\n } else {\n this.$topElement.show();\n this.$bottomElement.show();\n }\n\n this.$topElement.css('width', width + 'px');\n this.$bottomElement.css('width', width + 'px');\n }",
"function i2uiResizeColumns(tableid, shrink, copyheader, slave, headerheight)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n var len = headeritem.rows[lastheaderrow].cells.length;\r\n var len2 = len;\r\n\r\n //i2uitrace(1,\"ResizeColumns entry scroller width=\"+scrolleritem.offsetWidth);\r\n\r\n if (headerheight != null && len > 1)\r\n return i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight, slave);\r\n\r\n // check first if resize needed\r\n //i2uitrace(1,\"check alignment in ResizeColumns\");\r\n if (i2uiCheckAlignment(tableid))\r\n {\r\n //i2uitrace(1,\"skip alignment in ResizeColumns\");\r\n return headeritem.clientWidth;\r\n }\r\n\r\n // insert a new row which is the same as the header row\r\n // forces very nice alignment whenever scrolling rows alone\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check for bypass\");\r\n for (var i=0; i<len; i++)\r\n {\r\n if (headeritem.rows[lastheaderrow].cells[i].innerHTML !=\r\n dataitem.rows[dataitem.rows.length-1].cells[i].innerHTML)\r\n break;\r\n }\r\n if (i != len)\r\n {\r\n //i2uitrace(1,\"insert fake row table=[\"+tableid+\"]\");\r\n\t // this is the DOM api approach\r\n\t var newrow = document.createElement('tr');\r\n\t if (newrow != null)\r\n\t {\r\n\t\t dataitem.appendChild(newrow);\r\n\t\t var newcell;\r\n\t\t for (var i=0; i<len; i++)\r\n\t \t {\r\n\t\t newcell = document.createElement('td');\r\n\t\t newrow.appendChild(newcell);\r\n\t\t if (newcell != null)\r\n\t\t {\r\n\t\t\t newcell.innerHTML = headeritem.rows[lastheaderrow].cells[i].innerHTML;\r\n\t\t }\r\n\t\t }\r\n\t }\r\n }\r\n\r\n //i2uitrace(1,\"ResizeColumns post copy scroller width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"post copy header into data for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n var newwidth;\r\n newwidth = dataitem.scrollWidth;\r\n\r\n //i2uitrace(1,\"assigned width=\"+newwidth);\r\n dataitem.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n headeritem.width = newwidth;\r\n headeritem.style.width = newwidth;\r\n\r\n //i2uitrace(1,\"post static width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n // if processing master table, delete newly insert row and return\r\n if (scrolleritem2 != null && (slave == null || slave == 0))\r\n {\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check5 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check5 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"delete/hide fake row table=\"+tableid);\r\n var lastrow = dataitem.rows[dataitem.rows.length - 1];\r\n dataitem.deleteRow(dataitem.rows.length - 1);\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check6 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check6 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // size header columns to match data columns\r\n for (i=0; i<len; i++)\r\n {\r\n newColWidth=(i==0?dataitem.rows[0].cells[i].clientWidth:dataitem.rows[0].cells[i].clientWidth-12);\r\n headeritem.rows[lastheaderrow].cells[i].style.width = newColWidth;\r\n headeritem.rows[lastheaderrow].cells[i].width = newColWidth;\r\n if(i==0)\r\n {\r\n for(j=0; j<dataitem.rows.length; j++)\r\n {\r\n dataitem.rows[j].cells[0].style.width = newColWidth;\r\n dataitem.rows[j].cells[0].width = newColWidth;\r\n }\r\n }\r\n }\r\n\r\n //for (i=0; i<len; i++)\r\n // i2uitrace(1,\"check7 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check7 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"post hide width for \"+tableid);\r\n //i2uitrace(1,\"data: width=\"+dataitem.width+\" style.width=\"+dataitem.style.width+\" client=\"+dataitem.clientWidth+\" scroll=\"+dataitem.scrollWidth+\" offset=\"+dataitem.offsetWidth);\r\n //i2uitrace(1,\"header: width=\"+headeritem.width+\" style.width=\"+headeritem.style.width+\" client=\"+headeritem.clientWidth+\" scroll=\"+headeritem.scrollWidth+\" offset=\"+headeritem.offsetWidth);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns short version=\"+i2uiCheckAlignment(tableid));\r\n return newwidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$2 scroller: width=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentNode.tagName+\" owner height=\"+tableitem.parentNode.offsetHeight);\r\n //i2uitrace(1,\"id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n // may need to adjust width of header to accomodate scroller\r\n //i2uitrace(1,\"data height=\"+dataitem.clientHeight+\" scroller height=\"+scrolleritem.clientHeight+\" header height=\"+headeritem.clientHeight);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // if horizontal scrolling and scroller needed\r\n var adjust;\r\n if ((scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth) ||\r\n headeritem.rows[lastheaderrow].cells.length < 3)\r\n {\r\n adjust = 0;\r\n }\r\n else\r\n {\r\n //i2uitrace(1,\"header cellpadding=\"+headeritem.cellPadding);\r\n adjust = headeritem.cellPadding * 2;\r\n\r\n // do not alter last column unless it contains a treecell\r\n if(dataitem.rows[0].cells[len-1].id.indexOf(\"TREECELL_\") == -1)\r\n len--;\r\n }\r\n //i2uitrace(1,\"adjust=\"+adjust+\" len=\"+len+\" headeritem #cols=\"+headeritem.rows[0].cells.length);\r\n\r\n // if window has scroller, must fix header\r\n // but not if scrolling in both directions\r\n //i2uitrace(1,\"resizecolumns scrolleritem.style.overflowY=\"+scrolleritem.style.overflowY);\r\n //i2uitrace(1,\"resizecolumns scrolleritem2=\"+scrolleritem2);\r\n if(scrolleritem.style.overflowY == 'scroll' ||\r\n scrolleritem.style.overflowY == 'hidden')\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n dataitem.width = dataitem.clientWidth;\r\n dataitem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header and data widths\");\r\n }\r\n else\r\n {\r\n if(scrolleritem2 != null)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"fixed header2 shrink=\"+shrink+\" copyheader=\"+copyheader);\r\n shrink = 0;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$3 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n if (document.body.clientWidth < headeritem.clientWidth)\r\n {\r\n len++;\r\n adjust = 0;\r\n //i2uitrace(1,\"new adjust=\"+adjust+\" new len=\"+len);\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$4 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n if (shrink != null && shrink == 1)\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * dataitem.rows[0].cells.length;\r\n\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<headeritem.rows[lastheaderrow].cells.length-1; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink\");\r\n }\r\n\r\n //i2uitrace(1,\"$$$$$$5 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n len = Math.min(len, headeritem.rows[0].cells.length);\r\n\r\n //i2uitrace(1,\"start data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n var w1, w2, w3;\r\n for (var i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n\r\n //i2uitrace(1,\"pre i=\"+i+\" w1=\"+w1+\" w2=\"+w2+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" w1=\"+headeritem.rows[0].cells[i].clientWidth+\" w2=\"+dataitem.rows[0].cells[i].clientWidth+\" w3=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n // try to handle tables that need window scrollers\r\n if (headeritem.clientWidth != dataitem.clientWidth)\r\n {\r\n //i2uitrace(1,\"whoa things moved. table=\"+tableid+\" i=\"+i+\" len=\"+len);\r\n\r\n // if window has scroller, resize to window unless slave table\r\n if (document.body.scrollWidth != document.body.offsetWidth)\r\n {\r\n //i2uitrace(1,\"window has scroller! slave=\"+slave);\r\n if (slave == null || slave == 0)\r\n {\r\n dataitem.width = document.body.scrollWidth;\r\n dataitem.style.width = document.body.scrollWidth;\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n if (headeritem.clientWidth < dataitem.clientWidth)\r\n {\r\n headeritem.width = dataitem.clientWidth;\r\n headeritem.style.width = dataitem.clientWidth;\r\n }\r\n else\r\n {\r\n dataitem.width = headeritem.clientWidth;\r\n dataitem.style.width = headeritem.clientWidth;\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"$$$$$$6 scroller: width=\"+scrolleritem.offsetWidth);\r\n\r\n // now delete the fake row\r\n if (copyheader == null || copyheader == 1)\r\n {\r\n //i2uitrace(1,\"pre delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n if (scrolleritem2 == null && (slave == null || slave == 0))\r\n {\r\n if (document.all)\r\n {\r\n dataitem.deleteRow(dataitem.rows.length-1);\r\n }\r\n }\r\n\r\n //i2uitrace(1,\"post delete row - data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n }\r\n\r\n width = headeritem.clientWidth;\r\n\r\n //i2uitrace(1,\"check alignment after ResizeColumns long version\");\r\n //i2uiCheckAlignment(tableid);\r\n }\r\n //i2uitrace(1,\"WIDTH=\"+width);\r\n return width;\r\n}",
"function calculateWidth(){\n $('#jsGanttChartModal').css('width', ($(window).width() - 40) + 'px');\n $('#jsGanttChartDiv').css('maxHeight', ($(window).height() - 200) + 'px');\n calculateLeftWidth();\n }",
"function i2uiResizeMasterColumns(tableid, column1width, headerheight, fixedColumnWidths)\r\n{\r\n var width = 0;\r\n\r\n var tableitem = document.getElementById(tableid);\r\n var headeritem = document.getElementById(tableid+\"_header\");\r\n var dataitem = document.getElementById(tableid+\"_data\");\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null &&\r\n dataitem.rows.length > 0)\r\n {\r\n //i2uitrace(1,\"i2uiResizeMasterColumns id=\"+tableid+\" parent is \"+tableitem.parentElement.tagName+\" owner height=\"+tableitem.parentElement.clientHeight);\r\n\r\n var len, i, w1, w2, w3, adjust, len2;\r\n var lastheaderrow = headeritem.rows.length - 1;\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n len2 = len;\r\n\r\n // if horizontal scrolling and scroller needed\r\n if (scrolleritem2 != null &&\r\n scrolleritem2.clientWidth < headeritem.clientWidth)\r\n {\r\n adjust = 0;\r\n len--;\r\n }\r\n else\r\n {\r\n adjust = headeritem.cellPadding * 2;\r\n // do not alter last column\r\n len--;\r\n }\r\n\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n if( fixedColumnWidths )\r\n {\r\n i2uiResizeColumnsWithFixedHeaderHeight_new(tableid, headerheight, null, fixedColumnWidths );\r\n }\r\n else if (headerheight != null)\r\n {\r\n\t i2uiResizeColumns(tableid);\r\n i2uiResizeColumnsWithFixedHeaderHeight(tableid, headerheight);\r\n }\r\n else\r\n {\r\n dataitem.style.width = 5 * dataitem.rows[0].cells.length;\r\n headeritem.style.width = 5 * headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // shrink each column first\r\n // note: this may cause the contents to wrap\r\n // even if nowrap=\"yes\"is specified\r\n //i2uitrace(1,\"pre shrink\");\r\n for (i=0; i<len; i++)\r\n {\r\n //headeritem.rows[lastheaderrow].cells[i].width = 15;\r\n //dataitem.rows[0].cells[i].width = 15;\r\n }\r\n //i2uitrace(1,\"post shrink. adjust=\"+adjust);\r\n\r\n len = headeritem.rows[lastheaderrow].cells.length;\r\n\r\n // resize each column to max width between the tables\r\n // NOTE: the computed max may not equal either of the\r\n // current widths due to the adjustment\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n //i2uitrace(1,\"pre i=\"+i+\" header=\"+w1+\" data=\"+w2+\" max=\"+w3);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n\r\n if (w1 != w3)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n }\r\n if (w2 != w3)\r\n {\r\n dataitem.rows[0].cells[i].width = w3;\r\n }\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth);\r\n }\r\n //i2uitrace(1,\"end data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check1 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check1 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n }\r\n\r\n if (dataitem.clientWidth > headeritem.clientWidth)\r\n {\r\n headeritem.style.width = dataitem.clientWidth;\r\n //i2uitrace(1,\"header width set to data width\");\r\n }\r\n else\r\n if (dataitem.clientWidth < headeritem.clientWidth)\r\n {\r\n dataitem.style.width = headeritem.clientWidth;\r\n //i2uitrace(1,\"data width set to header width\");\r\n }\r\n\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check2 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check2 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n\r\n if (scrolleritem.clientWidth > dataitem.clientWidth)\r\n {\r\n dataitem.style.width = scrolleritem.clientWidth;\r\n headeritem.style.width = scrolleritem.clientWidth;\r\n //i2uitrace(1,\"both widths set to scroller width\");\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check3 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check3 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n // one last alignment\r\n if (!i2uiCheckAlignment(tableid))\r\n for (i=0; i<len; i++)\r\n {\r\n w1 = headeritem.rows[lastheaderrow].cells[i].clientWidth;\r\n w2 = dataitem.rows[0].cells[i].clientWidth;\r\n w3 = Math.max(w1,w2) - adjust;\r\n if (w1 != w3)\r\n headeritem.rows[lastheaderrow].cells[i].width = w3;\r\n if (w2 != w3)\r\n dataitem.rows[0].cells[i].width = w3;\r\n //LPMremoved\r\n //if (i2uitracelevel == -1)\r\n // dataitem.rows[0].cells[i].width = w1;\r\n //i2uitrace(1,\"post i=\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n }\r\n //for (i=0; i<len2; i++)\r\n // i2uitrace(1,\"check4 cell #\"+i+\" header=\"+headeritem.rows[lastheaderrow].cells[i].clientWidth+\" data=\"+dataitem.rows[0].cells[i].clientWidth);\r\n //i2uitrace(1,\"check4 header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth);\r\n\r\n //i2uitrace(1,\"FINAL data width=\"+dataitem.clientWidth+\" scroller width=\"+scrolleritem.clientWidth+\" header width=\"+headeritem.clientWidth+\" doc offset=\"+document.body.clientWidth+\" doc scroll=\"+document.body.scrollWidth);\r\n\r\n // if column 1 has a fixed width\r\n if (column1width != null && column1width > 0 && len > 1)\r\n {\r\n // assign both first columns to desired width\r\n headeritem.rows[lastheaderrow].cells[0].width = column1width;\r\n dataitem.rows[0].cells[0].width = column1width;\r\n\r\n // assign both first columns to narrowest\r\n var narrowest = Math.min(dataitem.rows[0].cells[0].clientWidth,\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n headeritem.rows[lastheaderrow].cells[0].width = narrowest;\r\n dataitem.rows[0].cells[0].width = narrowest;\r\n\r\n // determine the width difference between the first columns\r\n var spread = Math.abs(dataitem.rows[0].cells[0].clientWidth -\r\n headeritem.rows[lastheaderrow].cells[0].clientWidth);\r\n\r\n // determine how much each non-first column should gain\r\n spread = Math.ceil(spread/(len-1));\r\n\r\n // spread this difference across all non-first columns\r\n if (spread > 0)\r\n {\r\n for (i=1; i<len; i++)\r\n {\r\n headeritem.rows[lastheaderrow].cells[i].width = headeritem.rows[lastheaderrow].cells[i].clientWidth + spread;\r\n dataitem.rows[0].cells[i].width = dataitem.rows[0].cells[i].clientWidth + spread;\r\n }\r\n }\r\n\r\n // if desiring abolsute narrowest possible\r\n if (column1width == 1)\r\n {\r\n // if not aligned, take difference and put in last column of data table\r\n var diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n var loop = 0;\r\n // well, one call may not be enough\r\n while (diff > 0)\r\n {\r\n dataitem.rows[0].cells[len-1].width = dataitem.rows[0].cells[len-1].clientWidth + diff;\r\n loop++;\r\n\r\n // only try 4 times then stop\r\n if (loop > 4)\r\n break;\r\n diff = dataitem.rows[0].cells[0].clientWidth - headeritem.rows[lastheaderrow].cells[0].clientWidth;\r\n }\r\n }\r\n }\r\n\r\n width = dataitem.clientWidth;\r\n }\r\n //i2uitrace(1,\"i2uiResizeMasterColumns exit. return width=\"+width);\r\n return width;\r\n}",
"function i2uiResizeScrollableArea(mastertableid, minheight, minwidth, slavetableid, flag, slave2width, column1width, headerheight, disableScrollAdjust, fixedColumnWidths)\r\n{\r\n //i2uitrace(1,\"RSA height=\"+minheight+\" width=\"+minwidth+\" slave=\"+slavetableid+\" flag=\"+flag);\r\n var slavetableid2 = null;\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n slavetableid2 = slavetableid+\"2\";\r\n }\r\n\r\n var tableitem = document.getElementById(mastertableid);\r\n var headeritem = document.getElementById(mastertableid+\"_header\");\r\n var dataitem = document.getElementById(mastertableid+\"_data\");\r\n var scrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n\r\n if (tableitem != null &&\r\n headeritem != null &&\r\n dataitem != null &&\r\n scrolleritem != null)\r\n {\r\n // make the slave area as narrow as possible\r\n var slavewidth = 0;\r\n // this is for the margins of the page\r\n if (flag != null && flag != \"undefined\")\r\n {\r\n if (slave2width != null &&\r\n slave2width != 'undefined')\r\n {\r\n slavewidth = Math.ceil(2 * (flag / 1));\r\n }\r\n else\r\n {\r\n slavewidth = flag / 1;\r\n }\r\n }\r\n\r\n if (slavewidth == 0 &&\r\n slave2width != null &&\r\n slave2width != 'undefined')\r\n {\r\n slavewidth += i2uiScrollerDimension;\r\n }\r\n\r\n if (window.document.body != null &&\r\n (window.document.body.scroll == null ||\r\n window.document.body.scroll == 'yes' ||\r\n window.document.body.scroll == 'auto'))\r\n {\r\n slavewidth += i2uiScrollerDimension;\r\n }\r\n\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n //i2uitrace(1,\"pre slavetable1 \"+slavetableid+\" slavewidth=\"+slavewidth);\r\n var x = i2uiResizeColumns(slavetableid,1,1,1,headerheight);\r\n //i2uitrace(1,\"post slavetable1 \"+slavetableid+\" slavewidth=\"+slavewidth);\r\n slavewidth += x;\r\n }\r\n\r\n if (slavetableid2 != null &&\r\n slavetableid2 != 'undefined' &&\r\n document.getElementById(slavetableid2) != null)\r\n {\r\n var x = i2uiResizeColumns(slavetableid2,1,1,1,headerheight);\r\n //i2uitrace(1,\"slave2width=\"+x);\r\n //i2uitrace(1,\"slave2width=\"+slave2width);\r\n //i2uitrace(1,\"slave2width=\"+document.getElementById(slavetableid2+\"_header\").clientWidth);\r\n //i2uitrace(1,\"slave2width=\"+document.getElementById(slavetableid2+\"_header\").offsetWidth);\r\n //i2uitrace(1,\"slave2width=\"+document.getElementById(slavetableid2+\"_header\").scrollWidth);\r\n\r\n //i2uitrace(1,\"post slavetable2 \"+slavetableid2+\" slavewidth=\"+slavewidth);\r\n\r\n if (slave2width != null && slave2width != 'undefined')\r\n {\r\n slavewidth += slave2width;\r\n }\r\n else\r\n {\r\n slavewidth += x;\r\n }\r\n //i2uitrace(1,\"post buffer \"+slavetableid2+\" slavewidth=\"+slavewidth);\r\n }\r\n if (minwidth != null && minwidth != 'undefined')\r\n {\r\n var scrolleritem2 = document.getElementById(mastertableid+\"_header_scroller\");\r\n if (scrolleritem2 != null)\r\n {\r\n var newwidth;\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n newwidth = Math.max(headeritem.clientWidth, dataitem.clientWidth);\r\n newwidth = Math.min(newwidth, minwidth);\r\n newwidth = Math.max(minwidth, document.body.offsetWidth - slavewidth);\r\n }\r\n else\r\n {\r\n newwidth = minwidth;\r\n }\r\n\r\n newwidth = Math.max(1,newwidth);\r\n\r\n //i2uitrace(1,\"smarter - minwidth (desired)=\"+minwidth);\r\n\r\n //i2uitrace(1,\"smarter pre - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"smarter pre - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"smarter pre - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n\r\n scrolleritem2.style.width = newwidth;\r\n scrolleritem2.width = newwidth;\r\n scrolleritem.style.width = newwidth;\r\n scrolleritem.width = newwidth;\r\n tableitem.style.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n\r\n // if scroller present for rows, add extra width to data area\r\n var adjust = scrolleritem2.clientWidth - scrolleritem.clientWidth;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n } \r\n //i2uitrace(1,\"width adjust=\"+adjust);\r\n if (adjust != 0)\r\n {\r\n scrolleritem.style.width = newwidth + adjust;\r\n }\r\n //i2uitrace(1,\"smarter post - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"smarter post - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"smarter post - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n //i2uitrace(1,\"smarter - newwidth (actual)=\"+newwidth);\r\n if (newwidth != scrolleritem.clientWidth)\r\n {\r\n newwidth--;\r\n scrolleritem2.style.width = newwidth;\r\n scrolleritem.style.width = newwidth + adjust;\r\n tableitem.style.width = newwidth;\r\n dataitem.style.width = newwidth;\r\n\r\n //i2uitrace(1,\"smarter post3 - client: header=\"+headeritem.clientWidth+\" data=\"+dataitem.clientWidth+\" scroller=\"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"smarter post3 - offset: header=\"+headeritem.offsetWidth+\" data=\"+dataitem.offsetWidth+\" scroller=\"+scrolleritem.offsetWidth);\r\n //i2uitrace(1,\"smarter post3 - scroll: header=\"+headeritem.scrollWidth+\" data=\"+dataitem.scrollWidth+\" scroller=\"+scrolleritem.scrollWidth);\r\n }\r\n\r\n // if aligned and scroller present, then skip re-alignment\r\n // however, doesn't mean table couldn't be more efficient\r\n var skip = false;\r\n //i2uitrace(1,\"check alignment in ResizeScrollableArea\");\r\n if (headerheight == null &&\r\n i2uiCheckAlignment(mastertableid) &&\r\n (headeritem.clientWidth > scrolleritem.clientWidth ||\r\n dataitem.clientWidth > scrolleritem.clientWidth))\r\n {\r\n //i2uitrace(1,\"check1 \"+scrolleritem.scrollWidth+\" != \"+scrolleritem.clientWidth);\r\n //i2uitrace(1,\"check2 \"+scrolleritem.scrollWidth+\" == \"+headeritem.scrollWidth);\r\n //i2uitrace(1,\"check3 \"+headeritem.scrollWidth+\" == \"+headeritem.clientWidth);\r\n //i2uitrace(1,\"columns aligned but ResizeTable may be needed\");\r\n\r\n skip = true;\r\n //i2uitrace(1,\"skip alignment in ResizeScrollableArea\");\r\n }\r\n if (!skip)\r\n {\r\n // scroll items to far left\r\n scrolleritem.scrollLeft = 0;\r\n scrolleritem2.scrollLeft = 0;\r\n\r\n // now resize columns to handle new overall width\r\n i2uiResizeMasterColumns(mastertableid, column1width, headerheight, fixedColumnWidths);\r\n\r\n //i2uitrace(1,\"check alignment after ResizeMasterColumns\");\r\n if (!i2uiCheckAlignment(mastertableid))\r\n {\r\n //i2uitrace(1,\"spawn ResizeColumns\");\r\n var cmd = \"i2uiResizeColumns('\"+mastertableid+\"',1,1)\";\r\n setTimeout(cmd, 250);\r\n }\r\n\r\n //i2uitrace(1,\"post3 header width=\"+headeritem.clientWidth+\" data width=\"+dataitem.clientWidth+\" desired width=\"+minwidth);\r\n //i2uitrace(1,\"post3 header width=\"+headeritem.offsetWidth+\" data width=\"+dataitem.offsetWidth+\" desired width=\"+minwidth);\r\n }\r\n }\r\n }\r\n if (minheight != null &&\r\n minheight != 'undefined' &&\r\n (slavetableid == null ||\r\n slavetableid != 'undefined'))\r\n {\r\n var newheight = Math.max(1, Math.min(dataitem.clientHeight, minheight));\r\n\r\n scrolleritem.style.height = newheight;\r\n\r\n // check if scroller beneath\r\n var adjust = dataitem.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n } \r\n //i2uitrace(1,\"setting height. adjust=\"+adjust);\r\n if (adjust != 0)\r\n {\r\n scrolleritem.style.height = newheight + Math.min(i2uiScrollerDimension,adjust);\r\n }\r\n\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n var dataitem2 = document.getElementById(slavetableid+\"_data\");\r\n var scrolleritem2 = document.getElementById(slavetableid+\"_scroller\");\r\n //i2uitrace(1,\"pre data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"pre scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n if (scrolleritem2 != null &&\r\n dataitem2 != null)\r\n {\r\n scrolleritem2.style.height = newheight;\r\n\r\n var adjust = scrolleritem2.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n }\r\n\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"setting slave height. adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem2.style.height = newheight - adjust;\r\n }\r\n }\r\n\r\n // now fix height of slave2 if defined\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n //i2uitrace(1,\"fix slave2\");\r\n var scrolleritem3 = document.getElementById(slavetableid2+\"_scroller\");\r\n if (scrolleritem3 != null)\r\n {\r\n //i2uitrace(1,\"fix scrolleritem3\");\r\n scrolleritem3.style.height = newheight;\r\n\r\n var adjust = scrolleritem3.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0; \r\n }\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem3.style.height = newheight - adjust;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n // now fix each row between the master and slave to be of same height\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n //i2uitrace(1,\"fix each row\");\r\n var dataitem2 = document.getElementById(slavetableid+\"_data\");\r\n if (dataitem2 != null)\r\n {\r\n var dataitem3 = null;\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n dataitem3 = document.getElementById(slavetableid2+\"_data\");\r\n }\r\n\r\n var len;\r\n\r\n // compute if any row grouping is occuring between slave and master\r\n var masterRowsPerSlaveRow = 1;\r\n // fakerow will be 1 if slave has extra row used to align columns\r\n var fakerow = 0;\r\n // if 2 slave tables\r\n if (dataitem3 != null)\r\n {\r\n //if (dataitem.rows.length % dataitem3.rows.length > 0)\r\n if (i2uiCheckForAlignmentRow(slavetableid2))\r\n {\r\n fakerow = 1;\r\n }\r\n masterRowsPerSlaveRow = Math.max(1,parseInt(dataitem.rows.length / (dataitem3.rows.length - fakerow)));\r\n }\r\n else\r\n {\r\n //if (dataitem.rows.length % dataitem2.rows.length > 0)\r\n if (i2uiCheckForAlignmentRow(slavetableid))\r\n {\r\n fakerow = 1;\r\n }\r\n masterRowsPerSlaveRow = Math.max(1,parseInt(dataitem.rows.length / (dataitem2.rows.length - fakerow)));\r\n }\r\n //i2uitrace(0, \"table \"+mastertableid+\" masterRows=\"+dataitem.rows.length+\" slaveRows=\"+dataitem2.rows.length);\r\n //i2uitrace(0, \"table \"+mastertableid+\" masterRowsPerSlaveRow=\"+masterRowsPerSlaveRow);\r\n\r\n // if 2 slave tables and masterRowsPerSlaveRow is not 1,\r\n // align master and inner slave first row for row\r\n if (dataitem3 != null && masterRowsPerSlaveRow > 1)\r\n {\r\n len = dataitem.rows.length;\r\n //i2uitrace(1, \"fix \"+len+\" rows between master and inner slave\");\r\n for (var i=0; i<len; i++)\r\n {\r\n var h1 = dataitem.rows[i].clientHeight;\r\n var h2 = dataitem2.rows[i].clientHeight;\r\n if (h1 != h2)\r\n {\r\n var h3 = Math.max(h1,h2);\r\n if (h1 != h3)\r\n dataitem.rows[i].style.height = h3;\r\n else\r\n if (h2 != h3)\r\n dataitem2.rows[i].style.height = h3;\r\n }\r\n }\r\n }\r\n\r\n // align master with sole slave or\r\n // both slaves when masterRowsPerSlaveRow is 1\r\n len = dataitem.rows.length / masterRowsPerSlaveRow;\r\n //i2uitrace(1, \"fix \"+len+\" rows between master and outer slave\");\r\n var j;\r\n var delta;\r\n var remainder;\r\n var k;\r\n for (var i=0; i<len; i++)\r\n {\r\n j = i * masterRowsPerSlaveRow;\r\n var h1 = dataitem.rows[j].clientHeight;\r\n for (k=1; k<masterRowsPerSlaveRow; k++)\r\n {\r\n h1 += dataitem.rows[j+k].clientHeight;\r\n h1++;\r\n }\r\n\r\n var h2 = dataitem2.rows[i].clientHeight;\r\n var h3 = Math.max(h1,h2);\r\n\r\n //i2uitrace(1, \"row i=\"+i+\" j=\"+j+\" h1=\"+h1+\" h2=\"+h2+\" h3=\"+h3);\r\n\r\n if (masterRowsPerSlaveRow == 1)\r\n {\r\n if (dataitem3 != null && dataitem3.rows[i] != null)\r\n {\r\n h3 = Math.max(h3, dataitem3.rows[i].clientHeight);\r\n //i2uitrace(1, \" new h3=\"+h3);\r\n if (dataitem3.rows[i].clientHeight != h3)\r\n dataitem3.rows[i].style.height = h3;\r\n }\r\n if (dataitem.rows[i].clientHeight != h3)\r\n dataitem.rows[i].style.height = h3;\r\n if (dataitem2.rows[i].clientHeight != h3)\r\n dataitem2.rows[i].style.height = h3;\r\n }\r\n else\r\n {\r\n if (dataitem3 != null)\r\n {\r\n // if combined height is more than outer slave\r\n if (h3 > dataitem3.rows[i].clientHeight)\r\n {\r\n //i2uitrace(1, \" new h3=\"+h3);\r\n dataitem3.rows[i].style.height = h3;\r\n }\r\n else\r\n {\r\n // increase height of last row in group\r\n //k = j + masterRowsPerSlaveRow - 1;\r\n //delta = h3 - h1;\r\n //dataitem.rows[k].style.height = dataitem.rows[k].clientHeight + delta;\r\n //dataitem2.rows[k].style.height = dataitem2.rows[k].clientHeight + delta;\r\n\r\n // increase height of each row in group\r\n // any remainder is added to last row in group\r\n k = j + masterRowsPerSlaveRow - 1;\r\n delta = dataitem3.rows[i].clientHeight - h1;\r\n remainder = delta % masterRowsPerSlaveRow;\r\n delta = parseInt(delta / masterRowsPerSlaveRow);\r\n //i2uitrace(1,\"i=\"+i+\" j=\"+j+\" k=\"+k+\" summed=\"+h1+\" slave=\"+dataitem3.rows[i].clientHeight+\" delta=\"+delta+\" remainder=\"+remainder);\r\n for (k=0; k<masterRowsPerSlaveRow-1; k++)\r\n {\r\n //x = j+k;\r\n //i2uitrace(1,\"change inner row \"+x+\" by \"+delta);\r\n dataitem.rows[j+k].style.height = dataitem.rows[j+k].clientHeight + delta;\r\n dataitem2.rows[j+k].style.height = dataitem2.rows[j+k].clientHeight + delta;\r\n }\r\n k = j + masterRowsPerSlaveRow - 1;\r\n //x = delta+remainder;\r\n //i2uitrace(1,\"change final row \"+k+\" by \"+x);\r\n dataitem.rows[k].style.height = dataitem.rows[k].clientHeight + delta + remainder;\r\n dataitem2.rows[k].style.height = dataitem2.rows[k].clientHeight + delta + remainder;\r\n }\r\n }\r\n else\r\n {\r\n // if combined height is more than slave\r\n if (h3 > dataitem2.rows[i].clientHeight)\r\n {\r\n dataitem2.rows[i].style.height = h3;\r\n }\r\n else\r\n {\r\n // increase height of last row in group\r\n //k = j + masterRowsPerSlaveRow - 1;\r\n //delta = Math.max(0,dataitem2.rows[i].clientHeight - h1);\r\n //dataitem.rows[k].style.height += delta;\r\n\r\n // increase height of each row in group\r\n // any remainder is added to last row in group\r\n k = j + masterRowsPerSlaveRow - 1;\r\n delta = dataitem2.rows[i].clientHeight - h1;\r\n remainder = delta % masterRowsPerSlaveRow;\r\n delta = parseInt(delta / masterRowsPerSlaveRow);\r\n //i2uitrace(1,\"i=\"+i+\" j=\"+j+\" k=\"+k+\" master=\"+h1+\" slave=\"+dataitem2.rows[i].clientHeight+\" delta=\"+delta+\" remainder=\"+remainder);\r\n for (k=0; k<masterRowsPerSlaveRow-1; k++)\r\n {\r\n //x = j+k;\r\n //i2uitrace(1,\"change inner row \"+x+\" by \"+delta);\r\n dataitem.rows[j+k].style.height = dataitem.rows[j+k].clientHeight + delta;\r\n }\r\n k = j + masterRowsPerSlaveRow - 1;\r\n //x = delta +remainder;\r\n //i2uitrace(1,\"change final row \"+k+\" by \"+x);\r\n dataitem.rows[k].style.height = dataitem.rows[k].clientHeight + delta + remainder;\r\n }\r\n }\r\n }\r\n }\r\n //i2uitrace(1,\"row heights all fixed\");\r\n\r\n // set minheight after resizing each row\r\n if (minheight != null && minheight != 'undefined')\r\n {\r\n var newheight = Math.max(1, Math.min(Math.max(dataitem.clientHeight,dataitem2.clientHeight), minheight));\r\n\r\n scrolleritem.style.height = newheight;\r\n\r\n // check if scroller beneath\r\n var adjust = dataitem.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0;\r\n }\r\n //i2uitrace(1,\"setting height. adjust=\"+adjust);\r\n if (adjust != 0)\r\n {\r\n scrolleritem.style.height = newheight + Math.min(i2uiScrollerDimension,adjust);\r\n }\r\n\r\n if (slavetableid != null && slavetableid != 'undefined')\r\n {\r\n var dataitem2 = document.getElementById(slavetableid+\"_data\");\r\n var scrolleritem2 = document.getElementById(slavetableid+\"_scroller\");\r\n //i2uitrace(1,\"pre data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"pre scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n\r\n scrolleritem2.style.height = newheight;\r\n\r\n var adjust = scrolleritem2.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0;\r\n }\r\n\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"setting slave height. adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem2.style.height = newheight - adjust;\r\n }\r\n\r\n // now fix height of slave2 if defined\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n //i2uitrace(1,\"fix slave2\");\r\n var scrolleritem3 = document.getElementById(slavetableid2+\"_scroller\");\r\n if (scrolleritem3 != null)\r\n {\r\n //i2uitrace(1,\"fix scrolleritem3\");\r\n scrolleritem3.style.height = newheight;\r\n\r\n var adjust = scrolleritem3.clientHeight - scrolleritem.clientHeight;\r\n if (disableScrollAdjust)\r\n {\r\n adjust = 0;\r\n }\r\n\r\n //i2uitrace(1,\"post data master=\"+dataitem.clientHeight+\" slave=\"+dataitem2.clientHeight);\r\n //i2uitrace(1,\"post scroller master=\"+scrolleritem.clientHeight+\" slave=\"+scrolleritem2.clientHeight);\r\n //i2uitrace(1,\"adjust=\"+adjust);\r\n\r\n if (adjust != 0)\r\n {\r\n scrolleritem3.style.height = newheight - adjust;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n var headeritem2 = document.getElementById(slavetableid+\"_header\");\r\n if (headeritem2 != null)\r\n {\r\n var headeritem3 = null;\r\n if (slavetableid2 != null && slavetableid2 != 'undefined')\r\n {\r\n headeritem3 = document.getElementById(slavetableid2+\"_header\");\r\n }\r\n\r\n var h1, h2, h3;\r\n var headerRows = headeritem.rows.length;\r\n var header2Rows = headeritem2.rows.length;\r\n\r\n if (headerRows == 1)\r\n {\r\n h1 = headeritem.rows[0].clientHeight;\r\n }\r\n else\r\n {\r\n h1 = -1;\r\n for (var k=0; k<headerRows; k++)\r\n {\r\n h1 += headeritem.rows[k].clientHeight;\r\n h1++;\r\n }\r\n }\r\n h2 = headeritem2.rows[0].clientHeight;\r\n h3 = Math.max(h1,h2);\r\n //i2uitrace(1,\"fix row height for headers. h1=\"+h1+\" h2=\"+h2+\" h3=\"+h3);\r\n if (headeritem3 != null)\r\n {\r\n var h4 = headeritem3.rows[0].clientHeight;\r\n var h5 = Math.max(h3,h4);\r\n if (headerRows == 1)\r\n {\r\n headeritem.rows[0].style.height = h5;\r\n }\r\n headeritem2.rows[0].style.height = h5;\r\n headeritem3.rows[0].style.height = h5;\r\n }\r\n else\r\n {\r\n if (headerRows == 1)\r\n {\r\n headeritem.rows[0].style.height = h3;\r\n }\r\n else\r\n if (header2Rows == 1)\r\n headeritem2.rows[0].style.height = h3;\r\n }\r\n //i2uitrace(1,\"post fix row height for headers. master=\"+headeritem.rows[0].clientHeight+\" slave=\"+headeritem2.rows[0].clientHeight);\r\n }\r\n }\r\n }\r\n}",
"function resizeDynamicScrollingPanels()\n{\n\tvar scrollingWrappers = $$('div.scrollingWrapper');\n\tvar productCells = $$('div.scrollingWrapper div.productCell');\n\t// we need to get this figure now, because the offset width of the visible product\n\t// differs from the offsetWidth of the not-visible product\n\tvar productOffsetWidth = productCells.first().offsetWidth;\n\n\tscrollingWrappers.each(\n\t\tfunction(currentElement)\n\t\t{\n\t\t\tif(currentElement.childElements().size() > 0)\n\t\t\t{\n\t\t\t\t// make the container big enough to handle all the children\n\t\t\t\t// the 1.1 is for margin of error\n\t\t\t\tcurrentElement.style.width = ((currentElement.childElements().size() * productOffsetWidth) * 1.02) + 'px';\n\t\t\t}\n\t\t}\n\t)\n}",
"function setSectionWidth(deviceWidth) {\n\n // querying all the elements with class section\n var sections = document.querySelectorAll(\"div.section\");\n // querying all the elements with class tool-div\n var toolDivs = document.querySelectorAll(\"div.tool-div\");\n\n var node;\n\n if (deviceWidth >= 1000) {\n for (node = 0; node < sections.length; node++) {\n sections[node].style.width = \"24%\";\n sections[node].style.marginLeft = \"8px\";\n toolDivs[node].style.overflow = \"auto\";\n toolDivs[node].style.height = \"96%\";\n }\n } else {\n for (node = 0; node < sections.length; node++) {\n sections[node].style.width = \"100%\";\n sections[node].style.marginLeft = \"0px\";\n toolDivs[node].style.overflow = \"initial\";\n }\n }\n}",
"recalculateColumnWidths() {\n if (!this._columnTree) {\n return; // No columns\n }\n if (this._cache.isLoading()) {\n this._recalculateColumnWidthOnceLoadingFinished = true;\n } else {\n const cols = this._getColumns().filter((col) => !col.hidden && col.autoWidth);\n this._recalculateColumnWidths(cols);\n }\n }",
"function columnedWidth() {\n var bd = columnedElement();\n var de = p.page.m.activeFrame.contentDocument.documentElement;\n\n var w = Math.max(bd.scrollWidth, de.scrollWidth);\n\n // Add one because the final column doesn't have right gutter.\n // w += k.GAP;\n\n if (!Monocle.Browser.env.widthsIgnoreTranslate && p.page.m.offset) {\n w += p.page.m.offset;\n }\n return w;\n }",
"function i2uiTableHasHorizontalScroller(tableid)\r\n{\r\n var rc = false;\r\n var scrolleritem = document.getElementById(tableid+\"_scroller\");\r\n var scrolleritem2 = document.getElementById(tableid+\"_header_scroller\");\r\n if (scrolleritem != null && scrolleritem2 != null)\r\n {\r\n var adjust = scrolleritem2.clientWidth - scrolleritem.clientWidth;\r\n if (adjust != 0)\r\n {\r\n rc = true;\r\n }\r\n }\r\n return rc;\r\n}",
"function i2uiResizeSlaveresize()\r\n{\r\n var distanceX = i2uiResizeSlavenewX - i2uiResizeSlaveorigX;\r\n //i2uitrace(1,\"resize dist=\"+distanceX);\r\n if (distanceX != 0)\r\n {\r\n //i2uitrace(1,\"resize variable=\"+i2uiResizeSlavewhichEl.id);\r\n\r\n // test that variable exists by this name\r\n if (i2uiIsVariableDefined(i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)))\r\n {\r\n var w = i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength);\r\n var newwidth = eval(w) + distanceX;\r\n //i2uitrace(1,\"distance=\"+distanceX+\" old width=\"+eval(w)+\" new width=\"+newwidth);\r\n\r\n var len = i2uiResizeWidthVariable.length;\r\n //i2uitrace(1,\"array len=\"+len);\r\n for (var i=0; i<len; i++)\r\n {\r\n if (i2uiResizeWidthVariable[i] == i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength))\r\n {\r\n //i2uitrace(1,\"resize slave2 table[\"+i2uiResizeSlave2Variable[i]+\"]\");\r\n //i2uitrace(1,\"resize master table[\"+i2uiResizeMasterVariable[i]+\"]\");\r\n\r\n // make newwidth the smaller of newwidth and scroll width\r\n var scrolleritem = document.getElementById(i2uiResizeSlave2Variable[i]+\"_scroller\");\r\n //i2uitrace(0,\"scrolleritem=\"+scrolleritem);\r\n if (scrolleritem != null)\r\n {\r\n //i2uitrace(1,\"scrolleritem=\"+scrolleritem);\r\n //i2uitrace(1,\"scroller: width=\"+scrolleritem.width+\" style.width=\"+scrolleritem.style.width+\" client=\"+scrolleritem.clientWidth+\" scroll=\"+scrolleritem.scrollWidth+\" offset=\"+scrolleritem.offsetWidth);\r\n newwidth = Math.min(newwidth,scrolleritem.scrollWidth);\r\n }\r\n\r\n // must know about row groupings !!\r\n i2uiResizeScrollableArea(i2uiResizeSlave2Variable[i],null,newwidth);\r\n i2uiResizeScrollableArea(i2uiResizeMasterVariable[i],null,20,i2uiResizeSlaveVariable[i],i2uiResizeFlagVariable[i],newwidth);\r\n eval(i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)+\"=\"+newwidth);\r\n break;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n window.status = \"ERROR: variable [\"+i2uiResizeSlavewhichEl.id.substring(i2uiResizeKeywordLength)+\"] not valid\";\r\n }\r\n }\r\n}",
"function fixMenuWidth() {\n\tvar ieVersion = getInternetExplorerVersion();\n\t\n\tif( ada$(menu.menuWrapEl).scrollHeight > ada$(shell.content.wrap).clientHeight ) {\n\t\tada$(menu.menuWrapEl).style.height = ada$(shell.content.wrap).clientHeight + 'px';\n\t\tada$(menu.scrollDiv).style.height = (ada$(shell.content.wrap).clientHeight - 29) + 'px';\n\t} else {\n\t\tada$(menu.menuWrapEl).style.height = 'auto';\n\t\tada$(menu.scrollDiv).style.height = 'auto';\n\t}\n\t\n\tif( ada$(menu.scrollDiv).scrollHeight > ada$(menu.scrollDiv).clientHeight) {\n\t\tif (ieVersion == 7) {\t\n\t\t\t// IE 7\n\t\t\t$(menu.menuContentEl).find('li').css('width', 225 + 'px');\n\t\t}\n\t\telse if (ieVersion < 7 && ieVersion > 0) {\t\n\t\t\t// IE 6\n\t\t\tif(ada$(menu.scrollDiv).clientHeight == 0)\n\t\t\t\t$(menu.menuContentEl).find('li').css('width', 242 + 'px');\n\t\t\telse\n\t\t\t\t$(menu.menuContentEl).find('li').css('width', 225 + 'px');\n\t\t}\n\t} else {\n\t\tif (ieVersion < 7 && ieVersion > 0) {\t\n\t\t\t// IE 6\n\t\t\t$(menu.menuContentEl).find('li').css('width', 242 + 'px');\n\t\t} else {\n\t\t\t$(menu.menuContentEl).find('li').css('width', 100 + '%');\n\t\t}\n\t}\n}",
"[resetRowWidth]() {\n\t\tconst self = this;\n\t\tself.width(self[CURRENT_AVAILABLE_WIDTH] - self[INDENT_WIDTH]);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve indirect symbol values to their final definitions. | indirectsym()
{
let changed;
do
{
changed = 0;
for (let sym = 0; sym < this.symbols.length; ++sym)
{
if (this.symbols[sym].value === null)
continue;
const cp = this.symbols[sym].value;
const [ ind ] = this.findsym(cp, 0);
if (ind === -1 || ind === sym ||
cp[0] != '\0' ||
this.symbols[ind] === null ||
this.symbols[ind].value === this.symbols[sym].value)
continue;
this.debugsym("indir...", sym);
this.symbols[sym].value = this.symbols[ind].value;
this.debugsym("...ectsym", sym);
changed++;
}
} while (changed);
} | [
"static async resolveNames(domain, types, value, resolveName) {\n // Make a copy to isolate it from the object passed in\n domain = Object.assign({}, domain);\n // Allow passing null to ignore value\n for (const key in domain) {\n if (domain[key] == null) {\n delete domain[key];\n }\n }\n // Look up all ENS names\n const ensCache = {};\n // Do we need to look up the domain's verifyingContract?\n if (domain.verifyingContract && !(0, index_js_4.isHexString)(domain.verifyingContract, 20)) {\n ensCache[domain.verifyingContract] = \"0x\";\n }\n // We are going to use the encoder to visit all the base values\n const encoder = TypedDataEncoder.from(types);\n // Get a list of all the addresses\n encoder.visit(value, (type, value) => {\n if (type === \"address\" && !(0, index_js_4.isHexString)(value, 20)) {\n ensCache[value] = \"0x\";\n }\n return value;\n });\n // Lookup each name\n for (const name in ensCache) {\n ensCache[name] = await resolveName(name);\n }\n // Replace the domain verifyingContract if needed\n if (domain.verifyingContract && ensCache[domain.verifyingContract]) {\n domain.verifyingContract = ensCache[domain.verifyingContract];\n }\n // Replace all ENS names with their address\n value = encoder.visit(value, (type, value) => {\n if (type === \"address\" && ensCache[value]) {\n return ensCache[value];\n }\n return value;\n });\n return { domain, value };\n }",
"resolve() {\n this.resolver.resolveAll(this.sources.definitions);\n }",
"function update_symbols(symbols, scopes, bound, free, classflag){\n var name,\n itr,\n v,\n v_scope,\n v_new,\n v_free,\n pos = 0\n\n /* Update scope information for all symbols in this scope */\n for(var name of _b_.dict.$keys_string(symbols)){\n var flags = _b_.dict.$getitem_string(symbols, name)\n v_scope = scopes[name]\n var scope = v_scope\n flags |= (scope << SCOPE_OFFSET)\n v_new = flags\n if (!v_new){\n return 0;\n }\n _b_.dict.$setitem_string(symbols, name, v_new)\n }\n\n /* Record not yet resolved free variables from children (if any) */\n v_free = FREE << SCOPE_OFFSET\n\n for(var name of free){\n\n v = _b_.dict.$get_string(symbols, name)\n\n /* Handle symbol that already exists in this scope */\n if (v !== _b_.dict.$missing) {\n /* Handle a free variable in a method of\n the class that has the same name as a local\n or global in the class scope.\n */\n if (classflag &&\n v & (DEF_BOUND | DEF_GLOBAL)) {\n var flags = v | DEF_FREE_CLASS;\n v_new = flags;\n if (! v_new) {\n return 0;\n }\n _b_.dict.$setitem_string(symbols, name, v_new)\n }\n /* It's a cell, or already free in this scope */\n continue;\n }\n /* Handle global symbol */\n if (bound && !bound.has(name)) {\n continue; /* it's a global */\n }\n /* Propagate new free symbol up the lexical stack */\n _b_.dict.$setitem_string(symbols, name, v_free)\n }\n\n return 1\n\n}",
"function lookupSymbol(symbol) {\n if (symbols[symbol] === undefined) {\n symbols[symbol] = lowestFreeROMAddress;\n lowestFreeROMAddress++;\n }\n return symbols[symbol];\n}",
"static isLateBoundSymbol(symbol) {\n // eslint-disable-next-line no-bitwise\n if (symbol.flags & ts.SymbolFlags.Transient &&\n symbol.checkFlags === ts.CheckFlags.Late) {\n return true;\n }\n return false;\n }",
"function performReferenceBackpatching()\n\t{\n\t\t// Before we backpatch, delete the string entries, because their addresses and offsets have already been determined\n\t\tfor(key in referenceTable)\n\t\t{\n\t\t\t// Delete string entries\n\t\t\tif(referenceTable[key].type === \"string\")\n\t\t\t\tdelete referenceTable[key];\n\t\t}\n\n\t\t// Iterate the reference table\n\t\tfor(key in referenceTable)\n\t\t{\n\t\t\t// Calculate the permanent memory location of this static variable (bytecodeList.length + offset) and put it in hex form\n\t\t\tvar location = (referenceTable[key].offset + _ByteCodeList.length - 1).toString(16).toUpperCase();\n\n\t\t\t// Make sure the location is two hex digits\n\t\t\tif(location.length === 1)\n\t\t\t\tlocation = \"0\" + location;\n\n\t\t\t// Iterate the bytecode list to find all occurances of this key\n\t\t\tfor(var i = 0; i < _ByteCodeList.length; i++)\n\t\t\t{\n\t\t\t\t// When found. replace with the permanent memory location\n\t\t\t\tif(_ByteCodeList[i] === key)\n\t\t\t\t\t_ByteCodeList.splice(i, 1, location)\n\t\t\t}\n\n\t\t\t// Delete the temp entry in the reference table\n\t\t\tdelete referenceTable[key];\n\t\t}\n\t}",
"unitsInitResolve()\n\t{\n\t\t//\n\t\t// Call parent method.\n\t\t//\n\t\tsuper.unitsInitResolve();\n\t\t\n\t\t//\n\t\t// Remove ambiguous document resolve.\n\t\t// Edges cannot have ambiguoug documents.\n\t\t//\n\t\tthis.resolveUnitDel( 'resolveAmbiguousObject' );\n\t\t\n\t\t//\n\t\t// Remove changed significant fields.\n\t\t// Edges have one set of significant fields which are also locked, in\n\t\t// addition, these fields automatically determine the value of the key, so\n\t\t// changing any of them would generate a new key, making this test redundant.\n\t\t//\n\t\tthis.resolveUnitDel( 'resolveChangeSignificantField' );\n\t\n\t}",
"function compile_sym(env, sym) {\n if (sym && sym.constructor === String) {\n return lookupSymbol(env, sym);\n }\n\n return undefined;\n}",
"function tokensThatResolveTo(value) {\n return literalTokensThatResolveTo(value).concat(cloudFormationTokensThatResolveTo(value));\n}",
"function resolveKnownDeclaration(decl) {\n switch (decl) {\n case host_1.KnownDeclaration.JsGlobalObject:\n return exports.jsGlobalObjectValue;\n case host_1.KnownDeclaration.TsHelperAssign:\n return assignTsHelperFn;\n case host_1.KnownDeclaration.TsHelperSpread:\n case host_1.KnownDeclaration.TsHelperSpreadArrays:\n return spreadTsHelperFn;\n default:\n throw new Error(\"Cannot resolve known declaration. Received: \" + host_1.KnownDeclaration[decl] + \".\");\n }\n }",
"function generate_canonical_map ( mod ) {\n var map = scope.make ( );\n function add_secondary_name ( obj, name ) {\n if ( obj.secondary_names !== undefined ) {\n obj.secondary_names = [];\n }\n obj.secondary_names.push ( name );\n }\n // We want the alphabetically first (\"smallest\") name.\n function add_new_name ( obj, name ) {\n if ( obj.canonical_name !== undefined ) {\n if ( obj.canonical_name > name ) {\n add_secondary_name ( obj, obj.canonical_name );\n obj.canonical_name = name;\n }\n else {\n add_secondary_name ( obj, name );\n }\n }\n else {\n obj.canonical_name = name;\n }\n }\n function gen_text ( scop, path, obj ) {\n scop.set_text ( path, obj );\n add_new_name ( obj, path );\n if ( obj.scope !== undefined ) {\n var named = [];\n misc.assert ( obj.objects !== undefined );\n obj.scope.each_text ( function ( key, child ) {\n if ( child.assignments.length === 1 ) {\n child = get_canonical_value ( child );\n if ( obj.objects.indexOf ( child ) !== -1 ) {\n gen_text ( scop, path + '.' + key, child );\n named.push ( child );\n }\n }\n } );\n for ( var i in obj.objects ) {\n var child = obj.objects[i];\n var name = path + '#' + i;\n add_secondary_name ( child, name );\n scop.set_text ( name, child );\n if ( named.indexOf ( child ) === -1 ) {\n // This object is not named.\n gen_text ( scop, path + '#' + i, child );\n child.canonical_name = name;\n }\n }\n }\n }\n mod.globals.each_text ( function ( key, glob ) {\n gen_text ( map, key, get_canonical_value ( glob ) );\n } );\n return map;\n }",
"function parseResolved(entry) {\n const resolved = entry.resolved;\n if (resolved) {\n const tokens = resolved.split(\"#\");\n entry.url = tokens[0];\n entry.sha1 = tokens[1];\n }\n}",
"static tryGetSymbolForDeclaration(declaration, checker) {\n let symbol = declaration.symbol;\n if (symbol && symbol.escapedName === ts.InternalSymbolName.Computed) {\n const name = ts.getNameOfDeclaration(declaration);\n symbol = name && checker.getSymbolAtLocation(name) || symbol;\n }\n return symbol;\n }",
"getResolve() {\n return {\n extensions: ['.js', '.jsx', '.ts', '.tsx'],\n alias: this.config.alias !== undefined ? _objectSpread({}, this.config.alias) : {}\n };\n }",
"function get_variable_aliases(resolve, reject) {\n // If the model has project_data, try to get aliases from it\n if (model.project_data && model.project_data[0]) {\n client\n .get_project_data_fetch({ did: model.project_data[0] })\n .then((project_data) => {\n if (project_data[\"artifact:variable_aliases\"]) {\n variable_aliases = project_data[\"artifact:variable_aliases\"];\n }\n // console.log(\"Set aliases from project_data\");\n resolve();\n })\n .catch(() => {\n // Disabling this alert and replacing with log entry because it comes up every time user opens the model.\n // Now I am writing to model's artifact if I can't get to the project data,\n // so we don't need this alert anymore.\n // window.alert(\n // 'Ooops, this model had project data in the past but it is no longer there. ' +\n // 'Original variable aliases can not be loaded. ' +\n // 'But we will try to load any aliases that were created after the project data disappeared. '\n // );\n console.log(\n \"Ooops, this model had project data in the past but it is no longer there. \" +\n \"Original variable aliases can not be loaded. \" +\n \"But we will try to load any aliases that were created after the project data disappeared.\"\n );\n // Something went wrong. We have a pointer to project data, but can't retrieve it.\n // Might have gotten deleted. So let's try to load aliases from the model's attributes\n // as a last-ditch effort.\n if (model[\"artifact:variable_aliases\"] !== undefined) {\n variable_aliases = model[\"artifact:variable_aliases\"];\n }\n resolve();\n });\n }\n // Otherwise try to get the aliases from the model's attributes\n else if (model[\"artifact:variable_aliases\"] !== undefined) {\n variable_aliases = model[\"artifact:variable_aliases\"];\n // console.log('Set aliases from model');\n resolve();\n }\n // Otherwise leave variable_aliases as empty\n else {\n // console.log('We do not have aliases on project_data or model, so leaving blank.');\n resolve();\n }\n }",
"function atomizeResolver(resolver, name, refObj, wire) {\n\t\twhen(atomize, function(atomize) {\n\t\t\tif(!name) return resolver.resolve(atomize);\n\n\t\t\tatomize.atomically(function() {\n\t\t\t\treturn name == ':root' ? atomize.root : atomize.root[name];\n\t\t\t}, resolver.resolve);\n\t\t});\n\t}",
"async alias(x, y) {\n assert(typeof x === 'string');\n assert(typeof y === 'string');\n assert(isAbsolute(y));\n\n if (!this.field)\n return x;\n\n const z = await findRoot(y);\n\n if (!z)\n return x;\n\n const b = await this.getField(z);\n\n if (!b)\n return x;\n\n if (!isAbsolute(x)) {\n if (b[x])\n return resolve(z, b[x]);\n return x;\n }\n\n const k = unresolve(x, z);\n\n if (b[k])\n return resolve(z, b[k]);\n\n return x;\n }",
"getResolvedValueOnDetachedSymbol() {\n var layer = this._object.layer()\n return layer.valueForOverrideAttribute(\n this.property\n )\n }",
"function ExprFindMappingOneOne(lhs, rhs, lhsFreeVars) {\r\n\tvar flags = [];\r\n\tvar mappings = ExprFindMapping(lhs, rhs, lhsFreeVars);\r\n\tif (mappings.length == 0) {\r\n\t\tflags.push({ flag: LINT_FLAG.INCORRECT, text: \"There is no possible source for \" + Print.letters(lhsFreeVars) + \" that leads to this sentence.\" });\r\n\t\treturn { mappings: [], flags: flags };\r\n\t}\r\n\r\n\t// We need to check if the mappings are\r\n\t// (a) complete: with no variable unaccounted for, and--\r\n\t// (b) unrepeating: with a one-to-one relationship between variables,\r\n\t// (c) free in main premise: meet the requirement that the mapping\r\n\t// source (i.e. (vars in targetExpr) == lhsFreeVars) are free in or absent\r\n\t// from in the cited line. We don't need to check this because, if it\r\n\t// is bound, the earlier variable check will catch it.\r\n\t// (d) free in premises: meet the requirement that the mapping\r\n\t// destination (i.e. vars in sourceExpr) are not free in any\r\n\t// premises.\r\n\t//\r\n\t// To establish completeness for all possible mappings, we need only check\r\n\t// the first mapping: assuming it works correctly, the algorithm will only\r\n\t// leave a mapping incomplete/undefined iff it never exists in the targetExpr\r\n\t// (which is the bit inside the UG). Therefore, any one mapping is incomplete iff\r\n\t// all mappings are incomplete.\r\n\r\n\t// (a)\r\n\tmappings = mappings.filter(m => m.indexOf(\"\") < 0);\r\n\tif (mappings.length == 0) {\r\n\t\tflags.push({ flag: LINT_FLAG.INCORRECT, text: \"There are no possible assignments that account for all of \" + Print.letters(lhsFreeVars) + \".\" });\r\n\t\treturn { mappings: [], flags: flags };\r\n\t}\r\n\r\n\t// (b)\r\n\tmappings = mappings.filter(function(m) {\r\n\t\tvar v = m.slice(0);\r\n\t\tv.sort();\r\n\t\tfor(var j = 1; j < v.length; ++j) {\r\n\t\t\tif (v[j - 1] == v[j]) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t});\r\n\tif (mappings.length == 0) {\r\n\t\tflags.push({ flag: LINT_FLAG.INCORRECT, text: \"There are no possible assignments that account for all of \" + Print.letters(lhsFreeVars) + \" without splitting a sentence letter.\" });\r\n\t\treturn { mappings: [], flags: flags };\r\n\t}\r\n\treturn { mappings: mappings, flags: flags };\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
move floats function starts here | function moveFloats() {
for (let index = 0; index < floatsArray.length; index++) {
const x = floatsArray[index].floatposition % width
if (floatsArray[index].direction === 'left') {
if (x > 0) {
floatsArray[index].floatposition = floatsArray[index].floatposition - 1 //* changes the value for the object's float position property
} else {
floatsArray[index].floatposition = floatsArray[index].floatposition + (width - 1) //* places the float back by using float position + ((with=9) - 1)
}
} else if (floatsArray[index].direction === 'right') {
if (x < width - 1) {
floatsArray[index].floatposition = floatsArray[index].floatposition + 1
} else {
floatsArray[index].floatposition = floatsArray[index].floatposition - (width - 1)
}
}
}
displayFloats() //* display floats function called here. Remove float function is already inside
} | [
"function moveForward(){\n this.xLoc = this.xLoc + this.speed * ((Math.floor(Math.cos(this.direction*Math.PI/180)) + 0.5) * 2);\n this.yLoc = this.yLoc + this.speed * ((Math.floor(Math.sin(this.direction*Math.PI/180)) + 0.5) * 2);\n this.endX = this.xLoc + bugLength * Math.cos(this.direction*Math.PI/180);\n this.endY = this.yLoc + bugLength * Math.sin(this.direction*Math.PI/180);\n}",
"function DragFloat(label, v, v_speed = 1.0, v_min = 0.0, v_max = 0.0, display_format = \"%.3f\", power = 1.0) {\r\n const _v = import_Scalar(v);\r\n const ret = bind.DragFloat(label, _v, v_speed, v_min, v_max, display_format, power);\r\n export_Scalar(_v, v);\r\n return ret;\r\n }",
"mover() {\n\n // Desloca o Pterossauro '1px' pra esquerda\n this.element.style.right = (parseFloat(this.element.style.right) + pixels_to_move) + \"px\";\n\n }",
"copyFromFloats(r, g, b, a) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n return this;\n }",
"function resetFlareonOnFloat() {\n if (cells[flareonPosition].classList.contains('floatAndFlareonLeft')) {\n cells[flareonPosition].classList.remove('floatAndFlareonLeft')\n cells[flareonPosition].classList.add('float-left')\n } else if (cells[flareonPosition].classList.contains('floatAndFlareonRight')) {\n cells[flareonPosition].classList.remove('floatAndFlareonRight')\n cells[flareonPosition].classList.add('float-right')\n }\n }",
"subtractFromFloats(x, y, z, w) {\n return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);\n }",
"function moeda2float(moeda){\r\n\r\nmoeda = moeda.replace(\".\",\"\");\r\n\r\nmoeda = moeda.replace(\",\",\".\");\r\n\r\nreturn parseFloat(moeda);\r\n\r\n}",
"function addOperand() {\n if (firstOperand === null) {\n firstOperand = displayToFloat();\n } else {\n secondOperand = displayToFloat();\n }\n }",
"function float(val, def)\n {\n if (isNaN(val)) return def;\n\n return parseFloat(val);\n }",
"function DragFloat3(label, v, v_speed = 1.0, v_min = 0.0, v_max = 0.0, display_format = \"%.3f\", power = 1.0) {\r\n const _v = import_Vector3(v);\r\n const ret = bind.DragFloat3(label, _v, v_speed, v_min, v_max, display_format, power);\r\n export_Vector3(_v, v);\r\n return ret;\r\n }",
"function moveDecimalNF(val, left, places)\n{\n\tvar newVal = '';\n\t\n\tif (places == null) \n\t\tnewVal = this.moveDecimalAsString(val, left);\n\telse \n\t\tnewVal = this.moveDecimalAsString(val, left, places);\n\t\n\treturn parseFloat(newVal);\n}",
"function DragFloat2(label, v, v_speed = 1.0, v_min = 0.0, v_max = 0.0, display_format = \"%.3f\", power = 1.0) {\r\n const _v = import_Vector2(v);\r\n const ret = bind.DragFloat2(label, _v, v_speed, v_min, v_max, display_format, power);\r\n export_Vector2(_v, v);\r\n return ret;\r\n }",
"function beforeMove(){\n sumInFront = 0;\n numInFront = 0;\n }",
"function floatRotate(bullet){\n \t//bullet.x = globalVar.playerX;\n \t//bullet.y = globalVar.playerY;\n \tglobalVar.test =bullet.rotation;\n \t//bullet.rotation += .1;\n \tbullet.rotation = bullet.rotation+(20* (Math.PI/180));\n \t\n }",
"multiplyByFloats(x, y) {\n return new Vector2(this.x * x, this.y * y);\n }",
"multiplyByFloats(x, y, z) {\n return new Vector3(this.x * x, this.y * y, this.z * z);\n }",
"move() {\n this.change = this.mouthGap == 0 ? -this.change : this.change;\n this.mouthGap = (this.mouthGap + this.change) % (Math.PI / 4) + Math.PI / 64;\n this.x += this.horizontalVelocity;\n this.y += this.verticalVelocity;\n }",
"moveAround() {\r\n\r\n\r\n }",
"function safeParseFloat(value) {\n if (!value) {\n return 0.00;\n }\n if (ok(value, tyString)) {\n return parseFloat(value);\n }\n if (ok(value, tyNumber)) {\n return value;\n }\n return 0.00;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigation shortcuts, such as Drawer, Folder, TabBar, must have child shortcuts. Use it as a fallback for navigation screen if shortcuts (children) are missing. | function ShortcutChildrenRequired(props) {
const { WrappedComponent, shortcut, isRootScreen } = props;
// Folder screen may not be root screen and if it has no children
// we present error as there is no content.
const fallbackScreen = isRootScreen ? <NoScreens /> : <NoContent title={shortcut.title} />;
return _.isEmpty(shortcut.children) ?
fallbackScreen :
<WrappedComponent {...props } />;
} | [
"function listStaticShortcuts() {\n\n\tif (!appShortcuts) {\n\t\treturn alert('This device does not support Force Touch');\n\t}\n\n\tlog.args('Ti.UI.iOS.ApplicationShortcuts.listStaticShortcuts', appShortcuts.listStaticShortcuts());\n}",
"_keyboardShortcuts() {\n browser.commands.onCommand.addListener((command) => {\n if (command === 'action-accept-new') {\n this.app.modules.calls.callAction('accept-new')\n } else if (command === 'action-decline-hangup') {\n this.app.modules.calls.callAction('decline-hangup')\n } else if (command === 'action-dnd') {\n // Only toggle when calling options are enabled and webrtc is enabled.\n if (!this.app.helpers.callingDisabled() && this.app.state.settings.webrtc.enabled) {\n this.app.setState({availability: {dnd: !this.app.state.availability.dnd}})\n }\n } else if (command === 'action-hold-active') {\n this.app.modules.calls.callAction('hold-active')\n }\n })\n }",
"function App() {\n return (\n <div className=\"App\">\n <Route \n path='/'\n render={props => <NavWrapper {...props} />}\n />\n <Route \n path='/mac' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/ipad' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/iphone' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/watch' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/tv' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/music' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/support' \n render={props => <SubNav {...props} />} \n />\n </div>\n );\n}",
"function bindShortcutsBtnClick() {\n $('#keyboard_shortcuts_link').click(function(){\n $(this).toggleClass('active');\n if($('#keyboard_shortcuts_cont').is(':visible')){\n $('#keyboard_shortcuts_cont').hide('fade', 0);\n } else {\n $('#keyboard_shortcuts_cont').show('fade', 0);\n }\n $('#settings_link.active').trigger('click');\n });\n\n $('#keyboard_shortcuts_cont').click(function(event){\n if ( $(event.target).parents('#close_keyboard_shortcuts_cont').length > 0 ) {\n $('#keyboard_shortcuts_link').trigger('click');\n } else {\n if ( !$(event.target).is('#keyboard_shortcuts') ) {\n if ( $(event.target).parents('#keyboard_shortcuts').length <= 0 ) {\n $('#keyboard_shortcuts_link').trigger('click');\n }\n }\n }\n });\n}",
"function listDynamicShortcuts() {\n\n\tif (!appShortcuts) {\n\t\treturn alert('This device does not support Force Touch');\n\t}\n\n\tvar res = appShortcuts.listDynamicShortcuts();\n\n\tlog.args('Ti.UI.iOS.ApplicationShortcuts.listDynamicShortcuts', res);\n\n\t// If don't have any, explain how to create it\n\tif (res.length === 0) {\n\t\tTi.UI.createAlertDialog({\n\t\t\ttitle: 'None',\n\t\t\tmessage: 'Open a picture to create a dynamic shortcut.'\n\t\t}).show();\n\t}\n}",
"get NavigationStatic() {}",
"function bindKeyboardShortcutsForTabs() {\n $( document ).keydown(function (event) {\n if($(document.activeElement).is('textarea,input,select')) { return; }\n switch (event.which) {\n case $.ui.keyCode.DOWN:\n event.preventDefault();\n nextTab();\n break;\n case $.ui.keyCode.UP:\n event.preventDefault();\n previousTab();\n break;\n default: return;\n }\n });\n}",
"function dynamicShortcutExists() {\n\n\tif (!appShortcuts) {\n\t\treturn alert('This device does not support Force Touch');\n\t}\n\n\tvar res = appShortcuts.dynamicShortcutExists('details');\n\n\tlog.args('Ti.UI.iOS.ApplicationShortcuts.dynamicShortcutExists', 'details', res);\n\n\t// If don't have it, explain how to create it\n\tif (!res) {\n\t\tTi.UI.createAlertDialog({\n\t\t\ttitle: 'Does not exist',\n\t\t\tmessage: 'Open a picture to create a dynamic shortcut.'\n\t\t}).show();\n\t}\n}",
"setNavigation() {\n errors.throwNotImplemented(\"setting navigation (dequeue options)\");\n }",
"addShortcut(keys, callback) {\n Mousetrap.bind(keys, callback)\n }",
"function isNavigationKeyCode(keyCode){\n switch(keyCode){\n case 8: //backspace\n case 35: //end\n case 36: //home\n case 37: //left\n case 38: //up\n case 39: //right\n case 40: //down\n case 45: //insert\n case 46: //delete\n return true;\n default:\n return false;\n }\n }",
"get quicklaunch() {\n return NavigationNodes(this, \"quicklaunch\");\n }",
"getNavigation() {\n errors.throwNotImplemented(\"getting navigation (dequeue options)\");\n }",
"componentDidMount() {\n this.props.navigation.setOptions({\n title: (this.props.route?.params?.path.split('/').slice(-1)[0] || 'Root Directory'),\n headerRight: ({ tintColor }) => (\n <IconButton icon='content-save' color={tintColor} onPress={this.saveDirectoryPath} />\n )\n });\n \n this.fetchDirectoryEntries();\n }",
"function registerNavigationKeys(keynapse){\n\tkeynapse.listener.simple_combo(\"tab\", nextKnCell);\n\tkeynapse.listener.simple_combo(\"enter\", selectKnCell);\n}",
"function vimNavigation({ keyCode: key }) {\n // 74 => J || 75 => K\n if (key === 74 || key === 75) {\n switch (key) {\n case 74: // J => Move the focus down the navigation bar\n if (navCounter < links.length - 1) navCounter++;\n links[navCounter].focus();\n break;\n case 75: // K => Move the focus up the navigation bar\n if (navCounter > 0) navCounter--;\n links[navCounter].focus();\n break;\n }\n }\n}",
"function setAppMenu() {\n let menuTemplate = [\n {\n label: appName,\n role: 'window',\n submenu: [\n {\n label: 'Quit',\n accelerator: 'CmdorCtrl+Q',\n role: 'close'\n }\n ]\n },\n {\n label: 'Edit',\n submenu: [\n {\n label: 'Cut',\n role: 'cut'\n },\n {\n label: 'Copy',\n role: 'copy'\n },\n {\n label: 'Paste',\n role: 'paste'\n },\n {\n label: 'Select All',\n role: 'selectall'\n }\n ]\n },\n {\n label: 'Help',\n role: 'help',\n submenu: [\n {\n label: 'Docs',\n accelerator: 'CmdOrCtrl+H',\n click() {\n shell.openExternal('https://docs.moodle.org/en/Moodle_Mobile');\n }\n }\n ]\n }\n ];\n\n Menu.setApplicationMenu(Menu.buildFromTemplate(menuTemplate));\n}",
"updateShortcut_() {\n this.removeAttribute('shortcutText');\n\n if (!this.command_ || !this.command_.shortcut ||\n this.command_.hideShortcutText) {\n return;\n }\n\n const shortcuts = this.command_.shortcut.split(/\\s+/);\n\n if (shortcuts.length === 0) {\n return;\n }\n\n const shortcut = shortcuts[0];\n const mods = {};\n let ident = '';\n shortcut.split('|').forEach(function(part) {\n const partUc = part.toUpperCase();\n switch (partUc) {\n case 'CTRL':\n case 'ALT':\n case 'SHIFT':\n case 'META':\n mods[partUc] = true;\n break;\n default:\n console.assert(!ident, 'Shortcut has two non-modifier keys');\n ident = part;\n }\n });\n\n let shortcutText = '';\n\n ['CTRL', 'ALT', 'SHIFT', 'META'].forEach(function(mod) {\n if (mods[mod]) {\n shortcutText += loadTimeData.getString('SHORTCUT_' + mod) + '+';\n }\n });\n\n if (ident === ' ') {\n ident = 'Space';\n }\n\n if (ident.length !== 1) {\n shortcutText += loadTimeData.getString('SHORTCUT_' + ident.toUpperCase());\n } else {\n shortcutText += ident.toUpperCase();\n }\n\n this.setAttribute('shortcutText', shortcutText);\n }",
"function AppNavigator() {\n\treturn (\n\t\t// Wrap NavigationContainer because its the route of the app\n\t\t<NavigationContainer>\n\t\t\t{/* Set up Tab.Navigator */}\n\t\t\t<Tab.Navigator\n\t\t\t\t// in screenOptions we give an object with function\n\t\t\t\t// this function has access to props from react-naviation {route}\n\t\t\t\tscreenOptions={({ route }) => ({\n\t\t\t\t\t// logic to check if route is home then show Home icon from MaterialIcon etc ..\n\t\t\t\t\ttabBarIcon: () => {\n\t\t\t\t\t\tlet iconName;\n\t\t\t\t\t\tif (route.name == 'Home') {\n\t\t\t\t\t\t\ticonName = 'home';\n\t\t\t\t\t\t} else if (route.name == 'About') {\n\t\t\t\t\t\t\ticonName = 'info';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// return MaterialIcon\n\t\t\t\t\t\treturn <MaterialIcons name={iconName} size={24} />;\n\t\t\t\t\t},\n\t\t\t\t})}\n\t\t\t>\n\t\t\t\t{/* Setting up screens in Tab.Navigator*/}\n\t\t\t\t<Tab.Screen name=\"Home\" component={stackNavigator} />\n\t\t\t\t<Tab.Screen name=\"About\" component={AboutStackNavigator} />\n\t\t\t</Tab.Navigator>\n\t\t</NavigationContainer>\n\t);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When the training ended for this model | onTrainingEnded(event) {
if (event.context.modelName == this.props.modelName) {
this.setState({
training: false
})
this.loadRetrainedModel()
}
} | [
"onTrainingStarted(event) {\n\n if (event.context.modelName == this.props.modelName) {\n this.setState({\n training: true\n })\n }\n }",
"function workoutFinished(){\n\n }",
"gameEnd() {\n\t\tthis.gameDataList.push(this.curGameData);\n\t\tthis.curGameData = null;\n this.fitness = null;\n\t}",
"modelChanged() {\n }",
"finish() {\n if (!this.disabled) {\n this._sendBatch();\n this.clearEvents();\n }\n }",
"modelDidReconstruct() {}",
"function calculatePredictedFinish() {}",
"onPromotionEnded(event) {\n if (event.context.modelName == this.props.modelName) this.loadRetrainedModel();\n }",
"onAnimationEnd() {\n return null;\n }",
"function finish() {\n off();\n if (events[\"refresh-finished\"]) return;\n events[\"refresh-finished\"] = true;\n // setTimeout guarantees calling order\n setTimeout(function() {\n store.trigger(\"refresh-finished\");\n }, 100);\n }",
"function operationComplete() {\n if ((successfulOperations.length + failedOperations.length) >= totalOperations) {\n saveComplete();\n }\n }",
"endGame()\r\n {\r\n this.gameInProgress = false;\r\n game.arrowPosition = [];\r\n\r\n this.interface.gameOptions.open();\r\n this.interface.gameMovie = this.interface.gui.add(this, 'ViewGameFilm');\r\n }",
"recordingStopped() {\n if (this.stopAfterRecording) {\n this.stopBuffering();\n }\n }",
"setFinished() {\n this.condition = 'finished';\n }",
"function completedProcess(self) {\n\t//console.log('completedProcess called');\n\tself.emit('completedProcess', self.file, self.fileObjectList.getAll());\n\tconsole.log(\"FeedFileProcessor : Finished processing \", self.file);\n\t//console.log(\"Contents are \", self.fileObjectList.getAll());\n\n}",
"train() {\n this.settings.classifier.clear();\n this.docs.forEach((doc) => {\n this.settings.classifier.addObservation(this.textToFeatures(doc.utterance), doc.intent);\n });\n if (this.settings.classifier.observationCount > 0) {\n this.settings.classifier.train();\n }\n }",
"function trainFace(username_email, cb) {\n var trained = false;\n console.log('training started>>>>>');\n // lighting\n var a = 180;\n var a2 = 0;\n var l = setInterval(function() {\n matrix.led([{\n arc: Math.round(180 * Math.sin(a)),\n color: 'blue',\n start: a2\n }, {\n arc: -Math.round(180 * Math.sin(a)),\n color: 'blue',\n start: a2 + 180\n }]).render();\n a = (a < 0) ? 180 : a - 0.1;\n }, 25);\n function stopLights() {\n clearInterval(l);\n }\n\n console.log(username_email);\n // starts training \n matrix.service('recognition').train(''+username_email).then(function(data) {\n stopLights();\n //continue if training is not finished\n if (!trained && data.hasOwnProperty('count')) {\n // means it's partially done\n matrix.led({\n arc: Math.round(360 * (data.count / data.target)),\n color: 'blue',\n start: 0\n }).render();\n }\n //training is finished\n else {\n trained = true;\n matrix.led('green').render();\n console.log('trained!', data);\n matrix.service('recognition').stop();\n setTimeout(function() {\n matrix.led('black').render();\n }, 2000);\n cb();\n //io.emit('TrainSuccess', true); //SEND DATA TO CLIENT\n return true;\n }\n });\n}",
"onDestroy() {\n STATE.cows--;\n }",
"dispatchErrorBackward(){\n\n this.clearAllErrorsInputLayer();\n\n for(var i = 0; i < this.neurons.length; i++){\n this.neurons[i].dispatchErrorBackward();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable the report date period | function disableReportDatePeriod(){
toggleErrorMessage("#account_created_period_error_text", true, "");
disableField("#selectRange1Value");
//Clear create account period
resetSelect("#selectRange1Value");
//Reset datePicker
enableField("#date-picker-start");
enableField("#date-picker-end");
} | [
"function disableReportDateRangeFields(){\n\ttoggleErrorMessage(\"#account_created_range_error_text\", true, \"\");\n\t\n\tenableField(\"#selectRange1Value\");\n\t\n\t//Reset datepicker\n\tresetDatePicker(\"#date-picker-start\");\n\tresetDatePicker(\"#date-picker-end\");\n\t\n\t//Disable datepicker\n\tdisableField(\"#date-picker-start\");\n\tdisableField(\"#date-picker-end\");\n}",
"function CP_clearDisabledDates() {\r\n this.disabledDatesExpression = \"\";\r\n this.yearmax = \"\";\r\n this.yearmin = \"\";\r\n this.yearSelectStart = \"\";\r\n this.yearSelectStartOffset = CP_YearOfset();\r\n}",
"function CP_addDisabledDates(start, end) {\r\n if (arguments.length == 1) { end = start; }\r\n if (!start && !end) { return; }\r\n if (this.disabledDatesExpression) { this.disabledDatesExpression += \"||\"; }\r\n if (start) {\r\n start = parseDate(start);\r\n if (start) start = (\"\" + start.getFullYear() + LZ(start.getMonth() + 1) + LZ(start.getDate()));\r\n }\r\n if (end) {\r\n end = parseDate(end);\r\n if (end) end = (\"\" + end.getFullYear() + LZ(end.getMonth() + 1) + LZ(end.getDate()));\r\n }\r\n if (!start) { this.disabledDatesExpression += \"(ds<=\" + end + \")\"; }\r\n else if (!end) { this.disabledDatesExpression += \"(ds>=\" + start + \")\"; }\r\n else if (start && end){ this.disabledDatesExpression += \"(ds>=\" + start + \"&&ds<=\" + end + \")\"; }\r\n}",
"stopAutoReport(){\n if (this.options.interval){\n clearInterval(this.options.interval) \n delete this.options.interval\n }\n }",
"function disableFunctionOnStartTimeSheet()\r\n {\r\n\t \r\n\t document.getElementById(\"timeSheetMainFunction\").style.display=\"none\"; \r\n\t document.getElementById(\"showStatusOfTimeSheet\").style.display=\"\"; \r\n\t \r\n\t \r\n }",
"function setDefault() {\n if (ctrl.rrule.bymonthday || ctrl.rrule.byweekday) return\n ctrl.rrule.bymonthday = ctrl.startTime.getDate()\n }",
"function disableAttendeeHourSubmit(disable) {\n $('#attendeeHourSubmit').attr('disabled', disable);\n}",
"function monthlyReport() {\n\n}",
"function disableOtherEventsFromThisSubmission( ){\n const eventsFromThisSubmission = allEvents.filter( event => event.submissionId === selectedEvent.submissionId && event.id != selectedEvent.id ) ;\n eventsFromThisSubmission.forEach( event => updateField( event.rowNum, header.status, \"disabled\") );\n }",
"onDisabled() {\n this.updateInvalid();\n }",
"function common_dateWarning(period, timeLimit, ngaybd, ngaykt)\n{\n\n limitJson = JSON.parse(timeLimit);\n\tvar message = '';\n\n\tif(period != '')\n\t{\n var limit;\n\t\tvar retval;\n\t\tvar suffix;\n\t\tvar prefix = Language.translate('CONFIRM_DATE_OVER');\n\t\tvar startArr = ngaybd.split(\"-\");\n\t\tvar endArr = ngaykt.split(\"-\");\n\t\tvar start = new Date( parseInt(startArr[2]), parseInt(startArr[1]) - 1, parseInt(startArr[0]));\n\t\tvar secondDate = new Date();\n\t\tvar secondDateLimit = new Date();\n\t\t\n\t\tswitch(period)\n\t\t{\n\t\t\tcase 'D':\n limit = (limitJson['D'] != undefined && !isNaN(limitJson['D']))?limitJson['D']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setDate(start.getDate() + limit - 1); \n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_DAYS');\n\t\t\tbreak;\n\t\t\tcase 'W':\n limit = (limitJson['W'] != undefined && !isNaN(limitJson['W']))?limitJson['W']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setDate(start.getDate() + (limit *7 ) -1);\n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_WEEKS');\n\t\t\tbreak;\n\t\t\tcase 'M':\n limit = (limitJson['M'] != undefined && !isNaN(limitJson['M']))?limitJson['M']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setMonth(start.getMonth() + limit);\n\t\t\t\tstart.setDate(start.getDate() - 1);\n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_MONTHS');\n\t\t\tbreak;\n\t\t\tcase 'Q':\n limit = (limitJson['Q'] != undefined && !isNaN(limitJson['Q']))?limitJson['Q']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setMonth(start.getMonth() + limit);\n\t\t\t\tstart.setDate(start.getDate() - 1);\n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_QUARTERS');;\n\t\t\tbreak;\n\t\t\tcase 'Y':\n limit = (limitJson['Y'] != undefined && !isNaN(limitJson['Y']))?limitJson['Y']:0;\n limit = parseInt(limit);\n\t\t\t\tstart.setYear(start.getFullYear() + limit); \n\t\t\t\tstart.setDate(start.getDate() - 1); \n\t\t\t\tsuffix = Language.translate('CONFIRM_DATE_OVER_YEARS');\n\t\t\tbreak;\t\t\t\t\t\t\t\t\n\t\t}\n\t\tsecondDate.setFullYear(parseInt(endArr[2]), parseInt(endArr[1]) - 1, parseInt(endArr[0]));\n\t\tsecondDateLimit.setFullYear(start.getFullYear(), start.getMonth(), start.getDate());\n\n\t\tif( (secondDateLimit < secondDate ) && (limit > 0) )\n\t\t{\n\t\t\tmessage = prefix + ' ' + limit + ' ' + suffix;\n\t\t}\n\t}\n\treturn message;\n}",
"function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}",
"function resetReportModal(){\n\t\n\ttoggleErrorMessage(\"#report_filter_criteria\", true, \"\");\n\t\n\t$('#account_created_period_error_text').attr('style', \"display: none;\");\n\t$('#account_created_range_error_text').attr('style', \"display: none;\");\n\t$('#report_format_error_text').attr('style', \"display: none;\");\n\t\n\t//Unchecking the account created radio button period\n\ttoggleIcheckBox('#accountCreatedPeriodRadio', false);\n\t\n\t//Setting the default select\n\tresetSelect(\"#selectRange1Value\");\n\tdisableField(\"#selectRange1Value\");\n\t\n\t//Unchecking the account created radio button range\n\ttoggleIcheckBox('#accountCreatedRangeRadio', false);\n\t\n\t//Reset Datepicker\n\tresetDatePicker(\"#date-picker-start\");\n\tresetDatePicker(\"#date-picker-end\");\n\tdisableField(\"#date-picker-start\");\n\tdisableField(\"#date-picker-end\");\n\t\n\t//Unchecking the no account information and no category description\n\ttoggleIcheckBox('#noAccountInformation', false);\n\ttoggleIcheckBox('#noCatagoryDescription', false);\n\n\t//Setting the default select\n\tresetSelect(\"#managerReportFormatSelect\");\n}",
"function enableBrushTime() {\n var range = x2.domain()[1] - x2.domain()[0];\n if (range > 3600000) {\n //enable 1h button\n $('[name=oneHour]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24) {\n //enable 1d button\n $('[name=oneDay]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24 * 7) {\n //enable 1w button\n $('[name=oneWeek]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24 * 30) {\n //enable 1month button\n $('[name=oneMonth]', topToolbar).prop('disabled', false);\n }\n if (range > 3600000 * 24 * 365) {\n //enable 1y button\n $('[name=oneYear]', topToolbar).prop('disabled', false);\n }\n }",
"function bkDisableBookedTimeSlots(all_dates, bk_type){\n\n var inst = jQuery.datepick._getInst(document.getElementById('calendar_booking'+bk_type));\n var td_class;\n\n var time_slot_field_name = 'select[name=\"rangetime' + bk_type + '\"]';\n var time_slot_field_name2 = 'select[name=\"rangetime' + bk_type + '[]\"]';\n \n var start_time_slot_field_name = 'select[name=\"starttime' + bk_type + '\"]';\n var start_time_slot_field_name2 = 'select[name=\"starttime' + bk_type + '[]\"]';\n \n // HERE WE WILL DISABLE ALL OPTIONS IN RANGE TIME INTERVALS FOR SINGLE DAYS SELECTIONS FOR THAT DAYS WHERE HOURS ALREADY BOOKED\n //here is not range selections\n all_dates = get_first_day_of_selection(all_dates);\n if ( (bk_days_selection_mode == 'single') || (true) ) { // Only single day selections here\n\n var current_single_day_selections = all_dates.split('.');\n td_class = (current_single_day_selections[1]*1) + '-' + (current_single_day_selections[0]*1) + '-' + (current_single_day_selections[2]*1);\n var times_array = [];\n\n jQuery( time_slot_field_name + ' option:disabled,' + time_slot_field_name2 + ' option:disabled,' + start_time_slot_field_name + ' option:disabled,' + start_time_slot_field_name2 + ' option:disabled').removeClass('booked'); // Remove class \"booked\"\n jQuery( time_slot_field_name + ' option:disabled,' + time_slot_field_name2 + ' option:disabled,' + start_time_slot_field_name + ' option:disabled,' + start_time_slot_field_name2 + ' option:disabled').removeAttr('disabled'); // Make active all times\n \n\n if ( jQuery( time_slot_field_name+','+time_slot_field_name2 + ',' + start_time_slot_field_name+','+start_time_slot_field_name2 ).length == 0 ) return; // WE DO NOT HAVE RANGE SELECTIONS AT THIS FORM SO JUST RETURN\n\n var range_time_object = jQuery( time_slot_field_name + ' option:first,'+time_slot_field_name2 + ' option:first,' + start_time_slot_field_name + ' option:first,'+start_time_slot_field_name2 + ' option:first' ) ;\n if (range_time_object == undefined) return; // WE DO NOT HAVE RANGE SELECTIONS AT THIS FORM SO JUST RETURN\n\n // Get dates and time from aproved dates\n if(typeof(date_approved[ bk_type ]) !== 'undefined')\n if(typeof(date_approved[ bk_type ][ td_class ]) !== 'undefined') {\n if( ( date_approved[ bk_type ][ td_class ][0][3] != 0) || ( date_approved[ bk_type ][ td_class ][0][4] != 0) ) {\n for ( i=0; i< date_approved[ bk_type ][ td_class ].length; i++){\n h = date_approved[ bk_type ][ td_class ][i][3];if (h < 10) h = '0' + h;if (h == 0) h = '00';\n m = date_approved[ bk_type ][ td_class ][i][4];if (m < 10) m = '0' + m;if (m == 0) m = '00';\n s = date_approved[ bk_type ][ td_class ][i][5];if (s == 2) s = '02';\n times_array[ times_array.length ] = [h,m,s];\n }\n }\n }\n\n // Get dates and time from pending dates\n if(typeof( date2approve[ bk_type ]) !== 'undefined')\n if(typeof( date2approve[ bk_type ][ td_class ]) !== 'undefined')\n if( ( date2approve[ bk_type ][ td_class ][0][3] != 0) || ( date2approve[ bk_type ][ td_class ][0][4] != 0) ) //check for time here\n {for ( i=0; i< date2approve[ bk_type ][ td_class ].length; i++){\n h = date2approve[ bk_type ][ td_class ][i][3];if (h < 10) h = '0' + h;if (h == 0) h = '00';\n m = date2approve[ bk_type ][ td_class ][i][4];if (m < 10) m = '0' + m;if (m == 0) m = '00';\n s = date2approve[ bk_type ][ td_class ][i][5];if (s == 2) s = '02';\n times_array[ times_array.length ] = [h,m,s];\n }\n }\n \n // Check about situations, when we have end time without start time (... - 09:00) or start time without end time (21:00 - ...)\n times_array.sort();\n if (times_array.length > 0 ) {\n s = parseInt( times_array[0][2] );\n if ( s == 2 ) {\n times_array[ times_array.length ] = ['00','00','01'];\n times_array.sort();\n }\n s = parseInt( times_array[ ( times_array.length - 1 ) ][2] );\n if ( s == 1 ) {\n times_array[ times_array.length ] = ['23','59','02'];\n times_array.sort();\n }\n }\n\n var removed_time_slots = is_time_slot_booked_for_this_time_array( bk_type, times_array );\n var my_time_value = jQuery( time_slot_field_name + ' option,'+time_slot_field_name2 + ' option,' + start_time_slot_field_name + ' option,'+start_time_slot_field_name2 + ' option');\n\n for ( j=0; j< my_time_value.length; j++){\n if ( wpdev_in_array( removed_time_slots, j ) ) {\n jQuery( time_slot_field_name + ' option:eq('+j+'),'+time_slot_field_name2 + ' option:eq('+j+'),' + start_time_slot_field_name + ' option:eq('+j+'),'+start_time_slot_field_name2 + ' option:eq('+j+')').attr('disabled', 'disabled'); // Make disable some options\n jQuery( time_slot_field_name + ' option:eq('+j+'),'+time_slot_field_name2 + ' option:eq('+j+'),' + start_time_slot_field_name + ' option:eq('+j+'),'+start_time_slot_field_name2 + ' option:eq('+j+')').addClass('booked'); // Add \"booked\" CSS class \n if( jQuery( time_slot_field_name + ' option:eq('+j+'),'+time_slot_field_name2 + ' option:eq('+j+'),' + start_time_slot_field_name + ' option:eq('+j+'),'+start_time_slot_field_name2 + ' option:eq('+j+')' ).attr('selected') ){ // iF THIS ELEMENT IS SELECTED SO REMOVE IT FROM THIS TIME\n jQuery( time_slot_field_name + ' option:eq('+j+'),'+time_slot_field_name2 + ' option:eq('+j+'),' + start_time_slot_field_name + ' option:eq('+j+'),'+start_time_slot_field_name2 + ' option:eq('+j+')' ).removeAttr('selected');\n\n if (IEversion_4_bk == 7) { // Emulate disabling option in selectboxes for IE7 - its set selected option, which is not disabled\n \n var rangetime_element = document.getElementsByName(\"rangetime\" + bk_type );\n if (typeof(rangetime_element) != 'undefined' && rangetime_element != null) {\n set_selected_first_not_disabled_option_IE7(document.getElementsByName(\"rangetime\" + bk_type )[0] );\n }\n \n var start_element = document.getElementsByName(\"starttime\" + bk_type );\n if (typeof(start_element) != 'undefined' && start_element != null) {\n set_selected_first_not_disabled_option_IE7(document.getElementsByName(\"starttime\" + bk_type )[0] );\n }\n \n }\n }\n }\n }\n\n if (IEversion_4_bk == 7) { // Emulate disabling option in selectboxes for IE7 - its set grayed text options, which is disabled\n emulate_disabled_options_to_gray_IE7( \"rangetime\" + bk_type );\n emulate_disabled_options_to_gray_IE7( \"starttime\" + bk_type );\n }\n }\n\n}",
"function eventLogRecordingsFileSelectionCancelled() {\n dumpCreator.disableEventLogRecordings();\n}",
"function disableDownloadButtons() {\n\t$('.dwnld').prop('disabled', true);\n}",
"function clearDates(){\n beginDate = \"\";\n endDate = \"\";\n days = [];\n\n}",
"function activateDateField(){\n $('[type=\"checkbox\"]').click(function(){\n if (this.checked===true){\n $(this).nextAll('[type=\"date\"]').slice(0,2).prop( \"disabled\",false);\n }\n else\n $(this).nextAll('[type=\"date\"]').slice(0,2).prop(\"disabled\",true);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a vertical Basic Buffer Geometry (BGB) in a form of a rectangle. The BGB is a made up of two lines (one on the left and the other on the right) of the input line. | function getverticalBGB(startCoordinate, endCoordinate){
let startE = start[0];
let startN = start[1];
let endE = end[0];
let endN = end[1];
let rightLine = [ [startE + BD, startN], [ endE + BD, endN] ];
let leftLine = [ [startE - BD, startN], [ endE - BD, endN] ];
return [topLine, bottomLine];
} | [
"function getHorizontalBGB(LNode, RNode){\n let LX = LNode[0]; //LX is for easting value or x value of the left node\n let LY= LNode[1]; //LY us for northing value or y value of the left node\n let RX = RNode[0]; //RX is for easting value or x value of the right node\n let RY = RNode[1]; //RN us for northing value or y value of the right node\n\n //console.log(\"lx: \" + LX + \" | rx: \" + RX);\n let topLine = [ [LX, LY + BD], [ RX, RY + BD] ];\n let bottomLine = [ [LX, LY - BD], [ RX, RY - BD] ];\n\n return [topLine, bottomLine];\n}",
"function CreateBuffer() {\n var line_vertices = [ // A VBO for horizontal line in a standard position. To be translated to position of mouse click \n -0.1, 0.0, 0.0,\n 0.1, 0.0, 0.0\n ];\n LineVertexPositionBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, LineVertexPositionBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(line_vertices), gl.STATIC_DRAW);\n LineVertexPositionBuffer.itemSize = 3; // NDC'S [x,y,0] \n LineVertexPositionBuffer.numItems = 2;// this buffer only contains A line, so only two vertices \n}",
"function getBoundingBox() {\n var rect = self.getViewRect();\n \n return new T5.Geo.BoundingBox(\n T5.GeoXY.toPos(T5.XY.init(rect.x1, rect.y2), radsPerPixel),\n T5.GeoXY.toPos(T5.XY.init(rect.x2, rect.y1), radsPerPixel));\n }",
"setBoundingBox() {\n /**\n * Array of `Line` objects defining the boundary of the Drawing<br>\n * - using these in `View.addLine` to determine the end points of {@link Line} in the {@link model}\n * - these lines are not added to the `Model.elements` array\n */\n this.boundaryLines = []\n\n // TODO; set these values in main\n\n // top left\n let tlPt = new Point(\"-4\", \"-4\")\n // bottom right\n let brPt = new Point(\"4\", \"4\")\n\n // top right\n let trPt = new Point(brPt.x, tlPt.y)\n // bottom left\n let blPt = new Point(tlPt.x, brPt.y)\n\n let lineN = new Line(tlPt, trPt)\n this.boundaryLines.push(lineN)\n\n let lineS = new Line(blPt, brPt)\n this.boundaryLines.push(lineS)\n\n let lineW = new Line(tlPt, blPt)\n this.boundaryLines.push(lineW)\n\n let lineE = new Line(trPt, brPt)\n this.boundaryLines.push(lineE)\n }",
"generateBoundingBox() {\n this.n = parseFloat(waypoints[0].lat);\n this.s = parseFloat(waypoints[0].lat);\n this.e = parseFloat(waypoints[0].lon);\n this.w = parseFloat(waypoints[0].lon);\n for (let i = 1; i < waypoints.length; i++) {\n\n if (waypoints[i].lat > this.n) {\n this.n = parseFloat(waypoints[i].lat);\n }\n\t else if (waypoints[i].lat < this.s) {\n this.s = parseFloat(waypoints[i].lat);\n }\n if (waypoints[i].lon > this.e) {\n this.e = parseFloat(waypoints[i].lon);\n }\n\t else if (waypoints[i].lon < this.w) {\n this.w = parseFloat(waypoints[i].lon);\n }\n }\n\n // creating the polylines for the bounding box\n \n // if square bounding box is not selected, then the quadtree\n // will be split as a rectangle\n let nEnds = [[this.n,this.w],[this.n,this.e]];\n let sEnds = [[this.s,this.w],[this.s,this.e]];\n let eEnds = [[this.n,this.e],[this.s,this.e]];\n let wEnds = [[this.n,this.w],[this.s,this.w]];\n \n if (document.getElementById(\"squareBB\").checked) {\n const EW = distanceInMiles(nEnds[0][0],nEnds[0][1],nEnds[1][0],nEnds[1][1]);\n const NS = distanceInMiles(eEnds[0][0],eEnds[0][1],eEnds[1][0],eEnds[1][1]);\n let difference;\n //check if the difference between the east west is longer than the north south\n if (EW > NS) {\n difference = (EW - NS) / 69;\n this.n += difference / 2;\n this.s -= difference / 2;\n\n }\n\t else {\n difference = (NS - EW) / (Math.cos(Math.abs(this.n - this.s) / 2) * 69);\n this.e += difference / 2;\n this.w -= difference / 2;\n }\n\n nEnds = [[this.n,this.w],[this.n,this.e]];\n sEnds = [[this.s,this.w],[this.s,this.e]];\n eEnds = [[this.n,this.e],[this.s,this.e]];\n wEnds = [[this.n,this.w],[this.s,this.w]];\n }\n this.boundingPoly.push(\n L.polyline(nEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n })\n );\n this.boundingPoly.push(\n L.polyline(sEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n })\n );\n this.boundingPoly.push(\n L.polyline(eEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n })\n );\n this.boundingPoly.push(\n L.polyline(wEnds, {\n color: visualSettings.undiscovered.color,\n opacity: 0.7,\n weight: 3\n }) \n );\n\t\n for (let i = 0; i < 4; i++) {\n this.boundingPoly[i].addTo(map);\n }\n }",
"function getLabelBBox(textWidth, textHeight, align, baseline, angle, margin){\n \n var polygon = getLabelPolygon(textWidth, textHeight, align, baseline, angle, margin);\n var corners = polygon.corners();\n var bbox;\n if(angle === 0){\n var min = corners[2]; // topLeft\n var max = corners[1]; // bottomRight\n \n bbox = new pvc.Rect(min.x, min.y, max.x - min.x, max.y - min.y);\n } else {\n bbox = polygon.bbox();\n }\n \n bbox.sourceCorners = corners;\n bbox.sourceAngle = angle;\n bbox.sourceAlign = align;\n bbox.sourceTextWidth = textWidth;\n \n return bbox;\n }",
"function BoundingBoxRenderer(scene){/**\n * The component name helpfull to identify the component in the list of scene components.\n */this.name=BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;/**\n * Color of the bounding box lines placed in front of an object\n */this.frontColor=new BABYLON.Color3(1,1,1);/**\n * Color of the bounding box lines placed behind an object\n */this.backColor=new BABYLON.Color3(0.1,0.1,0.1);/**\n * Defines if the renderer should show the back lines or not\n */this.showBackLines=true;/**\n * @hidden\n */this.renderList=new BABYLON.SmartArray(32);this._vertexBuffers={};this.scene=scene;scene._addComponent(this);}",
"updateBB() {\n this.lastWorldBB = this.worldBB;\n this.worldBB = new BoundingBox(\n this.pos.x, this.pos.y, this.dim.x, this.dim.y);\n }",
"static getBounds(rectangle, matrix, out = null) {\n if (!out) out = new Rectangle()\n\n let minX = Number.MAX_VALUE,\n maxX = -Number.MAX_VALUE\n let minY = Number.MAX_VALUE,\n maxY = -Number.MAX_VALUE\n const positions = RectangleUtil.getPositions(\n rectangle,\n RectangleUtil.sPositions\n )\n\n for (let i = 0; i < 4; ++i) {\n MatrixUtil.transformCoords(\n matrix,\n positions[i].x,\n positions[i].y,\n RectangleUtil.sPoint\n )\n\n if (minX > RectangleUtil.sPoint.x) minX = RectangleUtil.sPoint.x\n if (maxX < RectangleUtil.sPoint.x) maxX = RectangleUtil.sPoint.x\n if (minY > RectangleUtil.sPoint.y) minY = RectangleUtil.sPoint.y\n if (maxY < RectangleUtil.sPoint.y) maxY = RectangleUtil.sPoint.y\n }\n\n out.setTo(minX, minY, maxX - minX, maxY - minY)\n return out\n }",
"function Boundary(x_,y_, w_, h_) {\n // But we also have to make a body for box2d to know about it\n // Body b;\n\n this.x = x_;\n this.y = y_;\n this.w = w_;\n this.h = h_;\n\n var fd = new box2d.b2FixtureDef();\n fd.density = 1.0;\n fd.friction = 0.5;\n fd.restitution = 0.2;\n\n var bd = new box2d.b2BodyDef();\n\n bd.type = box2d.b2BodyType.b2_staticBody;\n bd.position = scaleToWorld(this.x, this.y);\n fd.shape = new box2d.b2PolygonShape();\n fd.shape.SetAsBox(this.w/(scaleFactor*2), this.h/(scaleFactor*2));\n this.body = world.CreateBody(bd).CreateFixture(fd);\n\n // Draw the boundary, if it were at an angle we'd have to do something fancier\n this.display = function() {\n fill(127);\n stroke(200);\n rectMode(CENTER);\n rect(this.x,this.y,this.w,this.h);\n };\n}",
"function Basin(index, basinX, basinY, basinCap, basinWidth, basinHeight) {\n var isQuad = true;\n\n this.basinX = basinX;\n this.basinY = basinY;\n this.basinCap = basinCap;\n this.basinWidth = basinWidth;\n this.basinHeight = basinHeight;\n\n MAX_SIZE = basinWidth * basinHeight;\n basinSize = new Array(2);\n basinSize[0] = int((basinCap[0] + basinCap[1]) / agileModel.maxCap * MAX_SIZE);\n basinSize[1] = int( basinCap[0] / agileModel.maxCap * MAX_SIZE);\n CORNER_BEVEL = new Array(2);\n CORNER_BEVEL[0] = 10;\n CORNER_BEVEL[1] = 5;\n s = new Array(2);\n\n // Designate CellType\n for (var i=0; i<basinSize[0]; i++) {\n var u = basinX + i%basinWidth;\n var v = basinY + i/basinWidth;\n cellType[u][v][0] = \"SITE_\" + index;\n if (i<basinSize[1]) {\n cellType[u][v][1] = \"EXISTING\";\n } else {\n cellType[u][v][1] = \"GREENFIELD\";\n }\n }\n\n // Outline (0 = Existing Capacity; 1 = Greenfield Capacity);\n for (var i=0; i<2; i++) {\n \n if (basinSize[i]%basinWidth != 0) {\n isQuad = false;\n } else {\n isQuad = true;\n }\n \n beginShape();\n noFill();\n strokeWeight(2*CORNER_BEVEL[i]);\n\n if (i==0) {\n stroke(255, 150);\n } else {\n stroke(GSK_ORANGE);\n }\n\n vertex( - CORNER_BEVEL[i] + basinX*cellW, - CORNER_BEVEL[i] + basinY*cellH);\n vertex( + CORNER_BEVEL[i] + (basinX + basinWidth) * cellW, - CORNER_BEVEL[i] + basinY*cellH);\n if (isQuad) {\n vertex( + CORNER_BEVEL[i] + (basinX + basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n vertex( - CORNER_BEVEL[i] + basinX*cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n } else {\n vertex( + CORNER_BEVEL[i] + (basinX + basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n vertex( + CORNER_BEVEL[i] + (basinX + basinSize[i]%basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth) * cellH);\n vertex( + CORNER_BEVEL[i] + (basinX + basinSize[i]%basinWidth) * cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth + 1) * cellH);\n vertex( - CORNER_BEVEL[i] + basinX*cellW, + CORNER_BEVEL[i] + (basinY + basinSize[i] / basinWidth + 1) * cellH);\n }\n vertex( - CORNER_BEVEL[i] + basinX*cellW, - CORNER_BEVEL[i] + basinY*cellH);\n\n endShape(CLOSE);\n }\n \n }",
"static calculateRubberBandPosition(selectedMatrix, selectedBox, globalMatrix, parentMatrix) {\n if (!selectedMatrix) {\n return {\n x: 0,\n y: 0,\n w: 0,\n h: 0,\n transform: 0\n };\n }\n\n let box = selectedBox;\n let matrix = selectedMatrix;\n //extract rotation\n box = this.calculateTrasformBox(box, globalMatrix, matrix, parentMatrix);\n box.x = box.x - Consts.RUBBER_BAND_HANDLE_SIZE;\n box.y = box.y - Consts.RUBBER_BAND_HANDLE_SIZE;\n box.w = box.w + Consts.RUBBER_BAND_HANDLE_SIZE * 2;\n box.h = box.h + Consts.RUBBER_BAND_HANDLE_SIZE * 2;\n\n let rubberMatrix = new Matrix();\n let cx = box.x + box.w / 2;\n let cy = box.y + box.h / 2;\n rubberMatrix = SpacialHelper.rotateToCenter(cx, cy, box.angle, rubberMatrix);\n rubberMatrix = rubberMatrix.matrixToText();\n return {\n x: box.x,\n y: box.y,\n w: box.w,\n h: box.h,\n transform: rubberMatrix\n };\n }",
"getBlocksAABB() {\n // always include top left and available width to anchor the bounds\n let aabb = new Box2D(0, 0, this.sceneGraph.availableWidth, 0);\n // we should only autosize the nodes representing parts\n objectValues(this.parts2nodes).forEach((node) => {\n aabb = aabb.union(node.getAABB());\n // add in any part list items for this block\n const blockId = this.elementFromNode(node);\n objectValues(this.listNodes[blockId]).forEach((node) => {\n aabb = aabb.union(node.getAABB());\n });\n });\n // add any nested constructs\n objectValues(this.nestedLayouts).forEach((layout) => {\n aabb = layout.getBlocksAABB().union(aabb);\n });\n return aabb;\n }",
"getModelAABB() {\n if (!this.mesh) {\n console.log(\"Error while creating AABB for model: No\" + \n \" mesh set.\")\n return;\n }\n\n var minX = Infinity;\n var maxX = -Infinity;\n var minY = Infinity;\n var maxY = -Infinity;\n var minZ = Infinity;\n var maxZ = -Infinity;\n \n for (var i = 0; i < this.mesh.vertPositions.length; i += 3) {\n const x = this.mesh.vertPositions[i];\n const y = this.mesh.vertPositions[i+1];\n const z = this.mesh.vertPositions[i+2];\n\n if (x < minX) {\n minX = x;\n } else if (x > maxX) {\n maxX = x;\n }\n\n if (y < minY) {\n minY = y;\n } else if (y > maxY) {\n maxY = y;\n }\n\n if (z < minZ) {\n minZ = z;\n } else if (z > maxZ) {\n maxZ = z;\n }\n }\n\n return {\n \"minX\" : minX,\n \"maxX\" : maxX,\n \"minY\" : minY,\n \"maxY\" : maxY,\n \"minZ\" : minZ,\n \"maxZ\" : maxZ,\n }\n }",
"bbox () {\r\n parser().path.setAttribute('d', this.toString());\r\n return parser.nodes.path.getBBox()\r\n }",
"function Rectangle(width, height, color) {\n var _this = _super.call(this) || this;\n _this.width = width;\n _this.height = height;\n _this.color = color;\n // Set default position.\n _this.setPosition(0, 0);\n return _this;\n }",
"function render_bottom_border() {\n context.setLineDash([5, 15]);\n\n context.lineWidth = 1;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(0, (canvas.height - 155));\n context.lineTo(canvas.width, (canvas.height - 155));\n context.stroke();\n }",
"function histogramRenderBar(params, api) {\n var yValue = api.value(2);\n var start = api.coord([api.value(0), yValue]);\n var size = api.size([api.value(1) - api.value(0), yValue]);\n var style = api.style();\n\n return {\n type: 'rect',\n shape: {\n x: start[0] + 1,\n y: start[1],\n width: size[0] - 2,\n height: size[1]\n },\n style: style\n };\n }",
"function BoundingBox2D(min, max) {\n if (typeof min === \"undefined\") { min = new Vapor.Vector2(); }\n if (typeof max === \"undefined\") { max = new Vapor.Vector2(); }\n this.min = min;\n this.max = max;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FETCH (POST) TO PERSIST NEW OBSERVATION TO DATABASE addMarkerToDatabase function called in ShowNewObservationForm function sends a post request to backend to create new observation instance from newObservation object and persist it in the database | addMarkerToDatabase(newObservation, map) {
let configObj = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(newObservation)
};
fetch(this.baseURL, configObj)
.then(function(response) {
return response.json()
})
.then(json => {
let obs = json.data
let observation = new Observation(obs.id, obs.attributes.name, obs.attributes.description, obs.attributes.category_id, obs.attributes.latitude, obs.attributes.longitude)
observation.renderMarker(map)
})
.catch(function(error) {
alert("ERROR! Please Try Again");
console.log(error.message);
});
} | [
"postNewInterest(newInterestToSave) {\n // We want to return this fetch request so that at the point it is called, we can take advantage of the asynchronous nature of promises to wait for this to be done before getting the latest data and rerendering the DOM.\n return fetch(\"http://localhost:8088/interests\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(newInterestToSave)\n })\n }",
"postToDatabase(newJournal) {\n return fetch(\"http://localhost:8088/journalEntries\", {\n method: \"POST\",\n body: JSON.stringify(newJournal),\n headers: {\n \"Content-Type\": \"application/json\"\n }\n })\n .then(response => response.json())\n }",
"saveJournalEntry(newJournalEntry) {\n // const entryBody = JSON.stringify(newJournalEntry)\n // console.log(entryBody)\n return fetch(\"http://localhost:3000/entries\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(newJournalEntry)\n })\n .then(response => response.json()) //the object that was just created\n }",
"function insertEVV(longitude, latitude) {\n //get user data to pull correct schedule\n $.ajax({\n url: \"/api/user_data\",\n type: \"GET\"\n }).then(function(userData) {\n //get shift record for shift occuring today\n $.ajax({\n url: \"/api/shiftRecord/\" + userData.id,\n type: \"GET\"\n }).then(function(currentShift) {\n //checks if today's shift clientSignature has a value which indicates shift end\n if (currentShift.clientSignature) {\n //creates Check Out object to send to db\n var EVVRecord = {\n checkOutLongitude: longitude,\n checkOutLatitude: latitude,\n checkOutTime: moment().format(\"h:mm:ss\"),\n UserID: userData.id,\n id: currentShift.id\n };\n } else {\n //creates Check In object if client signature is blank in database\n var EVVRecord = {\n checkInLongitude: longitude,\n checkInLatitude: latitude,\n checkInTime: moment().format(\"h:mm:ss\"),\n UserID: userData.id,\n id: currentShift.id\n };\n }\n //puts new EVVRecord data into database for respective Check In or Check Out\n $.ajax({\n method: \"PUT\",\n url: \"/api/EVVRecord\",\n data: EVVRecord\n }).then(\n console.log(\"successfully updated shift id: \" + currentShift.id)\n );\n });\n });\n }",
"onSavesuppliers(event) {\n event.preventDefault();\n // adding\n if (this.state.suppliersId == \"\") {\n fetch(`${this.url}`, {\n method: 'POST', \n body: JSON.stringify({\n suppliersId: 0, \n name: this.$suppliersName.value,\n phone: this.$suppliersPhone.value,\n email: this.$suppliersEmail.value,\n website: this.$suppliersWebsite.value,\n contactFirstName: this.$suppliersContactFirstName.value,\n contactLastName: this.$suppliersContactLastName.value,\n contactPhone: this.$suppliersContactPhone.value,\n contactEmail: this.$suppliersContactEmail.value,\n note: this.$suppliersNote.value\n }),\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(response => response.json())\n .then(data => { \n // returns the record that we added so the ids should be there \n if (data.suppliersId)\n {\n this.state.suppliersId = data.suppliersId;\n this.state.suppliers = data;\n this.$suppliersId.value = this.state.suppliersId;\n this.fillsuppliersFields();\n this.$suppliersId.readOnly = false;\n this.enableButtons(\"found\");\n alert(\"suppliers was added.\")\n }\n else{\n alert('There was a problem adding suppliers info!'); \n }\n })\n .catch(error => {\n alert('There was a problem adding suppliers info!'); \n });\n }\n // updating\n else {\n // the format of the body has to match the original object exactly \n // so make a copy of it and copy the values from the form\n let suppliers = Object.assign(this.state.suppliers);\n suppliers.name = this.$suppliersName.value;\n suppliers.phone = this.$suppliersPhone.value;\n suppliers.email = this.$suppliersEmail.value;\n suppliers.website = this.$suppliers.Website.value;\n suppliers.contactFirstName = this.$suppliersContactFirstName.value;\n suppliers.contactLastName = this.$suppliersContactLastName.value;\n suppliers.contactPhone = this.$suppliersContactPhone.value;\n suppliers.contactEmail = this.$suppliersContactEmail.value;\n suppliers.note = this.$suppliersNote.value;\n fetch(`${this.url}/${this.state.suppliersId}`, {\n method: 'PUT', \n body: JSON.stringify(suppliers),\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(response => {\n // doesn't return a body just a status code of 204 \n if (response.status == 204)\n {\n this.state.suppliers = Object.assign(suppliers);\n this.fillsuppliersFields();\n this.$suppliersId.readOnly = false;\n this.enableButtons(\"found\");\n alert(\"suppliers was updated.\")\n }\n else{\n alert('There was a problem updating suppliers info!'); \n }\n })\n .catch(error => {\n alert('There was a problem adding suppliers info!'); \n });\n }\n }",
"function jnuine_add(req, res, next) {\n var jnuineParams = req.body;\n var jnuine = new Models.Jnuine(jnuineParams);\n jnuine.save(function(err, savedJnuine) {\n if(err) res.send(500, err);\n else res.send(200, savedJnuine); \n });\n}",
"function postNewToy(toy) {\n fetch('http://localhost:3000/toys', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: \"application/json\"\n },\n body: JSON.stringify({\n \"name\": toy.name.value,\n \"image\": toy.image.value,\n \"likes\": 0\n })\n })\n .then(resp => resp.json())\n .then((t) => {\n toyData(t)\n })\n}",
"function handleCreateNewIdea() {\n $('body').on(\"submit\", \"#form-new-idea\", (event) => {\n event.preventDefault();\n const statusElement = document.getElementById('status-selector');\n const statusVal = statusElement.options[statusElement.selectedIndex].value;\n const likabilityElement = document.getElementById('likability-selector');\n const likabilityVal = likabilityElement.options[likabilityElement.selectedIndex].value;\n\n const newIdea = {\n title: $('#title-txt').val(),\n description: document.getElementById(\"description-txt\").value,\n status: statusVal,\n likability: likabilityVal\n }\n\n createNewIdea({\n jwToken: user,\n newIdea,\n onSuccess: getAndDisplayIdeas,\n onError: \"\"\n });\n });\n}",
"function otpAddDataSave(event, addOtpData, config, client) {\n //console.log(addFormOtp);\n delete addOtpData.province;\n delete addOtpData.Tehsil;\n delete addOtpData.district;\n delete addOtpData.province;\n delete addOtpData.ddHealthHouseOTP;\n delete addOtpData.uc;\n addOtpData.client_id = client;\n addOtpData.username = config.usernameL;\n addOtpData.org_name = config.org_nameL;\n addOtpData.project_name = config.project_nameL;\n const addFormOtp = addOtpData;\n console.log(addFormOtp);\n knex('tblOtpAdd')\n .insert(addFormOtp)\n .then(result => {\n console.log(result + 'OTP addmision added')\n sucMsg(event, '', 'OTP admission added successfully')\n // addOtp.webContents.send(\"resultSentOtpAdd\", {\n // 'msg': 'records added'\n // });\n var interimData = {\n otp_id: addOtpData.otp_id,\n interim_id: _uuid(),\n client_id: imran.client,\n muac: addFormOtp.muac,\n weight: addFormOtp.weight,\n ration1: addFormOtp.ration1,\n quantity1: addFormOtp.quantity1,\n ration2: (addFormOtp.ration2 ? addFormOtp.ration2 : ''),\n quantity2: addFormOtp.quantity2,\n ration3: (addFormOtp.ration3 ? addFormOtp.ration3 : ''),\n quantity3: addFormOtp.quantity3,\n curr_date: localDate(),\n created_at: localDate(),\n status: 'open',\n next_followup: function () {\n var myDate = new Date(addOtpData.reg_date);\n myDate.setDate(myDate.getDate() + (addOtpData.prog_type == 'sfp' ? 14 : 7))\n return toJSONLocal(myDate)\n }()\n }\n console.log(interimData)\n return knex('tblInterimOtp')\n .insert(interimData)\n })\n .then(result => {\n console.log('interim ID: ', result);\n })\n .catch(e => {\n console.log(e)\n console.log(e + 'OTP add error');\n errMsg(event, '', 'OTP Addmision not added, plz try again or contact admin');\n // addOtp.webContents.send(\"resultSentOtpAdd\", {\n // 'err': 'records not added, plz try again'\n // });\n })\n // addFormOtp = null;\n}",
"function createNoteObject(writebackContext, clinicalObjectUid, callback) {\n var noteObject = {};\n noteObject.patientUid = writebackContext.model.patientUid;\n noteObject.authorUid = writebackContext.model.authorUid;\n noteObject.domain = 'ehmp-note';\n noteObject.subDomain = 'noteObject';\n noteObject.visit = writebackContext.model.visit;\n noteObject.ehmpState = 'active';\n noteObject.referenceId = null;\n var noteObjectData = {};\n noteObjectData.sourceUid = clinicalObjectUid;\n noteObjectData.problemRelationship = '';\n noteObjectData.annotation = '';\n if (writebackContext.model.data) {\n if (writebackContext.model.data.problemRelationship) {\n noteObjectData.problemRelationship = writebackContext.model.data.problemRelationship;\n }\n if (writebackContext.model.data.annotation) {\n noteObjectData.annotation = writebackContext.model.data.annotation;\n }\n noteObjectData.madlib = writebackContext.model.data.madlib;\n }\n noteObject.data = noteObjectData;\n pjds.create(writebackContext.logger, writebackContext.appConfig, noteObject, function(err, response) {\n if (err) {\n return callback(err);\n }\n writebackContext.logger.debug({\n noteObject: response\n }, 'new note object');\n return callback(null, response.headers.location);\n });\n}",
"function submitObjektForm() {\n console.log(\"submitObjektForm(), getselectedcontentmode: \" + getSelectedContentMode());\n\n if (getSelectedContentMode() == \"upload\") {\n alert(\"create multipart form!\");\n var formdata = new FormData();\n formdata.append(\"title\", objektForm.title.value);\n formdata.append(\"src\", objektForm.upload.files[0]);\n formdata.append(\"description\", objektForm.description.value);\n formdata.append(\"type\", \"objekt\");\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function() {\n if (xhr.readyState==4 && xhr.status == 200) {\n alert(\"got response from server: \" + xhr.responseText);\n var objektData = JSON.parse(xhr.responseText);\n crudops.createObject(objektData, function(created) {\n alert(\"created objekt element: \" + JSON.stringify(created));\n eventDispatcher.notifyListeners(iam.eventhandling.customEvent(\"crud\", \"created\", \"object\", created));\n });\n }\n };\n xhr.open(\"POST\", \"http2mdb/objects\");\n xhr.send(formdata);\n \n } else if (getSelectedContentMode() == \"list\") {\n var objid = objektFormInputList.value;\n console.log(\"ObjektID: \" + objid);\n var objectToAdd;\n crudops.readObject(objid, function (foundObject) {\n var newObjekt = {\"_id\" : objid, \"type\" : \"objekt\", \"render_container\" : \"none\"}; \n alert(\"topicid: \" + topicid);\n console.log(\"Dieses Objekt wird nun zum Topicview hinzugefügt: \" + JSON.stringify(newObjekt) + \"erhaltenes Objekt: \" + JSON.stringify(foundObject));\n console.log(\"updateTopicview im ObjektFormVC\");\n crudops.updateTopicview(topicid, newObjekt, function(update) {\n //eventDispatcher.notifyListeners(iam.eventhandling.customEvent(\"crud\", \"updated\", \"topicview\", ));\n eventDispatcher.notifyListeners(iam.eventhandling.customEvent(\"crud\", \"read\", \"object\", update));\n });\n });\n \n } else {\n crudops.createObject({\n title : objektForm.title.value,\n src : objektForm.src.value,\n type : \"objekt\",\n description : objektForm.description.value\n }, function(created) {\n //alert(\"created objekt: \" + JSON.stringify(created));\n eventDispatcher.notifyListeners(iam.eventhandling.customEvent(\"crud\", \"created\", \"object\", created));\n });\n }\n return false;\n }",
"function createListing(){\n event.preventDefault()\n // clearUL()\n \n const listing = { \n ad_name: document.getElementById('ad-name').value, \n business_name: document.getElementById('business-name').value,\n home_service_id: document.getElementById('service-list').value,\n logo_image: document.getElementById('logo-image').value,\n ad_message: document.getElementById('ad-message').value,\n ad_image: document.getElementById('ad-image').value,\n home_service_updated_at: document.getElementById('home-service-updated-at').value \n\n // home_service_updated_at: new Date()\n }\n\n // debugger\n\n const configObj = {\n method: 'POST',\n body: JSON.stringify(listing),\n headers: {\n 'Content-Type': 'application/json', \n 'Accept': 'application/json'\n }\n }\n \n fetch(BASE_URL, configObj)\n .then(response => response.json())\n .then(listings => {\n pullFromDB(listings)\n // console.log(listings)\n // let dateStr = JSON.parse(json);\n // let date = new Date(dateStr); \n })\n\n clearForm();\n // document.getElementById(\"listing-Form\").addEventListener(\"submit\", pullFromDB)\n\n\n }",
"function CreateRequestObject() {\r\n $scope.ShiftList[0] = { ShiftMasterId: $scope.Shift.ShiftMasterId1, CompanyId: $scope.CompanyId, ShiftNo: 1, FromTime: $scope.Shift.FromTime1, ToTime: $scope.Shift.ToTime1 }\r\n $scope.ShiftList[1] = { ShiftMasterId: $scope.Shift.ShiftMasterId2, CompanyId: $scope.CompanyId, ShiftNo: 2, FromTime: $scope.Shift.FromTime2, ToTime: $scope.Shift.ToTime2 }\r\n $scope.ShiftList[2] = { ShiftMasterId: $scope.Shift.ShiftMasterId3, CompanyId: $scope.CompanyId, ShiftNo: 3, FromTime: $scope.Shift.FromTime3, ToTime: $scope.Shift.ToTime3 }\r\n }",
"function apiNew(req, res) {\n //console.log('POST /api/breed');\n // create a new breed in the db\n //console.log(req.body);\n if (!req.body.name) {\n res.status(503).send('cannot add a new breed without a name');\n } else if (!req.body.description) {\n res.status(503).send('cannot add a new breed without a description');\n } else if (!req.body.infoSources) {\n res.status(503).send('cannot add a new breed without any info sources');\n } else {\n //console.log('r.b.i: ' + req.body.infoSources);\n let infoList = req.body.infoSources.split(', ');\n //console.log('infoList: ' + infoList);\n //console.log('infoList.length: ' + infoList.length);\n let sheep = new db.Breed({\n name: req.body.name,\n origin: req.body.origin || '',\n status: req.body.status || '',\n stapleLength: req.body.stapleLength || '',\n fleeceWeight: req.body.fleeceWeight || '',\n fiberDiameter: req.body.fiberDiameter || '',\n description: req.body.description,\n image: req.body.image || 'n/a',\n infoSources: [],\n notes: req.body.notes || ''\n });\n\n //console.log(sheep.infoSources);\n for (let i = 0; i < infoList.length; i++) {\n sheep.infoSources.push(infoList[i]);\n }\n\n //console.log(sheep);\n db.Breed.create(sheep, function(err, sheepie) {\n if (err) {\n res.status(503).send('could not add new sheep breed. sorry.');\n } else {\n res.json(sheepie);\n }\n });\n }\n\n}",
"function newPlaceSuccess(data){\n $('#newPlaceForm input').val('');\n allNeighborhoods.forEach(function (neighborhood){\n if(neighborhood._id === neighborhoodId){\n neighborhood.places.push(data);\n }\n });\n\n renderSpecificNeighborhood();\n }",
"function add(venue_id, note, api_url, loginHeader, user_id) {\n console.log(\"About to post new note note to server. venue id: \" + venue_id + \", note: \" + note);\n var headers = loginHeader;\n headers['Content-type'] = 'application/json;charset=utf-8';\n\n $http({\n method: 'POST',\n url: api_url + '/api/v1/note',\n headers: headers,\n data: {\n note: note,\n venue_id: venue_id,\n user_id: user_id\n }\n })\n .then(function(response) {\n console.log(response.data);\n }, function(rejection) {\n console.log(rejection.data);\n });\n }",
"function myLoansSaveLoan() {\n \n // TO DO\n // save the details of the loan to the db\n \n}",
"createMapping() {\n this.toastService_.showInfo('Creating mapping ...');\n this.addMappingService_\n .createRootstockMappings(\n this.selectedSourceProviderId, this.selectedTargetProviderId)\n .then(\n (response) => {\n this.toastService_.showInfo(\n `Mapping created successfully. Please check cl/${\n response.getChangelistNumber()} for details.`,\n TOAST_DISPLAY_DURATION_MS);\n\n this.state_.reload();\n },\n (error) => {\n this.toastService_.showError(\n `Unable to create mapping. Error: ${error.message}`);\n });\n }",
"function MDUO_Save(){\n console.log(\"=== MDUO_Save =====\") ;\n // save subject that have exam_id or ntb_id\n // - when exam_id has value and ntb_id = null: this means that ntb is removed\n // - when exam_id is null and ntb_id has value: this means that there is no exam record yet\n // - when exam_id and ntb_id both have value: this means that ntb_id is unchanged or chganegd\n const exam_list = [];\n if(mod_MDUO_dict.duo_subject_dicts){\n for (const data_dict of Object.values(mod_MDUO_dict.duo_subject_dicts)) {\n\n if (data_dict.exam_id || data_dict.ntb_id){\n exam_list.push({\n subj_id: data_dict.subj_id,\n ntb_id: data_dict.ntb_id,\n dep_pk: data_dict.dep_id,\n level_pk: data_dict.lvl_id,\n subj_name_nl: data_dict.subj_name_nl,\n exam_id: data_dict.exam_id,\n ntb_omschrijving: data_dict.ntb_omschrijving\n });\n };\n };\n };\n if (exam_list.length) {\n const upload_dict = {\n examperiod: setting_dict.sel_examperiod,\n exam_list: exam_list\n };\n// --- upload changes\n const url_str = urls.url_duo_exam_upload;\n console.log(\"upload_dict\", upload_dict) ;\n console.log(\"url_str\", url_str) ;\n\n UploadChanges(upload_dict, url_str);\n };\n $(\"#id_mod_duoexams\").modal(\"hide\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
new click action for randomizing saturation and lightness of the pixel pool | function buttonrandomcolorclick() {
function get_random_color() {
var h = rand(1, 360);
var s = rand(0, 100);
var l = rand(10, 90);
return 'hsl(' + h + ',' + s + '%,' + l + '%)';
}
for (var i = 0, max = px.$swatchpixels.length; i < max; i++) {
px.$swatchpixels[i].style.backgroundColor = get_random_color();
}
} | [
"function mouseClicked() {\n var size = random(10, 40);\n drawMondrianblue(mouseX, mouseY, size);\n}",
"function setPixelColor(event) {\n if (event.type === 'click') {\n event.target.style.backgroundColor = 'red';\n } else if (mousingDown) {\n event.target.style.backgroundColor = 'red';\n }\n }",
"function mouseClickBtnRandom() {\n clickColor =\n \"rgb( \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" \" +\n Math.floor(Math.random() * (0 + 255)) +\n \" )\";\n mouseClickBtn.style.backgroundColor = clickColor;\n clickButton.style.backgroundColor = clickColor;\n\n}",
"function makeitBlur() {\n if (imageisloaded(image5)){\n output=new SimpleImage(image5.getWidth(),image5.getHeight());\n for (var px of image5.values()) {\n var x = px.getX();\n var y = px.getY();\n \n if(Math.random()<0.5){\n output.setPixel(x,y,px);\n }\n //if not, call getnewPixel() (does math, returns new pixel), call it newpix, set that new pixel to output \n else{\n newinpix = getnewPixel(image5,x,y);\n output.setPixel(x,y,newinpix);\n }\n output.drawTo(canvas);\n }\n } \n}",
"function randomize() {\n $(\"#saturation\").slider('value', rand(0, 100));\n $(\"#lightness\").slider('value', rand(0, 100));\n\n var min = rand(0, 360);\n var max = rand(0, 360);\n\n if (min > max) {\n min = min + max;\n max = min - max;\n min = min - max;\n }\n\n $(\"#hue\").slider('values', 0, min);\n $(\"#hue\").slider('values', 1, max);\n }",
"function redClick() {\n\tredLight();\n\tuserPlay.push(2);\n\tuserMovement();\t\n}",
"function yellowClick() {\n\tyellowLight();\n\tuserPlay.push(3);\n\tuserMovement();\t\n}",
"function colorAlgorithm(){\n\tvar temp = new Array();\n\t\n\tvar tag2 = document.getElementById('gloss').value;\n\tglossiness = tag2;\n\t\n\tvar lightVector = new Vector3([500, 500, 500]);\n\tlightVector.normalize();\n\tvar lightVector2 = new Vector3([0,500,0]);\n\tlightVector2.normalize();\n\t\tfor (var j = 3; j < normies.length; j+=6){\n\t\t\tvar nVector = new Vector3([normies[j],normies[j+1],normies[j+2]]);\n\t\t\tnVector.normalize();\n\t\t\tvar reflect = calcR(nVector,lightVector); //two times dot times normal minus lightdirection\n\t\t\tvar dot = (\n\t\t\t\tnormies[j] * lightVector.elements[0] +\n\t\t\t\tnormies[j+1] * lightVector.elements[1] +\n\t\t\t\tnormies[j+2] * lightVector.elements[2]\n\t\t\t\t);\n\t\t\t\tdot = dot/256; //////color hack\n\n\t\t\tif (pointLight&&lightDir.checked){\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + (1*dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + (0*dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + (0*dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\t\t\n\t\t\t} else if (pointLight&&!lightDir.checked){\n\t\t\t\t\n\t\t\t\tvar L = new Vector3([\n\t\t\t\t\tlightVector2.elements[0] - normies[j],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+1],\n\t\t\t\t\tlightVector2.elements[0] - normies[j+2]\n\t\t\t\t]);\n\t\t\t\tvar dot2 = (\n\t\t\t\t\tnormies[j] * lightVector2.elements[0] +\n\t\t\t\t\tnormies[j+1] * lightVector2.elements[1] +\n\t\t\t\t\tnormies[j+2] * lightVector2.elements[2]\n\t\t\t\t\t);\n\t\t\t\t\n\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1*dot2) + Ia.elements[0];\n\t\t\t\t\tvar g = (0*dot2) + Ia.elements[1];\n\t\t\t\t\tvar b = (0*dot2) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\t\n\t\t\t\t}\n\t\t\t} else if (lightDir.checked){\n\t\t\t\tvar Is = calcIs(eyeDirection,reflect,glossiness);\n\t\t\t\tvar specTag = document.getElementById(\"specToggle\");\n\t\t\t\tif (specTag.checked){\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0] + Is.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1] + Is.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2] + Is.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tvar r = (1 * dot) + Ia.elements[0];\n\t\t\t\t\tvar g = (0 * dot) + Ia.elements[1];\n\t\t\t\t\tvar b = (0 * dot) + Ia.elements[2];\n\t\t\t\t\t\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t\ttemp.push(r,g,b);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse for (var k = 0; k < 20; k++) temp.push(0.5,0.5,0.5);\n\t\t}\n\t return temp;\n}",
"function redHue() {\n for (var pixel of image.values()) {\n var avg =\n (pixel.getRed() + pixel.getGreen() + pixel.getBlue()) /3;\n if (avg < 128){\n pixel.setRed(2 * avg);\n pixel.setGreen(0);\n pixel.setBlue(0);\n } else {\n pixel.setRed(255);\n pixel.setGreen(2 * avg - 255);\n pixel.setBlue(2 * avg - 255);\n }\n }\n var c2 = document.getElementById(\"c2\");\n var image2 = image;\n image2.drawTo(c2);\n \n \n}",
"function initMouse() {\r\n\tGame.mouse = Crafty.e(\"2D, Mouse\").attr({\r\n\t\tw : Game.width(),\r\n\t\th : Game.height(),\r\n\t\tx : 0,\r\n\t\ty : 0\r\n\t});\r\n\t//Everytime somewhere is clicked, this method is executed\r\n\tGame.mouse.bind('Click', function(e) {\r\n\t\t//Calculates the board field that is clicked, e.g Floor(157.231 / 70) = 2 \r\n\t\tGame.mousePos.x = Math.floor(Crafty.mousePos.x / Game.map_grid.tile.width);\r\n\t\tGame.mousePos.y = Math.floor(Crafty.mousePos.y / Game.map_grid.tile.width);\r\n\t\tconsole.log(Game.mousePos.x, Game.mousePos.y);\r\n\t\tconsole.log(\"x: \" + Crafty.mousePos.x + \" - y: \" + Crafty.mousePos.y);\r\n\r\n\t\t// CLick on a figure\r\n\t\tif ((Game.board[Game.mousePos.x][Game.mousePos.y].player == Game.playerTurn) && Game.turn\t//if the figure has the same color as the player who is next\r\n\t\t\t\t&& Game.board[Game.mousePos.x][Game.mousePos.y].type != 'Chip') { //and wether it is no \r\n\t\t\tif (Game.mousePos.x != Game.clicked.x || Game.mousePos.y != Game.clicked.y) { \r\n\t\t\t\tGame.setColor(Game.clicked.x, Game.clicked.y, false);\r\n\t\t\t}\r\n\t\t\t//Save the selected figure\r\n\t\t\tGame.clicked.x = Game.mousePos.x;\r\n\t\t\tGame.clicked.y = Game.mousePos.y\r\n\t\t\tGame.clicked.active = 'true';\r\n\r\n\t\t\tconsole.log(\"DEBUG> Clicked!!\");\r\n\t\t\tGame.setColor(Game.clicked.x, Game.clicked.y, true); //Highlight the figure in green\r\n\t\t} else if (Game.clicked.active == 'true' && Game.clicked.x == Game.mousePos.x \r\n\t\t\t\t&& Game.clicked.y == Game.mousePos.y) { //Click on the selceted figure again\r\n\t\t\tGame.setColor(Game.clicked.x, Game.clicked.y, false);\r\n\t\t\tGame.clicked.x = -1;\r\n\t\t\tGame.clicked.y = -1;\r\n\t\t\tGame.clicked.active = 'false';\r\n\r\n\t\t\t// Click on a field, make a turn\r\n\t\t} else if (Game.clicked.active == 'true' && Game.turn) {\r\n\t\t\tsend('{\"type\" : \"turn\", \"x\" : \"' + Game.mousePos.x + '\", \"y\" : \"' + Game.mousePos.y + '\", \"oldX\" : \"' + Game.clicked.x\r\n\t\t\t\t\t+ '\", \"oldY\" : \"' + Game.clicked.y + '\"}'); //send turn request to server\r\n\t\t} else {\r\n\t\t\ttoastr.warning('Du bist nicht dran!');\r\n\t\t}\r\n\t});\r\n\t\r\n\t//bind mouse to Crafty stage\r\n\t//Crafty.addEvent(Game.mouse, Crafty.stage.elem, \"mousedown\", Game.mouse.onMouseDown);\r\n}",
"function shaderButton() {\n document.getElementById(\"shaderBtn\").addEventListener(\"click\", function () {\n colorMode == \"Shader\" ? colorMode = \"Normal\" : colorMode = \"Shader\";\n });\n}",
"function randLightColor() {\r\n\tvar rC = Math.floor(Math.random() * 256);\r\n\tvar gC = Math.floor(Math.random() * 256);\r\n\tvar bC = Math.floor(Math.random() * 256);\r\n\twhile (Math.max(rC, gC, bC) < 200) {\r\n\t\trC = Math.floor(Math.random() * 256);\r\n\t\tgC = Math.floor(Math.random() * 256);\r\n\t\tbC = Math.floor(Math.random() * 256);\r\n\t}\r\n\treturn tColor(rC, gC, bC, 1.0);\r\n}",
"function rndColor() {\n var iRed = Math.floor((Math.random() * 255) + 1);\n var iGreen = Math.floor((Math.random() * 255) + 1);\n var iBlue = Math.floor((Math.random() * 255) + 1);\n\n $(\"#red\").slider(\"value\", iRed);\n $(\"#green\").slider(\"value\", iGreen);\n $(\"#blue\").slider(\"value\", iBlue);\n }",
"function clickevent(TorF)\n{\n\t//The startend value will only activate until it becomes true. This will happen when the button is pressed and calls RandVal().\n\t//Will allow the rest of the code inside to continue while true, but when time ends, will stop the function from running.\n\tif (startEnd) \n\t{\n\t\t//This if statement is checking if the parameter value from the onclick is the same as the rand value.\n\t\tif (TorF == rand)\n\t\t{\n\t\t\tclicked=TorF; //Assigns the TorF value to clicked. clicked will act as a container of the last parameter clicked.\n\t\t\tscore++; //Will increment the score once the if statement activates.\n\t\t\tRandVal() //Calls to RandVal to change the value of rand again.\n\t\t}\n\t\t//Will activate the while statement as long as clicked equals rand.\n\t\t//Clicked is the previous parameter value, so in this statement, it will make sure that the 'mole' will not be in the same place.\n\t\twhile (clicked == rand)\n\t\t{\n\t\t\tRandVal() //Calls to RandVal to change the value of rand again.\n\t\t}\n\t\tdocument.getElementById(clicked).src= 'images/hole.png'; //Will change the src of img on clicked back to a hole.\n\t}\n}",
"function randomColour() {\r\n pattern.push(colours[Math.floor(Math.random() * 4)]);\r\n animations(pattern);\r\n levelAndScoreCount();\r\n\r\n}",
"setClickPenetration (cp){\n if ( cp != undefined ){\n this.clickPenetration = cp ;\n }\n this.projectCrds.setUniform('clickPenetration',\n this.clickPenetration) ;\n this.projectCrds.render() ;\n }",
"function getnewPixel(image5,x,y){\n var distance = 2*Math.floor(Math.random()*10 - 10/2);\n var dx = x + distance;\n var dy = y + distance;\n var newinpix = image5.getPixel(Check(dx,image5.getWidth()), Check(dy,image5.getHeight()));\n return newinpix;\n}",
"function makeWhaleSharkButton() {\n\n // Create the clickable object\n whaleSharkButton = new Clickable();\n \n whaleSharkButton.text = \"\";\n\n whaleSharkButton.image = images[23]; \n\n //makes the button color transparent \n whaleSharkButton.color = \"#00000000\";\n whaleSharkButton.strokeWeight = 0; \n\n //set width + height to image size\n whaleSharkButton.width = 270; \n whaleSharkButton.height = 390;\n\n // placing the button on the page \n whaleSharkButton.locate( width * (31/32) - whaleSharkButton.width * (31/32), height * (1/128) - whaleSharkButton.height * (1/128));\n\n // // Clickable callback functions for the whaleshark button , defined below\n whaleSharkButton.onPress = whaleSharkButtonPressed;\n whaleSharkButton.onHover = beginButtonHover;\n whaleSharkButton.onOutside = animalButtonOnOutside;\n}",
"function colorTarget() {\n let colorPicked = Math.floor(Math.random() * colors.length);\n return colors[colorPicked];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Safely install SIGINT listener. NOTE: this will only work on OSX and Linux. | function _safely_install_sigint_listener() {
const listeners = process.listeners(SIGINT);
const existingListeners = [];
for (let i = 0, length = listeners.length; i < length; i++) {
const lstnr = listeners[i];
/* istanbul ignore else */
if (lstnr.name === '_tmp$sigint_listener') {
existingListeners.push(lstnr);
process.removeListener(SIGINT, lstnr);
}
}
process.on(SIGINT, function _tmp$sigint_listener(doExit) {
for (let i = 0, length = existingListeners.length; i < length; i++) {
// let the existing listener do the garbage collection (e.g. jest sandbox)
try {
existingListeners[i](false);
} catch (err) {
// ignore
}
}
try {
// force the garbage collector even it is called again in the exit listener
_garbageCollector();
} finally {
if (!!doExit) {
process.exit(0);
}
}
});
} | [
"function setupTerminationHandlers(){\n // Process on exit and signals.\n process.on('exit', function() { terminator(); });\n\n // Removed 'SIGPIPE' from the list - bugz 852598.\n ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',\n 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'\n ].forEach(function(element, index, array) {\n process.on(element, function() { terminator(element); });\n });\n }",
"function onCtrlC() {\n w.info(\"\\nGracefully shutting down from SIGINT (Ctrl+C)\");\n setTimeout(process.exit, 2000); // Wait 2 seconds and exit. This is needed for Firebase to exit.\n}",
"function exitOnSignal(signal) {\n process.on(signal, function () {\n logger.warn(\"Caught \" + signal + \", shutting down\");\n process.exit(1);\n });\n}",
"function setupHandlers() {\n\n function terminate(err) {\n util.log('Uncaught Error: ' + err.message);\n console.log(err.stack);\n if (proc.shutdownHook) {\n proc.shutdownHook(err, gracefulShutdown);\n }\n }\n\n process.on('uncaughtException', terminate);\n\n process.addListener('SIGINT', gracefulShutdown);\n\n process.addListener('SIGHUP', function () {\n util.log('RECIEVED SIGHUP signal, reloading log files...');\n reload(argv);\n });\n\n}",
"_startListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.on(eventName, this._terminate);\n });\n }",
"function badCertListener() {\n}",
"_stopListeningForTermination() {\n this._terminationEvents.forEach((eventName) => {\n process.removeListener(eventName, this._terminate);\n });\n }",
"function catchExceptions () {\n process.on ('uncaughtException', function (err) {\n exceptionHandler (err);\n process.exit (1);\n });\n}",
"function handleSignals(process, server) {\n // Create a handler for each signal...\n signals.forEach((signal) => {\n process.on(signal, async () => {\n server.log(['info'], `Received signal ${signal}. Gracefully shutting down`);\n try {\n // Stop the server. This call is async, so we must await it.\n await server.stop({});\n } catch (error) {\n server.log(['error'], `An error occurred shutting down the server: ${error}`);\n process.exit(1);\n }\n\n // We successfully and cleanly shut down.\n process.exit(0);\n });\n });\n}",
"addQuitListener(handler) {\r\n if (!handler || !(typeof handler == 'function')) {\r\n throw new Error('Handler is not a function!');\r\n }\r\n this._quitHandlers.push(handler);\r\n }",
"static createExitHandling() {\r\n process.on('exit', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'hjbot exit. \\r\\n'}));\r\n\r\n process.on('SIGINT', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'Keyboard interrupt'}));\r\n\r\n process.on('SIGUSR1', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'hjbot process was killed'}));\r\n\r\n process.on('SIGUSR2', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'hjbot process was killed'}));\r\n\r\n process.on('UncaughtException', \r\n Application.exitProgram.bind(null, 0,\r\n {message: 'Uncaught exception occurred'}));\r\n }",
"function fIOSEvents( vEventName, vEventData )\n{\n\t//User has just started the iOS app & Switch to remote control view\n\tif (vEventName == \"changeview\" && vEventData == \"remote\")\n\t{\n\t}\n\t\n\t//User has just started the iOS app & select an unconfigured device\n\tif (vEventName == \"changeview\" && vEventData == \"loading\")\n\t{\n\t\tmCPanel.fOnSignal(cConst.SIGNAL_IOS_START_CONFIGURING);\n\t}\n}",
"initErrorHandlers() {\n this.subscriberSocket.on('connect_delay', () => {\n this.emit(ZmqClient.events.CONNECTION_DELAY, 'Dashcore ZMQ connection delay');\n this.incrementErrorCount();\n });\n this.subscriberSocket.on('disconnect', () => {\n this.emit(ZmqClient.events.DISCONNECTED, 'Dashcore ZMQ connection is lost');\n this.incrementErrorCount();\n });\n this.subscriberSocket.on('monitor_error', (error) => {\n this.emit(ZmqClient.events.MONITOR_ERROR, error);\n this.incrementErrorCount();\n setTimeout(() => this.startMonitor(), 1000);\n });\n }",
"function fIOSEvents( vEventName, vEventData )\n{\n\t//User has just started the iOS app & Switch to remote control view\n\tif (vEventName == \"changeview\" && vEventData == \"remote\")\n\t{\n\t}\n\n\t//User has just started the iOS app & select an unconfigured device\n\tif (vEventName == \"changeview\" && vEventData == \"loading\")\n\t{\n\t\tmCPanel.fOnSignal(cConst.SIGNAL_IOS_START_CONFIGURING);\n\t}\n}",
"function tiproxy_remove_fire_listener(e) {\r\n throw new Error(\"should not be called\");\r\n }",
"function onSSLListening() {\n let addr = ssl_server.address();\n let bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('SSL Listening on ' + bind);\n}",
"static createReadLine() {\r\n iface = rl.createInterface({\r\n input: process.stdin, output: process.stdout\r\n });\r\n //@ts-ignore\r\n iface.on(\"SIGINT\", () => process.emit(\"SIGINT\") );\r\n }",
"function attachPromiseRejectionHandler() {\n detachPromiseRejectionFunction = Raygun.Utilities.addEventHandler(\n window,\n 'unhandledrejection',\n promiseRejectionHandler\n );\n }",
"function startListener(listener) {\n var delayed = q.delay(2000);\n const out = fs.createWriteStream(log_path + \"\\\\iso-\" + listener.company + \".\" + listener.environment + \"-\" + ts + \".log\", {\n flags: \"a\",\n defaultEncoding: \"utf8\" \n });\n deployListener(listener, out).then(function(path) {\n const child = spawn(config.get(\"iso.cmd\"), [], {\n detached: true,\n shell: true,\n stdio: [\"ignore\", out, out],\n cwd: path\n });\n log.write(\"ISO Listener (\" + name + \") starting up with PID \" + child.pid + \"\\r\\n\");\n child.on(\"close\", function(code) {\n if (code === 0) {\n log.write(\"ISO Listener (\" + name + \") shutdown successfully.\\r\\n\");\n } else {\n log.write(\"ISO Listener (\" + name + \") failed (\" + code + \"), please check the appropriate log.\\r\\n\");\n }\n });\n child.on(\"error\", function(err) {\n out.write(\"ERR: \" + err);\n out.end();\n });\n }, function() {\n out.end();\n });\n return delayed;\n}",
"function die() {\n \n var i;\n\n\tconsole.error(\"Script dying!\");\n\n window.addEventListener('error', function (e) {e.preventDefault();e.stopPropagation();}, false);\n\n var handlers = [\n 'copy', 'cut', 'paste',\n 'beforeunload', 'blur', 'change', 'click', 'contextmenu', 'dblclick', 'focus', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'resize', 'scroll',\n 'DOMNodeInserted', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument', 'DOMNodeInsertedIntoDocument', 'DOMAttrModified', 'DOMCharacterDataModified', 'DOMElementNameChanged', 'DOMAttributeNameChanged', 'DOMActivate', 'DOMFocusIn', 'DOMFocusOut', 'online', 'offline', 'textInput',\n 'abort', 'close', 'dragdrop', 'load', 'paint', 'reset', 'select', 'submit', 'unload'\n ];\n\n function stopPropagation (e) {\n e.stopPropagation();\n // e.preventDefault(); // Stop for the form controls, etc., too?\n }\n for (i=0; i < handlers.length; i++) {\n window.addEventListener(handlers[i], function (e) {stopPropagation(e);}, true);\n }\n\n if (window.stop) {\n window.stop();\n }\n\n throw '';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the main header based on settings data in local store. | loadMainHeader() {
// Get site name and description from store
const siteName = model.getPostBySlug('site-name', 'settings'),
siteDescription = model.getPostBySlug('site-description', 'settings');
view.updateSiteName(siteName.content);
view.updateSiteDescription(siteDescription.content);
} | [
"function setMainHeaders(kapitel, gruppe, klasse) {\r\n\tsetKapitel(kapitel);\r\n\tsetGruppe(gruppe);\r\n\tsetKlasse(klasse);\r\n}",
"initLoad(){\n //Load Main config file\n var sectionData = '';\n\n if(typeof(this.section) == 'object'){\n var ObjKeys = Object.keys(this.section);\n if(ObjKeys.length > 0){\n if(this.section['params'] && Object.keys(this.section['params']).length > 0) this.extraPrms = this.section['params'];\n if(this.section['successCall']) this.successCallBack = this.section['successCall'];\n if(this.section['endpoint']) this.section = this.section['endpoint'];\n }\n }\n\n if(configArr[this.section]) sectionData = configArr[this.section];\n if(!sectionData) this.getResponse(false, {error: 'Unable to load configuration for selected page'});\n this.sectionObj = sectionData;\n }",
"function validateAndInitHeader(event) {\n vm.isAuth = TcAuthService.isAuthenticated()\n if (vm.isAuth) {\n initHeaderProps(event)\n } else {\n loadUser().then(function(token) {\n // update auth flag\n vm.isAuth = TcAuthService.isAuthenticated()\n initHeaderProps(event)\n }, function(error) {\n // do nothing, just show non logged in state of navigation bar\n })\n }\n }",
"function setNavData()\n{\n //Calling the appropriate function to load header and footer based on the title of the page\n if (document.title == \"BIOPAGE\" || document.title == \"CONTACT\" || document.title == \"PROJECTS\") \n {\n loadHeader();\n loadFooter(); \n } \n}",
"function loadSettingsPage() {\n refreshRunesButton = true; // Reset toggle when main page eventually reloads\n $('#main-container').load('./settings.html', () => {\n buildRuneSettingsTable();\n markCheckboxes();\n });\n }",
"update() {\r\n this.updateHeader();\r\n }",
"function formatHeader( str ) {\n var defaultInfo = ['title','author','version','date','description','dependancies','references'];\n var info = {\n title : undefined,\n author : undefined,\n version : undefined,\n date : undefined,\n description : undefined,\n dependancies : undefined,\n references : undefined\n },\n headerinfo = [];\n\n // go thru each line of header\n str.split(/\\|/).forEach( function( line, indx ) {\n\n // parse file attributes and store name + value ( will use markdown to handle links/emphasis )\n headerinfo = line.match(/@(.+?) *?: *?(.+)/);\n\n if ( headerinfo ) {\n info[headerinfo[1]] = cheapMarkdown( headerinfo[2] );\n }\n\n } );\n\n // use custom user formater\n if ( settings.header ) {\n str = settings.headerFormater( info );\n } else {\n // build special `html` for header info\n var sourceFile = '<small><a href=\"'+ settings.source +'\"><span class=\"glyphicon glyphicon-file\"></span></a></small>';\n var authorStr = ( info.author ) ? '<small> by '+info.author + '</small>' : '';\n var descriptionStr = ( info.description ) ? '<p class=\"lead\">'+info.description+'</p>' : '';\n var versionStr = ( info.version ) ? 'Version '+info.version : '';\n var dateStr = ( info.date ) ? ' from '+info.date : '';\n var dependanciesStr = ( info.dependancies ) ? 'Dependancies : '+info.dependancies : '';\n var referencesStr = ( info.references ) ? 'References : '+info.references : '';\n\n str = '<h1>' + sourceFile + info.title + authorStr + '</h1>' + descriptionStr + '<p>'+ versionStr + dateStr +'<br>'+ dependanciesStr + '<br>'+ referencesStr + '</p>';\n\n var usrStr = '';\n // look for other user custom fields\n for (var key in info) {\n if ( $.inArray( key, defaultInfo ) === -1 ) {\n usrStr += key[0].toUpperCase()+key.slice(1)+' : '+info[key]+'<br>';\n }\n }\n\n str += '<p>' + usrStr + '</p>' + '<hr>';\n }\n\n return str;\n }",
"function updateHeader(scope, control) {\n control.header = scope.header;\n if (typeof (scope.value) != 'undefined' && control.selectedItem && control.displayMemberPath) {\n var currentValue = control.selectedItem[control.displayMemberPath];\n if (currentValue != null) {\n control.header += ': <b>' + currentValue + '</b>';\n }\n }\n }",
"function load(def){\n\tif(!instrumentDefinitions.contains(def)){\n\t\treturn\n\t}\n\n\tinit();\n\n\tdefinition = instrumentDefinitions.get(def);\n\tdefinition = JSON.parse(definition.stringify());\n\n\n\t//set global variables\n\tinstName = definition[\"METADATA\"][\"instrumentName\"];\n\tinstLabel.sendbox(\"hidden\", 0);\n\tinstLabel.set(instName);\n\n\tnsLabel.sendbox(\"hidden\", 0);\n\tnsMenu.sendbox(\"hidden\", 0);\n\n\n\n\tauthName = definition[\"METADATA\"][\"author\"];\n\tauthLabel.sendbox(\"hidden\", 0);\n\tauthLabel.set(authName);\n\n\tnamespaces = definition[\"DATA\"][\"NAMESPACES\"];\n\n\tmetaDict.parse(JSON.stringify(definition[\"METADATA\"]))\n\tdataDict.parse(JSON.stringify(definition[\"DATA\"]))\n\ttracksDict.parse(JSON.stringify(definition[\"DATA\"][\"TRACKS\"]))\n\tinstDef.parse(JSON.stringify(definition));\n\n\tupdateNsMenu();\n\tupdateUmenu(numTracks(), trackIndexMenu);\n\n\tfunction updateNsMenu(){\n\t\tvar ns = new Dict();\n\t\tns.clear();\n\t\tns.parse(JSON.stringify(namespaces));\n\t\t\n\t\tvar keys = ns.getkeys();\n\t\tkeys = arrayCheck(keys);\n\n\t\tnsMenu.message(\"clear\");\n\n\t\tfor(var i = 0; i < keys.length; i++){\n\t\t\tnsMenu.message(\"append\", String(keys[i]));\n\t\t}\n\t}\n\n}",
"function mainHeaderContent() {\n var winHeight = $(window).innerHeight();\n\n // @screen width => 992px\n if ($(window).width() >= 992) {\n var mainHeaderContentMargin = -($('.main-header-content').height() / 2);\n\n $('.main-header-content').css('margin-top', mainHeaderContentMargin);\n }\n\n \t// @screen width => 768px and <= 991px\n \telse if ($(window).width() >= 768 && $(window).width() <= 991) {\n var headerContainerHeight = $('.main-header > .container').height();\n\n if ((winHeight - 100) <= headerContainerHeight) {\n $('.main-header > .container').css('margin', '110px 0 60px');\n }\n\n else {\n var headerContainerMargin = (50 + ((winHeight - 100) - headerContainerHeight)) / 2;\n\n $('.main-header > .container').css('margin-top', headerContainerMargin);\n }\n \t}\n\n \t// @screen width <= 767px\n \telse {\n var headerContainerHeight = $('.main-header > .container').height();\n\n if ((winHeight - 50) <= headerContainerHeight) {\n\n }\n\n else {\n var headerContainerMargin = (50 + (winHeight - headerContainerHeight)) / 2;\n\n $('.main-header > .container').css('margin-top', headerContainerMargin);\n }\n \t};\n }",
"function assignNavAndSidebarHeaders() {\n\t\t\t$(\"#area-blank1 h3\").text(sgeonames[0]);\n\t\t\t$(\"#left-sidebar h3\").text(sgeonames[0]+\" Projects by :\");\n\n\t\t $(\".area-blank\").css(\"display\", \"inline-block\");\n\t\t if (sgeonames[1]) {\n\t\t \t$(\"#area-blank2 h3\").text(sgeonames[1]);\n\t\t\t\t$(\"#right-sidebar h3\").text(sgeonames[1]+\" Projects by :\");\n\t\t \t$(\"#data-buttons\").css(\"display\", \"inline-block\");\n\t\t }\n\t\t}",
"function loadMainConfig() {\n return $http({\n method: 'Get',\n data: {},\n url: 'config.json',\n withCredentials: false\n })\n .then(transformResponse)\n .then(conf => {\n try {\n if (conf && conf.endpoints && conf.endpoints.mdx2json) {\n MDX2JSON = conf.endpoints.mdx2json.replace(/\\//ig, '').replace(/ /g, '');\n NAMESPACE = conf.namespace.replace(/\\//ig, '').replace(/ /g, '');\n }\n } catch (e) {\n console.error('Incorrect config in file \"config.json\"');\n }\n adjustEndpoints();\n })\n }",
"function loadTopbar() {\n loadSection(\"/Frontend/shared/topbar/topbar.html\")\n .then(html => {\n TOPBARCONTAINER.innerHTML = html;\n })\n .catch(error => {\n console.warn(error);\n });\n}",
"get header() {\n return (0, _polymerDom.dom)(this.$.headerSlot).getDistributedNodes()[0];\n }",
"_defaultHeaderRenderer() {\n if (!this.path) {\n return;\n }\n\n this.__setTextContent(this._headerCell._content, this._generateHeader(this.path));\n }",
"function load() {\n _data_id = m_data.load(FIRST_SCENE, load_cb, preloader_cb);\n}",
"function loadSettingsLoader(){\r\n commands.set('regularCommands',\"printAddOnSettings\",printAddonSettings);\r\n commands.set('regularCommands',\"clearAddOnSettings\",clearAddonSettings);\r\n settings = new function() {\r\n this.set = function(key, val) {\r\n GM_setValue(key,val); \r\n unsafeWindow.addMessage('', \"[\"+key+\": \"+val+\"] \", '', 'hashtext');\r\n };\r\n this.remove = function (key) { \r\n GM_deleteValue(key); \r\n };\r\n this.clear = function() {\r\n var keyArr = settings.getAll(),\r\n i;\r\n for(i = 0; i < keyArr.length;i++) {\r\n settings.remove(keyArr[i]);\r\n }\r\n };\r\n this.get = function(key, val) {\r\n if(GM_getValue(key) === undefined){\r\n settings.set(key,val);\r\n }\r\n return GM_getValue(key);\r\n };\r\n this.getAll = function() {\r\n return GM_listValues();\r\n };\r\n };\r\n}",
"function constructHeaderTbl() {\t\n\tprintHeadInnerTable = '<div class=\"page\"><table cellspacing=\"0\" class=\"printDeviceLogTable ContentTable\" style=\"font-size: 15px;height:45%;min-height:700px;max-height:780px;table-layout: fixed; width: 1100px;\" width=\"100%\">'\n\t\t+'<thead><tr><th rowspan=\"2\" width=\"50px\">Article</th>'\n\t\t+'<th rowspan=\"2\" width=\"5px\"></th>'\n\t\t+'<th rowspan=\"2\" class=\"columnDivider\">Description</th>'\n\t\t+'<th colspan=\"3\" class=\"centerValue columnDivider\">Last Received Details</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">OM</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"50px\">SOH</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"80px\">Units to Fill</th>'\n\t\t+'<th rowspan=\"2\" class=\"centerValue\" width=\"100px\">LTO</th>'\n\t\t+'<th rowspan=\"2\" class=\"lastColumn leftValue\" width=\"140px\">Comment</th>'\n\t\t+'</tr><tr class=\"subHeader\">'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Date</th>'\n\t\t+'<th class=\"centerValue columnDivider\" width=\"50px\">Qty.</th>'\n\t\t+'<th class=\"centerValue\" width=\"50px\">Order</th></tr></thead>';\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n}",
"function addHeader(report) {\n var pageHeader = report.getHeader();\n pageHeader.addClass(\"header\");\n if (param.company) {\n pageHeader.addParagraph(param.company, \"heading\");\n }\n pageHeader.addParagraph(\"VAT Report Transactions currency to CHF\", \"heading\");\n pageHeader.addParagraph(Banana.Converter.toLocaleDateFormat(param.startDate) + \" - \" + Banana.Converter.toLocaleDateFormat(param.endDate), \"\");\n pageHeader.addParagraph(\" \", \"\");\n pageHeader.addParagraph(\" \", \"\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
open a modal dialog for new flights | function addNewFlight() {
vm.newForm = 'n';
//var result = modalPopupFactory.openTemplate('md', { flightEdit: false, flight: {}, gates: vm.domain.gates, flights: vm.domain.flights }, ROOT + 'app/flight/flight.html', 'flight');
modalPopupFactory.openTemplate('md', { flightEdit: false, flight: {}, gates: vm.domain.gates, flights: vm.domain.flights }, ROOT + 'app/flight/flight.html', 'flight').then(function (result) {
if (result) {
vm.filterFlightsByGateId(vm.filterByGateId);
}
});
} | [
"function display_form(){\r\n $('#staticBackdrop').modal('show');\r\n}",
"function setupCreateNewPathwayButton() {\n var newItem;\n $(\"div[name='createNewPathway']\").click(function(){\n if ( newItem == undefined )\n newItem = \n\t\tcreateDialog(\"div.createPathway\", \n\t\t\t\t{position:[250,150], width: 700, height: 350, \n\t\t\t\ttitle: \"Create a New Pathway Analysis\"});\n $.get(\"pathway.jsp\", function(data){\n newItem.dialog(\"open\").html(data);\n\t\tcloseDialog(newItem);\n });\n });\n}",
"function show_add_new_location () {\n\t\t$(\"#modal_title_location\").html(\"Add New Location\");\n\t\t$(\"#location_id\").val(\"\");\n\t\t$(\"#location_name\").val(\"\");\n\t\t$(\"#location_place\").val(\"\");\n\t\t$(\"#location_building\").val(\"\");\n\t\t$(\"#location_floor\").val(\"\");\n\t\t$(\"#location_info\").html(\"\");\n\t\t$(\"#photo\").val(\"\");\n\t\t$(\"#active\").val(\"yes\");\n\t\t$(\"#action\").val(\"add_location\");\n\t\t$(\"select\").trigger(\"chosen:updated\");\n\t\t$(\"#modal_dialog_location\").modal(\"show\");\n\t}",
"function openCreateLayerModal() {\n layerManagementWidget.expanded = false; //Close the widget that opens the window so it won't be in the way.\n\n //Create the list of features and renderers that available to create a layer from.\n const featureOptions = projectFeatures.map( (feature) => {\n const elem = document.createElement(\"option\");\n elem.value = feature.name;\n elem.text = feature.name;\n return elem;\n });\n\n const layerSelect = document.getElementById(\"layer-feature-select\");\n layerSelect.replaceChildren(...featureOptions);\n layerSelect.appendChild(new Option(\"None\", false));\n\n const rendererOptions = projectRenderers.map( ( renderer ) => {\n const elem = document.createElement(\"option\");\n elem.value = renderer.name;\n elem.text = renderer.name;\n return elem;});\n\n const rendererSelect = document.getElementById(\"layer-renderer-select\");\n rendererSelect.replaceChildren(...rendererOptions);\n rendererSelect.appendChild(new Option(\"None\", false));\n\n //Open the window\n document.getElementById(\"create-layer-modal\").style.display = \"block\";\n }",
"function openModalNewResponsableMedicion() {\n\tabrirCerrarModal(\"modalAsignaPersonas\");\n\tsetFirstInput();\n}",
"function trailDetails(trailId) {\n let trailWidget = $(\"<div>\");\n trailWidget.html('<iframe style=\"width:100%; max-width:1200px; height:410px;\" frameborder=\"0\" scrolling=\"no\" src=\"https://www.mtbproject.com/widget?v=3&map=1&type=trail&id=' + trailId + '&z=6\"></iframe>')\n $(\".trailModal\").empty();\n $(\".trailModal\").append(trailWidget);\n $('#modal1').modal('open');\n}",
"function openTrackList() {\n\t\t$('#modal-wrapper').show(5, 'linear', function(){\n\t\t\t$('.track-list').addClass('open-track-list');\n\t\t});\n\t}",
"function displayDelete() {\n $('#modalDelete').modal('show');\n}",
"showAddExerciseDialog()\n {\n this.addDialog.MaterialDialog.show();\n this.addExerciseName.focus();\n }",
"function win() {\n modal.style.display = \"block\";\n}",
"function openNewAssessmentTechniqueModal () {\n\t'use strict';\n\n\t// reset form on new modal open\n\t$('#add-new-technique').find('input, select, textarea').val('');\n\t$('#dimImageModal')\n\t\t.prop('src', '../../images/content/knowDimNone.png')\n\t\t.prop('title', '');\n\n\t$('#techniqueId').val('');\n\t$('#learningDomain option[value=\"null\"]').attr('disabled', 'disabled');\n\t$('#domainCategory option[value=\"null\"]').attr('disabled', 'disabled');\n\t$('#add-new-technique').css('display', 'block');\n\t$('#topicDialogBackground').css('display', 'block');\n}",
"function openAssessmentPlanModal () {\n\t'use strict';\n\t$('#topicDialogBackground').css('display', 'block');\n\t$('#assessment-plan').css('display', 'block');\n}",
"function showDeviceManagerModal(){\n\t$modalDeviceManager = $('<div></div>')\n\t\t.html('<div id=\"deviceManagerContainer\"></p>')\n\t\t.dialog({\n\t\t\tautoOpen: false,\n\t\t\theight: 500,\n\t\t\twidth: 410,\n\t\t\ttitle: \"Device Manager\",\n\t\t\tmodal: true,\n\t\t\tresizable: false,\n\t\t\tbuttons: {\"close\": function() \t{\n\t\t\t\t\t\t\t\t\t\t\t\t$(this).dialog(\"close\");\n\t\t\t\t\t\t\t\t\t\t\t\tif (devicePanel) deviceManager.removePanel(devicePanel);\n\t\t\t\t\t\t\t\t\t\t\t}}\n\t\t});\n\n\t\t$modalDeviceManager.dialog('open');\n\t\t\n\t\tif (deviceManager == null) deviceManager = TB.initDeviceManager(thePartnerKey);\n\t\tif (publisher) devicePanel = deviceManager.displayPanel(\"deviceManagerContainer\", publisher);\n\t\telse devicePanel = deviceManager.displayPanel(\"deviceManagerContainer\");\n\n}",
"function show_city_dialog(pcity)\n{\n var turns_to_complete = FC_INFINITY;\n active_city = pcity;\n \n if (pcity == null) return;\n\n // reset dialog page.\n $(\"#city_dialog\").remove();\n $(\"<div id='city_dialog'></div>\").appendTo(\"div#game_page\");\n\n var city_data = {};\n\n $.ajax({\n url: \"/webclient/city.hbs?ts=\" + ts,\n dataType: \"html\",\n cache: true,\n async: false\n }).fail(function() {\n console.error(\"Unable to load city dialog template.\");\n }).done(function( data ) {\n var template=Handlebars.compile(data);\n $(\"#city_dialog\").html(template(city_data));\n });\n\n $(\"#city_canvas\").click(city_mapview_mouse_click);\n\n city_worklist_dialog(pcity);\n show_city_traderoutes();\n\n var dialog_buttons = {};\n if (!is_small_screen()) {\n dialog_buttons = $.extend(dialog_buttons, \n {\n \"Previous city\" : function() {\n previous_city();\n },\n \"Next city\" : function() {\n next_city();\n }\n });\n }\n\n dialog_buttons = $.extend(dialog_buttons, \n {\n \"Buy\" : function() {\n request_city_buy();\n },\n \"Rename\" : function() {\n rename_city();\n },\n \"Close\": function() {\n close_city_dialog();\n }\n });\n\n $(\"#city_dialog\").attr(\"title\", decodeURIComponent(pcity['name']));\n $(\"#city_dialog\").dialog({\n\t\t\tbgiframe: true,\n\t\t\tmodal: true,\n\t\t\twidth: is_small_screen() ? \"98%\" : \"80%\",\n close : function(){\n close_city_dialog();\n }, \n\t\t\tbuttons: dialog_buttons\n });\n\t\n $(\"#city_dialog\").dialog('open');\t\t\n $(\"#game_text_input\").blur();\n\n /* prepare city dialog for small screens. */\n if (!is_small_screen()) {\n $(\"#city_tabs-5\").remove();\n $(\"#city_tabs-6\").remove();\n $(\".extra_tabs_small\").remove();\n } else {\n $(\"#city_tabs-4\").remove();\n $(\".extra_tabs_big\").remove();\n var units_element = $(\"#city_improvements_panel\").detach();\n $('#city_units_tab').append(units_element);\n }\n\n $(\"#city_tabs\").tabs({ active: city_tab_index});\n\n set_city_mapview_active();\n center_tile_mapcanvas(city_tile(pcity));\n update_map_canvas(0, 0, mapview['store_width'], mapview['store_height']);\n\n $(\"#city_size\").html(\"Population: \" + numberWithCommas(city_population(pcity)*1000) + \"<br>\" \n + \"Size: \" + pcity['size'] + \"<br>\"\n + \"Granary: \" + pcity['food_stock'] + \"/\" + pcity['granary_size'] + \"<br>\"\n + \"Change in: \" + city_turns_to_growth_text(pcity));\n \n if (pcity['production_kind'] == VUT_UTYPE) {\n var punit_type = unit_types[pcity['production_value']];\n $(\"#city_production_overview\").html(\"Producing: \" + punit_type['name']); \n turns_to_complete = city_turns_to_build(pcity, punit_type, true); \n }\n\n if (pcity['production_kind'] == VUT_IMPROVEMENT) {\n var improvement = improvements[pcity['production_value']];\n $(\"#city_production_overview\").html(\"Producing: \" + improvement['name']);\n turns_to_complete = city_turns_to_build(pcity, improvement, true);\n if (improvement['name'] == \"Coinage\") {\n turns_to_complete = FC_INFINITY;\n }\n }\n if (turns_to_complete != FC_INFINITY) {\n $(\"#city_production_turns_overview\").html(\"Turns to completion: \" + turns_to_complete);\n } else {\n $(\"#city_production_turns_overview\").html(\"-\");\n }\n \n var improvements_html = \"\";\n for (var z = 0; z < pcity['improvements'].length; z ++) {\n if (pcity['improvements'][z] == 1) {\n var sprite = get_improvement_image_sprite(improvements[z]);\n if (sprite == null) {\n console.log(\"Missing sprite for improvement \" + z);\n continue;\n }\n \n improvements_html = improvements_html +\n \"<div id='city_improvement_element'><div style='background: transparent url(\" \n + sprite['image-src'] +\n \");background-position:-\" + sprite['tileset-x'] + \"px -\" + sprite['tileset-y'] \n + \"px; width: \" + sprite['width'] + \"px;height: \" + sprite['height'] + \"px;float:left; '\"\n + \"title=\\\"\" + improvements[z]['helptext'] + \"\\\" \" \n\t + \"onclick='city_sell_improvement(\" + z + \");'>\"\n +\"</div>\" + improvements[z]['name'] + \"</div>\";\n }\n }\n $(\"#city_improvements_list\").html(improvements_html);\n \n var punits = tile_units(city_tile(pcity));\n if (punits != null) {\n var present_units_html = \"\";\n for (var r = 0; r < punits.length; r++) {\n var punit = punits[r];\n var ptype = unit_type(punit); \n var sprite = get_unit_image_sprite(punit);\n if (sprite == null) {\n console.log(\"Missing sprite for \" + punit);\n continue;\n }\n \n present_units_html = present_units_html +\n \"<div id='game_unit_list_item' style='cursor:pointer;cursor:hand; background: transparent url(\" \n + sprite['image-src'] +\n \");background-position:-\" + sprite['tileset-x'] + \"px -\" + sprite['tileset-y'] \n + \"px; width: \" + sprite['width'] + \"px;height: \" + sprite['height'] + \"px;float:left; '\"\n + \" onclick='city_dialog_activate_unit(units[\" + punit['id'] + \"]);'\"\n +\"></div>\";\n }\n $(\"#city_present_units_list\").html(present_units_html);\n }\n\n var sunits = get_supported_units(pcity);\n if (sunits != null) {\n var supported_units_html = \"\";\n for (var r = 0; r < sunits.length; r++) {\n var punit = sunits[r];\n var ptype = unit_type(punit); \n var sprite = get_unit_image_sprite(punit);\n if (sprite == null) {\n console.log(\"Missing sprite for \" + punit);\n continue;\n }\n \n supported_units_html = supported_units_html +\n \"<div id='game_unit_list_item' style='cursor:pointer;cursor:hand; background: transparent url(\" \n + sprite['image-src'] +\n \");background-position:-\" + sprite['tileset-x'] + \"px -\" + sprite['tileset-y'] \n + \"px; width: \" + sprite['width'] + \"px;height: \" + sprite['height'] + \"px;float:left; '\"\n + \" onclick='city_dialog_activate_unit(units[\" + punit['id'] + \"]);'\"\n +\"></div>\";\n }\n $(\"#city_supported_units_list\").html(supported_units_html);\n }\n\n\n $(\"#city_food\").html(pcity['prod'][0]);\n $(\"#city_prod\").html(pcity['prod'][1]);\n $(\"#city_trade\").html(pcity['prod'][2]);\n $(\"#city_gold\").html(pcity['prod'][3]);\n $(\"#city_luxury\").html(pcity['prod'][4]);\n $(\"#city_science\").html(pcity['prod'][5]);\n\n $(\"#city_corruption\").html(pcity['waste'][O_TRADE]);\n $(\"#city_waste\").html(pcity['waste'][O_SHIELD]);\n $(\"#city_pollution\").html(pcity['pollution']);\n\n /* Handle citizens and specialists */\n var specialist_html = \"\";\n var citizen_types = [\"angry\", \"unhappy\", \"content\", \"happy\"];\n for (var s = 0; s < citizen_types.length; s++) {\n for (var i = 0; i < pcity['ppl_' + citizen_types[s]][FEELING_FINAL]; i ++) {\n var sprite = get_specialist_image_sprite(\"citizen.\" + citizen_types[s] + \"_\" \n + (i % 2));\n specialist_html = specialist_html +\n \"<div class='specialist_item' style='background: transparent url(\" \n + sprite['image-src'] +\n \");background-position:-\" + sprite['tileset-x'] + \"px -\" + sprite['tileset-y'] \n + \"px; width: \" + sprite['width'] + \"px;height: \" + sprite['height'] + \"px;float:left; '\"\n +\" title='One \" + citizen_types[s] + \" citizen'></div>\";\n }\n }\n\n for (var i = 0; i < pcity['specialists_size']; i++) {\n var spec_type_name = specialists[i]['plural_name'];\n var spec_gfx_key = \"specialist.\" + specialists[i]['rule_name'] + \"_0\";\n for (var s = 0; s < pcity['specialists'][i]; s++) {\n var sprite = get_specialist_image_sprite(spec_gfx_key);\n specialist_html = specialist_html +\n \"<div class='specialist_item' style='cursor:pointer;cursor:hand; background: transparent url(\" \n + sprite['image-src'] +\n \");background-position:-\" + sprite['tileset-x'] + \"px -\" + sprite['tileset-y'] \n + \"px; width: \" + sprite['width'] + \"px;height: \" + sprite['height'] + \"px;float:left; '\"\n + \" onclick='city_change_specialist(\" + pcity['id'] + \",\" + specialists[i]['id'] + \");'\"\n +\" title='\" + spec_type_name + \" (click to change)'></div>\";\n\n }\n }\n specialist_html += \"<div style='clear: both;'></div>\";\n $(\"#specialist_panel\").html(specialist_html);\n\n $('#disbandable_city').off();\n $('#disbandable_city').prop('checked', pcity['disbandable_city']);\n $('#disbandable_city').click(function() {\n var packet = {\"pid\" : packet_city_disbandable_req, \"city_id\" : active_city['id']};\n send_request(JSON.stringify(packet));\n city_tab_index = 3;\n });\n\n city_tab_index = 0;\n\n if (is_small_screen()) {\n $(\".ui-tabs-anchor\").css(\"padding\", \"2px\");\n }\n}",
"function ShowDialog() {\n try {\n var options =\n {\n autoSize: true,\n allowMaximize: true,\n title: 'Version History',\n showClose: true,\n url: _spPageContextInfo.webAbsoluteUrl + '/_layouts/15/Versions.aspx?list=' + _spPageContextInfo.listId + '&ID=' + GetUrlKeyValue('ID') + '&Source=' + _spPageContextInfo.webServerRelativeUrl + '/Lists/' + _spPageContextInfo.listTitle + '/AllItems.aspx',\n };\n SP.UI.ModalDialog.showModalDialog(options);\n }\n catch (e) {\n console.log(e);\n }\n}",
"function openClientMeetingForm() {\n\n document.getElementById(\"ClientMeetingForm\").style.display = \"block\";\n\n //populate list of clients.\n populateClientList(\"clientAtMeeting\");\n\n}",
"function showInstructions()\n{\n $(\"#instructions_modal\").modal();\n}",
"function open_add_ntf_modal() {\n $(\"#resModal\").modal(\"show\");\n $(\"#resContent\").html(\"\");\n $(\"#resSpan\").html(\"\");\n $(\"#resTitle\").html(\"Add New Notification\");\n var add_ntf_html = \"<form name=\\\"add_ntf_form\\\" id=\\\"add_ntf_form\\\">\"\n + \"<label class=\\\"w3-text-teal w3-text-theme\\\">Notification Text \"\n + \"<span class=\\\"w3-text-red\\\" title=\\\"Required Field\\\">*</span></label>\"\n + \"<input id=\\\"ntf_text\\\" name=\\\"ntf_text\\\" class=\\\"w3-input w3-white \"\n + \"w3-round w3-border w3-padding w3-text-theme\\\" type=\\\"text\\\" \"\n + \"placeholder=\\\"Notification text\\\" required=\\\"required\\\" maxlength=\\\"500\\\"\"\n + \" minlength=\\\"3\\\"><div class=\\\"w3-padding\\\"></div>\"\n + \"<label class=\\\"w3-text-teal w3-text-theme\\\">Notification Link </label>\"\n + \"<input class=\\\"w3-input w3-white w3-round w3-border w3-padding w3-text-theme\\\"\"\n + \" placeholder=\\\"Notification Link (Optional)\\\" name=\\\"ntf_link\\\" id=\\\"ntf_link\\\"\"\n + \" maxlength=\\\"1024\\\" type=\\\"text\\\" /><hr style=\\\"margin-bottom:8px;\\\">\"\n + \"<input type=\\\"hidden\\\" value=\\\"1\\\" name=\\\"actionType\\\">\"\n + \"<button type=\\\"submit\\\" id=\\\"ntfAddSubmit\\\" name=\\\"ntfAddSubmit\\\"\"\n + \"onclick=\\\"return add_notification();\\\" \"\n + \"class=\\\"w3-btn w3-block w3-theme w3-round\\\">Submit</button></form>\";\n $(\"#resContent\").html(add_ntf_html);\n}",
"function Dialog() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if two sets of coordinates are adjacent. | function isAdjacent(x1, y1, x2, y2) {
var dx = Math.abs(x1 - x2);
var dy = Math.abs(y1 - y2);
return (dx + dy === 1);
} | [
"function areAdjacent(squareOne, squareTwo) { \n if (squareOne.x < squareTwo.x + 2 &&\n squareOne.x > squareTwo.x - 2 &&\n squareOne.y < squareTwo.y + 2 &&\n squareOne.y > squareTwo.y - 2) {\n return true;\n } else {\n return false;\n }\n}",
"adjacent(xVertex, yVertex) {\n let adjacentExist = false;\n let edge;\n for(edge of this.adjacencyList[xVertex]){\n if(edge.getToVertex() === yVertex) {\n adjacentExist = true;\n break;\n }\n }\n return adjacentExist;\n }",
"areDiagonallyAdjacent(tile1, tile2) {\r\n // Dos tiles son diagonalmente adyacentes si están separados por una distancia de una\r\n // unidad en ambos ejes. Si la distancia en cualquiera de los ejes fuera 0 ya no sería\r\n // una adyacencia diagonal, y si la distancia fuera más de 1 ya no sería una adyacencia.\r\n return Math.abs(tile1.x - tile2.x) == 1 && Math.abs(tile1.y - tile2.y) == 1;\r\n }",
"isAdjacent(node) {\n console.log(this.adjacents.indexOf(node) > -1);\n return this.adjacents.indexOf(node) > -1;\n }",
"isConnected(node1, node2) {\r\n for (let index = 0; index < this.edgeList.length; index++) {\r\n if ((this.edgeList[index].startNode === node1 &&\r\n this.edgeList[index].endNode === node2) ||\r\n (this.edgeList[index].endNode === node1 &&\r\n this.edgeList[index].startNode === node2)) {\r\n return true;\r\n }\r\n\r\n }\r\n return false;\r\n }",
"function isNeighbors(tile1, tile2) {\r\n\t\tvar left1 = parseInt(window.getComputedStyle(tile1).left);\r\n\t\tvar top1 = parseInt(window.getComputedStyle(tile1).top);\r\n\t\tvar left2 = parseInt(window.getComputedStyle(tile2).left);\r\n\t\tvar top2 = parseInt(window.getComputedStyle(tile2).top);\r\n\t\tif (Math.abs(left1 + top1 - left2 - top2) == 100) {\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}",
"function checkAdjacentTiles(x1, y1) {\n if((x1>=0)&&(y1>=0)&&(x1<columns)&&(y1<rows)) //Verify if coordinates do not fall outside of the gridMatrix.\n return gridMatrix[x1+y1*columns];\n}",
"function overlaps(a, b) {\n if (a.x1 >= b.xMax || a.y1 >= b.yMax || a.x2 <= b.xMin || a.y2 <= b.yMin) {\n return false\n } else {\n return true\n }\n }",
"oppositeColors(x1,y1,x2,y2){\r\n if(this.getColor(x1,y1) !== 0 && this.getColor(x2,y2) !== 0 && this.getColor(x1,y1) !== this.getColor(x2,y2)){\r\n return true;\r\n }\r\n return false;\r\n }",
"oppositeMoves(m1, m2) {\n return (\n !!m1 &&\n !(ChessRules.PIECES.includes(m2.appear[0].p)) &&\n m2.vanish.length == 1 &&\n !m2.end.released &&\n m1.start.x == m2.end.x &&\n m1.end.x == m2.start.x &&\n m1.start.y == m2.end.y &&\n m1.end.y == m2.start.y\n );\n }",
"function canSwap(x1,y1,x2,y2) {\n\t\t\tvar type1 = getJewel(x1,y1),\n\t\t\t type2 = getJewel(x2,y2),\n\t\t\tchain;\n\n\n\t\t\tif(!isAdjacent(x1, y1, x2, y2)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// temporarily swap jewels\n\t\t\tjewels[x1][y1] = type2;\n\t\t\tjewels[x2][y2] = type1;\n\n\t\t\tchain = (checkChain(x2, y2) > 2 ||\n\t\t\t\t checkChain(x1, y1) > 2);\n\n\t\t\t//swap back\n\t\t\tjewels[x1][y1] = type1;\n\t\t\tjewels[x2][y2] = type2;\n\n\t\t\treturn chain;\n\t\t}//end of canSwap()",
"function isequal(o1, o2) {\n\t if (o1.x == o2.x && o1.y == o2.y && o1.w == o2.w && o1.h == o2.h) return true;\n\t return false;\n\t }",
"hasIdenticalEndPoints(tileArr1,tileArr2){\n return (tileArr1.filter(endPoint=>{\n return tileArr2.indexOf(endPoint)!=-1;\n }).length>0);\n }",
"static eq(oldSets, newSets, from = 0, to) {\n if (to == null) to = 1000000000 /* C.Far */ - 1\n let a = oldSets.filter(\n (set) => !set.isEmpty && newSets.indexOf(set) < 0\n )\n let b = newSets.filter(\n (set) => !set.isEmpty && oldSets.indexOf(set) < 0\n )\n if (a.length != b.length) return false\n if (!a.length) return true\n let sharedChunks = findSharedChunks(a, b)\n let sideA = new SpanCursor(a, sharedChunks, 0).goto(from),\n sideB = new SpanCursor(b, sharedChunks, 0).goto(from)\n for (;;) {\n if (\n sideA.to != sideB.to ||\n !sameValues(sideA.active, sideB.active) ||\n (sideA.point && (!sideB.point || !sideA.point.eq(sideB.point)))\n )\n return false\n if (sideA.to > to) return true\n sideA.next()\n sideB.next()\n }\n }",
"function dist(distance, x1, y1, x2, y2) {\n if(Math.abs(x1-x2) === distance && y1 === y2 || x1 === x2 && Math.abs(y1-y2) === distance) {\n return true;\n }\n else {\n return false;\n }\n \n}",
"function equalBoxes(bb1, bb2){\n\treturn (bb1.min.x == bb2.min.x &&\n\t\tbb1.min.y == bb2.min.y && bb1.max.x == bb2.max.x &&\n\t\tbb1.max.y == bb2.max.y);\n}",
"function isDestination(x, y, dest) {\n if (x == dest.x && y == dest.y) {\n return true;\n }\n\n else {\n return false;\n }\n}",
"function canSwap(x1, y1, x2, y2) {\n var type1 = getJewel(x1, y2);\n var type2 = getJewel(x2, y2);\n var chain;\n\n // Are positions adjacent?\n if (!isAdjacent(x1, y1, x2, y2)) {\n return false;\n }\n\n // temporarily swap positions\n jewels[x1][y1] = type2;\n jewels[x2][y2] = type1;\n\n // Check that new chain lengths would \n // valid.\n chain = (checkChain(x2, y2) > 2\n || checkChain(x1, y1) > 2);\n\n // Return to original positions.\n jewels[x1][y1] = type1;\n jewels[x2][y2] = type2;\n\n return chain;\n }",
"pointsEqual(p1, p2) {\n return GeoPlus.distance(p1, p2) <= this.tolerance;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adding given job to the database | function addJobToDB(job){
return new Promise(function (resolve, reject) {
eRequest.patch({
headers: {'content-type': 'application/json'},
url: buildFirebaseURL(job.name),
body: job
}, function (error, response, body) {
res.send("success");
resolve("done");
});
});
} | [
"function addJob(jobid, userid, status, desc)\n{\n globalJobList.push({ \"Ownerid\" : userid,\n \"SubmitAddr\" : \"-\",\n \"Desc\" : desc,\n \"Taskid\" : jobid,\n \"Status\" : status,\n \"Age\" : 0,\n \"Starttime\" : Date.now(),\n \"Endtime\" : 0,\n \"ResCode\" : \"\",\n \"TrmCode\" : \"\",\n });\n globalJobBits.push(jobDefaultBits);\n}",
"function addJobRow(data)\n{\n var node = document.getElementById(\"jobs-table-body\");\n addJobRowAt(node,data);\n}",
"function addToQueue(ticket) {\n MongoClient.connect(mongodb_url, function(err, db) {\n if (err) {\n console.log('Error: ' + err);\n }\n else {\n db.collection('grocery_queue').insert(ticket, function(err, doc) {\n if (err) {\n console.log('Error inserting to db');\n }\n console.log('Inserted: ' + doc + ' to queue');\n });\n }\n });\n}",
"function recordJob(website, id, method, job_id) {\n //Dev bypass, will not log jobs as no key found.\n if (setup.api_dev_mode === true) {\n return;\n }\n\n API.findById(id, function (err, info) {\n if (err || !info) {\n logger.warn(\"Failed to add job ID to API key, API key not found\");\n return;\n } else {\n //log job\n info.associated_job_ids.push(website + \"/\" + method + \"/\" + job_id);\n info.save();\n }\n });\n}",
"insert(task, date, process) {\n let sql = `\n INSERT INTO tasks(task, date, process)\n VALUES (?, ?, ?)\n `;\n return this.dao.run(sql, [task, date, process]);\n }",
"function addTask(){\n var priority = program.priority || 1;\n var name = parseArgs();\n\n // TODO: create new instance of your ToDoItem model (call it task) and\n // set name, priority, and completed.\n\n // YOUR CODE HERE\n var task = new ToDoItem({\n name: name,\n priority: priority,\n completed: false\n });\n\n // TODO: Use mongoose's save function to save task (the new instance of\n // your model that you created above). In the callback function\n // you should close the mongoose connection to the database at the end\n // using \"mongoose.connection.close();\"\n\n // YOUR CODE HERE\n task.save(function (err, task) {\n if (err) return console.error(err);\n console.log(\"Added task named: \"+ task.name + \", and priority: \" + task.priority);\n mongoose.connection.close();\n });\n}",
"async function addWork(_work) {\n const new_work = new Work({\n work: _work.work,\n });\n return await new_work.save();\n}",
"saveJob(item) {\n this.props.sendJobToRedux(item);\n alert('Posting added to your Saved Jobs!')\n }",
"saveGoal(data) {\n let goal = this.get('store').createRecord('goal', data);\n goal.save()\n }",
"handleAddJobClick(job) {\n // console.log('handleAddJobClick job: '+JSON.stringify(job))\n let newState = this.state.jobs.concat(job);\n this.setState({ jobs: newState })\n }",
"async function registerPredictionModelJobTx(tx, context, modelId, jobId) {\n shares.enforceEntityPermissionTx(tx, context, 'job', jobId, 'edit');\n shares.enforceEntityPermissionTx(tx, context, 'prediction', modelId, 'edit');\n\n const predJob = {\n prediction: modelId,\n job: jobId\n };\n\n await tx('predictions_jobs').insert(predJob);\n await _rebuildOuputOwnership(tx, context, modelId);\n}",
"function insertContent(params, cb) {\n var database = params.db;\n database.collection('jobs').insertOne({\n \"_id\": params.id,\n \"content\": params.content\n },function(err, result) {\n if(err) {\n return cb(err);\n }\n cb(err, result);\n });\n}",
"function createChiefComplaintEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO chief_complaint (patient, assessed, primary_complaint, primary_other, secondary_complaint, diff_breathing, chest_pain, nausea, vomiting, diarrhea, dizziness, ' +\r\n\t\t\t\t' headache, loc, numb_tingling, gal_weakness, lethargy, neck_pain, time) ' +\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '', '', '', '', '', '', '', '', '', '', '', '', '', getSystemTime()], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}",
"function saveVmpsJobs() {\n\n var data = {};\n if ($('#name').val() == '') {\n $(\"#errLabel\").html(' Please enter job name')\n return false;\n }\n if ($('#platforms').val() == null) {\n $(\"#errLabel\").html(' Please select platform(s)')\n return false;\n }\n if ($('#gitTag').val() == '') {\n $(\"#errLabel\").html(' Please enter Git Tag name or SHA Id')\n return false;\n }\n if($('#jobSel').val() == null) {\n $(\"#errLabel\").html(' Please Select any Jobs');\n return false;\n }\n $(\"#errLabel\").html('');\n \n var unitData = {};\n\n if($('#id').val() != '') unitData['id'] = $('#id').val();\n unitData[\"name\"] = $('#name').val();\n unitData[\"Tests\"] = $('#jobSel').val();\n unitData[\"platforms\"] = $('#platforms').val();\n unitData[\"subscribers\"] = $('#subscribers').val();\n unitData[\"server\"] = $('#server').val();\n unitData[\"tagname\"] = $('#gitTag').val();\n unitData[\"test_type\"] = \"recurring\";\n unitData[\"mode\"] = $('input[type=\"radio\"][name=\"case\"]:checked').val();\n\n // For running the task\n $('#edit').attr(\"disabled\", \"disabled\");\n\n saveJob(unitData, function(jobId) {\n $(\"#errLabel\").html(' Job Created Successfully !!')\n $(\"#inputForm\").fadeOut(\"slow\");\n clearVmps();\n $('#add').show();\n $('#edit').removeAttr(\"disabled\");\n \n displayVmps();\n });\n}",
"async function addSchedule(ctx) {\n const { usernamect, availdate} = ctx.params;\n try {\n const sqlQuery = `INSERT INTO parttime_schedules VALUES ('${usernamect}', '${availdate}')`;\n await pool.query(sqlQuery);\n ctx.body = {\n 'username_caretaker': usernamect,\n 'availdate': availdate\n };\n } catch (e) {\n console.log(e);\n ctx.status = 403;\n }\n}",
"function save_task(doc, db, cb) {\n //store new data to our mLab DB\n db\n .collection('Tasks')\n .insertOne(doc, function (err, res) {\n if (err) return cb(err);\n\n console.log(`Successfully saved ${doc.description} task!`);\n\n cb(null);\n });\n}",
"function saveRecord(record) {\n const transaction = db.transaction([\"pending\"], \"readwrite\");\n \n // object store for pending db data to be accessed\n const store = transaction.objectStore(\"pending\");\n console.log(\"store\")\n // adds the record with the store\n store.add(record);\n }",
"function addTask(e) {\n // fetch the current value input in task box\n lkj('In addTask() Event');\n\n let task = {\n description: submitTaskBox.value,\n status: 0\n }\n lkj(task);\n\n currentTaskList.push(task);\n displaycurrentTaskList();\n\n updateLocalStorage();\n displayLocalStorage(); \n\n // alert('Task saved');\n\n //creating task on the HTML Page\n createTask(task);\n}",
"insert(user,content,completed,callback){\n this.connection.query(\"insert into task (userTask,taskText,completed) values ('\"+user+\"','\"+content+\"','\"+completed+\"')\", function(err,task){\n if(err){\n callback(err);\n }else{\n callback(null,task);\n }\n });\n }",
"function addPersonToSQL(name, classroom) {\n\tvar options = {\n\t\thostname: 'trap.euclidsoftware.com',\n\t\tpath: '/person/',\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'X-Trap-Token': X_Trap_Token\n\t\t}\n\t};\n\tvar data = '';\n\tvar req = http.request(options, function(res) {\n\t\tres.on('data', function(chunk) {\n\t\t\tdata += chunk;\n\t\t});\n\t\tres.on('end', function() {\n\t\t\tvar id = JSON.parse(data).id;\n\t\t\tputPerson(id, name, classroom);\n\t\t\tconsole.log(\"Added user \"+name+\" to class \"+classroom+\" with id \"+id)\n\t\t});\n\t});\n\treq.end();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This middleware modifies the input on S3 CreateBucket requests. If the LocationConstraint has not been set, this middleware will set a LocationConstraint to match the configured region. The CreateBucketConfiguration will be removed entirely on requests to the useast1 region. | function locationConstraintMiddleware(options) {
var _this = this;
return function (next) { return function (args) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
var CreateBucketConfiguration, region;
return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
switch (_a.label) {
case 0:
CreateBucketConfiguration = args.input.CreateBucketConfiguration;
return [4 /*yield*/, options.region()];
case 1:
region = _a.sent();
if (!CreateBucketConfiguration || !CreateBucketConfiguration.LocationConstraint) {
args = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, args), { input: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, args.input), { CreateBucketConfiguration: region === "us-east-1" ? undefined : { LocationConstraint: region } }) });
}
return [2 /*return*/, next(args)];
}
});
}); }; };
} | [
"function createBucket(bucketName, _callback){\n\n storage\n .createBucket(bucketName, {\n location: 'us-central1',\n storageClass: 'Regional',\n })\n .then(results => {\n console.log(`Bucket ${bucketName} created`);\n _callback(bucketName);\n })\n\n .catch(err => {\n console.error('ERROR:', err);\n });\n}",
"static async createBucketIfNotExists(bucketName) {\n var s3 = new AWS.S3();\n try {\n await s3.headBucket({ Bucket: bucketName }).promise();\n } catch (e) {\n if (e.statusCode != 404) throw e;\n // If HTTP status code is 404, S3 bucket does not exist\n console.log(\"Creating S3 bucket '%s'\", bucketName);\n await s3.createBucket({ Bucket: bucketName }).promise();\n }\n }",
"constructor(accessKey, secretKey, region, bucket, callback) {\n\t\tthis._s3 = null;\n\t\tthis._bucket = bucket;\n\t\tlet scriptTag = document.createElement('script');\n\t\tscriptTag.src = 'aws-sdk.min.js';\n\t\tscriptTag.onload = function () {\n\t\t\tAWS.config.update({\n\t\t\t\taccessKeyId: accessKey,\n\t\t\t\tsecretAccessKey: secretKey,\n\t\t\t\tregion: region\n\t\t\t});\n\t\t\tthis._s3 = new AWS.S3();\n\t\t\tcallback();\n\t\t}.bind(this);\n\t\tdocument.body.appendChild(scriptTag);\n\t}",
"function moveRegionToPosition(region, anchorPoint) {\n return (0, _merge[\"default\"])({}, region, {\n left: anchorPoint.x,\n top: anchorPoint.y,\n width: region.width,\n height: region.height\n });\n}",
"function createS3(){\n\treturn s3.createBucket({\n\t\tBucket: CONFIG.s3_image_bucket,\n\t}).promise().catch(err => {\n\t\tif (err.code !== \"BucketAlreadyOwnedByYou\") throw err\n\t})\n}",
"function cfnMultiRegionAccessPointRegionPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnMultiRegionAccessPoint_RegionPropertyValidator(properties).assertSuccess();\n return {\n Bucket: cdk.stringToCloudFormation(properties.bucket),\n BucketAccountId: cdk.stringToCloudFormation(properties.bucketAccountId),\n };\n}",
"get awsRegion() { return this.env.AWS_REGION }",
"function BucketPolicy(props) {\n return __assign({ Type: 'AWS::S3::BucketPolicy' }, props);\n }",
"function Bucket(props) {\n return __assign({ Type: 'AWS::S3::Bucket' }, props);\n }",
"function create(accessKeyId, secretAccessKey) {\n config.accessKeyId = accessKeyId;\n config.secretAccessKey = secretAccessKey;\n\n AWS.config.update(config);\n AWS.config.region = window.AWS_EC2_REGION;\n AWS.config.apiVersions = {\n cloudwatch: '2010-08-01',\n sqs: '2012-11-05'\n };\n\n cloudWatch = new AWS.CloudWatch();\n autoScaling = new AWS.AutoScaling();\n sqs = new AWS.SQS();\n }",
"function region_delete() {\n // populate_segments();\n }",
"function getS3Bucket(awsConfig) {\n // set the Amazon Cognito region\n AWS.config.region = awsConfig.awsCognitoRegion;\n // initialize the Credentials object with our parameters\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId: awsConfig.cognitoIdentityPoolId\n });\n\n // get identity ID and update credentials\n AWS.config.credentials.get(function(err) {\n if (err) {\n console.log(\"Error: \" + err);\n return;\n } else {\n console.log(\"Cognito Identity Id: \" + AWS.config.credentials.identityId);\n AWS.config.update({\n credentials: AWS.config.credentials.identityId\n });\n }\n });\n\n // create the s3 bucket locally\n var s3 = new AWS.S3();\n var bucketName = awsConfig.awsBucketName;\n var bucket = new AWS.S3({\n params: {\n Bucket: bucketName\n }\n });\n\n return bucket;\n}",
"deleteRequest() {\n let operation = {\n 'api': 'DeleteBucket',\n 'method': 'DELETE',\n 'uri': '/<bucket-name>',\n 'params': {\n },\n 'headers': {\n 'Host': this.properties.zone + '.' + this.config.host,\n },\n 'elements': {\n },\n 'properties': this.properties,\n 'body': undefined\n };\n this.deleteValidate(operation);\n return new Request(this.config, operation).build();\n }",
"function CfnStorageLens_S3BucketDestinationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('accountId', cdk.requiredValidator)(properties.accountId));\n errors.collect(cdk.propertyValidator('accountId', cdk.validateString)(properties.accountId));\n errors.collect(cdk.propertyValidator('arn', cdk.requiredValidator)(properties.arn));\n errors.collect(cdk.propertyValidator('arn', cdk.validateString)(properties.arn));\n errors.collect(cdk.propertyValidator('encryption', CfnStorageLens_EncryptionPropertyValidator)(properties.encryption));\n errors.collect(cdk.propertyValidator('format', cdk.requiredValidator)(properties.format));\n errors.collect(cdk.propertyValidator('format', cdk.validateString)(properties.format));\n errors.collect(cdk.propertyValidator('outputSchemaVersion', cdk.requiredValidator)(properties.outputSchemaVersion));\n errors.collect(cdk.propertyValidator('outputSchemaVersion', cdk.validateString)(properties.outputSchemaVersion));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n return errors.wrap('supplied properties not correct for \"S3BucketDestinationProperty\"');\n}",
"function cfnStorageLensS3BucketDestinationPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnStorageLens_S3BucketDestinationPropertyValidator(properties).assertSuccess();\n return {\n AccountId: cdk.stringToCloudFormation(properties.accountId),\n Arn: cdk.stringToCloudFormation(properties.arn),\n Encryption: cfnStorageLensEncryptionPropertyToCloudFormation(properties.encryption),\n Format: cdk.stringToCloudFormation(properties.format),\n OutputSchemaVersion: cdk.stringToCloudFormation(properties.outputSchemaVersion),\n Prefix: cdk.stringToCloudFormation(properties.prefix),\n };\n}",
"function changeRegion(array, index, region) {\n array[index].region = region;\n return array\n}",
"function insertCity(collection, place, lon, lat, next) {\n\n clean(place, false, function(err, names) {\n if (err) return next(err);\n var mDoc = {};\n var loc = {};\n var name = [];\n var container = [];\n var cd = [];\n if (names.length > 1) container[0] = names[1];\n cd[0] = parseFloat(lon);\n cd[1] = parseFloat(lat);\n name.push(names[0]); \n Object.defineProperty(mDoc, \"political\", {value: \"CITY\", \n enumerable: true, writable: true, configurable: true});\n Object.defineProperty(mDoc, \"containers\", {value: container, \n enumerable: true, writable: true, configurable: true});\n Object.defineProperty(loc, \"type\", {value: \"Point\", \n enumerable: true, writable: true, configurable: true});\n Object.defineProperty(loc, \"coordinates\", \n {value: cd, enumerable: true, writable: true, \n configurable: true});\n Object.defineProperty(mDoc, \"loc\", {value: loc, \n enumerable: true, writable: true, configurable: true});\n Object.defineProperty(mDoc, \"filePath\", {value: null, \n enumerable: true, writable: true, configurable: true});\n Object.defineProperty(mDoc, \"names\", {value: name, \n enumerable: true, writable: true, configurable: true});\n // TODO: need to make an upsert\n collection.update({\"names\": name[0], \"containers\": container[0]},\n function(err, doc){\n if(err) return next(err);\n next(null, doc);\n });\n });\n}",
"deleteCORSRequest() {\n let operation = {\n 'api': 'DeleteBucketCORS',\n 'method': 'DELETE',\n 'uri': '/<bucket-name>?cors',\n 'params': {\n },\n 'headers': {\n 'Host': this.properties.zone + '.' + this.config.host,\n },\n 'elements': {\n },\n 'properties': this.properties,\n 'body': undefined\n };\n this.deleteCORSValidate(operation);\n return new Request(this.config, operation).build();\n }",
"function createMultipartUpload (req, res, next) {\n // @ts-ignore The `companion` property is added by middleware before reaching here.\n const client = req.companion.s3Client\n const key = config.getKey(req, req.body.filename)\n const { type, metadata } = req.body\n if (typeof key !== 'string') {\n return res.status(500).json({ error: 's3: filename returned from `getKey` must be a string' })\n }\n if (typeof type !== 'string') {\n return res.status(400).json({ error: 's3: content type must be a string' })\n }\n\n client.createMultipartUpload({\n Bucket: config.bucket,\n Key: key,\n ACL: config.acl,\n ContentType: type,\n Metadata: metadata,\n Expires: ms('5 minutes') / 1000\n }, (err, data) => {\n if (err) {\n next(err)\n return\n }\n res.json({\n key: data.Key,\n uploadId: data.UploadId\n })\n })\n }",
"async function configAWS(){\n aws.config.update({\n region: 'us-east-1', // Put your aws region here\n accessKeyId: config.AWSAccessKeyId,\n secretAccessKey: config.AWSSecretKey\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
called by animation scheduler if Waveform.widgets.dirty === true | drawWidgets() {
Waveform.widgets.dirty = false
const drawn = []
for( let key in Waveform.widgets ) {
if( key === 'dirty' || key === 'findByObj' ) continue
const widget = Waveform.widgets[ key ]
if( widget === undefined || widget === null ) continue
// ensure that a widget does not get drawn more
// than once per frame
if( drawn.indexOf( widget ) !== -1 ) continue
if( typeof widget === 'object' && widget.ctx !== undefined ) {
widget.ctx.strokeStyle = Environment.theme.get('f_med')
widget.ctx.fillStyle = Environment.theme.get('f_med')
widget.ctx.clearRect( 0,0, widget.width, widget.height )
// draw left border
widget.ctx.beginPath()
widget.ctx.moveTo( widget.padding + .5, 0.5 )
widget.ctx.lineTo( widget.padding + .5, widget.height + .5 )
widget.ctx.stroke()
// draw right border
widget.ctx.beginPath()
widget.ctx.moveTo( widget.padding + widget.waveWidth + .5, .5 )
widget.ctx.lineTo( widget.padding + widget.waveWidth + .5, widget.height + .5 )
widget.ctx.stroke()
// draw waveform
widget.ctx.beginPath()
widget.ctx.moveTo( widget.padding, widget.height / 2 + 1 )
const wHeight = (widget.height * .85 + .45) - 1
// needed for fades
let isReversed = false
if( widget.isFade !== true ) {
const range = widget.max - widget.min
for( let i = 0, len = widget.waveWidth; i < len; i++ ) {
const data = widget.values[ i ]
const shouldDrawDot = typeof data === 'object'
const value = shouldDrawDot ? data.value : data
const scaledValue = ( value - widget.min ) / range
const yValue = Math.round(scaledValue * (wHeight)) - 1
if( shouldDrawDot === true ) {
widget.ctx.fillStyle = Environment.theme.get('f_high') //COLORS.DOT
widget.ctx.lineTo( i + widget.padding + .5, wHeight - yValue )
widget.ctx.fillRect( i + widget.padding - 1, wHeight - yValue - 1.5, 3, 3)
}else{
widget.ctx.lineTo( i + widget.padding + .5, wHeight - yValue )
}
}
}else{
const range = Math.abs( widget.gen.to - widget.gen.from )
isReversed = ( widget.gen.from > widget.gen.to )
if( !isReversed ) {
widget.ctx.moveTo( widget.padding, widget.height )
widget.ctx.lineTo( widget.padding + widget.waveWidth, 0 )
}else{
widget.ctx.moveTo( widget.padding, 0 )
widget.ctx.lineTo( widget.padding + widget.waveWidth, widget.height )
}
const value = widget.gen.values[0]
if( !isNaN( value ) ) {
let percent = isReversed === true ? Math.abs( (value-widget.gen.to) / range ) : Math.abs( (value-widget.gen.from) / range )
if( !isReversed ) {
widget.ctx.moveTo( widget.padding + ( Math.abs( percent ) * widget.waveWidth ), widget.height )
widget.ctx.lineTo( widget.padding + ( Math.abs( percent ) * widget.waveWidth ), 0 )
}else{
widget.ctx.moveTo( widget.padding + ( (1-percent) * widget.waveWidth ), widget.height )
widget.ctx.lineTo( widget.padding + ( (1-percent) * widget.waveWidth ), 0 )
}
// XXX we need to also check if the next value would loop the fade
// in which case finalizing wouldn't actually happen... then we
// can get rid of magic numbers here.
if( isReversed === true ) {
//console.log( 'reverse finalized', percent, widget.gen.from, widget.gen.to )
if( percent <= 0.01) widget.gen.finalize()
}else{
//console.log( 'finalized', percent, value, range, widget.gen.from, widget.gen.to )
if( percent >= .99 ) widget.gen.finalize()
}
}
}
widget.ctx.stroke()
//const __min = isReversed === false ? widget.min.toFixed(2) : widget.max.toFixed(2)
//const __max = isReversed === false ? widget.max.toFixed(2) : widget.min.toFixed(2)
let __min, __max
if( widget.isFade !== true ) {
__min = isReversed === false ? widget.min.toFixed(2) : widget.max.toFixed(2)
__max = isReversed === false ? widget.max.toFixed(2) : widget.min.toFixed(2)
}else{
__min = widget.gen.from.toFixed(2)//isReversed === false ? widget.gen.to.toFixed(2) : widget.gen.to.toFixed(2)
__max = widget.gen.to.toFixed(2) //isReversed === false ? widget.gen.from.toFixed(2) : widget.gen.from.toFixed(2)
}
const reverseHeight = widget.isFade === true && __min > __max
// draw min/max
widget.ctx.fillStyle = Environment.theme.get('f_med')//COLORS.STROKE
widget.ctx.textAlign = 'right'
widget.ctx.fillText( __min, widget.padding - 2, reverseHeight === false ? widget.height : widget.height / 2 )
widget.ctx.textAlign = 'left'
widget.ctx.fillText( __max, widget.waveWidth + widget.padding + 2, reverseHeight === false ? widget.height / 2 : widget.height )
// draw corners
widget.ctx.beginPath()
widget.ctx.moveTo( .5, 3.5 )
widget.ctx.lineTo( .5, .5 )
widget.ctx.lineTo( 3.5, .5)
widget.ctx.moveTo( .5, widget.height - 3.5 )
widget.ctx.lineTo( .5, widget.height - .5 )
widget.ctx.lineTo( 3.5, widget.height - .5 )
const right = widget.padding * 2 + widget.waveWidth - .5
widget.ctx.moveTo( right, 3.5 )
widget.ctx.lineTo( right, .5 )
widget.ctx.lineTo( right - 3, .5 )
widget.ctx.moveTo( right, widget.height - 3.5 )
widget.ctx.lineTo( right, widget.height - .5 )
widget.ctx.lineTo( right - 3, widget.height - .5 )
widget.ctx.stroke()
drawn.push( widget )
}
}
} | [
"dirty() {\n this.signal();\n }",
"_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }",
"_updateDirtyDomComponents() {\n // An item is marked dirty when:\n // - the item is not yet rendered\n // - the item's data is changed\n // - the item is selected/deselected\n if (this.dirty) {\n this._updateContents(this.dom.content);\n this._updateDataAttributes(this.dom.box);\n this._updateStyle(this.dom.box);\n \n // update class\n const className = this.baseClassName + ' ' + (this.data.className ? ' ' + this.data.className : '') +\n (this.selected ? ' vis-selected' : '') + ' vis-readonly';\n this.dom.box.className = 'vis-item ' + className;\n \n if (this.options.showStipes) {\n this.dom.line.className = 'vis-item vis-cluster-line ' + (this.selected ? ' vis-selected' : '');\n this.dom.dot.className = 'vis-item vis-cluster-dot ' + (this.selected ? ' vis-selected' : '');\n }\n \n if (this.data.end) {\n // turn off max-width to be able to calculate the real width\n // this causes an extra browser repaint/reflow, but so be it\n this.dom.content.style.maxWidth = 'none';\n }\n }\n }",
"function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.confirmBtnDisabled(true);\n }",
"setTransformDirty () {\n this._transformDirty = true;\n }",
"function setChanged (){\n\t\tformModified = true;\n\t}",
"watch() {\n if (this.shouldUpdate()) {\n this.trigger('change', this.rect);\n }\n\n if(!this.shouldStop){\n window.requestAnimationFrame(() => this.watch());\n }\n }",
"function editorUpdate() {\n if (editor.binding) {\n if ('hold' === generator.clientUpdateFragmentText(editor.binding, editor.$edit.val())) {\n editor.holding = true;\n }\n showIfModified();\n }\n }",
"refresh(timeNow, enableAnimation) {\n }",
"function toggleFreeze() {\n if (frozen) {\n frozen = false;\n } else {\n frozen = lastRenderMillis;\n }\n }",
"animationFrame() {\n\t\t\tvar canvases = this._getCanvases();\n\t\t\tif(!canvases.length) {\n\t\t\t\t// No canvas to draw onto, do nothing\n\t\t\t\tif(this.warnIfNoElement) console.warn(\"No dw-paint element found for root \"+this.name+\".\");\n\t\t\t\tthis.warnIfNoElement = false;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif(this._mmQueued) {\n\t\t\t\tthis.mouseX = this._mmQueued.x;\n\t\t\t\tthis.mouseY = this._mmQueued.y;\n\t\t\t\t\n\t\t\t\t// Components may change this, so reset it every frame\n\t\t\t\tmouse.cursor = \"initial\";\n\t\t\t\t\n\t\t\t\tGroup.prototype.interact.call(this, this._mmQueued);\n\t\t\t\tthis._mmQueued = null;\n\t\t\t}\n\t\t\t\n\t\t\tfor(var i = 0; i < canvases.length; i ++) {\n\t\t\t\tvar canvas = canvases[i];\n\t\t\t\t\n\t\t\t\tif(!this.noCleanCanvas) {\n\t\t\t\t\tcanvas.getContext(\"2d\").clearRect(0, 0, canvas.width, canvas.height);\n\t\t\t\t\tif(!this.noCacheCanvas)\n\t\t\t\t\t\tthis._cacheCanvases[i].getContext(\"2d\").clearRect(0, 0, canvas.width, canvas.height);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(this.noCacheCanvas) {\n\t\t\t\t\tthis.paint(canvas.getContext(\"2d\"), 0, 0, canvas.width, canvas.height);\n\t\t\t\t}else{\n\t\t\t\t\tthis.paint(this._cacheCanvases[i].getContext(\"2d\"), 0, 0, canvas.width, canvas.height);\n\t\t\t\t\tcanvas.getContext(\"2d\").drawImage(this._cacheCanvases[i], 0, 0, canvas.width, canvas.height);\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"onRedrawCanvas() {\n if (!this.file) return false;\n this.file.doAction(Redraw, this.canvas, this.loopCount);\n }",
"function isDirty(){\n return this.__isDirty__;\n}",
"wakeUp() {\n const self = this;\n // Only re render VizTool (should be super fast)\n self.render();\n }",
"function afterTweening() {\n isTweening = false;\n}",
"frame () {\n\t\t// This is to call the parent class's delete method\n\t\tsuper.frame();\n\n\t\tif (this.state === 'swinging') this.swing();\n\t\telse if (this.state === 'pulling' && this.shouldStopPulling()) this.stopPulling();\n\t\telse if (this.state === 'pulling' && this.shouldRemoveLastChain()) this.removeLastChain();\n\t\telse if (this.state === 'throwing' && this.shouldGenerateAnotherChain()) this.generateChain();\n\n\t\tif (this.hookedObject) {\n\t\t\t// Updates the hooked object's position to follow the hook at every frame.\n\t\t\tthis.hookedObject.position = this.position.add(this.hookedObject.offset);\n\t\t}\n\t}",
"[updateButtons]() {\n\t\t\tconst self = this;\n\t\t\tconst _self = _(self);\n\n\t\t\tif (!self.isRemoved && self.showButtons()) {\n\t\t\t\t_self.controls.get(PREV_BUTTON_ID).isVisible(!_self.isAtStart());\n\t\t\t\t_self.controls.get(NEXT_BUTTON_ID).isVisible(!_self.isAtEnd());\n\t\t\t}\n\t\t}",
"function redrawWidgets() {\n let W = global.WIDGETS;\n global.WIDGETS = {};\n Object.keys(W)\n .sort() // see comment in boot.js\n .sort((a, b) => (0|W[b].sortorder)-(0|W[a].sortorder))\n .forEach(k => {global.WIDGETS[k] = W[k];});\n Bangle.drawWidgets();\n }",
"setNeedsUpdate() {\n if (this.internalState) {\n this.context.layerManager.setNeedsUpdate(String(this));\n this.internalState.needsUpdate = true;\n }\n }",
"function privateAfterSongChanges(){\n\t\t/*\n\t\t\tAfter the new song is set, we see if we need to change\n\t\t\tthe visualization. If it's different, we need to start \n\t\t\tthe new one.\n\t\t*/\n\t\tif( privateCheckSongVisualization() ){\n\t\t\tprivateStartVisualization();\n\t\t}\n\n\t\t/*\n\t\t\tAfter the new song is set, Amplitude will update the\n\t\t\tvisual elements containing information about the\n\t\t\tnew song if the user wants Amplitude to.\n\t\t*/\n\t\tif( config.handle_song_elements ){\n\t\t\tprivateDisplaySongMetadata();\n\t\t}\n\n\t\t/*\n\t\t\tSync song status sliders. Sets them back to 0 because\n\t\t\twhen the song is changing there won't be any songs currently\n\t\t\tplaying.\n\t\t*/\n\t\tprivateResetSongStatusSliders();\n\n\t\t/*\n\t\t\tWe set the current times to 0:00 when song changes\n\t\t\tso all of the page's players will be synchronized.\n\t\t*/\n\t\tprivateSyncCurrentTimes();\n\n\t\t/*\n\t\t\tRemove class from all containers\n\t\t*/\n\t\tprivateSyncVisualPlayingContainers();\n\n\t\t/*\n\t\t\tSet new active song container by applying a class\n\t\t\tto the visual element containing the visual representation\n\t\t\tof the song that is actively playing.\n\t\t*/\n\t\tprivateSetActiveContainer();\n\n\t\t/*\n\t\t\tPlays the new song.\n\t\t*/\n\t\tprivatePlay();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clamp the given date between min and max dates. | clampDate(date, min, max) {
if (min && this.compareDate(date, min) < 0) {
return min;
}
if (max && this.compareDate(date, max) > 0) {
return max;
}
return date;
} | [
"function setSliderMinMaxDates(range) {\n $scope.layoutEndTimeMS = range.max;\n $scope.layoutStartTimeMS = range.min;\n $scope.currentDate = range.min;\n $scope.layoutCurTimeMS = range.min;\n }",
"function clamp(xmin, xmax, x) {\n\treturn Math.min(xmax, Math.max(xmin, x));\n}",
"function clamp(n, min, max) {\n return isNumeric(n) ? Math.min(Math.max(n, min), max) : min;\n}",
"clamp(number, lower, upper) {\r\n /* Initial version\r\n var leftBoundry = Math.max(number, lower);\r\n var clampedValue = Math.min(leftBoundry, upper);\r\n return clampedValue;\r\n */\r\n\r\n // Improved/Consise final version below\r\n return Math.min(Math.max(number, lower), upper);\r\n\r\n }",
"function restrictToRange(val,min,max) {\r\n if (val < min) return min;\r\n if (val > max) return max;\r\n return val;\r\n }",
"function clamp(value, lowerBound, upperBound) {\n\t\treturn Math.min(Math.max(value, lowerBound), upperBound);\n\t}",
"function restrictBounds(value) {\n\t\t/*jshint validthis:true */\n\t\tvalue = Number(value) || 0;\n\t\tif (value > this.max) {\n\t\t\treturn this.max;\n\t\t}\n\t\tif (value < this.min) {\n\t\t\treturn this.min;\n\t\t}\n\t\treturn value;\n\t}",
"function clampTimeRange(range, within) {\n if (within) {\n if (range.overlaps(within)) {\n var start = range.start < within.start ?\n range.start > within.end ?\n within.end :\n within.start : range.start;\n var end = range.end > within.end ?\n range.end < within.start ?\n within.start :\n within.end : range.end;\n if (start > end) {\n [start, end] = [end, start];\n }\n return moment.range(start, end);\n } else {\n return null;\n }\n } else {\n return range;\n }\n}",
"clampEach_(min, max) {\n this.x = Math.min(Math.max(this.x, min), max);\n this.y = Math.min(Math.max(this.y, min), max);\n return this;\n }",
"function minMaxSet() {\n min = parseInt(minRange.value);\n max = parseInt(maxRange.value);\n}",
"function clamp(num, lower, upper){\n if (num >= lower && num <= upper) return num;\n else if (num < lower) return lower;\n else return upper;\n}",
"function keepWithin(value, min, max) {\n if (value < min) value = min;\n if (value > max) value = max;\n return value;\n }",
"static ClampToRef(value, min, max, result) {\n let x = value.x;\n x = x > max.x ? max.x : x;\n x = x < min.x ? min.x : x;\n let y = value.y;\n y = y > max.y ? max.y : y;\n y = y < min.y ? min.y : y;\n let z = value.z;\n z = z > max.z ? max.z : z;\n z = z < min.z ? min.z : z;\n result.copyFromFloats(x, y, z);\n }",
"static Clamp(value, min, max) {\n const v = new Vector3();\n Vector3.ClampToRef(value, min, max, v);\n return v;\n }",
"function getDateExtent() {\n const opts = seasonal.opts;\n const years = opts.data.map(d=>+getYearFromDate(d[opts.date_field]));\n // Get min/max years\n opts.start_year = Math.min(...years);\n opts.end_year = Math.max(...years);\n // Get earliest month from earliest year\n opts.start_month = Math.min(...opts.data\n .filter(d=>+getYearFromDate(d[opts.date_field])==opts.start_year)\n .map(d=>+getMonthFromDate(d[opts.date_field])));\n // Zero-pad months\n if (opts.start_month < 10) `0${opts.start_month}`;\n\n // Validate detected dates\n if (+opts.start_month < 1 || +opts.start_month > 12) {\n exitError(\"Detected start month was not between 1 and 12.\");\n process.exit(1);\n }\n if (opts.start_year.toString().length > 4 || opts.start_year.toString().length < 4) {\n exitError(\"Detected start year was not four digits long.\");\n process.exit(1);\n }\n if (opts.end_year.toString().length > 4 || opts.end_year.toString().length < 4) {\n exitError(\"Detected end year was not four digits long.\");\n process.exit(1);\n }\n\n seasonal.opts = opts;\n}",
"minMaxConditionsHandler() {\n if (\n (this.min || this.min === 0) &&\n (this.value < this.min || this._previousValue < this.min)\n ) {\n this._value = this.min;\n }\n if (\n this.max &&\n (this.value > this.max || this._previousValue > this.max)\n ) {\n this._value = this.max;\n }\n }",
"static Clamp(value, min, max) {\n let x = value.x;\n x = x > max.x ? max.x : x;\n x = x < min.x ? min.x : x;\n let y = value.y;\n y = y > max.y ? max.y : y;\n y = y < min.y ? min.y : y;\n return new Vector2(x, y);\n }",
"function filterBetween(array, min, max){\n if(\n Array.isArray(array) &&\n typeof min == 'string' &&\n typeof max == 'string'\n ){\n let newArr = array.concat(min, max).sort()\n let startSlice = newArr.indexOf(min) + 1\n let endSlice = newArr.indexOf(max)\n\n return newArr.slice(startSlice, endSlice)\n }\n}",
"function Clip( n, minValue, maxValue)\n\t{\n\t\treturn Math.min(Math.max(n, minValue), maxValue);\n\t}",
"rescaleX(minDate, maxDate, force = false) {\n var needRescaling = false;\n if (!force) {\n if (minDate < this.minX) {\n this.minX = minDate;\n needRescaling = true;\n }\n if (maxDate > this.maxX) {\n this.maxX = maxDate;\n needRescaling = true;\n }\n }\n else {\n needRescaling = true;\n }\n\n if (needRescaling) {\n this.xScale = d3.scaleTime()\n .domain([this.minX, this.maxX])\n .range([0, this.maxWidth]);\n this.xAxis.attr('class', 'axis x-axis')\n .attr('transform', 'translate(0, ' + this.maxHeight + ')')\n .call(\n d3.axisBottom(this.xScale)\n );\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Legacy support for HC < 6 to make 'scatter' series in a 3D chart route to the real 'scatter3d' series type. (8407) | function onAddSeries(e) {
if (this.is3d()) {
if (e.options.type === 'scatter') {
e.options.type = 'scatter3d';
}
}
} | [
"function onAfterInit() {\n var options = this.options;\n if (this.is3d()) {\n (options.series || []).forEach(function (s) {\n var type = (s.type ||\n options.chart.type ||\n options.chart.defaultSeriesType);\n if (type === 'scatter') {\n s.type = 'scatter3d';\n }\n });\n }\n }",
"function scatter20() {\n make_scatter(20, 30);\n drawChart();\n}",
"function chartSurfacePlot () {\r\n\r\n\tvar x3d = void 0;\r\n\tvar scene = void 0;\r\n\r\n\t/* Default Properties */\r\n\tvar width = 1300;\r\n\tvar height = 500;\r\n\tvar dimensions = { x: 80, y: 40, z: 160 };\r\n\tvar colors = [\"blue\", \"red\"];\r\n\tvar classed = \"d3X3domSurfacePlot\";\r\n\tvar debug = false;\r\n\r\n\t/* Scales */\r\n\tvar xScale = void 0;\r\n\tvar yScale = void 0;\r\n\tvar zScale = void 0;\r\n\tvar colorScale = void 0;\r\n\r\n\t/* Components */\r\n\tvar viewpoint = component.viewpoint();\r\n\tvar axis = component.axisThreePlane();\r\n\tvar surface = component.surface();\r\n\r\n\t/**\r\n * Initialise Data and Scales\r\n *\r\n * @private\r\n * @param {Array} data - Chart data.\r\n */\r\n\tvar init = function init(data) {\r\n\t\tvar _dataTransform$summar = dataTransform(data).summary(),\r\n\t\t rowKeys = _dataTransform$summar.rowKeys,\r\n\t\t columnKeys = _dataTransform$summar.columnKeys,\r\n\t\t valueMax = _dataTransform$summar.valueMax;\r\n\r\n\t\tvar valueExtent = [600, 950];\r\n\t\tvar _dimensions = dimensions,\r\n\t\t dimensionX = _dimensions.x,\r\n\t\t dimensionY = _dimensions.y,\r\n\t\t dimensionZ = _dimensions.z;\r\n\r\n\r\n\t\txScale = d3.scalePoint().domain(rowKeys).range([0, dimensionX]);\r\n\r\n\t\tyScale = d3.scaleLinear().domain(valueExtent).range([0, dimensionY]).nice();\r\n\r\n\t\tzScale = d3.scalePoint().domain(columnKeys).range([0, dimensionZ]);\r\n\r\n\t\tcolorScale = d3.scaleLinear().domain(valueExtent).range(colors).interpolate(d3.interpolateLab);\r\n\t};\r\n\r\n\t/**\r\n * Constructor\r\n *\r\n * @constructor\r\n * @alias surfacePlot\r\n * @param {d3.selection} selection - The chart holder D3 selection.\r\n */\r\n\tvar my = function my(selection) {\r\n\t\t// Create x3d element (if it does not exist already)\r\n\t\tif (!x3d) {\r\n\t\t\tx3d = selection.append(\"x3d\");\r\n\t\t\tscene = x3d.append(\"scene\");\r\n\t\t}\r\n\r\n\t\tx3d.attr(\"width\", width + \"px\").attr(\"height\", height + \"px\").attr(\"showLog\", debug ? \"true\" : \"false\").attr(\"showStat\", debug ? \"true\" : \"false\");\r\n\r\n\t\t// Update the chart dimensions and add layer groups\r\n\t\tvar layers = [\"axis\", \"surface\"];\r\n\t\tscene.classed(classed, true).selectAll(\"group\").data(layers).enter().append(\"group\").attr(\"class\", function (d) {\r\n\t\t\treturn d;\r\n\t\t});\r\n\r\n\t\tselection.each(function (data) {\r\n\t\t\tinit(data);\r\n\r\n\t\t\t// Add Viewpoint\r\n\t\t\tviewpoint.centerOfRotation([dimensions.x / 2, dimensions.y / 2, dimensions.z / 2]);\r\n\r\n\t\t\tscene.call(viewpoint);\r\n\r\n\t\t\t// Add Axis\r\n\t\t\taxis.xScale(xScale).yScale(yScale).zScale(zScale).labelPosition(\"proximal\");\r\n\r\n\t\t\tscene.select(\".axis\").call(axis);\r\n\r\n\t\t\t// Add Surface Area\r\n\t\t\tsurface.xScale(xScale).yScale(yScale).zScale(zScale).colors(colors);\r\n\r\n\t\t\tscene.select(\".surface\").datum(data).call(surface);\r\n\t\t});\r\n\t};\r\n\r\n\t/**\r\n * Width Getter / Setter\r\n *\r\n * @param {number} _v - X3D canvas width in px.\r\n * @returns {*}\r\n */\r\n\tmy.width = function (_v) {\r\n\t\tif (!arguments.length) return width;\r\n\t\twidth = _v;\r\n\t\treturn this;\r\n\t};\r\n\r\n\t/**\r\n * Height Getter / Setter\r\n *\r\n * @param {number} _v - X3D canvas height in px.\r\n * @returns {*}\r\n */\r\n\tmy.height = function (_v) {\r\n\t\tif (!arguments.length) return height;\r\n\t\theight = _v;\r\n\t\treturn this;\r\n\t};\r\n\r\n\t/**\r\n * Dimensions Getter / Setter\r\n *\r\n * @param {{x: number, y: number, z: number}} _v - 3D object dimensions.\r\n * @returns {*}\r\n */\r\n\tmy.dimensions = function (_v) {\r\n\t\tif (!arguments.length) return dimensions;\r\n\t\tdimensions = _v;\r\n\t\treturn this;\r\n\t};\r\n\r\n\t/**\r\n * X Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.xScale = function (_v) {\r\n\t\tif (!arguments.length) return xScale;\r\n\t\txScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Y Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.yScale = function (_v) {\r\n\t\tif (!arguments.length) return yScale;\r\n\t\tyScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Z Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.zScale = function (_v) {\r\n\t\tif (!arguments.length) return zScale;\r\n\t\tzScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Color Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 color scale.\r\n * @returns {*}\r\n */\r\n\tmy.colorScale = function (_v) {\r\n\t\tif (!arguments.length) return colorScale;\r\n\t\tcolorScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Colors Getter / Setter\r\n *\r\n * @param {Array} _v - Array of colours used by color scale.\r\n * @returns {*}\r\n */\r\n\tmy.colors = function (_v) {\r\n\t\tif (!arguments.length) return colors;\r\n\t\tcolors = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Debug Getter / Setter\r\n *\r\n * @param {boolean} _v - Show debug log and stats. True/False.\r\n * @returns {*}\r\n */\r\n\tmy.debug = function (_v) {\r\n\t\tif (!arguments.length) return debug;\r\n\t\tdebug = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\treturn my;\r\n}",
"function updateTrace1() {\n trace1 = {\n x: [xCoords[sliderValue]],\n y: [yCoords[sliderValue]],\n error_y: {\n type: 'constant',\n value: yError3rdOrder(xCoords[sliderValue], xError)\n },\n error_x: {\n type: 'constant',\n value: xError\n },\n type: 'scatter'\n };\n}",
"function onInitializingScatterChart() {\n addScatterChartDragHandler(selector);\n }",
"function scatterPlotMatrix(a, dataType){\n // if(activeSvg ==1){\n // //checks if there is already a graph, and removes it\n // d3.select(\"svg\").remove();\n // }\n // activeSvg = 1;\n\n var tempA = JSON.parse(a);\n\n //get the data and put it into the right format\n var data;\n var tempData = new Array([]);\n var temp1 = [];\n var temp2 =[];\n var temp3 = [];\n\n if(dataType==\"rand\"){\n data = tempA.rand3LoadData;\n attributeNames = tempA.rand3AttrNames;\n bigData = tempA.bigRand3Array;\n } else if(dataType==\"strat\"){\n data = tempA.strat3LoadData;\n attributeNames = tempA.strat3AttrNames;\n bigData = tempA.bigStrat3Array;\n } else{\n data = tempA.org3LoadData;\n attributeNames = tempA.org3AttrNames;\n bigData = tempA.bigOrg3Array;\n }\n for(var i=0;i<data.length;i++){\n var superTempArray = [];\n for(var j=0;j<3;j++){\n superTempArray[j] = data[i][j];\n //tempData[i][j] = data[i][j];\n }\n tempData[i]= superTempArray;\n }\n for (var i=0; i<data.length;i++){\n //in order to get a column of features\n temp1[i] = tempData[i][0]\n temp2[i]= tempData[i][1]\n temp3[i] = tempData[i][2]\n }\n\n //standart parameters\n n = 3;\n var size = 230,\n padding = 60;\n\n var padDiv2 = padding/2;\n var sizeMinPadDiv2 = size - (padding/2);\n var sizeTnPlusPad = (size*n)+padding;\n\n //scales\n var yScale = d3.scaleLinear()\n .range([sizeMinPadDiv2, padDiv2]);\n\n var xScale = d3.scaleLinear()\n .range([padDiv2, sizeMinPadDiv2]);\n\n var yAxis = d3.axisLeft()\n .ticks(6)\n .tickFormat(d3.format(\"d\"))\n .scale(yScale)\n .tickSize(-size*n)\n ;\n var xAxis = d3.axisBottom()\n .ticks(6)\n .tickFormat(d3.format(\"d\"))\n .scale(xScale)\n .tickSize(size*n)\n ;\n\n \n var colors = [\"FA8D62\",\"#7D26CD\",\"#42C0FB\", \"E6D72A\"];\n var ftrNames = Object.keys(attributeNames);\n // console.log(\"ftr Names \" + ftrNames)\n var ftrs = [temp1, temp2,temp3]\n\n\n //gives domain for each attribute\n var domainByFtr ={};\n ftrNames.forEach(function(ftr) {\n var tempHere = d3.values(tempData[ftr])\n domainByFtr[ftr] = d3.extent(tempHere);\n })\n ;\n\n //create instance of svg\n var svg = d3.select(\"#scatterPlotMatrix\").append(\"svg\")\n .attr(\"x\", 70)\n .attr(\"height\", sizeTnPlusPad)\n .attr(\"width\", sizeTnPlusPad)\n .attr('id', 'svg')\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + padding + \",\" + padDiv2+ \")\")\n ;\n\n //create instance of x axis\n svg.selectAll(\".x.axis\")\n .data(ftrNames)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", function(d,i){return \"translate(\" + ((-1-d+n)*size) + \",0)\";})\n .each(function(d,i) { \n xScale\n .domain(domainByFtr[d]); \n d3.select(this)\n .call(xAxis); \n });\n\n //labels the x axis by attribute names\n for(var i=0; i<3; i++){\n var xAxisLabel = svg.append(\"text\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"font-family\", \"Courier\")\n .style(\"font-size\", \"20px\")\n .attr(\"transform\", \"translate(\" + ((size/2)+(size*i)) +\",\"+ (0) + \")\" )\n .text(attributeNames[2-i]);\n }\n\n //creates an instance of the y axis\n svg.selectAll(\".y.axis\")\n .data(ftrNames)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"y axis\")\n .attr(\"transform\", function(d,i) { return \"translate(0,\" + (i * size) + \")\"; })\n .each(function(d,i) { \n yScale\n .domain(domainByFtr[d]); \n d3.select(this)\n .call(yAxis)\n });\n \n //labels the y axis\n for(var i=0; i<3; i++){\n var yAxisLabel = svg.append(\"text\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"font-family\", \"Courier\")\n .style(\"font-size\", \"20px\")\n .attr(\"transform\", \"translate(\" + (-padding/2) +\",\"+ ((size/2)+(size*i)) + \")rotate(-90)\" )\n .text(attributeNames[i]);\n }\n\n //brings object to front\n d3.selection.prototype.move2Front = function() {\n return this.each(function(){\n this.parentNode.appendChild(this);\n });\n };\n var tempCross = cross(ftrs, ftrs);\n //create an instance of a cell\n var cell = svg.selectAll(\".cell\")\n .data(tempCross)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"cell\")\n .attr(\"transform\", function(d) { return \"translate(\" + (n - d.i - 1) * size + \",\" + d.j * size + \")\"; })\n .each(plot)\n ;\n\n //in order to plot each cell and data associated with cell\n function plot(p){\n var cell = d3.select(this);\n\n //sets the x and y domain of each corresponding cell\n xScale.domain([d3.min(p.x),d3.max(p.x)]);\n yScale.domain([d3.min(p.y),d3.max(p.y)]);\n\n //creates the instance of the cell\n cell.append(\"rect\")\n .attr(\"class\", \"frame\")\n .attr(\"y\", padDiv2)\n .attr(\"x\", padDiv2)\n .attr(\"height\", size - padding)\n .attr(\"width\", size - padding)\n .attr(\"fill\", \"none\")\n .attr(\"stroke\", \"black\");\n\n //just so that I go through the appropriate amount of data points\n var arrayForIndex = new Array(data.length)\n\n cell.selectAll(\"circle\")\n .data(arrayForIndex)\n .enter()\n .append(\"circle\")\n .attr(\"cx\", function(d,i) { \n return xScale(p.x[i]); })\n .attr(\"cy\", function(d,i) { \n return yScale(p.y[i]); \n })\n .attr(\"r\", 3)\n .style(\"fill\",function(d,i){\n if(data[i][3]!=2){\n d3.select(this).move2Front();\n }\n return colors[data[i][3]]})\n .on(\"mouseover\", function(d,i){\n d3.select(this).style(\"fill\", \"red\");\n })\n .on(\"mouseout\", function(d,i){\n d3.select(this).style(\"fill\", colors[data[i][3]]);\n });\n }\n //for title\n document.getElementById(\"t1\").style.color = \"#4682b4\";\n document.getElementById(\"t1\").style.textDecoration = \"underline\";\n if(dataType==\"org\"){\n document.getElementById(\"t1\").value = \"Scatter Plot Matrix\";\n } else if(dataType==\"rand\"){\n document.getElementById(\"t1\").value = \"Random Data Scatter Plot Matrix\";\n } else if (dataType==\"strat\"){\n document.getElementById(\"t1\").value = \"Stratified Data Scatter Plot Matrix\";\n }\n document.getElementById(\"topnav\").style.width =\"1350px\";\n document.getElementById(\"topnav\").style.transform = \"translate(\" + (-10) + \"px,\" + (-8) + \"px)\";\n document.getElementById(\"topnav\").style.height =\"41px\";\n // document.getElementById(\"topnav\").style.transform = \"translate(\" + (-10) + \"px,\" + (-428) + \"px)\";\n\n document.getElementById(\"scatterPlotMatrix\").style.transform = \"translate(\" + (-100) + \"px,\" + (-130) + \"px)\";\n document.getElementById(\"t1\").style.transform =\"translate(\" + (0) + \"px,\" + (-110) + \"px)\";\n}",
"function componentSurface () {\r\n\r\n\t/* Default Properties */\r\n\tvar dimensions = { x: 80, y: 40, z: 160 };\r\n\tvar colors = [\"blue\", \"red\"];\r\n\tvar classed = \"d3X3domSurface\";\r\n\r\n\t/* Scales */\r\n\tvar xScale = void 0;\r\n\tvar yScale = void 0;\r\n\tvar zScale = void 0;\r\n\tvar colorScale = void 0;\r\n\r\n\t/**\r\n * Array to String\r\n *\r\n * @private\r\n * @param {array} arr\r\n * @returns {string}\r\n */\r\n\tvar array2dToString = function array2dToString(arr) {\r\n\t\treturn arr.reduce(function (a, b) {\r\n\t\t\treturn a.concat(b);\r\n\t\t}, []).reduce(function (a, b) {\r\n\t\t\treturn a.concat(b);\r\n\t\t}, []).join(\" \");\r\n\t};\r\n\r\n\t/**\r\n * Initialise Data and Scales\r\n *\r\n * @private\r\n * @param {Array} data - Chart data.\r\n */\r\n\tvar init = function init(data) {\r\n\t\tvar _dataTransform$summar = dataTransform(data).summary(),\r\n\t\t rowKeys = _dataTransform$summar.rowKeys,\r\n\t\t columnKeys = _dataTransform$summar.columnKeys,\r\n\t\t valueMax = _dataTransform$summar.valueMax;\r\n\r\n\t\tvar valueExtent = [600, 950];\r\n\t\tvar _dimensions = dimensions,\r\n\t\t dimensionX = _dimensions.x,\r\n\t\t dimensionY = _dimensions.y,\r\n\t\t dimensionZ = _dimensions.z;\r\n\r\n\r\n\t\tif (typeof xScale === \"undefined\") {\r\n\t\t\txScale = d3.scalePoint().domain(rowKeys).range([0, dimensionX]);\r\n\t\t}\r\n\r\n\t\tif (typeof yScale === \"undefined\") {\r\n\t\t\tyScale = d3.scaleLinear().domain(valueExtent).range([0, dimensionY]);\r\n\t\t}\r\n\r\n\t\tif (typeof zScale === \"undefined\") {\r\n\t\t\tzScale = d3.scalePoint().domain(columnKeys).range([0, dimensionZ]);\r\n\t\t}\r\n\r\n\t\tif (typeof colorScale === \"undefined\") {\r\n\t\t\tcolorScale = d3.scaleLinear().domain(valueExtent).range(colors).interpolate(d3.interpolateLab);\r\n\t\t}\r\n\t};\r\n\r\n\t/**\r\n * Constructor\r\n *\r\n * @constructor\r\n * @alias surface\r\n * @param {d3.selection} selection - The chart holder D3 selection.\r\n */\r\n\tvar my = function my(selection) {\r\n\t\tselection.each(function (data) {\r\n\t\t\tinit(data);\r\n\r\n\t\t\tvar element = d3.select(this).classed(classed, true);\r\n\r\n\t\t\tvar surfaceData = function surfaceData(d) {\r\n\r\n\t\t\t\tvar coordPoints = function coordPoints(data) {\r\n\t\t\t\t\treturn data.map(function (X) {\r\n\t\t\t\t\t\treturn X.values.map(function (d) {\r\n\t\t\t\t\t\t\treturn [xScale(X.key), yScale(d.value), zScale(d.key)];\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar coordIndex = function coordIndex(data) {\r\n\t\t\t\t\tvar ny = data.length;\r\n\t\t\t\t\tvar nx = data[0].values.length;\r\n\r\n\t\t\t\t\tvar coordIndexFront = Array.apply(0, Array(ny - 1)).map(function (_, j) {\r\n\t\t\t\t\t\treturn Array.apply(0, Array(nx - 1)).map(function (_, i) {\r\n\t\t\t\t\t\t\tvar start = i + j * nx;\r\n\t\t\t\t\t\t\treturn [start, start + nx, start + nx + 1, start + 1, start, -1];\r\n console.log(start);\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\tvar coordIndexBack = Array.apply(0, Array(ny - 1)).map(function (_, j) {\r\n\t\t\t\t\t\treturn Array.apply(0, Array(nx - 1)).map(function (_, i) {\r\n\t\t\t\t\t\t\tvar start = i + j * nx;\r\n\t\t\t\t\t\t\treturn [start, start + 1, start + nx + 1, start + nx, start, -1];\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\r\n\t\t\t\t\treturn coordIndexFront.concat(coordIndexBack);\r\n\t\t\t\t};\r\n\r\n\t\t\t\tvar colorFaceSet = function colorFaceSet(data) {\r\n\t\t\t\t\treturn data.map(function (X) {\r\n\t\t\t\t\t\treturn X.values.map(function (d) {\r\n\t\t\t\t\t\t\tvar col = d3.color(colorScale(d.value));\r\n\t\t\t\t\t\t\treturn '' + Math.round(col.r / 2.55) / 100 + ' ' + Math.round(col.g / 2.55) / 100 + ' ' + Math.round(col.b / 2.55) / 100;\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t});\r\n\t\t\t\t};\r\n\r\n\t\t\t\treturn [{\r\n\t\t\t\t\tcoordindex: array2dToString(coordIndex(d)),\r\n\t\t\t\t\tpoint: array2dToString(coordPoints(d)),\r\n\t\t\t\t\tcolor: array2dToString(colorFaceSet(d))\r\n\t\t\t\t}];\r\n\t\t\t};\r\n\r\n\t\t\tvar surface = element.selectAll(\".surface\").data(surfaceData);\r\n\r\n\t\t\tvar surfaceSelect = surface.enter().append(\"shape\").classed(\"surface\", true).append(\"indexedfaceset\").attr(\"coordindex\", function (d) {\r\n\t\t\t\treturn d.coordindex;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceSelect.append(\"coordinate\").attr(\"point\", function (d) {\r\n\t\t\t\treturn d.point;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceSelect.append(\"color\").attr(\"color\", function (d) {\r\n\t\t\t\treturn d.color;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceSelect.merge(surface);\r\n\r\n\t\t\tvar surfaceTransition = surface.transition().select(\"indexedfaceset\").attr(\"coordindex\", function (d) {\r\n\t\t\t\treturn d.coordindex;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceTransition.select(\"coordinate\").attr(\"point\", function (d) {\r\n\t\t\t\treturn d.point;\r\n\t\t\t});\r\n\r\n\t\t\tsurfaceTransition.select(\"color\").attr(\"color\", function (d) {\r\n\t\t\t\treturn d.color;\r\n\t\t\t});\r\n\r\n\t\t\tsurface.exit().remove();\r\n\t\t});\r\n\t};\r\n\r\n\t/**\r\n * Dimensions Getter / Setter\r\n *\r\n * @param {{x: number, y: number, z: number}} _v - 3D object dimensions.\r\n * @returns {*}\r\n */\r\n\tmy.dimensions = function (_v) {\r\n\t\tif (!arguments.length) return dimensions;\r\n\t\tdimensions = _v;\r\n\t\treturn this;\r\n\t};\r\n\r\n\t/**\r\n * X Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.xScale = function (_v) {\r\n\t\tif (!arguments.length) return xScale;\r\n\t\txScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Y Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.yScale = function (_v) {\r\n\t\tif (!arguments.length) return yScale;\r\n\t\tyScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Z Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 scale.\r\n * @returns {*}\r\n */\r\n\tmy.zScale = function (_v) {\r\n\t\tif (!arguments.length) return zScale;\r\n\t\tzScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Color Scale Getter / Setter\r\n *\r\n * @param {d3.scale} _v - D3 color scale.\r\n * @returns {*}\r\n */\r\n\tmy.colorScale = function (_v) {\r\n\t\tif (!arguments.length) return colorScale;\r\n\t\tcolorScale = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Colors Getter / Setter\r\n *\r\n * @param {Array} _v - Array of colours used by color scale.\r\n * @returns {*}\r\n */\r\n\tmy.colors = function (_v) {\r\n\t\tif (!arguments.length) return colors;\r\n\t\tcolors = _v;\r\n\t\treturn my;\r\n\t};\r\n\r\n\t/**\r\n * Dispatch On Getter\r\n *\r\n * @returns {*}\r\n */\r\n\tmy.on = function () {\r\n\t\tvar value = dispatch.on.apply(dispatch, arguments);\r\n\t\treturn value === dispatch ? my : value;\r\n\t};\r\n\r\n\treturn my;\r\n}",
"function detect3dSupport(){\n var el = document.createElement('p'),\n has3d,\n transforms = {\n 'webkitTransform':'-webkit-transform',\n 'OTransform':'-o-transform',\n 'msTransform':'-ms-transform',\n 'MozTransform':'-moz-transform',\n 'transform':'transform'\n };\n // Add it to the body to get the computed style\n document.body.insertBefore(el, null);\n for(var t in transforms){\n if( el.style[t] !== undefined ){\n el.style[t] = 'translate3d(1px,1px,1px)';\n has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);\n }\n }\n document.body.removeChild(el);\n return (has3d !== undefined && has3d.length > 0 && has3d !== \"none\");\n }",
"function resetScatterZoom() {\n window.scatter.resetZoom();\n}",
"static netScatterPlot (canvasID,position,size,data) {\n let canvas = document.getElementById(canvasID);\n let ctx = canvas.getContext('2d');\n // draw rectangle\n ctx.beginPath();\n ctx.fillStyle = 'rgb(220,220,220)';\n ctx.fillRect(position[0],position[1],size[0],size[1]);\n ctx.strokeStyle = 'rgb(0,0,0)';\n ctx.strokeRect(position[0],position[1],size[0],size[1]);\n ctx.fill();\n ctx.stroke();\n ctx.closePath();\n // draw vectors\n data.forEach(e=>{\n let x0 = position[0] + 5 + (size[0]-10)*e.start[0]; // padding = 5\n let y0 = position[1] + 5 + (size[1]-10)*(1-e.start[1]);\n let x1 = position[0] + 5 + (size[0]-10)*e.end[0]; // padding = 5\n let y1 = position[1] + 5 + (size[1]-10)*(1-e.end[1]);\n if (x0 !== x1 || y0 !== y1) {\n let p = Geometry.LineEquation(x0,y0,x1,y1);\n let L = Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0));\n let d = L/4 < 5 ? L/4 : 5; // size of triangle in the arrow\n let x2 = (x0-x1 > 0) ? x1+Math.abs(p[1])*d/Math.sqrt(p[0]*p[0]+p[1]*p[1]) : x1-Math.abs(p[1])*d/Math.sqrt(p[0]*p[0]+p[1]*p[1]);\n let y2 = (y0-y1 > 0) ? y1+Math.abs(p[0])*d/Math.sqrt(p[0]*p[0]+p[1]*p[1]) : y1-Math.abs(p[0])*d/Math.sqrt(p[0]*p[0]+p[1]*p[1]);\n let x3 = x2 + (y1-y2)/Math.sqrt(3);\n let y3 = y2 - (x1-x2)/Math.sqrt(3);\n let x4 = x2 - (y1-y2)/Math.sqrt(3);\n let y4 = y2 + (x1-x2)/Math.sqrt(3);\n // line\n ctx.beginPath();\n ctx.moveTo(x0,y0);\n ctx.lineTo(x1,y1);\n ctx.strokeStyle = 'rgb(0,0,0)';\n ctx.stroke();\n ctx.closePath();\n // triangle\n ctx.beginPath();\n ctx.moveTo(x1,y1);\n ctx.lineTo(x3,y3);\n ctx.lineTo(x4,y4);\n ctx.lineTo(x1,y1);\n ctx.fillStyle = 'rgb(0,0,0)';\n ctx.fill();\n ctx.closePath();\n }\n });\n }",
"setUse3dTransform (use3dTransform) {\n this._use3dTransform = use3dTransform\n }",
"function chartSelectZoomSeries(placeholder) {\n\n\t\tvar data = [{\n\t\t\tlabel: \"United States\",\n\t\t\tdata: [[1990, 18.9], [1991, 18.7], [1992, 18.4], [1993, 19.3], [1994, 19.5], [1995, 19.3], [1996, 19.4], [1997, 20.2], [1998, 19.8], [1999, 19.9], [2000, 20.4], [2001, 20.1], [2002, 20.0], [2003, 19.8], [2004, 20.4]]\n\t\t}, {\n\t\t\tlabel: \"Russia\", \n\t\t\tdata: [[1992, 13.4], [1993, 12.2], [1994, 10.6], [1995, 10.2], [1996, 10.1], [1997, 9.7], [1998, 9.5], [1999, 9.7], [2000, 9.9], [2001, 9.9], [2002, 9.9], [2003, 10.3], [2004, 10.5]]\n\t\t}, {\n\t\t\tlabel: \"United Kingdom\",\n\t\t\tdata: [[1990, 10.0], [1991, 11.3], [1992, 9.9], [1993, 9.6], [1994, 9.5], [1995, 9.5], [1996, 9.9], [1997, 9.3], [1998, 9.2], [1999, 9.2], [2000, 9.5], [2001, 9.6], [2002, 9.3], [2003, 9.4], [2004, 9.79]]\n\t\t}, {\n\t\t\tlabel: \"Germany\",\n\t\t\tdata: [[1990, 12.4], [1991, 11.2], [1992, 10.8], [1993, 10.5], [1994, 10.4], [1995, 10.2], [1996, 10.5], [1997, 10.2], [1998, 10.1], [1999, 9.6], [2000, 9.7], [2001, 10.0], [2002, 9.7], [2003, 9.8], [2004, 9.79]]\n\t\t}, {\n\t\t\tlabel: \"Denmark\",\n\t\t\tdata: [[1990, 9.7], [1991, 12.1], [1992, 10.3], [1993, 11.3], [1994, 11.7], [1995, 10.6], [1996, 12.8], [1997, 10.8], [1998, 10.3], [1999, 9.4], [2000, 8.7], [2001, 9.0], [2002, 8.9], [2003, 10.1], [2004, 9.80]]\n\t\t}, {\n\t\t\tlabel: \"Sweden\",\n\t\t\tdata: [[1990, 5.8], [1991, 6.0], [1992, 5.9], [1993, 5.5], [1994, 5.7], [1995, 5.3], [1996, 6.1], [1997, 5.4], [1998, 5.4], [1999, 5.1], [2000, 5.2], [2001, 5.4], [2002, 6.2], [2003, 5.9], [2004, 5.89]]\n\t\t}];\n\n\t\tvar options = {\n\t\t\tseries: {\n\t\t\t\tlines: {\n\t\t\t\t\tshow: true,\n\t\t\t\t\tlineWidth: 2, \n\t\t\t\t\tfill: false\n\t\t\t\t},\n\t\t\t\tpoints: {\n\t\t\t\t\tshow: true, \n\t\t\t\t\tlineWidth: 3,\n\t\t\t\t\tfill: true,\n\t\t\t\t\tfillColor: \"#fafafa\"\n\t\t\t\t},\n\t\t\t\tshadowSize: 0\n\t\t\t},\n\t\t\tgrid: {\n\t\t\t\thoverable: true, \n\t\t\t\tclickable: true,\n\t\t\t\tborderWidth: 0,\n\t\t\t\ttickColor: \"#E4E4E4\",\n\t\t\t\t\n\t\t\t},\n\t\t\tlegend: {\n\t\t\t\tnoColumns: 3,\n\t\t\t\tlabelBoxBorderColor: \"transparent\",\n\t\t\t\tbackgroundColor: \"transparent\"\n\t\t\t},\n\t\t\txaxis: {\n\t\t\t\ttickDecimals: 0,\n\t\t\t\ttickColor: \"#fafafa\"\n\t\t\t},\n\t\t\tyaxis: {\n\t\t\t\tmin: 0\n\t\t\t},\n\t\t\tcolors: [\"#d9d9d9\", \"#5399D6\", \"#d7ea2b\", \"#f30\", \"#E7A13D\"],\n\t\t\ttooltip: true,\n\t\t\ttooltipOpts: {\n\t\t\t\tcontent: '%s: %y'\n\t\t\t},\n\t\t\tselection: {\n\t\t\t\tmode: \"x\"\n\t\t\t}\n\t\t};\n\n\t\tvar plot = $.plot(placeholder, data, options);\n\n\t\tplaceholder.bind(\"plotselected\", function (event, ranges) {\n\n\t\t\tplot = $.plot(placeholder, data, $.extend(true, {}, options, {\n\t\t\t\txaxis: {\n\t\t\t\t\tmin: ranges.xaxis.from,\n\t\t\t\t\tmax: ranges.xaxis.to\n\t\t\t\t}\n\t\t\t}));\n\t\t});\n\n\t\t$('#reset-chart-zoom').click( function() {\n\t\t\tplot.setSelection({\n\t\t\t\txaxis: {\n\t\t\t\t\tfrom: 1990,\n\t\t\t\t\tto: 2004\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}",
"function initChart(jsonarray) {\n plotedPoints=plotedPoints+jsonarray.length;\n //c3.js é uma biblioteca para plotar gráficos\n //veja a documentação do C3 em http://c3js.org/reference.html e exemplos em http://c3js.org/examples.html\n chart = c3.generate({\n transition: {\n //duration: 200//tempo do efeito especial na hora de mostrar o gráfico\n },\n bindto: \"#\" + chart_bindToId,//indica qual o ID da div em que o gráfico deve ser desenhado\n zoom: {\n enabled: true //permite ou não o zoom no gráfico\n },\n point: {\n show: false//mostra ou esconde as bolinhas na linha do gráfico\n },\n\n data: {\n json:jsonarray,// dados json a serem plotados\n\n keys: {\n x: chart_XData,//item do json correspondente ao eixo X\n value: [chart_YData] ,//item do json correspondente ao eixo Y\n },\n names: {\n [chart_YData]: chart_LineName//nome da linha plotada\n }\n ,\n colors: {\n [chart_YData]: '#E30613'//cor da linha\n }\n\n },\n axis: {\n x: {\n type : 'timeseries',//tipo do gráfico a ser plotado\n tick: {\n format: chart_Xformat,//formato dos dados no eixo X\n rotate: 45//rotação do texto dos dados no eixo X\n },\n label: {\n text: chart_XLabel,//nome do eixo X\n position: 'inner-middle'//posição do nome do eixo X\n }\n\n },\n\n y: {\n label: {\n text: chart_YLabel,//nome do eixo Y\n position: 'outer-middle'//posição do nome do eixo Y\n }\n }\n },\n\n tooltip: {\n show: true,\n format: {\n value: function (value, ratio, id, index) { return value + \" \" + chart_TooltipUnit; }\n }\n }\n });\n }",
"function updateHighligtedSchool() {\n\n //Gets the URN the user has searched for as an integer\n var newSchool = getSchool();\n\n\n if (newSchool !== undefined) {\n\n //Gets the y axis label of the current data been displayed\n var yAxisLabel = window.scatter.options.scales.yAxes[0].scaleLabel.labelString;\n\n var DataIndex = getDataIndex(yAxisLabel);\n\n //Generate the new data for the chart\n var newScatterData = generateData(DataIndex, schoolResults, newSchool);\n\n //Only update the scatterChart if the URN could be found\n if (newScatterData !== null) {\n\n selectedSchool = newSchool;\n\n var newSchools = newScatterData[1];\n var newData = newScatterData[0];\n\n //Update the school names labels list\n window.scatter.data.datasets[1].labels = newSchools.slice(1, newSchools.length - 1);\n\n //Update the x and y data for the chart\n window.scatter.data.datasets[1].data = newData.slice(1, newData.length - 1);\n\n //Update the data for the school data point to be in a different colour\n window.scatter.data.datasets[0].data = [newData[0]];\n window.scatter.data.datasets[0].label = newSchools[0];\n window.scatter.data.datasets[0].labels = [newSchools[0]];\n\n resetScatterZoom();\n\n window.scatter.update();\n\n }\n\n }\n\n}",
"function setTraces(){\n\n trace1 = {\n x: w,\n y: dampl, \n name: 'Displacement',\n type: 'scatter',\n mode: \"lines\",\n marker: {color: cDisp}\n };\n trace2 = {\n x: w, \n y: vampl, \n name: 'Velocity',\n type: 'scatter',\n mode: 'lines',\n marker: {color: cVel}\n };\n trace3 = {\n x: w, \n y: aampl, \n name: 'Acceleration',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cAcc}\n };\n\n trace4 = {\n x: din,\n y: dout, \n name: 'Displacement',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cDisp}\n };\n trace5 = {\n x: vin, \n y: vout, \n name: 'Velocity',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cVel}\n };\n trace6 = {\n x: ain, \n y: aout, \n name: 'Acceleration',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cAcc}\n };\n\n trace7 = {\n x: w,\n y: phased, \n name: 'Displacement',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cDisp}\n };\n trace8 = {\n x: w, \n y: phasev, \n name: 'Velocity',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cVel}\n };\n trace9 = {\n x: w, \n y: phasea, \n name: 'Acceleration',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cAcc}\n };\n\n \n\n data1 = [trace1, trace2, trace3];\n data2 = [trace4, trace5, trace6];\n data3 = [trace7, trace8, trace9];\n\n layout1= {\n autosize: true,\n margin:{\n l:50, r:10, b:45, t:10\n },\n xaxis:{title:'Frequency (rad/s)'},\n yaxis:{title:'Magnitude'},\n legend: {x: 0, y: 10, orientation: \"h\"},\n showlegend: false,\n font: {family: \"Fira Sans\", size:12} \n};\n\n layout2= {\n margin:{\n l:50, r:10, b:45, t:10\n },\n legend: {x: 50, y: 10, orientation: \"h\"\n },\n showlegend: false,\n xaxis: {title:'In-phase Component'},\n yaxis: {scaleanchor: \"x\",title:'Out-of-phase Component'},\n\n font: {\n family: \"Fira Sans\", size:12\n }\n};\n\nlayout3= {\n autosize: true,\n margin:{\n l:50, r:10, b:45, t:10\n },\n legend: {x: 50, y: 1, orientation: \"v\"\n },\n xaxis:{title:'Frequency (rad/s)'},\n yaxis:{title:'Phase (rad)'},\n font: {\n family: \"Fira Sans\", size:12\n }\n\n};\n\n}",
"function bringMixedScaleLineSeriesToFront(contentLayer) {\r\n // debugger;\r\n var pItems = contentLayer.pathItems;\r\n // Is there a zero line?\r\n var zeroLine = lookForElement(contentLayer, 'pathItems', 'axis-zero-line');\r\n if (typeof zeroLine === 'undefined') {\r\n return;\r\n }\r\n // The problem is that I have to work backwards to restructure in the\r\n // same order as Sibyl; but if I re-stack on the fly, that messes up\r\n // the structure, so that series get 'left behind'\r\n // get an array of names\r\n var pNameArray = [];\r\n for (var pNo = 0; pNo < pItems.length; pNo ++) {\r\n var thisPath = pItems[pNo];\r\n if (thisPath.name.search('line-series-path-') >= 0) {\r\n // The array is 'back to front'\r\n pNameArray.unshift(thisPath.name);\r\n }\r\n }\r\n // Now move all the series, as named in the array, to the front\r\n // (i.e., in front of any zero line)\r\n for (var elNo in pNameArray) {\r\n var pName = pNameArray[elNo];\r\n var thisPath = pItems[pName];\r\n thisPath.move(contentLayer, ElementPlacement.PLACEATBEGINNING);\r\n }\r\n}",
"init() {\n const series = this.chartData.series;\n const seriesKeys = Object.keys(series);\n\n for (let ix = 0, ixLen = seriesKeys.length; ix < ixLen; ix++) {\n this.addSeries(seriesKeys[ix], series[seriesKeys[ix]]);\n }\n\n if (this.chartData.data.length) {\n this.createChartDataSet();\n }\n }",
"function debug_drawRawClusterNo1()\r\n{\r\n var pts = g_3dClusters[0];\r\n for (var i=1; i< pts.length; i++)\r\n {\r\n var p1 = pts[i-1].normalize().multiplyScalar(sphereRadius);\r\n var p2 = pts[i].normalize().multiplyScalar(sphereRadius);\r\n setShortArc(p1, p2, 4, 'red');\r\n }\r\n\r\n spot(g_3dClusterCenters[0].clone().multiplyScalar(sphereRadius),'yellow');\r\n}",
"function loadSeries()\n {\n for(var i = 2, j = 0; i < data.length, j < series_names.length; i++, j++)\n {\n chart.addSeries({name: series_names[j], data : data[i]});\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Discription: return an array of cases with random amounts enclosed in each. | static populateCases() {
let casesArray = [];
let amounts = [
0.01,
1,
5,
10,
25,
50,
75,
100,
200,
300,
400,
500,
750,
1000,
5000,
10000,
25000,
50000,
75000,
100000,
200000,
300000,
400000,
500000,
750000,
1000000
];
for (var i = 0; i < 26; i++) {
//get a random number from the amounts array
let ranIndex = Math.floor(Math.random() * (amounts.length));
let ranAmount = amounts[ranIndex];
casesArray.push(new CaseClass(i + 1, ranAmount));
//take the selected case out of the case list so there are no duplicates of amounts.
amounts.splice(ranIndex,1);
}
return casesArray;
} | [
"function generate_RandArray(max, min, no_bars=4){\n let lab_array = [];\n for (let i = 0; i<no_bars; i++){\n let rand_val = (Math.random()*(max-min))+min;\n lab_array.push(rand_val);\n }\n return lab_array;\n }",
"function create_dummy_array(n){\n var arr = [];\n for(var i = 0; i < n; i++){\n arr.push(Math.floor(Math.random() * 10));\n }\n return arr;\n}",
"dealRandomCardsFromDeck(nb) {\n\n let out = new Array(nb);\n let temp = new Card();\n\n for(var i = 0; i < nb; i++) {\n do {\n temp = this.deck.randomCardObject();\n } while(this.cardsDealt.includes(temp));\n\n // Add the card to the cards dealt and to the output array\n this.cardsDealt.push(temp);\n out[i] = temp;\n }\n\n return out;\n }",
"getRandomSolution() {\n var sol = []\n for (let g = 0; g < this.genesCount; g++) {\n // 0 or 1 randomly\n sol.push(Math.round(Math.random()))\n }\n\n return sol;\n }",
"function randomSequence(){\n\t\t\tvar sequence = [];\n\t\t\tfor(var i = 0; i < 20; i++){\n\t\t\t\tsequence.push(Math.floor((Math.random()*100)%4)+1);\n\t\t\t}\n\t\t\treturn sequence;\n\t\t}",
"distribution(n: number): RandomArray {\n let triangularArray: RandomArray = [],\n random: RandomArray = (prng.random(n): any);\n for(let i: number = 0; i < n; i += 1){\n triangularArray[i] = this._random(random[i]);\n }\n return triangularArray;\n }",
"function giveMeRandom(n) {\n let array = [];\n for (let x = 0; x < n; x++) {\n array.push(Math.floor(Math.random() * 10));\n }\n return array;\n}",
"function random(r) {\n var desks = []\n var firstDesk = Math.floor(Math.random() * r);\n desks[0] = firstDesk;\n console.log('firstDesk: ', firstDesk);\n var secondDesk = Math.floor(Math.random() * r);\n while(firstDesk === secondDesk) {\n secondDesk = Math.floor(Math.random() * r);\n\n }\n desks[1] = secondDesk;\n console.log('secondDesk: ', secondDesk);\n return desks;\n}",
"function getRandomArray(min, max, length) {\n const ans = [];\n for (let i = 0; i < length; i++) {\n const newNumber = Math.floor(Math.random() * (max - min) + min);\n ans.push(newNumber);\n }\n return ans;\n}",
"function generateTestStrings(cnt, len) {\n\tlet test = [];\n\tfor(let i=0; i<cnt; i++) {\n\t\t// generate a string of the specified len\n\t\ttest[i] = getRandomString(len, 0, 65535);\n//\t\ttest[i] = getRandomString(len, 0, 55295);\n\t}\n\treturn test;\n}",
"function pickCards(array) {\n let startArr = array;\n let pickedArr = [];\n for (let i = 0; i < 8; i++) {\n let ranNum = (Math.floor(Math.random() * startArr.length));\n pickedArr.push(startArr[ranNum]);\n pickedArr.push(startArr[ranNum]);\n startArr.splice(ranNum, 1);\n }\n return pickedArr;\n}",
"function makeBeat(probs){\n var beatArray = []; //thing to be returned\n var currentNote = -1; //variable per note, not per beat\n for (var i = 0; i < 16; i++){//for each of 16 possible beat slots\n var roll = Math.random(); //roll a random number between 0 and 1\n if (roll < probs[i]){ //if we beat the probability for this note,\n currentNote += 1; //a new note!\n beatArray[currentNote] = i/16; //start playing new note at this beat's time\n }\n }\n return beatArray;\n}",
"function crystValues(){\n for (i = 0; i < gemArray.length; i++) {\n gemArray[i] = Math.floor(Math.random() * 12) + 1;\n} \n//prints values of each item\n //console.log(gemArray);\n}",
"function CookiesEachHour(min, max, avg) {\n var customerNumArray = [];\n for (let index = 0; index < hour.length; index++) {\n customerNumArray.push(Math.floor(getRandomNum(min, max) * avg));\n\n }\n return customerNumArray;\n}",
"createMatingPool() {\n let matingPool = [],\n limit;\n this.chromosomes.forEach((chromosome, index) => {\n limit = chromosome.fitness * 1000;\n for (let i = 0; i < limit; i++) matingPool.push(index);\n });\n return matingPool;\n }",
"constructor() {\n let chosenNums = [];\n for (let i = 0; i < 5; i++) { //row\n this.cardArr.push([]);\n for (let j = 0; j < 5; j++) { //column\n const num = Math.floor(Math.random() * 15) + 15 * j;\n if (chosenNums.indexOf(num) === -1) {\n chosenNums.push(num);\n this.cardArr[i][j] = new Cell(num, i, j);\n } else {\n j--;\n }\n }\n }\n this.cardArr[2][2] = new Cell(75, 2, 2); //75 is free space\n }",
"function crystals(min,max){return Math.floor(Math.random()*(max-min))+min;\n}",
"function randomTestGenerator(int) {\n\n // declare empty array\n var testArray = [];\n\n // create function to return random letter of alphabet\n function chooseRandomLetter() {\n\n // create array with each letter of alphabet as separate items\n var alphabetArray = [\"a\", \"b\", \"c\", \"d\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\",\n \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\",\n \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"];\n\n // create randomLetter variable that picks random item from alphabetArray\n var randomLetter = alphabetArray[Math.floor((Math.random() * 27) + 1)];\n\n // return randomLetter\n return randomLetter;\n };\n\n // create function to return random word using random letters\n function chooseRandomWords() {\n\n // declare empty string randomWord\n var randomWord = \"\";\n\n // loop between 1 and 10 times\n // add a random letter to the randomWord string each time\n for (var i = 0; i < (Math.floor((Math.random() * 10) + 1)); i++) {\n randomWord += chooseRandomLetter();\n };\n\n // return randomWord\n return randomWord;\n };\n\n // loop int amount of times\n // add a random word to the testArray each time\n for (var i = 0; i < int; i++) {\n testArray.push(chooseRandomWords())\n };\n\n // return testArray\n return testArray;\n}",
"function create(n){\n var n;\n var arr = [];\n for (i=1; i<=n; i++){\n if (i%2==0 && i%3==0 && i%5==0){\n arr.push(\"yu-gi-oh\");\n }else if (i%2==0 && i%3==0){\n arr.push(\"yu-gi\");\n }else if (i%2==0 && i%5==0){\n arr.push(\"yu-oh\");\n } else if (i%3==0 && i%5==0){\n arr.push(\"gi-oh\");\n } else if (i%5==0){\n arr.push(\"oh\");\n } else if (i%3==0){\n arr.push(\"gi\");\n } else if (i%2==0){\n arr.push(\"yu\");\n } \n else{\n arr.push(i);\n }\n console.log(arr);\n }\n return arr;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wavetable is a table of names for nonstandard waveforms. The table maps names to objects that have wave: and freq: properties. The wave: property is a PeriodicWave to use for the oscillator. The freq: property, if present, is a map from higher frequencies to more PeriodicWave objects; when a frequency higher than the given threshold is requested, the alternate PeriodicWave is used. | function makeWavetable(ac) {
return (function(wavedata) {
function makePeriodicWave(data) {
var n = data.real.length,
real = new Float32Array(n),
imag = new Float32Array(n),
j;
for (j = 0; j < n; ++j) {
real[j] = data.real[j];
imag[j] = data.imag[j];
}
try {
// Latest API naming.
return ac.createPeriodicWave(real, imag);
} catch (e) { }
try {
// Earlier API naming.
return ac.createWaveTable(real, imag);
} catch (e) { }
return null;
}
function makeMultiple(data, mult, amt) {
var result = { real: [], imag: [] }, j, n = data.real.length, m;
for (j = 0; j < n; ++j) {
m = Math.log(mult[Math.min(j, mult.length - 1)]);
result.real.push(data.real[j] * Math.exp(amt * m));
result.imag.push(data.imag[j] * Math.exp(amt * m));
}
return result;
}
var result = {}, k, d, n, j, ff, record, wave, pw;
for (k in wavedata) {
d = wavedata[k];
wave = makePeriodicWave(d);
if (!wave) { continue; }
record = { wave: wave };
// A strategy for computing higher frequency waveforms: apply
// multipliers to each harmonic according to d.mult. These
// multipliers can be interpolated and applied at any number
// of transition frequencies.
if (d.mult) {
ff = wavedata[k].freq;
record.freq = {};
for (j = 0; j < ff.length; ++j) {
wave =
makePeriodicWave(makeMultiple(d, d.mult, (j + 1) / ff.length));
if (wave) { record.freq[ff[j]] = wave; }
}
}
// This wave has some default filter settings.
if (d.defs) {
record.defs = d.defs;
}
result[k] = record;
}
return result;
})({
// Currently the only nonstandard waveform is "piano".
// It is based on the first 32 harmonics from the example:
// https://github.com/GoogleChrome/web-audio-samples
// /blob/gh-pages/samples/audio/wave-tables/Piano
// That is a terrific sound for the lowest piano tones.
// For higher tones, interpolate to a customzed wave
// shape created by hand, and apply a lowpass filter.
piano: {
real: [0, 0, -0.203569, 0.5, -0.401676, 0.137128, -0.104117, 0.115965,
-0.004413, 0.067884, -0.00888, 0.0793, -0.038756, 0.011882,
-0.030883, 0.027608, -0.013429, 0.00393, -0.014029, 0.00972,
-0.007653, 0.007866, -0.032029, 0.046127, -0.024155, 0.023095,
-0.005522, 0.004511, -0.003593, 0.011248, -0.004919, 0.008505],
imag: [0, 0.147621, 0, 0.000007, -0.00001, 0.000005, -0.000006, 0.000009,
0, 0.000008, -0.000001, 0.000014, -0.000008, 0.000003,
-0.000009, 0.000009, -0.000005, 0.000002, -0.000007, 0.000005,
-0.000005, 0.000005, -0.000023, 0.000037, -0.000021, 0.000022,
-0.000006, 0.000005, -0.000004, 0.000014, -0.000007, 0.000012],
// How to adjust the harmonics for the higest notes.
mult: [1, 1, 0.18, 0.016, 0.01, 0.01, 0.01, 0.004,
0.014, 0.02, 0.014, 0.004, 0.002, 0.00001],
// The frequencies at which to interpolate the harmonics.
freq: [65, 80, 100, 135, 180, 240, 620, 1360],
// The default filter settings to use for the piano wave.
// TODO: this approach attenuates low notes too much -
// this should be fixed.
defs: { wave: 'piano', gain: 0.5,
attack: 0.002, decay: 0.25, sustain: 0.03, release: 0.1,
decayfollow: 0.7,
cutoff: 800, cutfollow: 0.1, resonance: 1, detune: 0.9994 }
}
});
} | [
"function SpectrumToWaves(notePowers){\n\n // This function takes in notePowers, which attributes to each note to a given 'power'. \n\n // For each octave these powers are normalize. \n var normedOctaves = []; \n // Looping through the octaves: \n for( let i = 0; i < notePowers.length; i++){\n var proms = notePowers[i].tones.map( x => x.prominence); \n var normedProms = normalizeArray(proms);\n normedOctaves.push(normedProms); \n // Accumulate the note powers: \n if(i == 0){\n var accumulatedPowers = notePowers[i].tones.map( x => x.power); \n }\n else{\n accumulatedPowers = notePowers[i].tones.map( (x,index) => {\n var accPow = (x.power + accumulatedPowers[index]) / 2; \n return accPow; \n }\n )\n }\n }\n\n // Okay, we have to normalize the accumulated powers array, which will then serve to 'weight' the notes WRT one another. \n accumulatedPowers = normalizeArray(accumulatedPowers); \n\n // Prepare the output: \n var waveTable = {}; \n waveTable.table = normedOctaves; \n waveTable.weights = accumulatedPowers; \n\n // Output the 'waveTable'! \n return waveTable; \n}",
"function oneTestWave() {\n clearWaves();\n frozen = 1;\n lastRenderMillis = 1;\n\n for (var j = 0; j < wavesLength; j++) {\n writeWave(j, [j/10.0, .5], 1/1000.0, .65, decayingSineWave); \n }\n }",
"function randomWaves() {\n var randomX = randomMarkov(.1, .1, .4),\n randomY = randomMarkov(.1, .1, .4),\n randomTime = randomMarkov(.5, 0),\n randomHue = randomMarkov(.05, .1, .5);\n for (var i = 0; i < wavesLength; i++) {\n writeWave(i, [randomX(), randomY()], randomTime(), randomHue(), decayingSineWave);\n }\n }",
"function WaveDetector() {\r\n\tvar fader = Fader(Orientation.X, 100);\r\n\tfader.autoMoveToContain = true;\r\n\tfader.driftAmount = 15;\r\n\r\n\tvar api = {\r\n\t\tonattach : onattach,\r\n\t\tondetach : ondetach,\r\n\t\t// property: fader\r\n\t\t// The <Fader> used internally by the wave detector\r\n\t\tfader : fader,\r\n\t\t// property: numberOfWaves\r\n\t\t// How many waves before we trigger the <wave> event\r\n\t\tnumberOfWaves : 5,\r\n\t}\r\n\tvar events = Events();\r\n\tevents.eventify(api);\r\n\r\n\tvar edgebuffer = []\r\n\tvar lastEdge = -1;\r\n\r\n\tfader.addEventListener('edge', function(f) {\r\n\t\tvar now = (new Date()).getTime();\r\n\t\twhile ((edgebuffer.length > 0) && (now - edgebuffer[0] > 2000)) edgebuffer.shift();\r\n\t\tif (edgebuffer.length == 0) lastEdge = -1;\r\n\t\tif (lastEdge != f.value) edgebuffer.push(now);\r\n\t\tlastEdge = f.value;\r\n\r\n\t\tif (edgebuffer.length >= api.numberOfWaves) {\r\n\t\t\tevents.fireEvent('wave', api);\r\n\t\t\tedgebuffer=[];\r\n\t\t}\r\n\t});\r\n\r\n\tfunction onattach(target) {\r\n\t\ttarget.addListener(fader);\r\n\t}\r\n\tfunction ondetach(target) {\r\n\t\ttarget.removeListener(fader);\r\n\t}\r\n\r\n\treturn api;\r\n}",
"function sendWaves(gl) {\n sendDataViaTexture(gl, program.wavesSampler, \"wavesSampler\", waves);\n }",
"function waves () {\r\n\tif (waveEnd && currentWave !== 5) {\r\n\t\tif (clock > waveTimer+150 && clock > 400) {\r\n\t\t\twaveEnd = false;\r\n\t\t\tmobToSend = 0;\r\n\t\t\tmobWaveSent = false;\r\n\t\t\tfor (let i = 0; i < mobs.length; i++) {\r\n\t\t\t\tMatter.Body.setVelocity(mobs[i].body, {\r\n\t\t\t\t\tx: 0,\r\n\t\t\t\t\ty: 0\r\n\t\t\t\t})\r\n\t\t\t\tWorld.add(engine.world, mobs[i].body)\r\n\t\t\t\tmobs[i].alive = true;\r\n\t\t\t}\r\n\t\t\tcurrentWave++;\r\n\t\t\tconsole.log(currentWave)\r\n\t\t}\r\n\t}\r\n\tif (currentWave === 5) {\r\n\t\tconsole.log(\"I plan to have some sort of power up choice for every five waves\")\r\n\t}\r\n\tif (!waveEnd && !mobWaveSent) {\r\n\t\twaveState = 80;\r\n\t\tif (clock >= waveTimer+waveState) {\r\n\t\t\twaveTimer = clock;\r\n\t\t\tmobs[mobToSend].chasing = true;\r\n\t\t\t//console.log(mobs);\r\n\t\t\tmobToSend++;\r\n\t\t}\r\n\t}\r\n}",
"function createWavesForActiveNotes() {\n waves.forEach(wave => wave.stop());\n waves = [];\n for (let note in window.noteConfig) {\n if (window.noteConfig.hasOwnProperty(note)) {\n if (window.noteConfig[note].enabled) {\n waves.push(createWave(note));\n }\n }\n }\n}",
"function texttoMusic(string) {\n \n //There are three different synths users can choose.\n switch (selectedSound) {\n case 1:\n var synth = new Tone.SimpleSynth().fan(waveform).toMaster();\n break;\n\n case 2:\n var synth = new Tone.MonoSynth().fan(waveform).toMaster();\n break;\n\n case 3:\n var synth = new Tone.SimpleFM().fan(waveform).toMaster();\n break;\n }\n \n //Generates a waveform to add to the novelty.\n //If a waveform already exists this skips creation.\n if(waveContext == 0) {\n //the waveform HTML generation.\n waveContext = $(\"<canvas>\", {\n \"id\" : \"waveform\"\n }).appendTo(\"#soundgroup\").get(0).getContext(\"2d\");\n }\n\t\n var waveformGradient;\n\n //Analyses and draws the waveform based on incoming data from the synth\n function drawWaveform(values){\n //draw the waveform\n waveContext.clearRect(0, 0, canvasWidth, canvasHeight);\n var values = waveform.analyse();\n\t\twaveContext.beginPath();\n\t\twaveContext.lineJoin = \"round\";\n\t\twaveContext.lineWidth = 6;\n\t\twaveContext.strokeStyle = waveformGradient;\n\t\twaveContext.moveTo(0, (values[0] / 255) * canvasHeight);\n\t\tfor (var i = 1, len = values.length; i < len; i++){\n \t\tvar val = values[i] / 255;\n\t\t var x = canvasWidth * (i / len);\n\t\t var y = val * canvasHeight;\n\t\t waveContext.lineTo(x, y);\n\t\t}\n\t\twaveContext.stroke();\n\t }\n\n //Calculates the size the waveform canvas element should be.\n var canvasWidth, canvasHeight;\n function sizeCanvases(){\n\t canvasWidth = $(\"#page\").width();\n\t canvasHeight = 255;\n\t waveContext.canvas.width = canvasWidth;\n\t waveContext.canvas.height = canvasHeight;\n\n\t //Form the gradient the waveform will use.\n\t waveformGradient = waveContext.createLinearGradient(0, 0, canvasWidth, canvasHeight);\n\t waveformGradient.addColorStop(0, \"#ddd\");\n\t waveformGradient.addColorStop(1, \"#000\"); \n }\n\n sizeCanvases();\n\t \n //Loops while the synth is outputting in order to draw the waveform.\n function loop(){\n requestAnimationFrame(loop);\n //Get waveform values in order to draw it.\n var waveformValues = waveform.analyse();\n drawWaveform(waveformValues);\n }\n loop();\n \n var j = 0.0;\n var k = \"\";\n \n //Converts ASCII to a note based on the tonemap.\n for(i = 0; i < string.length; i++) {\n var ascii = string[i].charCodeAt();\n if (ascii > 31 && ascii < 84) {\n ascii = ascii - 32;\n }\n else {\n ascii = ascii - 84;\n }\n k = \"+\" + j;\n \n //Triggers the note at the set interval k.\n synth.triggerAttack(tonemap[ascii], k);\n j += 0.25;\n }\n //Stops the synth after all notes have been played.\n synth.triggerRelease(k);\n \n //Starts the progress bar.\n progressBar(j);\n}",
"makeWaveforms(parent, waveformDisplay, sampleSets) {\n clearElement(parent);\n const zoomControls = document.createElement(\"div\");\n zoomControls.appendChild(waveformDisplay.makeZoomControls());\n parent.appendChild(zoomControls);\n for (const sampleSet of sampleSets) {\n let label = document.createElement(\"p\");\n label.innerText = sampleSet.label;\n parent.appendChild(label);\n let canvas = document.createElement(\"canvas\");\n canvas.width = 800;\n canvas.height = 400;\n waveformDisplay.addWaveform(canvas, sampleSet.samples);\n parent.appendChild(canvas);\n }\n this.onHighlight.subscribe(highlight => waveformDisplay.setHighlight(highlight));\n this.onSelection.subscribe(selection => waveformDisplay.setSelection(selection));\n this.onDoneSelecting.subscribe(source => {\n if (source !== waveformDisplay) {\n waveformDisplay.doneSelecting();\n }\n });\n waveformDisplay.onHighlight.subscribe(highlight => this.setHighlight(highlight));\n waveformDisplay.onSelection.subscribe(selection => this.setSelection(selection));\n waveformDisplay.onDoneSelecting.subscribe(source => this.doneSelecting(source));\n waveformDisplay.zoomToFitAll();\n }",
"waveMsg (waveNum) {\n\t\tthis.events.emit('displayWaveW', waveNum);\n\t}",
"function create_frequency_container(frequency_value, parent_table, freq_flag) {\n\tvar new_row = document.createElement('tr');\n\tnew_row.className = 'space_under';\n\tvar freq_data = document.createElement('td');\n\tfreq_data.style.width = '12em';\n\tfreq_data.style.verticalAlign = 'top';\n\tvar freq_value = document.createElement('span');\n\tvar span_class = \"word_span\";\n\tif (WORD_FREQ_CLASSES[freq_flag]) {\n\t\tspan_class += WORD_FREQ_CLASSES[freq_flag];\n\t}\n\tfreq_value.className = span_class;\n\tfreq_value.innerHTML = \"Frequency: \" + frequency_value;\n\tfreq_data.appendChild(freq_value);\n\twords_data = document.createElement('td');\n\twords_data.style.width = '75%';\n\tnew_row.appendChild(freq_data);\n\tnew_row.appendChild(words_data);\n\tparent_table.appendChild(new_row);\n\treturn words_data;\n}",
"function changeWaveform(waveShape){\n oscillators.forEach(osc =>\n osc.type = waveShape)\n}",
"function sampleTable(){\n var htm=[];\n htm.push(\"<table id='samples' class='table table-condensed table-hover'>\");\n htm.push(\"<thead>\");\n htm.push(\"<th>#</th>\");\n //htm.push(\"<th>Sample name</th>\");\n htm.push(\"<th>Size</th>\");\n //htm.push(\"<th>Finetune</th>\");\n //htm.push(\"<th>Vol</th>\");\n htm.push(\"<th>loop</th>\");\n htm.push(\"<th>len</th>\");\n htm.push(\"</thead>\");\n htm.push(\"<tbody>\");\n var totalbytes=0;\n var totalsamples=0;\n for(var i=0;i<31;i++){\n //if(module.sample[i].length<1)continue;\n totalsamples++;\n totalbytes+=module.sample[i].length;\n htm.push(\"<tr id='smpl_\"+i+\"'>\");\n htm.push(\"<td>\"+hb(i+1));\n //htm.push(\"<td>\"+module.sample[i].name);\n htm.push(\"<td style='text-align:right'>\"+module.sample[i].length);\n //htm.push(\"<td>\"+module.sample[i].finetune);\n //htm.push(\"<td>\"+module.sample[i].volume);\n htm.push(\"<td style='text-align:right'>\"+module.sample[i].loopstart);\n htm.push(\"<td style='text-align:right'>\"+module.sample[i].looplength);\n \n //console.log(this.sample[i].name,this.sample[i].length,this.sample[i].finetune,this.sample[i].volume,this.sample[i].loopstart,this.sample[i].looplength);\n }\n //\n htm.push(\"</tbody>\");\n htm.push(\"<tfoot>\");\n htm.push(\"<tr>\");\n htm.push(\"<td>\");\n htm.push(\"<td>\"+totalsamples+\" sample(s)\");\n //htm.push(\"<td style='text-align:right'><b>Total bytes :\");\n htm.push(\"<td style='text-align:right'><b>\"+totalbytes+\"b\");\n htm.push(\"<td></td>\");\n htm.push(\"</tr>\");\n htm.push(\"</tfoot>\");\n htm.push(\"</table>\");\n return htm.join(\"\");\n}",
"function WeightedSound(loop,sounds,weights){var _this=this;/** When true a Sound will be selected and played when the current playing Sound completes. */this.loop=false;this._coneInnerAngle=360;this._coneOuterAngle=360;this._volume=1;/** A Sound is currently playing. */this.isPlaying=false;/** A Sound is currently paused. */this.isPaused=false;this._sounds=[];this._weights=[];if(sounds.length!==weights.length){throw new Error('Sounds length does not equal weights length');}this.loop=loop;this._weights=weights;// Normalize the weights\nvar weightSum=0;for(var _i=0,weights_1=weights;_i<weights_1.length;_i++){var weight=weights_1[_i];weightSum+=weight;}var invWeightSum=weightSum>0?1/weightSum:0;for(var i=0;i<this._weights.length;i++){this._weights[i]*=invWeightSum;}this._sounds=sounds;for(var _a=0,_b=this._sounds;_a<_b.length;_a++){var sound=_b[_a];sound.onEndedObservable.add(function(){_this._onended();});}}",
"function pulsesToWatt(pulses) {\n return pulsesToKwh(pulses * 1000);\n}",
"constructor(sampleRate, channels = 1, bitsPerSample = 16) {\r\n super();\r\n this.sampleRate = sampleRate;\r\n this.channels = channels;\r\n this.bitsPerSample = bitsPerSample;\r\n // Write WAV file header\r\n // Reference: http://www.topherlee.com/software/pcm-tut-wavformat.html\r\n const headerBuffer = new ArrayBuffer(44);\r\n const header = new DataStream(headerBuffer);\r\n // 'RIFF' indent\r\n header.writeChars('RIFF');\r\n // filesize (set later)\r\n header.writeUint32(0);\r\n // 'WAVE' indent\r\n header.writeChars('WAVE');\r\n // 'fmt ' section header\r\n header.writeChars('fmt ');\r\n // fmt section length\r\n header.writeUint32(16);\r\n // specify audio format is pcm (type 1)\r\n header.writeUint16(1);\r\n // number of audio channels\r\n header.writeUint16(this.channels);\r\n // audio sample rate\r\n header.writeUint32(this.sampleRate);\r\n // byterate = (sampleRate * bitsPerSample * channelCount) / 8\r\n header.writeUint32((this.sampleRate * this.bitsPerSample * this.channels) / 8);\r\n // blockalign = (bitsPerSample * channels) / 8\r\n header.writeUint16((this.bitsPerSample * this.channels) / 8);\r\n // bits per sample\r\n header.writeUint16(this.bitsPerSample);\r\n // 'data' section header\r\n header.writeChars('data');\r\n // data section length (set later)\r\n header.writeUint32(0);\r\n this.header = header;\r\n this.pcmData = null;\r\n }",
"function scalePlayer(unit, scale, direction, tempo) {\n\n\n// overwrite players interval variables with toneIndex values for scale type\n\n// if statement for reversing intervalic direction\n\n if (direction === \"up\"){\n\n first = unit[0];\n second = unit[1];\n third = unit[2];\n fourth = unit[3];\n fifth = unit[4];\n sixth = unit[5];\n seventh = unit[6];\n octave = unit[7];\n } else if (direction === \"down\"){\n first = unit[7];\n second = unit[6];\n third = unit[5];\n fourth = unit[4];\n fifth = unit[3];\n sixth = unit[2];\n seventh = unit[1];\n octave = unit[0];\n }\n\n // keySelector value brought in as 'scale' -- modifies oscillator.detune via 'detune'\n\n if (scale === \"B\") {\n var detune = 100;\n } else if (scale === \"A#/Bb\"){\n var detune = 200;\n } else if (scale === \"A\"){\n var detune = 300;\n } else if (scale === \"G#/Ab\"){\n var detune = 400;\n } else if (scale === \"G\"){\n var detune = 500;\n } else if (scale === \"F#/Gb\"){\n var detune = 600;\n } else if (scale === \"F\"){\n var detune = 700;\n } else if (scale === \"E\"){\n var detune = 800;\n } else if (scale === \"D#/Eb\"){\n var detune = 900;\n } else if (scale === \"D\"){\n var detune = 1000;\n } else if (scale === \"C#/Db\"){\n var detune = 1100;\n } else {\n var detune = 0;\n }\n\n// if statement makes sure ALL needed variables are in-function before allowing the synth to instantiate and trigger\n\n if ((unit !== undefined) && (scale !== undefined) && (direction !== undefined)){\n\n// initializes WebAudio API\n console.log(tempo);\n\n var oscillator = context.createOscillator();\n var gain = context.createGain();\n gain.value = .5\n\n oscillator.type = 'sine';\n\n oscillator.detune.value = detune;\n\n var quarterNoteTime = 60/tempo;\n\n var startTime = 1\n\n oscillator.frequency.setValueAtTime(first, startTime)\n oscillator.frequency.setValueAtTime(second, startTime + quarterNoteTime)\n oscillator.frequency.setValueAtTime(third, startTime + 2*quarterNoteTime)\n oscillator.frequency.setValueAtTime(fourth, startTime+ 3*quarterNoteTime)\n oscillator.frequency.setValueAtTime(fifth, startTime+ 4*quarterNoteTime)\n oscillator.frequency.setValueAtTime(sixth, startTime+ 5*quarterNoteTime)\n oscillator.frequency.setValueAtTime(seventh, startTime+ 6*quarterNoteTime)\n oscillator.frequency.setValueAtTime(octave, startTime+ 7*quarterNoteTime)\n\n//\n\n oscillator.connect(gain)\n gain.connect(context.destination)\n\n oscillator.start(startTime)\n gain.gain.linearRampToValueAtTime(0, startTime+ 8*quarterNoteTime + 1)\n oscillator.stop(startTime + 8*quarterNoteTime + 2)\n\n }\n}",
"function createTableElements(){\n\tvar table = document.getElementById('spectrum');\n\tvar tbdy = document.createElement('tbody');\n\n\tlet l_scans = prsm_data.prsm.ms.ms_header.scans.split(\" \") ;\n\tlet l_specIds = prsm_data.prsm.ms.ms_header.ids.split(\" \") ;\n\tconsole.log(\"l_scans : \", l_scans);\n\tconsole.log(\"l_specIds : \", l_specIds);\n\tlet l_matched_peak_count = 0;\n\tprsm_data.prsm.ms.peaks.peak.forEach(function(peak,i){\n\t\t/*\tCheck if peak contain matched_ions_num attribute\t*/\n\t\tif(peak.hasOwnProperty('matched_ions_num') && parseInt(peak.matched_ions_num)>1)\n\t\t{\n\t\t\tpeak.matched_ions.matched_ion.forEach(function(matched_ion,i){\n\t\t\t\tpeak.matched_ions.matched_ion = matched_ion ;\n\t\t\t\tloop_matched_ions(peak,i) ;\n\t\t\t})\n\t\t}\n\t\telse\n\t\t{\n\t\t\tloop_matched_ions(peak,i) ;\n\t\t}\n\t})\n\tfunction loop_matched_ions(peak,i){\n\t\t/*\tCreate row for each peak value object in the table\t*/\n\t\tvar tr = document.createElement('tr');\n\t\tid = peak.spec_id+\"peak\"+peak.peak_id;\n\t\tlet l_scan;\n\t\tif((parseInt(peak.peak_id) + 1)%2 == 0)\n\t\t{\n\t\t\tl_class = \"unmatched_peak even\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tl_class = \"unmatched_peak odd\";\n\t\t}\n\t\tif(peak.hasOwnProperty('matched_ions_num'))\n\t\t{\n\t\t\tid = id + peak.matched_ions.matched_ion.ion_type;\n\t\t\tif((parseInt(peak.peak_id) + 1)%2 == 0)\n\t\t\t{\n\t\t\t\tl_class = \"matched_peak even\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tl_class = \"matched_peak odd\";\n\t\t\t}\n\t\t\tl_matched_peak_count++;\n\t\t\t/*\tcreate a name for each row */\n\t\t\ttr.setAttribute(\"name\",peak.matched_ions.matched_ion.ion_position);\n\t\t}\n\t\t/*\tSet \"id\",\"class name\" and \"role\" for each row\t*/\n\t\ttr.setAttribute(\"id\", id);\n\t\ttr.setAttribute(\"class\",l_class);\n\t\ttr.setAttribute(\"role\",\"row\");\n\t\tfor(let i = 0;i<11;i++){\n\t\t\tvar td = document.createElement('td');\n\t\t\ttd.setAttribute(\"align\",\"center\");\n\t\t\tif(i == 0)\n\t\t\t{\n\t\t\t\tif(peak.spec_id == l_specIds[0]) l_scan = l_scans[0];\n\t\t\t\telse l_scan = l_scans[1];\n\n\t\t\t\ttd.innerHTML = l_scan ;\n\t\t\t}\n\t\t\tif(i == 1)\n\t\t\t{\n\t\t\t\ttd.innerHTML = parseInt(peak.peak_id) + 1 ;\n\t\t\t}\n\t\t\tif(i == 2)\n\t\t\t{\n\t\t\t\ttd.innerHTML = peak.monoisotopic_mass;\n\t\t\t}\n\t\t\tif(i == 3)\n\t\t\t{\n\t\t\t\t/*\tprovide link to click on m/z value to view spectrum */\n\t\t\t\tlet a = document.createElement('a');\n\t\t\t\ta.href=\"#!\"\n\t\t\t\ta.className = \"peakRows\"\n\t\t\t\ta.innerHTML = peak.monoisotopic_mz;\n\t\t\t\ttd.appendChild(a);\n\t\t\t}\n\t\t\tif(i == 4)\n\t\t\t{\n\t\t\t\ttd.innerHTML = peak.intensity;\n\t\t\t}\n\t\t\tif(i == 5)\n\t\t\t{\n\t\t\t\ttd.innerHTML = peak.charge;\n\t\t\t}\n\t\t\tif(peak.hasOwnProperty('matched_ions_num'))\n\t\t\t{\n\t\t\t\tif(i == 6)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.theoretical_mass;\n\t\t\t\t}\n\t\t\t\tif(i == 7)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.ion_type+peak.matched_ions.matched_ion.ion_display_position;\n\t\t\t\t}\n\t\t\t\tif(i == 8)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.ion_position;\n\t\t\t\t}\n\t\t\t\tif(i == 9)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.mass_error;\n\t\t\t\t}\n\t\t\t\tif(i == 10)\n\t\t\t\t{\n\t\t\t\t\ttd.innerHTML = peak.matched_ions.matched_ion.ppm;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttr.appendChild(td);\n\t\t}\n\t\ttbdy.appendChild(tr);\n\t}\n\tlet l_All_Peaks = prsm_data.prsm.ms.peaks.peak.length;\n\tlet l_not_matched_peak_count = l_All_Peaks - l_matched_peak_count; \n\tdocument.getElementById(\"all_peak_count\").innerHTML = \"All peaks (\" + l_All_Peaks + \")\" ;\n\tdocument.getElementById(\"matched_peak_count\").innerHTML = \"Matched peaks (\" + l_matched_peak_count + \")\" ;\n\tdocument.getElementById(\"not_matched_peak_count\").innerHTML = \"Not Matched peaks (\" + l_not_matched_peak_count + \")\" ;\n\t\n\ttable.appendChild(tbdy);\n}",
"wave(dir, speed) {\n this.cellData = [];\n\n // Load the cells up with rainbow colors at an interval\n let r = 255, g = 0, b = 0, count = 0;\n let values = this.keyboardData[0].length;\n do {\n if (count % ~~(765 / (values - 1)) === 0) {\n if (dir === 0) {\n this.cellData.unshift(new ColorCell(r, g, b, speed));\n } else {\n this.cellData.push(new ColorCell(r, g, b, speed));\n }\n }\n\n if (r > 0 && b === 0) {\n r--;\n g++;\n } else if (g > 0 && r === 0) {\n g--;\n b++;\n } else if (b > 0 && g === 0) {\n r++;\n b--;\n }\n\n count++;\n } while (r < 255);\n\n const effect = setInterval(() => {\n for (let i = 0; i < this.keyboardData[0].length; i++) {\n this.cellData[i].cycle();\n for (let row of this.keyboardData) {\n row[i] = this.cellData[i].getColor();\n }\n }\n\n this.setEffect(\"CHROMA_CUSTOM\", this.keyboardData);\n }, 5);\n\n Chroma.effects[this.devices] = effect;\n }",
"getSkinTone(){\n\t\treturn this.dataArray[4];\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pagingDir = +1: page to the rigth pagingDir = 1: page to the left | function nextPage(pagingDir: number) {
let totalPages = bagsize / pagesize
if (totalPages > (page + 1 * pagingDir) && 0 <= (page + 1 * pagingDir)) {
page = page + 1 * pagingDir;
}
} | [
"function initPaging() {\n vm.pageLinks = [\n {text: \"Prev\", val: vm.pageIndex - 1},\n {text: \"Next\", val: vm.pageIndex + 1}\n ];\n vm.prevPageLink = {text: \"Prev\", val: vm.pageIndex - 1};\n vm.nextPageLink = {text: \"Next\", val: vm.pageIndex + 1};\n }",
"turnPage(direction) {\n let nextPage = (this.state.currentPage + direction) % rules.length;\n if(nextPage < 0) nextPage = rules.length - 1;\n this.setState({currentPage: nextPage});\n }",
"function setupPagingNavigationButtons(p_name, p_tpages, p_page) {\n var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"next_' + p_name + '_Pager\"]');\n var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"first_' + p_name + '_Pager\"]');\n var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"last_' + p_name + '_Pager\"]');\n var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"prev_' + p_name + '_Pager\"]');\n\n if (p_tpages > 1) {\n if (p_page != p_tpages) {\n l_next_obj.removeClass('ui-state-disabled');\n l_last_obj.removeClass('ui-state-disabled');\n }\n if (p_page > 1) {\n l_prev_obj.removeClass('ui-state-disabled');\n l_first_obj.removeClass('ui-state-disabled');\n }\n }\n }",
"function movePagination(num){\n $(\"#crm_dishes .pagination li:not(:first,:last) a\").each(function(i){\n if(parseInt($(this).text())+num>0){\n $(this).text(parseInt($(this).text())+num);\n }\n });\n }",
"pageIndex(itemIndex) {\n if (itemIndex > this.collection.length || itemIndex < 0)\n return -1;\n if ((itemIndex + 1) % this.itemsPerPage === 0)\n return ((itemIndex + 1) / this.itemsPerPage) - 1;\n return Math.floor((itemIndex + 1) / this.itemsPerPage);\n }",
"get start_results(){\n return this.page_number * this.size + 1;\n }",
"paginate({ unlimited = false } = {}) {\r\n const { page: qPage, limit: qLimit, skip: qskip } = this.queryObj;\r\n\r\n const page = qPage * 1 || 1;\r\n let limit = unlimited ? undefined : defaultRecordPerQuery;\r\n if (qLimit)\r\n limit = qLimit * 1 > maxRecordsPerQuery ? maxRecordsPerQuery : qLimit * 1;\r\n const skip = qskip\r\n ? qskip * 1\r\n : (page - 1) * (limit || defaultRecordPerQuery);\r\n\r\n this.query.skip = skip;\r\n this.query.take = limit;\r\n return this;\r\n }",
"togglePaginationButtons() {\r\n let previousPageNum = this.state.currentPages[0];\r\n let nextPageNum = this.state.currentPages[2];\r\n if (previousPageNum != 0) {\r\n this.setState({disablePrev: false, disableFirst: false});\r\n } else {\r\n this.setState({disablePrev: true, disableFirst: true});\r\n }\r\n if (nextPageNum <= this.state.dataCount && nextPageNum > 1) {\r\n this.setState({disableNext: false, disableLast: false});\r\n } else {\r\n this.setState({disableNext: true, disableLast: true});\r\n }\r\n }",
"getPaged() {\n return this.using(PagedItemParser(this))();\n }",
"page(n = 1) {\n return this.addOption('page', n);\n }",
"_addPages (startNumber, upToNumbers) {\n var upTo = Math.min(...upToNumbers)\n\n for (var i = startNumber; i <= upTo; i++) {\n if (!this._pageNumberIncluded(i)) {\n this._addPageNumber(i)\n }\n }\n }",
"previousPage(currentPage) {\n if (currentPage > 1) {\n this.getArticles(currentPage-1);\n }\n }",
"function setupPagingNavigationEvents(p_name) {\n\n var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"next_' + p_name + '_Pager\"]');\n var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"first_' + p_name + '_Pager\"]');\n var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"last_' + p_name + '_Pager\"]');\n var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"prev_' + p_name + '_Pager\"]');\n var l_pager_input = jQuery('span[id=\"sp_1_' + p_name + '_Pager\"]').siblings('input');\n\n l_pager_input\n .unbind('blur')\n .bind('blur', function() {\n if (grid_current_pages[p_name] != l_pager_input.val()) {\n pagingRecords(p_name);\n }\n });\n\n l_next_obj\n .unbind('click')\n .bind('click', function() {\n if ((l_pager_input.val() * 1) != (grid_page_totals[p_name] * 1)) {\n l_pager_input.val((l_pager_input.val() * 1) + 1);\n pagingRecords(p_name);\n }\n });\n\n l_last_obj\n .unbind('click')\n .bind('click', function() {\n l_pager_input.val(grid_page_totals[p_name]);\n pagingRecords(p_name);\n });\n\n l_prev_obj\n .unbind('click')\n .bind('click', function() {\n if ((l_pager_input.val() * 1) != 1) {\n l_pager_input.val(((l_pager_input.val() * 1) - 1));\n pagingRecords(p_name);\n }\n });\n\n l_first_obj\n .unbind('click')\n .bind('click', function() {\n l_pager_input.val(1);\n pagingRecords(p_name);\n });\n }",
"function setPageHeader(page) {\n resetHeader();\n\n currentPage.innerText = page.currentPage;\n totalPages.innerText = page.totalPages;\n totalResultsValue.innerText = page.total;\n\n vm.config.query = page;\n\n currentOffset = page.offset;\n\n //\n if(currentOffset === 0) {\n commonService.addClass(leftButton, 'disabled');\n }\n\n if(currentOffset + page.limit >= page.total) {\n commonService.addClass(rightButton, 'disabled');\n }\n\n }",
"prev() {\n\t\t\tif (this.currPage > 1) {\n\t\t\t\tthis.currPage--;\n\t\t\t\tthis._loadPage();\n\t\t\t}\n\t\t}",
"function Pager(){\n\tthis.routes = {};\n\n\tthis.ctx = new PageContext();\n\n\tthis.start();\n\n\tbindEvents();\n}",
"function goToPage(page) {\n\tpage = Number(page);\n\tconsole.log('going to page', page);\n\tif (page < 1) return false;\n\n\tif (isEasternBook()) {\n\t\tgallery.goToPage(book.pages - page);\n\t}\n\telse {\n\t\tgallery.goToPage(page - 1);\n\t}\n\n\tstaggerImages(page);\n}",
"function switchPageStatus() {\n if(currPageNo === 1)\n $(\"div#pagination>ul>li#firstPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#firstPage\").removeClass(\"disabled\");\n if(currPageNo > 1)\n $(\"div#pagination>ul>li#prevPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#prevPage\").addClass(\"disabled\");\n if(currPageNo < currMaxPage)\n $(\"div#pagination>ul>li#nextPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#nextPage\").addClass(\"disabled\");\n if(currPageNo === currMaxPage)\n $(\"div#pagination>ul>li#lastPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#lastPage\").removeClass(\"disabled\");\n }",
"_addEllipsisPage () {\n this._addPageNumber(null)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup the grid pagingation navigation buttons | function setupPagingNavigationButtons(p_name, p_tpages, p_page) {
var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id="next_' + p_name + '_Pager"]');
var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id="first_' + p_name + '_Pager"]');
var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id="last_' + p_name + '_Pager"]');
var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id="prev_' + p_name + '_Pager"]');
if (p_tpages > 1) {
if (p_page != p_tpages) {
l_next_obj.removeClass('ui-state-disabled');
l_last_obj.removeClass('ui-state-disabled');
}
if (p_page > 1) {
l_prev_obj.removeClass('ui-state-disabled');
l_first_obj.removeClass('ui-state-disabled');
}
}
} | [
"function initPaging() {\n vm.pageLinks = [\n {text: \"Prev\", val: vm.pageIndex - 1},\n {text: \"Next\", val: vm.pageIndex + 1}\n ];\n vm.prevPageLink = {text: \"Prev\", val: vm.pageIndex - 1};\n vm.nextPageLink = {text: \"Next\", val: vm.pageIndex + 1};\n }",
"function refreshNaviButton() {\n self.naviPreBtnEnabled(curPage === 1 ? false : true);\n self.naviNextBtnEnabled(totalPage > 1 && curPage!== totalPage ? true:false);\n }",
"function setupPagingNavigationEvents(p_name) {\n\n var l_next_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"next_' + p_name + '_Pager\"]');\n var l_first_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"first_' + p_name + '_Pager\"]');\n var l_last_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"last_' + p_name + '_Pager\"]');\n var l_prev_obj = jQuery('#' + p_name + '_Pager_center').find('td[id=\"prev_' + p_name + '_Pager\"]');\n var l_pager_input = jQuery('span[id=\"sp_1_' + p_name + '_Pager\"]').siblings('input');\n\n l_pager_input\n .unbind('blur')\n .bind('blur', function() {\n if (grid_current_pages[p_name] != l_pager_input.val()) {\n pagingRecords(p_name);\n }\n });\n\n l_next_obj\n .unbind('click')\n .bind('click', function() {\n if ((l_pager_input.val() * 1) != (grid_page_totals[p_name] * 1)) {\n l_pager_input.val((l_pager_input.val() * 1) + 1);\n pagingRecords(p_name);\n }\n });\n\n l_last_obj\n .unbind('click')\n .bind('click', function() {\n l_pager_input.val(grid_page_totals[p_name]);\n pagingRecords(p_name);\n });\n\n l_prev_obj\n .unbind('click')\n .bind('click', function() {\n if ((l_pager_input.val() * 1) != 1) {\n l_pager_input.val(((l_pager_input.val() * 1) - 1));\n pagingRecords(p_name);\n }\n });\n\n l_first_obj\n .unbind('click')\n .bind('click', function() {\n l_pager_input.val(1);\n pagingRecords(p_name);\n });\n }",
"togglePaginationButtons() {\r\n let previousPageNum = this.state.currentPages[0];\r\n let nextPageNum = this.state.currentPages[2];\r\n if (previousPageNum != 0) {\r\n this.setState({disablePrev: false, disableFirst: false});\r\n } else {\r\n this.setState({disablePrev: true, disableFirst: true});\r\n }\r\n if (nextPageNum <= this.state.dataCount && nextPageNum > 1) {\r\n this.setState({disableNext: false, disableLast: false});\r\n } else {\r\n this.setState({disableNext: true, disableLast: true});\r\n }\r\n }",
"renderPageButtons() {\n const { page, hits, perpage } = this.state;\n const last = Math.ceil(hits / perpage);\n const pages = pagination(page, last);\n const pageButtons = pages.map((pageNo) => {\n if (pageNo === 'First') {\n return <Button color=\"primary\" size=\"sm\" key={pageNo} onClick={() => this.changePage(1)}>«</Button>;\n }\n if (pageNo === 'Last') {\n return <Button color=\"primary\" size=\"sm\" key={pageNo} onClick={() => this.changePage(last)}>»</Button>;\n }\n return <Button color=\"primary\" size=\"sm\" key={pageNo} onClick={() => this.changePage(pageNo)} className={(pageNo === this.state.page) ? 'active' : ''} disabled={(pageNo === this.state.page)}>{pageNo}</Button>;\n });\n\n return pageButtons;\n }",
"function paginator(){\n\t$('.paginator').click(function(e){\n\t\tvar id = $(this).attr('data-id');\n\t\tvar bid = $(this).attr('data-bid');\n\t\tvar rel = $(this).attr('data-rel');\n\t\tvar view = $(this).attr('data-view');\n\t\tshowLoader();\n\t\turl = encodeURI(\"index.php?page=\"+rel+\"&action=\"+bid+\"&pageNum=\"+id+\"&id=\"+view);\n\t\twindow.location.replace(url);\n\t});\n}",
"function preparePage() {\n links = [];\n\n $(\".js-scroll-indicator\").each(function(index, link) {\n prepareIndicator( $(link) );\n });\n }",
"function addNavigation() {\n let length = this.innerElements.length;\n for (let i = 0; i < length; i++) {\n const BTN = document.createElement('button');\n BTN.classList.add('slider-button');\n if (i == 0) BTN.classList.add('slider-button--active');\n BTN.addEventListener('click', () => this.goTo(i));\n this.selector.nextSibling.appendChild(BTN);\n }\n }",
"AsidePanelPages(){\n\t\t// All positions in navbar\n\t\tconst navs = document.querySelectorAll(\".pages-nav li\");\n\t\t// All pages\n\t\tconst pages = document.querySelectorAll(\".pages li\");\n\t\t// For each position add onclick function\n\t\tnavs.forEach((nav) => {\n\t\t\tnav.addEventListener(\"click\", () => {\n\t\t\t\tconst index = Array.from(navs).indexOf(nav);\n\t\t\t\t// Hide all active positions in navbar\n\t\t\t\tnavs.forEach((nav_item) => {\n\t\t\t\t\tnav_item.classList.remove(\"active\");\n\t\t\t\t});\n\t\t\t\t// Hide all active slides\n\t\t\t\tpages.forEach((page_item) => {\n\t\t\t\t\tpage_item.classList.remove(\"active\");\n\t\t\t\t});\n\t\t\t\t// Show active position in navbar and active page\n\t\t\t\tnav.classList.add(\"active\");\n\t\t\t\tpages[index].classList.add(\"active\");\n\t\t\t});\n\t\t});\n\t}",
"function setPageHeader(page) {\n resetHeader();\n\n currentPage.innerText = page.currentPage;\n totalPages.innerText = page.totalPages;\n totalResultsValue.innerText = page.total;\n\n vm.config.query = page;\n\n currentOffset = page.offset;\n\n //\n if(currentOffset === 0) {\n commonService.addClass(leftButton, 'disabled');\n }\n\n if(currentOffset + page.limit >= page.total) {\n commonService.addClass(rightButton, 'disabled');\n }\n\n }",
"function addPagination (list) {\n\n const noOfButtons = Math.ceil(list.length/itemsPerpage); // This dynamically creates a number value depending on the length of the data list and the value of itemsperPage\n buttonContainer.innerHTML = ''; // This clears the button ul container. Making sure there is nothing there before we append the buttons.\n\n for(let i =1; i <= noOfButtons; i++){ // This loop appends a list item and button to the DOM. The condition depends on the value of noOfButtons\n const button = `\n <li>\n <button type=\"button\">${i}</button>\n </li>\n `;\n buttonContainer.insertAdjacentHTML('beforeend', button); // Appending list items and buttons to the DOM.\n }\n const firstButton = document.querySelector('.link-list > li > button');\n firstButton.className = 'active'; // This sets the first button, which is 1, with a class of active. This indicates that the first page will be on view when it is loaded.\n \n buttonContainer.addEventListener('click', (e) =>{ // an event listener for the ulButton Container\n const pageNo = e.target.textContent; // this stores the textContent of the button the user has clicked on. I.e the number.\n if(e.target.tagName === 'BUTTON'){ // this if statement checks if the user has clicked on a button within the container\n const pagButtons = buttonContainer.querySelectorAll('li button'); // this stores all the buttons in a variable\n for(let i=0; i < pagButtons.length; i++){ // \n if(pagButtons[i].className === 'active'){ // This loop will remove all buttons with class of 'active'\n pagButtons[i].classList.remove('active');\n }\n }\n e.target.className = 'active'; // This will set whatever button the user has clicked as active\n showPage(list,parseInt(pageNo)); // the second arguement takes the number from the button the user has clicked on. \n }\n\n return console.log( parseInt(pageNo));\n });\n}",
"function setTablePaginationHandlers(pagination){\n \n // Get table\n \n let table = $(pagination).siblings('.table-container').find('table.paginated');\n \n // Set event handlers for page number buttons\n \n $(pagination).find('button:not(.first, .prev, .next, .last)').each(function(){\n \n $(this).on('click', function(event){\n \n let pageNumber = parseInt($(this).html());\n setTablePagination(table, pageNumber);\n \n });\n \n });\n \n // Set event handlers for first, prev, next, and last buttons\n \n $(pagination).find('button.first').on('click', function(event){\n \n setTablePagination(table, 1);\n \n });\n \n $(pagination).find('button.prev').on('click', function(event){\n \n prevTablePage(table);\n \n });\n \n $(pagination).find('button.next').on('click', function(event){\n \n nextTablePage(table);\n \n });\n \n $(pagination).find('button.last').on('click', function(event){\n \n // Get list of table rows (includes header row, not filtered rows) and number of rows to show\n \n let tableRows = $(table).find('tr:not(.filtered)');\n let showNumber = parseInt($(table).siblings('.table-show').find('select').val());\n \n // Get number of pages needed\n \n let pages = Math.ceil((tableRows.length - 1) / showNumber);\n \n setTablePagination(table, pages);\n \n });\n \n}",
"function initPage(sMode) {\n bindGrid();\n setDefaultValues();\n var sPageTitle = getPageTitle();\n el(\"hdnPageTitle\").value = sPageTitle;\n el(\"lstBack\").style.display = \"none\";\n el(\"lstFirst\").style.display = \"none\";\n el(\"lstPrev\").style.display = \"none\";\n el(\"lstNext\").style.display = \"none\";\n el(\"lstLast\").style.display = \"none\";\n el('iconFav').style.display = \"none\";\n reSizePane();\n}",
"function setArrows(hideAll) {\n let nextIcon = document.getElementById(\"next-icon\");\n let prevIcon = document.getElementById(\"prev-icon\");\n nextIcon.style.display = \"block\";\n prevIcon.style.display = \"block\";\n //If the file has only one page, don't show buttons\n if (pdfDoc.numPages === 1 || hideAll) {\n nextIcon.style.display = \"none\";\n prevIcon.style.display = \"none\";\n } else if (pageNum <= 1) {\n //If the first page is shown, don't show the previous-button\n prevIcon.style.display = \"none\";\n } else if (pageNum >= pdfDoc.numPages) {\n //If the the last page is shown, don't show the next-button\n nextIcon.style.display = \"none\";\n }\n}",
"addNavigationToChildrenButtons() {\n const buttons = this.el.querySelectorAll('button')\n for (let entry of buttons) {\n $(entry).click(function () {\n // console.log(\"CLICKED \" + entry.textContent)\n $('html, body').animate({\n scrollTop: $('#' + entry.textContent.toLowerCase()).offset().top\n }, 1000);\n });\n }\n }",
"function paginate() {\n var prev = document.querySelector(\"link[rel=prev]\");\n var next = document.querySelector(\"link[rel=next]\");\n var nav = document.createElement(\"nav\");\n nav.id = \"pagination\";\n if (prev)\n nav.innerHTML = \"<a class=prev href=\" + prev.href + \">\" + prev.title + \"</a>\";\n if (next)\n nav.innerHTML += \"<a class=next href=\" + next.href + \">\" + next.title + \"</a>\";\n if (prev || next)\n document.body.appendChild(nav);\n}",
"function activePagination() {\n\n\t\t\tcurrentSlide = this.currentSlide;\n\t\t\t$(this.selector).parent().find('.carousel__pagination-button').removeClass('is-active');\n\t\t\t$(this.selector).parent().find('.carousel__pagination-button--' + currentSlide).addClass('is-active');\n\t\t}",
"function paginationNavClick(event) {\n const linkButtons = document.querySelectorAll('.pagination ul li a');\n\n if (event.target.tagName === 'A') {\n for (let i = 0; i < linkButtons.length; i++) {\n if (linkButtons[i].innerText != event.target.innerText) {\n linkButtons[i].className = '';\n }\n else {\n event.target.className = 'active';\n }\n }\n studentDisplay(parseInt(event.target.innerText), studentTempList);\n }\n}",
"function switchPageStatus() {\n if(currPageNo === 1)\n $(\"div#pagination>ul>li#firstPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#firstPage\").removeClass(\"disabled\");\n if(currPageNo > 1)\n $(\"div#pagination>ul>li#prevPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#prevPage\").addClass(\"disabled\");\n if(currPageNo < currMaxPage)\n $(\"div#pagination>ul>li#nextPage\").removeClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#nextPage\").addClass(\"disabled\");\n if(currPageNo === currMaxPage)\n $(\"div#pagination>ul>li#lastPage\").addClass(\"disabled\");\n else\n $(\"div#pagination>ul>li#lastPage\").removeClass(\"disabled\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to print the formatted search results (includes number of results, full name and birthdate) | function printSearchResults (result) {
console.log(`Found ${result.rowCount} by the name ${searchName}`);
for (let i = 0; i < result.rowCount; i ++) {
console.log(`- ${i + 1}: ${result.rows[i].first_name} ${result.rows[i].last_name}, born ${returnDateStr(result.rows[i].birthdate)}`)
}
} | [
"function printSurnameIndex()\n{\n\tif (Dwr.search.Ndx >= 0)\n\t{\n\t\tvar html = '';\n\t\tif (N(Dwr.search.Ndx, 'persons').length == 0)\n\t\t{\n\t\t\thtml += '<p>' + _('No matching surname.') + '</p>';\n\t\t}\n\t\telse if (N(Dwr.search.Ndx, 'persons').length == 1)\n\t\t{\n\t\t\twindow.location.replace(indiHref(N(Dwr.search.Ndx, 'persons')[0]));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar txt = htmlPersonsIndex(N(Dwr.search.Ndx, 'persons'));\n\t\t\thtml +=\n\t\t\t\t'<h2 class=\"page-header\">' +\n\t\t\t\t(N(Dwr.search.Ndx, 'surname') || empty(_('Without surname'))) +\n\t\t\t\t'</h2>' +\n\t\t\t\ttxt;\n\t\t}\n\t\treturn html;\n\t}\n\telse\n\t{\n\t\treturn printSurnamesIndex();\n\t}\n}",
"function searchtoresults()\n{\n\tshowstuff('results');\n\thidestuff('interests');\t\n}",
"function outputSPARQLResults (results) {\n for (let row in results) {\n let printedLine = ''\n for (let column in results[row]) {\n printedLine = printedLine + results[row][column].value + ' '\n }\n console.log(printedLine)\n }\n}",
"function displaySearchResult(data) {\n\tconst pages = data.query.pages;\n\n\t//Create new li for each search item found.\n\tconst searchResultHtml = Object.keys(pages).map( function(key){\n\t\tconst { title, extract } = pages[key];\n\n\t\treturn html = `\n\t\t\t<li>\n\t\t\t\t<a href=\"https://en.wikipedia.org/wiki/${title}\">\n\t\t\t\t\t<div class=\"resultItem\">\t\t\t\t\t\t\n\t\t\t\t\t\t<h1> ${title} </h1> <br>\n\t\t\t\t\t\t${extract} \n\t\t\t\t\t\n\t\t\t\t\t</div>\n\t\t\t\t</a>\n\t\t\t</li>\n\t\t\t`;\n\t});\t\t\n\t//Put all li search result item in ul list.\n\tsearchResultList.innerHTML = searchResultHtml.join(\"\");\t\t\n}",
"function displayResult() {}",
"function searchStudent() {\t\r\n\t//convert all the input name to lowercase and remove the whitespace from the beginning and ending\r\n var searchTerm = $('#search').val().toLowerCase().trim();\r\n\r\n var SearchingResults = students.filter(function(i) {\r\n\t\tvar studentName = $(this).find('h3').text();\r\n \tvar studentEmail = $(this).find('.email').text();\r\n //Even part of text matches, it will still show the information of the student\r\n if (studentName.indexOf(searchTerm) > -1 || studentEmail.indexOf(searchTerm) > -1) {\r\n return true;\r\n }\r\n return false;\r\n });\r\n if (SearchingResults.length === 0 ) {\r\n \t$('.page-header h2').text('No Matching Results');\r\n } else {\r\n \t$('.page-header h2').text('Matching STUDENTS');\r\n }\r\n\t//add page numbers to to searching results too, delete the original pagination\r\n var paginated_students = setPages(SearchingResults);\r\n $('.pagination').remove();\r\n if (SearchingResults.length > 10) {\r\n appendPages(paginated_students);\r\n }\r\n pageIndication(0, paginated_students);\r\n}",
"function getFormattedSearchResults(searchGeometry, type) {\n var features;\n if (type == 'stones') {\n // Only stones can be filtered by age \n var queryFilter = constructFilter();\n features = map.queryRenderedFeatures(searchGeometry, {layers: [type], filter: queryFilter});\n }\n else {\n features = map.queryRenderedFeatures(searchGeometry, {layers: [type]});\n }\n\n // Creates string representing results \n var searchResults = \"\";\n searchResults += \"<b>\" + type.charAt(0).toUpperCase() + type.slice(1) + \":</b></br>\";\n for (var i = 0; i < features.length; i++) {\n var feature = features[i];\n var name = feature.properties.name;\n // Because of how MapBox treats features, some features may be \n // be split up and returned multiple times in the query \n if (!searchResults.includes(name)) {\n searchResults += \"<li data-type=\" + type + \" onclick=displayInfo(this)>\" + name + \"</li>\";\n }\n }\n if (features.length == 0) {\n searchResults += \"No results found</br>\"\n }\n\n return searchResults;\n}",
"function searchPrettify(result: any) {\n const list: Array<any> = result.list\n const term: string = result.term\n return list\n .map((pkg: any) => {\n let type = pkg.type\n switch (type) {\n case 'node-package':\n type = chalk.green('js')\n break\n case 'perl-package':\n type = chalk.red('pl')\n break\n case 'python-package':\n type = chalk.yellow('py')\n break\n case 'r-package':\n type = chalk.blue('r')\n break\n default:\n type = chalk.red(' ')\n }\n let descr = pkg.description ? pkg.description : ''\n descr = ellipsize(descr, 60)\n descr = chalk.gray(\n descr.replace(new RegExp(term.replace('*', ''), 'ig'), (match: any) => {\n return chalk.underline(match)\n })\n )\n return sprintf('%-13s %-30s %-10s %s', type, pkg.name, pkg.version, descr)\n })\n .join('\\n')\n}",
"displayTopEightMatchedRespondents() {\n console.log(\"\\nTop 8 matches- by matching scores:\");\n console.log(\"===================================\\n\");\n\n for (let i = 0; i < 8; i++) {\n const curr = this.results[this.results.length - 1 - i];\n console.log(i);\n console.log(\n `Name: ${curr.name.slice(0, 1).toUpperCase()}${curr.name.slice(\n 1\n )}`\n );\n console.log(\n `Distance to closest available city: ${curr.closestAvailableCity.distance}km`\n );\n console.log(`Matching Score: ${curr.score}`);\n console.log(\"-------------------------------\");\n }\n }",
"showResultCount( count ) {\n if( typeof( this.topicResults) != 'undefined' ) {\n return 'Search keyword found ' + count + ' of ' + this.topicResults.length + ' topics. ';\n }\n }",
"function displayMatches(){\n const matchArray = findMatches(this.value, cities);\n\n const html = matchArray.map( place => {\n const regex = new RegExp(this.value, 'gi');\n\n const cityName = place.city.replace(regex, `<span class=\"hl\">${this.value}</span>`);\n const stateName = place.state.replace(regex, `<span class=\"hl\">${this.value}</span>`);\n\n return `\n <li>\n <span class=\"name\">${cityName}, ${stateName}</span>\n <span class=\"population\">${numberWithCommas(place.population)}</span>\n </li>\n `;\n }).join('');\n\n let match_txt = (matchArray.length > 1) ? ' matches' : ' match';\n founds.innerHTML = matchArray.length + match_txt + ' found.';\n \n if(this.value == ''){\n founds.style.display = 'none'; \n } else {\n founds.style.display = 'block'; \n }\n\n suggestions.innerHTML = html;\n}",
"function formatResponse(searchTerm, res) {\n let docs = res.data.docs;\n docs.forEach((doc) => {\n let id = doc.id;\n let ingestDate = doc.ingestDate;\n let dataProvider = doc.provider.name;\n \n // Write line to file\n let writeData = `${searchTerm} ${id} ${ingestDate} ${dataProvider}\\r\\n`\n fs.appendFileSync('output.txt', writeData, (err) => {\n console.error(err);\n });\n })\n}",
"function displayFilmsData(data) {\r\n cartegoriesCounter = 0;\r\n var listBox = document.getElementById(\"searchResults\");\r\n listBox.innerHTML = \"\";\r\n listBox.innerHTML = \"<p>Title: \" + data.results[0].title + \"</p>\" +\r\n \"<br><p>Episode: \" + data.results[0].episode_id + \"</p><br>\" +\r\n \"<p>Opening Crawl:</p><br><p>\" + data.results[0].opening_crawl +\r\n \"<br><p>Director: \" + data.results[0].director + \"</p><br>\" +\r\n \"<p>Producer(s): \" + data.results[0].producer + \"</p>\";\r\n }",
"function displaySearchData(data) {\n\t\t\n\t\t//\tSet search form textfield value to term searched\n\t\t$('#form-text-term').val(data.term)\n\t\t\n\t\t//\tSlidedown as chart is created--animation is cool\n\t\t$('#stats').slideDown('fast', function() {\n\t\t\t$('#highcharts').highcharts({\n\t\t\t\tchart: {\n\t\t\t\t\ttype: 'column'\n\t\t\t\t},\n\t\t\t\ttitle: {\n\t\t\t\t\ttext: ''\n\t\t\t\t},\n\t\t\t\txAxis: {\n\t\t\t\t\ttype: 'category'\n\t\t\t\t},\n\t\t\t\t\n\t\t\t\tlegend: {\n\t\t\t\t\tenabled: false\n\t\t\t\t},\t\n\t\t\t\tplotOptions: {\n\t\t\t\t\tseries: {\n\t\t\t\t\t\tborderWidth: 0,\n\t\t\t\t\t\tdataLabels: {\n\t\t\t\t\t\t\tenabled: true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\t\t\t\t\n\t\t\t\tseries: [{\n\t\t\t\t\tname: 'Alphabet',\n\t\t\t\t\tcolorByPoint: true,\n\t\t\t\t\tdata: data.stats.seriesData\n\t\t\t\t}],\n\t\t\t\tdrilldown: {\n\t\t\t\t\tseries: data.stats.drilldownSeries\n\t\t\t\t}\n\t\t\t});\n\t\t});\t\n\t\t\n\t\t//\tShow search results\n\t\t$('#results').html(data.output).slideDown('fast');\n\t}",
"function showSearchParameters() {\n $('.searchParameters').html(`\n <h2 class=\"searchTerm\">Search Term: ${searchResults.params.q}</h2>\n <p class=\"advSearch\">Search Refined By</p>\n <ul>\n <li class=\"bull\"><strong>Calories - </strong>${calValue}</li>\n <li class=\"bull\"><strong>Max Number of Ingredients - </strong>${numIng}</li>\n <li class=\"bull\"><strong>Diet Labels - </strong>${dietLabel}</li>\n <li class=\"bull\"><strong>Allergies - </strong>${allergyLab}</li>\n </ul>\n `);\n}",
"formatSearchResults(rawResults) {\n const results = new Array();\n if (typeof (rawResults) === \"undefined\" || rawResults == null) {\n return [];\n }\n const tempResults = rawResults.results ? rawResults.results : rawResults;\n for (const tempResult of tempResults) {\n const cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells;\n results.push(cells.reduce((res, cell) => {\n res[cell.Key] = cell.Value;\n return res;\n }, {}));\n }\n return results;\n }",
"function showAll(request){\n\tnamesDB.getAll(gotNames);\n\tfunction gotNames(names){\n\t\tnamesText = \"\";\n\t\tif (names.length > 0){\n\t\t\tfor (i =0; i < names.length; i++) {\n\t\t\t\t// create a link like: <a href=\"/view/1DlDQu55m85dqNQJ\">Joe</a><br/>\n\t\t\t namesText += '<a href=\"/view/' + names[i]._id + '\">' + names[i].name + \"</a><br/>\";\n\t\t\t}\n\t\t} else {\n\t\t\tnamesText = \"No people in the database yet.\";\n\t\t}\n\t\t\n\t\t//console.log(namesText);\n\t\tvar footerText = '<hr/><p><a href=\"/search\">Search</a>';\n\t\trequest.respond( namesText + footerText);\n\t}\t\n}",
"function _drawResults() {\n\n let template = \"\";\n store.state.songs.forEach(song => {\n template += song.SearchTemplate;\n });\n document.getElementById(\"songs\").innerHTML = template;\n}",
"function getBiographySearch(data) {\n biography.innerHTML = \"\";\n let properties = [\"Full Name:\", \"Alter egos:\", \"Aliases:\", \"Place of Birth:\", \"First Appearance:\", \"Publisher:\", \"Alignment:\"];\n let i = 0;\n for (let prop in data.results[0].biography) {\n if (data.results[0].biography[prop] === \"null\" || data.results[0].biography[prop] === \"-\") {\n biography.innerHTML += `<p><span class=\"holders\">${properties[i]}</span> No information found.</p>`;\n } else {\n biography.innerHTML += `<p><span class=\"holders\">${properties[i]}</span> ${data.results[0].biography[prop]}</p>`;\n }\n i++;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
vbScript Year function: Year(date) | function Year(dt) {
if (isNull(dt)) { return null; }
var regex=new RegExp('-','g');
try {
dt=dt.replace(regex,'/'); //try/catch skips full date text of javascript
} catch(e) {}
var dat=new Date(dt);
return dat.getFullYear();
} | [
"function GetYearFromRawDateFunc(date) {\n var date = new Date(date);\n return date.getFullYear();\n }",
"function setYear() {\n\n // GET THE NEW YEAR VALUE\n var year = tDoc.calControl.year.value;\n\n // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR\n if (isFourDigitYear(year)) {\n calDate.setFullYear(year);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n else {\n // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH\n tDoc.calControl.year.focus();\n tDoc.calControl.year.select();\n }\n}",
"shortYear() {\n return this.date.getYear();\n }",
"function isYear(str) {\n\tvar inputYear\n\tvar resultStr = \"\";\n\t// Return immediately if an invalid value was passed in\n\tif (str+\"\" == \"undefined\" || str == null) return null;\n\t// Make sure the argument is a string\n\tstr += \"\";\n\tstr = Trim( str )\n\tinputYear = parseInt(str)\n\tif (isNaN(inputYear)) return null\n\tif (inputYear < 1900 || inputYear > 2200) return null //unreasonable value\n\tresultStr = \"\" + inputYear\n\treturn resultStr;\n}",
"function dateGetYear(dateS) {\n if (!dateS) // empty, null or undefined date string\n return null;\n\n return (new Date(dateS)).getFullYear();\n}",
"function prevYear() {\n\tif (YEAR > 1950) {\n\t\tYEAR--;\n\t}\n\tsetDateContent(MONTH, YEAR);\n}",
"getYearNum() {\n\t\treturn this.props.month.substr(0,4);\n\t}",
"function isFourDigitYear(year) {\n\n if (year.length != 4) {\n tDoc.calControl.year.value = calDate.getFullYear();\n tDoc.calControl.year.select();\n tDoc.calControl.year.focus();\n }\n else {\n return true;\n }\n}",
"getYearDifference(year) {\n return new Date().getFullYear() - year;\n }",
"function setNextYear() {\n\n var year = tDoc.calControl.year.value;\n if (isFourDigitYear(year)) {\n year++;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function secToYear(seconds) {\n return seconds / 31536000;\n}",
"function setYear() {\n\tvar element = document.getElementById(\"selected_year\");\n\tYEAR = element.options[element.selectedIndex].value;\n\tsetDateContent(MONTH, YEAR);\n}",
"function grshift_year(a, M, e) {\n return grshift(a, M, e) * YEAR_SEC / calc_orbit_period(a, M);\n}",
"function setPreviousYear() {\n\n var year = tDoc.calControl.year.value;\n\n if (isFourDigitYear(year) && year > 1000) {\n year--;\n calDate.setFullYear(year);\n tDoc.calControl.year.value = year;\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n}",
"function changeImmYear()\n{\n let form = this.form;\n let censusId = form.Census.value;\n let censusYear = censusId.substring(censusId.length - 4);\n let immyear = this.value;\n if (this.value == '[')\n {\n this.value = '[Blank';\n }\n let res = immyear.match(/^[0-9]{4}$/);\n if (!res)\n { // not a 4 digit number\n res = immyear.match(/^[0-9]{2}$/);\n if (res)\n { // 2 digit number\n // expand to a 4 digit number which is a year in the\n // century up to and including the census year\n immyear = (res[0] - 0) + 1900;\n while (immyear > censusYear)\n immyear -= 100;\n this.value = immyear;\n } // 2 digit number\n } // not a 4 digit number\n\n this.checkfunc();\n}",
"function hundYearBack() {\n var date = new Date();\n var yr = date.getFullYear();\n date.setFullYear(yr-100);\n document.write(\"Current year is \"+ yr +\"<br> 100 year ago, it was \"+ date);\n}",
"function leapYear() {\r\n var y = 2021\r\n var i = 0\r\n while (i < 20) {\r\n if ((y % 4 === 0) && (y % 100 !== 0) || (y % 400 === 0)) {\r\n document.write(y + \"\\n\");\r\n y++\r\n i++\r\n }\r\n else {\r\n y++\r\n }\r\n }\r\n\r\n}",
"function checkValidYear(c,obj)\n\t{\n\t\tvar calendar = eval('calendar'+c);\t\t\t\t\t\n\t\t// ------- 'calendar'+c is calendar componet ID.\n\t\t// ------- if you want to change calendar component ID please \n\t\t// ------- change calendar component ID in calendar generator at method getTagGenerator() too.\n\t\tvar objLength = obj.value.length;\n\t\tvar splitValue\t= \"/\";\n\t\tvar dateArray = obj.value.split(splitValue);\n\t\tvar year = dateArray[2];\n\t\tif( obj.value!=\"\" &&( Number(year) < calendar.minYear || Number(year) > calendar.maxYear) )\n\t\t{\n\t\t\tshowOWarningDialog(\"Data not complete\", \"Year must between \"+calendar.minYear+\" and \"+calendar.maxYear+\".\", \"OK\") ;\n\t\t\tif(Number(year) < calendar.minYear)\n\t\t\t{\n\t\t\t\tobj.value = dateArray[0]+splitValue+dateArray[1]+splitValue+ calendar.minYear;\n\t\t\t}else{\n\t\t\t\tobj.value = dateArray[0]+splitValue+dateArray[1]+splitValue+ calendar.maxYear;\n\t\t\t}\n\t\t\tobj.focus();\n\t\t}\n\t}",
"jYearToIYear(eraCode, jYear) {\n if (!this.isValidEraCode(eraCode)) {return (-1);} // eraCode not found \n const maxJYear = this.isNowEra(eraCode) ? 99 : this.yDict[eraCode].getNumYears(); // 99 if now era\n if (jYear>=1 && jYear<=maxJYear) { return this.yDict[eraCode].getStartYear() + parseInt(jYear) - 1; }\n return 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return NEW array with [Youngest Age, Oldest Age, Age difference btw Oldest & youngest] Pseudocode: // Step one, create a new array to put in numbers we've found var ageDiffArr = []; // Find Youngest age (using Math.min and spread operator) let youngest = Math.min(...ages); // and push into ageDiff / new array ageDiffArr.push(youngest); // Check array console.log(ageDiffArr); // Find Oldest age (using Math.max and spread operator); let oldest = Math.max(...ages); // and push into ageDiff / new array ageDiffArr.push(oldest); // Check array console.log(ageDiffArr); // Subtract Oldest from Youngest age let ageDiff = oldest youngest; // and push into ageDiff / new Array ageDiffArr.push(ageDiff); // Check array console.log(ageDiffArr); Solution: | function differenceInAges(ages) {
// Your code goes here
// Step one, create a new array to put in numbers we've found
var ageDiffArr = [];
// Find Youngest age (using Math.min and spread operator)
let youngest = Math.min(...ages);
// and push into ageDiff / new array
ageDiffArr.push(youngest);
// Find Oldest age (using Math.max and spread operator);
let oldest = Math.max(...ages);
// and push into ageDiff / new array
ageDiffArr.push(oldest);
// Subtract Oldest from Youngest age
let ageDiff = oldest - youngest;
// and push into ageDiff / new Array
ageDiffArr.push(ageDiff);
console.log(ageDiffArr);
} | [
"function findDiff(arr) {\n var max = Math.max(...arr)\n var min = Math.min(...arr)\n return max - min;\n }",
"function byAge(arr){\nreturn arr.sort((a, b) => a.age - b.age)\n}",
"function getDateForAccruedAges(expectedAge: number, ...participants: Participant[]): moment {\n checkExpectedAge(expectedAge);\n checkParticipants(participants);\n\n const participantsAsIterable = participants[0].length\n ? participants[0] // participants parameter given as an array\n : participants; // participants parameter given as an iterable\n\n const sortedByNextBirthday = sortByNextBirthday(participantsAsIterable);\n const olderPerson = sortByAge(participantsAsIterable)[0];\n\n const birthdays = [];\n let year = olderPerson.dateOfBirth.year() + 1;\n while (birthdays.length < expectedAge) {\n // eslint-disable-next-line no-loop-func\n sortedByNextBirthday.forEach((participant) => {\n const newBirthday = participant.dateOfBirth.clone().year(year);\n if (newBirthday.diff(participant.dateOfBirth) >= 1) {\n birthdays.push(newBirthday);\n }\n });\n year += 1;\n }\n return birthdays[expectedAge - 1];\n}",
"function max_min_avg () {\n var sum = 0;\n var i = 0;\n var arr = [3, 7, -8, 19, 27, -5, 6];\n var max = arr[i];\n var min = arr[i];\n var newarr = [];\n for (var i = 0; i < arr.length; i++) {\n sum = sum + arr[i];\n if (i > 0) {\n if (arr[i] > max){\n var max = arr[i];\n }\n \n else if (arr[i] < min){\n var min = arr[i];\n }\n }\n }\n var avg = sum / arr.length;\n newarr.push(max);\n newarr.push(min);\n newarr.push(avg);\n return newarr;\n\n}",
"function MinMax() {\n console.log('MAX: ', Math.max.apply(Math, newArr));\n console.log('MIN: ', Math.min.apply(Math, newArr));\n}",
"function calcDifference() {\n const n = prompt(\"Enter number\");\n const nArr = n.split(\"\");\n return Math.max(...nArr) - Math.min(...nArr);\n}",
"function calcAge(el) {\n return 2016 - el;\n}",
"function calcAge(yearBorn) {\n return 2019 - yearBorn;\n}",
"function SortByNamexOlderThan(age) {\n let choosenPlayers = []\n for (const player of players) {\n if (player.age >= age) {\n let sortedAwards = player.awards\n sortedAwards.sort((award1, award2) => {\n if (award1.year > award2.year) {\n return -1\n } else {\n return 1\n }\n })\n\n player.awards = sortedAwards\n choosenPlayers.push(player)\n }\n }\n\n choosenPlayers.sort((player1, player2) => {\n if (player1.name > player2.name) {\n return 1\n } else {\n return -1\n }\n })\n return choosenPlayers\n}",
"function avgAge(persons) \n{\n var out;\nout=persons.reduce()\n\n return out\n}",
"function maxMinAvg(arr){\n var max = arr[0];\n var min = arr[0];\n var avg = null;\n for(i=0;i<arr.length;i++){\n if(arr[i]<min){\n min = arr[i];\n }\n if(arr[i]>max){\n max = arr[i];\n }\n avg+=arr[i];\n }\n var newArr = [max, min, avg/arr.length]\n return newArr;\n}",
"function filterDataByRangeAge(minAge, maxAge) {\n emptyUITable();\n let result = originalData.filter(animal => animal.age >= minAge && animal.age <= maxAge);\n displayArray(result);\n }",
"function averageMomChildAgeDiff() {\n var ageDifferences = [];\n \n // ignore the mothers that are null, or don't exist in our ancestry database\n var filteredAncestry = ancestry.filter(hasKnownMother);\n \n // for every person in our ancestry array\n filteredAncestry.forEach(function(person) {\n // get the birth year of the person\n var birth = person.born;\n // get the birth year of the mother\n var motherBirth = byName[person.mother].born;\n // calculate the age difference\n var ageDiff = birth - motherBirth;\n // push it to our age differences array\n ageDifferences.push(ageDiff); \n });\n\n return average(ageDifferences);\n}",
"function ofAge(arr){\n return arr.filter(num => num.age >= 18)\n}",
"function printFullAge(years) {\n \n\n var ages = [];\n var output = [];\n\n for (var i = 0; i < years.length; i++) {\n ages[i] = 2018 - years[i];\n }\n\n for (var i = 0; i< ages.length; i++) {\n if(ages[i] >= 18) {\n console.log(\"Person \" + i + \" is of full age \" + ages[i]);\n output[i] = true;\n } else {\n console.log(\"Person \" + i + \" is of partial age \" + ages[i]);\n output[i] = false;\n }\n }\n return output;\n}",
"function getValueAt(when, strictlyEarlier){\n\t\t//alert(\"RatingMovingAverage::getValueAt pt a\\r\\n\");\n\t\tif (sumRatings.length == 0){\n\t\t\treturn [new Distribution(0, 0, 0), -1];\n\t\t}\n\t\t\n\t\t//alert(\"RatingMovingAverage::getValueAt pt b\\r\\n\");\n\t\tvar firstRating = sumRatings[0];\n\t\tif(!strictlyChronologicallyOrdered(firstRating.getDate(), when)) {\n \t\t//alert(\"RatingMovingAverage::getValueAt pt c\\r\\n\");\n\t\t\treturn [new Distribution(0, 0, 0), -1];\n\t\t}\n\t\t//alert(\"RatingMovingAverage::getValueAt pt d\\r\\n\");\n\t\t\n\t\tvar latestRatingIndex = getIndexForDate(when, strictlyEarlier);\n\t\t//alert(\"index = \" + latestRatingIndex);\n\t\tvar latestRatingDate = sumRatings[latestRatingIndex].getDate();\n\t\t//alert(\"calculating duration\");\n\t\tvar duration = latestRatingDate.timeUntil(when);\n\t\t//alert(\"constructing new date\");\n\t\tvar oldestRatingDate = latestRatingDate.datePlusDuration(-duration);\n\t\t//alert(\"getting new index\");\n\t\tvar earliestRatingIndex = getIndexForDate(oldestRatingDate, true);\n\t\t//alert(\"array lookups\");\t\t\n\t\tvar latestSumRating = sumRatings[latestRatingIndex];\n\t\tvar latestSumSquaredRating = sumSquaredRatings[latestRatingIndex];\n\t\tvar earliestSumRating = sumRatings[earliestRatingIndex];\n\t\tvar earliestSumSquaredRating = sumSquaredRatings[earliestRatingIndex];\n\t\t\n\t\tvar sumY = 0.0;\n\t\tvar sumY2 = 0.0;\n\t\tvar sumWeight = 0.0;\n\t\t//alert(\"in the middle of RatingMovingAverage::pt e\\r\\n\");\n\t\t\n\t\tif(strictlyChronologicallyOrdered(oldestRatingDate, sumRatings[0].getDate())){\n\t\t\tsumY = latestSumRating.getScore();\n\t\t\tsumY2 = latestSumSquaredRating.getScore();\n\t\t\tsumWeight = latestSumRating.getWeight();\n\t\t}\n\t\telse{\n\t\t\tsumY = latestSumRating.getScore() - earliestSumRating.getScore();\n\t\t\tsumY2 = latestSumSquaredRating.getScore() - earliestSumSquaredRating.getScore();\n\t\t\tsumWeight = latestSumSquaredRating.getWeight() - earliestSumSquaredRating.getWeight();\n\t\t}\n\t\t\n\t\tvar average = sumY/sumWeight;\n\t\tvar stdDev = Math.sqrt((sumY2 - sumY * sumY/sumWeight)/sumWeight);\n\t\tvar result = new Distribution(average, stdDev, sumWeight);\n\t\t\n\t\t//alert(\"done with RatingMovingAverage::getValueAt\\r\\n\");\n\t\treturn [result, latestRatingIndex];\n\t}",
"function sumTwoSmallestNumbers(numbers) { \n let arrayNumFour = [55, 87, 2, 4, 22]\n //set the order of the array, either < , >, or vice versa\n arrayNumFour.sort()\n console.log(arrayNumFour)\n //write a line of code to find the lowest values\n \n // return sum of lowest values \n }",
"function maxminavgobject(arr){\n var max = arr[0],\n min = arr[0],\n total = arr[0],\n avg;\n //set variables max min and total to arr[0]\n for(var i =1;i<arr.length;i++){ //loop through the array starting at index1 to the end\n if(arr[i] > max){ //check if index is > max if so update max\n max = arr[i]\n }\n if(arr[i] < min){ //check if index is < min if so update min\n min = arr[i]\n }\n total+= arr[i] //update the total for the avg variable later\n }\n avg = total/arr.length ///get the avg\n return {max: max, min: min,avg: avg} //return them all in an object\n}",
"low() {\n let mark = Object.values(marks[0]).map(element => {\n return parseInt(element);\n });\n return Math.min(...mark);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the candidate positions used for the elections simulation | function getCandidatePositions() {
return candidatePositions;
} // getCandidatePositions | [
"getPlayerPositions() {\n\t\treturn {\n\t\t\tplayer1: this.paddle1Y,\n\t\t\tplayer2: this.paddle2Y\n\t\t}\n\t}",
"function getCandidatePosition(anIndex) {\n return candidatePositions[anIndex];\n } // getCandidatePosition",
"function getNumCandidates() {\n return numCandidates;\n } // getNumCandidates",
"getContainerLocations() {\n if (this.containerLocations) { return this.containerLocations; }\n\n this.containerLocations = [];\n\n this.getSourceManagers().forEach(s => {\n s.findMiningSpots().forEach(pos => {\n this.containerLocations.push(pos);\n });\n });\n\n const room = this.object('room');\n const controllerPos = this.agent('controller').object('controller').pos;\n const adjacentOpen = room.lookAtArea(\n controllerPos.y - 1, controllerPos.x - 1,\n controllerPos.y + 1, controllerPos.y - 1, true).filter(lookObj => {\n return (lookObj.type === LOOK_TERRAIN &&\n lookObj[lookObj.type] !== 'wall');\n });\n let k = 0;\n for (let i = 0; i < adjacentOpen.length; i++) {\n this.containerLocations.push({\n x: adjacentOpen[i].x,\n y: adjacentOpen[i].y\n });\n k++;\n if (k > 2) { break; }\n }\n\n return this.containerLocations;\n }",
"function getScrollPositions() {\r\n return sectionIds.map(function() {\r\n return $(this).offset().top;\r\n });\r\n }",
"function getStrategyPositionTable() {\n /**\n * TODO: need to be tuned.\n */\n\n return {\n 'P': [\n 0, 0, 0, 0, 0, 0, 0, 0,\n 5, 10, 10,-25,-25, 10, 10, 5,\n 5, -5,-10, 0, 0,-10, -5, 5,\n 0, 0, 0, 25, 25, 0, 0, 0,\n 5, 5, 10, 27, 27, 10, 5, 5,\n 10, 10, 20, 30, 30, 20, 10, 10,\n 30, 30, 30, 40, 40, 30, 30, 30,\n 50, 50, 50, 50, 50, 50, 50, 50\n ],\n\n 'N': [\n -50,-40,-30,-30,-30,-30,-40,-50,\n -40,-20, 0, 5, 5, 0,-20,-40,\n -30, 5, 10, 15, 15, 10, 5,-30,\n -30, 0, 15, 20, 20, 15, 0,-30,\n -30, 5, 15, 20, 20, 15, 5,-30,\n -30, 0, 10, 15, 15, 10, 0,-30,\n -40,-20, 0, 0, 0, 0,-20,-40,\n -50,-40,-20,-30,-30,-20,-40,-50\n ],\n\n 'B': [\n -20,-10,-40,-10,-10,-40,-10,-20\n -10, 5, 0, 0, 0, 0, 5,-10,\n -10, 10, 10, 10, 10, 10, 10,-10,\n -10, 0, 10, 10, 10, 10, 0,-10,\n -10, 5, 5, 10, 10, 5, 5,-10,\n -10, 0, 5, 10, 10, 5, 0,-10,\n -10, 0, 0, 0, 0, 0, 0,-10,\n -20,-10,-10,-10,-10,-10,-10,-20\n ],\n\n 'R': [\n 20, 10, 10, 10, 10, 10, 10, 20,\n 20, 0, 0, 0, 0, 0, 0, 20,\n 20, 0, -5,-10,-10, -5, 0, 20,\n 10, 0,-10,-15,-15,-10, 0, 10,\n 10, 0,-10,-15,-15,-10, 0, 10,\n 10, 0, -5,-10,-10, -5, 0, 10,\n 20, 0, 0, 0, 0, 0, 0, 20,\n 20, 20, 10, 10, 10, 10, 20, 20\n ],\n\n 'Q': [\n 30, 20, 20, 50, 50, 20, 20, 30,\n 20, 20, 10, 5, 5, 10, 20, 20,\n 20, 10, -5,-10,-10, -5, 10, 20,\n 30, 0,-15,-20,-20,-15, 0, 30,\n 30, 0,-15,-20,-20,-15, 0, 30,\n 20, 0,-10,-50,-50,-20, 0, 20,\n 20, 20, 0, 0, 0, 0, 20, 20,\n 30, 20, 20, 40, 40, 20, 20, 30\n ],\n\n 'K': [\n 20, 30, 10, 0, 0, 10, 30, 20,\n 20, 20, 0, 0, 0, 0, 20, 20,\n -10, -20, -20, -20, -20, -20, -20, -10,\n -20, -30, -30, -40, -40, -30, -30, -20,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30,\n -30, -40, -40, -50, -50, -40, -40, -30\n ]\n };\n}",
"function getSelectionCoordinates() \n{\n var selection = SlidesApp.getActivePresentation().getSelection();\n switch (selection.getSelectionType()) \n {\n case SlidesApp.SelectionType.PAGE_ELEMENT:\n {\n // only interested if selection is containing page elements\n var elements = selection.getPageElementRange();\n var top = 1000000;\n var left = 1000000;\n if (elements) \n {\n // find the left-most, top-most coordinate of selected elements\n var pageElements = elements.getPageElements();\n for (var i = 0; i < pageElements.length; i++) \n {\n var element = pageElements[i];\n var elementTop = element.getTop();\n var elementLeft = element.getLeft();\n if (top > elementTop)\n top = elementTop;\n if (left > elementLeft)\n left = elementLeft;\n }\n return [left, top];\n }\n }\n }\n return [0, 0];\n}",
"function getPositions(which) {\n var sv = (which == 2) ? svg2 : svg;\n var positions = [];\n sv.selectAll(\".shapecontainer\").each(function(d) {\n translate = d3.select(this).attr(\"transform\");\n pos = translate.substring(translate.indexOf(\"(\")+1, translate.indexOf(\")\")).split(\",\");\n pos[0] = +pos[0];\n pos[1] = +pos[1];\n positions.push(pos);\n });\n return positions;\n}",
"function getPosition(event) {\n var toParse = event.target.className;\n var row = toParse.substring((toParse.indexOf('row_'))+4,(toParse.indexOf('col')));\n var col = toParse.substring((toParse.indexOf('col'))+4,(toParse.length));\n return [parseInt(row), parseInt(col)];\n }",
"function getNumVotersPerElection() {\n return numVotersPerElection;\n } // getNumVoters",
"function getPositions() {\n\t\t\t\t\t// Calculate the width, height, top and left values for the image\n\t\t\t\t\t// Available width and height takes into account space for navigation buttons if in a group\n\t\t\t\t\tvar windowHeight = window.innerHeight || document.documentElement.clientHeight,\n\t\t\t\t\t\twindowWidth = window.innerWidth || document.documentElement.clientWidth,\n\t\t\t\t\t\tavailableHeight = windowHeight - settings.spacing * 2 - (group ? 40 : 0),\n\t\t\t\t\t\tavailableWidth = windowWidth - settings.spacing * 2 - (group ? 50 : 0),\n\t\t\t\t\t\t// Get the size of the image borders\n\t\t\t\t\t\tborderHeight = (parseInt($figure.css(\"borderTopWidth\") + parseInt($figure.css(\"borderBottomWidth\")))),\n\t\t\t\t\t\tborderWidth = (parseInt($figure.css(\"borderLeftWidth\") + parseInt($figure.css(\"borderRightWidth\")))),\n\t\t\t\t\t\t// Get the value to scale the image by (we want to divide by the largest side)\n\t\t\t\t\t\tscale = Math.max((imageHeight+borderHeight) / availableHeight, (imageWidth+borderWidth) / availableWidth),\n\t\t\t\t\t\tfittedHeight = imageHeight / scale,\n\t\t\t\t\t\tfittedWidth = imageWidth / scale;\n\t\t\t\t\t\n\t\t\t\t\tif(fittedWidth > imageWidth || fittedHeight > imageHeight) {\n\t\t\t\t\t\tfittedWidth = imageWidth;\n\t\t\t\t\t\tfittedHeight = imageHeight;\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\treturn {\n\t\t\t\t\t\t\"width\": Math.floor(fittedWidth-borderWidth),\n\t\t\t\t\t\t\"height\": Math.floor(fittedHeight-borderHeight),\n\t\t\t\t\t\t\"top\": Math.floor(windowHeight/2 - (fittedHeight+borderHeight)/2 + $(window).scrollTop() - (group ? 20 : 0)),\n\t\t\t\t\t\t\"left\": Math.floor(windowWidth/2 - (fittedWidth+borderWidth)/2 + $(window).scrollLeft())\n\t\t\t\t\t};\n\t\t\t\t}",
"getAllOpenPositions(){\n let result = [];\n for (let p in this.motionDetectors){\n result.push({\n name: this.motionDetectors[p].name,\n originalValue: this.motionDetectors[p].getOriginalIntensity(),\n value: this.motionDetectors[p].getIntensity()\n })\n }\n return result;\n }",
"getWallPositions() {\n this.wallPositions.length = 0;\n\n for (i = 0; i < this.rowSize * this.columnSize; i++) {\n if (this.gridArray[i].state == \"wall\") { this.wallPositions.push(i); }\n }\n return this.wallPositions;\n }",
"function getElectionsResults() {\n \t return electionsResults;\n } // getElectionsResults",
"getPosition(width, height) {\n let twidth = window.innerWidth;\n let config = document.getElementById(\"config\");\n const margin = 10;\n if (config !== null) twidth -= config.offsetWidth + margin;\n\n // Make sure that if width > twidth we place it anyway\n twidth = Math.max(this.parent_.offsetLeft + 1, twidth - width);\n let grid_size = 20;\n let divs = [];\n for (let id in this.windows_) {\n if (this.windows_[id].style.display === \"none\") continue;\n divs.push(this.windows_[id]);\n }\n // Loop through a grid of position until we reach an empty spot.\n for (let y = 0;; y += grid_size) {\n for (let x = this.parent_.offsetLeft; x <= twidth; x += grid_size) {\n let free = true;\n for (let div of divs) {\n const box = div.getBoundingClientRect();\n if (box.top >= margin + y + height) continue;\n if (box.bottom + margin <= y) continue;\n if (box.left >= x + width + margin) continue;\n if (box.right + margin <= x) continue;\n free = false;\n break;\n }\n if (free) return {x: x + margin - this.parent_.offsetLeft, y: y + margin};\n }\n // Increase the speed of the search\n if (y > 100 * grid_size) grid_size += margin;\n }\n }",
"findNeighbours(){\n \t// Array of all free directions. Starts with all directions\n\tvar freeDirections = [0,1,2,3,4,5,6,7];\n\t// First, define the eight neighbouring locations\n\tvar neighN = this.pos.copy().add(createVector(0,-1));\n\tvar neighS = this.pos.copy().add(createVector(0, 1));\n\tvar neighE = this.pos.copy().add(createVector( 1,0));\n\tvar neighW = this.pos.copy().add(createVector(-1,0));\n\tvar neighNE = this.pos.copy().add(createVector(1, -1));\n\tvar neighSE = this.pos.copy().add(createVector(1, 1));\n\tvar neighNW = this.pos.copy().add(createVector(-1,-1));\n\tvar neighSW = this.pos.copy().add(createVector(-1,1));\n\t\n\t// Make a dictionary, for translating direction-number into location\n\tvar directionDict ={};\n\tdirectionDict[0] = neighN;\n\tdirectionDict[1] = neighS;\n\tdirectionDict[2] = neighE;\n\tdirectionDict[3] = neighW;\n\tdirectionDict[4] = neighNE;\n\tdirectionDict[5] = neighSE;\n\tdirectionDict[6] = neighNW;\n\tdirectionDict[7] = neighSW;\n\t\n\t// Check if the directions are in the occuPos dictionary\n\t// And remove it from the \"freeDirections\" vector if it is\n\tif (occuPos.hasKey(posToDictKey(neighN.x,neighN.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 0){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\tif (occuPos.hasKey(posToDictKey(neighS.x,neighS.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 1){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighE.x,neighE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 2){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighW.x,neighW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 3){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNE.x,neighNE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 4){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSE.x,neighSE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 5){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNW.x,neighNW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 6){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSW.x,neighSW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 7){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Return the vector of free directions and the dictionary for translating the vector \n\treturn [freeDirections,directionDict];\n }",
"function getSpawnCoords() {\n\tx = Math.round((Math.random()*(width-3*gridSize)+gridSize)/gridSize)*gridSize;\n\ty = Math.round((Math.random()*(height-3*gridSize)+gridSize)/gridSize)*gridSize;\n\treturn [x, y];\n}",
"function getRelativeCoords(othPlayer) {\n var trueRange = getTrueRange(currPlayer);\n var relI = othPlayer.i - trueRange.truelefti;\n var relJ = othPlayer.j - trueRange.truetopj;\n return { i: relI, j: relJ };\n}",
"function calcNextDefenceCoordinates(data) {\n var ret = {x: 0, y: 0};\n\n ret.x = Math.floor((battleSettings.defenceXCounter * data.cols / battleSettings.boardResolution + battleSettings.defenceYCounter % 3 * battleSettings.defenceBlockPixelShiftX) % data.cols);\n ret.y = Math.floor((data.rows - (battleSettings.defenceYCounter * battleSettings.defenceBlockPixelShiftY)) % (data.rows - battleSettings.defenceBlockPixelShiftY));\n\n\n //make sure coordinates are in the board's range\n ret.x = ret.x % (data.cols - battleSettings.defenceBlockPixelShiftX);\n ret.y = ret.y % (data.rows - battleSettings.defenceBlockPixelShiftY);\n\n ret.x = ret.x < battleSettings.defenceBlockPixelShiftX ? battleSettings.defenceBlockPixelShiftX : ret.x;\n ret.y = ret.y <= battleSettings.defenceBlockPixelShiftY ? data.rows - battleSettings.defenceBlockPixelShiftY : ret.y;\n\n return ret;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get template data. Transform from tableName, tableComment, columns, ddl, nameCase, groupCase | _data() {
return {
nameCases: this.nameCase,
groupCases: this.groupCase,
tableName: this.tableName,
tableComment: this.tableComment,
entityClass: _string.upperFirst(_string.camelCase(this.tableName)),
entityClassCamelCase: _string.camelCase(this.tableName),
...this._mapper(this.columns)
}
} | [
"visitCreate_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_create_table_template(self, cont_id, height_px)\r\n\t{\r\n\t\tconsole.log(\"_create_table_template/\");\r\n\t\t\r\n\t\tvar tableCont = document.getElementById(cont_id);\r\n\r\n\t\tvar dchartTableDivEl = document.createElement(\"div\"); \r\n\t\tdchartTableDivEl.style = \"max-height:\"+height_px.toString()\r\n\t\t\t\t\t\t\t\t\t\t\t +\"px; overflow-y: scroll;\";\r\n\t\t\r\n\t\tvar dchartTable = document.createElement(\"table\");\r\n\t\tdchartTable.className = \"table table-striped\";\r\n\r\n\t\tdchartTableDivEl.append(dchartTable);\r\n\t\t\r\n\t\tvar dchartTableHead = document.createElement(\"thead\");\r\n\t\tdchartTableHead.innerHTML = dchart_table_head;\r\n\t\tdchartTable.append(dchartTableHead);\r\n\t\t\r\n\t\tvar dchartTableBody = document.createElement(\"tbody\");\r\n\t\tdchartTableBody.id = self.__dchar_table_body_id;\r\n\t\t\r\n\t\tdchartTable.append(dchartTableBody);\r\n\t\t\r\n\t\ttableCont.append(dchartTableDivEl);\r\n\t\t\r\n\t\tconsole.log(\"/_create_table_template\");\r\n\t}",
"function buildInfoTemplate(popupInfo) {\n var json = {\n content: \"<table>\"\n };\n\n dojo.forEach(popupInfo.fieldInfos, function (field) {\n if (field.visible) {\n json.content += \"<tr><td valign='top'>\" + field.label + \": <\\/td><td valign='top'>${\" + field.fieldName + \"}<\\/td><\\/tr>\";\n }\n });\n json.content += \"<\\/table>\";\n return json;\n}",
"function getSql(tblName, tblData, alternateName) {\n tblData = tblData || getSqlTable();\n let altName = (alternateName || tblName);\n let sql;\n if (tblName.substr(0, 4) == \"idx_\") {\n // If this is an index, we need construct the SQL differently\n let idxTbl = tblData[tblName].shift();\n let idxOn = idxTbl + \"(\" + tblData[tblName].join(\",\") + \")\";\n sql = \"CREATE INDEX \" + altName + \" ON \" + idxOn + \";\";\n } else {\n sql = \"CREATE TABLE \" + altName + \" (\\n\";\n for (let [key, type] in Iterator(tblData[tblName])) {\n sql += \" \" + key + \" \" + type + \",\\n\";\n }\n }\n\n return sql.replace(/,\\s*$/, \");\");\n}",
"function mapCaseJsonToUi(data){\n\t//\n\t// This gives me ONE object - The root for test cases\n\t// The step tag is the basis for each step in the Steps data array object.\n\t// \n\tvar items = []; \n\tvar xdata = data['step'];\n\tif (!jQuery.isArray(xdata)) xdata = [xdata]; // convert singleton to array\n\n\n\t//console.log(\"xdata =\" + xdata);\n\tkatana.$activeTab.find(\"#tableOfTestStepsForCase\").html(\"\"); // Start with clean slate\n\titems.push('<table class=\"case_configuration_table table-striped\" id=\"Step_table_display\" width=\"100%\" >');\n\titems.push('<thead>');\n\titems.push('<tr id=\"StepRow\"><th>#</th><th>Driver</th><th>Keyword</th><th>Description</th><th>Arguments</th>\\\n\t\t<th>OnError</th><th>Execute</th><th>Run Mode</th><th>Context</th><th>Impact</th><th>Other</th></tr>');\n\titems.push('</thead>');\n\titems.push('<tbody>');\n\tfor (var s=0; s<Object.keys(xdata).length; s++ ) { // for s in xdata\n\t\tvar oneCaseStep = xdata[s]; // for each step in case\n\t\t//console.log(oneCaseStep['path']);\n\t\tvar showID = parseInt(s)+1;\n\t\titems.push('<tr data-sid=\"'+s+'\"><td>'+showID+'</td>'); // ID \n\t\t// -------------------------------------------------------------------------\n\t\t// Validation and default assignments \n\t\t// Create empty elements with defaults if none found. ;-)\n\t\t// -------------------------------------------------------------------------\n\t\tfillStepDefaults(oneCaseStep);\n\t\titems.push('<td>'+oneCaseStep['@Driver'] +'</td>'); \n\t\tvar outstr; \n\t\titems.push('<td>'+oneCaseStep['@Keyword'] + \"<br>TS=\" +oneCaseStep['@TS']+'</td>'); \n\t\toutstr = oneCaseStep['Description'];\n\t\titems.push('<td>'+outstr+'</td>'); \n\n\t\tvar arguments = oneCaseStep['Arguments']['argument'];\n\t\tvar out_array = [] \n\t\tvar ta = 0; \n\t\tfor (xarg in arguments) {\n\n\t\t\tif (!arguments[xarg]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar argvalue = arguments[xarg]['@value'];\n\t\t\tconsole.log(\"argvalue\", argvalue);\n\t\t\t\tif (argvalue) {\n\t\t\t\tif (argvalue.length > 1) {\n\t\t\t\t\tvar xstr = arguments[xarg]['@name']+\" = \"+arguments[xarg]['@value'] + \"<br>\";\n\t\t\t\t\t//console.log(xstr);\n\t\t\t\t\tout_array.push(xstr); \n\t\t\t\t\t}\n\t\t\t\tta = ta + 1; \n\t\t\t\t}\n\t\t\t}\n\t\toutstr = out_array.join(\"\");\n\t\t//console.log(\"Arguments --> \"+outstr);\n\t\titems.push('<td>'+outstr+'</td>'); \n\t\toutstr = oneCaseStep['onError']['@action'] \n\t\t\t//\"Value=\" + oneCaseStep['onError']['@value']+\"<br>\"; \n\t\titems.push('<td>'+oneCaseStep['onError']['@action'] +'</td>'); \n\t\toneCaseStep['Execute']['@ExecType'] = jsUcfirst( oneCaseStep['Execute']['@ExecType']);\n\t\toutstr = \"ExecType=\" + oneCaseStep['Execute']['@ExecType'] + \"<br>\";\n\t\tif (oneCaseStep['Execute']['@ExecType'] == 'If' || oneCaseStep['Execute']['@ExecType'] == 'If Not') {\n\t\t\toutstr = outstr + \"Condition=\"+oneCaseStep['Execute']['Rule']['@Condition']+ \"<br>\" + \n\t\t\t\"Condvalue=\"+oneCaseStep['Execute']['Rule']['@Condvalue']+ \"<br>\" + \n\t\t\t\"Else=\"+oneCaseStep['Execute']['Rule']['@Else']+ \"<br>\" +\n\t\t\t\"Elsevalue=\"+oneCaseStep['Execute']['Rule']['@Elsevalue'];\n\t\t}\n\t\t \n\t\t\t\n\t\titems.push('<td>'+outstr+'</td>'); \n\t\titems.push('<td>'+oneCaseStep['runmode']['@type']+'</td>');\n\t\titems.push('<td>'+oneCaseStep['context']+'</td>');\n\t\titems.push('<td>'+oneCaseStep['impact']+'</td>'); \n\t\tvar bid = \"deleteTestStep-\"+s+\"-id-\"\n\t\titems.push('<td><i title=\"Delete\" class=\"fa fa-trash\" theSid=\"'+s+'\" id=\"'+bid+'\" katana-click=\"deleteCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"editTestStep-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Edit\" class=\"fa fa-pencil\" theSid=\"'+s+'\" value=\"Edit/Save\" id=\"'+bid+'\" katana-click=\"editCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"addTestStepAbove-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Insert\" class=\"fa fa-plus\" theSid=\"'+s+'\" value=\"Insert\" id=\"'+bid+'\" katana-click=\"addCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t\tbid = \"dupTestStepAbove-\"+s+\"-id-\";\n\t\titems.push('<i title=\"Insert\" class=\"fa fa-copy\" theSid=\"'+s+'\" value=\"Duplicate\" id=\"'+bid+'\" katana-click=\"duplicateCaseFromLine()\" key=\"'+bid+'\"/>');\n\n\t}\n\n\titems.push('</tbody>');\n\titems.push('</table>'); // \n\tkatana.$activeTab.find(\"#tableOfTestStepsForCase\").html( items.join(\"\"));\n\tkatana.$activeTab.find('#Step_table_display tbody').sortable( { stop: testCaseSortEventHandler});\n\t\n\tfillCaseDefaultGoto();\n\tkatana.$activeTab.find('#default_onError').on('change',fillCaseDefaultGoto );\n\n\t/*\n\tif (jsonCaseDetails['Datatype'] == 'Custom') {\n\t\t$(\".arguments-div\").hide();\n\t} else {\n\n\t\t$(\".arguments-div\").show();\n\t}\n\t*/\n\t\n} // end of function ",
"function generateTable() {\n emptyTable();\n generateRows();\n generateHead();\n generateColumns();\n borderWidth();\n}",
"function template(str, data) {\n return new Function(\"obj\",\n \"var p=[],print=function(){p.push.apply(p,arguments);};\" +\n\n // Introduce the data as local variables using with(){}\n \"with(obj){p.push('\" +\n\n // Convert the template into pure JavaScript\n str.replace(/[\\r\\t\\n]/g, \" \")\n .replace(/'(?=[^%]*%>)/g,\"\\t\")\n .split(\"'\").join(\"\\\\'\")\n .split(\"\\t\").join(\"'\")\n .replace(/<%=(.+?)%>/g, \"',$1,'\")\n .split(\"<%\").join(\"');\")\n .split(\"%>\").join(\"p.push('\")\n + \"');}return p.join('');\")(data || {});\n}",
"function fill (template, data) {\n\n Object.keys(data).forEach(function (key) {\n var placeholder = \"{{\" + key + \"}}\";\n var value = data[key];\n\n while (template.indexOf(placeholder) !== -1) {\n template = template.replace(placeholder, value);\n }\n });\n\n return template;\n}",
"function generateLayoutObject (layoutObjName)\n{\n\tvar tempObj = new SE_Obj ();\n\tvar layout = doAction ('DATA_GETHEADERS', 'GetRow', true, 'ObjectName', layoutObjName).split('\\t');\n\tvar layoutObj = new Array();\n\tfor (var z = 0; z < layout.length; z++)\n\t{\n\t\tif (layout[z])\n\t\t{\n\t\t\tvar test = doActionBDO (\"MPEA_BDO_DESERIALIZE\", \"SerializedBdo\", layout[z]);\n\t\t\tlayoutObj [test.name] = test;\n\t\t}\n\t}\n\treturn layoutObj;\n}",
"function templateGeneration(auth) {\n const sheets = google.sheets({version: 'v4', auth});\n sheets.spreadsheets.values.get({\n spreadsheetId: '1MJFKvrmAXp6G2J386UtdZJFfxtYjkl01fN0rzxdFo80',\n range: 'Masterlist',\n }, (err, res) => {\n if (err) return console.log('The API returned an error: ' + err);\n const df = res.data.values;\n const questions = df.map(x => x[4]); // 4th column should be the list of questions\n\n const chosen_langs = [\"Vietnamese\", \"Myanmar\"] || df[0].slice(4); \n\n // In case there was a language added/modified, generate list of available languages\n fs.writeFile('languages.json', JSON.stringify(df[0].slice(4), null, 2), (err) => {\n if (err) return console.error(err);\n console.log('List of languages available stored to', 'languages.json');\n });\n\n /* The content of template1.txt is to be pushed to App Scripts editor and executed as a google script. \n The following code translates the original template to other languages by using regex to identify \n question titles.*/ \n fs.readFile('./templates/template1.txt', 'utf8', (err, tp) => {\n if (err) throw err;\n template_files.push({\n name: 'template1',\n type: 'SERVER_JS',\n source: tp,\n })\n \n var function_names = [`template1()`]\n for (var lang of chosen_langs){\n var tmp_template = tp;\n var array = [...tp.matchAll(/\\\"[^\\\"]+\\\"/g)];\n const lang_id = df[0].findIndex((element) => element == lang); \n\n tmp_template = tmp_template.replace(\"Original\", `Language: ${lang}`)\n tmp_template = tmp_template.replace('template1', `template1_${lang}`)\n tmp_template = tmp_template.replace('Covid Response Template', `Covid Response Template (${lang} translation`)\n for (var i=0; i<array.length; i++) {\n let original_q = array[i][0].slice(1,-1);\n let q_id = questions.findIndex((element) => element.includes(original_q));\n let translated_q = df[q_id][lang_id]\n if (original_q.includes('How many days')) { \n translated_q = translated_q.split(' (')[0] // Remove the unnecessary comment for this specific question \n }\n tmp_template = tmp_template.replace(original_q, `${original_q} / ${translated_q}`);\n if (!translated_q) {\n console.log(`Warning: \\'${original_q}\\' does not have a(n) ${lang} translation.`)\n }\n }\n // Add the translated template to the list of files to be pushed to the App Scripts editor\n template_files.push({\n name: `template1_${lang}`,\n type: 'SERVER_JS',\n source: tmp_template,\n })\n function_names.push(`template1_${lang}();`)\n }\n // Add function to create all the chosen templates\n template_files.push({\n name: 'main',\n type: 'SERVER_JS',\n source: `function main() {\\n ${function_names.join(\"\\n \")}\\n}`,\n })\n });\n });\n}",
"getTableauData () {\n if (!Array.isArray(this.data) || this.data.length === 0) {\n throw new Error('Data is not an array or is an empty!!')\n }\n\n return this.data.map((row) => {\n return {\n 'values': row.insights.data.map((value) => {\n return {\n 'post_id': parseInt(row.id.split('_')[1]),\n 'page_id': parseInt(row.id.split('_')[0]),\n 'page_post_id': row.id,\n [value.name]: value.values[0].value\n }\n })\n }\n }).reduce((a, b) => {\n let values = b.values.reduce((aF, bF) => {\n let keys = Object.keys(bF)\n\n keys.map((key) => {\n aF[key] = bF[key]\n })\n return aF\n }, {})\n\n return a.concat(values)\n }, [])\n }",
"_create_table_body(self, daily_data, station_tz, serie_id)\r\n\t{\r\n\t\t\r\n\t\tvar tablebody = document.getElementById(self.__dchar_table_body_id);\r\n\t\t\r\n\t\tfor(var ts in daily_data)\r\n\t\t{\t\r\n\t\t\tif(ts != \"general\")\r\n\t\t\t{\t\r\n\t\t\t\tvar sampleRowEl = document.createElement(\"tr\");\r\n\t\t\t\tvar hm = moment(parseInt(ts)*1000).tz(station_tz)\r\n\t\t\t\t\t\t\t\t\t\t\t\t .format(\"HH:mm\");\r\n\r\n\t\t\t\tvar act = daily_data[ts][\"f_act\"].toFixed(1).toString();\r\n\t\t\t\tvar avg = daily_data[ts][\"f_avg\"].toFixed(1).toString();\r\n\t\t\t\tvar min = daily_data[ts][\"f_min\"].toFixed(1).toString();\r\n\t\t\t\tvar max = daily_data[ts][\"f_max\"].toFixed(1).toString();\r\n\t\t\t\t\r\n\t\t\t\tvar t_min = moment(daily_data[ts][\"i_min_ts\"]*1000)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.tz(station_tz)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.format(\"HH:mm\");\r\n\t\t\t\t\r\n\t\t\t\tvar t_max = moment(daily_data[ts][\"i_max_ts\"]*1000)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.tz(station_tz)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.format(\"HH:mm\");\r\n\t\t\t\tvar serieUnit = serie_getUnit(serie_id);\r\n\t\t\t\t\r\n\t\t\t\tvar tsEl = document.createElement(\"td\");\r\n\t\t\t\ttsEl.innerHTML = hm;\r\n\t\t\t\ttsEl.style = \"text-align: center;\";\r\n\t\t\t\tvar actEl = document.createElement(\"td\");\r\n\t\t\t\tactEl.innerHTML = act+serieUnit;\r\n\t\t\t\tactEl.style = \"text-align: center;\";\r\n\t\t\t\tvar avgEl = document.createElement(\"td\");\r\n\t\t\t\tavgEl.innerHTML = avg+serieUnit;\r\n\t\t\t\tavgEl.style = \"text-align: center;\";\r\n\t\t\t\tvar minEl = document.createElement(\"td\");\r\n\t\t\t\tminEl.innerHTML = min+serieUnit;\r\n\t\t\t\tminEl.style = \"text-align: center;\";\r\n\t\t\t\tvar maxEl = document.createElement(\"td\");\r\n\t\t\t\tmaxEl.innerHTML = max+serieUnit;\r\n\t\t\t\tmaxEl.style = \"text-align: center;\";\r\n\t\t\t\tvar tMaxEl = document.createElement(\"td\");\r\n\t\t\t\ttMaxEl.innerHTML = t_max;\r\n\t\t\t\ttMaxEl.style = \"text-align: center;\";\r\n\t\t\t\tvar tMinEl = document.createElement(\"td\");\r\n\t\t\t\ttMinEl.innerHTML = t_min;\r\n\t\t\t\ttMinEl.style = \"text-align: center;\";\r\n\t\t\t\t\r\n\t\t\t\tsampleRowEl.append(tsEl);\r\n\t\t\t\tsampleRowEl.append(actEl);\r\n\t\t\t\tsampleRowEl.append(avgEl);\r\n\t\t\t\tsampleRowEl.append(maxEl);\r\n\t\t\t\tsampleRowEl.append(tMaxEl);\r\n\t\t\t\tsampleRowEl.append(minEl);\r\n\t\t\t\tsampleRowEl.append(tMinEl);\r\n\t\t\t\ttablebody.append(sampleRowEl);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function createTable() {\n if (config.data.length === 0) {\n console.log(`No data for table at ${tableSelector}`);\n // Remove any order directive to avoid Datatables errors\n delete config['order'];\n return this;\n }\n htTable.DataTable(config);\n dtapi = htTable.DataTable();\n const customFilterIds = Object.keys(filterFields);\n if (customFilterIds.length > 0) {\n const fields = customFilterIds.map(key => filterFields[key].html).join('');\n $(tableSelector + '_wrapper .right-filters').append(`<span class=\"form-group ml-4 pull-right\">${fields}</span>`);\n customFilterIds.forEach(key => {\n if (filterFields[key].hdlr) { $(`#${key}`).change(filterFields[key].hdlr); }\n if (filterFields[key].defaultChoice) { $(`#${key}`).trigger('change'); }\n });\n }\n // configureSearchReset();\n if (rowBtns.length > 0) {\n rowBtns.forEach(btn => { activateButton(btn); });\n htTable.on('draw.dt', function () {\n rowBtns.forEach(btn => { activateButton(btn); });\n });\n htTable.on('page.dt', function () {\n rowBtns.forEach(btn => { activateButton(btn); });\n });\n }\n return this;\n }",
"function prepareDecorationTable(table, assets)\n{\n jq.each(table, function(item) {\n if(table[item].type == \"pattern\")\n {\n table[item].fill = assets.getResult(table[item].fill_id);\n }\n });\n}",
"function CreateTblHeader(field_setting, col_hidden) {\n //console.log(\"=== CreateTblHeader ===== \");\n //console.log(\"field_setting\", field_setting);\n //console.log(\"col_hidden\", col_hidden);\n\n const column_count = field_setting.field_names.length;\n\n// +++ insert header and filter row ++++++++++++++++++++++++++++++++\n let tblRow_header = tblHead_datatable.insertRow (-1);\n let tblRow_filter = tblHead_datatable.insertRow (-1);\n\n // --- loop through columns\n for (let j = 0; j < column_count; j++) {\n const field_name = field_setting.field_names[j];\n\n // --- skip column if in columns_hidden\n if (!col_hidden.includes(field_name)){\n\n // --- get field_caption from field_setting,\n const field_caption = loc[field_setting.field_caption[j]];\n const field_tag = field_setting.field_tags[j];\n const filter_tag = field_setting.filter_tags[j];\n const class_width = \"tw_\" + field_setting.field_width[j] ;\n const class_align = \"ta_\" + field_setting.field_align[j];\n\n// ++++++++++ insert columns in header row +++++++++++++++\n // --- add th to tblRow_header +++\n let th_header = document.createElement(\"th\");\n // --- add div to th, margin not working with th\n const el_header = document.createElement(\"div\");\n el_header.innerText = (field_caption) ? field_caption : null;\n // --- add left border\n if(field_setting.cols_left_border && field_setting.cols_left_border.includes(j)){\n th_header.classList.add(\"border_left\");\n };\n\n // --- add width, text_align\n el_header.classList.add(class_width, class_align);\n th_header.appendChild(el_header)\n tblRow_header.appendChild(th_header);\n\n// ++++++++++ create filter row +++++++++++++++\n // --- add th to tblRow_filter.\n const th_filter = document.createElement(\"th\");\n // --- create element with tag based on filter_tag\n const filter_field_tag = ([\"text\", \"number\"].includes(filter_tag)) ? \"input\" : \"div\";\n const el_filter = document.createElement(filter_field_tag);\n // --- add data-field Attribute.\n el_filter.setAttribute(\"data-field\", field_name);\n el_filter.setAttribute(\"data-filtertag\", filter_tag);\n //el_filter.setAttribute(\"data-colindex\", j);\n // --- add EventListener to el_filter\n if ([\"text\", \"number\"].includes(filter_tag)) {\n el_filter.addEventListener(\"keyup\", function(event){HandleFilterKeyup(el_filter, event)});\n add_hover(th_filter);\n } else if (filter_tag === \"status\") {\n // add EventListener for icon to th_filter, not el_filter\n th_filter.addEventListener(\"click\", function(event){HandleFilterStatus(el_filter)});\n th_filter.classList.add(\"pointer_show\");\n el_filter.classList.add(\"diamond_3_4\"); // diamond_3_4 is blank img\n add_hover(th_filter);\n\n } else if (filter_tag === \"toggle\") {\n // add EventListener for icon to th_filter, not el_filter\n th_filter.addEventListener(\"click\", function(event){HandleFilterToggle(el_filter)});\n th_filter.classList.add(\"pointer_show\");\n };\n // --- add other attributes\n if (filter_tag === \"text\") {\n el_filter.setAttribute(\"type\", \"text\")\n el_filter.classList.add(\"input_text\");\n\n el_filter.setAttribute(\"autocomplete\", \"off\");\n el_filter.setAttribute(\"ondragstart\", \"return false;\");\n el_filter.setAttribute(\"ondrop\", \"return false;\");\n };\n\n // --- add left border\n if(field_setting.cols_left_border && field_setting.cols_left_border.includes(j)){\n th_filter.classList.add(\"border_left\");\n };\n\n // --- add width, text_align, color\n el_filter.classList.add(class_width, class_align, \"tsa_color_darkgrey\", \"tsa_transparent\");\n\n th_filter.appendChild(el_filter)\n tblRow_filter.appendChild(th_filter);\n } // if (!columns_hidden[field_name])\n } // for (let j = 0; j < column_count; j++)\n\n }",
"_createLiquibaseChangelog() {\n const time = moment().format('YYYYMMDDHHmmss')\n const filename = `${time}_add_table_${this.tableName}`\n const data = {\n filename,\n ddl: this.ddl,\n tableName: this.tableName\n }\n this.generator.fs.copyTpl(this.generator.templatePath(`_changelog.sql`), this.generator.destinationPath(`src/main/resources/liquibase/changelog/${filename}.sql`), data)\n }",
"function dataForTable(response) {\n return response;\n }",
"function getInputFieldsHtml(template_name)\n{\n //variables which change depending on the input type\n var num_input_index=0;\n var str_dynamic_index=0;\n var data = \"\";\n var cls = \"\";\n var input_type=\"\";\n var fieldName=\"\";\n\n var html=\"<div class='\"+template_name+\"-input'>\";\n var endDiv =\"</div>\";\n\n var template = getTemplateByID(template_name);\n var fieldID = template.id;\n\n //loop through all fields for each input type\n\n for(var i=0; i<template.str_fields.length; i++)\n {\n data=\"\";\n cls=\"\";\n input_type=\"\";\n fieldName = template.str_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.num_fields.length; i++)\n {\n input_type = \"-number\";\n num_input_index+=1;\n data = 'data-index=\"'+num_input_index+'\" ';\n cls=\" \"+fieldID+\"-input-field \";\n fieldName = template.num_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.img_fields.length; i++)\n {\n input_type=\"-img\";\n data=\"\";\n cls=\"\";\n fieldName = template.img_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.hero_icon.length; i++)\n {\n input_type=\"-hero\";\n data = 'data-folder=\"hero-icons\" ';\n cls=\"\";\n fieldName = template.hero_icon[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.hero_portrait.length; i++)\n {\n input_type=\"-hero\";\n data = 'data-folder=\"hero-portraits\" ';\n cls=\"\";\n fieldName = template.hero_portrait[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.str_dynamic.length; i++)\n {\n data = 'data-index=\"'+str_dynamic_index+'\" ';\n cls=\"-dynamic-str\";\n input_type=\"\";\n fieldName = template.str_dynamic[i];\n str_dynamic_index+=1;\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.team.length; i++)\n {\n data=\"\";\n cls=\"\";\n fieldName = template.team[i];\n input_type=\"-team\";\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n return html + endDiv;\n}",
"function tableContents(fileId,headers) {\n \n var doc = DocumentApp.openById(fileId);\n var tables = doc.getBody().getTables();\n var r;\n var c;\n var cellNumber = 0;\n var cellHeader;\n var cellContent;\n var tableContent = [];\n tableContent[0] = [];\n var formatHeader = DocumentApp.ParagraphHeading.HEADING2;\n \n \n for (var i = 0; i < tables.length; i++) {\n \n var RowNumber = tables[i].asTable().getNumRows();\n \n for (r=0; r<RowNumber; r++) {\n var Row = tables[i].asTable().getChild(r)\n var CellsInRow = Row.asTableRow().getNumCells();\n \n for (c=0; c<CellsInRow; c++) {\n var cell = Row.asTableRow().getChild(c)\n cell.getChild(0).asText().setText(headers[cellNumber]); //updates table cell header from header array from template\n cellHeader = cell.getChild(0).asText().getText()\n cell.getChild(0).asParagraph().setHeading(formatHeader);\n cellContent = cell.asText().getText();\n cellContent = cellContent.replace(cellHeader,\"\"); //removes cell header from cell content\n tableContent[0].push(cellContent); //adds to array an object with header and content names\n cellNumber++;\n } }\n }\n \n \n return tableContent;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render the dispatch day count chart | function renderDayCountChart() {
//Day keys
days = [];
//Count values
counts = [];
//Split the day_counts into keys and values for the line chart
for (var day in day_counts) {
days.push(day);
counts.push(day_counts[day]);
}
var ctx = document.getElementById('dispatchDayCountsChart').getContext('2d');
var dispatchDayCountChart = new Chart(ctx, {
type: 'line',
data: {
labels: days,
datasets: [{
label: "Dispatch Counts per Day",
data: counts,
borderColor: '#ea6a2e',
backgroundColor: '#ea6a2e',
fill: false
}]
},
options: {
elements: {
line: {
tension: 0, // disables bezier curves
}
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: "Dates",
fontSize: 14,
fontColor: '#000000'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: "Count",
fontSize: 14,
fontColor: '#000000'
}
}]
}
}
});
} | [
"function drawCategoryChart() {\n\t\n\tvar entertainmentnum = 0\n\tvar productivitynum = 0\n\tvar othernum = 0\n\tvar shoppingnum = 0\n\tvar data\n\tif(!useDateRangeSwitch)\n\t\tdata = listSiteData(globsiteData)\n\telse \n\t\tdata = listSiteData(dateRangeData)\n\n\tfor (i=1; i<data.length; i++){\n\t\ttemp = String(data[i][0]).trim()\n\t\tif(globCategoriesHostname.includes(temp)){\n\t\t\tif(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Entertainment\")\n\t\t\t\tentertainmentnum += data[i][1]\n\t\t\telse if(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Productivity\")\n\t\t\t\tproductivitynum+=data[i][1]\n\t\t\telse if(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Shopping\")\n\t\t\t\tshoppingnum+=data[i][1]\n\t\t}\n\t\telse \n\t\t\tothernum+=data[i][1]\n\t}\n\tvar catData = [\n\t\t['Task', 'Hours per Day'],\n\t\t['Entertainment', entertainmentnum],\n\t\t['Productivity', productivitynum],\n\t\t['Shopping', shoppingnum],\n\t\t['Other', othernum],\n\t];\n\n\tcatData.sort(function(a,b){\n\t\treturn b[1]-a[1] //high to low\n\t});\n\t\n\tvar processeddata = google.visualization.arrayToDataTable(catData);\n\n\tvar options = {\n\t title: 'Daily Screentime By Category'\n\t};\n\n\t//piechart\n\tvar piechart_options = {\n\t\ttitle: 'Pie Chart: My Daily Screentime'\n\t\t};\n\tvar piechart = new google.visualization.PieChart(document.getElementById('piechart'));\n\tpiechart.draw(processeddata, piechart_options);\n\n\t//barchart\n\tvar barchart_options = {\n\t\ttitle: 'Bar Chart: My Daily Screentime'\n\t}\n\tvar barchart = new google.visualization.BarChart(document.getElementById('barchart'));\n\tbarchart.draw(processeddata, barchart_options);\n}",
"function renderDispatchTypeCountChart(bat_number) {\n\n var counts = battalions[\"Battalion\" + bat_number].dispatch_type_counts;\n\n var total_count = battalions[\"Battalion\" + bat_number].total_dispatch_count;\n\n var disCountChart = document.getElementById(\"dis_counts_chart\");\n\n //Destroy the previous chart\n if (hasRendered)\n thePieChart.destroy();\n\n thePieChart = new Chart(disCountChart, {\n type: 'doughnut',\n data: {\n labels: [\"Medical Incident\", \"Fire\", \"Traffic Collision\", \"Alarms\", \"Other\"],\n datasets: [\n { \n label: \"Type\",\n backgroundColor: [\"#3e95cd\", \"#8e5ea2\",\"#3cba9f\",\"#c03095\",\"#c45850\"],\n data: counts\n }\n ]\n },\n options: {\n title: {\n display: true,\n text: \"Dispatch counts\",\n maintainAspectRatio: false,\n }\n }\n });\n\n //Set the various key totals\n $('#total_count').text('Total: ' + total_count);\n $('#med_counts').html(\"Medical: \" + counts[0] + '<br/>(' + (counts[0] / total_count * 100).toFixed(2) + '%)');\n $('#fire_counts').html('Fires: ' + counts[1] + '<br/>(' + (counts[1] / total_count * 100).toFixed(2) + '%)');\n $('#traf_counts').html('Traffic: ' + counts[2] + '<br/>(' + (counts[2] / total_count * 100).toFixed(2) + '%)')\n $('#alarm_counts').html('Alarms: ' + counts[3] + '<br/>(' + (counts[3] / total_count * 100).toFixed(2) + '%)')\n $('#other_counts').html('Other: ' + counts[4] + '<br/>(' + (counts[4] / total_count * 100).toFixed(2) + '%)')\n}",
"function renderChart() {\n requestAnimationFrame(renderChart);\n\n analyser.getByteFrequencyData(frequencyData);\n\n if(colorToggle == 1){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleRainbow(colorInterpolateRainbow(frequencyData[i])); })\n }\n\n if(colorToggle == 2){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleGray(colorInterpolateGray(frequencyData[i])); })\n }\n }",
"function calcTotalDayAgain() {\n var eventCount = $this.find('.everyday .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }",
"function dailyQuestionsChart (result) {\n // Get chart data\n function getMessages (data, channelFilter) {\n const channels = {}\n\n data.forEach(item => {\n const channel = item.MessageText; const id = item.MessageID\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n channels[channel].push(id)\n }\n }\n })\n\n for (channel in channels) {\n channels[channel] = channels[channel].length\n }\n\n return channels\n };\n\n // Sort chart keys descending\n function sortKeysDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] })\n };\n\n // Sort chart values descending\n function sortValuesDescending (array) {\n var keys = keys = Object.keys(array)\n return keys.sort(function (a, b) { return array[b] - array[a] }).map(key => array[key])\n };\n\n // Combine chart keys and values\n function combineKeysAndValues (keys, values) {\n var result = {}\n for (var i = 0; i < keys.length; i++) { result[keys[i]] = values[i] }\n return result\n }\n\n var dailyArrayKeys = sortKeysDescending(getMessages(result))\n var dailyArrayValues = sortValuesDescending(getMessages(result))\n var dailyCombinedArray = combineKeysAndValues(dailyArrayKeys, dailyArrayValues)\n\n // Set data and labels\n var labels = Object.keys(dailyCombinedArray)\n var data = Object.values(dailyCombinedArray)\n\n document.getElementById('dailyTotalQuestions').innerHTML = ''\n\n // Create chart\n var canvas = document.getElementById('dailyQuestionsChart')\n var ctx = canvas.getContext('2d')\n\n var chart = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: labels,\n datasets: [{\n label: '# of Messages',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Questions'\n },\n legend: {\n display: false\n },\n scales: {\n yAxes: [{\n gridLines: {\n display: false\n },\n ticks: {\n beginAtZero: true,\n stepSize: 1\n }\n }]\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n },\n datalabels: {\n display: function (context) {\n return context.dataset.data[context.dataIndex] !== 0 // or >= 1 or ...\n }\n }\n }\n }\n })\n}",
"function dailyMessagesChart (result) {\n // Get chart data\n function getMessagesByChannel (data, channelFilter) {\n const channels = {}\n\n data.forEach(item => {\n const channel = item.MessageChannel; const id = item.MessageID\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n channels[channel].push(id)\n }\n }\n })\n\n for (channel in channels) {\n channels[channel] = channels[channel].length\n }\n\n return channels\n };\n\n // Set data and labels\n var labels = Object.keys(getMessagesByChannel(result))\n var data = Object.values(getMessagesByChannel(result))\n var dailyTotalMessages = sumArrayValues(getMessagesByChannel(result))\n document.getElementById('dailyTotalMessages').innerHTML = dailyTotalMessages\n\n // Create chart\n var ctx = document.getElementById('dailyMessagesChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'doughnut',\n data: {\n labels: labels,\n datasets: [{\n label: 'Channels',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Messages by Channel'\n },\n legend: {\n position: 'bottom'\n },\n scales: {\n gridLines: {\n display: false\n }\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n }\n }\n }\n })\n}",
"function renderDate() {\n fill(\"black\");\n noStroke();\n textAlign(LEFT, CENTER);\n textSize(height / 2);\n const currentDate = new Date(state.date.from);\n currentDate.setUTCDate(\n currentDate.getUTCDate() + Math.floor(state.daysPassed)\n );\n text(\n currentDate.toISOString().slice(0, 10),\n 30,\n topOffset - gridAreaHeight / 2\n );\n}",
"function drawVotesChart() {\n fetch(DISHES_URL).then(response => response.json())\n .then((dishVotes) => {\n const data = new google.visualization.DataTable();\n data.addColumn('string', 'Dish');\n data.addColumn('number', 'Votes');\n Object.keys(dishVotes).forEach((dish) => {\n data.addRow([dish, dishVotes[dish]]);\n });\n\n const options = {\n 'title': CHARTS_TITLES.DISHES_BAR_CHART,\n 'width': 600,\n 'height': 500\n };\n\n const chart = new google.visualization.ColumnChart(\n document.getElementById(DOM_CONTAINARS_IDS.DISHES_CHART));\n chart.draw(data, options);\n });\n}",
"function drawDayLabels() {\n const dayLabelsGroup = svg.select('.day-labels-group');\n const arrayForYAxisLabels = yAxisLabels || daysHuman;\n\n dayLabels = svg.select('.day-labels-group').selectAll('.day-label')\n .data(arrayForYAxisLabels);\n\n dayLabels.enter()\n .append('text')\n .text((label) => label)\n .attr('x', 0)\n .attr('y', (d, i) => i * boxSize)\n .style('text-anchor', 'start')\n .style('dominant-baseline', 'central')\n .attr('class', 'day-label');\n\n dayLabelsGroup.attr('transform', `translate(-${dayLabelWidth}, ${boxSize / 2})`);\n }",
"function renderChartStatistics() {\n //we only want to draw the chart once.\n //populate data for the chart.\n populateChartNames();\n populateVotes();\n populateViews();\n if(!chartDrawn){\n drawChart();\n showChart();\n console.log('chart was drawn');\n }else{\n imageChart.update();\n showChart();\n }\n}",
"renderPowerOutputBar() {\n let dataSource = {};\n let categories = [];\n let series = [];\n this.loadingPowerOutputBar = true;\n this.client\n .get('/statistics/projectUtilization/poweroutputkwdaily')\n .then(res => {\n if (res && res.data) {\n for (let i = 0; i < res.data.length; i++) {\n let day = moment(new Date()).format('dddd');\n categories.push(res.data[i]._project.name);\n if (!dataSource[day]) {\n dataSource[day] = [res.data[i].powerOutputKW];\n } else {\n dataSource[day].push(res.data[i].powerOutputKW);\n }\n }\n for (let key in dataSource) {\n series.push({\n name: key,\n data: dataSource[key]\n });\n }\n\n //render bar chart\n $('#powerOutputBar').kendoChart({\n title: {\n text: 'Daily Output Generated'\n },\n theme: 'material',\n legend: {\n position: 'top'\n },\n seriesDefaults: {\n type: 'column'\n },\n seriesColors: ['#00838f', '#0097a7', '#00acc1', '#00bcd4', '#26c6da', '#4dd0e1', '#80deea', '#b2ebf2', '#e0f7fa'],\n series: series,\n valueAxis: {\n labels: {\n format: '{0} kVA'\n },\n line: {\n visible: true\n },\n axisCrossingValue: 0\n },\n categoryAxis: {\n categories: categories,\n line: {\n visible: false\n }\n },\n tooltip: {\n visible: true,\n format: '{0} kVA',\n template: '#= series.name #: #= value # kVA'\n }\n });\n this.loadingPowerOutputBar = false;\n }\n });\n }",
"function showAccidentsMonth(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"date\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let minDate = dim.bottom(1)[0].date;\n let maxDate = dim.top(1)[0].date;\n\n let composite = dc.compositeChart(\"#composite-month\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 10, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.time.scale().domain([minDate, maxDate]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" accidents\";\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .interpolate(\"monotone\")\n .group(totalCasByHour, \"Casualties\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" casualties\";\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" vehicles involved\";\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"8%\")\n .xAxis().ticks(12).tickFormat(d3.time.format(\"%b\")).outerTickSize(0);\n\n composite.yAxis().ticks(5).outerTickSize(0);\n}",
"function dailyConversationsChart (result) {\n // Get chart data\n function getConversationsByChannel (data, channelFilter) {\n const channels = {}\n\n // Loops through the data to build the `channels` object\n data.forEach(item => {\n const channel = item.MessageChannel; const id = item.ConversationID\n\n // Makes sure there is no filter, or channel matches filter, before proceeding\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n // Adds a property to the `channels` object. Its value is an array including one item: the ConversationID.\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n // Add a new ConversationID to the array for this channel\n channels[channel].push(id)\n }\n }\n })\n\n // Replaces the property's value with a number indicating the number of unique conversations\n for (var channel in channels) {\n // Uses `for...in` to loop through object properties\n channels[channel] = channels[channel].length\n }\n\n return channels\n }\n // Set data and labels\n var labels = Object.keys(getConversationsByChannel(result))\n var data = Object.values(getConversationsByChannel(result))\n var dailyTotalConversations = sumArrayValues(getConversationsByChannel(result))\n document.getElementById('dailyTotalConversations').innerHTML = dailyTotalConversations\n\n // Create chart\n var ctx = document.getElementById('dailyConversationsChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'doughnut',\n data: {\n labels: labels,\n datasets: [{\n label: 'Channels',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Conversations by Channel'\n },\n legend: {\n position: 'bottom'\n },\n scales: {\n gridLines: {\n display: false\n }\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n }\n }\n }\n })\n}",
"function dailyTimeChart (result) {\n // Get chart data\n function getMessagesByHour (data, channelFilter) {\n const channels = {}\n\n // Loops through the data to build the `channels` object\n data.forEach(item => {\n const channel = moment(item.MessageTime).format('YYYY-MM-DDTHH'); const id = item.MessageID\n\n // Makes sure there is no filter, or channel matches filter, before proceeding\n if (!channelFilter || channelFilter === channel) {\n if (!channels[channel]) {\n // Adds a property to the `channels` object. Its value is an array including one item: the MessageID.\n channels[channel] = [id]\n } else if (!channels[channel].includes(id)) {\n // Add a new MessageID to the array for this channel\n channels[channel].push(id)\n }\n }\n })\n\n // Replaces the property's value with a number indicating the number of unique conversations\n for (var channel in channels) {\n // Uses `for...in` to loop through object properties\n channels[channel] = channels[channel].length\n }\n return channels\n }\n\n // Push 0s where data is missing\n var timeArray = getMessagesByHour(result)\n\n var today = Object.keys(timeArray)\n var todayDate = moment(today[0]).format('YYYY-MM-DD')\n\n const timeLabels = []\n const timeData = []\n\n const date = moment(todayDate + 'T00:00')\n const endDate = moment(todayDate + 'T23:59')\n\n do {\n const dateStr = date.format('YYYY-MM-DDTHH')\n timeLabels.push(dateStr)\n\n if (timeArray.hasOwnProperty(dateStr)) { timeData.push(timeArray[dateStr]) } else { timeData.push(0) }\n\n date.add(1, 'hour')\n } while (date.isBefore(endDate))\n\n // Set data and labels\n var labels = timeLabels\n var data = timeData\n\n document.getElementById('dailyTotalTime').innerHTML = ''\n\n // Create chart\n var ctx = document.getElementById('dailyTimeChart').getContext('2d')\n var chart = new Chart(ctx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: '# of Messages',\n data: data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'Messages Received'\n },\n legend: {\n display: false\n },\n scales: {\n xAxes: [{\n type: 'time',\n time: {\n displayFormats: {\n minute: 'HH:mm'\n },\n unit: 'hour',\n min: todayDate + 'T00:00',\n max: todayDate + 'T23:39'\n }\n }],\n yAxes: [{\n gridLines: {\n display: false\n },\n ticks: {\n beginAtZero: true,\n stepSize: 1\n }\n }]\n },\n plugins: {\n colorschemes: {\n scheme: chartColorScheme\n },\n datalabels: {\n display: function (context) {\n return context.dataset.data[context.dataIndex] !== 0 // or >= 1 or ...\n }\n }\n }\n }\n })\n}",
"function renderPieChart() {\n var i, x, y, r, a1, a2, set, sum;\n\n i = 0;\n x = width / 2;\n y = height / 2;\n r = Math.min(x, y) - 2;\n a1 = 1.5 * Math.PI;\n a2 = 0;\n set = sets[0];\n sum = sumSet(set);\n\n for (i = 0; i < set.length; i++) {\n ctx.fillStyle = getColorForIndex(i);\n ctx.beginPath();\n a2 = a1 + (set[i] / sum) * (2 * Math.PI);\n\n // TODO opts.wedge\n ctx.arc(x, y, r, a1, a2, false);\n ctx.lineTo(x, y);\n ctx.fill();\n a1 = a2;\n }\n }",
"function show_pie_status(ndx) {\n var statusColors = d3.scale.ordinal()\n .domain([\"Completed\", \"Ongoing\", \"Pending\"])\n .range([\"#8FBC8F\", \"#FAFAD2\", \"#FFB6C1\"]);\n var dim = ndx.dimension(dc.pluck('status'));\n var group = dim.group();\n dc.pieChart(\"#bug-chart\")\n .height(250)\n .radius(125)\n .colors(statusColors)\n .transitionDuration(1500)\n .dimension(dim)\n .group(group)\n .on(\"renderlet\", function(chart) {\n chart.selectAll('text.pie-slice').text( function(d) {\n return 'Bugs' + ' ' + d.data.key + ' ' + dc.utils.printSingleValue((d.endAngle - d.startAngle) / (2*Math.PI) * 100) + '%';\n });\n });\n}",
"function drawTermDatesGraph() {\n // Get the elements we need\n var graphContainer = $('.term_dates_graph');\n var tableContainer = $('.term_dates_table');\n if (graphContainer.length === 0 || tableContainer.length === 0)\n return;\n\n var results = $.parseJSON(window.json_data);\n\n // Make a DataTable object\n var data = new google.visualization.DataTable();\n var rows = results.data;\n\n data.addColumn('number', results.year_header);\n data.addColumn('number', results.value_header);\n data.addRows(rows);\n\n // Make the line chart object\n var w = $(window).width();\n if (w > 750) {\n w = 750;\n }\n\n var h;\n if (w > 480) {\n h = 480;\n } else {\n h = w;\n }\n\n var options = { width: w, height: h,\n legend: { position: 'none' },\n hAxis: { format: '####',\n title: results.year_header },\n vAxis: { title: results.value_header },\n pointSize: 3 };\n\n var chart = new google.visualization.LineChart(graphContainer[0]);\n chart.draw(data, options);\n\n graphContainer.trigger('updatelayout');\n\n // Make a pretty table object\n var table = new google.visualization.Table(tableContainer[0]);\n table.draw(data, { page: 'enable', pageSize: 20, sortColumn: 0,\n width: '20em' });\n}",
"function showAccidentsHour(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"hour\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let composite = dc.compositeChart(\"#composite-hour\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 20, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.scale.linear().domain([0, 23]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\")\n .attr(\"dx\", \"-30\")\n .attr(\"dy\", \"-5\")\n .attr(\"transform\", \"rotate(-90)\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" accidents at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" accidents at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalCasByHour, \"Casualties\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" casualties at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" casualties at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" vehicles involved at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" vehicles involved at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"2%\")\n .xAxis().ticks(24).tickFormat(function(d) {\n if (d < 10) {\n return \"0\" + d + \":00\";\n }\n else { return d + \":00\"; }\n }).outerTickSize(0);\n composite.yAxis().ticks(5).outerTickSize(0);\n}",
"render() {\n\t\t\tthis.containerElement.fullCalendar(\"removeEvents\");\n\t\t\tthis.containerElement.fullCalendar(\"addEventSource\", [].concat(this.state.schedule));\n\n\t\t\tthis.setDateItemColor();\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a simple object containing the tab head and body elements. | function TabDom(h, b) {
this.head = h;
this.body = b;
} | [
"get horseProfile_TabsHeader() {return browser.element(\"\");}",
"function WMEAutoUR_Create_TabbedUI() {\n\tWMEAutoUR_TabbedUI = {};\n\t/**\n\t *@since version 0.11.0\n\t */\n\tWMEAutoUR_TabbedUI.init = function() {\n // See if the div is already created //\n\t\tvar urParentDIV = null;\n\t\tif ($(\"#WME_AutoUR_TAB_main\").length===0) {\n urParentDIV = WMEAutoUR_TabbedUI.ParentDIV();\n $(urParentDIV).append(WMEAutoUR_TabbedUI.Title());\n //$(ParentDIV).append($('<span>').attr(\"id\",\"WME_AutoUR_Info\")\n //\t\t\t\t\t\t\t\t.click(function(){$(this).html('');})\n //\t\t\t\t\t\t\t\t.css(\"color\",\"#000000\"));\n\n $(urParentDIV).append(WMEAutoUR_TabbedUI.TabsHead());\n\n var TabBody = WMEAutoUR_TabbedUI.TabsBody();\n\n $(TabBody).append(WMEAutoUR_TabbedUI.EditorTAB);\n //$(TabBody).append(WMEAutoUR_TabbedUI.MessagesTAB);\n $(TabBody).append(WMEAutoUR_TabbedUI.SettingsTAB);\n\n $(urParentDIV).append(TabBody);\n\n\t\t// See if the div is already created //\n\t\t//if ($(\"#WME_AutoUR_TAB_main\").length===0) {\n\n\t\t\tconsole.info(\"WME-WMEAutoUR_TabbedUI: Loaded Pannel\");\n\t\t\t//ScriptKit.GUI.addImage(1,icon,WMEAutoUR_TabbedUI.hideWindow);\n }\n\n\t\t$(\"div.tips\").after(urParentDIV);\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV TOGGLE --------- //\n\tWMEAutoUR_TabbedUI.hideWindow = function() {\n\n\t\tswitch($(\"#WME_AutoUR_TAB_main\").css(\"height\")) {\n\t\t\tcase '30px': \t$(\"#WME_AutoUR_TAB_main\").css(\"height\",\"auto\");\n\t\t\t\t\t\t\t$(\"#WMEAutoUR_TabbedUI_toggle\").html(\"-\");\n\t\t\t\t\t\t\tWMEAutoUR.on();\t\tbreak;\n\t\t\tdefault:\t\t$(\"#WME_AutoUR_TAB_main\").css(\"height\",\"30px\");\n\t\t\t\t\t\t\t$(\"#WMEAutoUR_TabbedUI_toggle\").html(\"+\");\n\t\t\t\t\t\t\tWMEAutoUR.off();\tbreak;\n\t\t}\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.ParentDIV = function() {\n\n\t\tvar MainTAB = $('<div>').attr(\"id\",\"WME_AutoUR_TAB_main\")\n\t\t\t\t\t\t\t\t.css(\"color\",\"#FFFFFF\")\n\t\t\t\t\t\t\t\t.css(\"border-bottom\",\"2px solid #E9E9E9\")\n\t\t\t\t\t\t\t\t.css(\"margin\",\"21px 0\")\n\t\t\t\t\t\t\t\t.css(\"padding-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t.css(\"max-width\",\"275px\")\n\t\t\t\t\t\t\t\t.css(\"height\",\"30px\")\n\t\t\t\t\t\t\t\t.css(\"overflow\",\"hidden\")\n\t\t\t\t\t\t\t\t.css(\"display\",\"block\");\n\n\t\treturn MainTAB;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.Title = function() {\n\t\tconsole.info(\"WME-WMEAutoUR_TabbedUI: create main div \");\n\n\t\t// ------- TITLE ------- //\n\t\tvar mainTitle = $(\"<div>\")\n\t\t\t\t\t\t.attr(\"id\",\"WME_AutoUR_TAB_title\")\n\t\t\t\t\t\t.css(\"width\",\"100%\")\n\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t.css(\"background-color\",\"rgb(93, 133, 161)\")\n\t\t\t\t\t\t.css(\"border-radius\",\"5px\")\n\t\t\t\t\t\t.css(\"padding\",\"3px\")\n\t\t\t\t\t\t.css(\"margin-bottom\",\"3px\")\n\t\t\t\t\t\t.html(\"WME-AutoUR \" + WMEAutoUR.version)\n\t\t\t\t\t\t.dblclick(WMEAutoUR.showDevInfo)\n\t\t\t\t\t\t.attr(\"title\",\"Click for Development Info\");\n\n\t\t$(mainTitle).append($('<div>').attr(\"id\",\"WMEAutoUR_TabbedUI_toggle\")\n\t\t\t\t\t\t\t\t\t .html(\"+\")\n\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t .css(\"color\",\"#ffffff\")\n\t\t\t\t\t\t\t\t\t .css(\"right\",\"3px\")\n\t\t\t\t\t\t\t\t\t .css(\"top\",\"0\")\n\t\t\t\t\t\t\t\t\t .css(\"background\",\"#000000\")\n\t\t\t\t\t\t\t\t\t .css(\"height\",\"16px\")\n\t\t\t\t\t\t\t\t\t .css(\"width\",\"16px\")\n\t\t\t\t\t\t\t\t\t .css(\"display\",\"block\")\n\t\t\t\t\t\t\t\t\t .css(\"line-height\",\"14px\")\n\t\t\t\t\t\t\t\t\t .css(\"border-radius\",\"5px\")\n\t\t\t\t\t\t\t\t\t .click(WMEAutoUR_TabbedUI.hideWindow));\n\n\t\treturn mainTitle;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.TabsHead = function() {\n\n\t\t// ------- TABS ------- //\n\t\tvar mainTabs = $(\"<div>\")\n\t\t\t\t\t\t.attr(\"id\",\"WME_AutoUR_TAB_head\")\n\t\t\t\t\t\t.css(\"padding\",\"3px\")\n\t\t\t\t\t\t.css(\"margin-bottom\",\"3px\")\n\t\t\t\t\t\t.attr(\"title\",\"Click for Development Info\");\n\t\tvar tabs = $(\"<ul>\").addClass(\"nav\")\n\t\t\t\t\t\t\t.addClass(\"nav-tabs\");\n\n\t\t$(tabs).append($(\"<li>\").append($(\"<a>\").attr(\"data-toggle\",\"tab\")\n\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"href\",\"#WMEAutoUR_EDIT_TAB\")\n\t\t\t\t\t\t\t\t\t\t\t\t.html(\"Editor\")\n\t\t\t\t\t\t\t\t\t ).addClass(\"active\")\n\t\t\t\t\t );\n\n\t\t//$(tabs).append($(\"<li>\").append($(\"<a>\").attr(\"data-toggle\",\"tab\")\n\t\t//\t\t\t\t\t\t\t\t\t\t.attr(\"href\",\"#WMEAutoUR_MSG_TAB\")\n\t\t//\t\t\t\t\t\t\t\t\t\t.html(\"Messages\")\n\t\t//\t\t\t\t\t\t\t )\n\t\t//\t\t\t );\n\n\t\t$(tabs).append($(\"<li>\").append($(\"<a>\").attr(\"data-toggle\",\"tab\")\n\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"href\",\"#WMEAutoUR_SET_TAB\")\n\t\t\t\t\t\t\t\t\t\t\t\t.html(\"Settings\")\n\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t );\n\n\t\t$(mainTabs).append(tabs);\n\n\t\treturn mainTabs;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.TabsBody = function() {\n\n\t\t// ------- TABS ------- //\n\t\tvar TabsBodyContainer = $(\"<div>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WME_AutoUR_TAB_tabs\")\n\t\t\t\t\t\t\t .attr(\"style\",\"padding: 0 !important;\")\n\t\t\t\t\t\t\t .addClass(\"tab-content\");\n\n\t\treturn TabsBodyContainer;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\n\t/**\n\t *@since version 0.8.1\n\t */\n\tWMEAutoUR_TabbedUI.EditorTAB = function() {\n\n\t\tvar editTAB = $('<div>').attr(\"id\",'WMEAutoUR_EDIT_TAB')\n\t\t\t\t\t\t\t\t.addClass(\"tab-pane\")\n\t\t\t\t\t\t\t\t.addClass(\"active\");\n\n\t\t$(editTAB).append($(\"<span id='WME_AutoUR_Info'>\")\n\t\t\t\t\t\t\t//.css(\"float\",\"right\")\n\t\t\t\t\t\t\t.css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t.css(\"display\",\"block\")\n\t\t\t\t\t\t\t.css(\"max-width\",\"275px\")\n\t\t\t\t\t\t\t//.css(\"height\",\"150px\")\n\t\t\t\t\t\t\t.css(\"color\",\"#000000\")\n\t\t\t\t\t\t\t.css(\"clear\",\"both\"));\n\n\t\tvar autoBar = $('<div>').css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t.css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t.css(\"padding-top\",\"10px\");\n\t\t$(editTAB).append($(autoBar));\n\n\t\t$(autoBar).append($(\"<button>Prev</button>\")\n\t\t\t\t\t\t\t.click(WMEAutoUR.Auto.Prev)\n\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t.attr(\"title\",\"Previous UR\"));\n\n\t\t$(autoBar).append($(\"<button>Next</button>\")\n\t\t\t\t\t\t\t.click(WMEAutoUR.Auto.Next)\n\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t.css(\"float\",\"right\")\n\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t.attr(\"title\",\"Next UR\"));\n\n\t\t$(autoBar).append($(\"<span id='WME_AutoUR_Count'>\")\n\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t.css(\"display\",\"block\")\n\t\t\t\t\t\t\t.css(\"width\",\"60px\")\n\t\t\t\t\t\t\t.css(\"margin\",\"0 auto\")\n\t\t\t\t\t\t\t.css(\"padding\",\"3px\")\n\t\t\t\t\t\t\t.css(\"background-color\",\"#000000\")\n\t\t\t\t\t\t\t.css(\"border-radius\",\"3px\")\n\t\t\t\t\t\t\t.html(\"Auto Off\")\n\t\t\t\t\t\t\t.dblclick(WMEAutoUR.Auto.getIDs)\n\t\t\t\t\t\t\t.attr(\"title\",\"Double click to load/reload list of URs\"));\n\n\n\t\tvar actsBar = $('<div>').css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t.css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t.css(\"font-size\",\"12px\")\n\t\t\t\t\t\t\t\t.css(\"padding-top\",\"2px\");\n\t\t$(editTAB).append($(actsBar));\n\n\t\t$(actsBar).append($(\"<button>None</button>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WME_AutoUR_Filter_button\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Auto.filterButton)\n\t\t\t\t\t\t\t .val(2)\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"background-color\",\"White\")\n\t\t\t\t\t\t\t .css(\"color\",\"Black\")\n\t\t\t\t\t\t\t .css(\"border-radius\",\"5px\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Change filter between Initial-Stale-Dead.\"));\n\n\t\t$(actsBar).append($(\"<button>Send</button>\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.Send)\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Insert message. \"));\n\n\t\t$(actsBar).append($(\"<button>Solve</button>\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.changeStatus)\n\t\t\t\t\t\t\t .attr(\"data-state\",\"0\")\n\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Mark Solved.\"));\n\n\t\t$(actsBar).append($(\"<button>Not ID</button>\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.changeStatus)\n\t\t\t\t\t\t\t .attr(\"data-state\",\"1\")\n\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Mark Not Identified.\"));\n\n\n\t\tvar setsBar = $('<div>').css(\"width\",\"275px\")\n\t\t\t\t\t\t\t\t.css(\"margin-top\",\"2px\")\n\t\t\t\t\t\t\t\t.css(\"clear\",\"both\");\n\t\t$(editTAB).append($(setsBar));\n\n\t\tvar setsBarSub1 = $('<div>').css(\"width\",\"55px\")\n\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\");\n\t\t//$(setsBar).append($(setsBarSub1));\n\n\n\t\tvar setsBarSub2 = $('<div>').css(\"width\",\"55px\")\n\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\");\n\t\t$(setsBar).append($(setsBarSub2));\n\t\t$(setsBarSub2).append($(\"<label>\")\n\t\t\t\t\t\t\t .html(\"Adv.\")\n\t\t\t\t\t\t\t .attr(\"for\",\"WMEAutoUR_AutoAdvance_CB\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Enable auto advance with Send/Solve/NI buttons.\")\n\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\"));\n\n\t\t$(setsBarSub2).append($(\"<input>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WMEAutoUR_AutoAdvance_CB\")\n\t\t\t\t\t\t\t .attr(\"type\",\"checkbox\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"margin-left\",\"5px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Enable auto advance with Send/Solve/NI buttons.\"));\n\n\n\t\tvar setsBarSub3 = $('<div>').css(\"width\",\"55px\")\n\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\");\n\t\t$(setsBar).append($(setsBarSub3));\n\t\t$(setsBarSub3).append($(\"<label>\")\n\t\t\t\t\t\t\t .html(\"Send\")\n\t\t\t\t\t\t\t .attr(\"for\",\"WMEAutoUR_SendMessage_CB\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Send message with Solve/NI buttons.\")\n\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\"));\n\n\t\t$(setsBarSub3).append($(\"<input>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WMEAutoUR_SendMessage_CB\")\n\t\t\t\t\t\t\t .attr(\"type\",\"checkbox\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"margin-left\",\"5px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Send message with Solve/NI buttons.\"));\n\n\n\n\n\t\tvar edit_select = $(\"<select>\").attr(\"id\",\"WMEAutoUR_Insert_Select\")\n\t\t\t\t\t\t\t\t\t .attr(\"title\",\"Select message to be inserted\")\n\t\t\t\t\t\t\t\t\t .css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t .change(WMEAutoUR.Messages.insertFromSelect)\n\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\");\n\n\t\tWMEAutoUR_TabbedUI.createSelect(edit_select);\n\n\t\t$(editTAB).append(edit_select);\n\n\t\t$(editTAB).append($(\"<span id='WME_AutoUR_MSG_Display'>\")\n\t\t\t\t\t\t\t.css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t.css(\"display\",\"block\")\n\t\t\t\t\t\t\t.css(\"width\",\"275px\")\n\t\t\t\t\t\t\t.css(\"padding\",\"10px 0\")\n\t\t\t\t\t\t\t.css(\"color\",\"#000000\")\n\t\t\t\t\t\t\t.css(\"clear\",\"both\"));\n\n\n\t\t$(editTAB).append($(\"<div>\").css(\"clear\",\"both\"));\n\n\n\t\treturn editTAB;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.8.1\n\t */\n\t// ------- SETTINGS TAB ------- //\n\tWMEAutoUR_TabbedUI.SettingsTAB = function() {\n\n\t\tvar setTAB = $('<div>').attr(\"id\",'WMEAutoUR_SET_TAB')\n\t\t\t\t\t\t\t\t//.css(\"padding\",\"10px\")\n\t\t\t\t\t\t\t\t.css(\"max-width\",\"275px\")\n\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t.html(\"coming soon\")\n\t\t\t\t\t\t\t\t.addClass(\"tab-pane\");\n\n\t\tvar select = $(\"<select>\").attr(\"id\",\"WMEAutoUR_Settings_Select\")\n\t\t\t\t\t\t\t\t.attr(\"title\",\"Select Message\")\n\t\t\t\t\t\t\t\t.css(\"width\",\"225px\")\n\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t.change(WMEAutoUR.Messages.ChangeSettingSelect)\n\t\t\t\t\t\t\t\t.focus(WMEAutoUR.Messages.SaveSettingSelect)\n\t\t\t\t\t\t\t\t.css(\"padding-top\",\"5px\");\n\n\t\tWMEAutoUR_TabbedUI.createSelect(select);\n\n\n\t\t// --- MESSAGES --- //\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t.css(\"margin-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t\t.append($(\"<h3>\").html(\"Messages\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append($(\"<textarea>\").attr(\"id\",\"WMEAutoUR_Settings_Comment\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .val(WMEAutoUR.Options.messages[6])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"125px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"margin-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append(select)\n\t\t\t\t\t\t\t\t\t.append($(\"<button>\").html(\"Save\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",'50px')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",'left')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.SaveSettingSelect)\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<button>\").html(\"Custom Msg\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",'35%')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",'left')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.addCustom)\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<input>\").attr('type','text')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",'WMEAutoUR_Settings_customName')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",'65%')\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").css(\"clear\",\"both\"))\n\t\t\t\t\t\t);\n\n\t\t// --- FILTERS --- //\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t.css(\"margin-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t\t.append($(\"<h3>\").html(\"Filters\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").attr(\"id\",\"UR_Stale_Dead\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"135px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('Stale Days')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Days since first editor comment.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_Stale_Days\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.staleDays)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('Dead Days')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Days since second editor comment.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_Dead_Days\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.deadDays)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").css(\"clear\",\"both\"))\n\t\t\t\t\t\t );\n\n\t\t// --- Advanced --- //\n\t\t//console.info(WMEAutoUR.Options.settings.staleDays);\n\t\t//console.info(WMEAutoUR.Options.settings.deadDays);\n\t\t//console.info(WMEAutoUR.Options.settings.firstURTextareaTime);\n\t\t//console.info(WMEAutoUR.Options.settings.nextURTextareaTime);\n\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t.css(\"margin-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t\t.append($(\"<h3>\").html(\"Advanced\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").attr(\"id\",\"UR_TA_Timers\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"135px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('1st UR TA')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Offset before attempting to insert into UR comment textarea for first loaded UR.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_First_TA_Time\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.firstURTextareaTime)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('Next UR TA')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Offset before attempting to insert into UR comment textarea for consecutive URs.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_Next_TA_Time\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.nextURTextareaTime)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").css(\"clear\",\"both\"))\n\t\t\t\t\t\t );\n\n\n\n\t\t$(setTAB).append($(\"<button>Save</button>\")\n\t\t\t\t .click(WMEAutoUR.Settings.Save)\n\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t .attr(\"title\",\"Save Current Comment\"));\n\n\n\n\n\t\t$(setTAB).append($(\"<button>Reset</button>\")\n\t\t\t\t .click(WMEAutoUR.Settings.Reset)\n\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t .attr(\"title\",\"Reset settings to defaults.\"));\n\n\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\"));\n\n\n\t\treturn setTAB;\n\t};\n\n\t/**\n\t*@since version 0.6.1\n\t*/\n\tWMEAutoUR_TabbedUI.createSelect = function(select) {\n\n\t\tvar g1 = $(\"<optgroup>\").attr('label','Default');\n\t\tvar g2 = $(\"<optgroup>\").attr('label','Stale/Dead');\n\t\tvar g3 = $(\"<optgroup>\").attr('label','Custom');\n\n\t\t$.each(WMEAutoUR.Options.names,function(i,v) {\n\t\t\tif(v) {\n\t\t\t\tvar opt = $('<option>');\n\t\t\t\t$(opt).attr('value',i);\n\t\t\t\t$(opt).html(v);\n\t\t\t\tif(i<40) {\n\t\t\t\t\t$(g1).append(opt);\n\t\t\t\t} else if(i<60) {\n\t\t\t\t\t$(g2).append(opt);\n\t\t\t\t} else if(i>59) {\n\t\t\t\t\t$(g3).append(opt);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t$(select).append(g1).append(g2).append(g3);\n\t};\n\n\n\n\tWMEAutoUR_TabbedUI.init();\n}",
"function TabbedElement(containerDiv, managementData, styleClass) {\n var tabContainer = containerDiv.appendChild(document.createElement(\"div\"));\n \n containerDiv.className = styleClass || \"tabbedElement\";\n tabContainer.className = \"tab-container\";\n \n this._containerDiv = containerDiv;\n this._tabContainerDiv = tabContainer;\n this._tabs = new Array();\n this._managementData = managementData;\n this._flashingFunctions = new Object();\n this._selectedIndex = -1;\n}",
"function createTabCtrl(meta) {\n \n }",
"function CreateServiceRequestTabContainer(attributes) {\n var tabContent = document.createElement('div');\n tabContent.id = 'tabContent';\n\n for (var i in attributes) {\n if (!attributes[i]) {\n attributes[i] = \"\";\n }\n }\n\n var dtlTab = new dijit.layout.ContentPane({\n title: \"Details\",\n content: CreateServiceRequestDetails(attributes)\n }, dojo.byId('tabContent'));\n var cmntTab = new dijit.layout.ContentPane({\n title: \"Comments\",\n content: CreateCommetsContainer()\n }, dojo.byId('tabContent'));\n var attTab = new dijit.layout.ContentPane({\n title: \"Attachments\",\n content: CreateAttachmentContainer()\n }, dojo.byId('tabContent'));\n\n dojo.connect(cmntTab, \"onShow\", function () {\n CreateCommentsScrollBar();\n });\n\n dojo.connect(attTab, \"onShow\", function () {\n CreateScrollbar(dojo.byId(\"divAttachments\"), dojo.byId(\"divAttachmentsData\"));\n });\n\n var tabContainer = document.createElement('div');\n tabContainer.id = 'divTabContainer';\n var tabs = new dijit.layout.TabContainer({\n style: \"width: 300px; height: 162px; vertical-align:middle;\",\n tabPosition: \"bottom\"\n }, dojo.byId('divTabContainer'));\n tabs.addChild(dtlTab);\n tabs.addChild(cmntTab);\n tabs.addChild(attTab);\n\n tabs.startup();\n\n return tabs;\n}",
"function addTabs(tabs, scope) \n{\n var list = $('<ul class=\"nav nav-tabs\" role=\"tablist\"></ul>');\n var div = $('<div class=\"tab-content\"></div>');\n var active = 'active';\n $.each( tabs, function( i, name ) {\n list.append('<li class=\"nav-item\"><a class=\"nav-link '+active+'\" href=\"#'+scope+'tab-'+i+'\" role=\"tab\" data-toggle=\"tab\">'+name+'</a></li>');\n div.append('<div role=\"tabpanel\" class=\"tab-pane '+active+'\" id=\"'+scope+'tab-'+i+'\"></div>');\n active = '';\n });\n $('#demo').append(list);\n $('#demo').append(div);\n}",
"function createHeader(){\n const header = document.createElement('header')\n const h1 = document.createElement('h1')\n h1.textContent = 'Mazzeratie Monica'\n header.appendChild(h1)\n header.appendChild(createNav())\n\n return header\n}",
"function tab() {\n return {\n restrict: 'E',\n transclude: true,\n template: '<div role=\"tabpanel\" ng-show=\"active\" ng-transclude></div>',\n // The '^' character instructs the directive to move up the scope hierarchy one level and look for the controller on \"tabset\".\n // If the controller can't be found, angular will throw an error.\n require: '^tabset',\n // By specifying a property on the scope object of the DDO, the scope object passed to our link function will now have\n // a \"heading\" property automatically attached to it whose value is equal to the string defined in index.html.\n // \"@\" means this scope property should be a string\n scope: {\n heading: '@'\n },\n // \"tabsetCtrl\" is the \"tabset\" controller, which we can now manipulate.\n link: function(scope, elem, attr, tabsetCtrl) {\n // The active property will determine whether or not an individual tab is shown so all tabs should begin life as inactive.\n scope.active = false;\n\n scope.disabled = false;\n if (attr.disable) {\n attr.$observe('disable', function(value) {\n scope.disabled = (value !== 'false');\n })\n }\n\n // Any property bound to scope in the \"tab\" directive will also be accessible by the \"tabset\" controller.\n tabsetCtrl.addTab(scope);\n }\n }\n }",
"function wrapTabs(container) {\n\t\t$(container).addClass('tabs-container');\n\t\t$(container).wrapInner('<div class=\"tabs-panels\"/>');\n\t\t$('<div class=\"tabs-header\">' + '<div class=\"tabs-scroller-left\"><div class=\"faceIcon icon-arrow2_left left-arrow\"></div></div>' + '<div class=\"tabs-scroller-right\"><div class=\"faceIcon icon-arrow2_right right-arrow\"></div></div>' + '<div class=\"tabs-wrap\">' + '<ul class=\"tabs\"></ul>' + '</div>' + '</div>').prependTo(container);\n\n\t\tvar header = $('>div.tabs-header', container);\n\n\t\t$('>div.tabs-panels>div', container).each(function () {\n\t\t\tif (!$(this).attr('id')) {\n\t\t\t\t$(this).attr('id', 'gen-tabs-panel' + $.fn.tauitabs.defaults.idSeed++);\n\t\t\t}\n\n\t\t\tvar options = {\n\t\t\t\tid: $(this).attr('id'),\n\t\t\t\ttitle: $(this).attr('title'),\n\t\t\t\tcontent: null,\n\t\t\t\thref: $(this).attr('href'),\n\t\t\t\tclosable: $(this).attr('closable') == 'true',\n\t\t\t\ticon: $(this).attr('icon'),\n\t\t\t\tselected: $(this).attr('selected') !== undefined,\n\t\t\t\tcache: $(this).attr('cache') == 'false' ? false : true,\n\t\t\t\tenable: $(this).attr('enable') == 'false' ? false : true\n\t\t\t};\n\t\t\t$(this).attr('title', '');\n\t\t\tcreateTab(container, options);\n\t\t});\n\n\t\t$('.tabs-scroller-left, .tabs-scroller-right', header).hover(function () {\n\t\t\t$(this).addClass('tabs-scroller-over');\n\t\t}, function () {\n\t\t\t$(this).removeClass('tabs-scroller-over');\n\t\t}).mousedown(function () {\n\t\t\t$(this).addClass('tabs-scroller-mousedown');\n\t\t}).mouseup(function () {\n\t\t\t$(this).removeClass('tabs-scroller-mousedown');\n\t\t});\n\t}",
"function createTab(battingTeam, bowlingTeam) {\n // Batting info table\n let tabContent = `\n <table class=\"table\" border=\"1\">\n <tr class=\"table-secondary\">\n <th>Batter</th>\n <th>R</th>\n <th>B</th>\n <th>4/6</th>\n </tr>`;\n battingTeam.players.forEach((player) => {\n tabContent += `\n <tr id=\"${player.name}-bat\">\n <td>${player.name}</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n </tr>`;\n });\n\n // Bowling info table\n tabContent += `</table>\n <br>\n <table class=\"table\" border=\"1\">\n <tr class=\"table-secondary\">\n <th>Bowler</th>\n <th>O</th>\n <th>R</th>\n <th>W</th>\n </tr>`;\n bowlingTeam.players.forEach((player) => {\n tabContent += `\n <tr id=\"${player.name}-bowl\">\n <td>${player.name}</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n </tr>`;\n });\n\n // Scorecard summary\n tabContent += `</table>\n <p class=\"alert alert-warning p-1 text-center fw-bolder\">Total: \n <span id=\"${battingTeam.id}-total\" class=\"text-primary\">0</span>\n / <span id=\"${battingTeam.id}-wickets\" class=\"text-danger\">0</span>\n Overs: <span id=\"${battingTeam.id}-overs\" class=\"text-success\">0.0</span> (${match.totalOvers})\n </p>`;\n\n return tabContent;\n}",
"setDomElements() {\n this.dom.header = this.dom.el.querySelector('.mf-tabs__header');\n this.dom.tabs = this.dom.el.querySelectorAll('.mf-tabs__tab');\n this.dom.content = this.dom.el.querySelector('.mf-tabs__content');\n this.dom.panels = this.dom.el.querySelectorAll('.mf-tabs__panel');\n }",
"function wrapTabs(container) { \n\t\t$(container).addClass('tabs-container'); \n\t\t$(container).wrapInner('<div class=\"tabs-panels\"/>'); \n\t\t$('<div class=\"tabs-header\">' \n\t\t\t\t+ '<div class=\"tabs-scroller-left\"></div>' \n\t\t\t\t+ '<div class=\"tabs-scroller-right\"></div>' \n\t\t\t\t+ '<div class=\"tabs-wrap\">' \n\t\t\t\t+ '<ul class=\"tabs\"></ul>' \n\t\t\t\t+ '</div>' \n\t\t\t\t+ '</div>').prependTo(container); \n\t\t \n\t\tvar header = $('>div.tabs-header', container); \n\t\t \n\t\t$('>div.tabs-panels>div', container).each(function(){ \n\t\t\tif (!$(this).attr('id')) { \n\t\t\t\t$(this).attr('id', 'gen-tabs-panel' + $.fn.tabs.defaults.idSeed++); \n\t\t\t} \n\t\t\t \n\t\t\tvar options = { \n\t\t\t\tid: $(this).attr('id'), \n\t\t\t\ttitle: $(this).attr('title'), \n\t\t\t\tcontent: null, \n\t\t\t\thref: $(this).attr('href'), \n\t\t\t\tclosable: $(this).attr('closable') == 'true', \n\t\t\t\ticon: $(this).attr('icon'), \n\t\t\t\tselected: $(this).attr('selected') == 'true', \n\t\t\t\tcache: $(this).attr('cache') == 'false' ? false : true \n\t\t\t}; \n\t\t\t$(this).attr('title',''); \n\t\t\tcreateTab(container, options); \n\t\t}); \n\t\t \n\t\t$('.tabs-scroller-left, .tabs-scroller-right', header).hover( \n\t\t\tfunction(){$(this).addClass('tabs-scroller-over');}, \n\t\t\tfunction(){$(this).removeClass('tabs-scroller-over');} \n\t\t); \n\t\t$(container).bind('_resize', function(){ \n\t\t\tvar opts = $.data(container, 'tabs').options; \n\t\t\tif (opts.fit == true){ \n\t\t\t\tsetSize(container); \n\t\t\t\tfitContent(container); \n\t\t\t} \n\t\t\treturn false; \n\t\t}); \n\t}",
"function generatePropertyTabs (num_of_units, unit_type, unit_label, unit_data)\n {\n var tabs_layout = '';\n // build the tabs \n tabs_layout += '<ul class=\"nav nav-tabs\" role=\"tablist\">\\n\\n';\n for (var i = 1; i <= num_of_units; i++) {\n if (i === 1) {\n tabs_layout += '<li role=\"presentation\" class=\"active\"><a href=\"#'+unit_type+i+'\" aria-controls=\"'+unit_type+i+'\" role=\"tab\" data-toggle=\"tab\">'+unit_label+i+'</a></li>\\n';\n }\n else\n {\n tabs_layout += '<li role=\"presentation\"><a href=\"#'+unit_type+i+'\" aria-controls=\"'+unit_type+i+'\" role=\"tab\" data-toggle=\"tab\">'+unit_label+i+'</a></li>\\n';\n }\n // end of if \n }// end of for loop\n tabs_layout += '</ul>';\n \n // build the pans \n tabs_layout += '<div class=\"tab-content\">';\n for (var i = 1; i <= num_of_units; i++) {\n if (i === 1) {\n tabs_layout += '<div role=\"tabpanel\" class=\"tab-pane active\" id=\"'+unit_type+i+'\">'+unit_data+' </div>';\n }\n else\n {\n tabs_layout += '<div role=\"tabpanel\" class=\"tab-pane\" id=\"'+unit_type+i+'\">'+unit_data+' </div>';\n } // end of if \n }// end of for loop\n \n tabs_layout += '</div>';\n \n return tabs_layout;\n }",
"function htmlStartBlock()\n{\n //print(\"\\t<hr />\\n\");\n print(\"\\t<table width=\\\"100%\\\" class=\\\"wiki_body_container\\\">\\n\");\n print(\"\\t\\t<tr>\\n\");\n print(\"\\t\\t\\t<td>\\n\");\n print(\"\\n<!-- PAGE BODY -->\\n\");\n}",
"buildTabToolbar(tab) {\r\n\r\n // test for 'entry, 'exit' or 'danbredtagging'\r\n if ( tab.name == 'entry' || tab.name == 'exit' || tab.name == 'danbredtagging' || tab.name == 'remark' || tab.name == 'keyfigures' ) {\r\n\r\n // skip creating toolbar components for these tabs\r\n return;\r\n }\r\n\r\n var buttons = [];\r\n\r\n // labels\r\n var vLittersT = session.get( 'sp_lang', 'SP_SowcardViewLitters') || Language.sowcard.viewLitters[this.lang];\r\n var addRowT = session.get( 'sp_lang', 'SP_ButtonAddRow') || Language.button.addRow[this.lang];\r\n\r\n // thead\r\n if ( tab.name == 'thead' ) {\r\n\r\n // create toolbar view\r\n buttons.push({\r\n class: 'btn-default',\r\n title: vLittersT,\r\n icon: 'glyphicon-th-list',\r\n visible: true,\r\n event: 'view-litters'\r\n });\r\n } else {\r\n\r\n // create toolbar view\r\n buttons.push({\r\n class: 'btn-primary',\r\n title: addRowT,\r\n icon: 'glyphicon-plus',\r\n visible: true,\r\n event: 'add-row'\r\n });\r\n }\r\n\r\n // define toolbar collection\r\n // var toolbarCollection = new ButtonsCollection({ model: ButtonModel });\r\n var toolbarCollection = new ButtonsCollection( buttons );\r\n\r\n // create toolbar view\r\n var toolbarView = new Toolbar({ collection: toolbarCollection });\r\n\r\n // listen for custom events\r\n toolbarView.on( 'add-row', this.onAddRow.bind(this) );\r\n toolbarView.on( 'view-litters', this.switchLittersView.bind(this) );\r\n\r\n // return toolbar view\r\n return toolbarView;\r\n }",
"function addObjectTab(wnd, node, data, tab)\n{\n if (!node.parentNode)\n return;\n\n // Click event handler\n tab.setAttribute(\"href\", data.location);\n tab.setAttribute(\"class\", policy.objtabClass);\n tab.addEventListener(\"click\", generateClickHandler(wnd, data), false);\n\n // Insert tab into the document\n if (node.nextSibling)\n node.parentNode.insertBefore(tab, node.nextSibling);\n else\n node.parentNode.appendChild(tab);\n}",
"_initElements () {\n this.tablist = this.element.querySelector(this.tablistSelector)\n this.tabs = Array.from(this.element.querySelectorAll(this.tabSelector))\n this.panels = Array.from(this.element.querySelectorAll(this.panelSelector))\n\n // The data-rvt-tablist attribute was added in Rivet 2.4.0. To maintain\n // backward compatibility, the code below infers which element is the\n // tablist if the data-rvt-tablist attribute is not present.\n\n if (!this.tablist) {\n this.tablist = this.tabs[0].parentElement\n }\n }",
"function WebConsole(aTab)\n{\n this.tab = aTab;\n this.chromeDocument = this.tab.ownerDocument;\n this.chromeWindow = this.chromeDocument.defaultView;\n this.hudId = \"hud_\" + this.tab.linkedPanel;\n this._onIframeLoad = this._onIframeLoad.bind(this);\n this._initUI();\n}",
"function TabDefWrapper(aTabmail, aTabTypeDef) {\n this.name = aTabTypeDef.name;\n\n // We define the bare minimum required for the modes. We need the mode to\n // exist since that is the actual 'atom' of tab definition, but we don't\n // want to put anything else in it, like methods, because tabmail always\n // forces \"this\" to be the tab type rather than the mode.\n this.modes = {};\n this.modes[aTabTypeDef.name] = {\n type: aTabTypeDef.name\n };\n\n this._tabmail = aTabmail;\n this._tabDef = aTabTypeDef;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize the val hash to query parameters and return it. Use the namePrefix to prefix all param names (for recursion) | function toQueryString(val, namePrefix) {
/*jshint eqnull:true */
var splitChar = Backbone.Router.arrayValueSplit;
function encodeSplit(val) { return String(val).replace(splitChar, encodeURIComponent(splitChar)); }
if (!val) {
return '';
}
namePrefix = namePrefix || '';
var rtn = [];
_.each(val, function(_val, name) {
name = namePrefix + name;
if (_.isString(_val) || _.isNumber(_val) || _.isBoolean(_val) || _.isDate(_val)) {
// primitive type
if (_val != null) {
rtn.push(name + '=' + encodeSplit(encodeURIComponent(_val)));
}
} else if (_.isArray(_val)) {
// arrays use Backbone.Router.arrayValueSplit separator
var str = '';
for (var i = 0; i < _val.length; i++) {
var param = _val[i];
if (param != null) {
str += splitChar + encodeSplit(param);
}
}
if (str) {
rtn.push(name + '=' + str);
}
} else {
// dig into hash
var result = toQueryString(_val, name + '.');
if (result) {
rtn.push(result);
}
}
});
return rtn.join('&');
} | [
"function uriSerialize(obj, prefix) {\n\t\tvar str = [];\n\t\tfor(var p in obj) {\n\t\t\tvar k = prefix ? prefix + \"[\" + p + \"]\" : p, v = obj[p];\n\t\t\tstr.push(typeof v == \"object\" ?\n\t\t\t\turiSerialize(v, k) :\n\t \t\tencodeURIComponent(k) + \"=\" + encodeURIComponent(v));\n\t\t}\n\t\treturn str.join(\"&\");\n\t}",
"function createEncodedParam (key,value) {\n return {\n key: percentEncode(key),\n value: percentEncode(value)\n }\n}",
"encodeParams(params) {\n return Object.entries(params).map(([k, v]) => `${k}=${encodeURI(v)}`).join('&')\n }",
"function formatQueryParamsHiking(params) {\n const queryItems = Object.keys(params)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)\n return queryItems.join('&');\n}",
"get params() {\n return this._parsed.params || {};\n }",
"function getParametersFromFilters () {\n var parameters = {};\n parameters.disp = 'T';\n\n for (var i = 0; i < filterIds.length; i++) {\n var value = getFilterValue(filterIds[i].id);\n if (value) {\n var obj = getFilterObject(filterIds[i].paramname, value);\n parameters[obj.name] = obj.value;\n }\n }\n\n return parameters;\n }",
"function serializeSpecific(selector) {\r\n\t var obj = \"\";\r\n\t $(form).find(selector).each(function () { \r\n\t obj += \"&\";\r\n\t obj += $(this).attr(\"name\");\r\n\t obj += \"=\";\r\n\t obj += $(this).val(); \r\n\t });\r\n\t return obj;\r\n\t}",
"function searchCheckboxesToParams(checkboxes) {\n var params = \"\";\n Object.keys(checkboxes).forEach(key => {//I iterate over each field of the object\n if (key !== \"years\") {//if it's not an year\n if (checkboxes[key]) {//if it's a true flag\n console.log(key)\n params += \"&\" + key + \"=\" + checkboxes[key];\n }\n }\n else {//if it's a year\n if (checkboxes.years.length !== 0) {//if there are some years selected\n params += \"&\" + queryString.stringify({\"years\": checkboxes.years}, {arrayFormat: 'comma'});\n }\n }\n });\n return params;\n}",
"function transformQuery(query) {\n const params = new URLSearchParams();\n for (const [name, value] of Object.entries(query)){\n if (Array.isArray(value)) {\n for (const val of value){\n params.append(name, val);\n }\n } else if (typeof value !== 'undefined') {\n params.append(name, value);\n }\n }\n return params;\n}",
"function generateKlimaParam(parent, param, bval) {\n var name = param.name.split(\"_\");\n if (name[1] == \"inter\") {\n if (name[2].substr(0,2) == \"tm\") return new ParameterKliInterpolacijatmokri(parent, param.name, param.id, param.mval, bval);\n else return new ParameterKliInterpolacija(parent, param.name, param.id, param.mval, bval); \n }\n else {\n if (name[1] == \"pritisk\") return new ParameterKliPritisk(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"maksimalna\") return new ParameterKliMaksimalnaTemperatura(parent, param.name, param.id, param.mval, bval); \n else if (name[1] == \"minimalna\") {\n if (name.length == 3) return new ParameterKliMinimalnaTemperatura(parent, param.name, param.id, param.mval, bval);\n else return new ParameterKliMinimalnaTemperatura5cm(parent, param.name, param.id, param.mval, bval);\n }\n else if (name[2] == \"suhi\") return new ParameterKliTemperaturaSuhi(parent, param.name, param.id, param.mval, bval);\n else if (name[2] == \"mokri\") return new ParameterKliTemperaturaMokri(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"led\") return new ParameterKliLed(parent, param.name, param.id, param.mval, bval);\n else if (name[2] == \"vlaga\") return new ParameterKliRelVlaga(parent, param.name, param.id, param.mval, bval); \n else if (name[1] == \"smer\") return new ParameterKliSmerVetra(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"jakost\") return new ParameterKliJakostVetra(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"hitrost\") return new ParameterKliHitrostVetra(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"stanje\") return new ParameterKliStanjeTal(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"vidnost\") return new ParameterKliVidnost(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"trajanje\") return new ParameterKliTrajanjeSonca(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"oblacnost\") return new ParameterKliOblacnost(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"padavine\") return new ParameterKliPadavine(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"oblika\") return new ParameterKliOblikaPadavin(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"voda\") return new ParameterKliVodaVSnegu(parent, param.name, param.id, param.mval, bval);\n else if (name[1] == \"sneg\") {\n if (name[2] == \"skupaj\") return new ParameterKliSnegSkupaj(parent, param.name, param.id, param.mval, bval);\n else return new ParameterKliSnegNovi(parent, param.name, param.id, param.mval, bval);\n } \n }\n}",
"function updateParams() {\n var hashParams = new Array();\n var curLatLon = map.getCenter();\n hashParams.push('q=' + jQuery('#controls .searchQuery').val());\n hashParams.push('date=' + jQuery('#controls .searchDate').val());\n hashParams.push('lat=' + curLatLon.lat());\n hashParams.push('lon=' + curLatLon.lng());\n hashParams.push('zoom=' + map.getZoom());\n hashParams.push('radius=' + getCurrentRadius());\n\n location.hash = hashParams.join('&');\n jQuery('#controls .jumpToLocation').val('');\n }",
"initializeFilterValuesFromQueryString() {\n this.clearAllFilters()\n\n if (this.encodedFilters) {\n this.currentFilters = Object.keys(this.encodedFilters).map(\n key => ({ name: key, value: this.encodedFilters[key] })\n )\n\n this.syncFilterValues()\n }\n }",
"function getSearchParams() {\n return { searchScript: optScript, searchTones: optTones };\n }",
"static toParamsMap(params) {\n const ret = {};\n params.forEach((param) => {\n ret[param.key] = param;\n });\n return ret;\n }",
"function ampGetQueryParams(qs) {\n qs = qs.split(\"+\").join(\" \");\n\n var params = {}, tokens,\n re = /\\butm_([^=]+)=([^&]+)/g;\n\n while (tokens = re.exec(qs)) {\n params[decodeURIComponent(tokens[1])]\n = decodeURIComponent(tokens[2]);\n }\n\n return params;\n }",
"function genQueryString (options) {\n\n if ( !options.queryParams ) {\n return \"\";\n }\n\n log(options.verbose,\"Now generating query string value ...\");\n\n var queryStringParams = [];\n\n Object.keys(options.queryParams).forEach(function (key) {\n queryStringParams.push(createEncodedParam(key,options.queryParams[key]));\n });\n\n var queryString = \"?\";\n\n log(options.verbose,\"Query string key/value pairs are:\");\n\n for ( var i=0; i<queryStringParams.length; i++ ) {\n log(options.verbose,\" \"+queryStringParams[i].key+\"=\"+queryStringParams[i].value);\n queryString += queryStringParams[i].key+\"=\"+queryStringParams[i].value;\n if ( queryStringParams[i+1] ) {\n queryString += \"&\";\n }\n }\n\n log(options.verbose,\"Query string value is: \"+queryString);\n\n return queryString;\n}",
"function urlEncodePair(key, value, str) {\n if (value instanceof Array) {\n value.forEach(function (item) {\n str.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(item));\n });\n }\n else {\n str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }",
"encodedFilters() {\n const encoded = pick(\n this.$route.query,\n this.filters.map(f => f.name)\n )\n return Object.keys(encoded).length ? encoded : null\n }",
"function cfnRouteQueryParameterPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnRoute_QueryParameterPropertyValidator(properties).assertSuccess();\n return {\n Match: cfnRouteHttpQueryParameterMatchPropertyToCloudFormation(properties.match),\n Name: cdk.stringToCloudFormation(properties.name),\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the sum of the array of string integers numList. | function sumStringInts(numList) {
return numList.reduce(function(m, n) { return parseInt(m) + parseInt(n); });
} | [
"function sumOfSums(inputArray) {\n let listOfNums = inputArray;\n let outputArray = [];\n let arrayOfNums = String(listOfNums).split(',');\n \n // iterate through arrayOfNums and accumulatively add the current number to the previous number\n for (let index = 1; index <= arrayOfNums.length; index += 1) {\n outputArray.push(arrayOfNums.slice(0, index));\n }\n \n // iterate through each inner array, converting elements to numbers and adding them, return the sums\n outputArray = outputArray.map(num => num.reduce((accumulator, currentNum) => accumulator + Number(currentNum), 0));\n \n // add and return all of numbers of the array\n return outputArray.reduce((accumulator, currentNum) => currentNum + accumulator, 0);\n\n}",
"function sumOfNumbers(arr) {\n function sum(total, num) {\n return total + num;\n }\n return arr.reduce(sum);\n}",
"function sumArray(input) {\r\n\tvar operands = [];\r\n\tvar result = [];\r\n\tvar sum = 0;\r\n\r\n\tfor (var i = 1; i < input.length; i++) {\r\n\t\toperands = (input[i].split(' '));\r\n\t\tsum = parseInt(operands[0]) + parseInt(operands[1]);\r\n\t\tresult.push(sum);\r\n\t}\r\n\r\n\treturn result;\r\n}",
"function NumberAddition(str) { \n//search for all the digits in str (returns an array)\nvar nums = str.match(/(\\d)+/g); \n\nif (!nums) {return 0;} //stop if there are no numbers\nelse {\n //convert array elements to numbers using .map()\n //then add all elements together using .reduce()\n return nums.map(function(element, index, array){\n return +element;\n }).reduce(function(previous, current, index, array){\n return previous + current;\n });\n}\n}",
"function sumOfSums(numberArray) {\n return numberArray.map(function (number, idx) {\n return numberArray.slice(0, idx + 1).reduce(function (sum, digit) {\n return sum + digit;\n });\n }).reduce(function (sum, partialSum) {\n return sum + partialSum;\n });\n}",
"function add(array) {\n var sum = 0;\n for (var i = 0; i < array.length; i++) {\n sum += array[i];\n }\n return sum;\n}",
"function grabNumberSum(s) {\n\treturn s.replace(/\\D/g, \" \").split(\" \").reduce((x, i) => x + +i, 0);\n}",
"function sum(xs) /* (xs : list<int>) -> int */ {\n return foldl(xs, 0, function(x /* int */ , y /* int */ ) {\n return $std_core._int_add(x,y);\n });\n}",
"function plusOneSum(arr) { \n var sum = arr.length;\n for (var index = 0; index < arr.length; index++) {\n sum += arr[index];\n } \n return sum;\n }",
"function getDigitsSum(inputNumber) {\n inputNumber += '';\n let sumOfDigits = 0;\n const inputNumberLength = inputNumber.length;\n \n for (let index = 0; index < inputNumberLength; index += 1) {\n sumOfDigits += parseInt(inputNumber[index]);\n }\n \n return sumOfDigits;\n}",
"function addArrays(array1, array2) {\n let arrayToNumber1 = parseInt(array1.join(''));\n let arrayToNumber2 = parseInt(array2.join(''));\n if (array1 === 'undefined' && array2 === 'undefined') return [];\n if (isNaN(arrayToNumber1)) arrayToNumber1 = 0;\n if (isNaN(arrayToNumber2)) arrayToNumber2 = 0;\n\n let finalSum = arrayToNumber1 + arrayToNumber2;\n \n finalSum = finalSum.toString().split('').map(el => parseInt(el));\n\n if(isNaN(finalSum[0])) {\n finalSum[1] = ~finalSum[1] + 1;\n finalSum.shift();\n }\n\n return finalSum[0] !== 0 ? finalSum : []\n}",
"function sumDigits(a, b) {\n\tconst x = [];\n\tfor (let i = a; i <= b; i++) {\n\t\tx.push(i);\n\t}\n\treturn x.map(x => x.toString().split(\"\")).flat().reduce((x, y) => Number(x) + Number(y));\n}",
"function arraySum(array){\n var sum=0;\n var index=0;\n function add(){\n if(index===array.length-1)\n return sum;\n\n sum=sum+array[index];\n index++;\n return add();\n }\n return add();\n}",
"function runningSum(nums) {\n const result = []\n \n nums.reduce((acc, curr) => {\n result.push(acc + curr)\n return acc + curr\n }, 0)\n \n return result;\n}",
"function findNumbers(num1, num2) {\n let array = [];\n\n for (x = num1; x <= num2; x++) {\n let elements = x.toString().split(\"\");\n let sum = 0;\n elements.forEach(function (element) {\n sum += element * element * element;\n });\n if (sum === x) array.push(x);\n }\n return array;\n}",
"function sumAges(arr) {\n}",
"function multiDimSum(arr) {}",
"function arraySum(arr){\n\n // code goes here\n // similar to flatten, handle all levels of depth\n // use reduce to flatten the array and add integers to the startValue \n // if the curr value is an array, use recursion to run the function on the array again\n // if the value is a number, then add that to the total sum, else add 0\n // 0 is for any other value that is not a number\n return arr.reduce(function(sum, isNested){\n \n sum += (Array.isArray(isNested)) ? arraySum(isNested) : (typeof isNested === \"number\") ? isNested : 0;\n return sum;\n \n },0);\n\n}",
"function charSum (str) {\n\t// First convert string to an array of digits via regEx.\n\t// Reduce the array of numbers(as strings), converting each string to a number first.\n\t// Provide reduce with a initial value of zero for edge case when there is only one digit match.\n\treturn str.match(/\\d/gi).reduce((a,b) => Number(a) + Number(b), 0)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
39.Write a function called pickBy which accepts an object and a callback function. The function should return a new object consisting of keys and values where the value returns something truthy when passed into the callback. | function pickBy(obj, cb){
let result = {};
for (let key in obj){
if(cb(obj[key])) result[key]=obj[key];
}
return result;
} | [
"function objFilter(obj, callback) {\n const newObj = {};\n for (const key in obj) {\n if (callback(key) === obj[key]) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}",
"function keyBy(arr, fn){\n var result = {};\n arr.forEach(function(v){\n result[fn(v)] = v;\n });\n return result;\n }",
"function pick(source, keys) {\n var finalOutput = {};\n for (var i = 0; i < keys.length; i++) {\n if (source[keys[i]] !== undefined) {\n finalOutput[keys[i]] = source[keys[i]];\n }\n }\n return finalOutput;\n}",
"function omitBy(obj, cb){\n let result = {};\n for (let key in obj){\n if (!cb(obj[key])) result[key] = obj[key];\n }\n return result;\n}",
"function filter_from_object(obj, bool_array){\r\n var obj_keys = Object.keys(obj);\r\n var out_obj = {}\r\n\r\n obj_keys = obj_keys.filter(function(elem, idx){\r\n\r\n return bool_array[idx]\r\n })\r\n obj_keys.forEach(function(elem){\r\n out_obj[elem] = obj[elem];\r\n })\r\n //console.log(out_obj)\r\n return out_obj\r\n}",
"function filter(object, property, callback) {\n\tif (Array.isArray(object)) {\n\t\treturn object.map((item) => filter(item, property, callback));\n\t} else if (isObject(object)) {\n\t\treturn Object.entries(object).reduce((acc, [key, value]) => {\n\t\t\treturn {\n\t\t\t\t...acc,\n\t\t\t\t[key]:\n\t\t\t\t\tkey === property\n\t\t\t\t\t\t? callback(value)\n\t\t\t\t\t\t: filter(value, property, callback),\n\t\t\t};\n\t\t}, {});\n\t} else {\n\t\treturn object;\n\t}\n}",
"function subKeepAssigned(objs, k, pusher) {\n var ka = keepAssigned();\n objs\n .map(propGetter(k))\n .filter(Boolean)\n .forEach(o => _keepAssigned(ka, o, pusher));\n return ka;\n}",
"function pluck(name){\n return function(object){\n return object[name];\n }\n}",
"eachCompare(context, checkFunc, expected, isFilterMask = false) {\n const result = {};\n for (const key in context) {\n if (helpers_1.isNullOrUndefined(expected)) {\n result[key] = checkFunc(context[key]);\n }\n else {\n const expectedValue = expected[key];\n if (isFilterMask) {\n if (this._includedInFilter(expectedValue)) {\n result[key] = checkFunc(context[key], expectedValue);\n }\n }\n else {\n if (typeof expectedValue !== 'undefined') {\n result[key] = checkFunc(context[key], expectedValue);\n }\n }\n }\n }\n return result;\n }",
"function parts(json, predicate = tarski.memoize(true)){\n return keys(json).filter(predicate)\n .map(x => { return {key: x, value: json[x]} }); \n}",
"function filterFunction(obj, key, value){\n\tif(obj[key] === value) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function filterBy(field, value) {\n return function(d) {\n return d[field] === value;\n };\n }",
"findKeyIdea (object, testFunction) {\n let returnValue = ''\n for (const key in object) {\n if (testFunction(object[key])) {\n returnValue = key\n } else {\n returnValue = undefined\n }\n }\n return returnValue\n }",
"function lookup(xs, pred) /* forall<a,b> (xs : list<(a, b)>, pred : (a) -> bool) -> maybe<b> */ {\n return foreach_while(xs, function(kv /* (21629, 21630) */ ) {\n var _x31 = pred(fst(kv));\n if (_x31) {\n return Just(snd(kv));\n }\n else {\n return Nothing;\n }\n });\n}",
"eachWait(context, waitFunc, expected, isFilterMask = false) {\n for (const key in context) {\n if (helpers_1.isNullOrUndefined(expected)) {\n waitFunc(context[key]);\n }\n else {\n if (isFilterMask) {\n if (this._includedInFilter(expected[key])) {\n waitFunc(context[key]);\n }\n }\n else if (typeof expected[key] !== 'undefined') {\n waitFunc(context[key], expected[key]);\n }\n }\n }\n return this;\n }",
"function myFilter(array, callback) {\n return callback(array);\n}",
"function filter(obj, prop, val) {\n\tvar arr = []\n\tfor (var k in obj) {\n\t\tvar v = obj[k]\n\t\tif (v[prop] === val)\n\t\t\tarr.push(v)\n\t}\n\treturn arr\n}",
"function bucketFindPredicate(tick, value) {\n return function(item) {\n return item.tick === tick && item.value === value;\n }\n}",
"function findFirstProp(objs, p) {\n for (let obj of objs) {\n if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the text direction of the document ('ltr', 'rtl', or 'auto'). | function setTextDirection(direction) {
document.body.setAttribute('dir', direction);
} | [
"get textDirection() {\n return this.viewState.defaultTextDirection\n }",
"_isRtl() {\n return this._dir && this._dir.value === 'rtl';\n }",
"function setDirection(){\n // set arrow\n let direction = document.getElementById('windDegrees');\n\n // may not have degree data, so reset every time and check for existence\n direction.innerText = \"\";\n\n if (data.wind.deg) {\n direction.innerText = \"↑\";\n\n // rotate\n let degreeContainer = document.getElementById(\"degreeContainer\");\n degreeContainer.style.transform=`rotate(${data.wind.deg}deg)`;\n degreeContainer.style.transition=\"1s ease-in-out\";\n }\n}",
"textDirectionAt(pos) {\n let perLine = this.state.facet(perLineTextDirection)\n if (!perLine || pos < this.viewport.from || pos > this.viewport.to)\n return this.textDirection\n this.readMeasured()\n return this.docView.textDirectionAt(pos)\n }",
"setDirection (dir, lengths) {\n this[dir.prop] = {\n ...lengths[0] && { before: lengths[0] },\n ...lengths[1] && { size: lengths[1] },\n ...lengths[2] && { after: lengths[2] }\n }\n }",
"function changeAlign(align) {\n gMeme.currText.align = align;\n gMeme.currText.x = gFontlocation[align].x\n}",
"setSurroundModeToLeft() {\n this._setSurroundMode(\"s_left\");\n }",
"function keyTyped() {\n textRotation = !textRotation;\n}",
"function setMode(newMode) {\r\n bTextMode = newMode;\r\n var cont;\r\n if (bTextMode) {\r\n// show html\r\n cleanHtml();\r\n cleanHtml();\r\n cont= Composition.document.body.innerHTML;\r\n Composition.document.body.innerText=cont;\r\n } else {\r\n cont=Composition.document.body.innerText;\r\n Composition.document.body.innerHTML=cont;\r\n }\r\n Composition.focus();\r\n}",
"setTextAlignment(value) {\n this.ctx.textAlign = value;\n }",
"function setsourceDirectionFn(scope) {\n\tselected_source_index = scope.source_Mdl;\n}",
"function setMarkers (plainText) {\r\n var matchedRtlChars = plainText.match(rtlChar);\r\n var text = plainText;\r\n if (matchedRtlChars || originalDir === \"rtl\") {\r\n text = replaceIndices(text, twttr.txt.extractEntitiesWithIndices, function (itemObj) {\r\n if (itemObj.entityType === \"screenName\") {\r\n return ltrMark + itemObj.entityText + rtlMark;\r\n }\r\n else if (itemObj.entityType === \"hashtag\") {\r\n return (itemObj.entityText.charAt(1).match(rtlChar)) ? itemObj.entityText : ltrMark + itemObj.entityText;\r\n }\r\n else if (itemObj.entityType === \"url\") {\r\n return itemObj.entityText + ltrMark;\r\n }\r\n else if (itemObj.entityType === \"cashtag\") {\r\n return ltrMark + itemObj.entityText;\r\n }\r\n });\r\n }\r\n return text;\r\n }",
"function setNextDirection(event) {\n let keyPressed = event.which;\n\n /* only set the next direction if it is perpendicular to the current direction */\n if (snake.head.direction !== \"left\" && snake.head.direction !== \"right\") {\n if (keyPressed === KEY.LEFT) { snake.head.nextDirection = \"left\"; }\n if (keyPressed === KEY.RIGHT) { snake.head.nextDirection = \"right\"; }\n }\n \n if (snake.head.direction !== \"up\" && snake.head.direction !== \"down\") {\n if (keyPressed === KEY.UP) { snake.head.nextDirection = \"up\"; }\n if (keyPressed === KEY.DOWN) { snake.head.nextDirection = \"down\"; }\n }\n}",
"function changeDirection(direction, command) {\r\n\tif (direction == 'N' && command == 'l') {\r\n\t\tmyRover.direction = 'W';\r\n\t}\r\n\telse if (direction == 'N' && command == 'r') {\r\n\t\tmyRover.direction = 'E';\r\n\t}\r\n\telse if (direction == 'E' && command == 'l') {\r\n\t\tmyRover.direction = 'N';\r\n\t}\r\n\telse if (direction == 'E' && command == 'r') {\r\n\t\tmyRover.direction = 'S';\r\n\t}\r\n\telse if (direction == 'W' && command == 'l') {\r\n\t\tmyRover.direction = 'S';\r\n\t}\r\n\telse if (direction == 'W' && command == 'r') {\r\n\t\tmyRover.direction = 'N';\r\n\t}\r\n\telse if (direction == 'S' && command == 'l') {\r\n\t\tmyRover.direction = 'E';\r\n\t}\r\n\telse {\r\n\t\tmyRover.direction = 'W';\r\n\t}\r\n}",
"function setLanguage(args) {\n\tSETTINGS.LANGUAGE = args.next() || SETTINGS.LANGUAGE\n}",
"function updateDirection() {\n\n\tvar p2 = {\n\t\tx: state.tree[1],\n\t\ty: state.tree[0]\n\t};\n\n\tvar p1 = {\n\t\tx: state.user.location[1],\n\t\ty: state.user.location[0]\n\t};\n\n\t// angle in degrees\n\tvar angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;\n\tangleDeg -= state.user.heading\n\t$(\"#trees .tree .left .dir\").css(\"transform\", \"rotate(\" + angleDeg + \"deg)\")\n\n\tvar dist = getDistanceFromLatLonInM(state.user.location, state.tree)\n\tdist = dist < 1000 ? dist + \"m\" : (Math.round(dist / 100)) / 10 + \"km\"\n\n\t$(\"#trees .tree .left .dist\").html(dist)\n}",
"function setTravelDirection() {\n if (elevator.currentFloor() <= getMinFloor(upQueue)) {\n elevator.travelDirection = \"up\";\n // Set up the lights\n if (directionLights) {\n elevator.goingDownIndicator(false);\n elevator.goingUpIndicator(true);\n }\n }\n else if (elevator.currentFloor() >= getMaxFloor(downQueue)) {\n elevator.travelDirection = \"down\";\n if (directionLights) {\n elevator.goingDownIndicator(true);\n elevator.goingUpIndicator(false);\n }\n }\n else {\n elevator.travelDirection = \"down\";\n if (directionLights) {\n elevator.goingDownIndicator(true);\n elevator.goingUpIndicator(false);\n }\n }\n }",
"function onAlignLineText(direction) {\n alignLineText(direction)\n renderMeme()\n}",
"flipRTL() {\n // Mirror the block's path.\n this.svgPath.setAttribute('transform', 'scale(-1 1)');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
runAngularTrigger function that gets around scope issues with chrome extensions. adds the script that needs to be run to trigger an angular trigger on the page. then removes the code. | function runAngularTrigger(css, trigger) {
var code = "angular.element('" + css + "').triggerHandler('" + trigger + "');";
createTag(find('body'), 'script', 'angular', '', code).nodeType='text/javascript';
remove('#angular');
} | [
"function trigger() {\n $el.data(\"pat-inject-autoloaded\", true);\n inject.onTrigger.apply($el[0], []);\n return true;\n }",
"function onWindowLoad(e){\r\n\tvar appcontent = window.document.getElementById(\"appcontent\"); // browser only\r\n\tif(appcontent){\r\n\t\t//everytime a page loaded, call \"runInject(e)\"\r\n\t\tappcontent.addEventListener(\"load\", runInject, true);\r\n\t}\r\n}",
"function executeScript() {\n chrome.tabs.executeScript(null, {\n file: 'scripts/getPagesSource.js'\n }, function() {\n // If you try and inject into an extensions page or the webstore/NTP you'll get an error\n if (chrome.runtime.lastError) {\n showErrorNotification('There was an error injecting script : \\n' + chrome.runtime.lastError.message, true);\n }\n });\n}",
"function delayed_trigger() {\n $el.data(\"pat-inject-autoloaded\", true);\n inject.onTrigger.apply($el[0], []);\n return true;\n }",
"_applyScript(value, old) {\n qx.bom.storage.Web.getSession().setItem(cboulanger.eventrecorder.UiController.CONFIG_KEY.SCRIPT, value);\n if (this.getRecorder()) {\n this.getRecorder().setScript(value);\n }\n }",
"function setupInjection() {\n try {\n // inject in-page script\n var scriptTag = document.createElement('script');\n scriptTag.textContent = inpageBundle;\n scriptTag.onload = function () {\n this.parentNode.removeChild(this);\n };\n var container = document.head || document.documentElement;\n // append as first child\n container.insertBefore(scriptTag, container.children[0]);\n } catch (e) {\n console.error('DefiMask injection failed.', e);\n }\n}",
"function injectBody() {\n if (bodyScripts.length > 0) {\n console.debug('injecting body JavaScript...');\n var bodies = document.getElementsByTagName('body');\n if (bodies.length > 0) {\n var scriptBlock = document.createElement('script');\n scriptBlock.appendChild(document.createTextNode(bodyScripts));\n bodies[0].appendChild(scriptBlock);\n }\n }\n}",
"function deleteTriggers() {\r\n var triggers = ScriptApp.getProjectTriggers();\r\n for (var i = 0; i < triggers.length; i++) {\r\n ScriptApp.deleteTrigger(triggers[i]);\r\n }\r\n}",
"function removeTriggers() {\n var triggers = ScriptApp.getProjectTriggers();\n for (var i = 0; i < triggers.length; i++) {\n ScriptApp.deleteTrigger(triggers[i]);\n }\n}",
"adjustSpecials(line, compiled, previousLineType) {\r\n // update events\r\n line = line.replace(this.eventsRegex, function (matchedText, event, callbackText) {\r\n if (previousLineType == 'htmlStatement') {\r\n compiled += '`';\r\n }\r\n\r\n compiled += \";\\n\";\r\n\r\n compiled += \"randomFunctionName = 'func' + Math.floor(Math.random() * 99999999999999);\\n\";\r\n\r\n // $el => the element dom object that may be used as special variable\r\n // i.e (click)=\"hide($el)\"\r\n compiled += 'window[randomFunctionName] = function ($el) {' + callbackText + ' }.bind(scope);';\r\n compiled += 'if (! window.customFunctions.on' + event + ') window.customFunctions.on' + event + ' = {};';\r\n compiled += 'window.customFunctions.on' + event + '[randomFunctionName] = window[randomFunctionName]';\r\n\r\n compiled += \"\\n\";\r\n if (previousLineType == 'htmlStatement') {\r\n compiled += 'htmlCode +=`';\r\n }\r\n\r\n return 'on' + event + '=\"${randomFunctionName}(this);';\r\n });\r\n\r\n // styles attributes\r\n // please note that this special attribute will override any style attribute in the line\r\n line = line.replace(this.stylesRegex, (matchedText, attribute, value) => {\r\n if (attribute == 'style') {\r\n if (previousLineType == 'htmlStatement') {\r\n compiled += '`';\r\n }\r\n\r\n compiled += \";\\n\";\r\n compiled += `\r\n var styleObject = ${value};\r\n\r\n var styleText = 'style=\"';\r\n\r\n for (var key in styleObject) {\r\n styleText += key + ':' + styleObject[key] + ';'; \r\n }\r\n\r\n styleText += '\"';\r\n `;\r\n\r\n compiled += \"\\n\";\r\n if (previousLineType == 'htmlStatement') {\r\n compiled += 'htmlCode +=`';\r\n }\r\n\r\n return '${styleText}';\r\n } else {\r\n return `style=\"${attribute}:${value};\"`;\r\n }\r\n });\r\n\r\n // update boolean attributes\r\n line = line.replace(this.attributesRegex, function (matchedText, attribute, booleanExpression) {\r\n return '${' + booleanExpression + ' ? \"' + attribute + '\" : \"\"}';\r\n });\r\n\r\n // classes list\r\n line = line.replace(this.classesListRegex, function (matchedText, objectText) {\r\n if (previousLineType == 'htmlStatement') {\r\n compiled += '`';\r\n }\r\n\r\n compiled += \";\\n\";\r\n\r\n compiled += `\r\n classesList = ${objectText};\r\n availableClasses = [];\r\n\r\n for (var className in classesList) {\r\n if (classesList[className]) {\r\n availableClasses.push(className);\r\n }\r\n }\r\n\r\n availableClasses = availableClasses.join(' ');\r\n `;\r\n\r\n compiled += \"\\n\";\r\n if (previousLineType == 'htmlStatement') {\r\n compiled += 'htmlCode +=`';\r\n }\r\n\r\n return '[class]=\"${availableClasses}\"';\r\n });\r\n\r\n return [line, compiled];\r\n }",
"function deleteTriggers() {\r\n var triggers = ScriptApp.getProjectTriggers();\r\n for (var i = 0; i < triggers.length; i++) {\r\n ScriptApp.deleteTrigger(triggers[i]);\r\n }\r\n}",
"function oosHookJsCode()\n{\n\tfor (var i = 0; i < oosHookJsCodeFunctions.length; i++)\n\t{\n\t\tif (function_exists(oosHookJsCodeFunctions[i]))\n\t\t\tsetTimeout(oosHookJsCodeFunctions[i] + '()', 0);\n\t}\n}",
"function pingAndInject(tabId, connector, cb) {\n\t\t// Ping the content page to see if the script is already in place.\n\t\t// In the future, connectors will have unified interface, so they will all support\n\t\t// the 'ping' request. Right now only YouTube supports this, because it\n\t\t// is the only site that uses ajax navigation via History API (which is quite hard to catch).\n\t\t// Other connectors will work as usual.\n\t\t//\n\t\t// Sadly there is no way to silently check if the script has been already injected\n\t\t// so we will see an error in the background console on load of every supported page\n\t\tchrome.tabs.sendMessage(tabId, {type: 'ping'}, function (response) {\n\t\t\t// if the message was sent to a non existing script or the script\n\t\t\t// does not implement the 'ping' message, we get response==undefined;\n\t\t\tif (!response) {\n\t\t\t\tconsole.log('-- loaded for the first time, injecting the scripts');\n\n\t\t\t\t// inject all scripts and jQuery, use slice to avoid mutating\n\t\t\t\tvar scripts = connector.js.slice(0);\n\n\t\t\t\t// for v2 connectors prepend BaseConnector, newer jQuery (!) and append starter\n\t\t\t\tif (typeof(connector.version) != 'undefined' && connector.version === 2) {\n\t\t\t\t\tscripts.unshift('core/content/connector.js');\n\t\t\t\t\tscripts.unshift('core/content/reactor.js');\n\t\t\t\t\tscripts.unshift('vendor/underscore-min.js');\n\t\t\t\t\tscripts.unshift(config.JQUERY_PATH);\n\n\t\t\t\t\tscripts.push('core/content/starter.js'); // needs to be the last script injected\n\t\t\t\t}\n\t\t\t\t// for older connectors prepend older jQuery as a first loaded script\n\t\t\t\telse {\n\t\t\t\t\tscripts.unshift(config.JQUERY_1_6_PATH);\n\t\t\t\t}\n\n\t\t\t\t// waits for script to be fully injected before injecting another one\n\t\t\t\tvar injectWorker = function () {\n\t\t\t\t\tif (scripts.length > 0) {\n\t\t\t\t\t\tvar jsFile = scripts.shift();\n\t\t\t\t\t\tvar injectDetails = {\n\t\t\t\t\t\t\tfile: jsFile,\n\t\t\t\t\t\t\tallFrames: connector.allFrames ? connector.allFrames : false\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tconsole.log('\\tinjecting ' + jsFile);\n\t\t\t\t\t\tchrome.tabs.executeScript(tabId, injectDetails, injectWorker);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t// done successfully\n\t\t\t\t\t\tcb(new injectResult.InjectResult(injectResult.results.MATCHED_AND_INJECTED, tabId, connector));\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tinjectWorker();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// no cb() call, useless to report this state\n\t\t\t\tconsole.log('-- subsequent ajax navigation, the scripts are already injected');\n\t\t\t}\n\t\t});\n\t}",
"function scope_on_scroll() {\n var cnt = document.getElementById(\"content\");\n var scope_cnt = document.getElementById(\"scope_content\");\n var y = cnt.getBoundingClientRect().top + 2;\n\n var c = document.elementFromPoint(15, y+1);\n scope_cnt.innerHTML = '';\n if (c.className === \"l\" || c.className === \"hl\") {\n prev = c;\n var par = c.parentNode;\n while( par.className !== 'scope-body' && par.className !== 'scope-head' ) {\n par = par.parentNode;\n if (par === null) {\n return ;\n }\n }\n var head = par.className === 'scope-body' ? par.previousSibling : par;\n var sig = head.children[0];\n scope_cnt.innerHTML = '<a href=\"#' + head.id + '\">' + sig.innerHTML + '</a>';\n }\n}",
"maybeTriggerScript(et, args) {\n let comps = this.ecs.getComponents(args.thing);\n if (!comps.has(Component.Enemy)) {\n return;\n }\n let enemy = comps.get(Component.Enemy);\n if (!enemy.finalBoss) {\n return;\n }\n this.scriptRunner.run(new Script.EndSequence());\n }",
"function simulateConsole(){\n let code = generateRandomJSCode();\n let codeElement = document.getElementById(\"desktopBkGroundOverlay\");\n codeElement.innerHTML += \"<p>\"+code+\"</p>\";\n while(codeElement.scrollHeight > codeElement.clientHeight){\n //Remove the first child of the element with a scroll up effect.\n codeElement.removeChild(codeElement.firstChild);\n }\n setTimeout(simulateConsole, Math.random()*50 + 450);\n}",
"function runCode() {\r\n const code = editor.getValue();\r\n if (!code) return;\r\n let { response, logs, error } = evaluate(code);\r\n\r\n if (error) response = '<span class=\"error\">' + response + '</span>';\r\n if (logs.length && response) response = logs.join('\\n') + '\\n' + response;\r\n else if (logs.length) response = logs.join('\\n');\r\n\r\n consoleHTML.innerHTML += `<pre class=\"log\">${response}\\n</pre>`;\r\n}",
"function exec(code)\n{\n if(!init_js_stuff)return\n try{parent.document.getElementById('exec').innerHTML+=';'+escape(code)}\n catch(e){top.status=\"code failed: \"+code+\": \"+e.message}\n}",
"function injectJs(js) {\r\n\tvar prom = lcdwindow.webContents\r\n\t\t.executeJavaScript(js)\r\n\t\t.then((value) => {\r\n\t\t\tconsole.log('Javascript Injected');\r\n\t\t})\r\n\t\t.catch((error) => {\r\n\t\t\tconsole.log('Error injecting JS');\r\n\t\t\tconsole.log('Error: ' + (error ? error : '<empty>'));\r\n\t\t});\r\n\r\n\treturn prom;\r\n}",
"addCustomTrigger(event)\n {\n event.preventDefault();\n\n if (this.alert.alert_triggers.length >= this.maxTriggers) {\n Popup.error('Max Triggers Reached', `You can add a maximum of ${this.maxTriggers} to a single alert. Sorry!`);\n return;\n }\n\n const trigger = {\n id: Math.floor((Math.random() * 99999) + 1),\n alert_trigger_field: this.uiForm.find('#alert_trigger_field').val().trim(),\n alert_trigger_op: this.uiForm.find('#alert_trigger_op').val().trim(),\n alert_trigger_value: this.uiForm.find('#alert_trigger_value').val().trim(),\n };\n\n this.addCustomTriggerVisual(trigger, true);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove label collector function on axis remove/update. | function onAxisDestroy() {
if (this.chart &&
this.chart.labelCollectors) {
var index = (this.labelCollector ?
this.chart.labelCollectors.indexOf(this.labelCollector) :
-1);
if (index >= 0) {
this.chart.labelCollectors.splice(index, 1);
}
}
} | [
"function hoverOutState(){\n\td3.select(\".infolabel\").remove(); //remove info label\n}",
"function hideLabel() { \n marker.set(\"labelVisible\", false); \n }",
"function clearScatterPlot(){\r\n svg.selectAll(\".axis\").remove();\r\n svg.selectAll('.dot').remove();\r\n svg.selectAll('.extraTextSP').remove();\r\n }",
"function removeInsulaLabels(){\n\t\tvar i=0;\n\t\tfor(i;i<insulaMarkersList.length;i++){\n\t\t\tpompeiiMap.removeLayer(insulaMarkersList[i]);\n\t\t}\n\t}",
"drawBarsRemoveOld(){\n }",
"function removeYearLabels(){\n \n for(var i=0; i<100; i++){\n\n var yearLabels = document.getElementsByClassName(\"yearLabel\");\n\n //should probably do null check here\n for(var j=0; j<yearLabels.length; j++){\n var temp = yearLabels[j].parentNode;\n temp.removeChild(yearLabels[j]);\n }\n }\n\n }",
"function myFunctionLabel(){\nconst labelForm = document.querySelector('.screen-reader-text');\nconst elementLabel = document.getElementsByTagName('label')[0];\nelementLabel.setAttribute('id', 'label-id');\n\telementLabel.remove();\n}",
"function removeVisualiserButton(){\r\n\teRem(\"buttonWaves\");\r\n\teRem(\"buttonBars\");\r\n\teRem(\"buttonBarz\");\r\n\teRem(\"buttonCircleBars\");\r\n\teRem(\"buttonCirclePeaks\");\r\n\tremoveSliderSelector();\r\n}",
"function hideAxis() {\n g.select('.x.axis')\n .transition().duration(500)\n .style('opacity', 0);\n }",
"function clickClearWarnings(label) {\n $(label + ' #input').validate().resetForm()\n $(\"div.ui-tooltip\").remove();\n}",
"removePlot(symbol) {\n if (this.data.hasOwnProperty(symbol)) {\n this.g.select('.plot-line-' + symbol)\n .remove();\n\n this.g.selectAll('.price-point-' + symbol)\n .remove();\n\n // Finally, add the used color back, and remove symbol data\n var color = this.data[symbol].color;\n this.colors.push(color);\n delete this.data[symbol];\n\n // Scale y-values with existing plots\n this.minY = this.ctrl.getGlobalMinY(this.data);\n this.maxY = this.ctrl.getGlobalMaxY(this.data);\n\n this.rescaleY(this.minY, this.maxY, true);\n\n var symbols = Object.keys(this.data);\n symbols.forEach( (sym) => {\n if (sym !== symbol) {\n this.redrawPlot(sym);\n }\n });\n\n }\n else {\n console.error('No symbol. Cannot remove ' + symbol);\n }\n\n }",
"function removeTrendChart() {\r\n $('.trendChartData').hide();\r\n $('#trendChartLegend').hide();\r\n $('#lineChartLegend').show();\r\n}",
"function remove_visible_tooltips() {\n $(\".tooltip\").remove();\n }",
"function TdeCtrl_OnToolTipCloseBt() \n{\n LabelOpObj.RemoveToolTip();\n}",
"removeUpdateListener(cb) {\n let idx = this.updateCallbacks.findIndex(o => o === cb);\n this.updateCallbacks.slice(idx);\n }",
"removeColorScaleMember(colorMemberIndex) {\n const state = this.state;\n state.configuration.charts[0].colorScale.splice(colorMemberIndex, 1);\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }",
"function removeServiceProviderFromLabel(label) {\n\tvar position = label.lastIndexOf(\" \");\n\tvar text = label.substring(position);\n\treturn text;\n}",
"function removeCorpusButton()\n{\n d3.select(\".corpus-link\").remove();\n d3.select(\".back-button\").remove();\n d3.select(\".aggregate-button\").remove();\n}",
"removeMouseInteractions() {\t\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"click\", this.towerStoreClick);\n\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"mousemove\", this.towerStoreMove);\t\t\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Capture video stream of tab, will pass stream back to sendResponse() | function captureTabVideo(senderTab) {
console.log("captureTabVideo");
// Sanity check, can only record one at a time
if (videoConnection)
{
console.log('ERROR: video stream already exists, cannot capture two at a time!');
}
var settings, width, height;
settings = {};
// Get video dimensions
debugLog('Tab dimensions:', senderTab.width, senderTab.height);
width = DEFAULT_VIDEO_WIDTH;
height = DEFAULT_VIDEO_HEIGHT;
debugLog('Video dimensions:', width, height);
debugLog('Adjusting aspect ratio...');
var fitSize = calculateAspectRatioFit(senderTab.width, senderTab.height, width, height);
width = Math.ceil(fitSize.width);
height = Math.ceil(fitSize.height);
debugLog('New size:', width, height);
// Get video settings
var videoSettings = {
mandatory: {
minWidth: width,
minHeight: height,
maxWidth: width,
maxHeight: height,
minFrameRate: DEFAULT_VIDEO_FRAME_RATE,
maxFrameRate: DEFAULT_VIDEO_FRAME_RATE,
chromeMediaSource: 'tab'
},
};
// Capture only video from the tab
chrome.tabCapture.capture({
audio: false,
video: true,
videoConstraints: videoSettings
},
function (localMediaStream)
{
debugLog('tabCapture:', localMediaStream);
// Send to active tab if capture was successful
if (localMediaStream)
{
// Store stream for reference
videoConnection = localMediaStream;
// Start recording
if (videoRecorder.start(videoConnection))
{
recordedTabID = extensionScreenCapture.id; // Track recorded tab id
chrome.browserAction.setBadgeText({
text: "REC",
});
chrome.browserAction.setBadgeBackgroundColor({
color: "#F00",
});
tabRecordingStatus = true;
isRecording = true;
running = true;
}
else // Error starting recording
{
console.log('ERROR: could not start video recorder');
videoConnection = null;
}
}
else // Failed
{
console.log("ERROR: could not capture video stream")
console.log(chrome.runtime.lastError);
videoConnection = null;
}
// Send to response
chrome.tabs.sendMessage(senderTab.id, {
request: 'videoRecordingStarted',
stream: videoConnection
});
}
);
} | [
"function Capture() {\n setInterval(function () {\n webcam.capture(function () {\n var frame = webcam.frameRaw();\n io.emit('streamCam', \"data:image/png;base64,\" + Buffer(frame).toString('base64'));\n });\n }, 200);\n }",
"function stopVideoCapture(senderTab, callback) {\n console.log(\"stopVideoCapture\");\n\n // Clear recording state\n recordedTabID = null;\n chrome.browserAction.setBadgeText({\n text: \"\",\n });\n chrome.browserAction.setBadgeBackgroundColor({\n color: \"#F00\",\n });\n\n // Sanity check\n if (!videoConnection) \n {\n videoConnection = null;\n chrome.tabs.sendMessage(senderTab.id, {\n request: 'videoRecordingStopped',\n sourceURL: null,\n });\n return;\n }\n\n // Stop video capture and save file\n var videoData = videoRecorder.stop();\n try {\n videoConnection.stop();\n } catch (exception) {\n console.log(exception);\n } finally {\n videoConnection = null;\n }\n\n // If output was bad, don't continue\n if (!videoData || !videoData.sourceURL) \n {\n chrome.tabs.sendMessage(senderTab.id, {\n request: 'videoRecordingStopped',\n sourceURL: null,\n });\n return;\n }\n \n console.log(videoData);\n var file = new File([videoData.videoBlob], 'RecordRTC-' + (new Date).toISOString().replace(/:|\\./g, '-') + '.webm', {\n type: 'video/webm'\n });\n\n var formData = new FormData();\n formData.append('video-filename', file.name);\n formData.append('video-file', file);\n\n sendMessageToContentScript({\"loadingScreen\": true, \"messageFromContentScript1234\": true});\n chrome.cookies.getAll({'domain': 'userstory.io', 'name': 'emailUserStory'}, function(cookie) {\n console.log(cookie[0].value);\n formData.append('email', cookie[0].value);\n xhr('http://userstory.io/uploadvideo/', formData, function(data) {\n //console.log(data['url']);\n sendMessageToContentScript({\"clearLoadingScreen\": true, \"messageFromContentScript1234\": true});\n var url = \"http://userstory.io\" + data['url'];\n\n chrome.tabs.create({url: url, selected: true});\n setDefaults();\n chrome.runtime.reload();\n\n askToStopExternalStreams();\n\n try {\n peer.close();\n peer = null;\n } catch (e) {\n\n };\n\n try {\n audioPlayer.src = null;\n mediaStremDestination.disconnect();\n mediaStremSource.disconnect();\n context.disconnect();\n context = null;\n } catch (e) {\n\n }\n });\n });\n \n isRecording = false;\n tabRecordingStatus = false;\n}",
"function onReceiveStream(stream, elementID){\n var video = $('#' + elementID + ' video')[0];\n console.log(video);\n video.src = window.URL.createObjectURL(stream);\n }",
"recordVideo() {\n this.refs.buttonCancel.style.display = 'none';\n this.refs.buttonRecord.style.display= 'none';\n this.refs.buttonStop.style.display= 'initial';\n var self = this;\n\n \n\n navigator.getUserMedia(\n\n // Constraints\n self.state.mediaConstraints,\n\n // Success Callback\n function(stream) {\n //RecordRTC part - recording of the video\n\n // Get a reference to the video element on the page.\n var video = document.getElementById('camera-stream');\n video.src = window.URL.createObjectURL(stream);\n\n var options = {\n mimeType: 'video/webm',\n bitsPerSecond: 1200000,\n bufferSize: 16384,\n sampleRate: 96000\n };\n var recordRTC = RecordRTC(stream, options);\n self.saveRecordRTC(recordRTC);\n self.state.recordRTC.startRecording();\n self.stopVideoCapture();\n self.updateStream(stream);\n },\n\n // Error Callback\n function(err) {\n // Log the error to the console.\n console.log('The following error occurred when trying to use getUserMedia: ' + err);\n }\n ); \n }",
"function recordVideo() {\n if (!video_capture) {\n if (scene.startVideoCapture()) {\n video_capture = true;\n video_button.innerHTML = \"STOP VIDEO\";\n video_blink = setInterval(function() {\n var bgcolor = window.getComputedStyle( video_button ,null).getPropertyValue('background-color');\n // flash recording button\n video_button.style.backgroundColor = (bgcolor != \"rgb(255, 192, 203)\") ? \"pink\" : \"white\";\n }, 500);\n }\n }\n else {\n return scene.stopVideoCapture().then(function(video) {\n video_capture = false;\n video_button.innerHTML = \"RECORD VIDEO\";\n window.clearInterval(video_blink);\n video_button.style.backgroundColor = \"white\";\n saveAs(video.blob, 'tangram-video-' + (+new Date()) + '.webm');\n });\n }\n}",
"function sendPreview( response ) {\n\tconsole.log(\"<< new preview\" );\n\t// auto-overwrite the preview file (piping \"y\" to yes/no-prompt)\n\texec('echo \"y\" | gphoto2 --capture-preview');\n\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\tresponse.end('{\"status\":\"ok\",\"image\":\"capture_preview.jpg\"}');\n}",
"function createCaptureFrame() {\r\n\r\n media_capture = new Windows.Media.Capture.MediaCapture();\r\n //media_capture = new Windows.Media.Capture.CameraCaptureUI();\r\n\r\n\r\n capture_frame = document.createElement(\"video\");\r\n capture_frame.style.cssText = \"position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index:995\";\r\n\r\n detection_line = document.createElement('div');\r\n detection_line.style.cssText = \"position: absolute; left:0; top: 50%; width: 100%; height: 3px; background: red; z-index:996\";\r\n\r\n\r\n cancel_scan_button = document.createElement(\"button\");\r\n cancel_scan_button.innerText = \"Cancel\";\r\n cancel_scan_button.style.cssText = \"position: fixed; right: 0; bottom: 0; display: block; margin: 20px; z-index:996\";\r\n cancel_scan_button.addEventListener('click', cancelScan, false);\r\n\r\n }",
"function captureScreen() {\n chrome.tabs.captureVisibleTab({format: 'png'}, function (imgData) {\n sendMessage('saveImg', imgData)\n });\n}",
"function openVideo() {\r\n\t\tTitanium.Platform.openURL(movie.trailerUrl);\r\n\t}",
"function captureTab() {\n chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {\n if(!tabs) {\n return ;\n }\n chrome.tabs.sendMessage(tabs[0].id, {action: \"addInterface\"}, \n function(response) {\n console.log(response);\n }\n );\n });\n}",
"function startPreview() {\n //reset isCancelled\n barcodeDecoder.scanning = false;\n barcodeDecoder.isCancelled = false;\n\n // Prevent the device from sleeping while the preview is running\n oDisplayRequest.requestActive();\n\n // Set the preview source in the UI\n previewVidTag = document.createElement(\"video\");\n previewVidTag.id = \"cameraPreview\";\n previewVidTag.style.position = 'absolute';\n previewVidTag.style.top = '0';\n previewVidTag.style.left = '0';\n previewVidTag.style.height = '100%';\n previewVidTag.style.width = '100%';\n previewVidTag.style.zIndex = '900';\n document.body.appendChild(previewVidTag);\n\n var previewUrl = URL.createObjectURL(oMediaCapture);\n previewVidTag.src = previewUrl;\n previewVidTag.play();\n\n previewVidTag.addEventListener(\"playing\", function () {\n isPreviewing = true;\n setPreviewRotationAsync();\n });\n}",
"function startCapture() {\n\tinitSize();\n\tinitStyle();\n\t//capturing = true;\n\tstartTime = new Date().getTime();\n\tnextFrame();\n}",
"function startVideo() {\n mini_peer.setLocalStreamToElement({ video: true, audio: true }, localVideo);\n}",
"function loadVideoStream (url) {\n\tvar outputVideo = '';\n\t$('#stream').click(function(e){\n\t\te.preventDefault();\n\t\t$.getJSON( url + '/main_page/build_video_stream', function(data){\n\t\t\tif (data.result != false) {\n\t\t\t\t$.each(data, function(){\n\t\t\t\t\t$.each(this, function(key, value){\n\t\t\t\t\t\t// console.log(value);\n\t\t\t\t\t\toutputVideo += generateVideoTags(value);\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\t// var element = document.getElementById('list_video');\n\t\t\t\t// element.innerHTML = outputVideo;\n\t\t\t\t$(\"#list_video\").html(outputVideo);\n\t\t\t\t// $('#ul').show().html\n\t\t\t};\n\t\t\t// console.log(outputVideo);\n\t\t\t// console.log(data);\n\t\t})\n\t})\n}",
"async function streamingToFacebook(data) {\n const blob = new Blob(recordedBlobs, { type: defaults.videoType });\n //Creates a form data and appends the recorded video and\n var formData = new FormData();\n formData.append(\n \"file\",\n blob,\n Math.floor(Math.random() * 100800000000) + 1\n );\n formData.append(\"id\", data.id);\n formData.append(\"secure_stream_url\", data.secure_stream_url);\n try {\n const response = await fetch(\n \"https://localhost:44366/facebook/streaming\",\n {\n method: \"POST\",\n body: formData,\n }\n );\n const content = await response.json();\n console.log(content);\n return content;\n } catch (err) {\n console.log(err);\n }\n }",
"async function handleStop(e) {\n const blob = new Blob(recordedChunks, {\n type: \"video/webm; codecs=vp9\"\n });\n\n const buffer = Buffer.from(await blob.arrayBuffer());\n\n const { filePath } = await dialog.showSaveDialog({\n buttonLabel: \"Save video\",\n defaultPath: `vid-${Date.now()}.webm`\n });\n\n console.log(filePath);\n\n writeFile(filePath, buffer, () => console.log(\"video saved successfully!\"));\n}",
"function cameraSnap (videoObject, next) {\n // FIXME - should probably play a camera shutter sound\n var canvasElement = document.createElement(\"canvas\");\n canvasElement.setAttribute(\"class\", \"hidden\");\n document.body.appendChild(canvasElement);;\n var width = $(videoObject).width(), height = $(videoObject).height();\n canvasElement.style.width = width + \"px\";\n canvasElement.style.height = height + \"px\";\n canvasElement.width = width;\n canvasElement.height = height;\n\n var graphicContext = canvasElement.getContext(\"2d\");\n graphicContext.clearRect(0, 0, width, height);\n graphicContext.drawImage(videoObject, 0, 0, width, height);\n userMedia.stopCapture(document.getElementById(\"vid\"));\n\n var imgData = canvasElement.toDataURL();\n $(\"#capture\").append(\n util.format(\n \"<img src=\\\"%s\\\" title=\\\"click again to take another\\\"></img>\", \n imgData\n )\n );\n $(videoObject).addClass(\"hidden\");\n next(imgData)\n}",
"function takePicture(time, response ) {\n\ttime = parseInt(time);\n\tconsole.log(\"<< new picture in \" + time + \"s\" );\n\t\n\tsetTimeout(function () {\n\t\tchild.send('stop');\n\t}, (time > 1 ? time - 1 : 0 ) * 1000 );\n\t\n\tsetTimeout(function() {\n\t\t\n\t\ttry {\n\t\t\texec('echo \"y\" | gphoto2 --capture-image-and-download --filename=capture.jpg');\n\t\t\t\n\t\t\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\t\t\tresponse.end('{\"status\":\"ok\"}');\n\t\t\t\n\t\t} catch (err) {\n\t\t\tconsole.log(\"-!- Error: \", err);\n\t\t\t\n\t\t\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\t\t\tresponse.end('{\"status\":\"error\"}');\n\t\t}\n\t}, time * 1000);\n}",
"function capture(url, out, cb) {\n var command = util.format('xvfb-run wkhtmltoimage --width 800 --height 480 %s %s', url, out);\n exec(command, function (error, stdout, stderr) {\n if (error) {\n return cb(err);\n }\n\n cb(null, {stderr: stderr, stdout: stdout});\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Middleware for decoding a token. | function getDecodedToken(req, res, next) {
req.decodedToken = verifyJwt(req, next);
return next();
} | [
"function authMiddleware(next){\n return function(msg, replier){\n var params = JSON.parse(msg);\n tokenAuthentication(params.token, function(valid){\n if (!valid) {\n return replier(JSON.stringify({ok: false, error: \"invalid_auth\"}));\n } else {\n next(msg, replier);\n }\n });\n }\n}",
"tokenPostCheck(req, res, next) {\n let postDataString = '';\n // Get all post data when receive data event.\n req.on('data', (chunk) => {\n postDataString += chunk;\n });\n // When all request post data has been received.\n req.on('end', () => {\n //chuyen doi Object JSON tu chuoi data nhan duoc\n let postDataObject = JSON.parse(postDataString);\n //console.log(postDataObject);\n\n if (postDataObject && postDataObject.Authorization) {\n let token = postDataObject.Authorization;\n //da lay duoc token qua json\n //gan cho req de xu ly token\n req.token=token;\n if (verifyToken(req,res)){\n next();\n }else{\n res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });\n res.end(JSON.stringify({\n success: false,\n message: 'Auth token is not supplied'\n }));\n }\n } else {\n //khong truyen\n res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });\n return res.end(JSON.stringify({\n success: false,\n message: 'Auth token is not supplied ANY!'\n }));\n }\n });\n }",
"static isAuthenticated(req, res, next) {\n const Authorization = req.get('Authorization');\n\n if (Authorization) {\n const token = Authorization.replace('Bearer ', '');\n try {\n // JWTSECRET=some long secret string\n const payload = jwt.verify(token, process.env.JWTSECRET);\n\n // Attach the signed payload of the token (decrypted of course) to the request.\n req.jwt = {\n payload\n };\n\n next();\n } catch {\n // The JSON Web Token would not verify.\n res.sendStatus(401);\n }\n } else {\n // There was no authorization.\n res.sendStatus(401);\n }\n }",
"function tokenHandler(err, resp, body) {\n try { //google\n token = JSON.parse(body);\n } catch(err) { //facebook\n token = qs.parse(body);\n }\n if (token.error) return res.send(502, token.error); //TODO: improve error management\n //Facebook gives no token_type, Google gives 'Bearer' and Windows Live gives 'bearer', but is this test really useful?\n if ((token.token_type) && (token.token_type.toLowerCase() !== 'bearer')) return res.send(502, 'Invalid token type');\n request.get(providers[session.provider].profileURL + '?' + oAuth2.access_token + '=' + encodeURIComponent(token.access_token), profileHandler);\n //TODO: isn't it too soon to redirect as the profile may not have been saved yet?\n if(session.returnUrl) {\n var params = {\n access_token: token.access_token,\n expires: token.expires_in || token.expires, //Note: Facebook as token.expires instead of token.expires_in\n state: session.state\n };\n token.state = session.state;\n res.redirect(session.returnUrl + '#' + qs.stringify(params));\n }\n res.json(token); //Without returnUrl, the client receives the token as json to do whatever he/she deems necessary\n }",
"function tokenFunc() {\n\tlet data = {username : process.env.WORDPRESS_USER, password : process.env.WORDPRESS_PASS};\n\treturn new Promise(function(resolve, reject) {\n\t\trequest({\n\t\t\turl: process.env.WORDPRESS_ROOT_PATH + \"/wp-json/jwt-auth/v1/token\",\n\t\t\tContentType : 'application/x-www-form-urlencoded',\n\t\t\tmethod: \"POST\",\n\t\t\tform: data\n\t\t}, function(error, response, body) {\n\t\t\tif(error) {\n\t\t\t\treject(error)\n\t\t\t} else {\n\t\t\t\tlet info = body.substring(body.indexOf(\"{\"));\n\t\t\t\tinfo = JSON.parse(info);\n\t\t\t\tinfo = info.token;\n\t\t\t\tresolve(info);\n\t\t\t\t/*\n\t\t\t\trequest({\n\t\t\t\t\turl: process.env.WORDPRESS_ROOT_PATH + '/wp-json/jwt-auth/v1/token/validate',\n\t\t\t\t\tContentType: 'application/json',\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tauth: {'bearer' : info},\n\t\t\t\t\tjson: true\n\t\t\t\t}, function(error, response, body) {\n\t\t\t\t\tif(error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\t\t\t\t\tif(body == undefined) {\n\t\t\t\t\t\treject(\"Not a real postID\");\n\t\t\t\t\t}\n\t\t\t\t\tbody = body.substring(body.indexOf(\"{\"));\n\t\t\t\t\tbody = JSON.parse(body);\n\t\t\t\t\tconsole.log(body);\n\t\t\t\t\tif(body.code == \"jwt_auth_valid_token\") {\n\t\t\t\t\t\tresolve(info);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t*/\n\t\t\t}\n\t\t});\n\t});\n}",
"_getTokenFromRequest (req) {\n let authorization = req.get ('authorization');\n\n if (authorization) {\n let parts = authorization.split (' ');\n\n if (parts.length !== 2)\n return Promise.reject (new BadRequestError ('invalid_authorization', 'The authorization header is invalid.'));\n\n if (!BEARER_SCHEME_REGEXP.test (parts[0]))\n return Promise.reject (new BadRequestError ('invalid_scheme', 'The authorization scheme is invalid.'));\n\n return Promise.resolve (parts[1]);\n }\n else if (req.body && req.body.access_token) {\n return Promise.resolve (req.body.access_token);\n }\n else if (req.query && req.query.access_token) {\n return Promise.resolve (req.query.access_token);\n }\n else {\n return Promise.reject (new BadRequestError ('missing_token', 'The access token is missing.'));\n }\n }",
"async function ensureToken(req, res, next) {\n try {\n var bearerHeader = req.headers['authorization']\n if (typeof bearerHeader == 'undefined') {\n console.log('undefined, gak ada token');\n return res.status(403).send({\n 'message': 'token not provided'\n })\n }\n var bearerToken = bearerHeader.split(' ')\n var tokenBracket = bearerToken[0]\n var tokenProvided = bearerToken[1]\n\n if (tokenBracket !== 'bearer')\n return res.status(403).send({'message': 'worng format header Authorization'})\n\n const user = await jwt.verify(tokenProvided, process.env.SECRET_KEY)\n\n if(user.isActive==false)\n return res.status(403).send({\"message\":\"need activation user.\"})\n \n req.body.user = user\n next()\n } catch (error) {\n console.log(error);\n return res.status(403).send({\n 'message': 'token is not valid'\n })\n }\n}",
"async function getAccessToken(req, res, next) {\n const code = req.query.code;\n //const state = JSON.parse(req.query.state); // TODO do i need state?\n\n res.locals.success = true;\n if (!code) {\n console.error('/facebook: Endpoint called without code query parameter.'); // STRETCH replace with server side logging \n return next();\n }\n\n // ask for token from authorization server\n const body = await fetch(getFacebookAccessTokenUrl(\n process.env.BASE_URL + '/login/facebook',\n facebook_oauth.app_id,\n facebook_oauth.app_secret,\n code\n )).then(response => response.json());\n\n const { access_token } = body;\n\n if (!access_token) console.error('facebookOathController.getAccessToken: ERROR: Unable to retrieve access_token after having been provided a code.'); // STRETCH replace with server side logging \n else res.locals.access_token = access_token;\n return next();\n}",
"static get_token({ organizationId, tokenId }) {\n return new Promise(\n async (resolve) => {\n try {\n resolve(Service.successResponse(''));\n } catch (e) {\n resolve(Service.rejectResponse(\n e.message || 'Invalid input',\n e.status || 405,\n ));\n }\n },\n );\n }",
"get(data, callback) {\n // Check id is valid\n const id =\n typeof data.queryStringObject.id === 'string'\n && data.queryStringObject.id.trim().length === 20\n ? data.queryStringObject.id.trim()\n : false;\n\n if(id) {\n // Lookup token\n _data.read(\n 'tokens',\n id,\n (err, tokenData) => (\n !err && tokenData\n ? callback(200, tokenData)\n : callback(404)\n )\n );\n }\n else {\n callback(400, { Error: 'Missing required field.' });\n }\n }",
"function passportTokenCallback(provider, options) {\n return function(req, res, next) {\n var theOptions = Object.assign({}, options);\n theOptions.session = false;\n passport.authenticate(provider + '-token', theOptions)(req, res, next);\n };\n }",
"function getMessageDecoding( msg )\n{\n\tlet dec = new TextDecoder();\n\treturn dec.decode( msg );\n}",
"function getToken(req, res, next) {\n var fb_uid = req.body.uid;\n var fb_token = req.body.token;\n // make a request to Facebook to check the validity of fb_uid and fb_token\n var params = {\n access_token: fb_token,\n fields: \"id\"\n };\n request.get({\n url: ' https://graph.facebook.com/me',\n qs: params\n }, function (err, resp, body) {\n req.body.isValid = false;\n var results = qs.parse(body);\n\n for (var item in results) {\n var finalObject = JSON.parse(item);\n if (finalObject.id) {\n if (finalObject.id == fb_uid) {\n req.body.isValid = true;\n }\n }\n }\n // console.log(\"from callback function: getToken: isValid: \", req.body.isValid);\n if (req.body.isValid) {\n extendFbAccessToken(req, res, next);\n } else {\n errObj.errNum = 4;\n errObj.errMessage = \"fb_shortToken is invalid or expired\";\n res.send(errObj);\n res.end();\n }\n\n });\n}",
"function decodeMessage() {\n// new RegExp( \"(\\\\d)(\\\\d{2})(.{\" + smash._securityTokenLength + \"})(.{\" + smash._securityTokenLength + \"})(\\\\d)(\\\\d{2})(.*)\" )\n\t\tvar type=currentHash.substr(0,1);\n\t\tvar msn=currentHash.substr(1,2);\n\t\tvar nextStart = 3;\n\t\tvar tokenParent=currentHash.substr(nextStart,smash._securityTokenLength);\n\t\tnextStart += smash._securityTokenLength;\n\t\tvar tokenChild=currentHash.substr(nextStart,smash._securityTokenLength);\n\t\tnextStart += smash._securityTokenLength;\n\t\tvar ack=currentHash.substr(nextStart,1);\n\t\tnextStart += 1;\n\t\tvar ackMsn=currentHash.substr(nextStart,2);\n\t\tnextStart += 2;\n\t\t// The payload needs to stay raw since the uri decoding needs to happen on the concatenated data in case of a large message\n\t\tvar payload=currentHash.substr(nextStart);\n\t\tlog( \"In : Type: \" + type + \" msn: \" + msn + \" tokenParent: \" + tokenParent + \" tokenChild: \" + tokenChild + \" ack: \" + ack + \" msn: \" + ackMsn + \" payload: \" + payload );\n\t\tmessageIn={type: type, msn: msn, tokenParent: tokenParent, tokenChild: tokenChild, ack: ack, ackMsn: ackMsn, payload: payload};\n\t\treturn true;\n\t}",
"isTokenExpired(token){\n try {\n const decoded = decode(token);\n return (decoded.exp < Date.now() / 1000);\n } catch (err) {\n console.log(\"expired check failed!\");\n return true;\n }\n }",
"getByToken(){\n return http.get(\"/Employee/token/\" + localStorage.getItem('login').toString().split(\"Bearer \")[1]);\n }",
"function validateToken(req, res) {\r\n var token = getToken(req);\r\n var user = users.getUserByToken(token);\r\n var isValidToken = user != undefined && user != '';\r\n console.log('[validToken] req=' + req.url);\r\n console.log('[validToken] Is Valid Token=%s User=%s', isValidToken, user);\r\n if (!isValidToken) {\r\n invalidToken(req, res);\r\n }\r\n return token;\r\n}",
"function getToken() {\n return localStorage.getItem('token');\n}",
"function tokenResponseRouter( response ) {\n\n if ( response.ErrorCode === 2106 ) {\n\n handleExpired();\n\n } else if ( response.ErrorCode === 1 ) {\n\n handleValid( response.Response );\n\n } else {\n\n handleUnknown( response );\n\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset position, direction, speed, and new random rotation start point | reset(){
this.x=1280 + (Math.floor(Math.random()*10)+1)*75;//Start off screen and a multiple of 75 pixels apart, to give different start points
this.y=60 + (Math.floor(Math.random()*10)*44);//Space out in 44 pixel intervals (I can't remember what fraction of the screen height this is)
this.direction=Math.floor(Math.random()*10);//Rotation direction (even clockwise/uneven anti-clockwise)
this.speed=Math.floor(Math.random()*4)+1;//Random speed between 1 and 4 pixels/frame
this.degrees=Math.floor(Math.random()*360);//Random rotation start point
} | [
"resetPosition(){\n this.speed = 0;\n this.deltaT = 0;\n this.rotation = 0;\n this.position[0] = this.startingPos[0];\n this.position[1] = this.startingPos[1];\n this.position[2] = this.startingPos[2];\n }",
"reset(){\n this.setSpeed();\n this.setStartPosition();\n }",
"reset() {\n this.seed = this._seed\n }",
"function resetFunction(){\n\tplayer.setPosition(...map.spawn_pos)\n\tcamera.position.z = 20;\n\tcamera.position.y = 20;\n\tcamera.position.x = 0;\n}",
"changeSpeed() {\r\n this.speed = Math.random() * 3 + 1.5;\r\n }",
"resetTimer() {\n this.timer = 0;\n this.spawnDelay = GageLib.math.getRandom(\n this.spawnRate.value[0],\n this.spawnRate.value[1]\n );\n }",
"function angleReset() {\n\tturnWheelTo(50); // 50 is the middle angle of the G27 wheel. \n\tglobal.turnCounter = 0;\n}",
"function moveArmToInitialPosition(){\n var servoIndex = 0;\n var moveFunc = function(err, script){\n\tservoIndex++;\n\tif(servoIndex < servoCount)\n\t setServo(servoIndex, 1.5).on(python_close, moveFunc);\n }\n\n setServo(servoIndex, 1.5).on(python_close, moveFunc);\n}",
"toggleRandomEyeMovement() {\n\t\t\tif (state.idleEyeMovement) {\n\t\t\t\tclearInterval(state.idleEyeMovement);\n\t\t\t\tstate.idleEyeMovement = false;\n\t\t\t} else {\n\t\t\t\tconst possibleDirections = ['up', 'down', 'left', 'right'];\n\n\t\t\t\tstate.idleEyeMovement = setInterval(() => {\n\t\t\t\t\tstate.drawingDirection = possibleDirections[random(0, 3)]; // !!! attention to default random function\n\t\t\t\t}, random(2000, 5000));\n\t\t\t}\n\t\t}",
"init(){\n this.speedX=0;\n this.speedY=-this.maxSpeed;\n this.speedZ=0;\n\n // these two components are used to know speed in the new coordinates after a rotation\n this.speedXAfterRotate=0;\n this.speedZAfterRotate=0;\n\n let now = (new Date).getTime();\n this.lastUpdate=now;\n }",
"startRandomAnimation() {\n this.clearPrevious();\n try {\n let n = this.getN();\n let parameterObject = this.generateParameter(n);\n this.startAnimation(parameterObject);\n } catch (e) {\n\n }\n }",
"resetTranslationRotation() {\n _wl_object_reset_translation_rotation(this.objectId);\n }",
"function setup () {\n createCanvas(500, 500);\n rectY = random(height - rectHeight);\n speed = random(1 , 3);\n}",
"function BardRandom__reset__Real( local__state )\n{\n this.p_state = local__state;\n}",
"function rotateTiles() {\n\t\tfor(var i = 0; i < tiles.length; i++){\n\t\t\tvar rotation = Math.random() * 360;\n\t\t\ttiles[i].setRotation(rotation);\n\t\t}\n\t}",
"startRotation() {\n this._options.rotation.enable = true;\n }",
"ghostChangeDirection() {\n let direction = random(4);\n switch(int(direction)) {\n case 0:\n this.currentDirection = \"up\";\n break;\n case 1:\n this.currentDirection = \"down\";\n break;\n case 2:\n this.currentDirection = \"left\";\n break;\n case 3:\n this.currentDirection = \"right\";\n break;\n }\n }",
"start() {\n // if the ball does not move, we can give it speed\n if (this.ball.vel.x === 0 && this.ball.vel.y === 0) {\n\n // Math.random() will set different directions for the ball to take when game starts \n this.ball.vel.x = 300 * (Math.random() > .5 ? 1 : -1); // ball's velocity at x (numbers represents speed)\n this.ball.vel.y = 300 * (Math.random() * 2 - 1); // ball's velocity at y (numbers represent speed)\n this.ball.vel.len = 200; // the ball will have a consistent speed\n }\n }",
"function randomLocatePacman(){\n\tif (shape.i != undefined && shape.j != undefined){\n\t\tboard[shape.i][shape.j] = 0;\n\t}\n\n\tlet pacmanCell = findRandomEmptyCell(board);\n\tboard[pacmanCell[0]][pacmanCell[1]] = 2;\n\tshape.i = pacmanCell[0];\n\tshape.j = pacmanCell[1];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
e.g. , , vfor, or when the children is provided by user with handwritten render functions / JSX. In such cases a full normalization is needed to cater to all possible types of children values. | function normalizeChildren(children){return isPrimitive(children)?[createTextVNode(children)]:Array.isArray(children)?normalizeArrayChildren(children):undefined;} | [
"render() {\n return Children.only(this.props.children);\n }",
"function mountChildren(children, parentDOM, parentElement) {\n if (children && typeof children.map === 'function') {\n children.map(function (child) {\n if (child && child.props) {\n child.props.parent = getDetailsForChild(parentElement);\n var childComponent = instantiateUrdxComponent(child);\n return childComponent.mountComponent(parentDOM);\n }\n });\n }\n\n return parentDOM;\n}",
"getChildrenProps() {\n const { children } = this.props;\n const targetNode = this.getPositionTarget();\n const childrenProps = { children };\n const childrenParams = {\n targetNode,\n visible: this.getVisible(),\n };\n if (typeof children === 'function') {\n return {\n children: children(childrenParams),\n };\n }\n if (children === undefined && targetNode) {\n const tooltip = targetNode.getAttribute('data-tooltip');\n if (tooltip != null) {\n return {\n dangerouslySetInnerHTML: {\n __html: tooltip,\n },\n };\n }\n }\n return childrenProps;\n }",
"outChildComponents() {\n if(Array.isArray(this.props.loopedComponents)) {\n this.props.loopedComponents.forEach((component) => {\n if(Array.isArray(component.renderedComponents)) {\n Array.from(component.renderedComponents).forEach(comp => {\n comp.out();\n })\n component.renderedComponents = [];\n }\n })\n }\n if(typeof this.childsObj == \"object\") {\n Object.values(this.childsObj).map((component) => {\n component.out();\n })\n }\n }",
"visitUnpivot_in_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function handle_children( parent, children ) {\n\n\t\t\tvar mat, dst, pos, rot, scl, quat;\n\n\t\t\tfor ( var objID in children ) {\n\n\t\t\t\t// check by id if child has already been handled,\n\t\t\t\t// if not, create new object\n\n\t\t\t\tvar object = result.objects[ objID ];\n\t\t\t\tvar objJSON = children[ objID ];\n\n\t\t\t\tif ( object === undefined ) {\n\n\t\t\t\t\t// meshes\n\n\t\t\t\t\tif ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {\n\n\t\t\t\t\t\tif ( objJSON.loading === undefined ) {\n\n\t\t\t\t\t\t\tvar reservedTypes = {\n\t\t\t\t\t\t\t\t\"type\": 1, \"url\": 1, \"material\": 1,\n\t\t\t\t\t\t\t\t\"position\": 1, \"rotation\": 1, \"scale\" : 1,\n\t\t\t\t\t\t\t\t\"visible\": 1, \"children\": 1, \"userData\": 1,\n\t\t\t\t\t\t\t\t\"skin\": 1, \"morph\": 1, \"mirroredLoop\": 1, \"duration\": 1\n\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\tvar loaderParameters = {};\n\n\t\t\t\t\t\t\tfor ( var parType in objJSON ) {\n\n\t\t\t\t\t\t\t\tif ( ! ( parType in reservedTypes ) ) {\n\n\t\t\t\t\t\t\t\t\tloaderParameters[ parType ] = objJSON[ parType ];\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmaterial = result.materials[ objJSON.material ];\n\n\t\t\t\t\t\t\tobjJSON.loading = true;\n\n\t\t\t\t\t\t\tvar loader = scope.hierarchyHandlers[ objJSON.type ][ \"loaderObject\" ];\n\n\t\t\t\t\t\t\t// ColladaLoader\n\n\t\t\t\t\t\t\tif ( loader.options ) {\n\n\t\t\t\t\t\t\t\tloader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );\n\n\t\t\t\t\t\t\t// UTF8Loader\n\t\t\t\t\t\t\t// OBJLoader\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tloader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else if ( objJSON.geometry !== undefined ) {\n\n\t\t\t\t\t\tgeometry = result.geometries[ objJSON.geometry ];\n\n\t\t\t\t\t\t// geometry already loaded\n\n\t\t\t\t\t\tif ( geometry ) {\n\n\t\t\t\t\t\t\tvar needsTangents = false;\n\n\t\t\t\t\t\t\tmaterial = result.materials[ objJSON.material ];\n\t\t\t\t\t\t\tneedsTangents = material instanceof THREE.ShaderMaterial;\n\n\t\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\t\t\tscl = objJSON.scale;\n\t\t\t\t\t\t\tmat = objJSON.matrix;\n\t\t\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\t\t\t// use materials from the model file\n\t\t\t\t\t\t\t// if there is no material specified in the object\n\n\t\t\t\t\t\t\tif ( ! objJSON.material ) {\n\n\t\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// use materials from the model file\n\t\t\t\t\t\t\t// if there is just empty face material\n\t\t\t\t\t\t\t// (must create new material as each model has its own face material)\n\n\t\t\t\t\t\t\tif ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {\n\n\t\t\t\t\t\t\t\tmaterial = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( material instanceof THREE.MeshFaceMaterial ) {\n\n\t\t\t\t\t\t\t\tfor ( var i = 0; i < material.materials.length; i ++ ) {\n\n\t\t\t\t\t\t\t\t\tneedsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( needsTangents ) {\n\n\t\t\t\t\t\t\t\tgeometry.computeTangents();\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ( objJSON.skin ) {\n\n\t\t\t\t\t\t\t\tobject = new THREE.SkinnedMesh( geometry, material );\n\n\t\t\t\t\t\t\t} else if ( objJSON.morph ) {\n\n\t\t\t\t\t\t\t\tobject = new THREE.MorphAnimMesh( geometry, material );\n\n\t\t\t\t\t\t\t\tif ( objJSON.duration !== undefined ) {\n\n\t\t\t\t\t\t\t\t\tobject.duration = objJSON.duration;\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif ( objJSON.time !== undefined ) {\n\n\t\t\t\t\t\t\t\t\tobject.time = objJSON.time;\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif ( objJSON.mirroredLoop !== undefined ) {\n\n\t\t\t\t\t\t\t\t\tobject.mirroredLoop = objJSON.mirroredLoop;\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif ( material.morphNormals ) {\n\n\t\t\t\t\t\t\t\t\tgeometry.computeMorphNormals();\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tobject = new THREE.Mesh( geometry, material );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tobject.name = objID;\n\n\t\t\t\t\t\t\tif ( mat ) {\n\n\t\t\t\t\t\t\t\tobject.matrixAutoUpdate = false;\n\t\t\t\t\t\t\t\tobject.matrix.set(\n\t\t\t\t\t\t\t\t\tmat[0], mat[1], mat[2], mat[3],\n\t\t\t\t\t\t\t\t\tmat[4], mat[5], mat[6], mat[7],\n\t\t\t\t\t\t\t\t\tmat[8], mat[9], mat[10], mat[11],\n\t\t\t\t\t\t\t\t\tmat[12], mat[13], mat[14], mat[15]\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\tobject.position.fromArray( pos );\n\n\t\t\t\t\t\t\t\tif ( quat ) {\n\n\t\t\t\t\t\t\t\t\tobject.quaternion.fromArray( quat );\n\n\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\tobject.rotation.fromArray( rot );\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tobject.scale.fromArray( scl );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tobject.visible = objJSON.visible;\n\t\t\t\t\t\t\tobject.castShadow = objJSON.castShadow;\n\t\t\t\t\t\t\tobject.receiveShadow = objJSON.receiveShadow;\n\n\t\t\t\t\t\t\tparent.add( object );\n\n\t\t\t\t\t\t\tresult.objects[ objID ] = object;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t// lights\n\n\t\t\t\t\t} else if ( objJSON.type === \"DirectionalLight\" || objJSON.type === \"PointLight\" || objJSON.type === \"AmbientLight\" ) {\n\n\t\t\t\t\t\thex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;\n\t\t\t\t\t\tintensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;\n\n\t\t\t\t\t\tif ( objJSON.type === \"DirectionalLight\" ) {\n\n\t\t\t\t\t\t\tpos = objJSON.direction;\n\n\t\t\t\t\t\t\tlight = new THREE.DirectionalLight( hex, intensity );\n\t\t\t\t\t\t\tlight.position.fromArray( pos );\n\n\t\t\t\t\t\t\tif ( objJSON.target ) {\n\n\t\t\t\t\t\t\t\ttarget_array.push( { \"object\": light, \"targetName\" : objJSON.target } );\n\n\t\t\t\t\t\t\t\t// kill existing default target\n\t\t\t\t\t\t\t\t// otherwise it gets added to scene when parent gets added\n\n\t\t\t\t\t\t\t\tlight.target = null;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} else if ( objJSON.type === \"PointLight\" ) {\n\n\t\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\t\tdst = objJSON.distance;\n\n\t\t\t\t\t\t\tlight = new THREE.PointLight( hex, intensity, dst );\n\t\t\t\t\t\t\tlight.position.fromArray( pos );\n\n\t\t\t\t\t\t} else if ( objJSON.type === \"AmbientLight\" ) {\n\n\t\t\t\t\t\t\tlight = new THREE.AmbientLight( hex );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tparent.add( light );\n\n\t\t\t\t\t\tlight.name = objID;\n\t\t\t\t\t\tresult.lights[ objID ] = light;\n\t\t\t\t\t\tresult.objects[ objID ] = light;\n\n\t\t\t\t\t// cameras\n\n\t\t\t\t\t} else if ( objJSON.type === \"PerspectiveCamera\" || objJSON.type === \"OrthographicCamera\" ) {\n\n\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\t\tif ( objJSON.type === \"PerspectiveCamera\" ) {\n\n\t\t\t\t\t\t\tcamera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );\n\n\t\t\t\t\t\t} else if ( objJSON.type === \"OrthographicCamera\" ) {\n\n\t\t\t\t\t\t\tcamera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcamera.name = objID;\n\t\t\t\t\t\tcamera.position.fromArray( pos );\n\n\t\t\t\t\t\tif ( quat !== undefined ) {\n\n\t\t\t\t\t\t\tcamera.quaternion.fromArray( quat );\n\n\t\t\t\t\t\t} else if ( rot !== undefined ) {\n\n\t\t\t\t\t\t\tcamera.rotation.fromArray( rot );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tparent.add( camera );\n\n\t\t\t\t\t\tresult.cameras[ objID ] = camera;\n\t\t\t\t\t\tresult.objects[ objID ] = camera;\n\n\t\t\t\t\t// pure Object3D\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tpos = objJSON.position;\n\t\t\t\t\t\trot = objJSON.rotation;\n\t\t\t\t\t\tscl = objJSON.scale;\n\t\t\t\t\t\tquat = objJSON.quaternion;\n\n\t\t\t\t\t\tobject = new THREE.Object3D();\n\t\t\t\t\t\tobject.name = objID;\n\t\t\t\t\t\tobject.position.fromArray( pos );\n\n\t\t\t\t\t\tif ( quat ) {\n\n\t\t\t\t\t\t\tobject.quaternion.fromArray( quat );\n\n\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\tobject.rotation.fromArray( rot );\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tobject.scale.fromArray( scl );\n\t\t\t\t\t\tobject.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;\n\n\t\t\t\t\t\tparent.add( object );\n\n\t\t\t\t\t\tresult.objects[ objID ] = object;\n\t\t\t\t\t\tresult.empties[ objID ] = object;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( object ) {\n\n\t\t\t\t\t\tif ( objJSON.userData !== undefined ) {\n\n\t\t\t\t\t\t\tfor ( var key in objJSON.userData ) {\n\n\t\t\t\t\t\t\t\tvar value = objJSON.userData[ key ];\n\t\t\t\t\t\t\t\tobject.userData[ key ] = value;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ( objJSON.groups !== undefined ) {\n\n\t\t\t\t\t\t\tfor ( var i = 0; i < objJSON.groups.length; i ++ ) {\n\n\t\t\t\t\t\t\t\tvar groupID = objJSON.groups[ i ];\n\n\t\t\t\t\t\t\t\tif ( result.groups[ groupID ] === undefined ) {\n\n\t\t\t\t\t\t\t\t\tresult.groups[ groupID ] = [];\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tresult.groups[ groupID ].push( objID );\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif ( object !== undefined && objJSON.children !== undefined ) {\n\n\t\t\t\t\thandle_children( object, objJSON.children );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}",
"renderNumericValues() {\n const { mean, stdDev } = this.props.data.stats;\n const barChartData = this.props.data.values;\n return (\n <div className=\"p-2\">\n {this.renderTitle()}\n {this.renderBarChart(barChartData)}\n {this.renderLabel('Mean', `${formatValue(mean)} ± ${formatValue(stdDev)}`)}\n </div>\n );\n }",
"canRenderChild(parentConfig: NodeConfig, childConfig: NodeConfig): boolean {\n if (!parentConfig.tagName || !childConfig.tagName) {\n return false;\n }\n\n // Valid children\n if (\n parentConfig.children &&\n parentConfig.children.length > 0 &&\n parentConfig.children.indexOf(childConfig.tagName) === -1\n ) {\n return false;\n }\n\n // Valid parent\n if (\n childConfig.parent &&\n childConfig.parent.length > 0 &&\n childConfig.parent.indexOf(parentConfig.tagName) === -1\n ) {\n return false;\n }\n\n // Self nesting\n if (!parentConfig.self && parentConfig.tagName === childConfig.tagName) {\n return false;\n }\n\n // Block\n if (!parentConfig.block && childConfig.type === TYPE_BLOCK) {\n return false;\n }\n\n // Inline\n if (!parentConfig.inline && childConfig.type === TYPE_INLINE) {\n return false;\n }\n\n return true;\n }",
"normalize(normalizations) {\n if (this.normalizations) {\n this.denormalize();\n }\n this.normalizations = normalizations;\n this.values = this.values.map((value, index) => {\n if (this.normalizations[index]) {\n return this.normalizations[index].normalize(value);\n }\n else {\n //new normalization is undefined for this index, so dont apply any transformation.\n return value;\n }\n });\n return this;\n }",
"function normalizer(rawData) {\n var rawMenu = get_1.default(rawData, 'data.categoryList', [])\n .filter(function (menu) { return get_1.default(menu, 'level') === 1; })[0];\n var children = get_1.default(rawMenu, 'children', []);\n var menu = normalizeItems(children);\n return menu;\n}",
"visitColumn_or_attribute(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"toText() {\n // To avoid this, we would subclass documentFragment separately for\n // MathML, but polyfills for subclassing is expensive per PR 1469.\n // $FlowFixMe: Only works for ChildType = MathDomNode.\n const toText = child => child.toText();\n\n return this.children.map(toText).join(\"\");\n }",
"function removeOrphanedChildren(children, unmountOnly) {\n\tfor (var i = children.length; i--;) {\n\t\tif (children[i]) {\n\t\t\trecollectNodeTree(children[i], unmountOnly);\n\t\t}\n\t}\n}",
"adjustChildrenHorizontally() {\n this.adjustChildHorizontally();\n }",
"function recursivelyMapChildren(children, callback) {\n return React.Children.toArray(children).map((child, index) => {\n if (!React.isValidElement(child)) return child\n child = callback(child, child.key || index)\n if (child.props.children) {\n const newKids = recursivelyMapChildren(child.props.children, callback)\n if (newKids !== child.props.children)\n child = React.cloneElement(child, { key: child.key || index, children: newKids })\n }\n return child\n })\n}",
"render() {\n return (\n <div>\n <Child onChange={this.changeName} /> <!-- 2. The stateful component passes that function down to a stateless component. -->\n <Sibling name={this.state.name} /> <!-- 5. The stateful component class passes down its state, distinct from the ability to \n change its state, to a different stateless component. -->\n </div>\n );\n }",
"visitRespect_or_ignore_nulls(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function ColumnLayout({\n mobileSize,\n tabletSize,\n desktopSize,\n children\n}) {\n\n let errorJsx = [];\n if (mobileSize === undefined && tabletSize === undefined && desktopSize === undefined) {\n throw new Error(\"Please set at least one of mobileSize, tableSize, and desktopSize\");\n }\n\n let columnClass = \"ColumnLayout\";\n if (desktopSize !== undefined) {\n if (desktopSize === 0) {\n columnClass += \" col-desktop-hidden\";\n }\n else {\n columnClass += \" col-desktop-\" + desktopSize;\n }\n }\n\n if (tabletSize !== undefined) {\n if (tabletSize === 0) {\n columnClass += \" col-tablet-hidden\";\n }\n else {\n columnClass += \" col-tablet-\" + tabletSize;\n }\n }\n\n if (mobileSize !== undefined) {\n if (mobileSize === 0) {\n columnClass += \" col-mobile-hidden\";\n }\n else {\n columnClass += \" col-mobile-\" + mobileSize;\n }\n }\n\n return (\n <div className={columnClass}>\n {errorJsx}\n {children}\n </div>\n );\n}",
"notValid(child, c) {\n return (\n (child.type === \"video\" && !this.isSupportedVideoType(child.video?.external?.url))\n || (child.type === \"image\" && this.isFile(child.image))\n || (child.type === \"column_list\" && c.length < 2));\n }",
"function summarizeChildren(datum) {\n function _summarize(datum) {\n var descendantValues = datum.values.reduce((acc, cur) => {\n cur.parent = datum;\n return acc.concat(cur.values ? _summarize(cur) : cur.value);\n }, []);\n var pValues = returnPValues(datum);\n\n function returnPValues(datum) {\n // var _datumValues = datum.values.slice();\n // there's a problem here: dividing by zero when the first value is zero, or all are zero\n // take a slice() copy of datum.values to avoid mutating datum and shift of the first value\n // so long as it's value === 0. in effect, measure pValue against the first nonzero value\n // in the series\n while ( datum.values.length > 0 && datum.values[0].value === 0 ){\n datum.values.shift();\n }\n return datum.values.reduce((acc, cur) => {\n var min = d3.min([acc[0], cur.values ? returnPValues(cur)[0] : (cur.value - datum.values[0].value) / datum.values[0].value]);\n var max = d3.max([acc[1], cur.values ? returnPValues(cur)[1] : (cur.value - datum.values[0].value) / datum.values[0].value]);\n return [min, max];\n }, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);\n }\n datum.descendantValues = descendantValues;\n datum.max = d3.max(descendantValues);\n datum.min = d3.min(descendantValues);\n datum.mean = d3.mean(descendantValues);\n datum.median = d3.median(descendantValues);\n datum.variance = d3.variance(descendantValues);\n datum.deviation = d3.deviation(descendantValues);\n datum.maxZ = d3.max(descendantValues, d => (d - datum.mean) / datum.deviation); // z-score\n datum.minZ = d3.min(descendantValues, d => (d - datum.mean) / datum.deviation); // z-score \n datum.minP = pValues[0]; // percentage values. min/max value as expressed as a percentage of the first data point (year 0).\n datum.maxP = pValues[1]; // percentage values. min/max value as expressed as a percentage of the first data point (year 0).\n\n return descendantValues;\n\n }\n _summarize(datum);\n return datum;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hideNoTaskHeader method looks for pending task count and hide/shows header based on that | function hideNoTaskHeader(){
if(!pendingTaskCount){
$('.pending-task-view .task-left').removeClass('hide');
} else{
$('.pending-task-view .task-left').addClass('hide');
}
} | [
"function checkIfnoTasks(){\n let noListItemsMessage = document.getElementById(\"no-tasks-msg\");\n noListItemsMessage.style.display = (tasks === 0) ? \"block\" : \"none\";\n}",
"function tasksZero() {\n let noTasksMsg = document.createElement('span');\n noTasksMsg.className = \"no-tasks-message\";\n let taskText = document.createTextNode('No Tasks To Show');\n noTasksMsg.appendChild(taskText);\n tasksContent.appendChild(noTasksMsg);\n }",
"hideUnusedToggleAndCount() {\n const toggle = this.cnt.querySelectorAll(\".files-tree-toggle\");\n\n toggle.forEach(toggle => {\n const ul = toggle.parentElement.nextElementSibling;\n const checkbox = ul.querySelector(`input[type=\"checkbox\"]`);\n\n if (checkbox === null) {\n if (this.options.showCount) {\n const count = toggle.nextElementSibling.querySelector('.files-tree-count');\n count.remove();\n }\n\n const span1 = document.createElement(\"span\");\n span1.classList.add(\"files-tree-toggle-empty\");\n toggle.parentElement.insertBefore(span1, toggle);\n toggle.remove();\n }\n })\n }",
"function HideProgressStatus(should_hide)\n{\n var progress_bar = GetProgressBar();\n var div_progress = GetDivProgress();\n if (div_progress && progress_bar)\n {\n if (should_hide == true)\n {\n div_progress.style.visibility = \"hidden\";\n div_progress.style.zIndex = \"-999\";\n g_status_text.splice(0, g_status_text.length);\n g_status_timer.splice(0, g_status_timer.length);\n progress_bar.value = -1;\n UpdateTextStatus(1.0);\n }\n else\n {\n div_progress.style.visibility = \"visible\";\n div_progress.style.zIndex = \"999\";\n progress_bar.value = -1;\n AddTextStatus('Please wait for module loading');\n UpdateTextStatus(1.0);\n }\n }\n}",
"function removeCompletedTasks() {\n let completedIds = [];\n for (let node of currentTaskHTML.childNodes) {\n if (node.completed) {\n completedIds.push(node.task.id);\n node.hide();\n setTimeout(() => {\n currentTaskHTML.removeChild(node);\n }, 200);\n \n }\n }\n\n for (let node of taskListHTML.childNodes) {\n if (node.completed) {\n completedIds.push(node.task.id);\n node.hide();\n setTimeout(() => {\n taskListHTML.removeChild(node);\n }, 200);\n \n }\n }\n completedIds.forEach((id) => {\n currentPomoSession.completeTask(id);\n });\n storePomoSession(currentPomoSession);\n\n }",
"function showHideCompleted(button) {\n\t\tif (showCompleted) {\n\t\t\tshowCompleted = false;\n\t\t\tbutton.innerText = 'Show completed items';\t\n\t\t} else {\n\t\t\tshowCompleted = true;\n\t\t\tbutton.innerText = 'Hide completed items';\n\t\t}\n\t\twriteList();\n\t\tevent.preventDefault();\n\t}",
"function show_task () {\n\tdocument.getElementById('inp-task').value='';\t\n\thtml = \"\";\n\thtml+= \"<table id='table-design'> <tr> <th>Sr-No </th> <th>Done/panding </th><th>Task-Name</th> <th>Edited Content</th><th>Action</th>\";\n\tfor (var i=0; i<arr_for_task.length; i++) {\n\thtml+=\"<tr> <td>\"+(i+1)+\"</td><td><input type='checkbox' id='doneorpanding(\"+i+\")' onclick='donePend(\"+i+\")'></td><td>\"+arr_for_task[i]+\"</td><td><input type='text' id='edit-content(\"+i+\")' class = 'edit-content'></td><td> <a href='#' onclick='delet(\"+i+\")'> DELETE</a> <a href='#'onclick='edit(\"+i+\")' id='edit'> EDIT</a> </td></tr>\";\n\t}\n\thtml+=\"</table>\";\n\tdocument.getElementById('entered_task').innerHTML = html;\n\tdiv_heading = \"\";\n\tdiv_heading+= \"<div id='head-design' class='head-design' style='padding: 10px;text-align: center;background-color: gray;font-size: 30px;color: white;'> The pending Task are showing Below -------!! </div>\";\n\tdocument.getElementById('head-design').innerHTML=div_heading ;\n}",
"function tasklistFadeOutResultText(){\n \n $( \"#tableWrapper\" ).animate({\n opacity: 1\n }, 1000, function() {\n if (!tasksFetched)\n tasklistFadeInResultText();\n });\n}",
"function sortTasks() {\n var sheet = SpreadsheetApp.getActiveSheet();\n var data = sheet.getDataRange().getValues();\n var totalRowCount = data.length;\n\n var toDoTasks = [];\n var backlogTasks = [];\n var doneTasks = [];\n\n var headerRowSheetIndex = 1;\n for (var i = 0; i < data.length; i++) {\n if (data[i][0] != '' && data[i][0] == PRIORITY_HEADER) {\n headerRowSheetIndex = i + 1;\n break;\n }\n }\n\n for (var i = headerRowSheetIndex + 1; i < data.length; i++) {\n row = data[i];\n key = row[0];\n if ((typeof key == \"string\" && isBacklogIndicator(key))\n || (key == '' && (row[1] != '' || row[2] != ''))) {\n row[0] = FORMATTED_BACKLOG_INDICATOR;\n backlogTasks.push(row);\n } else if (typeof key == \"string\" && isDoneIndicator(key)) {\n row[0] = FORMATTED_DONE_INDICATOR;\n doneTasks.push(row);\n } else if (isNumber(row[0])) {\n toDoTasks.push(row);\n }\n }\n\n // Sort task row numerically, and move empty columns last\n toDoTasks.sort(function(inp1, inp2) {\n if (inp1[0] == '') {\n return 1;\n } else if (inp2[0] == '') {\n return -1;\n }\n return inp1[0] - inp2[0];\n });\n\n // Write to do tasks\n toDoRow = sheet.getRange(headerRowSheetIndex + 1, 1, 1, 3);\n clearRange(toDoRow);\n toDoRow.setBackground(SECTION_HEADER_COLOR);\n toDoCell = sheet.getRange(headerRowSheetIndex + 1, 1);\n toDoCell.setFontWeight(\"bold\");\n toDoCell.setValue(\"To Do\");\n\n var currentRowCounter = headerRowSheetIndex + 2;\n var oddCounter = 0;\n for (var i = 0; i < toDoTasks.length; i++) {\n var priority = toDoTasks[i][0];\n var task = toDoTasks[i][1];\n var note = toDoTasks[i][2];\n\n // Only write the row if there is a priority or task.\n if (priority != '' || task != '') {\n var row = sheet.getRange(i + currentRowCounter, 1, 1, 3);\n clearRange(row);\n sheet.getRange(i + currentRowCounter, 2, 1, 2).setWrap(true);\n if (oddCounter % 2 == 1) {\n row.setBackground(OFF_CELL_COLOR);\n }\n\n row.setValues([[ALLOW_ARBITRARY_PRIORITIES ? priority : i + 1, task, note]]);\n\n }\n oddCounter += 1;\n }\n\n currentRowCounter += toDoTasks.length;\n clearRange(sheet.getRange(currentRowCounter, 1, 1, 3));\n currentRowCounter += 1;\n\n // Write backlog tasks\n backlogRow = sheet.getRange(currentRowCounter, 1, 1, 3);\n clearRange(backlogRow);\n backlogRow.setBackground(SECTION_HEADER_COLOR);\n backlogCell = sheet.getRange(currentRowCounter, 1);\n backlogCell.setFontWeight(\"bold\");\n backlogCell.setValue(\"Backlog\");\n\n currentRowCounter += 1;\n oddCounter = 0;\n for (var i = 0; i < backlogTasks.length; i++) {\n var backlog_marker = backlogTasks[i][0];\n var task = backlogTasks[i][1];\n var note = backlogTasks[i][2];\n\n if (priority != '' || task != '') {\n var row = sheet.getRange(i + currentRowCounter, 1, 1, 3);\n clearRange(row);\n\n sheet.getRange(i + currentRowCounter, 2, 1, 2).setWrap(true);\n if (oddCounter % 2 == 1) {\n row.setBackground(OFF_CELL_COLOR);\n }\n\n row.setValues([[backlog_marker, task, note]]);\n }\n oddCounter += 1;\n }\n\n currentRowCounter += backlogTasks.length;\n clearRange(sheet.getRange(currentRowCounter, 1, BUFFER_SPACE, 3));\n currentRowCounter += BUFFER_SPACE;\n\n // Write done tasks\n doneRow = sheet.getRange(currentRowCounter, 1, 1, 3);\n clearRange(doneRow);\n doneRow.setBackground(SECTION_HEADER_COLOR);\n doneCell = sheet.getRange(currentRowCounter, 1);\n doneCell.setFontWeight(\"bold\");\n doneCell.setValue(\"Done\");\n\n currentRowCounter += 1 ;\n oddCounter = 0;\n for (var i = 0; i < doneTasks.length; i++) {\n var done_marker = doneTasks[i][0];\n var task = doneTasks[i][1];\n var note = doneTasks[i][2];\n\n if (priority != '' || task != '') {\n var row = sheet.getRange(i + currentRowCounter, 1, 1, 3);\n clearRange(row);\n\n sheet.getRange(i + currentRowCounter, 2, 1, 2).setFontLine('line-through');\n sheet.getRange(i + currentRowCounter, 2, 1, 2).setWrap(true);\n if (oddCounter % 2 == 1) {\n row.setBackground(OFF_CELL_COLOR);\n }\n\n row.setValues([[done_marker, task, note]]);\n }\n oddCounter += 1;\n }\n\n currentRowCounter += doneTasks.length;\n\n // Delete any leftover rows\n if (currentRowCounter <= totalRowCount) {\n clearRange(sheet.getRange(currentRowCounter, 1, totalRowCount - currentRowCounter + 1, 3));\n }\n}",
"function displayFocusContent() {\n // Set the current main task\n let currMainTask = JSON.parse(window.localStorage.getItem(\"tasks\")).mainTask;\n let rightHeader = document.getElementById(\"rightSideHeader\");\n let focusTask = document.getElementById(\"focusTask\");\n let settingsDiv = document.getElementById(\"settingsContainer\");\n let taskListDiv = document.getElementById(\"taskListContainer\");\n let navIconContainer = document.getElementById(\"navIconContainer\");\n let areYouSureOptions = document.getElementById(\"areYouSureOptions\");\n\n if (currMainTask.name == null) {\n document.getElementById(\"focusTask\").textContent = \"No focus task selected\";\n } else {\n document.getElementById(\"focusTask\").textContent = currMainTask.name;\n }\n\n rightHeader.innerText = \"FOCUS\";\n focusTask.style.display = \"block\";\n settingsDiv.style.display = \"none\";\n taskListDiv.style.display = \"none\";\n navIconContainer.style.display = \"none\";\n areYouSureOptions.style.display = \"none\";\n}",
"function hideEmptyCells() {\n // get all the td elements\n jQuery('td.' + kradVariables.GRID_LAYOUT_CELL_CLASS).each(function () {\n // check if the children is hidden (progressive) or if there is no content(render=false)\n var cellEmpty = jQuery(this).children().is(\".uif-placeholder\") || jQuery(this).is(\":empty\");\n\n // hide the header only if the cell and the header is empty\n if (cellEmpty) {\n var hd = jQuery(this).siblings(\"th\");\n\n var headerEmpty = jQuery(hd).children().is(\":hidden\") || jQuery(hd).is(\":empty\");\n if (headerEmpty) {\n hd.hide();\n }\n\n // hide the cell\n jQuery(this).hide();\n }\n });\n}",
"function showTaskbar() {\n document.getElementById('bottomBar').style.display = 'block';\n setTimeout(function () {\n if (menu.style.display === 'block' || infoPanel.style.display === 'block' || appList.style.display === 'block' || ncPanel.style.display === 'block') {\n showTaskbar();\n } else {\n document.getElementById('bottomBar').style.display = 'none';\n }\n }, 6000);\n}",
"function toggleCompletedVisibility(element) {\n var lotRows = document.getElementsByClassName('lot-quantity-zero');\n\n if (element.textContent === ' Hide Completed Rows') {\n element.innerHTML = \"<i class=\\\"far fa-eye\\\"></i> Show Completed Rows\"\n for (var i = 0; i < lotRows.length; i++) {\n lotRows[i].classList.add('d-none');\n }\n } else {\n element.innerHTML = \"<i class=\\\"far fa-eye-slash\\\"></i> Hide Completed Rows\"\n for (var i = 0; i < lotRows.length; i++) {\n lotRows[i].classList.remove('d-none');\n }\n }\n}",
"function removeCompleted(n){\n //get id of task element(input) from parent elements\n taskElement = n.parentElement.parentElement.parentElement;\n taskId = taskElement.childNodes[0].id;\n //find task instance using the array and the id(index)\n curr = Task.ALLTASKS[taskId]; \n curr.complete();\n taskElement.style.display = 'none';\n addCompletedToDisplay() \n drawPercentage();\n updateReward();\n}",
"function confirmHide() {\n document.getElementById(\"hideWarning\").style.display = \"none\";\n data[accountGlobal.id].status = 0;\n restartUI();\n changeStory(accountGlobal.id + 1, 1);\n}",
"function showChannelCreateDoneDisplay() {\n const inProgress = document.getElementById('channel-publish-in-progress');\n inProgress.hidden=true;\n const done = document.getElementById('channel-publish-done');\n done.hidden = false;\n}",
"function hideProcessing(){\n vm.processing = false;\n }",
"function hideAll() {\n for(let bio in allBios) {\n if(!allBios[bio].hasClass('hidden-heading')) {\n allBios[bio].addClass('hidden-heading');\n }\n }\n }",
"load_tasks() {\n this.create_header();\n this.clear_tasks();\n this.get_tasks();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set navigation dots to an active state as the user scrolls | function redrawDotNav() {
var scrollPosition = $(document).scrollTop();
$('nav#primary a').removeClass('active');
$('#main-nav li').removeClass('current_page_item');
if (scrollPosition < (section2Top - menuBarHeight)) {
$('nav#primary a.main').addClass('active');
$('#main-nav li.menu-item-main').addClass('current_page_item');
} else if (scrollPosition >= section2Top - menuBarHeight && scrollPosition < section3Top) {
$('nav#primary a.experience').addClass('active');
$('#main-nav li.menu-item-experience').addClass('current_page_item');
} else if (scrollPosition >= section3Top && scrollPosition < section4Top) {
$('nav#primary a.skills').addClass('active');
$('#main-nav li.menu-item-skills').addClass('current_page_item');
} else if (scrollPosition >= section4Top && scrollPosition < section5Top) {
$('nav#primary a.training').addClass('active');
$('#main-nav li.menu-item-training').addClass('current_page_item');
} else if (scrollPosition >= section5Top && scrollPosition < section6Top) {
$('nav#primary a.languages').addClass('active');
$('#main-nav li.menu-item-languages').addClass('current_page_item');
} else if (scrollPosition >= section6Top) {
$('nav#primary a.contact').addClass('active');
$('#main-nav li.menu-item-contact').addClass('current_page_item');
}
} | [
"function activateNavDots(name,sectionIndex){if(options.navigation&&$(SECTION_NAV_SEL)[0]!=null){removeClass($(ACTIVE_SEL,$(SECTION_NAV_SEL)[0]),ACTIVE);if(name){addClass($('a[href=\"#'+name+'\"]',$(SECTION_NAV_SEL)[0]),ACTIVE);}else{addClass($('a',$('li',$(SECTION_NAV_SEL)[0])[sectionIndex]),ACTIVE);}}}",
"function setCurrentDotActive($dot) {\n $sliderDots.removeClass('active');\n $dot.addClass('slider-dot active');\n}",
"function changeActiveMenuItemOnScroll() {\r\n\t\tvar scrollPos = $(document).scrollTop();\r\n\t\t$('.header-menu-a').each(function () {\r\n\t\t\t\tvar $currLink = $(this);\r\n\t\t\t\tvar refElement = $($currLink.attr(\"href\"));\r\n\t\t\t\tif (refElement.position().top <= scrollPos && refElement.position().top + refElement.outerHeight(true) > scrollPos) {\r\n\t\t\t\t\t$('.header-menu-a').removeClass(\"header-menu-a_active\");\r\n\t\t\t\t\t$currLink.addClass(\"header-menu-a_active\");\r\n\r\n\t\t\t\t\tpaginationUnderlineTransition(\r\n\t\t\t\t\t\t$(\".header-menu-nav\"),\r\n\t\t\t\t\t\t\".header-pagination-underline\",\r\n\t\t\t\t\t\t$(\".header-menu-a_active\"),\r\n\t\t\t\t\t\t0.99\r\n\t\t\t\t\t);\r\n\r\n\t\t\t\t} else {\r\n\t\t\t\t\t$currLink.removeClass(\"header-menu-a_active\");\r\n\t\t\t\t}\r\n\t\t});\r\n\t}",
"function onScroll(event){\n var scrollPos = $(document).scrollTop();\n $('a.activeOnScroll').each(function () {\n var currLink = $(this);\n var refElement_id = $(this).attr(\"href\");\n var refElement = $(refElement_id);\n if ( (refElement.offset().top <= scrollPos ) && ( refElement.offset().top + refElement.height() > scrollPos ) ) {\n $('a.activeOnScroll').parent().removeClass(\"active\");\n currLink.parent().addClass(\"active\");\n }\n });\n}",
"function setActiveMenu() {\r\n var i;\r\n if (windowResized) {\r\n // reset after possible window resize\r\n scrollPositions = getScrollPositions();\r\n windowResized = false;\r\n }\r\n // Get top Window edge that is just under the Menu\r\n var topEdge = $(window).scrollTop() + menuHeight;\r\n // Special case: last section, don't switch black to\r\n // previous one immediatelly (avoid menu blinking).\r\n if (currentId == lastId && isThreshold(topEdge)) {\r\n return;\r\n }\r\n // explicitly set last section (as it has small height\r\n // and can't be selected otherwise inside a big window)\r\n else if (isPageEndReached(topEdge + $(window).height())) {\r\n setNewPosition(lastId);\r\n }\r\n // Going or scrolling down\r\n else if (topEdge > currentPosBottom) {\r\n for (i = currentId; i < scrollPositions.length; i++) {\r\n // we are looking for bottom edge here\r\n if (topEdge < getPosBottom(i)) {\r\n setNewPosition(i);\r\n return;\r\n }\r\n }\r\n }\r\n // Going up\r\n else if (topEdge < currentPosTop) {\r\n for (i = currentId; i >= 0; i--) {\r\n // is Window's top edge below this section's top?\r\n if (topEdge > scrollPositions[i]) {\r\n setNewPosition(i);\r\n return;\r\n }\r\n }\r\n }\r\n }",
"function whenScroll() {\n for (let section of sections) {\n if (isInViewport(section)) {\n removeActiveClassFromSection(); //remove 'active_section' class from the previous active section\n section.classList.add('active_section'); //add 'active_section' class to the current active section\n\n //update the corresponding navigation link\n removeActiveClassFromLink(); //remove 'active' class from the previous active section\n let correspondingLink = searchMenuByText(section.getAttribute('data-nav'));\n correspondingLink.classList.add('active'); //add 'active' class to the corresponding link\n break;\n }\n }\n}",
"function calculateAndDisplayPageNavigationDots() {\n var noPages = numberOfPages();\n \n $(\".ql-pagenav\").attr(\"pages\", noPages);\n\n // if page dot doesn't exist, add\n for (var i = 0; i < noPages; i++) {\n if (!$(`.pagedot[pg='${i+1}']`).length) { $(\".ql-pagenav\").append(`<button class=\"pagedot\" pg=\"${i + 1}\"></button>`); }\n }\n\n // remove extra dots (i.e. if user deletes some stuff, and there's less pages)\n var dotsCount = $(\".ql-pagenav\").children().length;\n var extraDots = $(\".ql-pagenav\").children().slice(noPages, dotsCount);\n extraDots.remove();\n \n $(\".ql-pagenav\").removeClass(\"compact tiny\");\n if (noPages > 30) {\n $(\".ql-pagenav\").addClass(\"compact\");\n }\n\n checkIfPageChanged();\n}",
"function onScroll() {\n var isNavBarVisible = window.pageYOffset >= showNavBarMinimum;\n if ( isNavBarVisible != wasNavBarVisible ) {\n $navBar.toggleClass('show');\n wasNavBarVisible = isNavBarVisible;\n }\n }",
"function checkIfPageChanged() {\n if (!isPaperMode()) { return; }\n \n var scrollLeftPX = document.getElementsByClassName(\"ql-editor\")[0].scrollLeft || 0;\n var scrollLeftMM = px2mm(scrollLeftPX);\n\n var visiblePageNo = scrollLeftMM / (paper.width + paper.opticalSeparator);\n visiblePageNo = parseFloat(visiblePageNo.toFixed(1));\n\n $(\".pagedot\").removeClass(\"active\");\n \n var currentPageIndex = Math.floor(visiblePageNo);\n $(\".pagedot\").eq(currentPageIndex).addClass(\"active\");\n \n if (visiblePageNo % 1) { \n // some parts of next page is visible too\n $(\".pagedot\").eq(currentPageIndex + 1).addClass(\"active\");\n }\n}",
"function setActiveBulletClass() {\n for (var i = 0; i < bullets.length; i++) {\n if (slides[i].style['transform'] == 'translateX(0px)') {\n bullets[i].classList.add('active');\n }\n }\n }",
"_carouselPointActiver() {\r\n const i = Math.ceil(this.currentSlide / this.slideItems);\r\n this.activePoint = i;\r\n this.cdr.markForCheck();\r\n }",
"function activeNavigation() {\n var locationUrl = window.location.href;\n var handlerAndAction = locationUrl\n .replace(/(.*\\/\\/vacation.+?\\/)(index.cfm\\/)?/i, '')\n .replace(/\\?.+/, '')\n .split('/');\n var currentHandler = handlerAndAction[0].toLowerCase();\n var currentAction = handlerAndAction[1] || 'index';\n var currentObjectId = handlerAndAction[2];\n\n $('[data-handler=\"' + currentHandler + '\"]').addClass('active');\n\n // breadcrumbs\n buildBradcrumbs(currentHandler, currentAction, currentObjectId);\n}",
"function navVertical(forward) {\n app.horizontalScroll = false; //allow enter button to execute procedures of the vertical indexes when pressed\n app.updateNavItems();\n // jump to tabIndex\n\n var next = app.currentNavId;\n\n\n next += forward ? 10 : -10;\n for (var i = 0; i < app.navItems.length; i++) {\n // if(current.location ==\"home.html\" && next > getNavTabIndex(app.navItems.length - 1)){ next=0;}\n if (getNavTabIndex(i) == next) {\n focusActiveButton(app.navItems[i]);\n // found = true;\n break;\n }\n }\n\n\n }",
"function setNavPosition(){\n let fixed = nav.classList.contains(\"fixed\")\n\n if(yOffset >= about.offsetTop && !fixed)\n {\n nav.classList.add(\"fixed\")\n }\n else if(yOffset < about.offsetTop && fixed)\n {\n nav.classList.remove(\"fixed\")\n }\n}",
"function setActivePage() {\n\t\t\tvar $carouselPage = $pager.find('.carousel-page');\n\t\t\t$carouselPage.each(function () {\n\t\t\t\t$(this).removeClass('current-page');\n\t\t\t\tif ($(this).index() == currentGroup) {\n\t\t\t\t\t$(this).addClass('current-page');\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function navAnimate() {\n var animation = \"animated fadeInDown\",\n $nav = $(\".nav\");\n $nav.waypoint(function (direction) {\n if (direction == 'down') {\n\n $nav.addClass(animation);\n } else {\n $($nav).removeClass(animation);\n }\n\n }, {\n offset: \"0%\"\n });\n }",
"function updateActiveLink() {\n\tif (this==activeLink){\n\t\treturn;\n\t}\n\t// loops over all li elements\n\tsliderLinks.forEach((link, index) => {\n\t\t// removes 'active' from each\n\t\tlink.classList.remove('active');\n\t\tsliderStack[index].classList.remove('active');\n\t});\n\t// adds 'active' to clicked item\n\tthis.classList.add('active');\n\tsliderStack[sliderLinks.indexOf(this)].classList.add('active');\n\t// stores clicked item\n\tactiveLink = this;\n\tmoveSlides();\n}",
"function activePagination() {\n\n\t\t\tcurrentSlide = this.currentSlide;\n\t\t\t$(this.selector).parent().find('.carousel__pagination-button').removeClass('is-active');\n\t\t\t$(this.selector).parent().find('.carousel__pagination-button--' + currentSlide).addClass('is-active');\n\t\t}",
"function headerNavScroll() {\n var scrollTop = $(window).scrollTop();\n var delta = scrollTop - prevScrollTop;\n\n if (scrollTop === 0) {\n $('.header-nav').removeClass('fixed');\n $('.header-nav').removeClass('slider-up');\n $('.header-nav').addClass('slider-down');\n } else {\n $('.header-nav').addClass('fixed');\n\n if (delta > 0) {\n if (Math.abs(delta) > 5) {\n $('.header-nav').removeClass('slider-down');\n $('.header-nav').addClass('slider-up');\n }\n } else {\n if (Math.abs(delta) > 5) {\n $('.header-nav').removeClass('slider-up');\n $('.header-nav').addClass('slider-down');\n }\n }\n }\n\n prevScrollTop = scrollTop;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
I delete the given movie, owned by the given user. Returns a Promise. | deleteMovie( userId, id ) {
var promise = new Promise(
( resolve, reject ) => {
var movies = this._paramMovies( userId );
var matchingIndex = movies.findIndex(
( item ) => {
return( item.id === id );
}
);
if ( matchingIndex === -1 ) {
throw( new Error( "Not Found" ) );
}
movies.splice( matchingIndex, 1 );
resolve();
}
);
return( promise );
} | [
"function deleteActor (actor) {\n console.log('deleteActor()')\n return new Promise((resolve, reject) => {\n actorDB.get(actor.identifier, (ko, ok) => {\n if (ko) {\n log(ko)\n reject(ko.reason)\n } else {\n actorDB.destroy(actor.identifier, ok._rev, (kko,okk) => {\n if (kko){\n log(kko);\n reject(kko.reason)\n } else resolve({ok, okk})\n })\n }\n })\n })\n}",
"async delete(req, res) {\n try {\n //get user\n let user = await users.findOne({where: {username : req.params.username}})\n let user_id = user.id\n let tagList = await Tags\n .findAll({\n where: { tag: { [Op.in]: req.body.tags } }\n })\n await TagToUser\n .destroy({\n where: {\n user_id: user_id,\n tag_id: { [Op.in]: tagList.map(tag => tag.id) }\n }\n })\n .then(() => res.status(200).send({ message: \"tag deleted from user\" }))\n\n }catch(error){\n res.status(400).send()\n }\n }",
"async onClick(){\n const user = this.props.user;\n const response = await this.deleteUser(user);\n this.props.removeUser(user.id);\n }",
"function removeFromCollection(movieId) {\n\n // fetch the Collection first.\n let collectionName = document.getElementById('searchFilterText').textContent;\n let collectionId = null;\n\n let url = \"http://localhost:3000/userCollections?name=\" + collectionName;\n\n // Fetch Collection details\n httpSync(url, (responseText) => {\n let response = JSON.parse(responseText);\n let index = response[0].movies.indexOf(parseInt(movieId));\n collectionId = response[0].id;\n if (index > -1) {\n response[0].movies.splice(index, 1);\n }\n\n //Update the DB\n var url = 'http://localhost:3000/userCollections/' + collectionId;\n\n // create a Post Request\n var json = JSON.stringify(response[0]);\n httpPostOrPut(url, 'PUT', json);\n\n }, 'GET', null);\n\n // Update the Store\n //store.dispatch(setActionFilter(ActionFilters.SHOW_MOVIE_REMOVED));\n currentAction = ActionFilters.MOVIE_REMOVED;\n store.dispatch(removeMovieFromCollectionStore(collectionId, movieId));\n}",
"function deleteMessage(req, res, user) {\n // Get the message ID.\n var messageID = parseInt(req.params.id);\n\n if (!messageID || messageID < 0) {\n res.status(400).json({message: 'invalid id'});\n\n return;\n }\n\n MessageController.getByMID(messageID)\n .then((message) => {\n if (message.recipient != user.userID) {\n res.status(403).json({message: 'not allowed'});\n\n return;\n }\n\n MessageController.deleteByMID(messageID);\n res.json({message: 'success'});\n });\n}",
"function deleteUser(req, res, next) {\n //Check if the id is valid and exists in db\n \n Users.findOne({\"_id\": req.query.id},\n\n function(err, result) {\n if (err){\n console.log(err);\n\n } \n //console.log(result);\n //If the user exists, delete the user and his/her reviews\n if(result){\n //Remove the user from the db\n Users.remove({\"_id\": req.query.id}, function(err, result){\n res.status(200);\n res.json({message: 'Accounts and Reviews Deleted!'});\n });\n\n //Remove all the users reviews\n Reviews.remove({\"userID\": req.query.id}, function(err, result){\n //res.json({message: 'Reviews Deleted!'});\n });\n \n\n \n } else { //return 404 status if userid does not exist\n res.status(404);\n return res.json({ error: 'Invalid: User does not exist' });\n }\n }); \n\n}",
"deleteAction(req, res) {\n Robot.remove({ _id: req.params.id }, (err, robot) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 204, { 'message': 'Deleted successfully!' });\n });\n }",
"async destroy ({ params, request, response }) {\n const tarefa = await Tarefa.findOrFail(params.id);\n await tarefa.delete();\n }",
"function deleteMovie() {\n\n let movieList = JSON.parse(sessionStorage.getItem(\"movieList\"));\n for (let i = 0; i < movieList.length; i++) {\n if (movieList[i].title == this.parentNode.id) {\n movieList.splice(i, 1);\n }\n }\n sessionStorage.setItem(\"movieList\", JSON.stringify(movieList));\n addMovies();\n}",
"function deleteVideo(req,res,next)\n{\n myTube.Video.remove({videoId:req.params.videoID}, function(error){\n if (error)\n {\n res.send(500, \"Error while trying to delete\");\n }\n else\n {\n res.send(200, \"video was successfully deleted from db\");\n }\n });\n}",
"function deleteUser(req, res) {\n User.remove({_id : req.params.id}, (err, result) => {\n res.json({ message: \"Bucket successfully deleted!\", result });\n });\n}",
"deleteUserCreative(c_id, u_id) {\n return new Promise((resolve, reject) => {\n pool.query(`WITH deletedUserCreative AS (DELETE FROM user_creatives WHERE c_id = $1 AND u_id = $2 RETURNING c_id)\n DELETE FROM creatives WHERE u_count <= 0 AND c_id IN ( SELECT c_id FROM deletedUserCreative)`, [c_id, u_id])\n .then( res => {\n resolve(res);\n }).catch(err => {\n reject(err);\n })\n })\n }",
"function borrarPedido(fila, IDPedido)\n{\n if (confirm(\"¿Seguro que desea eliminar este pedido?\")) \n { \n fetch((url+ '/' +IDPedido),{\n 'method':'DELETE',\n 'mode': 'cors'\n })\n .then(function(respuesta){\n if(respuesta.ok) {\n let tabla = document.getElementById(\"tablaPedido\");\n tabla.removeChild(fila);\n }\n else {\n alert(\"No se pudo eliminar el pedido\");\n }\n });\n }\n}",
"function deleteVideoObject(videoIdNum) {\n setTimeout(() => fetch(`${databaseURL}/${videoIdNum}`, {method: \"DELETE\"})\n .then(function() {\n delete localDatabase[videoIdNum];\n document.querySelector(`div[data-id=\"${videoIdNum}\"]`).remove()\n }), 250)\n \n}",
"function userDelete(id, cb){\n User.findByIdAndDelete(id, function (err, user) {\n if (err) {\n if (cb) cb(err, null)\n return\n }\n console.log('Deleted User: ' + user);\n if (cb) cb(null, user)\n });\n}",
"deleteUserOffer(listing_id, offer_user_id){\n return new Promise((resolve, reject) => {\n this.pool.query(`\n UPDATE OFFERS\n SET deleted = 1\n WHERE ((listing_id = ?) AND (offer_user_id = ?)) \n `, [listing_id, offer_user_id], function(err, data){\n if(err){\n reject(err);\n }\n else{\n resolve(data);\n }\n });\n });\n }",
"deleteUser( id ) {\n fluxUserManagementActions.deleteUser( id );\n }",
"delete(req, res) {\n Origin.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function (deletedRecords) {\n res.status(200).json(deletedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"static deleteUser(req, res) {\n return __awaiter(this, void 0, void 0, function* () {\n const { id } = req.params;\n try {\n yield User_1.default.findOneAndDelete({ _id: id });\n res.status(200).json({\n message: \"The user has been deleted\"\n });\n }\n catch (e) {\n res.status(500).json({ message: \"an internal error has been ocurred\" });\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
board string change to board Array, next replace old elemenet a newNumber by splice and change array to string by join('' witout commas) | hadleTileChange(id, newNumber) {
let boardArray = (this.state.board).split('');
boardArray.splice(id, 1, newNumber);
boardArray = boardArray.join('');
this.setState({
board: boardArray
});
} | [
"removePieceAt(row, col){\n //if arg0 is a string, then parse algebraic to indeces\n if(typeof row === 'string'){\n [row,col] = this.algerbraicToIndeces(row);\n }\n // else if it is not a string or number, then it is an array of nums\n else if(typeof row !== 'number'){\n [row,col] = row;\n }\n\n this.board[row][col] = undefined;\n }",
"transformBoardToArray (board) {\n const boardArray = []\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[i].length; j++) {\n boardArray.push({\n id: (i * 8) + j, // id will be equal to the original index position\n piece: board[i][j]\n })\n }\n }\n return boardArray\n }",
"changeBoard(fromSpace, toSpace){\n let fromIndex; let toIndex\n if (this.direction === 1){\n fromIndex = this.getId(fromSpace); toIndex = this.getId(toSpace)\n } else {\n fromIndex = this.getId(toSpace); toIndex = this.getId(fromSpace)\n }\n let orig_copy = $(\"#\"+fromIndex).children()\n let temp = orig_copy.clone()\n temp.appendTo('body')\n temp.css(\"display\", \"inline-block\")\n if (!$(\"#\"+toIndex).children().is('span')){\n let img_src = $(\"#\"+toIndex).children().prop('src')\n img_src = \".\"+img_src.slice(img_src.length - 11, img_src.length)\n this.takenPieces.push([img_src, this.current, this.direction])\n }\n $(\"#\"+toIndex).empty()\n let new_copy = orig_copy.clone().appendTo(\"#\"+toIndex)\n new_copy.css(\"display\", \"inline-block\")\n let oldOffset = orig_copy.offset()\n $(\"#\"+fromIndex).empty().append(\"<span id='piece'></span>\")\n let newOffset = new_copy.offset()\n for (let i = 0; i < this.takenPieces.length; i++){\n if (this.takenPieces[i][1] === this.current && this.takenPieces[i][2] !== this.direction){\n $(\"#\"+fromIndex).empty().append(`<img id=\"piece\" src=${this.takenPieces[i][0]}></img>`)\n $(\"#\"+fromIndex).css(\"display\", \"inline-block\")\n }\n }\n for (let i = 0; i < this.highlights.length; i++){\n if (this.highlights[i]){\n this.highlights[i].attr(\"class\").includes(\"dark\") ? this.highlights[i].css(\"border\", \"solid medium darkgrey\") : this.highlights[i].css(\"border\", \"solid medium lightgrey\")\n }\n }\n this.highlights[1] = $(\"#\"+fromIndex); this.highlights[2] = $(\"#\"+toIndex)\n $(\"#\"+fromIndex).css(\"border\", \"medium solid green\")\n $(\"#\"+toIndex).css(\"border\", \"medium solid green\")\n if (this.moves[this.current][\"special_square\"]){\n let special_square = [this.moves[this.current][\"special_square\"][\"row\"], this.moves[this.current][\"special_square\"][\"col\"]]\n $(\"#\"+this.getId(special_square)).css(\"border\", \"medium solid red\")\n this.highlights[0] = $(\"#\"+this.getId(special_square))\n }\n temp\n .css('position', 'absolute')\n .css('left', oldOffset.left)\n .css('top', oldOffset.top)\n .css('zIndex', 1000)\n .css(\"display\", \"inline\")\n .css(\"width\", \"25px\")\n .css(\"height\", \"25px\")\n new_copy.css(\"display\", \"none\")\n temp.animate({'top': newOffset.top, 'left':newOffset.left}, this.delay, function(){\n new_copy.css(\"display\", \"inline-block\")\n temp.remove()\n })\n }",
"function parseBoard() {\n var result = \"\\n 1 2 3\\na\";\n for (x in board) {\n for (y in board[x]) {\n if ((y + 1) % 3 != 0 || (x + 1 == 1 && y + 1 == 1)) {\n result += board[x][y] + \"|\";\n } else {\n if (y == 2 && x != 2) {\n result += board[x][y] + \"\\n ---|---|---\\n\";\n } else {\n result += board[x][y] + \"\\n\";\n }\n }\n\n if (x == 0 && y == 2) result += \"b\";\n else if (x == 1 && y == 2) result += \"c\"\n }\n }\n\n return result;\n }",
"function seperateComma(number) {\n var stringNumber = number.toString().split(\"\");\n var indexOfLastNumber = stringNumber.length;\n\n for (var counter = 3; counter <= indexOfLastNumber ; counter += 3 ) {\n var slices = indexOfLastNumber - counter;\n var numWithCommas = stringNumber.splice(slices, 0 ,\",\");\n var returnToString = numWithCommas.join();\n };\n console.log(stringNumber.join(\"\"));\n}",
"function replaceN() {\n numbers[numbers.indexOf(12)] = 1221;\n numbers[numbers.indexOf(18)] = 1881;\n}",
"function updateBoard(index, marker) {\r\n board[index] = marker;\r\n\r\n /* HTML5 localStorage only allows storage of strings - convert our array to a string */\r\n var boardstring = JSON.stringify(board);\r\n\r\n /* store this string to localStorage, along with the last player who marked a square */\r\n localStorage.setItem('tic-tac-toe-board', boardstring);\r\n localStorage.setItem('last-player', getCurrentPlayer());\r\n}",
"function stringItUp(arr){\n return arr.map(number => number.toString())\n}",
"removeOpponentPiece(board, row, col) {\n // if there was an opponent's piece at new index, get rid of that piece from board\n const opponentPiece = board[row][col];\n if (opponentPiece === null) return;\n\n // create copies of piecesInPlay and piecesOffPlay\n let piecesInPlay = BoardHelperFuncs.copyOfBoard(this.state.piecesInPlay);\n let piecesOffPlay = BoardHelperFuncs.copyOfBoard(this.state.piecesOffPlay);\n\n const opponentPieceColor = opponentPiece.color;\n // update opponent pieces in play\n piecesInPlay[opponentPieceColor] = piecesInPlay[opponentPieceColor].filter(\n function (piece) {\n return (piece !== opponentPiece,\n /////////////////////////////////\n /////////////////////////////////\n /////////////////////////////////\n console.log('remove'))\n /////////////////////////////////\n /////////////////////////////////\n /////////////////////////////////\n }\n );\n\n // update opponent pieces off play\n piecesOffPlay[opponentPieceColor].push(opponentPiece);\n\n this.setState({ piecesInPlay: piecesInPlay, piecesOffPlay: piecesOffPlay });\n }",
"function insertDash(num){\n\n const array = [];\n\n for (let i = 0; i < num.length; i++) {\n\n if ((num[i] % 2 === 0) && num[i + 1] % 2 === 0) {\n\n array.push(num[i] + '-' );\n\n } else {\n\n array.push(num[i]);\n\n }\n\n }\n\n return array.join('');\n\n }",
"function board_overwrite(fleet, num_boat){\r\n \r\n //It decomposes starting position\r\n let ini_x = Math.trunc(fleet[num_boat].occupied_places[0] / 10);\r\n let ini_y = fleet[num_boat].occupied_places[0] % 10;\r\n \r\n if(fleet == own_fleet) // It searchs the board corresponding to the ship\r\n var board = own_board;\r\n else\r\n var board = enemy_board;\r\n\r\n if(fleet[num_boat].direction == 0) // It prints the number\r\n for(let i = 0; i < fleet[num_boat].type; i++)\r\n board[ini_x + i][ini_y] = num_boat;\r\n\r\n else\r\n for(let i = 0; i < fleet[num_boat].type; i++)\r\n board[ini_x][ini_y + i] = num_boat; \r\n}",
"function weave(strings) {\n let phrase = ('coding iz hard')\n let string = phrase.split('')\n let nth = 4;\n let replace = 'x';\n for (i = nth - 1; i < string.length; i += nth) {\n string[i] = replace;\n }\n return string.join('');\n}",
"function assignCandidateState(board, arr, row, column) {\n if ($scope.puzzle.board[row][column] !== \"\") {\n arr[board[row][column] - 1] = true;\n }\n }",
"function drawChessboard(size){\nvar board = \"\".repeat(size);\nfor(var i = 0; i < size; i++){\n for(var a = 0; a < size; a++){\n board += (a % 2) == (i % 2) ? \" \" : \"#\";\n }\n board += \"\\n\";\n}console.log(board);\n}",
"function addComma(location, stringToArray) {\n stringToArray.splice(location,0,',')\n return arrayToString = stringToArray.join('');\n}",
"function changeFormatData(retails) {\n\tlet output = [];\n\t// Put ur code here\n\n\t// loop through the retails array\n\tfor (let i = 0; i < retails.length; i++) {\n\t\tlet row = [];\n\n\t\t// loop through the rows\n\t\tfor (let j = 0; j < retails[i].length; j++) {\n\t\t\tlet temp = '';\n\n\t\t\t// loop through the characters\n\t\t\tfor (let k = 0; k < retails[i][j].length; k++) {\n\t\t\t\t// if '-', push into row and reset temp\n\t\t\t\t// otherwise, put the string into temp\n\t\t\t\tif (retails[i][j][k] === '-') {\n\t\t\t\t\trow.push(temp);\n\t\t\t\t\ttemp = '';\n\t\t\t\t} else {\n\t\t\t\t\ttemp += retails[i][j][k];\n\t\t\t\t}\n\n\t\t\t\t// push the last set of string as a number into the row array\n\t\t\t\tif (k === retails[i][j].length - 1) {\n\t\t\t\t\trow.push(Number(temp));\n\t\t\t\t\ttemp = '';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\toutput.push(row);\n\t}\n\treturn output;\n}",
"refreshBoard() {\n\tfor(var i = 0; i < 8; ++i) {\n\t for(var j = 0; j < 8; ++j) {\n\t\tvar thecell = document.getElementById(this.cell2id(i, j));\n\t\tthecell.innerHTML = this.cell2piece(this.board.cellByRC(i, j));\n\t }\n\t}\n }",
"function setBoard(newBoard) {\n board = newBoard;\n boardHistory.push(newBoard);\n}",
"movePiece(p_index, t_index) {\n // Pull variables out of loop to expand scope\n let piece = null;\n let o_tile = null;\n let t_tile = null;\n\n // Look for old and new tiles by index\n for (let line of this.board) {\n for (let tile of line) {\n if (tile.index === p_index) {\n // Grap piece and old tile\n piece = tile.piece;\n o_tile = tile;\n }\n if (tile.index === t_index) {\n // Grab target tile\n t_tile = tile;\n }\n }\n }\n\n // Only move piece if old tile has one to move and move id valid\n // Make sure you can't take out your own pieces\n if (o_tile.piece && t_tile.valid) {\n if (o_tile.piece.color === this.turn) {\n if (t_tile.piece) {\n if (o_tile.piece.color !== t_tile.piece.color) {\n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n } else { \n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n }\n }\n\n // Reset all valid tags\n for (let line of this.board) {\n for (let tile of line) {\n tile.valid = false;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
I toggle the testing state for the given commit in production. | function toggleTestingInProduction( commit ) {
var nextTesting = _.cycle( [ "inactive", "active" ], commit.production.testing );
var nextStatus = commit.production.status;
// If the testing got reset, move the status back to a pending state.
if ( nextTesting === "inactive" ) {
nextStatus = "pending";
}
deploymentService
.updateCommitInProduction( deploymentID, commit.hash, nextTesting, nextStatus )
.then(
function handleResolve() {
$log.info( "Production commit [ %s ] updated.", commit.hash );
}
)
;
} | [
"function toggleStatusInProduction( commit ) {\n\n\t\tvar nextTesting = \"active\";\n\t\tvar nextStatus = _.cycle( [ \"pending\", \"pass\", \"fail\" ], commit.production.status );\n\n\t\tdeploymentService\n\t\t\t.updateCommitInProduction( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Production commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"function toggleTestingInStaging( commit ) {\n\n\t\tvar nextTesting = _.cycle( [ \"inactive\", \"active\" ], commit.staging.testing );\n\t\tvar nextStatus = commit.staging.status;\n\n\t\t// If the testing got reset, move the status back to a pending state.\n\t\tif ( nextTesting === \"inactive\" ) {\n\n\t\t\tnextStatus = \"pending\";\n\n\t\t}\n\n\t\tdeploymentService\n\t\t\t.updateCommitInStaging( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Staging commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"function toggleStatusInStaging( commit ) {\n\n\t\tvar nextTesting = \"active\";\n\t\tvar nextStatus = _.cycle( [ \"pending\", \"pass\", \"fail\" ], commit.staging.status );\n\n\t\tdeploymentService\n\t\t\t.updateCommitInStaging( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Staging commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"_is_testing() {\n return this.env != \"production\" && this.env != \"prod\";\n }",
"toggleVersions() {\n let newState = !(this.state.VersionSelectToggle);\n this.handleGetSchedulerRunVersions();\n this.setState( {VersionSelectToggle: newState});\n }",
"toggleApproval(currency, current_approval) {\n let new_approval = !current_approval\n if(new_approval) {\n this.approveCurrency(currency)\n } else {\n this.unapproveCurrency(currency)\n }\n }",
"toggleShowStudent() {\n let newState = !(this.state.showStudent);\n this.setState( {showStudent: newState, showProject: false} );\n }",
"function tract_toggle() {\n console.log(\"tract_toggle\");\n if (tract_counter%2 == 0) {\n click_tract_off();\n } else {\n click_tract_on();\n }\n}",
"_suiteChange() {\n if (DEBUG) {\n console.log('[*] ' + _name + ':_suiteChange ---');\n }\n\n this.setState({\n suites: getSuitesState()\n });\n }",
"toggleTransactionDetails() {\n var showorHidden = (this.state.showTransaction === \"hidden\") ? \"show\" : \"hidden\";\n this.setState({\n showTransaction:showorHidden\n });\n }",
"async function checkoutRelease(alternate) {\n console.log(\"Checking out the release branch...\");\n\n // Make sure we're on a release branch that matches dev\n if (shell.exec('git checkout release').code !== 0) {\n if (shell.exec('git checkout -b release').code !== 0) {\n console.log('Could not switch to the release branch. Make sure the branch exists locally.');\n process.exit(1);\n }\n }\n\n // Make sure we have the latest from the remote\n if (shell.exec('git fetch --all').code !== 0) {\n console.log('Could not fetch from remote servers.');\n process.exit(1);\n }\n\n console.log(\"Resetting the release branch to the latest contents in dev...\");\n // Make sure we are exactly what is in dev\n if (shell.exec(`git reset --hard ${ENSURE_REMOTE}/dev${alternate ? `-${alternate}` : \"\"}`).code !== 0) {\n console.log(`Could not reset branch to dev${alternate ? `-${alternate}` : \"\"}`);\n process.exit(1);\n }\n}",
"_submitState() {\n let objFields = Object.values(Object.values(this.testObj));\n let stateArr = objFields.map(f => f.state); // Creates array from test object with state boolean values.\n // Checks if the test array includes false, and changes the submit button according to this result.\n this._inputState(this.HTML.submitForm, !stateArr.includes(false), false);\n }",
"_togglePostCard() {\n this.setState({\n isSubmited: false\n })\n }",
"async function onPushMain() {\n const ghApi = github.getOctokit(actionGithubToken);\n\n if (github.context.ref === 'refs/heads/main' || github.context.ref === 'refs/heads/master') {\n // check that no open pull request has the envLabel\n const pulls = await ghApi.pulls.list({ ...github.context.repo, state: \"open\" });\n const isLabelOnPulls = pulls.data.some(pull => pull.labels.some(({ name }) => name === envLabel));\n core.setOutput('should-deploy', !isLabelOnPulls);\n } else {\n core.setOutput('should-deploy', false);\n }\n}",
"toggle() {\n let editorEl = h.getEditorEl(),\n toggleEl = h.getEditorToggleEl(),\n mainNav = h.getMainNavEl();\n\n // Clear menus and load edit panel\n editor.clearMenus();\n editor.currentPost = view.currentPost;\n editor.currentPostType = view.currentPost.type;\n editor.currentMenu = 'edit';\n\n // Toggle editor and nav hidden classes\n editorEl.classList.toggle('hidden');\n toggleEl.classList.toggle('hidden');\n // Toggle whether view nav is disabled\n mainNav.classList.toggle('inactive');\n\n // Take specific actions if opening or closing editor\n if (toggleEl.classList.contains('hidden') === false) {\n // If opening editor\n var navTitleLink = h.getEditorNavTitleLink();\n editor.showEditPanel();\n navTitleLink.addEventListener('click', editor.listenSecondaryNavTitle, false);\n view.listenDisableMainNavLinks();\n } else {\n // If closing editor\n if (view.currentPost.type === 'posts') {\n router.updateHash('blog/' + view.currentPost.slug);\n } else {\n if (editor.currentPost.slug === '_new') {\n // If closing a new post editor\n router.updateHash('blog');\n router.setCurrentPost();\n } else {\n router.updateHash(view.currentPost.slug);\n }\n }\n view.listenMainNavLinksUpdatePage();\n }\n }",
"function toggleApproval(args) {\n const approved = !$(`.review-button[data-id=\"${args.id}\"]`).hasClass('approved')\n $(`.review-button[data-id=\"${args.id}\"]`).toggleClass('approved', approved)\n $(`.review-block[data-id=\"${args.id}\"]`).toggleClass('approved', approved)\n\n if (args.context == 'content') {\n // This sends a message to the preview iframe to update the state of the block with the given id.\n // This allows us to have the preview dynamically change when a content change is approved/rejected.\n postMessage('approve', { id: args.id, approved: approved })\n } else if (args.context == 'details' && args.refresh == 'true') {\n // For detail changes, we instead reload the preview iframe, if refresh is set to true.\n const url = detailsIframe.src.split('?')[0]\n detailsIframe.src = `${url}?review=true&excerpt=true&reify=${getApprovedDetailChanges().join(',')}`\n }\n}",
"toggleEdit() {\n // url: doesn't include the ?edit part\n const { url, isEditing, history } = this.props;\n const newUrl = isEditing ? url : url + '?edit';\n history.push(newUrl);\n }",
"toggleCleared(transaction) {\n\t\tthis.transactionModel.updateStatus(this.contextModel.path(this.context.id), transaction.id, transaction.status).then(() => this.updateReconciledTotals());\n\t}",
"toggleHistoryView() {\n this['showHistoryView'] = !this['showHistoryView'];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prend une liste d'ID HTML id_contenus et les rens invisibles sur la page puis rend visible l'ID id_contenu_a_afficher (s'il existe) | function masque_affiche_contenus(id_contenus, id_contenu_a_afficher) {
console.debug(
`CALL masque_affiche_contenus([${id_contenus}],${id_contenu_a_afficher})`
);
id_contenus.map(function(idc) {
document.getElementById(idc).style.display = "none";
});
if (id_contenu_a_afficher !== undefined)
document.getElementById(id_contenu_a_afficher).style.display = "block";
} | [
"function afficherDetailRecette(id) {\n for(i = 0; i < listeRecettes.length; i++) {\n if(id == (listeRecettes[i].id)) {\n document.getElementById(\"bodyRecette\").innerHTML = \"<div class=\\\"divConnexion\\\"><div class=\\\"carteRecette\\\"><div class=\\\"boiteDeroulante\\\"><div class=\\\"headerRecette\\\"><img class=\\\"iconImage\\\" src= \\\"img/recette.jpg\\\"><div class=\\\"divFlexColumn\\\"><h1>\" + listeRecettes[i].nom + \"</h1><div><h3>Portions</h3> <h3>Temps</h3><h3>Calorie</h3></div></div></div><div class=\\\"bodyRecette\\\"><h3>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam consequatur officiis repellat corrupti dolorum, ipsa possimus. Incidunt mollitia perferendis, molestiae non expedita explicabo dolorem unde, aliquid doloremque dolores laudantium? Cupiditate? Lorem ipsum dolor, sit amet consectetur adipisicing elit. Sint id maxime architecto at accusamus debitis dignissimos, numquam est eum consectetur eius iusto quibusdam modi! Iure tenetur ea commodi tempora animi! <br> <br> Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam consequuntur, illum quaerat fugiat doloremque porro impedit dolor, voluptas aliquam molestias ut possimus animi quae. Aliquam rem harum ullam laudantium inventore.</h3></div></div></div></div><div class=\\\"divNavigation\\\"><a id=\\\"navigationRecettesPub\\\" href=\\\"/pageRecettes\\\"><p id=\\\"navigationRecettesPub\\\">Retour</p></div></a>\"\n }\n }\n}",
"function domandaSuccessiva() {\n document.getElementById(\"rispostaCorretta\").style.display = \"none\";\n document.getElementById(\"rispostaErrata\").style.display = \"none\";\n document.getElementById(\"next\").style.display = \"none\";\n document.getElementById(\"didascalia\").style.visibility = \"hidden\";\n\n booleanCounter = false;\n document.getElementById(\"apriSuggerimento\").style.visibility = \"hidden\";\n\n if (checkRisposta == true) {\n sezioneSuccessiva();\n } else {\n indiceDomanda++;\n if (jsonFile.File[indiceSezione].domanda.length > indiceDomanda) {\n gestioneDomandaSuccessiva();\n } else {\n sezioneSuccessiva();\n }\n }\n}",
"function ganhouShow(id) {\r\n ganhou = true\r\n verificaVitoria = true\r\n document.getElementById(\"ganhou\").style.display = 'flex'\r\n document.getElementById(\"content\").style.display = 'none'\r\n document.getElementById(\"ganhou\").style.opacity = '1'\r\n document.getElementById(\"nomeGanhador\").innerText = `PARABÉNS, ${nomeJogadores[id]}`\r\n document.getElementById(\"textoGanhador\").innerText = `VOCÊ GANHOU O BINGO!!!`\r\n\r\n}",
"function desactiveAfficheErreur(){\n\tvar afficheErreur=document.getElementById('afficheErreur');\n\tafficheErreur.style.display = ' none' ;\t\n}",
"function mostrarBtnDescargas(){\n\tif( $('#div_btn_descargas').is(\":visible\") ){ //esta visible\n\t\t//si esta visible el div\n\t}else{\n\t\t//si no esta visible el div\n\t\t$('#div_btn_descargas').show();\n\t\t$('#btn_iniciar').show();\n\t\t$('#div_btn_inspeccion_apk').hide();\n\t\t$('#div_btn_grabadora_apk').hide();\n\t\t$('#div_btn_regresar').hide();\n\t}\n}",
"function Mostrar_Ocultar(idMostrarOcultar, compCambiarHtml, idImgFlecha){\n\t var componente=null;\n\t var imagenFlecha=null;\n\t try {\n\t componente=document.getElementById(idMostrarOcultar);\n\t imagenFlecha=document.getElementById(idImgFlecha);\n if (\tcomponente.style.display == \"\") {\n\t\tcompCambiarHtml.innerHTML=literales_traducirLiteralMultiidioma('UTILS_MOSTRAR_DETALLES')+'  ';\n\t\tcomponente.style.display= \"none\";\n \timagenFlecha.src=flecha_m.src;\n\n } else {\n compCambiarHtml.innerHTML=literales_traducirLiteralMultiidioma('UTILS_OCULTAR_DETALLES')+'  ';\n componente.style.display= \"\";\n imagenFlecha.src=flecha_o.src;\n }\n }finally {\n\t componente=null;\n\t imagenFlecha=null; \n }\n}",
"function obtenerContenedor(flujoId)\n{\n \n var contenedor =null;\n var contenedora=false;\n var urlsDesconexionAux=null;\n var documento=null;\n var ventanasEmergentes_IdentificadoresAux=null;\n //variable para almacenar el nombre de la ventana padre\n var nombrePadre=null;\n var frame = null;\n \n try{\n \n try {\n //Se comprueba si se está lanzando el mensaje de error desde el contenedor o desde la página contenedora\n if (urlsDesconexion!=undefined && urlsDesconexion!=null){\n //Estoy en la pagina contenedora\n contenedora=true;\n urlsDesconexionAux=urlsDesconexion;\n documento=document;\n }else{\n //Estoy en el contenedor, luego tengo que tomar los datos de la página contenedora\n contenedora=false;\n urlsDesconexionAux=parent.urlsDesconexion;\n documento=parent.document;\n }\n }catch (err){\n try{\n contenedora=false;\n urlsDesconexionAux=parent.urlsDesconexion;\n documento=parent.document;\n }catch (err2){\n //Distinto dirbase\n urlsDesconexionAux=null;\n }\n }\n\n\n if (urlsDesconexionAux != undefined && urlsDesconexionAux!=null)\n {\n \t for (var i=0 ; i<urlsDesconexionAux.length ; i++){\n \t\t //identificador del contenedor\n \t\t var iden_conte = 'frame_'+urlsDesconexionAux[i][0];\n \t\t //se obtiene el frame del contenedor\n\n \t\t \n \t\t if (documento.getElementById(iden_conte).contentWindow)\n \t \t{\n \t frame = documento.getElementById(iden_conte).contentWindow;\n \t \t} else\n \t \t{\n \t // IE\n \t frame = documento.frames[iden_conte].window;\n \t \t}\n \t\t //var frame = getFrameContenedor(iden_conte);\n\n \t\t\t\t//se recupera el flujo\n \t\t var idflujo = null;\n \t\t try{\n \t\t\t idflujo = frame.document.forms[0].flujo.value;\n \t\t }catch (err){\n \t\t\t idflujo = null;\n \t\t }\n \t\t if (idflujo!=null && flujoId==idflujo)\n \t\t {\n \t\t \tcontenedor=frame;\n \t\t \tbreak;\n \t\t\t\t}\n \t\t}\n \t}\n \tif (contenedor!=null){\n \t return contenedor;\n }\n\n try{\n if (parent.parent.ventanasEmergentes_Identificadores!=undefined && parent.parent.ventanasEmergentes_Identificadores!=null && parent.parent.ventanasEmergentes_Identificadores.length>0)\n {\n \t\tventanasEmergentes_IdentificadoresAux=parent.parent.ventanasEmergentes_Identificadores;\n \tdocumento=parent.parent.document;\n\t\t\t\t\tnombrePadre=parent.name;\n\n }\n else if (parent.ventanasEmergentes_Identificadores!=undefined && parent.ventanasEmergentes_Identificadores!=null && parent.ventanasEmergentes_Identificadores.length>0)\n \t{\n \t \tventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores;\n \tdocumento=parent.document;\n }\n \telse {\n \tventanasEmergentes_IdentificadoresAux=ventanasEmergentes_Identificadores;\n \tdocumento=document;\n }\n }catch (err){\n try{\n\t\t\t\t//recogemos los identificadores que tenga la ventana\n ventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores;\n documento=parent.document;\n }catch (err2){\n //Distinto dirbase\n ventanasEmergentes_IdentificadoresAux=null;\n }\n }\n\n if (ventanasEmergentes_IdentificadoresAux != undefined && ventanasEmergentes_IdentificadoresAux!=null)\n {\n \t for (var i=0 ; i<ventanasEmergentes_IdentificadoresAux.length ; i++){\n\t\t //identificador del contenedor\n \t\t var iden_conte = 'iframeinterno_'+ventanasEmergentes_IdentificadoresAux[i];\n\t\t //se obtiene el frame del contenedor\n \t\t try{\n\t\t if (documento.getElementById(iden_conte).contentWindow)\n\t \t{\n\t frame = documento.getElementById(iden_conte).contentWindow;\n\t \t} else\n\t \t{\n\t // IE\n\t frame = documento.frames[iden_conte].window;\n\t \t}\n \t }catch (err){\n frame=null;\n }\n\n\t\t\t\t//se recupera el flujo\n\t\t var idflujo = null;\n\t\t try{\n\t\t\t idflujo = frame.document.forms[0].flujo.value;\n\t\t }catch (err){\n\t\t\t idflujo = null;\n\t\t }\n\t\t if (idflujo!=null && flujoId==idflujo)\n\t\t {\n\t\t \tcontenedor=frame;\n\t\t \tbreak;\n\t\t\t\t}\n\t\t\t\t\telse if (iden_conte==nombrePadre){\n\t\t\t\t\t\tcontenedor=frame;\n \t\t \tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn contenedor;\n\t\n\t}finally{\n\t\tcontenedor =null;\n\t\tcontenedora=false;\n\t\turlsDesconexionAux=null;\n\t\tdocumento=null;\n\t\tventanasEmergentes_IdentificadoresAux=null;\n\t\tnombrePadre=null;\n\t\tframe = null;\n\t\t\n\t}\n}",
"function obtenerIDContenedor(flujoId)\n{\n var contenedorID =null;\n var contenedora=false;\n var urlsDesconexionAux=null;\n var documento=null;\n var nombrePadre=null;\n var frame = null;\ntry {\n try {\n //Se comprueba si se está en la página contenedora o en el contenedor\n if (urlsDesconexion!=undefined && urlsDesconexion!=undefined){\n contenedora=true;\n urlsDesconexionAux=urlsDesconexion;\n documento=document;\n }else{\n contenedora=false;\n urlsDesconexionAux=parent.urlsDesconexion;\n documento=parent.document;\n }\n }catch (err){\n try{\n contenedora=false;\n urlsDesconexionAux=parent.urlsDesconexion;\n documento=parent.document;\n }catch (err2){\n //Distinto dirbase\n urlsDesconexionAux=null;\n }\n }\n\n if (urlsDesconexionAux != undefined && urlsDesconexionAux!=null)\n {\n \t for (var i=0 ; i<urlsDesconexionAux.length ; i++){\n \t\t //identificador del contenedor\n \t\t var iden_conte = 'frame_'+urlsDesconexionAux[i][0];\n \t\t //se obtiene el frame del contenedor\n\n \t\t var window = null;\n \t\t\t if (documento.getElementById(iden_conte).contentWindow)\n \t \t{\n \t window = documento.getElementById(iden_conte).contentWindow;\n \t \t} else\n \t \t{\n \t // IE\n \t window = documento.frames[iden_conte].window;\n \t \t}\n\n \t\t\t\t//se recupera el flujo\n \t\t var idflujo = null;\n \t\t try{\n \t\t\t idflujo = window.document.forms[0].flujo.value;\n \t\t }catch (err){\n \t\t\t idflujo = null;\n \t\t }\n \t\t if (idflujo!=null && flujoId==idflujo)\n \t\t {\n \t\t \tcontenedorID=urlsDesconexionAux[i][0];\n \t\t \tbreak;\n \t\t\t\t}\n \t\t}\n \t}\n \tif (contenedorID!=null){\n \t return contenedorID;\n }\n\n try{\n if (parent.parent.ventanasEmergentes_Identificadores!=undefined && parent.parent.ventanasEmergentes_Identificadores!=null && parent.parent.ventanasEmergentes_Identificadores.length>0){\n \tventanasEmergentes_IdentificadoresAux=parent.parent.ventanasEmergentes_Identificadores;\n \tdocumento=parent.parent.document;\n\t\t\t\t\tnombrePadre=parent.name;\n }else{\n \tif (parent.ventanasEmergentes_Identificadores!=undefined && parent.ventanasEmergentes_Identificadores!=null && parent.ventanasEmergentes_Identificadores.length>0)\n \t{\n \t \tventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores;\n \tdocumento=parent.document;\n }\n \telse{\n \t\tventanasEmergentes_IdentificadoresAux=ventanasEmergentes_Identificadores;\n \tdocumento=document;\n }\n }\n }catch (err){\n try{\n\t\t\t\t//recogemos los identificadores que tenga la ventana\n ventanasEmergentes_IdentificadoresAux=parent.ventanasEmergentes_Identificadores;\n documento=parent.document;\n }catch (err2){\n //Distinto dominio\n ventanasEmergentes_IdentificadoresAux=null;\n }\n }\n\n\n if (ventanasEmergentes_IdentificadoresAux != undefined && ventanasEmergentes_IdentificadoresAux!=null)\n {\n \t for (var i=0 ; i<ventanasEmergentes_IdentificadoresAux.length ; i++){\n\t\t //identificador del contenedor\n \t\t var iden_conte = 'iframeinterno_'+ventanasEmergentes_IdentificadoresAux[i];\n\t\t //se obtiene el frame del contenedor\n\n\t\t var window = null;\n \t\t try{\n\t\t\t if (documento.getElementById(iden_conte).contentWindow)\n\t \t{\n\t window = documento.getElementById(iden_conte).contentWindow;\n\t \t} else\n\t \t{\n\t // IE\n\t window = documento.frames[iden_conte].window;\n\t \t}\n \t\t }catch (err){\n window=null;\n }\n\t\t\t\t//se recupera el flujo\n\t\t var idflujo = null;\n\t\t try{\n\t\t\t idflujo = window.document.forms[0].flujo.value;\n\t\t }catch (err){\n\t\t\t idflujo = null;\n\t\t }\n\t\t if (idflujo!=null && flujoId==idflujo)\n\t\t {\n \t\t \tcontenedorID=ventanasEmergentes_IdentificadoresAux[i];\n\t\t \tbreak;\n \t\t\t}else if(iden_conte==nombrePadre){\n\t\t\t\t\t\tcontenedorID=ventanasEmergentes_IdentificadoresAux[i];\n \t\t \tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn contenedorID;\n\t\n\t} finally {\n\t\tcontenedorID =null;\n\t\tcontenedora=false;\n\t\turlsDesconexionAux=null;\n\t\tdocumento=null;\n nombrePadre=null;\n\t\tframe = null;\n\n\t}\n}",
"function ocutarTodasCamadas(){\n \n var qt = app.activeDocument.layers.length;\n var i;\n \n for(i=0;i<qt;i++){\n app.activeDocument.activeLayer = app.activeDocument.layers[i];\n app.activeDocument.activeLayer.visible = false;\n }\n}",
"function checkLoanAdvance(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showLoanItem('advance');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkLoanAdvance",
"function checkWireRep(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showWireItem('repetitive');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkWireRep",
"function seleccionarMenu(){\r\n\t//elementos del menú principal (sin submenús)\r\n\telementosDelMenu = $(\"ul.sf-menu > li\");\r\n\t//url en la que está el navegador\r\n\turlActual = window.location.href;\r\n\r\n\t//recorremos los elementos principales del menú\r\n\tfor(var i = 0; i<elementosDelMenu.length; i++){\r\n\t\t//cada tag LI del menú, uno por cada vuelta del for\r\n\t\telementoMenu = $(elementosDelMenu[i]);\r\n\t\tif(elementoMenu!=undefined){\r\n\t\t\t//Tags A de cada elemento LI del menú\r\n\t\t\tenlacesElementoMenu = elementoMenu.find(\"A\");\r\n\t\t\t//Enlace visible del menú (al que se le aplicará el estilo si el o alguno de sus subMenús coincide en la búsqueda)\r\n\t\t\tenlaceTituloMenu\t= enlacesElementoMenu[0];\r\n\t\t\tfor(var j=0; j<enlacesElementoMenu.length; j++){\r\n\t\t\t\t//URL de cada tag A del LI actual\r\n\t\t\t\turlElementoMenu = enlacesElementoMenu[j].href;\r\n\t\t\t\tif(urlActual.indexOf(urlElementoMenu)>=0){\r\n\t\t\t\t\t//si la URL que estamos comprobando es en la que estamos, se le aplica \r\n\t\t\t\t\t//el class \"Selected\" al tag A titular del submenú que estamos comprobando\r\n\t\t\t\t\t$(enlaceTituloMenu).addClass(\"selected\");\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}",
"function getCanalConId(id, listaCanalesFiltrar) {\r\n let ret = [];\r\n let indice = 0;\r\n\r\n while (indice < listaCanalesFiltrar.length && ret.length === 0){\r\n if(listaCanalesFiltrar[indice].id === id){\r\n ret[0] = listaCanalesFiltrar[indice];\r\n }\r\n indice++;\r\n }\r\n\r\n return ret;\r\n }",
"function active_piece(id){\n var num_select = -1; \n var id_select = -1; \n for(i=0;i<Tableau_pieces.length;i++){\n if(Tableau_pieces[i]['id'] == id) {\n num_select = i;\n id_select = id;\n break;\n }\n }\n if(num_select != -1){\n num_page = Math.floor(num_select/taille_tableau_content_page['piece']);\n num_in_page = num_select - num_page * taille_tableau_content_page['piece'];\n go_page_piece(num_page);\n affich_active_piece(num_in_page)\n }\n}",
"function checkBookReq(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showMenuItem('book');\r\n\tif (rc == '0'){\r\n\t\ttemp = document.getElementById(id);\r\n\t\ttemp.style.display = 'none';\r\n\t}\r\n}//end checkBookReq",
"function modificaTipoRegistrazioneIva() {\n var selectedOption = $(this).find(\"option:selected\");\n var selectedEsigibilita = selectedOption.data(\"tipoEsigibilitaIva\");\n var divs = $(\"#gruppoProtocolloProvvisorio, #gruppoProtocolloDefinitivo\");\n var divProvvisorio = $(\"#gruppoProtocolloProvvisorio\");\n var divDefinitivo = $(\"#gruppoProtocolloDefinitivo\");\n var regexDifferita = /DIFFERITA/;\n var regexImmediata = /IMMEDIATA/;\n\n if (regexDifferita.test(selectedEsigibilita) && !divProvvisorio.is(\":visible\")) {\n // Se ho selezionato il valore 'DIFFERITO' e il div e' ancora chiuso, lo apro\n divs.slideUp();\n divProvvisorio.slideDown();\n } else if (regexImmediata.test(selectedEsigibilita) && !divDefinitivo.is(\":visible\")) {\n // Se ho selezionato il valore 'IMMEDIATO' e il div e' ancora chiuso, lo apro\n divs.slideUp();\n divDefinitivo.slideDown();\n } else if (!selectedEsigibilita) {\n // Se non ho selezionato null, chiudo i div\n divs.slideUp();\n }\n // Se i div sono gia' aperti, non modifico nulla\n }",
"function buscando_personasCongreso(cual, valor, en_campo, form_id){\n\t\n//\tdocument.getElementById(form_id).style.color = \"#000000\";\n\n\tif(valor==\"\"){\n\t\t$(\"#\"+cual).css(\"display\",\"none\");\t\n\t}else{\n\t\t$(\"#\"+cual).css(\"display\",\"\");\n\t}\n\tpetision(\"buscarPersonasCongreso_ajax.php\", cual, \"POST\", \"str_persona=\" + valor + \"&en_campo=\"+en_campo)\n}",
"function click_btn_revision(){\n\t$(\"#btn_revision\").click(function(){\n\t\tif( $('#div_revision').is(\":visible\") ){\n\t\t\t//si esta visible\n\t\t}else{\n\t\t\t//si no esta visible\n\t\t\t$('#texto_seleccion').text('SELECCIONE UNA INSPECCIÓN');\n\t\t\t$('#div_btn_informe_inicial').hide('fast');\n\t\t\t$('#div_btn_eliminadas').hide('fast');\n\t\t\t$('#div_btn_revision').hide('fast');\n\t\t\t$('#div_revision').show('fast'); //muetras el div\n\t\t\t$('#div_btn_regresar').show('fast');\n\t\t}\n \t});\n}",
"function active_interface(id){\n var num_select = -1; \n var id_select = -1; \n for(i=0;i<Tableau_interfaces.length;i++){\n if(Tableau_interfaces[i]['id'] == id) {\n num_select = i;\n id_select = id;\n break;\n }\n }\n if(num_select != -1){\n num_page = Math.floor(num_select/taille_tableau_content_page['interface']);\n num_in_page = num_select - num_page * taille_tableau_content_page['interface'];\n go_page_interface(num_page);\n affich_active_interface(num_in_page)\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1 create folders 2 create package.json 3 create config 4 create logger 5 create server 6 create models 7 create routes 8 create app | function generate(opts){
let models = opts.models;
let appName = opts.appname;
let routes = opts.models.map(model => model.name);
console.log("Starting to Create CRUD API Boilerplate...");
console.log("Creating Server Folders...");
fileCreator.createServerTree(appName);
console.log("Creating 'package.json' ...");
pkgCreator(appName);
console.log("Creating Config Files ...");
configCreator(appName);
console.log("Creating Cache Files ...");
cacheCreator(appName);
console.log("Creating Logger Files ...");
loggerCreator(appName);
console.log("Creating Server Files ...");
binCreator(appName);
console.log("Creating Model Files ...");
modelCreator(appName, models);
console.log("Creating Route Files ...");
routeCreator(appName, models);
console.log("Creating App File ...");
serverCreator(appName, STDPACKAGES, routes);
console.log("Done !");
} | [
"async function startExpressApp() {\n const express = require(\"express\");\n const app = express();\n const path = require('path');\n\n const { landingPageCors } = require('@/middlewares/cors');\n app.use(landingPageCors);\n \n const bodyParser = require(\"body-parser\");\n app.use(bodyParser.json());\n \n const cookieParser = require(\"cookie-parser\");\n app.use(cookieParser());\n\n const responsesMiddleware = require(\"@/middlewares/responses\");\n app.use(responsesMiddleware);\n \n const routes = require(\"@/app/routes\");\n app.use(\"/v1\", routes);\n\n app.use((err, req, res, next) => {\n console.log(err);\n res.serverError();\n });\n\n app.use((req, res) => res.notFound());\n\n app.listen(APP_PORT, () => {\n console.log(`Server listening on port ${APP_PORT}`);\n });\n}",
"_setupRoutes() {\n // For requests to webhook handler path, make the webhook handler take care\n // of the requests.\n this.server.post(this.webhookOptions.path, (req, res, next) => {\n this.handler(req, res, error => {\n res.send(400, 'Error processing hook');\n this.logger.error({err: error}, 'Error processing hook');\n\n next();\n });\n });\n\n this.server.post('/builds/:bid/status/:context', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n this.server.post('/update', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n\n this.server.get('/pull-request/:owner/:repo/:pullRequestNumber', this.getPullRequest.bind(this));\n }",
"function app_init() {\r\n global = lib('globals');\r\n server = lib('server');\r\n app = lib('application');\r\n sys = app.sys = lib('system');\r\n req = app.req = lib('request');\r\n res = app.res = lib('response');\r\n req.router = lib('router');\r\n app.model = lib('model');\r\n app.util = lib('util');\r\n res.clear();\r\n trigger('ready');\r\n trigger('route');\r\n res.end();\r\n}",
"function taskResolveApiFiles() {\n createFolder()\n const fileArray = glob\n .sync('src/api/**/*.ts')\n .filter(f => path.basename(f) !== 'routes.ts')\n\n const imports = fileArray\n .map((f, i) => `import { router as r${i} } from '${format(f)}'`)\n .join('\\n')\n const uses = fileArray\n .map((f, i) => ` app.use('/${path.basename(f, '.ts')}', r${i});`)\n .join('\\n')\n\n const content = `import { Express } from 'express'\n${imports}\n\nexport function useRoutes(app: Express) {\n${uses}\n}`\n\n function format(s) {\n return './' + s.substring(8, s.length - 3)\n }\n\n const file_path = 'src/api/routes.ts'\n let msg\n if (fs.existsSync(file_path)) {\n msg = `\"${file_path}\" overwritten`\n } else {\n msg = `\"${file_path}\" created`\n }\n fs.writeFileSync(file_path, content)\n console.log(msg)\n}",
"async _createApi(plane) {\n let app = new Koa();\n\n // Make the plane available to the routes.\n app.context.plane = plane;\n\n app.use(koaLogger());\n\n // Set up the router middleware.\n app.use(router.routes());\n app.use(router.allowedMethods());\n\n // Start and wait until the server is up and then return it.\n return await new Promise((resolve, reject) => {\n let server = app.listen(this._port, (err) => {\n if (err) reject(err);\n else resolve(server);\n });\n\n // Add a promisified close method to the server.\n server.closeAsync = () => new Promise((resolve) => {\n server.close(() => resolve());\n });\n });\n }",
"async function initialize() {\n const artStories = await getStories();\n\n /* Routes */\n app.use('/api/art', (req, res) => {\n res.send(artStories);\n });\n // Serve static files\n app.use(express.static('build'));\n /* Listen */\n app.listen(PORT, () => {\n console.log(`Listening on port: ${PORT}`);\n });\n}",
"constructor() {\n this.router = express.Router(); // eslint-disable-line new-cap\n this.logger = new Logger();\n this.contr = new Controller();\n }",
"register() {\n this._container.instance('expressApp', require('express')())\n\n //TODO: add Socket.io here @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n\n this._container.register('httpServing', require(FRAMEWORK_PATH + '/lib/HTTPServing'))\n .dependencies('config', 'expressApp')\n .singleton()\n\n this._container.instance('expressRouterFactory', () => {\n return require('express').Router()\n })\n\n this._container.register('RoutesResolver', require(FRAMEWORK_PATH + '/lib/RoutesResolver'))\n .dependencies('logger', 'app', 'expressRouterFactory')\n\n this._container.register('httpErrorHandler', require(FRAMEWORK_PATH + '/lib/HTTPErrorHandler'))\n .dependencies('logger')\n .singleton()\n\n //TODO: add WS the serving @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n }",
"function setupRoutes(app) {\n const base = app.locals.base;\n app.use(cors());\n app.post(`${base}/${IMAGES}/:group`,\n\t upload.single(IMG_FIELD), createImage(app));\n app.get(`${base}/${IMAGES}/:group/:name.:type`, getImage(app));\n app.get(`${base}/${IMAGES}/:group/:name/meta`, getMeta(app));\n app.get(`${base}/${IMAGES}/:group`, listImages(app));\n app.post(`${base}/${STEG}/:group/:name`, bodyParser.json(), stegHide(app));\n app.get(`${base}/${STEG}/:group/:name`, stegUnhide(app));\n}",
"async nuxtServerInit({ commit, dispatch }) {\n var articles = await require.context(\"~/articles/\", false, /\\.md$/);\n let articlesList = await dispatch('prepareMarkdown', articles);\n await commit(\"setBlogList\", articlesList);\n\n var projects = await require.context(\"~/projects/\", false, /\\.md$/);\n let projList = await dispatch('prepareMarkdown', projects);\n await commit(\"setProjectList\", projList);\n }",
"makeServer() {\n this.server = http.Server(this.app);\n }",
"function createApp(opts, cb) {\n\n var appName = opts.appName\n , port = opts.port;\n\n function _copy(src, dst, cb) {\n fs.stat(src, function(err, stat) {\n if (err) return cb(err);\n if (stat.isDirectory()) {\n return fs.mkdir(dst, function(err) {\n if (err) return cb(err);\n fs.readdir(src, function(err, files) {\n if (err) return cb(err);\n async.each(files, function(file, cb) {\n _copy(path.join(src, file), path.join(dst, file), cb);\n }, cb);\n });\n });\n } else if (stat.isFile())\n _compile(src, dst, cb);\n });\n }\n\n function _compile(src, dst, cb) {\n fs.readFile(src, 'utf-8', function(err, text) {\n if (err) return cb(err);\n var compiled = _.template(text)({\n appName: appName,\n port: port\n });\n fs.writeFile(dst, compiled, 'utf-8', cb);\n });\n }\n\n var target = path.join(process.cwd(), appName);\n var archetype = path.join(__dirname, '../archetype');\n _copy(archetype, target, function(err) {\n if (err) return cb(err);\n console.log('\\n\\nApplication created successfully.\\n\\n');\n console.log('1. Go to your project\\n\\n\\tcd %s\\n\\n', appName);\n console.log('2. Install dependencies\\n\\n\\tnpm install\\n\\n');\n console.log('3. Run your application\\n\\n\\tnode run\\n\\n');\n });\n}",
"function main() {\n\tconsole.log('Abacus iPad App Generator.');\n console.log('Create flat basic styled app from converted spreadhseet.');\n\tDU.displayTag();\n\n\tif(ops.version){\n\t\tprocess.exit();\n\t}\n\n\tif(!ops.repoPath){\n\t\tconsole.error('Missing argument: --repoPath');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif(!ops.engine){\n\t\tconsole.error('Missing argument: --engine');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif (ops.instance){\n\t\tconfig.instance = S(ops.instance).slugify().s;\n\t}\n\n\tif(ops.language){\n\t\tconfig.language = ops.language;\n\t}\n\n\tif(ops.noExtract){\n\t\tconfig.extractEngine = false;\n\t}\n\n\tif(ops.numeric){\n\t\tconfig.usePageNames = false;\n\t}\n\n\t// mandatory arguments\n\tconfig.repoPath = ops.repoPath;\n\tconfig.engineFile = ops.engine;\n\n\t// call extract, pass in config\n\tAG.generate(config);\n}",
"function generateModels(ctx) {\n // Create Models\n var template = fs.readFileSync(\n require.resolve('./shared/model.ejs'),\n { encoding: 'utf-8' }\n );\n var results = [];\n var result;\n for (var modelName in ctx.models) {\n var meta = ctx.models[modelName];\n // capitalize the model name\n modelName = modelName[0].toUpperCase() + modelName.slice(1);\n result = ejs.render(template, {\n moduleName: ctx.moduleName,\n modelName: modelName,\n model: meta,\n urlBase: ctx.apiUrl.replace(/\\/+$/, ''),\n getModelType: getModelType\n });\n if (ctx.outputFolder) {\n ctx.outputFolder = path.resolve(ctx.outputFolder);\n fs.writeFileSync(\n ctx.outputFolder + '/models/' + modelName + '.ts',\n result\n );\n }\n results.push(result);\n }\n // Create Models index\n var indexTemplate = fs.readFileSync(\n require.resolve('./shared/models.ejs'),\n { encoding: 'utf-8' }\n );\n result = ejs.render(indexTemplate, {\n moduleName: ctx.moduleName,\n models: ctx.models,\n urlBase: ctx.apiUrl.replace(/\\/+$/, '')\n });\n if (ctx.outputFolder) {\n ctx.outputFolder = path.resolve(ctx.outputFolder);\n console.error('Saving the generated services source to %j', ctx.outputFolder);\n fs.writeFileSync(ctx.outputFolder + '/models/index.ts', result);\n }\n results.push(result);\n return results;\n}",
"addRoutes (router, socket) {\n // get all routes\n // NOTE: make relative\n glob('./server/api/routes/**/*.js', (err, routes) => {\n if (err) console.log(err)\n // dynamically require all files\n _.each(routes, (routePath) => {\n var route = routePath\n route = route.replace('./server/api/routes', '').replace('.js', '/')\n require(path.resolve(routePath))(router, socket, route)\n })\n })\n }",
"loadApp() {\n if (fs.existsSync(this.mainDir)) {\n eachDir(this.mainDir, (dirname) => {\n let dir = path.join(this.mainDir, dirname);\n let type = singularize(dirname);\n\n glob.sync('**/*', { cwd: dir }).forEach((filepath) => {\n let modulepath = withoutExt(filepath);\n if (filepath.endsWith('.js')) {\n let Class = require(path.join(dir, filepath));\n Class = Class.default || Class;\n this.container.register(`${ type }:${ modulepath }`, Class);\n } else if (filepath.endsWith('.json')) {\n let mod = require(path.join(dir, filepath));\n this.container.register(`${ type }:${ modulepath }`, mod.default || mod);\n }\n });\n });\n }\n }",
"setupDirs() {\n mkdirp.sync(__dirname+\"/../\"+config.files.dir);\n mkdirp.sync(__dirname+\"/../\"+config.qrcodes.dir);\n }",
"function serve() {\n const express = require('express');\n const helmet = require('helmet');\n const compression = require('compression');\n\n const app = express();\n app.use(helmet());\n app.use(compression());\n app.use(express.static(config.PUBLIC_PATH));\n\n // Redirect 404s\n app.get('*', (request, reply) => {\n reply.redirect('/');\n });\n\n // Start the server\n const port = process.env.PORT || 3000;\n let listener = app.listen(port, () => {\n console.log(chalk.bold.green(`Listening on port ${port}`));\n });\n\n // Enable auto restarting in development\n if (process.env.NODE_ENV !== 'production') {\n const enableDestroy = require('server-destroy');\n enableDestroy(listener);\n\n // Recompile on changes to anything\n [config.POSTS_PATH, config.TEMPLATES_PATH].forEach(path => {\n fs.watch(path, { recursive: true }, async (event, filename) => {\n // Recompile posts\n await compile();\n\n // Purge all connections and close the server\n listener.destroy();\n listener = app.listen(port);\n\n // Set up connection tracking so that we can destroy the server when a file changes\n enableDestroy(listener);\n });\n });\n }\n}",
"async function generate() {\n // get all of the files in this directory\n fs.readdirSync(__dirname)\n .filter((file) => {\n // filter include files with pattern *.json\n return (file.indexOf('.') !== 0) && (file.slice(-5) === '.json');\n })\n .forEach(async (file) => {\n // compile & write ts file for each json schema file\n fs.writeFileSync(\n __dirname + '/../src/shared/schemas/' + file.substring(0, file.length-5) + '.ts',\n await compileFromFile(file),\n );\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
$http DELETE function, id = TodoListEntryId | function deleteToDos(id) {
var defer = $q.defer();
$http({
method: 'DELETE',
url: 'http://localhost:50341/api/ToDoListEntries/' + id
}).then(function(response) {
if (typeof response.data === 'object') {
defer.resolve(response);
toastr.success('Deleted ToDo List Item!');
} else {
defer.reject(response);
//error if found but empty
toastr.warning('Failure! </br>' + response.config.url);
}
},
// failure
function(error) {
//error if the file isn't found
defer.reject(error);
$log.error(error);
toastr.error('error: ' + error.data + '<br/>status: ' + error.statusText);
});
return defer.promise;
} | [
"deleteById(id) {\n return this.del(this.getBaseUrl() + '/' + id);\n }",
"function deleteTodo(id) {\n //action\n return {\n type: \"DELETE_TODO\",\n id\n };\n}",
"deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }",
"function deleteTask(req, res) {\n var id = req.params.id;\n\n knex('task_items').where('id', id)\n .delete()\n .then(function () {\n res.sendStatus(204);\n }).catch(function (err) {\n console.log('Error Querying the DB', err);\n });\n}",
"deleteAction(req, res) {\n Robot.remove({ _id: req.params.id }, (err, robot) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 204, { 'message': 'Deleted successfully!' });\n });\n }",
"function remove(id) {\n return db(\"todos\")\n .where({ id })\n .del();\n}",
"function deleteBusiness(businessid) {\n console.log('deleteBusiness = ', deleteBusiness);\n $http({\n method: 'DELETE',\n url: '/business/delete' + businessid // NOTE: changing path resulted with this error: DELETE http://localhost:5500/mainPage/deleteMustMatc26 404 (Not Found)\n }).then(function(response) {\n getBusiness();\n });\n console.log('delete from business.factory.js'); // NOTE: 02: logging ok!\n } // NOTE: for: function deleteBusiness",
"function deleteAthlete(event) {\n event.stopPropagation();\n var id = $(this).data(\"id\");\n $.ajax({\n method: \"DELETE\",\n url: \"/api/athletes/\" + id\n }).then(getAthletes);\n }",
"delete(req, res) {\n Origin.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function (deletedRecords) {\n res.status(200).json(deletedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"deleteList(req, res, next) {\n listsHelper.deleteList(req.params.listId, req.reqId).then(() => {\n res.status(201);\n res.json({\n success: 1,\n message: responseMessages.listDeleted.success,\n data: {},\n });\n }).catch((error) => {\n next(error);\n });\n }",
"deleteEvent (eventId) {\n assert.equal(typeof eventId, 'number', 'eventId must be number')\n return this._apiRequest(`/event/${eventId}`, 'DELETE')\n }",
"delete(id) {\n return this.send(\"DELETE\", `events/${id}`);\n }",
"function DeleteTrackById(req, res) {\n\t// Deletes the artist by ID, get ID by req.params.artistId\n}",
"function deleteTipoProducto(req, res){\n \n const id = req.params.id;\n console.log(id)\n ModelTipoProducto.findByIdAndRemove( id, (err, doctipoProducto) => {\n\n if( err || !doctipoProducto ) return errorHandler(doctipoProducto, next, err)\n\n return res.json({\n data: doctipoProducto\n })\n })\n}",
"function putToDos(id, data) {\n\n var defer = $q.defer();\n\n $http({\n method: 'PUT',\n url: 'http://localhost:50341/api/ToDoListEntries/' + id,\n data: data\n }).then(function(response) {\n if (typeof response.data === 'object') {\n defer.resolve(response);\n toastr.success('Updated ToDo List Item!');\n } else {\n defer.reject(response);\n //error if found but empty\n toastr.warning('Failure! </br>' + response.config.url);\n }\n },\n // failure\n function(error) {\n //error if the file isn't found\n defer.reject(error);\n $log.error(error);\n toastr.error('error: ' + error.data + '<br/>status: ' + error.statusText);\n });\n\n return defer.promise;\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('shortlink_shortlink', 'delete', kparams);\n\t}",
"function deleteUrl(id) {\n var urlRef = new Firebase(baseUrl + '/savedApis/' + id);\n urlRef.remove();\n $('li').attr('data-id',id).remove();\n getApiList();\n}",
"function deleteIssue(id) {\n var url = 'http://localhost:1234/whap/issues?ID=';\n deleteData(url, id)\n .catch(rejected => {\n alert(\"Somehow ya broke it\\n\" +\n \"Don't know how but ya did\");\n });\n}",
"handleDeleteItems(e){\n\t\tconst id = e.target.attributes.keyset.value\n\t\tActions.deleteTodo(id)\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes index of a section Calculates the starting and ending point of its arc Returns a random point between them | function getPoint(index) {
let min = (wheel.numOfSections - index - 1) * wheel.arc + 0.005;
let max = (wheel.numOfSections - index) * wheel.arc - 0.005;
return random(min, max);
} | [
"function getNextAttractor() {\n let lastpoint = this.getLastAttractor();\n let endpoint = getRandomEndpoint.apply(this);\n let midpoint = getMidpoint(lastpoint, endpoint);\n\n this.addAttractor(midpoint);\n\n return midpoint;\n}",
"function generateArcPoints(length, elevation, sx, sy, hdg, curvature, lateralOffset) {\n\n\tvar points = [];\n\tvar heading = [];\n\tvar tOffset = [];\n\tvar sOffset = [];\t// sOffset from the beginning of the curve, used for distribute error\n\tvar currentHeading = hdg;\n\tvar prePoint, x, y, z;\n\n\tif (!elevation) {\n\t\televation = {s:0,a:0,b:0,c:0,d:0};\n\t}\n\n\t// s ranges between [0, length]\n\tvar s = 0;\n\tvar preS = 0;\n\n\tdo {\n\t\t\n\t\tif (s == 0) {\n\t\t\tpoints.push(new THREE.Vector3(sx, sy, elevation.a));\t\t\n\t\t\theading.push(currentHeading);\n\t\t\tif (lateralOffset) tOffset.push(lateralOffset.a);\n\t\t\tsOffset.push(s);\n\t\t\ts += step;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (s > length || Math.abs(s - length) < 1E-4) {\t\t\n\t\t\ts = length;\n\t\t}\n\n\t\tprePoint = points[points.length - 1];\n\n\t\tx = prePoint.x + (s - preS) * Math.cos(currentHeading + curvature * (s - preS) / 2);\n\t\ty = prePoint.y + (s - preS) * Math.sin(currentHeading + curvature * (s - preS) / 2);\n\t\tz = cubicPolynomial(s, elevation.a, elevation.b, elevation.c, elevation.d);\n\n\t\tcurrentHeading += curvature * (s - preS);\n\t\t\n\t\tpreS = s;\n\t\ts += step;\n\n\t\tpoints.push(new THREE.Vector3(x, y, z));\n\t\theading.push(currentHeading);\n\t\tif (lateralOffset) tOffset.push(cubicPolynomial(preS, lateralOffset.a, lateralOffset.b, lateralOffset.c, lateralOffset.d));\n\t\tsOffset.push(preS);\n\n\t} while (s < length + step);\n\n\t// apply lateral offset along t, and apply superelevation, crossfalls if any\n\tif (lateralOffset) {\n\n\t\tvar svector, tvector, hvector;\n\n\t\t// shift points at central clothoid by tOffset to get the parallel curve points\n\t\tfor (var i = 0; i < points.length; i++) {\n\n\t\t\tvar point = points[i];\n\t\t\tvar t = tOffset[i];\n\t\t\tvar currentHeading = heading[i];\n\t\t\tvar ds = sOffset[i];\n\n\t\t\tsvector = new THREE.Vector3(1, 0, 0);\n\t\t\tsvector.applyAxisAngle(new THREE.Vector3(0, 0, 1), currentHeading);\n\t\t\ttvector = svector.clone();\n\t\t\ttvector.cross(new THREE.Vector3(0, 0, -1));\n\n\t\t\thvector = svector.clone();\n\t\t\thvector.cross(tvector);\n\n\t\t\ttvector.multiplyScalar(t);\n\t\t\thvector.multiplyScalar(0);\t// no height\n\n\t\t\tpoint.x += tvector.x + hvector.x;\n\t\t\tpoint.y += tvector.y + hvector.y;\n\t\t\tpoint.z += tvector.z + hvector.z;\n\t\t}\n\t}\n\n\treturn {points: points, heading: heading};\n}",
"function drawArc(texte, e1, e2, a, k, num_arc, coordonnees, first, p) {\n\n var x = 140 + (a - 1) * 180,\n y = 55 + (4 - e1) * 50 - (e2 - e1) * 25,\n h = 2 + (e2 - e1) * 50,\n x1, x2, x3, x4, y1, y2, y3, y4;\n\n if (first) {\n first = false;\n\n if (k % 2 == 0) {\n\n if (e2 < e1) {\n coordonnees[num_arc][0] = x - 30 + 50 * ((k + 1) / 2) + (e1 - e2 - 1) * 15;\n coordonnees[num_arc][1] = y;\n } else {\n coordonnees[num_arc][0] = x - 30 - 50 * ((k + 1) / 2) - (e1 - e2 - 1) * 15;\n coordonnees[num_arc][1] = y;\n }\n } else {\n\n if (e2 >= e1) {\n coordonnees[num_arc][0] = x + 50 * ((k + 1) / 2) + (e2 - e1 - 1) * 15;\n coordonnees[num_arc][1] = y;\n } else {\n coordonnees[num_arc][0] = x - 55 - 50 * (k + 1) / 2 - (e2 - e1 - 1) * 15 + 30;\n coordonnees[num_arc][1] = y;\n }\n }\n var arc_div = document.createElement('div');\n arc_div.className = \"arc\";\n arc_div.id = num_arc;\n\n document.getElementById(\"sketch-auto\").appendChild(arc_div);\n arc_div.onmousedown = function(evt) {\n traine = true;\n xi = num_arc;\n xj = 0;\n yi = num_arc;\n yj = 1;\n }\n\n }\n\n if (selectedGenes[a-1]){\n if (k % 2 == 0) {\n\n if (e2 < e1) {\n x1 = x4 = x;\n y1 = y + 26 + (e1 - e2 - 1) * 25;\n y4 = y - 26 - (e1 - e2 - 1) * 25;\n p.line(x, y - h / 2, x + 8, y - h / 2 - 8);\n p.line(x, y - h / 2, x + 8, y - h / 2 + 8);\n p.noFill();\n p.bezier(x1, y1, coordonnees[num_arc][0], coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][0], coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, x4, y4);\n xx = p.bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx, yy + 10);\n p.textSize(10);\n } else {\n x1 = x4 = x - 18;\n y1 = y + 24 + (e2 - e1 - 1) * 25;\n y4 = y - 26 - (e2 - e1 - 1) * 25;\n p.line(x - 26, y - h / 2 - 9, x - 19, y - h / 2 - 1);\n p.line(x - 26, y - h / 2 + 7, x - 19, y - h / 2 - 1);\n p.noFill();\n p.bezier(x1, y1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, x4, y4);\n xx = p.bezierPoint(x1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][0] - 18, x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx, yy - 10);\n p.textSize(10);\n }\n } else {\n\n if (e2 >= e1) {\n x1 = x4 = x;\n y1 = y + 26 + (e2 - e1 - 1) * 25;\n y4 = y - 26 - (e2 - e1 - 1) * 25;\n p.line(x, y - h / 2, x + 7, y - h / 2 - 8);\n p.line(x, y - h / 2, x + 7, y - h / 2 + 8);\n p.noFill();\n p.bezier(x1, y1, coordonnees[num_arc][0], coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][0], coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, x4, y4);\n xx = p.bezierPoint(x1, coordonnees[num_arc][0], coordonnees[num_arc][0], x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e2 - e1 - 1) * 25 + 20, coordonnees[num_arc][1] - (e2 - e1 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx + 10, yy);\n p.textSize(10);\n\n\n } else {\n x1 = x4 = x - 18;\n x2 = x3 = x - 55 - 50 * (k + 1) / 2 - (e2 - e1 - 1) * 15;\n y1 = y + 24 + (e1 - e2 - 1) * 25;\n y4 = y - 26 - (e1 - e2 - 1) * 25;\n p.line(x - 26, y - h / 2 - 9, x - 19, y - h / 2 - 1);\n p.line(x - 26, y - h / 2 + 7, x - 19, y - h / 2 - 1);\n p.noFill();\n p.bezier(x1, y1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][0] - 18, coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, x4, y4);\n xx = p.bezierPoint(x1, coordonnees[num_arc][0] - 18, coordonnees[num_arc][0] - 18, x4, 1 / 2);\n yy = p.bezierPoint(y1, coordonnees[num_arc][1] + (e1 - e2 - 1) * 25 + 20, coordonnees[num_arc][1] - (e1 - e2 - 1) * 25 - 20, y4, 1 / 2);\n p.fill(0, 0, 255);\n p.textSize(15);\n p.text(texte, xx - 10, yy);\n p.textSize(10);\n\n }\n }\n var margeY = document.getElementById(\"sketch-auto\").offsetTop;\n var margeX = document.getElementById(\"sketch-auto\").offsetLeft;\n divs[num_arc].style.top = margeY + yy - 7.5 + \"px\" ;\n divs[num_arc].style.left = margeX + xx - 7.5 + \"px\";\n p.fill(255);\n p.ellipse(xx, yy, 5, 5);\n\n function move(evt) {\n if (traine) {\n p.clear();\n coordonnees[xi][xj] = p.mouseX + 15;\n coordonnees[yi][yj] = p.mouseY;\n }\n }\n\n function stopTraine() {\n traine = false;\n }\n\n\n document.getElementById(\"sketch-auto\").onmousemove = move;\n document.getElementById(\"sketch-auto\").onmouseup = stopTraine;\n\n }\n\n}",
"static generateRandomAngle() {\n return Math.random() * Math.PI * 2;\n }",
"function randomPoint() { return pick(points); }",
"function getPivotIndex(startIndex, endIndex) {\n return startIndex + Math.floor(Math.random() * (endIndex - startIndex));\n}",
"function indexAlgorithm(){\n\tvar temp = [];\n\tvar offset = 36;\n\tvar totalPoints = (revA.length/3);\n\tvar i = 0;\n\tfor (i = 0; i < totalPoints-offset; i++){\n\t\tif (i != 0 && (i+1) % 36 == 0) {\n\t\t\ttemp.push(i);\n\t\t\ttemp.push(i-35);\n\t\t\ttemp.push(i+offset);\n\t\t\t\n\t\t\ttemp.push(i-35);\n\t\t\ttemp.push(i+offset);\n\t\t\ttemp.push(i-35+offset);\n\t\t} else {\n\t\t\ttemp.push(i);\n\t\t\ttemp.push(i+1);\n\t\t\ttemp.push(i+offset);\n\t\t\t\n\t\t\ttemp.push(i+1);\n\t\t\ttemp.push(i+1+offset);\n\t\t\ttemp.push(i+offset);\n\t\t}\n\t}\n\ttemp.push(i-offset);\n\treturn temp;\n}",
"addArcTo(midX, midY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const startPoint = this._points[this._points.length - 1];\n const midPoint = new Vector2_1.Vector2(midX, midY);\n const endPoint = new Vector2_1.Vector2(endX, endY);\n const arc = new Arc2_1.Arc2(startPoint, midPoint, endPoint);\n let increment = arc.angle.radians() / numberOfSegments;\n if (arc.orientation === types_1$1.Orientation.CW) {\n increment *= -1;\n }\n let currentAngle = arc.startAngle.radians() + increment;\n for (let i = 0; i < numberOfSegments; i++) {\n const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;\n const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;\n this.addLineTo(x, y);\n currentAngle += increment;\n }\n return this;\n }",
"static generateRandomCardIndex() {\n let random = Math.floor(Math.random() * Math.floor(maxCard));\n return random;\n //return Math.floor(Math.random() * (+max - +min)) + +min;\n }",
"function ArcInfo(startAngle, stopAngle, r)\n{\n this.startAngle = startAngle;\n this.stopAngle = stopAngle;\n this.r = r;\n this.xp1 = Math.round(1000*Math.cos(startAngle));\n this.yp1 = Math.round(1000*Math.sin(startAngle));\n this.xp2 = Math.round(1000*Math.cos(stopAngle));\n this.yp2 = Math.round(1000*Math.sin(stopAngle));\n \n var angle = stopAngle - startAngle;\n if (angle < 0)\n angle += 2*Math.PI;\n if (angle > 2*Math.PI)\n angle -= 2*Math.PI;\n \n this.jumbo = (angle > Math.PI);\n this.angle = angle;\n}",
"function randomFromInterval(from,to){return Math.floor(Math.random()*(to-from+1)+from);}",
"generateDistTrav()\r\n {\r\n var distance = Math.floor((Math.random() * 2) + 1)\r\n console.log(distance + \"m\")\r\n }",
"function arcIntersections(cx, cy, r, startAngle, endAngle, counterClockwise, x1, y1, x2, y2) {\n // Solving the quadratic equation:\n // 1. y = k * x + y0\n // 2. (x - cx)^2 + (y - cy)^2 = r^2\n var k = (y2 - y1) / (x2 - x1);\n var y0 = y1 - k * x1;\n var a = Math.pow(k, 2) + 1;\n var b = 2 * (k * (y0 - cy) - cx);\n var c = Math.pow(cx, 2) + Math.pow(y0 - cy, 2) - Math.pow(r, 2);\n var d = Math.pow(b, 2) - 4 * a * c;\n if (d < 0) {\n return [];\n }\n var i1x = (-b + Math.sqrt(d)) / 2 / a;\n var i2x = (-b - Math.sqrt(d)) / 2 / a;\n var intersections = [];\n [i1x, i2x].forEach(function (x) {\n var isXInsideLine = x >= Math.min(x1, x2) && x <= Math.max(x1, x2);\n if (!isXInsideLine) {\n return;\n }\n var y = k * x;\n var a1 = normalizeAngle360(counterClockwise ? endAngle : startAngle);\n var a2 = normalizeAngle360(counterClockwise ? startAngle : endAngle);\n var intersectionAngle = normalizeAngle360(Math.atan2(y, x));\n // Order angles clockwise after the start angle\n // (end angle if counter-clockwise)\n if (a2 <= a1) {\n a2 += 2 * Math.PI;\n }\n if (intersectionAngle < a1) {\n intersectionAngle += 2 * Math.PI;\n }\n if (intersectionAngle >= a1 && intersectionAngle <= a2) {\n intersections.push({ x: x, y: y });\n }\n });\n return intersections;\n}",
"function diamond3() {\n return Math.floor(Math.random() * 11 + 1);\n }",
"function PathIndex(shapes, arcs) {\n var boundsQuery = getBoundsSearchFunction(getRingData(shapes, arcs));\n var totalArea = getPathBounds(shapes, arcs).area();\n\n function getRingData(shapes, arcs) {\n var arr = [];\n shapes.forEach(function(shp, shpId) {\n var n = shp ? shp.length : 0;\n for (var i=0; i<n; i++) {\n arr.push({\n ids: shp[i],\n id: shpId,\n bounds: arcs.getSimpleShapeBounds(shp[i])\n });\n }\n });\n return arr;\n }\n\n // Returns shape ids of all polygons that intersect point p\n // (p is inside a ring or on the boundary)\n this.findEnclosingShapes = function(p) {\n var ids = [];\n var cands = findPointHitCandidates(p);\n var groups = groupItemsByShapeId(cands);\n groups.forEach(function(group) {\n if (testPointInRings(p, group)) {\n ids.push(group[0].id);\n }\n });\n return ids;\n };\n\n // Returns shape id of a polygon that intersects p or -1\n // (If multiple intersections, returns one of the polygons)\n this.findEnclosingShape = function(p) {\n var shpId = -1;\n var groups = groupItemsByShapeId(findPointHitCandidates(p));\n groups.forEach(function(group) {\n if (testPointInRings(p, group)) {\n shpId = group[0].id;\n }\n });\n return shpId;\n };\n\n // Returns shape ids of polygons that contain an arc\n // (arcs that are )\n // Assumes that input arc is either inside, outside or coterminous with indexed\n // arcs (i.e. input arc does not cross an indexed arc)\n this.findShapesEnclosingArc = function(arcId) {\n var p = getTestPoint([arcId]);\n return this.findEnclosingShapes(p);\n };\n\n this.findPointEnclosureCandidates = function(p, buffer) {\n var items = findPointHitCandidates(p, buffer);\n return utils.pluck(items, 'id');\n };\n\n this.pointIsEnclosed = function(p) {\n return testPointInRings(p, findPointHitCandidates(p));\n };\n\n // Finds the polygon containing the smallest ring that entirely contains @ring\n // Assumes ring boundaries do not cross.\n // Unhandled edge case:\n // two rings share at least one segment but are not congruent.\n // @ring: array of arc ids\n // Returns id of enclosing polygon or -1 if none found\n this.findSmallestEnclosingPolygon = function(ring) {\n var bounds = arcs.getSimpleShapeBounds(ring);\n var p = getTestPoint(ring);\n var smallest;\n var cands = findPointHitCandidates(p);\n cands.forEach(function(cand) {\n if (cand.bounds.contains(bounds) && // skip partially intersecting bboxes (can't be enclosures)\n !cand.bounds.sameBounds(bounds) && // skip self, congruent and reversed-congruent rings\n !(smallest && smallest.bounds.area() < cand.bounds.area())) {\n if (testPointInRing(p, cand)) {\n smallest = cand;\n }\n }\n });\n\n return smallest ? smallest.id : -1;\n };\n\n this.arcIsEnclosed = function(arcId) {\n return this.pointIsEnclosed(getTestPoint([arcId]));\n };\n\n // Test if a polygon ring is contained within an indexed ring\n // Not a true polygon-in-polygon test\n // Assumes that the target ring does not cross an indexed ring at any point\n // or share a segment with an indexed ring. (Intersecting rings should have\n // been detected previously).\n //\n this.pathIsEnclosed = function(pathIds) {\n return this.pointIsEnclosed(getTestPoint(pathIds));\n };\n\n // return array of paths that are contained within a path, or null if none\n // @pathIds Array of arc ids comprising a closed path\n this.findEnclosedPaths = function(pathIds) {\n var b = arcs.getSimpleShapeBounds(pathIds),\n cands = boundsQuery(b.xmin, b.ymin, b.xmax, b.ymax),\n paths = [],\n index;\n\n if (cands.length > 6) {\n index = new PolygonIndex([pathIds], arcs);\n }\n cands.forEach(function(cand) {\n var p = getTestPoint(cand.ids);\n var isEnclosed = b.containsPoint(p[0], p[1]) && (index ?\n index.pointInPolygon(p[0], p[1]) : geom.testPointInRing(p[0], p[1], pathIds, arcs));\n if (isEnclosed) {\n paths.push(cand.ids);\n }\n });\n return paths.length > 0 ? paths : null;\n };\n\n this.findPathsInsideShape = function(shape) {\n var paths = []; // list of enclosed paths\n shape.forEach(function(ids) {\n var enclosed = this.findEnclosedPaths(ids);\n if (enclosed) {\n // any paths that are enclosed by an even number of rings are removed from list\n // (given normal topology, such paths are inside holes)\n paths = xorArrays(paths, enclosed);\n }\n }, this);\n return paths.length > 0 ? paths : null;\n };\n\n function testPointInRing(p, cand) {\n if (!cand.bounds.containsPoint(p[0], p[1])) return false;\n if (!cand.index && cand.bounds.area() > totalArea * 0.01) {\n // index larger polygons (because they are slower to test via pointInRing()\n // and they are more likely to be involved in repeated hit tests).\n cand.index = new PolygonIndex([cand.ids], arcs);\n }\n return cand.index ?\n cand.index.pointInPolygon(p[0], p[1]) :\n geom.testPointInRing(p[0], p[1], cand.ids, arcs);\n }\n\n //\n function testPointInRings(p, cands) {\n var isOn = false,\n isIn = false;\n cands.forEach(function(cand) {\n var inRing = testPointInRing(p, cand);\n if (inRing == -1) {\n isOn = true;\n } else if (inRing == 1) {\n isIn = !isIn;\n }\n });\n return isOn || isIn;\n }\n\n function groupItemsByShapeId(items) {\n var groups = [],\n group, item;\n if (items.length > 0) {\n items.sort(function(a, b) {return a.id - b.id;});\n for (var i=0; i<items.length; i++) {\n item = items[i];\n if (i === 0 || item.id != items[i-1].id) {\n groups.push(group=[]);\n }\n group.push(item);\n }\n }\n return groups;\n }\n\n function findPointHitCandidates(p, buffer) {\n var b = buffer > 0 ? buffer : 0;\n p[0]; p[1];\n return boundsQuery(p[0] - b, p[1] - b, p[0] + b, p[1] + b);\n }\n\n // Find a point on a ring to use for point-in-polygon testing\n function getTestPoint(ring) {\n // Use the point halfway along first segment rather than an endpoint\n // (because ring might still be enclosed if a segment endpoint touches an indexed ring.)\n // The returned point should work for point-in-polygon testing if two rings do not\n // share any common segments (which should be true for topological datasets)\n // TODO: consider alternative of finding an internal point of @ring (slower but\n // potentially more reliable).\n var arcId = ring[0],\n p0 = arcs.getVertex(arcId, 0),\n p1 = arcs.getVertex(arcId, 1);\n return [(p0.x + p1.x) / 2, (p0.y + p1.y) / 2];\n }\n\n // concatenate arrays, removing elements that are in both\n function xorArrays(a, b) {\n var xor = [], i;\n for (i=0; i<a.length; i++) {\n if (b.indexOf(a[i]) == -1) xor.push(a[i]);\n }\n for (i=0; i<b.length; i++) {\n if (a.indexOf(b[i]) == -1) xor.push(b[i]);\n }\n return xor;\n }\n}",
"function getTestPoint(ring) {\n // Use the point halfway along first segment rather than an endpoint\n // (because ring might still be enclosed if a segment endpoint touches an indexed ring.)\n // The returned point should work for point-in-polygon testing if two rings do not\n // share any common segments (which should be true for topological datasets)\n // TODO: consider alternative of finding an internal point of @ring (slower but\n // potentially more reliable).\n var arcId = ring[0],\n p0 = arcs.getVertex(arcId, 0),\n p1 = arcs.getVertex(arcId, 1);\n return [(p0.x + p1.x) / 2, (p0.y + p1.y) / 2];\n }",
"function drawArc(a, b, c) {\n const orient = b.x * (c.y - a.y) + a.x * (b.y - c.y) + c.x * (a.y - b.y);\n const sweep = (orient > 0) ? 1 : 0;\n const size = Point.distance(b, a);\n return [a.x, a.y + 'A' + size, size, 0, sweep, 1, c.x, c.y].join(',');\n}",
"function generateRefractors(){\n refractorSet.clear();\n let refractorRows = Math.floor(1.5 + simHeight / 300);\n let refractorCols = Math.floor(1.5 + simWidth / 300);\n\n let rowSpace = simHeight / (refractorRows);\n let colSpace = simWidth / (refractorCols);\n\n let triangleRadius = Math.min(rowSpace / 2 - (7 + simHeight / 50), colSpace / 2 - (7 + simWidth / 50));\n\n for(let i = 0; i < refractorCols; i ++)\n {\n for(let j = 0; j < refractorRows; j ++)\n {\n if(i != 0 || refractorRows % 2 == 0 || j != Math.floor(refractorRows / 2)){\n let center = new Vector(colSpace / 2 + colSpace * i, rowSpace / 2 + rowSpace * j);\n let ang = Math.random() * Math.PI * 2;\n let p1 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p2 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p3 = addVectors(angleMagVector(ang, triangleRadius), center);\n\n refractorSet.add(new SimVector(p1, subVectors(p2, p1)));\n refractorSet.add(new SimVector(p2, subVectors(p3, p2)));\n refractorSet.add(new SimVector(p3, subVectors(p1, p3)));\n }\n }\n }\n}",
"function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
That function is executed when the conference is joined | function onConferenceJoined() {
console.log('conference joined!');
isJoined = true;
for (let i = 0; i < localTracks.length; i++) {
room.addTrack(localTracks[i]);
}
} | [
"function onConferenceJoined() {\n //console.log('INFO (audience.js): Conference joined in silence!');\n $('#mainBtn').attr('disabled', false);\n /*room.sendTextMessage(details.nickName+\" joined the room..\");*/\n $.toast({\n text: 'You have joined the room as an audience.',\n icon: 'success',\n showHideTransition: 'fade',\n allowToastClose: false,\n hideAfter: 5000,\n stack: 5,\n\t loader: false,\n position: 'top-right',\n textAlign: 'left',\n bgColor: '#333333',\n textColor: '#ffffff'\n });\n}",
"function roomJoinListener (e) {\n state = GameStates.WAITING_FOR_OPPONENT;\n hud.setStatus(\"Waiting for opponent...\");\n initPlayers();\n}",
"function joinTimerListener (e) {\n hud.setStatus(\"Joining game...\");\n room.join();\n}",
"function mechanicsConference() {\n\tnextTurn();\n}",
"function joinRoom() {\n initSocket();\n initRoom();\n }",
"function roomJoinResultListener (e) {\n // If there are already two people playing, wait 5 seconds, then\n // attempt to join the game again (hoping that someone has left)\n if (e.getStatus() == Status.ROOM_FULL) {\n hud.setStatus(\"Game full. Next join attempt in 5 seconds.\");\n joinTimer.start();\n }\n}",
"function initParticipantActivityItems(localParticipant) {\n state.when('Conferenced', function () {\n addParticipantActivityItem('ParticipantJoined', localParticipant);\n state.equals('Conferenced').once(false, function () {\n addParticipantActivityItem('ParticipantLeft', localParticipant);\n });\n });\n participants.added(function (p) {\n p.isJoined.changed(function (val) {\n if (allowPActivityItems())\n addParticipantActivityItem(val ? 'ParticipantJoined' : 'ParticipantLeft', p);\n });\n });\n }",
"async function handleJoinedMeeting(e) {\n attendee = {\n ...e.participants.local,\n handRaised: false\n };\n\n let attendeeInformationDisplay = document.querySelector(\n \".local-participant-info\"\n );\n attendeeInformationDisplay.innerHTML = `\n <img\n id=\"hand-img\"\n class=\" is-pulled-right hidden\"\n src=\"assets/hand.png\"\n alt=\"hand icon\"\n /> \n\n <p class=\"name-label\"><strong>${attendee.user_name + \" (You)\" ||\n \"You\"}</strong></p>\n <button\n class=\"button is-info raise-hand-button\"\n onclick=\"changeHandState()\"\n >Raise Hand\n </button>\n <p class=\"hand-state has-text-right\">Your hand is down 💁</p>\n`;\n await handleParticipantUpdate();\n setTimeout(isHandRaised.sendAttendeeHandState, 2500)\n toggleLobby();\n toggleMainInterface();\n}",
"function joinChatRoom() {\n socketRef.current.emit(\"join chat\", { name, room: roomID });\n }",
"function handlePlayerJoinedEvent(data) {\n if (data.uID === uID) {\n if (data.joinSuccess) {\n\n //set team background colour\n if (data.team === 0) {\n userTeam = 'red-team';\n teamColors = ColorService.getRedColors();\n } else if (data.team === 1) {\n userTeam = 'blue-team';\n teamColors = ColorService.getBlueColors();\n }\n\n // set the specials and gamestate\n specialPowers = SpecialPowerManagerService.setupSpecials(data.specials);\n gameState = data.state;\n lane = data.lane;\n heroClass = data.heroClass;\n\n joinPromise.resolve(data);\n } else {\n joinPromise.reject(data);\n }\n }\n }",
"onPlayed () {\n UIManager.setStatusCast(UIManager.status.READY);\n UIManager.showSplashScreen();\n\n this.isCompleted = true;\n if (this.endedCallback !== null) {\n this.endedCallback();\n }\n\n this.notifySenders.apply(this, arguments);\n\n logger.info(LOG_PREFIX, 'Played');\n }",
"addConferenceWin() {\n this.addLeagueWin();\n this.#records[\"conference\"].addWin();\n }",
"function autoConnectionBroadcastersHandler() {\n\tif (autoStart && !isView && !isAdmin) { // auto-join-room for broadcasters\n\t\tDEBUG && console.log('Broadcasters auto-join-room');\n\t\trecheckSetupParams();\n\t\tdisableUIElements();\n\t\tstartJoinRoom();\n\t}\n}",
"function onParticipantVideo(status, resource, event) {\n var scope = event['in'];\n if (event.sender.href == rConversation.href && scope) {\n if (scope.rel == 'localParticipant') {\n switch (event.type) {\n case 'added':\n case 'updated':\n activeModalities.video = true;\n if (isConferencing()) {\n selfParticipant[Internal.sInternal].setMediaSourceId(event);\n updateMediaRoster(selfParticipant, isInMediaRoster(selfParticipant) ? 'update' : 'add');\n // check participants that are already in the conference - we need their msis\n // because we won't receive \"participantVideo added\" events for them.\n participants.each(function (p) {\n if (!isInMediaRoster(p) && p[Internal.sInternal].audioSourceId() != -1)\n updateMediaRoster(p, 'add');\n });\n }\n videoState(Internal.Modality.State.Connected);\n selfParticipant[Internal.sInternal].videoState(Internal.Modality.State.Connected);\n break;\n case 'deleted':\n removeVideo(selfVideoStream, true);\n activeModalities.video = false;\n if (isConferencing()) {\n if (isInMediaRoster(selfParticipant))\n updateMediaRoster(selfParticipant, 'remove');\n selfParticipant[Internal.sInternal].setMediaSourceId(event);\n }\n videoState(Internal.Modality.State.Disconnected);\n selfParticipant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);\n break;\n default:\n assert(false, 'unexpected event type');\n }\n }\n else if (scope.rel == 'participant') {\n Task.wait(getParticipant(scope.href)).then(function (participant) {\n switch (event.type) {\n case 'added':\n case 'updated':\n if (isConferencing()) {\n participant[Internal.sInternal].setMediaSourceId(event);\n updateMediaRoster(participant, isInMediaRoster(participant) ? 'update' : 'add');\n participant[Internal.sInternal].videoState(Internal.Modality.State.Connected);\n }\n else {\n participant[Internal.sInternal].setVideoStream(mainVideoStream);\n participant[Internal.sInternal].videoState(Internal.Modality.State.Connected);\n }\n break;\n case 'deleted':\n if (isConferencing()) {\n if (isInMediaRoster(participant))\n updateMediaRoster(participant, 'remove');\n participant[Internal.sInternal].setMediaSourceId(event);\n removeParticipantVideo(participant);\n participant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);\n // if participant video is deleted not because we stopped video\n // subscription explicitly (via isStarted(false)) but because \n // participant left the AV call then we need to reset isStarted.\n participant[Internal.sInternal].setVideoStarted(false);\n }\n else {\n participant[Internal.sInternal].setVideoStream(null);\n participant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);\n }\n break;\n default:\n assert(false, 'unexpected event type');\n }\n });\n }\n }\n }",
"function generateNewMeetingRoomName() {\n console.log(\"generate meeting room name\")\n sendEvent(\"create-room\", localVideoCallerId, {})\n\n}",
"function onParticipantAudio(status, resource, event) {\n var scope = event['in'];\n if (event.sender.href == rConversation.href && scope) {\n if (scope.rel == 'localParticipant') {\n switch (event.type) {\n case 'added': // signal for the initial AV session\n case 'updated':\n if (isConferencing())\n selfParticipant[Internal.sInternal].setMediaSourceId(event);\n activeModalities.audio = true;\n audioState(Internal.Modality.State.Connected);\n break;\n case 'deleted':\n activeModalities.audio = false;\n audioState(Internal.Modality.State.Disconnected);\n break;\n default:\n assert(false, 'unexpected event type');\n }\n }\n else if (scope.rel == 'participant') {\n Task.wait(getParticipant(scope.href)).then(function (participant) {\n switch (event.type) {\n case 'added':\n case 'updated':\n if (isConferencing()) {\n participant[Internal.sInternal].setMediaSourceId(event);\n // In conference mode, the indication of a remote\n // participant hold/resume or mute/unmute is\n // \"participantAudio updated\" event. We need to\n // reload \"participantAudio\" resource and set the\n // properties accordingly\n if (event.type == 'updated') {\n ucwa.send('GET', event.target.href).then(function (r) {\n if (r.has('audioDirection')) {\n participant[Internal.sInternal].audioOnHold(r.get('audioDirection') ==\n AudioVideoDirection.Inactive);\n }\n if (r.has('audioMuted'))\n participant[Internal.sInternal].audioMuted(r.get('audioMuted'));\n });\n }\n }\n participant[Internal.sInternal].audioState(Internal.Modality.State.Connected);\n break;\n case 'deleted':\n participant[Internal.sInternal].audioState(Internal.Modality.State.Disconnected);\n break;\n default:\n assert(false, 'unexpected event type');\n }\n });\n }\n }\n }",
"function onPlayerReady() {\n const roomCode = this.player.roomCode;\n\n // The player is ready to smack down.\n this.player.ready = true;\n\n // Let everyone else know the player is ready.\n this.broadcast.to(roomCode).emit('show player ready', this.player);\n\n // Check to see if all players are ready.\n if (checkAllPlayersReady(roomCode)) {\n io.in(roomCode).emit('start countdown');\n\n rooms[roomCode].countdownStarted = true;\n\n // Clear the player's texture map to clean up JSON payload.\n for (let player of getPlayersInRoom(roomCode)) {\n player.textureMap = [];\n }\n }\n}",
"function setupChannel() {\n // Join the general channel\n generalChannel.join().then(function(channel) {\n print('Joined channel as <span class=\"me\">' + username + '</span>.', username, new Date());\n });\n\n // Listen for new messages sent to the channel\n generalChannel.on('messageAdded', function(message) {\n //printMessage(message.author, message.body);\n print(message.body,message.author,message.dateCreated);\n });\n // Listen for new messages sent to the channel\n generalChannel.on('memberLeft', function(data) {\n console(data);\n //print(message.body,message.author,message.dateCreated);\n });\n }",
"function onConnectedHandler () {\n console.log(\"twitch bot connected\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the local items | getLocalItems(cb = null) {
const items = _localItems.get(this)
if (items && cb) {
cb(items)
}
return items
} | [
"function getAllItems(){\n\n}",
"loadAvailableItems() {\n // Load the available items and parses the data\n var tempList = lf.getAvailableItems();\n tempList.then((value) => {\n // Get the items, their ids, and data\n var items = value.items;\n var ids = value.ids;\n var genNames = value.genNames;\n\n // Save the item information\n var temp = [];\n for (var i = 0; i < ids.length; i++) {\n temp.push({\n name: items[i],\n title: items[i],\n id: ids[i],\n genName: genNames[i]\n });\n }\n\n // Add the option to register a new item to the list\n temp.push({ name: NEW_ITEM, title: NEW_ITEM, id: -1 });\n\n availableItems = temp;\n });\n }",
"function pullFromStorage(){\r\n return JSON.parse(localStorage.getItem(\"todoitems\"))\r\n}",
"function getLookupItems($query) {\n\n\t\t\t\t\tvar def = $q.defer();\n\n\t\t\t\t\tif ($scope.lookupItems !== void 0) {\n\n\t\t\t\t\t\t// Returns cached items\n\t\t\t\t\t\tdef.resolve($scope.lookupItems);\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tgetLookupList().then(function(list) {\n\n\t\t\t\t\t\t\tlist.getListItems($query).then(function(items) {\n\n\t\t\t\t\t\t\t\t$scope.lookupItems = items;\n\t\t\t\t\t\t\t\tdef.resolve($scope.lookupItems);\n\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\treturn def.promise;\n\t\t\t\t}",
"static async getStoreInventory() {\n const storeInventory = storage.get(\"products\").value()\n return storeInventory\n }",
"function getListItems() {\n let isLoggedIn = localStorage.getItem(\"isLoggedIn\")\n let username = localStorage.getItem(\"username\")\n\n if (isLoggedIn && username) {\n console.log(\"getting list of items\")\n axios\n .get(`/api/pantry?cmd=getList&username=${username}`)\n .then(response => {\n let items = response.data.items\n console.log(\"Response: \" + response)\n listOfItems.push(...items) // push each item separately into the list listOfItems\n allItems.push(...items) // push each item separately into the list listOfItems\n showListItems()\n })\n .catch(error => {\n console.error(error)\n })\n }\n}",
"function getLocalFiles(local) {\n return fs.readdirSync(local);\n}",
"function getItems() {\n fetch('http://genshinnews.com/api')\n .then(response => response.text())\n .then(data => {\n discordHooks = JSON.parse(`[${data}]`)\n webhookLoop(discordHooks)\n });\n }",
"static getDataFromLS(){\r\n let products;\r\n if(localStorage.getItem('products') === null){\r\n products = []\r\n }else{\r\n products = JSON.parse(localStorage.getItem('products'));\r\n }\r\n return products;\r\n }",
"getDatasetsKeys(){\n let keys=this.localStorageService.keys();\n\n return keys;\n }",
"function loadItems() {\n var items = '';\n for (var i=$assetindex; i < $assetindex+$assetbatchsize; i++ ) {\n if (i==$assets.length)\n break;\n items += loadItem(i);\n }\n $assetindex = i;\n // return jQuery object\n return jQuery( items ); \n}",
"function addLocalRuffles(items){\n\t\t\t// go through each ruffle and preprocess\n\t\t\tvar ruffles = [];\n\t\t\tangular.forEach(items, function(item){\n\t\t\t\tvar ruffle = new Ruffle(item.doc);\n\t\t\t\tRuffleLoader.add(ruffle);\n\t\t\t\truffles.push(ruffle);\n\t\t\t});\n\t\t\tstate.list = state.list.concat(ruffles);\n\t\t}",
"fileListCache() {\n return remote.getGlobal('application').fileListCache;\n }",
"loadTabItems() {\n let items = storage.get(this.itemsKey) || {}\n for (var key in items) {\n items[key] = Tab.restore(items[key])\n }\n this.items = items\n }",
"function getLSI(item) {\n return JSON.parse(localStorage.getItem(item));\n}",
"function getStocks(){\n return JSON.parse(localStorage.getItem(STOCK_STORAGE_NAME));\n}",
"function getLazyItems()/*:Array*/ {\n return this.lazyItems$qvyu;\n }",
"getManifestItems(cloneIt = true) {\n if (cloneIt) {\n return toJS(this.manifest.items);\n }\n return this.manifest.items;\n }",
"async getItem(...selects) {\n const q = this.listItemAllFields;\n const d = await q.select(...selects)();\n if (d[\"odata.null\"]) {\n throw Error(\"No associated item was found for this folder. It may be the root folder, which does not have an item.\");\n }\n return Object.assign(Item([this, odataUrlFrom(d)]), d);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds all the observable accessors defined on the target, including its prototype chain. | getAccessors(target) {
let accessors = accessorLookup.get(target);
if (accessors === void 0) {
let currentTarget = Reflect.getPrototypeOf(target);
while (accessors === void 0 && currentTarget !== null) {
accessors = accessorLookup.get(currentTarget);
currentTarget = Reflect.getPrototypeOf(currentTarget);
}
if (accessors === void 0) {
accessors = [];
}
else {
accessors = accessors.slice(0);
}
accessorLookup.set(target, accessors);
}
return accessors;
} | [
"function getAllRelationsForTargetInternal(target) {\n if (!target) {\n throw TypeError;\n }\n let targerKey = typeof target === 'function' ? target.prototype : target;\n if (_relationsCache[targerKey.constructor.name]) {\n return _relationsCache[targerKey.constructor.name];\n }\n //global.models.CourseModel.decorator.manytomany.students\n var meta = utils_1.MetaUtils.getMetaData(target);\n if (!meta) {\n return null;\n }\n let relations = Enumerable.from(meta)\n .where((x) => {\n return constants_1.RelationDecorators.indexOf(x.decorator) !== -1;\n })\n .toArray();\n _relationsCache[targerKey.constructor.name] = relations;\n return relations;\n}",
"function listAllProperties(o){ \n\tvar objectToInspect; \n\tvar result = [];\n\t\n\tfor(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){ \n\t\tresult = result.concat(Object.getOwnPropertyNames(objectToInspect)); \n\t}\n\t\n\treturn result; \n}",
"function testLookupGetter() {\n var obj = {};\n\n // Getter lookup traverses internal prototype chain.\n Object.defineProperty(Object.prototype, 'inherited', {\n get: function inheritedGetter() {}\n });\n Object.defineProperty(obj, 'own', {\n get: function ownGetter() {}\n });\n print(obj.__lookupGetter__('own').name);\n print(obj.__lookupGetter__('inherited').name);\n\n // An accessor lacking a 'get' masks an inherited getter.\n Object.defineProperty(Object.prototype, 'masking', {\n get: function inheritedGetter() {}\n });\n Object.defineProperty(obj, 'masking', {\n set: function ownGetter() {}\n // no getter\n });\n print(obj.__lookupGetter__('masking'));\n\n // A data property causes undefined to be returned.\n Object.defineProperty(Object.prototype, 'inheritedData', {\n value: 123\n });\n Object.defineProperty(obj, 'ownData', {\n value: 321\n });\n print(obj.__lookupGetter__('ownData'));\n print(obj.__lookupGetter__('inheritedData'));\n\n // Same for missing property.\n print(obj.__lookupGetter__('noSuch'));\n\n // .length and .name\n print(Object.prototype.__lookupGetter__.length);\n print(Object.prototype.__lookupGetter__.name);\n}",
"function getAssociations(target) {\n return Reflect.getMetadata(ASSOCIATIONS_KEY, target);\n}",
"function getForeignKeys(target) {\n return Reflect.getMetadata(FOREIGN_KEYS_KEY, target);\n}",
"function resolve(obj, accessors, thisvar) {\n\teachOwn(obj, function (key, value) {\n\t\t// If the value is an accessor, generate the accessor function.\n\t\t// This applies filters and listeners too.\n\t\tif (proxyFlag(value, 'accessor')) {\n\t\t\tobj[key] = accessors[key] = generate(value, thisvar, key);\n\t\t\n\t\t// If the value isn't an accessor but is a TubuxProxy,\n\t\t// set the property to the proxy's value.\n\t\t} else if (proxyFlag(value)) {\n\t\t\tobj[key] = value._value;\n\t\t}\n\t});\n\treturn accessors;\n}",
"function getAllRelationsForTarget(target) {\n if (!target) {\n throw TypeError;\n }\n //global.models.CourseModel.decorator.manytomany.students\n var name = getResourceNameFromModel(target);\n if (!name) {\n return null;\n }\n var metaForRelations = utils_1.MetaUtils.getMetaDataForDecorators(constants_1.RelationDecorators);\n return Enumerable.from(metaForRelations)\n .selectMany(keyVal => keyVal.metadata)\n .where(x => x.params.rel === name)\n .toArray();\n}",
"getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }",
"makeObservable(propertyNames) {\n var that = this;\n for (var propertyName of propertyNames) {\n // wrap into anonymous function to get correct closure behavior\n (function(pn) {\n const fieldName = \"_\" + pn;\n that[fieldName] = that[pn]; // ensure initial value is set to created field\n Object.defineProperty(that, pn, {\n enumerable: true,\n configurable: true,\n get() { return that[\"_\" + pn]; },\n set(value) {\n const oldValue = that[fieldName];\n that[fieldName] = value;\n that._firePropertyChanged(pn, oldValue, value);\n }\n });\n const subscribeFunctionName = pn + \"Changed\";\n that[subscribeFunctionName] = (listenerFunction) => that._listen(pn, listenerFunction);\n })(propertyName);\n }\n }",
"static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this._classProperties.forEach((v, p) => {\n const attr = this._attributeNameForProperty(p, v);\n if (attr !== undefined) {\n this._attributeToPropertyMap.set(attr, p);\n attributes.push(attr);\n }\n });\n return attributes;\n }",
"function collectOwnMethods(object) {\n\t var methods = [];\n\t\n\t walk(object, collectMethod.bind(null, methods, object));\n\t\n\t return methods;\n\t}",
"getAll() {\n\t\treturn this.motors;\n\t}",
"onOwnPropertyNamesGet(room, identifier) {\n return Object.getOwnPropertyNames(room);\n }",
"getAllEvents(objectInstance) {\n if (!objectInstance) {\n return [];\n }\n let prototype = Object.getPrototypeOf(objectInstance);\n return prototype._espDecoratorMetadata\n ? prototype._espDecoratorMetadata._events\n : [];\n }",
"getTrackedElements() {\n const sourceTrackedKeys = Object.keys(this.getSourceMembers());\n return sourceTrackedKeys.map((key) => this.getTrackedElement(key));\n }",
"_registerHandlers() {\n let obj = this;\n while (obj = Reflect.getPrototypeOf(obj)) {\n let keys = Reflect.ownKeys(obj)\n keys.forEach((method) => {\n if (method.startsWith('_handle')) {\n this[method]();\n }\n });\n }\n }",
"onOwnPropertyDescriptorGet(room, prop, identifier) {\n return Object.getOwnPropertyDescriptor(room, prop);\n }",
"function defineAllProperties(to, from) {\n to.__model__ = to.__model__ || from;\n each(from, function(m,n) {\n try {\n if (to.__model__ !== from)\n to.__model__[n] = m;\n defineProperty(to,n,m);\n } catch (t) {}\n });\n }",
"function initAll(handler){\r\n let overrideProxy=new Proxy({},{\r\n has:function(target,prop){\r\n return true\r\n },\r\n get:function(target,prop){\r\n return newElementHolderProxy()[prop](handler)\r\n }\r\n }\r\n )\r\n return newElementHolderProxy(undefined,overrideProxy)\r\n }",
"function lodashBindAll() {\n var originalBindAll = _.bindAll;\n\n _.bindAll = function(object, methodNames) {\n if (arguments.length === 1) {\n return originalBindAll(object, _.functionsIn(object));\n } else {\n return originalBindAll.apply(null, arguments);\n }\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
after pushing the start new game button in settings, the function change to game screen and start game. | function startNewGame(){
toggleNewGameSettings();
newGame();
} | [
"function setStartScreen() {\n score = 0;\n showScreen('start-screen');\n document.getElementById('start-btns').addEventListener('click', function (event) {\n if (!event.target.className.includes('btn')) return; //makes sure event is only fired if a button is clicked\n let button = event.target; //sets button to the element that fired the event\n let gameType = button.getAttribute('data-type');\n setGameScreen(gameType);\n });\n }",
"startGame() {\n let self = this\n this.props.changeSetupConfigClass(\"setupconfig__holder setupconfig__holder__deactive\")\n setTimeout(()=>{\n self.props.changeResetCoords(true)\n self.props.changeMarkerCoords([0,0])\n self.props.changeResetCoords(false)\n self.props.changeActiveHandler(this.props.game.id, false, true)\n self.props.changeActiveState(this.props.game.id, true)\n }, 1600)\n }",
"function startGame() {\n removeWelcomePage();\n createGamePage();\n createCards();\n}",
"moveToNextGame() {\n this._startGame(this._getNextGame());\n }",
"function startGame() {\r\n startScreen0.style.display = 'none';\r\n startScreen1.style.display = 'none';\r\n startScreen2.style.display = 'none';\r\n startScreen3.style.display = 'none';\r\n startScreen4.style.display = 'none';\r\n startScreen5.style.display = 'none';\r\n singleClickElement.style.display = 'flex';\r\n doubleClickElement.style.display = 'flex';\r\n initialize();\r\n startTimer();\r\n}",
"function stateChangeButtonPress(button) {\n switch (button.name) {\n case 'To Title Screen':\n game.state.start('titleScreen');\n break;\n case 'To Main Game':\n game.state.start('mainGame');\n break;\n case 'To Game Over':\n game.state.start('gameOver');\n break;\n }\n }",
"startGame() {\r\n this.generateInitialBoard();\r\n this.printBoard();\r\n this.getMoveInput();\r\n }",
"function setGame() {\n console.log(\"game being set\");\n gameStart = false;\n resetRods();\n resetBall();\n}",
"function setGameOverScreen() {\n showScreen('game-over-screen');\n\n let tryAgain = document.getElementById('try-again');\n tryAgain.addEventListener('click', function () {\n score = 0; // resets the score\n let gameType = document.getElementById('difficulty').innerHTML;\n setGameScreen(gameType); // afer the event fires setGameScreen function is called\n });\n\n let restart = document.getElementById('restart');\n restart.addEventListener('click', function () {\n setStartScreen(); // after the event fires setStartScreen function is called\n });\n }",
"function initSimon() {\n $('[data-action=start]').on('click', startGame);\n\n }",
"function GameScreenAssistant() { }",
"function startGameMinimax(){\r\n isMinimax = true;\r\n startGame();\r\n}",
"function startGame() {\n createButtons();\n createCards();\n displayCards();\n}",
"function winScreen() {\n\t\n\tPhaser.State.call(this);\n\t\n}",
"function startGame() {\n removeWelcome();\n questionIndex = 0;\n startTimer();\n generateQuestions();\n}",
"function gameStart() {\n let random = Math.random();\n if (random > 0.5) {\n playerTurn = true;\n playerMessage.text('Your Turn');\n } else {\n playerTurn = false;\n loader.show();\n computerAction();\n }\n}",
"function giveInstructions()\n{\n startScene.visible = false;\n instructionScene.visible = true;\n gameScene.visible = false;\n pauseMenu.visible = false;\n gameOverScene.visible = false;\n screenButtonSound.play();\n}",
"function displayGameScreen()\n{\n\t\n\tdisplayResourceElement();\n\t\t\t\n\tdisplayInfoElement();\n\t\n\tdisplayMapElement();\n\t\n\tjoinGame();\n\t\n\tif(player.onTurn == true)\n\t{\n\t\tdisplayEndTurnElement(\"salmon\");\n\t\t\n\t\tdisplayTurnCounterElement(\"lightGreen\");\n\t}\n\telse\n\t{\n\t\tdisplayEndTurnElement(\"lightSlateGrey\");\n\t\n\t\tdisplayTurnCounterElement(\"salmon\");\n\t}\n\t\n\tgameStarted = true;\n\t\n\tstage.update();\n}",
"processStartButton() {\n\t\tclearTimeout(this.timer);\n\t\tthis.timer = null;\n\t\tthis.game.switchScreens('play');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The name of the currency for the main country using this locale (e.g. USD for the locale enUS). The name will be `null` if the main country cannot be determined. | function getLocaleCurrencyName(locale) {
var data = findLocaleData(locale);
return data[16 /* CurrencyName */] || null;
} | [
"static getCurrencyName(code) {\n let currencyName = this.getPhrase(code, \"CurrencyCode\");\n if (currencyName != \"\" && currencyName.length > 0)\n return currencyName;\n else\n return code;\n }",
"function get_currency_name(str) {\n return str.replace(` (${get_currency_code(str)})`, '');\n}",
"function standardizeCountryName(countryName) {\n const possibleMapping = constants.countryMapping.filter(mapping => mapping.possibleNames.indexOf(countryName) >= 0);\n return (possibleMapping.length == 1 ? possibleMapping[0].standardizedName : countryName.toLowerCase());\n}",
"static getLanguageName() {\n let twoLetterLangName = global.language.value.toLowerCase().split('-')[0];\n switch (twoLetterLangName) {\n case \"en\":\n return \"english\";\n case \"de\":\n return \"german\";\n case \"es\":\n return \"spanish\";\n case \"fr\":\n return \"french\";\n case \"it\":\n return \"italian\";\n case \"nl\":\n return \"dutch\";\n case \"fi\":\n return \"finnish\";\n case \"sv\":\n return \"swedish\";\n case \"ru\":\n return \"russian\";\n case \"pl\":\n return \"polish\";\n case \"zh\":\n case \"cn\":\n case \"chs\":\n case \"tw\":\n case \"cht\":\n return \"chinese\";\n case \"ja\":\n return \"japanese\";\n case \"ko\":\n return \"korean\";\n case \"is\":\n return \"icelandic\";\n case \"da\":\n return \"danish\";\n case \"no\":\n case \"nb\":\n case \"nn\":\n return \"norwegian\";\n case \"ar\":\n return \"arabic\";\n case \"vi\":\n return \"vietnamese\";\n default:\n return \"english\";\n }\n }",
"function getCountryFromRegionsMap(country) {\n for (var r in regionsMap) {\n var region = regionsMap[r];\n\n var countryCurrency = getCountryFromRegion(region, country);\n\n if (countryCurrency) {\n return countryCurrency;\n }\n }\n\n return null;\n}",
"function formatCountry(country) {\n let formattedCountry;\n if (country === 'USA') {\n formattedCountry = 'the United States';\n } else if (country === 'UK') {\n formattedCountry = 'the United Kingdom';\n } else if (country === 'S.Korea') {\n formattedCountry = 'South Korea';\n } else if (country === 'CAR') {\n formattedCountry = 'the Central African Republic';\n } else if (country === 'DRC') {\n formattedCountry = 'the Democratic Republic of the Congo / Congo Kinshasa';\n } else if (country === 'Congo') {\n formattedCountry = 'the Congo Republic / Congo Brazzaville';\n } else if (country === 'U.S. Virgin Islands') {\n formattedCountry = 'the U.S. Virgin Islands';\n } else {\n formattedCountry = country;\n }\n return formattedCountry;\n}",
"static get iso3166() {\n\t\treturn 'CY';\n\t}",
"function getCurrency(amount) {\n\tvar fmtAmount;\n\tvar opts = {MinimumFractionDigits: 2, maximumFractionDigits: 2};\n\tif (selectedCurrency === \"CAD\") {\n\t\tfmtAmount = \"CAD $\" + amount.toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"USD\") {\n\t\tfmtAmount = \"USD $\" + (amount * currencyRates.USD).toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"MXN\") {\n\t\tfmtAmount = \"MXN ₱\" + (amount * currencyRates.MXN).toLocaleString(undefined, opts);\n\t} else {\n\t\tthrow \"Unknown currency code: this shouldn't have happened.\";\n\t}\n\treturn fmtAmount;\n}",
"function _getLocale(name) {\n\treturn _locales[name] || _locales.$def;\n}",
"function getCountryName(place) {\n for (var i = 0; i < place.address_components.length; i++) {\n var addressType = place.address_components[i].types[0];\n if (addressType == 'country') {\n country = place.address_components[i]['long_name'];\n }\n }\n // console.log(\"Current country\" + country);\n}",
"function getCountryFromRegion(region, country) {\n for (var c in region) {\n var countryCurrency = region[c];\n\n if (contains(countryCurrency, country)) {\n return countryCurrency;\n }\n }\n\n return null;\n}",
"findCountryData(name) {\n\t\treturn this.state.data?.countries[name.toLowerCase().replace(\" \",\"_\")]?.data\n\t}",
"function getCurrency(){\n //selected currencies\n fromCurr = selects[0].selectedOptions[0].textContent;\n toCurr = selects[1].selectedOptions[0].textContent;\n \n //get currency code according to currency name\n if(fromCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == fromCurr);\n base = currencies[index].currency_code;\n }\n\n if(toCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == toCurr);\n rateKey = currencies[index].currency_code;\n }\n}",
"get name () {\n return this._creep.name;\n }",
"locale() {\n return d3.formatLocale(this.selectedLocale);\n }",
"function getLocale () {\n return locale\n}",
"getCurrency() {\n const tier = this.getTier();\n return get(tier, 'currency', this.props.data.Collective.currency);\n }",
"function getSiteLocaleNameFor$static(content/* :Content*/)/*:String*/ {\n var site/*:Site*/ = com.coremedia.cms.editor.sdk.editorContext.getSitesService().getSiteFor(content);\n if (site === undefined) {\n // not loaded\n return undefined;\n }\n if (!site) {\n // content has no site\n return '';\n }\n var locale/*:Locale*/ = site.getLocale();\n if (!locale) {\n return ''; // attributes of Site can never by \"undefined\"\n }\n return locale.getDisplayName();\n }",
"function formatCurrency(value, options={}) {\n\n if (value == null) {\n return null;\n }\n\n let maxDigits = options.digits || global_settings.PRICING_DECIMAL_PLACES || 6;\n let minDigits = options.minDigits || global_settings.PRICING_DECIMAL_PLACES_MIN || 0;\n\n // Extract default currency information\n let currency = options.currency || global_settings.INVENTREE_DEFAULT_CURRENCY || 'USD';\n\n // Extract locale information\n let locale = options.locale || navigator.language || 'en-US';\n\n let formatter = new Intl.NumberFormat(\n locale,\n {\n style: 'currency',\n currency: currency,\n maximumFractionDigits: maxDigits,\n minimumFractionDigits: minDigits,\n }\n );\n\n return formatter.format(value);\n}",
"function get_unit_homecity_name(punit)\n{\n if (punit['homecity'] != 0 && cities[punit['homecity']] != null) {\n return decodeURIComponent(cities[punit['homecity']]['name']);\n } else {\n return null;\n }\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a sprite image with the "name". Scale the img proportionally to fit the width | function drawSprite(spriteName, x, y, width) {
var spriteLoc = spriteLocMap[spriteName];
var scale = width / spriteLoc.width;
ctx.drawImage(spriteImg,
spriteLoc.pixelsLeft,
spriteLoc.pixelsTop,
spriteLoc.width,
spriteLoc.height,
x,
y,
spriteLoc.width * scale,
spriteLoc.height * scale);
} | [
"drawSkier() {\n var skierAssetName = this.getSkierAsset();\n var skierImage = vars.loadedAssets[skierAssetName];\n var x = (vars.gameWidth - skierImage.width) / 2;\n var y = (vars.gameHeight - skierImage.height) / 2;\n ctx.drawImage(skierImage, x, y, skierImage.width, skierImage.height);\n }",
"function drawSprite(img, row,column, x,y, width,height) {\n\t//set default parameters if not specified\n\tif(!row) row = 0;\n\tif(!column) column = 0;\n\tif(!x) x = 0;\n\tif(!y) y = 0;\n\tif(!width) width = img.spriteWidth;\n\tif(!height) height = img.spriteHeight;\n\t\n\tvar sourceX=Math.floor(Math.floor(column) * img.spriteWidth); //get the horizontal offset into the image to grab the frame\n\tvar sourceY=Math.floor(Math.floor(row) * img.spriteHeight); //get the vertical offset into the image to grab the frame\n\t\n\tcontext.drawImage(img, //draw the image...\n\t\tsourceX, sourceY, //...cropping it to the desired sprite...\n\t\tMath.floor(img.spriteWidth),Math.floor(img.spriteHeight), //...where the sprite is this size\n\t\tMath.floor(x), Math.floor(y), //draw it at this position\n\t\tMath.floor(width),Math.floor(height) //...with the specified size\n\t);\n}",
"draw(medalName='none') {\n const { spriteX, spriteY } = medalsObj.medals[medalName];\n\n ctx.drawImage(\n sprites,\n spriteX, spriteY,\n medalsObj.width, medalsObj.height,\n medalsObj.x, medalsObj.y,\n medalsObj.width, medalsObj.height\n )\n }",
"createSprite() {\n this.sprite = new PIXI.Sprite(PIXI.loader.resources[this.category].textures[this.spriteName]);\n if(this.isOnFloor) {\n this.sprite.position.set(this.x, this.y);\n }\n this.sprite.width = this.sprite.height = this.spriteSize;\n this.floor.itemSprites.addChild(this.sprite);\n\n // would be nice to consolidate to a function. currently not working\n // this._textStyle = new PIXI.TextStyle({\n // fill: '#fff',\n // fontSize: 17\n // });\n // this.itemNameSprite = new PIXI.Text(this.spriteName, this._textStyle);\n // /* eslint-disable-next-line no-extra-parens */\n // this.itemNameSpriteOffset = (this.sprite.width / 2) - (this.itemNameSprite.width / 2);\n // this.itemNameSprite.position.set(\n // this.sprite.position.x + this.itemNameSpriteOffset,\n // this.sprite.position.y - 15\n // );\n // this.floor.itemSprites.addChild(this.itemNameSprite);\n }",
"updateSprite() {\n\t\tif(!this.multiTexture) {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '.png');\n\t\t}\n\t\telse {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '_' +\n\t\t\t\t\t\t\t\t\t\t\t(this.multiTextureId < 10 ? '0' : '') + this.multiTextureId + '.png');\n\t\t}\n\t}",
"function Sprite( params ) {\n this.game = params.game;\n var r = this.game.getSprite( params.imageid );\n if( !r ) {\n console.log( \"Sprite id :\" + params.id + \" references invalid image\");\n return;\n }\n\n // body width/heihgt can be different thatn physical dimensiosn due to margin\n this.margins = {top:r.sprite.top/SCALE,\n left:r.sprite.left/SCALE,\n right:r.sprite.right/SCALE,\n bottom:r.sprite.bottom/SCALE};\n\n params.width = r.sprite.w/SCALE - this.margins.left - this.margins.right;\n params.height = r.sprite.h/SCALE - this.margins.top - this.margins.bottom;\n params.x += this.margins.left;\n params.y += this.margins.top;\n RectangleEntity.call(this, params);\n this.imageid = params.imageid;\n this.bodyless = params.bodyless;\n}",
"load_sprite (img_name, sx, sy, sw, sh) {\n\t\tif (cached_assets[img_name] == null) return false;\n\t\tthis._sprites['idle'] = [];\n\t\tthis._sprites['idle'][0] = cached_assets[img_name];\n\t\tthis._sx = sx || 0;\n\t\tthis._sy = sy || 0;\n\t\tthis._width = sw || cached_assets[img_name].width;\n\t\tthis._height = sh || cached_assets[img_name].height;\n\t\treturn true;\n\t}",
"function drawPlayer() {\n push();\n tint(255,playerHealth);\n image(playerHunter,playerX,playerY,playerRadius*5, playerRadius*5);\n pop();\n}",
"display()\r\n {\r\n image(this.image,this.x, this.y, this.w,this.h);\r\n }",
"function renderNPCSprites(aDev,aGame)\n{\n ////this makes a temp object of the image we want to use\n //this is so the image holder does not have to keep finding image\n tempImage1 = aDev.images.getImage(\"orb\")\n tempImage2 = aDev.images.getImage(\"fireAmmo\")\t\n for (var i = 0; i < aGame.gameSprites.getSize(); i++)\n {\t\n ////this is to make a temp object for easier code to write and understand\n tempObj = aGame.gameSprites.getIndex(i); \n switch(tempObj.name)\n {\n case \"orb\":\n aDev.renderImage(tempImage1,tempObj.posX,tempObj.posY);\n break;\n case \"fireAmmo\":\n aDev.renderImage(tempImage2,tempObj.posX,tempObj.posY);\n break;\n } \n }\n}",
"function CreateSprite(paths, size_factor, size_min,\n\t\t speed_factor, speed_min, left, right){\n\n // Make the mesh \n var size = Math.random()*size_factor + size_min;\n var trand = Math.floor(Math.random()*paths.length);\n var texture= THREE.ImageUtils.loadTexture(paths[trand]);\n var material = new THREE.SpriteMaterial( { map: texture, fog: true, } );\n var sprite = new THREE.Sprite( material );\n sprite.scale.set(size, size, size);\n var speed = Math.random() *speed_factor + speed_min;\n\n // Initial placement\n x = (Math.random()*(right-left))-((right-left)/2);\n y = (Math.random()*3000)-1000;\n sprite = new FallingObject(sprite, speed, x, y, -1000, 0, -1, 0);\n sprite.set_box_rules(2000, -1000, left, right);\n\n \n //sprite.place();\n\n return sprite;\n}",
"render(lagOffset = 1) {\n\n //Calculate the sprites' interpolated render positions if\n //`this.interpolate` is `true` (It is true by default)\n\n if (this.interpolate) {\n\n //A recursive function that does the work of figuring out the\n //interpolated positions\n let interpolateSprite = (sprite) => {\n\n\n //Position (`x` and `y` properties)\n if(this.properties.position) {\n\n //Capture the sprite's current x and y positions\n sprite._currentX = sprite.x;\n sprite._currentY = sprite.y;\n\n //Figure out its interpolated positions\n if (sprite._previousX !== undefined) {\n sprite.x = (sprite.x - sprite._previousX) * lagOffset + sprite._previousX;\n }\n if (sprite._previousY !== undefined) {\n sprite.y = (sprite.y - sprite._previousY) * lagOffset + sprite._previousY;\n }\n }\n\n //Rotation (`rotation` property)\n if(this.properties.rotation) {\n\n //Capture the sprite's current rotation\n sprite._currentRotation = sprite.rotation;\n\n //Figure out its interpolated rotation\n if (sprite._previousRotation !== undefined) {\n sprite.rotation = (sprite.rotation - sprite._previousRotation) * lagOffset + sprite._previousRotation;\n }\n } \n\n //Size (`width` and `height` properties)\n if(this.properties.size) {\n \n //Only allow this for Sprites or MovieClips. Because\n //Containers vary in size when the sprites they contain\n //move, the interpolation will cause them to scale erraticly\n if (sprite instanceof this.Sprite || sprite instanceof this.MovieClip) {\n\n //Capture the sprite's current size\n sprite._currentWidth = sprite.width;\n sprite._currentHeight = sprite.height;\n\n //Figure out the sprite's interpolated size\n if (sprite._previousWidth !== undefined) {\n sprite.width = (sprite.width - sprite._previousWidth) * lagOffset + sprite._previousWidth;\n }\n if (sprite._previousHeight !== undefined) {\n sprite.height = (sprite.height - sprite._previousHeight) * lagOffset + sprite._previousHeight;\n }\n }\n }\n\n //Scale (`scale.x` and `scale.y` properties)\n if(this.properties.scale) {\n \n //Capture the sprite's current scale\n sprite._currentScaleX = sprite.scale.x;\n sprite._currentScaleY = sprite.scale.y;\n\n //Figure out the sprite's interpolated scale\n if (sprite._previousScaleX !== undefined) {\n sprite.scale.x = (sprite.scale.x - sprite._previousScaleX) * lagOffset + sprite._previousScaleX;\n }\n if (sprite._previousScaleY !== undefined) {\n sprite.scale.y = (sprite.scale.y - sprite._previousScaleY) * lagOffset + sprite._previousScaleY;\n }\n }\n\n //Alpha (`alpha` property)\n if(this.properties.alpha) {\n\n //Capture the sprite's current alpha\n sprite._currentAlpha = sprite.alpha;\n\n //Figure out its interpolated alpha\n if (sprite._previousAlpha !== undefined) {\n sprite.alpha = (sprite.alpha - sprite._previousAlpha) * lagOffset + sprite._previousAlpha;\n }\n } \n\n //Tiling sprite properties (`tileposition` and `tileScale` x\n //and y values)\n if (this.properties.tile) {\n\n //`tilePosition.x` and `tilePosition.y`\n if (sprite.tilePosition !== undefined) {\n\n //Capture the sprite's current tile x and y positions\n sprite._currentTilePositionX = sprite.tilePosition.x;\n sprite._currentTilePositionY = sprite.tilePosition.y;\n\n //Figure out its interpolated positions\n if (sprite._previousTilePositionX !== undefined) {\n sprite.tilePosition.x = (sprite.tilePosition.x - sprite._previousTilePositionX) * lagOffset + sprite._previousTilePositionX;\n }\n if (sprite._previousTilePositionY !== undefined) {\n sprite.tilePosition.y = (sprite.tilePosition.y - sprite._previousTilePositionY) * lagOffset + sprite._previousTilePositionY;\n }\n }\n\n //`tileScale.x` and `tileScale.y`\n if (sprite.tileScale !== undefined) {\n\n //Capture the sprite's current tile scale\n sprite._currentTileScaleX = sprite.tileScale.x;\n sprite._currentTileScaleY = sprite.tileScale.y;\n\n //Figure out the sprite's interpolated scale\n if (sprite._previousTileScaleX !== undefined) {\n sprite.tileScale.x = (sprite.tileScale.x - sprite._previousTileScaleX) * lagOffset + sprite._previousTileScaleX;\n }\n if (sprite._previousTileScaleY !== undefined) {\n sprite.tileScale.y = (sprite.tileScale.y - sprite._previousTileScaleY) * lagOffset + sprite._previousTileScaleY;\n }\n } \n }\n \n //Interpolate the sprite's children, if it has any\n if (sprite.children.length !== 0) {\n for (let j = 0; j < sprite.children.length; j++) {\n\n //Find the sprite's child\n let child = sprite.children[j];\n\n //display the child\n interpolateSprite(child);\n }\n }\n };\n \n //loop through the all the sprites and interpolate them\n for (let i = 0; i < this.stage.children.length; i++) {\n let sprite = this.stage.children[i];\n interpolateSprite(sprite);\n } \n }\n\n //Render the stage. If the sprite positions have been\n //interpolated, those position values will be used to render the\n //sprite\n this.renderer.render(this.stage);\n\n //Restore the sprites' original x and y values if they've been\n //interpolated for this frame\n if (this.interpolate) {\n\n //A recursive function that restores the sprite's original,\n //uninterpolated x and y positions\n let restoreSpriteProperties = (sprite) => {\n if(this.properties.position) {\n sprite.x = sprite._currentX;\n sprite.y = sprite._currentY;\n }\n if(this.properties.rotation) {\n sprite.rotation = sprite._currentRotation;\n }\n if(this.properties.size) {\n\n //Only allow this for Sprites or Movie clips, to prevent\n //Container scaling bug\n if (sprite instanceof this.Sprite || sprite instanceof this.MovieClip) {\n sprite.width = sprite._currentWidth;\n sprite.height = sprite._currentHeight;\n }\n }\n if(this.properties.scale) {\n sprite.scale.x = sprite._currentScaleX;\n sprite.scale.y = sprite._currentScaleY;\n }\n if(this.properties.alpha) {\n sprite.alpha = sprite._currentAlpha;\n }\n if(this.properties.tile) {\n if (sprite.tilePosition !== undefined) {\n sprite.tilePosition.x = sprite._currentTilePositionX;\n sprite.tilePosition.y = sprite._currentTilePositionY;\n }\n if (sprite.tileScale !== undefined) {\n sprite.tileScale.x = sprite._currentTileScaleX;\n sprite.tileScale.y = sprite._currentTileScaleY;\n }\n }\n\n //Restore the sprite's children, if it has any\n if (sprite.children.length !== 0) {\n for (let i = 0; i < sprite.children.length; i++) {\n\n //Find the sprite's child\n let child = sprite.children[i];\n\n //Restore the child sprite properties\n restoreSpriteProperties(child);\n }\n }\n };\n for (let i = 0; i < this.stage.children.length; i++) {\n let sprite = this.stage.children[i];\n restoreSpriteProperties(sprite);\n }\n }\n }",
"setTextureUScale(u) {\n //TODO\n }",
"function SLTReelSprite() {\n this.initialize.apply(this, arguments);\n}",
"constructor(name, pixelWidth, pixelHeight, pixelOffsetX, pixelOffsetY, sight, hitPoints, cost,\n spriteImages, defaults, radius, range, moveSpeed, interactSpeed, firePower, builtFrom, weaponType) {\n super(name, pixelWidth, pixelHeight, pixelOffsetX, pixelOffsetY,\n sight, hitPoints, cost, spriteImages, defaults);\n this.defaults.type = 'units';\n this.radius = radius;\n this.range = range;\n this.moveSpeed = moveSpeed;\n this.interactSpeed = interactSpeed;\n this.firePower = firePower;\n this.builtFrom = builtFrom;\n\t\tthis.weaponType = weaponType;\n this.directions = 4;\n this.animationIndex = 0;\n this.imageOffset = 0;\n this.canAttack = true;\n this.canMove = true;\n this.turnSpeed = 2;\n this.speedAdjustmentWhileTurningFactor = 0.5;\n }",
"function createTempImage(){\n tempImage = game.instantiate(new Sprite('./img/beginplaatje.svg'));\n tempImage.setPosition({x: Settings.canvasWidth/2 - 110, y: Settings.canvasHeight/2 - 110});\n tempImage.setSize({x: 200, y: 200});\n}",
"drawBoss() {\n ctx.drawImage(this.boss,\n 0, 0, this.boss.width, this.boss.height,\n this.x_boss_pos, this.y_icon_pos,\n icon_width, icon_height);\n \n // Health outer\n ctx.strokeStyle = \"black\";\n ctx.strokeRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, icon_width + 100, 25);\n\n // Health drawing\n ctx.fillStyle = \"red\";\n ctx.fillRect(this.x_boss_pos - 100, this.y_icon_pos + icon_height + 10, this.health, 25);\n\n ctx.fillStyle = \"black\";\n ctx.font = '20px Arial';\n ctx.fillText(\"Health: \" + this.health, this.x_boss_pos - 150 - 100, this.y_icon_pos + icon_height + 25);\n }",
"function drawBG(pen) {\n\tlet tile = new Image();\n\ttile.src = \"pictures/sprite_sheet.png\";\n\tlet tileLen = 10; //tile is a 10x10 square\n\tlet x = 0, y = 0;\n\tfor(x=0; x<64; x+=1) {\n\t\tfor(y=0; y<64; y +=1) {\n\t\t\t//to use drawImage() with sprite sheet, it takes 9 args:\n\t\t\t//1. imgName, 2. x of sprite cutout 3. y of sprite cutout 4. width of sprite cutout\n\t\t\t//5. height of sprite cutout 6. x of canvas location 7. y of canvas location\n\t\t\t//8. width of drawn img on canvas 9. height of drawn img on canvas\n\t\t\t//(note: x, y start at 0,0 in the upper-left corner for both canvas and sprite sheet)\n\t\t\tpen.drawImage(tile, 10, 0, 10, 10, x * 10, y * 10, tileLen, tileLen);\n\t\t}\n\t}\n}",
"function Image(user_texture_id, size, uv0 = ImVec2.ZERO, uv1 = ImVec2.UNIT, tint_col = ImVec4.WHITE, border_col = ImVec4.ZERO) {\r\n bind.Image(ImGuiContext.setTexture(user_texture_id), size, uv0, uv1, tint_col, border_col);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loadAvailableItems Loads the known item names and their corresponding ids from the database. | loadAvailableItems() {
// Load the available items and parses the data
var tempList = lf.getAvailableItems();
tempList.then((value) => {
// Get the items, their ids, and data
var items = value.items;
var ids = value.ids;
var genNames = value.genNames;
// Save the item information
var temp = [];
for (var i = 0; i < ids.length; i++) {
temp.push({
name: items[i],
title: items[i],
id: ids[i],
genName: genNames[i]
});
}
// Add the option to register a new item to the list
temp.push({ name: NEW_ITEM, title: NEW_ITEM, id: -1 });
availableItems = temp;
});
} | [
"function loadShuffledItems() {\n\tloadItemLabels();\n \tshuffledItems = shuffle(itemLabels);\n}",
"handleLoaded(itemName) {\n this.toLoad = this.toLoad.filter(item => item !== itemName);\n\n if (this.toLoad.length === 0) {\n this.callbacks.onLoaded();\n }\n }",
"function ENSURE_ACTIVE_ITEMS(_ref4) {\n\t var dispatch = _ref4.dispatch,\n\t getters = _ref4.getters;\n\n\t return dispatch('FETCH_ITEMS', {\n\t ids: getters.activeIds\n\t });\n\t}",
"function loadItemList() {\n removeEmptyItems() // cleanup\n db = getDBFromLocalStorage() // get the latest saved object from localStorage\n Object.keys(db).forEach(function(key) {\n if(db[key]['title'] !== \"\") {\n main.innerHTML = `<section data-key='${key}'>${db[key]['title'].substr(0, titleLimit)}</section>` + main.innerHTML\n } else { // if title is blank, then show the first couple characters of the content as the title\n main.innerHTML = `<section data-key='${key}'>${decodeURIComponent(db[key]['content']).substr(0, titleLimit)}</section>` + main.innerHTML\n }\n })\n }",
"function loadList() {\n var begin = ((currentPage - 1) * numberPerPage);\n var end = begin + numberPerPage;\n\n pageList = hotelsArr.slice(begin, end);\n getDetails();\n check();\n}",
"async function getItemsUserNeedsToBring(req, res, next) {\n\ttry {\n\t\tconst { id } = req.params;\n\t\tconst usersItems = await db.getItemsByUserId(id);\n\t\tif (!usersItems) {\n\t\t\treturn res.status(404).json({\n\t\t\t\tmessage: \"you have not yet selected what you will bring anything to this potluck\",\n\t\t\t});\n\t\t}\n\t\tres.status(200).json(usersItems);\n\t} catch (err) {\n\t\tnext(err);\n\t}\n}",
"loadItems(url) {\n this.indexUrl = url;\n this.getFromServer(url, this.serverParams).then(response => {\n this.totalRecords = response.meta.total;\n this.rows = response.data;\n });\n }",
"function fetchItems(roomId) {\n //List to hold item ids in a given room\n var itemsInRoom = [];\n\n //List to hold the item objects of a given room\n var finalItemsList = [];\n\n //Iterate through rooms to identify the room based on roomId passed\n for(var i=0; i< room.length; i++){\n //Get the room matching the roomId\n if(room[i].roomId === roomId){\n //item ids in the room selected\n itemsInRoom = room[i].itemId;\n }\n }\n\n //Iterate through items to fetch the item objects based on item ids\n for(var i=0; i< items.length; i++){\n //Get the item based on itemids\n if(itemsInRoom.includes(items[i].itemId)) {\n //Item object added to final item list\n finalItemsList.push(items[i]);\n }\n };\n\n //Clear the content\n document.body.innerHTML = \"\";\n\n //Create the items page for the given room\n document.body.appendChild(createItemsPage(finalItemsList));\n}",
"function loaded() {\n var m = null,\n pending = [];\n\n for (m in modules) {\n if (modules.hasOwnProperty(m) && modules[m].name === undefined) {\n pending.push(m);\n }\n }\n\n if (pending.length === 0) {\n console.log('core::loaded,', 'all modules loaded');\n link();\n }\n }",
"function getAllItems(){\n\n}",
"loadInstanceAppItems ({commit}) {\n Vue.prototype.$axios.get('/applications/instance')\n .then(response => {\n if (response.status === 200) {\n const appItems = response.data\n commit('setAppItems', appItems)\n }\n })\n }",
"function loadItems() {\n var items = '';\n for (var i=$assetindex; i < $assetindex+$assetbatchsize; i++ ) {\n if (i==$assets.length)\n break;\n items += loadItem(i);\n }\n $assetindex = i;\n // return jQuery object\n return jQuery( items ); \n}",
"loadItemData() {\n this.setState({ loading: true });\n console.log(\"Loading item data\");\n fetch(SERVICE_URL + \"/items\")\n .then((data) => data.json())\n .then((data) => this.setState({ itemData: data, loading: false }));\n }",
"loadRecommendedItems() {\n // Get the ids of the current items in the list\n var currItemIds = this.state.listItemIds ? this.state.listItemIds : [];\n var currPrevRec = this.state.prevRecommended ? this.state.prevRecommended : [];\n\n var that = this;\n\n var ref = firebase.database().ref('/recommendations');\n var retItems = ref.once('value').then((snapshot) => {\n var newItems = {};\n var finalItems = [];\n\n // First check the rules\n // If an item is the precedent of a rule, add\n // the antecedent to the list of recommended items\n var ssv = snapshot.val();\n if (ssv) {\n for (var i = 0; i < currItemIds.length; i++) {\n var itemId = currItemIds[i];\n if (itemId in ssv) {\n var items = ssv[itemId];\n for (var newItemId in items) {\n var newItem = items[newItemId];\n if (!currItemIds.includes(newItem)) {\n if (!(newItem in newItems)) {\n newItems[newItem] = 0;\n }\n newItems[newItem] += 1;\n }\n }\n }\n }\n\n // Sort the current recommend items and\n // the list of top items\n var recItems = this.sortObjectByKeys(newItems);\n var topItems = this.sortObjectByKeys(ssv.topItems);\n\n var ids = [];\n var backlog = [];\n\n // Copy the top recommended items to the final list to recommend\n // as well as their ids, upto the maximum length\n for (var i = 0; (i < recItems.length) && (finalItems.length < NUM_REC_ITEMS); i++) {\n var info = globalComps.ItemObj.getInfoFromId(recItems[i][0]);\n var name = (new globalComps.ItemObj(info.name)).getDispName();\n var id = recItems[i][0];\n\n var toAdd = {\n genName: info.name,\n name: name,\n id: id,\n added: false\n };\n\n // Add the item to final items if it is not currently in the\n // user's list and it has not been previosuly recommended.\n // Otherwise, if the item is not in the list, but has been\n // previously recommended, add it to the backlog\n if ((!ids.includes(id)) && (!currPrevRec.includes(id))) {\n finalItems.push(toAdd);\n } else if ((!ids.includes(id)) && (currPrevRec.includes(id))) {\n backlog.push(toAdd);\n }\n\n ids.push(id)\n }\n\n // Fill the remaining space in the list of recommend items\n // with the most popular items\n for (var i = 0; (i < topItems.length) && (finalItems.length < NUM_REC_ITEMS); i++) {\n var id = topItems[i][0];\n if (!currItemIds.includes(id)) {\n var info = globalComps.ItemObj.getInfoFromId(topItems[i][0]);\n var name = (new globalComps.ItemObj(info.name)).getDispName();\n\n var toAdd = {\n genName: info.name,\n name: name,\n id: id,\n added: false\n };\n\n // Same as above\n if ((!ids.includes(id)) && (!currPrevRec.includes(id))) {\n finalItems.push(toAdd);\n } else if ((!ids.includes(id)) && (currPrevRec.includes(id))) {\n backlog.push(toAdd);\n }\n }\n }\n\n // If we're out of items to recommend, reset the backlog and previosuly recommended items\n for (var i = 0; (i < backlog.length) && (finalItems.length < NUM_REC_ITEMS); i++) {\n finalItems.push(backlog[i]);\n currPrevRec = [];\n }\n }\n\n // Save the list of recommended items\n that.setState({\n recommendedItems: finalItems,\n prevRecommended: currPrevRec\n });\n });\n }",
"async getItemsById (modelName, itemIds) {\n\n\t\tconst records = await this.database.find(modelName, {\n\t\t\t$or: itemIds.map(id => Object({ _id: id })),\n\t\t});\n\n\t\treturn records || [];\n\n\t}",
"function loadAllProductInShop() {\n Product.getProductLive({ SearchText: '' })\n .then(function (res) {\n $scope.products = res.data;\n });\n }",
"function load() {\n numOfPages();\n loadList();\n}",
"getLocalItems(cb = null) {\n const items = _localItems.get(this)\n if (items && cb) {\n cb(items)\n }\n\n return items\n }",
"function loadItemLabels() {\n\titemLabels[0] = \"Balloon\"\n\titemLabels[1] = \"Banana Peel\"\n\titemLabels[2] = \"Candy Wrapper\"\n\titemLabels[3] = \"Cereal Box\"\n\titemLabels[4] = \"Compostable Box\"\n\titemLabels[5] = \"Dry Leaves\"\n\titemLabels[6] = \"Filled Soup Can\"\n\titemLabels[7] = \"Lego\"\n\titemLabels[8] = \"Milk Carton\"\n\titemLabels[9] = \"Paper Bag\"\n\titemLabels[10] = \"Water Bottle\"\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get count of gender in a dict | function getCount(list, gender) {
var count = 0; // Var to store gender count
if (list) { // If list exists, loop through entries
for (var i=0; i<list.length-1; i++) {
if (list[i]['gender'] === gender) { count++; } // Increase count if list gender is gender passed in arg
}
}
return count
} //END getCount | [
"function getCount(list, gender) {\n let count = 0; // let to store gender count\n if (list) { // If list exists, loop through entries\n for (let i=0; i<list.length-1; i++) {\n if (list[i]['gender'] === gender) { count++; } // Increase count if list gender is gender passed in arg\n }\n }\n return count\n} //END getCount",
"function numberOfMales(array) {\n\tvar count=0;\n\tfor(var i=0; i<array.length; i++) {\n\t\tif( array[i][gender]===\"male\") {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count;\n}",
"function getTotalMale(){\n let total_amount_of_male = 0;\n \n census_data.population.forEach(ele => {\n total_amount_of_male += ele.male;\n });\n \n return total_amount_of_male;\n}",
"function getTotalFemale(){\n let total_amount_of_female = 0;\n \n census_data.population.forEach(ele => {\n total_amount_of_female += ele.female;\n });\n \n return total_amount_of_female;\n}",
"function countVisit(person) {\n let count = visitsCountMap.get(person) || 0;\n visitsCountMap.set(person, count + 1);\n console.log(visitsCountMap.get(person));\n}",
"function buildGenderRaceTable(data) {\r\n\t\tvar raceMale = { raceA: 0, raceB: 0, raceH: 0, raceN: 0, raceP: 0, raceW: 0, raceT: 0, raceO: 0, raceU: 0, raceNR: 0 };\r\n\t\tvar raceFemale = { raceA: 0, raceB: 0, raceH: 0, raceN: 0, raceP: 0, raceW: 0, raceT: 0, raceO: 0, raceU: 0, raceNR: 0 };\r\n\r\n\t\tfor (var i = 0; i < data.length; i++) {\r\n\t\t\tif (data[i].sex == \"M\") {\r\n\t\t\t\tswitch (data[i].race) {\r\n\t\t\t\t\tcase \"A\":\r\n\t\t\t\t\t\traceMale.raceA++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"B\":\r\n\t\t\t\t\t\traceMale.raceB++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"H\":\r\n\t\t\t\t\t\traceMale.raceH++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"N\":\r\n\t\t\t\t\t\traceMale.raceN++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"P\":\r\n\t\t\t\t\t\traceMale.raceP++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"W\":\r\n\t\t\t\t\t\traceMale.raceW++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"T\":\r\n\t\t\t\t\t\traceMale.raceT++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"O\":\r\n\t\t\t\t\t\traceMale.raceO++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"U\":\r\n\t\t\t\t\t\traceMale.raceU++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"NR\":\r\n\t\t\t\t\t\traceMale.raceNR++;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\traceMale.raceU++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tswitch (data[i].race) {\r\n\t\t\t\t\tcase \"A\":\r\n\t\t\t\t\t\traceFemale.raceA++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"B\":\r\n\t\t\t\t\t\traceFemale.raceB++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"H\":\r\n\t\t\t\t\t\traceFemale.raceH++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"N\":\r\n\t\t\t\t\t\traceFemale.raceN++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"P\":\r\n\t\t\t\t\t\traceFemale.raceP++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"W\":\r\n\t\t\t\t\t\traceFemale.raceW++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"T\":\r\n\t\t\t\t\t\traceFemale.raceT++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"O\":\r\n\t\t\t\t\t\traceFemale.raceO++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"U\":\r\n\t\t\t\t\t\traceFemale.raceU++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"NR\":\r\n\t\t\t\t\t\traceFemale.raceNR++;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\traceFemale.raceU++;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//Trying to figure out how to make this more efficient/less of a pain to look at\r\n\t\tvar percMale = {\r\n\t\t\tpercA: calcPercRace(raceMale.raceA, countMale), percB: calcPercRace(raceMale.raceB, countMale), percH: calcPercRace(raceMale.raceH, countMale),\r\n\t\t\tpercN: calcPercRace(raceMale.raceN, countMale), percP: calcPercRace(raceMale.raceP, countMale), percW: calcPercRace(raceMale.raceW, countMale),\r\n\t\t\tpercT: calcPercRace(raceMale.raceT, countMale), percO: calcPercRace(raceMale.raceO, countMale), percU: calcPercRace(raceMale.raceU, countMale),\r\n\t\t\tpercNR: calcPercRace(raceMale.raceNR, countMale)\r\n\t\t};\r\n\t\tvar percFemale = {\r\n\t\t\tpercA: calcPercRace(raceFemale.raceA, countFemale), percB: calcPercRace(raceFemale.raceB, countFemale), percH: calcPercRace(raceFemale.raceH, countFemale),\r\n\t\t\tpercN: calcPercRace(raceFemale.raceN, countFemale), percP: calcPercRace(raceFemale.raceP, countFemale), percW: calcPercRace(raceFemale.raceW, countFemale),\r\n\t\t\tpercT: calcPercRace(raceFemale.raceT, countFemale), percO: calcPercRace(raceFemale.raceO, countFemale), percU: calcPercRace(raceFemale.raceU, countFemale),\r\n\t\t\tpercNR: calcPercRace(raceFemale.raceNR, countFemale)\r\n\t\t};\r\n\t\tvar percTotal = {\r\n\t\t\tpercA: calcPercRace((raceMale.raceA + raceFemale.raceA), countTotal), percB: calcPercRace((raceMale.raceB + raceFemale.raceB), countTotal), percH: calcPercRace((raceMale.raceH + raceFemale.raceH), countTotal),\r\n\t\t\tpercN: calcPercRace((raceMale.raceN + raceFemale.raceN), countTotal), percP: calcPercRace((raceMale.raceP + raceFemale.raceP), countTotal), percW: calcPercRace((raceMale.raceW + raceFemale.raceW), countTotal),\r\n\t\t\tpercT: calcPercRace((raceMale.raceT + raceFemale.raceT), countTotal), percO: calcPercRace((raceMale.raceO + raceFemale.raceO), countTotal), percU: calcPercRace((raceMale.raceU + raceFemale.raceU), countTotal),\r\n\t\t\tpercNR: calcPercRace((raceMale.raceNR + raceFemale.raceNR), countTotal)\r\n\t\t};\r\n\r\n\t\t//Same as chunk above\r\n\t\tvar optA = writeTableRowRace('Asian', raceFemale.raceA, percFemale.percA, raceMale.raceA, percMale.percA, percTotal.percA);\r\n\t\tvar optB = writeTableRowRace('Black/African American', raceFemale.raceB, percFemale.percB, raceMale.raceB, percMale.percB, percTotal.percB);\r\n\t\tvar optH = writeTableRowRace('Hispanic', raceFemale.raceH, percFemale.percH, raceMale.raceH, percMale.percH, percTotal.percH);\r\n\t\tvar optN = writeTableRowRace('Native American', raceFemale.raceN, percFemale.percN, raceMale.raceN, percMale.percN, percTotal.percN);\r\n\t\tvar optP = writeTableRowRace('Pacific Islander', raceFemale.raceP, percFemale.percP, raceMale.raceP, percMale.percP, percTotal.percP);\r\n\t\tvar optW = writeTableRowRace('White', raceFemale.raceW, percFemale.percW, raceMale.raceW, percMale.percW, percTotal.percW);\r\n\t\tvar optT = writeTableRowRace('Two or more', raceFemale.raceT, percFemale.percT, raceMale.raceT, percMale.percT, percTotal.percT);\r\n\t\tvar optO = writeTableRowRace('Opt out', raceFemale.raceO, percFemale.percO, raceMale.raceO, percMale.percO, percTotal.percO);\r\n\t\tvar optU = writeTableRowRace('Unknown/Not reported', raceFemale.raceU, percFemale.percU, raceMale.raceU, percMale.percU, percTotal.percU);\r\n\t\tvar optNR = writeTableRowRace('Non-Resident', raceFemale.raceNR, percFemale.percNR, raceMale.raceNR, percMale.percNR, percTotal.percNR);\r\n\r\n\t\tvar total = writeTableRowRace('Total', countFemale, calcPercRace(countFemale, countTotal), countMale, calcPercRace(countMale, countTotal), calcPercRace(countTotal, countTotal));\r\n\r\n\r\n\t\t$('#genderEthnicityBody').append(optA);\r\n\t\t$('#genderEthnicityBody').append(optB);\r\n\t\t$('#genderEthnicityBody').append(optH);\r\n\t\t$('#genderEthnicityBody').append(optN);\r\n\t\t$('#genderEthnicityBody').append(optP);\r\n\t\t$('#genderEthnicityBody').append(optW);\r\n\t\t$('#genderEthnicityBody').append(optT);\r\n\t\t$('#genderEthnicityBody').append(optO);\r\n\t\t$('#genderEthnicityBody').append(optU);\r\n\t\t$('#genderEthnicityBody').append(optNR);\r\n\t\t$('#genderEthnicityBody').append(total);\r\n\t}",
"getMedalsTotal(country, medals){\n var x = 0;\n medals.forEach(medal => { \n x += country[medal.type + \"MedalCount\"]\n })\n return x;\n }",
"function totalAmountAdjectives(obj) {\n\treturn Object.values(obj).length;\n}",
"getReviewCountByReviewer(){\n const reviewCountByReviewer = {};\n\n reviewStore.reviews.forEach((review) => {\n const {reviewerID} = review;\n\n // Check if reviews includes reviewID key\n if (!Object.keys(reviewCountByReviewer).includes(reviewerID)){\n reviewCountByReviewer[reviewerID] = 0;\n }\n reviewCountByReviewer[reviewerID] += 1;\n });\n return reviewCountByReviewer;\n }",
"function getObjectLength(object) {\n // YOUR CODE BELOW HERE //\n \n var count = 0 //initialize a variable\n for (var key in object) { //iterate through the given object\n count++; //count each key/value and store the value in count variable\n }\n \n return count //return the number of key/value pairs\n // YOUR CODE ABOVE HERE //\n}",
"count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }",
"static frequencies(arr) {\n let result = {};\n arr.forEach(e => {\n if (e in result) {\n result[e] += 1;\n } else {\n result[e] = 1;\n }\n });\n return result;\n }",
"function getCountiesPopulation(county_array){\n let all_counties_population = {};\n census_data.population.forEach((ele)=>{\n if(all_counties_population.hasOwnProperty(ele.county) === false){\n all_counties_population[ele.county] = {\n male: ele.male,\n female: ele.female,\n sum: ele.male + ele.female\n }\n }\n else\n {\n all_counties_population[ele.county].male += ele.male;\n all_counties_population[ele.county].female += ele.female;\n all_counties_population[ele.county].sum += ele.male + ele.female;\n }\n \n })\n \n return all_counties_population;\n}",
"function keysCounter(obj) {\n // your code here\n var counter = 0;\n counter = Object.keys(obj).length;\nreturn counter;\n // code ends here\n}",
"function count_provinces( language_countries, parent_country_regex ){\n var num_provinces = 0;\n var strDebug = 'count_provinces( language_countries, ' +parent_country_regex+ ' )\\n';\n for(var i=0; i<language_countries.length; i++){ // language_countries is array from JSON\n var regex_match = language_countries[i].country_id.match(parent_country_regex);\n //strDebug += '\\n' +i+ ') ' +language_countries[i].country_id+ ' ; FUNC PLUS regex_match = ' +regex_match;\n if ( regex_match ) {\n num_provinces += language_countries[i].country_pubs;\n }\n }// end for\n //console.info( strDebug, ' ; end with num_provinces = ', num_provinces );\n return num_provinces;\n}// end count_provinces",
"function getPercentageOfMen(d) {\n return d.values.find(obj => obj.key == \"Man\").percentage\n }",
"getReviewCountByYear() {\n const reviewCountByYear = {};\n\n reviewStore.reviews.forEach((review) => {\n const [year] = getTimeInfo(review.reviewTime);\n\n // Check if reviews includes a year key\n if (!Object.keys(reviewCountByYear).includes(year)){\n reviewCountByYear[year] = 0;\n }\n reviewCountByYear[year] += 1;\n });\n return reviewCountByYear;\n }",
"function agePerObj(ageObj){\n ageObj[\"age\"] = ageObj.firstName.length + ageObj.lastName.length;\n}",
"function getCountedObjects(){\n var counted = {};\n for (var i = 0; i < detections.length; i++){\n var lbl = detections[i].label;\n if (!counted[lbl]) counted[lbl] = 0;\n counted[lbl]++;\n }\n return counted;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns POTENTIAL_MATCHES short strings, using the input characters a lot. | function regexShortStringsWith(frequentChars) {
var matches = [];
for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
var s = "";
while (rnd(3)) {
s += rnd(4) ? Random.index(frequentChars) : String.fromCharCode(regexCharCode());
}
matches.push(s);
}
return matches;
} | [
"function solve(s) {\n\tlet result = \"\";\n\tlet regex = /[aeiou]/;\n\tlet consonants = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn !regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tlet vowels = s\n\t\t.split(\"\")\n\t\t.filter(char => {\n\t\t\treturn regex.test(char);\n\t\t})\n\t\t.sort((a, b) => {\n\t\t\treturn a.charCodeAt(0) - b.charCodeAt(0);\n\t\t});\n\tif (consonants.length > vowels.length) {\n\t\tfor (let i = 0; i < consonants.length; i++) {\n\t\t\tif (!vowels[i]) {\n\t\t\t\tresult += consonants[consonants.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += consonants[i];\n\t\t\tresult += vowels[i];\n\t\t}\n\t} else {\n\t\tfor (let i = 0; i < vowels.length; i++) {\n\t\t\tif (!consonants[i]) {\n\t\t\t\tresult += vowels[vowels.length - 1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += vowels[i];\n\t\t\tresult += consonants[i];\n\t\t}\n\t}\n\tif (result.length !== s.length) {\n\t\treturn \"failed\";\n\t} else {\n\t\treturn result;\n\t}\n}",
"function matchSingleCharactersNotSpecified(string, possibilities) {\n // This will find all the characters not in possibilities in string.\n let regex = new RegExp(\"[^\" + possibilities + \"]\", \"ig\");\n console.log(regex);\n return string.match(regex);\n}",
"function fuzz () {\n let len = 10\n let alpha = 'abcdfghijk'\n for (let v = 0; v < len; v++) {\n for (let w = 0; w < len; w++) {\n for (let x = 0; x < len; x++) {\n for (let y = 0; y < len; y++) {\n for (let z = 0; z < len; z++) {\n let str = [alpha[v], alpha[w], alpha[x], alpha[y], alpha[z]].join('')\n let tree = STree.create(str)\n testSuffixes(tree, str)\n }\n }\n }\n }\n }\n console.log('all ok')\n}",
"function generateHints(guess) {\n var guessArray = guess.split('');// split the strings to arrays \n\tvar solutionArray = solution.split('');// split the strings to arrays \n\tvar correctPlacement = 0; // create a variable for correctPlacement\n\t// create for loop that checks each items in the solution array against guess array\n\tfor (var i = 0; i < solutionArray.length; i++) {\n\t// if there is a match, set the location to null\n\t\tif (solutionArray[i] === guessArray[i]) {\n\t\t\tcorrectPlacement++; \n\t\t\tsolutionArray[i] = null;\n\t\t}\n\t}\n\tvar correctLetter = 0; // create a variable for correctLetter\n\t// create for loop that checks indexOf each items in the guess array against solution array\n\t// note: indexOf automatically returns -1 if there are no instances\n // if there is a match it signifies correctLetter\n\tfor (var i = 0; i < solutionArray.length; i++\t) {\n\t\tvar targetIndex = solutionArray.indexOf(guessArray[i]);\n\t\tif (targetIndex > -1) {\n\t\t\tcorrectLetter++;\n\t\t\tsolutionArray[targetIndex] = null;\n\t\t}\n}\nreturn colors.red(correctPlacement + ' - ' + correctLetter);\n}",
"function findShort(inputString){\n splitString = inputString.split(' ')\n shortestLength = splitString[0].length\n\n for (let word of splitString) {\n if (word.length < shortestLength) {\n shortestLength = word.length\n }\n }\n return shortestLength\n }",
"function matchingChars(lifeForm, targetLifeform){\r\n\tvar matchedLetters = 0;\r\n\tlifeForm = lifeForm.toLowerCase();\r\n\ttargetLifeform = targetLifeform.toLowerCase();\r\n\tfor(var i = 0; i < lifeForm.length && i < targetLifeform.length; i++){\r\n\t\tif( lifeForm.substring(i, i+1) === targetLifeform.substring(i, i+1) ){\r\n\t\t\tmatchedLetters++;\r\n\t\t}\r\n\t}\r\n\treturn (matchedLetters / lifeForm.length);\r\n}",
"match(word) {\n if (this.pattern.length == 0) return [-100 /* NotFull */]\n if (word.length < this.pattern.length) return null\n let { chars, folded, any, precise, byWord } = this\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0),\n firstSize = codePointSize(first)\n let score = firstSize == word.length ? 0 : -100 /* NotFull */\n if (first == chars[0]);\n else if (first == folded[0]) score += -200 /* CaseFold */\n else return null\n return [score, 0, firstSize]\n }\n let direct = word.indexOf(this.pattern)\n if (direct == 0)\n return [\n word.length == this.pattern.length ? 0 : -100 /* NotFull */,\n 0,\n this.pattern.length\n ]\n let len = chars.length,\n anyTo = 0\n if (direct < 0) {\n for (\n let i = 0, e = Math.min(word.length, 200);\n i < e && anyTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (next == chars[anyTo] || next == folded[anyTo]) any[anyTo++] = i\n i += codePointSize(next)\n }\n // No match, exit immediately\n if (anyTo < len) return null\n }\n // This tracks the extent of the precise (non-folded, not\n // necessarily adjacent) match\n let preciseTo = 0\n // Tracks whether there is a match that hits only characters that\n // appear to be starting words. `byWordFolded` is set to true when\n // a case folded character is encountered in such a match\n let byWordTo = 0,\n byWordFolded = false\n // If we've found a partial adjacent match, these track its state\n let adjacentTo = 0,\n adjacentStart = -1,\n adjacentEnd = -1\n let hasLower = /[a-z]/.test(word),\n wordAdjacent = true\n // Go over the option's text, scanning for the various kinds of matches\n for (\n let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */;\n i < e && byWordTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0) adjacentStart = i\n adjacentEnd = i + 1\n adjacentTo++\n } else {\n adjacentTo = 0\n }\n }\n }\n let ch,\n type =\n next < 0xff\n ? (next >= 48 && next <= 57) || (next >= 97 && next <= 122)\n ? 2 /* Lower */\n : next >= 65 && next <= 90\n ? 1 /* Upper */\n : 0 /* NonWord */\n : (ch = fromCodePoint(next)) != ch.toLowerCase()\n ? 1 /* Upper */\n : ch != ch.toUpperCase()\n ? 2 /* Lower */\n : 0 /* NonWord */\n if (\n !i ||\n (type == 1 /* Upper */ && hasLower) ||\n (prevType == 0 /* NonWord */ && type != 0) /* NonWord */\n ) {\n if (\n chars[byWordTo] == next ||\n (folded[byWordTo] == next && (byWordFolded = true))\n )\n byWord[byWordTo++] = i\n else if (byWord.length) wordAdjacent = false\n }\n prevType = type\n i += codePointSize(next)\n }\n if (byWordTo == len && byWord[0] == 0 && wordAdjacent)\n return this.result(\n -100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0),\n byWord,\n word\n )\n if (adjacentTo == len && adjacentStart == 0)\n return [\n -200 /* CaseFold */ -\n word.length +\n (adjacentEnd == word.length ? 0 : -100) /* NotFull */,\n 0,\n adjacentEnd\n ]\n if (direct > -1)\n return [\n -700 /* NotStart */ - word.length,\n direct,\n direct + this.pattern.length\n ]\n if (adjacentTo == len)\n return [\n -200 /* CaseFold */ + -700 /* NotStart */ - word.length,\n adjacentStart,\n adjacentEnd\n ]\n if (byWordTo == len)\n return this.result(\n -100 /* ByWord */ +\n (byWordFolded ? -200 /* CaseFold */ : 0) +\n -700 /* NotStart */ +\n (wordAdjacent ? 0 : -1100) /* Gap */,\n byWord,\n word\n )\n return chars.length == 2\n ? null\n : this.result(\n (any[0] ? -700 /* NotStart */ : 0) +\n -200 /* CaseFold */ +\n -1100 /* Gap */,\n any,\n word\n )\n }",
"function smallestSubstringContaining(bigString, smallString) {\n const targetCharCounts = getCharCounts(smallString); //iterate through small string and store the count of charcaters in a hash\n // console.log('targetCharCounts', targetCharCounts);\n const substringBounds = getSubstringBounds(bigString, targetCharCounts);\n // console.log('substringBounds',substringBounds)\n return getStringFromBounds(bigString, substringBounds);s\n }",
"function LCS2(str1, str2) {\n\t// get short and long str\n\tlet { shortestName, longestName } = stringLen(str1, str2)\n\tshortestName = stringLen(str1, str2).shortestVal\n\tlongestName = stringLen(str1, str2).longestVal\n\tlet indexShort\n\tlet arr = []\n\tlet longestNameCopy1 = longestName.slice()\n\tlet longestNameCopy2 = longestNameCopy1.slice()\n\tlet k = 0\n\tlet count = countInstances(longestName)\n\t// keep copy of original count\n\tconst originalCount = JSON.parse(JSON.stringify(count))\n\twhile(longestNameCopy1) {\n\t\tlet i = 0\n\t\t// reset substr each loop\n\t\tlet subStr = \"\"\n\t\t// keep each iteration in temp arr\n\t\tlet tempArr = []\n\t\tlet shortestNameCopy = shortestName.slice()\n\t\t// keep copy of fullSubstr\n\t\tlet fullSubstring = \"\"\n\n\t\t// start substring from found letter forward\n\t\tfunction makeSubtr(shortCopy, longCopy, shortIndex) {\n\t\t\tindexShort = shortCopy.indexOf(longCopy[0])\n\t\t\t// start make subStr of shorter str on each round - remove starting letter\n\t\t\tshortCopy = shortCopy.substring(indexShort + 1, shortCopy.length)\n\t\t\treturn shortCopy\n\t\t}\n\n\t\tfunction getLetters(subString, longString, count) {\n\t\t\tif(!longString) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// check if substring includes longString part\n\t\t\tif(subString.includes(longString[0])) {\n\t\t\t\t// get index of letter in of shorter\n\t\t\t\tindexShort = shortestNameCopy.indexOf(longString[0])\n\t\t\t\t// copy full substr to above\n\t\t\t\tif(!fullSubstring) {\n\t\t\t\t\tfullSubstring = shortestNameCopy.substring(indexShort, shortestNameCopy.length)\n\t\t\t\t}\n\t\t\t\t// make subString of shorter str on each round -remove first letter\n\t\t\t\tsubString = makeSubtr(subString, longString[0], indexShort)\n\t\t\t\t// push to store\n\t\t\t\ttempArr.push(longString[0])\n\t\t\t\t// decrement count\n\t\t\t\tcount[longString[0]].count--\n\t\t\t\t// shift first char off long\n\t\t\t\tlongString = shiftString(longString)\n\t\t\t} else {\n\t\t\t\tlongString = shiftString(longString)\n\t\t\t}\n\t\t\tgetLetters(subString, longString, count)\n\t\t}\n\t\tgetLetters(shortestNameCopy, longestNameCopy1, count)\n\t\t// check if any part of count is left\n\t\tObject.values(count).forEach((val, i) => {\n\t\t\tlet value = Object.keys(count)[i]\n\t\t\t// check if values are in the substring\n\t\t\tif(val.count > 0 && fullSubstring.includes(value)) {\n\t\t\t\tlet charIndexes = getCharIndexes(longestNameCopy1, value)\n\t\t\t\t// splice each index out of the longestName and rerun\n\t\t\t\tcharIndexes.forEach(index => {\n\t\t\t\t\tlet newLong = stringSplice(longestNameCopy1, index)\n\t\t\t\t\tif(tempArr.length) {\n\t\t\t\t\t\tarr.push(tempArr)\n\t\t\t\t\t\ttempArr = []\n\t\t\t\t\t}\n\t\t\t\t\tlet countCopy = JSON.parse(JSON.stringify(originalCount))\n\t\t\t\t\t// recall with long with removed index and full count\n\t\t\t\t\tgetLetters(fullSubstring, newLong, countCopy)\n\t\t\t\t})\n\t\t\t}\n\n\t\t})\n\t\t// decrease long string by one\n\t\tlongestNameCopy2 = shiftString(longestNameCopy2)\n\t\tlongestNameCopy1 = longestNameCopy2\n\t\tarr.push(tempArr)\n\t\t// recalc count obj\n\t\tcount = countInstances(longestName)\n\t\tk++\n\t}\n\t// find the longest string\n\tfunction findLongest() {\n\t\tlet longestLen = 0\n\t\tlet longest = \"\"\n\t\tarr.forEach(i => {\n\t\t\tif(i.length > longestLen) {\n\t\t\t\tlongestLen = i.length\n\t\t\t\tlongest = i\n\t\t\t}\n\t\t})\n\t\treturn longest ? longest.join('') : longest\n\t}\n\treturn findLongest(arr)\n}",
"function minimuNumberOfApperances(char, arrayOfStrings) {\n return Math.min(...arrayOfStrings.map(string => (string.match(new RegExp(char,'g')) || []).length));\n}",
"function longWord (input) {\n return input.some(x => x.length > 10);\n}",
"function makeAnagram(a, b) {\n let count = 0;\n\n //track all the letters that are the longer string and then compare them to the letters from the short string.\n let freq = {};\n\n const longStr = a.length > b.length ? a : b;\n const shortStr = longStr === a ? b : a;\n\n // Log all chars from the long string into an object\n for (let char of longStr) {\n freq[char] >= 0 ? (freq[char] += 1) : (freq[char] = 0);\n }\n\n // see if the character is found in longString --> if so. add to count and subtract from obj\n for (let char of shortStr) {\n if (freq[char] >= 0) {\n count++;\n freq[char] -= 1;\n }\n }\n // The count variable is the common letters between each string\n // subtract count from the length of each string and add result together\n const deletions = longStr.length - count + shortStr.length - count;\n console.log(deletions);\n return deletions;\n}",
"match(word) {\n if (this.pattern.length == 0)\n return [0];\n if (word.length < this.pattern.length)\n return null;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0);\n return first == chars[0] ? [0, 0, codePointSize(first)]\n : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return [0, 0, this.pattern.length];\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return null;\n }\n let preciseTo = 0;\n let byWordTo = 0, byWordFolded = false;\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {\n let next = codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)\n : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);\n if (type == 1 /* Upper */ || prevType == 0 /* NonWord */ && type != 0 /* NonWord */ &&\n (this.chars[byWordTo] == next || (this.folded[byWordTo] == next && (byWordFolded = true))))\n byWord[byWordTo++] = i;\n prevType = type;\n i += codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return [-200 /* CaseFold */, 0, adjacentEnd];\n if (direct > -1)\n return [-700 /* NotStart */, direct, direct + this.pattern.length];\n if (adjacentTo == len)\n return [-200 /* CaseFold */ + -700 /* NotStart */, adjacentStart, adjacentEnd];\n if (byWordTo == len)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */, byWord, word);\n return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);\n }",
"function generateTestStrings(cnt, len) {\n\tlet test = [];\n\tfor(let i=0; i<cnt; i++) {\n\t\t// generate a string of the specified len\n\t\ttest[i] = getRandomString(len, 0, 65535);\n//\t\ttest[i] = getRandomString(len, 0, 55295);\n\t}\n\treturn test;\n}",
"function isCorrectLengthExtensions(s) {\n return isCorrectLength(s,50);\n}",
"function seaSick(x) {\n let w = 0;\n\n x.split('').forEach((el, i) => {\n if (el === '_' && x[i + 1] === '~') w++;\n else if (el === '~' && x[i + 1] === '_') w++;\n });\n\n if (w > (x.length * 20) / 100) return 'Throw Up';\n else return 'No Problem';\n}",
"generateSmallDescription(text){\r\n\t if(text){\r\n\t\tif(text.length > 120){\r\n\t\t text= text.slice(0,120) + '...';\r\n\t\t return text;\r\n\t\t}\r\n\t\telse{\r\n\t\t return text;\r\n\t\t}\r\n\t }\r\n\t}",
"function numKeypadSolutions(wordlist, keypads) {\n // Write your code here\n // INPUT: an array of acceptable words\n // an array of 7 letter strings, each letter representing a key button\n // OUTPUT: array of numbers corresponding to the number of words from wordlist\n // that can be made from each keypad in order\n // CONSTRAINTS: all words in wordlist are at least 5 letters long\n // first letter of each keypad is guaranteed to be in the word\n // longest word in scrabble dictionary is 15 characters long - must be faster way\n // EDGE CASES: what happens if no letters match?\n\n // iterate over wordlist, and store a set in a new wordlist array of all letters of word\n let wordListSets = wordlist.map(word => {\n let wordSet = new Set();\n for(let i=0; i < word.length; i++) {\n let letter = word[i];\n if(!wordSet.has(letter)) { wordSet.add(letter) }\n }\n return wordSet;\n });\n\n // write a mapping function that takes a keypad string\n // initiates a count at 0\n // makes a set of the string\n // loops through the entire new wordlist array\n // if the word doesn't have keypadstring[0] continue\n // if all letters in word set are contained in string set increment the count\n // return the count\n let numValidSolutions = keypads.map(keyString => {\n let solutionCount = 0;\n let keyStringSet = new Set();\n for(let i=0; i < keyString.length; i++) {\n let letter = keyString[i];\n if(!keyStringSet.has(letter)) { keyStringSet.add(letter) }\n }\n\n for(let j = 0; j < wordListSets.length; j++) {\n let allLettersPresent = true;\n let wordSetInQuestion = wordListSets[j];\n if (!wordSetInQuestion.has(keyString[0])) { continue }\n for(let letter of wordSetInQuestion) {\n if(!keyStringSet.has(letter)) {\n allLettersPresent = false;\n break;\n }\n }\n\n if (allLettersPresent) { solutionCount++ }\n }\n\n return solutionCount;\n })\n\n return numValidSolutions;\n // THE ULTRA 1337 SOLUTION USES A BIT MASK. WTF IS THAT\n}",
"function moreZeros(s) {\n s = [... new Set(s)].join('')\n const result = []\n\n\n s.split('').forEach((el, index) => {\n const e = s.charCodeAt(index).toString(2)\n let zeros = 0\n let ones = 0\n\n if (e.match(/0/g) !== null) zeros = e.match(/0/g).length\n if (e.match(/1/g) !== null) ones = e.match(/1/g).length\n\n zeros > ones ? result.push(el) : null\n });\n\n\n\n return result\n}",
"function checkRepetition(pLen,str)\n{\n res = \"\";\n for ( i=0; i<str.length ; i++ ) {\n repeated=true;\n for (j=0;j < pLen && (j+i+pLen) < str.length;j++) {\n repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen));\n }\n\n if (j<pLen) repeated=false;\n if (repeated) {\n i+=pLen-1;\n repeated=false;\n } else {\n res+=str.charAt(i);\n }\n }\n return res\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a path from a variable length list of curve primtiives | static create(...curves) {
const result = new Path();
for (const curve of curves) {
result.children.push(curve);
}
return result;
} | [
"function Path(spec, colorfunction) {\n\tvar points = spec.split(',')\n\tthis.colorfunction = colorfunction\n\tthis.path = new Array(points.length)\n\tthis.path[0] = this.translate(points[0])\n\tthis.start = this.end = null\n\t\n\tfor(var i = 1; i < points.length; i++) {\n\t\tthis.path[i] = this.step(points[i], this.path[i-1])\n\t}\n\tthis.length = this.computeLength()\n}",
"function pointsToPath(points) {\r\n return points.map(function(point, iPoint) {\r\n return (iPoint>0?'L':'M') + point[0] + ' ' + point[1];\r\n }).join(' ')+'Z';\r\n }",
"constructor(pathList){\n\t\tthis.pointPath = pathList;\n\t}",
"path(x, y) {\n stroke(116, 122, 117);\n strokeWeight(4);\n fill(147, 153, 148);\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n rect(x - this.pxl * i, y + this.pxl * j, this.pxl, this.pxl);\n }\n }\n }",
"function genPathways(waypoints) \n{\n\t// Define a dashed line symbol using SVG path notation, with an opacity of 1.\n\tvar lineSymbol = {path: \"M 0,-1 0,1\", strokeOpacity: 1, scale: 2}\n\n\tvar pathColors = [\"#ff6600\", \"#f40696\", \"#FF0000\", \"#d39898\", \"#00FF00\", \"#FFA500\", \"#0000FF\"];\n\tvar pcSize = pathColors.length \n\n\tJSbldPathways(waypoints, pathways);\n\n\tvar nx = 0;\t// Index for path names in array\n\tvar px = 0;\t// Color index\n\n\tfor (pw in pathways)\n\t{\n\t\tif(LOG_PW == true)\n\t\t{\n\t\t\tconsole.log(pathways[pw]);\n\t\t}\n\t\n\t\tnewPath = new google.maps.Polyline({\n\t\t\tpath: pathways[pw],\n\t\t\tgeodesic: true,\n\t\t\tstrokeColor: pathColors[px++],\n\t\t\tstrokeOpacity: 0,\n\t\t\ticons: [{icon: lineSymbol,offset: '0',repeat: '10px'}],\n\t\t\tstrokeWeight: 1});\n\t\t\n\t\tnewPath.setMap(map);\n\t\tptNames[nx++] = newPath;\n\n\t\tpx = (px >= pcSize ? 0 : px);\n\t}\n}",
"getCurve( startX, startY, endX, endY ) {\n let middleX = startX + (endX - startX) / 2;\n return `M ${startX} ${startY} C ${middleX},${startY} ${middleX},${endY} ${endX},${endY}`;\n }",
"get curve() {}",
"function drawCurve() {\n\tfor(let i=0;i<curvePts.length-1;i++) {\n\t\tlet pt1 = curvePts[i];\n\t\tlet pt2 = curvePts[i+1];\n\t\tdrawLine(pt1.x, pt1.y, pt2.x, pt2.y, 'rgb(0,255,0)');\n\t}\n}",
"function trianglePath(triangles){\n var path = \"M \" + xScale(triangles[0].x) + \",\" + yScale(triangles[0].y);\n path += \" L \" + xScale(triangles[1].x) + \",\" + yScale(triangles[1].y);\n path += \" L \" + xScale(triangles[2].x) + \",\" + yScale(triangles[2].y) + \" Z\";\n\n return path;\n}",
"function addPointsToPath(point){\r\n path.push(point);\r\n $('#coordinates-container').html('');\r\n \r\n for(var i = 0; i < path.length; i++){\r\n $('#coordinates-container').html($('#coordinates-container').html() + 'x: ' + path[i].x + ' y: ' + path[i].y + '<br/>');\r\n }\r\n}",
"function buildCurve(curve) {\n var base = d3['curve' + curve.name]; // The base curve without any arguments\n var args = curve.args;\n var built;\n\n if (args !== false) {\n var x;\n built = base;\n for (var i = 0; i < args.length; i++) {\n x = args[i];\n built = built[x.name](x.value) // Plug in the argument\n }\n } else {\n built = base;\n }\n return d3.line().curve(built);\n}",
"continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }",
"function createPathString(data) {\n\t\t\t\n\t\t\t var points = data.charts[data.current].points;\n\t\t\t\n\t\t\t \n\t\t\t\tvar path = 'M 25 291 L ' + data.xOffset + ' ' + (data.yOffset - points[0].value);\n\t\t\t\tvar prevY = data.yOffset - points[0].value;\n\t\t\t\n\t\t\t\tfor (var i = 1, length = points.length; i < length; i++) {\n\t\t\t\t\tpath += ' L ';\n\t\t\t\t\tpath += data.xOffset + (i * data.xDelta) + ' ';\n\t\t\t\t\tpath += (data.yOffset - points[i].value);\n\t\t\t\n\t\t\t\t\tprevY = data.yOffset - points[i].value;\n\t\t\t\t}\n\t\t\t\t//path += ' L 989 291 Z';\n\t\t\t\tpath += ' L 2200 291 Z';\n\t\t\t\treturn path;\n\t\t\t}",
"function drawPath(pathList, allNodes){\n\n\tvar path = pathList;\n\tvar start = 0;\n\n\t// Draw path with delay\n\tdrawPathWithDelay(path, allNodes, start, path.length, 150);\t\n}",
"static createArray(curves) {\n const result = new Loop();\n for (const curve of curves) {\n result.children.push(curve);\n }\n return result;\n }",
"function PathAnimation(p, x1, y1, x2, y2, th) {\n this._p = p;\n this._x1 = x1;\n this._y1 = y1;\n this._x2 = x2;\n this._y2 = y2;\n this._th = th;\n}",
"function drawBezierCurve(context, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y, lines) {\r\n const bezierMatrix = [[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 3, 0, 0], [1, 0, 0, 0]];\r\n const pointVectorX = [p1x, p2x, p3x, p4x];\r\n const pointVectorY = [p1y, p2y, p3y, p4y];\r\n\r\n const cx = multiplyMatrixByVector(bezierMatrix, pointVectorX);\r\n const cy = multiplyMatrixByVector(bezierMatrix, pointVectorY);\r\n\r\n step = 1/lines;\r\n for(let t = 0; Math.floor((t+step)*100)/100 <= 1; t+=step) {\r\n let startX = calculateCurvePoint(cx, 1-t);\r\n let startY = calculateCurvePoint(cy, 1-t);\r\n let endX = calculateCurvePoint(cx, 1-(t+step));\r\n let endY = calculateCurvePoint(cy, 1-(t+step));\r\n\r\n drawLine(context, startX, startY, endX, endY);\r\n if(Math.floor((t+step)*100)/100 === 1)\r\n break\r\n }\r\n}",
"function serializePaths(){\r\n var paths = extractSelectedPaths();\r\n var data = [];\r\n\r\n var MARGIN_TOP = 50;\r\n var MARGIN_LEFT = 25;\r\n \r\n var top_left = getTopLeftOfPaths(paths);\r\n var top = top_left[0] + MARGIN_TOP;\r\n var left = top_left[1] - MARGIN_LEFT;\r\n \r\n for(var i = paths.length - 1; i >= 0; i--){\r\n var r = [\"@\"]; // \"@\" is a mark that means the beginning of a path\r\n var p = paths[i];\r\n \r\n r.push(p.closed ? \"1\" : \"0\");\r\n\r\n r.push([p.filled ? \"1\" : \"0\",\r\n serializeColor(p.fillColor)]);\r\n \r\n r.push([p.stroked && p.strokeColor.typename != \"NoColor\" ? \"1\" : \"0\",\r\n _f2s(p.strokeWidth),\r\n serializeColor(p.strokeColor)]);\r\n\r\n for(var j = 0, jEnd = p.pathPoints.length; j < jEnd; j++){\r\n var ppt = p.pathPoints[j];\r\n var anc = ppt.anchor;\r\n r.push([_f2s(anc[0] - left), _f2s(anc[1] - top),\r\n _f2s(ppt.rightDirection[0] - anc[0]),\r\n _f2s(ppt.rightDirection[1] - anc[1]),\r\n _f2s(ppt.leftDirection[0] - anc[0]),\r\n _f2s(ppt.leftDirection[1] - anc[1])]);\r\n // ignore pointType becauses paper js doesn't have this property\r\n }\r\n \r\n data[data.length] = r;\r\n }\r\n \r\n // \"data\" is passed to callback function as a comma separated string\r\n return data;\r\n}",
"function _buildArrowPoints(line){\n\t\tvar sx = line.shape.x1,\n\t\t\tsy = line.shape.y1,\n\t\t\tex = line.shape.x2,\n\t\t\tey = line.shape.y2;\n\t var len = Math.sqrt((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy));\n\t if (len == 0) {\n\t return;\n\t }\n\t var t = (ey - sy) / (ex - sx);\n\t var angle = Math.atan(t);\n\t var x, y;\n\t var len1 = Math.min(10, len - 2);\n\t var len2 = Math.min(3, len / 2 - 1);\n\t if (ex < sx) {\n\t x = (len1 - len) * Math.cos(angle) + sx;\n\t y = (len1 - len) * Math.sin(angle) + sy;\n\t } else{\n\t x = (len - len1) * Math.cos(angle) + sx;\n\t y = (len - len1) * Math.sin(angle) + sy;\n\t }\n\t var x3 = x + len2 * Math.sin(angle);\n\t var y3 = y - len2 * Math.cos(angle);\n\t var x4 = x - len2 * Math.sin(angle);\n\t var y4 = y + len2 * Math.cos(angle);\n\t return [{\n\t x : ex,\n\t y : ey\n\t }, {\n\t x : x3,\n\t y : y3\n\t }, {\n\t x : x4,\n\t y : y4\n\t } ];\n\t}",
"function build_path(p_orig, p_dest){\n var res = new Array();\n\n if(p_orig.x == p_dest.x){\n if(p_orig.y < p_dest.y){\n // Vertical path, going downwards.\n for(var y = p_orig.y + 1; y <= p_dest.y; y++){\n res.push({x: p_orig.x, y: y});\n }\n } else {\n // Vertical path, going upwards.\n for(var y = p_orig.y - 1; y >= p_dest.y; y--){\n res.push({x: p_orig.x, y: y});\n }\n }\n } else if(p_orig.y == p_dest.y){\n if(p_orig.x < p_dest.x){\n // Horizontal path, going to the right.\n for(var x = p_orig.x + 1; x <= p_dest.x; x++){\n res.push({x: x, y: p_orig.y});\n }\n } else {\n // Horizontal path, going to the left.\n for(var x = p_orig.x - 1; x >= p_dest.x; x--){\n res.push({x: x, y: p_orig.y});\n }\n }\n } else {\n res.push(p_dest); // TODO properly handle diagonal paths.\n }\n\n return res;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
code starts from here / "fetchData" function to fetch price updates Retrieved data is stored in "rawData" | function fetchData() {
client.subscribe("/fx/prices", function (data) { //subscribing for updates
rawData.push(JSON.parse(data.body)); //storing retrived data
});
} | [
"async price_update() {}",
"async fetchCoinPrice() {\n await fetch(\"https://api.coingecko.com/api/v3/simple/price?ids=\" + this.getCoinID() + \"&vs_currencies=usd\")\n .then((response) => response.json())\n .then((json) => {\n this.coinPrice = json[this.getCoinID()][\"usd\"];\n })\n .catch((error) => console.error(error))\n .finally(() => {\n this.priceLoaded = true;\n this.coinPrice = this.coinPrice;\n });\n }",
"function getInitialPrices(){\n\n\t$.getJSON(\"https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR,GBP,JPY,KRW,INR,ETH,LTC\", function(data) {\n\t // Collect the data in the BTCPRICES variable\n\t Object.assign(BTCPRICES, data);\n\t // Update the prices to the website\n\t updatePrices();\n\t updateTables();\n\t // Update the autocomplete options\n\t updateAutocomplete();\n\t // Do an inital conversion for the default value in the left box\n\t calculateConversion(\"right\");\n\t updateSummary();\n\t updateTime();\n\t // Get all the other coins\n\t getCoins();\n\t\t});\n}",
"function getDataCoinbase()\n {\n $.ajax({\n url: \"https://api.gdax.com/products/btc-usd/candles/\",\n success: function(data)\n {\n var data = {\n last: $(\"#tableData\").attr(\"data-usd-coinbase\"),\n volume: data[0][5],\n high : data[0][2],\n low : data[0][1]\n };\n\n $.ajax({\n url: \"serverCoinbase\",\n method: \"GET\",\n data: \"dataCoinbase=\" + JSON.stringify(data),\n success: function(){}\n });\n }\n })\n }",
"function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }",
"async function update() {\n try {\n let coins = await fetchStablecoins();\n DATA.stablecoins = updateStablecoinData(coins, DATA.stablecoins);\n DATA.metrics = calcMetrics(DATA.stablecoins);\n DATA.platform_data = calcPlatformData(DATA.stablecoins);\n console.info('Data Updated.');\n } catch (e) {\n console.error(` ***CRITICAL*** Could not update data: ${e}`);\n }\n}",
"checkAvailData() {\n \n return new Promise((resolve, reject) => {\n // check if it is necessary to load new data\n if (this.dataPointer-this.noCandles < 0) {\n var dir = 'left';\n var message = createMessageForDataLoad(this.dtArray[0], dir);\n } else if (this.dataPointer > this.priceArray.length-1) {\n var dir = 'right';\n var message = createMessageForDataLoad(this.dtArray.slice(-1)[0], dir);\n } else { return resolve(); }\n // load new data if necessary\n this.isLoadingData = true;\n serverRequest('loadNewData', message).then((data) => {\n if (dir === 'left') { \n this.dataPointer += data.length;\n data = this.parseDates(data);\n this.priceArray = data.concat(this.priceArray);\n this.createDtArray();\n } else if (dir === 'right') {\n data = this.parseDates(data);\n this.priceArray = this.priceArray.concat(data);\n this.createDtArray();\n }\n return resolve();\n });\n });\n }",
"getData(base, date) {\n this.currencies = [];\n \n fetch(`https://api.exchangeratesapi.io/${date}?base=${base}`)\n .then(response => response.json())\n .then(json => {\n // console.log(json);\n for (const currency in json.rates) {\n this.currencies.push(new Currency(currency));\n }\n\n // Loop through currencies and set 'buy' to 5% less than conversion.\n // Loop through currencies and set 'sell' to 5% more than conversion.\n \n this.currencies.forEach(currency => {\n currency.buy = (json.rates[currency.name] * 0.95).toFixed(4);\n currency.sell = (json.rates[currency.name] * 1.05).toFixed(4);\n });\n\n // If page is being loaded for first time, table mounts.\n // Otherwise table updates with new base of alphabet order.\n \n if (this.table.mounted === false) {\n this.table.mount(container, this.currencies);\n } else {\n this.table.updateHTML(this.currencies, this.base);\n }\n });\n }",
"function fetchTickerPrices() {\n store.dispatch('fetchTickerPrices');\n setTimeout(fetchTickerPrices, 60000 /* One minute. */);\n}",
"function upethprice(){\n //send info request to server\n fetch(API_ethprice+API_KEY)\n //when the server responds, do this\n .then( result => result.json() )\n //when the server responds, do this\n .then(res => {\n //if an error happens that is not classified as an error (etherscan.io didn't work well)\n if (res.status != \"1\")\n throw (\"etherscan.io error, failed to load\"); \n //update ethereum price\n document.getElementById(\"ethprice\").innerHTML = res.result.ethusd;\n //update the clock on most recent update of eth price\n updateClock(\"timeupdated\",res.result.ethusd_timestamp*1000 );\n })\n //if an error was found, do this\n .catch(err => console.log(\"Etherscan.io failed because of error: \"+ err));\n }//endupethprice",
"function pullLivePriceData(url){\n var reqq = new XMLHttpRequest();\n reqq.open(\"GET\", url, false);\n reqq.send(null);\n var r = JSON.parse(reqq.response);\n return r;\n}",
"apiPromise(apiAction) {\n Promise.all([this.apiCall(apiAction).getData(), this.apiCall(apiAction).getPrice()])\n .then(([data, prices]) => {\n this.setState({\n coinData: data,\n coinPrice: prices\n });\n })\n }",
"function getprices() {\n\trequest(c.URL, function(error, res, body) {\n\t\tif (!error && res.statusCode == 200) {\n\n\t\t\tvar prices = {};\n\t\t\tvar result = JSON.parse(body);\n\n\t\t\tprices.btcusd = result.btc_usd;\n\t\t\tprices.btceur = result.btc_eur;\n\t\t\tprices.ltcusd = result.ltc_usd;\n\t\t\tprices.ltceur = result.ltc_eur;\n\t\t\tprices.ethusd = result.eth_usd;\n\n\t\t\tvar json = JSON.stringify(prices);\n\t\t\tfs.writeFile('./src/prices.json', json, function(err) {\n\t\t\t\tif (err) throw err;\n\t\t\t});\n\n\t\t\t// loop indefinitely\n\t\t\tsetTimeout(function(){getprices()}, 60000);\n\t\t}\n\t});\n}",
"function successfulCarmaPull(data) {\n geo_info_object.fossil = parseFloat(data[0].fossil.present);\n geo_info_object.hydro = parseFloat(data[0].hydro.present);\n geo_info_object.nuclear = parseFloat(data[0].nuclear.present);\n geo_info_object.renewable = parseFloat(data[0].renewable.present);\n google.charts.setOnLoadCallback(drawChart);\n}",
"function stockDataRequest(ticker) {\n\n var apiKey = \"TFCCMLBLD91O6OFT\";\n var queryURL = \"https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol=\" + ticker + \"&apikey=\" + apiKey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n //changing the objects of objects into an array of objects\n var responseArray = [];\n for (item in response[\"Monthly Adjusted Time Series\"]) {\n responseArray.push(response[\"Monthly Adjusted Time Series\"][item]);\n }\n\n //storing 4 values in an array to show quarterly growth\n var quarterlyData = [];\n for (var i = 13; i > 0; i -= 4) {\n quarterlyData.push(responseArray[i][\"5. adjusted close\"]);\n }\n\n //check if the stock is worth buying and display it\n worthBuy(quarterlyData);\n\n //passing through the data we retrieved to the displayChart function to show the chart on screen\n displayChart(quarterlyData);\n displayStats(responseArray[0]);\n\n\n });\n}",
"fetchAllData(){\n // clear current prosumerData list\n this.prosumerData = new Array()\n var query = `query { \n simulate {\n consumption\n wind\n }\n \n }`\n\n this.prosumerList.forEach( pro => {\n fetchFromSim(query).then( (data) => {\n // structure of returned data: data['data']['simulate']['getWind']\n this.prosumerData.push(\n {\n \"id\": pro.id,\n \"consumption\": data.data.simulate.consumption,\n \"wind\": data.data.simulate.wind\n }\n )\n })\n })\n }",
"_startPollingData() {\n this._pollDataInterval = setInterval(() => this._getBalance(), 3000);\n\n // We run it once immediately so we don't have to wait for it\n this._getBalance();\n }",
"function getCoins() {\r\n console.log(\"checking if getCoins works\");\r\n $.get(\"/api/coins\", function(data){\r\n\r\n var rowsToAdd = [];\r\n var coinPriceArray = [];\r\n for (var i = 0; i <data.length; i++) {\r\n rowsToAdd.push(createCoinRow(data[i]));\r\n }\r\n renderCoinList(rowsToAdd);\r\n console.log(\"rows to add are \" + rowsToAdd);\r\n });\r\n \r\n }",
"function getData() {\n // let toDate = e;\n // console.log(toDate.target.value)\n console.log(to.onchange)\n\n\n axios.get(`http://api.coindesk.com/v1/bpi/historical/close.json?start=${fromDateValue}&end=${toDateValue}`)\n .then(res => {\n let labels = Object.keys(res.data.bpi)\n let values = Object.values(res.data.bpi)\n printChart(res.data, labels, values)\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the selected currency to the matching string and switches the widget to match. | function setSelectedCurrency(currency) {
selectedCurrency = currency;
var currencyOpt = document.getElementById(currency);
if (currencyOpt) {
currencyOpt.selected = "selected";
}
} | [
"function setCurrencyList(currency, defval) {\r\n var obj = {}\r\n for (var key in currency) {\r\n obj[currency[key]] = null\r\n }\r\n $('#ddcurrlist').material_chip({\r\n placeholder: \"Enter Currency Pair\",\r\n data: defval,\r\n autocompleteLimit: 5,\r\n autocompleteOptions: {\r\n data: obj,\r\n limit: 7,\r\n minLength: 1\r\n }\r\n });\r\n $('.chips').on('chip.add', function(e, chip) {\r\n socket.emit('subscribecurr', {\r\n \"currency\": chip.tag,\r\n \"user\": username\r\n })\r\n subscribeCurrency(chip.tag);\r\n });\r\n\r\n $('.chips').on('chip.delete', function(deleted, chip) {\r\n var tag = chip.tag.replace(\"/\", \"\");\r\n socket.emit('unsubscribecurr', {\r\n \"currency\": chip.tag,\r\n \"user\": username\r\n })\r\n $(\"#\" + tag + \"block\").remove();\r\n if ($('#ddcurrlist').material_chip(\"data\").length== 0) $(\"#norecord\").show()\r\n else $(\"#norecord\").hide() \r\n });\r\n}",
"function setPayOptionAsSelected(optionVal){\r\n\tjQuery(\"#paymentMethodSelection option[value='\"+optionVal+\"']\").attr('selected', 'selected');\r\n\t$('#paymentMethodSelection').find(':option').addClass('selected').removeClass('selected');\r\n\tjQuery(\"#paymentMethodSelection option[value='\"+optionVal+\"']\").addClass('selected');\r\n}",
"function getCurrencyWidget(parent) {\n\tvar widget = document.createElement(\"select\");\n\twidget.id = \"currencyWidget\";\n\twidget.name = \"currency\";\n\tvar option = document.createElement(\"option\");\n\toption.value = \"CAD\";\n\toption.id = \"CAD\";\n\toption.selected = \"selected\";\n\toption.innerHTML = \"Canadian Dollar\";\n\twidget.appendChild(option);\n\toption = document.createElement(\"option\");\n\toption.value = \"USD\";\n\toption.id = \"USD\";\n\toption.innerHTML = \"US Dollar\";\n\twidget.appendChild(option);\n\toption = document.createElement(\"option\");\n\toption.value = \"MXN\";\n\toption.id = \"MXN\"\n\toption.innerHTML = \"Mexican Peso\";\n\twidget.appendChild(option);\n\twidget.addEventListener(\"change\", changeSelectedCurrency, false);\n\tif (parent) {\n\t\tparent.appendChild(widget);\n\t} else {\n\t\treturn widget;\n\t}\n}",
"callback(value) { return ynabToolKit.shared.formatCurrency(value); }",
"switchCurrencies() {\n [this.selectedFromCurrency, this.selectedToCurrency] = [\n this.selectedToCurrency,\n this.selectedFromCurrency,\n ];\n shake(\"#exchange-calculator\");\n }",
"function swapCurrencies() {\r\n const temp = currencyOneSymbol.value;\r\n currencyOneSymbol.value = currencyTwoSymbol.value;\r\n currencyTwoSymbol.value = temp;\r\n updateRate();\r\n}",
"function switchText_cb(new_string)\r\n{\r\n\twith(currObj);\r\n\tnew_string = new_string.replace(/~~~/gi, \"\\n\");\r\n\r\n\t// Remove the prefixed asterisk that was added in switchText().\r\n\tnew_string = new_string.substr(1);\r\n\tcurrObj.objToCheck.style.display = \"none\";\r\n\tcurrObj.objToCheck.value = new_string;\r\n\tcurrObj.objToCheck.disabled = false;\r\n\tif(currObj.spellingResultsDiv)\r\n\t{\r\n\t\tcurrObj.spellingResultsDiv.parentNode.removeChild(currObj.spellingResultsDiv);\r\n\t\tcurrObj.spellingResultsDiv = null;\r\n\t}\r\n\tcurrObj.objToCheck.style.display = \"block\";\r\n\tcurrObj.resetAction();\r\n}",
"function updateCurrencyExchangeHtml(viewModel) {\n jQuery.each(viewModel.wallets, function(index, wallet) {\n var price = viewModel.cryptoCurrencies[wallet.currency][viewModel.selectedExchange].price;\n var val = (wallet.balance * price).toFixed(2);\n wallet.val = val;\n jQuery(\"#wallet-\" + index).find(\".dollarValue\").hide().html(\"$\" + val).fadeIn('fast');\n });\n\n jQuery(\"#exchangeRates\").hide();\n jQuery(\"#exchangeRates\").empty();\n var exchangeHtml = \"\";\n jQuery.each(viewModel.cryptoCurrencies, function(cryptoCurrency, cryptoData) {\n jQuery(\"#exchangeRates\").append(genCurrencyExchangeHtml(viewModel, cryptoCurrency, cryptoData));\n });\n jQuery(\"#exchangeRates\").fadeIn('fast');\n}",
"function updateAutocomplete(){\n\n\t// Get only the cryptocurrency names that we have a btc price for\n\tCRYPTONAMES = []\n\n\tfor (var key in CRYPTOCODES){\n\t\tif(BTCPRICES[CRYPTOCODES[key]]){\n\t\t\tCRYPTONAMES.push(key);\n\t\t}\n\t}\n\t\n\t// Create the autocompletes\n\t$( \"#currency1-name\").autocomplete({\n source: CRYPTONAMES,\n minLength: 2, // Change this if performance suffers once we have thousands of currencies\n close: function(ev,ui){\n \tcalculateConversion(\"left\");\n }\n });\n $( \"#currency2-name\").autocomplete({\n source: CRYPTONAMES,\n minLength: 2,\n close: function(ev,ui){\n \tcalculateConversion(\"right\");\n }\n });\n}",
"function onSelectionChange(){\n if (ui.amountBox.value > 0 && ui.icosBox.selectedIndex != 0 && ui.roundBox.selectedIndex != 0 && ui.currencyBox != 0) {\n onCalculateClick();\n }\n }",
"function CurrencyHandler() {\n\t\tthis.type = 'currency';\n\t}",
"function commerceProviderSelectedHandler() {\n const commerceProvider = getSelectedCommerceProvider();\n if (commerceProvider !== '') {\n const catalogs = getCatalogIdentifiers(commerceProvider);\n\n catalogIdentifierCoralSelectComponent.items.clear();\n const items = buildSelectItems(catalogs);\n items.forEach(item => {\n catalogIdentifierCoralSelectComponent.items.add(item);\n });\n catalogIdentifierCoralSelectComponent.disabled = false;\n } else {\n catalogIdentifierCoralSelectComponent.disabled = true;\n }\n }",
"function getCurrency(){\n //selected currencies\n fromCurr = selects[0].selectedOptions[0].textContent;\n toCurr = selects[1].selectedOptions[0].textContent;\n \n //get currency code according to currency name\n if(fromCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == fromCurr);\n base = currencies[index].currency_code;\n }\n\n if(toCurr !== ''){\n const index = currencies.findIndex((obj) => obj.currency_name == toCurr);\n rateKey = currencies[index].currency_code;\n }\n}",
"function init() {\n utilsService.addDropdownOptions('from-currency', availableCurrencies);\n document.getElementById('amount').value = defaultAmount;\n getRates(selectedBase);\n}",
"function getCurrency(amount) {\n\tvar fmtAmount;\n\tvar opts = {MinimumFractionDigits: 2, maximumFractionDigits: 2};\n\tif (selectedCurrency === \"CAD\") {\n\t\tfmtAmount = \"CAD $\" + amount.toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"USD\") {\n\t\tfmtAmount = \"USD $\" + (amount * currencyRates.USD).toLocaleString(undefined, opts);\n\t} else if (selectedCurrency === \"MXN\") {\n\t\tfmtAmount = \"MXN ₱\" + (amount * currencyRates.MXN).toLocaleString(undefined, opts);\n\t} else {\n\t\tthrow \"Unknown currency code: this shouldn't have happened.\";\n\t}\n\treturn fmtAmount;\n}",
"function removeCurrencySignAndPadding(value, selection) {\n var newValue = value;\n if (newValue.charAt(0) === config.currencySymbol) {\n newValue = newValue.substring(1); // Remove sign\n }\n selection.start --;\n selection.end --;\n var lastPadChar = -1;\n for (var i = 0; i < newValue.length; i++) {\n if (newValue.charAt(i) === config.padChar) {\n\tlastPadChar = i;\n } else {\n\tbreak;\n }\n }\n newValue = newValue.substring(lastPadChar + 1);\n selection.start -= (lastPadChar + 1);\n selection.end -= (lastPadChar + 1);\n if (selection.start < 0) selection.start = 0;\n if (selection.end < 0) selection.end = 0;\n return newValue;\n }",
"function setSelectedText(objectUrl) {\r\n var text_iframe = document.getElementById('text-input'); \r\n text_iframe.contentWindow.setSelectedText(objectUrl);\r\n }",
"function updateExpressWidget() {\nvar grandTotalSum = $('.grand-total-sum').text();\n console.log(\"Updating express widget. Grandtotal=\", grandTotalSum);\n grandTotalSum = grandTotalSum.replace(/\\$/g, '');\n var currency = $('#afterpay-widget-currency').val();\n if (\"afterpayWidget\" in window) {\n afterpayWidget.update({\n amount: { amount: grandTotalSum, currency: currency },\n });\n\n $('#afterpay-widget-amount').val(grandTotalSum);\n $('#afterpay-widget-currency').val(currency);\n }\n}",
"function setSelectedLocale(locale) {\n if (!_initSuccess) {\n return;\n }\n\n if (!_.includes(_supportedLocale, locale)) {\n return;\n }\n\n if (!locale || locale === _selectedLocale) {\n return;\n }\n\n _selectedLocale = locale;\n\n // reset the $rs.locale object\n $rs[localeKey] = {};\n\n // load the locale bundles of the selected locale\n loadLocaleBundles(true);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce an array of twoelement arrays [x,y] for each segment of values. | function segments(values) {
var segments = [], i = 0, n = values.length
while (++i < n) segments.push([[i - 1, values[i - 1]], [i, values[i]]]);
return segments;
} | [
"function flattenPoints(input) {\n let res = new Array(input.length * 2);\n for (let i = 0; i < input.length; i++) {\n res[i * 2] = input[i].x;\n res[i * 2 + 1] = input[i].y;\n }\n return res;\n}",
"function splitIntoSegments(pathCoordinates, valueData) {\n\t var segments = [];\n\t var hole = true;\n\n\t for(var i = 0; i < pathCoordinates.length; i += 2) {\n\t // If this value is a \"hole\" we set the hole flag\n\t if(valueData[i / 2].value === undefined) {\n\t if(!options.fillHoles) {\n\t hole = true;\n\t }\n\t } else {\n\t // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment\n\t if(hole) {\n\t segments.push({\n\t pathCoordinates: [],\n\t valueData: []\n\t });\n\t // As we have a valid value now, we are not in a \"hole\" anymore\n\t hole = false;\n\t }\n\n\t // Add to the segment pathCoordinates and valueData\n\t segments[segments.length - 1].pathCoordinates.push(pathCoordinates[i], pathCoordinates[i + 1]);\n\t segments[segments.length - 1].valueData.push(valueData[i / 2]);\n\t }\n\t }\n\n\t return segments;\n\t }",
"function convertArrayToXY(array) {\n const newArray = [];\n for(let i = 0; i < array.length; i += 2) {\n newArray.push({\n x: array[i],\n y: array[i + 1]\n });\n }\n return newArray;\n}",
"getSegmentArray(num) {\n return this.list[num] || [];\n }",
"getRealCoords(x, y) {\n const real_x = (x - this.x_min) * this.x_scale + this.x;\n const real_y = this.height - (y - this.y_min) * this.y_scale + this.y;\n\n return [real_x, real_y];\n }",
"getChunksInRange(point1, point2)\n {\n var chunks = [];\n \n for(var x = point1.x, xi = 0; x <= point2.x; x += X_CHUNKS_PER_REGION * TILE_SIZE, xi++) // add 32 each iteration\n {\n var addedIndex = false;\n\n for(var y = point1.y; y <= point2.y; y += Y_CHUNKS_PER_REGION * TILE_SIZE) // same here, 32 per iteration\n {\n var chunk = WORLD.getChunk(x, y);\n if(chunk == null)\n continue;\n \n if(!addedIndex)\n {\n addedIndex = true;\n chunks.push(new Array());\n }\n\n chunks[xi].push(chunk);\n }\n }\n return chunks;\n }",
"function createArrayFromNumberSequence ( start, end ) {\n\tvar result;\n\n\tif ( typeof start === 'number' && typeof end === 'number' && start <= end ) {\n\t\tresult = Array.apply(null, { length: ( end - start + 1 ) } )\n\t\t\t.map(Number.call, Number)\n\t\t\t.map( function( i ) { return i + start; } );\n\t} else {\n\t\tresult = [];\n\t}\n\treturn result;\n}",
"function getSurroundCells(y,x) {\n var arr1 = [[y-1,x-1],[y-1,x],[y-1,x+1],[y,x-1],[y,x+1],[y+1,x-1],[y+1,x],[y+1,x+1]];\n var arr2 = [];\n for (ai=0; ai<arr1.length; ai++) {\n if (arr1[ai][0]<height && arr1[ai][1]<width && 0<=arr1[ai][0] && 0<=arr1[ai][1]) {\n arr2.push(arr1[ai]);\n }\n }\n return arr2;\n}",
"function formatIntersectingSegment(x, y, i, j, xx, yy) {\n if (xx[i] == x && yy[i] == y) {\n return [i, i];\n }\n if (xx[j] == x && yy[j] == y) {\n return [j, j];\n }\n return i < j ? [i, j] : [j, i];\n}",
"function arrayOperation(x, y, n) {\n\tconst a = [];\n\tfor (let i = x; i <= y; i++) {\n\t\tif (i % n === 0) a.push(i);\n\t}\n\treturn a;\n}",
"function positionArray(keypoints){\r\n var keypointArray = new Array();\r\n sortByKey(keypoints,'part');\r\n for (let i = 0; i < keypoints.length; i++) {\r\n const keypoint = keypoints[i];\r\n keypointArray.push(keypoint.position.x, keypoint.position.y);\r\n }\r\n return keypointArray;\r\n}",
"function computeEachPoint(min, max, fx)\n{\n let xData = [];\n let yData = [];\n const step = 0.1;\n\n for(let i = min;i <= max; i += step)\n {\n xData.push(i);\n let y = fx(i);\n yData.push(y);\n }\n\n return [xData, yData];\n}",
"function linspace(start, stop, n) {\n let arr = [];\n let step = (stop - start) / (n - 1);\n for (let i = 0; i < n; i++) {\n arr.push(start + step * i);\n }\n return arr;\n}",
"function scaleSegment(x1, y1, x2, y2) {\r\n const magn = mag(x1, y1, x2, y2);\r\n const prop1 = (magn - 35) / magn;\r\n const prop2 = (magn - 45) / magn;\r\n const x_1p = x2 - (x2 - x1) * prop1;\r\n const y_1p = y2 - (y2 - y1) * prop1;\r\n const x_2p = x1 + (x2 - x1) * prop2;\r\n const y_2p = y1 + (y2 - y1) * prop2;\r\n return [x_1p, y_1p, x_2p, y_2p];\r\n}",
"function createNoiseTrackerArray(){\n\tvar xLimit = 11;\n\tfor(var y=0; y<=15; y++){\n\t\tnoiseTracker[y] = [];\n\t\tnoiseTracker2[y] = [];\n for(var x=0; x<=xLimit; x++){\n\t\t\tvar noiseValue = noise(x, y);\n\t\t\tif(y == 0 || y == 15){\n\t\t\t\tnoiseValue = 0.5;\n\t\t\t}\n\t\t\tnoiseTracker[y][x] = noiseValue;\n\t\t\tnoiseTracker2[y][x] = noise(x * y);\n\t\t}\n\t\tif((y % 2) == 0){\n xLimit = 12;\n }\n else {\n xLimit = 11;\n }\n\t}\n}",
"function create2dArray(ids_array, ansType_array) {\n var twoD_array = [];\n \n for(var i = 0; i < qid_len; i++) {\n twoD_array.push([ids_array[i], ansType_array[i]]);\n }\n \n return twoD_array;\n}",
"function createPosition(){\n position = [];\n // push the x and y position values to an array of position objects\n for (var i = 0; i < rangee; i++){\n for (var j = 0; j < column; j++){\n position.push(new Position(pX[j],pY[i]));\n }\n }\n}",
"get ancestorAndSubsequentSlices() {\n var res = [];\n\n res.push(this);\n\n for (var aSlice of this.enumerateAllAncestors())\n res.push(aSlice);\n\n this.iterateAllSubsequentSlices(function(sSlice) {\n res.push(sSlice);\n });\n\n return res;\n }",
"function appendBasketPointsOfColumn(c){\n var temp_basket_array = [];\n var squaresInColumn = document.getElementById('Column'+ (c+1)).childNodes;\n var array_index = 0;\n for (m = 0 ; m < squaresInColumn.length; m ++){\n if ( !(m%2) ) {\n var rectsInColumn = squaresInColumn[m].getBoundingClientRect();\n temp_basket_array[array_index] = {x: rectsInColumn.left, y: rectsInColumn.top };\n }\n array_index++;\n }\n return temp_basket_array;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves the proxy rules into the DB | function saveproxyRule() {
var rules = {};
var co = 0;
$("#proxy_rules_list .proxy_rule_boxes").each(function() {
var url = stripHTMLTags($(this).find('.url').text());
var proxy_type = stripHTMLTags($(this).find('.proxy_type').prop("selectedIndex"));
var proxy_location = stripHTMLTags($(this).find('.proxy_location').text());
var proxy_port = stripHTMLTags($(this).find('.proxy_port').text());
var active = stripHTMLTags($(this).find('.active').prop('checked'));
var global = stripHTMLTags($(this).find('.global').prop('checked'));
var caseinsensitive = stripHTMLTags($(this).find('.caseinsensitive').prop('checked'));
// prepare the object
rules[co] = {id: co, url:url, proxy_type:proxy_type, proxy_location:proxy_location, proxy_port:proxy_port, active: active, global:global, caseinsensitive:caseinsensitive}
co++;
});
localStorage.proxy_rules = JSON.stringify(rules);
} | [
"async function setRules(){\n const data = {\n add: rules\n }\n const response = await needle('post', rulesURL, data, {\n headers:{\n 'content-type': 'application/json',\n Authorization: `Bearer ${process.env.TWITTER_BEARER_TOKEN}`\n }\n });\n return response.body\n}",
"function addProxyRule(url, proxy_type, proxy_location, proxy_port, active, global, caseinsensitive) {\n\t\n\tvar bkg = chrome.extension.getBackgroundPage();\n\t\n\t// uuid for the panels\n\tvar c = new Date().getTime();\n\t// draw the proxy rule\n\tvar htmlText = '<div class=\"proxy_rule_boxes fly_box\" id=\"proxy_rule_box_id_' + c + '\">' + $('#proxy_rules_template').html() + '</div>';\n\t// add the proxy rule box\n\t$('#proxy_rules_list').append(htmlText);\n\t// set up the parameters\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .url').html(url);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .url').keyup(function() { saveproxyRule() });\n\t\n\tif(typeof $('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type option')[proxy_type] != 'undefined')\n\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type option')[proxy_type].selected = true;\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type').change(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_location').html(proxy_location);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_location').keyup(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_port').html(proxy_port);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_port').keyup(function() { saveproxyRule() });\n\t\n\t// checkboxes\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .active').prop('checked', active ? 1 : 0);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .active').change(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .global').prop('checked', global ? 1 : 0);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .global').change(function() { saveproxyRule() });\n\t\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .caseinsensitive').prop('checked', caseinsensitive ? 1 : 0);\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .caseinsensitive').change(function() { saveproxyRule() });\n\n\t// attach the close button action\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .head a').click(\n\t\t\tfunction() {\n\t\t\t\tdeleteproxyRulePanel(c);\n\t\t\t}\n\t);\n\n\t// set active/inactive background on creation\n\tif(active!='1')\n\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c).addClass('box_inactive');\n\n\t// attach active/inactive action\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .active').click(function() {\n\t\tif($(this).prop('checked'))\n\t\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c).removeClass('box_inactive');\n\t\telse\n\t\t\t$('#proxy_rules_list #proxy_rule_box_id_' + c).addClass('box_inactive');\n\t});\n\n\t// attach even to hide/show unused fields depending of the proxy type\n\t$('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type').change(function() {\n\t\tvar proxy_type = $('#proxy_rules_list #proxy_rule_box_id_' + c + ' .proxy_type').prop(\"selectedIndex\");\t\n\t\tproxyTypeHideFields(proxy_type, c);\n\t} );\n\t\t\n\t// hide unused fields depending of proxy type\n\tproxyTypeHideFields(proxy_type, c);\n\t\n\t// make the pop-out animation effect\n\twindow.setTimeout( function() { $('#proxy_rules_list #proxy_rule_box_id_' + c).addClass('fly_box-zoomed');} , 100);\n\t\n\tsanitizeContenteditableDivs();\n}",
"function saveRules() {\n if ($('.stats').length != 0) {\n var rulesJSON = getJSONFromRules();\n\n if (rulesJSON == 1)\n return 1;\n\n var\tallJSON = $('body').data('json');\n allJSON.forEach(function (e, i, arr) {\n // arr is just used for changing values directly!\n if (e['feed-name'] == activeFeed) {\n e['items'].forEach(function (eItem, iItem, arrItem) {\n if (eItem['item-name'] == activeItem) {\n arrItem[iItem]['rules'] = rulesJSON;\n }\n });\n\n arr[i] = e;\n }\n });\n\n markAsContentChanged();\n }\n\n return 0;\n /* SINCE ANIMATION TAKES TIME, VERY POSSIBLE THAT ONLY PART OF\n THE BLOCK IS SAVED */\n}",
"function addPoliciesToDescriptor(apiProxy, policyNames){\n fs.readFile(__dirname + '/' +apiProxy+ '/apiproxy/'+apiProxy+'.xml', function(err, data) {\n parser.parseString(data, function (err, result) {\n result.APIProxy.Policies = {\n \"Policy\": policyNames\n };\n var xml = builder.buildObject(result);\n fs.writeFile(__dirname + '/' +apiProxy+ '/apiproxy/'+apiProxy+'.xml', xml, function(err, data){\n if (err) console.log(err);\n console.log(\"Successfully update Proxy descriptor\");\n });\n });\n });\n}",
"function updateRulesTable() {\n\tdeleteRulesTable();\n\tbuildRulesTable();\n}",
"function ExportRules() {\n try {\n //update json for all rules in ruleset\n CurrentRuleSet.updateAll();\n\n CurrentRuleSet.Rules.forEach(rule =>{\n\n //convert ruleset to JSON\n var text = JSON.stringify(rule, null, 3);\n \n var filename = rule.title;\n\n //export/download ruleset as text/json file\n var blob = new Blob([text], {\n type: \"application/json;charset=utf-8\"\n });\n saveAs(blob, filename);\n });\n \n } catch (e) {\n alert(e);\n }\n}",
"function submitDelegates()\n{\n\tvar delegates = new Array();\n\tif (module) {\n\t\tfor (var i in module.delegateProps) {\n\t\t\tdelegates.push(module.delegateProps[i]);\n\t\t}\n\t\tmodule.save(delegates);\n\t}\n}",
"function saveDB(){\n clearInterval( intervalId );\n setInterval( saveDB, 60*60*1000 );\n PostsService.save();\n //$rootScope.postCount = $rootScope.postCount + 1;\n $rootScope.posthacked = [];\n }",
"saveGoal(data) {\n let goal = this.get('store').createRecord('goal', data);\n goal.save()\n }",
"function saveProtocolEntry() {\r\n clearErrors();\r\n var dataToSend = prepareDataForAddProtocolEntry();\r\n if(dataToSend == null) {\r\n return;\r\n }\r\n enableInput(false);\r\n execAjax(dataToSend, protocolEntrySaved);\r\n loadProtocolList();\r\n }",
"async writeCurPeerUrls(peerUrls) {\n let data = JSON.stringify(peerUrls);\n return this.db.put(genKey('cur_peer_urls'), data);\n }",
"save() {\n this.init_();\n this.mergeFromMap_();\n Settings.getInstance().set(['map', 'z-order'], this.groups_);\n }",
"addProductionRule() {\n this.productionRules.push({\n source: this.ruleSource,\n target: this.ruleTarget\n });\n this.ruleSource = '';\n this.ruleTarget = '';\n this.validSubmit = true;\n this.validateSubmit();\n }",
"saveWorker(worker) {\n worker.taxToPay = Util.payTaxes(worker.salary);\n ODWorker.ListOfWorkers.push(worker);\n console.log('save worker reach and save');\n console.log(worker);\n }",
"function saveApis(data) {\n \n defineDBSchema(2);\n firstDBShemaVersion(1);\n db.open();\n\n /* data.forEach(function(item) {\n db.apis.put(item);\n console.log('saved api', item.apiName);\n });\n */\n\n db.transaction('rw', db.apis, function() {\n data.forEach(function(item) {\n db.apis.put(item);\n console.log('added api from txn', item.apiName);\n });\n }).catch(function(error) {\n console.error('error', error);\n });\n \n\n // .finally(function() {\n // db.close(); \n // });\n }",
"function saveLayerChanges() {\n // Update the currently active dataset\n var activeDatasetId = getActiveDatasetId();\n var activeDataset = getDatasetById(activeDatasetId);\n activeDataset.parameters = formToJSON();\n // Update dataset name to reflect the distribution and format\n updateDatasetName(activeDataset);\n // Update the permalink and Python generation code\n setLinksForLayer(activeDataset);\n // Update the visualization\n refreshLayerVisualization(activeDataset.mapLayer, activeDataset.parameters);\n}",
"create(data) {\n console.log('Creating rule')\n data.created = Date.now()\n data.updated = data.created\n data.id = data.created + '_' + uuid.v4()\n let jsonString = JSON.stringify(data)\n safari.extension.settings.setItem('rule_' + data.id, jsonString)\n return this.get(data.id)\n }",
"savePrivacyCompliancePolicy() {\n return this.saveJson('compliance', get(this, 'complianceInfo'))\n .then(this.actions.resetPrivacyCompliancePolicy.bind(this))\n .catch(this.exceptionOnSave);\n }",
"function saveRealmList() {\n \"use strict\";\n window.gmSetValue(\"realmList2\", realmList);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GETDISTRACTORS: gives three distractors for the perceptual fluency task | function getDistractors() {
var match = true;
if (onPFtaskA) {
for (var i=0; i<3; i++) {
while (match) {
distractors[i] = pfTaskAtargets[Math.floor(Math.random()*16)];
match = false;
if (distractors[i]==pfTaskAtargets[ind]) {
match = true;
} else {
for (var j=0; j<i; j++) {
if (distractors[i]==distractors[j]) {
match= true;
}
}
}
}
match = true;
}
} else if (onPFtaskB) {
for (var i=0; i<4; i++) {
while (match) {
distractors[i] = pfTaskBtargets[Math.floor(Math.random()*16)];
match = false;
if (distractors[i]==pfTaskBtargets[ind]) {
match = true;
} else {
for (var j=0; j<i; j++) {
if (distractors[i]==distractors[j]) {
match= true;
}
}
}
}
match = true;
}
}
} | [
"function makePerceptualFluencyTrials() {\n\n var pfA = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,\n 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,\n 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];\n var pfB = pfA;\n pfA = shuffleArray(pfA);\n pfB = shuffleArray(pfB);\n var r = Math.floor(Math.random() * 2);\n if (r==0) {\n for (var i=0; i<pfA.length; i++) {\n pfTaskAtargets[i] = pstimsetA[pfA[i]];\n pfTaskBtargets[i] = pstimsetB[pfB[i]];\n } \n } else {\n for (var i=0; i<pfA.length; i++) {\n pfTaskAtargets[i] = pstimsetB[pfB[i]];\n pfTaskBtargets[i] = pstimsetA[pfA[i]];\n }\n }\n pfTypeA = pstimsetA[0].slice(0,4);\n pfTypeB = pstimsetB[0].slice(0,4);\n}",
"function nutrition(cal, fat, sod, carb, fiber, sugar, pro, vita, vitc, calc){\n\t\treturn {\n\t\t\tcal:cal,\n\t\t\tfat:fat,\n\t\t\tsod:sod,\n\t\t\tcarb:carb,\n\t\t\tfiber:fiber,\n\t\t\tsugar:sugar,\n\t\t\tpro:pro,\n\t\t\tvita:vita,\n\t\t\tvitc:vitc,\n\t\t\tcalc:calc,\n\t\t\t//iron:iron\n\t\t}\n\t}",
"function makeTestTrials() {\n \n var pr = []; pc = [];\n if (debugging) {\n pr = [0,1,2,3];\n pc = [0];\n pr = shuffleArray(pr);\n } else {\n pr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33];\n pc = [0,1,2,3,4,5,6,7];\n pr = shuffleArray(pr);\n pc = shuffleArray(pc);\n }\n \n // if debugging just have one test trial of each type\n if (debugging) {\n \n // one pattern recognition item with one foil\n patternrecogTarget[pr[0]] = hardtriplets[0]; \n patternrecogFoilsone[pr[0]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogFoilstwo[pr[0]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[0]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n // one pattern recognition item with three foils\n patternrecogTarget[pr[1]] = hardtriplets[1]; \n patternrecogFoilsone[pr[1]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[1]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogFoilsthree[pr[1]] = [stimset[0], stimset[1], stimset[3]];\n // one item with only pairs, and one other answer option \n patternrecogTarget[pr[2]] = [stimset[1], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[2]] = [stimset[0], stimset[15],\"white.jpg\"];\n patternrecogFoilstwo[pr[2]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[2]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n // now items with only pairs, and three other answer options \n patternrecogTarget[pr[3]] = [stimset[11], stimset[12],\"white.jpg\"];\n patternrecogFoilsone[pr[3]] = [stimset[5], stimset[10],\"white.jpg\"];\n patternrecogFoilstwo[pr[3]] = [stimset[11], stimset[14],\"white.jpg\"];\n patternrecogFoilsthree[pr[3]] = [stimset[8], stimset[3],\"white.jpg\"]; \n // give them names for easy reference (here in debugging these are meaningless)\n for (var i=0; i<pr.length; i++) {\n testitems[pr[i]] = i+1;\n }\n // now a pattern completion item. first item in foils array is always the target\n patterncompletionQuestion[0] = [stimset[0], \"blank.jpg\", stimset[2]];\n patterncompletionFoils[0] = [stimset[1], stimset[12], stimset[8]]\n testitems[pr.length] = 0; \n \n // if not debugging have all test items \n } else {\n // first set up the pattern recognition items with one foil\n patternrecogTarget[pr[0]] = hardtriplets[0]; \n patternrecogFoilsone[pr[0]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogTarget[pr[1]] = hardtriplets[1]; \n patternrecogFoilsone[pr[1]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[2]] = hardtriplets[2]; \n patternrecogFoilsone[pr[2]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogTarget[pr[3]] = hardtriplets[3]; \n patternrecogFoilsone[pr[3]] = [stimset[6], stimset[0], stimset[2]];\n patternrecogTarget[pr[4]] = easytriplets[0]; \n patternrecogFoilsone[pr[4]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogTarget[pr[5]] = easytriplets[1]; \n patternrecogFoilsone[pr[5]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogTarget[pr[6]] = easytriplets[2]; \n patternrecogFoilsone[pr[6]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogTarget[pr[7]] = easytriplets[3]; \n patternrecogFoilsone[pr[7]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[8]] = hardtriplets[0]; \n patternrecogFoilsone[pr[8]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogTarget[pr[9]] = hardtriplets[1]; \n patternrecogFoilsone[pr[9]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogTarget[pr[10]] = hardtriplets[2]; \n patternrecogFoilsone[pr[10]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogTarget[pr[11]] = hardtriplets[3]; \n patternrecogFoilsone[pr[11]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogTarget[pr[12]] = easytriplets[0]; \n patternrecogFoilsone[pr[12]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogTarget[pr[13]] = easytriplets[1]; \n patternrecogFoilsone[pr[13]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogTarget[pr[14]] = easytriplets[2]; \n patternrecogFoilsone[pr[14]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[15]] = easytriplets[3]; \n patternrecogFoilsone[pr[15]] = [stimset[15], stimset[6], stimset[9]];\n for (var i=0; i<16; i++) {\n patternrecogFoilstwo[pr[i]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[i]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n }\n\n // now set up the pattern recognition items with three foils \n patternrecogTarget[pr[16]] = hardtriplets[0]; \n patternrecogFoilsone[pr[16]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[16]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogFoilsthree[pr[16]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogTarget[pr[17]] = hardtriplets[1]; \n patternrecogFoilsone[pr[17]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[17]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogFoilsthree[pr[17]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[18]] = hardtriplets[2]; \n patternrecogFoilsone[pr[18]] = [stimset[15], stimset[6], stimset[9]];\n patternrecogFoilstwo[pr[18]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogFoilsthree[pr[18]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogTarget[pr[19]] = hardtriplets[3]; \n patternrecogFoilsone[pr[19]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogFoilstwo[pr[19]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogFoilsthree[pr[19]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[20]] = easytriplets[0]; \n patternrecogFoilsone[pr[20]] = [stimset[15], stimset[6], stimset[9]];\n patternrecogFoilstwo[pr[20]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogFoilsthree[pr[20]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogTarget[pr[21]] = easytriplets[1]; \n patternrecogFoilsone[pr[21]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogFoilstwo[pr[21]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogFoilsthree[pr[21]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogTarget[pr[22]] = easytriplets[2]; \n patternrecogFoilsone[pr[22]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogFoilstwo[pr[22]] = [stimset[6], stimset[0], stimset[2]];\n patternrecogFoilsthree[pr[22]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[23]] = easytriplets[3]; \n patternrecogFoilsone[pr[23]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogFoilstwo[pr[23]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogFoilsthree[pr[23]] = [stimset[6], stimset[0], stimset[2]];\n \n // now items with only pairs, and one other answer option \n patternrecogTarget[pr[24]] = [stimset[1], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[24]] = [stimset[0], stimset[15],\"white.jpg\"];\n patternrecogTarget[pr[25]] = [stimset[0], stimset[3],\"white.jpg\"];\n patternrecogFoilsone[pr[25]] = [stimset[1], stimset[3],\"white.jpg\"];\n patternrecogTarget[pr[26]] = [stimset[2], stimset[0],\"white.jpg\"];\n patternrecogFoilsone[pr[26]] = [stimset[5], stimset[2],\"white.jpg\"];\n patternrecogTarget[pr[27]] = [stimset[3], stimset[1],\"white.jpg\"];\n patternrecogFoilsone[pr[27]] = [stimset[12], stimset[1],\"white.jpg\"];\n patternrecogTarget[pr[28]] = [stimset[5], stimset[6],\"white.jpg\"];\n patternrecogFoilsone[pr[28]] = [stimset[4], stimset[10],\"white.jpg\"];\n patternrecogTarget[pr[29]] = [stimset[7], stimset[8],\"white.jpg\"];\n patternrecogFoilsone[pr[29]] = [stimset[2], stimset[13],\"white.jpg\"];\n for (var i=24; i<30; i++) {\n patternrecogFoilstwo[pr[i]] = [\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[i]] = [\"white.jpg\",\"white.jpg\"];\n } \n \n // now items with only pairs, and three other answer options \n patternrecogTarget[pr[30]] = [stimset[11], stimset[12],\"white.jpg\"];\n patternrecogFoilsone[pr[30]] = [stimset[5], stimset[10],\"white.jpg\"];\n patternrecogFoilstwo[pr[30]] = [stimset[11], stimset[14],\"white.jpg\"];\n patternrecogFoilsthree[pr[30]] = [stimset[8], stimset[3],\"white.jpg\"];\n patternrecogTarget[pr[31]] = [stimset[13], stimset[14],\"white.jpg\"];\n patternrecogFoilsone[pr[31]] = [stimset[7], stimset[9],\"white.jpg\"];\n patternrecogFoilstwo[pr[31]] = [stimset[0], stimset[7],\"white.jpg\"];\n patternrecogFoilsthree[pr[31]] = [stimset[14], stimset[6],\"white.jpg\"];\n patternrecogTarget[pr[32]] = [stimset[0], stimset[1],\"white.jpg\"];\n patternrecogFoilsone[pr[32]] = [stimset[6], stimset[0],\"white.jpg\"];\n patternrecogFoilstwo[pr[32]] = [stimset[2], stimset[13],\"white.jpg\"];\n patternrecogFoilsthree[pr[32]] = [stimset[12], stimset[4],\"white.jpg\"];\n patternrecogTarget[pr[33]] = [stimset[3], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[33]] = [stimset[8], stimset[1],\"white.jpg\"];\n patternrecogFoilstwo[pr[33]] = [stimset[9], stimset[3],\"white.jpg\"];\n patternrecogFoilsthree[pr[33]] = [stimset[15], stimset[11],\"white.jpg\"];\n \n // give them the name as in the paper for easy reference\n for (var i=0; i<pr.length; i++) {\n testitems[pr[i]] = i+1;\n }\n for (var i=0; i<pc.length; i++) {\n testitems[pr.length+pc[i]] = 35+i;\n }\n \n // now the pattern completion items\n patterncompletionQuestion[pc[0]] = [stimset[0], \"blank.jpg\", stimset[2]];\n patterncompletionFoils[pc[0]] = [stimset[1], stimset[12], stimset[8]]\n patterncompletionQuestion[pc[1]] = [stimset[1], stimset[0], \"blank.jpg\"];\n patterncompletionFoils[pc[1]] = [stimset[3], stimset[5], stimset[15]]\n patterncompletionQuestion[pc[2]] = [\"blank.jpg\", stimset[5], stimset[6]];\n patterncompletionFoils[pc[2]] = [stimset[4], stimset[13], stimset[2]]\n patterncompletionQuestion[pc[3]] = [stimset[7], \"blank.jpg\", stimset[9]];\n patterncompletionFoils[pc[3]] = [stimset[8], stimset[14], stimset[3]]\n patterncompletionQuestion[pc[4]] = [stimset[10], \"blank.jpg\", \"white.jpg\"];\n patterncompletionFoils[pc[4]] = [stimset[11], stimset[6], stimset[0]];\n patterncompletionQuestion[pc[5]] = [\"blank.jpg\", stimset[14], \"white.jpg\"];\n patterncompletionFoils[pc[5]] = [stimset[13], stimset[7], stimset[11]];\n patterncompletionQuestion[pc[6]] = [stimset[2], \"blank.jpg\", \"white.jpg\"];\n patterncompletionFoils[pc[6]] = [stimset[0], stimset[1], stimset[4]];\n patterncompletionQuestion[pc[7]] = [\"blank.jpg\", stimset[3], \"white.jpg\"];\n patterncompletionFoils[pc[7]] = [stimset[2], stimset[10], stimset[9]];\n }\n\n}",
"function getAllChords(inputScale){\n\tvar allChords = [];\n\tvar chordSeeds = chordmaker.chords; // TODO -- this.chordmaker?\n\n\t// for each pitch in input scale, get array of possible chords\n\tfor (var i = 0; i < inputScale.length; i++) {\n\t\tvar thisMode = getMode(inputScale, i);\n\t\t\n\t\t// for each type of chord defined above, get chord and push to allChords array\n\t\tfor(type in chordSeeds) {\n\t\t\tif (chordSeeds.hasOwnProperty(type)) {\n\t\t\t\t\n\t\t\t\tvar thisChord = [];\n\t\t \t// for each interval in the given chord type, get the note and push to this chord\n\t\t\t\tfor (var j = 0; j < chordSeeds[type].length; j++) {\n\t\t\t\t\t// TODO -- 0 v 1 indexing jankiness\n\t\t\t\t\tvar noteInt = chordSeeds[type][j] - 1;\n\t\t\t\t\t// console.log(noteInt);\n\n\t\t\t\t\tvar thisNote = thisMode[noteInt];\n\t\t\t\t\tthisChord.push(thisNote);\n\t\t\t\t}\n\t\t\t\tallChords.push(thisChord);\n\t\t }\n\t\t}\n\t}\n\tconsole.log(allChords);\n\treturn allChords;\n}",
"getSumOfDssRatios() {\n let sum = 0;\n for (let disease of this.diseases) {\n sum += this.getDssRatio(disease);\n }\n return sum;\n }",
"function add_tracts(){\n for(var i = 0; i < features.length; i++){\n features[i].properties.tract = get_bad_tract(features[i])\n }\n}",
"calcProjectMrealtionships(project) {\n var _this = this;\n var m_results = []; // capture results from each CRITERIA loop - to be multiplied for final m_result\n $.each(project.categories, function(index, category) {\n m_results.push(category.Ml + category.Mdash);\n });\n return m_results.reduce(_this.getProduct);\n }",
"function exerciseDog(name, breed) {\n let activitiesArray = [];\n for(let i = 0; i < routine.length; i++) {\n let singleRoutine = routine[i](name, breed);\n activitiesArray.push(singleRoutine);\n }\n return activitiesArray;\n}",
"get fluxes(){\n let components={};\n let totals={};\n\n //components\n Object.entries(this.components).forEach(([key,value])=>{\n components[key]=this.Q*value;\n });\n\n //totals\n Object.entries(this.totals).forEach(([group_name,group])=>{\n totals[group_name]={};\n Object.entries(group).forEach(([key,val])=>{\n totals[group_name][key]=this.Q*val;\n });\n });\n\n return {components, totals};\n }",
"maternaluncle(person) {\n var mother = person.mother;\n if(mother === undefined){\n return []; \n }\n var uncles = this.brothers(mother);\n var brotherlaw = this.brotherinlaw(mother);\n if (brotherlaw.length > 0) {\n brotherlaw.forEach(function (brother) {\n uncles.push(brother);\n }, this);\n }\n return uncles;\n }",
"function chooseControllers(set,cont){\n // It turns out that writing the comparison predicate for the data is just a pain in the ass. Randomly schedule, for now.\n /* var keys = set.map(function(i){return redisKeys[i];});\n redis.mget(keys,function(err,res){\n if(err){\n console.log(\"Redis error, with keys :\"+keys);\n cont(set[0],set[1]);//Just choose the first two...\n }else{\n res = res.map(function(obj,index){return {obj:obj,ctrl:set[index]};});\n res.sort(function(a,b){\n //Some predicate for the epicness.\n\n\n\n return Math.random()-0.5;\n });\n cont(res[0].ctrl,res[1].ctrl);\n }\n });\n */\n set.sort(function(a,b){return Math.random()-0.5;});\n cont(set[0],set[1]);\n}",
"async function getParcoursupCoverage(formation) {\n const sirets = [formation.siret_cerfa ?? \"\", formation.siret_map ?? \"\"];\n const uais = [\n formation.uai_affilie,\n formation.uai_gestionnaire,\n formation.uai_composante,\n formation.uai_insert_jeune ?? \"\",\n formation.uai_cerfa ?? \"\",\n formation.uai_map ?? \"\",\n ];\n\n const m0 = await getMatch({\n $or: [{ rncp_code: { $in: formation.codes_rncp_mna } }, { cfd_entree: { $in: formation.codes_cfd_mna } }],\n published: true,\n });\n\n // strength 1\n const m1 = m0.filter((f) => hasInsee(f, formation.code_commune_insee)); // insee + (rncp ou cfd)\n\n // strength 2\n const m2 = m0.filter((f) => hasSiret(f, sirets)); // siret + (rncp ou cfd)\n const m3 = m0.filter((f) => hasUai(f, uais)); // uai + (rncp ou cfd)\n\n // strength 3\n const m4 = m1.filter((f) => hasUai(f, uais)); // insee + uai + (rncp ou cfd)\n\n // strength 5\n const m5 = m1.filter((f) => hasPostalCode(f, formation.code_postal)); // code postal + insee + (rncp ou cfd)\n const m6 = m5.filter((f) => hasRncp(f, formation.codes_rncp_mna) && hasCfd(f, formation.codes_cfd_mna)); // code postal + insee + rncp + cfd\n const m7 = m5.filter((f) => hasUai(f, uais)); // uai + code postal + insee + (rncp ou cfd)\n const m8 = m6.filter((f) => hasUai(f, uais)); // uai + code postal + insee + rncp + cfd\n\n // strength 6\n const m9 = m5.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + code postal + insee + (rncp ou cfd)\n const m10 = m6.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + code postal + insee + rncp + cfd\n const m11 = m7.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + uai + code postal + insee + (rncp ou cfd)\n const m12 = m8.filter((f) => hasAcademy(f, formation.nom_academie)); // academie + uai + code postal + insee + rncp + cfd\n\n // strength 7\n const m13 = m2.filter((f) => hasInsee(f, formation.code_commune_insee) && hasAcademy(f, formation.nom_academie)); // insee + academie +siret + (rncp ou cfd)\n const m14 = m13.filter((f) => hasUai(f, uais)); // uai + insee + academie +siret + (rncp ou cfd)\n\n // strength 8\n const m15 = m13.filter((f) => hasRncp(f, formation.codes_rncp_mna) && hasCfd(f, formation.codes_cfd_mna)); // insee + academie +siret + rncp + cfd\n const m16 = m14.filter((f) => hasRncp(f, formation.codes_rncp_mna) && hasCfd(f, formation.codes_cfd_mna)); // uai + insee + academie + siret + rncp + cfd\n\n const psMatchs = [\n {\n strength: \"8\",\n result: m16,\n },\n {\n strength: \"8\",\n result: m15,\n },\n {\n strength: \"7\",\n result: m14,\n },\n {\n strength: \"7\",\n result: m13,\n },\n {\n strength: \"6\",\n result: m12,\n },\n {\n strength: \"6\",\n result: m11,\n },\n {\n strength: \"6\",\n result: m10,\n },\n {\n strength: \"6\",\n result: m9,\n },\n {\n strength: \"5\",\n result: m8,\n },\n {\n strength: \"5\",\n result: m7,\n },\n {\n strength: \"5\",\n result: m6,\n },\n {\n strength: \"5\",\n result: m5,\n },\n {\n strength: \"3\",\n result: m4,\n },\n {\n strength: \"2\",\n result: m3,\n },\n {\n strength: \"2\",\n result: m2,\n },\n {\n strength: \"1\",\n result: m1,\n },\n ];\n\n let match = null;\n\n for (let i = 0; i < psMatchs.length; i++) {\n const { result, strength } = psMatchs[i];\n\n if (result.length > 0) {\n match = {\n matching_strength: strength,\n data_length: result.length,\n data: result.map(({ _id, cle_ministere_educatif, intitule_court, parcoursup_statut }) => {\n return {\n intitule_court,\n parcoursup_statut,\n _id,\n cle_ministere_educatif,\n };\n }),\n };\n\n break;\n }\n }\n\n return match;\n}",
"function get_item_prices(rarity_counts, price_dice) {\n// !!!\n}",
"createMatingPool() {\n let matingPool = [],\n limit;\n this.chromosomes.forEach((chromosome, index) => {\n limit = chromosome.fitness * 1000;\n for (let i = 0; i < limit; i++) matingPool.push(index);\n });\n return matingPool;\n }",
"function setExperiment() {\n \n s = [\"A\",\"D\",\"E\",\"G\",\"H\",\"J\",\"L\",\"M\",\"O\",\"P\",\"Q\",\"T\",\"W\",\"Y\",\"AA\",\"CC\"];\n sl = [\"B\",\"C\",\"F\",\"I\",\"K\",\"N\",\"R\",\"S\",\"U\",\"V\",\"X\",\"Z\",\"BB\",\"DD\",\"EE\",\"FF\"];\n sl = shuffleArray(sl);\n \n // set the training sequence\n trainseq = [\"train4.jpg\",\"train1.jpg\",\"hat.jpg\",\"train6.jpg\",\"train2.jpg\",\"train3.jpg\"];\n\n // make the stimuli for statistical learning\n for (var j=0; j<16; j++) {\n stimset[j] = condition + sl[j] + '.jpg';\n }\n // make stimuli for the first perceptual fluency test (matching their statistical learning test last time)\n s = shuffleArray(s);\n for (var j=0; j<16; j++) {\n pstimsetA[j] = lasttime + s[j] + '.jpg';\n }\n \n // make stimuli for the last perceptual fluency test (matching their statistical learning test today)\n sl = shuffleArray(sl);\n for (var j=0; j<16; j++) {\n pstimsetB[j] = condition + sl[j] + '.jpg';\n }\n \n createTriplets();\n\n wordseq = getWordSequence();\n getSyllableSequence();\n makeTestTrials();\n makePerceptualFluencyTrials();\n\n}",
"combine(p1, p2, m) {\n\t\tlet newField = [];\n\t\t\n\t\t// for every value in the flowfield\n\t\tfor (let i = 0; i < this.rows * this.cols; i++) {\n\t\t\t// check mutation chance\n\t\t\t// if mutation happens, set this value randomly\n\t\t\tif (Math.random() < m) {\n\t\t\t\tnewField[i] = Math.random() * Math.PI * 2;\n\t\t\t}\n\t\t\t// if no mutation, choose one parent's value randomly\n\t\t\telse {\n\t\t\t\t//let sum = p1.fitness + p2.fitness;\n\t\t\t\t//if (Math.random() * sum < p1.fitness) {\n\t\t\t\tif (Math.random() > 0.5) {\n\t\t\t\t\tnewField[i] = p1.brain.field[i];\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnewField[i] = p2.brain.field[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn newField;\n\t}",
"computeDamage (payload) {\n this.hardwareDamage.computeDamage(payload[meetingCategoryDamage.HARDWARE])\n this.softwareDamage.computeDamage(payload[meetingCategoryDamage.SOFTWARE])\n this.journeyDamage.computeDamage(payload[meetingCategoryDamage.JOURNEY])\n\n // Compute the total damage caused by all the components of the meeting thanks to the\n // total damage caused by each category of components.\n this.totalDamage = this.softwareDamage.totalDamage.add(this.hardwareDamage.totalDamage).add(this.journeyDamage.totalDamage)\n }",
"function AlgorithmForSliders( elements , type_attrb , type , criteria) {\n\t// console.clear()\n\t// console.log( \"\\t - - - - - AlgorithmForSliders - - - - -\" )\n\t// console.log( \"\" )\n\t// console.log( \"elements:\" )\n\t// console.log( elements )\n\t// console.log( \"type_attrb: \" + type_attrb )\n\t// console.log( \"type: \"+type )\n\t// console.log( \"criteria: \"+criteria )\n\n\t// // ( 1 )\n // // get visible sigma nodes|edges\n if(isUndef(elements)) return {\"steps\":0 , \"finalarray\":[]};\n \n var elems = [];/*=elements.filter(function(e) {\n return e[type_attrb]==type;\n });*/\n\n for(var e in elements) {\n if( elements[e][type_attrb]==type ) {\n if(getGraphElement(e)) {\n elems.push(elements[e])\n } \n }\n }\n if(elems.length==0) return {\"steps\":0 , \"finalarray\":[]};\n\n // identifying if you received nodes or edges\n var edgeflag = ( !isNaN(elems.slice(-1)[0].id) || elems.slice(-1)[0].id.split(\";\").length>1)? true : false;\n // // ( 2 )\n // // extract [ \"edgeID\" : edgeWEIGHT ] | [ \"nodeID\" : nodeSIZE ] \n // // and save this into edges_weight | nodes_size\n var elem_attrb=[]\n for (var i in elems) {\n e = elems[i]\n id = e.id\n elem_attrb[id]=e[criteria]\n // pr(id+\"\\t:\\t\"+e[criteria])\n }\n // pr(\"{ id : size|weight } \")\n // pr(elem_attrb)\n\n // // ( 3 )\n // // order dict edges_weight by edge weight | nodes_size by node size\n var result = ArraySortByValue(elem_attrb, function(a,b){\n return a-b\n //ASCENDENT\n });\n // pr(result.length)\n // // ( 4 )\n // // printing ordered ASC by weigth\n // for (var i in result) {\n // r = result[i]\n // idid = r.key\n // elemattrb = r.value\n // pr(idid+\"\\t:\\t\"+elemattrb)\n // // e = result[i]\n // // pr(e[criteria])\n // }\n var N = result.length\n // var magnitude = (\"\"+N).length //order of magnitude of edges|nodes\n // var exponent = magnitude - 1\n // var steps = Math.pow(10,exponent) // #(10 ^ magnit-1) steps\n // var stepsize = Math.round(N/steps)// ~~(visibledges / #steps)\n\n\n //var roundsqrtN = Math.round( Math.sqrt( N ) );\n var steps = Math.round( Math.sqrt( N ) );\n var stepsize = Math.round( N / steps );\n\n // pr(\"-----------------------------------\")\n // pr(\"number of visible nodes|edges: \"+N); \n \n // pr(\"number of steps : \"+steps)\n // pr(\"size of one step : \"+stepsize)\n // pr(\"-----------------------------------\")\n \n\n var finalarray = []\n var counter=0\n for(var i = 0; i < steps*2; i++) {\n // pr(i)\n var IDs = []\n for(var j = 0; j < stepsize; j++) {\n if(!isUndef(result[counter])) {\n k = result[counter].key\n // w = result[counter].value\n // pr(\"\\t[\"+counter+\"] : \"+w)\n IDs.push(k)\n }\n counter++;\n }\n if(IDs.length==0) break;\n \n finalarray[i] = (edgeflag)? IDs : IDs.map(Number);\n }\n // pr(\"finalarray: \")\n return {\"steps\":finalarray.length,\"finalarray\":finalarray}\n}",
"function Chore () {\n this.task = randomChores()\n this.completed = false\n this.payment = random(100)\n this.punishment = randomPunishments()\n}",
"distribution(n: number): RandomArray {\n let triangularArray: RandomArray = [],\n random: RandomArray = (prng.random(n): any);\n for(let i: number = 0; i < n; i += 1){\n triangularArray[i] = this._random(random[i]);\n }\n return triangularArray;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hide District and Assembly Constituency for certain Initiative values BAD LOGIC | function handleDistrictAndAssembly(country, initiative, $form) {
var pattern1 = new RegExp("voter", "i");
var pattern2 = new RegExp("election", "i");
if (country != 'India') {
$($form).find(".district_dropdown_div").css("visibility", "hidden").end()
.find(".district_dropdown").removeClass("required-field").end()
.find(".assembly_constituency_dropdown_div").css("visibility", "hidden").end()
.find(".assembly_constituency_dropdown").removeClass("required-field");
} else {
$($form).find(".district_dropdown_div").css("visibility", "visible").end()
.find(".district_dropdown").removeClass("required-field").end()
.find(".assembly_constituency_dropdown_div").css("visibility", "visible").end()
.find(".assembly_constituency_dropdown").removeClass("required-field");
if (initiative != undefined) {
if (initiative.match(pattern1) || initiative.match(pattern2)) {
$($form).find(".district_dropdown").addClass("required-field").end()
.find(".assembly_constituency_dropdown").addClass("required-field");
}
}
}
} | [
"function disableConfidence( id ) {\n $(id).find(\"select.confidence\").each( function(i) {\n if(i != 0) { $(this).addClass(\"vis-hide\") }; \n });\n}",
"function hide_important_elements(){\n\tdocument.getElementById('segment_middle_part').style.display\t= \"none\";\n\tdocument.getElementById('groupe_add_container').style.display\t= \"none\";\n\tdocument.getElementById('segment_send_part').style.display\t= \"none\";\n}",
"function displayUnexcavatedLabels(){\n\t\tvar i;\n\t\tvar currentCenter;\n\t\tvar currentCoordinatesList;\n\t\tvar displayTheseUnexAreas = [];\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[0]);\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[1]);\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[6]);\n\t\tdisplayTheseUnexAreas=adjustUnexcavatedCenters(displayTheseUnexAreas);\n\t\tfor(i=0; i<displayTheseUnexAreas.length; i++){\n\t\t\tcurrentCenter=displayTheseUnexAreas[i];\n\t\t\tif(currentCenter!=null){\n\t\t\t\tshowALabelOnMap(currentCenter, \"unexcavated\", \"small\", \"unexcavated\");\n\t\t\t}\n\t\t}\n\n\t}",
"function showRiskCharacteristicsWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nColumns of risk weights must TOTAL 100\\nProblem groups highlighted in red'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"function showOrksClanStratagems() {\r\n // Orks CLAN name/value\r\n var orks_clan = orksClanName();\r\n\r\n // Select all Orks CLANs stratagems\r\n var all_orks_clan_spc_strt = orksAllSpecificClansStratagems();\r\n\r\n // Select all Orks stratagems\r\n var all_orks_stratagems = orksAllStratagems();\r\n\r\n // Select specific CLAN stratagems\r\n var orks_clan_stratagems;\r\n\r\n uncheckCheckMarks();\r\n checkMarksDefaultStyle();\r\n document.getElementById('orks').style.display = 'block';\r\n\r\n // --- Filter Orks stratagems including CLAN specific stratagems\r\n // Show all Orks stratagems\r\n for (let i = 0; i < all_orks_stratagems.length; i++) {\r\n all_orks_stratagems[i].style.display = 'block';\r\n }\r\n\r\n if (orks_clan != 'all-clans-stratagems') {\r\n // Hide all CLAN stratagems\r\n if (all_orks_clan_spc_strt.length > 0) {\r\n for (let i = 0; i < all_orks_clan_spc_strt.length; i++) {\r\n all_orks_clan_spc_strt[i].style.display = 'none';\r\n }\r\n }\r\n \r\n if (orks_clan != 'no-clan') { // Show all Orks & CLAN specific stratagems\r\n orks_clan_stratagems = orksSpecificClansStratagems();\r\n \r\n // Show CLAN specific stratagems\r\n if (orks_clan_stratagems.length > 0) {\r\n for (let i = 0; i < orks_clan_stratagems.length; i++) {\r\n orks_clan_stratagems[i].style.display = 'block';\r\n }\r\n }\r\n }\r\n }\r\n}",
"function cleandistricts(){\n for(i in districts){\n if(districts[i].nnighboors ===0){\n //delete from the map and data structure\n districts[i].poligs.forEach((pol)=>{\n pol.setMap(null)\n delete districts[i]\n });\n }\n }\n}",
"function div_hide_learn() {\n\t\tdocument.getElementById('ghi').style.display = \"none\";\n\t}",
"function show_codeLink_normalization_parameters() {\n\tvar normalize_method = $(\"select[name='normalize_method']\").val(); \n\n // No method selected\n if (normalize_method == 'none') {\n $(\"div#loess_div\").hide();\n $(\"div#limma_div\").hide();\n // loess\n } else if (normalize_method == 'loess') {\n $(\"div#loess_div\").show();\n $(\"div#limma_div\").hide();\n // vsn\n } else if (normalize_method == 'vsn') {\n $(\"div#loess_div\").hide();\n $(\"div#limma_div\").hide();\n\n // limma\n } else if (normalize_method == 'limma') {\n $(\"div#loess_div\").hide();\n $(\"div#limma_div\").show();\n }\n}",
"function styleDistrict() {\n return {\n fillColor: randomPresetColor(pastelPresets),\n weight: districtStyle.weight,\n opacity: districtStyle.opacity,\n color: districtStyle.color,\n fillOpacity: districtStyle.fillOpacity,\n };\n}",
"function get_charity_values()\r\n {\r\n $(\"#registration_form input\").each(\r\n function()\r\n {\r\n if(!$(this).attr(\"exclude\"))\r\n charity_info[$(this).attr(\"id\")]=$(this).val();\r\n });\r\n }",
"function removeShowHide() {\n seminarInfo.each(function () {\n $(this).closest('.flag-seminar-container').removeClass('show');\n $(this).closest('.flag-seminar-container').removeClass('hide');\n });\n }",
"function cleanFireDistrictDataVIC(data, fireDistrict) {\n const { results } = data;\n const merged = mergeItems(results, fireDistrict);\n return { [fireDistrict]: merged };\n}",
"hide() {\n\n let svm = symbologyViewModel;\n let vm = this;\n\n svm.dictionary[svm.currentTab][vm.currentTypologyCode].isRadarDiagramVisible =\n !svm.dictionary[svm.currentTab][vm.currentTypologyCode].isRadarDiagramVisible;\n\n this.isVisible = false;\n\n $('#radarContainerVM').addClass('collapse');\n\n Spatial.sidebar.open('map-controls');\n\n $('#sidebar').removeClass('invisible');\n $('#sidebar').addClass('visible');\n\n }",
"function hideNoYear() {\n\tvar controlsNode = this.parentNode.parentNode;\n\tvar maps = $(controlsNode).parent().parent().find('.map');\n\tvar mapsNode = $(controlsNode.parentNode.parentNode).find('.maps')[0];\n\tvar mapsToOutput = [];\n\tif (this.checked) { // Hide maps\n\t\tfor (var i = 0; i < maps.length; i++) {\n\t\t\tvar year = maps[i].firstElementChild.children[3].textContent;\n\t\t\tif (year != \"No year listed\") {\n\t\t\t\tmapsToOutput.push(maps[i]);\n\t\t\t} else {\n\t\t\t\tnoYearMaps.push(maps[i]);\n\t\t\t}\n\t\t}\n\t} else { // Unhide maps\n\t\tif (controlsNode.children[2].firstElementChild.checked) { // If in descending order\n\t\t\tfor (var i = 0; i < noYearMaps.length; i++) {\n\t\t\t\tmapsToOutput.push(noYearMaps[i]);\n\t\t\t}\n\t\t\tfor (var i = 0; i < maps.length; i++) {\n\t\t\t\tmapsToOutput.push(maps[i]);\n\t\t\t}\n\t\t} else {\n\t\t\tmapsToOutput = maps;\n\t\t\tfor (var i = 0; i < noYearMaps.length; i++) {\n\t\t\t\tmapsToOutput.push(noYearMaps[i]);\n\t\t\t}\n\t\t}\n\t\tnoYearMaps = [];\n\t}\n\toutputMaps(mapsToOutput, mapsNode);\n}",
"function showImpactAssessmentWarningDialogue() {\n showDialog({\n title: 'WARNING: Inconsistent data',\n text: 'Elements on this page need correcting: \\nRows of risk weights should NOT EXCEED 100 for each area\\nProblem groups highlighted in red'.split('\\n').join('<br>'),\n negative: {\n title: 'Continue'\n }\n });\n}",
"function initReplacement(){\n $('#id_replacement').attr('onchange', 'displayReplacementOptions(event)')\n //hide replacement options fields \n $('#div_id_replaced_by').hide()\n $('#div_id_date_replacement').hide() \n //remove fields as required for form control\n $('#id_replaced_by').removeAttr('required')\n $('#id_date_replacement').removeAttr('required') \n\n //check if situation is Against Gibela to show or not the progress field\n let selected_option = $('#id_situation option:selected')\n let situation_type = selected_option.text().toLowerCase()\n if(!situation_type.includes('gibela')){\n $('#div_id_progress').hide()\n $('#id_progress').removeAttr('required')\n }\n }",
"function hideYears() {\n svg.selectAll('.year').remove();\n }",
"calcIgnorance() {\n var _this = this;\n var data = this.data;\n\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC Ignorance - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var ignorance_result = category.MdashH / (1 - category.MlH);\n category.Ignorance = ignorance_result;\n if (_this.debug) console.log(\"category.Ignorance: \" + category.Ignorance);\n });\n\n }",
"function onOffAreaScenarioVocabulary(state) {\n\tif (state == 0) {\n\t\t$('.vocabularyImg').removeClass('invisible');\n\t\t$('.contenInforVocabulary').addClass('invisible');\n\t\t$('.scenarioImg').addClass('invisible');\n\t\t$('.contenInfoSenario').removeClass('invisible');\n\t} else {\n\t\t$('.contenInfoSenario').addClass('invisible');\n\t\t$('.scenarioImg').removeClass('invisible');\n\t\t$('.vocabularyImg').addClass('invisible');\n\t\t$('.contenInforVocabulary').removeClass('invisible');\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name : matchDualFieldValue Return type : boolean Input Parameter(s) : elementId Purpose : To validate the dual/replica form fields of biller and personal information section against the regular expressions sent by API. History Header : Version Date Developer Name Added By : 1.0 30th July, 2013 Pradeep Yadav | function matchDualFieldValue(elementId) {
var dualFieldId = 'replicaof' + elementId;
var mainFieldValue = $('#element' + elementId).val().trim();
var replicaFieldValue = $('#' + dualFieldId).val().trim();
/* Checkng if the replica field have the value in it */
if (replicaFieldValue) {
/* Removing all characters as (, ) and - to validate the */
mainFieldValue = mainFieldValue.replace(/\W+/g, '');
/* Removing all characters as (, ) and - to validate the */
replicaFieldValue = replicaFieldValue.replace(/\W+/g, '');
/* Checking if the dual field matched with original field */
if (mainFieldValue === replicaFieldValue) {
return true;
}
}
return false;
} | [
"function validateDualField(elementId) {\n var dualFieldId = 'replicaof' + elementId;\n var replicaFieldValue = $('#' + dualFieldId).val().trim();\n /* Checkng if the replica field have the value in it */\n if (replicaFieldValue) {\n /* Checking if the dual field matched with original field */\n if (matchDualFieldValue(elementId)) {\n removeErrorBorderClass(dualFieldId);\n /* Remove the error border class */\n $('#errAddbillDual' + elementId).hide();\n /* Hide the error box div */\n } else {\n applyErrorClass(dualFieldId);\n /* Apply the error border class */\n // $('#errAddbillDual' + elementId).show();\n /* Show the error box div */\n var placeholder = $('#element' + elementId).attr('placeholder');\n /* Creating a message to be shown when error occurs */\n var message = formatMessage(messages['addEditBiller.alert.validationReenterMsg'], placeholder);\n var errorDivParentId = 'errAddbillDual' + elementId;\n // show error message for mobile above the input field.\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + dualFieldId + \" #mobAddBillErrorMsg\").text(message);\n /* Show the error box div */\n $('#' + errorDivParentId).show();\n return true;\n }\n } else {\n removeErrorBorderClass(dualFieldId);\n /* Remove the error border class */\n $('#errAddbillDual' + elementId).hide();\n $('#mobAddBillErrorMsgDiv' + dualFieldId).hide();\n /* Hide the error box div */\n }\n return false;\n}",
"function validateFieldRegEx(elementId, fieldValue) {\n var elementObj = billerCredElements[elementId];\n /* Creating the regular expression */\n var regExpr = new RegExp(\"^\" + elementObj.exprCharacters + elementObj.exprLength + \"$\");\n if (!addBill) {\n var isSecure = billerCredElements[elementId].securedFlag;\n if (isSecure) {\n var asterisk = new RegExp(\"^[\\\\*]*$\");\n if (asterisk.test(fieldValue)) {\n return true;\n }\n\n if (fieldValue === getValueFromKey(parseInt(elementId))) {\n return true;\n }\n }\n }\n /* Checking for PHONE and DATE box type and getting only number from the input field */\n if (elementObj.elementType === \"PHONE_BOX\" || elementObj.elementType === \"DATE_BOX\") {\n \tif(elementObj.elementType === \"DATE_BOX\"){\n \t\tvar regexOfDateBox = /^(0[1-9]|1[0-2])\\/(0[1-9]|1\\d|2\\d|3[01])\\/(19|20)\\d{2}$/;\n \t\t if(!regexOfDateBox.test(fieldValue)){\n \t\t\t return regexOfDateBox.test(fieldValue); \n \t\t }\n \t}\n \t fieldValue = getNumberFromString(fieldValue);\n }\n return regExpr.test(fieldValue);\n}",
"function createDualEntryField(inputType, requiredSymbol, propertyValue, fieldMaxLength, isPersonalInfoSec,\n billerCredsElement) {\n var PHONE_BOX = \"PHONE_BOX\";\n var DATE_BOX = \"DATE_BOX\";\n var replicaName = 'replicaof' + billerCredsElement.id;\n var elementId = billerCredsElement.id;\n var elementType = billerCredsElement.elementType;\n /* Create error div row for mobile */\n var mobErrorDiv = '<div id=\"mobAddBillErrorMsgDiv'+replicaName+'\" class=\"mob_error_msg\">'\n\t\t\t\t\t\t+\t'<span id=\"mobAddEditBillErrorIconDiv\" class=\"failed_icon\"></span>'\n\t\t\t\t\t\t+\t'<span id=\"mobError\" href=\"javascript:void(0)\">'\n\t\t\t\t\t\t+\t\t'<span id=\"mobAddBillErrorMsg\">Error occured.</span>'\n\t\t\t\t\t\t+\t'</span>'\n\t\t\t\t\t\t+'</div>';\n /* Create replica of current row for validation only */\n var replicaDiv = \"<div class='mrgn_bottom create_acc_field'> \"\n + \"<div id='frmRepRowArea\" + billerCredsElement.id + \"' class='addbill-td txt_bold'>\"\n + formatMessage(messages[\"addBill.reEnter\"], billerCredsElement.label) + requiredSymbol\n + \"</div>\"\n + \"<div id='frmRepInputRowArea\" + billerCredsElement.id + \"'>\"\n + mobErrorDiv\n + \"<input type='\" + inputType + \"' class='' placeholder='\" + billerCredsElement.label\n + \"' id='\" + replicaName + \"' maxlength='\" + fieldMaxLength + \"' value='\" + propertyValue + \"' />\";\n if ($.browser.msie && parseInt($.browser.version, 10) === 8) {\n\t if (billerCredsElement.securedFlag) {\n\t \treplicaDiv += \"<input type='text' class='new-textarea txt_inv' id='other\" + replicaName + \"' maxlength='\" + fieldMaxLength + \"' value='\" + propertyValue + \"' />\";\t\n\t }\n\t}\n replicaDiv += \"</div>\"\n + \"</div>\"\n + \"<div class='clear'> </div>\";\n\n /* Checking the elementId for personal information section to draw */\n if (isPersonalInfoSec) {\n $(\"#billerUserData\").append(replicaDiv);\n } else {\n $(\"#billerData\").append(replicaDiv);\n // $('#frmRepRowArea' + billerCredsElement.id).addClass(\"width_area20\");\n $('#frmRepInputRowArea' + billerCredsElement.id).addClass(\"add_bill_bluemsg_frmarea\");\n }\n\n $(\"#\" + replicaName).focus(function() {\n\t\t// Change input type of field from password to text.\n\t\tif (billerCredsElement.securedFlag) {\n\t\t\tif ($.browser.msie && parseInt($.browser.version, 10) === 8) {\n\t\t\t\tcreateInputForIE8Focus(replicaName);\n\t\t\t} else {\n\t\t\t\t$(\"#\" + replicaName).get(0).type = 'text';\n\t\t\t}\n\t\t\t $(\"#\" + replicaName).select();\n\t\t}\n\t}); \n $(\"#\" + replicaName).blur(function () {\n /* Checking for the type of field as PHONE_BOX */\n var formatMightBeNeeded = true;\n if (billerCredsElement.securedFlag) {\n var fieldValue = $(\"#\" + replicaName).val();\n if (/^[\\\\*]*$/.test(fieldValue)) {\n formatMightBeNeeded = false;\n }\n }\n if (formatMightBeNeeded) {\n if (PHONE_BOX === elementType) {\n /* Format the field value to phone format on blur */\n formatPhoneNo(this);\n } else if (DATE_BOX === elementType) { /* Checking for the type of field as DATE_BOX */\n /* Format the field value to date format on blur */\n formatDate(this);\n }\n }\n /* Validating the dual field and sending the biller id */\n var isErrorFound = validateDualField(billerCredsElement.id);\n /* Remove Blue background and question mark icon classes from error div in moblie */\n $(\"#mobAddEditBillErrorIconDiv\").removeClass(\"blue_error_icon\").addClass(\"failed_icon\");\n $(\"#mobAddBillErrorMsgDiv\").removeClass(\"add_blue_hint\").addClass(\"mob_error_msg\");\n if (isErrorFound) {\n \t$(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + replicaName).show();\n } else {\n /* Remove the old message from message span */\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + replicaName + \" #mobAddBillErrorMsg\").empty();\n /* Hide the error box on blur from field */\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + elementId).hide();\n }\n /* Change input type of field from text to password.*/\n\t\tif (billerCredsElement.securedFlag) {\n\t\t\t$(\"#\" + replicaName).get(0).type = 'password';\n\t\t}\n });\n\n $(\"#\" + replicaName).keypress(function (e) {\n /* Creating a regular expression with max length to validate data on keyPress */\n var regExLocal = billerCredsElement.exprCharacters + '{0,' + fieldMaxLength + '}';\n /* Remove the red error border class */\n removeErrorBorderClass(replicaName);\n // hide mobile error message div\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\"+replicaName).hide();\n $('#errAddbillDual' + billerCredsElement.id).hide();\n /* Show the error box div */\n var key = e.keyCode || e.charCode;\n\n if (billerCredsElement.securedFlag) {\n var fieldValue = $(\"#\" + replicaName).val();\n if (/^[\\\\*]*$/.test(fieldValue)) {\n return true;\n }\n }\n\n /* Checking for the type of field as PHONE_BOX */\n if (PHONE_BOX === elementType) {\n /* Checking for Enter key pree to format the phone no */\n if (key === 13) {\n /* Format the field value to phone format on blur */\n formatPhoneNo(this);\n return true;\n }\n /* Validating the field value for Phone field on key press */\n return isValidPhoneEntered(this, e, fieldMaxLength - 4);\n } else if (DATE_BOX === elementType) { /* Checking for the type of field as DATE_BOX */\n /* Checking for Enter key pree to format the phone no */\n if (key === 13) {\n /* Format the field value to date format on blur */\n formatDate(this);\n return true;\n }\n /* Validating the field value for Date field on key press */\n return isValidDateEntered(this, e, fieldMaxLength - 2);\n } else {\n /* Validating the field value for rest of the fields on key press */\n return validateUserInput(this, e, regExLocal);\n }\n });\n}",
"function IBCMatching() {\r\n var asoFilters = new Array();\r\n aSOFilters = ibcCriteria(idrrm, salesOrderCompare);\r\n var aSearchResults = findMatchingRecord(aSOFilters);\r\n if (aSearchResults != null && aSearchResults != '') {\r\n idrrm = aSearchResults[0].getId();\r\n revRec = true;\r\n } else {\r\n revRec = false;\r\n // return;\r\n }\r\n }",
"function createBillerAndPersonalInfoSec(billerCredsElement) {\n var PHONE_BOX = \"PHONE_BOX\";\n var DATE_BOX = \"DATE_BOX\";\n var inputType = \"text\";\n var elementId = billerCredsElement.id;\n var elementType = billerCredsElement.elementType;\n var isPersonalInfoSec = false;\n if (elementId === 9 || (elementId >= 11 && elementId <= 20) || (elementId >= 52 && elementId <= 58)) {\n isPersonalInfoSec = true;\n }\n \n var exprLength = billerCredsElement.exprLength.match(/([^}{]+)(?=})/g);\n var fieldMaxLength = parseInt((exprLength[0].split(','))[1]);\n\n if (PHONE_BOX === elementType) {\n propertyValue = getFormattedPhoneNo(getValueFromKey(elementId));\n fieldMaxLength = fieldMaxLength + 4; /* +4 for two '-' , one '(' and one ')'. */ \n } else if (DATE_BOX === elementType) {\n propertyValue = getFormattedDate(getValueFromKey(elementId));\n fieldMaxLength = fieldMaxLength + 2; /* +2 for two seprators */\n } else {\n propertyValue = getValueFromKey(elementId); /* Get the property value */\n }\n\n /* If it is secure property add masking to behave as password property */\n var isSecuredCred = billerCredsElement.securedFlag;\n if (isSecuredCred) {\n \tinputType = \"password\";\n if (!addBill && propertyValue) { /* If there is no property value just skip the condition then keep the field empty */\n propertyValue = \"*******************************************\".substring(0, fieldMaxLength);\n }\n } else if(billerCredsElement.exprCharacters === \"[0-9]\"){\n \tinputType = \"tel\";\n }\n\n var requiredSymbol = \"\";\n if (billerCredsElement.required) {\n /* To show the required symbol as * after the field label */\n requiredSymbol = '<span class=\"red-astrick\">*</span>';\n }\n /* Creating an error box to show the client side errors */\n var mobErrorDiv = '<div id=\"mobAddBillErrorMsgDiv'+elementId+'\" class=\"mob_error_msg desk_wid_input\">'\n\t \t\t\t\t+\t'<span id=\"mobAddEditBillErrorIconDiv\" class=\"failed_icon\"></span>'\n\t \t\t\t\t+\t'<div id=\"mobError\">'\n\t \t\t\t\t+\t\t'<span id=\"mobAddBillErrorMsg\">Error occured.</span>'\n\t \t\t\t\t+\t'</div>'\n\t \t\t\t\t+'</div>';\n\n var mobHintDiv = \"\";\n /* Checking that hint is available or not */\n if (billerCredsElement.elementHint) {\n /* Creating a hint div to show the hints in the field */\n mobHintDiv = '<div id=\"mobHintMsgMainDiv' + elementId + '\" class=\"txt_inv add_blue_hint add_blue_mobile_hint\">'\n\t\t\t\t\t+ '<span class=\"blue_error_icon\"></span>'\n\t\t\t\t\t+ '<span id=\"mobHintMsg\"></span>'\n\t\t\t\t\t+ '</div>';\n }\n var billerInfoBox = \"\";\n var isUserRegistered = parseBoolean(localStorage.getItem(\"registerUser\"));\n /* If the user status in the user object is guest or null or undefined in any way\n * we are not displaying user-name and password fields for selected billers. */\n if ((!isUserRegistered || isUserRegistered === undefined || isUserRegistered === null)\n \t\t&& (elementId == 52 || elementId == 53)) {\n \tbillerInfoBox = \"\";\n \treturn;\n }\n /* Adding the incentive info icon only for the registered user*/\n var showIncentiveIcon = messages[\"billerRegistration.promoMessage.credentialId_\" + billerCredsElement.id \n + \".industryId_\" + bp_biller_corp_creds_obj.industryId];\n \tif(showIncentiveIcon) {\n \t\tbillerInfoBox += \"<div id='billerIncentiveImgId' class='wid_area100 flt_lft'>\"\n \t\t\t\t\t\t+ \"<img id='incentiveImgId' src='\" + showIncentiveIcon +\"' class='incentive_img' />\"\n \t\t\t\t\t\t+ \"</div>\";\n \t}\n \n \t/* Creating the biller box for personal info section */\n \t\t billerInfoBox += \"<div class='create_acc_field'>\"\n\t\t \t\t\t\t\t+ \"<label id='frmRowArea\" + elementId + \"'>\"\n\t\t\t\t\t + getLabelForSecureElements(elementId, billerCredsElement)\n\t\t\t\t\t + requiredSymbol;\n\n var showPromoUrlInfoIcon = messages[\"billerRegistration.promoUrl.credentialId_\" + billerCredsElement.id];\n if(showPromoUrlInfoIcon) {\n \tbillerInfoBox += \"<span class='fa fa-info-circle fa-lg cred_info_icon' onclick='showProviderInfoPopup(\\\"\"\n \t\t+ showPromoUrlInfoIcon +\"\\\")' id='billerHintIcon\" + billerCredsElement.id + \"'></span>\";\n }\n\tbillerInfoBox += \"</label>\"\n\t\t + \"<div id='frmInputRowArea\" + elementId + \"' class='wid_area100 flt_lft'>\"\n\t\t + mobHintDiv\n\t\t + mobErrorDiv\n\t\t + \"<input type='\" + inputType + \"' class='flt_lft' id='element\" + elementId + \"' placeholder='\"\n\t\t + billerCredsElement.label + \"' maxlength='\" + fieldMaxLength + \"' value='\" + propertyValue + \"'/>\";\n if ($.browser.msie && parseInt($.browser.version, 10) === 8) {\n\t if (billerCredsElement.securedFlag) {\n\t \tbillerInfoBox += \"<input type='text' id='other\" + elementId + \"' class='new-textarea txt_inv' maxlength='\" \n\t \t\t\t\t\t+ fieldMaxLength + \"' value='\" + propertyValue + \"'/>\";\t\n\t }\n }\n /* Creating the biller box end section, making it separate because we have to deal with\n * two different designs for Personal Info section and Biller Info section */\n billerInfoBox += \"</div>\"\n\t + \"</div>\"\n\t + \"<div class='clear'> </div>\";\n\n /* Checking the elementId for personal information section to draw */\n if (isPersonalInfoSec) {\n /* Creating the biller box for personal info section */\n $(\"#billerUserData\").append(billerInfoBox);\n $(\"#billerUserData\").show();\n } else {\n /* Creating the biller box for personal info section with hint and error with in it */\n $(\"#billerData\").append(billerInfoBox);\n $('#frmRowArea' + elementId).addClass(\"width_area20\");\n $('#frmInputRowArea' + elementId).addClass(\"add_bill_bluemsg_frmarea\");\n }\n\n $(\"#element\" + elementId).focus(function () {\n if (billerCredsElement.elementHint) {\n $(\"#element\" + elementId).addClass(\"blue_brdr\");\n /* Set the hint text in error message box */\n $(\"#mobHintMsgMainDiv\" + elementId + \" #mobHintMsg\").text(billerCredsElement.elementHint);\n $(\"#mobHintMsgMainDiv\" + elementId).show();\n $(\"#mobAddBillErrorMsgDiv\" + elementId).hide();\n /* Getting the value from field */\n var hintValue = $(\"#element\" + elementId).val();\n /* Setting the same value in same field so that for mobile if hint is shown\n * the cursor should move back to field as per bug fixes. */\n $(\"#element\" + elementId).val(hintValue);\n }\n /* Change input type of field from password to text */\n if (billerCredsElement.securedFlag) {\n \tif ($.browser.msie && parseInt($.browser.version, 10) === 8) {\n\t\t\t\tcreateInputForIE8Focus(elementId, billerCredsElement.elementHint);\n\t\t\t} else {\n\t\t\t\t$(\"#element\" + elementId).get(0).type = 'text';\n\t\t\t}\n $(\"#element\" + elementId).select();\n }\n });\n\n $(\"#element\" + elementId).blur(function () {\n var formatMightBeNeededBlur = true;\n if (billerCredsElement.securedFlag) {\n var fieldValue = $(\"#element\" + elementId).val();\n if (/^[\\\\*]*$/.test(fieldValue)) {\n formatMightBeNeededBlur = false;\n }\n }\n if (formatMightBeNeededBlur) {\n if (PHONE_BOX === elementType) {\n formatPhoneNo(this);\n } else if (DATE_BOX === elementType) {\n formatDate(this);\n }\n }\n /*$(\"#blueHint\" + elementId).hide();*/\n var isErrorFound = validateBillerInputField(elementId);\n $(\"#element\" + elementId).removeClass(\"blue_brdr\");\n /* Remove Blue background and question mark icon classes from error div in moblie */\n if (isErrorFound) {\n \t$(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + elementId).show();\n } else {\n /* Remove the old message from message span */\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + elementId + \" #mobAddBillErrorMsg\").empty();\n /* Hide the error box on blur from field */\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + elementId).hide();\n }\n if (billerCredsElement.elementHint) {\n \t$(\"#mobHintMsgMainDiv\" + elementId + \" #mobHintMsg\").empty();\n $(\"#mobHintMsgMainDiv\" + elementId).hide();\n }\n /* Change input type of field from text to password. */\n if (billerCredsElement.securedFlag) {\n\t\t\t$(\"#element\" + elementId).get(0).type = 'password';\n }\n });\n\n $(\"#element\" + elementId).keypress(function (e) {\n \tvar regExLocal = '';\n /* Creating a regular expression with max length to validate data on keyPress */\n /* if(billerCredsElement.displayOrder == 14 && billerCredsElement.exprCharacters === '.'){\n \tregExLocal = '[0-' + 9 + ']' + '{0,' + fieldMaxLength + '}';\n \t} else {*/\n \tregExLocal = billerCredsElement.exprCharacters + '{0,' + fieldMaxLength + '}';\n /*}*/\n /* Remove error border class on key press */\n removeErrorBorderClass(elementId);\n // hide error message on mobile\n $(\"#addEditBillerForm #mobAddBillErrorMsgDiv\" + elementId).hide();\n $('#errAddbill' + elementId).hide();\n /* Hide the error box div */\n /* Getting the key code */\n var key = e.keyCode || e.charCode;\n /* Checking for the element type as PHONE BOX*/\n\n if (billerCredsElement.securedFlag) {\n \tvar fieldValue = $(\"#element\" + elementId).val();\n \tif(billerCredsElement.displayOrder == 14){\n \t\tvalidateUserInput(this, e, regExLocal);\n \t\t\n \t} else if (/^[\\\\*]*$/.test(fieldValue)) {\n return true;\n }\n }\n\n if (PHONE_BOX === elementType) {\n /* Checking if Enter key is pressed then format the Phone Field */\n if (key === 13) {\n /* Format the field value to phone format */\n formatPhoneNo(this);\n return true;\n }\n /* Validating the field value for Phone field on key press */\n return isValidPhoneEntered(this, e, fieldMaxLength - 4);\n } else if (DATE_BOX === elementType) { /* Checking for the element type as DATE BOX*/\n /* Checking if Enter key is pressed then format the Date Field */\n if (key === 13) {\n /* Format the field value to date format */\n formatDate(this);\n return;\n }\n /* Validating the field value for Date field on key press */\n return isValidDateEntered(this, e, fieldMaxLength - 2);\n\n } else {\n /* Validating the field value for Date field on key press */\n return validateUserInput(this, e, regExLocal);\n }\n });\n /* Checking for the dual property of the biller if ture then create a dual field on UI */\n if (billerCredsElement.dualEntryFlag) {\n /* Creating a dual entry field same as original field */\n createDualEntryField(inputType, requiredSymbol, propertyValue, fieldMaxLength, isPersonalInfoSec,\n billerCredsElement);\n }\n mobileKeyboardFooterToggle();\n}",
"function pageValidate(){\n var txtFieldIdArr = new Array();\n txtFieldIdArr[0] = \"tf1_SysName,\"+LANG_LOCALE['12134'];\n if (txtFieldArrayCheck(txtFieldIdArr) == false) \n return false;\n \n if (alphaNumericValueCheck (\"tf1_SysName\", '-', '') == false) \n return false;\n\n if (isProblemCharArrayCheck(txtFieldIdArr, \"'\\\" \", NOT_SUPPORTED) == false) \n return false;\n}",
"function validateField(e,o) {\r\n\tvar valid = false;\r\n\tvar v = o.validate;\r\n\tvar r = o.related_field;\r\n\tswitch (v) {\r\n\t\t// VALIDATE INTEGERS\r\n\t\tcase \"integer\":\r\n\t\t\tvalid = isInt(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE FLOATS\r\n\t\tcase \"float\":\r\n\t\t\tvalid = isFloat(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE NO BLANKS - FIELDS THAT JUST NEED SOMETHING FILLED OUT, EXCLUDING WHITESPACE CHARACTERS\r\n\t\tcase \"noblanks\":\r\n\t\t\tvalid = isNotBlank(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE EMAIL ADDRESSES\r\n\t\tcase \"email\":\r\n\t\t\tvalid = isEmail(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE PASSWORDS\r\n\t\tcase \"password\":\r\n\t\t\t//valid = $isNotBlank($(e).value);\r\n\t\t\tvalid = isPassword(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// CONFIRM THE PASSWORDS\r\n\t\tcase \"fields_match\":\r\n\t\t\tif(o.required){\r\n\t\t\t\tvalid = ( document.getElementById(e).value == document.getElementById(r).value && isNotBlank(document.getElementById(e).value));\r\n\t\t\t} else {\r\n\t\t\t\tvalid = (document.getElementById(e).value == document.getElementById(r).value);\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t// VALIDATE IATA NUMBERS\r\n\t\tcase \"iata\":\r\n\t\t\t// A VALID IATA IS EITHER AN INTEGER OR ONE OR OUR CUSTOM DNAG NUMBERS\r\n\t\t\tvalid = isInt(document.getElementById(e).value) || isDNAG(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE NO EMAIL - FIELDS THAT NEED SOMETHING FILLED IN, BUT NOT AN EMAIL ADDRESS\r\n\t\tcase \"noemail\":\r\n\t\t\tvalid = isNotBlank(document.getElementById(e).value) && !isEmail(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE US FORMATTED DATES\r\n\t\tcase \"usdate\":\r\n\t\t\tvalid = isUSDate(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE EURO FORMATTED DATES\r\n\t\tcase \"eurodate\":\r\n\t\t\tvalid = isEuroDate(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// VALIDATE CHECKBOX FIELDS\r\n\t\tcase \"checkbox\":\r\n\t\t\tvar n = document.getElementsByName(document.getElementById(e).name);\r\n\t\t\tfor (var i=0; i<n.length; i++) {\r\n\t\t\t\tif (n[i].checked) {\r\n\t\t\t\t\tvalid = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t// VALIDATE RADIO FIELDS\r\n\t\tcase \"radio\":\r\n\t\t\tvar n = document.getElementsByName(document.getElementById(e).name);\r\n\t\t\tfor (var i=0; i<n.length; i++) {\r\n\t\t\t\tif (n[i].checked) {\r\n\t\t\t\t\tvalid = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t// VALIDATE SELECT FIELDS\r\n\t\tcase \"select-one\":\r\n\t\t\tif (document.getElementById(e).selectedIndex > 0) {\r\n\t\t\t\tvalid = true;\r\n\t\t\t} else {\r\n\t\t\t\tvalid = false;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase \"select-multiple\":\r\n\t\t\tif (document.getElementById(e).selectedIndex > -1) {\r\n\t\t\t\tvalid = true;\r\n\t\t\t} else {\r\n\t\t\t\tvalid = false;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t// VALIDATE CREDIT CARD NUMBERS\r\n\t\tcase \"creditcard\":\r\n\t\t\tvalid = isCreditCardNumber(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t\t// THE DEFAULT VALIDATION FOR A REQUIRED FIELD IS NO BLANKS\r\n\t\tdefault:\r\n\t\t\tvalid = isNotBlank(document.getElementById(e).value);\r\n\t\t\tbreak;\r\n\t}\r\n\treturn valid;\r\n}",
"function validateMatch(row, select) {\n const fields = row.querySelectorAll(\"select\");\n const validator = row.querySelector(\".add-match-validation\");\n if (\n fields[0] === select &&\n select.selectedIndex > 0 &&\n select.selectedIndex !== fields[1].selectedIndex\n ) {\n fields[0].setAttribute(\"aria-invalid\", \"false\");\n if (fields[1].selectedIndex > 0) {\n fields[1].setAttribute(\"aria-invalid\", \"false\");\n validator.innerHTML = \"\";\n }\n } else if (\n fields[1] === select &&\n select.selectedIndex > 0 &&\n select.selectedIndex !== fields[0].selectedIndex\n ) {\n fields[1].setAttribute(\"aria-invalid\", \"false\");\n if (fields[0].selectedIndex > 0) {\n validator.innerHTML = \"\";\n }\n } else if (\n fields[0].selectedIndex > 0 &&\n fields[0].selectedIndex === fields[1].selectedIndex\n ) {\n fields[0].setAttribute(\"aria-invalid\", \"false\");\n fields[1].setAttribute(\"aria-invalid\", \"true\");\n validator.innerHTML = validator.getAttribute(\"data-val-msg-diff\");\n } else {\n if (fields[0] === select && fields[0].selectedIndex === 0) {\n fields[0].setAttribute(\"aria-invalid\", \"true\");\n validator.innerHTML = validator.getAttribute(\"data-val-msg\");\n }\n if (fields[1] == select && fields[1].selectedIndex === 0) {\n fields[1].setAttribute(\"aria-invalid\", \"true\");\n validator.innerHTML = validator.getAttribute(\"data-val-msg\");\n }\n }\n if (validator.innerHTML) {\n validator.classList.remove(\"field-validation-valid\");\n validator.classList.add(\"field-validation-error\");\n } else {\n validator.classList.add(\"field-validation-valid\");\n validator.classList.remove(\"field-validation-error\");\n }\n }",
"function fieldDeterminant(element) {\n var numElements = element.length;\n\n for (var i = 0; i < numElements; i++) {\n if (element[i].value.length < 1) {\n return false;\n }\n }\n\n return true;\n }",
"function checkCreateAccountSec(elementId) {\n\tvar validated = true;\n\tvar emailRegEx = /^[a-zA-Z0-9][a-zA-Z0-9\\_\\.\\+\\-]*[a-zA-Z0-9]\\@[a-zA-Z0-9][a-zA-Z0-9\\.\\-]*\\.[a-zA-z]{2,6}/;\n\tvar passwordRegEx = /^(?=\\S+$).{4,20}/;\n\tvar phoneRegEx = /^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$/;\n\tvar zipRegEx = /^\\d{5}$/;\n\tvar $requiredFields = $('input[type=\"text\"],input[type=\"password\"],input[type=\"tel\"]','#frmGuestCreateAcc');\n\t/* Iterating through the list of input fields */\n\t$requiredFields.each(function () {\n\t\t/* Getting the value of input field */\n\t\tvar inputVal = $(this).val().trim();\n\t\tvar elementId = $(this).attr('id');\n\t\tif (!emailRegEx.test(inputVal) && elementId === 'emailId') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!emailRegEx.test(inputVal)&& elementId === 'confrmEmailId') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!passwordRegEx.test(inputVal)&& elementId === 'password') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!phoneRegEx.test(inputVal)&& elementId === 'mobileNo') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!zipRegEx.test(inputVal)&& elementId === 'zipCode') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!inputVal || $(this).hasClass('error_red_border')) {\n\t\t\tvalidated = false;\n\t\t}\n\t});\n\treturn validated;\n}",
"function validateEquipmentno(oSrc, args) {\n var cols = ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).GetClientColumns();\n var _rowI = ifgPreAdvice.rowIndex;\n var sEquipmentno = args.Value\n var checkDigit;\n var sContNo;\n var strContinue = \"\";\n var msg = checkContainerNo(sEquipmentno);\n\n if (msg == \"\") {\n if (el(\"hdnchkdgtvalue\").value == \"True\") {\n if (sEquipmentno.length == 10) {\n sEquipmentno = sEquipmentno + getCheckSum(sEquipmentno.substr(0, 10));\n ifgPreAdvice.Rows(_rowI).SetColumnValuesByIndex(1, sEquipmentno);\n strContinue = \"N\";\n } else {\n checkDigit = getCheckSum(sEquipmentno.substr(0, 10));\n\n if (sEquipmentno.length >= 10) {\n if (checkDigit != sEquipmentno.substr(10)) {\n args.IsValid = false;\n oSrc.errormessage = \"Check Digit is incorrect for the entered Equipment. Correct check digit is \" + checkDigit;\n return;\n }\n }\n }\n }\n } else {\n args.IsValid = false;\n oSrc.errormessage = msg;\n return;\n }\n\n if (strContinue == \"\") {\n validateEquipmentNo(oSrc, args);\n if (args.IsValid == false) {\n return false\n }\n }\n\n var rowState = ifgPreAdvice.ClientRowState();\n var oCallback = new Callback();\n\n oCallback.add(\"EquipmentId\", sEquipmentno);\n oCallback.add(\"GridIndex\", ifgPreAdvice.VirtualCurrentRowIndex());\n oCallback.add(\"RowState\", rowState);\n oCallback.invoke(\"PreAdvice.aspx\", \"ValidateEquipment\");\n if (oCallback.getCallbackStatus()) {\n //Newly added if Equipment no already available in some other depot\n if (oCallback.getReturnValue(\"EquipmentNoInAnotherDepot\") == \"false\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" already exists for Pre-Advice in some other Depot.\";\n args.IsValid = false;\n }\n else if (oCallback.getReturnValue(\"StatusOfEquipment\") == \"false\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" already is in Active State in some other Depot.\";\n args.IsValid = false;\n }\n else if (oCallback.getReturnValue(\"bNotExists\") == \"true\") {\n args.IsValid = true;\n } \n else if (oCallback.getReturnValue(\"bRentalNotExists\") == \"false\") {\n // args.IsValid = false;\n var strCustomer = oCallback.getReturnValue(\"Customer\");\n var strAllowRental = oCallback.getReturnValue(\"AllowRental\");\n var cols = ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).GetClientColumns();\n if (strCustomer != cols[0] && cols[0] != \"\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" already exists for Customer \" + strCustomer + \" in Rental\";\n args.IsValid = false;\n }\n else if (strAllowRental == \"False\") {\n oSrc.errormessage = \"This Equipment \" + sEquipmentno + \" cannot be submitted as Rental Gate Out not created \" + strCustomer + \" in Rental\";\n args.IsValid = false;\n }\n }\n else {\n args.IsValid = false;\n var strCustomer = oCallback.getReturnValue(\"Customer\");\n oSrc.errormessage = \"Gate In has been already created for the Equipment \" + sEquipmentno + \" with Customer \" + strCustomer + \",hence cannot create Pre-Advice.\";\n }\n if (oCallback.getReturnValue(\"EquipmentTypeCode\") != '' && oCallback.getReturnValue(\"EquipmentTypeId\") != '') {\n ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).SetColumnValuesByIndex(2, new Array(oCallback.getReturnValue(\"EquipmentTypeCode\"), oCallback.getReturnValue(\"EquipmentTypeId\")));\n ifgPreAdvice.Rows(ifgPreAdvice.CurrentRowIndex()).SetReadOnlyColumn(2, true);\n }\n \n }\n else {\n showErrorMessage(oCallback.getCallbackError());\n }\n oCallback = null;\n}",
"findSignInElement(data,matchCriteria){\n var elemmentToSearch=\"input\";\n if(matchCriteria.element){\n elemmentToSearch=matchCriteria.element;\n }\n if(!data[elemmentToSearch]){\n data[elemmentToSearch]={\n elements:document.getElementsByTagName(elemmentToSearch)\n };\n }\n var elementsToMatch=data[elemmentToSearch].elements;\n\n if((!elementsToMatch) || (!elementsToMatch.length)){\n //if there is no any controllable elements in the page, it will not operate\n return null;\n }\n\n\n for(var x=0;x<elementsToMatch.length;x++){\n var currentElement=elementsToMatch[x];\n var attrData={matched:0};\n this.matchAttribute(attrData,currentElement,\"id\",matchCriteria.id);\n this.matchAttribute(attrData,currentElement,\"name\",matchCriteria.name);\n this.matchAttribute(attrData,currentElement,\"type\",matchCriteria.type);\n this.matchAttribute(attrData,currentElement,\"class\",matchCriteria.className);\n this.matchAttribute(attrData,currentElement,\"data-callback\",matchCriteria.dataCallback);\n this.matchAttribute(attrData,currentElement,\"value\",matchCriteria.value);\n this.matchAttribute(attrData,currentElement,\".textContent\",matchCriteria.textContent);\n this.matchChildElement(attrData,currentElement,matchCriteria.childElement);\n if(attrData.matched===1){\n return currentElement;\n }\n }\n return null;\n }",
"function validateFieldValue(regex,valueToValidate,errorField,failedText) {\n if (timesSubmited) {\n if (valueToValidate != \"\") {\n if (!regex.test(valueToValidate)) {\n return fadeInError(errorField, failedText);\n }else{\n return fadeOutError(errorField);\n }\n } else {\n return fadeInError(errorField, \"Ovo polje je obavezno.\");\n }\n }\n}",
"function validateAdvisorInput() {\n //select advisor input text value\n var rA = document.getElementById('advisor').value;\n //return a bool for validity if function isSet returns true for the value.\n var valid = (isSet(rA));\n //if valid, return the advisor.\n if (valid) {\n console.log(rA);\n return rA\n };\n //on error, return an error.\n console.log('Advisor is not set.')\n document.getElementById('fieldAdvisor').style.border = \"8px solid red\";\n return Error('please select an Advisor. ');\n \n}",
"function errorRRRV(){\n\tvar RRRV1 = document.getElementById('TRV_RRRV1_id').value\n\tvar RRRV2 = document.getElementById('TRV_RRRV2_id').value\n\t\n\tif (RRRV1 != 0 && RRRV2 ==0){\n\t\treturn true\n\t}\n\tif (RRRV2 == 0 && RRRV1 == 0){\n\t\treturn true\n\t} \n\telse \n\t\treturn false\n}",
"static validateValuationCodeEntered(pageClientAPI, dict) {\n let error = false;\n let message = '';\n //Code group is not empty\n if (!libThis.evalCodeGroupIsEmpty(dict)) {\n //Characteristic is blank\n if (libThis.evalIsCodeOnly(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('field_is_required');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n } else {\n //Code sufficient is set and reading is empty\n if (libThis.evalIsCodeSufficient(dict) && libThis.evalIsReadingEmpty(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('validation_valuation_code_or_reading_must_be_selected');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n }\n }\n }\n if (error) {\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n } else {\n return Promise.resolve(true);\n }\n }",
"function account_patient_validate () {\n acc_patienterrorFound = false;\n if($j('[id$=LensAccountId]').val() == '' || $j('[id$=LensAccount]').val() == ''){\n acc_patienterrorFound = true;\n var ele = $j('[id$=LensAccountId]'); \n removeErrorClass(ele);\n addErrorClass(ele, 'Account is required');\n } else {\n var ele = $j('[id$=LensAccountId]'); \n removeErrorClass(ele);\n }\n\n if($j('[id$=autoNameOptions]').prop('checked')){\n if($j('[id$=Patient]').val() == ''){\n acc_patienterrorFound = true; \n }\n }\n\n if($j('[id$=Patient]').val() == ''){\n acc_patienterrorFound = true;\n var ele = $j('[id$=PatientLKId]'); \n removeErrorClass(ele);\n addErrorClass(ele, 'Patient is required'); \n } else {\n var ele = $j('[id$=PatientLKId]'); \n removeErrorClass(ele);\n }\n return acc_patienterrorFound;\n }",
"function validateCoiHolderSelection() {\r\n if (typeof testgrid1 != \"undefined\") {\r\n if (!isEmptyRecordset(testgrid1.recordset)) {\r\n var validRecords = testgrid1.documentElement.selectNodes(\r\n \"//ROW[CSELECT_IND='-1' and (CROLETYPECODE='COI_HOLDER' or CROLETYPECODE='COI_HOLDER(PENDING)') and CEFFECTIVETODATE='01/01/3000']\");\r\n\r\n //alert(invalidRecords2.length + \"|\" + invalidRecords.length);\r\n\r\n if (validRecords.length <= 0) {\r\n alert(getMessage(\"ci.entity.message.coiHolder.select\"));\r\n return false;\r\n }\r\n var invalidRecords2= testgrid1.documentElement.selectNodes(\r\n \"//ROW[CSELECT_IND='-1' and CROLETYPECODE='COI_HOLDER(PENDING)' and CEFFECTIVETODATE='01/01/3000']\");\r\n\r\n if (invalidRecords2.length > 0 ) {\r\n alert(getMessage(\"ci.entity.message.coiHolder.Pendingselect\"));\r\n return false;\r\n }\r\n var invalidRecords = testgrid1.documentElement.selectNodes(\r\n \"//ROW[CSELECT_IND='-1' and CROLETYPECODE='COI_HOLDER' and CEFFECTIVETODATE!='01/01/3000' \" +\r\n \"or CSELECT_IND='-1' and CROLETYPECODE!='COI_HOLDER']\");\r\n if (invalidRecords.length > 0) {\r\n alert(getMessage(\"ci.entity.message.selection.invalid\", new Array(\"\\n\")));\r\n return false;\r\n }\r\n } else {\r\n alert(getMessage(\"ci.entity.message.coiHolder.oneSelect\"));\r\n return false;\r\n }\r\n } else {\r\n alert(getMessage(\"ci.entity.message.coiHolder.oneSelect\"));\r\n return false;\r\n }\r\n return true;\r\n}",
"function validateAdsAddPageForm(formname,isimage)\n{\n var frmAdType = $(\"#\"+formname+\" input[type='radio']:checked\").val();\n \n if(frmAdType=='html'){\n if($('#frmTitle').val() == ''){\n alert(TIT_REQ);\n $('#frmTitle').focus()\n return false;\n }else if($('#frmHtmlCode').val() == ''){\n alert(HTML_REQ);\n $('#frmHtmlCode').focus()\n return false;\n }\n }else{ \n if($('#frmTitle').val() == ''){\n alert(TIT_REQ);\n $('#frmTitle').focus()\n return false;\n }else if($('#frmAdUrl').val() == ''){\n alert(URL_LINK_REQ);\n $('#frmAdUrl').focus()\n return false;\n }else if(IsUrlLink($('#frmAdUrl').val()) ==false){ \n alert(ENTER_VALID_LINK);\n $('#frmAdUrl').select();\n return false;\n }\n \n if(isimage==0){\n if($('#frmImg').val() == ''){\n alert(IMG_REQ);\n $('#frmImg').focus()\n return false;\n }\n }\n if($('#frmImg').val() != ''){\n var ff = $('#frmImg').val();\n var exte = ff.substring(ff.lastIndexOf('.') + 1);\n var ext = exte.toLowerCase();\n if(ext!='jpg' && ext!='jpeg' && ext!='gif' && ext!='png'){\n alert(ACCEPTED_IMAGE_FOR);\n $('#frmImg').focus();\n return false;\n }\n \n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clear the localStorage and set as blank array | clearDataFromLocalStorage() {
localStorage.db = [];
} | [
"vaciarLocalStorage() {\n localStorage.clear();\n }",
"function clearLeaderboard() {\n leaderboardArr = [];\n localStorage.clear();\n displayLeaderboard();\n}",
"function clear(){\n localStorage.clear();\n highScores=[];\n highScoreParent.innerHTML=\"\";\n }",
"function clear() {\n localStorage.clear();\n location.reload();\n}",
"function updateLocalStorage(school) {\n localStorage.setItem('student_arry', '');\n\n localStorage.setItem('student_array', JSON.stringify(school.student_array));\n}",
"function clearAllTasksFromLocalStorage() {\n\n localStorage.removeItem('tasks');\n\n \n}",
"function clearCoffees(){\n storageArr = [];\n localStorage.clear();\n cardArea.innerHTML = \"\";\n location.reload();\n}",
"removeFromLocalStorage() {\n const artistsInStorage = localStorage.getItem(\"Artists\");\n let currentArray = [];\n if (artistsInStorage) {\n currentArray = JSON.parse(artistsInStorage);\n const index = this.indexContainingID(currentArray, this.props.info.id);\n if (index > -1) {\n currentArray.splice(index, 1);\n }\n }\n localStorage.removeItem(\"Artists\");\n localStorage.setItem(\"Artists\", JSON.stringify(currentArray));\n }",
"function clearStorage() {\n Object.keys(localStorage).filter(function (key) {\n return key.startsWith(options.name);\n }).forEach(function (key) {\n return localStorage.removeItem(key);\n });\n}",
"function clearCityStorage() {\n window.localStorage.clear();\n location.reload();\n}",
"function clearSavedState()\n{\n localStorage.clear(); // nuclear option\n console.info(\"All saved states have been cleared.\");\n}",
"static clearMyGifos() {\n const myGifos = [];\n localStorage.setItem(Local.MY_GIFOS_KEY, JSON.stringify(myGifos));\n }",
"function clear() {\n resetStore();\n }",
"deleteTasks(){\n\t\tlocalStorage.clear();\n\t}",
"function clearScore(){\n localStorage.setItem('highscore','');\n localStorage.setItem('highscoreName','');\n reset();\n}",
"function clearMemory(){ memory = [] }",
"function clearNotes() {\n clear: localStorage.clear();\n}",
"function checkLocalStorage() {\n if (!Array.isArray(topicsList)) {\n topicsList = [];\n }\n if (!Array.isArray(favList)) {\n favList = [];\n }\n}",
"function clearInitiative () {\n\tinitiative.length = 0;\n\tdelete localStorage.initiative;\n\tinitDisplay.textContent = '';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get fan in Harbor Breeze Hub from remote id. | function getFanByRemoteId(remoteId) {
if (!(remoteId in router.hbhub.fans)) {
return null;
}
return router.hbhub.fans[remoteId];
} | [
"getById(id) {\n return HubSite(this, `GetById?hubSiteId='${id}'`);\n }",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('livechannel', 'get', kparams);\n\t}",
"function getBeerById(req, res) {\n brewerydbModel\n .getBeerById(req.params.beerid)\n .then(function(beerData) {\n res.json(beerData);\n });\n }",
"function remoteLookup (callback) {\n bo.runtime.sendMessage({\n type: \"remoteLookup\",\n payload: {\n // window.location.pathname.split('/')\n // Array(4) [ \"\", \"d\", \"1886119869\", \"Soccer\" ]\n // window.location.pathname.split('/')[2]\n // \"1886119869\"\n testId: window.location.pathname.split('/')[2]\n }\n }, callback);\n}",
"async function getFarmer(farmerId) {\n try {\n let response = await axios.get(`${process.env.REACT_APP_API_BACKEND}/info/farmer/${farmerId}`, {\n headers: authHeader(),\n });\n return response.data;\n } catch (error) {\n throw error;\n }\n}",
"findById(id) {\n return request.get(`/api/flows/${id}`);\n }",
"family(id) {\n\t\tlet arr = this.families.get(id);\n\t\treturn arr || null;\n\t}",
"function GetFreelancerById(id) {\n var URL = API_HOST + API_PROFILS_PATH +'/'+id\n Axios.get(URL)\n .then((response) => response.data);\n \n}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('shortlink_shortlink', 'get', kparams);\n\t}",
"static async getListing(id) {\n const result = await db.query(\n `SELECT id, host_username, title, description, price\n FROM listings\n WHERE id = $1`, \n [id]\n );\n let listing = result.rows[0];\n return listing;\n }",
"function getVenue(id) {\n $.ajax({\n url: `https://api.songkick.com/api/3.0/venues/${id}.json?apikey=${myApi}`,\n method: \"GET\"\n }).done(function(response) {\n $d.trigger(\"venue:loaded\", response.resultsPage.results.venue);\n });\n}",
"getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }",
"function GetRack() {\r\n GetRackWithName(getUrlParameter('id')) ;\r\n}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'get', kparams);\n\t}",
"retrieveHotel(id){\n return axios.get(`${CONST_API_URL}/showHotelDetails/${id}`);\n }",
"function getDrink( id ) {\n return rp( {\n url: \"http://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=\" + id,\n json: true\n }).then(function (res) {\n return res.drinks[0];\n }, function(err) {\n return err;\n })\n}",
"static getRemotePaths(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'getRemotePaths', kparams);\n\t}",
"function getAlbum (id) {\n return $http({\n url: 'local.json',\n method: 'GET'\n }).then(function(response) {\n return _.find(response.data, {'id': parseInt(id, 10)});\n });\n }",
"function GetById(id){\n return $http.get('http://localhost:8080/api/media/' + id).then(handleSuccess, handleError('Error getting media by id'));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event handlers for adding a library in settings. | function addLibraryClicks () {
var addButton = document.getElementById('add');
var libraryName = document.getElementById('name-input');
var libraryPath = document.getElementById('library-path-input');
addButton.addEventListener('click', function () {
var data = JSON.stringify({
name: libraryName.value,
library_path: libraryPath.value
});
addLibrary(data);
});
} | [
"createLibrary(event) {\n const controller = event.data.controller;\n InputDialog.type = 'createLibrary';\n const dialog = new InputDialog((input) => {\n if (null == controller.createLibrary(input)) {\n InfoDialog.showDialog('A library' +\n ' with this name already exists!');\n }\n }, 'New Library', null);\n dialog.show();\n }",
"function addLibrary (info) {\n\n\t\tvar response = null;\n\t\tvar params = { method: 'POST', body: info, headers:\n\t\t\t\t{ 'Content-Type': 'application/json' } };\n\n\t\tfetch('/add_library', params).then(function (res) {\n\n\t\t\tresponse = res;\n\t\t\treturn res.text();\n\n\t\t}).then(function (message) {\n\n\t\t\tif (response.status === 201) {\n\t\t\t\tViews.addMessage('Library added.');\n\t\t\t} else {\n\t\t\t\tViews.addMessage(message);\n\t\t\t}\n\n\t\t});\n\n\t}",
"_onAddApplication() {\n this._showLoader();\n this.$.appscoApplicationAddSettings.addApplication();\n }",
"function libraryChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = libraryHome;\n pushstream.addChannel('library');\n pushstream.connect();\n}",
"function addToGallery() {\n library.forEach(book => displayBooks(book));\n updateStats();\n library.splice(0, library.length);\n form.reset();\n}",
"function setLibrary() {\n\tmyLibrary = JSON.parse(localStorage.getItem('library'));\n}",
"function addMovieToLibrary(movie,movieID,library){\n \n library.set(movieID,movie);\n movieID++;\n }",
"getLibraries() {\n this.sendMessage('libraries', { libraries: Ember.libraries._registry });\n }",
"function addToListen(e) {\n isToListen = true\n\n const url = '/toListenAlbum';\n\n const data = {\n albumID: album._id,\n name: album.name,\n cover: album.cover\n }\n\n // Create our request constructor with all the parameters we need\n const request = new Request(url, {\n method: 'post',\n body: JSON.stringify(data),\n headers: {\n 'Accept': 'application/json, text/plain, */*',\n 'Content-Type': 'application/json'\n },\n });\n\n fetch(request)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json()\n } else {\n return res.json()\n }\n })\n .then((json) => { // the resolved promise with the JSON body\n styleToLoistenButton()\n }).catch((error) => {\n })\n}",
"add(handler) {\n // Give it an ECS reference and let it set up its internal data\n // structure.\n handler.init(this.ecs, this.scriptRunner, this.firer);\n // Register all events the handler is interested in to it.\n for (let et of handler.eventsHandled()) {\n this.register(et, handler);\n }\n // Add it to the internal list for updates.\n this.handlers.push(handler);\n }",
"function saveLibrary() {\n // Add library to firebase database \n // return firebase.firestore().collection('messages').add({\n\n }",
"addKeys () {\n this._eachPackages(function (_pack) {\n _pack.add()\n })\n }",
"function saveLib(){\n chrome.storage.local.set({'library': raw_notes}, function(){\n console.log(\"Library successfully saved.\");\n });\n}",
"function addType(newType, configFunction) {\n OPTION_CONFIGURERS[newType] = configFunction;\n }",
"function init() {\n id(\"add\").addEventListener(\"click\", newList);\n }",
"_defineListeners() {\n this.editor.model.on('insertContent', (eventInfo, [modelElement]) => {\n if (!isDrupalMedia(modelElement)) {\n return;\n }\n this.upcastDrupalMediaIsImage(modelElement);\n // Need to upcast DrupalMediaType to model so it can be used to show\n // correct buttons based on bundle.\n this.upcastDrupalMediaType(modelElement);\n });\n }",
"importLibrary(file) {\n const controller = this;\n this.persistenceController.loadLibraryFromFile(file, function (lib) {\n if (lib != null) {\n if (controller.addLibrary(lib) == null) {\n InfoDialog.showDialog('Can\\'t import this library: a library with this name already exists!');\n }\n }\n else {\n InfoDialog.showDialog('Can\\'t import this library: invalid file content!');\n }\n });\n }",
"InstallMultipleEventClasses() {\n\n }",
"function sharedLibrary (state) {\n return function (row, cb) {\n const [\n /* event */, lib, start, end, slide\n ] = row\n const name = lib[0] === '\"' ? lib.substr(1, lib.length - 2) : lib\n const type = 'LIB'\n const startn = parseInt(start, 16)\n state.code[startn] = { name, start, end, slide, type }\n sorted.add(state.addresses, startn)\n cb()\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IMGUI_API void SetWindowFontScale(float scale); // perwindow font scale. Adjust IO.FontGlobalScale if you want to scale all windows | function SetWindowFontScale(scale) { bind.SetWindowFontScale(scale); } | [
"useFontScaling(scale) {\n this.element.value = this.fontSizeScale.indexOf(scale);\n document.documentElement.style.fontSize = scale * this.baseSize + 'px';\n this.update(this.element.value);\n }",
"function _changeTextScale ( values, handle ) {\n\t\tchangeScale.call( this, values, handle );\n\t}",
"function _updateTextScale ( values, handle ) {\n\t\tupdateScale.call( this, values, handle );\n\t}",
"function increaseFontSize() {\n gMeme.currText.size += 3\n}",
"function resizeScalingTextFromColumn() {\n $('.scaled-text').each(function(){\n var $base = $(this).closest('.scaled-text-base');\n var scale = $base.width() / 1200;\n $(this).css('font-size', (scale * 100) + '%');\n });\n }",
"function decreaseFont(){\r\n\tbody = document.getElementById('fontChange');\r\n\tstyle = window.getComputedStyle(body, null).getPropertyValue('font-size');\r\n\tsettSize = parseFloat(style);\r\n\tbody.style.fontSize = (setSize -3) + 'px'; //decreases the current font size of the page by 3px \r\n}",
"function resizeText(pixels) {\r\n\r\n}",
"function _scaling ( /*[Object] event*/ e ) {\n\t\tvar activeObject = cnv.getActiveObject(),\n\t\tscale = activeObject.get('scaleY') * 100;\n\t\tif ( scale > 500 ) {\n\t\t\tactiveObject.scale(5);\n\t\t\tactiveObject.left = activeObject.lastGoodLeft;\n \tactiveObject.top = activeObject.lastGoodTop;\n\t\t}\n\t\tactiveObject.lastGoodTop = activeObject.top;\n \tactiveObject.lastGoodLeft = activeObject.left;\n\t\tif ( is_text(activeObject) ) {\n\t\t\teditTextScale.set( scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'scale', scale );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'top', activeObject.top );\n\t\t\twindow.tmpTextProps && window.tmpTextProps.setNEW( 'left', activeObject.left );\n\t\t}\n\t\telse {\n\t\t\teditImageScale.set(scale);\n\t\t}\n\t}",
"function updateCanvasScale() {\n cellSize = (window.innerWidth / 100) * gridCellSizePercent;\n cellsPerWidth = parseInt(window.innerWidth / cellSize);\n cellsPerHeight = parseInt((cellsPerWidth * 9) / 21);\n\n canvasWidth = window.innerWidth;\n canvasHeight = cellSize * cellsPerHeight;\n resizeCanvas(canvasWidth, canvasHeight);\n\n if (smallScreen != canvasWidth < minCanvasWidth) {\n smallScreen = canvasWidth < minCanvasWidth;\n if (!smallScreen) {\n ui.showUIByState();\n }\n }\n\n ui.hiscores.resize(false);\n}",
"function updateScale(increment) {\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n //var viewportScale = document.getElementById(\"scale\").value;\n axes.scale += increment;\n draw();\n}",
"function changeFont(){\n\tvar new_font = $('#font').val();\n\teditor.setFontSize(parseInt(new_font));\n}",
"function shrink() {\r\n document.querySelectorAll('.word').forEach((element) => {\r\n element.style.fontSize = '16px';\r\n });\r\n}",
"function canvas_set_font(ctx, size, monospaced) {\n var s = window.getComputedStyle(onscreen_canvas);\n // First set something that we're certain will work. Constructing\n // the font string from the computed style is a bit fragile, so\n // this acts as a fallback.\n ctx.font = `${size}px ` + (monospaced ? \"monospace\" : \"sans-serif\");\n // In CSS Fonts Module Level 4, \"font-stretch\" gets serialised as\n // a percentage, which can't be used in\n // CanvasRenderingContext2d.font, so we omit it.\n ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` +\n (monospaced ? \"monospace\" : s.fontFamily);\n}",
"function setLabel(text) {\n label = text;\n var w = ctx.textWidth(label,0.5);\n if (w > 6) // there are 6 units across the screen\n w = 6;\n if (w < 2)\n w = 2;\n wbound = w / 2;\n ctx.onmodify();\n }",
"updateTextAreaSize(text) {\n var textSettings = this.currentText.getTextSettings();\n\n // Setting the font and size of the text\n this.textAreaElement.css(\"font-size\", textSettings.pixels + \"px\");\n this.textAreaElement.css(\"font-family\", textSettings.fontType);\n\n //TODO: resize text area.\n }",
"function resize() {\n map_width = sky_map.width();\n map_height = sky_map.height();\n font_height = map_height / 25;\n axis_size.x = map_width / 20;\n var x = sky_map.css('font-size', font_height).measureText({\n text: '888888'\n });\n if (x.width > axis_size.x) {\n font_height = font_height * axis_size.x / x.width;\n x = sky_map.css('font-size', font_height).measureText({\n text: '888888'\n });\n }\n axis_size.x = x.width;\n axis_size.y = x.height * 5 / 4;\n font_height = x.height;\n }",
"function setFontMetrics(fontName, metrics) {\n metricMap[fontName] = metrics;\n }",
"calcCompFontSize(num) {\n // num is the main display size in digits\n const d1 = 4; // minimum display size\n const d2 = 32; // maximum display size\n const f1 = 10; // minimum font size\n const f2 = 30; // maximum font size\n let f = f1 + (d2 - num) * ((f2 - f1) / (d2 - d1));\n f = f.toFixed(1);\n f = parseFloat(f, 10);\n // store the font size in variable\n runText.fontSizeComp = `${f}px`;\n }",
"updateFabricTextObject (feature, changes) {\n\n const canvas = this.get('canvas');\n const fabricObj = canvas.featureFabObjs[feature.get('id')];\n const doesFontSizeChange = Object\n .keys(changes)\n .reduce((acc, key) => {\n canvas.update_texttopath(fabricObj, key, changes[key]);\n return acc || key === 'fontSize';\n }, false);\n\n [ 'top', 'left' ]\n .forEach((attrName) =>\n canvas.update_texttopath(fabricObj, attrName, feature.get(attrName))\n );\n\n const newFabricObj = canvas.replace_texttopath(fabricObj);\n\n if (newFabricObj) {\n canvas.container.offsetObject(newFabricObj);\n }\n\n canvas.setZIndexPosition();\n canvas.render();\n\n if (!doesFontSizeChange) {\n // #bug465\n this.updateFabricTextObject(feature, { 'fontSize': feature.get('fontSize') });\n }\n }",
"function scaleBody()\n{\n var w, h, scale;\n\n if (document.body.offsetWidth && document.body.offsetHeight) {\n w = document.body.offsetWidth;\n h = document.body.offsetHeight;\n scale = Math.min(window.innerWidth/w, window.innerHeight/h);\n document.body.style.transform = \"scale(\" + scale + \")\";\n document.body.style.position = \"relative\";\n document.body.style.marginLeft = (window.innerWidth - w)/2 + \"px\";\n document.body.style.marginTop = (window.innerHeight - h)/2 + \"px\";\n document.body.style.top = \"0\";\n document.body.style.left = \"0\";\n /* --shower-full-scale is for style sheets written for Shower 3.1: */\n document.body.style.setProperty('--shower-full-scale', '' + scale);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To display the correct background colour for the recommendation pop up by media type | function selectBackgroundColor() {
if (props.mediaType == "Article") {
return styles.articleBackgroundColor
}
else if (props.mediaType == "Book") {
return styles.bookBackgroundColor
}
else if (props.mediaType == "Movie") {
return styles.movieBackgroundColor
}
else if (props.mediaType == "Song") {
return styles.songBackgroundColor
}
else if (props.mediaType == "TikTok") {
return styles.tiktokBackgroundColor
}
else if (props.mediaType == "YouTube") {
return styles.videoBackgroundColor
}
} | [
"function selectColor() {\n if (props.mediaType == \"Article\") {\n return styles.articleColor\n }\n else if (props.mediaType == \"Book\") {\n return styles.bookColor\n }\n else if (props.mediaType == \"Movie\") {\n return styles.movieColor\n }\n else if (props.mediaType == \"Song\") {\n return styles.songColor\n }\n else if (props.mediaType == \"TikTok\") {\n return styles.tiktokColor\n }\n else if (props.mediaType == \"YouTube\") {\n return styles.videoColor\n }\n}",
"function notiflixConfirm() {\n let amstedOrGreenbrier = Array.from(document.querySelector(\"body\").classList).includes(\"theme-am\") ? \"#0C134F\" : \"#32c682\";\n Notiflix.Confirm.init({\n titleColor: amstedOrGreenbrier,\n okButtonColor: '#f8f8f8',\n okButtonBackground: amstedOrGreenbrier,\n });\n}",
"function tShirtColor() {\n if (designSelector.value === \"Select Theme\") {\n colorListDiv.style.visibility = \"hidden\";\n } else if (designSelector.value === \"js puns\") {\n showColorOptions(puns);\n } else if (designSelector.value === \"heart js\") {\n showColorOptions(heart);\n }\n}",
"function matchMessageBoardColorTo(riskLevel) {\r\n if (riskLevel === \"lowRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#62b1f5';\r\n }\r\n if (riskLevel === \"mediumRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#ffff82';\r\n }\r\n if (riskLevel === \"highRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#f56262';\r\n }\r\n\r\n}",
"function changeFlixerBackgroundToOptionsPage(message) {\r\n changeVideoBackgroundToOptionsPage(message, flixelBackgroundType);\r\n}",
"function showMoodSelectionConfirmation()\n{\n // change the color of the checkmark to reflect the mood of the user\n colorCheckMark();\n // show the mood confirmation window\n switchScreens(activeWindow, document.getElementById(\"mood-logged-screen\"));\n}",
"get_background_color(){\n \tconsole.log(\"returning color based on: \" + this.props.priority)\n\n \tswitch (this.props.priority){\n \t\tcase \"low\":\n \t\t\treturn \"#ffffe6\"\n \t\tcase \"medium\":\n \t\t\treturn \"#fff8eb\"\n \t\tcase \"high\":\n \t\t\treturn \"#ffebeb\"\n \t\tdefault:\n \t\t\treturn \"#ffffff\"\n \t}\n }",
"function showred() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"greenbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"redbg\");\r\n}",
"function showMoodLevel() {\n\t\tvar positiveOrNegative = moodLevel > 0 ? 1 : -1;\n\t\tvar startingColor = 242;\n\t\tvar blueStep = 242 / 100;\n\t\tvar redStep = moodLevel > 0 ? 242 / 100 : 142 / 100;\n\t\tvar greenStep = moodLevel < 0 ? 242 / 100 : 142 / 100;\n\n\t\tvar newRed = startingColor - redStep * moodLevel * positiveOrNegative;\n\t\tvar newGreen = startingColor - greenStep * moodLevel * positiveOrNegative;\n\t\tvar newBlue = startingColor - blueStep * moodLevel * positiveOrNegative;\n\n\t\ttextField.style.background = \"rgb(\" + newRed + \", \" + newGreen + \", \" + newBlue + \")\";\n\t}",
"function showMoodConfirmation(moodProposed)\n{\n document.getElementById(\"mood-image-confirmation\").href = moodNameToFilename(moodEnumToName(moodProposed));\n document.getElementById(\"mood-description-confirmation\").text = moodEnumToName(moodProposed);\n switchScreens(activeWindow, document.getElementById(\"mood-confirmation-screen\"));\n}",
"function updateStylePreview(style)\n{\n //Story title\n let title = $(\"#preview-title\");\n title.css(\"font-family\", style.title_font);\n title.css(\"color\", style.title_font_color);\n \n //Activity area\n let text = $(\"#preview-mission-title, #preview-activity-title, #preview-activity-text\");\n text.css(\"font-family\", style.text_font);\n text.css(\"color\", style.text_font_color);\n \n let area = $(\"#preview-activity-area\");\n area.css('background-color', convertHex(style.activity_area_color, style.activity_area_opacity));\n area.css('border-color', style.activity_area_border);\n \n //Buttons\n let button = $(\"#preview-button\");\n button.css(\"background-color\", style.buttons_color);\n button.css(\"color\", style.buttons_text_color);\n \n //Background\n if(style.use_background_image) {\n $(\"#preview-body\").css(\"background-color\", 'transparent');\n if(style.background_image)\n {\n let url = 'url(\\'' + style.background_image + '\\')';\n $(\"#preview-body\").css(\"background-image\", url);\n }\n } else {\n $(\"#preview-body\").css(\"background-color\", style.background_color);\n $(\"#preview-body\").css(\"background-image\", '');\n }\n \n //Chat preview\n let chat_color;\n let chat_text_color;\n switch (style.chat_theme) {\n case 'dark':\n chat_color = '#575b5f';\n chat_text_color = 'white';\n break;\n case 'light':\n chat_color = 'white';\n chat_text_color = 'black';\n break;\n case 'pink':\n chat_color = '#9932CC';\n chat_text_color = 'white';\n break;\n }\n $(\"#preview-chat-header\").css(\"color\", chat_text_color);\n $(\"#preview-chat-header\").css(\"background-color\", chat_color);\n}",
"function displayModePatch() {\n\tif (PLAYER.type!=PLAYERTYPE) {\n\t\tPLAYERTYPE=PLAYER.type;\n\t\tif ($_modesel.val()==\"chMode\" || $_modesel.val()==\"rMode\") {\n\t\t\t$videowidth.removeClass().addClass('span1');\n\t\t\t$(\"#ytapiplayer\").attr(\"width\", '1').attr(\"height\", '1');\n\t\t}\n\n\t}\n}",
"function changeDisplayBackgroundColor() {\n iterations++;\n $(\"#display\").css(\"background-color\", DISPLAY_BACKGROUND_COLORS[iterations % DISPLAY_BACKGROUND_COLORS.length]);\n }",
"function updateColorPreview() {\n\t\tif (ctrColor.colorButton.style.display === 'none') return;\n\t\tlet [r, g, b, al = 1] = getRGBpack(\n\t\t\tgetCurrentColor()\n\t\t).map((n, i) => {\n\t\t\tif (i !== 3) return Math.round(n * 255);\n\t\t\telse return n;\n\t\t});\n\t\tctrColor.colorButtonPreview.style.background = (\n\t\t\t`linear-gradient(-45deg,rgba(${r},${g},${b}) 49%,rgba(${r},${g},${b},${al}) 51%)`\n\t\t);\n\t}",
"confirmColor() {\n if (this.state.amount === this.props.amount) {\n return \"light\";\n }\n return \"primary\";\n }",
"function showgreen() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"redbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"greenbg\");\r\n}",
"function toggleBgOption(theme, bg_type) {\r\n jQuery('#gaddon-setting-row-' + theme + '_bg_color, #gaddon-setting-row-' + theme + '_bg_image').hide();\r\n\r\n if (bg_type == 'color') {\r\n jQuery('#gaddon-setting-row-' + theme + '_bg_color').slideDown();\r\n }\r\n\r\n if (bg_type == 'image') {\r\n jQuery('#gaddon-setting-row-' + theme + '_bg_image').slideDown();\r\n }\r\n}",
"setCustomAppearance(app) {\n //TODO\n }",
"function showpwtopView( aquest, viure ) {\n\n if (viure==1) {\n\n aquest.style.backgroundColor = \"#a529254d\";\n aquest.style.boxShadow = \"0px 0px 1px 3px rgba(165, 41, 37, 0.3)\";\n\n } else {\n\n showpwtop.style.boxShadow = \"none\";\n showpwtop.style.backgroundColor = \"transparent\";\n\n }\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the datetime value of the specified Property from a [[Thing]]. If the Property is not present or its value is not of type datetime, returns null. If the Property has multiple datetime values, returns one of its values. | function getDatetime(thing, property) {
internal_throwIfNotThing(thing);
const literalString = getLiteralOfType(thing, property, xmlSchemaTypes.dateTime);
if (literalString === null) {
return null;
}
return deserializeDatetime(literalString);
} | [
"function parsePropertyValue (node) {\n var $node = $(node);\n\n if ($node.is('meta')) {\n return resolveAttribute($node, 'content');\n } else if ($node.is('audio,embed,iframe,img,source,track,video')) {\n return resolveUrlAttribute($node, 'src');\n } else if ($node.is('a,area,link')) {\n return resolveUrlAttribute($node, 'href');\n } else if ($node.is('object')) {\n return resolveUrlAttribute($node, 'data');\n } else if ($node.is('data,meter')) {\n return resolveAttribute($node, 'value');\n } else if ($node.is('time')) {\n return resolveAttribute($node, 'datetime');\n } else {\n var content = resolveAttribute($node, 'content');\n var text = $node.text();\n return content|| text || '';\n }\n }",
"function getDisplacementTime(dt, fieldname)\n{\n dt.value = dt.value.replace(/[\\[\\]\\'\\\"]/g, \"\");\n var errMsg = \"Invalid \" + fieldname + \".\";\n if (!validateDate(dt, true))\n {\n alert(errMsg);\n return null;\n }\n return dt.value;\n}",
"function CfnAnomalyDetector_TimestampColumnPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('columnFormat', cdk.validateString)(properties.columnFormat));\n errors.collect(cdk.propertyValidator('columnName', cdk.validateString)(properties.columnName));\n return errors.wrap('supplied properties not correct for \"TimestampColumnProperty\"');\n}",
"timestamp() {\n return this._d.get(\"time\");\n }",
"function cfnAnomalyDetectorTimestampColumnPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_TimestampColumnPropertyValidator(properties).assertSuccess();\n return {\n ColumnFormat: cdk.stringToCloudFormation(properties.columnFormat),\n ColumnName: cdk.stringToCloudFormation(properties.columnName),\n };\n}",
"getEntityValue(entity) {\n return this.isLazy ? entity[\"__\" + this.propertyName + \"__\"] : entity[this.propertyName];\n }",
"get timestamp() {\n if (this._timestamp == null) {\n this._timestamp = new Date(this.ts);\n }\n\n return this._timestamp;\n }",
"timeTo (x, y) { return this.get(x, y).time }",
"function jsonObject2Date(jsonObj) {\n if (jsonObj) {\n return new Date(jsonObj.time);\n }\n return null;\n}",
"function CfnBucket_ReplicationTimeValuePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('minutes', cdk.requiredValidator)(properties.minutes));\n errors.collect(cdk.propertyValidator('minutes', cdk.validateNumber)(properties.minutes));\n return errors.wrap('supplied properties not correct for \"ReplicationTimeValueProperty\"');\n}",
"date(time){\n return moment(time);\n }",
"getInputProperty(input) {\n if (input.tagName === 'TEXTAREA') return 'value';\n if (input.tagName === 'SELECT') return 'value';\n if (input.tagName === 'OPTION') return 'selected';\n if (input.tagName === 'INPUT') {\n const type = input.getAttribute('type');\n if (['radio', 'checkbox'].includes(type)) return 'checked';\n return 'value';\n }\n console.warn('FormSync: Cannot synchronize value of form element %o, is unknown.', input);\n return 'value';\n }",
"get dateTimeCreated()\n\t{\n\t\treturn this._dateTimeCreated;\n\t}",
"function getPropertyValuePath(path: NodePath, propertyName: string): ?NodePath {\n types.ObjectExpression.assert(path.node);\n\n return path.get('properties')\n .filter(propertyPath => getPropertyName(propertyPath) === propertyName)\n .map(propertyPath => propertyPath.get('value'))[0];\n}",
"function portalGetDateTime(valMonth, valDay, valYear, valHH, valMM)\r\n{\r\n //set the value \r\n var strDate = valMonth + '/' + valDay + '/' + valYear;\r\n strDate += ' ';\r\n strDate += valHH;\r\n\r\n strDate += ':';\r\n\r\n strDate += valMM;\r\n\r\n strDate += ':';\r\n\r\n //seconds are always zero!\r\n strDate += '00';\r\n\r\n return strDate;\r\n}",
"get stampTime()\n\t{\n\t\t//dump(\"get stampTime: title:\"+this.title+\", value:\"+this._calEvent.stampTime);\n\t\treturn this._calEvent.stampTime;\n\t}",
"get timeChecked()\r\n\t{\r\n\t\treturn this._timeChecked;\r\n\t}",
"getUpdateTimestamp() {\n if (this.updated_ === null) {\n this.updated_ = new Date(this.json_.updated);\n }\n return this.updated_;\n }",
"get createdMoment() {\r\n return date_utils_1.momentify(this.createdAt);\r\n }",
"addDateTime(title, properties) {\n return this.add(title, 4, {\n DateTimeCalendarType: 1 /* Gregorian */,\n DisplayFormat: DateTimeFieldFormatType.DateOnly,\n FriendlyDisplayFormat: DateTimeFieldFriendlyFormatType.Unspecified,\n ...properties,\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method responsible for displaying the correct translation of the 'Welcome Message' section based on the language | renderWelcomeMessage(language) {
switch(language) {
case 'en':
this.setState({welcomeMessage: 'Welcome message from STORMRIDER'});
break;
case 'is':
this.setState({welcomeMessage: 'Bulbulbul asfgwthyt sadasd STORMRIDER'});
break;
default:
break;
}
} | [
"showWelcomeMessage(welcomeMessageMode) {\n Instabug.showWelcomeMessageWithMode(welcomeMessageMode);\n }",
"function helloWorld(language) {\r\n if (language === 'fr') {\r\n return 'Bonjour tout le monde';\r\n }\r\n else if (language === 'es') {\r\n return 'Hola, Mundo';\r\n }\r\n else (language === '') {\r\n return 'Hello, World';\r\n }\r\n}",
"function showWelcome() {\n\n\tconst welcomeHeader = `\n\n=================================================================\n|| ||\n| Employee Summary Generator |\n|| ||\n=================================================================\n\n`\n\n\tconst welcomeMessage = `\n\nWelcome to the Employee Summary Generator!\nThis application will generate a roster of employee details based on information you provide.\n\n`\n\n\tconsole.clear();\n\n\tconsole.log(colors.brightCyan(welcomeHeader));\n\tconsole.log(colors.brightCyan(welcomeMessage));\n\n}",
"function setGreeting() {\n var greetingTranslation = i18nHelper.t('Hello world.');\n greetingElement.innerHTML = greetingTranslation;\n}",
"function greetings(name, language){\n if(language === \"French\"){\n console.log(`Bonjour, ${name}!`)\n }\n else if(language === \"Spanish\"){\n console.log(`Hola, ${name}!`)\n }\n else{\n console.log(`Hello, ${name}!`)\n }\n}",
"function multigreeting(name, language) {\n language = language.toLowerCase() \n if (language === 'en') { return `Hello, ${name}!`}\n if (language === 'es') { return `¡Hola, ${name}!`}\n if (language === 'fr') { return `Bonjour, ${name}!`}\n if (language === 'eo') { return `Saluton, ${name}!`}\n }",
"setWelcomeMessageMode(welcomeMessageMode) {\n Instabug.setWelcomeMessageMode(welcomeMessageMode);\n }",
"function menutoshowlang(){\n}",
"function welcomeUser() {\n let greeting = \"No Current User\";\n\n if (isLoggedIn === true) {\n greeting = \"Welcome, \" + currentUser.name;\n }\n\n return greeting;\n }",
"function GetWelcomeMessege(name)\n{ \n console.log('Assignment 1: Get Welcome Messege ');\n if(name != null && name != \"\" )\n\t{\n console.log(`Welcome ${name} to Tavisca!`);\n }\n else\n {\n console.log('Name is blank!');\n }\n}",
"function onLocaleChange(e)\r\n{\r\n\tvar flashObj = getFlashObject();\r\n\t\r\n\t/* Change the active locale of the flash object. */\r\n\tif (flashObj && flashObj['changeLocale'])\r\n\t{\r\n\t\tflashObj.changeLocale(e.locale);\r\n\t}\r\n\t\r\n\t/* Remove the active-class from the all tabs, add it to the current language. */\r\n\t$(\"#locale a.active\").removeClass('active');\r\n\t$(\"#locale a.\" + e.locale).addClass('active');\r\n\t\r\n\t/* Change alert message if no flash. */\r\n\tif ($(\"#noflash-message div\"))\r\n\t{\r\n\t\t$(\"#noflash-message div\").addClass('hidden');\r\n\t\t$(\"#noflash-message div.\" + e.locale).removeClass('hidden');\r\n\t}\r\n\t\r\n\t/* Update the URL with the selected language. */\r\n\tif (window.history && window.history.pushState)\r\n\t{\r\n\t\twindow.history.pushState(\r\n\t\t{\r\n\t\t\tlocale: e.locale\r\n\t\t}, document.title, \"?locale=\" + e.locale);\r\n\t}\r\n\t\r\n /* Sets a cookie to remember the language use. */\r\n $.cookie(\"locale\", e.locale);\r\n}",
"function languageError() {\n $(\"#results\").append(\n `<p class=\"small\">Sorry, there's no Google translation for Dzongkha, Bhutan's principal language; \n but you may be able to use Nepali phrases!</p>\n \n <p class=\"small\">Nepali:</p>`\n );\n}",
"function showGrowl(message, title, theme) {\n var context = getContext();\n if (theme) {\n context.jGrowl(message, { header:title, theme:theme});\n }\n else {\n context.jGrowl(message, { header:title});\n }\n}",
"translate(text, target, callback){\n\t\t\t\t// Assume that our default language on every JS or HTML template is en_US\n\t\t\t\ttranslates('en_US', target, text, callback);\n\t\t\t}",
"function updateLanguageToKorean() {\n localStorage.setItem('lang', 'ko');\n document.title = $('#title-ko').val();\n $('.navbar__language--english').removeClass('language--active');\n $('.navbar__language--korean').addClass('language--active');\n $('[data-lang=\"en\"]').addClass('hidden');\n $('[data-lang=\"ko\"]').removeClass('hidden');\n}",
"function introResponse() {\n var commands = {\n \"What is it like being an AI\": function() {\n beingAnAI();\n },\n \"Are you a human\": function() {\n humanQuestion();\n },\n \"I don't want to be here\": function() {\n doNotWant();\n }\n };\n\n // can only say the phrases as they appear on screen and can only say one phrase\n annyang.start({\n autoRestart: false,\n continuous: false\n });\n // show the commands and let player say one when function is triggered\n annyang.addCommands(commands);\n $('#intro').show();\n}",
"function setMenuLang(){\n \n // Browser basic settings\n var currentLang = \"lang_\"+getNavigatorLang();\n \n \n if(localStorage.myLang)\n {\n currentLang= \"lang_\"+localStorage.myLang;\n }\n\n //Menu setting\n \n var menu = document.querySelectorAll(\"ul.nav li a\");\n for(var i=0; i<menu.length; i++)\n {\n var data = menu[i].getAttribute(\"data-name\");\n menu[i].innerHTML= window[currentLang][data];\n }\n \n // Navbar title and header setting\n \n var getSelector = document.querySelector(\".navbar-header a\");\n \n var dataName = getSelector.getAttribute(\"data-title\");\n \n getSelector.innerHTML = window[currentLang][dataName];\n \n \n var getSelector = document.querySelector(\".starter-template h1\");\n \n var dataName = getSelector.getAttribute(\"header-title\");\n \n getSelector.innerHTML = window[currentLang][dataName]; \n}",
"greet() {\n return (`${this.name} offers a greeting in ${this.language}`);\n }",
"function contactLanguage(){\r\n\tif(location.pathname.split(\"/\").slice(-1)==\"kontakt.html\"){\r\n\t\t$(\".kontaktInfoS\").hide();\r\n\t}\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checking molecule intersection assigning gap as distance minus radius assigning check to gap less than or equal to 0 and if its true or false | isIntersecting(_molecule) {
//creates new vector without affecting the other vectors weve created
let resultantV = p5.Vector.sub(this.position, _molecule.position);
//distance is length of resultant
let distance = resultantV.mag();
let gap = distance - this.radius - _molecule.radius;
let check = (gap <= 0) ? true : false;
if (check) {
//taking 2 points and calulating dx and dy to get the distance
let dx = this.position.x - _molecule.position.x;
let dy = this.position.y - _molecule.position.y;
//reaction to check
let normalX = dx / distance;
let normalY = dy / distance;
//collision detection
let midpointX = (this.position.x + _molecule.position.x) / 2;
let midpointY = (this.position.y + _molecule.position.y) / 2;
//calc difference in velocity and multiply by normal
let dVector = (this.velocity.x - _molecule.velocity.x) * normalX;
dVector += (this.velocity.y - _molecule.velocity.y) * normalY;
//differences in velocity multiplying by normal
let dvx = dVector * normalX;
let dvy = dVector * normalY;
this.velocity.x -= dvx;
this.velocity.y -= dvy;
let indexValue = _molecule.index;
molecules[indexValue].velocity.x += dvx;
molecules[indexValue].velocity.y += dvy;
}
return check;
} | [
"function checkSurroundingArea(icosphere, centerTile, radius) {\n\tvar queue = new Queue();\n\tvar visited = [];\n\tfor (var size = icosphere.tiles.length-1; size >= 0; size--) visited[size] = false;\n\tvar land = [];\n\tfor (var size = icosphere.tiles.length-1; size >= 0; size--) land[size] = false;\n\tvar distances = [];\n\tfor (var size = icosphere.tiles.length-1; size >= 0; size--) distances[size] = -2;\n\tvar shortestDistance = -1;\n\t\n\tqueue.enqueue(centerTile);\n\tvisited[centerTile] = true;\n\tdistances[centerTile] = 0;\n\twhile (!queue.isEmpty()) {\n\t\tvar tileIndex = queue.dequeue();\n\t\tvar tile = icosphere.tiles[tileIndex];\n\t\tvar neighbors = tile.getNeighborIndices();\n\t\t\n\t\tif (icosphere.vertexHeights[tile.vertexIndices[0]] != 0 ||\n\t\t\ticosphere.vertexHeights[tile.vertexIndices[1]] != 0 ||\n\t\t\ticosphere.vertexHeights[tile.vertexIndices[2]] != 0) {\n\t\t\t\t//Found a land tile\n\t\t\t\tland[tileIndex] = true;\n\t\t\t\tif (shortestDistance === -1 || distances[tileIndex] < shortestDistance) {\n\t\t\t\t\tshortestDistance = distances[tileIndex];\n\t\t\t\t}\n\t\t}\n\t\t\n\t\tfor (var i = 0; i < neighbors.length; i++) {\n\t\t\tvar neighbor = neighbors[i];\n\t\t\tif (!visited[neighbor]) {\n\t\t\t\tif (distances[tileIndex] < radius) {\n\t\t\t\t\tvisited[neighbor] = true;\n\t\t\t\t\tqueue.enqueue(neighbor);\n\t\t\t\t\tdistances[neighbor] = distances[tileIndex] + 1;\n\t\t\t\t}\n\t\t\t} else if (distances[tileIndex] + 1 < distances[neighbor]) {\n\t\t\t\tdistances[neighbor] = distances[tileIndex] + 1;\n\t\t\t\tif (land[neighbor]) {\n\t\t\t\t\tif (shortestDistance === -1 || distances[neighbor] < shortestDistance) {\n\t\t\t\t\t\tshortestDistance = distances[neighbor];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn shortestDistance;\n}",
"isCircleTooClose(x1,y1,x2,y2){\n // if(Math.abs(x1-x2)<50 && Math.abs(y1-y2)<50)\n // return true;\n // return false; \n\n var distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\n if(distance<90)\n return true;\n return false;\n \n }",
"function collision(x1, y1, radius1, x2, y2, radius2) {\n return Math.hypot(x1 - x2, y1 - y2) < radius1 + radius2 ? true : false;\n}",
"function checkIntersections(_collection) {\n for (let a = 0; a < _collection.length; a++) {\n for (let b = a + 1; b < _collection.length; b++) {\n let moleculeA = molecules[_collection[a]];\n let moleculeB = molecules[_collection[b]];\n if (obj.lineState) {\n stroke(125, 100);\n line(moleculeA.position.x, moleculeA.position.y, moleculeB.position.x, moleculeB.position.y);\n };\n moleculeA.isIntersecting(moleculeB) ? (moleculeA.changeColor(), moleculeB.changeColor()) : null;\n }\n }\n}",
"function cannonInBarrierBoolean(cannonBall){\n for(let i = 0; i < barriers.length; i++){\n let barrier = barriers[i];\n\n //Work out barrier edges\n let leftEdge = stageX + (barrier.x * stageDivPathWidth);\n let width = (stageDivPathWidth ) * barrier.length;\n let topEdge = stageY + (barrier.y * stageDivPathHeight);\n let height = stageDivPathHeight + 1;\n //Distance between circle centre & rectangle centre\n var distX = Math.abs(cannonBall.x - leftEdge - width/2);\n var distY = Math.abs(cannonBall.y - topEdge - height/2);\n //Too far apart to be colliding\n if (distX > (width/2 + cannonBall.radius)) { continue; }\n if (distY > (height/2 + cannonBall.radius)) { continue; }\n // SIDE COLLISIONS\n if (distX <= (width/2)) { return true} \n if (distY <= (height/2)) { return true }\n \n // CORNER COLLISIONS\n var dx=distX-width/2;\n var dy=distY-height/2;\n if (dx*dx+dy*dy<=(cannonBall.radius*cannonBall.radius)){\n return true\n }\n }\n return false;\n}",
"intersects(region) {\n return (\n (this[REGION][0] < region[0] + region[2] && this[REGION][0] + this[REGION][2] > region[0]) &&\n (this[REGION][1] < region[1] + region[3] && this[REGION][1] + this[REGION][3] > region[1])\n );\n }",
"function collisionTopBorder(circle){\n /*******************\n * PARTIE A ECRIRE */\n return circle.y-circle.radius<0;\n //return false;\n /*******************/\n}",
"function segmentIntersecte(a, b, c, d) {\n var d1 = determinant(b.x - a.x, b.y - a.y, c.x - a.x, c.y - a.y);\n var d2 = determinant(b.x - a.x, b.y - a.y, d.x - a.x, d.y - a.y);\n if (d1 > 0 && d2 > 0) return false;\n if (d1 < 0 && d2 < 0) return false;\n d1 = determinant(d.x - c.x, d.y - c.y, a.x - c.x, a.y - c.y);\n d2 = determinant(d.x - c.x, d.y - c.y, b.x - c.x, b.y - c.y);\n if (d1 > 0 && d2 > 0) return false;\n if (d1 < 0 && d2 < 0) return false;\n return true;\n }",
"function checkMeshConnectivity({points, delaunator: {triangles, halfedges}}) {\n // 1. make sure each side's opposite is back to itself\n // 2. make sure region-circulating starting from each side works\n let r_ghost = points.length - 1, s_out = [];\n for (let s0 = 0; s0 < triangles.length; s0++) {\n if (halfedges[halfedges[s0]] !== s0) {\n console.log(`FAIL _halfedges[_halfedges[${s0}]] !== ${s0}`);\n }\n let s = s0, count = 0;\n s_out.length = 0;\n do {\n count++; s_out.push(s);\n s = TriangleMesh.s_next_s(halfedges[s]);\n if (count > 100 && triangles[s0] !== r_ghost) {\n console.log(`FAIL to circulate around region with start side=${s0} from region ${triangles[s0]} to ${triangles[TriangleMesh.s_next_s(s0)]}, out_s=${s_out}`);\n break;\n }\n } while (s !== s0);\n }\n}",
"millPathIsMilled(millPath, intersections) {\n for (var p = 1; p < 3; p++) {\n if (intersections[millPath[0]] === p && intersections[millPath[1]] === p && intersections[millPath[2]] === p) {\n return true;\n }\n } \n // else\n return false;\n }",
"function distanceFromIntersectArea(r1, r2, overlap) {\n\t // handle complete overlapped circles\n\t if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL$1) {\n\t return Math.abs(r1 - r2);\n\t }\n\n\t return bisect(function (distance$$1) {\n\t return circleOverlap(r1, r2, distance$$1) - overlap;\n\t }, 0, r1 + r2);\n\t }",
"millPathHasIntersection(millPath, i) {\n return (millPath[0] === i || millPath[1] === i || millPath[2] === i);\n }",
"function insideCircles(node){\n\tvar strCircles = node.region.label;\n\tvar result = [];\n\t//console.log(circles);\n\n\tfor (var i = 0; i < circles.length; i++){\n\t\tvar circle = circles[i];\n\t\tvar distance = Math.sqrt( Math.pow(node.x - circle.x, 2) + Math.pow(node.y - circle.y, 2) );\n\t\t//does this node's region contain this circle\n\t\tif (strCircles.indexOf(circle.label) != -1) {\n\t\t\t//check node is inside\n\t\t\t\n\t\t\t//console.log(strCircles, label, circle, node, distance);\n\t\t\tif (distance >= circle.r){\n\t\t\t\tresult.push(circle);\n\t\t\t}\n\t\t} else {\n\t\t\t//check if node is outside\n\t\t\tif (distance <= circle.r){\n\t\t\t\tresult.push(circle);\n\t\t\t}\n\n\t\t}\n\t}\n\n/*\n\tfor (var i = 0; i < strCircles.length; i++){\n\t\tvar label = strCircles[i];\n\t\tvar circle = findCircle(label);\n\n\t\tvar distance = Math.sqrt( Math.pow(node.x - circle.x, 2) + Math.pow(node.y - circle.y, 2) );\n\n\t\t//console.log(strCircles, label, circle, node, distance);\n\t\tif (distance > circle.r){\n\t\t\tresult.push(circle);\n\t\t}\n\t}\n*/\t\t\t\treturn result;\n}",
"inCone (radius, width, angle, x1, y1, x2, y2) {\n if (radius * radius < this.distanceSq(x1, y1, x2, y2))\n return false\n const angle12 = this.radiansToward(x1, y1, x2, y2) // angle from 1 to 2\n return (width / 2) >= Math.abs(this.subtractAngles(angle, angle12))\n }",
"checkEnvironment(agents, regions, width, height) {\n agents = agents.toArray();\n regions = regions.toArray();\n\n let alerts = [], valid = true;\n let agentsOutOfRegion = [];\n regions.forEach((region) => {\n region.agents.forEach((agent) => {\n let exists = region.some((square) => {\n return agent.row == square.row && agent.column == square.column;\n });\n if (!exists) agentsOutOfRegion.push(agent);\n });\n });\n // agents.forEach((agent) => {\n // let inRegion = regions.some((region) => {\n // return region.some((square) => {\n // return agent.row == square.row && agent.column == square.column;\n // });\n // });\n\n // if (!inRegion) agentsOutOfRegion.push(agent);\n // });\n\n let regionsOutOfEnv = [];\n regions.forEach((region) => {\n let isOutOf = region.some((square) => {\n return square.row + 1 > height || square.row < 0 || square.column + 1 > width || square.column < 0;\n });\n if (isOutOf) regionsOutOfEnv.push(region);\n });\n\n let jointRegions = [];\n regions.forEach((region1, index1) => {\n regions.forEach((region2, index2) => {\n if (index1 === index2) return false;\n\n let joint = region1.some((square1) => {\n return region2.some((square2) => {\n let join = square1.row === square2.row && square1.column === square2.column || $f.isAdjacent(square1, square2);\n return join;\n });\n });\n if (joint) jointRegions = [region1, region2];\n });\n });\n\n let isolateSpaces = [];\n regions.forEach((region) => {\n region.forEach((square1, index) => {\n let notIsolate = region.some((square2, index) => {\n return $f.isAdjacent(square1, square2);\n });\n if (!notIsolate) isolateSpaces.push({square: square1, regionId: region.id});\n });\n });\n\n if (agentsOutOfRegion.length > 0) {\n if (agentsOutOfRegion.length === 1)\n alerts.push('Agent ' + agentsOutOfRegion[0].id + ' is out of the region');\n else {\n let agents = agentsOutOfRegion.map((agent) => {\n return 'agent ' + agent.id;\n });\n agents = agents.join(', ').replace(/a/, 'A');\n alerts.push(agents + ' are out of the region');\n }\n valid = false;\n }\n\n if (regionsOutOfEnv.length > 0) {\n if (regionsOutOfEnv.length === 1)\n alerts.push('Region ' + regionsOutOfEnv[0].id + ' is out of the environment');\n else {\n let regions = regionsOutOfEnv.map((region) => {\n return 'region ' + region.id;\n });\n regions = regions.join(', ').replace(/a/, 'R');\n alerts.push(regions + ' are out of the environment');\n }\n valid = false;\n }\n\n if (jointRegions.length > 0) {\n alerts.push(`Region ${jointRegions[1].id} and region ${jointRegions[0].id} are connected`);\n valid = false;\n }\n\n if (isolateSpaces.length > 0) {\n let space = isolateSpaces[0];\n alerts.push(`Open space (${space.square.column + 1}, ${space.square.row + 1}) in region ${space.regionId} is isolate`);\n valid = false;\n }\n\n let legal = $f.varify(this.state.selected_algorithm, agents, regions, (err) => {\n if (err) {\n alerts.push(err);\n }\n });\n if (!legal) valid = false;\n\n let regionsWithNoAgent = [];\n regionsWithNoAgent = regions.filter((region) => {\n return region.agents.length < 1;\n });\n\n if (regionsWithNoAgent.length > 0) {\n let str = regionsWithNoAgent.map((region) => {\n return 'region ' + region.id;\n }).join(', ').replace(/r/, 'R') + ' do not have agent';\n alerts.push(str);\n valid = false;\n }\n\n if (alerts.length > 0) {\n this.setState({alert: alerts.join('. ')});\n }\n\n return valid;\n }",
"intersectsWith(anotherCollider) {\n\n let delta = [\n this.x - anotherCollider.x, \n this.y - anotherCollider.y\n ];\n\n let dist = magnitudeSquared(delta);\n let r = this.radius + anotherCollider.radius;\n \n return dist < r*r;\n }",
"function checkColision(){\n return obstacles.obstacles.some(obstacle => {\n if(obstacle.y + obstacle.height >= car.y && obstacle.y <= car.y + car.height){\n if(obstacle.x + obstacle.width >= car.x && obstacle.x <= car.x + car.width){\n console.log(\"colision\")\n return true;\n }\n }\n return false;\n });\n}",
"function checkShipIntersection(){\n var placementFootPrint = 0,\n rowForThisFunc = row,\n colForThisFunc = col;\n\n if (isHorizontal) {\n for(var i = 0; i < shipLength; i++) {\n placementFootPrint += gameBoard[rowForThisFunc][colForThisFunc];\n colForThisFunc++;\n }\n } else {\n for(var i = 0; i < shipLength; i++) {\n placementFootPrint += gameBoard[rowForThisFunc][colForThisFunc]\n rowForThisFunc++;\n }\n }\n if (placementFootPrint){\n return false;\n } else {\n return true;\n }\n}",
"intersection () {\n var tan = this.vector.y / this.vector.x,\n _this = this,\n from, to,\n cursorDegree = -Math.atan2(-this.vector.y, -this.vector.x) * 180/Math.PI + 180;\n\n\n for (var i= 0, max = this.cache.length; i < max; i++) {\n var item = _this.cache[i];\n\n from = item.range[0];\n to = item.range[1];\n\n // If one of item's sides area is on the edge state. For example\n // when we have item which 'from' begins from 157 and ends to -157, when all\n // 'cursorDegree' values are appear hear. To not let this happen, we compare\n // 'from' and 'to' and reverse comparing operations.\n if (from > to) {\n if (cursorDegree <= from && cursorDegree <= to || cursorDegree >= from && cursorDegree >= to) {\n _this.activate(item);\n }\n } else {\n if (cursorDegree >= from && cursorDegree <= to) {\n _this.activate(item);\n }\n }\n }\n this.cache.forEach(function (item) {\n\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
end placeDetail function Calls placeSearch API with lat & lng & return place id used for placeDetail | function placeSearch(lat, lng) {
var query = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + lat + "," + lng + "&radius=50000&type=park&keyword=kyak&key=AIzaSyDAhGg64lKOYPK-6jEMFKqQlc2TSTHTI2M";
$.ajax({
url: query,
method: "GET"
}).done(function(response) {
console.log(response);
var placeId = response.results[0].place_id;
console.log(placeId);
placeDetail(placeId);
});
} | [
"function searchPlace(){\n var search = new google.maps.places.PlacesService(map);\n var request = {\n keyword: [searchType],\n location: map.getCenter(),\n rankBy: google.maps.places.RankBy.DISTANCE\n }\n search.nearbySearch(request, function(data, status){\n if(status == google.maps.places.PlacesServiceStatus.OK){\n loc = data[0].name;\n add = data[0].vicinity;\n rating = data[0].rating;\n latitude = data[0].geometry.location.k;\n longitude = data[0].geometry.location.D;\n\n var placeLoc = data[0].geometry.location;\n var marker = new google.maps.Marker({ map: map, position: data[0].geometry.location});\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.setContent(data[0].name);\n infowindow.open(map, this); //google\n });\n // var loc = data[0].place_id;\n\n }\n });\n\n}",
"function geocoder(state) {\n geocoder = new google.maps.Geocoder();\n\n geocoder.geocode( { 'address': state}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n\n var lat = results[0].geometry.location.lat();\n var lng = results[0].geometry.location.lng();\n dispLoc = results[0].formatted_address;\n var placeID = results[0].place_id;\n console.log(dispLoc);\n console.log(placeID);\n\n placeSearch(lat, lng);\n\n console.log(\"lat: \"+lat+\" lng: \"+ lng);\n console.log(results);\n }\n else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n\n}",
"function callNearBySearchAPI() {\n //\n city = new google.maps.LatLng(coordinates.lat, coordinates.long);\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: city,\n zoom: 15,\n });\n //\n request = {\n location: city,\n radius: \"5000\", // meters\n type: [\"restaurant\"],\n // openNow: true,\n fields: [\n \"name\",\n \"business_status\",\n \"icon\",\n \"types\",\n \"rating\",\n \"reviews\",\n \"formatted_phone_number\",\n \"address_component\",\n \"opening_hours\",\n \"geometry\",\n \"vicinity\",\n \"website\",\n \"url\",\n \"address_components\",\n \"price_level\",\n \"reviews\",\n ],\n };\n //\n service = new google.maps.places.PlacesService(map);\n service.nearbySearch(request, getGooglePlacesData);\n //\n}",
"function createMarker(place, map) {\n var infowindow = new google.maps.InfoWindow();\n const newrequest = {\n placeId: place.place_id,\n fields: [\"name\", \"formatted_address\", \"place_id\", \"geometry\",\"website\",\"opening_hours\",\"formatted_phone_number\",\"business_status\"],\n };\n const newservice = new google.maps.places.PlacesService(map);\n \n\n const bounds = new google.maps.LatLngBounds();\n const placesList = document.getElementById(\"places\");\n \n const image = {\n url: \"http://maps.google.com/mapfiles/ms/micons/restaurant.png\",\n size: new google.maps.Size(71, 71),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(17, 34),\n scaledSize: new google.maps.Size(25, 25),\n };\n\n const marker =new google.maps.Marker({\n map,\n icon: image,\n title: place.name,\n position: place.geometry.location,\n });\n\n \n\n marker.addListener(\"click\", () => {\n map.setZoom(17);\n map.setCenter(marker.getPosition());\n\n newservice.getDetails(newrequest, (newplace, newstatus) => {\n if (newstatus === google.maps.places.PlacesServiceStatus.OK) {\n google.maps.event.addListener(marker, \"click\", function () {\n infowindow.setContent(\n \"<div><strong>\" +\n newplace.name +\n \"</strong><br><br>\" +\n \"Business Status: \" +\n newplace.business_status +\n \"<br>\" +\n \"<br>\" +\n newplace.formatted_address +\n \"</div><br>\"+\n \"Opening Hours: \" +\n newplace.opening_hours.weekday_text +\n \"<br>\" +\n \"<br>\" +\n \"Phone: \" +\n newplace.formatted_phone_number +\n \"<br>\"+\n \"<br>\" +\n \"<a href =\" +newplace.website +\" >Check Us Out Online</a>\"+\n \"<br>\" \n );\n \n infowindow.open(map, this);\n });\n }\n });\n\n });\n\n //Places Buttons\n const placesbutton = document.createElement(\"button\");\n placesbutton.textContent = place.name;\n placesbutton.setAttribute(\"class\", \"m-1 btn btn-warning\");\n placesbutton.onclick = function(){\n map.setZoom(17);\n map.setCenter(marker.getPosition());\n infowindowpopup(newservice, newrequest, infowindow, map, marker);\n \n };\n placesList.appendChild(placesbutton);\n bounds.extend(place.geometry.location);\n\n}",
"function getGooglePlacesData2(results, status) {\n //\n if (status == google.maps.places.PlacesServiceStatus.OK) {\n //\n for (var i = 0, l = results.length; i < l; i++) {\n //\n placesObj = {\n id: \"\",\n name: \"\",\n status: \"\",\n openNow: \"\",\n rating: \"\",\n userRatingTotal: \"\",\n priceLevel: \"\",\n photos: [],\n types: [],\n };\n //\n // Place data\n //\n placesObj.id = results[i].place_id;\n placesObj.name = results[i].name;\n placesObj.status = results[i].business_status;\n // placesObj.openNow = results[i].opening_hours.isOpen;\n placesObj.rating = results[i].rating;\n placesObj.userRatingTotal = results[i].user_ratings_total;\n placesObj.priceLevel = results[i].price_level;\n //\n // Photos\n //\n for (var j = 0, m = results[i].photos.length; j < m; j++) {\n //\n photoObj = {\n url: \"\",\n };\n //\n photoObj.url = results[i].photos[j].html_attributions[0];\n //\n placesObj.photos.push(photoObj);\n //\n }\n //\n // Types\n //\n for (var k = 0, n = results[i].types.length; k < n; k++) {\n //\n typeObj = {\n name: \"\",\n };\n //\n typeObj.name = results[i].types[k];\n //\n placesObj.types.push(typeObj);\n //\n }\n //\n places.push(placesObj);\n //\n }\n //\n renderGooglePlacesData();\n //\n }\n //\n}",
"function getExtraDetails(placesMapping, place_id, service) {\n\tservice.getDetails(obj, function(place, status) {\n\t\t\n\t});\n}",
"getPlaceInfo(pos) {\n\t\tlet venueID = '';\n\t\tlet lat = pos.lat, lng = pos.lng;\t\t\n\n\t\t//this fetch's purpose is to find the venueID of the given position\n\t\treturn fetch(`https://api.foursquare.com/v2/venues/search?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&v=${VERSION}&ll=${lat},${lng}`)\n\t\t .then(data => data.json())\n\t\t .then(data => {\n\t\t \tvenueID = data.response.venues[0].id;\n\t\t \treturn this.getPlaceTip(venueID);\n\t\t })\n\t\t .catch(function(e) {\n\t\t console.log(e);\n\t\t return null;\n\t\t });\t \n\t}",
"function searchPlaces(loc) {\n // create places service\n var service = new google.maps.places.PlacesService(map);\n service.nearbySearch({\n location: loc,\n radius: 500\n // type: ['store']\n },\n // callback function for nearbySearch\n function(results, status) {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n for (var i = 0; i < results.length; i++) {\n createMarker(results[i]);\n }\n } else {\n window.alert(\"Google places search failed at that moment, please try again\");\n }\n });\n }",
"function searchRestaurant() {\n let search = {\n bounds: map.getBounds(),\n types: [\"restaurant\"],\n };\n places.nearbySearch(search, (results, status) => {\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n clearResults();\n clearMarkers();\n\n // Create a marker for each resturant found, and\n // assign a letter of the alphabetic to each marker icon.\n for (let i = 0; i < results.length; i++) {\n let markerLetter = String.fromCharCode(\"A\".charCodeAt(0) + (i % 26));\n let markerIcon = MARKER_PATH + markerLetter + \".png\";\n\n // Use marker animation to drop the icons incrementally on the map.\n markers[i] = new google.maps.Marker({\n position: results[i].geometry.location,\n animation: google.maps.Animation.DROP,\n icon: markerIcon,\n });\n\n // If the user clicks a resturant marker, show the details of that place in an info window\n markers[i].placeResult = results[i];\n google.maps.event.addListener(markers[i], \"click\", showInfoWindow);\n setTimeout(dropMarker(i), i * 100);\n addResult(results[i], i);\n }\n }\n });\n}",
"function getplaceByPosition(lat, lon, callback) {\n\t\n\trest('get', googleplaceBaseUrl + 'key=' + googleplacesApiKey + '&latlng=' + lat + ',' + lon, null, callback);\n\t\n}",
"function PlaceObject(arg) {\n this.lat = arg.lat;\n this.lng = arg.lng;\n this.placeId = arg.placeId;\n this.name = arg.name || \"Loading...\";\n this.desc = arg.desc || \"Loading...\";\n this.address = arg.address || \"Loading...\";\n this.categories = arg.categories || [];\n this.isGooglePlace = arg.isGooglePlace;\n this.isLoaded = false;\n this.isDestroyed = false;\n this.imageURL = \"\";\n\n this.marker = null; //References the marker\n\n /*\n Load place-specific details. Is only called on the first mouse event with the marker.\n */\n this.loadDetails = function () {\n if (this.isLoaded || this.isDestroyed) return;\n placeService.getDetails({ //Call details api\n placeId: this.placeId\n }, function(placeDetails, status){ //Bound function into callback\n if (status === google.maps.places.PlacesServiceStatus.OK) { //Check status\n this.name = placeDetails.name; //Update details\n if (placeDetails.reviews && placeDetails.reviews.length > 0) {\n //Use top review as description\n this.desc = placeDetails.reviews.reduce(function (last, cur) {\n if (last.rating < cur.rating) {\n return cur\n } else {\n return last\n }\n }).text;\n } else {\n this.desc = \"No review available.\"\n }\n this.categories = placeDetails.types;\n this.address = placeDetails.formatted_address;\n this.rating = placeDetails.rating;\n this.phone = placeDetails.formatted_phone_number || \"No phone number available.\";\n if (placeDetails.photos) {\n this.imageURL = placeDetails.photos[0].getUrl({\n maxWidth: 500\n });\n }\n this.website = placeDetails.website || \"No website available.\";\n this.url = placeDetails.website || \"javascript:void(0)\";\n this.marker.setMap(null); //Destroy existing marker\n this.createMarker(false);\n this.isLoaded = true;\n } else {\n console.warn(status)\n }\n }.bind(this));\n }\n\n /*\n Create a new marker if one does not exist\n */\n this.createMarker = function (isNew) {\n if (this.isLoaded || this.isDestroyed) return; \n var icon = {\n url: 'img/pin.png',\n size: new google.maps.Size(30, 40),\n origin: new google.maps.Point(0,0),\n anchor: new google.maps.Point(10, 30)\n };\n this.marker = new google.maps.Marker({\n map: map\n , position: new google.maps.LatLng(this.lat, this.lng)\n , title: isNew ? null : this.name\n , icon: icon,\n animation: isNew && markers.length < 20 && map.getZoom() >= 15 ? google.maps.Animation.DROP : null ,\n });\n\n function intToStars(x) {\n var result = \"\";\n for (var i = 0; i < x; i++) {\n result += \"★\"\n }\n return result;\n }\n var imgHTML;\n if (this.imageURL) {\n imgHTML = '<div class=\"img-wrapper\"><img src=\"' + this.imageURL + '\" alt=\"Porcelain Factory of Vista Alegre\"></div>'\n } else {\n imgHTML = \"\";\n }\n this.marker.content = '<div class=\"infoWindowContent\"><h2 class=\"iw-title\">' + this.name + '</h2>' + imgHTML + '<p class=\"iw-rating\">' + intToStars(this.rating) + '</p><p class=\"iw-desc\">' + this.desc + '</p><p class=\"iw-phone\">'+this.address+'</p><p class=\"iw-phone\">' + this.phone + '</p><p class=\"iw-phone\"><a target=\"_blank\" href='+this.url+'>'+this.website+'</a></p></div>';\n markers.push(this.marker);\n\n google.maps.event.addListener(this.marker, 'mouseover', function(){\n this.loadDetails();\n }.bind(this));\n\n google.maps.event.addListener(this.marker, 'click', function(){\n infoWindow.setContent(this.marker.content);\n window.setTimeout(function(){\n infoWindow.open(map, this.marker);\n }.bind(this), 300);\n\n }.bind(this));\n }\n\n this.destroy = function () {\n this.isDestroyed = true;\n this.marker.setMap(null);\n }\n }",
"function callback(results, status) {\n\tif (status == google.maps.places.PlacesServiceStatus.OK) {\n\t\tcreateMapMarkerAndInfoWindow(results);\n\t}\n}",
"function initAutocomplete() {\n const map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: -33.8688, lng: 151.2195 },\n zoom: 13,\n mapTypeId: \"roadmap\",\n });\n // Create the search box and link it to the UI element.\n const input = document.getElementById(\"pac-input\");\n const searchBox = new google.maps.places.SearchBox(input);\n \n map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);\n // Bias the SearchBox results towards current map's viewport.\n map.addListener(\"bounds_changed\", () => {\n searchBox.setBounds(map.getBounds());\n });\n \n let markers = [];\n \n // Listen for the event fired when the user selects a prediction and retrieve\n // more details for that place.\n searchBox.addListener(\"places_changed\", () => {\n const places = searchBox.getPlaces();\n \n if (places.length == 0) {\n return;\n }\n \n // Clear out the old markers.\n markers.forEach((marker) => {\n marker.setMap(null);\n });\n markers = [];\n \n // For each place, get the icon, name and location.\n const bounds = new google.maps.LatLngBounds();\n \n places.forEach((place) => {\n if (!place.geometry || !place.geometry.location) {\n console.log(\"Returned place contains no geometry\");\n return;\n }\n \n const icon = {\n url: place.icon,\n size: new google.maps.Size(71, 71),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(17, 34),\n scaledSize: new google.maps.Size(25, 25),\n };\n \n // Create a marker for each place.\n markers.push(\n new google.maps.Marker({\n map,\n icon,\n title: place.name,\n position: place.geometry.location,\n })\n );\n if (place.geometry.viewport) {\n // Only geocodes have viewport.\n bounds.union(place.geometry.viewport);\n } else {\n bounds.extend(place.geometry.location);\n }\n });\n map.fitBounds(bounds);\n });\n }",
"function getBaiduData(location) {\n jQuery.ajax({\n url: 'https://api.map.baidu.com/place/v2/search',\n type: 'GET',\n dataType: 'jsonp',\n data: {\n // query for only attractions\n 'q': '旅游景点',\n 'scope': '2',\n // sort by raiting\n 'filter': 'sort_name:好评|sort_rule:0',\n 'region': location,\n 'output': 'json',\n // ak = acess key\n 'ak': 'oXmLrK2EjxWxZm1qab51f1fmRLm4I4kF',\n // max page_size is 20\n 'page_size': '20',\n 'page_num': '0'\n }\n })\n .done(function(data, textStatus, jqXHR) {\n //store results in locations array\n locations = data.results;\n //create markers for locations returned by Baidu\n createMarkers(locations);\n })\n .fail(function(jqXHR, textStatus, errorThrown) {\n console.log('HTTP Request Failed');\n alert('Baidu search results could not load properly. Please try again in a few minutes.');\n });\n }",
"function wikidata_user_nearby_city(user_lat, user_lon, fk_wikidata){\n\tvar placeInfoList = null;\n\tvar query_str = `\n\t\t\t\t\tPREFIX wd: <http://www.wikidata.org/entity/>\n\t\t\t\t\tPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n\t\t\t\t\tPREFIX geo: <http://www.opengis.net/ont/geosparql#>\n\t\t\t\t\tPREFIX wikibase: <http://wikiba.se/ontology#>\n\t\t\t\t\tPREFIX wdt: <http://www.wikidata.org/prop/direct/>\n\t\t\t\t\tPREFIX bd: <http://www.bigdata.com/rdf#>\n\n\t\t\t\t\tSELECT distinct ?place ?placeLabel ?distance ?location \n\t\t\t\t\tWHERE {\n\t\t\t\t\t# geospatial queries\n\t\t\t\t\tSERVICE wikibase:around {\n\t\t\t\t\t# get the coordinates of a place\n\t\t\t\t\t?place wdt:P625 ?location .\n\t\t\t\t\t# create a buffer around (-122.4784360859997 37.81826788900048)\n\t\t\t\t\tbd:serviceParam wikibase:center \"Point(` + user_lon.toString()+ ` ` + user_lat.toString()+ `)\"^^geo:wktLiteral .\n\t\t\t\t\t# buffer radius 2km\n\t\t\t\t\tbd:serviceParam wikibase:radius \"10\" .\n\t\t\t\t\tbd:serviceParam wikibase:distance ?distance .\n\t\t\t\t\t}\n\t\t\t\t\t# retrieve the English label\n\t\t\t\t\tSERVICE wikibase:label {bd:serviceParam wikibase:language \"en\". ?place rdfs:label ?placeLabel .}\n\t\t\t\t\t?place wdt:P31 wd:Q515.\n\t\t\t\t\t#?placeFlatType wdt:P279* wd:Q2221906.\n\n\t\t\t\t\t# show results ordered by distance\n\t\t\t\t\t} ORDER BY ?distance\n\t\t\t\t\t\t`;\n\tconsole.log(query_str);\n\n\tconst P_ENDPOINT = \"https://query.wikidata.org/bigdata/namespace/wdq/sparql\";\n\trequest({\n\t\t\tmethod: \"GET\",\n\t\t\turl: P_ENDPOINT,\n\t\t\theaders: {\n\t\t\t\taccept: 'application/sparql-results+json'\n\t\t\t},\n\t\t\tqs: {\n\t\t\t\tquery: query_str\n\t\t\t}\n\t\t}, (e_req, d_res, s_body) => {\n\t\t\tconsole.log(d_res.headers['content-type']);\n\t\t\t// console.log(e_req);\n\t\t\tif(e_req) {\n\t\t\t\tconsole.log(e_req);\n\t\t\t} else {\n\t\t\t\ttry{\n\t\t\t\t\tvar h_json = JSON.parse(s_body);\n\t\t\t\t\tvar a_bindings = h_json.results.bindings;\n\t\t\t\t\tconsole.log(a_bindings);\n\t\t\t\t\tif(a_bindings.length > 0){\n\t\t\t\t\t\tvar sparqlItem = a_bindings[0];\n\t\t\t\t\t\tvar url = sparqlItem[\"place\"][\"value\"];\n\t\t\t\t\t\tvar label = sparqlItem[\"placeLabel\"][\"value\"];\n\t\t\t\t\t\tvar coord = sparqlItem[\"location\"][\"value\"].replace(\"Point(\", \"\").replace(\")\", \"\").split(\" \");\n\t\t\t\t\t\tvar place_lat = parseFloat(coord[1]);\n\t\t\t\t\t\tvar place_lon = parseFloat(coord[0]);\n\n\t\t\t\t\t\tplaceInfoList = {};\n\t\t\t\t\t\tplaceInfoList[url] = {};\n\t\t\t\t\t\tplaceInfoList[url][\"label\"] = label;\n\t\t\t\t\t\tplaceInfoList[url][\"lat\"] = place_lat;\n\t\t\t\t\t\tplaceInfoList[url][\"long\"] = place_lon;\n\t\t\t\t\t\tplaceInfoList[url][\"r\"] = 1000;\n\n\t\t\t\t\t\t\n\t\t\t\t\t}else{\n\t\t\t\t\t\tplaceInfoList = null;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}catch(jsonParseError){\n\t\t\t\t\tconsole.log(jsonParseError);\n\t\t\t\t\t// fk_geo(null);\n\t\t\t\t\tplaceInfoList = null;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\t}\n\t\t\tfk_wikidata(placeInfoList);\n\t \n\t});\n}",
"function geocode (address, api_key, log=false) {\n address = xdmp.urlEncode(address);\n \n // First see if we cached this address already\n let geodata;\n let cache = cts.search(cts.andQuery([cts.collectionQuery(\"geodata\"), cts.jsonPropertyValueQuery('address', address)]));\n if (!fn.empty(cache)) {\n if (log) {console.log('GEOCODE: CACHED RESULT')};\n geodata = fn.head(cache).root.geodata;\n } else {\n // Call the geocoding service and sleep for 1000 ms\n let result = xdmp.httpGet('https://eu1.locationiq.com/v1/search.php?key=' + api_key + '&format=json&q=' + address);\n xdmp.sleep(1000);\n \n result = result.toArray();\n if (result[0].code == '200') {\n // When the HTTP response equals 200, take the result from the service\n if (log) {console.log('GEOCODE: MATCH (' + result[0].code + ' / ' + result[0].message + ')')};\n geodata = result[1].root[0];\n } else {\n // When there is another HTTP response, return an empty result\n if (log) {console.log('GEOCODE: ADDRES NOT FOUND (' + result[0].code + ' / ' + result[0].message + ')')};\n geodata = xdmp.toJSON({});\n }\n \n // Cache the data for future use\n let jsInsert = `\n declareUpdate();\n let geodoc = {\n \"address\": \"` + address + `\",\n \"geodata\": ` + geodata + `\n };\n xdmp.documentInsert(sem.uuidString(), geodoc, {collections: 'geodata'});`\n xdmp.eval(jsInsert, null);\n }\n\n return {\n coordinate: {\n \"lat\": geodata.lat,\n \"lon\": geodata.lon\n },\n \"class\": geodata.class,\n \"type\": geodata.type\n };\n}",
"function getLocationName(lat, long) {\n console.log(lat, long)\n fetch(`https://api.geocod.io/v1.4/reverse?q=${lat},${long}&fields=census2010&api_key=8cccc5825cc2d2dc042d3db2d00b2d5dcd85bcd`)\n .then(response => {\n if (response.ok) {\n return response.json();\n } else console.log(\"That didn't work.\")\n })\n .then(responseJson => grabCensusData(responseJson))\n .catch(err => {\n console.log(err)\n })\n }",
"function displayRestaurantInfo(place) {\n $('#review-window').show();\n $('#add-review-button').show();\n restaurantInfoContainer.show();\n $('#name').text(place.name);\n $('#address').text(place.vicinity);\n $('#telephone').text(place.formatted_phone_number);\n\n var reviewsDiv = $('#reviews');\n var reviewHTML = '';\n reviewsDiv.html(reviewHTML);\n if (place.reviews) {\n if (place.reviews.length > 0) {\n for (var i = 0; i < place.reviews.length; i += 1) {\n var review = place.reviews[i];\n var avatar;\n if (place.reviews[i].profile_photo_url) {\n avatar = place.reviews[i].profile_photo_url;\n } else {\n avatar = 'img/avatar.svg';\n }\n reviewHTML += `<div class=\"restaurant-reviews\">\n <h3 class=\"review-title\">\n <span class=\"user-avatar\" style=\"background-image: url('${avatar}')\"></span>`;\n if (place.rating) {\n reviewHTML += `<span id=\"review-rating\" class=\"rating\">${placeRating(review)}</span>`;\n }\n reviewHTML += ` <h3>${place.reviews[i].author_name}</h3>\n </h3>\n <p> ${place.reviews[i].text} </p>\n </div>`;\n reviewsDiv.html(reviewHTML);\n }\n }\n }\n\n /********** Street view using Google API **********/\n\n /*** Add Street View ***/\n var streetView = new google.maps.StreetViewService();\n streetView.getPanorama({\n location: place.geometry.location,\n radius: 50\n }, processStreetViewData);\n\n var streetViewWindow = $('#street-view-window');\n var photoContainer = $('#photo');\n var photoWindow = $('#see-photo');\n var seeStreetView = $('#see-street-view');\n photoContainer.empty();\n photoContainer.append('<img class=\"place-api-photo\" ' + 'src=\"' + createPhoto(place) + '\"/>');\n\n streetViewWindow.show();\n if (photo) {\n photoWindow.show();\n } else {\n photoWindow.hide();\n }\n\n function processStreetViewData(data, status) {\n if (status === 'OK') {\n var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'));\n panorama.setPano(data.location.pano);\n panorama.setPov({\n heading: 440,\n pitch: 0\n });\n panorama.setVisible(true);\n\n } else {\n photoWindow.hide();\n streetViewWindow.hide();\n photoContainer.show();\n }\n }\n }",
"function createMapMarker(placeData) {\n\n\t\t\tplaceData.forEach(function(place) {\n\t\t\t\t// console.log(place);\n\t\t\t\t// The next lines save location data from the search result object to local variables\n\t\t\t\tvar lat = place.geometry.location.lat(); // latitude from the place service\n\t\t\t\tvar lon = place.geometry.location.lng(); // longitude from the place service\n\t\t\t\tvar name = place.name; // name of the place from the place service\n\t\t\t\tvar bounds = window.mapBounds; // current boundaries of the map window\n\t\t\t\t// marker is an object with additional data about the pin for a single location\n\t\t\t\tplace.marker = new google.maps.Marker({\n\t\t\t\t\tmap: map,\n\t\t\t\t\tposition: place.geometry.location,\n\t\t\t\t\ttitle: name\n\t\t\t\t});\n\t\t\t\t// infoWindows are the little helper windows that open when you click\n\t\t\t\t// or hover over a pin on a map. They usually contain more information\n\t\t\t\t// about a location.\n\t\t\t\tplace.infoWindow = new google.maps.InfoWindow({\n\t\t\t\t\tcontent: name\n\t\t\t\t});\n\t\t\t\t// bounds.extend() takes in a map location object\n\t\t\t\tbounds.extend(new google.maps.LatLng(lat, lon));\n\t\t\t\t// fit the map to the new marker\n\t\t\t\tmap.fitBounds(bounds);\n\t\t\t\t// center the map\n\t\t\t\tmap.setCenter(bounds.getCenter());\n\t\t\t});\n\n\t\t\tplaceData.forEach(function(place) {\n\t\t\t\t// add an info window to the markers\n\t\t\t\tgoogle.maps.event.addListener(place.marker, 'click', function() {\n\t\t\t\t\tconsole.log(placeData);\n\t\t\t\t\tplaceData.forEach(function(plc) {\n\t\t\t\t\t\tplc.infoWindow.close();\n\t\t\t\t\t});\n\t\t\t\t\tplace.infoWindow.open(map, place.marker);\n\t\t\t\t});\n\t\t\t});\n\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts objArray of emotion data into CSV format Input: times = obj array of times, integers emotions = obj array of obj arrays of emotion data, floats ie: [[10.2,11.2,12.2],[10.2,11.2,12.2],[10.2,11.2,12.2]] Output: Str object, CSV format | function convertToCSV(times, emotions, key) {
//log('#logs', "dataArr:"+ itemsFormatted);
var array = typeof emotions != 'object' ? JSON.parse(emotions) : emotions;
var str = '';
//NOTE: Fix: NOT COLLECTING ENGAGEMENT
for (var i = 0; i < emotions.length; i++) {
var line = '';
for (index in emotions[i]) {
//console.log(emotions[i][index]);
if (line != ''){
line += ',';
line += emotions[i][index].toFixed(2);
}
else{
line += times[i].toFixed(0);
line += ',';
line += emotions[i][index].toFixed(2);
}
}
//console.log("line " + i + ": " + line);
str += line + ', ' + key + '\r\n';
}
return str;
} | [
"formatMotionData(obj){\n var orientationX = {label:'orientationX',values:[]},\n orientationY = {label:'orientationY',values:[]},\n orientationZ = {label:'orientationZ',values:[]},\n accelerationX = {label:'accelerationX',values:[]},\n accelerationY = {label:'accelerationY',values:[]},\n accelerationZ = {label:'accelerationZ',values:[]},\n speed = {label:'speed',values:[]},\n distance = {label:'distance',values:[]}, earliestTime, skipsTime, latestTime;\n\n var totals = {\n s:0, d:0\n };\n var curVals = {};\n try{\n var newObj = obj[0];\n if(newObj){\n var previousTime;\n var avg = 0;\n for(let val in newObj){\n if(!isNaN(val)){\n var curVal = newObj[val];\n if(curVal){\n curVals = curVal;\n curVal.hasOwnProperty('speed') && speed.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['speed']}) && !isNaN(curVal['speed']) && (totals.s += curVal['speed']);\n curVal.hasOwnProperty('ox') && orientationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ox']});\n curVal.hasOwnProperty('oy') && orientationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oy']});\n curVal.hasOwnProperty('oz') && orientationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['oz']});\n curVal.hasOwnProperty('ax') && accelerationX.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ax']});\n curVal.hasOwnProperty('ay') && accelerationY.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['ay']});\n curVal.hasOwnProperty('az') && accelerationZ.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['az']});\n curVal.hasOwnProperty('distance') && distance.values.push({\"x\":this.formatTime(parseInt(val,10)), \"y\":curVal['distance']}) && !isNaN(curVal['distance']) && (totals.d += curVal['distance']);\n if(parseInt(val,10) < earliestTime || !earliestTime){\n earliestTime = parseInt(val,10);\n }\n if(parseInt(val,10) > latestTime || !latestTime){\n latestTime = parseInt(val,10);\n }\n if(parseInt(val,10) - previousTime > 10000){\n skipsTime = true;\n }\n previousTime = parseInt(val,10);\n }\n }\n }\n }\n }\n catch(e){\n console.error(e);\n }\n var data = {\n skipsTime:skipsTime,\n acceleration:[accelerationX,accelerationY,accelerationZ],\n speed:[speed],\n distance:[distance],\n orientation:[orientationX,orientationY,orientationZ],\n currentValues:curVals\n };\n data['acceleration'].earliestTime = earliestTime;\n data['acceleration'].latestTime = latestTime;\n data['acceleration'].skipsTime = skipsTime;\n data['speed'].earliestTime = earliestTime;\n data['speed'].latestTime = latestTime;\n data['speed'].skipsTime = skipsTime;\n data['speed'].avg = totals.s ? totals.s / speed.values.length : 0;\n data['distance'].earliestTime = earliestTime;\n data['distance'].latestTime = latestTime;\n data['distance'].skipsTime = skipsTime;\n data['distance'].avg = totals.d ? totals.d / speed.values.length : 0;\n data['orientation'].earliestTime = earliestTime;\n data['orientation'].latestTime = latestTime;\n data['orientation'].skipsTime = skipsTime;\n return data;\n }",
"function csvExportVideoAnalytics(){\n var data_array = [];\n var csv_data;\n firebase.database().ref('users').once(\"value\", function(snapshot){\n let user_array = snapshot.val()\n let data;\n let videoAnalytics;\n\n for(id in user_array){\n for(i in user_array[id]['videoHistory']){\n \n if(user_array[id]['videoHistory'][i]['videoAnalytics'] !== undefined){\n videoAnalytics = user_array[id]['videoHistory'][i]['videoAnalytics']\n \n for(j in videoAnalytics){\n for(k in videoAnalytics[j]){\n data = {\n user_id: user_array[id]['phone'],\n username: user_array[id]['username'],\n phone: user_array[id]['phone'],\n post_id: user_array[id]['videoHistory'][i]['postId'],\n video_watch_date: j,\n video_last_watched_time: k, // timestamp\n video_duration_seconds: videoAnalytics[j][k]['videoDuration'],\n video_current_time_seconds: videoAnalytics[j][k]['videoCurrentTime'],\n video_elapsed_time_seconds: videoAnalytics[j][k]['videoElapsedTime'],\n video_status: videoAnalytics[j][k]['videoStatus'],\n video_percent_done: videoAnalytics[j][k]['videoPercent'],\n video_visible_on_screen: videoAnalytics[j][k]['videoVisible']\n \n } \n }\n\n data_array.push(data)\n }\n \n }\n }\n \n }\n\n }).then(() => {\n csv_data = convertObjectToCSV(data_array); \n }).then(() => {\n csvDownload(csv_data, \"recommender_user_video_analytics\");\n });\n}",
"function createCSV(state, data) {\n let string = stateToCSV(state) + '\\n\\n';\n let keys = Object.keys(data);\n for (let i = 0; i < keys.length; i++) {\n string += keys[i] + ','\n }\n string = string.slice(0, string.length - 1) + '\\n';\n for (let i = 0; i < data[keys[0]].length; i++){\n for (let j = 0; j < keys.length; j++) {\n string += data[keys[j]][i] + ','\n }\n string = string.slice(0, string.length - 1) + '\\n';\n }\n return string\n}",
"function arrayToData(values) {\n\t\t// Are we dealing with multi-dimensional array\n\t\t// If so then we need to convert array to a string, but with a \n\t\t// pipe seperating each array dimension\n\t\tif (typeof values[0] == \"object\") {\n\t\t\tvar r = '';\n\t\t\t// Loop through dimensions\n\t\t\tfor (var i = 0, len = values.length; i < len; i++) {\n\t\t\t\t// If we are onto another dimension then add a pipe character (marks seperation)\n\t\t\t\tif (i > 0) r = r.slice(0, -1) + '|';\n\t\t\t\t// Loop through values of array\n\t\t\t\tfor (var x = 0, ilen = values[i].length; x < ilen; x++) {\n\t\t\t\t\tr+= values[i][x] + ',';\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Return formatted string\n\t\t\treturn r.slice(0, -1);\n\t\t}\n\t\t// Else normal single dimensional array, so just return as is\n\t\telse { \n\t\t\treturn values;\n\t\t}\n\t}",
"function export_instances_to_csv(instances) {\n\n var csv = \"data:text/csv;charset=utf-8,\";\n var header = \"User Name, Email,Condition Type, Conditiong Info\\n\";\n csv += header;\n\n instances.forEach(instance => {\n let condition_type = `\"${JSON.stringify(Object.keys(instance.conditions)).replaceAll('\"', '\"\"')}\"`;\n let condition_info = `\"${JSON.stringify(instance[\"conditions\"]).replaceAll('\"', '\"\"')}\"`;\n csv += `${instance.name},${instance.email},${condition_type},${condition_info}\\n`;\n });\n\n var encodedUri = encodeURI(csv);\n var link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n // create file name with current date and time\n link.setAttribute(\"download\", `student_metrics_${new Date().toLocaleString()}.csv`);\n document.body.appendChild(link); // Required for FF\n link.click(); \n document.body.removeChild(link);\n\n}",
"listToTXT() {\n const { articles } = this.props.articleData\n const articleArray = articles.map((article, i) => {\n const authors = article.authors.join()\n const conferences = article.conferences.join()\n return `${i + 1}: ${article.title}\\nAuthors: ${authors}\\nConferences: ${conferences}\\n`\n })\n const blob = new Blob(articleArray, {\n type: 'text/plain;charset=utf-8'\n })\n FileSaver.saveAs(blob, 'article-list.txt')\n }",
"function exportToCSV(data, type) {\n\tlet csvContent = \"data:text/csv;charset=utf-8,Email,Start,End,Number of Riders,Time,Wait Time,ETA,End Time,Vehicle\\r\\n\";\n\tdata.forEach(function(rowArray) {\n\t\trowArray[0] = rowArray[0].replace(\",\", \".\");\n\t\tcsvContent += rowArray.join(\",\") + \"\\r\\n\";\n\t});\n\tvar encodedUri = encodeURI(csvContent);\n\tvar link = document.createElement(\"a\");\n\tlink.setAttribute(\"href\", encodedUri);\n\tvar date = new Date();\n\tvar dateString = date.getMonth() + \"-\" + date.getDay() + \"-\" + date.getFullYear() + \"_\" + calculateETA(0)\n\tlink.setAttribute(\"download\", type + \"_\" + dateString + \".csv\");\n\tmainDiv.appendChild(link);\n\tlink.click();\n}",
"function csvExportFavouritedVideos(){\n var data_array = [];\n var csv_data;\n firebase.database().ref('users').once(\"value\", function(snapshot){\n let user_array = snapshot.val()\n let data;\n let videoFavourites;\n\n for(id in user_array){\n for(i in user_array[id]['videoFavourite']){\n \n if(user_array[id]['videoFavourite'] !== undefined){\n videoFavourites = user_array[id]['videoFavourite']\n \n data = {\n user_id: user_array[id]['phone'],\n username: user_array[id]['username'],\n phone: user_array[id]['phone'],\n post_id: user_array[id]['videoFavourite'][i]['postId'],\n video_title: user_array[id]['videoFavourite'][i]['videoTitle'],\n video_url: user_array[id]['videoFavourite'][i]['videoUrl'],\n video_interest: user_array[id]['videoFavourite'][i]['interest'],\n post_id: user_array[id]['videoFavourite'][i]['postId']\n\n } \n \n\n data_array.push(data)\n \n \n }\n }\n \n }\n\n }).then(() => {\n csv_data = convertObjectToCSV(data_array); \n }).then(() => {\n csvDownload(csv_data, \"recommender_user_favourited_videos\");\n });\n}",
"function exportCSV() {\n\n if (queryData != null && queryData != \"\") {\n console.log(queryData);\n } else {\n // let user know there is an error\n dialogSpawn(\"Error\",\"Please query data before exporting to a CSV file.\",\"notif\",\"errTitle\",\"filterText\");\n return;\n }\n\n var temp, csvStr = \"\"; // set csvStr to an empty string\n // concat csvStr together to form a string in CSV format\n // values on the same line are separated by commas, values on different lines are separated by newline character\n for (var a=0; a<queryData.length; a++) {\n temp = queryData[a];\n for (var b=0; b<temp.length; b++) {\n if (b < temp.length-1)\n csvStr = csvStr + temp[b] + \",\";\n else\n csvStr = csvStr + temp[b] + \"\\n\";\n }\n }\n\n\n /**\n * References for CSV exporting code:\n * http://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side (Oliver Lloyd's edit reponse)\n * http://stackoverflow.com/questions/17836273/export-javascript-data-to-csv-file-without-server-interaction (adeneo's response)\n **/ \n\n // encode csvStr - escapes certain characters\n var encodedStr = encodeURI(csvStr);\n console.log(encodedStr);\n var downloadLnk = document.createElement(\"a\");\n downloadLnk.setAttribute(\"href\",'data:attachment/csv,'+encodedStr);\n downloadLnk.setAttribute(\"download\",\"awards_data.csv\");\n document.body.appendChild(downloadLnk); \n\n downloadLnk.click();\n}",
"async function getCsv(ctx, next) {\n const events = db.getEvents();\n if (!events) {\n logger.warn('Got no events');\n ctx.body = {};\n } else {\n logger.debug(`Got events ${JSON.stringify(events)}`);\n const eventArr = [];\n Object.keys(events).forEach((id) => {\n eventArr.push(events[id]);\n });\n ctx.set('X-content-type', 'text/csv');\n const csvPromise = new Promise((resolve, reject) => {\n json2csv({data: eventArr}, (err, csv) => {\n if (err) {\n reject(err);\n }\n resolve(csv);\n });\n });\n const csv = await csvPromise;\n logger.info(`${csv}`);\n ctx.body = csv;\n }\n return next();\n}",
"function createBlob() {\n\tblob = [];\n\tfor (let i = 0; i < xValues.length; i++) {\n\t\tblob.push(\"x: \" + String(xValues[i]) + \", y: \" + String(yValues[i]))\n\t}\n\tsaveStrings(blob, 'coodrinateList.txt');\n}",
"function makeExerciseSqlStr(exercisesValuesArr) {\n let finalStr = \"\";\n for (let c in exercisesValuesArr) {\n if (c < exercisesValuesArr.length -1) {\n finalStr = finalStr + makeStr(exercisesValuesArr[c]) + ','}\n else {\n finalStr = finalStr + makeStr(exercisesValuesArr[c])\n }\n }\nreturn finalStr\n}",
"function Csv () {}",
"function generateCSV (analyses) {\n const columns = [\n { title: 'out-unitid', getter (a) { return a.unitid; } },\n { title: 'out-rtype', getter (a) { return a.rtype; } },\n { title: 'out-mime', getter (a) { return a.mime; } },\n { title: 'in-url', getter (a) { return a.url; } }\n ];\n\n // Add a column for each identifier\n analyses.forEach(analysis => {\n if (!analysis.identifiers) { return; }\n\n analysis.identifiers.forEach(id => {\n if (!id.type) { return; }\n if (columns.find(c => c.title === `out-${id.type}`)) { return; }\n\n columns.unshift({\n title: `out-${id.type}`,\n getter (a) {\n if (a.identifiers) {\n const identifier = a.identifiers.find(i => i.type === id.type);\n return identifier && identifier.value;\n }\n }\n });\n });\n });\n\n const header = columns.map(col => escapeCSVstring(col.title)).join(';');\n const lines = analyses.map(analysis => {\n return columns.map(col => escapeCSVstring(col.getter(analysis))).join(';');\n }).join('\\n');\n\n return `${header}\\n${lines}`;\n}",
"function formatData(data) {\n return data.map((el) => {\n return {\n x: new Date(el[0]).toLocaleString().substr(11,9),\n y: el[1].toFixed(2),\n };\n });\n }",
"function _type(data){\n for (i = 0; i < settings.xColumn.length; i++) {\n if (settings.hasTimeX) {\n console.log(data[settings.xColumn[i]]);\n data[settings.xColumn[i]] = (new Date(data[settings.xColumn[i]]).getTime()) / 1000;\n console.log(data[settings.xColumn[i]]);\n // data[settings.xColumn[i]] = (data[settings.xColumn[i]].getTime()) / 1000;\n // console.log(data[settings.xColumn[i]]);\n } else {\n data[settings.xColumn[i]] = +data[settings.xColumn[i]];\n }\n }\n for (i = 0; i < settings.yColumn.length; i++) {\n if (settings.hasTimeY) {\n data[settings.yColumn[i]] = new Date(data[settings.yColumn[i]]);\n } else {\n data[settings.yColumn[i]] = +data[settings.yColumn[i]];\n }\n }\n return data;\n }",
"cellToArray(dt, columns, splitExpr) {\n if (splitExpr === undefined) splitExpr = /\\b\\s+/;\n let j;\n dt.forEach((p) => {\n p = p.data;\n columns.forEach((column) => {\n let list = p[column];\n if (list === null) return;\n if (typeof list === 'number') {\n p[column] = `${list}`;\n return;\n }\n const list2 = list.split(splitExpr);\n list = [];\n // remove empty \"\" records\n for (j = 0; j < list2.length; j++) {\n list2[j] = list2[j].trim();\n if (list2[j] !== '') list.push(list2[j]);\n }\n p[column] = list;\n });\n });\n }",
"function concatValues(obj) {\n\n value = \"\";\n for (var prop in obj) {\n var parts = obj[prop].split(\",\");\n var vals = value.split(\",\");\n var newvals = cartesian(parts, vals);\n\n value = newvals.map(x => concatArr(x)).join(',');\n }\n\n return value;\n}",
"function arrToStr(arr) {\n\t//initialize resulting string\n\tvar res = \"Array[\";\n\t//loop thru array elements\n\tfor( var index = 0; index < arr.length; index++ ){\n\t\tres += (index > 0 ? \", \" : \"\") + objToStr(arr[index]);\n\t}\n\treturn res + \"]\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the user's pointer is close to the edges of either the viewport or the drop list and starts the autoscroll sequence. | _startScrollingIfNecessary(pointerX, pointerY) {
if (this.autoScrollDisabled) {
return;
}
let scrollNode;
let verticalScrollDirection = 0 /* AutoScrollVerticalDirection.NONE */;
let horizontalScrollDirection = 0 /* AutoScrollHorizontalDirection.NONE */;
// Check whether we should start scrolling any of the parent containers.
this._parentPositions.positions.forEach((position, element) => {
// We have special handling for the `document` below. Also this would be
// nicer with a for...of loop, but it requires changing a compiler flag.
if (element === this._document || !position.clientRect || scrollNode) {
return;
}
if (isPointerNearClientRect(position.clientRect, DROP_PROXIMITY_THRESHOLD, pointerX, pointerY)) {
[verticalScrollDirection, horizontalScrollDirection] = getElementScrollDirections(element, position.clientRect, pointerX, pointerY);
if (verticalScrollDirection || horizontalScrollDirection) {
scrollNode = element;
}
}
});
// Otherwise check if we can start scrolling the viewport.
if (!verticalScrollDirection && !horizontalScrollDirection) {
const { width, height } = this._viewportRuler.getViewportSize();
const clientRect = {
width,
height,
top: 0,
right: width,
bottom: height,
left: 0,
};
verticalScrollDirection = getVerticalScrollDirection(clientRect, pointerY);
horizontalScrollDirection = getHorizontalScrollDirection(clientRect, pointerX);
scrollNode = window;
}
if (scrollNode &&
(verticalScrollDirection !== this._verticalScrollDirection ||
horizontalScrollDirection !== this._horizontalScrollDirection ||
scrollNode !== this._scrollNode)) {
this._verticalScrollDirection = verticalScrollDirection;
this._horizontalScrollDirection = horizontalScrollDirection;
this._scrollNode = scrollNode;
if ((verticalScrollDirection || horizontalScrollDirection) && scrollNode) {
this._ngZone.runOutsideAngular(this._startScrollInterval);
}
else {
this._stopScrolling();
}
}
} | [
"startAutoScroll() {\n this.selectNextSibling();\n this.setAutoScroll();\n }",
"scrollToMousePos() {\n let [xMouse, yMouse] = global.get_pointer();\n\n if (xMouse != this.xMouse || yMouse != this.yMouse) {\n this.xMouse = xMouse;\n this.yMouse = yMouse;\n\n let monitorIdx = this._tree.find([xMouse, yMouse]);\n let zoomRegion = this._zoomRegions[monitorIdx];\n let sysMouseOverAny = false;\n if (zoomRegion.scrollToMousePos())\n sysMouseOverAny = true;\n\n if (sysMouseOverAny)\n this.hideSystemCursor();\n else\n this.showSystemCursor();\n }\n return true;\n }",
"scrollToMousePos() {\n this._followingCursor = true;\n if (this._mouseTrackingMode != GDesktopEnums.MagnifierMouseTrackingMode.NONE)\n this._changeROI({ redoCursorTracking: true });\n else\n this._updateMousePosition();\n\n // Determine whether the system mouse pointer is over this zoom region.\n return this._isMouseOverRegion();\n }",
"isInViewport() {\n const vm = this;\n\n if(vm.firstTime) {\n // first time set postion of element outside monitor\n vm.firstTime = false\n return true\n } else {\n return vm.offset + vm.height > vm.scroll &&\n vm.offset < vm.scroll + vm.wheight\n }\n\n }",
"autoScrollOn() {\n const carouselItemsLength = this.carouselItems.length;\n\n if (!this.disableAutoScroll) {\n if (\n this.activeIndexItem === carouselItemsLength - 1 &&\n this.disableAutoRefresh\n ) {\n this.unselectCurrentItem();\n this.selectNewItem(0);\n }\n\n this.autoScrollIcon = PAUSE_ICON;\n this.ariaPressed = FALSE_STRING;\n this.setAutoScroll();\n }\n }",
"handleScroll_() {\n this.resetAutoAdvance_();\n }",
"function setupAutoScroll() {\n $('.header--course-and-subject').append('<div id=\"startScroll\"></div>');\n startScroll = $('#startScroll').offset().top;\n window.addEventListener('scroll', function sidebarScroll() {\n // This value is your scroll distance from the top\n var distanceFromTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;\n var sidebar = document.querySelector('.layout-sidebar__side__inner');\n // stop scrolling, reached upper bound\n if (distanceFromTop < startScroll) {\n sidebar.style.position = 'absolute';\n sidebar.style.top = '';\n } else if (distanceFromTop >= startScroll) {\n // make div follow user\n sidebar.style.position = 'fixed';\n sidebar.style.top = '100px';\n }\n });\n}",
"startTrackingMouse() {\n if (!this._pointerWatch) {\n let interval = 1000 / Clutter.get_default_frame_rate();\n this._pointerWatch = PointerWatcher.getPointerWatcher().addWatch(interval, this.scrollToMousePos.bind(this));\n }\n }",
"function scrollRefraction(){\n simBorder = simSection.getBoundingClientRect();\n simOrigin.y = simBorder.y;\n onScreen = false;\n if(simBorder.top < h && simBorder.bottom > 0)\n onScreen = true;\n}",
"function scroller(){\n this.start_x = null;\n this.end_x = null;\n this.start_offset = null;\n this.scrollable_element = null;\n this.scroller_elemets = null;\n this.x=0;\n this.current_index =0;\n this.fixed_stops = true;\n this.fixed_stop_width = 0;\n this.max_stops = 0;\n this.move_treshold = 0.01;\n this.is_touch = \"ontouchstart\" in window;\n this.tap_treshold = 0;\n this.tap = function(){ };\n this.after_stop = function(index){ };\n\n var me = this;\n\n function isset(v){\n return(typeof v != 'undefined');\n };\n\n function mouse_x(e){\n return (isset(e.targetTouches)) ? e.targetTouches[0].pageX : e.pageX;\n };\n\n this.bind_events = function(){\n if(this.is_touch){\n this.bind_touch_events();\n } else {\n this.bind_click_events();\n }\n };\n\n function start(e){\n e.preventDefault();\n me.start_x = me.end_x = mouse_x(e);\n if($.browser.webkit){\n me.scrollable_element.css(\"-webkit-transition-duration\", \"0s\");\n }\n };\n\n function move(e){\n e.preventDefault();\n if(me.start_x !== null && me.scrollable_element !== null){\n me.end_x = mouse_x(e);\n var val = me.x+(me.end_x-me.start_x);\n if($.browser.webkit){\n me.scrollable_element.css(\"-webkit-transform\", \"translate3d(\"+val +\"px,0px,0px)\");\n } else {\n me.scrollable_element.css({'left':val+'px'});\n }\n }\n };\n\n function end(e){\n e.preventDefault();\n if(me.fixed_stops && me.start_x !== null && me.end_x !== null && me.scrollable_element !== null){\n me.move_to_closest();\n\n /* detect tap */\n var move_x = Math.abs(me.start_x - me.end_x);\n if (move_x <= me.tap_treshold * me.fixed_stop_width) {\n me.tap();\n }\n }\n\n me.start_x = me.end_x = null;\n };\n\n function cancel(e){\n e.preventDefault();\n if(me.fixed_stops && me.start_x !== null && me.end_x !== null && me.scrollable_element !== null){\n me.move_to_closest();\n }\n me.start_x = me.end_x = null;\n };\n\n this.move_to_closest = function (){\n var move_x = this.start_x-this.end_x,\n curr_i = Math.round((-1*this.x) / this.fixed_stop_width),\n new_i = curr_i,\n newloc = this.fixed_stop_width*(curr_i);\n\n if(move_x > this.move_treshold*this.fixed_stop_width && curr_i+1 <= (this.max_stops)){\n new_i = curr_i+1;\n }\n\n if(((-1)*move_x) > this.move_treshold*this.fixed_stop_width && curr_i-1 >= 0){\n new_i = curr_i-1;\n }\n\n newloc = Math.round(this.fixed_stop_width*(new_i));\n this.current_index = new_i;\n this.x = -1*(newloc);\n\n if($.browser.webkit){\n this.scrollable_element.css(\"-webkit-transition-duration\", \"0.5s\");\n this.scrollable_element.css(\"-webkit-transform\", \"translate3d(\"+(-1*newloc) +\"px,0px,0px)\");\n } else {\n this.scrollable_element.stop().animate({'left': (-1*newloc)},800);\n }\n\n this.after_stop(new_i);\n\n };\n\n this.move_to = function(index){\n var newloc = this.fixed_stop_width*(index);\n if($.browser.webkit){\n this.scrollable_element.css(\"-webkit-transition-duration\", \"0.5s\");\n this.scrollable_element.css(\"-webkit-transform\", \"translate3d(\"+(-1*newloc) +\"px,0px,0px)\");\n } else {\n this.scrollable_element.stop().animate({'left': (-1*newloc)},800);\n }\n this.current_index = index;\n this.x = -1*(newloc);\n this.after_stop(index);\n };\n\n this.next = function(){\n if(this.current_index+1 <= this.max_stops){\n this.move_to(this.current_index+1);\n }\n };\n\n this.previous = function(){\n if(this.current_index-1 >= 0){\n this.move_to(this.current_index-1);\n }\n };\n\n /* set image with index to viewport center */\n this.center_to_index = function (v_index){\n var index;\n if (this.scrollable_element !== null){\n if(isset(v_index)){\n this.current_index = v_index;\n index = v_index;\n } else {\n index = this.current_index;\n }\n var loc = -1*((index)*this.fixed_stop_width);\n if($.browser.webkit){\n this.scrollable_element.css({\n \"-webkit-transform\": \"translate3d(\"+loc+\"px,0px,0px)\",\n \"-webkit-transition-duration\": \"0s\"\n });\n } else {\n this.scrollable_element.stop().css('left',loc+'px');\n }\n this.x = loc;\n }\n };\n\n this.bind_touch_events = function(){\n if(this.scroller_elemets !== null){\n this.scroller_elemets.each(function(){\n /* remove old events */\n this.removeEventListener(\"touchstart\", start, false);\n this.removeEventListener(\"touchmove\", move, false);\n this.removeEventListener(\"touchend\", end, false);\n this.removeEventListener(\"touchcancel\", cancel, false);\n\n /* add events */\n this.addEventListener(\"touchstart\", start, false);\n this.addEventListener(\"touchmove\", move, false);\n this.addEventListener(\"touchend\", end, false);\n this.addEventListener(\"touchcancel\", cancel, false);\n });\n }\n };\n\n this.bind_click_events = function(){\n if(this.scroller_elemets !== null){\n /* remove old events */\n this.scroller_elemets.unbind('mousedown')\n .unbind('mousemove')\n .unbind('mouseup');\n\n /* add events */\n this.scroller_elemets.mousedown(start)\n .mousemove(move)\n .mouseup(end);\n }\n };\n\n }",
"function mouseDragged(){\n if(dist(mouseX,mouseY,ball.x,ball.y) <= 1.5*ball.r){\n\tball.drag();\n }\n//use the slider control\n if(dist(mouseX,mouseY,slider.x,slider.y) <= 30){\n \tslider.drag();\n slider.control();\n }\n}",
"function scrollUpViewport(event)\n{\n \tvar viewportHeight = window.innerHeight;\n \tvar heightOffset = window.pageYOffset;\n \tvar yCoord = event.clientY;\n \tvar xCoord = event.clientX;\n \tvar tolerance = 40;\n\n \tif (yCoord + tolerance > viewportHeight)\n \t{\n \t\tvar scrollTarget = yCoord + heightOffset - viewportHeight + tolerance;\n \t\tvar currentScrollPosition = yCoord + heightOffset - viewportHeight;\n \t\twhile (scrollTarget > currentScrollPosition)\n \t\t{\n \t\t\twindow.scrollTo(0, currentScrollPosition);\n \t\t\tcurrentScrollPosition += 2;\n \t\t}\n \t}\n}",
"__patchWheelOverScrolling() {\n this.$.selector.addEventListener('wheel', (e) => {\n const scrolledToTop = this.scrollTop === 0;\n const scrolledToBottom = this.scrollHeight - this.scrollTop - this.clientHeight <= 1;\n if (scrolledToTop && e.deltaY < 0) {\n e.preventDefault();\n } else if (scrolledToBottom && e.deltaY > 0) {\n e.preventDefault();\n }\n });\n }",
"function mapScrollDecide() {\n if (siteIndex == 'vwcc') {\n initMap(),\n scrollToAbout();\n } else {\n setMap(),\n scrollToAbout();\n }\n}",
"_onScrollEvent(actor, event) {\n if (this._settings.get_boolean('disable-scroll') &&\n this._autohideStatus &&\n this._slider.slidex == 0 && // Need to check the slidex for partially showing dock\n (this._dockState == DockState.HIDDEN || this._dockState == DockState.HIDING))\n return Clutter.EVENT_STOP;\n\n let workspaceManager = global.workspace_manager;\n let activeWs = workspaceManager.get_active_workspace();\n let direction;\n switch (event.get_scroll_direction()) {\n case Clutter.ScrollDirection.UP:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.LEFT;\n } else {\n direction = Meta.MotionDirection.UP;\n }\n break;\n case Clutter.ScrollDirection.DOWN:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.RIGHT;\n } else {\n direction = Meta.MotionDirection.DOWN;\n }\n break;\n case Clutter.ScrollDirection.LEFT:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.LEFT;\n }\n break;\n case Clutter.ScrollDirection.RIGHT:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.RIGHT;\n }\n break;\n }\n\n if (direction) {\n if (this._settings.get_boolean('scroll-with-touchpad')) {\n // passingthru67: copied from dash-to-dock\n // Prevent scroll events from triggering too many workspace switches\n // by adding a 250ms deadtime between each scroll event.\n // Usefull on laptops when using a touchpad.\n\n // During the deadtime do nothing\n if(this._scrollWorkspaceSwitchDeadTimeId > 0)\n return false;\n else {\n this._scrollWorkspaceSwitchDeadTimeId =\n GLib.timeout_add(GLib.PRIORITY_DEFAULT, 250, () => {\n this._scrollWorkspaceSwitchDeadTimeId = 0;\n });\n }\n }\n\n let ws = activeWs.get_neighbor(direction);\n\n if (Main.wm._workspaceSwitcherPopup == null) {\n Main.wm._workspaceSwitcherPopup = new WorkspaceSwitcherPopup.WorkspaceSwitcherPopup();\n }\n\n // Set the workspaceSwitcherPopup actor to non reactive,\n // to prevent it from grabbing focus away from the dock\n Main.wm._workspaceSwitcherPopup.reactive = false;\n Main.wm._workspaceSwitcherPopup.connect('destroy', function() {\n Main.wm._workspaceSwitcherPopup = null;\n });\n\n // Do not show wokspaceSwitcher in overview\n if (!Main.overview.visible)\n Main.wm._workspaceSwitcherPopup.display(direction, ws.index());\n\n Main.wm.actionMoveWorkspace(ws);\n }\n\n return Clutter.EVENT_STOP;\n }",
"function onScroll() {\n if (scrollContainer.current.scrollTop < 5) {\n setShowTopIndicator(false)\n }\n else {\n setShowTopIndicator(true)\n }\n if (scrollContainer.current.scrollHeight - scrollContainer.current.scrollTop > scrollContainer.current.clientHeight + 5) {\n setShowBottomIndicator(true)\n }\n else {\n setShowBottomIndicator(false)\n }\n }",
"function showHideHotSpots()\r\n\t\t\t{\r\n\t\t\t\t// When you can't scroll further left\r\n\t\t\t\t// the left scroll hot spot should be hidden\r\n\t\t\t\t// and the right hot spot visible\r\n\t\t\t\tif($mom.find(options.scrollWrapper).scrollLeft() === 0)\r\n\t\t\t\t{\r\n\t\t\t\t\thideLeftHotSpot();\r\n\t\t\t\t\tshowRightHotSpot();\r\n\t\t\t\t}\r\n\t\t\t\t// When you can't scroll further right\r\n\t\t\t\t// the right scroll hot spot should be hidden\r\n\t\t\t\t// and the left hot spot visible\r\n\t\t\t\telse if(($mom.scrollableAreaWidth) <= ($mom.find(options.scrollWrapper).innerWidth() + $mom.find(options.scrollWrapper).scrollLeft()))\r\n\t\t\t\t{\r\n\t\t\t\t\thideRightHotSpot();\r\n\t\t\t\t\tshowLeftHotSpot();\r\n\t\t\t\t}\r\n\t\t\t\t// If you are somewhere in the middle of your\r\n\t\t\t\t// scrolling, both hot spots should be visible\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tshowRightHotSpot();\r\n\t\t\t\t\tshowLeftHotSpot();\r\n\t\t\t\t}\r\n\r\n\t\t\t}",
"function scrolledUpEnough( firstItem, lastItem ) {\n\t\treturn ( firstItem - lastItem ) > 160;\n\t}",
"_carouselScrollOne(Btn) {\r\n let itemSpeed = this.speed;\r\n let translateXval = 0;\r\n let currentSlide = 0;\r\n const touchMove = Math.ceil(this.dexVal / this.itemWidth);\r\n this._setStyle(this.nguItemsContainer.nativeElement, 'transform', '');\r\n if (this.pointIndex === 1) {\r\n return;\r\n }\r\n else if (Btn === 0 && ((!this.loop && !this.isFirst) || this.loop)) {\r\n const currentSlideD = this.currentSlide - this.slideItems;\r\n const MoveSlide = currentSlideD + this.slideItems;\r\n this._btnBoolean(0, 1);\r\n if (this.currentSlide === 0) {\r\n currentSlide = this.dataSource.length - this.items;\r\n itemSpeed = 400;\r\n this._btnBoolean(0, 1);\r\n }\r\n else if (this.slideItems >= MoveSlide) {\r\n currentSlide = translateXval = 0;\r\n this._btnBoolean(1, 0);\r\n }\r\n else {\r\n this._btnBoolean(0, 0);\r\n if (touchMove > this.slideItems) {\r\n currentSlide = this.currentSlide - touchMove;\r\n itemSpeed = 200;\r\n }\r\n else {\r\n currentSlide = this.currentSlide - this.slideItems;\r\n }\r\n }\r\n this._carouselScrollTwo(Btn, currentSlide, itemSpeed);\r\n }\r\n else if (Btn === 1 && ((!this.loop && !this.isLast) || this.loop)) {\r\n if (this.dataSource.length <= this.currentSlide + this.items + this.slideItems &&\r\n !this.isLast) {\r\n currentSlide = this.dataSource.length - this.items;\r\n this._btnBoolean(0, 1);\r\n }\r\n else if (this.isLast) {\r\n currentSlide = translateXval = 0;\r\n itemSpeed = 400;\r\n this._btnBoolean(1, 0);\r\n }\r\n else {\r\n this._btnBoolean(0, 0);\r\n if (touchMove > this.slideItems) {\r\n currentSlide = this.currentSlide + this.slideItems + (touchMove - this.slideItems);\r\n itemSpeed = 200;\r\n }\r\n else {\r\n currentSlide = this.currentSlide + this.slideItems;\r\n }\r\n }\r\n this._carouselScrollTwo(Btn, currentSlide, itemSpeed);\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test : var a = [ [ 0, 2 ], [ 4, 2 ] ]; var b = [ [ 1, 0 ], [ 5, 0 ] ]; console.log(lineLineIntersection(...a, ...b)); var a = [ [ 0, 2 ], [ 4, 2 ] ]; var b = [ [ 1, 0 ], [ 5, 4 ] ]; console.log(lineLineIntersection(...a, ...b)); var a1 = [ 0, 2 ]; var a2 = [ 4, 2 ]; var b1 = [ 1, 0 ]; var b2 = [ 5, 4 ]; console.log(lineLineIntersection(a1, a2, b1, b2)); var a1 = [ 0, 2 ]; var a2 = [ 4, 2 ]; var b1 = [ 4, 0 ]; var b2 = [ 9, 4 ]; console.log(lineLineIntersection(a1, a2, b1, b2)); console.log(lineLineIntersection(a1, a2, b1, b2, false, true)); console.log(lineLineIntersection(a1, a2, b1, b2, true, false)); Segmentsegment intersection | function segmentSegmentIntersection( [ x1, y1 ], [ x2, y2 ], [ x3, y3 ], [ x4, y4 ] ) {
return lineLineIntersection( [ x1, y1 ], [ x2, y2 ], [ x3, y3 ], [ x4, y4 ], true, true);
} | [
"function segmentIntersection(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) {\n var d = (ax2 - ax1) * (by2 - by1) - (ay2 - ay1) * (bx2 - bx1);\n if (d === 0) {\n // The lines are parallel.\n return null;\n }\n var ua = ((bx2 - bx1) * (ay1 - by1) - (ax1 - bx1) * (by2 - by1)) / d;\n var ub = ((ax2 - ax1) * (ay1 - by1) - (ay2 - ay1) * (ax1 - bx1)) / d;\n if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {\n return {\n x: ax1 + ua * (ax2 - ax1),\n y: ay1 + ua * (ay2 - ay1),\n };\n }\n return null; // The intersection point is outside either or both segments.\n}",
"function intersection(pos1, vec1, pos2, vec2){\n //This function is based on this math:\n //https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect\n // pos1 == p\n // vec1 == r\n // pos2 == q\n // vec2 == s\n\n let denom = crossProduct(vec1, vec2); //(r × s)\n let num1 = crossProduct(subVectors(pos2, pos1) , vec2); //(q − p) × s\n let num2 = crossProduct(subVectors(pos2, pos1) , vec1); //(q − p) × r\n\n if(denom == 0) //don't really care if they're parallel for my purposes.\n return null;\n\n let t = num1 / denom;\n let u = num2 / denom;\n\n if(t > 0 && t < 1 && u > 0 && u < 1) {\n let offset = new Vector(vec1.x, vec1.y);\n multVector(offset, t);\n return addVectors(pos1, offset);\n }\n\n return null;\n}",
"function cullIntersections() {\n function toLines(pts) {\n let lns = [];\n for (let i=0, il=pts.length; i<il; i += 2) {\n lns.push({a: pts[i], b: pts[i+1], l: pts[i].distTo2D(pts[i+1])});\n }\n return lns;\n }\n let aOa = [...arguments].filter(t => t);\n if (aOa.length < 1) return;\n let aa = toLines(aOa.shift());\n while (aOa.length) {\n let bb = toLines(aOa.shift());\n loop: for (let i=0, il=aa.length; i<il; i++) {\n let al = aa[i];\n if (al.del) {\n continue;\n }\n for (let j=0, jl=bb.length; j<jl; j++) {\n let bl = bb[j];\n if (bl.del) {\n continue;\n }\n if (base.util.intersect(al.a, al.b, bl.a, bl.b, base.key.SEGINT)) {\n if (al.l < bl.l) {\n bl.del = true;\n } else {\n al.del = true;\n }\n continue;\n }\n }\n }\n aa = aa.filter(l => !l.del).concat(bb.filter(l => !l.del));\n }\n let good = [];\n for (let i=0, il=aa.length; i<il; i++) {\n let al = aa[i];\n good.push(al.a);\n good.push(al.b);\n }\n return good.length > 2 ? good : [];\n}",
"function cubicSegmentIntersections(px1, py1, px2, py2, px3, py3, px4, py4, x1, y1, x2, y2) {\n var e_1, _a;\n var intersections = [];\n // Find line equation coefficients.\n var A = y1 - y2;\n var B = x2 - x1;\n var C = x1 * (y2 - y1) - y1 * (x2 - x1);\n // Find cubic Bezier curve equation coefficients from control points.\n var bx = bezierCoefficients(px1, px2, px3, px4);\n var by = bezierCoefficients(py1, py2, py3, py4);\n var a = A * bx[0] + B * by[0]; // t^3\n var b = A * bx[1] + B * by[1]; // t^2\n var c = A * bx[2] + B * by[2]; // t\n var d = A * bx[3] + B * by[3] + C; // 1\n var roots = cubicRoots(a, b, c, d);\n try {\n // Verify that the roots are within bounds of the linear segment.\n for (var roots_1 = __values$n(roots), roots_1_1 = roots_1.next(); !roots_1_1.done; roots_1_1 = roots_1.next()) {\n var t = roots_1_1.value;\n var tt = t * t;\n var ttt = t * tt;\n // Find the cartesian plane coordinates for the parametric root `t`.\n var x = bx[0] * ttt + bx[1] * tt + bx[2] * t + bx[3];\n var y = by[0] * ttt + by[1] * tt + by[2] * t + by[3];\n // The parametric cubic roots we found are intersection points\n // with an infinite line, and so the x/y coordinates above are as well.\n // Make sure the x/y is also within the bounds of the given segment.\n var s = void 0;\n if (x1 !== x2) {\n s = (x - x1) / (x2 - x1);\n }\n else {\n // the line is vertical\n s = (y - y1) / (y2 - y1);\n }\n if (s >= 0 && s <= 1) {\n intersections.push({ x: x, y: y });\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (roots_1_1 && !roots_1_1.done && (_a = roots_1.return)) _a.call(roots_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return intersections;\n}",
"function segmentIntersecte(a, b, c, d) {\n var d1 = determinant(b.x - a.x, b.y - a.y, c.x - a.x, c.y - a.y);\n var d2 = determinant(b.x - a.x, b.y - a.y, d.x - a.x, d.y - a.y);\n if (d1 > 0 && d2 > 0) return false;\n if (d1 < 0 && d2 < 0) return false;\n d1 = determinant(d.x - c.x, d.y - c.y, a.x - c.x, a.y - c.y);\n d2 = determinant(d.x - c.x, d.y - c.y, b.x - c.x, b.y - c.y);\n if (d1 > 0 && d2 > 0) return false;\n if (d1 < 0 && d2 < 0) return false;\n return true;\n }",
"getIntersection(vectors) {\n if (vectors.length > 1) {\n var isect = vectors.slice(1).reduce((isect, tsls) => arrayutils_1.intersectSortedArrays(isect, tsls), vectors[0]);\n //console.log(JSON.stringify(points), JSON.stringify(isect));\n return isect;\n }\n return vectors[0];\n }",
"function getIntersection(linePointVector, dVector, planePointVector, nVector){\n\t\n\t//calculate the cross product vector of the line vector and the \n\t//plane normal. \n\tvar crossProduct = vector3CrossProduct(dVector, nVector);\n\n\t//calculate the magnitude of that vector\n\tvar magnitude = vector3Magnitude(crossProduct);\n\n\t//If the two are close to parallel, then it is a miss.\n\t//if the are not parallel, it will be a hit and the intersection point\n\t//will be calculated.\n\tvar e = 0.01;\n\n\tif (mag < e){\n\t\treturn null;\n\t} else{\n\t\tvar pMinusL = vector3Subtract(planePointVector, linePointVector);\n\t\tvar u = vector3DotProduct(pMinusL, nVector) / vector3DotProduct(dVector, nVector);\n\n\t\tvar intersect = vector3Add(linePointVector, vector3MultiplyByConst(u, dVector));\n\n\t\treturn intersect;\n\t}\n\n}",
"function getIntersection3D(lineId1, lineId2) {\r\n\tvar inter = {};\r\n\t inter = checkIntersection3D( lineId1, lineId2);\r\n if(inter.x != null && inter.y != null && inter.z !=null) { return inter;}\r\n else{console.log(\" no Intersection found\"); return null;}\r\n}",
"function rayXline(rx, ry, dx, dy, x1, y1, x2, y2, infinite){\n\t\n\tvar lx, ly, d, nx, ny, a, b;\n\tlx = x2 - x1;\n\tly = y2 - y1;\n\td = Math.sqrt(lx * lx + ly * ly);\n\tnx = ly / d;\n\tny = -lx / d;\n\t\n\ta = dx * nx + dy * ny;\n\tb = (x1 - rx) * nx + ( y1 - ry ) * ny;\n\n\tif( a != 0 && ( a > 0 ^ b < 0 ) ){//Check if there is an intersection with the inifinite line\n\t\n\t\tl = b / a;\n\t\tif( infinite )\n\t\t\treturn l;\n\t\telse {\n\t\t\tvar xx = rx + dx * l;\n\t\t\tvar yy = ry + dy * l;\n\t\t\tvar g = ((xx - x1) * lx + (yy - y1) * ly) / (lx * lx + ly * ly);\n\t\t\tif( g >= 0 && g <= 1)\n\t\t\t\treturn l;\n\t\t\telse return null;\n\t\t\t\n\t\t}\n\t} else return null;\n}",
"function formatIntersectingSegment(x, y, i, j, xx, yy) {\n if (xx[i] == x && yy[i] == y) {\n return [i, i];\n }\n if (xx[j] == x && yy[j] == y) {\n return [j, j];\n }\n return i < j ? [i, j] : [j, i];\n}",
"function intersect_segment_triangle (P0, P1, V0, V1, V2) {\n\tvar SMALL_NUM = 0.00000001\n\tvar u = subtract(V1, V0);\n\tvar v = subtract(V2, V0);\n\tvar n3 = cross( vec3(u[0], u[1], u[2]), vec3(v[0], v[1], v[2]));\n\tvar n = vec4(n3[0], n3[1], n3[2], 0);\n\tvar dir = subtract(P1, P0);\n\tvar w0 = subtract(P0, V0);\n\tvar a = -dot(n, w0);\n\tvar b = dot(n, dir);\n\tif (Math.abs(b) < SMALL_NUM)\t\t// Segment is parallel to the plane\n\t\treturn false;\n\tvar r = a / b;\n\tif (r < 0.0 || r > 1.0)\n\t\treturn false;\n\tvar I = add(P0, scale1(r, dir));\t// Intersection point of the segment and the plane\n\t// Is I inside the triangle?\n\tvar uu = dot(u, u);\n\tvar uv = dot(u, v);\n\tvar vv = dot(v, v);\n\tvar w = subtract(I, V0);\n\tvar wu = dot(w, u);\n\tvar wv = dot(w, v);\n\tvar D = uv * uv - uu * vv;\n\t// get and test parametric coordinates\n\tvar s = (uv * wv - vv * wu) / D;\n\tif (s < 0.0 || s > 1.0)\n\t\treturn false;\n\tvar t = (uv * wu - uu * wv) / D;\n\tif (t < 0.0 || (s + t) > 1.0)\n\t\treturn false;\n\treturn true;\n}",
"function lineIntersectCircle(pointa, pointb, center, radius) {\n var result = {};\n var a = (pointb.x - pointa.x) * (pointb.x - pointa.x) + (pointb.y - pointa.y) * (pointb.y - pointa.y);\n var b = 2 * ((pointb.x - pointa.x) * (pointa.x - center.x) + (pointb.y - pointa.y) * (pointa.y - center.y));\n var cc = center.x * center.x + center.y * center.y + pointa.x * pointa.x + pointa.y * pointa.y -\n 2 * (center.x * pointa.x + center.y * pointa.y) - radius * radius;\n var deter = b * b - 4 * a * cc;\n\n function interpolate(p1, p2, d) {\n return {\n x: p1.x + (p2.x - p1.x) * d,\n y: p1.y + (p2.y - p1.y) * d\n };\n }\n if (deter <= 0) {\n result.inside = false;\n } else {\n var e = Math.sqrt(deter);\n var u1 = (-b + e) / (2 * a);\n var u2 = (-b - e) / (2 * a);\n if ((u1 < 0 || u1 > 1) && (u2 < 0 || u2 > 1)) {\n if ((u1 < 0 && u2 < 0) || (u1 > 1 && u2 > 1)) {\n result.inside = false;\n } else {\n result.inside = true;\n }\n } else {\n if (0 <= u2 && u2 <= 1) {\n result.enter = interpolate(pointa, pointb, u2);\n }\n if (0 <= u1 && u1 <= 1) {\n result.exit = interpolate(pointa, pointb, u1);\n }\n result.intersects = true;\n }\n }\n return result;\n }",
"function LineSegment2D (\n _lineSegmentBatch,\n _screenPosition1,\n _screenPosition2,\n _screenThickness,\n _color,\n _vertexPositions, // which is a [], not a Float32Array.\n _vertexColors // which is a [], not a Float32Array.\n){\n // 1. Vertex positions.\n LineSegment2D.createVertexPositions (\n // Part 1.\n _vertexPositions,\n // Part 2.\n _screenPosition1, _screenPosition2, _screenThickness\n );\n \n // 2. Vertex colors.\n LineSegment2D.createVertexColors(_vertexColors, _color);\n\n // Note:\n // Let LineSegment2DBatch get indices using LineSegment2D.INDICES directly.\n /*\n // 3. Indices.\n this.indices = LineSegment2D.INDICES;\n */\n}",
"function lineDividing(x1, y1, x2, y2, a, b) {\n\tp1 = (b * x1 + a * x2) / (a + b);\n\tp2 = (b * y1 + a * y2) / (a + b);\n\treturn { p1, p2 };\n}",
"breshnamDrawLine (point0, point1) {\n let x0 = point0.x >> 0;\n let y0 = point0.y >> 0;\n let x1 = point1.x >> 0;\n let y1 = point1.y >> 0;\n let dx = Math.abs(x1 - x0);\n let dy = Math.abs(y1 - y0);\n let color = new BABYLON.Color4(1,1,0,1);\n\n if(dy > dx){\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dx - dy;\n\n for(let y=y0; y!=y1; y=y+sy){\n this.drawPoint(new BABYLON.Vector2(x0, y), color);\n if(err >= 0) {\n x0 += sx ;\n err -= dy;\n }\n err += dx;\n }\n }\n else{\n let sx = (x0 < x1) ? 1 : -1;\n let sy = (y0 < y1) ? 1 : -1;\n let err = dy - dx;\n\n for(let x=x0; x!=x1; x=x+sx){\n this.drawPoint(new BABYLON.Vector2(x, y0), color);\n if(err >= 0) {\n y0 += sy ;\n err -= dx;\n }\n err += dy;\n }\n }\n }",
"function LineSeg(begin, end) {\n\t\tObject.defineProperties(this, {\n\t\t\tbegin: { value: begin, enumerable: true },\n\t\t\tend: { value: end, enumerable: true }\n\t\t});\n\t}",
"function intersect_primitive_primitive (buffer1, buffer2) {\n\tfor (var i = 0; i < buffer1.length; i += 3)\n\t{\n\t\tfor (var j = 0; j < buffer2.length; j += 3)\n\t\t{\n\t\t\tif ( intersect_triangle_triangle(buffer1[i], buffer1[i+1], buffer1[i+2], buffer2[j], buffer2[j+1], buffer2[j+2]) )\n\t\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"function linePlaneIntersection(p, q, n, c) {\n var v = [q.x - p.x, q.y - p.y, q.z - p.z]\n var w = [c.x - p.x, c.y - p.y, c.z - p.z]\n var t = (n[0]*w[0] + n[1]*w[1] + n[2]*w[2]) /\n (n[0]*v[0] + n[1]*v[1] + n[2]*v[2])\n if (t < 0 || t > 1)\n return null\n return {x: p.x + t*v[0], y: p.y + t*v[1], z: p.z + t*v[2]}\n}",
"function drawLineSegment(x1, y1, x2, y2, color, width) {\n if (color == undefined) color = colors[0];\n if (width == undefined) width = LINE_WIDTH;\n\n\tif(x1 != NaN && y1 != NaN && x1 != NaN && y2 != NaN && math.abs(y2-y1) < 10)\n\t{\n\t\tx1 = transformX(x1);\n\t\ty1 = transformY(y1);\n\t\tx2 = transformX(x2);\n\t\ty2 = transformY(y2);\n\n\t\tcontext.beginPath();\n\t\tcontext.moveTo(x1, y1);\n\t\tcontext.lineTo(x2, y2);\n\n\t\tcontext.strokeStyle = color;\n\t\tcontext.lineWidth = width;\n\t\tcontext.stroke();\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to sort two array by their sort field, which is an array of comparable things (numbers or strings) starting with the most signficant. | function arraySorter(a, b) {
var retval = _.chain(_.zip(a.sort, b.sort)).map(function (x) {
var aval = x[0];
var bval = x[1];
if (aval === null || bval === null) {
return 0;
} else if (typeof(aval) === "number") {
return aval - bval;
} else {
return aval.localeCompare(bval);
};
}).find(function(n) { return n !== 0; }).value();
if (retval === undefined) {
/* all the same, return 0 */
return 0;
} else {
return retval;
}
} | [
"function sortStock(a, b) {\n if (parseInt(a[0]) > parseInt(b[0])) return 1;\n else return -1;\n}",
"function sortArrays(x, y)\n{\n\tfor (let xInd = 0; xInd < x.length; xInd++)\n\t{\n\t\tif (x[xInd] > y[0])\tswap(x, xInd, y)\n\t\ty.sort((left, right) => {\n\t\t\tif (left < right) return -1\n\t\t\telse if (left > right) return 1\n\t\t\telse return 0\n\t\t})\n\t}\n}",
"function sortByFundingSourceType(a, b) {\n\tvar cnt = 0, tem;\n\ta = String(a.description).toLowerCase();\n\tb = String(b.description).toLowerCase();\n\tif (a === b) {\n\t\treturn 0;\n\t}\n\tif (/\\d/.test(a) || /\\d/.test(b)) {\n\t\tvar Rx = /^\\d+(\\.\\d+)?/;\n\t\twhile (a.charAt(cnt) === b.charAt(cnt) && !Rx.test(a.substring(cnt))) {\n\t\t\tcnt++;\n\t\t}\n\t\ta = a.substring(cnt);\n\t\tb = b.substring(cnt);\n\t\tif (Rx.test(a) || Rx.test(b)) {\n\t\t\tif (!Rx.test(a)) {\n\t\t\t\treturn a ? 1 : -1;\n\t\t\t}\n\t\t\tif (!Rx.test(b)) {\n\t\t\t\treturn b ? -1 : 1;\n\t\t\t}\n\t\t\ttem = parseFloat(a) - parseFloat(b);\n\t\t\tif (tem != 0) {\n\t\t\t\treturn tem;\n\t\t\t}\n\t\t\ta = a.replace(Rx, '');\n\t\t\tb = b.replace(Rx, '');\n\t\t\tif (/\\d/.test(a) || /\\d/.test(b)) {\n\t\t\t\treturn a1Sort(a, b);\n\t\t\t}\n\t\t}\n\t}\n\tif (a === b) {\n\t\treturn 0;\n\t}\n\treturn a > b ? 1 : -1;\n}",
"function combine(arr1, arr2){\n return arr1.concat(arr2).sort()\n}",
"function sortOn(arr) {\n var comparators = [];\n for (var i=1; i<arguments.length; i+=2) {\n comparators.push(getKeyComparator(arguments[i], arguments[i+1]));\n }\n arr.sort(function(a, b) {\n var cmp = 0,\n i = 0,\n n = comparators.length;\n while (i < n && cmp === 0) {\n cmp = comparators[i](a, b);\n i++;\n }\n return cmp;\n });\n return arr;\n}",
"function sortNumbersAscending(a,b) {\n\treturn a - b;\n}",
"function sortPacks(a, b) {\n if (a.packSize > b.packSize) {\n return b;\n } else {\n return (b.packSize < a.packSize) ? -1 : 1;\n }\n}",
"function scoreSort(a, b){\n return b.score-a.score;\n}",
"function awardSortFunc(a, b){\n\t// Match\n\tif (a.name == b.name)\n\t\treturn 0;\n\t// Non-match\n\telse\n\t\treturn (a.name > b.name ? 1 : -1);\n}",
"function sortByIdentifiersCount(a, b) {\n if (a.count === b.count) {\n return stringCompare(a, b)\n }\n\n return b.count - a.count\n}",
"function sort_by_largest_numerical_suffix (a, b) {\n let suffix_a = a.match(suffix_number_regex);\n let suffix_b = b.match(suffix_number_regex);\n // If no number is detected (eg: preview version like android-R),\n // designate a suffix of 0 so it gets moved to the end\n suffix_a = suffix_a || ['0', '0'];\n suffix_b = suffix_b || ['0', '0'];\n // Return < zero, or > zero, based on which suffix is larger.\n return (parseInt(suffix_a[1]) > parseInt(suffix_b[1]) ? -1 : 1);\n}",
"function extensionCmp(a, b) {\n const aSortBucket = (a.isBuiltin ? 0 /* Builtin */ : a.isUnderDevelopment ? 2 /* Dev */ : 1 /* User */);\n const bSortBucket = (b.isBuiltin ? 0 /* Builtin */ : b.isUnderDevelopment ? 2 /* Dev */ : 1 /* User */);\n if (aSortBucket !== bSortBucket) {\n return aSortBucket - bSortBucket;\n }\n const aLastSegment = path.posix.basename(a.extensionLocation.path);\n const bLastSegment = path.posix.basename(b.extensionLocation.path);\n if (aLastSegment < bLastSegment) {\n return -1;\n }\n if (aLastSegment > bLastSegment) {\n return 1;\n }\n return 0;\n }",
"function sortPageObjArrayByButtonOrder (a, b)\n{\n\tvar agBOrder = a.pageObjArray[a.pageList[1]][gBUTTON_ORDER];\n\tvar bgBOrder = b.pageObjArray[b.pageList[1]][gBUTTON_ORDER];\n\tif (agBOrder == bgBOrder)\n\t\treturn 0;\n\telse if (bgBOrder < 0)\n\t\treturn -1;\n\telse if (agBOrder < 0)\n\t\treturn 1;\n\t\n\treturn (agBOrder - bgBOrder);\n}",
"function naturalSort(a, b) {\n var re = /(^-?[0-9]+(\\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,\n sre = /(^[ ]*|[ ]*$)/g,\n dre = /(^([\\w ]+,?[\\w ]+)?[\\w ]+,?[\\w ]+\\d+:\\d+(:\\d+)?[\\w ]?|^\\d{1,4}[\\/\\-]\\d{1,4}[\\/\\-]\\d{1,4}|^\\w+, \\w+ \\d+, \\d{4})/,\n hre = /^0x[0-9a-f]+$/i,\n ore = /^0/,\n // convert all to strings and trim()\n x = a.toString().replace(sre, '') || '',\n y = b.toString().replace(sre, '') || '',\n // chunk/tokenize\n xN = x.replace(re, '\\0$1\\0').replace(/\\0$/,'').replace(/^\\0/,'').split('\\0'),\n yN = y.replace(re, '\\0$1\\0').replace(/\\0$/,'').replace(/^\\0/,'').split('\\0'),\n // numeric, hex or date detection\n xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),\n yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null;\n // first try and sort Hex codes or Dates\n if (yD) {\n if ( xD < yD ) {\n return -1;\n } else if ( xD > yD ) {\n return 1;\n }\n }\n // natural sorting through split numeric strings and default strings\n for (var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {\n // find floats not starting with '0', string or 0 if not defined (Clint Priest)\n oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;\n oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;\n // handle numeric vs string comparison - number < string - (Kyle Adams)\n if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {\n return (isNaN(oFxNcL)) ? 1 : -1;\n // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'\n } else if (typeof oFxNcL !== typeof oFyNcL) {\n oFxNcL += '';\n oFyNcL += '';\n }\n if (oFxNcL < oFyNcL) {\n return -1;\n }\n if (oFxNcL > oFyNcL) {\n return 1;\n }\n }\n return 0;\n}",
"function SORT(ref) {\n for (var _len13 = arguments.length, criteria = Array(_len13 > 1 ? _len13 - 1 : 0), _key13 = 1; _key13 < _len13; _key13++) {\n criteria[_key13 - 1] = arguments[_key13];\n }\n\n // reduce the criteria array into a function\n var makeComparer = function makeComparer() {\n return function (a, b) {\n var result = 0;\n for (var i = 0; i < criteria.length; i + 2) {\n var field = typeof criteria[i] === 'string' ? criteria[i] : criteria[i] - 1,\n order = criteria[i + 1];\n\n if (a[field] < b[field]) {\n return order ? -1 : 1;\n } else {\n return order ? 1 : -1;\n }\n }\n\n return result;\n };\n };\n\n if (ISREF(ref) || Array.isArray(ref)) {\n return ref.sort(makeComparer());\n }\n\n return error$2.na;\n}",
"function checksumCompare(a, b){\r\n if (a.score == b.score){ // if scores tied sort by character\r\n return Object.compare(a.char, b.char);\r\n }\r\n\r\n // comparison to sort count / char by score first\r\n return Object.compare(b.score, a.score);\r\n}",
"function qsort(arry, left, right)\n{\n\tif(left < right) \n\t{\n\t\tvar part = __qsort_split(arry, left, right);\n\t\tqsort(arry, left, part-1);\n\t\tqsort(arry, part+1, right);\n\t}\n}",
"function _ascendingCompare(first, second) {\n return first.position - second.position;\n }",
"function compauthor(a, b) {\n return a.author > b.author;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
keycode_to_midinote() it turns a keycode to a MIDI note based on this reference layout: 1 2 3 4 5 6 7 8 9 0 = Q W E R T Y U I O P [ ] A S D F G H J K L ; ' \ Z X C V B N M , . | function keycode_to_midinote(keycode) {
// get row/col vals from the keymap
var key = synth.keymap[keycode];
if ( isNil(key) ) {
// return false if there is no note assigned to this key
return false;
} else {
var [row, col] = key;
return (row * synth.isomorphicMapping.vertical) + (col * synth.isomorphicMapping.horizontal) + tuning_table['base_midi_note'];
}
} | [
"function keyToNote(key)\n{\n var l = key.length-1;\n var rawKey = key.substr(0, l);\n var octave = parseInt(key[l]);\n return (octave*12)+keyNoteMap[rawKey];\n}",
"function playNote(keycode) {\n //dont trigger if key is already pressed\n if (!keysPressed.includes(keycode)) {\n //push keycode to pressed\n keysPressed.push(keycode);\n //get respective key from keycode\n var key = document.querySelector(\".key[data-keycode=\\\"\" + keycode + \"\\\"]\");\n //add playing transform to respective note\n key.classList.add(\"playing\");\n //play note\n poly.triggerAttack(key.dataset.note + key.dataset.octave);\n //display note/chord being played\n document.querySelector(\".currentNote\").innerHTML = getChord();\n return key.dataset.note + key.dataset.octave;\n }\n}",
"function getNoteName (midi) { \n const noteNames = [ \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\", \"A\", \"Bb\", \"B\" ];\n const index = midi % 12;\n const octave = Math.floor(midi / 12) - 1;\n return \"\" + noteNames[index] + octave;\n}",
"function midiMessageHandler(m) {\n\twindow.dispatchEvent(new CustomEvent('piano', {detail:{data: m.data, source: \"midi\"}}));\n}",
"function MidiToInt(message) {\r\n return (message[0] << 16) + (message[1] << 8) + message[2];\r\n}",
"saveMIDI(filename) {\n\t\t\tvar buffer = new Buffer(this.buildFile());\n\t\t\tfs.writeFile(filename + '.mid', buffer, function (err) {\n\t\t\t\tif(err) return console.log(err);\n\t\t\t});\n\t\t}",
"notesNotation() {\r\n let actual = this.octaveGenerator();\r\n let notes = [];\r\n\r\n for (let i = 0; i < actual.length; i++) {\r\n if (actual[i].indexOf(\"#\") !== -1 || actual[i].indexOf(\"b\") !== -1) {\r\n notes.push(new VF.StaveNote({ clef: \"treble\", keys: [actual[i]], duration: \"w\" }).addAccidental(0, new VF.Accidental(actual[i][1]))); //index1 is always an accidantal in this case\r\n }\r\n else if (actual[i].indexOf(\"#\") === -1 || actual[i].indexOf(\"b\") === -1) {\r\n notes.push(new VF.StaveNote({ clef: \"treble\", keys: [actual[i]], duration: \"w\" }));\r\n\r\n }\r\n }\r\n\r\n for (let i = 0; i < notes.length - 1; i++) {\r\n //Checks if there is appearence of \"natural - accidental\" \r\n if (notes[i].keys[0][0] === notes[i + 1].keys[0][0] && this.keySigns.lastIndexOf(\"B\") === -1) {\r\n\r\n notes[i + 1] = notes[i + 1].addAccidental(0, new VF.Accidental(\"n\"));\r\n }\r\n else if (notes[i].keys[0][0] === notes[i + 1].keys[0][0] && notes[0].keys[0][0] === notes[notes.length - 1].keys[0][0]) {\r\n notes[notes.length - 1] = notes[notes.length - 1].addAccidental(0, new VF.Accidental(\"n\"));\r\n break;\r\n }\r\n\r\n }\r\n\r\n return notes;\r\n }",
"function IntToMidi(x) {\r\n\tvar message = [0, 0, 0];\r\n\tmessage[0] = (x >> 16) & 255;\r\n\tmessage[1] = (x >> 8) & 255;\r\n\tmessage[2] = (x) & 255;\r\n\treturn message;\r\n}",
"function intToNote(k) {\n var l1 = [];\n if (k.length === 0) {\n return l1;\n } else {\n var x = k[0];\n for (var i = 0; i < k.length; i++) {\n var r = new Note(k[i] - x + 1, false);\n l1.push(r);\n }\n return l1;\n }\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;\n \n function readEvent(stream) {\n var event = {};\n event.deltaTime = stream.readVarInt();\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.readVarInt();\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 = (\n (stream.readInt8() << 16)\n + (stream.readInt8() << 8)\n + stream.readInt8()\n )\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, 0x20: 25, 0x40: 29, 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.readVarInt();\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf7) {\n event.type = 'dividedSysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else {\n throw \"Unrecognised MIDI event type byte: \" + eventTypeByte;\n }\n } else {\n /* channel event */\n var param1;\n if ((eventTypeByte & 0x80) == 0) {\n /* running status - reuse lastEventTypeByte as the event type.\n eventTypeByte 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 stream = 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 = 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 } else {\n ticksPerBeat = timeDivision;\n }\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 = 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}",
"snapshotToNote (snapshot) {\n // we will need the key often, so we always want to have the key included in the note\n let key = snapshot.key()\n let note = snapshot.val()\n note.key = key\n return note\n }",
"initMidi() {\n this.midi = new WebMIDIInterface({_outputSelector:\n this.midiOutputSelector});\n this.midi.init();\n }",
"function octaveUp() {\n //remove all playing notes\n for (var i = 0, len = keysPressed.length; i < len; i++) {\n stopNote(keysPressed[0]);\n }\n\n //get all keys in the html\n var keys = document.querySelectorAll(\".key\")\n //increment their octave up\n keys.forEach(key => key.dataset.octave = String(parseInt(key.dataset.octave) + 1))\n}",
"function octaveDown() {\n //remove all playing notes\n for (var i = 0, len = keysPressed.length; i < len; i++) {\n stopNote(keysPressed[0]);\n }\n\n //get all keys in the html\n var keys = document.querySelectorAll(\".key\");\n //increment their octave up\n keys.forEach(key => key.dataset.octave = String(parseInt(key.dataset.octave) - 1));\n}",
"generateKeyboard(elementId, pianoType=Piano2.PIANO_TYPE_NEW, includeLabels=false) {\r\n \r\n this.out(\"Generating Keyboard_\" + pianoType + \" in \" + elementId);\r\n var wrap = document.getElementById(elementId);\r\n if (null == wrap)\r\n throw new Error(\"ERROR: Invalid Element '\"+elementId+\"' in generateKeyboard()\");\r\n var wrap2 = document.createElement(\"div\");\r\n wrap2.classList.add(\"piano\");\r\n \r\n var divs = [];\r\n var xOffset = -0.5; //For X-axis offset in display (as CSS var(--xOffset))\r\n for (var i = 0; i < Piano2.MAX_KEYS; ++i) {\r\n var randomId = Math.floor(Math.random() * 9999999); //Give it 1 of 10M unique IDs\r\n randomId = \"__p2__key_\" + randomId;\r\n xOffset += 0.5; //Move over 1-half key each time\r\n var note1 = Piano2.HALF_STEPS[0][i % Piano2.NUM_HALF_STEPS]; //Note Name for Classic Piano\r\n var note2 = Piano2.HALF_STEPS[1][i % Piano2.NUM_HALF_STEPS]; //Note Name for Piano 2.0\r\n\r\n //Create a Div Representing a Piano Key\r\n divs.push(document.createElement(\"div\"));\r\n divs[i].id = randomId;\r\n divs[i].classList.add(\"key\", \"white\", \"freq\" + i); //\"black\" may replace \"white\"\r\n divs[i].dataset.freq = i;\r\n \r\n var label = document.createElement(\"div\");\r\n label.classList.add(\"keyLabel\");\r\n label.innerHTML = note1;\r\n divs[i].appendChild(label);\r\n\r\n //Black Key Handling\r\n if (pianoType == Piano2.PIANO_TYPE_NEW) { //for Piano 2.0\r\n label.innerHTML = note2;\r\n divs[i].title = note2 + \" (Classically \" + note1 + \")\";\r\n if (i % 2 == 1) { //Odd keys are always Black in 2.0\r\n divs[i].classList.replace(\"white\", \"black\");\r\n if (i in Piano2.BLACK_KEYS_CENTERED)\r\n divs[i].classList.add(\"blackCenter\");\r\n else if (i in Piano2.BLACK_KEYS_LONG)\r\n divs[i].classList.add(\"blackBig\");\r\n else\r\n divs[i].classList.add(\"blackLighter\");\r\n }\r\n } else { //For Classic style piano (1.0)\r\n if (i in Piano2.BLACK_KEYS_CLASSIC) {\r\n divs[i].classList.replace(\"white\", \"black\");\r\n divs[i].title = note1;\r\n }\r\n }\r\n\r\n //Handle 2 whites in a row (more xOffset needed)\r\n if (i > 0 && divs[i].classList.contains(\"white\") && divs[i - 1].classList.contains(\"white\"))\r\n xOffset += 0.5; //Extra half position\r\n divs[i].style.setProperty(\"--xOffset\", xOffset);\r\n \r\n //Make Clickable Note (with Kludge to keep \"this\" context in p2)\r\n var p2 = this;\r\n divs[i].onclick = function() { p2.handleKeyClick(event, p2); };\r\n wrap2.appendChild(divs[i]);\r\n }\r\n\r\n wrap.appendChild(wrap2);\r\n }",
"function getIndexedEventNote(event) {\n\n if (!event.indexedNote && event.note && event.note.length) {\n var note = enyo.string.escapeHtml(event.note);\t// Let's escape prior to doing anything, regardless of length.\n//\t\t\tvar note = enyo.string.removeHtml(event.note);\t// removeHTML now uses a regex and also escapes the html.\n\n event.note.length < MAX_INDEXABLE_SIZE && (note = enyo.string.runTextIndexer(note)); // If we can, index the note.\n\n note = note.replace(/\\n/g, \"<br />\");\t\t\t// Finally, do the replace for breaks.\n\n event.indexedNote = note;\t\t\t\t\t\t// Save the indexed note on the event.\n }\n\n return event.indexedNote || \"\";\t// Return the best match.\n }",
"pulse_midi_clock() {\n this.midi_clock.send([0xf8]);\n }",
"function setupMIDI() {\n\tnavigator.requestMIDIAccess().then(\n\t\tfunction (m) {\n\t\t\tconsole.log(\"Initializing MIDI\");\n\t\t\tm.inputs.forEach(function (entry) { // for all the midi device set the message handler as midiMessageHandler\n\t\t\t\tconsole.log(entry.name + \" detected\");\n\t\t\t\tentry.onmidimessage = midiMessageHandler;\n\t\t\t});\n\t\t\tSynth.setSampleRate(4000); // set the quality of the synthesized audio\n\t\t},\n\t\tfunction (err) {\n\t\t\tconsole.log('An error occured while trying to init midi: ' + err);\n\t\t}\n\t);\n}",
"function keysig(keyname) {\n if (!keyname) { return {}; }\n var kkey, sigcodes = {\n // Major\n 'c#':7, 'f#':6, 'b':5, 'e':4, 'a':3, 'd':2, 'g':1, 'c':0,\n 'f':-1, 'bb':-2, 'eb':-3, 'ab':-4, 'db':-5, 'gb':-6, 'cb':-7,\n // Minor\n 'a#m':7, 'd#m':6, 'g#m':5, 'c#m':4, 'f#m':3, 'bm':2, 'em':1, 'am':0,\n 'dm':-1, 'gm':-2, 'cm':-3, 'fm':-4, 'bbm':-5, 'ebm':-6, 'abm':-7,\n // Mixolydian\n 'g#mix':7, 'c#mix':6, 'f#mix':5, 'bmix':4, 'emix':3,\n 'amix':2, 'dmix':1, 'gmix':0, 'cmix':-1, 'fmix':-2,\n 'bbmix':-3, 'ebmix':-4, 'abmix':-5, 'dbmix':-6, 'gbmix':-7,\n // Dorian\n 'd#dor':7, 'g#dor':6, 'c#dor':5, 'f#dor':4, 'bdor':3,\n 'edor':2, 'ador':1, 'ddor':0, 'gdor':-1, 'cdor':-2,\n 'fdor':-3, 'bbdor':-4, 'ebdor':-5, 'abdor':-6, 'dbdor':-7,\n // Phrygian\n 'e#phr':7, 'a#phr':6, 'd#phr':5, 'g#phr':4, 'c#phr':3,\n 'f#phr':2, 'bphr':1, 'ephr':0, 'aphr':-1, 'dphr':-2,\n 'gphr':-3, 'cphr':-4, 'fphr':-5, 'bbphr':-6, 'ebphr':-7,\n // Lydian\n 'f#lyd':7, 'blyd':6, 'elyd':5, 'alyd':4, 'dlyd':3,\n 'glyd':2, 'clyd':1, 'flyd':0, 'bblyd':-1, 'eblyd':-2,\n 'ablyd':-3, 'dblyd':-4, 'gblyd':-5, 'cblyd':-6, 'fblyd':-7,\n // Locrian\n 'b#loc':7, 'e#loc':6, 'a#loc':5, 'd#loc':4, 'g#loc':3,\n 'c#loc':2, 'f#loc':1, 'bloc':0, 'eloc':-1, 'aloc':-2,\n 'dloc':-3, 'gloc':-4, 'cloc':-5, 'floc':-6, 'bbloc':-7\n };\n var k = keyname.replace(/\\s+/g, '').toLowerCase().substr(0, 5);\n var scale = k.match(/maj|min|mix|dor|phr|lyd|loc|m/);\n if (scale) {\n if (scale == 'maj') {\n kkey = k.substr(0, scale.index);\n } else if (scale == 'min') {\n kkey = k.substr(0, scale.index + 1);\n } else {\n kkey = k.substr(0, scale.index + scale[0].length);\n }\n } else {\n kkey = /^[a-g][#b]?/.exec(k) || '';\n }\n var result = accidentals(sigcodes[kkey]);\n var extras = keyname.substr(kkey.length).match(/(_+|=|\\^+)[a-g]/ig);\n if (extras) {\n for (var j = 0; j < extras.length; ++j) {\n var note = extras[j].charAt(extras[j].length - 1).toUpperCase();\n if (extras[j].charAt(0) == '=') {\n delete result[note];\n } else {\n result[note] = extras[j].substr(0, extras[j].length - 1);\n }\n }\n }\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggles the visibility of all layers of a certain type by changing their opacity to either 1.0 or 0.0. This way, here will not be any interference with a possibly available layer selection. | toggleLayersByType(layerType) {
//Iterate over all tile layers
this.allLayers
//Filter for layers of the given type
.filter(layer => layer instanceof layerType)
.forEach(layer => {
//Invert opacity
let newOpacity = layer.getOpacity() < 1 ? 1 : 0;
layer.setOpacity(newOpacity);
});
} | [
"function togglePreviewLayers(display) {\n // Preserve inline formatting of opacity sliders & output labels in LayerDiv\n var display_inline = (display == 'block') ? 'inline' : 'none';\n var layerDiv = getElement('LayerDiv');\n var layers = layerDiv.getElementsByTagName('label');\n var sliders = layerDiv.getElementsByTagName('input');\n var slider_values = layerDiv.getElementsByTagName('output');\n for (var i = 0; i < layers.length; i++) {\n layers[i].style.display = display;\n }\n for (var i = 0; i < sliders.length; i++) {\n sliders[i].style.display = display_inline;\n }\n for (var i = 0; i < slider_values.length; i++) {\n slider_values[i].style.display = display_inline;\n }\n}",
"function hideAllLayers(layers) {\n\tlayers = layers || doc.layers;\n\tfor (var i = 0; i < layers.length; i++) {\n\t\tlayers[i].visible = false;\n\t}\n}",
"function updateBaseLayersOpacity(value) {\r\n\tif (map.hasLayer(OpenStreetMap_Mapnik)) {\r\n\t\tOpenStreetMap_Mapnik.setOpacity(value / 100);\r\n\t};\r\n\tif (map.hasLayer(Stamen_Watercolor)) {\r\n\t\tStamen_Watercolor.setOpacity(value / 100);\r\n\t};\r\n\tif (map.hasLayer(OpenTopoMap)) {\r\n\t\tOpenTopoMap.setOpacity(value / 100);\r\n\t};\r\n\tif (map.hasLayer(BingAerial)) {\r\n\t\tBingAerial.setOpacity(value / 100);\r\n\t};\r\n}",
"function toggleLayer(layer) {\r\n switch (layer.isHidden()) {\r\n case true:\r\n // Need to move layers to index position on top\r\n layer.show();\r\n clientLeft.moveLayer(layer, clientLeft.getLayers().length - 1);\r\n clientRight.moveLayer(layer,clientRight.getLayers().length - 1);\r\n break;\r\n case false:\r\n layer.hide();\r\n }\r\n }",
"function evaluateLayerVisibility()\r\n{\r\n\t//console.log( \"Evaluating visibility\" );\r\n\tvar viewLayers = map.getLayers();\r\n\t\r\n\tif( viewLayers != undefined )\r\n\t{\r\n\t\tviewLayers = viewLayers.getArray();\r\n\t\r\n\t\tvar viewLayer;\r\n\t\tvar mapLayer;\r\n\t\tvar mapShapes;\r\n\t\t\r\n\t\tfor( var i = 0; i < viewLayers.length; i++ )\r\n\t\t{\r\n\t\t\tviewLayer = viewLayers[i];\r\n\t\t\t//layerSource = viewLayer.getSource();\r\n\t\t\tmapLayer = getLayerById( imageMap, viewLayer.id ); \r\n\t\t\t\r\n\t\t\tif( mapLayer != undefined )\r\n\t\t\t{\r\n\t\t\t\tlet zoom = getZoom();\r\n\t\t\t\t//console.log( \"Zoom is \" + zoom );\r\n\t\t\t\t//console.log( \"Map Layer's min zoom is \" + mapLayer.minZoom );\r\n\t\t\t\t//console.log( \"Map Layer's min zoom is \" + mapLayer.maxZoom );\r\n\t\t\t\t\r\n\t\t\t\tif( zoom >= mapLayer.minZoom && zoom <= mapLayer.maxZoom )\r\n\t\t\t\t{\r\n\t\t\t\t\t//console.log( \"Showing layer \" + mapLayer.id );\r\n\t\t\t\t\tviewLayer.setVisible( true );\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t//console.log( \"Hiding layer \" + mapLayer.id );\r\n\t\t\t\t\tviewLayer.setVisible( false );\r\n\t\t\t\t}\t\r\n\t\t\t}\r\n\t\t}\t\r\n\t}\r\n}",
"function DisableTranspOptionalLayers(index, id_minus, id_plus, checkboxId)\n{\n\n\tvar checkid = document.getElementById(checkboxId);\n\n\n\tif (checkid.checked == true)//check if the layer is selected\n\t{\n\t\tvar optionOpacity = optionalArray[index];//localte which global opacity layer it is\n\n\t\t//Disables the buttons.\n\t\tif (optionOpacity < maxOpacity) {\n\t\t\tdocument.getElementById(id_minus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_minus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_minus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\t\t}\n\n\t\tif (optionOpacity > minOpacity) {\n\t\t\tdocument.getElementById(id_plus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_plus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_plus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\t\t}\n\t}\n\telse\n\t{\n\t\t//Disables the buttons.\n\t\tdocument.getElementById(id_minus).disabled = true;\n\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\n\t\tdocument.getElementById(id_plus).disabled = true;\n\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\n\t}\n\n}",
"function toggleEarthLayer(layerId) {\n // Define layer and whether or not it is expandable.\n var layer = ge.getLayerRoot().getLayerById(layerId)\n var layerStyle = layer.getComputedStyle().getListStyle();\n var expandable = layerStyle.getListItemType();\n var action;\n if (layer.getVisibility() == false) {\n // If off, turn on.\n action = true\n ge.getLayerRoot().enableLayerById(layerId, action);\n // Also turn on parent layers and check their checkboxes. Only\n // if toggling layers on.\n toggleParentCheckbox(layer);\n } else {\n // If on, turn off.\n action = false\n ge.getLayerRoot().enableLayerById(layerId, action);\n }\n // Whether toggling on or off, make sure all child layers mimic the\n // behavior by turning them on/off as well.\n if (layer.getType() == 'KmlFolder' && expandable == 1) {\n var childLayers = layer.getFeatures().getChildNodes();\n toggleChildLayers(childLayers, action);\n }\n}",
"updateVisibility() {\n const {\n fadeStages,\n currentLifetime: time,\n opacityAmountPerFrame: amount,\n } = this\n\n if (time >= fadeStages.invisible) {\n this.graphics.alpha = 0\n return\n }\n\n if (time >= fadeStages.fadeIn) {\n this.graphics.alpha += amount\n return\n }\n\n if (time <= fadeStages.fadeOut) {\n this.graphics.alpha -= amount\n return\n }\n\n this.graphics.alpha = constants.PARTICLE_OPACITY\n }",
"function getMapLayers() {\n for (var i = 0; i < geeServerDefs.layers.length; i++) {\n var layer = geeServerDefs.layers[i];\n var layerId = layer.glm_id ?\n layer.glm_id + '-' + layer.id : '0-' + layer.id;\n var div = document.getElementById('LayerDiv');\n var checked = layer.initialState ? ' checked' : '';\n var imgPath =\n geeServerDefs.serverUrl + 'query?request=Icon&icon_path=' + layer.icon;\n div.innerHTML +=\n '<label>' +\n '<input type=\"checkbox\" onclick=\"toggleMapLayer(\\'' +\n layerId + '\\')\"' + 'id=\"' + layerId + '\" ' + checked + '/>' +\n '<img src=\"' + imgPath + '\" onerror=\"this.style.display=\\'none\\';\" >' +\n layer.label + '</label>';\n div.innerHTML +=\n '<input type=range id=opacity_' + i + ' min=0 value=100 max=100 step=10 ' +\n 'oninput=\"geeMap.setOpacity(\\'' + layerId + '\\', Number(value/100))\" ' +\n 'onchange=\"outputOpacityValue(\\'' + i + '\\', Number(value))\">';\n div.innerHTML += '<output id=opacity_out_' + i + '>100%</output>';\n\n }\n togglePolygonVisibility();\n}",
"function show(type) {\n for (var i=0; i<gmarkers.length; i++) {\n if (gmarkers[i].type == type) {\n gmarkers[i].setVisible(true);\n }\n }\n $(\"#filter_\"+type).removeClass(\"inactive\");\n}",
"function unhideLayers(n) {\n for (var i = n; i >= 0; i--) {\n layersToHitTest[i].style[propName] = propBackup[i];\n }\n }",
"function updateOverlayLayersOpacity(value) {\r\n\tgeojsonCCAA.setStyle({\r\n\t\tfillOpacity: value / 100\r\n\t});\r\n\tgeojsonProvincias.setStyle({\r\n\t\tfillOpacity: value / 100\r\n\t});\r\n\tgeojsonZonas.setStyle({\r\n\t\tfillOpacity: value / 100\r\n\t});\r\n}",
"function hideLayers(evt) {\r\n dialogLayer.style.display = \"none\";\r\n maskLayer.style.display = \"none\";\r\n }",
"function hideOVLayer(name) {\t\t\n \tvar layer = getOVLayer(name);\t\t\n \tif (isNav4)\n \tlayer.visibility = \"hide\";\n \t//if (document.all)\n\telse\n \t layer.visibility = \"hidden\";\n\t //layer.display=\"block\";\n}",
"function changeTranspOptionalLayers(selectedLayer, val, index, id_minus, id_plus, checkboxId)\n{\n\tvar checkid = document.getElementById(checkboxId);\n\n\tif (checkid.checked == true)//check if the layer is selected\n\t{\n\t\toptionalArray[index] = optionalArray[index] + val;\n\n\t\tvar optionOpacity = optionalArray[index];//locate which global opacity layer it is\n\n\t\t//Disables the buttons.\n\t\tif (optionOpacity < maxOpacity) {\n\t\t\tdocument.getElementById(id_minus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_minus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_minus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_minus), 3);//Change color to disabled \n\t\t}\n\n\t\tif (optionOpacity > minOpacity) {\n\t\t\tdocument.getElementById(id_plus).disabled = false;\n\t\t\tchangeColor(document.getElementById(id_plus), 0);//Change color to enabled\n\t\t} else {\n\t\t\tdocument.getElementById(id_plus).disabled = true;\n\t\t\tchangeColor(document.getElementById(id_plus), 3);//Change color to disabled \n\t\t}\n\n\t\tif (optionOpacity < .00001) {\n\t\t\toptionOpacity = 0;\n\t\t}\n\t\tselectedLayer.setOpacity(optionOpacity);\n\t}\n}",
"function makeAllNodesFullOpacity(){\n model.nodeDataArray.forEach(node => {\n setOpacity(node, 1);\n })\n}",
"static set AllLayers(value) {}",
"updateVisibility() {\n //Get current zoom level\n let zoomLevel = this.map.getView().getZoom();\n let visible = this.isVisibleAtZoomLevel(zoomLevel);\n //Update visibility\n super.setVisible(visible);\n }",
"function setLinkOpacity(){\n model.linkDataArray.forEach(link => {\n if (hasTransparentNode(link)){\n setOpacity(link, 0.15)\n } else {\n setOpacity(link, 1)\n }\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An upload progress event. | function HttpUploadProgressEvent() { } | [
"function onProgress(e) {\n if (video.buffered.length > 0)\n {\n var end = video.buffered.end(0),\n start = video.buffered.start(0);\n load_bar.setAttribute(\"width\", Math.ceil((end - start) / video.duration * 100).toString());\n }\n}",
"function notifyUploadDone(numberOfFiles, error) {\n var url = '${fileUploadDoneUrl}';\n Wicket.Ajax.get( {\n u: url + \"&numberOfFiles=\" + numberOfFiles + \"&error=\" + error\n });\n }",
"upload(e){\n if(e.target.files.length) this.handleFile(e.target.files[0])\n }",
"#updateFormProgress() {\n if (this.#steps?.length) {\n let activeStepIndex = this.#steps.findIndex(\n ({ name }) => name === this.activeStep\n );\n let activeStepCount = activeStepIndex + 1;\n let progress =\n Math.ceil((activeStepIndex / (this.#steps.length - 1)) * 100) || 10;\n let indicator = this.#progressBar.querySelector(\".indicator\");\n indicator.style.setProperty(\"--progress\", progress + \"%\");\n // Ensure progressbar starts translated at -100% before we\n // set --progress to avoid a layout race.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n indicator.toggleAttribute(\"ready\", true);\n });\n });\n this.#progressBar.setAttribute(\"aria-valuenow\", activeStepCount);\n this.#progressBar.setAttribute(\n \"aria-label\",\n interpolate(gettext(\"Step %s of %s\"), [\n activeStepCount,\n this.#steps.length,\n ])\n );\n }\n }",
"handleUploadFinished(event) {\n let strFileNames = '';\n // Get the list of uploaded files\n const uploadedFiles = event.detail.files;\n\n let listUploadedFileNames = [];\n for (let i = 0; i < uploadedFiles.length; i++) {\n strFileNames += uploadedFiles[i].name + ', ';\n listUploadedFileNames.push(uploadedFiles[i].name);\n }\n\n //Retrieve the uploaded files along with the urls\n this.getFiles();\n\n this.showToastMessage('Files uploaded', strFileNames + ' Files uploaded Successfully!!!', 'success');\n }",
"function progressUpdate() {\n // the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n // we put the percentage in the screen\n $('.txt-perc').text(`${loadingProgress}%`);\n}",
"seek(position) {\r\n if (this.isSeeking)\r\n this.progress = position * 100;\r\n }",
"onAudioProgress(audioInfo) {\n // console.log('audio progress', audioInfo)\n }",
"function logProgress(msg, err) {\n if (err) {\n console.log(msg, err);\n } else {\n process.stdout.write(msg);\n }\n\n // send progress message to browser client\n if (sio) {\n sio.sockets.emit('status_data', {\n msg: msg\n });\n }\n}",
"sendProgress() {\n // compute number of tests if not done so already\n if (!this.testCount) {\n this.testCount = 0;\n this.frameworks.forEach(framework => {\n framework.tests.forEach(test => {\n this.testCount++;\n });\n });\n }\n\n var percentage = (this.testsComplete / this.testCount) * 100;\n this.socket.emit('benchmark_progress', {'percent' : percentage});\n }",
"function upload() {\n if (! canUpload()) {\n return alert(\"Can't upload right now.\");\n }\n\n // sanity check queued files\n var totalSize = 0;\n for (var i = 0; i < allFiles.length; i++) {\n totalSize += allFiles[i].size;\n }\n if (totalSize > maxUploadSize) {\n return alert(\n 'Sorry, you can only upload ' +\n humanSize(maxUploadSize) +\n ' at a time (you tried to upload ' +\n humanSize(totalSize) +\n ')!'\n );\n }\n\n uploading = true;\n\n // update UI\n var uploadButton = $(\"#upload\");\n uploadButton.text(\"Cancel Upload\");\n\n $(\"#statusText\").show();\n $(\"#selectFiles\").slideUp(200);\n $(\".remove\").fadeOut(200);\n\n // start the upload\n // http://stackoverflow.com/a/8244082\n var request = $.ajax({\n url: \"/upload?json\",\n type: \"POST\",\n contentType: false,\n\n data: getFormData(),\n processData: false,\n\n xhr: function() {\n var req = $.ajaxSettings.xhr();\n\n req.upload.addEventListener(\"progress\", function(e) {\n if (request != uploadRequest) {\n return; // upload was cancelled\n }\n\n if (e.lengthComputable) {\n updateProgress(e.loaded, e.total);\n }\n }, false);\n\n return req;\n },\n\n error: function(xhr, status) {\n if (request !== uploadRequest) {\n return; // upload was cancelled\n }\n\n if (xhr.responseJSON) {\n alert(xhr.responseJSON.error);\n cancelUpload();\n } else {\n // TODO: improve error handling\n console.log(\"Unhandled failure: \" + status + \", status=\" + xhr.status + \", statusText=\" + xhr.statusText);\n alert(\"Sorry, an unexpected error occured.\");\n cancelUpload();\n }\n },\n\n success: function(data) {\n if (request != uploadRequest) {\n return; // upload was cancelled\n }\n\n // TODO: improve error handling\n if (! data.success) {\n return alert(data.error);\n }\n\n if (uploadHistory.enabled()) {\n uploadHistory.addItemToHistory({\n url: data.redirect,\n time: new Date(),\n fileDetails: Object.entries(data.uploaded_files).map(([filename, metadata]) => ({\n filename,\n bytes: metadata.bytes,\n rawUrl: metadata.raw,\n pasteUrl: metadata.paste,\n })),\n });\n }\n\n window.location.href = data.redirect;\n }\n });\n\n uploadRequest = request;\n}",
"async continueUpload(uploadId, fileOffset, fragment) {\n let n = await spPost(File(this, `continueUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`), { body: fragment });\n if (typeof n === \"object\") {\n // When OData=verbose the payload has the following shape:\n // { ContinueUpload: \"20971520\" }\n n = n.ContinueUpload;\n }\n return parseFloat(n);\n }",
"function upload() {\n\n isCanceled = false;\n indexNumbers = [];\n space = undefined;\n progress = 0;\n let path = $('#file-chooser').val();\n if (validatePath(path) & validateKey.call($('#space-key')) & validateTitle.call($('#space-title'))) {\n space = {\n name: $('#space-title').val(),\n key: $('#space-key').val()\n };\n setUploadMessage(i18n.PREPARING_FOR_UPLOAD, \"generic\");\n createDialog();\n if (AJS.$('#radioButtonUpdate').prop(\"checked\")) {\n\n } else if (AJS.$('#radioButtonClone').prop(\"checked\")) {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, cloneToOldSpace, error);\n } else {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, deleteOldSpace, error);\n }\n\n }\n }",
"function onSeek(event) {\n var seekTime = parseInt(event.data.currentTime);\n if (seekTime >= duration - 1) {\n seekTime = (duration > 1) ? duration - 1 : 0;\n }\n event.data.currentTime = seekTime;\n printDebugMessage(\"onSeek\", event);\n player.mb.publish(OO.EVENTS.SEEK, seekTime);\n window.mediaManager.onSeekOrig(event);\n window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);\n}",
"async startUpload(uploadId, fragment) {\n let n = await spPost(File(this, `startUpload(uploadId=guid'${uploadId}')`), { body: fragment });\n if (typeof n === \"object\") {\n // When OData=verbose the payload has the following shape:\n // { StartUpload: \"10485760\" }\n n = n.StartUpload;\n }\n return parseFloat(n);\n }",
"async setContentChunked(file, progress, chunkSize = 10485760) {\n if (!isFunc(progress)) {\n progress = () => null;\n }\n const fileSize = (file === null || file === void 0 ? void 0 : file.size) || file.length;\n const totalBlocks = parseInt((fileSize / chunkSize).toString(), 10) + ((fileSize % chunkSize === 0) ? 1 : 0);\n const uploadId = getGUID();\n const fileRef = File(this).using(CancelAction(() => {\n return File(fileRef).cancelUpload(uploadId);\n }));\n // report that we are starting\n progress({ uploadId, blockNumber: 1, chunkSize, currentPointer: 0, fileSize, stage: \"starting\", totalBlocks });\n let currentPointer = await fileRef.startUpload(uploadId, file.slice(0, chunkSize));\n // skip the first and last blocks\n for (let i = 2; i < totalBlocks; i++) {\n progress({ uploadId, blockNumber: i, chunkSize, currentPointer, fileSize, stage: \"continue\", totalBlocks });\n currentPointer = await fileRef.continueUpload(uploadId, currentPointer, file.slice(currentPointer, currentPointer + chunkSize));\n }\n progress({ uploadId, blockNumber: totalBlocks, chunkSize, currentPointer, fileSize, stage: \"finishing\", totalBlocks });\n return fileRef.finishUpload(uploadId, currentPointer, file.slice(currentPointer));\n }",
"PrintProgress() {\n process.stdout.clearLine()\n process.stdout.cursorTo(0) \n process.stdout.write('Progress: '+this.folIter+' from '+this.totalFol)\n }",
"streamModeProgressFunction(dltotal, dlnow, ultotal, ulnow) {\n if (this.streamError)\n throw this.streamError;\n const ret = this.streamUserSuppliedProgressFunction\n ? this.streamUserSuppliedProgressFunction.call(this.handle, dltotal, dlnow, ultotal, ulnow)\n : 0;\n return ret;\n }",
"function completedProcess(self) {\n\t//console.log('completedProcess called');\n\tself.emit('completedProcess', self.file, self.fileObjectList.getAll());\n\tconsole.log(\"FeedFileProcessor : Finished processing \", self.file);\n\t//console.log(\"Contents are \", self.fileObjectList.getAll());\n\n}",
"function uploadFile(file) {\n const storageRef = firebase.storage().ref('uploads/' + file.name);\n const task = storageRef.put(file);\n\n task.on('state_changed',\n function progress(snap) {\n var progress = (snap.bytesTransferred / snap.totalBytes) * 100;\n uploadProgress.value = progress\n },\n\n function error(err) {\n console.error(err);\n },\n\n function complete() {\n task.snapshot.ref.getDownloadURL().then(function (downloadURL) {\n analysedImage.src = downloadURL;\n });\n const storedPath = task.snapshot.ref.fullPath;\n // Create request to vision\n submitToVision(storedPath);\n\n // Clear input and progress\n uploadProgress.removeAttribute('value');\n fileInput.value = \"\";\n }\n )\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returnable account is a POJO that is returned to interacting applications. For instance, in EOSIO blockchains a name is required, however in Ethereum blockchains only a publicKey/address is required. | returnableAccount(account){} | [
"function Account(props) {\n return __assign({ Type: 'AWS::ApiGateway::Account' }, props);\n }",
"getAccount(actor) {\n const getAccount = new queries.GetAccount(actor);\n return getAccount.execute(this.publicKey);\n }",
"async currentAccount() {\n const accounts = await this.web3.eth.getAccounts()\n const defaultAccount = this.web3.eth.defaultAccount\n return defaultAccount || accounts[0]\n }",
"function getAccount(name) {\n var acc = read(name);\n if (acc === \"undefined\"){\n\t\t// storage not supported by browser\n } else if (acc == null) {\n\t // nothing stored at that key\n return new Account(name, [], []);\n } else {\n // result successfully found\n return JSON.parse(acc);\n }\n}",
"getAccount(pin){\n for (let i = 0; i < this.accounts.length; i++) {\n if (this.accounts[i].pin === pin) {\n //return the bank account that matches our pin\n console.log (\"GetAccount\");\n this.currentAccount = this.accounts[i]; \n updateATM(); \n return this.accounts[i];\n }\n }\n return null; \n }",
"get effectiveAccount() {\n return this.action.actionProperties.role?.env.account\n ?? this.action.actionProperties?.resource?.env.account\n ?? this.action.actionProperties.account;\n }",
"to(account) {\n return this.setDebitAccount(account);\n }",
"function AccountObj()\n{\n\tthis.Countries = new Array() // list of country codes used by all direct deposit accounts on record\n\tthis.Hash = new Array()\t // list of accounts indexed by country code; each is an AccountsHash object\n\tthis.sysAvailable = 0\t // total accounts available to add for the system, independent of country\n\tthis.totalOpen = 0\t // total number of active accounts for the system, across all countries\n\tthis.totalClose = 0\t // total number of inactive accounts for the system, across all countries\n\tthis.sysLimit = MAXACCOUNTS // the maximum allowable number of accounts the system will hold\n}",
"function createAccount (account) {\r\n accounts.push(account);\r\n return account;\r\n}",
"async updateAccount() {\r\n const accounts = await web3.eth.getAccounts();\r\n const account = accounts[0];\r\n this.currentAccount = account;\r\n console.log(\"ACCOUNT: \"+account)\r\n }",
"function getAbi(account){\n try {\n return eos.getAbi(account).then(function(abi) {\n return abi;\n });\n } catch (err) {\n let errorMessage = `Get Abi Controller Error: ${err.message}`;\n return errorMessage;\n } \n}",
"getCurrentBalance() {\n if (!this.owner) {\n return Promise.reject(new Error(\"Owner is required\"));\n }\n return this.contract\n .methods\n .getCurrentBalance()\n .call({ from: this.owner });\n }",
"getAccountByName(name, commit=true) {\n for (let i = 0; i < this.accounts.length; i++) {\n let account = this.accounts[i];\n if (account.name === name) {\n return account;\n }\n }\n if (commit) {\n let newAccount = new Account(name);\n this.accounts.push(newAccount);\n return newAccount;\n } else {\n return undefined;\n }\n }",
"async balanceFor(account, token){}",
"function getBorrowersForBook(book, accounts) {\n const borrowList = book.borrows;\n const borrowedBy = [];\n borrowList.forEach((borrow) => {\n let findAccount = accounts.find((account) => account.id.includes(borrow.id));\n let dupliCheck = borrowedBy.some((borrow) => borrow.id === findAccount.id);\n if(findAccount != undefined && !dupliCheck)\n {\n findAccount[\"returned\"] = borrow.returned;\n borrowedBy.push(findAccount);\n }\n return borrowedBy;\n });\n return borrowedBy;\n}",
"async getAccount(accountNo) {\n try {\n const accounts = await this.getAccounts();\n return accounts.find(account => account.accountNo == accountNo);\n } catch (err) {\n throw err;\n }\n }",
"function getAccount(username){\n var matchedAccount;\n\n accounts.forEach(function(account){\n if (account.username === username){\n matchedAccount = account;\n }\n\n });\n\n return matchedAccount;\n\n\n}",
"async getContract() {\n let res = await axios(`${rahatServer}/api/v1/app/contracts/Rahat`);\n const { abi } = res.data;\n res = await axios(`${rahatServer}/api/v1/app/settings`);\n const contractAddress = res.data.agency.contracts.rahat;\n return new ethers.Contract(contractAddress, abi, wallet);\n }",
"BinanceAccountInfoMarginIso() {\n this.command = \"/sapi/v1/margin/isolated/account\"\n this.param = \"\"\n this.pos = 2\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funcion para ocultar los datos de un dia y volver a mostrar la tabla donde se encuentra la semana | function mostrarOcultar()
{
var dia=document.getElementById("dia");
var semana=document.getElementById("semana");
// ocultamos el div donde se encuentran los datos del dia
dia.className="oculta";
// dejamos el div vacio
dia.innerHTML="";
// volvemos a asignar estilos a la tabla donde se encuentran los datos de la semana para volver a mostrarla
semana.className="tablaInicial";
} | [
"function llenar_tabla_vistas_observaciones() {\n $(\"#modal_vista_observaciones\").show()\n $(\"#tabla_vistas_observaciones tr\").remove()\n\n var cuestionario, pregunta, indice_cues, indice_preg = 1;\n $.each(datos_mostrar, function (index, item) {\n //*********aqui se va a usar pendiente \n var fillas = $(\"<tr></tr>\")\n if (item.folio > 0) {\n //recorre las incidencias corregidas para reasignar la respuesta\n $.each(insidencias_corregidas, function (i, t) {\n if (t.insidencias == item.folio) {\n item.respuesta = t.solucionadas;\n }\n })\n if (index == 0) {\n cuestionario = item.cuestionario\n pregunta = item.pregunta\n \n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<th colspan='2'>\").append(cuestionario).css({ \"background-color\": \"#c5cfcb\" }))\n , $(\"<tr>\").append(\n $(\"<td >\").append(indice_preg).css({ \"background-color\": \"#c5cfaf\" })\n , $(\"<td >\").append(pregunta).css({ \"background-color\": \"#c5cfaf\" }))\n )\n indice_preg++\n }\n if (cuestionario == item.cuestionario) {\n\n if (pregunta != item.pregunta) {\n cuestionario = item.cuestionario\n pregunta = item.pregunta\n\n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<td>\").append(indice_preg).css({ \"background-color\": \"#c5cfaf\" })\n , $(\"<td>\").append(pregunta).css({ \"background-color\": \"#c5cfaf\" })\n ))\n indice_preg++\n }\n } else if (cuestionario != item.cuestionario) {\n cuestionario = item.cuestionario\n pregunta = item.pregunta\n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<th colspan='2'>\").append(cuestionario).css({ \"background-color\": \"#c5cfcb\" }))\n ,$(\"<tr>\").append(\n $(\"<td colspan='1'>\").append(indice_preg).css({ \"background-color\": \"#c5cfaf\" })\n , $(\"<td colspan='1'>\").append(pregunta).css({ \"background-color\": \"#c5cfaf\" }))\n )\n indice_preg++\n }\n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<td>\").append((index + 1)).css({ width: \"50px\", \"text-align\": \"center\" })\n , $(\"<td>\").append(item.observaciones).css({ \"background-color\": bg_estado(item.respuesta) })\n ))}\n })\n function bg_estado(valor) {\n if (valor == 1) { return \"rgb(149, 251, 0)\" }\n else if (valor == 0) { return \"red\" }\n else return \"\"\n }\n }",
"function criarItensTabela(dados) {\n\n\tconst linha = tabela.insertRow()\n\n\tconst colunaClienteNome = linha.insertCell(0)\n\tconst colunaPedidoDados = linha.insertCell(1)\n\tconst colunaPedidoHora = linha.insertCell(2)\n\n\tconst dados_pedido = dados.pedido_dados.substr(0, 10) + \" ...\"\n\n\tcolunaClienteNome.appendChild(document.createTextNode(dados.cliente_nome))\n\tcolunaPedidoDados.appendChild(document.createTextNode(dados_pedido.replace(/<br>/g, \" \")))\n\n\tconst data = new Date(Number(dados.pedido_data))\n\tconst date = moment(data).format('HH:mm:ss')\n\tcolunaPedidoHora.appendChild(document.createTextNode(date))\n\n\tcolunaClienteNome.style = \"text-align: center\"\n\tcolunaPedidoDados.style = \"text-align: center\"\n\tcolunaPedidoHora.style = \"text-align: center\"\n\n\tcriarBotoesTabela(linha, dados)\n\n\t//ordemCrescente()\n}",
"function crearTabla(datos) {\n //limpiamos lo que hubiere antes\n cleanDatos();\n //creamos la tabla\n let tabla = document.createElement(\"TABLE\");\n tabla.setAttribute(\"border\", \"1\");\n //creo la cabecera de la tabla\n tabla.appendChild(crearCabeceraTabla(datos));\n //cuerpo de la tabla\n for (let i = 0; i < datos.length; i++) {\n //creamos las filas\n let fila = document.createElement(\"TR\");\n //recorremos cada objeto y mostramos su información\n rellenaFila(datos, i, fila);\n //añadimos la fila a la tabla\n tabla.appendChild(fila);\n }\n //añadimos la tabla al documento\n document.getElementById(\"datos\").appendChild(tabla);\n}",
"function mostrarCursosActiiQueImparte(){\n let listaCursosActii = getListaCursosActii();\n let sede = getSedeVisualizar();\n let nombreSede = sede[0];\n let cuerpoTabla = document.querySelector('#tblCursosActii tbody');\n cuerpoTabla.innerHTML = '';\n\n for (let i = 0; i < listaCursosActii.length; i++) {\n\n let sedeAsociada = listaCursosActii[i][5];\n\n for (let j = 0; j < sedeAsociada.length; j++) {\n \n if (sedeAsociada[j] == nombreSede) {\n let fila = cuerpoTabla.insertRow();\n\n let cCodigo = fila.insertCell();\n let cCursoActii = fila.insertCell();\n let sCodigo = document.createTextNode(listaCursosActii[i][0]);\n let sCursoActii = document.createTextNode(listaCursosActii[i][1]);\n cCodigo.appendChild(sCodigo);\n cCursoActii.appendChild(sCursoActii);\n\n }\n }\n\n }\n}",
"function mostrarCursosCarreraQueImparte(){\n let listaCursosCarrera = getListaCursos();\n let sede = getSedeVisualizar();\n let nombreSede = sede[0];\n let cuerpoTabla = document.querySelector('#tblCursosCarrera tbody');\n cuerpoTabla.innerHTML = '';\n\n for (let i = 0; i < listaCursosCarrera.length; i++) {\n\n let sedeAsociada = listaCursosCarrera[i][7];\n\n for (let j = 0; j < sedeAsociada.length; j++) {\n\n if (sedeAsociada[j][0] == nombreSede) {\n let fila = cuerpoTabla.insertRow();\n let cCursoCarrera = fila.insertCell();\n let sCursoCarrera = document.createTextNode(listaCursosCarrera[i][1]);\n cCursoCarrera.appendChild(sCursoCarrera);\n\n }\n }\n\n }\n}",
"function pronalazenjeDatuma(d) {\n\n let mesec = d.getMonth() + 1;\n if (mesec.toString().length == 1) {\n mesec = \"0\" + mesec.toString();\n }\n let dan = d.getDate();\n if (dan.toString().length == 1) {\n dan = \"0\" + dan.toString();\n }\n let danas = getDatum(dan + \" \" + mesec + \" \" + d.getFullYear());\n var dict = {}; //key = datum, value = pozicija u tabeli\n\n let dat = parseInt(d.getDate());\n\n for (let index = danas; index <= 6; index++) {\n if (mesec == 1 || mesec == 3 || mesec == 5 || mesec == 7 || mesec == 8 || mesec == 10 || mesec == 12) {\n if (dat > 31) {\n dat = 1;\n }\n } else if (mesec == 2) {\n if (dat > 29) {\n dat = 1;\n }\n } else {\n if (dat > 30) {\n dat = 1;\n }\n }\n dict[dat] = index;\n dat++;\n }\n\n let brojac = 0;\n for (let index = danas; index > 0; index--) {\n if (mesec == 1 || mesec == 3 || mesec == 5 || mesec == 7 || mesec == 8 || mesec == 10 || mesec == 12) {\n if (dat > 31) {\n dat = 1;\n }\n } else if (mesec == 2) {\n if (dat > 29) {\n dat = 1;\n }\n } else {\n if (dat > 30) {\n dat = 1;\n }\n }\n dict[d.getDate() - index] = brojac;\n brojac++;\n }\n for (var key in dict) {\n dobavi(key, dict, d);\n }\n}",
"function M_table(collection, tipo_tabla, ubicacion_html, headers, rows, types) {\n var objetivo = document.getElementById(ubicacion_html);\n\n var tbl = document.getElementById('tabla_automatica'); //Limpiar tabla antes de agregar la nueva.//\n if (tbl) tbl.parentNode.removeChild(tbl);\n\n var tabla = '<table id=\"tabla_automatica\" class=\"striped responsive-table centered\">';\n //Head.//\n tabla += '<thead>';\n tabla += '<tr>';\n headers.forEach(data => {\n tabla += '<th>' + data + '</th>';\n });\n tabla += '</tr>';\n tabla += '</thead>';\n //Body.//\n tabla += '<tbody id=\"tabla_dinamica_body\">';\n tabla += '</tbody>';\n tabla += '</table>';\n tabla += '<div class=\"progress col s8 offset-s2\"><div class=\"indeterminate\"></div ></div >'; //Loader\n\n objetivo.innerHTML = tabla;\n\n setTimeout(function () { \n document.getElementsByClassName('progress')[0].style.display = 'none';\n\n //Generar rows de la tabla.//\n if (tipo_tabla === 0) { //Si la coleccion es directa de firestore.//\n collection.forEach(doc => {\n var contador = 0;\n var body = '<tr>';\n rows.forEach(data => {\n if (types && types.length > 0) {\n switch (types[contador]) {\n case 'id':\n body += '<td><b>' + doc.data()[data] + '</b></td>';\n break;\n case 'money':\n body += '<td>$' + doc.data()[data] + '</td>';\n break;\n case 'date':\n var fecha = M_toMexDate(doc.data()[data]); //Convertir fechas a formato es-MEX\n body += '<td>' + fecha + '</td>';\n break;\n default:\n body += '<td>' + doc.data()[data] + '</td>';\n break;\n }\n } else {\n body += '<td>' + doc[data] + '</td>';\n }\n contador++;\n });\n /*body += '<td>' + doc.data().folio + '</td>';*/\n body += '</tr>';\n document.getElementById('tabla_dinamica_body').insertRow(0);\n document.getElementById('tabla_dinamica_body').rows[0].innerHTML = body;\n });\n } else if (tipo_tabla === 1) { //Si es un arreglo creado manualmente con M_objeto.//\n collection.forEach(doc => {\n var contador = 0;\n var body = '<tr>';\n rows.forEach(data => {\n if (types && types.length > 0) {\n switch (types[contador]) {\n case 'id':\n body += '<td><b>' + doc[data] + '</b></td>';\n break;\n case 'money':\n body += '<td>$' + doc[data] + '</td>';\n break;\n case 'date':\n var fecha = M_toMexDate(doc[data]); //Convertir fechas a formato es-MEX\n body += '<td>' + fecha + '</td>';\n\n break;\n default:\n body += '<td>' + doc[data] + '</td>';\n break;\n }\n } else {\n body += '<td>' + doc[data] + '</td>';\n }\n contador++;\n });\n body += '</tr>';\n document.getElementById('tabla_dinamica_body').insertRow(0);\n document.getElementById('tabla_dinamica_body').rows[0].innerHTML = body;\n });\n }\n }, 3000);\n\n\n\n /*collection.forEach(doc => {\n console.log(doc.data()); //<=== Crear una tabla html en la clase .vista-reporte y ver como llega a data\n });*/\n}",
"function generate_table_schedule_group(route2) {\n \n var tabla_head = \"<table id=\\\"profesores_asignados_a_curso\\\" >\" +\n \"<thead>\" +\n \"<th>Dia</th>\" +\n \"<th>Hora Inicio</th>\" +\n \"<th>Hora Fin</th>\" +\n \"<th>Aula</th>\" +\n \"</thead>\" +\n \"<tbody>\";\n $.getJSON(route2, function (data) {\n var tabla = \"\";\n if (data.length != 0) {\n for (i = 0; i < data.length; i++) {\n tabla = tabla + \"<tr>\" +\n \"<td>\" + data[i].Day + \"</td>\" +\n \"<td>\" + data[i].StartHour + \"</td>\" +\n \"<td>\" + data[i].EndHour + \"</td>\" +\n \"<td>\" + data[i].Code + \"</td>\" +\n \"</tr>\";\n\n\n }\n\n tabla = tabla + \"</tbody> </table>\";\n\n document.getElementById('table_schedule_group').innerHTML = tabla_head+tabla;\n }\n else {\n var tabla = \"<table id=\\\"profesores_asignados_a_curso\\\" >\" +\n \"<thead>\" +\n \"<th>Dia</th>\" +\n \"<th>Hora Inicio</th>\" +\n \"<th>Hora Fin</th>\" +\n \"<th>Aula</th>\" +\n \"</thead> \" +\n \"<tr>\" +\n \"<td>-</td>\" +\n \"<td>-</td>\" +\n \"<td>-</td>\" +\n \"<td>-</td>\" +\n \"</tr>\"+\n \"<tr>\" +\n \"<td>-</td>\" +\n \"<td>-</td>\" +\n \"<td>-</td>\" +\n \"<td>-</td>\" +\n \"</tr>\";;\n tabla = tabla + \"</tbody> </table>\";\n document.getElementById('table_schedule_group').innerHTML = table_head+tabla;\n }\n });\n}",
"function cargarPedido(nuevoPedido, IDnuevoPedido) {\n // Recibe la direccion de la tabla y crea una fila siempre al final\n \n let tabla = document.getElementById(\"tablaPedido\");\n let fila = tabla.insertRow(-1);\n\n /// El td del producto\n let producto = document.createElement(\"td\");\n producto.textContent =nuevoPedido.producto; // el textContent del td es el producto\n fila.appendChild(producto);\n // El td del cantidad\n let cantidad = document.createElement(\"td\");\n cantidad.textContent =nuevoPedido.cantidad ; // el textContent del td es el cantidad\n fila.appendChild(cantidad);\n // El td del precio\n let precio = document.createElement(\"td\");\n precio.textContent =nuevoPedido.precio; // el textContent del td es el precio\n fila.appendChild(precio);\n \n //Crea el boton de editar, le asigna las propiedades\n let btnEditar = document.createElement(\"button\");\n btnEditar.innerHTML = \"Editar\";\n btnEditar.type = \"button\";\n btnEditar.addEventListener('click', function(){editarPedido(fila, IDnuevoPedido);});\n fila.appendChild(btnEditar);\n //Crea el boton de borrar, le asigna las propiedades\n let btnBorrar = document.createElement(\"button\");\n btnBorrar.innerHTML = \"Borrar\";\n btnBorrar.type = \"button\";\n btnBorrar.addEventListener('click', function(){borrarPedido(fila, IDnuevoPedido);});\n fila.appendChild(btnBorrar);\n // Finalmente agregamos la fila al cuerpo de la tabla\n tabla.appendChild(fila);\n // modifica el atributo \"border\" de la tabla y lo fija a \"2\";\n tabla.setAttribute(\"border\", \"2\"); \n}",
"function obtenerCodigoInspeccionesPendientesAscensores(estado){\n $('#ascensores').show('fast');\n db.transaction(function (tx) {\n var query = \"SELECT * FROM auditoria_inspecciones_ascensores WHERE o_estado_envio = ?\";\n tx.executeSql(query, [estado], function (tx, resultSet) {\n for(var x = 0; x < resultSet.rows.length; x++) {\n var k_codusuario = resultSet.rows.item(x).k_codusuario;\n var codigo_inspeccion = resultSet.rows.item(x).k_codinspeccion;\n var cantidad_nocumple = resultSet.rows.item(x).v_item_nocumple;\n var consecutivo_inspe = resultSet.rows.item(x).o_consecutivoinsp;\n visualizarInspeccionesAscensores(k_codusuario,codigo_inspeccion,cantidad_nocumple,consecutivo_inspe);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n}",
"function LlenarTablaCategoria() {\n\ttable = $('#table_categoria').DataTable({\n\t\tpageLength: 10,\n\t\tresponsive: true,\n\t\tprocessing: true,\n\t\tajax: \"../controller/CategoriaController.php?operador=listar_categoria\",\n\t\tcolumns: [\n\t\t\t{ data: 'op' },\n\t\t\t{ data: 'id' },\n\t\t\t{ data: 'nombre' },\n\t\t\t{ data: 'descripcion' },\n\t\t\t{ data: 'estado' }\n\t\t]\n\t});\n}",
"function obtenerCorrectivos(){\n\t\t \tvar bodytable = $(\"#bodytable_correctivo\");\n\t\t\t$.get(\"\"+baseurl+\"/obtenercorrectivos\", \n\t\t\t\t{ fecha_inicio: $(\"#fecha_inicio_correctivo\").val(), fecha_fin: $(\"#fecha_fin_correctivo\").val() }, \n\t\t\t\tfunction(data){\n\t\t\t\t\tbodytable.empty();\n\t\t\t\t\tvar x = 1;\n\t\t\t\t\tif($.isEmptyObject(data)){\n\t\t\t\t\t\tbodytable.append('<tr><td colspan=\"10\"><p style=\"color:red;text-align:center;padding:0;margin:0;\">No existen mantenimientos correctivos en este rango de fecha</p></td></tr>');\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$.each(data, function(index,element) {\n\t\t\t\t\t\t\tbodytable.append('<tr><td>'+x+'</td><td>'+convertirFecha(element.fecha_realizacion)+'</td><td>'+element.num_activo+'</td><td>'+element.nombre+'</td><td>'+element.marca+'</td><td>'+element.modelo+'</td><td>'+element.serie+'</td><td>'+element.realizado_por+'</td><td>'+element.aprobado_por+'</td><td>'+element.costo_mantenimiento+'</td></tr>');\n\t\t\t\t\t\t\tx++;\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t});\t\n\t\t}",
"function crearTablero(){\n //Inicializa el tablero\n for (f = 0; f < alt; f++){\n for (c = 0; c < anc; c++){\n tablero[f][c] = 0;\n visible[f][c] = 0;\n }\n }\n estado = 0;\n casillasVistas = 0;\n\n //Poner 99 minas\n for (mina = 0; mina < 99; mina++){\n //Busca una posicion aleatoria donde no haya mina\n var f;\n var c;\n do{\n f = Math.trunc((Math.random()*(15+1)));\n c = Math.trunc((Math.random()*(29+1)));\n //System.out.println(\"Coor(\" + f + \",\" + c +\")\");\n }while(tablero[f][c] == 9);\n //Pone la mina\n tablero[f][c] = 9;\n //Recorre el contorno de la mina e incrementa los contadores\n for (f2 = max(0, f-1); f2 < min(alt,f+2); f2++){\n for (c2 = max(0,c-1); c2 < min(anc,c+2); c2++){\n if (tablero[f2][c2] != 9){ //Si no es bomba\n tablero[f2][c2]++; //Incrementa el contador\n }\n }\n }\n }\n tableroConsola();\n}",
"function obtenerCostoActivos(){\n\t\t\tvar bodytable = $(\"#bodytable_costos_activos\");\t\n\t\t\t\n\t\t\t$.get(\"\"+baseurl+\"/obtenercostosactivos\", \n\t\t\t\t{ fecha_inicio: $(\"#fecha_inicio_costo_1\").val(), fecha_fin: $(\"#fecha_fin_costo_1\").val() }, \n\t\t\t\tfunction(data){\n\t\t\t\t\tbodytable.empty();\n\t\t\t\t\tvar x = 1;\n\t\t\t\t\tif($.isEmptyObject(data)){\n\t\t\t\t\t\tbodytable.append('<tr><td colspan=\"8\"><p style=\"color:red;text-align:center;padding:0;margin:0;\">No existen activos en este rango de fecha</p></td></tr>');\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$.each(data, function(index,element) {\n\t\t\t\t\t\t\tbodytable.append('<tr><td>'+x+'</td><td>'+element.num_activo+'</td><td>'+element.nombre+'</td><td>'+element.modelo+'</td><td>'+element.marca+'</td><td>'+element.serie+'</td><td>'+convertirFecha(element.fecha_compra)+'</td><td>'+element.costo+'</td></tr>');\n\t\t\t\t\t\t\tx++;\n\t\t\t\t\t\t});\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t}, 'json');\n\t\t}",
"function createTable() {\n let table = [];\n adeudo = 0;\n importe = 0;\n\n let num_orders = pagosTicket.length;\n if (num_orders !== 0) {\n total = parseFloat(pagosTicket[0].monto);\n importe = 0;\n for (let i = 0; i < num_orders; i++) {\n let children = [];\n children.push(<td hidden>{pagosTicket[i].id_pago}</td>);\n children.push(<td>${pagosTicket[i].abono}</td>);\n children.push(<td>{pagosTicket[i].fecha_pago}</td>);\n children.push(<td>{pagosTicket[i].asesor}</td>);\n children.push(<td><button className=\"btn btn-success btn-ticket\" onClick={() => printTicket(pagosTicket[i].id_pago)}>Ticket</button></td>);\n table.push(<tr>{children}</tr>);\n\n importe += Number(pagosTicket[i].abono);\n }\n\n importe = parseFloat(toFixedTrunc(importe, 2));\n\n adeudo = total - importe;\n } else {\n adeudo = total;\n }\n\n adeudo = parseFloat(adeudo);\n console.log('ADEUDO', adeudo);\n if (adeudo > 1) adeudo = parseFloat(adeudo.toFixed(2));\n\n return table;\n}",
"function llenarTablaAscensorValoresIniciales(){\n var cod_inspector = window.localStorage.getItem(\"codigo_inspector\");\n var parametros = {\"inspector\" : cod_inspector};\n $.ajax({\n async: true,\n url: \"http://www.montajesyprocesos.com/inspeccion/servidor/php/json_app_ascensor_valores_iniciales.php\",\n data: parametros,\n type: \"POST\",\n dataType : \"JSON\",\n success: function(response){\n $.each(response, function(i,item){\n var k_codusuario = item.k_codusuario;\n var k_codinspeccion = item.k_codinspeccion;\n var n_cliente = item.n_cliente;\n var n_equipo = item.n_equipo;\n var n_empresamto = item.n_empresamto;\n var o_tipoaccion = item.o_tipoaccion;\n var v_capacperson = item.v_capacperson;\n var v_capacpeso = item.v_capacpeso;\n var f_fecha = item.f_fecha;\n var v_codigo = item.v_codigo;\n var v_paradas = item.v_paradas;\n var o_consecutivoinsp = item.o_consecutivoinsp;\n var ultimo_mto = item.ultimo_mto;\n var inicio_servicio = item.inicio_servicio;\n var ultima_inspeccion = item.ultima_inspeccion;\n var h_hora = item.h_hora;\n var o_tipo_informe = item.o_tipo_informe;\n\n var codigo_inspeccion = k_codinspeccion;\n if (codigo_inspeccion < 10) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n if (codigo_inspeccion < 100) {\n codigo_inspeccion = \"0\" + codigo_inspeccion;\n }\n\n db.transaction(function (tx) {\n var query = \"SELECT * FROM ascensor_valores_iniciales WHERE k_codusuario = ? AND k_codinspeccion = ?\";\n tx.executeSql(query, [k_codusuario,codigo_inspeccion], function (tx, resultSet) {\n //alert(resultSet.rows.length);\n if (resultSet.rows.length == 0) {\n addItemsAscensorValoresIniciales(k_codusuario,codigo_inspeccion,n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe);\n }else{\n updateItemsAscensorValoresIniciales(n_cliente,n_equipo,n_empresamto,o_tipoaccion,v_capacperson,v_capacpeso,v_paradas,f_fecha,v_codigo,o_consecutivoinsp,ultimo_mto,inicio_servicio,ultima_inspeccion,h_hora,o_tipo_informe, k_codusuario,codigo_inspeccion);\n }\n },\n function (tx, error) {\n console.log('SELECT error: ' + error.message);\n });\n }, function (error) {\n console.log('transaction error: ' + error.message);\n }, function () {\n console.log('transaction ok');\n });\n \n });\n }\n });\n}",
"function listaJugadores(datos){\n\tif(datos==\"OK\"){\n\t\twindow.location.replace(\"/prfinal/jugada\");\n\t}\n\telse{\n\t\tvar jugadores = eval (\"(\"+datos+\")\");\n\t\tvar textoHTML=\"<table class='table'>\"\n\t\t\ttextoHTML+=\"<tr><th>Nombre</th><th>Turno</th></tr>\"\n\n\t\t\t\tif(jugadores[0].nombre==1)\n\t\t\t\t\t$('#btnComenzar').show();\n\t\t\t\telse\n\t\t\t\t\t$('#btnComenzar').hide();\n\n\t\tfor (var i=1; i<jugadores.length; i++){\n\t\t\ttextoHTML+=\"<tr>\"\n\t\t\t\ttextoHTML+=\"<td>\"+jugadores[i].nombre+\"</td>\"\n\t\t\t\ttextoHTML+=\"<td>\"+jugadores[i].turno+\"</td>\"\n\t\t\t\ttextoHTML+='</tr>'\n\t\t}\n\t\ttextoHTML+='</table>'\n\n\t\t\tdocument.getElementById(\"lJugadores\").innerHTML=textoHTML;\n\n\t}\n\n\n}",
"function obtenerPreventivos(){\n\t\t \tvar bodytable = $(\"#bodytable_preventivo\");\n\t\t\t$.get(\"\"+baseurl+\"/obtenerpreventivos\", \n\t\t\t\t{ fecha_inicio: $(\"#fecha_inicio_preventivo\").val(), fecha_fin: $(\"#fecha_fin_preventivo\").val() }, \n\t\t\t\tfunction(data){\n\t\t\t\t\tbodytable.empty();\n\t\t\t\t\tvar x = 1;\n\t\t\t\t\tif($.isEmptyObject(data)){\n\t\t\t\t\t\tbodytable.append('<tr><td colspan=\"10\"><p style=\"color:red;text-align:center;padding:0;margin:0;\">No existen mantenimientos preventivos en este rango de fecha</p></td></tr>');\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$.each(data, function(index,element) {\n\t\t\t\t\t\t\tbodytable.append('<tr><td>'+x+'</td><td>'+convertirFecha(element.fecha_realizacion)+'</td><td>'+element.num_activo+'</td><td>'+element.nombre+'</td><td>'+element.marca+'</td><td>'+element.modelo+'</td><td>'+element.serie+'</td><td>'+element.realizado_por+'</td><td>'+element.aprobado_por+'</td><td>'+element.costo_mantenimiento+'</td></tr>');\n\t\t\t\t\t\t\tx++;\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t});\t\n\t\t}",
"function actualizarTablaVida(oponente, jsonPartida){\n\tif(!jsonPartida.tiros1 || !jsonPartida.tiros2)\n\t\treturn true;\n\n\t//se ajustan las vidas al maximo\n\tpuntajePortaaviones.innerHTML = \"5/5\";\n\tpuntajeAcorazado.innerHTML = \"3/3\";\n\tpuntajeFragata.innerHTML = \"3/3\";\n\tpuntajeSubmarino.innerHTML = \"3/3\";\n\tpuntajeBuque.innerHTML = \"2/2\";\n\tpuntajePortaaviones2.innerHTML = \"5/5\";\n\tpuntajeAcorazado2.innerHTML = \"3/3\";\n\tpuntajeFragata2.innerHTML = \"3/3\";\n\tpuntajeSubmarino2.innerHTML = \"3/3\";\n\tpuntajeBuque2.innerHTML = \"2/2\";\n\n\n\tvar vidas = {\n\t\tportaaviones: 5,\n\t\tacorazado: 3,\n\t\tfragata: 3,\n\t\tsubmarino: 3,\n\t\tbuque: 2\n\t}\n\tvar tablero1; //tablero del huesped\n\tvar tiros1;\n\tvar tablero2; //tablero oponente\n\tvar tiros2;\n\tif(oponente == 1){\n\t\ttablero1 = jsonPartida.tablero2;\n\t\ttablero2 = jsonPartida.tablero1;\n\t\ttiros1 = jsonPartida.tiros2;\n\t\ttiros2 = jsonPartida.tiros1;\n\t} else if (oponente == 2){\n\t\ttablero1 = jsonPartida.tablero1;\n\t\ttablero2 = jsonPartida.tablero2;\n\t\ttiros1 = jsonPartida.tiros1;\n\t\ttiros2 = jsonPartida.tiros2\n\t} else {\n\t\treturn false;\n\t}\n\tfor(var i = 0; i < tiros2.length; i++){ //verificando vidas del huesped\n\t\tvar posicionTirada = parseInt(tiros2[i]);\n\t\tvar posicionEnPortaavion = tablero1.portaaviones.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnAcorazado = tablero1.acorazado.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnFragata = tablero1.fragata.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnSubmarino = tablero1.submarino.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnBuque = tablero1.buque.posiciones.indexOf(posicionTirada);\n\n\t\tif(posicionEnPortaavion != -1){\n\t\t\tvidas.portaaviones--;\n\t\t\tpuntajePortaaviones.innerHTML = vidas.portaaviones + \"/\" + 5;\n\t\t\ttablero1.portaaviones.posiciones.splice(posicionEnPortaavion, 1);\n\t\t}\n\t\tif(posicionEnAcorazado != -1){\n\t\t\tvidas.acorazado--;\n\t\t\tpuntajeAcorazado.innerHTML = vidas.acorazado + \"/\" + 3;\n\t\t\ttablero1.acorazado.posiciones.splice(posicionEnAcorazado, 1);\n\t\t}\n\t\tif(posicionEnFragata != -1){\n\t\t\tvidas.fragata--;\n\t\t\tpuntajeFragata.innerHTML = vidas.fragata + \"/\" + 3;\n\t\t\ttablero1.fragata.posiciones.splice(posicionEnFragata, 1);\n\t\t}\n\t\tif(posicionEnSubmarino != -1){\n\t\t\tvidas.submarino--;\n\t\t\tpuntajeSubmarino.innerHTML = vidas.fragata + \"/\" + 3;\n\t\t\ttablero1.submarino.posiciones.splice(posicionEnSubmarino, 1);\n\t\t}\n\t\tif(posicionEnBuque != -1) {\n\t\t\tvidas.buque--;\n\t\t\tpuntajeBuque.innerHTML = vidas.buque + \"/\" + 2;\n\t\t\ttablero1.buque.posiciones.splice(posicionEnBuque, 1);\n\t\t}\n\t}\n\tvidas = {\n\t\tportaaviones: 5,\n\t\tacorazado: 3,\n\t\tfragata: 3,\n\t\tsubmarino: 3,\n\t\tbuque: 2\n\t}\n\tfor(var i = 0; i < tiros1.length; i++){ //verificando vidas del oponente\n\t\tvar posicionTirada = parseInt(tiros1[i]);\n\t\tvar posicionEnPortaavion = tablero2.portaaviones.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnAcorazado = tablero2.acorazado.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnFragata = tablero2.fragata.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnSubmarino = tablero2.submarino.posiciones.indexOf(posicionTirada);\n\t\tvar posicionEnBuque = tablero2.buque.posiciones.indexOf(posicionTirada);\n\n\t\tif(posicionEnPortaavion != -1){\n\t\t\tvidas.portaaviones--;\n\t\t\tpuntajePortaaviones2.innerHTML = vidas.portaaviones + \"/\" + 5;\n\t\t\ttablero2.portaaviones.posiciones.splice(posicionEnPortaavion, 1);\n\t\t}\n\t\tif(posicionEnAcorazado != -1){\n\t\t\tvidas.acorazado--;\n\t\t\tpuntajeAcorazado2.innerHTML = vidas.acorazado + \"/\" + 3;\n\t\t\ttablero2.acorazado.posiciones.splice(posicionEnAcorazado, 1);\n\t\t}\n\t\tif(posicionEnFragata != -1){\n\t\t\tvidas.fragata--;\n\t\t\tpuntajeFragata2.innerHTML = vidas.fragata + \"/\" + 3;\n\t\t\ttablero2.fragata.posiciones.splice(posicionEnFragata, 1);\n\t\t}\n\t\tif(posicionEnSubmarino != -1){\n\t\t\tvidas.submarino--;\n\t\t\tpuntajeSubmarino2.innerHTML = vidas.fragata + \"/\" + 3;\n\t\t\ttablero2.submarino.posiciones.splice(posicionEnSubmarino, 1);\n\t\t}\n\t\tif(posicionEnBuque != -1) {\n\t\t\tvidas.buque--;\n\t\t\tpuntajeBuque2.innerHTML = vidas.buque + \"/\" + 2;\n\t\t\ttablero2.buque.posiciones.splice(posicionEnBuque, 1);\n\t\t}\n\t}\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DSGVO stuff / Cookie optout wrapper for $.cookie function Passes cookies through to $.cookie function, but only if user has not opted out or if cookie is not blacklisted via cookiebanner.cookies.optout | function setCookieSafely(title, value, options) {
if (window.cookiebanner && window.cookiebanner.optedOut && window.cookiebanner.optoutCookies && window.cookiebanner.optoutCookies.length) {
var blacklist = window.cookiebanner.optoutCookies.split(',');
for (var i = 0; i < blacklist.length; i++) {
if (title === $.trim(blacklist[i])) {
return false;
}
}
}
$.cookie(title, value, options);
} | [
"function optionsCookie(req, res, next) {\r\n \r\n function isString(v) {return typeof v == 'string'}\r\n\r\n if(isString(req.query.sort) && req.query.sort != req.cookies.sort) {\r\n res.cookie('sort', req.query.sort, {httpOnly: false}) \r\n }\r\n\r\n if(isString(req.query.sort) && req.query.order != req.cookies.order) {\r\n res.cookie('order', req.query.order, {httpOnly: false}) \r\n }\r\n\r\n if(isString(req.cookies.sort) && !req.query.sort) {\r\n req.query.sort = req.cookies.sort\r\n }\r\n\r\n if(isString(req.cookies.order) && !req.query.order) {\r\n req.query.order = req.cookies.order\r\n }\r\n\r\n return next()\r\n}",
"static clearCookie() {\n var cookies = document.cookie.split(\";\");\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;\n if (name.trim().toLowerCase() == 'voting-username')\n document.cookie = name + \"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n }\n \n }",
"function saveConfirmUserSetting(event, ui){\n var dontShowAgainOption = $(this).parent().find(\"#perc_show_again_check\").is(':checked');\n if (dontShowAgainOption) {\n var currentUser = $.PercNavigationManager.getUserName();\n var confirmDialogId = $(this).parent().attr('id');\n var cookieKey = \"dontShowAgain-\" + currentUser + \"-\" + confirmDialogId;\n $.cookie(cookieKey, \"true\");\n }\n}",
"function bakeCookies() {\n\n}",
"function getCheckCookie() {\r\n\treturn $.cookies.test();\r\n}",
"function cookieExists() {\n if (typeof $.cookie('accessToken') === 'undefined') {\n return false;\n }\n return true;\n }",
"function set_pref_box(){\nsetCookie('pref_box',\"true\",cookie_time,\"/\")\nwindow.location.reload(false) ;\n}",
"function getCookieOptions() {\n let cookieOpt = {\n httpOnly: true\n };\n if (opt.cookieDomain) {\n cookieOpt.domain = opt.cookieDomain;\n }\n if (opt.secure) {\n cookieOpt.secure = true;\n }\n if (opt.cookiePath) {\n cookieOpt.path = opt.cookiePath;\n }\n if (opt.sameSite) {\n cookieOpt.sameSite = typeof opt.sameSite === 'string' ? opt.sameSite : true;\n }\n return cookieOpt;\n }",
"function initializeCookieBanner() {\n let isCookieAccepted = localStorage.getItem(\"cc_isCookieAccepted\");\n if (isCookieAccepted === null) {\n localStorage.clear();\n localStorage.setItem(\"cc_isCookieAccepted\", \"false\");\n showCookieBanner();\n }\n if (isCookieAccepted === \"false\") {\n showCookieBanner();\n }\n}",
"function noCookieFound()\n{\n\treturn document.cookie == \"\" || document.cookie == null;\n}",
"function cookieGetSettings() {\n return JSON.parse($.cookie(cookie));\n }",
"function cookieExists() {\n return typeof $.cookie(cookie) !== 'undefined';\n }",
"function cerrarAvisoCookies(){\n\t\t$('#contenedorCookies').css('display','none');\n\t\t$.cookie(\"avisado\", \"yes\", { expires : 10 });\n}",
"function testPersistentCookie () {\nwritePersistentCookie (\"testPersistentCookie\", \"Enabled\", \"minutes\", 1);\nif (getCookieValue (\"testPersistentCookie\")==\"Enabled\")\nreturn true \nelse \nreturn false;\n}",
"function loadUserInfoFromCookie()\n {\n userName = $.cookie(\"perc_userName\");\n isAdmin = $.cookie(\"perc_isAdmin\") == 'true' ? true : false;\n isDesigner = $.cookie(\"perc_isDesigner\") == 'true' ? true : false;\n isAccessibilityUser = $.cookie(\"perc_isAccessibilityUser\") == 'true' ? true : false;\n\t \n $.perc_utils.info(\"UserInfo\", \"userName: \" + userName + \", isAdmin: \" + isAdmin + \", isDesigner: \" + isDesigner + \", isAccessibilityUser: \" + isAccessibilityUser);\n }",
"function cookieAdvices(numberAdvices, indexAdvice) {\n\tvar oldValue = getCookie(\"advice\"); //get the old value of the cookie\n\tvar newValues = \"\"; //create a new empty cookie value\n\t\n\t//check if the old cookie was empty \n\tif (oldValue == \"\") {\n\t\tvar newValues = \"\";\n\t\tfor (i in Array.from(Array(numberAdvices).keys())) { //fill it with zeroes\n\t\t\tnewValues += 0;\n\t\t\tnewValues += \"%\";\n\t\t}\n\t}\n\t\n\telse {\n\t\tvar newValuesList = oldValue.split(\"%\"); //new value is a list of the values in the old value string\n\t\t\n\t\t//replace the value for the checkboxs of the selected index \n\t\tif (newValuesList[indexAdvice] == 1) {\n\t\t\tnewValuesList[indexAdvice] = 0; \n\t\t} else {\n\t\t\tnewValuesList[indexAdvice] = 1;\n\t\t}\n\t\t\n\t\t//make a string of all values\n\t\tfor (i in Array.from(Array(numberAdvices).keys())) { \n\t\t\tnewValues += newValuesList[i];\n\t\t\tnewValues += \"%\";\n\t\t}\n\t}\n\t\n\tsetCookie(\"advice\", newValues);\n\tconsole.log(\"testing if cookie exists\");\n\tconsole.log(document.cookie);\n}",
"function cookieFromFilterpanel(){\n var ch = [];\n if ($j('.shop-filter-panel .filter-toggle').hasClass(\"open\")){\n ch.push(true);\n }\n\n $j.cookie(\"filterpanelCookie\", ch.join(','));\n}",
"function setCookie(){\r\nvar xxcookie = document.cookie;\r\n\tif (xxcookie.indexOf(\"DesafioLeoLearning\") >= 0){ //verifica se o cookie existe\r\n\t}else{//caso não exista cria o cookie e exibe o banner na tela\t\t\r\n\t\tdocument.cookie = \"username=DesafioLeoLearning; expires=Thu, 18 Dec 2093 12:00:00 UTC\";\r\n\t\tdocument.getElementById('banner').style.marginTop = '0px';\r\n\t}\t\r\n}",
"function hide(div){\n div.css('display','none')\n document.cookie='closed_announce=1'\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List the billing.CreditCard objects [PRODUCTION] [See on api.ovh.com]( | ListOfCreditCards() {
let url = `/me/paymentMean/creditCard`;
return this.client.request('GET', url);
} | [
"function getCreditCards(){\n\tif(paymentScreenProps.windowType==\"Modal\" && !isUserLoggedIn()){\n\t\treturn false;\n\t}\n\ttogglePaymentAndIFrameBlock(false);\n\t\n\t\t$('#cancelButton').attr(\"disabled\", true);\n\t\t$.ajax({\n \t\t\ttype: \"POST\",\n \t\t\turl: \"/listCreditCards.do?operation=retrieveCreditCardList\",\n \t\t\tdata: \"displayRadioButtons=\"+paymentScreenProps.displayRadioButtons,\n \t\t\tsuccess: \n\t\t\t\tfunction(data){\t\t\n\t\t\t\t\t\t$('#ccRows').html(data);\n\t\t\t\t\t\t$(\"#profileRow1\").attr(\"checked\", \"checked\");\n\t\t\t\t\t $(\"#profileRow1\").click();\n\t\t\t\t\t\tinit();\t\n\t\t\t\t\t}\n\t\t});\t\n\t\t//highlightExpiredCards();\t\t\t\n}",
"ListOfBankAccounts(state) {\n let url = `/me/paymentMean/bankAccount?`;\n const queryParams = new query_params_1.default();\n if (state) {\n queryParams.set('state', state.toString());\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"async index({ params: { companyId }, request, response, auth }) {\n const user = await auth.getUser();\n const company = await user.company().fetch();\n const purchases = await company\n .purchases()\n .with('products')\n .fetch();\n\n response.status(200).json({\n message: 'Listado de compras',\n purchases: purchases,\n });\n }",
"function GetAllGiftCards() {\n return $resource(_URLS.BASE_API + 'homegiftcard' + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }",
"async function reservationSummariesDailyWithBillingAccountId() {\n const subscriptionId =\n process.env[\"CONSUMPTION_SUBSCRIPTION_ID\"] || \"00000000-0000-0000-0000-000000000000\";\n const scope = \"providers/Microsoft.Billing/billingAccounts/12345\";\n const grain = \"daily\";\n const filter = \"properties/usageDate ge 2017-10-01 AND properties/usageDate le 2017-11-20\";\n const options = { filter };\n const credential = new DefaultAzureCredential();\n const client = new ConsumptionManagementClient(credential, subscriptionId);\n const resArray = new Array();\n for await (let item of client.reservationsSummaries.list(scope, grain, options)) {\n resArray.push(item);\n }\n console.log(resArray);\n}",
"ListOfAuthorizedDeferredPaymentAccountForThisCustomer() {\n let url = `/me/paymentMean/deferredPaymentAccount`;\n return this.client.request('GET', url);\n }",
"function GetAddBankList(token, suc_func, error_func) {\n let api_url = 'get_bank_card_list.php',\n post_data = {\n 'token': token\n };\n CallApi(api_url, post_data, suc_func, error_func);\n}",
"function getCards() {\n axios({\n method: \"GET\",\n url: \"https://omgvamp-hearthstone-v1.p.rapidapi.com/cards\",\n headers: {\n \"content-type\": \"application/octet-stream\",\n \"x-rapidapi-host\": \"omgvamp-hearthstone-v1.p.rapidapi.com\",\n \"x-rapidapi-key\": \"174f54c7e9msh385aea11f59db8ep1eecbfjsna5431ab42c87\",\n useQueryString: true,\n params: {\n locale: \"ptBR\",\n },\n },\n })\n .then((response) => {\n const filteredCards = response.data.Basic.map((card) => card.attack);\n if (filteredCards !== undefined) {\n setCards(response.data.Basic);\n }\n })\n .catch((error) => {\n console.log(error);\n });\n }",
"ListOfPaypalAccountsUsableForPaymentsOnThisAccount() {\n let url = `/me/paymentMean/paypal`;\n return this.client.request('GET', url);\n }",
"getCredits() {\n return this.credits;\n }",
"async getCryptoCurrenciesList(){\n\t\tconst endpointResponse = await fetch('https://api.coinmarketcap.com/v1/ticker/');\n\n\t\t// Return response as json\n\t\tconst cryptoCurrencies = await endpointResponse.json();\n\n\t\t// Return the object\n\t\treturn {\n\t\t\tcryptoCurrencies\n\t\t}\n\t}",
"function allCards(){\n createFile();\n var data = fs.readFileSync('deck.json');\n var dataParsed = JSON.parse(data);\n var keys = dataParsed[Object.keys(dataParsed)[0]];\n var allCards = \"https://deckofcardsapi.com/api/deck/\" + keys + \"/draw/?count=52\";\n return allCards;\n}",
"migrateCreditCards() {}",
"GiveAccessToAllEntriesOfTheBill(billId) {\n let url = `/me/bill/${billId}/details`;\n return this.client.request('GET', url);\n }",
"ListAvailablePaymentMethodsInThisNicCountry() {\n let url = `/me/availableAutomaticPaymentMeans`;\n return this.client.request('GET', url);\n }",
"ListOfOVHAccountsTheLoggedAccountHas() {\n let url = `/me/ovhAccount`;\n return this.client.request('GET', url);\n }",
"function listSubscriptions() {\n\n\t// Lists all subscriptions in the current project\n\treturn pubsub.getSubscriptions().then(results => {\n\t\tconst subscriptions = results[0];\n\n\t\tconsole.log('Subscriptions:');\n\t\tsubscriptions.forEach(subscription => console.log(subscription.name));\n\n\t\treturn subscriptions;\n\t});\n}",
"function getCustomerList(source, callback) {\n\tconsole.log('entering getCustomerList function')\n\t// get json data object from ECS bucket\t\n\tvar GDUNS = [];\n\tvar params = {\n\t\t\tBucket: 'installBase',\n\t\t\tKey: source\n\t}; \n\t \n\tecs.getObject(params, function(err, data) {\n\t\tif (err) {\n\t\t\tcallback(err, null); // this is the callback saying getCustomerList function is complete but with an error\n\t\t} else { // success\t\t\t\t\t\n\t\t\tconsole.log(data.Body.toString()); // note: Body is outputted as type buffer which is an array of bytes of the body, hence toString() \n\t\t\tvar dataPayload = JSON.parse(data.Body);\n\t\t\t\n\t\t\t// load GDUNS array\n\t\t\tfor (var i = 0; i < dataPayload.length; i++) {\n\t\t\t\tGDUNS.push(dataPayload[i].gduns);\n\t\t\t}\n\t\t\t\n\t\t\t// free up memory\n\t\t\tdata = null; \n\t\t\tdataPayload = null;\n\t\t\t\n\t\t\tcallback(null, GDUNS) // this is the callback saying getCustomerList function is complete\n\t\t}\n\t});\n}",
"function showList() {\n $state.go('customer.list');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ALGO: map the array of strings with the count for the char return the minimum count | function minimuNumberOfApperances(char, arrayOfStrings) {
return Math.min(...arrayOfStrings.map(string => (string.match(new RegExp(char,'g')) || []).length));
} | [
"function solve(arr){ \n let alpha = \"abcdefghijklmnopqrstuvwxyz\";\n return arr.map(a => a.split(\"\").filter((b,i) => b.toLowerCase() === alpha[i]).length )\n}",
"function getMinPartition(s, i=0, j=s.length-1)\n{\n let ans = Number.MAX_VALUE\n let count = 0\n\n if (isPalindrome(s.substring(i, j + 1)) || s==='')\n return 0\n \n for(let k = i; k < j; k++)\n {\n count = getMinPartition(s, i, k) + getMinPartition(s, k + 1, j) + 1;\n ans = Math.min(ans, count);\n }\n return ans\n}",
"function main(wordArray){\n let map = new Map();\n wordList = [];\n\n for(let string of wordArray){\n let counter = 1;\n\n if(map.has(string)){\n let wordCount = map.get(string);\n\n map.set(string, wordCount + 1);\n }else{\n map.set(string, counter);\n }\n }\n wordList = Array.from(map).sort((a, b) => b[1] - a[1]);\n wordList.forEach((word)=> {\n console.log(`${word[0]} -> ${word[1]} times`);\n });\n}",
"function repeatedChars(arrayOfStrings) {\n if (arrayOfStrings === undefined || arrayOfStrings === []) return [];\n\n let lowerCaseStrings = arrayOfStrings.map(string => string.toLowerCase());\n\n let uniqueChars = getUniqueChars(lowerCaseStrings);\n\n let appearances = [];\n\n uniqueChars.forEach(char => {\n let charApperance = minimuNumberOfApperances(char, lowerCaseStrings);\n appearances.push(...(new Array(charApperance).fill(char)));\n });\n\n return appearances.sort();\n}",
"function bin2min_term(string)\n{\n\tvar alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\talphabets = alphabets.split(\"\");\n\tvar alphabet_index = 0;\n\tvar min_term = \"\";\n\tvar dont_cares = 0;\n\tfor (var i = 0; i < string.length; i++)\n\t{\n\t\tif (string[i] == 1)\n\t\t{\n\t\t\tmin_term += \" \" + alphabets[alphabet_index] + \" \";\n\t\t}\n\t\telse if (string[i] == 0)\n\t\t{\n\t\t\tmin_term += \" ~\" + alphabets[alphabet_index] + \" \";\n\t\t}\n\t\telse if (string[i] == \"X\")\n\t\t{\n\t\t\tdont_cares += 1;\n\t\t}\n\t\talphabet_index += 1;\n\t}\n\tif (dont_cares == string.length)\n\t{\n\t\tmin_term = 1;\n\t}\n\treturn min_term;\n}",
"function min (metric, count) {\n if ((typeof metric === 'string') && (typeof count === 'number')) {\n const oldCount = map.get(metric)\n const newCount = (oldCount == null) ? count : (oldCount > count) ? count : oldCount\n map.set(metric, newCount)\n return newCount\n } else {\n return 0\n }\n }",
"function longest_common_starting_substring(arr1){\r\n const arr= arr1.concat().sort();\r\n const a1= arr[0];\r\n const a2= arr[arr.length-1];\r\n const L= a1.length;\r\n let i= 0;\r\n while(i< L && a1.charAt(i)=== a2.charAt(i)) i++;\r\n return a1.substring(0, i);\r\n }",
"function startWithA(characters) {\n let nameA = [];\n let count = 0;\n characters.forEach(function (array) {\n if (array.name.startsWith(\"A\")) {\n nameA.push(array.name);\n count += 1;\n }\n });\n // console.log(nameA);\n return count;\n}",
"function sc(apple) {\n return apple.reduce((acc, letterArr, i) => {\n let letterIndex = letterArr.indexOf('B')\n letterIndex === -1 ? false : acc = [i, letterIndex]\n return acc\n }, -1)\n\n}",
"function shortestLength(array){\n\tvar minLength = array[0].length;\n\tfor(var i = 1; i < array.length; i++){\n\t\tif(array[i].length < minLength){\n\t\t\tminLength = array[i].length;\n\t\t}\n\t}\n\treturn minLength\n}",
"function startWithZ(characters) {\n let nameZ = [];\n let count = 0;\n characters.forEach(function (array) {\n if (array.name.startsWith(\"Z\")) {\n nameZ.push(array.name);\n count += 1;\n }\n });\n // console.log(nameZ);\n return count;\n}",
"function repeatChar(string,char){\n string= string.toLowerCase()\n string= string.split(\"\")\n var result = string.reduce(function(num,str){\n\nif ( str===char){\n ++num\n}return num\n\n } ,0)\n return result\n}",
"function countingSort(stringArr, pfxlen){\n if(pfxlen === undefined){ pfxlen = 1; }\n\n var i, k, p, counts, sortedArr;\n\n /* For a given item, reuturn its 0-based array index integer key.\n * This should be a constant-time function mapping an item/prefix\n * to its array index.\n */\n var _keyfn = function(idx, itm){\n return punycode.ucs2.decode(itm[idx])[0];\n };\n\n // Prefix block method:\n // idx, start, end\n var prefixBlocks = [[0, 0, stringArr.length - 1]];\n var block, keyfn, idx, pfx, curPfx, curStart, start, end;\n\n while(prefixBlocks.length > 0){\n sortedArr = [];\n block = prefixBlocks.pop();\n idx = block[0]; start = block[1]; end = block[2];\n if(idx > pfxlen){ break; }\n if(start === end){ continue; }\n\n keyfn = partial(_keyfn, [idx]);\n counts = countItems(stringArr, keyfn, start, end);\n counts = init0(counts);\n counts = accumulate(counts);\n\n for(i=start; i<=end; i++){\n k = keyfn(stringArr[i]);\n sortedArr[counts[k]] = stringArr[i];\n counts[k]++;\n }\n\n // copy sorted items back to original array (sub-range now sorted)\n for(i=0; i<sortedArr.length; i++){\n stringArr[i+start] = sortedArr[i];\n }\n\n if(idx < pfxlen){\n curStart = start;\n curPfx = stringArr[start].slice(0, idx+1);\n for(i=start; i<=end; i++){\n pfx = stringArr[i].slice(0, idx+1);\n if(pfx !== curPfx){\n if(curStart !== i-1){ // don't add a 1-element sub-range\n prefixBlocks.push([idx+1, curStart, i-1]);\n }\n curStart = i;\n curPfx = stringArr[i].slice(0, idx+1);\n }\n }\n if(curStart !== end){ // don't add a 1-element sub-range\n prefixBlocks.push([idx+1, curStart, end]);\n }\n }\n\n }\n\n return stringArr;\n}",
"function shortestWord(string) {\n var arrayOfString = string.split(' ');\n var myMin = arrayOfString[0];\n each(arrayOfString, function(elem, i) {\n if (elem.length < myMin.length) {\n myMin = elem;\n }\n });\n return myMin;\n}",
"function countCharacters(arr) {\n\treturn arr.join(\"\").length;\n}",
"function longest(A, B, C) {\n const heap = new Heap(\n [\n { char: \"a\", count: A },\n { char: \"b\", count: B },\n { char: \"c\", count: C }\n ],\n null,\n (a, b) => {\n if (a.count !== b.count) {\n return a.count - b.count;\n }\n return a.char > b.char;\n }\n );\n const nextValidIndex = new Array(3).fill(0);\n let res = \"\";\n const temp = []\n while (heap.length > 0) {\n let { char, count } = heap.pop(); // The most frequent one\n let charIdx = charToNum(char);\n let nextIndex = res.length;\n if (nextValidIndex[charIdx] <= nextIndex) {\n // Valid index\n res += char;\n // Update count\n if (count > 1) {\n heap.push({ count: count - 1, char });\n }\n // Update next valid index\n if (nextIndex !== 0 && res[nextIndex - 1] === char) {\n // next one cant be the same char\n nextValidIndex[charIdx] = nextIndex + 2;\n }\n // Push back the non-valid\n while(temp.length) {\n heap.push(temp.pop())\n }\n } else {\n // Not valid\n temp.push({ char, count });\n }\n }\n\n return res;\n}",
"function timesOfMostFreqChar(chars) {\n let joined = chars.split(\" \").join(\"\").split(\"\");\n\n let maxFreq = 0,\n freq = {},\n maxChar = \"\";\n joined.forEach((char) => {\n if (freq[char]) {\n freq[char]++;\n if (freq[char] > maxFreq) {\n maxFreq = freq[char];\n maxChar = char;\n }\n } else freq[char] = 1;\n });\n\n return maxChar + \" is the max letter frequncy :\" + maxFreq + \" times \\n\";\n}",
"function reducer2(a, e) {\n var summ = 0;\n if (typeof a == \"string\") { // this handles the initial case where the first element is used\n summ = a.length; // as the starting value.\n }\n else {\n summ = a;\n }\n return summ + countLetters(e);\n}",
"function longest_substring_with_k_distinct(str, k) {\n if( k === 0 || str.length === 0) return 0;\n // TODO: Write code here\n let windowStart = 0,\n windowEnd = 0,\n maxLen = 0,\n frequency = {};\n\n \n for(windowEnd; windowEnd < str.length; windowEnd++){\n if(!(str[windowEnd] in frequency)){\n frequency[str[windowEnd]] = 0;\n }\n frequency[str[windowEnd]] += 1;\n // console.log(frequency[]);\n }\n console.log(frequency['a']);\n maxLen = Math.max(maxLen, windowEnd - windowStart);\n\n return maxLen;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
unlink email with default strategy | unlinkEmail(email, code, password, callback) {
password = AccountsEx._hashPassword(password);
callback = ensureCallback(callback);
return AccountsEx._unlinkEmail({type: 'default', email, code, password}, callback);
} | [
"_unlinkEmail(options, callback) {\n Meteor.call(prefix + '_unlinkEmail', options, ensureCallback(callback));\n }",
"deleteEmail() {\n\n \n switch (this.view) {\n\n // move item to trash\n case \"inbox\":\n this.$set(this.selectedEmail, \"deleted\", true);\n this.selectedEmail = \"\";\n break;\n // move item back from trash to inbox\n case \"trash\":\n this.$set(this.selectedEmail, \"deleted\", false);\n this.selectedEmail = \"\";\n break;\n }\n }",
"_unlinkPhone(options, callback) {\n Meteor.call(prefix + '_unlinkPhone', options, ensureCallback(callback));\n }",
"function remove_archive(email_id) {\n fetch('/emails/'+email_id, {\n method: 'PUT',\n body: JSON.stringify({\n archived: false,\n })\n })\n load_mailbox('inbox')\n console.log(\"Archived Removed\")\n}",
"function unlinkHookFn () {\n fqHookFilename = fqProjDirname + '/.git/hooks/pre-commit';\n fsObj.unlink( fqHookFilename, function ( error_data ) {\n // Ignore any error\n eventObj.emit( '07LinkHook' );\n });\n }",
"function unlinkPrevious(callback) {\n fs.unlink(path.resolve(yeoman, 'foundation'), function(err) {\n if (err) return console.log('unlink error:', err);\n console.log('Previous version of yeoman-foundation successfully unlinked...');\n return callback();\n });\n}",
"onDeletingTrash() {\r\n this._update('Deleting trash emails...');\r\n }",
"function deleteEmail(encoding, i) {\n\n if (confirm(\"Are you sure you want to delete this email?\") == true) {\n var name = getNameFromEncoding(encoding);\n $.post(\n SERVER_URL + \"/deleteEmail\",\n createNameIndexReq(name, i),\n runOnSuccessFulDeletion\n ).fail(alert(\"could not delete email\"));\n reloadPage(name);\n }\n\n function runOnSuccessFulDeletion(data) {\n if (DEBUG) {\n alert(data.message);\n }\n }\n\n}",
"function stopAttLink() {\n require(['io.ox/core/extPatterns/links'], function (links) {\n new links.Action('io.ox/mail/compose/attachment/shareAttachmentsEnable', {\n id: 'stop',\n index: 1,\n requires: function (e) {\n try {\n if (e.baton.view.model.get('encrypt')) { // Do not offer shareAttachments if encrypted\n console.log('stopping');\n e.stopPropagation();\n return false;\n }\n } catch (f) {\n console.log(f);\n }\n return false;\n }\n });\n });\n }",
"function deleteEmail(id) {\n const emailID = id;\n const url = '/email/' + emailID;\n const request = 'DELETE';\n const row = $('a[data-id=\"'+ emailID +'\"]').parents('.table-row');\n\n ajax_requests(url, request, emailID, true, function(result) {\n if(result.status === 200) {\n row.fadeOut('slow', function() {\n $(this).remove();\n });\n console.log(result.status);\n }\n });\n}",
"function doRemove(theurl, response) {\n response.setHeader(\"Content-Type\", \"text/plain\");\n theurl = theurl.substr(7);\n return new Promise((resolve, reject) => {\n fs.unlink(WORKDIRECTORY + theurl.match(FILE)[0], err => {\n // If there is an error, write an error message to the response\n if (err) {\n var errorMessage =\n \"ERROR: could not unlink file \" + theurl.match(FILE)[0];\n\tconsole.log(errorMessage);\n response.statusMessage = errorMessage;\n response.write(errorMessage + '\\n');\n response.statusCode = 403;\n resolve(errorMessage);\n // Else, write a message to the response that the file was removed\n } else {\n var unlinkedMessage =\n \"UNLINK: the URL \" + theurl.match(FILE)[0] + \" was removed.\";\n response.statusCode = 200;\n response.write(unlinkedMessage + '\\n');\n resolve(unlinkedMessage);\n }\n });\n });\n}",
"function deleteEmail(id) {\n $.ajax({\n url: apiUrl + 'contact?id=' + id,\n type: 'DELETE',\n success: () => {\n $('#email_' + id).remove();\n }\n });\n}",
"function removeAttachmentFile(attachment, remove_url) {\n\tvar id = attachment.find(\".AttachmentFiles\");\n\t$.post(remove_url, {'id': id.val()});\n\n\tattachment.remove();\n}",
"forgetMe(resource) {\n let result = this.searchMessages({modelName: MESSAGE, to: resource, isForgetting: true})\n let batch = []\n let ids = []\n result.forEach((r) => {\n let id = utils.getId(r)\n batch.push({type: 'del', key: id})\n ids.push(id)\n })\n let id = utils.getId(resource)\n ids.push(id)\n batch.push({type: 'del', key: id})\n return db.batch(batch)\n .then(() => {\n ids.forEach((id) => {\n this.deleteMessageFromChat(utils.getId(resource), this._getItem(id))\n delete list[id]\n })\n this.trigger({action: 'messageList', modelName: MESSAGE, to: resource, forgetMeFromCustomer: true})\n return this.meDriverSignAndSend({\n object: { [TYPE]: FORGOT_YOU },\n to: { permalink: resource[ROOT_HASH] }\n })\n })\n .catch((err) => {\n debugger\n })\n }",
"static async unstarAll() {\n await this.env.services.rpc({\n model: 'mail.message',\n method: 'unstar_all',\n });\n }",
"writeEmailFile (callback) {\n\t\tconst outputFile = `${this.emailFile}-${Math.random()}.eml`;\n\t\tlet path = Path.join(this.config.inboundEmailServer.inboundEmailDirectory, outputFile);\n\t\tif (FS.existsSync(path)) {\n\t\t\tFS.unlinkSync(path);\n\t\t}\n\t\tFS.writeFile(path, this.emailData, callback);\n\t}",
"function cancelAction(email, ref, type) { \n\tvar message = prompt(\"Cancel Ride: Put the reason as to why the ride was cancelled in the text field below; it will be sent to the user. A reason is not required.\", \"\");\n\tif (message != null) {\n\t\tvar user = ref.child(email);\n\t\tuser.once(\"value\", function(snapshot) {\n\t\t\tvar ts = snapshot.val().timestamp\n\t\t\tuser.update({\"endTime\" : \"Cancelled by Dispatcher\", \"message\" : message});\n\t\t\tvar cancelled = firebase.database().ref().child(\"CANCELLED RIDES\");\n\t\t\tcancelled.child(email + \"_\" + ts).set({ \n\t\t\t\temail: snapshot.val().email,\n\t\t\t\tend: snapshot.val().end,\n\t\t\t\tendTime: \"Cancelled by Dispatcher\",\n\t\t\t\teta: snapshot.val().eta,\n\t\t\t\tmessage: message,\n\t\t\t\tnumRiders: snapshot.val().numRiders,\n\t\t\t\tstart: snapshot.val().start,\n\t\t\t\ttime: snapshot.val().time,\n\t\t\t\ttimestamp: ts,\n\t\t\t\twaitTime: snapshot.val().waitTime,\n\t\t\t\tvehicle: snapshot.val().vehicle,\n\t\t\t});\n\t\t\tuser.remove();\n\t\t});\n\t} //else do not cancel\n}",
"async function deleteFamilyMember(current, email) {\n let sql = `DELETE FROM family WHERE email = ? AND name = ?`;\n await db.query(sql, [email, current]);\n}",
"function prevMsgDelete() {\n message.delete([300])\n .then(msg => console.log(`Deleted message from ${msg.author.username}`))\n .catch(console.error);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
divShowOnly(divHideList,divId) Hide all divs in divHideList and Show divId | function divShowOnly(divHideList,divId) {
//console.log('divShow('+divHideList+','+divId+')');
if ( document.getElementById(divId) ) {
var divHideArray = divHideList.split(",");
for(var i=0; i<divHideArray.length; i++){
divHide(divHideArray[i]);
}
divShow(divId);
} else {
console.warn('document.getElementById('+divId+') == udefined');
}
} | [
"function divShowOnlyInline(divHideList,divId) {\n //console.log('divShow('+divHideList+','+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t\tvar divHideArray = divHideList.split(\",\");\n\t\tfor(var i=0; i<divHideArray.length; i++){\n\t\t\tdivHide(divHideArray[i]);\n\t\t}\n\t\tdivShowInline(divId);\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function divHideShow(divId) {\n //console.log('divHide('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t\tif ( divDisplayState(divId) == 'none' ) {\n\t\t\tdivShow(divId);\n\t\t} else {\n\t\t\tdivHide(divId);\n\t\t}\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function hideAllExcept(elementId) {\n var containerDivs = ['firstContainerDiv', 'secondContainerDiv', 'thirdContainerDiv', 'popUpWindow'];\n for (var containerDiv of containerDivs) {\n document.getElementById(containerDiv).style.display = containerDiv != elementId ? 'none' : 'flex';\n }\n}",
"function toggleDivs(elementToHide, elementToShow)\n{\n elementToHide.style.display = \"none\";\n elementToShow.style.display = \"block\";\n}",
"function divHide(divId) {\n //console.log('divHide('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).style.display = 'none';\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function divShow(divId) {\n //console.log('divShow('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).style.display = 'block';\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function hideAllBoxes(){\n\tfor (var i = 0; i < divArray.length; i++)\n\t\tdocument.getElementById(divArray[i]).style.display = \"none\";\n}",
"function HideElements(theArray){\n\tfor(var i=0; i < theArray.length; i++){\n\t var oElmnt;\n\t oElmnt = document.getElementById(theArray[i]);\n\t if(oElmnt != null || oElmnt != undefined){\n\t\t oElmnt.style.display = \"none\";\n\t\t oElmnt.style.position = \"relative\";\n\t\t}\n }\t\n}",
"function showHideCombine(flag) {\n var hidDiv = document.getElementById(\"hiddenDiv\");\n var Result = \"\";\n if (flag) {\n hidDiv.style.display ='block';\n \n } else {\n hidDiv.style.display ='none';\n } \n} // end of \"showHideCombine\" function",
"showItem(aItemOrId, aShow) {\r\n var item = typeof (aItemOrId) == \"string\" ? document.getElementById(aItemOrId) : aItemOrId;\r\n if (item && item.hidden == Boolean(aShow))\r\n item.hidden = !aShow;\r\n }",
"function hideOtherSectionsViaStyle(exceptElem) {\n var sections = document.getElementsByTagName(\"div\");\n for (var i=0; i<sections.length; ++i) {\n if ((sections[i].className == \"section-show\")\n && (sections[i].id != exceptElem)) {\n sections[i].className = \"section-hide\";\n }\n }\n}",
"function showAllBoxes(){\n\tfor (var i = 0; i < divArray.length; i++)\n\t\tdocument.getElementById(divArray[i]).style.display = \"block\";\n}",
"function fn_ShowHideUserMessageDivWithCssClass_common(divId, strDisplayMsg, IsShowHideFlag, strClassName) {\n var objdivId = $(\"#\" + divId);\n objdivId.html(\"<a href='#' class='close' onclick='fn_closeMe(this)' aria-label='close'>×</a>\" + strDisplayMsg);\n if (IsShowHideFlag == true)//show / hide the div\n {\n objdivId.show();\n }\n else {\n objdivId.hide();\n }\n\n try {\n objdivId.removeAttr(\"class\");\n } catch (e) { }\n if (strClassName != \"\") {\n objdivId.attr(\"class\", strClassName);\n }\n\n objdivId.focus();//focusing the div\n}",
"function handleBlockView(id,status='hide') {\n if(status == 'hide') {\n document.getElementById(id).style.display = 'none';\n } else {\n document.getElementById(id).style.display = 'block';\n }\n \n}",
"function divShowInline(divId) {\n //console.log('divShow('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).style.display = 'inline';\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function hideProfilesSettingDiv(theDiv){\n\t$(\"#profileItemSettingsDiv-\"+theDiv).hide();\n}",
"function ShowProcessPanel(bShow){\n $(\".processValuesPanel\").css(\"display\", bShow ? \"block\" : \"none\");\n}",
"function removeShowHide() {\n seminarInfo.each(function () {\n $(this).closest('.flag-seminar-container').removeClass('show');\n $(this).closest('.flag-seminar-container').removeClass('hide');\n });\n }",
"function hidePopups(){\n\tvar keys = document.getElementById(\"keysDiv\");\n\tkeys.style.visibility = \"visible\";\n\tvar len=popupList.length;\n\tfor(var i=0;i<len;i++){\n\t\tdocument.getElementById(popupList[i]).style.visibility = \"hidden\";\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deploy A Data Source To An Environment | function deploy(params, cb) {
params.resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + "/data_sources/:id/deploy", params);
params.method = "POST";
params.data = params.dataSource;
mbaasRequest.admin(params, cb);
} | [
"function datasourceForConfig(args)\n{\n\tvar bename;\n\n\tmod_assertplus.object(args);\n\tmod_assertplus.object(args.dsconfig);\n\tmod_assertplus.object(args.log);\n\n\tbename = args.dsconfig.ds_backend;\n\n\tif (bename == 'manta')\n\t\treturn (mod_datasource_manta.createDatasource(args));\n\tif (bename == 'file')\n\t\treturn (mod_datasource_file.createDatasource(args));\n\n\treturn (new VError('unknown datasource backend: \"%s\"', bename));\n}",
"async function setup() {\n // Deploying provider, connecting to the database and starting express server.\n const port = process.env.SERVERPORT ? process.env.SERVERPORT : 8080;\n await lti.deploy({ port });\n\n // Register platform, if needed.\n await lti.registerPlatform({\n url: process.env.PLATFORM_URL,\n name: 'Platform',\n clientId: process.env.PLATFORM_CLIENTID,\n authenticationEndpoint: process.env.PLATFORM_ENDPOINT,\n accesstokenEndpoint: process.env.PLATFORM_TOKEN_ENDPOINT,\n authConfig: {\n method: 'JWK_SET',\n key: process.env.PLATFORM_KEY_ENDPOINT,\n },\n });\n\n // Get the public key generated for that platform.\n const plat = await lti.getPlatform(\n process.env.PLATFORM_URL,\n process.env.PLATFORM_CLIENTID\n );\n console.log(await plat.platformPublicKey());\n}",
"async function get_datasource(basePath, fromAddress) {\n let source = new Datasource(basePath, fromAddress)\n await source.init()\n return source\n}",
"function getDataSource() {\n let config = jsonfile.readFileSync(\"server/config.json\");\n\n return config.dataSource == \"jsonfile\" ? require(\"./JsonFileSource\") : require(\"./MongoDbSource\");\n}",
"function deployDirectory() {\n console.log(chalk.bold('Deploying to BitBucket'));\n _command('npm run deploy-demo', (result) => {\n console.log(chalk.bold('Deployed!'));\n console.log('Site will be visible on ' + chalk.cyan(opts.demoUrl) + ' shortly.');\n\n done();\n });\n }",
"function main() {\n\n setUp(config.mongoURL);\n\n\n if (config.getSourcesFromDB) {\n PodcastSource.getFromDatabase(startRunning);\n } else {\n _.forEach(\n config.XMLSource,\n function(sourceEntry) {\n if (sourceEntry.saveToDB) {\n sourceEntry.save(\n function(err) {\n //intentionally not using a callback from here, \n //we only care enough about the write to log an error\n if (err) {\n winston.error('Error saving source to database. [' + sourceEntry.source + ']', err);\n }\n }\n );\n winston.info('Saving source to database: ' + sourceEntry.source);\n }\n }\n );\n startRunning(null, config.XMLSource);\n }\n\n function startRunning(err, sourcesList) {\n if (err) {\n winston.error(err);\n throw err;\n }\n\n if (!sourcesList.length) {\n winston.warn(\"No sources defined, exiting program.\" + \"\\n\" +\n config.cmdline_help_text);\n return tearDown();\n }\n\n processing.runOnSource(\n sourcesList,\n /**\n * Called when each source has completed scraping, or on an error.\n * @param {Error} err Error encountered, if any\n */\n function mainComplete(err) {\n if (err) {\n throw err;\n } else {\n tearDown();\n }\n }\n );\n }\n }",
"setUpSchema() {\n const { ctx } = this;\n if (!ctx.haveSchema) {\n this.log.info('Schema not set up, setting up now... /n');\n const [schemaProdDeps, schemaDevDeps, schemaScripts] = template\n .createSchema(this, this.newFilePath, this.indexFilePath, {\n importExport: ctx.importExport || true,\n });\n this.config.set({ haveSchema: true });\n this.deps.prod.push(...schemaProdDeps);\n this.deps.dev.push(...schemaDevDeps);\n Object.assign(this.pkgScripts, schemaScripts);\n }\n }",
"function initDb() {\n\n\t\tif(fs.existsSync(path.join(cloudDir ,dbName))){\n\t\t\t//TODO: catch errors\n\t\t\tfs.createReadStream(path.join(cloudDir ,dbName))\n\t\t\t\t.pipe(fs.createWriteStream(path.join(tempDir, dbName)));\n\t\t\n\t\t}\n\t\n\t}",
"function datasourceForName(args)\n{\n\tvar dsconfig, datasource;\n\n\tmod_assertplus.object(args, 'args');\n\tmod_assertplus.object(args.log, 'args.log');\n\tmod_assertplus.object(args.config, 'args.config');\n\tmod_assertplus.string(args.dsname, 'args.dsname');\n\n\tdsconfig = args.config.datasourceGet(args.dsname);\n\tif (dsconfig === null)\n\t\treturn (new VError('unknown datasource: \"%s\"', args.dsname));\n\n\tdatasource = datasourceForConfig({\n\t 'log': args.log,\n\t 'dsconfig': dsconfig\n\t});\n\n\tif (datasource instanceof Error)\n\t\treturn (datasource);\n\n\treturn (datasource);\n}",
"function setupDistBuild(cb) {\n context.dev = false;\n context.destPath = j('dist', context.assetPath);\n del.sync('dist');\n cb();\n}",
"function runPublishScript() {\n\n const script = [];\n\n // merge dev -> master\n script.push(\n \"git checkout dev\",\n \"git pull\",\n \"git checkout master\",\n \"git pull\",\n \"git merge dev\",\n \"npm install\");\n\n // version here to all subsequent actions have the new version available in package.json\n script.push(\"npm version patch\");\n\n // push the updates to master (version info)\n script.push(\"git push\");\n\n // package and publish to npm\n script.push(\"gulp publish:packages\");\n\n // merge master back to dev for updated version #\n script.push(\n \"git checkout master\",\n \"git pull\",\n \"git checkout dev\",\n \"git pull\",\n \"git merge master\",\n \"git push\");\n\n // always leave things on the dev branch\n script.push(\"git checkout dev\");\n\n return chainCommands(script);\n}",
"function deploy(cb) {\n console.log(\"deploying with the role name 'assigner' in metadata ...\");\n var req = {\n fcn: \"init\",\n args: [],\n metadata: new Buffer(\"assigner\")\n };\n if (devMode) {\n req.chaincodeName = chaincodeName;\n } else {\n req.chaincodePath = \"github.com/asset_management_with_roles/\";\n }\n var tx = deployer.deploy(req);\n tx.on('submitted', function (results) {\n console.log(\"deploy submitted: %j\", results);\n });\n tx.on('complete', function (results) {\n console.log(\"deploy complete: %j\", results);\n chaincodeID = results.chaincodeID;\n console.log(\"chaincodeID:\" + chaincodeID);\n return cb();\n });\n tx.on('error', function (err) {\n console.log(\"deploy error: %j\", err.toString());\n return cb(err);\n });\n}",
"function setup(argv, log, cb) {\n var dbFile = argv.d;\n if (!dbFile && !argv.c) {\n cb(new Error('config file or db filename required.'));\n return;\n } else if (!dbFile) {\n var cfgFileName = argv.c;\n var stats = fs.statSync(cfgFileName);\n if (!stats || !stats.isFile()) {\n cb(new Error('config file cannot be found.'));\n return;\n }\n var cfg = null;\n try {\n cfg = JSON.parse(fs.readFileSync(cfgFileName));\n } catch (e) {\n cb(e);\n return;\n }\n if (!cfg.dbFile) {\n cb(new Error('Config file contains no dbFile field.'));\n return;\n }\n dbFile = cfg.dbFile;\n }\n\n var d = new db.Db({\n 'fileName': dbFile,\n 'log': log\n });\n\n d.on('ready', function () {\n cb(null, d);\n });\n\n d.on('error', function (err) {\n cb(err);\n });\n}",
"function deploy(cb) {\n console.log(\"deploying with the role name 'assigner' in metadata ...\");\n var req = {\n fcn: \"init\",\n args: [],\n metadata: \"assigner\"\n };\n if (networkMode) {\n req.chaincodePath = \"github.com/asset_management_with_roles/\";\n } else {\n req.chaincodeName = \"asset_management_with_roles\";\n }\n var tx = admin.deploy(req);\n tx.on('submitted', function (results) {\n console.log(\"deploy submitted: %j\", results);\n });\n tx.on('complete', function (results) {\n console.log(\"deploy complete: %j\", results);\n chaincodeID = results.chaincodeID;\n return assign(cb);\n });\n tx.on('error', function (err) {\n console.log(\"deploy error: %j\", err.toString());\n return cb(err);\n });\n}",
"createDataSources (config) {\n // Save and compare previous sources\n this.last_config_sources = this.config_sources || {};\n this.config_sources = config.sources;\n let last_sources = this.sources;\n let changed = [];\n\n // Parse new sources\n this.sources = {}; // clear previous sources\n for (let name in config.sources) {\n if (JSON.stringify(this.last_config_sources[name]) === JSON.stringify(config.sources[name])) {\n this.sources[name] = last_sources[name];\n continue;\n }\n\n // compile any user-defined JS functions\n config.sources[name] = compileFunctionStrings(config.sources[name]);\n\n let source;\n try {\n source = DataSource.create(Object.assign({}, config.sources[name], {name}), this.sources);\n }\n catch(e) {\n continue;\n }\n\n if (!source) {\n continue;\n }\n this.sources[name] = source;\n changed.push(name);\n }\n\n // Clear tile cache for data sources that changed\n changed.forEach(source => {\n for (let t in this.tiles) {\n if (this.tiles[t].source === source) {\n delete this.tiles[t];\n }\n }\n });\n }",
"function createDeployment_() {\r\n progress = cli.progress('Creating VM');\r\n utils.doServiceManagementOperation(channel, 'createDeployment', dnsPrefix, dnsPrefix,\r\n role, deployOptions, function(error, response) {\r\n progress.end();\r\n if (!error) {\r\n logger.info('OK');\r\n } else {\r\n cmdCallback(error);\r\n }\r\n });\r\n }",
"function deployChaincode() {\n\t// Construct the deploy request\n\tvar deployRequest = {\n\t\t// Path (under $GOPATH/src) required for deploy in network mode\n\t\tchaincodePath: \"crowd_fund_chaincode\",\n\t\t// Function to trigger\n\t\tfcn: \"init\",\n\t\t// Arguments to the initializing function\n\t\targs: [\"key1\", \"key_value_1\"],\n\t};\n\n\t// Trigger the deploy transaction\n\tvar deployTx = app_user.deploy(deployRequest);\n\n\t// Print the successfull deploy results\n\tdeployTx.on('complete', function (results) {\n\t\t// Set the chaincodeID for subsequent tests\n\t\tchaincodeID = results.chaincodeID;\n\t\tconsole.log(util.format(\"Successfully deployed chaincode: request=%j, \" +\n\t\t\t\"response=%j\" + \"\\n\", deployRequest, results));\n\t\t// The chaincode is successfully deployed, start the listener port\n\t\tstartListener();\n\t});\n\tdeployTx.on('error', function (err) {\n\t\t// Deploy request failed\n\t\tconsole.log(util.format(\"ERROR: Failed to deploy chaincode: request=%j, \" +\n\t\t\t\"error=%j\", deployRequest, err));\n\t\tprocess.exit(1);\n\t});\n}",
"function loadTasks(env, args, shouldDeploy, cb){\n var didLoad = config.load(args.file);\n var tasks = config.getTasks();\n if(!tasks) mess.warning(\"No tasks were found/specified\");\n if(!didLoad || !tasks){\n mess.yesOrNo('Would you like to deploy anyways?', rl, (yes) => {\n if(yes){\n return deployApplication(env, shouldDeploy);\n }else{\n endProcess();\n }\n })\n }else{\n return cb(tasks);\n }\n}",
"function runImportSQLDatabase(){\n g.mockDataSource = 'sqlMockData';\n //Just recreate the worksheet using the SQL database source\n createSampleTable(g.mockDataSource); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the number of bounding spheres in the bounding spheres array that are actually being used. | SetBoundingSphereCount() {} | [
"SetBoundingDistances() {}",
"set boundingBoxMode(value) {}",
"function addSpheres() {\n // Visible grid sphere\n const gridSphere = createSphereOfQuadsWireframe(gridRadius, 36, 18, \"#2e2e2e\", true, true);\n gridSphere.name = 'gridSphere';\n scene.add(gridSphere);\n // Clickable inverted sphere (transparent hollow cube)\n const invertedSphere = createInvertedSphere(gridRadius, 36, 18)\n invertedSphere.name = 'clickSphere';\n scene.add(invertedSphere);\n}",
"function setSpreadSize(size) {\n\tspreadSize\t\t= size;\n\n\tgrid\t\t\t= new THREE.GridHelper(spreadSize, spreadSize);\n\tgrid.position.x\t= spreadSize / 2;\n\tgrid.position.z\t= spreadSize / 2;\n\tgrid.name\t\t= \"GRID\";\n\tscene.remove(\"GRID\");\n\tscene.add(grid);\n\n\tlocalGrid\t\t\t\t= new THREE.GridHelper(spreadSize / 5, spreadSize);\n\tlocalGrid.position.x\t= spreadSize / 2;\n\tlocalGrid.position.z\t= spreadSize / 2;\n\tlocalGrid.name\t\t\t= \"LOCALGRID\";\n\tscene.remove(\"LOCALGRID\");\n\tscene.add(localGrid);\n\n\taxes\t\t= new THREE.AxesHelper(spreadSize);\n\taxes.position.set(0, 0.05, 0);\n\taxes.name\t= \"AXES\";\n\tscene.remove(\"AXES\");\n\tscene.add(axes);\n}",
"configure(width, height)\n {\n // use the width passed by the user\n // but check the height, each team should have at least 200 px of space\n this.width = width\n let len = Object.keys(this.teams).length;\n if (len * 200 > height)\n {\n this.height = len * 200 + 100;\n }\n else\n {\n this.height = height;\n }\n\n this.app.renderer.autoResize = true;\n this.app.renderer.resize(this.width, this.height);\n }",
"function generateNSpheres(N, R) {\n\n var r_margin= R * 1.2\n var D = 2 * R ;\n var d_margin = 2 * R * 1.5 ; // 50% margin between 2 objects\n var elem_on_one_line = parseInt(1 / d_margin);\n var maxIndex = elem_on_one_line ** 2;\n const spheres = new Array();\n\n if (maxIndex < N) {\n throw new Error(\"Impossible situation, too many or too big spheres.\");\n }\n\n // Let's keep a bound on the computational cost of this:\n if (maxIndex > 1000000) {\n throw new Error(\"Radius is too small\");\n }\n\n occupied = [];\n // reservation of N values for N spheres\n for (var i = 0; i < N; i++) {\n occupied[i] = true;\n }\n // fill the rest of the array with false\n for (i = N; i < maxIndex; i++) {\n occupied[i] = false;\n }\n // Shuffle array so that occupied[i] = true is distributed randomly\n shuffleArray(occupied);\n var count = 0;\n for (var i = 0; i < maxIndex; i++) {\n if (occupied[i]) {\n // Random velocity. TODO: take velocity from Boltzmann distribution at set temperature!\n vx = (1 - 2 * Math.random()) * 0.3;\n vy =(1 - 2 * Math.random()) * 0.3;\n x = r_margin + d_margin * Math.floor(i / elem_on_one_line);\n y = r_margin + d_margin * (i % elem_on_one_line);\n sphere = new Sphere(R, 1, x, y, vx, vy, count);\n sphere.setStatus(STATUS_HEALTHY);\n spheres[count] = sphere;\n count++;\n }\n }\n // Setting the first sphere as infected\n spheres[N / 2].setStatus(STATUS_INFECTED)\n return spheres\n}",
"set Mesh(value) {}",
"setColliders() {\n this.physics.add.collider(this.player, this.platforms);\n this.physics.add.collider(this.stars, this.platforms);\n this.physics.add.collider(this.bombs, this.platforms);\n this.physics.add.collider(this.player, this.bombs, this.endGame, null, this);\n this.physics.add.overlap(this.player, this.stars, this.collectStar, null, this);\n }",
"function initializeRadius() {\n for (let i = 0; i < INITIAL_NUMBER_OF_BALLS; i++) {\n let ball = ballArray[i];\n ball.radius = ball.mass / (5 / 3) + 1; //size the radius proportionally to its mass (between 1 and 4)\n }\n}",
"function massOfObjBChange(scope) {\n mass_ball_b = scope.mass_of_b;\n getChild(\"ball_b\").scaleX = 0.5 + (scope.mass_of_b - 1) / 20;\n getChild(\"ball_b\").scaleY = 0.5 + (scope.mass_of_b - 1) / 20;\n ball_b_radius = (getChild(\"ball_b\").image.height * getChild(\"ball_b\").scaleY) / 2;\n}",
"setBoundingBox() {\n /**\n * Array of `Line` objects defining the boundary of the Drawing<br>\n * - using these in `View.addLine` to determine the end points of {@link Line} in the {@link model}\n * - these lines are not added to the `Model.elements` array\n */\n this.boundaryLines = []\n\n // TODO; set these values in main\n\n // top left\n let tlPt = new Point(\"-4\", \"-4\")\n // bottom right\n let brPt = new Point(\"4\", \"4\")\n\n // top right\n let trPt = new Point(brPt.x, tlPt.y)\n // bottom left\n let blPt = new Point(tlPt.x, brPt.y)\n\n let lineN = new Line(tlPt, trPt)\n this.boundaryLines.push(lineN)\n\n let lineS = new Line(blPt, brPt)\n this.boundaryLines.push(lineS)\n\n let lineW = new Line(tlPt, blPt)\n this.boundaryLines.push(lineW)\n\n let lineE = new Line(trPt, brPt)\n this.boundaryLines.push(lineE)\n }",
"function initbricks() {\n bricks = new Array(NROWS);\n for (i=0; i < NROWS; i++) {\n bricks[i] = new Array(NCOLS);\n for (j=0; j < NCOLS; j++) {\n bricks[i][j] = 1;\n }\n }\n }",
"function change_num_to_brick(){\n for (let z = 0; z < arr.length; z++) {\n arr1.push([]);\n brick_pos_x = 69.5; //69.5\n brick_pos_y = 69.5; //69.5\n count = 0;\n for (let x = 0; x < arr[z].length; x++) {\n arr1[z].push([]);\n for (let y = 0; y < arr[z][x].length; y++) {\n count++;\n if (arr[z][x][y] == 1) {\n brick_count++;\n arr1[z][x][y] = new bricks(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;\n }\n if (arr[z][x][y] == 2) {\n brick_count++;\n arr1[z][x][y] = new golden_brick(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;\n }\n if (arr[z][x][y] == 0) {\n arr1[z][x][y] = new no_brick(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;//101\n }\n if (count % 5 == 0) {\n brick_pos_y += 33;\n brick_pos_x = 69.5; //69.5\n }\n } \n } \n arr_len.push(brick_count);\n brick_count = 0\n }\n}",
"function BinaryBoxset(name, x, y, n, size, orientation, isClickable) {\n objects.push(this);\n boxsets.set(name, this);\n\n this.x = ~~x;\n this.y = ~~y;\n this.name = name;\n this.size = size;\n this.orientation = orientation;\n this.boxes = [];\n this.isClickable = isClickable === undefined ? false : isClickable;\n\n let xOffset = orientation == Orientation.HORIZONTAL ? size - border: 0;\n let yOffset = orientation == Orientation.VERTICAL ? size - border: 0;\n\n for (let i = 0; i < n; i++) {\n // After the loop, xMax and yMax will hold the \"size\" of the whole BinaryBoxset\n this.xMax = this.x + xOffset * i;\n this.yMax = this.y + yOffset * i;\n this.boxes.push(new BinaryBox(this.xMax, this.yMax, this.size, this.isClickable));\n }\n }",
"function addSphere() {\r\n sphereNum += 1;\r\n \r\n // Generate random position of particle\r\n var x = Math.random() * 2.4 - 1.2;\r\n var y = Math.random() * 2.4 - 1.2;\r\n var z = Math.random() * 2.4 - 1.2;\r\n \r\n pos.push(vec3.fromValues(x, y, z));\r\n \r\n // Generate random velocity of particle\r\n x = Math.random() * 0.1 + 0.05;\r\n y = Math.random() * 0.1 + 0.05;\r\n z = Math.random() * 0.1 + 0.05;\r\n \r\n vel.push(vec3.fromValues(x, y, z));\r\n \r\n // Keep track of where this sphere was created\r\n birth.push(time);\r\n}",
"setFreeBets (freeBets = []) {\n this.memory.set(this.getName(\"freeBets\"), freeBets);\n\n if(freeBets){\n this.memory.set(this.getName(\"freeBetsLast\"), freeBets);\n }\n }",
"function setNumVotersPerElection(aNumVoters) {\n numVotersPerElection = parseInt(aNumVoters);\n } // setNumVotersPerElection",
"function setSizePerElection(aSize) {\n sizePerElection = parseInt(aSize);\n } // setResolution",
"function increaseVertexCount() {\n let vertexCount = retrieveVertexCount();\n if (vertexCount < 100) {\n ++vertexCount;\n document.getElementById(\"vertices\").value = vertexCount.toString();\n document.getElementById(\"vertices\").dispatchEvent(new Event(\"change\"));\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Listener for player state changes. Calls getTime every second. | function onPlayerStateChange(event) {
if (event.data === YT.PlayerState.PLAYING) {
getTime();
} else if (event.data === YT.PlayerState.ENDED || event.data === YT.PlayerState.PAUSED){
clearInterval(getTime);
}
} | [
"function onTimeUpdate(e) {\n var newTime = Math.floor(video.currentTime);\n if (newTime != timeInt) {\n timeInt = newTime;\n time_str = toTimeString(timeInt);\n updateTimeBar();\n }\n}",
"function setCurrentTime() {\n\t\tvar total = player.currentTime;\n\t\tcurrentTimeElement.innerHTML = timeFormat(total);\n\t}",
"updateVideoTime(videoPlayer, time) {\n videoPlayer.currentTime = time;\n \n }",
"function updateTime() {\n if (trackerTime != 0) {\n // Update the time\n trackerInputBox.value = trackerTime--;\n } else {\n trackerInputBox.value = null;\n myVideo.pause();\n clearInterval(refreshIntervalId);\n\n // We want to make sure that the last interval is scored.\n // In order to trigger this, we need to make sure that another key is pressed.\n // However, it can not be the same as the last key that was pressed.\n // However, we can short cut this by adding an additional boolean\n isScoringEnd = true;\n keydownHandlers[lastScoredBehaviour.key]();\n isScoringEnd = false;\n\n scoringTabActive = false;\n lastScoredBehaviour = undefined;\n currentBehaviorOutput.innerHTML = 'No Current Behaviour Being Scored';\n }\n}",
"function onTimeupdate(){\n //if the video has finished\n if ( this.currentTime >= this.duration ){\n //if we are offering e-mail sharing\n if (configHandler.get('showLocalShare')){\n var vidElem = document.getElementById('videoReview');\n //if we have not shown the e-mail option yet\n if (haveShownShare === false ){\n //remember that we have shown it\n haveShownShare = true;\n //transition in the other UI elements\n var container = document.getElementById('videoReviewContainer');\n container.classList.add('share');\n var btn = document.getElementById('breakButton');\n btn.classList.remove('enabled');\n btn.classList.add('disabled');\n vidElem.muted = true;\n //play the audio after the e-mail option\n // has transitioned in\n if (soundPlayer.exists()){\n soundTimeout = setTimeout(function(){\n soundPlayer.play();\n }, 1000);\n }\n }\n //replay the video\n vidElem.currentTime = 0;\n vidElem.play();\n } else {\n //if we are not offering e-mail sharing\n // just transition to the thank you screen\n window.events.dispatchEvent(new Event('special'));\n }\n }\n }",
"function updatePlayer()\n{\n if (tillPlayed)\n {\n song.play();\n song.currentTime = tillPlayed;\n }\n else\n {\n song.play();\n setCookie('timePlayed', \"0\");\n }\n}",
"timeout(){\n\n\t\tdocument.querySelector(\"audio\").play();\n\n\t\tif (this.state.currentType ===\"session\"){\n\t\t\t\t\tthis.setState({\n\t\t\t\t\t\ttimeLeft:this.state.breakLength * 60, \n\t\t\t\t\t\tcurrentType:\"break\"\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.setState({\n\t\t\t\t\t\ttimeLeft:this.state.sessionLength * 60, \n\t\t\t\t\t\tcurrentType:\"session\"\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\tthis.time();\n\t\t\n\t}",
"function update_timer() {\n seconds = Math.floor(game.time.time / 1000);\n milliseconds = Math.floor(game.time.time);\n elapsed = game.time.time - starting_time;\n}",
"function updateTime() {\n const datetime = tizen.time.getCurrentDateTime();\n const hour = datetime.getHours();\n const minute = datetime.getMinutes();\n const second = datetime.getSeconds();\n\n const separator = second % 2 === 0 ? \":\" : \" \";\n\n $(\"#time-text\").html(padStart(hour.toString()) + separator + padStart(minute.toString()));\n\n // Update the hour/minute/second hands\n rotateElements((hour + (minute / 60) + (second / 3600)) * 30, \"#hands-hr-needle\");\n rotateElements((minute + second / 60) * 6, \"#hands-min-needle\");\n clearInterval(interval);\n if (!isAmbientMode) {\n let anim = 0.1;\n rotateElements(second * 6, \"#hands-sec-needle\");\n interval = setInterval(() => {\n rotateElements((second + anim) * 6, \"#hands-sec-needle\");\n anim += 0.1;\n }, 100);\n }\n }",
"function update(){\n\tvlc.status().then(function(status) {\n\t\tvar newPlaying={\n\t\t state: escapeHtml(status.artist+\" - \"+status.album),\n\t\t details: escapeHtml(status.title),\n\t\t largeImageKey: \"vlc\",\n\t\t smallImageKey: status.state,\n\t\t instance: true,\n\t\t}\n\t\tif(newPlaying.state!==nowPlaying.state || newPlaying.details!==nowPlaying.details || newPlaying.smallImageKey!==nowPlaying.smallImageKey){\n\t\t\tconsole.log(\"Changes detected; sending to Discord\")\n\t\t\tif(status.state===\"playing\"){\n\t\t\t\tnewPlaying.startTimestamp=Date.now()/1000\n\t\t\t\tnewPlaying.endTimestamp=parseInt(parseInt(Date.now()/1000)+(parseInt(status.duration)-parseInt(status.time)))\n\t\t\t\tclient.updatePresence(newPlaying);\n\t\t\t}else{\n\t\t\t\tclient.updatePresence(newPlaying);\n\t\t\t}\n\t\t\tdelete newPlaying.startTimestamp\n\t\t\tdelete newPlaying.endTimestamp\n\t\t\tnowPlaying=newPlaying\n\t\t}\n\t});\n}",
"function e_timer() {\n if (!localStream)\n getVideo();\n\n if (peerConnection == null) {\n f_showTextMessage(\"Not connected\")\n if (started) start(true);\n }\n else\n f_showTextMessage(peerConnection.iceConnectionState);\n}",
"handleDurationchange() {\n if (this.player_.duration() === Infinity) {\n this.startTracking();\n } else {\n this.stopTracking();\n }\n }",
"updateTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n\r\n // divide by 1000 to get it into seconds\r\n this.time = (this.timeAtThisFrame - this.timeAtFirstFrame) / 1000.0;\r\n\r\n this.deltaTime = (this.timeAtThisFrame - this.timeAtLastFrame) / 1000.0;\r\n this.timeAtLastFrame = this.timeAtThisFrame;\r\n\r\n // update and set our scene time uniforms\r\n this.t = this.time / 10;\r\n this.dt = this.deltaTime;\r\n }",
"startTracking() {\n if (this.isTracking()) {\n return;\n }\n\n // If we haven't seen a timeupdate, we need to check whether playback\n // began before this component started tracking. This can happen commonly\n // when using autoplay.\n if (!this.timeupdateSeen_) {\n this.timeupdateSeen_ = this.player_.hasStarted();\n }\n\n this.trackingInterval_ = this.setInterval(this.trackLive_, 30);\n this.trackLive_();\n\n this.on(this.player_, 'play', this.trackLive_);\n this.on(this.player_, 'pause', this.trackLive_);\n\n // this is to prevent showing that we are not live\n // before a video starts to play\n if (!this.timeupdateSeen_) {\n this.one(this.player_, 'play', this.handlePlay);\n this.handleTimeupdate = () => {\n this.timeupdateSeen_ = true;\n this.handleTimeupdate = null;\n };\n this.one(this.player_, 'timeupdate', this.handleTimeupdate);\n }\n }",
"_update() {\n console.log(\"UPDATE:\" + this.currentTurn);\n // on vérifie toujours en premier lieu l'état de validité\n if (!this.isValid()) {\n this._terminate();\n } else {\n\n switch (this.state) {\n case GameStates.Starting: {\n this._starting();\n }\n break;\n\n case GameStates.NextPlayer: {\n this._nextPlayer();\n }\n break;\n\n case GameStates.Picking: {\n this._picking();\n }\n break;\n\n case GameStates.Drawing: {\n this._drawing();\n }\n break;\n\n case GameStates.Ended: {\n this._ended();\n }\n break;\n\n case GameStates.Terminating: {\n this._terminate();\n }\n break;\n }\n\n }\n this.sendState();\n }",
"function updateTime() {\n let now = new Date();\n let hour = now.getHours();\n let mins = now.getMinutes();\n let sec = now.getSeconds();\n \n syncAnalogClock(hour, mins, sec);\n syncDigitalClock24Hours(hour, mins, sec);\n syncDigitalClock12Hours(hour, mins, sec);\n}",
"function is_playing() {\n return player.getPlayerState() == 1;\n}",
"function update() {\n\tchangeSpeed(game_object);\n\tchangeLivesOfPlayer(game_object);\n\thackPlayerScore(game_object);\n}",
"function updateTillPlayed()\n{\n setCookie('timePlayed', song.currentTime);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.