query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Gets the closest th element to hover. | _getClosestThToHover(event) {
const that = this,
x = event.clientX,
headerCellElements = Array.from(that.$.tableContainer.querySelectorAll('th[data-field]:not(.smart-pivot-table-total-header)'));
let closest, closestDistance, side;
for (let i = 0; i < headerCellElements.length; i++) {
const currentCell = headerCellElements[i];
if (!currentCell || this._dragDetails.Item === currentCell) {
continue;
}
const rect = currentCell.getBoundingClientRect(),
leftDistance = Math.abs(x - rect.left),
rightDistance = Math.abs(x - rect.right),
bestHorizontalDistance = Math.min(leftDistance, rightDistance);
if (closestDistance === undefined || bestHorizontalDistance < closestDistance) {
closest = currentCell;
closestDistance = bestHorizontalDistance;
side = leftDistance < rightDistance ? 'left' : 'right';
}
else {
break;
}
}
if (closest) {
closest.classList.add(side);
}
return closest;
} | [
"function retrieveNearestRow(element) {\n // find nearest row\n var nearestRow = $(element).closest(\".row.sqs-row\")[0];\n return nearestRow;\n}",
"static getClosestHeading($, headingsSelector, element) {\n const prevElements = $(element).prevAll();\n for (let i = 0; i < prevElements.length; i += 1) {\n const currentElement = $(prevElements[i]);\n if (currentElement.is(headingsSelector)) {\n return currentElement;\n }\n const childHeadings = currentElement.find(headingsSelector);\n if (childHeadings.length > 0) {\n return childHeadings.last();\n }\n }\n if ($(element).parent().length === 0) {\n return null;\n }\n return Page.getClosestHeading($, headingsSelector, $(element).parent());\n }",
"function findTable()\n{\n\treturn $(\"th:contains(Offer)\").first().closest(\"table\");\n}",
"function hoverTd() {\n indexHover = this.index;\n display();\n}",
"function getTableHeader() { return getTable().querySelector('thead tr'); }",
"function getTableHeader () { return getTable().querySelector( 'thead tr' ); }",
"TagHoverElement() {\n\t\tlet { table, cell, row } = this.UI.GetValidHoverElements();\n\t\tif(table === undefined)\n\t\t\treturn;\n\n\t\t((cell.tagName == 'TH' && row) || cell)\n\t\t\t.classList.toggle('Tagged');\n\t}",
"function grabHeadersAndHighlightRelatedCells(element){\n\t\tvar table = $(element).closest(\"table\");\n\t\tif($(table).attr(\"role\") != \"presentation\"){\n\t\t\t//TODO: does role=none matter?\n\t\t\tvar rowIndex = $(element).attr('data-tANDI508-rowIndex');\n\t\t\tvar rowMember = $(element).attr(\"data-tANDI508-rowMember\");\n\t\t\tvar colIndex = $(element).attr('data-tANDI508-colIndex');\n\t\t\tvar colMember = $(element).attr(\"data-tANDI508-colMember\");\n\t\t\tvar headers = $.trim($(element).attr(\"headers\"));\n\t\t\tvar idsArray, referencedId, referencedElement;\n\t\t\t//Find Related <th> cells\n\t\t\t//==HEADERS/ID MODE==//\n\t\t\tif((mode == \"headers/id mode\") && headers){\n\t\t\t\tidsArray = headers.split(\" \");\n\t\t\t\tfor (var x=0;x<idsArray.length;x++){\n\t\t\t\t\t//Can the id be found somewhere on the page?\n\t\t\t\t\treferencedId = andiUtility.escapeCssCharactersInId(idsArray[x]);\n\t\t\t\t\treferencedElement = $(\"#\"+referencedId);\n\t\t\t\t\t\n\t\t\t\t\tif($(referencedElement).html() !== undefined){\n\t\t\t\t\t\tif($(referencedElement).is(\"th\") || $(referencedElement).is(\"td\")){\n\t\t\t\t\t\t\tassociatedThText += andiUtility.formatForHtml(andiUtility.getTextOfTree($(referencedElement))) + tANDI.associatedThDelimeter;\n\t\t\t\t\t\t\t$(referencedElement).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//==SCOPE MODE==//\n\t\t\telse if(mode == \"scope mode\"){\n\t\t\t\tif($(element).is(\"td\")){\n\t\t\t\t\t//Highlight associating <th> for this <td>\n\t\t\t\t\t$(table).find(\"th.ANDI508-element\").filter(':visible').each(function(){\n\t\t\t\t\t\t//get associated th from col\n\t\t\t\t\t\tif(index_greaterThan(rowIndex, $(this).attr(\"data-tANDI508-rowIndex\"))\n\t\t\t\t\t\t&& index_match(colIndex, $(this).attr(\"data-tANDI508-colIndex\"))\n\t\t\t\t\t\t&& !index_match(rowIndex, $(this).attr(\"data-tANDI508-rowIndex\")))\n\t\t\t\t\t\t{//add associatedThText and highlight the cell from whence it came\n\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\tassociatedThText += andiUtility.formatForHtml(andiUtility.getTextOfTree($(this))) + tANDI.associatedThDelimeter;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//get associated th from row\n\t\t\t\t\t\tif(index_greaterThan(colIndex, $(this).attr(\"data-tANDI508-colIndex\"))\n\t\t\t\t\t\t&& index_match(rowIndex, $(this).attr(\"data-tANDI508-rowIndex\"))\n\t\t\t\t\t\t&& !index_match(colIndex, $(this).attr(\"data-tANDI508-colIndex\")))\n\t\t\t\t\t\t{//add associatedThText\n\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\tassociatedThText += andiUtility.formatForHtml(andiUtility.getTextOfTree($(this))) + tANDI.associatedThDelimeter;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Highlight associating <th> and <td> for this th\n\t\t\tif($(element).is(\"th\")){\n\t\t\t\tvar scope = $(element).attr(\"scope\");\n\t\t\t\tvar id = $(element).attr(\"id\");\n\t\t\t\tif((mode == \"scope mode\")){\n\t\t\t\t\t$(table).find(\"th.ANDI508-element,td.ANDI508-element\").filter(':visible').each(function(){\n\t\t\t\t\t\tif(scope){\n\t\t\t\t\t\t\t//th has scope\n\t\t\t\t\t\t\tif((scope == \"col\" || scope == \"colgroup\")\n\t\t\t\t\t\t\t\t&& !index_greaterThan(rowIndex, $(this).attr(\"data-tANDI508-rowIndex\"))\n\t\t\t\t\t\t\t\t&& index_match(colIndex,$(this).attr(\"data-tANDI508-colIndex\")))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t//alert(rowIndex+\" \"+$(this).attr(\"data-tANDI508-rowIndex\"));\n\t\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if((scope == \"row\" || scope == \"rowgroup\")\n\t\t\t\t\t\t\t\t&& !index_greaterThan(colIndex, $(this).attr(\"data-tANDI508-colIndex\"))\n\t\t\t\t\t\t\t\t&& index_match(rowIndex,$(this).attr(\"data-tANDI508-rowIndex\")))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t//th has no scope\n\t\t\t\t\t\t\t//**Assumed associations - this is where it gets sketchy**\n\t\t\t\t\t\t\tif($(this).is(\"td\")){\n\t\t\t\t\t\t\t\tif(index_match(colIndex, $(this).attr(\"data-tANDI508-colIndex\")) || index_match(rowIndex,$(this).attr(\"data-tANDI508-rowIndex\")))\n\t\t\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//No scope assumptions relating to other th\n\t\t\t\t\t\t\telse if($(this).is(\"th\")){\n\t\t\t\t\t\t\t\tif(rowIndex == \"0\"\n\t\t\t\t\t\t\t\t\t&& index_match(colIndex,$(this).attr(\"data-tANDI508-colIndex\"))\n\t\t\t\t\t\t\t\t\t&& !index_greaterThan(rowIndex, $(this).attr(\"data-tANDI508-rowIndex\")))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse if((mode == \"headers/id mode\") && id){//might have headers attributes pointing to this <th>\n\t\t\t\t\t$(table).find(\"th.ANDI508-element,td.ANDI508-element\").filter(':visible').each(function(){\n\t\t\t\t\t\theaders = $(this).attr(\"headers\");\n\t\t\t\t\t\tif(headers){\n\t\t\t\t\t\t\tidsArray = headers.split(\" \");\n\t\t\t\t\t\t\tfor (var x=0;x<idsArray.length;x++){\n\t\t\t\t\t\t\t\tif(id==idsArray[x]){\n\t\t\t\t\t\t\t\t\t$(this).addClass(\"tANDI508-highlight\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function findHoveredElement(event) {\n if (mode === 'content') return event.target\n\n const element = isInElement(event, event.target);\n if (element) return element\n\n return event.target\n }",
"function getTableHeader() {\n return getTable().querySelector( 'thead tr' )\n }",
"function getCellForHeader($rowElement, headerText) {\n var $matchingHeader =\n $(\"#balancesTable thead th div:contains('\" + headerText + \"')\");\n if ($matchingHeader.length == 0)\n return null;\n var index = $matchingHeader.closest(\"th\").prevAll().length;\n return $($rowElement).find(\"td:eq(\" + index + \")\");\n}",
"function getAvailabilityHeaderTR(rowInAvailabilityTable)\r\n{\r\n return rowInAvailabilityTable.parentNode.rows[0];\r\n}",
"function closest(el, selector) {\n while (el) {\n if (selectorMatches(el, selector)) {\n break;\n }\n el = el.parentElement;\n }\n return el;\n}",
"function retrieveRowParent(element) {\n var nearestRowParent = $(element).parent()[0];\n return nearestRowParent;\n\n}",
"get headerCell() {\n return this.grid.headerCellList.find((header) => header.column === this);\n }",
"function getMouseoverElement() {\n\tvar items = document.querySelectorAll( \":hover\" );\n\n\tif(items.length > 0) {\n\t\titem = items[items.length - 1];\n\t\treturn item;\n\t}\n\treturn null;\n}",
"function toggleRow() {\n /* hovering for ipet tables */\n trIndex = $(this).index()+index;\n $(\"#\"+name+'_wrapper table.dataTable').each(function(index) {\n row = $(this).find(\"tr:eq(\"+trIndex+\")\")\n row.toggleClass(\"hover\");\n row.each(function(index) {\n $(this).find(\"td\").toggleClass(\"hover\");\n });\n });\n }",
"function getDragAfterElement(y) {\n // an array of all the rank-rows except for the one being dragged\n const rankRows = [...rankList.querySelectorAll(\".rank-row:not(.dragging)\")]\n return rankRows.reduce((closest, child) => {\n // the bounding box of each rank-row\n const box = child.getBoundingClientRect(); \n // the vertical distance between the mouse and the middle of the box\n const offset = y - box.top - box.height/2;\n // if offset is less than 0, there is at least one rank-row after the dragged rank-row\n // return the rank-row with the largest offset (closest rank-row after the dragged one)\n if (offset < 0 && offset > closest.offset) {\n return {offset: offset, element: child}\n // else return the current closest \n } else {\n return closest;\n }\n }, {offset: Number.NEGATIVE_INFINITY} ).element;\n}",
"function cellHover(e) {\n var cell = $(this).closest('.cell');\n if (!cell.hasClass('disabled')) {\n\n if (ws !== null) {\n cell.addClass('hover');\n ws.send(JSON.stringify({\n message_type: 'cell_hover',\n cell_id: cell.data('id'),\n }));\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
addButton(label) take in a string and create a button with that string as the label | function addButton(label) {
var $button = $("<div class='guess'></div>").text(label).button().click(handleGuess).removeClass("ui-corner-all");
$('.btn-wrapper').append($button);
} | [
"addButton(text, parent = this.$controls) {\n return $(document.createElement('button')).text(text).appendTo(parent);\n }",
"function addButton(label) {\n // Creating a guess class that will be added to the HTML body\n // Said class will contain an animal name due to the 'label' argument\n let $div = $('<div></div>');\n $div.addClass('guess');\n $div.text(label);\n $div.button();\n $div.appendTo('body');\n $div.on('click', handleGuess);\n}",
"addButton(text, parent = this.$controls) {\n return $(document.createElement('button'))\n .text(text)\n .appendTo(parent)\n }",
"function new_button(label)\n {\n return jQuery('<button />')\n .css(options.buttonStyle)\n .html(label);\n }",
"function new_button(label)\r\n\t\t{\r\n\t\t\treturn jQuery('<button />')\r\n\t\t\t\t.css(options.buttonStyle)\r\n\t\t\t\t.html(label);\r\n\t\t}",
"function createTextButton(parent, label, id) {\n var button = document.createElement('button');\n button.innerHTML = label;\n button.id = id;\n parent.appendChild(button);\n return button;\n }",
"function addButton(label) {\n let $createButton = $('<div></div>');\n $createButton.addClass('guess');\n $createButton.text(label);\n $createButton.button();\n $createButton.appendTo('body');\n// check if the player clicked on the right answer\n $createButton.on('click', handleGuess);\n}",
"function createTextButton(parent, label, id, btnClass) {\n var button = document.createElement('button');\n button.className = btnClass;\n button.innerHTML = label;\n button.id = id;\n parent.appendChild(button);\n return button;\n }",
"function addButton(label) {\n // Create a div with jQuery using HTML\n let $button = $('<div></div>');\n // Give it the guess class\n $button.addClass(\"guess\");\n // Set the text in the div to our label\n $button.text(label);\n // Turn the div into a button using jQuery UI's .button() method\n $button.button();\n // Listen for a click on the button which means the user has guessed\n $button.on('click', handleGuess);\n // Finally, add the button to the page so we can see it\n $('.buttons').append($button);\n // Return the button\n return $button;\n}",
"function createButtonBuy(label) {\n const button = document.createElement('button');\n button.innerText = label || `Buy`\n button.addEventListener('click', () => {\n console.warn(`Clicked ${button.innerText} `)\n })\n\n return button\n}",
"function createBikeButton(label, container) {\r\n\t var btn = L.DomUtil.create('button', '', container);\r\n\t btn.setAttribute('type', 'button');\r\n\t btn.innerHTML = label;\r\n\t btn.title = \"Biking Route\";\r\n\t return btn;\r\n\t}",
"function createButtonField(graph, form, cell, id, text, handler) {\n\t\tvar label = mxResources.get(text) || '';\n\t\tvar input = form.addButton(id, label, id);\n\t\t\n\t\tvar applyHandler = function() {\n\t\t\thandler(graph, form, cell, input);\n\t\t};\n\t\t\n\t\tmxEvent.addListener(input, 'click', applyHandler);\n\t\treturn input;\n\t}",
"addButtonBefore(identifier, label, clickDelegate, destroy)\n {\n let insertIndex = typeof identifier == \"string\" ?\n this.indexOf(identifier) : identifier;\n\n // create the button\n let button = {\n type: \"button\",\n label: label,\n clickDelegate: clickDelegate,\n destroy: destroy\n };\n\n this.elements.splice(insertIndex, 0, button);\n }",
"function createButton(str) {\n // ---------- Your Code Here ----------\n\n var buttonDiv = $(\"<button>\");\n buttonDiv.addClass(\" addedButton\");\n buttonDiv.text (str)\n buttonDiv.data (\"content\", str)\n $(\"#button-area\").append(buttonDiv);\n \n\n\n\n // ---------- End of Code area ----------\n}",
"createAddButton() {\n let addSourceButton = document.createElement('button')\n addSourceButton.innerText = 'Add ' + this.capitalize(this.type)\n addSourceButton.addEventListener('click', () => this.toggleFormVisibility())\n this.div.appendChild(addSourceButton)\n }",
"function buildButton(){\r\n var buttonLabels = [\"Up\", \"Down\", \"Left\", \"Right\", \"Mark Cell\"];\r\n for (var i=0; i<buttonLabels.length; i++){\r\n var newButton = document.createElement(\"button\");\r\n newButton.setAttribute(\"id\", buttonLabels[i]);\r\n newButton.textContent = buttonLabels[i];\r\n document.body.appendChild(newButton);\r\n }\r\n}",
"function createSubmitButton(id, label) {\n let button = document.createElement('BUTTON');\n button.id = id;\n button.innerText = label;\n return button;\n }",
"function addWords(label) {\n let $createWords = $('<div></div>');\n $createWords.addClass('words');\n $createWords.text(label);\n $createWords.button();\n $createWords.appendTo('h6');\n //speak the words on the button when it is clicked\n $createWords.click(speakWords);\n}",
"addButton(text, imageUrl, onPointerDown) {\n var width = this.makeRoomForMore();\n \n var button = new BABYLON.GUI.HolographicButton(text+\"Button\");\n this.guiManager.addControl(button);\n button.imageUrl = imageUrl;\n button.text=text;\n button.position = new BABYLON.Vector3(this.elements.length*width/2,0,0);\n button.scaling = new BABYLON.Vector3( this.buttonSize, this.buttonSize, this.buttonSize );\n button.mesh.parent = this.rowRoot;\n this.elements.push(button);\n this.controls.push(button);\n button.backMaterial.alpha = this.alpha;\n this.rescaleHUD();\n if ( onPointerDown ) {\n button.onPointerDownObservable.add( (vector3WithInfo) => onPointerDown(button, vector3WithInfo) );\n }\n if ( text ) {\n this.speechInput.addCommand(text, () => {\n // execute click callback(s) on visible button\n this.activateButton(button);\n });\n }\n return button;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Soal No. 1 Fungsi Teriak / Buatlah sebuah fungsi bernama teriak(), yang mengembalikan nilai berupa "Halo Function!", yang kemudian akan ditampilkan di halaman html. Tampilkan dengan cara document.getElementById("jawaban1").innerHTML seperti di CONTOH. | function teriak() {
// Tulis Code mulai di sini
document.getElementById("jawaban1").innerHTML = "Aku Teriak"
// Tampilkan dengan cara document.getElementById("jawaban1").innerHTML seperti di CONTOH.
} | [
"function tampilkan() {\n document.getElementById(\"contohJawaban\").innerHTML = \"Aku Tampil\"\n }",
"function buatKalimat(nama, umur, alamat, hobi) {\n // Code kamu mulai dari sini\n var kalimat = \"Nama saya \" + nama + \", Umur \" + umur + \" Bertempat tinggal di \" + alamat + \", hobi saya \" + hobi;\n // Tampilkan dengan cara document.getElementById(\"jawaban3\").innerHTML seperti di CONTOH.\n document.getElementById(\"jawaban3\").innerHTML = kalimat;\n }",
"function tampilkan() {\r\n document.getElementById(\"Halo Sanbers\").innerHTML = \"Halo Sanbers\"\r\n }",
"function kalikan(num1, num2) {\n // Code kamu mulai dari sini\n var kali = num1 * num2;\n\n\n // Tampilkan jawaban dengan cara document.getElementById(\"jawaban2\").innerHTML seperti di CONTOH\n document.getElementById(\"jawaban2\").innerHTML = kali;\n }",
"function kalikan(dua belas, empat) {\r\n document.getElementById(\"kalikan\").innerHTML = dua belas * empat\r\n }",
"function pengembangan(){\n alert(\"Fitur ini masih dalam tahap pengembangan.\");\n}",
"function simpleFunction() { \r\n // disini kita bisa menggunakan variabel 'makanan'\r\n}",
"function miFuncion() {\n console.log(\"funciona\")\n contendor.innerHTML = \"Un texto generado desde Javascript\"\n}",
"function simpleFunction(){\r\n var makanan = \"Bakso\";\r\n // jika variabel 'makanan' ditaruh di dalam sini maka variabel 'makanan' dapat diakses\r\n}",
"function potongAwalanMe(kata){\n\tvar _2hurufAwal = kata.substr(0,2);\n\tvar awalan = \"\";\n\tvar\t_4hurufAwal = kata.substr(0,4);\n\tvar\t_3hurufAwal = kata.substr(0,3);\n\tvar hurufPengganti=\"\";\n\tif(_4hurufAwal == \"meng\" || _4hurufAwal == \"peng\"){\n\t\t\tawalan = _4hurufAwal;\n\t\t\t// hasil yang dipotong tambahkan dengan salah satu huruf berikut ini\n\t\t\t// hurufPengganti=['v','k','g','h','q'];\t\n\t\t\t}\n\t\telse if(_4hurufAwal == \"meny\" || _4hurufAwal == \"peny\"){\n\t\t\t//awalan = _4hurufAwal.substr(0,2);\n\t\t\tawalan = _4hurufAwal;\n\t\t\t// ganti ny dengan huruf pengganti\n\t\t\thurufPengganti=['s'];\n\t\t\t}\n\t\telse if(_3hurufAwal == \"mem\" || _3hurufAwal == \"pem\"){\n\t\t\tawalan = _3hurufAwal;\n\t\t\t// tambahkan huruf pengganti jika hasil kata yang dipotong berupa huruf vokal\n\t\t\thurufPengganti=['b','f','p','v'];\t\n\t\t\t}\n\t\telse if(_3hurufAwal == \"men\" || _3hurufAwal == \"pen\"){\n\t\t\tawalan = _3hurufAwal;\n\t\t\t// tambahkan huruf pengganti jika hasil kata yang dipotong berupa huruf vokal\n\t\t\thurufPengganti=['c','d','j','s','t','z'];\t\n\t\t\t}\n\t\telse if(_3hurufAwal == \"per\"){\n\t\t\tawalan = _3hurufAwal;\n\t\t//\thurufPengganti=['c','d','j','s','t','z'];\t\n\t\t\t}\t\n\t\telse if(_2hurufAwal == \"me\" || _2hurufAwal == \"pe\"){\n\t\t\tawalan = _2hurufAwal;\n\t\t//\thurufPengganti=['l','m','n','r','y','w'];\t\n\t\t\t}\n\treturn awalan;\t\t\n//\treturn awalan+\" \"+kata.substr(awalan.length)+\" \"+hurufPengganti;\n}",
"function ChangeButtonTekst(t)\n{\n document.getElementById('ChangeTekst').innerHTML = \"hey there\";\n}",
"function tampilnama(nama){\n console.log(nama);\n }",
"function doicau(caumay){ //Khi bấm nút next thì đổi câu hỏi hiển thị\n //Sửa sound và ảnh replace\n\tvar hienthi = dulieu[caumay].FRONT\n\thienthi = suahienthi(hienthi,0).result\n\t//đổi câu luôn\n\t$(\"#cauhoi\").html(hienthi)\n\t$(\"#cauhoi *,#cauhoi\").addClass(localStorage.caidatAnchu)\n\t$(\"#titlebaiviet\").html('<b>'+(Number(localStorage.caumayCollegiate_English_words_4895)+1)+\"/\"+tongcau+' - '+bainao )\n $(\".thongbao\").html(\"<b>bsquochoai@gmail.com</b> - <a href='https://youtube.com/bsquochoai' target='_blank'>https://youtube.com/bsquochoai</a>\")\n $(\"#nhapdapan\").val(\"\").focus()\n\tread(hienthi)\n translate(hienthi)\n translate(dulieu[caumay].BACK,'dichdapan')\n}",
"function simpanData(){\n // semua inputan pada form menabung masukkan pada variable nama, nominal, tanggal\n // data inputan di tangkap menggunakan properti id pada tag <input>\n var nama = document.getElementById('nama_penabung').value;\n var nominal = document.getElementById('nominal_menabung').value;\n var tanggal = document.getElementById('tanggal_menabung').value;\n\n // jika form tambah tabungan tidak semua di isi\n if(!nama || !nominal || nominal == 0 || !tanggal){\n alert('Form tambah tabungan harus di isi semua');\n\n // jika form tambah tabungan di isi semua\n }else{\n\n // ambil data tabungan di local storage lalu parse & masukkan ke variable dataTabungan\n var dataTabungan = JSON.parse(localStorage.getItem('tabungan'));\n\n // buat variable id\n var id;\n\n // jika data tabungan di local storage tidak ada\n if(dataTabungan === null || dataTabungan.length === 0){\n\n // variable id di isi dengan angka 1\n id = 1;\n\n // buat variable array dengan isi data id, namaPenabung, nominalMenabung, tanggalMenabung\n // ke 4 data itu akan menjadi field-field di local storage\n // yang pernah main database (DBMS) kaya MySQL dll pasti paham field-field yang saya maksud\n var data = {\n 'id': id,\n 'namaPenabung': nama,\n 'nominalMenabung': nominal,\n 'tanggalMenabung': tanggal\n };\n \n // push variable data ke dalam variable dataTabungan\n dataTabungan = [data];\n\n // simpan data tabungan ke dalam local storage\n localStorage.setItem('tabungan', JSON.stringify(dataTabungan));\n\n // jalankan function/fungsi menampilkan data tabungan\n tampilkanDataTabungan();\n\n // jika data tabungan di local storage ada\n }else{\n\n // variable id di isi dengan jumlah data tabungan + 1 (di tambah satu) \n id = dataTabungan.length+1;\n\n // buat variable array dengan isi data id, namaPenabung, nominalMenabung, tanggalMenabung\n // ke 4 data itu akan menjadi field-field di local storage\n // yang pernah main database (DBMS) kaya MySQL dll pasti paham field-field yang saya maksud\n var data = {\n 'id': id,\n 'namaPenabung': nama,\n 'nominalMenabung': nominal,\n 'tanggalMenabung': tanggal\n };\n\n // looping data tabungan\n for (let i = 0; i < dataTabungan.length; i++) {\n // tambahkan / gabungkan data tabungan baru dengan data tabungan yang sudah ada \n dataTabungan.push(data);\n\n // hentikan looping\n break;\n }\n\n // simpan data tabungan ke dalam local storage\n localStorage.setItem('tabungan', JSON.stringify(dataTabungan));\n\n // jalankan function/fungsi menampilkan data tabungan\n tampilkanDataTabungan();\n }\n }\n}",
"function Exo_6_2_jsform()\r\n\t//Début\r\n\t{\r\n\t\t// Effacer résultat précédent\r\n\t\tdocument.getElementById(\"sp_result\").innerHTML=\"\";\r\n\r\n\t\tvar Tab = [5];\r\n\r\n\t\tTab[0] = \"A\";\r\n\t\tTab[1] = \"E\";\r\n\t\tTab[2] = \"I\";\r\n\t\tTab[3] = \"O\";\r\n\t\tTab[4] = \"U\";\r\n\t\tTab[5] = \"Y\";\r\n\r\n\t\t//Ecrire \"Tableau :\" & Tab\r\n\t\tdocument.getElementById(\"sp_result\").innerHTML=\"Tableau : \" + Tab + \"<br>\";\r\n\r\n\t//Fin\r\n\t}",
"function ChangeSangkat(){\r\n\t\t\thtmlid=\"sangkat\";\r\n\t\t\tvar item_khan = document.getElementById(\"khan\").value;\r\n\t\t\tif(item_khan != \"\"){\r\n\t\t\t\txmlobj =getHTTPObject();\r\n\t\t\t\tif(xmlobj==null){\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\turl =\"php_ajax/get_sangkat.php?khan_id=\"+item_khan;\r\n\t\t\t\txmlobj.onreadystatechange=ajax_return;\r\n\t\t\t\txmlobj.open(\"GET\",url,true)\r\n\t\t\t\txmlobj.send(null)\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}",
"function afficheDonnees(aId, aTexte) {\n\n\tdocument.getElementById(aId).innerHTML = aTexte;\n\n}",
"function select_kab_kota(id, kab_kota) {\n // hilangkan list kecamatan\n list_kab_kota.style.display = \"none\";\n list_kab_kota.innerHTML = \"\";\n // simpan id kabupaten/kota dalam value input id_prov untuk disimpan\n id_kab_kota.value = id;\n // tampilkan nama kabupaten/kota dalam value input nm_prov agar tetap terlihat nama kabupaten/kota yang dipilih\n nm_kab_kota.value = kab_kota.trim();\n // aktifkan input kecamatan\n document.getElementById('nm_wil').disabled = false;\n document.getElementById('nm_wil').focus();\n }",
"function afficher(){\n document.getElementById('motMystere').innerHTML=mot-Affiche;\n document.getElementById('listeLettres').innerHTML=lettresutilisees;\n dessinPendu();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Default to a dummy "batch" implementation that just runs the callback | function defaultNoopBatch(callback){callback();} | [
"function defaultNoopBatch(callback) {\n\t callback();\n\t}",
"function defaultNoopBatch(callback) {\n callback();\n }",
"addBatchCallback(callback) {\n this.batchCallback = callback;\n return this;\n }",
"function defaultNoopBatch(callback) {\n callback();\n}",
"function batchCallback(err, data) {\n return {err: err, data: data};\n}",
"function batchedCallback(callback) {\n\treturn function(err, res) {\n\t\tReactUpdates.batchedUpdates(callback.bind(null, err, res));\n\t};\n}",
"function aleph2_global_handle_batch(batch, batch_size, grouping_key) {\r\n\thandle_batch_java(batch, batch_size, grouping_key);\r\n}",
"static batchRead(batch, callback) {\n var key, obj;\n for (key in batch) {\n if (!hasProp.call(batch, key)) continue;\n obj = batch[key];\n this.batchJSON(obj, batch, callback);\n }\n }",
"createBatchObserver(callback, options = {}) {\n const opt = Object.assign({}, options);\n const batchObserver = new BatchObserver_1.BatchObserver(opt, callback);\n this._batchObservers.push(batchObserver);\n return batchObserver;\n }",
"_sendFn(enqueueOnBatchCallback, op) {\n // A backoff duration greater than 0 implies that this batch is a retry.\n // Retried writes are sent with a batch size of 10 in order to guarantee\n // that the batch is under the 10MiB limit.\n if (op.backoffDuration > 0) {\n if (this._bulkCommitBatch.pendingOps.length >= exports.RETRY_MAX_BATCH_SIZE) {\n this._scheduleCurrentBatch(/* flush= */ false);\n }\n this._bulkCommitBatch.setMaxBatchSize(exports.RETRY_MAX_BATCH_SIZE);\n }\n if (this._bulkCommitBatch.has(op.ref)) {\n // Create a new batch since the backend doesn't support batches with two\n // writes to the same document.\n this._scheduleCurrentBatch();\n }\n enqueueOnBatchCallback(this._bulkCommitBatch);\n this._bulkCommitBatch.processLastOperation(op);\n if (this._bulkCommitBatch._opCount === this._bulkCommitBatch.maxBatchSize) {\n this._scheduleCurrentBatch();\n }\n else if (op.flushed) {\n // If flush() was called before this operation was enqueued into a batch,\n // we still need to schedule it.\n this._scheduleCurrentBatch(/* flush= */ true);\n }\n }",
"async onBatchEnd(batch, logs) {\n if (logs == null) {\n logs = {};\n }\n for (const callback of this.callbacks) {\n await callback.onBatchEnd(batch, logs);\n }\n }",
"function Batcher(batchCallback, postprocessCallback) {\n console.assert(_.isFunction(batchCallback));\n console.assert(_.isFunction(postprocessCallback) || postprocessCallback == null);\n this.batchCallback = batchCallback;\n this.requested = [];\n this.requestTimeout = null;\n\n this.get = function(request) {\n return new Promise(function (resolve, reject) {\n this.requested.push({request: request, resolve: resolve, reject: reject});\n if (!this.requestTimeout) {\n this.requestTimeout = setTimeout(this.fetchRequested.bind(this), 0);\n }\n }.bind(this));\n }.bind(this);\n\n this.fetchRequested = function() {\n this.requestTimeout = null;\n var acceptedRequests = this.requested;\n this.requested = [];\n\n var requests = _.map(acceptedRequests, 'request');\n console.assert(_.isArray(requests));\n return this.batchCallback(requests).then(function(response) {\n // resolving promises that could be resolved\n _.each(acceptedRequests, function(promiseCallbacks) {\n if (postprocessCallback) {\n try {\n var postprocessed = postprocessCallback(promiseCallbacks.request, response);\n promiseCallbacks.resolve(postprocessed);\n } catch(err) {\n promiseCallbacks.reject(err);\n }\n } else {\n promiseCallbacks.resolve(response);\n }\n });\n }).catch(function (err) {\n console.error('Batcher: ' + requests + ' --> ERROR: ', err);\n _.each(acceptedRequests, function(promiseCallbacks) {\n promiseCallbacks.reject(err);\n });\n });\n }.bind(this);\n}",
"_sendFn(enqueueOnBatchCallback, op) {\n if (this._bulkCommitBatch.has(op.ref)) {\n // Create a new batch since the backend doesn't support batches with two\n // writes to the same document.\n this._sendCurrentBatch();\n }\n // Run the operation on the current batch and advance the `_lastOp` pointer.\n // This ensures that `_lastOp` only resolves when both the previous and the\n // current write resolves.\n enqueueOnBatchCallback(this._bulkCommitBatch);\n this._bulkCommitBatch.processLastOperation(op);\n this._lastOp = this._lastOp.then(() => util_1.silencePromise(op.promise));\n if (this._bulkCommitBatch._opCount === this._maxBatchSize) {\n this._sendCurrentBatch();\n }\n }",
"function callback(){}",
"function batch_rec(batches, userid_table, count, connection, callback) {\n if (batches && batches.length) {\n batch(batches[0], userid_table, count, connection, (err) => {\n if (err) {\n callback(err)\n } else {\n batches.shift()\n count ++\n return batch_rec(batches, userid_table, count, connection, callback)\n }\n })\n } else {\n callback(null)\n }\n}",
"writeBatch(callback: WriteCallback): void {\n const batch = this.batch;\n // reset the instance batch\n this.batch = [];\n const tx = this.db.transaction(this.objectStore, \"readwrite\");\n const store = tx.objectStore(this.objectStore);\n for (const item of batch) {\n const toInsert = this.options.extra ? { ...item, ...this.options.extra } : item;\n store.put(toInsert);\n }\n // use setTimeout to yield the thread a bit - even with their quasi-asyncness\n // node streams can sometimes cause a bit too much throughput pressure on writes\n tx.complete.then(() => setTimeout(callback, 1)).catch(callback);\n }",
"function asap$1(callback, context) {\n !batchingStrategy.isBatchingUpdates ? _prodInvariant$12('125') : void 0;\n asapCallbackQueue.enqueue(callback, context);\n asapEnqueued = true;\n}",
"static batchRead(batch, callback, create = null) {\n var key, obj;\n for (key in batch) {\n if (!hasProp.call(batch, key)) continue;\n obj = batch[key];\n this.batchJSON(obj, batch, callback, create);\n }\n }",
"function batchFetch(iter) {\n var pos = iter._batchIndex;\n if (pos === iter.count) {\n return; // return if at the end\n }\n var next = Math.min(pos + iter.batch_size, iter.count);\n iter._batchIndex += next-pos;\n var callback = true;\n var i = 0;\n iter.file.get(pos, next, null, function(item) {\n if (callback) {\n callback = iter._futureCallbacks[pos + i];\n if (callback) {\n callback(item);\n delete iter._futureCallbacks[pos + i];\n // setTimeout((function(callback, item, idx) {\n // callback(item);\n // delete iter._futureCallbacks[idx];\n // })(callback, item, pos + i), 0);\n i++;\n return;\n }\n }\n iter._items.push(item);\n i++;\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queue life when the particle died completely (increase the opacity once set to 0 or less) /wait for as much as the delay was set | queueLife() {
if (this.alpha < 1) {
setTimeout(() => {
this.alpha += 0.1;
this.queueLife();
}, this.delay);
} else {
this.dead = false;
this.queueDeath();
}
} | [
"queueDeath() {\n if (this.alpha > 0) {\n setTimeout(() => {\n this.alpha -= 0.1;\n this.queueDeath();\n }, this.delay);\n } else {\n this.dead = true;\n this.inversion = Math.random() <= 0.5 ? -1 : 1;\n this.inversion2 = Math.random() <= 0.5 ? -1 : 1;\n this.Xpos =\n this.canvasX + Math.random() * (this.canvasX - 200) * this.inversion;\n this.Ypos =\n this.canvasY + Math.random() * (this.canvasY - 100) * this.inversion2;\n this.blueTint = Math.random() * 100;\n this.greenTint = Math.random() * 50;\n this.queueLife();\n }\n }",
"onParticleEnd(){}",
"function updateCrashParticles(particles){\n particles.material.color.setHex(actualColor);\n particles.material.transparent = true;\n particles.material.opacity -= 0.01;\n particles.scale.x +=2;\n particles.scale.y +=2;\n particles.scale.z +=2;\n \n}",
"render() {\n this.delay -= 100;\n if (this.delay <= 0) {\n this.fadeTime -= 100;\n if (this.fadeTime <= 0) {\n this.reset();\n } else {\n ctx.globalAlpha = this.fadeTime / this.alphaDivisor;\n GamePiece.prototype.render.call(this);\n ctx.globalAlpha = 1.0;\n }\n }\n }",
"function readyNextFade() {\n let buffer = fade_queue.dequeue();\n fade_start_time = tick + Math.abs(buffer);\n //document.getElementById('fade').classList.remove('hidden');\n if (buffer >= 0) {fading_in = true;}\n else {fading_out = true;}\n}",
"CrossFadeQueued() {}",
"function explodeParticle(particle, scale, position, amount, duration){\n //sends out a random amount of a particle\n for(var i = 0; i < amount; i++){\n var tempMesh = particle.mesh;\n tempMesh.scale.x = scale;\n tempMesh.scale.y = scale;\n tempMesh.scale.z = scale;\n tempMesh.position.x = position.x+10;\n tempMesh.position.y = position.y;\n tempMesh.position.z = position.z;\n tempMesh.rotation.x = Math.random();\n tempMesh.rotation.y = Math.random();\n tempMesh.rotation.z = Math.random();\n scene.add(tempMesh);\n fireParticles.push(tempMesh);\n setTimeout(function(){scene.remove(tempMesh)}, duration);\n }\n}",
"function drawExplosion(){\n if(particles_display){\n for(let i = 0; i < explosionParticlesArray.length; i++){\n if(explosionParticlesArray[explosionParticlesArray.length-1].opacity > 0.05){\n explosionParticlesArray[i].speedX *= 0.91 + Math.random()/10\n explosionParticlesArray[i].speedY *= 0.91 + Math.random()/10\n explosionParticlesArray[i].posY += explosionParticlesArray[i].speedY\n explosionParticlesArray[i].posX += explosionParticlesArray[i].speedX\n explosionParticlesArray[i].opacity *= 0.94\n explosionParticlesArray[i].color = `rgba(255,165,0,${explosionParticlesArray[i].opacity})`\n ctx.save()\n ctx.beginPath()\n ctx.shadowColor = explosionParticlesArray[i].color\n ctx.shadowBlur = 1\n ctx.arc(explosionParticlesArray[i].posX, explosionParticlesArray[i].posY, explosionParticlesArray[i].radius, 0, 2 * Math.PI, false)\n ctx.fillStyle = explosionParticlesArray[i].color\n ctx.stroke()\n ctx.fill()\n ctx.restore()\n if(soundPlay){\n explosionSound.play()\n }\n }\n else{\n explosionParticlesArray.splice(0,explosionParticlesArray.length)\n }\n }\n }\n}",
"function timeDelayEnemy() {\n stage.insert(new Q.Enemy({ x: 700, y: 0 }));\n }",
"function particleBurst()\n{\n\temitter = spriteGroup.add(game.add.emitter(124, 275, 10));\n\temitter.makeParticles('star');\n\temitter.gravity = 0;\n\temitter.alpha = 0.8;\n\temitter.start(true, 1000, null, 50);\n\n\tgame.add.tween(emitter).to(\n\t\t{\n\t\t\talpha: 0\n\t\t},\n\t\t1000,\n\t\tPhaser.Easing.Linear.Out,\n\t\ttrue\n\t);\n\n\tspriteGroup.sendToBack(emitter);\n}",
"@autobind\n updateColorTime (event, opacity=true) {\n var r = 0;\n var g = 0;\n var b = 0;\n\n for (var i=0, i3=0, l=this.particleCount; i<l; i++, i3 += 3) {\n if (opacity) {\n if (this.opacityArray[i] < 1) {\n this.opacityArray[i] += 0.01;\n if (this.opacityArray[i] > 1) {\n this.opacityArray[i] = 1;\n }\n }\n }\n\n r = this.colorsTargetArray[i3 + 0] - this.colorsArray[i3 + 0];\n g = this.colorsTargetArray[i3 + 1] - this.colorsArray[i3 + 1];\n b = this.colorsTargetArray[i3 + 2] - this.colorsArray[i3 + 2];\n\n this.colorsArray[i3 + 0] += r * this.tweenContainer.colorTime;\n this.colorsArray[i3 + 1] += g * this.tweenContainer.colorTime;\n this.colorsArray[i3 + 2] += b * this.tweenContainer.colorTime;\n }\n\n this.material.uniforms[ 'colortime' ].value = this.tweenContainer.colorTime;\n this.material2.uniforms[ 'colortime' ].value = this.tweenContainer.colorTime;\n }",
"function update() {\n\tclear();\n\tfor (i = 0; i < particles.length; i++) {\n\t\tvar p = particles[i];\n\t\t\n\t\t// For the burning effect, we'll increase the radius\n\t\t// of each particles whilst reducing its opacity.\n\t\t// As soon as the opacity goes below zero, we'll make the\n\t\t// particle reborn, LOVELY!\n\t\tp.r += 0.15;\n\t\tp.a -= 0.015;\n\t\t\t\n\t\tif(p.a < 0) {\n\t\t\tp.r = Math.random() * 6;\n\t\t\tp.a = Math.random();\n\t\t}\n\t\t\n\t\t// Logic for making them fall on hover \n\t\tif(mouse.x > p.x - p.r && \n\t\t\t mouse.x < p.x + p.r &&\n\t\t\t mouse.y > p.y - p.r &&\n\t\t\t mouse.y < p.y + p.r)\n\t\t\ttouched = true;\n\t\t\n\t\t//console.log(touched); // Working\n\t\t// We'll also make the nearby particles fall down\n\t\t// so we will need a minimum distance\n\t\t// We'll calculate the distance b/w mouse cursor\n\t\t// and the particles and then compare it with minDist\n\t\t\n\t\tif (touched == true) {\n\t\t\tvar dist = Math.sqrt((p.x-mouse.x)*(p.x-mouse.x) + (p.y-mouse.y)*(p.y-mouse.y));\n\t\t\t\n\t\t\tif(dist <= minDist) \n\t\t\t\tp.isFree = true;\n\t\t\t\n\t\t\tif(p.isFree == true) {\n\t\t\t\t// Add velocities and gravity\n\t\t\t\tp.y += p.vy;\n\t\t\t\tp.x += p.vx;\n\t\t\t\t\n\t\t\t\t// Take a moment and pause the codecast. Try hovering\n\t\t\t\t// particles and they'll fly away because no gravity \n\t\t\t\t// is present, but it is still a cool effect ;)\n\t\t\t\t\n\t\t\t\t// Now they'll obey the rules of nature\n\t\t\t\tp.vy += gravity;\n\t\t\t\t\n\t\t\t\t// Note that particles go below the floor so we need\n\t\t\t\t// to make them bouncy and make them rebound as they\n\t\t\t\t// hit the floor and walls\n\t\t\t\tif(p.y + p.r > H) {\n\t\t\t\t\tp.vy *= -bounceFactor;\n\t\t\t\t\tp.y = H - p.r;\n\t\t\t\t\t\n\t\t\t\t\t// We also need a little friction on the floor\n\t\t\t\t\t// otherwise the particles will keep moving like\n\t\t\t\t\t// little ants :P\n\t\t\t\t\tif (p.vx > 0) \n\t\t\t\t\t\tp.vx -= 0.1;\n\t\t\t\t\telse\n\t\t\t\t\t\tp.vx += 0.1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// The codecast completes here. Try changing the colors\n\t\t\t\t// or size of particles and add your own text keywords!\n\t\t\t\t// Buh-bye :)\n\t\t\t\t\n\t\t\t\t// Collision with walls\n\t\t\t\tif(p.x + p.r > W) {\n\t\t\t\t\tp.vx *= -bounceFactor;\n\t\t\t\t\tp.x = W - p.r;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (p.x - p.r < 0) {\n\t\t\t\t\tp.vx *= -bounceFactor;\n\t\t\t\t\tp.x = p.r;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tctx.globalCompositeOperation = \"lighter\";\n\t\tp.draw();\n\t}\n}",
"function wait() {\n timer = setTimeout(function(){fadeIt()},6000);\n}",
"wait() {\n on (ETrigger eTrigger) : {\n\n CEntity *penInflictor = this;\n if (m_bDamageFromTriggerer) {\n penInflictor = eTrigger.penCaused;\n }\n\n CEntity *penVictim = NULL;\n if (m_penToDamage!=NULL) {\n penVictim = m_penToDamage;\n } else if (eTrigger.penCaused!=NULL) {\n penVictim = eTrigger.penCaused;\n }\n \n if (penVictim!=NULL) {\n if (!(penVictim==m_penLastDamaged && _pTimer->CurrentTick()<m_tmLastDamage+0.1f))\n {\n InflictDirectDamage(penVictim, penInflictor, m_dmtType, m_fAmmount, \n penVictim->GetPlacement().pl_PositionVector, FLOAT3D(0,1,0));\n m_penLastDamaged = penVictim;\n m_tmLastDamage = _pTimer->CurrentTick();\n }\n }\n stop;\n }\n otherwise() : {\n resume;\n };\n }",
"function tick() {\n\tif (perf.lowQualityMode == false) {\n\t\tparticleEmitter.emit(ball.position, 100, particleProps, defaultParticle);\n\t}\n}",
"function hitDelay(){\n let planeImg = plane.children[0];\n explosionAudio.play();\n planeImg.style.height = \"0\";\n planeNr--;\n if (planeNr == 3){\n clearInterval(changePositionInt1); //need to clear so doesn't fire multiple times\n changePositionInt2 = setInterval(changePosition, 1400); // need to give a new id so can be cleared later\n hintPlane.textContent = '1 down, 3 to go';\n planeLeft.textContent = \"1/4\";\n setTimeout(hintGone, 2000);\n } else if (planeNr == 2){\n clearInterval(changePositionInt2);\n changePositionInt3 = setInterval(changePosition, 1000);\n hintPlane.textContent = 'half way done, 2 to go';\n planeLeft.textContent = \"2/4\";\n setTimeout(hintGone, 2000);\n } else if (planeNr == 1){\n clearInterval(changePositionInt3);\n changePositionint4 = setInterval(changePosition, 700);\n hintPlane.textContent = '3 down, finish the last one';\n planeLeft.textContent = \"3/4\";\n setTimeout(hintGone, 2000);\n } else if (planeNr ==0 && timeToDisplay.innerHTML[1] != 0) { // finished too fast, add extra planes\n hintPlane.textContent = '4 down! WELL DONE! But 3 backup planes just joined the battle!';\n planeLeft.textContent = \"4/7\";\n setTimeout(hintGone, 4000);\n extraPlanes.forEach(showExtra);\n function showExtra(extraPlane){\n extraPlane.style.display = \"inherit\";\n }\n } else if (planeNr ==0 && timeToDisplay.innerHTML[1] == 0){\n clearInterval(changePositionInt4);\n changePositionint5 = setInterval(changePosition, 1100);\n planeLeft.textContent = \"4/4\";\n clearInterval(timerRunDown);\n timeToDisplay.classList.remove('flash');\n// timeToDisplay.style.transform = \"scale(1.5)\";\n window.removeEventListener('mousedown', gunfire);\n window.removeEventListener('keypress', moveSky);\n setTimeout(redirectToStatic, 2500);\n } else if (planeNr == -1){\n clearInterval(changePositionInt5);\n changePositionint6 = setInterval(changePosition, 900);\n hintPlane.textContent = 'bonus 1 !';\n planeLeft.textContent = \"5/7\";\n setTimeout(hintGone, 2000);\n } else if (planeNr == -2){\n clearInterval(changePositionInt6);\n changePositionint7 = setInterval(changePosition, 700);\n hintPlane.textContent = 'bonus 2 !';\n planeLeft.textContent = \"6/7\";\n setTimeout(hintGone, 2000);\n }else if (planeNr == -3) {\n clearInterval(changePositionInt7);\n hintPlane.textContent = 'bonus 3 !';\n planeLeft.textContent = \"7/7\";\n clearInterval(timerRunDown);\n timeToDisplay.classList.remove('flash');\n window.removeEventListener('mousedown', gunfire);\n window.removeEventListener('keypress', moveSky);\n setTimeout(redirectToStatic, 2500);\n }\n }",
"function eatPowerPellet() {\n score += 50;\n power_pellets -= 1;\n\n ghostsEdible(true);\n\n setTimeout(function() {\n ghostsEdible(false);\n drawScreen();\n }, 5000)\n\n // for (var i = 0; i < ghosts.length; i++) {\n // ghosts[i].edible = true;\n // }\n}",
"timer () {\n setTimeout(() => {\n this.fireImg.style.opacity = 0\n }, 10000)\n }",
"waterEvent () {\n if (this.shadowRoot.querySelector('#smoke')) { return }\n\n if (this.matchLit === true) {\n this.fireImg.style.opacity = 0\n\n const img = document.createElement('img')\n img.setAttribute('src', '/image/smoke.gif')\n img.setAttribute('id', 'smoke')\n const container = this.shadowRoot.querySelector('#fireContainer')\n\n setTimeout(() => {\n this.fireImg.remove()\n container.appendChild(img)\n img.style.opacity = 0\n }, 4000)\n\n setTimeout(() => {\n img.style.opacity = 1\n }, 4500)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Expand a the node with the given ID | function expand(id, recursive)
{
collapse(id, recursive, false);
} | [
"function ECMS_expand_id(tree, id) {\n\tECMS_control_node(ECMS_find_node(tree, id), 1);\n}",
"function expandCompressNode(id) {\t\n\tvar node = nodeIndex[id];\n\t \n\tif (!node.expanded) {\n\t\tnode.expandChildren();\n\t} else {\t\t\n\t\tnode.expanded = false;\n\t\tnode.compressChildren();\n\t}\n}",
"expand(node) {}",
"function setExpandNode(pk, state) {\n}",
"expand(dataNode) {\n this.expansionModel.select(this._trackByValue(dataNode));\n }",
"function add_expanded(id) {\n var expanded = get_expanded();\n if ($.inArray(id, expanded) === -1) {\n expanded.push(id);\n set_expanded(expanded);\n }\n }",
"expand(dataNode) {\n this.expansionModel.select(this._trackByValue(dataNode));\n }",
"function expandTree(treeId) {\n\tvar ul = document.getElementById(treeId);\n\tif (ul == null) { return false; }\n\texpandCollapseList(ul,nodeOpenClass);\n}",
"function expandTree(treeId) {\n var ul = document.getElementById(treeId);\n if (ul == null) { return false; }\n expandCollapseList(ul,nodeOpenClass,null,null);\n}",
"function openOWLNode(id){\n \t\n \t\tvar exp;\n \tcollapseTree(\"Thing\");\n var newId = '';\n \n $(\"[id=\"+id+\"]\").each(function(){\n \n \texp = $(this).parent().parent().hasClass(\"expandable\");\n \tvar parentId = $(this).parent().parent().attr(\"id\");\n \twhile(exp){\n \texpandBranch(parentId);\n \texp = $(\"#\"+parentId).parent().parent().hasClass(\"expandable\");\n \tparentId = $(\"#\"+parentId).parent().parent().attr(\"id\");\n }\n \n \t$(this).children(\"span\").each(function(){\n newId = this.id;\n });\n \t\n });\n \n //alert(\"final id : \"+newId)\n $(\"#loadowl\").scrollTo(\"#\"+newId,100,{offset:-50});\n var def = $(\"#\"+id).attr(\"data\");\n var label;\n $(\"#\"+id+\" span\").each(function(){\n label = $(this).text();\n });\n //alert(label)\n selectOWLNode(def,label,id);\n }",
"function selectionExpand(id)\n{\n\tvar currentRange\t= getTextRangeFromSelection(id);\n\tvar parent\t\t\t= currentRange.parentElement();\n\n\tif(parent == null)\n\t\treturn;\n\n\tvar parentRange = currentRange.duplicate();\n\tparentRange.moveToElementText(parent);\n\n\t// Check if we already have the entire parent text selected - if so, expand another element\n\t// (unless the entire BODY-tag is selected, we cannot move outside that).\n\twhile(parentRange.htmlText == currentRange.htmlText && parent.tagName.toUpperCase() != 'BODY')\n\t{\n\t\tvar grandParent = parent.parentElement;\t// NOTE: using the parentElement _property_, not the TextRange _method()_\n\t\tif(grandParent != null)\n\t\t{\n\t\t\tparent = grandParent;\n\t\t\tparentRange.moveToElementText(parent);\n\t\t}\n\t\telse\n\t\t\tbreak;\n\t}\n\tcurrentRange.moveToElementText(parent);\n\tcurrentRange.select();\n}",
"function expand_node_view(node) {\n}",
"_AddNode(node, id) {\n node.rId = this.Size + 1;\n if (node.Id == null || node.Id == undefined) {\n node.Id = this.Size + 1;\n }\n this.Nodes[node.Id] = node;\n this.Size++;\n }",
"expand() {\n const args = {\n owner: this.tree,\n node: this,\n cancel: false\n };\n this.tree.nodeExpanding.emit(args);\n if (!args.cancel) {\n this.treeService.expand(this, true);\n this.cdr.detectChanges();\n this.playOpenAnimation(this.childrenContainer);\n }\n }",
"expandNodeRecursive(){this._selectedField.expandRecursive()}",
"function expandGroup(nodeId, node) {\n node.children.forEach((val) => {\n // Set children nodes\n g.setNode(val.id, val.value);\n mapTaskToNode.set(val.id, val.id);\n g.node(val.id).id = val.id;\n if (val.children !== undefined) {\n // Set children attribute so that the group can be expanded later when needed.\n const groupNode = g.node(val.id);\n groupNode.children = val.children;\n // Map task that are under this node to this node's id\n getChildrenIds(val).forEach((childId) =>\n mapTaskToNode.set(childId, val.id)\n );\n }\n // Only call setParent if node is not the root node.\n if (nodeId != null) g.setParent(val.id, nodeId);\n });\n\n // Add edges\n edges.forEach((edge) => {\n const sourceId = mapTaskToNode.get(edge.source_id);\n const targetId = mapTaskToNode.get(edge.target_id);\n if (\n sourceId !== targetId &&\n !g.hasEdge(sourceId, targetId) &&\n sourceId &&\n targetId\n ) {\n g.setEdge(sourceId, targetId, {\n curve: d3.curveBasis,\n arrowheadClass: \"arrowhead\",\n label: edge.label,\n });\n }\n });\n\n g.edges().forEach((edge) => {\n // Remove edges that were associated with the expanded group node..\n if (nodeId === edge.v || nodeId === edge.w) {\n g.removeEdge(edge.v, edge.w);\n }\n });\n\n saveExpandedGroup(nodeId);\n}",
"setExpandedNodes(treeData, idToExpand, idToCollapse) {\n var expandedIDs = []; //array to hold IDs of expanded nodes\n var flatData = getFlatDataFromTree({treeData:treeData, getNodeKey: this.getNodeKey}); //get flat data (in array form) so we can more easily determine expanded nodes\n\n for (var i = 0; i < flatData.length; i++) { //for each top level node\n if (\"expanded\" in flatData[i].node) { //check for expanded field\n if (flatData[i].node.expanded === true && \"children\" in flatData[i].node) { //if the node is expanded and has children (no need to expand if no children)\n expandedIDs.push(flatData[i].node.id); //add the node id to expandedIDs\n }\n }\n }\n if (idToExpand) { //if we want to manually expand a node, we do it here (example: when adding node, we want to expand its parent node the next time the tree is created)\n expandedIDs.push(idToExpand);\n }\n if (idToCollapse) { //manually collapse a node (used to remove a node and its children from expandedIDs)\n var index = expandedIDs.indexOf(idToCollapse);\n if (index !== -1) {\n expandedIDs.splice(index, 1); //remove idToCollapse from expandedIDs\n }\n //remove children of idToCollapse\n for (i = 0; i < flatData.length; i++) {\n if (flatData[i].node.id === idToCollapse) { //if we find the node to collapse\n if (\"children\" in flatData[i].node) { //remove all children from expandedIDs\n this.removeExpandedChildren(expandedIDs, flatData[i].node);\n }\n }\n }\n }\n this.props.updateNotebookExpansion(this.props.match.params.notebookid, expandedIDs); //update the state in app\n }",
"expandRow(rowID) {\n this.gridAPI.set_row_expansion_state(rowID, true);\n }",
"static enableIdExpanding() {\n $('#codeView').on('click', '.id-expand', function toggleExpand(e) {\n const current = $(this).text();\n const fullId = $(this).data('id');\n\n if (current.length < fullId.length) {\n $(this).text(fullId);\n } else {\n $(this).text(String(fullId).substring(0, 8));\n $(this).slideDown(2000);\n }\n\n e.stopPropagation();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pads a `tf.Tensor4D` with a given value and paddings. See `pad` for details. | function pad4d_(x, paddings, constantValue) {
if (constantValue === void 0) { constantValue = 0; }
util.assert(paddings.length === 4 && paddings[0].length === 2 &&
paddings[1].length === 2 && paddings[2].length === 2 &&
paddings[3].length === 2, function () { return 'Invalid number of paddings. Must be length of 2 each.'; });
return exports.pad(x, paddings, constantValue);
} | [
"function pad4d_(x, paddings, constantValue) {\n if (constantValue === void 0) {\n constantValue = 0;\n }\n assert(paddings.length === 4 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2 && paddings[3].length === 2, function () {\n return 'Invalid number of paddings. Must be length of 2 each.';\n });\n return pad(x, paddings, constantValue);\n}",
"function pad4d_(x, paddings, constantValue = 0) {\n assert(paddings.length === 4 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2 && paddings[3].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}",
"function pad4d_(x, paddings, constantValue = 0) {\n assert(paddings.length === 4 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2 &&\n paddings[3].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}",
"function pad4d_(x, paddings, constantValue = 0) {\n (0,_util__WEBPACK_IMPORTED_MODULE_0__.assert)(paddings.length === 4 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2 &&\n paddings[3].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');\n return (0,_pad__WEBPACK_IMPORTED_MODULE_1__.pad)(x, paddings, constantValue);\n}",
"function pad(value, padding) {\n var values = (value + '').split('');\n var zeros = padding - values.length;\n for (var i=0; i<zeros; i++) {\n values.unshift('0');\n }\n return values.join('');\n}",
"function pad3d_(x, paddings, constantValue) {\n if (constantValue === void 0) {\n constantValue = 0;\n }\n assert(paddings.length === 3 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2, function () {\n return 'Invalid number of paddings. Must be length of 2 each.';\n });\n return pad(x, paddings, constantValue);\n}",
"function pad3d_(x, paddings, constantValue) {\n if (constantValue === void 0) { constantValue = 0; }\n util.assert(paddings.length === 3 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2, function () { return 'Invalid number of paddings. Must be length of 2 each.'; });\n return exports.pad(x, paddings, constantValue);\n}",
"function pad3d_(x, paddings, constantValue) {\n if (constantValue === void 0) { constantValue = 0; }\n util_1.assert(paddings.length === 3 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2, function () { return 'Invalid number of paddings. Must be length of 2 each.'; });\n return pad_1.pad(x, paddings, constantValue);\n}",
"function pad1d_(x, paddings, constantValue) {\n if (constantValue === void 0) {\n constantValue = 0;\n }\n assert(paddings.length === 2, function () {\n return 'Invalid number of paddings. Must be length of 2.';\n });\n return pad(x, [paddings], constantValue);\n}",
"function pad1d_(x, paddings, constantValue) {\n if (constantValue === void 0) { constantValue = 0; }\n util_1.assert(paddings.length === 2, function () { return 'Invalid number of paddings. Must be length of 2.'; });\n return pad_1.pad(x, [paddings], constantValue);\n}",
"function pad1d_(x, paddings, constantValue) {\n if (constantValue === void 0) { constantValue = 0; }\n util.assert(paddings.length === 2, function () { return 'Invalid number of paddings. Must be length of 2.'; });\n return exports.pad(x, [paddings], constantValue);\n}",
"pad(paddingX = 0, paddingY = paddingX) {\n return this.x -= paddingX, this.y -= paddingY, this.width += paddingX * 2, this.height += paddingY * 2, this;\n }",
"function pad3d_(x, paddings, constantValue = 0) {\n (0,_util__WEBPACK_IMPORTED_MODULE_0__.assert)(paddings.length === 3 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');\n return (0,_pad__WEBPACK_IMPORTED_MODULE_1__.pad)(x, paddings, constantValue);\n}",
"function pad4(str) {\r\n while (str.length < 4) {\r\n str = \"0\" + str;\r\n }\r\n return str;\r\n }",
"function pad4(str) {\n while (str.length < 4) {\n str = \"0\" + str;\n }\n return str;\n }",
"function pad3d_(x, paddings, constantValue = 0) {\n assert(paddings.length === 3 && paddings[0].length === 2 &&\n paddings[1].length === 2 && paddings[2].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');\n return pad(x, paddings, constantValue);\n}",
"function pad4(str) {\r\n\t while (str.length < 4) {\r\n\t str = \"0\" + str;\r\n\t }\r\n\t return str;\r\n\t }",
"function pad3d_(x, paddings, constantValue = 0) {\n _util.assert(paddings.length === 3 && paddings[0].length === 2 && paddings[1].length === 2 && paddings[2].length === 2, () => 'Invalid number of paddings. Must be length of 2 each.');\n return _pad.pad(x, paddings, constantValue);\n}",
"function pad1d_(x, paddings, constantValue = 0) {\n (0,_util__WEBPACK_IMPORTED_MODULE_0__.assert)(paddings.length === 2, () => 'Invalid number of paddings. Must be length of 2.');\n return (0,_pad__WEBPACK_IMPORTED_MODULE_1__.pad)(x, [paddings], constantValue);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Classifies as either sky or ground object TO BE CHANGED LATER | function generate_context(object) {
var sky_objects = ["angel", "bee", "bird", "butterfly", "helicopter",
"mosquito", "owl", "parrot", "rain", "snowflake","swan"];
if (sky_objects.includes(object)){
return "sky";
} else{
return "ground";
}
} | [
"function changeTileSky (el){\n console.log(el, shovel.value);\n if(shovel.value === true){\n console.log('removing groundtile');\n el.target.classList.add('skyTile')\n el.target.classList.remove('groundTile')\n }\n}",
"updateEarth() {\n // Check Environment status\n if (getEnvironment() < 25) {\n this.tweenLayer(this.earth_dirty_water_3, 1);\n this.tweenLayer(this.earth_dirty_land_3, 1);\n this.tweenLayer(this.dirty_mt, 1);\n } else if (getEnvironment() >= 25 && getEnvironment() < 50){\n this.tweenLayer(this.earth_dirty_water_2, 1);\n this.tweenLayer(this.earth_dirty_land_2, 1);\n this.tweenLayer(this.default_mt, 1);\n this.tweenLayer(this.dirty_clouds, 1);\n\n // remove layers\n this.tweenLayer(this.clean_clouds, 0);\n this.tweenLayer(this.earth_dirty_water_3, 0);\n this.tweenLayer(this.earth_dirty_land_3, 0);\n this.tweenLayer(this.dirty_mt, 0);\n } else if (getEnvironment() >= 50 && getEnvironment() < 75){\n this.tweenLayer(this.earth_dirty_water_1, 1);\n this.tweenLayer(this.earth_dirty_land_1, 1);\n this.tweenLayer(this.clean_clouds, 1);\n\n // remove layers\n this.tweenLayer(this.earth_dirty_water_2, 0);\n this.tweenLayer(this.earth_dirty_land_2, 0);\n this.tweenLayer(this.dirty_clouds, 0);\n\n } else if (getEnvironment() >= 75) {\n this.tweenLayer(this.clean_mt, 1);\n\n // remove layer\n this.tweenLayer(this.earth_dirty_water_1, 0);\n this.tweenLayer(this.earth_dirty_land_1, 0);\n this.tweenLayer(this.dirty_clouds, 0);\n }\n\n // Check Resource status\n if (getResources() < 25) {\n // remove layers\n this.tweenLayer(this.tree_1, 0);\n this.tweenLayer(this.tree_2, 0);\n this.tweenLayer(this.tree_3, 0);\n this.tweenLayer(this.tree_4, 0);\n this.tweenLayer(this.fish_2, 0);\n this.tweenLayer(this.salmon_2, 0);\n this.tweenLayer(this.tuna_2, 0);\n this.tweenLayer(this.cow_2, 0);\n this.tweenLayer(this.pig_2, 0);\n this.tweenLayer(this.shrimp_2, 0);\n this.tweenLayer(this.fish_1, 0);\n this.tweenLayer(this.salmon_1, 0);\n this.tweenLayer(this.tuna_1, 0);\n this.tweenLayer(this.cow_1, 0);\n this.tweenLayer(this.pig_1, 0);\n this.tweenLayer(this.shrimp_1, 0);\n\n } else if (getResources() >= 25 && getResources() < 50) {\n this.tweenLayer(this.tree_4, 1);\n this.tweenLayer(this.fish_2, 1);\n this.tweenLayer(this.cow_2, 1);\n this.tweenLayer(this.pig_2, 1);\n this.tweenLayer(this.shrimp_2, 1);\n\n //remove layers\n this.tweenLayer(this.tree_2, 0);\n this.tweenLayer(this.tree_3, 0);\n this.tweenLayer(this.salmon_2, 0);\n this.tweenLayer(this.tuna_2, 0);\n this.tweenLayer(this.cow_1, 0);\n this.tweenLayer(this.pig_1, 0);\n this.tweenLayer(this.shrimp_1, 0);\n\n } else if (getResources() >= 50 && getResources() < 75) {\n this.tweenLayer(this.tree_3, 1);\n this.tweenLayer(this.tree_2, 1);\n this.tweenLayer(this.fish_2, 1);\n this.tweenLayer(this.salmon_2, 1);\n this.tweenLayer(this.tuna_2, 1);\n this.tweenLayer(this.whale_2, 1);\n this.tweenLayer(this.cow_1, 1);\n this.tweenLayer(this.pig_1, 1);\n this.tweenLayer(this.shrimp_1, 1);\n\n //remove layers\n this.tweenLayer(this.tree_1, 0);\n this.tweenLayer(this.salmon_1, 0);\n this.tweenLayer(this.tuna_1, 0);\n this.tweenLayer(this.fish_1, 0);\n this.tweenLayer(this.whale_1, 0);\n\n } else if (getResources() >= 75) {\n this.tweenLayer(this.tree_1, 1);\n this.tweenLayer(this.fish_1, 1);\n this.tweenLayer(this.salmon_1, 1);\n this.tweenLayer(this.tuna_1, 1);\n this.tweenLayer(this.whale_1, 1);\n }\n\n // Check Economy Status\n if (getEconomy() < 25) {\n this.tweenLayer(this.factory_2, 0);\n\n // remove layers\n this.tweenLayer(this.wind_turbines_3, 0);\n } else if (getEconomy() >= 25 && getEconomy() < 50) {\n this.tweenLayer(this.factory_2, 1);\n\n // remove layers\n this.tweenLayer(this.factory_1, 0);\n this.tweenLayer(this.wind_turbines_2, 0);\n this.tweenLayer(this.wind_turbines_3, 0);\n\n } else if (getEconomy() >= 50 && getEconomy() < 75) {\n this.tweenLayer(this.factory_1, 1);\n this.tweenLayer(this.wind_turbines_3, 1);\n\n // remove layers\n this.tweenLayer(this.wind_turbines_1, 0);\n this.tweenLayer(this.wind_turbines_2, 0);\n\n } else if (getEconomy() >= 75) {\n this.tweenLayer(this.wind_turbines_1, 1);\n this.tweenLayer(this.wind_turbines_2, 1);\n }\n\n // Check Society status\n if (getSociety() < 33){\n // remove layers\n this.tweenLayer(this.house_2, 0);\n this.tweenLayer(this.bush_2, 0);\n\n } else if (getSociety() >= 33 && getSociety() < 66) {\n // remove layers\n this.tweenLayer(this.house_1, 0);\n this.tweenLayer(this.bush_1, 0);\n\n } else if (getSociety() > 66) {\n this.tweenLayer(this.house_1, 1);\n this.tweenLayer(this.bush_1, 1);\n this.tweenLayer(this.house_2, 1);\n this.tweenLayer(this.bush_2, 1);\n }\n }",
"function ChangeUnitMovementSpeedBasedOnTerrainType(object) {\n var pixel = context.getImageData(object.currentPos.x, object.currentPos.y, 1, 1);\n /*console.log(\"pixel red\",pixel.data[0]);\n console.log(\"pixel green\",pixel.data[1]);\n console.log(\"pixel blue\",pixel.data[2]);\n console.log(\"pixel alpha\",pixel.data[3]);*/\n var currentTerrainType = object.terrain;\n\n if((pixel.data[0]===255)&&(pixel.data[1]===255)&&(pixel.data[2]===255)){\n object.terrain = \"clear\";\n if(currentTerrainType!=\"clear\"){\n SendUnitList();\n }\n //console.log(\"clear set\");\n }\n else{\n object.terrain = \"slow\";\n if(currentTerrainType!=\"slow\"){\n SendUnitList();\n }\n //console.log(\"slow set\");\n }\n}",
"function skyChanges() {\n if (globalData.current[\"is_day\"] == \"no\") {\n document.querySelector(\".sky\").style.background = \"var(--night-sky)\";\n\n document.querySelector(\n \".weather-icon\"\n ).src = `./icons/${globalData.current.weather_code}-night.png`;\n document.querySelector(\".is_day\").innerText = \"Night\";\n } else if (globalData.current[\"is_day\"] == \"yes\") {\n document.querySelector(\".sky\").style.background = \"var(--day-sky)\";\n\n document.querySelector(\n \".weather-icon\"\n ).src = `../icons/${globalData.current.weather_code}.png`;\n document.querySelector(\".is_day\").innerText = \"Day\";\n }\n}",
"function ChangeSeason() {\n if (summer == true) {\n changeTexture(\"summer\");\n removeSnow();\n summer = false;\n snowing = false;\n }\n if (winter == true) {\n changeTexture(\"winter\");\n if(snowing == false){\n addSnow();\n snowing = true;\n }\n winter = false;\n }\n}",
"function mapIconsToSkycons() {\n if(main == 'Thunderstorm') {\n main = 'SLEET';\n }\n if(main == 'Drizzle') {\n main = 'RAIN';\n }\n if(main == 'Clear') {\n main = 'CLEAR_DAY';\n }\n if(main == 'Clouds') {\n main = 'PARTLY_CLOUDY_DAY';\n }\n }",
"function changePlanet() {\r\n\tif(planetType == 0)\r\n\t{// Change to Jupiter\r\n\t\tplanetType = 1;\r\n\t\tplanet.material = jupiterMaterial;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tplanetType = 0;\r\n\t\tplanet.material = earthMaterial;\r\n\t}\r\n}",
"function update_objet(){\n var shader;\n switch(shader_actif){\n case \"miroir\":\n shader = \"objCT\";\n break;\n\n case \"phong\":\n shader = \"objPhong\";\n break;\n }\n middleobject = new MiddleObject(shader, name_object);\n}",
"function OnCollisionEnter(col: Collision) {\n\tif (col.gameObject.tag == \"Ground\") {\n\t\tonGround = true;\n\t}\n}",
"function collisionUpdate(entity) {\n\n if (entity === undefined) {\n for (var i = 0; i < entities.length; i += 1) {\n entities[i].onGround = false;\n }\n } else {\n entity.onGround = false;\n }\n }",
"changeVehicle() {\n if (this.userData.vehicle = 'car') {\n this.vehicles.motorcycle.position.copy(this.vehicles.car.position);\n this.scene.remove(this.vehicles.car);\n this.scene.add(this.vehicles.motorcycle);\n this.userData.vehicle = 'motorcycle';\n } else {\n this.vehicles.car.position.copy(this.vehicles.motorcycle.position);\n this.scene.remove(this.vehicles.motorcycle);\n this.scene.add(this.vehicles.car);\n this.userData.vehicle = 'car';\n }\n }",
"transitionUsualState() {\n if (!Util.onGround(this.entity)) {\n this.ai.changeState(`fall`);\n } else if (Math.abs(this.entity.body.velocityX) < 100) {\n this.ai.changeState(`stationary`);\n } else {\n this.ai.changeState(`walk`);\n }\n }",
"function switchTranslation(target, targetScale, preObj, preObjScale){\n\n let planetNum;\n let preSunSize;\n let prePlanetSize = [];\n let preMoonSize;\n let targetPos = new THREE.Vector3();\n let cameraPos = new THREE.Vector3();\n let distance;\n let dir = new THREE.Vector3();\n let desiredScale = 0.0003;\n let scaledPercent;\n let preScalePercent;\n\n preScalePercent = desiredScale - preObjScale;\n preScalePercent /= 100;\n\n //This is the percentage change for the previous object\n preScalePercent /= preObjScale;\n\n //Get the preSunSize of the sun\n preSunSize = jsonObj.sun.radius / jsonObj.sizeScale / 10;\n preSunSize += ((jsonObj.sun.radius / jsonObj.sizeScale / 10) * preScalePercent) * 100;\n\n //Get the previous scale of all the planets\n for (let i=0; i<jsonObj.numPlanets; i++){\n prePlanetSize[i] = jsonObj.planets[i].radius / jsonObj.sizeScale;\n\n //Get the previous size of the moon\n //Note: applied only to Earths moon\n if (jsonObj.planets[i].moon){\n preMoonSize = jsonObj.planets[i].moon.radius / jsonObj.sizeScale;\n }\n\n prePlanetSize[i] += ((jsonObj.planets[i].radius / jsonObj.sizeScale) * preScalePercent) * 100;\n\n if (jsonObj.planets[i].moon){\n preMoonSize += ((jsonObj.planets[i].moon.radius / jsonObj.sizeScale) * preScalePercent) * 100;\n }\n }\n\n //Check what the target is\n if (target == sunObj ){\n scaledPercent = desiredScale - preSunSize;\n scaledPercent /= 100;\n\n //This is the percentage change that will be applied to the solar system\n scaledPercent /= preSunSize;\n\n //Note Only applied to Earths Moon\n } else if (target == moonObj){\n scaledPercent = desiredScale - preMoonSize;\n scaledPercent /= 100;\n\n //This is the percentage change that will be applied to the solar system\n scaledPercent /= preMoonSize;\n\n } else {\n\n for (let i=0; i<jsonObj.numPlanets; i++){\n if (target == planets[i]){\n planetNum = i;\n scaledPercent = desiredScale - prePlanetSize[i];\n scaledPercent /= 100;\n\n //This is the percentage change that will be applied to the solar system\n scaledPercent /= prePlanetSize[i];\n }\n }\n }\n\n //Sun\n if (target == sunObj) {\n sunObj.scale.addScalar(preSunSize * scaledPercent);\n }\n\n //Scale Planets\n for (let i=0; i<jsonObj.numPlanets; i++){\n planets[i].scale.addScalar(prePlanetSize[i] * scaledPercent);\n\n //Scale moon\n if (jsonObj.planets[i].moon){\n moonObj.scale.addScalar(preMoonSize * scaledPercent);\n }\n }\n\n //Move target towards camera\n let box = new THREE.Box3();\n camera.getWorldPosition(cameraPos);\n\n //Sun\n if (target == sunObj){\n originPoint.getWorldPosition(targetPos);\n box.setFromObject(sunObj);\n }\n\n //Planet\n if (planetNum || target == planets[0]) {\n planetOrigins[planetNum].getWorldPosition(targetPos);\n box.setFromObject(planets[planetNum]);\n }\n\n\n //Moon\n if (target == moonObj){\n moonOrigin.getWorldPosition(targetPos);\n box.setFromObject(moonObj);\n }\n\n\n dir.subVectors(cameraPos, targetPos).normalize();\n distance = box.distanceToPoint(cameraPos);\n distance -= 0.1; //Camera Buffer\n originPoint.translateOnAxis(dir, distance / jsonObj.objTranslation.timeStep);\n}",
"updateTexture(sky) {\n for (let i = 0; i < this.m_faceCount; ++i) {\n this.fillTextureData(this.m_faces[i].image.data, i, new three_1.Color(sky.topColor), new three_1.Color(sky.bottomColor), new three_1.Color(sky.groundColor), sky.monomialPower);\n this.m_faces[i].needsUpdate = true;\n }\n if (this.m_projectionType === harp_geoutils_1.ProjectionType.Spherical) {\n this.m_skybox.needsUpdate = true;\n }\n }",
"changeblend() {\r\n\t\t\t\tfor (layersindex = 0; layersindex < vm.scenestore.s_mcount; layersindex++) {\r\n\t\t\t\t\tvm.mockup_object_blink[layersindex].blendMode = vm.blend_mode;\r\n\t\t\t\t}\r\n\t\t\t}",
"function changeDrink(kidneyScene, value) {\n /* Switch the ureter material */\n switch (value) {\n case \"Water\":\n histColor = params.waterColor;\n params.waterColor = \"rgba(12, 132, 230, 0.8)\";\n break;\n case \"Milk\":\n histColor = params.waterColor;\n params.waterColor = \"rgba(220, 217, 205, 0.8)\";\n break;\n case \"Orange Juice\":\n histColor = params.waterColor;\n params.waterColor = \"rgba(255, 127, 51,0.8)\";\n break;\n case \"reset\":\n params.waterColor = histColor;\n break;\n default:\n console.log(\"error\")\n }\n var selectedObject = kidneyScene.getObjectByName(\"Ureter_mesh\");\n selectedObject.traverse(function (child) {\n texture = ctx_texture()\n const material = new THREE.MeshBasicMaterial({\n map: texture,\n side: THREE.DoubleSide,\n depthWrite: true,\n depthTest: true,\n transparent: true,\n opacity: 0.5\n });\n child.material = material;\n });\n}",
"function onGround_vs(){\n\n\tif (jump_ended_vs == false) {\n\t\t// before jump\n\t\t//console.log('before jump');\n\t\tbefore_jump_vs += 1;\n\t\t$color_state_vs.push('before jump')\n\t\t//console.log(before_jump);\n\t} else if (jump_ended_vs == true) {\n\t\t// after jump\n\t\tafter_jump_vs += 1;\n\t\t$color_state_vs.push('after jump');\n\t}\n\t\n\telapsed_time_on_air_vs = 0;\n\tair_interval_vs = 0;\n\tinterval_vs += 1;\n\n\tinitialYaw_vs = $yaw_vs[0];\n \t//console.log(initialYaw);\n\n\t// If there have been 180\n\tif ( plus180_vs == true ) { $yaw_vs [k] = $yaw_vs[k] + 180; $roll_vs[k] = $roll_vs[k] ; $pitch_vs[k] = $pitch_vs[k] ;}\n \tif ( minus180_vs == true ) { $yaw_vs[k] = $yaw_vs[k] - 180; $roll_vs[k] = $roll_vs[k] ; $pitch_vs[k] = $pitch_vs[k] ; }\n\n \tinitialYaw_vs = $yaw_vs[0];\n \ttotal_angle_diff_vs = $yaw_vs[k] - initialYaw_vs;\n \t// to radians\n \ttotal_angle_diff_vs = total_angle_diff_vs*pi/180;\n\n \t// Calculate x positions\n \txSpeed_vs = totalSpeed_vs*Math.sin(total_angle_diff_vs);\n \txPosition_vs = xPreviousPosition_vs + xSpeed_vs*time;\n \txPreviousPosition_vs = xPosition_vs;\n\n \t// Calculate y positions\n \tySpeed_vs = totalSpeed_vs*Math.cos(total_angle_diff_vs);\n \tyPosition_vs = yPreviousPosition_vs + ySpeed_vs*time;\n \tyPreviousPosition_vs = yPosition_vs;\n\n \t// Update z: is always 0 on ground\n \tzPosition_vs = 0;\n \t// Update pitch: is always 0 on ground\n \t$pitch_vs[k] = 0;\n\n \t// Push yaw, pitch, roll / x, y, z positions\n\t$total_yaws_vs.push(total_angle_diff_vs);\n\t$total_pitchs_vs.push($pitch_vs[k]);\n\t$total_rolls_vs.push($roll_vs[k]);\n\t$total_x_positions_vs.push(xPosition_vs);\n\t$total_y_positions_vs.push(yPosition_vs);\n\t$total_z_positions_vs.push(zPosition_vs);\n\n\t$reception_vs.push(0);\n\ttailUp_vs = false;\n\tnoseUp_vs = false;\n\n}",
"function changeMaterial(obj) {\n var skinImage = THREE.ImageUtils.loadTexture('../assets/Images/skin.jpg');\n var bloodImage = THREE.ImageUtils.loadTexture('../assets/Images/blood.jpg');\n if (obj.timesHit == 1) {\n uniforms = {\n tex: {type : \"t\", value: skinImage},\n tex2: {type : \"t\", value: bloodImage},\n texLevel:{type:\"f\", min: 0.0, max: 1.0, value: 0.8},\n texLevel2:{type:\"f\", min: 0.0, max: 1.0, value: 0.2},\n };\n } else if (obj.timesHit == 2) {\n uniforms = {\n tex: {type : \"t\", value: skinImage},\n tex2: {type : \"t\", value: bloodImage},\n texLevel:{type:\"f\", min: 0.0, max: 1.0, value: 0.6},\n texLevel2:{type:\"f\", min: 0.0, max: 1.0, value: 0.4},\n };\n } else if (obj.timesHit == 3) {\n uniforms = {\n tex: {type : \"t\", value: skinImage},\n tex2: {type : \"t\", value: bloodImage},\n texLevel:{type:\"f\", min: 0.0, max: 1.0, value: 0.4},\n texLevel2:{type:\"f\", min: 0.0, max: 1.0, value: 0.6},\n };\n } else if (obj.timesHit == 4) {\n uniforms = {\n tex: {type : \"t\", value: skinImage},\n tex2: {type : \"t\", value: bloodImage},\n texLevel:{type:\"f\", min: 0.0, max: 1.0, value: 0.2},\n texLevel2:{type:\"f\", min: 0.0, max: 1.0, value: 0.8},\n };\n } else {\n uniforms = {\n tex: {type : \"t\", value: skinImage},\n tex2: {type : \"t\", value: bloodImage},\n texLevel:{type:\"f\", min: 0.0, max: 1.0, value: 0.0},\n texLevel2:{type:\"f\", min: 0.0, max: 1.0, value: 1.0},\n };\n }\n \n var vertexShader = document.getElementById('vertexShader').text;\n var fragmentShader = document.getElementById('fragmentShader').text;\n var newMaterial = new THREE.ShaderMaterial({ \n uniforms: uniforms,\n vertexShader: vertexShader,\n fragmentShader: fragmentShader, \n });\n obj.material = newMaterial;\n }",
"function OnCollisionExit2D()\n{\n maybeOffGround = 1;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get a react component from name (components can be an angular injectable e.g. value, factory or available on window | function getReactComponent( name, $injector ) {
// if name is a function assume it is component and return it
if (angular.isFunction(name)) {
return name;
}
// a React component name must be specified
if (!name) {
throw new Error('ReactComponent name attribute must be specified');
}
// ensure the specified React component is accessible, and fail fast if it's not
var reactComponent;
try {
reactComponent = $injector.get(name);
} catch(e) { }
if (!reactComponent) {
try {
reactComponent = name.split('.').reduce(function(current, namePart) {
return current[namePart];
}, window);
} catch (e) { }
}
if (!reactComponent) {
throw Error('Cannot find react component ' + name);
}
return reactComponent;
} | [
"function getReactComponent( name, $injector ) {\n // if name is a function assume it is component and return it\n if (angular.isFunction(name)) {\n return name;\n }\n\n // a React component name must be specified\n if (!name) {\n throw new Error('editor-ui-lib: UI component name attribute must be specified. See docs here: https://dev.wix.com/docs/ui-lib/ui-controls/');\n }\n\n // ensure the specified React component is accessible, and fail fast if it's not\n var reactComponent;\n try {\n reactComponent = $injector.get(name);\n } catch(e) { }\n\n if (!reactComponent) {\n try {\n reactComponent = name.split('.').reduce(function(current, namePart) {\n return current[namePart];\n }, window);\n } catch (e) { }\n }\n\n if (!reactComponent) {\n throw Error('editor-ui-lib: Cannot find react component ' + name);\n }\n\n return reactComponent;\n}",
"findComponent(name) {\n const { components } = this;\n for (let i = components.length - 1; i >= 0; i -= 1) {\n const component = components[i];\n if (component.name === name) {\n return component;\n }\n }\n return null;\n }",
"getComponent(name){\n\t\tfor(let component of this.components){\n\t\t\tif(component.constructor.name == name)\n\t\t\t\treturn component;\n\t\t}\n\t\t//If we didn't find it, search any children we have\n\t\tfor(let child of this.children){\n\t\t\tlet component = child.getComponent(name);\n\t\t\tif(component) return component;\n\t\t}\n\t}",
"getComponentByName(name) {\n if(!this.components[name]){\n throw new Error('Component with name `'+name +'` not found ');\n }\n return this.components[name];\n }",
"function getBobrilComponent( name, $injector ) {\n // if name is a function assume it is component and return it\n if (angular.isFunction(name)) {\n return name;\n }\n\n // a Bobril component name must be specified\n if (!name) {\n throw new Error('BobrilComponent name attribute must be specified');\n }\n\n // ensure the specified Bobril component is accessible, and fail fast if it's not\n var bobrilComponent;\n try {\n bobrilComponent = $injector.get(name);\n } catch(e) { }\n\n if (!bobrilComponent) {\n try {\n bobrilComponent = name.split('.').reduce(function(current, namePart) {\n return current[namePart];\n }, window);\n } catch (e) { }\n }\n\n if (!bobrilComponent) {\n throw Error('Cannot find bobril component ' + name);\n }\n\n return bobrilComponent;\n }",
"getComponent(name) {\n const hasComponent = this.hasComponent(name);\n if (!hasComponent) throw new Error(`getComponent(): component \"${name}\" not found.`);\n return this.components.find((component)=>component.name === name);\n }",
"component(name) {\n if (this.components[name] === undefined) {\n this.components[name] = new ComponentStore(name);\n }\n return this.components[name];\n }",
"getComponent(name) {\n return (this._nextDict[name] || [undefined])[0];\n }",
"getComponent(klass, baseName) {\n const component = _.find(this.components, (c) => {\n return (c instanceof klass) && c.baseName == baseName;\n })\n return component;\n }",
"get(name) {\n return this.getComponent(name);\n }",
"getComponentByName (name, options) {\n // check for arguments\n if (!name) throw ReferenceError('name')\n\n // assign options to opts\n const opts = options || {}\n\n // declare component name\n let componentName = name\n\n // if the name has arguments like name?arg1=val&arg2=val2\n // try to use querystring to parse and assign to options\n if (name.indexOf('?') >= 0) {\n // check the name has arguments or not\n const index = name.indexOf('?')\n\n // get componentName from name string\n componentName = name.toLowerCase().substring(0, index)\n\n // parse options from name string\n Object.assign(\n opts,\n querystring.parse(name.substring(index + 1, name.length))\n )\n }\n\n // get instance of nblue application\n const nblue = this.NBlue\n\n // get instance of components cache\n const cache = this.Cache\n\n // get instance of components cache\n const uidCache = this.UidCache\n\n // create new instance of application if can't find it in cache\n if (!cache.has(componentName) || opts.new === true) {\n // get Class of application by name\n const Component = this.createComponent(componentName, opts)\n\n // create new instance of application\n const component = new Component(nblue, opts)\n\n // throw error if create application failed\n if (!component) {\n throw new ReferenceError(\n `Doesn't support application by name: ${componentName}`\n )\n }\n\n // save component to cache by uid\n uidCache.set(component.Uid, component)\n\n // return new instance of component without putting to cache\n if (opts.new === true) return component\n\n // save instance of application to cache\n cache.set(componentName, component)\n }\n\n // get instance of applicatin from cache by name\n return cache.get(componentName)\n }",
"guessComponent (): ?Object {\n const registeredComponents = this.component.components\n if (!registeredComponents) {\n return null\n }\n const name = this.guessComponentName()\n return Object.values(registeredComponents)\n .find(component => {\n return component.name === name\n }) || null\n }",
"function getComponentConstructor(ractive, name) {\n var instance = findInstance('components', ractive, name);\n var Component;\n\n if (instance) {\n Component = instance.components[name];\n\n if (Component && !Component.isInstance) {\n if (Component.default && Component.default.isInstance) { Component = Component.default; }\n else if (!Component.then && isFunction(Component)) {\n // function option, execute and store for reset\n var fn = Component.bind(instance);\n fn.isOwner = hasOwn(instance.components, name);\n Component = fn();\n\n if (!Component) {\n warnIfDebug(noRegistryFunctionReturn, name, 'component', 'component', {\n ractive: ractive\n });\n return;\n }\n\n if (isString(Component)) {\n // allow string lookup\n Component = getComponentConstructor(ractive, Component);\n }\n\n Component._fn = fn;\n instance.components[name] = Component;\n }\n }\n }\n\n return Component;\n}",
"buildComponent(name) {\n if (!(name in this.components)) {\n console.debug(\"Unknown component name\");\n return null;\n }\n // Assemble the dependencies -- recursively if required. This follows the\n // DAG of dependencies in a DFS-like manner, effectively performing a top-sort.\n let component = this.components[name];\n let deps = {};\n // `argName` is the name that the component's ctor expects and the `depName` is the\n // name of the component within the IoC container that is bound to this argument.\n for (let argName in component.deps) {\n let depName = component.deps[argName];\n deps[argName] = this.getComponent(depName);\n }\n\n // The dependencies are now ready to be passed to the components ctor.\n let instance = component.ctor.call(this, deps);\n return instance;\n }",
"resolveReactComponent(parsedName) {\n parsedName.type = 'component';\n const result =\n this._resolveReactStyleFile(parsedName) || this.resolveOther(parsedName);\n parsedName.type = 'react-component';\n return result;\n }",
"getComponentName(name, def) {\n return _.get(self.options, `components.${name}`, def);\n }",
"getComponent(e, name) {\n return this.component(name).get(e);\n }",
"function component(name) {\n if (arguments.length <= 1) {\n return;\n }\n\n var result = combine.apply(\n this,\n [ui.common].concat(\n [].slice.apply(arguments).slice(1)\n )\n );\n\n Vue.component(name, result);\n return result;\n}",
"function getComponentConstructor ( ractive, name ) {\n\t \tvar instance = findInstance( 'components', ractive, name );\n\t \tvar Component;\n\n\t \tif ( instance ) {\n\t \t\tComponent = instance.components[ name ];\n\n\t \t\t// best test we have for not Ractive.extend\n\t \t\tif ( !Component._Parent ) {\n\t \t\t\t// function option, execute and store for reset\n\t \t\t\tvar fn = Component.bind( instance );\n\t \t\t\tfn.isOwner = instance.components.hasOwnProperty( name );\n\t \t\t\tComponent = fn();\n\n\t \t\t\tif ( !Component ) {\n\t \t\t\t\twarnIfDebug( noRegistryFunctionReturn, name, 'component', 'component', { ractive: ractive });\n\t \t\t\t\treturn;\n\t \t\t\t}\n\n\t \t\t\tif ( typeof Component === 'string' ) {\n\t \t\t\t\t// allow string lookup\n\t \t\t\t\tComponent = getComponentConstructor( ractive, Component );\n\t \t\t\t}\n\n\t \t\t\tComponent._fn = fn;\n\t \t\t\tinstance.components[ name ] = Component;\n\t \t\t}\n\t \t}\n\n\t \treturn Component;\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lets you make any Instagram API request. | function api(obj) {
var method = obj.method || 'GET',
params = obj.params || {},
url;
params['access_token'] = tokenStore['igtoken'];
url = 'https://api.instagram.com/v1' + obj.path + '?' + toQueryString(params);
if (method === 'GET') {
jsonp(url, function(data) {
if (obj.success) obj.success(data);
});
} else {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (obj.success) obj.success(JSON.parse(xhr.responseText));
} else {
var error = xhr.responseText ? JSON.parse(xhr.responseText).error : {
message: 'An error has occurred'
};
if (obj.error) obj.error(error);
}
}
};
xhr.open(method, url, true);
xhr.send();
}
} | [
"function instagramAPI(){\n const instagramURL = 'https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,permalink,thumbnail_url,timestamp&access_token=';\n const url = instagramURL + authKey;\n fetch(url)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayResults(responseJson))\n .catch(err => {\n $('#errorMessage').text(`Something went wrong: ${err.message}`);\n });\n}",
"function Instagram (){\r\n\r\n let xhr = new XMLHttpRequest;\r\n var resp = 0;\r\n xhr.addEventListener('load',function(){\r\n resp = JSON.parse(this.responseText)\r\n instafollowers = resp.graphql.user.edge_followed_by.count;\r\n console.log('insta' + instafollowers)\r\n Twitter()\r\n })\r\n\r\n xhr.addEventListener('error',function(){\r\n console.log('error');\r\n })\r\n\r\n if(instahandle != '')\r\n {\r\n xhr.open('GET',`https://www.instagram.com/${instahandle}/?__a=1`)\r\n xhr.send()\r\n }\r\n }",
"function loadInstagram(callback) {\n if (GLOBALS.env == \"html\") {\n instagramDatatype = \"jsonp\";\n instagramRequest = {};\n } else {\n instagramDatatype = \"json\";\n instagramRequest = {\n offset : 40\n }\n }\n\n $.ajax({\n url : GLOBALS.api.instagramUrl,\n type : \"GET\",\n data : instagramRequest,\n dataType : instagramDatatype,\n success: function(data) {\n if (GLOBALS.env == \"html\") {\n var count = 15; \n for (var i = 0; i < count; i++) {\n if (typeof data['data'] !== 'undefined' && typeof data.data[i] !== 'undefined' ) {\n posts.push({'type': 'instagram', 'img': data.data[i].images.low_resolution.url, 'date' : data.data[i].created_time, 'text': '<div class=\"txt\"><div class=\"vCenter\"><div class=\"vCenterKid\"><p>' + data.data[i].caption.text.substr(0, 140).parseURL().parseUsername().parseHashtag() + '</p></div></div></div>', 'user': data.data[i].user.username});\n }\n \n if(i == count - 1) {\n callback();\n }\n }\n } else {\n var count = Math.min(data.length, 15);\n for (var i = 0; i < count; i++) {\n posts.push({'type': 'instagram', 'text': '<div class=\"txt\"><div class=\"vCenter\"><div class=\"vCenterKid\"><p>' + data[i].message.substr(0, 140).parseURL().parseUsername(true).parseHashtag(true) + '</p></div></div></div>', 'img': data[i].content});\n \n if(i == count - 1) {\n callback();\n }\n }\n }\n }\n });\n }",
"function loadInstagram(callback) {\n if (GLOBALS.env == \"html\") {\n instagramDatatype = \"jsonp\";\n instagramRequest = {};\n } else {\n instagramDatatype = \"json\";\n instagramRequest = {\n offset : 40\n }\n }\n\n $.ajax({\n url : GLOBALS.api.instagramUrl,\n type : \"GET\",\n data : instagramRequest,\n dataType : instagramDatatype,\n success: function(data) {\n if (GLOBALS.env == \"html\") {\n var count = 15; \n for (var i = 0; i < count; i++) {\n if (typeof data.data[i] !== 'undefined' ) {\n posts.push({'type': 'instagram', 'img': data.data[i].images.low_resolution.url, 'date' : data.data[i].created_time, 'text': '<div class=\"txt\"><div class=\"vCenter\"><div class=\"vCenterKid\"><p>' + data.data[i].caption.text.substr(0, 140).parseURL().parseUsername().parseHashtag() + '</p></div></div></div>', 'user': data.data[i].user.username});\n }\n \n if(i == count - 1) {\n callback();\n }\n }\n } else {\n var count = Math.min(data.length, 15);\n for (var i = 0; i < count; i++) {\n posts.push({'type': 'instagram', 'text': '<div class=\"txt\"><div class=\"vCenter\"><div class=\"vCenterKid\"><p>' + data[i].message.substr(0, 140).parseURL().parseUsername(true).parseHashtag(true) + '</p></div></div></div>', 'img': data[i].content});\n \n if(i == count - 1) {\n callback();\n }\n }\n }\n }\n });\n }",
"function fetchInstagramPosts(){\n\tvar feed = new Instafeed({\n\t\tget: 'user',\n\t\tuserId: 227012267,\n\t\taccessToken: '283823831.ee2c8fb.d8276e2ea678489f9a2d283b720dc64a',\n\t\tresolution: 'low_resolution',\n\t\ttemplate: '<img class=\"instagramPhotoFormatting\" onclick=OpenUrlInMobileOrWebpage(\"{{link}}\",\"{{id}}\") class=\"instagram\" src=\"{{image}}\"/>'\n\t});\n\tfeed.run();\t\n}",
"function loadInstagram(callback) {\n if (GLOBALS.env == \"html\") {\n instagramDatatype = \"json\";\n instagramRequest = {};\n } else {\n instagramDatatype = \"json\";\n instagramRequest = {\n offset : 40\n }\n }\n\n $.ajax({\n url : GLOBALS.api.instagramUrl,\n type : \"GET\",\n data : instagramRequest,\n dataType : instagramDatatype,\n success: function(data) {\n\n if (GLOBALS.env == \"html\") {\n var count = 15; \n for (var i = 0; i < count; i++) {\n if (typeof data.data !== 'undefined' ) {\n if (typeof data.data[i] !== 'undefined' ) {\n posts.push({'type': 'instagram', 'img': data.data[i].images.low_resolution.url, 'date' : data.data[i].created_time, 'text': '<div class=\"txt\"><div class=\"vCenter\"><div class=\"vCenterKid\"><p>' + data.data[i].caption.text.substr(0, 140).parseURL().parseUsername().parseHashtag() + '</p></div></div></div>', 'user': data.data[i].user.username});\n }\n }\n \n if(i == count - 1) {\n callback();\n }\n }\n } else {\n var count = Math.min(data.length, 15);\n for (var i = 0; i < count; i++) {\n posts.push({'type': 'instagram', 'text': '<div class=\"txt\"><div class=\"vCenter\"><div class=\"vCenterKid\"><p>' + data[i].message.substr(0, 140).parseURL().parseUsername(true).parseHashtag(true) + '</p></div></div></div>', 'img': data[i].content});\n\n if(i == count - 1) {\n callback();\n }\n }\n }\n },\n error: function (xhr, ajaxOptions, thrownError) {\n\n }\n });\n }",
"function InstagramClient (access_token, client_id, client_secret, user_id) {\n\tthis.access_token = access_token;\n\tthis.client_id = client_id;\n\tthis.client_secret = client_secret;\n\tthis.user_id = user_id;\n \tthis.next_url = '/v1/users/' + user_id + '/media/recent/?access_token=' + access_token;\n}",
"function getInstagram()\n{\n\t//Define variables\n\tvar html = $('#instagram-slide'), entry, link, image, user, message, itemId, divider, wrapper;\n\n\t//Fire up the AJAXerator, Lem!\n\t$.ajax(\n\t\t'/social/instagram',\n\t\t{\n\t\t\t//Aww yeah, she's hummin' away\n\t\t\tsuccess: function(response)\n\t\t\t{\n\n\t\t\t\t//What've we got here? Fresh batch o' instagrams, I reckon\n\t\t\t\tresponse = JSON.parse(response);\n\t\t\t\tresponse = response.data;\n\n\t\t\t\t//We're done loadin, git rid o' that shitty spinner\n\t\t\t\thtml.find('.loading-gif').remove();\n\n\t\t\t\t//Now lets start mooshin' this here JSON into some good ol' HTML\n\t\t\t\tresponse.forEach(function(gram){\n\n\t\t\t\t\t//Each one o' these sumbitches got them an image and some text in a link, plus a divider.\n\t\t\t\t\tentry = $('<div class=\"social-entry\"></div>');\n\n\t\t\t\t\t//Get the link together, 'n stick th'image right in thur\n\t\t\t\t\tlink = $('<a href=\"'+ gram.link +'\" target=\"_blank\"></a>');\n\t\t\t\t\timage = $('<div class=\"social-image\" style=\"background: url(' + gram.images.thumbnail.url + ') no-repeat 50% 50%;\"></div>');\n\n\t\t\t\t\t//Plaster that message on\n\t\t\t\t\tmessage = $('<div class=\"social-message\"></div>');\n\t\t\t\t\tmessage.text(gram.caption.text);\n\n\t\t\t\t\t//Whip up a lil' divider\n\t\t\t\t\tdivider = $('<div class=\"divider\"></div>');\n\n\t\t\t\t\t//Now start mixin'\n\t\t\t\t\tlink.append(image).append(message);\n\n\t\t\t\t\tentry.append(link);\n\n\t\t\t\t\twrapper = $('<div class=\"social-wrapper\"></div>');\n\n\t\t\t\t\twrapper.append(entry).append(divider);\n\n\t\t\t\t\t//And we're all set on that one.\n\t\t\t\t\thtml.append(wrapper);\n\t\t\t\t\t\n\t\t\t\t});\n\n\t\t\t\t//If the sidebar slide has been toggled since the request started, fade it in\n\t\t\t\tif($('#instagram-tab').hasClass('active'))\n\t\t\t\t{\n\t\t\t\t\t$('.sidebar-slide .inner').html($('#instagram-slide').html());\n\t\t\t\t}\n\t\t\t},\n\n\t\t\t//Aw shit, we got a bug. Time to flush 'em out.\n\t\t\terror: function(response)\n\t\t\t{\n\t\t\t\tthrow {\n\t\t\t\t\t\tname: 'HTTPException', \n\t\t\t\t\t\tmessage: response\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t);\n}",
"function fnInstagram(word) {\n\t\tvar address = \"https://api.instagram.com/v1/tags/\" + word + \n\t\t\t\"/media/recent?callback=?&client_id=d51f6ee392ba41dfa0c28e580e9fa5da&min_id=10\";\n\t\t$.getJSON(address, fnDisplayPics);\n\t}",
"async function getInstagram (req, res, next) {\n const token = req.user.tokens.find(token => token.kind === 'instagram');\n ig.use({ client_id: process.env.INSTAGRAM_ID, client_secret: process.env.INSTAGRAM_SECRET });\n ig.use({ access_token: token.accessToken });\n try {\n const userSearchAsync = promisify(ig.user_search);\n const userAsync = promisify(ig.user);\n const userSelfMediaRecentAsync = promisify(ig.user_self_media_recent);\n const searchByUsername = await userSearchAsync('richellemead');\n const searchByUserId = await userAsync('175948269');\n const myRecentMedia = await userSelfMediaRecentAsync();\n res.render('original/example/instagram', {\n title: 'Instagram API',\n usernames: searchByUsername,\n userById: searchByUserId,\n myRecentMedia\n });\n } catch (error) {\n next(error);\n }\n}",
"function InstagramClass(){\n //set your config preferences here\n this.accessToken='';\n this.clientId='';\n this.count=1;\n this.url='https://api.instagram.com/v1';\n this.hash='expoinmobiliaria2014';\n this.userId='596741613';\n this.location=null;\n this.search=null;\n this.basicData=null;\n }",
"function InstagramGallery(params,$e){\n\t'use strict';\n\n\tvar o = {};\n\n\to.s = {\n\t\tresourcesLoaded:undefined,\n\t\tmethod:params.method,\n\t\ttagOptions:params.tagOptions,\n\t\tuserOptions:params.userOptions,\n\t\taccessToken:params.accessToken,\n\t\timageCount:params.imageCount,\n\t\tid:$.attr('id')\n\t};\n\n\t/**********************************\n\tInitialize\n\n\tNotes\n\t[1] \tAfter the resources for using instafeed have been loaded, get the images.\n\t[2] \tIf it's using tags, and there's a list of users then filter by that list of users\n\t[3] \tDoing this to avoid posts with multiple photos since at this point they just come across as gray\n\t\t\tsquares in the API. The feature is brand new though so it might be worth checking on this later. -meanspa 2.24.17\n\t**********************************/\n\to.init = function(){\n\t\tvar promises = $.grep(Globals.s.promises, function(p){ return p.name === 'InstafeedResources'; })\n\t\tif (promises.length === 0){\n\t\t\tvar resources = ['../plugins/instafeed/instafeed.min.js']\n\t\t\to.s.resourcesLoaded = Globals.getStuff(resources);\n\t\t\tvar p = {\n\t\t\t\tname:'InstafeedResources',\n\t\t\t\tpromise:o.s.resourcesLoaded\n\t\t\t}\n\t\t\tGlobals.s.promises.push(p);\n\t\t}\n\t\telse {\n\t\t\to.s.resourcesLoaded = promises[0].promise;\n\t\t}\n\t\to.s.resourcesLoaded.then(function(){ /*[1]*/\n\t\t\tvar successCallback = function(r){\n\t\t\t\tif(o.s.method === 'tag' && o.s.tagOptions.users && o.s.tagOptions.users.length > 0){ /*[2]*/\n\t\t\t\t\to.s.results = $.grep(r.data,function(img,i){\n\t\t\t\t\t\treturn o.s.tagOptions.users.indexOf(img.user.id) != -1;\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\to.s.results = r.data;\n\t\t\t\t}\n\t\t\t\to.s.imageCount = o.s.imageCount > o.s.results.length?o.s.results.length:o.s.imageCount;\n\t\t\t\tfor (var i = 0; i < o.s.imageCount; i++) {\n\t\t\t\t\tvar item = o.s.results[i];\n\t\t\t\t\tif (item.type === \"video\" && item.images.thumbnail.url.indexOf(\"null\") >= 0) { /*[3]*/\n\t\t\t\t\t\to.s.imageCount++;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tvar markup = '<a href=\"'+item.link+'\" target=\"_blank\" class=\"wc-instagram-thumbnail wc-card-link\"><img src=\"'+item.images.low_resolution.url+'\" alt=\"Instagram Image - '+item.caption.text.replace(/\\\"/g,'"')+'\" /></a>';\n\t\t\t\t\t\t$e.append(markup);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$.publish('dom.newElements');\n\t\t\t}\n\t\t\tvar options = {\n\t\t\t\taccessToken: o.s.accessToken,\n\t\t\t\tmock: true,\n\t\t\t\tsuccess: successCallback\n\t\t\t};\n\t\t\tif(o.s.method === 'tag'){\n\t\t\t\toptions.get = 'tagged';\n\t\t\t\toptions.tagName = o.s.tagOptions.tag;\n\t\t\t}\n\t\t\telse if(o.s.method === 'user'){\t\t\t\t\n\t\t\t\toptions.get = 'user';\n\t\t\t\toptions.userId = o.s.userOptions.userID;\n\t\t\t}\n\t\t\to.s.feed = new Instafeed(options);\n\t\t\to.s.feed.run();\n\t\t});\n\t}\n\n\treturn o;\n}",
"function queryInsta(tag) {\n instagram_url=\"https://api.instagram.com/v1/tags/\"+ tag +\"/media/recent\" + getcount + instragram_key + callback;\n\tgrabInsta();\n\t//addnewtoDB(instagram_url);\t\t\t\t// Ask instagram for tag name\n \n}",
"instagramFollow(data, ios = false) {\n // if iOS user\n if (ios && data.ios) {\n return {\n url: 'instagram://user?',\n data,\n };\n }\n\n return {\n url: `http://www.instagram.com/${data.username}?`,\n popup: {\n width: 980,\n height: 655,\n },\n };\n }",
"_loadInstagram(url, context, cb) {\n\n const instagramBase = `https://api.instagram.com/oembed?url=${encodeURIComponent(url)}&omitscript=true`;\n\n api.router.get('/api/resourceproxy', {url: instagramBase})\n .then(response => api.router.checkForOKStatus(response))\n .then(response => api.router.toJson(response))\n .then(json => {\n let tplNode = document.createElement('template'),\n parentNode,\n oldImgNode,\n newImgNode\n\n\n try {\n tplNode.innerHTML = json.html\n parentNode = tplNode.content.childNodes[0].querySelector('blockquote>div')\n oldImgNode = tplNode.content.childNodes[0].querySelector('blockquote>div>a')\n\n newImgNode = document.createElement('img')\n newImgNode.setAttribute('src', json.thumbnail_url)\n newImgNode.style.width = '100%'\n newImgNode.style.textAlign = 'center'\n\n tplNode.content.childNodes[0].style.boxShadow = null;\n parentNode.style.padding = 0;\n\n parentNode.removeChild(oldImgNode)\n parentNode.insertBefore(newImgNode, parentNode.firstChild)\n json.html = tplNode.innerHTML\n }\n catch (ex) {\n // FIXME: Maybe tell the user or log that this does not work no longer\n }\n\n cb(null, {\n author: json.author_url,\n html: json.html,\n oembed: json,\n uri: `im://instagram/${json.media_id}`,\n url: url,\n title: json.title,\n linkType: 'x-im/instagram',\n socialChannel: 'Instagram',\n socialChannelIcon: 'fa-instagram'\n }, {\n history: false\n })\n })\n .catch((error) => {\n cb(error)\n })\n\n\n }",
"function getInstagramSelf() {\n\t\tif (window.location.hash.indexOf('access_token=') !== -1) {\n\t\t\tinstagramToken = window.location.hash.split('=')[1];\n\t\t}\n\n\t\tvar currentPage = APP.History.getCurrentPage();\n\t\tif (currentPage.page.length>0 && currentPage.page[0].indexOf('access_token=') !== -1) {\n\t\t\tinstagramToken = currentPage.page[0].split('=')[1];\n\t\t}\n\n\t\tif (instagramToken) {\n\t\t\tconsole.log('instagram token accepted', instagramToken);\n\t\t\t$.getJSON('https://api.instagram.com/v1/users/self/?access_token=' + instagramToken + '&callback=?', function (result) {\n\t\t\t\tconsole.log('instagram user self result', result.data);\n\t\t\t\tinstagramUserData = result.data;\n\t\t\t\tuserData.userId = result.data.id;\n\t\t\t\tuserData.userName = result.data.username;\n\t\t\t\tuserData.userToken = instagramToken;\n\t\t\t\tAPP.Social.getInstagramImages({callback: APP.Contribute.onInstagramImagesLoaded});\n\t\t\t\tAPP.Views.switchContributionView('images');\n\t\t\t});\n\n\t\t}\n\n\t}",
"function getInstaFeed() {\n $.ajax({\n url: '/insta',\n type: 'GET',\n dataType: 'json',\n success: function success(res) {\n displayInstaImages(res);\n },\n error: function error() {}\n });\n}",
"function obtenerImagenPerfilInstagram(req,res){\n\n console.log(req.params.accesstoken)\n https.get('https://api.instagram.com/v1/users/self?access_token='.concat(req.params.accesstoken), res2 => {\n res2.setEncoding(\"utf8\");\n let body = \"\";\n res2.on(\"data\", data => {\n body += data;\n });\n res2.on(\"end\", () => {\n var resultado = JSON.parse(body);\n return res.status(200).send(resultado)\n console.log(\"devuelvo esto\",resultado)\n });\n });\n\n}",
"function getInstagramPhotos() {\n return async dispatch => {\n try {\n // Fetch Instagram photos\n const { data } = await fetchInstagramPhotos();\n\n if (data instanceof Error) {\n console.error(data);\n\n return dispatch({\n type: SET_INSTAGRAM_ERROR,\n payload: true\n });\n }\n\n dispatch({\n type: SET_INSTAGRAM_PHOTOS,\n payload: data\n });\n\n return data;\n } catch (error) {\n console.error(error);\n\n dispatch({\n type: SET_INSTAGRAM_ERROR,\n payload: true\n });\n }\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the borders and shading dialog | showBordersAndShadingDialog() {
if (this.bordersAndShadingDialogModule && !this.isReadOnlyMode && this.viewer) {
this.bordersAndShadingDialogModule.show();
}
} | [
"function showHandles() {\n\tupdateHandles();\n\tneHandle.setOpacity(1);\n\tnwHandle.setOpacity(1);\n\tseHandle.setOpacity(1);\n\tswHandle.setOpacity(1);\n}",
"function displayDialog ( )\n{\n var modal= document.getElementById('modal');\n var shade= document.getElementById('shade');\n \n //\n // if these elements do not exist, there is nothing to display\n //\n if (modal != null && shade != null)\n {\n modal.style.display = 'block';\n shade.style.display = 'block';\n document.getElementById('close_dialog').onclick= function() {\n modal.style.display=shade.style.display= 'none';\n };\n }\n}",
"function addBorderClick(obj)\n {\n \n var rgb = getColorArray(obj); //get rgb values\n var hsl = getHSLArray(rgb);\n \n //set css background the same opactiy and show border\n $(obj).css({ 'transition':'0.4s',\n \t\t\t\t\t'background': 'rgba('+ (rgb[0]) +','+ (rgb[1]) +',' + (rgb[2]) + ',0.9)',\n \t\t\t\t\t'-webkit-box-shadow': 'inset 0px 0px 0px 2px hsla('+ (hsl[0]) +','+ (hsl[1])+'%,' + (hsl[2]-15) + '%,1)'\n });\n }",
"show() {\n if (this.closeCallback !== undefined) {\n this.closeCallback();\n this.closeCallback = undefined;\n }\n\n this.applied = false;\n this.frame.style.display = 'block';\n this._generateHueCircle();\n }",
"visible (visible) {\n visible\n ? this.shade = this.createShadeLayer().show()\n : this.shade.destroy()\n }",
"show() { \n if (!this.showing) {\n this.element.style.borderStyle = 'solid'; \n this.showing = true;\n }\n }",
"_showBlurs() {\n this._blurs.forEach( ( blur ) => {\n blur.show();\n })\n }",
"function CreateOverlayGraphic() { \n CreateBlackOverlays();\n CreateScrollBarBgGraphic();\n CreateScrollBarImage();\n}",
"_createCloseModalButtonBorder() {\n const x = this._getGameWidth() - this.padding - 20;\n const y = this._getGameHeight() - this.windowHeight - this.padding;\n this.graphics.strokeRect(x, y, 20, 20);\n }",
"showStylesDialog() {\n if (this.stylesDialogModule && !this.isReadOnlyMode && this.viewer) {\n this.stylesDialogModule.show();\n }\n }",
"function primarySelectFade(obj)\n {\n var rgb = getColorArray(obj); //get rgb values\n var hsl = getHSLArray(rgb);\n \n //set css background opacity low and make border transparent\n $(obj).css({ 'transition': '0.4s',\n 'background': 'rgba('+ (rgb[0]) +','+ (rgb[1]) +',' + (rgb[2]) + ',0.3)',\n '-webkit-box-shadow': 'inset 0px 0px 0px 2px hsla('+ (hsl[0]) +','+ (hsl[1])+'%,' + (hsl[2]-15) + '%,0)'\n }); \n }",
"function showBox() {\n\n initializeState();\n\n jQuery('#calculations2').dialog( {\n autoOpen: true,\n// create: function(event) { jQuery(event.target).parent().css('position', 'fixed'); },\n width: 900,\n title: 'Calculations / Functions',\n modal: true,\n buttons: {\n \"Apply Calculations\": function() { \n apply_calculations();\n jQuery( this ).dialog( \"close\" );\n },\n Cancel: function() {\n jQuery( this ).dialog( \"close\" );\n }\n }\n });\n }",
"function _showEdgeLegend()\r\n{\r\n\r\n//\t$(\"#edge_legend .in-same-component .color-bar\").css(\r\n//\t\t\"background-color\", \"#CD976B\");\r\n//\t\r\n//\t$(\"#edge_legend .reacts-with .color-bar\").css(\r\n//\t\t\"background-color\", \"#7B7EF7\");\r\n//\t\r\n//\t$(\"#edge_legend .state-change .color-bar\").css(\r\n//\t\t\"background-color\", \"#67C1A9\");\r\n//\t\r\n//\t$(\"#edge_legend .other .color-bar\").css(\r\n//\t\t\t\"background-color\", \"#A583AB\");\r\n//\t\r\n//\t$(\"#edge_legend .merged-edge .color-bar\").css(\r\n//\t\t\"background-color\", \"#666666\");\r\n\t\r\n\t// open legend panel\r\n\t//$(\"#edge_legend\").dialog(\"open\").height(\"auto\");\r\n\t$(\"#edge_legend\").dialog(\"open\");\r\n}",
"showAllFloors() {\n this.canvas3D.showAllFloors();\n }",
"show () {\n this.setColor(); //set the brick color according to some given info\n rect(this.x, this.y, this.length, this.thickness, 3);\n }",
"drawBorder(graphics) {\r\n graphics.setColor(colors.view)\r\n graphics.drawRect(0, 0, this.widthPixels - 1, this.heightPixels - 1)\r\n }",
"function scheduledTransactionPreShow(){\r\n // set checkingColor\r\n if (selectedAccountColor === checkingColor){\r\n frmScheduledTransactionDetailsKA.skin = sknaccountCheckingBkg;\r\n frmScheduledTransactionDetailsKA.titleBarWrapper.skin = sknaccountTypeChecking;\r\n // Set savingsColor\r\n } else if (selectedAccountColor === savingsColor){\r\n frmScheduledTransactionDetailsKA.skin = sknaccountSavingsBkg;\r\n frmScheduledTransactionDetailsKA.titleBarWrapper.skin = sknaccountTypeSavings;\r\n // set creditColor\r\n } else if (selectedAccountColor === creditColor){\r\n frmScheduledTransactionDetailsKA.skin = sknaccountCreditBkg;\r\n frmScheduledTransactionDetailsKA.titleBarWrapper.skin = sknaccountTypeCredit;\r\n } \r\n}",
"function setOpacityBackGroundShopPopUpShopWidget(){\n\t document.getElementById('shopPopup').style.backgroundColor = \"rgba(0,0,0,0.7)\";\n}",
"function legendSelectFade(obj)\n {\n var rgb = getColorArray(obj); //get rgb values\n var hsl = getHSLArray(rgb);\n \n //decrease background opacity and adds border\n $(obj).css({ 'transition': '0.7s',\n 'background': 'rgba('+ (rgb[0]) +','+ (rgb[1]) +',' + (rgb[2]) + ',0.1)',\n '-webkit-box-shadow': 'inset 0px 0px 0px 1px hsla('+ (hsl[0]) +','+ (hsl[1])+'%,' + (hsl[2]-15) + '%,0.7)'\n }); \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggle whether a button's text starts 'Hide' or 'Show'. | function hiddenToggle($button)
{
var oldText = $button.text(),
hide;
if (oldText.substr(0, 4) == 'Show') {
hide = false;
$button.text('Hide' + oldText.substr(4));
} else {
hide = true;
$button.text('Show' + oldText.substr(4));
}
return hide;
} | [
"function toggleHideShowText() {\n let showHideCopy = showHideButton.innerHTML.toLowerCase() === 'hide' ? 'Show' : 'Hide';\n\n showHideButton.innerHTML = showHideCopy;\n}",
"function changeButtonText() {\n if ($(\"#myDiv\").hasClass(\"showText\")) {\n $(\"#btnShowText\").text(\"Hide Text\");\n } \n else {\n $(\"#btnShowText\").text(\"Show Text\");\n }\n }",
"function toggleVisibility(idButton, idTarget, toggleContentName) {\n\tvar targetEle = document.getElementById(idTarget);\n\tvar buttonEle = document.getElementById(idButton); \n \n if (targetEle.style.display == \"block\" ){\n targetEle.style.display = \"none\";\n\t\tbuttonEle.value = \"Show \"+toggleContentName;\n } else {\n targetEle.style.display = \"block\";\n\t\tbuttonEle.value = \"Hide \"+toggleContentName;\n }\n}",
"function toggle() {\n const desc = document.getElementById(\"show-hide\");\n if (desc.innerHTML === \"Show description\") {\n desc.innerHTML = \"Hide description\";\n } else {\n desc.innerHTML = \"Show description\";\n }\n}",
"function showChampions() {\n\n //toggle textContent of id=\"btnChampions\"\n var t = document.getElementById('btnChampions');\n //console.log(t);\n if (t.textContent == \"Hide\"){\n t.textContent = \"Show\";\n }else{\n t.textContent = \"Hide\";\n }\n\n //toggle display of id=\"champions\"\n var x = document.getElementById(\"champions\");\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n } else {\n x.style.display = \"none\";\n }\n }",
"function changeToggleText($block) {\n if ($block.children('p').css('display') == 'none') {\n $('#buttonToToggle').html('More')\n } else {\n $('#buttonToToggle').html('Less')\n }\n}",
"function toggle() {\n\t\tvar ele = document.getElementById(\"toggleText\");\n\t\tvar text = document.getElementById(\"displayText\");\n\t\tif(ele.style.display == \"block\") {\n\t\t\t\tele.style.display = \"none\";\n\t\t\ttext.innerHTML = \"show skills\";\n\t\t}\n\t\telse {\n\t\t\tele.style.display = \"block\";\n\t\t\ttext.innerHTML = \"hide skills\";\n\t\t}\n\t}",
"function toggleBtn () {\n startBtn.hidden = true\n stopBtn.hidden = false\n}",
"function toggleSearchOptionsTitle() {\n if ($(searchForm).css(\"display\") === \"none\") {\n $(searchOptionsBtn).text('Hide Search Options');\n } else {\n $(searchOptionsBtn).text('Show Search Options');\n }\n}",
"function toggleText() {\n var text = document.getElementById(\"demo\");\n if (text.style.display === \"none\") {\n text.style.display = \"block\";\n } else {\n text.style.display = \"none\";\n }\n}",
"function transcriptToggle() {\n target = this.classList[1] - 1;\n\n if(transcript[target].classList.contains('hidden')){\n transcript[target].classList.remove('hidden');\n transcriptBtnText[target].textContent = 'Hide';\n } else {\n transcript[target].classList.add('hidden');\n transcriptBtnText[target].textContent = 'Show';\n }\n \n }",
"function toggleTrueAndFalseButtons(){\n trueButton.classList.contains('hide')? trueButton.classList.remove('hide'): trueButton.classList.add('hide')\n falseButton.classList.contains('hide')? falseButton.classList.remove('hide'): falseButton.classList.add('hide') \n}",
"function toggleSpanVisibility() {\r\n var span = document.getElementById(\"message\");\r\n var button = document.getElementById(\"toggle\");\r\n \r\n /*Checking if the span is hidden or visible*/\r\n if(span.style.display == \"none\") {\r\n span.style.display = \"inline\";\r\n button.innerHTML = \"Hide\";\r\n } else {\r\n span.style.display = \"none\";\r\n button.innerHTML = \"Show\";\r\n }\r\n}",
"_toggleButtonText() {\n const { toggleButton } = this.refs;\n if (this.maskState === 'hidden') {\n toggleButton.innerHTML = 'Show';\n } else if (this.maskState === 'visible') {\n toggleButton.innerHTML = 'Hide';\n }\n }",
"function hideButtonsAndText() {\n $(\"sport-btn\").classList.add(\"hidden\");\n qs(\"textarea\").classList.add(\"hidden\");\n $(\"player-btn\").classList.add(\"hidden\");\n $(\"back-btn\").classList.remove(\"hidden\");\n }",
"function toggleText() {\n\t\tif (opt.playStopBtn && opt.playText && opt.stopText) {\n\t\t\tif (autoPlay) {\n\t\t\t\t$(opt.playStopBtn).text(opt.stopText);\n\t\t\t} else {\n\t\t\t\t$(opt.playStopBtn).text(opt.playText);\n\t\t\t}\n\t\t}\n\t}",
"function setVisibilityButtonText() {\n\tif (visible) {\n\t\t$(\"#toggleVisible span\").text(\"Close Course\");\n\t} else {\n\t\t$(\"#toggleVisible span\").text(\"Release Course\");\n\t}\n\tif (deprecated) {\n\t\t$(\"#toggleDeprecation span\").text(\"Remove Deprecation\");\n\n\t} else {\n\t\t$(\"#toggleDeprecation span\").text(\"Deprecate Course\");\n\n\t}\n\t\n}",
"function toggleSpanVisibility() {\r\n $(\"#message\").toggle(300);\r\n if($(this).text() == \"Hide\") {\r\n $(this).text(\"Show\");\r\n } else {\r\n $(this).text(\"Hide\");\r\n }\r\n}",
"function toggleSearchOptionsTitle()\n{\n\tif ($(searchForm).css(\"display\") === \"none\") {\n\t\t$(searchOptionsBtn).text('Hide Search Options');\n } \n\telse {\n \t$(searchOptionsBtn).text('Show Search Options');\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
disableInsConsButton() enableInsConsButtonEnable a button "accept" | function enableInsConsButton() {
var xbutton = document.getElementById("insconsbutton");
if( xbutton != undefined ){
document.getElementById("insconsbutton").removeAttribute('hidden');
acceptButton = true;
}
return true;
} | [
"function disableInsConsButton() {\t\t\n\tvar xbutton = document.getElementById(\"insconsbutton\");\n\tif( xbutton != undefined ){\n\t\tdocument.getElementById(\"insconsbutton\").setAttribute('hidden', 'true');\n\t\tacceptButton = false;\n\t}\n\treturn true;\n}",
"function enableAcceptButton() {\t\t\n\tvar xbutton = document.getElementById(\"acceptbutton\");\n\tif( xbutton != undefined ){\n\t\tdocument.getElementById(\"acceptbutton\").removeAttribute('hidden');\n\t\tacceptButton = true;\n\t}\n\treturn true;\n}",
"function disableAcceptButton() {\t\t\n\tvar xbutton = document.getElementById(\"acceptbutton\");\n\tif( xbutton != undefined ){\n\t\tdocument.getElementById(\"acceptbutton\").setAttribute('hidden', 'true');\n\t\tacceptButton = false;\n\t}\n\treturn true;\n}",
"function enableDialogOkButton() {\n dialogOkBtn.\n attr('disabled', false).\n prop('disabled', false);\n }",
"function enableChangeButton() {\t\t\n\tvar xbutton = document.getElementById(\"enableChange\");\n\tif( xbutton != undefined ){\n\t\tdocument.getElementById(\"enableChange\").removeAttribute('hidden');\n\t}\n\treturn true;\n}",
"configureAcceptButton(config) {\n if (config.needsReboot(this.trs80.getConfig())) {\n this.acceptButton.classList.add(gRebootButtonCssClass);\n this.acceptButton.innerText = \"Reboot\";\n }\n else {\n this.acceptButton.classList.remove(gRebootButtonCssClass);\n this.acceptButton.innerText = \"OK\";\n }\n }",
"function enableSaveCancelBtn(){\r\n $('#step2QA_review_popup_save_btn').removeAttr('disabled');\r\n $('#step2QA_review_popup_cancel_btn').removeAttr('disabled');\r\n}",
"function enableClickOK () {\n svl.ui.modalSkip.ok.attr(\"disabled\", false);\n svl.ui.modalSkip.ok.removeClass(\"disabled\");\n status.disableClickOK = false;\n }",
"function enableClickOk () {\n modalUI.ok.attr(\"disabled\", false);\n modalUI.ok.removeClass(\"disabled\");\n status.disableClickOk = false;\n }",
"enableOkBtn() {\r\n if (this.okBtnEl) {\r\n if (this.okBtnEl.attr('originOnClickEvent')) {\r\n this.okBtnEl.attr('onclick', this.okBtnEl.attr('originOnClickEvent'));\r\n }\r\n\r\n if (this.okBtnEl.attr('originTitle')) {\r\n this.okBtnEl.attr('title', this.okBtnEl.attr('originTitle'));\r\n }\r\n\r\n this.okBtnEl.removeClass('disabled');\r\n this.okBtnEl.removeAttr('disabled');\r\n this.okBtnEl.removeAttr('originOnClickEvent');\r\n this.okBtnEl.removeAttr('originTitle');\r\n }\r\n }",
"function enablebtnProceed(){\n $('#btnProceed').prop('disabled', false);\n}",
"function disableDialogOkButton() {\n dialogOkBtn.\n attr('disabled', true).\n prop('disabled', true);\n }",
"function disableChangeButton() {\t\t\n\tvar xbutton = document.getElementById(\"enableChange\");\n\tif( xbutton != undefined ){\n\t\tdocument.getElementById(\"enableChange\").setAttribute('hidden', 'true');\n\t}\n\treturn true;\n}",
"_updateOkButtonStatus() {\n\t\tif (this._psychoJS.config.environment === PsychoJS.Environment.LOCAL || (this._allResourcesDownloaded && this._nbSetRequiredKeys >= this._requiredKeys.length) ) {\n\t\t\t$(\"#buttonOk\").button(\"option\", \"disabled\", false);\n\t\t} else\n\t\t\t$(\"#buttonOk\").button(\"option\", \"disabled\", true);\n\n\t\t// strangely, changing the disabled option sometimes fails to update the ui,\n\t\t// so we need to hide it and show it again:\n\t\t$(\"#buttonOk\").hide(0, () => { $(\"#buttonOk\").show(); });\n\t}",
"disableOkBtn() {\r\n if (this.okBtnEl) {\r\n // store the button onclick handler and title for future restore\r\n if (!this.okBtnEl.attr('originOnClickEvent')) {\r\n this.okBtnEl.attr('originOnClickEvent', this.okBtnEl.attr('onclick'));\r\n }\r\n\r\n if (!this.okBtnEl.attr('originTitle')) {\r\n this.okBtnEl.attr('originTitle', this.okBtnEl.attr('title'));\r\n }\r\n\r\n this.okBtnEl.addClass('disabled');\r\n this.okBtnEl.attr('disabled', 'disabled');\r\n this.okBtnEl.attr('onclick', false);\r\n this.okBtnEl.attr('title', '');\r\n }\r\n }",
"function enable_ap_buttons()\r\n{\r\n try\r\n {\r\n\t if (document.options_adv_exclusions_ap.AP_Exclusions.options.selectedIndex < 0)\r\n\t {\r\n\t ButtonDisable(document.options_adv_exclusions_ap.Change);\r\n\t ButtonDisable(document.options_adv_exclusions_ap.Remove);\t \r\n\t }\r\n\t else\r\n\t {\r\n\t ButtonNormalize(document.options_adv_exclusions_ap.Change);\r\n\t ButtonNormalize(document.options_adv_exclusions_ap.Remove);\t\r\n\t } \r\n }\r\n catch (err)\r\n {\r\n\t g_ErrorHandler.DisplayException (err);\r\n\t return;\r\n }\r\n}",
"function SA_EnableCancel()\r\n {\r\n \tEnableCancel();\r\n }",
"function enableButton_ar1()\n{\n\tdocument.getElementById(\"rejectForm\").submit();\n}",
"function subfrmRegButtonEnable() {\n\ttry {\n\t\tfrmRegionMaintenance.txtRegCode.disabled = false;\n\t\tfrmRegionMaintenance.txtRegCode.readOnly = false;\n\t\tfrmRegionMaintenance.txtRegName.disabled = false;\n\t\tfrmRegionMaintenance.txtRegSeq.disabled = false;\n\t\tfrmRegionMaintenance.txtRegLang.disabled = false;\n\t\tfrmRegionMaintenance.txtRegLat.disabled = false;\n\t\tfrmRegionMaintenance.cboRegionGroup.disabled = false;\n\t\tfrmRegionMaintenance.txtRegCode.focus();\n\t\tfrmRegionMaintenance.btnSave.disabled = false;\n\t\tfrmRegionMaintenance.btnAdd.disabled = true;\n\t\tfrmRegionMaintenance.hdEdit.value = false;\n\t\tparent.UpdateUniform();\n\t}\n\tcatch (e) {\n\t\tsubDisplayError(\"BackOfficeModuleCode.js\", \"subfrmRegButtonEnable()\", e);\n\t}\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reset foreground color to default | function resetForeColor() {
richTextField.document.execCommand("foreColor", true, "#000000");
} | [
"reset() {\n this.colorFg = this.defaultFg;\n this.colorBg = this.defaultBg;\n }",
"function resetBGColor () {\r\n\teditValue('bgColor', '#0000FF');\r\n\tchangeBGColor('bgColor');\r\n}",
"reset() {\n this.changeColors(EMPTYCOLOR);\n }",
"function resetTextColor () {\r\n\teditValue('textColor', '#FFFFFF');\r\n\tchangeTextColor('textColor');\r\n}",
"function reset_colour() {\n options.colourList = {};\n colours_fill();\n switch_action.action_colour_setup('colour');\n}",
"restoreDefaults() {\n this.selectedColor = 0;\n this.colors = [new Color(0.5176, 0.7843, 0.0902)];\n }",
"setDefaultColors(){\n\t\tthis.st.write(\"\\x1b[0m\");\n\t}",
"function resetColour(){\n\n\t\tcurrentColour.css(\"background-color\",settingResetcolours(currentColour));\n\t}",
"setForegroundColor() {\n const yiq = this.getContrastYIQ();\n if (yiq >= 170) {\n this.$body[0].style.setProperty('--foreground-color', this.blackHex);\n } else {\n this.$body[0].style.setProperty('--foreground-color', this.whiteHex);\n }\n }",
"function resetAttributes() {\n foreground = 7;\n background = 0;\n foreground24bit = undefined;\n background24bit = undefined;\n bold = false;\n blink = false;\n inverse = false;\n }",
"function resetColors(){\r\n\t\r\n\tcolors = createSquares(mode);\r\n\r\n\t\r\n\tassignColors();\r\n\r\n\t// update message\r\n\tmessage.textContent = \"\";\r\n\r\n\t// change h1Header\r\n\th1Header.style.backgroundColor=\"rgb(60, 118, 174)\";\r\n\r\n\t// change text of new colors/ reset button\r\n\tresetBtn.textContent = \"New Colors\";\r\n}",
"function resetColor() {\n\t$('body').css('background-color', data['bg']);\n\t$('body').css('color', data['fg']);\n}",
"resetColor() {\n\t this.red = this.green = this.blue = undefined;\n\t }",
"setBlack() { this.setColor(0, 0, 0); }",
"async _resetDefaultBackgroundColor() {\n await this._client.send('Emulation.setDefaultBackgroundColorOverride');\n }",
"function resetBodyColor(defColor) {\n\t\tdocument.documentElement.style.setProperty(\"--bcg-fill-color\", defColor, )\n\t}",
"reset() {\n this.color = 0xFFFFFF;\n this.alpha = 1;\n }",
"function clearColors() {\n setNewColor([])\n }",
"resetColor() {\n this.__updateByColorString = this.__updateByColorProperties = false;\n this.setProperties({\n colorString: undefined,\n r: undefined,\n g: undefined,\n b: undefined,\n h: undefined,\n s: undefined,\n l: undefined,\n hex: undefined,\n alpha: undefined\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a page from view, using input string pageId | function removePage(pageId) {
var page = $(pageId);
page.attr("style", "display: none");
} | [
"function deletePage(pageId) {\n return pageModel.remove({_id: pageId});\n}",
"function deletePage(pageId) {\n for (var i = 0; i < pages.length; ++i) {\n if (pages[i]._id == pageId)\n pages.splice(i, 1);\n }\n }",
"function deletePage() {\n var $wp = $('.write-pages li'); // the list of book pages\n var $page = $($wp.get(editIndex)); // the current page\n $page.remove(); // remove it\n setupEditContent();\n setModified();\n }",
"deletePage(){\t\n\t\tthis.page.selectAll(\"*\").remove();\n\t\tthis.hidePage();\n\t}",
"static remove(params, callback) {\n myFirebase.removefromFirebase(myFirebase.firebaseRef,\n `pages/${params._id}`)\n .then((result) => {\n if (result) {\n //Success\n var page = {id: params._id};\n callback(null, page);\n } else {\n callback(`Error removing object: ${params._id}`);\n }\n }, (e) => {\n // Error\n callback(e);\n });\n }",
"function page_deleted(view) {\n if (typeof memento != 'undefined') {\n var mem = { 'templateId': memento.templateId, 'pageId': null };\n // Use the PercNavigationManager to reload to the template editor without pageId\n var querystring = $.deparam.querystring();\n $.PercNavigationManager.goToLocation(\n view,\n querystring.site,\n null,\n null,\n null,\n querystring.path,\n null,\n mem);\n }\n }",
"function removeItemFromPage(itemId) {\n $('div[data-item-id=' + itemId + ']').remove();\n}",
"function deletePage(vendorid, landingpage, siteid, pageid) \n{\n\tlocalStorage.removeItem('page'+pageid);\n\tif (pageid == landingpage) {\n\t\tsetLandingPage(0);\n\t}\n\t\n\tdelete pageChanges['page'+pageid];\n\tdelete pageLoaded['page'+pageid];\n\t\n\t/** delete the page from the database and from the server */\n\t$.ajax(\n\t\t{\n\t\t\turl: 'destroy',\n\t\t\tdatatype: 'application/json',\n\t\t\ttype: 'POST',\n\t\t\tbeforeSend : function(xhr)\n\t\t\t{\n\t\t\t\txhr.setRequestHeader('X-CSRF-Token', $('meta[name = \"csrf-token\"]').attr('content'))\n\t\t\t},\n\t\t\tdata: \n\t\t\t{\n\t\t\t\tvendor_id: \tvendorid,\n\t\t\t\tsite_id: \tsiteid, \n\t\t\t\tpage_id:\tpageid\n\t\t\t}, \n\t\t\tsuccess: function(data) \n\t\t\t{\n\t\t\t\t/** remove it from the view */\n\t\t\t\t$(\"#pageholder\" + pageid).remove();\n\t\t\t\t/** clear the current preview */\n\t\t\t\t$(\"#preview_frame\").contents().find('html').empty();\n\t\t\t}, \n\t\t\terror: function(objAJAXRequest, strError, errorThrown) \n\t\t\t{\n\t\t\t\talert(\"Error: \" + strError + \" \" + errorThrown);\n\t\t\t}\n\t\t});\n}",
"function deleteWikiPage(wikiID){\r\n \r\n for (let i = 0; i < WikiPagesList.length; i++) {\r\n if( WikiPagesList[i].id===wikiID)\r\n {\r\n WikiPagesList.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n createWikiPagePreview(WikiPagesList,true)\r\n }",
"function deletePage(id) {\n return $http.delete('rest/pages/' + id);\n }",
"function deletePage() {\n var ret = PageService.deletePage(vm.pid);\n ret\n .success(function (s) {\n $location.url(\"/user/\" + vm.uid + \"/website/\" + vm.wid + \"/page\");\n })\n .error(function (e) {\n console.log(e);\n });\n\n }",
"function deletePage(req,res) {\n var pageId=req.params.pageId;\n pageModel.deletePage(pageId).then(\n function (success) { res.sendStatus(200); },\n function (error) { res.statusCode(404).send(error); });\n }",
"deletePage(id) {\n let p = DashboardUtils.findDashboardPageById(this.props.dashboard, id);\n if (p.pages && p.pages.length > 0) {\n const errorMessage = this.context.intl.formatMessage({id:\"page.delete.error\",\n defaultMessage: \"Unable to delete this page since it contains sub-pages\"});\n this.setState({\n error: errorMessage,\n showError: true,\n });\n return;\n }\n this.deletePageRecursively(this.props.dashboard.pages, id);\n this.savePages(this.props.dashboard.pages);\n // navigate to home page\n this.props.history.push(window.contextPath + '/designer/' + this.props.dashboard.url);\n }",
"'click .js-media-delete-button'( e, t ) {\n e.preventDefault();\n\n let cur = $( '#cb-current' ).val()\n , idx = P.indexOf( `${cur}` );\n\n \t\tP.removeAt( idx );\n $( `#${cur}` ).remove();\n $( '#cb-current' ).val('');\n $( '#cb-media-toolbar' ).hide();\n $('#frameBorder').remove();\n pp.update( { _id: Session.get('my_id') },\n { $pull: { pages:{ id: cur} } });\n\n //console.log( pp.find({}).fetch() );\n }",
"function deletePage() {\n pageService.deletePage(vm.pageId);\n $location.url('/user/' + vm.userId + '/website/' + vm.websiteId + '/page');\n }",
"cleanUpTrash(page) {\n this.pages[page].remove();\n }",
"removePage(page) {\n if (!this.matchedTabs.has(page.caption)) {\n throw new Error(`The specified page does not exists in the tab container.`);\n }\n this.removePageElement(page.caption);\n }",
"remove() {\r\n this.page.sections = this.page.sections.filter(section => section._memId !== this._memId);\r\n reindex(this.page.sections);\r\n }",
"function removePageNumbers() {\n \n var slides = presentation.getSlides();\n for (var i = 0; i < slides.length; ++i) {\n var elements = slides[i].getPageElements();\n \n for (var j = 0; j < elements.length; ++j) {\n if (elements[j].getPageElementType() === SlidesApp.PageElementType.SHAPE &&\n elements[j].asShape().getLink() &&\n elements[j].asShape().getLink().getUrl() === BOX_ID) {\n elements[j].remove();\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Charge function that is called for each node. As part of the ManyBody force. This is what creates the repulsion between nodes. Charge is proportional to the diameter of the circle (which is stored in the radius attribute of the circle's associated data. This is done to allow for accurate collision detection with nodes of different sizes. Charge is negative because we want nodes to repel. | function charge(d) {
return -Math.pow(d.radius, 2.1) * forceStrength;
} | [
"function charge(d) {\n return -Math.pow(d.radius, 2.0) * forceStrength;\n }",
"function charge(d) {\n return -1.4 * Math.pow(d.radius, 2.0) * forceStrength;\n }",
"function charge(d) {\r\n\t\t\t\t\t return -Math.pow(d.radius, 2.0) * forceStrength;\r\n\t\t\t\t\t }",
"function charge(d) {\n return -Math.pow(d.radius, 2.0) * forceStrength;\n }",
"UpdateCharge()\n {\n if(this.visited)\n return;\n\n this.visited = true;\n\n for(let i = 0; i < this.outgoingNodes.outgoingConnections.length; i++)\n this.outgoingNodes.outgoingConnections[i].gate.parent.UpdateCharge();\n }",
"function charge(d) {\n return Math.pow(d.radius, 2.0) * 0.01\n }",
"function PCharge(charge, mass, x, y, dp) {\n // Attributes\n this.radius = (sizeConstant * Math.sqrt(Math.abs(mass)))\n this.charge = charge;\n this.mass = mass;\n this.x = x\n this.y = y\n this.xvel = 0\n this.yvel = 0\n this.dp = dp\n this.selected = false\n if (charge < 0) {\n this.color = \"rgba(0,30,255, 0.3)\"\n } else {\n this.color = \"rgba(255,30,0, 0.3)\"\n }\n\n // Literally draw on the screen\n this.draw = function () {\n c.fillStyle = this.color;\n c.beginPath();\n c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);\n c.fill();\n c.font = \"15px Roboto Mono\";\n c.fillStyle = \"rgba(0, 0, 0, 0.7)\"\n if (info) {\n c.fillText(this.charge + \"C\", this.x + 20, this.y + 15);\n c.fillText(this.mass + \"kg\", this.x + 20, this.y);\n c.fillText(rnd(Math.sqrt(Math.pow(this.yvel, 2) + Math.pow(this.xvel, 2))) + \"m/s\", this.x + 20, this.y - 15);\n }\n\n }\n\n // Only calculate the net acceleration and change the x/y velocities\n this.calc = function () {\n // Components of net force \n fx = 0\n fy = 0\n if (this.dp == false) {\n // Iterate through charges\n for (var i = 0; i < numCharges; i++) {\n // Delta x, y, and distance between two charges\n dx = (this.x - charges[i].x)\n dy = (this.y - charges[i].y)\n dist = (distance(this.x, this.y, charges[i].x, charges[i].y))\n // Calculate angles\n if (dist != 0) {\n if (dx > 0) {\n if (dy > 0) {\n trig = Math.PI - Math.acos(Math.abs(dx) / dist);\n } else {\n trig = Math.PI + Math.acos(Math.abs(dx) / dist)\n }\n } else {\n if (dy > 0) {\n trig = Math.acos(Math.abs(dx) / dist);\n } else {\n trig = (2 * Math.PI) - Math.acos(Math.abs(dx) / dist)\n }\n }\n // Coulombs Law\n cl = (k * Math.abs(this.charge) * Math.abs(charges[i].charge) / Math.pow(dist, 2))\n sign = -((this.charge * charges[i].charge) / Math.abs((this.charge * charges[i].charge)))\n // Components of force for x and y direction\n fx += sign * cl * Math.cos(trig)\n fy += sign * cl * -Math.sin(trig)\n }\n }\n // Update x and y vel\n this.xvel += fx / this.mass\n this.yvel += fy / this.mass\n }\n }\n\n // Update charge position and call draw method\n this.update = function () {\n if (!pause && (this.dp == false)) {\n this.x += this.xvel\n this.y += this.yvel\n }\n this.draw()\n }\n}",
"function charge(d) {\n return -Math.pow(d.radius, 2.0) / 8;\n }",
"function act_charge(entity) {\r\n\tif (!entity.inRangeOfBase()) {\r\n\t\tentity.move(base.position);\r\n\t}\r\n\tentity.energize(base);\r\n}",
"function calcRepulsiveForce(node1) {\n var m1 = node1[\"mass\"];\n var P = createVector(node1[\"pos_x\"], node1[\"pos_y\"]);\n\n var node2;\n var m2;\n var Q = createVector(0.0, 0.0);\n\n var totalForce = createVector(0.0, 0.0);\n var distance;\n var force;\n\n // Iterate over all nodes to calculate repulsion\n var arrayLength = allNodes.length;\n for (var i = 0; i < arrayLength; i++) {\n node2 = allNodes[i];\n m2 = node2[\"mass\"];\n Q.set(node2[\"pos_x\"], node2[\"pos_y\"]);\n\n distance = p5.Vector.dist(P, Q);\n if(distance == 0.0) continue;\n // to avoid distance from being a very small number\n // causing force to be very large\n distance += 0.01;\n force = (repulsionConstant * m1 * m2) / (distance*distance);\n totalForce.add(p5.Vector.sub(P, Q).normalize().mult(force));\n }\n\n return totalForce;\n}",
"applyCoulombsLaw() {\n this.eachNode(function(n1, point1) {\n this.eachNode(function(n2, point2) {\n if (point1 !== point2) {\n const d = point1.position.difference(point2.position);\n const distance = d.length() + 0.1; // .length | avoid massive forces at small distances (and divide by zero)\n const direction = d.normalize();\n\n // apply force to each end point\n point1.applyForce(direction.scale(this.repulsion).divide(distance * distance * 0.5));\n point2.applyForce(direction.scale(this.repulsion).divide(distance * distance * -0.5));\n }\n });\n });\n }",
"acChangeCharge(value) {\n this._configLayout.charge = +value;\n this._forceLayout.force(\"charge\", forceManyBody().strength((d) => { return -(this._chargeScale(d.qtNodes) + this._configLayout.charge); }));\n this._forceLayout.alpha(1).restart();\n }",
"consumeCharges( charges = 1, forceCooldown = false ){\n\n\t\t// If there's no cooldown at all, the charge system is ignored\n\t\tif( this.getCooldown() <= 0 && charges > 0 )\n\t\t\treturn;\n\n\t\t// Subtract a charge\n\t\tthis._charges = Math.min(Math.max(0, this._charges-charges), this.charges);\n\t\tthis.setCooldown(forceCooldown);\n\n\t}",
"function formalcharge() {\n // Declare local variables\n var i, num;\n var octet, qbonds;\n var formalpos, formalneg;\n var molecule = Mol();\n var numatoms = molecule[0].numatoms;\n var bonds = BondMatrix();\n\n // Calculate formal charges based on number of bonds\n formalpos = 0.0;\n formalneg = 0.0;\n for (i=1; i <= numatoms; i++) {\n octet = 0;\n if (element(molecule[i].atomicnumber,\"block\") == \"s\")\n octet = 2;\n if (element(molecule[i].atomicnumber,\"block\") == \"p\")\n octet = 8;\n if ( octet > 0 ) {\n qbonds = bonds[i][0] + element(molecule[i].atomicnumber,\"valence\") - octet;\n if ( qbonds < 0 )\n formalneg += qbonds;\n if ( qbonds > 0 )\n formalpos += qbonds;\n \t}\n }\n\n // Since multiple bonds not yet known, \"scale down\" negative charges\n while ( formalneg <= -2 )\n formalneg += 2;\n\n // Store formal charge prediction of molecular charge\n molecule[0].charge = formalpos + formalneg;\n\n // End formalcharge routine\n return;\n }",
"buildCharges () {\n\n\t\tlet planets = this.gameElements.planets.instances;\n\n\t\tfor ( let i = 0; i < planets.length; i ++ ) {\n\n\t\t\tlet planet = planets[ i ];\n\t\t\tlet layers = planet.particles;\n\n\t\t\tfor ( let j = 0; j < layers.length; j ++ ) {\n\n\t\t\t\tfor ( let k = 0; k < layers[ j ]; k ++ ) {\n\n\t\t\t\t\tlet step = ( Math.PI * 2.0 ) / layers[ j ];\n\t\t\t\t\tlet angle = step * k;// + ( Math.random() - 0.5 ) * 0.2;\n\t\t\t\t\tlet dist = ( ( planet.scale[ 0 ] * 0.50 ) / ( layers.length - 1 ) ) * j;\n\n\t\t\t\t\tlet rSize = Math.random() * 0.05 + 0.12;\n\n\t\t\t\t\tlet color = null;\n\n\t\t\t\t\tif ( Math.random() > 0.5 ) {\n\n\t\t\t\t\t\tcolor = vec4.fromValues ( 50/255, 104/255, 252/255, 1.0 );\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tcolor = vec4.fromValues ( 252/255, 74/255, 50/255, 1.0 );\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Store the charges in the planet to have an easy access.\n\n\t\t\t\t\tplanets[ i ].charges.push (\n\n\t\t\t\t\t\tthis.addInstanceOf ( 'charges', {\n\n\t\t\t\t\t\t\tname: 'gravityChargeParticle',\n\t\t\t\t\t\t\tposition: vec3.fromValues ( planet.position[ 0 ] + Math.cos ( angle ) * dist, planet.position[ 1 ] + Math.sin ( angle ) * dist, 0.0 ),\n\t\t\t\t\t\t\trotation: [ 0, 0, Math.random () * Math.PI * 2 ],\n\t\t\t\t\t\t\tminRadius: 0.1,\n\t\t\t\t\t\t\tmaxRadius: 0.5,\n\t\t\t\t\t\t\tradius: ( j == 0 ) ? 0.2 : 0.05,\n\t\t\t\t\t\t\ttargetRadius: ( j == 0 ) ? 0.2 : Math.random () * 0.1 + 0.1,\n\t\t\t\t\t\t\tmass: 400,\n\t\t\t\t\t\t\tdrag: 0.9,\n\t\t\t\t\t\t\tenabled: ( j == 0 ) ? false : true, // disable the first instance to keep it in the center.\n\n\t\t\t\t\t} ) );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}",
"function Charges()\n{\n var charges = new Array();\n var distributions = new Array();\n\n // Add a charge to the set of charges. \n this.addCharge = function(charge)\n {\n charges.push(charge);\n return this;\n }\n\n this.getCharges = function()\n {\n return charges;\n }\n\n this.getNCharges = function()\n {\n return charges.length;\n }\n\n // Add a charge distribution to the set of charges.\n this.addDistribution = function(distribution)\n {\n distributions.push(distribution);\n return this;\n }\n\n this.getDistributions = function()\n {\n return distributions;\n }\n\n this.getNDistributions = function()\n {\n return distributions.length;\n }\n\n /*\n * Comnpute the field at x, y, z resulting from a all\n * charge configurations.\n */\n this.getField = function(x, y, z)\n {\n // Field from the current charge\n var currentField;\n // The field vector\n var field = new Array(0, 0, 0);\n\n field = this.getFieldFromCharges(charges, x, y, z);\n currentField = this.getFieldFromCharges(distributions, x, y, z);\n\n field[0] += currentField[0];\n field[1] += currentField[1];\n field[2] += currentField[2];\n\n return field;\n }\n\n /*\n * Comnpute the field at x, y, z resulting from a charge\n * configuration.\n */\n this.getFieldFromCharges = function(charges, x, y, z)\n {\n var charge;\n // Field from the current charge\n var currentField;\n // The field vector\n var field = new Array(0, 0, 0);\n \n\n for(var i=0, n=charges.length; i<n; i++)\n {\n charge = charges[i];\n\n currentField = charge.getField(x, y, z);\n field[0] += currentField[0];\n field[1] += currentField[1];\n field[2] += currentField[2];\n }\n return field;\n }\n\n /**\n * Set the vertex registry, that holds the vertex arrays for each\n * geometry. That is all cylinders use the same vertices, just\n * different transformations.\n *\n * @param {GeometryEngine.VertexRegistry} vertexRegistry Registry for vertex buffers for each geometry type.\n */\n this.setVertexRegistry = function(vertexRegistry)\n {\n for(var i=0, n=distributions.length; i<n; i++)\n {\n distributions[i].setVertexRegistry(vertexRegistry);\n }\n }\n}",
"function getNodeCharge(type) {\n\t//console.log(type);\n\tif (type == \"serv\") {return [-1000]; }\n\telse if (type == \"vol\") { return [-400];\t}\n\telse if (type == \"net\") { return [-4000]; }\n\telse if (type == \"rou\") { return [-5000]; }\n\telse { return [-800]; }\n}",
"function n_recalculateTorques(node)\n{\n\tif(node == null)\t// error check\n\t{\n\t\tconsole.log(\"<!> n_recalculateTorques: input node is null!\");\n\t\treturn;\t\n\t}\n\n\tif(node.children == null)\t// base case, return.\n\t{\n\t\treturn node.mass;\n\t}\n\n\t/*\tRecursive call to find mass sum off all descendants, then use that mass to apply a torque force originating from this node's children\t*/\n\tvar totalMass =\tn_recalculateTorques(node.children);\n\tnode.torque = calculateGravitationalTorque(calculateDistance2D(node.pos, node.children.pos), totalMass, calculateAbsoluteAngle(node.pos, node.children.pos));\n\n\t/*\tUpdate the total mass with our own mass before we return it.\t\t*/\n\ttotalMass += node.mass;\n\n\t/*\tReturn the total mass\t*/\n\treturn totalMass;\n}",
"function atomicCharge(BondMtx) {\n\n // Declare parameters\n var ALPHA = 0.5; // Fraction of charge to mix with EN\n var MIX = 0.5; // Reduce effects of formal charges (1=no reduction)\n var MAXSTEP = 15;\n var CONVERGED = 0.001;\n // Declare local variables\n var i, j, loop;\n var Z, mixfactor;\n var q, delta, dmax;\n var molcharge = 0.0;\n var atomEN = new Array();\n var molecule = Mol();\n var numatoms=molecule[0].numatoms;\n var bonds = BondMatrix();\n\n // Calculate charge on molecule\n for (i=1; i <= numatoms; i++) {\n molcharge += element(molecule[i].atomicnumber,\"valence\");\n for (j=1; j <= numatoms; j++) {\n if ( i == j ) {\n molcharge -= BondMtx[i][i];\n } else {\n molcharge -= 0.5*BondMtx[i][j];\n }\n }\n }\n delta = Math.abs(molcharge - molecule[0].charge);\n if ( delta > 0.001 )\n alert(\"Error: Electron assignment does NOT match molecular charge.\");\n\n // Initialize electronegativity array and set mixing factor\n mixfactor = MIX;\n // If molecule has a charge, use 100% formal charge method\n if ( Math.abs(molcharge) > 0.001 )\n mixfactor = 1.0;\n for ( i=1; i <= numatoms; i++ ) {\n Z = molecule[i].atomicnumber;\n if ( (element(Z,\"block\")==\"d\") || (element(Z,\"block\")==\"f\") )\n mixfactor = 0.0;\n q = element(Z,\"EN\") || 0;\n if ( q == 0 ) {\n q = 1.0;\n InfoWin(\"WARNING: No electronegativity defined for \");\n InfoWin(element(molecule[i].atomicnumber,\"symbol\")+\"\\n\");\n }\n atomEN[i] = q;\n }\n\n // Inform user of method used to calculate charges\n if (mixfactor==1.0)\n InfoWin(\"Using 100% formal charge method to calculate charges.\\n\");\n if (mixfactor==0.0)\n InfoWin(\"Using 100% bond polarity method to calculate charges.\\n\");\n if (mixfactor==MIX)\n InfoWin(\"Using mixture of formal charge and bond polarity method to calculate charges.\\n\");\n\n // Perform iterations until charges remain constant\n loop = 0;\n dmax = 100.0;\n while ( (loop<MAXSTEP) && (dmax>CONVERGED) ) {\n loop++;\n // Calculate charges for each atom\n for ( i=1; i <= numatoms; i++ ) {\n Z = molecule[i].atomicnumber;\n q = mixfactor * (element(Z,\"valence\") - BondMtx[i][i]);\n for ( j = 1; j <= numatoms; j++) {\n if ( bonds[i][j] > 0 ) {\n q += (1.0-mixfactor) * 0.5 * BondMtx[i][j];\n q -= BondMtx[i][j]*atomEN[i]/(atomEN[i]+atomEN[j]);\n }\n }\n molecule[i].charge = q;\n }\n // Calculate new electronegativity values for each atom\n dmax = 0.0;\n for ( i=1; i <= numatoms; i++ ) {\n q = atomEN[i];\n atomEN[i] = element(molecule[i].atomicnumber,\"EN\") || 1.0;\n atomEN[i] += ALPHA*molecule[i].charge;\n delta = Math.abs(q - atomEN[i]);\n if ( delta > dmax )\n dmax = delta;\n }\n }\n\n // Finished with atomicCharge routine\n return BondMtx;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Derives the `R3DirectiveMetadata` structure from the AST object. | function toR3DirectiveMeta(metaObj, code, sourceUrl) {
var typeExpr = metaObj.getValue('type');
var typeName = typeExpr.getSymbolName();
if (typeName === null) {
throw new fatal_linker_error_1.FatalLinkerError(typeExpr.expression, 'Unsupported type, its name could not be determined');
}
return {
typeSourceSpan: createSourceSpan(typeExpr.getRange(), code, sourceUrl),
type: util_1.wrapReference(typeExpr.getOpaque()),
typeArgumentCount: 0,
internalType: metaObj.getOpaque('type'),
deps: null,
host: toHostMetadata(metaObj),
inputs: metaObj.has('inputs') ? metaObj.getObject('inputs').toLiteral(toInputMapping) : {},
outputs: metaObj.has('outputs') ?
metaObj.getObject('outputs').toLiteral(function (value) { return value.getString(); }) :
{},
queries: metaObj.has('queries') ?
metaObj.getArray('queries').map(function (entry) { return toQueryMetadata(entry.getObject()); }) :
[],
viewQueries: metaObj.has('viewQueries') ?
metaObj.getArray('viewQueries').map(function (entry) { return toQueryMetadata(entry.getObject()); }) :
[],
providers: metaObj.has('providers') ? metaObj.getOpaque('providers') : null,
fullInheritance: false,
selector: metaObj.has('selector') ? metaObj.getString('selector') : null,
exportAs: metaObj.has('exportAs') ?
metaObj.getArray('exportAs').map(function (entry) { return entry.getString(); }) :
null,
lifecycle: {
usesOnChanges: metaObj.has('usesOnChanges') ? metaObj.getBoolean('usesOnChanges') : false,
},
name: typeName,
usesInheritance: metaObj.has('usesInheritance') ? metaObj.getBoolean('usesInheritance') : false,
};
} | [
"getModuleMetadataForDirective(classSymbol) {\n const result = {\n directives: [],\n pipes: [],\n schemas: [],\n };\n // First find which NgModule the directive belongs to.\n const ngModule = this.analyzedModules.ngModuleByPipeOrDirective.get(classSymbol) ||\n findSuitableDefaultModule(this.analyzedModules);\n if (!ngModule) {\n return result;\n }\n // Then gather all transitive directives and pipes.\n const { directives, pipes } = ngModule.transitiveModule;\n for (const directive of directives) {\n const data = this.resolver.getNonNormalizedDirectiveMetadata(directive.reference);\n if (data) {\n result.directives.push(data.metadata.toSummary());\n }\n }\n for (const pipe of pipes) {\n const metadata = this.resolver.getOrLoadPipeMetadata(pipe.reference);\n result.pipes.push(metadata.toSummary());\n }\n result.schemas.push(...ngModule.schemas);\n return result;\n }",
"getDirectiveMetadata(ref) {\n const clazz = ref.node;\n const def = this.reflector.getMembersOfClass(clazz).find(field => field.isStatic && (field.name === 'ɵcmp' || field.name === 'ɵdir'));\n if (def === undefined) {\n // No definition could be found.\n return null;\n }\n else if (def.type === null || !ts.isTypeReferenceNode(def.type) ||\n def.type.typeArguments === undefined || def.type.typeArguments.length < 2) {\n // The type metadata was the wrong shape.\n return null;\n }\n const isComponent = def.name === 'ɵcmp';\n const ctorParams = this.reflector.getConstructorParameters(clazz);\n // A directive is considered to be structural if:\n // 1) it's a directive, not a component, and\n // 2) it injects `TemplateRef`\n const isStructural = !isComponent && ctorParams !== null && ctorParams.some(param => {\n return param.typeValueReference.kind === 1 /* IMPORTED */ &&\n param.typeValueReference.moduleName === '@angular/core' &&\n param.typeValueReference.importedName === 'TemplateRef';\n });\n const inputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[3]));\n const outputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[4]));\n return Object.assign(Object.assign({ type: MetaType.Directive, ref, name: clazz.name.text, isComponent, selector: readStringType(def.type.typeArguments[1]), exportAs: readStringArrayType(def.type.typeArguments[2]), inputs,\n outputs, queries: readStringArrayType(def.type.typeArguments[5]) }, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), { baseClass: readBaseClass(clazz, this.checker, this.reflector), isPoisoned: false, isStructural });\n }",
"getDirectiveMetadata(ref) {\n const clazz = ref.node;\n const def = this.reflector.getMembersOfClass(clazz).find(field => field.isStatic && (field.name === 'ɵcmp' || field.name === 'ɵdir'));\n if (def === undefined) {\n // No definition could be found.\n return null;\n }\n else if (def.type === null || !ts.isTypeReferenceNode(def.type) ||\n def.type.typeArguments === undefined || def.type.typeArguments.length < 2) {\n // The type metadata was the wrong shape.\n return null;\n }\n const inputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[3]));\n const outputs = ClassPropertyMapping.fromMappedObject(readStringMapType(def.type.typeArguments[4]));\n return Object.assign(Object.assign({ ref, name: clazz.name.text, isComponent: def.name === 'ɵcmp', selector: readStringType(def.type.typeArguments[1]), exportAs: readStringArrayType(def.type.typeArguments[2]), inputs,\n outputs, queries: readStringArrayType(def.type.typeArguments[5]) }, extractDirectiveTypeCheckMeta(clazz, inputs, this.reflector)), { baseClass: readBaseClass(clazz, this.checker, this.reflector), isPoisoned: false });\n }",
"function toR3InjectorMeta(metaObj) {\n var typeExpr = metaObj.getValue('type');\n var typeName = typeExpr.getSymbolName();\n if (typeName === null) {\n throw new fatal_linker_error_1.FatalLinkerError(typeExpr.expression, 'Unsupported type, its name could not be determined');\n }\n return {\n name: typeName,\n type: util_1.wrapReference(typeExpr.getOpaque()),\n internalType: metaObj.getOpaque('type'),\n providers: metaObj.has('providers') ? metaObj.getOpaque('providers') : null,\n imports: metaObj.has('imports') ? metaObj.getArray('imports').map(function (i) { return i.getOpaque(); }) : [],\n };\n }",
"function compileDeclareDirectiveFromMetadata(meta) {\n const definitionMap = createDirectiveDefinitionMap(meta);\n const expression = importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);\n const type = createDirectiveType(meta);\n return { expression, type, statements: [] };\n}",
"function compileDeclareDirectiveFromMetadata(meta) {\n var definitionMap = createDirectiveDefinitionMap(meta);\n var expression = importExpr(Identifiers.declareDirective).callFn([definitionMap.toLiteralMap()]);\n var type = createDirectiveType(meta);\n return {\n expression: expression,\n type: type,\n statements: []\n };\n}",
"function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {\n var e_1, _a;\n // Use the `CompileReflector` to look up references to some well-known Angular types. These will\n // be compared with the token to statically determine whether the token has significance to\n // Angular, and set the correct `R3ResolvedDependencyType` as a result.\n var elementRef = reflector.resolveExternalReference(Identifiers.ElementRef);\n var templateRef = reflector.resolveExternalReference(Identifiers.TemplateRef);\n var viewContainerRef = reflector.resolveExternalReference(Identifiers.ViewContainerRef);\n var injectorRef = reflector.resolveExternalReference(Identifiers.Injector);\n // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\n var deps = [];\n try {\n for (var _b = Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__values\"])(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {\n var dependency = _c.value;\n if (dependency.token) {\n var tokenRef = tokenReference(dependency.token);\n var resolved = R3ResolvedDependencyType.Token;\n if (tokenRef === elementRef) {\n resolved = R3ResolvedDependencyType.ElementRef;\n }\n else if (tokenRef === templateRef) {\n resolved = R3ResolvedDependencyType.TemplateRef;\n }\n else if (tokenRef === viewContainerRef) {\n resolved = R3ResolvedDependencyType.ViewContainerRef;\n }\n else if (tokenRef === injectorRef) {\n resolved = R3ResolvedDependencyType.Injector;\n }\n else if (dependency.isAttribute) {\n resolved = R3ResolvedDependencyType.Attribute;\n }\n // In the case of most dependencies, the token will be a reference to a type. Sometimes,\n // however, it can be a string, in the case of older Angular code or @Attribute injection.\n var token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);\n // Construct the dependency.\n deps.push({\n token: token,\n resolved: resolved,\n host: !!dependency.isHost,\n optional: !!dependency.isOptional,\n self: !!dependency.isSelf,\n skipSelf: !!dependency.isSkipSelf,\n });\n }\n else {\n unsupported('dependency without a token');\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return deps;\n}",
"function dependenciesFromGlobalMetadata(type,outputCtx,reflector){var e_1,_a;// Use the `CompileReflector` to look up references to some well-known Angular types. These will\n// be compared with the token to statically determine whether the token has significance to\n// Angular, and set the correct `R3ResolvedDependencyType` as a result.\nvar injectorRef=reflector.resolveExternalReference(Identifiers.Injector);// Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\nvar deps=[];try{for(var _b=Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__values\"])(type.diDeps),_c=_b.next();!_c.done;_c=_b.next()){var dependency=_c.value;if(dependency.token){var tokenRef=tokenReference(dependency.token);var resolved=dependency.isAttribute?R3ResolvedDependencyType.Attribute:R3ResolvedDependencyType.Token;// In the case of most dependencies, the token will be a reference to a type. Sometimes,\n// however, it can be a string, in the case of older Angular code or @Attribute injection.\nvar token=tokenRef instanceof StaticSymbol?outputCtx.importExpr(tokenRef):literal(tokenRef);// Construct the dependency.\ndeps.push({token:token,resolved:resolved,host:!!dependency.isHost,optional:!!dependency.isOptional,self:!!dependency.isSelf,skipSelf:!!dependency.isSkipSelf});}else{unsupported('dependency without a token');}}}catch(e_1_1){e_1={error:e_1_1};}finally{try{if(_c&&!_c.done&&(_a=_b[\"return\"]))_a.call(_b);}finally{if(e_1)throw e_1.error;}}return deps;}",
"function dependenciesFromGlobalMetadata(type,outputCtx,reflector){// Use the `CompileReflector` to look up references to some well-known Angular types. These will\n// be compared with the token to statically determine whether the token has significance to\n// Angular, and set the correct `R3ResolvedDependencyType` as a result.\nvar injectorRef=reflector.resolveExternalReference(Identifiers.Injector);// Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\nvar deps=[];for(var _iterator19=type.diDeps,_isArray19=Array.isArray(_iterator19),_i36=0,_iterator19=_isArray19?_iterator19:_iterator19[Symbol.iterator]();;){var _ref41;if(_isArray19){if(_i36>=_iterator19.length)break;_ref41=_iterator19[_i36++]}else{_i36=_iterator19.next();if(_i36.done)break;_ref41=_i36.value}var dependency=_ref41;if(dependency.token){var tokenRef=tokenReference(dependency.token);var resolved=dependency.isAttribute?R3ResolvedDependencyType.Attribute:R3ResolvedDependencyType.Token;// In the case of most dependencies, the token will be a reference to a type. Sometimes,\n// however, it can be a string, in the case of older Angular code or @Attribute injection.\nvar token=tokenRef instanceof StaticSymbol?outputCtx.importExpr(tokenRef):literal(tokenRef);// Construct the dependency.\ndeps.push({token:token,resolved:resolved,host:!!dependency.isHost,optional:!!dependency.isOptional,self:!!dependency.isSelf,skipSelf:!!dependency.isSkipSelf})}else{unsupported(\"dependency without a token\")}}return deps}",
"function dependenciesFromGlobalMetadata(type,outputCtx,reflector){// Use the `CompileReflector` to look up references to some well-known Angular types. These will\n// be compared with the token to statically determine whether the token has significance to\n// Angular, and set the correct `R3ResolvedDependencyType` as a result.\nvar injectorRef=reflector.resolveExternalReference(Identifiers.Injector);// Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\nvar deps=[];for(var _iterator8=type.diDeps,_isArray8=Array.isArray(_iterator8),_i22=0,_iterator8=_isArray8?_iterator8:_iterator8[Symbol.iterator]();;){var _ref29;if(_isArray8){if(_i22>=_iterator8.length)break;_ref29=_iterator8[_i22++]}else{_i22=_iterator8.next();if(_i22.done)break;_ref29=_i22.value}var dependency=_ref29;if(dependency.token){var tokenRef=tokenReference(dependency.token);var resolved=dependency.isAttribute?R3ResolvedDependencyType.Attribute:R3ResolvedDependencyType.Token;// In the case of most dependencies, the token will be a reference to a type. Sometimes,\n// however, it can be a string, in the case of older Angular code or @Attribute injection.\nvar token=tokenRef instanceof StaticSymbol?outputCtx.importExpr(tokenRef):literal(tokenRef);// Construct the dependency.\ndeps.push({token:token,resolved:resolved,host:!!dependency.isHost,optional:!!dependency.isOptional,self:!!dependency.isSelf,skipSelf:!!dependency.isSkipSelf})}else{unsupported(\"dependency without a token\")}}return deps}",
"function dependenciesFromGlobalMetadata(type,outputCtx,reflector){// Use the `CompileReflector` to look up references to some well-known Angular types. These will\n// be compared with the token to statically determine whether the token has significance to\n// Angular, and set the correct `R3ResolvedDependencyType` as a result.\nvar injectorRef=reflector.resolveExternalReference(Identifiers.Injector);// Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\nvar deps=[];for(var _iterator6=type.diDeps,_isArray6=Array.isArray(_iterator6),_i16=0,_iterator6=_isArray6?_iterator6:_iterator6[Symbol.iterator]();;){var _ref28;if(_isArray6){if(_i16>=_iterator6.length)break;_ref28=_iterator6[_i16++]}else{_i16=_iterator6.next();if(_i16.done)break;_ref28=_i16.value}var dependency=_ref28;if(dependency.token){var tokenRef=tokenReference(dependency.token);var resolved=dependency.isAttribute?R3ResolvedDependencyType.Attribute:R3ResolvedDependencyType.Token;// In the case of most dependencies, the token will be a reference to a type. Sometimes,\n// however, it can be a string, in the case of older Angular code or @Attribute injection.\nvar token=tokenRef instanceof StaticSymbol?outputCtx.importExpr(tokenRef):literal(tokenRef);// Construct the dependency.\ndeps.push({token:token,resolved:resolved,host:!!dependency.isHost,optional:!!dependency.isOptional,self:!!dependency.isSelf,skipSelf:!!dependency.isSkipSelf})}else{unsupported(\"dependency without a token\")}}return deps}",
"function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {\n // Use the `CompileReflector` to look up references to some well-known Angular types. These will\n // be compared with the token to statically determine whether the token has significance to\n // Angular, and set the correct `R3ResolvedDependencyType` as a result.\n const elementRef = reflector.resolveExternalReference(Identifiers.ElementRef);\n const templateRef = reflector.resolveExternalReference(Identifiers.TemplateRef);\n const viewContainerRef = reflector.resolveExternalReference(Identifiers.ViewContainerRef);\n const injectorRef = reflector.resolveExternalReference(Identifiers.Injector);\n // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\n const deps = [];\n for (let dependency of type.diDeps) {\n if (dependency.token) {\n const tokenRef = tokenReference(dependency.token);\n let resolved = R3ResolvedDependencyType.Token;\n if (tokenRef === elementRef) {\n resolved = R3ResolvedDependencyType.ElementRef;\n }\n else if (tokenRef === templateRef) {\n resolved = R3ResolvedDependencyType.TemplateRef;\n }\n else if (tokenRef === viewContainerRef) {\n resolved = R3ResolvedDependencyType.ViewContainerRef;\n }\n else if (tokenRef === injectorRef) {\n resolved = R3ResolvedDependencyType.Injector;\n }\n else if (dependency.isAttribute) {\n resolved = R3ResolvedDependencyType.Attribute;\n }\n // In the case of most dependencies, the token will be a reference to a type. Sometimes,\n // however, it can be a string, in the case of older Angular code or @Attribute injection.\n const token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);\n // Construct the dependency.\n deps.push({\n token,\n resolved,\n host: !!dependency.isHost,\n optional: !!dependency.isOptional,\n self: !!dependency.isSelf,\n skipSelf: !!dependency.isSkipSelf,\n });\n }\n else {\n unsupported('dependency without a token');\n }\n }\n return deps;\n}",
"function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {\n var e_1, _a;\n // Use the `CompileReflector` to look up references to some well-known Angular types. These will\n // be compared with the token to statically determine whether the token has significance to\n // Angular, and set the correct `R3ResolvedDependencyType` as a result.\n var injectorRef = reflector.resolveExternalReference(Identifiers.Injector);\n // Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.\n var deps = [];\n try {\n for (var _b = Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__values\"])(type.diDeps), _c = _b.next(); !_c.done; _c = _b.next()) {\n var dependency = _c.value;\n if (dependency.token) {\n var tokenRef = tokenReference(dependency.token);\n var resolved = dependency.isAttribute ?\n R3ResolvedDependencyType.Attribute :\n R3ResolvedDependencyType.Token;\n // In the case of most dependencies, the token will be a reference to a type. Sometimes,\n // however, it can be a string, in the case of older Angular code or @Attribute injection.\n var token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);\n // Construct the dependency.\n deps.push({\n token: token,\n resolved: resolved,\n host: !!dependency.isHost,\n optional: !!dependency.isOptional,\n self: !!dependency.isSelf,\n skipSelf: !!dependency.isSkipSelf,\n });\n }\n else {\n unsupported('dependency without a token');\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return deps;\n}",
"getTemplateAst(template) {\n const { type: classSymbol, fileName } = template;\n const data = this.resolver.getNonNormalizedDirectiveMetadata(classSymbol);\n if (!data) {\n return;\n }\n const htmlParser = new compiler_1.HtmlParser();\n const expressionParser = new compiler_1.Parser(new compiler_1.Lexer());\n const parser = new compiler_1.TemplateParser(new compiler_1.CompilerConfig(), this.reflector, expressionParser, new compiler_1.DomElementSchemaRegistry(), htmlParser, null, // console\n [] // tranforms\n );\n const htmlResult = htmlParser.parse(template.source, fileName, {\n tokenizeExpansionForms: true,\n preserveLineEndings: true,\n });\n const { directives, pipes, schemas } = this.getModuleMetadataForDirective(classSymbol);\n const parseResult = parser.tryParseHtml(htmlResult, data.metadata, directives, pipes, schemas);\n if (!parseResult.templateAst) {\n return;\n }\n return {\n htmlAst: htmlResult.rootNodes,\n templateAst: parseResult.templateAst,\n directive: data.metadata, directives, pipes,\n parseErrors: parseResult.errors, expressionParser, template,\n };\n }",
"getDirectiveMetadata(directiveType) {\n const dirMeta = this._directiveCache.get(directiveType);\n if (!dirMeta) {\n this._reportError(syntaxError(`Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive ${stringifyType(directiveType)}.`), directiveType);\n }\n return dirMeta;\n }",
"function extract_metadata(contents) {\n var metadata = undefined;\n \n if (contents && contents.substring(0,metadata_tag.length) == metadata_tag) {\n var end = contents.indexOf('\\n');\n if (end != -1) {\n metadata = JSON.parse(contents.substring(metadata_tag.length,end));\n contents = contents.substring(end+1,contents.length);\n }\n }\n\n return {contents: contents, metadata: metadata };\n }",
"function extractDirectiveMetadata(clazz, decorator, reflector, evaluator, defaultImportRecorder, isCore, flags, annotateForClosureCompiler, defaultSelector = null) {\n let directive;\n if (decorator === null || decorator.args === null || decorator.args.length === 0) {\n directive = new Map();\n }\n else if (decorator.args.length !== 1) {\n throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @${decorator.name} decorator`);\n }\n else {\n const meta = unwrapExpression(decorator.args[0]);\n if (!ts.isObjectLiteralExpression(meta)) {\n throw new FatalDiagnosticError(ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `@${decorator.name} argument must be an object literal`);\n }\n directive = reflectObjectLiteral(meta);\n }\n if (directive.has('jit')) {\n // The only allowed value is true, so there's no need to expand further.\n return undefined;\n }\n const members = reflector.getMembersOfClass(clazz);\n // Precompute a list of ts.ClassElements that have decorators. This includes things like @Input,\n // @Output, @HostBinding, etc.\n const decoratedElements = members.filter(member => !member.isStatic && member.decorators !== null);\n const coreModule = isCore ? undefined : '@angular/core';\n // Construct the map of inputs both from the @Directive/@Component\n // decorator, and the decorated\n // fields.\n const inputsFromMeta = parseFieldToPropertyMapping(directive, 'inputs', evaluator);\n const inputsFromFields = parseDecoratedFields(filterToMembersWithDecorator(decoratedElements, 'Input', coreModule), evaluator, resolveInput);\n // And outputs.\n const outputsFromMeta = parseFieldToPropertyMapping(directive, 'outputs', evaluator);\n const outputsFromFields = parseDecoratedFields(filterToMembersWithDecorator(decoratedElements, 'Output', coreModule), evaluator, resolveOutput);\n // Construct the list of queries.\n const contentChildFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, 'ContentChild', coreModule), reflector, evaluator);\n const contentChildrenFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, 'ContentChildren', coreModule), reflector, evaluator);\n const queries = [...contentChildFromFields, ...contentChildrenFromFields];\n // Construct the list of view queries.\n const viewChildFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, 'ViewChild', coreModule), reflector, evaluator);\n const viewChildrenFromFields = queriesFromFields(filterToMembersWithDecorator(decoratedElements, 'ViewChildren', coreModule), reflector, evaluator);\n const viewQueries = [...viewChildFromFields, ...viewChildrenFromFields];\n if (directive.has('queries')) {\n const queriesFromDecorator = extractQueriesFromDecorator(directive.get('queries'), reflector, evaluator, isCore);\n queries.push(...queriesFromDecorator.content);\n viewQueries.push(...queriesFromDecorator.view);\n }\n // Parse the selector.\n let selector = defaultSelector;\n if (directive.has('selector')) {\n const expr = directive.get('selector');\n const resolved = evaluator.evaluate(expr);\n if (typeof resolved !== 'string') {\n throw createValueHasWrongTypeError(expr, resolved, `selector must be a string`);\n }\n // use default selector in case selector is an empty string\n selector = resolved === '' ? defaultSelector : resolved;\n if (!selector) {\n throw new FatalDiagnosticError(ErrorCode.DIRECTIVE_MISSING_SELECTOR, expr, `Directive ${clazz.name.text} has no selector, please add it!`);\n }\n }\n const host = extractHostBindings$1(decoratedElements, evaluator, coreModule, directive);\n const providers = directive.has('providers') ?\n new WrappedNodeExpr(annotateForClosureCompiler ?\n wrapFunctionExpressionsInParens(directive.get('providers')) :\n directive.get('providers')) :\n null;\n // Determine if `ngOnChanges` is a lifecycle hook defined on the component.\n const usesOnChanges = members.some(member => !member.isStatic && member.kind === ClassMemberKind.Method &&\n member.name === 'ngOnChanges');\n // Parse exportAs.\n let exportAs = null;\n if (directive.has('exportAs')) {\n const expr = directive.get('exportAs');\n const resolved = evaluator.evaluate(expr);\n if (typeof resolved !== 'string') {\n throw createValueHasWrongTypeError(expr, resolved, `exportAs must be a string`);\n }\n exportAs = resolved.split(',').map(part => part.trim());\n }\n const rawCtorDeps = getConstructorDependencies(clazz, reflector, defaultImportRecorder, isCore);\n let ctorDeps;\n // Non-abstract directives (those with a selector) require valid constructor dependencies, whereas\n // abstract directives are allowed to have invalid dependencies, given that a subclass may call\n // the constructor explicitly.\n if (selector !== null) {\n ctorDeps = validateConstructorDependencies(clazz, rawCtorDeps);\n }\n else {\n ctorDeps = unwrapConstructorDependencies(rawCtorDeps);\n }\n // Detect if the component inherits from another class\n const usesInheritance = reflector.hasBaseClass(clazz);\n const type = wrapTypeReference(reflector, clazz);\n const internalType = new WrappedNodeExpr(reflector.getInternalNameOfClass(clazz));\n const inputs = ClassPropertyMapping.fromMappedObject(Object.assign(Object.assign({}, inputsFromMeta), inputsFromFields));\n const outputs = ClassPropertyMapping.fromMappedObject(Object.assign(Object.assign({}, outputsFromMeta), outputsFromFields));\n const metadata = {\n name: clazz.name.text,\n deps: ctorDeps,\n host,\n lifecycle: {\n usesOnChanges,\n },\n inputs: inputs.toJointMappedObject(),\n outputs: outputs.toDirectMappedObject(),\n queries,\n viewQueries,\n selector,\n fullInheritance: !!(flags & HandlerFlags.FULL_INHERITANCE),\n type,\n internalType,\n typeArgumentCount: reflector.getGenericArityOfClass(clazz) || 0,\n typeSourceSpan: createSourceSpan(clazz.name),\n usesInheritance,\n exportAs,\n providers\n };\n return {\n decorator: directive,\n metadata,\n inputs,\n outputs,\n };\n }",
"function parseID3v1Metadata(footer) {\n var title = footer.getASCIIText(3, 30);\n var artist = footer.getASCIIText(33, 30);\n var album = footer.getASCIIText(63, 30);\n var p = title.indexOf('\\0');\n if (p !== -1)\n title = title.substring(0, p);\n p = artist.indexOf('\\0');\n if (p !== -1)\n artist = artist.substring(0, p);\n p = album.indexOf('\\0');\n if (p !== -1)\n album = album.substring(0, p);\n\n metadata[TITLE] = title || undefined;\n metadata[ARTIST] = artist || undefined;\n metadata[ALBUM] = album || undefined;\n var b1 = footer.getUint8(125);\n var b2 = footer.getUint8(126);\n if (b1 === 0 && b2 !== 0)\n metadata[TRACKNUM] = b2;\n var genre = footer.getUint8(127);\n metadata[GENRE] = genre || undefined;\n metadataCallback(metadata);\n }",
"function parseID3v1Metadata(footer) {\n var title = footer.getASCIIText(3, 30);\n var artist = footer.getASCIIText(33, 30);\n var album = footer.getASCIIText(63, 30);\n var p = title.indexOf('\\0');\n if (p !== -1)\n title = title.substring(0, p);\n p = artist.indexOf('\\0');\n if (p !== -1)\n artist = artist.substring(0, p);\n p = album.indexOf('\\0');\n if (p !== -1)\n album = album.substring(0, p);\n\n metadata[TITLE] = title || undefined;\n metadata[ARTIST] = artist || undefined;\n metadata[ALBUM] = album || undefined;\n var b1 = footer.getUint8(125);\n var b2 = footer.getUint8(126);\n if (b1 === 0 && b2 !== 0)\n metadata[TRACKNUM] = b2;\n metadataCallback(metadata);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
In order to keep the number of buttons to switch playlist pages reasonable, once the number of pages gets too large, only show the first few, last few, and a neighborhood around the current page. | function populatePages() {
$('#playlist-pages').empty();
$('#playlist-pages').append('<li id="playlist-pages-label">Page: </li>')
num_pages = Math.floor((vid_array.length-1)/8) + 1;
if(num_pages <= 9) {
var i = 1;
for (i = 1; i<=num_pages; i++) {
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + i +')">' + i + '</a></li>');
}
}
else {
if (current_page < 4) {
var i = 1;
for (i = 1; i<=4; i++) {
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + i +')" id="page-' + i + '">' + i + '</a></li>');
}
$('#playlist-pages').append('<li>...</li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages - 1) +')" id="page-' + (num_pages - 1) + '">' + (num_pages-1) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + num_pages +')" id="page-' + num_pages + '">' + num_pages + '</a></li>');
}
else if (num_pages - current_page < 4) {
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + 1 +')" id="page-' + 1 + '">' + 1 + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + 2 +')" id="page-' + 2 + '">' + 2 + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + 3 +')" id="page-' + 3 + '">' + 3 + '</a></li>');
$('#playlist-pages').append('<li>...</li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages-4) +')" id="page-' + (num_pages-4) + '">' + (num_pages-4) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages-3) +')" id="page-' + (num_pages-3) + '">' + (num_pages-3) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages-2) +')" id="page-' + (num_pages-2) + '">' + (num_pages-2) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages-1) +')" id="page-' + (num_pages-1) + '">' + (num_pages-1) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages) +')" id="page-' + (num_pages) + '">' + (num_pages) + '</a></li>');
}
else {
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + 1 +')" id="page-' + 1 + '">' + 1 + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + 2 +')" id="page-' + 2 + '">' + 2 + '</a></li>');
$('#playlist-pages').append('<li>...</li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (current_page-1) +')" id="page-' + (current_page-1) + '">' + (current_page-1) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (current_page) +')" id="page-' + (current_page) + '">' + (current_page) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (current_page+1) +')" id="page-' + (current_page+1) + '">' + (current_page+1) + '</a></li>');
$('#playlist-pages').append('<li>...</li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages-2) +')" id="page-' + (num_pages-2) + '">' + (num_pages-2) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + (num_pages-1) +')" id="page-' + (num_pages-1) + '">' + (num_pages-1) + '</a></li>');
$('#playlist-pages').append('<li><a onclick="javascript:switchToPage(' + num_pages +')" id="page-' + num_pages + '">' + num_pages + '</a></li>');
}
}
} | [
"function show_page( n ) {\n\n // Increment page counter:\n current_page += n;\n n = current_page;\n\n // Erase last page of tablets:\n $(\"#tablet_previews\").html('');\n\n // add \"next page\" and \"previous page\" buttons:\n var buttons = document.createElement(\"div\");\n buttons.id = \"preview_buttons\";\n buttons.style = \"text-align:center;padding-right:4px;\";\n\n var nextPg = document.createElement(\"a\");\n nextPg.href = \"javascript:void(0);\";\n nextPg.innerHTML = \" > next page \";\n nextPg.onclick = function() {\n show_page(1);\n };\n\n var lastPg = document.createElement(\"a\");\n lastPg.href = \"javascript:void(0);\";\n lastPg.innerHTML = \" prev page < \";\n lastPg.onclick = function() {\n show_page(-1);\n };\n // Only draw buttons if there is actually \n // a next/last page to go to:\n if (current_page > 0) {\n buttons.appendChild(lastPg);\n }\n if (current_page < Math.ceil(pages.length / 5) - 1) {\n buttons.appendChild(nextPg);\n }\n $(\"#tablet_previews\").append(buttons);\n\n\n\n // Load the search string (the set of\n // nodes the user has selected in the tree):\n var search_str = search_str_saved;\n // Retrieve the correct page of tablets:\n var tablets_with_string = pages.slice(5 * n, 5 * (1 + n));\n // Make a deep copy so we don't change the pages array:\n var rotated = [...pages];\n // Look for repeated strings. Uses the 5 tablets currently\n // on display plus the next 5 pages of tablets. Doesn't use\n // all of the tablets for reasons of time.\n var hilites = myDiff( \n rotated.rotate(5 * n).slice(0, 30), \n search_str\n );\n\n // Draw the tablets to the page:\n for (var i = 0; i < tablets_with_string.length; i++) {\n var hilite = false;\n\n // div to hold this tablet:\n var preview = document.createElement(\"div\");\n preview.className = \"tablet_preview\";\n\n // Fetch tablet content, with line breaks already inserted:\n var split_tablet = tablets_with_string[i];\n // Print tablet's CDLI catalogue number and a link\n // to the tablet's archival record on the CDLI website:\n preview.innerHTML = \"<a href='https://cdli.ucla.edu/search/archival_view.php?ObjectID=\" \n\t + split_tablet[0] // split_tablet[0] = the CDLI number\n\t + \"'>\" \n\t + split_tablet[0] \n\t + \"</a><br/>\";\n var content = \"<p>\";\n for (var j = 1; j < split_tablet.length; j++) {\n\t // Too slow to draw the sign images like this:\n //preview.innerHTML += \"<img src='pngs/PE_mainforms/\"+\"M388\"+\".png' alt='\"+split_tablet[j]+\"' style='height:12px;width:12px;'/>\";\n\t // Convert line breaks to p tags for nicer display:\n if (split_tablet[j] == \"<br/>\") {\n content += \"</p><p>\"\n } else {\n\t // id uniquely defines this sign as the jth character\n\t // in the ith tablet. Id will be used for highlighting.\n content += \"<span id='char_\" + i + \"_\" + j + \"'>\" + split_tablet[j] + \" </span>\";\n }\n }\n preview.innerHTML += content;\n $(\"#tablet_previews\").append(preview);\n }\n\n // hilites contains list of indices of characters that should be\n // highlighted. Iterate and highlight each one:\n for (var key in hilites) {\n // Highlight the background:\n $(key).css(\"background-color\", getColor(hilites[key]));\n // Make sure text stands out against background:\n $(key).css(\"color\", invertColor(getColor(hilites[key]), bw = true));\n }\n}",
"function ShowNextPrevButtons(lastpage)\n{\n // Show Prev and Next buttons if there is more than 1 page.\n if (lastpage > 1)\n {\n $(\"#prev\").css(\"visibility\", \"visible\");\n $(\"#next\").css(\"visibility\", \"visible\");\n }\n else \n {\n $(\"#prev\").css(\"visibility\", \"hidden\");\n $(\"#next\").css(\"visibility\", \"hidden\"); \n } \n}",
"function showPage(list, page) {\n const startIndex = (page * numberOfItems) - numberOfItems;\n const endIndex = page * numberOfItems;\n for ( let i = 0; i < list.length; i++ ) {\n if ( i < startIndex || i >= endIndex ) { //condition to select 10 items per page. true if either of the conditions are true.\n list[i].style.display = 'none';\n } else {\n list[i].style.display = 'block';\n }\n }\n}",
"function showTab(key, n) {\n var x = paginations[key].children;\n var y = indicatorSets[key].children;\n var z = document.getElementById(absoluteParents[key]);\n if (x != null && x.length > 0) {\n x[n].style.display = \"block\";\n /*// Hides btns depending if on first or last page\n if (n == 0) {\n document.getElementById(\"firstBtn\").style.display = \"none\";\n document.getElementById(\"prevBtn\").style.display = \"none\";\n } else {\n document.getElementById(\"firstBtn\").style.display = \"inline\";\n document.getElementById(\"prevBtn\").style.display = \"inline\";\n }\n if (n == x.length - 1) {\n document.getElementById(\"lastBtn\").style.display = \"none\";\n document.getElementById(\"nextBtn\").style.display = \"none\";\n } else {\n document.getElementById(\"lastBtn\").style.display = \"inline\";\n document.getElementById(\"nextBtn\").style.display = \"inline\";\n }//*/\n // Displays indicator based on page\n if (y.length > 5) {\n for (var i = 0; i < y.length; i++) {\n y[i].style.display = \"none\";\n y[i].className = y[i].className.replace(\" active\", \"\");\n }\n if (n < 3) {\n for (var i = 0; i < 5; i++) {\n y[i].style.display = \"inline-block\";\n }\n } else if (n > y.length - 4) {\n for (var i = y.length - 1; i > y.length - 6; i--) {\n y[i].style.display = \"inline-block\";\n }\n } else {\n for (var i = n - 2; i <= n + 2; i++) {\n y[i].style.display = \"inline-block\";\n }\n }\n } else {\n for (var i = 0; i < y.length; i++) {\n y[i].style.display = \"inline-block\";\n y[i].className = y[i].className.replace(\" active\", \"\");\n }\n }\n y[n].className += \" active\";\n z.scrollTop = 0;\n }\n}",
"function showHidePages() {\n $.each(pageArray, function (index, value) {\n if (index != visiblePageIndex) {\n value.hide();\n } else {\n value.show();\n }\n });\n\n // If the first or last page is visible, hide the appropriate scroll button(s).\n visiblePageIndex == 0 ? $(\"#left\").addClass(\"pageScrollButtonDisabled\") : $(\"#left\").removeClass(\"pageScrollButtonDisabled\");\n visiblePageIndex == pageArray.length - 1 ? $(\"#right\").addClass(\"pageScrollButtonDisabled\") : $(\"#right\").removeClass(\"pageScrollButtonDisabled\");\n setInfoPaneHeight();\n }",
"function showPage(n) {\n var x = document.getElementsByClassName(\"page\");\n x[n].style.display = \"block\";\n if (n == 0) { // Hide previous button if on first page\n $('.prev_button').hide();\n } else {\n $('.prev_button').show();\n }\n if (n == (x.length - 1)) { // Show submit button if on last page\n $('.next_button').html(\"Submit\");\n } else {\n $('.next_button').html('Next <i class=\"fas fa-arrow-right\"></i>');\n }\n}",
"function buttonsAction(){\n if (currentNumberOfPage >= Number(numberOfPages.innerHTML)) {\n nextButton.classList.add(\"hide\");\n } else if (currentNumberOfPage < Number(numberOfPages.innerHTML) && currentNumberOfPage > 1) {\n nextButton.classList.remove(\"hide\");\n }\n\n if (currentNumberOfPage < 2) {\n previousButton.classList.add(\"hide\");\n } else if (currentNumberOfPage > 1) {\n previousButton.classList.remove(\"hide\");\n }\n}",
"function makeList() {\n numberOfRecPages = Math.ceil(rec_list.length / numberPerPage);\n numberOfRestPages = Math.ceil(rest_list.length / numberPerPage);\n \n //show up to first five buttons\n if (numberOfRestPages >= 5) {\n createNumberedRestButton(1, 5);\n } else {\n createNumberedRestButton(1, numberOfRestPages);\n }\n if (numberOfRecPages >= 5) {\n createNumberedRecButton(1, 5);\n } else {\n createNumberedRecButton(1, numberOfRestPages);\n }\n}",
"function showMoreStories() {\n var tempEndIndex = storyDisplayRange.endIndex + storyDisplayRange.limit;\n if (tempEndIndex < topStories.length) {\n storyDisplayRange.startIndex = storyDisplayRange.endIndex;\n storyDisplayRange.endIndex = tempEndIndex;\n getLimitedStories();\n } else {\n getLimitedStories();\n removeLimitButton();\n }\n}",
"function checkVisibleBtns() {\n if (currPageNum == maxPageNum && nextBtnOn) {document.querySelector('#nextbtn').style.display = \"none\"; nextBtnOn = false;}\n else if (!nextBtnOn) {document.querySelector('#nextbtn').style.display = \"inline\"; nextBtnOn = true;}\n\n if (currPageNum == minPageNum && backBtnOn) {document.querySelector('#backbtn').style.display = \"none\"; backBtnOn = false;}\n else if (!backBtnOn) {document.querySelector('#backbtn').style.display = \"inline\"; backBtnOn = true;}\n}",
"function showButtons() {\n var current = jQuery('.pressReleaseListingWrapper:visible');\n if (current.index() == 0) {\n jQuery('.prevBtn').hide();\n jQuery('.nextBtn').show();\n } else if (current.index() == jQuery('.pressReleaseListingWrapper').length - 1) {\n jQuery('.prevBtn').show();\n jQuery('.nextBtn').hide();\n } else {\n jQuery('.prevBtn').show();\n jQuery('.nextBtn').show();\n };\n }",
"NextVisible() {}",
"function displayNextMovies () {\n $('.next-button').on('click', function() {\n if (end >= popularMovies.length) {\n pageNumber++;\n retrieveMovies(pageNumber);\n }\n start += resultsPerPage;\n end += resultsPerPage;\n displayMovies();\n if (start >= resultsPerPage) {\n $('.prev-button').show();\n }\n });\n}",
"function showPage(pageNum){\n //clear all\n for (let i = 0; i < rows.length; i++){\n rows[i].style.display = 'none';\n }\n //set display to none if not in page range\n for (let i = 0; i < list.length; i++){\n if(i + 1 > (pageNum * resultsPerPage) - resultsPerPage && i < pageNum * resultsPerPage){\n list[i].style.display = '';\n }\n }\n }",
"function myPages(data, nbr_rslt = nbr_of_result_to_display, opt = null) { //ne pas changer nbr_rslt\r\n var pages = Math.ceil(data.length / nbr_rslt);\r\n $(\"#pages-container\").remove();\r\n $(\"#main-container\").append(\"<div id='pages-container'></div>\");\r\n if (nbr_rslt == data.length) {\r\n clearMoviePage();\r\n clearResult();\r\n allResultsWithNoButton(data);\r\n return;\r\n }\r\n //PAGE NUMBER BUTTON MAKER\r\n for (let i = 1; i <= pages; i++) {\r\n $(\"#pages-container\").append(\"<button id='page-\" + i + \"'>\" + i + \"</button>\");\r\n //AFFICHAGE DE PAGES\r\n $(\"#page-\" + i).on(\"click\", function () {\r\n $(\"#result\").html(\"\");\r\n if (i == 1) {\r\n for (let j = 0; j <= nbr_rslt - 1; j++) {\r\n if (opt == 'member') {\r\n if (data[j] && data[j] != undefined) {\r\n getMemberHistoric(data[j].split(\"|\"));\r\n }\r\n } else {\r\n $(\"#title-mem\").text() == \"\"\r\n ? myMovieCardWithAPI(data[j])\r\n : getMemberHistoric(data[j].split(\"|\"));\r\n }\r\n }\r\n } else {\r\n for (let j = (i - 1) * nbr_rslt; j <= (i - 1) * nbr_rslt + (nbr_rslt - 1); j++) {\r\n if (data[j] == null) {\r\n break;\r\n } else {\r\n $(\"#title-mem\").text() == \"\"\r\n ? myMovieCardWithAPI(data[j])\r\n : getMemberHistoric(data[j].split(\"|\"));\r\n }\r\n }\r\n }\r\n });\r\n }\r\n $(\"#page-1\").click();\r\n}",
"function showPage (list, page, itemsPerPage){\n let startIndex = (page*itemsPerPage)-itemsPerPage;\n let endIndex = (page*itemsPerPage)-1;\n for (let i=0; i<list.length; i++){\n if (i>=startIndex && i<=endIndex){\n list[i].style.display =\"\";\n } else {\n list[i].style.display = \"none\";\n }\n }\n}",
"function showPagination(){\n let prev = document.getElementById(\"prev\")\n let next = document.getElementById(\"next\")\n if(pageCounter === 1) {\n next.classList.remove(\"hidden\");\n next.classList.add(\"show\");\n prev.classList.remove(\"show\");\n prev.classList.add(\"hidden\");\n } else if (pageCounter > 1) {\n next.classList.remove(\"hidden\");\n next.classList.add(\"show\");\n prev.classList.remove(\"hidden\");\n prev.classList.add(\"show\");\n }\n}",
"function mllsdPagination(){\n $(\".MLLSD_Page\").hide();\n $(\".MLLSD_Dropdown\").hide();\n $(\".MLLSD_Tag\").hide();\n const range = 2;\n const url = window.location.pathname.split('_');\n const num = parseInt(url[url.length - 1]);\n var MLLSD_page = Number.isInteger(num) ? num : 0;\n $(\"#v0\").show();\n $(\"#v14\").show();\n if(MLLSD_page <= (range+1)){\n $(\"#mllsd_prev\").hide();\n MLLSD_page = range + 1;\n }else{\n for(var i=1; i < MLLSD_page-range; i++){\n const id = i;\n $(\"#p\"+id).show();\n }\n }\n if(MLLSD_page >= (14 - range - 1)){\n $(\"#mllsd_next\").hide();\n MLLSD_page = 14 - range - 1;\n }else{\n for(var j=13; j > MLLSD_page+range; j--){\n const id = j;\n $(\"#n\"+id).show();\n }\n }\n $(\"#v\"+MLLSD_page).show();\n for(var k=0; k < range; k++){\n for(var n=0; n<2; n++){\n const id = MLLSD_page + (2*n-1)*(k+1);\n $(\"#v\"+id).show();\n }\n }\n}",
"function updatePagers() {\n jQuery('div.pz2-pager').each(function (index) {\n var pages = Math.ceil(displayHitList.length / recPerPage);\n\n // Update pager\n var jPageNumbersContainer = jQuery('.pz2-pageNumbers', this);\n jPageNumbersContainer.removeClass().addClass('pz2-pageNumbers pz2-pageCount-' + pages);\n jPageNumbersContainer.empty();\n var pageNumbersContainer = jPageNumbersContainer[0];\n\n var previousLink = document.createElement('span');\n if (curPage > 1) {\n previousLink = document.createElement('a');\n previousLink.setAttribute('href', '#');\n previousLink.onclick = new Function('pagerPrev(this);return false;');\n previousLink.title = localise('Vorige Trefferseite anzeigen');\n }\n jQuery(previousLink).addClass('pz2-prev');\n previousLink.appendChild(document.createTextNode('«'));\n pageNumbersContainer.appendChild(previousLink);\n\n var pageList = document.createElement('ol');\n jQuery(pageList).addClass('pz2-pages');\n pageNumbersContainer.appendChild(pageList);\n\n var blockSize = 4;\n var inBlockGap = false;\n\n for (var pageNumber = 1; pageNumber <= pages; pageNumber++) {\n if (pageNumber < 5 || Math.abs(pageNumber - curPage) < 3 || pages < pageNumber + 4) {\n var pageItem = document.createElement('li');\n pageList.appendChild(pageItem);\n if (pageNumber !== curPage) {\n var linkElement = document.createElement('a');\n linkElement.setAttribute('href', '#');\n linkElement.onclick = new Function('showPage(' + pageNumber + ', this);return false;');\n linkElement.appendChild(document.createTextNode(pageNumber));\n pageItem.appendChild(linkElement);\n }\n else {\n jQuery(pageItem).addClass('pz2-currentPage');\n pageItem.appendChild(document.createTextNode(pageNumber));\n }\n inBlockGap = false;\n }\n else {\n if (!inBlockGap) {\n var dotsItem = document.createElement('li');\n pageList.appendChild(dotsItem);\n dotsItem.setAttribute('class', 'pz2-pagerGap');\n dotsItem.appendChild(document.createTextNode('…'));\n inBlockGap = true;\n }\n }\n }\n\n var nextLink = document.createElement('span');\n if (pages - curPage > 0) {\n nextLink = document.createElement('a');\n nextLink.setAttribute('href', '#');\n nextLink.onclick = new Function('pagerNext(this);return false;');\n nextLink.title = localise('Nächste Trefferseite anzeigen');\n }\n jQuery(nextLink).addClass('pz2-next');\n nextLink.appendChild(document.createTextNode('»'));\n pageNumbersContainer.appendChild(nextLink);\n\n var jRecordCount = jQuery('.pz2-recordCount');\n jRecordCount.removeClass('pz2-noResults');\n\n // Add record count information\n var infoString;\n if (displayHitList.length > 0) {\n var firstIndex = recPerPage * (curPage - 1);\n var numberOfRecordsOnPage = Math.min(displayHitList.length - firstIndex, recPerPage);\n infoString = String(firstIndex + 1) + '-'\n + String(firstIndex + numberOfRecordsOnPage)\n + ' ' + localise('von') + ' '\n + String(displayHitList.length);\n\n // Determine transfer status and append indicators about it to\n // the result count: + for overflow, … while we are busy and\n // · for errors.\n var transfersBusy = [];\n var resultOverflow = [];\n var hasError = [];\n var totalResultCount = 0;\n var statusIndicator = '';\n\n for (var targetIndex in targetStatus) {\n var target = targetStatus[targetIndex];\n\n if (!isNaN(target.hits)) {\n totalResultCount += parseInt(target.hits, 10);\n }\n\n if (target.state === 'Client_Working') {\n transfersBusy.push(target);\n }\n else if (target.state === 'Client_Idle') {\n if (target.hits > target.records) {\n resultOverflow.push(target);\n }\n }\n else if (target.state === 'Client_Error' || target.state === 'Client_Disconnected') {\n hasError.push(target);\n }\n }\n\n var titleText = [];\n if (resultOverflow.length > 0) {\n infoString += localise('+');\n var overflowMessage = localise('Es können nicht alle # Treffer geladen werden.');\n titleText.push(overflowMessage.replace('#', totalResultCount));\n }\n if (transfersBusy.length > 0) {\n infoString += localise('...');\n }\n if (hasError.length > 0) {\n infoString += localise('Error indicator');\n var errorMessage = localise('Bei der Übertragung von Daten aus # der abgefragten Kataloge ist ein Fehler aufgetreten.');\n titleText.push(errorMessage.replace('#', hasError.length));\n }\n\n jRecordCount.attr('title', titleText.join('\\n'));\n\n // Mark results as filtered if the filterArray has a\n // non-trivial property.\n for (var filterIndex in filterArray) {\n if (filterArray[filterIndex] !== undefined) {\n infoString += ' [' + localise('gefiltert') + ']';\n break;\n }\n }\n }\n else {\n if (!my_paz.currQuery) {\n infoString = localise('keine Suchabfrage');\n }\n else if (my_paz.activeClients === 0) {\n infoString = localise('keine Treffer gefunden');\n jRecordCount.addClass('pz2-noResults');\n updateProgressBar(100);\n }\n else {\n infoString = localise('Suche...');\n }\n }\n\n jRecordCount.empty();\n jRecordCount.append(infoString);\n }\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A panel to display a study's participant annotation types. | function StudyAnnotationTypesPanelCtrl($scope,
Panel) {
var vm = this,
panel = new Panel($scope.panelId, $scope.addStateName);
vm.study = $scope.study;
vm.annotationTypes = $scope.annotationTypes;
vm.annotationTypeIdsInUse = $scope.annotationTypeIdsInUse;
vm.annotationTypeName = $scope.annotationTypeName;
vm.panelHeading = panelHeading($scope.annotationTypeName);
vm.annotationTypeDescription = annotationTypeDescription($scope.annotationTypeName);
vm.updateStateName = $scope.updateStateName;
vm.add = add;
vm.panelOpen = panel.getPanelOpenState();
vm.modificationsAllowed = vm.study.isDisabled();
$scope.$watch(angular.bind(vm, function() { return vm.panelOpen; }),
angular.bind(panel, panel.watchPanelOpenChangeFunc));
//--
function add() {
return panel.add();
}
function panelHeading(annotationTypeName) {
switch (annotationTypeName) {
case 'ParticipantAnnotationType':
return 'Participant Annotation Types';
case 'CollectionEventAnnotationType':
return 'Collection Event Annotation Types';
case 'SpecimenLinkAnnotationType':
return 'Specimen Link Annotation Types';
default:
throw new Error('invalid annotation type name: ' + vm.annotationTypeName);
}
}
function annotationTypeDescription(annotationTypeName) {
switch (annotationTypeName) {
case 'ParticipantAnnotationType':
return 'Participant annotations allow a study to collect custom named and ' +
'defined pieces of data for each participant. Annotations are optional and ' +
'are not required to be defined.';
case 'CollectionEventAnnotationType':
return 'Collection event annotations allow a study to collect custom named and ' +
'defined pieces of data for each collection event. Annotations are optional and ' +
'are not required to be defined.';
case 'SpecimenLinkAnnotationType':
return 'Specimen link annotations allow a study to collect custom named and '+
'defined pieces of data when processing specimens. Annotations are optional and ' +
'are not required to be defined.';
default:
throw new Error('invalid annotation type name: ' + vm.annotationTypeName);
}
}
} | [
"function showAnnotationType(annotTypeId) {\n annotTypeModalService.show('Specimen Link Annotation Type', vm.annotTypesById[annotTypeId]);\n }",
"function showAnnotationType(annotTypeId) {\n annotTypeModalService.show('Specimen Link Annotation Type', vm.annotationTypesById[annotTypeId]);\n }",
"function getPropertiesByType(annotation) {\n const sections = [];\n let title;\n const pushSectionForType = (annotationKey, label) => {\n const ul = document.createElement(\"ul\");\n\n Object.keys(annotationsMap[annotationKey]).forEach((prop) => {\n const { label, getElements, icon } = annotationsMap[annotationKey][prop];\n const domElements = getElements();\n\n if (Array.isArray(domElements) && domElements.length > 0) {\n ul.appendChild(generateListItem(label, prop, domElements, icon));\n }\n });\n\n // If there's enough width the inspector can be rendered on the sides of\n // the annotation even when the height of the viewport wouldn't be enough\n const shouldCollapseSectionsByDefault =\n window.innerHeight <= COLLAPSE_BY_DEFAULT_HEIGHT &&\n window.innerWidth <= COLLAPSE_BY_DEFAULT_WIDTH;\n\n if (shouldCollapseSectionsByDefault) {\n ul.classList.toggle(\"collapsed-list\");\n }\n\n const sectionIcon = shouldCollapseSectionsByDefault\n ? \"panel-expand.svg\"\n : \"panel-collapse.svg\";\n const sectionEl = document.createElement(\"section\");\n const collapseBtn = document.createElement(\"button\");\n\n collapseBtn.className = \"collapse-toggle-button\";\n\n const collapseImg = document.createElement(\"img\");\n\n collapseImg.src = `/annotations-inspector/static/${sectionIcon}`;\n collapseImg.setAttribute(\"alt\", \"Expand\");\n collapseBtn.appendChild(collapseImg);\n collapseBtn.id = `collapse-${annotationKey}`;\n\n const sectionDiv = document.createElement(\"div\");\n\n sectionDiv.className = \"section-title\";\n sectionDiv.innerHTML = `<label class=\"group-title\" for=\"${collapseBtn.id}\">${label}</label>`;\n sectionDiv.firstChild.appendChild(collapseBtn);\n sectionEl.appendChild(sectionDiv);\n sectionEl.appendChild(ul);\n collapseBtn.addEventListener(\"click\", () => {\n if (ul.classList.contains(\"collapsed-list\")) {\n collapseImg.src = \"/annotations-inspector/static/panel-collapse.svg\";\n collapseImg.setAttribute(\"alt\", \"Collapse\");\n } else {\n collapseImg.src = \"/annotations-inspector/static/panel-expand.svg\";\n collapseImg.setAttribute(\"alt\", \"Expand\");\n }\n\n ul.classList.toggle(\"collapsed-list\");\n });\n sections.push(sectionEl);\n };\n\n pushSectionForType(\"annotation\", \"Container style\");\n\n if (annotation instanceof PSPDFKit.Annotations.ShapeAnnotation) {\n pushSectionForType(\"shapeAnnotation\", \"Shape style\");\n title = \"Shape annotation properties\";\n } else if (annotation instanceof PSPDFKit.Annotations.InkAnnotation) {\n pushSectionForType(\"inkAnnotation\", \"Ink style\");\n title = \"Ink annotation properties\";\n } else if (annotation instanceof PSPDFKit.Annotations.TextAnnotation) {\n pushSectionForType(\"textAnnotation\", \"Text style\");\n title = \"Text annotation properties\";\n } else if (annotation instanceof PSPDFKit.Annotations.NoteAnnotation) {\n pushSectionForType(\"noteAnnotation\", \"Note style\");\n } else if (annotation instanceof PSPDFKit.Annotations.HighlightAnnotation) {\n pushSectionForType(\"highlightAnnotation\", \"Highlight style\");\n title = \"Highlight annotation properties\";\n }\n\n // we reverse the array to show the most specific properties first\n return { title, sections: sections.reverse() };\n}",
"_initAnnotationPanel(){\n var that = this;\n\n\n\n // open file button\n this._annotationPanel.addFileChooser(\n \"Annotation file\",\n \"Open\",\n \"\",\n function( file ){\n that._annotationCollection.loadAnnotationFileDialog( file );\n }\n );\n\n // save annot button\n this._annotationPanel.addButton(\"Export annotations\", null);\n this._annotationPanel.overrideStyle(\"Export annotations\", \"width\", \"100%\");\n document.getElementById(\"Export annotations\").parentElement.style[\"margin-top\"] = \"0px\";\n\n // dropdown menu\n this._annotationPanel.addDropDown(\"Annotations\", [],\n function( dropdownObj ){\n var annotation = that._annotationCollection.getAnnotation( dropdownObj.value );\n\n if(annotation){\n that._displayAnnotInfo( annotation );\n }\n }\n );\n\n\n\n // callback when a new annot is added in the core, a new item shows on the menu\n that._annotationCollection.onAddingAnnotation( function(name){\n var dropdownObj = that._annotationPanel.getControl(\"Annotations\");\n dropdownObj.addItem(name);\n console.log( dropdownObj );\n\n //dropdownObj.setValue(name);\n\n var annotation = that._annotationCollection.getAnnotation( name );\n\n if(annotation){\n that._displayAnnotInfo( annotation );\n }\n });\n\n /*\n this._annotationPanel.getControl(\"Annotations\").removeItem(\"pouet2\");\n */\n\n // editable field for annotation name\n this._annotationPanel.addText(\"Annotation name\", \"\", function(){} );\n this._annotationPanel.overrideStyle(\"Annotation name\", \"text-align\", \"center\");\n\n // editable description of the annot\n this._annotationPanel.addTextArea(\"Annotation description\", \"\", function(){} );\n document.getElementById(\"Annotation description\").parentElement.style[\"margin-top\"] = \"0px\";\n\n // Pannel of buttons for dealing with existing annot\n this._annotationPanel.addHTML(\"panelEditExistingAnnot\", this._buildPanelEditExistingAnnot());\n document.getElementById(\"panelEditExistingAnnot\").parentElement.style[\"margin-top\"] = \"0px\";\n\n\n // Button to create a new annotation\n this._annotationPanel.addButton(\"Start new annotation\", function(){\n // show and hide the relevant componants\n that._annotationPanel.hideControl(\"panelEditExistingAnnot\");\n that._annotationPanel.showControl(\"panelCreateAnnot\");\n that._annotationPanel.showControl(\"Validate annotation\");\n that._annotationPanel.hideControl(\"Start new annotation\");\n\n // prevent the user from doing stupid interactions\n that._annotationPanel.disableControl(\"Annotations\");\n that._annotationPanel.disableControl(\"Export annotations\");\n that._annotationPanel.disableControl(\"Annotation file\");\n\n // enable creation\n // (the temp annot will 'really' be created at the first click)\n that._annotationCollection.enableAnnotCreation();\n });\n this._annotationPanel.overrideStyle(\"Start new annotation\", \"width\", \"100%\");\n\n // Button to validate a homemade annotation\n this._annotationPanel.addButton(\"Validate annotation\", function(){\n // show and hide the relevant componants\n that._annotationPanel.showControl(\"panelEditExistingAnnot\");\n that._annotationPanel.hideControl(\"panelCreateAnnot\");\n that._annotationPanel.hideControl(\"Validate annotation\");\n that._annotationPanel.showControl(\"Start new annotation\");\n\n // allow the user to interact\n that._annotationPanel.enableControl(\"Annotations\");\n that._annotationPanel.enableControl(\"Export annotations\");\n that._annotationPanel.enableControl(\"Annotation file\");\n\n // done with the creation\n that._annotationCollection.addTemporaryAnnotation();\n\n });\n this._annotationPanel.overrideStyle(\"Validate annotation\", \"width\", \"100%\");\n this._annotationPanel.hideControl(\"Validate annotation\");\n\n // homemade annot options\n this._annotationPanel.addHTML(\"panelCreateAnnot\", this._buildPanelCreateAnnot());\n document.getElementById(\"panelCreateAnnot\").parentElement.style[\"margin-top\"] = \"0px\";\n this._annotationPanel.hideControl(\"panelCreateAnnot\");\n }",
"_initAnnotationPanel(){\n var that = this;\n\n\n\n // open file button\n this._annotationPanel.addFileChooser(\n \"Annotation file\",\n \"Open\",\n \"\",\n function( file ){\n that._annotationCollection.loadAnnotationFileDialog( file );\n }\n );\n\n // save annot button\n this._annotationPanel.addButton(\"Export annotations\", null);\n this._annotationPanel.overrideStyle(\"Export annotations\", \"width\", \"100%\");\n document.getElementById(\"Export annotations\").parentElement.style[\"margin-top\"] = \"0px\";\n\n // dropdown menu\n this._annotationPanel.addDropDown(\"Annotations\", [],\n function( dropdownObj ){\n var annotation = that._annotationCollection.getAnnotation( dropdownObj.value );\n\n if(annotation){\n that._displayAnnotInfo( annotation );\n }\n }\n );\n\n\n\n // callback when a new annot is added in the core, a new item shows on the menu\n that._annotationCollection.onAddingAnnotation( function(name){\n var dropdownObj = that._annotationPanel.getControl(\"Annotations\");\n dropdownObj.addItem(name);\n console.log( dropdownObj );\n\n //dropdownObj.setValue(name);\n\n var annotation = that._annotationCollection.getAnnotation( name );\n\n if(annotation){\n that._displayAnnotInfo( annotation );\n }\n })\n\n /*\n this._annotationPanel.getControl(\"Annotations\").removeItem(\"pouet2\");\n */\n\n // editable field for annotation name\n this._annotationPanel.addText(\"Annotation name\", \"\", function(){} );\n this._annotationPanel.overrideStyle(\"Annotation name\", \"text-align\", \"center\");\n\n // editable description of the annot\n this._annotationPanel.addTextArea(\"Annotation description\", \"\", function(){} );\n document.getElementById(\"Annotation description\").parentElement.style[\"margin-top\"] = \"0px\";\n\n // Pannel of buttons for dealing with existing annot\n this._annotationPanel.addHTML(\"panelEditExistingAnnot\", this._buildPanelEditExistingAnnot());\n document.getElementById(\"panelEditExistingAnnot\").parentElement.style[\"margin-top\"] = \"0px\";\n\n\n // Button to create a new annotation\n this._annotationPanel.addButton(\"Start new annotation\", function(){\n // show and hide the relevant componants\n that._annotationPanel.hideControl(\"panelEditExistingAnnot\");\n that._annotationPanel.showControl(\"panelCreateAnnot\");\n that._annotationPanel.showControl(\"Validate annotation\");\n that._annotationPanel.hideControl(\"Start new annotation\");\n\n // prevent the user from doing stupid interactions\n that._annotationPanel.disableControl(\"Annotations\");\n that._annotationPanel.disableControl(\"Export annotations\");\n that._annotationPanel.disableControl(\"Annotation file\");\n\n // enable creation\n // (the temp annot will 'really' be created at the first click)\n that._annotationCollection.enableAnnotCreation();\n });\n this._annotationPanel.overrideStyle(\"Start new annotation\", \"width\", \"100%\");\n\n // Button to validate a homemade annotation\n this._annotationPanel.addButton(\"Validate annotation\", function(){\n // show and hide the relevant componants\n that._annotationPanel.showControl(\"panelEditExistingAnnot\");\n that._annotationPanel.hideControl(\"panelCreateAnnot\");\n that._annotationPanel.hideControl(\"Validate annotation\");\n that._annotationPanel.showControl(\"Start new annotation\");\n\n // allow the user to interact\n that._annotationPanel.enableControl(\"Annotations\");\n that._annotationPanel.enableControl(\"Export annotations\");\n that._annotationPanel.enableControl(\"Annotation file\");\n\n // done with the creation\n that._annotationCollection.addTemporaryAnnotation();\n\n });\n this._annotationPanel.overrideStyle(\"Validate annotation\", \"width\", \"100%\");\n this._annotationPanel.hideControl(\"Validate annotation\");\n\n // homemade annot options\n this._annotationPanel.addHTML(\"panelCreateAnnot\", this._buildPanelCreateAnnot());\n document.getElementById(\"panelCreateAnnot\").parentElement.style[\"margin-top\"] = \"0px\";\n this._annotationPanel.hideControl(\"panelCreateAnnot\");\n }",
"function TypePStudy() {\n var _this = _super.call(this, SwfType.PSTUDY) || this;\n _this.addParameterFile();\n _this.addUpload();\n _this.sortPropertyInfo();\n return _this;\n }",
"function __showAnnotations(){\r\n switch(_currentSlide) {\r\n case 2:\r\n d3.selectAll(\"#annotations g.annotation\")\r\n .style(\"visibility\", d => d.id.includes(\"A2\") ? \"visible\" : \"hidden\");\r\n break;\r\n case 3:\r\n d3.selectAll(\"#annotations g.annotation\")\r\n .style(\"visibility\", d => d.id.includes(\"A3\") ? \"visible\" : \"hidden\");\r\n break;\r\n case 4:\r\n d3.selectAll(\"#annotations g.annotation\")\r\n .style(\"visibility\", d => d.id.includes(\"A4\") ? \"visible\" : \"hidden\");\r\n break;\r\n case 5:\r\n d3.selectAll(\"#annotations g.annotation\")\r\n .style(\"visibility\", d => d.id.includes(\"A5\") ? \"visible\" : \"hidden\");\r\n break;\r\n case 1:\r\n default:\r\n d3.selectAll(\"#annotations g.annotation\")\r\n .style(\"visibility\", \"hidden\");\r\n };\r\n }",
"function buildAnnotationPane(annotations){\n var contents = \"\";\n\n //if a single annotation is passed in, put it in an array\n if (!_.isArray(annotations)) {\n annotations = [annotations];\n }\n\n for(var i = 0; i < annotations.length; i++){\n contents += buildAnnotationContents(annotations[i]);\n }\n\n return contents;\n }",
"function publictypechange() {\n var data = google.visualization.arrayToDataTable([\n ['Type', '2005', '2015', {role: 'annotation'}, {role: 'style'}],\n [\"International\", 0, 17.8, \"17.8%\", \"color: black\"],\n [\"Higher Education\", 0, 13.2, \"13.2%\", \"color: black\"],\n [\"Envionment and animals\", 0, 12.8, \"12.8%\", \"color: black\"],\n [\"Religion related\", 0, 8.2, \"8.2%\", \"color: black\"],\n [\"Human Services\", 0, 4.4, \"4.4%\", \"color: black\"],\n [\"All public charities\", 0, 0.6, \"0.6%\", \"color: red\"],\n [\"Hospitals/primary care\", 0, -0.5, \"-0.5%\", \"color: black\"],\n [\"Other public and social benefit\", 0, -2.4, \"-2.4%\", \"color: black\"],\n [\"Education\", 0, -3.3, \"-3.3%\", \"color: black\"],\n [\"Other Education\", 0, -4, \"-4%\", \"color: black\"],\n [\"Health\", 0, -4.9, \"-4.9%\", \"color: black\"],\n [\"Other health care\", 0, -5.9, \"-5.9%\", \"color: black\"],\n [\"Arts\", 0, -9.7, \"-9.7%\", \"color: black\"]\n ]);\n \n var options = {\n title:'Nonprofits Registered with the IRS',\n legend: {position: \"none\"},\n chartArea:{left: 250, right: 0, width:\"100%\",height:\"500px\"},\n annotations: {alwaysOutside: true, stemColor: 'none'},\n backgroundColor: { fill:'transparent' },\n fontName: 'Karla', \n fontSize: '16',\n };\n \n var chart = new google.visualization.LineChart(document.getElementById('six'));\n chart.draw(data, options);\n }",
"function CeventAnnotTypesPanelCtrl($scope,\n $state,\n modalService,\n ceventAnnotTypesService,\n annotationTypeRemoveService,\n annotTypeModalService,\n panelService) {\n var vm = this;\n\n var helper = panelService.panel(\n 'study.panel.participantAnnottionTypes',\n 'admin.studies.study.collection.ceventAnnotTypeAdd',\n annotTypeModalService,\n 'Collection Event Annotation Type');\n\n vm.study = $scope.study;\n vm.annotTypes = $scope.annotTypes;\n vm.annotTypesInUse = $scope.annotTypesInUse;\n vm.update = update;\n vm.remove = remove;\n vm.information = helper.information;\n vm.add = helper.add;\n vm.panelOpen = helper.panelOpen;\n vm.panelToggle = helper.panelToggle;\n\n vm.modificationsAllowed = vm.study.status === 'Disabled';\n\n vm.columns = [\n { title: 'Name', field: 'name', filter: { 'name': 'text' } },\n { title: 'Type', field: 'valueType', filter: { 'valueType': 'text' } },\n { title: 'Description', field: 'description', filter: { 'description': 'text' } }\n ];\n\n vm.tableParams = helper.getTableParams(vm.annotTypes);\n\n //--\n\n function annotTypeInUseModal() {\n var headerHtml = 'Cannot update this annotation type';\n var bodyHtml = 'This annotation type is in use by a collection event type. ' +\n 'If you want to make changes to the annotation type, ' +\n 'it must first be removed from the collection event type(s) that use it.';\n return modalService.modalOk(headerHtml, bodyHtml);\n }\n\n /**\n * Switches state to update a collection event annotation type.\n */\n function update(annotType) {\n if (_.contains(vm.annotTypesInUse, annotType.id)) {\n annotTypeInUseModal();\n } else {\n $state.go(\n 'admin.studies.study.collection.ceventAnnotTypeUpdate',\n { annotTypeId: annotType.id });\n }\n }\n\n function remove(annotType) {\n if (_.contains(vm.annotTypesInUse, annotType.id)) {\n var headerHtml = 'Cannot remove this annotation type';\n var bodyHtml = 'This annotation type is in use by a collection event type. ' +\n 'If you want to remove the annotation type, ' +\n 'it must first be removed from the collection event type(s) that use it.';\n modalService.modalOk(headerHtml, bodyHtml);\n } else {\n annotationTypeRemoveService.remove(\n ceventAnnotTypesService.remove,\n annotType,\n 'admin.studies.study.collection',\n {studyId: annotType.studyId});\n }\n }\n\n }",
"function vjsAnnotation_(options){\n var player = this;\n \n // variables to know if it is ready\n \n player.annotations = new vjsAnnotation(player, options);\n \n // When the DOM, Range Slider and the video media is loaded\n function initialVideoFinished(event) {\n // -- wait for plugins -- //\n var wrapper = $('.annotator-wrapper').parent()[0];\n var annotator = $.data(wrapper, 'annotator');\n \n // wait for Annotator and the Share plugin\n if (typeof Annotator.Plugin[\"Share\"] === 'function') {\n if (typeof annotator.isShareLoaded != 'undefined' && annotator.isShareLoaded) {\n annotator.unsubscribe('shareloaded', initialVideoFinished);\n } else {\n annotator.subscribe('shareloaded', initialVideoFinished);\n return false;\n }\n }\n \n var plugin = player.annotations;\n \n // All components will be initialize after they have been loaded by videojs\n for (var index in plugin.components) {\n plugin.components[index].init_();\n }\n\n player.annotations.BigNewAn.show();\n \n // set the position of the big buttom\n plugin.setposBigNew(plugin.options.posBigNew);\n \n if(!options.showDisplay) \n plugin.hideDisplay();\n if(!options.showStatistics) \n plugin.hideStatistics();\n \n \n // Get current instance of annotator \n player.annotator = annotator;\n plugin.annotator = annotator;\n \n // get annotations\n var allannotations = annotator.plugins['Store'].annotations;\n plugin.refreshDisplay();\n \n // -- Listener to Range Slider Plugin\n player.rangeslider.rstb.on('mousedown', function(){plugin._onMouseDownRS(event)});\n // Open the autoPlay from the API\n if (player.autoPlayAPI) {\n var OnePlay = function () {\n player.annotations.showAnnotation(player.autoPlayAPI);\n $('html, body').animate({\n scrollTop: $(\"#\" + player.id_).offset().top},\n 'slow');\n };\n if (player.techName == 'Youtube')\n setTimeout(OnePlay, 100); // fix the delay playing youtube\n else\n OnePlay();\n }\n \n // set the number of Annotations to display\n plugin.refreshDesignPanel();\n \n // check full-screen change\n player.on('fullscreenchange', function() {\n if (player.isFullScreen) {\n $(player.annotator.wrapper[0]).addClass('vjs-fullscreen');\n } else {\n $(player.annotator.wrapper[0]).removeClass('vjs-fullscreen');\n }\n plugin.refreshDesignPanel();\n });\n \n // loaded plugin\n plugin.loaded = true;\n }\n player.one('loadedRangeSlider', initialVideoFinished); // Loaded RangeSlider\n \n console.log(\"Loaded Annotation Plugin\");\n }",
"function showAnnotationPanel() {\r\n var requestedPosBAndA;\r\n\r\n requestedPosBAndA = realityBuilderCom.controlPanel.requestedPosBAndA();\r\n realityBuilderCom.annotationPanel.prepare(requestedPosBAndA);\r\n realityBuilderCom.controlPanel.disable();\r\n realityBuilderCom.controlPanel.flipOut(function () {\r\n realityBuilderCom.annotationPanel.flipIn(\r\n realityBuilderCom.annotationPanel.enable\r\n );\r\n });\r\n }",
"function StudentGroupPanel(){}",
"function IntersectionTypeAnnotation(node, print) {\n\t print.join(node.types, { separator: \" & \" });\n\t}",
"function H(t,e,n){var a={};t.multiview?a=t:(t&&t.type&&h[t.type]&&w.extend(!0,a,h[t.type]),w.extend(!0,a,t));var o=new Atalasoft.Annotations.Annotation(a,x);return o._pageindex=e,void 0===x.annos[e]&&(x.annos[e]=[]),x.annos[e].push(o),_.redrawPageFromIndex(e,!0),\"function\"==typeof n&&n(o),ut(o),o}",
"function showDescription(annotationNum) {\n const descriptions = document.getElementsByClassName(\"annotation-description\");\n var description = descriptions[annotationNum];\n description.style.display = \"block\";\n}",
"function studyTypeBadge(study) {\n if (study.study_source === 'HCA') {\n // Display a badge indicating this result came from Azul\n return <span className=\"badge badge-secondary study-type\" data-toggle=\"tooltip\"\n title={'Study from Human Cell Atlas'}> Human Cell Atlas </span>\n }\n}",
"function writeAnnotationInfo(styleClass, spannedText, annotType, features)\r\n{\r\n if (!holdInfoFrame)\r\n {\r\n var doc = parent.frames[\"infoFrame\"].document;\r\n\r\n //write the annotation's spanned text, formatted the same way in which it appears in the document view\r\n doc.write('<span class=\"' + styleClass + '\">');\r\n doc.write(spannedText);\r\n doc.write('</span><br>');\r\n\r\n //write CAS type and features\r\n doc.write('CAS Type: ' + annotType + '<br>');\r\n for (i = 0; i < features.length; i++)\r\n {\r\n doc.writeln(features[i][0] + ' = ' + features[i][1] + '<br>'); \r\n }\r\n doc.write('<br>');\r\n doc.write('<br>'); \r\n }\r\n}",
"function publictype() {\n var data = google.visualization.arrayToDataTable([\n ['Type', 'Number', {role: 'annotation'}, {role: 'style'}],\n [\"Human Services\", 110801, \"111K\", \"color: #1696d2\"],\n [\"Education\", 54214, \"54K\", \"color: #1696d2\"],\n [\"Other Education\", 52061, \"52K\", \"color: #1696d2\"],\n [\"Health\", 38861, \"39K\", \"color: #1696d2\"],\n [\"Other public and social benefit\", 37478, \"37K\", \"color: #1696d2\"],\n [\"Other health care\", 31748, \"32K\", \"color: #1696d2\"],\n [\"Arts\", 31429, \"31K\", \"color: #1696d2\"],\n [\"Religion related\", 20443, \"20K\", \"color: #1696d2\"],\n [\"Envionment and animals\", 14591, \"15K\", \"color: #1696d2\"],\n [\"Hospitals/primary care\", 7113, \"7K\", \"color: #1696d2\"],\n [\"International\", 6927, \"7K\", \"color: #1696d2\"],\n [\"Higher Education\", 2153, \"2K\", \"color: #1696d2\"]\n ]);\n \n\nvar options = {\n title:'Nonprofits Registered with the IRS',\n titleTextStyle: {fontSize: 20, color: '#062635'},\n legend: {position: \"none\"},\n chartArea:{left: 250, right: 0, bottom: 75, width:\"100%\",height:\"80%\"},\n vAxis: {minValue: 1000000, maxValue: 1650000, format: \"short\"}, //Set min to 0?\n annotations: {alwaysOutside: true, stemColor: 'none'},\n backgroundColor: { fill:'transparent' },\n fontName: 'Karla', \n fontSize: '16',\n hAxis: {title: \"Number of Organizations in 2015\"}\n };\n \nvar chart = new google.visualization.BarChart(document.getElementById('five'));\nchart.draw(data, options);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is the container that contains both tabs for the login and register | render() {
return (
<Col className="justify-content-center" id="myLoginBox">
<Container id="loginContainer">
<Tabs
defaultActiveKey="Login"
id="UserLoginRegister"
className="justify-content-around"
>
<Tab eventKey="Login" title="Login">
<Login
loginUpdate={this.loginUpdate.bind(this)}
/>
</Tab>
<Tab eventKey="Register" title="Register">
<Register/>
</Tab>
</Tabs>
</Container>
</Col>
)
} | [
"function compare_plan_login() {\n\tvar tabs, tabContent, tabModule;\n\t\n\ttabs = $('#tabGroup > li > a');\n\ttabContent = $('#tabContent');\n\t\n\ttabModule = new tabingModule();\n\ttabModule.init(tabs, tabContent);\n}",
"register() {\n const section = document.querySelector(\"#login-section\");\n HTMLFactory.clearContainer(section);\n section.appendChild(registerForm.buildRegisterForm());\n }",
"constructor(tabs, container) {\n this.tabs = tabs;\n this.container = container;\n\n if (localStorage.getItem('currentTab') >= tabs.config.length) {\n localStorage.setItem('currentTab', 0);\n }\n\n this.buildEditor();\n }",
"function open_aboutlogins_in_tab() {\r\n\t\ttry {\r\n\t\t LoginHelper.openPasswordManager(window, { filterString: gBrowser.currentURI.host, entryPoint: 'mainmenu' });\r\n\t\t} catch (e) {\r\n\t\t LoginHelper.openPasswordManager(window, { entryPoint: 'mainmenu' });\r\n\t\t}\r\n\t }",
"function dispTab( tabId ) {\n //Declare any necessary variables\n var login = document.getElementById( 'login' ), signup = document.getElementById('signup'),\n sForm = document.getElementById( 'sForm' ), lForm = document.getElementById('lForm');\n\n //If the user clicked on \"Log In\" tab\n if ( tabId == 'login' ) {\n //Change the background of \"Sign Up\" tab gray\n signup.style.background = '#eee';\n signup.style.color = \"grey\";\n //Change the background of \"Log In\" tab white\n login.style.background = 'white';\n login.style.color = \"#2B98F0\"\n //Hide the text boxes and buttons for the sign up form\n sForm.style.display = 'none';\n //Display the text boxes and the buttons for the log in form\n lForm.style.display = 'block';\n } else {\n //Change the background of \"Log In\" tab gray\n login.style.background = '#eee';\n login.style.color = \"grey\"\n //Change the background of \"Sign Up\" tab white\n signup.style.background = 'white';\n signup.style.color = \"#2B98F0\";\n //Hide the text boxes and buttons for the log in form\n lForm.style.display = 'none';\n //Display the text boxes and buttons for the sign up form\n sForm.style.display = 'block';\n }\n\n}",
"showLoginForm() {\n manageLoginSignupForm(\"/login\");\n }",
"function enterLogIn() {\r\n\t\tclearPage();\r\n\t\t\r\n\t\taddLogInDiv();\r\n\t\t\r\n\t\taddNewUserDiv();\r\n\t\t\r\n\t}",
"renderTabs() {\n return [\n // Dashboard element\n {\n content: <dashboard.Dashboard\n l={this.l}\n login={this.login}\n handleTabChange={this.handleTabChange}\n authenticated={this.state.authenticated}\n currentUser={this.state.currentUser}\n key='dashboard' />,\n tab: <Ons.Tab\n label={this.l('tabs.dashboard')}\n icon='md-info'\n key='dashboard'\n style={{display: 'none'}} />\n },\n // Map element\n {\n content: <map.Map\n l={this.l}\n logging={this.state.logging}\n externalData={this.state.externalData}\n layerControl={this.state.layerControl}\n draggable={this.state.draggable}\n zoomable={this.state.zoomable}\n currentUser={this.state.currentUser}\n centerPosition={this.state.centerPosition}\n selectedUserId={this.state.selectedUserId}\n calculateDistanceTo={this.calculateDistanceTo}\n users={this.state.users}\n key='map' />,\n tab: <Ons.Tab\n label={this.l('tabs.map')}\n icon='md-map'\n key='map' />\n },\n // List element\n {\n content: <list.List\n l={this.l}\n logging={this.state.logging}\n externalData={this.state.externalData}\n layerControl={this.state.layerControl}\n draggable={this.state.draggable}\n zoomable={this.state.zoomable}\n currentUser={this.state.currentUser}\n centerPosition={this.state.centerPosition}\n selectedUserId={this.state.selectedUserId}\n onListItemClick={this.handleListItemClick}\n usersAreLoaded={this.state.usersAreLoaded}\n errorLoadingUsers={this.state.errorLoadingUsers}\n users={this.state.users}\n key='list' />,\n tab: <Ons.Tab\n label={this.l('tabs.list')}\n icon='md-view-list'\n key='list' />\n },\n // Settings element, with no tab displayed in the tab bar, as it is accessible via the sidebar\n {\n content: <settings.Settings\n l={this.l}\n onLoggingChange={this.handleLoggingChange}\n onDataChange={this.handleExternalDataChange}\n onLayerControlChange={this.handleLayerControlChange}\n onDragMapChange={this.handleDragMapChange}\n onZoomMapChange={this.handleZoomMapChange}\n pushUserUpdate={this.pushUserUpdate}\n currentUser={this.state.currentUser}\n authenticated={this.state.authenticated}\n logout={this.logout}\n login={this.login}\n logging={this.state.logging}\n externalData={this.state.externalData}\n layerControl={this.state.layerControl}\n draggable={this.state.draggable}\n zoomable={this.state.zoomable}\n key='settings' />,\n tab: <Ons.Tab\n label={this.l('tabs.settings')}\n icon='md-settings'\n key='settings'\n style={{display: 'none'}} />\n },\n // Offer form element, with no tab displayed in the tab bar, as it is accessible via the sidebar\n {\n content: <offerForm.offerForm\n l={this.l}\n pushUserUpdate={this.pushUserUpdate}\n currentUserIsLoaded={this.state.currentUserIsLoaded}\n currentUser={this.state.currentUser}\n outOfGeofence={this.state.outOfGeofence}\n key='offerForm' />,\n tab: <Ons.Tab\n label={this.l('tabs.offers')}\n icon='md-edit'\n key='offerForm'\n style={{display: 'none'}} />\n },\n // Help page iframe\n {\n content: <embededSite.EmbededComponent site='help.html' key='help' name='Help' />,\n tab: <Ons.Tab\n label={this.l('tabs.help')}\n icon='md-help'\n key='help'\n style={{display: 'none'}} />\n },\n // Ship around an error in current onsen release\n // Can be solved with an update of onsen/onsen react --> issue: https://github.com/OnsenUI/OnsenUI/issues/2307\n {\n content: <div key='placeholder' />,\n tab: null\n }\n ]\n }",
"function TabsPage() {\n this.tab1Root = __WEBPACK_IMPORTED_MODULE_1__home_home__[\"a\" /* HomePage */];\n this.tab2Root = __WEBPACK_IMPORTED_MODULE_2__login_login__[\"a\" /* LoginPage */];\n this.tab3Root = __WEBPACK_IMPORTED_MODULE_3__register_register__[\"a\" /* RegisterPage */];\n this.tab4Root = __WEBPACK_IMPORTED_MODULE_4__findpassword_findpassword__[\"a\" /* FindpasswordPage */];\n // this.nav.setRoot(TabsPage);\n // this.tabRef.select(2);\n }",
"function wrapTabs(container) {\r\n\t\tvar tabs = $.data(container, 'tabs').tabs;\r\n\t\tvar cc = $(container).addClass('tabs-container');\r\n\t\tvar panels = $('<div class=\"tabs-panels\"></div>').insertBefore(cc);\r\n\t\tcc.children('div').each(function(){\r\n\t\t\tpanels[0].appendChild(this);\r\n\t\t});\r\n\t\tcc[0].appendChild(panels[0]);\r\n\t\t$('<div class=\"tabs-header\">'\r\n\t\t\t\t+ '<div class=\"tabs-scroller-left\"></div>'\r\n\t\t\t\t+ '<div class=\"tabs-scroller-right\"></div>'\r\n\t\t\t\t+ '<div class=\"tabs-wrap\">'\r\n\t\t\t\t+ '<ul class=\"tabs\"></ul>'\r\n\t\t\t\t+ '</div>'\r\n\t\t\t\t+ '</div>').prependTo(container);\r\n\t\t\r\n\t\tcc.children('div.tabs-panels').children('div').each(function(i){\r\n\t\t\tvar opts = $.extend({}, $.parser.parseOptions(this), {\r\n\t\t\t\tdisabled: ($(this).attr('disabled') ? true : undefined),\r\n\t\t\t\tselected: ($(this).attr('selected') ? true : undefined)\r\n\t\t\t});\r\n\t\t\tcreateTab(container, opts, $(this));\r\n\t\t});\r\n\t\t\r\n\t\tcc.children('div.tabs-header').find('.tabs-scroller-left, .tabs-scroller-right').hover(\r\n\t\t\t\tfunction(){$(this).addClass('tabs-scroller-over');},\r\n\t\t\t\tfunction(){$(this).removeClass('tabs-scroller-over');}\r\n\t\t);\r\n\t\tcc.bind('_resize', function(e,force){\r\n\t\t\tif ($(this).hasClass('easyui-fluid') || force){\r\n\t\t\t\tsetSize(container);\r\n\t\t\t\tsetSelectedSize(container);\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t});\r\n\t}",
"function setupLoginUI() {\n $(`#login-submit-button`).on(`click`, login);\n $(`#login-new-user-button`).on(`click`, newUser);\n}",
"function createTab() {\n let user = {\n 'name': $('#user-name').val(),\n 'login': $('#user-login').val(),\n 'uuid': new Date().getTime()\n }\n states.tabsList.unshift(user); // append newly created tab to \"tabsList\"\n renderTab(user);\n\n // reset \"Add transaction\" fields\n $('#user-name').val('');\n $('#user-login').val('');\n}",
"function wrapTabs(container) {\r\n\t\tvar tabs = $.data(container, 'tabs').tabs;\r\n\t\tvar cc = $(container);\r\n\t\tcc.addClass('tabs-container');\r\n\t\tvar pp = $('<div class=\"tabs-panels\"></div>').insertBefore(cc);\r\n\t\tcc.children('div').each(function(){\r\n\t\t\tpp[0].appendChild(this);\r\n\t\t});\r\n\t\tcc[0].appendChild(pp[0]);\r\n//\t\tcc.wrapInner('<div class=\"tabs-panels\"/>');\r\n\t\t$('<div class=\"tabs-header\">'\r\n\t\t\t\t+ '<div class=\"tabs-scroller-left\"></div>'\r\n\t\t\t\t+ '<div class=\"tabs-scroller-right\"></div>'\r\n\t\t\t\t+ '<div class=\"tabs-wrap\">'\r\n\t\t\t\t+ '<ul class=\"tabs\"></ul>'\r\n\t\t\t\t+ '</div>'\r\n\t\t\t\t+ '</div>').prependTo(container);\r\n\t\t\r\n\t\tcc.children('div.tabs-panels').children('div').each(function(i){\r\n\t\t\tvar opts = $.extend({}, $.parser.parseOptions(this), {\r\n\t\t\t\tselected: ($(this).attr('selected') ? true : undefined)\r\n\t\t\t});\r\n\t\t\tvar pp = $(this);\r\n\t\t\ttabs.push(pp);\r\n\t\t\tcreateTab(container, pp, opts);\r\n\t\t});\r\n\t\t\r\n\t\tcc.children('div.tabs-header').find('.tabs-scroller-left, .tabs-scroller-right').hover(\r\n\t\t\t\tfunction(){$(this).addClass('tabs-scroller-over');},\r\n\t\t\t\tfunction(){$(this).removeClass('tabs-scroller-over');}\r\n\t\t);\r\n\t\tcc.bind('_resize', function(e,force){\r\n\t\t\tif ($(this).hasClass('easyui-fluid') || force){\r\n\t\t\t\tsetSize(container);\r\n\t\t\t\tsetSelectedSize(container);\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t});\r\n\t}",
"function loginTab() {\n document.querySelector(\"#login-tab\").classList.remove(\"active\");\n document.querySelector(\".modal-login\").style.borderTop = \"#087DD2 4px solid\";\n document.querySelector(\".signup-content\").style.display = \"none\";\n document.querySelector(\".modal-content\").style.height = \"60rem\";\n document.querySelector(\"#signup-tab\").classList.add(\"active\");\n document.querySelector(\".modal-signup\").style.borderTop = \"none\";\n document.querySelector(\".login-content\").style.display = \"block\";\n}",
"get loginTab() {return browser.element(\"~Go to Log in\");}",
"function loginTab() {\n document.querySelector('#login-tab').classList.remove(\"active\");\n document.querySelector('.modal-login').style.borderTop = \"#2EBD71 4px solid\";\n document.querySelector('.signup-content').style.display = \"none\";\n document.querySelector('.modal-content').style.height = \"76%\";\n document.querySelector('#signup-tab').classList.add(\"active\");\n document.querySelector('.modal-signup').style.borderTop = \"none\"\n document.querySelector('.login-content').style.display = \"block\";\n}",
"function createTab(){\n let user = {\n 'name': $('#user-name').val(),\n 'login': $('#user-login').val()\n }\n states.tabsList.push(user); // append newly created tab to \"tabsList\"\n renderTab(user);\n\n // reset \"Add transaction\" fields\n $('#user-name').val('');\n $('#user-login').val('');\n}",
"function addAllPlacehoderFormLogin() {\n\taddPlaceholder(\"username\", TEXT_USERNAME_LOGIN);\n\taddPlaceholder(\"password\", TEXT_GENERAL_PASSWORD);\n}",
"function startUp() {\n //Hide all pages except for Login Page, which is the start page.\n\n // First, hide all padded pages\n setHide([...document.getElementsByClassName(\"paddedPage\")])\n\n // Then, display login screen \n itemBlock(document.getElementById(\"loginModeDiv\"))\n\n // Make sure correct menu button icon is displayed\n itemBlock(document.getElementById(\"menuBtn\"))\n itemHide(document.getElementById(\"menuBtnAlt\"))\n\n\n //Clear all text from email and password fields\n setClearText([...document.getElementsByClassName(\"login-input\")])\n\n //Set top bar text\n itemBlock(document.getElementById(\"topBarTitleWelcome\"))\n itemHide(document.getElementById(\"topBarTitleData\"))\n\n //Hide the bottom bar initially\n itemHide(document.getElementById(\"bottomBar\"))\n\n //Hide all menu items except for items of current mode:\n setHide([...document.getElementsByClassName(\"dataMenuItem\")])\n\n //Disable menu button:\n toggleEnable(document.getElementById(\"menuBtn\"))\n\n //Set current mode\n mode = \"loginMode\"\n\n //set the input focus to the email field\n itemFocus(document.getElementById(\"emailInput\"))\n\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when the user clicks on a waypoint search result, it is used as waypoint. The search results vanish and only the selected address is shown. | function handleSearchWaypointResultClick(e) {
var rootElement = $(e.currentTarget).parent().parent().parent().parent();
var index = rootElement.attr('id');
rootElement.removeClass('unset');
rootElement = rootElement.get(0);
rootElement.querySelector('.searchAgainButton').show();
rootElement.querySelector('.guiComponent').hide();
var waypointResultElement = rootElement.querySelector('.waypointResult');
//remove older entries:
while (waypointResultElement.firstChild) {
waypointResultElement.removeChild(waypointResultElement.firstChild);
}
waypointResultElement.insert(e.currentTarget);
waypointResultElement.show();
//remove search markers and add a new waypoint marker
theInterface.emit('ui:waypointResultClick', {
wpIndex : index,
featureId : e.currentTarget.id,
searchIds : rootElement.getAttribute('data-search')
});
} | [
"function handleWaypointResultClick(atts) {\n\t\t\tvar wpIndex = atts.wpIndex;\n\t\t\tvar featureId = atts.featureId;\n\t\t\tvar searchIds = atts.searchIds;\n\t\t\tif (searchIds) {\n\t\t\t\tsearchIds = searchIds.split(' ');\n\t\t\t}\n\n\t\t\tvar type = selectWaypointType(wpIndex);\n\t\t\tvar waypointResultId = map.addWaypointMarker(wpIndex, featureId, type);\n\t\t\tmap.clearMarkers(map.SEARCH, searchIds);\n\n\t\t\twaypoint.setWaypoint(wpIndex, true);\n\n\t\t\thandleRoutePresent();\n\n\t\t\tvar position = map.convertFeatureIdToPositionString(waypointResultId, map.ROUTE_POINTS);\n\t\t\tui.setWaypointFeatureId(wpIndex, waypointResultId, position, map.ROUTE_POINTS);\n\n\t\t\t//update preferences\n\t\t\thandleWaypointChanged(map.getWaypointsString());\n\t\t}",
"function handleSearchAgainWaypointClick(e) {\n\t\t\tvar wpElement = $(e.currentTarget).parent();\n\t\t\tvar index = wpElement.attr('id');\n\n\t\t\tvar addrElement = wpElement.get(0).querySelector('.address');\n\t\t\tvar featureId = addrElement.getAttribute('id');\n\t\t\tvar layer = addrElement.getAttribute('data-layer');\n\n\t\t\tvar resultComponent = wpElement.get(0).querySelector('.waypointResult');\n\t\t\t$(resultComponent).hide();\n\n\t\t\tvar searchComponent = wpElement.get(0).querySelector('.guiComponent');\n\t\t\t$(searchComponent).show();\n\n\t\t\tvar searchResults = wpElement.attr('data-search');\n\t\t\tif (searchResults) {\n\t\t\t\t//this waypoint was created by a search input. Only then it is useful to view previous search results\n\t\t\t\t//therefore we have to re-calculate the search\n\n\t\t\t\t//index of the waypoint (0st, 1st 2nd,...)\n\n\t\t\t\tvar input = wpElement.attr('data-searchInput');\n\t\t\t\t//empty search results\n\t\t\t\tinvalidateWaypointSearch(index);\n\t\t\t\tvar resultContainer = wpElement.get(0).querySelector('.searchWaypointResults');\n\t\t\t\twhile (resultContainer && resultContainer.hasChildNodes()) {\n\t\t\t\t\tresultContainer.removeChild(resultContainer.lastChild);\n\t\t\t\t}\n\t\t\t\t//request new results\n\t\t\t\ttheInterface.emit('ui:searchWaypointRequest', {\n\t\t\t\t\tquery : input,\n\t\t\t\t\twpIndex : index,\n\t\t\t\t\tsearchIds : null\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\tresultComponent.removeChild(addrElement);\n\t\t\t\tvar responses = searchComponent.querySelector('.responseContainer');\n\t\t\t\tif (responses) {\n\t\t\t\t\t$(responses).hide();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//remove old waypoint marker\n\t\t\ttheInterface.emit('ui:searchAgainWaypoint', {\n\t\t\t\twaypointFeature : featureId,\n\t\t\t\twaypointLayer : layer,\n\t\t\t\twpIndex : index\n\t\t\t});\n\t\t}",
"function selectSearchResult() {\n //move to position\n setupMapCenter($(this).data('coords'));\n //fill the search box\n fillSearchBox($(this).data('address'));\n //save user choice to hidden values\n storeNewAddress($(this).data('address'), $(this).data('coords'), yMap.getZoom());\n }",
"function handleSearchAgainWaypoint(atts) {\n\t\t\tvar waypointFeature = atts.waypointFeature;\n\t\t\tvar waypointLayer = atts.waypointLayer;\n\t\t\tvar wpIndex = atts.wpIndex;\n\n\t\t\t//remove the waypoint marker\n\t\t\tmap.clearMarkers(waypointLayer, [waypointFeature]);\n\n\t\t\t//to re-view the search results of the waypoint search, the whole thing is re-calculated using existant functions\n\n\t\t\t//waypoint-internal\n\t\t\twaypoint.setWaypoint(wpIndex, false);\n\n\t\t\t//update preferences\n\t\t\thandleWaypointChanged(map.getWaypointsString());\n\t\t}",
"function geolocaterSwitch() {\n if (gui.cast.search.hasAttribute('hidden')) {\n gui.cast.sel.setAttribute('hidden',true);\n gui.cast.search.removeAttribute('hidden');\n gui.cmds.switch.setAttribute('type','go'); \n\n gui.edit.name.value = '';\n } else { \n gui.cast.search.setAttribute('hidden',true);\n gui.cast.sel.removeAttribute('hidden');\n gui.cmds.switch.setAttribute('type','back'); \n geolocaterCleanAddress('edit');\n\n var editFrame = gui.frames.edit.contentWindow.wrappedJSObject;\n var center = editFrame.centers.features[0];\n var position = editFrame.getPosition();\n\n var address = gui.addrs.edit;\n\n if (gui.search.responseData != null) {\n var sw = gui.search.responseData.viewport.sw;\n var ne = gui.search.responseData.viewport.ne;\n if (position.latitude < sw.lat ||\n position.latitude > ne.lat ||\n position.longitude < sw.lng ||\n position.longitude > ne.lng)\n gui.search.responseData = null;\n }\n\n if (gui.search.responseData != null) {\n var result = gui.search.responseData.results[0];\n gui.edit.name.value = result.titleNoFormatting;\n address.city = result.city;\n address.region = result.region;\n address.postalCode = result.postalCode || '';\n if (result.country.length == 2)\n address.countryCode = result.country;\n\n var streetAddress = result.streetAddress.split(', ');\n var streetInfo = streetAddress[1] || '';\n streetAddress = streetAddress[0];\n streetAddress = streetAddress.replace(result.postalCode,'');\n streetAddress = streetAddress.replace(result.city,'');\n if (result.accuracy == 6) {\n address.street = streetAddress;\n }\n if (result.accuracy == 8) {\n streetAddress = streetAddress.split(' ');\n if (!isNaN(streetAddress[0][0])) {\n address.streetNumber = streetAddress[0];\n streetAddress.shift();\n } else if (!isNaN(streetAddress[streetAddress.length-1][0])){\n address.streetNumber = streetAddress[streetAddress.length-1];\n streetAddress.pop();\n }\n address.street = streetAddress.join(' ');\n }\n\n if (streetInfo.length != 0) {\n streetInfo = streetInfo.split(' ');\n if (!isNaN(streetInfo[0]))\n address.postalCode = streetInfo[0];\n }\n }\n\n var q = position.latitude+','+position.longitude;\n var url = 'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=';\n url += q;\n\n var xhr = CL[\"@mozilla.org/xmlextras/xmlhttprequest;1\"]\n .createInstance(CI.nsIXMLHttpRequest);\n xhr.mozBackgroundRequest = true;\n xhr.open(\"GET\", url, true);\n xhr.onerror = function(req) {\n alert('Error');\n };\n xhr.onload = function(req) {\n var resp = JSON.parse(req.target.responseText);\n\n if (!resp.responseData.results[0]) {\n alert(gui.stringBundle.getString('alert_no_address_found'));\n return false;\n }\n var result = resp.responseData.results[0];\n\n if (gui.edit.name.value == '')\n gui.edit.name.value = result.titleNoFormatting;\n\n if (address.city == '')\n address.city = result.city;\n if (address.region == '')\n address.region = result.region;\n if (address.postalCode == '')\n address.postalCode = result.postalCode || '';\n if (result.country.length == 2)\n address.countryCode = result.country;\n\n var streetAddress = result.streetAddress.split(', ');\n var streetInfo = streetAddress[1] || '';\n streetAddress = streetAddress[0];\n streetAddress = streetAddress.replace(result.postalCode,'');\n streetAddress = streetAddress.replace(result.city,'');\n streetAddress = streetAddress.split(' ');\n var streetNumber = ''\n if (!isNaN(streetAddress[0][0])) {\n streetNumber = streetAddress[0];\n streetAddress.shift();\n } else if (!isNaN(streetAddress[streetAddress.length-1][0])){\n streetNumber = streetAddress[streetAddress.length-1];\n streetAddress.pop();\n }\n if (address.street == '')\n address.street = streetAddress.join(' ');\n\n var accuracy = center.attributes.accuracy;\n if (accuracy < 1001 && address.streetNumber == '')\n address.streetNumber = streetNumber;\n\n if (streetInfo.length != 0) {\n streetInfo = streetInfo.split(' ');\n if (!isNaN(streetInfo[0]) && address.postalCode == '')\n address.postalCode = streetInfo[0];\n }\n gui.edit.acc.value = accuracy;\n guiController.onCommandUpdate();\n return true;\n };\n xhr.send(null);\n }\n guiController.onCommandUpdate();\n}",
"function goToSuggestion() {\n\t \t var location = new google.maps.LatLng(this.dataset.lat, this.dataset.long);\n\t\t\t map.panTo(location);\n\t\t\t geoResults.innerHTML = \"<span class='results-header'>Results: <div class='toggle-results'>-</div></span><div data-lat='\" + this.dataset.lat + \"' data-long='\" + this.dataset.long + \"' class='results'>\" + this.innerHTML + \"</div>\";\n\t\t var marker = new google.maps.Marker({\n\t\t map: map,\n\t\t position: location,\n\t\t icon: iconPath,\n\t\t zoom: 3\n\t\t });\n\t }",
"function handleSearchWaypointInput(e) {\n\t\t\tvar waypointElement = $(e.currentTarget).parent().parent();\n\n\t\t\t//index of the waypoint (0st, 1st 2nd,...)\n\t\t\tvar index = waypointElement.attr('id');\n\n\t\t\tclearTimeout(typingTimerWaypoints[index]);\n\t\t\tif (e.keyIdentifier != 'Shift' && e.currentTarget.value.length != 0) {\n\t\t\t\tvar input = e.currentTarget.value;\n\t\t\t\twaypointElement.attr('data-searchInput', input);\n\t\t\t\ttypingTimerWaypoints[index] = setTimeout(function() {\n\t\t\t\t\t//empty search results\n\t\t\t\t\tvar resultContainer = waypointElement.get(0).querySelector('.searchWaypointResults');\n\t\t\t\t\twhile (resultContainer && resultContainer.hasChildNodes()) {\n\t\t\t\t\t\tresultContainer.removeChild(resultContainer.lastChild);\n\t\t\t\t\t}\n\t\t\t\t\t//request new results\n\t\t\t\t\ttheInterface.emit('ui:searchWaypointRequest', {\n\t\t\t\t\t\tquery : input,\n\t\t\t\t\t\twpIndex : index,\n\t\t\t\t\t\tsearchIds : waypointElement.get(0).getAttribute('data-search')\n\t\t\t\t\t});\n\t\t\t\t}, DONE_TYPING_INTERVAL);\n\t\t\t}\n\t\t}",
"function showAddressSearchBox(){ \n\tvar place = autocomplete.getPlace();\n\tvar point = place.geometry.location;\n\t\n\tnewRideInfo = {};\n\tnewRideInfo.lat = point.lat();\n\tnewRideInfo.lng = point.lng();\n\tnewRideInfo.address = place.formatted_address;\n\tbeginRideCreationPopup(); \n}",
"function searchApartment() {\n // opzioni per ricerca\n var searchOptions = {\n key: 'LXS830AiWeCA3ogV5iiftuD8GgwteTOE',\n language: 'it-IT',\n limit: 5\n };\n // opzione autocomplete\n var autocompleteOptions = {\n key: 'LXS830AiWeCA3ogV5iiftuD8GgwteTOE',\n language: 'it-IT'\n };\n var searchBoxOptions = {\n minNumberOfCharacters: 0,\n searchOptions: searchOptions,\n autocompleteOptions: autocompleteOptions\n };\n\n var ttSearchBox = new tt.plugins.SearchBox(tt.services, searchBoxOptions);\n var searchBoxHTML = ttSearchBox.getSearchBoxHTML();\n $('.search-app').append(searchBoxHTML);\n\n //invio risultati form-homepage\n $('input').on('keydown', function (e) {\n var key = (e.keyCode || e.which);\n if (key == 13 || key == 3) {\n $('.form-search').submit();\n }\n });\n\n $(\".home-form form .inner-form .input-field .search-app svg\").click(function () {\n $('.form-search').submit();\n });\n\n\n\n\n\n // prendo il risultato selezionato salvo i dati di lat e lon\n ttSearchBox.on('tomtom.searchbox.resultselected', function (data) {\n var position = data['data']['result']['position'];\n console.log(position);\n var latitudine = position['lat'];\n var longitudine = position['lng'];\n console.log(latitudine, longitudine);\n $(\".lat\").val(latitudine);\n $(\".lon\").val(longitudine);\n });\n}",
"function OnLocalSearch() {\r\n if (!gLocalSearch.results) return;\r\n //var searchWell = document.getElementById(\"searchwell\");\r\n\r\n // Clear the map and the old search well\r\n //searchWell.innerHTML = \"\";\r\n for (var i = 0; i < gCurrentResults.length; i++) {\r\n gCurrentResults[i].marker().setMap(null);\r\n }\r\n // Close the infowindow\r\n gInfoWindow.close();\r\n\r\n gCurrentResults = [];\r\n for (var i = 0; i < gLocalSearch.results.length; i++) {\r\n gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));\r\n }\r\n\r\n /*var attribution = gLocalSearch.getAttribution();\r\n if (attribution) {\r\n document.getElementById(\"searchwell\").appendChild(attribution);\r\n }*/\r\n\r\n // Move the map to the first result\r\n if (gLocalSearch.results.length > 0) {\r\n var first = gLocalSearch.results[0];\r\n gMap.setCenter(new google.maps.LatLng(parseFloat(first.lat), parseFloat(first.lng)));\r\n }\r\n }",
"function onLocalSearch(searchTerm) {\n var {results} = gLocalSearch;\n if ((results || \"\").length === 0) {\n $(\"#mapArea\").hide();\n $(\"#msg\").html('<div>No results for \"' + searchTerm + '\\\"</div>');\n return;\n }\n $(\"#mapArea\").show();\n $(\"#msg\").html(\"\");\n\n $(\"#address-list\").empty();\n var searchWell = document.getElementById(\"address-list\");\n\n gCurrentResults = [];\n var numToDisplay = Math.min(3, results.length);\n for (var i = 0; i < numToDisplay; i++) {\n gCurrentResults.push(new LocalResult(results[i]));\n }\n\n // move the map to the first result\n var first = results[0];\n var point = new google.maps.LatLng(first.lat, first.lng);\n\n setMarker(point, 0);\n}",
"function placesCallback(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n destination_LatLng = results[0].geometry.location;\n \n var coffee_request = {\n location: destination_LatLng,\n keyword: \"coffee\",\n types: [\"restaurant\", \"cafe\", \"meal_takeaway\"],\n rankBy: google.maps.places.RankBy.DISTANCE\n };\n\n var donut_request = {\n location: destination_LatLng,\n keyword: \"donuts\",\n types: [\"restaurant\", \"cafe\", \"meal_takeaway\"],\n rankBy: google.maps.places.RankBy.DISTANCE\n };\n\n var service = new google.maps.places.PlacesService(document.getElementById(\"attributionsPanel\"));\n service.nearbySearch(coffee_request, coffee_callback);\n service.nearbySearch(donut_request, donut_callback);\n\n var hidden_elements = document.getElementsByClassName(\"hidden_on_load\");\n if (hidden_elements.length > 0) {\n for (var i = 0; i < hidden_elements.length; i++) {\n hidden_elements[i].style.visibility = \"visible\";\n }\n }\n } else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {\n alert(\"Bad destination address.\");\n } else {\n alert(\"Error calling Google Geocode API.\");\n } \n}",
"function showDirections(place) {\n index = this.dataset.index;\n google.maps.event.trigger(searchResults[index], 'click');\n }",
"function findRouteClicked() {\n\t\t// Validate\n\t\tvar cancel = false;\n\t\t$.each(['start', 'finish'], function(sfIndex, sfValue) {\n\t\t\tif ($('#' + sfValue + 'Input').val() === '') {\n\t\t\t\tcancel = true;\t\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\tif (cancel) {\n\t\t\tshowAlert(messageFillBoth, 'alert');\t\t\t\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tclearAlerts();\n\t\tclearRoutingResultsOnTable();\n\t\tshowAlert(messagePleaseWait, 'secondary');\n\t\t\n\t\tvar completedLatLon = 0;\n\t\t$.each(['start', 'finish'], function(sfIndex, sfValue) {\n\t\t\tvar placeInput = $('#' + sfValue + 'Input');\n\t\t\tvar placeSelect = $('#' + sfValue + 'Select');\n\t\t\tif (isLatLng(placeInput.val())) {\n\t\t\t\tcoordinates[sfValue] = placeInput.val();\n\t\t\t\tcompletedLatLon++;\n\t\t\t} else {\n\t\t\t\tif (coordinates[sfValue] == null) {\n\t\t\t\t\t// Coordinates not yet ready, we do a search place\n\t\t\t\t\tprotocol.searchPlace(\n\t\t\t\t\t\t\tplaceInput.val(),\n\t\t\t\t\t\t\tregion,\n\t\t\t\t\t\t\tfunction(result) {\n\t\t\t\t\t\t\t\tplaceSelect.empty();\n\t\t\t\t\t\t\t\tplaceSelect.addClass('hidden');\n\t\t\t\t\t\t\t\tif (result.status != 'error') {\n\t\t\t\t\t\t\t\t\tif (result.searchresult.length > 0) {\n\t\t\t\t\t\t\t\t\t\t$.each(result.searchresult, function(index, value) {\n\t\t\t\t\t\t\t\t\t\t\tvar placeSelect = $('#' + sfValue + 'Select');\n\t\t\t\t\t\t\t\t\t\t\tplaceSelect\n\t\t\t\t\t\t\t\t\t\t .append($('<option></option>')\n\t\t\t\t\t\t\t\t\t\t .attr('value',value['location'])\n\t\t\t\t\t\t\t\t\t\t .text(value['placename']));\n\t\t\t\t\t\t\t\t\t\t\tplaceSelect.removeClass('hidden');\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tcoordinates[sfValue] = result.searchresult[0]['location'];\n\t\t\t\t\t\t\t\t\t\tcheckCoordinatesThenRoute(coordinates);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tclearSecondaryAlerts();\n\t\t\t\t\t\t\t\t\t\tclearRoutingResultsOnMap();\n\t\t\t\t\t\t\t\t\t\tshowAlert(placeInput.val() + messageNotFound, 'alert');\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tclearSecondaryAlerts();\n\t\t\t\t\t\t\t\t\tclearRoutingResultsOnMap();\n\t\t\t\t\t\t\t\t\tshowAlert(messageConnectionError, 'alert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Coordinates are already available, skip searching\n\t\t\t\t\tcheckCoordinatesThenRoute(coordinates);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tif (completedLatLon == 2) {\n\t\t\tcheckCoordinatesThenRoute(coordinates);\n\t\t}\n\t}",
"function showAddWaypointUI(currentlyAddingWaypointIndex) {\n \n var autocomplete = null;\n var currentWaypoint = null;\n \n var input = document.getElementById('input_waypoint');\n input.value = \"\";\n \n var input_notes = document.getElementById('input_notes');\n input_notes.value = \"\";\n\n var select_mode = document.getElementById('select_mode');\n\n var input_photo = document.getElementById('input_photo');\n input_photo.value = \"\";\n\n var addUI = document.getElementById('div_addWaypoint');\n addUI.style.display = \"inline-block\";\n\n // Create the autocomplete object, restricting the search to geographical\n // location types.\n \n // set the bounds of the autocomplete to the entire world\n // TODO might want to set this to something else ?\n var defaultBounds = new google.maps.LatLngBounds(\n new google.maps.LatLng(-90, -180),\n new google.maps.LatLng(90, 180));\n \n autocomplete = new google.maps.places.Autocomplete(input),\n {\n bounds: defaultBounds,\n types: ['geocode']\n };\n \n autocomplete.addListener('place_changed', function() {\n var place = autocomplete.getPlace(); \n if (!place.geometry) {\n alert(\"Could not find the location, please try again!\");\n return;\n }\n \n // set the current waypoint to what we found \n currentWaypoint = {\n Id : guid(),\n Name : input.value,\n Notes : input_notes.value,\n Place : place,\n Marker : null\n }; \n }); \n\n var input_waypoint_ok = document.getElementById('input_waypoint_ok');\n \n // user clicks Ok so we need to add the waypoint to the array, to the table and show it on the map\n input_waypoint_ok.onclick = function clicked(e) {\n \n if (!currentWaypoint.Place) {\n alert(\"Could not find the location, please try again!\");\n return;\n }\n \n var addUI = document.getElementById('div_addWaypoint');\n addUI.style.display = \"none\"; \n \n // If the place has a geometry, then present it on a map.\n if (currentWaypoint.Place.geometry.viewport) {\n map.fitBounds(currentWaypoint.Place.geometry.viewport);\n } else {\n map.setCenter(currentWaypoint.Place.geometry.location);\n // TODO We may need to change the zoom, depending on what the user is searching for (cities, specific addresses ?)\n map.setZoom(4);\n }\n \n var marker = new google.maps.Marker({\n map: map,\n position: currentWaypoint.Place.geometry.location,\n // this will bounce the marker until we set setAnimation(null) animation: google.maps.Animation.BOUNCE,\n // this shows a text inside the marker, but it can only be one character label: '1',\n // this shows a longer text when the user clicks on the marker title: 'Bucharest'\n });\n \n currentWaypoint.Marker = marker;\n currentWaypoint.Notes = input_notes.value;\n \n currentlyAddingWaypointIndex += 1;\n\n currentWaypoint.Mode = select_mode.value;\n currentWaypoint.Photo = input_photo.value;\n\n // set the polygon that is the route between the last waypoint and the one we are adding\n if (currentlyAddingWaypointIndex > 0) {\n\n getPoly(waypoints[currentlyAddingWaypointIndex - 1], currentWaypoint,\n function(poly) {\n currentWaypoint.Poly = poly;\n });\n }\n\n addWaypointToList(currentlyAddingWaypointIndex, currentWaypoint)\n \n };\n \n }",
"function findRouteClicked() {\n\t\t// Validate\n\t\tvar cancel = false;\n\t\t$.each(['start', 'finish'], function(sfIndex, sfValue) {\n\t\t\tif ($('#' + sfValue + 'Input').val() === '') {\n\t\t\t\tclearSecondaryAlerts();\n\t\t\t\tshowAlert(messageFillBoth, 'alert');\n\t\t\t\tcancel = true;\t\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\tif (cancel) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tclearAlerts();\n\t\tclearRoutingResultsOnTable();\n\t\tshowAlert(messagePleaseWait, 'secondary');\n\t\t$.each(['start', 'finish'], function(sfIndex, sfValue) {\n\t\t\tvar placeInput = $('#' + sfValue + 'Input');\n\t\t\tvar placeSelect = $('#' + sfValue + 'Select');\n\t\t\tif (isLatLng(placeInput.val())) {\n\t\t\t\tcoordinates[sfValue] = placeInput.val();\n\t\t\t\tcheckCoordinatesThenRoute(coordinates);\n\t\t\t} else {\n\t\t\t\tif (coordinates[sfValue] == null) {\n\t\t\t\t\t// Coordinates not yet ready, we do a search place\n\t\t\t\t\tprotocol.searchPlace(\n\t\t\t\t\t\t\tplaceInput.val(),\n\t\t\t\t\t\t\tregion,\n\t\t\t\t\t\t\tfunction(result) {\n\t\t\t\t\t\t\t\tplaceSelect.empty();\n\t\t\t\t\t\t\t\tplaceSelect.addClass('hidden');\n\t\t\t\t\t\t\t\tif (result.searchresult.length > 0) {\n\t\t\t\t\t\t\t\t\t$.each(result.searchresult, function(index, value) {\n\t\t\t\t\t\t\t\t\t\tvar placeSelect = $('#' + sfValue + 'Select');\n\t\t\t\t\t\t\t\t\t\tplaceSelect\n\t\t\t\t\t\t\t\t\t .append($('<option></option>')\n\t\t\t\t\t\t\t\t\t .attr('value',value['location'])\n\t\t\t\t\t\t\t\t\t .text(value['placename']));\n\t\t\t\t\t\t\t\t\t\tplaceSelect.removeClass('hidden');\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcoordinates[sfValue] = result.searchresult[0]['location'];\n\t\t\t\t\t\t\t\t\tcheckCoordinatesThenRoute(coordinates);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tclearSecondaryAlerts();\n\t\t\t\t\t\t\t\t\tshowAlert(placeInput.val() + messageNotFound, 'alert');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\t// Coordinates is already available, skip searching\n\t\t\t\t\tcheckCoordinatesThenRoute(coordinates);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"function showOnMap(drive) {\n placeOrigin['name'] = drive['from']['name'];\n placeOrigin['id'] = drive['from']['placeId'];\n placeDestination['name'] = drive['to']['name'];\n placeDestination['id'] = drive['to']['placeId'];\n waypoints = [];\n for (let i = 0; i < drive['stops'].length; i++) {\n if (drive['stops'][i]['name'] !== \"\") {\n waypoints.push({\n name: drive['stops'][i]['name'],\n placeId: drive['stops'][i]['placeId']\n });\n }\n }\n triggerSearch();\n}",
"function showSingleRoutingResultOnMap(result) {\n\t\tclearRoutingResultsOnMap();\n\n\t\tvar trackCounter = 0;\n\t\t$.each(result.steps, function (stepIndex, step) {\n\t\t\tif (step[0] === 'none') {\n\t\t\t\t// Don't draw line\n\t\t\t} else {\n\t\t\t\tvar lineFeature = new ol.Feature({\n\t\t\t\t\tgeometry: new ol.geom.LineString(stringArrayToPointArray(step[2])),\n\t\t\t\t});\n\t\t\t\tlineFeature.setStyle(step[0] == 'walk' ? walkStrokeStyle : trackStrokeStyles[trackCounter++ % trackStrokeStyles.length]);\n\t\t\t\tresultVectorSource.addFeature(lineFeature);\n\t\t\t}\n\t\t\t\n\t\t\tif (stepIndex === 0) {\n\t\t\t\tvar pointFeature = new ol.Feature({\n\t\t\t\t\tgeometry: new ol.geom.Point(ol.proj.transform(stringToLonLat(step[2][0]), 'EPSG:4326', 'EPSG:3857'))\n\t\t\t\t})\n\t\t\t\tpointFeature.setStyle(new ol.style.Style({\n\t\t\t\t\timage: new ol.style.Icon({\n\t\t\t\t\t\tsrc: 'images/start.png',\n\t\t\t\t\t\tanchor: [1.0, 1.0]\n\t\t\t\t\t})\n\t\t\t\t}));\n\t\t\t\tresultVectorSource.addFeature(pointFeature);\n\t\t\t} else {\n\t\t\t\tvar lonlat = stringToLonLat(step[2][0]);\n\t\t\t\tif(step[0] != \"walk\"){\n\t\t\t\t\tvar pointFeature = new ol.Feature({\n\t\t\t\t\t\tgeometry: new ol.geom.Point(ol.proj.transform(lonlat, 'EPSG:4326', 'EPSG:3857'))\n\t\t\t\t\t})\n\t\t\t\t\tpointFeature.setStyle(new ol.style.Style({\n\t\t\t\t\t\timage: new ol.style.Icon({\n\t\t\t\t\t\t\tsrc: '../images/means/' + step[0] + '/baloon/' + step[1] + '.png',\n\t\t\t\t\t\t\tanchor: [0.0, 1.0]\n\t\t\t\t\t\t})\n\t\t\t\t\t}));\n\t\t\t\t\tresultVectorSource.addFeature(pointFeature);\n\t\t\t\t} else {\n\t\t\t\t\tvar pointFeature = new ol.Feature({\n\t\t\t\t\t\tgeometry: new ol.geom.Point(ol.proj.transform(lonlat, 'EPSG:4326', 'EPSG:3857'))\n\t\t\t\t\t})\n\t\t\t\t\tpointFeature.setStyle(new ol.style.Style({\n\t\t\t\t\t\timage: new ol.style.Icon({\n\t\t\t\t\t\t\tsrc: 'images/means/walk/baloon/walk.png',\n\t\t\t\t\t\t\tanchor: [1.0, 1.0]\n\t\t\t\t\t\t})\n\t\t\t\t\t}));\n\t\t\t\t\tresultVectorSource.addFeature(pointFeature);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (stepIndex === result.steps.length - 1) {\n\t\t\t\tvar lonlat = stringToLonLat(step[2][step[2].length - 1]);\n\t\t\t\tvar pointFeature = new ol.Feature({\n\t\t\t\t\tgeometry: new ol.geom.Point(ol.proj.transform(lonlat, 'EPSG:4326', 'EPSG:3857'))\n\t\t\t\t})\n\t\t\t\tpointFeature.setStyle(new ol.style.Style({\n\t\t\t\t\timage: new ol.style.Icon({\n\t\t\t\t\t\tsrc: 'images/finish.png',\n\t\t\t\t\t\tanchor: [0.0, 1.0]\n\t\t\t\t\t})\n\t\t\t\t}));\n\t\t\t\tresultVectorSource.addFeature(pointFeature);\n\t\t\t}\n\t\t});\n\t\tmap.getView().fitExtent(resultVectorSource.getExtent(), map.getSize());\n\t}",
"function handleWaypointRequest(atts) {\n\t\t\tui.searchWaypointChangeToSearchingState(true, atts.wpIndex);\n\t\t\tvar lastSearchResults = atts.searchIds;\n\t\t\tlastSearchResults = lastSearchResults ? lastSearchResults.split(' ') : null;\n\n\t\t\tif (lastSearchResults) {\n\t\t\t\tmap.clearMarkers(map.SEARCH, lastSearchResults);\n\t\t\t}\n\n\t\t\twaypoint.incrRequestCounterWaypoint(atts.wpIndex);\n\t\t\twaypoint.find(atts.query, handleSearchWaypointResults, handleSearchWaypointFailure, atts.wpIndex, preferences.language);\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
render tabs eyebrow text | renderTabsEyebrowText() {
if (this.eyebrowText) {
return (core.h("p", { class: "tabs-eyebrow-text dxp-title-eyebrow dxp-font-size-sm" }, this.eyebrowText));
}
} | [
"function _jsTabControl_drawTab(d, tab) {\n\td.write(\"<table border=\\\"0\\\" cellspacing=\\\"0\\\" cellpadding=\\\"0\\\"><tr><td><img src=\\\"\");\n\td.write(IMG_TAB_OFF[0].filename);\n\td.write(\"\\\" border=\\\"0\\\" height=\\\"\");\n\td.write(IMG_TAB_OFF[0].height);\n\td.write(\"\\\" width=\\\"\");\n\td.write(IMG_TAB_OFF[0].width);\n\td.write(\"\\\" id=\\\"tab\");\n\td.write(tab.id);\n\td.write(\"left\\\" /></td><td id=\\\"tab\");\n\td.write(tab.id);\n\td.write(\"text\\\" class=\\\"tabText\\\" width=\\\"\");\n\td.write(this.tabWidth - IMG_TAB_OFF[2].width - IMG_TAB_OFF[0].width);\n\td.write(\"\\\"><a class=\\\"tabLink\\\" href=\\\"javascript:clickTab(\");\n\td.write(tab.id);\n\td.write(\")\\\">\");\n\td.write(tab.text);\n\td.write(\"</a></td><td><img src=\\\"\");\n\td.write(IMG_TAB_OFF[2].filename);\n\td.write(\"\\\" border=\\\"0\\\" height=\\\"\");\n\td.write(IMG_TAB_OFF[2].height);\n\td.write(\"\\\" width=\\\"\");\n\td.write(IMG_TAB_OFF[2].width);\n\td.write(\"\\\"id=\\\"tab\");\n\td.write(tab.id);\n\td.write(\"right\\\" /></td></tr></table>\");\n}",
"function _render(tabs) {\n var res = {header: [], content: []};\n\n _.each(tabs, function (i, val) {\n res.header.push(_.template(headTpl, val));\n res.content.push(_.template(contentTpl, val));\n });\n\n res = _.template(wrapperTpl, {\n header: res.header.join(''),\n content: res.content.join('')\n });\n\n this.elem.innerHTML = res;\n\n this.activeTab(this.active);\n }",
"function _jsTabControl_drawTab(d, tab, on) {\n\td.write(\"<table border=\\\"0\\\" cellspacing=\\\"0\\\" cellpadding=\\\"0\\\"><tr><td><img src=\\\"\");\n\td.write(on ? IMG_TAB_ON[0].filename : IMG_TAB_OFF[0].filename);\n\td.write(\"\\\" border=\\\"0\\\" height=\\\"\");\n\td.write(IMG_TAB_OFF[0].height);\n\td.write(\"\\\" width=\\\"\");\n\td.write(IMG_TAB_OFF[0].width);\n\td.write(\"\\\" /></td><td class=\\\"tabText\\\" width=\\\"\");\n\td.write(this.tabWidth - IMG_TAB_OFF[2].width - IMG_TAB_OFF[0].width);\n\td.write(\"\\\" background=\\\"\");\n\td.write(on ? IMG_TAB_ON[1].filename : IMG_TAB_OFF[1].filename);\n\td.write(\"\\\"><a class=\\\"tabLink\\\" href=\\\"javascript:clickTab(\");\n\td.write(tab.id);\n\td.write(\")\\\">\");\n\td.write(tab.text);\n\td.write(\"</a></td><td><img src=\\\"\");\n\td.write(on ? IMG_TAB_ON[2].filename : IMG_TAB_OFF[2].filename);\n\td.write(\"\\\" border=\\\"0\\\" height=\\\"\");\n\td.write(IMG_TAB_OFF[2].height);\n\td.write(\"\\\" width=\\\"\");\n\td.write(IMG_TAB_OFF[2].width);\n\td.write(\"\\\" /></td></tr></table>\");\n}",
"function draw_tabs() {\n // Get tab area\n var tabX = 0;\n var tabY = display.getHeight() - 4;\n var tabW = display.getWidth();\n var tabH = 4;\n\n // Draw the red area\n display.fill(tabX, tabY, tabW, tabH, \"white\", \"red\", ' ');\n\n // Draw instruction text\n display.text(tabX + Math.floor(tabW / 2) - 7, tabY + 1, \"Press <TAB> to\");\n display.text(tabX + Math.floor(tabW / 2) - 10, tabY + 2, \"switch between panes.\");\n\n // Width tab\n display.text(tabX + 2, tabY + 1, \" WIDTH \", 'red', 'white');\n if (tabSelected === 0) {\n display.fill(tabX + 2, tabY + 2, 11, 1, 'red', 'white', ' ');\n }\n display.text(tabX + 6, tabY + 2, etch.getWidth().toString());\n // Height tab\n display.text(tabX + 15, tabY + 1, \" HEIGHT \", 'red', 'white');\n if (tabSelected === 1) {\n display.fill(tabX + 15, tabY + 2, 11, 1, 'red', 'white', ' ');\n }\n display.text(tabX + 19, tabY + 2, etch.getHeight().toString());\n // Clear tab\n display.text(tabX + tabW - 26, tabY + 1, \" CLEAR \", 'red', 'white');\n if (tabSelected === 2) {\n display.text(tabX + tabW - 26, tabY + 2, \" [ENTER] \", 'red', 'white');\n }\n // Exit tab\n display.text(tabX + tabW - 13, tabY + 1, \" EXIT \", 'red', 'white');\n if (tabSelected === 3) {\n display.text(tabX + tabW - 13, tabY + 2, \" [ENTER] \", 'red', 'white');\n }\n}",
"function tabInit() {\n \"use strict\";\n\n var tabText = 'options';\n $('#optionTab').html('<div id=\"optionTabText\">' + tabText + '</div');\n }",
"function Tabcontent() {\r\n $('.menu .item').tab({\r\n cache: false,\r\n alwaysRefresh: true,\r\n history: true,\r\n historyType: 'hash',\r\n apiSettings: {\r\n loadingDuration : 1000,\r\n url: 'modules/{$tab}.html'\r\n }\r\n });\r\n}",
"function CreateVerticalTabs( VerticalObj ) {\n var tabStr = \"\"; var j = 0;\n tabStr += '<div class=\"col-xs-3\">';\n tabStr += '<ul class=\"nav nav-tabs tabs-left\">';\n \n $.each(VerticalObj, function(i, TabVal){\n if(j == 0 ) tabStr += '<li class=\"active\"><a href=\"#'+i+'\" data-toggle=\"tab\" aria-expanded=\"false\">'+TabVal+'</a></li>';\n else tabStr += '<li class=\"\"><a href=\"#'+i+'\" data-toggle=\"tab\" aria-expanded=\"false\">'+TabVal+'</a></li>';\n j ++;\n });\n\n tabStr += '</ul>';\n tabStr += '</div>';\n return tabStr;\n }",
"function tabTextStyle() {\n\t\thideTabContent();\n\t\ttextStyleContainer.addClass('standBy');\n\t}",
"getTabString() {\n if (this.getUseSoftTabs()) {\n return lang.stringRepeat(\" \", this.getTabSize());\n } else {\n return \"\\t\";\n }\n }",
"get activedTabText() {\n return this.getTabText(this.activedTabIndex);\n }",
"function getTabs(tabs) {\n if (!tabs) return '';\n return ' '.repeat(tabs * 4);\n}",
"renderTabNotice() {\n return DEFAULT_TAB_DISABLED\n ? this.renderDisabledTabNotice()\n : this.renderEnabledTabNotice();\n }",
"function draw_tab(i,active_tab){\n\n //tab border\n ctx.strokeStyle = \"#000000\";\n ctx.fillStyle = \"#ffffff\";\n ctx.lineWidth = (active_tab && OBJ.selected) ? 2 : 1;\n //if(i == OBJ.active_tab){ctx.lineWidth = 2;}else{ctx.lineWidth = 1;}\n\n BASE.roundTab(\n ctx,\n OBJ.x,OBJ.y-OBJ.tab_height,OBJ.width,OBJ.height+OBJ.tab_height,//x,y,width,height of total square surrounding window and tab\n OBJ.tabs[i].x,OBJ.tabs[i].tab_width,OBJ.tab_height,//offset to the right from the window that the tab is,width of tab,height of the tab\n 4//rounded border radius\n );\n ctx.globalAlpha = 1.0;\n ctx.stroke();\n ctx.fill();\n\n //tab title\n ctx.fillStyle = \"#000000\";\n ctx.font = \"12px Verdana\";\n ctx.textAlign = \"left\"\n ctx.textBaseline = \"bottom\";\n ctx.fillText(OBJ.tabs[i].title,OBJ.x+OBJ.tabs[i].x+OBJ.tab_inner+0.5,OBJ.y-OBJ.tab_up+0.5);\n\n }",
"function generateTabs(items) {\n\t\tvar html = '<ul id=\"tabmenu\">\\n';\n\t\tfor (var i in items) {\n\t\t\tvar item = items[i];\n // jquery-ui tabs needs to have achor link in <li>\n\t\t\thtml += ' <li id=\"tab' + item.category + '\"><a href=\"#tab-' + item.category + '\">' + item.title + '</a></li>\\n';\n\t\t}\n\t\thtml += '</ul>\\n';\n\t\treturn html;\n\t}",
"function makeContentTab(entry) {\n var escapedText = entry.response.content.text || \"\";\n var unescapedText = escapedText.replace(escapedNewLineRegex, \"\\n\").replace(escapedTabRegex, \"\\t\");\n var newLines = escapedText.match(newLineRegex);\n var lineCount = newLines ? newLines.length : 1;\n return makeLazyWaterfallEntryTab(\"Content (\" + lineCount + \" Line\" + (lineCount > 1 ? \"s\" : \"\") + \")\", function () { return \"<pre><code>\" + parse_1.escapeHtml(unescapedText) + \"</code></pre> \"; }, \"content rendered-data\");\n}",
"function getTabs(tabs) {\n for (let tab of tabs) {\n let title = `<xmp>${tab.title}</xmp>`;\n\n const tab_li = `<li class=\"tab\">\n <img class=\"close\" id=\"${tab.id}\" src=\"close.png\">\n <p>${title}</p>\n </li>`;\n tabs_element.insertAdjacentHTML(\"beforeend\", tab_li);\n \n total++;\n }\n tab_num.innerText = \"Total tabs: \" + total;\n}",
"function onTabActivated() {\n render();\n }",
"function addTab() {\n var label = tabTitle.val() || \"Tab\" + tabCounter + \".lua\";\n id = tabCounter;\n li = $(tabTemplate.replace(/#\\{href\\}/g, \"#\" + id).replace(/#\\{label\\}/g, label).replace(/#\\{id\\}/g, \"tab_\"+id));\n tabs.find(\".ui-tabs-nav\").append(li);\n tabs.append(\"<div id='\" + id + \"'><textarea id='code\" + tabCounter + \"' name = 'code\" + tabCounter + \"'></textarea></div>\");\n tabs.tabs(\"refresh\");\n tabIndexMap.push(tabCounter);\n tabLabels.push(label);\n addEditor();\n tabs.tabs('select', tabIndexMap.length - 1);\n \n cm[cm.length - 1].refresh();\n cm[cm.length - 1].focus();\n \n }",
"function createTabs(numTabs)\r\n{\r\n var tabString = \"\";\r\n for(var i=0; i<numTabs; i++)\r\n {\r\n tabString += \"| \";\r\n }\r\n return tabString;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` and `https` modules. (NB: Not a typo this is a creator^2!) | function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) {
return function wrappedRequestMethodFactory(originalRequestMethod) {
return function wrappedMethod() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
var httpModule = this;
var requestArgs = http_1.normalizeRequestArgs(this, args);
var requestOptions = requestArgs[0];
var requestUrl = http_1.extractUrl(requestOptions);
// we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method
if (http_1.isSentryRequest(requestUrl)) {
return originalRequestMethod.apply(httpModule, requestArgs);
}
var span;
var parentSpan;
var scope = core_1.getCurrentHub().getScope();
if (scope && tracingEnabled) {
parentSpan = scope.getSpan();
if (parentSpan) {
span = parentSpan.startChild({
description: (requestOptions.method || 'GET') + " " + requestUrl,
op: 'http.client',
});
var sentryTraceHeader = span.toTraceparent();
utils_1.logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": ");
requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader });
}
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
return originalRequestMethod
.apply(httpModule, requestArgs)
.once('response', function (res) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
var req = this;
if (breadcrumbsEnabled) {
addRequestBreadcrumb('response', requestUrl, req, res);
}
if (tracingEnabled && span) {
if (res.statusCode) {
span.setHttpStatus(res.statusCode);
}
span.description = http_1.cleanSpanDescription(span.description, requestOptions, req);
span.finish();
}
})
.once('error', function () {
// eslint-disable-next-line @typescript-eslint/no-this-alias
var req = this;
if (breadcrumbsEnabled) {
addRequestBreadcrumb('error', requestUrl, req);
}
if (tracingEnabled && span) {
span.setHttpStatus(500);
span.description = http_1.cleanSpanDescription(span.description, requestOptions, req);
span.finish();
}
});
};
};
} | [
"function createHttp() {\n const http = {\n request(url, options = {}) {\n return new Promise((resolve, reject) => {\n fetch(url, options).then((response) => {\n if (response.ok) {\n response.json().then((data) => {\n resolve(data)\n })\n }\n }).catch((e) => reject(e))\n })\n },\n get(url, options = {}) {\n return http.request(url, Object.assign(options, { method: METHODS.Get }))\n },\n post(url, options = {}) {\n return http.request(url, Object.assign(options, { method: METHODS.Post }))\n }\n }\n\n return http\n}",
"function makeHttp(httpFn, preFetch, postFetch) {\n postFetch = postFetch || function (a) {return a;};\n preFetch = preFetch || function (a) {return a;};\n\n return function (req) {\n if (typeof req === 'string') {\n req = { url: req };\n }\n http_self.mergeInQueryOrForm(req);\n req = preFetch(req);\n return postFetch(httpFn(req));\n };\n}",
"function makeHttp(httpFn, preFetch, postFetch) {\n\t postFetch = postFetch || function (a) {\n\t return a;\n\t };\n\t preFetch = preFetch || function (a) {\n\t return a;\n\t };\n\n\t return function (req) {\n\t if (typeof req === 'string') {\n\t req = { url: req };\n\t }\n\t self.mergeInQueryOrForm(req);\n\t req = preFetch(req);\n\t return postFetch(httpFn(req));\n\t };\n\t}",
"_getPatchHttpsOutgoingGetFunction(clientRequest) {\n return (original) => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n options, ...args) {\n return instrumentation._getPatchOutgoingGetFunction(clientRequest)(original)(options, ...args);\n };\n };\n }",
"request(first, url, options = {}) {\n let req; // First, check whether the primary argument is an instance of `HttpRequest`.\n\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n } else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n } else {\n headers = new HttpHeaders(options.headers);\n } // Sort out parameters.\n\n\n let params = undefined;\n\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n } else {\n params = new HttpParams({\n fromObject: options.params\n });\n }\n } // Construct the request.\n\n\n req = new HttpRequest(first, url, options.body !== undefined ? options.body : null, {\n headers,\n context: options.context,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials\n });\n } // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n\n\n const events$ = (0,rxjs__WEBPACK_IMPORTED_MODULE_0__.of)(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_1__.concatMap)(req => this.handler.handle(req))); // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n } // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n\n\n const res$ = events$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.filter)(event => event instanceof HttpResponse)); // Decide which stream to return.\n\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n\n return res.body;\n }));\n\n case 'blob':\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n\n return res.body;\n }));\n\n case 'text':\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n\n return res.body;\n }));\n\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => res.body));\n }\n\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }",
"function HTTP() {}",
"function wrapRequest(req) {\n const { originalRequest } = req;\n const url = getRequestMeta(originalRequest, \"__NEXT_INIT_URL\");\n if (!url) throw new Error(\"Invariant: missing url on request\");\n // HEAD and GET requests can not have a body.\n const body = req.method !== \"GET\" && req.method !== \"HEAD\" && req.body ? req.body : null;\n return new NextRequest(url, {\n body,\n // @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457\n duplex: \"half\",\n method: req.method,\n headers: fromNodeHeaders(req.headers)\n });\n}",
"function http(...fns) {\n\n // ensure we have been passed only functions\n fns.forEach(f=> {\n if (typeof f != 'function')\n throw TypeError(f + ' not a function')\n })\n\n // return an aws lambda function signature\n return function lambda(request, context, callback) {\n\n // verify the request is configured by arc\n if (!request.headers)\n throw Error('gateway missing headers')\n\n // cache the functions\n let cache = fns.slice()\n\n // read the session\n //console.log('got request', request)\n read(request, function _read(err, session) {\n //console.log('got session', session)\n\n // fail loudly if the session isn't setup correctly\n if (err)\n throw err\n\n // construct a response function\n let req = interpolate(Object.assign({}, request, {session}))\n let res = response.bind({}, req, callback)\n\n // loop thru middleware\n ;(function iterator(fun) {\n function fail() {throw Error('next() called from last function')}\n let next = iterator.bind({}, cache.shift() || fail)\n fun.call({}, req, res, next)\n })(cache.shift())\n })\n }\n}",
"createFromRequest(req, res, next) {\n var reqd = create();\n return reqd;\n }",
"function requestFactory (config) {\n // authorization is set in etl.js\n var authorization = nconf.get('authorization');\n var uri;\n\n if (config.type === 'worklog') {\n uri = api + '/rest/api/' + version + '/issue/' + config.parent + '/worklog';\n \n } else if (config.type === 'issue') {\n uri = api + '/rest/api/' + version + '/issue/' + config.parent;\n }\n\n return function (callback) {\n request({\n uri: uri,\n json: true,\n headers: {\n \"Authorization\" : authorization\n }\n }, function(error, response, json) {\n networkLog(response);\n\n // handle error logging\n if (error || response.statusCode !== 200) {\n var err = {\n uri: uri,\n status: response.statusCode\n };\n\n if (error) {\n err.details = error;\n } else if (response.statusCode !== 200) {\n err.details = 'Error: status code not 200 OK. Status code: ' + response.statusCode;\n }\n }\n\n \n\n // add the resulting data to the config object.\n var state = _.merge(config, {\n data: json,\n error: err || null\n });\n \n return callback(error, state);\n });\n };\n}",
"function wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024\n }; // Wrap each protocol\n\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); // Executes a request, following redirects\n\n wrappedProtocol.request = function (input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n\n try {\n input = urlToOptions(new URL(urlStr));\n } catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n } else if (URL && input instanceof URL) {\n input = urlToOptions(input);\n } else {\n callback = options;\n options = input;\n input = {\n protocol: protocol\n };\n }\n\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n } // Set defaults\n\n\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }; // Executes a GET request, following redirects\n\n\n wrappedProtocol.get = function (input, options, callback) {\n var request = wrappedProtocol.request(input, options, callback);\n request.end();\n return request;\n };\n });\n return exports;\n}",
"function wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL$1(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n }\n else if (URL$1 && (input instanceof URL$1)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug$2(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}",
"function wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n }\n else if (URL && (input instanceof URL)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug_1(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}",
"function wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n }\n else if (URL && (input instanceof URL)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}",
"function wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url__default['default'].parse(urlStr);\n }\n }\n else if (URL && (input instanceof URL)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert__default['default'].equal(options.protocol, protocol, \"protocol mismatch\");\n debug_1(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}",
"async function initWrappers() {\n const WRAPPERS = [wrapHandlerWithCORS, wrapHandlerWithAuthorization];\n\n return WRAPPERS;\n}",
"request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n }\n else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n }\n else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n }\n else {\n params = new HttpParams({ fromObject: options.params });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {\n headers,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials,\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"concatMap\"])((req) => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((event) => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }",
"function RequestBase() {}",
"function makeRequestor(proxyHost) {\n return function(method, forwardUrl, headers, cb) {\n if (!cb) {\n var cb = headers;\n headers = {};\n }\n\n var options = {\n method: method,\n url: proxyHost+'/'+forwardUrl,\n headers: headers\n }\n\n request(options, cb);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
end utility functions reliableEntropy is the Shannon Entropy with the total always being 1 for hot init | function reliableEntropy (pspace) {
let tfreq = vectorSum(Object.values(pspace)) + 1
let hrel = -(1 / tfreq) * Math.log2(1 / tfreq)
for (var freq in pspace) {
var tmp = pspace[freq] / tfreq
hrel -= tmp * Math.log2(tmp)
}
return hrel
} | [
"get entropy(): number {\n return 0.5 * 0.693 * Math.log2(2* Math.PI * Math.E * this.trials * this.successProb * (1 - this.successProb));\n }",
"generateEntropy () {\n return this.get32RandomBytes();\n }",
"get entropy(): number {\n return -1 * (Math.log(1- this.p) * (1 - this.p) + Math.log(this.p) * this.p);\n }",
"generateEntropy() {\n return this.get32RandomBytes();\n }",
"get entropy(): number {\n return Math.log(2 * this.scale * 2.71828182845904523536);\n }",
"get entropy(): number {\n return Math.log(this.xm * Math.exp(1 + (1 / this.alpha)) / this.alpha);\n }",
"entropy(Array){\n var to_compute = this.twodto1d(Array);\n var sum = 0;\n for (var i = 0; i < to_compute.length; i++){\n if (to_compute[i] != 0){\n sum = sum + to_compute[i] * Math.log2(to_compute[i]);\n }\n }\n return -sum;\n }",
"get entropy(): number {\n return Math.log(this.max - this.min);\n }",
"function y=entropy(x){\n var tot = 0.0;\n var ent = 0.0;\n for (i=0;i < x.length; i++){\n tot = tot + x[i]ˆ2;\n }\n for (i=0;i < x.length; i++){\n quo = x[i]ˆ2 / tot;\n ent = ent + (quo * log10(quo));\n }\n var y = -ent;\n return y\n}",
"get entropy(): number {\n return 1.28860783245076643030325605 + Math.log(this.sigma / 1.4142135623730950488016887242097);\n }",
"static entropyChecksumBits(entropy) {\r\n const hash = Sha256.sum256(entropy);\r\n const bits = entropy.length * 8;\r\n const hashbits = Converter.bytesToBinary(hash);\r\n return hashbits.slice(0, bits / 32);\r\n }",
"function get_entropy() {\n var pts, prev_x, prev_y, h, x, y, p, i;\n pts = this.get_breakpoints();\n prev_x = -1;\n prev_y = -1;\n h = 0;\n for (i = 0; i < pts.length; i++) {\n x = pts[i][0];\n y = pts[i][1];\n if (prev_x != -1) {\n p = (y - prev_y) / (x - prev_x);\n if (p > 0) {\n h -= (p * (Math.log(p) / Math.log(2))) * (x - prev_x);\n }\n }\n prev_x = x;\n prev_y = y;\n\n }\n return h;\n }",
"static entropyChecksumBits(entropy) {\r\n const hash = Sha256.sum256(entropy);\r\n const bits = entropy.length * 8;\r\n const hashbits = util_js.Converter.bytesToBinary(hash);\r\n return hashbits.slice(0, bits / 32);\r\n }",
"function renyiEntropy(histogram, total) {\n let optThreshold; // Optimal threshold\n let firstBin; // First non-zero bin\n let lastBin; // last non-zero bin\n\n let normHisto = new Array(histogram.length); // normalized histogram\n let P1 = new Array(histogram.length); // acumulative normalized histogram\n let P2 = new Array(histogram.length); // acumulative normalized histogram\n\n // Entropy Variables\n let threshold1 = 0;\n let threshold2 = 0;\n let threshold3 = 0;\n let maxEnt1 = 0.0;\n let maxEnt2 = 0.0;\n let maxEnt3 = 0.0;\n let alpha2 = 0.5;\n let term2 = 1.0 / (1.0 - alpha2);\n let alpha3 = 2.0;\n let term3 = 1.0 / (1.0 - alpha3);\n\n for (let ih = 0; ih < histogram.length; ih++) {\n normHisto[ih] = histogram[ih] / total;\n }\n\n P1[0] = normHisto[0];\n P2[0] = 1.0 - P1[0];\n for (let ih = 1; ih < histogram.length; ih++) {\n P1[ih] = P1[ih - 1] + normHisto[ih];\n P2[ih] = 1.0 - P1[ih];\n }\n\n /* Determine the first non-zero bin */\n firstBin = 0;\n for (let ih = 0; ih < histogram.length; ih++) {\n if (Math.abs(P1[ih]) >= Number.EPSILON) {\n firstBin = ih;\n break;\n }\n }\n\n /* Determine the last non-zero bin */\n lastBin = histogram.length - 1;\n for (let ih = histogram.length - 1; ih >= firstBin; ih--) {\n if (Math.abs(P2[ih]) >= Number.EPSILON) {\n lastBin = ih;\n break;\n }\n }\n\n /* Maximum Entropy Thresholding - BEGIN */\n /* ALPHA = 1.0 */\n /* Calculate the total entropy each gray-level\n and find the threshold that maximizes it\n */\n for (let it = firstBin; it <= lastBin; it++) {\n /* Entropy of the background pixels */\n let entBack1 = 0.0;\n let entBack2 = 0.0;\n let entBack3 = 0.0;\n for (let ih = 0; ih <= it; ih++) {\n if (histogram[ih] !== 0) {\n entBack1 -= (normHisto[ih] / P1[it]) * Math.log(normHisto[ih] / P1[it]);\n }\n entBack2 += Math.sqrt(normHisto[ih] / P1[it]);\n entBack3 += (normHisto[ih] * normHisto[ih]) / (P1[it] * P1[it]);\n }\n\n /* Entropy of the object pixels */\n let entObj1 = 0.0;\n let entObj2 = 0.0;\n let entObj3 = 0.0;\n for (let ih = it + 1; ih < histogram.length; ih++) {\n if (histogram[ih] !== 0) {\n entObj1 -= (normHisto[ih] / P2[it]) * Math.log(normHisto[ih] / P2[it]);\n }\n entObj2 += Math.sqrt(normHisto[ih] / P2[it]);\n entObj3 += (normHisto[ih] * normHisto[ih]) / (P2[it] * P2[it]);\n }\n\n /* Total entropy */\n let totEnt1 = entBack1 + entObj1;\n let totEnt2 =\n term2 * (entBack2 * entObj2 > 0.0 ? Math.log(entBack2 * entObj2) : 0.0);\n let totEnt3 =\n term3 * (entBack3 * entObj3 > 0.0 ? Math.log(entBack3 * entObj3) : 0.0);\n\n if (totEnt1 > maxEnt1) {\n maxEnt1 = totEnt1;\n threshold1 = it;\n }\n\n if (totEnt2 > maxEnt2) {\n maxEnt2 = totEnt2;\n threshold2 = it;\n }\n\n if (totEnt3 > maxEnt3) {\n maxEnt3 = totEnt3;\n threshold3 = it;\n }\n }\n /* End Maximum Entropy Thresholding */\n\n let tStars = [threshold1, threshold2, threshold3];\n tStars.sort(num_sort__WEBPACK_IMPORTED_MODULE_0__[\"ascending\"]);\n\n let betas;\n\n /* Adjust beta values */\n if (Math.abs(tStars[0] - tStars[1]) <= 5) {\n if (Math.abs(tStars[1] - tStars[2]) <= 5) {\n betas = [1, 2, 1];\n } else {\n betas = [0, 1, 3];\n }\n } else {\n if (Math.abs(tStars[1] - tStars[2]) <= 5) {\n betas = [3, 1, 0];\n } else {\n betas = [1, 2, 1];\n }\n }\n\n /* Determine the optimal threshold value */\n let omega = P1[tStars[2]] - P1[tStars[0]];\n optThreshold = Math.round(\n tStars[0] * (P1[tStars[0]] + 0.25 * omega * betas[0]) +\n 0.25 * tStars[1] * omega * betas[1] +\n tStars[2] * (P2[tStars[2]] + 0.25 * omega * betas[2]),\n );\n\n return optThreshold;\n}",
"function entropy(vals) {\n var uniqueVals = _.unique(vals);\n var probs = uniqueVals.map(function(x) {\n return prob(x, vals)\n });\n\n var logVals = probs.map(function(p) {\n return -p * log2(p)\n });\n \n return logVals.reduce(function(a, b) {\n return a + b\n }, 0);\n }",
"function entropy(vals) {\n var uniqVals = _.uniq(vals);\n var probs = uniqVals.map(function(x) {\n return prob(x, vals)\n });\n\n var logVals = probs.map(function(p) {\n return -p * log2(p)\n });\n \n return logVals.reduce(function(a, b) {\n return a + b\n }, 0);\n }",
"function entropy(s) {\n //create an object containing each individual char\n\t//and the amount of iterations per char\n function prob(s) {\n var h = Object.create(null);\n s.split('').forEach(function(c) {\n h[c] && h[c]++ || (h[c] = 1);\n });\n return h;\n }\n\n s = s.toString(); //just in case\n var e = 0, l = s.length, h = prob(s);\n\n for (var i in h ) {\n var p = h[i]/l;\n e -= p * Math.log(p) / Math.log(2);\n }\n return e;\n}",
"function chaos(entropy) {\n return Math.floor( Math.random() * (entropy) ) + 1;\n}",
"function entropy(obj){\n return -Iterator.values(obj)\n .map(p=>p*Math.log2(p))\n .sum()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the constraint with the given ID. | function runConstraint(constraintId, responseDiv) {
console.log("runConstraint(" + constraintId + ")");
responseDiv.text("");
responseDiv.attr("class", "list-group-item"); // reset the CSS of the DIV
showSpinner();
$.ajax(JqaConstants.REST_ANALYSIS_CONSTRAINT_URL,
{
'data': constraintId,
'type': 'POST',
'headers': {
'Accepts': 'text/plain',
'Content-Type': 'text/plain'
}
}).done(function (data, textStatus, jqXHR) { /* the success function */
console.log("Successfully ran constraint.");
var message;
var listClass;
if (!data) {
message = "No result received from the server. Please check the logs.";
listClass = "list-group-item-warning";
} else {
message = "Affected rows after executing the constraint: " + data;
listClass = "list-group-item-success";
}
responseDiv.addClass(listClass);
responseDiv.text(message);
responseDiv.show();
})
.fail(function (jqxhr, textStatus, error) { /* the failed function */
var errorMessage;
if (jqxhr.status == 0) {
errorMessage = "Error running constraint: Is the service down?";
} else {
errorMessage = "Error running constraint: " + jqxhr.status + " " + jqxhr.statusText;
}
console.log(errorMessage);
responseDiv.addClass("list-group-item-danger");
responseDiv.text(errorMessage);
responseDiv.show();
})
.always(function () { /* always executed after the AJAX call */
removeSpinner();
console.log("Finished running constraint.");
});
} | [
"runValidation(validationId, planId) {\n return this.defaultRequest(`/validations/${validationId}/run`, {\n method: 'PUT',\n data: { plan_id: planId }\n });\n }",
"function check_compound_constraint(constraint_id){\n\n var reverse_constraint_lookup = \n env['reverse_constraint_lookup'];\n var compound_constraint_lookup = \n env['compound_constraint_lookup'];\n\n var compound_constraint_id = \n reverse_constraint_lookup[constraint_id];\n\n var compound_constraint = \n compound_constraint_lookup[compound_constraint_id]; \n\n var result = compound_constraint(constraint_id);\n \n return result;\n }",
"function addConstraintBetween( id1, id2 )\n{\n var ballA = idToCircleMap.get( id1 );\n var ballB = idToCircleMap.get( id2 );\n\n if ( ballA && ballB )\n {\n var constraint = Constraint.create({\n bodyA: ballA,\n bodyB: ballB,\n render: {strokeStyle: CONSTRAINT_STROKE_COLOR},\n stiffness: STIFFNESS_CONSTANT\n });\n\n Composite.add(barAndJointComposite, [constraint]);\n }\n else \n {\n console.log( \"one or both IDs are invalid\" );\n console.log( \"id1: \" + id1 + \" mapped to \" + \"ballA\"+ ballA );\n console.log( \"id2: \" + id2 + \" mapped to \" + \"ballB\"+ ballB );\n }\n}",
"function runCmdExact(id, val) {\n var cmd = id + '/command/exact?level=' + val;\n dataFactory.runApiCmd(cmd).then(function(response) {\n }, function(error) {\n dataService.logError(error);\n });\n return;\n }",
"fire(id) {\n if (id && this.nodes[id]) {\n this.nodes[id].fire();\n }\n }",
"async _delete(id) {\n // log method\n logger.log(2, '_delete', `Preparing to delete contract ${id}`);\n\n // compute method\n try {\n let contract = new Contract(await this.databaseModify.getEntry(id));\n await this._validateDelete(contract);\n\n // log success\n logger.log(2, '_delete', `Successfully prepared to delete contract ${id}`);\n\n // return contract deleted\n return contract;\n } catch (err) {\n // log error\n logger.log(2, '_delete', `Failed to prepare delete for contract ${id}`);\n\n // return rejected promise\n return Promise.reject(err);\n }\n }",
"function runCmdExact(id, val) {\n //console.log('Knob from directive:',val)\n var cmd = id + '/command/exact?level=' + val;\n dataFactory.runApiCmd(cmd).then(function (response) {\n }, function (error) {});\n return;\n }",
"main({ id: id }, closure) {\n if( id === undefined ) { throw new Error(`The main flow id must be defined.`) }\n\n this.rootFlow.setId({ id: id, idPath: id })\n\n if( closure != undefined ) {\n this.evaluate({ closure: closure, with: this.rootFlow })\n }\n }",
"run(taskID) {\n let actions = this._tasks[taskID];\n if (actions !== undefined) {\n let result = Promise.resolve(this._model)\n for (let i = 0; i < actions.length; i++) {\n let actionID = actions[i];\n let action = this._actions[actionID];\n if (action !== undefined) {\n result = result.then(model=>{\n return new Promise((resolve, reject) => {\n action.apply(this, [model, resolve, reject]);\n })\n });\n } else {\n return Promise.reject(\"No Action found for given action ID\")\n }\n }\n return result;\n }\n return Promise.reject(\"No Actions found for given task ID\")\n }",
"function deleteCrossTreeConstraint(constraintId) {\n\t\t//constraintObj = dojo.byId(constraintId);\n\t\t//constraintObj.parentNode.removeChild(constraintObj);\n\t\tcrossTreeConstraints[constraintId].deleted = true;\n\t\tdojo.byId(constraintId).style.display = 'none';\n\t\t// update statistics\n\t\tupdateFeatureModelStatistics( 'delete', 'constraint', {} );\n\t}",
"static get(name, id, state, opts) {\n return new Constraint(name, state, Object.assign(Object.assign({}, opts), { id: id }));\n }",
"function CrossidConstraint_Mvc(params){\n\tCatalogueConstraint_Mvc.call(this, params);\n}",
"function executeValidation(validationId) {\n\t$.ajax({\n\t\t'url' :getPhase4URL() + \"/validation/validateData?id=\"\n\t\t\t\t+ getURLParameter(\"validationId\"),\n\t\t'type' : 'get',\n\t\t'contentType' : \"application/json; charset=utf-8\",\n\t\t'dataType' : \"json\",\n\t\t\n\t\tsuccess : function(response) {\n\t\t\tvar response = JSON.parse(JSON.stringify(response));\n\n\t\t\tif(response.hasOwnProperty('countermeasures')){\n\t\t\t\t//validazione fallita\n\t\t\t\tshowElementsValidationFailed(response);\n\t\t\t} else {\n\t\t\t\t//validazione effettuata con successo\n\t\t\t\t $('#groupButtonSuccess').show();\n\t\t\t}\n\t\t},\n\t\terror : function(response) {\n\t\t\talert(response.errorCode + \" \" + response.message);\n\t\t}\n\t});\n}",
"function submitID( id ) {\r\n\tfindPrecinct( null, id );\r\n}",
"doConstraints() {\n this.constraint_set.forEach((constraint, _) => {\n constraint.constrain(this.s1, this.s2);\n });\n }",
"function ID() {\n return Validator(function (input) {\n var value = convert.toInt(input);\n assert.isGreaterThan(0, value);\n return value;\n }, ID.name);\n}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('parentalrule', 'delete', kparams);\n\t}",
"function checkId(id, res) {\n const { ObjectId } = require(\"mongodb\");\n if (!ObjectId.isValid(id)) {\n res.status(400).json({ error: \"ID is invalid\" });\n return;\n }\n}",
"static async insertTrueForGuardianApproved(id) {\n try {\n const query = `UPDATE volunteer_activities SET guardian_approval = true WHERE id = ${id};`;\n const response = await db.result(query);\n return response;\n } catch (error) {\n console.log(error.message);\n return error.message;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recontruct the world from past epochs | async build (history, getCurrent) {
// Get epoch models sorted oldest to most recent
this.history = history ? history.map(item => {
return item instanceof Epoch ? item : new Epoch(item);
}).sort((a, b) => {
return parseInt(a._signed_.number) - parseInt(b._signed_.number);
}) : [];
if (this.history.length > 0) { // If historical epochs provided
// Iterate through historical epochs to build world
for (let i = 0; i < this.history.length; i++) {
const epoch = new Epoch(this.history[i].payload);
// Download signal data and load into epoch.
// Epoch contains the logic for decoding the
// data and applying each signal to the state.
// If not first epoch, initialize states with
// corresponding final states of previous epoch.
const data = await this.getTorrentData(epoch);
const body = data instanceof Buffer ? data : Buffer.from(data);
await epoch.data(body, (state) => {
return Buffer.from(this.epoch.state[state.name].compressed);
});
// Fire event with inflated epoch
this.event('onBuild', epoch);
this.epoch = epoch;
}
// Initialize the most recent epoch
this.epoch = await this.epoch.next({ name: this.signer });
} else { // Current epoch defaults to genesis
this.epoch = new Epoch({
name: this.signer,
alpha: this.genesis,
number: 0
});
}
// Apply current epoch signals, if provided
if (getCurrent) {
const current = await getCurrent(this.epoch);
for (let signal of current) {
this.receive(signal);
}
}
// Prepare to receive new signals
this.listen(true);
} | [
"function epoch(currentEpoch) {\n\n // Randomize the order of the cities and loop through them\n var rndCityIndices = shuffleArray(Array.apply(null, { length: numCities }).map(Number.call, Number));\n\n for (var i = 0; i < numCities; i++) {\n\n var city = cities[rndCityIndices[i]];\n var winningNodeIdx = euclideanDistance(W, city);\n\n for (var nodeIdx = 0; nodeIdx < numNodes; nodeIdx++) {\n\n var theta = neighborhoodGaussian(winningNodeIdx, nodeIdx, currentEpoch, numNodes);\n W[nodeIdx][0] = W[nodeIdx][0] + theta * learningRate * (city[0] - W[nodeIdx][0]);\n W[nodeIdx][1] = W[nodeIdx][1] + theta * learningRate * (city[1] - W[nodeIdx][1]);\n\n var nodeShape = drawableNodes[nodeIdx];\n nodeShape.x = W[nodeIdx][0];\n nodeShape.y = W[nodeIdx][1];\n }\n }\n\n // Update line graphics\n for (var lineIdx = 1; lineIdx < drawableLines.length; lineIdx++) {\n updateLine(drawableLines[lineIdx - 1], W[lineIdx - 1][0], W[lineIdx - 1][1], W[lineIdx][0], W[lineIdx][1]);\n }\n\n // Update the final line. This call is required since the graph is circular\n updateLine(drawableLines[numNodes - 1], W[numNodes - 1][0], W[numNodes - 1][1], W[0][0], W[0][1]);\n}",
"getFinalState() { \r\n let copy = this.getCopy(t)\r\n while(copy.maneuvers.length > 0) {\r\n copy.doNextManeuver(false)\r\n }\r\n copy.time = copy.epoch;\r\n return copy;\r\n }",
"initializeWorld() {\n this.world = new World(this.seed);\n }",
"function initialWorld(){\n var world = new World();\n world.images = getImages();\n \n return world;\n}",
"function newMap(){\n\tresetVars();\n\tisNew = true;\n\n\tworld = new Array(WORLDHEIGHT);\n\n\tupdateMap();\n\tisNew = false;\n}",
"function World(){\n\tthis.players = [];\n}",
"updateEpoch(layerDateEpoch) {\n this.setState({\n epochStart: layerDateEpoch - oneDayEpoch,\n epochEnd: layerDateEpoch + oneDayEpoch,\n });\n }",
"createNewEpochOnDropedpPosition(position){\r\nconsole.log(this.state.setupRules)\r\n let prevRule = this.state.setupRules;\r\n let count = prevRule.length+1\r\n let epochInfo = this.getEpochConfigJSON();\r\n epochInfo.name = \"Epoch\"+count;\r\n epochInfo.description = \"\";\r\n epochInfo.during_status = \"\";\r\n epochInfo.ending_status = \"\";\r\n epochInfo.drop_from = \"\";\r\n epochInfo.nodeKey = \"epoch_\"+Common.getRandomNumber();//10 digit alphanumeric value\r\n epochInfo.position = position\r\n prevRule.push(epochInfo);\r\n this.setState(prevRule);\r\n }",
"enterEpoch(ctx) {\n\t}",
"function initWorldStatus(){\n var squares = []\n for (var i = 1; i <= WUMPUS_WORLD_SIZE; i++) {\n for (var j = 1; j <= WUMPUS_WORLD_SIZE; j++) {\n squares.push({x: i, y: j});\n }\n };\n world_status.squares = squares;\n }",
"function WorldFactory() {}",
"function World(ts, tq, td, es, ct, st, mt) { // t = type, s = size, q = quantity\n\tWorld.TILES = {\n\t'Size' : ts, //cubic kilometers\n\t'Quantity' : tq,\n\t'Divisor' : td,\n\t'UnitOfMeasure' : \"KM\",\n\t};\n\tWorld.LANDSCAPE = [];\n\tWorld.LANDSCAPE.CloudDensity = [];\n\tWorld.LANDSCAPE.Terrain = [];\n\tWorld.LANDSCAPE.Ownership = [];\n\tWorld.LANDSCAPE.Ownership.Worker = [];\n\tWorld.LANDSCAPE.Ownership.Leader = [];\t\n\tWorld.LANDSCAPE.Ownership.Settlers = [];\t\t\n\tWorld.LANDSCAPE.Ownership.Gatherer = [];\t\n\tWorld.LANDSCAPE.Ownership.Farmer = [];\t\n\tWorld.LANDSCAPE.Ownership.Miner = [];\t\n\tWorld.LANDSCAPE.Ownership.Builder = [];\t\n\tWorld.LANDSCAPE.Ownership.Swordsman = [];\t\n\tWorld.LANDSCAPE.Ownership.Spearman = [];\t\n\tWorld.LANDSCAPE.Ownership.Knight = [];\t\n\tWorld.LANDSCAPE.Ownership.Pikeman = [];\t\t\n\tWorld.LANDSCAPE.Ownership.Barracks = [];\t\n\tWorld.LANDSCAPE.Ownership.Farm = [];\n\tWorld.LANDSCAPE.Ownership.Repository = [];\n\n\tWorld.LANDSCAPE.Terra = {\n\t0 : 'Mountains',\n 1 : 'Plains',\n\t2 :'Hills',\n\t3 : 'Grasslands',\n\t4 : 'Swamps'\n\t};\n\tWorld.Epoch = {\n\t'Epoch' : es,\n\t'Day' : 0,\n\t'Hours' : 0,\n\t'Minutes' : 0,\n\t'Seconds' : 0,\n\t'GameSeconds' : 0\n\t};\n\tWorld.CLOUDS = {\n\t'Type' : ct,\n\t'Coverage' : [],\n\t};\n\tWorld.SUN = true;\n\tWorld.MOON = true;\n\t}",
"function nextStep(world) {\n var elem = function(v, arr) {\n return (arr.some(val => val == v))\n }\n \n return world.map((v, y) =>\n v.map(function(val, x) {\n var lRound = lifeAround(y, x, world)\n // DEBUG: console.log(y.toString(), \",\" , x.toString(), \": \" + lRound)\n return elem(lRound, birthN) ?\n 1 :\n (elem(lRound, liveN) ?\n val :\n 0)}))\n }",
"function generate_world() {\n const rand_seed = get_random_seed();\n Math.seedrandom(rand_seed);\n\n // Default world parameters\n let starting_density = 0.01;\n let ignition_rate = 0.000001;\n\n if (DEBUG_MODE) {\n starting_density = 1;\n ignition_rate = 0;\n }\n\n // Get current window size\n const width = window.innerWidth;\n const height = window.innerHeight;\n\n // TODO: Use the size of the content div container to exclude the navbar\n // Calculate number of rows and cols in the grid based on window size\n const rows = Math.ceil(height / grid_size);\n const cols = Math.ceil(width / grid_size);\n\n const new_world = new World(rows, cols, starting_density, ignition_rate)\n\n new_world.populate();\n\n return new_world\n}",
"function seed() {\n\t\t\tvar bbox = L.latLngBounds(L.latLng(-10,50), L.latLng(-4,60));\n\t\t\tEsri_WorldShadedRelief.seed( bbox, 0, 10 );\n\t\t}",
"nextEpochServer() {\n this.serverEpoch += 1;\n assert(this.clientEpoch === this.serverEpoch, 'mismatch epoches');\n }",
"function generate() {\n objects = [];\n layers = [];\n if ( world.hasChildNodes() ) {\n while ( world.childNodes.length >= 1 ) {\n world.removeChild( world.firstChild );\n }\n }\n for( var j = 0; j < 5; j++ ) {\n objects.push( createCloud() );\n }\n}",
"function populateFutureTimeline() {\n // Same as with the past timeline\n\n let dataPoint = document.querySelector(\"#future-data-point\");\n let parentContainer = document.querySelector(\"#future-parent-container\");\n\n let startingYear = futureYearsArray[0];\n parseInt(startingYear);\n\n for (let i = 1; i < futureYearsArray.length; i++) {\n let currentYear = futureYearsArray[i];\n parseInt(currentYear);\n\n let yDistance = (currentYear - startingYear) * 240 + 2450;\n\n yFutureDataPointsArray.push(yDistance);\n\n let cloneDP = dataPoint.cloneNode(true);\n cloneDP\n .querySelector(\".outer-circle\")\n .setAttribute(\"transform\", `matrix(1,0,0,1,918.5,${yDistance})`);\n cloneDP\n .querySelector(\".inner-circle\")\n .setAttribute(\"transform\", `matrix(1,0,0,1,918.5,${yDistance})`);\n parentContainer.appendChild(cloneDP);\n }\n\n createYearsTimeline();\n}",
"function lifeCycle(){\n\n yolkWorld.forEach(function(yolk) {\n \n // Decay happiness based on birthNumber and rate\n if(yolk.birthNumber >= 2){\n // console.log(\"Before: \" + yolk.happinessScale);\n var equation = 11/ (yolk.birthNumber * 7);\n yolk.happinessScale = yolk.happinessScale - equation;\n }\n else if(yolk.birthNumber == 1){\n // console.log(yolk.happinessScale);\n var equation = 11/12;\n yolk.happinessScale = yolk.happinessScale - equation;\n }\n\n else if(yolk.birthNumber == 0){\n var equation = 11/10;\n yolk.happinessScale = yolk.happinessScale - equation; \n }\n\n //Check happiness to change state and animation\n if(yolk.happinessScale < 6 && yolk.happinessScale > 3)\n {\n yolk.sm.transition('happy_to_neutral', 'happy', 'neutral', changeState);\n }\n else if(yolk.happinessScale < 3)\n {\n yolk.sm.transition('neutral_to_sad', 'neutral', 'sad', changeState);\n }\n\n // When happiness = 0 stop decay\n if(yolk.happinessScale < 0)\n {\n yolk.happinessScale = 0;\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
code to get Restricted locations data | function hrAuthRestrictedRole() {
gso.getCrudService().execute(constants.get,'/api-config/v1/company/'+gso.getAppConfig().companyId+ "/" +gso.getAppConfig().userId+'/locations',null,
function (response) {
$scope.locationsData = response;
},
function (data) {
}
);
} | [
"function u(){n.getData(m.getParameterizedUrl(\"FIND_ACCESSIBLE_SYSTEM_LOCATION\"),null,function(b){a.accessabelSystemLocation=b.data,a.accessabelSystemLocation&&!o.isEmpty(a.accessabelSystemLocation)&&(a.whetherSystemUser=!0)},function(a){o.isEmpty(a.data)||o.isEmpty(a.data.messages[0])||g(\"error\",i.instant(a.data.messages[0]))})}",
"function z(){n.getData(o.getParameterizedUrl(\"FIND_ACCESSIBLE_SYSTEM_LOCATION\"),null,function(b){a.accessabelSystemLocation=b.data,a.accessabelSystemLocation&&!p.isEmpty(a.accessabelSystemLocation)&&(a.whetherSystemUser=!0)},function(a){p.isEmpty(a.data)||p.isEmpty(a.data.messages[0])||g(\"error\",j.instant(a.data.messages[0]))})}",
"function z(){o.getData(n.getParameterizedUrl(\"FIND_ACCESSIBLE_SYSTEM_LOCATION\"),null,function(b){a.accessabelSystemLocation=b.data,a.accessabelSystemLocation&&!p.isEmpty(a.accessabelSystemLocation)&&(a.whetherSystemUser=!0)},function(a){p.isEmpty(a.data)||p.isEmpty(a.data.messages[0])||g(\"error\",i.instant(a.data.messages[0]))})}",
"function t(){k.getData(l.getParameterizedUrl(\"FIND_ACCESSIBLE_SYSTEM_LOCATION\"),null,function(b){a.accessabelSystemLocation=b.data,a.accessabelSystemLocation&&!m.isEmpty(a.accessabelSystemLocation)&&(a.whetherSystemUser=!0)},function(a){m.isEmpty(a.data)||m.isEmpty(a.data.messages[0])||f(\"error\",h.instant(a.data.messages[0]))})}",
"static list() {\n return api_base_1.default.request('locations/').then((locations) => {\n return locations.data.map(each => new Location_1.default(each));\n });\n }",
"function getLocations(){\n AuthActions.locations.getAll()\n .then(locations => setLocations(locations))\n }",
"function getLocations(distance, type, lat, lng)\r\n{\r\n\tvar xmlHttp = new XMLHttpRequest();\r\n\t//distance unused in this version\r\n\txmlHttp.open( \"GET\",\"http://api.tripadvisor.com/api/partner/2.0/map/\" + lat + \",\" + lng + \"/\" + type + \"?key=\" + KEY, false );\r\n\txmlHttp.send();\r\n\treturn xmlHttp.responseText;\r\n}",
"GetAllLocations() {\n return location_queries.GetAllLocations(this.pool);\n }",
"function fetchLocationData()\n{\n\tvar lSearchCriteria = \"\";\n\tif(frmStores.tbxSearch.text.length == 2)\n\t{\n\t\tlSearchCriteria = \"region=\"+frmStores.tbxSearch.text;\n\t}\n\telse if(frmStores.tbxSearch.text.length > 2)\n\t{\n\t\tlSearchCriteria = \"city=\"+frmStores.tbxSearch.text;\n\t}\n\tkony.application.showLoadingScreen(sknLoading,kony.i18n.getLocalizedString(\"PLEASE_WAIT\"),constants.LOADING_SCREEN_POSITION_FULL_SCREEN,true,false,null);\n\tvar lLocation_inputparam = {};\n\tlLocation_inputparam[\"serviceID\"] = \"FecthStoresData\";\n\tlLocation_inputparam[\"key\"] = gAppData.apiKey;\n\tlLocation_inputparam[\"searchCriteria\"] = lSearchCriteria;\n\tlLocation_inputparam[\"httpheaders\"] = {};\n\tlLocation_inputparam[\"httpconfigs\"] = {};\n\tvar lLocations = appmiddlewaresecureinvokerasync(lLocation_inputparam,fetchLocationData_callback);\n}",
"function getOtherLocations(curLat, curLong) { \n var response;\n var request = new XMLHttpRequest();\n var result = \"login=\" + username + \"&lat=\" + curLat + \"&lng=\" + curLong;\n \n request.open(\"POST\", \"https://radiant-ocean-68966.herokuapp.com/sendLocation\", true);\n request.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n request.onreadystatechange = function() {\n if(request.readyState == 4 && request.status == 200) {\n response = JSON.parse(request.responseText); \n displayOtherPeople(response.people);\n displayLandmarks(response.landmarks);\n }\n }\n request.send(result);\n}",
"function locationFinder() {\n\tvar locations = [];\n\n\tlocations.push(bio.contacts.location);\n\tfor (var school in educations.schools) {\n\t\tlocations.push(education.schools[school].location);\n\t}\n\n\n\n\tfor (var job in work.jobs) {\n\t\tlocations.push(work.jobs[job].location);\n\t}\n\n\treturn locations;\n}",
"function getLocations() {\n $.get(\"/api/users/\" + localStorage.getItem(\"userId\"))\n .then(res => renderLocationList(res.Locations));\n }",
"function get_loc() {\n var tmp_loc = JSON.parse(localStorage.getItem(\"locations\"));\n\n all_locations = _.pairs(tmp_loc);\n\n //console.info(\"All Locations: \" + all_locations);\n}",
"async function getLocations() {\n // gets location data\n const resp = await fetch(`locations`);\n let locations;\n if (resp.ok) {\n locations = await resp.json();\n } else {\n locations[0].locationname = 'Error loading locations! Please try again or contact the developer.';\n return locations[0].locationname;\n }\n // new user check. usercreatecheck being true indicates new user\n if (userCreateCheck) {\n showNewUserPage(locations);\n } else {\n getBreeds(locations);\n }\n}",
"getLocationsByRating(locationData) {\r\n\t\tlet currLat, currLng, minLat, maxLat, minLng, maxLng, userfcl, radius, country, score\r\n\t\tcurrLat = locationData.currLat, currLng = locationData.currLng, minLat = locationData.minLat, maxLat = locationData.maxLat\r\n\t\tminLng = locationData.minLng, maxLng = locationData.maxLng, userfcl = locationData.userfcl, country = locationData.country\r\n\t\tradius = locationData.radius, score = locationData.rating\r\n\t\treturn this.pool.queryAsync('call radial_search_rating(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',\r\n\t\t\t[currLat,\r\n\t\t\tcurrLng,\r\n\t\t\tminLat,\r\n\t\t\tmaxLat,\r\n\t\t\tminLng,\r\n\t\t\tmaxLng,\r\n\t\t\tuserfcl,\r\n\t\t\tradius,\r\n\t\t\tscore,\r\n\t\t\tcountry])\r\n\t\t \t.then((resolve) => {\r\n\t\t\t\treturn resolve\r\n\t\t\t}).catch((err) => {\r\n\t\t\t\tthrow err\r\n\t\t\t})\r\n\t}",
"getLocationList() {\n return async function() {\n let locationNames = await this._model.find({}, 'locationName -_id');\n let filteredNames = [];\n \n // Take out duplicate location names, and the N/A one for the admin.\n locationNames.forEach(user => filteredNames.indexOf(user.locationName) === -1 ? filteredNames.push(user.locationName) : undefined);\n //filteredNames.splice(filteredNames.indexOf(\"N/A\"), 1); UNCOMMENT TO REMOVE ADMIN ACCOUNT\n return filteredNames;\n }.bind(this)();\n }",
"get locations() { return this.locations_.values(); }",
"_getDataByGpsLocation(){\n\n // Handle iOS and Android dangerous permissions\n Permissions.request(PERMISSION_LOCATION_VALUE).then(response => {\n console.log(response);\n if(response === PERMISSION_RESPONSE_DENIED_VALUE || response === PERMISSION_RESPONSE_RESTRICTED_VALUE || response === PERMISSION_RESPONSE_UNDETERMINED_VALUE){\n this._platformGpsSettingPrompt();\n return \n }\n\n // Returns once the user has chosen to 'allow' or to 'not allow' access\n // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'\n navigator.geolocation.getCurrentPosition(data => {\n\n this._userLat = data.coords.latitude;\n this._userLng = data.coords.longitude;\n \n // We cache this location to later be able to\n // determine if the use has panned the map.\n // If the map is panned past the threshold \n // the user will be presented with a redo search \n // in this area button.\n this._currentRegionLat = data.coords.latitude;\n this._currentRegionLng = data.coords.longitude;\n \n // Fetch project data by location and radius \n this.props.getProjectsByLocation(this._userLat, this._userLng, this.state.radius, PROJECT_FETCH_LIMIT_NUMBER);\n this.setState({gpsEnabled: GPS_ENABLED_TRUE_BOOL});\n }, error => {\n this._platformGpsSettingPrompt();\n }, {\n enableHighAccuracy: GPS_HIGH_ACCURACY_BOOL // Allows for high accuracy gps coordinates\n });\n\n });\n\n }",
"function restrictLocations(locations, restrictions, level) {\n var restrictedLocations = [];\n for (var locationsIndex=0; locationsIndex < locations.length; locationsIndex++) {\n var location = locations[locationsIndex];\n for (var restrictionsIndex=0; restrictionsIndex < restrictions.length; restrictionsIndex++) {\n var restriction = restrictions[restrictionsIndex];\n if (restriction.name === location.name && restriction.id === location.id && restriction.level === level) {\n restrictedLocations.push(locations[locationsIndex]);\n }\n }\n }\n return restrictedLocations;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load tags that a user just added for both websites | function loadTags(website, tags) {
var site = '#' + website;
var editor = $(site).next('.CodeMirror')[0].CodeMirror;
var tag_names = "";
var colors = ['red', 'pink', 'yellow', 'purple', 'deep-purple', 'indigo', 'blue', 'light-blue', 'cyan', 'teal', 'green', 'light-green', 'lime', 'amber', 'orange', 'deep-orange', 'brown', 'blue-grey'];
for (var tag in tags) {
var ri = Math.floor(Math.random() * colors.length);
var rs = colors.splice(ri, 1);
var random_color = rs + ' lighten-4';
var website_tag = '<div class="chip-wrapper"><div class="chip ' + random_color + '">' + tag + '<span class="tag-count">' + tags[tag].count + '</span></div></div>';
var comments = tags[tag].comments;
var tag_comments = "";
for (var c in comments) {
tag_comments += '<div class="comment"><p>"' + comments[c].comment + '" - ' + comments[c].name + '</p></div>';
}
var highlights = tags[tag].highlights;
for (var h in highlights) {
loadHighlight(editor, highlights[h], random_color);
}
tag_names += '<div class="tag-wrapper">' + website_tag + tag_comments + '</div>';
}
$('#annotations .row').append('<div class="col s6"><div class="card"><div class="card-content"><span class="card-header">Other users have tagged this code as:</span><div class="card-content">' + tag_names + '</div></div></div></div>');
} | [
"function getUserTags(username) {\n\tvar query = \"SELECT Content.id, username_tagger, username_taggee, Tag.timest \" +\n\t\t\t\t\"FROM Tag, Content WHERE Tag.id = Content.id AND username_taggee = ? AND status IS false\";\n\treturn new Promise((resolve, reject) => {\n\t\tconnection.query(query, username, (err, rows) => {\n\t\t\tif (err) return reject(err);\n\t\t\tif (rows.length === 0) resolve(null);\n\t\t\telse { resolve(rows); }\n\t\t})\n\t})\n}",
"function loadTags() {\n\t\tlet tags = new wp.api.collections.Tags()\n\n\t\ttags.fetch().done( () => {\n\t\t\tconsole.log(tags);\n\t\t\t\t//clearCategories();\n\t\t\t\ttags.each( tag => loadTag( tag.attributes ) );\n\t\t});\n\t}",
"function syncUserTags() {\n\t\t\tvar userTags = User.getSelectedTags();\n\t\t\t\n\t\t\tfor (var k = 0; k < userTags.length; k++) {\t\t\t\n\t\t\t\tif(!tagExist(userTags[k])) {\n\t\t\t\t\tUser.removeTag(userTags[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"function loadRemoteData() {\n \ttagService.getTags().then(\n function( tags ) {\n applyRemoteData( tags );\n });\n }",
"async loadTags() {\n let additionalTags = []\n\n /*\n If a workspace exists and user has chosen to use the workspace preferences for tags,\n else use global settings.\n */\n if (FUNCTIONS.isWorkspace() &&\n (nova.workspace.config.get('todo.workspace-custom-tags') == 'Use Workspace Preferences')) {\n additionalTags = Configuration.PREFERENCE_TAGS.filter((tag) => {\n return nova.workspace.config.get(`todo.workspace-tag-${tag}`)\n })\n } else {\n additionalTags = Configuration.PREFERENCE_TAGS.filter((tag) => {\n return nova.config.get(`todo.global-tag-${tag}`)\n })\n }\n\n let tags = [...Configuration.DEFAULT_TAGS, ...additionalTags]\n tags = tags.map((tag) => { return tag.toUpperCase() })\n\n return tags\n }",
"function getTags() {\n \n $.getJSON('js/test-data.json').success(function(data) {\n \n $.each(data.data, function(k,v) {\n $.each(v.tags, function(k,v) {\n availableTags.push(v);\n });\n });\n \n $.unique(availableTags);\n \n appendTags();\n \n });\n \n }",
"function loadTags() {\n for (var tagClass in ANDROID_TAGS) {\n for (var tag in ANDROID_TAGS[tagClass]) {\n allTags[tag] = {\n displayTag: ANDROID_TAGS[tagClass][tag],\n tagClass: tagClass\n };\n }\n }\n}",
"function loadTags() {\n\t$(\".fill-tags\").empty();\n\t$(\".fill-tags\").append(getTags());\n\tnewId = localTags.length;\n\teditable = true;\n}",
"function getTags() {\n if (localStorage.getItem('tags') === null) return;\n\n tags = JSON.parse(localStorage.getItem('tags'));\n\n tags.forEach(element => {\n addTag(element)\n });\n}",
"function addTagLinksToGlobals() { \n var tagLinks_url_prefix = 'http://' + SW.hostname + ':' + SW.port + '/tags/links/';\n var addFlag = true;\n\n for(var i = 0; i < SW.selected_tag_nids.length; i++) {\n var tagNid = SW.selected_tag_nids[i];\n $.ajax({\n type: 'GET',\n url: tagLinks_url_prefix+tagNid,\n success: function(linksData) {\n var linksArr = JSON.parse(linksData);\n \n for(var key = 0; key < linksArr.length; key++) {\n var type = linksArr[key]['type'];\n var name = linksArr[key]['name'];\n var nid = linksArr[key]['nid'];\n\n if(type == 0) { // PERSON\n addFlag = true;\n for(var i = 0; i < SW.selected_people_nids.length; i++)\n if(SW.selected_people_nids[i] == nid) addFlag = false;\n if(addFlag) {\n SW.selected_people_names.push(linksArr[key]['name']);\n SW.selected_people_nids.push(nid);\n }\n }\n else if(type == 1) { // GROUP\n addFlag = true;\n for(var i = 0; i < SW.selected_group_nids.length; i++)\n if(SW.selected_group_nids[i] == nid) addFlag = false;\n if(addFlag) {\n SW.selected_group_names.push(linksArr[key]['gname']);\n SW.selected_group_nids.push(nid);\n }\n }\n else if(type == 2) { // JOB\n addFlag = true;\n for(var i = 0; i < SW.selected_job_nids.length; i++)\n if(SW.selected_job_nids[i] == nid) addFlag = false;\n if(addFlag) {\n SW.selected_job_names.push(linksArr[key]['name']);\n SW.selected_job_nids.push(nid);\n }\n }\n else if(type == 3) { // JOB\n addFlag = true;\n for(var i = 0; i < SW.selected_app_nids.length; i++)\n if(SW.selected_app_nids[i] == nid) addFlag = false;\n if(addFlag) {\n SW.selected_app_ids.push(linksArr[key]['aid']);\n SW.selected_app_nids.push(nid);\n }\n }\n else if(type == 4) { // FILE\n addFlag = true;\n for(var i = 0; i < SW.selected_file_nids.length; i++)\n if(SW.selected_file_nids[i] == nid) addFlag = false;\n if(addFlag) {\n SW.selected_file_paths.push(linksArr[key]['path']);\n SW.selected_file_nids.push(nid);\n }\n }\n }\n $('#doiModalPeopleField').html(''+SW.selected_people_names);\n $('#doiModalGroupsField').html(''+SW.selected_group_names);\n $('#doiModalJobsField').html(''+SW.selected_job_names);\n $('#doiModalAppsField').html(''+SW.selected_app_ids);\n $('#doiModalFilesField').html(''+SW.selected_file_paths);\n },\n error: function(e) {console.log('Error in addTagLinksToGlobals(): '+e);}\n });\n }\n}",
"function loadTagCloud () {\n $('#tag-cloud-box').children('.cloud-tags').remove()\n if (tasks.tagList.length + gitHub.tagList.length + serviceNow.snTagList.length + rally.rallyTagList.length > 0) {\n const utl = [...new Set(tasks.tagList.concat(gitHub.tagList).concat(serviceNow.snTagList).concat(rally.rallyTagList))]\n utl.sort()\n utl.forEach((tag) => {\n let color = `#${asciiToHex(tag)}`\n color = hexToHSL(color, 60)\n $('#tag-cloud-box').append(`<div class=\"cloud-tags\" style=\"background-color: ${color}\">${tag}</div>`)\n })\n }\n}",
"initTags(user) {\n this.tags = {};\n user.organization.tags.forEach(tag => {\n this.tags[tag.id] = {\n id: tag.id,\n name: tag.name,\n description: tag.description,\n users: tag.users\n };\n });\n\n user.tags.forEach(tag => {\n this.tags[tag.id].subscribed = true;\n });\n\n this.showAllTags();\n }",
"function initTags() {\n \n for (var j = $scope.QUERY.whattodo.length - 1; j >= 0; j--) {\n for (var i = $scope.tripTags.length - 1; i >= 0; i--) {\n if ($scope.QUERY.whattodo[j].slug == $scope.tripTags[i].slug) {\n $scope.local.tags.push($scope.tripTags[i]);\n break;\n }\n }\n }\n }",
"with_tags(more_tags) {\n var tags = {\n 'host': this.host\n };\n\n this.extra_tags.forEach(function (t, v) {\n tags[t] = v;\n });\n\n if (more_tags != null && typeof(more_tags) != 'undefined') {\n more_tags.forEach(function (t, v) {\n tags[t] = v;\n })\n }\n\n return tags;\n }",
"function autoLoadTags(){\n const tags = []\n for(const {name, value} of document.currentScript.attributes){\n if(name !== 'src' && name.startsWith('src'))\n tags.push({name, value})\n }\n const urls = tags\n .sort((a, b) => a.name >= b.name ? 1 : -1)\n .map(t => t.value)\n loadOneOf(urls, document.currentScript.onerror)\n}",
"function generateTags(currUser, userList, gameInfo) {\n\n}",
"function load_excluded_tags(url) {\n $('#tagcontent').hide();\n $('#excluded').load(url);\n $('#excluded').show();\n}",
"function getTagsOnStartup() {\n exports.updateTagArray().catch(function() {log.error('Failed to update the tag array on startup')})\n}",
"function loadThisTagsPosts(theTag) {\n\n theTag = theTag.replace(/_/g, ' ');\n var thisTagPosts = [];\n $.get(\"posts/posts.xml\", function(posts) {\n $(posts).find('post').each(function(i) {\n var this_post = $(this);\n // if post has tag being loaded\n this_post.find('tags').find('tag').each(function() {\n if ($(this).text() == theTag) {\n thisTagPosts.push( buildPostObj(this_post) );\n }\n }); // end each tag of post\n }); // end each post\n }).complete(function() {\n $('#main').empty();\n thisTagPosts.sort(date_sort_desc);\n buildPosts(thisTagPosts, 0, thisTagPosts.length);\n\n var tagInfo = 'Tag: ' + theTag + ' <span>' + thisTagPosts.length + ' ';\n tagInfo+= (thisTagPosts.length > 1) ? 'Posts' : 'Post';\n var tagTitle = $('<h4>').html(tagInfo+'</span>');\n $(tagTitle).insertBefore('.post:first-of-type');\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the next prefetch request should only be served from the edge cache. This is done by comparing a random number between 0 and 1 to options.forcePrefetchRatio | function shouldAcceptThrottling() {
return !options.forcePrefetchRatio || Math.random() > options.forcePrefetchRatio;
} | [
"validatePrefetch(cachedResponse) {\n const isThrottled = Object.keys(this.request.query || {}).includes(constants_1.THROTTLED_QUERY_PARAM);\n if (isThrottled && !cachedResponse) {\n this.response.writeHead(constants_1.LAYER0_UNCACHED_PREFETCH_STATUS);\n this.response.end();\n return false;\n }\n else {\n return true;\n }\n }",
"prefetchingOn() {\n this._prefetchingOn = true;\n }",
"function existNextFetch() {\r\n if (localStorage.getItem('next_fetch') !== null) return true; \r\n return false;\r\n}",
"async maybePrefetchCanteens() {\n\n if (prefetching) return false;\n prefetching = true;\n\n try {\n\n const curPos = locationManager.lastDevicePosition.coordinate;\n\n if (\n // we have the position of the device\n locationManager.lastDevicePosition.timestamp !== 0 &&\n // the traffic is unlimited\n networkManager.networkState.trafficLimit === NetworkManager.NETWORK_TRAFFIC_LIMIT.UNLIMITED &&\n // the network speed is fast\n networkManager.networkState.speed === NetworkManager.NETWORK_SPEED.FAST &&\n // we did not prefetch yet or the last prefetch is out of range\n (\n this.lastPrefetchedCanteensAt.timestamp === 0 ||\n Coordinate.calcDistance(\n this.lastPrefetchedCanteensAt.coordinate, curPos\n ) > (this.lastPrefetchedCanteensAt.distance - this.canteenTrackingRadius)\n )\n ) {\n try {\n console.log(\"Prefetching canteens...\");\n const prefetchRadius = this.canteenTrackingRadius*7.5;\n\n // fetch canteens from OpenMensa and persist them\n await this.saveCanteens( await this.fetchCanteens() );\n\n // update last prefetch position\n this.lastPrefetchedCanteensAt.timestamp = Util.currentUnixTimestamp;\n this.lastPrefetchedCanteensAt.coordinate = curPos;\n this.lastPrefetchedCanteensAt.distance = prefetchRadius;\n\n // return true\n prefetching = false;\n return true;\n } catch(e) {\n console.log(\"Could not prefetch canteens:\", e);\n }\n }\n\n } catch(e) {\n console.error(\"Unexpected error while checking the prefetch conditions:\", e);\n }\n\n prefetching = false;\n return false;\n \n }",
"_canFetch() {\n let now = Date.now();\n let elapsed = Math.floor( ( now - this.last ) / 1000 );\n let delay = this._options.fetchDelay | 0;\n\n if ( this.fetching || this.last >= now ) return false; // busy, wait\n if ( delay && elapsed < delay ) return false; // too soon, wait\n return true; // looks good\n }",
"get shouldPrefetch(){\n return this.name == \"window\" || this.name == \"this\";\n }",
"prefetchingOff() {\n this._prefetchingOn = false;\n }",
"function isRequestRecommended$static()/*:Boolean*/ {\n return networkProblemCount$static === 0 &&\n (requestThreshold$static > openRequestCount$static + openBackgroundRequestCount$static || openRequestCount$static === 0);\n }",
"function maybeAddPrefetchParam(url) {\n if (!options.includeCacheMisses && shouldAcceptThrottling()) {\n appendSearchParam(url, constants_1.PREFETCH_QUERY_PARAM, '1');\n }\n}",
"function moreDataCanBeLoaded(){\n return !stopFetching;\n }",
"isPreFetchMode() {\n\t\treturn this._preFetchMode;\n\t}",
"static warmConnections() {\n if (this.preconnected) return;\n\n this.addPrefetch('preconnect', 'https://vimeo.com');\n this.addPrefetch('preconnect', 'https://player.vimeo.com');\n this.addPrefetch('preconnect', 'https://i.vimeocdn.com');\n this.addPrefetch('preconnect', 'https://f.vimeocdn.com');\n\n this.preconnected = true;\n }",
"async canHandle(e) { \n if (!_cacheReady[_getCacheKey(this.appName, this.version)]) {\n LOG.debug(`Cache not ready for app ${this.appName}, version ${this.version}, refusing to handle request ${e.request.url}.`)\n return false;\n }\n\n if (RequestHandler.#justURL(e.request.url).endsWith(MONKSHU_CONSTANTS.FORCE_NETWORK_FETCH)) return true; // can always network fetch\n\n const cache = await caches.open(_getCacheKey(this.appName, this.version));\n if (await cache.match(RequestHandler.#justURL(e.request.url))) return true;\n else return false;\n }",
"addRequestAndCheckIfRateLimited() {\n return __awaiter(this, void 0, void 0, function* () {\n const now = new Date().getTime();\n this.requestCounter = this.requestCounter.filter((date) => date + this.rateLimitWindowInSeconds * 1000 > now);\n this.requestCounter.push(now);\n return this.requestCounter.length > this.rateLimit;\n });\n }",
"addRequestAndCheckIfRateLimited() {\n return __awaiter(this, void 0, void 0, function*() {\n const now = new Date().getTime();\n this.requestCounter = this.requestCounter.filter((date)=>date + this.rateLimitWindowInSeconds * 1000 > now\n );\n this.requestCounter.push(now);\n return this.requestCounter.length > this.rateLimit;\n });\n }",
"shouldBeSent(){\n return this.redundancy > this.currentProcessorCount + (2*this.totalCount - this.majorityCount);\n }",
"canRequest() {\n return this.requestQueue.size < this.requestQueueSize;\n }",
"#shouldFetch(key) {\n return !Object.prototype.hasOwnProperty.call(this.fetches, key) || this.fetches[key].fetch\n }",
"shouldPreloadNextSlide() {\n\t\tconst { i } = this.props\n\t\treturn this.didScrollThroughSlides || i === 0\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset environment variables used by JSDoc to the default values for tests. | function resetJsdocEnv() {
const env = require('jsdoc/env');
env.conf = {
tags: {
dictionaries: ['jsdoc']
},
templates: {
cleverLinks: false,
monospaceLinks: false
}
};
env.dirname = path.resolve(__dirname, '../../node_modules/jsdoc');
env.opts = {
// list of source files parsed by JSDoc
_: [],
// encoding for reading/writing files
encoding: 'utf8',
// destination for template output
destination: './out/',
// path to the JSDoc template
template: path.resolve(__dirname, '../..')
};
env.version = {
number: '1.2.3.4'
};
} | [
"static resetEnvVariables() {\n for (const k in TestEnvConfig) {\n delete process.env[k];\n }\n TestEnvConfig = {};\n }",
"function reset() {\n environment = { ...defaultEnvironment };\n}",
"function clear() {\n const env = getEmptySlateEnv();\n SLATE_ENV_VARS.forEach(key => process.env[key] = '');\n}",
"function clear() {\n SLATE_ENV_VARS.forEach((key) => (process.env[key] = ''));\n}",
"function resetEnvironment() {\n\t// the idea behind the OR conditions is, that if the env. variable is declared\n\t// from the outside, then use this value to override the environment each time.\n\t// else, just use the default values supplied.\n\tprocess.env.MONGO_HOST = MONGO_HOST || 'localhost';\n\tprocess.env.MONGO_PORT = MONGO_PORT || '27017';\n\tprocess.env.MONGO_DATABASE = MONGO_DATABASE || 'replay_test_consumer';\n\tprocess.env.STORAGE_PATH = path.join(__dirname, 'data');\n\tprocess.env.CAPTURE_STORAGE_PATH = path.join(process.env.STORAGE_PATH, 'capture');\n\tprocess.env.RABBITMQ_HOST = RABBITMQ_HOST || 'localhost';\n\tprocess.env.RABBITMQ_PORT = RABBITMQ_PORT || '5672';\n\tprocess.env.RABBITMQ_USERNAME = RABBITMQ_USERNAME || 'guest';\n\tprocess.env.RABBITMQ_PASSWORD = RABBITMQ_PASSWORD || 'guest';\n\tprocess.env.RABBITMQ_MAX_RESEND_ATTEMPTS = RABBITMQ_MAX_RESEND_ATTEMPTS || 1;\n}",
"function clear() {\n PACKER_ENV_VARS.forEach((key) => (process.env[key] = ''));\n}",
"static reset() {\r\n EnvironmentConfiguration._rushTempFolderOverride = undefined;\r\n EnvironmentConfiguration._hasBeenInitialized = false;\r\n }",
"async function setLocalEnvDefaults(context) {\n const projectPath = process.cwd();\n const defaultEditor = 'vscode';\n const envName = 'sampledev';\n context.print.warning(`Setting default editor to ${defaultEditor}`);\n context.print.warning(`Setting environment to ${envName}`);\n context.print.warning('Run amplify configure project to change the default configuration later');\n context.exeInfo.localEnvInfo = {\n projectPath,\n defaultEditor,\n envName,\n };\n context.exeInfo.inputParams.amplify.envName = envName;\n await generateLocalEnvInfoFile(context);\n}",
"beforeEach() {\n // TODO: Add any logic needed to reset the test environment before each test\n }",
"static async resetTestingModule() {\n await TestMind.terminate();\n\n TestModuleImports = [];\n TestModuleProviders = [];\n TestApplicationModule = undefined;\n testAppInstance = undefined;\n TestMind.resetEnvVariables();\n }",
"function reset() {\n compilers = u.filter(compilers, 'isDefault');\n macros = u.filter(macros, 'isDefault');\n }",
"static reset() {\n // Use the defaults\n Object.assign(Flags, FlagDefaults);\n // Overwrite the defaults with the testFlags.\n if (typeof global !== 'undefined') {\n Object.assign(Flags, global['testFlags']);\n }\n }",
"function reset() {\n\t\tfor (let key in defaultValues) {\n\t\t\tsetSetting(key, getDefaultValue(key));\n\t\t}\n\t}",
"function reset() {\n settings = _UtilsJs2['default'].clone(defaultSettings);\n }",
"function reset() {\r\n\t\tfor (let key in defaultValues) {\r\n\t\t\tsetSetting(key, getDefaultValue(key));\r\n\t\t}\r\n\t}",
"function reset() {\n settings = _Utils_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"].clone(defaultSettings);\n }",
"function reset$1() {\n mergeOptions(globalOptions, defaultOptions);\n}",
"function reset() {\n compilers = u.filter(compilers, 'isDefault')\n macros = u.filter(macros, 'isDefault')\n }",
"static setImportantEnvVariable() {\n if (Cypress.env('IMPORTANT_VAR')) {\n cy.log('Important variable already set by another test')\n return \n }\n Cypress.env('IMPORTANT_VAR', 'IMPORTANT_VAR_VALUE')\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
; public static const ISSUE_ELEMENT_LINK:BEMElement = | function ISSUE_ELEMENT_LINK$static_(){IssuesPanelBase.ISSUE_ELEMENT_LINK=( IssuesPanelBase.ISSUE_BLOCK.createElement("link"));} | [
"function ISSUE_BLOCK$static_(){IssuesPanelBase.ISSUE_BLOCK=( new com.coremedia.ui.models.bem.BEMBlock(\"cm-issue\"));}",
"function EBX_Constants() {\r\n\r\n}",
"function EBX_Constants() {\n\n}",
"function ELEMENT_ICON$static_(){IconWithTextBEMEntities.ELEMENT_ICON=( IconWithTextBEMEntities.BLOCK.createElement(\"icon\"));}",
"function ISSUE_ELEMENT_LIST$static_(){IssuesPanelBase.ISSUE_ELEMENT_LIST=( IssuesPanelBase.ISSUE_BLOCK.createElement(\"list\"));}",
"get link () {\n return new IconData(0xe157,{fontFamily:'MaterialIcons'})\n }",
"function getLinkValue(link) {\n return link.substring(link.indexOf(enum_1.default.T_link) + 5);\n}",
"get insert_link () {\n return new IconData(0xe250,{fontFamily:'MaterialIcons'})\n }",
"function ISSUE_ELEMENT_TEXT$static_(){IssuesPanelBase.ISSUE_ELEMENT_TEXT=( IssuesPanelBase.ISSUE_BLOCK.createElement(\"text\"));}",
"function useMngLblLnk()\n {\n this.ruleID = 'useMngLblLnk';\n }",
"function ELEMENT_ITEM$static_(){IssuesPanelBase.ELEMENT_ITEM=( IssuesPanelBase.BLOCK.createElement(\"item\"));}",
"get linkType() {\n return this.typeInternal;\n }",
"get PREF_BRANCH() { return \"extensions.firefm.\"; }",
"constructor() { \n \n IssueLinkType.initialize(this);\n }",
"get link_off () {\n return new IconData(0xe16f,{fontFamily:'MaterialIcons'})\n }",
"function LinkTypeHelper() {\n}",
"_addMessageReference(element, key) {\n const registeredMessage = messageRegistry.get(key);\n // Add the aria-describedby reference and set the\n // describedby_host attribute to mark the element.\n addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);\n element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, '');\n registeredMessage.referenceCount++;\n }",
"function PROJECT_ELEMENT_ICON$static_(){ProjectsTodosWidgetProject.PROJECT_ELEMENT_ICON=( ProjectsTodosWidgetProject.PROJECT_BLOCK.createElement(\"icon\"));}",
"get concepttypeHref() {\n return this.conceptTypeLink.href;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The CenterControl adds a control to the map that recenters the map on Chicago. This constructor takes the control DIV as an argument. | function CenterControl(controlDiv, map) {
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#fff';
controlUI.style.border = '2px solid #fff';
controlUI.style.borderRadius = '3px';
controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '22px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to recenter the map';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.color = 'rgb(25,25,25)';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '5px';
controlText.style.paddingRight = '5px';
controlText.innerHTML = 'Center Haiti Map';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to Chicago.
controlUI.addEventListener('click', function() {
map.setCenter(centerHaiti);
map.setZoom(8);
});
} | [
"function CenterControl(controlDiv, map) {\n \n // Set CSS for the control border.\n var controlUI = document.createElement('div');\n controlUI.className=\"mapCenterButton\"\n controlUI.title = 'Click to recenter the map';\n controlDiv.appendChild(controlUI);\n \n // Set CSS for the control interior.\n var controlText = document.createElement('div');\n controlText.style.color = 'rgb(25,25,25)';\n controlText.style.fontFamily = 'Roboto,Arial,sans-serif';\n controlText.style.fontSize = '16px';\n controlText.style.lineHeight = '38px';\n controlText.style.paddingLeft = '5px';\n controlText.style.paddingRight = '5px';\n controlText.innerHTML = '<span class=\"icon-centerMap icon ion-pinpoint\"></span>';\n controlUI.appendChild(controlText);\n \n // Setup the click event listeners: simply set the map to Chicago.\n controlUI.addEventListener('click', function() {\n map.setCenter(latLng);\n });\n \n }",
"function CenterControl(controlDiv, map) {\r\n\r\n // Set CSS for the control border.\r\n var controlUI = document.createElement('div');\r\n controlUI.style.backgroundColor = '#fff';\r\n controlUI.style.border = '2px solid #fff';\r\n controlUI.style.borderRadius = '3px';\r\n controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\r\n controlUI.style.cursor = 'pointer';\r\n controlUI.style.marginBottom = '22px';\r\n controlUI.style.marginTop = '6px';\r\n controlUI.style.textAlign = 'center';\r\n controlUI.title = 'Click to recenter the map';\r\n controlDiv.appendChild(controlUI);\r\n\r\n // Set CSS for the control interior.\r\n var controlText = document.createElement('div');\r\n controlText.style.color = 'rgb(25,25,25)';\r\n controlText.style.fontFamily = 'Roboto,Arial,sans-serif';\r\n controlText.style.fontSize = '16px';\r\n controlText.style.lineHeight = '38px';\r\n controlText.style.paddingLeft = '5px';\r\n controlText.style.paddingRight = '5px';\r\n controlText.innerHTML = ' Center S. GA';\r\n controlUI.appendChild(controlText);\r\n\r\n // Setup the click event listeners: simply set the map to Chicago.\r\n var flag = true\r\n controlUI.addEventListener('click', function() {\r\n if (flag) {\r\n map.setCenter({lat: 31.232117, lng: -84.210631});\r\n controlText.innerHTML = 'Center ATL';\r\n flag = false;\r\n } else {\r\n map.setCenter({lat: 33.746511, lng: -84.388339});\r\n controlText.innerHTML = ' Center S. GA';\r\n flag = true;\r\n };\r\n });\r\n\r\n }",
"function CenterControl(controlDiv, map) {\n\t\t\n\n // Set CSS for the control border.\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = '#fff';\n controlUI.style.border = '2px solid #fff';\n controlUI.style.borderRadius = '3px';\n controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\n controlUI.style.cursor = 'pointer';\n controlUI.style.marginBottom = '22px';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to recenter the map';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior.\n var controlText = document.createElement('div');\n controlText.style.color = 'rgb(25,25,25)';\n controlText.style.fontFamily = 'Roboto,Arial,sans-serif';\n controlText.style.fontSize = '16px';\n controlText.style.lineHeight = '38px';\n controlText.style.paddingLeft = '5px';\n controlText.style.paddingRight = '5px';\n controlText.innerHTML = 'Nearby';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to Chicago.\n controlUI.addEventListener('click', function() {\n //map.setCenter(chicago);\n\t\t\t//alert(' in set center ');\n\t\t\tinfoWindow = new google.maps.InfoWindow;\n\t\t if (navigator.geolocation) {\n\t\t\t\tnavigator.geolocation.getCurrentPosition(function(position) {\n\t\t\t\tvar pos = {\n\t\t\t\t lat: position.coords.latitude,\n\t\t\t\t lng: position.coords.longitude\n\t\t\t\t};\n\n\t\t\t\t//infoWindow.setPosition(pos);\n\t\t\t\t//infoWindow.setContent('Location found.');\n\t\t\t\t//infoWindow.open(map);\n\t\t\t\tmap.setCenter(pos);\n\t\t\t\tmap.setZoom(17);\n\t\t\t }, function() {\n\t\t\t\thandleLocationError(true, infoWindow, map.getCenter());\n\t\t\t });\n\t\t\t}\n });\n\n }",
"function CenterControl(controlDiv, map) {\n // Set CSS for the control border.\n const controlUI = document.createElement(\"div\");\n controlUI.style.marginRight = \"25px\";\n controlUI.style.backgroundColor = \"#fff\";\n controlUI.style.border = \"2px solid #fff\";\n controlUI.style.borderRadius = \"3px\";\n controlUI.style.boxShadow = \"0 2px 6px rgba(0,0,0,.3)\";\n controlUI.style.cursor = \"pointer\";\n controlUI.style.marginBottom = \"22px\";\n controlUI.style.textAlign = \"center\";\n controlUI.title = \"Click to recenter the map\";\n controlDiv.appendChild(controlUI);\n // Set CSS for the control interior.\n var reload = '<i style=\"font-size:20px\" class=\"fa\"></i>';\n const controlText = document.createElement(\"div\");\n controlText.style.color = \"rgb(25,25,25)\";\n controlText.style.fontFamily = \"Roboto,Arial,sans-serif\";\n controlText.style.fontSize = \"20px\";\n controlText.style.lineHeight = \"38px\";\n controlText.style.paddingLeft = \"5px\";\n controlText.style.paddingRight = \"5px\";\n controlText.innerHTML = \"現在地 \" + reload;\n controlUI.appendChild(controlText);\n // Setup the click event listeners: simply set the map to Chicago.\n controlUI.addEventListener(\"click\", () => {\n map.setCenter(new google.maps.LatLng(35.08969903728947, 139.06380775082175));\n });\n }",
"function initMap() {\n map = new google.maps.Map(document.getElementById('map'), {\n zoom: 11,\n center: centerNash,\n mapTypeId: 'roadmap',\n scrollwheel: false\n });\n\n // Create the DIV to hold the control and call the CenterControl()\n // constructor passing in this DIV.\n var centerControlDiv = document.createElement('div');\n var centerControl = new CenterControl(centerControlDiv, map);\n\n centerControlDiv.index = 1;\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);\n\n}",
"function CenterControl(controlDiv, map) {\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = '#fff';\n controlUI.style.border = '2px solid #fff';\n controlUI.style.borderRadius = '3px';\n controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\n controlUI.style.cursor = 'pointer';\n controlUI.style.float = 'left';\n controlUI.style.marginBottom = '22px';\n controlUI.style.marginLeft = '12px';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to recenter the map';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var goCenterText = document.createElement('div');\n controlUI.style.color = 'rgb(25,25,25)';\n controlUI.style.fontFamily = 'Roboto,Arial,sans-serif';\n controlUI.style.fontSize = '16px';\n controlUI.style.lineHeight = '38px';\n controlUI.style.paddingLeft = '5px';\n controlUI.style.paddingRight = '5px';\n controlUI.innerHTML = 'Center Map';\n controlUI.appendChild(goCenterText);\n\n // Set CSS for the goToToday control border\n var todayUI = document.createElement('div');\n todayUI.style.backgroundColor = '#fff';\n todayUI.style.border = '2px solid #fff';\n todayUI.style.borderRadius = '3px';\n todayUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\n todayUI.style.cursor = 'pointer';\n todayUI.style.float = 'left';\n todayUI.style.marginBottom = '22px';\n todayUI.style.marginLeft = '12px';\n todayUI.style.textAlign = 'center';\n todayUI.title = 'Click to set the current day to today';\n controlDiv.appendChild(todayUI);\n\n // Set CSS for the control interior\n var todayText = document.createElement('div');\n todayUI.style.color = 'rgb(25,25,25)';\n todayUI.style.fontFamily = 'Roboto,Arial,sans-serif';\n todayUI.style.fontSize = '16px';\n todayUI.style.lineHeight = '38px';\n todayUI.style.paddingLeft = '5px';\n todayUI.style.paddingRight = '5px';\n todayUI.innerHTML = 'Go To Today';\n todayUI.appendChild(todayText);\n\n google.maps.event.addDomListener(controlUI, 'click', function() {\n map.setCenter(mapCenter);\n map.setZoom(initialZoomLevel);\n moveSlider(getSliderValue());\n });\n\n \n google.maps.event.addDomListener(todayUI, 'click', function() {\n moveSliderToToday();\n });\n \n }",
"function initCenterMapButton() {\n\n // Create the DIV to hold the control and call the CenterControl() constructor\n // passing in this DIV.\n var centerControlDiv = document.createElement('div');\n var centerControl = new CenterControl(centerControlDiv, map);\n\n centerControlDiv.index = 1;\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);\n}",
"function setupControl() {\n // Create the DIV to hold the control and call the CenterControl()\n // constructor passing in this DIV.\n let centerControlDiv = document.createElement(\"div\");\n centerControlDiv.id = \"control-panel\";\n centerControlDiv.index = 1;\n map.controls[google.maps.ControlPosition.TOP_LEFT].push(centerControlDiv);\n\n // Create global controls\n currentControl = ShowControl(centerControlDiv, showAllMarkers, show_all_title);\n ShowControl(centerControlDiv, showFutureEvents, upcoming_only_title);\n\n toggleControlHighlight(null, currentControl);\n}",
"function HomeControl(controlDiv, map, center) {\n\n // Set CSS styles for the DIV containing the control\n // Setting padding to 5 px will offset the control\n // from the edge of the map\n controlDiv.style.padding = '5px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '1px';\n controlUI.style.margin = '1px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to set the map to Home';\n controlDiv.appendChild(controlUI);\n controlUI.style.setProperty(\"border-radius\",\"2px\");\n controlUI.style.setProperty(\"border-color\",\"#c2c2c2\")\n\n // Set CSS for the control interior\n var controlText = document.createElement('div');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '12px';\n controlText.style.paddingLeft = '4px';\n controlText.style.paddingRight = '4px';\n controlText.innerHTML = '<b>Home</b>';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to\n // the marker\n google.maps.event.addDomListener(controlUI, 'click', function() {\n map.setCenter(center);\n });\n\n}",
"function CenterControl(controlDiv, map,html) {\n\n // CSS For Button 'Filter By Cluster'\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = '#fff';\n controlUI.style.border = '2px solid #fff';\n controlUI.style.borderRadius = '3px';\n controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';\n controlUI.style.cursor = 'pointer';\n controlUI.style.marginBottom = '22px';\n controlUI.style.textAlign = 'center';\n controlUI.style.marginTop = '8px';\n controlUI.style.marginRight = '16px';\n controlDiv.appendChild(controlUI); // appends the button on maps\n\n // CSS for interior text of button.\n var controlText = document.createElement('div');\n controlText.style.color = 'rgb(25,25,25)';\n controlText.style.fontFamily = 'Roboto,Arial,sans-serif';\n controlText.style.fontSize = '16px';\n controlText.style.lineHeight = '38px';\n // sets the cluster names in the dropdown menu\n controlText.innerHTML = '<div class=\"dropdown\"><button class=\"dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" style=\"background:none;border:none\">Filter by Cluster<span class=\"caret\"></span></button><ul class=\"dropdown-menu\">'+html+'</ul></div>';\n controlUI.appendChild(controlText);\n $('.dropdown-menu show').css({\"display\":\"contents\"})\n}",
"function HomeControl(controlDiv, map, position, messageop) {\n\n // Set CSS styles for the DIV containing the control\n // Setting padding to 5 px will offset the control\n // from the edge of the map\n controlDiv.style.padding = '5px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('DIV');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '2px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to set the map to ' + messageop;\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var controlText = document.createElement('DIV');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '12px';\n controlText.style.paddingLeft = '4px';\n controlText.style.paddingRight = '4px';\n controlText.innerHTML = messageop;\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to Chicago\n google.maps.event.addDomListener(controlUI, 'click', function() {\n map.setCenter(position)\n });\n}",
"function HomeControl(controlDiv, map) {\n\n // Set CSS styles for the DIV containing the control\n // Setting padding to 5 px will offset the control\n // from the edge of the map\n controlDiv.style.padding = '5px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '2px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to set the map to Home';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var controlText = document.createElement('div');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '12px';\n controlText.style.paddingLeft = '4px';\n controlText.style.paddingRight = '4px';\n controlText.innerHTML = '<b>Home</b>';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to\n // Chicago\n google.maps.event.addDomListener(controlUI, 'click', function() {\n map.setCenter(seedbed)\n });\n\n}",
"function HomeControl(controlDiv, map) {\n\n // Set CSS styles for the DIV containing the control\n // Setting padding to 5 px will offset the control\n // from the edge of the map\n controlDiv.style.padding = '5px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '2px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to user current location';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var controlText = document.createElement('div');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '12px';\n controlText.style.paddingLeft = '4px';\n controlText.style.paddingRight = '4px';\n controlText.innerHTML = '<b>Use Current Location</b>';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to current position\n google.maps.event.addDomListener(controlUI, 'click', function() {\n map.setCenter(currentPosition);\n \n startMarker.setMap(null);\n \n\n var marker = new google.maps.Marker({\n position: currentPosition,\n map: map,\n title: 'Hello World!'\n \t});\n startPoint = currentPosition;\n console.log(startPoint);\n });\n\n}",
"function initialize(map_element, map_para ) { \r\n map = new google.maps.Map(map_element, map_para);\r\n var marker = new google.maps.Marker({\r\n position: map_para.center,\r\n map: map,\r\n title: 'Here'\r\n });\r\n \r\n \r\n\r\n var quitmap = emulator.creatediv(\"\",\"\");\r\n \r\n CenterControl(quitmap, map);\r\n CenterControl.index=1;\r\n map.controls[google.maps.ControlPosition.LEFT_TOP].push(quitmap); \r\n \r\n }",
"function HomeControl(controlDiv, map) {\n\n // Set CSS styles for the DIV containing the control\n // Setting padding to 5 px will offset the control\n // from the edge of the map\n controlDiv.style.padding = '5px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '2px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to Save Hole GPS Data';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var controlText = document.createElement('div');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '12px';\n controlText.style.paddingLeft = '4px';\n controlText.style.paddingRight = '4px';\n controlText.innerHTML = '<b>Save Hole GPS Data</b>';\n controlUI.appendChild(controlText);\n\n // Setup the click event listeners: simply set the map to\n // Chicago\n google.maps.event.addDomListener(controlUI, 'click', saveHoleGPSData);\n}",
"function mxLeanControlCenter(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}",
"function panZoomControl(controlDiv,Map)\n\t\t{\n\t\t\t// Set CSS styles for the DIV containing the control\n\t\t\t// Setting padding to 5 px will offset the control\n\t\t\t// from the edge of the map.\n\t\t\tcontrolDiv.style.padding = '1em';\n\t\t\t// Set CSS for the control border.\n\t\t\tvar controlUI = document.createElement('div');\n\t\t\tcontrolUI.style.backgroundColor = '#aadffa';\n\t\t\t//controlUI.style.color = 'white';\n\t\t\tcontrolUI.style.borderStyle = 'solid';\n\t\t\tcontrolUI.style.borderWidth = '0px';\n\t\t\tcontrolUI.style.cursor = 'pointer';\n\t\t\tcontrolUI.style.textAlign = 'center';\n\t\t\tcontrolUI.style.borderRadius = '6px';\n\t\t\tcontrolUI.title = 'Click to interact with the map.';\n\t\t\tcontrolDiv.appendChild(controlUI);\n\t\t\t// Set CSS for the control interior.\n\t\t\tvar controlText = document.createElement('div');\n\t\t\tcontrolText.style.fontFamily = 'sans-serif';\n\t\t\tcontrolText.style.fontSize = '12px';\n\t\t\tcontrolText.style.paddingLeft = '.5em';\n\t\t\tcontrolText.style.paddingRight = '.5em';\n\t\t\tcontrolText.style.paddingTop = '.3em';\n\t\t\tcontrolText.style.paddingBottom = '.3em';\n\t\t\tcontrolText.innerHTML = 'Explore Map';\n\t\t\tcontrolUI.appendChild(controlText);\n\t\t\t// Setup the click event listeners.\n\t\t\tgoogle.maps.event.addDomListener(controlUI, 'click', function() {\n\t\t\t\tvar cntr = Map.Map.getCenter();\n\t\t\t\tif(Map.Map.zoomControl === false)\n\t\t\t\t{\n\t\t\t\t\tMap.setPanZoom(true);\n\t\t\t\t\tif(Default.touch)\n\t\t\t\t\t{\n\t\t\t\t\t\tMap.setTouchScroll(false);\n\t\t\t\t\t}\n\t\t\t\t\t$('#before-map-fluid,#div-footer').hide(0,function(){\n\t\t\t\t\t\t$('#map-width').css('height','100%');\n\t\t\t\t\t\t$('#map-ratio').css('margin-top', $(window).height());\n\t\t\t\t\t\tcontrolUI.title = 'Click to close up the map.';\n\t\t\t\t\t\tcontrolText.innerHTML = 'Minimize';\n\t\t\t\t\t\tMap.Map.setCenter(cntr);\n\t\t\t\t\t\tgoogle.maps.event.trigger(Map.Map, 'resize');\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tMap.setPanZoom(false);\n\t\t\t\t\tif(Default.touch)\n\t\t\t\t\t{\n\t\t\t\t\t\tMap.setTouchScroll(true);\n\t\t\t\t\t}\n\t\t\t\t\t$('#before-map-fluid,#div-footer').show(0,function(){\n\t\t\t\t\t\t$('#map-width').css('height','');\n\t\t\t\t\t\t$('#map-ratio').css('margin-top','300px');\n\t\t\t\t\t\tcontrolUI.title = 'Click to interact with the map.';\n\t\t\t\t\t\tcontrolText.innerHTML = 'Explore Map';\n\t\t\t\t\t\tMap.Map.setCenter(cntr);\n\t\t\t\t\t\tgoogle.maps.event.trigger(Map.Map, 'resize');\n\t\t\t\t\t\twindow.scrollTo(0, 1);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function FullMapControl(controlDiv) {\r\n controlDiv.style.padding = '5px';\r\n var controlUI = document.createElement('DIV');\r\n controlUI.style.backgroundColor = 'white';\r\n controlUI.style.borderStyle = 'solid';\r\n controlUI.style.borderWidth = '2px';\r\n controlUI.style.cursor = 'pointer';\r\n controlUI.style.textAlign = 'center';\r\n controlUI.title = 'Click to see whole Indonesia Map';\r\n controlDiv.appendChild(controlUI);\r\n var controlText = document.createElement('DIV');\r\n controlText.style.fontFamily = 'Arial,sans-serif';\r\n controlText.style.fontSize = '12px'; \r\n controlText.style.paddingTop = '3px';\r\n controlText.style.paddingRight = '4px';\r\n controlText.style.paddingBottom = '3px'; \r\n controlText.style.paddingLeft = '4px';\r\n controlText.innerHTML = 'Full Indonesia Map';\r\n controlUI.appendChild(controlText);\r\n google.maps.event.addDomListener(controlUI, 'click', function () {\r\n lamanbudaya.maps.showFullMap();\r\n });\r\n}",
"function centreMap() {\n\t\t var widget_data = $this.data(WIDGET_NS);\n\t\t if (widget_data.polygon !== null) {\n\t\t\tvar bounds = new google.maps.LatLngBounds();\n\t\t\tvar i;\n\n\t\t\t// The Bermuda Triangle\n\t\t\tvar polygonCoords = widget_data.polygon.getPath().getArray();\n\t\t\tfor (i = 0; i < polygonCoords.length; i++) {\n\t\t\t bounds.extend(polygonCoords[i]);\n\t\t\t}\n\t\t\t//resetZoom();//google map api bug fix\n\t\t\twidget_data.map.fitBounds(bounds);\n\t\t }\n\n\t\t // Check for a marker to centre on.\n\t\t if (widget_data.marker !== null && settings.jumpToPoint) {\n\t\t\twidget_data.map.setCenter(widget_data.marker.getPosition());\n\t\t }\n\t\t $this.data(WIDGET_NS, widget_data);\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the db name from the url path. Strip nonword characters and 'store/' from the start | function getDbName(url) {
//get the path and make the db name the path.json
var dbName = url.pathname.replace(/\W/g, '').replace(/^store/, '');
if (dbName) {
return dbName + '.json';
}
return 'default.json';
} | [
"function getDatabaseName() {\n const url_string = window.location.href;\n const url = new URL(url_string);\n const dbNameFromUrl = url.searchParams.get('database');\n\n let ret = 'heroesdb';\n if (dbNameFromUrl) {\n console.log('databaseName from url: ' + dbNameFromUrl);\n ret += dbNameFromUrl;\n }\n return ret;\n}",
"function getDbNameFromLocation(){\n var databasename = location.pathname.split(\"/\")[1];\n return(databasename);\n}",
"function getDbName(url) {\n var dbName = url.pathname.replace(/\\W/g, '').replace(/^checkin/, '');\n\n if (dbName) {\n return dbName + '.json';\n }\n\n return 'default.json';\n }",
"function checkDbName( db )\n {\n if( db.trim() === \"\" ) return false;\n if( db.indexOf(\".bdb\") == -1 ) return db + \".bdb\";\n return db;\n }",
"function getDbPath() {\r\n\tif (isCacheInvalid(\"dbpathweb\", 5)) {\r\n\t\tsynchronized(applicationScope) {\r\n\t\t\tvar dbPath = @Left(context.getUrl(), \".nsf\") + \".nsf\";\r\n\t\t\tvar pos = (context.isRunningContext(\"Notes\")) ? 4 : 3;\r\n\t\t\tvar secondPathElements = dbPath.split(\"/\");\r\n\t\t\tvar secondPath = \"\";\r\n\t\t\tfor (pos; pos < secondPathElements.length; pos++) {\r\n\t\t\t\tif (secondPath != \"\") secondPath += \"/\";\r\n\t\t\t\tsecondPath += secondPathElements[pos];\r\n\t\t\t}\r\n\t\t\tvar res: Array = new Array();\r\n\t\t\tres.push(dbPath);\r\n\t\t\tres.push(secondPath);\r\n\t\t\tapplicationScope.dbPathWeb = res;\r\n\t\t}\r\n\t}\r\n\treturn applicationScope.dbPathWeb[0];\r\n}",
"nameDB() {\n let hostname = window.location.host.split('.')\n let response = hostname\n\n //Set capitalize to all words\n hostname.forEach((word, index) => {\n if (index >= 1) {\n hostname[index] = word.charAt(0).toUpperCase() + word.slice(1)\n }\n })\n\n //Remove .com .org....\n if (hostname.length >= 2) response.pop()\n\n return `${response.join('')}DB`//Response\n }",
"function databaseName(testCase) {\n return \"db\" + self.location.pathname + \"-\" + testCase.name;\n}",
"function cleanShop(shop) {\n var parsed = _url2.default.parse(shop);\n var base = parsed.protocol ? parsed.host : shop;\n return base.split('.')[0];\n}",
"function databaseName(testCase) {\n return 'db' + self.location.pathname + '-' + testCase.name;\n}",
"ensureName() {\n if (this.meaningfulName) {\n return this.meaningfulName;\n }\n if (this.tables.length) {\n this.name = this.tables[0] + \".db\";\n return this.name;\n }\n if (this.id) {\n this.name = this.id.substr(0, 6) + \".db\";\n return this.name;\n }\n return this.name;\n }",
"function extractArtworkNameFromURL() {\n\n var pathComponents = window.location.pathname.split('/');\n return pathComponents.slice( -1 )[0];\n\n}",
"function getLegalDBName(input) {\n input = input.toLowerCase();\n var output = encodeURIComponent(input);\n output = output.replace(/\\./g, \"%2E\");\n output = output.replace(/!/g, \"%21\");\n output = output.replace(/~/g, \"%7E\");\n output = output.replace(/\\*/g, \"%2A\");\n output = output.replace(/'/g, \"%27\");\n output = output.replace(/\\(/g, \"%28\");\n output = output.replace(/\\)/g, \"%29\");\n output = output.replace(/-/g, \"%2D\");\n output = output.toLowerCase();\n output = output.replace(/(%..)/g, function(esc) {\n esc = esc.substr(1);\n return \"(\" + esc + \")\";\n });\n return output;\n}",
"function getDbPath(){\r\n\tif (!applicationScope.containsKey(\"dbpath\")){\r\n\t\tapplicationScope.dbpath = \"/\" + @ReplaceSubstring(database.getFilePath(), \"\\\\\", \"/\");\r\n\t}\r\n\treturn applicationScope.dbpath;\r\n}",
"function getNameFromUrl(url){\r\n return url.split(\"/\").pop().replace(/\\.[^/.]+$/, \"\")\r\n }",
"extractPhotoName() {\n var url = this.state.photoURL;\n url = url.substring(url.indexOf('smartphoto-storage-bucket/'));\n url = url.substring(url.indexOf('/') + 1);\n url = url.substring(url.indexOf('/') + 1);\n url = url.substring(url.indexOf('/') + 1);\n url = url.substring(url.indexOf('/') + 1);\n return url;\n }",
"function prf_getDomainStr() {\n var dname = \"\",\n dcmps = location.hostname.split(\".\"),\n ncmps = dcmps.length,\n i,\n start_idx;\n\n if (ncmps === 1 || prf_isNumStr(dcmps[ncmps - 1])) {\n return \"\";\n }\n\n if (ncmps > 3 && dcmps[ncmps - 1].length === 2) {\n start_idx = ncmps - 3;\n } else {\n start_idx = ncmps - 2;\n }\n\n for (i = start_idx; i < ncmps; i++) {\n dname += \".\" + dcmps[i];\n }\n\n return dname;\n }",
"static get localDbName() { return \"LandslideSurvey\" }",
"function getName() {\n productName = window.location.href.split(\"/\").reverse()[1];\n const search = productName.search(\"%\");\n if (search == -1) {\n productName = window.location.href.split(\"/\").reverse()[1];\n } else {\n productName = productName.replace(/%20/g, ' ');\n }\n }",
"function getDictName() {\n var ref = window.location.toString();\n var name = ref.substring(ref.lastIndexOf('/')+1);\n return name;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given plant information, we fill in the defaults. | function fill_default_show(plant) {
$("#water-amount").val(plant.water);
$("#sunlight-amount").val(plant.sunlight);
$("#plant-season").val(plant.plant_during);
$("#bloom-season").val(plant.blooming_season);
} | [
"function setupPlant() {\n // Generate mostly random values for the arguments of the Plant constructor\n for (let i = 0; i < numLeaves; i++) {\n let leafX = random(225, 275);\n let leafY = random(440, 450);\n let leafWidth = random(0, 5);\n let leafHeight = random(0, 10);\n let leafAvatar = leafAvatars[i];\n let leafGrowningRate = 0.008; // 0.008\n let leafMaxHeight = 80;\n // Create a new leaf with the values\n let newLeaf = new Leaves(leafX, leafY, leafWidth, leafHeight, leafAvatar, leafGrowningRate, leafMaxHeight)\n // Add the new leaf to the array\n leaves.push(newLeaf);\n }\n}",
"function makePlant () {\n var plant = {};\n plant.height = 5*getRandomInt (1, 10) + 5*getRandomInt (1, 10);\n plant.petal_number = getRandomInt (2, 6);\n if (getRandomInt(0, 1)==0) {\n plant.leaf_veins = \"parallel\";\n } else {\n plant.leaf_veins = \"branched\";\n }\n plant.location = locations[getRandomInt(0, locations.length-1)];\n plant.petal_colour = colours[getRandomInt(0, colours.length-1)];\n return plant;\n}",
"buildAllPlants() {\n for (let id in this.rawData) {\n if (!(id in this.plants)) {\n this.plants[id] = new Plant(this.attributes, this.rawData[id]);\n }\n }\n return Object.assign({}, this.plants);\n }",
"function set_new_patron_defaults(prs) {\n if (!$scope.patron.passwd) {\n // passsword may originate from staged user.\n $scope.generate_password();\n }\n $scope.hold_notify_phone = true;\n $scope.hold_notify_email = true;\n\n // staged users may be loaded w/ a profile.\n $scope.set_expire_date();\n\n if (prs.org_settings['ui.patron.default_ident_type']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_ident_type'];\n var ident_type = $scope.ident_types.filter(\n function(type) { return type.id() == id })[0];\n $scope.patron.ident_type = ident_type;\n }\n if (prs.org_settings['ui.patron.default_inet_access_level']) {\n // $scope.patron needs this field to be an object\n var id = prs.org_settings['ui.patron.default_inet_access_level'];\n var level = $scope.net_access_levels.filter(\n function(lvl) { return lvl.id() == id })[0];\n $scope.patron.net_access_level = level;\n }\n if (prs.org_settings['ui.patron.default_country']) {\n $scope.patron.addresses[0].country = \n prs.org_settings['ui.patron.default_country'];\n }\n }",
"initializeRegularBeaker()\n {\n //Water should be some reasonable value.\n this.water = STARTING_WATER_LEVEL;\n\n //Everything else should be Zero.\n this.red = this.green = this.blue = 0;\n\n this.ph = 7.0;\n\n this.color = Difficulty_1_Colors.WATER;\n\n\n this.temperature = STARTING_TEMPERATURE;\n }",
"createBaseVars() {\n this.defaultList().forEach(name => {\n this.setVar(name.replace(`--default`, ''), this.getVar(name));\n });\n }",
"buildChildPlantKeyValuePairs() {\n this.children.forEach((child, index) => {\n // There's an unlikely danger doing it this way if we get a child name that overlaps an existing property\n this[child.toLowerCase()] = this.getPlantsAtIndex(index);\n });\n }",
"function setTshirtDefaults() {\n\t\t\tdeleteTshirtProperties();\n\t\t\t_this.tshirt.nombre = '';\n\t\t\t_this.tshirt.estampas = [];\n\t\t\t_this.tshirt.costo = 0;\n\t\t\t_this.tshirt.color = _this.colors[0].id;\n\t\t\t_this.tshirt.talla = _this.sizes[0].id;\n\t\t\t_this.tshirt.estilo = _this.styles[0].id;\n\n\t\t\tsetCSS();\n\t\t}",
"populate(){\n\t\t\tconsole.log(\"Populating settings...\");\n\t\t\tfor(group of this.settings){\n\t\t\t\tfor(setting of group.subSettings){\n\t\t\t\t\tsetting.value = this.demo.settings[setting.alias];\n\t\t\t\t\t\n\t\t\t\t\tif(setting.subSettings !== undefined){\n\t\t\t\t\t\tfor(subSetting of setting.subSettings){\n\t\t\t\t\t\t\tsubSetting.value = this.demo.settings[subSetting.alias];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconsole.log(\"Finnished populating settings...\");\n\t\t}",
"function selectPlant()\n{\n\tif(unitCount < 8 && money >= 50 && !ready) {\n\t\tunits[unitCount] = \"plant\";\n\t\tunitCount++;\n\t\tmoney = money - 50;\n\t\tupdateResources();\n\t\tprintUnitList();\n\t}\n}",
"function setDefaultsForStand(data_point, file_name) {\n /////////////////////////////////////////////////////////////////////////////////////\n // REMOVE THIS PART ONCE WE ACTUALLY COLLECT NEW DATA\n // It adds match, role, and team to stand app files, which the new stand app automatically does\n /////////////////////////////////////////////////////////////////////////////////////\n let parts = file_name.split(\"-\");\n parts[2] = parts[2].split(\".\")[0] // removing the .json\n if (data_point[\"info\"] === undefined) {\n data_point[\"info\"] = {}\n data_point[\"info\"][\"match\"] = parts[0].substr(1);\n data_point[\"info\"][\"role\"] = parts[1];\n data_point[\"info\"][\"team\"] = parts[2];\n }\n // sets default values to unfilled JSON requirements\n traverseScoutKitJSON(defaultStandJSON, function(json, page, page_index, question, question_index) {\n // if the question is not in the JSON\n if (data_point[page][question] === undefined) {\n // it adds the default response\n data_point[page][question] = defaultStandJSON[page][question];\n }\n });\n}",
"buildPlant(idPlant) {\n if (idPlant === null) {\n return new Plant(this.attributes, {});\n }\n if (!(idPlant in this.plants)) {\n this.plants[idPlant] = new Plant(this.attributes, this.rawData[idPlant]);\n }\n return this.plants[idPlant];\n }",
"function createPlant(gardenObject){\r\n //Create the garden object by finding the parent and prepending to the html\r\n $(\"#\" + gardenObject.parentId).prepend(\"<div id=\"+ gardenObject.id+\" class=plantJ title=\"+gardenObject.title+\">\"\r\n + \"<div class=plantWidthLabel></div>\"\r\n + \"<div class=plantHeightLabel></div>\"\r\n +\"<div id=\"+ gardenObject.id +\"picture class=plantJ title=\"+ gardenObject.title +\">\"\r\n +\"</div>\");\r\n $(\".plantWidthLabel\").addClass(\"widthLabel\");\r\n $(\".plantHeightLabel\").addClass(\"heightLabel\"); \r\n\r\n //Sets the background picture for the plant creates the size and repeats \r\n $(\"#\" + gardenObject.id+ \"picture\").css(\"background-image\", \"url(\" + gardenObject.backgroundImage +\")\");\r\n $(\"#\" + gardenObject.id + \"picture\").css({\r\n height: \"100%\",\r\n width: \"100%\",\r\n \"background-repeat\": \"repeat\",\r\n });\r\n $(\"#\" + gardenObject.id + \"picture\").css(\"background-size\", gardenObject.minWidth +\"px \"+ gardenObject.minHeight +\"px\");\r\n \r\n \r\n $(\"#\" + gardenObject.id).css({\r\n height: gardenObject.height,\r\n width: gardenObject.width,\r\n left: gardenObject.left,\r\n top: gardenObject.top\r\n });\r\n\r\n //$(\"#\" + gardenObject.id).css(\"background-size\", gardenObject.minWidth +\"px \"+ gardenObject.minHeight+\"px\");\r\n makeResizable( gardenObject ); \r\n makeDraggable( gardenObject );\r\n createToolTip( gardenObject );\r\n\r\n var lblWidth = ($(\"#\" + gardenObject.id).width()/pixelsPerFoot).toFixed(2);\r\n var lblHeight = ($(\"#\" + gardenObject.id).height()/pixelsPerFoot).toFixed(2); \r\n var lblRowSpacing = (gardenObject.minHeight/pixelsPerFoot).toFixed(2);\r\n var lblPlantSpacing = (gardenObject.minWidth/pixelsPerFoot).toFixed(2);\r\n\r\n if(lblWidth >= 12){\r\n $(\"#\" + gardenObject.id + \" > div.plantWidthLabel\").text(gardenObject.title + \" \"+ lblWidth + \"ft\" \r\n +\" (Plant \" + lblPlantSpacing + \"ft / \" \r\n +\" Row \" + lblRowSpacing + \"ft)\" );\r\n }\r\n else if(lblWidth >=5) {\r\n $(\"#\" + gardenObject.id + \" > div.plantWidthLabel\").text(gardenObject.title + \" \"+ lblWidth + \"ft\");\r\n }\r\n else\r\n {\r\n $(\"#\" + gardenObject.id + \" > div.plantWidthLabel\").text(lblWidth + \"ft\");\r\n }\r\n\r\n if(lblHeight >=1)\r\n {\r\n $(\"#\" + gardenObject.id + \" > div.plantHeightLabel\").text(lblHeight + \" ft\");\r\n }\r\n else {\r\n $(\"#\" + gardenObject.id + \" > div.plantHeightLabel\").text(\"\");\r\n }\r\n\r\n}//end create plant",
"function updatePreset() {\n switch(preset.value) {\n case 'person':\n storyInput.value = JSON.stringify(EXAMPLE_PERSON, null, 2);\n break;\n case 'product':\n storyInput.value = JSON.stringify(EXAMPLE_PRODUCT, null, 2);\n break;\n case 'place':\n storyInput.value = JSON.stringify(EXAMPLE_PLACE, null, 2);\n break;\n default:\n storyInput.value = '{ }';\n }\n}",
"function fillOptionalRecipeData(recipe) {\n if (recipe.result != null && recipe.result_count == null) {\n recipe.result_count = 1;\n }\n //console.log(recipe);\n if (recipe.category == null) {\n recipe.category = \"crafting\";\n }\n\n if (recipe.energy_required == null) {\n recipe.energy_required = 0.5;\n }\n\n if (recipe.enabled == null) {\n recipe.enabled = \"true\";\n }\n}",
"function initFields() {\n if (vm.diaryId) {\n if (vm.create.site_notes.delays !== null) {\n vm.delays = vm.create.site_notes.delays;\n }\n if (vm.create.site_notes.tools_used !== null) {\n vm.tools = vm.create.site_notes.tools_used;\n }\n if (vm.create.site_notes.materials_requested !== null) {\n vm.materials = vm.create.site_notes.materials_requested;\n }\n }\n if (!vm.diaryId) {\n if (vm.create.site_notes.delays) {\n vm.delays = vm.create.site_notes.delays;\n }\n if (vm.create.site_notes.tools_used) {\n vm.tools = vm.create.site_notes.tools_used;\n }\n if (vm.create.site_notes.materials_requested) {\n vm.materials = vm.create.site_notes.materials_requested;\n }\n }\n }",
"function default_artifacts()\n{\n\tlogMessage(\"Artifacts set to default positions\");\t\n\t\n\t//Celeron\n\tvar celeron_x = 13; \n\tvar celeron_y = 13;\n\tvar celeron_recipe = true;\t\n\t\n\t//Xeon\n\tvar xeon_x = 2; \n\tvar xeon_y = 2;\t\n\tvar xeon_recipe = false;\t\n\t\n\t//Ryzen\n\tvar ryzen_x = 3; \n\tvar ryzen_y = 3;\t\n\tvar ryzen_recipe = false;\t\n\t\n\t//Saturn\n\tvar saturn_x = 4; \n\tvar saturn_y = 4;\t\n\tvar saturn_recipe = false;\t\n\t\n\t//Mars\n\tvar mars_x = 5; \n\tvar mars_y = 5;\t\n\tvar mars_recipe = false;\t\n\t\n\t//Jupiter\n\tvar jupiter_x = 6; \n\tvar jupiter_y = 6;\t\n\tvar jupiter_recipe = false;\t\n\t\n\t//Pluto\n\tvar pluto_x = 7; \n\tvar pluto_y = 7;\t\n\tvar pluto_recipe = false;\t\n\n\t//Asteroid\n\tvar ax = 11;\n\tvar ay = 11; \n\n\t//Space Station\n\tvar sx = 13;\n\tvar sy = 11;\n\t\n\tgame_map.map[celeron_x][celeron_y].obj = new pentium(\"Celeron\", false, celeron_recipe);\n\tgame_map.map[celeron_x][celeron_y].change_type(PENTIUM);\n\t\n\tgame_map.map[xeon_x][xeon_y].obj = new pentium(\"Xeon\", false, xeon_recipe);\n\tgame_map.map[xeon_x][xeon_y].change_type(PENTIUM);\n\t\n\tgame_map.map[ryzen_x][ryzen_y].obj = new pentium(\"Ryzen\", false, ryzen_recipe);\n\tgame_map.map[ryzen_x][ryzen_y].change_type(PENTIUM);\n\t\n\tgame_map.map[saturn_x][saturn_y].obj = new pentium(\"Saturn\", false, saturn_recipe);\n\tgame_map.map[saturn_x][saturn_y].change_type(PENTIUM);\n\t\n\tgame_map.map[mars_x][mars_y].obj = new pentium(\"Mars\", false, mars_recipe);\n\tgame_map.map[mars_x][mars_y].change_type(PENTIUM);\n\t\n\tgame_map.map[jupiter_x][jupiter_y].obj = new pentium(\"Jupiter\", false, jupiter_recipe);\n\tgame_map.map[jupiter_x][jupiter_y].change_type(PENTIUM);\n\t\n\tgame_map.map[pluto_x][pluto_y].obj = new pentium(\"Pluto\", false, pluto_recipe);\n\tgame_map.map[pluto_x][pluto_y].change_type(PENTIUM);\n\t\t\n\tgame_map.map[ax][ay].obj = new asteroid(20);\n\tgame_map.map[ax][ay].change_type(ASTEROID);\n\t\n\tgame_map.map[sx][sy].obj = new space_station(0);\n\tgame_map.map[sx][sy].change_type(SPACE_STATION);\n}",
"addPlant(plant) {\n if (plant.type == \"rose\") {\n this.roseArbor.addplant(plant);\n } else if (plant.isPerennial == true && plant.amountOfSunNeeded <= 5) {\n this.perennialGarden.addplant(plant);\n } else this.slopePlanters.addplant(plant);\n }",
"function setDefaultsForPit(data_point) {\n // sets default values to unfilled JSON requirements\n traverseScoutKitJSON(defaultPitJSON, function(json, page, page_index, question, question_index) {\n // if the question is not in the JSON\n if (data_point[page][question] === undefined) {\n // it adds the default response\n data_point[page][question] = defaultPitJSON[page][question];\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This anonymous function takes three parameters and adds them together then returns the total back to addTasks. | function addTasks(pasqualeTasks, darylTasks, kadriTasks ){
var totalTasks = Number(pasqualeTasks) + Number(darylTasks) + Number(kadriTasks);
return totalTasks;
} | [
"function getTotal() {\n let args = Array.prototype.slice.call(arguments);\n\n if (args.length == 2) return args[0] + args[1];\n else if (args.length == 1) {\n return (num2) => {\n return args[0] + num2;\n };\n }\n}",
"addAdditionTask(y) {\n this.tasks.push((x) => x+y);\n }",
"function sumNums (num1, num2, cb)\n{ \n\tvar sum = num1 + num2;\n\tcb(sum); \n}",
"function sumNums(a, b, cb){\n\tsum = a + b;\n cb(sum);\n}",
"function addn(...args){ //LOOP\n\tvar total = 0;\n\tfor(i = 0; i < args.length; i++){\n\t total = add2(function(){return total;}, args[i]);\n\t}\n\treturn total;\n}",
"function sum(a) {\n return function (b) {\n return function (c) {\n return function (d) {\n return function (e) {\n return function (callback) {\n const total = a + b + c + d + e;\n callback(total);\n };\n };\n };\n };\n };\n}",
"function sumNums (num1, num2, cb){\n cb(num1 + num2);\n}",
"function addNumbers() {\n\n // since we don't know how many arguments we have\n // we can use the arguments word inside out function\n\n let total = 0;\n\n for (const number of arguments) {\n total += number;\n }\n\n return total;\n\n}",
"function add(...numbersToAdd) { // This is a Rest parameter\n return numbersToAdd.reduce((sum, next) => sum + next);\n}",
"function addAll(...args) {\n return args.reduce((total, number) => total + number, 0);\n}",
"function getTotalTasks() {\n var totalTasks = 0;\n \n if (data.index < data.lists.length) {\n totalTasks = data.lists[data.index].tasks.length;\n }\n \n return totalTasks;\n }",
"function sum_duration(taskArr){\n\n let total_duration = 0; \n for(let taskObj of taskArr){\n total_duration += taskObj['duration'];\n }\n return total_duration;\n}",
"function add(a, b) {\n var total = (a + b);\n return total;\n }",
"function addFourNumberWithParameters(numberone, numbertwo, numberthree, numberfour){\n //function with four parameters to add four numbers\n\n var result = numberone + numbertwo + numberthree + numberfour;\n // declaring variable result and assigning it the sum of the four variables\n \n console.log(\"The result is: \" +result);\n //printing the total value to the console\n }",
"function computeTotalHours(tasks) {\n\tvar now = new Date().getTime();\n\tvar sum = 0;\n\t\n\tfor (var index = 0; index < tasks.length; ++index) {\n\t\tvar task = tasks[index];\n\t\t\n\t\tif (!task.start) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (task.end && task.start <= task.end) {\n\t\t\tsum += task.end - task.start;\n\t\t}\n\t\t\n\t\tif (!task.end && task.start <= now) {\n\t\t\tsum += now - task.start;\n\t\t}\n\t}\n\t\n\t// Return the number of hours.\n\treturn Math.floor(sum / hours) + 'h ' +\n\t\tMath.floor(sum % hours / minutes) + '\\'';\n}",
"function addThree(number1, number2, number3){\n var result = number1 + number2 + number3;\n return result;\n\n}",
"function updateTaskTotalTime()\n{\n\tvar totalTimeActualSeconds = 0;\n\tvar totalTimePlannedSeconds = 0;\n\n\t// Actual time\n\t$.each($(\".task-do\"), function(index,elem)\n\t{\n\t\tvar actualTimeInSeconds = hmsToSecondsOnly($(elem).val());\n\t\tvar plannedTimeInSeconds = hmsToSecondsOnly($(elem).parent().parent().find(\".task-plan\").val());\n\n\t\ttotalTimeActualSeconds += actualTimeInSeconds;\n\t\ttotalTimePlannedSeconds += plannedTimeInSeconds;\n\t});\n\n\t$(\".time-total-actual\").text( secondsTimeSpanToHMS(totalTimeActualSeconds) );\n\t$(\".time-total-planned\").text( secondsTimeSpanToHMS(totalTimePlannedSeconds) );\n}",
"function getTotal(list, getValueToAddfn) {\n if (isNullOrUndefined(list, getValueToAddfn)) {\n return;\n }\n var result = 0;\n for (var i = 0, length = list.length; i < length; i++) {\n var item = list[i];\n result += getValueToAddfn(item);\n }\n return result;\n }",
"function addTask(task, tasks){\n tasks.push(task);\n return tasks;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
proxy clicks to input focus | click() {
this.$('input').focusin();
} | [
"setFocus() {\n trapFocus(this.wrapper);\n }",
"setFocus(){\n this.getInputEle().focus();\n }",
"focus() {\n this.callMethodOnElementOrChild(this.input, 'focus');\n }",
"setFocus() {\n const focusable = this.wrapper.querySelectorAll('a, button, input, select')[0];\n if (focusable) {\n focusable.focus();\n }\n }",
"delegateFocus(ev) {\n const clickedItem = ev.target.tagName === 'ION-ITEM';\n const input = this.getFirstInput();\n let firstActive = false;\n // If the first input is the same as the active element we need\n // to focus the first input again, but if the active element\n // is another input inside of the item we shouldn't switch focus\n if (input && document.activeElement) {\n firstActive = input.querySelector('input, textarea') === document.activeElement;\n }\n // Only focus the first input if we clicked on an ion-item\n // and the first input exists\n if (clickedItem && input && firstActive) {\n input.fireFocusEvents = false;\n input.setBlur();\n input.setFocus();\n raf(() => {\n input.fireFocusEvents = true;\n });\n }\n }",
"delegateFocus(ev, input) {\n const clickedItem = ev.target.tagName === 'ION-ITEM';\n let firstActive = false;\n // If the first input is the same as the active element we need\n // to focus the first input again, but if the active element\n // is another input inside of the item we shouldn't switch focus\n if (document.activeElement) {\n firstActive = input.querySelector('input, textarea') === document.activeElement;\n }\n // Only focus the first input if we clicked on an ion-item\n // and the first input exists\n if (clickedItem && firstActive) {\n input.fireFocusEvents = false;\n input.setBlur();\n input.setFocus();\n raf(() => {\n input.fireFocusEvents = true;\n });\n }\n }",
"function focus_input() {\n focused = this;\n }",
"onFocus() {}",
"function focus_on_click() {\n\n $('.focus-on-click').on('click', function(event) {\n\n var target = $($(this).data('focus-element'));\n\n if (!$(this).hasClass('scroll-on-click') && (target.length)) {\n\n target.focus();\n\n }\n\n });\n\n }",
"handleFocus() {\n this.focused = true;\n this.updateItemList();\n\n document.addEventListener('click', this._handleClick);\n }",
"focus() {\n this.callRequiredChildMethod(this.inputSlot, 'focus', []);\n }",
"_setFocusToInput() {\n if (!flagTouchStart && document.activeElement !== this._elements.input) {\n this._elements.input.focus();\n }\n flagTouchStart = false;\n }",
"listenToFocusEvents () {\r\n const callback = ev => {\r\n const name = ev.target.nodeName\r\n const type = ev.target.type\r\n \r\n if (!ev.target.classList.contains('simple-keyboard-input')) {\r\n if ((name === 'INPUT' && (type === 'text' || type === 'password'))\r\n || (name === 'TEXTAREA')) {\r\n this.$target = ev.target\r\n this.show()\r\n }\r\n }\r\n\r\n this.$target && this.setInputType()\r\n }\r\n this.callbacks.focusin.push(callback)\r\n\r\n document.addEventListener('click', callback)\r\n document.addEventListener('focusin', callback)\r\n }",
"focus() {\n this.input.focus();\n }",
"function focusInput() { \n input.focus()\n}",
"_focusChange(arg) {\n if(arg === true) {\n this.$.input.focus();\n }\n }",
"function focusInput() {\n if (this.getInput()) {\n this.getInput().focus();\n }\n}",
"focus() {\n this.toggleMenuList();\n this.input.focus();\n }",
"_setFocus() {\n if (this._blurTimeoutId) {\n clearTimeout(this._blurTimeoutId);\n }\n this._focus = true;\n this._setFocusWithin();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selects the next tab in the list, if any. | selectNextTab() {
const selectedTab = this.selectedTab;
const tabs = this.tabs;
const length = tabs.get('length');
let idx = selectedTab.get('index');
let tab;
do {
idx++;
// Next from the last tab should select the first tab.
if (idx === length) {
idx = 0;
}
tab = tabs.objectAt(idx);
} while (tab && tab.isDestroying && tab !== selectedTab);
if (tab) {
tab.select();
}
} | [
"_nextTab() {\n const tabs = this._allTabs();\n let newIdx = tabs.findIndex(tab => tab.selected) + 1;\n return tabs[newIdx % tabs.length];\n }",
"_nextTab() {\n const tabs = this._allTabs();\n let newIdx = tabs.findIndex(tab => tab.selected) + 1;\n return tabs[newIdx % tabs.length];\n }",
"nextTab() {\n\t\tthis.switchTab(this.currentTab.next.length ? this.currentTab.next : this.tabs.first);\n\t}",
"function nextTab() {\n if (menuIsNotOpening()) {\n var selected = $ionicTabsDelegate.selectedIndex();\n if (selected !== -1 && selected !== 0) {\n $ionicTabsDelegate.select(selected - 1);\n }\n }\n }",
"activateNextTab() {\n const current = this._currentTabBar();\n if (!current) {\n return;\n }\n const ci = current.currentIndex;\n if (ci === -1) {\n return;\n }\n if (ci < current.titles.length - 1) {\n current.currentIndex += 1;\n if (current.currentTitle) {\n current.currentTitle.owner.activate();\n }\n return;\n }\n if (ci === current.titles.length - 1) {\n const nextBar = this._adjacentBar('next');\n if (nextBar) {\n nextBar.currentIndex = 0;\n if (nextBar.currentTitle) {\n nextBar.currentTitle.owner.activate();\n }\n }\n }\n }",
"activateNextTab() {\n let current = this._currentTabBar();\n if (!current) {\n return;\n }\n let ci = current.currentIndex;\n if (ci === -1) {\n return;\n }\n if (ci < current.titles.length - 1) {\n current.currentIndex += 1;\n if (current.currentTitle) {\n current.currentTitle.owner.activate();\n }\n return;\n }\n if (ci === current.titles.length - 1) {\n let nextBar = this._adjacentBar('next');\n if (nextBar) {\n nextBar.currentIndex = 0;\n if (nextBar.currentTitle) {\n nextBar.currentTitle.owner.activate();\n }\n }\n }\n }",
"function GetNextTab() {\n let currentTab = GetCurrentTab();\n return TabList[($.inArray(currentTab, TabList) + 1) % TabList.length];\n}",
"next() {\n // Find current selected element\n const selectedElement = querySelector('li[tabindex=\"0\"]', this.rootElement);\n\n // Remove selection\n selectedElement.removeAttribute('tabindex');\n\n // Use the next element or the element at the start of the list\n const nextElement = (selectedElement.nextSibling ? selectedElement.nextSibling : selectedElement.parentNode.firstChild);\n if (nextElement !== selectedElement) {\n // Set focus and scroll into view\n nextElement.setAttribute('tabindex', 0);\n this.scrollIntoView(nextElement);\n }\n }",
"function tabNext () {\n var next, i,\n a = document.activeElement,\n\n // Get element list as a real array so we can sort it\n n = Array.prototype.slice.call((a.form||document).getElementsByTagName('*'));\n\n // Filter out untabables\n n = n.filter(function (a) { return a.tabIndex > -1 && a.offsetHeight && !a.disabled; });\n\n // Sort by tab order\n n.sort(function (a, b) {\n // Use Number.MAX_VALUE instead of 0 to sort to end\n return (a.tabIndex||Number.MAX_VALUE) - (b.tabIndex||Number.MAX_VALUE);\n });\n\n // Reorder and remove active so next element is first\n i = n.indexOf(a);\n n = n.slice(i + 1).concat(n.slice(0, i));\n i = 0;\n\n while (document.activeElement != next && n.length) {\n // Find the element following the currently focused element\n next = n.shift();\n next.focus();\n }\n}",
"next(step = 1) {\n if (this.isAnimated) {\n return;\n }\n\n const nextItemIndex = this._getNextItemIndex(step);\n this.currentItemIndex = nextItemIndex;\n Axentix.createEvent(this.el, 'tab.next', { step });\n\n const target = this.tabLinks[nextItemIndex].children[0].getAttribute('href');\n this.select(target.split('#')[1]);\n }",
"function jumpToNext(){\n if(indexCardInFocus==16){\n indexCardInFocus=1;\n }else{\n indexCardInFocus++;\n }\n if (indexCardInFocus==0){\n indexCardInFocus=1;\n }\n while(!document.querySelector(`li[tabIndex='${indexCardInFocus}']`)){\n if (indexCardInFocus==16){\n indexCardInFocus=0;\n }\n indexCardInFocus++;\n }\n}",
"nextTab() {\n\t\tsuper.nextTab();\n\t\tthis._updateActualTab();\n\t}",
"function websys_nexttab(index,frm) {\n\tvar next='';\n\tvar nextidx=9999;\n\tindex=parseInt(index,10);\n\t//if (frm) objs=frm.all; else objs=document.all;\n\tif (frm) var objs=websys_getChildElements(frm);\n\telse var objs=document.all;\n\tfor (var j=0;j<objs.length;j++) {\n\t\tif ( websys_canfocus(objs[j]) ) {\n\t\t\tif (objs[j].tabIndex>index&&(objs[j].tabIndex<nextidx)) {\n\t\t\t\tnextidx=objs[j].tabIndex;\n\t\t\t\tnext=objs[j].name;\n\t\t\t\tif (nextidx==(1+index)) break; //quit as soon as we find the very next one\n\t\t\t}\n\t\t}\n\t}\n\tif (next!='') {\n\t\twebsys_setfocus(next);\n\t}\n}",
"focusNext() {\n if (this._focusIndex === this._tabs.length - 1) {\n // hover first item\n this._focusIndex = 0;\n } else {\n this._focusIndex += 1;\n }\n\n this._tabs[this._focusIndex].triggerFocus();\n }",
"function getNextTab() {\n\t\treturn $(\".form-nav a.active\").parent().closest('li').next().children().first().attr('href');\n\t}",
"function selectNext(){\n chrome.tabs.query({\n 'active': true,\n 'currentWindow': true\n },\n function(tabs) {\n if ('undefined' != typeof tabs[0].id && tabs[0].id) {\n chrome.tabs.sendMessage(tabs[0].id, {\n 'message' : 'selectNextNode'\n });\n }\n });\n}",
"function nextTab(elem) {\n $(elem).next().find('a[data-toggle=\"tab\"]').click();\n}",
"selectFirst() {\n const tabs = this._allTabs();\n const idx = this._getAvailableIndex(0, 1);\n this._selectTab(tabs[idx % tabs.length]);\n }",
"next() {\n var selected = this.getSelection()[0];\n var go = this._indexOf(selected) + 1;\n var children = this._getChildren();\n\n var next = children[go] || children[0];\n\n this.setSelection([next]);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the measure question from a set of numeric responses | function getMeasureQuestionFromNumericResponses(numericResponses) {
for (var i = 0; i < numericResponses.length; i++) {
// Check if we hit the magic measure question
if (numericResponses[i].question_id == this.standardMeasureQuestion.id) {
return numericResponses[i];
}
}
return new Array();
} | [
"function getMeasureQuestionAnswer(measureQuestion) {\n\n var possibleAnswers = this.standardMeasureQuestion.answers;\n\n // Loop through our predefined array of measure question answers (excellent, very good...)\n for (answer in possibleAnswers) {\n\n // Get question column\n if (measureQuestion.option3 == possibleAnswers[answer].id) {\n\n if (SWEET_DEBUG) {\n response.writeLine('Respondents answer is ' + answer);\n }\n return possibleAnswers[answer];\n\n }\n\n }\n\n if (SWEET_DEBUG) {\n response.writeLine('Respondent didnt answer measure question');\n }\n\n return null;\n }",
"analyzeConceptnetScores (responses) {\n let maxWeight = 0\n let response = \"Sorry, i don't know ...'\"\n for (let i = 0; i < responses.length; i++) {\n if (responses[i].weight > maxWeight) {\n response = this.clean(responses[i].surfaceText)\n maxWeight = responses[i].weight\n }\n }\n return response\n }",
"function processAnswerMMC(answer,mc1,mc2,mc3,mc4,mc5){\n\n var a;\n if(answer.search('a')>=0)\n var a = '[{\"answer_text\":\"'+mc1+'\",\"answer_weight\":100}';\n else {\n var a = '[{\"answer_text\":\"'+mc1+'\",\"answer_weight\":0}';\n }\n\n if(answer.search('b')>=0)\n a = a+',{\"answer_text\":\"'+mc2+'\",\"answer_weight\":100}';\n else {\n a = a+',{\"answer_text\":\"'+mc2+'\",\"answer_weight\":0}';\n }\n\n if(mc3 != null && mc3 != ''){\n if(answer.search('c')>=0)\n a = a+',{\"answer_text\":\"'+mc3+'\",\"answer_weight\":100}';\n else {\n a = a+',{\"answer_text\":\"'+mc3+'\",\"answer_weight\":0}';\n }\n }\n if(mc4 != null && mc4 != ''){\n if(answer.search('d')>=0)\n a = a+',{\"answer_text\":\"'+mc4+'\",\"answer_weight\":100}';\n else {\n a = a+',{\"answer_text\":\"'+mc4+'\",\"answer_weight\":0}';\n }\n }\n if(mc5 != null && mc5 != ''){\n if(answer.search('e')>=0)\n a = a+',{\"answer_text\":\"'+mc5+'\",\"answer_weight\":100}';\n else {\n a = a+',{\"answer_text\":\"'+mc5+'\",\"answer_weight\":0}';\n }\n }\n a = a+']';\n return a;\n }",
"function collectResponses()\n{\n\tvar responses = {};\n\t\n\tfor (var c = 0; c < calc_categories.length; c++)\n\t{\n\t\tvar category = calc_categories[c].name;\n\t\tresponses[category] = [];\n\t\t\n\t\tvar questionElements = document.querySelectorAll(\".question[data-category~=\\\"\" + category + \"\\\"] > .choice.selected\");\n\t\t\n\t\tfor (var q = 0; q < questionElements.length; q++)\n\t\t{\n\t\t\tif (questionElements[q].dataset.value != null)\n\t\t\t\tresponses[category].push(parseInt(questionElements[q].dataset.value));\n\t\t}\n\t}\n\t\n\treturn responses;\n}",
"function get_correct_answers() {\n if (qtype === 'reading') {\n if (itype === 'k') {\n switch (item.emph) {\n case \"onyomi\": return item.on;\n case \"kunyomi\": return item.kun;\n case \"nanori\": return item.nanori;\n }\n } else {\n return item.kana;\n }\n } else {\n return [].concat(item.syn,item.en);\n }\n }",
"function getAnswerText({\n valueBoolean,\n valueDecimal,\n valueInteger,\n valueDate,\n valueDateTime,\n valueTime,\n valueString,\n valueUri,\n valueAttachment,\n valueCoding,\n valueQuantity,\n valueCalculation\n}) {\n let response = '';\n\n if (typeof valueBoolean !== 'undefined') {\n if (valueBoolean === true || valueBoolean === false) {\n response += valueBoolean;\n } else {\n errors.push('valueBoolean can only be a true or false value');\n }\n }\n\n if (typeof valueDecimal !== 'undefined') {\n response += valueDecimal;\n console.log((typeof valueDecimal).toString());\n }\n\n if (typeof valueInteger !== 'undefined') {\n if (Number.isInteger(valueInteger)) {\n response += valueInteger;\n } else {\n errors.push('valueInteger must be a valid Integer value');\n }\n response += valueInteger;\n }\n\n if (typeof valueDate !== 'undefined') {\n response += valueDate;\n }\n\n if (typeof valueDateTime !== 'undefined') {\n response += valueDateTime;\n }\n\n if (typeof valueTime !== 'undefined') {\n response += valueTime;\n }\n\n if (typeof valueString !== 'undefined') {\n response += valueString;\n }\n\n if (typeof valueUri !== 'undefined') {\n response += valueUri;\n }\n\n if (typeof valueAttachment !== 'undefined') {\n response += valueAttachment;\n }\n\n if (typeof valueCoding !== 'undefined') {\n response += valueCoding;\n }\n\n if (typeof valueQuantity !== 'undefined') {\n response += valueQuantity;\n }\n if (typeof valueCalculation !== 'undefined') {\n response += String(valueCalculation);\n }\n\n return response;\n}",
"function calcAnswer(rules, numbers) {\n let answer = [];\n try {\n for (let n of numbers) {\n let tempo = [];\n for (let r of rules) {\n if (n % r[\"number\"] === 0) {\n tempo.push(r[\"response\"]);\n }\n }\n let result = tempo.join(\"\");\n if (result === \"\") {\n result = String(n);\n }\n answer.push(result);\n }\n } catch (error) {\n console.log(\"Something Bad Happened!!\")\n console.log(error);\n }\n return {\"answer\": answer.join(\" \")};\n}",
"function getQuestionStats() {\n return questions;\n }",
"function qualityMetrics() {\n let auto = [];\n let manual = [];\n for (let entry of texts) {\n (entry.automaticSpeed ? auto : manual).push(entry);\n }\n auto.sort((entry) => entry.score);\n manual.sort((entry) => entry.score);\n\n /**\n * @param {Entry[]} group\n */\n const stats = (group) => {\n const scores = group.map((entry) => entry.score);\n return {\n scores: scores.reduce((object, score, i) => {\n const firstWord = group[i].text.split(/\\s+/)[0];\n object[firstWord] = score;\n return object;\n }, {}),\n min: scores[0],\n max: scores[scores.length - 1],\n mean: scores.reduce((a, b) => a + b) / scores.length,\n expectedYesRatio:\n group.filter((entry) => entry.expectedAnswer === \"yes\").length /\n group.length,\n longestWords: group.map(\n (entry) =>\n entry.text.split(/\\s+/).sort((a, b) => b.length - a.length)[0]\n ),\n };\n };\n\n return {\n auto: stats(auto),\n manual: stats(manual),\n };\n}",
"function getScoreInfoForAnswer (question, answer) {\n\t// Search questionInfo for the question\n\tfor (let i = 0; i < questionInfo.length; i++) {\n\t\tconst info = questionInfo[i];\n\t\tif (info.text === question) {\n\t\t\t// Found the question! Now try to match the answer.\n\t\t\tfor (let j = 0; j < info.choices.length; j++) {\n\t\t\t\tconst choice = info.choices[j];\n\t\t\t\tif (choice.text === answer) {\n\t\t\t\t\t// We found the answer. Return our array of information.\n\t\t\t\t\treturn [info.domain, info.facet, choice.score];\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Answer not found\n\t\t\tif (answer !== \"\") {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.log(`Unrecognized answer '${answer}' for question '${question}'`);\n\t\t\t}\n\t\t\treturn [info.domain, info.facet, -1];\n\t\t}\n\t}\n\t// Question not found.\n\t// eslint-disable-next-line no-console\n\tconsole.log(`Unrecognized question '${question}'`);\n\treturn [null, null, null];\n}",
"function getSurveyResults(clickedCard) {\n var answersArr = [];\n for (index = 1; index <= 9; index++) {\n var classname = '.q' + index;\n var answer = $.trim($(clickedCard).find(classname).text());\n switch(answer) {\n case '0':\n answer = \"Not At All (0)\";\n break;\n case '1':\n answer = \"Several Days (1)\";\n break;\n case '2':\n answer = \"More Than Half the Days (2)\";\n break;\n case '3':\n answer = \"More Than Every Day (3)\";\n break;\n }\n answersArr.push(answer);\n }\n\n return answersArr;\n }",
"function getResponse(myWeights, offer, quantity, sum, minWeightTreshold, minResTreshold)\r\n\r\n {\r\n\r\n // calculate score for proposed solution\r\n\r\n var score = dotProduct(offer, myWeights);\r\n\r\n var response = [];\r\n\r\n\r\n\r\n if (score >= minResTreshold)\r\n\r\n {\r\n\r\n // good proposition nothing to do\r\n\r\n return response;\r\n\r\n }\r\n\r\n\r\n\r\n // get all possible weigths respective to 'quantity' and 'sum'\r\n\r\n var weigths = calcAllPossibleWeights(quantity, sum);\r\n\r\n var nWeights = weigths.length;\r\n\r\n var opponentSolution = substract(quantity, offer);\r\n\r\n // select weigths relevant for opponent\r\n\r\n var acceptWeights = [];\r\n\r\n for (var idx = 0; idx < nWeights; ++idx)\r\n\r\n {\r\n\r\n var weight = weigths[idx];\r\n\r\n if (dotProduct(weight, opponentSolution) >= minWeightTreshold)\r\n\r\n {\r\n\r\n acceptWeights.push(weight.slice());\r\n\r\n }\r\n\r\n }\r\n\r\n var nAcceptWeights = acceptWeights.length;\r\n\r\n if (0 == nAcceptWeights)\r\n\r\n {\r\n\r\n // something wrong ...\r\n\r\n return response;\r\n\r\n }\r\n\r\n\r\n\r\n // get all acceptable for me solutions\r\n\r\n var solutions = getAllSolutions(quantity, myWeights, sum, minResTreshold);\r\n\r\n var nSolutions = solutions.length;\r\n\r\n\r\n\r\n // get any solution giving maximal sum for opponent\r\n\r\n for (var s = 0; s < nSolutions; ++s)\r\n\r\n {\r\n\r\n var mySolution = solutions[s];\r\n\r\n var opponentSolution = substract(quantity, mySolution);\r\n\r\n var myScore = dotProduct(mySolution, myWeights);\r\n\r\n // calculate sum of scores for opponent per solution\r\n\r\n var sum = 0;\r\n\r\n for (var w = 0; w < nAcceptWeights; ++w)\r\n\r\n {\r\n\r\n var opponentScore = dotProduct(opponentSolution, acceptWeights[w]);\r\n\r\n sum += opponentScore;\r\n\r\n }\r\n\r\n // fill statistics\r\n\r\n if (sum > 0)\r\n\r\n {\r\n\r\n response.push(new Stat(mySolution, sum, myScore));\r\n\r\n }\r\n\r\n }\r\n\r\n if (0 == response.length)\r\n\r\n {\r\n\r\n // probably wrong thresholds for data were selected\r\n\r\n return response;\r\n\r\n }\r\n\r\n response.sort(compare);\r\n\r\n return response;\r\n\r\n }",
"function surveyDepartment(){\n var arrayResp = [];\n for(var i=0 ; i < 10 ; i++){\n arrayResp[i] = randomResponses(responses);\n }\n return arrayResp;\n}",
"function setQuestions(response){\n for (let i = 0; i < 1; i++){\n //response returns response_code and results\n //let questions = JSON.parse(response.result);\n questions = response.results[i];\n // console.log(questions)\n //console.log(typeof questions)\n givePosibleAnswers(response.results[i].incorrect_answers, response.results[i].correct_answer,response.results[i].question);\n }\n}",
"async function getSpecificAnswers(map, responses) {\n\tconst result = {};\n\n\tfor (let i = 0; i < responses.length; i++) { // iterate through the pages in the responses\n\t\tconst page = responses[i]; // get page\n\t\tif (page.questions) { // check if the page has any questions\n\t\t\tpage.questions = await formatAnswers(page.questions);\n\t\t\tfor (let j = 0; j < page.questions.length; j++) { // iterate through the questions\n\t\t\t\tconst question = page.questions[j]; // get question\n\t\t\t\tconst desiredQuestion = await map.find((x) => x.questionID.toString() === question.id.toString()); // check if this question is one of the question we're looking for\n\t\t\t\tif (desiredQuestion) { // check if we found a desirable question\n\t\t\t\t\tconst theAnswer = await getAnswer(question); // get the actual answer from the question\n\t\t\t\t\tif (theAnswer) { // check if we did find an answer\n\t\t\t\t\t\tresult[desiredQuestion.paramName] = theAnswer; // create an aux obj with the name of the param and the answer found\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}",
"function calcDistictAnswers(answers, question) {\n\n //Check if answers contains more than one submission and question is defined\n if (answers.length < 1 || question == undefined) {\n console.log(\"Error in calculating disctinct answers: No answers provided or question missing\")\n return;\n }\n\n //Prepare return object\n var result = new Array();\n\n if (question.questionType == \"multi-choice\") {\n //All submissions must have same amount of options\n var optionsLength = question.questionOptions.length;\n\n //Get correct answer\n var solution = new Array();\n for (var i = 0; i < optionsLength; i++) {\n if (question.questionType == \"multi-choice\") {\n solution.push(question.questionOptions[i].correct);\n } else {\n solution.push(question.questionOptions[i].text);\n }\n };\n console.log(solution);\n\n //Iterate over answers\n for (var i = 0; i < answers.length; i++) {\n //Check if answer has the correct amount of options\n if (answers[i].submission.length != optionsLength) {\n console.log(\"Error in calculating disctinct options: Multiple choice options differ in length. This can't be as every answer has to have the same length.\")\n }\n\n //Remember id answer is not part of results yet\n var newAnswer = true\n\n //Check if answer was seen before. If yes increase quantity, if no add to results.\n\n for (var j = 0; j < result.length; j++) {\n //Check if answer alreday exists in results and if yes increase quantity\n if (arrayEqual(result[j].submission, answers[i].submission)) {\n result[j].quantity++;\n newAnswer = false;\n break;\n }\n };\n //If still new anser add to reluts\n if (newAnswer) {\n\n //Check if new answer is correct\n var correct = arrayEqual(answers[i].submission, solution);\n\n //text for each dataset\n var optionText = \"\";\n //text that contains all selected answer option texts\n\n var selected = new Array();\n for (var k = 0; k < answers[i].submission.length; k++) {\n if (answers[i].submission[k] == true) {\n selected.push(question.questionOptions[k].text.trim());\n optionText = optionText + String.fromCharCode(65 + k) + \" \";\n }\n };\n\n if (question.questionType == \"multi-choice\") {\n optionText = optionText + \"- \" + selected.join(\", \");\n\n } else {\n console.log(\"Qswefrgth\");\n optionText = selected.join(\", \");\n }\n\n //push new answer to results\n result.push({\n submission : answers[i].submission,\n text : optionText,\n correct : correct,\n quantity : 1 //How often option was selected\n });\n }\n\n };\n }\n //Text questions\n else if (question.questionType = \"text-input\") {\n for (var i = 0; i < answers.length; i++) {\n //Test if answer is new, if no increase quantity in results\n var isNewAnswer = true;\n for (var j = 0; j < result.length; j++) {\n if (arrayEqual(result[j].submission, answers[i].submission)) {\n isNewAnswer = false;\n result[j].quantity++;\n }\n };\n\n //If new answer push to results\n if (isNewAnswer) {\n var newAnswer = {\n submission : answers[i].submission,\n text : answers[i].submission.join(),\n correct : false,\n quantity : 1 //How often option was selected\n }\n if (answers[i].correctness == 100) {\n newAnswer.correct = true;\n }\n result.push(newAnswer)\n }\n };\n }\n //Else (missing or unknown question type) log error\n //else{\n // console.log(\"Error in calculating disctinct options: question type is unknown or mission: \");\n // console.log(question.questionType)\n //}\n\n return result;\n}",
"function getAnswers()\n{\n\tif (appTop.booAlertQuestions)\n\t{\n\t\talert(\"Correct options: \" + refNum.toString().split(\"\"))\n\t}\n\tvar _intLength = new String(refNum).length;\n\tvar _intDivNum = Math.pow(10,(_intLength-1));\n\n\tfor (var i=0; i<_intLength; i++)\n\t{\n\t\tbooCorrectAnswers[i] = Math.floor(refNum/_intDivNum);\n\t\trefNum = refNum % _intDivNum;\n\t\t_intDivNum = _intDivNum / 10;\n\t}\n}",
"function getQuestionStats() {\n return questions;\n }",
"async function getRankedResponses(model, query, responses) {\n const input = {\n queries: [query],\n responses: responses\n };\n\n const embeddings = await model.embed(input);\n\n // We use just one query input\n const inputTensor = embeddings['queryEmbedding'].arraySync()[0];\n\n const responseTensors = embeddings['responseEmbedding'].arraySync();\n\n let scores = [];\n for(let i = 0; i < responseTensors.length; i++) {\n scores.push({\n response: responses[i],\n score: dotProduct(inputTensor, responseTensors[i])\n });\n }\n\n scores = scores.sort((el1, el2) => { el2 - el1});\n\n return scores;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grabs values from the comment form fields and places them in the object which is subsequently pushed into an array | function getVal() {
let obj = {};
obj.userName = document.getElementById('name').value;
obj.userComment = document.getElementById('comment').value;
arrayOfDynamicComments.push(obj);
} | [
"function postNewComments(input, formData) {\n // return array of only objects that has new comments and with all other properties\n const updatedData = [];\n\n for (const id in formData) {\n const matchingData = input.find((element) => {\n return element.id == id;\n });\n\n if (matchingData.comments !== formData[id]) {\n matchingData.comments = formData[id];\n updatedData.push(matchingData);\n }\n }\n\n return updatedData;\n}",
"function getCommentPost(event) {\n const newComment = {\n name: event.target.commentsFormName.value,\n comment: event.target.commentsFormComment.value,\n datestamp: new Date(),\n photo: \" \",\n };\n // clears the input elements\n clearForm();\n return newComment; //returns the new comment as an object\n }",
"function ParseToCommentHiddenField() {\n var comArray = new Array();\n $(\"#tCommentData li span.tc\").each(function (index) {\n var tCom = $(this).html();\n if (tCom != null) {\n comArray.push(tCom);\n }\n });\n $(\"input[id=commentHiddenField]\").attr(\"value\", JSON.stringify(comArray));\n}",
"addComments(comments) {\n for (var i = 0; i < comments.length; i++) {\n this.comments.push(comments[i]);\n }\n }",
"function buildForm() {\n return [\n $('#title').val(),\n $('#year').val(),\n $('#director').val(),\n $('#imdbRating').val(),\n $('#rating').val(),\n $('#genre').val()\n ];\n}",
"function makeCommentObject(){\n let comment = {}\n comment.name = nameInput.value\n comment.comment = commentInput.value\n return comment\n}",
"function createComment(event) {\n event.preventDefault();\n var nameVal = event.target.name.value;\n var dateVal = new Date();\n var messageVal = event.target.comment.value;\n if (nameVal !== \"\" && messageVal !== \"\") {\n comments.push({\n name: nameVal,\n date: dateVal,\n message: messageVal,\n });\n commentForm.reset();\n listComments(dateSortArray(comments));\n } else {\n alert(\"Please add a name and message\");\n }\n}",
"function saveCommentObject() {\n\torderItems[commentItemPos].notes = $('#commentBox').val();\n\tconsole.log(orderItems);\n\t$('#commentBox').val(''); //Clear comment box\n\t$('#commentModal').modal('toggle');\n}",
"function _readCampaignInputs() {\r\n //INPUT fields have ID's campedit-<name>-input\r\n var fields = model.def.fields;\r\n var field, val;\r\n for (var i = 0; i < fields.length; i++) {\r\n field = fields[i];\r\n val = $(\"#campedit-\" + field.name + \"-input\").val();\r\n if (val) {\r\n \tif (field.isarrayfield) {\r\n if (!model.campaign[field.name]) {\r\n \tmodel.campaign[field.name] = [];\r\n }\r\n model.campaign[field.name].push(val);\r\n \t} else {\r\n \t\tmodel.campaign[field.name] = val;\r\n \t}\r\n }\r\n }\r\n model.addToCampaignId = $(\"#campaign-addto-list\").val();\r\n }",
"function getPostInputs() {\n\t\treturn { title : $blogTitle.val() , description : $blogDescription.val() , content : $blogContent.val() };\n\t}",
"function populateListArray(form, arr){\n\n\t\tcInd=0;\n\t\tfor(i=0; i<form.elements.length; i++){\n\t\n\t\t\tvar cType = form.elements[i].type;\n\n\t\t\tswitch(cType){\n\t\t\t\tcase \"checkbox\":\n\t\t\t\t\tvar cValue = form.elements[i].checked;\n\t\t\t\t\tarr[cInd++]=cValue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"text\":\n\t\t\t\t\tvar cValue = form.elements[i].value;\n\t\t\t\t\tarr[cInd++]=cValue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"radio\":\n\t\t\t\t\tvar cValue = form.elements[i].checked;\n\t\t\t\t\tarr[cInd++]=cValue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"select-one\":\n\t\t\t\t\tvar cValue = form.elements[i].value;\n\t\t\t\t\tarr[cInd++]=cValue;\n\t\t\t\t\tbreak;\n\t\t\t\t\t\n\t\t\t\tcase \"textarea\":\n\t\t\t\t\tvar cValue = form.elements[i].value;\t\t\t\n\t\t\t\t\tarr[cInd++]=cValue;\n\t\t\t\t\tbreak;\n\t\t\t}\t\n\t\t}\n\n\t}",
"function makeCommentData(){\n commentId++;\n windowId++;\n var newComment = {\n id: commentId,\n windowId: 'w'+windowId,\n message: $scope.commentInput,\n user: currentUsersInfo[0],\n location: [\n $scope.userPosition.coords.latitude,\n $scope.userPosition.coords.longitude\n ]\n };\n return newComment;\n }",
"function populateComments(comments) {\n var commentsDiv = document.getElementById(\"issueComments\")\n for(var i = 0; i < comments.length; i++) {\n var comment = comments[i]\n var date = `<em><font size=\"-1\">${comment.created_at.slice(0,10)}</font></em>`\n var author = `<a href=\"${comment.user.html_url}\">${comment.user.login}</a>`\n var body = htmlify(comment.body)\n\n post = document.createElement(\"p\");\n post.innerHTML = `<b>${author}</b> ${date} <br />${htmlify(body)}<br /><br />`\n commentsDiv.appendChild(post);\n }\n}",
"function addComment(talkIndex){ \n let commentBox = document.getElementById(\"test\").querySelector('#inputComments' + talkIndex).value;\n let usernameBox = document.getElementById(\"test\").querySelector('#inputUsername' + talkIndex).value;\n\n const newComment = {\n index: talkIndex,\n id: speakerArray[talkIndex].id,\n talkCounter: speakerArray[talkIndex].counter,\n username: usernameBox,\n date: getTimestamp,\n location: getLocation,\n content: commentBox\n }\n \n comments.push(newComment); \n saveLocalStorage(comments);\n console.log(comments);\n viewComments(talkIndex);\n}",
"function submit(){\n\tvar codeSnippet = {\n\n\t\ttitle:$(\"#title\").val(),\n\t\tcode:$(\"#code\").val(),\n\t\ttagIt:$(\"#tagIt\").val(),\n\t\tcomments: $(\"#comments\").val()\n\n\n\t}; \n\n\t// this line clears out the form \n \t$('#title, #code, #tagIt , #comments').val('');\n\n \t// add to firebase repository \n\tobjectsInFirebase.push(codeSnippet);\n\n\n}",
"function collectDataFromFields(){\n function fillValue($form, fieldSetName, $field, counter, valToVal){\n var name = $field.attr(\"name\");\n\n if (!name) {\n return;\n }\n\n //strip ./\n if (name.indexOf(\"./\") == 0) {\n name = name.substring(2);\n }\n\n var value = $field.val();\n\n if( $field.prop(\"type\") == \"checkbox\" ){\n value = $field.prop(\"checked\") ? $field.val() : \"\";\n }\n\n $('<input />').attr('type', 'hidden')\n .attr('name', fieldSetName + \"/\" + counter + \"/\" + name)\n .attr('value', value )\n .appendTo($form);\n\n\n //remove the field, so that individual values are not POSTed\n $field.remove();\n }\n\n $(document).on(\"click\", \".cq-dialog-submit\", function () {\n var $multifields = $(\"[\" + DATA_EAEM_NESTED + \"]\");\n\n if(_.isEmpty($multifields)){\n return;\n }\n\n var $form = $(this).closest(\"form.foundation-form\"),\n $fieldSets, $fields;\n\n $multifields.each(function(i, multifield){\n $fieldSets = $(multifield).find(\"[class='coral-Form-fieldset']\");\n\n $fieldSets.each(function (counter, fieldSet) {\n $fields = $(fieldSet).children().children(CFFW);\n //TO Store as Child Notes\n var valToVal = '';\n $fields.each(function (j, field) {\n\n if(valToVal == ''){\n valToVal = $(field).find(\"[name]\").val();\n\n } else {\n var str = $(field).find(\"[name]\").val();\n valToVal = valToVal + \":\" + str;\n }\n\n fillValue($form, $(fieldSet).data(\"name\"), $(field).find(\"[name]\"), (counter + 1));\n });\n\n //add the record JSON in a hidden field as string - support classic UI\n $('<input />').attr('type', 'hidden')\n .attr('name', SOLR_FACET_FIELDS)\n .attr('value', valToVal)\n .appendTo($form);\n\n\n });\n });\n });\n }",
"function collectDataFromFields(){\n function fillValue($form, fieldSetName, $field, counter){\n var name = $field.attr(\"name\");\n\n if (name) {\n //strip ./\n if (name.indexOf(\"./\") == 0) {\n name = name.substring(2);\n }\n\n //remove the field, so that individual values are not POSTed\n $field.remove();\n\n $('<input />').attr('type', 'hidden')\n .attr('name', fieldSetName + \"/\" + counter + \"/\" + name)\n .attr('value', $field.val())\n .appendTo($form);\n }\n\n }\n\n $(document).on(\"click\", \".cq-dialog-submit\", function () {\n var $multifield = $(\"[\" + DATA_EAEM_NESTED + \"]\").first();\n\n if( _.isNotEmpty($multifield)){\n var childPrefix = $multifield.attr('data-element-prefix');\n var $form = $(this).closest(\"form.foundation-form\");\n var $fieldSets;\n var $fields;\n\n $fieldSets = $multifield.find(\"[class='coral-Form-fieldset']\");\n\n $fieldSets.each(function (counter, fieldSet) {\n $fields = $(fieldSet).children().children(CFFW);\n\n $fields.each(function (j, field) {\n fillValue($form, $(fieldSet).data(\"name\"), $(field).find(\"[name]\"), childPrefix + (counter + 1));\n });\n });\n }\n });\n }",
"function getFormObjects() {\n\n let formObjects = [];\n\n $$('#form .input-box').forEach(el => {\n\n formObjects.push({\n name: el.querySelectorAll('input')[0].value,\n quant: el.querySelectorAll('input')[1].value\n });\n\n });\n\n return formObjects;\n\n }",
"function squashCommentFields() {\n var phone_val = $('form#contact input#phone').val();\n var time_val = $('form#contact input#time').val();\n var contact_method_val = ($(\"form#contact input#via-phone\").is(':checked') ? \"via-phone\" : \"\") + ($(\"form#contact input#via-email\").is(':checked') ? \" via-email\" : \"\");\n var promo_name = $('form#contact').attr(\"name\");\n var new_comment_val = \"Promo: \" + promo_name + \" Phone: \" + phone_val + \" Good time to call: \" + time_val + \" Preferred contact method: \" + contact_method_val\n $('form#contact input#comment').val(new_comment_val);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for repositoriesWorkspaceRepoSlugCommitNodeApprovePost / Approve the specified commit as the authenticated user. This operation is only available to users that have explicit access to the repository. In contrast, just the fact that a repository is publicly accessible to users does not give them the ability to approve commits. | repositoriesWorkspaceRepoSlugCommitNodeApprovePost(incomingOptions, cb) {
const Bitbucket = require('./dist');
let defaultClient = Bitbucket.ApiClient.instance;
// Configure API key authorization: api_key
let api_key = defaultClient.authentications['api_key'];
api_key.apiKey = incomingOptions.apiKey;
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';
// Configure HTTP basic authorization: basic
let basic = defaultClient.authentications['basic'];
basic.username = 'YOUR USERNAME';
basic.password = 'YOUR PASSWORD';
// Configure OAuth2 access token for authorization: oauth2
let oauth2 = defaultClient.authentications['oauth2'];
oauth2.accessToken = incomingOptions.accessToken;
let apiInstance = new Bitbucket.CommitsApi(); // String | The commit's SHA1 // String | This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`. // String | This can either be the repository slug or the UUID of the repository, surrounded by curly-braces, for example: `{repository UUID}`.
/*let node = "node_example";*/ /*let workspace = "workspace_example";*/ /*let repoSlug = "repoSlug_example";*/ apiInstance.repositoriesWorkspaceRepoSlugCommitNodeApprovePost(
incomingOptions.node,
incomingOptions.workspace,
incomingOptions.repoSlug,
(error, data, response) => {
if (error) {
cb(error, null, response);
} else {
cb(null, data, response);
}
}
);
} | [
"getAllApprovePost({ commit }, payload) {\n return new Promise((resolve, reject) => {\n const query = new URLSearchParams(payload).toString();\n axios\n .get(`${ENDPOINTS.POSTS.GET}/approved?${query}`)\n .then(res => {\n commit(\"SET_POST\", res.data);\n resolve(res);\n })\n .catch(err => reject(err));\n });\n }",
"async addPrInfoToCommit(commit) {\n const modifiedCommit = Object.assign({}, commit);\n if (!modifiedCommit.labels) {\n modifiedCommit.labels = [];\n }\n if (modifiedCommit.pullRequest) {\n const [err, info] = await await_to_js_1.default(this.git.getPr(modifiedCommit.pullRequest.number));\n if (err || !info || !info.data) {\n return modifiedCommit;\n }\n const labels = info ? info.data.labels.map((l) => l.name) : [];\n modifiedCommit.labels = [\n ...new Set([...labels, ...modifiedCommit.labels]),\n ];\n modifiedCommit.pullRequest.body = info.data.body;\n modifiedCommit.subject = info.data.title || modifiedCommit.subject;\n const hasPrOpener = modifiedCommit.authors.some((author) => author.username === info.data.user.login);\n // If we can't find the use who opened the PR in authors attempt\n // to add that user.\n if (!hasPrOpener) {\n const user = await this.git.getUserByUsername(info.data.user.login);\n if (user) {\n modifiedCommit.authors.push(Object.assign(Object.assign({}, user), { username: user.login }));\n }\n }\n }\n return modifiedCommit;\n }",
"grantManualApproval(grantable) {\n if (!this.stage) {\n throw new Error('Cannot grant permissions before binding action to a stage');\n }\n grantable.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({\n actions: ['codepipeline:ListPipelines'],\n resources: ['*'],\n }));\n grantable.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({\n actions: ['codepipeline:GetPipeline', 'codepipeline:GetPipelineState', 'codepipeline:GetPipelineExecution'],\n resources: [this.stage.pipeline.pipelineArn],\n }));\n grantable.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({\n actions: ['codepipeline:PutApprovalResult'],\n resources: [`${this.stage.pipeline.pipelineArn}/${this.stage.stageName}/${this.props.actionName}`],\n }));\n }",
"async approve(request, response) {\n\t\tconst resolver = new RouteResolver('announcement', this.layer.approveAnnouncement, [request.body._id]);\n\t\tawait this.handleRoute(request, response, 'Admin', resolver);\n\t}",
"approve() {\n\t\t\t\tif (Phased.team.members[Phased.user.uid].role != Phased.meta.ROLE_ID.ADMIN \n\t\t\t\t\t&& Phased.team.members[Phased.user.uid].role != Phased.meta.ROLE_ID.OWNER) {\n\t\t\t\t\tthrow new Error('User must be admin to approve or reject task completion');\n\t\t\t\t}\n\n\t\t\t\tif (this.status != Phased.meta.task.STATUS_ID.IN_REVIEW) {\n\t\t\t\t\tthrow new Error('Task must be in review before approval or rejection');\n\t\t\t\t}\n\n\t\t\t\tthis.status = Phased.meta.task.STATUS_ID.COMPLETE;\n\t\t\t\t\n\t\t\t\tStatusFactory.create({\n\t\t\t\t\tname : `${appConfig.strings.status.prefix.task.approvedReview}: ${this.name}`,\n\t\t\t\t\ttaskID : this.ID\n\t\t\t\t}).then(statusID => {\n\t\t\t\t\tthis.linkStatus(statusID);\n\t\t\t\t}, err => {\n\t\t\t\t\tconsole.warn('Posting status for task failed!', err);\n\t\t\t\t});\n\t\t\t}",
"editUserPermissionForRepo(username, repoId, permission) {\n if (permission === 'none') {\n return repoUtil.removeRepoCollaborator(repoId, username);\n }\n return repoUtil.addRepoCollaborator(repoId, username, permission);\n }",
"handleApproval(event) {\n const email = event.target.id;\n let approvedUser = this.getUser(email);\n this.submitDecision(true, approvedUser.username).then(response => {\n alert(approvedUser.firstName + ' approved successfully!');\n this.updatePending(email);\n }).catch(error => {\n alert(approvedUser.firstName + ' could not be approved');\n })\n }",
"async addPrInfoToCommit(commit) {\n const modifiedCommit = Object.assign({}, commit);\n if (!modifiedCommit.labels) {\n modifiedCommit.labels = [];\n }\n if (modifiedCommit.pullRequest) {\n const info = await this.git.getPr(modifiedCommit.pullRequest.number);\n if (!info || !info.data) {\n return modifiedCommit;\n }\n const labels = info ? info.data.labels.map(l => l.name) : [];\n modifiedCommit.labels = [\n ...new Set([...labels, ...modifiedCommit.labels])\n ];\n modifiedCommit.pullRequest.body = info.data.body;\n if (!modifiedCommit.authors.find(author => Boolean(author.username))) {\n const user = await this.git.getUserByUsername(info.data.user.login);\n if (user) {\n modifiedCommit.authors.push(Object.assign(Object.assign({}, user), { username: user.login }));\n }\n }\n }\n return modifiedCommit;\n }",
"function approve_block_user(approve_disable_user){\n\t\t$(approve_disable_user).click(function(e){\n\t\t\te.preventDefault();\n\t\t\tvar master_user_id \t = $(this).data('id');\n\t\t\tvar master_user_type = $(this).data('type');\n\t\t\t\n\t\t\tif(confirm('Želite li da odobrite pristup korisniku?')){\n\t\t\t\t$.ajax({\n\t\t\t\t\ttype:'POST',\n\t\t\t\t\turl: 'inc/pages/pages_insert_info.php',\n\t\t\t\t\tdata:{ master_user_id:master_user_id, master_user_type:master_user_type },\n\t\t\t\t\tsuccess: function(data){\n\t\t\t\t\t\tif(!data.error){\n\t\t\t\t\t\t\tlocation.reload();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\t\n\t\t\t}\n\t\t});\n\t}",
"approve(comment = \"\") {\r\n return this.clone(File, `approve(comment = '${comment}')`).postCore();\r\n }",
"* postRepo (request, response) {\n const input = request.only('title', 'description','user_description' , 'language', 'create_date', 'oc_login', 'oc_url', 'repo_url')\n\n try {\n // Attempt to authenticate user based on auth token and subsequently create new repo post\n const user = request.authUser\n input.user_id = user.id\n input.github = user.github\n const repo = yield Repo.create(input)\n // Begin Logging Block\n console.log(chalk.dim.white('\\n=============================='))\n console.log(chalk.dim.white(' New Repo Posted'))\n console.log(chalk.dim.white('=============================='))\n console.log(chalk.white('Repo Title: ','%s','\\nemail: ','%s','\\ngithub account:','%s\\n'), input.title,request.authUser.email, request.authUser.github);\n // End Logging Block\n return response.json(repo.toJSON())\n\n } catch (e) {\n return response.status(401).json({ error: e.message });\n }\n }",
"approve(comment = \"\") {\n return spPost(this.clone(File, `approve(comment='${escapeQueryStrValue(comment)}')`));\n }",
"function authorize() {\n\t\tlet username = document.forms[0].elements[0].value;\n\t\tlet password = document.forms[0].elements[1].value;\n\t\trepoInformation.authorize.call(repoInformation, username, password);\n\t\tcloseLoginPopup();\n\t\thideLoginButton();\n\t}",
"approvePublish() {\n\n /**\n * Get scope\n * @type {SiteConfig}\n */\n const scope = this.scope;\n\n /**\n * Define $modal\n * @type {ModalElement}\n */\n const $modal = scope.view.elements.$modal;\n\n if (!$modal) {\n scope.logger.warn('Undefined $modal');\n return false;\n }\n\n /**\n * Get root config\n * @type {{activate: boolean, mode: string}}\n */\n const config = this.root().model.getConfig();\n\n /**\n * Get create update site route\n * @type {{string[]}}\n */\n const route = scope.model.getConfig('routes/publishSiteStorage');\n const key = config.appName,\n opts = {\n dataType: 'json',\n url: route[0].replace(/\\{id}/, key),\n method: route[1]\n };\n\n $.ajax(opts).done((data, type, xhr) => {\n scope.logger.debug(data.notice, arguments);\n $modal.selfDestroy();\n });\n }",
"function onProjectApprove() {\n let projectId = getProjectId();\n\n let body = {\n action: 'approveProject',\n projectId\n };\n\n api.post('/projects.php', body)\n .then(res => {\n // location.reload();\n snackbar(res.message, 'success');\n })\n .catch(err => {\n snackbar(err.message, 'error');\n });\n}",
"submitGitCommit(){\n try {\n this.commitMessage.innerHTML = this.canCommit();\n }\n catch (e) {\n this.commitMessage.innerHTML = e.toString();\n }\n }",
"async toggleApproval(body, responseId, userInfo) {\n const response = await dbContext.Responses.findOne({ _id: responseId })\n // @ts-ignore\n const wager = response._doc.wager\n if (userInfo.roles[0] === 'Host') {\n // const approved = await dbContext.Responses.findByIdAndUpdate(responseId, body, { new: true })\n await dbContext.Responses.findByIdAndUpdate(responseId, body, { new: true })\n // @ts-ignore\n const points = await this.updatePoints(response._doc.teamId, wager, body.approved)\n\n return points\n } else {\n throw new BadRequest('Permission denied')\n }\n }",
"function commitGithub(GH, UI) {\n var d = new Date()\n var ds = d.toLocaleDateString()\n var ts = d.toLocaleTimeString()\n var data = GH.parse(UI);\n data['editcontent'] = UI.geteditor();\n data['commitmsg'] = \"Updated from Brython Server: \"+ds+\" \"+ts;\n $.ajax({\n url : 'api/v1/commit',\n contentType: 'application/json; charset=UTF-8', \n dataType : 'json',\n data : JSON.stringify(data),\n type : 'PUT',\n complete : function() {\n },\n success : function(data){\n },\n error : function(err){\n alert(err.responseJSON.message)\n }\n }); \n }",
"function commitGithub(GH, UI) {\n var d = new Date();\n var ds = d.toLocaleDateString();\n var ts = d.toLocaleTimeString();\n var data = GH.parse(UI);\n data['editcontent'] = UI.geteditor();\n data['commitmsg'] = \"Updated from Brython Server: \" + ds + \" \" + ts;\n UI.showworking();\n $.ajax({\n url: 'api/v1/commit',\n contentType: 'application/json; charset=UTF-8',\n dataType: 'json',\n data: JSON.stringify(data),\n type: 'PUT',\n complete: function() {UI.hideworking();},\n success: function(data) {},\n error: function(err) {\n alert(err.responseJSON.message);\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assemble l'objet de contact et le tableau d'id de produit | function assembleProductEtContact() {
let products = creerTableauCommande();
let contact = creerObjetContact();
return {contact, products};
} | [
"function User_Insert_Contacts_Liste_des_contacts0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 2\n\nId dans le tab: 114;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 115;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"contact\";\n var CleMaitre = TAB_COMPO_PPTES[111].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var cn_type=GetValAt(114);\n if (!ValiderChampsObligatoire(Table,\"cn_type\",TAB_GLOBAL_COMPO[114],cn_type,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cn_type\",TAB_GLOBAL_COMPO[114],cn_type))\n \treturn -1;\n var cn_coordonnee=GetValAt(115);\n if (!ValiderChampsObligatoire(Table,\"cn_coordonnee\",TAB_GLOBAL_COMPO[115],cn_coordonnee,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"cn_coordonnee\",TAB_GLOBAL_COMPO[115],cn_coordonnee))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",cn_type,cn_coordonnee\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(cn_type==\"\" ? \"null\" : \"'\"+ValiderChaine(cn_type)+\"'\" )+\",\"+(cn_coordonnee==\"\" ? \"null\" : \"'\"+ValiderChaine(cn_coordonnee)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}",
"function ajouterContact(nom, prenom){\n\tnouveauContact = new personne(nom, prenom);\n\tlistesContact.push(nouveauContact);\n\tconsole.log(nouveauContact.messageAjout()) ;\n}",
"function affichageTableau(contacts){\n nb=contacts.length;\n $('tbody tr').remove();\n for(let i=0;i<nb;i++){\n $(`\n <tr>\n <td>`+ contacts[i].nom +`</td>\n <td>`+ contacts[i].prenom +`</td>\n <td>`+ contacts[i].email +`</td>\n <td>`+ contacts[i].tel +`</td>\n </tr>\n `).appendTo('#contacts > tbody');\n }\n $('#contact').get(0).reset();\n // -- Affichage du message de réussite\n $(\".alert-contact\").show(10).delay(5000).hide(1000);\n }",
"function traiteReponseAjoutSupContact(rep, id) {\n \tif (rep.error != undefined) {\n \t\talert(rep.error);\n \t} else {\n \t\tvar user = environnement.users[id];\n \t\tuser.modifStatut();\n \t\tliste();\n \t}\n }",
"function creerContact(prenomContact, nomContact) {\n var nouveauContact = Object.create(Contact);\n nouveauContact.init(prenomContact, nomContact);\n contacts.push(nouveauContact);\n var message = \"Le nouveau contact a été ajouté\"\n return message;\n}",
"function cargarCgg_res_persona_contactoCtrls(){\n if(inRecordCgg_res_persona_contacto){\n txtCrprc_codigo.setValue(inRecordCgg_res_persona_contacto.get('CRPRC_CODIGO'));\n txtCrper_codigo.setValue(inRecordCgg_res_persona_contacto.get('CRPER_CODIGO'));\n //txtCrper_codigo.setValue(inCrper_codigo);\n txtCrtco_codigo.setValue(inRecordCgg_res_persona_contacto.get('CRTCO_CODIGO'));\n txtCrprc_descripcion.setValue(inRecordCgg_res_persona_contacto.get('CRPRC_DESCRIPCION'));\n txtCrprc_contacto.setValue(inRecordCgg_res_persona_contacto.get('CRPRC_CONTACTO'));\n isEdit = true;\n habilitarCgg_res_persona_contactoCtrls(true);\n }}",
"function _setup_row_for_client_contact_section(db) {\n\t\t\ttry {\n\t\t\t\tvar rows = db.execute('SELECT * from my_' + _type + ' WHERE id=?', _selected_job_id);\n\t\t\t\tif ((rows.getRowCount() > 0) && (rows.isValidRow())) {\n\t\t\t\t\tif ((rows.fieldByName('client_id') != undefined) && (rows.fieldByName('client_id') != null)) {\n\t\t\t\t\t\t_client_id = rows.fieldByName('client_id');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trows = db.execute('SELECT a.*,my_client_contact.position,my_client_contact.first_name,my_client_contact.last_name FROM my_' + _type + '_client_contact as a' + ' left join my_client_contact on (my_client_contact.id = a.client_contact_id)' + ' WHERE a.' + _type + '_id=? and a.status_code=1 and my_client_contact.status_code=1', _selected_job_id);\n\t\t\t\tvar client_contact_count = rows.getRowCount();\n\t\t\t\tvar i = 0;\n\t\t\t\tif (client_contact_count <= 1) {\n\t\t\t\t\tif (rows.getRowCount() > 0) {\n\t\t\t\t\t\twhile (rows.isValidRow()) {\n\t\t\t\t\t\t\tvar row = Ti.UI.createTableViewRow({\n\t\t\t\t\t\t\t\tfilter_class : 'client_contact',\n\t\t\t\t\t\t\t\tclassName : 'client_contact_' + i,\n\t\t\t\t\t\t\t\theight : 'auto',\n\t\t\t\t\t\t\t\thasChild : true,\n\t\t\t\t\t\t\t\tobject_id : rows.fieldByName('client_contact_id'),\n\t\t\t\t\t\t\t\tjob_client_contact_id : rows.fieldByName('id')\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tvar edit_btn = Ti.UI.createButton({\n\t\t\t\t\t\t\t\tname : 'view_btn',\n\t\t\t\t\t\t\t\tbackgroundImage : self.get_file_path('image', 'BUTT_grn_off.png'),\n\t\t\t\t\t\t\t\tcolor : '#fff',\n\t\t\t\t\t\t\t\tfont : {\n\t\t\t\t\t\t\t\t\tfontSize : _header_view_font_size - 2,\n\t\t\t\t\t\t\t\t\tfontWeight : 'bold'\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\ttitle : 'View',\n\t\t\t\t\t\t\t\ttextAlign : 'center',\n\t\t\t\t\t\t\t\tstyle : Titanium.UI.iPhone.SystemButtonStyle.BORDERED,\n\t\t\t\t\t\t\t\tleft : 10,\n\t\t\t\t\t\t\t\twidth : _header_view_button_width - 5,\n\t\t\t\t\t\t\t\theight : _header_view_button_height\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif ((rows.fieldByName('position') != null) && (self.trim(rows.fieldByName('position')) != '')) {\n\t\t\t\t\t\t\t\tedit_btn.top = 5;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\trow.add(edit_btn);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif ((rows.fieldByName('position') != null) && (self.trim(rows.fieldByName('position')) != '')) {\n\t\t\t\t\t\t\t\tvar title_label = Ti.UI.createLabel({\n\t\t\t\t\t\t\t\t\ttop : 5,\n\t\t\t\t\t\t\t\t\tleft : 10 + _header_view_button_width,\n\t\t\t\t\t\t\t\t\twidth : self.screen_width - 100,\n\t\t\t\t\t\t\t\t\ttext : rows.fieldByName('first_name') + ' ' + rows.fieldByName('last_name'),\n\t\t\t\t\t\t\t\t\theight : 20,\n\t\t\t\t\t\t\t\t\tfont : {\n\t\t\t\t\t\t\t\t\t\tfontSize : self.normal_font_size,\n\t\t\t\t\t\t\t\t\t\tfontWeight : self.font_weight\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trow.add(title_label);\n\t\t\t\t\t\t\t\tvar position_label = Ti.UI.createLabel({\n\t\t\t\t\t\t\t\t\ttop : 25 + 5,\n\t\t\t\t\t\t\t\t\tleft : 10,\n\t\t\t\t\t\t\t\t\twidth : self.screen_width - 100,\n\t\t\t\t\t\t\t\t\ttext : '[' + rows.fieldByName('position') + ']',\n\t\t\t\t\t\t\t\t\theight : 20,\n\t\t\t\t\t\t\t\t\tfont : {\n\t\t\t\t\t\t\t\t\t\tfontSize : self.small_font_size\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trow.add(position_label);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttitle_label = Ti.UI.createLabel({\n\t\t\t\t\t\t\t\t\tleft : 10 + _header_view_button_width,\n\t\t\t\t\t\t\t\t\twidth : self.screen_width - 100,\n\t\t\t\t\t\t\t\t\ttext : rows.fieldByName('first_name') + ' ' + rows.fieldByName('last_name'),\n\t\t\t\t\t\t\t\t\theight : 20,\n\t\t\t\t\t\t\t\t\tfont : {\n\t\t\t\t\t\t\t\t\t\tfontSize : self.normal_font_size,\n\t\t\t\t\t\t\t\t\t\tfontWeight : self.font_weight\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\trow.add(title_label);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tself.data[_section_no].add(row);\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t\trows.next();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trow = Ti.UI.createTableViewRow({\n\t\t\t\t\t\tfilter_class : 'client_contact',\n\t\t\t\t\t\tclassName : 'client_contact_' + 100,\n\t\t\t\t\t\theight : 'auto',\n\t\t\t\t\t\thasChild : true,\n\t\t\t\t\t\twidth : 180,\n\t\t\t\t\t\tleft : 10,\n\t\t\t\t\t\ttitle : 'Client Contacts'\n\t\t\t\t\t});\n\t\t\t\t\tvar client_contact_label = Ti.UI.createLabel({\n\t\t\t\t\t\tright : 5,\n\t\t\t\t\t\tbackgroundColor : self.table_view_row_number_label_background_color,\n\t\t\t\t\t\tcolor : '#fff',\n\t\t\t\t\t\twidth : 30,\n\t\t\t\t\t\theight : 20,\n\t\t\t\t\t\ttextAlign : 'center',\n\t\t\t\t\t\ttext : client_contact_count,\n\t\t\t\t\t\tborderRadius : 8\n\t\t\t\t\t});\n\t\t\t\t\trow.add(client_contact_label);\n\t\t\t\t\tself.data[_section_no].add(row);\n\t\t\t\t}\n\t\t\t\trows.close();\n\t\t\t\t_section_no++;\n\t\t\t} catch (err) {\n\t\t\t\tself.process_simple_error_message(err, window_source + ' - _setup_row_for_client_contact_section');\n\t\t\t\treturn;\n\t\t\t}\n\t\t}",
"function getContactsAndTableBody() {\n tableBody = document.getElementById('tableBody');\n let contactName;\n let contactSurname;\n let contactPhone;\n for (let i = 0; i < tableBody.rows.length; i++) {\n\tcontactName = tableBody.rows[i].cells[0].innerHTML;\n\tcontactSurname = tableBody.rows[i].cells[1].innerHTML;\n\tcontactPhone = tableBody.rows[i].cells[2].innerHTML;\n\tcontacts.push(new contact(contactName, contactSurname, contactPhone))\n }\n}",
"function User_Insert_Personnes_Tâches_25(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 5\n\nId dans le tab: 455;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 456;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = typetache,th_numero,th_numero\n\nId dans le tab: 457;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 458;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 459;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"appel\";\n var CleMaitre = TAB_COMPO_PPTES[449].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var ap_date=GetValAt(455);\n if (!ValiderChampsObligatoire(Table,\"ap_date\",TAB_GLOBAL_COMPO[455],ap_date,false))\n return -1;\n if (!ValiderChampsType(Table,\"ap_date\",TAB_GLOBAL_COMPO[455],ap_date))\n return -1;\n var th_numero=GetValAt(456);\n if (th_numero==\"-1\")\n th_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"th_numero\",TAB_GLOBAL_COMPO[456],th_numero,true))\n return -1;\n var ap_libelle=GetValAt(457);\n if (!ValiderChampsObligatoire(Table,\"ap_libelle\",TAB_GLOBAL_COMPO[457],ap_libelle,false))\n return -1;\n if (!ValiderChampsType(Table,\"ap_libelle\",TAB_GLOBAL_COMPO[457],ap_libelle))\n return -1;\n var ap_duree=GetValAt(458);\n if (!ValiderChampsObligatoire(Table,\"ap_duree\",TAB_GLOBAL_COMPO[458],ap_duree,false))\n return -1;\n if (!ValiderChampsType(Table,\"ap_duree\",TAB_GLOBAL_COMPO[458],ap_duree))\n return -1;\n var ap_description=GetValAt(459);\n if (!ValiderChampsObligatoire(Table,\"ap_description\",TAB_GLOBAL_COMPO[459],ap_description,false))\n return -1;\n if (!ValiderChampsType(Table,\"ap_description\",TAB_GLOBAL_COMPO[459],ap_description))\n return -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pe_numero,ap_date,th_numero,ap_libelle,ap_duree,ap_description\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[405].NewCle+\",\"+(ap_date==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_date)+\"'\" )+\",\"+th_numero+\",\"+(ap_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_libelle)+\"'\" )+\",\"+(ap_duree==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_duree)+\"'\" )+\",\"+(ap_description==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_description)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n alert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}",
"function delete_contact_entreprise(){\n\t// Recuperation de l'id du contact\n\tvar id_contact = liste_infos_contacts.getCoupler().getLastInformation();\n\t\n\tif(id_contact != -1) {\n\t\tvar xhr = new XMLHttpRequest();\n\t\txhr.open(\"DELETE\", \"/personnes/delete/\"+id_contact, false);\n\t\txhr.send();\n\t\t\n\t\tsocket.emit(\"update\",{url: \"/entreprises/\"+newContactForm.getCoupler().getLastInformation()+\"/contacts\",func: getHandler(function(url){\n\t\t\tliste_cts.clear();\n\t\t\tvar datas = DatasBuffer.getRequest(url);\n\t\t\tfor(var i=0; i < datas.length; i++)\n\t\t\t\tliste_cts.addItem('<p class=\"nom_contact\">'+datas[i].prenom+\" \"+datas[i].nom+'</p><p class=\"statut_contact\">'+datas[i].statut+'</p>',datas[i]._id);\n\t\t\tliste_cts.update();\n\t\t})});\n\n\t\tliste_infos_contacts.clear();\n\t\tliste_infos_contacts.update();\n\t\tGraphicalPopup.hidePopup(popup_sup_contact_entreprise.getPopupIndex());\n\t}\n}",
"getAll(){\n\n return this.contactos;\n\n }",
"function User_Insert_Personnes_Tâches_26(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 5\n\nId dans le tab: 58;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 59;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = typetache,th_numero,th_numero\n\nId dans le tab: 60;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 61;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 62;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"appel\";\n var CleMaitre = TAB_COMPO_PPTES[52].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var ap_date=GetValAt(58);\n if (!ValiderChampsObligatoire(Table,\"ap_date\",TAB_GLOBAL_COMPO[58],ap_date,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ap_date\",TAB_GLOBAL_COMPO[58],ap_date))\n \treturn -1;\n var th_numero=GetValAt(59);\n if (th_numero==\"-1\")\n th_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"th_numero\",TAB_GLOBAL_COMPO[59],th_numero,true))\n \treturn -1;\n var ap_libelle=GetValAt(60);\n if (!ValiderChampsObligatoire(Table,\"ap_libelle\",TAB_GLOBAL_COMPO[60],ap_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ap_libelle\",TAB_GLOBAL_COMPO[60],ap_libelle))\n \treturn -1;\n var ap_duree=GetValAt(61);\n if (!ValiderChampsObligatoire(Table,\"ap_duree\",TAB_GLOBAL_COMPO[61],ap_duree,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ap_duree\",TAB_GLOBAL_COMPO[61],ap_duree))\n \treturn -1;\n var ap_description=GetValAt(62);\n if (!ValiderChampsObligatoire(Table,\"ap_description\",TAB_GLOBAL_COMPO[62],ap_description,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"ap_description\",TAB_GLOBAL_COMPO[62],ap_description))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pe_numero,ap_date,th_numero,ap_libelle,ap_duree,ap_description\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[3].NewCle+\",\"+(ap_date==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_date)+\"'\" )+\",\"+th_numero+\",\"+(ap_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_libelle)+\"'\" )+\",\"+(ap_duree==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_duree)+\"'\" )+\",\"+(ap_description==\"\" ? \"null\" : \"'\"+ValiderChaine(ap_description)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}",
"function User_Insert_Personnes_Adresses_9(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 7\n\nId dans le tab: 781;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 782;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 783;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 784;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 785;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = codepostal,cp_numero,cp_numero\n\nId dans le tab: 786;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = ville,vi_numero,vi_numero\n\nId dans le tab: 787;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"adresse\";\n var CleMaitre = TAB_COMPO_PPTES[776].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var ad_ligne2=GetValAt(781);\n if (!ValiderChampsObligatoire(Table,\"ad_ligne2\",TAB_GLOBAL_COMPO[781],ad_ligne2,false))\n return -1;\n if (!ValiderChampsType(Table,\"ad_ligne2\",TAB_GLOBAL_COMPO[781],ad_ligne2))\n return -1;\n var ad_ligne3=GetValAt(782);\n if (!ValiderChampsObligatoire(Table,\"ad_ligne3\",TAB_GLOBAL_COMPO[782],ad_ligne3,false))\n return -1;\n if (!ValiderChampsType(Table,\"ad_ligne3\",TAB_GLOBAL_COMPO[782],ad_ligne3))\n return -1;\n var ad_ligne4=GetValAt(783);\n if (!ValiderChampsObligatoire(Table,\"ad_ligne4\",TAB_GLOBAL_COMPO[783],ad_ligne4,false))\n return -1;\n if (!ValiderChampsType(Table,\"ad_ligne4\",TAB_GLOBAL_COMPO[783],ad_ligne4))\n return -1;\n var ad_ligne5=GetValAt(784);\n if (!ValiderChampsObligatoire(Table,\"ad_ligne5\",TAB_GLOBAL_COMPO[784],ad_ligne5,false))\n return -1;\n if (!ValiderChampsType(Table,\"ad_ligne5\",TAB_GLOBAL_COMPO[784],ad_ligne5))\n return -1;\n var cp_numero=GetValAt(785);\n if (cp_numero==\"-1\")\n cp_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"cp_numero\",TAB_GLOBAL_COMPO[785],cp_numero,true))\n return -1;\n var vi_numero=GetValAt(786);\n if (vi_numero==\"-1\")\n vi_numero=\"null\";\n if (!ValiderChampsObligatoire(Table,\"vi_numero\",TAB_GLOBAL_COMPO[786],vi_numero,true))\n return -1;\n var ad_default=GetValAt(787);\n if (!ValiderChampsObligatoire(Table,\"ad_default\",TAB_GLOBAL_COMPO[787],ad_default,false))\n return -1;\n if (!ValiderChampsType(Table,\"ad_default\",TAB_GLOBAL_COMPO[787],ad_default))\n return -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pe_numero,ad_ligne2,ad_ligne3,ad_ligne4,ad_ligne5,cp_numero,vi_numero,ad_default\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[759].NewCle+\",\"+(ad_ligne2==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_ligne2)+\"'\" )+\",\"+(ad_ligne3==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_ligne3)+\"'\" )+\",\"+(ad_ligne4==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_ligne4)+\"'\" )+\",\"+(ad_ligne5==\"\" ? \"null\" : \"'\"+ValiderChaine(ad_ligne5)+\"'\" )+\",\"+cp_numero+\",\"+vi_numero+\",\"+(ad_default==\"true\" ? \"true\" : \"false\")+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n alert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}",
"function SetMedioContacto(id, medio)\n{\n var medioContacto = new MedioContacto();\n medioContacto.MedioContactoId = id;\n medioContacto.Nombre = medio;\n \n return medioContacto;\n}",
"function setContactDetails() {\n var supplierContactFromInvoice = {\n id: 0,\n contactId: vm.invoice.billFromContactId,\n name: vm.invoice.billFromContactName,\n telephoneNumber: vm.invoice.billFromContactTelephone,\n fax: vm.invoice.billFromContactFax,\n email: vm.invoice.billFromContactEmail,\n reference: vm.invoice.billFromContactReference\n };\n\n vm.supplierContactFromInvoice = supplierContactFromInvoice;\n\n var customerContactFromInvoice = {\n id: 0,\n contactId: vm.invoice.billToContactId,\n name: vm.invoice.billToContactName,\n telephoneNumber: vm.invoice.billToContactTelephone,\n fax: vm.invoice.billToContactFax,\n email: vm.invoice.billToContactEmail,\n reference: vm.invoice.billToContactReference\n };\n\n vm.customerContactFromInvoice = customerContactFromInvoice;\n }",
"function User_Insert_Classes_Propriétés_8(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 7\n\nId dans le tab: 19;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 20;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 21;\nsimple\nNbr Jointure: 1;\n Joint n° 0 = typepropriete,pr_type,tr_numero\n\nId dans le tab: 22;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 23;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 24;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 25;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"propriete\";\n var CleMaitre = TAB_COMPO_PPTES[14].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n /* COMPOSANT LISTE AVEC JOINTURE SIMPLE */\n var pr_libelle=GetValAt(19);\n if (!ValiderChampsObligatoire(Table,\"pr_libelle\",TAB_GLOBAL_COMPO[19],pr_libelle,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pr_libelle\",TAB_GLOBAL_COMPO[19],pr_libelle))\n \treturn -1;\n var pr_nom=GetValAt(20);\n if (!ValiderChampsObligatoire(Table,\"pr_nom\",TAB_GLOBAL_COMPO[20],pr_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pr_nom\",TAB_GLOBAL_COMPO[20],pr_nom))\n \treturn -1;\n var pr_type=GetValAt(21);\n if (pr_type==\"-1\")\n pr_type=\"null\";\n if (!ValiderChampsObligatoire(Table,\"pr_type\",TAB_GLOBAL_COMPO[21],pr_type,true))\n \treturn -1;\n var pr_obligatoire=GetValAt(22);\n if (!ValiderChampsObligatoire(Table,\"pr_obligatoire\",TAB_GLOBAL_COMPO[22],pr_obligatoire,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pr_obligatoire\",TAB_GLOBAL_COMPO[22],pr_obligatoire))\n \treturn -1;\n var pr_colonne=GetValAt(23);\n if (!ValiderChampsObligatoire(Table,\"pr_colonne\",TAB_GLOBAL_COMPO[23],pr_colonne,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pr_colonne\",TAB_GLOBAL_COMPO[23],pr_colonne))\n \treturn -1;\n var pr_colesclave=GetValAt(24);\n if (!ValiderChampsObligatoire(Table,\"pr_colesclave\",TAB_GLOBAL_COMPO[24],pr_colesclave,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pr_colesclave\",TAB_GLOBAL_COMPO[24],pr_colesclave))\n \treturn -1;\n var pr_ordre=GetValAt(25);\n if (!ValiderChampsObligatoire(Table,\"pr_ordre\",TAB_GLOBAL_COMPO[25],pr_ordre,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"pr_ordre\",TAB_GLOBAL_COMPO[25],pr_ordre))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",pr_classe,pr_libelle,pr_nom,pr_type,pr_obligatoire,pr_colonne,pr_colesclave,pr_ordre\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+TAB_COMPO_PPTES[3].NewCle+\",\"+(pr_libelle==\"\" ? \"null\" : \"'\"+ValiderChaine(pr_libelle)+\"'\" )+\",\"+(pr_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(pr_nom)+\"'\" )+\",\"+pr_type+\",\"+(pr_obligatoire==\"true\" ? \"true\" : \"false\")+\",\"+(pr_colonne==\"true\" ? \"true\" : \"false\")+\",\"+(pr_colesclave==\"true\" ? \"true\" : \"false\")+\",\"+(pr_ordre==\"\" ? \"null\" : \"'\"+ValiderChaine(pr_ordre)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}",
"function contacto(req,res){\n\tlet contacto = new Contactoempresa(\n\t\treq.body.id_origen,\n\t\treq.body.nombre_contacto,\n\t\treq.body.area,\n\t\treq.body.extencion,\n\t\treq.body.email,\n\t\treq.body.celular,\n\t\treq.body.director_general,\n\t\treq.body.gerente_administrativo,\n\t\treq.body.gerente_personal,\n\t\treq.body.gerente_ventas,\n\t\treq.body.cel2,\n\t\treq.body.cel3,\n\t\treq.body.correo2,\n\t\treq.body.correo3\n\t\t);\n\tconsole.log(contacto);\n\tCONN('contacto_empresa').insert(contacto).then(idcontacto =>{\n\n\t\tif (!idcontacto){\n\n\t\t\tres.status(500).send({ resp: 'error', error: `${error}` });\n\t\t}else{\n\t\t\tres.status(200).send({ resp: 'Datos almacenados de contacto', idcontacto:idcontacto });\n\t\t}\t\t\n\t}).catch(error =>{\n\t\tres.status(500).send({resp: 'error', error: `${error}` });\n\t});\n}",
"function _setup_row_for_client_contact_section(db){\n try{\n var rows = db.execute('SELECT * from my_'+_type+' WHERE id=?',_selected_job_id);\n if((rows.getRowCount() > 0) && (rows.isValidRow())){\n if((rows.fieldByName('client_id') != undefined)&&(rows.fieldByName('client_id') != null)){\n _client_id = rows.fieldByName('client_id');\n }\n }\n rows = db.execute('SELECT a.*,my_client_contact.position,my_client_contact.first_name,my_client_contact.last_name FROM my_'+_type+'_client_contact as a'+ \n ' left join my_client_contact on (my_client_contact.id = a.client_contact_id)'+\n ' WHERE a.'+_type+'_id=? and a.status_code=1 and my_client_contact.status_code=1',_selected_job_id);\n var client_contact_count = rows.getRowCount(); \n var i=0;\n if(client_contact_count <= 1){\n if(rows.getRowCount() > 0){\n while(rows.isValidRow()){\n var row = Ti.UI.createTableViewRow({\n filter_class:'client_contact',\n className:'client_contact_'+i,\n height:'auto',\n hasChild:false,\n object_id:rows.fieldByName('client_contact_id'),\n job_client_contact_id:rows.fieldByName('id')\n });\n var edit_btn = Ti.UI.createButton({\n name:'view_btn',\n backgroundImage:self.get_file_path('image', 'BUTT_grn_off.png'),\n color:'#fff',\n font:{\n fontSize:_header_view_font_size-2,\n fontWeight:'bold'\n },\n title:'View',\n textAlign:'center',\n style:Titanium.UI.iPhone.SystemButtonStyle.BORDERED,\n left:10,\n width:_header_view_button_width-5,\n height:_header_view_button_height\n });\n if((rows.fieldByName('position') != null) && (self.trim(rows.fieldByName('position')) != '')){\n edit_btn.top = 5;\n } \n row.add(edit_btn); \n\n if((rows.fieldByName('position') != null) && (self.trim(rows.fieldByName('position')) != '')){\n var title_label = Ti.UI.createLabel({\n top:5,\n left:10+_header_view_button_width,\n width:self.screen_width-100,\n text:rows.fieldByName('first_name')+' '+rows.fieldByName('last_name'),\n height:20,\n font:{\n fontSize:self.normal_font_size,\n fontWeight:self.font_weight\n }\n });\n row.add(title_label);\n var position_label = Ti.UI.createLabel({\n top:25+5,\n left:10,\n width:self.screen_width-100,\n text:'['+rows.fieldByName('position')+']',\n height:20,\n font:{\n fontSize:self.small_font_size\n }\n });\n row.add(position_label);\n }else{\n title_label = Ti.UI.createLabel({\n left:10+_header_view_button_width,\n width:self.screen_width-100,\n text:rows.fieldByName('first_name')+' '+rows.fieldByName('last_name'),\n height:20,\n font:{\n fontSize:self.normal_font_size,\n fontWeight:self.font_weight\n }\n });\n row.add(title_label);\n }\n self.data[_section_no].add(row);\n i++;\n rows.next();\n } \n }\n }else{\n row = Ti.UI.createTableViewRow({ \n filter_class:'client_contact',\n className:'client_contact_'+100,\n height:'auto',\n hasChild:true,\n width:180,\n left:10,\n title:'Client Contacts'\n });\n var client_contact_label = Ti.UI.createLabel({\n right:5,\n backgroundColor:self.table_view_row_number_label_background_color,\n color:'#fff',\n width:30,\n height:20,\n textAlign:'center',\n text:client_contact_count,\n borderRadius:8\n });\n row.add(client_contact_label);\n self.data[_section_no].add(row); \n }\n rows.close();\n _section_no++;\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _setup_row_for_client_contact_section');\n return;\n }\n }",
"activerContact() {\n this.activeAccueil = false;\n this.activeSpotify = false;\n this.activeLyrics = false;\n this.activeInfos = false;\n this.activeConcert = false;\n this.activeContact = true;\n this.activeAPropos = false;\n this.changementAccueil.emit(\"contact\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transferFunds function allows user to see transfer menu and to transfer funds to another user | function transferFunds() {
console.log("\nTRANSFER FUNDS");
console.log("-----------------------------");
console.log(user.name + ", (ID: " + user.id + ")");
console.log("Current balance: " + Math.floor(user.balance* 100) / 100);
console.log("-----------------------------");
const transferAmount = readline.question("How much money do you want to transfer (min. 1)?\n>> ");
if (transferAmount === "quit") {
currentLoc = "funds";
} else if (transferAmount > user.balance) {
console.log("You don't have enough balance for that. Please try again with lower amount.");
transferFunds();
} else if (transferAmount >= 1) {
const transferTarget = readline.question("Which ID will receive transfer? (or 'quit' to go back)\n>> ");
const userArray = JSON.parse(fs.readFileSync("./accountDetails.json", "utf8"));
if (transferTarget === "quit") {
currentLoc = "funds";
} else if (transferTarget === user.id) {
console.log("Receiving ID must be different than your own ID");
currentLoc = "funds";
} else {
// Compare userArray:s id:s with transferTarget's ID and take true/false in checkBoolean
const checkBoolean = userArray.some((x)=> x.id === transferTarget);
if (checkBoolean) {
const toCheckPassword = readline.question("To transfer funds, please enter your password " +
"(or type 'quit' to go back):\n>> ");
if (toCheckPassword === "quit") {
currentLoc = "funds";
} else {
if (toCheckPassword === user.password) {
user.balance = Number(user.balance) - Number(transferAmount);
// Map wanted id from userArray, update balance and return data to newAllUsers.
const newAllUsers = userArray.map(balanceFunction);
function balanceFunction(x) {
if (x.id === transferTarget) {
x.balance = Number(x.balance) + Number(transferAmount);
return x;
} else if (x.id === user.id) {
x.balance = user.balance;
return x;
} else {
return x;
}
}
// Saving newAllUsers back to accountDetails.json file
fs.writeFileSync("./accountDetails.json", JSON.stringify(newAllUsers), "utf8", (err) => {
if (err) {
console.log("Could not save userData to file!");
}
});
console.log("\nTransfer successful, your balance in your account is now: " +
Math.floor(user.balance * 100) / 100);
} else {
console.log("\nThe password is incorrect, please try again. (or 'quit' to go back to start)");
transferFunds();
}
}
} else {
console.log("No user found by that ID. Try again.");
transferFunds();
}
}
} else {
console.log("\nSorry but min. transfer amount is 1e and you can only use numbers (or 'quit' to go back).");
transferFunds();
}
} | [
"function transferFunds(amount, user, escrow, loanId, orderBookId) {\n\n var amt = web3.toWei(amount);\n // console.log(orderBookId, amt);\n loanCreatorInstance.transferFunds(loanId, orderBookId, {\n from: user,\n value: amt\n }, function(err, res) {\n console.log(res);\n if (!err) {\n // var xhr = new XMLHttpRequest();\n // xhr.open(\"POST\", absolute_url + '/lender/fundTransferEvent', true);\n // xhr.setRequestHeader('Content-Type', 'application/json');\n // xhr.send(JSON.stringify({\n // from: user,\n // to: escrow,\n // txnId: res,\n // orderBookId: orderBookId,\n // loanId: loanId\n // }));\n } else {\n Snackbar.show({\n pos: 'top-center',\n text: \"Transaction Was Cancelled\"\n });\n }\n });\n}",
"function transferAccountFunds(btcAmount, sourceAddress, targetAddress, sourceButton) {\n\tif ((targetAddress==null) || (targetAddress==undefined) || (targetAddress==\"\")) {\n\t\ttargetAddress = $(\"#transferTargetAddress\").val();\n\t}\n\tif ((targetAddress==null) || (targetAddress==undefined) || (targetAddress==\"\")) {\n\t\talert (\"No target address specified. Cannot transfer funds.\");\n\t\tthrow (new Error(\"No target address specified. Cannot transfer funds.\"));\n\t}\n\tvar params = new Object();\n\tparams.account = sourceAddress;\n\tparams.receiver = targetAddress;\n\tparams.btc = btcAmount;\n\tcurrentBatchTransferAccount = sourceAddress;\n\t$(sourceButton).replaceWith(\"<button class=\\\"transferButton\\\" data =\\\"\"+sourceAddress+\"\\\" disabled>Transfer pending...</button>\");\n\tcallServerMethod(\"admin_transferAccountFunds\", params, onTransferAccountFunds);\n}",
"function transfer(username,to,amount,callback){\n hub.GetDepositAddress({userId: username, includeChecksum: true},(err,res)=>{\n\tif (err){\n\t console.log(\"FAILED TO GET BALANCE FOR THIS USER\")\n\t console.log(username)\n\t console.log(err)\n\t}else{\n\t hub.UserWithdraw({userId: username, payoutAddress: address, amount: amount, validateChecksum: true},(err,response)=>{\n\t\tif(err){\n\t\t console.log(\"FAILED TO WITHDRAW\")\n\t\t console.log(username,address.length,amount)\n\t\t console.log(err)\n\t\t}\n\t\telse{\n\n\t\t callback(response.uuid)\n\t\t}\n\t })\n\n\t}\n })\n}",
"function withdrawFunds() {\n \n var nullWithdrawalField = document.getElementById(\"withdraw-field\");\n if (nullWithdrawalField.value == \"\") {\n document.getElementById(\"popup-1\").classList.toggle(\"active\");\n return;\n }\n \n if(currentSelectedToken == \"ETH\") {\n var dep = contractInstance.methods.withdraw(web3.utils.toWei(String(nullWithdrawalField.value), \"ether\")).send({from: account}).on(\"transactionHash\", function(hash) { \n loadLoader();\n \n }).on(\"receipt\", function(receipt) {\n \n hideLoader();\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"Withdrawal successful! Balance has been updated\";\n displayAddOwnerPopup(popupMessage);\n \n }).on(\"error\", function(error) {\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"User denied the transaction\";\n displayAddOwnerPopup(popupMessage);\n hideLoader();\n \n }).then(function(result) {\n displayBalance()\n })\n }\n else {\n var dep = contractInstance.methods.withdrawERC20Token(web3.utils.toWei(String(nullWithdrawalField.value), \"ether\"), currentSelectedToken).send({from: account}).on(\"transactionHash\", function(hash) { \n loadLoader();\n \n }).on(\"receipt\", function(receipt) {\n \n hideLoader();\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"Withdrawal successful! Balance has been updated\";\n displayAddOwnerPopup(popupMessage);\n \n }).on(\"error\", function(error) {\n hideLoader();\n \n }).then(function(result) {\n var popupMessage = document.getElementById(\"msg\").innerHTML = \"User denied the transaction\";\n displayAddOwnerPopup(popupMessage);\n displayBalance()\n })\n }\n \n updateAdminTables(\"fundsWithdrawed\")\n }",
"function transfer(fromAcc, toAcc, transferAmnt)\n{\n var fromAccIndex = getIndexOf(fromAcc);\n var toAccIndex = getIndexOf(toAcc);\n //Check if From Account exists\n if ( (fromAccIndex === -1) || (toAccIndex === -1) )\n {\n console.log(\"From Account with the account number:\",fromAcc+\" is not found\");\n console.log(\"Or To Account with the account number:\",toAcc+\" is not found\");\n return -1;\n }\n if (Bank[fromAccIndex].balance < transferAmnt)\n {\n console.log(\"Insufficient funds in From account:\",fromAcc);\n console.log(\"Your currentBalance:\",Bank[fromAccIndex].balance+\"$.\");\n return -1;\n }\n Bank[fromAccIndex].balance -= transferAmnt;\n Bank[toAccIndex].balance += transferAmnt;\n console.log(\"Amount:\",transferAmnt+\"$ is tranferred from:\",fromAcc+\" to:\",toAcc);\n console.log(\"Acc:\",fromAcc+\" current balance:\",Bank[fromAccIndex].balance);\n console.log(\"Acc:\",toAcc+\" current balance:\",Bank[toAccIndex].balance);\n return true;\n}",
"function transferOwnAccount() {\n transferProvider.transferToOwnAccount($scope.transfer.account._account_id, $scope.transfer.destiny._account_id,\n $scope.transfer.amount, $scope.transfer.concept).then(\n function(data) {\n $scope.transferId = data._transaction_id;\n $scope.selection = 3;\n $scope.updateProgress(3);\n },\n function(data) {\n var status = data.status;\n var msg = codeStatusErrors.errorMessage(status);\n if (status === 500){\n $scope.setServiceError(msg + data.response.message);\n } else {\n $scope.setServiceError(msg);\n }\n }\n );\n }",
"function showTransfer() {\n clearErrorMsg();\n showView('transferForm');\n showLinks(['logoutLink', 'tradeLink', 'portfolioLink']);\n}",
"function transferFundingFee(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount) { \r\n var options = {broadcast: true}; \r\n eos\r\n .contract(code)\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:feeAccount,quantity:arbPaidFee + \" \" + token,memo:\"arbitration release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n if (Number(doneeRelease) <= 0) {\r\n // skip donee - nothing to release\r\n transferFundingP1(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n } else {\r\n transferFundingDonee(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n })\r\n .catch(function (err) { console.log('error100'); }) \r\n }) \r\n}",
"function transferFunding(person1,expectedBalance) { \r\n var options = {broadcast: true}; \r\n eos\r\n .contract('eosio.token')\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:person1,quantity:expectedBalance + \" \" + token,memo:\"rejected release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n finalReturn(outputMessage);\r\n })\r\n .catch(function (err) { console.log('error100'); }) \r\n }) \r\n}",
"async fundAccount(fundAmount) {\n await reach.transfer(this.state.faucet, this.state.acc, reach.parseCurrency(fundAmount));\n this.setState({view: 'ValidatorOrMember'});\n }",
"transfer(amount, destination) {\n this.withdraw(amount);\n destination.deposit(amount);\n }",
"function transfer(fromAccount, toAccount, transferAmount) {\n if (fromAccount !== \"external\") {\n fromAccount.value -= transferAmount;\n }\n if (toAccount !== \"external\") {\n toAccount.value += transferAmount;\n }\n }",
"function fundRequests() {\n if (user.fundRequests.length === 0) {\n console.log(\"No-one has sent fund request to you, returning to menu.\");\n } else {\n console.log(\"\\nFUND REQUESTS\");\n console.log(\"-----------------------------\");\n console.log(user.name + \", (ID: \" + user.id + \")\");\n console.log(\"Current balance: \" + Math.floor(user.balance* 100) / 100);\n console.log(\"-----------------------------\");\n\n console.log(\"\\nYou have following fund requests (ID, amount):\");\n for (const i in user.fundRequests) {\n if (user.fundRequests) {\n console.log((Number(i)+1) + \": \" + user.fundRequests[i]);\n }\n }\n\n const acceptInput = readline.question(\"\\nPlease enter number of request to accept transfer \" +\n \"(or 'quit' to go back in menu)\\n>> \");\n\n if (acceptInput === \"quit\") {\n currentLoc = \"funds\";\n // If accept input is >= 1 and given fundRequest index is not undefined (there IS request by that number)\n } else if (user.fundRequests[Number(acceptInput) - 1][1] > user.balance) {\n console.log(\"You dont have enough balance to pay requested amount.\");\n fundRequests();\n } else if ((acceptInput >= 1) && (user.fundRequests[Number(acceptInput) - 1] !== undefined)) {\n // Check for ID of fundRequest matching acceptInput\n const transferTarget = user.fundRequests[Number(acceptInput) - 1][0];\n // Check for requested amount matching acceptInput\n const transferAmount = user.fundRequests[Number(acceptInput) - 1][1];\n\n const passwordCheck = readline.question(\"Please enter your password to accept payment \"+\n \"for following request: \\n\" + \"To ID: \" + transferTarget + \", Amount: \" + transferAmount +\n \". (or 'quit' to return back to menu)\\n>> \");\n\n if (passwordCheck === \"quit\") {\n fundRequests();\n } else if (passwordCheck === user.password) {\n user.balance = Number(user.balance) - Number(transferAmount);\n\n const userArray = JSON.parse(fs.readFileSync(\"./accountDetails.json\", \"utf8\"));\n\n // Search userArray for transferTarget and add it with modified values to newAllUsers array.\n const newAllUsers = userArray.map(balanceFunction);\n function balanceFunction(x) {\n if (x.id === transferTarget) {\n // Modify target's balance to receive transferAmount\n x.balance = Number(x.balance) + Number(transferAmount);\n return x;\n } else if (x.id === user.id) {\n // Modify balance in newAllUsers to match user.balance\n x.balance = user.balance;\n\n // Remove correct fundRequest from array\n x.fundRequests.splice((Number(acceptInput) - 1), 1);\n\n // Update user.fundRequests\n user.fundRequests = x.fundRequests;\n return x;\n } else {\n return x;\n }\n }\n\n // Saving newAllUsers back to accountDetails.json file\n fs.writeFileSync(\"./accountDetails.json\", JSON.stringify(newAllUsers), \"utf8\", (err) => {\n if (err) {\n console.log(\"Could not save userData to file!\");\n }\n });\n\n console.log(\"\\nTransfer successful, your balance in your account is now: \" +\n Math.floor(user.balance* 100) / 100);\n } else {\n console.log(\"Password was incorrect, please try again.\");\n fundRequests();\n }\n } else {\n console.log(\"You didn't have request matching that number, please try again.\");\n fundRequests();\n }\n }\n}",
"async withdrawFunds() {\n // FIXME Need systemic handling of default from address.\n await EthereumHelpers.sendSafely(this.contract.methods.withdrawFunds())\n }",
"function transferFundingP1(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount) { \r\n if (Number(person1Release > 0)) {\r\n var options = {broadcast: true}; \r\n eos\r\n .contract(code)\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:person1,quantity:person1Release + \" \" + token,memo:\"arbitration release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n if (Number(person2Release) <= 0) {\r\n // finish - nothing to release\r\n finalReturn(outputMessage);\r\n } else {\r\n transferFundingP2(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n })\r\n .catch(function (err) { console.log('error102'); }) \r\n }) \r\n } else {\r\n // skip to person2\r\n transferFundingP2(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n}",
"async handleTransferClick(){\n let balance_;\n const walletAddress = this.state.firstAccount;\n const web3 = new Web3API(new PrivateKeyProvider(this.state.firstPrivKey, this.state.rpcUrl));\n await web3.eth.getBalance(walletAddress, async(err, balance) => {\n balance_ = await web3.utils.fromWei(balance, \"ether\");\n });\n let averageBal = parseFloat(balance_) / parseInt(this.state.inputAccounts);\n console.log(this.state.allAccounts[1].address)\n this.state.allAccounts.forEach(account => {\n // web3.eth.sendTransaction({from:walletAddress, to:account.address, value:web3.utils.toWei(averageBal.toString(), \"ether\")});\n web3.eth.sendTransaction({from:walletAddress, to:account.address, value:web3.utils.toWei(\"0.00001\", \"ether\")});\n });\n console.log(\"transfer ether success!\");\n\n // balance = web3.toDecimal(balance);\n }",
"function TransfersCtrl($scope, AccountService, TransferService) {\n var vm = this;\n vm.accounts = [];\n vm.selectedAccountFrom = null;\n vm.accountTo = null;\n vm.operationType = 'Transfer';\n vm.title = null;\n vm.amount = 0;\n\n refreshAccountList();\n\n // Submitting client operation\n vm.submitOperation = () => {\n if (vm.operationType == 'Transfer') {\n TransferService.makeTransfer(vm.selectedAccountFrom.accountNumber, vm.accountTo, vm.title, vm.amount,\n (result) => {\n console.log(result);\n })\n }\n else if (vm.operationType == 'Deposit') {\n TransferService.makeDeposit(vm.accountTo, vm.amount,\n (result) => {\n console.log(result);\n })\n }\n else if (vm.operationType == 'Withdrawal') {\n TransferService.makeWithdrawal(vm.selectedAccountFrom.accountNumber, vm.amount,\n (result) => {\n console.log(result);\n })\n }\n }\n\n function refreshAccountList() {\n AccountService.getAccountList((accounts) => {\n if (accounts == null)\n accounts = { accounts: [] };\n\n if (!Array.isArray(accounts.accounts))\n accounts.accounts = [accounts.accounts];\n\n vm.accounts = accounts.accounts;\n })\n }\n}",
"function transferFundingDonee(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount) { \r\n var options = {broadcast: true}; \r\n eos\r\n .contract(code)\r\n .then((contract) => {\r\n contract.transfer( {from:accountName,to:arbAccount,quantity:doneeRelease + \" \" + token,memo:\"arbitration release\"},\r\n { scope: code, authorization: [accountName + \"@\" + keyType] })\r\n .then(trx => {\r\n this.transaction = trx; \r\n if (Number(person1Release) <= 0) {\r\n // skip person1 - nothing to release\r\n transferFundingP2(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n } else {\r\n transferFundingP1(person1Release,person2Release,doneeRelease,arbPaidFee,person1,person2,arbAccount,feeAccount);\r\n }\r\n })\r\n .catch(function (err) { console.log('error101'); }) \r\n }) \r\n}",
"function transferOwnership() {\n var transfer_address = document.getElementById(\"ethereum_trans_address\").value;\n\n swal({\n title: \"You are transfering certifaction ownership\",\n text: \"Once transfered to another entity you will not be able to regain ownership of smart contract\",\n icon: \"warning\",\n buttons: true,\n dangermode: true,\n })\n .then((willTransfer) => {\n\n if (willTransfer) {\n contract.transferOwnership.sendTransaction(transfer_address, {\n from: web3.eth.accounts[0],\n gas: 70000\n }, function(err, res) {\n if (err) {\n swal(err);\n } else {\n swal(\"Your ownership has been transfered to \" + transfer_address, {\n icon: \"success\",\n });\n }\n });\n //var _current_owner = contract.getCurrentOwner();\n } else {\n swal(\"Ownership retained\");\n }\n });\n} //end of transfer ownnership"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle bookmark moved event bnId = string. ID of the item that was moved. curParentId = string. ID of the current parent folder. targetParentId = string. ID of the new parent folder. targetIndex = integer. The new index of this item in its parent. | function bkmkMoved (bnId, curParentId, targetParentId, targetIndex) {
//console.log("Move event on: "+bnId+" from: <<"+curParentId+">> to: <<"+targetParentId+", "+targetIndex+">>");
if (!isDisplayComplete) // If we get an event while not yet ready, ignore
return;
// Retrieve the real BookmarkNode and all its children, and its new parent
let BN = curBNList[bnId];
// Remember current trash state (from curParentId BN, since BN was already modified - except in private page)
let curInBSP2Trash = curBNList[curParentId].inBSP2Trash;
let targetParentBN = curBNList[targetParentId];
let tgtInBSP2Trash = targetParentBN.inBSP2Trash;
if (backgroundPage == undefined) { // Redo change in our own copy of curBNList
// Remove item and its children from its current parent, but keep them in list
// as this is only a move.
BN_delete(BN, curParentId, false);
// Then insert it at new place, again not touching the list
if (options.trashEnabled) { // Maintain inBSP2Trash and trashDate fields
BN_markTrash(BN, tgtInBSP2Trash);
}
BN_insert(BN, targetParentBN, targetIndex, false);
}
// Get move description in current (= old) reference
if ((tgtInBSP2Trash == true) && !options.trashVisible) { // Simply remove source row, there is no visible target where to insert
if (curInBSP2Trash != true) { // If source is also in trash, nothing wisible to do ..
let movedRow = curRowList[bnId];
removeBkmks(movedRow, true); // remove from cur lists, as there is no visible targets
}
}
else if ((curInBSP2Trash == true) && !options.trashVisible) { // Simply insert tartget row, there is no wisible source to remove from
let targetParentRow = curRowList[targetParentId];
// Find insertion point, in current (= old) reference
let targetRow;
// Introduce robustness in case the BN tree is empty and index is not 0, as that seems to occur some times
let children = targetParentBN.children;
if ((targetIndex == 0) || (children == undefined)) { // Insert just after parent row
// Note that this also takes care of the case where parent had so far no child
targetRow = targetParentRow.nextElementSibling; // Can be null if we move at end
}
else { // Insert just after previous row
// ASSUMPTION (true so far): when multiple moves / creates to same parent, like in multi-select move
// or reorder or ..., items are sent to us in increasing row/index order, so previous
// rows to current item under process are always already at the right place.
// Note that in such multi operations, things have been all processed in background first or the copy,
// so the BN tree is not any more in sync with display.
let previousSibblingBN = children[targetIndex-1];
if (previousSibblingBN.inBSP2Trash && !options.trashVisible) { // Protect against inserting just after BSP2 trash when not visible
if (targetIndex < 2) {
targetRow = targetParentRow.nextElementSibling; // Can be null if we move at end
}
else {
let previousBN = BN_lastDescendant(children[targetIndex-2]);
targetRow = curRowList[previousBN.id].nextElementSibling; // Can be null if we move at end
}
}
else {
let previousBN = BN_lastDescendant(previousSibblingBN);
targetRow = curRowList[previousBN.id].nextElementSibling; // Can be null if we move at end
}
}
// We got the insert point in targetRow (null if at end), proceed to move
// Insert the item at its new place (with its children) using global variable insertRowIndex
// and get the last inserted row in return.
if (targetRow == null) // Moving at end of bookmarks table
insertRowIndex = bookmarksTable.rows.length;
else insertRowIndex = targetRow.rowIndex; // Get the updated row index of target
insertBkmks(BN, targetParentRow);
}
else { // Normal case
let movedRow = curRowList[bnId];
let curRowIndex = movedRow.rowIndex;
let targetParentRow = curRowList[targetParentId];
let targetCurIndex = targetIndex;
// Find insertion point, in current (= old) reference
let targetCurRowIndex;
let targetRow;
// Introduce robustness in case the BN tree is empty and index is not 0, as that seems to occur some times
let children = targetParentBN.children;
if ((targetCurIndex == 0) || (children == undefined)) { // Insert just after parent row
// Note that this also takes care of the case where parent had so far no child
targetCurRowIndex = targetParentRow.rowIndex + 1;
targetRow = targetParentRow.nextElementSibling; // Can be null if we move at end
}
else { // Insert just after previous row
// ASSUMPTION (true so far): when multiple moves / creates to same parent, like in multi-select move
// or reorder or ..., items are sent to us in increasing row/index order, so previous
// rows to current item under process are always already at the right place.
// Note that in such multi operations, things have been all processed in background first or the copy,
// so the BN tree is not any more in sync with display.
let previousSibblingBN = children[targetIndex-1];
if (previousSibblingBN.inBSP2Trash && !options.trashVisible) { // Protect against inserting just after BSP2 trash when not visible
if (targetIndex <= children.length) { // Remember that the child was already added in the BN tree in the background task
targetCurRowIndex = targetParentRow.rowIndex + 1;
targetRow = targetParentRow.nextElementSibling; // Can be null if we move at end
}
else {
let previousBN = BN_lastDescendant(children[targetIndex-2]);
targetRow = curRowList[previousBN.id];
targetCurRowIndex = targetRow.rowIndex + 1; // Can be at end of bookmarks table
targetRow = targetRow.nextElementSibling; // Can be null if we move at end
}
}
else {
let previousBN = BN_lastDescendant(previousSibblingBN);
targetRow = curRowList[previousBN.id];
targetCurRowIndex = targetRow.rowIndex + 1; // Can be at end of bookmarks table
targetRow = targetRow.nextElementSibling; // Can be null if we move at end
}
}
// We got the move point in targetRow (null if at end), and its position in
// targetCurRowIndex, proceed to move
//console.log("curRowIndex: "+curRowIndex+" targetCurRowIndex: "+targetCurRowIndex);
// Remove item and its children from display, but keep them in their cur lists
// as this is only a move.
// The returned value is the row which took its place in the table (or null if
// removed at end).
let deletePos = removeBkmks(movedRow, false);
// Insert the item at its new place (with its children) using global variable insertRowIndex
// and get the last inserted row in return.
if (curRowIndex == targetCurRowIndex) { // targetRow has disappeared, it was the moved row
// We are then visually inserting where it was deleted
if (deletePos == null) { // This is the end of the bookmark table
insertRowIndex = bookmarksTable.rows.length;
}
else {
insertRowIndex = deletePos.rowIndex;
}
}
else {
if (targetRow == null) // Moving at end of bookmarks table
insertRowIndex = bookmarksTable.rows.length;
else insertRowIndex = targetRow.rowIndex; // Get the updated row index of target
}
insertBkmks(BN, targetParentRow);
}
// State of parent folders may change, so save folder open state
saveFldrOpen();
if (options.showPath || options.trashEnabled) {
// Trigger an update as results can change, if there is a search active
triggerUpdate();
}
} | [
"async function moveBkmk (a_id, a_BN, newParentId, newIndex = undefined) {\n let len = a_BN.length;\n // Fecord a multiple operation if more than one item in the array\n if (len > 1) {\n\tawait recordHistoryMulti(\"move\", a_id);\n }\n\n if (newIndex == undefined) { // Cut and pasting into a folder, at end\n\tlet BN;\n\tfor (let i=0 ; i<len ; i++) {\n\t BN = a_BN[i];\n//trace(\"Move BN id: \"+BN.id+\" to Parent id: \"+newParentId+\" at index: \"+newIndex);\n\t // Move BTN at end of folder. Do that synchronously to avoid mess when processing multiple BNs\n\t if (!BN.protect) {\n\t\tawait browser.bookmarks.move(\n\t\t BN.id,\n\t\t {parentId: newParentId\n\t\t }\n\t\t);\n\t }\n\t}\n }\n else {\n\tlet BN;\n\tfor (let i=0 ; i<len ; i++) {\n\t BN = a_BN[i];\n // If designated place is under same parent and after, some special handling ..\n\t if (BN.parentId == newParentId) {\n\t\t// If moved after, need to decrease index by 1 to represent position without moved item ..\n\t\t// This is not documented properly on https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/bookmarks/move\n\t\tlet index = BN_getIndex(BN);\n\t\tif (newIndex > index) newIndex--;\n\t\tif (newIndex == index) { // No move\n\t\t continue;\n\t\t}\n\t }\n\t // Move BTN at designated place. Do that synchronously to avoid mess when processing multiple BNs\n\t if (!BN.protect) {\n\t\tawait browser.bookmarks.move(\n\t\t BN.id,\n\t\t {parentId: newParentId,\n\t\t index: newIndex++\n\t\t }\n\t\t);\n\t }\n\t}\n }\n}",
"function moveBookmark(id, parentId, index) {\n chrome.runtime.sendMessage(extension_id, \n {'operation': 'move', 'id':id, 'parentId': parentId, 'index': index});\n}",
"move(targetId, newParentId, index) {\n const targetNode = state.nodes[targetId],\n currentParentId = targetNode.data.parent,\n newParent = state.nodes[newParentId],\n newParentNodes = newParent.data.nodes;\n\n query.node(newParentId).isDroppable(targetNode, (err) => {\n throw new Error(err);\n });\n\n const currentParent = state.nodes[currentParentId],\n currentParentNodes = currentParent.data.nodes;\n\n currentParentNodes[currentParentNodes.indexOf(targetId)] = 'marked';\n\n newParentNodes.splice(index, 0, targetId);\n\n state.nodes[targetId].data.parent = newParentId;\n currentParentNodes.splice(currentParentNodes.indexOf('marked'), 1);\n }",
"function move(item, new_parent_id, next) {\n\t\tif (moveCB) return moveCB(item, new_parent_id, next);\n\n\t\titem[parent_field] = new_parent_id;\n\t\tself.update(item, [parent_field], next);\n\t}",
"folderMoveCopyCompleted(aMove, aSrcFolder, aDestFolder) {\n this.indexer._log.debug(\n \"folderMoveCopy notification (Move: \" + aMove + \")\"\n );\n if (aMove) {\n let srcURI = aSrcFolder.URI;\n let targetURI =\n aDestFolder.URI + srcURI.substring(srcURI.lastIndexOf(\"/\"));\n this._folderRenameHelper(aSrcFolder, targetURI);\n } else {\n this.indexer.indexingSweepNeeded = true;\n }\n }",
"function bkmkRemoved (bnId) {\n//console.log(\"Remove event on: \"+bnId);\n if (!isDisplayComplete) // If we get an event while not yet ready, ignore\n\treturn;\n\n // Retrieve removed subtree\n let BN = curBNList[bnId]; \n if (backgroundPage == undefined) { // Redo deletion in our own copy of curBNList\n\t// Remove item and its children from curBNList\n\tBN_delete(BN);\n }\n\n // Retrieve position of removed item in the bookmarks table\n let row = curRowList[bnId];\n\n if (row != undefined) { // If non existing, do not try to remove\n\t\t\t\t\t\t // Can happen for example on restore bookmarks, on our special \"place:xxx\"\n\t\t\t\t\t\t // BNs unders the special most recent or most visited folders\n\t// Remove item and its children from display, and from the appropriate display lists\n\t// The returned value is the row which took its place in the table (or none if at end).\n\trow = removeBkmks(row, true);\n }\n\n // Save new current info\n // A folder delete can presumably delete bookmarks, and a bookmark delete can\n // also change the open state of its parent if it was the only children in there,\n // so save at all times.\n saveFldrOpen();\n\n // Call refresh search if there is one active\n if (isOtherThanSeparatorRemoved) { // Global variable set by removeBkmks()\n\ttriggerUpdate();\n }\n}",
"function moveItem(src, dst, copy) {\n \"use strict\";\n var tab;\n copy = copy || false;\n console.log('moveItem ' + src + ' ' + dst);\n $.post('/editor/move_item', { src: src, dst: dst, copy: copy.toString() }, function (response) {\n var srcDirs = (src.match(/.*\\//)[0]).split('/'),\n dstDirs = (dst.match(/.*\\//)[0]).split('/'),\n dstDir = dstDirs.join('/'),\n jqDst = $('li.directory > a[rel=\"' + dstDir + '\"]'),\n bDstIsFile = (dst.split('/').pop() !== ''),\n srcFpath = src.split(ROOT).pop();\n // If src is a directory, reduce by one\n if (srcDirs.join('/') === src) {\n srcDirs.pop();\n }\n // Optimise redisplay of fileTree\n if (dstDir === ROOT) {\n console.log('move to top');\n displayTree(src);\n } else if (srcDirs.length === dstDirs.length) {\n console.log('optimise equal paths');\n $('li > a[rel=\"' + src + '\"]').hide('slow');\n if (bDstIsFile) {\n jqDst.click();\n }\n jqDst.click();\n } else if (srcDirs.length < dstDirs.length) {\n console.log('optimise deeper');\n if (jqDst.parent().hasClass('expanded')) {\n jqDst.click();\n }\n $('li > a[rel=\"' + src + '\"]').hide('slow');\n jqDst.click();\n } else {\n console.log('optimise shallower');\n if (jqDst.parent().hasClass('expanded')) {\n jqDst.click();\n }\n jqDst.click();\n }\n // If relevant, update tabs and fileTree\n if (!copy) {\n if (rascal.picture.showing) {\n if (bDstIsFile) {\n showPicture(dst);\n } else {\n showPicture(dst + src.split('/').pop());\n }\n } else if ((tab = getTabFromPath(srcFpath))) {\n if (bDstIsFile) {\n if (fileHasBeenChanged(srcFpath)) {\n unhighlightInTree(src);\n highlightInTree(dst);\n }\n updateLocation(tab, dst.split(ROOT).pop());\n } else {\n if (fileHasBeenChanged(srcFpath)) {\n unhighlightInTree(src);\n highlightInTree(dst + src.split('/').pop());\n }\n updateLocation(tab, (dst + src.split('/').pop()).split(ROOT).pop());\n }\n }\n }\n }).error(function (jqXHR, textStatus, errorThrown) {\n console.log('moveItem: ' + textStatus + ': ' + errorThrown);\n saveMsg('Move failed');\n });\n}",
"function responseMoveDocumentAction(d, s)\n{\n $.post(domainUrl + 'documents/childfolderList', {'node_id': InitalDragFolderId}, responseFolderChildAction, 'JSON');\n $.post(domainUrl + 'documents/folderDetails', {'order_by': 'node_instance_id', 'order': 'DESC', 'type': 'no-pagination', 'mode': 'Normal', 'class_node_id': d.destination_id}, responseCallFolderDetailsAction, 'html');\n}",
"_handleMoveItem(e) {\n this.activeItem = e.detail.item;\n this.moveItem(e.detail.item, e.detail.moveUp, e.detail.byGroup);\n }",
"function _insertAfter(todo, dest, id) {\n var parent = _.pluck(_.where(todoItems, {'parent_id': dest}));\n var index = todo.position;\n _insert(todo, parent, index + 1, id);\n}",
"function _moveItemTo(event, ui) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tevent.stopPropagation();\n\t\t\t\tvar movedItem = ui.draggable,\n\t\t\t\ttype = /file/.test(movedItem[0].className) ? 'file': 'dir',\n\t\t\t\tdestination = $(event.target).parent()[0].id,\n\t\t\t\t// the directory the item gets moved to\n\t\t\t\tsource = type === 'file' ? movedItem.parents().filter('li.dir')[0].id: movedItem.parent()[0].id,\n\t\t\t\tfile = type === 'file' ? movedItem[0].id.substr(5) : undefined;\n\t\t\t\tthis.collection.moveItem({\n\t\t\t\t\ttype: type,\n\t\t\t\t\tdestination: destination,\n\t\t\t\t\tsource: source,\n\t\t\t\t\tfile: type === 'file' ? parseInt(file, 10) : file,\n\t\t\t\t}).always(function (resp) {\n\t\t\t\t\tnew SysMessage(null, resp);\n\t\t\t\t});\n\t\t\t}",
"moveListItemDown(ev) {\n\n //li element to be moved\n const item = ev.target.parentNode.parentNode\n \n if (item === item.parentNode.lastElementChild) {\n return\n }\n\n const itemID = item.dataset.id\n \n item.parentNode.insertBefore(item.nextSibling, item)\n \n const itemObject = this.getFlickItem(itemID)\n\n const itemObjectIndex = this.flicks.indexOf(itemObject)\n \n this.swapFlickItem(itemObjectIndex, itemObjectIndex+1)\n\n }",
"noteMove(aOldHdr, aNewHdr) {\n let oldKey = aOldHdr.folder.URI + \"#\" + aOldHdr.messageKey;\n if (!(oldKey in this._indexedMessagesPendingCommitByKey)) {\n return;\n }\n\n let glodaId = this._indexedMessagesPendingCommitByKey[oldKey];\n delete this._indexedMessagesPendingCommitByKey[oldKey];\n\n let newKey = aNewHdr.folder.URI + \"#\" + aNewHdr.messageKey;\n this._indexedMessagesPendingCommitByKey[newKey] = glodaId;\n\n // only clobber the header, not the dirty state\n this._indexedMessagesPendingCommitByGlodaId[glodaId][0] = aNewHdr;\n }",
"msgsMoveCopyCompleted(aMove, aSrcMsgHdrs, aDestFolder, aDestMsgHdrs) {\n this.indexer._log.debug(\"MoveCopy notification. Move: \" + aMove);\n try {\n // ---- Move\n if (aMove) {\n // -- Effectively a deletion?\n // If the destination folder is not indexed, it's like these messages\n // are being deleted.\n if (!GlodaMsgIndexer.shouldIndexFolder(aDestFolder)) {\n this.msgsDeleted(aSrcMsgHdrs);\n return;\n }\n\n // -- Avoid propagation of filthy gloda-id's.\n // If the source folder is filthy or should not be indexed (and so\n // any gloda-id's found in there are gibberish), our only job is to\n // strip the gloda-id's off of all the destination headers because\n // none of the gloda-id's are valid (and so we certainly don't want\n // to try and use them as a basis for updating message keys.)\n let srcMsgFolder = aSrcMsgHdrs[0].folder;\n if (\n !this.indexer.shouldIndexFolder(srcMsgFolder) ||\n GlodaDatastore._mapFolder(srcMsgFolder).dirtyStatus ==\n GlodaFolder.prototype.kFolderFilthy\n ) {\n // Local case, just modify the destination headers directly.\n if (aDestMsgHdrs.length > 0) {\n for (let destMsgHdr of aDestMsgHdrs) {\n // zero it out if it exists\n // (no need to deal with pending commit issues here; a filthy\n // folder by definition has nothing indexed in it.)\n let glodaId = destMsgHdr.getUint32Property(\n GLODA_MESSAGE_ID_PROPERTY\n );\n if (glodaId) {\n destMsgHdr.setUint32Property(GLODA_MESSAGE_ID_PROPERTY, 0);\n }\n }\n\n // Since we are moving messages from a folder where they were\n // effectively not indexed, it is up to us to make sure the\n // messages now get indexed.\n this.indexer._reindexChangedMessages(aDestMsgHdrs);\n return;\n }\n\n // IMAP move case, we need to operate on the pending headers using\n // the source header to get the pending header and as the\n // indication of what has been already set on the pending header.\n let destDb;\n // so, this can fail, and there's not much we can do about it.\n try {\n destDb = aDestFolder.msgDatabase;\n } catch (ex) {\n this.indexer._log.warn(\n \"Destination database for \" +\n aDestFolder.prettyName +\n \" not ready on IMAP move.\" +\n \" Gloda corruption possible.\"\n );\n return;\n }\n for (let srcMsgHdr of aSrcMsgHdrs) {\n // zero it out if it exists\n // (no need to deal with pending commit issues here; a filthy\n // folder by definition has nothing indexed in it.)\n let glodaId = srcMsgHdr.getUint32Property(\n GLODA_MESSAGE_ID_PROPERTY\n );\n if (glodaId) {\n destDb.setUint32AttributeOnPendingHdr(\n srcMsgHdr,\n GLODA_MESSAGE_ID_PROPERTY,\n 0\n );\n }\n }\n\n // Nothing remains to be done. The msgClassified event will take\n // care of making sure the message gets indexed.\n return;\n }\n\n // --- Have destination headers (local case):\n if (aDestMsgHdrs.length > 0) {\n // -- Update message keys for valid gloda-id's.\n // (Which means ignore filthy gloda-id's.)\n let glodaIds = [];\n let newMessageKeys = [];\n // Track whether we see any messages that are not gloda indexed so\n // we know if we have to mark the destination folder dirty.\n let sawNonGlodaMessage = false;\n for (let iMsg = 0; iMsg < aSrcMsgHdrs.length; iMsg++) {\n let srcMsgHdr = aSrcMsgHdrs[iMsg];\n let destMsgHdr = aDestMsgHdrs[iMsg];\n\n let [glodaId, dirtyStatus] = PendingCommitTracker.getGlodaState(\n srcMsgHdr\n );\n if (\n glodaId >= GLODA_FIRST_VALID_MESSAGE_ID &&\n dirtyStatus != GlodaMsgIndexer.kMessageFilthy\n ) {\n // we may need to update the pending commit map (it checks)\n PendingCommitTracker.noteMove(srcMsgHdr, destMsgHdr);\n // but we always need to update our database\n glodaIds.push(glodaId);\n newMessageKeys.push(destMsgHdr.messageKey);\n } else {\n sawNonGlodaMessage = true;\n }\n }\n\n // this method takes care to update the in-memory representations\n // too; we don't need to do anything\n if (glodaIds.length) {\n GlodaDatastore.updateMessageLocations(\n glodaIds,\n newMessageKeys,\n aDestFolder\n );\n }\n\n // Mark the destination folder dirty if we saw any messages that\n // were not already gloda indexed.\n if (sawNonGlodaMessage) {\n let destGlodaFolder = GlodaDatastore._mapFolder(aDestFolder);\n destGlodaFolder._ensureFolderDirty();\n this.indexer.indexingSweepNeeded = true;\n }\n } else {\n // --- No dest headers (IMAP case):\n // Update any valid gloda indexed messages into their new folder to\n // make the indexer's life easier when it sees the messages in their\n // new folder.\n let glodaIds = [];\n\n let srcFolderIsLocal =\n srcMsgFolder instanceof Ci.nsIMsgLocalMailFolder;\n for (let msgHdr of aSrcMsgHdrs) {\n let [glodaId, dirtyStatus] = PendingCommitTracker.getGlodaState(\n msgHdr\n );\n if (\n glodaId >= GLODA_FIRST_VALID_MESSAGE_ID &&\n dirtyStatus != GlodaMsgIndexer.kMessageFilthy\n ) {\n // we may need to update the pending commit map (it checks)\n PendingCommitTracker.noteBlindMove(msgHdr);\n // but we always need to update our database\n glodaIds.push(glodaId);\n\n // XXX UNDO WORKAROUND\n // This constitutes a move from a local folder to an IMAP\n // folder. Undo does not currently do the right thing for us,\n // but we have a chance of not orphaning the message if we\n // mark the source header as dirty so that when the message\n // gets re-added we see it. (This does require that we enter\n // the folder; we set the folder dirty after the loop to\n // increase the probability of this but it's not foolproof\n // depending on when the next indexing sweep happens and when\n // the user performs an undo.)\n msgHdr.setUint32Property(\n GLODA_DIRTY_PROPERTY,\n GlodaMsgIndexer.kMessageDirty\n );\n }\n }\n // XXX ALSO UNDO WORKAROUND\n if (srcFolderIsLocal) {\n let srcGlodaFolder = GlodaDatastore._mapFolder(srcMsgFolder);\n srcGlodaFolder._ensureFolderDirty();\n }\n\n // quickly move them to the right folder, zeroing their message keys\n GlodaDatastore.updateMessageFoldersByKeyPurging(\n glodaIds,\n aDestFolder\n );\n // we _do not_ need to mark the folder as dirty, because the\n // message added events will cause that to happen.\n }\n } else {\n // ---- Copy case\n // -- Do not propagate gloda-id's for copies\n // (Only applies if we have the destination header, which means local)\n for (let destMsgHdr of aDestMsgHdrs) {\n let glodaId = destMsgHdr.getUint32Property(\n GLODA_MESSAGE_ID_PROPERTY\n );\n if (glodaId) {\n destMsgHdr.setUint32Property(GLODA_MESSAGE_ID_PROPERTY, 0);\n }\n }\n\n // mark the folder as dirty; we'll get to it later.\n let destGlodaFolder = GlodaDatastore._mapFolder(aDestFolder);\n destGlodaFolder._ensureFolderDirty();\n this.indexer.indexingSweepNeeded = true;\n }\n } catch (ex) {\n this.indexer._log.error(\n \"Problem encountered during message move/copy:\",\n ex.stack\n );\n }\n }",
"function bkmkCreated (BN, index) {\n//trace(t1.getTime()+\" Create event on: \"+BN.id+\" type: \"+BN.type+\" parentId: \"+BN.parentId+\" index: \"+index);\n if (!isDisplayComplete) // If we get an event while not yet ready, ignore\n\treturn;\n\n let parentId = BN.parentId;\n let parentBN = curBNList[parentId];\n if (backgroundPage == undefined) { // Redo insertion in our own copy of curBNList\n\n\t// Insert the new BN tree under its parent\n\tBN_insert(BN, parentBN, index);\n }\n\n // Find insertion point, setting it in global variable insertRowIndex\n // We need to retrieve the insertion point the hard way if we do not want to call\n // getSubtree() which is very very long ...\n let parentRow = curRowList[parentId];\n // Introduce robustness in case the BN tree is empty and index is not 0, as that seems to occur some times\n let children = parentBN.children;\n if ((index == 0) || (children == undefined)) { // Insert just after parent row\n\t// Note that this also takes care of the case where parent had so far no child\n\tinsertRowIndex = parentRow.rowIndex + 1; // Can be at end of bookmarks table\n }\n else { // Insert just after previous row\n\t\t // ASSUMPTION (true so far): when multiple moves / creates to same parent, like in multi-select move\n\t \t // or reorder or ..., items are sent to us in increasing row/index order, so previous\n \t // rows to current item under process are always already at the right place.\n\t\t // Note that in such multi operations, things have been all processed in background first for the copy,\n\t\t // so the BN tree is not anymore in sync with display.\n\tlet previousSibblingBN = children[index-1];\n\tif (previousSibblingBN.inBSP2Trash && !options.trashVisible) { // Protect against inserting just after BSP2 trash when not visible\n\t if (index < 2) {\n\t\tinsertRowIndex = parentRow.rowIndex + 1;\n\t }\n\t else {\n\t\tlet previousBN = BN_lastDescendant(children[index-2]);\n\t\tlet row = curRowList[previousBN.id];\n\t\tinsertRowIndex = row.rowIndex + 1; // Can be at end of bookmarks table\n\t }\n\t}\n\telse {\n\t let previousBN = BN_lastDescendant(previousSibblingBN);\n\t let row = curRowList[previousBN.id];\n\t insertRowIndex = row.rowIndex + 1; // Can be at end of bookmarks table\n\t}\n }\n\n // We got the insertion point, proceed to insertion\n insertBkmks(BN, parentRow);\n\n // Save new current info and refresh search\n let type = BN.type;\n if (type != \"separator\") {\n\tif (type == \"folder\") {\n\t saveFldrOpen(); // If real folder creation, there is no children (yet)\n\t}\n\n\t// Call refresh search if there is one active\n\ttriggerUpdate();\n }\n}",
"moveListItemUp(ev) {\n\n //li element to be moved\n const item = ev.target.parentNode.parentNode\n\n if (item === item.parentNode.firstElementChild) {\n return\n }\n\n const itemID = item.dataset.id\n\n item.parentNode.insertBefore(item, item.previousSibling)\n\n const itemObject = this.getFlickItem(itemID)\n\n const itemObjectIndex = this.flicks.indexOf(itemObject)\n\n this.swapFlickItem(itemObjectIndex, itemObjectIndex-1)\n\n\n }",
"function removeBookmark(e) {\n\t\t\tconsole.log('test', e, e.target);\n\t\t\tif (e.target.id == '') {console.log('its a link');return;}\n\n\t\t if (e.target !== e.currentTarget) {\n\n\t\t elementId = 'fol-'+e.target.id.substr(4);\n\t\t\t\tbookmarkId = elementId.substr(4);\n\t\t\t\tconsole.log(elementId, bookmarkId);\n\t\t\t\tconsole.log('CHECK - ');\n\n\t\t\t\tremContent = $('#'+elementId).children().detach();\n\n\t\t\t\tsetTimeout(function(){\n\t\t\t\tconsole.log(elementId); \n\t\t\t\t\t$('#'+elementId).append('<div id=\"confirmBox\"></div>')\n\t\t\t\n\t\t \t\t}, 100);\n\t\t \t\tsetTimeout(function(){ \n\t\t \t\t\tconsole.log(elementId, bookmarkId, e.target.id.substr(4));\n\t\t \t\t \t$('#confirmBox').append('<input id=\"confirmRemove\" class=\"btn btn-default greenHov\" type=\"button\" value=\"confirm\" data=\"'+elementId+'\">')\n\t\t\t\t\t$('#confirmBox').append('<input id=\"cancelRemove\" class=\"btn btn-default\" type=\"button\" value=\"cancel\" data=\"'+elementId+'\">');\n\t\t \t\t }, 200);\n\t\t \t\t// $('#'+elementId).stop().animate({height:'-=70px'},1000,'easeOutQuint', function(){\n\t\t \t \t$('#'+elementId).stop().animate({height:'+=48px'},1000,'easeOutQuint');\n\t\t \t\t// });\n\n\t\t\t\t\n\t\t\t\t\t// $('#confirmRemove').on('click', processRemoval(elementId, bookmarkId));\n\t\t }\n\t\t e.stopPropagation();\n\t\t}",
"function bkmkMouseHandler (e) {\r\n let target = e.target; // Type depends ..\r\n let className = target.className;\r\n//console.log(\"Bookmark click event: \"+e.type+\" button: \"+e.button+\" shift: \"+e.shiftKey+\" target: \"+target+\" class: \"+className);\r\n\r\n // The click target is one of .bscrollok (empty space click in div, nothing should happen),\r\n // .brow/.selbrow cell,\r\n // .seqnum, .histicon, .bkmkitem_x div, .favseparator/.favseparatorend div, .favicon or .favttext\r\n // Go up to the level of the cell (.brow/.selbrow) to handle click\r\n if (!className.includes(\"bscrollok\")) {\r\n\tlet cell;\r\n\tif (className.includes(\"brow\")) {\r\n\t cell = target;\r\n\t}\r\n\telse if (className.includes(\"bkmkitem_\")) {\r\n\t cell = target.parentElement;\r\n\t}\r\n\telse {\r\n\t cell = target.parentElement.parentElement;\r\n\t}\r\n\r\n\t// Highlight history node, and display it in the node panel\r\n\tsetCellHighlight(cell);\r\n\tlet row = cell.parentElement;\r\n\tlet hnId = row.dataset.id;\r\n\tdisplayHN(hnId);\r\n }\r\n e.stopPropagation(); // Prevent handlers up the DOM chain on same event\r\n}",
"function ddhandler(target, dd, e, data, drop, v) {\r\n if (folderlink) return false;\r\n\r\n var node = false;\r\n\r\n if (!drop) var v = this.v;\r\n\r\n // the target node is the white area in the filegrid\r\n if ((v.id == 'filegrid') && (target.className.indexOf('x-grid-view') > -1)) node = dirroot.getById(currentdirid);\r\n // the target node is the whit area in the imagegrid\r\n else if ((v.id == 'imagegrid') && (target.id == 'imagegrid')) node = dirroot.getById(currentdirid);\r\n // the target node is an icon in the imagegrid\r\n else if (v.id == 'imagegrid') node = v.getRecord(target);\r\n // the target node is an icon in the filegrid or treepanel\r\n else node = v.getView().getRecord(target);\r\n\r\n // no operations with directly to the inbox or contacts node\r\n if (node && ((node.get('id') == InboxID) || (node.get('id') == NetworkID))) {\r\n $('.x-dd-drag-proxy').removeClass('copy move');\r\n if (drop) return false;\r\n else return 'nodrop';\r\n }\r\n\r\n // if the target node is not the root or trashbin, look it up in the filestore (root and trashbin are not present with nodes in the filestore)\r\n if ((node) && (node.get('id') != RootID) && (node.get('id') != TrashbinID)) {\r\n node = FileStore.getById(node.get('id'));\r\n if (!node.get('folder')) node = dirroot.getById(node.get('parentid'));\r\n }\r\n\r\n // if no node was found in the filestore -> invalid dd operation\r\n if (!node) {\r\n $('.x-dd-drag-proxy').removeClass('copy move');\r\n if (drop) return false;\r\n else return 'nodrop';\r\n }\r\n\r\n // obtain the dragtype for this operation\r\n var dragtype = ddtype(data.records[0].data.id, node.get('id'));\r\n\r\n\r\n var copydel = false;\r\n if (dragtype == 'copydel') {\r\n // onmouseover show that the operation is a move, but when dropped handle it as a copy + delete (copydel)\r\n if (drop) dragtype = 'copy';\r\n else dragtype = 'move';\r\n copydel = true;\r\n }\r\n\r\n if (dragtype) {\r\n var d = document.getElementById('ddtext');\r\n\r\n if (dragtype == 'copy') {\r\n if (drop) {\r\n var copyids = [];\r\n for (var i in data.records) copyids[i] = data.records[i].data.id;\r\n\r\n // if the toid is 11 chars then it's a copy to a user's inbox\t\t\t\t\r\n if (node.get('id').length == 11) copytouser(copyids, node.get('id'), false, function () {});\r\n // process copy\r\n else copyitems(copyids, node.get('id'), copydel);\r\n } else {\r\n $('.x-dd-drag-proxy').removeClass('move nodrop');\r\n if (data.records.length == 1) d.innerHTML = 'Copy 1 selected item';\r\n else d.innerHTML = 'Copy ' + data.records.length + ' selected items';\r\n }\r\n } else {\r\n if (drop) {\r\n // process move\t\t\t\t\r\n var jsonmove = [];\r\n var i = 0;\r\n for (key in data.records) {\r\n moveitem(FileStore.getById(data.records[key].get('id')), node.get('id'), false);\r\n jsonmove[i] = {\r\n a: 'm',\r\n n: data.records[key].get('id'),\r\n t: node.get('id'),\r\n i: requesti\r\n }\r\n i++;\r\n }\r\n processmove(jsonmove);\r\n aftermove(true);\r\n } else {\r\n $('.x-dd-drag-proxy').removeClass('copy nodrop');\r\n if (data.records.length == 1) d.innerHTML = 'Move 1 selected item';\r\n else d.innerHTML = 'Move ' + data.records.length + ' selected items';\r\n }\r\n }\r\n return dragtype;\r\n } else {\r\n $('.x-dd-drag-proxy').removeClass('copy move');\r\n //console.log('dragtype','nodrop');\r\n if (drop) return false;\r\n else return 'nodrop';\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End Segment2d\\ Start Segment3d\\ Segment3d Class | function Segment3d () {
/**
* Ray of segment
* @type Ray3d
*/
this.pRay = new Ray3d();
/**
* Distance
* @type Float
*/
this.fDistance = 0.0;
} | [
"function SegmentBase() {\n}",
"function doSegmentDemo() {\n appendHeading(\"Segment\");\n let qr;\n let segs;\n const QrCode = qrcodegen.QrCode; // Abbreviation\n const QrSegment = qrcodegen.QrSegment; // Abbreviation\n // Illustration \"silver\"\n const silver0 = \"THE SQUARE ROOT OF 2 IS 1.\";\n const silver1 = \"41421356237309504880168872420969807856967187537694807317667973799\";\n qr = QrCode.encodeText(silver0 + silver1, QrCode.Ecc.LOW);\n qr.drawCanvas(10, 3, appendCanvas(\"sqrt2-monolithic-QR\"));\n segs = [\n QrSegment.makeAlphanumeric(silver0),\n QrSegment.makeNumeric(silver1)\n ];\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);\n qr.drawCanvas(10, 3, appendCanvas(\"sqrt2-segmented-QR\"));\n // Illustration \"golden\"\n const golden0 = \"Golden ratio \\u03C6 = 1.\";\n const golden1 = \"6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374\";\n const golden2 = \"......\";\n qr = QrCode.encodeText(golden0 + golden1 + golden2, QrCode.Ecc.LOW);\n qr.drawCanvas(8, 5, appendCanvas(\"phi-monolithic-QR\"));\n segs = [\n QrSegment.makeBytes(toUtf8ByteArray(golden0)),\n QrSegment.makeNumeric(golden1),\n QrSegment.makeAlphanumeric(golden2)\n ];\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);\n qr.drawCanvas(8, 5, appendCanvas(\"phi-segmented-QR\"));\n // Illustration \"Madoka\": kanji, kana, Cyrillic, full-width Latin, Greek characters\n const madoka = \"\\u300C\\u9B54\\u6CD5\\u5C11\\u5973\\u307E\\u3069\\u304B\\u2606\\u30DE\\u30AE\\u30AB\\u300D\\u3063\\u3066\\u3001\\u3000\\u0418\\u0410\\u0418\\u3000\\uFF44\\uFF45\\uFF53\\uFF55\\u3000\\u03BA\\u03B1\\uFF1F\";\n qr = QrCode.encodeText(madoka, QrCode.Ecc.LOW);\n qr.drawCanvas(9, 4, appendCanvas(\"madoka-utf8-QR\"));\n const kanjiCharBits = [\n 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1,\n 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,\n 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1,\n 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1,\n 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,\n 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1,\n 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1,\n 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1,\n 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,\n 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1,\n 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,\n ];\n segs = [new QrSegment(QrSegment.Mode.KANJI, kanjiCharBits.length / 13, kanjiCharBits)];\n qr = QrCode.encodeSegments(segs, QrCode.Ecc.LOW);\n qr.drawCanvas(9, 4, appendCanvas(\"madoka-kanji-QR\"));\n }",
"function Segment(oa){\n\t\t// debug('\\n SEGMENT - START');\n\t\toa = oa || {};\n\t\tthis.objtype = 'segment';\n\n\t\tthis.p1x = numSan(oa.p1x) || 0;\n\t\tthis.p1y = numSan(oa.p1y) || 0;\n\n\t\tthis.p2x = numSan(oa.p2x) || this.p1x || 0;\n\t\tthis.p2y = numSan(oa.p2y) || this.p1y || 0;\n\n\t\tthis.p3x = numSan(oa.p3x) || 0;\n\t\tthis.p3y = numSan(oa.p3y) || 0;\n\n\t\tthis.p4x = numSan(oa.p4x) || 0;\n\t\tthis.p4y = numSan(oa.p4y) || 0;\n\n\t\tif(!oa.p3x) this.p3x = this.p4x;\n\t\tif(!oa.p3y) this.p3y = this.p4y;\n\n\t\tthis.line = this.isLine();\n\n\t\t// cache\n\t\toa.cache = oa.cache || {};\n\t\tthis.cache = {};\n\t\tthis.cache.length = oa.cache.length || false;\n\n\t\t// debug(' SEGMENT - END\\n');\n\t}",
"function Segment(startFrame, endFrame) {\n\t\tthis.id = -1;\n\t\tthis.startFrame = startFrame;\n\t\tthis.endFrame = endFrame;\n\t\tthis.description = '';\n\t}",
"function Segment(i,e,t,n){this.path=i,this.length=i.getTotalLength(),this.path.style.strokeDashoffset=2*this.length,this.begin=\"undefined\"!=typeof e?this.valueOf(e):0,this.end=\"undefined\"!=typeof t?this.valueOf(t):this.length,this.circular=\"undefined\"!==n?n:!1,this.timer=null,this.animationTimer=null,this.draw(this.begin,this.end,0,{circular:this.circular})}",
"handleLineSegment3d(segment0) {\n if (this._geometry1 instanceof LineSegment3d_1.LineSegment3d) {\n const segment1 = this._geometry1;\n return LineSegment3d_1.LineSegment3d.create(segment0.startPoint().interpolate(this._fraction, segment1.startPoint()), segment0.endPoint().interpolate(this._fraction, segment1.endPoint()));\n }\n return undefined;\n }",
"function Segment(x1, y1, x2, y2){\r\n\tthis.x1 = x1;\r\n\tthis.y1 = y1;\r\n\tthis.x2 = x2;\r\n\tthis.y2 = y2;\r\n}",
"segment() {\n\t\tif(!this.RoadBuilding) {\n\t\t\tconsole.log(\"Error in segment: You need to start building a road first\");\n\t\t}\n\t\telse {\n\t\t\tvar segment = new roadSegment(this.PosX,\n\t\t\t\t\t\t\t\t\t \tthis.PosY,\n\t\t\t\t\t\t\t\t\t\t this.PosZ,\n\t\t\t\t\t\t\t\t\t\t this.RoadSegmentWidth,\n\t\t\t\t\t\t\t\t\t\t this.TorusRadius,\n\t\t\t\t\t\t\t\t\t\t \tthis.TorusTubeRadius,\n\t\t\t\t\t\t\t\t\t\t \tthis.Color);\n\t\t\tthis.road.add(segment.getObject());\n\t\t\tthis.PosZ += (2*this.TorusRadius + this.RoadSpaceBetweenSegments)*Math.cos(this.Direction);\n\t\t\tthis.PosX += (2*this.TorusRadius + this.RoadSpaceBetweenSegments)*Math.sin(this.Direction);\n\t\t\tsegment.getObject().rotation.y = this.Direction;\n\t\t}\n\t}",
"function Segment2d () {\n /**\n * Ray of segment\n * @type Ray2d\n */\n this.pRay = new Ray2d();\n /**\n * Distance\n * @type Float\n */\n this.fDistance = 0.0;\n}",
"function R3_subdivide_triangle_segment(side0, t0, side1, t1) {\n //console.log('Subdividing triangle segment', side0, t0, side1, t1);\n var start_subtri = (t0 <= 0.5 ? side0 : (side0+1)%3);\n var end_subtri = (t1 <= 0.5 ? side1 : (side1+1)%3);\n var ans = ( t0 <= 0.5 ? [ [ side0, -1, 2*t0 ] ] : [ [ (side0+1)%3, -3, 2*(t0-0.5) ] ]);\n //console.log('start,end,ans so far:', start_subtri, end_subtri, ans);\n if (start_subtri == end_subtri) {\n //No crossings\n return ans;\n }\n //Otherwise, there are some; we first leave the start subtri\n //then we enter the end_subtri\n var model_tri = [ new R2Point(0,0), new R2Point(1,0), new R2Point(0,1) ];\n var model_start = R2_interpolate_segment(t0, model_tri[side0], model_tri[(side0+1)%3]);\n var model_end = R2_interpolate_segment(t1, model_tri[side1], model_tri[(side1+1)%3]);\n var model_middles = [ [new R2Point(0.5,0), new R2Point(0,0.5)],\n [new R2Point(0.5,0.5), new R2Point(0.5,0)],\n [new R2Point(0,0.5), new R2Point(0.5,0.5)] ];\n var start_t = R2_segment_intersection(model_start, model_end, model_middles[start_subtri][0], model_middles[start_subtri][1])[1];\n var end_t = R2_segment_intersection(model_start, model_end, model_middles[end_subtri][0], model_middles[end_subtri][1])[1];\n //console.log('start_t, end_t', start_t, end_t);\n ans.push( [ start_subtri, 2, start_t ] );\n ans.push( [ end_subtri, -2, end_t ] );\n return ans;\n}",
"segmentType(gameObject, other) {\n if ( recSegIntersect(gameObject.rec, other.rec.segRight) || recSegIntersect(gameObject.rec, other.rec.segLeft) ) {\n return \"vertical\";\n } else if ( recSegIntersect(gameObject.rec, other.rec.segTop) || recSegIntersect(gameObject.rec, other.rec.segBot) ) {\n return \"horizontal\";\n } else {\n throw Error(gameObject.constructor.name + \" did not intersect with any segments of \" + other.constructor.name + \" [segmentType]\");\n }\n }",
"segment() {\n var output =\n this.brand + \" \" + this.model + \" is in \" + this.type + \" segment.\";\n return output;\n }",
"function setSegmentAnimation()\n{\nvar transformObject1 = kony.ui.makeAffineTransform();\nvar transformObject2 = kony.ui.makeAffineTransform();\n\n// \ntransformObject1.translate(200, 0);\ntransformObject2.translate(0, 0);\n\nvar animationObject = kony.ui.createAnimation(\n {\n \t\"0\":{\"transform\":transformObject1,\"stepConfig\":{\"timingFunction\":kony.anim.LINEAR}},\n \"100\":{\"transform\":transformObject2,\"stepConfig\":{\"timingFunction\":kony.anim.LINEAR}}\n});\n\nvar animationConfig = {\n duration: 1,\n fillMode: kony.anim.FILL_MODE_FORWARDS\n};\n\nvar animationCallbacks = {\"animationEnd\":function(){kony.print(\"animation END\");}};\n\nvar animationDefObject={definition:animationObject,config:animationConfig,callbacks:animationCallbacks};\n\nfrmHome.sgmtCategories.setAnimations({visible:animationDefObject});\n}",
"createStrand(atoms, num, div, fill, coilWidth, helixSheetWidth, doNotSmoothen, thickness, bHighlight) {\n let ic = this.icn3d,\n me = ic.icn3dui\n if (me.bNode) return\n\n let bRibbon = fill ? true : false\n\n // when highlight, the input atoms may only include part of sheet or helix\n // include the whole sheet or helix when highlighting\n let atomsAdjust = {}\n\n //if( (bHighlight === 1 || bHighlight === 2) && !ic.bAllAtoms) {\n if (!ic.bAllAtoms) {\n atomsAdjust = this.getSSExpandedAtoms(atoms)\n } else {\n atomsAdjust = atoms\n }\n\n if (bHighlight === 2) {\n if (fill) {\n fill = false\n num = null\n div = null\n coilWidth = null\n helixSheetWidth = null\n thickness = undefined\n } else {\n fill = true\n num = 2\n div = undefined\n coilWidth = undefined\n helixSheetWidth = undefined\n thickness = ic.ribbonthickness\n }\n }\n\n num = num || ic.strandDIV\n div = div || ic.axisDIV\n coilWidth = coilWidth || ic.coilWidth\n doNotSmoothen = doNotSmoothen || false\n helixSheetWidth = helixSheetWidth || ic.helixSheetWidth\n let pnts = {}\n for (let k = 0; k < num; ++k) pnts[k] = []\n let pntsCA = []\n let prevCOArray = []\n let bShowArray = []\n let calphaIdArray = [] // used to store one of the final positions drawn in 3D\n let colors = []\n let currentChain,\n currentResi,\n currentCA = null,\n currentO = null,\n currentColor = null,\n prevCoorCA = null,\n prevCoorO = null,\n prevColor = null\n let prevCO = null,\n ss = null,\n ssend = false,\n atomid = null,\n prevAtomid = null,\n prevResi = null,\n calphaid = null,\n prevCalphaid = null\n let strandWidth,\n bSheetSegment = false,\n bHelixSegment = false\n let atom,\n tubeAtoms = {}\n\n // test the first 30 atoms to see whether only C-alpha is available\n ic.bCalphaOnly = me.utilsCls.isCalphaPhosOnly(atomsAdjust) //, 'CA');\n\n // when highlight, draw whole beta sheet and use bShowArray to show the highlight part\n let residueHash = {}\n for (let i in atomsAdjust) {\n let atom = atomsAdjust[i]\n\n let residueid = atom.structure + '_' + atom.chain + '_' + atom.resi\n residueHash[residueid] = 1\n }\n let totalResidueCount = Object.keys(residueHash).length\n\n let drawnResidueCount = 0\n let highlightResiduesCount = 0\n\n let bFullAtom = Object.keys(ic.hAtoms).length == Object.keys(ic.atoms).length ? true : false\n\n let caArray = [] // record all C-alpha atoms to predict the helix\n\n for (let i in atomsAdjust) {\n atom = atomsAdjust[i]\n let atomOxygen = undefined\n if ((atom.name === 'O' || atom.name === 'CA') && !atom.het) {\n // \"CA\" has to appear before \"O\"\n\n if (atom.name === 'CA') {\n if (\n atoms.hasOwnProperty(i) &&\n ((atom.ss !== 'helix' && atom.ss !== 'sheet') || atom.ssend || atom.ssbegin)\n ) {\n tubeAtoms[i] = atom\n }\n\n currentCA = atom.coord\n currentColor = atom.color\n calphaid = atom.serial\n\n caArray.push(atom.serial)\n }\n\n if (atom.name === 'O' || (ic.bCalphaOnly && atom.name === 'CA')) {\n if (currentCA === null || currentCA === undefined) {\n currentCA = atom.coord\n currentColor = atom.color\n calphaid = atom.serial\n }\n\n if (atom.name === 'O') {\n currentO = atom.coord\n }\n // smoothen each coil, helix and sheet separately. The joint residue has to be included both in the previous and next segment\n let bSameChain = true\n // if (currentChain !== atom.chain || currentResi + 1 !== atom.resi) {\n if (currentChain !== atom.chain) {\n bSameChain = false\n }\n\n if (atom.ssend && atom.ss === 'sheet') {\n bSheetSegment = true\n } else if (atom.ssend && atom.ss === 'helix') {\n bHelixSegment = true\n }\n\n // assign the previous residue\n if (prevCoorO) {\n if (bHighlight === 1 || bHighlight === 2) {\n colors.push(ic.hColor)\n } else {\n colors.push(prevColor)\n }\n\n if (ss !== 'coil' && atom.ss === 'coil') {\n strandWidth = coilWidth\n } else if (ssend && atom.ssbegin) {\n // a transition between two ss\n strandWidth = coilWidth\n } else {\n strandWidth = ss === 'coil' ? coilWidth : helixSheetWidth\n }\n\n let O,\n oldCA,\n resSpan = 4\n if (atom.name === 'O') {\n O = prevCoorO.clone()\n if (prevCoorCA !== null && prevCoorCA !== undefined) {\n O.sub(prevCoorCA)\n } else {\n prevCoorCA = prevCoorO.clone()\n if (caArray.length > resSpan + 1) {\n // use the calpha and the previous 4th c-alpha to calculate the helix direction\n O = prevCoorCA.clone()\n oldCA = ic.atoms[caArray[caArray.length - 1 - resSpan - 1]].coord.clone()\n //O.sub(oldCA);\n oldCA.sub(O)\n } else {\n O = new THREE.Vector3(Math.random(), Math.random(), Math.random())\n }\n }\n } else if (ic.bCalphaOnly && atom.name === 'CA') {\n if (caArray.length > resSpan + 1) {\n // use the calpha and the previous 4th c-alpha to calculate the helix direction\n O = prevCoorCA.clone()\n oldCA = ic.atoms[caArray[caArray.length - 1 - resSpan - 1]].coord.clone()\n //O.sub(oldCA);\n oldCA.sub(O)\n } else {\n O = new THREE.Vector3(Math.random(), Math.random(), Math.random())\n }\n }\n\n O.normalize() // can be omitted for performance\n O.multiplyScalar(strandWidth)\n if (prevCO !== null && O.dot(prevCO) < 0) O.negate()\n prevCO = O\n\n for (let j = 0, numM1Inv2 = 2 / (num - 1); j < num; ++j) {\n let delta = -1 + numM1Inv2 * j\n let v = new THREE.Vector3(\n prevCoorCA.x + prevCO.x * delta,\n prevCoorCA.y + prevCO.y * delta,\n prevCoorCA.z + prevCO.z * delta,\n )\n if (!doNotSmoothen && ss === 'sheet') v.smoothen = true\n pnts[j].push(v)\n }\n\n pntsCA.push(prevCoorCA)\n prevCOArray.push(prevCO)\n\n if (atoms.hasOwnProperty(prevAtomid)) {\n bShowArray.push(prevResi)\n calphaIdArray.push(prevCalphaid)\n\n ++highlightResiduesCount\n } else {\n bShowArray.push(0)\n calphaIdArray.push(0)\n }\n\n ++drawnResidueCount\n }\n\n let maxDist = 6.0\n let bBrokenSs =\n (prevCoorCA && Math.abs(currentCA.x - prevCoorCA.x) > maxDist) ||\n (prevCoorCA && Math.abs(currentCA.y - prevCoorCA.y) > maxDist) ||\n (prevCoorCA && Math.abs(currentCA.z - prevCoorCA.z) > maxDist)\n\n if (\n (atom.ssbegin || atom.ssend || drawnResidueCount === totalResidueCount - 1 || bBrokenSs) &&\n pnts[0].length > 0 &&\n bSameChain\n ) {\n let atomName = 'CA'\n\n let prevone = [],\n nexttwo = []\n\n if (isNaN(ic.atoms[prevAtomid].resi)) {\n prevone = []\n } else {\n let prevoneResid =\n ic.atoms[prevAtomid].structure +\n '_' +\n ic.atoms[prevAtomid].chain +\n '_' +\n (parseInt(ic.atoms[prevAtomid].resi) - 1).toString()\n let prevoneCoord = ic.firstAtomObjCls.getAtomCoordFromResi(prevoneResid, atomName)\n prevone = prevoneCoord !== undefined ? [prevoneCoord] : []\n }\n\n if (!isNaN(ic.atoms[prevAtomid].resi)) {\n let nextoneResid =\n ic.atoms[prevAtomid].structure +\n '_' +\n ic.atoms[prevAtomid].chain +\n '_' +\n (parseInt(ic.atoms[prevAtomid].resi) + 1).toString()\n let nextoneCoord = ic.firstAtomObjCls.getAtomCoordFromResi(nextoneResid, atomName)\n if (nextoneCoord !== undefined) {\n nexttwo.push(nextoneCoord)\n }\n\n let nexttwoResid =\n ic.atoms[prevAtomid].structure +\n '_' +\n ic.atoms[prevAtomid].chain +\n '_' +\n (parseInt(ic.atoms[prevAtomid].resi) + 2).toString()\n let nexttwoCoord = ic.firstAtomObjCls.getAtomCoordFromResi(nexttwoResid, atomName)\n if (nexttwoCoord !== undefined) {\n nexttwo.push(nexttwoCoord)\n }\n }\n\n if (!bBrokenSs) {\n // include the current residue\n // assign the current joint residue to the previous segment\n if (bHighlight === 1 || bHighlight === 2) {\n colors.push(ic.hColor)\n } else {\n //colors.push(atom.color);\n colors.push(prevColor)\n }\n\n if (atom.ssend && atom.ss === 'sheet') {\n // current residue is the end of ss and is the end of arrow\n strandWidth = 0 // make the arrow end sharp\n } else if (ss === 'coil' && atom.ssbegin) {\n strandWidth = coilWidth\n } else if (ssend && atom.ssbegin) {\n // current residue is the start of ss and the previous residue is the end of ss, then use coil\n strandWidth = coilWidth\n } else {\n // use the ss from the previous residue\n strandWidth = atom.ss === 'coil' ? coilWidth : helixSheetWidth\n }\n\n let O,\n oldCA,\n resSpan = 4\n if (atom.name === 'O') {\n O = currentO.clone()\n O.sub(currentCA)\n } else if (ic.bCalphaOnly && atom.name === 'CA') {\n if (caArray.length > resSpan) {\n // use the calpha and the previous 4th c-alpha to calculate the helix direction\n O = currentCA.clone()\n oldCA = ic.atoms[caArray[caArray.length - 1 - resSpan]].coord.clone()\n //O.sub(oldCA);\n oldCA.sub(O)\n } else {\n O = new THREE.Vector3(Math.random(), Math.random(), Math.random())\n }\n }\n\n O.normalize() // can be omitted for performance\n O.multiplyScalar(strandWidth)\n if (prevCO !== null && O.dot(prevCO) < 0) O.negate()\n prevCO = O\n\n for (let j = 0, numM1Inv2 = 2 / (num - 1); j < num; ++j) {\n let delta = -1 + numM1Inv2 * j\n let v = new THREE.Vector3(\n currentCA.x + prevCO.x * delta,\n currentCA.y + prevCO.y * delta,\n currentCA.z + prevCO.z * delta,\n )\n if (!doNotSmoothen && ss === 'sheet') v.smoothen = true\n pnts[j].push(v)\n }\n\n atomid = atom.serial\n\n pntsCA.push(currentCA)\n prevCOArray.push(prevCO)\n\n // when a coil connects to a sheet and the last residue of coild is highlighted, the first sheet residue is set as atom.highlightStyle. This residue should not be shown.\n //if(atoms.hasOwnProperty(atomid) && (bHighlight === 1 && !atom.notshow) ) {\n if (atoms.hasOwnProperty(atomid)) {\n bShowArray.push(atom.resi)\n calphaIdArray.push(calphaid)\n } else {\n bShowArray.push(0)\n calphaIdArray.push(0)\n }\n }\n\n // draw the current segment\n for (let j = 0; !fill && j < num; ++j) {\n if (bSheetSegment) {\n ic.curveStripArrowCls.createCurveSubArrow(\n pnts[j],\n 1,\n colors,\n div,\n bHighlight,\n bRibbon,\n num,\n j,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n true,\n prevone,\n nexttwo,\n )\n } else if (bHelixSegment) {\n if (bFullAtom) {\n ic.curveCls.createCurveSub(\n pnts[j],\n 1,\n colors,\n div,\n bHighlight,\n bRibbon,\n false,\n bShowArray,\n calphaIdArray,\n undefined,\n prevone,\n nexttwo,\n )\n } else {\n ic.curveStripArrowCls.createCurveSubArrow(\n pnts[j],\n 1,\n colors,\n div,\n bHighlight,\n bRibbon,\n num,\n j,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n false,\n prevone,\n nexttwo,\n )\n }\n }\n }\n if (fill) {\n if (bSheetSegment) {\n let start = 0,\n end = num - 1\n ic.curveStripArrowCls.createStripArrow(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n num,\n start,\n end,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n true,\n prevone,\n nexttwo,\n )\n } else if (bHelixSegment) {\n if (bFullAtom) {\n ic.stripCls.createStrip(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n false,\n bShowArray,\n calphaIdArray,\n undefined,\n prevone,\n nexttwo,\n pntsCA,\n prevCOArray,\n )\n } else {\n let start = 0,\n end = num - 1\n ic.curveStripArrowCls.createStripArrow(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n num,\n start,\n end,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n false,\n prevone,\n nexttwo,\n )\n }\n } else {\n if (bHighlight === 2) {\n // draw coils only when highlighted. if not highlighted, coils will be drawn as tubes separately\n ic.stripCls.createStrip(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n false,\n bShowArray,\n calphaIdArray,\n undefined,\n prevone,\n nexttwo,\n pntsCA,\n prevCOArray,\n )\n }\n }\n }\n for (let k = 0; k < num; ++k) pnts[k] = []\n\n colors = []\n pntsCA = []\n prevCOArray = []\n bShowArray = []\n calphaIdArray = []\n bSheetSegment = false\n bHelixSegment = false\n } // end if (atom.ssbegin || atom.ssend)\n\n // end of a chain\n // if ((currentChain !== atom.chain || currentResi + 1 !== atom.resi) && pnts[0].length > 0) {\n if (currentChain !== atom.chain && pnts[0].length > 0) {\n let atomName = 'CA'\n\n let prevone = [],\n nexttwo = []\n if (isNaN(ic.atoms[prevAtomid].resi)) {\n prevone = []\n } else {\n let prevoneResid =\n ic.atoms[prevAtomid].structure +\n '_' +\n ic.atoms[prevAtomid].chain +\n '_' +\n (parseInt(ic.atoms[prevAtomid].resi) - 1).toString()\n let prevoneCoord = ic.firstAtomObjCls.getAtomCoordFromResi(prevoneResid, atomName)\n let prevone = prevoneCoord !== undefined ? [prevoneCoord] : []\n }\n\n for (let j = 0; !fill && j < num; ++j) {\n if (bSheetSegment) {\n ic.curveStripArrowCls.createCurveSubArrow(\n pnts[j],\n 1,\n colors,\n div,\n bHighlight,\n bRibbon,\n num,\n j,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n true,\n prevone,\n nexttwo,\n )\n } else if (bHelixSegment) {\n if (bFullAtom) {\n ic.curveCls.createCurveSub(\n pnts[j],\n 1,\n colors,\n div,\n bHighlight,\n bRibbon,\n false,\n bShowArray,\n calphaIdArray,\n undefined,\n prevone,\n nexttwo,\n )\n } else {\n ic.curveStripArrowCls.createCurveSubArrow(\n pnts[j],\n 1,\n colors,\n div,\n bHighlight,\n bRibbon,\n num,\n j,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n false,\n prevone,\n nexttwo,\n )\n }\n }\n }\n if (fill) {\n if (bSheetSegment) {\n let start = 0,\n end = num - 1\n ic.curveStripArrowCls.createStripArrow(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n num,\n start,\n end,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n true,\n prevone,\n nexttwo,\n )\n } else if (bHelixSegment) {\n if (bFullAtom) {\n ic.stripCls.createStrip(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n false,\n bShowArray,\n calphaIdArray,\n undefined,\n prevone,\n nexttwo,\n pntsCA,\n prevCOArray,\n )\n } else {\n let start = 0,\n end = num - 1\n ic.curveStripArrowCls.createStripArrow(\n pnts[0],\n pnts[num - 1],\n colors,\n div,\n thickness,\n bHighlight,\n num,\n start,\n end,\n pntsCA,\n prevCOArray,\n bShowArray,\n calphaIdArray,\n false,\n prevone,\n nexttwo,\n )\n }\n }\n }\n\n for (let k = 0; k < num; ++k) pnts[k] = []\n colors = []\n pntsCA = []\n prevCOArray = []\n bShowArray = []\n calphaIdArray = []\n bSheetSegment = false\n bHelixSegment = false\n }\n\n currentChain = atom.chain\n currentResi = atom.resi\n ss = atom.ss\n ssend = atom.ssend\n prevAtomid = atom.serial\n prevResi = atom.resi\n\n prevCalphaid = calphaid\n\n // only update when atom.name === 'O'\n prevCoorCA = currentCA\n prevCoorO = atom.coord\n prevColor = currentColor\n } // end if (atom.name === 'O' || (ic.bCalphaOnly && atom.name === 'CA') ) {\n } // end if ((atom.name === 'O' || atom.name === 'CA') && !atom.het) {\n } // end for\n\n caArray = []\n\n ic.tubeCls.createTube(tubeAtoms, 'CA', coilWidth, bHighlight)\n\n tubeAtoms = {}\n pnts = {}\n }",
"function Segment(args) {\n if (args === undefined) {\n return;\n }\n if (args.text) {\n this.windows = [args.text];\n } else if (args.windows) {\n this.windows = args.windows;\n } else {\n this.windows = [\"\"];\n }\n // What index we are in the window.\n this.windowIx = (args.windowIx || 0) % this.windows.length;\n\n this.fecund = args.fecund || false;\n this.direction = args.direction || 1;\n this.wasFecund = this.fecund;\n this.animation = args.animation || EAnimation.NONE;\n\n // The previous 'Segment' we are linked to.\n this.prev = null;\n // The next 'Segment' we are linked to.\n this.next = null;\n if (args.last) {\n var next = args.last.next;\n args.last.next = this;\n this.prev = args.last;\n if (next) {\n this.next = next;\n next.prev = this;\n }\n }\n\n // Assert the windows are all of the same size.\n this.length = undefined;\n for (var i = 0; i < this.windows.length; ++i) {\n var length = this.windows[i].length;\n if (this.length === undefined) {\n this.length = length;\n } else if (length != this.length) {\n throw new Error(\"Segment cannot have segments of different lengths.\");\n }\n }\n }",
"function Segment( plant, parentSegment, basePoint1, basePoint2 ) {\n this.plantId = plant.id;\n this.parentPlant = plant;\n this.id = plant.segmentCount;\n this.child = null;\n this.hasChild = false;\n this.parentSegment = parentSegment;\n this.isBaseSegment = false; if (this.parentSegment === null) { this.isBaseSegment = true; }\n this.hasLeaves = false;\n this.hasLeafScaffolding = false;\n //settings\n this.forwardGrowthRateVariation = Tl.rfb(0.97,1.03); // for left & right span length variation\n this.mass = 1; // mass of the segment stalk portion ( divided between the two extension points)\n //base points\n this.ptB1 = basePoint1; // base point 1\n this.ptB2 = basePoint2; // base point 2\n //extension points\n var originX = ( this.ptB1.cx + this.ptB2.cx ) / 2; // center of base points x values\n var originY = ( this.ptB1.cy + this.ptB2.cy ) / 2; // center of base points y values \n this.ptE1 = addPt( pctFromXVal( originX ) - 0.1, pctFromYVal( originY ) - 0.1 ); // extension point 1\n this.ptE2 = addPt( pctFromXVal( originX ) + 0.1, pctFromYVal( originY ) - 0.1 ); // extension point 2\n this.ptE1.mass = this.mass / 2;\n this.ptE2.mass = this.mass / 2;\n //spans\n this.spL = addSp( this.ptB1.id, this.ptE1.id ); // left span\n this.spR = addSp( this.ptB2.id, this.ptE2.id ); // right span\n this.spF = addSp( this.ptE1.id, this.ptE2.id ); // forward span\n this.spCd = addSp( this.ptE1.id, this.ptB2.id ); // downward (l to r) cross span\n this.spCu = addSp( this.ptB1.id, this.ptE2.id ); // upward (l to r) cross span\n if (!this.isBaseSegment) {\n this.spCdP = addSp( this.ptE1.id, this.parentSegment.ptB2.id ); // downward (l to r) cross span to parent\n this.spCuP = addSp( this.parentSegment.ptB1.id, this.ptE2.id ); // upward (l to r) cross span to parent\n this.spCdP.strength = plant.stalkStrength;\n this.spCuP.strength = plant.stalkStrength;\n }\n this.spL.strength = plant.stalkStrength;\n this.spR.strength = plant.stalkStrength;\n this.spF.strength = plant.stalkStrength;\n this.spCd.strength = plant.stalkStrength;\n this.spCu.strength = plant.stalkStrength;\n //skins\n this.skins = [];\n this.skins.push( addSk( [ this.ptE1.id, this.ptE2.id, this.ptB2.id, this.ptB1.id ], null ) );\n //leaves\n this.ptLf1 = null; // leaf point 1 (leaf tip)\n this.ptLf2 = null; // leaf point 2 (leaf tip) \n this.spLf1 = null; // leaf 1 Span\n this.spLf2 = null; // leaf 2 Span\n //colors\n this.clS = C.hdf; // stalk color (dark green when healthy)\n this.clO = C.hol; // outline color (very dark brown when healthy)\n this.clI = C.hil; // inner line color (slightly darker green than leaf fill when healthy) \n this.clL = C.hlf; // leaf color (green when healthy)\n this.clLS = C.hls; // leaf shadow color (barely opaque black when healthy) \n}",
"static EndVertical() {}",
"function drawArcSegOut(isUpperHalf)\r\n\t {\r\n\t\t var divY;\r\n\t\t var xDataArray1,xDataArray1;\r\n\t\t var divWidthFirst=divWidthOrg;\r\n\t\t var divWidthSecond=divWidthOrg;\r\n\t\t var drawFirst=false;\r\n\t\t var drawSecond=false;\r\n \t\t\r\n\t\t if(isUpperHalf)\r\n\t\t {\r\n\t\t\t var draw1=false; //upper half\r\n\t\t\t var draw3=false; //upper half second\r\n\t\t\t divY=divY1;\r\n\t\t\t xDataArray1=xDataArraySa;\r\n\t\t\t xDataArray2=xDataArrayEa;\r\n\t\t\t saDvar=saD;\r\n\t\t\t eaDvar=eaD;\r\n\t\t }\r\n\t\t else\r\n\t\t {\r\n\t\t\t var draw2=false; //lower half\r\n\t\t\t var draw4=false; //lower half second\r\n\t\t\t divY=divY2;\r\n\t\t\t xDataArray2=xDataArraySa;\r\n\t\t\t xDataArray1=xDataArrayEa;\r\n\t\t\t saDvar=360-eaD;\r\n\t\t\t eaDvar=360-saD;\r\n\t\t }\r\n\t\t if(eaDvar>saDvar)\r\n\t\t {\r\n\t\t\t if(xDataArray2[divY]!=null && divX1+divWidthOrg>=xDataArray2[divY].xMin && divX1<=xDataArray2[divY].xMin)\r\n\t\t\t {\r\n\t\t\t\t eaX=xDataArray2[divY].xMin;\r\n\t\t\t\t if(xDataArray1[divY] && divX1+divWidthOrg>=xDataArray1[divY].xMax+1 && divX1<=xDataArray1[divY].xMax+1)\r\n\t\t\t\t {\r\n\t\t\t\t\t saX=xDataArray1[divY].xMax+1;\r\n\t\t\t\t\t divWidthFirst=saX-eaX;\r\n\t\t\t\t }\r\n\t\t\t\t else\r\n\t\t\t\t {\r\n\t\t\t\t\t divWidthFirst=divX1+divWidthOrg-eaX;\r\n\t\t\t\t }\r\n\t\t\t\t divX1=eaX;\r\n\t\t\t\t drawFirst=true;\r\n\t\t\t }\r\n\t\t\t else if(xDataArray1[divY]!=null && divX1+divWidthOrg>=xDataArray1[divY].xMax+1 && divX1<=xDataArray1[divY].xMax+1)\r\n\t\t\t {\r\n\t\t\t\t saX=xDataArray1[divY].xMax+1;\r\n\t\t\t\t divWidthFirst=saX-divX1;\r\n\t\t\t\t drawFirst=true;\r\n\t\t\t }\r\n\t\t\t else if(eaDvar>90 && saDvar<90)\r\n\t\t\t {\r\n\t\t\t\t drawFirst=true;\r\n\t\t\t }\r\n\t\t }\r\n\t\t else //saDvar>eaDvar\r\n\t\t {\r\n\t\t\t if(xDataArray1[divY]!=null && divX1+divWidthOrg>=xDataArray1[divY].xMax+1 && divX1<=xDataArray1[divY].xMax+1)\r\n\t\t\t {\r\n\t\t\t\t saX=xDataArray1[divY].xMax+1;\r\n\t\t\t\t divWidthFirst=saX-divX1;\r\n\t\t\t\t drawFirst=true;\r\n\t\t\t }\r\n\t\t\t else if(eaDvar<90 && saDvar<90)\r\n\t\t\t {\r\n\t\t\t\t drawFirst=true;\r\n\t\t\t }\r\n \t\r\n\t\t\t if(xDataArray2[divY]!=null && divX1+divWidthOrg>=xDataArray2[divY].xMin && divX1<=xDataArray2[divY].xMin)\r\n\t\t\t {\r\n\t\t\t\t divX2=xDataArray2[divY].xMin;\r\n\t\t\t\t divWidthSecond=divWidthOrg-xDataArray2[divY].xMin+divX1;\r\n\t\t\t\t drawSecond=true;\r\n\t\t\t }\r\n\t\t\t else if(eaDvar>90 && saDvar>90)\r\n\t\t\t {\r\n\t\t\t\t divX2=divX1;\r\n\t\t\t\t divWidthSecond=divWidthOrg;\r\n\t\t\t\t drawSecond=true;\r\n\t\t\t }\r\n\t\t }\r\n \t\t\r\n\t\t if(isUpperHalf)\r\n\t\t {\r\n\t\t\t if(drawFirst)\r\n\t\t\t\t draw1=true;\r\n \t\t\t\r\n\t\t\t if(drawSecond)\r\n\t\t\t\t draw3=true;\r\n \t\t\t\t\r\n\t\t\t divWidth1=divWidthFirst;\r\n\t\t\t divWidth3=divWidthSecond;\t\r\n\t\t }\r\n\t\t else\r\n\t\t {\r\n\t\t\t if(drawFirst)\r\n\t\t\t\t draw2=true;\r\n \t\t\t\r\n\t\t\t if(drawSecond)\r\n\t\t\t\t draw4=true;\r\n \t\t\t\t\r\n\t\t\t divWidth2=divWidthFirst;\r\n\t\t\t divWidth4=divWidthSecond;\t\r\n\t\t }\r\n \t\t\r\n\t\t if(saD>=0 && saD<180 && eaD>=0 && eaD<180 && saD>eaD)\r\n\t\t {\r\n\t\t\t draw2=true;\r\n\t\t }\t\t\t\t\r\n\t\t else if(saD>=180 && saD<360 && eaD>=180 && eaD<360 && saD>eaD)\r\n\t\t {\r\n\t\t\t draw1=true;\r\n\t\t }\r\n \t\t\r\n //Start: Only for drawArc (not in fillArc) \r\n if(draw1)\r\n {\r\n \r\n\t if(xArray[divY1-yc] && divX1!=null)\r\n\t {\r\n\t if(xc+xArray[divY1-yc]<=divX1+divWidth1)\r\n\t {\r\n\t if(divWidth1>divX1+divWidth1-xc-xArray[divY1-yc])\r\n\t {\r\n\t divX1i=xc+xArray[divY1-yc];\r\n\t divWidth1i=divX1+divWidth1-xc-xArray[divY1-yc];\r\n\t }\r\n\t }\r\n\t else\r\n\t divX1i=\"X\";\r\n \t \r\n\t if(divX1<xc-xArray[divY1-yc]+1)\r\n\t {\r\n\t if(divWidth1>xc-xArray[divY1-yc]-divX1+1)\r\n divWidth1=xc-xArray[divY1-yc]-divX1+1;\r\n\t }\r\n\t else if(divWidth1>=divX1+divWidth1-xc-xArray[divY1-yc]+1)\r\n\t divX1=\"X\";\r\n\t\t }\r\n \t\t \r\n\t\t }\r\n \r\n if(draw3)\r\n {\r\n\t if(xArray[divY1-yc] && divX2!=null)\r\n\t {\r\n if(xc+xArray[divY1-yc]<=divX2+divWidth3)\r\n\t {\r\n\t if(divWidth3>divX2+divWidth3-xc-xArray[divY1-yc])\r\n\t {\r\n\t divX2i=xc+xArray[divY1-yc];\r\n\t divWidth3i=divX2+divWidth3-xc-xArray[divY1-yc];\r\n\t }\r\n\t }\r\n\t else\r\n\t divX2i=\"X\";\r\n \t \r\n\t if(divX2<=xc-xArray[divY1-yc]+1)\r\n\t {\r\n\t if(divWidth3>xc-xArray[divY1-yc]-divX2+1)\r\n divWidth3=xc-xArray[divY1-yc]-divX2+1;\r\n\t }\r\n\t else if(divWidth3>=divX2+divWidth3-xc-xArray[divY1-yc]+1)\r\n\t divX2=\"X\";\r\n\t }\r\n\t }\r\n\r\n //Lower Half \r\n if(draw2)\r\n {\r\n\t if(xArray[divY1-yc] && divX1!=null)\r\n\t {\r\n\t if(xc+xArray[divY1-yc]<=divX1+divWidth2)\r\n\t {\r\n\t if(divWidth2>divX1+divWidth2-xc-xArrayI[divY1-yc])\r\n\t {\r\n\t divX1i=xc+xArray[divY1-yc];\r\n\t divWidth2i=divX1+divWidth2-xc-xArray[divY1-yc];\r\n\t }\r\n\t }\r\n\t else\r\n\t divX1i=\"X\";\r\n \t \r\n\t if(divX1<=xc-xArray[divY1-yc]+1)\r\n\t {\r\n\t if(divWidth2>xc-xArray[divY1-yc]-divX1+1)\r\n divWidth2=xc-xArray[divY1-yc]-divX1+1;\r\n\t }\r\n\t else if(divWidth2>=divX1+divWidth2-xc-xArray[divY1-yc]+1)\r\n\t divX1=\"X\";\r\n\t\t }\r\n\t\t }\r\n \t\t\r\n if(draw4)\r\n {\r\n\t if(xArrayI[divY1-yc] && divX2!=null)\r\n\t {\r\n if(xc+xArray[divY1-yc]<=divX2+divWidth4)\r\n\t {\r\n\t if(divWidth4>divX2+divWidth4-xc-xArray[divY1-yc])\r\n\t {\r\n\t divX2i=xc+xArray[divY1-yc];\r\n\t divWidth4i=divX2+divWidth4-xc-xArray[divY1-yc];\r\n\t }\r\n\t }\r\n\t else\r\n\t divX2i=\"X\";\r\n \t \r\n\t if(divX2<=xc-xArray[divY1-yc]+1)\r\n\t {\r\n\t if(divWidth4>xc-xArray[divY1-yc]-divX2+1)\r\n divWidth4=xc-xArray[divY1-yc]-divX2+1;\r\n\t }\r\n\t else if(divWidth4>=divX2+divWidth4-xc-xArray[divY1-yc]+1)\r\n\t divX2=\"X\";\r\n\t }\r\n\t }\r\n //End: Only for drawArc (not in fillArc) \r\n\r\n\t\t if(divX2==null)\r\n\t\t divX2=\"X\";\r\n\t\t if(divX1==null)\r\n\t\t divX1=\"X\";\r\n \t\t\r\n\t if(divX2i==null)\r\n\t\t divX2i=\"X\";\r\n\t\t if(divX1i==null)\r\n\t\t divX1i=\"X\";\r\n \t\t\r\n\t\t if(isUpperHalf)\r\n\t\t {\r\n\t\t\t divHeight=1;\r\n\t\t\t if(draw3)\r\n\t\t\t {\r\n\t\t\t\t if(divX2!=\"X\")\r\n\t\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX2 + \"px;top:\" + divY1 + \"px;width:\" + divWidth3 + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t\t\t\r\n\t\t\t\t if(divX2i!=\"X\")\r\n\t\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX2i + \"px;top:\" + divY1 + \"px;width:\" + divWidth3i + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t }\r\n\r\n\t\t\t if(draw1)\r\n\t\t\t {\r\n\t\t\t\t if(divX1!=\"X\")\r\n\t\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX1 + \"px;top:\" + divY1 + \"px;width:\" + divWidth1 + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\r\n\t\t\t\t if(divX1i!=\"X\")\r\n\t\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX1i + \"px;top:\" + divY1 + \"px;width:\" + divWidth1i + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t }\r\n\t\t }\t\r\n\t\t else\r\n\t\t {\r\n\t\t\t divHeight=1;\r\n\t\t\t if(draw4)\r\n\t\t\t {\r\n\t\t\t\t if(divX2!=\"X\")\r\n\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX2 + \"px;top:\" + (divY2+1-divHeight) + \"px;width:\" + divWidth4 + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t\t\t\r\n\t\t\t\t if(divX2i!=\"X\")\r\n\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX2i + \"px;top:\" + (divY2+1-divHeight) + \"px;width:\" + divWidth4i + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t }\r\n\t\t\t if(draw2)\r\n\t\t\t {\r\n\t\t\t\t if(divX1!=\"X\") \r\n\t\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX1 + \"px;top:\" + (divY2+1-divHeight) + \"px;width:\" + divWidth2 + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t\t\t\r\n\t\t\t\t if(divX1i!=\"X\") \r\n\t\t\t\t\t iHtml[iHtml.length]=\"<DIV style=\\\"position:absolute;overflow:hidden;left:\" + divX1i + \"px;top:\" + (divY2+1-divHeight) + \"px;width:\" + divWidth2i + \"px;height:\" + divHeight + \"px;background-color:\" + hexColor + \"\\\"></DIV>\";\r\n\t\t\t }\r\n\t\t }\t\t\t\r\n\t }",
"endClassDefinition() { this.endSection('};'); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `DistributionConfigProperty` | function CfnDistribution_DistributionConfigPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
errors.collect(cdk.propertyValidator('aliases', cdk.listValidator(cdk.validateString))(properties.aliases));
errors.collect(cdk.propertyValidator('cacheBehaviors', cdk.listValidator(CfnDistribution_CacheBehaviorPropertyValidator))(properties.cacheBehaviors));
errors.collect(cdk.propertyValidator('comment', cdk.validateString)(properties.comment));
errors.collect(cdk.propertyValidator('customErrorResponses', cdk.listValidator(CfnDistribution_CustomErrorResponsePropertyValidator))(properties.customErrorResponses));
errors.collect(cdk.propertyValidator('defaultCacheBehavior', CfnDistribution_DefaultCacheBehaviorPropertyValidator)(properties.defaultCacheBehavior));
errors.collect(cdk.propertyValidator('defaultRootObject', cdk.validateString)(properties.defaultRootObject));
errors.collect(cdk.propertyValidator('enabled', cdk.requiredValidator)(properties.enabled));
errors.collect(cdk.propertyValidator('enabled', cdk.validateBoolean)(properties.enabled));
errors.collect(cdk.propertyValidator('httpVersion', cdk.validateString)(properties.httpVersion));
errors.collect(cdk.propertyValidator('ipv6Enabled', cdk.validateBoolean)(properties.ipv6Enabled));
errors.collect(cdk.propertyValidator('logging', CfnDistribution_LoggingPropertyValidator)(properties.logging));
errors.collect(cdk.propertyValidator('originGroups', CfnDistribution_OriginGroupsPropertyValidator)(properties.originGroups));
errors.collect(cdk.propertyValidator('origins', cdk.listValidator(CfnDistribution_OriginPropertyValidator))(properties.origins));
errors.collect(cdk.propertyValidator('priceClass', cdk.validateString)(properties.priceClass));
errors.collect(cdk.propertyValidator('restrictions', CfnDistribution_RestrictionsPropertyValidator)(properties.restrictions));
errors.collect(cdk.propertyValidator('viewerCertificate', CfnDistribution_ViewerCertificatePropertyValidator)(properties.viewerCertificate));
errors.collect(cdk.propertyValidator('webAclId', cdk.validateString)(properties.webAclId));
return errors.wrap('supplied properties not correct for "DistributionConfigProperty"');
} | [
"function CfnDistributionPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('distributionConfig', cdk.requiredValidator)(properties.distributionConfig));\n errors.collect(cdk.propertyValidator('distributionConfig', CfnDistribution_DistributionConfigPropertyValidator)(properties.distributionConfig));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n return errors.wrap('supplied properties not correct for \"CfnDistributionProps\"');\n}",
"function containsAllowedProps(properties) {\n if (properties === null || (typeof properties === 'undefined' ? 'undefined' : _typeof(properties)) !== 'object') {\n return false;\n }\n return Object.entries(properties).some(function (property) {\n var key = property[0];\n var value = property[1];\n if (typeof value === 'string') {\n return key === 'style' || key === 'src' || key === 'href';\n } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && key === 'attributes') {\n return 'class' in properties.attributes;\n }\n });\n}",
"function CfnDistributionPropsValidator(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('bundleId', cdk.requiredValidator)(properties.bundleId));\n errors.collect(cdk.propertyValidator('bundleId', cdk.validateString)(properties.bundleId));\n errors.collect(cdk.propertyValidator('cacheBehaviorSettings', CfnDistribution_CacheSettingsPropertyValidator)(properties.cacheBehaviorSettings));\n errors.collect(cdk.propertyValidator('cacheBehaviors', cdk.listValidator(CfnDistribution_CacheBehaviorPerPathPropertyValidator))(properties.cacheBehaviors));\n errors.collect(cdk.propertyValidator('certificateName', cdk.validateString)(properties.certificateName));\n errors.collect(cdk.propertyValidator('defaultCacheBehavior', cdk.requiredValidator)(properties.defaultCacheBehavior));\n errors.collect(cdk.propertyValidator('defaultCacheBehavior', CfnDistribution_CacheBehaviorPropertyValidator)(properties.defaultCacheBehavior));\n errors.collect(cdk.propertyValidator('distributionName', cdk.requiredValidator)(properties.distributionName));\n errors.collect(cdk.propertyValidator('distributionName', cdk.validateString)(properties.distributionName));\n errors.collect(cdk.propertyValidator('ipAddressType', cdk.validateString)(properties.ipAddressType));\n errors.collect(cdk.propertyValidator('isEnabled', cdk.validateBoolean)(properties.isEnabled));\n errors.collect(cdk.propertyValidator('origin', cdk.requiredValidator)(properties.origin));\n errors.collect(cdk.propertyValidator('origin', CfnDistribution_InputOriginPropertyValidator)(properties.origin));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n return errors.wrap('supplied properties not correct for \"CfnDistributionProps\"');\n}",
"function validateProperties(props) {\n let validProps = getProperties();\n for (let i in props) {\n if (!validProps.includes(props[i])) {\n return false;\n }\n }\n return true;\n}",
"function CfnStreamingDistribution_StreamingDistributionConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('aliases', cdk.listValidator(cdk.validateString))(properties.aliases));\n errors.collect(cdk.propertyValidator('comment', cdk.requiredValidator)(properties.comment));\n errors.collect(cdk.propertyValidator('comment', cdk.validateString)(properties.comment));\n errors.collect(cdk.propertyValidator('enabled', cdk.requiredValidator)(properties.enabled));\n errors.collect(cdk.propertyValidator('enabled', cdk.validateBoolean)(properties.enabled));\n errors.collect(cdk.propertyValidator('logging', CfnStreamingDistribution_LoggingPropertyValidator)(properties.logging));\n errors.collect(cdk.propertyValidator('priceClass', cdk.validateString)(properties.priceClass));\n errors.collect(cdk.propertyValidator('s3Origin', cdk.requiredValidator)(properties.s3Origin));\n errors.collect(cdk.propertyValidator('s3Origin', CfnStreamingDistribution_S3OriginPropertyValidator)(properties.s3Origin));\n errors.collect(cdk.propertyValidator('trustedSigners', cdk.requiredValidator)(properties.trustedSigners));\n errors.collect(cdk.propertyValidator('trustedSigners', CfnStreamingDistribution_TrustedSignersPropertyValidator)(properties.trustedSigners));\n return errors.wrap('supplied properties not correct for \"StreamingDistributionConfigProperty\"');\n}",
"function CfnLoggingConfiguration_MatchPatternPropertyValidator(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('all', cdk.validateObject)(properties.all));\n errors.collect(cdk.propertyValidator('includedPaths', cdk.listValidator(cdk.validateString))(properties.includedPaths));\n return errors.wrap('supplied properties not correct for \"MatchPatternProperty\"');\n}",
"function hasEveryProp() {\n var nodeProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_OPTIONS;\n\n var propsToCheck = typeof props === 'string' ? props.split(' ') : props;\n\n return propsToCheck.every(function (prop) {\n return hasProp(nodeProps, prop, options);\n });\n}",
"function CfnDeliveryChannel_ConfigSnapshotDeliveryPropertiesPropertyValidator(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('deliveryFrequency', cdk.validateString)(properties.deliveryFrequency));\n return errors.wrap('supplied properties not correct for \"ConfigSnapshotDeliveryPropertiesProperty\"');\n}",
"function CfnCanary_ArtifactConfigPropertyValidator(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('s3Encryption', CfnCanary_S3EncryptionPropertyValidator)(properties.s3Encryption));\n return errors.wrap('supplied properties not correct for \"ArtifactConfigProperty\"');\n}",
"function CfnDeploymentConfigPropsValidator(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('computePlatform', cdk.validateString)(properties.computePlatform));\n errors.collect(cdk.propertyValidator('deploymentConfigName', cdk.validateString)(properties.deploymentConfigName));\n errors.collect(cdk.propertyValidator('minimumHealthyHosts', CfnDeploymentConfig_MinimumHealthyHostsPropertyValidator)(properties.minimumHealthyHosts));\n errors.collect(cdk.propertyValidator('trafficRoutingConfig', CfnDeploymentConfig_TrafficRoutingConfigPropertyValidator)(properties.trafficRoutingConfig));\n return errors.wrap('supplied properties not correct for \"CfnDeploymentConfigProps\"');\n}",
"function hasEveryProp() {\n var nodeProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_OPTIONS;\n var propsToCheck = typeof props === 'string' ? props.split(' ') : props;\n return propsToCheck.every(function (prop) {\n return hasProp(nodeProps, prop, options);\n });\n}",
"function matches(property, config, model) {\n\t\treturn listVerdict(Object.keys(config), function(key) {\n\t\t\treturn operation(key, model, property, config[key]);\n\t\t});\n\t}",
"function matches(property, config, model) {\n\t\t\treturn listVerdict(Object.keys(config), function(key) {\n\t\t\t\treturn operation(key, model, property, config[key]);\n\t\t\t});\n\t\t}",
"function hasSamePropertiesValue(properties1, properties2) {\n for (var property in properties1) {\n if (properties1.hasOwnProperty(property)) {\n if (properties1[property] !== properties2[property]) return false;\n }\n }\n\n return true;\n }",
"hasProperty(aProperty){\n for(let i = 0; i < this._properties.length; i++){\n let prop = this._properties[i];\n if(aProperty.matches(prop)){\n return true;\n }\n }\n return false;\n }",
"function CfnTargetGroup_HealthCheckConfigPropertyValidator(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('enabled', cdk.validateBoolean)(properties.enabled));\n errors.collect(cdk.propertyValidator('healthCheckIntervalSeconds', cdk.validateNumber)(properties.healthCheckIntervalSeconds));\n errors.collect(cdk.propertyValidator('healthCheckTimeoutSeconds', cdk.validateNumber)(properties.healthCheckTimeoutSeconds));\n errors.collect(cdk.propertyValidator('healthyThresholdCount', cdk.validateNumber)(properties.healthyThresholdCount));\n errors.collect(cdk.propertyValidator('matcher', CfnTargetGroup_MatcherPropertyValidator)(properties.matcher));\n errors.collect(cdk.propertyValidator('path', cdk.validateString)(properties.path));\n errors.collect(cdk.propertyValidator('port', cdk.validateNumber)(properties.port));\n errors.collect(cdk.propertyValidator('protocol', cdk.validateString)(properties.protocol));\n errors.collect(cdk.propertyValidator('unhealthyThresholdCount', cdk.validateNumber)(properties.unhealthyThresholdCount));\n return errors.wrap('supplied properties not correct for \"HealthCheckConfigProperty\"');\n}",
"function CfnDataSource_AuthorizationConfigPropertyValidator(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('authorizationType', cdk.requiredValidator)(properties.authorizationType));\n errors.collect(cdk.propertyValidator('authorizationType', cdk.validateString)(properties.authorizationType));\n errors.collect(cdk.propertyValidator('awsIamConfig', CfnDataSource_AwsIamConfigPropertyValidator)(properties.awsIamConfig));\n return errors.wrap('supplied properties not correct for \"AuthorizationConfigProperty\"');\n}",
"function checkSameProps(properties, qParams, model) {\n var result = INCLUDE;\n\n _.each(properties, function(property) {\n if (_.has(qParams, property) && qParams[property] !== model.get(property)) {\n result = EXCLUDE;\n }\n });\n\n return result;\n }",
"function CfnStreamingDistributionPropsValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('streamingDistributionConfig', cdk.requiredValidator)(properties.streamingDistributionConfig));\n errors.collect(cdk.propertyValidator('streamingDistributionConfig', CfnStreamingDistribution_StreamingDistributionConfigPropertyValidator)(properties.streamingDistributionConfig));\n errors.collect(cdk.propertyValidator('tags', cdk.requiredValidator)(properties.tags));\n errors.collect(cdk.propertyValidator('tags', cdk.listValidator(cdk.validateCfnTag))(properties.tags));\n return errors.wrap('supplied properties not correct for \"CfnStreamingDistributionProps\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Represents a strategy that validates the configuration (post loading). | function ValidateClientConfigStrategy () {
} | [
"function Strategy() {\n passport.Strategy.call(this);\n this.name = 'requireuser';\n}",
"constructor(strategy) {\n /**\n * @type {Strategy} The Context maintains a reference to one of the Strategy\n * objects. The Context does not know the concrete class of a strategy. It\n * should work with all strategies via the Strategy interface.\n */\n this.strategy = strategy;\n }",
"_validateConfig() {\n if (!Array.isArray(this.options.configGroups)) {\n throw new Error('options.configGroups is not an array');\n } else if (!this.options.configGroups.length) {\n throw new Error('options.configGroups must have at least one config object');\n }\n // checking fields which MUST be specified in configGroups. (Only one as of now :D)\n const mustInclude = ['targetXPath'];\n this.options.configGroups.forEach((group) => {\n mustInclude.forEach((field) => {\n // eslint-disable-next-line no-prototype-builtins\n if (!group.hasOwnProperty(field)) {\n throw new Error(`${field} must be specified in all configs in options.configGroups`);\n }\n });\n });\n // type checks for crucial fields\n // expected types for crucial fields in the config\n // may do type checking for all fields in the future but it's just not necessary as of now\n const expectedTypes = {\n targetXPath: 'string',\n renderToPath: 'string',\n urlMatch: 'string',\n };\n this.options.configGroups.forEach((group) => {\n Object.keys(expectedTypes).forEach((key) => {\n // eslint-disable-next-line no-prototype-builtins\n if (group.hasOwnProperty(key) && (typeof group[key] !== typeof expectedTypes[key])) {\n throw new Error(`${key} must be of type ${expectedTypes[key]}`);\n }\n });\n });\n // check correct factorization\n this.options.configGroups.forEach((group) => {\n Object.keys(group).forEach((key) => {\n if (this._propsNotInConfigGroup.indexOf(key) >= 0) {\n throw new Error(`${key} is not a property of a configGroup. Specify this key at the outermost layer`);\n }\n });\n });\n // if control reaches this point, the config is acceptable. It may not be perfect since the checks\n // are pretty loose, but at least the crucial parts of it are OK. May add more checks in the future.\n }",
"function Strategy() {\n }",
"configIsValid(config) {\n return true;\n }",
"getValidationConfig() {\n const validator = _validator.get(this);\n const message = _message.get(this);\n return {\n validator,\n message,\n };\n }",
"function Strategy() {\n}",
"register (name, strategy) {\n // Call the functions a strategy can implement\n if (typeof strategy.setName === 'function') {\n strategy.setName(name);\n }\n\n if (typeof strategy.setApplication === 'function') {\n strategy.setApplication(this.app);\n }\n\n if (typeof strategy.setAuthentication === 'function') {\n strategy.setAuthentication(this);\n }\n\n if (typeof strategy.verifyConfiguration === 'function') {\n strategy.verifyConfiguration();\n }\n\n // Register strategy as name\n this.strategies[name] = strategy;\n }",
"getStrategy(config) {\r\n return Object(_spartacus_core__WEBPACK_IMPORTED_MODULE_3__[\"resolveApplicable\"])(this.renderStrategies, [config]);\r\n }",
"async validate() {\n\t\tconst {name, validate} = this.config;\n\t\tif (isFunction(validate)) {\n\t\t\tconst {options, env} = this.generator;\n\t\t\tconst input = options[name];\n\t\t\tlet result = await validate(input);\n\t\t\tif (!result) result = `Invalid ${name} option '${input}'`;\n\t\t\tif (isString(result)) env.error(result);\n\t\t}\n\t}",
"async strategyAccessibleRequired(ctx, next) {\n const { service: { mysql } } = ctx;\n if (!ctx.checkPossibleParams(['strategyId'])) {\n return;\n }\n\n const strategyId = ctx.query.strategyId || ctx.request.body.strategyId;\n const strategy = await mysql.getStrategyById(strategyId);\n if (!strategy) {\n return ctx.authFailed(404, '规则不存在');\n }\n\n const { userId } = ctx.user;\n const [owner, member] = await ctx.checkAppMember(strategy.app, userId);\n if (!owner && !member) {\n return ctx.authFailed(403, '您没有此规则的访问权限');\n }\n ctx.strategy = strategy;\n\n await next();\n }",
"constructor() {\n super(...arguments);\n this.name = this.args.validation;\n this.parent = this.args.parent;\n\n if (this.args.parent === undefined) {\n if (this.args.alone) return; // if input is alone ignore\n\n throw new ConfigurationException(`Component '${this.constructor.name}' needs to have a 'BaseValidationFormComponent' instance as '@parent' , if you want this component without validation and parent use '@alone={{true}}' as argument to the input. Note that the validate() method will throw an error if called`);\n }else{\n if (this.parent.state.validationSchema === undefined) {\n throw new ConfigurationException(`Component '${this.constructor.name}' needs to have a 'BaseValidator' instance as '@schema' , if you want this component without validation and parent use '@alone={{true}}' as argument to the input. Note that the validate() method will throw an error if called`);\n }\n }\n\n if (!this.args.value && !this.args.selected) {\n // eslint-disable-next-line no-console\n console.warn(`Component '${this.constructor.name}' seems to have an undefined @validation attribute`);\n }\n\n if (!this.args.validation) {\n throw new ConfigurationException(`Component '${this.constructor.name}' needs to have a '@validation' attribute , if you want this component without validation and parent use '@alone={{true}}' as argument to the input. Note that the validate() method will throw an error if called`);\n }\n\n this.parent.registerChild(this);\n }",
"getStrategy(config) {\n return resolveApplicable(this.renderStrategies, [config]);\n }",
"function Strategy(options, verify) {\n if (typeof options == 'function') {\n verify = options;\n options = {};\n }\n if (!verify) throw new Error('freepbx authentication strategy requires a verify function');\n this._usernameField = options.usernameField || 'username';\n this._passwordField = options.passwordField || 'password';\n\n passport.Strategy.call(this);\n this.name = 'freepbx-auth';\n this.verify = verify;\n}",
"function Strategy(options) {\n samlOptions = {\n entryPoint: shibboleth2.idp_entrypoint,\n identifierFormat: null,\n issuer: shibboleth2.entityId || shibboleth2.domain,\n callbackUrl: 'https://' + shibboleth2.domain + options.callbackUrl,\n decryptionPvk: privateKey,\n privateCert: privateKey,\n acceptedClockSkewMs: 180000,\n forced: options.forced,\n passive: options.passive\n };\n\n function verify(profile, done) {\n if (!profile)\n return done(new Error('Empty SAML profile returned!')); \n else { \n user = convertProfileToUser(profile);\n if (user) {\n if (\"authz\" in options) {\n authz = options[\"authz\"](user);\n if (!authz.status) {\n return done(null, false, { message: authz.message });\n }\n }\n }\n return done(null, user);\n } \n }\n saml.Strategy.call(this, samlOptions, verify);\n this.name = strategyName;\n}",
"function OktaConfigurationStrategy() {\n\n}",
"function Configuration() {\n Testable.call(this);\n}",
"function UserStrategy(config){\n var SecurityInfo = config.SecurityInfo;\n\n this.getUser = function(params,callback){\n callback(null,null);\n };\n this.listUsers = function(params,callback){\n callback(null,null);\n };\n this.initiateAuth = function(params,callback){\n callback(null,null);\n };\n this.globalSignOut = function(params,callback){\n callback(null,null);\n };\n this.signUp = function(params,callback){\n callback(null,null);\n };\n this.confirmSignUp = function(params,callback){\n callback(null,null);\n };\n this.forgotPassword = function(params,callback){\n callback(null,null);\n };\n this.updateUserAttributes = function(params,callback){\n callback(null,null);\n };\n this.adminConfirmSignUp = function(params,callback){\n callback(null,null);\n };\n this.adminUpdateUserAttributes = function(params,callback){\n callback(null,null);\n };\n this.adminGetUser = function(params,callback){\n callback(null,null);\n };\n\n}",
"function Strategy()\r\n\t{\r\n\t\tvar _strategyChoices = new Object; \r\n\t\tthis.strategyChoices = _strategyChoices;\r\n\t\t\r\n\t\tvar _strategyChoicesCount = 0;\r\n\t\tthis.strategyChoicesCount = _strategyChoicesCount;\r\n\t\t\r\n\t\tvar name = \"\";\r\n\t\tvar key = \"\";\r\n\t\tvar value = \"\";\r\n\t\tvar seq = 0;\r\n\t\tvar _visible = true;\r\n\t\tvar _color = null;\r\n\t\t\r\n\t\tthis.name = name;\r\n\t\tthis.key = key;\r\n\t\tthis.value = value;\r\n\t\tthis.seq = seq;\r\n\t\tthis.visible = _visible;\r\n\t\tthis.color = _color;\r\n\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the CBT by connecting at 1200 baud | function reset(){
var oldBaudRate = baudRate;
baudRate = 1200;
close()
.then(open)
.then(close)
.then(function(){
baudRate = oldBaudRate;
open();
$timeout(function(){
$rootScope.$broadcast('SerialService.RESET' );
}, 500);
});
} | [
"function re_connectSerial(){ \n setTimeout(function(){\n connectSerial();\n }, 2000);\n }",
"function resetDevice()\n{\n sendMidi(0xB0, 0, 0);\n\n for(var i=0; i<80; i++)\n {\n pendingLEDs[i] = 0;\n }\n flushLEDs();\n}",
"function reset_settings()\n {\n setTimeout(() =>\n {\n port.write('\\n');\n //reset time/div\n setTimeout(() => {\n port.write('11200\\n');\n }, 100);\n //port.write('11200\\n');\n acquisition_period = 0.00005;\n time_div_.innerText = \"1 ms/div\";\n reductor_index = 0;\n\n //reset volt/div\n btn_volt_div_.innerText = \"1 V/div\";\n setTimeout(() => {\n port.write('21000\\n');\n }, 200);\n //port.write('21000\\n');\n gain = 1;\n v_ref = mid_screen;\n trigger_lvl = mid_screen;\n \n //sends V_ref to uC\n setTimeout(() => {\n port.write('3'+('000' + Math.round(v_ref+adjust_v_ref)).substr(-4)+'0\\n');\n }, 300);\n //port.write('3'+('000' + Math.round(v_ref+adjust_v_ref)).substr(-4)+'0\\n');\n //reset trigger\n trigger_status = 0;\n btn_trigger_.innerText = \"Trigger: OFF\";\n config_file_check();\n }, 2000);\n \n }",
"Serial(port, baud, timeout) {\n }",
"function alarmSetBaudRate(speed) {\n // setup and send baud rate command\n // 0=9600, 1=19200, 2=38400, 3=57600, 4=115200\n\n var cmd = \"080\";\n if (speed == \"9600\") {\n cmd = cmd + \"0\";\n }\n else if (speed == \"19200\") {\n cmd = cmd + \"1\";\n }\n else if (speed == \"38400\") {\n cmd = cmd + \"2\";\n }\n else if (speed == \"57600\") {\n cmd = cmd + \"3\";\n }\n else if (speed == \"115200\") {\n cmd = cmd + \"4\";\n }\n else // By default set to 9600 \n {\n cmd = cmd + \"0\";\n } \n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function reset(wifi, creds, timeouts){\n // when the wifi chip resets, it will automatically try to reconnect\n // to the last saved network\n wifi.reset(function(){\n if (timeouts){ timeouts = 0 }\n console.log(\"done power cycling\")\n\n // give it some time to auto reconnect\n setTimeout(function(){\n if (!wifi.isConnected()) {\n // try to reconnect\n reConnect(wifi, creds)\n }\n }, 12000) // wait 12 sec\n })\n\n console.log(resetting)\n}",
"resetBtc() {\n this.balance = 0;\n }",
"function btInit() {\r\n networking.bluetooth.disable(function () {\r\n console.log(\"Bluetooth disabled by Init\");\r\n }, function () {\r\n console.log(\"Error: Disabling Bluetooth by Init failed\");\r\n });\r\n\r\n window.setTimeout(function () {\r\n networking.bluetooth.enable(function () {\r\n console.log(\"Bluetooth enabled by Init\");\r\n }, function () {\r\n console.log(\"Error: Enabling Bluetooth by Init failed\");\r\n });\r\n }, 5000);\r\n\r\n for (i = 1; i <= 12; i++) {\r\n networking.bluetooth.close(i);\r\n }\r\n}",
"function rebootMcu() {\n \tportWrite('MCU BOOT_SYSTEM');\n}",
"blinkLED() {\n var blinkDuration = 1500;\n var led = this.onboardLED;\n led.write(1);\n setTimeout(function() {\n led.write(0);\n }, blinkDuration );\n }",
"async reset_mcu() {\n const reset_program = new Uint8Array([\n 0x01, 0x4a, 0x02, 0x4b, 0x1a, 0x60, 0x70, 0x47,\n 0x04, 0x00, 0xfa, 0x05, 0x0c, 0xed, 0x00, 0xe0\n ]);\n\n await this.send_command('W ' + this.RAM_ADDRESS + ' ' + reset_program.length);\n await this.uart.write(reset_program);\n\n // Unlock the Go command\n await this.send_command('U 23130');\n\n // Run the isp_program from RAM. Note that this command does not respond with\n // COMMAND_SUCCESS as it directly executes.\n await this.uart.write('G ' + this.RAM_ADDRESS + ' T\\r\\n');\n }",
"function bt_OnConnect(ok) {\n if (!ok) {\n console.log(\"BT ERROR!\");\n bt.Connect(\"HC-05\"); // Try to reconnect again\n } else if (ok)\n console.log(\"BT Successful\");\n}",
"reset() {\n var signalState = this.peerConnection.signalingState;\n if (this._send_channel !== null && this._send_channel.readyState === \"open\") {\n this._send_channel.close();\n }\n if (this.peerConnection !== null) this.peerConnection.close();\n if (signalState !== \"stable\") {\n setTimeout(() => {\n this.connect();\n }, 3000);\n } else {\n this.connect();\n }\n }",
"function setBaudrate(_baudrate) {\n // TODO: Check the supplied baudrate value to ensure that it is reasonable\n // Set the global baudrate variable\n baudrate = _baudrate;\n}",
"function serialInit (callback) {\n console.log(\"------->3\");\n serialList(function(portName) {\n if (portName == '') {\n console.log('Serial port not found...');\n callback(-1);\n return;\n }\n // console.log('Serial port name ->',portName);\n var sPort = new serialPort(portName, {\n // baudrate: 115200,\n baudrate: 9600,\n autoOpen: false,\n //autoOpen: true\n }); // this is the openImmediately flag [default is true]\n \n sPort.open();\n\n sPort.on('open', function() {\n console.log(portName, 'baudrate ->', sPort.options.baudRate);\n callback(sPort);\n }); \n\n sPort.on(\"close\", function () {\n console.log('Serial port closed...',portName);\n });\n\n sPort.on('error', function(err) {\n console.log(err);\n });\n\n var tempBuff = '';\n var endLine = -1;\n\n sPort.on(\"data\", function (_data) {\n var data = _data+'';\n endLine = data.indexOf('\\n');\n // console.log('Temp-data ->',data, endLine);\n if (endLine == -1) { \n tempBuff += data;\n }\n else {\n // data = data.split('\\u0000').join('');\n var sportBuff = tempBuff+data;\n tempBuff = '';\n console.log('Recive-data-Arduino--->',sportBuff);\n SaveTemp(sportBuff);\n if (sPort != null) {\n // var text = 'R';\n // writeSerialPort(sPort, text, function() { \n // console.log('Send-dataArduino----->', text);\n // })\n }\n }\n }); \n })\n}",
"function powerCycle() {\n // when the wifi chip resets, it will automatically try to reconnect\n // to the last saved network\n wifi.reset(function() {\n timeouts = 0; // reset timeouts\n console.log(\"done power cycling\");\n // give it some time to auto reconnect\n setTimeout(function() {\n if (!wifi.isConnected()) {\n // try to reconnect\n connect();\n }\n }, 20 * 1000); // 20 second wait\n })\n}",
"function resetBlinkingLed(){\n if (ledBlinking) {\n led.stop();\n ledBlinking = false;\n }\n }",
"async function hardreset(){\n\n // trigger reset\n await _nodeMcuConnector.hardreset(_options.device);\n\n // log\n _mculogger.log('Hard-Reset executed (100ms)');\n}",
"constructor() {\n this.init = new Buffer([0x03, 0x03, 0x03, 0x02, 0x28, 0x0c, 0x01, 0x06]);\n this.LCD_LINE1 = 0x80;\n this.LCD_LINE2 = 0xc0;\n this.LCD_ENABLE = 0x04;\n this.LCD_BACKLIGHT = 0x08;\n\n rpio.i2cBegin();\n rpio.i2cSetSlaveAddress(0x27);\n rpio.i2cSetBaudRate(10000);\n\n for (let i = 0; i < this.init.length; i++) {\n this.sendChar(this.init[i], 0);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
N is a variable for storing the length of input string bubblesortstr is a user defind fucntion which takes the original string and sort it | function bubblesortstr(string1) {
var N = string1.length;
array1 = string1.split("");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (array1[j + 1] < array1[j]) // comparing the adjacent element
{
temp = array1[j + 1];
array1[j + 1] = array1[j]; // interchanging the element
array1[j] = temp;
}
}
}
console.log(array1); // prinring the sorted array
return "";
} | [
"insertionSortForString(n, arr) {\n\n var temp;\n var j;\n\n for (i = 1; i <= n; i++) {\n temp = arr[i];\n j = i - 1;\n while (temp < arr[j] && j >= 0) {\n arr[j + 1] = arr[j];\n j = j - 1;\n }\n arr[j + 1] = temp;\n\n }\n\n console.log(\"Strings are sort = \" + arr);\n\n\n }",
"bubbleSortForString(size) {\n try {\n if (isNaN(size && arr)) {\n /** \n * Initialize arr\n * \n */\n var arr = [];\n for (let i = 0; i < size; i++) {\n arr[i] = readline.question(\"enter the array elements\");\n }\n /** \n * To display array elements\n */\n console.log(\"The array elements are : \" + arr);\n /** \n * find length of arr and store the result in n\n */\n var n = arr.length;\n for (let i = 0; i < n; i++) {\n for (j = i + 1; j < n; j++) {\n /** \n * condition to caompare the adjacent elements\n */\n if ((arr[i]) > (arr[j])) {\n /**\n * swapping their positions\n */\n var temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n }\n /** \n * To display the array elements\n */\n console.log(\"the sorted elements are : \" + arr);\n }\n /**\n * ask the user to enter valid input\n */\n else {\n console.log(\"enter valid input\");\n }\n }\n /**\n * to display an error message\n */\n catch (exception) {\n console.log(err);\n }\n }",
"bubbleSortStr(num) {\n try {\n var arr = [];\n for (let i = 0; i < num; i++) {\n arr[i] = readline.question(\"Enter the element :\");\n /**\n * \n * Loop over till array size is equal to userinput and\n * take the user input elements and push it to array.\n * \n *\n */\n }\n for (let i = 0; i < arr.length; i++) {\n for (let j = i + 1; j < arr.length; j++) {\n /**\n * Loop over till array length and compare the values .\n */\n if ((arr[i]) > (arr[j])) {\n /**\n * swap temp and arr[i]\n */\n var temp = arr[i];\n arr[i] = arr[j]\n arr[j] = temp\n }\n }\n }\n console.log(arr);\n\n } catch (error) {\n console.log(error.message);\n\n }\n }",
"function sortByLength(strs) {\n \n for (let i = 0; i < strs.length; i++) {\n \n for (let j = 0; j < strs.length-1; j++) {\n let firstStrIndex = j;\n let secondStrIndex = j + 1;\n\n let firstNumLen = strs[firstStrIndex].length\n let secondNumLen = strs[secondStrIndex].length\n\n if (firstNumLen === secondNumLen) {\n j++;\n\n } else if (firstNumLen > secondNumLen) {\n let temp = strs[firstStrIndex];\n strs[firstStrIndex] = strs[secondStrIndex];\n strs[secondStrIndex] = temp;\n j++;\n } \n }\n }\n return strs;\n}",
"function sortByLength(strs) {\n let sortedArray = \n strs.sort((sortedArray, valueLength) => {return sortedArray.length - valueLength.length})\n return sortedArray;\n}",
"function sort_by_string_length(arr) {\n for (let i = 0; i < arr.length; i++) {\n for (let j = i+1; j < arr.length; j++) {\n if (arr[i].length > arr[j].length) {\n const m = arr[i];\n arr[i] = arr[j];\n arr[j] = m;\n // đảo chỗ 2 val của mảng\n // console.log(m, arra[i], arra[j]);\n // xyz aa xyz\n // aa aa\n // acd bb acd\n // bb a bb\n // xyz aa xyz\n // aa b aa\n // acd bb acd\n // zzz aa zzz\n }\n }\n }\n return arr;\n}",
"function sortString(str) {\n // @TODO\n}",
"function sortLength(strArray){\n return strArray.sort((a,b) => a.length - b.length);\n}",
"function poresort()\r\n{\r\n // Before we begin, assume that the string is currently sorted\r\n poresortHasFinished = true;\r\n\r\n // iterate through each even pair in the string\r\n for (let index = 0; index + 1 < stringToBeSorted.length; index += 2)\r\n {\r\n // If we need to swap characters, then swap characters. And indicate that another iteration of poresort may be necessary.\r\n if (poresortString[index] > poresortString[index + 1])\r\n {\r\n poresortString = swapCharacters(poresortString, index, index + 1);\r\n poresortHasFinished = false;\r\n }\r\n }\r\n \r\n // iterate through each odd pair in the string\r\n for (let index = 1; index + 1 < stringToBeSorted.length; index += 2)\r\n {\r\n // If we need to swap characters, then swap characters. And indicate that another iteration of poresort may be necessary.\r\n if (poresortString[index] > poresortString[index + 1])\r\n {\r\n poresortString = swapCharacters(poresortString, index, index + 1);\r\n poresortHasFinished = false;\r\n }\r\n }\r\n}",
"function sortLetters(inputString) {\n\t// your code goes here\n}",
"function sort_string(string){\n var stringArray = string.toLowerCase().split(' '); //lowercased array of strings separated by commas\n var sortedArray = stringArray.sort(function(a,b){\n return (a.length - b.length);\n });\n console.log(sortedArray);\n}",
"function sortLetters(inputString) {\n\t// your code goes here\n\tif (typeof inputString !== \"string\"){\n\t\tthrow \"Invalid Input\"\n\t}\n\n\tvar inputString = inputString.split(\"\");\n\tvar inputString = inputString.sort();\n\tvar inputString = inputString.join(\"\");\n\treturn inputString;\n}",
"function customSort(S, T){\n const sArr = S.split('');\n const tArr = T.split('');\n const result = [];\n\n while(sArr.length > 0){\n let ch = sArr[0];\n let index = tArr.indexOf(ch);\n\n if(index > -1){\n result.push(tArr[index]);\n tArr.splice(index, 1);\n }else{\n sArr.shift();\n }\n }\n\n result.push(...tArr);\n return result.join('');\n}",
"function alphabetSoup(str) {\n inputStr = \"yellow pillow\";\n // get input string letters and assign it to index of alphStr\n inputArr = inputStr.split(\"\");\n inputArr.sort();\n inputArr.join();\n \n\n\n\n}",
"function sortLetters(inputString) {\n if (typeof inputString === \"string\") {\n arrayString = inputString.split(\"\");\n console.log(arrayString);\n sortedString = arrayString.sort();\n return sortedString.join(\"\");\n } else {\n throw new Error(\"Invalid input provided! Not a string!\");\n }\n}",
"function sortIt (str) {\n // Array to store the letters as numbers.\n var numbers = []\n\n // First translate each letter into a number. Not the ascii number though\n // a better way for doing capital/lowercase sort.\n for (var i = 0; i < str.length; i++) {\n var code = str.charCodeAt(i)\n // Capitals are translated to 1, 3, 5, ... using 2X - 129\n // Lowercase are translated to 2, 4, 6, ... using 2X - 192\n var shift = (code <= 90) ? 129 : 192\n numbers.push(2 * code - shift)\n }\n\n numbers.sort(function (a, b) { return a - b })\n\n var output = ''\n numbers.forEach(function (it) {\n // Even means capital so we inverse the math done above with 129\n // Odd means lowercase so we inverse the math done above with 192\n var shift = (it % 2) ? 129 : 192\n output += String.fromCharCode((it + shift) / 2)\n })\n\n return output\n}",
"function shorterString(string1, string2, string3, string4, string5) {\r\n let strings = [string1, string2, string3, string4, string5];\r\n return console.log(strings.sort((a, b) => a.length - b.length)[0]);\r\n}",
"function sortString(str)\n{\n return str.split('').sort().join('');\n}",
"function sortByLength(strings) {\n const stringClone = [...strings];\n\n stringClone.sort((a, b) => a.length - b.length);\n\n // stringClone.sort(function(a, b) {\n // return a.length - b.length;\n // });\n return stringClone;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads usage data for the given timeframe and format. | async fetchUsages(timeframe, format) {
const url = this.createUrlBuilder()
.setFileType("txt" /* TEXT */)
.setTimeframe(timeframe)
.setFormat(format)
.build();
return usages_1.usageFromString(await this.request(url, "txt" /* TEXT */));
} | [
"async loadPerformanceHistory() {\n let rawFile = null;\n try {\n rawFile = await fse.readFile(this.hardConfigs.heatmapDataFile, 'utf8');\n } catch (error) { }\n\n const setFile = async () => {\n try {\n await fse.writeFile(this.hardConfigs.heatmapDataFile, '[]');\n this.perfSeries = [];\n } catch (error) {\n console.error(`Unable to create stats_heatmapData_v1 with error: ${error.message}`);\n process.exit();\n }\n };\n\n if (rawFile !== null) {\n try {\n const heatmapData = JSON.parse(rawFile);\n if (!Array.isArray(heatmapData)) throw new Error('data is not an array');\n if (!validatePerfCacheData(heatmapData)) throw new Error('invalid data in cache');\n this.perfSeries = heatmapData.slice(-this.hardConfigs.performance.lengthCap);\n } catch (error) {\n console.warn(`Failed to load stats_heatmapData_v1 with message: ${error.message}`);\n console.warn('Since this is not a critical file, it will be reset.');\n await setFile();\n }\n } else {\n await setFile();\n }\n }",
"function loadHistoricalData() {\n if (dailyTimer) clearInterval(dailyTimer);\n dailyTimer = setInterval(loadDailyStats, 180000);\n loadDailyStats();\n\n loader.transition().style('opacity',1);\n status.html(\"\");\n\n var end = moment().utc().endOf('day');\n var start = moment().utc().startOf('day').subtract(1,'day');\n\n if (self.request) self.request.abort();\n self.request = apiHandler.offersExercised({\n endTime : end.format(),\n startTime : start.format(),\n reduce : false,\n base : self.base,\n counter : self.counter,\n descending : true,\n limit : 60\n\n }, function(data){\n\n loader.transition().style('opacity',0);\n\n data.forEach(function(d) {\n d.amount = valueFilter(d.amount, 8);\n d.price = valueFilter(d.price, 5);\n transactions.push(d);\n });\n\n transactions = transactions.slice(0,60);\n updateTrades();\n\n }, function (error){\n\n if (!transactions.length) //trades may have come through the live feed\n status.html(error.text ? error.text : \"Unable to load data\");\n\n loader.transition().style('opacity',0);\n console.log(error);\n });\n }",
"async fetchFormats(timeframe, useMonotype = false) {\n const urlBuilder = this.createUrlBuilder();\n urlBuilder.setTimeframe(timeframe);\n if (useMonotype) {\n urlBuilder.setSubPath(\"monotype\" /* MONOTYPE */);\n }\n const url = urlBuilder.build();\n return formats_1.parseFormatsPage(await this.request(url, \"txt\" /* TEXT */));\n }",
"function loadHistoricalData(){\n\ttry{\n\t\tconsole.log(\"Loading Historical Data\");\n\n\t\tlet data = String(fs.readFileSync(historicalData));\n\t\tlet lines = data.split(\"\\n\"); //downloaded from yahoo finance\n\t\tlines.shift();\n\t\tlines.forEach((line) => {\n\t\t\tlet splitData = line.split(',');\n\t\t\tlet tempObj = {\n\t\t\t\topen: splitData[1],\n\t\t\t\tclose: splitData[4]\n\t\t\t};\n\t\t\tindex[splitData[0]] = tempObj;\n\t\t});\n\n\t\tconsole.log(\"Historical Data Loaded Successfully\");\n\t\tconsole.log(lineBreak);\n\n\t}catch(err){\n\t\tconsole.error(err);\n\t}\n}",
"async parseData(forecastHour, filePath) {\n this.data[forecastHour] = {};\n\n const capeData = await DataSource.parseGribFile(filePath, {\n category: 7, // Grib2 category number, equals to --fc 1\n parameter: 6, // Grib2 parameter number, equals to --fp 7\n surfaceType: 1, // Grib2 surface type, equals to --fs 103\n //surfaceValue: 10, // Grib2 surface value, equals to --fv 10\n }, GfsDataSource.parseGfsBody);\n\n const windUData = await DataSource.parseGribFile(filePath, {\n category: 2, // Grib2 category number, equals to --fc 1\n parameter: 2, // 2 U-wind, 3 V-wind, 192 Vert speed sheer\n surfaceType: 100, // Isobar surface\n surfaceValue: 100000,\n }, GfsDataSource.parseGfsBody);\n\n const windVData = await DataSource.parseGribFile(filePath, {\n category: 2, // Grib2 category number, equals to --fc 1\n parameter: 3, // 2 U-wind, 3 V-wind, 192 Vert speed sheer\n surfaceType: 100, // Isobar surface\n surfaceValue: 100000,\n }, GfsDataSource.parseGfsBody);\n\n const tempData = await DataSource.parseGribFile(filePath, {\n category: 0,\n parameter: 0,\n }, GfsDataSource.parseGfsBody);\n\n const vortexData = await DataSource.parseGribFile(filePath, {\n category: 2,\n parameter: 10,\n surfaceType: 100,\n surfaceValue: 10000,\n }, GfsDataSource.parseGfsBody);\n\n this.data[forecastHour] = {\n cape: capeData[0],\n windU: windUData[0],\n windV: windVData[0],\n temperature: tempData[0],\n vorticity: vortexData[0],\n };\n }",
"function loadData(item) {\n var temp_labels = [];\n $http.get('https://www.quandl.com/api/v3/datasets/WIKI/'+item+'/metadata.json?api_key=RHczh31e48Xd6yRtSHvS')\n .success(function (metadata) {\n $http.get('https://www.quandl.com/api/v3/datasets/WIKI/'+item+'/data.json?start_date=2015-01-01&order=asc&collapse=weekly&column_index=4&api_key=RHczh31e48Xd6yRtSHvS')\n .success(function(data) {\n // received data since start of 2015\n\n var stock_prices = [];\n data.dataset_data.data.forEach(function (element, index, array) {\n var str= element[0];\n var dateArray = str.split('-');\n var newDate = dateArray[1]+\"/\"+dateArray[2];\n $scope.year = dateArray[0];\n\n temp_labels.push(newDate);\n stock_prices.push(element[1]);\n });\n $scope.data.push(stock_prices);\n $scope.labels = temp_labels;\n var str = metadata.dataset.name;\n str = str.substr(0,str.indexOf('(',0)); // extract out just the company name\n\n $scope.series.push(str);\n $scope.symbols.push(item);\n// window.dispatchEvent(new Event('resize'));\n });\n});\n }",
"function loadDataForByHour() {\r\n\tvar dateRange_value = 'where[full_date.between]='\r\n\t\t\t+ urlMaster.getParam('where[full_date.between]');\r\n\tvar url = apiRootUrl\r\n\t\t\t+ '/revenueByHour?select=full_date|hour24_of_day&limit=2000&'\r\n\t\t\t+ dateRange_value + \"&by=pais|pid\";\r\n\tif (myAjaxStore.isLoading(url)) {\r\n\t\treturn;\r\n\t}\r\n\tvar ajaxData = myAjaxStore.get(url);\r\n\tif (ajaxData == null) {\r\n\t\tmyAjaxStore.registe(url);\r\n\t\t$.ajax({\r\n\t\t\tdataType : \"json\",\r\n\t\t\turl : url,\r\n\t\t\ttimeout : ajaxRequestTimeout,\r\n\t\t\txhrFields : {\r\n\t\t\t\twithCredentials : true\r\n\t\t\t},\r\n\t\t\tsuccess : function(json) {\r\n\t\t\t\tmyAjaxStore.add(url, json);\r\n\t\t\t},\r\n\t\t\terror : function(xhr, status, error) {\r\n\t\t\t\tmyAjaxStore.remove(url);\r\n\t\t\t},\r\n\t\t\tcomplete : function() {\r\n\r\n\t\t\t}\r\n\r\n\t\t});\r\n\t} else {\r\n\t}\r\n}",
"function loadStats() {\n if (statsPath == undefined) return\n if (existsSync(statsPath)) {\n try {\n stats = JSON.parse(readFileSync(statsPath).toString())\n return\n } catch (e) {\n error(\"Failed to read \", e)\n }\n }\n\n if (existsSync(statsPath + \".old\")) {\n try {\n stats = JSON.parse(readFileSync(statsPath + \".old\").toString())\n log(\"Recovered stats from old file\")\n return\n } catch (e) {\n error(\"Failed to read old file \", e)\n }\n }\n\n stats = {\n \"startDate\": new Date().getTime()\n }\n}",
"function loadData(){\n\td3.queue()\n\t\t.defer(d3.csv,\"public/locationsinter.csv\", parseLocations) //locations_nest\n .defer(d3.csv,\"public/res3.csv\", parseSamples)\n .await(callbackDataLoaded)\n}",
"function loadDataForByHour(){\r\n \t\tvar dateRange_value='where[full_date.between]='+urlMaster.getParam('where[full_date.between]');\r\n \t\tvar url=apiRootUrl+'/revenueByHour?select=full_date|hour24_of_day&limit=2000&'+dateRange_value+\"&by=pais|pid\";\r\n \t\tif(myAjaxStore.isLoading(url)){\r\n\t\t\treturn;\r\n\t\t}\r\n \t\tvar ajaxData=myAjaxStore.get(url);\r\n\t\tif(ajaxData==null){\r\n\t\t\tmyAjaxStore.registe(url);\r\n\t\t\t$.ajax({\r\n\t\t\t\tdataType: \"json\",\r\n\t\t\t\turl: url,\r\n\t\t\t\ttimeout: ajaxRequestTimeout,\r\n\t\t\t\txhrFields: {\r\n\t\t\t\t\t withCredentials: true\r\n\t\t\t\t},\r\n\t\t\t\tsuccess: function(json){\r\n\t\t\t\t\t myAjaxStore.add(url,json);\r\n\t\t\t\t},\r\n\t\t\t\terror: function(xhr,status,error){\r\n\t\t\t\t\tmyAjaxStore.remove(url);\r\n\t\t\t\t},\r\n\t\t\t\tcomplete: function(){\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t \r\n\t\t\t\t});\t\t\t\r\n\t\t}else{\r\n\t\t}\r\n \t}",
"function loadUsageData() {\n\tvar data = null;\n\tif(localStorage['cacheTime']) {\n\t\tvar curTime = (new Date()).getTime();\n\t\tvar minutes = (curTime - localStorage['cacheTime'])/1000/60;\n\t\tif(minutes <= 30) {\n\t\t\tdata = window.JSON.parse(localStorage['cache']);\n\t\t} \n\t}\n\treturn data;\n}",
"getUsage(usageList, dateFormatted) {\n // will remove when db stops storing values with attached string.\n var todaysDate = dateFormatted + 'T00:00:00.000Z';\n var i, usageObj;\n for (i=0; i<usageList.length; i++) {\n usageObj = usageList[i];\n if (usageObj.usageDate === todaysDate) {\n return usageObj;\n }\n }\n return {\n appUsage: [],\n timerUsage: []\n }\n }",
"async fetchMetagame(timeframe, format) {\n const url = this.createUrlBuilder()\n .setSubPath(\"metagame\" /* METAGAME */)\n .setFileType(\"txt\" /* TEXT */)\n .setTimeframe(timeframe)\n .setFormat(format)\n .build();\n return metagame_1.metagameFromString(await this.request(url, \"txt\" /* TEXT */));\n }",
"function loadData(start, end){\n var filter = $('#filter').val();\n if ($.isNumeric(filter) == false){\n filter = 1;\n }\n isNewData = true;\n\n var rest_request_values = \"/stream/getstreamdata?streamid=\"+streamId\n +\"&startdate=\"+start.format('YYYY-MM-DD')\n +\"&enddate=\"+end.format('YYYY-MM-DD')\n +\"&filter=\" + filter;\n\n console.log(start.format('YYYY-MM-DD'))\n console.log(end.format('YYYY-MM-DD'))\n\n var rest_request_info = \"/stream/getstreaminfo?streamid=\"+streamId;\n var rest_request_setting = \"/streams/settings?streamid=\"+streamId+\"&msgtype=\"+messageType;\n\n queue()\n .defer(d3.json, rest_request_values)\n .defer(d3.json, rest_request_info)\n .defer(d3.json, rest_request_setting)\n .awaitAll(handleData);\n}",
"function read_data() {\n fs.readFile('./dates.json', function(err, data) {\n if (err) throw err;\n \n DATE_GRAPH = JSON.parse(data);\n console.log(\"Processed \" + Object.keys(DATE_GRAPH).length + \" dates\");\n });\n}",
"function usageData(startDate, endDate,\n\taccessToken, callback) {\n\tgetConnectionNumber(accessToken, function(err, data){\n\t\tif (!err) {\n\t\t\toauth.get(\n\t\t\t\tapi + \"/v1/usage_data.js?start_date=\" + startDate + \"&end_date=\" + endDate + \"&icp_number=\" + data,\n\t\t\t\taccessToken,\n\t\t\t\toauthAccessSecert,\n\t\t\t\tfunction(err, data) {\n\t\t\t\t\tif (!err) {\n\t\t\t\t\t\tcallback(null, data);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconsole.log('error: ' + JSON.stringify(err));\n\t\t\t\t\t\tcallback(err, null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t);\n\t\t} else {\n\t\t\tconsole.log('error: ' + JSON.stringify(err));\n\t\t\tcallback(err, null);\n\t\t}\n\n\t});\n}",
"function _setDailyUsageChart(usageData) {\n var today = moment().endOf('day');\n var threeMonthsFromNow = moment().subtract(3, 'months').startOf('day');\n var range = moment().range(threeMonthsFromNow, today);\n var dailyUsageData = [];\n var date = threeMonthsFromNow;\n while (range.contains(date)) {\n var data = _.find(usageData, function (item) { return item.date == date.format('YYYY-MM-DD') });\n if (angular.isDefined(data)) {\n data.day = date.format('YYYY-MM-DD');\n data.avg = data.avg;\n dailyUsageData.push(data);\n } else {\n dailyUsageData.push({ date: date.format('YYYY-MM-DD'), avg: 0, day: date.format('YYYY-MM-DD') });\n }\n date = date.add(1, 'day');\n }\n return dailyUsageData;\n }",
"function getNewTimeRangeData (p) {\n //console.log(formatDate(p.start));\n //console.log(formatDate(p.end));\n\n if (p.manual === undefined) {\n //Update timeline graph data too\n p.manual = true;\n getNewTimelineData(p);\n timeline.setWindow(p.start, p.end);\n }\n\n let timeMod = getTimeMod(p.start, p.end);\n let start = formatDate(p.start);\n let end = formatDate(p.end);\n\n /* sensor 1 fetch - fermenter temperature */\n let queryString = \"./sensor1?start=\" + start + \"&end=\" + end + \"&mod=\" + timeMod;\n jQuery.getJSON(queryString, function(sensor1_data, status) {\n if (status == \"success\") {\n let items = [];\n console.log(\"returned \" + sensor1_data.sensor1.length + \" sensor1 entries\");\n sensor1_data.sensor1.forEach(function(entry) {\n if (globals.sensor_cache[sensorEnum.FERMENTER_TEMP][entry.index] === undefined) {\n globals.sensor_cache[sensorEnum.FERMENTER_TEMP][entry.index] = 1;\n\n let item = {};\n //item['id'] = entry.index; --can't use with groups\n item['x'] = entry.timestamp;\n item['y'] = entry.temperature;\n item['group'] = sensorEnum.FERMENTER_TEMP;\n items.push(item);\n }\n });\n if (items.length > 0) {\n dataset.add(items);\n }\n items.length=0; //Tell javascript we are done with this?\n } else {\n console.log(\"Jquery failed to get sensor1 information\");\n }\n });\n\n /* sensor 2 fetch - ambient temperature */\n queryString = \"./sensor2?start=\" + start + \"&end=\" + end + \"&mod=\" + timeMod;\n jQuery.getJSON(queryString, function(sensor2_data, status) {\n if (status == \"success\") {\n let items = [];\n sensor2_data.sensor2.forEach(function(entry) {\n if (globals.sensor_cache[sensorEnum.AMBIENT_TEMP][entry.index] === undefined) {\n globals.sensor_cache[sensorEnum.AMBIENT_TEMP][entry.index] = 1;\n\n let item = {};\n //item['id'] = entry.index; --can't use with groups\n item['x'] = entry.timestamp;\n item['y'] = entry.temperature;\n item['group'] = sensorEnum.AMBIENT_TEMP; //Note different group\n items.push(item);\n }\n });\n if (items.length > 0) {\n dataset.add(items);\n }\n items.length=0; //Tell javascript we are done with this\n } else {\n console.log(\"Jquery failed to get sensor2 information\");\n }\n });\n}",
"function YDataSet_parse(str_json)\n {\n var summaryMinVal = Number.MAX_VALUE;\n var summaryMaxVal = -Number.MAX_VALUE;\n var summaryTotalTime = 0;\n var summaryTotalAvg = 0;\n var loadval = JSON.parse(str_json);\n\n this._functionId = loadval.id;\n this._unit = loadval.unit;\n this._calib = YAPI._decodeWords(loadval.cal);\n this._summary = new YMeasure(0,0,0,0,0);\n this._streams = [];\n this._preview = [];\n this._measures = [];\n for(var i = 0; i < loadval.streams.length; i++) {\n var stream = this._parent._findDataStream(this, loadval.streams[i]);\n if(this._startTime > 0 && stream.get_startTimeUTC() + stream.get_duration() <= this._startTime) {\n // this stream is too early, drop it\n } else if(this._endTime > 0 && stream.get_startTimeUTC() > this._endTime) {\n // this stream is too late, drop it\n } else {\n this._streams.push(stream);\n if(stream.isClosed() && stream.get_startTimeUTC() >= this._startTime &&\n (this._endTime == 0 || stream.get_startTimeUTC() + stream.get_duration() <= this._endTime)) {\n if (summaryMinVal > stream.get_minValue())\n summaryMinVal = stream.get_minValue();\n if (summaryMaxVal < stream.get_maxValue())\n summaryMaxVal = stream.get_maxValue();\n summaryTotalAvg += stream.get_averageValue() * stream.get_duration();\n summaryTotalTime += stream.get_duration();\n\n var rec = new YMeasure(stream.get_startTimeUTC(),\n stream.get_startTimeUTC() + stream.get_duration(),\n stream.get_minValue(),\n stream.get_averageValue(),\n stream.get_maxValue());\n this._preview.push(rec);\n }\n }\n }\n if((this._streams.length > 0) && (summaryTotalTime>0)) {\n // update time boundaries with actual data\n stream = this._streams[this._streams.length-1];\n var endtime = stream.get_startTimeUTC() + stream.get_duration();\n var startTime = this._streams[0].get_startTimeUTC() - stream.get_dataSamplesIntervalMs()/1000;\n if(this._startTime < startTime) {\n this._startTime = startTime;\n }\n if(this._endTime == 0 || this._endTime > endtime) {\n this._endTime = endtime;\n }\n this._summary = new YMeasure(this._startTime,this._endTime,\n summaryMinVal,summaryTotalAvg/summaryTotalTime,summaryMaxVal);\n }\n this._progress = 0;\n return this.get_progress(); \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
select and focus on plot change the view of active plot | function focusIn(element, type){
let clicked = d3.select(element);
if (type == "plot") d3.activeGraph.activePlot = clicked;
else if (type == "cursor") {
d3.activeGraph.activeCursor = clicked;
}
} | [
"function focusIn(element, type){\n let clicked = d3.select(element);\n if (type == \"plot\") d3.activeGraph.activePlot = clicked;\n else if (type == \"cursor\") d3.activeGraph.activeCursor = clicked;\n }",
"function activateChart() {\n drawChart(store, xChoice.getValue(), yChoice.getValue(), 'PlotContainer');\n //updatePlots('PlotContainer');\n }",
"chosen_plot() {\n this.createPlot();\n }",
"set axesVisible(value){this.setAppState('axesVisible', value);}",
"function regionUpdate(){\n setPlot(regionSel.value);\n}",
"function clearSelection() {\n if(plotview.selected) {\n for(var i = 0; i < plotview.selected.length; i++) {\n plotview.selected[i] = false;\n }\n }\n}",
"function displayModelsPane() {\n focusOnPane(\"choose-models-pane\");\n}",
"set activeView(val) {\n this._activeView = val;\n }",
"function new_plot() {\n nav_start(\"#nav_tumor\");\n nav_start(\"#nav_gene\");\n nav_start(\"#nav_region\");\n nav_start(\"#nav_clinical\");\n $(\".cancel\").hide();\n $(\".nav_module_close\").hide();\n start = true;\n}",
"function setSelection(area){\n\t\t\tclearSelection();\n\t\t\t\t\t\t\n\t\t\tselection.first.y = (options.selection.mode == \"x\") ? 0 : (yaxis.max - area.y1) * vertScale;\n\t\t\tselection.second.y = (options.selection.mode == \"x\") ? plotHeight : (yaxis.max - area.y2) * vertScale;\t\t\t\n\t\t\tselection.first.x = (options.selection.mode == \"y\") ? 0 : (area.x1 - xaxis.min) * hozScale;\n\t\t\tselection.second.x = (options.selection.mode == \"y\") ? plotWidth : (area.x2 - xaxis.min) * hozScale;\n\t\t\t\n\t\t\tdrawSelection();\n\t\t\tfireSelectedEvent();\n\t\t}",
"function graph_tab_clicked() {\n // Deselect other tabs\n $('#sim-tab').removeClass(\"active\");\n $('#editor-tab').removeClass(\"active\");\n $('#sim-tools').hide();\n $('#editor-tools').hide();\n // Select graph tab\n $('#graph-tab').addClass(\"active\");\n $('#graph-settings').show();\n}",
"function showAddPlotDialog (){ model.style.display = \"block\"; }",
"dblclick() {\n\t\tthis.setView( 'focus' );\n\t}",
"function displayMetricsPane() {\n focusOnPane(\"choose-metric-pane\");\n}",
"function select() {\n selection.select(swimlane);\n }",
"changeView() {\r\n if (this.graph.currView < this.graph.cameras.length - 1) {\r\n this.graph.currView++;\r\n }\r\n else {\r\n this.graph.currView = 0;\r\n }\r\n\r\n this.camera = this.graph.cameras[this.graph.currView];\r\n this.interface.setActiveCamera(this.camera);\r\n }",
"function setSelection(area)\n {\n clearSelection();\n\n selection.first.y = (options.selection.mode == \"x\") ? 0 : (yaxis.max - area.y1) * vertScale;\n selection.second.y = (options.selection.mode == \"x\") ? plotHeight : (yaxis.max - area.y2) * vertScale;\n selection.first.x = (options.selection.mode == \"y\") ? 0 : (area.x1 - xaxis.min) * hozScale;\n selection.second.x = (options.selection.mode == \"y\") ? plotWidth : (area.x2 - xaxis.min) * hozScale;\n\n drawSelection();\n fireSelectedEvent();\n }",
"selectFocused(){this._tabs[this._focusIndex].selectItem()}",
"focusSelectedPanel() {\n this.preferencesPanels.focusSelectedPanel();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a Query with a path and optional additional query constraints. Path must currently be empty if this is a collection group query. | function Query(path, collectionGroup, explicitOrderBy, filters, limit, startAt, endAt) {
if (collectionGroup === void 0) {
collectionGroup = null;
}
if (explicitOrderBy === void 0) {
explicitOrderBy = [];
}
if (filters === void 0) {
filters = [];
}
if (limit === void 0) {
limit = null;
}
if (startAt === void 0) {
startAt = null;
}
if (endAt === void 0) {
endAt = null;
}
this.path = path;
this.collectionGroup = collectionGroup;
this.explicitOrderBy = explicitOrderBy;
this.filters = filters;
this.limit = limit;
this.startAt = startAt;
this.endAt = endAt;
this.memoizedCanonicalId = null;
this.memoizedOrderBy = null;
if (this.startAt) {
this.assertValidBound(this.startAt);
}
if (this.endAt) {
this.assertValidBound(this.endAt);
}
} | [
"function Query(path, collectionGroup, explicitOrderBy, filters, limit, startAt, endAt) {\n if (collectionGroup === void 0) { collectionGroup = null; }\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.collectionGroup = collectionGroup;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }",
"function Query(path, collectionGroup, explicitOrderBy, filters, limit, startAt, endAt) {\r\n if (collectionGroup === void 0) { collectionGroup = null; }\r\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\r\n if (filters === void 0) { filters = []; }\r\n if (limit === void 0) { limit = null; }\r\n if (startAt === void 0) { startAt = null; }\r\n if (endAt === void 0) { endAt = null; }\r\n this.path = path;\r\n this.collectionGroup = collectionGroup;\r\n this.explicitOrderBy = explicitOrderBy;\r\n this.filters = filters;\r\n this.limit = limit;\r\n this.startAt = startAt;\r\n this.endAt = endAt;\r\n this.memoizedCanonicalId = null;\r\n this.memoizedOrderBy = null;\r\n if (this.startAt) {\r\n this.assertValidBound(this.startAt);\r\n }\r\n if (this.endAt) {\r\n this.assertValidBound(this.endAt);\r\n }\r\n }",
"function Query(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) {\n if (collectionGroup === void 0) { collectionGroup = null; }\n if (explicitOrderBy === void 0) { explicitOrderBy = []; }\n if (filters === void 0) { filters = []; }\n if (limit === void 0) { limit = null; }\n if (limitType === void 0) { limitType = LimitType.First; }\n if (startAt === void 0) { startAt = null; }\n if (endAt === void 0) { endAt = null; }\n this.path = path;\n this.collectionGroup = collectionGroup;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.limitType = limitType;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedOrderBy = null;\n // The corresponding `Target` of this `Query` instance.\n this.memoizedTarget = null;\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }",
"function asCollectionQueryAtPath(query, path) {\n return new QueryImpl(path, \n /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt);\n}",
"function newQueryForPath(path) {\n return new QueryImpl(path);\n}",
"function PathQuery(input, subject, path, object) {\r\n this.input = input;\r\n this.source = input.source;\r\n if(typeof subject === 'string' && subject.indexOf(\"?\") == 0) {\r\n this.subjectAttr = var2Attr(subject);\r\n }\r\n else {\r\n this.subject = subject;\r\n }\r\n if(path == null) {\r\n throw \"Path cannot be unbound\";\r\n }\r\n if(typeof path === 'string') {\r\n this.path_ = T(path);\r\n }\r\n else {\r\n this.path_ = path;\r\n }\r\n if(typeof object === 'string' && object.indexOf(\"?\") == 0) {\r\n this.objectAttr = var2Attr(object);\r\n }\r\n else {\r\n this.object = object;\r\n }\r\n}",
"static create(query) {\n query.setPath(join(query.path)); // ensures dot notation\n const obj = new Query(query.path);\n obj._query = query;\n return obj;\n }",
"function PathQuery(input, subject, path, object) {\n this.input = input;\n this.source = input.source;\n if(typeof subject === 'string' && subject.indexOf(\"?\") == 0) {\n this.subjectAttr = var2Attr(subject);\n }\n else {\n this.subject = subject;\n }\n if(path == null) {\n throw \"Path cannot be unbound\";\n }\n if(typeof path === 'string') {\n this.path_ = T(path);\n }\n else {\n this.path_ = path;\n }\n if(typeof object === 'string' && object.indexOf(\"?\") == 0) {\n this.objectAttr = var2Attr(object);\n }\n else {\n this.object = object;\n }\n}",
"constructor(collection_name, query) {\n this.collection_name = collection_name;\n this._query = query || [];\n }",
"function Query(parseObject) {\n this._query = new Parse.Query(parseObject);\n }",
"function setQuery(query) {\n 'use strict';\n\n\n /* jshint validthis : true*/\n var constructorInstance = this;\n\n\n // init\n var queryValidation, messageToLog, queryDocument;\n\n\n // check document\n queryValidation = validate.document(query);\n\n // invalid document\n if (queryValidation.valid === false) {\n queryDocument = null;\n messageToLog = messages('document.error.constructingQuery' + [queryValidation.reason], [queryValidation.moreInfo]);\n // error messages are always logged\n log.error(messageToLog.message);\n }\n // valid document\n else {\n queryDocument = queryValidation;\n }\n\n\n ////////\n return queryDocument;\n}",
"constructor() {\n QueryPattern.initialize(this);\n }",
"function inheritedQuery(){ this.extendDefaults({ inheritedQuery:true }); return this; }",
"static query() {\n return new Query(this);\n }",
"static __query() {\n // Return a newly constructed DbQuery given `this` and internal DB API\n return new Query(this, DATA.db);\n }",
"collection(path, queryFn) {\n const collectionRef = this.ref.collection(path);\n const { ref, query } = associateQuery(collectionRef, queryFn);\n return new AngularFirestoreCollection(ref, query, this.afs);\n }",
"function SharePointQueryable(baseUrl, path) {\n var _this = _super.call(this) || this;\n _this._options = {};\n _this._query = new collections_1.Dictionary();\n _this._batch = null;\n if (typeof baseUrl === \"string\") {\n // we need to do some extra parsing to get the parent url correct if we are\n // being created from just a string.\n var urlStr = baseUrl;\n if (util_1.Util.isUrlAbsolute(urlStr) || urlStr.lastIndexOf(\"/\") < 0) {\n _this._parentUrl = urlStr;\n _this._url = util_1.Util.combinePaths(urlStr, path);\n }\n else if (urlStr.lastIndexOf(\"/\") > urlStr.lastIndexOf(\"(\")) {\n // .../items(19)/fields\n var index = urlStr.lastIndexOf(\"/\");\n _this._parentUrl = urlStr.slice(0, index);\n path = util_1.Util.combinePaths(urlStr.slice(index), path);\n _this._url = util_1.Util.combinePaths(_this._parentUrl, path);\n }\n else {\n // .../items(19)\n var index = urlStr.lastIndexOf(\"(\");\n _this._parentUrl = urlStr.slice(0, index);\n _this._url = util_1.Util.combinePaths(urlStr, path);\n }\n }\n else {\n var q = baseUrl;\n _this._parentUrl = q._url;\n _this._options = q._options;\n var target = q._query.get(\"@target\");\n if (target !== null) {\n _this._query.add(\"@target\", target);\n }\n _this._url = util_1.Util.combinePaths(_this._parentUrl, path);\n }\n return _this;\n }",
"function Query(query) {\t\t\n\t\tvar queryParameters = [];\n\t\tvar queryFunction = null;\n\t\ttry {\n\t\t\tqueryFunction = new Function('_$qp', \n\t\t\t\tcompileQuery(parseQuery(query)));\n\t\t} catch (e) {\t\t\t\n\t\t\tif (e instanceof ParseError) {\n\t\t\t\tvar errorContext = getErrorContext(e, query);\n\t\t\t\tthrow new QueryTranslationException(e.message,\n\t\t\t\t\terrorContext.line, errorContext.offset, \n\t\t\t\t\terrorContext.context);\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * Binds a specified value to a placeholder\n\t\t * @param index Index of the placeholder\n\t\t * @param value The value to bind to the placeholder\n\t\t */\t\t\n\t\tthis.setValue = function(index, value) {\n\t\t\tif (queryFunction == null) {\n\t\t\t\tthrow new jsinq.InvalidOperationException();\n\t\t\t}\n\t\t\tqueryParameters[index] = value;\t\n\t\t};\t\t\n\n\t\t/**\n\t\t * Executes the query and returns the result\n\t\t * @return The result of the query\n\t\t */\t\t\n\t\tthis.execute = function() {\n\t\t\tif (queryFunction == null) {\n\t\t\t\tthrow new jsinq.InvalidOperationException();\n\t\t\t}\n\t\t\treturn queryFunction(queryParameters);\n\t\t};\n\t\t\n\t\t/**\n\t\t * Returns the anonymous function that executes the query\n\t\t * @return The query function\n\t\t */\n\t\tthis.getQueryFunction = function() {\n\t\t\tif (queryFunction == null) {\n\t\t\t\tthrow new jsinq.InvalidOperationException();\n\t\t\t}\t\t\t\n\t\t\treturn queryFunction;\n\t\t};\n\t}",
"ParseAndConstructQuery(query) {\n let limit = 50;\n // construct a query\n let gquery = this._dataStore.createQuery(this._kind);\n\n if ( query.filters ) {\n for (let i = 0; i < query.filters.length; ++i ) {\n let filter = query.filters[i];\n if ( filter && filter.prop && filter.val && filter.opt) {\n gquery.filter(filter.prop, filter.opt , filter.val );\n }\n }//for\n }\n\n // By default, sort descending is true\n let sortDesc = ( typeof query.SortDescending !== 'undefined' )? query.SortDescending: true;\n\n if ( query.sortByProp ) {\n gquery.order( query.sortByProp, { descending: sortDesc } );\n }\n\n if ( query.limit ) {\n gquery.limit( query.limit );\n } else {\n gquery.limit(limit);\n }\n\n return gquery;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple hash for mapping items to indices. ITEMS is a seq of objects, each having field denoted by KEY. Map item.key to item's index in ITEMS. Returns resulting association map (hash map). | function simpleHash (items, key) {
var itemhash = {};
var i = 0;
for (var o in items) {
var x = items[o][key];
itemhash[x]=i;
i = i + 1;
}
return itemhash;
} | [
"function createKeyToIndexMap(items, start, end) {\n const map = new Map();\n for (let i = start; i <= end; i++) {\n const item = items[i];\n if (item !== null) {\n map.set(item.key, i);\n }\n }\n return map;\n}",
"function indexBy(iterator, context) {\n var memo = new Hash();\n \n this.each(function(item) {\n var k = iterator(item),\n v = memo.get(k) || [];\n v.push(item);\n memo.set(k, v);\n }, context);\n \n return memo;\n }",
"function buildIndex(ids) {\n return ids.reduce(function (map, id, index) {\n map.set(id, index);\n return map;\n }, new Map_1.default());\n }",
"getFactAndAttributeIndexMap(queryItemList) {\n // Build a fact index map. The key is the fact label and the value is the index of the column that is equivalent to this fact.\n const factsIndexMap = {};\n const attributesIndexMap = {};\n queryItemList.forEach((queryItem, index) => {\n const dataItemList = queryItem.getDataItemList();\n // A query item is a tuple that might contain multiple dataitem. Depending on the visualization, but in most case, it is only one data item\n const isTheQueryItemAnAttribute = !!dataItemList.find((dataItem) => dataItem.getType() === 'attribute');\n const label = dataItemList.map(dataItem => dataItem.getLabel()).join();\n if (isTheQueryItemAnAttribute) {\n attributesIndexMap[label] = index;\n } else {\n // If the query item is a fact, it is safe to say that it contains one dataItem.\n factsIndexMap[label] = index;\n }\n\n });\n\n return {\n factsIndexMap: factsIndexMap,\n attributesIndexMap: attributesIndexMap\n }\n }",
"function buildMapIndex() {\n // mapIndex[typename] will be [[x,y],[x,y],...]\n var mapIndex = {};\n\n for (var y = 0; y < map.length; y++) {\n for (var x = 0; x < map[y].length; x++) {\n var typeName = tileTypes[map[y][x].type][0];\n if (!mapIndex[typeName]) { mapIndex[typeName] = []; }\n mapIndex[typeName].push([x, y]);\n }\n }\n\n return mapIndex;\n}",
"function partitionMap(items, keygen) {\n const map = new Map();\n for (const item of items) {\n const key = keygen(item);\n const partition = map.get(key) || [];\n if (!map.has(key)) {\n map.set(key, partition);\n }\n partition.push(item);\n }\n return map;\n}",
"createSectionsKey (map) {\n\n var key = {};\n\n for (var i = 0; i < map.length; i++) {\n key[ map[i].id ] = i;\n }\n\n return key;\n }",
"rebuildIndices() {\n const me = this,\n isFiltered = me.isFiltered,\n indices = me._indices || (me._indices = {}),\n keyProps = Object.keys(indices),\n indexCount = keyProps.length,\n values = me._values,\n count = values.length;\n\n let i, j;\n\n // First, clear indices.\n if (isFiltered) {\n indices[filteredIndicesProperty] = {};\n }\n for (i = 0; i < indexCount; i++) {\n indices[keyProps[i]] = {};\n if (isFiltered) {\n indices[filteredIndicesProperty][keyProps[i]] = {};\n }\n }\n\n /*\n * Rebuild the indices object.\n * Loop through all items adding an entry for each one to each index.\n * So collection.add({id : foo, name : 'Nige'}, {id : 'bar', name : 'Faye'}) where collection has had an index\n * added for the \"name\" property would result in:\n *\n * {\n * id : {\n * foo : 0,\n * bar : 1\n * },\n * name : {\n * Nige : 0,\n * Faye : 1\n * }\n * }\n */\n for (i = 0; i < count; i++) {\n const item = values[i];\n\n for (j = 0; j < indexCount; j++) {\n const keyProp = keyProps[j];\n // This does indices.name['Nige'] = 0\n indices[keyProp][safeIndexKey(item[keyProp])] = i;\n }\n }\n\n // Create a parallel lookup structure into the _filteredValues\n if (isFiltered) {\n const values = me._filteredValues,\n count = values.length,\n indices = me._indices[filteredIndicesProperty];\n\n for (i = 0; i < count; i++) {\n const item = values[i];\n\n for (j = 0; j < indexCount; j++) {\n const keyProp = keyProps[j];\n // This does indices[filteredIndicesProperty].name['Nige'] = 0\n indices[keyProp][safeIndexKey(item[keyProp])] = i;\n }\n }\n }\n\n me._indicesInvalid = false;\n }",
"function generateIndexMap(allUniqueColIndex, startDim, dimNum)\r\n {\r\n var map = {};\r\n for(var i = 0; i < allUniqueColIndex.length; ++i)\r\n {\r\n map[buildOneHeader(allUniqueColIndex[i], startDim, dimNum)] = i;\r\n }\r\n return map;\r\n }",
"indices () { return Array.from(this._store.keys()) }",
"function genMap(chain) {\n var eleConParMap = new Map();\n for (var i = 1; i < chain.length; i++) {\n var key = chain[i].data.eleid + \"\" + chain[i].data.conid + \"\" + chain[i].data.parid;\n if (eleConParMap.has(key)) {\n var val = eleConParMap.get(key);\n val++;\n eleConParMap.set(key, val);\n } else {\n eleConParMap.set(key, 1);\n }\n }\n return eleConParMap;\n}",
"function createIdMap(sheet) {\n var indexId = getColumnIndex(sheet, \"ID\");\n Logger.log(\"ID = \" + indexId);\n var range = sheet.getRange(2, indexId + 1, sheet.getLastRow() - 1, 1);\n var rows = range.getValues();\n var map = {};\n for (var ri = 0; ri < rows.length; ri++) {\n map[rows[ri][0]] = ri + 2; // 1-based row number (+header)\n }\n return map;\n }",
"function indexReplaceableItems (message) {\n\tconst map = {};\n\ttoReplace.forEach(function (key) {\n\t\tif (!message[key]) {\n\t\t\treturn;\n\t\t}\n\t\tmessage[key].forEach(function (replaceItem) {\n\t\t\tif (!replaceItem || !replaceItem.positions) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treplaceItem.positions.forEach(function (start) {\n\t\t\t\tmap[start] = {\n\t\t\t\t\titem: replaceItem,\n\t\t\t\t\ttype: key\n\t\t\t\t};\n\t\t\t});\n\t\t});\n\t});\n\treturn map;\n}",
"indexProperties(properties) {\n return properties.reduce(function(result, item, index) {\n result[item] = index + 1;\n return result;\n }, {});\n }",
"function createIndex() {\n item_index = [];\n connection.query('SELECT * from products', function (err, res) {\n if (err) throw err;\n for (var i = 0; i < res.length; i++) {\n item_index.push(res[i].item_id);\n }\n });\n}",
"function build_indexed_entries() {\n\n\t// clear out the global object\n\tindexed_entries = {};\n\t\n\t// loop through the entries in the global array entries and stick each entry\n\t// object in the global object indexed_entries, with each key being the\n\t// entry id\n\tvar total_entries = entries.length;\n\tfor (var i = 0; i < total_entries; ++i) {\n\t\tvar entry = entries[i];\n\t\tvar entry_id = entry[\"id\"];\n\t\tindexed_entries[entry_id] = entry;\n\t}\n\t\n\treturn;\n}",
"toHashIndex(identityFunction) {\n const identityFunc = identityFunction || defaultIdentityFunction;\n const hash = {};\n for(let i = 0, iCount = array.length; i < iCount; i += 1) {\n const identity = identityFunc(array[i]);\n if(!hash[identity]) {\n hash[identity] = array[i];\n }\n }\n \n return hash;\n }",
"getUrlBookmarkIdMap () {\n const bmEnts = this.bookmarkIdMap.entrySeq()\n\n // bmEnts :: Iterator<[BookmarkId,TabWindow]>\n const getSavedUrls = (tw) => tw.tabItems.map((ti) => ti.url)\n\n const bmUrls = bmEnts.map(([bmid, tw]) => getSavedUrls(tw).map(url => [url, bmid])).flatten(true)\n\n const groupedIds = bmUrls.groupBy(([url, bmid]) => url).map(vs => Immutable.Set(vs.map(([url, bmid]) => bmid)))\n // groupedIds :: Seq.Keyed<URL,Set<BookmarkId>>\n\n return Immutable.Map(groupedIds)\n }",
"function getEnumMap(metaJson) {\n const items = JSPath.apply('.\"imin:index\"(.subClass | .enumeration)..\"imin:item\"', metaJson);\n return new Map(items.map(i => [i.id, i.name]));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print enemies onto HTML | function printEnemies(){
for (var i = 0; i < enemies.length; i++) {
var en = $('<div class="fighter enemy media p-2 m-2 rounded" data-fighter-pos="'+fighters.indexOf(enemies[i])+'"><div class="media-body"><h5>'+enemies[i].name+'</h5><p>Health: '+enemies[i].health+'</p></div><img src="'+enemies[i].img+'" alt="" width="45" class="img-responsive rounded" /></div>');
en.appendTo(colEnemies);
colEnemies.removeClass('hide').addClass('show');
}
} | [
"function showEnemies(){\n enemies.forEach(function(enemy) {\n $('#enemies').prepend($(\"<div>\").html(\"<img src='assets/images/\" + enemy.name + \".png' alt='\" + enemy.name + \"'>\"));\n });\n }",
"function displayEnemies() {\n\n\t\tvar enemiesCounter = 0;\n\n\t\t// Loop through the list of available enemies...\n\t\tenemies.forEach(function(enemy) {\n\n\t\t\t// Create a div\n\t\t\tvar enemiesDiv = $(\"<div>\");\n\n\t\t\tenemiesDiv.addClass(\"enemies\");\n\t\t\tenemiesDiv.attr(\"value\", enemiesCounter);\n\n\t\t\t// Append enemie's name, img, and hp to the enemies's div\n\t\t\tenemiesDiv.append(\"<p>\" + enemy.name + \"</p>\");\n\t\t\tenemiesDiv.append(\"<img src=\" + enemy.src + \" alt='character'>\");\n\t\t\tenemiesDiv.append(\"<p>\" + enemy.hp + \"<p>\");\n\n\t\t\t// Add the enemie's div to the enemies-available-section\n\t\t\t$(\"#enemies-available-section\").append(enemiesDiv);\n\n\t\t\tenemiesCounter++;\n\t\t});\n\t}",
"function renderEnemies() {\n for (var i = 0; i < Enemies.length; i++) {\n var enemy = Enemies[i];\n context.drawImage(enemy.img, enemy.left(), enemy.top());\n }\n }",
"displayEnemies(){\n for( let i = 0; i < this._enemyList.length; i++){\n this._enemyList[i].draw();\n this._enemyList[i].move();\n }\n }",
"function displayEnemy() {\n\t$enemy = $('#enemy');\n\tenemyObj = enemies[activeEnemy.title];\n\n\tif(activeEnemy.health <= 0) combatWin();\n\n\t$enemy.empty();\n\t$enemy.append(enemyLink(activeEnemy.title) + '<br><br>')\n\t\t.append(`Health: ${activeEnemy.health} / ${enemyObj.health}`);\n}",
"renderenemies(ctx) {\n this.enemies.forEach((enemy) => {\n enemy.render(ctx);\n });\n }",
"function renderEnemies () {\n\n\t\tvar i;\n\t\tfor (i = 0; enemiesArray.length > i; i += 1) {\n\n\t\t\tif (enemiesArray[i].name == 'wolf') {\n\n\t\t\t\tsetFramesSpriteAnimationEnemies(contextBackground, enemiesArray[i].image, enemiesArray[i].yFramePosition, enemiesArray[i].width, enemiesArray[i].height, 0, enemiesArray[i].frameCuantity, enemiesArray[i].x + background.x, enemiesArray[i].y + background.y);\n\n\t\t\t} else if (enemiesArray[i].name == 'warlock') {\n\n\t\t\t\tif (warlockShootingAnimation == true) {\n\t\t\t\t\tsetFramesSpriteAnimationEnemies(contextBackground, enemiesArray[i].image, 0, enemiesArray[i].width, enemiesArray[i].height, 0, enemiesArray[i].frameCuantity, enemiesArray[i].x + background.x, enemiesArray[i].y + background.y);\n\t\t\t\t} else {\n\t\t\t\t\tsetFramesSpriteAnimationEnemies(contextBackground, enemiesArray[i].image, 230, enemiesArray[i].width, enemiesArray[i].height, 0, enemiesArray[i].frameCuantity, enemiesArray[i].x + background.x, enemiesArray[i].y + background.y);\n\t\t\t\t}\n\t\t\t}\n\n\t\t};\n\t}",
"function printChampion(){\n champEl.html('<div class=\"fighter enemy media p-2 m-2 rounded\"><div class=\"media-body\"><h5>'+champion.name+'</h5><p>Health: <span class=\"champion-health fighter-health\">'+champion.health+'</span></p></div><img src=\"'+champion.img+'\" alt=\"\" width=\"45\" class=\"img-responsive rounded\" /></div>');\n colPlay.removeClass('hide').addClass('show');\n areaPlay.fadeIn(500, function(){\n printEnemies(); \n });\n }",
"function renderEnemyInfo (enemy) {\n if (enemy.hp < 1) {\n $('.enemy-info').html(\"<span class='red'>Enemy has dead</span>\")\n } else {\n $('.enemy-info').html(\"Enemy has \" + enemy.hp + \"hp\")\n }\n}",
"function renderEntities() {\n /* Loop through all of the objects within the allEnemies array and call\n * the render function you have defined.\n */\n PosDetails.allEnemies.forEach(function(enemy) {\n enemy.render();\n });\n\n player.render();\n }",
"function displayEnemies() {\n //we iterate through the array, only displaying the enemies which exist inside\n //the array (possibillity of 0)\n for (let e = 0; e < enemies.length; e++) {\n enemies[e].move();\n enemies[e].display();\n }\n}",
"function displayEnemy(x, y, text) {\n var pos = document.getElementById(x + y)\n pos.innerHTML = text\n // console.log(`Enemy Loaded: ${text}`);\n }",
"function updateEnemy() {\n document.getElementById(\"enemies\").innerHTML = \"\";\n var i;\n for (i = 0; i < enemies.length; i++) {\n if (i == enemies.length - 1 && level >= 2) {\n document.getElementById(\"enemies\").innerHTML +=\n \"<div class='enemy boss' style='left:\" +\n enemies[i].left +\n \"px; top:\" +\n enemies[i].top +\n \"px;'></div>\";\n break;\n }\n document.getElementById(\"enemies\").innerHTML +=\n \"<div class='enemy' style='left:\" +\n enemies[i].left +\n \"px; top:\" +\n enemies[i].top +\n \"px;'></div>\";\n }\n}",
"function renderEnemies(indx){\n\n allLevels[indx].enemies.forEach(function(enemy){\n enemy.element.style.top = enemy.pos[1] + 'px';\n enemy.element.style.left = enemy.pos[0] + 'px';\n enemy.element.style.width = enemy.size[0] + 'px';\n enemy.element.style.height = enemy.size[1] + 'px';\n\n document.getElementById('enemies').appendChild(enemy.element);\n\n });\n}",
"function renderEntities() {\n /* Loop through all of the objects within the allEnemies array and call\n * the render function you have defined.\n */\n allEnemies.forEach(function(enemy) {\n enemy.render();\n });\n\n player.render();\n token.render();\n }",
"function enemyGen() {\n // gen random number of enemies\n let numEnemies = randomNum(1, 3);\n // pushes enemy container elements to DOM\n let enemyBank = []; // will have a list of enemies to randomly select from\n let enemySelect = []; // the randomly selected enemies go here\n let output = '';\n\n for (let i = 0; i < numEnemies; i++) {\n output += `<article></article>`;\n }\n // \n $enemyCont.innerHTML = output;\n // set class for all enemies\n $enemy = $fightCont.querySelectorAll('article');\n // \n $enemy.forEach(enemy => enemy.classList.add('enemy'));\n // find what enemies will appear\n if (numEnemies === 1) {\n enemySelect = [];\n //randomly selects an enemy from strong, medium and weak strength enemies\n enemyBank = weakEnemy.concat(medEnemy.concat(strongEnemy)); \n enemySelect.push(enemyBank[randomNum(1, enemyBank.length-1)]);\n renderEnemy(enemySelect);\n } else if (numEnemies === 2) {\n enemySelect = [];\n //randomly selects an enemy from strong and weak strength enemies\n enemyBank = weakEnemy.concat(strongEnemy);\n enemySelect.push(enemyBank[randomNum(1, enemyBank.length-1)]);\n //randomly selects an enemy from medium and weak strength enemies\n enemyBank = weakEnemy.concat(medEnemy);\n enemySelect.push(enemyBank[randomNum(1, enemyBank.length-1)]);\n renderEnemy(enemySelect);\n } else {\n enemySelect = [];\n //randomly selects an enemy from strong, medium and weak strength enemies\n enemyBank = weakEnemy.concat(medEnemy.concat(strongEnemy));\n enemySelect.push(enemyBank[randomNum(1, enemyBank.length-1)]);\n //pushes 2 random enemies from weakEnemy to enemySelect\n run(() => {\n enemySelect.push(weakEnemy[randomNum(1, weakEnemy.length-1)]);\n }, 2);\n renderEnemy(enemySelect);\n }\n }",
"function renderEntities() {\n /*\n * Loop through all of the objects within the allEnemies array and call the\n * render function you have defined.\n */\n allEnemies.forEach(function(enemy) {\n enemy.render();\n });\n\n player.render();\n }",
"function renderEntities() { \n allEnemies.forEach(function(enemy) {\n enemy.render();\n }); \n\n player.render();\n }",
"function renderEntities() {\n /* Loop through all of the objects within the allEnemies array and call\n * the render function you have defined.\n */\n allEnemies.forEach(function (enemy) {\n enemy.render();\n });\n\n player.render();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Web Sockets Functions Sharing userselected EQ type to backend | function getEQtype() {
var x = document.getElementById("EQtype").value;
console.log(x);
var socket = io.connect('http://localhost:3001');
socket.on('connect', function(data){
socket.emit('typeSel', x);
});
} | [
"function sendVoteChar(){\n\tcheckConnection();\n\tvar socket = io();\n\tvar val = sessionStorage.getItem('user');\n\tsocket.emit('Get Voted Charities', val);\n}",
"function askValue(e){\n\n var payload = {\n key: document.getElementById('key_to_obtain').value\n }\n socket.send(JSON.stringify(payload));\n \n return false;\n}",
"function\nWebSocketIFRequestGetBayTypes()\n{\n WebSocketIFSendSimpleRequest(\"getbaytypes\");\n}",
"function clientType(){\n\t//alert(\"Sending client type\");\n\tsocket.emit(\"clientType\", {type: \"player\"});\n}",
"function\nWebSocketIFHandleResponseBayTypes(InBayTypes)\n{\n MainBayTypes = InBayTypes;\n}",
"sendKeysFromGuitar(selectedNote) {\n socket.emit('sendFromGuitar', selectedNote);\n }",
"send(session_id, type, text, data = {}) {\n let input = {\n client: this.name,\n auth_token: this.auth_token,\n session_id: session_id,\n type: type,\n data: data,\n fast: true\n };\n\n if(text) {\n input.text = text;\n }\n\n this.socket.emit('request',input);\n }",
"subscribeQuery(queryId) {\n let data = {\n 'target': 'oracle',\n 'action': 'subscribe',\n 'payload': {\n 'type': 'response',\n 'query_id': queryId\n }\n }\n this.webSocket.send (JSON.stringify (data))\n }",
"function sendQuestion(){\n\tsocket.emit('transmit host question', document.getElementById(\"thequestion\").value);\n}",
"subscribe(oracleId) {\n let data = {\n 'target': 'oracle',\n 'action': 'subscribe',\n 'payload': {\n 'type': 'query',\n 'oracle_id': oracleId\n }\n }\n this.webSocket.send (JSON.stringify (data))\n }",
"function play(choice){\n socket.emit('choice', choice); \n //alert(\"I played \"+choice);\n}",
"selectChoice(choice) { socket.emit(choice); }",
"subscribeQuery(queryId) {\n let data = {\n 'target': 'oracle',\n 'action': 'subscribe',\n 'payload': {\n 'type': 'response',\n 'query_id': queryId\n }\n }\n this.webSocket.send (JSON.stringify (data))\n return data\n }",
"function sendData(event){\n console.log(\"sending assignment data...\");\n var socket = io({transports: ['websocket']});\n \n\n var svr1 = $(\".section1\").text();\n var svr2 = $(\".section2\").text();\n var svr3 = $(\".section3\").text(); \n\n var assignment = [svr1, svr2, svr3]; \n\n console.log(assignment);\n socket.emit('managerAssign', assignment);\n\n}",
"function requestToJoin(){\n var codeRoom = $('#code').val();\n if (codeRoom === \"\") {\n alert('Enter the code from the desktop');\n }else{\n socket.emit('requestToJoin', {\n id: socket.id,\n room: $('#code').val()\n });\n }\n}",
"subscribe(oracleId) {\n let data = {\n 'target': 'oracle',\n 'action': 'subscribe',\n 'payload': {\n 'type': 'query',\n 'oracle_id': oracleId\n }\n }\n this.webSocket.send (JSON.stringify (data))\n return data\n }",
"function sendSelections(event)\n{\n var destination = sendSelectionsMenu.val();\n sendSelectionsMenu.val(\"Send selection...\");\n datasetID = currentlySelectedDataStoreItem.file;\n\n cmd = \"userDataStoreGetDataItem\";\n callback = \"sendSelectionTo_\" + destination;\n\n payload = {\"userID\": userID,\n \"userGroups\": [\"public\", \"test\"],\n \"dataItemName\": datasetID};\n\n msg = {\"cmd\": cmd, \"status\": \"request\", \"callback\": callback, \"payload\": payload};\n hub.send(JSON.stringify(msg));\n\n} // sendSelections",
"function send_both(type, data) {\n\tsocket.emit(\"event\", { type : type, data : data });\n\n\tvar url = \"http://\" + $(\"#connect_server\").val() + \"/event\";\n\t// Send GET request to second server\n\tif (second_connected) {\n\t\t$.ajax({\n\t\t\turl : url,\n\t\t\ttype : \"get\",\n\t\t\tdata : {\n\t\t\t\ttype : encodeURIComponent(type),\n\t\t\t\tdata : encodeURIComponent(data)\n\t\t\t}\n\t\t});\n\t}\n}",
"function playerAction(action,data){\n console.log('playerAction',action,data);\n if(socketdata.player.role=='viewer')socket.emit('viewerAction', {action:action, id:socketdata.player.id, _data:data});\n else if(socketdata.player.role=='controller')socket.emit('playerAction', {action:action, id:socketdata.player.id, _data:data});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fonction qui incremente le nombre de victoires pour le login | async function incrementeVictoires(login){
try{
await knex.raw("UPDATE users SET partiesGagnees = partiesGagnees+1 WHERE users.login= ?", [login]);
}
catch(err){
console.error('Erreur dans la connection d\'un utilisateur dans la table users (incrementeVictoires)');
}
} | [
"function addCount() {\n if (count == 16) {\n count = 0;\n // console.log(count);\n showPerson();\n // console.log('count:',count);\n flashIndex();\n } else {\n count += 1;\n // console.log(count);\n showPerson();\n // console.log('count:', count);\n flashIndex();\n }\n }",
"function changeUserCounter(userCount) {\n document.getElementById('room-users-counter').innerHTML = userCount + ' users in this room';\n}",
"function increaseCount($this) {\n\t\tif ($this.hasClass('chocolate')) {\n\t\t\tcookies.set('chocolate', cookies.get('chocolate')+1);\n\t\t}\n\t\tif ($this.hasClass('sugar')) {\n\t\t\tcookies.set('sugar', cookies.get('sugar')+1);\n\t\t}\n\t\tif ($this.hasClass('lemon')) {\n\t\t\tcookies.set('lemon', cookies.get('lemon')+1);\n\t\t}\n\t\tfillCounts(); //Update page counts\n\t}",
"function incrementCount() {\n count.set($count + 1);\n }",
"function getNumberParticipants(){\n let value = 0;\n for(name in logins){\n value++;\n }\n return value;\n }",
"function ticketsNumberCounter(isIncrese, tickets){\n var totalTickets = document.getElementById(tickets).value;\n var firstClass = parseInt(totalTickets);\n var increaseTickets = firstClass;\n if(isIncrese == true){\n increaseTickets = increaseTickets+1;\n }\n if(isIncrese == false && increaseTickets > 0){\n increaseTickets = increaseTickets-1;\n }\n document.getElementById(tickets).value = increaseTickets;\n}",
"function increasePreviousLogins(user) {\n if (user.status !== \"FAIL\") {\n // Increment number of logins count.\n const previousLogins = (user.data.previousLogins || 0) + 1;\n const recieveOfferAlerts = user.data.recieveOfferAlerts ? user.data.recieveOfferAlerts : false;\n\n //\n log(\"X. - Increase Previous logins...\", \"SET ACCOUNT INFO\");\n\n gigya.accounts.setAccountInfo({\n data: {\n // This integer field must have been previously added to the site's schema via the UI Builder or accounts.setSchema API\n previousLogins,\n },\n callback: (event2) => {\n // Check if we must show or not the progressive profile screenset\n checkIfShowConsentsPopup(event2, previousLogins, recieveOfferAlerts);\n\n // Re-render the counter after this increase\n renderPreviousLoginsIfDefined(previousLogins);\n },\n });\n }\n}",
"function updateValues() {\n\n \"use strict\";\n var count = sessionStorage.getItem('cnt');\n count++;\n document.getElementById('planetCount').value = count;\n\n updatePicture(count);\n\n if(count >= 5) {\n document.getElementById('Go').value = \"Show Solar System\";\n }\n\n document.getElementById('user').value = sessionStorage.getItem('id');\n\n}",
"function increase_count() {\n let rval = parseInt(document.getElementById(\"count\").innerHTML);\n set_cookie(rval+1);\n window.location.reload();\n}",
"function increaseGuest() {\n\t\tvar value = parseInt(document.getElementsByName('guests')[0].value, 10);\n\t\tvalue = isNaN(value) ? 0 : value;\n\t\tif(value >= 16){\n\t\t\tdocument.getElementsByName('guests').disabled = true;\n\t\t}else{\n\t\t\tvalue++;\n\t\t}\n\t\tdocument.getElementsByName('guests')[0].value = value;\n\t\tsetTotalValue()\n\t}",
"function incrementCount(params) {\n\t// increase count by 1 per each 'next' arrow click\n\tcardCount++;\n\tif (cardCount > energetics.length) {\n\t\tcardCount = 1;\n\t}\n\tcurCard.innerText = cardCount;\n}",
"function incrementCounter () {\r\n// \t\tconsole.log('counter '+ counter);\r\n counter ++;\r\n\t\tconsole.log('counter '+ counter);\r\n }",
"increaseNumApuestas() {\n this.numApuestas++;\n }",
"function counterTotalUsers() {\n let totalUsers = 0\n let strHtml = \"\"\n\n for (let i = 0; i < users.length; i++) {\n if (users[i].userPermissions == 2) {\n totalUsers++\n } \n }\n strHtml += `<h6>Utilizadores</h6>\n <h3>${totalUsers}</h3>`\n\n counterUsers.innerHTML = strHtml\n }",
"function turnIncrement() {\n totalTurns++;\n $turnCounter.html('<p>Turns: ' + totalTurns + '</p>');\n }",
"function addCount() {\n\t\tcount++;\n\t}",
"function addPlayerCounter() {\n pCounter.innerHTML = user;\n }",
"function subirNivel() {\n\tniv++;\n\tatrapados = 0;\n\tcant = 2 + niv;\n\tpy++;\n}",
"function increment(){\n\t\tsetCount(prevCount=>prevCount+1)\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes year, month and day as strings and pads them as needed | function normalizeDate(year, month, day) {
return [year.padStart(4, '2000'), month.padStart(2, '0'), day.padStart(2, '0')];
} | [
"function padDate(date) {\n const year = date.getFullYear();\n const month = date.getMonth() + 1;\n const day = date.getDate();\n\n return year + String(month).padStart(2, \"0\") + String(day).padStart(2, \"0\");\n}",
"dateString(someDate = new Date()) {\n let year = String(someDate.getFullYear()).padStart(4, \"0\");\n let month = String(someDate.getMonth() + 1).padStart(2, \"0\");\n let day = String(someDate.getDate()).padStart(2, \"0\");\n return year + month + day;\n }",
"function formattedDate(year, month, day)\n{\n\tday = zeroPad(day);\n\tmonth = zeroPad(month);\n\t\n\tswitch (dateFormat)\n\t{\n\tcase 'B': // Big-endian\n\t\treturn year + \"/\" + month + \"/\" + day;\n\t\tbreak;\n\t\n\tcase 'M': // Middle-endian\n\t\treturn month + \"/\" +day + \"/\" + year;\n\t\tbreak;\n\t\n\tcase 'L': // Little-endian is default.\n\tdefault:\n\t\treturn day + \"/\" + month + \"/\" + year;\n\t\tbreak;\n\t}\n}",
"function padDatePart(n) {\n var r = String(n);\n if (r.length === 1) { r = '0' + r; }\n return r;\n }",
"function dateWriter(year, month, day) {\n return month+\"/\"+day+\"/\"+year;\n}",
"toYYYYMMDD(date){\n let month = '' + (date.getMonth() + 1);\n let day = '' + date.getDate();\n let year = date.getFullYear();\n \n if (month.length < 2) \n month = '0' + month;\n if (day.length < 2) \n day = '0' + day;\n\n return [year, month, day].join('-');\n }",
"function paddedDate(date){\n if (date >= 10){\n return date.toString();\n }\n else{\n return \"0\" + date.toString();\n }\n }",
"function dateBuilder(d){ \r\n let months=[\"January\" , \"February\", \"March\", \"April\" ,\"May\" , \"June\" , \"July\" , \"August\" , \"September\" ,\"October\" , \"November\" , \"December\"];\r\n let days=[\"Sunday\" ,\"Monday\" , \"Tuesday\" , \"Wednesday\", \"Thursday\" ,\"Friday\" , \"Saturday\"];\r\n\r\n let day=days[d.getDay()];\r\n let date=d.getDate();\r\n let month=months[d.getMonth()];\r\n let year=d.getFullYear();\r\n return `${day} ${date} ${month} ${year}`;\r\n\r\n\r\n}",
"function getYYYYMMDD (date) {\n let yyyy = date.getFullYear().toString();\n let mm = (date.getMonth()+1).toString();\n let dd = date.getDate().toString();\n return yyyy + '-' + padWithZeroes(mm) + '-' + padWithZeroes(dd);\n }",
"function zeroPadDate(str) {\n if (str.length < 2) {\n return '0' + str;\n } else {\n return str;\n }\n}",
"function dateWriter(year, month, day) {\n return month + '/' + day + '/' + year;\n}",
"pad (datevalue)\n {\n\t\tif ((datevalue.toString().length) === 1)\n\t\t{\n\t \t\tdatevalue = ('0' + datevalue);\n\t\t}\t\n\t\treturn datevalue;\n\t}",
"function formatDateMMDDYYYY(inputDate) {\n\t// Add 0 to Day or Month if < 10\n\tfunction pad(s) {\n\t\treturn (s < 10) ? '0' + s : s;\n\t}\n\n\tvar inputDate = new Date(inputDate);\n\tvar formatedDate = [ inputDate.getFullYear(),\n\t\t\tpad(inputDate.getMonth() + 1), pad(inputDate.getDate()) ].join(\"-\");\n\n\treturn formatedDate;\n}",
"function buildDateStamp(date) {\n if (date === void 0) { date = new Date(); }\n var year = \"\" + date.getFullYear();\n var month = (\"\" + (date.getMonth() + 1)).padStart(2, '0');\n var day = (\"\" + date.getDate()).padStart(2, '0');\n return [year, month, day].join('-');\n }",
"function dobArrange(dob) {\n var year = dob.slice(0, 4);\n var month = dob.slice(5, 7);\n var day = dob.slice(8, 10);\n var date = month + '/' + day + '/' + year;\n return date;\n}",
"function FormatDte4(dte)\n{\n\tdte+=\"\" \n\tvar year=\"\"\n\tvar month=\"\"\n\tvar day=\"\"\n\tyear=dte.substring(0,4)\n\tmonth=dte.substring(4,6)\n\tday=dte.substring(6,8)\n\t\t\n\tdte=month+\"/\"+day+\"/\"+year\n\treturn dte\n}",
"dateFormatYYMMDD(date) {\n const d = new Date(date);\n const day = d.getDate().toString().padStart(2, '0');\n const month = (d.getMonth() + 1).toString().padStart(2, '0');\n const year = d.getFullYear().toString().substr(-2);\n ;\n return `${year}${month}${day}`;\n }",
"function dateStringFormat (date) {\n return `${date.getFullYear()}${lpad1(date.getMonth()+1)}${lpad1(date.getDate())}`;\n }",
"function getFormatedDate_DDMMYYYY(date) {\n var year = date.getFullYear();\n var month = (date.getMonth() + 1);\n if (month < 10)\n month = '0' + month;\n var date = date.getDate();\n if (date < 10)\n date = '0' + date;\n\n var formatedDate = date + '-' + month + '-' + year;\n return formatedDate;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changer le titre de la page | function replace_titre_page() {
add_log(3,"replace_titre_page() > Début.");
var nouv_titre = "[" + document.title.split(" ")[1].toUpperCase() + "] " + var_divers['village_actif_nom'] + " (" + var_divers['village_actif_pos'][0] + "|" + var_divers['village_actif_pos'][1] + ")";
document.title = nouv_titre;
add_log(1,"replace_titre_page() > Nouveau titre : " + nouv_titre);
add_log(3,"replace_titre_page() > Fin.");
} | [
"function changeTitleEverywhereOnThePage(pageName, newTitle)\r\n{\r\n\t//get global title (20 = length of \"Заголовок сторінки: \")\r\n\tvar titlePrefix = $(\"[id $= '_title_label']\").html().substring(\"Заголовок сторінки: \".length, $(\"[id $= '_title_label']\").html().length);\r\n\t\r\n\t//change editor form data for next edits\r\n\t$(\"#pageTitle\").val(newTitle);\r\n\t//change page title (<title> tag)\r\n\tparent.document.title = titlePrefix + newTitle;\r\n}",
"function setTitle(page,text) {\n if (fhirVersion == 2) {\n page.name = text\n } else {\n page.title = text;\n }\n }",
"function titlePage(){\n\t\t$('.title-page').html('<h2 class=\"text-center\">'+objet_concours[last_concours]+'</h2>');\n\t}",
"function setPageTitle (newTitle) {\n title = newTitle;\n }",
"function setPageTitle() {\r\n document.querySelector('#title').innerText = pageTitle;\r\n}",
"function setPageTitle() {\n const title = document.getElementById('title');\n title.innerText = pageTitle;\n}",
"function modifyTitlePage() {\n $(\".jawBoneContainer\").each((_, container) => {\n const titleId = container.id;\n falcor.getTitleInfo(titleId).then(title => {\n !$(`.${SELECTORS.SEARCHES}`, container).length\n && $(\".jawBone\", container).prepend(NetflixTitle.makeSearchLinks($, title.title, title.releaseYear));\n\n modifyOverviewTab(container, title);\n })\n .catch(err => {\n console.error(\"TIN: could not fetch title data\", err);\n });\n });\n }",
"_updateTitle() {\n let ttl = '';\n if (this._curPage) {\n ttl = this._curPage.title()\n }\n document.title = this._rootArea.title(ttl);\n }",
"function replacePageTitle() {\n\t$('title').empty();\n\t$('title').append($( '.menu nav ul li.active-menu' ).text());\n}",
"function setPageTitle() {\n const title = document.querySelector('#title');\n title.innerText = pageTitle;\n}",
"function setPageTitle() {\n const thePageTitle = document.getElementById('title')\n thePageTitle.innerText = pageTitle;\n }",
"function setPageTitle() {\n const titleHTML = document.getElementById('title');\n titleHTML.innerText = pageTitle;\n}",
"function setPageTitle() {\n const titleElement = document.getElementById('title');\n titleElement.innerText = pageTitle;\n}",
"function updatePageTitle (title) {\n $('.js-page-title').html(title);\n}",
"function setCurrentPageTitle() {\n $('.nav-title').html(document.title);\n}",
"changeTitle() {\n one.title = 'Title Changed';\n }",
"function setPageTitle(path){\n var title = getTitle(path);\n\n if (title){\n $('title').text(title);\n } else {\n $('title').text(window.location.origin.split('/')[3]);\n }\n\n }",
"function updateTitle()\n{\n\tclearTitle();\n\taddTitle();\n}",
"function PINT_ChangePageTitle( pageTitle )\r\n\t{\r\n\tif(document.title.readOnly == true) document.title = pageTitle;\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the bidding history to find the first bid of a particular userID | function showFirstBid() {
var aBid;
var i=0;
var firstBidString="You have not placed a bid in this auction.";
var searchUserID=document.forms[0][2].value.toUpperCase();
var endOfBidHistory=auction.bidHistory.length==i;
var found=false;
while (!endOfBidHistory && !found) {
aBid=auction.bidHistory[i];
if (aBid.userID==searchUserID) {
found=true;
firstBidString=aBid.userID+"\t\t"+aBid.amt+"\r";
}
i++;
if (i==auction.bidHistory.length)
endOfBidHistory=true;
}
document.forms[0][6].value=firstBidString;
} | [
"function showFirstBidLogic() {\n\tvar aBid;\n\tvar i=0;\n\tvar firstBidString=\"You have not placed a bid in this auction.\";\n\tvar searchUserID=document.forms[0][2].value.toUpperCase();\n\tvar found=false;\n\t\n\twhile ((i!=auction.bidHistory.length) && !found) {\n\t\taBid=auction.bidHistory[i];\n\t\tif (aBid.userID==searchUserID) {\n\t\t\tfound=true;\n\t\t\tfirstBidString=aBid.userID+\"\\t\\t\"+aBid.amt+\"\\r\";\n\t\t}\n\t\ti++;\n\t}\n\n\tdocument.forms[0][6].value=firstBidString;\n}",
"async getLowestBid(ctx, auctionID){\n let {bids} = await ctx.stub.getState(auctionID);\n let lowestBid =bids[0]\n bids.forEach((bid)=>{if(bid['CostOfHire']>lowestBid['CostOfHire'])lowestBid=bid})\n return lowestBid\n }",
"function bidHistory(itemID){\n\tif(isEmpty(itemID) || itemID < 0){\n\t\t$(\"#itemName\").html(\"Error: itemID not present\");\n\t}\n\telse{\n\t\tvar response=$.ajax({\n\t\t\tasync: false,\n\t\t\turl: $.urldomain()+\"/bidhistory?useHTML5=1&itemID=\"+$.urlParam(\"itemID\"),\n\t\t\ttype: \"GET\",\n\t\t\tdataType: \"json\",\n\n\t\t\tsuccess:function(data) {\n\t\t\t\tif(!isEmpty(data)){\n\t\t\t\t\tif(!isEmpty(data.bids)){\n\t\t\t\t\t\tdatabase.loadBids(data.bids,itemID);\n\t\t\t\t\t}\n\t\t\t\t\tprintErrorsAndStats(data);\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\terror:function(jqXHR,textStatus,errorThrown){\n\t\t\t\talert(textStatus+\" , \"+errorThrown);\n\t\t\t}\n\t\t});\n\t}\n}",
"function hitTheBid () {\n // get bid price\n // place limit sell order at bid\n domInterface.getBestBid()\n .then((price) => {\n domInterface.placeSellOrder(price)\n })\n }",
"* bidAuction ({knownAmount, bidAmount, userToken, auctionId}) {\n\t\tyield* this.verifyAuction({auctionId});\n\n\t\tconst user = yield* this.dependencies.userService.getUserByToken(userToken);\n\n\t\tconst {_id: userId, username, avatarUrl} = user;\n\n\t\tconst now = Date.now();\n\n\t\tconst totalAmount = bidAmount + knownAmount;\n\n\t\tyield this.auctions.update({\n\t\t\t_id: ObjectId(auctionId),\n\t\t\t/* atomically check for this condition before write */\n\t\t\thighestBid: { $eq: knownAmount }\n\t\t}, {\n\t\t\t/* increase highestBid by bidSize */\n\t\t\t$inc: { highestBid: bidAmount },\n\n\t\t\t$push: {\n\t\t\t\t/* record bid */\n\t\t\t\tbids: {\n\t\t\t\t\tuserId,\n\t\t\t\t\tusername,\n\t\t\t\t\tbidAmount,\n\t\t\t\t\ttotalAmount,\n\t\t\t\t\tdate: now\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\treturn {\n\t\t\tauction: { auctionId },\n\t\t\tuser: { username, avatarUrl },\n\t\t\tbid: { bidAmount, totalAmount, date: now }\n\t\t};\n\t}",
"function findBid() {\n for (var i = 0; i < bidStructure.length; i++) {\n if (mData[post].revenue < bidStructure[i].cap) {\n bid = bidStructure[i].start;\n addBid = Math.round(bidStructure[i].bid / players.length);\n break;\n }\n }\n}",
"addBid(bid) {\n if (this._endTimestamp === null) {\n // This is the first bid in the auction.\n this._endTimestamp = bid.timestamp() + AUCTION_DURATION_MS;\n this._minBid = bid;\n } else if (bid.timestamp() < this._endTimestamp) {\n if ((bid.player() in this._bids) &&\n (this._bids[bid.player()].steps() <= bid.steps())) {\n // The player who made the current bid has already made a loweor bid.\n // So discard the current bid.\n return false;\n }\n } else {\n // This bid was made after the auction ended; so don't store it.\n return false;\n }\n\n // Store the bid for the player.\n this._bids[bid.player()] = bid;\n\n if (bid.steps() < this._minBid.steps()) {\n // Check if this bid is the minimum bid so far.\n this._minBid = bid;\n }\n\n return true;\n }",
"bid(user, amount) {\n\t\tthis.bidder = user;\n\t\tthis.amount = amount;\n\t\tthis.logEvent(user.display_name + ' bid '+amount);\n\t\tthis.bids = this.bids + 1;\n\t\tthis.room.emit('bid', {\n\t\t\tby : this.cleanPlayer(user),\n\t\t\tamount : amount,\n\t\t\tbidTime : this.startBidTimeout(),\n\t\t});\n\t}",
"static getUserGiftHistory(userID) {\n return __awaiter(this, void 0, void 0, function* () {\n const rawGiftHistory = yield Util.getJSON(`https://www.myanonamouse.net/json/userBonusHistory.php?other_userid=${userID}`);\n const giftHistory = JSON.parse(rawGiftHistory);\n // Return the full data\n return giftHistory;\n });\n }",
"function getBidInfo(bid,bidder){\n let better=(bid===PlayerGame.BID_RIK_BETER||bid===PlayerGame.BID_NEGEN_ALLEEN_BETER||bid===PlayerGame.BID_TIEN_ALLEEN_BETER||\n bid===PlayerGame.BID_ELF_ALLEEN_BETER||bid===PlayerGame.BID_TWAALF_ALLEEN_BETER||bid===PlayerGame.BID_DERTIEN_ALLEEN_BETER);\n if(better)bid--;\n switch(bid){\n case PlayerGame.BID_PAS:\n return(bidder?bidder+\" heeft gepast.\":\"Je hebt gepast.\");\n case PlayerGame.BID_RIK:\n return(bidder?bidder+\" heeft \":\"Je hebt \")+(better?\"beter \":\"\")+\" gerikt.\";\n case PlayerGame.BID_NEGEN_ALLEEN:\n return(bidder?bidder+\" wil negen slagen alleen halen.\":\"Je wilt negen slagen alleen halen.\");\n case PlayerGame.BID_TIEN_ALLEEN:\n return(bidder?bidder+\" wil tien slagen alleen halen.\":\"Je wilt tien slagen alleen halen.\");\n case PlayerGame.BID_ELF_ALLEEN:\n return(bidder?bidder+\" wil elf slagen alleen halen.\":\"Je wilt elf slagen alleen halen.\");\n case PlayerGame.BID_TWAALF_ALLEEN:\n return(bidder?bidder+\" wil twaalf slagen alleen halen.\":\"Je wilt twaalf slagen alleen halen.\");\n case PlayerGame.BID_DERTIEN_ALLEEN:\n return(bidder?bidder+\" wil\":\"Je wilt\")+\" dertien slagen alleen halen.\";\n case PlayerGame.BID_PICO:\n return(bidder?bidder+\" wil\":\"Je wilt\")+\" slechts een slag halen.\";\n case PlayerGame.BID_MISERE:\n return(bidder?bidder+\" wil\":\"Je wilt\")+\" geen enkele slag halen.\";\n case PlayerGame.BID_OPEN_MISERE:\n return(bidder?bidder+\" wil\":\"Je wilt\")+\" geen enkele slag halen met open kaarten.\";\n case PlayerGame.BID_OPEN_MISERE_MET_EEN_PRAATJE:\n return(bidder?bidder+\" wil\":\"Je wilt\")+\" geen enkele slag halen met een praatje en open kaarten.\";\n }\n return(bidder?bidder+\" heeft\":\"Je hebt\")+\" een ongeldig bod gedaan.\";\n}",
"_bidMade(bid){\n if(!this._game)return new Error(\"Geen spel om in te bieden!\");\n console.log(\"Passing bid \"+bid+\" of player '\"+this.name+\"' to the game!\");\n return this._game.bidMade(bid);\n }",
"makeABid(playerbids){\n // assumes that this player has made a bid before, or that this is the first bid\n // this default implementation assumes to be running in a browser so we can use prompt()\n // all other available bids should be better than the last bid by any other player\n let highestBidSoFar=PlayerGame.BID_PAS;\n if(playerbids){\n this.log(\"Player bids:\",playerbids);\n for(let player=0;player<playerbids.length;player++)\n if(playerbids[player].length>0&&playerbids[player][0]>highestBidSoFar)\n highestBidSoFar=playerbids[player][0];\n }\n this.log(\"Highest bid so far: '\"+PlayerGame.BID_NAMES[highestBidSoFar]+\"'.\");\n // if the highest possible bid is not a bid all can play (at the same time), can't be bid again\n if(PlayerGame.BIDS_ALL_CAN_PLAY.indexOf(PlayerGame.BID_NAMES[highestBidSoFar])<0)highestBidSoFar++;\n let possibleBidNames=PlayerGame.BID_NAMES.slice(highestBidSoFar);\n possibleBidNames.unshift(PlayerGame.BID_NAMES[PlayerGame.BID_PAS]); // user can always 'pas'\n this.log(\"Possible bids: \",possibleBidNames);\n let bid=-1;\n while(bid<0){\n let bidname=prompt(\"@\"+this.name+\" (holding \"+this.getTextRepresentation(true)+\")\\nWhat is your bid (options: '\"+possibleBidNames.join(\"', '\")+\"')?\",possibleBidNames[0]);\n bid=PlayerGame.BID_NAMES.indexOf(bidname);\n if(bid<0)continue;\n try{\n this._setBid(bid);\n }catch(error){\n console.error(error);\n bid=-1;\n }\n }\n }",
"function handleBid($throttle, $cost)\n {\n \n\n $throttle = ( $throttle === 0 ? 1 : $throttle ) * 30;\n\n logger.log('info',\n '[%s]: Bid for auction with id %s, for user %s scheduled with throttle %sms.',\n INSTANCE,\n $id,\n $userid,\n $throttle );\n\n setTimeout(async function() {\n\n \n \n // NEW CODE\n const isStillBlocked = await db.isStillBlocked($userid)\n const isStatusBlocked = await db.isStatusBlocked($userid) \n\n if((Array.isArray(isStillBlocked) && isStillBlocked.length) && (Array.isArray(isStatusBlocked) && isStatusBlocked.length)){\n self.sockets.emitUserGlobal($userid, 'ALREADY_WON');\n\n return\n }\n \n // if((isWinner.length > 0 || isWeekWinner.length >= 3 )){\n // self.sockets.emitUserGlobal($userid, 'ALREADY_WON');\n\n // return\n // }\n\n const lastBid = await db.getLastBid($id) \n if(lastBid[0] && $userid == lastBid[0].uid){\n self.sockets.emitUserGlobal($userid, 'CAN_NOT_BID');\n\n return\n }\n // NEW CODE\n\n if ( isNaN($id) )\n {\n logger.info('info',\n '[%s]: User with id %s tried to bid with %s as auction id.',\n INSTANCE,\n $userid,\n $id );\n\n return;\n }\n\n redisCl.get('AUCTION_CLOSED_' + $id, function(err, isClosed) {\n if ( isClosed )\n {\n logger.log('info',\n '[%s]: User with id %s tried to bid on auction with id %s but redis says the auction is closed, ignoring the bid request.',\n INSTANCE,\n $userid,\n $id );\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n return;\n }\n\n db.isAlreadyEnded($id).then(function ($ended) { // Check if the bid hasn't already ended\n db.isTimeEnded($id).then(function($isTimeEnded) {\n var bidTime = ( +($isTimeEnded[0].meta_value) - Math.floor(Date.now() / 1000) );\n\n if ( bidTime < 0 && !$autobid )\n {\n logger.log('info',\n '[%s]: Time left in database for auction with id %s is lower than 0, which means the auction is pending close, ignoring the bid request from user with id %s.',\n INSTANCE,\n $id,\n $userid );\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n return;\n }\n\n if ( $ended[0].meta_value == 0 )\n {\n q.allSettled([db.getUser($userid), db.getAuctionData($id)]).spread(async function ($user, $auction) {\n if ( $auction.value.length > 0 && $user.value.length > 0 )\n {\n \n var userName = $user.value[0].meta_value,\n userAvatarId = $user.value[3] ? $user.value[3].user_id : false,\n // userAvatarId = $user.value[3] ? $user.value[3].meta_value : false,\n userCountry = $user.value[2] ? $user.value[2].meta_value : false,\n userCredits = $user.value[1] ? Number($user.value[1].meta_value) : 0,\n auctionPriceIncrease = Number($auction.value[0].meta_value) || 1,\n auctionTimeLeft = $auction.value[1].meta_value - Math.floor(Date.now() / 1000),\n auctionMultiplier = Number($auction.value[4].meta_value) || 1,\n auctionCurrentBids = Number($auction.value[3].meta_value) || 0;\n\n var newTotal = ( auctionCurrentBids + auctionPriceIncrease ).toFixed(2);\n var autoBidsLeft = ( $autobid && $autobid_data.take_credits ) ? $autobid_data.credits_start - $autobid_data.credits_current : 0;\n\n if ( ( !$autobid ? ( userCredits >= auctionMultiplier ) : true )\n && ( $autobid ? ( $autobid_data.take_credits ? ( autoBidsLeft >= auctionMultiplier ) : true ) : true ) )\n {\n \n redisCl.get('AUCTION_CLOSED_' + $id, function(err, isClosed) {\n\n if ( isClosed )\n {\n logger.log('info',\n '[%s]: User with id %s tried to bid on auction with id %s but redis says the auction is closed, ignoring the bid request.',\n INSTANCE,\n $userid,\n $id );\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n return;\n }\n\n q.allSettled([userAvatarId ? db.getAvatar(userAvatarId) : null,\n takeCredits(auctionMultiplier),\n db.updateAuctionData($id, auctionPriceIncrease, (auctionTimeLeft < 15)), // Only change the time if less than 15 seconds\n db.insertBid($id, $userid, newTotal)])\n .spread(function ($avatar) {\n \n var userAvatar = $avatar.value != null ? $avatar.value[0].meta_value : \"\";\n \n if ( $autobid && $autobid_data && $autobid_data.take_credits )\n {\n /* code changes for _penny_assistant table */\n db.incrementCreditsCurrent($id, $userid, auctionMultiplier).then(function () {\n\n logger.log('info',\n '[%s]: User with id %s has auto bid on auction with id %s on %ss time left.',\n INSTANCE,\n $userid,\n $id,\n bidTime);\n\n self.sockets.emitUserGlobal($userid, 'AUTO_BID_OK', {\n id: $id,\n bids_left: autoBidsLeft,// - auctionMultiplier,\n credits: userCredits// - auctionMultiplier\n }, self.isMaster);\n\n });\n }\n else if ( $autobid && $autobid_data && !$autobid_data.take_credits )\n {\n logger.log('info',\n '[%s]: User with id %s has admin auto bid on auction with id %s on %ss time left.',\n INSTANCE,\n $userid,\n $id,\n bidTime);\n }\n else\n {\n logger.log('info',\n '[%s]: User with id %s has bid on auction with id %s on %ss time left.',\n INSTANCE,\n $userid,\n $id,\n bidTime);\n }\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, Number(auctionMultiplier), function(err, totalCreditsToBeUsed) {\n if ( err )\n {\n logger.log('error',\n '[%s]: Error occurred while incrementing user total bids credit count in redis: %s.',\n INSTANCE,\n err );\n\n return;\n }\n\n logger.log('info',\n '[%s]: Total credits that are still to be used for user with id %s: %s',\n INSTANCE,\n $userid,\n totalCreditsToBeUsed );\n });\n\n redisCl.decr('AUCTION_BIDS_IN_PROGRESS_' + $id, async function (err, bidsInProgress) {\n logger.log('info', '[%s]: Bids left in current auction queue: %s', INSTANCE, bidsInProgress);\n\n self.sockets.emitGlobal('NEW_BID', { // Tell the users there's a new bid and update the clients\n id: $id,\n time_left: (auctionTimeLeft < 15 ? 15 : auctionTimeLeft),\n bid_amount: newTotal,\n total: newTotal,\n name: userName,\n country: userCountry,\n avatar: userAvatar\n }, ['GLOBAL', 'AUCTION_' + $id], self.isMaster);\n\n //NEW CODE\n if (!$autobid){\n await db.decrementUserCredits($userid, auctionMultiplier)\n self.sockets.emitUserGlobal($userid, 'BID_OK', {\n credits: userCredits - auctionMultiplier\n }, self.isMaster);\n }\n //NEW CODE\n // self.sockets.emitUserGlobal($userid, 'BID_OK', {\n // credits: userCredits\n // }, self.isMaster);\n });\n });\n });\n }\n else\n {\n if ( $autobid && $autobid_data.take_credits )\n {\n /**\n * This is coming from an auto bid, and the user does\n * not have the bids anymore, pause the auto bid.\n */\n /* code changes for _penny_assistant table */\n db.pauseAutobid($id, $userid).then(function() {\n logger.log('info',\n '[%s]: Auto bid of user with id %s was paused as the last bid hasn\\'t passed due of low credits.',\n INSTANCE,\n $userid,\n $id );\n\n self.sockets.emitUserGlobal($userid, 'AUTO_BID_PAUSED', {\n id: $id\n }, ['AUCTION_' + $id], self.isMaster);\n });\n }\n else if ( !$autobid )\n {\n logger.log('info',\n '[%s]: User %s tried to bid on auction with id %s without having enough credits.',\n INSTANCE,\n $userid,\n $id );\n }\n\n redisCl.decr('AUCTION_BIDS_IN_PROGRESS_' + $id, noop);\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n }\n }\n else\n {\n redisCl.decr('AUCTION_BIDS_IN_PROGRESS_' + $id, function() {\n logger.log('info',\n '[%s]: User with id %s tried to bid on an auction with no data.',\n INSTANCE,\n $userid );\n });\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n }\n });\n }\n else\n {\n redisCl.decr('AUCTION_BIDS_IN_PROGRESS_' + $id, function() {\n logger.log('info',\n '[%s]: User with id %s tried to bid on an auction that has already closed.',\n INSTANCE,\n $userid );\n });\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n }\n });\n }, function (err) {\n redisCl.decr('AUCTION_BIDS_IN_PROGRESS_' + $id, function() {\n logger.log('error',\n '[%s]: Error while checking if auction has already ended: %s',\n INSTANCE,\n err );\n });\n\n redisCl.decrby('TOTAL_CREDITS_FOR_BIDS_IN_QUEUE_' + $userid, $cost, noop);\n });\n });\n }, $throttle );\n }",
"async bid(ctx, auctionID, costOfHire, driverName, truckNumber){\n let {origin,destination,bids} = await ctx.stub.getState(auctionID);\n let bid={}\n bid['CostOfHire']=costOfHire\n bid['DriverName']=driverName\n bid['TruckNumber']=truckNumber\n bids.push(bid)\n let auctionInfo = {origin,destination,bids}\n await ctx.stub.putState(auctionID, auctionInfo);\n console.info('Created bid');\n }",
"function bid(bid, item) {\n connection.query('UPDATE auctions SET ? WHERE ?', [{ current_bid: `${bid}` }, { item: `${item}` }], (err) => {\n if (err) { console.log(err) }\n if console.log(`New highest bid is set to ${}.`)\n })\n}",
"function _bid($player) {\n\t\t\t_resetStatuses();\n\n\t\t\tconst paState = _$pennyAuction.data(\"state\");\n\t\t\tif (paState.state == \"ended\") {\n\t\t\t\t$player.find(\".status\").text(\"Auction not started.\").addClass(\"error\");\n\t\t\t\t_refresh();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t_sendEth($player, _$pennyAuction).then(()=>{\n\t\t\t\tpaState.winner = $player;\n\t\t\t\tpaState.bidFees = paState.bidFees.plus(new BigNumber(.1));\n\t\t\t\t_$pennyAuction.find(\".status\").text(`Received .1 Eth`);\n\t\t\t\t$player.find(\".status\").text(`Sent .1 Eth`);\n\t\t\t\t_refresh();\t\n\t\t\t});\n\t\t}",
"function place_bid(auction_id, error_div, user_id, do_request, is_detail_page) {\r\n if (_bid_running == 1 && ((new Date()).getTime()-_last_bid_placed)<600) {\r\n return;\r\n }\r\n\r\n _last_bid_placed = (new Date()).getTime();\r\n\r\n _bid_running = 1;\r\n if (user_id == undefined || user_id == null || user_id == '') {\r\n user_id = 0;\r\n }\r\n\r\n if (do_request == undefined || do_request == null || do_request == '') {\r\n do_request = 0;\r\n }\r\n\r\n if (is_detail_page == undefined || is_detail_page == null || is_detail_page == '') {\r\n is_detail_page = 0;\r\n }\r\n\r\n\r\n // clean error div\r\n el = $(error_div);\r\n el2 = $(\"fehlerfeld_\" + auction_id);\r\n if (el2) {\r\n el2.style.display = \"none\";\r\n }\r\n if (el) {\r\n el.innerHTML = \"\";\r\n }\r\n/*\r\n var opt = {\r\n // Use POST\r\n //method: 'post',\r\n // Send this lovely data\r\n //postBody: escape('thisvar=true&thatvar=Howdy&theothervar=2112'),\r\n // Handle successful response\r\n //parameters:'aid=' + auction_id,\r\n onSuccess: function(t) {\r\n _bid_running = 0;\r\n if (t.responseText == \"OK\" || t.responseText == \"\") {\r\n force_single_bid_update(auction_id, user_id);\r\n update_bid_account();\r\n if (is_detail_page == 1) {\r\n// update_bid_agent(auction_id);\r\n }\r\n if (do_request == 1) {\r\n do_counter_request(auction_id, user_id);\r\n }\r\n } else {\r\n el = $(error_div);\r\n if (el) {\r\n el.innerHTML = t.responseText;\r\n }\r\n hidedisplay_fade(\"fehlerfeld_\" + auction_id);\r\n // window.setTimeout(\"hidedisplay_fade('fehlerfeld_\" + auction_id + \"', 1)\", 3000);\r\n }\r\n // TODO force update\r\n },\r\n // Handle 404\r\n on404: function(t) {\r\n alert('Error 404: location \"' + t.statusText + '\" was not found.');\r\n },\r\n // Handle other errors\r\n onFailure: function(t) {\r\n alert('Error ' + t.status + ' -- ' + t.statusText);\r\n }\r\n }\r\n*/\r\n url = '/ajax/place_bid.html?aid=' + auction_id;\r\n refreshDetails(url, 'place_bid_' + auction_id);\r\n\r\n window.setTimeout(\"update_savings_details(\" + auction_id + \",1)\", 1000);\r\n\r\n if (is_detail_page == 1) {\r\n _ct_force_update = 1;\r\n //do_counter_request(auction_id, user_id);\r\n }\r\n\r\n// new Ajax.Request('/ajax/place_bid.html?aid=' + auction_id, opt);\r\n}",
"async function getBrancheByUserId(userId) {\n return baseFetch(GET_BRANCH_BY_USER_ID(userId))\n}",
"function getBid(bidId) {\n return BidCollection.findById(bidId)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
change the slider Development Mode | function toogleSlider()
{
if($('#DevelopmentModeToggle .slider').hasClass('sliderRight')){
$('#DevelopmentModeToggle .slider').removeClass('sliderRight');
$('#DevelopmentModeToggle .slider').addClass('sliderLeft');
}
else{
$('#DevelopmentModeToggle .slider').removeClass('sliderLeft');
$('#DevelopmentModeToggle .slider').addClass('sliderRight');
}
} | [
"function drawingSwitchToSlideMode()\n{\n\tcurrentMode = SLIDE_MODE;\n\n\tvar tempDict;\n\n\tif (ROOT_NODE.hasAttribute(\"style\"))\n\t\ttempDict = propStrToDict(ROOT_NODE.getAttribute(\"style\"));\n\telse\n\t\ttempDict = new Object();\n\n\ttempDict[\"cursor\"] = \"auto\";\n\tROOT_NODE.setAttribute(\"style\", dictToPropStr(tempDict));\n}",
"function SliderActivation() {\n if (SliderEnabled == 1) {\n sliderButton.innerHTML = \"Slider [Disabled]\";\n } else {\n sliderButton.innerHTML = \"Slider [Enabled]\";\n }\n SliderEnabled ^= 1; // Toggles the value of SliderEnabled between 1 and 0\n}",
"function activateSlider(){\r\n if (!sliderActivated){\r\n sliderActivated = true;\r\n choice = slider.noUiSlider.get()[2];\r\n slidervis[2].style.display = 'block';\r\n prev = slider.noUiSlider.get();\r\n }\r\n }",
"function changeMode() {\n\tselectedMode = $('#mode-select').val();\n\t$(\"#slider\").slider(\"option\", \"value\", currentTimeValue);\n\tinitActivityData();\n}",
"function toggleDebug(){\n let debugScreen = app.stage.getChildByName(\"DebugScreen\");\n let button = debugScreen.getChildByName(\"DebugSwich\");\n if(DEBUG_MODE) {\n DEBUG_MODE = false;\n button.getChildByName(\"on\").visible = false;\n button.getChildByName(\"off\").visible = true;\n } else {\n DEBUG_MODE = true;\n button.getChildByName(\"on\").visible = true;\n button.getChildByName(\"off\").visible = false;\n }\n \n }",
"enableSlider () {\n if (this.slider.attr('disabled')) this.slider.attr('disabled', null)\n }",
"set presentationMode(value) {\n this.toggleClass('jp-mod-presentationMode', value);\n }",
"function switchThemeSlider() {\n if (toggleSwitch.checked) {\n swichToDark()\n } else {\n swichToLight()\n }\n}",
"function sliderDrawMode(val) {\n val = parseInt(val);\n drawMode = val;\n document.getElementById('range-drawmode').setAttribute('value', val.toString());\n document.getElementById('range-drawmode').value = val.toString();\n document.getElementById('td-drawmode').innerHTML =\n \"draw mode (<b>E</b>): \" + val.toString();\n}",
"function setSlider(fld,val,enable) {\r\n $(\"#slider-\"+fld).slider(\"option\", \"value\", val);\r\n $(\"#slider-\"+fld).slider(\"enable\");\r\n $(\"#sldrmsg-\"+fld).css('visibility','hidden');\r\n}",
"function updateRoomModeSlider(mode) {\n var slider = document.getElementById('mode-slider');\n var slides = slider.querySelectorAll('.slide');\n\n for(var i = 0; i < slides.length; i++) {\n var slideMode = slides[i].getAttribute('id');\n\n //Hide inactive slides\n if(slideMode !== mode) {\n slides[i].classList.add('hidden');\n }\n else {\n slides[i].classList.remove('hidden');\n }\n }\n}",
"function setSlider(fld,val,enable) {\r\n\t$(\"#slider-\"+fld).slider(\"option\", \"value\", val);\r\n\t$(\"#slider-\"+fld).slider(\"enable\");\r\n\t$(\"#sldrmsg-\"+fld).css('visibility','hidden');\r\n}",
"function changeSlider(brightness) {\n $('input[type=hidden]').val(brightness);\n $('input[name=slide]').val(brightness);\n}",
"function switchAudioComponentsToPreviewMode() {\n $('._audio_editor_component ._player_content').css('opacity', 1);\n $('.msie ._audio_editor_component ._double_slider .ui-slider-range').css('opacity', 1);\n $('._audio_editor_component').css('opacity', 0.2);\n $('._audio_editor_component ._remove').hide();\n $('._audio_editor_component ._media_player_slider .ui-slider-handle').hide();\n $('._audio_editor_component ._audio_component_icon').css('visibility', 'hidden');\n}",
"function toggleSliders(){\n $('param_radius_demand').style.visibility = (getTripType() == TYPE_OFFER) ? 'hidden' : 'visible';\n $('help_radius_demand_slider').style.visibility = (getTripType() == TYPE_OFFER) ? 'hidden' : 'visible';\n $('param_radius_offer').style.visibility = (getTripType() == TYPE_DEMAND) ? 'hidden' : 'visible';\n $('help_radius_offer_slider').style.visibility = (getTripType() == TYPE_DEMAND) ? 'hidden' : 'visible';\n}",
"function showDesktop(){\n document.getElementById('sliderMobile').style.display='none';\n document.getElementById('sliderDesktop').style.display='block';\n $('.slider').slick('setPosition'); \n $('#btn-mobile').removeClass('active');\n $('#btn-desktop').toggleClass('active');\n }",
"function switchToLive() {\n\n if(isPause){\n $(\"#pla i\").removeClass(\"fw-circle\");\n $(\"#pla i\").addClass(\"fw-right\");\n isPause=false;\n sliderPoint=sliderPointMin;\n }\n\n isLive = true;\n $(\".date-picker\").slideToggle(\"slow\");\n $('input[name=\"daterange\"]').val('');\n\n if (isDatePick) {\n isDatePick = false;\n $('#historical-view').addClass(\"hidden\");\n }\n\n $('#historic-toggle').removeClass(\"history\");\n $('#historic-toggle').addClass(\"live\");\n $('#live-view').removeClass(\"hidden\");\n\n setSlider(rangeSlider, sliderPointMin, sliderPointMax);\n handleData(sliderPointMax, floorData);\n}",
"function switchMode() {\n if (d3.select(\"#playMode\").attr(\"mode\") === \"auto\") {\n d3\n .select(\"#playMode\")\n .attr(\"mode\", \"manual\")\n .html(\"Manual Mode\");\n d3.select(\"#append_btn\").attr(\"disabled\", null);\n } else {\n d3\n .select(\"#playMode\")\n .attr(\"mode\", \"auto\")\n .html(\"Auto Mode\");\n d3.select(\"#append_btn\").attr(\"disabled\", true);\n autoAppend();\n }\n}",
"function openSlider(){\n $('.slider-ui').removeClass('hidden');\n $('.slider-ui').addClass('show');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
send an expression (or result of an advanced expression) to the input screen. | function addHistExprToScreen(expr){
var inputScreen = document.querySelector('.screen');
// extract inner expression from a square root expression and send the square root of that expression to the input screen.
if(expr.startsWith('sqrt(')){
var innerExpr = evaluateArgument(expr.substring(5, expr.length-1));
inputScreen.innerHTML = Math.sqrt(innerExpr);
}
// extract inner expression from a sine expression and send the sine of that expression to the input screen.
else if(expr.startsWith('sin(')){
var innerExpr = evaluateArgument(expr.substring(4, expr.length-1));
inputScreen.innerHTML = Math.sin(innerExpr);
}
// extract inner expression from a cosine expression and send the cosine of that expression to the input screen.
else if(expr.startsWith('cos(')){
var innerExpr = evaluateArgument(expr.substring(4, expr.length-1));
inputScreen.innerHTML = Math.cos(innerExpr);
}
// extract inner expression from a tangent expression and send the tangent of that expression to the input screen.
else if(expr.startsWith('tan(')){
var innerExpr = evaluateArgument(expr.substring(4, expr.length-1));
inputScreen.innerHTML = Math.tan(innerExpr);
}
// extract inner expression from a factorial expression and send the factorial of that expression to the input screen.
else if(expr.startsWith('(')){
var innerExpr = evaluateArgument(expr.substring(1, expr.length-2));
var evaluatedExpr = parseInt(innerExpr);
function factorial(num) {
if(num == 0) { return 1; }
return num * factorial(num-1);
}
inputScreen.innerHTML = factorial(evaluatedExpr);
}
// send a basic expression to the input screen
else{
inputScreen.innerHTML = expr;
startNew = false;
}
// re-enable operators
var elems = document.getElementsByClassName("operator");
for (var i = 0; i < elems.length; i++){
elems[i].classList.remove("disabled");
}
// disable factorial for numbers with decimal points and don't allow multiple decimal points in a number
if (inputScreen.innerHTML.contains(".")){
document.getElementById("factorial").classList.add("disabled");
document.getElementById("deci").classList.add("disabled");
}
} | [
"function display(answer) {\n\texpression.value = answer;\n}",
"function calculate(equation) {\n let answer = eval(equation);\n document.getElementById('screen').value = answer;\n}",
"function pressOperator(op) {\n terms[0] = num;\n terms[1] = op.value;\n showDisplay(op.value)\n num = '';\n}",
"function addNumberToScreen(val)\n{\n\tif(getExpression()==\"Expression\")\n\t\temptyExpression();\n\n\tif(getResult()!=\"Result\")\n\t{\t\n\t\tdocument.getElementById(\"equation\").innerText=\"\";\n\t\tdocument.getElementById(\"result\").innerText=\"Result\";\n\t\tdocument.getElementById(\"result\").style.color= \"#D5D8DC\";\n\t}\n\n\tdocument.getElementById(\"equation\").innerText+= val;\n}",
"enterDisplayOperand(ctx) {\n\t}",
"function evaluateExpression() {\r\n if (calculator.operator != null) {\r\n operation = getOperation(calculator.operator);\r\n result = operation(calculator.firstOperand, calculator.displayValue);\r\n addHistoryElement(\r\n calculator.firstOperand,\r\n calculator.displayValue,\r\n calculator.operator,\r\n result\r\n );\r\n updateHistory();\r\n calculator.displayValue = result;\r\n calculator.firstOperand = result;\r\n calculator.waitingForSecondOperand = true;\r\n }\r\n}",
"function enterOperand(){\n readline.question(\"Enter the operation (+-*/, q to quit):\", (symbol) => {operand(symbol)});\n}",
"function showOnScreen(input){\n output.html(input);\n }",
"function hitOperator(operator) {\n\tif (result != \"\") {\n\t\t\tmath_sentence = current_num.toString();\n\t}\n\n\t//if the last character in the math equation/sentence is already an operator, \n\t//\tthis statement removes that operator before displaying the clicked one\n\tif (math_sentence.slice(-1) == \"+\" || math_sentence.slice(-1) == \"-\"\n\t\t|| math_sentence.slice(-1) == \"*\" || math_sentence.slice(-1) == \"/\") {\n\t\tmath_sentence = math_sentence.slice(0,-1);\n\t\tconsole.log(math_sentence);\n\t}\n\n\tmath_sentence += operator;\n\t$(\"#history_screen\").text(math_sentence);\n\tcurrent_num = \"\";\n\tresult = \"\";\n}",
"function shownumber(number) \n{\n inputscreen.value += number; \n //concatenate our number,then assign it to the input screen \n //attribute value to display it.\n}",
"function evaluate() {\n var expression = document.getElementById(\"display-field\").value;\n try {\n if(expression && expression !== \"\") {\n var result = eval(expression);\n setDisplayField(\"display-field\", result);\n setDisplayField(\"prev-result\", expression + \"=\" + result)\n }else{\n //= is pressed without any key entry, then display 0\n setDisplayField(\"display-field\", 0);\n }\n } catch (e) {\n document.getElementById(\"prev-result\").value = expression + \" =ERROR\";\n }\n}",
"function askExpression(){\r\n console.log('please write a expression.\\n');\r\n var express = readlineSync.question('>> ');\r\n if(express === 'quit'){\r\n console.log(\"Bye! See you next time! \");\r\n return express;\r\n }else{\r\n express = express.replace(/\\s/g,\"\"); // replace space\r\n express = express.replace(/POW/g,'^'); //replace POW with ^\r\n\r\n express = express.match(/[1-9][0-9]*|[+*-/^%\\(\\)]/g); // a reqular expression which can match all numbers and operators in a input expression\r\n console.log(express);\r\n return express;\r\n }\r\n}",
"updateScreen() {\n this.currOperandTextElem.innerText = this.getDisplayNumber(this.currOperand)\n if(this.operation != null) {\n this.prevOperandTextElem.innerText = \n `${this.getDisplayNumber(this.prevOperand)} ${this.operation}`\n } else {\n this.prevOperandTextElem.innerText = ''\n }\n }",
"function typeOperator (event) {\n currentOperator = event.target.innerHTML\n textView.innerHTML = currentOperator\n num1 = Number(userInput.join(''))\n userInput = []\n}",
"function compute() {\r\n var expression = document.getElementById('output').innerText;\r\n\r\n //using eval() inbuilt function to evaluate expression.\r\n var answer = eval(expression);\r\n\r\n //stroring the expression entered into a variable so that it can be displyed on top of current answer.\r\n var prev_expression = document.getElementById('prev-output');\r\n prev_expression.innerText = expression;\r\n\r\n //clearing the screen so that the ans is displayed clearly and not attatched to the query entered.\r\n clear_screen();\r\n\r\n //calling 'display()' method to finally output the answer.\r\n display(answer);\r\n}",
"function button(operator) {\n //insert operator into expression box\n var currentExp = document.getElementById('txtExpr').value;\n var symbol = getSymbol(operator);\n\n if (currentExp == \"Input expression\" || symbol == \"\") {\n document.getElementById('txtExpr').value = symbol;\n } else {\n insertAtCaret(document.getElementById('txtExpr'), symbol);\n }\n}",
"function render() {\n\t$(\"#result\").text(calc.value);\n\t$(\"#working\").text(calc.equation.join(\" \") || \"---\");\n}",
"function askForOperator() {\r\n calcInterface.question('Enter operation (+-*/, q to quit): ', userInput => { \r\n calculateLogic(userInput); \r\n });\r\n}",
"printResult() {\n const resultString = document.querySelector(`${this.selector} .calc__result`);\n resultString.innerHTML = addSpace(this.result);\n this.display.action(resultString);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate DOM elements for variant selectors ============================================================ | function generateSelectors(product) {
var elements = product.options.map(function(option) {
return '<select name="' + option.name + '">' + option.values.map(function(value) {
return '<option value="' + value + '">' + value + '</option>';
}) + '</select>';
});
return elements;
} | [
"function generateDOMProductSelector(product) {\n $(`#product-${product.id} .product-variantSelector`).html(generateSelectors(product));\n }",
"function generateSelectors(product) {\n var elements = '';\n\n product.options.map(function(option) {\n elements +='<ul name=\"' + option.name + '\" class=\"' + option.name + ' ext-variant-selectors select\">';\n\n var count = 0;\n\n option.values.map(function(value) {\n count++;\n\n if(count == 1) {\n var active = 'v-active';\n } else {\n var active = '';\n }\n\n if (value.indexOf('Free') < 0) {\n elements += '<li value=\"' + value + '\" class=\"'+ active +'\">' + value + '</li>';\n }\n });\n\n elements += '</ul>';\n });\n\n return elements;\n}",
"function generateSelectors(product) {\n let elements = product.options.map((option) => {\n let optionsHtml = option.values.map((value) => {\n return `<option value=\"${value}\">${value}</option>`;\n });\n\n return `\n <select class=\"select\" name=\"${option.name}\">${optionsHtml}</select>\n `;\n });\n\n return elements;\n }",
"getProductNodes() {\n return document.querySelectorAll(this.selector)\n }",
"generateSelector() {\n /* root element cannot have a selector as it isn't a proper element */\n if (this.isRootElement()) {\n return null;\n }\n const parts = [];\n let root;\n for (root = this; root.parent; root = root.parent) {\n /* .. */\n }\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let cur = this; cur.parent; cur = cur.parent) {\n /* if a unique id is present, use it and short-circuit */\n if (cur.id) {\n const escaped = escapeSelectorComponent(cur.id);\n const matches = root.querySelectorAll(`#${escaped}`);\n if (matches.length === 1) {\n parts.push(`#${escaped}`);\n break;\n }\n }\n const parent = cur.parent;\n const child = parent.childElements;\n const index = child.findIndex((it) => it.unique === cur.unique);\n const numOfType = child.filter((it) => it.is(cur.tagName)).length;\n const solo = numOfType === 1;\n /* if this is the only tagName in this level of siblings nth-child isn't needed */\n if (solo) {\n parts.push(cur.tagName.toLowerCase());\n continue;\n }\n /* this will generate the worst kind of selector but at least it will be accurate (optimizations welcome) */\n parts.push(`${cur.tagName.toLowerCase()}:nth-child(${index + 1})`);\n }\n return parts.reverse().join(\" > \");\n }",
"function __swapSel_buildCode()\n{\n // Create main div\n obj_swapSel = document.createElement('div');\n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select';\n obj_swapSel.setAttributeNode(obj_attribute);\n \n // Create hidden fields container div an append it into main div\n obj_hiddenContainer = document.createElement('div');\n obj_attribute = document.createAttribute(\"id\");\n obj_attribute.nodeValue = this.id + '_selected_fields';\n obj_hiddenContainer.setAttributeNode(obj_attribute);\n obj_swapSel.appendChild(obj_hiddenContainer);\n \n // Create 'swap_select_all' div an append it into main div\n obj_all = document.createElement('div');\n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_all';\n obj_all.setAttributeNode(obj_attribute);\n obj_swapSel.appendChild(obj_all);\n \n // Create 'swap_select_available' p tag an append it into 'swap_select_all'\n obj_p = document.createElement('p');\n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_available';\n obj_p.setAttributeNode(obj_attribute);\n obj_all.appendChild(obj_p);\n \n // Create label an append it into p tag\n obj_label = document.createElement('label');\n obj_attribute = document.createAttribute(\"for\");\n obj_attribute.nodeValue = this.id + '_all';\n obj_label.setAttributeNode(obj_attribute);\n obj_p.appendChild(obj_label);\n \n // Create text node and append into label\n obj_text = document.createTextNode(this.languagesValues[\"AviableHeadline\"]);\n obj_label.appendChild(obj_text);\n \n // Create p tag an append it into 'swap_select_all'\n obj_p = document.createElement('p');\n obj_all.appendChild(obj_p);\n \n // Creaate select tag an append it into p tag\n obj_select = document.createElement('select');\n obj_attribute = document.createAttribute(\"id\");\n obj_attribute.nodeValue = this.id + '_all';\n obj_select.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"name\");\n obj_attribute.nodeValue = this.id + '_all';\n obj_select.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"size\");\n obj_attribute.nodeValue = this.size;\n obj_select.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"multiple\");\n obj_attribute.nodeValue = 'multiple';\n obj_select.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_select);\n \n // Add all option tags into select box\n for (i = 0; i < this.structure.length; i++)\n {\n // Create a option tag and append it into select box\n obj_optionTag = document.createElement('option');\n obj_attributeTag = document.createAttribute(\"value\");\n obj_attributeTag.nodeValue = this.structure[i][0];\n obj_optionTag.setAttributeNode(obj_attributeTag);\n \n obj_text = document.createTextNode(this.structure[i][1]);\n obj_optionTag.appendChild(obj_text);\n \n obj_select.ondblclick = function(e) {swapSel_switchItems(obj_selfRef, true, false);}\n \n obj_select.appendChild(obj_optionTag);\n }\n \n // Create 'swap_select_options' div an append it into main div\n obj_options = document.createElement('div');\n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_options';\n obj_options.setAttributeNode(obj_attribute);\n obj_swapSel.appendChild(obj_options);\n \n // Create p tag an append it into 'swap_select_options'\n obj_p = document.createElement('p');\n obj_options.appendChild(obj_p);\n \n // Save reference to this as a global var\n var obj_selfRef = this;\n \n \n // Create 'swap_select_options_all_right' a tag\n obj_a = document.createElement('a');\n obj_attribute = document.createAttribute(\"a\");\n obj_attribute.nodeValue = '#';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_a.onclick = function(e) {swapSel_switchItems(obj_selfRef, true, true);}\n obj_a.onkeydown = function(e) {\n if ((e.keyCode == 0) || (e.keyCode == 13)) swapSel_switchItems(obj_selfRef, true, false);\n }\n \n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_options_all_right';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"title\");\n obj_attribute.nodeValue = this.languagesValues[\"AssumeAllButtonTitleAttr\"];\n obj_a.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_a);\n \n // Create span tag and append it into a tag and append it into p tag\n obj_span = document.createElement('span');\n obj_text = document.createTextNode(this.languagesValues[\"AssumeAllButtonText\"]);\n obj_span.appendChild(obj_text);\n obj_a.appendChild(obj_span);\n \n // Create 'swap_select_options_right' a tag and append it into p tag\n obj_a = document.createElement('a');\n obj_attribute = document.createAttribute(\"a\");\n obj_attribute.nodeValue = '#';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_a.onclick = function(e) {swapSel_switchItems(obj_selfRef, true, false);}\n obj_a.onkeydown = function(e) {\n if ((e.keyCode == 0) || (e.keyCode == 13)) swapSel_switchItems(obj_selfRef, true, false);\n }\n \n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_options_right';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"title\");\n obj_attribute.nodeValue = this.languagesValues[\"AssumeButtonTitleAttr\"];\n obj_a.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_a);\n \n // Create span tag and append it into a tag and append it into p tag\n obj_span = document.createElement('span');\n obj_text = document.createTextNode(this.languagesValues[\"AssumeButtonText\"]);\n obj_span.appendChild(obj_text);\n obj_a.appendChild(obj_span);\n\n // Create 'swap_select_options_left' a tag\n obj_a = document.createElement('a');\n obj_attribute = document.createAttribute(\"a\");\n obj_attribute.nodeValue = '#';\n obj_a.setAttributeNode(obj_attribute); \n \n obj_a.onclick = function(e) {swapSel_switchItems(obj_selfRef, false, false);}\n obj_a.onkeydown = function(e) {\n if ((e.keyCode == 0) || (e.keyCode == 13)) swapSel_switchItems(obj_selfRef, true, false);\n }\n \n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_options_left';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"title\");\n obj_attribute.nodeValue = this.languagesValues[\"TakeBackButtonTitleAttr\"];\n obj_a.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_a);\n \n // Create span tag and append it into a tag and append it into p tag\n obj_span = document.createElement('span');\n obj_text = document.createTextNode(this.languagesValues[\"TakeBackButtonText\"]);\n obj_span.appendChild(obj_text);\n obj_a.appendChild(obj_span);\n \n // Create 'swap_select_options_all_left' a tag\n obj_a = document.createElement('a');\n obj_attribute = document.createAttribute(\"a\");\n obj_attribute.nodeValue = '#';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_a.onclick = function(e) {swapSel_switchItems(obj_selfRef, false, true);}\n obj_a.onkeydown = function(e) {\n if ((e.keyCode == 0) || (e.keyCode == 13)) swapSel_switchItems(obj_selfRef, true, false);\n }\n \n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_options_all_left';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"title\");\n obj_attribute.nodeValue = this.languagesValues[\"TakeBackAllButtonTitleAttr\"];\n obj_a.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_a);\n \n // Create span tag and append it into a tag\n obj_span = document.createElement('span');\n obj_text = document.createTextNode(this.languagesValues[\"TakeBackAllButtonText\"]);\n obj_span.appendChild(obj_text);\n obj_a.appendChild(obj_span);\n \n // Create 'swap_select_select' div an append it into main div\n obj_select = document.createElement('div');\n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_select';\n obj_select.setAttributeNode(obj_attribute);\n obj_swapSel.appendChild(obj_select);\n \n // Create 'swap_select_selected' p tag an append it into 'swap_select_select'\n obj_p = document.createElement('p');\n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_select_selected';\n obj_p.setAttributeNode(obj_attribute);\n obj_select.appendChild(obj_p);\n \n // Create label an append it into p tag\n obj_label = document.createElement('label');\n obj_attribute = document.createAttribute(\"for\");\n obj_attribute.nodeValue = this.id + '_selected';\n obj_label.setAttributeNode(obj_attribute);\n obj_p.appendChild(obj_label);\n \n // Create text node and append into label\n obj_text = document.createTextNode(this.languagesValues[\"SelectedHeadline\"]);\n obj_label.appendChild(obj_text);\n \n // Create p tag an append it into 'swap_select_all'\n obj_p = document.createElement('p');\n obj_select.appendChild(obj_p);\n \n // Create select tag an append it into p tag\n obj_select = document.createElement('select');\n obj_attribute = document.createAttribute(\"id\");\n obj_attribute.nodeValue = this.id + '_selected';\n obj_select.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"name\");\n obj_attribute.nodeValue = this.id + '_selected';\n obj_select.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"size\");\n obj_attribute.nodeValue = this.size;\n obj_select.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"multiple\");\n obj_attribute.nodeValue = 'multiple';\n obj_select.setAttributeNode(obj_attribute);\n \n obj_select.ondblclick = function(e) {swapSel_switchItems(obj_selfRef, false, false);}\n \n obj_p.appendChild(obj_select);\n \n // Create 'swap_selected_option_up' a tag and append it into p tag\n obj_a = document.createElement('a');\n obj_attribute = document.createAttribute(\"a\");\n obj_attribute.nodeValue = '#';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_a.onclick = function(e) {\n swapSel_move(obj_selfRef, -1);\n }\n \n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_selected_option_up';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"title\");\n obj_attribute.nodeValue = this.languagesValues[\"SwapSelectedOptionUp\"];\n obj_a.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_a);\n \n // Create 'swap_selected_option_down' a tag and append it into p tag\n obj_a = document.createElement('a');\n obj_attribute = document.createAttribute(\"a\");\n obj_attribute.nodeValue = '#';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_a.onclick = function(e) {\n swapSel_move(obj_selfRef, 1);\n }\n \n obj_attribute = document.createAttribute(\"class\");\n obj_attribute.nodeValue = 'swap_selected_option_down';\n obj_a.setAttributeNode(obj_attribute);\n \n obj_attribute = document.createAttribute(\"title\");\n obj_attribute.nodeValue = this.languagesValues[\"SwapSelectedOptionDown\"];\n obj_a.setAttributeNode(obj_attribute);\n \n obj_p.appendChild(obj_a);\n \n // Write tmp element to get parent\n document.write(\"<div id='\" + this.id + \"_tmp'></div>\");\n obj_parentNode = document.getElementById(this.id + '_tmp').parentNode;\n \n // Add swap select element to parent element\n obj_parentNode.appendChild(obj_swapSel);\n \n // Delete tmp element\n for (i = 0; i < obj_parentNode.childNodes.length; i++)\n {\n if ((obj_parentNode.childNodes[i].nodeType == 1) && (obj_parentNode.childNodes[i].nodeName.toLowerCase() == 'div') && (obj_parentNode.childNodes[i].id == this.id + '_tmp'))\n {\n obj_parentNode.removeChild(obj_parentNode.childNodes[i]);\n }\n }\n}",
"findViewElements() {\r\n this.testDiv = document.getElementById(\r\n getTestId(this.conditionId, this.id));\r\n this.cat1Select = document.getElementById(\r\n getTestCatId(this.conditionId, this.id, 1));\r\n this.option1Select = document.getElementById(\r\n getTestOptionId(this.conditionId, this.id, 1));\r\n this.typeSelect = document.getElementById(\r\n getTestTypeId(this.conditionId, this.id));\r\n this.cat2Select = document.getElementById(\r\n getTestCatId(this.conditionId, this.id, 2));\r\n this.option2Select = document.getElementById(\r\n getTestOptionId(this.conditionId, this.id, 2));\r\n }",
"function htmlStateSelectors(){\n for (i = 0; i < Object.keys(mats[0].matrixStates).length; i++) {\n var stateDiv = document.createElement(\"h2\");\n stateDiv.name = \"state\"+(i);\n stateDiv.id = i;\n var stateDivText = document.createTextNode(\"Layout \" + (i));\n stateDiv.appendChild(stateDivText);\n var element = document.getElementById(\"options\");\n element.appendChild(stateDiv);\n $('#'+(i)).click( objectAnimator ); \n }\n}",
"function buildVariantChoice(content, parent){\r\n\r\n let group = parent;\r\n \r\n\r\n for(let i in content){\r\n let choiceElement = document.createElement('option');\r\n choiceElement.setAttribute('value', content[i]);\r\n\r\n choiceElement.classList.add('col-12', 'text-orinoco', 'text-center', 'bg-primary');\r\n choiceElement.innerHTML = content[i];\r\n\r\n group.appendChild(choiceElement);\r\n }\r\n\r\n return group;\r\n}",
"findViewElements() {\r\n super.findViewElements();\r\n this.subCat1Select = document.getElementById(\r\n getTestSubCatId(this.conditionId, this.id, 1));\r\n this.ops1Input = document.getElementById(\r\n getTestOpsId(this.conditionId, this.id, 1));\r\n this.subCat2Select = document.getElementById(\r\n getTestSubCatId(this.conditionId, this.id, 2));\r\n this.ops2Input = document.getElementById(\r\n getTestOpsId(this.conditionId, this.id, 2));\r\n }",
"_buildDOMElements() {\n let containerElement = document.createElement('div');\n containerElement.id = this.id;\n containerElement.className = 'seelect-container';\n this.containerElement = containerElement;\n\n let selectedElement = document.createElement('div');\n selectedElement.className = 'seelect-selected';\n containerElement.appendChild(selectedElement);\n this.selectedElement = selectedElement;\n\n let placeholder = document.createElement('span');\n placeholder.className = 'seelect-placeholder';\n placeholder.innerText = this.dictionary.selectValue;\n this.placeholderElement = placeholder;\n this.selectedElement.appendChild(this.placeholderElement);\n\n this.selectedElement.appendChild(document.createElement('div'));\n\n if(!this.settings.disableAutocomplete) {\n let inputElement = document.createElement('input');\n inputElement.className = 'seelect-input';\n containerElement.appendChild(inputElement);\n this.inputElement = inputElement;\n }\n\n\n let dropdownElement = document.createElement('ul');\n dropdownElement.className = 'seelect-dd';\n this.dropdownElement = dropdownElement;\n containerElement.appendChild(dropdownElement);\n\n this._buildResults();\n\n if(this.settings.debug) {\n let debugElement = document.createElement('pre');\n debugElement.innerHTML = JSON.stringify(this.settings, undefined, 2);\n this.debugElement = debugElement;\n this.selectElement.parentNode.insertBefore(debugElement, this.selectElement);\n }\n this.selectElement.parentNode.insertBefore(containerElement, this.selectElement);\n\n }",
"_createDOMElements() {\n\t\tthis.$control = $( this.template( this.controlOptions ) );\n\t\tthis.$sliderGroup = this.$control.find( '.slider-group' );\n\t\tthis.$units = this.$control.find( '.unit' );\n\t\tthis.$revert = this.$control.find( '.undo' );\n\t\tthis.$deleteSaved = this.$control.find( '.delete-saved .remove' );\n\t}",
"function loadSelectors() {\n brandSelector();\n engineSelector();\n transmissionSelector();\n carBodiesSelector();\n drivesSelector();\n}",
"htmlFromSelector(selector, traversal, innerText = \"\", atts) {\n if (selector.startsWith('#') || selector.startsWith('.')) selector = 'div' + selector;\n const arr = [\n [/#([\\w-]+)/, ` id=\"$1\"`],\n [/((\\.[\\w-]+)+)/, (_, c) => ` class=\"${c.split`.`.join` `.trim()}\"`],\n [/(\\[.+?\\])/g, (_, a) => \" \" + a.slice(1, -1)],\n [/([\\S]+)(.*)/, `<$1$2 ${atts}>${innerText}${traversal}</$1>`]\n ].map((replacement) => {\n const regex = replacement[0];\n const str = replacement[1];\n selector = selector.replace(regex, str);\n return selector;\n }\n )[3];\n return arr;\n }",
"function createThemeSelector() {\r\n let custom_select = document.getElementsByClassName('select_theme')[0];\r\n custom_select.appendChild(createSelectHead());\r\n custom_select.appendChild(createSelectOptions());\r\n}",
"$(selector)\n {\n return this['el'].querySelectorAll(selector);\n }",
"function generateDom()\n{\n\t// Spirits and attached clues\n\tfor(key in spiritsClues){\n\t\t$(\"#spiritList\").append(\n\t\t\t'<div class=\"all-20 small-50 tiny-100 spiritBtn\" id=\"'+key+'\">'\n\t\t\t\t+'<span class=\"'+key+'\"></span><br />'\n\t\t\t\t+'<ul class=\"sclues\">'\n\t\t\t\t\t+'<li class=\"'+spiritsClues[key][0]+'\"></li>'\n\t\t\t\t\t+'<li class=\"'+spiritsClues[key][1]+'\"></li>'\n\t\t\t\t\t+'<li class=\"'+spiritsClues[key][2]+'\"></li>'\n\t\t\t\t+'</ul>'\n\t\t\t+'</div>'\n\t\t);\t \n\t}\n\tloadLang(navigator.language.replace('-', '_'));\n}",
"function fix_variant(form,sw)\n{\n eval (\"var ele = document.\" + form + \".\" + sw);\n eval (\"var list = variant_\" + sw);\n//alert(\"type of \" + sw + \" select = \" + ele.type);\n\n for ( i=0 ; i< list.length ; i++ ) {\n\tvar found = false;\n\n // for multi-select widgets, if nothing is selected, then enable all\n // variants.\n\n if ( ele.type == \"select-multiple\" ) {\n var numselected = 0;\n for ( opt = 0 ; opt<ele.options.length && !found ; opt++ ) {\n if ( ele.options[opt].selected ) {\n numselected++;\n for ( j=0 ; j<list[i][1].length && !found ; j++ ) {\n if ( ele.options[opt].value == list[i][1][j] ) {\n found = true;\n }\n }\n }\n }\n if ( numselected == 0 ) {\n found = true;\n }\n } else {\n for ( j=0 ; j<list[i][1].length && !found ; j++ ) {\n\t if ( ele.value == list[i][1][j] ) {\n\t\t found = true;\n\t }\n }\n\t}\n var id = document.getElementById(\"div_\" + form + \"_\" + list[i][0]);\n if ( id ) {\n if ( found ) {\n id.style.visibility = 'visible';\n } else {\n\t id.style.visibility = 'hidden';\n }\n\t}\n }\n\n}",
"function getWeightSelectors() {\n\tlet weightTitleSelector1 = new elemSelector(\"titletest\", getWeightTitleCond, verifyTitle);\n let weightNameSelector = new elemSelector(\"name\", getWeightName);\n let weightWeightSelector = new elemSelector(\"weight\", getWeightWeight);\n\treturn [weightTitleSelector1, weightNameSelector, weightWeightSelector];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
delete a specific supplier | deleteSupplier(params){
return Api().delete('/suppliers/' + params)
} | [
"function destroy(supplier_id) {\n // Unlike update() and insert(), del() does not accept any arguments\n return knex(\"suppliers\").where({ supplier_id }).del();\n}",
"function deleteSupplier(id) {\n results.style.display = \"none\";\n SupplierController.Delete(id, onDeleteSupplier);\n}",
"function removeSupplier(id)\n{\n\tif (confirm('<?php echo $this->__('Are you sure ?'); ?>'))\n\t{\n\t\t//définit l'url\n\t\tvar url = '';\n\t\turl = '<?php echo $this->getUrl('Purchase/Products/DeleteAssociatedSupplier', array('pps_id' => 'XXX')); ?>';\n\t\turl = url.replace('XXX', id);\n\t\t\n\t\t//Appel en ajax\n\t\tvar request = new Ajax.Request(url,\n\t\t {\n\t\t method:'get',\n\t\t onSuccess: function onSuccess(transport)\n\t\t \t\t\t{\n\t\t \t\t\t\t//Rafraichit la page\n\t\t\t\t\t\t\t\tRefreshAssociatedSuppliers();\n\t\t \t\t\t},\n\t\t onFailure: function onFailure() \n\t\t \t\t\t{\n\t\t \t\t\t\talert('error');\n\t\t \t\t\t}\n\t\t }\n\t );\n\t}\n}",
"function del(){\n $(\".supplier.delete\").click(function() {\n var supplierId = $(this).data('id');\n var section = $(this).data('section');\n\n if(confirm(BowsManager.copies.deleteSupplier)){\n $.ajax({\n url: \"/supplier-delete\",\n method: \"POST\",\n data: {id: supplierId},\n success: function(data) {\n if(data.success){\n // on bill list page so hide row\n if(typeof section == \"undefined\") {\n $(\"#supplier-\"+supplierId).fadeOut(\"slow\");\n }\n else {\n //on bill details page so return on collection details page\n window.location.href = '/supplier-list/'+section;\n }\n }\n else {\n $('.error-message.supplier').html(data.error);\n }\n }\n });\n }\n });\n }",
"deletePurchase(state, id) {\n var index = state.purchases.map(purchase => {\n return purchase.id\n }).indexOf(id)\n state.purchases.splice(index, 1)\n }",
"function setSupplier(request,supplier) {\n if(!request) {\n return;\n }\n\n //if supplier is null then delete existing supplier\n if(!supplier) {\n Issues.update(request._id,{$set:{\n assignee:null,\n supplier:null\n }});\n\n }\n //otherwise update supplier accordingly\n else {\n Issues.update(request._id,{$set:{\n assignee:null,\n supplier:{\n _id:supplier._id,\n name:supplier.name\n }\n }});\n }\n}",
"'click #delete'(event, instance) {\n \tPrimary.remove(this._id)\n }",
"function deleteOnePlant(deleteButton, plant, plantSoloCard){\n deleteButton.addEventListener(\"click\", (evt) => {\n deleteFetch(plant.id)\n .then((response) => {\n plantSoloCard.remove()\n divId = \"p\" + response.plant.id\n const imageDiv = plantCollection.querySelector(`div[data-id=\"${divId}\"]`)\n imageDiv.remove()\n plantCollection.classList.remove(\"hide\")\n genusButton.classList.remove(\"hide\")\n createButton.classList.remove(\"hide\")\n divDrop.classList.remove(\"hide\")\n })\n })\n}",
"function deleteChore (chore) {\n var choreIndex = $scope.choreList.indexOf(chore);\n\n $scope.choreList.splice(choreIndex, 1);\n ChoreList.save($scope.choreList);\n }",
"deleteParty(party) {\n this.party_list.pop(party);\n }",
"function removeSupplierInvoice(supplierinv_pk, supplierinv_name) {\n Ext.Msg.confirm('Delete ' + supplierinv_name, 'Are you sure you want to remove ' + supplierinv_name + ' from Your Suppliers Invoices', function(button) {\n\n if(button == 'yes') {\n Ext.Ajax.request({\n url: '/suppliers/removesupplierinvoice',\n method: 'POST',\n params: {\n supplierinv_key: supplierinv_pk,\n \n },\n\n success: function() {\n \n suppliersinvoice_store.reload() // usersstore has a global scope\n Ext.Msg.alert('Success', 'Successfully removed Supplier Invoice')\n },\n failure: function() {\n Ext.Msg.alert('Failed', 'Failed to remove Supplier Invoice')\n }\n\n });\n\n }\n\n });\n }",
"function delete_ship(id){\n const key = datastore.key([SHIP, parseInt(id,10)]);\n return datastore.get(key).then( result => {\n //Get the ship name to clear it from slip\n var ship = result[0];\n return ship.name;\n }).then(name => {\n //Clears slip if it contained deleted ship\n emptySlip(name)\n }).then( resp =>{\n //Delete the ship\n return datastore.delete(key);\n });\n}",
"_deleteTheChore() {\n const element = document.getElementById(this.chore.id);\n // Removes the element from the DOM\n element.remove();\n const choresArray = instanceOfChoreState.chores;\n const removeIndex = choresArray.map((item) => item.id).indexOf(element);\n // Removes it from the Array\n choresArray.splice(removeIndex, 1);\n }",
"function deleteGiveScholarship(index) {\n vm.giveScholarships.splice(index, 1);\n }",
"delete( req, res, next ) {\n\n Provider.deleteOne( {\n _id: req.params._id\n }, ( err, data ) => {\n if ( err ) {\n return res.status( 400 ).send( err );\n }\n\n return res.json( data );\n } );\n }",
"function deleteStock(e) {\n var indexToDelete = $(e.target).closest('div').index();\n var storedStock = storage.get();\n storedStock.splice(indexToDelete, 1);\n storage.set(storedStock);\n renderStored();\n\n }",
"delItem (identifier) {\n const dependents = this.dependents(identifier);\n\n dependents.forEach((dependent, index) => {\n this.items.splice(index, 1);\n });\n\n const index = this.items.findIndex(i => i.identifier === identifier);\n this.items.splice(index, 1);\n }",
"static deleteProvider(id) {\n return axios.delete(`${url}${id}`)\n }",
"deleteDriver(state, id) {\n const ind = findIndex(state.drivers, (r) => {\n return r.id === id\n })\n\n state.drivers.splice(ind, 1)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
callback allowing modification of newly created image objects | imageCreated(/* image */) {} | [
"addImage() {\n }",
"function setImageChanged() {\n imageChanged = true;\n}",
"imageProcessed(img, eventname) {\n console.log(img.hist);\n this.allpictures.insert(img);\n console.log(\"image processed \" + this.allpictures.stuff.length + eventname);\n if (this.allpictures.stuff.length === (this.num_Images * this.categories.length)) {\n this.createXMLColordatabaseLS();\n //this.createXMLIExampledatabaseLS();\n }\n }",
"updAviableImgs(image){\n image.isLoaded = true;\n }",
"function new_image(get_image)//get_image is a variable which is used to store a specific block image on a specific key press from fabric.js\r\n{\r\n fabric.Image.fromURL(get_image, function(Img) {\r\n block_image_object = Img;\r\n\r\n block_image_object.scaleToWidth(block_image_width);\r\n block_image_object.scaleToHeight(block_image_height);\r\n \r\n block_image_object.set({\r\n top:player_y,\r\n left:player_x\r\n });\r\n canvas.add(block_image_object);\r\n\r\n });\r\n\r\n}",
"function create_Images(){\n\n\n}",
"imageProcessed(img, eventname) {\n\t\tthis.allpictures.insert(img);\n\t\tconsole.log('image processed ' + this.allpictures.stuff.length + eventname);\n\t\tif (this.allpictures.stuff.length === this.num_Images * this.categories.length) {\n\t\t\talert('fim do processamento');\n\t\t\tthis.createXMLColordatabaseLS();\n\t\t\tthis.createXMLIExampledatabaseLS();\n\t\t}\n\t}",
"handleNewImageChange(i, event) {\n\t\tconst modifiedList = this.state.newImages\n\t\tmodifiedList[i][event.target.name] = event.target.value\n\t\tthis.setState({ newImages: modifiedList })\n\t}",
"function imageLoaded() {\n self.framed = self.createFramedImage(self.image, width, height);\n //self.framed = self.image;\n self.object = self.createRendererObject();\n if(self.prepareCallback) {\n self.prepareCallback(true);\n }\n }",
"function ModifyImage(image)\r\n{\r\n console.log(image);\r\n //Hiding the texteditor\r\n $(\"#imageEditor\").css({'bottom':\"-\"+$(\"#imageEditor\")[0].clientHeight+\"px\"});\r\n\r\n //Finding the index of the id\r\n console.log($(\"#imageEditor\").contents().find(\"#id_holder\")[0].value);\r\n var index = GetIndexOfByID($(\"#imageEditor\").contents().find(\"#id_holder\")[0].value);\r\n\r\n var str = $(image).attr(\"src\");\r\n str = str.substr(str.indexOf('/') + 2);\r\n\r\n //Setting up the new values\r\n console.log(\"Setto src dell'immagine: \" + str);\r\n modificableTagsValue[index] = str;\r\n\r\n //Saving the new files\r\n SaveModificableTagsArray();\r\n\r\n //Reloading the graphicalEditor\r\n $('#graphicalEditor').attr('src', $('#graphicalEditor').attr('src'));\r\n}",
"newImage(path) {\n\t\tlet idx = this.children.length;\n\t\tthis.addImage(this.generateId('image-' + idx), path, this.parent.left, this.parent.top, 'image ' + idx);\n\t}",
"_onImageAdd() {\n this._imageEditor.open(this._onEditorDone.bind(this));\n this._metaForm.open();\n }",
"function insertNewImage(img_width, img_height) {\r\n var newImage = svgCanvas.addSvgElementFromJson({\r\n \"element\": \"image\",\r\n \"attr\": {\r\n \"x\": 0,\r\n \"y\": 0,\r\n \"width\": 100,\r\n \"height\": 100,\r\n \"id\": svgCanvas.getNextId(),\r\n \"style\": \"pointer-events:inherit\"\r\n }\r\n });\r\n\r\n svgCanvas.setHref(newImage, e.target.result);\r\n svgCanvas.selectOnly([newImage]);\r\n svgCanvas.alignSelectedElements(\"m\", \"page\");\r\n svgCanvas.alignSelectedElements(\"c\", \"page\");\r\n\r\n $(newImage).attr(\"class\", \"ctype:graphic;\");\r\n // $(newImage).removeAttr(\"xlink:href\");\r\n //updateContextPanel();\r\n }",
"function newDraggedImage(img) {\n\n var id = 'img' + nextId;\n nextId++;\n\n createImage(img, 20, 20, id, 50);\n\n BR.assign(stage.find(id)[0]);\n\n layer.draw();\n\n\n }",
"function setImage(newLocation) {\r\n\r\n if(currentLocation<388){\r\n context.clearRect ( 0 , 0 , 670, 670 );\r\n context.drawImage(images[newLocation], 0, 0, 670, 670);\r\n }\r\n else {\r\n context.drawImage(images[388], 0, 0, 670, 670);\r\n }\r\n }",
"function onNewImage(e) {\n\n var eventData = e.detail;\n // If we are currently playing a clip then update the FPS\n // Get the state of the 'playClip tool'\n var playClipToolData = cornerstoneTools.getToolState(element, 'playClip');\n\n // If playing a clip ...\n if (playClipToolData !== undefined && playClipToolData.data.length > 0 && playClipToolData.data[0].intervalId !== undefined && eventData.frameRate !== undefined) {\n\n // Update FPS\n $(bottomLeft[0]).text(\"FPS: \" + Math.round(eventData.frameRate));\n } else {\n // Set FPS empty if not playing a clip\n if ($(bottomLeft[0]).text().length > 0) {\n $(bottomLeft[0]).text(\"\");\n }\n }\n\n var toolData = cornerstoneTools.getToolState(element, 'stack');\n if(toolData === undefined || toolData.data === undefined || toolData.data.length === 0) {\n return;\n }\n var stack = toolData.data[0];\n\t\tvar imageId=eventData.image.imageId;\n\t\tvar imageIndex=stack.imageIds.indexOf(imageId);\n \t\t// Update Image number overlay\n\t\t$(bottomLeft[2]).text(\"Image # \" + (imageIndex + 1) + \"/\" + stack.imageIds.length);\n\n }",
"static ReloadImages()\n {\n for (var i = 0; i < GImage.imageReloadList.GetSize(); i++)\n {\n GImage.imageReloadList.Get(i).SetImage(GImage.imageReloadList.Get(i).imageIndex);\n }\n \n }",
"function newImages() {\n setNewBG();\n removeShapes(container);\n removeShapes(clipPaths);\n removeShapes(triangleContainer);\n makeTriangles(getRandomInt(15), triangleContainer);\n makeCircles(getRandomInt(16), clipPaths);\n makeCircles(getRandomInt(8), container);\n basicXHR(containers);\n}",
"function ImageManager(){}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate element ancestors. Check if an element has the required set of elements. At least one of the selectors must match. | static validateAncestors(node, rules) {
if (!rules || rules.length === 0) {
return true;
}
return rules.some((rule) => node.closest(rule));
} | [
"function isAncestorOf(element, selector) {\n\n // If the element itself matches, then we're done already.\n if (element.matches(selector)) {\n return true;\n }\n\n // Ascend along the ancestor elements and check.\n // See https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType\n var parent = element.parentNode;\n while (parent && parent.nodeType && parent.nodeType === 1) {\n if (parent.matches(selector)) {\n return true;\n }\n parent = parent.parentNode;\n }\n return false;\n }",
"function getAncestors(node, selector){\n\n var ancestors = [];\n\n while(( node = node.parentElement )){\n if( node.matches(selector) ){ ancestors.push(node); }\n }\n return ancestors;\n}",
"parentsWhileMatch(selector) {\n const retArr = [];\n let parent = this.parent().filter(item => item.matchesSelector(selector));\n while (parent.isPresent()) {\n retArr.push(parent);\n parent = parent.parent().filter(item => item.matchesSelector(selector));\n }\n return new DomQuery(...retArr);\n }",
"function hasParentSelector(el, tag, classes)\n {\n tag = tag.toUpperCase();\n var found = false;\n while (el.parentNode && !found)\n {\n el = el.parentNode; // Check parent\n if (el && el.tagName == tag) {\n for (var i = 0; i < classes.length; i++)\n {\n if (!el.classList.contains(classes[i])) {\n break;\n }\n found = true; // Found = true if element has all classes\n break; // Break to while loop\n }\n }\n }\n return el;\n }",
"function checkElementsRecursive(el) {\n if (!el) return\n checkElementForCorona(el)\n const childs = el.children || []\n for (let n of childs)\n checkElementsRecursive(n)\n}",
"function checkElementsRecursive(el) {\n if (!el) return\n\n checkElementForCorona(el)\n const childs = el.children || []\n for (let n of childs) checkElementsRecursive(n)\n\n}",
"function checkRequiredParent(target, filterExpression) {\n //parents function return true if current element is child of any\n var res = filterExpression.split(',');\n var itemHasClass = false;\n var itemHasId = false;\n //search for either clicked item is required item\n for (var i = 0; i < res.length; i++) {\n //if found any one class than skip others\n if (!itemHasClass) {\n //remove . and # from string\n var className = res[i].replace('.', '').replace('#', '');\n itemHasClass = target.hasClass(className);\n }\n //if found a single id then skip others\n if (!itemHasId) {\n itemHasId = target.is(res[i]);\n }\n }\n //search for clicked item has required item as parent\n if (target.parents(filterExpression).length || itemHasClass || itemHasId) {\n //console.log('filterExpression found or item has it as a class');\n return true;\n } else {\n //console.log('filterExpression not found. other item');\n return false;\n }\n}",
"ancestors(selector,limit) {return this.parents(selector,limit)}",
"hasParent() {\n return this._ancestors.size() !== 0;\n }",
"function getValidatedAncestorsLength(ancestorArray) {\n\tlet len = ancestorArray.length;\n\tif (len < 2) {\n\t\tconsole.log(`ERROR: orderedItemsToDelete contains item <${ancestorArray[0]}> which is not of the form <ancestors.../child>`);\n\t\treturn null;\n\t}\n\treturn len;\n}",
"hasParent(...$p) {\n const tests = $p.map(p => p._el);\n let parent = this._el.parentNode;\n while (parent) {\n if (isOneOf(parent, ...tests))\n return true;\n parent = parent.parentNode;\n }\n return false;\n }",
"function findCommonAncestor(elements) {\n if (elements.length === 0) {\n throw new ReferenceError(\"Cannot get common ancestor of 0 nodes.\");\n }\n // this doesn't handle null nodes, so filter those out first\n elements = elements.filter((el) => el && $(el).parents().length);\n let xPathLists = elements.map((node) => toXPathNodeList(fromNode(node)));\n let firstXPathList = xPathLists[0];\n let i;\n for (i = 0; i < firstXPathList.length; i++) {\n let all_match = xPathLists.every((curXPathList) => curXPathList[i].nodeName === firstXPathList[i].nodeName &&\n curXPathList[i].index === firstXPathList[i].index &&\n curXPathList[i].iterable === firstXPathList[i].iterable);\n if (!all_match) {\n break;\n }\n }\n let last_matching = i - 1;\n let ancestor_xpath_list = firstXPathList.slice(0, last_matching + 1);\n let ancestor_nodes = getNodes(XPath.toString(ancestor_xpath_list));\n return ancestor_nodes[0];\n }",
"validateClassParameters(){\n\t\t// Ensure anchor, element are HTMLElements\n\t\t['element', 'anchor'].forEach(node=>{\n\t\t\tif(!(this[node] instanceof HTMLElement)){\n\t\t\t\tthrow new Error(node+\" must be instance of HTMLElement\");\n\t\t\t}\n\t\t});\n\t\t// Ensure all containers are HTMLElements\n\t\tthis.containers.forEach(container=>{\n\t\t\tif(!(container instanceof HTMLElement)){\n\t\t\t\tthrow new Error(\"containers must be instances of HTMLElement\");\n\t\t\t}\n\t\t});\n\t\t// Ensure Element is in a continaer\n\t\tif(!this.isInContainer(this.element)){\n\t\t\tthrow new Error(\"element must be contained within container.\");\n\t\t}\n\t\t// Ensure anchor is within element\n\t\tif(!this.element.contains(this.anchor) && this.element !== this.anchor){\n\t\t\tthrow new Error(\"anchor must be contained within element.\");\n\t\t}\n\t}",
"function checkSubStructure( rootDesc ) {\n\n let match = false;\n let extraInserted = false;\n let missingElement = false;\n\n // compare rootDesc and curNode - nextSibling curNode until a match is found\n while( !match && curNode != null ) {\n // TODO: Test if last node is checked!\n if( compareTag( rootDesc, curNode) ) {\n console.log(\"Match between %o and %o\", rootDesc, curNode );\n firstmatchfound = true;\n match = true;\n } else {\n // if first match has been found - check if required element is missing!\n if( firstmatchfound ) {\n console.log(\"something wrong after first!\");\n // ekstra element inserted ...\n if( curNode.nextElementSibling != null && compareTag( rootDesc, curNode.nextElementSibling ) ) {\n console.log(\"Extra element inserted between required\");\n extraInserted = true;\n }\n else\n // an element might be missing - check if this one matches the next descriptor\n if( rootDesc.nextSibling != null && compareTag( rootDesc.nextSibling, curNode )) {\n missingElement = true;\n console.log(\"Required element missing: \", rootDesc);\n break;\n }\n else {\n // TODO: Figure out what this is! . might be multiple extranous elements ...\n console.log(\"Something else...\");\n curNode = curNode.nextElementSibling;\n }\n }\n\n if( !firstmatchfound || extraInserted ) {\n curNode = curNode.nextElementSibling;\n }\n }\n }\n\n if( !match ) {\n // FIX: If HTML is missing required element - but has the next one, we will never know\n console.log(\"Never found match for %o\", rootDesc);\n // Mark as incorrect\n markAsIncorrect(rootDesc);\n\n } else {\n // Mark as correct\n markAsCorrect(rootDesc);\n // Correct!\n // if rootDesc has children, check those\n if( rootDesc.children != undefined ) {\n let lastNode = curNode;\n curNode = curNode.firstElementChild;\n rootDesc.children.forEach( desc => checkSubStructure(desc) );\n curNode = lastNode;\n }\n\n // finally, move curNode to the nextSibling\n // curNode = curNode.nextElementSibling;\n }\n\n if( match ) {\n curNode = curNode.nextElementSibling;\n }\n\n}",
"parents(selector) {\n const result = [];\n let parent = this.parent;\n while (parent) {\n if (!selector || parent.is(selector))\n result.push(parent);\n parent = parent.parent;\n }\n return result;\n }",
"function initAncestorEventListeners() {\n var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),\n i, a;\n if( watch ) {\n watch = parseInt( watch, 10 );\n i = 0;\n a = el.parentNode;\n while( a && ( watch === 'NaN' || i++ < watch ) ) {\n addListener( a, 'onpropertychange', ancestorPropChanged );\n addListener( a, 'onmouseenter', mouseEntered );\n addListener( a, 'onmouseleave', mouseLeft );\n addListener( a, 'onmousedown', mousePressed );\n if( a.tagName in PIE.focusableElements ) {\n addListener( a, 'onfocus', focused );\n addListener( a, 'onblur', blurred );\n }\n a = a.parentNode;\n }\n }\n }",
"function hasAncestor(dataName, elem, parentOfBoth) {\n let parent = elem.parentElement;\n\n while (parent != parentOfBoth) {\n if (isInvalid(parent)) return false;\n if (parent.dataset[dataName] !== undefined) break;\n parent = parent.parentElement;\n }\n return parent.dataset[dataName] !== undefined ? parent : false;\n }",
"requiredElementsPresent() {\n let allElementsPresent = true;\n\n const requiredElements = get(this, 'requiredElements');\n\n if (isPresent(requiredElements)) {\n /* istanbul ignore next: also can't test this due to things attached to root blowing up tests */\n requiredElements.forEach((element) => {\n const selectedElement = document.querySelector(element.selector);\n\n if (allElementsPresent && (!selectedElement || elementIsHidden(selectedElement))) {\n allElementsPresent = false;\n set(this, 'errorTitle', element.title);\n set(this, 'messageForUser', element.message);\n }\n });\n }\n return allElementsPresent;\n }",
"function hasAncestor(l, ance) {\n var tick,\n ancestor,\n ancestors = [1, 2, 3, 4, 5];\n\n if (typeof ance === 'string') {\n ancestor = queryDOM(ance);\n } else {\n ancestor = ance;\n }\n\n ancestors[0] = l.parentNode;\n ancestors[1] = ancestors[0].parentNode;\n\n if (!!ancestors[1].parentNode) {\n ancestors[2] = ancestors[1].parentNode;\n }\n if (!!ancestors[2].parentNode) {\n ancestors[3] = ancestors[2].parentNode;\n }\n if (!!ancestors[3].parentNode) {\n ancestors[4] = ancestors[3].parentNode;\n }\n //For inspection....\n // var dir = {};\n // dir.ance = ance;\n // dir.l = l;\n // dir.ancestor = ancestor;\n // dir.ancestors = ancestors;\n //\n // console.log(dir);\n\n tick = 0;\n\n for (var i = 0; i < ancestors.length; i++) {\n if (ancestors[i] === ancestor) tick++;\n }\n if (tick > 0) return true;else return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the interactions from a scene and keep it in common variable | function LoadInteractions() {
ReadCSV("CurrentIntro", CurrentChapter, CurrentScreen, "Intro", GetWorkingLanguage());
ReadCSV("CurrentStage", CurrentChapter, CurrentScreen, "Stage", GetWorkingLanguage());
LoadText();
} | [
"function loadScene() {\n var obj = pullGet();\n if (obj) {\n loadFromObject(obj);\n }\n}",
"interact() {\n if (this.currentInteractive instanceof Book) {\n //var text = this.scene.add.bitmapText(this.x,this.y + 100, 'editundo', this.currentInteractive.formattedText);\n game.scene.add('BookScene', Scene_book, true, {text: this.currentInteractive.formattedText});\n game.scene.start('BookScene');\n this.scene.events.emit('changeTooltip', \"Q to close\");\n this.scene.scene.pause();\n this.scene.matter.world.pause();\n }\n else if (this.currentInteractive instanceof Lever) {\n //console.log(\"pull lever\")\n this.currentInteractive.activate();\n }\n else {\n this.currentInteractive.activate();\n }\n }",
"loadScene() { }",
"function load() {\n scene.add(new Floor(80, 2));\n scene.add(new Axis(82));\n scene.load('../../common/models/geometries/cone3.json', 'cone');\n}",
"function initScene() {\n\n\tspeech.text = \" \";\n\tspeechSynthesis.speak(speech); // workaround for allowing us to use text to speech at a later stage without needing another click event\n\t\n\tdocument.querySelector('.modal:not(.hide)').classList.add('hide'); // hide current view\n\tdocument.body.classList.add('playing'); // present sceneview\n\t\n\tfetch(\"scene.json\") // load scene data\n\t .then(response => response.json())\n\t .then(json => playScene(json));\n}",
"function add_electron_excited_state_to_scene() {\n\n // Creates the Electron's Excited State's Orbit\n create_electron_excited_state_orbit();\n\n // Creates the Electron's Excited State\n create_electron_excited_state();\n\n\n // Loads the JSON data file of the Electron's Excited State Element\n load_electron_excited_state_json(function(response) {\n\n // Parses Electron's Excited State's JSON string into object\n var electron_excited_state_data_json = JSON.parse(response);\n\n // Loads the Property Keys' data of\n // the JSON data file of the Electron's Excited State Element\n electron_excited_state_property_keys = Object.keys(electron_excited_state_data_json);\n\n // Binds the Property Keys' data of\n // the JSON data file of the Electron's Excited State Element to\n // the Mesh of the Electron's Excited State\n for(i = 0; i < electron_excited_state_property_keys.length; i++)\n electron_excited_state_mesh[electron_excited_state_property_keys[i]] = electron_excited_state_data_json[electron_excited_state_property_keys[i]];\n\n });\n\n\n // Loads the JSON data file of the Electron's Quantum Superposition of States Element\n load_electron_superposition_json(function(response) {\n\n // Parses Electron's Quantum Superposition of States' JSON string into object\n var electron_excited_superposition_data_json = JSON.parse(response);\n\n // Loads the Property Keys' data of\n // the JSON data file of the Electron's Quantum Superposition of States Element\n electron_excited_superposition_property_keys = Object.keys(electron_excited_superposition_data_json);\n\n // Binds the Property Keys' data of\n // the JSON data file of the Electron's Quantum Superposition of States Element to\n // the Mesh of the Electron's Excited State\n for(i = 0; i < electron_excited_superposition_property_keys.length; i++)\n electron_excited_state_mesh[ (electron_ground_state_property_keys.length + electron_ground_superposition_property_keys) [i]] = electron_excited_superposition_data_json[electron_excited_superposition_property_keys[i]];\n\n });\n\n\n // Creates the group for the Electron's Excited State's Pivot\n electron_excited_state_pivot = new THREE.Group();\n\n // Adds the Mesh of the Electron's Excited State to\n // the group for the Electron's Excited State's Pivot\n electron_excited_state_pivot.add(electron_excited_state_orbit_mesh);\n\n // Adds the Mesh of the Electron's Excited State Particle's Pivot to\n // the group for the Electron's Excited State's Pivot\n electron_excited_state_pivot.add(electron_excited_state_particle_pivot);\n\n // Adds the group for the Electron's Excited State Pivot to\n // the Scene (Bohr's Atom Model) \n bohr_atom_model_scene.add(electron_excited_state_pivot);\n\n}",
"function add_elements_to_scene() {\n\n add_nucleus_proton_to_scene();\n add_electron_ground_state_to_scene();\n add_electron_excited_state_to_scene();\n\n}",
"function interact() {\n\n raycaster.ray.origin.copy(controls.getObject().position);\n raycaster.ray.direction.copy(controls.getObject().rotation)\n raycaster.far = 10;\n raycaster.ray.intersectHidden = true;\n raycaster.setFromCamera(mouse, camera);\n var intersections = raycaster.intersectObjects(scene.children)\n for (var i = 0; i < intersections.length; i++) {\n switch (intersections[i].object.name) {\n case \"album\":\n if (ambientMusicPlaying) {\n pauseAmbientAudio();\n } else {\n playAmbientAudio();\n }\n\n break;\n case \"musicBoxTrig\":\n if (ambientMusicPlaying) {\n pauseAmbientAudio();\n musicBoxMusic.play();\n } else if (musicBoxMusic.isPlaying) {\n musicBoxMusic.stop();\n\n } else {\n musicBoxMusic.play();\n }\n break;\n case \"piano\":\n if (ambientMusicPlaying) {\n pauseAmbientAudio();\n pianoScale.play();\n } else if (musicBoxMusic.isPlaying) {\n pianoScale.stop();\n\n } else {\n pianoScale.play();\n }\n break;\n case \"spotLight\":\n if (lampSpotLight.intensity == 1) {\n lampSpotLight.intensity = 0;\n } else {\n lampSpotLight.intensity = 1;\n }\n break;\n }\n }\n}",
"function notesInteractionsLoadNotes() \n{\n notesLoad();\n}",
"get scenes() {}",
"LoadSceneAdditive(key)\n {\n this.scene.launch(key);\n this.scene.bringToTop(this.ui_key);\n\n this.ui_scene = this.scene.get(this.ui_key);\n this.ui_scene.mainScene = this;\n }",
"function sceneManager () {\n switch (scene) {\n case \"titleScreen\":\n // scene = \"introScene\";\n // touchToContinue();\n break;\n \n\n case \"intro\":\n displayText = grammar.flatten(\"#opening#\");\n // touchToContinue();\n backgroundAudio(\"play\");\n displayText = textFilter(displayText);\n scene = \"sceneOne\";\n break;\n \n\n case \"sceneOne\":\n continueButton.hide();\n userInput();\n displayText = grammar.flatten(\"#sceneOne#\");\n displayText = textFilter(displayText);\n scene = \"questionOne\";\n break;\n\n case \"sceneTwo\":\n displayText = grammar.flatten(\"#sceneThree#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneThree\";\n break;\n \n case \"sceneThree\":\n displayText = grammar.flatten(\"#sceneFour#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneFour\";\n break;\n\n case \"sceneFour\":\n displayText = grammar.flatten(\"#sceneFive#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneFive\";\n break;\n\n case \"sceneFive\":\n continueButton.hide();\n input.show();\n displayText = grammar.flatten(\"#questionFour#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"questionFour\";\n break;\n\n case \"sceneSix\":\n displayText = grammar.flatten(\"#sceneSeven#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneSeven\";\n break;\n\n case \"sceneSeven\":\n displayText = grammar.flatten(\"#sceneEight#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneEight\";\n break;\n\n case \"sceneEight\":\n displayText = grammar.flatten(\"#sceneNine#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneNine\";\n break;\n\n case \"sceneNine\":\n displayText = grammar.flatten(\"#sceneTen#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"sceneTen\";\n break;\n\n case \"sceneTen\":\n displayText = grammar.flatten(\"#endingOne#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText += \"\\n\" + \"\\n\" + \"Run\";\n displayText = textFilter(displayText);\n scene = \"endingOne\";\n break;\n\n case \"endingOne\":\n displayText = grammar.flatten(\"#endingTwo#\");\n wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText += \"\\n\" + \"\\n\" + \"GET OUT NOW\";\n displayText = textFilter(displayText);\n scene = \"endingTwo\";\n break;\n\n case \"endingTwo\":\n continueButton.hide();\n input.show();\n displayText = grammar.flatten(\"#endingQuestion#\");\n // wholeStory += displayText + \"\\n\" + \"\\n\";\n displayText = textFilter(displayText);\n scene = \"endingQuestion\";\n break;\n\n case \"endingThree\":\n continueButton.hide();\n saveStoryButton();\n displayText = grammar.flatten(\"#endingFour#\");\n displayText = textFilter(displayText);\n // wholeStory += displayText + \"\\n\" + \"\\n\";\n // scene = \"endingFour\";\n break;\n\n case 6:\n displayText = grammar.flatten(\"#dreamSequence#\");\n scene = 7;\n break;\n\n case 7:\n continueButton.hide();\n displayText = grammar.flatten(\"#beginning#\");\n saveStoryButton();\n break;\n\n case 50:\n displayText = grammar.flatten(\"#warning#\");\n scene = 51;\n break;\n\n case 51:\n displayText = grammar.flatten(\"#warning.capitalize#\");\n scene = 52;\n break;\n\n case 52:\n displayText = grammar.flatten(\"#warning.capitalizeAll#\");\n scene = 53;\n break;\n \n default:\n }\n }",
"function SceneLoader() {}",
"function _setObjectivesAndInteractions() {\n var pages = ScormManager.dataForLMS.pages;\n var exercises = ScormManager.dataForLMS.exercises;\n\n //**********************\n //create Objectives\n _.forEach(pages, function (page) {\n var status_12 = 'not attempted'; //'passed'|'completed'|'failed'|'incomplete'|'browsed'|'not attempted'\n var success_status_2004 = 'unknown'; //'passed', 'failed', 'unknown'\n var completion_status_2004 = 'unknown'; //'completed', 'incomplete', 'not attempted', 'unknown'\n\n if (page.passed) {\n status_12 = 'passed';\n success_status_2004 = 'passed';\n completion_status_2004 = 'completed'\n }\n\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.id', 'chapter_' + page.chapter + '_' + page.id);\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.score.raw', page.result);\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.status', status_12);\n\n //SCORM2004-------------------------------\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.success_status', success_status_2004);\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.completion_status', completion_status_2004);\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.progress_measure', page.result);\n scormWrapper.doLMSSetValue('cmi.objectives.' + i + '.description', page.title);\n });\n\n //**********************\n //create Interactions\n _.forEach(exercises, function (exercise) {\n scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.id', 'chapter_' + exercise.chapter + '_page_' + pages[tasks[i].page].id + '_task_' + i);\n scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.type', 'numeric');\n scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.result', exercise.data.result);\n scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.weighting', '1');\n\n\n //TODO: неясно зачем назначать objectives для interaction\n //scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.objectives.' + i + '.id', 'chapter_'+pages[tasks[i].chapter]+'_'+pages[tasks[i].page].id);\n\n //SCORM2004-------------------------------\n scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.description', pages[exercise.page].title);\n\n //TODO: interaction types & learner_responses\n //scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.type', pages[i].tasks[j].data.type);\n //scormWrapper.doLMSSetValue('cmi.interactions.' + i + '.learner_response', pages[i].tasks[j].data.learner_response);\n });\n }",
"get AfterSceneLoad() {}",
"function Scene_Load() {\n this.initialize.apply(this, arguments);\n}",
"function add_elements_to_scene() {\n\n // Adds the Atom's Nucleus\n add_atom_nucleus_to_scene();\n \n // Adds the Atom's Particles' States and Orbits\n add_atom_orbit_state_to_scene_1();\n add_atom_orbit_state_to_scene_2();\n add_atom_orbit_state_to_scene_3();\n add_atom_orbit_state_to_scene_4();\n\n}",
"function reloadInteractions($url) {\n $('#create-interaction-modal-button').button('loading');\n Loading('interactions-widget', false);\n $('#interaction-view').load($url);\n}",
"function preload() {\n clickablesManager = new ClickableManager('data/clickableLayout.csv');\n adventureManager = new AdventureManager(\"data/adventureStates.csv\", \"data/interactionTable.csv\", \"data/clickableLayout.csv\");\n\n // Load clickable images for instructions\n instructions1 = loadImage('assets/instructions/instructions1.png');\n instructions2 = loadImage('assets/instructions/instructions2.png');\n instructions3 = loadImage('assets/instructions/instructions3.png');\n interactBox = loadImage('assets/interact.png');\n\n // Load clickable images for sexy room\n sexyDialogue1 = loadImage('assets/sexroom/dialogue1.png')\n sexyDialogue2 = loadImage('assets/sexroom/dialogue2.png')\n sexyDialogue3 = loadImage('assets/sexroom/dialogue3.png')\n sexyPornBlack = loadImage('assets/sexroom/pornblack.png');\n\n // Load clickable images for hetero room\n hetDialogue1 = loadImage('assets/hetroom/dialogue1.png')\n hetDialogue2 = loadImage('assets/hetroom/dialogue2.png')\n hetDialogue3 = loadImage('assets/hetroom/dialogue3.png')\n\n // Load sprite animations\n spriteFrontIdle = loadAnimation('assets/sprite/em_spritefront1.png', 'assets/sprite/em_spritefront2.png');\n spriteLeftIdle = loadAnimation('assets/sprite/em_spriteleftstand1.png', 'assets/sprite/em_spriteleftstand2.png');\n spriteRightIdle = loadAnimation('assets/sprite/em_spriterightstand1.png', 'assets/sprite/em_spriterightstand2.png');\n spriteBackIdle = loadAnimation('assets/sprite/em_spriteback1.png', 'assets/sprite/em_spriteback2.png');\n spriteFrontWalk = loadAnimation('assets/sprite/em_spritefrontwalk1.png', 'assets/sprite/em_spritefront1.png',\n 'assets/sprite/em_spritefrontwalk2.png', 'assets/sprite/em_spritefront1.png');\n spriteLeftWalk = loadAnimation('assets/sprite/em_spriteleft1.png', 'assets/sprite/em_spriteleftstand1.png',\n 'assets/sprite/em_spriteleft2.png', 'assets/sprite/em_spriteleftstand1.png');\n spriteRightWalk = loadAnimation('assets/sprite/em_spriteright1.png', 'assets/sprite/em_spriterightstand1.png',\n 'assets/sprite/em_spriteright2.png', 'assets/sprite/em_spriterightstand1.png');\n spriteBackWalk = loadAnimation('assets/sprite/em_spritebackwalk1.png', 'assets/sprite/em_spriteback1.png',\n 'assets/sprite/em_spritebackwalk2.png', 'assets/sprite/em_spriteback1.png');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stack limit checks only occur for Kernel mode and are either a yellow warning trap after instruction completion, or a red abort which stops the current instruction. | function stackCheck(virtualAddress) {
"use strict";
if (!CPU.mmuMode) { // Kernel mode 0 checking only
if (virtualAddress <= CPU.stackLimit || virtualAddress >= 0xfffe) {
if (virtualAddress + 32 <= CPU.stackLimit || virtualAddress >= 0xfffe) {
CPU.displayPhysical = -1; // Set ADRS ERR light
CPU.CPU_Error |= 4; // Red stack
CPU.registerVal[6] = 4;
return trap(4, 38);
}
CPU.CPU_Error |= 8; // Yellow
CPU.trapMask |= 4;
}
}
return virtualAddress;
} | [
"function stackCheck(virtualAddress) {\n \"use strict\";\n if (!CPU.mmuMode) { // Kernel mode 0 checking only\n if (virtualAddress <= CPU.stackLimit || virtualAddress >= 0xfffe) {\n if (virtualAddress + 32 <= CPU.stackLimit || virtualAddress >= 0xfffe) {\n CPU.CPU_Error |= 4; // Red stack\n CPU.registerVal[6] = 4;\n return trap(4, 38);\n }\n CPU.CPU_Error |= 8; // Yellow\n CPU.trapMask |= 4;\n }\n }\n return virtualAddress;\n}",
"function setStackTraceLimit(){if(Error.stackTraceLimit<100){// Also tests that we won't set the property if it doesn't exist.\nError.stackTraceLimit=100;}}",
"function setStackTraceLimit() {\n if (Error.stackTraceLimit < 100) {\n Error.stackTraceLimit = 100;\n }\n}",
"function setStackTraceLimit() {\n if (Error.stackTraceLimit < 100) {\n Error.stackTraceLimit = 100;\n }\n }",
"function setStackTraceLimit() {\n if (Error.stackTraceLimit < 100) {\n Error.stackTraceLimit = 100;\n }\n }",
"kCheckstack(n) {\n var newstack = this._freereg + n;\n if (newstack > this._f.maxstacksize) {\n if (newstack >= Lua_1.Lua.MAXSTACK) {\n this._ls.xSyntaxerror(\"function or expression too complex\");\n }\n this._f.maxstacksize = newstack;\n }\n }",
"toggleWarnings() {\n if (this.limit) {\n this.limit = undefined;\n } else {\n this.limit = this.defaultLimit;\n }\n }",
"function disableStack() {\n Object.defineProperty(global, '__stack', {\n get: function () {\n return null;\n }\n });\n}",
"overflowForGlobal(cpu, memory) {\n let overflow = false;\n\n _.forEach(this.nodesLimits, (value) => {\n if (cpu > value.CPU || memory > value.Memory) {\n overflow = true;\n }\n });\n\n return overflow;\n }",
"enterHandlerConditionWarning(ctx) {\n\t}",
"function overflowThreshold() {\n let prefs = require(\"preferences-service\");\n return prefs.get(OVERFLOW_THRESH_PREF, OVERFLOW_THRESH_DEFAULT);\n }",
"enterBadBinConstant(ctx) {\n\t}",
"canPush() {\n return this.stackControl.length !== this.MAX_SIZE;\n }",
"function MinStack() {}",
"async function rateLimitCheck() {\n numRequests ++;\n if (numRequests % 100 !== 0) {\n return\n }\n const rateLimit = (await octokit.misc.getRateLimit({})).data.rate\n if (rateLimit.remaining < 150) {\n const timeToSleep = (rateLimit.reset + 5) * 1000 - Date.now()\n const timeToSleepInMinutes = Math.floor((timeToSleep / 1000 / 60) * 100) / 100\n console.log(`Out of requests! Sleeping for ${timeToSleepInMinutes} minutes`)\n await new Promise((res) => setTimeout(res, timeToSleep))\n }\n else {\n console.log(`${rateLimit.remaining} requests remaining. Continue`)\n }\n}",
"exitLimitSpec(ctx) {\n\t}",
"exitAlter_overflow_clause(ctx) {\n\t}",
"function enoughOperands(stack) {\n if (stack < 2) {\n return false;\n } else {\n return true;\n }\n}",
"ensureLimitIsUnderThreshold() {\n\t\tif (this.hasLimit()) {\n\t\t\tconst { threshold, config: { limit } } = this;\n\n\t\t\tconst sizeLimit = this.fileHelper.parseSize(limit);\n\t\t\tconst sizeThreshold = this.fileHelper.parseSize(threshold);\n\n\t\t\tif (sizeLimit > sizeThreshold) {\n\t\t\t\tthrow new TypeError(`Size limit of [${limit}] is over maximum threshold of [${threshold}]`);\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
===================RABBITMQ============================= Set up and start rabbit mq | function start() {
amqp.connect(config.rabbit.url, function (err, conn) {
if (err) {
return setTimeout(start, 1000);
}
conn.on("error", function (err) {
if (err.message !== "Connection closing") {
}
});
conn.on("close", function () {
return setTimeout(start, 1000);
});
amqpConn = conn;
whenConnected();
});
} | [
"async start() {\n try {\n const conn = await this.createConnection();\n console.log(\"Connected to RabbitMQ\");\n this.channel = await conn.createChannel();\n await this.channel.assertExchange(RABBITMQ_EXCHANGE, \"direct\", {\n durable: false,\n });\n let queue = await this.channel.assertQueue(RABBITMQ_QUEUE, {\n durable: true,\n });\n await this.channel.bindQueue(\n queue.queue,\n RABBITMQ_EXCHANGE,\n RABBITMQ_ROUTING_KEY\n );\n } catch (err) {\n console.log(\"RabbitMQ Connection Error:\", err.message);\n }\n }",
"function startRabbitMQ() {\n\tapp.rMQconnection = amqp.createConnection({host : 'localhost', port : 5672, login : 'cplsyx', password : 'cplsyx'});\n\tapp.rMQconnection.on('ready', function() {\n\t\t//app.exchange = connection.exchange('');\n\t\tapp.webQueue = app.rMQconnection.queue('updateWeb', {durable : true, autoDelete: false});\n\t\tapp.webQueue.bind('#'); //# means all messages on the queue\n\t\tapp.webQueue.subscribe(function (message) {\n\t\t\t/*io.emit('send:message', {\n\t\t\t\tuser: \"Rabbit\",\n\t\t\t\ttext: message.data.toString('utf8')\n\t\t\t});*/\n\t\t\t//app.rMQconnection.publish('updateDevice', message.data.toString('utf8')); //This works but leaving it here results in a send/receive loop!\n\t\t\tconsole.log(message.data.toString('utf8'));\n\t\t});\n\t\n\n\t});\nconsole.log(\"...\");\n}",
"function setupAmqpExchange() {\n var exchangeOpts = {\n type: 'fanout'\n };\n\n amqpConn.exchange('munin', exchangeOpts, function(exchange) {\n console.log('Exchange ' + exchange.name + ' set up, starting publishing.');\n setInterval(publishTime, 100, exchange);\n }); // set up a munin exchange\n}",
"function connectRabbit() {\n\n console.log(`Connecting to RabbitMQ server at ${RABBIT}.`);\n\n return amqp.connect(RABBIT) // Connect to the RabbitMQ server.\n .then(messagingConnection => {\n console.log(\"Connected to RabbitMQ.\");\n\n return messagingConnection.createChannel(); // Create a RabbitMQ messaging channel.\n });\n}",
"function connectRabbit() {\n\n console.log(`Connecting to RabbitMQ server at ${RABBIT}.`);\n\n return amqp.connect(RABBIT) // Connect to the RabbitMQ server.\n .then(connection => {\n console.log(\"Connected to RabbitMQ.\");\n\n return connection.createChannel(); // Create a RabbitMQ messaging channel.\n });\n}",
"function connectRabbit() {\n\n console.log(`Connecting to RabbitMQ server at ${RABBIT}.`);\n\n return amqp.connect(RABBIT) // Connect to the RabbitMQ server.\n .then(connection => {\n console.log(\"Connected to RabbitMQ.\");\n\n return connection.createChannel() // Create a RabbitMQ messaging channel.\n .then(messageChannel => {\n return messageChannel.assertExchange(\"viewed\", \"fanout\") // Assert that we have a \"viewed\" exchange.\n .then(() => {\n return messageChannel;\n });\n });\n });\n}",
"async init () {\n try {\n this.mqInstance.on('disconnected', () => {\n this._log('info', 'Disconnected from MQ. Stop listening for events')\n this.mqInstance.reconnect()\n })\n\n this.mqInstance.on('connected', async (connection) => {\n this.setConnection(connection)\n this._log('info', 'Connected to MQ, initializing topics')\n })\n\n this.mqInstance.on('reconnected', async (connection) => {\n this.setConnection(connection)\n this._log('info', 'ReConnected to MQ, initializing topics')\n await this._startEventListeners()\n })\n\n this.mqInstance.on('error', (err) => {\n this._log('error', 'Connection error', err)\n throw err\n })\n\n this._log('info', 'Connecting to RabbitMQ')\n var connection = await this.mqInstance.connect()\n this.setConnection(connection)\n await this._startEventListeners()\n\n return connection\n }\n catch (err) {\n this._log('error', err)\n throw err\n }\n }",
"function setupAmqpQueue(exchange) {\n console.log('Exchange ' + exchange.name + ' is open');\n\n var queueOpts = {\n exclusive: true\n };\n\n // Create a randomly-named queue in the context of this exchange. This queue is exclusive to this connection.\n amqpConn.queue('', queueOpts, function(queue) {\n console.log('Queue ' + queue.name + ' is open');\n queue.bind(exchange, '#');\n subscribeToAmqpQueue(queue);\n });\n}",
"async init(){\n this.connection = await amqp.connect('amqp://localhost')\n console.log(\"CONECTADO\")\n this.channel = await this.connection.createChannel()\n console.log(\"CANALIZADO\")\n }",
"function initQueues(connection) {\n var optsTask = config.rabbitmq.tasks;\n var optsAutoTask = config.rabbitmq.autoTasks;\n log.debug('initQueues')\n var def = q.defer();\n exchange = def.promise;\n\n connection.createChannel().then(function (ch) {\n async function phonegapMessages(msg) {\n try {\n var message = JSON.parse(msg.content.toString());\n await processMessage(message);\n } catch (err) {\n log.error(`can't process ${err.message}`)\n }\n ch.ack(msg);\n }\n var ok = ch.assertQueue(optsTask.name, optsTask);\n ok = ok.then(function (qok) {\n return ch.prefetch(30).then(function () {\n return qok.queue;\n });\n });\n ok = ok.then(function (queue) {\n return ch.consume(queue, phonegapMessages, {noAck: false});\n });\n });\n\n connection.createChannel().then(function (ch) {\n var ok = ch.assertExchange(optsAutoTask.name, optsAutoTask.type, optsAutoTask);\n ch.on('close', function () {\n def.reject();\n });\n return ok.then(function () {\n def.resolve(ch);\n });\n });\n}",
"async function initQueue() {\n sails.log.verbose('sails-hook-resque starting initialize resque queue');\n // Setup resque queue\n const queue = new NR.Queue(\n {\n connection: config.connection\n },\n jobs\n );\n\n queue.on('error', function(error) {\n sails.log.error(error);\n });\n\n try {\n await queue.connect();\n sails.resque.queue = queue;\n sails.log.verbose('sails-hook-resque Queue service initalized');\n } catch (err) {\n sails.log.error('sails-hook-resque failed initializing queue.', err);\n }\n }",
"function rabbitConnect() {\n return amqp.connect(BROKER_URL)\n .catch((err)=> {\n return rabbitConnect();\n });\n}",
"function connectRabbit(rabbitHost) {\n\n // console.log(`Connecting to RabbitMQ server at ${rabbitHost}.`);\n\n return amqp.connect(rabbitHost) // Connect to the RabbitMQ server.\n .then(messagingConnection => {\n // console.log(\"Connected to RabbitMQ.\");\n\n return messagingConnection.createChannel(); // Create a RabbitMQ messaging channel.\n });\n}",
"function startConsumer() {\n // amqpConn.createChannel creates a channel on the connection\n amqpConn.createChannel(function(err, ch) { \n if (closeOnErr(err)) return;\n\n ch.on(\"error\", function(err) {\n console.error(\"[AMQP] channel error\", err.message); \n });\n\n ch.on(\"close\", function() { \n console.log(\"[AMQP] channel closed\"); \n });\n \n ch.prefetch(10); \n\n // creates a queue if it does not already exist\n ch.assertQueue(\"jobs\", { durable: true }, function(err, _ok) {\n if (closeOnErr(err)) return; \n\n //ch.consume sets up a consumer with a callback to be invoked with each message it receives.\n ch.consume(\"jobs\", processMsg, { noAck: false }); \n console.log(\"Worker is started\"); \n });\n\n function processMsg(msg) { \n work(msg, function(ok) { \n try {\n if (ok) ch.ack(msg);\n else \n ch.reject(msg, true); \n } catch (e) { \n closeOnErr(e); \n } \n });\n } \n });\n}",
"function startpubRMQartist() {\n amqp.connect(config.amqpURL, function(err, conn) {\n if (err) {\n console.error(\"[AMQP ARTIST]\", err.message);\n return setTimeout(startpubRMQartist, 1000);\n }\n conn.on(\"error\", function(err) {\n if (err.message !== \"Connection closing\") {\n console.error(\"[AMQP ARTIST] conn error\", err.message);\n }\n });\n conn.on(\"close\", function() {\n console.error(\"[AMQP ARTIST] reconnecting\");\n return setTimeout(startpubRMQartist, 1000);\n });\n console.log(\"[AMQP ARTIST] connected\");\n amqpConn = conn;\n addArtistPub('addArtistQueue');\n editArtistphotoPub('editArtistphotoQueue');\n deleteArtistPub('deleteArtistQueue');\n });\n}",
"async init(host) {\r\n\r\n //#region parameter Description:\r\n /* \r\n -host : this refer to the rabbitMQ Server that we want to connect to\r\n */\r\n //#endregion\r\n \r\n if (!validateHost(host)) {\r\n\r\n throw new Error('Invalid Host Format of RabbitMQ');\r\n }\r\n\r\n try {\r\n\r\n const connection = await amqplib.connect(host);\r\n\r\n const channel = await connection.createChannel();\r\n\r\n channel.prefetch(1);\r\n\r\n console.log(' [x] Awaiting RPC requests');\r\n\r\n this.connection = connection; \r\n \r\n this.channel = channel;\r\n } \r\n\r\n catch (err) {\r\n\r\n console.error(err);\r\n\r\n }\r\n }",
"function RabbitMq(options) {\n\n const _options = R.reject(\n R.isNil\n , { name : options.name\n , durable : R.defaultTo(true, options.durable)\n , prefetch : R.defaultTo(1, options.prefetch)\n , deadLetterExchange : options.deadLetterExchange\n , messageTtl : options.messageTtl\n }\n )\n\n return {\n listen : listen.bind(null, options.channel, _options)\n , ack : ack.bind(null, options.channel)\n }\n}",
"function startRMQ(res){\n var args = process.argv.slice(2);\n amqp.connect('amqp://localhost', function(error0, connection) {\n if (error0) {\n throw error0;\n }\n connection.createChannel(function(error1, channel) {\n if (error1) {\n throw error1;\n }\n channel.assertQueue('controller_queue', {\n }, function(error2, q) {\n if (error2) {\n throw error2;\n }\n console.log(' [*] Waiting for logs. To exit press CTRL+C');\n args.forEach(function(severity) {\n channel.bindQueue(q.queue, exchange, severity);\n });\n channel.consume(q.queue, function(msg) {\n let ids = msg.content.toString().split(\" \");\n const sock = res.io;\n Project.find({_id : ids[0]})\n .exec()\n .then((result)=>{\n let y = 0;\n while((y<result[0]['data'].length)&&(result[0]['data'][y]['tweetID']!==ids[1])){\n y++;\n }\n if(y<result[0]['data'].length){\n console.log(\"sending message\");\n let returnObject = {\n tweetText: result[0]['data'][y]['tweetObject']['text'],\n tweetSentiment: result[0]['data'][y]['tweetSentiment']\n };\n sock.emit(\"datasend\", returnObject);\n }else if(ids[1]==\"/t\"){\n console.log(\"termination character\");\n }\n })\n setTimeout(() => {\n sock.disconnect();\n }, 4788000);\n\n }, {\n noAck: true\n });\n });\n });\n });\n}",
"function connect(){\n return rabitMQ.connect(\"amqp://localhost\")\n .then(conn => conn.createChannel())\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check buffer length regularly and apply various policies to avoid buffering | _checkBuffer() {
const EPS = 1e-3;
if (this.config.isLive) {
// Live stream, try to maintain buffer between 3s and 8s
// TODO make 3s and 8s configurable
let currentBufferEnd = this.getCurrentBufferEnd();
if (typeof currentBufferEnd === 'undefined') {
// QUICKFIX:
// if getCurrentBuffereEnd() is undefined, check if currentTime is in a gap,
// and if it is jump to the latest buffered area
const buffered = this.video.buffered;
const lenBuffered = buffered.length;
if (lenBuffered > 0
&& buffered.start(lenBuffered - 1) > this.video.currentTime + EPS) {
// In a gap, jump to latest buffered area
Log.verbose('currentTime being in no-data GaP detected. Jumping to '
+ buffered.start(lenBuffered - 1));
this.video.currentTime = buffered.start(lenBuffered - 1);
currentBufferEnd = buffered.end(lenBuffered - 1);
} else {
// Not in a gap, noop
return;
}
}
const buffered = currentBufferEnd - this.video.currentTime;
if (this._lastBufferd != null) {
const changePlaybackRate = (toRate) => {
Log.verbose('Change playback rate from ' + this.video.playbackRate + ' to ' + toRate + ', buffered:' + buffered);
this.video.playbackRate = toRate;
this.realtimeBeaconBuilder.playbackSpeedChanged(toRate);
};
if (this.video.playbackRate < 1 - EPS) {
// Slowed down case. If buffer recovers to >= 5s, resume regular speed
if (buffered > 5 - EPS) {
changePlaybackRate(1.0);
}
} else if (this.video.playbackRate > 1 + EPS) {
// Speeded up case. If buffer recovers to <= 5s, resume regular speed
if (buffered < 5 + EPS) {
changePlaybackRate(1.0);
} else if (buffered > 8 + EPS) {
// drop excessive data
// Log.verbose('Dropping excessive data, buffer: ' + buffered);
// this.realtimeBeaconBuilder.excessiveDataDropped(buffered - 5);
// this.video.currentTime += buffered - 5;
}
} else {
// Regular speed case. If buffer drops to < 3s or grows to > 6s, adjust speed accordingly
// If buffer significantly grows to > 10s, keep 5s and drop excessive data
if (buffered < 3 - EPS) {
// changePlaybackRate(0.75);
} else if (buffered > 8 + EPS) {
// drop excessive data
// Log.verbose('Dropping excessive data, buffer: ' + buffered);
// this.realtimeBeaconBuilder.excessiveDataDropped(buffered - 5);
// this.video.currentTime += buffered - 5;
} else if (buffered > 6 + EPS) {
// changePlaybackRate(1.25);
}
}
}
this._lastBufferd = buffered;
}
} | [
"onBuffering() {}",
"function checkBufferCompleteness(buffer) {\n // Return 0 if buffer's length less than 6, it means that the buffer has not been received completely.\n if (buffer.length < 6) {\n return 0;\n }\n const bodyLength = buffer.readInt32BE(2);\n return 6 + bodyLength;\n}",
"function _isBufferFull() {\n return _getNormalizedBufferLength() >= 0.9 || _haveDownloadedRemainingMedia();\n }",
"function checkBuffering() {\n currentPlayPos = videoElement.currentTime;\n\n // if no buffering is currently detected,\n // and the position does not seem to increase\n // and the player isn't manually paused...\n if (\n !bufferingDetected \n && (currentPlayPos ==lastPlayPos)\n && (!videoElement.paused)\n ) {\n bufferStartTime = new Date().getTime();\n console.log(\"buffering\");\n bufferingDetected = true;\n bufferingNo+=1;\n if(prevResponseDone)\n {\n forceFetch=true; //force fetch the next video chunk if it is buffering and no get request pending\n console.log(\"Video is force fetched\");\n }\n }\n lastPlayPos = currentPlayPos\n}",
"onBufferingEnd() {}",
"function shouldProcessBuffer (context) {\n const config = context.config\n const buffer = context.buffer\n\n if (config.lines != null) {\n if (buffer.objects.length >= config.lines) return true\n }\n\n if (config.time != null) {\n const elapTime = (Date.now() - context.buffer.start) / 1000\n if (elapTime > config.time) return true\n }\n\n return false\n}",
"_tryBuffer() {\n if (!this.open) {\n return;\n }\n\n if (this._buffer.length === 0) {\n return;\n }\n\n const msg = this._buffer[0];\n\n if (this._trySend(msg)) {\n this._buffer.shift();\n\n this._bufferSize = this._buffer.length;\n\n this._tryBuffer();\n }\n }",
"monitorBuffer_() {\n if (this.checkBufferTimeout_) {\n window.clearTimeout(this.checkBufferTimeout_);\n }\n\n this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);\n }",
"function _calculateBufferSize() {\n try {\n if (_sourceBuffer.buffered.length < 1) {\n return 0;\n }\n return _sourceBuffer.buffered.end(0) - _audio.currentTime;\n } catch (e) {\n return 0;\n }\n }",
"bufGotLonger() {\n if(this._buf.length < 16 ) {\n return;\n }\n // console.log('bufGotLonger2 ' + _buf);\n\n // trim zeros first cuz why not\n for(let i = 0; i < this._buf.length; i++) {\n let word = this._buf[i];\n if( word != 0 ) {\n // if this isn't the first loop\n if( i != 0 ) {\n // trim buf\n this._buf = this._buf.slice(i);\n\n if( this._jamming !== -1 )\n {\n if( this.printPackets ) {\n console.log('jamming for ' + this._jamming);\n this._jamming = -1;\n }\n }\n\n }\n break; // break if we trimmed or not\n } else {\n if( this._jamming === -1 ) {\n this._jamming = 1;\n } else {\n this._jamming++;\n }\n }\n } // for\n\n // console.log('bufGotLonger2a ' + this._buf);\n\n for(let i = 0; i < this._buf.length; i++) {\n\n let word = this._buf[i];\n\n // console.log('bufGotLonger3 i:' + i + ' ' + word);\n\n if( word != 0 ) {\n let [adv_error, advance, is_mapmov] = this.feedback_word_length(this._buf);\n\n if( advance > this._buf.length ) {\n return;\n } else {\n\n if( this.printPackets ) {\n if( adv_error && advance !== 1 ) {\n console.log('advance: ' + advance + ' error: ' + adv_error + ' mapmov: ' + is_mapmov);\n }\n }\n\n\n if( !adv_error ) {\n // we got a match, emit the event\n let t0 = g_type(this._buf);\n let t1 = g_vtype(this._buf);\n\n // fixme this could be done without entirePacket temporary value\n let entirePacket = this._buf.slice(i, advance);\n let header = entirePacket.slice(0,16);\n let buf = entirePacket.slice(16);\n const tag = strForType(t0,t1);\n this._notify.emit(tag, header, buf);\n\n if( this.printUnhandled ) {\n let listners = this._notify.listenerCount(tag);\n if( listners === 0 ) {\n console.log(\"UNHANDLED feedbackbus to \" + tag);\n }\n }\n \n // console.log(\"t0: \" + t0 + \" t1: \" + t1);\n // console.log('bufGotLonger4a ' + this._buf);\n\n this._buf = this._buf.slice(i + advance);\n\n // console.log('bufGotLonger4b ' + this._buf);\n\n if( this._buf.length >= 16 ) {\n // console.log('will recurse for remaining ' + this._buf.length);\n this._notify.emit('newp'); // recurse back in\n }\n\n break;\n }\n }\n }\n\n } // for\n }",
"available() {\n return this.buf.byteLength - this.usedBufferBytes;\n }",
"calculateBufferSize() {\n this.options.buffer_size = this.options.buffer_size || 52428800; //50 megaBytes\n\n if (this.options.size <= this.options.buffer_size)\n this.options.buffer_size = this.options.size;\n }",
"monitorBuffer_() {\n if (this.checkBufferTimeout_) {\n window__default[\"default\"].clearTimeout(this.checkBufferTimeout_);\n }\n this.checkBufferTimeout_ = window__default[\"default\"].setTimeout(this.monitorBufferTick_.bind(this), 1);\n }",
"pollBufferState_() {\n console.assert(this.video_, 'Need a media element to update the buffering observer')\n console.assert(this.bufferObserver_, 'Need a buffering observer to update')\n\n let bufferedToEnd\n switch (this.loadMode_) {\n case LoadMode.SRC_EQUALS:\n bufferedToEnd = this.isBufferedToEndSrc_()\n break\n case LoadMode.MEDIA_SOURCE:\n bufferedToEnd = this.isBufferedToEndMS_()\n break\n default:\n bufferedToEnd = false\n break\n }\n\n const bufferLead = TimeRangesUtils.bufferedAheadOf(this.video_.buffered, this.video_.currentTime)\n const stateChanged = this.bufferObserver_.update(bufferLead, bufferedToEnd)\n\n // If the state changed, we need to surface the event.\n if (stateChanged) {\n this.updateBufferState_()\n }\n }",
"function checkBuffer() {\n\tif (buffer[0]) {\n\t\tisPrinting = true;\n\t\tvar top = buffer.shift();\n\t\tvar htmlstring = top[0];\n\t\tvar timeout = top[1];\n\t\t\n\t\tdocument.getElementById(\"output\").innerHTML += htmlstring;\n\t\tscrollToBottom();\n\t\twindow.setTimeout(checkBuffer, timeout);\n\t\t\n\t} else {\n\t\tisPrinting = false;\n\t\twindow.setTimeout(checkBuffer, 150);\n\t}\n}",
"async readWait(length)\n {\n // Create buffer\n let buf = Buffer.alloc(length);\n let received = 0;\n\n while (received < length)\n {\n if (this.receivedBuffers.length > 0)\n {\n let src = this.receivedBuffers[0]\n if (src.length > length - received)\n {\n // Use part of the buffer...\n\n // Copy out the bit we want\n src.copy(buf, received, 0, length - received);\n\n // Split the buffer to extract the part we need\n let subBuf = Buffer.alloc(src.length - (length - received));\n src.copy(subBuf, 0, length - received, length - received + subBuf.length);\n this.receivedBuffers.shift();\n this.receivedBuffers.unshift(subBuf);\n\n // Finished\n received = length;\n }\n else\n {\n // Use the entire buffer\n src.copy(buf, received);\n received += this.receivedBuffers.shift().length;\n }\n }\n else\n {\n // Wait for more data\n await new Promise((resolve, reject) => {\n this.waiter = resolve;\n });\n this.waiter = null;\n }\n }\n return buf;\n }",
"function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}",
"function needMoreData(state){return !state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0);} // backwards compatibility.",
"function maxLengthReached(){\n\tif (continuous){\n\t\t//drop old buffer\n\t\tvar shift = (recordedBuffers.length - recordBufferMaxN);\n\t\t_shiftedBuffers += shift;\n\t\trecordedBuffers.splice(0, shift);\n\t}else{\n\t\t//close\n\t\tif (gateIsOpen){\n\t\t\tgateControl(false);\n\t\t}\n\t}\n\t//TODO: do more ... ?\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimates cloud shadow mask from image sun parameters. | function computeCloudShadowMask(sunElevation, sunAzimuth, cloudMask, options) {
var maxCloudHeight = 8000 // in image pixel units
var cloudHeightStep = 200
var radiusDilate = 10
var radiusErode = 3
if(options) {
maxCloudHeight = options.maxCloudHeight || maxCloudHeight
cloudHeightStep = options.cloudHeightStep || cloudHeightStep
radiusDilate = options.radiusDilate || radiusDilate
radiusErode = options.radiusErode || radiusErode
}
// generate cloud heights
var cloudHeights = ee.List.sequence(100, maxCloudHeight, cloudHeightStep);
// cast cloud shadows
var cloudShadowMask = ee.ImageCollection(castCloudShadows(cloudMask, cloudHeights, sunAzimuth, sunElevation)).max();
// remove clouds
cloudShadowMask = cloudShadowMask.updateMask(cloudMask.not());
return cloudShadowMask;
} | [
"function cloud_and_shadow_maskS2(img) {\n var toa = sentinel2toa(img);\n var cloud = ESAcloud(toa);\n var shadow = shadowMask(toa,cloud);\n var mask = cloud.or(shadow).eq(0);\n return toa.updateMask(mask);\n }",
"function projectShadows(cloudMask,image,irSumThresh,contractPixels,dilatePixels,cloudHeights,yMult){\r\n if(yMult === undefined || yMult === null){\r\n yMult = ee.Algorithms.If(ee.Algorithms.IsEqual(image.select([3]).projection(), ee.Projection(\"EPSG:4326\")),1,-1);\r\n }\r\n var meanAzimuth = image.get('MEAN_SOLAR_AZIMUTH_ANGLE');\r\n var meanZenith = image.get('MEAN_SOLAR_ZENITH_ANGLE');\r\n ///////////////////////////////////////////////////////\r\n // print('a',meanAzimuth);\r\n // print('z',meanZenith)\r\n \r\n //Find dark pixels\r\n var darkPixels = image.select(['nir','swir1','swir2']).reduce(ee.Reducer.sum()).lt(irSumThresh)\r\n .focal_min(contractPixels).focal_max(dilatePixels)\r\n ;//.gte(1);\r\n \r\n \r\n //Get scale of image\r\n var nominalScale = cloudMask.projection().nominalScale();\r\n //Find where cloud shadows should be based on solar geometry\r\n //Convert to radians\r\n var azR =ee.Number(meanAzimuth).add(180).multiply(Math.PI).divide(180.0);\r\n var zenR =ee.Number(meanZenith).multiply(Math.PI).divide(180.0);\r\n \r\n \r\n \r\n //Find the shadows\r\n var shadows = cloudHeights.map(function(cloudHeight){\r\n cloudHeight = ee.Number(cloudHeight);\r\n \r\n var shadowCastedDistance = zenR.tan().multiply(cloudHeight);//Distance shadow is cast\r\n var x = azR.sin().multiply(shadowCastedDistance).divide(nominalScale);//X distance of shadow\r\n var y = azR.cos().multiply(shadowCastedDistance).divide(nominalScale).multiply(yMult);//Y distance of shadow\r\n // print(x,y)\r\n \r\n return cloudMask.changeProj(cloudMask.projection(), cloudMask.projection().translate(x, y));\r\n \r\n \r\n });\r\n \r\n \r\n var shadowMask = ee.ImageCollection.fromImages(shadows).max();\r\n \r\n //Create shadow mask\r\n shadowMask = shadowMask.and(cloudMask.not());\r\n shadowMask = shadowMask.and(darkPixels).focal_min(contractPixels).focal_max(dilatePixels);\r\n // Map.addLayer(cloudMask.updateMask(cloudMask),{'min':1,'max':1,'palette':'88F'},'Cloud mask');\r\n // Map.addLayer(shadowMask.updateMask(shadowMask),{'min':1,'max':1,'palette':'880'},'Shadow mask');\r\n \r\n var cloudShadowMask = shadowMask.or(cloudMask);\r\n \r\n image = image.updateMask(cloudShadowMask.not()).addBands(shadowMask.rename(['cloudShadowMask']));\r\n return image;\r\n}",
"function projectShadows(cloudMask,image,cloudHeights){\n var meanAzimuth = image.get('MEAN_SOLAR_AZIMUTH_ANGLE');\n var meanZenith = image.get('MEAN_SOLAR_ZENITH_ANGLE');\n ///////////////////////////////////////////////////////\n // print('a',meanAzimuth);\n // print('z',meanZenith)\n \n //Find dark pixels\n var darkPixels = image.select(['nir','swir1','swir2']).reduce(ee.Reducer.sum()).lt(irSumThresh)\n .focal_min(contractPixels).focal_max(dilatePixels)\n ;//.gte(1);\n \n \n //Get scale of image\n var nominalScale = cloudMask.projection().nominalScale();\n //Find where cloud shadows should be based on solar geometry\n //Convert to radians\n var azR =ee.Number(meanAzimuth).add(180).multiply(Math.PI).divide(180.0);\n var zenR =ee.Number(meanZenith).multiply(Math.PI).divide(180.0);\n \n \n \n //Find the shadows\n var shadows = cloudHeights.map(function(cloudHeight){\n cloudHeight = ee.Number(cloudHeight);\n \n var shadowCastedDistance = zenR.tan().multiply(cloudHeight);//Distance shadow is cast\n var x = azR.sin().multiply(shadowCastedDistance).divide(nominalScale);//X distance of shadow\n var y = azR.cos().multiply(shadowCastedDistance).divide(nominalScale);//Y distance of shadow\n // print(x,y)\n \n return cloudMask.changeProj(cloudMask.projection(), cloudMask.projection().translate(x, y));\n \n \n });\n \n \n var shadowMask = ee.ImageCollection.fromImages(shadows).max();\n // Map.addLayer(cloudMask.updateMask(cloudMask),{'min':1,'max':1,'palette':'88F'},'Cloud mask');\n // Map.addLayer(shadowMask.updateMask(shadowMask),{'min':1,'max':1,'palette':'880'},'Shadow mask');\n \n //Create shadow mask\n shadowMask = shadowMask.and(cloudMask.not());\n shadowMask = shadowMask.and(darkPixels).focal_min(contractPixels).focal_max(dilatePixels);\n \n var cloudShadowMask = shadowMask.or(cloudMask);\n \n image = image.updateMask(cloudShadowMask.not()).addBands(shadowMask.rename(['cloudShadowMask']));\n return image;\n}",
"function projectShadows(cloudMask,image,cloudHeights,yMult){\n if(yMult === undefined || yMult === null){\n yMult = ee.Algorithms.If(ee.Algorithms.IsEqual(image.select([3]).projection(), ee.Projection(\"EPSG:4326\")),1,-1);\n }\n var meanAzimuth = image.get('MEAN_SOLAR_AZIMUTH_ANGLE');\n var meanZenith = image.get('MEAN_SOLAR_ZENITH_ANGLE');\n ///////////////////////////////////////////////////////\n // print('a',meanAzimuth);\n // print('z',meanZenith)\n \n //Find dark pixels\n var darkPixels = image.select(['nir','swir1','swir2']).reduce(ee.Reducer.sum()).lt(irSumThresh)\n .focal_min(contractPixels).focal_max(dilatePixels)\n ;//.gte(1);\n \n \n //Get scale of image\n var nominalScale = cloudMask.projection().nominalScale();\n //Find where cloud shadows should be based on solar geometry\n //Convert to radians\n var azR =ee.Number(meanAzimuth).add(180).multiply(Math.PI).divide(180.0);\n var zenR =ee.Number(meanZenith).multiply(Math.PI).divide(180.0);\n \n \n \n //Find the shadows\n var shadows = cloudHeights.map(function(cloudHeight){\n cloudHeight = ee.Number(cloudHeight);\n \n var shadowCastedDistance = zenR.tan().multiply(cloudHeight);//Distance shadow is cast\n var x = azR.sin().multiply(shadowCastedDistance).divide(nominalScale);//X distance of shadow\n var y = azR.cos().multiply(shadowCastedDistance).divide(nominalScale).multiply(yMult);//Y distance of shadow\n // print(x,y)\n \n return cloudMask.changeProj(cloudMask.projection(), cloudMask.projection().translate(x, y));\n \n \n });\n \n \n var shadowMask = ee.ImageCollection.fromImages(shadows).max();\n \n //Create shadow mask\n shadowMask = shadowMask.and(cloudMask.not());\n shadowMask = shadowMask.and(darkPixels).focal_min(contractPixels).focal_max(dilatePixels);\n // Map.addLayer(cloudMask.updateMask(cloudMask),{'min':1,'max':1,'palette':'88F'},'Cloud mask');\n // Map.addLayer(shadowMask.updateMask(shadowMask),{'min':1,'max':1,'palette':'880'},'Shadow mask');\n \n var cloudShadowMask = shadowMask.or(cloudMask);\n \n image = image.updateMask(cloudShadowMask.not()).addBands(shadowMask.rename(['cloudShadowMask']));\n return image;\n}",
"function fmask(img) {\n var cloudShadowBitMask = 1 << 3;\n var cloudsBitMask = 1 << 5;\n var qa = img.select('pixel_qa');\n var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)\n .and(qa.bitwiseAnd(cloudsBitMask).eq(0));\n return img.updateMask(mask);\n}",
"function landsat5SRCloudShadowCFmask_FMask(image) // For USGS version SR\n{\n\tvar timeStart = image.get('system:time_start'); // Data availability (time): Jan 1, 1984 - May 5, 2012\n var toaImageList = ee.ImageCollection('LANDSAT/LT5_L1T_TOA_FMASK') /*USGS Landsat 5 TOA Reflectance (Orthorectified) with Fmask*/\n .filterMetadata('system:time_start','equals',timeStart)\n .toList(5);\n // If TOA image existed\n var fmaskTOA = ee.Image(ee.Algorithms.If(toaImageList.size().gt(0),\n ee.Image(toaImageList.get(0)).select('fmask'),\n ee.Image(1) /* if TOA not exist , creat an all-1 image */\n ));\n var cfmaskSR = image.select('cfmask');\n var cfmaskSR_conf = image.select('cfmask_conf');\n var mask = cfmaskSR.eq(0)/* 0=clear, set all 0 as 1 while non-0 pixels as 0 */\n .or(cfmaskSR.eq(1)) /* 1=water, then add all 1 pixels to the above image */\n .and(cfmaskSR_conf.lte(1)) /*0=none, 1=cloud confidence ≤ 12.5% , select1 pixels in above image with cloud mask confidence*/\n .and(fmaskTOA.eq(0).or(fmaskTOA.eq(1))); \n return image.updateMask(mask);\n}",
"function landsat7SRCloudShadowCFmask_FMask(image) // For USGS version SR\n{\n\tvar timeStart = image.get('system:time_start');\n var toaImageList = ee.ImageCollection('LANDSAT/LE7_L1T_TOA_FMASK') /*USGS Landsat 7 TOA Reflectance (Orthorectified) with Fmask*/\n .filterMetadata('system:time_start','equals',timeStart)\n .toList(5);\n // If TOA image existed\n var fmaskTOA = ee.Image(ee.Algorithms.If(toaImageList.size().gt(0),\n ee.Image(toaImageList.get(0)).select('fmask'),\n ee.Image(1) /* if TOA not exist , creat an all-1 image */\n ));\n var cfmaskSR = image.select('cfmask');\n var cfmaskSR_conf = image.select('cfmask_conf');\n var mask = cfmaskSR.eq(0)/* 0=clear, set all 0 as 1 while non-0 pixels as 0 */\n .or(cfmaskSR.eq(1)) /* 1=water, then add all 1 pixels to the above image */\n .and(cfmaskSR_conf.lte(1)) /*0=none, 1=cloud confidence ≤ 12.5% , select1 pixels in above image with cloud mask confidence*/\n .and(fmaskTOA.eq(0).or(fmaskTOA.eq(1))); \n return image.updateMask(mask);\n}",
"function projectShadows (img, aoi, cloudband, cloudthresh, darkband, darkthresh, cloudHeights, yMult){\n//function projectShadows(cloudMask, img, darkthresh, cloudHeights, yMult){\n var max = cloudHeights.reduce(ee.Reducer.max());\n\n if(yMult === undefined || yMult === null){\n yMult = ee.Algorithms.If(ee.Algorithms.IsEqual(img.select([3]).projection(), ee.Projection(\"EPSG:4326\")),1,-1);\n }\n var meanAzimuth = img.get('MEAN_SOLAR_AZIMUTH_ANGLE');\n var meanZenith = img.get('MEAN_SOLAR_ZENITH_ANGLE');\n var viewAzimuth = img.get('MEAN_INCIDENCE_AZIMUTH_ANGLE_B8');\n var viewZenith = img.get('MEAN_INCIDENCE_ZENITH_ANGLE_B8');\n\n //Get scale of image for 'B8' will be 10\n var nominalScale = img.select(cloudband).projection().nominalScale();\n print(nominalScale);\n //Find where cloud shadows should be based on solar geometry\n //Convert to radians\n var azR = ee.Number(meanAzimuth).add(180).multiply(Math.PI).divide(180.0);\n var zenR = ee.Number(meanZenith).multiply(Math.PI).divide(180.0);\n\n var vazR = ee.Number(viewAzimuth).add(180).multiply(Math.PI).divide(180.0);\n var vzenR = ee.Number(viewZenith).multiply(Math.PI).divide(180.0);\n\n //Clip an image extending beyond border of target image to match all clouds to their shadows\n //These have the same projection and scale\n var image = img.clip(aoi);\n var cloudMask = image.select(cloudband).gte(cloudthresh).focal_min(2).focal_max(3);\n var buff = aoi.buffer(zenR.tan().multiply(max));\n var buff_image = img.clip(buff);\n\n //Find dark pixels\n //This image has same projection and scale as 'image' and 'buff_image'\n //var darkPixels = buff_image.select(darkband).reduce(ee.Reducer.sum()).round();\n var darkPixels = buff_image.select(darkband).reduce(ee.Reducer.sum()).lt(darkthresh)\n .focal_min(2).focal_max(3);\n //.gte(1);\n //print(cloudMask.max(darkPixels).bandNames());\n //Find the shadows\n var shadows = cloudHeights.map(function(cloudHeight){\n cloudHeight = ee.Number(cloudHeight);\n\n var cloudCastedDistance = vzenR.tan().multiply(cloudHeight);//Distance cloud is projected onto image\n var shadowCastedDistance = zenR.tan().multiply(cloudHeight);//Distance shadow is cast\n\n var cldx = vazR.sin().multiply(cloudCastedDistance).multiply(yMult).divide(nominalScale);//X distance of cloud\n var cldy = vazR.cos().multiply(cloudCastedDistance).divide(nominalScale);//Y distance of cloud\n //Vertical location of cloud above ground\n var cloudpos = cloudMask.changeProj(cloudMask.select(cloudband).projection(), cloudMask.select(cloudband).projection().translate(cldx, cldy));\n\n var x = azR.sin().multiply(shadowCastedDistance).divide(nominalScale);//X distance of shadow\n var y = azR.cos().multiply(shadowCastedDistance).divide(nominalScale).multiply(yMult);//Y distance of shadow\n //print(x,y);\n\n var shift = cloudpos.changeProj(cloudpos.select(cloudband).projection(), cloudpos.select(cloudband).projection().translate(x, y));\n shift = shift.updateMask(cloudMask.not());\n var total = shift.max(darkPixels).reduceRegion({\n reducer: ee.Reducer.sum(),\n geometry: buff,\n scale: 10\n }).get(cloudband);\n\n return total;\n });\n\n //return the position of the maximum overlap score\n var maxhgt = shadows.indexOf(shadows.reduce(ee.Reducer.min()));\n //return the most likely cloud height\n var height_est = cloudHeights.get(maxhgt);\n\n var darkScale = darkPixels.projection().nominalScale();\n var cloudCastedDistance = vzenR.tan().multiply(height_est);//Distance cloud is projected onto image\n var shadowCastedDistance = zenR.tan().multiply(height_est);//Distance chadow is cast from cloud\n //Reverse the signs of x and y variables to move shadows 'back' towards clouds\n var x = azR.sin().multiply(shadowCastedDistance).divide(darkScale).multiply(yMult);//X distance of shadow\n var y = azR.cos().multiply(shadowCastedDistance).divide(darkScale);//Y distance of shadow\n var cldx = vazR.sin().multiply(cloudCastedDistance).divide(darkScale);//X distance of cloud\n var cldy = vazR.cos().multiply(cloudCastedDistance).divide(darkScale).multiply(yMult);//Y distance of cloud\n\n\n //Create shadow mask\n //var shadowMask = img.changeProj(img.select(['cloudScore_z']).projection(), img.select(['cloudScore_z']).projection().translate(x.add(cldx), y.add(cldy)));\n\n return ee.Dictionary.fromLists(['x', 'y', 'height'], [x.add(cldx), y.add(cldy), height_est]);\n}",
"function build_shadow_map()\n\t{\n\t\tmaps.shadow.length = 0;\n\t\tvar surface, intensity, exponent, shadow;\n\n\t\tfor ( var y = -radius ; y < radius ; y += resolution ) {\n\t\t\tfor ( var x = -radius ; x < radius ; x += resolution ) {\n\t\t\t\tif ( Math.sqrt( x * x + y * y ) < radius ) {\n\t\t\t\t\tsurface = get_sphere_coordinates( x, y ).normalize( 1 );\n\t\t\t\t\tintensity = Vector.dotProduct( LIGHT_SOURCE, surface );\n\t\t\t\t\tintensity = ( intensity < 0 ? -1 * intensity : 0 );\n\t\t\t\t\texponent = Math.pow( intensity, LIGHT_DIFFUSION ) + LIGHT_AMBIENCE;\n\t\t\t\t\tshadow = Math.floor( clamp( ( 1 - exponent ) * 255, 0, 255 ) );\n\t\t\t\t\tmaps.shadow.push( shadow );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function cloudProject(img,dilatePixels,cloudHeights,azimuthField,zenithField){\n \n //Get the cloud mask\n var cloud = img.select('cloudMask').not();\n cloud = cloud.focal_max(dilatePixels);\n cloud = cloud.updateMask(cloud);\n \n //Get TDOM mask\n var TDOMMask = img.select(['TDOMMask']).not();\n \n //Project the shadow finding pixels inside the TDOM mask that are dark and inside the expected area given the solar geometry\n var shadow = projectShadows(cloud,TDOMMask,img, img.get(azimuthField),img.get(zenithField),cloudHeights,dilatePixels);\n \n //Combine the cloud and shadow masks\n var combinedMask = cloud.mask().or(shadow.mask()).eq(0);\n \n //Update the image's mask and return the image\n img = img.updateMask(img.mask().and(combinedMask));\n img = img.addBands(combinedMask.rename(['cloudShadowMask']));\n \n return img;\n}",
"function cloudMaskL8(image) {\r\n var cloudShadowBitMask = 1 << 3; \r\n var cloudsBitMask = 1 << 5;\r\n var qa = image.select('pixel_qa'); \r\n var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0).and(qa.bitwiseAnd(cloudsBitMask).eq(0));\r\n return image.updateMask(mask);}",
"function landsat7SRCloudShadowCFmask_FMask(image) // For USGS version SR\n{\n\tvar timeStart = image.get('system:time_start');\n var toaImageList = ee.ImageCollection('LANDSAT/LE7_L1T_TOA_FMASK')\n .filterMetadata('system:time_start','equals',timeStart)\n .toList(5);\n // If TOA image existed\n var fmaskTOA = ee.Image(ee.Algorithms.If(toaImageList.size().gt(0),\n ee.Image(toaImageList.get(0)).select('fmask'),\n ee.Image(1)));\n var cfmaskSR = image.select('cfmask');\n var cfmaskSR_conf = image.select('cfmask_conf');\n var mask = cfmaskSR.eq(0).or(cfmaskSR.eq(1)).and(cfmaskSR_conf.lte(1))\n .and(fmaskTOA.eq(0).or(fmaskTOA.eq(1)));\n return image.updateMask(mask);\n}",
"function landsat8SRCloudShadowCFmask_FMask(image) // For USGS version SR\n{ \n\tvar timeStart = image.get('system:time_start');\n var toaImageList = ee.ImageCollection('LANDSAT/LC8_L1T_TOA_FMASK')\n .filterMetadata('system:time_start','equals',timeStart)\n .toList(5);\n // If TOA image existed\n var fmaskTOA = ee.Image(ee.Algorithms.If(toaImageList.size().gt(0),\n ee.Image(toaImageList.get(0)).select('fmask'),\n ee.Image(1)));\n var cfmaskSR = image.select('cfmask');\n var cfmaskSR_conf = image.select('cfmask_conf');\n var mask = cfmaskSR.eq(0).or(cfmaskSR.eq(1)).and(cfmaskSR_conf.lte(1))\n .and(fmaskTOA.eq(0).or(fmaskTOA.eq(1)));\n return image.updateMask(mask);\n}",
"function maskS2clouds(image) {\n var qa = image.select('QA60');\n var cloudBitMask = ee.Number(2).pow(10).int();\n var cirrusBitMask = ee.Number(2).pow(11).int();\n var mask = qa.bitwiseAnd(cloudBitMask).eq(0).and( qa.bitwiseAnd(cirrusBitMask).eq(0));\n return image.updateMask(mask).divide(10000);\n}",
"function maskClouds(img) {\n var clouds = ee.Image(img.get('cloud_mask')).select('probability');\n var isNotCloud = clouds.lt(MAX_CLOUD_PROBABILITY);\n return img.updateMask(isNotCloud);\n}",
"function bustClouds(img){\n img = sentinelCloudScore(img);\n img = img.updateMask(img.select(['cloudScore']).gt(cloudThresh).focal_min(contractPixels).focal_max(dilatePixels).not());\n return img;\n}",
"function getShadowData() {\r\n var pixelData = getCameraData();\r\n var randomR = getRandomInt(0,255);\r\n var randomG = getRandomInt(0,255);\r\n var randomB = getRandomInt(0,255);\r\n // Each pixel gets four array indices: [r, g, b, alpha]\r\n for (var i=0; i<pixelData.data.length; i=i+4) {\r\n var rCurrent = pixelData.data[i];\r\n var gCurrent = pixelData.data[i+1];\r\n var bCurrent = pixelData.data[i+2];\r\n \r\n var rBackground = background.data[i];\r\n var gBackground = background.data[i+1];\r\n var bBackground = background.data[i+2];\r\n \t\t\r\n var distance = pixelDistance(rCurrent, gCurrent, bCurrent, rBackground, gBackground, bBackground); \r\n \r\n if (distance >= SHADOW_THRESHOLD) {\r\n // foreground, show shadow\r\n if(scream){\r\n pixelData.data[i] = randomR;\r\n pixelData.data[i+1] = randomG;\r\n pixelData.data[i+2] = randomB;\r\n }\r\n else{\r\n pixelData.data[i] = 0;\r\n pixelData.data[i+1] = 0;\r\n pixelData.data[i+2] = 0; \r\n }\r\n } else {\r\n // update model of background, since we think this is in the background\r\n updateBackground(i, rCurrent, gCurrent, bCurrent, rBackground, gBackground, bBackground);\r\n // now set the background color\r\n pixelData.data[i] = 255;\r\n pixelData.data[i+1] = 255;\r\n pixelData.data[i+2] = 255;\r\n pixelData.data[i+3] = 0;\r\n } \r\n }\r\n return pixelData; \r\n}",
"function shapeCloudAddShadow(){\r\n\tthis.shape.setShadow({\r\n\t\tcolor: 'black',\r\n\t\tblur: 10,\r\n\t\toffset: [10, 10],\r\n\t\talpha: 0.5\r\n\t});\r\n}",
"function maskL8sr(image) {\r\n // Bit 3 dan 5 masing-masing adalah cloud shadow dan cloud.\r\n var cloudShadowBitMask = ee.Number(2).pow(3).int();\r\n var cloudsBitMask = ee.Number(2).pow(5).int();\r\n\r\n // Dapatkan band pixel QA.\r\n var qa = image.select('pixel_qa');\r\n\r\n // Kedua 'flag' harus diatur ke 'nol', yang menunjukkan kondisi yang jelas.\r\n var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)\r\n .and(qa.bitwiseAnd(cloudsBitMask).eq(0));\r\n\r\n // Kembalikan nilai citra yang di-mask, diskalakan ke [0, 1].\r\n return image.updateMask(mask).divide(10000);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to delete a channel name for an event via the REST API | function delete_slack_channel_for_event(event_id, channel_id, callback) {
var url = "/events/" + event_id + "/slack-channels/"+channel_id;
$.ajax_delete(url, callback);
} | [
"function delete_channel_for_event(event_id, channel_id, callback) {\n var url = \"/events/\" + event_id + \"/channels/\"+channel_id;\n $.ajax_delete(url, callback);\n}",
"deleteChannel(name){\n if(typeof this.activeChannels[name]!=='undefined') {\n delete this.activeChannels[name];\n console.log('The channel ' + name + ' got deleted');\n }else{\n console.error('The channel '+name+' was not deleted because this channel doesn\\'t exist.')\n }\n }",
"function deleteChannel(channel,ChannelName){\n if (channel.name.startsWith(ChannelName) && channel.type == \"text\"){\n channel.delete();\n clearcounter++;\n }\n}",
"@track({action: 'click-channel-delete'})\n handleChannelDelete(channel){\n let {url} = channel;\n this.props.deleteChannelRequest(url);\n }",
"static deleteAction(channelId){\n\t\tlet kparams = {};\n\t\tkparams.channelId = channelId;\n\t\treturn new kaltura.RequestBuilder('channel', 'delete', kparams);\n\t}",
"delete(arg) {\n return this.httpClient\n .url(`/event_subscriptions/${arg.id}`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }",
"async function deleteChannel() {\n const subscriptionId = process.env[\"BOTSERVICE_SUBSCRIPTION_ID\"] || \"subscription-id\";\n const resourceGroupName = process.env[\"BOTSERVICE_RESOURCE_GROUP\"] || \"OneResourceGroupName\";\n const resourceName = \"samplebotname\";\n const channelName = \"EmailChannel\";\n const credential = new DefaultAzureCredential();\n const client = new AzureBotService(credential, subscriptionId);\n const result = await client.channels.delete(resourceGroupName, resourceName, channelName);\n console.log(result);\n}",
"async function handleDeleteChannel(req, res) {\n var name = req.body.name;\n if (typeof name !== \"string\") {\n res.send(400);\n return;\n }\n\n const user = await webserver.authorize(req);\n // TODO: error\n if (!user) {\n return sendPug(res, \"account-channels\", {\n channels: [],\n });\n }\n\n\n db.channels.lookup(name, function (err, channel) {\n if (err) {\n sendPug(res, \"account-channels\", {\n channels: [],\n deleteChannelError: err\n });\n return;\n }\n\n if ((!channel.owner || channel.owner.toLowerCase() !== user.name.toLowerCase()) && user.global_rank < 255) {\n db.channels.listUserChannels(user.name, function (err2, channels) {\n sendPug(res, \"account-channels\", {\n channels: err2 ? [] : channels,\n deleteChannelError: \"You do not have permission to delete this channel\"\n });\n });\n return;\n }\n\n db.channels.drop(name, function (err) {\n if (!err) {\n Logger.eventlog.log(\"[channel] \" + user.name + \"@\" +\n req.realIP + \" deleted channel \" +\n name);\n }\n\n globalMessageBus.emit('ChannelDeleted', {\n channel: name\n });\n\n db.channels.listUserChannels(user.name, function (err2, channels) {\n sendPug(res, \"account-channels\", {\n channels: err2 ? [] : channels,\n deleteChannelError: err ? err : undefined\n });\n });\n });\n });\n}",
"function test_delete() {\n //List all channels\n channelApi.list_channel((err, res) => {\n if (err) {\n sharedResource.dbgOut(err);\n }\n if (res) {\n //sharedResource.dbgOut(res);\n if (res.list.length < 1) {\n sharedResource.dbgOut('Please add some channel first');\n } else {\n //Take the first channel\n let chan = res.list[0];\n //delete the channel with the channel id\n channelApi.delete_channel(chan.id, (err_d) => {\n //if it was successful. err_d will be null, otherwise it will be filled with the related error message\n sharedResource.dbgOut(res_d ? res_d : 'Deleted successfully');\n })\n }\n \n }\n })\n}",
"delete(arg) {\n return this.httpClient\n .url(`/event_streams/${arg.id}`)\n .delete()\n .json(payload => util.deserializeResult(payload))\n .then(f => f, util.onRejected);\n }",
"function delete_event(event_name) {\n for(key in project.list_events){\n if (key == event_name) {\n delete project.list_events[event_name];\n }\n }\n // save project\n fs.writeFileSync(data_file, JSON.stringify(project, null, 2));\n}",
"function delMyChannel(req, res) {\n var index = _.findIndex(req.user.myChannels, function(myChannel) {\n return myChannel._id == req.params.id;\n });\n\n User.findById(req.user._id, function(err, user) {\n user.myChannels.splice(index, 1);\n user.save(function(err) {\n if (err) res.send(err);\n var message = \"myChannel deleted!\";\n res.json({message: message});\n });\n });\n}",
"function deleteEvent(response,eventId,client)\n{\n console.log('Deleting event: ' + eventId);\n\n var query;\n\n query = client.query({\n name: 'delete event',\n text: \"UPDATE events SET status = '0' where id = $1\",\n values: [eventId]\n });\n\n query.on('error',function(err) {\n console.dir(err);\n });\n\n query.on('end', function(result) {\n console.dir(result);\n if (result === false) {\n restResponse.returnRESTResponse(\n response,\n true,\n \"Error deleting event\",\n null);\n } else if (result.rowCount === 0 || result.rowCount === null) {\n restResponse.returnRESTResponse(\n response,\n true,\n \"Error deleting event\",\n null);\n } else {\n restResponse.returnRESTResponse(\n response,\n false,\n \"Event deleted\",\n null);\n }\n });\n}// END function deleteEvent",
"static deleteAction(externalChannelId){\n\t\tlet kparams = {};\n\t\tkparams.externalChannelId = externalChannelId;\n\t\treturn new kaltura.RequestBuilder('externalchannelprofile', 'delete', kparams);\n\t}",
"function deleteChannel(obj) {\n // adapter.log.info('deleteChannel: ' + JSON.stringify(obj));\n // search recrusive for channel name. If found and missing in\n // configuration, delete channel and all states\n Object.keys(obj).forEach((key) => {\n if (obj[key] && typeof obj[key] === 'object') {\n deleteChannel(obj[key]); // recurse.\n } else {\n if (obj[key] == 'channel') {\n let found = false;\n let channelname = obj.common.name;\n // Channel Name ist ein subscriber\n for (let i = 0; i < adapter.config.keys.length; i++) {\n let keyc = adapter.config.keys[i];\n let idc = getSubscriberID(keyc.subscriber);\n if (idc == channelname) {\n found = true;\n }\n }\n if (!found) {\n adapter.deleteChannel(channelname);\n }\n }\n }\n });\n}",
"async function delChannelPractice (arg) {\n if (!guildInfo['permitted_channels'].includes(arg.replace(/[<#>]/g, ''))) {\n return client.errorMessage(message, 'That channel is not in database.')\n }\n\n guildInfo['permitted_channels'].splice(guildInfo.permitted_channels.indexOf(arg.replace(/[<#&>]/g, '')), 1)\n await client.writeGuildData(message.guild.id, guildInfo)\n fin()\n }",
"function deleteChannel(obj) {\n\n // adapter.log.info('deleteChannel: ' + JSON.stringify(obj));\n\n // search recrusive for channel name. If found and missing in\n // configuration, delete channel and all states\n Object.keys(obj).forEach(key => {\n\n if (obj[key] && typeof obj[key] === 'object') {\n\n deleteChannel(obj[key]); // recurse.\n\n } else {\n\n if (obj[key] == 'channel') {\n\n var found = false;\n var channelname = obj.common.name;\n\n // Channel Name ist ein subscriber\n for (var i = 0; i < adapter.config.keys.length; i++) {\n\n var keyc = adapter.config.keys[i];\n var idc = getSubscriberID(keyc.subscriber);\n\n if (idc == channelname) {\n\n found = true;\n\n }\n\n }\n\n if (!found) {\n\n adapter.deleteChannel(channelname);\n\n }\n\n }\n\n }\n\n });\n\n}",
"function deleteEvent(req, res) {\n Event.deleteOne({_id : req.params.id}, (err, result) => {\n res.json({ message: \"Event successfully deleted!\", result });\n });\n}",
"function deleteEvent(eventID){\n db.events.delete(eventID);\n console.log('Event deleted succesfully');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Keep track of slider state and update price accordingly | onSliderChange(e, v) {
const newValue = Math.round(v * this.maxServiceHours);
const diff = newValue - this.state.previousServiceHours;
this.setState({
serviceHours: newValue,
price: this.state.price + (this.props.data.flatrate.serviceHourPrice * diff),
previousServiceHours: newValue,
});
} | [
"function updateSlider() {\n var val = $(\"#slider\").val();\n\n $(\"#salary-cap-box\").html(`$${addCommas(val)}`);\n luxuryTax();\n }",
"function onSliderChange() {\n var zero = ($(\"#slider\").val() == 0);\n $(\"#not-paying\").toggle(zero);\n $(\"#payment-types\").toggle(!zero);\n $(\"#gift\").toggle(!zero);\n\n updateAmountFromSlider();\n }",
"function priceSlider() {\r\n // woocommerce_price_slider_params is required to continue, ensure the object exists\r\n if (typeof woocommerce_price_slider_params === 'undefined') {\r\n return false;\r\n }\r\n\r\n if ($('.catalog-sidebar').find('.widget_price_filter').length <= 0 && $('#jws-shop-topbar').find('.widget_price_filter').length <= 0) {\r\n return false;\r\n }\r\n\r\n // Get markup ready for slider\r\n $('input#min_price, input#max_price').hide();\r\n $('.price_slider, .price_label').show();\r\n\r\n // Price slider uses jquery ui\r\n var min_price = $('.price_slider_amount #min_price').data('min'),\r\n max_price = $('.price_slider_amount #max_price').data('max'),\r\n current_min_price = parseInt(min_price, 10),\r\n current_max_price = parseInt(max_price, 10);\r\n\r\n if ($('.price_slider_amount #min_price').val() != '') {\r\n current_min_price = parseInt($('.price_slider_amount #min_price').val(), 10);\r\n }\r\n if ($('.price_slider_amount #max_price').val() != '') {\r\n current_max_price = parseInt($('.price_slider_amount #max_price').val(), 10);\r\n }\r\n\r\n $(document.body).bind('price_slider_create price_slider_slide', function(event, min, max) {\r\n if (woocommerce_price_slider_params.currency_pos === 'left') {\r\n\r\n $('.price_slider_amount span.from').html(woocommerce_price_slider_params.currency_symbol + min);\r\n $('.price_slider_amount span.to').html(woocommerce_price_slider_params.currency_symbol + max);\r\n\r\n } else if (woocommerce_price_slider_params.currency_pos === 'left_space') {\r\n\r\n $('.price_slider_amount span.from').html(woocommerce_price_slider_params.currency_symbol + ' ' + min);\r\n $('.price_slider_amount span.to').html(woocommerce_price_slider_params.currency_symbol + ' ' + max);\r\n\r\n } else if (woocommerce_price_slider_params.currency_pos === 'right') {\r\n\r\n $('.price_slider_amount span.from').html(min + woocommerce_price_slider_params.currency_symbol);\r\n $('.price_slider_amount span.to').html(max + woocommerce_price_slider_params.currency_symbol);\r\n\r\n } else if (woocommerce_price_slider_params.currency_pos === 'right_space') {\r\n\r\n $('.price_slider_amount span.from').html(min + ' ' + woocommerce_price_slider_params.currency_symbol);\r\n $('.price_slider_amount span.to').html(max + ' ' + woocommerce_price_slider_params.currency_symbol);\r\n\r\n }\r\n\r\n $(document.body).trigger('price_slider_updated', [min, max]);\r\n });\r\n if (typeof $.fn.slider !== 'undefined') {\r\n $('.price_slider').slider({\r\n range: true,\r\n animate: true,\r\n min: min_price,\r\n max: max_price,\r\n values: [current_min_price, current_max_price],\r\n create: function() {\r\n\r\n $('.price_slider_amount #min_price').val(current_min_price);\r\n $('.price_slider_amount #max_price').val(current_max_price);\r\n\r\n $(document.body).trigger('price_slider_create', [current_min_price, current_max_price]);\r\n },\r\n slide: function(event, ui) {\r\n\r\n $('input#min_price').val(ui.values[0]);\r\n $('input#max_price').val(ui.values[1]);\r\n\r\n $(document.body).trigger('price_slider_slide', [ui.values[0], ui.values[1]]);\r\n },\r\n change: function(event, ui) {\r\n\r\n $(document.body).trigger('price_slider_change', [ui.values[0], ui.values[1]]);\r\n }\r\n });\r\n }\r\n }",
"function handlePrice(e) {\n const priceRange = e.target.value;\n setActivePriceRange(priceRange);\n setCurrentPage(1);\n }",
"function update_price_filter_slider() {\n\t\tvar $ = jQuery;\n\t\tif($('.price_slider').length <= 0) {\n\t\t\treturn;\n\t\t}\n\t\tvar $price_slider = $('.price_slider');\n\t\tvar $price_slider_amount = $('.price_slider_amount');\n\n\t\tif($price_slider_amount.length <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Store the Currency used by the Price Filter. This will be used to determine\n\t\t// how to convert filter range into base Currency\n\t\tvar selected_currency = wc_aelia_currency_switcher_params.selected_currency;\n\n\t\t// If the \"price filter currency\" field already exists, use it\n\t\t// @since 4.6.9.181217\n\t\tvar $price_filter_currency_field = $price_slider_amount.find('input[name=\"price_filter_currency\"]').attr('id', 'price_filter_currency');\n\n\t\t// Update the currency for the price filter, if the field already exists\n\t\t// @since 4.7.8.190709\n\t\tif($price_filter_currency_field.length > 0) {\n\t\t\t$price_filter_currency_field.val(selected_currency);\n\t\t}\n\t\telse {\n\t\t\tvar price_filter_currency_field = $('<input>')\n\t\t\t\t.attr('id', 'price_filter_currency')\n\t\t\t\t.attr('name', 'price_filter_currency')\n\t\t\t\t.attr('value', selected_currency)\n\t\t\t\t.hide();\n\t\t\t\t$price_slider_amount.append(price_filter_currency_field);\n\t\t}\n\t}",
"updatePrice() { }",
"function price_slider(){\n\t\t$(\"#slider-range\").slider({\n\t\t\trange: true,\n\t\t\tmin: 1000,\n\t\t\tmax: 500000,\n\t\t\tvalues: [1000, 100000],\n\t\t\tslide: function(event, ui) {\n\t\t\t\t$(\"#amount\").val(\"₸\" + ui.values[0] + \" - ₸\" + ui.values[1]);\n\t\t\t}\n\t\t});\n\t\t$(\"#amount\").val(\"₸\" + $(\"#slider-range\").slider(\"values\", 0) +\n\t\t\" - ₸\" + $(\"#slider-range\").slider(\"values\", 1));\n\t}",
"function adjustSlider(){\n if ( $( \"#js-slider-range\" ).slider(\"instance\") !== undefined) {\n $(\"#js-slider-range\").slider(\"values\",0,rangeStart);\n $(\"#js-slider-range\").slider(\"values\",1,rangeEnd);\n }\n $( \"#js-amount\" ).html( formatCurrency(rangeStart) + \" - \" + formatCurrency(rangeEnd));\n $( \"input[name=price]\" ).val( rangeStart + \";\" + rangeEnd );\n }",
"function updateSlide(e) {\n horn.volume = e.target.value / 100;\n slider.value = e.target.value;\n volNum.value = e.target.value;\n\n if (horn.volume > .66) {\n volImg.setAttribute('src','./assets/media/icons/volume-level-3.svg');\n }\n if (horn.volume > .33 && horn.volume < .67) {\n volImg.setAttribute('src','./assets/media/icons/volume-level-2.svg');\n }\n if (horn.volume > 0 && horn.volume < .34) {\n volImg.setAttribute('src','./assets/media/icons/volume-level-1.svg');\n }\n if (horn.volume == 0) {\n volImg.setAttribute('src','./assets/media/icons/volume-level-0.svg');\n }\n}",
"function sliderValueChange() {\n elemValue = document.getElementById('value');\n var porcessorValue = processorSlider.value;\n var memoryValue = memorySlider.value;\n var storageValue = storageSlider.value;\n //formula to calculate cloud price based on slider value\n finalValue = Number(((((porcessorValue * memoryValue) * 1000) + ((porcessorValue * memoryValue) * storageValue) + ((porcessorValue * memoryValue) * 100)) / 12).toFixed(2));\n if (document.getElementById('cPanel').ej2_instances[0].checked) {\n finalValue = Number((finalValue - 10).toFixed(2));\n }\n if (document.getElementById('discount').ej2_instances[0].checked) {\n finalValue = Number((finalValue - ((finalValue * 25) / 100)).toFixed(2));\n }\n elemValue.innerText = finalValue.toString();\n }",
"function switchPriceValue() {\n\t\tvar currentOffer = iniitialObject.parents('.offer'),\n\t\t\tpriceValue = targetPopup.find('.value'),\n\t\t\tcheckedRadioButton = targetPopup.find('input[type=\"radio\"]:checked').data('price'),\n\t\t\ttargetPriceVariant = currentOffer.find('.js-price' + checkedRadioButton).text();\n\n\t\tpriceValue.text(targetPriceVariant);\n\t}",
"function price() {\n let slider_value = parseInt(price_slider.value);\n let price = \"\";\n\n //show price message depending on slider value\n\n switch (slider_value) {\n case 0:\n price = \"Up to £150\";\n break;\n case 1:\n price = \"Up to £200\";\n break;\n case 2:\n price = \"Up to £250\";\n break;\n case 3:\n price = \"Up to £300\";\n break;\n case 4:\n price = \"Up to £350\";\n break;\n case 5:\n price = \"Up to £400\";\n break;\n case 6:\n price = \"Up to £450\";\n break;\n case 7:\n price = \"Up to £500\";\n break;\n case 8:\n price = \"More than £500\";\n }\n\n price_text.innerHTML = price;\n\n //change price image height depending on slider\n price_image.style.height = slider_value * 3 + 76 + \"%\";\n //grab the new price image height and make the width equal\n let height = price_image.offsetHeight.toString() + \"px\";\n price_image.style.width = height;\n}",
"function setPriceValues() {\r\n\t\tlet priceStartValue;\r\n\t\tlet priceEndValue;\r\n\t\tif (priceStart.value != '') {\r\n\t\t\tpriceStartValue = priceStart.value;\r\n\t\t}\r\n\t\tif (priceEnd.value != '') {\r\n\t\t\tpriceEndValue = priceEnd.value;\r\n\t\t}\r\n\t\tpriceSlider.noUiSlider.set([priceStartValue, priceEndValue]);\r\n\t}",
"function setPriceValues() {\n\t\tlet priceStartValue;\n\t\tlet priceEndValue;\n\t\tif (priceStart.value != '') {\n\t\t\tpriceStartValue = priceStart.value;\n\t\t}\n\t\tif (priceEnd.value != '') {\n\t\t\tpriceEndValue = priceEnd.value;\n\t\t}\n\t\tpriceSlider.noUiSlider.set([priceStartValue, priceEndValue]);\n\t}",
"getSlider (state, slider) {\n state.slider = slider;\n }",
"function initPriceSlider()\n {\n\t\t$( \"#slider-range\" ).slider(\n\t\t{\n\t\t\trange: true,\n\t\t\tmin: 0,\n\t\t\tmax: 1000,\n\t\t\tvalues: [ 0, 580 ],\n\t\t\tslide: function( event, ui )\n\t\t\t{\n\t\t\t\t$( \"#amount\" ).val( \"$\" + ui.values[ 0 ] + \" - $\" + ui.values[ 1 ] );\n\t\t\t}\n\t\t});\n\t\t\t\n\t\t$( \"#amount\" ).val( \"$\" + $( \"#slider-range\" ).slider( \"values\", 0 ) + \" - $\" + $( \"#slider-range\" ).slider( \"values\", 1 ) );\n }",
"updatePriceFromPricing () {\n this.config.display.amount = this.pricing.totalNow;\n this.config.display.currency = this.pricing.currencyCode;\n }",
"_updatePrices(){\n document.getElementById('final-price').textContent = TipHandler.final_price;\n document.getElementById('tip-price').textContent = TipHandler.tip_price;\n }",
"function onPriceChange(event) {\n // Getting the new value entered by the user\n const enteredValue = event.target.value;\n // Setting the value of the \"price\" state to the newly updated value so that what the user enters is in sync\n // with the value of the state\n setPrice(enteredValue);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
xPageY, Copyright 20012007 Michael Foster (CrossBrowser.com) Part of X, a CrossBrowser Javascript Library, Distributed under the terms of the GNU LGPL | function xPageY(e)
{
var y = 0;
e = xGetElementById(e);
while (e) {
if (xDef(e.offsetTop)) y += e.offsetTop;
e = xDef(e.offsetParent) ? e.offsetParent : null;
}
return y;
} | [
"function _loadYDirectPageX() {\n this.name = \"Load Index Register Y from Memory Direct Page Indexed X\"\n this.argCount = 0;\n this.size = Size.INDEX;\n this.addrMode = AddressingMode.DIRECT_PAGE_INDEXED_X;\n this.mnemonic = 'LDY'\n}",
"function xPageY(e)\n{\n if (!(e=xGetElementById(e))) return 0;\n var y = 0;\n while (e) {\n if (xDef(e.offsetTop)) y += e.offsetTop;\n e = xDef(e.offsetParent) ? e.offsetParent : null;\n }\n// if (xOp7Up) return y - document.body.offsetTop; // v3.14, temporary hack for opera bug 130324 (reported 1nov03)\n return y;\n}",
"function _loadXDirectPageY() {\n this.name = \"Load Index Register X from Memory Direct Page Indexed Y\"\n this.argCount = 0;\n this.size = Size.INDEX;\n this.addrMode = AddressingMode.DIRECT_PAGE_INDEXED_Y;\n this.mnemonic = 'LDX'\n}",
"function genericPageToNode(ele,x,y) {\n\tvar ulc = getPageOffset( ele );\n\tvar ret = [ x - ulc[0], y - ulc[1] ];\n\t//console.log([\"genericPageToNode\",ele,x,y,\"=>\", ret.join(' ')]);\n\t//var wret = webkitPageToNode(ele,x,y);\n\t//console.log([\"webkitPageToNode\",ele,x,y,\"=>\", ret.join(' '), wret.join(' ')]);\n\treturn ret;\n}",
"function main(page){\n\tglobVar.callFunc = \"main\";\n\tvar main = xDoc.getElementsByTagName(\"page\");\n\tvar xmain = make_page(page, main);\n\tdocument.getElementById(\"main\").appendChild(xmain);\n\tglobVar.lastPage = globVar.currPage;\n\tglobVar.currPage = page;\n\tif (globVar.isIE){\n\t\t_correct_positioning_ie();\n\t}\n}",
"function xCardinalPosition(e, cp, margin, outside)\r\n{\r\n if(!(e=xGetElementById(e))) return;\r\n if (typeof(cp)!='string'){window.status='xCardinalPosition error: cp=' + cp + ', id=' + e.id; return;}\r\n var x=xLeft(e), y=xTop(e), w=xWidth(e), h=xHeight(e);\r\n var pw,ph,p = xParent(e);\r\n if (p == document || p.nodeName.toLowerCase() == 'html') {pw = xClientWidth(); ph = xClientHeight();}\r\n else {pw=xWidth(p); ph=xHeight(p);}\r\n var sx=xScrollLeft(p), sy=xScrollTop(p);\r\n var right=sx + pw, bottom=sy + ph;\r\n var cenLeft=sx + Math.floor((pw-w)/2), cenTop=sy + Math.floor((ph-h)/2);\r\n if (!margin) margin=0;\r\n else{\r\n if (outside) margin=-margin;\r\n sx +=margin; sy +=margin; right -=margin; bottom -=margin;\r\n }\r\n switch (cp.toLowerCase()){\r\n case 'n': x=cenLeft; if (outside) y=sy - h; else y=sy; break;\r\n case 'ne': if (outside){x=right; y=sy - h;}else{x=right - w; y=sy;}break;\r\n case 'e': y=cenTop; if (outside) x=right; else x=right - w; break;\r\n case 'se': if (outside){x=right; y=bottom;}else{x=right - w; y=bottom - h}break;\r\n case 's': x=cenLeft; if (outside) y=sy - h; else y=bottom - h; break;\r\n case 'sw': if (outside){x=sx - w; y=bottom;}else{x=sx; y=bottom - h;}break;\r\n case 'w': y=cenTop; if (outside) x=sx - w; else x=sx; break;\r\n case 'nw': if (outside){x=sx - w; y=sy - h;}else{x=sx; y=sy;}break;\r\n case 'cen': x=cenLeft; y=cenTop; break;\r\n case 'cenh': x=cenLeft; break;\r\n case 'cenv': y=cenTop; break;\r\n }\r\n var o = new Object();\r\n o.x = x; o.y = y;\r\n return o;\r\n}",
"function calculateBrowserPositions(x,y) {\n\t\treturn {\n\t\t\tscreenX:\t\tx + window.screenLeft,\n\t\t\tscreenY:\t\ty + window.screenTop,\n\t\t\tpageX:\t\t\tx + window.pageXOffset,\n\t\t\tpageY:\t\t\ty + window.pageYOffset,\n\t\t\tclientX:\t\tx,\n\t\t\tclientY:\t\ty\n\t\t}\n\t}",
"function getPageScroll()\n{\n\tvar xScroll, yScroll;\n\tif (self.pageYOffset)\n\t{\n\t\tyScroll = self.pageYOffset;\n\t\txScroll = self.pageXOffset;\n\t} \n\telse if (document.documentElement && document.documentElement.scrollTop)\n\t{\n\t\tyScroll = document.documentElement.scrollTop;\n\t\txScroll = document.documentElement.scrollLeft;\n\t} \n\telse if (document.body)\t// all other Explorers\n\t{\n\t\tyScroll = document.body.scrollTop;\n\t\txScroll = document.body.scrollLeft;\n\t}\n\treturn [xScroll, yScroll];\n}",
"function xCardinalPosition(e, cp, margin, outside)\n{\n if(!(e=xGetElementById(e))) return;\n if (typeof(cp)!='string'){window.status='xCardinalPosition error: cp=' + cp + ', id=' + e.id; return;}\n var x=xLeft(e), y=xTop(e), w=xWidth(e), h=xHeight(e);\n var pw,ph,p = xParent(e);\n if (p == document || p.nodeName.toLowerCase() == 'html') {pw = xClientWidth(); ph = xClientHeight();}\n else {pw=xWidth(p); ph=xHeight(p);}\n var sx=xScrollLeft(p), sy=xScrollTop(p);\n var right=sx + pw, bottom=sy + ph;\n var cenLeft=sx + Math.floor((pw-w)/2), cenTop=sy + Math.floor((ph-h)/2);\n if (!margin) margin=0;\n else{\n if (outside) margin=-margin;\n sx +=margin; sy +=margin; right -=margin; bottom -=margin;\n }\n switch (cp.toLowerCase()){\n case 'n': x=cenLeft; if (outside) y=sy - h; else y=sy; break;\n case 'ne': if (outside){x=right; y=sy - h;}else{x=right - w; y=sy;}break;\n case 'e': y=cenTop; if (outside) x=right; else x=right - w; break;\n case 'se': if (outside){x=right; y=bottom;}else{x=right - w; y=bottom - h}break;\n case 's': x=cenLeft; if (outside) y=sy - h; else y=bottom - h; break;\n case 'sw': if (outside){x=sx - w; y=bottom;}else{x=sx; y=bottom - h;}break;\n case 'w': y=cenTop; if (outside) x=sx - w; else x=sx; break;\n case 'nw': if (outside){x=sx - w; y=sy - h;}else{x=sx; y=sy;}break;\n case 'cen': x=cenLeft; y=cenTop; break;\n case 'cenh': x=cenLeft; break;\n case 'cenv': y=cenTop; break;\n }\n var o = new Object();\n o.x = x; o.y = y;\n return o;\n}",
"function set_page(){\n\tglobVar.callFunc = \"set_page\";\n\t// Create all the div elements needed for the page layout.\n\tvar xDocDiv = document.createElement(\"div\");\n\txDocDiv.id = \"page\";\n\tvar xLogoDiv = document.createElement(\"div\");\n\txLogoDiv.id = \"logoDiv\";\n\txLogoDiv.className = \"logoClass\";\n\tvar xNavDivSide = document.createElement(\"div\");\n\txNavDivSide.id = \"navSide\";\n\txNavDivSide.className = \"navClass\";\n\tvar xNavDivTop = document.createElement(\"div\");\n\txNavDivTop.id = \"navTop\";\n\txNavDivTop.className = \"navClass\";\n\tvar xMainDiv = document.createElement(\"div\");\n\txMainDiv.id = \"main\";\n\txMainDiv.className = \"mainClass\";\n\n\t// Assemble all the div elements and put them all in the HTML document.\n\txDocDiv.appendChild(xLogoDiv);\n\txDocDiv.appendChild(xNavDivSide);\n\txDocDiv.appendChild(xNavDivTop);\n\txDocDiv.appendChild(xMainDiv);\n\tdocument.body.appendChild(xDocDiv);\n\n\t// Populate the created structure.\n\tvar main = xDoc.getElementsByTagName(\"page\");\n\tvar xmain = make_page(globVar.currPage, main);\n\txMainDiv.appendChild(xmain);\n\tvar navigation = xDoc.getElementsByTagName(\"navigation\");\n\tvar nav_top = navigation[0].getElementsByTagName(\"top\");\n\tvar top_nav = navigation_top(nav_top);\n\txNavDivTop.appendChild(top_nav);\n\tvar nav_side = navigation[0].getElementsByTagName(\"side\");\n\tvar side_nav = navigation_side(nav_side);\n\txNavDivSide.appendChild(side_nav);\n\tvar ad_top = navigation[0].getElementsByTagName(\"topad\");\n\tvar top_ad = advert_top(ad_top);\n\txNavDivTop.appendChild(top_ad);\n\tvar xLogo = setLogo();\n\txLogoDiv.appendChild(xLogo);\n\tif (globVar.isIE){\n\t\t_correct_positioning_ie();\n\t}\n// Assign events to side menus. (external function in menucontrol.js)\n\tassignLabelEventsSideMenu();\n}",
"function ___getPageScroll() {\r\n\tvar xScroll, yScroll;\r\n\tif (self.pageYOffset) {\r\n\t\tyScroll = self.pageYOffset;\r\n\t\txScroll = self.pageXOffset;\r\n\t} else if (document.documentElement && document.documentElement.scrollTop) {\t // Explorer 6 Strict\r\n\t\tyScroll = document.documentElement.scrollTop;\r\n\t\txScroll = document.documentElement.scrollLeft;\r\n\t} else if (document.body) {// all other Explorers\r\n\t\tyScroll = document.body.scrollTop;\r\n\t\txScroll = document.body.scrollLeft;\t\r\n\t}\r\n\tarrayPageScroll = new Array(xScroll,yScroll);\r\n\treturn arrayPageScroll;\r\n}",
"_getPageIndexForPageXYValues (pageX, pageY)\n {\n //get the four edges of the outer element\n const outerOffset = this.viewerState.outerElement.getBoundingClientRect();\n const outerTop = outerOffset.top;\n const outerLeft = outerOffset.left;\n const outerBottom = outerOffset.bottom;\n const outerRight = outerOffset.right;\n\n //if the clicked position was outside the diva-outer object, it was not on a visible portion of a page\n if (pageX < outerLeft || pageX > outerRight)\n return -1;\n\n if (pageY < outerTop || pageY > outerBottom)\n return -1;\n\n //navigate through all diva page objects\n const pages = document.getElementsByClassName('diva-page');\n let curPageIdx = pages.length;\n while (curPageIdx--)\n {\n //get the offset for each page\n const curPage = pages[curPageIdx];\n const curOffset = curPage.getBoundingClientRect();\n\n //if this point is outside the horizontal boundaries of the page, continue\n if (pageX < curOffset.left || pageX > curOffset.right)\n continue;\n\n //same with vertical boundaries\n if (pageY < curOffset.top || pageY > curOffset.bottom)\n continue;\n\n //if we made it through the above two, we found the page we're looking for\n return curPage.getAttribute('data-index');\n }\n\n //if we made it through that entire while loop, we didn't click on a page\n return -1;\n }",
"function pagePosition(book) {\n\n //get current book\n var children = book.childNodes;\n\n var positioner = 1;\n\n for (var pages = 0; pages<children.length; pages++){\n if (positioner>1)\n positioner = 0;\n children[pages].style.left = (positioner * children[pages].offsetWidth) + 'px';\n positioner++;\n }\n}",
"get X_Axis1_OverviewTab(){return browser.getLocation('//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[2]/android.widget.HorizontalScrollView/android.view.ViewGroup/android.view.ViewGroup[3]', 'x');}",
"function initPage() {\r\ncExplain=0;\r\ncDialect='SHH';\r\niDialect=0;\r\nsetEnhancedStyle(document.getElementById(cDialect));\r\ncRhyme='';\r\niRhyme=-1;\r\ncPage='';\r\ndisplayExplanations();\r\n\r\n/*\r\nvar i;\r\n\r\n// init the array for getting content pages' heights\r\n// (we can't get them until the focus is given back to the user,\r\n// that is, too late for the newly loaded page)\r\n// used for some compensating vertical scrolling when switching dialects\r\n// inside a same rhyme\r\n// rhyme then dialect\r\n\r\naHeight = new Array(2);\r\nfor (i = 0; i < 2; i++) {\r\n\taHeight[i] = new Array(2);\r\n}\r\naHeight[0][0]=5543; aHeight[0][1]=5425;\r\naHeight[1][0]=4149; aHeight[1][1]=4224;\r\n*/\r\n\r\n/*\r\n// nb of rhyme rows depends only on rhyme\r\naNbRhymeRows = new Array(2);\r\naNbRhymeRows[0]=105;\r\naNbRhymeRows[1]=112;\r\n\r\n\r\n// high rows depend on rhyme and dialect\r\n// on such combination, is itself an array\r\n// in this array, first value is number of size exceptions,\r\n// following values are the exceptions themselves \r\naHighRows = new Array(2);\r\nfor (i = 0; i < 2; i++) {\r\n\taHighRows[i] = new Array(2);\r\n}\r\n\r\naHighRows[1][1]=new Array(32);\r\naHighRows[1][1][0] = 31;\r\naHighRows[1][1][1] = 2;\r\naHighRows[1][1][2] = 11;\r\naHighRows[1][1][3] = 15;\r\naHighRows[1][1][4] = 33;\r\naHighRows[1][1][5] = 34;\r\naHighRows[1][1][6] = 40;\r\naHighRows[1][1][7] = 41;\r\naHighRows[1][1][8] = 42;\r\naHighRows[1][1][9] = 44;\r\naHighRows[1][1][10] = 46;\r\naHighRows[1][1][11] = 52;\r\naHighRows[1][1][12] = 52;\r\naHighRows[1][1][13] = 65;\r\naHighRows[1][1][14] = 67;\r\naHighRows[1][1][15] = 67;\r\naHighRows[1][1][16] = 68;\r\naHighRows[1][1][17] = 73;\r\naHighRows[1][1][18] = 73;\r\naHighRows[1][1][19] = 73;\r\naHighRows[1][1][20] = 74;\r\naHighRows[1][1][21] = 74;\r\naHighRows[1][1][22] = 75;\r\naHighRows[1][1][23] = 76;\r\naHighRows[1][1][24] = 77;\r\naHighRows[1][1][25] = 85;\r\naHighRows[1][1][26] = 87;\r\naHighRows[1][1][27] = 87;\r\naHighRows[1][1][28] = 87;\r\naHighRows[1][1][29] = 95;\r\naHighRows[1][1][30] = 108;\r\naHighRows[1][1][31] = 109;\r\n*/\r\n\r\n}",
"function dhtmlXWindowsSngl(){}",
"function move(pageX, pageY) {\n element.style.left = pageX - element.offsetWidth / 2 + 'px';\n element.style.top = pageY - element.offsetHeight / 2 + 'px';\n }",
"function getPageScroll() {\n var xScroll, yScroll;\n\n if (self.pageYOffset)\n {\n yScroll = self.pageYOffset;\n xScroll = self.pageXOffset;\n } else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict\n yScroll = document.documentElement.scrollTop;\n xScroll = document.documentElement.scrollLeft;\n } else if (document.body) {// all other Explorers\n yScroll = document.body.scrollTop;\n xScroll = document.body.scrollLeft; \n }\n\n return new Array(xScroll,yScroll);\n}",
"function SetWindowScroll(x,y) {\r\nif(Try) {\r\n \r\n var doc = document.documentElement;\r\n if(!doc || !doc.clientWidth || window.pageXOffset!=null && document.compatMode!=\"CSS1Compat\") doc = document.body;\r\n if(x!=null && doc.scrollLeft != x) doc.scrollLeft = x; \r\n if(y!=null && doc.scrollTop != y) doc.scrollTop = y;\r\n }\r\nelse if(Catch){ }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
picks config.tagsCount random tags from config.tags list | function pickRandomTags() {
const tags = config.tags.sort((a, b) => Math.random() > 0.5 ? 1 : -1);
let res = '';
for (let i = 0; i < config.tagsCount; ++i) {
res += `#${tags[i]} `;
}
return res.trim();
} | [
"function createTagPool(){\n let tagPool = [];\n let i;\n for (i = 0; i < 10; i++) {\n tagPool.push(faker.lorem.word());\n }\n _.uniq(tagPool);\n return tagPool;\n}",
"function getRandomTag() {\n\tvar tagLists = [\n\t\tapparelTags, \n\t\tcelebrityTags, \n\t\tcolorTags, \n\t\tdemographicsTags, \n\t\tfoodTags, \n\t\tgeneralTags, \n\t\tlogoTags, \n\t\tmoderationTags,\n\t\tnsfwTags,\n\t\ttravelTags,\n\t\tweddingTags\n\t];\n\t\n\tvar randomIndex = Math.floor((Math.random() * 11));\n\t\n\tvar randomTagList = tagLists[randomIndex];\n\t\n\treturn randomTagList[Math.floor(Math.random()*randomTagList.length)];\n}",
"function randomTag(tagArray){\n\tvar randomNum = Math.floor(Math.random() * tagArray.length);\n\treturn randomNum;}",
"function getRandom(tagsList, n){\r\n let result = new Array(n); //console.log(result); 4 empty string\r\n let len = tagsList.length; //console.log(len); length of the tagsList = 11\r\n let taken = new Array(len); //console.log(taken); 11 empty string\r\n if (n > len) //error checking//this will never happen because n, which is 4 only, will always less than tagsList.length of 11\r\n throw new RangeError(\"getRandom: more elements taken than available\");\r\n while (n--) { //iterating from 3>2>1>0\r\n let x = Math.floor(Math.random() * len); // iterate 4x to get 4 random number ranging from 0 to 10,\r\n result[n] = tagsList[x in taken ? taken[x] : x];\r\n taken[x] = --len in taken ? taken[len] : len;\r\n }\r\n return result;\r\n}",
"function randomTagPicker () {\r\n\r\n const tags = document.querySelectorAll('.tag');\r\n\r\n return tags[Math.floor(Math.random() * tags.length)];\r\n\r\n}",
"function generateTags() {\n var tags = ['cycling', 'museum', 'neighborhood', 'park', 'show', 'biking', 'food',\n 'nightlife', 'watersports', 'history', 'monuments', 'architecture',\n 'engineering', 'bridges', 'comedy', 'wine tasting', 'MTA', \n 'transportation', 'airports', 'shipping docks', 'technology', \n 'retail', 'shopping', 'walking', 'cruise', 'antique', 'art', 'street food', \n 'nice guy', 'bad girl', 'helicopter', 'photography', 'music', 'festival',\n 'fishing', 'hunting', 'hiking', 'sailing', 'cemetery', 'beer', 'brewery',\n 'barhop', 'circus', 'sightseeing', 'water taxi', 'family', 'horse riding',\n 'rafting', 'shows', 'clubbing', 'trolling', 'amusement park']\n\n tags = tags.map( tag => Tag.build({\n name: tag\n }));\n return tags;\n}",
"function pickRandomTag() {\r\n const tags = document.querySelectorAll(\".tag\");\r\n return tags[Math.floor(Math.random()*tags.length)];\r\n}",
"function pickRandomTag() {\n const tags = document.querySelectorAll('.tag');\n return tags[Math.floor(Math.random() * tags.length)];\n}",
"getRandomHashtag() {\n return this.config.hashtags[utils_1.Utils.getRandomInt(0, this.config.hashtags.length - 1)];\n }",
"function pickRandomTag() {\n const tags = document.querySelectorAll('.tag')\n return tags[Math.floor(Math.random() * tags.length)]\n}",
"function generateTags() {\n let allTags = {};\n const articles = document.querySelectorAll(optArticleSelector);\n\n for (let article of articles) {\n\n const tagList = article.querySelector(optArticleTagsSelector);\n let html = '';\n const articleTags = article.getAttribute('data-tags');\n const articleTagsArray = articleTags.split(' ');\n\n for (let tag of articleTagsArray) {\n const linkHTMLData = { id: tag, title: tag };\n const linkHTML = templates.tagLink(linkHTMLData);\n html = html + linkHTML + ' ';\n\n // eslint-disable-next-line no-prototype-builtins\n if (!allTags.hasOwnProperty(tag)) {\n allTags[tag] = 1;\n } else {\n allTags[tag]++;\n }\n }\n tagList.innerHTML = html;\n }\n\n const tagList = document.querySelector('.tags');\n const tagsParams = calculateTagsParams(allTags);\n const allTagsData = { tags: [] };\n\n for (let tag in allTags) {\n allTagsData.tags.push({\n tag: tag,\n count: allTags[tag],\n className: calculateTagClass(allTags[tag], tagsParams)\n });\n\n }\n tagList.innerHTML = templates.tagCloudLink(allTagsData);\n }",
"function generateRandomInterests() {\n const interestTags = InterestModel.schema.path('tag').enumValues;\n let numOfInterests = Math.floor(Math.random() * 3 + 1);\n let randomInterests = [];\n\n for(let i = 0; i <= numOfInterests; i++) {\n let interest = interestTags[Math.floor(Math.random()*interestTags.length)];\n if (!randomInterests.includes(interest)) {\n randomInterests.push(interest);\n }\n }\n\n return randomInterests;\n}",
"function showTags(htmlTags) {\n var randIndex = Math.floor(Math.random() * htmlTags.length);\n Tag.innerHTML = htmlTags[randIndex];\n}",
"generateRandomTagString(tag) {\n\t\tvar replacementArray = this.telegraphTagAssocDict[tag];\n\t\tvar randoIndex = Math.floor(Math.random() * replacementArray.length);\n\t\treturn replacementArray[randoIndex];\n\t}",
"function pickRandomSpan() {\n let spans = document.querySelectorAll('.random__content--tags__tag');\n return spans[Math.floor(Math.random() * spans.length)];\n}",
"async loadTags() {\n let additionalTags = []\n\n /*\n If a workspace exists and user has chosen to use the workspace preferences for tags,\n else use global settings.\n */\n if (FUNCTIONS.isWorkspace() &&\n (nova.workspace.config.get('todo.workspace-custom-tags') == 'Use Workspace Preferences')) {\n additionalTags = Configuration.PREFERENCE_TAGS.filter((tag) => {\n return nova.workspace.config.get(`todo.workspace-tag-${tag}`)\n })\n } else {\n additionalTags = Configuration.PREFERENCE_TAGS.filter((tag) => {\n return nova.config.get(`todo.global-tag-${tag}`)\n })\n }\n\n let tags = [...Configuration.DEFAULT_TAGS, ...additionalTags]\n tags = tags.map((tag) => { return tag.toUpperCase() })\n\n return tags\n }",
"function generateTags(currUser, userList, gameInfo) {\n\n}",
"function chooseRandomSpan() {\n const allSpans = document.querySelectorAll('.random__content--tags__tag');\n return allSpans[Math.floor(Math.random() * allSpans.length)];\n}",
"static get maxNumOfTags() {\n return 100;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name:onlinePushNotificationiPhoneCallback Author:Kony Purpose:Callback function for the push message recieving event while online. | function onlinePushNotificationiPhoneCallback(msg, actionId) {
kony.print("************ JS onlinePushNotificationCallback() called *********");
kony.print("\n received push:-" + JSON.stringify(msg));
//alert("Message: "+JSON.stringify(msg));
kony.print("Action id is:" + actionId);
if (actionId == "action1") {
var msgs = [];
var flightNo = msg["flightNo"];
checkInNotification(flightNo);
} else {
frmAdd.show();
}
} | [
"function onlinePushNotificationCallback(msg){\n debugger;\n kony.print(\"************ JS onlinePushNotificationCallback() called *********\");\n kony.print(JSON.stringify(msg));\n kony.store.setItem(\"isNewOnlineNotification\", true);\n var currentForm = kony.application.getCurrentForm();\n if(currentForm.id === \"frmLiveJourney\"){\n var controller = _kony.mvc.GetController('frmLiveJourney', true);\n controller.displayOnlineMsg(msg);\n }\n else if(currentForm.id === \"frmMyJourneys\"){\n var controllerContext = _kony.mvc.GetController('frmMyJourneys', true);\n controllerContext.anyUnreadMsg();\n }\n\n /*if(msg[\"content-available\"]!=1)\n {\n if(msg[\"isRichPush\"]!=undefined){\n displayRichPush(msg);\n }else\n alert(\"Message: \"+msg[\"content\"]);\n }\n else\n {\n alert(\"Silent Push Received\");\n //addCalendarEvent();\n }*/\n\n}",
"function onlinePushNotificationAndroidCallback(msg) {\n kony.print(\"************ JS onlinePushNotificationCallback() called *********\");\n kony.print(JSON.stringify(msg));\n if (msg[\"content-available\"] != 1) {\n if (msg[\"isRichPush\"] != undefined) {\n displayRichPush(msg);\n } else alert(\"Message: \" + msg[\"content\"]);\n } else {\n alert(\"Silent Push Received\");\n }\n}",
"function offlinePushNotificationCallback(msg){\n kony.print(\"************ JS offlinePushNotificationCallback() called *********\");\n kony.print(msg);\n kony.store.setItem(\"isNewOfflineNotification\", true);\n// if(msg[\"content-available\"]!=1)\n// alert(\"Message: \"+msg[\"content\"]);\n// else{\n// alert(\"silent push received\");\n// }\n}",
"function offlinePushNotificationAndroidCallback(msg) {\n kony.print(\"************ JS offlinePushNotificationCallback() called *********\");\n kony.print(msg);\n if (msg[\"content-available\"] != 1) {\n alert(\"Message: \" + msg[\"content\"]);\n } else {\n alert(\"silent push received\");\n }\n}",
"function offlinePushNotificationiPhoneCallback(msg, actionId) {\n kony.print(\"************ JS offlinePushNotificationCallback() called *********\");\n alert(\"Message: \" + msg[\"alert\"]);\n kony.print(\"\\n received push:-\" + JSON.stringify(msg));\n kony.print(msg);\n}",
"function onOnline () {\n\tconsole.log(\"online\");\n}",
"function notifyOnline() {\n if (dw) {\n dw.postMessage({ online: navigator.onLine });\n }\n }",
"function phonegapOnline()\r\n {\r\n }",
"function onOnline()\n {\n onlineStatus = '<b>online</b>';\n }",
"function onPresenceStateChange(callback)\n{\n if ( !callback || typeof (callback) !== 'function' ) { return; }\n webphone_api.presencecb.push(callback);\n}",
"function onNotificationGCM(e) {\n //$(\"#app-status-ul\").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');\n //console.log(\"EVENT -> RECEIVED:\" + e.event);\n \n switch( e.event )\n {\n case 'registered':\n\t\tif ( e.regid.length > 0 )\n\t\t{\n\t\t\t//console.log('<li>REGISTERED -> REGID:' + e.regid + \"</li>\");\n\t\t\t// Your GCM push server needs to know the regID before it can push to this device\n\t\t\t// here is where you might want to send it the regID for later use.\n\t\t\tconsole.log(\"regID = \" + e.regid);\n\t\t\tregID = e.regid;\n\t\t\tupdateDeviceToServer();\n\t\t}\n break;\n \n case 'message':\n \t// if this flag is set, this notification happened while we were in the foreground.\n \t// you might want to play a sound to get the user's attention, throw up a dialog, etc.\n \tif (e.foreground)\n \t{\n\t\t\t\t//console.log('<li>--INLINE NOTIFICATION--' + '</li>');\n\t\t\t\t\n\t\t\t\t// if the notification contains a soundname, play it.\n\t\t\t\t/*var my_media = new Media(\"/android_asset/www/\"+e.soundname);\n\t\t\t\tmy_media.play();*/\n\t\t\t}\n\t\t\telse\n\t\t\t{\t// otherwise we were launched because the user touched a notification in the notification tray.\n\t\t\t\tif (e.coldstart){\n\t\t\t\t\t//console.log('<li>--COLDSTART NOTIFICATION--' + '</li>');\n\t\t\t\t}else{\n\t\t\t\t\t//console.log('<li>--BACKGROUND NOTIFICATION--' + '</li>');\n\t\t\t\t}\n\t\t\t}\n \t//console.log('PUSHJS' + JSON.stringify(e.payload));\n \t//window.setTimeout(app.errorNewsSave(),4000);\n \texecutePushInit(e.payload[\"extra_params\"]);\n\t\t\t//console.log('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');\n\t\t\t//console.log('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');\n break;\n \n case 'error':\n\t\t\tconsole.log('<li>ERROR -> MSG:' + e.msg + '</li>');\n break;\n \n default:\n\t\t\tconsole.log('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');\n break;\n }\n}",
"function onNotificationGCM(e) {\n //$(\"#app-status-ul\").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');\n\n switch( e.event )\n {\n case 'registered':\n if ( e.regid.length > 0 )\n {\n //$(\"#app-status-ul\").append('<li>REGISTERED -> REGID:' + e.regid + \"</li>\");\n // Your GCM push server needs to know the regID before it can push to this device\n // here is where you might want to send it the regID for later use.\n console.log(\"regID = \" + e.regid);\n\n // pristroj nenbyl jeste zaregistrovan\n if(token==\"\")\n {\n token = e.regid;\n //infoZobraz(\"Ukládání nastavení na server\");\n serverSend(nastaveniZmenaOk,ajaxError);\n\n }\n token = e.regid;\n }\n break;\n\n case 'message':\n // if this flag is set, this notification happened while we were in the foreground.\n // you might want to play a sound to get the user's attention, throw up a dialog, etc.\n if (e.foreground)\n {\n //$(\"#app-status-ul\").append('<li>--INLINE NOTIFICATION--' + '</li>');\n //alert(\"aa\");\n console.log(\"foreground\");\n //infoZobraz(e.payload.title);\n //infoZobraz(e.payload.message);\n //infoZobraz(e.payload.msgcnt);\n // if the notification contains a soundname, play it.\n //var my_media = new Media(\"/android_asset/www/\"+e.soundname);\n //my_media.play();\n }\n else\n {\t// otherwise we were launched because the user touched a notification in the notification tray.\n /*\n if (e.coldstart)\n $(\"#app-status-ul\").append('<li>--COLDSTART NOTIFICATION--' + '</li>');\n else\n $(\"#app-status-ul\").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');\n */\n //alert(\"bb\");\n console.log(\"foreground\");\n\n }\n infoZobraz(e.payload.message);\n infoZobraz(e.payload.title);\n //$(\"#app-status-ul\").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');\n //$(\"#app-status-ul\").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');\n //infoZobraz(e.payload.message+ \"<br>\" +e.payload.msgcnt);\n\n break;\n\n case 'error':\n //$(\"#app-status-ul\").append('<li>ERROR -> MSG:' + e.msg + '</li>');\n infoZobraz(\"ERROR -> MSG:\" + e.msg );\n break;\n\n default:\n //$(\"#app-status-ul\").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');\n infoZobraz(\"Neznámám chyba\");\n break;\n }\n}",
"function onNotificationGCM(e) {\n\t$(\"#app-status-ul\").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');\n\t//console.log('GCM '+print_r(e)); console.log('GCM '+print_r(e.payload));\n\tswitch( e.event ) {\n\t\tcase 'registered':\n\t\tif ( e.regid.length > 0 ) {\n\t\t\t$(\"#app-status-ul\").append('<li>REGISTERED -> REGID:' + e.regid + \"</li>\");\n\t\t\t// Your GCM push server needs to know the regID before it can push to this device\n\t\t\t// here is where you might want to send it the regID for later use.\n\t\t\tconsole.log(\"regID = \" + e.regid);\n\t\t\t//registerMyAppPush(e.regid);\n\t\t\tapp.registerMyAppPush(e.regid);\n\t\t}\n\t\tbreak;\n\t\t\n\t\tcase 'message':\n\t\t\t// if this flag is set, this notification happened while we were in the foreground.\n\t\t\t// you might want to play a sound to get the user's attention, throw up a dialog, etc.\n\t\t\tif (e.foreground) {\n\t\t\t\t$(\"#app-status-ul\").append('<li>--INLINE NOTIFICATION--' + '</li>');\n\n\t\t\t\t// if the notification contains a soundname, play it.\n\t\t\t\t//var my_media = new Media(e.payload.soundToPlay/*\"/android_asset/www/\"+e.soundname*/);\n\t\t\t\t//my_media.play();\n\t\t\t\tif(e.payload.soundToPlay) {\n\t\t\t\t\tvar music=new AudioAlert(e.payload.soundToPlay); \n\t\t\t\t\tmusic.play();\n\t\t\t\t}\t\n\t\t\t\n\t\t\t}\n\t\t\telse {\t// otherwise we were launched because the user touched a notification in the notification tray.\n\t\t\t\tif (e.coldstart)\n\t\t\t\t\t$(\"#app-status-ul\").append('<li>--COLDSTART NOTIFICATION--' + '</li>');\n\t\t\t\telse\n\t\t\t\t$(\"#app-status-ul\").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');\n\t\t\t}\n\n\t\t\t$(\"#app-status-ul\").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');\n\t\t\t$(\"#app-status-ul\").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');\n\t\t\t\n\t\tbreak;\n\t\t\n\t\tcase 'error':\n\t\t\t$(\"#app-status-ul\").append('<li>ERROR -> MSG:' + e.msg + '</li>');\n\t\tbreak;\n\t\t\n\t\tdefault:\n\t\t\t$(\"#app-status-ul\").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');\n\t\tbreak;\n\t}\n}",
"onPushOpen(callback: Function) {\n\t\tPushwooshModule.onPushOpen(callback);\n\t}",
"function onNotificationGCM(e) {\r\n\tswitch( e.event ){\r\n\t\tcase 'registered':\r\n\t\tif ( e.regid.length > 0 ){\r\n\t\t\t// $(\"#app-status-ul\").append('<li>REGISTERED -> REGID:' + e.regid + \"</li>\");\r\n\t\t\t// Your GCM push server needs to know the regID before it can push to this device\r\n\t\t\t// here is where you might want to send it the regID for later use.\r\n\t\t\tconsole.log(\"regID = \" + e.regid);\r\n\t\t\t$.ajax({\r\n\t\t\t\turl:'http://maxmeio.mine.nu/cnt/unirn/servidorpush/add.php?key='+e.regid+'os=1',\r\n\t\t\t\ttype:'GET',\r\n\t\t\t\tdataType:'json',\r\n\t\t\t\terror:function(jqXHR,text_status,strError){\r\n\t\t\t\t\t// alert(\"no connection\");\r\n\t\t\t\t},\r\n\t\t\t\ttimeout:60000,\r\n\t\t\t\tsuccess:function(data){\r\n\t\t\t\t\t// alert(\"Save\");\r\n\t\t\t\t\t// $(\"#app-status-ul\").append('<li>response :' + data.success + \"</li>\");\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\tbreak;\r\n\t\tcase 'message':\r\n\t\t\t// if this flag is set, this notification happened while we were in the foreground.\r\n\t\t\t// you might want to play a sound to get the user's attention, throw up a dialog, etc.\r\n\t\t\tif (e.foreground){\r\n\t\t\t\t// if the notification contains a soundname, play it.\r\n\t\t\t\tvar my_media = new Media(\"/android_asset/www/\"+e.soundname);\r\n\t\t\t\tmy_media.play();\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase 'error':\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t}\r\n}",
"function onNotificationAPN(e) {\n if (e.alert) {\n $(\"#app-status-ul\").append('<li>push-notification: ' + e.alert + '</li>');\n // showing an alert also requires the org.apache.cordova.dialogs plugin\n navigator.notification.alert(e.alert);\n }\n \n if (e.sound) {\n // playing a sound also requires the org.apache.cordova.media plugin\n var snd = new Media(e.sound);\n snd.play();\n }\n \n if (e.badge) {\n pushNotification.setApplicationIconBadgeNumber(successHandler, e.badge);\n }\n }",
"function PushNotification() {}",
"onOnline() {\n this.logger.info('reconnect because receiving an online event')\n this.reconnect({ immediate: true })\n }",
"function remoteNotCallbacks() {\n kony.print(\"\\n\\n\\n<--------in remoteNotCallbacks--------->\\n\\n\\n\");\n var callbacksTable = {\n onsuccessfulregistration: regSuccessiPhoneCallback,\n onfailureregistration: regFailureiPhoneCallback,\n onlinenotification: onlinePushNotificationiPhoneCallback,\n offlinenotification: offlinePushNotificationiPhoneCallback,\n onsuccessfulderegistration: unregSuccessiPhoneCallback,\n onfailurederegistration: unregFailureiPhoneCallback\n };\n kony.push.setCallbacks(callbacksTable);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function will initiate the stripe checkout flow requires orderId | function intStripeCheckOut(orderId, email){
//get the sku of the item to be ordred
var stripeSKU = $(this).data('init-checkout-flow');
//get the active product
var product = getActiveProduct();
//init stripe
var stripe = Stripe('pk_test_9zTgVGnh5lp27tRAdf0DDSkO');
//get the quantity of items to be ordred
var qty = $('[data-target="qty"]').html();
//set the base url for the resposne from stripe
//expect default is remote
//if its actually local point response url to local api
var location = 'https://us-central1-backpacks-5bda5.cloudfunctions.net/handleStripePaymentResponse?location=remote';
if(window.location.hostname == 'localhost'){
location = 'http://localhost:5001/backpacks-5bda5/us-central1/handleStripePaymentResponse?location=localhost'
}
//stripe promise
stripe.redirectToCheckout({
items: [{sku: product.stripkeSKU, quantity: parseInt(qty)}],
// Note that it is not guaranteed your customers will be redirected to this
// URL *100%* of the time, it's possible that they could e.g. close the
// tab between form submission and the redirect.
//add a q param to the call with the user id? or order ID? so I can know what happened in the thing
successUrl: location + '&orderId='+orderId+'&success=true',
cancelUrl: location + '&orderId='+orderId+'&success=false',
customerEmail: email,
})
.then(function (result) {
if (result.error) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer.
var displayError = document.getElementById('error-message');
displayError.textContent = result.error.message;
}
});
} | [
"async function startCheckout() {\n const {error} = await stripe.redirectToCheckout({\n sessionId: s_id\n });\n\n if (error) {\n alert('Something went wrong with the payment, please try again.');\n }\n}",
"async function startCheckout() {\n const { error } = await stripe.redirectToCheckout({\n sessionId: s_id\n });\n\n if (error) {\n alert('Something went wrong with the payment, please try again.');\n }\n}",
"function stripe_checkout(session_id){\n var stripe = Stripe('pk_test_Yqj2w9ax4qsL9fv6YS8CdCYU00ebyWvnZ4');\n \n stripe.redirectToCheckout({\n // Make the id field from the Checkout Session creation API response\n // available to this file, so you can provide it as parameter here\n // instead of the {{CHECKOUT_SESSION_ID}} placeholder.\n sessionId: session_id\n\n }).then(function (result) {\n // If `redirectToCheckout` fails due to a browser or network\n // error, display the localized error message to your customer\n // using `result.error.message`.\n console.log(result);\n console.log(result.error.message);\n });\n}",
"function issuePurchaseOrder(order_id, options={}) {\n\n let html = `\n <div class='alert alert-block alert-warning'>\n {% trans 'After placing this order, line items will no longer be editable.' %}\n </div>`;\n\n constructForm(`{% url \"api-po-list\" %}${order_id}/issue/`, {\n method: 'POST',\n title: '{% trans \"Issue Purchase Order\" %}',\n confirm: true,\n preFormContent: html,\n onSuccess: function(response) {\n handleFormSuccess(response, options);\n }\n });\n}",
"async clientToken([order]) {\n try {\n const pricing = new OrderPricingSheet({\n calculation: order.calculation,\n currency: order.currency\n });\n\n const rounded = Math.round(pricing.total().amount / 10 || 0) * 10;\n\n const clientObj = coinbase.Client.init(COINBASE_COMMERCE_KEY);\n clientObj.setRequestTimeout(10000);\n\n const config = {\n name: 'Postcard',\n description: 'Handpainted by Veli & Amos and friends',\n pricing_type: 'fixed_price',\n local_price: {\n amount: `${rounded / 100}.00`,\n currency: order.currency\n },\n requested_info: []\n };\n\n const checkout = await coinbase.resources.Checkout.create(config);\n return checkout.id;\n } catch (e) {\n console.error(e);\n throw e;\n }\n }",
"function issuePurchaseOrder(order_id, options={}) {\n\n constructForm(\n `/api/order/po/${order_id}/issue/`,\n {\n method: 'POST',\n title: '{% trans \"Issue Purchase Order\" %}',\n confirm: true,\n preFormContent: function(opts) {\n var html = `\n <div class='alert alert-block alert-warning'>\n {% trans 'After placing this purchase order, line items will no longer be editable.' %}\n </div>`;\n\n return html;\n },\n onSuccess: function(response) {\n handleFormSuccess(response, options);\n }\n }\n );\n}",
"function AuthorizePayment() {\n var requestObject = EAUtils.ExtractRequestObject();\n var order = GetOrder(requestObject.order_no);\n if (order) {\n if (EAUtils.isStorefrontControllers()) {\n var COPlaceOrder = require('app_storefront_controllers/cartridge/controllers/COPlaceOrder');\n COPlaceOrder.handlePayments(order);\n } else {\n Pipeline.execute('COPlaceOrder-HandlePayments');\n }\n var orderResult = SubmitOrder(order);\n if (!orderResult.placeOrderError) {\n EAUtils.UpdateProductMessages(order);\n }\n }\n}",
"function ConfirmWebOrder(order) {\n Transaction.wrap(function() {\n order.custom.eaCountry = request.httpParameterMap.country;\n });\n if (!EAUtils.isStorefrontControllers()) {\n var validateBilling = Pipeline.execute('COBilling-ValidateBilling', {\n CurrentForms : session.forms,\n CurrentHttpParameterMap : request.httpParameterMap\n });\n if (validateBilling.EndNodeName != \"Error\") {\n var paymentSelection = Pipeline.execute('COBilling-HandlePaymentSelection', {\n CurrentForms : session.forms,\n Order : order\n });\n if (paymentSelection.EndNodeName == \"error\") {\n app.getView(\n {\n OrderToken : request.httpParameterMap.OrderToken,\n AppURL : request.httpParameterMap.AppUrl,\n AppTimeout : request.httpParameterMap.AppTimeout,\n orderTotal : request.httpParameterMap.orderTotal,\n balanceDue : request.httpParameterMap.balanceDue,\n country : request.httpParameterMap.country,\n ContinueURL : URLUtils.https('EACheckout-StartWebPaymentSubmitForm', 'OrderToken', request.httpParameterMap.OrderToken, 'AppURL', request.httpParameterMap.AppURL,\n 'AppTimeout', request.httpParameterMap.AppTimeout, 'orderTotal', request.httpParameterMap.orderTotal, 'balanceDue', request.httpParameterMap.balanceDue, 'country', request.httpParameterMap.country)\n }).render('webpayment/webpayment');\n return paymentSelection;\n }\n var submitPayment = Pipeline.execute('COPlaceOrder-SubmitPaymentImpl', {\n Order : order\n });\n if (submitPayment.EndNodeName == \"error\") {\n return false;\n }\n return true;\n } else {\n app.getView(\n {\n OrderToken : request.httpParameterMap.OrderToken,\n AppURL : request.httpParameterMap.AppUrl,\n AppTimeout : request.httpParameterMap.AppTimeout,\n orderTotal : request.httpParameterMap.orderTotal,\n balanceDue : request.httpParameterMap.balanceDue,\n country : request.httpParameterMap.country,\n ContinueURL : URLUtils.https('EACheckout-StartWebPaymentSubmitForm', 'OrderToken', request.httpParameterMap.OrderToken, 'AppURL', request.httpParameterMap.AppURL,\n 'AppTimeout', request.httpParameterMap.AppTimeout, 'orderTotal', request.httpParameterMap.orderTotal, 'balanceDue', request.httpParameterMap.balanceDue, 'country', request.httpParameterMap.country)\n }).render('webpayment/webpayment');\n }\n } else {\n var validateBilling = COBilling.validateBilling();\n if (validateBilling) {\n var cart = app.getModel('Cart').get(order);\n var paymentSelection = app.getController('COBilling').HandlePaymentSelection(cart);\n if (!paymentSelection) {\n app.getView(\n {\n OrderToken : request.httpParameterMap.OrderToken,\n AppURL : request.httpParameterMap.AppUrl,\n AppTimeout : request.httpParameterMap.AppTimeout,\n orderTotal : request.httpParameterMap.orderTotal,\n balanceDue : request.httpParameterMap.balanceDue,\n country : request.httpParameterMap.country,\n ContinueURL : URLUtils.https('EACheckout-StartWebPaymentSubmitForm', 'OrderToken', request.httpParameterMap.OrderToken, 'AppURL', request.httpParameterMap.AppURL,\n 'AppTimeout', request.httpParameterMap.AppTimeout, 'orderTotal', request.httpParameterMap.orderTotal, 'balanceDue', request.httpParameterMap.balanceDue, 'country', request.httpParameterMap.country)\n }).render('webpayment/webpayment');\n return paymentSelection;\n }\n var submitPayment = COPlaceOrder.handlePayments(order);//submitImpl\n if (!submitPayment) {\n return false;\n }\n return true;\n } else {\n app.getView(\n {\n OrderToken : request.httpParameterMap.OrderToken,\n AppURL : request.httpParameterMap.AppUrl,\n AppTimeout : request.httpParameterMap.AppTimeout,\n orderTotal : request.httpParameterMap.orderTotal,\n balanceDue : request.httpParameterMap.balanceDue,\n country : request.httpParameterMap.country,\n ContinueURL : URLUtils.https('EACheckout-StartWebPaymentSubmitForm', 'OrderToken', request.httpParameterMap.OrderToken, 'AppURL', request.httpParameterMap.AppURL,\n 'AppTimeout', request.httpParameterMap.AppTimeout, 'orderTotal', orderTotal, 'balanceDue', balanceDue, 'country', country)\n }).render('webpayment/webpayment');\n }\n }\n}",
"function approveOrderFinancially(orderObject) {\n ordersPage.clickApproveButtonOrderDetails();\n ordersPage.clickFinancialApprovalCheckBoxOrderApprovalModal();\n ordersPage.clickApproveButtonOrderApprovalModal();\n ordersPage.clickOkInOrderApprovalModal();\n}",
"async createCheckOutSessionWithStripe(req, res) {\n const {\n line_items,\n email,\n payment_method_types,\n tax,\n shippingCost,\n currency,\n } = req.body;\n const orderId = req.params.id;\n console.log(currency);\n // add Shipping\n line_items.push({\n price_data: {\n currency: currency,\n product_data: {\n name: \"Shipping Fee\",\n description: \"standard shipping\",\n },\n unit_amount: shippingCost * 100,\n },\n quantity: 1,\n });\n\n // add tax\n line_items.push({\n price_data: {\n currency: currency,\n product_data: {\n name: \"Tax\",\n description: \"Tax\",\n },\n unit_amount: tax * 100,\n },\n quantity: 1,\n });\n\n if (!email || !payment_method_types) {\n throw new Error(\"Email or payment method is required\");\n }\n if (!shippingCost) {\n throw new Error(\"Shipping cost is missing\");\n }\n\n try {\n const session = await stripe.checkout.sessions.create({\n line_items: line_items,\n customer_email: email,\n payment_method_types,\n payment_method_options: {\n wechat_pay: {\n client: \"web\",\n },\n },\n\n // for guest checkout\n // shipping_rates: [process.env.STRIPE_SHIPPING_RATE_ID],\n // shipping_address_collection: {\n // allowed_countries: ['HK', 'JP'],\n // }, /success?session_id={CHECKOUT_SESSION_ID}\n client_reference_id: orderId,\n mode: \"payment\",\n success_url: `${process.env.WEB_APP_URL}/order/${orderId}`,\n cancel_url: `${process.env.WEB_APP_URL}/order/${orderId}`,\n });\n res.status(200).send(session.id);\n } catch (error) {\n res.status(400).send({\n message:\n \"An error occured, unable to create a checkout session, please try again or contact us\",\n });\n }\n }",
"function orderStarted(orderId)\n{\n\tmyApp.alert(\"Current order has been updated\");\n xmlHttpRequest.open(\"POST\", \"OrderStarted?username=\" + getCookie(\"username\") + \"&password=\" + getCookie(\"password\") + \"&orderId=\" + orderId, true);\n xmlHttpRequest.onreadystatechange = orderStatusChanged;\n xmlHttpRequest.send();\n}",
"function submitOrder(order_id, req, res, next) {\n\tvar currentBasket = BasketMgr.getCurrentBasket();\n\tvar order = OrderMgr.getOrder(order_id);\n var fraudDetectionStatus = HookMgr.callHook('app.fraud.detection', 'fraudDetection', currentBasket);\n var Transaction = require('dw/system/Transaction');\n var Resource = require('dw/web/Resource');\n\n if (fraudDetectionStatus.status === 'fail') { \n Transaction.wrap(function () { OrderMgr.failOrder(order, true); });\n // fraud detection failed\n req.session.privacyCache.set('fraudDetectionStatus', true);\n res.redirect(URLUtils.https('Error-ErrorCode', 'err', fraudDetectionStatus.errorCode));\n return next();\t\n }\n \n // Place the order\n var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);\n if (placeOrderResult.error) {\n res.redirect(URLUtils.https('Checkout-Begin', 'stage', 'placeOrder', 'PlaceOrderError', Resource.msg('error.technical', 'checkout', null)));\n return next();\n }\n\n // Set order confirmation status to not confirmed for REVIEW orders.\n if (session.custom.CybersourceFraudDecision == \"REVIEW\") {\n var Order = require('dw/order/Order');\n Transaction.wrap(function () {\n order.setConfirmationStatus(Order.CONFIRMATION_STATUS_NOTCONFIRMED);\n });\n }\n\n COHelpers.sendConfirmationEmail(order, req.locale.id);\n // Reset using MultiShip after successful Order placement\n req.session.privacyCache.set('usingMultiShipping', false);\n\tres.redirect(URLUtils.https('Order-Confirm', 'ID' , order.orderNo, 'token', order.orderToken));\n return next();\n}",
"onPlacedOrder(orderId){\n\t\tif (this.shoppingCart){\n\t\t\tthis.shoppingCart.dismiss();\n\t\t}\n\t\tthis.setState({\n\t\t\tlisteningOrderId: orderId\n\t\t});\n\t}",
"function initializeOrder(order_id) { \n\t\tvar default_view_type = $('#default_view_type').val();\n\t\t\n // Turn off the master Schedule Edit form. This will happen on both computer/mobile.. From the schedule and order modules.\n scheduleMasterOff();\n \n\t\tif(!default_view_type.length) {\n\t\t\tdefault_view_type = 'items';\n //default_view_type = 'tasks';\n\t\t}\n\t\tif(default_view_type == 'items') {\n\t\t\ttoggleOrderViewTypeToItem(order_id);\n\t\t} else {\n\t\t\ttoggleOrderViewTypeToTask(order_id);\n\t\t}\n\t\treturn false;\n\t}",
"async payCheckout ({ view, request }) {\n const sessionId = request.input('sessionId')\n return view.render('checkout', {\n sessionId: sessionId,\n keyPublishable: Stripe.getKeyPublishable()\n })\n }",
"function PostAuthProcess(order, requestObject) {\n // if you have an OC(Order Center) integration uncomment the line below\n // order.custom.bfType=\"InStore\";\n var placeOrder;\n var result = EAPaymentFulfilled.paymentFulfilled(order);\n if (result) {\n if (result.OrderTotalAuthorized == true) {\n if (EAUtils.isStorefrontControllers()) {\n Transaction.wrap(function() {\n placeOrder = OrderMgr.placeOrder(order);\n })\n if (placeOrder.error != true) {\n Transaction.wrap(function() {\n order.custom.eaEmployeeId = session.custom.agent.employeeId;\n order.custom.eaStoreId = session.custom.agent.storeId;\n order.custom.eaCountry = session.custom.country;\n var args = {\n Order : order\n }\n SetOrderStatus.execute(args);\n });\n }\n } else {\n placeOrder = Pipeline.execute('COPlaceOrder-PlaceOrder', {\n Order : order\n });\n if (placeOrder.EndNodeName != \"error\") {\n Transaction.wrap(function() {\n order.custom.eaEmployeeId = session.custom.agent.employeeId;\n order.custom.eaStoreId = session.custom.agent.storeId;\n order.custom.eaCountry = session.custom.country;\n var args = {\n Order : order\n }\n SetOrderStatus.execute(args);\n });\n }\n\n }\n }\n }\n if (requestObject && requestObject.transaction_id) {\n Transaction.wrap(function() {\n SetPaymentStatus.execute({\n Order : order\n });\n });\n }\n EAUtils.UpdateProductMessages(order);\n\n}",
"function completePurchaseOrder(order_id, options={}) {\n\n constructForm(\n `/api/order/po/${order_id}/complete/`,\n {\n method: 'POST',\n title: '{% trans \"Complete Purchase Order\" %}',\n confirm: true,\n fieldsFunction: function(opts) {\n var fields = {\n accept_incomplete: {},\n };\n\n if (opts.context.is_complete) {\n delete fields['accept_incomplete'];\n }\n\n return fields;\n },\n preFormContent: function(opts) {\n\n var html = `\n <div class='alert alert-block alert-info'>\n {% trans \"Mark this order as complete?\" %}\n </div>`;\n\n if (opts.context.is_complete) {\n html += `\n <div class='alert alert-block alert-success'>\n {% trans \"All line items have been received\" %}\n </div>`;\n } else {\n html += `\n <div class='alert alert-block alert-warning'>\n {% trans 'This order has line items which have not been marked as received.' %}</br>\n {% trans 'Completing this order means that the order and line items will no longer be editable.' %}\n </div>`;\n }\n\n return html;\n },\n onSuccess: function(response) {\n handleFormSuccess(response, options);\n }\n }\n );\n}",
"async createCheckoutSession(ctx) {\n const payload = ctx.request.body;\n\n try {\n const session = await stripe.checkout.sessions.create({\n payment_method_types: ['card', 'sepa_debit', 'sofort'],\n locale: 'en',\n line_items: [\n {\n price_data: {\n currency: 'eur',\n product_data: {\n name: payload.orderSummary\n },\n unit_amount: payload.timePrice // price is in cents\n },\n quantity: 1,\n tax_rates: [ taxRateId ],\n },\n ],\n metadata: {\n responseId: payload.id, // response id if answers were already saved in cms\n name: payload.name,\n timeAmount: payload.timeAmount,\n timeUnit: payload.timeUnit,\n timePurpose: payload.timePurpose, // original user input\n orderSummary: payload.orderSummary,\n },\n mode: 'payment',\n // TODO: Check wether URLs are either localhost:3000 or timesales.ltd to prevent fraud\n success_url: payload.successUrl + '?key={CHECKOUT_SESSION_ID}',\n cancel_url: payload.cancelUrl\n });\n\n // Return session id for the link to the Stripe checkout page\n return { id: session.id };\n } catch (err) {\n console.log(err)\n }\n }",
"async checkout() {\n if (!this.data.allowToPay) return console.log('not enough')\n\n const token = wx.getStorageSync('token');\n if (this.data.isCartOpen) this.setData({isCartOpen: false});\n\n if (!token) {\n const loginRes = await login();\n if (loginRes) {\n wx.navigateTo({\n url: '../checkout/checkout',\n })\n }\n }else {\n wx.navigateTo({\n url: '../checkout/checkout',\n })\n }\n\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculating the Block Data Hash SHA256 hashing of the JSON representation of the following fields 'index' 'transactions' 'difficulty' 'prevBlockHash' 'minedBy' | calculateBlockDataHash() {
let transactionsListJson = [];
for (let i = 0; i < this.transactions.length; i++) {
let transactionJson = this.transactions[i];
let transactionDataToAddJson = {
'from': transactionJson.from,
'to': transactionJson.to,
'value': transactionJson.value,
'fee': transactionJson.fee,
'dateCreated': transactionJson.dateCreated,
'data': transactionJson.data,
'senderPubKey': transactionJson.senderPubKey,
'transactionDataHash': transactionJson.transactionDataHash,
'senderSignature': transactionJson.senderSignature,
'minedInBlockIndex': transactionJson.minedInBlockIndex,
'transferSuccessful': transactionJson.transferSuccessful
};
transactionsListJson.push(transactionDataToAddJson)
}
let blockDataToHashJson = {
'index': this.index,
'transactions': transactionsListJson,
'difficulty': this.difficulty,
'prevBlockHash': this.prevBlockHash,
'minedBy': this.minedBy
}
let blockDataToHashJsonStr = JSON.stringify(blockDataToHashJson);
let blockDataHash = CryptoJS.SHA256(blockDataToHashJsonStr);
let blockDataHashStr = blockDataHash.toString();
return blockDataHashStr;
} | [
"calculateBlockHash(){\n return SHA256(this.index + this.timestamp + JSON.stringify(this.data) + this.prevHash).toString();\n }",
"calculateBlockHash() {\n let blockHashDataToHashString = `${this.blockDataHash}|${this.nonce}|${this.dateCreated}`;\n let blockHash = CryptoJS.SHA256(blockHashDataToHashString);\n let blockHashStr = blockHash.toString();\n return blockHashStr;\n }",
"calculateHash(){\n // Fields 1-7: (1-6) Transaction, (7) Sequence Number\n //console.log(`Hash Input: ${this.previousHash + this.nonceToHexString() + JSON.stringify(this.data) + this.index}`)\n return SHA256(this.previousHash + this.nonceToHexString() + JSON.stringify(this.data) + this.index).toString();\n }",
"calculateHash() {\n let blockHash = this.hash;\n this.hash = '';\n\n // Recalculate the correct hash\n let validBlockHash = SHA256(JSON.stringify(this)).toString();\n this.hash = blockHash;\n\n return validBlockHash;\n }",
"calculateCurrentBlockHash(){\n return sha256(this.timeStamp + JSON.stringify(this.transactions) + this.previousHash + this.nonce);\n }",
"calculateHash() {\n return SHA256(\n this.previousHash +\n JSON.stringify(this.transactions) +\n this.timestamp +\n this.nonce\n ).toString();\n }",
"transactionHash() {\n let o = {\n chainLength: this.chainLength,\n timestamp: this.timestamp,\n transactions: Array.from(this.transactions.entries()),\n rewardAddr: this.rewardAddr,\n prevBlockHash: this.prevBlockHash,\n };\n return utils.hash(JSON.stringify(o));\n }",
"calculateHash(){\n return SHA256(this.index, this.previousHash, this.timestamp,JSON.stringify(this.data).toString())\n }",
"hash(block) {\n const blockString = JSON.stringify(block);\n const hash = crypto\n .createHmac(\"sha256\", \"420\")\n .update(blockString)\n .digest(\"hex\");\n\n return hash;\n }",
"calculateCurrentBlockHash(){\n return sha256(this.transactionTime + JSON.stringify(this.blockData) + this.previousHash + this.nonce);\n }",
"calculateTransactionDataHash() {\n let rawTransactionDataJSON = {'from': this.from,'to': this.to,'value': this.value,'fee': this.fee,'dateCreated': this.dateCreated,'data': this.data,'senderPubKey': this.senderPubKey};\n\n let rawTransactionDataJSONStr = JSON.stringify(rawTransactionDataJSON);\n let transactionDataHash = CryptoJS.SHA256(rawTransactionDataJSONStr);\n let transactionDataHashStr = transactionDataHash.toString();\n\n return transactionDataHashStr;\n }",
"function computeHash (block) {\n return SHA256(JSON.stringify(block)).toString()\n}",
"static calculateHashForBlock (block) {\n return Ruleset.calculateHash(block.index, block.nonce, block.previousHash, block.timestamp, block.data, block.status, block.creatorID);\n }",
"calculateHash() {\n signale.info(\"|> Calculate hash..\");\n const secret =\n this.index +\n this.previousHash +\n this.timestamp +\n JSON.stringify(this.data).toString();\n const hash = crypto.createHmac(\"sha256\", secret).digest(\"hex\");\n signale.success(\"|> hash ok\");\n return hash;\n }",
"calculateHash(){\n\t\t//it will take the properties of this function, run them through a hash function\n\t\t//and return the hash, used to identify the hash.\n\t\treturn SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();\n\t}",
"static hash(block) {\n const blockString = JSON.stringify(block, Object.keys(block).sort())\n return crypto.createHash(\"sha256\").update(blockString).digest(\"hex\")\n }",
"miningHash() {\n //\n // **YOUR CODE HERE**\n //\n let o = {\n prevBlockHash: this.prevBlockHash,\n pubKey: this.pubKey,\n proof: this.prelimHash(),\n sig: this.sig1\n };\n return utils.hash(JSON.stringify(o));\n }",
"static hash(block) {\n /*\"\"\"\n Creates a SHA-256 hash of a Block\n :param block: <dict> Block\n :return: <str>\n \"\"\"\n */\n // We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes\n let blockString = JSON.stringify(block);\n var eHex = crypto.SHA256(blockString).toString(crypto.enc.Hex);\n return eHex; //.hexdigest();\n }",
"hash(block) {\n\t\treturn sha256(stringify(block));\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renderizamos el componene ListaResultados con sus subcomponentes en un div id=cuerpo Recibe la lista de resultados | function renderizar(resultadosBusqueda){
ReactDOM.render(<ListaResultados list={resultadosBusqueda}/>,document.getElementById("Cuerpo"));
controlEventosJquery();
} | [
"function consultarDatosPuntos() {\n $.ajax({\n type: 'POST',\n dataType: 'json',\n url: url + \"ReporteAPH/ctrlLocalizacionLesiones/ListarDatosPuntos\",\n data: {\"idReporteAPH\": idReporteAPH}\n }).done(function (res) {\n\n var puntoTemp = [];\n\n // Recorro el json res por cada iteración creo un objeto temporal\n // y lo agrego al arreglo de lesiones\n $.each(res , function (indexPunto , valorPunto) {\n\n var lesionesTemp = [];\n var datosLesiones = valorPunto.datosLesiones;\n\n // Se encarga de recorrer las lesiones y agregarlos a lesionesTemp\n $.each(datosLesiones , function (indexLesiones , valorLesiones) {\n\n var objLesiones = {\n 'nombre': valorLesiones.descripcionCIE10,\n 'cie10' : valorLesiones.codigoCIE10,\n 'id' : valorLesiones.idLesion,\n 'especificacion' : (valorLesiones.especificacionLesion != null) ? valorLesiones.especificacionLesion : ''\n };\n\n lesionesTemp.push(objLesiones);\n\n });\n\n // Construye objeto con las lesiones y las cordenadas x - y del punto\n var objPunto = {\n\n \"infoLesion\" : lesionesTemp,\n\n \"infoPunto\" : {\n 'posX' : valorPunto.datosPunto.posX,\n 'posY' : valorPunto.datosPunto.posY\n }\n\n };\n\n\n // Agrego al arreglo puntoTemp el objeto temporal objPunto\n puntoTemp.push(objPunto);\n\n // Almacena la cantidad de puntos que hay en el cuerpo\n canLesiones++;\n\n // Arma la estructura del #id\n var idLesion = 'Puntolesion_' + canLesiones;\n // i apunta al indice de la lesion ==> lesion[i]\n var i = puntoTemp.length - 1;\n\n // Creación de un punto en el DOM\n $(\"#cont_cuerpo\").append(\"<div class='lesion' id='\"+ idLesion +\"' onclick='consultarLesion(\"+ i +\" , this.id, event)'></div>\");\n\n\n // Ubicar el punto en las cordenadas correspondientes\n $(\"#\" + idLesion).css({\n top : objPunto.infoPunto.posY + '%',\n left : objPunto.infoPunto.posX + '%'\n });\n\n });\n\n // Setear arreglo lesiones con puntoTemp\n lesiones = puntoTemp;\n\n }).fail(function () {\n\n // alerta de error\n Notificate({\n tipo: 'error',\n titulo: 'Error $Ajax',\n descripcion: 'ReporteAPH/ctrlLocalizacionLesiones/ListarDatosPuntos',\n duracion: 4\n });\n\n });\n }",
"function renderResults(){\n ulElem.textContent = '';\n\n for (let product of Product.allProducts) {\n let liElem = document.createElement('li');\n liElem.textContent = `${product.name}: ${product.votes}: ${product.views}`;\n ulElem.appendChild(liElem);\n }\n}",
"async function buscarProdutos(tipoBusca) {\r\n let codigoHTML = ``, json = null, json2 = null, produtosFilterCategorias = [];\r\n\r\n VETORDEPRODUTOSCLASSEPRODUTO = []\r\n\r\n if (tipoBusca == 'nome') {\r\n await aguardeCarregamento(true)\r\n json = await requisicaoGET(`itemsDesk/${$('#nome').val()}`, { headers: { Authorization: `Bearer ${buscarSessionUser().token}` } })\r\n json2 = await requisicaoGET(`categories`, { headers: { Authorization: `Bearer ${buscarSessionUser().token}` } });\r\n await aguardeCarregamento(false)\r\n for (let category of json2.data) {\r\n produtosFilterCategorias.push({ 'name': category.name, 'itens': json.data.filter((element) => category.products.findIndex((element1) => element1._id == element._id) > -1) })\r\n }\r\n } else if (tipoBusca == 'todos') {\r\n await aguardeCarregamento(true)\r\n json = await requisicaoGET(`itemsDesk`, { headers: { Authorization: `Bearer ${buscarSessionUser().token}` } })\r\n json2 = await requisicaoGET(`categories`, { headers: { Authorization: `Bearer ${buscarSessionUser().token}` } });\r\n await aguardeCarregamento(false)\r\n for (let category of json2.data) {\r\n produtosFilterCategorias.push({ 'name': category.name, 'itens': json.data.filter((element) => category.products.findIndex((element1) => element1._id == element._id) > -1) })\r\n }\r\n }\r\n\r\n codigoHTML += `<div class=\"shadow-lg p-3 mb-5 bg-white rounded\">\r\n <h4 class=\"text-center\" style=\"margin-top:40px;\">Lista de produtos</h4>\r\n <table style=\"margin-top:10px;\" class=\"table table-light table-sm\">\r\n <thead class=\"thead-dark\">\r\n <tr>\r\n <th scope=\"col\">Name</th>\r\n <th scope=\"col\">Descrição</th>\r\n <th scope=\"col\">Preço de custo</th>\r\n <th scope=\"col\">Preço de venda</th>\r\n <th scope=\"col\">Editar</th>\r\n <th scope=\"col\">Excluir</th>\r\n <th scope=\"col\">Disponível</th>\r\n </tr>\r\n </thead>\r\n <tbody>`\r\n\r\n for (let itemCategory of produtosFilterCategorias) {\r\n\r\n if (itemCategory.itens[0] != null) {\r\n codigoHTML += `<tr class=\"bg-warning\">\r\n <th colspan=\"7\" class=\"text-center\"> ${itemCategory.name}</th>\r\n </tr>`\r\n }\r\n\r\n for (let item of itemCategory.itens) {\r\n VETORDEPRODUTOSCLASSEPRODUTO.push(item)\r\n codigoHTML += `<tr>\r\n <th class=\"table-info\" title=\"${item.name}\">${item.drink ? '<span class=\"fas fa-wine-glass-alt\"></span>' : '<span class=\"fas fa-utensils\"></span>'} ${corrigirTamanhoString(20, item.name)}</th>\r\n <th class=\"table-info\" title=\"${item.description}\">${corrigirTamanhoString(40, item.description)}</th>\r\n <th class=\"table-warning\"><strong>R$${(item.cost).toFixed(2)}<strong></th>\r\n <th class=\"table-warning text-danger\"><strong>R$${(item.price).toFixed(2)}<strong></th>\r\n <td class=\"table-light\"><button class=\"btn btn-primary btn-sm\" onclick=\"carregarDadosProduto('${item._id}');\"><span class=\"fas fa-pencil-alt iconsTam\"></span> Editar</button></td>\r\n <td class=\"table-light\"><button class=\"btn btn-outline-danger btn-sm\" onclick=\"confirmarAcao('Excluir os dados do produto permanentemente!', 'deletarProduto(this.value)', '${item._id}');\" ><span class=\"fas fa-trash-alt iconsTam\"></span> Excluir</button></td>\r\n <td class=\"table-light\">\r\n <div class=\"custom-control custom-switch\">`\r\n if (item.available) {\r\n codigoHTML += `<input type=\"checkbox\" onclick=\"this.checked? disponibilizarIndisponibilizarProduto('${item._id}',true) : disponibilizarIndisponibilizarProduto('${item._id}',false) \" class=\"custom-control-input custom-switch\" id=\"botaoselectdisponivel${item._id}\" checked=true>`\r\n } else {\r\n codigoHTML += `<input type=\"checkbox\" onclick=\"this.checked? disponibilizarIndisponibilizarProduto('${item._id}',true) : disponibilizarIndisponibilizarProduto('${item._id}',false) \" class=\"custom-control-input custom-switch\" id=\"botaoselectdisponivel${item._id}\">`\r\n }\r\n codigoHTML += `<label class=\"custom-control-label\" for=\"botaoselectdisponivel${item._id}\">Disponível</label>\r\n </div>\r\n </td>\r\n </tr>`\r\n }\r\n }\r\n codigoHTML += `</tbody>\r\n </table>\r\n </div>`\r\n\r\n if (json.data[0] == null) {\r\n document.getElementById('resposta').innerHTML = `<h5 class=\"text-center\" style=\"margin-top:20vh;\"><span class=\"fas fa-exclamation-triangle\"></span> Nenhum produto encontrado!</h5>`;\r\n } else {\r\n document.getElementById('resposta').innerHTML = codigoHTML;\r\n }\r\n setTimeout(function () {\r\n animacaoSlideDown(['#resposta']);\r\n }, 300);\r\n\r\n}",
"function renderList (results) {\n var productsContainer = document.querySelector('#productsContainer');\n\n // clear out inner HTML to get rid of any older results\n productsContainer.innerHTML = '';\n\n // Map each item to its own item on the page\n var products = results.map(function (result) {\n return '<div class=\"product\" data-CandyID=\"' + result._id + '\"><a href=\"product.html\">'\n + '<div class=\"product_top\">' + result.name + '</div><div class=\"product_middle\">' // Name\n + '<img src=\"Images/' + result._id + '.jpg\" class=\"product_image\"/></div>' // Image\n + '<div class=\"product_price\">$' + result.price + '</div>' // Price\n + '<div class=\"product_top\">' + result.description + '</div>' // Name\n + '</a></div>'\n });\n\n // Add all of these created HTML elements to the page inside the\n // productsContainer div\n products.forEach(function (item) {\n productsContainer.innerHTML += item; // += adds to HTML instead of overwriting it entirely.\n });\n\n AddClickEvents();\n }",
"function listResult( data , quantity ) {\n let utts = data.content.utts ;\n keys = getSortedObjectKeys(utts);\n \n // selected elements by display quantity\n if( quantity != 'all' ){\n quantity = parseInt(quantity) ;\n keys = keys.slice(0, quantity) ;\n }\n\n let listWrapperHTML = \"\" ;\n keys.forEach(key => {\n // set all display row\n let orhHTMLList = csidClasses( data.content.utts[key] ) ; // get ops/ref/hyp HTML with csid classes\n let opsHTML = orhHTMLList[0] , refHTML = orhHTMLList[1] , hypHTML = orhHTMLList[2] ;\n\n keyHTML = \"<h5><a href=\\\"\" + data.content.utts[key].ctm_link + \"\\\" target=\\\"_blank\\\"> \" + key + \" </a></h5>\" ;\n keyHTML += \"<h5>csid: </h5> <p>\" + data.content.utts[key].csid + \"</p>\" ;\n keyHTML += \"<h5>ops: </h5> <p id=\\\"ops\\\">\" + opsHTML + \"</p>\" ;\n keyHTML += \"<h5>wer: </h5> <p>\" + data.content.utts[key].wer.round(4) + \"</p>\" ;\n keyHTML += \"<h5>ref: </h5> <p id=\\\"ref\\\">\" + refHTML + \"</p>\" ;\n keyHTML += \"<h5>hyp: </h5> <p id=\\\"hyp\\\">\" + hypHTML + \"</p>\" ;\n keyHTML += \"<h5>audio: </h5> <div class=\\\"icono-play audio\\\" onclick=\\\"playAudio(this, \\'\" + key + \"\\');\\\"></div>\" ;\n\n listWrapperHTML += \"<div class=list-item id=\\\"\" + key + \"\\\">\" + keyHTML + \"</div>\" ;\n });\n $(\"#listWrapper\").html( listWrapperHTML ) ;\n}",
"function renderResultsList(){\n for (let i=0; i < Item.allItems.length; i++){\n let ulElem = document.createElement('ul');\n canvasContainerElem.appendChild(ulElem);\n let item = Item.allItems[i];\n let liElem = document.createElement('li');\n liElem.textContent = `${item.name} had ${item.votes} votes and was seen ${item.views} times.`;\n ulElem.appendChild(liElem);\n }\n}",
"function llamarConteo(respuesta){\r\n\t$('#resultados2').empty();\r\n\tvar resultados = respuesta.split('###');\r\n\tfor (var i = 0; i < resultados.length-1; i++) {\r\n\t\tvar datos = resultados[i].split('***');\r\n\t\tvar node = document.createElement(\"div\");\r\n\t\tnode.setAttribute(\"class\", \"CursosGeneral2\");\r\n\t\tvar palabras = \"Palabra: \" + datos[0] + \" Total: \" + datos[1];\r\n\t\tvar pnode = document.createElement(\"p\");\r\n\t\tvar textnode = document.createTextNode(palabras);\r\n\t\tpnode.appendChild(textnode);\r\n\t\tnode.appendChild(pnode);\r\n\t\t$('#resultados2').append(node);\r\n\t}\r\n}",
"function View_Lecciones(curso_id) {\n\t// Render de Lecciones \n\t$.ajax({\n\t\ttype:'get',\n\t\turl: '/plataforma/cursos/'+ curso_id +'/simulador/muestra/',\n\t\tsuccess: function (lecciones) {\n\t\t\t// Render template de las lecciones por curso_id\n\t\t\tconsole.log(lecciones)\n\n\t\t\tvar lecciones_disponibles = ''\n\n\t\t\t//evento ciclico para mostrar cada leccion\n\t\t\tfor (var i = 0; i <= lecciones.length - 1; i++) {\n\t\t\t\tvar leccion = lecciones[0]\n\n\t\t\t\t// Mostrando cada titulo de lección\n\t\t\t\tvar template = `<div>\n\t\t\t\t\t\t\t\t<h3>Lección: ${leccion.title}</h3>\n\t\t\t\t\t\t\t\t<p>${leccion.description}</p>\n\t\t\t\t\t\t\t\t<a href=\"/plataforma/cursos/${curso_id}/simulador/muestra/${leccion.title}\">Iniciar</a> \n\t\t\t\t\t\t\t\t</div>`\n\n\t\t\t\t// Acumulando las lecciones disponibles\n\t\t\t\tlecciones_disponibles += template\n\t\t\t}\n\t\t\t\n\t\t\t// Render del template con todas las lecciones por curso\n\t\t\t$('.leccion_box').append(lecciones_disponibles)\n\n\t\t}\n\n\t})\n\t\n}",
"function listVerCompras(){\n $(\"tabla-verCompras\").html(\"\");\n compras.forEach( (p)=>{rowVerCompras($(\"#tabla-verCompras\"),p);});\t \n}",
"async function renderizarPanes() {\n btnCarrito.click(() => armarPedido());\n btnCarritoNav.click(() => armarPedido());\n await setearPanes();\n for (const pan of listadoPanes) {\n let li = $(`<li>\n <img src=\"${pan.imagen}\" alt=\"pan\">\n <p>${pan.tipo} - $${pan.costo} (${pan.peso})</p>\n <a id=\"${pan.id}-add-btn\" class=\"agregar-btn\" >Agregar</a>\n <div id=\"${pan.id}-add-section\" class=\"agregar-item\">\n <div id=\"${pan.id}-remove\">\n <i style=\"color: var(--secondary-color)\" class=\"fas fa-minus\"></i>\n </div>\n <p id=\"${pan.id}-cantidad\">${pan.cantidadPedido}</p>\n <div id=\"${pan.id}-add\">\n <i class=\"fas fa-plus\"></i>\n </div>\n </div>\n </li>`);\n\n listaPanes.append(li);\n renderSeccionEleccionPanes(pan);\n }\n getCantidadTotalPanes();\n btnCarritoNav.html(`Ir al carrito ${cantidadTotalPanes > 0 ? `(${cantidadTotalPanes})` : ''}`);\n btnCarrito.html(`Ir al carrito ${cantidadTotalPanes > 0 ? `(${cantidadTotalPanes})` : ''}`);\n}",
"async function telaRespostaListaTodosOsPedidosAbertos() {\r\n await aguardeCarregamento(true)\r\n let json = await requisicaoGET(`orders`, { headers: { Authorization: `Bearer ${buscarSessionUser().token}` } }), codigoHTML = ``;\r\n await aguardeCarregamento(false)\r\n\r\n codigoHTML += `<table class=\"table table-dark table-bordered text-center\">\r\n <thead class=\"thead-dark\">\r\n <tr>\r\n <td scope=\"col\"><small>Identificação</small></td>\r\n <td scope=\"col\"><small>Lista itens por Nome</small></td>\r\n <td scope=\"col\"><small>Valor total</small></td>\r\n </tr>\r\n </thead>\r\n <tbody>`\r\n\r\n for (let item of json.data) {\r\n codigoHTML += `<tr class=\"table-light text-dark\">\r\n <td scope=\"col\"><small>${item.identification}</small></td>\r\n <td scope=\"col\"><small>`\r\n\r\n for (let item2 of item.items) {\r\n codigoHTML += `( ${corrigirTamanhoString(20, item2.product.name)} X ${item2.quantity} )`\r\n }\r\n codigoHTML += `</small></td>\r\n <td scope=\"col\"><small>R$${(item.total).toFixed(2)}</small></td>\r\n </tr>`\r\n }\r\n\r\n codigoHTML += `</tbody>\r\n </table>`\r\n\r\n document.getElementById('lista').innerHTML = codigoHTML;\r\n\r\n}",
"function listoKurimas() {\n divuiAte();\n pridedamVerteIMasyva();\n var divListui = document.createElement('div'); // sukuriam diva listui\n // divui id\n divListui.id = \"divoId\";\n // pridedam sukurta diva i body\n document.getElementsByTagName('body')[0].appendChild(divListui);\n // sukuriam ul taga\n var ulDivui = document.createElement('ul');\n // idedam ul i diva\n divListui.appendChild(ulDivui);\n // sukuriam for loopa kad pridetu i ul masyvo \n // elementus kaip li\n var kiekListeYraLi = komentaruMasyvas.length;\n \n\n //////////////////////////////////////////////////////////////////////////\n // cia GAL su get element by tag name pasigauti sukurta ul ir appendint kuriamus li \n // i ji?\n for (var i = 0; i < kiekListeYraLi; ++i) {\n var listoElementas = document.createElement('li');\n listoElementas.innerHTML = komentaruMasyvas[i];\n ulDivui.appendChild(listoElementas);\n\n };\n document.getElementById('divasIsHtmlSkriptoVietai').appendChild(divListui);\n\n}",
"function listoKurimas() {\r\n divuiAte();\r\n pridedamVerteIMasyva();\r\n var divListui = document.createElement('div'); // sukuriam diva listui\r\n // divui id\r\n divListui.id = \"divoId\";\r\n // pridedam sukurta diva i body\r\n document.getElementsByTagName('body')[0].appendChild(divListui);\r\n // sukuriam ul taga\r\n var ulDivui = document.createElement('ul');\r\n // idedam ul i diva\r\n divListui.appendChild(ulDivui);\r\n // sukuriam for loopa kad pridetu i ul masyvo \r\n // elementus kaip li\r\n var kiekListeYraLi = komentaruMasyvas.length;\r\n \r\n\r\n //////////////////////////////////////////////////////////////////////////\r\n // cia GAL su get element by tag name pasigauti sukurta ul ir appendint kuriamus li \r\n // i ji?\r\n for (var i = 0; i < kiekListeYraLi; ++i) {\r\n var listoElementas = document.createElement('li');\r\n listoElementas.innerHTML = komentaruMasyvas[i];\r\n ulDivui.appendChild(listoElementas);\r\n\r\n };\r\n document.getElementById('divasIsHtmlSkriptoVietai').appendChild(divListui);\r\n\r\n}",
"function listarAgricultores(){\n var Sessao = getSessao();\n var envio = {\n metodo: \"TODOS_DA_UNIDADE\",\n idunidade: Sessao.unidade_idunidade\n };\n\n //chama a requisicao do servidor, o resultado é listado em uma tabela\n requisicao(true, \"agricultor/listar\", envio, function(dadosRetorno) {\n \n if(dadosRetorno.sucesso){\n var item = \"\";\n\n $.each(dadosRetorno.data, function(i, valor){\n item += \"<tr><td>\"+valor.idpessoa+\"</td><td>\"+valor.nome+\"</td><td>\"+valor.sobrenome+\"</td><td>\"+valor.rg+\"</td><td>\"+valor.cpf+\"</td><td>\"+valor.telefone1+\"</td><td>\"+valor.nomeunidade+\"</td></tr>\";\n\n });\n\n $(\"#page\").fadeOut(400, function(){\n $(\"#divItens\").empty().append('<h2 class=\"sub-header\">Lista de agricultores</h2><div class=\"table-responsive\"><table class=\"table table-hover\"><thead><tr><th>ID</th><th>Nome</th><th>Sobrenome</th><th>RG</th><th>CPF</th><th>Telefone</th><th>Unidade</th></tr></thead><tbody>'+item+'</tbody></table></div>');\n $(\"#divItens\").show();\n $(\"#page\").fadeIn(400);\n });\n //retira o painel loading\n $(\".painelCarregando\").fadeOut(400);\n }else{\n //retira o painel loading\n $(\".painelCarregando\").fadeOut(400);\n alerta(\"Alerta!\", dadosRetorno.mensagem);\n }\n //atualiza a sessao\n updateSessao(dadosRetorno.sessao);\n });\n}",
"getListOfCustomers () {\n fetch(this.ROUTING_URL+\"getCustomersList\")\n .then(response=>response.json())\n .then(json=>json.map(c=>[customer(c), false])).then(json=>{\n this.listOfCustomers = json; // assigning json response to list of customer global array.\n const customerListDiv = select(\"customerListView\");\n setAnElementClassToVisible(\"customerListContainer\");//making div visible\n customerListDiv.innerHTML = this.showCustomersResult(); // drawing html table element\n });\n }",
"function renderAll() {\n let results = renderGrid(),\n content = document.querySelector(\"#content\");\n content.appendChild(results);\n}",
"function obtenerTodosLosCursos() {\n console.debug(\"obtenerTodosLosCursos\")\n const url = \"http://localhost:8080/apprest/api/cursos/profesor\";\n\n const promesa = ajax('GET', url, null);\n\n promesa.then(cursos => {\n console.debug(\"dentro then\");\n console.debug(JSON.stringify(cursos));\n let inactivos = document.getElementById(\"cursosinactivos\");\n inactivos.innerHTML = \"\";\n\n cursos.forEach(curso => {\n inactivos.innerHTML += `<div><img onclick=\"selectInactivo(event,null)\" id=\"${curso.id}\" src=\"img/${curso.imagen}\" alt=\"${curso.nombre}\" title=\"${curso.nombre}\"> <b>Nombre</b>: ${curso.nombre} </div>`\n })\n });\n}",
"function displayResult() {\n var html = '';\n if (hits.length === 0) {\n html += '<div id=\"pre-list\">Inga träffar</div>';\n } else {\n html += '<div id=\"pre-list\">' + hits.length + ' produkter hittade</div>';\n html += '<ul id=\"item-list\">';\n html += '<li><div class=\"header\">Produkt</div><div class=\"header\">Kategori</div></li>';\n $.each(hits, function(index, item) {\n html += '<li><div class=\"produkt\">' + item.produkt_namn + '</div> <div class=\"kategori\">' + item.kategori_namn + '</div></li>';\n });\n html += '</ul>';\n }\n $('#hit-list').html(html);\n }",
"function affichageProduits(resultat){\n //1-Sélection élément du DOM\n const positionElement = document.querySelector(\".Vcams-container\");\n\n //2-Boucle for pour afficher tous les objets dans la page web\n for (i = 0 ; i < resultat.length ; i++){\n\n //3-mettre les données dans les variables\n resultat.forEach((element, i) => {\n nom[i] = element.name;\n price[i] = element.price;\n description[i] = element.description;\n _id[i] = element._id;\n imageUrl[i] = element.imageUrl;\n // lenses[i] = element.lenses;\n });\n //4-afficher tous les objets sur la page web\n // Ci-dessous on fait une récurssivité de la variable à chaque tour de boucle pour afaire appaître les autre éléments\n structureProduits = structureProduits +`\n <a href=\"./PageProduit.html?id=${_id[i]}\" class=\"link\">\n <div class=\"card\">\n <img src=\"${imageUrl[i]}\" class=\"card-img-top lsimg\">\n <div class=\"card-body\">\n <h5 class=\"card-title\">${nom[i]}<span>${price[i]/100}€</span></h5>\n <p class=\"card-text\">${description[i]}</p>\n </div>\n </div>\n </a>`;\n\n //5-injection html\n positionElement.innerHTML = structureProduits;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the remote window | function showRemote() {
$("#remote").centerInClient();
$("#remote").css("display", "block");
documentReady();
} | [
"show()\n {\n this._window.show();\n }",
"show() {\n this.window.show();\n this.window.focus();\n }",
"function openAdminRemoteWindow() {\n\turl = \"/internal/adminremote.php\";\n var adminRemoteWindow =\n window.open(url,\n \"adminRemoteWindow\",\n \"resizable=no,height=410,width=300\");\n}",
"show() {\n\t\tif (this.xid) {\n\t\t\tglobal.X.MapWindow( this.xid );\n\t\t\t// Make sure the window is in the correct position again.\n\t\t\tthis.redraw();\n\t\t}\n\t}",
"function show() {\n window.extensions.KJSLINT.KomodoAdaptor.showCommandPanel();\n }",
"show() {\n\t\tthis.settingsWin = null;\n\t\tthis.window = new BrowserWindow({\n\t\t\twidth: 800,\n\t\t\theight: 600,\n\t\t\tresizable: true,\n\t\t\ttitle: 'PhotoImp',\n\t\t\ticon: path.resolve(__dirname, '../../assets/logo_32.png'),\n\t\t\twebPreferences: {\n\t\t\t\tnodeIntegration: true\n\t\t\t}\n\t\t});\n\n\t\t// Create the menu\n\t\tvar menu = Menu.buildFromTemplate([\n\t\t\t{\n\t\t\t\tlabel: 'File',\n\t\t\t\tsubmenu: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: 'Open...',\n\t\t\t\t\t\tclick: this.onMnuOpenClick.bind(this)\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: 'Settings...',\n\t\t\t\t\t\tclick: this.onMnuSettingsClick.bind(this)\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'separator'\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: 'Quit',\n\t\t\t\t\t\tclick: this.onMnuQuitClick.bind(this)\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t]);\n\n\t\tthis.window.setMenu(menu);\n\t\tthis.window.loadURL('file://' + __dirname + '/main.html');\n\t}",
"function showWindow(windowDOM, launcherDOM) {\n // Show window\n windowDOM.show();\n \n // Trigger event: Window is now visible and content is loading\n $.event.trigger({\n type: 'fwModalWindow',\n event: 'loading',\n id: windowDOM.attr('id')\n });\n }",
"function showClient() {\r\n $($window.document.body).show();\r\n }",
"showCreatorWindow() {\n console.log('Show gitignore creator window.')\n this.panel.show()\n this.selectorView.focus()\n }",
"function BTopLocalServer_viewBTopSensorConfig(remoteChannel, remoteHost)\n{\n window.open('http://' + remoteHost + '/cgi-bin/Sensor/Test.cgi?ChannelId=' + remoteChannel + '&mode=1', 'Sensor remote configuration', 'width=800,height=600,location=no');\n}",
"show() {\n this.playerWindow.show();\n this.playerWindow.focus();\n }",
"show()\n {\n // Don't create multiple windows, focus on last created one instead\n if (this._window && this._window.isDestroyed() === false) {\n this._window.show();\n\n return;\n }\n\n // Create window instance\n this._window = new Electron.BrowserWindow({\n resizable: false,\n center: true,\n minimizable: false,\n maximizable: false,\n title: this.app.translator.getString('preferences'),\n alwaysOnTop: true,\n show: false\n });\n\n // Load the contents\n this._window.loadURL(`file://${__dirname}/preferences.html`);\n\n // While loading the page, the ready-to-show event will be emitted when\n // renderer process has done drawing for the first time, showing window\n // after this event will have no visual flash\n this._window.once('ready-to-show', () => this._window.show());\n }",
"function showLogWindow() {\r\n\t\tGUI.Window(0, logWindowRect, WindowFunction, \"Log Window\");\r\n\t}",
"function showMainScreen() {\n display.set(\"mainScreen\").show();\n }",
"function _remoteEditShow() {\n $('remoteEditTarget').show();\n $('remoteEditholder').show();\n\n $('remoteEditResultHolder').hide();\n $('nodesTable').hide();\n}",
"function show(msg)\n{\n\twindow.open(msg.url,'_target');\n}",
"showAndFocusWindow(windowName = 'main') {\n const browserWindow = this.windows[windowName];\n if (browserWindow) {\n browserWindow.show();\n browserWindow.focus();\n }\n }",
"function showDevTools() {\n GUI.Window.get().showDevTools();\n }",
"function launchDemo() {\r\n\t\r\n\tvar url = \"/servlet/ContentServer?pagename=Sirius/Common/Demo\";\r\n\tvar features = \"menubar=no,locationbar=no,status=no,resizable=yes,height=275,width=605,screenX=10,screenY=10,left=10,top=10\";\r\n\tvar newWin = window.open(url, \"SiriusFlashDemo\", features);\r\n\r\n\treturn;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when user presses the "reconnect" button. Basically restarts channel. | function user_reconnect() {
console.log("User reconnected.");
attempt_reopen_channel = true;
fullyUsedUp = false;
// set this to true so websockets automatically reopen the channel if they fail
open_channel = true;
send_version();
set_ui_state(UI_STATES.CONNECTED);
} | [
"on_reconnect(context) {\n logger.err(\"On_reconnect called. :c\");\n this.currentState = STATE.RECONNECTING;\n stats.reconnectedCount++;\n }",
"_onReconnectAttempt () {\n log( 'Event: reconnect_attempt' );\n\n this.emit( 'reconnect_attempt' );\n }",
"function OnPlayerReconnect(data) {\n\tPlayerReconnected(data.PlayerID, data.PickedHeroes, data.PlayerPicks, data.pickState, data.repickState);\n}",
"function onReconnectButton() {\n\t\t// show in the modal error the information that the connection is being established\n\t\t$(\"#lost-connection-modal .text-danger\").hide();\n\t\t$(\"#lost-connection-modal .text-info\").show();\n\t\t\n\t\tcommunicator.reconnect();\n\t}",
"function OnPlayerReconnect( data ) {\n\tPlayerReconnected( data.PlayerID, data.PickedHeroes, data.PlayerPicks, data.pickState, data.repickState);\n}",
"function onReconnectButton() {\n // show in the modal error the information that the connection is being established\n $(\"#lost-connection-modal .text-danger\").hide();\n $(\"#lost-connection-modal .text-info\").show();\n\n communicator.reconnect();\n }",
"function onReconnectButton() {\n // show in the modal error the information that the connection is being established\n $(\"#lost-connection-modal .text-danger\").hide();\n $(\"#lost-connection-modal .text-info\").show();\n \n communicator.reconnect();\n }",
"reconnectPlayer() {\n idleHelpers.removeListeners();\n\n this.socket.connect();\n\n this.clearBoard(true, false, false, false);\n }",
"reconnected () {\n window.location.reload() // This triggers another websocket disconnect/connect (!)\n }",
"function connectionErrorRestart() {\n if(!isSessionActive) {\n return;\n }\n\n slackBot.postMessageToChannel(process.env.SLACK_CHANNEL, '*_Error connecting to Omegle. Retrying..._*', {\n username: 'ManInTheMiddle',\n icon_url: process.env.SLACK_ICON\n }, function() {\n regularRestart();\n });\n}",
"function onReconnect() {\n emitHello();\n $log.log(\"monitor is reconnected\");\n }",
"reconnect() {\n this.debug('Attemping to reconnect in 5500ms...');\n /**\n * Emitted whenever the client tries to reconnect to the WebSocket.\n * @event Client#reconnecting\n */\n this.client.emit(Constants.Events.RECONNECTING);\n this.connect(this.gateway, 5500, true);\n }",
"async reconnect()\n {\n // nothing to do\n }",
"reconnect() {\n if (this.retry || this.isShutdown) {\n this.isShutdown = false;\n logger.info('Connection retry in progress...');\n return;\n }\n\n const tokenLastFourDigit = this.token.substring(this.token.length - 5);\n this.retry = true;\n\n if (\n !this.retryCountStore[tokenLastFourDigit] ||\n this.retryCountStore[tokenLastFourDigit] >= 20\n ) {\n this.retryCountStore[tokenLastFourDigit] = 0;\n }\n\n this.retryCountStore[tokenLastFourDigit] =\n this.retryCountStore[tokenLastFourDigit] + 1;\n /*\n Initial retry is 5 seconds and consecutive\n retry is mulitple of number of retries to allow\n enough time for network recovery or for something bad.\n */\n const timer = Math.pow(this.retryCountStore[tokenLastFourDigit], 2) * 500;\n\n logger.info(\n 'No connection, will attempt to retry for bot token ' +\n tokenLastFourDigit +\n ' in ' +\n timer / 1000 +\n ' seconds'\n );\n\n setTimeout(() => {\n logger.info('Retrying to connect for ' + tokenLastFourDigit);\n return this.connect();\n }, timer);\n }",
"reconnect() {\n if (this.lockReconnect) {\n return;\n }\n this.lockReconnect = true;\n this.reTt && clearTimeout(this.reTt);\n this.reTt = setTimeout(() => {\n this.createWebSocket();\n this.lockReconnect = false;\n }, 2000);\n }",
"_reconnect() {\n if (this.socket.readyState === 1) {\n this.disconnect()\n }\n\n if (++this.reconnects <= MAX_RECONNECTS) {\n console.warn(\n `attempting to reconnect...${this.reconnects}/${MAX_RECONNECTS}`\n )\n this.connect()\n }\n }",
"reconnect() {\n this._socket.close('reconnect');\n this._initSocket();\n }",
"function reconnect() {\n if(mpcStatus === MPC_RECONNECTING) {\n return\n }\n mpc = null;\n mpcStatus = MPC_RECONNECTING;\n setTimeout(() => {\n connect();\n }, 3000);\n}",
"function reconnect(reconnectInterval) {\n if (reconnectInterval > MAX_RETRY_TIME_MS) {\n if (config.onstopreconnectattempts) {\n config.onstopreconnectattempts()\n }\n } else {\n totalNumRetries++;\n setTimeout(function () {\n if (config.onreconnecting) {\n config.onreconnecting();\n }\n ws = resetWebSocket(config);\n\n }, reconnectInterval)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
= Description Call this if you need to remove a component from its parent's views array without destroying the DOM element itself, making it in effect a view without parent. Useful, for example, for moving a view from one parent component to another. = Returns +self+ | remove() {
if (this.parent) {
const _viewZIndex = this.parent.viewsZOrder.indexOf(this.viewId);
const _viewParentIndex = this.parent.views.indexOf(this.viewId);
this.parent.views.splice(_viewParentIndex, 1);
HSystem.delView(this.viewId);
this.parent.viewsZOrder.splice(_viewZIndex, 1);
const _sysUpdateZIndexOfChildrenBufferIndex = HSystem._updateZIndexOfChildrenBuffer.indexOf(this.viewId);
if (_sysUpdateZIndexOfChildrenBufferIndex !== -1) {
HSystem._updateZIndexOfChildrenBuffer.splice(_sysUpdateZIndexOfChildrenBufferIndex, 1);
}
this._updateZIndexAllSiblings();
delete this.parent;
this.parents = [];
}
return this;
} | [
"remove() {\n for (let i = 0; i < this._childViews.length; i++) {\n // no need to unregister child from parent,\n // since the parent is also being removed\n this._childViews[i]._unregisterFromParent = false;\n this._childViews[i].remove();\n }\n\n if (this._parentView && this._unregisterFromParent) {\n this._parentView.unregisterChild(this);\n }\n\n super.remove();\n\n this._removed = true;\n }",
"remove() {\n\t\tif( this.parent instanceof Container ) {\n\t\t\tthis.parent.children.splice(this.parent.children.indexOf(this),1);\n\t\t\tif( this.parent.children.length === 0 ) {\n\t\t\t\tthis.parent.remove();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.parent.redraw();\n\t\t\t}\n\t\t}\n\t}",
"_removeView(view) {\n if (_trace__WEBPACK_IMPORTED_MODULE_4__[\"Trace\"].isEnabled()) {\n _trace__WEBPACK_IMPORTED_MODULE_4__[\"Trace\"].write(\"\".concat(this, \"._removeView(\").concat(view, \")\"), _trace__WEBPACK_IMPORTED_MODULE_4__[\"Trace\"].categories.ViewHierarchy);\n }\n\n if (view.parent !== this) {\n throw new Error('View not added to this instance. View: ' + view + ' CurrentParent: ' + view.parent + ' ExpectedParent: ' + this);\n }\n\n if (this.domNode) {\n this.domNode.onChildRemoved(view);\n }\n\n this._removeViewCore(view);\n\n view.parent = undefined;\n\n view._parentChanged(this);\n }",
"removeComponent() {\n if (this.ptr == 0) {\n throw \"this is disposed\";\n }\n instance().exports.LayoutEditor_remove_component(this.ptr);\n }",
"remove() {\n this.el.parentNode.removeChild(this.el)\n }",
"remove(){\n this.removeViews(Object.keys(this.views));\n this.el.innerHTML = null;\n this.layouts[this.layout].isRendered = false;\n this.layout = null;\n }",
"detachFromParent() {\n scene.add(this);\n this.parent.removeDirectChild(this);\n }",
"destroy() {\r\n\t\tthis.parentComponent.removeChild(this.el);\r\n\r\n\t\tthis.cleanThis();\r\n\t}",
"remove(){\n this.view.remove();\n }",
"function remove_component() {\n // shift focus elsewhere\n\n // visually remove the component container\n var component_ref = getObject( this.id );\n component_ref.parentNode.removeChild( component_ref );\n \n // correct any pointers in the pipeline on adjacent components/sets\n var node_originally_above = this.node.up;\n var node_originally_below = this.node.down;\n \n node_originally_above.setNodeBelow( node_originally_below );\n node_originally_below.setNodeAbove( node_originally_above );\n \n if ( node_originally_below.type == 'component' ) {\n components[node_originally_below.id].checkArrows();\n }\n \n if ( node_originally_above.type == 'component' ) {\n components[node_originally_above.id].checkArrows();\n }\n \n this.node.remove();\n \n // remove component from javascript data structures\n delete components[ this.id ];\n}",
"removeCurrentView() {\n if (this.currentView && this.currentView.remove) {\n this.currentView.remove();\n }\n }",
"remove() {\n BaseElement.controller.remove(this);\n this.root.remove();\n }",
"remove() {\r\n if (this.parent) {\r\n this.parent.removeChild(this);\r\n }\r\n }",
"function remove () {\n this.removeAllChildren();\n\n if (this.parent && _.contains(this.parent.children, this)) {\n this.parent.removeChild(this);\n }\n\n this.trigger('onRemove');\n\n\n if (this.model) {\n this.model.off();\n this.model.stopListening();\n delete this.model;\n }\n\n if (!this.$el) {\n this.$el = $('<div/>');\n }\n Backbone.View.prototype.remove.apply(this, arguments);\n\n\n if (this.$el) {\n this.undelegateEvents();\n this.$el.removeData().unbind();\n this.$el.empty();\n delete this.$el;\n }\n\n if (this.el) {\n delete this.el;\n }\n }",
"destroyElement(view) {\n view.renderer.remove(view, false);\n return view;\n }",
"_removeView(view) {\n if (Trace.isEnabled()) {\n Trace.write(`${this}._removeView(${view})`, Trace.categories.ViewHierarchy);\n }\n if (view.parent !== this) {\n throw new Error('View not added to this instance. View: ' + view + ' CurrentParent: ' + view.parent + ' ExpectedParent: ' + this);\n }\n if (this.domNode) {\n this.domNode.onChildRemoved(view);\n }\n this._removeViewCore(view);\n view.parent = undefined;\n view._parentChanged(this);\n }",
"function remove() {\n domUtils.removeElement(this.owner.el);\n}",
"destroy() {\n this.listen(false);\n this.parent.children.splice(this.parent.children.indexOf(this), 1);\n this.parent.controllers.splice(this.parent.controllers.indexOf(this), 1);\n this.parent.$children.removeChild(this.domElement);\n }",
"removeElement() {\n this.el.parentNode.removeChild(this.el);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set click events for mobile nav and country selector | setEvents() {
$('.fa-bars').click(() => {
$('.top-nav').addClass('-active');
});
this.$navToggle.on('click', (e) => {
e.preventDefault();
this.$navMenu.toggleClass('-active');
this.$navToggle.toggleClass('-close');
});
$(document).on('click', this.$countryToggle.selector, (e) => {
e.preventDefault();
if (this.$countryMenu.hasClass('-active')) {
this.$countryToggle.removeClass('-close');
this.$countryMenu.removeClass('-active');
} else {
this.$countryToggle.addClass('-close');
this.$countryMenu.addClass('-active');
}
});
$(document).on('click', (e) => {
// Closes country dropdown on desktop if clicked outside the dropdown
if (!$(e.target).closest('.country-container').length && (e.target.className !== 'header-site-links' && !$(e.target).closest('.header-site-links').length)) {
$('.country-dropdown').removeClass('-active');
}
// Closes country dropdown menu on mobile-only if clicked anywhere but one of the actual links
if ((e.target.className !== 'country-dropdown-list' && !$(e.target).closest('.header-site-links').length) && (this.$countryMenu.hasClass('-active') && this.$navToggle.is(':visible'))) {
$('.country-dropdown').removeClass('-active');
}
});
} | [
"function setClickEvents() {\n // Toggle html class\n [...nodes.navToggle].forEach((btn) => {\n btn.addEventListener('click', () => {\n App.EM.emit('Nav::toggle');\n });\n });\n }",
"function initMobileNav() {\n jQuery('.wrap').mobileNav({\n menuActiveClass: 'active',\n menuOpener: '.opener'\n });\n \n jQuery('.wrap2').mobileNav({\n hideOnClick: true,\n menuActiveClass: 'active',\n menuOpener: '.opener',\n menuDrop: '.drop'\n });\n jQuery('.menu li').touchHover({ hoverClass: 'custom-hover' });\n}",
"function setupNavClickHandlers() {\n variables.nav.find(\"a\").each(function() {\n $(this).click(function(e) {\n e.preventDefault();\n if (this.hash !== \"\") {\n scrollToElement(this.hash, 200, -80);\n } else {\n scrollToElement(variables.body, 200, 0);\n }\n\n });\n });\n }",
"function mobileButtonClick(selector, handler) {\n selector.on('click touchstart', handler);\n}",
"function initMobileNav() {\n\n\t//OPEN/CLOSES THE MOBILE NAV\n\tfunction toggleMobileNav(event) {\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\t\n\t\t$('body').toggleClass('mobile-nav--is-open');\n\t\twindow.scrollTo(0,0);\n\t}\n\n\t$('.mobile-nav-handler--toggle').on('click', toggleMobileNav);\n\t//CLOSES MOBILE NAV\n\t$('.mobile-nav-handler--close').on('click', toggleMobileNav);\n}",
"function touchNav() {\r\n $(\"#work-carousel-mobile\").on(\"swipeleft\", function () {\r\n $(\".right.carousel-control\").trigger(\"click\");\r\n });\r\n $(\"#work-carousel-mobile\").on(\"swiperight\", function () {\r\n $(\".left.carousel-control\").trigger(\"click\");\r\n });\r\n }",
"function touchNavigation() {\r\n L1Link.on('click keydown', primaryNavEvent);\r\n L2Link.on('click keydown', secondaryNavEvent);\r\n backLink.on('click keydown', goBackEvent);\r\n}",
"function mobileSelectOpen() {\n $('.clinic-item').on('click', function(e){\n e.preventDefault();\n\n $('.mobile-menu').removeClass('is-open');\n $('body').addClass('mobile-select-menu_is-open');\n $('.mobile-select-menu').addClass('is-open');\n })\n }",
"function pagesWithHeaderMobile() {\n // Show page information/instructions on icon click\n if ($(\".info-drop-down\").length > 0) {\n // $(\".header-page-icon\").on(\"click\", toggleOverlays);\n $(\".close-drop-down\").on(\"click\", function() {\n $(\".info-drop-down\").removeClass(\"pull-down\");\n $(\".will-blur\").removeClass(\"blur\");\n $(\".prevent-click\").removeClass(\"visible\");\n $(\".header-page-icon\").removeClass(\"open\");\n });\n\n $(\".header-page-icon\").on(\"click\", function() {\n $(this).toggleClass(\"open\");\n $(\".info-drop-down\").toggleClass(\"pull-down\");\n $(\".will-blur\").toggleClass(\"blur\");\n $(\".prevent-click\").toggleClass(\"visible\");\n });\n }\n // $(\".menu-btn\").on(\"click\", toggleOverlays);\n // $(\".prevent-click\").on(\"click\", toggleOverlays);\n\n $(\".menu-btn\").on(\"click\", function() {\n $(\".menu\").toggleClass(\"pull-right\");\n $(\".will-blur\").toggleClass(\"blur\");\n $(\".prevent-click\").toggleClass(\"visible\");\n });\n\n $(\".prevent-click\").on(\"click\", function() {\n $(\".info-drop-down\").removeClass(\"pull-down\");\n $(\".menu\").removeClass(\"pull-right\");\n $(\".will-blur\").removeClass(\"blur\");\n $(\".prevent-click\").removeClass(\"visible\");\n $(\".header-page-icon\").removeClass(\"open\");\n });\n\n // console.log(\"loaded js for pages with mobile header\");\n }",
"function bindNavEvents() {\n\t\tbp.CONF.els.sections.find('.arrow img').click(function() {\n\n\t\t\tvar currentSection = bp.CONF.els.container.find('.ss-active');\n\t\t\tvar nextSection = currentSection.next();\n\n\t\t\tbp.CONF.els.win.scrollTo(nextSection, 500, {easing: 'easeOutCirc', 'axis':'y'});\n\t\t});\n\n\t\tbp.CONF.els.sections.find('.arrowTop img').click(function() {\n\t\t\tbp.CONF.els.win.scrollTo($('#landing-page'), 500, {easing: 'easeOutCirc', 'axis':'y'});\n\t\t});\n\t}",
"function mobMenu(){\n\t\t$('#mob-menu-contacts').click(function(e){\n\t\t\t$('.open-menu__left').hide();\n\t\t\t$('.open-menu__right').show();\n\t\t})\n\t\t$('#mob-menu-contacts--back').click(function(e){\n\t\t\t$('.open-menu__left').show();\n\t\t\t$('.open-menu__right').hide();\n\t\t})\n\t}",
"function setUpClickHandlers() {\n $('#button-search').click(searchClicked);\n $('#back-to-front').click(startNewSearch);\n $('#get-location').click(getCurrentLocation);\n}",
"function mobileItemClicked(e) {\n\t\tif (mobileMenu.is(':visible')) {\n\t\t\twholeContent.removeClass('mobile-opened', speeed, type, function(){\n\t\t\t\tmobileMenu.hide();\n\t\t\t});\n\t\t} else {\n\t\t\tmobileMenu.show();\n\t\t\twholeContent.addClass('mobile-opened', speeed, type);\t\t\t\n\t\t}\n\t\t$('.mobile-heading').trigger('click');\n\t}",
"function countryClick() {\n let countryBtn = document.getElementsByClassName('btn--country');\n for (var i = 0; i < countryBtn.length; i++) {\n countryBtn[i].addEventListener('click', clickOnCountry, false);\n }\n }",
"function manageMobileView() {\r\n //----- Legislative nav\r\n\r\n //toggle top-level\r\n jQuery('#leg_mobile_LegNavHeader h2').click(function (event) {\r\n toggleNavHeader('leg_mobile_LegNavHeader', 'leg_LegNav');\r\n event.preventDefault(); //don't follow a link\r\n });\r\n\r\n //toggle core links\r\n jQuery('.leg_LegNavTop').click(function (event) {\r\n var returnStatus = handleNavCore(this, 'leg_LegNav', true);\r\n if (returnStatus == true) {\r\n return;\r\n }\r\n else {\r\n event.preventDefault(); //don't follow a link\r\n }\r\n });\r\n\r\n jQuery('.leg_LegNav .leg_mobile_Accordion').click(function (event) {\r\n handleNavCore(this, 'leg_LegNav', false);\r\n event.preventDefault(); //don't follow a link\r\n });\r\n\r\n\r\n //----- office nav\r\n\r\n //toggle top-level\r\n jQuery(\"#leg_mobile_OfficeNavHeader h2\").click(function (event) {\r\n toggleNavHeader('leg_mobile_OfficeNavHeader', 'leg_OfficeNav');\r\n event.preventDefault(); //don't follow a link\r\n });\r\n\r\n //toggle core links\r\n jQuery('.leg_OfficeNavTop').click(function () {\r\n var returnStatus = handleNavCore(this, 'leg_OfficeNav', true);\r\n if (returnStatus == true) {\r\n return;\r\n }\r\n else {\r\n event.preventDefault(); //don't follow a link\r\n }\r\n });\r\n\r\n jQuery('.leg_OfficeNav .leg_mobile_Accordion').click(function (event) {\r\n handleNavCore(this, 'leg_OfficeNav', false);\r\n event.preventDefault(); //don't follow a link\r\n });\r\n } //end manageMobileView()",
"_registerOpenTriggerEvents() {\n const event = (DeviceDetection.isTouchDevice()) ? 'touchstart' : 'click';\n\n this.el.addEventListener(event, this._onOpenOffCanvasCart.bind(this));\n }",
"function mobile_nav_close_listener() {\r\n document.getElementsByTagName('nav')[0].addEventListener('mousedown', nav_swip_down, true);\r\n document.getElementsByTagName('nav')[0].addEventListener('touchstart', nav_swip_down, true);\r\n document.getElementsByTagName('nav')[0].addEventListener('mouseup', nav_swip_up, true);\r\n document.getElementsByTagName('nav')[0].addEventListener('touchend', nav_swip_up, true);\r\n}",
"_onWindowClick(event) {\n if (this.element.classList.contains('mobile-side-in') && !event.target.closest('#nav')) {\n this._hideMobileMenu();\n }\n }",
"function mobileClinicOpen() {\n $('.open-clinic-menu').on('click', function(e){\n e.preventDefault();\n $(this).toggleClass('active');\n\n $('.mobile-menu').removeClass('is-open');\n $('.mobile-select-menu').removeClass('is-open');\n\n $('body').removeClass('mobile-menu_is-open');\n $('body').removeClass('mobile-select-menu_is-open');\n $('body').toggleClass('mobile-clinic-menu_is-open');\n $('.mobile-clinic-menu').toggleClass('is-open');\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws the axes on the chart, on the bottom and to the right. TODO: Different axes styles, i.e. x=0, y=0, right, left | draw_axes () {
let canvas = this.layers.get(CONST.CHART_LAYER_AXES);
// Draw axes
let ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = CONST.WHITE;
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(0, canvas.height-this.chart_padding_x_axis);
ctx.lineTo(canvas.width - this.chart_padding_y_axis, canvas.height-this.chart_padding_x_axis);
ctx.lineTo(canvas.width - this.chart_padding_y_axis, 0);
ctx.stroke();
this.draw_axes_labels();
} | [
"function draw_axes() {\n\t\t// Open the path to start drawing\n\t\tcontext.beginPath();\n\t\t\n\t\t// Start the path at the top of the y-axis\n\t\tcontext.moveTo(40, graph_properties.top_gap);\n\t\t\n\t\t// Draw the rest of the path\n\t\tcontext.lineTo(40, 344);\n\t\tcontext.lineTo(490, 344);\n\t\tcontext.lineTo(490, 339);\n\t\t\n\t\t// Set the color of the axes and slap 'em in\n\t\tcontext.strokeStyle = graph_properties.axes_color;\n\t\tcontext.stroke();\n\t}",
"function draw_axes(ctx) {\n const xm = g_eye == EYE_LEFT ? 1 : -1 ; \n\n const x_axis_y = g_cy +28*g_d2p; // virtual pixels\n const y_axis_x = g_cx -35*g_d2p; // virtual pixels\n const tick_len = 1.0 * g_d2p; // virtual pixels\n\n // draw axes\n ctx.fillStyle = \"black\";\n ctx.strokeStyle = \"black\";\n ctx.lineWidth=1;\n ctx.moveTo(scale(g_cx - 27*g_d2p), yscale(x_axis_y)); // x-axis\n ctx.lineTo(scale(g_cx + 27*g_d2p), yscale(x_axis_y));\n ctx.moveTo(scale(y_axis_x), yscale(g_cy -27*g_d2p)); // y-axis\n ctx.lineTo(scale(y_axis_x), yscale(g_cy +27*g_d2p)); \n\n ctx.font= scale(20) + \"px Arial\";\n ctx.textBaseline=\"middle\"; \n for (i = -27 ; i <= 27 ; i += 6) {\n // x-ticks\n const x = scale(g_cx + i*g_d2p);\n ctx.moveTo(x, yscale(x_axis_y)); \n ctx.lineTo(x, yscale(x_axis_y + tick_len));\n ctx.textAlign = \"center\"; // below?\n ctx.fillText(i, x, yscale(x_axis_y + tick_len + 20/2));\n\n // y-ticks\n const y = yscale(g_cy + i*g_d2p);\n ctx.moveTo(scale(y_axis_x - tick_len), y); \n ctx.lineTo(scale(y_axis_x) , y);\n ctx.textAlign = \"right\";\n ctx.fillText(-i, scale(y_axis_x - tick_len), y);\n }\n ctx.stroke();\n\n // axis sliders\n ctx.beginPath();\n ctx.font = scale(20) + \"px Arial\";\n ctx.fillStyle = \"purple\";\n ctx.strokeStyle = \"purple\";\n ctx.textBaseline=\"middle\"; \n\n // draw ONHX slider \n var tx = scale(g_cx + xm * g_onhx * g_d2p);\n var ty = yscale(x_axis_y + 4.0 * g_d2p);\n ctx.font = scale(18) + \"px Arial\";\n ctx.textAlign = \"center\";\n ctx.fillText(\"ONH \" + xm * g_onhx, tx, ty + yscale(1.0 * g_d2p));\n ctx.moveTo(tx, ty);\n ctx.lineTo(tx, yscale(x_axis_y));\n ctx.stroke();\n g_regions.push([tx, ty, REGION_ONHX]);\n\n // draw ONHY slider \n tx = scale(y_axis_x - 3.0 * g_d2p);\n ty = yscale(g_cy + g_d2p * g_onhy);\n ctx.textAlign = \"right\";\n ctx.fillText(\"ONH \" + g_onhy, tx, ty);\n ctx.moveTo(tx, ty);\n ctx.lineTo(scale(y_axis_x), ty);\n ctx.stroke();\n g_regions.push([tx, ty, REGION_ONHY]);\n\n ctx.closePath();\n}",
"drawAxes() {\n this.statePlot.drawAxes(true)\n this.barChart.drawAxes()\n }",
"addAxes () {\n this.setTickSizes();\n var axis, svgAxis, orient, axisTransform,\n leftTickSize = this.getTickSize(\"left\"),\n rightTickSize = this.getTickSize(\"right\")/*,\n topTickSize = this.getTickSize(\"top\"),\n bottomTickSize = this.getTickSize(\"bottom\")*/;\n\n this.svg.selectAll(`.${defaultClasses.AXIS}`).remove();\n\n for(let axisName in this.axes.axes) {\n axis = this.axes.axis(axisName);\n orient = axis.orient();\n\n svgAxis = this.svg.append(\"g\")\n .classed({\n [defaultClasses.AXIS]: true,\n [defaultClasses.AXIS + \"-\" + axisName]: true\n });\n switch (orient) {\n case \"left\":\n axisTransform = `translate(${leftTickSize}, 0)`;\n break;\n case \"bottom\":\n axisTransform = `translate(${leftTickSize}, ${this.dimensions.height})`;\n break;\n case \"right\":\n axisTransform = `translate(${this.dimensions.width - rightTickSize}, 0)`;\n break;\n default:\n axisTransform = \"translate(0, 0)\";\n break;\n }\n svgAxis.attr(\"transform\", `${axisTransform}`)\n .call(axis);\n }\n\n this.addGridArea();\n this.addChartArea();\n // this.addZones();\n this.event.trigger(\"axis_rendered\");\n }",
"function drawAxes(svg) {\n // Note: scales must be updated first\n let leftAxis = d3.axisLeft(yScale);\n let bottomAxis = d3.axisBottom(xScale);\n if (useGrid) {\n leftAxis.tickSize(-1 * (width - margin.right - margin.left - chartPadding/2));\n bottomAxis.tickSize(-1 * (height - margin.top - margin.bottom - chartPadding));\n }\n svg.append(\"g\")\n .attr('id', 'yAxis')\n .attr('transform', translate(margin.left - 10, margin.top))\n .call(leftAxis);\n svg.append(\"g\")\n .attr('id', 'xAxis')\n .attr(\"transform\", translate(margin.left, height - margin.bottom))\n .call(bottomAxis);\n\n // Draw the titles\n let labels = svg.append('g')\n .attr('id', 'labels');\n\n let xTitle = svg.attr(xTitleAttr);\n labels.append('text')\n .text(xTitle)\n .style('fill', 'black')\n .style('font-size', '0.8rem')\n .attr('id', 'xTitle')\n .attr('text-anchor', 'middle')\n .attr(\"transform\", translate(width / 2 , height - margin.bottom))\n .attr('x', 0)\n .attr('y', +35);\n\n let yTitle = svg.attr(yTitleAttr);\n let rotateGroup = labels.append('g')\n .attr('id', 'group-yTitle')\n .attr(\"transform\", translate(margin.left , ((height-margin.bottom - margin.top) / 2) + margin.top));\n\n rotateGroup.append('text')\n .text(yTitle)\n .style('fill', 'black')\n .style('font-size', '0.8rem')\n .attr('id', 'yTitle')\n .attr('text-anchor', 'middle')\n .attr('transform', \"rotate(-90)\")\n // .attr('x', -10)\n .attr('y', -45);\n }",
"function appendAxes() {\n graphImg\n .append(\"g\")\n .call(xAxis)\n .attr(\"class\", \"xAxis\")\n .attr(\n \"transform\",\n \"translate(0,\" + (displayHeight - margin - labelArea) + \")\"\n );\n graphImg\n .append(\"g\")\n .call(yAxis)\n .attr(\"class\", \"yAxis\")\n .attr(\"transform\", \"translate(\" + (margin + labelArea) + \", 0)\");\n }",
"drawAxes() {\n this.context.fillStyle = DEFAULT_PLOT_PARAMETERS.color;\n\n if(this.drawYAxis) {\n assert(this.range.x.min <= 0 && this.range.y.max >= 0,\n 'Cannot draw the y axis as it is out of range.')\n\n let labelWidth = this.context.measureText('y').width;\n\n //has to be fudged to look right\n let labelPosY = 0;\n let labelPosX = this.center.x - (labelWidth / 2);\n this.context.fillText('y', labelPosX, labelPosY);\n\n this._drawLine(this.center.x, LABELHEIGHT + AXIS_ARROW_LENGTH, this.center.x,\n this.height, 2);\n\n this.context.beginPath();\n this.context.lineWidth = 1;\n this.context.moveTo(this.center.x, LABELHEIGHT);\n this.context.lineTo(this.center.x + 5, LABELHEIGHT + AXIS_ARROW_LENGTH);\n this.context.lineTo(this.center.x - 5, LABELHEIGHT + AXIS_ARROW_LENGTH);\n this.context.fill();\n\n if(this.drawYUnits) {\n let stepSize = this.stepY;\n let i = stepSize.times(Math.ceil(this.drawRegion.bottom / stepSize.approx));\n for(; i.lessThan(this.drawRegion.top); i = i.plus(stepSize)) {\n if(!(i.equal(0))) {\n let yPos = this.center.y - i.approx * this.unitSize.y;\n\n this._drawLine(this.center.x, yPos, this.center.x + 6, yPos, 2);\n i.draw(this.context, {top: yPos, right: this.center.x});\n\n if(this.drawGrid) {\n this._drawLine(0, yPos, this.width - LABELWIDTH, yPos, 1,\n [5, 5]);\n }\n }\n }\n }\n }\n\n if(this.drawXAxis) {\n assert(this.range.y.min <= 0 && this.range.y.max >= 0,\n 'Cannot draw the x axis as it is out of range.')\n\n let labelWidth = this.context.measureText('x').width;\n\n //has to be fudged to look right\n let labelPosY = this.center.y - FONTSIZE / 2;\n let labelPosX = this.width - (LABELWIDTH / 2) - (labelWidth / 2);\n this.context.fillText('x', labelPosX, labelPosY);\n\n this._drawLine(0, this.center.y, this.width - LABELWIDTH - AXIS_ARROW_LENGTH, this.center.y, 2);\n\n this.context.beginPath();\n this.context.lineWidth = 1;\n this.context.moveTo(this.width - LABELWIDTH, this.center.y);\n this.context.lineTo(this.width - LABELWIDTH - AXIS_ARROW_LENGTH, this.center.y + 5);\n this.context.lineTo(this.width - LABELWIDTH - AXIS_ARROW_LENGTH, this.center.y - 5);\n this.context.fill();\n\n if(this.drawXUnits) {\n let stepSize = this.stepX;\n let xMin = this.range.x.min\n let i = stepSize.times(Math.ceil(this.drawRegion.left / stepSize.approx));\n for(; i.lessThan(this.drawRegion.right); i = i.plus(stepSize)) {\n if(!(i.equal(0))) {\n let xPos = this.center.x + i.approx * this.unitSize.x;\n\n //are any of the labels fractions? if step is an integer,\n //or an integral multiple of pi, then no.\n if(stepSize.approx === parseInt(stepSize.approx)) {\n var areFractions = false;\n } else {\n let stepSizeDivPi = stepSize.divide(new Rational(\"pi\"));\n\n if(stepSizeDivPi.approx === parseInt(stepSizeDivPi.approx)) {\n var areFractions = false;\n } else {\n var areFractions = true;\n }\n }\n\n this._drawLine(xPos, this.center.y, xPos, this.center.y - 6, 2);\n\n let labelYPos = this.center.y + MARKING_PADDING_TOP;\n if(i.greaterThan(0)) {\n i.draw(this.context, {top: labelYPos, left: xPos}, areFractions);\n } else if(i.lessThan(0)) {\n i.draw(this.context, {top: labelYPos, right: xPos}, areFractions);\n }\n\n if(this.drawGrid) {\n this._drawLine(xPos, LABELHEIGHT, xPos, this.height, 1,\n [5, 5]);\n }\n }\n }\n }\n }\n\n //draw origin\n if(this.drawOrigin) {\n let origin = new Rational(0);\n origin.draw(this.context, {top: this.center.y, right: this.center.x});\n }\n }",
"drawAxes() {\n this.drawLabels([\n { label: LightTypes.A, column: 9 },\n { label: LightTypes.B, column: 10 },\n ])\n \n let colLabels = new Array(8).fill(null).map((_, i) => ({ label: `${i + 1}`, column: i }))\n this.drawLabels(colLabels)\n \n this.ctx.beginPath()\n this.ctx.strokeStyle = \"black\"\n this.ctx.moveTo(0, this.maxDrawH * 1.01)\n this.ctx.lineTo(this.w, this.maxDrawH * 1.01)\n this.ctx.moveTo(8 * this.barColumnW + this.barColumnW / 2, this.h)\n this.ctx.lineTo(8 * this.barColumnW + this.barColumnW / 2, 0)\n this.ctx.stroke()\n }",
"function drawYAxis() {\n // draw tick marks and labels\n var domain = y1Domain,\n styles = vis.__styles,\n ticks = vis.getYTicks(scales.y, c.h, extendRange, useLogScale);\n\n if (!extendRange && ticks[ticks.length-1] != domain[1]) ticks.push(domain[1]);\n\n if ($('body').hasClass('fullscreen')) {\n theme.horizontalGrid['stroke-width'] = 2;\n }\n\n _.each(ticks, function(val, t) {\n var y = scales.y(val), x = c.lpad;\n if (val >= domain[0] && val <= domain[1] || extendRange) {\n // c.paper.text(x, y, val).attr(styles.labels).attr({ 'text-anchor': 'end' });\n\n // axis label\n vis.label(x+2, y-10, formatter.y1(val, t == ticks.length-1), { align: 'left', cl: 'axis' });\n // axis ticks\n if (theme.yTicks) {\n vis.path([['M', c.lpad-25, y], ['L', c.lpad-20,y]], 'tick');\n }\n // grid line\n if (theme.horizontalGrid) {\n vis.path([['M', c.lpad, y], ['L', c.w - c.rpad,y]], 'grid')\n .attr(theme.horizontalGrid);\n }\n }\n });\n\n // draw axis line\n if (domain[0] <= 0 && domain[1] >= 0) {\n y = scales.y(0);\n vis.path([['M', c.lpad, y], ['L', c.w - c.rpad,y]], 'axis')\n .attr(theme.xAxis);\n }\n }",
"function renderAxis() {\n dom.axis.x0\n .call(drag);\n\n dom.axis.x1\n .call(drag);\n\n dom.axis.x0\n .transition()\n .duration(transitionDuration)\n .call(axis.x0);\n\n dom.axis.x1\n .transition()\n .duration(transitionDuration)\n .call(axis.x1);\n\n axis.y.tickSize(WIDTH - mg.l);\n\n dom.axis.y\n .call(axis.y)\n .call(drag);\n\n dom.axis.boundaries\n .attr('x1', (d, i) => scale.x.range()[i])\n .attr('x2', (d, i) => scale.x.range()[i])\n .attr('y1', 10)\n .attr('y2', 20);\n\n dom.axis.label1\n .attr('x', scale.x.range()[1] - 5);\n }",
"function drawAxes() {\n\t//draw axes\n\tvar ctx = c.getContext(\"2d\");\n\tctx.lineWidth = 1;\n\tctx.beginPath();\n\tctx.moveTo(axesOffset, axesOffset);\n\tctx.lineTo(axesOffset, canvasHeight - axesOffset);\n\tctx.lineTo(canvasWidth - axesOffset, canvasHeight - axesOffset);\n\tctx.strokeStyle = \"#000000\";\n\tctx.stroke();\n\t\n\t//draw interval markers\n\tvar markLength = 5;\n\txInterval = xMax / numAxisMarkers;\n\tyInterval = yMax / numAxisMarkers;\n\tctx.font = \"12px Courier\";\n\tctx.fillStyle = \"#000000\";\n\t\n\t//x axis interval markers\n\tfor (var i = 1; i < numAxisMarkers + 1; i++) {\n\t\tctx.beginPath();\n\t\tctx.moveTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset);\n\t\tctx.lineTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset - markLength); //5 = marker length\n\t\tctx.stroke();\n\t\tctx.textAlign = \"center\";\n\t\tctx.fillText(Number((i * xInterval).toFixed(3)), axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset + 12); //12 is text offset\n\t\t\n\t\t//draw the grid if enabled\n\t\tif (showGrid) {\n\t\t\tctx.save();\n\t\t\tctx.globalAlpha = alpha;\n\t\t\tctx.moveTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset);\n\t\t\tctx.lineTo(axesOffset + (i * graphWidth / numAxisMarkers), canvasHeight - axesOffset - graphWidth);\n\t\t\tctx.stroke();\n\t\t\tctx.restore();\n\t\t}\n\t}\n\t\n\t//y axis interval markers\n\tfor (var i = 1; i < numAxisMarkers + 1; i++) {\n\t\tctx.beginPath();\n\t\tctx.moveTo(axesOffset, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));\n\t\tctx.lineTo(axesOffset + markLength, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers))); //5 = marker length\n\t\tctx.stroke();\n\t\tctx.textAlign = \"right\";\n\t\tctx.fillText(Number((i * yInterval).toFixed(3)), axesOffset - 4, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)) + 3); //4 and 3 are text offset\n\t\t\n\t\t//draw the grid if enabled\n\t\tif (showGrid) {\n\t\t\tctx.save();\n\t\t\tctx.globalAlpha = alpha;\n\t\t\tctx.moveTo(axesOffset, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));\n\t\t\tctx.lineTo(axesOffset + graphHeight, canvasHeight - axesOffset - (i * (graphHeight / numAxisMarkers)));\n\t\t\tctx.stroke();\n\t\t\tctx.restore();\n\t\t}\n\t}\n\t//draw \"0\" at origin\n\tctx.fillText(\"0\", axesOffset - 4, canvasHeight - axesOffset + 4);\n}",
"function drawAxes() {\n\t\t\t\t// x axis\n\t\t\t\tvar xAxis = d3.svg.axis()\n\t\t\t\t\t\t\t\t.scale(xScale)\n\t\t\t\t\t\t\t\t.orient('bottom')\n\t\t\t\t\t\t\t\t.ticks(2);\n\t\t\t\t// y axis\n\t\t\t\tvar yAxis = d3.svg.axis()\n\t\t\t\t\t\t\t\t.scale(yScale)\n\t\t\t\t\t\t\t\t.orient(\"left\")\n\t\t\t\t\t\t\t\t.ticks(2);\n\t\t\t\t// Add x axis\n\t\t\t\tsvg.append('g')\n\t\t\t\t\t.attr(\"transform\", \"translate(0,\" + (height) + \")\")\n\t\t\t\t\t.call(xAxis);\n\t\t\t\t// Add y Axis\n\t\t\t\t\tsvg.append(\"g\")\n\t\t\t\t\t\t\t.attr(\"transform\", \"translate(\"+(0)+\",0)\")\n\t\t\t\t\t\t\t.call(yAxis);\n\t\t\t\t// now add titles to the axes\n\t\t\t\tsvg.append(\"text\")\n\t\t\t\t\t\t.attr(\"text-anchor\", \"middle\") // this makes it easy to centre the text as the transform is applied to the anchor\n\t\t\t\t\t\t.attr(\"transform\", \"translate(\"+ (padding/2) +\",\"+10+\")\") // text is drawn off the screen top left, move down and out and rotate\n\t\t\t\t\t\t.text(\"C 2\"); // Component 2\n\t\t\t\tsvg.append(\"text\")\n\t\t\t\t\t\t.attr(\"text-anchor\", \"middle\") // this makes it easy to centre the text as the transform is applied to the anchor\n\t\t\t\t\t\t.attr(\"transform\", \"translate(\"+ (19*width/20) +\",\"+(height-(padding/3))+\")\") // centre below axis\n\t\t\t\t\t\t.text(\"C1\"); // Component 1\n\n\t\t\t\td3.selectAll(\".domain\").attr(\"fill\", \"none\").attr(\"stroke\", \"black\").attr(\"stroke-width\", 2);\n\t\t\t}",
"function redrawAxes() {\r\n xAxis.scale(xScale)\r\n yAxis.scale(yScale)\r\n\r\n plotXAxis.call(xAxis);\r\n plotYAxis.call(yAxis);\r\n\r\n plotXAxis.selectAll('line').style({\r\n 'fill': 'none',\r\n 'stroke': '#dbdbdb',\r\n 'shape-rendering': 'crispEdges'\r\n })\r\n\r\n var lastBBox;\r\n var rotateLabels = false;\r\n\r\n plotXAxis.selectAll('text').style({\r\n 'text-anchor': 'middle'\r\n })\r\n .attr('transform', 'rotate(0)');\r\n\r\n plotXAxis.selectAll('text').each(function () {\r\n\r\n var currentBBox = this.getBoundingClientRect();\r\n\r\n if (lastBBox == undefined) {\r\n lastBBox = currentBBox;\r\n } else if (lastBBox.right > currentBBox.left - 2) {\r\n rotateLabels = true;\r\n return false;\r\n } else {\r\n lastBBox = currentBBox;\r\n }\r\n });\r\n\r\n if (rotateLabels == true) {\r\n plotXAxis.selectAll('text').style({\r\n 'text-anchor': 'end'\r\n })\r\n .attr('dx', '-.2em')\r\n .attr('dy', '.4em')\r\n .attr('transform', 'rotate(-65)');\r\n }\r\n\r\n plotYAxis.selectAll('line').style({\r\n 'fill': 'none',\r\n 'stroke': '#dbdbdb',\r\n 'shape-rendering': 'crispEdges'\r\n })\r\n\r\n }",
"drawAxis() {\n const y = d3.scaleLinear().range([this.pfBar.chartHeight - this.pfBar.labelHeight, 0]);\n this.base.attr('transform', 'translate(40,10)');\n this.base.call(d3.axisLeft(y));\n }",
"function drawAxes(){\n\tstrokeWeight(3);\n\tstroke(255,22);\n\t// X-axis.\n\tlet xp = width*0.5;\n\tline(xp,0,xp,height);\n\t// X-axis.\n\tlet yp = height*0.5;\n\tline(0,yp,width,yp);\n}",
"function generate_axis()\n{\n canvas\n .append(\"g\")\n .attr(\"id\",\"x-axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(d3.axisBottom(xScale).ticks(5));\n\n\n canvas\n .append(\"g\")\n .attr(\"id\",\"y-axis\")\n .call(d3.axisLeft(yScale).ticks(15))\n .attr(\"transform\", \"translate(0,0)\");\n}",
"function generate_axis(canvas,x_ticks,y_ticks)\n{\n canvas\n .append(\"g\")\n .attr(\"id\",\"x-axis\")\n .attr(\"transform\", \"translate(0,\" + height + \")\")\n .call(d3.axisBottom(xScale).ticks(x_ticks));\n\n\n canvas\n .append(\"g\")\n .attr(\"id\",\"y-axis\")\n .call(d3.axisLeft(yScale).ticks(y_ticks))\n .attr(\"transform\", \"translate(0,0)\");\n}",
"static addDefaultAxes(nodes, ctxt, cfg) {\n if (ctxt.init) { // if first call\n let rv = Hive.facet.getAxes(ctxt);\n // add children to left and bottom\n let leftAxis = Hive.templates.getCfgNode(nodes, 'chart left axis');\n let bottomAxis = Hive.templates.getCfgNode(nodes, 'chart > bottom > axis');\n // let chartBottomAxisContainer = Hive.templates.getCfgNode(nodes, 'chart bottom-container');\n // chartBottomAxisContainer.attr.padding = [];\n\n leftAxis.children = rv.left.nodes.map(d=> {\n // d.attr.padding = [['edge-bottom', 5], ['edge-top', cfg.marginFrame+cfg.marginView+cfg.titleFontSize]];\n d.attr['padding edge-bottom'] = 5;\n d.attr['padding edge-top'] = cfg.marginFrame+cfg.marginView+cfg.titleFontSize;\n return d;\n });\n\n bottomAxis.children = rv.bottom.nodes.map(d=> {\n // d.attr.padding = [['edge-left', 5], ['edge-right', cfg.marginView]];\n d.attr['padding edge-left'] = 5;\n d.attr['padding edge-right'] = cfg.marginView;\n return d;\n });\n\n return rv;\n }\n }",
"function drawAxisLines() {\n\tvar axesColorFromColorPicker;\n\n\t// removing axes, if they do not exist the scene doesn't complain\n\tg_mainScene.remove(g_xAxisLine);\n\tg_mainScene.remove(g_yAxisLine);\n\tg_mainScene.remove(g_zAxisLine);\n\n\t// value should be retrieved from the picker every time the axes are drawn\n\taxesColorFromColorPicker = $(\"#axescolor\").spectrum(\"get\").toHexString(true);\n\taxesColorFromColorPicker = axesColorFromColorPicker.replace('#','0x')\n\taxesColorFromColorPicker = parseInt(axesColorFromColorPicker, 16)\n\n\t// one line for each of the axes\n\tg_xAxisLine = makeLine([g_xMinimumValue, g_yMinimumValue, g_zMinimumValue],\n\t\t[g_xMaximumValue, g_yMinimumValue, g_zMinimumValue], axesColorFromColorPicker, 3);\n\tg_yAxisLine = makeLine([g_xMinimumValue, g_yMinimumValue, g_zMinimumValue],\n\t\t[g_xMinimumValue, g_yMaximumValue, g_zMinimumValue], axesColorFromColorPicker, 3);\n\tg_zAxisLine = makeLine([g_xMinimumValue, g_yMinimumValue, g_zMinimumValue],\n\t\t[g_xMinimumValue, g_yMinimumValue, g_zMaximumValue], axesColorFromColorPicker, 3);\n\n\t// axes shouldn't be transparent\n\tg_xAxisLine.material.transparent = false;\n\tg_yAxisLine.material.transparent = false;\n\tg_zAxisLine.material.transparent = false;\n\n\tg_mainScene.add(g_xAxisLine)\n\tg_mainScene.add(g_yAxisLine)\n\tg_mainScene.add(g_zAxisLine)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Utility function to add metdata to a vFile. | function addMetadata(vFile, destinationFilePath) {
vFile.data = {
destinationFilePath,
destinationDir: path.dirname(destinationFilePath),
};
} | [
"updateDataFile(file, data, info) {\n console.log(file, this._mapFile[file]);\n this._mapFile[file]['info'] = info;\n this._mapFile[file]['data'] = data;\n }",
"function add(data, filepath, stats){\n newUpdates.push({\n app: data.app,\n version: completeVer(data.version),\n channels: data.channels,\n compatible: {\n os: data.os,\n osversion: data.osversion,\n architectures: data.architectures,\n appversion: data.appversion\n },\n percentage: parseFloat(data.percentage) || 100,\n path: path.resolve(path.dirname(filepath), data.path),\n format: data.format || path.extname(data.path).slice(1),\n jsonpath: filepath,\n date: stats.ctime\n });\n }",
"function addMetaData(file, meta) {\n bug(`file=${JSON.stringify(file)}, meta:${JSON.stringify(meta)}`)\n ffm.read(file.dir + file.name, function(err, data) {\n\tbug(`err: ${err}`)\n\tbug(`data before:${JSON.stringify(data)}`)\n\tupdateMeta(data, meta)\n\tbug(`data after switch:${JSON.stringify(data)}`)\n\t\n\tffm.write(file.dir + file.name, data, function(err) {\n\t file.meta = data\n\t if (isValidMeta(data.title)) {\n\t\tbug(\"in write, data.title was valid\")\n\t\t// REWRITE TITLE IF IT HAS\n\t\t\n\t\tfs.renameSync(file.dir + file.name, file.dir + data.title + \".mp3\")\n\t\t// edit file in local storage\n\t\tfile.name = data.title + \".mp3\"\n\t\tbug(`file after rewriting name:${JSON.stringify(file)}`)\n\t\t// this only happens on single edit, so updte immediately\n\t\t\n\t }\n\t bug(\"update comparios\")\n\t bug(`file that might have changed:${JSON.stringify(file)}`)\n\t bug(`current activeFiles:${JSON.stringify(activeFiles)}`)\n\t ipc.updateActiveFiles(activeFiles)\n\t bug(`err = ${err} on file=${JSON.stringify(file)}`)\n\t})\n })\n}",
"addData(key, value) {\n this._additionalData[key] = value;\n }",
"function appendFunction(info) {\n fs.appendFile(\"data.txt\", info, function(err) {\n if (err) {\n console.log(err);\n }\n });\n }",
"set add_meta(v){\n this._meta = Object.assign(this._meta,v);\n this.backup_meta();\n }",
"function processNewFile(file) {\n try {\n var fileinfo = {\n name: file.name,\n type: file.type,\n size: file.size,\n date: file.lastModifiedDate,\n };\n newfiles.push(fileinfo);\n \n if (dsdb.metadataParser) {\n dsdb.metadataParser(file, function(metadata) {\n fileinfo.metadata = metadata;\n cursor.continue();\n }, function(error) {\n console.error(error);\n cursor.continue();\n });\n }\n else {\n fileinfo.metadata = null;\n callback();\n }\n }\n catch(e) {\n console.error(e);\n cursor.continue();\n }\n }",
"function add_metadata() {\n return (files, metalsmith) => {\n Object.keys(files).forEach(file => {\n files[file].meta = metalsmith._metadata;\n });\n };\n}",
"function addFileRecord(pool, tags, file, callback) {\n let meta_string = {\n id: file.id,\n name: file.name,\n size: file.size,\n tags: tags,\n type: file.type\n };\n pool\n .query(\"INSERT INTO files(meta, thumbnail) VALUES($1, $2)\", [JSON.stringify(meta_string), file.thumbnail])\n .then(() => {\n callback(null);\n })\n .catch(error => {\n callback(`Failed to insert new file record of file ${file.name} to database\\n${error}`);\n })\n}",
"addFile(file, metadataPath, options) {\n let mpath = metadataPath;\n if (!mpath) {\n mpath = path.basename(file);\n }\n this.zipFiles.push({\n path: file,\n metadataPath: mpath,\n options\n });\n }",
"addFile(file, metadataPath) {\n let mpath = metadataPath;\n if (!mpath) {\n mpath = path.basename(file);\n }\n this.zipFiles.push({\n path: file,\n metadataPath: mpath\n });\n }",
"updateMeta(filePath, data, indx){\n ipcRenderer.send('exiftool-write', filePath, data, indx);\n }",
"appendMetafile (record, callback) {\n let record_buf = Buffer.from(record, this.encoding)\n // obtain total file size\n fs.stat(this.metapath, (err, stats) => {\n let filesize = 0\n // if file does not exist, filesize remains 0\n // otherwise, assign to actual file size\n if (!err && stats) {\n filesize = stats.size\n }\n let meta_buf = Buffer.allocUnsafe(META_LENGTH)\n meta_buf.writeUInt32LE(1, 0)\n meta_buf.writeUInt32LE(record_buf.length, 4)\n meta_buf.writeUInt32LE(0, 8)\n meta_buf.writeUInt32LE(0, 12)\n meta_buf.writeUInt32LE(filesize, 16)\n // console.log('meta buffer: ', meta_buf)\n let totallen = meta_buf.length + record_buf.length\n let w_buf = Buffer.concat([meta_buf, record_buf], totallen)\n let option = {encoding: this.encoding, flag: 'a'}\n fs.appendFile(this.metapath, w_buf, option, (err) => {\n callback(err)\n })\n })\n }",
"function addFileElement(request, file_json){\n var element = fileElementArray(file_json);\n addElement(element,dataTable_files);\n}",
"addChange(data) {\n this._changeFileData.changes.push(data);\n }",
"addMetadata(type, data, from) {\n if (data == null) {\n return;\n }\n const trace = createStackTrace(from || this.addMetadata);\n this._metadata.push({ type, data, trace });\n }",
"function updateData() {\n data.saveFile();\n // Make sure the data loaded in memory will not cause errors\n data.loadFile();\n}",
"onFileAdded(config, collection, vpinfo) {\n if (vpinfo.docMetadata\n && vpinfo.docMetadata.products\n && Array.isArray(vpinfo.docMetadata.products)) {\n for (let product of vpinfo.docMetadata.products) {\n if (!(product.doc)) product.doc = {};\n product.doc.vpath = vpinfo.vpath;\n product.doc.renderPath = vpinfo.renderPath;\n this.affiliateProduct(config, product.code, product);\n }\n }\n }",
"__setData(data) {\n this.__file = {\n id: data[0],\n name: data[1],\n size: data[2],\n downloaded: data[3],\n priority: data[4],\n first_piece: data[5],\n num_pieces: data[6],\n streamable: data[7],\n encoded_rate: data[8],\n duration: data[9],\n width: data[10],\n height: data[11],\n stream_eta: data[12],\n streamability: data[13]\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
moveDown(board: Board, emptyIdx: int): void | function moveDown(board, emptyIdx){
for(let i = emptyIdx; i < board.HEIGHT - 1; i++){
let copy = [];
for(let j = 0; j < board.WIDTH; j++){
copy.push(board.board[i+1][j]);
}
board.board[i] = copy;
}
for(let i = 0; i < board.WIDTH; i++){
board.board[board.HEIGHT - 1][i] = {isEmpty: () => true, color: () => 'gray'};
}
board.highestPiece -= 1;
} | [
"moveDown() {\n let indexZero = this.board.indexOf(0);\n if (indexZero < this.board.length - this.N) {\n this.__makeMove__(indexZero, indexZero + this.N);\n }\n }",
"moveUp() {\n let indexZero = this.board.indexOf(0);\n if (indexZero > this.N - 1) {\n this.__makeMove__(indexZero, indexZero - this.N);\n }\n }",
"function moveDown(tile) {\n var tileIndex = tileArray.indexOf(tile);\n var emptyTileIndex = tileIndex + numColumns;\n var emptyTile = tileArray[emptyTileIndex];\n\n x_coordinate_tile = elementCoordinatesArray[tileIndex][0];\n y_coordinate_tile = elementCoordinatesArray[tileIndex][1];\n\n x_coordinate_emptyTile = elementCoordinatesArray[emptyTileIndex][0];\n y_coordinate_emptyTile = elementCoordinatesArray[emptyTileIndex][1];\n\n // Change tile coordinates to emptyTile coordinates\n tileArray[tileIndex].style.left = `${x_coordinate_emptyTile}` + \"px\";\n tileArray[tileIndex].style.top = `${y_coordinate_emptyTile}` + \"px\";\n\n // Change emptyTile coordinates to tile coordinates\n tileArray[emptyTileIndex].style.left = `${x_coordinate_tile}` + \"px\";\n tileArray[emptyTileIndex].style.top = `${y_coordinate_tile}` + \"px\";\n\n // Animate the shift\n tileArray[tileIndex].style.transition = \"top 1.0s ease-in-out\";\n\n // Swap tile and emptyTile places within the tileArray\n var temp = emptyTile;\n tileArray[emptyTileIndex] = tile;\n tileArray[tileIndex] = temp;\n}",
"function moveDown() {\n unDraw();\n currentPosition += gridWidth;\n draw(currentBlock, gameMatrix, currentPosition, random);\n stopMoveDown();\n}",
"moveDown() {\n const {board} = this.state;\n\n let movementHappened = false;\n\n let updatedBoard = this.getEmptyBoard();\n\n for(let j=0 ; j<BOARD_SIZE ; j++) {\n let slidedColumn = [];\n\n let flag = false;\n for(let i=BOARD_SIZE-1 ; i>=0 ; i--) {\n if(board[i][j] != 0) {\n slidedColumn.push(board[i][j]);\n if(flag) {\n movementHappened = true;\n }\n }\n else {\n flag = true;\n }\n }\n\n let shrinkedColumn = this.shrinkArray(slidedColumn);\n\n if(shrinkedColumn.length != slidedColumn.length) {\n movementHappened = true;\n }\n\n for(let i=BOARD_SIZE-1 ; i>=0 ; i--) {\n if(BOARD_SIZE-i-1 < shrinkedColumn.length) {\n updatedBoard[i][j] = shrinkedColumn[BOARD_SIZE-i-1];\n }\n else {\n updatedBoard[i][j] = 0;\n }\n }\n }\n\n if(movementHappened) {\n let emptyCellNumber = [];\n for(let j=0 ; j<BOARD_SIZE ; j++) {\n if(updatedBoard[0][j] == 0) {\n emptyCellNumber.push(j);\n }\n }\n\n if(emptyCellNumber.length != 0) {\n let index = Math.floor(Math.random()*emptyCellNumber.length);\n let positionToFill = emptyCellNumber[index];\n updatedBoard[0][positionToFill] = this.props.generateRandomCellValue();\n }\n }\n\n this.setState({board: updatedBoard});\n }",
"function moveDown() {\r\n\t\tfor( var column = tableSize; column >= 1; column-- ) {\r\n\t\t\tfor( var row = tableSize; row >= 1; row-- ) {\r\n\t\t\t\tmoveTile( row, column, 1, 0 );\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function movePieceDown() {\n // console.log(\"Moving down\");\n undraw();\n currentPosition += height;\n draw();\n freeze();\n }",
"movePieceDown(){\n if(this.status == 'stopped'){\n if(this.moveInterval) clearInterval(this.moveInterval);\n if(!this._finishCalled) this.finish();\n return; \n }\n this.mobile.down();\n if(this.board.spaceConflict(this.mobile)){\n this.mobile.undo();\n this.getNextPiece();\n }else if(this.mobile.y+1-this.mobile.height== 0){ // the mobile piece has reached the bottom of the floor.\n this.getNextPiece();\n }else{\n this.emit('update UI');\n }\n }",
"function moveDown() {\n var grid = null;\n for(grid of GameData.activePiece.getOrientation()) {\n GameData.mainPlayField.setBlock(\n GameData.row + grid.getRow(),\n correctColumn(GameData.column + grid.getColumn()),\n 0\n );\n }\n\n GameData.row++;\n\n var grid = null;\n for(grid of GameData.activePiece.getOrientation()) {\n GameData.mainPlayField.setBlock(\n GameData.row + grid.getRow(),\n correctColumn(GameData.column + grid.getColumn()),\n GameData.activePiece.getType()\n );\n }\n}",
"move_down()\n {\n const _x = Base.bsnake.x + 1;\n const _y = Base.bsnake.y;\n this.base_move(_x, _y);\n }",
"function moveTilesDown() {\n for (var column = 3; column >= 0; column--) {\n for (var row = 2; row >= 0; row--) {\n if (checkBelow(row, column) && tileArray[row][column] != null) {\n moveTileDown(row, column);\n }\n }\n }\n }",
"function moveCellDownWithIndex(state, index) {\n let cell;\n let nextCell;\n let newCellOrder;\n let cellOrder = state.get('cellOrder');\n\n // cannot move lower than last\n if (index === (cellOrder.size - 1)) {\n return state;\n }\n\n cell = cellOrder.get(index);\n nextCell = cellOrder.get(index + 1);\n\n newCellOrder = cellOrder.set(index, nextCell).set(index + 1, cell);\n return state.set('cellOrder', newCellOrder);\n}",
"function move(grid, empty, x, y) {\n if (adjacent(empty, x, y)) {\n grid[empty.y][empty.x] = grid[y][x];\n grid[y][x] = 0;\n return {\n x: x,\n y: y\n };\n }\n return empty;\n }",
"function moveShipDown() {\n const ship = getShipLocation();\n const down = getElementAtSameIndex(ship, ship.parentElement.nextElementSibling);\n moveShip(ship, down);\n}",
"moveDown() {\n this.currentFloor -= 1;\n }",
"function dropToBottom(x_pos, y_pos) {\n // Start at the bottom of the column, and step up, checking to make sure\n // each position has been filled. If one hasn't, return the empty position.\n for (var y = 5; y > y_pos; y--) {\n if (board[y][x_pos] === 0) {\n return y;\n }\n }\n return y_pos;\n}",
"function moveTilesDown() {\n var moved = false\n var captured = false\n for (var column = 0; column < grid_size; column++) {\n var row = grid_size\n while (row--) {\n if (grid_size - row > 1) {\n var ind = index(row,column)\n if (tiles[ind] != null) {\n var preind = index(row + 1,column)\n\n if (tiles[preind] == null) {\n\n moved = true\n moveTile(ind,preind)\n row = grid_size\n\n } else if (canMergeTiles(ind,preind)) {\n\n moved = true\n prepareTileMerging(ind,preind)\n container.merged(tiles[ind].value);\n moveTile(ind,preind)\n row = grid_size\n\n }\n\n if (moved && !captured) {\n tiles[preind].emitMoved = true\n captured = true\n }\n }\n } // if grid_size - row > 1\n } // while row--\n } // for column < grid_size\n updateTiles(moved)\n}",
"moveUp() {\n const {board} = this.state;\n\n let movementHappened = false;\n\n let updatedBoard = this.getEmptyBoard();\n\n for(let j=0 ; j<BOARD_SIZE ; j++) {\n let slidedColumn = [];\n\n let flag = false;\n for(let i=0 ; i<BOARD_SIZE ; i++) {\n if(board[i][j] != 0) {\n slidedColumn.push(board[i][j]);\n if(flag) {\n movementHappened = true;\n }\n }\n else {\n flag = true;\n }\n }\n\n let shrinkedColumn = this.shrinkArray(slidedColumn);\n\n if(shrinkedColumn.length != slidedColumn.length) {\n movementHappened = true;\n }\n\n for(let i=0 ; i<BOARD_SIZE ; i++) {\n if(i < shrinkedColumn.length) {\n updatedBoard[i][j] = shrinkedColumn[i];\n }\n else {\n updatedBoard[i][j] = 0;\n }\n }\n }\n\n if(movementHappened) {\n let emptyCellNumber = [];\n for(let j=0 ; j<BOARD_SIZE ; j++) {\n if(updatedBoard[BOARD_SIZE-1][j] == 0) {\n emptyCellNumber.push(j);\n }\n }\n\n if(emptyCellNumber.length != 0) {\n let index = Math.floor(Math.random()*emptyCellNumber.length);\n let positionToFill = emptyCellNumber[index];\n updatedBoard[BOARD_SIZE-1][positionToFill] = this.props.generateRandomCellValue();\n }\n }\n\n this.setState({board: updatedBoard});\n }",
"function emptyToLeft(emptyPos, tile) {\n\t//records which order #'d tile is being moved\n _solution.push(tile.order);\n //resets that tile's position on page\n tile.style.left = _empty_tile.col*tile.width + \"px\";\n //update's its current column\n tile.col +=1;\n //current order of tiles must be updated\n _puzzle_board[emptyPos-1] = 0;\n _puzzle_board[emptyPos] = tile;\n //update's empty tile's position\n _empty_tile.col-=1;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the default domain. | setDefaultDomain() {
let htmlFileName = window.location.href.split('/').filter((pth) => pth.indexOf('.html') > -1)[0] || '____'
config.domain = window.location.href.replace(htmlFileName, '');
if (config.domain.slice(-1) === '/') {
config.domain = config.domain.slice(0, -1)
}
} | [
"function setDomain(domain) {\n\t defaultDomain = domain;\n\t hasSetDomain = true;\n\t}",
"function getDomain() {\n\t return defaultDomain;\n\t}",
"function setDomain() {\n let parseDomain = function(url) {\n if (!url || typeof url !== 'string' || url.length === 0) return;\n\n var match = url.match(/^(?:https?:\\/\\/)?(?:www\\.)?(.*?(?=(\\?|\\#|\\/|$)))/i);\n\n return match && match[1];\n };\n\n let domain = parseDomain(getRefererInfo().canonicalUrl)\n\n if (domain) {\n mergeDeep(ortb2, { site: { domain: domain } });\n mergeDeep(ortb2, { site: { publisher: { domain: findRootDomain(domain) } } });\n };\n}",
"function DefaultDomainOnly(defaultDomainValue){\n ToggleSubmitToSlackButton();\n CleanSlackPosting();//To fill slack content box for issue tracker template\n AutoApiChecker(defaultDomainValue + '/__mwp2_check__');\n AutoApiChecker(defaultDomainValue + '/__mwp2_httpd_check__');\n AutoApiChecker(defaultDomainValue + '/__mwp2_php_check__');\n}",
"setDomain( domain ) {\n this.domain = domain\n }",
"function setDocumentDomain() {\n console.log('setDocumentDomain()');\n if ( window.location.host.indexOf( \"atfingertips.com\" ) > 0 ) document.domain = \"atfingertips.com\";\n if ( isProduction ) { document.domain = \"macys.com\"; }\n }",
"function setDomain() {\n let parseDomain = function(url) {\n if (!url || typeof url !== 'string' || url.length === 0) return;\n\n var match = url.match(/^(?:https?:\\/\\/)?(?:www\\.)?(.*?(?=(\\?|\\#|\\/|$)))/i);\n\n return match && match[1];\n };\n\n let domain = parseDomain(getRefererInfo().canonicalUrl)\n\n if (domain) utils.mergeDeep(ortb2, { site: { domain: domain } });\n}",
"function setDomain(newValue, oldValue) {\n $scope.browserLocation.domain = $scope.genoverseUtils.getGenomeObject(newValue, $scope.genomes).subdomain;\n }",
"setDomain(d) {\n\t\tthis.#dom = d;\n\t\tthis.clear();\n\t}",
"function update_domain(value) {\n console.log(\"Setting domain to \" + value);\n domain_str = value;\n start();\n}",
"function _setMyTimeDomain(domain) {\n\n config.mytimeDomain = domain;\n }",
"function setDomains() {\n x0.domain(currentData.map(getId));\n x1.domain(keys).rangeRound([0, x0.bandwidth()]);\n y.domain([0, getMaxValueOfYear(currentData)]);\n}",
"_overrideDomain (axisName, domains) {\n const configDomain = this.config.getDomain(axisName)\n if (!configDomain) return\n if (!_.isNil(configDomain[0])) domains[axisName][0] = configDomain[0]\n if (!_.isNil(configDomain[1])) domains[axisName][1] = configDomain[1]\n }",
"function setActiveDomain(domain) {\n vm.activeDomain = domain;\n }",
"function DefaulyAndPrimaryDomains(defaultDomainValue, primaryDomainValue){\n ToggleSubmitToSlackButton();\n CleanSlackPosting();//To fill slack content box for issue tracker template\n AutoApiChecker(defaultDomainValue + '/__mwp2_check__');\n AutoApiChecker(defaultDomainValue + '/__mwp2_httpd_check__');\n AutoApiChecker(defaultDomainValue + '/__mwp2_php_check__');\n AutoApiChecker(primaryDomainValue + '/__mwp2_check__');\n AutoApiChecker(primaryDomainValue + '/__mwp2_httpd_check__');\n AutoApiChecker(primaryDomainValue + '/__mwp2_php_check__');\n}",
"function setDomain(name) {\n if (name.length > 25) {\n name = name.substring(0, 17) + \"...\" +\n name.substring(name.length - 5);\n }\n $(\"#div_status_whitelisted span\").text(\n translate(\"adblock_is_disabled_on_domain\", [name]));\n $(\"#div_whitelist\").text(\n translate(\"dont_run_on_domain\", [name]));\n }",
"function _defineCookieDomain()\n{\n\tvar domainPattern = /(([^.\\/]+\\.[^.\\/]{2,3}\\.[^.\\/]{2})|(([^.\\/]+\\.)[^.\\/]{2,4}))(\\/.*)?$/;\n\n\tif(domainPattern.test(oCONFIG.SUBDOMAIN_BASED.toString()))\n\t{\n\t\toCONFIG.COOKIE_DOMAIN = oCONFIG.SUBDOMAIN_BASED.toLowerCase().replace('www.','');\n\t\toCONFIG.SUBDOMAIN_BASED = true;\n\t}\n\telse\n\t{\n\t\tif (oCONFIG.SUBDOMAIN_BASED.toString() == 'false')\n\t\t{\n\t\t\toCONFIG.COOKIE_DOMAIN = document.location.hostname.match(/(([^.\\/]+\\.[^.\\/]{2,3}\\.[^.\\/]{2})|(([^.\\/]+\\.)[^.\\/]{2,4}))(\\/.*)?$/)[1];\n\t\t\toCONFIG.SUBDOMAIN_BASED = true;\n\t\t}\n\t\telse if(oCONFIG.SUBDOMAIN_BASED.toString() == 'auto' || oCONFIG.SUBDOMAIN_BASED == 'true')\n\t\t{\n\t\t\toCONFIG.COOKIE_DOMAIN = location.hostname.toLowerCase().replace('www.','');\n\t\t\toCONFIG.SUBDOMAIN_BASED = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\toCONFIG.COOKIE_DOMAIN = location.hostname.toLowerCase().replace('www.','');\n\t\t\toCONFIG.SUBDOMAIN_BASED = false;\n\t\t}\n\t}\n}",
"setActiveDomain(domain) {\n this.activeDomain = domain;\n }",
"function init(){\n initMaster();\n createDomain(\"gmail.com\");\n createDomain(\"hotmail.com\");\n updateLabel();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
= [ 20, 2, 4.428571428571429 ] Given an array, if a value in that array is a negative, replace with the word "Negative": | function replaceNegative(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] < 0){
arr[i] = "Negative"
}
}
console.log(arr);
} | [
"function replaceNegatives(array){\n for (var i = 0; i < array.length; i++) {\n if (array[i] < 0){\n array[i] = 0;\n }\n }\n return array;\n}",
"function SwapStringForArrayNegativeVals(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] = 'dojo';\n }\n }\n return arr;\n}",
"function swapStringForArrayNegativeVals(arr) {\n arr.forEach((val, index, array) => {\n if (val < 0) {\n array[index] = 'dojo';\n }\n });\n return arr;\n}",
"function outlookNegative(array){\n for(let x = 0; x < array.length; x++){\n if(array[x] > 0){\n array[x] = array[x] * -1\n }\n }\n return array \n}",
"function replaceNegativeNumbers(arr){\n for (var i=0; i<arr.length; i++){\n if (arr[i]<0){\n arr[i]=0\n }\n }\n return arr\n}",
"function replaceNegatives(arr){\n\n for ( var i = 0; i<arr.length; i++){\n if( arr[i] < 0){\n arr[i] = 'Dojo';\n }\n\n }\n return arr;\n }",
"function SwapStringForArrayNegativeVals(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] = \"Dojo\"\n }\n }\n return arr\n}",
"function negatives(array) {\n for (let i = 0; i < array.length; i++) {\n if(array[i] < 0) { \n array[i] = 0;\n }\n }\n return array;\n}",
"function negative(array){\n for(var i=0; i<array.length; i++){\n if(array[i]<0){\n array[i] = 0;\n }\n }\n return array;\n}",
"function swapStringForArrayNegativeVals(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = \"Dojo\";\n }\n }\n return arr;\n}",
"function swapStringForArrayNegativeVals(arr){\n for(let i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = \"Dojo\";\n }\n }\n return arr\n}",
"function swapStringForArrayNegativeVals(arr)\n{ \n for (var idx = 0; idx < arr.length; idx++) \n {\n if (arr[idx] < 0 ) \n { \n arr[idx] = \"Dojo\";\n } \n } \n return arr ;\n}",
"function swapStringForArrayNegativeVals(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = \"Dojo\";\n }\n }\n console.log(arr);\n}",
"function replaceNums(array) {\n for (var i = 0; i < array.length; i++) {\n if (array[i] < 0){\n array[i] = 'Fun';\n }\n }\n return array;\n}",
"function outlookNegative(){\n\n var arr = [1,-3,5,8,-5,6,-10]\n var newarr = [];\n for(var i =0; i<arr.length;i++){\n if(arr[i]<0){\n newarr.push(arr[i]);\n }\n if(arr[i]>0){\n newarr.push(arr[i]*=-1);\n }\n } return newarr;\n }",
"function negatives(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 0;\n }\n }\n return arr;\n}",
"function makePositive(array) {\n\n for ( let i = 0; i < array.length; i++ ) {\n if ( array[i] < 0 ) {\n array[i] = array[i] * -1;\n }\n }\n return array;\n}",
"function zero_out_negatives(array){\n\tfor(var i =0; i <array.length; i++){\n\t\tif(array[i] < 0){\n\t\t\tarray[i] = 0;\n\t\t}\n\t}\n\treturn array;\n}",
"function makePositive(array) {\n\tfor (let i = 0; i < array.length; i++) {\n\t\tif (array[i] < 0) {\n\t\t\tarray[i] = Math.abs(array[i]);\n\t\t}\n\t}\n\treturn array;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for overriding Here should be all of footer render | renderFooter() {
return null;
} | [
"renderFooter() {\n return null;\n }",
"get footerRender() {\n return this.$slots.footer || this.$props.footer ? (\n <footer class={`${this.prefixCls}-footer`}>{this.$slots.footer || this.$props.footer}</footer>\n ) : null;\n }",
"renderFooterWrapper() {\n return (\n <footer>\n {this.renderFooter()}\n </footer>\n )\n }",
"render() {\n if (this.props.viewsite) {\n return (FooterJSX.call(this));\n } else {\n return null;\n }\n }",
"render() {\r\n return(FooterJSX.call(this));\r\n }",
"function FOOTER$static_(){ToolbarSkin.FOOTER=( new ToolbarSkin(\"footer\"));}",
"function renderFooter() {\n\t\t\tfooter.setToolbarOptions(computeFooterOptions());\n\t\t\tfooter.render();\n\t\t\tif (footer.el) {\n\t\t\t\telement.append(footer.el);\n\t\t\t}\n\t\t}",
"function footer_func(){\n showfooter();\n hideicon();\n }",
"renderFooter() { // public: Gets the HTML page for the footer and displays it in the footer div\n const DOMelement = document.getElementById(\"footerDiv\");\n return this.render(DOMelement, \"footer\");\n }",
"function EMBEDDED_FOOTER$static_(){ToolbarSkin.EMBEDDED_FOOTER=( new ToolbarSkin(\"embedded-footer\"));}",
"splitFooter() {\n return (\n <div className=\"phantom\">\n <footer className=\"devourFooter mdl-mini-footer mdl-cell--12-col mdl-cell--8-col-phone mdl-cell--8-col-tablet\">\n <div className=\"footLeft mdl-grid mdl-mini-footer__left-section\">\n <button id=\"upcomingButton\" className=\"mdl-cell--stretch mdl-button mdl-js-button mdl-button--accent\">\n <span>{this.state.left}</span>\n </button>\n </div>\n <div className=\"centerFoot mdl-grid mdl-mini-footer__left-section\">\n <Link to='/home'><i className=\"homeIcon material-icons\">restaurant</i></Link>\n </div>\n <div className=\"footRight mdl-grid mdl-mini-footer__right-section\">\n <button id=\"pastButton\" className=\"mdl-cell--stretch mdl-button mdl-js-button mdl-button--accent\">\n <span>{this.state.right}</span>\n </button>\n </div>\n </footer>\n </div>\n );\n }",
"buildFooter() {\n this.footer = document.createElement('footer');\n this.footer.appendChild(this.buildItemCounter());\n this.footer.appendChild(this.buildActivityNotifier());\n }",
"function footerChangeRegion() {\n app.getView().render('components/footer/footerchangeregion');\n}",
"blankFooter() {\n return(\n <div className=\"phantom\">\n <footer className=\"devourFooter mdl-mini-footer mdl-cell--12-col mdl-cell--8-col-phone mdl-cell--8-col-tablet\">\n <div className=\"footLeft mdl-grid mdl-mini-footer__left-section\">\n </div>\n <div className=\"centerFoot mdl-grid mdl-mini-footer__left-section\">\n </div>\n <div className=\"footRight mdl-grid mdl-mini-footer__right-section\">\n </div>\n </footer>\n </div>\n );\n }",
"displayFooter() {\n const { footer } = this.tool.options;\n if (footer) {\n this.out(footer, 1);\n }\n }",
"render() {\n switch (this.state.title) {\n case \"devour\":\n return this.blankFooter();\n case \"taste profile\":\n return this.blankFooter();\n case \"recipes\":\n return (<span></span>);\n case \"social\":\n return this.splitFooter();\n case \"recipe book\":\n return this.blankFooter();\n case \"budget\":\n return this.splitFooter()\n case \"plan\":\n return this.splitFooter();\n default:\n break;\n }\n }",
"updateFooter(){\n\t\tif(this.recall(this.dateList)){\n\t\t\tthis.footer.backgroundColor = \"#0AFF0B\";\n\t\t\tSS.style(this.footer, {\"backgroundColor\" : \"#0AFF0B\"});\n\t\t}\n\t\telse {\n\t\t\tSS.style(this.footer, {\"backgroundColor\" : \"#F8F8F8\"});\n\t\t}\n\t}",
"function callFooterFunctions() {\n columnSum();\n totalTotalSum();\n makeTotalsRender();\n}",
"chargerFooter(){\n $(\"#page\"+this.instrument.ref).append('<div data-role=\"footer\" data-position=\"fixed\" data-tap-toggle=\"false\" data-fullscreen=\"false\" data-theme=\"b\">\\\n <div data-role=\"navbar\" data-grid=\"\" data-iconpos=\"left\">\\\n <ul id=\"menu\">\\\n <li><a href=\"#pageEtat\">Etat</a></li>\\\n <li><a href=\"#pageInstruments\"> Instruments</a></li>\\\n <li><a href=\"#pageCommande\">Commande</a></li>\\\n <li><a href=\"#pageConfiguration\"> Configuration</a></li>\\\n </ul>\\\n </div>\\\n </div>');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An element consisting of an image on the left and an article with a scrollbar on the right articleright options: 0: image URL 1: article text | function buildArticleRight(options) {
html += `<section id="article-right">
<img src="${options[0]}" />
<p>${options[2]}</p>
</section>
`} | [
"function buildArticleLeft(options) {\n html += `<section id=\"article-left\">\n <p>${options[2]}</p>\n <img src=\"${options[0]}\" />\n \n </section>\n `}",
"function scrollThumbnailRight() {\n\t\t// Set flag to using scrolls\n\t\tthumbnailScrollUse = true;\n\n\t\tif (thumbnailScrollIndex >= elementsCount - floor(thumbnailVisibleCount / 2)) {\n\t\t\t// On end scroll\n\t\t\t//thumbnailScrollIndex = elementsCount - floor(thumbnailVisibleCount / 2);\n\t\t\t//thumbnailScrollIndex = floor(thumbnailVisibleCount / 2) - 1;\n\t\t\tthumbnailScrollIndex = elementsCount - 1;\n\t\t} else if (thumbnailScrollIndex < floor(thumbnailVisibleCount / 2)) {\n\t\t\t// On start scroll\n\t\t\tthumbnailScrollIndex = floor(thumbnailVisibleCount / 2) + 1 ;\n\t\t} else {\n\t\t\t// On scroll\n\t\t\t// Scroll to 1/2 display left\n\t\t\tthumbnailScrollIndex += floor(thumbnailVisibleCount / 2);\n\t\t\t//thumbnailScrollIndex++;\n\t\t}\n\t\t// Check the max value\n\t\tif (thumbnailScrollIndex >= elementsCount) {\n\t\t\tthumbnailScrollIndex = elementsCount - 1;\n\t\t}\n\t\t//playElement.innerHTML = thumbnailScrollIndex;\n\t\tscrollThumbnailToView();\n\t}",
"function addLeftGraphicalScrollbar() {\n\t$('body').append('<img id=\"uparrow\" src=\"images/arrow.png\"></img><div id=\"vscroll\" class=\"scroll_y\"><div class=\"nub_y\"></div><div class=\"ghost_y\"></div></div><img id=\"downarrow\" src=\"images/arrowdn.png\"></img>');\n}",
"function eltdSideAreaScroll(){\n\n\n }",
"function setScrollingFor(el) {\n\t\"use strict\";\n\tel.classList.add('JS','p-r');\n\t// mark list gallery in touch devices (to prevent hover)\n\t// NB - this code has to appear here rather than in scrolling.js,\n\t//\t\totherwise the summaries are hidden until the arrow is clicked for the first time\n\tif (eventSupport('touchstart') && (matches(el, 'ol') || matches(el, 'ul'))) {\n\t\tel.setAttribute('data-touch', 'true');\n\t\t// for each image, on click - hide the currently displayed summary and show the sibling summary\n\t\tforEach(el.querySelectorAll('img'), function(img) {\n\t\t\timg.addEventListener('click', function(e) {\n\t\t\t\tel.querySelector('[data-hidden]').style.display = 'none';\n\t\t\t\tel.querySelector('[data-hidden]').removeAttribute('data-hidden');\n\t\t\t\tthis.nextElementSibling.style.display = 'flex';\n\t\t\t\tthis.nextElementSibling.setAttribute('data-hidden', 'true');\n\t\t\t});\n\t\t});\n\t}\n\t// insert a right arrow which on click, calls the scrolling function,\n\t// but only proceed if combined width of child elements, less margin-right of first element, is less than available width\n\tvar childrenWidth = (getOuterWidth(el.firstElementChild) * el.children.length) - parseInt(getComputedStyle(el.firstElementChild).marginRight);\n\tif (childrenWidth > getInnerWidth(el)) {\n\t\tvar launcher = document.createElement('div');\n\t\tlauncher.className = 'ui-arrow p-a';\n\t\tel.appendChild(launcher);\n\t\tlauncher.onclick = function (e) {\n\t\t\tcallFunction('setScrollWidget','scrolling',el);\n\t\t};\n\t}\n}",
"function getScroller(content,imgArr,title)\n{\n\tvar imgStr = \"\",\n\t\theader = \"\",\n\t\twidth = imgArr.length *300 +'px';\n\n\tfor(var i = -1, l = imgArr.length;++i <l;){\n\t\timgStr += '<img src=\"'+imgArr[i]+'\" class=\"item\"/>';\n\t}\n\tif(title == null || title == ''){\n\t\theader = \"\";\n\t}\n\telse if(title != null){\n\t\theader = '<div class=\"articleHeader\">'+title+'</div>';\n\t}\n\n\tvar htmlContent = [];\n\tvar imgGallery = '<div id=\"wrapper\" style=\"width:'+width+'\">' +\n\t\t\t\t\t\t'<div id=\"scrollContent1\">' +\n\t\t\t\t\t\t\timgStr +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t'</div>';\n\thtmlContent.push(imgGallery);\n\n\tvar content = '<div style=\"padding:1px\"></div><hr/>'+header + '<div class=\"article\">' + content + '</div>'+ '<div id=\"footer\" class=\"w_box w_footer w_bg_dark\">';\n\thtmlContent.push(content);\n\n\t/*var htmlContent = \n\t\t'<div id=\"header\" class=\"w_box w_header w_bg_dark\"></div>' +\n\t\t\t'<div id=\"wrapper\">' +\n\t\t\t\t\t\t'<div id=\"scrollContent1\" style=\"width:'+width+'\">' +\n\t\t\t\t\t\t\timgStr +\n\t\t\t\t\t\t'</div>' +\n\t\t\t'</div>' +\n\t\t '<hr />' +\n\t\t\theader +\n\t\t\t\t'<div class=\"article\">' +\n\t\t\t\t\tcontent +\n\t\t\t\t'</div>'+\n\t\t'<div id=\"footer\" class=\"w_box w_footer w_bg_dark\">' +\n\t\t'</div>';*/\n\t\treturn htmlContent;\n}",
"get newsHub_Article_HeroImage() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[2]/android.view.ViewGroup\");}",
"get newsHub_CarouselContent() {return browser.element(\"//android.widget.HorizontalScrollView/android.view.ViewGroup/android.widget.Button/android.view.ViewGroup/android.view.ViewGroup/android.widget.ImageView\");}",
"function scrollLeftRight() {\n\n // checking if thumbs are in the view of screen or not\n if (thumbRef.current.getBoundingClientRect().left < document.getElementById(listId).getBoundingClientRect().right\n ) {\n if (thumbRef.current.getBoundingClientRect().right < document.getElementById(listId).getBoundingClientRect().left)\n setAddRevealThumb(false)\n else\n setAddRevealThumb(true)\n } else {\n setAddRevealThumb(false)\n }\n }",
"function galleryRight (){\n\n\t// Sets limit.\n\tvar limit = ((document.getElementById('container').scrollWidth - document.getElementById('container').clientWidth) - 190);\n\t\n\t// Checks if limit is greater or equal to scroll position.\n\tif (limit <= document.getElementById('container').scrollLeft){\n\t\t\n\t\t// Sets forward opacity.\n\t\tdocument.getElementById('forward').style.opacity = 0.5;\n\t\t\n\t\t// Sets back & forward cursor.\n\t\tdocument.getElementById(\"forward\").style.cursor = \"default\";\n\t\tdocument.getElementById(\"back\").style.cursor = \"pointer\";\n\t\n\t}else{\n\t\t\n\t\t// Sets back opacity and moves thumbnails to the right.\n\t\tdocument.getElementById('back').style.opacity = 1;\n\t\tdocument.getElementById('container').scrollLeft += 190;\n\t\n\t}\n\t\n}",
"function ScrollViewer(name,isImageBased){var _this=_super.call(this,name)||this;_this._barSize=20;_this._pointerIsOver=false;_this._wheelPrecision=0.05;_this._thumbLength=0.5;_this._thumbHeight=1;_this._barImageHeight=1;_this._horizontalBarImageHeight=1;_this._verticalBarImageHeight=1;_this._oldWindowContentsWidth=0;_this._oldWindowContentsHeight=0;_this._forceHorizontalBar=false;_this._forceVerticalBar=false;_this._useImageBar=isImageBased?isImageBased:false;_this.onDirtyObservable.add(function(){_this._horizontalBarSpace.color=_this.color;_this._verticalBarSpace.color=_this.color;_this._dragSpace.color=_this.color;});_this.onPointerEnterObservable.add(function(){_this._pointerIsOver=true;});_this.onPointerOutObservable.add(function(){_this._pointerIsOver=false;});_this._grid=new _grid__WEBPACK_IMPORTED_MODULE_2__[\"Grid\"]();if(_this._useImageBar){_this._horizontalBar=new _sliders_imageScrollBar__WEBPACK_IMPORTED_MODULE_6__[\"ImageScrollBar\"]();_this._verticalBar=new _sliders_imageScrollBar__WEBPACK_IMPORTED_MODULE_6__[\"ImageScrollBar\"]();}else{_this._horizontalBar=new _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_5__[\"ScrollBar\"]();_this._verticalBar=new _sliders_scrollBar__WEBPACK_IMPORTED_MODULE_5__[\"ScrollBar\"]();}_this._window=new _scrollViewerWindow__WEBPACK_IMPORTED_MODULE_4__[\"_ScrollViewerWindow\"](\"scrollViewer_window\");_this._window.horizontalAlignment=_control__WEBPACK_IMPORTED_MODULE_3__[\"Control\"].HORIZONTAL_ALIGNMENT_LEFT;_this._window.verticalAlignment=_control__WEBPACK_IMPORTED_MODULE_3__[\"Control\"].VERTICAL_ALIGNMENT_TOP;_this._grid.addColumnDefinition(1);_this._grid.addColumnDefinition(0,true);_this._grid.addRowDefinition(1);_this._grid.addRowDefinition(0,true);_super.prototype.addControl.call(_this,_this._grid);_this._grid.addControl(_this._window,0,0);_this._verticalBarSpace=new _rectangle__WEBPACK_IMPORTED_MODULE_1__[\"Rectangle\"]();_this._verticalBarSpace.horizontalAlignment=_control__WEBPACK_IMPORTED_MODULE_3__[\"Control\"].HORIZONTAL_ALIGNMENT_LEFT;_this._verticalBarSpace.verticalAlignment=_control__WEBPACK_IMPORTED_MODULE_3__[\"Control\"].VERTICAL_ALIGNMENT_TOP;_this._verticalBarSpace.thickness=1;_this._grid.addControl(_this._verticalBarSpace,0,1);_this._addBar(_this._verticalBar,_this._verticalBarSpace,true,Math.PI);_this._horizontalBarSpace=new _rectangle__WEBPACK_IMPORTED_MODULE_1__[\"Rectangle\"]();_this._horizontalBarSpace.horizontalAlignment=_control__WEBPACK_IMPORTED_MODULE_3__[\"Control\"].HORIZONTAL_ALIGNMENT_LEFT;_this._horizontalBarSpace.verticalAlignment=_control__WEBPACK_IMPORTED_MODULE_3__[\"Control\"].VERTICAL_ALIGNMENT_TOP;_this._horizontalBarSpace.thickness=1;_this._grid.addControl(_this._horizontalBarSpace,1,0);_this._addBar(_this._horizontalBar,_this._horizontalBarSpace,false,0);_this._dragSpace=new _rectangle__WEBPACK_IMPORTED_MODULE_1__[\"Rectangle\"]();_this._dragSpace.thickness=1;_this._grid.addControl(_this._dragSpace,1,1);// Colors\nif(!_this._useImageBar){_this.barColor=\"grey\";_this.barBackground=\"transparent\";}return _this;}",
"function showArticleContent(canvas, article) {\n var imageInfo = getImageConfig(article);\n var imageAnnotations = getImageAnnotations(article);\n var imageHighlights = getImageHighlights(article, function(idx) {\n canvas.focusOnZone(idx);\n });\n canvas.setImage({\n image : imageInfo,\n annotations : imageAnnotations,\n highlights : imageHighlights\n });\n }",
"function ImageViewer(opts) {\n 'use strict';\n var i, divSidebar, divOptions, divDoclist, imgDoclist, divIndex, imgIndex,\n divThumbnails, divThumbpanel, divDocPanel, divPagePanel, divPages, divStatusBar,\n divCtrlPage, divPrev, imgPrev, divCurrPage, txtCurrPage, divNext, imgNext,\n divCtrlZoom, divZoomOut, imgZoomOut, divZoom, txtZoom, divZoomIn, imgZoomIn,\n that = this,\n zoomScale = 100,\n currPage = 1,\n lastPage = opts.imgslist.length,\n imgTemp, thumbTemp, factor,\n xmlns = 'http://www.w3.org/2000/svg',\n page = [],\n svg = [],\n image = [],\n thumbnail = [],\n imgThumbnail = [],\n divLabel = [],\n spanLabel = [],\n maxWidth = 0,\n settings = $.extend({\n sidebar: false,\n thumbnails: false,\n bookmarks: false,\n statusbar: false\n }, opts);\n\n /** Create viewer's elements **/\n if (settings.sidebar) {\n divOptions = document.createElement('div');\n divOptions.setAttribute('class', 'options');\n\n if (settings.thumbnails) {\n imgDoclist = document.createElement('img');\n imgDoclist.src = 'icons/thumbs.svg';\n\n divDoclist = document.createElement('div');\n divDoclist.setAttribute('class', 'option active');\n divDoclist.appendChild(imgDoclist);\n\n divOptions.appendChild(divDoclist);\n\n divThumbpanel = document.createElement('div');\n divThumbpanel.setAttribute('class', 'thumbpanel');\n\n divThumbnails = document.createElement('div');\n divThumbnails.setAttribute('class', 'thumbnails');\n divThumbnails.appendChild(divThumbpanel);\n }\n\n if (settings.bookmarks) {\n imgIndex = document.createElement('img');\n imgIndex.src = 'icons/toc.svg';\n\n divIndex = document.createElement('div');\n divIndex.setAttribute('class', 'option');\n divIndex.appendChild(imgIndex);\n\n divOptions.appendChild(divIndex);\n }\n\n divSidebar = document.createElement('div');\n divSidebar.setAttribute('class', 'sidebar');\n divSidebar.appendChild(divOptions);\n\n if (settings.thumbnails) {\n divSidebar.appendChild(divThumbnails);\n }\n }\n\n divPages = document.createElement('div');\n divPages.setAttribute('class', 'pages');\n\n divPagePanel = document.createElement('div');\n divPagePanel.setAttribute('class', 'pagePanel');\n divPagePanel.appendChild(divPages);\n\n if (settings.statusbar) {\n imgPrev = document.createElement('img');\n imgPrev.src = 'icons/left.svg';\n\n divPrev = document.createElement('div');\n divPrev.setAttribute('class', 'btnPage prev');\n divPrev.appendChild(imgPrev);\n\n txtCurrPage = document.createElement('input');\n txtCurrPage.setAttribute('class', 'currPage');\n txtCurrPage.setAttribute('type', 'text');\n txtCurrPage.setAttribute('value', '1 / ' + settings.imgslist.length);\n\n divCurrPage = document.createElement('div');\n divCurrPage.setAttribute('class', 'btnPage');\n divCurrPage.appendChild(txtCurrPage);\n\n imgNext = document.createElement('img');\n imgNext.src = 'icons/right.svg';\n\n divNext = document.createElement('div');\n divNext.setAttribute('class', 'btnPage next');\n divNext.appendChild(imgNext);\n\n divCtrlPage = document.createElement('div');\n divCtrlPage.setAttribute('class', 'ctrlPage');\n divCtrlPage.appendChild(divPrev);\n divCtrlPage.appendChild(divCurrPage);\n divCtrlPage.appendChild(divNext);\n\n imgZoomOut = document.createElement('img');\n imgZoomOut.src = 'icons/zoomOut.svg';\n\n divZoomOut = document.createElement('div');\n divZoomOut.setAttribute('class', 'btnZoom zoomOut');\n divZoomOut.appendChild(imgZoomOut);\n\n txtZoom = document.createElement('span');\n txtZoom.setAttribute('class', 'zoom');\n //txtZoom.setAttribute('id', 'zoom');\n txtZoom.innerHTML = '100%';\n\n divZoom = document.createElement('div');\n divZoom.setAttribute('class', 'txtZoom');\n divZoom.appendChild(txtZoom);\n\n imgZoomIn = document.createElement('img');\n imgZoomIn.src = 'icons/zoomIn.svg';\n\n divZoomIn = document.createElement('div');\n divZoomIn.setAttribute('class', 'btnZoom zoomIn');\n divZoomIn.appendChild(imgZoomIn);\n\n divCtrlZoom = document.createElement('div');\n divCtrlZoom.setAttribute('class', 'ctrlZoom');\n divCtrlZoom.appendChild(divZoomOut);\n divCtrlZoom.appendChild(divZoom);\n divCtrlZoom.appendChild(divZoomIn);\n\n divStatusBar = document.createElement('div');\n divStatusBar = document.createElement('div');\n divStatusBar.setAttribute('class', 'statusBar');\n divStatusBar.appendChild(divCtrlPage);\n divStatusBar.appendChild(divCtrlZoom);\n }\n\n divDocPanel = document.createElement('div');\n divDocPanel.setAttribute('class', 'docPanel');\n divDocPanel.appendChild(divPagePanel);\n\n if (settings.statusbar) {\n divDocPanel.appendChild(divStatusBar);\n }\n\n this.mainPanel = document.createElement('div');\n this.mainPanel.setAttribute('class', 'viewerPanel');\n\n if (settings.sidebar) {\n this.mainPanel.appendChild(divSidebar);\n }\n\n this.mainPanel.appendChild(divDocPanel);\n\n /*** Draw viewer ***/\n if (settings.parent != null) {\n $(settings.parent).append(that.mainPanel);\n }\n\n /** Private functions **/\n function scrollPages(e) {\n var scrollMiddle = (e.target.scrollTop + e.target.clientHeight) * 2,\n numberPage = 0;\n\n $('.page', divPages).each(function () {\n if (scrollMiddle > this.offsetTop) {\n var idx = this.getAttribute('idx'),\n page = this,\n imgTemp;\n\n numberPage = parseInt(idx, 10);\n\n if ($(this).hasClass('preload')) {\n $(this).removeClass('preload');\n imgTemp = new Image();\n imgTemp.onload = function () {\n $('image', page).fadeOut(200, function () {\n this.setAttributeNS('http://www.w3.org/1999/xlink', 'href', settings.imgslist[idx].urlImg);\n $(this).fadeIn(200);\n });\n };\n imgTemp.src = settings.imgslist[idx].urlImg;\n }\n }\n });\n\n currPage = numberPage + 1;\n $(txtCurrPage).val(currPage + ' / ' + lastPage);\n }\n\n function scrollThumbnails(e) {\n var scrollBottom = (e.target.scrollTop + e.target.clientHeight) * 2;\n\n $('.thumbnail img.preload', divThumbpanel).each(function () {\n var idx = this.getAttribute('idx'),\n thumbImg = this,\n thumbTemp = new Image();\n\n if (scrollBottom > this.offsetTop) {\n $(this).removeClass('preload');\n\n thumbTemp.onload = function () {\n $(thumbImg).fadeOut(200, function () {\n this.src = thumbTemp.src;\n $(this).fadeIn(200);\n });\n };\n thumbTemp.src = settings.imgslist[idx].urlImg;\n }\n });\n }\n\n function clickOnThumbnail(e) {\n var idx = e.target.getAttribute('idx');\n\n $(divPagePanel).off('scroll', scrollPages);\n\n $(divPagePanel).animate({\n scrollTop: $('#page_' + idx, divPages)[0].offsetTop\n }, 400, function () {\n setTimeout(function () {\n $(divPagePanel).scroll(scrollPages);\n $(divPagePanel).trigger('scroll');\n }, 100);\n });\n }\n\n function toggleThumbnails() {\n $(divThumbnails).toggle('blind', {\n direction: 'left',\n duration: 300\n }, function () {\n if ($(divThumbnails).is(':hidden')) {\n $(divDoclist).removeClass('active');\n }\n });\n }\n\n function turnPage(dir) {\n if (dir == 'prev') {\n if (currPage == 1) {\n return;\n }\n currPage -= 1;\n } else if (dir == 'next') {\n if (currPage == lastPage) {\n return;\n }\n currPage += 1;\n }\n\n $(divPagePanel).stop().animate({\n scrollTop: $('#page_' + (currPage - 1), divPages)[0].offsetTop\n }, 400, function () {\n $(txtCurrPage).val(currPage + ' / ' + lastPage);\n });\n }\n\n function loadImages() {\n /*** Get the greatest width of list images ***/\n for (i = 0; i < settings.imgslist.length; i += 1) {\n if (settings.imgslist[i].width > maxWidth) {\n maxWidth = settings.imgslist[i].width;\n }\n }\n\n factor = (divPagePanel.clientWidth - 50) / maxWidth;\n\n for (i = 0; i < settings.imgslist.length; i += 1) {\n /*** Create thumbnails ***/\n if (settings.sidebar && settings.thumbnails) {\n spanLabel[i] = document.createElement('span');\n spanLabel[i].innerHTML = i + 1;\n\n divLabel[i] = document.createElement('div');\n divLabel[i].setAttribute('class', 'label');\n divLabel[i].appendChild(spanLabel[i]);\n\n imgThumbnail[i] = document.createElement('img');\n imgThumbnail[i].setAttribute('class', 'preload');\n imgThumbnail[i].setAttribute('idx', i);\n imgThumbnail[i].src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKoAAADcCAYAAADgDTpeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\\nAAAbrwAAG68BXhqRHAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAwSSURB\\nVHic7dl9TJV1H8fxzzk8PwnmMYeOB3mQWMWKIgVW5DJrmojpyqy1XKv+KdcfzfBhaTWzzP6xja0y\\n/2gjrQ0dlMxZFkiMSkirGagl4AMKDOSZ8ACf+4/Gdd/Xfbrtflg3fNvn9d/5na/X+Xl4e3ldFx6S\\nhMgU553sDYj8OxSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVM\\nUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhi\\ngkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIV\\nExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSq\\nmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQ\\nxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSF\\nKiYoVAO6urqwceNGNDQ0TPZWJk3wZG/gP9HZ2Yk9e/bg6NGj6O3tRVJSEoqKirBq1Sp4PJ7J3t6f\\npqqqCtu3b8fdd9892VuZNGbOqAcOHEB6ejo2bdqE7u5uxMbGoqamBg899BC2bt062dv7U02cSbOz\\nsyd5J5PHxBn10KFDWL16NebOnYvS0lLcdtttAIDx8XHs3r0bkZGRk7zDP1dDQwOSkpLg8/kmeyuT\\nxkOSk72Ja+np6UFaWhqCgoJQX1+PhISEa84PDg7i008/xYULF5CdnY2FCxfi66+/RmRkJLKysgAA\\nbW1tOHbsGJYvX476+nrU1tZi0aJFuPHGGwEAo6OjOHjwIH7++WfMmzcPS5YsQWNjI3p7e5Gfn+/6\\nvG+++QZ1dXWIi4vDihUrMDIygrq6OhQWFjqXI5WVlbjpppuQkJCAI0eOoLGxEVlZWSgoKAjYf39/\\nPz755BO0t7fjjjvuQH5+Pnw+HwoKClBWVuaaPXnyJKqqqgAAGRkZKCgoQEhIyH/1PU95nOI2bdpE\\nAHzvvff+cPb7779neno6ATAyMpIAuG7dOsbGxnLLli3OXHFxMefMmcNt27bR4/EQAF977TWS5IUL\\nF7hgwQLXMYqKinjzzTdzzZo1zjH8fj+feeYZAmBYWBiDgoKYnp7O1atX0+fzOXOXL18mAO7atYs5\\nOTn0er0MDQ0lAL799tuu/R87dozJycmuz161ahUBcNu2bc7c0NAQH330UXo8HkZGRjI6OpoAeMst\\nt/DKlSv/7Vc9pU3pUMfHx5mYmEifz8eRkZFrzl65coXJyclMSkri8ePHSZKfffYZp0+fTgCsqKhw\\nZu+9917OmDGDcXFx3L9/P8+ePcvu7m76/X7m5+czLi6Ohw8f5vj4OE+cOMGUlBQC4FtvveUcY/Pm\\nzQTAN954g7/++is7Ozv5wAMPEADvu+8+Z+7gwYMEwPj4eD7++ONsb29nZ2cnY2JiuGDBAmeus7OT\\ns2fPZmpqKn/44QeSZFlZGcPCwgiAhw4dcmYLCwsZGhrKPXv20O/3c3x8nC+99BIB8PXXX//fvvQp\\nakqH+uOPPxIAH3744T+cffnllwmAX375pWt9/fr1BMCLFy86azNmzKDH4+Hnn3/umt23bx8B8N13\\n33Wt7969mwBYVVVFkmxra2NoaChXrlzpmmttbSUAbty40Vl75ZVXCIDLly93zWZkZDAnJ8d5XVxc\\nTACsq6tzzT377LMEwM7OTpJkRUUFAXDHjh2uud7eXgJwnfX/SqZ0qPv37ycAvvrqq384m5iYyKys\\nrID1JUuWMD4+3nnd3NxMAFyxYkXA7OLFixkXF8fh4WHX+vPPP0+v18ve3l6S5I4dOwiA1dXVrrnK\\nykoCYFlZmbNWWFhIr9fL1tZWZ83v9zMiIoKPPfYYyd/+55g1a5Yr3AmLFi1iUlKS83rZsmWMjo7m\\nwMCAa25oaOgvHeqUfjzV0dEBAIiJibnmXEtLC86dO4d77rnHtT44OIjq6mrnKQHw90c9a9ascc2O\\njY2htrYW+fn5CA8Pd71XWVmJ9PR0TJs2DQBw9OhRREREIC8vL2AOcD9GamhoQH5+PhITE521xsZG\\nDA8PO/s6deoU2tvbA/bf39+P2tpa1/6rq6uRk5ODqKgo1+zp06cBACkpKb/7HVk3pUONjY0FADQ3\\nN19zrrW1FQCQnJzsWt+3bx8GBwd/N9R/vuPu6OjA4OBgwDFqampw+vRp3H777c5aS0sLEhISEBz8\\n96d7fX19+Pjjj+Hz+ZxjXL58GRcvXgx4UD+xh4l9Tex/7ty5rrkPP/zQFfTg4CD6+vowZ86cgO+g\\nvLwcAHD//fcHvPdXMKVDzcvLg9frRWlpKbq6ulzvjY6O4osvvgAA5zHQ8PCw835LSwvWr18PAK5Q\\nv/vuOyQkJGDmzJmu4wUFBQEAhoaGnLWenh48/fTTAcfwer2uOZJYt24dOjo6XGfT+vp6AIEP6hsa\\nGuD1enHrrbcC+O15MPBbiBPOnj2L4uJi12dHREQgPDwcly5dch3v/Pnz2LVrF3Jzc53HZyMjI2hq\\nanKODQBXr15FU1MTxsbGnLXR0VE0NTVhdHQUU9pkX3v8kaeeeooAmJiYyO3bt/ODDz7gli1bmJaW\\nxsWLF5Mku7q6GB4eztTUVB4+fJjvvPMOr7/+eubk5ATcSPl8voAbG/K368SEhAROnz6dBw4cYGlp\\nKTMyMpiZmRlwPbp27Vrnjr+yspLLli1jZmYmo6OjuWHDBmdu69atBMBz5865Pis3N5eZmZnO60uX\\nLjE4OJg33HADjxw5wpKSEvp8PmZnZ7tupEhy6dKl9Hq93LlzJxsaGrh3716mpKTQ5/Pxp59+cuYe\\neeQRAmB5ebmz9uSTTxIA9+7d66w999xzBMD333//P/q5/L9N+VBHRkb44osvctq0aQRAALzuuuu4\\ndu1a1w1KSUkJg4ODCYA+n48lJSXcsGEDExMTnZnz588HPJP8RxUVFYyJiSEARkVFcfPmzSwuLqbX\\n62VfX58z19zczHnz5hEAPR4PV65cyePHjweEUVRUxNmzZ7s+Y3x8nFFRUXziiSdc62+++SZDQkJc\\n+3/hhReYlpbmmmtpaeH8+fOd7yIoKIhLly7lqVOnXHPz589neHg4f/nlF2dt4cKFDA0N5cmTJ521\\npUuXMiQkhPX19f/yZzAVTPnfTE0YHR1FW1sbQkJCMGvWLHi9gVct3d3d6OrqQkpKCoKCguD3+wHA\\n9duavr4+56bo9/j9frS0tCAxMRFhYWG488470d/fjxMnTrjmxsbGcObMGcTHxzvX0kNDQ65f546M\\njAAAwsLCXH92YGAAkZGRAX+Hnp4edHV1ISkpCcHBwfD7/fB4PK5r4Qn9/f1oa2tDcnJywPEnPnts\\nbCxgP6Ojo64bsatXr8Lv9wfcnE05k/0vZaoYGBhgZWUlx8bGnLXy8nJ6PB7u3LlzEncmpKEz6p+t\\npqYGd911F3w+H1JTU9Hd3Y0zZ87gwQcfxEcfffS7ZzX5/1Go/+Dbb7/FV199hY6ODsycORN5eXnI\\nzc2d7G0JFKoYMaWfo4pMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSF\\nKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYo\\nVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFB\\noYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJ\\nClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVM\\nUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhigkIVExSqmKBQxQSFKiYoVDFBoYoJClVMUKhi\\ngkIVExSqmPA3lU/xMjEYr2MAAAAASUVORK5CYII=';\n\n thumbnail[i] = document.createElement('div');\n thumbnail[i].setAttribute('class', 'thumbnail');\n thumbnail[i].setAttribute('idx', i);\n thumbnail[i].onclick = clickOnThumbnail;\n thumbnail[i].appendChild(imgThumbnail[i]);\n thumbnail[i].appendChild(divLabel[i]);\n\n divThumbpanel.appendChild(thumbnail[i]);\n\n if (imgThumbnail[i].offsetTop < divThumbnails.clientHeight) {\n $(divThumbnails).trigger('scroll');\n }\n }\n\n /*** Create pages ***/\n image[i] = document.createElementNS(xmlns, 'image');\n image[i].setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVQAAAG4CAYAAAAaFB9MAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\\nAAA3XQAAN10BGYBGXQAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAABYtSURB\\nVHic7d15cNT1/cfx1+YiBxIgkFgD2AmHFIoENoCUoUMhtSDlbq2lHZ3WghVwii3MwBSLWIbCWCtW\\nCkqpOtUBqUg7RS1NKa3JFHMZ7ChEhks5YiAhcpiDI/v+/dEh0/3tblB5V2J8Pv78fvfz/X42mTz5\\n7vdYAmZmAgBctbhrPQEAaC8IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGo\\nAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKA\\nE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4I\\nKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA\\n4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoAT\\nggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggq\\nADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADg\\nhKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOC\\nCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoA\\nOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCE\\noAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IK\\nAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4\\nIagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISg\\nAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoA\\nTggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADgh\\nqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4SbjWE8BH19jYqMrKStXV1SkuLk49evRQ\\n3759FQgErvXUgM80jlA/RQoKCjRhwgSlp6crGAzqq1/9qsaNG6ebbrpJN9xwgx588EE1NjZe62m2\\nS3v27FEgENATTzxxraeCNowj1E+B8+fP695779XTTz+tjh076tvf/rYmTJigHj16KCkpSZWVldqw\\nYYOWLVumF154QX/72990ww03XOtptyvFxcWSpBEjRlzjmaBNM7RpFy5csFtvvdUk2YQJE+z48eNR\\nXxcKhWzZsmUmyYYNG2aXLl36hGfavt19992WmppqFy9evNZTQRvGR/42bsGCBSooKNCUKVO0bdu2\\nmEeegUBAP/vZz/SNb3xDZWVl+sMf/vAJz7R9e+211xQMBpWQwIc6xEZQ27Dy8nKtWbNGvXv31saN\\nGxUfH3/FMUuWLJEkbd68udXXXbp0STU1NWpubv7I8/rggw908eLFVl/T1NSkmpoamdlH3r4k1dXV\\nXdX54Pfff18XLlz4SGPMTDU1NRHv7fTp03r77bev+HH/3LlzV/We8elHUNuwVatWKRQKafXq1UpN\\nTf1QYwYPHqw77rhDAwYMiFh36tQpLViwQL1791ZKSooyMzOVnJysQYMG6Ve/+pUaGhqibnPp0qWa\\nMWOGTpw4oYkTJ6pTp05KT0/XokWLFAqFWl73wQcf6MEHH1S/fv1atp+SkqJvfetbOnDggCRp+fLl\\nGj16dNg46T8xe/bZZzVq1CilpaUpIyNDqampyszM1A9/+ENVVlZGnduOHTuUl5en3bt369y5c1q0\\naJGuv/56de3aVampqRozZowqKipi/rwuXLigp556SsOGDQub81e+8hUVFRVJkkpKShQKhaIGtaqq\\nSnPmzFH37t3VqVMnZWZmqmvXrrr77rtVVVUVc79op67tGQfEcvbsWUtKSrIBAwa4bG///v3Ws2dP\\ny8nJsbVr11pJSYlVVlbaP//5T1u4cKElJydbXl6eNTY2RowdNGiQTZ061QYNGmQzZ860ZcuW2ciR\\nI23atGktr9mzZ4/16tXLsrKy7JFHHrE333zTDh8+bC+99JKNGTPGMjIy7M0337S8vDz70pe+FLb9\\n5uZmmzlzpnXo0MHuu+8+27lzp+3bt89KSkps/fr11r9/f0tOTraioqKIuS1evNgCgYCVlJRY7969\\nbciQIbZixQr77W9/a/Pnz7eUlBTr1KmTVVdXR4ytqamxUaNG2XXXXWdLly61119/3Y4fP25lZWV2\\n7733WlJSkm3ZssWWLl1qkuzo0aNh4wsLC61Lly6WmZlpq1atstLSUquoqLDVq1dbt27dLDs7244c\\nOfJxf2X4FCKobdSf/vQnk2SrVq1y2d4tt9xi/fv3t5qamqjr169fb5Ls+eefD1t+7tw5i4+Pt65d\\nu9pvfvObluWhUMjq6+vNzOzIkSOWmZlpubm5dvLkyajb//GPf2yDBw+2pKQku//++8PWPfHEExYI\\nBGzbtm1Rx544ccI6d+5s48ePj1g3duxYS09PtxtvvNGWL19uzc3NYevXrl1rkux3v/td2PLz589b\\nbm6u9ezZ0w4ePBh1v48++qh16dLFhg4datnZ2WHrDhw4YF26dLG+fftGvVD473//2xITE23SpElR\\nt432iaC2UXPnzjVJ9tprr131toqLi61bt2724osvxnzNkSNHTJKtXLkybPk//vEPk2SjR4+OOTY/\\nP98yMjKsqqoq5msaGxutU6dOEdFubm62kSNH2owZM1p9D+PGjbP+/fuHLWtubm7Z5vz586OOe+ut\\nt0ySPfzww2HLlyxZYgkJCVZeXh5zn6FQyAYMGGCSbPr06WHrxo8fb2lpafbWW2/FHD979mwLBAJR\\nj47RPnEOtY06dOiQJCk3N/eqtzVixAjV1NRo+vTpMV9TV1cnSerRo0fY8tLSUknSwoULo44rKirS\\njh07tHz5cn3uc5+Luf3k5GQNHjy4ZT6XxcXFadeuXdqyZUur7+HUqVPq2bNn2LK9e/fq7Nmz6tWr\\nl37xi19EHVdbWytJYXdHnDlzRo888oh+8IMfKBgMxtxnIBDQ2LFjI+a8e/dubd++XbNmzdLAgQNj\\njr/11ltlZtq9e3er7w3tB/eAtFFVVVVKS0tTcnLy/2T7TU1Nqq2tVU1NjQ4cONBym9XNN98c9rrS\\n0lKlpKRo3LhxUbfz7LPPqmPHjrrzzjuvuM+4uDhlZWXp85//fKuvC4VCqq2tVW1trd577z2VlZWp\\nsrIyYg4lJSWSpPnz58f8Oe3du1eS1KdPn5ZlmzdvVmNjo+bNm3fFOV++GPjfQX3uueckSXPnzm11\\n7OWInz59+or7QftAUNuoCxcuqEOHDm7be+mll/TCCy+ooqJCx48f1/vvvy9Jio+PV9++fVVXV6e0\\ntLSIuwNKS0s1evTomHcZFBUVaeTIkR/qLoTa2tqoV8oPHTqkDRs26NVXX9W7776r6urqltu5srKy\\nlJGRofPnzysvLy9s3OWgTps2LeY+y8rK1KFDh5ajY0nauXOnsrOzWz26vKympkYJCQlh+/7Xv/6l\\nnJycsEjHer+SdN11111xP2gf+MjfRnXt2lVnzpy54v2e/83MdM8994R9/A2FQvrOd76jSZMmqaKi\\nQjNmzNDatWu1a9cuHTlyRA0NDaqsrFT37t2Vm5sbdq/re++9p6NHj2rUqFEx93ns2LErHnFKUkND\\ng/bt2xcR1D/+8Y/64he/qLVr1+rmm2/WAw88oIKCgpaP89XV1fre974nSVGDOmTIkFb3X1JSotzc\\n3LB/nI4eParevXtfcc6S9MYbb2jgwIFKS0trWXbw4MFWTxX891hJuvHGGz/UvtAOXOuTuIhuzpw5\\nJslKS0s/9JhNmzaZJFuwYEHLsstXudevXx9zXHV1tcXFxUVc2Ll8p0FBQUHUcaFQyAKBgM2ePfuK\\nc3vxxRdNku3YsaNl2cmTJy0tLc2+9rWv2dmzZ2OOnThxonXp0sVCoVDLsst3HyxcuDDmuDNnzlhc\\nXJz96Ec/Clt+0003tXqR7bJ3333X4uLi7J577glbnpiYaHPmzLni+Ly8POvcuXPEnQdovzhCbaPG\\njx8v6T/nKD+M+vp6/fSnP1Xnzp3DLiBt2rRJw4cP16xZs2KO3bhxo0KhUMQRYGlpqeLi4jR8+PCo\\n4wKBgDIyMnT48OErzu+xxx5TXFychg0b1rJs27Ztqq+v16OPPhrzY/HJkydVUFCgYDAY9vWE5eXl\\nam5ubvXppfLy8qg35Hfr1q3lol9r1qxZE3V8x44ddfbs2VbHlpeXq7y8XDNnzlRcHH9mnxX8ptuo\\n2267Tf369dP69etbPjrGcvHiRd155506dOiQVq9erczMzJZ1J0+eVMeOHWOObWxs1Lp16yRJQ4YM\\nCVtXWlqqgQMHKj09Peb4ESNGqKysLOZTVpL0+9//XoWFhfrCF76gTp06tSw/ceKEJLU6v8cff1wX\\nL16MmNvl86etBfXyHQq33HJL2PJRo0apqqoq5tNXkvT222/r8ccfj7qPYDCowsLCmI/tmpkWL16s\\n1NRU/eQnP4m5D7RD1/oQGbEVFhZafHy8ZWVlWWFhYdTXvPPOO5afn2+SbPHixRHrJ02aZGlpabZ/\\n//6IdQ0NDTZjxgyTZIFAwBoaGlrWNTc3W3p6us2aNavVOW7dutUk2bx586Ku/8tf/mIpKSkmyb7/\\n/e+HrduyZYtJshUrVkQdu3HjRktISDBJtm7durB106dPtx49erQ6t2nTpllWVlbE8n379lliYqKN\\nGTPGmpqaItYfPHjQ+vTpY4mJiZaenh7xkf35559v9aGLBx54wCTZmjVrItaFQiH7+te/bvn5+fb6\\n669HrF+yZInl5+fbhg0bItZt3brV8vPzP9TpBlwbBLWN27p1q6WmplogELCxY8faQw89ZE8++aSt\\nXLnSpk6daomJiZaammq//vWvo47ftWuXJSUlWXZ2tq1bt85KS0utoKDAHn74YcvJybEpU6bYxIkT\\nLTk5OewcZWVlpUmyp5566opznDZtmkmyKVOm2Msvv2y7d++2l19+2e666y5LTU21hx56yCTZk08+\\nGTbuwoULNnToUEtISLB58+bZzp07rbi42J555hmbNGmSXX/99S1fSbhx48awsdnZ2Vd8GCA7O9sm\\nT54cdd3KlStNkg0dOtSee+45Kysrs+3bt9uCBQusc+fOtnDhQhswYIDl5+dHjA2FQjZ16lSTZLff\\nfru98sortmfPHvvzn/9st912m8XHx0c8IHHZ3r17TZJJivpUWXZ2dtT3a2Z21113Rf2HCW0HQf0U\\nOHbsmM2fP9/69OnT8scoyfr06WP333+/vfPOO62OLyoqsi9/+cuWmppqkiw5OdnGjRtnmzdvtlAo\\nZKtWrbJgMGgnTpxoGbN9+3YLBoNRj2z/v6amJlu2bJn16tWrZW5ZWVk2e/ZsO3z4sD3zzDMmyd54\\n442IsadOnbLZs2dbVlZWy5Fy//79bcmSJVZXV2d79+61YDAYdsR26tQpCwaDEY+T/v/tBoPBVi/G\\nbdq0yfLy8iwQCJgkS0tLs8mTJ9urr75qDQ0NNmzYMHvsscdivuef//znlpOT0/Keu3TpYnfccYeV\\nlZXF3Ocrr7xiwWDQJkyYELGutrbWgsGgBYNBO3z4cMT622+/3YLBYMTjwWg7AmZ819inycWLF3X2\\n7NmPfdP/mTNnWj0nerUaGxtlZmH3pU6ePFnFxcWqrq5u9QJNfX29OnTo8Il/5+ilS5dUX1//sX8u\\nTU1Nam5uDru1Cp9NXJT6lElMTFRGRsbHfoLKM6bFxcVatWqVzp0717IsJSUlLKbHjh3TX//6V33z\\nm9+84tXutLS0a/IFzgkJCVf1c0lOTiamkERQcRUOHTqkRYsWxfzfARoaGvTd735X8fHxXO3GZwKP\\nnuJjmzRpknr06KH77rtPtbW1mjhxorp3765jx46poqJCv/zlL7V//349/fTTysnJudbTBf7nOIeK\\nq7J//37NnTtXf//73yO+hX/48OFasWJFzC9WAdobggoXp0+f1tGjR3XixAl16NBB/fr1U1ZW1rWe\\nFvCJIqgA4ISLUgDghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggq\\nADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADg\\nhKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOC\\nCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoA\\nOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCE\\noAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IK\\nAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4\\nIagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISg\\nAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoA\\nTggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADgh\\nqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKAC\\ngBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBO\\nCCoAOCGoAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGo\\nAOCEoAKAE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKA\\nE4IKAE4IKgA4IagA4ISgAoATggoATggqADghqADghKACgBOCCgBOCCoAOCGoAOCEoAKAE4IKAE4I\\nKgA4IagA4ISgAoATggoATggqADghqADghKACgJP/AxAUOuY0BmpVAAAAAElFTkSuQmCC');\n image[i].setAttribute('class', 'preload');\n image[i].setAttribute('width', settings.imgslist[i].width);\n image[i].setAttribute('height', settings.imgslist[i].height);\n\n svg[i] = document.createElementNS(xmlns, 'svg');\n svg[i].setAttribute('viewBox', '0 0 ' + settings.imgslist[i].width + ' ' + settings.imgslist[i].height);\n svg[i].setAttribute('width', settings.imgslist[i].width * factor);\n svg[i].setAttribute('height', settings.imgslist[i].height * factor);\n svg[i].appendChild(image[i]);\n\n page[i] = document.createElement('div');\n page[i].setAttribute('class', 'page preload');\n page[i].setAttribute('id', 'page_' + i);\n page[i].setAttribute('idx', i);\n page[i].appendChild(svg[i]);\n\n divPages.appendChild(page[i]);\n\n if (page[i].offsetTop < divPagePanel.clientHeight) {\n $(divPagePanel).trigger('scroll');\n }\n }\n }\n\n function setHandlers() {\n if (settings.sidebar) {\n if (settings.bookmarks) {\n $(divIndex).click(function () {\n if ($(this).hasClass('active')) {\n $(this).removeClass('active');\n } else {\n if ($(divThumbnails).is(':visible')) {\n toggleThumbnails();\n }\n\n $('.option', divOptions).removeClass('active');\n $(this).addClass('active');\n }\n });\n }\n\n $(divDoclist).click(function () {\n if ($(divThumbnails).is(':hidden')) {\n $('.option', divOptions).removeClass('active');\n $(this).addClass('active');\n }\n\n toggleThumbnails();\n });\n\n $(divThumbnails).scroll(scrollThumbnails);\n }\n\n if (settings.statusbar) {\n $('.btnPage.prev, .btnPage.next', divCtrlPage).click(function () {\n if ($(this).hasClass('prev')) {\n turnPage('prev');\n } else if ($(this).hasClass('next')) {\n turnPage('next');\n }\n });\n\n $(txtCurrPage).focus(function () {\n this.select();\n });\n\n $(txtCurrPage).keypress(function (e) {\n var idx;\n if (e.which == 13) {\n idx = parseInt($(this).val() - 1, 10);\n\n if (isNaN(idx)) {\n $(this).val(currPage + ' / ' + lastPage);\n return;\n }\n\n if (idx < 0) {\n idx = 0;\n } else if (idx > lastPage) {\n idx = lastPage - 1;\n }\n\n $(divPagePanel).animate({\n scrollTop: $('#page_' + idx, divPages)[0].offsetTop\n }, 400);\n\n $(this).val(idx + ' / ' + lastPage);\n\n currPage = idx;\n\n e.target.blur();\n }\n });\n\n $(divZoomIn).click(function () {\n that.zoom('in');\n });\n\n $(divZoomOut).click(function () {\n that.zoom('out');\n });\n\n $(txtZoom).click(function () {\n that.zoom('restore');\n });\n }\n\n $(divPagePanel).scroll(scrollPages);\n }\n\n /*** Public functions ***/\n this.zoom = function (action) {\n var value, scrollPos;\n\n $(divPagePanel).finish();\n\n scrollPos = divPagePanel.scrollTop / divPagePanel.scrollHeight;\n\n if (action == 'in') {\n value = (zoomScale == 300) ? 300 : zoomScale + 25;\n } else if (action == 'out') {\n value = (zoomScale == 50) ? 50 : zoomScale - 25;\n } else if (action == 'restore') {\n value = 100;\n }\n\n $('.page svg', divPages).each(function (idx) {\n $(this).finish().animate({\n width: $(this).width() * value / zoomScale,\n height: $(this).height() * value / zoomScale\n }, 300);\n });\n\n $(divPagePanel).animate({\n fakeAttr: 300\n }, {\n step: function (now, fx) {\n fx.elem.scrollTop = fx.elem.scrollHeight * scrollPos;\n },\n duration: 300,\n complete: function () {\n zoomScale = value;\n\n if (txtZoom != null) {\n txtZoom.innerHTML = value + '%';\n }\n }\n });\n };\n\n this.loadImages = function (list) {\n settings.imgslist = list;\n lastPage = list.length;\n divPagePanel.scrollTop = 0;\n that.zoom('restore');\n $(divPages).empty();\n loadImages();\n };\n\n this.turnPage = function (dir) {\n turnPage(dir);\n };\n\n this.gotoPage = function (value) {\n var idx = parseInt(value - 1, 10);\n if (isNaN(idx)) {\n $(txtCurrPage).val(currPage + ' / ' + lastPage);\n return;\n }\n\n if (idx < 0) {\n idx = 0;\n } else if (idx > lastPage) {\n idx = lastPage - 1;\n }\n\n $(divPagePanel).animate({\n scrollTop: $('#page_' + idx, divPages)[0].offsetTop\n }, 400);\n\n $(txtCurrPage).val(idx + ' / ' + lastPage);\n\n currPage = idx;\n };\n\n this.destroy = function () {\n $(settings.parent).empty();\n eval(settings.name + ' = null');\n };\n\n /*** Initialize viewer ***/\n setHandlers();\n\n loadImages();\n}",
"function ImageScrollBar(name){var _this=_super.call(this,name)||this;_this.name=name;_this._thumbLength=0.5;_this._thumbHeight=1;_this._barImageHeight=1;_this._tempMeasure=new _measure__WEBPACK_IMPORTED_MODULE_2__[\"Measure\"](0,0,0,0);/** Number of 90° rotation to apply on the images when in vertical mode */_this.num90RotationInVerticalMode=1;return _this;}",
"function mkdSideAreaScroll(){\n\n var sideMenu = $('.mkd-side-menu');\n\n if(sideMenu.length){\n sideMenu.niceScroll({\n scrollspeed: 60,\n mousescrollstep: 40,\n cursorwidth: 0,\n cursorborder: 0,\n cursorborderradius: 0,\n cursorcolor: \"transparent\",\n autohidemode: false,\n horizrailenabled: false\n });\n }\n }",
"function create_scrollbar()\n\t{\n\t\tif ( List.scrollbar !== null ) {\n\t\t\treturn;\n\t\t}\n\n\t\tList.scrollbar = new Entity()\n\t\t\t.add(\n\t\t\t\tnew FillSprite( '#fff', 12, List.view_ratio() * List.pixel_height() )\n\t\t\t\t\t.setAlpha( 0.75 )\n\t\t\t\t\t.setXY( List.width + 2, 0 )\n\t\t\t);\n\n\t\tstage.addChild( List.scrollbar );\n\t}",
"function scrollGalleryRight(galleryID, event){\n\n let elem = document.body.querySelector(`#${galleryID} .gallery`);\n let timer = setInterval(scrollSmooth, 15);\n let stepCounter = 0;\n\n function scrollSmooth(){\n\n stepCounter += 10;\n elem.scrollLeft += 10;\n\n if(stepCounter >= 300){\n clearInterval(timer);\n }\n }\n \n let leftbutton = elem.querySelector(`.prev`);\n leftbutton.style.display = '';\n\n if (elem.scrollLeft >= (elem.scrollWidth - elem.clientWidth)){\n let rightbutton = elem.querySelector(`.next`);\n rightbutton.style.display = 'none';\n }\n\n event.stopPropagation(); // Stop bubbling to the parent tags\n}",
"function InitializeScrollbar(image) {\n //Sets position of viewed image\n _currImage = image;\n _currImage.setPos(_game.global.constants.INFO_VIEW_MARGIN, _game.global.constants.INFO_VIEW_MARGIN);\n\n //Scales scrollbar depending on viewed image height\n var _heightFraction = _game.global.constants.INFO_VIEW_HEIGHT/_currImage.getHeight();\n _scrollbarDraggable.setHeight(_heightFraction*_game.global.constants.SCROLLBAR_DIM[1]);\n\n //Resets position of scrollbar\n _scrollbarDraggable.setY(_game.global.constants.SCROLLBAR_POS[1]);\n\n //Gets range of y values that the scrollbar should take for scrolling\n _effectiveScrollBarHeight = _game.global.constants.SCROLLBAR_DIM[1] - _scrollbarDraggable.getHeight();\n _effectiveImageHeight = _currImage.getHeight() - _game.global.constants.INFO_VIEW_HEIGHT;\n}",
"function mkdfSideAreaScroll(){\n\n var sideMenu = $('.mkdf-side-menu');\n\n if(sideMenu.length){ \n sideMenu.niceScroll({ \n scrollspeed: 60,\n mousescrollstep: 40,\n cursorwidth: 0, \n cursorborder: 0,\n cursorborderradius: 0,\n cursorcolor: \"transparent\",\n autohidemode: false, \n horizrailenabled: false \n });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public function `infinity`. Returns true if `data` is positive or negative infinity, false otherwise. | function infinity (data) {
return data === neginf || data === posinf;
} | [
"function infinity (data) {\n return data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY;\n }",
"function infinity(data) {\n return data === neginf || data === posinf;\n}",
"function infinity(data) {\n return data === neginf || data === posinf;\n }",
"function infinity(data) {\n return data === neginf || data === posinf;\n }",
"function isInfinity(num) {\n \treturn num === Infinity || num === -Infinity\n }",
"function isInfinity(number) {\n if (number === Infinity || number === -Infinity) {\n return true;\n } else {\n return false;\n }\n}",
"function isInfinite(val) {\n return val === Infinity;\n}",
"function onlyInfinity (x) {\n return !isFinite(x.lo) && x.lo === x.hi\n}",
"function number (data) {\n return typeof data === 'number' &&\n isNaN(data) === false &&\n data !== Number.POSITIVE_INFINITY &&\n data !== Number.NEGATIVE_INFINITY;\n }",
"function number (data) {\n return typeof data === 'number' && isNaN(data) === false &&\n data !== Number.POSITIVE_INFINITY &&\n data !== Number.NEGATIVE_INFINITY;\n }",
"testIsInfinite() {\n this.isInfinite(Infinity);\n this.hasException(() => this.isInfinite(0));\n this.hasException(() => this.isInfinite(NaN));\n }",
"function ec_isinf(p) { return !mp_cmp(p.x, [0]) && !mp_cmp(p.y, [0]); }",
"function numberPositiveInfinity(){\n /*BEG dynblock*/\n return JSNumber((typeof Number==='undefined'||Number===null?m$3g8.throwexc(m$3g8.Exception(\"Undefined or null reference: Number\"),'32:18-32:23','number.ceylon'):Number).POSITIVE_INFINITY);\n /*END dynblock*/\n}",
"function myIsNaN(val) {\n return !(val <= 0) && !(val > 0);\n}",
"function numberNegativeInfinity(){\n /*BEG dynblock*/\n return JSNumber((typeof Number==='undefined'||Number===null?m$3g8.throwexc(m$3g8.Exception(\"Undefined or null reference: Number\"),'25:18-25:23','number.ceylon'):Number).NEGATIVE_INFINITY);\n /*END dynblock*/\n}",
"function isNegZero(num) {\n return 1/num === -Infinity;\n}",
"function Infinity() {}",
"function checkIfFinite(inf) {\n return Number.isFinite(inf);\n}",
"function zero(data) {\n return data === 0;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup typeahead on the category input, killing the prevous instance if present. | setupCategorySearch() {
if (this.typeahead) this.typeahead.destroy();
$('#category-input').typeahead({
ajax: {
url: 'https://commons.wikimedia.org/w/api.php',
timeout: 200,
triggerLength: 1,
method: 'get',
preDispatch: query => {
return {
action: 'query',
list: 'prefixsearch',
format: 'json',
pssearch: query,
psnamespace: 14
};
},
preProcess: data => {
const results = data.query.prefixsearch.map(elem => elem.title.replace(/^Category:/, ''));
return results;
}
}
});
} | [
"_createTypeahead() {\n\n if (this.typeahead === true || this.inputEl.getAttribute('data-typeahead') !== null) {\n this.typeahead = new Typeahead(this.el, {\n onBlur: this._onBlurBound\n });\n }\n }",
"function initializeTypeahead() {\n var reinitialize = !!terms;\n if (reinitialize) {\n $search_input.typeahead('destroy');\n } else {\n terms = buildSuggestionEngine();\n }\n terms.initialize(reinitialize);\n\n $search_input.typeahead(DEFAULT_OPTIONS, {\n name: 'terms',\n source: terms.ttAdapter(),\n limit: SUGGESTION_COUNT,\n display: function(response) { return displayTerm(response); },\n templates: {\n suggestion: ttEntry,\n header: ttHeader, // TODO: keep?\n footer: ttFooter, // TODO: keep?\n notFound: ttNotFound,\n pending: ttPending\n }\n });\n }",
"function initTypeahead() {\n $ingredientName.attr('autocomplete', 'off');\n\n $('.ingredient-name').typeahead({\n source: ingredientList,\n items: 5,\n autoSelect: false,\n selectOnBlur: true,\n changeInputOnSelect: true,\n changeInputOnMove: true,\n displayText: (item) => {\n return item.ingredient_name;\n },\n sorter: (items) => {\n const curr = $ingredientName.val();\n\n return items.sort(function(a, b) {\n if (curr == a.ingredient_name) {\n return -1;\n } else if (curr == b.ingredient_name) {\n return 1;\n } else if (curr.toLowerCase() == a.ingredient_name.toLowerCase()) {\n return -1;\n } else if (curr.toLowerCase() == b.ingredient_name.toLowerCase()) {\n return 1;\n } else if (a.ingredient_name < b.ingredient_name) {\n return -1;\n } else if (a.ingredient_name > b.ingredient_name) {\n return 1;\n }\n return 0;\n });\n },\n });\n }",
"function typeahead() {\n\t\tconsole.log(\"typeahead\"); //test\n\n\t\t$(\"#sun_query\").typeahead({\n\t\t minLength: 1,\n\t\t source: function (query, process) {\n\t\t return $.post(\n\t\t '/autocomplete', \n\t\t { msg: query }, \n\t\t function (data) {\n\t\t \tvar data = JSON.parse(data)\n\t\t return process(data.options);\n\t\t });\n\t\t }\n\t\t});\n\t}",
"initTypeahead(cityNames) {\n const city_suggestions = new Bloodhound({\n datumTokenizer: Bloodhound.tokenizers.whitespace,\n queryTokenizer: Bloodhound.tokenizers.whitespace,\n local: cityNames\n });\n $('#my_search').typeahead({\n hint: true,\n highlight: true,\n minLength: 1\n },\n {\n name: 'cities',\n source: city_suggestions\n })\n .on('typeahead:selected', function () {\n $('.city-input-form').submit();\n });\n }",
"initTypeahead(typediv, formdiv, url, fxn) {\n\n const _this = this;\n let typeurl;\n typediv = (typediv === undefined) ? this.typeahead : $(typediv);\n formdiv = (formdiv === undefined) ? this.searchform : $(formdiv);\n // get the typeahead search page getparams url\n try {\n typeurl = (url === undefined) ? Flask.url_for('search_page.getparams', {'paramdisplay':'best'}) : url;\n } catch (error) {\n Raven.captureException(error);\n console.error('Error getting search getparams url:',error);\n }\n const afterfxn = (fxn === undefined) ? null : fxn;\n\n function customQueryTokenizer(str) {\n let newstr = str.toString();\n return [_this.extractor(newstr)];\n };\n\n // create the bloodhound engine\n this.queryparams = new Bloodhound({\n datumTokenizer: Bloodhound.tokenizers.whitespace,\n //queryTokenizer: Bloodhound.tokenizers.whitespace,\n queryTokenizer: customQueryTokenizer,\n prefetch: typeurl,\n remote: {\n url: typeurl,\n filter: (qpars)=>{ return qpars; }\n }\n });\n\n // initialize the bloodhound suggestion engine\n this.queryparams.initialize();\n\n // init the search typeahead\n typediv.typeahead('destroy');\n typediv.typeahead(\n {\n showHintOnFocus: true,\n items: 'all',\n source:this.queryparams.ttAdapter(),\n updater: function(item) {\n // used to updated the input box with selected option\n // item = selected item from dropdown\n let currenttext = this.$element.val();\n let removedtemptype = currenttext.replace(/[^,]*$/,'');\n let newtext = removedtemptype+item+', ';\n return newtext;\n },\n matcher: function (item) {\n // used to determined if a query matches an item\n let tquery = _this.extractor(this.query);\n console.log('query', this.query);\n console.log(tquery);\n if(!tquery) return false;\n return ~item.toLowerCase().indexOf(tquery.toLowerCase());\n },\n highlighter: function (item) {\n // used to highlight autocomplete results ; returns html\n let oquery = _this.extractor(this.query);\n let query = oquery.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, '\\\\$&');\n return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {\n return '<strong>' + match + '</strong>';\n });\n }\n });\n }",
"function initializeTypeAhead() {\r\n \r\n var termsData = []; \r\n $.getJSON('/api/terms', function(terms){\r\n console.log(terms.data[0]);\r\n\r\n for (var i=0; i <= terms.data.length; i++) {\r\n if (terms.data[i]) { // If empty then it will not assign\r\n termsData.push(terms.data[i]);\r\n }\r\n }\r\n \r\n $(\"#termtypeahead\").typeahead({\r\n source:termsData,\r\n updater: function(item) {\r\n // display the terms and generate the JSON savable term data\r\n gettermdetails(item);\r\n return item;\r\n }\r\n });\r\n });\r\n }",
"hideTypeahead() {\n if (!this.input.length) {\n this.$nextTick(() => {\n this.clearSearchResults();\n });\n }\n }",
"hideTypeahead() {\n if (! this.input.length) {\n this.$nextTick(() => {\n this.clearSearchResults();\n });\n }\n }",
"function typeaheadDisable() {\n\t\t$('#meetings #search input[name=\"query\"]').typeahead('destroy');\n\t}",
"function setAutocomplete() {\n\tvar url = 'api.cgi?method=search_filters&q=%QUERY&limit=10';\n\tvar temp = '<table><tr><td>';\n\ttemp += '<span class=\"glyphicon glyphicon-{{icon}}\" title=\"{{type}} filter\"></span>';\n\ttemp += '</td><td style=\"padding-left: 10px\">';\n\ttemp += '<a href=\"#filter={{type}}&text={{text}}\">{{text}}</a>';\n\ttemp += '</td></tr></table>';\n\t$('#search-filters,#add-spam-filter').typeahead([\n\t\t\t{\n\t\t\t\tname: 'spam-filters',\n\t\t\t\tremote: url,\n\t\t\t\ttemplate: temp,\n\t\t\t\tvalueKey: 'text',\n\t\t\t\tlimit: 10,\n\t\t\t\tengine: Hogan\n\t\t\t}\n\t\t])\n\t\t.on('typeahead:selected', function($e, datum) {\n\t\t\t$('#search-filters,#add-spam-filter').blur().val('');\n\t\t\twindow.location.hash = 'filter=' + datum.type + '&text=' + datum.text;\n\t\t\tcheckForPageChange();\n\t\t})\n\t\t.focusin(function() {\n\t\t\t$(this).stop().animate( {\n\t\t\t\t'width': ($(window).width() - $(this).offset().left - 50) + 'px'\n\t\t\t}, 200);\n\t\t})\n\t\t.focusout(function() {\n\t\t\t$(this).stop().animate( {\n\t\t\t\t'width': ($(window).width() - $('#search-filters').offset().left - 60) + 'px'\n\t\t\t}, 200);\n\t\t})\n\t\t.css('width', '150px');\n}",
"function attachTypeahead() {\n // attach an empty source by default\n $input.typeahead({source: [], items: 59, updater: addModule});\n\n if (planner.school) {\n updateTypeahead();\n }\n\n $.subscribe(\"app:school\", updateTypeahead);\n }",
"function SetAutocomplete()\r\n{\r\n var vName = '#Name';\r\n var remUrl = \"Supervisor/GetVendors?searchTerm=%QUERY\";\r\n\r\n var vendorCols = new Bloodhound({\r\n datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),\r\n queryTokenizer: Bloodhound.tokenizers.whitespace,\r\n hint: true,\r\n highlight: true,\r\n items: 5,\r\n minLength: 3,\r\n remote: remUrl\r\n });\r\n\r\n vendorCols.initialize();\r\n\r\n $(vName).typeahead(null, {\r\n name: 'vendorCols',\r\n displayKey: 'Name',\r\n source: vendorCols.ttAdapter()\r\n });\r\n}",
"function SetAutocomplete()\r\n{\r\n var itemId = '#ItemName_0';\r\n var remUrl = \"Supervisor/GetItems?searchTerm=%QUERY\";\r\n\r\n itemCols = new Bloodhound({\r\n datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),\r\n queryTokenizer: Bloodhound.tokenizers.whitespace,\r\n hint: true,\r\n highlight: true,\r\n items: 5,\r\n minLength: 3,\r\n remote: remUrl\r\n });\r\n\r\n itemCols.initialize();\r\n\r\n $(itemId).typeahead(null, {\r\n name: 'itemCols',\r\n displayKey: 'ItemName',\r\n source: itemCols.ttAdapter()\r\n });\r\n}",
"function typeaheadConfig() {\r\n if ($('.ajax-typeahead')) {\r\n var url = $('.ajax-typeahead').data('url');\r\n window.query_cache = {};\r\n $('.ajax-typeahead').typeahead({\r\n source: function (q, process) {\r\n if (query_cache[q]) {\r\n process(query_cache[q]);\r\n return;\r\n }\r\n if ( typeof searching != 'undefined') {\r\n clearTimeout(searching);\r\n process([]);\r\n }\r\n searching = setTimeout(function() {\r\n return $.get(url, { q: q }, function (data) {\r\n // make a json string that bootstrap can use\r\n var num = data.RES.M;\r\n var allResults = { 'results': [] };\r\n if (num != 1) {\r\n $.each(data.RES.R,function(i,item){\r\n var currentResult = {};\r\n currentResult = item.T; // we could also add the url in here and make it clickable\r\n allResults.results.push(currentResult);\r\n data = allResults;\r\n });\r\n } else {\r\n var currentResult = {};\r\n currentResult = data.RES.R.T;\r\n allResults.results.push(currentResult);\r\n data = allResults;\r\n }\r\n return process(data.results);\r\n });\r\n }, 600); // 300 ms\r\n }\r\n });\r\n}\r\n}",
"function set_search_des_auto(module){\r\n var module = module;\r\n\r\n var destinations = new Bloodhound({\r\n datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),//'name'\r\n queryTokenizer: Bloodhound.tokenizers.whitespace,\r\n prefetch: '/' + module + '-des-auto-prefetch/' + module + '-des-auto.json',\r\n remote: '/' + module + '-des-auto-remote/%QUERY.json',\r\n limit:20\r\n });\r\n\r\n destinations.initialize();\r\n\r\n $('#' + module + '_destination').typeahead({\r\n minLength: 2,\r\n highlight : true,\r\n hint : true,\r\n autoselect: true\r\n },{\r\n name: 'destinations',\r\n displayKey: 'name',\r\n source: destinations.ttAdapter(),\r\n templates: {\r\n suggestion: Handlebars.compile('<span class=\"pull-left type-width\" style=\"font-size:10px; background-color: {{color}};\">{{destination_type}}</span> <span class=\"pull-left arrow-seach\" style=\" border-color: transparent transparent transparent {{color}};\"></span> <span class=\"margin-left-15\">{{name}}</span> <span class=\"pull-right\">{{parent_name}}</span>')\r\n }\r\n }).on(\"typeahead:selected\", function($e, datum){\r\n //alert('go here 2');4\r\n \tif(module == 'hotel'){\t\r\n \t\t\r\n \t\tif(datum.is_hotel != undefined){ // select the hotel\r\n \t\t\t$('#' + module + '_destination_id').val('');\r\n \t\t\t$('#hotel_search_id').val(datum.id);\r\n \t\t} else {\r\n \t\t\t$('#' + module + '_destination_id').val(datum.id);\r\n \t\t\t$('#hotel_search_id').val('');\r\n \t\t}\r\n \t\t\r\n \t\t\r\n \t} else {\r\n \t\t$('#' + module + '_destination_id').val(datum.id);\r\n \t} \r\n\r\n }).on(\"typeahead:autocompleted\", function($e, datum){\r\n //alert('go here');\r\n $('.tt-dataset-destination .tt-suggestions .tt-suggestion').first().addClass('tt-cursor');\r\n }).on(\"keyup\", function(e){\r\n if(e.keyCode != 13){\r\n $('#' + module + '_destination').popover('destroy');\r\n $('#' + module + '_destination').removeClass('input-error');\r\n $('#' + module + '_destination_id').val('');\r\n \r\n if(module == 'hotel'){\t\r\n \t$('#hotel_search_id').val('');\r\n }\r\n }\r\n });\r\n}",
"function navbar_serach_box_autocomplate() {\n $('#ask_question_input').typeahead({\n delay : 500,\n source : function(query, process) {\n $.post('/api/autocomplete', {\n queries: [{\n type : 'question',\n term : query, // search term\n max_match: 7,\n use_similar: 0,\n }]\n }, function(results) {\n process(results);\n })\n },\n displayText : function(item) {\n return item.title;\n },\n afterSelect : function(item) {\n if (item || item.url) {\n window.location.replace(item.url);\n }\n },\n bottomElement : {\n html : \"<li class='nav_search_box_hint' onclick='navbar_ask_question_detail()'>I don't find my desired answer, keep asking</li>\",\n },\n noResultHide : false,\n items: 8,\n });\n}",
"function SearchTypeahead(selector, currency, productURLRoot, searchResultPage, ismodal, prodListing) {\n \n if(mInstance !== null){\n throw new Error(\"Cannot instantiate more than one SearchTypeahead, use SearchTypeahead.getInstance()\");\n }\n currencySymbol = currency.symbol;\n if(currencySymbol.match(/^[0-9a-zA-Z]+$/)) {\n currencySymbol = currencySymbol + ' ';\n }\n fractionalDigits = currency.fractionalDigits;\n this.productURLRoot = productURLRoot ? productURLRoot : PRODUCT_URL_ROOT;\n this.searchResultPage = searchResultPage ? searchResultPage : CCConstants.SEARCH_RESULTS_HASH;\n isModal = (ismodal == null) ? false : ismodal;\n productListing = (prodListing == null) ? null : prodListing;\n this.initialize(selector);\n }",
"function pkTagahead(tagaheadUrl)\n{\n $(function() {\n function getKey(event)\n {\n // Portable keycodes sigh\n return event.keyCode ? event.keyCode : event.which;\n }\n function setClick(target)\n {\n $(target).find('li').click(function(event)\n {\n // span contains ul contains li contains a\n var span = this.parentNode.parentNode;\n var input = $(span).data(\"tag-peer\");\n // Get text from the li\n var tags = $('.left',this).html()+$('a',this).html()+$('.right',this).html();\n $('input.tag-input').data('tag-last',tags);\n $('li',target).remove();\n \n $(input).val(tags);\n $(input).focus();\n return false;\n }).hover(function(){\n $(this).addClass('selected');\n },function(){\n $('li.selected',$(\"input.tag-input\").data('tag-peer')).removeClass('selected');\n });\n }\n // Add suggestions span (you'll need to style that)\n $('input.tag-input').after(\"<div class='tag-suggestions'></div>\");\n // Each tag field remembers its suggestions span...\n $('input.tag-input').each(function() \n {\n $(this).data(\"tag-peer\", $(this).next()[0]);\n });\n // And vice versa\n $('div.tag-suggestions').each(function() \n {\n $(this).data(\"tag-peer\", $(this).prev()[0]);\n });\n // Now we can really throw down\n $('input.tag-input').keyup(function(event) \n {\n var key = getKey(event);\n // Tab key \n if (key == 13)\n {\n $('li.selected',$(\"input.tag-input\").data('tag-peer')).trigger('click');\n// var peer = $(this).data(\"tag-peer\");\n// var suggestions = $(peer).find(\"li\"); \n// if (suggestions.length)\n// {\n// $(this).val($(suggestions[0]).text());\n// $(this).focus();\n// }\n // In any case don't insert the tab\n return false;\n }\n else\n {\n // Trigger ajax update of suggestions\n } \n });\n $('input.tag-input').keypress(function(event) \n {\n var lis = $('li',$(\"input.tag-input\").data('tag-peer'));\n var selected = $('li.selected',$(\"input.tag-input\").data('tag-peer'));\n var key = getKey(event);\n //up\n if(key==38){\n if(!selected.length){\n lis.last().addClass('selected');\n }else if(selected.prev()){\n selected.removeClass('selected');\n selected.prev().addClass('selected');\n }\n }\n //down\n if(key==40){\n if(!selected.length){\n lis.first().addClass('selected');\n }else if(selected.next()){\n selected.removeClass('selected');\n selected.next().addClass('selected');\n }\n }\n // Firefox 2.0 mac is stubborn and only allows cancel here\n // (we will still get the keyup and do the real work there)\n //tab or enter\n if (key == 9 || key==13)\n {\n return false;\n }\n });\n var lastValues = {};\n setInterval(function() \n {\n // AJAX query for suggestions only when changes have taken place\n $('input.tag-input').each(function() \n {\n var last = $(this).data('tag-last'); \n var value = $(this).val();\n var peer = $(this).data('tag-peer');\n var query = $(this).val(); \n if (last !== value && query.split(\",\").pop().length > 1)\n {\n $(this).data('tag-last', value);\n $.post(\n tagaheadUrl, \n { \n current: query \n },\n function(data, textStatus) \n {\n $(peer).html(data); \n setClick(peer);\n }\n );\n }\n });\n }, 200);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
with ticket update radio box checked, pop up the tickets | function statusRadioTicket(e) {
if (e.id == 'optTicket1') {
$('#list-tickets').show('0.3');
} else {
$('#list-tickets').hide('0.3');
}
} | [
"function changeViewTickets(){\n\tif($(\"#webpartTickets .slm-layout-main\").attr(\"data-current\") == \"cards\"){\n\t\tfade($(\"#webpartTickets .ticket_display\"),\"out\",null);\n\t\tfade($(\"#webpartTickets .ticket_submit\"),\"in\",\"add\");\n\t}\n\telse if($(\"#webpartTickets .slm-layout-main\").attr(\"data-current\") == \"add\"){\n\t\tfade($(\"#webpartTickets .ticket_submit\"),\"out\",null);\n\t\tfade($(\"#webpartTickets .ticket_display\"),\"in\",\"cards\");\n\t}\n}",
"function updateTracTicket(id,timestamp){\n\t//document.write(ticket[3]._ts);\n\tvar attributes={\n\t\t'_ts': timestamp,\n\t\t'action': $('input:radio[name=tracAction]:checked').val()\n\t}\n\t//retrieve value in select box if it exists\n\tvar test = $('input:radio[name=tracAction]:checked').parent().children('select');\n\tif (test.length>0){\n\t\tattributes[test.attr('name')]=test.val();\n\t}\n\tif(option.prefill!=null){\n\t\tvar comment= $('#commentField').val() + \"\\n{{{\\n\" + $('#prefillTrac').html().replace(/<br>|<br\\/>/g,'\\n') + \"\\n}}}\";\n\t}\n\telse{\n\t\tvar comment= $('#commentField').val();\n\t}\n\ttry{\n\t\treturn rpcTrac(\"ticket.update\",id,comment,attributes);\n\t}\n\tcatch(err){\n\t\tconsole.debug(err);\n\t}\n}",
"showTickets() {\n if (this.fieldTo.value) {\n this.elements.form.querySelector('.ticket-to').innerHTML = `Билет туда: <span class=\"ticket-value\">${this.fieldTo.value}</span>`;\n }\n\n if (this.elements.form.querySelector('.field-back').value) {\n const ticketBack = this.elements.form.querySelector('.ticket-back');\n ticketBack.innerHTML = `Билет обратно: <span class=\"ticket-value\">${this.elements.form.querySelector('.field-back').value}</span>`;\n }\n this.elements.form.querySelector('.field-back').value = '';\n this.fieldTo.value = '';\n this.fieldTo = null;\n }",
"function btn_update_send_received_onclick(p_checkbox_obj,p_type,p_doc_id){\r\n\tv_value_list = checkbox_value_to_list(p_checkbox_obj,\",\");\r\n\tif (!v_value_list){\r\n\t\talert(\"Chua co doi tuong nao duoc chon\");\r\n\t}else{\r\n\t\tarr_value = v_value_list.split(\",\");\r\n\t\tif (arr_value.length > 1){\r\n\t\t\talert(\"Chi duoc chon mot doi tuong de sua\")\r\n\t\t\treturn;\r\n\t\t}else{\r\n\t\t\tif(p_type == 'VB_DEN'){\r\n\t\t\t\tdocument.getElementById('hdn_object_id').value = v_value_list;\r\n\t\t\t\tvar p_url = '../editreceived/?showModalDialog=1&hdn_object_id=' + v_value_list + '&hdn_doc_id=' + p_doc_id +'&hdn_type=' + p_type;\r\n\t\t\t\tDialogCenter(p_url,'',800,560);\r\n\t\t\t}\r\n\t\t\tif(p_type == 'VB_DI'){\r\n\t\t\t\tdocument.getElementById('hdn_object_id').value = v_value_list;\r\n\t\t\t\tvar p_url = '../editsend/?showModalDialog=1&hdn_object_id=' + v_value_list + '&hdn_doc_id=' + p_doc_id +'&hdn_type=' + p_type;\r\n\t\t\t\tDialogCenter(p_url,'',800,560);\r\n\t\t\t}\r\n\t\t\tif(p_type == ''){\r\n\t\t\t\tp_url = '../edit';\r\n\t\t\t\titem_onclick(v_value_list,p_url);\r\n\t\t\t}\t\r\n\t\t}\r\n\t}\r\n}",
"function updateInfoBox(module){\n\tvar items = generateDataForTrackingTable(module);\n\tvar infobox = dhtml.getElementById(\"meetingrequest_responses\");\n\tif(items.length >1){\n\t\tvar accepted = 0, tentative = 0, declined = 0;\n\t\tfor(var i=0;i<items.length;i++){\n\t\t\tswitch( parseInt(items[i].recipient_status_num.innerHTML, 10) ) {\n\t\t\t\tcase olResponseTentative: // tentative\n\t\t\t\t\ttentative++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase olResponseAccepted: //accepted\n\t\t\t\t\taccepted++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase olResponseDeclined: // declined\n\t\t\t\t\tdeclined++;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tinfobox.style.display = \"block\";\n\t\tinfobox.innerHTML = NBSP + accepted +\" \"+ _(\"attendee accepted\") +\", \"+ tentative +\" \"+ _(\"tentatively accepted\") +\", \"+ declined +\" \"+ _(\"declined\") +\".\";\n\t}\n}",
"function ticketFromThread( thread_id ) {\n var r = confirm( 'Are you sure you wish to create a new ticket from this thread?' );\n if ( r == true ) {\n jQuery('#ticketContainer .wpspActionDashboardBody,#ticketActionDashboard,#ticketContainer .ticket_list,#ticketContainer .ticket_indivisual,#ticketContainer .ticket_assignment').hide();\n jQuery('#ticketContainer .wait').show();\n \n var data = {\n 'action': 'ticketFromThread',\n 'thread_id': thread_id\n };\n \n jQuery.post(display_ticket_data.wpsp_ajax_url, data, function(response) {\n var ticket_id = response.substring(0,response.length - 1);\n openTicket(ticket_id);\n });\n }\n}",
"function onChangeStatusClick() {\n\t\n\tvar newStatus;\n\t\n\tvar shid = $(this).attr(\"shid\"); // get the id of the hour selected\n\t\n\tconsole.log(shid);\n\t\n\t/*\n\t * Change the new status to whatever button was clicked\n\t */\n\tif ($(this).hasClass(\"btnApprove\"))\n\t\tnewStatus = \"Approved\";\n\telse\n\t\tnewStatus = \"Rejected\";\n\t\n\t// open the feedback dialog, specifying the new hour status\n\tvar data = $(\"#feedbackDlg\").data();\n\tdata.newStatus = newStatus;\n\tdata.shid = shid;\n\t$(\"#feedbackDlg\").dialog(\"open\");\n}",
"function updateTicket(){\n\t//getting the values given in the field\n \tvar x= document.getElementById(\"status\");\n var y = parseInt(x.options[x.selectedIndex].value);\n var a= document.getElementById(\"priority\");\n var b = parseInt(a.options[a.selectedIndex].value);\n var c= document.getElementById(\"type\");\n var d = c.options[c.selectedIndex].value;\n var sub = document.getElementById('subject').value;\n var des = document.getElementById('description').value;\n var\temail = document.getElementById('contact').value;\n \n //getting the id value from the URL\n\tvar id = parent.document.URL.substring(parent.document.URL.indexOf('?'), parent.document.URL.length);\n var trueid = id.substring(4);\n \n //performing the updation process\n\tfetch(`https://newaccount1626771088636.freshdesk.com/api/v2/tickets/${trueid}`,{\n\t\tmethod : 'PUT',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization': 'Bearer ' + btoa('70KHRsQhmNSxhIZs0Nz:X')\n },\n body :JSON.stringify({\n \t //subject : `${sub}`,\n //description : `${des}`,\n status : y,\n priority : b,\n email : `${email}`,\n //type : d\n })\n\t})\n .then(data => data.json())\n\t.then(data => {\n\t\t//error handling\n\t\tif(data.errors){\n\t\tdata.errors.map(ele => {\n alert(`Invalid ${ele.field}`);\n })\n }\n else{\n \talert('Update Sucess!');\n \tlocation.replace('index.html');\n }\n\t\n})\n\t.catch(err => console.log(err));\n}",
"function updateTicket(e) {\r\n\te.preventDefault();\r\n\tif (validateMandatoryFields()) {\r\n\t\t$.ajax({\r\n\t\t\turl : 'rest/portal/updateticket',\r\n\t\t\ttype : 'PUT',\r\n\t\t\tdata : $('#ticketing_form').serializeArray(),\r\n\t\t\tsuccess : function(data) {\r\n\r\n\t\t\t\t$(\"#creationstatus_message\").html(data);\r\n\t\t\t\tif (data.substring(0, 6) == 'Ticket') {\r\n\t\t\t\t\t$('#ticketid').html(\"\");\r\n\t\t\t\t\t$('#ticketing_form')[0].reset();\r\n\t\t\t\t}\r\n\t\t\t\tvar elmnt = document.body;\r\n\t\t\t\telmnt.scrollTop = 0;\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n}",
"function checkInNotification(flightNo) {\n var allFlightsData = kony.store.getItem(\"AllFlightsData\");\n if (allFlightsData != null) {\n allFlights = allFlightsData[\"flightdetails\"];\n for (var i = 0; i < allFlights.length; i++) {\n var com = \"completed\";\n var update = \"true\";\n if (flightNo == allFlights[i][\"flightNumber\"]) {\n frmCheckin.lblFno.text = allFlights[i][\"flightNumber\"];\n frmCheckin.lblFDestination.text = allFlights[i][\"flightDestination\"];\n frmCheckin.lblFSource.text = allFlights[i][\"flightSource\"];\n frmCheckin.lblBoarding.text = allFlights[i][\"flightTime\"];\n var GateNO = Math.floor((Math.random() * 100) + 10);\n GateNO = 'A' + GateNO;\n var SeatNo = Math.floor((Math.random() * 100) + 10);\n SeatNo = SeatNo + 'B';\n frmCheckin.lblGate.text = GateNO;\n frmCheckin.lblSeat.text = SeatNo;\n frmCheckin.lblCheckinStatus.text = \"Ready to Board\";\n frmCheckin.show();\n break;\n }\n }\n }\n}",
"function wpi_update_status_box() {\r\n jQuery.post(ajaxurl, {\r\n action: 'wpi_get_status',\r\n invoice_id: jQuery('#wpi_invoice_id').val()\r\n }, function(data) {\r\n jQuery(\"#wpi_invoice_status_table\").html(data);\r\n if(is_recurring)\r\n jQuery(\".wpi_not_for_recurring\").hide();\r\n });\r\n}",
"function viewClosedTickets() {\n var upload_url = baseURL + nlapiResolveURL('suitelet', 'customscript_sl_edit_closed_ticket', 'customdeploy_sl_edit_closed_ticket');\n window.open(upload_url, \"_self\", \"height=750,width=650,modal=yes,alwaysRaised=yes\");\n}",
"function showActiveTicketsPopup() {\n showPopupWithResults({\n popupPaneId: \"activeTicketsPopup\",\n title: getResource(\"popup.activeTickets.title\"),\n url: \"/agent/panels/activeTicketsMainPanel.jsp\"\n });\n}",
"function buyTicket() {\n\t$(\"#dialog-not-implemented\").dialog({\n\t\tmodal : true,\n\t\tbuttons : {\n\t\t\tok : function() {\n\t\t\t\t$(this).dialog(\"close\");\n\t\t\t}\n\t\t}\n\t});\n}",
"function edit_question(question_id, category_id, max_score, active){\n // sets all the form values\n jQuery('#edit_criterion_category').val(category_id);\n jQuery('#edit_criterion_category').selectpicker('refresh');\n jQuery('#edit_criterion_max_score').val(max_score);\n jQuery('#edit_criterion_text').val(jQuery('#question-text-'+question_id).html());\n jQuery('#edit-criterion-form').attr('action', jQuery('#edit_question_action').val()+question_id);\n // check the switchery box\n if (active == '0'){\n jQuery('#edit_criterion_active').prop('checked', false);\n }\n if (active == '1'){\n jQuery('#edit_criterion_active').prop('checked', true);\n }\n // code to fire event to switch the switchery box\n el = document.querySelector('#edit_criterion_active');\n if (typeof Event === 'function' || !document.fireEvent) {\n var event = document.createEvent('HTMLEvents');\n event.initEvent('change', true, true);\n el.dispatchEvent(event);\n } else {\n el.fireEvent('onchange');\n }\n // open modal\n jQuery('#editQuestion').modal('show');\n}",
"function due_date_update() {\n $(\"#due_date_input_set, #due_date_input_hours, #due_date_input_days\").hide();\n switch (this.id) {\n case \"due_date_radio_set\":\n $(\"#due_date_input_set\").show();\n break;\n case \"due_date_radio_hours\":\n $(\"#due_date_input_hours\").show();\n break;\n case \"due_date_radio_days\":\n $(\"#due_date_input_days\").show();\n break;\n }\n }",
"function set_ticket_information() \n{\n RMPApplication.debug(\"begin set_ticket_information\");\n c_debug(dbug.information, \"=> set_ticket_information\");\n\n\tfor(i=0; i<wt_ol.length; i++) {\n\t\tif (wt_ol[i].task_sys_id == RMPApplication.get(\"ticket_number\")) {\n\t\t\tc_debug(dbug.information, \"=> set_ticket_information: wt_ol[\" + i + \"] = \", wt_ol[i]);\n\t\t\tRMPApplication.set(\"short_description\", wt_ol[i].task_short_description);\n\t\t\tRMPApplication.set(\"description\", wt_ol[i].task_description);\n\t\t\tvar opened_at_date_utc = moment(wt_ol[i].wo_opened_at, \"YYYY-MM-DD HH:mm:ss\").utc().format(\"DD/MM/YYYY HH:mm:ss\");\n\t\t\tRMPApplication.set(\"opened_at\", opened_at_date_utc);\n\t\t\tRMPApplication.set(\"diagnosis_description\", wt_ol[i].task_diagnosis_description);\n\t\t\tid_short_description.setVisible(true);\n\t\t\tid_description.setVisible(true);\n\t\t\tid_opened_at.setVisible(true);\n\t\t\tif (!isEmpty(wt_ol[i].task_diagnosis_description)) {\n\t\t\t\tid_diagnosis_description.setVisible(true);\n\t\t\t}\n\t\t\tid_ticket_information.setVisible(true);\n\t\t\tbreak;\n\t\t}\n\t}\t\n\n\tRMPApplication.debug(\"end set_ticket_information\");\n}",
"function UpdateForm(method_selected) {\n\tvar rows = $(\"table.entry tr\");\n\tif (method_selected == 'netchop') {\n\t\tvar netchop = rows.filter(\".netchop_form\").show();\n\t\t$(\".netctl_form\").hide();\n\t\t$(\".netctlpan_form\").hide();\n\t} else if (method_selected == 'netctl') {\n\t\tvar netctl = rows.filter(\".netctl_form\").show();\n\t\t$(\".netchop_form\").hide();\n\t\t$(\".netctlpan_form\").hide();\n\t} else {\n\t\tvar netctlpan = rows.filter(\".netctlpan_form\").show();\n\t\t$(\".netchop_form\").hide();\n\t\t$(\".netctl_form\").hide();\n\t\tUpdateAllele(\"human\", freq=true);\n\t}\n}",
"function tallyCheckboxes(qnNumber){\n\t\n\t// update hidden parameter FEEDBACK_QUESTION_SHOWRESPONSESTO\n\tvar checked = [];\n\t$('.answerCheckbox'+qnNumber+':checked').each(function () {\n checked.push($(this).val());\n });\n $(\"[name=\"+FEEDBACK_QUESTION_SHOWRESPONSESTO+\"]\").val(checked.toString());\n \n // update hidden parameter FEEDBACK_QUESTION_SHOWGIVERTO\n checked = [];\n $('.giverCheckbox'+qnNumber+\":checked\").each(function () {\n checked.push($(this).val());\n });\n $(\"[name=\"+FEEDBACK_QUESTION_SHOWGIVERTO+\"]\").val(checked.toString());\n \n // update hidden parameter FEEDBACK_QUESTION_SHOWRECIPIENTTO\n checked = [];\n $('.recipientCheckbox'+qnNumber+':checked').each(function () {\n checked.push($(this).val());\n });\n $(\"[name=\"+FEEDBACK_QUESTION_SHOWRECIPIENTTO+\"]\").val(checked.toString());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lookup table for btoa(), which converts a sixbit number into the corresponding ASCII character. | function btoaLookup(idx) {
if (idx < 26) {
return String.fromCharCode(idx + 'A'.charCodeAt(0));
}
if (idx < 52) {
return String.fromCharCode(idx - 26 + 'a'.charCodeAt(0));
}
if (idx < 62) {
return String.fromCharCode(idx - 52 + '0'.charCodeAt(0));
}
if (idx == 62) {
return '+';
}
if (idx == 63) {
return '/';
}
// Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.
} | [
"function btoaLookup(idx) {\n\t if (idx < 26) {\n\t return String.fromCharCode(idx + \"A\".charCodeAt(0));\n\t }\n\t if (idx < 52) {\n\t return String.fromCharCode(idx - 26 + \"a\".charCodeAt(0));\n\t }\n\t if (idx < 62) {\n\t return String.fromCharCode(idx - 52 + \"0\".charCodeAt(0));\n\t }\n\t if (idx === 62) {\n\t return \"+\";\n\t }\n\t if (idx === 63) {\n\t return \"/\";\n\t }\n\t // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.\n\t return undefined;\n\t}",
"function btoaLookup(idx) {\n\t if (idx < 26) {\n\t return String.fromCharCode(idx + 'A'.charCodeAt(0));\n\t }\n\t if (idx < 52) {\n\t return String.fromCharCode(idx - 26 + 'a'.charCodeAt(0));\n\t }\n\t if (idx < 62) {\n\t return String.fromCharCode(idx - 52 + '0'.charCodeAt(0));\n\t }\n\t if (idx == 62) {\n\t return '+';\n\t }\n\t if (idx == 63) {\n\t return '/';\n\t }\n\t // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.\n\t}",
"function btoaLookup(idx) {\n if (idx < 26) {\n return String.fromCharCode(idx + \"A\".charCodeAt(0));\n }\n if (idx < 52) {\n return String.fromCharCode(idx - 26 + \"a\".charCodeAt(0));\n }\n if (idx < 62) {\n return String.fromCharCode(idx - 52 + \"0\".charCodeAt(0));\n }\n if (idx == 62) {\n return \"+\";\n }\n if (idx == 63) {\n return \"/\";\n }\n // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.\n}",
"function btoaLookup(idx) {\n if (idx < 26) {\n return String.fromCharCode(idx + \"A\".charCodeAt(0));\n }\n if (idx < 52) {\n return String.fromCharCode(idx - 26 + \"a\".charCodeAt(0));\n }\n if (idx < 62) {\n return String.fromCharCode(idx - 52 + \"0\".charCodeAt(0));\n }\n if (idx === 62) {\n return \"+\";\n }\n if (idx === 63) {\n return \"/\";\n }\n // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.\n return undefined;\n}",
"function btoaLookup(idx) {\n if (idx < 26) {\n return String.fromCharCode(idx + \"A\".charCodeAt(0));\n }\n\n if (idx < 52) {\n return String.fromCharCode(idx - 26 + \"a\".charCodeAt(0));\n }\n\n if (idx < 62) {\n return String.fromCharCode(idx - 52 + \"0\".charCodeAt(0));\n }\n\n if (idx === 62) {\n return \"+\";\n }\n\n if (idx === 63) {\n return \"/\";\n } // Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests.\n\n\n return undefined;\n}",
"function atobLookup(chr){if(/[A-Z]/.test(chr)){return chr.charCodeAt(0)-'A'.charCodeAt(0);}if(/[a-z]/.test(chr)){return chr.charCodeAt(0)-'a'.charCodeAt(0)+26;}if(/[0-9]/.test(chr)){return chr.charCodeAt(0)-'0'.charCodeAt(0)+52;}if(chr=='+'){return 62;}if(chr=='/'){return 63;}// Throw exception; should not be hit in tests\n}",
"function atobLookup(chr) {\n if (/[A-Z]/.test(chr)) {\n return chr.charCodeAt(0) - \"A\".charCodeAt(0);\n }\n if (/[a-z]/.test(chr)) {\n return chr.charCodeAt(0) - \"a\".charCodeAt(0) + 26;\n }\n if (/[0-9]/.test(chr)) {\n return chr.charCodeAt(0) - \"0\".charCodeAt(0) + 52;\n }\n if (chr === \"+\") {\n return 62;\n }\n if (chr === \"/\") {\n return 63;\n }\n // Throw exception; should not be hit in tests\n}",
"function atobLookup(chr) {\n\t if (/[A-Z]/.test(chr)) {\n\t return chr.charCodeAt(0) - \"A\".charCodeAt(0);\n\t }\n\t if (/[a-z]/.test(chr)) {\n\t return chr.charCodeAt(0) - \"a\".charCodeAt(0) + 26;\n\t }\n\t if (/[0-9]/.test(chr)) {\n\t return chr.charCodeAt(0) - \"0\".charCodeAt(0) + 52;\n\t }\n\t if (chr === \"+\") {\n\t return 62;\n\t }\n\t if (chr === \"/\") {\n\t return 63;\n\t }\n\t // Throw exception; should not be hit in tests\n\t return undefined;\n\t}",
"function atobLookup(chr) {\n if (/[A-Z]/.test(chr)) {\n return chr.charCodeAt(0) - 'A'.charCodeAt(0);\n }\n if (/[a-z]/.test(chr)) {\n return chr.charCodeAt(0) - 'a'.charCodeAt(0) + 26;\n }\n if (/[0-9]/.test(chr)) {\n return chr.charCodeAt(0) - '0'.charCodeAt(0) + 52;\n }\n if (chr == '+') {\n return 62;\n }\n if (chr == '/') {\n return 63;\n }\n // Throw exception; should not be hit in tests\n}",
"function atobLookup(chr) {\n if (/[A-Z]/.test(chr)) {\n return chr.charCodeAt(0) - \"A\".charCodeAt(0);\n }\n if (/[a-z]/.test(chr)) {\n return chr.charCodeAt(0) - \"a\".charCodeAt(0) + 26;\n }\n if (/[0-9]/.test(chr)) {\n return chr.charCodeAt(0) - \"0\".charCodeAt(0) + 52;\n }\n if (chr == \"+\") {\n return 62;\n }\n if (chr == \"/\") {\n return 63;\n }\n // Throw exception; should not be hit in tests\n}",
"function atobLookup(chr) {\n if (/[A-Z]/.test(chr)) {\n return chr.charCodeAt(0) - \"A\".charCodeAt(0);\n }\n\n if (/[a-z]/.test(chr)) {\n return chr.charCodeAt(0) - \"a\".charCodeAt(0) + 26;\n }\n\n if (/[0-9]/.test(chr)) {\n return chr.charCodeAt(0) - \"0\".charCodeAt(0) + 52;\n }\n\n if (chr === \"+\") {\n return 62;\n }\n\n if (chr === \"/\") {\n return 63;\n } // Throw exception; should not be hit in tests\n\n\n return undefined;\n}",
"function hex_byte(num)\n{\n return hex_chr.charAt((num >> 4) & 0x0F) + hex_chr.charAt(num & 0x0F);\n}",
"function ctl(ch){return String.fromCharCode(ch.charCodeAt(0)-64);}",
"function chr(i) {\r\n return String.fromCharCode(i);\r\n}",
"function uniCharCode(a, b, c, d) {\n return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);\n}",
"function chr(n) {\n return String.fromCharCode(n);\n }",
"function encode_digit(d, flag) {\n return d + 22 + 75 * (d < 26) - ((flag !== 0) << 5);\n // 0..25 map to ASCII a..z or A..Z \n // 26..35 map to ASCII 0..9\n }",
"function chr(i) {\n return String.fromCharCode(i);\n}",
"function code2utf(code)\r\n{\r\n\tif (code < 128) return chr(code);\r\n\tif (code < 2048) return chr(192+(code>>6)) + chr(128+(code&63));\r\n\tif (code < 65536) return chr(224+(code>>12)) + chr(128+((code>>6)&63)) + chr(128+(code&63));\r\n\tif (code < 2097152) return chr(240+(code>>18)) + chr(128+((code>>12)&63)) + chr(128+((code>>6)&63)) + chr(128+(code&63));\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find an enemy tile adjcaent to fog with a minimum army value | static chooseEnemyTargetTileByLowestArmy(gameState, gameMap) {
let tilesWithFog = [];
//loop through all visible enemy tiles
for (let [key, value] of gameState.enemyTiles) {
if(gameMap.isAdjacentToFog(gameState, key)) {
tilesWithFog.push({"index": key, "value": value});
}
}
if(tilesWithFog.length == 0) {
return null;
}
//find one with lowest army value
return tilesWithFog.reduce((a, b) =>
(a.value < b.value) ? a : b
);
} | [
"function steeringBehaviourLowestCost(agent) {\r\n\r\n\t//Do nothing if the agent isn't moving\r\n\tif (agent.velocity.magnitude() == 0) {\r\n\t\treturn zeroVector;\r\n\t}\r\n\tvar floor = agent.floor(); //Coordinate of the top left square centre out of the 4\r\n\tvar x = floor.x;\r\n\tvar y = floor.y;\r\n\r\n\t//Find our 4 closest neighbours and get their distance value\r\n\tvar f00 = Number.MAX_VALUE;\r\n\tvar f01 = Number.MAX_VALUE;\r\n\tvar f10 = Number.MAX_VALUE;\r\n\tvar f11 = Number.MAX_VALUE;\r\n\r\n\tif (isValid(x, y)) {\r\n\t\tf00 = grid[x][y].distance;\r\n\t};\r\n\tif (isValid(x, y + 1)) {\r\n\t\tf01 = grid[x][y + 1].distance;\r\n\t}\r\n\tif (isValid(x + 1, y)) {\r\n\t\tf10 = grid[x +1][y].distance; \r\n\t}\r\n\tif (isValid(x + 1, y + 1)) {\r\n\t\tf11 = grid[x + 1][y + 1].distance;\r\n\t}\r\n\r\n\t//Find the position(s) of the lowest, there may be multiple\r\n\tvar minVal = Math.min(f00, f01, f10, f11);\r\n\tvar minCoord = [];\r\n\r\n\tif (f00 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(0, 0)));\r\n\t}\r\n\tif (f01 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(0, 1)));\r\n\t}\r\n\tif (f10 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(1, 0)));\r\n\t}\r\n\tif (f11 == minVal) {\r\n\t\tminCoord.push(floor.plus(new Vector(1, 1)));\r\n\t} \r\n\r\n\r\n\t//Tie-break by choosing the one we are most aligned with\r\n\tvar currentDirection = agent.velocity.norm();\r\n\tvar desiredDirection = zeroVector;\r\n\tminVal = Number.MAX_VALUE;\r\n\tfor (var i = 0; i < minCoord.length; i++) {\r\n\t\t//the direction to the coord from the agent\r\n\t\tvar directionTo = minCoord[i].minus(agent).norm();\r\n\t\t//the magnitude of difference from the current vector to direction of the coord from the agent\r\n\t\tvar magnitude = directionTo.minus(currentDirection).magnitude();\r\n\t\t//if it's the smallest magnitude, set it as the desiredDirection\r\n\t\tif (magnitude < minVal) {\r\n\t\t\tminVal = magnitude;\r\n\t\t\tdesiredDirection = directionTo;\r\n\t\t}\r\n\t}\r\n\r\n\t//Convert to a force\r\n\tvar force = desiredDirection.mul(agent.maxForce / agent.maxSpeed);\r\n\treturn force;\r\n}",
"function getClosestTarget(enemy){\n\n if(enemyGrids[enemy][playerPositions[0][0]][playerPositions[0][1]] < enemyGrids[enemy][playerPositions[1][0]][playerPositions[1][1]]){\n return 0;\n }\n else{\n return 1;\n }\n\n}//end getClosestTarget()",
"updateFogOfWar() {\n const fogOfWar = this.map.getFogOfWar();\n const tiles = fogOfWar.getMatrix();\n let cache = this.cache.fogOfWar;\n if (!cache) {\n cache = {};\n cache.color = '0x001A45';\n cache.mapWidth = tiles.length - 1;\n cache.mapHeight = tiles[0].length - 1;\n cache.tileWidthOnMinimap = MINIMIZED_WIDTH / cache.mapWidth;\n cache.tileHeightOnMinimap = MINIMIZED_HEIGHT / cache.mapHeight;\n this.cache.fogOfWar = cache;\n }\n for (let i = tiles.length - 1; i >= 0; i -= 1) {\n for (let j = tiles[i].length - 1; j >= 0; j -= 1) {\n if (tiles[j][i]) {\n const x = i / cache.mapWidth * MINIMIZED_WIDTH;\n const y = j / cache.mapHeight * MINIMIZED_HEIGHT;\n this.graphics.beginFill(cache.color);\n this.graphics.drawRect(\n x,\n y,\n cache.tileWidthOnMinimap,\n cache.tileHeightOnMinimap,\n );\n this.graphics.endFill();\n }\n }\n }\n }",
"FindClosestEnemy_(plane_position) {\n if (this.enemies_.length == 0) {\n return;\n }\n let min = 1000;\n let index = -1;\n for (let i = 0; i < this.enemies_.length; i++)\n if (this.enemies_[i].position.z < min)\n if (\n Math.abs(\n this.enemies_[i].position.x - plane_position.x\n ) < 0.25\n ) {\n min = this.enemies_[i].position.z;\n index = i;\n }\n if (index != -1) {\n this.SpawnEnemyBullet_(\n 0.01,\n -0.1,\n this.enemies_[index].position\n );\n }\n }",
"function closestPlayerXY(rm, enemy) {\nif (rooms[rm].players.numPlayers > 0) {\n var closestPlayer;\n var closestPlayerDistance = Infinity;\n for (var player in rooms[rm].players) {\n var distance = manhattanHeuristic([enemy.x, enemy.y], [player.x, player.y]);\n if (distance < closestPlayerDistance) {\n closestPlayer = player;\n closestPlayerDistance = distance;\n }\n }\n if (rooms[rm].players[closestPlayer] == undefined) {\n console.log(\"players[closestPlayer] is undefined. Ignoring\",\n \"moveEnemies() logic instead of letting program crash.\",\n \"Please check the logic.\");\n return;\n }\nreturn [closestPlayer.x, closestPlayer.y];\n}\n}",
"searchForTile() {\n let foundTile;\n let tempTiles = Array.from(this.tiles);\n for (let i = tempTiles.length - 1; i > 0; i--) {\n if (tempTiles[i].width > this.height) {\n break;\n } else {\n if (tempTiles[i].height > this.width) {\n break;\n }\n }\n foundTile = tempTiles[i];\n }\n if (foundTile) {\n this.eat(foundTile);\n }\n }",
"function illuminate(){\r\n\r\n if(gamestarted){\r\n\r\n lum = eval(\"props_room\" + player_location)[0][1]; // read luminance level from room properties\r\n\r\n // reset lighting for all tiles\r\n for(a = 0; a < tileArray.length; a ++){\r\n tileArray[a].alpha = lum / 8 ;\r\n }\r\n\r\n // gets statistics for player position\r\n if(!newapy){newapy = Math.ceil((player.y - speed) / tilesize); newapx = Math.ceil((player.x - speed) / tilesize)}\r\n c = tileArray.length;\r\n d = parseInt((newapy * htiles) + newapx);\r\n\r\n // illuminate tiles surrounding the player by increasing their alpha value\r\n if (typeof oldtime != 'undefined'){\r\n if(createjs.Ticker.getTime() - 100 > oldtime){ // every 100 ticks the alpha of the surrounding tiles is randomized\r\n r = Math.random() / 10;\r\n oldtime = createjs.Ticker.getTime();\r\n }\r\n } else {\r\n oldtime = createjs.Ticker.getTime();\r\n r = Math.random() / 10;\r\n }\r\n\r\n // some shorthand equations to save cpu time\r\n b1 = lum / 1.5 + r;\r\n b2 = lum / 2 + r;\r\n b3 = lum / 2.5 + r;\r\n\r\n b = d; if(b > 0 && b < c){tileArray[b].alpha = b1}\r\n b = d + 1; if(b > 0 && b < c && newapx < 19){tileArray[b].alpha = b1}\r\n b = d - 1; if(b > 0 && b < c && newapx > 0){tileArray[b].alpha = b1}\r\n b = d + htiles; if(b > 0 && b < c){tileArray[b].alpha = b1}\r\n b = d - htiles; if(b > 0 && b < c){tileArray[b].alpha = b1}\r\n b = d + (htiles + 1); if(b > 0 && b < c && newapx < 19){tileArray[b].alpha = b2}\r\n b = d - (htiles + 1); if(b > 0 && b < c && newapx > 0){tileArray[b].alpha = b2}\r\n b = d + (htiles - 1); if(b > 0 && b < c && newapx > 0){tileArray[b].alpha = b2}\r\n b = d - (htiles - 1); if(b > 0 && b < c && newapx < 19){tileArray[b].alpha = b2}\r\n b = d + 2; if(b > 0 && b < c && newapx < 18){tileArray[b].alpha = b3}\r\n b = d - 2; if(b > 0 && b < c && newapx > 1){tileArray[b].alpha = b3}\r\n b = d + (2 * htiles); if(b > 0 && b < c){tileArray[b].alpha = b3}\r\n b = d - (2 * htiles); if(b > 0 && b < c){tileArray[b].alpha = b3}\r\n\r\n stage.update();\r\n\r\n }\r\n}",
"function moveEnemy(){\r\n\r\n for(en = 0; en < enemyList.length; en ++){\r\n\r\n // for the cave levels, the enemies needed their alpha tweaked\r\n if(enemyList[en].id == 4){\r\n if(player.x > enemyList[en].x){xdiff = player.x - enemyList[en].x} else {xdiff = enemyList[en].x - player.x}\r\n if(player.y > enemyList[en].y){ydiff = player.y - enemyList[en].y} else {ydiff = enemyList[en].y - player.y}\r\n if(xdiff >= ydiff){diff = xdiff} else {diff = ydiff}\r\n enemyList[en].alpha = 0.5 - (parseInt(diff / tilesize) / 14);\r\n }\r\n\r\n // check to see if enemy is close enough to fight player\r\n /*\r\n schematically, it goes a little like this, but remember that some values need proper ceil/floor rounding before they'll work!\r\n (x == player.x && y == player.y) ||\r\n (x + 1 == player.x && y == player.y) ||\r\n (x - 1 == player.x && y == player.y) ||\r\n (x == player.x && y + 1 == player.y) ||\r\n (x == player.x && y - 1 == player.y)\r\n */\r\n\r\n if(\r\n ((parseInt(enemyList[en].x/tilesize) == newapx) && (parseInt(enemyList[en].y/tilesize) == newapy)) ||\r\n (((parseInt(Math.floor(enemyList[en].x/tilesize)) + 1) == newapx) && (parseInt(enemyList[en].y/tilesize) == newapy)) ||\r\n (((parseInt(Math.ceil(enemyList[en].x/tilesize)) - 1) == newapx) && (parseInt(enemyList[en].y/tilesize) == newapy)) ||\r\n ((parseInt(enemyList[en].x/tilesize) == newapx) && ((parseInt(Math.floor(enemyList[en].y/tilesize)) + 1) == newapy)) ||\r\n ((parseInt(enemyList[en].x/tilesize) == newapx) && ((parseInt(Math.ceil(enemyList[en].y/tilesize)) - 1) == newapy))\r\n ) {\r\n\r\n // able to hit player!\r\n\r\n // set rotation\r\n if(player.x < enemyList[en].x){enemyList[en].rotation = 270}\r\n if(player.x > enemyList[en].x){enemyList[en].rotation = 90}\r\n if(player.y < enemyList[en].y){enemyList[en].rotation = 0}\r\n if(player.y > enemyList[en].y){enemyList[en].rotation = 180}\r\n\r\n // playing fight animation\r\n if(enemyList[en].currentAnimation != \"fight\" && enemyList[en].currentAnimation != \"stance\" ){\r\n enemyList[en].gotoAndPlay(\"fight\");\r\n }\r\n if(enemyList[en].currentAnimation == \"fight\" && swordAnimActive == 0) {\r\n swordAnimActive = 1;\r\n }\r\n\r\n if(enemyList[en].currentAnimation == \"stance\" && swordAnimActive == 1) {\r\n swordAnimActive = 0;\r\n player_strength -= (enemyList[en].strength / 2);\r\n createjs.Sound.play(\"player-hit\");\r\n updateHealthCounter();\r\n }\r\n } else {\r\n\r\n // not able to hit player!\r\n\r\n // calculate movement\r\n enx = enemyList[en].x;\r\n eny = enemyList[en].y;\r\n\r\n //when moving y, make sure x is rounded off, and vice versa\r\n if(enemyList[en].y > player.y){roundedeny = Math.floor(enemyList[en].y / tilesize) * tilesize} else {roundedeny = Math.ceil(enemyList[en].y / tilesize) * tilesize}\r\n if(enemyList[en].x > player.x){roundedenx = Math.floor(enemyList[en].x / tilesize) * tilesize} else {roundedenx = Math.ceil(enemyList[en].x / tilesize) * tilesize}\r\n\r\n enemy_walkable_tiles = walkable_tiles[0];\r\n enemy_walkable_tiles.push(89); // make snow tile by default walkable for enemies\r\n\r\n // note: the direction of enemy's movement has to be rounded off to the max of that direction. this means floor if moving to left or top, ceil of moving down or right.\r\n if ( (player.x > enemyList[en].x) && (enemy_walkable_tiles.indexOf(curarray[parseInt(eny / tilesize)][Math.ceil((enx + enemyList[en].speed) / tilesize)],0) >= 0) ) { enemyList[en].x += enemyList[en].speed; enemyList[en].y = roundedeny; enemyList[en].rotation = 90; if(enemyList[en].currentAnimation != \"walk\"){enemyList[en].gotoAndPlay(\"walk\")}; if(player.x < enemyList[en].x){enemyList[en].x = player.x}}\r\n else if ( (player.x < enemyList[en].x) && (enemy_walkable_tiles.indexOf(curarray[parseInt(eny / tilesize)][Math.floor((enx - enemyList[en].speed) / tilesize)],0) >= 0) ) { enemyList[en].x -= enemyList[en].speed; enemyList[en].y = roundedeny; enemyList[en].rotation = 270; if(enemyList[en].currentAnimation != \"walk\"){enemyList[en].gotoAndPlay(\"walk\")}; if(player.x > enemyList[en].x){enemyList[en].x = player.x}}\r\n else if ( (player.y > enemyList[en].y) && (enemy_walkable_tiles.indexOf(curarray[Math.ceil((eny + enemyList[en].speed) / tilesize)][parseInt(enx / tilesize)],0) >= 0) ) { enemyList[en].y += enemyList[en].speed; enemyList[en].x = roundedenx; enemyList[en].rotation = 180; if(enemyList[en].currentAnimation != \"walk\"){enemyList[en].gotoAndPlay(\"walk\")}; if(player.y < enemyList[en].y){enemyList[en].y = player.y}}\r\n else if ( (player.y < enemyList[en].y) && (enemy_walkable_tiles.indexOf(curarray[Math.floor((eny - enemyList[en].speed) / tilesize)][parseInt(enx / tilesize)],0) >= 0) ) { enemyList[en].y -= enemyList[en].speed; enemyList[en].x = roundedenx; enemyList[en].rotation = 0; if(enemyList[en].currentAnimation != \"walk\"){enemyList[en].gotoAndPlay(\"walk\")}; if(player.y > enemyList[en].y){enemyList[en].y = player.y}}\r\n else { enemyList[en].gotoAndPlay(\"stand\"); }\r\n\r\n }\r\n }\r\n}",
"function find_tiles_w_that_vertice(vertice, sometiles) {\n nearby_tiles = [];\n nearby_edges_as_vectors = [];\n nearby_vert = [];\n var epsilon = 0.0001;\n var count = 0;\n edges_count = 0;\n\n // console.log('sometiles.length', sometiles.length);\n // console.log(vertice - sometiles[1].vert[1]);\n // console.log(sometiles[1].vert[1]);\n\n // console.log((vertice.x - sometiles[i].vert[j].x < epsilon));\n // console.log((vertice.y - sometiles[i].vert[j].y < epsilon));\n // (vertice.x - sometiles[i].vert[j].x <= epsilon)\n\n // (vertice.y - sometiles[i].vert[j].y <= epsilon)\n for (var i = 0; i < sometiles.length; i++) {\n //j -- vertex number\n for (var j = 0; j < 4; j++) {\n if ((Math.abs(vertice.x - sometiles[i].vert[j].x) <= epsilon) &&\n (Math.abs(vertice.y - sometiles[i].vert[j].y) <= epsilon)) {\n\n\n nearby_tiles[count] = sometiles[i];\n count++;\n\n if (j > 0) {\n nearby_edges_as_vectors.push(sometiles[i].edge[j].vec);\n // nearby_edges_as_vectors.push(sometiles[i].edge[j - 1].vec * (-1)); //not working\n nearby_edges_as_vectors.push(reverse_vec(sometiles[i].edge[j - 1].vec));\n\n edges_count += 2;\n }\n if (j === 0) {\n nearby_edges_as_vectors.push(sometiles[i].edge[0].vec);\n // nearby_edges_as_vectors.push(sometiles[i].edge[3].vec * (-1)); //not WORKING\n nearby_edges_as_vectors.push(reverse_vec(sometiles[i].edge[3].vec));\n\n edges_count += 2;\n }\n\n\n\n // console.log('.x -.x ', vertice.x - sometiles[i].vert[j].x);\n // console.log('.y - sometiles[i].vert[j].y ', vertice.y - sometiles[i].vert[j].y);\n // console.log('i ', i);\n // console.log('j ', j);\n // console.log('count', count);\n\n // break;\n\n }\n }\n }\n // for (var i = 0; i < sometiles.length; i++) {\n // for (var j = 0; j < 4; j++) {\n // if (vertice == sometiles[i].vert[j]) {\n // nearby[count] = sometiles[i];\n // count++;\n // }\n // }\n // }\n // console.log('count = ', count);\n // myCircle = new Path.Circle(vertice, 7);\n // myCircle.strokeColor = 'green';\n\n}",
"hit(enemy) {\n let d = dist(this.x, this.y, enemy.x, enemy.y)\n if (d < this.size / 2 + enemy.size / 2) {\n return true;\n } else {\n return false;\n }\n }",
"get shadowNearPlane() {}",
"function mapEdgeCollision(){\n if(((player.location.x + xval) <= 0) || ((player.location.x + xval) >= 400)){\n xval = 0;\n }\n if(((player.location.y + yval) >= 400) || ((player.location.y + yval) <= 0)){\n yval = 0;\n } \n }",
"updateEnemyOpacityForRangeAndObscurity(transport, targetHex) {\n // console.log('updateEnemyOpacityForRangeAndObscurity', transport);\n let player = this.player;\n let playerSightRange = player.sightRange;\n let currentOpacity = transport.imageGroup.opacity();\n let returnFieldOfViewHexes = this.gameboard.isFieldOfViewBlockedForHex(player.hex, targetHex/**, sortedByDistanceNeighbors**/);\n // console.log('returnFieldOfViewHexes', returnFieldOfViewHexes, player, player.sightRange, this.enemyToPlayerDistance);\n let playerSightBlocked = this.hexService.arrayOfHexesIncludesHex(returnFieldOfViewHexes.blocked, targetHex)\n if (currentOpacity > 0) { // allows for partial obscurity (like fog/eather)\n if (playerSightBlocked) {\n transport.imageGroup.to({opacity: 0});\n } else if (transport.playerDistance > playerSightRange) {\n // } else if (this.enemyToPlayerDistance > playerSightRange) {\n transport.imageGroup.to({opacity: 0});\n }\n } else if (transport.playerDistance <= playerSightRange) {\n // } else if (this.enemyToPlayerDistance <= playerSightRange) {\n if (!playerSightBlocked) {\n transport.imageGroup.to({opacity: 1});\n }\n }\n }",
"findFloorNear(targetPos,targetRadiusSq=9,targetTop=-0.5,targetBottom=-2) {\n\n // scratch variables\n let meshPos = vec3.create()\n let bestPos = vec3.create()\n let bestY = 0\n\n // visit all candidate meshes\n meshMap.forEach(object => {\n\n let worldMesh = object.worldMesh\n\n // skip non horizontal features\n //if(worldMesh.alignment()) return\n\n // where is mesh center point in world coords?\n vec3.set(meshPos, worldMesh._center.x, worldMesh._center.y, worldMesh._center.z)\n vec3.transformMat4(meshPos,meshPos,worldMesh.modelMatrix)\n\n // a number expressing the distance below the target Y\n let distanceY = meshPos[1] - targetPos[1]\n\n // candidate mesh is vertically to high?\n if(distanceY > targetTop) return\n\n // candidate mesh is vertically too low?\n if(distanceY < targetBottom) return\n\n // how far is a rough mesh extent from target in 2d in distance squared?\n let distSq = (targetPos[0]-meshPos[0])*(targetPos[0]-meshPos[0])\n + (targetPos[2]-meshPos[2])*(targetPos[2]-meshPos[2])\n - worldMesh._extent[0] * worldMesh._extent[0]\n - worldMesh._extent[1] * worldMesh._extent[1]\n - targetRadiusSq;\n\n // is too far away to be of interest?\n if(distSq > 0) return\n\n // distanceY fails to be the lowest acceptable candidate?\n if(bestY < distanceY) return\n\n // remember lowest area so far\n bestY = distanceY\n vec3.set(bestPos,targetPos[0],meshPos[1],targetPos[2])\n\n })\n\n // found nothing\n if(!bestY) return false\n\n // get local coordinates floor elevation\n vec3.copy(targetPos,bestPos)\n\n return true\n }",
"function ClosestEnemy(arr) {\n var ind;\n var indEnemy=[];\n for(var i=0; i<arr.length;i++) {\n // cari indeks dari angka 1\n if(arr[i]==1) ind=i;\n // cari indeks dari tiap angka 2\n if(arr[i]==2) indEnemy.push(i);\n }\n var jarak=[];\n for(i=0;i<indEnemy.length;i++) {\n // hitung jarak indeks angka 1 dengan tiap angka 2\n jarak[i]=Math.abs(ind-indEnemy[i])\n }\n jarak.sort(function(a,b) {return a-b})\n // kembalikan jarak terdekat\n if(jarak[0]===undefined) return 0; else return jarak[0];\n}",
"getFogOpacity(minCount, minPosition) {\n let highestOpacity = 200;\n for (let fogInterval of this.fogTimes) {\n let start = fogInterval[0];\n let end = fogInterval[1];\n if (minCount > start && minCount < end) {\n return highestOpacity;\n } else if (minCount === start) {\n return highestOpacity * minPosition / this.framesPerMin;\n } else if (minCount === end) {\n return highestOpacity - (highestOpacity * minPosition / this.framesPerMin);\n }\n }\n return 0;\n }",
"function findNearby() {\n\n\tvar frog = getFrog();\n\t\n\tvar frogAnchor = new b2AABB( );\n\tfrogAnchor.lowerBound.Set( frog.GetPosition().x - 160 / \n\t\tWORLD_SCALE, \n\t\tfrog.GetPosition().y - 160 / WORLD_SCALE );\n\tfrogAnchor.upperBound.Set( frog.GetPosition().x + 160 / \n\t\tWORLD_SCALE, \n\t\tfrog.GetPosition().y + 160 / WORLD_SCALE );\n\n\t/**\n\t * This is called for each object within \"sight\" of the frog\n\t * @param {Fixture} fixture Fixture within the specified range\n\t * @return {Boolean} Always true\n\t */\n\tfunction frogCallback( fixture ) {\n\t\tvar type = fixture.GetBody( ).GetUserData().type;\n\t\tswitch (type) {\n\t \tcase 'fish':\n\t \t\tif (FROG_STATE === 'Roaming' || \n\t \t\t\tFROG_STATE === 'Looking for Shallow Water' || \n\t \t\t\tFROG_STATE === 'Avoiding Turtle') {\n\t\t \t\t\tif (Math.random() < .75) {\n\t\t\t \t\t\tupdateState('Avoiding Fish', 'frog');\n\t\t\t \t\t\tFISH_NUM = fixture.GetBody().GetUserData().num;\n\t\t\t \t\t}\n\t \t\t}\n\t \t\tbreak;\n\t \tcase 'turtle':\n\t \t\tif (FROG_STATE === 'Roaming' || \n\t \t\t\tFROG_STATE === 'Looking for Shallow Water') {\n\t\t \t\t\tif (Math.random() < .5) {\n\t\t\t \t\t\tupdateState('Avoiding Turtle', 'frog');\n\t\t\t \t\t}\n\t \t\t}\n\t \t\tbreak;\n\t \tcase 'rock':\n\t \t\tif (FROG_STATE === 'Roaming' && \n\t \t\t\t(FROG_LAST_STATE !== 'Sunning' || \n\t \t\t\t(FROG_LAST_STATE === 'Sunning' && \n\t \t\t\tFROG_STATE_CHG_TIME + 5000 < (new Date()).getTime())) \n\t \t\t\t&& (FROG_LAST_STATE !=='Looking for Shallow Water' \n\t \t\t\t|| (FROG_LAST_STATE === 'Looking for Shallow Water' \n\t \t\t\t&& FROG_STATE_CHG_TIME + 5000 < \n\t \t\t\t(new Date()).getTime()))) {\n\t\t \t\t\tupdateState('Looking for Shallow Water',\n\t\t \t\t\t\t'frog');\n\t\t \t\t\trockNearFrog = fixture.GetBody();\n\t \t\t}\n\t \t\tbreak;\n\t \tdefault:\n\t \t\t//nothing\n\t \t\tbreak;\n\t\t}\n\t\treturn true;\n\t}\n \t// query the world using above callback\n\tworld.QueryAABB( frogCallback, frogAnchor );\n \n\tvar turtle = getTurtle();\n \n\tvar turtleAnchor = new b2AABB( );\n\tturtleAnchor.lowerBound.Set( turtle.GetPosition().x - 160 / \n\tWORLD_SCALE, turtle.GetPosition().y - 160 / WORLD_SCALE );\n\tturtleAnchor.upperBound.Set( turtle.GetPosition().x + 160 / \n\t\tWORLD_SCALE, \n\t\tturtle.GetPosition().y + 160 / WORLD_SCALE );\n\t\n\t/**\n\t * This is called for each object within \"sight\" of the turtle\n\t * @param {Fixture} fixture Fixture within the specified range\n\t * @return {Boolean} Always true\n\t */\n\tfunction turtleCallback( fixture ) {\n\t\tvar type = fixture.GetBody( ).GetUserData().type;\n\t\tswitch (type) {\n\t \tcase 'fish':\n\t \t\tif (TURTLE_STATE === 'Roaming' || \n\t \t\t\tTURTLE_STATE === 'Playing' ) {\n\t \t\t\t\tupdateState('Hungry', 'turtle');\n\t \t\t\t\tFISH_NUM = fixture.GetBody().GetUserData().num;\n\t \t\t}\n\t \t\tbreak;\n\t \tcase 'frog':\n\t \t\tif (TURTLE_STATE === 'Roaming' ) {\n\t \t\t\tupdateState('Playing', 'turtle');\n\t \t\t}\n\t \t\tbreak;\n\t \tdefault:\n\t \t\t//nothing\n\t \t\tbreak;\n\t\t}\n\t\treturn true;\n\t}\n // check what is near the turtle\n world.QueryAABB( turtleCallback, turtleAnchor );\n}",
"function bestAttack(allHexesObj, artIntelplayerId, battleMatrix, minThresholdToAttack){\n const currentAttackMatrix = attackMatrixFunctions.attackMatrix(allHexesObj, artIntelplayerId)\n let bestWinProbability = minThresholdToAttack\n let nextAttack = []\n for (const myHex in currentAttackMatrix){\n currentAttackMatrix[myHex].forEach(enemyHex => {\n const winChance = winProbability(allHexesObj, battleMatrix, myHex, enemyHex)\n if (winChance >= bestWinProbability){\n bestWinProbability = winChance;\n nextAttack = [myHex,enemyHex, winChance]\n }\n })\n }\n if (nextAttack.length === 0) nextAttack = null\n return nextAttack\n}",
"findAttackTarget(creep) {\n\n let hostile = creep.pos.findClosestByPath(FIND_HOSTILE_CREEPS, {filter: (enemy) => !global.Friends[enemy.owner.username]}); \n if (!hostile) {\n hostile = creep.pos.findClosestByPath(FIND_HOSTILE_STRUCTURES, {filter: (enemy) => !global.Friends[enemy.owner.username]});\n }\n\n if (hostile){\n creep.memory.attackTarget = hostile.id;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an xkcd comic | function getXkcd (number, callback) {
var BASE_URL = 'https://xkcd.com/'
var url
if (number) {
url = BASE_URL + number + '/info.0.json'
} else {
url = BASE_URL + 'info.0.json'
}
var options = {
url: url,
json: true
}
request(options, (err, res, body) => {
if (res.statusCode === 200) {
console.log('retrieved XKCD comic', body.num, body.img)
var xkcd = {
num: body.num,
img: body.img,
title: body.title,
alt: body.alt
}
callback(xkcd)
} else if (err) {
console.log('error retrieveing XKCD comic', url)
callback()
}
})
} | [
"function retrieveComic(doc_id){\n var comic = DocumentApp.openById(doc_id).getBody().getText();\n return comic\n}",
"function srvConcGet(cntx) {\n\t\tvar dataRequest = {\n\t\t\tiden: cntx.form.get('conc').data\n\t\t};\n\t\tsetBase(dataRequest, cntx);\n\t\t\n\t\tvar d = $q.defer();\n\t\t\n\t\tvar output = srv.call(targetHost + 'service/angular/conc/get/', dataRequest);\n\t\toutput.then(function() {\n\t\t\tvar data = srv.getData();\n\t\t\tif (data.EXEC_RC === 'V') {\n\t\t\t\td.reject();\n\t\t\t} else {\n\t\t\t\tcntx.data.set('conc', data.OUTPUT['conc']);\n\t\t\t\td.resolve(data);\n\t\t\t}\n\t\t}, function() {\n\t\t\tvar status = srv.getData();\n\t\t\tsrv.frontNotify('FRNT-00001', 'Error de comunicaciones (' + status + ')');\n\t\t\td.reject();\n\t\t});\n\t\treturn d.promise;\n\t}",
"async get_comic( comic_num ) {\n let comic = {};\n\n if ( comic_num < 1 ) {\n return comic;\n }\n\n this.url = `server/apis/get-comic.php?number=${ comic_num }`;\n const response = await fetch( this.url, { headers: this.headers } );\n const res_obj = await response.json();\n\n if ( res_obj.success ) {\n comic = res_obj['comic'];\n }\n\n return comic;\n }",
"function cpx_getXCat(name) {\n\tif (copicXCatalog[name] === undefined) {\n\t\tcopicXCatalog[name] = new Object();\n\t\tcopicXCatalog[name].exclusions = new Array();\n\t\tcopicXCatalog[name].hasMarker = false;\n\t\tcopicXCatalog[name].hasRefill = false;\n\t}\n\treturn copicXCatalog[name];\n}",
"function getxkcd(numComics, callback) {\n var comicToSelect = Math.floor(Math.random() * numComics);\n request({ \n url: 'http://xkcd.com/' + comicToSelect + '/info.0.json',\n method: 'GET'\n }, function(error, response, body){\n if(error) {\n console.log(error);\n } else {\n var image = JSON.parse(body).img; \n callback(image);\n }\n });\n}",
"function Capicom()\n{\n this.error = 0;\n this.store = null;\n this.certificate = null;\n\n var instance = this;\n\n /**\n * Функция обработки ошибок.\n * @return false\n */\n function error(error)\n {\n if (!instance.error) {\n instance.error = true;\n alert(error);\n }\n return false;\n }\n\n /**\n * Инициализирует хранилище сертификатов\n * @return {Boolean}\n */\n function init()\n {\n if (!$.browser.msie) {\n throw 'Внимание! Для корректной работы системы требуется Internet Explorer версии не ниже 7.0. ' +\n 'Вы можете бесплатно установить последнюю версию Internet Explorer с сайта производителя. ' +\n '<a href=\"http://www.microsoft.com/rus/windows/internet-explorer/\" target=\"_blank\">Загрузить Internet Explorer</a>.';\n }\n\n // получаем хранилище CAPICOM.\n instance.store = new ActiveXObject(\"CAPICOM.Store\");\n\n // открываем персональное хранилище сертификатов.\n instance.store.Open(CAPICOM_CURRENT_USER_STORE, 'My', CAPICOM_STORE_OPEN_READ_ONLY);\n\n return true;\n }\n\n /**\n * Инициализатор\n */\n this.init = function()\n {\n try {\n init();\n } catch (e) {\n error(e);\n }\n };\n\n /**\n * Открывает окно выбора сертификата.\n */\n this.selectCertificate = function()\n {\n try {\n this.certificate = this.store.Certificates.Select('Выберите сертификат.', \"Выберите один из сертификатов\", false);\n\n return this.certificate;\n } catch(e) {\n error(e);\n }\n return false;\n };\n\n /**\n * Получает сертификаты из личного хранилища сертификатов на компьютере пользователя.\n */\n this.getCertificates = function()\n {\n if (this.store.Certificates.Count == 0) {\n throw 'Не найдено ни одного действующего сертификата для электронной цифровой подписи.';\n }\n\n try {\n var certificates = this.store.Certificates.Find(CAPICOM_CERTIFICATE_FIND_TIME_VALID);\n var result = [];\n for (var i = 1; i <= certificates.Count; i++) {\n result.push(certificates.Item(i));\n }\n return result;\n } catch (e) {\n error(e);\n }\n return false;\n };\n\n /**\n * Получает сертификат по его хешу.\n * @param {string} thumbprint\n */\n function _getCertificateByThumbprint(thumbprint)\n {\n var certificate = instance.store.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, thumbprint);\n\n console.log('get');\n console.log(certificate);\n\n if (certificate.Count > 0) {\n return certificate.Item(1);\n } else {\n throw 'Не найден сертификат пользователя';\n }\n }\n\n /**\n *\n * @param data\n * @param certificateThumbprint\n * @param time\n * @return {*}\n *\n * @private\n */\n function _sign(data, certificateThumbprint, time)\n {\n if (!data) throw 'data is not set';\n if (!certificateThumbprint) throw 'certificateThumbprint is not set';\n\n var today = new Date(time),\n\n SignedData = new ActiveXObject(\"CAPICOM.SignedData\"),\n Signer = new ActiveXObject(\"CAPICOM.Signer\"),\n TimeAttribute = new ActiveXObject(\"CAPICOM.Attribute\");\n\n var certificate = _getCertificateByThumbprint(certificateThumbprint);\n\n console.log('sign');\n console.log(certificate);\n\n SignedData.Content = data;\n Signer.Certificate = certificate;\n\n TimeAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME;\n TimeAttribute.Value = today.getVarDate();\n\n Signer.AuthenticatedAttributes.Add(TimeAttribute);\n\n\n return SignedData.Sign(Signer, true, CAPICOM_ENCODE_BASE64);\n }\n\n /**\n * Подписы\n * @param time\n * @param data\n * @param certificateThumbprint\n */\n this.sign = function(data, certificateThumbprint, time)\n {\n try {\n return _sign(data, certificateThumbprint, time);\n } catch(e) {\n\n if (e.number) {\n switch (e.number) {\n case -2146827859:\n error('Ваш браузер не поддерживает работу с ActiveX объектами. Либо не установлен объект Capicom.');\n break;\n case CAPICOM_E_SIGNER_INVALID_USAGE:\n error('Сертификат не действителен для подписания.');\n break;\n default:\n error('Ошибка при подписании данных: ' + e.description);\n break;\n }\n } else {\n error(e);\n }\n }\n return false;\n };\n\n// this.checkSignCapicom = function(data, signedData, noSha1)\n// {\n// try {\n// var SignedData = new ActiveXObject(\"CAPICOM.SignedData\");\n// var certificate = null;\n// var infoText = {};\n// var date = null;\n//\n// if (noSha1) {\n// data = sha1(data);\n// }\n//\n// // устанавливаем контент для проверки подписи.\n// SignedData.Content = data;\n//\n// // проверяем подпись.\n// SignedData.Verify(signedData, true, CAPICOM_VERIFY_SIGNATURE_AND_CERTIFICATE);\n//\n// // если проверка прошла успешно, то выбираем из подписи сертификат, которым подписывались данные.\n// certificate = SignedData.Signers.Item(1).Certificate;\n//\n// // получаем данные сертификата.\n// certificateInfo = this.getCertificateInfo(certificate, false);\n//\n// date = new Date(certificateInfo['ValidToDate']);\n//\n// alertCapicom('<div style=\"margin-top: -85px;\">Проверка подписи прошла успешно.<br/><br/>' +\n// 'Владелец сертификата: ' + certificateInfo.user['name'] +'.<br>' +\n// 'Организация: ' + certificateInfo.user['organisation'] + '.<br/>' +\n// 'Сертификат выдан: ' + certificateInfo.user['certificateName'] + '.<br/>' +\n// 'Сертификат действителен до: ' + date.toLocaleDateString() + '</div>', 'Проверка подписи', 600, 250);\n// } catch (e) {\n// return this.errorHandler(e.description);\n// }\n// };\n\n init();\n\n return instance;\n}",
"function xcServiceDiscovery() {\n try {\n var iq = new JSJaCIQ();\n iq.setType('get');\n iq.appendNode(iq.buildNode('query', {xmlns: NS_DISCO_INFO}));\n con.send(iq, window.xcServiceDiscoverySet);\n } catch (e) {};\n}",
"async function xkcd_curr(){\n await common.getFromAPI(\"https://xkcd.com/info.0.json\", downloader);\n}",
"function getIcd(qid) { // doesn't seem to be used\n var a = $icd(qid);\n return (a && a.icd) ? a.icd : null;\n}",
"get cockpit() {\n\t\treturn this.tool.cockpit\n\t}",
"getLatestComic(setComic = true) {\n const requestUrl = `${this.corsProxy}/${this.xkcdApiUrl}/${this.xkcdApiUrlFormat}`\n fetch(requestUrl)\n .then(response => response.json())\n .then(data => {\n this.setLatestComicNumber(data.num)\n if(setComic == true){\n this.DomInterface.setComic(data)\n this.increaseCounter(data.num)\n this.setCurrentComicNumber(data.num)\n }\n })\n }",
"getComics() {\r\n return api.get('/comics')\r\n }",
"_get_comm_info() {\n return this._context.session.kernel.requestCommInfo({ target: this.comm_target_name }).then(reply => reply.content.comms);\n }",
"function str4class(c) {\r\n\tvar str = \"Unknown(\" + c + \")\";\r\n\tswitch(c) {\r\n\tcase PKCS11Object.CKO_DATA: str = \"CKO_DATA\"; break;\r\n\tcase PKCS11Object.CKO_CERTIFICATE: str = \"CKO_CERTIFICATE\"; break;\r\n\tcase PKCS11Object.CKO_PUBLIC_KEY: str = \"CKO_PUBLIC_KEY\"; break;\r\n\tcase PKCS11Object.CKO_PRIVATE_KEY: str = \"CKO_PRIVATE_KEY\"; break;\r\n\tcase PKCS11Object.CKO_SECRET_KEY: str = \"CKO_SECRET_KEY\"; break;\r\n\tcase PKCS11Object.CKO_HW_FEATURE: str = \"CKO_HW_FEATURE\"; break;\r\n\tcase PKCS11Object.CKO_DOMAIN_PARAMETERS: str = \"CKO_DOMAIN_PARAMETERS\"; break;\r\n\tcase PKCS11Object.CKO_MECHANISM: str = \"CKO_MECHANISM\"; break;\r\n\t}\r\n\treturn str;\r\n}",
"function _getSdk() {\n if (_comapiSDK) {\n return Promise.resolve(_comapiSDK);\n } else {\n return COMAPI.Foundation.initialise(comapiConfig)\n .then(function (result) {\n _comapiSDK = result;\n _subscribe();\n return _comapiSDK.startSession();\n })\n .then(function (result) {\n return _comapiSDK;\n });\n }\n }",
"async _get_comm_info() {\n const reply = await this._context.session.kernel.requestCommInfo({ target: this.comm_target_name });\n if (reply.content.status = 'ok') {\n return reply.content.comms;\n }\n else {\n return {};\n }\n }",
"function Comic(){}",
"function CIQ() {}",
"function srvCateGet(cntx) {\n\t\tvar dataRequest = {\n\t\t\tiden: cntx.form.get('cate').data\n\t\t};\n\t\tsetBase(dataRequest, cntx);\n\t\t\n\t\tvar d = $q.defer();\n\t\t\n\t\tvar output = srv.call(targetHost + 'service/angular/cate/get/', dataRequest);\n\t\toutput.then(function() {\n\t\t\tvar data = srv.getData();\n\t\t\tif (data.EXEC_RC === 'V') {\n\t\t\t\td.reject();\n\t\t\t} else {\n\t\t\t\tcntx.data.set('cate', data.OUTPUT['cate']);\n\t\t\t\td.resolve(data);\n\t\t\t}\n\t\t}, function() {\n\t\t\tvar status = srv.getData();\n\t\t\tsrv.frontNotify('FRNT-00001', 'Error de comunicaciones (' + status + ')');\n\t\t\td.reject();\n\t\t});\n\t\treturn d.promise;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs features necessary for a coverage track showing base composition for BAM reads Params features: a list of features from BAM records. currentRefSeq: a DASSequence object containing reference sequence. baseColors: an object mapping base to desired colors. Returns a list of features of type basecoverage. | function getBaseCoverage(features, currentRefSeq, baseColors) {
var minBin = null;
var maxBin = null;
var allBins = [];
// Populate BaseBins
for (var fi = 0; fi < features.length; ++fi) {
var f = features[fi];
if (f.groups && f.groups.length > 0) {
// Don't downsample complex features
return features;
}
var processedSeq = alignSeqUsingCigar(f.seq, f.quals, f.cigar);
var seq = processedSeq.seq;
var quals = processedSeq.quals;
var strand = f.orientation;
var minForFeature = f.min || 0;
var maxForFeature = f.max || 0;
var ind = 0;
for (var b = minForFeature; b <= maxForFeature; ++b) {
var bm = allBins[b];
if (!bm) {
bm = new BaseBin(b);
allBins[b] = bm;
}
var base = seq.charAt(ind);
var qual = quals.charCodeAt(ind) - 33; // Generate numeric qual score
bm.recordBase(base, qual, strand);
ind++;
}
if (!minBin) minBin = minForFeature;else minBin = Math.min(minBin, minForFeature);
if (!maxBin) maxBin = maxForFeature;else maxBin = Math.max(maxBin, maxForFeature);
}
// Generate coverage features
var refSeq = getRefSeq(currentRefSeq, minBin, maxBin);
var baseFeatures = [];
var ind = 0;
for (var b = minBin; b <= maxBin; ++b) {
var bm = allBins[b];
if (bm) {
var f = new DASFeature();
f.segment = features[0].segment;
f.min = bm.pos();
f.max = f.min;
f.notes = [];
f.notes = f.notes.concat(bm.infoList());
f.type = 'base-coverage';
f.suppressScore = true;
if (refSeq) {
var refBase = refSeq.charAt(ind);
var refString = 'Ref=' + refBase;
f.notes.unshift(refString);
var baseScoreList = bm.baseScoreList(refBase, 0.2);
// TODO: shift 0.2 threshold to a config parameter
for (var i = 0; i < baseScoreList.length; i++) {
var base = baseScoreList[i].base;
var score = baseScoreList[i].score;
var fBase = shallowCopy(f);
fBase.score = score;
// Color by baseColor when mismatch occurs
// otherwise, BoxGlyph to COLOR1 in style
if (baseScoreList.length > 1 || base != refBase) fBase.itemRgb = baseColors[base];
baseFeatures.push(fBase);
}
} else {
// No refSeq, only show coverage height.
baseFeatures.push(f);
}
}
ind++;
}
return baseFeatures;
} | [
"function getBaseCoverage(features, currentRefSeq, baseColors) {\n var minBin = null;\n var maxBin = null;\n\n var allBins = [];\n\n // Populate BaseBins\n for (var fi = 0; fi < features.length; ++fi) {\n var f = features[fi];\n if (f.groups && f.groups.length > 0) {\n // Don't downsample complex features\n return features;\n }\n var processedSeq = alignSeqUsingCigar(f.seq, f.quals, f.cigar);\n var seq = processedSeq.seq;\n var quals = processedSeq.quals;\n var strand = f.orientation;\n var minForFeature = f.min || 0;\n var maxForFeature = f.max || 0;\n var ind = 0;\n\n for (var b = minForFeature; b <= maxForFeature; ++b) {\n var bm = allBins[b];\n if (!bm) {\n bm = new BaseBin(b);\n allBins[b] = bm;\n }\n var base = seq.charAt(ind);\n var qual = quals.charCodeAt(ind) - 33; // Generate numeric qual score\n bm.recordBase(base, qual, strand);\n ind++;\n }\n\n if (!minBin)\n minBin = minForFeature;\n else\n minBin = Math.min(minBin, minForFeature);\n if (!maxBin)\n maxBin = maxForFeature;\n else\n maxBin = Math.max(maxBin, maxForFeature);\n }\n\n // Generate coverage features\n var refSeq = getRefSeq(currentRefSeq, minBin, maxBin);\n var baseFeatures = [];\n var ind = 0;\n for (var b = minBin; b <= maxBin; ++b) {\n var bm = allBins[b];\n if (bm) {\n var f = new DASFeature();\n f.segment = features[0].segment;\n f.min = bm.pos();\n f.max = f.min;\n f.notes = [];\n f.notes = f.notes.concat(bm.infoList());\n f.type = 'base-coverage';\n f.suppressScore = true;\n if (refSeq) {\n var refBase = refSeq.charAt(ind);\n var refString = 'Ref=' + refBase;\n f.notes.unshift(refString);\n var baseScoreList = bm.baseScoreList(refBase, 0.2);\n // TODO: shift 0.2 threshold to a config parameter\n for (var i = 0; i < baseScoreList.length; i++) {\n var base = baseScoreList[i].base;\n var score = baseScoreList[i].score;\n var fBase = shallowCopy(f);\n fBase.score = score;\n // Color by baseColor when mismatch occurs\n // otherwise, BoxGlyph to COLOR1 in style\n if (baseScoreList.length > 1 || base != refBase)\n fBase.itemRgb = baseColors[base];\n\n baseFeatures.push(fBase);\n }\n } else {\n // No refSeq, only show coverage height.\n baseFeatures.push(f);\n }\n }\n ind ++;\n }\n return baseFeatures;\n}",
"function useFeatures(defaultFeatures, isStatic, visualElement, controls, props, context, parentContext, shouldInheritVariant) {\n var plugins = Object(react__WEBPACK_IMPORTED_MODULE_5__[\"useContext\"])(MotionConfigContext);\n // If this is a static component, or we're rendering on the server, we don't load\n // any feature components\n if (isStatic || typeof window === \"undefined\")\n return null;\n var allFeatures = Object(tslib__WEBPACK_IMPORTED_MODULE_0__[/* __spread */ \"e\"])(defaultFeatures, plugins.features);\n var numFeatures = allFeatures.length;\n var features = [];\n // Decide which features we should render and add them to the returned array\n for (var i = 0; i < numFeatures; i++) {\n var _a = allFeatures[i], shouldRender = _a.shouldRender, key = _a.key, getComponent = _a.getComponent;\n if (shouldRender(props, parentContext)) {\n var Component = getComponent(props);\n Component &&\n features.push(Object(react__WEBPACK_IMPORTED_MODULE_5__[\"createElement\"])(Component, Object(tslib__WEBPACK_IMPORTED_MODULE_0__[/* __assign */ \"a\"])({ key: key }, props, { localContext: context, parentContext: parentContext, visualElement: visualElement, controls: controls, inherit: shouldInheritVariant })));\n }\n }\n return features;\n}",
"function get_features(refseqID) {\n\n\tvar myFeatures;\t\n\tglue.inMode(\"reference/\"+refseqID, function(){\n\t\tmyFeatures = glue.getTableColumn(glue.command([\"list\", \"feature-location\"]), \"feature.name\");\n\t});\n\treturn myFeatures;\n}",
"get features() {\r\n return new Features(this);\r\n }",
"get features() {\n\t\tconst getRawFeatures = (table) => {\n\t\t\tif (!table) return [];\n\t\t\treturn table.featureList.featureRecords.map(\n\t\t\t\t(record) => record.featureTag\n\t\t\t);\n\t\t};\n\n\t\tconst getFeatureIndex = (rawFeature) => {\n\t\t\tconst featureInitial = rawFeature.substring(0, 2);\n\t\t\tif (featureInitial == \"ss\" || featureInitial == \"cv\") {\n\t\t\t\treturn `${featureInitial}##`;\n\t\t\t} else {\n\t\t\t\treturn rawFeature;\n\t\t\t}\n\t\t};\n\n\t\tconst rawFeatures = new Set([\n\t\t\t...getRawFeatures(this._raw(\"GSUB\")),\n\t\t\t...getRawFeatures(this._raw(\"GPOS\")),\n\t\t]);\n\n\t\treturn [...rawFeatures].reduce((features, rawFeature) => {\n\t\t\tconst featureIndex = getFeatureIndex(rawFeature);\n\t\t\tconst feature = {\n\t\t\t\t...featureMapping.find((f) => f.tag == featureIndex),\n\t\t\t};\n\t\t\tif (feature) {\n\t\t\t\t// Restore original tag in case of enumerated tag (ss## or cv##)\n\t\t\t\tfeature.tag = rawFeature;\n\t\t\t\tfeatures.push(feature);\n\t\t\t}\n\t\t\treturn features;\n\t\t}, []);\n\t}",
"function get_features(refseqID) {\r\n\r\n\tvar myFeatures;\t\r\n\tglue.inMode(\"reference/\"+refseqID, function(){\r\n\t\tmyFeatures = glue.getTableColumn(glue.command([\"list\", \"feature-location\"]), \"feature.name\");\r\n\t});\r\n\treturn myFeatures;\r\n}",
"function useFeatures(defaultFeatures, isStatic, visualElement, props) {\n var plugins = useContext(MotionConfigContext);\n // If this is a static component, or we're rendering on the server, we don't load\n // any feature components\n if (isStatic || typeof window === \"undefined\")\n return null;\n var allFeatures = __spread(defaultFeatures, plugins.features);\n var numFeatures = allFeatures.length;\n var features = [];\n // Decide which features we should render and add them to the returned array\n for (var i = 0; i < numFeatures; i++) {\n var _a = allFeatures[i], shouldRender = _a.shouldRender, key = _a.key, getComponent = _a.getComponent;\n if (shouldRender(props)) {\n var Component = getComponent(props);\n Component &&\n features.push(createElement(Component, __assign({ key: key }, props, { visualElement: visualElement })));\n }\n }\n return features;\n}",
"function useFeatures(defaultFeatures, isStatic, visualElement, props) {\n var plugins = Object(react__WEBPACK_IMPORTED_MODULE_5__[\"useContext\"])(MotionConfigContext);\n // If this is a static component, or we're rendering on the server, we don't load\n // any feature components\n if (isStatic || typeof window === \"undefined\")\n return null;\n var allFeatures = Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__spread\"])(defaultFeatures, plugins.features);\n var numFeatures = allFeatures.length;\n var features = [];\n // Decide which features we should render and add them to the returned array\n for (var i = 0; i < numFeatures; i++) {\n var _a = allFeatures[i], shouldRender = _a.shouldRender, key = _a.key, getComponent = _a.getComponent;\n if (shouldRender(props)) {\n var Component = getComponent(props);\n Component &&\n features.push(Object(react__WEBPACK_IMPORTED_MODULE_5__[\"createElement\"])(Component, Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__assign\"])({ key: key }, props, { visualElement: visualElement })));\n }\n }\n return features;\n}",
"function findCfPolygons( features, mapBounds, cfBounds ){\n\tassert(features,\"findCfPolygons: features not found\");\n\tselected = [];\n\tvar cfBbox = boundsToTurfBbox(cfBounds);\n\tvar centerPt = turf.point([mapBounds.getCenter().lng, mapBounds.getCenter().lat]);\n\t// for each feature in the data\n\tturf.featureEach(features, function (currentFeature, featureIndex) {\n\t\tfBbox = featureToTurfBbox(currentFeature);\n\t\tis_intersect = turf.intersect(fBbox, cfBbox);\n\t\tif (is_intersect != null){\n\t\t\t// found object\n\t\t\tselected.push(currentFeature);\n\t\t}\n\t});\n\tconsole.info(\"Selected features: \"+selected.length);\n\treturn(selected);\n}",
"pickVectorFeatures(screenPosition) {\n var _a, _b;\n // Pick vector features\n const vectorFeatures = [];\n const pickedList = this.scene.drillPick(screenPosition);\n for (let i = 0; i < pickedList.length; ++i) {\n const picked = pickedList[i];\n let id = picked.id;\n if (id &&\n id.entityCollection &&\n id.entityCollection.owner &&\n id.entityCollection.owner.name === GlobeOrMap._featureHighlightName) {\n continue;\n }\n if (!defined(id) && defined(picked.primitive)) {\n id = picked.primitive.id;\n }\n // Try to find catalogItem for picked feature, and use catalogItem.getFeaturesFromPickResult() if it exists - this is used by FeatureInfoMixin\n const catalogItem = (_b = (_a = picked === null || picked === void 0 ? void 0 : picked.primitive) === null || _a === void 0 ? void 0 : _a._catalogItem) !== null && _b !== void 0 ? _b : id === null || id === void 0 ? void 0 : id._catalogItem;\n if (typeof (catalogItem === null || catalogItem === void 0 ? void 0 : catalogItem.getFeaturesFromPickResult) === \"function\") {\n const result = catalogItem.getFeaturesFromPickResult.bind(catalogItem)(screenPosition, picked);\n if (result) {\n if (Array.isArray(result)) {\n vectorFeatures.push(...result);\n }\n else {\n vectorFeatures.push(result);\n }\n }\n }\n else if (id instanceof Entity && vectorFeatures.indexOf(id) === -1) {\n const feature = Feature.fromEntityCollectionOrEntity(id);\n if (picked.primitive) {\n feature.cesiumPrimitive = picked.primitive;\n }\n vectorFeatures.push(feature);\n }\n }\n return vectorFeatures;\n }",
"extractClassesAndFeatures(features) {\n let newClasses = {};\n\n features.forEach((feature) => {\n // Check if feature has a class, otherwise set it to unassigned\n if (!feature.values_.name) {\n feature.setProperties({\n 'name': this.unassigned\n });\n }\n\n // Check if feature has an id, otherwise set one\n if(!feature.getId()) {\n feature.setId(RandomGenerator.getRandomId());\n }\n\n // If class doesn't exist, add it to the list of classes\n if (!Object.keys(newClasses).includes(feature.values_.name)) {\n\n // Get color of feature or create random\n const featureColor = feature.values_.color ? feature.values_.color : RandomGenerator.getRandomColor();\n newClasses[feature.values_.name] = {color: featureColor, features : []};\n }\n\n newClasses[feature.values_.name].features.push(feature);\n });\n\n return newClasses;\n }",
"function findCfPoints( features, mapBounds, cfBounds ){\n\tselected = [];\n\tvar cfBbox = boundsToTurfBbox(cfBounds);\n\tvar mapBbox = boundsToTurfBbox(mapBounds);\n\tvar centerPt = turf.point([mapBounds.getCenter().lng, mapBounds.getCenter().lat]);\n\t// for each feature in the data\n\tturf.featureEach(features, function (currentFeature, featureIndex) {\n\t\t//fBbox = featureToTurfBbox(currentFeature);\n\t\tis_in_context_frame = turf.booleanPointInPolygon(currentFeature.geometry, cfBbox);\n\t\tif (is_in_context_frame){\n\t\t\tis_in_map = turf.booleanPointInPolygon(currentFeature.geometry, mapBbox);\n\t\t\tif (!is_in_map){\n\t\t\t\tselected.push(currentFeature);\n\t\t\t}\n\t\t}\n\t});\n\tconsole.info(\"Selected features: \"+selected.length);\n\treturn(selected);\n}",
"function ObjectFeatures() {\n _super.call(this, \"Features\");\n }",
"function completeCurrent (objects, baseobj, polygons, vectors, options) {\n if (baseobj instanceof CSG.Path2D) {\n // console.log('##### completing Path2D')\n objects.push(new CSG.Path2D(vectors, baseobj.closed))\n }\n if (baseobj instanceof CSG) {\n // console.log('##### completing CSG')\n objects.push(CSG.fromPolygons(polygons))\n }\n return null\n}",
"function process_refseqs() {\n\n\t// Get a list of all the distinct sources for reference sequences\n\tvar source_names = get_refseq_sources();\n\n\t// Process reference sequences in each source\n\tvar featureSummary = {};\n\tfor(var i = 0; i < source_names.length; i++) {\n\n\t\tvar sourceName = source_names[i];\n\t\tglue.logInfo(\"Processing source: \"+sourceName);\n\n\t\t// Get the names (IDs) of all references in this source\t\n\t\tvar refseq_ids = get_refseq_ids(sourceName);\t\n\n\t\t// Iterate through the list of references\n\t\tfor(var j = 0; j < refseq_ids.length; j++) {\n\n\t\t\tvar refseqID = refseq_ids[j];\n\t\t\tglue.logInfo(\"Processing source \"+sourceName+\", Reference: \"+refseqID);\t\t\n\n\t\t\t// Get a list of the features in this reference sequence\n\t\t\tvar myFeatures = get_features(refseqID);\t\t\t\t\n\n\t\t\t// Iterate through the list of features\n\t\t\tfor(var k = 0; k < myFeatures.length; k++) {\n\t\t\n\t\t\t\tvar featureID = myFeatures[k];\t\t\n\t\t\t\tprocess_feature(featureSummary, refseqID, featureID);\n\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Write ORFs as NT and AA fasta\n\twrite_feature_fasta(Rep_fasta_aa, Cap_fasta_aa)\n}",
"function useFeatures(props, visualElement, preloadedFeatures) {\n\t var features = [];\n\t var lazyContext = react.useContext(LazyContext);\n\t if (!visualElement)\n\t return null;\n\t /**\n\t * If we're in development mode, check to make sure we're not rendering a motion component\n\t * as a child of LazyMotion, as this will break the file-size benefits of using it.\n\t */\n\t if (process.env.NODE_ENV !== \"production\" &&\n\t preloadedFeatures &&\n\t lazyContext.strict) {\n\t invariant(false, \"You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead.\");\n\t }\n\t for (var i = 0; i < numFeatures; i++) {\n\t var name_1 = featureNames[i];\n\t var _a = featureDefinitions[name_1], isEnabled = _a.isEnabled, Component = _a.Component;\n\t /**\n\t * It might be possible in the future to use this moment to\n\t * dynamically request functionality. In initial tests this\n\t * was producing a lot of duplication amongst bundles.\n\t */\n\t if (isEnabled(props) && Component) {\n\t features.push(react.createElement(Component, __assign({ key: name_1 }, props, { visualElement: visualElement })));\n\t }\n\t }\n\t return features;\n\t}",
"function makeCar(features) {\n let car = new Car();\n\n const featureList = {\n powerwindows: false,\n powerLocks: false,\n ac: false\n }\n\n // If they specified some features then add them\n if (features && features.length) { \n // iterate over all the features and add them\n\n for (i = 0; i < features.length; i++) {\n // mark the feature in the featureList as a feature\n // that will be included. This way we only get one of\n // each feature.\n featureList[features[i]] = true; \n }\n\n // Now we add the features on in a specific order\n if (featureList.powerwindows) {\n car = new PowerWindowsDecorator(car);\n }\n if (featureList.powerlocks) {\n car = new PowerLocksDecorator(car);\n }\n if (featureList.ac) {\n car = new ACDecorator(car);\n }\n\n }\n return car;\n}",
"function formatFeatures(features){\r\n //first sort features by start\r\n features.sort(sortByProperty('start'));\r\n\r\n var line = 0;\r\n var fLine =[];\r\n var total = features.length;\r\n\r\n //get the max possible lines and push empty array\r\n for(a=0; a< total; a++){\r\n fLine.push([]);\r\n }\r\n\r\n if(total>0){\r\n if(total === 1){\r\n Line[0].push(features[0]);\r\n }\r\n else\r\n {\r\n //>1\r\n var rFeature = features[features.length - 1];\r\n fLine[line].push(rFeature);\r\n features.pop();\r\n\r\n while(true){\r\n if(features.length ===0){\r\n break;\r\n }\r\n\r\n features.sort(sortByProperty('start'));\r\n var tempArray = [];\r\n if(features.length ===1){\r\n if(line==0){\r\n if(features[0].end <= rFeature.start){\r\n fLine[0].push(features[0]);\r\n features.pop();\r\n }\r\n else{\r\n fLine[1].push(features[0]);\r\n features.pop();\r\n }\r\n }\r\n else{\r\n if(features[0].end <= rFeature.start){\r\n fLine[line].push(features[0]);\r\n }\r\n else{\r\n fLine[line+1].push(features[0]);\r\n }\r\n features.pop();\r\n }\r\n }\r\n\r\n if(features.length ===0){\r\n break;\r\n }\r\n\r\n var z = features.length;\r\n while(z--){\r\n var lFeature = features[z];\r\n if(lFeature.end <= rFeature.start){\r\n fLine[line].push(lFeature);\r\n rFeature = lFeature;\r\n features.pop();\r\n }\r\n else{\r\n tempArray.push(lFeature);\r\n rFeature = lFeature;\r\n features.pop();\r\n }\r\n }\r\n\r\n if(tempArray.length == 0){\r\n break;\r\n }else{\r\n line++;\r\n features = tempArray;\r\n features.sort(sortByProperty('start'));\r\n rFeature = features[features.length - 1];\r\n fLine[line].push(rFeature);\r\n features.pop();\r\n }\r\n }\r\n }\r\n }\r\n\r\n return fLine;\r\n }",
"get features(){\r\n\t\tvar that = this\r\n\t\treturn Object.keys(this)\r\n\t\t\t.filter(function(e){ \r\n\t\t\t\treturn e != 'features' \r\n\t\t\t\t\t&& that[e] instanceof Feature }) }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Vega sort parameters (tuple of field and order). | function sortParams(orderDef, fieldRefOption) {
return array(orderDef).reduce(function (s, orderChannelDef) {
var _a;
s.field.push(_vgField(orderChannelDef, fieldRefOption));
s.order.push((_a = orderChannelDef.sort) !== null && _a !== void 0 ? _a : 'ascending');
return s;
}, {
field: [],
order: []
});
} | [
"function common_sortParams(orderDef, fieldRefOption) {\n return vega_util_src_array(orderDef).reduce((s, orderChannelDef) => {\n var _a;\n s.field.push(channeldef_vgField(orderChannelDef, fieldRefOption));\n s.order.push((_a = orderChannelDef.sort, (_a !== null && _a !== void 0 ? _a : 'ascending')));\n return s;\n }, { field: [], order: [] });\n}",
"function sortParams(orderDef, fieldRefOption) {\n return Object(vega_util__WEBPACK_IMPORTED_MODULE_0__[\"array\"])(orderDef).reduce((s, orderChannelDef) => {\n var _a;\n s.field.push(Object(_channeldef__WEBPACK_IMPORTED_MODULE_1__[\"vgField\"])(orderChannelDef, fieldRefOption));\n s.order.push((_a = orderChannelDef.sort) !== null && _a !== void 0 ? _a : 'ascending');\n return s;\n }, { field: [], order: [] });\n}",
"function sortParams(orderDef, fieldRefOption) {\n return (0, _vegaUtil.array)(orderDef).reduce((s, orderChannelDef) => {\n s.field.push((0, _channeldef.vgField)(orderChannelDef, fieldRefOption));\n s.order.push(orderChannelDef.sort || 'ascending');\n return s;\n }, {\n field: [],\n order: []\n });\n}",
"function sortParams(orderDef, fieldRefOption) {\n return (Object(vega_util__WEBPACK_IMPORTED_MODULE_0__[\"isArray\"])(orderDef) ? orderDef : [orderDef]).reduce((s, orderChannelDef) => {\n s.field.push(Object(_fielddef__WEBPACK_IMPORTED_MODULE_2__[\"vgField\"])(orderChannelDef, fieldRefOption));\n s.order.push(orderChannelDef.sort || 'ascending');\n return s;\n }, { field: [], order: [] });\n}",
"function sortParams(orderDef, fieldRefOption) {\n return (isArray(orderDef) ? orderDef : [orderDef]).reduce(function (s, orderChannelDef) {\n s.field.push(vgField(orderChannelDef, fieldRefOption));\n s.order.push(orderChannelDef.sort || 'ascending');\n return s;\n }, { field: [], order: [] });\n }",
"function sortParams(orderDef, fieldRefOption) {\n return array(orderDef).reduce((s, orderChannelDef) => {\n s.field.push(vgField(orderChannelDef, fieldRefOption));\n s.order.push(orderChannelDef.sort || 'ascending');\n return s;\n }, { field: [], order: [] });\n }",
"getSortParameters() {\n const SorterInstance = new Sorter(this.entriesType);\n\n return SorterInstance.getSortParameters(this.appState);\n }",
"getSortParameters(state) {\n const entriesType = this.type;\n\n const sortParams = state[entriesType].sort;\n const storedSort = this.getStoredSort(entriesType);\n\n // If no order in state, check storage, then default\n let order = sortParams.order || (\n storedSort ? storedSort.order : this.getDefaultOrder()\n );\n\n // If no orderBy in state, check storage, then default\n let orderBy = sortParams.orderBy || (\n storedSort ? storedSort.orderBy : this.getDefaultOrderBy()\n );\n\n return {\n order: order,\n orderBy: orderBy\n };\n }",
"function getSortingParams(query) {\n if (!query) {\n return null;\n }\n var orders = query.getOrderBy();\n if (orders.length === 0) {\n return null;\n }\n var sort = [];\n var order;\n for (var i = 0; i < orders.length; i++) {\n order = orders[i];\n sort.push({\n n: order.getSelector(),\n o: order.getOrder(),\n l: !order.getOrder()\n });\n }\n return sort;\n }",
"function _getSortTuple() {\n var sort = $('#sort-results').val();\n if(sort == \"experience-low\") \n return ['Experience', 'asc'];\n if(sort == \"experience-high\") \n return ['Experience', 'desc'];\n if(sort == \"time-short\") \n return ['Duration', 'asc'];\n if(sort == \"time-long\") \n return ['Duration', 'asc'];\n if(sort == \"rating\")\n return ['Rating', 'asc'];\n else\n return '';\n}",
"function getSortingParams(sortCriterion) {\n let firstCriterion;\n let secondCriterion;\n let factor;\n\n if (sortCriterion === SortCriterions.COUNT) {\n // Sort by -count, then +label.\n firstCriterion = SortCriterions.COUNT;\n secondCriterion = SortCriterions.ALPHA;\n factor = 1;\n } else if (sortCriterion === SortCriterions.ALPHA) {\n // Sort by +label, then -count.\n firstCriterion = SortCriterions.ALPHA;\n secondCriterion = SortCriterions.COUNT;\n factor = -1;\n }\n\n return { firstCriterion, secondCriterion, factor };\n}",
"genSortAscendingByField(field) {\n return (a, b) => {\n const valA = a[field].toUpperCase()\n const valB = b[field].toUpperCase()\n let order = 0\n if (valA < valB) order = -1\n if (valA > valB) order = 1\n return order\n }\n }",
"#orderByFieldSort(fields) {\n\t\treturn (a, b) => fields.map(c => {\n\t\t\tlet dir = 1\n\t\t\tif (c[1] === 'desc') dir = -1\n\t\t\tlet field = c[0]\n\t\t\t// if (c[0] === '-') { dir = -1; field=c.substring(1); } else field=c\n\t\t\t// return x > y ? 1 : x < y ? -1 : 0\n\t\t\treturn a[field] > b[field] ? dir : a[field] < b[field] ? -(dir) : 0\n\t\t}).reduce((p, n) => p ? p : n, 0)\n\t}",
"function generateSortingParameterFromDropdowns() {\n\tvar sortOrders = getSortingParameter();\n\n\t// map through the array to generate the list of params\n\tvar orderedDisplayFields = $([1, 2, 3]).map(function() {\n\t\tvar el = \"sort_by_\" + this;\n\n\t\tvar selected = $(\"#\" + el + \" option:selected\").val();\n\n\t\t// ignore the \"SELECT COLUMN\" option\n\t\tif (selected > -1) {\n\t\t\tvar order = $(\"[name=\" + el + \"_dir]:checked\").val();\n\n\t\t\t// if there isn't already a sort direction selected, choose ASC\n\t\t\tif (!order) {\n\t\t\t\t$(\"#\" + el + \"_dir_asc\").attr('checked', true);\n\t\t\t}\n\n\t\t\treturn selected + \":\" + (order ? order : \"asc\");\n\t\t}\n\t});\n\n\t// jQuery returns an object from $.map; $.makeArray fixes it.\n\tsortOrders.val($.makeArray(orderedDisplayFields));\n}",
"buildSortParams(sorts) {\n let sortString = '';\n\n for (const prop in sorts) {\n if (sorts[prop]) {\n sortString += sorts[prop] === 'desc' ? `-${prop}` : prop;\n sortString += ',';\n }\n }\n\n sortString = sortString.substr(0, sortString.length - 1);\n\n return sortString;\n }",
"prepareSequelizeSort (locals) {\n // Prepare sorting object for MySQL\n var listOrder = [];\n if (locals.sorting.field && locals.sorting.order) {\n var order = ['asc', 'desc'].indexOf(locals.sorting.order) > -1 ? locals.sorting.order : 'asc';\n listOrder = [locals.sorting.field, order];\n }\n\n return listOrder.length === 0 ? [['id', 'desc']] : [listOrder];\n }",
"formatSortParams(list) {\n var str = '';\n var len = list.length;\n for (ctr = 0; ctr < len; ctr++) {\n var item = list[ctr];\n str += `${item.dir}(${item.column})`;\n if (ctr < len-1) {\n str += ',';\n }\n }\n return str;\n }",
"function getSortParams(obj){\n var sortParams = [\n utils.getObjectSet(obj.resourceType)\n ];\n if(obj.sortField) {\n sortParams.push('BY');\n sortParams.push(utils.getSortField(\n obj.resourceType, obj.sortField));\n }\n\n for(var key in obj.fields) {\n var field = obj.fields[key];\n sortParams.push('GET');\n if (field.indexOf('@') < 0) {\n sortParams.push(utils.getSortField(\n obj.resourceType, field));\n }else{\n field = field.split(\"@\")[0];\n sortParams.push(utils.getSortField(\n obj.resourceType, field));\n }\n }\n for(var field in obj.query) {\n sortParams.push('GET');\n if (field.indexOf('@') < 0) {\n sortParams.push(utils.getSortField(\n obj.resourceType, field));\n }else{\n field = field.split(\"@\")[0];\n sortParams.push(utils.getSortField(\n obj.resourceType, field));\n }\n }\n\n if(obj.insertId) {\n // insert id at the end of each record, use to split query result\n sortParams.push('GET');\n sortParams.push(utils.getSortField(obj.resourceType, 'id'));\n sortParams.push('ALPHA');\n }\n if(obj.isDesc) {\n sortParams.push('DESC');\n }\n return sortParams;\n}",
"function getSortObj(req){\n var field = \"word\";\n if(req.query.sort === 'Vowels'){\n field = 'stats.vowels';\n } else if(req.query.sort === 'Consonants'){\n field = 'stats.consonants';\n } else if(req.query.sort === 'Length'){\n field = 'size';\n }else{\n field = req.query.sort.toLowerCase();\n }\n return [[field, req.query.direction]];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string describing `odesc`. | function operationMeaning (odesc) {
let msg
switch (odesc.type) {
case 'accountMerge':
return 'Merge account inside {destination}'
case 'allowTrust':
if (odesc.authorize) {
return 'Allow usage of your asset {assetCode} to {trustor}'
} else {
return 'Deny usage of your asset {assetCode} to {trustor}'
}
case 'bumpSequence':
return 'Set account sequence number to {bumpTo}'
case 'changeTrust':
if (odesc.limit === '0') {
return 'Refuse asset {asset}'
} else if (odesc.limit) {
return 'Set holding limit as {limit} for asset {asset}'
} else {
return 'Accept asset {asset}'
}
case 'createAccount':
return 'Create account {destination} and send it {startingBalance} XLM'
case 'createPassiveOffer':
return 'Passive offer of {amount} {selling} at {price} {buying} / unit'
case 'inflation':
return 'Run inflation'
case 'manageData':
if (odesc.value) {
return "Set data entry '{name}' as '{value}'"
} else {
return "Delete data entry '{name}'"
}
case 'manageOffer':
if (!odesc.offerId || odesc.offerId === '0') {
return 'Offer {amount} {selling} at {price} {buying} / unit'
} else if (odesc.amount !== '0') {
return "Change offer '{offerId}' to: offer {amount} {selling} at " +
'{price} {buying} / unit'
} else {
return "Delete offer '{offerId}'"
}
case 'pathPayment':
msg = 'Send {destAmount} {destAsset} to {destination} for a maximum ' +
'of {sendMax} {sendAsset}'
if (odesc.path) msg += ' using conversion path: {path}'
return msg
case 'payment':
return 'Send {amount} {asset} to {destination}'
case 'setOptions':
msg = ''
if (odesc.inflationDest) {
msg += 'Set inflation destination to: {inflationDest}{newline}'
}
if (odesc.clearFlags) msg += 'Clear flag(s): {clearFlags}{newline}'
if (odesc.setFlags) msg += 'Set flag(s): {setFlags}{newline}'
if (odesc.masterWeight) {
if (odesc.masterWeight === '0') {
msg += 'Delete master key{newline}'
} else {
msg += 'Set master key weight at: {masterWeight}{newline}'
}
}
['lowThreshold', 'medThreshold', 'highThreshold'].forEach(field => {
if (odesc[field]) msg += 'Set ' + field + ' at: {' + field + '}{newline}'
})
if (odesc.signer) {
if (odesc.signer.type === 'tx') {
if (odesc.signer.weight === '0') msg += 'Remove pre-signed {signer}{newline}'
else msg += 'Pre-sign {signer}{newline}'
} else {
if (odesc.signer.weight === '0') msg += 'Remove signer: {signer}{newline}'
else msg += 'Set signer: {signer}{newline}'
}
}
if (odesc.homeDomain) msg += 'Set home domain: {homeDomain}{newline}'
if (odesc.homeDomain === '') msg += 'Unset home domain'
if (!msg) msg = 'Do nothing'
return msg
default:
throw new Error('Unknow operation: ' + odesc.type)
}
} | [
"function getDescription(){\n\t\tvar str = \"Draw Tool\";\n\n\t\treturn str;\n\t}",
"function calcolaStringaSoggetto(sog) {\n var res = sog.codiceSoggetto || \"\";\n res = sog.denominazione ? res + \" - \" + sog.denominazione : res;\n res = sog.codiceFiscale ? res + \" - CF: \" + sog.codiceFiscale : res;\n res = sog.partitaIva ? res + \" - P.IVA: \" + sog.partitaIva : res;\n return res;\n }",
"toStringGeneralLatex() {\n\t\tlet cuadraticTerms = \"x^{2}+\" + this.C +\"x\";\n\t\tlet linearTerms = this.D + \"y\";\n\t\tif(this.h === 0){\n\t\t\tcuadraticTerms = \"x^{2}\";\n\t\t}\n\t\tif(this.orientation === \"right\" || this.orientation === \"left\"){\n\t\t\tcuadraticTerms.replace(/x/g, \"y\");\n\t\t\tlinearTerms = linearTerms.replace(\"y\", \"x\");\n\t\t}\n\t\treturn (cuadraticTerms + linearTerms + \"+\" + this.F + \"=0\").replace(/\\+\\-/g, \"-\");\n\t}",
"get description() {\n return this.sysInfo.dev_name;\n }",
"function __opString(op)\r\n{\r\n var opString = \"Executing - \";\r\n // We don't want to print out the parameters because then Schemer will record every test case because \r\n // the output we print out will be unique for each test case\r\n if(op != null)\r\n {\r\n if(op.indexOf(\"(\") != -1) // If it is a method, get the name\r\n {\r\n opString += (op.substring(0, op.indexOf(\"(\")));\r\n }\r\n else if((op.substring(0, 3) == \"obj\") && (op.indexOf(\" =\") != -1)) // If it is a property set, get the property name\r\n {\r\n opString += (op.substring(0, op.indexOf(\" =\")));\r\n }\r\n else // Just print\r\n {\r\n opString += (op);\r\n }\r\n }\r\n return opString;\r\n}",
"function showConstrOf(dataType){\r\n return dataType._dataConstructor;\r\n}",
"function emitDeclCode() {\n initMode = false\n return `#include \"sde.h\"\n\n// Model variables\n${declSection()}\n\n// Internal variables\n${internalVarsSection()}\n\n// Array dimensions\n${arrayDimensionsSection()}\n\n// Dimension mappings\n${dimensionMappingsSection()}\n\n`\n }",
"function describe(node, log=false) {\n let msg = core.getAttribute(node, 'name');\n msg += ' ' + core.getAttribute(node, 'direction');\n if (log) console.log(msg);\n return msg;\n }",
"function showOCLstr(strOfArr, parallel, show) {\r\n\r\n Soa = strOfArr;\r\n Soa = 1; //TODO: CAUTION. For OpenCL we cannot pass structs.\r\n ShowParallel = parallel;\r\n\r\n // If parallel code generation selected first we need to analyze.\r\n if (ShowParallel) {\r\n\r\n var mO = CurModObj; // TODO: Generalize for multiple modules.\r\n var fO = mO.allFuncs[getFuncIdByName(mO, \"Main\")];\r\n analyzeParallelismAll(fO, 0);\r\n \r\n }\r\n\r\n TypesAllFuncs = new Array();\r\n NamesAllFuncs = new Array();\r\n CL_Funcs = new Array(); // Save OpenCL code for .cl file.\r\n Func_code_ser = new Array(); // Contains SERIAL (for __device)\r\n CalledFuncsFromKernels = new Array();\r\n DeviceAuxPrototypes = new Array();\r\n\r\n var code = getOCLstr();\r\n if (show) {\r\n\r\n alert(code);\r\n\r\n } else {\r\n\r\n return code;\r\n\r\n }\r\n\r\n}",
"function getDescription(){\n\t\tvar str = \"Move Tool\";\n\n\t\treturn str;\n\t}",
"toStringOrdinaryLatex() {\n\t\tlet cuadraticTerms = \"(x-\" + this.h +\")^{2}\";\n\t\tlet nonCuadraticTerms = 4 * this.p + \"(y-\" + this.k + \")\";\n\t\tif(this.orientation === \"down\"){\n\t\t\tnonCuadraticTerms = \"-\" + nonCuadraticTerms;\n\t\t}else if(this.orientation === \"right\"){\n\t\t\tcuadraticTerms = cuadraticTerms.replace(\"x\", \"y\");\n\t\t\tnonCuadraticTerms = nonCuadraticTerms.replace(\"y\", \"x\");\n\t\t}else if(this.orientation === \"left\"){\n\t\t\tcuadraticTerms = cuadraticTerms.replace(\"x\", \"y\");\n\t\t\tnonCuadraticTerms = \"-\" + nonCuadraticTerms.replace(\"y\", \"x\");\n\t\t}\n\t\treturn (cuadraticTerms + \"=\" + nonCuadraticTerms).replace(/\\-\\-/g, \"+\").replace(/\\-\\+/g, \"-\");\n\t}",
"decrireArme() {\n const description = this.nom + \" fait \" + this.degat + \" points de dégâts\";\n return description;\n }",
"function getEICDFTooltip(self) {\n\n return [\n '<b> Cumulative Distribution </b>',\n '<b>Latitude: </b>' + self.x.toFixed(2),\n '<b>CDF: </b>' + self.point.y.toFixed(3)\n ].join(\"<br>\");\n\n}",
"function computeStringSoggetto(soggetto, classeSoggetto) {\n var res = '';\n if(soggetto && soggetto.uid) {\n res = soggetto.codiceSoggetto + ' - ' + soggetto.denominazione;\n if(soggetto.codiceFiscale) {\n res += ' - CF: ' + soggetto.codiceFiscale;\n }\n if(soggetto.partitaIva) {\n res += ' - P.IVA: ' + soggetto.partitaIva;\n }\n return res;\n }\n if(classeSoggetto) {\n res = 'Classe: ' + classeSoggetto.codice + ' - ' + classeSoggetto.descrizione;\n return res;\n }\n return res;\n }",
"function getOCLstr() {\r\n\r\n var mO = CurModObj;\r\n\r\n // First, generate code for all functions, including 'main()'\r\n // Will be elements of the func_code array.\r\n var func_code = new Array(); // Used to store code for EACH function.\r\n \r\n // Variable to store all include statements needed.\r\n var inclStmts = \"#include <stdio.h>\\n\" +\r\n\t \t \"#include <stdlib.h>\\n\" +\r\n\t\t \"#include <assert.h>\\n\";\r\n if (ShowParallel) {\r\n\r\n\tif (Device_type != DevT.FPGA) {\r\n\r\n inclStmts += \"#include <CL/cl.h>\\n\";\r\n\r\n\t} else {\r\n\r\n\t inclStmts += \"#include \\\"CL/opencl.h\\\"\\n\";\r\n\r\n\t}\r\n\r\n\tinclStmts += \"#include \\\"ocl_util.h\\\"\\n\";\r\n\r\n }\r\n\r\n TypeStr = \"\"; // Used to store TYPEs (i.e., structures).\r\n Func_prototypes = new Array();\r\n \r\n // A single string that contains all function code.\r\n var func_code_all = \"\";\r\n\r\n // TODO: Be careful with global variables. If not initialized every time, \r\n // they'll hold the value, until exiting program!\r\n GID_function = 0;\r\n\r\n for (var f = mO.FuncStartID; f < mO.allFuncs.length; f++) {\r\n\r\n\tvar func_code_tmp = getOCLstr4Func(mO, f);\r\n\tFunc_code_ser[f] = func_code_tmp[0].replace(/^.*?#pragma omp.*\\n?/mg, \r\n\t\t\t \"\");\r\n func_code[f] = func_code_tmp[1];\r\n \r\n\t// Note: Be careful where TypesAllFuncs starts != mO.allFuncs[start].\r\n\tfunc_code_all += TypesAllFuncs[f - mO.FuncStartID] + \" \" +\r\n\t\t \t func_code[f];\r\n\r\n }\r\n\r\n\r\n // Code generation generates memory allocations with clSVMAlloc().\r\n // For the FPGA case, where fine-grained system SVM is supported\r\n // we don't need clSVMAlloc(), but *aligned* regular memory allocation.\r\n // So, we substitute all instances accordingly.\r\n // Last, we need to substitute clSetKernelArgSVMPointer() to \r\n // clSetKernelArgSVMPointerAltera()\r\n if (Device_type == DevT.FPGA && DataTran == 0) {\r\n\r\n func_code_all = func_code_all.replace(/clSetKernelArgSVMPointer/g, \r\n\t\t\t\"clSetKernelArgSVMPointerAltera\");\r\n\r\n\t// Also, replace clSVMAlloc() with alignedMalloc()\r\n\t// clSVMAlloc(context, CL_MEM_READ_WRITE, <SIZE>, 0);\\n\r\n\t// alignedMalloc(<SIZE>);\\n\r\n\tfunc_code_all = func_code_all.replace(\r\n\t\t /clSVMAlloc\\(context, CL\\_MEM\\_READ\\_WRITE, (.+?), 0\\)/g,\r\n\t\t \"alignedMalloc($1)\");\r\n\r\n\t// Also, replace clSVMFree() with alignedFree().\r\n\tfunc_code_all = func_code_all.replace(\r\n\t\t\t/clSVMFree\\(context, (.+)\\)/g,\r\n\t\t\t\"alignedFree($1)\");\r\n\r\n }\r\n\r\n\r\n // Generate code for main method.\r\n var main_call = \"int main(int argc, char *argv[]) {\\n\";\r\n\r\n //TODO:C: Use startup arguments grid as *argv[]. Add more flexibility.\r\n var t_mainFunc = CurModObj.allFuncs[DefMainFuncInd];\r\n main_call += addIndentation(0) + \"char *\" +\r\n \t var2OCL(t_mainFunc.allGrids[1].caption)+\"[4];\\n\";\r\n\r\n main_call += addIndentation(0) + \"int \" +\r\n \t var2OCL(t_mainFunc.allGrids[0].caption) + \";\\n\";\r\n\r\n // If generating parallel implementation, setting nested parallelism off\r\n // by default.\r\n // TODO: This may be an option for the auto-tuner.\r\n // \t If no parallel step in program, no need.\r\n if (ShowParallel) {\r\n\t \r\n main_call += addIndentation(0) + \"setup_OCL_dev();\\n\";\r\n\r\n }\r\n\r\n if (DataTran == 0) {\r\n\r\n main_call += addIndentation(0) + \"index_data = (int *)clSVMAlloc(\" +\r\n\t \t \"context, CL_MEM_READ_WRITE, sizeof(int)*9, 0);\\n\";\r\n\r\n } else {\r\n\r\n main_call += addIndentation(0) + \"index_data = (int *)malloc(\" +\r\n\t \t \"sizeof(int)*9);\\n\";\r\n\r\n main_call += addIndentation(0) + \"index_data_dev = clCreateBuffer(\" +\r\n\t \t \"context, CL_MEM_READ_WRITE, \" +\r\n\t\t \"sizeof(int)*9, NULL, &error);\\n\";\r\n\r\n }\r\n\r\n // If device type is not FPGA (i.e., is CPU/GPU/MIC, then query the \r\n // device for degree of SVM_SUPPORT.\r\n // NOTE: We only support OpenCL on devices that support OpenCL 2.0\r\n if (Device_type != DevT.FPGA && DataTran == 0) {\r\n\r\n main_call += addIndentation(0) + \"SVM_Support = \" +\r\n\t\t \"checkSVMAvailability(dev_id);\\n\";\r\n\r\n \tmain_call += addIndentation(0) + \"if (SVM_Support==2) {\\n\" +\r\n\t\t addIndentation(1) + \"addNewAddress(index_data);\\n\" + \r\n\t\t addIndentation(0) + \"}\\n\";\r\n\r\n } else if (DataTran == 1) {\r\n\r\n\tmain_call += addIndentation(0) + \r\n\t\t \"addNewAddress(index_data, &index_data_dev);\\n\";\r\n\r\n } \r\n // Else, if FPGA, do nothing (any required changes are done cumulatively\r\n // at the end of code generation.\r\n\r\n main_call += addIndentation(0) +\r\n var2OCL(CurModObj.allFuncs[DefMainFuncInd].allGrids[0].caption) +\r\n \" = \" + var2OCL(DefMainFuncName) +\r\n \"(\" + \r\n\tvar2OCL(CurModObj.allFuncs[DefMainFuncInd].allGrids[1].caption) +\r\n \");\\n\";\r\n\r\n main_call += addIndentation(0) + \"finalize_OCL_dev();\\n\";\r\n\r\n if (DataTran == 0) {\r\n\r\n main_call += addIndentation(0) + \"clSVMFree(context, index_data);\\n}\\n\";\r\n\r\n } else {\r\n\r\n main_call += addIndentation(0) + \"free(index_data);\\n\";\r\n main_call += addIndentation(0) + \r\n\t\t \"clReleaseMemObject(index_data_dev);\\n}\\n\";\r\n\r\n }\r\n\r\n if (Device_type == DevT.FPGA) {\r\n\r\n\r\n\tmain_call = main_call.replace(\r\n\t\t /clSVMAlloc\\(context, CL\\_MEM\\_READ\\_WRITE, (.+?), 0\\)/g,\r\n\t\t \"alignedMalloc($1)\");\r\n\r\n\tmain_call = main_call.replace(\r\n\t\t\t/clSVMFree\\(context, (.+)\\)/g,\r\n\t\t\t\"alignedFree($1)\");\r\n\r\n }\r\n\r\n // Check if any math functions have been called in the program, so as to \r\n // add the math library in the include statements.\r\n if (InclMath) {\r\n \r\n inclStmts += \"#include <math.h>\\n\\n\";\r\n\r\n } else {\r\n \r\n \tinclStmts += \"\\n\";\r\n\r\n }\r\n\r\n // Construct function prototypes\r\n var func_protos = \"\";\r\n for (var i = mO.FuncStartID; i < mO.allFuncs.length; i++) {\r\n\r\n func_protos += TypesAllFuncs[i - mO.FuncStartID] + \" \" + \r\n\t\t Func_prototypes[i - mO.FuncStartID];\r\n\r\n\t//TODO: What about serial/parallel version if both abailable?\r\n\r\n }\r\n\r\n func_protos += \"\\n\\n\";\r\n \r\n // Final generated code will contain the TYPEs code, the library functions\r\n // code (e.g., for read/write CSV), the functions' code (that contains all\r\n // functions, including ft_Main), and the PROGRAM \"int main\" that calls\r\n // Main function and subsequently any other functions.\r\n var returnedCode = inclStmts + TypeStr + func_protos +\r\n\t func_code_all + \"\\n\" + main_call;\r\n\r\n returnedCode = returnedCode.replace(/UNIQUEIND/g, \"int\"); //TT\r\n\r\n return returnedCode;\r\n\r\n}",
"function getConfDIhtml() {\n\treturn `\n <!-- DI -->\n <div class=\"box-table\">\n <h2 class=\"title-center\">Confirmación inscripción (2da Parte)</h2>\n <div class=\"box-info\">\n <div><span class=\"subtitle-table\">Estudiantes</span></div>\n <div>\n <span class=\"bs\">${formatNumber.new(\n\t\t\t\t\t2.5 * getUCMes(4) * valorBCV,\n\t\t\t\t\t`Bs `,\n\t\t\t\t\ttrue\n\t\t\t\t)}</span> <br />\n \n <span class=\"usd\">${formatNumber.new(2.5 * getUCMes(4), `USD `, true)}</span>\n </div>\n </div>\n </div> \n `;\n}",
"static scientificName() {\n return 'Suricata suricatta';\n }",
"get sdsd() {\n\t\treturn this._sdsd;\n\t}",
"function formatOpenMetricsSensor(sensor) {\n let output = '';\n output += `#HELP ${sensor.name} ${sensor.description}\\n`;\n output += `#TYPE ${sensor.name} ${sensor.type}\\n`;\n output += `${sensor.name}{location=\"${sensor.source}\"} ${sensor.value}\\n`;\n return output;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a request to the server to add a new artifact to a project. This AJAX request has content type urlformencoded. | function onAddNewArtifactSubmit() {
let form = new FormData(this);
form.append('action', 'addArtifact');
api.post('/artifacts.php', form, true)
.then(res => {
snackbar(res.message, 'success');
onAddArtifactSuccess(
res.content.id,
form.get('name'),
form.get('description'),
form.get('artifactType'),
form.get('artifactLink')
);
})
.catch(err => {
snackbar(err.message, 'error');
});
return false;
} | [
"issueAddArtifact(artifact,op) {\n if (artifact && op) {\n var body = this.suppliedArtifact;\n body.nodeType = this.name;\n body.class = this.name;\n // copy in values from this.suppliedArtifact\n\n this.$.addGridArtifactAjaxId.method =\"post\";\n this.$.addGridArtifactAjaxId.body = body;\n this.$.addGridArtifactAjaxId.url = this.urlRoot;\n this.$.addGridArtifactAjaxId._go();\n }\n }",
"createProjectAJAX() {\n var project = {};\n project.nodeType = \"Project\";\n project.class = \"Project\";\n project.name = this.$.projectName.value;\n if (this.$.projectDescription.value) {\n project.description= this.$.projectDescription.value;\n }\n if (this.$.projectQualifiedName) {\n project.qualifiedName =this.$.projectQualifiedName.value;\n }\n\n this.$.addProjectAjaxId.method =\"post\";\n this.$.addProjectAjaxId.body = project;\n this.$.addProjectAjaxId.url = \"/api/subject-area/projects\";\n this.$.addProjectAjaxId._go();\n }",
"async function createArtifact (req, res) {\n res.json(await ArtifactService.createArtifact(req.files, req.params.submissionId, req.body))\n}",
"function checkAndAddProject() {\n var url = $('url').value;\n var projectName = $('projectName').value;\n disableAddProjectButtons(true);\n var vcIcon = $('url_icon');\n vcIcon.src = context_path(\"images/wait.gif\");\n new Ajax.Request(context_path('addProjectFromVersionControl.ajax'), {\n parameters: \"url=\" + url + \"&projectName=\" + projectName + \"&vcsType=\" + $('vcsType').value + \"&moduleName=\" + $('moduleName').value,\n asynchronous:1,\n method: 'GET',\n onComplete: function(transport) {\n\t \tvar json = transport.responseText\n\t\t json = json ? eval('(' + json + ')') : null\n ajax_update_icons_and_invoke_callback_function(json);\n }\n });\n}",
"function onDeleteArtifact() {\n let id = $(this).data('id');\n\n let body = new FormData();\n body.append('action', 'deleteArtifact');\n body.append('artifactId', id);\n body.append('projectId', $('#projectId').val());\n\n api.post('/artifacts.php', body, true)\n .then(res => {\n snackbar(res.message, 'success');\n $(`#${id}`).remove();\n })\n .catch(err => {\n snackbar(err.message, 'error');\n });\n}",
"function createNewProject() {\r\n\tvar requestData = '{'\r\n\t\t\t+ '\"command\" : \"createProject\",'\r\n\t\t\t+ '\"arguments\" : {'\r\n\t\t\t+ '\"project\" : \"' + $('#new-project-name').val() + '\"'\r\n\t\t\t+ '}'\r\n\t\t\t+ '}';\r\n\tmakeAsynchronousPostRequest(requestData, refresh, null);\t// Defined in \"/olive/scripts/master.js\".\r\n}",
"function addIssue() {\n\n//populating the data from form fields\n var data = {\n title: $('input[name=title]').val(),\n description: $('#description').val(),\n completionDate: $('input[name=completionDate]').val(),\n status: $('#status').chosen().val(),\n assigned: $('#assigned').chosen().val(),\n tracker: $('#tracker').chosen().val()\n };\n\n\n//ajax post\n $.ajax({\n\n type: \"POST\",\n url: \"/jit/app/issues/\" + getProjectName() + \"/add\",\n contentType: \"application/json\",\n dataType: 'json',\n data: JSON.stringify(data),\n beforeSend: function (xhr) {\n xhr.setRequestHeader(header, token);\n },\n success: function (data) {\n\n\n }\n });\n}",
"function submitProject() {\n\t$.ajax({\n\t\ttype: \"POST\",\n\t\turl: api(\"/project\"),\n\t\tdata: getProjectProperties(),\n\t\tcontentType: \"application/x-www-form-urlencoded\",\n\t\tsuccess: function(data) {\n\t\t\twatchForDownload(data)\n\t\t},\n\t\terror: function(jqXHR) {\n\t\t\thandleSubmissionError(jqXHR)\n\t\t}\n\t})\n}",
"function addButtonClick() {\n\tname = $('body > div.project form.project input.name').val();\n\tdescription = $('body > div.project form.project input.description').val();\n\taddProject(name, description);\n}",
"function addDeploymentArtifact(xmlAsDOM, xmlAsString) {\n\tvar da = xmlAsDOM.firstChild;\n\tvar daName = da.getAttribute(\"name\");\n\n\t// we do NOT extract artifactType / artifactTemplate from the XML, but use the user input\n\t// showDeploymentArtifactInformation will extract its data directly from the XML without querying some input at the other HTML elements\n\tvar daArtifactTemplateName = $(\"#artifactTemplateName\").val();\n\tvar daArtifactTypeName = $(\"#artifactType option:selected\").text();\n\n\t// add information to node template shape\n\tvar daData = {\n\t\tnodeTemplateId : currentlySelectedNodeTemplate,\n\t\tname : daName,\n\t\txml : xmlAsString,\n\t\tartifactTypeName: daArtifactTypeName\n\t};\n\tif (daArtifactTemplateName != \"\") {\n\t\tdaData.artifactTemplateName = daArtifactTemplateName;\n\t}\n\taddDeploymentArtifactInfoToNodeTemplate(daData);\n}",
"upload() {\n const result = this.grrArtifactDialogService_.openUploadArtifact();\n result.then(function resolve() {\n this.triggerUpdate();\n }.bind(this));\n }",
"addProject(newProject) {\n\t\tAxios.request({\n\t\t\tmethod: 'post',\n\t\t\turl: 'http://localhost:3000/api/Projects/',\n\t\t\tdata: newProject\n\t\t}).then(response => {\n\t\t\tthis.props.history.push('/'); // Redirect to homepage\n\t\t});\n\t}",
"function setupCreatePack() {\n\tconst form = document.forms['create-pack'];\n\tform.addEventListener('submit', function(e) {\n\t\te.preventDefault();\n\t\t// convert form data into query param string\n\t\tconst form = document.forms['create-pack'];\n\t\tconst body = new URLSearchParams(new FormData(form));\n\t\t// send body to create_pack.php\n\t\tUtil.postLog('ajax/create_pack.php', body)\n\t\t\t.then((json) => refreshPacks());\n\t});\n}",
"function submitNewMedia() {\n\n\ttype = $('input[name=\"newmedia\"]:checked').val();\n\tmedia = $('input[name=\"modal_result\"]:checked').val();\n\tlibrary_id = $('input[name=\"modal_library\"]:checked').val();\n\n\tif(media == undefined) {\n\t\tconsole.log('Error! No media in modal selected!');\n\t\tclose_modal();\n\t\treturn;\n\t}\n\n\tif(library_id == undefined) {\n\t\tconsole.log('Error! No library in modal selected! (Most likely no library for ' + type + ' on server)');\n\t\tclose_modal();\n\t\treturn;\n\t}\n\n\txhr = new XMLHttpRequest();\n\txhr.open(\"POST\", \"/new_media/\" + type + \"/\" + media + \"/\" + library_id , true);\n\txhr.send(null);\n\n\tclose_modal();\n}",
"issueUpdateArtifact(artifact,op) {\n if (artifact && op) {\n var body = artifact;\n body.nodeType = this.name;\n body.class = this.name;\n // copy in values from this.suppliedArtifact\n let guid = \"\";\n if (artifact.systemAttributes) {\n guid = artifact.systemAttributes.guid;\n }\n\n this.$.updateGridArtifactAjaxId.method =\"put\";\n this.$.updateGridArtifactAjaxId.body = body;\n this.$.updateGridArtifactAjaxId.url = this.urlRoot+\"/\"+guid;\n this.$.updateGridArtifactAjaxId._go();\n }\n }",
"function addProduct(e){\n\t// ajax stuff....\n\tdata = {\n\t\tname \t\t: $('#prodName').val(),\n\t\tdescription\t: $('#prodDesc').val(),\n\t\tprice \t\t: $('#prodPrice').val()\n\t}\n\trequest = $.post('/new', data);\n\trequest.done(responseHandler);\n\trequest.error(errorHandler)\n}",
"function uploader(payload){\n\t\t$.ajax({\n\t\t\ttype: 'POST',\n\t\t\turl: endPoint+'import/upload?context=default',\n\t\t\tcontentType: 'application/rdf+xml',\n\t\t\tdata: payload,\n\t\t\tsuccess: function(){\n\t\t\t\tconsole.log(\"Success\");\n\t\t\t}\n\n\t\t});\n\t}",
"function submitProject(Project) {\n $.post('/api/project/new', Project, function() {\n window.location.href = '/projects';\n });\n }",
"function createProject()\n{\n\tvar projectName, projectDescription;\n\n\t$(\"#projectStatus\").html(\"\");\n\ttok = getToken();\n\n\tprojectName = $(\"input#txtProjectName\").val();\n\t\n\t//alert(tok);\n\t//alert(projectName);\n\t\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: '/plm/rest/projectmanage/create',\n\t\tcontentType: 'application/json; charset=UTF-8',\n\t\taccepts: {\n\t\t\ttext: 'application/json'\n\t\t},\n\t\tdataType: 'json',\n\t\tdata: JSON.stringify({\n\t\t\ttoken: {\n\t\t\t\ttoken:tok\n\t\t\t},\n\t\t\tproject:{\n\t\t\t\tname: projectName \n\t\t\t},\n\t\t}),\n\t\tsuccess: function(data){\n\n\t\t\t// message\":\"Success\n\t\t\t if(data.message==\"Success\")\n\t\t\t {\n\t\t\t $(\"#projectStatus\").html(\"New Project has been created.\");\n\t\t\t document.getElementById(\"txtProjectName\").value=\"\";\n\t\t\t // redirect to project list\n\t\t\t //window.location=\"viewProjects.html\"; /*Redirect to the login page after succesful registration*/\n\t\t\t }\n\t\t\t else\n\t\t\t { /* Usually internal error or other */\n\t\t\t \t$(\"#projectStatus\").html(data.message);\n\t\t\t }\n\t\t},\n\t\terror: function(data){\n\t\t\talert(\"error\");\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws an array of SCRIB.Face_Info structures to the screen, using HTML5 Canvas2D. | function drawFaceInfoArray(G, face_info_array)
{
var len = face_info_array.length;
for(var i = 0; i < len; i++)
{
var face = face_info_array[i];
// Note: We could put the color attribute in face.face.faceData.color,
// But, I want to keep halfedge stuff out of my ScribbleJS user's mind...
// Instead they should interact directly with the Face_Info objects.
if (face.color === undefined)
{
face.color = G.randomColor();
}
var color = face.color;
// Highlight the face that the mouse is currently in.
/*
if(face.polyline.containsPoint(new BDS.Point(EX.mouse.x, EX.mouse.y)))
{
color = 0xffffff;
}
*/
// Draw Non-complemented faces.
if(!face.isComplemented())
{
G.fillColor(color);
G.drawPolygon(face.polyline);
}
}
} | [
"function drawFaceInfoArray(G, face_info_array)\n{\n\n var comp_faces = [];\n\n var len = face_info_array.length;\n for(var i = 0; i < len; i++)\n {\n var face = face_info_array[i];\n\n // Note: We could put the color attribute in face.face.faceData.color,\n // But, I want to keep halfedge stuff out of my ScribbleJS user's mind...\n // Instead they should interact directly with the Face_Info objects.\n if (face.color === undefined)\n {\n face.color = G.randomColor();\n }\n\n var color = face.color;\n\n // Highlight the face that the mouse is currently in.\n /*\n if(face.polyline.containsPoint(new BDS.Point(EX.mouse.x, EX.mouse.y)))\n {\n color = 0xffffff;\n }\n */\n\n // Draw Non-complemented faces.\n if(!face.isExterior())\n {\n G.fillColor(color);\n G.strokeColor(0x000000);\n G.drawPolygon(face.polyline);\n G.drawPolyline(face.polyline);\n }\n else\n {\n // Draw complemented faces later.\n comp_faces.push(face);\n }\n }\n\n while(comp_faces.length > 0)\n {\n face = comp_faces.pop();\n\n // Draw all of the complemented faces.\n G.strokeColor(0xffffff);\n G.drawPolyline(face.polyline);\n }\n}",
"function drawFaceInfoArray(G, face_info_array)\n{\n\n // For every face, convert it to a bezier face loop,\n // then stylishly draw it to the screen.\n var len = face_info_array.length;\n for(var i = 0; i < len; i++)\n {\n face = face_info_array[i];\n\n face_loop = face.toCurves();\n\n // Draw Non-complemented faces.\n if(!face.isComplemented())\n {\n // Black stroke, random fill.\n G.strokeColor(0xff000000);\n G.fillColor(G.randomColor());\n G.drawBezierLoop(face_loop, true, true);\n }\n else\n { \n // White Stroke, No Fill.\n G.strokeColor(0xffffffff);\n G.drawBezierLoop(face_loop, true, false);\n }\n }\n}",
"function drawFaces(faces) {\r\n ctx.strokeStyle = \"#9400D3\";\r\n ctx.lineWidth = 5;\r\n for (i = 0; i < faces.faceAnnotations.length; i++) {\r\n face = faces.faceAnnotations[i].boundingPoly.vertices;\r\n // Check if all 4 vertices are returned (we need 4 to draw a square :D )\r\n if (face[0].hasOwnProperty(\"x\") && face[0].hasOwnProperty(\"y\") &&\r\n face[1].hasOwnProperty(\"x\") && face[1].hasOwnProperty(\"y\") &&\r\n face[2].hasOwnProperty(\"x\") && face[2].hasOwnProperty(\"y\") &&\r\n face[3].hasOwnProperty(\"x\") && face[3].hasOwnProperty(\"y\")) {\r\n for (var a = 0; a < face.length; a++) {\r\n\r\n if (a < 3) {\r\n ctx.moveTo(face[a].x, face[a].y);\r\n ctx.lineTo(face[a + 1].x, face[a + 1].y);\r\n ctx.stroke();\r\n } else {\r\n ctx.moveTo(face[a].x, face[a].y);\r\n ctx.lineTo(face[0].x, face[0].y);\r\n ctx.stroke();\r\n }\r\n }\r\n }\r\n }\r\n }",
"function drawFaces(canvas, data, fps) {\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return;\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n // draw title\n ctx.font = 'small-caps 20px \"Segoe UI\"';\n ctx.fillStyle = \"white\";\n ctx.fillText(`FPS: ${fps}`, 10, 25);\n for (const person of data) {\n // face matching logic wrt reference label image\n const bestMatch = faceMatcher.findBestMatch(person.descriptor);\n recognizedFaceLabel = bestMatch.toString();\n\n // draw box around each face\n ctx.lineWidth = 3;\n ctx.strokeStyle = \"deepskyblue\";\n ctx.fillStyle = \"white\";\n ctx.globalAlpha = 0.6;\n ctx.beginPath();\n ctx.rect(\n person.detection.box.x,\n person.detection.box.y,\n person.detection.box.width,\n person.detection.box.height\n );\n ctx.stroke();\n ctx.globalAlpha = 1;\n\n ctx.fillText(\n `Name: ${recognizedFaceLabel}`,\n person.detection.box.x,\n person.detection.box.y - 39\n );\n\n // draw face points for each face\n ctx.globalAlpha = 0.8;\n ctx.fillStyle = \"lightblue\";\n const pointSize = 2;\n for (let i = 0; i < person.landmarks.positions.length; i++) {\n ctx.beginPath();\n ctx.arc(\n person.landmarks.positions[i].x,\n person.landmarks.positions[i].y,\n pointSize,\n 0,\n 2 * Math.PI\n );\n ctx.fill();\n }\n }\n}",
"function drawFace(faceAnnotations, imgObj, context) {\n for (var i = 0; i < faceAnnotations.length; i++) {\n var annotation = faceAnnotations[i];\n\n drawRectangle(annotation.boundingPoly.vertices, imgObj, context);\n\n // Part that encloses only the skin part of the face\n drawRectangle(annotation.fdBoundingPoly.vertices, imgObj, context);\n\n drawCircles(annotation.landmarks, imgObj, context);\n }\n}",
"function draw() {\n if (!listening) {\n return;\n }\n\n canvasCtx.fillStyle = 'rgb(255,255,255)';\n canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);\n canvasCtx.lineWidth = 1;\n canvasCtx.strokeStyle = 'rgb(0,97,184)';\n canvasCtx.beginPath();\n\n var sliceWidth = WIDTH * 1.0 / bufferLength;\n var x = 0;\n\n for (var i = 0; i < bufferLength; i++) {\n var v = dataArray[i] / 128.0;\n var y = v * HEIGHT / 2;\n if (i === 0) {\n canvasCtx.moveTo(x, y);\n } else {\n canvasCtx.lineTo(x, y);\n }\n x += sliceWidth;\n }\n\n canvasCtx.lineTo(canvas.width, canvas.height / 2);\n canvasCtx.stroke();\n }",
"function drawCards() {\n for (i = 0; i < 2; i++) {\n cardFaces[i] = createCardFace(850 + i * 150, 600);\n app.stage.addChild(cardFaces[i]);\n console.log(cardFaces);\n }\n}",
"function BindFaceIndciesWithBuffer(){\n // six directions\n for(var i = 0; i < 6; i++){\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, FaceIndcies[i]);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,\n new Uint16Array(IndciesDirection[i]), gl.STATIC_DRAW);\n }\n}",
"function drawFace() {\n // eyes\n draw(\"O\", 300, 140);\n draw(\"O\", 400, 140);\n // mouth\n draw(\"O\", 350, 310);\n}",
"function draw(){\n\t\tmainCtx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);\n\n\t\tfor (var i = 0, len = furniture.length; i < len; i++){\n\t\t\t// if (furniture[i].isVisible()) furniture[i].draw();\n\t\t\tfurniture[i].draw();\n\t\t}\n\t}",
"function draw () {\n\t\tsky.draw(camera);\n\t\tm.draw(camera, debug);\n\t\tm.drawObjects(camera);\n\n\t\tif (debug) {\n\t\t\tcamera.draw();\n\n\t\t\tcanvas.getContext().font = \"12px Arial\";\n\t\t\tcanvas.getContext().fillStyle = 'black';\n\t\t\tcanvas.getContext().fillText(fps + \" fps\\n\", 10, 20);\n\t\t\tcanvas.getContext().fillText(\"screen size: \" + JSON.stringify(screenSize.get()), 10, 30);\n\t\t\tif (hoveredCell) {\n\t\t\t\tcanvas.getContext().fillText(\"hovered: \" + JSON.stringify(hoveredCell), 10, 40);\n\t\t\t}\n\t\t}\n\t}",
"function draw(){\n context.clearRect(0, 0, canvas.width, canvas.height);\n boxes.forEach(function(box, i){\n context.fillStyle = box.color;\n context.fillRect(box.x, box.y, box.width, box.height);\n });\n}",
"function drawFace(canvasName, skin, eye, eyebrow, smile, mouth) {\n\tvar posX = 50;\n\tvar posY = 50;\n\tvar scale = 1.0;\n\tvar canvas = document.getElementById(canvasName);\n\tvar ctx = canvas.getContext(\"2d\");\n\tvar RADIUS = 40;\n\tvar LINE_WIDTH = RADIUS * 0.06;\n\n\tvar SKIN_MAX = 7;\n\tvar SKIN_STEP = 0xFF / (SKIN_MAX - 1);\n\n\tvar EYE_OFFSET_X = RADIUS * 0.5;\n\tvar EYE_OFFSET_Y = RADIUS * 0.2;\n\tvar EYE_RADIUS = RADIUS * 0.1;\n\tvar EYE_MAX = 7;\n\n\tvar EYEBROW_OFFSET_X = RADIUS * 0.2;\n\tvar EYEBROW_OFFSET_Y = RADIUS * 0.5;\n\tvar EYEBROW_LENGTH = RADIUS * 0.9;\n\tvar EYEBROW_MAX = 7;\n\tvar EYEBROW_STEP = (Math.PI / 180) * 90 / (EYEBROW_MAX - 1);\n\n\tvar MOUTH_OFFSET_Y = RADIUS * 0.25;\n\tvar MOUTH_WIDTH = RADIUS * 0.5;\n\n\tvar SMILE_MAX = 7;\n\tvar MOUTH_MAX = 7;\n\n\tposY = posY + RADIUS * 0.2;\n\n\tvar skinColor = 0xFF - Math.floor((skin - 1) * SKIN_STEP);\n\tvar skinColorStr = skinColor <= 0xF ? \"0\" + skinColor : skinColor.toString(16);\n\tskinColorStr = \"#FFFF\" + skinColorStr.toUpperCase();\n\n\tvar leye = new Object();\n\tleye.x = posX - EYE_OFFSET_X * scale;\n\tleye.y = posY - EYE_OFFSET_Y * scale;\n\tleye.r = EYE_RADIUS * scale * (2.5 * eye / EYE_MAX);\n\n\tvar reye = new Object();\n\treye.x = posX + EYE_OFFSET_X * scale;\n\treye.y = posY - EYE_OFFSET_Y * scale;\n\treye.r = EYE_RADIUS * scale * (2.5 * eye / EYE_MAX);\n\n\tvar dx = EYEBROW_LENGTH * Math.cos((eyebrow - 1) * EYEBROW_STEP) * scale;\n\tvar dy = EYEBROW_LENGTH * Math.sin((eyebrow - 1) * EYEBROW_STEP) * scale;\n\n\tvar leyebrow = new Object();\n\tleyebrow.x = posX - (EYEBROW_OFFSET_X) * scale;\n\tleyebrow.y = posY - (EYEBROW_OFFSET_Y) * scale;\n\tleyebrow.x1 = leyebrow.x - dx;\n\tleyebrow.y1 = leyebrow.y - dy;\n\n\tvar reyebrow = new Object();\n\treyebrow.x = posX + (EYEBROW_OFFSET_X) * scale;\n\treyebrow.y = posY - (EYEBROW_OFFSET_Y) * scale;\n\treyebrow.x1 = reyebrow.x + dx;\n\treyebrow.y1 = reyebrow.y - dy;\n\n\tvar smileScale = 1.5 * (smile / SMILE_MAX - 0.5);\n\tvar mouthScale = 0.4 * (1 + mouth) / MOUTH_MAX;\n\n\t// Draw the face\n\tctx.fillStyle = skinColorStr;\n\tctx.beginPath();\n\tctx.arc(posX, posY, RADIUS * scale, 0, 2 * Math.PI);\n\tctx.closePath();\n\tctx.fill();\n\tctx.lineWidth = LINE_WIDTH * scale;\n\tctx.stroke();\n\tctx.fillStyle = \"black\";\n\n\t// Draw the left eye\n\tctx.beginPath();\n\tctx.arc(leye.x, leye.y, leye.r, 0, 2 * Math.PI);\n\tctx.closePath();\n\tctx.fill();\n\tctx.stroke();\n\n\t// Draw the right eye\n\tctx.beginPath();\n\tctx.arc(reye.x, reye.y, reye.r, 0, 2 * Math.PI);\n\tctx.closePath();\n\tctx.fill();\n\tctx.stroke();\n\n\t// Draw the left eyebrow\n\tctx.moveTo(leyebrow.x, leyebrow.y);\n\tctx.lineTo(leyebrow.x1, leyebrow.y1);\n\tctx.stroke();\n\n\t// Draw the right eyebrow\n\tctx.moveTo(reyebrow.x, reyebrow.y);\n\tctx.lineTo(reyebrow.x1, reyebrow.y1);\n\tctx.stroke();\n\n\t// mouth up lip\n\tctx.save();\n\tctx.translate(posX, posY + MOUTH_OFFSET_Y * scale + (SMILE_MAX - smile) * 3 * scale);\n\tctx.scale(1, smileScale - mouthScale);\n\tctx.beginPath();\n\tctx.arc(0, 0, MOUTH_WIDTH * scale, 0, Math.PI, false);\n\tctx.restore();\n\tctx.strokeStyle = 'black';\n\tctx.stroke();\n\n\t// mouth bottom lip\n\tctx.save();\n\tctx.translate(posX, posY + MOUTH_OFFSET_Y * scale + (SMILE_MAX - smile) * 3 * scale);\n\tctx.scale(1, smileScale + mouthScale);\n\tctx.beginPath();\n\tctx.arc(0, 0, MOUTH_WIDTH * scale, 0, Math.PI, false);\n\tctx.restore();\n\tctx.strokeStyle = 'black';\n\tctx.stroke();\n}",
"function drawFace () {\n const center = $('body').width() / 2;\n drawCircle(center - 165 , 100, 30);\n drawCircle(center - 165, 100, 5);\n drawCircle(center + 165, 100, 30);\n drawCircle(center + 165, 100, 5);\n drawHalfCircle(center, 200, 200, false);\n}",
"function handleFaces(args) {\n if (inPreview) {\n var context = facesCanvas.getContext(\"2d\");\n context.clearRect(0, 0, facesCanvas.width, facesCanvas.height);\n var detectedFaces = args.resultFrame.detectedFaces;\n var numFaces = detectedFaces.length;\n if (numFaces > 0) {\n var face;\n\n for (var i = 0; i < numFaces; i++) {\n face = detectedFaces.getAt(i).faceBox;\n context.beginPath();\n context.rect(face.x, face.y, face.width, face.height);\n context.lineWidth = 3;\n context.strokeStyle = faceboxColors[i % faceboxColors.length];\n context.stroke();\n context.closePath();\n\n if (mirroring) {\n facesCanvas.style.transform = \"scale(-1, 1)\";\n }\n }\n }\n }\n }",
"function startFace(\n bkgd_color,\n ros_uri,\n cm_per_pixel,\n viseme_adj,\n eye_white_color,\n eye_iris_color,\n eye_size,\n eye_height,\n eye_separation,\n eye_iris_size,\n eye_pupil_scale,\n eye_pupil_shape,\n eyelid_width,\n eyelid_height,\n eyelid_arch,\n nose_color,\n nose_x,\n nose_y,\n nose_width,\n nose_height,\n mouth_color,\n mouth_x,\n mouth_y,\n mouth_width,\n mouth_height,\n mouth_thickness,\n mouth_opening,\n mouth_dimple_size,\n upper_lip_height_scale,\n lower_lip_height_scale,\n brow_color,\n brow_width,\n brow_height,\n brow_thickness,\n brow_innersize) {\n\n d = new Date();\n startup_time = d.getTime()\n prev_frame_time = startup_time\n viseme_buffer = []\n viseme_time_buffer = []\n poked = false\n poke_start_time = 0\n\n parts = []\n\n background_color = bkgd_color;\n cm_per_px = cm_per_pixel;\n ros_master_uri = ros_uri;\n\n\n container = document.createElement('div');\n container.setAttribute(\"id\", \"face-div\");\n document.body.appendChild(container);\n viseme_adjustment = viseme_adj\n\n var elem = document.getElementById('face-div');\n var params = { fullscreen: true };\n two = new Two(params).appendTo(elem);\n\n\n var rect = two.makeRectangle(windowHalfX, windowHalfY, window.innerWidth, window.innerHeight);\n rect.fill = background_color;\n rect.stroke = 'None'\n\n\n // addEyes(white_color, iris_color, size, height, separation, iris_size, pupil_scale, pupil_shape)\n addEyes(eye_white_color,\n eye_iris_color,\n eye_size,\n eye_height,\n eye_separation,\n eye_iris_size,\n eye_pupil_scale,\n eye_pupil_shape);\n\n // addLids(color, width, height, arch)\n addLids(background_color,\n eyelid_width,\n eyelid_height,\n eyelid_arch)\n\n // addNose(color, x, y, width, height)\n addNose(nose_color,\n nose_x,\n nose_y,\n nose_width,\n nose_height)\n\n // addMouth(color, x, y, width, height, thickness, opening, dimple_size, ulip_h_scale, llip_h_scale)\n addMouth(mouth_color,\n mouth_x,\n mouth_y,\n mouth_width,\n mouth_height,\n mouth_thickness,\n mouth_opening,\n mouth_dimple_size,\n upper_lip_height_scale,\n lower_lip_height_scale)\n\n // addBrows(color, width, height, thickness, arch)\n addBrows(brow_color,\n brow_width,\n brow_height,\n brow_thickness,\n brow_innersize)\n\n last_blink = 0;\n last_gaze = 0;\n looking = false;\n\n aus_l = []\n aus_r = []\n for (i = 0; i <= n_aus + 1; i++) {\n aus_l.push(0)\n aus_r.push(0)\n }\n\n document.addEventListener('mousedown', onDocumentMouseDown, false);\n document.addEventListener('touchstart', onDocumentTouchStart, false);\n document.addEventListener('touchmove', onDocumentTouchMove, false);\n window.addEventListener('resize', onWindowResize, false);\n\n // Connecting to ROS\n // -----------------\n\n if (ros_master_uri == \"\") {\n ros_master_uri = \"ws://\" + location.hostname + \":9090\"\n }\n console.log(\"ROS master URI: \" + ros_master_uri)\n\n ros = new ROSLIB.Ros({\n url: ros_master_uri\n });\n\n ros.on('connection', function () {\n console.log('Connected to websocket server.');\n });\n\n ros.on('error', function (error) {\n console.log('Error connecting to websocket server: ', error);\n reload_page_to_retry_connecting(2);\n });\n\n ros.on('close', function () {\n console.log('Connection to websocket server closed.');\n reload_page_to_retry_connecting(2);\n });\n\n // Setup ROS network\n // ----------------------\n\n listener = new ROSLIB.Topic({\n ros: ros,\n name: '/harmoni/actuating/face/default/expressing',\n messageType: 'pc_face/FaceRequest'\n });\n listener.subscribe(get_goal);\n\n is_connected_client = new ROSLIB.Service({\n ros: ros,\n name: '/harmoni/actuating/face/is_connected',\n serviceType: 'std_srvs/Trigger'\n });\n\n is_connected_client.advertise(function (_, response) {\n console.log('is_connected_client received service request');\n response['success'] = true;\n response['message'] = 'Face is connected';\n return true;\n });\n\n zeroFace(5)\n //finally, start the animation loop.\n two.bind('update', animate).play();\n}",
"draw() {\n for (let i in this.actors) {\n ctx.drawImage(this.actors[i].image, this.actors[i].x, this.actors[i].y, this.actors[i].width, this.actors[i].height);\n }\n }",
"function drawFace() {\n penUp();\n moveTo (260, 336);\n penRGB (0, 0, 0, 1);\n dot (1);\n penUp();\n moveTo (274, 336);\n dot (1);\n penUp();\n moveTo(260, 343);\n penWidth (1);\n penDown();\n turnLeft(180);\n arcLeft(180, 8);\n penUp();\n}",
"function draw()\n{\n\tif (canvas.getContext)\n\t{\n\t\tpen.fillStyle = \"#89AD6F\";\n\t\tpen.fillRect(0, 0, 110, 220);\n\t\tvar px = entidades.length;\n\t\tfor (var i = 0; i < px; i++)\n\t\t{\n\t\t\tvar p = entidades[i];\n\t\t\tif (p != undefined)\n\t\t\t\tp.draw();\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the index of the reader based on its id | function getReaderIndexByID(id){
// Iterates through the reader array
for (var i = 0; i < readerArr.length; i++) {
// If the id is correct, return the index
if (readerArr[i].id == id) {
return i;
}
}
// If id not found, return the length (next index) of the array
return readerArr.length;
} | [
"function getIndex(id){\n for(var i = 0; i < self.length; ++i)\n if(self.fields[i].id == id)\n return i;\n return -1;\n }",
"function _findIndexFromID(id) \n{\n var len=this.rsList.length, i=0;\n\n for(i=0; i<len; i++) {\n\tif(id == this.rsList[i].ruleID)\n\t break;\n }\n if(i == len)\n\treturn -1;\n else\n\treturn i;\n}",
"function _getModelIndex(id) {\n\t\t\tvar items = self[items_name];\n\t\t\tif (items.length)\n\t\t\t\tfor (var i = 0; i < items.length; i++)\n\t\t\t\t\tif (items[i].id == id)\n\t\t\t\t\t\treturn i;\n\t\t\treturn -1;\n\t\t}",
"function getIndexFromID(id) {\n\tvar counter = 0;\n\tvar result = -1;\n\tconnections.forEach(function(e) {\n\t\tif (e.id == id) {\n\t\t\tresult = counter;\n\t\t}\n\t\tcounter++;\n\t});\n\treturn result;\n}",
"function getConnectionIndex(id){\n for(let i = 0; i < connections.length; i++)\n if(connections[i].line.id === id)\n return i;\n return null;\n}",
"function getIndex(id){\n for(var i = 0; i<playerRoster.length; i++){\n if (id === playerRoster[i].id){\n return i;\n }\n } return -1;\n}",
"function getIDIndex(id) {\n return parseInt(id.slice(2));\n}",
"findIndexById(id){\n for (var i = 0; i < this.cars.length; i++) {\n if(this.cars[i]._id === id) {\n return i;\n }\n }\n return -1;\n }",
"function indexFromId(id){\n var index\n switch(id){\n case 'cell-0':\n index = 0\n break;\n case 'cell-1':\n index = 1\n break;\n case 'cell-2':\n index = 2\n break;\n case 'cell-3':\n index = 3\n break;\n case 'cell-4':\n index = 4\n break;\n case 'cell-5':\n index = 5\n break;\n case 'cell-6':\n index = 6\n break;\n case 'cell-7':\n index = 7\n break;\n case 'cell-8':\n index = 8\n break;\n }\n return index\n }",
"findIndexById(id){\n for (var i = 0; i < this.buses.length; i++) {\n if(this.buses[i]._id === id) {\n return i;\n }\n }\n return -1;\n }",
"function getIndex(id){\r\n\t\t\tfor( var i = 0; i < $scope.people.length; i++){\r\n\t\t\t\tif($scope.people[i].id === id){\r\n\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}",
"function find_row_index( rowid, rows ) {\n for (i = 0; i<rows.length; i++) {\n row = rows[i];\n if (row.attr('rowid') == rowid) return i;\n }\n return undefined;\n }",
"static getUserIndexById(id, array){\n for (var i = 0; i < array.length; i++){\n if (array[i].id === id){\n return i;\n }\n }\n return -1\n }",
"getItemIndex(id) {\n if (!id) {\n throw new Error(`An id must be provided to getItemIndex`);\n }\n if (typeof id !== \"string\") {\n throw new Error(\n `The id provided to getItemIndex must be a string. Received ${id}(${typeof id})`\n );\n }\n const index = this.#items.findIndex((item) => {\n return item._id === id;\n });\n\n if (!~index) {\n log(`Item with _id of ${id} not found`);\n }\n return index;\n }",
"getItemIndex(id) {\n if (!id) {\n throw new Error(`An id must be provided to getItemIndex`);\n }\n if (typeof id !== 'string') {\n throw new Error(\n `The id provided to getItemIndex must be a string. Received ${id}(${typeof id})`\n );\n }\n const index = this.#items.findIndex((item) => {\n return item._id === id;\n });\n\n if (!~index) {\n log(`Item with _id of ${id} not found`);\n }\n return index;\n }",
"findCursorByID(id) {\n\t\tfor (let i = 0; i < this.menuData.length; i++) {\n\t\t\tif (this.menuData[i].id === id) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}",
"getIndex (id, array) {\n for (let i = 0; i < array.length; ++i)\n if (array[i].id === id) return i;\n return -1;\n }",
"getItemIndex(id) {\n if (typeof id === \"undefined\") {\n throw new Error(`An id must be provided to getItemIndex`);\n }\n if (typeof id !== \"string\") {\n throw new Error(\n `The id provided to getItemIndex must be a string. Received ${id}(${typeof id})`\n );\n }\n const index = this.#items.findIndex((item) => {\n return item._id === id;\n });\n\n if (!~index) {\n log(`Item with _id of ${id} not found`);\n }\n return index;\n }",
"function itemIndex(state, id) {\n var ind = state.findIndex(item => {\n return item.get('id') === id\n })\n if (ind === -1) {\n throw new Error(\"Cannot find item by id=\" + id)\n }\n return ind\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.