query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Parameters: url string containing the url to convert Returns: string containing the converted url to match the protocol of the current document
function convertToCurrentProtocol(url) { if(url && url.replace) { url = url.replace(/http[s]?:/i, document.location.protocol); } return url; }
[ "function urlAdjust(url, fp) {\r\n\t\treturn fp && url.indexOf('//') == 0 ? protocolForFile + url : url;\r\n\t}", "function processUrlTemplate(url, document_ = document) {\n const scriptUrl = currentScriptUrl(document_);\n if (scriptUrl) {\n url = url.replace('{current_host}', scriptUrl.hostname);\n url = url.replace('{current_scheme}', scriptUrl.protocol.slice(0, -1));\n }\n return url;\n}", "convertUrl(url) {\n if (PackageUrlHandler.isUrlInternalToPackage(url)) {\n // TODO(fks): Revisit this format? The analyzer returns URLs without this\n return ('./' + url);\n }\n const newUrl = url.replace('bower_components/', 'node_modules/');\n const newUrlPieces = newUrl.split('/');\n const bowerPackageName = newUrlPieces[1];\n if (bowerPackageName === this.bowerPackageName) {\n newUrlPieces[1] = this.npmPackageName;\n }\n else {\n const depInfo = package_manifest_1.lookupDependencyMapping(bowerPackageName);\n if (depInfo) {\n newUrlPieces[1] = depInfo.npm;\n }\n }\n return ('./' + newUrlPieces.join('/'));\n }", "function getRelativeConverter(pageUrl) {\n return (src) => {\n const isAbsoluteUrl = /^(\\/\\/|\\w+:\\/\\/)/.exec(src);\n if (isAbsoluteUrl) {\n return src;\n } else {\n const parsed = url.parse(pageUrl);\n const base = path.basename(parsed.pathname);\n return parsed.protocol + '//' + parsed.host +\n (base ? base + '/' : '') + src;\n }\n };\n}", "function urlReplace(url) {\n\tif (window.location.host.indexOf('localhost') !== -1) {\n\t\tvar urlNew = new URL(url);\n\t\turlNew.host = 'localhost';\n\t\turlNew.protocol = window.location.protocol;\n\t\treturn urlNew.toString();\n\t}\n\n\treturn url;\n}", "function checkForHTTP(url) {\n let outputString = \"\";\n if (url.slice(0,7) === \"http://\") {\n return url;\n } else if (url.slice(0,8) === \"https://\") {\n return url;\n } else {\n outputString += \"http://\";\n outputString += url;\n return outputString;\n }\n}", "parse(_stUrl) {\n Url.parse(_stUrl, true);\n }", "function ConvertUrlToAnchor(s) {\n var description = s;\n var whitespace = \" \";\n var anchortext = \"\";\n var words;\n var splitList = [whitespace, '\\n', '\\r\\n'];\n words = splitString(description, splitList);\n \n var regexp = /^((https?|ftp):\\/\\/|(www|ftp)\\.)[a-z0-9-]+(\\.[a-z0-9-]+)+([\\/?].*)?$/\n var i = 0;\n for (i = 0; i <= words.length; i++) {\n if (words[i] != undefined) {\n var urls = \"\";\n var testregexp = /^((ftp|http|https):\\/\\/|(www|ftp)\\.)[a-z0-9-]+(\\.[a-z0-9-]+)+([\\/?].*)?(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!-\\/]))?$/\n if (testregexp.test(words[i].toString()) == true) {\n urls = '<a target=\"_blank\" href= \\\"' + words[i].toString() + '\\\">' + words[i].toString() + '</a>'\n\n if (i == words.length - 1) {\n description = description.substring(0, description.lastIndexOf(words[i].toString()));\n description = description + urls;\n } else {\n description = description.replace(words[i].toString() + ' ', urls + ' ').replace(words[i].toString() + '\\n', urls + '\\n').replace(words[i].toString() + '\\r\\n', urls + '\\r\\n');\n }\n }\n }\n }\n return description;\n}", "function giveFriendlyUrl(url){\n\t\tvar splitElements = url.split(\"../index.html\");\n\t\treturn splitElements[splitElements.length-2];\n\t}", "function getFallbackURL(url) {\n if (url.search(/osapublishing\\.org\\/DirectPDFAccess/i) == -1) return null;\n\n //get base url\n let baseurl = url.replace(/osapublishing\\.org.*/gi,\"osapublishing.org\");\n\n //get id\n let id = url.replace(/\\.pdf\\?.*$/gi,\"\").replace(/^.*\\//gi,\"\");\n if (id == \"\") return null;\n return (baseurl + \"/fulltext.cfm?uri=\" + id);\n }", "function cleanGitHubUrl(url) {\n return url.replace('https://api.github.com', 'https://github.com');\n}", "function cssParseUri(url) {\n var match = /^url[(][\"'](.*)[\"'][)]$/.exec(url);\n return match ? match[1] : null;\n }", "function parseURL(url) {\n parsed_url = {}\n\n if (url == null || url.length == 0)\n return parsed_url;\n\n protocol_i = url.indexOf('://');\n parsed_url.protocol = url.substr(0, protocol_i);\n\n remaining_url = url.substr(protocol_i + 3, url.length);\n domain_i = remaining_url.indexOf('/');\n domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;\n parsed_url.domain = remaining_url.substr(0, domain_i);\n parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);\n\n //a domain can have multiple configuration (google.com, www.google.com, plus.google.com...), this sorts it out for the parsed url\n domain_parts = parsed_url.domain.split('.');\n switch (domain_parts.length) {\n case 2:\n parsed_url.subdomain = null;\n parsed_url.host = domain_parts[0];\n parsed_url.tld = domain_parts[1];\n break;\n case 3:\n parsed_url.subdomain = domain_parts[0];\n parsed_url.host = domain_parts[1];\n parsed_url.tld = domain_parts[2];\n break;\n case 4:\n parsed_url.subdomain = domain_parts[0];\n parsed_url.host = domain_parts[1];\n parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];\n break;\n }\n\n parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;\n\n return parsed_url;\n}", "function getRootUrl(url) {\n var domain = url.replace('http://','').replace('https://','').replace('www.', '').split(/[/?#]/)[0];\n return domain;\n}", "function slugifyUrl(url) {\n\t\t\treturn Util.parseUrl(url).path\n\t\t\t\t.replace(/^[^\\w]+|[^\\w]+$/g, '')\n\t\t\t\t.replace(/[^\\w]+/g, '-')\n\t\t\t\t.toLocaleLowerCase();\n\t\t}", "function parsePinUrl(url) {\n if (url != null) {\n var urlParts = url.replace('http://', '').replace('https://', '').replace('www.', '').split(/[/?#]/);\n return urlParts[0];\n } else {\n return \"\"\n }\n }", "function cleanRepoGitHubUrl(url) {\n return url.replace('https://api.github.com/repos', 'https://github.com');\n}", "function processUrl (inputUrl, port) {\n const parsedUrl = url.parse(inputUrl)\n\n if (parsedUrl.host === TEST_HOSTNAME &&\n parsedUrl.port === TEST_PORT) {\n const path = url.format({\n protocol: 'http',\n hostname: 'localhost',\n port,\n pathname: parsedUrl.pathname,\n search: parsedUrl.search\n })\n return path\n }\n\n return inputUrl\n}", "pathToFileUrl(url) {\n const filePrefix = process.platform === \"win32\" ? \"file:///\" : \"file://\";\n return filePrefix + url;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
here the i in this loop gives me only the number of the index, but not actually the content of the position. this is why I have to change it to boldSelect[i])
function getBold_items(){ for (let i = 0; i < boldSelect.length; i++){ boldWords.push(boldSelect[i].textContent); } console.log(boldWords); }
[ "function index_after_formatting(position) {\n\t var start = position === 0 ? 0 : position - 1;\n\t var command_len = $.terminal.length(command);\n\t for (var i = start; i < command_len - 1; ++i) {\n\t var substr = $.terminal.substring(command, 0, i);\n\t var next_substr = $.terminal.substring(command, 0, i + 1);\n\t var formatted_substr = formatting(substr);\n\t var formatted_next = formatting(next_substr);\n\t var substr_len = length(formatted_substr);\n\t var next_len = length(formatted_next);\n\t var test_diff = Math.abs(next_len - substr_len);\n\t if (test_diff > 1) {\n\t return i;\n\t }\n\t }\n\t }", "function scanFiles(files, i, j) {\n //var output = [];//buffer array for reading file (array of lines)\n var f;\n for (; i < j; i++) { //read every file\n f = files[i]; //currently reading this file\n if (!txtExtension(f.name)) continue;\n var reader = new FileReader();\n var result;\n reader.onload = function(e) { //done loading\n var lines = e.target.result.split(\"\\n\");\n var thisPoem = new Poem(lines); //make a new poem with the file contents\n var item = selectBar.text(buffer, listY, lines[0]); //this is the poem name in the select bar\n item.attr({\n font: \"12px Fontin-Sans, Helvetica\",\n fill: deselectColor,\n \"text-anchor\": \"start\"\n });\n listY += lineSpacing + 2;\n item.data(\"poem\", thisPoem); //link actual Poem object to clickable raphael object\n poemList.push(item); //add it to the list\n item.click(function() { //click function for poem name\n if (selected != null) { //if other poem was selected before this\n if (selected.data('poem').contains()) { //currently selected word is in the poem\n selected.attr(\"fill\", containsColor)\n } else selected.attr(\"fill\", deselectColor);\n }\n selected = this; //now this one is selected\n this.attr(\"fill\", selectColor); //change the color of this item\n this.data('poem').showPoem(); //and show its poem\n });\n };\n reader.readAsText(f, \"UTF-8\");\n reader.onloadend = function(e) {\n adjustSizes();\n };\n }\n}", "function handleMouseDown(e){\n e.preventDefault();\n startX=parseInt(e.clientX-offsetX);\n startY=parseInt(e.clientY-offsetY);\n \n // Put your mousedown stuff here\n for(var i = 0;i < texts.length;i++){\n \t if(textHittest(texts, startX, startY, i)){\n \t\t selectedType = 0;\n \t\t selectedText = i;\n \t\t// selectedId = texts[i].id;\n \t }\n }\n for(i = 0;i < arranged_texts.length;i++){\n \t if(textHittest(arranged_texts, startX, startY, i)){\n \t\t selectedType = 1;\n \t\t selectedText = i;\n \t }\n } \n }", "function createBoldRegAlternatingText() {\r\n var originalTextList = document.getElementsByClassName(\"bold-reg-text-alternate\");\r\n for (var i = 0; i < originalTextList.length; i++) {\r\n console.log(originalTextList[i].innerHTML);\r\n var wordsFromText = originalTextList[i].innerHTML.trim().split(\" \");\r\n var updatedText = \"\";\r\n\r\n for (var j = 0; j < wordsFromText.length; j++) {\r\n if (j % 2 == 0) {\r\n updatedText += \"<b>\" + wordsFromText[j] + \"</b>\";\r\n }\r\n else {\r\n updatedText += wordsFromText[j];\r\n }\r\n }\r\n console.log(updatedText);\r\n originalTextList[i].innerHTML = updatedText;\r\n }\r\n}", "function setSelected(index) {\n selected = points[index];\n console.log('selected knowledge point');\n console.dir(selected);\n chapter = selected.chapter;\n syllabus = chapter.syllabus;\n }", "handleOList(){\n this.sliceString();\n var list = this.selection.split(/\\n/);\n var text = \"\";\n var i = 1;\n list.map(function(word){\n text = text + \" \" + i.toString() + \". \" + word + \"\\n\";\n i = i + 1;\n })\n this.post.value = this.beg + text + this.end;\n }", "function updateSelectPositions() {\n let selectY = 480;\n\n heightSelect.x = gameCanvas.getBoundingClientRect().left + 87;\n heightSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n\n massSelect.x = gameCanvas.getBoundingClientRect().left + 212;\n massSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n\n surfaceSelect.x = gameCanvas.getBoundingClientRect().left + 359;\n surfaceSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n\n positionSelect.x = gameCanvas.getBoundingClientRect().left + 506;\n positionSelect.y = gameCanvas.getBoundingClientRect().top + selectY;\n}", "display_raw_text(div, raw_text, word_lists=[], colors=[], positions=false) {\n div.classed('lime', true).classed('text_div', true);\n div.append('h3').text('Text with highlighted words');\n let highlight_tag = 'span';\n let text_span = div.append('span').text(raw_text);\n let position_lists = word_lists;\n if (!positions) {\n position_lists = this.wordlists_to_positions(word_lists, raw_text);\n }\n let objects = []\n for (let i of range(position_lists.length)) {\n position_lists[i].map(x => objects.push({'label' : i, 'start': x[0], 'end': x[1]}));\n }\n objects = sortBy(objects, x=>x['start']);\n let node = text_span.node().childNodes[0];\n let subtract = 0;\n for (let obj of objects) {\n let word = raw_text.slice(obj.start, obj.end);\n let start = obj.start - subtract;\n let end = obj.end - subtract;\n let match = document.createElement(highlight_tag);\n match.appendChild(document.createTextNode(word));\n match.style.backgroundColor = colors[obj.label];\n try {\n let after = node.splitText(start);\n after.nodeValue = after.nodeValue.substring(word.length);\n node.parentNode.insertBefore(match, after);\n subtract += end;\n node = after;\n }\n catch (err){\n }\n }\n }", "function updateFontOptions() {\n styleSelectFont.innerHTML = \"\";\n for (let i = 0; i < fonts.length; i++) {\n const opt = document.createElement(\"option\");\n opt.value = i;\n const font = fonts[i].split(\":\")[0].replace(/\\+/g, \" \");\n opt.style.fontFamily = opt.innerHTML = font;\n styleSelectFont.add(opt);\n }\n}", "getPositionStringForIndex (index) {\n let { row, column } = this.getCoordinates(index)\n const number = Math.abs(row - 7) + 1\n const letter = String.fromCharCode(97 + column)\n return `${letter}${number}`\n }", "function edit_textarea(index) {\r\n\tif (virtual_keyboard_option == \"lowercase_alphabet\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(lowercase_letter_comma_period_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"uppercase_alphabet\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(uppercase_letter_comma_period_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"punctuation_numbers_one\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(punctuation_numbers_one_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"punctuation_numbers_two\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(punctuation_numbers_two_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"lowercase_accent_characters_one\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(lowercase_accent_characters_one_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"uppercase_accent_characters_one\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(uppercase_accent_characters_one_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"lowercase_accent_characters_two\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(lowercase_accent_characters_two_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"uppercase_accent_characters_two\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(uppercase_accent_characters_two_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"lowercase_accent_characters_three\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(lowercase_accent_characters_three_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"uppercase_accent_characters_three\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(uppercase_accent_characters_three_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"lowercase_accent_characters_four\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(lowercase_accent_characters_four_utf_8_array[index]));\r\n\t} else if (virtual_keyboard_option == \"uppercase_accent_characters_four\") {\r\n\t\tadd_character_move_cursor(String.fromCharCode(uppercase_accent_characters_four_utf_8_array[index]));\r\n\t} \r\n\tscroll_to_cursor();\r\n\tupdate_printable_table();\r\n}", "function editSelection() {\n var selection = DocumentApp.getActiveDocument().getSelection();\n \n if (selection) {\n var elements = selection.getRangeElements();\n \n for (var i = 0; i < elements.length; i++) {\n var element = elements[i];\n var textElement = element.getElement();\n \n if (textElement.getType() != DocumentApp.ElementType.TEXT) {\n var textElements = getTextChildren(textElement);\n textElements.forEach(function(e) {\n insertThinSpaces(e);\n });\n \n continue;\n }\n \n if (element.isPartial()) {\n insertThinSpaces(textElement, element.getStartOffset(), element.getEndOffsetInclusive());\n } else {\n insertThinSpaces(textElement);\n }\n }\n } else {\n var cursor = DocumentApp.getActiveDocument().getCursor();\n \n if (!cursor) \n throw 'Please, select some text';\n var tableCell = cursor.getElement().getParent();\n \n while (tableCell.getType() != DocumentApp.ElementType.TABLE_CELL) {\n tableCell = tableCell.getParent(); \n \n if (!tableCell)\n throw 'Please, select some text';\n }\n var colIndex = tableCell.getParent().getChildIndex(tableCell);\n var table = tableCell.getParentTable();\n var numRows = table.getNumChildren();\n \n for (var i = 0; i < numRows; i++) {\n var currentCell = table.getChild(i).getChild(colIndex);\n \n var textElements = getTextChildren(currentCell);\n textElements.forEach(function(e) {\n insertThinSpaces(e);\n });\n }\n }\n}", "function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}", "function extUtils_getOffsetsAfterCheckingForBodySelection(allText,currOffs)\n{\n var offsets = currOffs;\n var selStr = allText.substring(offsets[0],offsets[1]);\n var newStartOff = currOffs[0];\n var newEndOff = currOffs[1];\n var openBracketInd,closeBracketInd,nOpenBrackets,nCloseBrackets;\n var ind;\n\n if ( selStr.indexOf(\"<BODY\") == 0 || selStr.indexOf(\"<body\") == 0 ){\n nOpenBrackets = 1;\n nCloseBrackets = 0;\n closeBracketInd = 0; // index of closing bracket of </body>\n ind=1;\n\n while ( !closeBracketInd && selStr.charAt(ind) ) {\n if ( selStr.charAt(ind) == \"<\" ){\n nOpenBrackets++;\n } else if (selStr.charAt(ind) == \">\" ){\n nCloseBrackets++;\n if( nOpenBrackets == nCloseBrackets ){\n closeBracketInd = ind;\n }\n }\n ind++;\n }\n\n // get first non-newline character inside of the body tag\n newStartOff = closeBracketInd + 1;\n while ( selStr.charAt(newStartOff) == \"\\n\" ||\n selStr.charAt(newStartOff) == \"\\r\" ) {\n newStartOff++;\n }\n\n // get last non-newline character inside of the body tag\n openBracketInd = selStr.lastIndexOf(\"<\"); // open bracket index of </body>\n newEndOff = openBracketInd - 1;\n while ( selStr.charAt(newEndOff) == \"\\n\" ||\n selStr.charAt(newEndOff) == \"\\r\" ) {\n newEndOff--;\n }\n\n // add 1 because selection actually goes to newEndOff minus one\n newEndOff++;\n\n newStartOff += currOffs[0];\n newEndOff += currOffs[0];\n }\n\n return new Array(newStartOff,newEndOff);\n}", "function findSelectionIn(doc, node, pos, index, dir, text) {\n\t if (node.isTextblock) return new TextSelection(doc.resolve(pos));\n\t for (var i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {\n\t var child = node.child(i);\n\t if (!child.type.isLeaf) {\n\t var inner = findSelectionIn(doc, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text);\n\t if (inner) return inner;\n\t } else if (!text && child.type.selectable) {\n\t return new NodeSelection(doc.resolve(pos - (dir < 0 ? child.nodeSize : 0)));\n\t }\n\t pos += child.nodeSize * dir;\n\t }\n\t}", "function getTypeSelectStr(ind, selected_index, htmlId) {\r\n\r\n str = \"<select onchange='changeType(this,\" + ind + \",\\\"\" + htmlId +\r\n \"\\\")'>\";\r\n for (var i = 0; i < TypesArr.length; i++) {\r\n str += \"<option value='\" + i + \"' \";\r\n if (i == selected_index)\r\n str += \"selected\";\r\n str += \">\" + TypesArr[i] + \"</option>\";\r\n }\r\n str += \"</select>\";\r\n\r\n return str;\r\n }", "prepareSelectItems() {\n let that = this;\n let items_buffer = getReferencesOfType('AGItem');\n let select_item_buffer = '';\n if (items_buffer.length > 0) {\n items_buffer.forEach(function (element) {\n select_item_buffer = select_item_buffer + '<option value = \"' + getReferenceById(element).ID + '\">' + getReferenceById(element).name + '</option>';\n });\n }\n return select_item_buffer;\n }", "function renderSelection()\r\n{\r\n var totalZbllSel = 0;\r\n for (var oll in zbllMap) if (zbllMap.hasOwnProperty(oll)) {\r\n var ollNoneSel = true, ollAllSel = true; // ollNoneSel = 0 selected, ollAllSel = all cases selected\r\n var zbllsInOll = 0;\r\n var ollMap = zbllMap[oll];\r\n for (var coll in ollMap) if (ollMap.hasOwnProperty(coll)) {\r\n var collNoneSel = true, collAllSel = true; // ollNoneSel = 0 selected, ollAllSel = all cases selected\t\r\n var zbllsInColl = 0;\r\n collMap = ollMap[coll];\r\n for (var zbll in collMap) if (collMap.hasOwnProperty(zbll)) {\r\n var zbllAlg = collMap[zbll];\r\n if (collMap[zbll][\"c\"])\r\n {\r\n // case selected\r\n ollNoneSel = false;\r\n collNoneSel = false;\r\n zbllsInColl++; zbllsInOll++; totalZbllSel++;\r\n }\r\n else {\r\n // case not selected\r\n ollAllSel = false;\r\n collAllSel = false;\r\n }\r\n }\r\n // render coll item background\r\n document.getElementById( idTdColl(oll, coll) ).style.backgroundColor = colorBySelection(collAllSel, collNoneSel);\r\n document.getElementById( idHeaderColl(oll, coll) ).innerHTML = collHeaderContent(oll, coll, zbllsInColl);\r\n }\r\n document.getElementById( idTdOll(oll) ).style.backgroundColor = colorBySelection(ollAllSel, ollNoneSel);\r\n document.getElementById( idHeaderOll(oll) ).innerHTML = ollHeaderContent(oll, zbllsInOll);\r\n }\r\n\r\n // Save the selection to local storage if possible\r\n if (window.saveSelection) { // No guarantee that saveSelection function is ready, so test first\r\n saveSelection();\r\n }\r\n}", "buildHighlightPosition (position, linenum, text) {\n var remainingCharacters = position;\n let lines = text.split(\"\\n\");\n\n // Iterate until we get to the position of the character we need, and then build\n // a relative vscode.Position.\n for (var i = 0; i < lines.length; i++) {\n let charactersInLine = lines[i].length + 1; // +1 for the newline.\n\n if (remainingCharacters - charactersInLine < 0) {\n return new vscode.Position(linenum - 1, remainingCharacters);\n }\n\n remainingCharacters = remainingCharacters - charactersInLine;\n }\n\n // If we get here, there's probaly a buffer mismatch.\n return undefined;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get sum of points column NB: uses Q.defer as this is an async call, eventually we should implement it everywhere
function getPointSum(){ var deferred = $q.defer(); db.transaction(function(tx){ tx.executeSql('SELECT sum(points) AS sumPoints FROM activities', [], function(tx,results){ var tot = results.rows.item(0).sumPoints; deferred.resolve(tot); }); }); return deferred.promise; }
[ "function getCategoryTotalPoints(category){\n let htmlPath = \" > td.possible.points_possible\"; //HTML path to get to the total points within the table data (td)\n return sumTablePortion(htmlPath, category);\n}", "function getTotalPoints() {\n\tvar totalPoints = window.currentBuild.traits.line1.total\n\t\t+ window.currentBuild.traits.line2.total\n\t\t+ window.currentBuild.traits.line3.total\n\t\t+ window.currentBuild.traits.line4.total\n\t\t+ window.currentBuild.traits.line5.total;\n\n\t\treturn totalPoints;\n\n}", "get points() {\n if (this.issues) {\n return this.issues.reduce((pts, issue) => pts + issue.points, 0);\n }\n\n return 0;\n }", "calculateTotal() {\n this.total = [this.darts.one, this.darts.two, this.darts.three]\n .map(dart => this.getDartValueFromID(dart))\n .reduce((a, b) => a + b, 0);\n }", "function getCategoryEarnedPoints(category){\n let htmlPath = \" > td.assignment_score > div > div > span.what_if_score\"; //HTML path to get to the total points within the table data (td)\n return sumTablePortion(htmlPath, category);\n}", "function totalDistance(points){\n\tvar totalDistance = 0;\n\tfor(var i = 0; i < points.length - 1; i++){\n\t\ttotalDistance += Math.sqrt(Math.pow(points[i+1][0]-points[i][0], 2) + \n\t\t\t\t\t\t\t\t\tMath.pow(points[i+1][1]-points[i][1], 2) + \n\t\t\t\t\t\t\t\t\tMath.pow(points[i+1][2]-points[i][2], 2));\n\t}\n\treturn totalDistance;\n}", "function calcTotal(){\n\n //Variable to hold total of all expense rows\n var totalExp = 0;\n\n //Adds values from row to totalExp\n for (j = 1; j <= 4; j++){\n totalExp += calcRow(j);\n }\n\n return totalExp;\n}", "add(x, y) {\n return new Promise(function (resolve, reject) {\n // if (x === 0 || y === 0) {\n // reject('No zeroes');\n // }\n setTimeout(() => resolve(x + y), 0);\n });\n }", "statsSum() {\n let sum = 0;\n for (let key in this.stats) {\n sum += this.stats[key];\n }\n\n console.log(`La suma de tus estadísticas es ${sum}`);\n }", "dataPoints () {\n let dimension = this;\n \n // Get the data points for this user for this dimension\n return DataPoints.find({\n dimensionId: dimension._id\n });\n }", "entryTimeTotal({ commit }, data) {\n let time = [];\n\n data.forEach(ele => {\n time.push(ele.entries_sum);\n });\n const hours = time.reduce((acc, seconds) => {\n return acc + seconds;\n }, 0);\n\n commit(\"set_total\", hours);\n }", "_contentSummary(){\n let ptsTotal = 0\n this.#qs.forEach( question => {\n ptsTotal += question.userPoints\n })\n return<div id=\"summary-text\"><div>\n {this.#qs.map( question => {\n return <p>{question.text} {question.correct}<br />{question.userAnswer}</p>\n })}</div>\n <p>Pisteet: {ptsTotal} / {this.#maxPts}</p>\n <Button text='uudestaan?!' onClick={this.next}/>\n </div>\n }", "function totalDepartment() {\n connection.query(\"SELECT Department, SUM(SalaryTotal) as 'Total Spend by Department' FROM ( SELECT title as Title, SUM(salary) as SalaryTotal, name as Department FROM employee LEFT JOIN role ON employee.role_id = role.id LEFT JOIN department ON role.department_id = department.id GROUP BY role_id) derived_salaries GROUP BY Department ORDER BY SUM(SalaryTotal) DESC\", function(err, results) {\n if (err) throw err;\n console.table(results);\n budgetQs();\n});\n}", "function calculateCostForDataPoints(energy_data_points) {\n var cost = 0.0;\n for (var i = 0; i < energy_data_points.length; i++) {\n var rate = getRate(i % 24);\n cost += energy_data_points[i].value * rate;\n }\n return cost;\n }", "function totalCreditsAndQualityPoints(e){\n \n var credit = parseFloat($(e.currentTarget).parent('td').parent('tr').find('input[name=\"credit\"], select[name=\"credit\"] option:selected').val());\n var gpa = $(e.currentTarget).parent('td').parent('tr').find('input[name=\"gpa\"]').val();\n var grade = $(e.currentTarget).parent('td').parent('tr').find('input[name=\"grade\"], select[name=\"grade\"]').val(); \n \n if($('input[name=\"gpa\"]')){ //calculate GPA\n var qualityPointsFirstRowTotal = totalQualityPointsPerRow(parseFloat(gpa, 10), credit); \n $(e.currentTarget).parent('td').parent('tr').find('#qualityPointsFirstRow').text(qualityPointsFirstRowTotal);\n \n }\n if($('select[name=\"grade\"]')){ //calculate Grade\n var qualityPointsPerRowTotal = totalQualityPointsPerRow(parseFloat(computeGradeNum(grade), 10), parseFloat(credit, 10));\n $(e.currentTarget).parent('td').parent('tr').find('#qualityPoints').text(qualityPointsPerRowTotal);\n \n }\n \n var totalAllCredits = 0;\n var totalAllQualityPoints = 0;\n \n totalAllQualityPoints = calculatePoints($allQualityPoints, totalAllQualityPoints);\n totalAllCredits = calculateCredits($allCredits, totalAllCredits);\n \n $('#newCumulativeCredits').text(totalAllCredits); \n $('#newCumulativeQualityPoints').text(totalAllQualityPoints);\n \n overallGPA();\n }", "totalTip() {\n let billclass = this;\n _.map(this.diners, function(index) {\n billclass.tTip.push(index.tip);\n });\n billclass.tTip = _.sum(billclass.tTip);\n }", "getSumOfDssRatios() {\n let sum = 0;\n for (let disease of this.diseases) {\n sum += this.getDssRatio(disease);\n }\n return sum;\n }", "getTotalValue() {\n var totalVal = 0.0;\n for (var i in this.state.stocks) {\n //check if not null\n if (this.state.stocks[i][\"totalValue\"]) {\n totalVal += this.state.stocks[i][\"totalValue\"];\n }\n }\n // return totalVal.toFixed(3) + \" \" + currSymbol;\n return parseFloat(totalVal).toFixed(3) + this.getCurrencySymbol();\n }", "function getTotalPriceAmount(userId) {\n return new Promise(async (resolve, reject) => {\n try {\n const sci = await Shopping_cart_items.findOne({ userId: userId });\n resolve(sci.totalAmount);\n } catch (err_msg) {\n reject({\n error: true,\n message: 'Something went wrong while fetching total price of shopping cart!',\n status: 500,\n err_msg\n })\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the provided property is a Placeholder component from Belle.
function isPlaceholder(reactElement) { return (0, _isComponentOfType2.default)(_Placeholder2.default, reactElement); }
[ "isEmpty(patternProperty) {\n if ((patternProperty = \"\")) {\n return true;\n } else {\n return false;\n }\n }", "placeholderHidden() {\n return !!(this.labels.length > 0 || this.value);\n }", "check(abstract) {\n let resolved_abstract = this.resolveAbstract(abstract);\n if (this.bindings[resolved_abstract] === undefined) {\n return false;\n } else {\n return true;\n }\n }", "exists() {\n return this.element ? true : false;\n }", "function is(value) {\n var candidate = value;\n return candidate && Is.string(candidate.newText) && Range$1.is(candidate.insert) && Range$1.is(candidate.replace);\n }", "function isPropValid()\n{\n\n}", "isVisible (template) {\n if (template) {\n return QuickPopoverController.popover && QuickPopoverController.contentTemplate === template\n } else {\n return QuickPopoverController.popover !== undefined\n }\n }", "get placeholderCellRendered() {\n return this._placeholderCellRendered;\n }", "exists(el)\n {\n if(typeof(el) != 'undefined' && el != null) { return true; } // If not undefined or null, then exists.\n return false;\n }", "isTextProps(props) {\n return props.text !== undefined;\n }", "isEmpty(editor, element) {\n var {\n children\n } = element;\n var [first] = children;\n return children.length === 0 || children.length === 1 && Text.isText(first) && first.text === '' && !editor.isVoid(element);\n }", "static isValid(make) {\n return make != null && make !== '';\n }", "validateLocalStrategyProperty(property) {\r\n return ((this.provider !== 'local' && !this.updated) || property.length);\r\n }", "function isNotNull(value){\n return !isNull(value);\n }", "isRequired () {\n\t\tconst definition = this.definition;\n\t\treturn ('required' in definition) && definition.required === true;\n\t}", "function isPresent(obj) {\r\n return obj !== undefined && obj !== null;\r\n}", "botTitleExist(){\n \n expect(this.botTitle).toBeDisplayed()\n }", "function check_in_region(address_components,type,name_,value) {\n if (g_find_type_in_results(address_components,type,name_) == value) {\n return true;\n } else {\n return false;\n }\n}", "isText(value) {\n return isPlainObject(value) && typeof value.text === 'string';\n }", "isValidType() {\n return Menu.getPizzaTypesSet().has(this.type.toLowerCase());\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
instantiates selector, which is first called in Engine.js before init()
function startLoad() { selector = new Selector(); }
[ "createSelector() {\n\t\t// Add a selector icon and scales it\n\t\tthis.selector = this.add.image(32, 32, 'selector');\n\t\tthis.selector.alpha = 0;\n\n\t\t// Listen to mouse movement\n\t\tthis.input.on('pointermove', function (pointer) {\n\t\t\t// Grabs mouse position & divide by 64 (To get index of array)\n\t\t\tlet mouseY = Math.floor(pointer.y / 64);\n\t\t\tlet mouseX = Math.floor(pointer.x / 64);\n\n\t\t\t// Check if position available\n\t\t\tif (this.checkPosition(mouseY, mouseX)) {\n\t\t\t\t// If true, update cursor position (32 to center)\n\t\t\t\tthis.selector.setPosition(mouseX * 64 + 32, mouseY * 64 + 32);\n\t\t\t\tthis.selector.alpha = 0.9;\n\t\t\t} else {\n\t\t\t\t// If false\n\t\t\t\tthis.selector.alpha = 0;\n\t\t\t}\n\t\t}.bind(this));\n\t}", "function Selector() {\n\t\tthis.rules = {};\n\t}", "startSelection(label) {\n this.selector = label;\n }", "init() {\n this.#elemetn = this.getElement(this.UiSelectors.timer);\n }", "function createSelector() {\n for (var _len7 = arguments.length, args = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {\n args[_key7] = arguments[_key7];\n }\n\n var selector = _reselect.createSelector.apply(undefined, args);\n selector.$$factory = function () {\n return _reselect.createSelector.apply(undefined, args);\n };\n return selector;\n}", "_initSelectors () {\n this.tabAttribute = 'data-rvt-tab'\n this.panelAttribute = 'data-rvt-tab-panel'\n\n this.tabSelector = `[${this.tabAttribute}]`\n this.panelSelector = `[${this.panelAttribute}]`\n this.tablistSelector = '[data-rvt-tablist]'\n this.initialTabSelector = '[data-rvt-tab-init]'\n }", "function init_tag_selector() {\n if(query('#tag_selector')) {\n\tlet fieldset = query('#add_topic_form > fieldset');\n\tlet banned = fieldset && fieldset.disabled;\n\tlet tags_input = query('select[name=\"tags\"]');\n\tfor(let I of tags_input.options) {\n\t let option = I;\n\t let checkbox = (\n\t\ttag_selector.querySelector(\n\t\t printf('input[data-slug=\"%1\"]', option.value)\n\t\t)\n\t );\n\t let event_handler = function() {\n\t\toption.selected = this.checked;\n\t };\n\t checkbox.addEventListener('change', event_handler);\n\t event_handler.call(checkbox);\n\t if(!banned) {\n\t\tcheckbox.parentElement.addEventListener('click', function(ev) {\n\t\t if(ev.target != checkbox) {\n\t\t\tcheckbox.checked = !checkbox.checked;\n\t\t\tevent_handler.call(checkbox);\n\t\t }\n\t\t});\n\t } else {\n\t\tcheckbox.parentElement.style.color = 'gray';\n\t }\n\t checkbox.nextElementSibling.unselectable = 'on';\n\t checkbox.nextElementSibling.onselectstart = (function() {\n\t\treturn false;\n\t });\n\t}\n\ttags_input.style.display = 'none';\n\ttag_selector.style.display = '';\n }\n}", "function Game_SelectorTS() {\n this.initialize.apply(this);\n}", "function Sprite_SelectorTS() {\n this.initialize.apply(this, arguments);\n}", "function initInstanceElement(el) {\n const visible = $(el).data('visible');\n $(el).addClass('instance')\n .toggleClass('invisible-instance', visible !== true && visible !== 'true')\n .on('click', function(e) {\n e.stopPropagation();\n selectInstance(this);\n })\n .on('blur', function(e) {\n })\n .on('keydown', function(e) {\n if (e.key === 'Escape') {\n exitInlineEditing(this);\n }\n })\n .on('dblclick', function(e) {\n e.stopPropagation();\n enterInlineEditing(this);\n })\n // use mouseover and mouseout for hover styling instead of css :hover\n // to avoid styling parent instance elements\n .on('mouseover', function(e) {\n e.stopPropagation();\n $(this).addClass('hover');\n })\n .on('mouseout', function(e) {\n $(this).removeClass('hover');\n });\n }", "setSelector(selectorText){\n if (typeof selectorText !== \"string\") throw new TypeError(\"Your selectorText is not a string\");\n let head = super.getHead();\n\n this.patch({\n action: VirtualActions.PATCH_REPLACE,\n start: head.startOffset,\n end: head.endOffset,\n value: selectorText,\n patchDelta: selectorText.length - head.endOffset\n })\n }", "_getOptionSelector(widgetInstance){\n return this.cache.selector[widgetInstance.id] = this.cache.selector[widgetInstance.id] || widgetInstance._getOptionSelector({ enableCaching: true });\n }", "function initSelection() {\n canvas.on({\n \"selection:created\": function __listenersSelectionCreated() {\n global.console.log(\"**** selection:created\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n \"before:selection:cleared\": function __listenersBeforeSelectionCleared() {\n global.console.log(\"**** before:selection:cleared\");\n },\n \"selection:cleared\": function __listenersSelectionCleared() {\n global.console.log(\"**** selection:cleared\");\n toolbar.hideActiveTools();\n },\n \"selection:updated\": function __listenersSelectionUpdated() {\n global.console.log(\"**** selection:updated\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n });\n}", "function $Q(selector) {\n\n //declare events:\n\n console.log(selector);\n\n var query = [];\n\n //handle selector / selection of objects:\n\n if (typeof selector !== 'string') {\n\n if (selector instanceof Array) {\n\n } else {\n\n\n }\n\n } else {\n\n\n if (selector && selector !== '*') {\n\n var s = selector || '';\n\n console.info('selector:' + s);\n\n\n var mainSelector = $Q.before('[', s).trim(),\n msfChar = mainSelector.substring(0, 1);\n\n var __targetClassName = \"*\";\n\n var output = [];\n\n var cleanSelectorString = function(str) {\n return str.replace(\",\", \"\");\n };\n\n switch (msfChar.toLowerCase()) {\n case \".\":\n\n console.info('Selecting by \".\" or class');\n\n __targetClassName = cleanSelectorString($Q.after('.', mainSelector));\n\n console.info('Target class is:' + __targetClassName);\n\n break;\n\n case \"*\":\n\n console.info('Selecting by \"*\" or ANY object in the library instance');\n\n __targetClassName = \"*\";\n\n break;\n\n }\n\n var criterion = $Q.between('[', ']', s),\n cparts = criterion.split('=');\n\n var __targetGroup = \"*\",\n __targetName = \"*\";\n\n var getParts = function() {\n\n if (cparts.length >= 2) {\n\n switch (cparts[0].toLowerCase()) {\n\n case \"name\":\n\n //get all objects according to name=name\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetName = cleanSelectorString(cparts[1]);\n\n break;\n\n case \"group\":\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetGroup = cleanSelectorString(cparts[1]);\n\n break;\n\n }\n\n }\n\n if (cparts.length >= 4) {\n\n cparts[2] = cparts[2].replace(\",\", \"\");\n\n switch (cparts[2].toLowerCase()) {\n\n case \"name\":\n\n //get all objects according to name=name\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetName = cleanSelectorString(cparts[3]);\n\n break;\n\n case \"group\":\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetGroup = cleanSelectorString(cparts[3]);\n\n break;\n\n }\n\n }\n\n };\n\n getParts(cparts);\n\n query = Gamelab.select(__targetClassName, __targetName, __targetGroup);\n\n } else if (selector == '*') {\n\n query = Gamelab.all();\n\n }\n\n }\n\n\n query.each = function(callback) {\n\n var objects = [];\n\n for (var x = 0; x < this.length; x++) {\n if (typeof x == 'number') {\n\n callback(x, this[x]);\n }\n\n }\n\n\n };\n\n query.on = function(evt_key, selectorObject, controller_ix, callback) //handle each event such as on('collide') OR on('stick_left_0') << first controller stick_left\n {\n\n if (typeof evt_key == 'function' && typeof selectorObject == 'function') {\n //this is a special pattern of if(f() == true){ runFunction(); };\n\n var boolTrigger = evt_key,\n boolCall = selectorObject,\n\n boolEvent = new Gamelab.BoolEvent().On(boolTrigger).Call(boolCall);\n\n }\n\n\n var criterion = $Q.between('[', ']', evt_key);\n\n if (criterion.indexOf('===') >= 0) {\n criterion = criterion.replace('===', '=');\n }\n\n if (criterion.indexOf('==') >= 0) {\n criterion = criterion.replace('==', '=').replace('==', 0);\n }\n\n var cparts = criterion.split('=');\n\n var __targetGroup = \"*\",\n __targetName = \"*\";\n\n if (evt_key.indexOf('[') >= 0) {\n evt_key = $Q.before('[', evt_key).trim();\n\n }\n\n\n var padding = 0;\n\n //if controller_ix is function, and callback not present, then controller_ix is the callback aka optional argument\n\n if (controller_ix && typeof controller_ix == 'function' && !callback) {\n callback = controller_ix;\n controller_ix = 0;\n }\n\n //optional argument: if controller_ix is function, and callback not present, then callback is selectorObject\n\n if (selectorObject && typeof selectorObject == 'function' && !callback) {\n\n callback = selectorObject;\n\n selectorObject = $Q('*');\n\n controller_ix = 0;\n };\n\n var evt_profile = {};\n\n //which controller?\n\n evt_profile.cix = controller_ix;\n\n //Need the control key: 'left_stick', 'button_0', etc..\n\n evt_profile.evt_key = evt_key;\n\n if ($Q.contains_any(['stick', 'button', 'click', 'key'], evt_profile.evt_key)) {\n\n var button_mode = evt_profile.evt_key.indexOf('button') >= 0;\n\n Gamelab.GamepadAdapter.on(evt_profile.evt_key, 0, function(x, y) {\n\n callback(x, y);\n\n });\n\n console.info('detected input event key in:' + evt_profile.evt_key);\n\n console.info('TODO: rig events');\n\n }\n\n //TODO: test collision events:\n else if ($Q.contains_any(['collide', 'collision', 'hit', 'touch'], evt_profile.evt_key)) {\n\n // console.info('Rigging a collision event');\n\n // console.info('detected collision event key in:' + evt_profile.evt_key);\n\n // console.info('TODO: rig collision events');\n\n this.each(function(ix, item1) {\n\n // console.info('Collision Processing 1:' + item1.name);\n // console.info('Collision Processing 1:' + item1.type);\n\n selectorObject.each(function(iy, item2) {\n\n // console.info('Collision Processing 2:' + item2.name);\n // console.info('Collision Processing 2:' + item2.type);\n\n if (typeof(item1.onUpdate) == 'function') {\n\n var update = function(sprite) {\n\n console.log('Box collide::' + jstr([this, item2]));\n\n if (this.hasBoxCollision(item2, padding)) {\n\n callback(this, item2);\n\n };\n\n };\n\n item1.onUpdate(update);\n\n }\n\n\n });\n\n });\n\n\n } else {\n console.info('Rigging a property event');\n\n //TODO: test property-watch events:\n\n console.info('detected property threshhold event key in:' + evt_profile.evt_key);\n\n console.info('TODO: rig property events');\n\n var condition = \"_\",\n key = criterion || evt_profile.evt_key;\n\n if (key.indexOf('[') >= 0 || key.indexOf(']') >= 0) {\n key = $Q.between('[', ']', key);\n\n }\n\n var evt_parts = [];\n\n var run = function() {\n console.error('Sprite property check was not set correctly');\n\n };\n\n if (key.indexOf('>=') >= 0) {\n condition = \">=\";\n\n\n } else if (key.indexOf('<=') >= 0) {\n condition = \"<=\";\n } else if (key.indexOf('>') >= 0) {\n condition = \">\";\n } else if (key.indexOf('<') >= 0) {\n condition = \"<\";\n } else if (key.indexOf('=') >= 0) {\n condition = \"=\";\n }\n\n evt_parts = key.split(condition);\n\n for (var x = 0; x < evt_parts.length; x++) {\n evt_parts[x] = evt_parts[x].replace('=', '').replace('=', '').trim(); //remove any trailing equals and trim()\n\n }\n\n var mykey, number;\n\n // alert(evt_parts[0]);\n\n try {\n\n mykey = evt_parts[0];\n\n number = parseFloat(evt_parts[1]);\n\n } catch (e) {\n console.log(e);\n }\n\n console.info('Gamelab:Processing condition with:' + condition);\n\n switch (condition) {\n\n case \">=\":\n\n\n run = function(obj, key) {\n if (obj[key] >= number) {\n callback();\n }\n };\n\n break;\n\n case \"<=\":\n\n run = function(obj, key) {\n if (obj[key] <= number) {\n callback();\n }\n };\n\n break;\n\n\n case \">\":\n\n run = function(obj, key) {\n if (obj[key] > number) {\n callback();\n }\n };\n\n break;\n\n case \"<\":\n\n run = function(obj, key) {\n if (obj[key] < number) {\n callback();\n }\n };\n\n break;\n\n case \"=\":\n\n run = function(obj, key) {\n if (obj[key] == number) {\n callback();\n }\n };\n\n break;\n\n }\n\n\n /************\n * Attach update to each member\n *\n * **************/\n\n var keys = mykey.split('.'),\n propkey = \"\";\n\n this.each(function(ix, item) {\n\n var object = {};\n\n if (keys.length == 1) {\n object = item;\n\n propkey = mykey;\n\n } else if (keys.length == 2) {\n object = item[keys[0]];\n\n propkey = keys[1];\n\n\n } else if (keys.length == 3) {\n object = item[keys[0]][keys[1]];\n\n propkey = keys[2];\n\n } else {\n console.error(\":length of '.' notation out of range. We use max length of 3 or prop.prop.key.\");\n\n }\n\n if (typeof item.onUpdate == 'function') {\n\n\n var spr = item;\n\n item.onUpdate(function(sprite) {\n\n run(object, propkey);\n\n });\n\n }\n\n });\n\n }\n\n };\n\n\n return query;\n\n}", "function selectElement(_) {\n\t\t// _.element - javascript element\n\t\t// _.jelement - jQuery element\n\t\t// _.id - ID of Element\n\n\n\n\t\tif (_===undefined || typeof _!=\"object\" || (_.element===undefined && _.jelement===undefined && _.id===undefined)) return false;\n\t\tif (_.id!==undefined) _.jelement = jQuery('#'+_.id);\n\t\tif (_.element===undefined) _.element=_.jelement[0];\n\t\tif (_.jelement===undefined) _.jelement = jQuery(_.element);\n\t\tif (_.id===undefined) _.id = _.element.id;\n\n\t\tif (_.jelement===undefined) return;\n\n\t\tdeselectAllElement(_.element.id);\n\n\t\tRVS.S.selElements = [];\n\t\tRVS.S.selElements.push({\n\t\t\t\t\tjobj : _.jelement,\n\t\t\t\t\tmultiplemark: _.element.dataset.multiplemark,\n\t\t\t\t\tforms:_.jelement.data('forms'),\n\t\t\t\t\tid:_.element.id,\n\n\t\t\t});\n\n\t\t_.jelement.addClass(\"marked\");\n\n\t}", "function init() {\n var _this = this;\n\n this._get('options').plugins.forEach(function (plugin) {\n // check if plugin definition is string or object\n var Plugin = undefined;\n var pluginName = undefined;\n var pluginOptions = {};\n if (typeof plugin === 'string') {\n pluginName = plugin;\n } else if ((typeof plugin === 'undefined' ? 'undefined' : babelHelpers.typeof(plugin)) === 'object') {\n pluginName = plugin.name;\n pluginOptions = plugin.options || {};\n }\n\n Plugin = find(pluginName);\n _this._get('plugins')[plugin] = new Plugin(_this, pluginOptions);\n\n addClass(_this._get('$container'), pluginClass(pluginName));\n });\n }", "function setSelectorFields() {\n // Clear existing selectors\n removeChildren(visualSelector);\n removeChildren(propertySelector);\n\n let propertyOpts = propertyOptions();\n propertyOpts.forEach(function (element) {\n var optK = document.createElement(\"option\")\n optK.value = element;\n optK.innerHTML = element;\n\n propertySelector.appendChild(optK);\n });\n\n propertySelector.value = selectedPropertyOption();\n\n // Add new visual options\n let visualSelectionOptions = visualisationOptions()\n\n visualSelectionOptions.forEach(function (element) {\n var optV = document.createElement('option');\n\n optV.value = element.value;\n optV.innerHTML = element.description;\n\n visualSelector.appendChild(optV);\n });\n}", "function $$(cssSelector) {\n return $(cssSelector, gamesolverDriver);\n }", "function setupBot(name, selector) {\n $( selector ).click( function activator(){\n console.log( \"Activating: \" + name );\n } );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove this entity from the game world completely, and allow it to be GCed. Any specific destruction functionality should be added to onDestroy, which is called from this method.
destroy() { // Prevent multiple destruction of entities. if (this._destroyed === true) return; this._destroyed = true; this.onDestroy(); }
[ "function Cleanup_Entities() {\n\tfor(var k in game.ents) {\n\t\tif(game.ents[k].remove) {\n\t\t\t// Entity should clean up its own game.ents index when remove is called\n\n\t\t\t// It's important not to forcably remove from game.ents in case \n\t\t\t// to do a cleanup for some reason after its removal is signaled\n\t\t\tgame.ents[k].remove();\n\t\t}\n\t}\n\t// Remove player data structures\n\tfor(var k in game.clients) {\n\t\tdelete game.clients[k];\n\t\tFireEvent('player_leave',{userId: k});\n\t}\n\tgame.async = {};\n}", "destroy() {\n //console.log('destroy');\n if (this.scene !== undefined) {\n this.scene.time.removeEvent(this.shootEvent);\n }\n if (this.body !== undefined){\n this.body.enable = false;\n }\n\n super.destroy();\n }", "destroy() {\n _wl_scene_remove_object(this.objectId);\n this.objectId = null;\n }", "function destroy() {\n if (!isBuilded) {\n return;\n }\n\n isBuilded = false;\n\n darlingjs.removeWorld('myGame');\n world = darlingjs.world('myGame', [\n 'myApp',\n 'ngFlatland',\n 'ngCyclic',\n 'ng3D',\n 'ngPhysics',\n 'ngBox2DEmscripten',\n 'ngPixijsAdapter',\n 'ngStats',\n 'ngPerformance',\n 'ngInfinity1DWorld',\n 'ngPlayer',\n 'ngParticleSystem',\n 'ngSound',\n 'ngHowlerAdapter',\n 'ngResources'\n ], {\n fps: 60\n });\n world.$c('ground', {});\n }", "destroy () {\n this.group.remove(this.sprite, true, true);\n this.gameObjectsGroup.destroyMember(this);\n }", "Destroy()\n {\n const gl = device.gl;\n\n if (this.texture)\n {\n gl.deleteTexture(this.texture.texture);\n this.texture = null;\n }\n\n if (this._renderBuffer)\n {\n gl.deleteRenderbuffer(this._renderBuffer);\n this._renderBuffer = null;\n }\n\n if (this._frameBuffer)\n {\n gl.deleteFramebuffer(this._frameBuffer);\n this._frameBuffer = null;\n }\n }", "function complete(){\n game.stage.removeChild(object);\n }", "destroy()\n {\n //first remove it from the scene.\n this.#scene.remove(this);\n //then destroy all components.\n while(this.#components.length > 0)\n {\n let currentComponent = this.#components.pop();\n currentComponent.destroy();\n }\n }", "UnloadScene()\n {\n\n if ( !this.__loaded )\n {\n console.warn( \"Unable to unload scene. Not loaded\" );\n return;\n }\n\n // Destroy all objects loaded into the scene.\n Object.keys( this.sceneObjects ).forEach( key => {\n this.Destroy( this.sceneObjects[ key ] );\n });\n\n this.__loaded = false;\n\n }", "detach() {\n this.surface = null;\n this.dom = null;\n }", "destroy()\n {\n this.parentGroup.removeSprite(this);\n }", "remove() {\n this.floor.itemSprites.removeChild(this.sprite);\n }", "async removeAndFlush(entity) {\n await this.em.removeAndFlush(entity);\n }", "destroy() {\n\t\tif (this.timer) {\n\t\t\tclearTimeout(this.timer);\n\t\t}\n\t\tfor (const i in this.playerTable) {\n\t\t\tthis.playerTable[i].destroy();\n\t\t}\n\t\t// destroy this game\n\t\tthis.room.game = null;\n\t}", "removeLater(entity) {\n this.em.removeLater(entity);\n }", "remove(entity) {\n return this.em.remove(entity);\n }", "function complete(){\n stage.removeChild(object);\n }", "destroy() {\n this.map.off('dragging', this.listenDragging, this);\n this.map.off('dragend', this.listenDragEnd, this);\n this.customLayer.setMap(null);\n }", "onRemovedFromScene() {\n if (this._pixiObject !== null)\n this._pixiContainer.removeChild(this._pixiObject);\n if (this._threeObject !== null) this._threeGroup.remove(this._threeObject);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funcion encargada de crear un icono con el url y size pasados como parametro
function iconsMaker(url, size) { var icon = L.icon({ iconUrl: url, iconSize: [size, size], iconAnchor: [22, 94], shadowAnchor: [4, 62], popupAnchor: [-3, -76] }); return icon; }
[ "function GoogleThumbSetSizes(level, startI, tn, data, kind ) {\r\n var sizes=['xs','sm','me','la','xl'];\r\n \r\n for(var i=0; i<sizes.length; i++ ) {\r\n tn.url[level][sizes[i]]=data.media$group.media$thumbnail[startI+i].url;\r\n if( kind == 'image' ) {\r\n tn.width[level][sizes[i]]=data.media$group.media$thumbnail[startI+i].width;\r\n tn.height[level][sizes[i]]=data.media$group.media$thumbnail[startI+i].height;\r\n\r\n var gw=data.media$group.media$thumbnail[startI+i].width;\r\n var gh=data.media$group.media$thumbnail[startI+i].height;\r\n if( G.tn.settings.width[level][sizes[i]] == 'auto' ) {\r\n if( gh < G.tn.settings.height[level][sizes[i]] ) {\r\n // calculate new h/w and change URL\r\n var ratio=gw/gh;\r\n tn.width[level][sizes[i]]=gw*ratio;\r\n tn.height[level][sizes[i]]=gh*ratio;\r\n var url=tn.url[level][sizes[i]].substring(0, tn.url[level][sizes[i]].lastIndexOf('/'));\r\n url=url.substring(0, url.lastIndexOf('/')) + '/';\r\n tn.url[level][sizes[i]]=url+'h'+G.tn.settings.height[level][sizes[i]]+'/';\r\n }\r\n }\r\n if( G.tn.settings.height[level][sizes[i]] == 'auto' ) {\r\n if( gw < G.tn.settings.width[level][sizes[i]] ) {\r\n // calculate new h/w and change URL\r\n var ratio=gh/gw;\r\n tn.height[level][sizes[i]]=gh*ratio;\r\n tn.width[level][sizes[i]]=gw*ratio;\r\n var url=tn.url[level][sizes[i]].substring(0, tn.url[level][sizes[i]].lastIndexOf('/'));\r\n url=url.substring(0, url.lastIndexOf('/')) + '/';\r\n tn.url[level][sizes[i]]=url+'w'+G.tn.settings.width[level][sizes[i]]+'/';\r\n }\r\n }\r\n }\r\n else {\r\n // albums\r\n // the Google API returns incorrect height/width values\r\n if( G.tn.settings.width[level][sizes[i]] != 'auto' ) {\r\n// tn.width[level][sizes[i]]=data.media$group.media$thumbnail[startI+i].width;\r\n }\r\n else {\r\n var url=tn.url[level][sizes[i]].substring(0, tn.url[level][sizes[i]].lastIndexOf('/'));\r\n url=url.substring(0, url.lastIndexOf('/')) + '/';\r\n tn.url[level][sizes[i]]=url+'h'+G.tn.settings.height[level][sizes[i]]+'/';\r\n }\r\n \r\n if( G.tn.settings.height[level][sizes[i]] != 'auto' ) { \r\n// tn.height[level][sizes[i]]=data.media$group.media$thumbnail[startI+i].height;\r\n }\r\n else {\r\n var url=tn.url[level][sizes[i]].substring(0, tn.url[level][sizes[i]].lastIndexOf('/'));\r\n url=url.substring(0, url.lastIndexOf('/')) + '/';\r\n tn.url[level][sizes[i]]=url+'w'+G.tn.settings.width[level][sizes[i]]+'/';\r\n }\r\n }\r\n }\r\n return tn;\r\n }", "addImage(url) {\n \n }", "function generateURL(id) {\n return `https://picsum.photos/id/${id}/400`;\n }", "function createImgObj(sym,yOfTop){\r\n\tvar imgNames = [\"Ace.png\",\"King.png\",\"Queen.png\",\"Joker.png\",\"Ten.png\"];\r\n\tvar imageObj = new Image();\r\n\t\timageObj.src = imgNames[sym];\t\r\n\t\tvar iObj = {\r\n\t\t\tx: 50,\r\n\t\t\ty: yOfTop-100,\r\n\t\t\twidth: 100,\r\n\t\t\theight: 50,\r\n\t\t\tborderWidth: 5,\r\n\t\t\timg: imageObj\r\n\t\t};\r\n\treturn iObj;\r\n}", "function getWidthIcon(x,y,s){\n\treturn \"M\"+(x-s/2)+\" \"+y+\",L\"+(x+s/2)+\" \"+y; \n}", "function get_img(i,f){var b,a=__CONF__.img_url+\"/img_new/{0}--{1}-{2}-1\",g=__CONF__.img_url+\"/img_src/{0}\",c=\"d96a3fdeaf68d3e8db170ad5\",d=\"43e2e6f41e3b3ebe22aa6560\",k=\"726a17bd880cff1fb375718c\",j=\"6ea1ff46aab3a42c975dd7ab\";i=i||\"0\";f=f||{};ObjectH.mix(f,{type:\"head\",w:30,h:30,sex:1});if(i!=\"0\"){if(f.type==\"src\"){b=g.format(i);}else{b=a.format(i,f.w,f.h);}}else{if(f.type==\"head\"){if(f.sex==1){b=a.format(c,f.w,f.h);}else{b=a.format(d,f.w,f.h);}}else{if(f.type==\"subject\"){b=a.format(k,f.w,f.h);}else{if(f.type==\"place\"){b=a.format(j,f.w,f.h);}else{b=a.format(\"0\",f.w,f.h);}}}}return b;}", "function getIcFilename(ext, color, size) {\n let filename = `ic_${iconArg.trim().replace(' ', '_')}`;\n if (color)\n filename += `_${color}`;\n if (size) \n filename += `_${size}dp`;\n if (ext)\n filename += `.${ext}`;\n\n return filename;\n}", "function calculateImageSize(value) {\r\n\r\n}", "function pngPath(size) {\n\t\treturn path.join(cacheDir, baseName + '-' + size + '.png')\n\t}", "function makeMarkerIcon(color) {\n var markerImage = new google.maps.MarkerImage('img/' + color + 'flag' + '.png',\n new google.maps.Size(64, 64),\n new google.maps.Point(0, 0),\n new google.maps.Point(32, 64),\n new google.maps.Size(64, 64));\n return markerImage;\n}", "function loadUbuntuIcon() {\n var logo = new Image();\n logo.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR0AAAEdCAYAAAAxarN7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAIYZJREFUeNrsnU2QFFXWhm+3KC2NNATT4s8wtLoV7NEV7YLSGBewsY34FhoYUrORheLXgyEudLB1mIUYKgO6aDYWhsQQMQvLDS4wtFgMrMZp1OXotKLjABp08y/4yZdv1k1Iuqsyb1Zl3p+87xtRUSjaVX0r86n3nHvOuT2CohJ0+fLle4KnxVn+n56enoNcOart9cEl8A4iK4KnodgDqsT+k0oBLzsZPKZn/Xk6+nMAqSP8ZAgdym2wDARPw/KxWIIkDhkbNSUfEZQa+HMApBl+ooQOZSdgKjHQDJXoV4wcUUM+A0Rf85MndCh9kLknBplKyQCTBUSN6MHwjNCh8oXMihhgRkXGpC4hRBE6lApo1kjARCETlU1TEkD1AEAfcDkIHao1aB6WoKGbyV/16MHENKFD0BA0BBChQxUMGiSCq/JB0JjTdAw+DMEIndKBZiAGGuZo7NNU8Kjhwe14QqcMrmZMwoZyJ/yq0f0QOq7BZoMETYWr4bT7GRfM/RA6DoRQcDZDXJHSCLmfHQy9CB3bYDMmH0wMl1s1uB/Ch9AhbCjCh9AhbCjChyJ0CBuqKO2Q8GHCmdDJDTjYjRoXTBBT7RUlnHcQPoRON7BZIy8kFvRRqpqSrmcPl4LQyQKbFdLZVLkaVIdqIBTnmI256uUSzAHO/4rmhDoCh+pGFVxHwfX0pswHUnQ6c2CDloUaQymqoJBrjK0VdDoRbAbwbSTdDYFDFaGh4FEPrrP36Xo8dzoyUVwT3JWi9Am7XFWfXY+XTifmbhoEDqVZi313Pd45HeZuKLoeOh2dwIl2pggcyibX49UOlxdOR36gcDejvM4pSzUpXU/p63pKDx0ZTjUE+6UoN8KtsbJXM5c6vIqFUwQO5Uq4VQuu23fodNwMp9AzVeV1TDkcblXK2DxaOujIvikM12aymCpDuFUpW56nVOGVzN9wd4oqU7g1KUerEDoWAmeDYP6GKqdqspiV0LEIOC+J5pY4RZVVY0gwl6Gex/mcjsz0V3lNUp7I+QSzs9BhwR9F8LgJHiehI4HTEEwYU/7K2Z0t56BD4FCU2+BxCjoEDtWJfvryc3Hhs0Pip6++ED8f+yZ4HBU/Hz8a/l3fypHw+Ya77hbz77xbLFi9Tly30KlcrXPgcQY6BA6VRf93Zkacqk+I0wf2XQGMqhasXiv6g8dNDz1G8PgKHQKHygqbk3tf6/pnzbt5uRh8dpe4cdX9BI9P0CFwKFWd/+zv4sTrmzI7GxXnM7h5lwthlxPgsRo6BA6lqpPvbc/F3SS5nmVb94j5d60keMoKHQKHUtXxwN2c+Whf4a/T279I3PpqneDpdh0JHMpl/TDxghbgQL+cPSW+f3403A2zXOg/bMiJC4SOomoEDpWm0wf+Kk7Vd2t9TYDn2CsbwoS1A+Cp29irZR10ZC8VWxuoRF069o34ceJFI6+NRPWJNza5sEzD0vFYBR6roCO7xau8pag0AThwHaZ07vCH4W6ZI+CpETqtgYN5OOO8nag04WbHTW9a2DFzRKM2zV22AjqxA/AoKlUz9Qkr3seFzw+54nagqi0TCI1DR2bYG7yVKBUhl2ODy7ENgIrCBMI1XkNHJrgwRJ0jRiklnTv0oV3v5/CHri1h3fRWummng2NiuDVOKev85/aFMw6FWEJYsJVuDDryILwqbyMqiy5YeINfcAs6Qn7R7/AKOjJxvIO3EJVFKMgzuU3eTpjT46CMJZa1QyfW4kBRmXTR0pv7lzPOzkivSQNQeqdTE0wcU5Qt0p7f0QodmcdhiwNF2aMhoTnVMU8jcJjHcUCX5AxhhAzxcAZ5i7QwIj5h74Y77xa9CwfCcRAOjILwXcjv1Ht6ej4oDXRiZ1RRlgjjGS6Gg8qPhlu+8WHlnQoVum0vtJuXi3nLll8ZgD5v2W8yjwHF/08VJuR3hgPwfF0WpzMuWI9jVAALtnbD5wQ4FCUADY/Zr43TGACiG1feL/oCCCWNBL0+AJWNcmSGcpoWS2PwQNEvVPjkQFl23eBtr9/J4NiVs4f3G4FMp1r4u0fFzc/uavv3/9nysHW/z+DmnS6dHJGmscDt/MVZp8OwSj9oTn+0L2wVyHs4uS6dCyApxK5EV2EbdPrK4XSuRCUyv1NYmFV0eIWwaog4KE5hA2QAGTQeugqauFD8h9+pXSiFkxmKHMCeVUiY2xr22RpmFbZlLnerxoiFYoTczH9feUIcrd4nftz9YimAc8XtJDR1YicMN7otGhh9soyXV0WWt7gFHYZVxQhzgb/ZcG84INzBDmc1oKY0ddpyo6McoES5nFZhViFFg4VAR1KSu1U5ClPqAJsTbzxTKlfT0ukEMEWI1U640bEFb1pLN24r88eAMKuQurrcoSNndYwTE/mHU2WHTVxnDiQfKzOYsMOlQwjxSuxyIlWLGPpVhNMZF+ytyl2mbzLdQmI86ZgX7GItMhRmIazCNrknyt3t5AodScUqEZG/sEOyqJxJy5bCLtaplFGgv9r457C40ERY5VFrx3DeSeVciwODN/dPwVxOYcI3/9HqvVbOlCnKUSyvfZpYpYw1QVJd19iLkhUCqgrHFA/19PTkMsMjN6cjBwIROAUKN9/A6Eav3E7aoXZYE5wvrsPxeAocCOmScaucjtxamxQsBMzsXHBT9a9em+lixi6WT0nlZX/cI/pH1qX+d9jhK6JwEDtly7buYbd80+10Xamcl9MZI3CyCbtRCJWwPYzTKrOcjb3k8ee8WiuAOWkL/eq6bAldT57Fg8ij3f72JwROU7m4na6djnQ5U4I7Vsr6YeIFcaq+e87FjcSoqmxsfCxSAAmAkpTfiQtFlKcP7OtojZBLWrB6XQj3krU45KFK4HYOmobOS4J1OcrhVFLS8/a3Plb+RoVTws/ySVnBA0W9aei2x7q3S8LjZ+OBUDdtxIbnagTQ6aovqyvo0OWoCx3ggETSzhOSobdtVx/eht6rsrZC5AmeVp9F9Dng5xEwet1Ot9Chy1G0+mhfUFGWHRJ8i6Ph0zcBFFgn5lncdDsdQ4cuR02t8jdp+YS02pRufn5Z1KwK3qW0q0XZ5Xa62b0aI3CSdfz1TZmBoFKJG9eS9VvCG9A3YZ2O/WlDGGKq7GxRuavjCKcjp0OXkywkjLENfuajfR3/jOW1fyjvnMy8PxHO1PFVgC6KJhcFD+ZntKqjup1OoYNeDB4n0wY4eZTlZ00q+1Yw2A4+Cx96NARQXlvd+DwJsraqBdD5vS7o/FuwGLAw4ERSrcSFzh7aH4YbVFPh6InfPSr6Vo1kSjjjM8SpGWcPfxjOa8ZROd3ultHtdAkd2WNV41oXCxwI5feohlW94H0rGMzqHAGQ69ucnZV09lce2/Ql1ngAnZeLhs4nwVOFa32tkDTuJofTTkvWPxeW96vIx4JBnc6J4GmpzB3omaAjh61Pcp31ACdSlqRynu8FOZKojwkH4l3XP5AKPSiP00IJHqdUDaCzpyjovCM4pOsa6aiTyZJU7rRgEDdUmP/o8MjfVoqOLsY56Be//KIUoV/aYYCeajKAzm9zh47cJp/m+l5VlkrjbpUlqawy4gH5ogUja5WO881T0fHGSNTqGryVt7I253oinIN+JG/ocJt81rf4d08/qO31siSV200YjECDXR0bWgiiZkycSuoagDwe6NVOytvnWaDDUaQpN3XRypJUjhcM4lRMgMbmlgFAfCYIU7FN7co41ixTATyQckJZCTpMIF+rb596wNg3c5akMsIsFMu5NBMGQEcbCGbh2J6MzlrS4IGUEsqq0HlT8IjgUKYbLLNWKrss5MzQTmKz84GLvGXru7wxmlJKKKs2fFa5ns0kqOmObuwAofrYByFngo57hJW2NrVinhFCWSrUsDxsszunE/yQh4Onuu+radPxLz7aeiSd4XpsHVrG/M4VjQVu5y/dOh2WuIrmcHBbbD5yHVnGX5RByEshjEHpgI2uR1fphAvQySO88h46CGds+4Y969mY0kjYgUPIhVyKTcLGAhL3lBiSG0+dQUeGVl7PzInOprJJKE779dufePuZIKyE60GtjE2uBwWZ2Pqnko1Kbzf/sw+yafekOaJzJ6thpZBoRi8Uclw2XS8UodOxsFtVZCNnVuDgBmMV7LVC8hZJ9TwP2OtG2F3EVr/nStzF6k0Irdb4HlrZEqPjhkIeg7sj7cMtABnNmLa4nSwntvrmdnrpcloL31Y2dEVznII6eND9bQN4sg7X9w06PQlOx+teKxtmDhM4nano+UaqytKyUlItbtWL1dsGOCt8Bg7CKgLHXdnieE6+95rvH0UlS3hV8XWVEIvPGLbGBE45wAO35fmZXISOihCLm9wij3apCJx8wGN6V8tztzOaBTreJpFNuhwCJ3+ZruPx3O0Mtdo6nwMdWcLs5VY5dqxMupylG7dxWzxnAeDLtprt1/Lc7VRUnI7HCWRzFwdaG1j4V4wAcgDdlDAN0eO6HSXoVHxcmfCwNUM7Vsg7sLWhWAHophLLcM9nDuzzdemHCZ02MpXLifqpKD3hq6n8zoy/xYLD8iSZ1tCRfznk26qEpxIYGhWxZP0W5nE0CfmdQUNnVsFFR4cR+u52etOskA/CMSimwqqBRzaSBhqFQwRNhVmn/Q2xKknQYWilUQyrzIVZJnazsH3uaUKZTicuDF0ykUBeaMmBd76GWQhrjbjqw/t9XHJC5xrLa6AxEN+ySx5/jne/QSGsNZFU9nTM7FA8mXwFOr4mkU3kcwZGN/refWyFTIAfGxa+h1i9DK30hlZwOYtGmTy2QajdMeF2fA+xvIbOhc/0D+nCMb/srfLb7Zz/7JCPSz3UCjre9VudNfCNM0CX473bodO5qop3TkfzOFLsWDGXYyN49NbtoC3Cw6NqWkJnyLdV0F0kpvviptRDXh9Ce8O6EknNcwU6aFX4+djR4NF8jtS36v4wOdtJzcvNsiRexzxdWHhUw1L2Ce4TJ4bqbIU5//nfvatGxwkzPT09B+fJf1hh45tErwpKxy8kdYDvvTqOom/liOhfvS5TslYXeBaMrOXdbbH6NUPngr99WM3TIOQZVw1b3hSGaWG2TTfb2QidsDOhmkMp+gSB29/6mBXIluurtYNaX8/D0yLGA6fzcq9NoRWSa98+9YA48cYzXdfPACBHq/cpH5iHfpyi5ukitCJw7BdCLJ3y1e1YAx3A4bunHxQXv/oi358bhF8AWdqc2nDsweadhTQCMrRyJ8TSqXhu0hNV4tAxKoQ2J/cWNyoUIPsuAE/aNiXcSBGNgDeuZALZBfVpTvSf99zpVEwCR8fuEWojvn9+NBU8RTQC9nHXygkhv6KzUNBDpzNk3On8MPGC1uNfI/CkNdzlOV0OeSK2PdDttITOcUJHq84e2i9O1Xdrf12A59grTySHQ8GFl1dSuW/VCO9khzRf8+F8PoZYRsIrOI0Tb2wy9kuj/WHm/eRpgQOjTzp5EVNdOtO7+HkVKYzQMeJ0Tu7dbvRQu+g9JIVZaATMYydrHnutnJLuqnEPt82HtUMHW9cmwqpWYdaplNnIC1avc+4iprqXyWOIfQqvtMmmQ8fSBrJ3W7dh8ihbqht3qg86l/zbwRK98uxybbLpGA64HSS026nbnYwbmM9xFDr6QuKfU4pWS7m+QuPwLlMnLyQJg7L7R1qHUdjqBjjyrpKm7NaNq0Y6ggGS0Nf1ZyuP0OmqLNHieTpfzcYZImmJPFwUnUKHOyFuCpsIeFCFSG8i+dJx+6xkmvPqZss767ceRfkgrdC5+KWdYYqHoyMpyg/o2KqkmiEmgymK0NG7QOyboihCh6IoQqe08nmWLUU5Dx1b+5DYqkBRJYWOjR3XaX02PpapU1Sh95zOF7NxtkxaAV831ciYlbKE15hzwufWbVjd2z+gVBza6ZltDmtKK3SwuFhk02Mt4kpr6mQLhH/CGfe6JiHgrLbbtn/gFXR6ceKezldcaNHRugBg0viKbqe6EVhuSmcRq4/zlrTvXg2M2nOUKoCTNL8Y33jdyCZHR9n5uV3vX8Onfuhg4j5O37RBOAE0SecOdX/MLFssHHQ6dKjlgo7Kza7lPaxPPnIYc3byGMPBC9gt6f6S8LDNZiqCzqRut7P0yW3Gfmtsky9KCfPSpgoqX8SEDl1O0re+Z202PT09X0fQmdb94jjUTvfZ0eGH3L9ILNu6JzGXE26Zfp7P7B9bO+spO74kfCxMNdoGMbh5l3Z7uXTjttS6CJyrnpfyghelRzoHzXk4Q3s6Dp1JE+8AbuPWV+vawDO4eWfqRDjkcvIGxXn2bzkhHEmkM7zyMJ8zGYfOtKl3EYGnyFAL3yi3v/VxKnCKOgSQTaOuuBy9n5Ov42yNQycCzy1b3w2Ty3lbTsBsee1TpVJzAKeIGg0Mf6fsl+7Pab7nTmfShneE5DIAkUcdD8rL4aAAs+sUdgiQxzlX0EUHy37Jw6NGXNO5LotBGV6latoapzPb9dz87C6x4m//Cp1Plg8GLgnAAmzQz6K6M3D6wF/Fyb2vFXtBH6LbsdrlHNqvvYLcs0bPK+YmbPjs6ek5cvnyZaveHeAD54NHlOCLYm5sa/4S/LvonCEcEwM4dfIhAjgn3nim8N/n9Ef7wt+FYmgVOXEPNX0FOlJTwWPIxncKAMG15F3TMPP+hPhx94tafgdAE9WuHn67WS98qekOrTwdHHdNTieCjlcXmi7gXIGcpnEJVMbQ97D+0KrPQ+gEEdXMbOhM+rQA0ZHBui9uwI6ySyffe037a3rodBrRH3pnx1s+SfckQ3ybnsqpp4vKRyjczKOxN4tMtP9YoKlW0Gn4tgo3GRixcfrAPt7pVrmc7dpfs5/Q8TO8gqLxqTqFb1XsmFF2uBwTvXF9fiaR54ZXMsnjXYiVNK60KP048SJzO566HOQRr/dwRGk7p+Ol2zFhdZnbMa8iGnttDekt0DTm6LSDTsM76IysSz37qghhSBhbI8wJbtOIsx7xMp9zjZnx3umYuhDgdkxd+AyrtmvfsWqG8mt9Da0ahM4smTqhAg2msPmUPsFdFt1nZ1Mob73TkXGXd8lkfPuY6oXBOA0mlTWu9+ubjLwudknT5jn5Gl7NsUK+6CZDhwAizCpicBjVOqwyNT7WpkMmNWsqnkQmdK6BzmPGZtYizELzKVWc0GxrKqwyGcJboDk8IXQsuTDQfMqD+YoRwtdjr2ww9vqY8eRpAnlOaNUSOpitIzzM60A4C8vkhH7cGMzvFLGuTxjZrTIdurvkdLx1O+HgMINuBzfG98+PEjw56vjrm4weA4QNCk9n50BT0sQQOolWOPhWMul2MOyL9Tv5CInjMx+ZbbBd8vgWuhxCJ1mIvU0n/XCjHH+dO1rdSMfca7qcHKEjLdGUrytlOrdD8HQPHB1zr+lyUlXP4nS8djumczsEj/vAwY6V5y5nMhpPmgU6dZ9XDG7HRCMowdO5kMOxAThwyUsef44up936tPuLgFIf+LxicDtLN26z4r0APN8+9QB3tRIEMJvO4USCS/a4Lqdz6NDtNMde2HI+EXa1vgvAwwLCawUQ/2fLw8Z3qSLBHS8a9f58s5Zb5YSOogaf3WXNe4nqeDjutCkAGCA2WYfT6npROcbaV5dD6CgINnnJenvi82aD6DPe53mQv/nu6QeNVhrPFubleJ48jlTrGDoy++w9eLD16eFh91YK83AQTtmSv7lyI/UvEoObd/EDSgmtVJwO3U5kmzfvNF67E7/AbUlya3c3loVTV68PhlWqvFCFzrTvK4njapast6PYC+/DpwscR8V8s+He0N3oPv5XRYtGnww3Haj00CqMoFR+yuXLl98JnqpcTyH++8oT4fwbU0KY9+u3P/EGNiYHb6l+Hre+WqfLuRpa3ZGH02GINctGmywazBJWuTp/GbBB3gY7dTYDp5nH2UngXNUOlf+oR/WnBW7n38HTENdVbtU+/aD210Vp/c2KW/gAzrE/bQgBiXku6J63uWAN9TbnDu8XM/XdYU2SG19AO32ee9xKQ7NHk3YLnZeCp3Gua1O6e3zwrbq89qnytypyILO3k7GlixMJbLpRAMezQbgK4NiYr2kn5HF+tfHPvBFi0VAAnEfydjorhMed5630w8QL4lTwzawlrHpymxh4RK3SFfOWMf40SRGAcK62TgcER3MhCJ9cBE187W7Z+i5vgGs1qto61ZPlpwbgeR8/nOt7VSjSK7oEP0vyGDf10eq9mW5mhGCAz42rRsS8AEB5FrghFEW49FPwuPDZIWdCp6TPgonjOVJKIHcKnYcFk8pzbnIkPIu8mXCRq4IAuz15FM4BRPOWLRc33HW3uK6/eYP1JbyHi19+EYCu2ZCKRDCg5zpgWq3J7QH8CZw5Gg+g83Ih0JHgYUJZI3iyWHlU6x6t3scPpAAhpwb4o16LmqPF7WbntIR3J1QTCgVAPgnffLgg8wZP1srjk++9xg8jJTSKqsrh4H4+dlT8IseF4HNrF5ISOImqZQFOp04H3nIKdON6F+t40GiqOvISIQ1em7oKCoSDSJYDNirAwOd3Mcw9NRPd+DOBk6rhtF6rrqEjwcPt84LBg/zBb/Z8qvzfo5jO5kI6XcL8I9Ql5VEWgHAV4kCutmoEwHkg6//UKXS4fV4weLIkj6NCQN9hA1fI0RJaVQmgc1ALdCR42I9VEHiy1oG0KgT0RXCEGJxF2LjhcsLQt4sXZXiVoCi5DIBkzUVkSx5v9xY4qApGCErgGFGt0/+xY+jIHosa1z4ZPHAs6JlSVZah3nBTM/UJ79YVYF72xz1sQzAnFAPu0Q4duh11oUkTzYEqoUKWA9pO7t3uZBtBt8CBg+T8GqPq6r7v6fbVmdtRF1oCkOdpB4osyWMfCwE73b5GOQG2wfGM2pzZ4SiS0Gj/mH/n3WLByFruVqW7nDu6+QF5QIc7WRmEkOjYK0/M2d7Omjw2PUzMduAAygg9zxzYl9kNoq5nYPRJjq1orY52rHKFjgTPm8HTGD8PdcV7pHBDoadH9RvWx0JAVRcIqP848WIuTbjNcPc5wueqOt6xKgI6rFLuMNzCTB5UzWbJ5fhWCKg61gP1Sife2JR7ngvh17LAhbLRs3uXkxt0JHhYpaxBuoeHmRZu+Nu2p49pKXq2Edsh1Id06YQOvgYmBTvQC5VvhYDLa/9IDTt1zDQieNRGkSqtY17vSHaa0ukUKN8KAVH8ZwtwIIRtyKV5eJ78eF7AydXpxBwPRtxViIh81clEQJelMhPaVKiZdV6145qWLmcmt/Ur4E1yF6sAYUfGp0LABavXJd7U2BLHmphQ8zx5b86SH8sTOIVAR87W2EFMUN0IW9VJOvH6JqMQRo2Uq+eKZVCjm3YHbeGVDLGYVC5A+HbHdEBXT1FQVdogelvqlLLOPHJQmQd0mQqvoqQyw6ychaQq+riQT0DtismTRovUTSkNskio2yAk9UvsdsaLAE5h0JHgQXEFT44oQMh1oFgO37Lots7Sxe6C+laNJLo9mwojT2vaOdOsqSynO1gRXs0Ks6YEK5ULV3Qsb/MQO7d7su788ETbv1M5SFC3VvztX2Xbycql8li704mFWVUiQY/7QY8QmkZxE2CUBppIo9MPnHE5K0cS//7sYfvCGXSwl0g7igRO4U4n5nh4MqhBoZgN7gcJ2KSjVkyCBs2czVNGk5s6p/7nLuvef5ZTO2wPq0QzeTxT5IvM0/TLVBlmmRPK9vFYEoNQdNQvTubUBSK4LuxM4cwpzK5RPRomHkLauGv3U3lOMh0tGjjaoINfJHA7AA8TyxZB6KZZ//68DBOicOESBl7JY1igVgOw4jC58s9BqDdf/nN4wF3wz3juNu9h6zHF0YF9jquw3SpTTifczQrAg6JBbqVbqii04aBz79QocrdqzpeUbpqKZtEgRVF2CL1VVZ0vqBU6sd2saX7WFGWFqnl2kNvodKLeLIZYVPZcwLLlXIR8tUMW8WpVr4nfVDaR1fiZU1lk6ykNjubAJoP78A8mXrjX1G8c/MK/F8zvUBmVVjxoQvGdO0eE9EbF1Iv3Gv7lK4L5HcpxV9HnntOp6KjHsRI68hev8FaiVJX1bHgd78exvquqrnocW51OlFiu8naiVISiRptCrH7LIJiiWhFDuZyDjgQPFoLTBikl3fSQHaM8MM/IoYP4GjKPaly9tqyIzKTXeEtR6dB5zAq3kzZS1SJhw8aahuteyxZnTHBHi1LQ0o3bjL4+oOeIywl3qkwmjq2GTiyxTPBQiQq75tebcRpocB18dheBUxKnEwcPt9KplPBmi5FRrYObd1lbqNgCOEdse2O9Nq4WwUNlCbN0FudhImP/yDoXlqZqI3CshY4EzxGCh0oTamRwvnjRjicMqQLgOJLHqZroqVK+t21fvcuXL98TPDUEpw5SKSpqaDucFICTZcqhYeDssfkN9riwigQPpSqMYsVxw3kcUwN3MzC60aX5x9YDxxnoEDxUVmH06kx9oqPjeCLYLAoeDrU4OAEcp6BD8FCdKDoP7Pxnh8IZy+3mLKPuBgPjb1x5vyuJYieB4xx0CB6Kchs4TkKH4KGoUNPC8l2qUkFHgmeFaB5pM8zrj/IQOBVb63BKCx0JngHpeAgeisBxRL0ur36scpmH+FE+CD2JQy4Dx3noROAJHo8IjsWgyq26sLB507vwqkW4tYHwoUqomi0DuAid1uBZI78VuLNFlUHObYl7Bx0JHu5sUa7L+YRxO/WW8dOSx6RWGGpRjqoUCWOvoCPBMyPjYB5hTLkkHPX72zIkjL0Kr1qEW/fIcGuI1zRlcTjlZIUxnU5r1wObOsxwi7JUDVyfPgDHG+jMCreqgtMIKXs0HlyXD8g8pB/3oo+fstzdguup8JqnDGkqeIyWNVlMpzPX9XyNbxfRTDLT9VC6tUOGU0e8vP98//TpeijN7gbJ4oM+L0Kv71cBXQ+lScjd3OE7cOh05rqeAWl9q1wNKic18IXmayhF6KjDZ40MuYa4GlSHmpaw2cOlYHilEnIdhBVmyEV1GkqJZhsDgUOn03HINS7YTkGlqy7dzddcCjqdblwPigr/IEOtGleEaqGGaHaEP0Lg0OkU4XzWSOdT4Wp4rynBLXA6HQ3O56DcYq/IbzjKX9hwC5xOh86HKjyMqjFBTOjYAp8VEj5VrkYpYTNOV0Po2AwfgAe7XZzT7LZqojlUi4V9hI4T8MFW+6iED2c1u6OpGGxmuByEjqsAWiPdzyjdj7VCjU3Nl0FahA7dD2XO1aDXrs76GkLHBwCtiAFoiCuiFTSRq2GuhtDxFkD3SACN0gERNIQOZcoB4VHhinSsSQmaOkFD6FDqABqQ4KlICDEMS3YzDfmoc+eJ0KHyc0ERhIY9D8UiyMDRNOhmCB1KnxMangWhMrqh6Qgu8nmSu02EDmUfiCIARX92pT6oIV1M5GSmCBhCh3IXSGvkHyuznoc0OaTIsQj5PB1/Zh6G0KH8dkpxLRZq+aPIoVzz7+hUqLj+X4ABAAW22X2zqIf0AAAAAElFTkSuQmCC';\n return logo;\n}", "function DrawIcon( position : Vector2 ){\n\t\t//do a bunch of null checks\n\t\tif(manager == null)\n\t\t\treturn;\n\t\tif(manager.commandElementImg == null)\n\t\t\treturn;\n\t\tif(icon == null)\n\t\t\treturn;\n\t\t\t\n\t\tvar elmRect = Rect( position.x-24, position.y-24, 48, 48 );\n\t\tvar iconRect = Rect( position.x-20, position.y-20, 40, 40 );\n\t\tGUI.color = color;\n\t\tGUI.DrawTexture( elmRect, manager.commandElementImg, ScaleMode.StretchToFill );\n\t\tGUI.DrawTexture( iconRect, icon, ScaleMode.StretchToFill );\n\t\tGUI.color = Color.white;\n\t}", "function createIconBackground(size) {\n //create new canvas\n var iconBackgroundCanvas = document.createElement('canvas');\n iconBackgroundCanvas.width = size;\n iconBackgroundCanvas.height = size;\n var context = iconBackgroundCanvas.getContext('2d');\n\n //set icon background color\n context.fillStyle = iconBackground;\n\n //draw circle or square icon depending on setting\n if (shapePicker.value == 'circle') {\n context.arc(size / 2, size / 2, size / 2, 0, 2 * Math.PI);\n context.fill();\n } else {\n context.fillRect(0, 0, size, size);\n }\n\n return iconBackgroundCanvas;\n}", "function createIconWrapper(i, locationObject) {\n let tempIcon = locationObject.siteIcon;\n let tempName = locationObject.siteName;\n let tempURL = locationObject.url;\n let wrapper = \"\";\n if (tempURL === null) {\n // DISPLAY NONE\n wrapper = `<a href=\"${tempURL}\" class=\"iz-i m-s d-n\">\n <img src=\"${tempIcon}\" alt=\"${tempName}\" title=\"${tempName}\" class=\"br bd-g e-g-hv h-f w-f s-hv d-n\">\n </a>`;\n }\n else {\n wrapper = `<a href=\"${tempURL}\" class=\"iz-i m-s\">\n <img src=\"${tempIcon}\" alt=\"${tempName}\" title=\"${tempName}\" class=\"br bd-g e-g-hv h-f w-f p-s s-hv\">\n </a>`;\n }\n return wrapper;\n }", "function init() {\n var img = new Image();\n img.name = url;\n img.onload = setDimensions;\n img.src = url;\n }", "function afiCreateImage( $imageContainer, $deleteImage, $uploadImage, json, inputField){\n\t\t$imageContainer.append( '<img src=\"' + json.url + '\" alt=\"' + json.caption + '\" style=\"max-width: 100%;\" />' );\n\t\tinputField.val( json.url );\n\t\t$deleteImage.removeClass( 'hidden' );\n\t\t$uploadImage.addClass( 'hidden' );\n\t}", "function generatePictureHtml(content){\n return \"<a href=\\\"\" + content + \"\\\" target=\\\"_blank\\\">\" + content + \"</l>\" +\n \"<br>\" +\n \"<img class=\\\"chat-photo\\\" src=\\\"\" + content + \"\\\" target=\\\"_blank\\\">\";\n}", "get icon_url() {\n return this.args.icon_url;\n }", "function makeMarkerIcon(markerColor) {\n var markerImage = {\n url: 'https://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +\n '|40|_|%E2%80%A2',\n size: new google.maps.Size(21, 34),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(10, 34),\n scaledSize: new google.maps.Size(21, 34)\n };\n return markerImage;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Walks entirety of an html node's downstream tree and returns Set of nodes it finds. root is node | null found is Set of matching nodes
function crawlNode(root, found = new Set()) { const predicate = (node) => node && node.tagName === 'VIDEO' if (!root || !root.childNodes) { return found } if (predicate(root)) { found.add(root) } return Array.from(root.childNodes).reduce((acc, node) => { if (predicate(node)) { return crawlNode(node, new Set([...acc, node])) } else { return crawlNode(node, acc) } }, found) }
[ "function findAndAdd(n, matches) {\n\tif (! n || ! n.parentNode) return;\n\tif (! matches) matches = function(n) { return true; };\n\tvar df = document.createDocumentFragment();\n\tcollectNodes(n, matches, df);\n\t// for (var i=0; i<df.childNodes.length; i++) {\n\t//\tconsole.log(df.childNodes[i]);\n\t// }\n\tn.parentNode.appendChild(df);\n}", "find(value){\n const go = (value, node, parent, depth) => {\n if(node === null) return [false, null, null, null];\n else if(value === node.value) return [true, node, parent, depth];\n else\n return value < node.value ? go(value, node.left, node, ++depth) : go(value, node.right, node, ++depth);\n };\n return go(value, this.root, null, 0);\n }", "function getNodes(ns, mode, tagName){\n var result = [], ri = -1, cs,\n i, ni, j, ci, cn, utag, n, cj;\n if(!ns){\n return result;\n }\n tagName = tagName || \"*\";\n // convert to array\n if(typeof ns.getElementsByTagName != \"undefined\"){\n ns = [ns];\n }\n\n // no mode specified, grab all elements by tagName\n // at any depth\n if(!mode){\n for(i = 0, ni; ni = ns[i]; i++){\n cs = ni.getElementsByTagName(tagName);\n for(j = 0, ci; ci = cs[j]; j++){\n result[++ri] = ci;\n }\n }\n // Direct Child mode (/ or >)\n // E > F or E/F all direct children elements of E that have the tag\n } else if(mode == \"/\" || mode == \">\"){\n utag = tagName.toUpperCase();\n for(i = 0, ni, cn; ni = ns[i]; i++){\n cn = ni.childNodes;\n for(j = 0, cj; cj = cn[j]; j++){\n if(cj.nodeName == utag || cj.nodeName == tagName || tagName == '*'){\n result[++ri] = cj;\n }\n }\n }\n // Immediately Preceding mode (+)\n // E + F all elements with the tag F that are immediately preceded by an element with the tag E\n }else if(mode == \"+\"){\n utag = tagName.toUpperCase();\n for(i = 0, n; n = ns[i]; i++){\n while((n = n.nextSibling) && n.nodeType != 1);\n if(n && (n.nodeName == utag || n.nodeName == tagName || tagName == '*')){\n result[++ri] = n;\n }\n }\n // Sibling mode (~)\n // E ~ F all elements with the tag F that are preceded by a sibling element with the tag E\n }else if(mode == \"~\"){\n utag = tagName.toUpperCase();\n for(i = 0, n; n = ns[i]; i++){\n while((n = n.nextSibling)){\n if (n.nodeName == utag || n.nodeName == tagName || tagName == '*'){\n result[++ri] = n;\n }\n }\n }\n }\n return result;\n }", "function fetchTags(xmlDoc,nodeType)\n {\n var node = xmlDoc.documentElement;\n var nodes = node.querySelectorAll(\"*\");\n var childrenNodes =[];\n for (var i = 0; i < nodes.length; i++) \n {\n var text = null;\n if (nodes[i].childNodes.length == 1 && nodes[i].childNodes[0].nodeType == nodeType) //if nodeType == text node\n if(doesNotExist(nodes[i].tagName,childrenNodes))\n childrenNodes.push(nodes[i].tagName);\n }\n return childrenNodes;\n }", "*elements(root) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n for (var [node, path] of Node$1.nodes(root, options)) {\n if (Element$1.isElement(node)) {\n yield [node, path];\n }\n }\n }", "function findForward(node, callback) {\n if (callback(node))\n return node;\n for (var i=0; i < node.children.length; i++) {\n foundNode = findForward(node.children[i], callback);\n if (foundNode)\n return foundNode;\n }\n return null;\n}", "inOrder() {\r\n\r\n let resultsArr = [];\r\n\r\n let _walk = node => {\r\n if (node.left) _walk(node.left);\r\n resultsArr.push(node.value);\r\n if (node.right) _walk(node.right);\r\n }\r\n\r\n _walk(this.root);\r\n\r\n return resultsArr\r\n}", "function filteredElements(nodeList) {\n var filtered = [];\n for (var i = 0; i < nodeList.length; i++) {\n var node = nodeList[i];\n if (node.nodeType !== 3) { // Don't process text nodes\n var $element = $(node);\n if ( $element.closest('.ant,.ant_indicator,.ant-custom-cta-container').length === 0 ) {\n filtered.push($element);\n }\n }\n }\n return filtered;\n }", "function walkDom(n) {\n do {\n console.log(n); // can use document.write instead\n if (n.hasChildNodes()) {\n walkDom(n.firstChild)\n }\n } while (n = n.nextSibling)\n}", "getElements() {\n const result = new Set();\n for (const item of this.leftSide.concat(this.rightSide))\n item.getElements(result);\n return Array.from(result);\n }", "findTheme(search) {\n if (typeof search== \"string\") search={id: search};\n if (!search) {\n return this.treeMum.getChild();\n }\n function innerFind(search, myTree) {\n if (!myTree) return;\n if (Object.entries(search).every(srch=>Object.entries(myTree.props).find(src=>srch[0]==src[0] && src[1]==srch[1]))) {\n return myTree;\n }\n for (const child of myTree.getRelationship(\"descendents\").children) {\n let result=innerFind(search, child);\n if (result) return result;\n }\n }\n return innerFind(search, this.treeMum.getChild());\n }", "textNodes(...args) {\n let filter = \"\", i = 0, a = [], recursive = false;\n $sel = $();\n while(arguments[i]){\n if (typeof arguments[i] === \"string\"){\n filter += (filter) ? \"|\" : \"\";\n filter += arguments[i];\n }else if (Array.isArray(arguments[i])){\n\t\t\t\t\tfilter += (filter) ? \"|\" : \"\";\n\t\t\t\t\tfilter += arguments[i].join(\"|\");\n\t\t\t\t}\n i++;\n }\n lastArg = arguments[arguments.length-1];\n if(typeof lastArg === \"boolean\" && lastArg) {recursive = true;}\n that = (recursive) ? this.find(\"*\").addBack() : this;\n that.each(function() {\n $sel = $sel.add($(this).contents());\n });\n $sel.each(function(){\n if(filter){\n reg = new RegExp(filter);\n }\n keep = (this.nodeType === 3 && (!filter || this.textContent.search(filter)+1)) ? true : false;\n if (keep) a.push(this);\n });\n $sel = $(a);\n $sel.prevObject = this;\n $sel.selector = filter;\n return $sel;\n }", "function findMatch(node, params) {\n\n var nodeValue = node.nodeValue.trim();\n var nodeIndex = params.nodeIndex;\n var searchTerm = params.searchTerm;\n var searchElements = params.searchElements;\n var field = params.field;\n var total = params.total;\n var count = params.count;\n var text = params.text;\n var currentIndex = params.currentIndex;\n\n if (text === \"\") {\n text = nodeValue;\n } else {\n text += \" \" + nodeValue;\n }\n console.log(\"nodeIndex: \" + nodeIndex + \" - \" + nodeValue);\n console.log(textNodes[nodeIndex]);\n\n // if searchTerm is found, current text node is the end node for one count\n var index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n\n // if there is multiple instances of searchTerm in text (loops through while loop), use oldStartIndex to calculate startIndex\n var oldStartIndex, startNodeIndex;\n\n // stores the number of characters the start of searchTerm is from the end of text\n var charactersFromEnd = text.length - index;\n //console.log(\"charactersFromEnd: \" + charactersFromEnd);\n\n // loop through text node in case there is more than one searchTerm instance in text\n while (index !== -1) {\n currentIndex = index;\n\n // remember how many text nodes before current node we are pulling from textNodes\n var textNodesBackIndex = nodeIndex - 1;\n console.log(textNodesBackIndex);\n\n // textSelection will contain a combined string of all text nodes where current searchTerm spans over\n var textSelection = nodeValue;\n var startNode;\n\n // set textSelection to contain prevSibling text nodes until the current searchTerm matches\n while (textSelection.length < charactersFromEnd) {\n console.log(\"textSelection.length: \" + textSelection.length + \" < \" + charactersFromEnd);\n //console.log(\"old textSelection: \" + textSelection);\n console.log(\"textnodesback index: \" + textNodesBackIndex + \" \" + textNodes[textNodesBackIndex].nodeValue);\n\n textSelection = textNodes[textNodesBackIndex].nodeValue.trim() + \" \" + textSelection;\n //console.log(\"space added: \" + textSelection);\n textNodesBackIndex--;\n }\n\n // use old startNodeIndex value before re-calculating it if its the same as new startNodeIndex\n // startIndex needs to ignore previous instances of text\n var startIndex;\n if (startNodeIndex != null && startNodeIndex === textNodesBackIndex + 1) {\n // find index searchTerm starts on in text node (or prevSibling)\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase(), oldStartIndex + 1);\n } else {\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase());\n }\n oldStartIndex = startIndex;\n\n // startNode contains beginning of searchTerm and node contains end of searchTerm\n var startNodeIndex = textNodesBackIndex + 1;\n // possibly null parentNode because highlighted text before, adding MARK tag and then removed it\n startNode = textNodes[startNodeIndex];\n //console.log(\"final textSelection: \" + textSelection);\n\n if (startIndex !== -1) {\n // set parent as first element parent of textNode\n console.log(\"end parent\");\n console.log(node);\n var endParent = node.parentNode;\n\n console.log(\"start parent\");\n console.log(startNode);\n var startParent = startNode.parentNode;\n\n var targetParent;\n // start and end parents are the same\n if (startParent === endParent) {\n console.log(\"start parent is end parent\");\n targetParent = startParent;\n }\n // start parent is target parent element\n else if ($.contains(startParent, endParent)) {\n console.log(\"start parent is larger\");\n targetParent = startParent;\n }\n // end parent is target parent element\n else if ($.contains(endParent, startParent)) {\n console.log(\"end parent is larger\");\n targetParent = endParent;\n }\n // neither parents contain one another\n else {\n console.log(\"neither parent contains the other\");\n // iterate upwards until startParent contains endParent\n while (!$.contains(startParent, endParent) && startParent !== endParent) {\n startParent = startParent.parentNode;\n //console.log(startParent);\n }\n targetParent = startParent;\n }\n\n // set startNode to node before the parent we are calculating with\n if (textNodesBackIndex !== -1) {\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n\n var startElement = startNode.parentNode;\n\n // continue adding text length to startIndex until parent elements are not contained in targetParent\n while (($.contains(targetParent, startElement) || targetParent === startElement) && textNodesBackIndex !== -1) {\n startIndex += startNode.nodeValue.trim().length + 1;\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n startElement = startNode.parentNode;\n }\n }\n\n // find index searchTerm ends on in text node\n var endIndex = startIndex + searchTerm.length;\n /*console.log(\"start index: \" + startIndex);\n console.log(\"end index: \" + endIndex);*/\n\n // if a class for field search already exists, use that instead\n var dataField = \"data-tworeceipt-\" + field + \"-search\";\n if ($(targetParent).attr(dataField) != null) {\n console.log(\"EXISTING SEARCH ELEMENT\");\n console.log($(targetParent).attr(dataField));\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: parseInt($(targetParent).attr(dataField)),\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n } else {\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: count,\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n console.log(\"NEW SEARCH ELEMENT\");\n $(targetParent).attr(dataField, count);\n console.log($(targetParent));\n }\n\n console.log(searchElements[count]);\n\n count++;\n } else {\n console.log(textSelection);\n console.log(searchTerm);\n }\n\n index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n charactersFromEnd = text.length - index;\n //console.log(\"characters from end: \" + charactersFromEnd);\n\n if (total != null && count === total) {\n console.log(\"Completed calculations for all matched searchTerms\");\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: false\n };\n }\n }\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: true\n };\n}", "parent() {\n\t const parents = [];\n\t this.each(el => {\n\t if (!parents.includes(el.parentNode)) {\n\t parents.push(el.parentNode);\n\t }\n\t });\n\t return new DOMNodeCollection(parents);\n\t }", "function Siblings(thi,depth,maxParent){\n\tvar depth=depth||1;\n\tvar maxParent=GetElement(maxParent)||document.body;\n\tvar d=0;\n\tvar parent=GetElement(thi);\n\t\n\tif(!parent)\n\t\treturn [];\n\t\n\twhile(d<depth&&parent!==maxParent){\n\t\tparent=parent.parentNode;\n\t\td=d+1;\n\t}\n\t\n\tvar chi=[[parent]];\n\twhile(d>0){\n\t\tvar sib=[];\n\t\tLast(chi).map(function(c){sib=sib.concat(Array.from(c.childNodes).filter(function(n){return n.nodeName!==\"#text\"}))})\n\t\tchi.push(sib);\n\t\td=d-1;\n\t}\n\treturn Last(chi);\n}", "verifyUndeclared() {\n for (const [nodeID, node] of Object.entries(this.nodes)) {\n for (const desc of node.descendants) {\n if (desc.type === \"noderef\") {\n if (this.nodes[desc.id] == null) {\n return desc.id\n }\n }\n }\n }\n return null\n }", "get nodelist() {\n\t\treturn this.nodes.values();\n\t}", "function findAllWords(node, arr) {\n // base case, if node is at a word, push to output\n if (node.end) {\n arr.unshift(node.getWord());\n }\n\n // iterate through each children, call recursive findAllWords\n for (var child in node.children) {\n findAllWords(node.children[child], arr);\n }\n}", "getInorderSuccessor(node) {\n if(node == null || node.left == null)\n return node;\n return this.getInorderSuccessor(node.left);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the rating buttons to posts where the most received rating is known
function addRatingButtons( ratings ) { var postLinkSections = document.getElementsByClassName( "postlinking" ); var icons = { "agree": "tick", "disagree": "cross", "funny": "funny2", "winner": "winner", "zing": "zing", "informative": "information", "friendly": "heart", "useful": "wrench", "optimistic": "rainbow", "artistic": "palette", "late": "clock", "dumb": "box", "oify pinknipple": "nipple", "lua helper": "lua_helper", "lua king": "lua_king", "smarked": "weed", "programming king": "programming_king", "mapping king": "mapping_king" }; var messages = { "agree": "This user is usually agreed with.", "disagree": "This user doesn't have a popular opinion.", "funny": "This user is funny!", "winner": "This user is a true winner.", "zing": "This user is witty.", "informative": "This user knows what's up!", "friendly": "This user is a bro.", "useful": "This user helps people out.", "optimistic": "This user is very optimistic.", "artistic": "This user is artistic.", "late": "This user lives under a rock.", "dumb": "This user is packed with an extra chromosome.", "oify pinknipple": "This is the hottest user on the web.", "lua helper": "This user aids others in making Lua aimbots.", "lua king": "This user excels at making Lua aimbots.", "smarked": "This user wanted to post, but then they got high.", "programming king": "This user is quite possibly a computer hacker.", "mapping king": "This user is good with a hammer." }; for ( var i in postLinkSections ) { if ( ratings[i] == "null" ) continue; var icon = icons[ ratings[i] ]; var message = messages[ ratings[i] ]; var container = postLinkSections[i]; var eventLogButton = container.getElementsByTagName( "a" )[0]; var button = document.createElement( "img" ); button.src = "/fp/ratings/" + icon + ".png"; button.alt = button.title = message; if(icon == 'funny2'){ button.width = 15; button.height = 15; } else { button.width = 16; button.height = 16; } button.style.marginRight = "2px"; button.style.cursor = "pointer"; var userid = eventLogButton.getAttribute( "onclick" ).match( /[0-9]+/ ); button.setAttribute( "onclick", "document.location = 'javascript:void(OpenURLInBox( \"ratinginfo_" + userid + "\", \"http://dev.vertinode.nl/fpratings.php?uid=" + userid + "\" ));';" ); container.insertBefore( button, eventLogButton ); } }
[ "function populateRatingElements(selector, value)\n {\n selector.children(base.options.elementType).each(function()\n {\n if (IsNullOrEmpty(value) || $(this).data(\"data-count\") > value)\n {\n $(this).css(base.options.ratingCss);\n }\n else\n {\n $(this).css(base.options.ratingHoverCss);\n }\n });\n }", "listenNewLikes() {\n document.querySelectorAll(\"article button\").forEach(likeBtn => {\n likeBtn.addEventListener('click', () => {\n this.totalLikes++;\n this.querySelector(\"aside span\").innerHTML = this.totalLikes + \" ❤️\";\n })\n })\n }", "function markRating(rating) {\n\n\t\t// Save off the the rating type\n\t\tvar negVote = rating.hasClass('downvote'),\n\t\tmoreInfo = false,\n\t\tupdown = \"1\";\n\t\tactionType = $('#ratings').attr('data-type');\n\n\t\t// Check to see if the needs improvement was check to flag if the additional info\n\t\t// function needs to be called\n\t\tif (negVote) {\n\t\t\tmoreInfo = true;\n\t\t\tupdown = \"-1\";\n\t\t}\n\n\t\trating.addClass('vote');\n\t\totherRatingWidth = rating.siblings('a').width();\n\t\trating.siblings('a').off('click').animate({opacity: 0, width: 0 }, {duration: 650, queue: false, complete: addChangeRating(rating, otherRatingWidth, moreInfo)})\n\n\t\t// Set the rating cookie.\n\n\t\t// Post the rating made.\n\t\tpostRating(updown, actionType);\n\n\n\t\t// Chekc to see if negitive vote was false. If so then we want to show the thank you message\n\t\tif (!negVote) {\n\t\t\tshowThanks();\n\t\t}\n\n\t}", "function adjustRating() {\n if(newRestroom.rating === 1) {\n newRestroom.rating += 1;\n } else if(newRestroom.rating === -1){\n newRestroom.rating -= 1;\n }// end if\n console.log('current rating: ', newRestroom.rating);\n }//end adjustRating", "function showNewPostVotes(singlePostElement,userOptionIndex) {\n\t\t\nsinglePostElement.find(\".votesContainer\").show();\n\nvar oldVotesNewNum = parseFloat(singlePostElement.find(\".vote_holder .totalVotesNumber[data-user-vote='true']\").attr(\"data-votes-number\")) - 1;\nvar newVotesNewNum = parseFloat(singlePostElement.find(\".vote_holder[data-option-index='\" + userOptionIndex + \"']\").find(\".totalVotesNumber\").attr(\"data-votes-number\")) + 1;\n\nsetNewNumber(singlePostElement.find(\".vote_holder .totalVotesNumber[data-user-vote='true']\"),\"data-votes-number\",false,false,\" Vote\" + (oldVotesNewNum == 1 ? \"\" : \"s\"));\t\nsinglePostElement.find(\".vote_holder\").find(\".totalVotesNumber, .votesIcon\").attr(\"data-user-vote\",\"false\");\t\nsinglePostElement.find(\".vote_holder[data-option-index='\" + userOptionIndex + \"']\").find(\".totalVotesNumber , .votesIcon\").attr(\"data-user-vote\",\"true\");\t\nsetNewNumber(singlePostElement.find(\".vote_holder .totalVotesNumber[data-user-vote='true']\"),\"data-votes-number\",true,false,\" Vote\" + (newVotesNewNum == 1 ? \"\" : \"s\"));\t\n\nif(singlePostElement.attr(\"data-post-type\") != \"1\") {\nsinglePostElement.find(\".votesIcon i\").html(singlePostElement.attr(\"data-negative-icon\"));\t\nsinglePostElement.find(\".votesIcon[data-user-vote=true] i\").html(singlePostElement.attr(\"data-positive-icon\"));\t\n} \n\nvar allVotesNumber = 0;\nsinglePostElement.find(\".votesContainer\").each(function(){\n// just for the worst case scenario. we check if the data-votes-number actually exists.\nif(typeof $(this).find(\".totalVotesNumber\").attr(\"data-votes-number\") != \"undefined\") {\nallVotesNumber += parseFloat($(this).find(\".totalVotesNumber\").attr(\"data-votes-number\"));\n}\t\n});\n\n// now recalculate the percentages.\nsinglePostElement.find(\".votesContainer\").each(function(){\n// just for the worst case scenario. we check if the data-votes-number actually exists.\nif(typeof $(this).find(\".totalVotesNumber\").attr(\"data-votes-number\") != \"undefined\") {\n$(this).find(\".totalVotesPercentage\").html(Math.round((parseFloat($(this).find(\".totalVotesNumber\").attr(\"data-votes-number\")) / allVotesNumber) * 100) + \"%\");\n// give a new height to the votesLine.\nvar newVotesLineHeight = Math.round(parseFloat($(this).find(\".totalVotesNumber\").attr(\"data-votes-number\")) / allVotesNumber) * parseFloat($(this).find(\".votesLineContainer\").attr(\"data-max-height\")) + \"px\";\n$(this).find(\".votesLineContainer\").css(\"height\",newVotesLineHeight);\n}\t\n});\n\n// re-style majorities and minorities\nsinglePostElement.find(\".votesIcon, .votesLine\").removeClass(\"majorityVoteBackgroundColor\").addClass(\"minorityVoteBackgroundColor\");\nvar majorityVotes = getMajorityVoteIndex(singlePostElement);\nfor(var i = 0;i < majorityVotes.length;i++) {\nsinglePostElement.find(\".vote_holder[data-option-index='\" + majorityVotes[i] + \"'] .votesIcon, .vote_holder[data-option-index='\" + majorityVotes[i] + \"'] .votesLine\").removeClass(\"minorityVoteBackgroundColor\").addClass(\"majorityVoteBackgroundColor\");\t\n}\n\n\n}", "function addToCount() {\n totalButtonsPressed++;\n recentButtonsPressed++;\n}", "function toggleRating(id) {\n\tvar other = 1 - id;\n\t$(\"#\" + id).toggleClass(\"btn-primary\");\n\t// If the rating was removed (the button was set to default)\n\tif ($(\"#\" + id).attr(\"class\") == \"btn btn-default likedislike\") {\n\t\t$(\"#\" + other).removeAttr(\"disabled\");\n\t} else { // The rating was added\n\t\t$(\"#\" + other).prop(\"disabled\", \"disabled\");\n\t}\n}", "function appendVoteButtons(a_Parent, a_SongHash, a_RatingCategory, a_Class)\n{\n\tvar div = document.createElement(\"div\");\n\tdiv.setAttribute(\"class\", \"voteContainer\" + a_Class);\n\tvar i;\n\tfor (i = 5; i >= 1; --i)\n\t{\n\t\tvar img = document.createElement(\"img\");\n\t\timg.setAttribute(\"src\", \"static/voteButton\" + i + \".png\")\n\t\timg.setAttribute(\"class\", \"voteButton\")\n\t\timg.setAttribute(\"OnClick\", \"vote(this, \\\"\" + a_SongHash + \"\\\", \\\"\" + a_RatingCategory + \"\\\", \" + i + \")\");\n\t\tdiv.appendChild(img);\n\t}\n\ta_Parent.appendChild(div);\n}", "function renderAnswerButtons(messageContent, messageId, question) {\n if (question.canManageQuestionState) {\n var helpfulCount = question.numHelpful;\n var maxHelpfulCount = question.totalNumHelpful;\n var helpfulCountRemaining = maxHelpfulCount-helpfulCount;\n var $parentHeader = $j(messageContent).closest('.j-thread-post').find('header');\n var $dotted = $parentHeader.find('.j-dotted-star');\n var button = $j(messageContent).find('.jive-thread-reply-btn');\n\n if ($parentHeader.find('.j-dotted-star').length == 0)\n $parentHeader.append('<span class=\"j-dotted-star j-ui-elem\"/>');\n\n if (button.length == 0) {\n $j(messageContent.append($j(\"<div>\").addClass('jive-thread-reply-btn')));\n button = $j(messageContent).find('.jive-thread-reply-btn');\n }\n\n var $helpfulStar = $parentHeader.find('.j-helpful-star');\n button.empty();\n $dotted.unbind();\n // First two conditionals: answer already marked.\n if (question.correctAnswer && messageId == question.correctAnswer.ID) {\n button.append(jive.discussions.soy.qUnmarkAsCorrect({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-correct-unmark').click(function() {\n questionSourceCallback.unMarkAsCorrect(messageId, that.renderAll);\n return false;\n });\n }\n else if (question.helpfulAnswers && (containsAnswer(question.helpfulAnswers, messageId))) {\n button.append(jive.discussions.soy.qUnmarkAsHelpful({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-helpful-unmark').click(function() {\n questionSourceCallback.unMarkAsHelpful(messageId, that.unMarkAsHelpful.bind(that, $j(button)));\n return false;\n });\n $helpfulStar.click(function(e) {\n questionSourceCallback.markAsCorrect(messageId, that.renderAll);\n e.preventDefault();\n })\n }\n // Answer not marked.\n else {\n if (question.questionState!='resolved' &&\n !(question.helpfulAnswers && (containsAnswer(question.helpfulAnswers, messageId)))) {\n button.append(jive.discussions.soy.qMarkAsCorrect({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-correct').add($helpfulStar).click(function() {\n questionSourceCallback.markAsCorrect(messageId, function(question) {\n that.renderAll(question);\n jive.dispatcher.dispatch(\"trial.updatePercentComplete\");\n });\n return false;\n });\n }\n if (helpfulCountRemaining>0) {\n button.append(jive.discussions.soy.qMarkAsHelpful({question:question, i18n:i18n}));\n button.find('.jive-thread-reply-btn-helpful').add($dotted).click(function() {\n questionSourceCallback.markAsHelpful(messageId, that.markAsHelpful.bind(that, $j(button)));\n return false;\n });\n\n }\n }\n\n\n\n\n\n }\n }", "function ButtonUI_R() {\n\tthis.y = 10;\n\tthis.x = 10;\t\n\tthis.width = imgw;\n\tthis.height = imgh;\n\n\tthis.setx = function(x){\n\t\tthis.x = x;\n\t}\n\n\tthis.Paint = function(gr, button_n, y) {\n\t\tthis.y = y;\n\t\tvar rating_to_draw = (rating_hover_id!==false?rating_hover_id:g_infos.rating);\n\t\tthis.img = ((rating_to_draw - button_n) >= 0) ? img_rating_on : img_rating_off;\n\t\tif(button_n!=1)\n\t\tgr.DrawImage(this.img, this.x, this.y, this.width, this.height, 0, 0, this.width, this.height, 0);\n\t}\n\n\tthis.MouseMove = function(x, y, i) {\n\t\tif (g_infos.metadb) {\n\t\t\tvar half_rating_space = Math.ceil(rating_spacing/2)+1;\n\t\t\tif (x > this.x - half_rating_space && x < this.x + this.width + half_rating_space && y > this.y && y < this.y + this.height) {\n\t\t\t\trating_hover_id = i;\n\t\t\t\tif(g_cursor.getActiveZone()!=\"rating\"+i) {\n\t\t\t\t\tg_cursor.setCursor(IDC_HAND,\"rating\"+i);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t} else if(g_cursor.getActiveZone()==\"rating\"+i) {\n\t\t\t\t\tg_cursor.setCursor(IDC_ARROW,4);\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\tthis.MouseUp = function(x, y, i) {\n\t\tif (g_infos.metadb) {\n\t\t\tvar half_rating_space = Math.ceil(rating_spacing/2)+1;\n\t\t\tif (x > this.x - half_rating_space && x < this.x + this.width + half_rating_space && y > this.y && y < this.y + this.height) {\n\t\t\t\tvar derating_flag = (i == g_infos.rating ? true : false);\n\t\t\t\tg_avoid_metadb_updated = true;\n\t\t\t\tif (derating_flag) {\n\t\t\t\t\tif(g_infos.album_infos) {\n\t\t\t\t\t\tg_infos.rating = rateAlbum(0,g_infos.rating-1, new FbMetadbHandleList(g_infos.metadb))+1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tg_infos.rating = rateSong(0,g_infos.rating-1, g_infos.metadb)+1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif(g_infos.album_infos) {\n\t\t\t\t\t\tg_infos.rating = rateAlbum(i-1,g_infos.rating-1, new FbMetadbHandleList(g_infos.metadb))+1;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tg_infos.rating = rateSong(i-1,g_infos.rating-1, g_infos.metadb)+1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function set_review_count(newReviewCount) {\n Log.info('set_review_count', newReviewCount);\n update_badge(String(newReviewCount));\n\n chrome.storage.local.get('reviews_available', data => {\n const oldReviewCount = data.reviews_available || 0;\n chrome.storage.local.set({ reviews_available: newReviewCount }, () => {\n if (newReviewCount > oldReviewCount) {\n // show_notification();\n }\n });\n });\n}", "updatePriorityColors() {\n // Mutation may have been one that removes the DOM\n if (!getSidebar()) { return; }\n\n const selectedPriorities = new Set();\n this.appliedLabels.forEach(b => selectedPriorities.add(b.textContent));\n\n this.buttons.forEach(button => {\n if (selectedPriorities.has(button.id)) {\n button.classList.add(`selected-${button.id}`);\n } else {\n button.classList.remove(`selected-${button.id}`);\n }\n })\n }", "function renderButtons() {\n\n // Deleting the reactions prior to adding new reactions\n // (this is necessary otherwise you will have repeat buttons)\n $(\"#buttons-view\").empty();\n\n // Looping through the array of topics\n for (var i = 0; i < topics.length; i++) {\n\n // Then dynamicaly generating buttons for each item in the array\n var giphySearchButton = $(\"<button>\");\n // Adding a class of giphy-btn and bootstrap styles to the button\n giphySearchButton.addClass(\"giphy-btn btn btn-info\");\n // Adding a data-attribute\n giphySearchButton.attr(\"data-name\", topics[i]);\n // Providing the initial button text\n giphySearchButton.text(topics[i]);\n // Adding the button to the buttons-view div\n $(\"#buttons-view\").append(giphySearchButton);\n }\n}", "upvote(btn, upvoteNumber) {\n btn.classList.toggle('feedback__upvote-box--active');\n btn.classList.remove('feedback__upvote-box--hover');\n\n if (\n !this.increasedByOne &&\n btn.classList.contains('feedback__upvote-box--active')\n ) {\n upvoteNumber.textContent = +upvoteNumber.textContent + 1;\n this.increasedByOne = !this.increasedByOne;\n } else {\n upvoteNumber.textContent = +upvoteNumber.textContent - 1;\n this.increasedByOne = !this.increasedByOne;\n }\n }", "styleButtons () {\n // Check if it was rated\n if (this.props.wasPositive !== null) {\n // Previous rating positive\n if (this.props.wasPositive) {\n // Is this a positive rating button\n return (this.props.isPositive) ? 'green' : 'grey'\n } else {\n // Previous rating was negative\n // Is this a negative rating button\n return (!(this.props.isPositive)) ? 'red' : 'grey'\n }\n } else { // There was no previous rating\n return (this.props.isPositive) ? 'lightgreen' : 'lightred'\n }\n }", "function handle_post_buttons_actions(post) {\n let like_button = $(post).find('.like-button');\n let comment_input = $(post).find('.comment-input');\n let comment_button = $(post).find('.write-comment-button');\n let share_button = $(post).find('.share-button');\n\n handle_like_button(like_button);\n handle_comment_input(comment_input);\n handle_coment_button(comment_button);\n handle_share_button(share_button);\n}", "function ApplyRating() \n{\n $(\"div[id^='movieratingdiv']\").each(function () \n {\n var avgRating = $(this).attr('avgrating');\n if(avgRating == null)\n {\n $(this).text(\"No Rating\")\n }\n else\n {\n $(this).raty(\n {\n start: avgRating,\n readOnly: true,\n half: true\n }\n );\n }\n });\n\n $('div .moviesDiv').each(function () { $(this).corners() });\n}", "get buttons() { return getSidebar().querySelectorAll('.priority-labels button'); }", "function vote(a_Button, a_SongHash, a_VoteType, a_VoteValue)\n{\n\t// Highlight and disable the button for a while:\n\ta_Button.style.opacity = '0.5';\n\ta_Button.enabled = false\n\tsetTimeout(function()\n\t{\n\t\ta_Button.style.opacity = '1';\n\t\ta_Button.enabled = false;\n\t}, 1000);\n\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function()\n\t{\n\t\tif ((this.readyState === 4) && (this.status === 200))\n\t\t{\n\t\t\t// TODO: Update the relevant song's rating\n\t\t\t// document.getElementById(\"demo\").innerHTML = this.responseText;\n\t\t}\n\t};\n\txhttp.open(\"POST\", \"api/vote\", true);\n\txhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\txhttp.send(\"songHash=\" + a_SongHash + \"&voteType=\" + a_VoteType + \"&voteValue=\" + a_VoteValue);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Put film photo on overlay
function showFilm(item) { var displayPoster = item.children("img").attr("src"); $('#slideShow').attr("src", displayPoster); //Use movie ID to look up plot var displayID = item.children("p").first().text(); var displayTitle = item.children("h3").text(); var displayYear = item.children("p").last().text(); var omdbURLById = "https://www.omdbapi.com/?i=" + displayID + "&r=json"; $.ajax(omdbURLById, { complete: function(newXHR){ var film = $.parseJSON(newXHR.responseText); $('#overlay span').html("<p>" + "Title: " + displayTitle + "</p>" + "<p>" + "Year: " + displayYear + "</p>" + "<p>" + "Plot: " + film.Plot + "</p>"); } }); //Fade in the overlay $('#overlay').fadeIn(500); }
[ "function addOverlay() { \n imgOverlay.setMap(map);\n}", "function loadPredefinedPanorama( ) {\n\tvar evt=window.event;\n\tevt.preventDefault();\n var div = document.getElementById('container');\n\tvar PSV = new PhotoSphereViewer({\n\tpanorama: 'house.jpg',\n container: div,\n\t\ttime_anim: false,\n\t\tnavbar: true,\n\t\tsize: {\n\t\t\twidth: '45%',\n\t\t\theight: '400px'\n\t\t}\n\t});\n}", "function heri_popupCover(elm) {\n var newPic = heri_coverSize($(elm).attr('src'), 'l');\n $('div.popup-covers img.popup-cover').attr('src', newPic);\n $.facebox({div: '#comic-gn-popup'});\n}", "function displayMovieLightbox(e) { \r\n $(e).click((event)=>{\r\n let posterIndex = $(event.target).attr(\"data-index\");\r\n let index = parseInt(posterIndex, 10);\r\n let movieSlides = $('.movie-slides');\r\n $('#lightbox-b').show();\r\n movieSlides.eq(index).show();\r\n });\r\n}", "createFullElt() {\n const elt = createImgElt(`FishEye_Photos/Images/${this.src}`, this.alt);\n elt.setAttribute(\"id\", \"current-media-lightbox\");\n\n return elt;\n }", "function show_image_on_popup(image_path) {\n\tvar photo_enlarger_main_image = document.getElementById(\"photo_enlarger__photo\");\n\tphoto_enlarger_main_image.src = image_path;\n\t\n\ttoggle_photo_enlarger_display();\n}", "function showBigPhoto() {\n let target = document.querySelector('#imgTarget');\n const control = document.querySelectorAll('.control');\n\n control.forEach(element => {\n element.dataset.id = this.dataset.id;\n });\n target.src = this.dataset.src;\n photoModal.classList.toggle('show');\n\n}", "function openOverlay(e) {\n const videoWrapper =\n e.target.parentNode.parentNode.parentNode.parentNode.children[0];\n const videoWrapperInner = e.target.parentNode.parentNode;\n const mosVideo = videoWrapper.children[0];\n\n videoWrapper.style.display = \"block\";\n videoWrapperInner.style.visibility = \"hidden\";\n mosVideo.play();\n\n setIsVideoOpen(true);\n }", "function insertImageOnModal(src,alt) {\n modal.style.display = \"block\";\n modalImg.src = src;\n captionText.innerHTML = alt;\n}", "function ProjectionOverlay() {\n }", "function app(){\n //Set up the dropzone\n var dropZone = document.querySelector('#dropzone input');\n \n dropZone.addEventListener('dragenter',function(e){\n e.target.parentNode.classList.add('active');\n e.preventDefault();\n });\n \n dropZone.addEventListener('dragover',function(e){\n e.preventDefault();\n });\n \n dropZone.addEventListener('dragleave',function(e){\n e.target.parentNode.classList.remove('active');\n e.preventDefault();\n });\n\n dropZone.addEventListener('drop',function(e){\n e.target.parentNode.classList.remove('active');\n\n //# A file has been dropped, load the file\n loadFile(e.dataTransfer.files[0]);\n\n e.preventDefault();\n })\n\n //Listen to the change event of the file selector\n dropZone.addEventListener('change',function(e){\n\n //# A file has been chosen, load the file\n loadFile(e.target.files[0]);\n\n e.target.value = \"\";\n });\n\n //Listen to the click events of the close buttons on the result window\n var closeButtons = document.querySelectorAll(\".message .close\");\n for(var i = 0; i < closeButtons.length; i++){\n closeButtons[i].addEventListener('click',hideResult);\n }\n\n //Initialize the PhotoMosaic creator\n var drawArea = document.getElementById('drawArea');\n mosaicCreator = PhotoMosaic(drawArea,mosaicStarted,mosaicProgressChanged,mosaicCompleted,mosaicFailed);\n}", "function loadCustomLightbox(product, button) {\n var imgLocation;\n if (button === \"example\") {\n imgLocation = window.LightboxRoot + product + '-examples.jpg'\n } else if (button === \"moreInfo\") {\n imgLocation = window.LightboxRoot + product + '-box.jpg'\n } else if( button === \"sizing\"){\n if (product === 'hoodie' || product === 'coat') {\n imgLocation = window.LightboxRoot + 'generic-size-chart.jpg'\n } else {\n imgLocation = window.LightboxRoot + product + '-size-chart.jpg'\n }\n }\n $('#imageModalContent').attr(\"src\", imgLocation);\n $('#imageModal').modal('show');\n }", "showOverlay_() {\n this.overlay_.setAttribute('i-amphtml-lbg-fade', 'in');\n this.controlsMode_ = LightboxControlsModes.CONTROLS_DISPLAYED;\n }", "function addPicnikboxMarkup() {\n\tvar bod = document.getElementsByTagName('body')[0];\n\tvar overlay = document.createElement('div');\n\toverlay.id = 'overlay';\n\tvar pbox = document.createElement('div');\n\tpbox.id = 'picnikbox';\n\tbod.appendChild(overlay);\n\tbod.appendChild(pbox);\n}", "function setBackground(weather) {\n\tconst flickrAppID = \"a02184147893b2c40cd03d198ccd7944\";\n\tconst searchTerm = weather + \"+landscape\";\n\tconst sortMethod = \"relevance\";\n\tconst minViews = 100;\n\tconst imageSize = \"url_h\";\n\n\t$.getJSON(\"https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\" + flickrAppID +\n\t\t\t \"&text=\" + searchTerm + \"&sort=\" + sortMethod + \"&media=photos&extras=views%2C\"+ imageSize + \"&per_page=50&format=json&nojsoncallback=1\", function(data) {\n\t\t\t \tvar popularPhotos = [];\n\t\t\t \tvar index = 0;\n\t\t\t \tvar currentPhoto;\n\n\t\t\t \t// Finds the first 10 photos with the minimum number of views.\n\t\t\t \twhile(popularPhotos.length < 10) {\n\t\t\t \t\tcurrentPhoto = data.photos.photo[index];\n\t\t\t \t\tif (currentPhoto.views >= minViews && currentPhoto.hasOwnProperty(imageSize)) {\n\t\t\t \t\t\tpopularPhotos.push(data.photos.photo[index]);\n\t\t\t \t\t}\n\t\t\t \t\tindex++;\n\t\t\t \t}\n\n\t\t\t \t// Picks a random photo from the 10 selected photos.\n\t\t\t \tvar randomNumber = Math.floor(Math.random() * 10);\n\t\t\t \tvar image = popularPhotos[randomNumber];\n\n\t\t\t \t// Sets the background of the page to the selected photo.\n\t\t\t \t$(\"body\").css(\"background-image\", \"url(\" + image[imageSize] + \")\");\n\t});\n}", "function setPhotos(p){\n\t\t\tfunction setPic(sp){\n\t\t\t\tvar id=\"\";\n\t\t\t\tfor(i in sp){\n\t\t\t\t\tif(i>3)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\n\t\t\t\t\t\tid=\"#photoimg\"+i;\n\t\t\t\t\t\t$(id).css('background-image','url('+sp[i].images[i].source+')');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif(p.photos==undefined||p.photos==null)\n\t\t\t{\n\t\t\t\t$('#photoimg0').html(\"<h4>NO PHOTOS</h4>\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsetPic(p.photos.data);\n\t\t\t}\n\n\n\t\t}", "function open_overview() {\n\ton_overview=true;\n\toverview_curslide=curslide;\n\t// Add the overlay to blur the background\n\tdocument.body.insertAdjacentHTML('afterbegin','<div id=\"coverlayer\"></div>');\n\tdocument.getElementById('coverlayer').style.opacity='1';\n\tlet slideo=getSlide(curslide);\n\tlet oldpos=slideo.getBoundingClientRect(); // Remember the position of the current slide\n\t// Wrap all slides in new divs to put them in a flexbox layout, and make them thumbnails\n\tfor (let slide of slides) {\n\t\tlet element=document.getElementById(slide['id']);\n\t\tif (element.classList.contains('thumbnail')) continue;\n\t\telement.classList.add('thumbnail');\n\t\tlet wrapper=document.createElement('div');\n\t\twrapper.classList.add('wthumb');\n\t\telement.parentNode.appendChild(wrapper);\n\t\twrapper.appendChild(element);\n\t\twrapper.addEventListener('click',function() {\n\t\t\tclose_overview(getSlideIndex(element.id));\n\t\t});\n\t}\n\tlet nwrapper=document.createElement('div');\n\tnwrapper.id='thumblayer';\n\tlet firstdiv=document.querySelector('body div.wthumb');\n\tfirstdiv.parentNode.insertBefore(nwrapper,firstdiv);\n\tdocument.querySelectorAll('body div.wthumb').forEach(function(element) {\n\t\tnwrapper.appendChild(element);\n\t});\n\tif (slideo.id!='outline') {\n\t\tlet wrapper=slideo.parentNode;\n\t\t// Scroll the overview div so that the current slide is visible\n\t\tlet tl=document.getElementById('thumblayer');\n\t\ttl.scrollTop=tl.offsetTop+wrapper.offsetTop;\n\t\twrapper.style.zIndex='30';\n\t\tlet newpos=wrapper.getBoundingClientRect();\t// Remember the new position of the current slide\n\t\tlet deltal=newpos.left-oldpos.left;\n\t\tlet deltat=newpos.top-oldpos.top;\n\t\tlet deltaw=newpos.width/oldpos.width-1;\n\t\tlet deltah=newpos.height/oldpos.height-1;\n\t\t// Put back the current slide at its original position\n\t\tslideo.classList.remove('thumbnail');\n\t\tslideo.style.position='fixed';\n\t\tslideo.style.transformOrigin='left top';\n\t\tslideo.style.backgroundColor='white';\n\t\tslideo.style.visibility='visible';\n\t\tsetTimeout(function() {\n\t\t\tslideo.classList.add('overview-transition');\n\t\t\t// Animate the transition while blurring the background\n\t\t\tslideo.addEventListener('transitionend',function(event) {\n\t\t\t\tslideo.style.transform=null;\n\t\t\t\tslideo.style.position=null;\n\t\t\t\tslideo.style.transformOrigin=null;\n\t\t\t\tslideo.style.backgroundColor=null;\n\t\t\t\tslideo.style.visibility=null;\n\t\t\t\tslideo.classList.add('thumbnail');\n\t\t\t\tslideo.classList.remove('overview-transition');\n\t\t\t\twrapper.style.zIndex=null;\n\t\t\t},{capture:false,once:true});\n\t\t\tsetTimeout(function() {\n\t\t\t\tslideo.style.transform='translate('+newpos.left+'px, '+newpos.top+'px) scale('+(newpos.width/oldpos.width)+', '+(newpos.height/oldpos.height)+')';\n\t\t\t\tgetSlide(overview_curslide).classList.add('targetted'); // Add a visual style to the targetted slide in the overview\n\t\t\t},20);\n\t\t},20);\n\t}\n}", "function addOverlay() {\n console.log('add OVERLAY');\n $('body').append('<div class=\"overlay\"></div>');\n }", "function initContentOverlay() {\n var $open = $('.open_overlay');\n var $overlay = $('.o__content_overlay');\n var $body = $('body');\n var $close = $overlay.find('.close_overlay');\n var old_share = null;\n\n $open.click(function(e) {\n e.preventDefault(); // We can't assure everything is a button, some items may be anchors.\n var $anchor = $(this);\n var host = '//' + window.location.host;\n var url = host + '/wp-json/wp/v2/' + $anchor.attr('data-cpt') + '/' + $anchor.attr('data-id');\n $.ajax({\n url: url\n }).done(function(data) {\n toggleOverlay();\n fillData(data);\n });\n });\n\n function strip(html) {\n var tmp = document.createElement(\"DIV\");\n tmp.innerHTML = html;\n return tmp.textContent || tmp.innerText || \"\";\n }\n\n /**\n * Update share URL for the buttons inside the overlay (we want to share\n * the Detail post page, not the actual one)\n */\n function renderShare(data) {\n if (typeof addthis !== 'undefined') {\n // Save current info for sharing and store it for when the overlay is closed.\n old_share = JSON.parse(JSON.stringify(addthis_share));\n\n addthis.update('share', 'url', data.link);\n addthis.update('share', 'title', data.title.rendered);\n addthis.update('share', 'image', get_image(data));\n addthis.update('share', 'description', strip(get_description(data)));\n }\n }\n\n /**\n * Get the correct image depending on CPT\n * @param data\n * @returns {*}\n */\n function get_image(data) {\n if ( 'post_image' in data.acf ) {\n return data.acf.post_image\n }\n\n if ( 'featured_image_square' in data.acf ) {\n return data.acf.featured_image_square\n }\n\n if ( 'image' in data.acf ) {\n return data.acf.image\n }\n }\n\n function get_description(data) {\n if ('post' === data.type) {\n return data.excerpt.rendered;\n } else if ('sun_event' === data.type) {\n return data.event_excerpt;\n } else if ('sun_person' === data.type) {\n return data.acf.description;\n }\n }\n\n $close.click(toggleOverlay);\n\n function fillData(data) {\n var $left = $overlay.find('.left');\n var $right = $overlay.find('.right');\n var $image = $left.find('.post_image');\n var $content = $overlay.find('.right>.post_content');\n var image_field = get_image(data);\n $left.css('background-image', 'url(' + get_image(data) + ')');\n\n $image.attr('src', image_field );\n $overlay.find('.left').find('.content_ov_bg').attr('src', image_field);\n \n $content.find('.post_title').html(data.title.rendered);\n var content = data.content.rendered;\n if ( 'description' in data.acf ) {\n content = data.acf.description;\n }\n $content.find('.content').html(content);\n var $caption = $content.find('.caption');\n if (data.acf.caption) {\n $caption.css('display', 'block');\n $caption.html(data.acf.caption);\n } else {\n $caption.css('display', 'none');\n }\n\n var $additional = $content.find('.additional');\n if (data.acf.additional_info) {\n $additional.css('display', 'block');\n $additional.html(data.acf.additional_info);\n } else {\n $additional.css('display', 'none');\n }\n\n if ('event_date_start' in data.acf) {\n $overlay.find('.date_start>.date').html(data.acf.event_date_start);\n $overlay.find('.date_start').css('display', 'block');\n } else {\n $overlay.find('.date_start').css('display', 'none');\n }\n\n var $button = $right.find('.a__button');\n if ('cta' in data.acf && data.acf.cta.length >= 1) {\n $button.css('opacity', '1');\n var cta = data.acf.cta[0];\n $button.attr('href', cta.link);\n $button.attr('target', cta.new_window ? '_blank' : '');\n $button.html(cta.label)\n } else {\n $button.css('opacity', '0');\n }\n\n renderShare(data);\n }\n\n function toggleOverlay() {\n $overlay.toggleClass('active');\n $body.toggleClass('modal');\n\n if (!($overlay).hasClass('active')) {\n // If we closed the Overlay.\n addthis.update('share', 'url', old_share.url);\n addthis.update('share', 'title', old_share.title);\n addthis.update('share', 'image', old_share.image);\n addthis.update('share', 'description', old_share.description);\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal `_.pick` helper function to determine whether `key` is an enumerable property name of `obj`.
function keyInObj(value, key, obj) { return key in obj; }
[ "function isObjectAssignable(key) {\n return typeof key === 'string' || typeof key === 'number' || typeof key === 'symbol';\n}", "function hasProps(keys, x) {\n if(!isFoldable(keys)) {\n throw new TypeError(err)\n }\n\n if(isNil(x)) {\n return false\n }\n\n var result = keys.reduce(\n every(hasKey(x)),\n null\n )\n\n return result === null || result\n}", "isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }", "function findKey (obj, key) {\n if (has(obj, key)) return [obj]\n return flatten(\n map(obj, function (v) {\n return typeof v === 'object' ? findKey(v, key) : []\n }),\n true\n )\n}", "function defineObjectKeys(){\n Object.keys = (function() {\n 'use strict';\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function(obj) {\n if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {\n throw new TypeError('Object.keys called on non-object');\n }\n\n var result = [], prop, i;\n\n for (prop in obj) {\n if (hasOwnProperty.call(obj, prop)) {\n result.push(prop);\n }\n }\n\n if (hasDontEnumBug) {\n for (i = 0; i < dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) {\n result.push(dontEnums[i]);\n }\n }\n }\n return result;\n };\n }());\n}", "function whoHasKey(tableObj, key){\n for ( var name in tableObj){\n if (key in tableObj[name]){\n return name;\n }\n }\n}", "function showProperties(obj) {\n for(let key in obj) {\n if(typeof obj[key] === 'string') {\n console.log(key, obj[key]);\n }\n }\n}", "objectKeys(obj) {\n if (obj instanceof Object) {\n return (function*() {\n for (let key in obj) {\n yield key;\n }\n })();\n } else {\n return [];\n }\n }", "function findFirstProp(objs, p) {\n for (let obj of objs) {\n if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); }\n }\n}", "function isExtension(value, key) {\n return _lodash2['default'].startsWith(key, 'x-');\n}", "function pickBy(obj, cb){\n let result = {};\n for (let key in obj){\n if(cb(obj[key])) result[key]=obj[key];\n }\n return result;\n}", "function testcase() {\n var obj = { \"a\": \"a\" };\n\n var result = Object.getOwnPropertyNames(obj);\n\n try {\n var beforeOverride = (result[0] === \"a\");\n result[0] = \"b\";\n var afterOverride = (result[0] === \"b\");\n\n return beforeOverride && afterOverride;\n } catch (ex) {\n return false;\n }\n }", "function filterFunction(obj, key, value){\n\tif(obj[key] === value) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function obj_find(obj, prop, val) {\n\tfor (let k in obj) {\n\t\tlet v = obj[k]\n\t\tif (v[prop] === val)\n\t\t\treturn v\n\t}\n\treturn null\n}", "ensureProperty(obj, prop, value) {\n if (!(prop in obj)) {\n obj[prop] = value;\n }\n }", "function FILTER_KEY(key) {\n var string = %ToString(key);\n if (%HasProperty(this, string)) return string;\n return 0;\n}", "function testcase() {\n var newObj = Object.create({}, {\n prop: {\n set: function () { },\n enumerable: true,\n configurable: true\n }\n });\n return newObj.hasOwnProperty(\"prop\") && newObj.prop === undefined;\n }", "function propEquals(obj){\n\t/*var obj = arguments.slice(0, 1);\n\t var val = arguments.pop();\n\t \n\t if(isEmpty.apply(this, arguments)){\n\t return false;\n\t }*/\n\t\n\tif(typeof obj === 'undefined'){\n\t\treturn false;\n\t}\n\t\n\tfor(var i = 1; i < arguments.length - 1; i++){\n\t\tvar obj = obj[arguments[i]];\n\t\tif(typeof obj === 'undefined'){\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn obj == arguments[arguments.length-1];\n}", "function isExtension(value, key) {\n return _.startsWith(key, 'x-');\n}", "function testLookupGetter() {\n var obj = {};\n\n // Getter lookup traverses internal prototype chain.\n Object.defineProperty(Object.prototype, 'inherited', {\n get: function inheritedGetter() {}\n });\n Object.defineProperty(obj, 'own', {\n get: function ownGetter() {}\n });\n print(obj.__lookupGetter__('own').name);\n print(obj.__lookupGetter__('inherited').name);\n\n // An accessor lacking a 'get' masks an inherited getter.\n Object.defineProperty(Object.prototype, 'masking', {\n get: function inheritedGetter() {}\n });\n Object.defineProperty(obj, 'masking', {\n set: function ownGetter() {}\n // no getter\n });\n print(obj.__lookupGetter__('masking'));\n\n // A data property causes undefined to be returned.\n Object.defineProperty(Object.prototype, 'inheritedData', {\n value: 123\n });\n Object.defineProperty(obj, 'ownData', {\n value: 321\n });\n print(obj.__lookupGetter__('ownData'));\n print(obj.__lookupGetter__('inheritedData'));\n\n // Same for missing property.\n print(obj.__lookupGetter__('noSuch'));\n\n // .length and .name\n print(Object.prototype.__lookupGetter__.length);\n print(Object.prototype.__lookupGetter__.name);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the callback function to be run when the response comes in. this callback assumes a chunked response, with several 'data' events and one final 'end' response.
function callback(response) { var result = ''; // string to hold the response // as each chunk comes in, add it to the result string: response.on('data', function (data) { result += data; }); // when the final chunk comes in, print it out: response.on('end', function () { console.log('result: ' + result); }); }
[ "function handleEnd(dataChunked) {\n\t\t\t\ttry {\n\t\t\t\t\tcontent = JSON.parse(dataChunked);\n\t\t\t\t\tcallback(content);\n\t\t\t\t} catch(ex) {\n\t\t\t\t\tthrow new Error(ex);\n\t\t\t\t}\n\t\t\t}", "onXHRComplete(inName, inResponse) {\n\t\tconsole.debug(`Loaded raw audio data for '${inName}', doing decode...`);\n\t\tlet ctx = new AudioContext();\n\t\tthis[inName].context = ctx;\n\t\tctx.decodeAudioData(inResponse, \n\t\t\tfunction(inBuffer) { ALL_LOADED_AUDIO.onDecodeAudioSuccess(inName, inBuffer); },\n\t\t\tfunction() { throw `ERROR DECODING AUDIO FOR ${inName}`; }\n\t\t);\n\t}", "function handleResponse(request, responseHandler) {\n if (request.readyState == 4 && request.status == 200) {\n responseHandler(request);\n }\n }", "_onHeader (header) {\n if (header === 0) {\n // Message boundary\n let message\n switch (this._currentMessage.length) {\n case 0:\n // Keep alive chunk, sent by server to keep network alive.\n return this.AWAITING_CHUNK\n case 1:\n // All data in one chunk, this signals the end of that chunk.\n message = this._currentMessage[0]\n break\n default:\n // A large chunk of data received, this signals that the last chunk has been received.\n message = new CombinedBuffer(this._currentMessage)\n break\n }\n this._currentMessage = []\n this.onmessage(message)\n return this.AWAITING_CHUNK\n } else {\n this._chunkSize = header\n return this.IN_CHUNK\n }\n }", "function attachCallback(req, callback) {\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n callback(req.status, req.statusText, req.responseText);\n }\n }\n }", "handleResponse_(error, request) {\n let segmentInfo;\n let segment;\n let view;\n\n // timeout of previously aborted request\n if (!this.xhr_ ||\n (request !== this.xhr_.segmentXhr &&\n request !== this.xhr_.keyXhr &&\n request !== this.xhr_.initSegmentXhr)) {\n return;\n }\n\n segmentInfo = this.pendingSegment_;\n segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];\n\n // if a request times out, reset bandwidth tracking\n if (request.timedout) {\n this.abort_();\n this.bandwidth = 1;\n this.roundTrip = NaN;\n this.state = 'READY';\n return this.trigger('progress');\n }\n\n // trigger an event for other errors\n if (!request.aborted && error) {\n // abort will clear xhr_\n let keyXhrRequest = this.xhr_.keyXhr;\n\n this.abort_();\n this.error({\n status: request.status,\n message: request === keyXhrRequest ?\n 'HLS key request error at URL: ' + segment.key.uri :\n 'HLS segment request error at URL: ' + segmentInfo.uri,\n code: 2,\n xhr: request\n });\n this.state = 'READY';\n this.pause();\n return this.trigger('error');\n }\n\n // stop processing if the request was aborted\n if (!request.response) {\n this.abort_();\n return;\n }\n\n if (request === this.xhr_.segmentXhr) {\n // the segment request is no longer outstanding\n this.xhr_.segmentXhr = null;\n segmentInfo.startOfAppend = Date.now();\n\n // calculate the download bandwidth based on segment request\n this.roundTrip = request.roundTripTime;\n this.bandwidth = request.bandwidth;\n this.mediaBytesTransferred += request.bytesReceived || 0;\n this.mediaRequests += 1;\n this.mediaTransferDuration += request.roundTripTime || 0;\n\n if (segment.key) {\n segmentInfo.encryptedBytes = new Uint8Array(request.response);\n } else {\n segmentInfo.bytes = new Uint8Array(request.response);\n }\n }\n\n if (request === this.xhr_.keyXhr) {\n // the key request is no longer outstanding\n this.xhr_.keyXhr = null;\n\n if (request.response.byteLength !== 16) {\n this.abort_();\n this.error({\n status: request.status,\n message: 'Invalid HLS key at URL: ' + segment.key.uri,\n code: 2,\n xhr: request\n });\n this.state = 'READY';\n this.pause();\n return this.trigger('error');\n }\n\n view = new DataView(request.response);\n segment.key.bytes = new Uint32Array([\n view.getUint32(0),\n view.getUint32(4),\n view.getUint32(8),\n view.getUint32(12)\n ]);\n\n // if the media sequence is greater than 2^32, the IV will be incorrect\n // assuming 10s segments, that would be about 1300 years\n segment.key.iv = segment.key.iv || new Uint32Array([\n 0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence\n ]);\n }\n\n if (request === this.xhr_.initSegmentXhr) {\n // the init segment request is no longer outstanding\n this.xhr_.initSegmentXhr = null;\n segment.map.bytes = new Uint8Array(request.response);\n this.initSegments_[initSegmentId(segment.map)] = segment.map;\n }\n\n if (!this.xhr_.segmentXhr && !this.xhr_.keyXhr && !this.xhr_.initSegmentXhr) {\n this.xhr_ = null;\n this.processResponse_();\n }\n }", "function handleResponse() {\n var doc = req.responseXML;\n if (!doc) {\n handleFeedParsingFailed(\"Not a valid feed.\");\n return;\n }\n parseEntry(doc);\n}", "function readyStateChangePoll() {\n\t\t\tif( asyncRequest.req.readyState == 4 ) {\n\t\t\t\tprocessResponse();\n\t\t\t}\n\t\t}", "function handleRequest() {\n // debugger;\n if (myReq.readyState === XMLHttpRequest.DONE) {\n // debugger;\n // check status here and proceed\n if (myReq.status === 200) {\n // 200 means done and dusted, ready to go with the dataset!\n console.log(myReq);\n handleDataSet(myReq.responseText);\n\n } else {\n // probably got some kind of error code, so handle that \n // a 404, 500 etc... can render appropriate error messages here\n console.error(`${myReq.status} : something done broke, son`);\n }\n } else {\n // request isn't ready yet, keep waiting...\n console.log(`Request state: ${myReq.readyState}. Still processing...`);\n }\n\n }", "end(response, status = 200) {\n let entiry;\n let headers = {};\n if (typeof response === 'string') {\n entiry = response;\n }\n else {\n entiry = response.entiry;\n headers = response.headers;\n status = response.status;\n }\n this.finish(status, headers, entiry);\n }", "_runResponseCycle () {\n const everyStep = (step, next) => {\n if (!step) {\n return next()\n }\n\n return step.call(this, this, next)\n }\n\n const finalStep = (error) => {\n if (error) {\n console.log(error)\n }\n }\n\n const _onPreResponse = this._getMergedExtensions('onPreResponse')\n const _onResponse = [ this._sendResponse ]\n const _onPostResponse = this._getMergedExtensions('onPostResponse')\n\n const cycle = new Cycle(everyStep, finalStep)\n\n cycle.add(_onPreResponse)\n cycle.add(_onResponse)\n cycle.add(_onPostResponse)\n\n cycle.start()\n }", "function getAllItemsCallback(response){\n\t\n}", "function startStream (response) {\n\n\tchild.send('start'); \n\n\tresponse.writeHead(200, {\"Content-Type\": \"text/json\"});\n\tresponse.end('{\"status\":\"ok\"}');\n}", "function giveBackData(error , data){\n console.log('inside callback function');\n console.log(data+\"\");\n}", "_addServiceStreamDataListener ( ) {\n\n this.serviceStream.on(\n 'data'\n , this.boundStreamListener\n );\n }", "parseChunks(chunk, byteStart) {\r\n if (!this._onError || !this._onMediaInfo || !this._onTrackMetadata || !this._onDataAvailable) {\r\n throw new IllegalStateException('Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified');\r\n }\r\n\r\n let offset = 0;\r\n let le = this._littleEndian;\r\n\r\n if (byteStart === 0) { // buffer with header\r\n let probeData = MP4Demuxer.probe(chunk);\r\n offset = probeData.dataOffset;\r\n if (!probeData.enoughData) {\r\n return 0;\r\n }\r\n }\r\n\r\n\r\n if (this._firstParse) { // parse moov box\r\n this._firstParse = false;\r\n if (byteStart + offset !== this._dataOffset) {\r\n Log.w(this.TAG, 'First time parsing but chunk byteStart invalid!');\r\n }\r\n\r\n let uintarr = new Uint8Array(chunk);\r\n let moov = boxInfo(uintarr, offset);\r\n //moov still not finished, wait for it\r\n if (!moov.fullyLoaded) {\r\n this._firstParse = true;\r\n return 0;\r\n }\r\n let moovData = new Uint8Array(chunk, byteStart + offset, moov.size);\r\n this._parseMoov(moovData);\r\n offset += moov.size;\r\n }\r\n\r\n let chunkOffset;\r\n\r\n while (offset < chunk.byteLength) {\r\n this._dispatch = true;\r\n\r\n let v = new Uint8Array(chunk, offset);\r\n\r\n if (offset + 8 > chunk.byteLength) {\r\n // data not enough for parsing box size\r\n break;\r\n }\r\n\r\n let chunkMap = this._chunkMap;\r\n if (this._mdatEnd > byteStart + offset) {\r\n //find the chunk\r\n let sampleOffset = byteStart + offset;\r\n let dataChunk = null;\r\n if (chunkOffset === undefined) {\r\n // bi search first chunk\r\n chunkOffset = (function () {\r\n let bottom = 0, top = chunkMap.length - 1;\r\n while (bottom <= top) {\r\n let mid = Math.floor((bottom + top) / 2);\r\n let result = (function (mid) {\r\n if (sampleOffset < chunkMap[mid].offset) return -1;\r\n if (chunkMap[mid + 1] && sampleOffset >= chunkMap[mid + 1].offset) return 1;\r\n return 0;\r\n })(mid);\r\n if (result == 0) return mid;\r\n if (result < 0) top = mid - 1;\r\n else bottom = mid + 1;\r\n }\r\n })();\r\n dataChunk = chunkMap[chunkOffset];\r\n } else {\r\n // sequal search other chunk\r\n for (; chunkOffset < chunkMap.length; chunkOffset++) {\r\n dataChunk = chunkMap[chunkOffset];\r\n if (sampleOffset < dataChunk.offset) {\r\n dataChunk = chunkMap[chunkOffset - 1];\r\n break;\r\n }\r\n }\r\n if (!dataChunk) {\r\n dataChunk = chunkMap[chunkMap.length - 1];\r\n }\r\n }\r\n\r\n //find out which sample\r\n sampleOffset -= dataChunk.offset;\r\n let sample;\r\n for (let i = 0; i < dataChunk.samples.length; i++) {\r\n if (sampleOffset == 0) {\r\n sample = dataChunk.samples[i];\r\n break;\r\n }\r\n sampleOffset -= dataChunk.samples[i].size;\r\n }\r\n\r\n if (sample === undefined) {\r\n //extra unused data, drop it\r\n let chunkOffset = chunkMap.indexOf(dataChunk);\r\n let nextChunk = chunkMap[chunkOffset + 1];\r\n let droppedBytes = (nextChunk != undefined ? nextChunk.offset : this._mdatEnd) - byteStart - offset;\r\n if (offset + droppedBytes <= chunk.byteLength) {\r\n Log.w(this.TAG, `Found ${droppedBytes} bytes unused data in chunk #${chunkOffset} (type: ${dataChunk.type}), dropping. `);\r\n offset += droppedBytes;\r\n continue;\r\n } else {\r\n break; //data not enough wait next time\r\n }\r\n }\r\n\r\n let sampleSize;\r\n if (dataChunk.type == 'video') {\r\n sampleSize = sample.size;\r\n if (offset + sampleSize > chunk.byteLength) {\r\n break;\r\n }\r\n this._parseAVCVideoData(chunk, offset, sampleSize, sample.ts, byteStart + offset, sample.isKeyframe, sample.cts, sample.duration);\r\n } else if (dataChunk.type == 'audio') {\r\n sampleSize = sample.size;\r\n if (offset + sampleSize > chunk.byteLength) {\r\n break;\r\n }\r\n let track = this._audioTrack;\r\n let dts = this._timestampBase / 1e3 * this._audioMetadata.timescale + sample.ts;\r\n let accData = v.subarray(0, sampleSize);\r\n let aacSample = { unit: accData, length: accData.byteLength, dts: dts, pts: dts };\r\n track.samples.push(aacSample);\r\n track.length += aacSample.length;\r\n }\r\n\r\n offset += sampleSize;\r\n } else {\r\n let box = boxInfo(v, 0);\r\n if (box.name == 'mdat') {\r\n this._mdatEnd = byteStart + offset + box.size - 8;\r\n offset += box.headSize;\r\n } else {\r\n if (box.fullyLoaded) {\r\n //not mdat box, skip\r\n offset += box.size;\r\n } else {\r\n //not mdat box, not fully loaded, break out\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // dispatch parsed frames to consumer (typically, the remuxer)\r\n if (this._isInitialMetadataDispatched()) {\r\n if (this._dispatch && (this._audioTrack.length || this._videoTrack.length)) {\r\n this._onDataAvailable(this._audioTrack, this._videoTrack);\r\n }\r\n }\r\n\r\n return offset; // consumed bytes, just equals latest offset index\r\n }", "function respond() {\r\n if (!responded) {\r\n responded = true;\r\n self.callback.apply(null, arguments);\r\n }\r\n }", "function get_server_response(path,method,callbackFn){\r\n\tdelete serverRequestOptions[\"headers\"];\r\n\tdelete serverRequestOptions[\"form\"];\r\n\tserverRequestOptions.path = path;\r\n\tserverRequestOptions.method = method;\r\n\tvar fullResponse = \"\";\r\n\tvar serverRequest;\r\n\r\n\t//read data\r\n\tif(serverRequestOptions.use_https){\r\n\t\tserverRequest = https.get(serverRequestOptions, function(serverResponse){\r\n\t\t\tserverResponse.on('data', function(data) {\r\n\t\t\t\tfullResponse += data;\r\n\t\t\t});\r\n\r\n\t\t\t// finished reading all data\r\n\t\t\tserverResponse.on('end', function(){\r\n\t\t\t\tcallbackFn(fullResponse);\r\n\t\t\t});\r\n\r\n\t\t\tserverResponse.on('error', function(error){\r\n\t\t\t\tcallbackFn(JSON.stringify(error));\r\n\t\t\t});\r\n\t\t});\r\n\t}else{\r\n\t\tserverRequest = http.get(serverRequestOptions, function(serverResponse){\r\n\t\t\tserverResponse.on('data', function(data) {\r\n\t\t\t\tfullResponse += data;\r\n\t\t\t});\r\n\r\n\t\t\t// finished reading all data\r\n\t\t\tserverResponse.on('end', function(){\r\n\t\t\t\tcallbackFn(fullResponse);\r\n\t\t\t});\r\n\r\n\t\t\tserverResponse.on('error', function(error){\r\n\t\t\t\tcallbackFn(JSON.stringify(error));\r\n\t\t\t});\r\n\t\t});\r\n\t}\r\n\r\n\tserverRequest.on('error',function(error){\r\n\t\tconsole.log(error.stack);\r\n\t\tfullResponse = JSON.stringify(error);\r\n\t\tcallbackFn(fullResponse);\r\n\t});\r\n\r\n\tserverRequest.on('end', function(){\r\n\t\tcallbackFn(fullResponse);\r\n\t});\r\n\r\n\tserverRequest.end();\r\n}", "_bufferParse(response)\n {\n return new Promise((resolve, reject) => {\n response.on('error', reject);\n\n let dataBuffer = [];\n\n response.on('data', (data) => {\n dataBuffer.push(data);\n });\n\n response.on('end', () => resolve(dataBuffer));\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
instantiatePopper Creates the instance of a popper and repositions it by calling updating state.data with the new position data returned by the create() and update() callbacks
instantiatePopper() { const modifiers = { offset: { offset: this.props.offsets } }; this._popper = new PopperJs(this._tooltipTriggerRef, this._tooltipPopupRef, { placement: this.props.placement, modifiers, onCreate: data => this.setState({ data }), onUpdate: data => this.setState({ data }) }); this.updatePopper(); }
[ "function attachPopper(anchor, element) {\n if (popper !== null) {\n popper.destroy();\n }\n\n popper = new Popper(anchor, element, {\n placement: 'auto-start',\n modifiers: {\n preventOverflow: {\n enabled: true,\n },\n shift: {\n enabled: true,\n },\n flip: {\n enabled: true,\n }\n },\n });\n }", "destroyPopper() {\n this.$_popper && this.$_popper.destroy()\n this.$_popper = null\n }", "function _setTooltipPosition() {\n // eslint-disable-next-line no-new\n new PopperJs($element, _tooltip, {\n placement: lumx.position || 'top',\n modifiers: {\n arrow: {\n // eslint-disable-next-line id-blacklist\n element: `.${CSS_PREFIX}-tooltip__arrow`,\n enabled: true,\n },\n },\n });\n }", "function popover () {\n var _id = _.uniqueId('ds-popover-');\n var $popover = null;\n var _content = null;\n var _x = null;\n var _y = null;\n // Previous values. Used to know if we need to reposition or update\n // the popover.\n var _prev_content = null;\n var _prev_x = null;\n var _prev_y = null;\n\n $popover = document.createElement('div');\n document.getElementById('site-canvas').appendChild($popover);\n $popover.outerHTML = ReactDOMServer.renderToStaticMarkup(<div className='popover' id={_id} />);\n $popover = document.getElementById(_id);\n\n /**\n * Sets the popover content.\n *\n * @param ReactElement\n * Content for the popover. Can be anything supported by react.\n */\n this.setContent = function (ReactElement, classes) {\n if (classes) {\n $popover.classList.add(...classes.split(' '));\n }\n _prev_content = _content;\n _content = ReactDOMServer.renderToStaticMarkup(ReactElement);\n return this;\n };\n\n /**\n * Positions the popover in the correct place\n * The anchor point for the popover is the bottom center with 8px of offset.\n *\n * Note: The popover needs to have content before being shown.\n *\n * @param anchorX\n * Where to position the popover horizontally.\n * @param anchorY\n * Where to position the popover vertically.\n */\n this.show = function (anchorX, anchorY) {\n _prev_x = _x;\n _prev_y = _y;\n _x = anchorX;\n _y = anchorY;\n\n if (_content === null) {\n console.warn('Content must be set before showing the popover.');\n return this;\n }\n\n var changePos = !(_prev_x === _x && _prev_y === _y);\n\n // Animate only after it was added.\n if (_prev_x !== null && _prev_y !== null) {\n $popover.classList.add('chart-popover-animate');\n }\n\n // Different content?\n if (_content !== _prev_content) {\n $popover.innerHTML = _content;\n // With a change in content, position has to change.\n changePos = true;\n }\n\n if (changePos) {\n let containerW = document.getElementById('site-canvas').offsetWidth;\n let sizeW = $popover.offsetWidth;\n let sizeH = $popover.offsetHeight;\n\n let leftOffset = anchorX - sizeW / 2;\n let topOffset = anchorY - sizeH - 8;\n\n // If the popover would be to appear outside the window on the right\n // move it to the left by that amount.\n // And add some padding.\n let overflowR = (leftOffset + sizeW) - containerW;\n if (overflowR > 0) {\n leftOffset -= overflowR + 16;\n }\n\n // Same for the left side.\n if (leftOffset < 0) {\n leftOffset = 16;\n }\n\n $popover.style.left = leftOffset + 'px';\n $popover.style.top = topOffset + 'px';\n $popover.style.display = '';\n $popover.style.opacity = 1;\n }\n\n return this;\n };\n\n /**\n * Removes the popover from the DOM.\n */\n this.hide = function () {\n $popover.style = null;\n $popover.classList.remove('chart-popover-animate');\n _content = null;\n _prev_content = null;\n _x = null;\n _y = null;\n _prev_x = null;\n _prev_y = null;\n return this;\n };\n\n return this;\n}", "function createElementsForPopup() {\r\n _dom.el.css(\"position\", \"absolute\");\r\n _dom.el.addClass(\"s-c-p-popup\");\r\n _dom.arrow = $(\"<div></div>\")\r\n .appendTo(_dom.el)\r\n .addClass(\"s-c-p-arrow\");\r\n _dom.arrowInner = $(\"<div></div>\")\r\n .appendTo(_dom.arrow)\r\n .addClass(\"s-c-p-arrow-inner\");\r\n }", "function setUpPopUps() {\n\t//console.log('setUpPopUps');\n\tif (currPageData.popUps) {\n\t\tvar isRequired = shell.popUp.isRequired;\n\t\tfor (var i=0, j=currPageData.popUps.length; i<j; i++) {\n\t\t\tpopUp.widthArray[popUp.widthArray.length] = currPageData.popUps[i].width;\n\t\t\tpopUp.heightArray[popUp.heightArray.length] = currPageData.popUps[i].height;\n\t\t\tif(currPageData.popUps[i].isRequired != 'undefined') {\n\t\t\t\tisRequired = currPageData.popUps[i].isRequired;\n\t\t\t}\n\t\t}\n\t\tpopUp.isRequired = isRequired;\n\t\tcreatePopUp();\t\n\t}\n}", "popspawner(){\n this.spawnOne();\n this.hitPoints=0;\n }", "drawPopUpPage(event){\n\t\tlet state = event.detail.state,\n\t\t\tyear = event.detail.year;\n\t\tthis.popUpPage = new PopUpPage(\"popup\", state, year);\n\t\tthis.popUpPage.eventTarget.addEventListener(\"closeButton\" ,this.onPopUpClosed.bind(this), false);\n\t\tthis.popUpPage.init();\n\t\tthis.popUpPage.drawPage();\n\t}", "componentDidUpdate(prevProps, prevState) {\n if (prevState.show !== this.state.show || (prevProps.targetPosition!==this.props.targetPosition)){\n if(this.state.show){\n // targetPosition prop is the boundary box of the target element. \n this.setState((prevState)=>({...prevState,show: true}),this.setPopoverPosition(this.props.targetPosition));\n }\n else{\n this.setState((prevState)=>({...prevState,show: false}));\n }\n \n }\n}", "function PopoverManager(options) {\n this.defaults = {\n trigger: options.trigger,\n placement: options.placement,\n boundary: options.boundary,\n content: options.content\n };\n\n //OPTION: Mode\n //Mode determines how the manager deals with multiple popovers\n if(!options.mode) {\n options.mode = PopoverManager.MODES[\"defaultValue\"];\n }\n this.mode = options.mode;\n this.multipleShowBehavior = PopoverManager.MULTIPLE_SHOW_REQUEST_BEHAVIORS[\"defaultValue\"];\n\n var dismissOnTemplate = {\n outside: {\n click: true,\n scroll: true\n },\n inside: {\n click: false, //NO IMPLEMENTATION YET\n scroll: false //NO IMPLEMENTATION YET\n },\n timeout: {\n bool: true,\n duration: 8000\n }\n };\n\n if(!options.dismissOn) {\n options.dismissOn = {};\n }\n\n //Combine the defaults for DismissOn with the options provided\n $.extend(true, dismissOnTemplate, options.dismissOn);\n this.dismissOn = dismissOnTemplate;\n\n //TIMEOUTS\n this.clickCaptureTimeout = null;\n\n //Active ID of the popover to display\n this.activeID = null;\n\n //Tracks the popovers created\n this.popovers = {};\n this.count = {\n open: 0,\n managed: 0\n };\n }", "renderPopup() {\n return (\n <div\n className=\"usaf-tooltip__popup\"\n ref={(el) => {\n this._tooltipPopupRef = el;\n }}\n onMouseEnter={this.onPopupMouseEnter}\n onMouseLeave={this.onPopupMouseLeave}\n style={this.getPopperStyle(this.state.data)}\n >\n {this.props.popupComponent}\n </div>\n );\n }", "initAndPosition() {\n // Append the info panel to the body.\n $(\"body\").append(this.$el);\n }", "componentWillUnmount() {\n if (this._popper) {\n this._popper.destroy();\n }\n }", "function init_pman() {\n\n var pman = new Pacman();\n pman.direction = LEFT;\n pman.x = 10;\n pman.y = 15;\n pman.lives = 3;\n\n actors[\"pman\"] = pman;\n pman.ref = $('<div>',{id:\"pman\",class:\"pman-left\"}).appendTo('#game-canvas');\n pman.draw();\n}", "function PopupRenderer(parent) {\n this.parent = parent;\n }", "evolvePopulation(pop) {\n let newPopulation = new Population(pop.size(), false);\n\n // Keep our best individual if elitism is enabled\n let elitismOffset = 0;\n if (this.elitism) {\n newPopulation.saveTour(0, pop.getFittest());\n elitismOffset = 1;\n }\n\n // Crossover population\n // Loop over the new population's size and create\n // individuals from current population\n for (let i = elitismOffset; i < newPopulation.size(); i++) {\n // Select parents\n let parent1 = this.tournamentSelection(pop);\n let parent2 = this.tournamentSelection(pop);\n // Crossover parents\n let child = this.crossover(parent1, parent2);\n // Add child to new population\n newPopulation.saveTour(i, child);\n }\n\n // Mutate the new population a bit to add some new genetic material\n for (let i = elitismOffset; i < newPopulation.size(); i++) {\n this.mutate(newPopulation.getTour(i));\n }\n\n return newPopulation;\n }", "function actCompletePopUp(){\n\t\t\t\t\t\t\tclearInterval(actTmr);\n\t\t\t\t\t\t\tstageBlocker(true);\n\t\t\t\t\t\t\tactCompletePopUpMC=new lib._PopUpBox();\t\n\t\t\t\t\t\t\tactCompletePopUpMC.x=myStageW/2-actCompletePopUpMC.nominalBounds.width/2;\n\t\t\t\t\t\t\tactCompletePopUpMC.y=myStageH/2-actCompletePopUpMC.nominalBounds.height/2;\t\n\t\t\t\t\t\t\tstage.addChild(actCompletePopUpMC);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcreatejs.Ticker.addEventListener(\"tick\", updateEnterFrame);\t\n\t\t\t\t\t\t\tfunction updateEnterFrame(event) {\n\t\t\t\t\t\t\t\tactCompletePopUpMC.playNext_mc.gotoAndStop(1);\n\t\t\t\t\t\t\t\tactCompletePopUpMC.playNext_mc.play_txt.text=\"Next Level\";\n\t\t\t\t\t\t\t\tactCompletePopUpMC.playNext_mc.alpha=actCompletePopUpMC.playA_mc.alpha=0.5;\n\t\t\t\t\t\t\t\tcreatejs.Ticker.removeEventListener(\"tick\", updateEnterFrame);\n\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tactCompletePopUpMC.title_txt.text=levelNameArr[currentLevelNum];\n\t\t\t\t\t\t\tactCompletePopUpMC.userScroreDetail_txt.text=\"\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Score\\t\\t\\t\"+getScore+\"/\"+(minScore*getTotalQ_num)+\"\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Lives\\t\\t\\t\"+lifeNum+\"\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Correct\\t\\t\"+totalRightAns+\"/\"+getTotalQ_num+\"\\n\"+\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"Incorrect\\t\\t\"+totalWrongAns+\"/\"+getTotalQ_num;\n\t\t\t\t\t\t\tactCompletePopUpMC.userScroreDetail_txt.visible=false;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tupdateScorePercentage();\n\t\t\t\t\t\t}", "positionMenu_() {\n positionPopupAroundElement(\n this, this.menu, this.anchorType, this.invertLeftRight);\n }", "show (contentTemplate, contentData, anchorEl, placement, reposition) {\n let controller = this,\n popoverPlacement = $(anchorEl);\n \n // Capture the context\n controller.contentTemplate = contentTemplate;\n controller.data = contentData;\n controller.anchorEl = anchorEl;\n \n if (controller.popover === undefined) {\n //console.log('QuickPopoverController.show anchorEl:', anchorEl);\n \n // Possibly correct the placement\n if (placement.match(/left|right/i)) {\n let bounds = popoverPlacement.get(0).getBoundingClientRect(),\n windowWidth = window.innerWidth;\n \n if (bounds.right > windowWidth / 2 && placement.match(/right/i) && placement.match(/auto/i)) {\n console.log('QuickPopoverController placement change:', placement, '->', 'left');\n placement = 'left';\n } else if (bounds.left < windowWidth / 2 && placement.match(/left/i) && placement.match(/auto/i)) {\n console.log('QuickPopoverController placement change:', placement, '->', 'left');\n placement = 'right';\n }\n }\n \n controller.elementId = Random.id();\n controller.popover = popoverPlacement\n .popover({\n placement: placement || 'auto bottom',\n html : true,\n content : '<div class=\"quick-popover-contents\" id=\"' + controller.elementId + '\"></div>'\n })\n .popover('show');\n \n // Render the contents\n setTimeout(() => {\n controller.renderContent(reposition);\n \n // Add a click handler to close the popover if you click outside of it\n $('body').bind('click.quickPopoverClose', controller.hide);\n }, 10);\n \n // Focus on the first input\n setTimeout(() => {\n $('.quick-popover-contents input:visible').first('input').focus()\n }, 500);\n \n return controller.popover\n } else {\n controller.renderContent();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The value of the current property is always the final element of this.stack.
getValue() { return getLast(this.stack); }
[ "popValue() {\n let size = this.stack.pop().size;\n this.write(\"[-]<\".repeat(size));\n }", "peek(){\n\n if(!this.top){\n return 'Stack is empty.';\n\n }\n try{\n return this.top.value;\n } \n catch(err){\n return 'Stack is empty.';\n }\n }", "get name() {\n return this.stack.name;\n }", "push(val) {\n this._stack.push(val);\n }", "pop() {\n if(this.stack.length == 0) {return null\n }\n\n return this.stack[this.top--];\n }", "future() {\n if (this.stack.length === 0) {\n this.pushToken(this.lexer.lex());\n }\n\n return this.stack[this.stack.length - 1];\n }", "get back() {\n return this.get(this.length - 1);\n }", "function last() {\n return _navigationStack[_navigationStack.length - 1];\n }", "get expNext() {\n return this.expToLevel(this.level + 1);\n }", "plus() {\n this._lastX = this.pop();\n this._stack.push(this.pop() + this._lastX);\n }", "getValue() {\n return this.node.value;\n }", "getTail() {\n return this._tail;\n }", "popActive() {\n\t\t\tif(!this._activeStack.length) throw new Error(\"Active stack for \"+this.name+\" is empty and requested pop.\");\n\t\t\tthis._activeStack.pop().becomeActive();\n\t\t}", "get stack() {\n \t\treturn extractStacktrace(this.errorForStack, 2);\n \t}", "popBack() {\n const last = this.length - 1;\n const value = this.get(last);\n this._vec.remove(last);\n this._changed.emit({\n type: 'remove',\n oldIndex: this.length,\n newIndex: -1,\n oldValues: [value],\n newValues: []\n });\n return value;\n }", "minus() {\n this._lastX = this.pop();\n let first = this.pop();\n this._stack.push(first - this._lastX);\n }", "pop() {\r\n return this._msgStack.pop()\r\n }", "get source() {\n \t\t\t\treturn test.stack;\n \t\t\t}", "pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }", "get lastItem() {\n return !this.buttons\n ? undefined\n : this.mainItems[this.mainItems.length - 1];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Jump to the bottom of a node.
function scrollToBottom(node) { node.scrollTop = node.scrollHeight - node.clientHeight; }
[ "function scrollToBottom () {\n endRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' })\n }", "scrollToBottom() {\n this.tableBodyNode.scrollTop = this.tableBodyNode.scrollHeight;\n }", "function scrollToBottom() {\n $('#messages-bottom')[0].scrollIntoView();\n }", "function scrollToBottom() {\n \n // If scrolling is not locked\n if (scroll) {\n \n // Lock scroll\n scroll = false;\n \n // Scroll to bottom\n bodyhtml.animate({\n scrollTop: $(document).height()\n }, TIME_SCROLL);\n \n // Unlock scrolling\n setTimeout(function() {\n scroll = true;\n }, (TIME_SCROLL * 2));\n }\n }", "function movelegBottom(){\n if(leg.moveDone){\n // reset motion\n leg.vy=0;\n leg.move1=false;\n leg.move3=false;\n // paw facing up\n // set shapes to initial direction\n leg.paw=abs(leg.paw);\n leg.h=abs(leg.h);\n leg.extend=abs(leg.extend);\n // position\n legStartPos=height+200;\n // start motion\n leg.move1=true;\n leg.moveDone=false;\n }\n}", "static scrollToBottom() {\n\t\tvar storyEl = document.getElementsByTagName(\"jw-story\")[0];\n\t\t// Create invisible div element after the end of the story element\n\t\tvar storyBottomEl = storyEl.appendChild(document.createElement(\"div\"));\n\t\t// Scroll it into view\n\t\tstoryBottomEl.scrollIntoView();\n\t\t// Now we don't need that element anymore\n\t\tstoryBottomEl.remove();\n\t}", "__getBottomPosition(node) {\n const positionClassName = this.__getClassStartingWith(node, 'y');\n return this.__parseCSSValueToInt(\n cssTree[`.${positionClassName}`].bottom\n );\n }", "bottom(el){\n setTimeout(_=>{\n let parent = el.closest('.window').querySelector('.text')\n parent.scrollTop = parent.scrollHeight\n })\n }", "get bottom() {\n return this.pos.y + this.size.y / 2; // ball reflects\n }", "onScrolledToBottom() {\n callAction(this, 'onScrolledToBottom', ...arguments);\n }", "function scrollToChatBottom() {\n var height = 0;\n height = height < $(\"#chat-window\")[0].scrollHeight ? $(\"#chat-window\")[0].scrollHeight : 0;\n $(\"#chat-window\").stop().animate({scrollTop: height}, 500);\n }", "function positionElementBottom(){\n\t\t\n\t\tvar totalTextHeight = getTotalTextHeight();\n\t\tvar startY = g_objTextWrapper.height() - totalTextHeight - g_options.slider_textpanel_padding_bottom;\n\t\t\n\t\tpositionElementsTop(false, startY);\n\t}", "goToNextBlock () {\n const nextBlockId = this.target.blocks.getNextBlock(this.peekStack());\n this.reuseStackForNextBlock(nextBlockId);\n }", "function lastItemOffset(node) {\n var item = node.lastChild;\n if (!item) {\n return 0;\n }\n var menuRect = node.getBoundingClientRect();\n var itemRect = item.getBoundingClientRect();\n return menuRect.bottom - itemRect.bottom;\n }", "_clickBottomEdge(event) {\n event.stopPropagation();\n let that = this,\n opts = this.options,\n bottomEdge = event.target,\n node = bottomEdge.parentNode,\n childrenState = this._getNodeState(node, 'children');\n\n if (childrenState.exist) {\n let temp = this._closest(node, function (el) {\n return el.nodeName === 'TR';\n }).parentNode.lastChild;\n\n if (Array.from(temp.querySelectorAll('.node')).some((node) => {\n return this._isVisible(node) && node.classList.contains('slide');\n })) { return; }\n // hide the descendant nodes of the specified node\n if (childrenState.visible) {\n this.hideChildren(node);\n } else { // show the descendants\n this.showChildren(node);\n }\n } else { // load the new children nodes of the specified node by ajax request\n let nodeId = bottomEdge.parentNode.id;\n\n if (this._startLoading(bottomEdge, node)) {\n this._getJSON(typeof opts.ajaxURL.children === 'function' ?\n opts.ajaxURL.children(node.dataset.source) : opts.ajaxURL.children + nodeId)\n .then(function (resp) {\n if (that.dataset.inAjax === 'true') {\n if (resp.children.length) {\n that.addChildren(node, resp);\n }\n }\n })\n .catch(function (err) {\n console.error('Failed to get children nodes data', err);\n })\n .finally(function () {\n that._endLoading(bottomEdge, node);\n });\n }\n }\n }", "function jumpOut() {\r\n rpgcode.animateCharacter(\"\", \"JUMP_WEST\", function() {\r\n rpgcode.setCharacterStance(spriteId, \"EAST\");\r\n rpgcode.delay(500, function() {\r\n situp();\r\n }, false);\r\n }); \r\n}", "function postOrder( node ){\n if( node ){\n postorder( node.left );\n postorder( node.right );\n console.log( node.value ); // print out current node, then traverse\n }\n}", "jump () {\n if (this.body.onFloor() === true) {\n this.body.velocity.y = -this.jumpPower\n this.animations.play('jump', 30)\n this.doubleJump = true\n } else if (this.doubleJump === true) {\n console.log('doubleJump: ', this.doubleJump)\n this.doubleJump = false\n this.body.velocity.y = -this.jumpPower\n this.anmations.play('jump', 30)\n }\n }", "_end(resolve){\n window.scrollTo(0, this.start + this.distance);\n resolve();\n }", "keepScrollAtBottom(){\n let scrollContainer = document.getElementById(\"scrollContainer\");\n scrollContainer.scrollTop = scrollContainer.scrollHeight;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call from Flex if subtitle upload was failed
function setSubtitleUploadFailedFromFlex(jobHash) { console.log("Subtitle upload faile"); $("#Uploaded_subtitle_" + jobHash).val("0"); }
[ "function changeBackgroundVideoFileError(message) {\r\n changeBackgroundVideoContentError(message, liveBackgroundType);\r\n}", "function changeBackgroundFlixerVideoFileErrorToPage(message) {\r\n changeBackgroundVideoContentError(message, flixelBackgroundType);\r\n}", "onAudioLoadError(e) {\n //swal(\"audio load error\", \"\", \"error\");\n console.log(\"audio load err\", e);\n }", "function FailToPulish(err){\n console.log(\"Publish local stream error: \" + err);\n }", "function onSetupError () {\n\n popup\n .showConfirm('Something went wrong while loading the video, try again?')\n .then(function (result) {\n if (true === result) {\n $state.reload();\n }\n });\n\n vm.loading = false;\n $timeout.cancel(loadingTimeout);\n }", "function appxEncodingError(encoding) {\r\n var message = appx_session.language.alerts.encodingFrontError + encoding + appx_session.language.alerts.encodingBackError;\r\n //alert(message);\r\n appxSetStatusText(message, 2);\r\n}", "function validateSpeechFailTMSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Too Much Speech\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}", "function OnFailure(sender, args) {\n alert(\"Error occurred at UpdateListItem. See console for details.\");\n console.log('Request failed at UpdateListItem :' + args.get_message() + '\\n' + args.get_stackTrace());\n }", "function sp_ToolTip()\n{\n\ntry {\n\tnDomain = DVD.CurrentDomain;\n\tif (nDomain != 4) return;\n\n nSubpics = DVD.SubpictureStreamsAvailable;\n if (nSubpics == 0) {\n\t\tAudio.ToolTip = L_NoSubtitles_TEXT;\n\t\tAudioFull.ToolTip = L_NoSubtitles_TEXT;\n\t\treturn;\n\t}\n \n nCurrentSP = DVD.CurrentSubpictureStream;\n bSPDisplay = DVD.SubpictureOn;\n\n\tif (nCurrentSP<0 || nCurrentSP>=32) return;\n\tstrCurrentLang = DVD.GetSubpictureLanguage(nCurrentSP);\n \n // Next click will disable subpicture\n if (bSPDisplay && nCurrentSP+1 == nSubpics) {\n tempStr = L_SubtitlesAreLanguageClickToDisable_TEXT.replace(/%1/i, strCurrentLang);\n Subtitles.ToolTip = tempStr;\n SubtitlesFull.ToolTip = tempStr;\n }\n else {\n // Next click will enable subpicture to the first stream\n if (!bSPDisplay) {\n nCurrentSP = 0;\n\t\t\tstrNextLang = DVD.GetSubpictureLanguage(nCurrentSP);\n tempStr = L_SubtitlesAreDisabledClickForLanguage_TEXT.replace(/%1/i, strNextLang);\n\t\t\tSubtitles.ToolTip = tempStr;\n\t\t\tSubtitlesFull.ToolTip = tempStr;\n }\n\t\telse {\n\t\t nCurrentSP++;\n\t\t\tstrNextLang = DVD.GetSubpictureLanguage(nCurrentSP);\n\t\t\ttempStr = L_SubtitlesAreLanguageClickForLanguage_TEXT.replace(/%1/i, strCurrentLang).replace(/%2/i, strNextLang);\n Subtitles.ToolTip = tempStr;\n\t\t\tSubtitlesFull.ToolTip = tempStr;\n\t\t}\n }\n\n\tMessage.Text = Subtitles.ToolTip;\n\tMessageFull.Text = Subtitles.ToolTip;\n\tMFBar.SetTimeOut(2000, DVDMSGTIMER);\n}\n\ncatch(e) {\n //e.description = L_ERRORToolTip_TEXT;\n\t//HandleError(e);\n\treturn;\n}\n\n}", "function uploadDone(name, myRId) {\r\n var frame = frames[name];\r\n if (frame) {\r\n var ret = frame.document.getElementsByTagName(\"body\")[0].innerHTML;\r\n if (ret.length) {\r\n alert(ret);\r\n frame.document.getElementsByTagName(\"body\")[0].innerHTML = \"\";\r\n showRecordView(myRId);\r\n }\r\n }\r\n }", "static sFailure(sid, request, code, msg) {\n Signals.emit(sid, \"sFailure\", {\"request\": request, \"msg\": msg, \"code\": code});\n }", "error(code, api){\n // Favorite API specific errors\n if (api === 'SYNO.FileStation.Favorite') {\n switch (code) {\n case 800: return 'A folder path of favorite folder is already added to user\\'s favorites.'; break;\n case 801:\n return 'A name of favorite folder conflicts with an existing folder path in the user\\'s favorites.';\n break;\n case 802: return 'There are too many favorites to be added.'; break;\n }\n }\n // Upload API specific errors\n if (api === 'SYNO.FileStation.Upload') {\n switch (code) {\n case 1800:\n return `There is no Content-Length information in the HTTP header or the received size doesn\\'t \\\nmatch the value of Content-Length information in the HTTP header.`;\n break;\n case 1801:\n return `Wait too long, no date can be received from client (Default maximum wait time is 3600 \\\nseconds).`;\n break;\n case 1802: return 'No filename information in the last part of file content.'; break;\n case 1803: return 'Upload connection is cancelled.'; break;\n case 1804: return 'Failed to upload too big file to FAT file system.'; break;\n case 1805: return 'Can\\'t overwrite or skip the existed file, if no overwrite parameter is given.'; break;\n }\n }\n // Sharing API specfic errors\n if (api === 'SYNO.FileStation.Sharing') {\n switch (code) {\n case 2000: return 'Sharing link does not exist.'; break;\n case 2001: return 'Cannot generate sharing link because too many sharing links exist.'; break;\n case 2002: return 'Failed to access sharing links.'; break;\n }\n }\n // CreateFolder API specific errors\n if (api === 'SYNO.FileStation.CreateFolder') {\n switch (code) {\n case 1100: return 'Failed to create a folder. More information in <errors> object.'; break;\n case 1101: return 'The number of folders to the parent folder would exceed the system limitation.'; break;\n }\n }\n // Rename API specific errors\n if (api === 'SYNO.FileStation.Rename') {\n switch (code) {\n case 1200: return 'Failed to rename it. More information in <errors> object.'; break;\n }\n }\n // CopyMove API specific errors\n if (api === 'SYNO.FileStation.CopyMove') {\n switch (code) {\n case 1000: return 'Failed to copy files/folders. More information in <errors> object.'; break;\n case 1001: return 'Failed to move files/folders. More information in <errors> object.'; break;\n case 1002: return 'An error occurred at the destination. More information in <errors> object.'; break;\n case 1003:\n return 'Cannot overwrite or skip the existing file because no overwrite parameter is given.';\n break;\n case 1004:\n return `File cannot overwrite a folder with the same name, or folder cannot overwrite a file with \\\nthe same name.`;\n break;\n case 1006: return 'Cannot copy/move file/folder with special characters to a FAT32 file system.'; break;\n case 1007: return 'Cannot copy/move a file bigger than 4G to a FAT32 file system.'; break;\n }\n }\n // Delete API specific errors\n if (api === 'SYNO.FileStation.Delete') {\n switch (code) {\n case 900: return 'Failed to delete file(s)/folder(s). More information in <errors> object.'; break;\n }\n }\n // Extract APi specific errors\n if (api === 'SYNO.FileStation.Extract') {\n switch (code) {\n case 1400: return 'Failed to extract files.'; break;\n case 1401: return 'Cannot open the file as archive.'; break;\n case 1402: return 'Failed to read archive data error'; break;\n case 1403: return 'Wrong password.'; break;\n case 1404: return 'Failed to get the file and dir list in an archive.'; break;\n case 1405: return 'Failed to find the item ID in an archive file.'; break;\n }\n }\n // Compress API specific errors\n if (api === 'SYNO.FileStation.Compress') {\n switch (code) {\n case 1300: return 'Failed to compress files/folders.'; break;\n case 1301: return 'Cannot create the archive because the given archive name is too long.'; break;\n }\n }\n // FileStation specific errors\n switch (code) {\n case 400: return 'Invalid parameter of file operation'; break;\n case 401: return 'Unknown error of file operation'; break;\n case 402: return 'System is too busy'; break;\n case 403: return 'Invalid user does this file operation'; break;\n case 404: return 'Invalid group does this file operation'; break;\n case 405: return 'Invalid user and group does this file operation'; break;\n case 406: return 'Can\\'t get user/group information from the account server'; break;\n case 407: return 'Operation not permitted'; break;\n case 408: return 'No such file or directory'; break;\n case 409: return 'Non-supported file system'; break;\n case 410: return 'Failed to connect internet-based file system (ex: CIFS)'; break;\n case 411: return 'Read-only file system'; break;\n case 412: return 'Filename too long in the non-encrypted file system'; break;\n case 413: return 'Filename too long in the encrypted file system'; break;\n case 414: return 'File already exists'; break;\n case 415: return 'Disk quota exceeded'; break;\n case 416: return 'No space left on device'; break;\n case 417: return 'Input/output error'; break;\n case 418: return 'Illegal name or path'; break;\n case 419: return 'Illegal file name'; break;\n case 420: return 'Illegal file name on FAT file system'; break;\n case 421: return 'Device or resource busy'; break;\n case 599: return 'No such task of the file operation'; break;\n }\n // No specific error found, so call super function\n return super.error(...arguments);\n }", "function callbackBaseName ( response )\n {\n\tif ( response.warnings )\n\t{\n\t var err_msg = response.warnings.join(\"</li><li>\") || \"There is a problem with the API\";\n\t setErrorMessage(\"pe_base_name\", err_msg);\n\t param_errors.base_name = 1;\n\t}\n\t\n\telse if ( response.errors )\n\t{\n\t var err_msg = response.errors.join(\"</li><li>\") || \"There is a problem with the API\";\n\t setErrorMessage(\"pe_base_name\", err_msg);\n\t param_errors.base_name = 1;\n\t}\n\t\n\telse\n\t{\n\t setErrorMessage(\"pe_base_name\", \"\");\n\t param_errors.base_name = 0;\n\t}\n\t\n\tupdateFormState();\n }", "function displayErrorTitleDescription(error) {\n var defaultErrorTitle = \"There Is an Error\";\n var defaultErrorDescription = \"Please Restart Your Application\";\n\n // Create mapping of Ooyala errors to error messages\n var errorMap = {};\n // General API Errors\n errorMap[OO.ERROR.API.NETWORK] = \"Cannot Contact Server\";\n errorMap[OO.ERROR.API.SAS.GENERIC] = \"Invalid Authorization Response\";\n errorMap[OO.ERROR.API.SAS.GEO] = \"This video is not authorized in your location\";\n errorMap[OO.ERROR.API.SAS.DOMAIN] = \"This video is not authorized for your domain\";\n errorMap[OO.ERROR.API.SAS.FUTURE] = \"This video will be available soon\";\n errorMap[OO.ERROR.API.SAS.PAST] = \"This video is no longer available\";\n errorMap[OO.ERROR.API.SAS.DEVICE] = \"This video is not authorized for playback on this device\";\n errorMap[OO.ERROR.API.SAS.PROXY] = \"An anonymous proxy was detected. Please disable the proxy and retry.\";\n errorMap[OO.ERROR.API.SAS.CONCURRENT_STREAMS] = \"You have exceeded the maximum number of concurrent streams\";\n errorMap[OO.ERROR.API.SAS.INVALID_HEARTBEAT] = \"Invalid heartbeat response\";\n errorMap[OO.ERROR.API.SAS.ERROR_DEVICE_INVALID_AUTH_TOKEN] = \"Invalid Ooyala Player Token\";\n errorMap[OO.ERROR.API.SAS.ERROR_DEVICE_LIMIT_REACHED] = \"Device limit reached\";\n errorMap[OO.ERROR.API.SAS.ERROR_DEVICE_BINDING_FAILED] = \"Device binding failed\";\n errorMap[OO.ERROR.API.SAS.ERROR_DEVICE_ID_TOO_LONG] = \"Device id too long\";\n errorMap[OO.ERROR.API.SAS.ERROR_DRM_RIGHTS_SERVER_ERROR] =\n \"General SOAP error from DRM server, will pass message from server to event\";\n errorMap[OO.ERROR.API.SAS.ERROR_DRM_GENERAL_FAILURE] = \"General error with acquiring license\";\n errorMap[OO.ERROR.API.CONTENT_TREE] = \"Invalid Content\";\n errorMap[OO.ERROR.API.METADATA] = \"Invalid Metadata\";\n\n // General Playback Errors\n errorMap[OO.ERROR.PLAYBACK.GENERIC] = \"Could not play the content\";\n errorMap[OO.ERROR.PLAYBACK.STREAM] = \"This video isn't encoded for your device\";\n errorMap[OO.ERROR.PLAYBACK.LIVESTREAM] = \"Live stream is off air\";\n errorMap[OO.ERROR.PLAYBACK.NETWORK] = \"Network connection temporarily lost\";\n\n // General Ooyala Errors\n errorMap[OO.ERROR.UNPLAYABLE_CONTENT] = \"This video is not playable on this player\";\n errorMap[OO.ERROR.INVALID_EXTERNAL_ID] = \"Invalid External ID\";\n errorMap[OO.ERROR.EMPTY_CHANNEL] = \"This channel is empty\";\n errorMap[OO.ERROR.EMPTY_CHANNEL_SET] = \"This channel set is empty\";\n errorMap[OO.ERROR.CHANNEL_CONTENT] = \"This channel is not playable at this time\";\n errorMap[OO.ERROR.STREAM_PLAY_FAILED] = \"This video is not encoded for your device\";\n\n // Chromecast Specific Errors\n // https://developers.google.com/cast/docs/reference/player/cast.player.api.ErrorCode\n errorMap[OO.ERROR.CHROMECAST.MANIFEST] = \"Error loading or parsing the manifest\";\n errorMap[OO.ERROR.CHROMECAST.MEDIAKEYS] = \"Error fetching the keys or decrypting the content\";\n errorMap[OO.ERROR.CHROMECAST.NETWORK] = \"Network error\";\n errorMap[OO.ERROR.CHROMECAST.PLAYBACK] = \"Error related to media playback\";\n\n var errorTitle = defaultErrorTitle;\n // Use the error mapping created to generate the description\n var errorDescription = (!errorMap[error]) ? defaultErrorDescription : errorMap[error];\n\n // Set the DOM elements to its respective title and description\n document.querySelector(\"#error_title\").innerHTML = errorTitle;\n document.querySelector(\"#error_description\").innerHTML = errorDescription;\n }", "onWebViewErrorOccurred(details) {\n this.fire('error');\n this.loadingError_ = true;\n }", "function validateSpeechFailUPResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0002\", \"messageId\");\n equal(se[\"text\"], \"Undefined Parameter\", \"text\");\n equal(se[\"variables\"], \"%1\", \"variables\");\n }\n }\n}", "function handleGetUserMediaError (err) {\n util.trace(err)\n\n switch (err.name) {\n case 'NotFoundError':\n alert('Unable to open your call because no camera and/or microphone were found.')\n break\n case 'SecurityError':\n case 'PermissionDeniedError':\n // Do nothing; this is the same as the user canceling the call.\n break\n default:\n alert('Error opening your camera and/or microphone: ' + err.message)\n break\n }\n}", "function notifyUploadDone(numberOfFiles, error) {\n var url = '${fileUploadDoneUrl}';\n Wicket.Ajax.get( {\n u: url + \"&numberOfFiles=\" + numberOfFiles + \"&error=\" + error\n });\n }", "processPocketAudio(introFile, articleFile, article_id, locale) {\n return new Promise(resolve => {\n polly_tts\n .concatAudio([introFile, articleFile], uuidgen.generate())\n .then(function(audio_file) {\n return polly_tts.uploadFile(audio_file);\n })\n .then(function(audio_url) {\n return polly_tts.getFileMetadata(audio_url);\n })\n .then(function(audio_metadata) {\n resolve(audio_metadata);\n // Delete the local file now that it's uploaded.\n let audio_file = utils.urlToFile(audio_metadata.url);\n polly_tts.deleteLocalFiles(audio_file, function(err) {\n if (err) {\n logger.error('Error removing files ' + err);\n } else {\n logger.debug('all files removed');\n }\n });\n // Send the stitched file off for transcoding.\n xcodeQueue.add(audio_file, article_id, locale);\n });\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the status of MTA services. (only subway rn.) First checks a local cache of the data. Fetches the status via html scraping, if cache expired or unavailable.
function checkStatus() { return new Promise((resolve, reject) => { getStatusFromCache() .then(function(data) { resolve(data); }) .catch(function(err) { resolve(scrapeStatus()); }); }); }
[ "function scrapeStatus() {\n return new Promise((resolve, reject) => {\n request(mtaStatusUrl, (err, response, responseHtml) => {\n if (err) {\n reject(err);\n }\n\n const $ = cheerio.load(responseHtml);\n\n let results = {\n subway: []\n };\n\n $('#subwayDiv').find('tr').each((index, row) => {\n // First row is irrelevant.\n if (index !== 0) {\n\n results.subway.push({\n name: $(row).find('img').attr('alt').replace(/subway|\\s/ig, ''),\n status: $(row).find('span[class^=\"subway_\"]').text(),\n });\n }\n });\n\n // Write to the local cache.\n fs.writeFile(__dirname + cachedData, JSON.stringify(results), (err) => {\n // @todo: handle error\n });\n\n resolve(results);\n });\n });\n}", "function getCacheStatuses() {\n\tgetCacheCount();\n\tgetCacheAvailableCount();\n\tgetCacheDownCount();\n\tgetCacheStates();\n}", "function getCacheStates() {\n\tfunction parseIPAvailable(server, ipField) {\n\t\treturn server.status.indexOf(\"ONLINE\") !== 0 ? server[ipField] : \"N/A\";\n\t}\n\n\tfunction parseBandwidth(server) {\n\t\tif (Object.prototype.hasOwnProperty.call(server, \"bandwidth_kbps\") &&\n\t\t\t\tObject.prototype.hasOwnProperty.call(server, \"bandwidth_capacity_kbps\")) {\n\t\t\tconst kbps = (server.bandwidth_kbps / kilobitsInMegabit).toFixed(2);\n\t\t\tconst max = numberStrWithCommas((server.bandwidth_capacity_kbps / kilobitsInMegabit).toFixed(0));\n\t\t\treturn `${kbps} / ${max}`;\n\t\t} else {\n\t\t\treturn \"N/A\";\n\t\t}\n\t}\n\n\tajax(\"/api/cache-statuses\", function(r) {\n\t\tlet serversArray = Object.entries(JSON.parse(r)).sort((serverTupleA, serverTupleB) => {\n\t\t\treturn -1*serverTupleA[0].localeCompare(serverTupleB[0]);\n\t\t});\n\t\tconst servers = new Map(serversArray);\n\n\t\tconst oldtable = document.getElementById(\"cache-states\");\n\t\tconst table = document.createElement('TBODY');\n\t\tconst interfaceTableTemplate = document.getElementById(\"interface-template\").content.children[0];\n\t\tconst interfaceRowTemplate = document.getElementById(\"interface-row-template\").content.children[0];\n\t\tconst cacheStatusRowTemplate = document.getElementById(\"cache-status-row-template\").content.children[0];\n\t\ttable.id = oldtable.id;\n\n\t\t// Match visibility of interface tables based on previous table\n\t\tconst interfaceRows = oldtable.querySelectorAll(\".encompassing-row\");\n\t\tlet openCachesByName = new Set();\n\t\tfor(const row of interfaceRows) {\n\t\t\tif(row.classList.contains(\"visible\")){\n\t\t\t\topenCachesByName.add(row.querySelector(\".sub-table\").getAttribute(\"server-name\"));\n\t\t\t}\n\t\t}\n\n\t\tfor (const [serverName, server] of servers) {\n\t\t\tconst row = cacheStatusRowTemplate.cloneNode(true);\n\t\t\tconst cacheRowChildren = row.children;\n\t\t\tconst indicatorDiv = cacheRowChildren[0].children[0];\n\n\t\t\tif (Object.prototype.hasOwnProperty.call(server, \"status\") &&\n\t\t\t\t\tObject.prototype.hasOwnProperty.call(server, \"combined_available\")) {\n\t\t\t\tif (server.status.indexOf(\"ADMIN_DOWN\") !== -1 || server.status.indexOf(\"OFFLINE\") !== -1) {\n\t\t\t\t\trow.classList.add(\"warning\");\n\t\t\t\t} else if (!server.combined_available && server.status.indexOf(\"ONLINE\") !== 0) {\n\t\t\t\t\trow.classList.add(\"error\");\n\t\t\t\t} else if (server.status.indexOf(\" availableBandwidth\") !== -1) {\n\t\t\t\t\trow.classList.add(\"error\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcacheRowChildren[1].textContent = serverName;\n\t\t\tcacheRowChildren[2].textContent = server.type || \"UNKNOWN\";\n\t\t\tcacheRowChildren[3].textContent = parseIPAvailable(server, \"ipv4_available\");\n\t\t\tcacheRowChildren[4].textContent = parseIPAvailable(server, \"ipv6_available\");\n\t\t\tcacheRowChildren[5].textContent = server.status || \"\";\n\t\t\tcacheRowChildren[6].textContent = server.load_average || \"\";\n\t\t\tcacheRowChildren[7].textContent = server.query_time_ms || \"\";\n\t\t\tcacheRowChildren[8].textContent = server.health_time_ms || \"\";\n\t\t\tcacheRowChildren[9].textContent = server.stat_time_ms || \"\";\n\t\t\tcacheRowChildren[10].textContent = server.health_span_ms || \"\";\n\t\t\tcacheRowChildren[11].textContent = server.stat_span_ms || \"\";\n\t\t\tcacheRowChildren[12].textContent = parseBandwidth(server);\n\t\t\tcacheRowChildren[13].textContent = server.connection_count || \"N/A\";\n\t\t\ttable.prepend(row);\n\n\t\t\tconst encompassingRow = table.insertRow(1);\n\t\t\tencompassingRow.classList.add(\"encompassing-row\");\n\t\t\tconst encompassingCell = encompassingRow.insertCell(0);\n\t\t\tconst interfaceTable = interfaceTableTemplate.cloneNode(true);\n\t\t\tencompassingCell.colSpan = 14;\n\t\t\t// Add interfaces\n\t\t\tif (Object.prototype.hasOwnProperty.call(server, \"interfaces\")) {\n\t\t\t\tlet interfacesArray = Object.entries(server.interfaces).sort((interfaceTupleA, interfaceTupleB) => {\n\t\t\t\t\treturn -1 * interfaceTupleA[0].localeCompare(interfaceTupleB[0]);\n\t\t\t\t});\n\t\t\t\tserver.interfaces = new Map(interfacesArray);\n\t\t\t\tinterfaceTable.removeAttribute(\"id\");\n\t\t\t\t// To determine what cache this interface table belongs to\n\t\t\t\t// used to ensure servers that were expanded remain expanded when refreshing the data.\n\t\t\t\tinterfaceTable.setAttribute(\"server-name\", serverName);\n\t\t\t\tconst interfaceBody = interfaceTable.querySelector(\".interface-content\");\n\t\t\t\tfor (const [interfaceName, stat] of server.interfaces) {\n\t\t\t\t\tconst interfaceRow = interfaceRowTemplate.cloneNode(true);\n\t\t\t\t\tconst cells = interfaceRow.children;\n\n\t\t\t\t\tcells[0].textContent = interfaceName;\n\t\t\t\t\tcells[1].textContent = parseIPAvailable(stat, \"ipv4_available\");\n\t\t\t\t\tcells[2].textContent = parseIPAvailable(stat, \"ipv6_available\");\n\t\t\t\t\tcells[3].textContent = stat.status || \"\";\n\t\t\t\t\tcells[4].textContent = parseBandwidth(stat);\n\t\t\t\t\tcells[5].textContent = stat.connection_count || \"N/A\";\n\n\t\t\t\t\tif (Object.prototype.hasOwnProperty.call(stat, \"available\")) {\n\t\t\t\t\t if (stat.available === false) {\n\t\t\t\t\t\t\tinterfaceRow.classList.add(\"error\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tinterfaceBody.prepend(interfaceRow);\n\t\t\t\t}\n\t\t\t\trow.onclick = function() {\n\t\t\t\t\tif(encompassingRow.classList.contains(\"visible\")) {\n\t\t\t\t\t\tencompassingRow.classList.remove(\"visible\");\n\t\t\t\t\t\tindicatorDiv.classList.remove(\"down\");\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tencompassingRow.classList.add(\"visible\");\n\t\t\t\t\t\tindicatorDiv.classList.add(\"down\");\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t\telse {\n\t\t\t\tindicatorDiv.classList.add(\"hidden\");\n\t\t\t}\n\n\t\t\tencompassingCell.appendChild(interfaceTable);\n\t\t\t// Row was unhidden previously\n\t\t\tif(openCachesByName.has(serverName)) {\n\t\t\t\trow.click();\n\t\t\t}\n\t\t}\n\n\t\toldtable.parentNode.replaceChild(table, oldtable);\n\t});\n}", "function updateStatus() {\n Packlink.ajaxService.get(\n checkStatusUrl,\n /** @param {{logs: array, finished: boolean}} response */\n function (response) {\n let logPanel = document.getElementById('pl-auto-test-log-panel');\n\n logPanel.innerHTML = '';\n for (let log of response.logs) {\n logPanel.innerHTML += writeLogMessage(log);\n }\n\n logPanel.scrollIntoView();\n logPanel.scrollTop = logPanel.scrollHeight;\n response.finished ? finishTest(response) : setTimeout(updateStatus, 1000);\n }\n );\n }", "function getAvailability() {\r\n fetch(\"templates/availability.php\", { credentials: \"include\" })\r\n .then(response => response.text())\r\n .then(refreshAvailability);\r\n function refreshAvailability(data) {\r\n document.getElementById(\"availability\").innerHTML = data;\r\n setAvilabilityListeners();\r\n }\r\n }", "function loadStatus(page) {\n $(\".page\").css(\"display\", \"none\");\n $(\"#\" + page + \"_status\").css(\"display\", \"block\");\n\n // Clear the page and add the loading sign (this request can take a few seconds)\n $(\"#\" + page + \"_status\").html('<i class=\"fa fa-spinner fa-pulse fa-3x fa-fw center\"></i>');\n\n sendMessage(\"agent/status/\" + page, \"\", \"post\",\n function(data, status, xhr){\n $(\"#\" + page + \"_status\").html(DOMPurify.sanitize(data));\n\n // Get the trace-agent status\n sendMessage(\"agent/getConfig/apm_config.receiver_port\", \"\", \"GET\",\n function(data, status, xhr) {\n var apmPort = data[\"apm_config.debug.port\"];\n if (apmPort == null) {\n apmPort = \"5012\";\n }\n var url = \"http://127.0.0.1:\"+apmPort+\"/debug/vars\"\n $.ajax({\n url: url,\n type: \"GET\",\n success: function(data) {\n $(\"#apmStats > .stat_data\").html(ejs.render(apmTemplate, data));\n },\n error: function() {\n $(\"#apmStats > .stat_data\").text(\"Status: Not running or not on localhost.\");\n }\n })\n }, function() {\n $(\"#apmStats > .stat_data\").html(\"Could not obtain trace-agent port from API.\");\n })\n },function(){\n $(\"#\" + page + \"_status\").html(\"<span class='center'>An error occurred.</span>\");\n });\n}", "static get offline_enabled() {\n if (!PageCache.enabled) return false;\n\n // disable offline in production for now\n // if location.hostname =~ /^whimsy.*\\.apache\\.org$/\n // return false unless location.hostname.include? '-test'\n // end\n return true\n }", "async function isServiceLive() {\n // Fetch the current or next service data\n const service = await fetch(\"https://northlandchurch.online.church/graphql\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\"\n },\n body: JSON.stringify({\n query: CURRENT_SERVICE_QUERY,\n operationName: \"CurrentService\"\n })\n })\n .then((response) => response.json())\n .catch((error) => console.error(error));\n\n // If no service was returned from the API, don't display the countdown\n if (!service.data.currentService || !service.data.currentService.id) {\n return;\n }\n\n // Set the date we're counting down to\n const startTime = new Date(service.data.currentService.startTime).getTime();\n const endTime = new Date(service.data.currentService.endTime).getTime();\n\n // Create a one second interval to tick down to the startTime\n const intervalId = setInterval(function () {\n const now = new Date().getTime();\n\n // If we are between the start and end time, the service is live\n if (now >= startTime && now <= endTime) {\n clearInterval(intervalId);\n $(\".worship-is-live-text\").show();\n \t\t$('#alert-banner').hide();\n return;\n }\n\n // Find the difference between now and the start time\n const difference = startTime - now;\n\n // Time calculations for days, hours, minutes and seconds\n const days = Math.floor(difference / (1000 * 60 * 60 * 24));\n const hours = Math.floor(\n (difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)\n );\n const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));\n const seconds = Math.floor((difference % (1000 * 60)) / 1000);\n\n // If we are past the end time, clear the countdown\n if (difference < 0) {\n clearInterval(intervalId);\n return;\n }\n }, 1000);\n}", "function checkState() {\n \n \n if(currentState.running == false) {\n return;\n }\n \n // get request of the job information\n $.ajax({\n url: \"job?id=\" + currentState.currentId\n , type: \"GET\"\n\n , success: function (data) {\n \n currentState.running = data.finished !== true;\n currentState.ready = data.finished;\n currentState.status = data.status;\n currentState.fileName = data.fileName;\n if (currentState.running) {\n setTimeout(checkState, 1000);\n }\n updateView();\n } \n });\n}", "function updateCache() {\n request('https://hypno.nimja.com/app', function (error, response, body) {\n if (error) {\n console.log(error);\n }\n var data = JSON.parse(body);\n if (data) {\n cache = data;\n parseCacheForSearchAndLookup();\n }\n });\n}", "function getBookStatus(item, isbn){\r\n\tvar libraryAvailability = /Checked In/;\r\n\tvar libraryOnOrder = /On Order/;\r\n\tvar libraryInProcess = /In Process/;\r\n\tvar libraryDueBack = /(\\d{2}\\/\\d{2}\\/\\d{4})/;\r\n\tvar libraryHolds = /holds /;\r\n\tvar notFound = /Sorry, could not find anything matching/;\r\n\r\n\tGM_xmlhttpRequest\r\n\t\t({\r\n\t\tmethod:'GET',\r\n\t\turl: libraryUrlPattern + isbn,\r\n\t\tonload:function(results) {\r\n\t\t\tpage = results.responseText;\r\n\t\t\tif ( notFound.test(page) )\r\n\t\t\t\t{\r\n\t\t\t\tvar due = page.match(notFound)[1]\r\n/*\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"Not carried\",\r\n\t\t\t\t\t\"Not in \" + libraryName,\r\n\t\t\t\t\t\"red\"\r\n\t\t\t\t\t);\r\n*/\t\t\t\t}\r\n\t\t\t//if there are holds\r\n\t\t\telse if ( libraryHolds.test(page) ) {\r\n\t\t\t\t//23 active, 12 inactive\r\n\t\t\t\tvar holds = /\\d{1,} active, \\d{1,} inactive/;\r\n\t\t\t\tvar holdsStr = page.match(holds);\r\n\r\n\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"Holds!\",\r\n\t\t\t\t\tholdsStr + \" holds at \" + libraryName,\r\n\t\t\t\t\t\"#AA7700\" // dark yellow\r\n//\t\t\t\t\t\"#ffffac\" //light yellow\r\n\t\t\t\t\t);\r\n\t\t\t}\r\n\t\t\telse if ( libraryAvailability.test(page) )\r\n\t\t\t\t{\r\n\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"On the shelf now!\",\r\n\t\t\t\t\t\"Available in \" + libraryName,\r\n\t\t\t\t\t\"green\" \r\n//\t\t\t\t\t\"#2bff81\" //light green\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\telse if ( libraryOnOrder.test(page) )\r\n\t\t\t\t{\r\n\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"On order!\",\r\n\t\t\t\t\t\"On order at \" + libraryName,\r\n\t\t\t\t\t\"#AA7700\" // dark yellow\r\n//\t\t\t\t\t\"#ffffac\" //light yellow\r\n\t\t\t\t\t);\r\n\t\t\t\t} \r\n\t\t\telse if ( libraryInProcess.test(page) )\r\n\t\t\t\t{\r\n\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"In process!\",\r\n\t\t\t\t\t\"In process (available soon) at \",\r\n\t\t\t\t\t\"#AA7700\" // dark yellow\r\n//\t\t\t\t\t\"#ffffac\" //light yellow\r\n\t\t\t\t\t);\r\n\t\t\t\t} \r\n\t\t\telse if ( libraryDueBack.test(page) )\r\n\t\t\t\t{\r\n\t\t\t\tvar due = page.match(libraryDueBack)[1]\r\n\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"Due back \" + due,\r\n\t\t\t\t\t\"Due back at \" + libraryName + \" on \" + due,\r\n\t\t\t\t\t\"#AA7700\" // dark yellow\r\n//\t\t\t\t\t\"#ffffac\" //light yellow\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\tsetLibraryHTML(\r\n\t\t\t\t\titem, isbn,\r\n\t\t\t\t\t\"Error\",\r\n\t\t\t\t\t\"Error checking \" + libraryName,\r\n\t\t\t\t\t\"orange\"\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n}", "async _cachingFetch(url) {\n // super-hacky cache clearing without opening devtools like a sucker.\n if (/NUKECACHE/.test(url)) {\n this.cache = null;\n await caches.delete(this.cacheName);\n this.cache = await caches.open(this.cacheName);\n }\n\n let matchResp;\n if (this.cache) {\n matchResp = await this.cache.match(url);\n }\n if (matchResp) {\n const dateHeader = matchResp.headers.get('date');\n if (dateHeader) {\n const ageMillis = Date.now() - new Date(dateHeader);\n if (ageMillis > ONE_HOUR_IN_MILLIS) {\n matchResp = null;\n }\n } else {\n // evict if we also lack a date header...\n matchResp = null;\n }\n\n if (!matchResp) {\n this.cache.delete(url);\n } else {\n return matchResp;\n }\n }\n\n const resp = await fetch(url);\n this.cache.put(url, resp.clone());\n\n return resp;\n }", "function update_server_status()\n{\n _statuslogging =\"Game Status: \";\n $.each(_jsongames.games,function(index, item){\n //only include if scrape property exists\n if(item.hasOwnProperty('scrape')) {\n\n var _status = \"\";\n var _gameindex = index;\n var _game = item.name;\n var _propername = item.propername;\n var _scrape = item.scrape;\n var _state = item.state;\n var _url = item.url;\n var _xpath = item.xpath;\n var _exclude = item.exclude;\n var _qry = \"SELECT * FROM html WHERE url='\" + _url + _xpath;\n console.log(_qry);\n var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(_qry) + \"&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys\";\n var yqlload = $.getJSON(yql, function(data){\n\n if (_scrape == \"cryptic\") { \n _status = data.query.results.body;\n var _serverdetails = '{\"zones\":[{\"zone\":\"' + _propername + '\",\"servers\":[{\"server\":\"Live\",\"status\":\"' + _status + '\"}]}]}';\n set_server_status(_game, _status, _serverdetails, _state); \n }\n if (_scrape == \"zone\" || _scrape == \"server-times\") {\n var _serverdetails = \"\", _status = \"\", _upcnt = 0, _dncnt = 0;\n _serverdetails += '{\"zones\":[';\n var g = 0, h = data.query.results.div.length;\n $.each(data.query.results.div, function(index, _elZone) {\n g++;\n //page specific details\n if (_scrape == \"zone\") { _serverdetails += '{\"zone\":\"' + _elZone.h5.replace('EU','Europe') + '\",\"servers\":['; }\n if (_scrape == \"server-times\") { _serverdetails += '{\"zone\":\"' + _elZone.h4[0].replace('EU','Europe') + '\",\"servers\":['; }\n\n if (_elZone.ul.li.length) {\n //if multiple servers returned\n var i = 0, j = _elZone.ul.li.length;\n $.each(_elZone.ul.li, function(index, _elServer) {\n i++;\n\n //page specific details\n if (_scrape == \"zone\") { var _servername = _elServer.span , _serverclass = _elServer.class; }\n if (_scrape == \"server-times\") { var _servername = _elServer.content , _serverclass = _elServer.span.class; }\n\n if (_exclude.indexOf(_servername) >= 0) { j--; }\n if (_exclude.indexOf(_servername) < 0) { \n\n if (_serverclass.indexOf('online') >= 0) {_upcnt++; _status = \"up\";}\n if (_serverclass.indexOf('offline') >= 0) {_dncnt++; _status = \"down\";}\n _serverdetails += '{\"server\":\"' + _servername + '\",\"status\":\"' + _status + '\"}';\n if (i < j){ _serverdetails += \",\";}\n\n }\n });\n } else {\n //if single server returned\n //page specific details\n if (_scrape == \"zone\") { var _servername = _elZone.ul.li.span , _serverclass = _elZone.ul.li.class; }\n if (_scrape == \"server-times\") { var _servername = _elZone.ul.li.content , _serverclass = _elZone.ul.li.span.class; }\n\n if (_exclude.indexOf(_servername) < 0) { \n\n if (_serverclass.indexOf('online') >= 0) {_upcnt++; _status = \"up\";}\n if (_serverclass.indexOf('offline') >= 0) {_dncnt++; _status = \"down\";} \n _serverdetails += '{\"server\":\"' + _servername + '\",\"status\":\"' + _status + '\"}';\n\n }\n }\n _serverdetails += ']}';\n if (g < h){ _serverdetails += ',';}\n });\n _serverdetails += ']}';\n\n if (_upcnt > 0){ _status = \"up\"; }\n if (_dncnt > 0){ _status = \"down\"; }\n if (_upcnt > 0 && _dncnt > 0 ){ _status = \"mix\"; }\n console.log(_serverdetails);\n set_server_status(_game, _status, _serverdetails, _state);\n } \n })\n .fail(function(){\n _jsongames.games[_gameindex].state=\"failed\";\n }) \n .complete(function(){\n _jsongames.games[_gameindex].state=\"checked\";\n if (_gameindex == _jsongames.games.length - 1) {\n setTimeout(function(){ console.log(_statuslogging); }, 10 * 1000); \n }\n }); \n }\n }); \n}", "function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }", "checkForCachedResponse(request, cacheDuration, freshDataGetter) {\n\t\tconst key = 'service.league.request:' + JSON.stringify(request)\n\n\t\treturn this.core.cache.remember(key, cacheDuration, () => {\n\t\t\tdebug('cache miss', key)\n\n\t\t\treturn freshDataGetter()\n\t\t}).then(response => {\n\t\t\t// Make a copy of response to avoid mucking with cache with mutations (esp. memory based ones)\n\t\t\treturn _.cloneDeep(response)\n\t\t})\n\t}", "function parseCache(){\n for(let page of cache){\n assessData(page);\n }\n }", "function urlCheckAlive(data){\n \n var url = data['url'],\n params = data['params'],\n timeOut = data['timeout'] || null,\n caseId = data['caseid'],\n rType = data['type'] || 'GET',\n crossDomain = data['crossDomain'] || null;\n \n var checkDeferred = $simjq.Deferred(),\n start = new Date().getTime(),\n urlAlive = false;\n \n (function pollUrl(){\n \n console.log('Polling ' + url);\n \n var payload = {\n type: rType,\n url: url,\n data: params\n };\n if(timeOut)\n payload['timeout'] = timeOut;\n if(crossDomain)\n payload['crossDomain'] = crossDomain;\n $simjq.ajax(payload).done(\n function(response){\n console.log('Ping to ' + url + ' was successful');\n urlAlive = true;\n checkDeferred.resolve(response);\n return;\n }\n ).fail(\n function(err){\n \n console.log('Poll failed');\n\n if(new Date().getTime() - start > timeOut){\n console.log('Unable to reach ' + url);\n urlAlive = false;\n checkDeferred.reject(urlAlive);\n return;\n } else {\n setTimeout(pollUrl, 1000);\n }\n }\n ); \n }()); \n \n return checkDeferred.promise();\n}", "function checkStatus() {\n var allDone = true;\n\n for (var _i2 = 0; _i2 < layers.length; _i2++) {\n if (layers[_i2].loaded === false) {\n allDone = false;\n break;\n }\n }\n\n if (allDone) finish();else setTimeout(checkStatus, 500);\n }", "async function checkURL(check, context, ignoreRedirects, globalHeaders) {\r\n if (!check || !check.url) throw \"Check is missing URL!\"\r\n if (!check.statuses) check.statuses = [200]\r\n\r\n if (check.disabled) {\r\n context.log(`### Skipping: ${check.url}`)\r\n return\r\n }\r\n\r\n context.log(`### Checking: ${check.url}`)\r\n\r\n // Use simple HTTP client (see http.js) to make request\r\n // Add any global headers (for all requests)\r\n const client = new HTTP('', false, null, globalHeaders, false)\r\n const startTime = Date.now()\r\n\r\n // Make the HTTP request, with any additional check level headers\r\n let response = await client.get(check.url, check.headers)\r\n\r\n // Handle redirects, which is the default unless ignoreRedirects is set\r\n if (!ignoreRedirects && (response.status == 301 || response.status == 302)) {\r\n context.log(` - Following redirect to ${response.headers.location}`)\r\n response = await client.get(response.headers.location, check.headers)\r\n }\r\n const endTime = Date.now()\r\n\r\n // Debug\r\n if (process.env.WEBMONITOR_DEBUG === \"true\") {\r\n context.log(`### DEBUG: Status: ${response.status}`)\r\n context.log(`### DEBUG: Headers: ${JSON.stringify(response.headers, null, 1)}`)\r\n context.log('### DEBUG: Content: ')\r\n context.log(response.data)\r\n // if (!fs.existsSync(`${__dirname}/debug/`)) { fs.mkdirSync(`${__dirname}/debug`) }\r\n // const fn = check.url.replace(/https?:\\/\\//g, \"\").replace(/\\//g, \":\")\r\n // fs.writeFileSync(`${__dirname}/debug/${fn}.log`, `${response.status}\\n\\n${JSON.stringify(response.headers, null, 1)}\\n\\n${response.data}`)\r\n }\r\n\r\n // Check status code\r\n let msg = ''\r\n const statusOK = check.statuses.includes(response.status)\r\n if (!statusOK) {\r\n msg = `The HTTP status code '${response.status}' wasn't one of: ${check.statuses}`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n\r\n // Look for expected content\r\n if (check.expect) {\r\n let re = new RegExp(check.expect, 'gms')\r\n if (response.data.search(re) == -1) {\r\n msg = `Expected to find '${check.expect}' in content, but it was not found`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n }\r\n\r\n // Look for regex not wanted in content\r\n if (check.dontExpect) {\r\n let re = new RegExp(check.dontExpect, 'gms')\r\n if (response.data.search(re) != -1) {\r\n msg = `The regex '${check.dontExpect}' found in content, but it was not expected`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n }\r\n\r\n // Scan headers for regex\r\n if (check.headerExpect) {\r\n let re = new RegExp(check.headerExpect)\r\n const headers = JSON.stringify(response.headers)\r\n if (headers.search(re) == -1) {\r\n msg = `Response HTTP headers did not contain '${check.headerExpect}'`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n }\r\n\r\n // Check content size minimum\r\n if (check.contentSizeMin) {\r\n if (response.data.length < check.contentSizeMin) {\r\n msg = `Response content was ${response.data.length} bytes, below the threshold of: ${check.contentSizeMin} bytes`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n }\r\n\r\n // Check content size maximum\r\n if (check.contentSizeMax) {\r\n if (response.data.length > check.contentSizeMax) {\r\n msg = `Response content was ${response.data.length} bytes, over the threshold of: ${check.contentSizeMax} bytes`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n }\r\n\r\n // Check response time in milli-seconds\r\n if (check.responseTime) {\r\n const time = endTime - startTime\r\n if (time > check.responseTime) {\r\n msg = `Response time of ${time}ms exceeded the threshold of ${check.responseTime}ms`\r\n context.log(`### - ${msg}`)\r\n return msg\r\n }\r\n }\r\n\r\n return null\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show node in table or show success message
function showNodeOrMessage() { var update = false; status.collection.forEach(function (item) { if (item.get("id") === newNode.get("id")) { item.set(newNode.attributes); update = true; } }); if (!update) { var folder_id = status.collection.node.get('id'), parent_id = newNode.get('parent_id'), sub_folder_id = newNode.get('sub_folder_id'); if (folder_id === parent_id || folder_id === -parent_id) { status.collection.add(newNode, {at: 0}); } else { if ( folder_id !== sub_folder_id && sub_folder_id !== 0 ) { //CWS-5155 var sub_folder = new NodeModel( {id: sub_folder_id }, { connector: status.container.connector, collection: status.collection }); sub_folder.fetch( { success: function () { if ( sub_folder.get('parent_id') === folder_id ) { if (status.collection.findWhere({id: sub_folder.get("id")}) === undefined) { sub_folder.isLocallyCreated = true; status.collection.add(sub_folder, {at: 0}); } } // as the workspace got created at different place // show message after subFolder added to the nodes table successWithLinkMessage(); }, error: function(err) { ModalAlert.showError(lang.ErrorAddingSubfolderToNodesTable); successWithLinkMessage(); }}); } else { // simply show message If the workspace got created // in target location (XYZ folder) but created from (ABC folder) successWithLinkMessage(); } } } }
[ "function showNodeData(d) {\n var object ={};\n object.name = d.name.toString(); // transform to string or it will show and array\n object.type = d.type;\n object.solvers = d.solvers;\n object.status = d.status;\n\n var ppTable = prettyPrint(object);\n document.getElementById('d6_1').innerHTML = \"Node\".bold();\n var item = document.getElementById('d6_2');\n\n if(item.childNodes[0]){\n item.replaceChild(ppTable, item.childNodes[0]); //Replace existing table\n }\n else{\n item.appendChild(ppTable);\n }\n\n}", "function display_nodes_info( node ) \n{\n\twhile( node != null )\n\t{\n\t\tconsole.log( \"Data : \",node.data )\n\t\tnode = node.next\n\t}\n}", "function showParent($node) {\n // just show only one superior level\n var $temp = $node.closest('table').closest('tr').siblings().removeClass('hidden');\n // just show only one line\n $temp.eq(2).children().slice(1, -1).addClass('hidden');\n // show parent node with animation\n var parent = $temp.eq(0).find('.node')[0];\n repaint(parent);\n $(parent).addClass('slide').removeClass('slide-down').one('transitionend', function() {\n $(parent).removeClass('slide');\n if (isInAction($node)) {\n switchVerticalArrow($node.children('.topEdge'));\n }\n });\n }", "function getNodeState($node, relation) {\n var $target = {};\n if (relation === 'parent') {\n $target = $node.closest('table').closest('tr').siblings(':first').find('.node');\n } else if (relation === 'children') {\n $target = $node.closest('tr').siblings();\n } else {\n $target = $node.closest('table').parent().siblings();\n }\n if ($target.length) {\n if ($target.is(':visible')) {\n return {\"exist\": true, \"visible\": true};\n }\n return {\"exist\": true, \"visible\": false};\n }\n return {\"exist\": false, \"visible\": false};\n }", "function showNode(node, color) {\r\n if (color) { \r\n setColor(node, color);\r\n }\r\n resetNode(node, 0);\r\n }", "function showHighScoreTable(table) {\n // Show the table\n var node = document.getElementById(\"highscoretable\");\n console.log(node);\n node.style.setProperty(\"visibility\", \"visible\", null);\n\n // Get the high score text node\n var node = document.getElementById(\"highscoretext\");\n node.innerHTML = \"\";\n\n for (var i = 0; i < 10; i++) {\n // If i is more than the length of the high score table exit\n // from the for loop\n if (i >= table.length) break;\n\n // Add the record at the end of the text node\n addHighScore(table[i], node);\n }\n}", "function nodeTextActive(){\r\n for (var i = 0;i<visTree.orderedNodes.length;i++) {\r\n if (mouseX > visTree.orderedNodes[i].boxLeft && mouseX < visTree.orderedNodes[i].boxRight) {\r\n if (mouseY > visTree.orderedNodes[i].boxTop && mouseY < visTree.orderedNodes[i].boxBottom) {\r\n //sets flag for expanded view\r\n nodeText(visTree.orderedNodes[i],1);\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}", "function showSiblings($node, direction) {\n // firstly, show the sibling td tags\n var $siblings = $();\n if (direction) {\n if (direction === 'left') {\n $siblings = $node.closest('table').parent().prevAll().removeClass('hidden');\n } else {\n $siblings = $node.closest('table').parent().nextAll().removeClass('hidden');\n }\n } else {\n $siblings = $node.closest('table').parent().siblings().removeClass('hidden');\n }\n // secondly, show the lines\n var $upperLevel = $node.closest('table').closest('tr').siblings();\n if (direction) {\n $upperLevel.eq(2).children('.hidden').slice(0, $siblings.length * 2).removeClass('hidden');\n } else {\n $upperLevel.eq(2).children('.hidden').removeClass('hidden');\n }\n // thirdly, do some cleaning stuff\n if (!getNodeState($node, 'parent').visible) {\n $upperLevel.removeClass('hidden');\n var parent = $upperLevel.find('.node')[0];\n repaint(parent);\n $(parent).addClass('slide').removeClass('slide-down').one('transitionend', function() {\n $(this).removeClass('slide');\n });\n }\n // lastly, show the sibling nodes with animation\n $siblings.find('.node:visible').addClass('slide').removeClass('slide-left slide-right').eq(-1).one('transitionend', function() {\n $siblings.find('.node:visible').removeClass('slide');\n if (isInAction($node)) {\n switchHorizontalArrow($node);\n $node.children('.topEdge').removeClass('fa-chevron-up').addClass('fa-chevron-down');\n }\n });\n }", "function displayTable() {\r\n displayOnly(\"#tableOfContents\");\r\n traverseAndUpdateTableHelper();\r\n prepareText(heirarchy.tree[0].sections[0].id);\r\n activePart = 0;\r\n iconEventListeners();\r\n settingsEventListeners();\r\n scrollEventListener();\r\n}", "function update_info_preview_segment(node_id) {\n $('form.my-form-control').addClass('d-none');\n form_selector = 'form#'.concat(node_id);\n $(form_selector).removeClass('d-none');\n // update preview table\n // if (node_name == 'Export_File') {\n // node_name = 'Tokenization';\n // }\n\n $('#preview .table').addClass('d-none');\n table_selector = 'table#'.concat(node_id);\n $(table_selector).removeClass('d-none');\n}", "function showInfoCountry(result) {\n // On rend le tableau visible\n var table = document.getElementById(\"tableInfo\");\n table.style.display = \"initial\";\n \n // On met en titre du tableau le nom du Country\n var country = document.getElementById(\"title\");\n country.innerHTML = result.name;\n \n // On affiche les infos\n showInfo(result);\n}", "function showFamilyTree(familyTree) {\n if (familyTree) {\n var chartConfig = {\n container: '#familyTreeChart',\n scrollbar: 'fancy',\n connectors: {type: 'step'},\n animateOnInit: true,\n animation: {nodeAnimation: 'easeOutBounce', nodeSpeed: 700, connectorsAnimation: 'bounce', connectorSpeed: 700},\n node: {HTMLclass: 'chartNode'}\n };\n var chartData = [chartConfig];\n var nodes = {};\n familyTree.forEach(function(member, index, family) {\n var memberID = member.member_id;\n var parentID = (member.parent_id) ? member.parent_id : member.spouse_id;\n var parent = nodes[parentID];\n var location = (member.location) ? member.location : '';\n var orientation = (!member.parent_id && parent) ? 'EAST' : null; // Add horizontal orientation for the second node in a spouse relation\n var link = {id: memberID, href: '#'};\n var node = {\n text: {name: member.name, title: location},\n orientation: orientation,\n link: link\n };\n if (parent) {\n node['parent'] = parent;\n }\n if (member['fb_id']) {\n node['image'] = 'http://graph.facebook.com/' + member['fb_id'] + '/picture';\n }\n //console.log('node: ' + JSON.stringify(node));\n nodes[member.member_id] = node;\n chartData.push(node);\n });\n var tree = new Treant(chartData);\n }\n}", "function showAttrs(node, opt) {\n\t\tvar i;\n\t\tvar out = \"<table class='ms-vb' width='100%'>\";\n\t\tfor (i=0; i < node.attributes.length; i++) {\n\t\t\tout += \"<tr><td width='10px' style='font-weight:bold;'>\" + i + \"</td><td width='100px'>\" +\n\t\t\t\tnode.attributes.item(i).nodeName + \"</td><td>\" + checkLink(node.attributes.item(i).nodeValue) + \"</td></tr>\";\n\t\t}\n\t\tout += \"</table>\";\n\t\treturn out;\n\t} // End of function showAttrs", "function displayResult() {}", "function showAccountTable() {\r\n actionTable.style.display = 'none';\r\n accountTable.style.display = 'table';\r\n back.style.display = 'inline-block';\r\n}", "function setSelectedNode(node) {\n selected_node = node;\n var selectedNodeLabel = d3.select('#edit-pane');\n // update selected node label\n selectedNodeLabel.html(selected_node ? '<strong>' + selected_node.lbl + ': ' + selected_node.wid + '</strong>' : 'No state selected');\n\n }", "function nr_basicRenderNode(node,divid,titleid)\n{\n\tvar div = $('#'+divid);\n\tdiv.empty();\n\tvar title = $('#'+titleid);\n\tvar ttext = su_getNodeShortLabel(node);\n\ttitle.text(ttext);\n\tdocument.title=ttext;\n\n\t// loop over properties\n\tparr = su_getNodePropertyAndDisplayNames(node.type,node);\n\tvar len = parr.length;\n\tvar prop = null;\n\tvar disp = null;\n\tvar val = null;\n\tvar row = null;\n\tvar lc = null;\n\tvar rc = null;\n\tfor(var i=0; i<len; i++)\n\t{\n\t\tprop = parr[i][0];\n\t\tdisp = parr[i][1];\n\t\tval = node[prop];\n\t\tif(isEmpty(val)) val = node[prop.toLowerCase()];\n\t\tif(isEmpty(val)) continue;\n\t\t\n\t\trow = $('<div class=\"w3-row\"></div>');\n\t\tlc = $('<div class=\"w3-col s1 w3-theme-d3 w3-center\"><p>'+disp+'</p></div>');\n\t\trc = $('<div class=\"w3-col s5 w3-theme-l3\"><p>&nbsp;&nbsp;'+val+'</p></div>');\n\t\trow.append(lc);\n\t\trow.append(rc);\n\t\tdiv.append(row);\n\t}\n} // end nr_basicRenderNode", "renderSaveSuccessful()\n\t{\n\n\t\tif(this.state.isSaveSuccessful)\n\t\t{\n\n\t\t\treturn(<Message positive>\n\t\t\t\t\t\t<Message.Header>Successfully added an edit to the corpus!</Message.Header>\n\t\t\t\t </Message>)\n\n\t\t}\n\n\t}", "function switchContent() {\n let nodeId= $(clickedNode).attr('id');\n let node = nodeMap.get(nodeId);\n $(clickedNode).children(\".node_inhalt\").toggleClass(\"invis\");\n if($(clickedNode).children(\".node_inhalt\").hasClass(\"invis\")){\n node.toggleToAbstract();\n node.focus(); }\n else{\n node.toggleToDetailed();\n }\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to edit a subshape.
function show_shape_edit(shape_key, subshape_index) { let div, i; let dom_element = (subshape_index == 0) ? data_editor.dom.edit : data_editor.dom.edit2; DOM.removeChilds(dom_element, true); DOM.cdiv(dom_element, null, "edit_title", "SubShape " + subshape_index); if(subshape_index in data_editor.definition.shapes[shape_key].subshapes) { let ss = data_editor.definition.shapes[shape_key].subshapes[subshape_index]; // Flat Normals div = DOM.cdiv(dom_element, null, "edit_section"); DOM.clabel(div, null, "edit_label", "Faces are flat.", "ss_flat_normals_" + subshape_index); data_editor.dom["ss_flat_normals_" + subshape_index] = DOM.ci_checkbox(div, null, "ss_flat_normals_" + subshape_index); data_editor.dom["ss_flat_normals_" + subshape_index].checked = ss.flat_normals; // Texture let texture_options = []; for(let x = 0; x < data_editor.definition.textures.length; x++) texture_options.push([data_editor.definition.textures[x], data_editor.definition.textures[x]]); div = DOM.cdiv(dom_element, null, "edit_section"); DOM.clabel(div, null, "edit_label", "Texture", "ss_texture_" + subshape_index); data_editor.dom["ss_texture_" + subshape_index] = DOM.cselect(div, "ss_texture_" + subshape_index, null, texture_options); data_editor.dom["ss_texture_" + subshape_index].value = ss.texture; // Color let r = ss.color >> 16; let g = (ss.color >> 8) & 0xff; let b = ss.color & 0xff; div = DOM.cdiv(dom_element, null, "edit_section"); DOM.clabel(div, null, "edit_label", "Color"); DOM.clabel(div, null, "edit_label_s", "Red", "ss_colorr_" + subshape_index); data_editor.dom["ss_colorr_" + subshape_index] = DOM.ci_text(div, "ss_colorr_" + subshape_index, "edit_input_s"); data_editor.dom["ss_colorr_" + subshape_index].value = r; DOM.clabel(div, null, "edit_label_s", "Green", "ss_colorg_" + subshape_index); data_editor.dom["ss_colorg_" + subshape_index] = DOM.ci_text(div, "ss_colorg_" + subshape_index, "edit_input_s"); data_editor.dom["ss_colorg_" + subshape_index].value = g; DOM.clabel(div, null, "edit_label_s", "Blue", "ss_colorb_" + subshape_index); data_editor.dom["ss_colorb_" + subshape_index] = DOM.ci_text(div, "ss_colorb_" + subshape_index, "edit_input_s"); data_editor.dom["ss_colorb_" + subshape_index].value = b; // Apply button div = DOM.cdiv(dom_element, null, "edit_section_end"); DOM.cbutton(div, null, "button_mini", "Apply", {shape_key: shape_key, subshape_index: subshape_index}, show_shape_edit_apply); // Elements of this subshape div = DOM.cdiv(dom_element, null, "edit_section"); DOM.clabel(div, null, "edit_label", "Elements"); for(let x = 0; x < ss.elements.length; x++) { DOM.cbutton(div, null, "button_mini", "" + x, {shape_key: shape_key, subshape_index: subshape_index, element_index: x}, (ev, data) => { show_shape_element(data.shape_key, data.subshape_index, data.element_index); }); } div = DOM.cdiv(dom_element, null, "edit_section"); DOM.clabel(div, null, "edit_label", "Add Element"); DOM.cbutton(div, null, "button_mini", "Vertex List", {shape_key: shape_key, subshape_index: subshape_index}, show_shape_edit_addelement); DOM.cbutton(div, null, "button_mini", "Cube", {shape_key: shape_key, subshape_index: subshape_index}, show_shape_edit_addcube); data_editor.dom["subshape_element_container_" + subshape_index] = DOM.cdiv(div, null, "element_container"); } else { DOM.cbutton(dom_element, null, "button_mini", "Enable this subshape", {shape_key: shape_key, subshape_index: subshape_index}, show_shape_edit_enable_subshape); } }
[ "function editShapes(shapes, editPart) {\n for (var i=0, n=shapes.length; i<n; i++) {\n shapes[i] = editShapeParts(shapes[i], editPart);\n }\n}", "function refactorShape(id){\r\n\tsciMonk.viewStack.pop();\r\n\tsciMonk.placementType = \"shape\";\r\n\tsciMonk.currentShape.shape = sciMonk.currentModel.shapes[id].shape;\r\n\tsciMonk.currentShape.scaledShape = sciMonk.currentModel.shapes[id].shape;\r\n\tsciMonk.currentShape.originalShape = sciMonk.currentModel.shapes[id].shape;\r\n\tsciMonk.currentShape.type = sciMonk.currentModel.shapes[id].shapeType;\r\n\tsciMonk.currentShape.pos = sciMonk.currentModel.shapes[id].pos;\r\n\tsciMonk.clientZ = sciMonk.currentModel.shapes[id].pos[2]; \r\n\tsciMonk.currentShape.scale = sciMonk.currentModel.shapes[id].scale;\r\n\tsciMonk.currentShape.rot = sciMonk.currentModel.shapes[id].rot;\r\n\tvar color = sciMonk.currentModel.shapes[id].colour;\r\n\tsciMonk.currentShape.colour = color;\r\n\tdocument.getElementById('colourPicker').value = \"#\"+decToHex(color[0])+decToHex(color[1])+decToHex(color[2]);\r\n\tsciMonk.currentModel.shapes = removeElement(sciMonk.currentModel.shapes,id);\r\n\t\t\r\n\tupdateShapeList();\r\n\tsciMonk.update=true;\r\n\tsciMonk.currentModel.nr--;\r\n\t\r\n\tvar i =0;\r\n\tfor(i=0;i<sciMonk.currentModel.shapes.length;i++){\r\n\t\tsciMonk.currentModel.shapes.shapeId = i;\r\n\t}\r\n}", "function expandedShape(){\n if(Object.keys(currentSelection).length > 2){\n noFill()\n stroke(\"rgba(\" + colors.red + \",\" + colors.green + \",\" + colors.blue + \",\" + vol + \")\")\n strokeWeight(3)\n beginShape();\n for(x in currentSelection){\n var sel = currentSelection[x]\n vertex(h+(h*sel[\"vert\"][0]*(fcount/4)), h+(h*sel[\"vert\"][1]*(fcount/4)))\n bezierVertex(h+(h*sel[\"vert\"][2]*(fcount/4)),h+(h*sel[\"vert\"][3]*(fcount/4)),\n h+(h*sel[\"vert\"][4]*(fcount/4)),h+(h*sel[\"vert\"][5]*(fcount/4)),\n h*sel[\"vert\"][6],h*sel[\"vert\"][7])\n }\n endShape(CLOSE);\n }\n}", "_applyShapeAtSide(shape, side) {\n const viewBox = ShapeWebcomponent.registeredShapes[shape].viewBox || '0 0 1440 320';\n const ratio = viewBox.split(' ')[2] / viewBox.split(' ')[3];\n // create and append the svg code\n this[`_${side}`] = __strToHtml(`<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"${viewBox}\" side=\"${side}\" ratio=\"${ratio || 4.5}\"><path fill=\"currentColor\" fill-opacity=\"1\" d=\"${ShapeWebcomponent.registeredShapes[shape].shape || shape}\"></path></svg>`);\n this.appendChild(this[`_${side}`]);\n }", "function alterPolygon() {\n if (drawMode === true) return;\n\n var alteredPoints = [];\n var selectedP = d3.select(this);\n var parentNode = d3.select(this.parentNode);\n \n //select only the elements belonging to the parent <g> of the selected circle\n var circles = d3.select(this.parentNode).selectAll('circle');\n var polygon = d3.select(this.parentNode).select('polygon');\n\n\n var pointCX = d3.event.x;\n var pointCY = d3.event.y;\n\n\n //rendering selected circle on drag\n selectedP.attr(\"cx\", pointCX).attr(\"cy\", pointCY);\n\n //loop through the group of circle handles attatched to the polygon and push to new array\n for (var i = 0; i < polypoints.length; i++) {\n\n var circleCoord = d3.select(circles._groups[0][i]);\n var pointCoord = [circleCoord.attr(\"cx\"), circleCoord.attr(\"cy\")];\n alteredPoints[i] = pointCoord;\n\n }\n\n //re-rendering polygon attributes to fit the handles\n polygon.attr(\"points\", alteredPoints);\n bbox = parentNode._groups[0][0].getBBox();\n }", "function toggleShape($li,editable) {\n \t$li.each(function() {\n \t\tvar $parent = $(this);\n \t\tvar index = $('.edit',$parent).attr('data-index');\n \t\tvar isCircle = $('.circle.button',$parent).hasClass('active');\n \t\t\n \t\tif (isCircle) {\n \t\t\tcircles[index].editable = editable;\n \t\t\tcircles[index].draggable = editable;\n \t\t\tcircles[index].setMap(null);\n \t\t\tcircles[index].setMap(maps[index]);\n \t\t} else {\n \t\t\trectangles[index].editable = editable;\n \t\t\trectangles[index].draggable = editable;\n \t\t\trectangles[index].setMap(null);\n \t\t\trectangles[index].setMap(maps[index]);\n \t\t};\n \t});\n }", "changeSize() {\n // Calculate the distance between the mouse and the center of the shape\n this.distanceFromCenterX = mouseX - this.x;\n this.distanceFromCenterY = mouseY - this.y;\n // Change width and height according to the mouse position\n this.width = 2 * (this.distanceFromCenterX);\n this.height = 2 * (this.distanceFromCenterY);\n }", "function AddShapeToCanvas(shape){\n self.canvas.add(shape);\n self.DropDefault_X +=10;\n self.DropDefault_Y +=10; \n self.canvas.isDrawingMode = false; \n }", "function selectShape( shape )\r\n{\r\n if( shape != undefined )\r\n\tselectShapeById( shape.id );\r\n}", "function updateShapePointer() {\n selectedShape.oldFillColor = selectedShape.fillColor;\n selectedShape.oldLineColor = selectedShape.lineColor;\n selectedShape.oldLineWidth = selectedShape.lineWidth;\n shapeArray[shapeArrayPointer++] = selectedShape;\n}", "function toggleShapes(){\n\tif (shapesOn) {\n\t\tshapesOn = false;\n\t} else {\n\t\tshapesOn = true;\n\t}\n}", "function rotateShape() {\n removeShape();\n currentShape.shape = rotate(currentShape.shape, 1);\n if (collides(grid, currentShape)) {\n currentShape.shape = rotate(currentShape.shape, 3);\n }\n applyShape();\n }", "add(shape) {\n // store shape offset\n var offset = shape.__position;\n\n // reset shapes list cache\n this.__shapes_list_c = void 0;\n\n // add shape to list of shapes and fix position\n this.__shapes.push({\n shape: shape,\n offset: offset.clone()\n });\n shape.set_position(this.__position.add(offset));\n\n // reset bounding-box\n this.reset_aabb();\n\n // set shape tags to be the composite shape tags\n shape.__collision_tags_val = this.__collision_tags_val;\n shape.__collision_tags = this.__collision_tags;\n\n // set shape debug colors\n shape.__override_fill_color = this.__override_fill_color;\n shape.__override_stroke_color = this.__override_stroke_color;\n\n // return the newly added shape\n return shape;\n }", "function applyShape() {\n //for each value in the current shape (row x column)\n for (var row = 0; row < currentShape.shape.length; row++) {\n for (var col = 0; col < currentShape.shape[row].length; col++) {\n //if its non-empty\n if (currentShape.shape[row][col] !== 0) {\n //set the value in the grid to its value. Stick the shape in the grid!\n grid[currentShape.y + row][currentShape.x + col] = currentShape.shape[row][col];\n }\n }\n }\n }", "function shapegroup3() {\n circle(-150, shapeY3, bgshapesize);\n ellipse(-50, shapeY3, 40, bgshapesize);\n rect(50, shapeY3, 30, bgshapesize);\n square(150, shapeY3, bgshapesize, 5);\n}", "function generateShibeShape() {\n const showShape = document.getElementById('shape-preview')\n\n $(document).ready(function() {\n $('#generate').on(\"click\", function(event) {\n event.preventDefault()\n inputSelectColor()\n inputSelectShape()\n fillWithShibe()\n showShape.style.display = \"block\"\n })\n })\n}", "function move_shape(this_animal, delay_duration, animation_duration){\n this_animal.animal_shape\n .transition()\n .delay(delay_duration)\n .duration(animation_duration)\n .attr('cx', ((this_animal.x_current + 1) * environment_settings.space_width_px) + environment_settings.space_width_px / 2)\n .attr('cy', ((this_animal.y_current + 1) * environment_settings.space_width_px) + environment_settings.space_width_px / 2);\n}", "function newShape() {\n var id = Math.floor( Math.random() * shapes.length );\n var shape = shapes[ id ]; // maintain id for color filling\n\n current = [];\n for ( var y = 0; y < 4; ++y ) {\n current[ y ] = [];\n for ( var x = 0; x < 4; ++x ) {\n var i = 4 * y + x;\n if ( typeof shape[ i ] != 'undefined' && shape[ i ] ) {\n current[ y ][ x ] = id + 1;\n }\n else {\n current[ y ][ x ] = 0;\n }\n }\n }\n \n // new shape starts to move\n freezed = false;\n var max = COLS - 4;\n // Random X\n var testX = Math.floor(Math.random() * 5) + 2; // check priv and allways move 2-7 right untill max has been met.\n testX = priv + testX;\n testX = testX % max;\n priv = testX;\n\n\n\n // position where the shape will evolve\n currentX = testX;\n currentY = 0;\n}", "static _create2DShape (typeofShape, width, depth, height, scene) {\n switch (typeofShape) {\n case 0:\n var faceUV = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV[4] = new BABYLON.Vector4(0, 0, 1, 1)\n faceUV[5] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options = {\n width: width,\n height: height,\n depth: depth,\n faceUV: faceUV\n }\n\n return BABYLON.MeshBuilder.CreateBox('pin', options, scene)\n case 1:\n var faceUV2 = new Array(6)\n for (let i = 0; i < 6; i++) {\n faceUV2[i] = new BABYLON.Vector4(0, 0, 0, 0)\n }\n faceUV2[0] = new BABYLON.Vector4(0, 0, 1, 1)\n \n var options2 = {\n diameterTop: width,\n diameterBottom: depth,\n height: height,\n tessellation: 32,\n faceUV: faceUV2\n }\n\n return BABYLON.MeshBuilder.CreateCylinder('pin', options2, scene)\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
highlight the map marker for a particular station...
function highlightStationMap(station) { console.log(station); m = locData.get(station).marker; m.setMap(null); m.icon = highlightedMapIcon; m.setMap(map); }
[ "function highlight(lat,lng,year,title=null){\r\n\tsetMapOnAll(null);\r\n\tvar index = [lat,lng];\r\n\tx = (year/2) + 350;\r\n\tmovehair(x);\r\n\tvar marker = new google.maps.Marker({\r\n position: new google.maps.LatLng(lat, lng),\r\n title: title,\r\n map: map,\r\n icon: highlightedIcon()\r\n });\r\n\tmarkers.push(marker);\r\n\t// map.setCenter(google.maps.LatLng(lat, lng));\r\n}", "function highlightStationGraph(station) {\n\td3.select('g.lines').selectAll('polyline').each(function (d) {\n\t\tvar sel = d3.select(this);\n\t\tif (station == sel.attr('station')) {\n\t\t\tsel.transition()\n\t\t\t\t.duration(500)\n\t\t\t\t.attr('stroke-width',3)\n\t\t\t\t.attr('stroke','red');\n\t\t}\n\t});\n}", "function selectStation(id) {\n\n reset = false;\n delete selectedFilters.stationStart[-1];\n\n var marker = Hubway.stations[id]['marker'];\n \n selectedFilters['stationStart'][id] = {'row': Hubway.stations[id], 'marker': marker};\n marker.setStyle(markerOptions.stationSelected);\n\n if (!selectAllStations) {\n redraw();\n }\n \n displaySelectedStationsText(); \n}", "function showStations() {\n\n Object.keys(Hubway.stations).forEach(function(id) {\n \n var row = Hubway.stations[id];\n \n var description = '['+ id + '] ' + row.name + ', ' + row['docks'] + ' bikes'; \n var marker = addMarker(row.latitude, row.longitude, description, \"default\", 10 * defaultMarkerRadius, markerOptions.default, activeStation === +id);\n marker.setStyle(markerOptions.stationUnselected);\n\n marker.bindPopup(description, {autoPan: false});\n marker.on('mouseover', function (e) { this.openPopup(); });\n marker.on('mouseout', function (e) { this.closePopup(); });\n\n // add a reference to the original data\n Hubway.stations[id]['marker'] = marker; \n \n if (selectedFilters['stationStart'][row.id]) {\n selectedFilters['stationStart'][row.id] = {'row': row, 'marker': marker};\n marker.setStyle(markerOptions.stationSelected); \n }\n \n marker.on('click', function (e) { \n if (!selectedFilters['stationStart'][row.id]) { \n selectStation(row.id);\n } else {\n removeStation(row.id);\n }\n });\n \n });\n}", "function unHighlightStationMap(station) {\n\tconsole.log(station);\n\tm = locData.get(station).marker;\n\tm.setMap(null);\n\tm.icon = defaultMapIcon;\n\tm.setMap(map);\n}", "function setMarkerByMouse(mse) {\n\t\t\tif (CPicker.markers.active === null) return false;\n\t\t\t\n\t\t\tswitch (CPicker.markers.active.type) {\n\t\t\t\tcase 'hue':\n\t\t\t\t\tsetHueMarkerByMse(CPicker.markers.active.id, mse);\n\t\t\t\t\tCPicker.triangle = updateColorWheel(CPicker.markers.hue[0].angle);\n\t\t\t\t\tsetSatValMarkerByNumber(\n\t\t\t\t\t\tCPicker.markers.active.id,\n\t\t\t\t\t\tCPicker.markers.satv[CPicker.markers.active.id].sat,\n\t\t\t\t\t\tCPicker.markers.satv[CPicker.markers.active.id].val,\n\t\t\t\t\t\tCPicker.triangle\n\t\t\t\t\t);\n\t\t\t\t\tdrawMarkers();\n\t\t\t\t\tupdateTextInputs();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'satv':\n\t\t\t\t\tsetSatValMarkerByMse(CPicker.markers.active.id, mse, CPicker.triangle);\n\t\t\t\t\t// this should not update CPicker.triangle ever\n\t\t\t\t\tupdateColorWheel(CPicker.markers.hue[0].angle);\n\t\t\t\t\tdrawMarkers();\n\t\t\t\t\tupdateTextInputs();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t// throw; // ADD CUSTOM ERROR\n\t\t\t}\n\t\t\t\n\t\t\treturn true;\n\t\t}", "function _highlightTile() {\n var itemSelected = lv_cockpits.winControl.selection.getItems()._value[0];\n if (!itemSelected.data.spotlighted_at) {\n itemSelected.data.spotlighted_at = new Date();\n }\n else\n itemSelected.data.spotlighted_at = null;\n lv_cockpits.winControl.itemDataSource.change(itemSelected.key, itemSelected.data);\n }", "function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\t\n\t\n\tinfo_panel.update(layer.feature.properties)\n\t\n\n\t\n\n\t\n\n}", "function highlightTheseStations(stations) {\n\tvar newHighlights = [];\n\tfor (i in stations) {\n\t\tstation = stations[i];\n\t\tvar idx = highlightedStations.indexOf(station);\n\t\tif (idx==-1) {\n\t\t\t// in the list and not highlighted...\n\t\t\tnewHighlights.push(station);\n\t\t}\n\t}\n\tfor (i in highlightedStations) {\n\t\tstation = highlightedStations[i];\n\t\tvar idx = stations.indexOf(station);\n\t\tif (idx==-1) {\n\t\t\t// highlighted and not in the list...\n\t\t\tnewHighlights.push(station);\n\t\t}\n\t}\n\ttoggleHighlightStations(newHighlights);\n}", "function selectMarker(loc) {\n\t\tlet idOut;\n\t\tidOut = CPicker.markers.hue.findIndex(item => {\n\t\t\treturn distance(loc, item) < MARK_SIZE;\n\t\t});\n\t\tif (idOut > -1) {\n\t\t\treturn {\n\t\t\t\ttype: 'hue', id: idOut\n\t\t\t};\n\t\t}\n\t\t\n\t\tidOut = CPicker.markers.satv.findIndex(item => {\n\t\t\treturn distance(loc, item) < MARK_SIZE;\n\t\t});\n\t\tif (idOut > -1) {\n\t\t\treturn {\n\t\t\t\ttype: 'satv', id: idOut\n\t\t\t};\n\t\t}\n\t\t\n\t\treturn null;\n\t}", "function highlightIndusZones(e) {\n var layer = e.target;\n\n layer.setStyle({\n weight: 2,\n color: 'yellow',\n dashArray: '3',\n fillOpacity: 0.7,\n fillColor: '#F58723'\n });\n\n if (!L.Browser.ie && !L.Browser.opera) {\n layer.bringToFront();\n }\n\n var popupIndus = $(\"<div></div>\",{\n id:\"industrial\",\n css:{}\n });\n var contentIndus = $(\"<h4>Industrial Zones</h4><p>\"+layer.feature.properties.CODE+\"</p><p style='font-size:11px'><i><b>\"+layer.feature.properties.LOCATION+\"</b></i></p>\").appendTo(popupIndus);\n\n popupIndus.appendTo(\"#map\");\n }", "onLayerHighlight() {}", "function highlightFeature(e) {\n\tvar layer = e.target;\n\n\t// style to use on mouse over\n\tlayer.setStyle({\n\t\tweight: 2,\n\t\tcolor: '#666',\n\t\tfillOpacity: 0.7\n\t});\n\n\tif (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {\n\t\tlayer.bringToFront();\n\t}\n\n\tinfo_panel.update(layer.feature.properties)\n\tcreateDashboard(layer.feature.properties)\n}", "function highlightInsulaFromMarker(e){\n\t\tvar insulaMarker = e.target;\n\t\tvar insulaToHighlight = getInsulaFromMarker(insulaMarker);\n\t\tpompeiiInsulaLayer.eachLayer(function(layer){\n\t\t\tif(layer.feature!=undefined && interactive){\n\t\t\t\tif (layer.feature.properties.insula_id == insulaToHighlight){\n\t\t\t\t\thighlightInsula(layer);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function markMap()\n\t{\n\t\tstrResult=req.responseText;\n\n\t\tfltLongitude=getValue(\"<Longitude>\",\"</Longitude>\",11);\n\t\tfltLatitude=getValue(\"<Latitude>\",\"</Latitude>\",10);\n\t\tif( fltLongitude==\"\" || fltLatitude==\"\")\n\t\t{\n\t\t\tshowSearchResultsError('No information found',\"WARNING\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// First Clear any Previous Error Messages \t\n\t\t\tdocument.getElementById(\"divMapErrorBox\").innerHTML=\"\";\n\t\t\tdocument.getElementById(\"divMapErrorBox\").style.visibility=\"visible\";\n\t\t\t\n\t\t\t// Create Html \n\t\t\tstrHtml=\"<table cellspacing=0 cellpadding=0 border=0>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Longitude:</b></td><td width=5></td><td>\"+fltLongitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"<tr><td align=right><b>Latitude:</b></td><td width=5></td><td>\"+fltLatitude+\"</td>\";\n\t\t\tstrHtml=strHtml+\"</table>\";\n\t\t\t\n\t\t\t// Save Location in Global Variables \n\t\t\t//G_CURRENT_POINT=new YGeoPoint(fltLatitude,fltLongitude);\n\t\t\t\n\t\t\t//Show Marker \n\t \t showMarker(fltLatitude, fltLongitude,13,\"\",strHtml);\n\t \t \n\t \t //document.getElementById('mapContainer').innerHTML=\"Problems ..........\";\n\t\t} \n\t}", "function setMarkerIconActive(marker) {\n setMarkerIcon(marker, 'yellow', 'dot');\n}", "function setMarkerStopped(marker) {\n marker.getIcon().fillColor = \"red\";\n }", "function addHighlight(feature) {\n //add feature to map\n var vectors = app.mapPanel.map.getLayersByName(\"highlightLayer\")[0];\n //reproject feature to mapProj (considering all overlays are in epsg:4326)\n if (app.mapPanel.map.baseLayer.projection.projCode != 'EPSG:4326') {\n var geom = feature.geometry.transform(new OpenLayers.Projection('EPSG:4326'), app.mapPanel.map.baseLayer.projection);\n feature = new OpenLayers.Feature.Vector(geom);\n }\n vectors.addFeatures([feature]);\n}", "function highlight(id) {\n var myLine = chart.svg.selectAll('.line').filter(function (d) {\n return d.values[0].values.raw[0][config.id_col] === id[config.id_col];\n });\n myLine.select('path').attr('stroke-width', 4);\n\n var myPoints = chart.svg.selectAll('.point').filter(function (d) {\n return d.values.raw[0][config.id_col] === id[config.id_col];\n });\n myPoints.select('circle').attr('r', 4);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO: Rename to make it clear that this is used to check if account can be created and that it throws. requireAccountNotExists?
async checkNewAccount(accountId) { if (!this.isLegitAccountId(accountId)) { throw new Error('Invalid username.'); } // TODO: This check doesn't seem up to date on what are current account name requirements // TODO: Is it even needed or is checked already both upstream/downstream? if (accountId.match(/.*[.@].*/)) { if (!accountId.endsWith(`.${ACCOUNT_ID_SUFFIX}`)) { throw new Error('Characters `.` and `@` have special meaning and cannot be used as part of normal account name.'); } } if (await this.accountExists(accountId)) { throw new Error('Account ' + accountId + ' already exists.'); } return true; }
[ "async shouldRequestAccountName() {\n return false;\n }", "async function maybeCreateAccount(\n near,\n masterAccountId,\n accountId,\n accountPK,\n initBalance,\n contractPath\n) {\n if (!(await accountExists(near, accountId))) {\n console.log('Account %s does not exist creating it.', accountId)\n const masterAccount = new nearlib.Account(near.connection, masterAccountId)\n const balance = new BN(initBalance)\n let accountCreated = false\n for (let i = 0; i < RETRY_NONCE; i++) {\n try {\n await masterAccount.createAccount(accountId, accountPK, balance)\n accountCreated = true\n break\n } catch (e) {\n if (e.type && e.type === 'AccountAlreadyExists') {\n // Last createAccount can timeout, but actually success later\n accountCreated = true\n break\n }\n // retry on timeout, nonce error, and socket hangout\n }\n }\n if (!accountCreated) {\n console.log(\n `Failed to create account %s in ${RETRY_NONCE} retries due to nonce`,\n accountId\n )\n process.exit(1)\n }\n\n console.log('Created account %s', accountId)\n\n const account = new nearlib.Account(near.connection, accountId)\n\n let contractDeployed = false\n for (let i = 0; i < RETRY_NONCE; i++) {\n try {\n const data = fs.readFileSync(contractPath)\n await account.deployContract(data)\n contractDeployed = true\n break\n } catch (e) {\n if (e.message.includes('Transaction nonce')) {\n continue\n }\n console.log(\n 'Failed to deploy contract to account %s. ERROR: %s',\n accountId,\n e\n )\n process.exit(1)\n }\n }\n if (!contractDeployed) {\n console.log(\n `Failed to deploy contract to account %s in ${RETRY_NONCE} retries due to nonce`,\n accountId\n )\n process.exit(1)\n }\n console.log('Deployed contract to account %s', accountId)\n }\n}", "function createCustomerIfNotExist()\n{\n\tvar telNo='';\n\n\ttry\n\t{\n\t\tif(custIntID == 0 || custIntID == '' || custIntID == null)\n\t\t{\n\t\t\t//***************************************************\n\t\t\t// create the customer\n\t\t\t//***************************************************\n\t\t\ttelNo = simRecord.getFieldValue('custrecord_sim_phone_number');\n\t\t\tnlapiLogExecution('audit', 'createCustomerIfNotExist telNo', telNo);\n\t\t\t\n\t\t\tcustIntID = createCustomer(telNo);\n\n\t\t}\n\t\t\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"createCustomerIfNotExist\", e);\t\t\t\t\n\t} \n\n}", "async function verifyAccount(near, accountId) {\n if (!(await accountExists(near, accountId))) {\n console.log(\n 'Failed to fetch state of the %s account. Is it initialized?',\n accountId\n )\n process.exit(1)\n }\n\n if (!(await accountHasTheKey(near, accountId))) {\n console.log(\n 'Account %s does not have the access key that can be used to operate with it.',\n accountId\n )\n process.exit(1)\n }\n return true\n}", "function createAccount (account) {\r\n accounts.push(account);\r\n return account;\r\n}", "function RegisterAccount(username, pass, email, phone, name, birthday, sex, avatarLink) {\n user.ThemUser(username, name, birthday, sex, phone, email, pass, avatarLink);\n return userIsExisting(username);\n}", "function findOrCreateAccount(username, facebookUserId, email, firstName, lastName) {\n\tvar deferred = Q.defer();\n\tthis.findAccountByUsername(username)\n\t\t.then(function(account) {\n\t\t\tif (account && account.username && account.username !== '') {\n\t\t\t\tdeferred.resolve(account); // Found!\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// Let's create the account\n\t\t\t\tcreateAccount(username, ' ', firstName, lastName, email, facebookUserId)\n\t\t\t\t\t.then(function(account) {\n\t\t\t\t\t\tdeferred.resolve(account);\n\t\t\t\t\t});\n\t\t\t}\n\t\t})\n\t\t.fail(function(err) {\n\t\t\tdeferred.reject(err);\n\t\t});\n\treturn deferred.promise;\n}", "returnableAccount(account){}", "async function validateExistence(req, res, next){\n try{\n const { username, email } = req.body;\n const [user_database] = await sequelize.query(\n `SELECT * FROM user_database`,\n { raw: true },\n );\n \n const user = user_database.find( item => item.username == username || item.email == email);\n const userExist = Boolean(user);\n\n if(!userExist){\n next();\n }else{\n throw 'Este usuario ya existe en la base de datos';\n };\n }catch(fail){\n res.json({ Error: fail });\n };\n}", "async notExists(identifier) {\n try {\n await this.findComponent(identifier);\n } catch (e) {\n if (e.name == \"ComponentNotFoundError\") {\n return true;\n }\n throw e;\n }\n throw new Error(`Component with identifier ${identifier} was present`);\n }", "function _noUsernameError() {\n\tthrow new Error('A username is required, for example \"dfox\"');\n}", "function pessimistic_create_owner(attempt, username, cb) {\n\tvar options = {\n\t\tpeer_urls: [helper.getPeersUrl(0)],\n\t\targs: {\n\t\t\tmarble_owner: username,\n\t\t\towners_company: process.env.marble_company\n\t\t}\n\t};\n\tmarbles_lib.register_owner(options, function (e) {\n\n\t\t// --- Does the user exist yet? --- //\n\t\tif (e && e.parsed && e.parsed.indexOf('owner already exists') >= 0) {\n\t\t\tconsole.log('');\n\t\t\tlogger.debug('finally the user exists, this is a good thing, moving on\\n\\n');\n\t\t\tcb(null);\n\t\t}\n\t\telse {\n\n\t\t\t// -- Try again -- //\n\t\t\tif (attempt < 4) {\n\t\t\t\tsetTimeout(function () {\t\t\t\t\t\t\t\t//delay for peer catch up\n\t\t\t\t\tlogger.debug('owner existance is not yet confirmed, trying again', attempt, username, Date.now());\n\t\t\t\t\treturn pessimistic_create_owner(++attempt, username, cb);\n\t\t\t\t}, helper.getBlockDelay() + 1000 * attempt);\n\t\t\t}\n\n\t\t\t// -- Give Up -- //\n\t\t\telse {\n\t\t\t\tlogger.debug('giving up on creating the user', attempt, username, Date.now());\n\t\t\t\tif (cb) return cb(e);\n\t\t\t\telse return;\n\t\t\t}\n\t\t}\n\t});\n}", "function createUserAttempt(userName,password){\n if (userNameExists(userName) == 1) return -1;\n\n else return createNewUser(userName,password);\n}", "function checkCreateAccountSec(elementId) {\n\tvar validated = true;\n\tvar emailRegEx = /^[a-zA-Z0-9][a-zA-Z0-9\\_\\.\\+\\-]*[a-zA-Z0-9]\\@[a-zA-Z0-9][a-zA-Z0-9\\.\\-]*\\.[a-zA-z]{2,6}/;\n\tvar passwordRegEx = /^(?=\\S+$).{4,20}/;\n\tvar phoneRegEx = /^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$/;\n\tvar zipRegEx = /^\\d{5}$/;\n\tvar $requiredFields = $('input[type=\"text\"],input[type=\"password\"],input[type=\"tel\"]','#frmGuestCreateAcc');\n\t/* Iterating through the list of input fields */\n\t$requiredFields.each(function () {\n\t\t/* Getting the value of input field */\n\t\tvar inputVal = $(this).val().trim();\n\t\tvar elementId = $(this).attr('id');\n\t\tif (!emailRegEx.test(inputVal) && elementId === 'emailId') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!emailRegEx.test(inputVal)&& elementId === 'confrmEmailId') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!passwordRegEx.test(inputVal)&& elementId === 'password') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!phoneRegEx.test(inputVal)&& elementId === 'mobileNo') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!zipRegEx.test(inputVal)&& elementId === 'zipCode') {\n\t\t\tvalidated = false;\n\t\t}\n\t\tif (!inputVal || $(this).hasClass('error_red_border')) {\n\t\t\tvalidated = false;\n\t\t}\n\t});\n\treturn validated;\n}", "function getCreateAccountToken() {\n var params_0 = {\n action: \"query\",\n meta: \"tokens\",\n type: \"createaccount\",\n format: \"json\"\n };\n\n request.get({ url: endPoint, qs: params_0 }, function (error, res, body) {\n if (error) {\n return;\n }\n var data = JSON.parse(body);\n createaccount(data.query.tokens.createaccounttoken);\n });\n}", "createAccount()\n {\n account = this.web3.eth.accounts.create();\n\n vaultData.account_list.push(account)\n\n this.selectAccount( account.address )\n\n this.saveVaultData( vaultData )\n\n }", "validateOrganisation(ctx, organisation) {\n\t \tconst orgMSPId = ctx.clientIdentity.getMSPID();\n\t \tif (orgMSPId !== organisation) {\n\t\t\t throw new Error(\"Only users from Registrar Organisation can invoke this function call\");\n\t \t}\n \t}", "async function accountsCreateOrUpdate() {\n const subscriptionId =\n process.env[\"NETAPP_SUBSCRIPTION_ID\"] || \"D633CC2E-722B-4AE1-B636-BBD9E4C60ED9\";\n const resourceGroupName = process.env[\"NETAPP_RESOURCE_GROUP\"] || \"myRG\";\n const accountName = \"account1\";\n const body = { location: \"eastus\" };\n const credential = new DefaultAzureCredential();\n const client = new NetAppManagementClient(credential, subscriptionId);\n const result = await client.accounts.beginCreateOrUpdateAndWait(\n resourceGroupName,\n accountName,\n body\n );\n console.log(result);\n}", "async function createMondayAccount(account) {\n console.log('Creting new Monday account:', account.Name)\n await monday.createItem(boardId, account.Id, {\n Name: () => account.Name,\n Phone: () => account.Phone,\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
StructuredHeadingsManager ========================= A heading structure management object that makes it easier for a user to structure the headings in a document by simplifying the user interface and adding features such as heading numbering.
function StructuredHeadingsManager(options, wym) { var shm = this; options = jQuery.extend({ headingIndentToolSelector: "li.wym_tools_indent a", headingOutdentToolSelector: "li.wym_tools_outdent a", enableFixHeadingStructureButton: false, fixHeadingStructureButtonHtml: String() + '<li class="wym_tools_fix_heading_structure">' + '<a name="fix_heading_structure" href="#" title="Fix Heading Structure" ' + 'style="background-image: ' + "url('" + wym._options.basePath + "plugins/structured_headings/ruler_arrow.png')" + '">' + 'Fix Heading Structure' + '</a>' + '</li>', fixHeadingStructureSelector: "li.wym_tools_fix_heading_structure a", headingContainerPanelHtml: String() + '<li class="wym_containers_heading">' + '<a href="#" name="HEADING">Heading</a>' + '</li>', headingContainerPanelSelector: "li.wym_containers_heading a", highestAllowableHeadingLevel: 1, lowestAllowableHeadingLevel: 6 }, options); shm._headingElements = WYMeditor.HEADING_ELEMENTS .slice(options.highestAllowableHeadingLevel - 1, options.lowestAllowableHeadingLevel); shm._limitedHeadingSel = shm._headingElements.join(", "); shm._fullHeadingSel = WYMeditor.HEADING_ELEMENTS.join(", "); shm._options = options; shm._wym = wym; shm.init(); }
[ "function headingRule(n) {\n\t var type = MarkupIt.BLOCKS['HEADING_' + n];\n\t return HTMLRule(type, 'h' + n);\n\t}", "function tocSetupHeadingClasses() {\n\n\tfunction getDepth(element, currentDepth=0) {\n\t const elemParent = tocGetParent(element);\n\t if (elemParent) {\n\t\treturn getDepth(elemParent, currentDepth + 1);\n\t } else {\n\t\treturn currentDepth;\n\t }\n\t}\n\n\tfor (const elem of document.querySelectorAll('#table-of-contents ul')) {\n\t const depth = getDepth(elem);\n\t elem.classList.add('toc');\n\t elem.classList.add('toc-depth-' + depth);\n\t elem.setAttribute('data-toc-depth', depth);\n\t}\n }", "_firstHeading() {\n const headings = this._allHeadings();\n return headings[0];\n }", "function mkHeadingGrouper(by) {\n var last = null;\n return function (ref) {\n /* handle reference groups */\n if ($.type(ref) === 'array') {\n ref = ref[0];\n }\n if (by === \"journal\") {\n return ref.data.bibliographic['container-title'];\n } else if (by === \"appearance\" || by === \"repeated\") {\n if (ref.group.section) {\n /* hack to handle the fact that sometimes we have no\n * group, for unmentioned cites. Use the last one. */\n last = ref.group.section;\n }\n return ref.group.section || last;\n } else if (by === \"license\") {\n return getLicenseShorthand(ref.data);\n } else {\n return null;\n }\n };\n}", "[renderGroupHeading]() {\n\t\tconst self = this;\n\t\tconst doRenderCheckBox = !!self.columns().find((column) => column.type === COLUMN_TYPES.CHECKBOX);\n\n\t\tself[hideCells]();\n\n\t\tif (!self[GROUP_HEADING]) {\n\t\t\tself[GROUP_HEADING] = new Heading({\n\t\t\t\tcontainer: self,\n\t\t\t\twidth: HUNDRED_PERCENT,\n\t\t\t\tclasses: 'grid-group-header',\n\t\t\t\tisExpandable: true,\n\t\t\t\tshouldMainClickExpand: true,\n\t\t\t\tstopPropagation: true\n\t\t\t});\n\t\t}\n\n\t\tself[GROUP_HEADING]\n\t\t\t.isDisplayed(true)\n\t\t\t.data(self.rowData())\n\t\t\t.onExpand(self.onExpandCollapseGroup())\n\t\t\t.onSelect(self.onSelectGroup())\n\t\t\t.isExpanded(!self.rowData().isCollapsed)\n\t\t\t.showCheckbox(doRenderCheckBox)\n\t\t\t.isSelectable(doRenderCheckBox)\n\t\t\t.isSelected(self.isSelected())\n\t\t\t.isIndeterminate(self.isIndeterminate())\n\t\t\t.title(self.rowData().title)\n\t\t\t.subTitle(self.rowData().childCount + ' ' + (self.rowData().footerSuffix || 'items'))\n\t\t\t.image(self.rowData().image ? (self.rowData().image(self.rowData()) || '') : '')\n\t\t\t.buttons(self.rowData().buttons, true);\n\n\t\tdefer(() => self[GROUP_HEADING].resize());\n\t}", "function addHeader(table, headings) {\n var cols = headings.split(\" \");\n var hr = table.insertRow(-1);\n cols.forEach(function (item, index) {\n var hcell=document.createElement('TH')\n hcell.innerHTML = item;\n hr.appendChild(hcell);\n });\n}", "function getHeadingInfo(cell) {\n if (!(cell instanceof MarkdownCell)) {\n return { isHeading: false, headingLevel: 7 };\n }\n let level = cell.headingInfo.level;\n let collapsed = cell.headingCollapsed;\n return { isHeading: level > 0, headingLevel: level, collapsed: collapsed };\n }", "handleHeading(){\n this.sliceString();\n this.post.value = this.beg + \"# \" + this.selection + this.end;\n }", "function buildTableHeading() {\n row = document.createElement(\"tr\");\n\n tableHeadings.forEach(function (heading) {\n console.log(heading);\n row.appendChild(createNodeAndText(\"th\", heading));\n });\n return row;\n }", "function slabTextHeadlines() {\n $(\".home-quote h1\").slabText({\n // Don't slabtext the headers if the viewport is under 479px\n \"viewportBreakpoint\":300\n });\n }", "getTableHeading() {\n return (\n <Entries.Row isHeading={true}>\n { this.getCellLayouts() }\n </Entries.Row>\n );\n }", "collectHeadingsAndKeywords() {\n const $ = cheerio.load(fs.readFileSync(this.pageConfig.resultPath));\n this.collectHeadingsAndKeywordsInContent($(`#${CONTENT_WRAPPER_ID}`).html(), null, false, []);\n }", "_allHeadings() {\n return Array.from(this.querySelectorAll('howto-accordion-heading'));\n }", "parse_header(text){\n\t\tconst head=/^(={1,6})(.+?)(={1,6})$/gm,pos=this.pos;\n\t\thead.lastIndex=pos;\n\t\tconst m=head.exec(text);\n\t\t\n\t\tif(m && m.index==pos){\n\t\t\tthis.pos=m.lastIndex;\n\t\t\t\n\t\t\tconst left=m[1],right=m[3];\n\t\t\tlet section,level,content=m[2];\n\t\t\t\n\t\t\tif(content){\n\t\t\t\tif(left.length==right.length){\n\t\t\t\t\tlevel=left.length;\n\t\t\t\t}\n\t\t\t\telse if(left.length<right.length){\n\t\t\t\t\tlevel=left.length;\n\t\t\t\t\tcontent+='='.repeat(right.length-level);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tlevel=right.length;\n\t\t\t\t\tcontent='='.repeat(left.length-level)+content;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsection=new Section(left.length,content);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconst hl=m[0].length;\n\t\t\t\tlevel=hl>>1;\n\t\t\t\tsection=new Section(level,hl%2?'=':'==');\n\t\t\t}\n\t\t\t\n\t\t\tconst path=this.path;\n\t\t\t\n\t\t\twhile(\n\t\t\t\tpath.length>0 && path[path.length-1].level>=level\n\t\t\t){\n\t\t\t\tpath.pop();\n\t\t\t}\n\t\t\tpath.push(section);\n\t\t\tthis.cur=section;\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}", "_expandHeading(heading) {\n heading.expanded = true;\n }", "function FunH5oSemSection(eltStart) {\n this.ssArSections = [];\n this.ssElmStart = eltStart;\n /* the heading-element of this semantic-section */\n this.ssElmHeading = false;\n\n this.ssFAppend = function (what) {\n what.container = this;\n this.ssArSections.push(what);\n };\n this.ssFAsHTML = function () {\n var headingText = fnH5oGetSectionHeadingText(this.ssElmHeading);\n headingText = '<a href = \"#' + fnH5oGenerateId(this.ssElmStart) + '\">'\n + headingText\n + '</a>';\n return headingText + fnH5oGetSectionListAsHtml(this.ssArSections);\n };\n }", "_nextHeading() {\n const headings = this._allHeadings();\n let newIdx =\n headings.findIndex(heading =>\n heading === document.activeElement) + 1;\n return headings[newIdx % headings.length];\n }", "function formatHeader( str ) {\n var defaultInfo = ['title','author','version','date','description','dependancies','references'];\n var info = {\n title : undefined,\n author : undefined,\n version : undefined,\n date : undefined,\n description : undefined,\n dependancies : undefined,\n references : undefined\n },\n headerinfo = [];\n\n // go thru each line of header\n str.split(/\\|/).forEach( function( line, indx ) {\n\n // parse file attributes and store name + value ( will use markdown to handle links/emphasis )\n headerinfo = line.match(/@(.+?) *?: *?(.+)/);\n\n if ( headerinfo ) {\n info[headerinfo[1]] = cheapMarkdown( headerinfo[2] );\n }\n\n } );\n\n // use custom user formater\n if ( settings.header ) {\n str = settings.headerFormater( info );\n } else {\n // build special `html` for header info\n var sourceFile = '<small><a href=\"'+ settings.source +'\"><span class=\"glyphicon glyphicon-file\"></span></a></small>';\n var authorStr = ( info.author ) ? '<small> by '+info.author + '</small>' : '';\n var descriptionStr = ( info.description ) ? '<p class=\"lead\">'+info.description+'</p>' : '';\n var versionStr = ( info.version ) ? 'Version '+info.version : '';\n var dateStr = ( info.date ) ? ' from '+info.date : '';\n var dependanciesStr = ( info.dependancies ) ? 'Dependancies : '+info.dependancies : '';\n var referencesStr = ( info.references ) ? 'References : '+info.references : '';\n\n str = '<h1>' + sourceFile + info.title + authorStr + '</h1>' + descriptionStr + '<p>'+ versionStr + dateStr +'<br>'+ dependanciesStr + '<br>'+ referencesStr + '</p>';\n\n var usrStr = '';\n // look for other user custom fields\n for (var key in info) {\n if ( $.inArray( key, defaultInfo ) === -1 ) {\n usrStr += key[0].toUpperCase()+key.slice(1)+' : '+info[key]+'<br>';\n }\n }\n\n str += '<p>' + usrStr + '</p>' + '<hr>';\n }\n\n return str;\n }", "_isHeading(elem) {\n return elem.tagName.toLowerCase() === 'howto-accordion-heading';\n }", "function addHeadingToTOC(toc, h, uid, altTitle) {\n const headingID = 'fseNavTo--Heading--' + uid;\n h.classList.add(headingID);\n\n const heading = document.createElement('button');\n heading.appendChild(document.createTextNode(altTitle || h.innerText));\n heading.className = 'fseNavTo--Heading';\n heading.setAttribute('data-heading-id', headingID);\n heading.addEventListener('click', function(e) {\n document.querySelector('.' + e.target.getAttribute('data-heading-id')).scrollIntoView({ behavior: 'smooth' });\n toc.style.display = 'none';\n });\n toc.appendChild(heading);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Keydown event for edit controls
function SEC_onEditControlKeyDown(event){SpinEditControl.onEditControlKeyDown(event);}
[ "function SEC_onEditControlKeyUp(event){SpinEditControl.onEditControlKeyUp(event);}", "function ODBInlineEditKeydown(event, p, path, bracket) {\n var keyCode = ('which' in event) ? event.which : event.keyCode;\n\n if (keyCode == 27) {\n /* cancel editing */\n p.ODBsent = true;\n p.inEdit = false;\n mie_back_to_link(p, path, bracket);\n return false;\n }\n\n if (keyCode == 13) {\n ODBFinishInlineEdit(p, path, bracket);\n return false;\n }\n\n return true;\n}", "handleBoardKeyPress(e) {\n if (!this.state.helpModalOpen && !this.state.winModalOpen) {\n if (49 <= e.charCode && e.charCode <= 57) {\n this.handleNumberRowClick((e.charCode - 48).toString());\n // undo\n } else if (e.key === \"r\") {\n this.handleUndoClick();\n // redo\n } else if (e.key === \"t\") {\n this.handleRedoClick();\n // erase/delete\n } else if (e.key === \"y\") {\n this.handleEraseClick();\n // notes\n } else if (e.key === \"u\") {\n this.handleNotesClick();\n }\n }\n }", "function SEC_onEditControlBlur(event){SpinEditControl.onEditControlBlur(event);}", "function editElement(event){\n\t\t\t\t\tclickedItem.innerHTML = textBox.value;\n\t\t\t\t}", "function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}", "edit() {\n\t\tvar value = this.input.val();\n\n\t\tthis.$el.addClass('editing');\n\t\tthis.input.val(value).focus();\n\t}", "function inputElem_add_byKey(e) {\n\t\n}", "function handleKey (){\n var keyObj = event;\n handleInput(keyObj);\n}", "function updCatEnter(state){\n $('.delete_update').on('keypress', '#updateCat', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setCatValue(state,$('#updateCat'),$('.delete_update'));\n $('#updateCat').val('');\n }\n });\n}", "handleEdit(event) {\n console.log('inside handleEdit');\n this.displayMode = 'Edit';\n }", "function onKeyUp() {\n d3.event.stopPropagation();\n if (d3.event.target.nodeName == 'BODY') {\n // Do not handle \"Backspace\" key event here as it clashes with editing actions in the spec editor.\n // Handle \"Delete\" key event only.\n if (d3.event.key === \"Delete\") {\n let selected = _svg.selectAll('.entity.selected');\n let nItemsSelected = selected._groups[0].length;\n if (nItemsSelected > 0) {\n let event = new CustomEvent(\"delete-entity\", {\n detail: {\n entity: selected.data()[0].data || selected.data()[0],\n }\n });\n container.dispatchEvent(event);\n }\n }\n }\n }", "function editItemOnDblClick(event) {\n var input = $(this).find(\"input[type=text]\");\n var span = $(this).find(\"span\");\n\n span.hide();\n input.show().focus();\n}", "function on_edit_button_click(){\n\t\tif ($(this).text()=='Edit'){\n\t\t\t$(\"#middle\").find(\"button.edit\").text('Edit')\n\t\t\t\t.siblings('span').hide()\n\t\t\t\t.siblings('span.value').show();\n\n\t\t\t$(this).siblings('span').show()\n\t\t \t\t\t .siblings('span.value').hide();\n\t\t\t$(this).text('Cancel');\n\t\t} else {\n\t\t\t$(this).siblings('span').hide().siblings('span.value').show();\n\t\t\t$(this).text('Edit');\n\t\t}\n}", "function handleKeyDownEvent(){\n if(d3.event.keyCode == 49){\n // Number 1: Set start point\n } else if(d3.event.keyCode == 50){\n // Number 2: Set end point\n } else if(d3.event.keyCode == 83){\n // Character S: Start search\n startSearch();\n } else if(d3.event.keyCode == 82){\n // Character R: Reset search\n resetSearch();\n } else if(d3.event.keyCode == 67){\n // Character C: Clear walls\n clearWalls();\n }\n}", "function editMemberNameKeyBoard(e) {\n const inputFiled = e.target.closest('.member-in-list').querySelector('.new-member-name');\n const memberName = e.target.closest('.member-in-list').querySelector('.memebr-name');\n\n\n\n if (e.keyCode === 13) {\n if (e.target.value) {\n\n //to toggle sapn\\inpute\n uppdatMemberInAppData(e, memberName);\n memberName.textContent = inputFiled.value;\n }\n memberName.classList.toggle('displayState')\n inputFiled.classList.toggle('displayState')\n changMemberButtonsClasses(e);\n\n // uppdatMemberInAppData(e)\n\n }\n\n}", "add_keyup(func) {\n this.add_event(\"keyup\", func);\n }", "function input(event_type) {\r\n\tinput_keyboard_options_with_one_state(0, event_type, \"lowercase_alphabet\"); //virtual_keyboard option 0; alphabet\r\n\tinput_keyboard_options_with_two_states(1, event_type, \"lowercase_accent_characters_one\", 8, 9); //virtual_keyboard option 1; accent characters one\r\n\tinput_keyboard_options_with_two_states(2, event_type, \"lowercase_accent_characters_two\", 10, 11); //virtual_keyboard option 2; accent characters two\r\n\tinput_keyboard_options_with_one_state(3, event_type, \"lowercase_accent_characters_three\"); //virtual_keyboard option 3; accent characters three\r\n\tinput_keyboard_options_with_one_state(4, event_type, \"lowercase_accent_characters_four\"); //virtual_keyboard option 4; accent characters four\r\n\tinput_keyboard_options_with_two_states(5, event_type, \"punctuation_numbers_one\", 4, 5); //virtual_keyboard option 5; punctuation and numbers\r\n\tinput_keyboard_options_with_two_states(6, event_type, \"punctuation_numbers_two\", 6, 7); //virtual_keyboard option 6; punctuation\r\n\r\n\tinput_editing_keys(7, event_type, delete_function, \"Delete\"); //delete \r\n\tinput_character_keys(8, event_type, 0, \"KeyQ\") //q (113), Q (81), 1 (49)\r\n\tinput_character_keys(9, event_type, 1, \"KeyW\"); //w (119), W (87), 2 (50)\r\n\tinput_character_keys(10, event_type, 2, \"KeyE\"); //e (101), E (69), 3 (51)\r\n\tinput_character_keys(11, event_type, 3, \"KeyR\"); //r (114), R (82), 4 (52)\r\n\tinput_character_keys(12, event_type, 4, \"KeyT\"); //t (116), T (84), 5 (53)\r\n\tinput_character_keys(13, event_type, 5, \"KeyY\"); //y (121), Y (89), 6 (54)\r\n\tinput_character_keys(14, event_type, 6, \"KeyU\"); //u (117), U (85), 7 (55)\r\n\tinput_character_keys(15, event_type, 7, \"KeyI\"); //i (105), I (73), 8 (56)\r\n\tinput_character_keys(16, event_type, 8, \"KeyO\"); //o (111), O (79), 9 (57)\r\n\tinput_character_keys(17, event_type, 9, \"KeyP\"); //p (112), P (80), 0 (48)\r\n\tinput_editing_keys(18, event_type, backspace_function, \"Backspace\") //backspace\r\n\t\r\n\tinput_whitespace_keys(19, event_type, 9, \"Tab\"); //horizonal tab (9)\r\n\tinput_character_keys(20, event_type, 10, \"KeyA\"); //a (97), A (65), @ (64)\r\n\tinput_character_keys(21, event_type, 11, \"KeyS\"); //s (115), S (83), # (35)\r\n\tinput_character_keys(22, event_type, 12, \"KeyD\"); //d (100), D (68), $ (36)\r\n\tinput_character_keys(23, event_type, 13, \"KeyF\"); //f (102), F (70), & (38)\r\n\tinput_character_keys(24, event_type, 14, \"KeyG\"); //g (103), G (71), * (42)\r\n\tinput_character_keys(25, event_type, 15, \"KeyH\"); //h (104), H (72), ( (40)\r\n\tinput_character_keys(26, event_type, 16, \"KeyJ\"); //j (106), J (74), ) (41)\r\n\tinput_character_keys(27, event_type, 17, \"KeyK\"); //k (107), K (75),' (39)\r\n\tinput_character_keys(28, event_type, 18, \"KeyL\"); //l (108), L (76), \" (34)\r\n\tinput_whitespace_keys(29, event_type, 13, \"Enter\") //enter (13)\r\n\r\n\tinput_caps_lock(30, event_type, 0, 1, 2, 3, \"CapsLock\"); //left caps lock\r\n\tinput_character_keys(31, event_type, 19, \"KeyZ\"); //z (122), Z (90), % (37)\r\n\tinput_character_keys(32, event_type, 20, \"KeyX\"); //x (120), X (88), - (45)\r\n\tinput_character_keys(33, event_type, 21, \"KeyC\"); //c (99), C (67), + (43)\r\n\tinput_character_keys(34, event_type, 22, \"KeyV\"); //v (118), V (86), = (61)\r\n\tinput_character_keys(35, event_type, 23, \"KeyB\"); //b (98), B (66), / (47)\r\n\tinput_character_keys(36, event_type, 24, \"KeyN\"); //n (110), N (78), semicolon (59)\r\n\tinput_character_keys(37, event_type, 25, \"KeyM\"); //m (109), M (77), colon (59)\r\n\tinput_character_keys(38, event_type, 26, \"Comma\"); //comma (44), exclamtion mark (33)\r\n\tinput_character_keys(39, event_type, 27, \"Period\"); //full stop (46), question mark (63)\r\n\tinput_caps_lock(40, event_type, 0, 1, 2, 3, \"CapsLock\"); //right caps lock\r\n\r\n\tinput_keyboard_options_with_two_states(41, event_type, \"punctuation_numbers_one\", 4, 5); // punctuation numbers \r\n\tinput_keyboard_options_with_two_states(42, event_type, \"punctuation_numbers_two\", 6, 7);//punctuation 2\r\n\tinput_whitespace_keys(43, event_type, 32, \"Space\"); //space (32)\r\n\tinput_keyboard_options_with_two_states(44, event_type, \"lowercase_accent_characters_one\", 8, 9); //accent chars\r\n\tinput_keyboard_options_with_two_states(45, event_type, \"lowercase_accent_characters_two\", 10, 11); //accent chars 2\t\r\n}", "keyPress(e) {\n // If enter or tab key pressed on new notebook input\n if (e.keyCode === 13 || e.keyCode === 9) {\n this.addNotebook(e);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A basic binding to value, our base class
function Binding(value){ this.value= value; if(value){ value._binding = this; } }
[ "updateBoundVariable(value) {\n let binddatavalue = this.binddatavalue;\n // return if the variable bound is not static.\n if (this.datavaluesource && this.datavaluesource.execute(DataSource.Operation.IS_API_AWARE)) {\n return;\n }\n else if (this.datavaluesource && !this.datavaluesource.twoWayBinding) {\n return;\n }\n // return if widget is bound.\n if (!binddatavalue || binddatavalue.startsWith('Widgets.') || binddatavalue.startsWith('itemRef.currentItemWidgets')) {\n return;\n }\n binddatavalue = binddatavalue.replace(/\\[\\$i\\]/g, '[0]');\n // In case of list widget context will be the listItem.\n if (_.has(this.context, binddatavalue.split('.')[0])) {\n _.set(this.context, binddatavalue, value);\n }\n else {\n _.set(this.viewParent, binddatavalue, value);\n }\n }", "updateValue() {\n [...this.template.querySelectorAll('lightning-input')].forEach(\n (element) => {\n element.value = this._value;\n }\n );\n\n this._updateProxyInputAttributes('value');\n\n /**\n * @event\n * @name change\n * @description The event fired when the value changes.\n * @param {number} value\n */\n this.dispatchEvent(\n new CustomEvent('change', {\n detail: {\n value: this._value\n }\n })\n );\n this.showHelpMessageIfInvalid();\n }", "bind(context) {\n\t\tif (!globalParams.modelProperty) {\n\t\t\tthrow new Error('Data key has not been set!');\n\t\t}\n\t\treturn Reflex.set(this, globalParams.modelProperty, context);\n\t}", "onSliderValueChanged() {\n this.setBase();\n const label = `${this.name}: ${JSON.stringify(this.value)}`;\n ChromeGA.event(ChromeGA.EVENT.SLIDER_VALUE, label);\n }", "get fieldValue(){}", "run() {\n this.setDisplayValue();\n this.bindClickHandlers();\n }", "getRawValue() {\n return this.value;\n }", "set CustomProvidedInput(value) {}", "function StatefulPropertyBinding(stateful, name){\r\n\t\tthis.stateful = stateful;\r\n\t\tthis.name = name;\r\n\t}", "static from(type, value) {\n return new Typed(_gaurd, type, value);\n }", "function JSONViewer (value) {\n this.value = value;\n}", "redrawValue () {\n this._domControl.value = this.get( 'value' );\n }", "set value(val) {\n if (val !== this._value) {\n this._value = val;\n this.notify();\n }\n }", "update(value) {\n\t\tthis.input.value = value || ''\n\t\tthis.updateClasses()\n\t}", "set fieldValue(value){\n this.element.innerHTML = value;\n }", "set value(_) {\n throw \"Cannot set computed property\";\n }", "onModelChange(value) {\n this.newValue = value\n }", "function addBindingProperty(e)\n {\n if(!e.binding)\n {\n e.binding = ko.dataFor(e.target);\n }\n\n return e;\n }", "_$setValue(value, directiveParent = this, valueIndex, noCommit) {\n const strings = this.strings;\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive$1(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n }\n else {\n // Interpolation case\n const values = value;\n value = strings[0];\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex + i], directiveParent, i);\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = this._$committedValue[i];\n }\n change || (change = !isPrimitive$1(v) || v !== this._$committedValue[i]);\n if (v === nothing) {\n value = nothing;\n }\n else if (value !== nothing) {\n value += (v !== null && v !== void 0 ? v : '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n this._$committedValue[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
renderNavigationBar Pass props to the React Native Router Flux NavBar
static renderNavigationBar(props) { return <NavBarWithProps {...props}/>; }
[ "render(){\n return(\n <div className=\"bar-item\" style={navBarItemStyle}>\n {this.props.children}\n </div>\n );\n }", "function renderNav() {\n var page = 'pages/menu';\n getPage(page, false, navContainer, false);\n }", "render() {\n const { navigation } = this.props;\n return (\n <View style={styles.container}>\n <BrowseHeader navigate={() => this.navigateToCamera()} />\n <BrowseFilterPreview />\n <BrowseFilterWheel navigate={this.navigateToEditview} navigation={navigation} />\n </View>\n );\n }", "function renderIndexHTMLNav() { \n renderStickyNavBar(navbar2, navbar1);\n}", "function renderNavBar(state, element){\n const message = `\n <li class=\"nav_el\"><a href=\"mainScreen.html\" class=\"home\">Jabber Jam</a></li>\n <li class=\"nav_user\"><p class=\"username\">${state.userId}</p></li>`;\n element.html(message);\n}", "function renderNavBar()\n{\n\tvar nav = '<li class=\"nav-item\"><a id=\"homeLink\" class=\"nav-link\" href=\"#\">Home</a></li>';\n\n\tif (window.localStorage.apiKey)\n\t{\n\t\tnav += '<li class=\"nav-item\"><a id=\"dashboardLink\" class=\"nav-link\" href=\"#dashboard\">Dashboard</a></li>';\n\t\tnav += '<li class=\"nav-item\"><a id=\"recommendationsLink\" class=\"nav-link\" href=\"#recommendations\">Recommendations</a></li>';\n\t\tnav += '<li class=\"nav-item\"><a id=\"idleInstancesLink\" class=\"nav-link\" href=\"#idleInstances\">Idle instances</a></li>';\n\t\tnav += '<li class=\"nav-item\"><a id=\"allInstancesLink\" class=\"nav-link\" href=\"#allInstances\">All instances</a></li>';\t\t\n\t\tnav += '<li class=\"nav-item\"><a id=\"logoutLink\" class=\"nav-link\" onclick=\"javascript:logout();\">Log out</a></li>';\n\t}\n\telse\n\t{\n\t\tnav += '<li class=\"nav-item\"><a id=\"loginLink\" class=\"nav-link\" href=\"#login\">Log in</a></li>';\n\t}\n\n\tdocument.getElementById('navBar').innerHTML = nav;\n}", "render() {\n return (\n <div id='nav-bar'>\n <div className='nav-link'>\n <Link to='/'>\n Home\n </Link>\n </div>\n <div className='nav-link'>\n <Link to='/about'>\n About\n </Link>\n </div>\n <div className='nav-link'>\n <Link to='/login-with-linkedin'>\n Login With Linkedin\n </Link>\n </div>\n <div className='nav-link'>\n <Link to='/user-info'>\n Users\n </Link>\n </div>\n <div className='nav-link' id='right'>\n <Input value={this.state.email} onChange={this.handleChange} placeholder='Find Someone via Email'></Input>\n <a target=\"_blank\" rel=\"noopener noreferrer\" href={`https://www.linkedin.com/sales/gmail/profile/viewByEmail/${this.state.email}`}>\n <button className='ui button'>Search Email</button>\n </a>\n </div>\n </div>\n )\n }", "function App() {\n return (\n <div className=\"App\">\n <Route \n path='/'\n render={props => <NavWrapper {...props} />}\n />\n <Route \n path='/mac' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/ipad' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/iphone' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/watch' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/tv' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/music' \n render={props => <SubNav {...props} />} \n />\n <Route \n path='/support' \n render={props => <SubNav {...props} />} \n />\n </div>\n );\n}", "render() {\n return (\n <View style={localStyles.flex}>\n <StatusBar hidden={true} />\n <ViroARSceneNavigator\n style={localStyles.arView}\n apiKey=\"YOUR-API-KEY-HERE\"\n initialScene={{\n scene: () => {\n return <InitialScene viroAppProps={this.state.viroAppProps} />;\n },\n }}\n ref={this._setARNavigatorRef}\n />\n\n {/* AR Initialization animation shown to the user for moving device around to get AR Tracking working*/}\n <ARInitializationUI\n style={{\n position: 'absolute',\n top: 20,\n left: 0,\n right: 0,\n width: '100%',\n height: 140,\n flexDirection: 'column',\n justifyContent: 'space-between',\n alignItems: 'center',\n }}\n />\n\n {/* ListView at the bottom of the screen */}\n {renderIf(\n this.props.currentScreen !== UIConstants.SHOW_SHARE_SCREEN,\n <View style={localStyles.listView}>\n <FigmentListView\n items={this._getListItems()}\n onPress={this._onListPressed}\n />\n </View>,\n )}\n\n {/* 2D UI buttons on top right of the app, that appear when a 3D object is tapped in the AR Scene */}\n {this._renderContextMenu()}\n\n {/* This menu contains the buttons on bottom left corner - toggle listview contents between\n Portals, Effects and Models (objects) */}\n {this._renderButtonLeftMenu()}\n\n {/* 2D UI for sharing rendered after user finishes taking a video / screenshot */}\n {this._renderShareScreen()}\n\n {/* 2D UI rendered to enable the user changing background for Portals using stock images/videos or through their camera roll */}\n {this._renderPhotosSelector()}\n\n {/* Buttons and their behavior for recording videos and screenshots at the bottom of the screen */}\n {this._renderRecord()}\n </View>\n );\n }", "function renderNavbar() {\n const homeLink = document.createElement('li');\n homeLink.innerText = 'Home';\n homeLink.className = 'menu__link';\n homeLink.onclick = () => scrollTo();\n navbarList.appendChild(homeLink);\n sections.forEach(section => {\n if (!section.dataset || !section.dataset.nav) return;\n const item = document.createElement('li');\n item.innerText = section.dataset.nav;\n item.className = 'menu__link';\n item.onclick = () => scrollTo($(`#${section.id}`));\n navbarList.appendChild(item);\n });\n}", "componentDidUpdate() {\n let navItems = JSON.parse(JSON.stringify(this.state.navItems));\n navItems[this.state.active].active = true;\n\n renderNav(navItems);\n }", "function GalleryNavigationBar( albumIdx ) {\r\n\r\n // new navigation bar items are not build in the DOM, but in memory\r\n G.GOM.navigationBar.$newContent=jQuery('<div class=\"nGY2Navigationbar\"></div>');\r\n\r\n //-- manage breadcrumb\r\n if( G.O.displayBreadcrumb == true && !G.O.thumbnailAlbumDisplayImage) {\r\n // retrieve new folder level\r\n var newLevel = 0,\r\n lstItems=[];\r\n if( albumIdx != 0 ) {\r\n var l=G.I.length,\r\n parentID=0;\r\n \r\n lstItems.push(albumIdx);\r\n var curIdx=albumIdx;\r\n newLevel++;\r\n \r\n while( G.I[curIdx].albumID != 0 && G.I[curIdx].albumID != -1) {\r\n for(var i=1; i < l; i++ ) {\r\n if( G.I[i].GetID() == G.I[curIdx].albumID ) {\r\n curIdx=i;\r\n lstItems.push(curIdx);\r\n newLevel++;\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n \r\n // build breadcrumb\r\n if( !(G.O.breadcrumbAutoHideTopLevel && newLevel == 0) ) {\r\n BreadcrumbBuild( lstItems );\r\n }\r\n }\r\n\r\n \r\n //-- manage tag filters\r\n if( G.galleryFilterTags.Get() != false ) {\r\n var nTags=G.I[albumIdx].albumTagList.length;\r\n if( nTags > 0 ) {\r\n for(var i=0; i < nTags; i++ ) {\r\n var s=G.I[albumIdx].albumTagList[i];\r\n var ic=G.O.icons.navigationFilterUnselected;\r\n var tagClass='Unselected';\r\n if( jQuery.inArray(s, G.I[albumIdx].albumTagListSel) >= 0 ) {\r\n tagClass='Selected';\r\n ic=G.O.icons.navigationFilterSelected;\r\n }\r\n var $newTag=jQuery('<div class=\"nGY2NavigationbarItem nGY2NavFilter'+tagClass+'\">'+ic+' '+s+'</div>').appendTo(G.GOM.navigationBar.$newContent);\r\n $newTag.click(function() {\r\n var $this=jQuery(this);\r\n var tag=$this.text().replace(/^\\s*|\\s*$/, ''); //trim trailing/leading whitespace\r\n // if( $this.hasClass('oneTagUnselected') ){\r\n if( $this.hasClass('nGY2NavFilterUnselected') ){\r\n G.I[albumIdx].albumTagListSel.push(tag);\r\n }\r\n else {\r\n var tidx=jQuery.inArray(tag,G.I[albumIdx].albumTagListSel);\r\n if( tidx != -1 ) {\r\n G.I[albumIdx].albumTagListSel.splice(tidx,1);\r\n }\r\n }\r\n $this.toggleClass('nGY2NavFilters-oneTagUnselected nGY2NavFilters-oneTagSelected');\r\n DisplayAlbum('-1', G.I[albumIdx].GetID());\r\n });\r\n }\r\n var $newClearFilter=jQuery('<div class=\"nGY2NavigationbarItem nGY2NavFilterSelectAll\">'+G.O.icons.navigationFilterSelectedAll+'</div>').appendTo(G.GOM.navigationBar.$newContent);\r\n $newClearFilter.click(function() {\r\n var nTags=G.I[albumIdx].albumTagList.length;\r\n G.I[albumIdx].albumTagListSel=[];\r\n for(var i=0; i <nTags; i++ ) {\r\n var s=G.I[albumIdx].albumTagList[i];\r\n G.I[albumIdx].albumTagListSel.push(s);\r\n }\r\n DisplayAlbum('-1', G.I[albumIdx].GetID());\r\n });\r\n }\r\n }\r\n\r\n }", "function Stacks( {route, navigation} ) {\n let site = route.params.site\n // console.log(route.params)\n // console.log(site)\n return (\n // Creates the header of each webview screen\n <Stack.Navigator screenOptions={{\n headerStyle:{backgroundColor:'maroon'}\n }}>\n <Stack.Screen\n name= {route.params.name}\n // The name of the screen within the list\n component={Web}\n initialParams={{site: site}}\n // Throws the website for each screen to the screen renderer\n options={{\n headerLeft: () => <Header navigation={navigation} />\n }}\n />\n </Stack.Navigator>\n );\n}", "function navigationParser (navArray, level=0) {\n if (navArray.length === 0) {\n return <Nav.Item className=\"px-3\">no sites found</Nav.Item>\n }\n return navArray.map(el => {\n if (el.navigation) {\n return (\n <NavDropdown id={el.label} title={el.label} key={el.label}>\n {navigationParser(el.navigation, 1)}\n </NavDropdown>\n );\n } else {\n if (level > 0) {\n return <NavDropdown.Item key={el.label} eventKey={el.link}>{el.label}</NavDropdown.Item>\n } else {\n return (\n <Nav.Item key={el.label}>\n <Nav.Link eventKey={el.link}>{el.label}</Nav.Link>\n </Nav.Item>\n )\n }\n }\n })\n}", "get topNavigationBar() {\n return NavigationNodes(this, \"topnavigationbar\");\n }", "function createEventNavBar() {\n $(\"#nav-bar\").html(\"\");\n for (let i = 0; i < events.length; i++) {\n let navBar = $('<button class = \"event-nav-bar nav-btn\"> </button>');\n // navBar.attr(\"href\", \"#\" + events[i]);\n navBar.attr(\"id\", \"ev-\" + parseInt(i));\n navBar.text(events[i]);\n $(\"#nav-bar\").append(navBar);\n navBar.css({ display: \"flex\" }, { \"flex-direction\": \"column\" });\n }\n}", "render() {\n const {game, message, score, authors, topScore} = this.state;\n return (\n <React.Fragment>\n <NavBar \n className=\"row\"\n game={game}\n message={message}\n score={score}\n topScore={topScore}\n />\n\n <Title />\n\n <div>\n <Wrapper>\n {authors.map(({id, image, clicked}) => (\n <AuthorCard\n id={id}\n key={id}\n image={image}\n clicked={clicked}\n clickHandler={this.handleClick}\n />\n ))}\n </Wrapper>\n </div>\n </React.Fragment>\n );\n }", "function AppNavigator() {\n\treturn (\n\t\t// Wrap NavigationContainer because its the route of the app\n\t\t<NavigationContainer>\n\t\t\t{/* Set up Tab.Navigator */}\n\t\t\t<Tab.Navigator\n\t\t\t\t// in screenOptions we give an object with function\n\t\t\t\t// this function has access to props from react-naviation {route}\n\t\t\t\tscreenOptions={({ route }) => ({\n\t\t\t\t\t// logic to check if route is home then show Home icon from MaterialIcon etc ..\n\t\t\t\t\ttabBarIcon: () => {\n\t\t\t\t\t\tlet iconName;\n\t\t\t\t\t\tif (route.name == 'Home') {\n\t\t\t\t\t\t\ticonName = 'home';\n\t\t\t\t\t\t} else if (route.name == 'About') {\n\t\t\t\t\t\t\ticonName = 'info';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// return MaterialIcon\n\t\t\t\t\t\treturn <MaterialIcons name={iconName} size={24} />;\n\t\t\t\t\t},\n\t\t\t\t})}\n\t\t\t>\n\t\t\t\t{/* Setting up screens in Tab.Navigator*/}\n\t\t\t\t<Tab.Screen name=\"Home\" component={stackNavigator} />\n\t\t\t\t<Tab.Screen name=\"About\" component={AboutStackNavigator} />\n\t\t\t</Tab.Navigator>\n\t\t</NavigationContainer>\n\t);\n}", "constructor(props) {\n super(props);\n this.state = {};\n const tree = NavSideBar.mkOrderedNavItemTree(this.props.links, {});\n this.items = [];\n NavSideBar.mkNavItems(tree.items, this.items);\n }", "render(){\n\n if(this.state.isLoggedIn){\n return(\n <Router>\n <div>\n <Navigation isLoggedIn={this.state.isLoggedIn} isAuthenicated={this.isAuthenicated.bind(this)}/>\n <Switch>\n <Route exact path=\"/\" component={Home} />\n\n <Route exact path=\"/home\" component={Home} />\n\n <Route exact path=\"/about\" component={About} />\n\n <Route exact path=\"/account\" component={Account} isLoggedIn={this.state.isLoggedIn} />\n\n <Route exact path=\"/search\" component={Search} />\n\n <Route component={NoMatch} />\n\n </Switch>\n </div>\n </Router>\n )\n }\n else {\n return(\n <Router>\n <div>\n <Navigation isLoggedIn={this.state.isLoggedIn} isAuthenicated={this.isAuthenicated.bind(this)}/>\n <Switch>\n <Route exact path=\"/\" component={Home} />\n\n <Route exact path=\"/home\" component={Home} />\n\n <Route exact path=\"/about\" component={About} />\n\n <Route exact path=\"/search\" component={Search} />\n\n <Route exact path=\"/account\" component={Home} />\n\n <Route component={NoMatch} />\n\n </Switch>\n </div>\n </Router>\n )\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a `:try` type to a `:maybe` value.
function maybe(t) /* forall<a> (t : try<a>) -> maybe<exception> */ { return (t._tag === 1) ? Just(t.exception) : Nothing; }
[ "function maybe_3(m, nothing) /* forall<a> (m : maybe<a>, nothing : a) -> a */ {\n return $default(m, nothing);\n}", "function maybe_6(b) /* (b : bool) -> maybe<()> */ {\n return (b) ? Just(_unit_) : Nothing;\n}", "function Maybe(value){ \n this.value = value;\n }", "function maybe_7(i) /* (i : int) -> maybe<int> */ {\n return ($std_core._int_eq(i,0)) ? Nothing : Just(i);\n}", "function string_4(ms) /* (ms : maybe<string>) -> string */ {\n return (ms == null) ? \"\" : ms.value;\n}", "function mapOrElseAsyncForResult(input, recoverer, transformer) {\n if (Result_1.isOk(input)) {\n var inner = unwrap_1.unwrapFromResult(input);\n var result = transformer(inner);\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(result, ErrorMessage_1.ERR_MSG_TRANSFORMER_MUST_RETURN_PROMISE);\n return result;\n }\n var err = unwrap_1.unwrapErrFromResult(input);\n var fallback = recoverer(err);\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(fallback, ErrorMessage_1.ERR_MSG_RECOVERER_MUST_RETURN_PROMISE);\n return fallback;\n}", "function null_1(i) /* (i : int) -> null<int> */ {\n return $null(maybe_7(i));\n}", "function untry(ex) /* forall<a> (ex : try<a>) -> exn a */ {\n return (ex._tag === 1) ? $throw(ex.exception) : ex.result;\n}", "function tryCatch(fn,obj,arg){try{return{type:\"normal\",arg:fn.call(obj,arg)};}catch(err){return{type:\"throw\",arg:err};}}", "function maybe(item, action) {\n if(!item) {\n return;\n }\n return action(item);\n}", "function guessTypeOfValue(tval) {\n if (tval['ctype'] === 'boolean') {\n return type.bool;\n } else if (tval['ctype'] === 'number') {\n let z = tval['value'];\n if (Math.abs(z['imag']) < 1e-5) { //eps test. for some reasons sin(1) might have some imag part of order e-17\n if ((z['real'] | 0) === z['real']) {\n return type.int;\n } else {\n return type.float;\n }\n } else {\n return type.complex;\n }\n } else if (tval['ctype'] === 'list') {\n let l = tval['value'];\n if (l.length === 3) {\n if (tval[\"usage\"] === \"Point\")\n return type.point;\n else if (tval[\"usage\"] === \"Line\")\n return type.line\n }\n if (l.length > 0) {\n let ctype = guessTypeOfValue(l[0]);\n for (let i = 1; i < l.length; i++) {\n ctype = lca(ctype, guessTypeOfValue(l[i]));\n }\n if (ctype) return {\n type: 'list',\n length: l.length,\n parameters: ctype\n };\n }\n } else if (tval['ctype'] === 'string' || tval['ctype'] === 'image') {\n return type.image;\n } else if (tval['ctype'] === 'geo' && tval['value']['kind'] === 'L') {\n return type.line;\n }\n console.error(`Cannot guess type of the following type:`);\n console.log(tval);\n return false;\n}", "function maybe_5(xs) /* forall<a> (xs : list<a>) -> maybe<a> */ {\n return (xs == null) ? Nothing : Just(xs.head);\n}", "function extract(item, field) {\n if (item[field]) {\n return item[field];\n } else if (typeof item == \"string\" || typeof item == \"number\") {\n return item;\n }\n // intentionally don't return anything\n }", "function chewValue(optionalName, valueThing, ctx) {\n var kind = null;\n\n switch (typeof(valueThing)) {\n case \"string\":\n kind = \"String\";\n break;\n case \"boolean\":\n kind = \"Boolean\";\n break;\n case \"number\":\n kind = \"Number\";\n break;\n case \"object\":\n if (valueThing instanceof Identifier) {\n switch (valueThing.identifier) {\n case \"true\":\n kind = \"Boolean\";\n valueThing = true;\n break;\n case \"false\":\n kind = \"Boolean\";\n valueThing = false;\n break;\n // otherwise it probably is a type reference/global that needs\n // resolution.\n }\n }\n }\n if (kind) {\n return new $typerep.NamedValue(optionalName, valueThing, kind,\n new $typerep.LifeStory());\n }\n // just use chewType for everything else.\n return chewType(optionalName, valueThing, ctx);\n}", "visitTryStatement(node){\r\n var key = this.addToCFG(node);\r\n this.node_stack[this.current_class][this.current_function].push(key);\r\n this.visit(node.block);\r\n this.catch_clauses[this.current_class][this.current_function][key] = this.nodeStr(node.handler);\r\n this.visit(node.handler); // new functions for catch clauses\r\n this.visit(node.finalizer)\r\n }", "function firstOk(results) {\r\n return results.find(isOk) || error(null);\r\n}", "cast(value, cast) {\n return cast ? cast(value) : value;\n }", "function tryToParse(txt) {\r\n\r\n // The listing of all possible formats that can reasonably be parsed, listed\r\n // in order from shortest to longest string.\r\n var formatArray = [ \"H\",\r\n \"HH\",\r\n \"HHm\",\r\n \"HHmm\",\r\n \"H:\",\r\n \"HH:\",\r\n \"H:m\",\r\n \"HH:m\",\r\n \"H:mm\",\r\n \"HH:mm\",\r\n \"H:mt\",\r\n \"HH:mt\",\r\n \"H:mmt\",\r\n \"HH:mmt\",\r\n \"H:mtt\",\r\n \"HH:mtt\",\r\n \"H:mmtt\",\r\n \"HH:mmtt\" ];\r\n\r\n // An index to be used for iterating through the format array\r\n var formatIdx = null;\r\n\r\n // Get rid of any spaces\r\n var hourText = txt.replace(/\\s/g, \"\");\r\n\r\n // Iterate through every format, and attempt to parse using that format.\r\n for (formatIdx in formatArray) {\r\n var cTime = Date.parseExact(hourText, formatArray[formatIdx]);\r\n if (cTime) {\r\n return cTime;\r\n }\r\n }\r\n\r\n // If not a single format matches, then return null\r\n return null;\r\n}", "exitNullableType(ctx) {\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inverse Operation Handlers Computes and displays the transpose of a matrix.
handleTranspose() { const matrix = this.getMatrices(this.getSelectValue("transpose")); if (matrix !== null) { const transpose = matrix.transpose(); this.displayResults("Transpose", matrix, "=", transpose); } }
[ "handleInverse() {\n const matrix = this.getMatrices(this.getSelectValue(\"inverse\"));\n if (matrix !== null) {\n const inverse = matrix.inverse().last();\n if (inverse.equals(matrix)) {\n this.displayResults(\"Inverse\", matrix, \"=\", \"This matrix is not invertible.\");\n } else {\n this.displayResults(\"Inverse\", matrix, \"=\", inverse);\n }\n }\n }", "invert(){\n let out = new matrix4();\n for(var column = 0; column < 4; column++){\n for(var row = 0; row < 4; row++){\n out.matArray[column][row] = -this.matArray[column][row];\n }\n }\n return out;\n }", "invertRows() {\n // flip \"up\" vector\n // we flip up first because invertColumns update projectio matrices\n this.up.multiplyScalar(-1);\n this.invertColumns();\n\n this._updateDirections();\n }", "function Inversa(panelId,matrix)\n{\n matrix= savematriz(panelId,matrix);\n var sizes= math.size(matrix)._data;\n if(sizes[0]!=sizes[1])\n {\n alert(\"A matriz deve ser quadrada para calcular a sua Inversa\");\n return;\n }\n matrix= math.inv(matrix);\n escreveMatriz(math.size(matrix)._data,panelId,matrix,false);\n}", "function inv()\n {\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let akk = undefined ;\n let akj = undefined ;\n let aik = undefined ;\n\n let r = new Matrix( this.nr , this.nc ) ;\n\n console.log( 'r=' , r ) ;\n\n for( i = 0; i < this.nr; ++i )\n\n for( j = 0; j < this.nc; ++j )\n \n if( this.idx( i , j ) < this.nv )\n \n r.v[ r.idx( i , j ) ] = this.v[ this.idx( i , j ) ] ;\n\n for( k = 0; k < r.nr; ++k )\n\n if( akk = r.v[ r.idx( k , k ) ] )\n {\n\n for( i = 0; i < r.nc; ++i )\n\n for( j = 0; j < r.nr; ++j )\n\n if( (i != k) && (j != k) )\n {\n\n akj = r.v[ r.idx( k , j ) ] ;\n\n aik = r.v[ r.idx( i , k ) ] ;\n\n r.v[ r.idx( i , j ) ] -= ( (akj * aik) / akk ) ;\n\n } ;\n\n for( i = 0; i < r.nc; ++i )\n\n if( i != k )\n\n r.v[ r.idx( i , k ) ] /= (- akk ) ;\n\n for( j = 0; j < r.nr; ++j )\n\n if( k != j )\n\n r.v[ r.idx( k , j ) ] /= akk ;\n\n r.v[ r.idx( k , k ) ] = ( 1.0 / akk ) ;\n\n } // end if{} +\n\n else\n\n r.v[ r.idx( k , k ) ] = undefined ;\n\n for( i = 0; i < this.nr; ++i )\n\n for( j = 0; j < this.nc; ++j )\n \n if( this.idx( i , j ) < this.nv )\n \n this.v[ this.idx( i , j ) ] = r.v[ r.idx( i , j ) ];\n\n return ;\n\n }", "function myTranspose (mtx) {\n\nlet grid = [];\n for (let i = 0; i < mtx[0].length; i++) {\n grid[i] = [];\n for (let j = 0; j < mtx.length; j++) {\n grid[i][j] = mtx[j][i];\n }\n }\n return grid;\n}", "function transpose(board){\n var newBoard = board[0].map(function(col, i) {\n return board.map(function(row) {\n return row[i];\n });\n });\n return newBoard;\n }", "invert() {\n for (let i = 0; i < this._data.length; i++) {\n this._data[i] = ~this._data[i];\n }\n }", "function updateTransformationMatrixDisplay () {\n // Divide by 1 to remove trailing zeroes\n $('#matrixElemA').val(matrix.a.toFixed(decimalPlaces) / 1)\n $('#matrixElemB').val(matrix.b.toFixed(decimalPlaces) / 1)\n $('#matrixElemC').val(matrix.c.toFixed(decimalPlaces) / 1)\n $('#matrixElemD').val(matrix.d.toFixed(decimalPlaces) / 1)\n }", "toggleProjectionMatrixHandInPlace() {\n const m = this._m;\n m[8] *= -1;\n m[9] *= -1;\n m[10] *= -1;\n m[11] *= -1;\n this._markAsUpdated();\n }", "renderMatrix () {\n return this.generateMatrix().map((y, i) => {\n return (<tr key={i + 'y'}>{\n y.map((x, i) => {\n return (<td key={i + 'x'}>{x}</td>);\n })\n }</tr>);\n });\n }", "function matrix_mult(x, A_inv, b) {\n x[0] = A_inv[0][0] * b[0] + A_inv[0][1] * b[1];\n x[1] = A_inv[1][0] * b[0] + A_inv[1][1] * b[1];\n}", "invert() {\n quat.invert(this, this);\n return this.check();\n }", "function backsub(\n u, // u[1..m][1..n], the column-orth. matrix from decomp\n w, // w[1..n], the diagonal matrix from decomp\n v, // v[1..n][1..n], the orth. matrix from decomp\n m, // number of rows\n n, // number of columns\n b // b[1..m] is the right hand side (B)\n)\n{\n var s;\n var tmp = new Array();\n var x = new Array();\n \n // Calculate UT * B\n for (var j=1; j<=n; j++)\n {\n s = 0.0;\n \n // Nonzero result only if w[j] is nonzero\n if (w[j] != 0.0)\n {\n for (var i=1; i<=m; i++)\n s += u[i][j]*b[i];\n s /= w[j];\n }\n tmp[j] = s;\n }\n \n // Matrix multiply by V to get answer.\n for (var j=1; j<=n; j++)\n {\n s = 0.0;\n for (var jj=1; jj<=n; jj++)\n s += v[j][jj]*tmp[jj];\n x[j] = s;\n }\n \n return x;\n}", "function invertNum(num)\n{\n\treturn num *= -1;\n}", "function uploadNormalMatrixToShader(){\n mat3.fromMat4(nMatrix,mvMatrix);\n mat3.transpose(nMatrix,nMatrix);\n mat3.invert(nMatrix,nMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function determinant (matrix) {\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];\n}", "handleSubtraction() {\n const left = this.getSelectValue(\"subtract\", 1);\n const right = this.getSelectValue(\"subtract\", 2);\n const matrices = this.getMatrices(left, right);\n\n if (matrices !== null) {\n try {\n const difference = matrices[0].matrixAddition(matrices[1], false);\n this.displayResults(matrices[0], \"-\", matrices[1], \"=\", difference);\n } catch (error) {\n alert(\"Rows and columns of the matrices must match.\");\n }\n }\n }", "function inv ( subject ) {\n return subject * -1;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the AWS CloudFormation properties of an `AWS::AppMesh::VirtualNode.BackendDefaults` resource
function cfnVirtualNodeBackendDefaultsPropertyToCloudFormation(properties) { if (!cdk.canInspect(properties)) { return properties; } CfnVirtualNode_BackendDefaultsPropertyValidator(properties).assertSuccess(); return { ClientPolicy: cfnVirtualNodeClientPolicyPropertyToCloudFormation(properties.clientPolicy), }; }
[ "function cfnVirtualGatewayVirtualGatewayBackendDefaultsPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayBackendDefaultsPropertyValidator(properties).assertSuccess();\n return {\n ClientPolicy: cfnVirtualGatewayVirtualGatewayClientPolicyPropertyToCloudFormation(properties.clientPolicy),\n };\n}", "function cfnVirtualNodeBackendPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_BackendPropertyValidator(properties).assertSuccess();\n return {\n VirtualService: cfnVirtualNodeVirtualServiceBackendPropertyToCloudFormation(properties.virtualService),\n };\n}", "function cfnVirtualNodeVirtualServiceBackendPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualServiceBackendPropertyValidator(properties).assertSuccess();\n return {\n ClientPolicy: cfnVirtualNodeClientPolicyPropertyToCloudFormation(properties.clientPolicy),\n VirtualServiceName: cdk.stringToCloudFormation(properties.virtualServiceName),\n };\n}", "function CfnVirtualNode_BackendDefaultsPropertyValidator(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('clientPolicy', CfnVirtualNode_ClientPolicyPropertyValidator)(properties.clientPolicy));\n return errors.wrap('supplied properties not correct for \"BackendDefaultsProperty\"');\n}", "function cfnVirtualGatewayVirtualGatewaySpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewaySpecPropertyValidator(properties).assertSuccess();\n return {\n BackendDefaults: cfnVirtualGatewayVirtualGatewayBackendDefaultsPropertyToCloudFormation(properties.backendDefaults),\n Listeners: cdk.listMapper(cfnVirtualGatewayVirtualGatewayListenerPropertyToCloudFormation)(properties.listeners),\n Logging: cfnVirtualGatewayVirtualGatewayLoggingPropertyToCloudFormation(properties.logging),\n };\n}", "function CfnVirtualGateway_VirtualGatewayBackendDefaultsPropertyValidator(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('clientPolicy', CfnVirtualGateway_VirtualGatewayClientPolicyPropertyValidator)(properties.clientPolicy));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayBackendDefaultsProperty\"');\n}", "function cfnVirtualNodeVirtualNodeSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeSpecPropertyValidator(properties).assertSuccess();\n return {\n BackendDefaults: cfnVirtualNodeBackendDefaultsPropertyToCloudFormation(properties.backendDefaults),\n Backends: cdk.listMapper(cfnVirtualNodeBackendPropertyToCloudFormation)(properties.backends),\n Listeners: cdk.listMapper(cfnVirtualNodeListenerPropertyToCloudFormation)(properties.listeners),\n Logging: cfnVirtualNodeLoggingPropertyToCloudFormation(properties.logging),\n ServiceDiscovery: cfnVirtualNodeServiceDiscoveryPropertyToCloudFormation(properties.serviceDiscovery),\n };\n}", "function cfnVirtualServiceVirtualNodeServiceProviderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualNodeServiceProviderPropertyValidator(properties).assertSuccess();\n return {\n VirtualNodeName: cdk.stringToCloudFormation(properties.virtualNodeName),\n };\n}", "function cfnVirtualNodeAwsCloudMapInstanceAttributePropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_AwsCloudMapInstanceAttributePropertyValidator(properties).assertSuccess();\n return {\n Key: cdk.stringToCloudFormation(properties.key),\n Value: cdk.stringToCloudFormation(properties.value),\n };\n}", "function cfnVirtualGatewayVirtualGatewayConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualGatewayVirtualGatewayGrpcConnectionPoolPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualGatewayVirtualGatewayHttpConnectionPoolPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualGatewayVirtualGatewayHttp2ConnectionPoolPropertyToCloudFormation(properties.http2),\n };\n}", "function cfnVirtualGatewayVirtualGatewayGrpcConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayGrpcConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}", "function cfnVirtualServiceVirtualRouterServiceProviderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualRouterServiceProviderPropertyValidator(properties).assertSuccess();\n return {\n VirtualRouterName: cdk.stringToCloudFormation(properties.virtualRouterName),\n };\n}", "function cfnVirtualNodeVirtualNodeGrpcConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeGrpcConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n MaxRequests: cdk.numberToCloudFormation(properties.maxRequests),\n };\n}", "function cfnVirtualGatewayLoggingFormatPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_LoggingFormatPropertyValidator(properties).assertSuccess();\n return {\n Json: cdk.listMapper(cfnVirtualGatewayJsonFormatRefPropertyToCloudFormation)(properties.json),\n Text: cdk.stringToCloudFormation(properties.text),\n };\n}", "function cfnVirtualNodePropsToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNodePropsValidator(properties).assertSuccess();\n return {\n MeshName: cdk.stringToCloudFormation(properties.meshName),\n Spec: cfnVirtualNodeVirtualNodeSpecPropertyToCloudFormation(properties.spec),\n MeshOwner: cdk.stringToCloudFormation(properties.meshOwner),\n Tags: cdk.listMapper(cdk.cfnTagToCloudFormation)(properties.tags),\n VirtualNodeName: cdk.stringToCloudFormation(properties.virtualNodeName),\n };\n}", "function cfnVirtualNodeVirtualNodeConnectionPoolPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_VirtualNodeConnectionPoolPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualNodeVirtualNodeGrpcConnectionPoolPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualNodeVirtualNodeHttpConnectionPoolPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualNodeVirtualNodeHttp2ConnectionPoolPropertyToCloudFormation(properties.http2),\n TCP: cfnVirtualNodeVirtualNodeTcpConnectionPoolPropertyToCloudFormation(properties.tcp),\n };\n}", "function cfnVirtualServiceVirtualServiceProviderPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualServiceProviderPropertyValidator(properties).assertSuccess();\n return {\n VirtualNode: cfnVirtualServiceVirtualNodeServiceProviderPropertyToCloudFormation(properties.virtualNode),\n VirtualRouter: cfnVirtualServiceVirtualRouterServiceProviderPropertyToCloudFormation(properties.virtualRouter),\n };\n}", "function renderValues() {\n renderInitialValues(initialPhysicValues);\n renderInitialValues(resultPhysicValues);\n}", "function cfnVirtualServiceVirtualServiceSpecPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualService_VirtualServiceSpecPropertyValidator(properties).assertSuccess();\n return {\n Provider: cfnVirtualServiceVirtualServiceProviderPropertyToCloudFormation(properties.provider),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ToLL function to compute Latitude and Longitude given UTM Northing and Easting in meters Description: This member function converts input north and east coordinates to the corresponding Northing and Easting values relative to the defined UTM zone. Refer to the reference in this file's header. Parameters: north (i) Northing (meters) east (i) Easting (meters) utmZone (i) UTM Zone of the North and East parameters lat (o) Latitude in degrees lon (o) Longitude in degrees
function ToLL(north,east,utmZone) { // This is the lambda knot value in the reference var LngOrigin = DegToRad(utmZone * 6 - 183) // The following set of class constants define characteristics of the // ellipsoid, as defined my the WGS84 datum. These values need to be // changed if a different dataum is used. var FalseNorth = 0. // South or North? //if (lat < 0.) FalseNorth = 10000000. // South or North? //else FalseNorth = 0. var Ecc = 0.081819190842622 // Eccentricity var EccSq = Ecc * Ecc var Ecc2Sq = EccSq / (1. - EccSq) var Ecc2 = Math.sqrt(Ecc2Sq) // Secondary eccentricity var E1 = ( 1 - Math.sqrt(1-EccSq) ) / ( 1 + Math.sqrt(1-EccSq) ) var E12 = E1 * E1 var E13 = E12 * E1 var E14 = E13 * E1 var SemiMajor = 6378137.0 // Ellipsoidal semi-major axis (Meters) var FalseEast = 500000.0 // UTM East bias (Meters) var ScaleFactor = 0.9996 // Scale at natural origin // Calculate the Cassini projection parameters var M1 = (north - FalseNorth) / ScaleFactor var Mu1 = M1 / ( SemiMajor * (1 - EccSq/4.0 - 3.0*EccSq*EccSq/64.0 - 5.0*EccSq*EccSq*EccSq/256.0) ) var Phi1 = Mu1 + (3.0*E1/2.0 - 27.0*E13/32.0) * Math.sin(2.0*Mu1) + (21.0*E12/16.0 - 55.0*E14/32.0) * Math.sin(4.0*Mu1) + (151.0*E13/96.0) * Math.sin(6.0*Mu1) + (1097.0*E14/512.0) * Math.sin(8.0*Mu1) var sin2phi1 = Math.sin(Phi1) * Math.sin(Phi1) var Rho1 = (SemiMajor * (1.0-EccSq) ) / Math.pow(1.0-EccSq*sin2phi1,1.5) var Nu1 = SemiMajor / Math.sqrt(1.0-EccSq*sin2phi1) // Compute parameters as defined in the POSC specification. T, C and D var T1 = Math.tan(Phi1) * Math.tan(Phi1) var T12 = T1 * T1 var C1 = Ecc2Sq * Math.cos(Phi1) * Math.cos(Phi1) var C12 = C1 * C1 var D = (east - FalseEast) / (ScaleFactor * Nu1) var D2 = D * D var D3 = D2 * D var D4 = D3 * D var D5 = D4 * D var D6 = D5 * D // Compute the Latitude and Longitude and convert to degrees var lat = Phi1 - Nu1*Math.tan(Phi1)/Rho1 * ( D2/2.0 - (5.0 + 3.0*T1 + 10.0*C1 - 4.0*C12 - 9.0*Ecc2Sq)*D4/24.0 + (61.0 + 90.0*T1 + 298.0*C1 + 45.0*T12 - 252.0*Ecc2Sq - 3.0*C12)*D6/720.0 ) lat = RadToDeg(lat) var lon = LngOrigin + ( D - (1.0 + 2.0*T1 + C1)*D3/6.0 + (5.0 - 2.0*C1 + 28.0*T1 - 3.0*C12 + 8.0*Ecc2Sq + 24.0*T12)*D5/120.0) / Math.cos(Phi1) lon = RadToDeg(lon) // Create a object to store the calculated Latitude and Longitude values var sendLatLon = new PC_LatLon(lat,lon) // Returns a PC_LatLon object return sendLatLon }
[ "function getLongitude(input) {\n // we know input is validated so we know we can go from North/South to the end\n var search = input.search(/[NS]/);\n\n var longitude = \"\";\n if (search == -1) {\n longitude = input.substr(input.search(' '));\n } else {\n longitude = input.substring(search + 1);\n }\n\n return longitude;\n}", "function calcSolNoonUTC(t, longitude) {\n // First pass uses approximate solar noon to calculate eqtime\n var tnoon = calcTimeJulianCent(calcJDFromJulianCent(t) + longitude/360.0);\n var eqTime = calcEquationOfTime(tnoon);\n var solNoonUTC = 720 + (longitude * 4) - eqTime; // min\n var newt = calcTimeJulianCent(calcJDFromJulianCent(t) -0.5 + solNoonUTC/1440.0); \n eqTime = calcEquationOfTime(newt);\n // var solarNoonDec = calcSunDeclination(newt);\n solNoonUTC = 720 + (longitude * 4) - eqTime; // min\n return solNoonUTC;\n}", "toUTM() {\n return new UTMPoint().fromLatLng(this);\n }", "function getMiddle() {\n\n // setup vars\n var lat1 = loc1.lat;\n var lon1 = loc1.long;\n var lat2 = loc2.lat;\n var lon2 = loc2.long;\n\n // helper functions\n function toRadians(degrees) {\n return degrees * (Math.PI / 180);\n }\n\n function toDegrees(radians) {\n return radians * (180 / Math.PI);\n }\n\n var dLon = toRadians(lon2 - lon1);\n\n // convert to radians\n lat1 = toRadians(lat1);\n lat2 = toRadians(lat2);\n lon1 = toRadians(lon1);\n\n // some calculations\n var Bx = Math.cos(lat2) * Math.cos(dLon);\n var By = Math.cos(lat2) * Math.sin(dLon);\n var lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By));\n var lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx);\n\n // convert back to degrees\n lat3 = toDegrees(lat3);\n lon3 = toDegrees(lon3);\n\n return { lat: lat3, long: lon3 };\n }", "_convertToLocalSpace()\n {\n if (!this._tempLandmarks)\n return null\n\n // clear the Array (and hopefully not to create a new one)\n this._landmarks.splice(0, this._landmarks.length)\n //this._landmarks = []\n\n this._tempLandmarks.forEach((pose, i) => {\n let v = new THREE.Vector3(pose.x, pose.y, pose.z)\n\n // convert to the sceen space\n /*\n v.x = v.x * 2 - 1\n v.y = -v.y * 2 + 1\n v.z = 0\n */\n\n /*\n // making the Head as a center of axes model\n v.x = v.x - this._tempLandmarks[0].x\n v.y = -(v.y - this._tempLandmarks[0].y)\n v.z = -(v.z - this._tempLandmarks[0].z)\n */\n\n // make a repere and convert all points/poses to it\n v.sub(this._reperePosition)\n v.y = -v.y\n v.z = -v.z // invert z to get the mirrar effect\n\n this._landmarks.push(v)\n })\n }", "toDefaultProjection(lat, long) {\n return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');\n }", "function ComputeLonFromTrueCourseAndDistance(Lon2output, Lat1input, Lon1input, TCinput, DistInput) {\n Equation.call(this, Lon2output, Lat1input, Lon1input, TCinput, DistInput);\n}", "function ComputeLatFromTrueCourseAndDistance(Lat2output, Lat1input, Lon1input, TCinput, DistInput) {\n Equation.call(this, Lat2output, Lat1input, Lon1input, TCinput, DistInput);\n}", "function North() {\n props.setMoveLocation(true);\n props.setLocation((latMove += 0.002), longMove);\n }", "function convertCityLatLong(inputCity){\n let directGeocodingAPI = 'https://api.openweathermap.org/geo/1.0/direct?q=' + inputCity + '&limit=5&appid=fe69a8ae1bfba9fa932a4b4358617cbf'\n fetch(directGeocodingAPI)\n .then(function(response){\n return response.json();\n })\n .then(function(data){\n var lat = data[0].lat\n var long = data[0].lon\n fiveDayForecastAPI(lat,long)\n })\n \n \n}", "function CHtoWGSlat(y, x) {\n\n // Converts military to civil and to unit = 1000km\n // Auxiliary values (% Bern)\n var y_aux = (y - 600000)/1000000;\n var x_aux = (x - 200000)/1000000;\n \n // Process lat\n lat = 16.9023892\n + 3.238272 * x_aux\n - 0.270978 * Math.pow(y_aux,2)\n - 0.002528 * Math.pow(x_aux,2)\n - 0.0447 * Math.pow(y_aux,2) * x_aux\n - 0.0140 * Math.pow(x_aux,3);\n \n // Unit 10000\" to 1 \" and converts seconds to degrees (dec)\n lat = lat * 100/36;\n \n return lat;\n \n}", "function printLongitudeHint () {\n console.log(' \"long\" is the longitude west(west is negative, east is positive) in degrees')\n console.log(' longitudes are between -180 and 180 degrees')\n console.log(' A typical \"long\" looks like: \"long\": -90.596')\n}", "function moveEast() {\n currentLonPoint += 0.00050\n console.log(currentLonPoint)\n map.setView([currentLatPoint, currentLonPoint], 18)\n\n }", "function getnearestweather(latinput, longinput)\n{\n // var forecastobj = {\n // BR: \"Mist\",\n // CL: \"Cloudy\",\n // CR: \"Drizzle\",\n // FA: \"Fair(Day)\",\n // FG: \"Fog\",\n // FN: \"Fair(Night)\",\n // FW: \"Fair & Warm\",\n // HG: \"Heavy Thundery Showers with Gusty Winds\",\n // HR: \"Heavy Rain\",\n // HS: \"Heavy Showers\",\n // HT: \"Heavy Thundery Showers\",\n // HZ: \"Hazy\",\n // LH: \"Slightly Hazy\",\n // LR: \"Light Rain\",\n // LS: \"Light Showers\",\n // OC: \"Overcast\",\n // PC: \"Partly Cloudy (Day)\",\n // PN: \"Partly Cloudy (Night)\",\n // PS: \"Passing Showers\",\n // RA: \"Moderate Rain\",\n // SH: \"Showers\",\n // SK: \"Strong Winds,Showers\",\n // SN: \"Snow\",\n // SR: \"Strong Winds, Rain\",\n // SS: \"Snow Showers\",\n // SU: \"Sunny\",\n // SW: \"Strong Winds\",\n // TL: \"Thundery Showers\",\n // WC: \"Windy,Cloudy\",\n // WD: \"Windy\",\n // WF: \"Windy,Fair\",\n // WR: \"Windy,Rain\",\n // WS: \"Windy, Showers\"\n // };\n\n var forecastobj = {\n BR: \"Not Raining\",\n CL: \"Not Raining\",\n CR: \"Raining\",\n FA: \"Not Raining\",\n FG: \"Not Raining\",\n FN: \"Not Raining\",\n FW: \"Not Raining\",\n HG: \"Raining\",\n HR: \"Raining\",\n HS: \"Raining\",\n HT: \"Raining\",\n HZ: \"Not Raining\",\n LH: \"Not Raining\",\n LR: \"Raining\",\n LS: \"Raining\",\n OC: \"Not Raining\",\n PC: \"Not Raining\",\n PN: \"Not Raining\",\n PS: \"Raining\",\n RA: \"Raining\",\n SH: \"Raining\",\n SK: \"Raining\",\n SN: \"Not Raining\",\n SR: \"Raining\",\n SS: \"Not Raining\",\n SU: \"Not Raining\",\n SW: \"Not Raining\",\n TL: \"Raining\",\n WC: \"Not Raining\",\n WD: \"Not Raining\",\n WF: \"Not Raining\",\n WR: \"Raining\",\n WS: \"Raining\"\n };\n\n var getlatfromuser = latinput;\n var getlongfromuser = longinput;\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n\n var parser1 = new xml2js.Parser({explicitArray : true, attrkey : 'Child'});\n\n http.get('http://api.nea.gov.sg/api/WebAPI/?dataset=2hr_nowcast&keyref=781CF461BB6606ADC767F3B357E848ED3A27067168AB8007', function(res)\n {\n var response_data = '';\n res.setEncoding('utf8');\n res.on('data', function(chunk)\n {\n response_data += chunk;\n });\n \n res.on('end', function() \n {\n parser1.parseString(response_data, function(err, result) \n {\n if (err) \n {\n console.log('Got error: ' + err.message);\n }\n else \n {\n eyes.inspect(result);\n \n //convert into JSON object\n console.log('Converting to JSON object.');\n var jsonobject2 = JSON.parse(JSON.stringify(result));\n console.log(util.inspect(jsonobject2, false, null));\n\n //read and traverse JSON object\n var nearestdistance1 = 0;\n var showdistanceformat1;\n var showdistance1;\n \n var showlat1;\n var showlong1;\n var nearestForeCast;\n var nearestForeCastName;\n\n console.log(\"name 1: \" + jsonobject2.channel.title);\n console.log(\"name 2: \" + jsonobject2.channel.source);\n console.log(\"date3 : \" +jsonobject2.channel.item[0].forecastIssue[0].Child.date);\n console.log(\"length \"+jsonobject2.channel.item[0].weatherForecast[0].area.length)\n\n for (var i = 0; i < jsonobject2.channel.item[0].weatherForecast[0].area.length; ++i)\n {\n showlat1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lat;\n showlong1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lon;\n showdistance1 = calculatedistance(showlat1, showlong1, getlatfromuser, getlongfromuser, 'K');\n //round to 3 decimal places\n showdistanceformat1 = Math.round(showdistance1*1000)/1000;\n console.log(\"Distance(in km) : \" + showdistanceformat1);\n\n var tempdistance1 = showdistanceformat1;\n if (i == 0)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n if (nearestdistance1 > tempdistance1)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n }\n console.log(\"Distance to Nearest Town : \" + nearestdistance1);\n console.log(\"Forecast in Nearest Town : \" + nearestForeCast);\n console.log(\"Nearest Town : \" + nearestForeCastName);\n\n var forecast = forecastobj[nearestForeCast];\n console.log(\"Forecast in Current Location : \" + forecast);\n }\n });\n });\n\n res.on('error', function(err) \n {\n console.log('Got error: ' + err.message);\n });\n });\n}", "function gpsToLatLng(text) {\n var text = text.replace(/\\s+$/,'').replace(/^\\s+/,'');\n\n // simplest format is decimal numbers and minus signs and that's about it\n // one of them must be negative, which means it's the longitude here in North America\n if (text.match(/^[\\d\\.\\-\\,\\s]+$/)) {\n var dd = text.split(/[\\s\\,]+/);\n if (dd.length == 2) {\n dd[0] = parseFloat(dd[0]);\n dd[1] = parseFloat(dd[1]);\n if (dd[0] && dd[1]) {\n var lat,lng;\n if (dd[0] < 0) {\n lat = dd[1];\n lng = dd[0];\n } else {\n lat = dd[0];\n lng = dd[1];\n }\n return L.latLng([lat,lng]);\n }\n }\n }\n\n // okay, how about GPS/geocaching format: N xx xx.xxx W xxx xx.xxx\n var gps = text.match(/^N\\s*(\\d\\d)\\s+(\\d\\d\\.\\d\\d\\d)\\s+W\\s*(\\d\\d\\d)\\s+(\\d\\d\\.\\d\\d\\d)$/i);\n if (gps) {\n var latd = parseInt(gps[1]);\n var latm = parseInt(gps[2]);\n var lond = parseInt(gps[3]);\n var lonm = parseInt(gps[4]);\n\n var lat = latd + (latm/60);\n var lng = -lond - (lonm/60);\n\n return L.latLng([lat,lng]);\n }\n\n //if we got here then nothing matched, so bail\n return null;\n}", "function cprNLFunction (lat) {\n if (lat < 0) lat = -lat /* Table is simmetric about the equator. */\n if (lat < 10.47047130) return 59\n if (lat < 14.82817437) return 58\n if (lat < 18.18626357) return 57\n if (lat < 21.02939493) return 56\n if (lat < 23.54504487) return 55\n if (lat < 25.82924707) return 54\n if (lat < 27.93898710) return 53\n if (lat < 29.91135686) return 52\n if (lat < 31.77209708) return 51\n if (lat < 33.53993436) return 50\n if (lat < 35.22899598) return 49\n if (lat < 36.85025108) return 48\n if (lat < 38.41241892) return 47\n if (lat < 39.92256684) return 46\n if (lat < 41.38651832) return 45\n if (lat < 42.80914012) return 44\n if (lat < 44.19454951) return 43\n if (lat < 45.54626723) return 42\n if (lat < 46.86733252) return 41\n if (lat < 48.16039128) return 40\n if (lat < 49.42776439) return 39\n if (lat < 50.67150166) return 38\n if (lat < 51.89342469) return 37\n if (lat < 53.09516153) return 36\n if (lat < 54.27817472) return 35\n if (lat < 55.44378444) return 34\n if (lat < 56.59318756) return 33\n if (lat < 57.72747354) return 32\n if (lat < 58.84763776) return 31\n if (lat < 59.95459277) return 30\n if (lat < 61.04917774) return 29\n if (lat < 62.13216659) return 28\n if (lat < 63.20427479) return 27\n if (lat < 64.26616523) return 26\n if (lat < 65.31845310) return 25\n if (lat < 66.36171008) return 24\n if (lat < 67.39646774) return 23\n if (lat < 68.42322022) return 22\n if (lat < 69.44242631) return 21\n if (lat < 70.45451075) return 20\n if (lat < 71.45986473) return 19\n if (lat < 72.45884545) return 18\n if (lat < 73.45177442) return 17\n if (lat < 74.43893416) return 16\n if (lat < 75.42056257) return 15\n if (lat < 76.39684391) return 14\n if (lat < 77.36789461) return 13\n if (lat < 78.33374083) return 12\n if (lat < 79.29428225) return 11\n if (lat < 80.24923213) return 10\n if (lat < 81.19801349) return 9\n if (lat < 82.13956981) return 8\n if (lat < 83.07199445) return 7\n if (lat < 83.99173563) return 6\n if (lat < 84.89166191) return 5\n if (lat < 85.75541621) return 4\n if (lat < 86.53536998) return 3\n if (lat < 87.00000000) return 2\n else return 1\n}", "function checkCity(lat, lng) {\n if (lat.toFixed(3) >= 50.000 && lat.toFixed(3) <= 52.000) {\n if (lng.toFixed(3) >= 5.000 && lng.toFixed(3) <= 7.000) {\n inCity = true;\n $('#content_overzicht').empty();\n getWeetjes();\n getKoepons();\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n}", "function calcSunTrueLong(t) {\n var l0 = calcGeomMeanLongSun(t);\n var c = calcSunEqOfCenter(t);\n var O = l0 + c;\n return O; // in degrees\n}", "function encodeLongitude(longitude) {\n if (longitude === undefined) {\n return \",\";\n }\n var hemisphere;\n if (longitude < 0) {\n hemisphere = \"W\";\n longitude = -longitude;\n }\n else {\n hemisphere = \"E\";\n }\n // get integer degrees\n var d = Math.floor(longitude);\n // longitude degrees are always 3 digits\n var s = padLeft(d, 3, \"0\");\n // get fractional degrees\n var f = longitude - d;\n // convert to fractional minutes and round up to the specified precision\n var m = (f * 60.0);\n // format the fixed point fractional minutes \"mm.mmmmmm\"\n var t = padLeft(m.toFixed(6), 9, \"0\");\n s = s + t + \",\" + hemisphere;\n return s;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Not done yet. I want add it so this assertresultlength can take parameters besides a number, equals, greater than, small than.
testAssertResultLength() { }
[ "function testRecordLength(that, test) {\n\n // get records length from the w2ui's grid record\n var w2uiRecordLength = casper.evaluate(function (gridName) {\n return w2ui[gridName].records.length;\n }, that.grid);\n\n\n // Check w2ui records length match with length with api response\n test.assertEquals(w2uiRecordLength, that.apiResponse.total, \"{0} record length matched with response list\".format(that.grid));\n\n // get record length from the DOM\n var trsLen = casper.evaluate(function gridTableRowsLen(a, b, grid) {\n return b(a(grid));\n },\n w2ui_utils.getGridRecordsDivID,\n w2ui_utils.getGridTableRowsLength,\n that.grid\n );\n casper.log('[GridTest] [{0}] table rows length: {1}'.format(that.grid, trsLen), 'debug', common.logSpace);\n\n // match api response record length with records length in DOM\n test.assertEquals(trsLen, that.apiResponse.total, \"Grid [{0}] records (table rows) loaded in DOM\".format(that.grid));\n }", "get numberOfResultsIsValid() {\n return this._isPositiveNumber(this.state.numberOfResults);\n }", "function countTestsWithResult(tests, result) {\n\tvar total = 0;\n\n\ttests.forEach(function (test) {\n\t\tif (!test.isDataDriven) {\n\t\t\tif (test.result == result) {\n\t\t\t\ttotal++;\n\t\t\t}\n\t\t} else {\n\t\t\ttest.subtests.forEach(function (test) {\n\t\t\t\tif (test.result == result) {\n\t\t\t\t\ttotal++;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n\n\treturn total;\n}", "function findShorterAndCheckEqualitty(arr, length) {\n // Set variables to shorter and count\n let shorter = 1000, count = 0;\n \n // Loop array to find shorter integer and count how many of the same value\n for (let i = 0; i < length; i++) {\n if (arr[i] < shorter) {\n shorter = arr[i]\n } else if (arr[i] === shorter) {\n count++;\n }\n }\n \n // If count is equal length - 1, it means that all elements are equal to the first one\n if (count === length - 1) {\n return 0;\n }\n \n // Return shorter value\n return shorter;\n }", "function VerificationPrenom() {\n const prenom = document.getElementById(\"prenom\");\n const LMINI = 2, // DP LMINI = longueur minimale du prenom\n LMAXI = 50; //DP LMAXI = longueur maximale du prenom\n\n //DP si le prenom comporte moins de 2 lettres ou plus de 50 lettres alors erreur\n if ((prenom.value.length < LMINI) || (prenom.value.length > LMAXI)) {\n console.log(\"longueur prenom NOK\", prenom.value.length);\n return false;\n } else {\n console.log(\"longueur prenom OK\", prenom.value.length);\n return true;\n }\n}", "function mCreateTest(rows,cols,amp){\n\tif(rows === 0 || cols === 0){\n\t\tthrow new Error('ERROR: rows === 0 || cols === 0')\n\t}\n\tif(isNaN(amp)){\n\t\tthrow new Error('ERROR: isNaN(amp)')\n\t}\n}", "function verifyFileLength(fileEntry, length, onSuccess)\n{\n verifyFileContents(fileEntry, verifyFileLengthHelper, length, null, onSuccess);\n}", "function lengthValue(num1, num2) {\n var arr = [];\n if (num1 === num2) {\n console.log(\"Jinx!\");\n }\n for (var x=0; x<num1; x++) {\n arr.push(num2);\n }\n return arr;\n}", "function getLength(string){\n\n\n}", "function mMultiTest(m1,v){\n\tif(v[0].length !== 1){\n\t\tthrow new Error('ERROR: v[0].length !== 1')\n\t}\n\tif(m1[0].length !== v.length){\n\t\tthrow new Error('ERROR: m1[0].length !== v.length')\n\t}\n\tif(m1.length < 1 || v.length < 1){\n\t\tthrow new Error('ERROR: m1.length < 1 || v.length < 1')\n\t}\n\tif(m1[0].length < 1 || v[0].length < 1){\n\t\tthrow new Error('ERROR: m1[0].length < 1 || v[0].length < 1')\n\t}\n}", "function hasLength (data, value) {\n return assigned(data) && data.length === value;\n }", "function tooLongContentLength() {\n var content = \"test\";\n var options = {\n path: '/check/blablablabla',\n method: 'GET',\n headers: {\n 'Content-Length': 1000 // it will wait for the whole request, and then timeout\n }\n };\n testResponse(options, content, function(res) {}, {\n 'error': function(d){\n console.log(\"Bad content-length (too long) - test succeeded\");\n }\n });\n\n}", "function checkOperationLength() {\n if (displayEl.textContent.length > 10) {return false;}\n}", "function strLength(x){\n if (typeof x === \"string\" && x.length >= 8){\n return true;\n }\n return false;\n }", "function millionOrMore(data) {\n return data.romanSearchResults > 1000000;\n}", "verifyNumberOfProducts(noOfProduct){\n cy.get(this.numberOfCartItems).should('have.length',noOfProduct)\n }", "function setTotalQuestionsDOM( quizLength ) {\n\n\t$('#totalQuestions').text( quizLength );\n\n}", "function lengthError() {\n const passwordLength = document.getElementById(\"passwordLength\");\n if (\n passwordLength.value < 8 ||\n passwordLength.value > 128 ||\n isNaN(passwordLength.value)\n ) {\n alert(\"Error: Password must have between 8 and 128 characters.\");\n } else {\n checkboxError();\n }\n}", "errorMsg (title, expected, actual) {\n console.log(colors.red(`FAILED ${title.toUpperCase()}`))\n\n if (arguments.length === 4) {\n expected = JSON.stringify(expected)\n actual = JSON.stringify(actual)\n console.log(` Expected ${expected}\\n but got ${actual}`)\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pre: array of message objects Post: null Purpose: prints out messages for user in chat
function printMessages( /*Array<Object>*/ arr) { arr.map(msg => { if (msg[1] === 'ALL' || msg[0] === window.username && msg[1] === window.username) { print(msg[3], msg[0], msg[2] * 1000); if (!document.hasFocus()) { new Notification(`New Message from ${msg[0]}`, { body: msg[3] }); } } }); }
[ "function showchats(target, context) {\r\n var viewer = context.username;\r\n\r\n var i = 0;\r\n while (i <= viewerObj.length) {\r\n if (viewerObj[i] == viewer) {\r\n sendMessage(target, context, context.username + ' has chatted ' + chatObj[i] + ' times!');\r\n console.log(\"viewer is in hugs array\")\r\n break;\r\n }\r\n else if (i == viewerObj.length) {\r\n console.log(viewer + \" is not in array\");\r\n sendMessage(target, context, context.username + ' has not chatted!');\r\n break;\r\n }\r\n i++;\r\n } \r\n}", "function postWinnerMessage(winnersInfo, channels, title, message) {\n let attachments = []\n \n winnersInfo.forEach(userInfo => {\n attachments.push({\n //pretext: message,\n color: '#36a64f',\n author_name: userInfo.real_name,\n author_icon: userInfo.profile.image_48,\n thumb_url: userInfo.profile.image_192,\n footer: title,\n ts: Date.now()\n })\n })\n \n let jsonPayload = {\n text: message,\n as_user: false,\n icon_emoji: \":tada\",\n attachments: attachments\n }\n postMessage(channels, jsonPayload)\n}", "function getSendMessageList() {\n console.log('geting message list...');\n var request = $http({\n method: \"post\",\n url: \"http://139.59.254.92/getmesslist.php\",\n data: {\n userName: $scope.userName,\n frUserName: $scope.user,\n },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n });\n /* Successful HTTP post request or not */\n request.success(function (data) {\n $scope.sendMess = data;\n for (var i = 0; i < $scope.sendMess.length; i++) {\n $scope.mess.push($scope.sendMess[i]);\n };\n sortMessage();\n getReplyMessageList();\n });\n request.error(function() {\n showMessage('Unable connect to load message, please check your internet connection!');\n });\n }", "function onMessage(evt) {\n let obj = JSON.parse(evt.data);\n if(obj.isMsg == true) {\n chatMsg(obj);\n } else {\n updateUsersList(obj);\n }\n}", "function showchatUserSelect(){\n if(userChat==null)\n {return;}\n /*eventAddChat(message);*/\n $(\".inyect-commit\").html(\"\");\n $(\"#bienvenida\").hide();\n listOfChat.forEach(function(message){\n if((message.name.id==userChat.id && message.userSend.id==JSON.parse($.session.get(\"ObjectUser\")).id) || (message.name.id==JSON.parse($.session.get(\"ObjectUser\")).id && message.userSend.id==userChat.id)){\n\n eventAddChat(message);\n }\n });\n $(\".inyect-commit\").scrollTo(10000,0)/*mejorar la parte del scroll*/\n }", "function showChats(channel, listOFMessages){\n\n\t// format the iso time coming from the server into something readable\n\tlistOFMessages.map(x => x.date = luxon.DateTime.fromISO(x.date).toLocaleString(luxon.DateTime.DATETIME_MED))\n\t// if the messages is not empty\n\tif (listOFMessages.length > 0){\n\n\t\tconsole.log(listOFMessages[0].date)\n\t\t// compile handle bar template that takes in a list of message dictionaries as input and renders it\n\t\tconst template = Handlebars.compile(document.querySelector(\"#chatstemplate\").innerHTML);\n\t\tconst messages = template({\"messages\": listOFMessages});\n\n\t\t// add the message to the dom\n\t\tdocument.querySelector(\".chat-box\").innerHTML = messages;\n\t}\n\telse\n\t{ \n\t \t// if a channel has no messages display nothing\n\t\tdocument.querySelector(\".chat-box\").innerHTML = \"\";\n\t}\n\n\t// if it contains a hyphen then its a user pair and we want the banner to be just the other guys name\n\tlet header = channel\n\tif (channel.includes('-')){\n\t\tpair = channel.split('-')\n\t\tif (pair.includes(username)){\n\t\t\tothername = (username === pair[0]) ? pair[1] : pair[0]\n\t\t\theader = othername\n\t\t}\n\t}\n\t// change name to reflect current channel\n\tdocument.querySelector(\"#channelname-header\").innerText = header;\n}", "async function pushNewMessagesToUI (data) {\n\n\tconst uiServerUrl = `${config.uiServer.baseUrl}/webhooks/new-message`;\n\n\tconst req = new RequestNinja(uiServerUrl, {\n\t\ttimeout: (1000 * 30),\n\t\treturnResponseObject: true,\n\t});\n\n\tconst res = await req.postJson({\n\t\tuserId: data.recUser._id.toString(),\n\t\tmessage: data.message,\n\t});\n\n\tif (res.statusCode !== 200) {\n\t\tthrow new Error(`Non 200 HTTP status code \"${res.statusCode}\" returned by the Eyewitness UI.`);\n\t}\n\n\tif (!res.body || !res.body.success) {\n\t\tthrow new Error(`The Eyewitness UI returned an error: \"${res.body.error}\".`);\n\t}\n\n}", "function sendNotif(msg, user){\r\n console.log(\"BEFORE:\");\r\n console.log(user);\r\n user.notifications.unshift(msg);\r\n console.log(\"AFTER:\");\r\n console.log(user);\r\n}", "function showChat() {\n\tdocument.getElementById(\"app\").innerHTML = chatHTML;\n\n\t// Find the latest 10 messages. They will come with the newest first\n\t// which is why we have to reverse before adding them\n\tclient\n\t\t.service(\"messages\")\n\t\t.find({\n\t\t\tquery: {\n\t\t\t\t$params: {\n\t\t\t\t\t$sort: { createdAt: -1 },\n\t\t\t\t\t$limit: 25\n\t\t\t\t},\n\t\t\t\ttotal: 1,\n\t\t\t\tlimit: 1,\n\t\t\t\tskip: 1,\n\t\t\t\tdata: {\n\t\t\t\t\ttext: 1,\n\t\t\t\t\towner: {\n\t\t\t\t\t\tname: 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.then(page => {\n\t\t\tpage.data.reverse().forEach(addMessage);\n\t\t});\n}", "function getMessages(req, res, user) {\n MessageController.getByUID(user.userID)\n .then((results) => {\n res.json(results);\n });\n}", "function updateChatRoom(message) {\n // TODO convert the data to JSON and append the message to the chat area\n let data = JSON.parse(message.data);\n\n console.log(data.userMessage);\n $(\"#chatArea\").append(data.userMessage);\n}", "renderMessages(messages, type) {\n if (!messages || !messages.length)\n return null;\n return messages.map((message, i) => {\n return React.createElement(FlashMessage, { message: message, type: type, key: `i${i}` });\n });\n }", "function displayOtherUsersMsg(message, userName) {\n\tlet otherUserMessage = userName + ' : ' + message;\n\n\tlet messageElement = document.createElement(\"div\");\n\tmessageElement.setAttribute('class','col-12 form-group');\n\tmessageElement.innerHTML = '<div class=\"card received-message\">'+\n\t\t\t\t\t\t\t'<div class=\"card-body\"><div class=\"card-text\">' + \n\t\t\t\t\t\t\totherUserMessage + '</div></div></div>';\n\n\tlet chatContainer = document.getElementById('chatContainer');\n\tchatContainer.insertBefore(messageElement, chatContainer.childNodes[0]);\n}", "function topLevelFeed(messages) {\n return _\n .chain(messages)\n .filter(d => !d.value.replyTo)\n .sortBy('change')\n .reverse()\n .value()\n}", "function fetchMessages() {\n const url = '/messages?user=' + parameterUsername;\n fetch(url)\n .then((response) => {\n return response.json();\n })\n .then((messages) => {\n const messagesContainer = document.getElementById('message-container');\n if (messages.length == 0) {\n messagesContainer.innerHTML = '<p>This user has no posts yet.</p>';\n } else {\n messagesContainer.innerHTML = '';\n }\n messages.forEach((message) => {\n const messageDiv = buildMessageDiv(message);\n messageDiv.appendChild(buildMessageRepliesDiv(message));\n messagesContainer.appendChild(messageDiv);\n });\n replaceCKEditor();\n });\n}", "listenMessages() {\n this.messageRef\n .limitToLast(10)\n .on('value', message => {\n this.setState({\n list: Object.values(message.val()),\n });\n });\n }", "function addMessage(msg, roomName, username, other) {\n var roomNameClass = toClassString(roomName);\n\n //check if user is in the room. If not, add 1 new unread message.\n if (currentRoom != roomName) {\n var index = userRoomsList.map(function(e) { return e.roomName; }).indexOf(roomName);\n userRoomsList[index].numNewMsgs++;\n //show badge if it is hidden\n if($('#' + roomNameClass + '-badge').is(\":hidden\")){\n $('#' + roomNameClass + '-badge').parent().addClass(\"tab-badge-notification-bg\");\n $('#' + roomNameClass + '-badge').show();\n }\n $('#' + roomNameClass + '-badge').text(userRoomsList[index].numNewMsgs);\n }\n \n //create message timestamp\n var time = new Date();\n var hour = time.getHours();\n var minute = time.getMinutes();\n var second = time.getSeconds();\n var sign = \"am\";\n if (hour > 11) {\n sign = \"pm\";\n if (hour > 12) {\n hour = hour % 12;\n }\n } else if (hour == 0) {\n hour = 12;\n }\n if (minute < 10) {\n minute = \"0\" + minute;\n }\n if (second < 10) {\n second = \"0\" + second;\n }\n time = hour + \":\" + minute + \":\" + second + \" \" + sign;\n\n //append to the right div/ie to the right room\n var bgCSSClass = other ? \"bg-info\" : \"bg-primary\";\n bgCSSClass = username == \"@UWBot\" ? \"bg-success\" : bgCSSClass;\n var message = username == \"@UWBot\" ? msg : escapeHtml(msg);\n $('div#chat-panel div#room-' + roomNameClass + ' div.chat-entries').append('<div class=\"message ' + bgCSSClass + '\"><span class=\"msg-user\">'\n + username + '</span> : <span class=\"msg-content\">' + message + '</span>' + '<span class=\"message-timestamp\">'\n + time + '</span>' + '</div>');\n\n var roomChatEntries = $('div#chat-panel div#room-' + roomNameClass + ' div.chat-entries');\n if (Math.abs((roomChatEntries[0].scrollHeight - roomChatEntries.scrollTop() - roomChatEntries.outerHeight())) < $(\"#chat-panel\").height() + 200) {\n roomChatEntries.animate({\n scrollTop: roomChatEntries[0].scrollHeight\n }, 200);\n }\n else {\n $('#more-msgs').filter(':hidden').fadeIn(500).delay(1500).fadeOut(500);\n }\n\n emojify.run(); //enable emojis\n}", "function findMessagethreadsByUserIdSuccess(response) {\n vm.messagethreads = response.data;\n // sort messages by last updated time\n vm.messagethreads.sort(function(a, b) {\n return new Date(b.dateUpdated) - new Date(a.dateUpdated);\n })\n }", "function reviewNotify(userObj){\r\n // Loop over all users followers\r\n console.log(\"In reviewNotify\");\r\n console.log(userObj);\r\n for(let i = 0; i < userObj.followers.length; i++){\r\n let userToNotify = users[userObj.followers[i].id];\r\n let msg = userObj.username + \" has created a new review.\";\r\n\r\n sendNotif(msg, userToNotify);\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getting the next number for a hexagon
function getNextNumber (numberCount, hexagonIndex, robberIndex) { if (hexagonIndex === robberIndex) { return '' // Desert tile has no number, robber starts on desert } var random = Math.floor(Math.random() * numberCount.length) var toReturn = numberCount[random] numberCount.splice(random, 1) return toReturn }
[ "function positionHexagon() {\r\n //CANTIDAD DE HEXAGONOS\r\n var espacio = [1, 1, 1]; //Cantidad de exagonos en una linea\r\n\r\n //POSICION DE HEXAGONOS \r\n hexagon = document.querySelectorAll(\"li.hexagon\");\r\n width_hexagon = parseInt($(hexagon[0]).css(\"width\"));\r\n separation = 2; //Distancia entre hexagonos\r\n\r\n left_hexagon = [10, 10]; //Distancia de separacion entre el DIV (X)\r\n left_hexagon.push((width_hexagon / 2) + (separation / 2) + left_hexagon[0]);\r\n top_hexagon = -30; //Distancia de separacion entre el DIV (Y)\r\n\r\n for (var i = 0; i < hexagon.length; i++) {\r\n if (i >= espacio[1]) {\r\n espacio[1] = espacio[1] + espacio[0];\r\n top_hexagon = top_hexagon + width_hexagon - (width_hexagon / 7) + separation;\r\n }\r\n if (left_hexagon[1] == (width_hexagon + separation) * espacio[0] + left_hexagon[0]) {\r\n left_hexagon[1] = left_hexagon[2];\r\n } else if (left_hexagon[1] == (width_hexagon + separation) * espacio[0] + left_hexagon[2]) {\r\n left_hexagon[1] = left_hexagon[0];\r\n }\r\n $(hexagon[i]).css({\r\n \"top\": top_hexagon,\r\n \"left\": left_hexagon[1],\r\n });\r\n left_hexagon[1] = left_hexagon[1] + (width_hexagon + separation);\r\n }\r\n\r\n //POSICION DE LA IMAGEN DE FONDO\r\n var positionSpan = document.querySelectorAll(\"span.hexagon-in2\");\r\n x_position = [-300, -300]; //Posicion de la imagen de fondo (X)\r\n x_position.push(-(width_hexagon / 2) - (separation / 2) + x_position[0])\r\n y_position = -40; //Posicion de la imagen de fondo (Y)\r\n\r\n for (var i = 0; i < positionSpan.length; i++) {\r\n if (i >= espacio[2]) {\r\n espacio[2] = espacio[2] + espacio[0];\r\n y_position = y_position - (width_hexagon - (width_hexagon / 7)) - separation;\r\n }\r\n if (x_position[1] == (-(width_hexagon + separation) * espacio[0] + x_position[0])) {\r\n x_position[1] = x_position[2];\r\n } else if (x_position[1] == -(width_hexagon + separation) * espacio[0] + x_position[2]) {\r\n x_position[1] = x_position[0];\r\n }\r\n $(positionSpan[i]).css({\r\n \"background-position-x\": x_position[1],\r\n \"background-position-y\": y_position,\r\n });\r\n x_position[1] = x_position[1] - (width_hexagon + separation);\r\n }\r\n}", "function nextColor() {\n c = colors[ count % color.length]\n count = count + 1\n return c\n}", "function makeHexagons(){\r\n var hexX = 0;\r\n var hexY = 0;\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][1][0] = hexX;\r\n hexagons[i][1][1] = hexY;\r\n hexY += 1;\r\n if(hexX == 9 && hexY == 7){\r\n hexX += 1;\r\n hexY = 5;\r\n }\r\n if(hexX == 8 && hexY == 8){\r\n hexX += 1;\r\n hexY = 4;\r\n }\r\n if(hexX == 7 && hexY == 9){\r\n hexX += 1;\r\n hexY = 3;\r\n }\r\n if(hexX == 6 && hexY == 10){\r\n hexX += 1;\r\n hexY = 2;\r\n }\r\n if(hexX == 5 && hexY == 11){\r\n hexX += 1;\r\n hexY = 1;\r\n }\r\n if(hexY == 11){\r\n hexY = 0;\r\n hexX += 1;\r\n }\r\n }\r\n for(var i = 0; i < 91; i++){\r\n hexagons[i][0][1] = hexagons[i][1][1] - 5;\r\n hexagons[i][0][0] = (hexagons[i][0][1]) / importantNumber;\r\n hexagons[i][0][0] = Math.abs(hexagons[i][0][0]);\r\n hexagons[i][0][0] += hexagons[i][1][0];\r\n hexagons[i][0][1] += 5;\r\n hexagons[i][0][0] *= s/13;\r\n hexagons[i][0][1] *= s/14;\r\n hexagons[i][0][0] += s/13 * 1.5;\r\n hexagons[i][0][1] += s/13 * 1.5;\r\n }\r\n for(var i = 0; i < 91; i++){\r\n if(hexagons[i][1][1] == 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] < 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n if(hexagons[i][1][1] > 5) for(var j = 0; j < 91; j++){\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][0] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][1] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][2] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] - 1) && (hexagons[i][1][1] == hexagons[j][1][1])){\r\n hexagons[i][3][3] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0] + 1) && (hexagons[i][1][1] == hexagons[j][1][1] - 1)){\r\n hexagons[i][3][4] = j;\r\n }\r\n if((hexagons[i][1][0] == hexagons[j][1][0]) && (hexagons[i][1][1] == hexagons[j][1][1] + 1)){\r\n hexagons[i][3][5] = j;\r\n }\r\n }\r\n }\r\n}", "function generateHex() {\n const rad = Math.floor(Math.random() * Math.floor(50) + 1);\n\n let hexagon = new Hexagon(rad); // see src/js/Hexagon.js\n\n return hexagon;\n}", "function getTileIndex(x, y) {\n return y * 12 + x;\n}", "function getX(hex, layout, hexWidth, hexRadius) {\n\t\t\tvar x = 0,\n\t\t\t xOffset = 0;\n\n\t\t\tswitch (layout) {\n\t\t\t\tcase \"odd-r\":\n\t\t\t\t\txOffset = hex.rc % 2 === 1 ? hexWidth : hexWidth / 2;\n\t\t\t\t\tx = hex.qc * hexWidth + xOffset;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"even-r\":\n\t\t\t\t\txOffset = hex.rc % 2 === 0 ? hexWidth : hexWidth / 2;\n\t\t\t\t\tx = hex.qc * hexWidth + xOffset;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"odd-q\":\n\t\t\t\tcase \"even-q\":\n\t\t\t\t\tx = hex.qc * hexRadius * 1.5 + hexRadius;\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn x;\n\t\t}", "function toCoordinate(id_num) {\n // Math doesnn't work properly for last cell\n if (id_num === \"256\") {\n return [15, 15];\n }\n else {\n id_num = parseInt(id_num);\n var x = Math.floor((id_num-1)/16);\n var y = id_num-(16*x);\n return [x, y-1];\n }\n}", "move (hex) {\r\n let world = this.hex.world\r\n this.calories -= this.movementCost\r\n if (hex) {\r\n return world.moveObj(this.key, hex)\r\n }\r\n let neighborHexes = this.hex.world.getNeighbors(this.hex)\r\n let index = Tools.getRand(0, neighborHexes.length - 1)\r\n let destinationHex = neighborHexes[index]\r\n return world.moveObj(this.key, destinationHex)\r\n }", "getCoordinates (index) {\n let row = Math.floor(index / 8)\n let column = index % 8\n\n if (this.reversed) {\n row = Math.abs(row - 7)\n column = Math.abs(column - 7)\n }\n\n return { row, column }\n }", "function getHex(x, y, hexArr) {\r\n\r\n // collisionDetect_tri(x, y, hexArr[0], hexArr[1], hexArr[2]);\r\n}", "function nextNumber(incomingNumber){\n if(isLastNumber(incomingNumber)){\n activeNumber = cohort[0].number;\n return activeNumber;\n }\n for (var i = 0; i < cohort.length; i++) {\n if(cohort[i].number === incomingNumber){\n activeNumber = cohort[i+1].number;\n return activeNumber;\n }\n }\n}", "function consoleCommon_getNextEmployeeNo()\n{\n var settingsObj_employeeNoPrefix= Cached_getSettingsByKey(SettingsConstants.SETTINGS_RELATION_KEY_EMPLOYEE_NO_PREFIX);\n var settingsObj_employeeMaxNo = Cached_getSettingsByKey(SettingsConstants.SETTINGS_RELATION_KEY_EMPLOYEE_NO_MAX);\n var settingsObj_employeeNextNo = Cached_getSettingsByKey(SettingsConstants.SETTINGS_RELATION_KEY_EMPLOYEE_NO_NEXT);\n \n // If next no has burst\n if (settingsObj_employeeNextNo.propValue > settingsObj_employeeMaxNo.propValue)\n \treturn false;\n \n // Construct billing number PREFIX + NEXTNO\n var maxLength = String(settingsObj_employeeMaxNo.propValue).length;\n var nextNo = settingsObj_employeeNoPrefix.propValue + \n\t\t\t\t\ttycheesText_leftPad(settingsObj_employeeNextNo.propValue, '0', maxLength);\n\t\n\treturn nextNo;\n}", "function parseIdx(p, n){ // PathPoints, number for index\n var len = p.length;\n if( p.parent.closed ){\n return n >= 0 ? n % len : len - Math.abs(n % len);\n } else {\n return (n < 0 || n > len - 1) ? -1 : n;\n }\n }", "function hexLinInt(n, start, end) {\n start = parseInt(start, 16);\n end = parseInt(end, 16);\n var hex = Math.round((end - start) * n + start);\n hex = hex.toString(16);\n hex = (\"00\" + hex).substring(hex.length);\n return hex;\n }", "next(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the next path of a root path [\".concat(path, \"], because it has no next index.\"));\n }\n\n var last = path[path.length - 1];\n return path.slice(0, -1).concat(last + 1);\n }", "function getNextBox(box){\n\t\t\t\tvar x = box.x;\n\t\t\t\tvar y = box.y;\n\t\t\t\tif(x == 8){\n\t\t\t\t\tx = 0;\n\t\t\t\t\ty++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tx++;\n\t\t\t\t}\n\n\t\t\t\tif(y > 8){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\treturn getBox(x,y);\n\t\t\t\t}\n\t\t\t}", "function colorNextCells(coords, color, index) {\n colorCells(coords, color, 'next-' + index);\n}", "function index(x, y) {\n return x * gridSize + y;\n}", "function nextConnectedArc(arcId) {\n var chainId = arcToChainId(arcId),\n chains = getNodeChains(),\n nextChainId = chains[chainId];\n if (!(nextChainId >= 0 && nextChainId < chains.length)) {\n // console.log('arcId:', arcId, 'chainId:', chainId, 'next chain id:', nextChainId)\n error(\"out-of-range chain id\");\n }\n return chainToArcId(nextChainId);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
b % w , q = b / w :: BigNat > BigNat > Word > Word
function h$ghcjsbn_quotRem_bw(q, b, w) { h$ghcjsbn_assertValid_b(b, "quotRem_bw"); h$ghcjsbn_assertValid_w(w, "quotRem_bw"); var a = h$ghcjsbn_tmp_2a; h$ghcjsbn_toBigNat_w(a, w); /* if(w === 0) { a[0] = 0; } else if(w > 0 && w <= GHCJSBN_MASK) { a[0] = 1; a[1] = w; } else { a[0] = 2; a[1] = w & GHCJSBN_MASK; a[2] = w >>> GHCJSBN_BITS; } */ var r = []; h$ghcjsbn_quotRem_bb(q, r, b, a); return h$ghcjsbn_toWord_b(r); }
[ "function inWord(bit) {\n return Math.floor((bit | 0) / 32);\n }", "function hs_wordToWord64(low) {\n return [0, low];\n}", "static uint104(v) { return n(v, 104); }", "static uint80(v) { return n(v, 80); }", "function __div64(q, r, u, v) {\n var m = u.countSignificantDigits();\n var n = v.countSignificantDigits();\n\n q.hi32 = q.lo32 = 0;\n\n if (n === 1) {\n // v has single digit\n var vd = v.getDigit(0, 0);\n var carry = 0;\n for (var i = m - 1; i >= 0; --i) {\n var ui = (carry << 16) | u.getDigit(i, 0);\n if (ui < 0) {\n ui += 0x100000000;\n }\n var qi = (ui / vd) | 0;\n q.setDigit(i, 0, qi);\n carry = ui - qi * vd;\n }\n\n r.hi32 = 0;\n r.lo32 = carry;\n return;\n }\n\n r.hi32 = u.hi32; \n r.lo32 = u.lo32;\n\n if (m < n) {\n return;\n }\n\n // Normalize\n var nrm = __countLeadingZeroes16(v.getDigit(n - 1, 0));\n\n var vd1 = v.getDigit(n - 1, nrm); \n var vd0 = v.getDigit(n - 2, nrm);\n for (var j = m - n; j >= 0; --j) {\n // Calculate qj estimate\n var ud21 = r.getTwoDigits(j + n, nrm);\n var ud2 = ud21 >>> 16;\n if (ud21 < 0) {\n ud21 += 0x100000000;\n }\n\n var qest = (ud2 === vd1) ? 0xFFFF : ((ud21 / vd1) | 0);\n var rest = ud21 - qest * vd1;\n\n // 0 <= (qest - qj) <= 2\n\n // Refine qj estimate\n var ud0 = r.getDigit(j + n - 2, nrm);\n while ((qest * vd0) > ((rest * 0x10000) + ud0)) {\n --qest;\n rest += vd1;\n }\n\n // 0 <= (qest - qj) <= 1\n \n // Multiply and subtract\n var carry = 0;\n for (var i = 0; i < n; ++i) {\n var vi = qest * v.getDigit(i, nrm);\n var ui = r.getDigit(i + j, nrm) - carry - (vi & 0xffff);\n r.setDigit(i + j, nrm, ui);\n carry = (vi >>> 16) - (ui >> 16);\n }\n var uj = ud2 - carry;\n\n if (uj < 0) {\n // qest - qj = 1\n\n // Add back\n --qest;\n var carry = 0;\n for (var i = 0; i < n; ++i) {\n var ui = r.getDigit(i + j, nrm) + v.getDigit(i, nrm)\n + carry;\n r.setDigit(i + j, nrm, ui);\n carry = ui >> 16;\n }\n uj += carry;\n }\n\n q.setDigit(j, 0, qest);\n r.setDigit(j + n, nrm, uj);\n }\n }", "function byteopsMontgomeryReduce(a) {\r\n var u = int16(int32(a) * paramsQinv);\r\n var t = u * paramsQ;\r\n t = a - t;\r\n t >>= 16;\r\n return int16(t);\r\n}", "static uint176(v) { return n(v, 176); }", "static uint64(v) { return n(v, 64); }", "function VxEuclideanRythm ()\n{\n\tthis.k = 4;\n\tthis.N = 16;\n\tthis.R = 0;\n\tthis.algorithm = 'bjorklund';\n\tthis.integermode = 0;\n}", "function divBy2(value) {\n return value >> 1;\n}", "static uint32(v) { return n(v, 32); }", "function readNWord(bytes, index, length)\n{\n\tif (length <= 4)\n\t{\n\t\t// Word fits in 32-bit\n\t\tlet result = 0;\n\t\tfor (let b = 0; b < length; b++)\n\t\t{\n\t\t\tresult <<= 8;\n\t\t\tresult |= bytes[index++];\n\t\t}\n\t\treturn result;\n\t}\n\telse\n\t{\n\t\t// Word requires 64-bit JS nastiness\n\t\tlet lo = 0, hi = 0;\n\t\tfor (let b = 4; b < length; b++)\n\t\t{\n\t\t\thi <<= 8;\n\t\t\thi |= bytes[index++];\n\t\t}\n\t\tfor (let b = 0; b < 4; b++)\n\t\t{\n\t\t\tlo <<= 8;\n\t\t\tlo |= bytes[index++];\n\t\t}\n\t\treturn { hi, lo };\n\t}\n}", "static uint160(v) { return n(v, 160); }", "function binb(x, len) {\n var j, i, l,\n W = new Array(80),\n hash = new Array(16),\n //Initial hash values\n H = [\n new int64(0x6a09e667, -205731576),\n new int64(-1150833019, -2067093701),\n new int64(0x3c6ef372, -23791573),\n new int64(-1521486534, 0x5f1d36f1),\n new int64(0x510e527f, -1377402159),\n new int64(-1694144372, 0x2b3e6c1f),\n new int64(0x1f83d9ab, -79577749),\n new int64(0x5be0cd19, 0x137e2179)\n ],\n T1 = new int64(0, 0),\n T2 = new int64(0, 0),\n a = new int64(0, 0),\n b = new int64(0, 0),\n c = new int64(0, 0),\n d = new int64(0, 0),\n e = new int64(0, 0),\n f = new int64(0, 0),\n g = new int64(0, 0),\n h = new int64(0, 0),\n //Temporary variables not specified by the document\n s0 = new int64(0, 0),\n s1 = new int64(0, 0),\n Ch = new int64(0, 0),\n Maj = new int64(0, 0),\n r1 = new int64(0, 0),\n r2 = new int64(0, 0),\n r3 = new int64(0, 0);\n\n if (sha512_k === undefined) {\n //SHA512 constants\n sha512_k = [\n new int64(0x428a2f98, -685199838), new int64(0x71374491, 0x23ef65cd),\n new int64(-1245643825, -330482897), new int64(-373957723, -2121671748),\n new int64(0x3956c25b, -213338824), new int64(0x59f111f1, -1241133031),\n new int64(-1841331548, -1357295717), new int64(-1424204075, -630357736),\n new int64(-670586216, -1560083902), new int64(0x12835b01, 0x45706fbe),\n new int64(0x243185be, 0x4ee4b28c), new int64(0x550c7dc3, -704662302),\n new int64(0x72be5d74, -226784913), new int64(-2132889090, 0x3b1696b1),\n new int64(-1680079193, 0x25c71235), new int64(-1046744716, -815192428),\n new int64(-459576895, -1628353838), new int64(-272742522, 0x384f25e3),\n new int64(0xfc19dc6, -1953704523), new int64(0x240ca1cc, 0x77ac9c65),\n new int64(0x2de92c6f, 0x592b0275), new int64(0x4a7484aa, 0x6ea6e483),\n new int64(0x5cb0a9dc, -1119749164), new int64(0x76f988da, -2096016459),\n new int64(-1740746414, -295247957), new int64(-1473132947, 0x2db43210),\n new int64(-1341970488, -1728372417), new int64(-1084653625, -1091629340),\n new int64(-958395405, 0x3da88fc2), new int64(-710438585, -1828018395),\n new int64(0x6ca6351, -536640913), new int64(0x14292967, 0xa0e6e70),\n new int64(0x27b70a85, 0x46d22ffc), new int64(0x2e1b2138, 0x5c26c926),\n new int64(0x4d2c6dfc, 0x5ac42aed), new int64(0x53380d13, -1651133473),\n new int64(0x650a7354, -1951439906), new int64(0x766a0abb, 0x3c77b2a8),\n new int64(-2117940946, 0x47edaee6), new int64(-1838011259, 0x1482353b),\n new int64(-1564481375, 0x4cf10364), new int64(-1474664885, -1136513023),\n new int64(-1035236496, -789014639), new int64(-949202525, 0x654be30),\n new int64(-778901479, -688958952), new int64(-694614492, 0x5565a910),\n new int64(-200395387, 0x5771202a), new int64(0x106aa070, 0x32bbd1b8),\n new int64(0x19a4c116, -1194143544), new int64(0x1e376c08, 0x5141ab53),\n new int64(0x2748774c, -544281703), new int64(0x34b0bcb5, -509917016),\n new int64(0x391c0cb3, -976659869), new int64(0x4ed8aa4a, -482243893),\n new int64(0x5b9cca4f, 0x7763e373), new int64(0x682e6ff3, -692930397),\n new int64(0x748f82ee, 0x5defb2fc), new int64(0x78a5636f, 0x43172f60),\n new int64(-2067236844, -1578062990), new int64(-1933114872, 0x1a6439ec),\n new int64(-1866530822, 0x23631e28), new int64(-1538233109, -561857047),\n new int64(-1090935817, -1295615723), new int64(-965641998, -479046869),\n new int64(-903397682, -366583396), new int64(-779700025, 0x21c0c207),\n new int64(-354779690, -840897762), new int64(-176337025, -294727304),\n new int64(0x6f067aa, 0x72176fba), new int64(0xa637dc5, -1563912026),\n new int64(0x113f9804, -1090974290), new int64(0x1b710b35, 0x131c471b),\n new int64(0x28db77f5, 0x23047d84), new int64(0x32caab7b, 0x40c72493),\n new int64(0x3c9ebe0a, 0x15c9bebc), new int64(0x431d67c4, -1676669620),\n new int64(0x4cc5d4be, -885112138), new int64(0x597f299c, -60457430),\n new int64(0x5fcb6fab, 0x3ad6faec), new int64(0x6c44198c, 0x4a475817)\n ];\n }\n\n for (i = 0; i < 80; i += 1) {\n W[i] = new int64(0, 0);\n }\n\n // append padding to the source string. The format is described in the FIPS.\n x[len >> 5] |= 0x80 << (24 - (len & 0x1f));\n x[((len + 128 >> 10) << 5) + 31] = len;\n l = x.length;\n for (i = 0; i < l; i += 32) { //32 dwords is the block size\n int64copy(a, H[0]);\n int64copy(b, H[1]);\n int64copy(c, H[2]);\n int64copy(d, H[3]);\n int64copy(e, H[4]);\n int64copy(f, H[5]);\n int64copy(g, H[6]);\n int64copy(h, H[7]);\n\n for (j = 0; j < 16; j += 1) {\n W[j].h = x[i + 2 * j];\n W[j].l = x[i + 2 * j + 1];\n }\n\n for (j = 16; j < 80; j += 1) {\n //sigma1\n int64rrot(r1, W[j - 2], 19);\n int64revrrot(r2, W[j - 2], 29);\n int64shr(r3, W[j - 2], 6);\n s1.l = r1.l ^ r2.l ^ r3.l;\n s1.h = r1.h ^ r2.h ^ r3.h;\n //sigma0\n int64rrot(r1, W[j - 15], 1);\n int64rrot(r2, W[j - 15], 8);\n int64shr(r3, W[j - 15], 7);\n s0.l = r1.l ^ r2.l ^ r3.l;\n s0.h = r1.h ^ r2.h ^ r3.h;\n\n int64add4(W[j], s1, W[j - 7], s0, W[j - 16]);\n }\n\n for (j = 0; j < 80; j += 1) {\n //Ch\n Ch.l = (e.l & f.l) ^ (~e.l & g.l);\n Ch.h = (e.h & f.h) ^ (~e.h & g.h);\n\n //Sigma1\n int64rrot(r1, e, 14);\n int64rrot(r2, e, 18);\n int64revrrot(r3, e, 9);\n s1.l = r1.l ^ r2.l ^ r3.l;\n s1.h = r1.h ^ r2.h ^ r3.h;\n\n //Sigma0\n int64rrot(r1, a, 28);\n int64revrrot(r2, a, 2);\n int64revrrot(r3, a, 7);\n s0.l = r1.l ^ r2.l ^ r3.l;\n s0.h = r1.h ^ r2.h ^ r3.h;\n\n //Maj\n Maj.l = (a.l & b.l) ^ (a.l & c.l) ^ (b.l & c.l);\n Maj.h = (a.h & b.h) ^ (a.h & c.h) ^ (b.h & c.h);\n\n int64add5(T1, h, s1, Ch, sha512_k[j], W[j]);\n int64add(T2, s0, Maj);\n\n int64copy(h, g);\n int64copy(g, f);\n int64copy(f, e);\n int64add(e, d, T1);\n int64copy(d, c);\n int64copy(c, b);\n int64copy(b, a);\n int64add(a, T1, T2);\n }\n int64add(H[0], H[0], a);\n int64add(H[1], H[1], b);\n int64add(H[2], H[2], c);\n int64add(H[3], H[3], d);\n int64add(H[4], H[4], e);\n int64add(H[5], H[5], f);\n int64add(H[6], H[6], g);\n int64add(H[7], H[7], h);\n }\n\n //represent the hash as an array of 32-bit dwords\n for (i = 0; i < 8; i += 1) {\n hash[2 * i] = H[i].h;\n hash[2 * i + 1] = H[i].l;\n }\n return hash;\n }", "static uint(v) { return n(v, 256); }", "function divisibleByB(a, b) {\n\treturn a - a % b + b;\n}", "static uint8(v) { return n(v, 8); }", "function answerQuery(l, r) {\n // Return the answer for this query modulo 1000000007.\n const s = word.slice(l - 1, r);\n const wordCount = Array(26);\n for (let i of s) {\n if (!wordCount[i.charCodeAt() - 97]) wordCount[i.charCodeAt() - 97] = 1;\n else wordCount[i.charCodeAt() - 97]++;\n }\n const countMap = {};\n for (let i of wordCount) {\n if (i > 1) {\n if (i % 2 === 0) {\n if (countMap[i]) countMap[i]++;\n else countMap[i] = 1;\n } else {\n if (countMap[i - 1]) countMap[i - 1]++;\n else countMap[i - 1] = 1;\n if (countMap[1]) countMap[1]++;\n else countMap[1] = 1;\n }\n } else if (i === 1) {\n if (countMap[1]) countMap[1]++;\n else countMap[1] = 1;\n }\n }\n console.log(Object.values(countMap).reduce((acc, c) => acc * c, 1));\n}", "function divid(a,b){\n var z = 10;\n return a/b;\n}", "static uint216(v) { return n(v, 216); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
builds model tree recursively
function _buildModelTreeRec(node) { instanceTree.enumNodeChildren(node.dbId, function (childId) { var childNode = null; if (createNodeFunc) { childNode = createNodeFunc(childId); } else { node.children = node.children || []; childNode = { dbId: childId, name: instanceTree.getNodeName(childId) }; node.children.push(childNode); } _buildModelTreeRec(childNode); }); }
[ "deserialiseTree($scope) {\n\n var models = {\n folders: {\n\n }\n };\n\n _.forEach(this.folders, _.bind(function(folder, i) {\n var folderId = folder.id;\n\n models.folders[folderId] = _.filter(this.documents, {'folderId':\n folder.id});\n\n // tree.push({\n // id: i,\n // title: folder.id,\n // nodes: _.filter(this.documents, {'folderId': folder.id})\n // });\n }, this));\n\n $scope.models = models;\n }", "build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}", "buildTree() {\n this.clear();\n\n const columnsCount = this.#sourceSettings.getColumnsCount();\n let columnIndex = 0;\n\n while (columnIndex < columnsCount) {\n const columnSettings = this.#sourceSettings.getHeaderSettings(0, columnIndex);\n const rootNode = new TreeNode();\n\n this.#rootNodes.set(columnIndex, rootNode);\n this.buildLeaves(rootNode, columnIndex, 0, columnSettings.origColspan);\n\n columnIndex += columnSettings.origColspan;\n }\n\n this.rebuildTreeIndex();\n }", "function buildTree(P, arg, path)\n{\n if (!path)\n path = \"/\";\n report(\"buildTree \"+arg);\n if (Number.isInteger(arg)) {\n report(\"atomic case \"+arg);\n var tree = getTree(P, {n: arg});\n tree.name = path+\"A\";\n return tree;\n }\n else {\n report(\"list case case \"+arg);\n path = path+\"H\";\n var children = arg;\n var nodes = [];\n for (var i=0; i<children.length; i++) {\n nodes.push(buildTree(P, children[i], path+\"/\"+i));\n }\n var tree = getTree(P, {children: nodes});\n tree.name = path;\n return tree;\n }\n}", "static mkOrderedNavItemTree(model, parent) {\n const levelItems = [];\n\n Object.getOwnPropertyNames(model).forEach(key => {\n const m = model[key];\n const link = m.link;\n const order = (link && link.order) || orderForGroup(key);\n const route = m.route;\n const lvlItem = { key, order, route, link };\n\n levelItems.push(lvlItem);\n if (!link) {\n NavSideBar.mkOrderedNavItemTree(m, lvlItem);\n }\n });\n\n levelItems.sort((i1, i2) => { return i1.order - i2.order; });\n parent.items = levelItems;\n return parent;\n }", "function createTree(){\n var colCount=0;\n head.find(selectors.row).first().find(selectors.th).each(function () {\n var c = parseInt($(this).attr(attributes.span));\n colCount += !c ? 1 : c;\n });\n\n root = new Node(undefined,colCount,0);\n var headerRows = head.find(selectors.row);\n var currParents = [root];\n // Iteration through each row\n //-------------------------------\n for ( var i = 0; i < headerRows.length; i++) {\n\n var newParents=[];\n var currentOffset = 0;\n var ths = $( headerRows[i] ).find(selectors.th);\n\n // Iterating through each th inside a row\n //---------------------------------------\n for ( var j = 0 ; j < ths.length ; j++ ){\n var colspan = $(ths[j]).attr(attributes.span);\n colspan = parseInt( !colspan ? '1' : colspan);\n var newChild = 0;\n\n // Checking which parent is the newChild parent (?)\n // ------------------------------------------------\n for( var k = 0 ; k < currParents.length ; k++){\n if ( currentOffset < currParents[k].colspanOffset + currParents[k].colspan ){\n var newChildId = 'cm-'+i+'-'+j+'-'+k ;\n $(ths[j]).addClass(currParents[k].classes);\n $(ths[j]).addClass(currParents[k].id);\n $(ths[j]).attr(attributes.id, newChildId);\n \n newChild = new Node( currParents[k], colspan, currentOffset, newChildId );\n tableNodes[newChild.id] = newChild;\n currParents[k].addChild( newChild );\n break;\n }\n }\n newParents.push(newChild);\n currentOffset += colspan;\n }\n currParents = newParents;\n }\n\n var thCursor = 0;\n var tdCursor = 0;\n var rows = body.find(selectors.row);\n var tds = body.find(selectors.td);\n /* Searches which 'parent' this cell belongs to by \n * using the values of the colspan */\n head.find(selectors.row).last().find(selectors.th).each(function () {\n var thNode = tableNodes[$(this).attr(attributes.id)];\n thCursor += thNode.colspan;\n while(tdCursor < thCursor) {\n rows.each(function () {\n $(this).children().eq(tdCursor).addClass(thNode.classes + ' ' + thNode.id);\n });\n tdCursor += $(tds[tdCursor]).attr(attributes.span) ? $(tds[tdCursor]).attr(attributes.span) : 1;\n }\n });\n\n /* Transverses the tree to collect its leaf nodes */\n var leafs=[];\n for ( var node in tableNodes){\n if ( tableNodes[node].children.length === 0){\n leafs.push(tableNodes[node]);\n }\n }\n /* Connects the last row of the header (the 'leafs') to the first row of the body */\n var firstRow = body.find(selectors.row).first();\n for ( var leaf = 0 ; leaf < leafs.length ; leaf++){\n firstRow.find('.' + leafs[leaf].id ).each(function(index){\n var newNode = new Node( leafs[leaf] , 1 , 0, leafs[leaf].id + '--' + leaf + '--' + index);\n newNode.DOMelement = $(this);\n leafs[leaf].addChild(newNode);\n tableNodes[newNode.id] = newNode;\n newNode.DOMelement.attr(attributes.id, newNode.id);\n });\n }\n }", "function buildTree(root, data, dimensions, value) {\n zeroCounts(root);\n var n = data.length,\n nd = dimensions.length;\n for (var i = 0; i < n; i++) {\n var d = data[i],\n v = +value(d, i),\n node = root;\n\n for (var j = 0; j < nd; j++) {\n var dimension = dimensions[j],\n category = d[dimension],\n children = node.children;\n node.count += v;\n node = children.hasOwnProperty(category) ? children[category]\n : children[category] = {\n children: j === nd - 1 ? null : {},\n count: 0,\n parent: node,\n dimension: dimension,\n name: category , \n class : d.class\n };\n }\n node.count += v;\n }\n return root;\n }", "static executeTaskOnModelTree(model, task) {\n\n const taskResults = []\n\n function executeTaskOnModelTreeRec(dbId) {\n\n instanceTree.enumNodeChildren(dbId,\n function (childId) {\n\n taskResults.push(task(model, childId))\n\n executeTaskOnModelTreeRec(childId)\n })\n }\n\n //get model instance tree and root component\n const instanceTree = model.getData().instanceTree\n\n const rootId = instanceTree.getRootId()\n\n executeTaskOnModelTreeRec(rootId)\n\n return taskResults\n }", "function buildTree(paths) {\n\n var i,path, subTree;\n\n subTree = tree;\n // JS5 forEach loop\n paths.forEach(function(path /*, index, originalArray */) {\n\n // Loop over each directory in the given path\n path.split('/').forEach(function(folder /*, index, originalArray */) {\n // Check to see if this folder was initialized already or not\n if (!subTree[folder] && folder !== \".\") {\n\n }\n });\n\n });\n for (i = 0; path = paths[i]; ++i) {\n var pathParts = path.split('/');\n var subObj = tree;\n for (var j = 0, folderName; folderName = pathParts[j]; ++j) {\n if (!subObj[folderName] && folderName != '.') {\n subObj[folderName] = j < pathParts.length - 1 ? {} : null;\n }\n subObj = subObj[folderName];\n }\n }\n return tree;\n }", "function buildHierarchy(data){\n var len=data.length+1; // length of items is length of merging+1\n var list=[];\n // push items\n for (var i=0;i<len;i++){\n list.push({name:i,size:1})\n }\n // push merges\n for (var i=len;i<len*2-1;i++){\n list.push({name:i,children:[]})\n }\n // reversely build their parent-children relationships\n for(var i=len-2;i>=0;i--){\n var node=data[i];\n var id1=node['id1'];\n var id2=node['id2'];\n list[i+len].children.push(list[id1])\n list[i+len].children.push(list[id2])\n }\n return d3.hierarchy(list[len*2-2]);\n }", "function buildUlTree(tree)\n{\n\tvar unordered_list = '';\n\tfor (node in tree)\n\t{\n\t\tnode = tree[node];\n\t\t\n\t\tunordered_list += '<ul style=\"margin-bottom: 0\">';\n\t\tunordered_list += println(node['title']);\n\t\tif(node['children'])\n\t\t{\n\t\t\tunordered_list += buildUlTree(node['children']);\n\t\t}\n\t\tunordered_list += '</ul>';\n\t}\n\treturn unordered_list;\n}", "function populateTree(data) {\n for (let n=0;n<data.children.length;n++) {\n populateTree(data.children[n]);\n }\n console.log(\"adding node:'\"+ data.name + \"' id:\"+data.id);\n nodeListByName[data.name]=data.id;\n}", "buildTree() {\n if (!this.drawnAnnotations.length && !this.annosToBeDrawnAsInsets.size) {\n // Remove all exlisting clusters\n this.areaClusterer.cleanUp(new KeySet());\n return;\n }\n\n // if (this.newAnno) this.tree.load(this.drawnAnnotations);\n\n this.createInsets();\n }", "visitReference_model(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function buildTreeNavigation() {\n\tvar html = '';\n\t\n\thtml += '<div class=\"tree_roles\">';\n\tfor (var i = 0; i < roles.length; i++) {\n\t\tvar role = roles[i];\n\t\t\n\t\thtml += '<div class=\"tree_role\">';\n\t\thtml += '<a href=\"' + i + '\" class=\"tree_role_link\"><img src=\"' + role.headshot + '\" class=\"tree_role_img\"/></a>';\n\t\thtml += ' <a href=\"' + i + '\" class=\"tree_role_link tree_link_text\">' + role.shortTitle + '</a>';\n\t\thtml += '</div>';\n\t\t\n\t\thtml += '<div class=\"tree_lessons\">';\n\t\tfor (var j = 0; j < role.lessons.length; j++) {\n\t\t\tvar lesson = role.lessons[j];\n\t\t\t\n\t\t\thtml += '<div class=\"tree_lesson\">';\n\t\t\thtml += '<a href=\"' + j + '\" class=\"tree_lesson_link\"><img src=\"' + lesson.icon + '\" class=\"tree_lesson_img\"/></a>';\n\t\t\thtml += ' <a href=\"' + j + '\" class=\"tree_lesson_link tree_link_text\">' + lesson.title + '</a>';\n\t\t\thtml += '</div>';\n\t\t}\n\t\thtml += '</div>';\n\t}\n\thtml += '</div>';\n\t\n\t$('#tree').html(html);\n\n\t$('#tree a.tree_role_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tshowLessons(getRole($(this).attr('href')));\n\t});\n\t\n\t$('#tree a.tree_lesson_link').bind('click', function(event) {\n\t\tevent.preventDefault();\n\t\tshowLesson(getLesson(\n\t\t\t$(this).parent().parent().prevAll('.tree_role:first').children('a.tree_role_link').attr('href'), \n\t\t\t$(this).attr('href')\n\t\t));\n\t});\n}", "function construct(nodes, parent) {\n var treeNodes = [];\n for (var i=0; i < nodes.length; i++) {\n var node = nodes[i];\n var treeNode = new TreeNode(node.data, parent);\n treeNode.children = construct(node.children, treeNode);\n treeNodes.push(treeNode);\n }\n return treeNodes;\n }", "saveTreeData(treeData) {\n var notebookFlat = {};\n notebookFlat.subnotes = {};\n notebookFlat.topLevelSubnotes = [];\n //top level subnotes are the top level objects of treeData\n for (var i = 0; i < Object.keys(treeData).length; i++) {\n notebookFlat.topLevelSubnotes.push(treeData[i].id);\n }\n\n for (i = 0; i < Object.keys(treeData).length; i++) {\n var id = treeData[i].id;\n notebookFlat.subnotes[id] = {};\n notebookFlat.subnotes[id].subtopic = treeData[i].title;\n notebookFlat.subnotes[id].note = treeData[i].subtitle;\n if (Array.isArray(treeData[i].tags) && treeData[i].tags.length > 0) {\n notebookFlat.subnotes[id].tags = treeData[i].tags;\n }\n if (Array.isArray(treeData[i].flashcards) && treeData[i].flashcards.length > 0) {\n notebookFlat.subnotes[id].flashcards = treeData[i].flashcards;\n }\n this.addChildrenToFlat(treeData[i], notebookFlat); //add info from all children (and children of children, etc)\n }\n this.setExpandedNodes(treeData); //update expanded state in app\n return notebookFlat;\n }", "function adjustTree(indexMapLeft,root){\n if(root.hasOwnProperty('children')){\n //console.log(root.data.name)\n var cL=root.children[0];\n var cR=root.children[1];\n //console.log(leavesL,leavesR)\n //console.log(bias0,bias1)\n\n var cross_result=optimizationFun_cross(cL,cR,indexMapLeft);\n if (cross_result<0){\n swapChildren(root);\n }\n else if(cross_result==0){\n if(optimizationFun_order(cL,cR,indexMapLeft)<0)\n swapChildren(root);\n }\n\n adjustTree(indexMapLeft,cL);\n adjustTree(indexMapLeft,cR);\n }\n }", "_setChildren(item, data) {\n // find all children\n const children = data.filter((d) => item.id === d.parent);\n item.children = children;\n if (item.children.length > 0) {\n item.children.forEach((child) => {\n // recursively call itself\n this._setChildren(child, data);\n });\n }\n }", "serialiseTree() {\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a unit spec with composite mark into a normal layer spec.
function normalize( // This GenericUnitSpec has any as Encoding because unit specs with composite mark can have additional encoding channels. spec, config) { var mark = mark_1.isMarkDef(spec.mark) ? spec.mark.type : spec.mark; var normalizer = normalizerRegistry[mark]; if (normalizer) { return normalizer(spec, config); } throw new Error("Unregistered composite mark " + mark); }
[ "function convertSpec(spec) {\n // get data\n let baseData = convertBaseSpec(spec.baseSpec);\n let alignType = spec.alignType ? AlignType[spec.alignType] : AlignType.Center;\n let extraOffset = spec.extraOffset ? Point.from(spec.extraOffset) : new Point(0, 0);\n let ad = {\n frameBase: baseData.base,\n nFrames: baseData.frames,\n speed: baseData.speed,\n playType: baseData.playType,\n anchor: baseData.anchor,\n alpha: baseData.alpha,\n tint: baseData.tint,\n scale: baseData.scale,\n align: {\n alignType: alignType,\n extraOffset: extraOffset,\n }\n };\n // get key. || handles undefined, null, and no key.\n let action = Action[spec.action];\n if (action == null) {\n throw new Error('Invalid Action: \"' + spec.action + '\". See enum Action for options');\n }\n let part = spec.part ? Part[spec.part] : Part.Core;\n let partID = spec.partID ? PartID[spec.partID] : PartID.Default;\n let ak = getKey(action, part, partID);\n return [ak, ad];\n }", "static replace(spec) {\n let block = !!spec.block;\n let { start, end } = getInclusive(spec);\n let startSide = block ? -200000000 /* BigBlock */ * (start ? 2 : 1) : 100000000 /* BigInline */ * (start ? -1 : 1);\n let endSide = block ? 200000000 /* BigBlock */ * (end ? 2 : 1) : 100000000 /* BigInline */ * (end ? 1 : -1);\n return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);\n }", "function transformTile(tile, extent) {\n if (tile.transformed) {\n return tile;\n }\n\n var z2 = 1 << tile.z,\n tx = tile.x,\n ty = tile.y,\n i,\n j,\n k;\n\n for (i = 0; i < tile.features.length; i++) {\n var feature = tile.features[i],\n geom = feature.geometry,\n type = feature.type;\n\n feature.geometry = [];\n\n if (type === 1) {\n for (j = 0; j < geom.length; j += 2) {\n feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));\n }\n } else {\n for (j = 0; j < geom.length; j++) {\n var ring = [];\n for (k = 0; k < geom[j].length; k += 2) {\n ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));\n }\n feature.geometry.push(ring);\n }\n }\n }\n\n tile.transformed = true;\n\n return tile;\n }", "function convertZoneSpec(zoneSpec) {\n // built up set of zone types\n let zts = new Set();\n if (zoneSpec.zoneTypes != null) {\n for (let rzt of zoneSpec.zoneTypes) {\n let zt = ZoneType[rzt];\n if (zt == null) {\n throw new Error('Unknown ZoneType: \"' + rzt + '\".');\n }\n zts.add(zt);\n }\n }\n // default active to true\n let active = true;\n if (zoneSpec.active != null) {\n active = zoneSpec.active;\n }\n return {\n zoneTypes: zts,\n active: active,\n gateID: zoneSpec.gateID || null,\n instructionID: zoneSpec.instructionID || null,\n controlID: zoneSpec.controlID || null,\n };\n }", "static widget(spec) {\n let side = Math.max(-10000, Math.min(10000, spec.side || 0)),\n block = !!spec.block\n side +=\n block && !spec.inlineOrder\n ? side > 0\n ? 300000000 /* BlockAfter */\n : -400000000 /* BlockBefore */\n : side > 0\n ? 100000000 /* InlineAfter */\n : -100000000 /* InlineBefore */\n return new PointDecoration(\n spec,\n side,\n side,\n block,\n spec.widget || null,\n false\n )\n }", "function applyTransformationRuleFormattingPrefix (diff) {\n let transformedDiff = []\n\n let isNewline = true\n let newlineString = '\\n'\n\n // iterate the input tokens to create the intermediate representation\n diff.forEach((currentBlock) => {\n if (isNewline && (currentBlock.added || currentBlock.removed)) {\n let match = currentBlock.value.match(MARKDOWN_PREFIX)\n if (match) {\n let preBlock = {value: match[0]}\n let postBlock = {added: currentBlock.added, removed: currentBlock.removed, value: currentBlock.value.substring(match[0].length)}\n\n if (currentBlock.added) {\n let newlineBlock = {value: newlineString}\n transformedDiff.push(newlineBlock)\n }\n transformedDiff.push(preBlock)\n transformedDiff.push(postBlock)\n } else {\n transformedDiff.push(currentBlock)\n }\n } else {\n transformedDiff.push(currentBlock)\n isNewline = NEWLINE_SUFFIX.test(currentBlock.value)\n if (isNewline) {\n newlineString = currentBlock.value.match(NEWLINE_SUFFIX)[0]\n }\n }\n })\n\n return transformedDiff\n}", "function makeLayerMapBox(name, spec)\n{\n\tvar urlTemplate =\n\t\t \"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png\"\n\t\t+ \"?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXV\"\n\t\t+ \"ycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw\";\n\tvar attr =\n\t\t \"Map data &copy; <a href='http://openstreetmap.org'>\"\n\t\t+ \"OpenStreetMap</a> contributors, \"\n\t\t+ \"<a href='http://creativecommons.org/licenses/by-sa/2.0/'>\"\n\t\t+ \"CC-BY-SA</a>, \"\n\t\t+ \"Imagery © <a href='http://mapbox.com'>Mapbox</a>\";\n\tvar errorTileUrl =\n\t\t\"https://upload.wikimedia.org/wikipedia/commons/e/e0/SNice.svg\";\n\tvar layer =\n\t\tL.tileLayer(urlTemplate, {\n\t\t\t\tminZoom: 10,\n\t\t\t\tmaxZoom: 18,\n\t\t\t\terrorTileUrl: errorTileUrl,\n\t\t\t\tid: spec,\n\t\t\t\tattribution: attr\n\t\t});\n\treturn layer;\n}", "static line(spec) {\n return new LineDecoration(spec);\n }", "function normalizeStyle(style) {\n if (!style) {\n return null;\n }\n\n if (typeof style === 'string') {\n return style;\n }\n\n if (style.toJS) {\n style = style.toJS();\n }\n\n var layerIndex = style.layers.reduce(function (accum, current) {\n return Object.assign(accum, (0, _defineProperty2.default)({}, current.id, current));\n }, {});\n style.layers = style.layers.map(function (layer) {\n layer = Object.assign({}, layer); // Breaks style diffing :(\n\n delete layer.interactive;\n var layerRef = layerIndex[layer.ref]; // Style diffing doesn't work with refs so expand them out manually before diffing.\n\n if (layerRef) {\n delete layer.ref;\n\n if (layerRef.type !== undefined) {\n layer.type = layerRef.type;\n }\n\n if (layerRef.source !== undefined) {\n layer.source = layerRef.source;\n }\n\n if (layerRef['source-layer'] !== undefined) {\n layer['source-layer'] = layerRef['source-layer'];\n }\n\n if (layerRef.minzoom !== undefined) {\n layer.minzoom = layerRef.minzoom;\n }\n\n if (layerRef.maxzoom !== undefined) {\n layer.maxzoom = layerRef.maxzoom;\n }\n\n if (layerRef.filter !== undefined) {\n layer.filter = layerRef.filter;\n }\n\n if (layerRef.layout !== undefined) {\n layer.layout = layer.layout || {};\n layer.layout = Object.assign({}, layer.layout, layerRef.layout);\n }\n }\n\n return layer;\n });\n return style;\n}", "removeEmulationPreventionByte(nalUnit) {\n let searchPos = 0;\n let removeBytePositions = [];\n while (true) {\n let emulPos = Bits.searchBytesInArray(nalUnit, [0x00, 0x00, 0x03], searchPos);\n if (emulPos === -1) {\n break;\n }\n removeBytePositions.push(emulPos + 2);\n searchPos = emulPos + 3;\n }\n if (removeBytePositions.length > 0) {\n let newBuf = new Buffer(nalUnit.length - removeBytePositions.length);\n let currentSrcPos = 0;\n for (let i = 0; i < removeBytePositions.length; i++) {\n // srcBuf.copy(destBuf, destStart, srcStart, srcEnd)\n let pos = removeBytePositions[i];\n nalUnit.copy(newBuf, currentSrcPos - i, currentSrcPos, pos);\n currentSrcPos = pos + 1;\n }\n if (currentSrcPos < nalUnit.length) {\n nalUnit.copy(newBuf, currentSrcPos - removeBytePositions.length,\n currentSrcPos, nalUnit.length);\n }\n nalUnit = newBuf;\n }\n return nalUnit;\n }", "setUnit(unit) {\r\n this.unit = unit;\r\n }", "function expandAliases(unit) {\n\t\tfor (var key in unit) {\n\t\t\tvar alias = unit[key].alias, i = alias.length;\n\t\t\twhile (i--) {\n\t\t\t\tunit[alias[i]] = unit[key];\n\t\t\t}\n\t\t}\n\t}", "renderLayers() {\n const {data, scale, iconAtlas, iconMapping} = this.state;\n\n const {\n getPosition,\n getColor,\n getSize,\n getAngle,\n getTextAnchor,\n getAlignmentBaseline,\n getPixelOffset,\n fp64,\n billboard,\n sdf,\n sizeScale,\n sizeUnits,\n sizeMinPixels,\n sizeMaxPixels,\n transitions,\n updateTriggers\n } = this.props;\n\n // Need to use modified IconLayer in TextLayer\n const SubLayerClass = this.getSubLayerClass('characters', MyMultiIconLayer);\n\n return new SubLayerClass(\n {\n sdf,\n iconAtlas,\n iconMapping,\n\n getPosition: d => getPosition(d.object),\n getStartPosition: d => d.object.source.coordinates,\n getEndPosition: d => d.object.target.coordinates,\n\n getColor: this._getAccessor(getColor),\n getSize: this._getAccessor(getSize),\n getAngle: this._getAccessor(getAngle),\n getAnchorX: this.getAnchorXFromTextAnchor(getTextAnchor),\n getAnchorY: this.getAnchorYFromAlignmentBaseline(getAlignmentBaseline),\n getPixelOffset: this._getAccessor(getPixelOffset),\n fp64,\n billboard,\n sizeScale: sizeScale * scale,\n sizeUnits,\n sizeMinPixels: sizeMinPixels * scale,\n sizeMaxPixels: sizeMaxPixels * scale,\n\n transitions: transitions && {\n getPosition: transitions.getPosition,\n getAngle: transitions.getAngle,\n getColor: transitions.getColor,\n getSize: transitions.getSize,\n getPixelOffset: updateTriggers.getPixelOffset\n }\n },\n this.getSubLayerProps({\n id: 'characters',\n updateTriggers: {\n getPosition: updateTriggers.getPosition,\n getAngle: updateTriggers.getAngle,\n getColor: updateTriggers.getColor,\n getSize: updateTriggers.getSize,\n getPixelOffset: updateTriggers.getPixelOffset,\n getAnchorX: updateTriggers.getTextAnchor,\n getAnchorY: updateTriggers.getAlignmentBaseline\n }\n }),\n {\n data,\n getIcon: d => d.text,\n getShiftInQueue: d => this.getLetterOffset(d),\n getLengthOfQueue: d => this.getTextLength(d)\n }\n );\n }", "function applyTransformationRuleMultilineDelThenIns (diff) {\n let transformedDiff = []\n\n const B_ADDED = 'added'\n const B_REMOVED = 'removed'\n const B_SAME = 'same'\n\n let previousBlockType = null\n let currentBlockType = null\n let previousBlockWasMultiline = false\n let currentBlockIsMultiline = false\n\n // iterate the input tokens to create the intermediate representation\n diff.forEach((currentBlock) => {\n previousBlockType = currentBlockType\n previousBlockWasMultiline = currentBlockIsMultiline\n currentBlockType = (currentBlock.added ? B_ADDED : (currentBlock.removed ? B_REMOVED : B_SAME))\n currentBlockIsMultiline = isMultilineDiffBlock(currentBlock)\n\n // transform rule 1 applys when:\n // the previous block was a del and had multiple lines\n // the current block is an ins\n if (previousBlockType === B_REMOVED && currentBlockType === B_ADDED && previousBlockWasMultiline) {\n // split the first line from the current block\n let currentBlockSplit = splitMultilineDiffBlock(currentBlock)\n\n // pop the previous diff entry\n let previousBlock = transformedDiff.pop()\n\n // split the first line from the previous block\n let previousBlockSplit = splitMultilineDiffBlock(previousBlock)\n\n // now add the blocks back, interleaving del and ins blocks\n for (let i = 0; i < Math.max(previousBlockSplit.length, currentBlockSplit.length); i++) {\n if (i < previousBlockSplit.length) {\n transformedDiff.push(previousBlockSplit[i])\n }\n if (i < currentBlockSplit.length) { transformedDiff.push(currentBlockSplit[i]) }\n }\n } else {\n // otherwise, we just add the current block to the transformed list\n transformedDiff.push(currentBlock)\n }\n })\n\n return transformedDiff\n}", "function setMouseAttributesLruUnit(newSpan, unit) {\n\tnewSpan.setAttribute('onmouseout', 'return lruMouseOut('\n\t\t\t+ unit.id + ', event)');\n\tnewSpan.setAttribute('onmouseover', 'return lruMouseOver('\n\t\t\t+ unit.id + ', event)');\n\tnewSpan.setAttribute('onmousedown', 'return lruMouseDown('\n\t\t\t+ unit.id +')');\n\tnewSpan.setAttribute('onmouseup', 'return lruMouseUp('\n\t\t\t+ unit.id + ')');\n\treturn newSpan;\n}", "function PreprocessSpec () {\n var testFileWithoutJSDoc, testFileWithJSDoc, testFileWithJSDocTransformed;\n\n return {\n setUp: function () {\n testFileWithoutJSDoc = [\n \"(function() {\",\n \" // normal comment\",\n \" var x = 1;\",\n \" /* long description\",\n \" * test\",\n \" */\",\n \"}());\"\n ].join(\"\\n\");\n\n testFileWithJSDoc = [\n \"(function() {\",\n \" /** long description\",\n \" * test\",\n \" */\",\n \" var x = 2;\",\n \"}());\"\n ].join(\"\\n\");\n\n testFileWithJSDocTransformed = [\n \"(function() {\",\n \"applicationContext.comment(\\\"long description\\\");\",\n \"applicationContext.comment(\\\"test\\\");\",\n \"applicationContext.comment(\\\"\\\");\",\n \" var x = 2;\",\n \"}());\"\n ].join(\"\\n\");\n },\n\n testDoesntChangeFileWithoutJSDocComments: function () {\n assertEqual(preprocess(testFileWithoutJSDoc), testFileWithoutJSDoc);\n },\n\n testTransformsFileWithJSDocComments: function () {\n assertEqual(preprocess(testFileWithJSDoc), testFileWithJSDocTransformed);\n }\n };\n}", "addUnits(e) {\n const unit = { shelterUnit: { unitSize: e.shelterUnit.unitSize, unitName: e.shelterUnit.unitName },\n shelters: { shelterName: e.shelters.shelterName },\n organizations: { orgName: e.organizations.orgName } };\n\n ManagerActions.addUnits(unit);\n }", "unitsInitCustom()\n\t{\n\t\t//\n\t\t// Call parent method.\n\t\t//\n\t\tsuper.unitsInitCustom();\n\t\t\n\t\t//\n\t\t// Instantiate with wrong type of edge.\n\t\t// Assert it fails.\n\t\t//\n\t\tthis.customUnitSet(\n\t\t\t'instantiateWrongEdgeType',\n\t\t\t\"Instantiate class with wrong edge type selector:\",\n\t\t\tthis.test_classes.base,\n\t\t\tnull,\n\t\t\ttrue\n\t\t);\n\t\t\n\t\t//\n\t\t// Validate edge key.\n\t\t// Assert that removing a constrained document fails.\n\t\t//\n\t\tthis.customUnitSet(\n\t\t\t'customEdgeKey',\n\t\t\t\"Validate edge key\",\n\t\t\tthis.test_classes.base,\n\t\t\tnull,\n\t\t\ttrue\n\t\t);\n\t\t\n\t}", "function applyTransformationRuleBreakUpDelIns (diff) {\n let transformedDiff = []\n\n const B_ADDED = 'added'\n const B_REMOVED = 'removed'\n const B_SAME = 'same'\n let blockType = null\n let blockIsMultiline = false\n\n // iterate the input tokens to create the intermediate representation\n diff.forEach((block) => {\n blockType = (block.added ? B_ADDED : (block.removed ? B_REMOVED : B_SAME))\n blockIsMultiline = isMultilineDiffBlock(block)\n\n // transform rule applys when:\n // the current block is an ins or del and is multiline\n if ((blockType === B_REMOVED || blockType === B_ADDED) && blockIsMultiline) {\n // split the first line from the current block\n let blockSplit = splitMultilineDiffBlock(block)\n\n blockSplit.forEach(blockSplitLine => transformedDiff.push(blockSplitLine))\n } else {\n // otherwise, we just add the current block to the transformed list\n transformedDiff.push(block)\n }\n })\n\n return transformedDiff\n}", "function convertUnitList(unitList) {\n let batches = {}\n\n for (let unit of unitList) {\n if (!batches[unit.OwnerId]) batches[unit.OwnerId] = []\n batches[unit.OwnerId].push(unit)\n }\n\n return batches\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Includes the JavaScript file located at 'jsFilePath'
function includeJs (jsFilePath) { var js = document.createElement("script"); js.type = "text/javascript"; js.src = jsFilePath; document.body.appendChild(js); }
[ "function includeJS(file_path){ \r\n var j = document.createElement(\"script\");\r\n j.type = \"text/javascript\";\r\n j.onload = function(){\r\n lib_loaded(file_path);\r\n };\r\n j.src = file_path;\r\n document.getElementsByTagName('head')[0].appendChild(j); \r\n}", "function addJs( src, document )\n{\n e = document.createElement(\"script\");\n e.async = true;\n e.type = \"text/javascript\";\n e.src = src;\n document.body.appendChild(e);\n}", "function js() {\n return gulp.src(config.paths.jsFiles)\n .pipe(concat('bundle.min.js'))\n .pipe(uglify())\n .pipe(gulp.dest('./_src/assets/js'));\n }", "function s_hp_includeConditional(whenCondition,matchStr,destServer,destFile) {\r\n\tif(whenCondition!=null && matchStr!=null) {\r\n\t\tv=whenCondition.split(\",\");h_u = matchStr;\r\n\t\tfor(i=0;i<v.length;i++) {if(h_u.indexOf(v[i]) != -1) {\r\n\t\t\ts_hp_includeJavaScriptFile(destServer,destFile);\r\n\t\t} }\r\n\t}\r\n}", "function getAllIncludedJS(foldername, filenames) {\n // Default binding\n let JSfilenames = ['assert.js', 'sta.js'];\n filenames.forEach(filename =>\n JSfilenames = JSfilenames.concat(getIncludedJS(foldername, filename)));\n //Deduplication\n JSfilenames = JSfilenames.filter((item, pos) => JSfilenames.indexOf(item) === pos);\n let harnessfoldername = `${process.env.JISET_HOME}/tests/test262/harness/`;\n let includedcontents = \"\";\n JSfilenames.forEach(filename =>\n includedcontents += getFileContent(harnessfoldername, filename))\n return includedcontents\n}", "function loadjscssfile(filename, filetype){\r\n if (filetype==\"js\"){ //if filename is a external JavaScript file\r\n var fileref=document.createElement('script')\r\n fileref.setAttribute(\"type\",\"text/javascript\")\r\n fileref.setAttribute(\"src\", filename)\r\n }\r\n else if (filetype==\"css\"){ //if filename is an external CSS file\r\n var fileref=document.createElement(\"link\")\r\n fileref.setAttribute(\"rel\", \"stylesheet\")\r\n fileref.setAttribute(\"type\", \"text/css\")\r\n fileref.setAttribute(\"href\", filename)\r\n }\r\n if (typeof fileref!=\"undefined\")\r\n document.getElementsByTagName(\"head\")[0].appendChild(fileref)\r\n}", "addLayoutScriptsAndStyles() {\n this.asset.layoutScript = path.join(this.pageConfig.layoutsAssetPath, this.layout, 'scripts.js');\n this.asset.layoutStyle = path.join(this.pageConfig.layoutsAssetPath, this.layout, 'styles.css');\n this.includedFiles.add(\n path.join(this.pageConfig.rootPath, LAYOUT_FOLDER_PATH, this.layout, 'scripts.js'));\n this.includedFiles.add(\n path.join(this.pageConfig.rootPath, LAYOUT_FOLDER_PATH, this.layout, 'styles.css'));\n }", "isScriptFile(filePath) {\n return ['.js', '.json'].includes(path_1.extname(filePath));\n }", "function jsTask() {\n return src(files.jsPath)\n .pipe(concat(\"all.js\"))\n .pipe(minify())\n .pipe(dest(\"dist\"));\n}", "function withExtJs(file) {\n if (file.match(/\\.js$/)) {\n return file;\n } else {\n return file + '.js';\n }\n}", "function jsInline() {\n $.fancyLog(\"-> Copying inline js\");\n return gulp.src(pkg.globs.inlineJs)\n .pipe($.plumber({errorHandler: onError}))\n .pipe($.if([\"*.js\", \"!*.min.js\"],\n $.newer({dest: pkg.paths.templates + \"_inlinejs\", ext: \".min.js\"}),\n $.newer({dest: pkg.paths.templates + \"_inlinejs\"})\n ))\n .pipe($.if([\"*.js\", \"!*.min.js\"],\n $.uglify()\n ))\n .pipe($.if([\"*.js\", \"!*.min.js\"],\n $.rename({suffix: \".min\"})\n ))\n .pipe($.size({gzip: true, showFiles: true}))\n .pipe(gulp.dest(pkg.paths.templates + \"_inlinejs\"))\n .pipe($.filter(\"**/*.js\"))\n // Add browsersync stream pipe after compilation\n .pipe($.browserSync.stream());\n}", "function vendorJS() {\n\treturn src(config.vendorJS.src)\n\t\t.pipe(dest(config.vendorJS.dest));\n}", "function fileincludeTask(cb) {\n return src(['./src/*.html'])\n .pipe(fileinclude({\n prefix: '@@',\n basepath: '@file'\n }))\n .pipe(gulp.dest('./public'))\n .pipe(browserSync.stream());\n cb();\n}", "function injectJsSrc(src, attrs) {\r\n let scriptElem = document.createElement('script');\r\n if (typeof attrs === 'undefined') attrs = [];\r\n\r\n scriptElem.src = src;\r\n scriptElem.type = 'application/javascript';\r\n\r\n for (let i = 0; i < attrs.length; i += 1) {\r\n let attr = attrs[i];\r\n scriptElem.setAttribute(attr[0], attr[1]);\r\n }\r\n\r\n document.head.appendChild(scriptElem);\r\n document.head.removeChild(scriptElem);\r\n}", "function javascriptExternal() {\n const installs = bowerData.appInstalls;\n const unminified = installs.js.map(item => `bower_components/${item}`);\n const minified = installs.jsMin.map(item => `bower_components/${item}`);\n\n const minifiedStream = gulp.src(minified);\n const externalStream = gulp.src('app/js/ext/**/*.js');\n const unminifiedStream = gulp.src(unminified)\n .pipe(gulpif(isProduction, uglify()));\n\n return merge(minifiedStream, unminifiedStream, externalStream)\n .pipe(concat('bower.js', { newLine: '\\n' }))\n .pipe(getStreamOutput('js'));\n}", "function js() {\n return new Promise(function (resolve, reject) {\n let b = browserify();\n b.add(config.jsIn);\n b.transform('babelify');\n // todo: minify\n var dest = fs.createWriteStream(config.jsOut);\n b.bundle().pipe(dest);\n console.log('bundled javascript');\n resolve();\n });\n}", "function loadScript(directoryName, filesArr) {\n\n for (var i = 0; i < filesArr.length; i++) {\n\n w.load(\"modules/\" + directoryName + \"/\" + filesArr[i] + '.js');\n }\n }", "function dependOn(dependency, callback) {\n var path = dependencies[dependency];\n if (/:\\/\\//.exec(path) !== null) {\n path = window.location.href + path;\n }\n var scripts = Array.prototype.slice.apply(document.getElementsByTagName('script'));\n if (!scripts.some(function(e) {return e.src === path;})) {\n var script = document.createElement('script');\n script.onload = callback();\n script.src = path;\n document.body.appendChild(script);\n } else {\n callback();\n }\n }", "function jsSite() {\n\treturn gulp.src(appFiles.siteScripts)\n\t\t.pipe(sourcemaps.init())\n\t\t.pipe(concat(appFiles.scriptFile))\n\t\t.pipe(sourcemaps.write())\n\t\t.pipe(isProduction ? uglify() : gutil.noop() )\n\t\t.pipe(gulp.dest(paths.scripts.dest));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
findUnconnectedPreds(label) Returns the position of the excluded predicate or 1 if it is not found. label = predication label to compare against the unconnectedPreds list for the current summarization schema.
function findUnconnectedPreds(label) { for (var j = 0; j < selection.summarization.unconnectedPreds.length; j++) { if (selection.summarization.unconnectedPreds[j] == label) { return j; } } return -1; }
[ "function getAppearedLabels(){\n\tvar arr = [] \n\tfor (var i = 0; i<labels.length; i++) {\n\t\tarr.push(labels[i].name.label);\n\t}\n\tvar appearedLabelsUnsort = arr.filter( onlyUnique );\n\t// manually add \"treeSphere\" and \"treeCube\" as their names are saved as \"vegetation\"\n\tappearedLabelsUnsort.push('treeSphere');\n\tappearedLabelsUnsort.push('treeCube');\n\n\tappearedLabels = [];\n\tfor (var label in category) {\n\t\tif (appearedLabelsUnsort.indexOf(label)>-1){\n\t\t\tappearedLabels.push(label);\n\t\t}\n\t}\n}", "function isObligatoryLabel(label){\t\r\n\treturn obligatoryDataElementsLabel.includes(label);\r\n}", "search_dir_label_helper(resultset, dir, label) {\n\tvar ans = {};\n\tfor(var n in resultset) {\n\t if(!(n in this.index_edge_label)) {\n\t\tcontinue;\n\t }\n\t if(label in this.index_edge_label[n][dir]) {\n\t\t// In this case, we get all outbound edges of the specified label\n\t\tfor(var nodeid in this.index_edge_label[n][dir][label]) {\n\t\t if(!(nodeid in resultset)) { continue; }\n\t\t ans[nodeid] = true;\n\t\t}\n\t }\n\t}\n\treturn ans;\n }", "function findDominant(predicate) {\n\n\tfor (var i = 0; i < selection.summarization.dominantPreds.length; i++) {\n\t\tif (selection.summarization.dominantPreds[i] == predicate) return i;\n\t}\n\treturn -1;\n}", "function findLabel() {\n var numbers = [];\n var index = 0;\n $(\"tbody\").find(\"tr\").each(function () {\n numbers[index] = parseInt($(this).find(\"td:first\").text());\n index++;\n });\n numbers.sort();\n var number = numbers.length + 1;\n for(var i =0; i < numbers.length; i++){\n if(i+1 !=numbers[i]){\n return i+1;\n }\n }\n return i+1;\n}", "move(states, label) {\n return states.reduce((nextStates, state)=> state.edges\n .filter(e => e.label.equals(label))\n .map(e => this.getStateByNum(e.dest, `State ${e.dest}(linked from ${state.num}) not found`))\n .__dfajs_concatTo(nextStates)\n , []).__dfajs_uniq()\n }", "getMissingFeatureIndex() {\n return this.values.findIndex(value => isNaN(value));\n }", "findInvalidSlot(addr) {\n var entries = this.sets[addr.idx];\n\n for(var i = 0; i < entries.length; i++) {\n if(entries[i].valid == false) {\n return i;\n }\n }\n\n return null;\n }", "function hideLabel() { \n marker.set(\"labelVisible\", false); \n }", "function displayUnexcavatedLabels(){\n\t\tvar i;\n\t\tvar currentCenter;\n\t\tvar currentCoordinatesList;\n\t\tvar displayTheseUnexAreas = [];\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[0]);\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[1]);\n\t\tdisplayTheseUnexAreas.push(unexcavatedCentersList[6]);\n\t\tdisplayTheseUnexAreas=adjustUnexcavatedCenters(displayTheseUnexAreas);\n\t\tfor(i=0; i<displayTheseUnexAreas.length; i++){\n\t\t\tcurrentCenter=displayTheseUnexAreas[i];\n\t\t\tif(currentCenter!=null){\n\t\t\t\tshowALabelOnMap(currentCenter, \"unexcavated\", \"small\", \"unexcavated\");\n\t\t\t}\n\t\t}\n\n\t}", "function nppsSearch(p, npps) {\n\tvar i, j;\n\tfor (i = 0; i < npps.length; i++) {\n\t\tfor (j = 0; j < npps[i].blocks.length; j++) {\n\t\t\tif (npps[i].blocks[j] === p) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t}\n\treturn -1;\n}", "function getPlacementNoPair(arr) {\n\tlet sets = subset(arr, 2);\n\tlet index;\n\tif (arr.length === 1) {\n\t\tWIN_COMBINATIONS.forEach(combo => {\n\t\t\tif (combo.includes(arr[0]) && compareEvery(combo, arr[0])) {\n\t\t\t\tindex = combo.filter(el => el !== arr[0]);\n\t\t\t}\n\t\t});\n\t} else {\n\t\tsets.forEach(set => {\n\t\t\tlet x = set[0];\n\t\t\tlet y = set[1] || undefined;\n\t\t\tWIN_COMBINATIONS.forEach(combo => {\n\t\t\t\tif (\n\t\t\t\t\t(combo.includes(x) || combo.includes(y)) &&\n\t\t\t\t\tcompareEvery(combo, playerMadeMoves)\n\t\t\t\t) {\n\t\t\t\t\t// console.log(combo);\n\t\t\t\t\tindex = combo.filter(num => num !== x && num !== y)[0];\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\treturn index;\n}", "function removeInsulaLabels(){\n\t\tvar i=0;\n\t\tfor(i;i<insulaMarkersList.length;i++){\n\t\t\tpompeiiMap.removeLayer(insulaMarkersList[i]);\n\t\t}\n\t}", "function negPeek(f){return function(s,p){var cp,ret\n cp=s.checkpoint()\n ret=f(s,p)\n s.restore(cp)\n return !ret}}", "function inactiveLabel(label) {\n d3.select(`.${label}`).classed(\"active\", false).classed(\"inactive\", true);\n}", "deleteAllNodesWithLabel(label){\n let task = session.run(`MATCH (N:${label}) DETACH DELETE N`);\n return task;\n }", "function take_DASH_while(pred, coll) {\n let ret = list();\n for (let ____coll = coll, ____index = 0, ____end = count(____coll), ____break = false; ((!____break) && (____index < ____end)); ____index = (____index + 1)) {\n let c = ____coll[____index];\n if (pred(c)) {\n ret.push(c);\n } else {\n (\n ____break = true)\n }\n }\n return ret;\n}", "function remove(xs, pred) /* forall<a> (xs : list<a>, pred : (a) -> bool) -> list<a> */ {\n return filter(xs, function(x /* 23638 */ ) {\n return !((pred(x)));\n });\n}", "function clickClearWarnings(label) {\n $(label + ' #input').validate().resetForm()\n $(\"div.ui-tooltip\").remove();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The sequenceid is incremented with each packet and may wrap around. It starts at 0 and is reset to 0 when a new command begins in the Command Phase.
_resetSequenceId() { this.sequenceId = 0; this.compressedSequenceId = 0; }
[ "nextMessageId() {\n this.messageId += 1;\n return this.messageId;\n }", "function sequenceNo(frame) {\n return frame.attr(\"id\");\n}", "function getNextPID() {\n DropballEntityPIDInc = DropballEntityPIDInc + 1;\n return DropballEntityPIDInc;\n }", "getID() {\r\n return this.id.toString().padStart(3, '0');\r\n }", "#nextId() {\n const nextId = \"id_\" + this.#currentId;\n this.#currentId++;\n return nextId;\n }", "nextId(position){\n position+=1;\n if(this.machine.length >position){\n return this.machine[position].activity_id\n }\n return -1\n }", "function uniqueId() {\n return id++;\n }", "generateId() {\n const newId = `dirId-${Directory.nextId}`;\n Directory.nextId++;\n return newId;\n }", "sendNextCommand() {\n\t\tif (this.commandQueue.length > 0) {\n\t\t\tthis.socket.send(this.commandQueue[0]);\n\t\t\tthis.cts = false;\n\t\t}\n\t\telse {\n\t\t\tthis.cts = true;\n\t\t}\n\t}", "function sendCommandsInSequence(socket, roomId, eventTotal, commandName, commandPayload, done) {\n const testRunUniqueId = 'serverPerformanceTest_' + uuid();\n\n console.log(`--- Starting ${testRunUniqueId} with \"${commandName}\", until ${eventTotal} events are received --`);\n\n var isDone = false;\n var eventCount = 0;\n var commandCount = 0;\n\n console.time(testRunUniqueId);\n send();\n\n socket.on('event', () => {\n eventCount++;\n\n if (isDone) {\n // some commands trigger multiple events.\n // make sure to only call \"done\" and \"console.timeEnd\" once per testrun!\n return;\n }\n\n if (eventCount < eventTotal) {\n send();\n } else {\n isDone = true;\n console.log(`Performance test done. sent ${commandCount} commands. Received ${eventCount} events.`);\n console.timeEnd(testRunUniqueId);\n console.log('\\n---');\n done();\n }\n });\n\n function send() {\n commandCount++;\n socket.emit('command', {\n id: uuid(),\n roomId: roomId,\n name: commandName,\n payload: commandPayload\n });\n }\n\n }", "function getNextGameID() {\n\n gameID++;\n\n const reply = { \"id\": gameID };\n\n return reply;\n\n}", "_requestUniqueId() {\n if (uniqueRequestId >= MAX_REQUEST_ID) {\n uniqueRequestId = 0;\n }\n return uniqueRequestId++;\n }", "arrangeId() {\n const rootNode = this.parent.contentDom.documentElement;\n let id = SlideSet.MIN_ID;\n for (let { slideId } of this.selfElement.items()) {\n const oriId = slideId.id;\n const relElements = rootNode.xpathSelect(`.//*[local-name(.)='sldId' and @id='${oriId}']`);\n for (let relIdx in relElements) {\n relElements[relIdx].setAttribute(\"id\", id);\n }\n id++;\n }\n this[$slideAvalidID] = id;\n }", "sortSequence () {\n this.sequence.sort(function (a, b) {\n return a.firstStart - b.firstStart;\n });\n }", "withSequenceNumber(t) {\n return new si(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);\n }", "function addSequenceTnel(fileData) { //similar to above just avoid lines which does not have any data\n let lines = fileData.split(\"\\n\"); \n let count = 1; \n for(let i = 0; i < lines.length; i++) { \n if(lines[i] != \"\") { \n console.log(count + \". \" + lines[i]); \n count++; \n }\n else { \n console.log(\"\"); \n }\n } \n}", "function generateMove() {\n var nextMove = Math.floor(Math.random() * 4);\n sequence.push(nextMove);\n }", "function nextCommand() {\n\t\t\tvar command = header.readByte();\n\n\t\t\t// Short waits\n\t\t\tif((command & 0xF0) == 0x70) {\n\t\t\t\treturn (command & 0x0F);\n\t\t\t}\n\n\t\t\t// Everything else\n\t\t\tswitch(command) {\n\t\t\t\tcase 0x4f:\t// GameGear PSG stereo register\n\t\t\t\t\theader.skipByte();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x50:\t// PSG\n\t\t\t\t\tpsg.write(header.readByte());\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x51:\t// YM2413\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x52:\t// YM2612 port 0\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x53:\t// YM2612 port 1\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x54:\t// YM2151\n\t\t\t\t\theader.skipShort();\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0x61:\t// Wait a number of samples\n\t\t\t\t\treturn header.readShort();\n\t\t\t\tcase 0x62:\t// Wait one frame (NTSC - 1/60th of a second)\n\t\t\t\t\treturn 735;\n\t\t\t\tcase 0x63:\t// Wait one frame (PAL - 1/50th of a second)\n\t\t\t\t\treturn 882;\n\t\t\t\tcase 0x66:\t// END\n\t\t\t\t\tif(settings.loop_samples > 0) {\n\t\t\t\t\t\theader.seek(settings.loop_offset);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisPlaying = false;\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t\tcase 0xe0: // Seek\n\t\t\t\t\theader.skipLong();\n\t\t\t\t\treturn 0;\n\t\t\t\tdefault:\n\t\t\t\t\tif((command > 0x30) && (command <= 0x4e)) {\n\t\t\t\t\t\theader.skipByte();\n\t\t\t\t\t} else if((command > 0x55) && (command <= 0x5f)) {\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xa0) && (command <= 0xbf)) {\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xc0) && (command <= 0xdf)) {\n\t\t\t\t\t\theader.skipByte();\n\t\t\t\t\t\theader.skipShort();\n\t\t\t\t\t} else if((command > 0xe1) && (command <= 0xff)) {\n\t\t\t\t\t\theader.skipLong();\n\t\t\t\t\t}\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t}", "function updateCRSequenceGenerator(center_id) {\n\tlet qryUpdateSqnc = '';\n\n\tqryUpdateSqnc = `\n\t\tupdate financialyear set cr_note_seq = cr_note_seq + 1 where \n\t\tcenter_id = '${center_id}' and \n\t\tCURDATE() between str_to_date(startdate, '%d-%m-%Y') and str_to_date(enddate, '%d-%m-%Y') `;\n\n\treturn new Promise(function (resolve, reject) {\n\t\tpool.query(qryUpdateSqnc, function (err, data) {\n\t\t\tif (err) {\n\t\t\t\treject(err);\n\t\t\t}\n\t\t\tresolve(data);\n\t\t});\n\t});\n}", "function StickyIdMaker() {\n this.highId = 0;\n this.spare = [];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a random p5 color
static randomP5Color(hasRandomAlpha: boolean = false): $FlowIgnore { return w.color(Color.randomRGBATuple(hasRandomAlpha)); }
[ "function randomColorGenerator() {\n\t\treturn Math.floor(Math.random() * backgroundColors.length);\n}", "static Random() {\n return new Color3(Math.random(), Math.random(), Math.random());\n }", "function colorTarget() {\n let colorPicked = Math.floor(Math.random() * colors.length);\n return colors[colorPicked];\n}", "function circleColor() {\n red = restrict(red + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n green = restrict(green + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n blue = restrict(blue + (random(50) * (round(random()) * 2 - 1)), 0, 255);\n fill(red, green, blue);\n}", "function randomColour() {\r\n pattern.push(colours[Math.floor(Math.random() * 4)]);\r\n animations(pattern);\r\n levelAndScoreCount();\r\n\r\n}", "function rndColor() {\n var iRed = Math.floor((Math.random() * 255) + 1);\n var iGreen = Math.floor((Math.random() * 255) + 1);\n var iBlue = Math.floor((Math.random() * 255) + 1);\n\n $(\"#red\").slider(\"value\", iRed);\n $(\"#green\").slider(\"value\", iGreen);\n $(\"#blue\").slider(\"value\", iBlue);\n }", "static fromP5Color(p5Color: $FlowIgnore): Color {\n return new Color(w.red(p5Color), w.green(p5Color), w.blue(p5Color), w.alpha(p5Color));\n }", "function randomColor(){\n\tlet selectedColor = content[Math.floor(Math.random()*(content.length-1))];\n\tlet line = selectedColor.split(',');\n\tlet hexCode = line[1].trim();\n\t// console.log(hexCode);\n\tlet red = hexCode.slice(1,3);\n\tlet green = hexCode.slice(3,5);\n\tlet blue = hexCode.slice(5);\n\n\t// console.log(red + 'red' + green + 'green' + blue + 'blue');\n\tred = parseInt(\"\"+red, 16);\n\tgreen = parseInt(\"\"+green, 16);\n\tblue = parseInt(\"\"+blue, 16);\n\t// console.log(red + 'red' + green + 'green' + blue + 'blue');\n\n\t// console.log('random hex is ' + hexCode);\n\tlet randomColor = new color(red, green, blue);\n\t// console.log(randomColor);\n\treturn randomColor;\n}", "function randLightColor() {\r\n\tvar rC = Math.floor(Math.random() * 256);\r\n\tvar gC = Math.floor(Math.random() * 256);\r\n\tvar bC = Math.floor(Math.random() * 256);\r\n\twhile (Math.max(rC, gC, bC) < 200) {\r\n\t\trC = Math.floor(Math.random() * 256);\r\n\t\tgC = Math.floor(Math.random() * 256);\r\n\t\tbC = Math.floor(Math.random() * 256);\r\n\t}\r\n\treturn tColor(rC, gC, bC, 1.0);\r\n}", "function generateRGB() {\n\tvar r = Math.floor(Math.random() * 256);\n\tvar g = Math.floor(Math.random() * 256);\n\tvar b = Math.floor(Math.random() * 256);\n\treturn \"rgb(\" + r + \", \" + g + \", \" + b + \")\";\n}", "function rgbColor()\n{\n\tvar string = \"rgb(\";\n\tstring = string + getRandomInt(255) + \", \";\n\tstring = string + getRandomInt(255) + \", \";\n\tstring = string + getRandomInt(255) + \")\";\n\treturn string;\n}", "function randomColourGen()\r\n{\r\n var colour = 'rgb(' + (Math.floor(Math.random() * 256)) +\r\n ',' + (Math.floor(Math.random() * 256)) +\r\n ',' + (Math.floor(Math.random() * 256)) + \r\n ',';\r\n var bright=colour+'1.0)';\r\n var light=colour+'0.7)';\r\n return [light,bright];\r\n}", "function startColor () {\n\t\treturn {\n\t\t\tr: 255,\n\t\t\tg: 255 * Math.random(),\n\t\t\tb: 75\n\t\t};\n\t}", "function winningColorGenerator(){\r\n\tfor (var i = 0; i < colors.length; i++){\r\n\t\tvar randNum = Math.floor(Math.random() * numSquare);\r\n\t}\r\n\treturn colors[randNum];\r\n}", "function color() {\n\tfor (var i = 0; i < num; i++) {\n\t\tcoloring.push(randomize());\n\t}\n}", "function randomValue () {\n var random = Math.floor(Math.random()*4);\n progressComputer.push(colors[random]);\n }", "function getHexColor() {\n if (Math.round(Math.random())) {\n return \"ff\";\n } else {\n return \"00\";\n }\n}", "function getRandomNum() {\n var random = Math.floor(Math.random() * 4);\n simonSeq.push(colorArr[random]);\n }", "static Purple() {\n return new Color3(0.5, 0, 0.5);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to update cursor position in the dom
function updateCursorPosition(left, top) { cursor.style.left = `${left}px `; cursor.style.top = `${top}px`; cursor.scrollIntoView({ behavior: "smooth", block: "center", inline: "center", }); }
[ "__refreshCursor() {\n var currentCursor = this.getStyle(\"cursor\");\n this.setStyle(\"cursor\", null, true);\n this.setStyle(\"cursor\", currentCursor, true);\n }", "function resetCursorPos(element) {\n element.selectionStart = 0;\n element.selectionEnd = 0;\n }", "updateCaret() {\n\t\tthis.caret = this.textarea.selectionStart;\n\t}", "function changeCursor(cursor) {\n document.body.style.cursor = cursor; \n}", "function updateFakeCursor(cm) {\n var className = 'cm-animate-fat-cursor';\n var vim = cm.state.vim;\n var from = clipCursorToContent(cm, copyCursor(vim.sel.head));\n var to = offsetCursor(from, 0, 1);\n clearFakeCursor(vim);\n // In visual mode, the cursor may be positioned over EOL.\n if (from.ch == cm.getLine(from.line).length) {\n var widget = dom('span', { 'class': className }, '\\u00a0');\n vim.fakeCursorBookmark = cm.setBookmark(from, {widget: widget});\n } else {\n vim.fakeCursor = cm.markText(from, to, {className: className});\n }\n }", "function setCaretPosition(position) {\n\tdocument.getElementById(\"content-editor\").setSelectionRange(position, position);\n\tdocument.getElementById(\"content-editor\").focus();\n}", "function setCursorPosition(field, position){\n \n // If not focused, set focus on field\n \n if(!$(field).is(':focus')){\n \n $(field).focus();\n \n }\n \n // Set cursor position for field\n \n field.selectionStart = position;\n field.selectionEnd = position;\n}", "function add_character_move_cursor(input_string) {\r\n\ttextarea_element.setRangeText(input_string, textarea_element.selectionStart, textarea_element.selectionEnd, \"end\");\r\n\t//textarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table();\r\n}", "_updateKnobPosition() {\n this._setKnobPosition(this._valueToPosition(this.getValue()));\n }", "function moveCursor(ix, iy) {\n var cursor = editor.cursor;\n if(ix < 0 && iy < 0) {\n editor.ix = ix;\n editor.iy = iy;\n editor.focus = null;\n cursor.setAttribute('visibility', 'hidden');\n return;\n }\n\n /*\n if(ix < 0) {\n ix = nrow - 1;\n iy--;\n }\n else if(ix >= nrow) {\n ix = 0;\n iy++;\n }\n\n if(iy < 0 || iy >= nrow)\n return;\n */\n if(0 <= ix && ix < nrow && 0 <= iy && iy < nrow) {\n cursor.setAttribute('visibility', 'visible');\n cursor.setAttribute('x', editor.margin[3] + ix*editor.w + 2);\n cursor.setAttribute('y', editor.margin[0] + iy*editor.w + 2);\n\n p = editor.ban[iy*nrow + ix];\n editor.ix = ix;\n editor.iy = iy;\n editor.focus = {type: 'ban', ix: ix, iy: iy, p: p};\n }\n}", "function setCursor(cursor) {\n var x = document.querySelectorAll(\"*\");\n for (var i = 0; i < x.length; i++) {\n x[i].style.cursor = cursor;\n }\n}", "function updateRange() {\r\n var position = parseInt(window.getComputedStyle(this, null).getPropertyValue('width')) / 100;\r\n this.nextElementSibling.style.left = ((this.value * position) - 10) + 'px';\r\n this.nextElementSibling.textContent = this.value;\r\n }", "refreshCenter()\n {\n let { x, y } = this.editing == \"start\"? { x: this.rect.x1, y: this.rect.y1 }: { x: this.rect.x2, y: this.rect.y2 };\n x *= this.width;\n y *= this.height;\n this._handle.querySelector(\".crosshair\").setAttribute(\"transform\", `translate(${x} ${y})`);\n }", "function showCursor(cur) {\n if (cur != undefined) selectCursor(cur);\n slides.style.cursor = currentCursor;\n }", "function updatePromptDisplay() {\n var line = promptText;\n var html = '';\n if (column > 0 && line == '') {\n // When we have an empty line just display a cursor.\n html = cursor;\n } else if (column == promptText.length) {\n // We're at the end of the line, so we need to display\n // the text *and* cursor.\n html = htmlEncode(line) + cursor;\n } else {\n // Grab the current character, if there is one, and\n // make it the current cursor.\n var before = line.substring(0, column);\n var current = line.substring(column, column + 1);\n if (current) {\n current =\n '<span class=\"jquery-console-cursor\">' +\n htmlEncode(current) +\n '</span>';\n }\n var after = line.substring(column + 1);\n html = htmlEncode(before) + current + htmlEncode(after);\n }\n prompt.html(html);\n scrollToBottom();\n }", "TreeAdvanceToLabelPos()\n {\n let g = this.guictx;\n g.CurrentWindow.DC.CursorPos.x += this.GetTreeNodeToLabelSpacing();\n }", "cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value)\n else this.map.set(cursor.tree, value)\n }", "function updatePointers(num_ops_processed, log_position) {\n if (num_ops_processed != -1) {\n d3.select('#commands')\n .selectAll(\"li\")\n .attr('class','');\n d3.select('#commands')\n .selectAll(\"li\")\n .filter(function(d, i) { return i == num_ops_processed; })\n .attr('class','current-op');\n var commandEle = document.getElementById('commands');\n commandEle.scrollTop = commandEle.children[0].offsetHeight * (num_ops_processed -2);\n }\n if (log_position != -1) {\n d3.select('#log')\n .selectAll(\"tr\")\n .filter(function(d, i) { return i == log_position; })\n .attr('class','current-row');\n }\n }", "changePxPositionPostIts() {\n let elArray = this.main.children;\n this.getWindowSize();\n for (let i = 0; i < elArray.length; i++) {\n let element = elArray[i];\n let posX = element.getAttribute(\"posX\");\n let posY = element.getAttribute(\"posY\");\n let newPx = this.calculatePercentToPX(posX, posY);\n element.style.transform = `translate(${newPx.pxX}px, ${newPx.pxY}px)`;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether any dimension in gO has a dynamic size
function hasDynSize(gO) { for (var d = 0; d < gO.numDims; d++) { if (gO.dimDynSize[d]) { logMsg("has dyn size"); return true; } } return false; }
[ "isFull() {\n return this.size == this.maxSize;\n }", "isFull() {\r\n\t\treturn (this.emptyCells.size() == 0);\r\n\t}", "function allocAnyDynamicGrid(mO, fO, sO) {\r\n\r\n var out_id = 0; // grid id of output grid\r\n\r\n var gId = sO.allGridIds[out_id];\r\n var gO = fO.allGrids[gId];\r\n\r\n // if this step doesn't have a new out grid OR the out grid does not\r\n // have any dynamic sizes, then nothing to do\r\n //\r\n if (!sO.isOutGridNew || !(gO && hasDynSize(gO)))\r\n return \"\";\r\n\r\n\r\n logMsg(\"Out grid of step has a dynmic size\");\r\n\r\n // Go thru each dimension and if any dim is dynamically sized (based on \r\n // the value of scalar grid), insert code to calculate the value and \r\n // reallcate grid data\r\n //\r\n var ret = \"/* dynamic grid allocation */\\n\";\r\n\r\n var outname = \"fO.allGrids[\" + gId + \"]\";\r\n //\r\n for (var d = 0; d < gO.numDims; d++) {\r\n\r\n if (gO.dimDynSize[d]) {\r\n\r\n // TODO: If scalar grid name does not exist, throw an error\r\n //\r\n // insert the line to copy the value of scalar grid to \r\n // dimActSize[d] \r\n //\r\n ret += outname + \".dimActSize[\" + d + \"] = \" + var2JS(gO.dimDynSize[\r\n d]) + \".data[0];\\n\";\r\n\r\n\r\n // logMsg(\"detected dyn size for dim: \" + d);\r\n }\r\n }\r\n\r\n // STEP:\r\n // Now, insert code to dynamically allocate the output grid at this\r\n // point\r\n //\r\n ret += \"createArrays(\" + outname + \");\\n\\n\";\r\n\r\n return ret;\r\n\r\n}", "isEmpty() {\n // the heap has a mark in the top of heap\n return this.size === 1;\n }", "function checkShipPlacement() {\n if (isHorizontal) {\n if (shipLength + col > 10) {\n return false;\n } else {\n return true;\n }\n } else {\n if (shipLength + row > 10) {\n return false;\n } else {\n return true;\n }\n }\n}", "function bigEnoughForInteractiveFigures() {\r\n if (!(window.matchMedia('(max-width: 600px)').matches)) {\r\n gtag('event', 'min-sheets-width', { 'event_category': 'user', 'event_label': 'true', 'value': 1 });\r\n return true;\r\n }\r\n gtag('event', 'min-sheets-width', { 'event_category': 'user', 'event_label': 'false', 'value': 0 });\r\n console.log('Screen too small for interactive visuals');\r\n return false;\r\n}", "function dataTooBig() {\n switch (qwQueryService.outputTab) {\n case 1: return(qc.lastResult.resultSize / qc.maxAceSize) > 1.1;\n //case 2: return(qc.lastResult.resultSize / qc.maxTableSize) > 1.1;\n case 3: return(qc.lastResult.resultSize / qc.maxTreeSize) > 1.1;\n }\n\n }", "function updateDimSize(dim, dim_size, isActual) {\r\n\r\n var gO = NewGridObj;\r\n var dimsz = parseInt(dim_size);\r\n\r\n if (!isActual) { // if we are updating display size\r\n\r\n gO.dimShowSize[dim] = dimsz;\r\n\r\n\tif (gO.dimHasTitles[dim]) // if this dim has titles\r\n\t gO.dimActSize[dim] = dimsz; // actual = disp, if titles\r\n\r\n // If we increased the # of dims, push init values\r\n //\r\n for (var i = gO.dimTitles[dim].length; i < dimsz; i++) {\r\n\r\n //gO.dimTitles[dim].push( \"d\" + (dim+1) + DefDimTitleRoot + i ); \r\n gO.dimTitles[dim].push(getTabName(dim, i));\r\n gO.dimComments[dim].push(null);\r\n }\r\n //\r\n // if we reduced the value, pop trailing entries\r\n //\r\n while (gO.dimTitles[dim].length > dimsz) {\r\n gO.dimTitles[dim].pop();\r\n gO.dimComments[dim].pop();\r\n }\r\n\r\n\tif (gO.dimSelectTabs[dim] >= dimsz) // if selected tab is deleted\r\n\t gO.dimSelectTabs[dim] = dimsz-1; // set it to the last \r\n\r\n\tif (gO.typesInDim == dim) { // push data types\r\n\t while (gO.dataTypes.length < dimsz) {\r\n\t\tgO.dataTypes.push(0);\r\n\t }\r\n\t}\r\n\r\n } else { // updating actual size\r\n\r\n gO.dimActSize[dim] = dimsz;\r\n }\r\n\r\n\r\n\r\n reDrawConfig(); // redraw with updates\r\n\r\n}", "function GADGET_GEN_Check_Dock()\n{\t\n\t\n\t\n\tvar Size_Dock = \"Small\";\n\t\t\n\tvar\tSize_UnDock = \"Small\";\n\t\n\tif (System.Gadget.docked)\n\t{\n\t\tif (Size_Dock == \"Small\")\n\t\t\tGADGET_GEN_OnDock();\n\t\telse if (Size_Dock == \"Large\")\n\t\t\tGADGET_GEN_OnUnDock();\t\n\t}\n\telse\n\t{\n\t\tif (Size_UnDock == \"Large\")\n\t\t\tGADGET_GEN_OnUnDock();\n\t\telse if (Size_UnDock == \"Small\")\n\t\t\tGADGET_GEN_OnDock();\n\t}\n}", "exceedsMaxSize() {\n return JSON.stringify(this.data).length > MAX_SESSION_DATA_SIZE;\n }", "function isValidGridSize(gridSize){\n if(gridSize < 5){\n return false;\n }\n var nMinusOne = gridSize - 1;\n if((nMinusOne & (nMinusOne - 1)) == 0){\n return true;\n } else {\n return false;\n }\n}", "function elementCanExpand() {\n return element.offset().top + element.height() < $(window).height() + 100; // 100 = number of pixels below view\n }", "function checkDomSize() {\n\t\tvar size = $('#pics .img-wrap').length\n\t\t,cols = $('#pics').children()\n\t\t,colsCount = cols.length\n\t\t,toDelete = Math.floor((size - maxUnitsNumber) / colsCount)\n\t\tif(size < maxUnitsNumber) return\n\t\tcols.each(function() {\n\t\t\t$(this).children(':lt(' + toDelete + ')').remove()\n\t\t})\n\t}", "function sameLength(g1,g2) {\n return g1.hasOwnProperty('coordinates') ? \n g1.coordinates.length === g2.coordinates.length\n : g1.length === g2.length;\n}", "function is_large( vp_width ) {\n return vp_width > $(58.75).toCleanPx(); \n}", "function isFullSizeImageLoaded() {\n var el = document.getElementById('lightBoxImage');\n return el && el.width && el.width >= MINIMUM_IMAGE_WIDTH;\n }", "isAreaEmpty(x, y, width, height) {\r\n return this.engine.isAreaEmpty(x, y, width, height);\r\n }", "function outOfBounds(i, j) {\n return (i < 0 || i >= gridHeight) || (j < 0 || j >= gridWidth);\n}", "function is_medium( vp_width ) {\n return vp_width > $(40).toCleanPx() && vp_width <= $(58.75).toCleanPx(); \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function ready() creates an object which stores the respective number of wins, losses, and draws. Also, it adds an event listener to each of the images which calls evaluateChoice(playerChoice, scoreboard) and passes "rock", "paper", or "scissors" depending on the image that's clicked. Precondition: The webpage's fully loaded. Postcondition: An object consisting of the respective number of wins, losses, and draws is created, and an event listener to each of the images which calls evaluateChoice(playerChoice, scoreboard).
function ready() { // Create an object that'll store the number of wins, losses, and draws, respectively. const scoreboard = { wins: 0, losses: 0, draws: 0 }; /* Add an event listener to each of the choices that'll pass a respective string value to evaluateChoice(playerChoice). */ document.querySelector(".rock-img").addEventListener("click", () => { evaluateChoice("rock", scoreboard); }); document.querySelector(".paper-img").addEventListener("click", () => { evaluateChoice("paper", scoreboard); }); document.querySelector(".scissors-img").addEventListener("click", () => { evaluateChoice("scissors", scoreboard); }); }
[ "function evaluateChoice(playerChoice, scoreboard)\n{\n // Create a variable that'll store the cpu's choice.\n let cpuChoice = generateCPUChoice(); // Stores \"rock\", \"paper\", or \"scissors\"\n\n // Evaluate whether both choices result in the player winning, losing, or drawing.\n switch (playerChoice)\n {\n case \"rock\":\n if (cpuChoice === \"rock\")\n {\n // Increase the number of draws by 1 and render it on the webpage.\n scoreboard.draws = scoreboard.draws + 1;\n document.querySelector(\".draws-number\").innerText = \"\" + scoreboard.draws;\n }\n else if (cpuChoice === \"paper\")\n {\n /*\n Increase the number of losses by 1 and render it on the webpage.\n If the # equals 10, call renderLossModal(scoreboard);\n */\n scoreboard.losses = scoreboard.losses + 1;\n document.querySelector(\".losses-number\").innerText = \"\" + scoreboard.losses;\n\n if (scoreboard.losses === 10)\n {\n renderLossModal(scoreboard);\n }\n }\n else // cpuChoice === \"scissors\"\n {\n /*\n Increase the number of wins by 1 and render it on the webpage.\n If the # equals 10, call renderWinModal(scoreboard);\n */\n scoreboard.wins = scoreboard.wins + 1;\n document.querySelector(\".wins-number\").innerText = \"\" + scoreboard.wins;\n\n if (scoreboard.wins === 10)\n {\n renderWinModal(scoreboard);\n }\n }\n break;\n\n case \"paper\":\n if (cpuChoice === \"rock\")\n {\n /*\n Increase the number of wins by 1 and render it on the webpage.\n If the # equals 10, call renderWinModal(scoreboard);\n */\n scoreboard.wins = scoreboard.wins + 1;\n document.querySelector(\".wins-number\").innerText = \"\" + scoreboard.wins;\n\n if (scoreboard.wins === 10)\n {\n renderWinModal(scoreboard);\n }\n }\n else if (cpuChoice === \"paper\")\n {\n // Increase the number of draws by 1 and render it on the webpage.\n scoreboard.draws = scoreboard.draws + 1;\n document.querySelector(\".draws-number\").innerText = \"\" + scoreboard.draws;\n }\n else // cpuChoice === \"scissors\"\n {\n /*\n Increase the number of losses by 1 and render it on the webpage.\n If the # equals 10, call renderLossModal(scoreboard);\n */\n scoreboard.losses = scoreboard.losses + 1;\n document.querySelector(\".losses-number\").innerText = \"\" + scoreboard.losses;\n\n if (scoreboard.losses === 10)\n {\n renderLossModal(scoreboard);\n }\n }\n break;\n \n case \"scissors\":\n if (cpuChoice === \"rock\")\n {\n /*\n Increase the number of losses by 1 and render it on the webpage.\n If the # equals 10, call renderLossModal(scoreboard);\n */\n scoreboard.losses = scoreboard.losses + 1;\n document.querySelector(\".losses-number\").innerText = \"\" + scoreboard.losses;\n\n if (scoreboard.losses === 10)\n {\n renderLossModal(scoreboard);\n }\n }\n else if (cpuChoice === \"paper\")\n {\n /*\n Increase the number of wins by 1 and render it on the webpage.\n If the # equals 10, call renderWinModal(scoreboard);\n */\n scoreboard.wins = scoreboard.wins + 1;\n document.querySelector(\".wins-number\").innerText = \"\" + scoreboard.wins;\n\n if (scoreboard.wins === 10)\n {\n renderWinModal(scoreboard);\n }\n }\n else // cpuChoice === \"scissors\"\n {\n // Increase the number of draws by 1 and render it on the webpage.\n scoreboard.draws = scoreboard.draws + 1;\n document.querySelector(\".draws-number\").innerText = \"\" + scoreboard.draws;\n }\n break;\n }\n}", "function init() {\n scores = {\n p: 0,\n t: 0,\n c: 0\n };\n results = {\n p: '',\n c: ''\n };\n winner = null;\n}", "function paperLoadedInit() {\n console.log('Paper ready!');\n\n $(window).resize();\n // Use mode settings management on all \"managed\" class items. This\n // saves/loads settings from/into the elements on change/init.\n //mode.settings.$manage('.managed'); // DEBUG! ENABLE THIS WHEN READY\n\n // With Paper ready, send a single up to fill values for buffer & pen.\n mode.run('up');\n}", "function setRockImg(){\n decision = \"rock\";\n document.getElementById('meImg').src = ROCKIMGPATH;\n}", "function checkImages(){ //Check if the images are loaded.\n\n if(game.doneImages >= game.requiredImages){ //If the image loads, load the page to the DOM.\n\n init();\n }else{ //loop until the images are loaded.\n\n setTimeout(function(){\n checkImages();\n },1);\n\n }\n }", "function makeReady() {\n\tconsole.log(\"play ready!\");\n\tdocument.getElementById(\"play\").onclick = function() {\n\t\t//\"play\" button disabled while game is in play\n\t\tdocument.getElementById(\"play\").disabled = true;\n\t\t//delays the function that re-enables play button until game timer = 0\n\t\tsetTimeout(enablePlay, 14000);\n\t\tready();\n\t};\n\t// console.log(\"reset ready!\");\n\t// document.getElementById(\"reset\").onclick = function() {\n\t// \twipeGameTimer();\n\t// \twipeGameBoard();\n\t// };\n\tmakeGameboard();\n}", "function loadLevelSelectionPage(){\n //Clearing the content on the page\n document.body.innerHTML = \"\";\n\n //Adding the level selction page statuc content\n document.body.appendChild(createLevelSelectionPage());\n\n //Making score to zero in back flow to level selection page\n score=0;\n\n //Resetting the timer\n resetTimer();\n}", "function onload_handler() {\n //\n // Create chess board\n //\n create_board();\n //\n // Indicate which side is to move\n //\n display_board.mark_side2move();\n //\n // Add event handlers to catch clicking on individual squares\n //\n add_cell_handlers();\n //\n // Add additional event handlers based on artificial HTML attribute values\n //\n add_controller_events(document.body);\n}", "function loadLandingPage() {\n //Clearing the content on the page\n document.body.innerHTML = \"\";\n\n //Adding the static content in the landing page\n document.body.appendChild(createLandingPageContent());\n\n //Manage the music when the speaker is on\n if(speakerImage === 'speaker_on'){\n //If arrived from game over page, sounds may already be initaited\n //Stop the levelUp sound and start game sound in this case\n if(sounds.levelUp != undefined){\n //Stop levelup music\n sounds.levelUp.pause();\n sounds.levelUp.currentTime = 0.0;\n }\n if(sounds.game != undefined){\n //Start game music\n sounds.game.loop = true;\n sounds.game.play();\n }\n }\n //Resetting the score to zero\n score = 0;\n\n //Resetting the timer\n resetTimer();\n}", "function initUIElements() {\n document.getElementById('splash_image').src = SPLASH_SCREEN_SRC;\n document.getElementById('logo_image').src = LOGO_IMAGE_SRC;\n\n promoImageElement = document.getElementById('promo_image');\n titleElement = document.getElementById('loading_title');\n descriptionElement = document.getElementById('loading_description');\n\n splashScreen = document.querySelector(\"#splash_screen\");\n loadingScreen = document.querySelector(\"#loading_screen\");\n playerScreen = document.querySelector(\"#player\");\n errorScreen = document.querySelector(\"#error_screen\");\n screens = [ splashScreen, loadingScreen, playerScreen, errorScreen ];\n screenController = new _ScreenController(screens);\n }", "function check() {\n // Determine milliseconds elapsed since the color was loaded\n var milliseconds_taken = Date.now() - time_at_load;\n\n // Calculate the percents that the user was off\n var percents = {\n red: (Math.abs(color.red - guess.red)/255)*100,\n green: (Math.abs(color.green - guess.green)/255)*100,\n blue: (Math.abs(color.blue - guess.blue)/255)*100\n };\n\n // Calculate the average (overall) percent off\n var percent_off = (percents.red + percents.green + percents.blue)/3;\n\n // Calculate the turn's score\n var turn_score = ((15 - settings.difficulty - percent_off) /\n (15 - settings.difficulty)) *\n (15000 - milliseconds_taken);\n\n // If positive, round to 2 decimals. If negative, set to 0.\n turn_score = (turn_score > 0) ? (Math.round(turn_score*100)/100) : 0;\n\n // Add the score for the turn to the running total\n total_score += turn_score;\n\t\ttotal_score = (Math.round(total_score*100)/100)\n\n\t\t// decrease the turn count\n turns_remaining--;\n\n\t\t// check if no turns remain\n if(turns_remaining > 0) {\n newColor();\n\n // Display the current statistics\n $('#result').html(\"Last Score: \" + turn_score +\n \"; Total Score: \" + total_score +\n \"; Turns Left: \" + turns_remaining);\n\n } else {\n // create a new div element to display game over info for the user\n // wrapped in a div for easy removing on game reset\n var gameOver = $('<div>').attr('id', 'gameOver');\n\n // Add a header to denote game over\n gameOver.append($(\"<h2>\").text(\"Game Over!\"));\n\n // Show the final score from the game\n gameOver.append($(\"<p>\").text(\"Final Score: \" + total_score));\n\n\t\t\t// Create the input for players to input a name for their high score\n var playerNameInput = $('<input>').attr('placeholder', 'Your name');\n\n\t\t\t// Add the input to the page with an ID for easy value access\n gameOver.append(playerNameInput.attr('id', 'hsName'));\n\n\t\t\t// Create a submit button to send the score to the high scores array\n var submit = $('<button>').text(\"Submit High Score!\");\n submit = submit.attr(\"type\", \"button\").attr(\"id\",\"hsSubmit\");\n\n\t\t\t// Show the button\n gameOver.append(submit.click(submitHighscore));\n\n\t\t\t// Create a try again buton to allow users to restart the game over\n\t\t\tvar againButton = $(\"<button>\").text(\"Try Again!\");\n\n\t\t\t// Show the button\n gameOver.append(againButton.attr(\"type\", \"button\").click(reset));\n\n\t\t\t// Hide the game so they can't keep playing\n gameElement.children().hide();\n\n\t\t\t// Add the game over elements\n gameElement.append(gameOver);\n }\n }", "function run() {\n \tplayerChoice = this.innerText;\n \tcomputerGamble();\n \tcompare();\n}", "function initialize() {\n\t\timageCompare = image_compare();\n\n\t\trendering = true;\n\n\t\tmain();\n\t}", "function initState() {\r\n var player1, player2, p1tag, p2tag;\r\n\r\n document.getElementsByClassName(\"game-container\")[0].style.display = \"block\";\r\n document.getElementsByClassName(\"game-intro\")[0].style.display = \"none\";\r\n\r\n player1 = document.getElementById('player1');\r\n p1tag = player1.children[2].children[5];\r\n p1tag.innerHTML = p1name +' is ready to fight.';\r\n\r\n player2 = document.getElementById('player2');\r\n p2tag = player2.children[2].children[5];\r\n p2tag.innerHTML = p2name +' is ready to fight.';\r\n\r\n document.getElementById('turn_text').innerHTML = p1name + \"'s turn\";\r\n}", "function main() {\n render();\n quizStartPageStartButton();\n questionSubmitButton();\n resultsResetButton();\n nextQuestionButton();\n}", "function loadContent(){\n pole = game.instantiate(new Pole(Settings.pole.size));\n pole.setColor(Settings.pole.color);\n pole.setPosition(Settings.canvasWidth /2 , Settings.canvasHeight /2);\n\n shield = game.instantiate(new Shield(pole));\n shield.getBody().immovable = true;\n shield.setColor(Settings.shield.color);\n\n player = game.instantiate(new Player(\"\"));\n player.setPole(pole);\n player.setShield(shield);\n pole.setPlayer(player);\n\n //Player labels, name is set once again when the user has filled in his/her name\n scoreLabel = game.instantiate(new ScoreLabel(player, \"Score: 0\"));\n scoreLabel.setPosition(Settings.label.score);\n\n nameLabel = game.instantiate(new Label(\"Unknown Player\"));\n nameLabel.setPosition(Settings.label.name);\n\n highscoreLabel = game.instantiate(new Label(\"Highscore: 0\"));\n highscoreLabel.setPosition(Settings.label.highscore);\n\n createTempImage();\n setTimeout(deleteTempImage, 3000);\n\n //Hide the canvas for the player until a username is filled in and accepted\n var gameElem = document.getElementById(\"gameCanvas\");\n gameElem.style.display=\"none\";\n}", "function definePageElements(){\n playerContainer = document.getElementsByClassName(\"hero\")[0];\n var temp = playerContainer.getElementsByTagName(\"span\");\n for(var i = 0; i < temp.length; i++){\n switch(temp[i].className){\n case \"health\":\n playerHpDisplay = temp[i];\n break;\n case \"mana\":\n playerManaDisplay = temp[i];\n break;\n default:\n console.log(\"Unidentified player span \" + temp[i].name);\n }\n }\n actions = [];\n actionLogDisplay = document.getElementById(\"action-log\");\n starter = document.getElementsByClassName(\"starter\")[0];\n temp = document.getElementById(\"fight-button\");\n gameContainer = document.getElementById(\"game-container\");\n addEvent(temp,'click',startGame,false);\n dragonCanvas = document.getElementById(\"dragon-info\");\n dragonCanvasContext = dragonCanvas.getContext('2d');\n temp = null;\n}", "function init() {\n document\n .getElementById(\"game-photo-1\")\n .addEventListener(\"click\", playSound1);\n document\n .getElementById(\"game-photo-2\")\n .addEventListener(\"click\", playSound2);\n document\n .getElementById(\"game-photo-3\")\n .addEventListener(\"click\", playSound3);\n document\n .getElementById(\"game-photo-4\")\n .addEventListener(\"click\", playSound4);\n}", "function loadQuizResults() {\n if (score >= 8) {\n $('.js-quiz-tv').html(\n `<div><p class=\"ultra\">You Win!</p></div>\n <div><img src=\"images/win_giphy.gif\" alt=\"High Score Reaction\"></div>\n <div><p class=\"slabo\">You are taking home today's Grand Prize...A chance to play agian.</p></div>`\n );\n }\n else if (score >= 5 && score < 8) {\n $('.js-quiz-tv').html(\n `<div><p class=\"ultra\">Good Job! You got most of them Correct.</p></div>\n <div><img src=\"images/good_giphy.gif\" alt=\"Middle Score Reaction\"></div>\n <div><p class=\"slabo\">You can do better, give it another shot to get a higher score.</p></div>`\n );\n }\n else {\n $('.js-quiz-tv').html(\n `<div><p class=\"ultra\">Oh No! You missed a lot.</p></div>\n <div><img src=\"images/bad_giphy.gif\" alt=\"Low Score Reaction\"></div>\n <div><p class=\"slabo\">That wasn't good, we should just start over.</p></div>`\n );\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get module by package id like require(id)
function getModuleByID(id, requireIfNotExists, req = require) { if (id === '.') { return getMainModule(id); } return getModuleByFile(req.resolve(id), requireIfNotExists, req); }
[ "function createRequire(requirer) {\n return function require(id) {\n // Make sure an id was passed.\n if (id === undefined) {\n throw new Error(\"can't require module without id!\");\n }\n\n // Built-in modules are cached by id rather than URL, so try to find the\n // module to be required by id first.\n let module = modules[id];\n if (module === undefined) {\n // Failed to find the module to be required by id, so convert the id to\n // a URL and try again.\n\n // If the id is relative, resolve it to an absolute id.\n if (id.startsWith(\".\")) {\n if (requirer === undefined) {\n throw new Error(\"can't require top-level module with relative id \" +\n id + \"!\");\n }\n id = resolve(id, requirer.id);\n }\n\n // Convert the absolute id to a normalized id.\n id = normalizeId(id);\n\n // Convert the normalized id to a URL.\n let url = id;\n\n // If the URL is relative, resolve it to an absolute URL.\n if (url.match(/^\\w+:\\/\\//) === null) {\n url = resolveURL(id);\n }\n\n // Try to find the module to be required by URL.\n module = modules[url];\n if (module === undefined) {\n // Failed to find the module to be required in the cache, so create\n // a new module, load it with the given URL, and add it to the cache.\n\n // Add modules to the cache early so that any recursive calls to\n // require for the same module will return the partially-loaded module\n // from the cache instead of triggering a new load.\n module = modules[url] = createModule(id);\n\n try {\n loadModule(module, url);\n } catch (error) {\n // If the module failed to load, remove it from the cache so that\n // subsequent calls to require for the same module will trigger a\n // new load instead of returning a partially-loaded module from\n // the cache.\n delete modules[url];\n throw error;\n }\n\n Object.freeze(module);\n }\n }\n\n return module.exports;\n };\n }", "function define_module(id) {\n return define_module_under(cObject, id);\n}", "static locate(module) {\n // Initialize name & default sources\n let name = module.toLowerCase();\n let repository = \"internal\";\n\n // Slice name and look for repository\n let slices = name.split(\":\");\n\n // Make sure there are exactly two slices\n if (slices.length === 2) {\n // Update name\n name = slices.pop();\n // Update sources\n repository = slices.pop();\n }\n\n // Query repository element\n let element = document.querySelector(`meta[name=\"repository-${repository}\"]`);\n\n // Make sure repository exists\n if (element !== null)\n return `${element.content}/${name}.js`;\n\n // Return null\n return null;\n }", "function lookupPackage(currDir) {\n // ideally we stop once we're outside root and this can be a simple child\n // dir check. However, we have to support modules that was symlinked inside\n // our project root.\n if (currDir === '/') {\n return null;\n } else {\n var packageJson = packageByRoot[currDir];\n if (packageJson) {\n return packageJson;\n } else {\n return lookupPackage(path.dirname(currDir));\n }\n }\n }", "function resolveModuleId(moduleId: string, parent: ?Module): string {\n return NativeModule._resolveFilename(moduleId, parent, false);\n}", "function getModName(s){\n if(EXEC(/^module\\s+([^\\s\\(]*)/, s)) {\n\treturn /^module\\s+([^\\s\\(]*)/.exec(s)[0];\n } else {\n\treturn \"\";\n }\n}", "require(path) {\n assert(path, 'missing path');\n assert(typeof path === 'string', 'path must be a string');\n return Module._load(path, this, /* isMain */ false);\n }", "function getLibrary (table, id) {\n\n\t\tvar query = db.select(table.library).from(table).where(table.id.eq(id));\n\n\t\treturn query.exec().then(function (result) {\n\t\t\treturn result[0].library;\n\t\t}).catch(function (err) {\n\t\t\tconsole.log(err);\n\t\t});\n\n\t}", "getCommandSpec(packageId, commandId) {\n return this.packages[packageId].commands[commandId];\n }", "async requireX(x, y) {\n assert(typeof x === 'string');\n assert(typeof y === 'string');\n assert(isAbsolute(y));\n\n if (x.length === 0 || y.length === 0)\n return null;\n\n if (x === '.' || x === '..')\n x += '/';\n\n if (CORE_MODULES.has(x))\n return x;\n\n // Allow lookups like `C:\\foobar` on windows.\n if (WINDOWS && isAbsolute(x) && x[0] !== '/') {\n y = x; // Gets set to root below.\n x = unix(x);\n }\n\n if (x[0] === '/')\n y = WINDOWS ? parse(y).root : '/';\n\n if (x[0] === '/' || x.startsWith('./') || x.startsWith('../')) {\n const yx = join(y, x);\n const a = await this.loadAsFile(yx);\n\n if (a)\n return a;\n\n const b = await this.loadAsDirectory(yx);\n\n if (b)\n return b;\n }\n\n // Early exit unless we want `/foo` to\n // be able to resolve to `/node_modules/foo`.\n if (x[0] === '/')\n return null;\n\n // Supposed to do dirname(y), but our\n // nodeModulePaths function is different (?).\n const z = await this.loadNodeModules(x, y);\n\n if (z)\n return z;\n\n return null;\n }", "function getModuleByVersion(modulename, version) {\n version = parseInt(version);\n while (version > 1 && !checkIfVersionExists(modulename, version)) {\n version--;\n }\n return instantiate(modulename, version); //return new modulename.v + version;\n}", "function getModuleByExports(exportModule, req = require) {\n let ks = Object.keys(req.cache);\n let i = ks.length;\n while (--i) {\n let key = ks[i];\n let mod = req.cache[key];\n if (mod.exports === exportModule) {\n return mod;\n }\n }\n return null;\n}", "resolveId ( id, importer = location.href ) {\n\t\t\t// don't touch absolute paths\n\t\t\tif ( absolutePath.test( id ) ) return id;\n\n\t\t\t// add '.js' to paths without extensions\n\t\t\tif ( extname( id ) === '' ) id += '.js';\n\n\t\t\t// keep everything before the last '/' in `importer`\n\t\t\tconst base = importer.slice(0, importer.lastIndexOf('/') + 1);\n\n\t\t\t// resolve `id` relative to `base`\n\t\t\treturn resolve( base + id );\n\t\t}", "function requireFromParentUp(id, startModule) {\n let ls = getAllModule(startModule);\n startModule = ls.shift();\n return requireFromModuleList(id, ls.reverse(), startModule);\n}", "function loadModule (moduleName, app, pool) {\n var fileName = __dirname + '/modules/' + moduleName;\n\n console.log('Loading module: [%s]', fileName);\n require(fileName)(app, pool);\n}", "_findResource(id) {\n return this.template.resources.find(res => {\n // Simple match on substring is possible after \n // fully resolving names & types\n return res.fqn.toLowerCase().includes(id.toLowerCase());\n });\n }", "function parseWebModuleSpecifier(specifier, knownDependencies) {\n const webModulesIndex = specifier.indexOf('web_modules/');\n if (webModulesIndex === -1) {\n return null;\n }\n // check if the resolved specifier (including file extension) is a known package.\n const resolvedSpecifier = specifier.substring(webModulesIndex + 'web_modules/'.length);\n if (knownDependencies.includes(resolvedSpecifier)) {\n return resolvedSpecifier;\n }\n // check if the resolved specifier (without extension) is a known package.\n const resolvedSpecifierWithoutExtension = stripJsExtension(resolvedSpecifier);\n if (knownDependencies.includes(resolvedSpecifierWithoutExtension)) {\n return resolvedSpecifierWithoutExtension;\n }\n // Otherwise, this is an explicit import to a file within a package.\n return resolvedSpecifier;\n}", "function parseNodeModulePackageJson(name) {\n const mod = require(`../node_modules/${name}/package.json`);\n\n // Take this opportunity to cleanup the module.bin entries\n // into a new Map called 'executables'\n const executables = mod.executables = new Map();\n\n if (Array.isArray(mod.bin)) {\n // should not happen, but ignore it if present\n } else if (typeof mod.bin === 'string') {\n executables.set(name, stripBinPrefix(mod.bin));\n } else if (typeof mod.bin === 'object') {\n for (let key in mod.bin) {\n executables.set(key, stripBinPrefix(mod.bin[key]));\n }\n }\n\n return mod; \n}", "function resolvePath(module, cwd) {\n\n\t\n\treturn resolve.sync(module, {\n\t\tbasedir: cwd\n\t});\n\n\tif(cwd && module.substr(0, 1) == \".\") {\n\t\treturn require.resolve(cwd + \"/\" + module);\n\t}\n\n\t//not local?\n\ttry {\n\t\treturn require.resolve(module);\n\t} catch(e) {\n\t\treturn null;\n\t}\n\t\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the arcgis.events collection by constructing event objects using the raw response objects from the arcgis.raw collection.
function createEventsFromRaw() { return new Promise((resolve, reject) => { const query = {}; const sourceDbUrl = WILDFIRE_CONFIG.PRIMARY_MONGODB_URL; const sourceDbName = "arcgis"; const sourceCollectionName = "raw"; const outputDbUrl = WILDFIRE_CONFIG.PRIMARY_MONGODB_URL; const outputDbName = "arcgis"; const outputCollectionName = "events"; // Load each document from the "raw" collection loadSave(query, sourceDbUrl, sourceDbName, sourceCollectionName, outputDbUrl, outputDbName, outputCollectionName, (err) => { if (err) { reject(err); } else { resolve(); } }, (docs, cb) => { // Construct each event document from the response objects in the "raw" collection cb(null, docs.reduce((acc, obj) => { const rows = obj.features.map(f => f.attributes); return acc.concat(rows); }, [])); }); }); }
[ "events() {\n return new OpenFDADrugEvents(this.api);\n }", "function collectAllEvents() {\n // A set for all calendar events displayed on the UI.\n // Each element in this set is a Json string. \n allEventJson = new Set(); \n \n const eventList = document.getElementById('new-event-list');\n \n // Looks at each event card and scrapes the event's name and \n // start and end times from the HTML elements. \n // Add all event information to a set of all Json strings. \n eventList.childNodes.forEach((eventCard) => {\n const eventName = eventCard.childNodes[0].childNodes[0].innerText; \n const startTime = eventCard.childNodes[0].childNodes[1].innerText; \n const endTime = eventCard.childNodes[0].childNodes[2].innerText; \n const event = new CalendarEvent(eventName, startTime, endTime);\n const eventJson = JSON.stringify(event); \n allEventJson.add(eventJson); \n }); \n}", "function convertResponse(events) {\n const items = [];\n\n // iterate through each issue and extract id, title, etc. into a new array\n for (let i = 0; i < events.length; i++) {\n const raw = events[i];\n const item = {\n id: raw.id,\n title: raw.summary,\n description: raw.description,\n date: raw.start.dateTime,\n link: raw.htmlLink,\n raw: raw\n };\n\n items.push(item);\n }\n\n return { items };\n}", "function createEvent(e) {\n\n let ev = {};\n ev.date_start = `${e.start.year}-${e.start.month.toString().padStart(2,'0')}-${e.start.day.toString().padStart(2,'0')}T`;\n ev.date_end = ev.date_start;\n ev.date_start += e.start.time;\n ev.date_end += e.end.time;\n\n let words = e.content.split('**'); \n// let words = e.content.slice(0,e.content.length - 1).split('**'); \n [ev.apogee, ev.acronym] = getIDs(words[0]);\n ev.isCourse = true;\n if (ev.acronym.indexOf('Evt::') !== -1) {\n ev.isCourse = false;\n [ev.year,ev.tracks] = getYearAndTracks(words[0]);\n }\n else {\n ev.year = (ev.acronym.substr(0,3) === \"S07\" || ev.acronym.substr(0,3) === \"S08\" ) ? 1 : 2;\n // HACK:console.log(ev.apogee);\n ev.tracks = calDB.courses[ev.apogee].tracks.substr(2,2);\n }\n ev.lecturer = getLecturer(words[1]);\n ev.type = getCourseType(words[2]);\n ev.location = getLocation(e.location);\n ev.title = getDescription(e.description);\n ev.ID = createCalendarID(ev);\n ev.group = words[3] || \"All\";\n return ev;\n}", "_createEvents(prefix, events) {\n for(let eventName in events) {\n events[eventName] = new Event(prefix + '_' + eventName, this);\n }\n }", "function createEvent(event){\n\n\t// Event Object: Type, Subtype, Description, StartTimeDate, Freshness, Status, NumberOfNotification, Reliability\t \n\tvar eventObject = new Object();\n\n\t// Type & Subtype Event\n\teventObject.type = event.type.type.charAt(0).toUpperCase() + event.type.type.slice(1).replace(/_/g,\" \");\n\teventObject.subtype = event.type.subtype.charAt(0).toUpperCase() + event.type.subtype.slice(1).replace(/_/g,\" \");\n\n\t// Description Array\n\teventObject.description = event.description;\n\n\t// Start Time Date\n\tvar date = new Date(event.start_time*1000);\n\tvar day = date.getDate();\n\tvar month = date.getMonth();\n\tvar year = date.getFullYear();\n\tvar hours = date.getHours();\n\tvar minutes = date.getMinutes();\n\tvar seconds = date.getSeconds();\n\teventObject.startTime = day+'/'+month+'/'+year+'\\t'+ hours + ':' + minutes + ':' + seconds;\n\teventObject.startTimeUnformatted = parseFloat(event.start_time);\n\t\n\t// Freshness\n\teventObject.freshness = event.freshness;\n\n\t// Event Status\n\tvar status = event.status;\n\teventObject.status = status.charAt(0).toUpperCase() + status.slice(1);\n\tswitch (eventObject.status) {\n\t\tcase \"Open\":\n\t\t\tvar statusHtml = '<button class=\"btn btn-success\">'+eventObject.status;\n\t\t\tbreak;\n\t\tcase \"Closed\":\n\t\t\tvar statusHtml = '<button class=\"btn btn-danger\">'+eventObject.status;\n\t\t\tbreak;\n\t\tcase \"Skeptical\":\n\t\t\tvar statusHtml = '<button class=\"btn btn-warning\">'+eventObject.status;\n\t\t\tbreak;\t\n\t}\n\n\t// Event reliability\n\teventObject.reliability = Math.round( parseFloat(event.reliability * 100)) + \"%\";\n\n\t// Number of Notification\n\teventObject.numNot = event.number_of_notifications;\n\n\t// Event coordinates\n\tif(eventObject.subtype != \"Coda\"){\n\t\teventObject.lat = middlePoint(event.locations).lat();\n\t\teventObject.lng = middlePoint(event.locations).lng();\n\t}\n\telse{\n\t\teventObject.lat = event.locations[0].lat;\n\t\teventObject.lng = event.locations[0].lng;\n\t}\n\t\t\n\t// Event ID\n\teventObject.eventID = event.event_id;\n\n\t// Event address\n\tif(event.route && event.street_number)\n\t\teventObject.address = event.route + \", \" + event.street_number;\n\telse if(event.route)\n\t\teventObject.address = event.route;\n\telse\n\t\teventObject.address = eventObject.lat + \", \" + eventObject.lng;\n\t\n\t// Add event to global Events Array\n\teventArray.push(eventObject);\n\t\n\t// Draw Queue\n\tif(eventObject.subtype.toLowerCase() == \"coda\" && !isiPad){\n\t\tdrawQueue(event);\n\t}\n\n\t// Add Event marker on map\n\taddEventMarker(eventObject);\n\n\t// Html description creation\n\tvar descriptionHtml = \"\";\n\tvar fullArray = checkArray(eventObject.description);\n\tif(fullArray){\n\t\tfor (j in eventObject.description){\n\t\t\tif(eventObject.description[j]){\n\t\t\t\teventObject.description[j] = eventObject.description[j].charAt(0).toUpperCase() + eventObject.description[j].slice(1);\n\t\t\t\tdescriptionHtml = descriptionHtml.concat('<li><p>'+eventObject.description[j]+'</p></li>');\n\t\t\t}\n\t\t}\t\n\t}\n\t\n\t// Add table row\t\t\t\n\t$('#modalBody').append('<tr id=\"'+eventObject.eventID+'tr\">\\\n\t\t\t\t\t\t<td>'+eventObject.type+' > '+eventObject.subtype+'</td>\\\n\t\t\t\t\t\t<td>'+eventObject.startTime+'</td>\\\n\t\t\t\t\t\t<td id='+eventObject.eventID+'>'+eventObject.address+'</td>\\\n\t\t\t\t\t\t<td><div class=\"btn-group\">\\\n\t\t\t\t\t\t\t<a href=\"#\" id=\"'+eventObject.eventID+'but\" class=\"btn btn-inverse dropdown-toggle\" data-toggle=\"dropdown\">Show</a>\\\n\t\t\t\t\t\t\t<ul class=\"dropdown-menu\">'+descriptionHtml+'</ul>\\\n\t\t\t\t\t\t</div></td>\\\n\t\t\t\t\t\t<td>'+eventObject.numNot+' / '+eventObject.reliability+'</td>\\\n\t\t\t\t\t\t<td>'+statusHtml+'</td>\\\n\t\t\t\t\t\t</tr>');\n\tvar butID = \"#\"+eventObject.eventID+\"but\";\t\t\t\n\tif(!fullArray)\n\t\t$(butID).addClass('disabled');\n}", "allEventABIs() {\n const allEventABIs = [];\n const { contracts, libraries, related, } = this.repoData;\n if (contracts) {\n mergeDefs(contracts);\n }\n if (libraries) {\n mergeDefs(libraries);\n }\n if (related) {\n mergeDefs(related);\n }\n return allEventABIs;\n // inner utility function for allEventABIs\n function mergeDefs(abiDefs) {\n for (const key of Object.keys(abiDefs)) {\n const defs = abiDefs[key].abi;\n for (const def of defs) {\n if (def.type === \"event\") {\n allEventABIs.push(def);\n }\n }\n }\n }\n }", "function CreateEvents(Category, Zipcode) {\n //Clears Events and EventData for Get Call\n $(\"#EventList\").empty()\n EventData = []\n $(\"#OneSecFindingResults\").removeClass(\"hide\")\n\n $.when(\n $.ajax({\n method: \"GET\",\n url: \"https://galvanize-cors-proxy.herokuapp.com/https://api.meetup.com/2/open_events?&sign=true&photo-host=public&zip=\"+ Zipcode + \"&country=United%20States&city=Denver&state=CO&category=\" + Category + \"&time=,1w&radius=10&key=\" + MeetupKey\n }),\n $.ajax({\n method: \"GET\",\n url: \"https://maps.googleapis.com/maps/api/geocode/json?address=\"+ Zipcode + \"&sensor=true\"\n })\n )\n .then(function (GetEventData, GetZipCity) {\n EventData.push(GetEventData[0].results)\n ZipCity = GetZipCity[0].results[0].address_components[2].long_name\n var CategoryTitle = $(\"#Categories\").find(\":selected\").text()\n if (EventData[0].length == 0) {\n throw new Error(\"Sorry no upcoming \" + CategoryTitle + \" Events found for \" + ZipCity)\n }\n })\n .then(function(){\n $('#CityEventTitle').text(ZipCity + \"'s Upcoming Events\")\n })\n //Creates an array of Dates from first array index to last array index\n .then(function () {\n $(\"#OneSecFindingResults\").addClass(\"hide\")\n var count = 0\n StartDate = new Date(EventData[0][0].time)\n EndDate = new Date(EventData[0][EventData[0].length - 1].time)\n RangeOfDates = moment.range(StartDate, EndDate)\n DateArray = Array.from(RangeOfDates.by('day'))\n DateArray.map(m => m.format('DD'))\n DateArray.forEach((datefound) => {\n var DateToSet = moment(datefound._d).format(\"dddd, MMMM Do\")\n var DayCount = \"Day\" + count\n $('#EventList').append(`\n <div id=${DayCount} class=\"animated fadeInLeft DateAdded\">\n <h2 class=\"SetDate\">${DateToSet}</h2>\n </div>\n `)\n count++\n })\n SetDates = $(\".SetDate\")\n })\n .then(function () {\n var EventCount = 0\n EventData[0].forEach((EventFound) => {\n Array.from(SetDates).forEach((datefound) => {\n // DateToSet = moment(datefound._d).format(\"dddd, MMMM Do\")\n if (moment(EventFound.time).format(\"dddd, MMMM Do\") === datefound.innerHTML) {\n //Convert Event's Time to usable format\n var Time = moment(EventFound.time).format(\"h:mma\")\n //if statement to check if the EventFound contains a venue key\n var EventLoc\n if (!EventFound.venue) {\n EventLoc = \"Location Not Selected\"\n } else {\n EventLoc = EventFound.venue.name\n }\n\n $(datefound).parent().append(`\n <a class=\"EventLink\" href=\"${EventFound.event_url}\" target=\"_blank\">\n <div id=\"Event${EventCount}\" class=\"Event animated fadeInLeft\">\n <div class=\"EventLeft\">\n <p class=\"EventTimeDate\">${Time}</p>\n </div>\n <div class=\"EventRight\">\n <h4 class=\"EventName\">${EventFound.name}</h4>\n <h4 class=\"GroupName\">${EventFound.group.name}</h4>\n <h5 class=\"EventLocation\">${EventLoc}</h5>\n </div>\n </div>\n </a>\n `)\n // use below for icon link\n // <i class=\"material-icons NTicon\">open_in_new</i>\n //Creates Object Key Event# with array value Group Name and Event ID numbers for each event\n GroupEventPairs[\"Event\" + EventCount] = []\n GroupEventPairs[\"Event\" + EventCount].push(EventFound.group.urlname)\n GroupEventPairs[\"Event\" + EventCount].push(EventFound.id)\n EventCount++\n }\n })\n })\n })\n .then(function() {\n var DateAdd = $('.DateAdded')\n Array.from(DateAdd).forEach((datefound) => {\n if($(datefound).children().length < 2) {\n $(datefound).append(`\n <h5 class=\"NoEvent\">No Events Today.</h5>`)\n }\n })\n })\n .catch(function (error) {\n $(\"#OneSecFindingResults\").addClass(\"hide\")\n $(\"#CityEventTitle\").text(error.message)\n })\n }", "function api_getCalendarEvents(token, callback){\n console.log(\"google_api: getCalendarData()\");\n \n var reqURL = \"https://www.googleapis.com/calendar/v3/calendars/primary/events\";\n\treqURL += \"?calendarId=primary\";\n\treqURL += \"&maxResults=200\";\n\treqURL += \"&orderBy=startTime\";\n\treqURL += \"&showDeleted=false\";\n\treqURL += \"&singleEvents=true\";\n\treqURL += \"&timeMin=\" + moment.tz(EST).format(fullDateFormat);\n\t\n var xhr = new XMLHttpRequest();\n xhr.responseType = 'json';\n xhr.open('GET', reqURL);\n xhr.setRequestHeader('Authorization', 'Bearer ' + token);\n \n xhr.onerror = function () {\n console.log(\"google_api: HTTP GET ERROR [CAL]\");\n console.log(this);\n };\n\n xhr.onload = function() {\n console.log(\"google_api: HTTP GET SUCCESS [CAL]\");\n\t\tconsole.log(this.response);\n\n\t\tcallback(this.response);\n };\n\n console.log(\"Request URL: \" + reqURL);\n\n\txhr.send();\n}", "function getEvents() {\n\t/// \\todo add /api/events-since/{index} (and change Traffic Monitor to keep latest\n\tajax(\"/publish/EventLog\", function(r) {\n\t\tconst events = JSON.parse(r).events || [];\n\t\tfor (const event of events.slice(lastEvent+1)) {\n\t\t\tlastEvent = event.index;\n\t\t\tconst row = document.getElementById(\"event-log\").insertRow(0);\n\n\t\t\trow.insertCell(0).textContent = event.name;\n\t\t\trow.insertCell(1).textContent = event.type;\n\n\t\t\tconst cell = row.insertCell(2);\n\t\t\tif(event.isAvailable) {\n\t\t\t\tcell.textContent = \"available\";\n\t\t\t} else {\n\t\t\t\tcell.textContent = \"offline\";\n\t\t\t\trow.classList.add(\"error\");\n\t\t\t}\n\n\t\t\trow.insertCell(3).textContent = event.description;\n\t\t\trow.insertCell(4).textContent = new Date(event.time * 1000).toISOString();\n\t\t}\n\t});\n}", "function getAllEvents() {\n if (dbPromise) {\n dbPromise.then(function (db) {\n var transaction = db.transaction('EVENT_OS', \"readonly\");\n var store = transaction.objectStore('EVENT_OS');\n var request = store.getAll();\n return request;\n }).then(function (request) {\n displayOnMap(request);\n });\n }\n}", "function getEvents(){\nreturn events;\n}", "generateStubs() {\n this.classBuilder = ClassBuilder.fromDataObject(require(`./stubs-data/data_server.json`), typeHints);\n\n const events = require('./stubs-data/events_server.json');\n events.push(...require('./stubs-data/events_modules.json'));\n\n this.eventSystem = new EventSystem(this.classBuilder, events);\n }", "function initializeRows() {\n eventContainer.empty();\n var eventsToAdd = [];\n for (var i = 0; i < events.length; i++) {\n eventsToAdd.push(createNewRow(events[i]));\n }\n eventContainer.append(eventsToAdd);\n }", "function initializeEvents(){\n var images = getImgArray(); \n images.forEach(addConcentrationHandler);\n}", "function makeEvent(item, refid) {\n var event = { 'refid': refid };\n event['etype'] = mapTag(item.tag);\n\n var tree = item.tree;\n for (i in tree) {\n var tag = tree[i].tag;\n var tag_lc = mapTag(tag);\n switch (tag) {\n case 'DATE':\n event['edate'] = formatDate(tree[i].data);\n case 'PLAC':\n event[tag_lc] = tree[i].data;\n break;\n case 'SOUR':\n if (typeof event[tag_lc] === 'undefined') {\n event[tag_lc] = [getSour(tree[i])];\n }\n else {\n event[tag_lc].push(getSour(tree[i]));\n }\n break;\n default:\n text = tag + \": \" + tree[i].data;\n if (typeof event.text === 'undefined') {\n event['text'] = text;\n }\n else {\n event['text'] += '; ' + text;\n }\n break;\n }\n }\n\n return event;\n}", "function _dispatchedExpectedEvents_(){this._dispatchedExpectedEvents$_LKQ=( new mx.collections.ArrayCollection());}", "function renderTMEvents(startDate, startTime, endDate, endTime, city, state, postalCode, countryCode, radius, maxEvents) {\n\n // We are expecting a valid date and city or else stop....TODO: return a valid error code\n if ((!startDate) || (!endDate) || (!city)) {\n alert(\"Fatal Error - no date or city passed into renderTMEvents\");\n }\n\n // Initialize time to 24 hours if not passed in\n if (!startTime) {\n startTime = \"00:00:00\";\n }\n\n if (!endTime) {\n endTime = \"23:59:59\";\n }\n\n if (!radius) {\n radius = 150;\n\n }\n\n // maximum number of events we want returned from Ticket Master event query\n if (!maxEvents) {\n maxEvents = \"30\";\n }\n\n // construct the TM localStartDateTime needed for the search event TM API\n var localStartDateTime = \"&localStartDateTime=\" + startDate + \"T\" + startTime + \",\" + endDate + \"T\" + endTime;\n //var endDateTime = \"&localStartEndDateTime=\" + endDate + \"T\" + endTime + \"Z\";\n\n // always looking for music events for this app.\n var classificationId = \"&classificationId=KZFzniwnSyZfZ7v7nJ\";\n\n //URL into TM API'\n var url = \"https://app.ticketmaster.com/discovery/v2/events.json?size=\" + maxEvents + \"&apikey=uFdFU8rGqFvKCkO5Jurt2VUNq9H1Wcsx\";\n var queryString = url + localStartDateTime + classificationId + countryCode;\n\n // construct the appropriate parameters needed for TM\n if (city) {\n queryString = queryString + \"&city=\" + city;\n }\n if (radius) {\n queryString = queryString + \"&radius=\" + radius;\n }\n if (postalCode) {\n queryString = queryString + \"&postalCode=\" + postalCode;\n }\n<<<<<<< HEAD\n if (state) {\n queryString = queryString + \"&state=\" + state;\n }\n\n // console log the queryString\n console.log(queryString);\n\n // make the AJAX call into TM\n $.ajax({\n type: \"GET\",\n url: queryString,\n async: true,\n dataType: \"json\",\n success: function (response) {\n // we are here if the AJAX call is successful\n console.log(response);\n var events = createEvents(response);\n return events;\n // console.log(TMEvents);\n },\n error: function (xhr, status, err) {\n // This time, we do not end up here!\n // TODO: return an error code for now just setTMEvent to empty\n TMEvents = \"\";\n console.log(err);\n }\n });\n }", "constructor() { \n \n ClientAddEventAllOfPayload.initialize(this);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserrename_column_clause.
visitRename_column_clause(ctx) { return this.visitChildren(ctx); }
[ "function _renameColumn(){\n self._visitingAlter = true;\n var table = self._queryNode.table;\n var result = [\"EXEC sp_rename '\"+\n self.visit(table.toNode())+'.'+self.visit(alter.nodes[0].nodes[0])+\"', \"+\n self.visit(alter.nodes[0].nodes[1])+', '+\n \"'COLUMN'\"\n ];\n self._visitingAlter = false;\n return result;\n }", "visitDrop_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModify_mv_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAdd_modify_drop_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitNew_column_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModify_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXml_column_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAdd_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSubstitutable_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitAdd_mv_log_column_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function _dropColumn(){\n self._visitingAlter = true;\n var table = self._queryNode.table;\n var result=[\n 'ALTER TABLE',\n self.visit(table.toNode())\n ];\n var columns='DROP COLUMN '+self.visit(alter.nodes[0].nodes[0]);\n for (var i= 1,len=alter.nodes.length; i<len; i++){\n var node=alter.nodes[i];\n assert(node.type=='DROP COLUMN',errMsg);\n columns+=', '+self.visit(node.nodes[0]);\n }\n result.push(columns);\n self._visitingAlter = false;\n return result;\n }", "visitParen_column_list(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitColumn_alias(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitModel_column_clauses(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitVirtual_column_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitXml_table_column(ctx) {\n\t return this.visitChildren(ctx);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EventItem This is an item that wraps a ZeitgeistItemInfo, which is in turn created from an event as returned by the Zeitgeist DBus API.
function EventItem (event, multi_select, journal_layout) { this._init (event, multi_select, journal_layout); }
[ "constructor() { \n \n OrderItemInformationEvent.initialize(this);\n }", "function Game_ItemEvent() {\n this.initialize.apply(this, arguments);\n}", "function onItemDetails(event) {\n // We want this to happen in a calendar window.\n var wm = Components.classes[\"@mozilla.org/appshell/window-mediator;1\"]\n .getService(Components.interfaces.nsIWindowMediator);\n var calWindow = wm.getMostRecentWindow(\"collab:main\");\n calWindow.modifyEventWithDialog(event.target.item, null, true);\n}", "function makeEvent(item, refid) {\n var event = { 'refid': refid };\n event['etype'] = mapTag(item.tag);\n\n var tree = item.tree;\n for (i in tree) {\n var tag = tree[i].tag;\n var tag_lc = mapTag(tag);\n switch (tag) {\n case 'DATE':\n event['edate'] = formatDate(tree[i].data);\n case 'PLAC':\n event[tag_lc] = tree[i].data;\n break;\n case 'SOUR':\n if (typeof event[tag_lc] === 'undefined') {\n event[tag_lc] = [getSour(tree[i])];\n }\n else {\n event[tag_lc].push(getSour(tree[i]));\n }\n break;\n default:\n text = tag + \": \" + tree[i].data;\n if (typeof event.text === 'undefined') {\n event['text'] = text;\n }\n else {\n event['text'] += '; ' + text;\n }\n break;\n }\n }\n\n return event;\n}", "function getEvent(item, refid) {\n var event = { 'refid': refid };\n var tree = item.tree;\n for (i in tree) {\n var tag = tree[i].tag;\n var tag_lc = mapTag(tag);\n switch (tag) {\n case 'TYPE':\n event['etype'] = tree[i].data;\n break;\n case 'DATE':\n event['edate'] = formatDate(tree[i].data);\n case 'PLAC':\n event[tag_lc] = tree[i].data;\n break;\n case 'SOUR':\n if (typeof event[tag_lc] === 'undefined') {\n event[tag_lc] = [getSour(tree[i])];\n }\n else {\n event[tag_lc].push(getSour(tree[i]));\n }\n break;\n case 'NOTE':\n event[tag_lc] = cleanPointer(tree[i].data);\n break;\n default:\n text = tag + \": \" + tree[i].data;\n if (typeof event.text === 'undefined') {\n event['text'] = text;\n }\n else {\n event['text'] += '; ' + text;\n }\n break;\n }\n }\n\n return event;\n}", "function ItemToXMLEntry(aItem, aCalendar, aAuthorEmail, aAuthorName) {\n let selfIsOrganizer = (!aItem.organizer ||\n aItem.organizer.id == \"mailto:\" + aCalendar.googleCalendarName);\n\n function addExtendedProperty(aName, aValue) {\n if (!selfIsOrganizer || !aValue) {\n // We can't set extended properties if we are not the organizer,\n // discard. Also, if the value is null/false, we can delete the\n // extended property by not adding it.\n return;\n }\n let gdExtendedProp = document.createElementNS(gdNS, \"extendedProperty\");\n gdExtendedProp.setAttribute(\"name\", aName);\n gdExtendedProp.setAttribute(\"value\", aValue || \"\");\n entry.appendChild(gdExtendedProp);\n }\n\n if (!aItem) {\n throw new Components.Exception(\"\", Components.results.NS_ERROR_INVALID_ARG);\n }\n\n const kEVENT_SCHEMA = \"http://schemas.google.com/g/2005#event.\";\n\n // Document creation\n let document = cal.xml.parseString('<entry xmlns=\"' + atomNS + '\" xmlns:gd=\"' + gdNS + '\" xmlns:gCal=\"' + gcalNS + '\"/>');\n let entry = document.documentElement;\n\n // Helper functions\n function elemNS(ns, name) document.createElementNS(ns, name);\n function addElemNS(ns, name, parent) (parent || entry).appendChild(elemNS(ns, name));\n\n // Basic elements\n let kindElement = addElemNS(atomNS, \"category\");\n kindElement.setAttribute(\"scheme\", \"http://schemas.google.com/g/2005#kind\");\n kindElement.setAttribute(\"term\", \"http://schemas.google.com/g/2005#event\");\n\n let titleElement = addElemNS(atomNS, \"title\");\n titleElement.setAttribute(\"type\", \"text\");\n titleElement.textContent = aItem.title;\n\n // atom:content\n let contentElement = addElemNS(atomNS, \"content\");\n contentElement.setAttribute(\"type\", \"text\");\n contentElement.textContent = aItem.getProperty(\"DESCRIPTION\") || \"\";\n\n // atom:author\n let authorElement = addElemNS(atomNS, \"author\");\n addElemNS(atomNS, \"name\", authorElement).textContent = aAuthorName || aAuthorEmail;\n addElemNS(atomNS, \"email\", authorElement).textContent = aAuthorEmail;\n\n // gd:transparency\n let transpElement = addElemNS(gdNS, \"transparency\");\n let transpValue = aItem.getProperty(\"TRANSP\") || \"opaque\";\n transpElement.setAttribute(\"value\", kEVENT_SCHEMA + transpValue.toLowerCase());\n\n // gd:eventStatus\n let status = aItem.status || \"confirmed\";\n if (status == \"CANCELLED\") {\n // If the status is canceled, then the event will be deleted. Since the\n // user didn't choose to delete the event, we will protect him and not\n // allow this status to be set\n throw new Components.Exception(\"\",\n Components.results.NS_ERROR_LOSS_OF_SIGNIFICANT_DATA);\n } else if (status == \"NONE\") {\n status = \"CONFIRMED\";\n }\n addElemNS(gdNS, \"eventStatus\").setAttribute(\"value\", kEVENT_SCHEMA + status.toLowerCase());\n\n // gd:where\n addElemNS(gdNS, \"where\").setAttribute(\"valueString\", aItem.getProperty(\"LOCATION\") || \"\");\n\n // gd:who\n if (cal.getPrefSafe(\"calendar.google.enableAttendees\", false)) {\n // XXX Only parse attendees if they are enabled, due to bug 407961\n\n let attendees = aItem.getAttendees({});\n if (aItem.organizer) {\n // Taking care of the organizer is the same as taking care of any other\n // attendee. Add the organizer to the local attendees list.\n attendees.push(aItem.organizer);\n }\n\n const attendeeStatusMap = {\n \"REQ-PARTICIPANT\": \"required\",\n \"OPT-PARTICIPANT\": \"optional\",\n \"NON-PARTICIPANT\": null,\n \"CHAIR\": null,\n\n \"NEEDS-ACTION\": \"invited\",\n \"ACCEPTED\": \"accepted\",\n \"DECLINED\": \"declined\",\n \"TENTATIVE\": \"tentative\",\n \"DELEGATED\": \"tentative\"\n };\n\n for each (let attendee in attendees) {\n if (attendee.userType && attendee.userType != \"INDIVIDUAL\") {\n // We can only take care of individuals.\n continue;\n }\n\n let xmlAttendee = addElemNS(gdNS, \"who\");\n\n // Strip \"mailto:\" part\n xmlAttendee.setAttribute(\"email\", attendee.id.replace(/^mailto:/, \"\"));\n\n if (attendee.isOrganizer) {\n xmlAttendee.setAttribute(\"rel\", kEVENT_SCHEMA + \"organizer\");\n } else {\n xmlAttendee.setAttribute(\"rel\", kEVENT_SCHEMA + \"attendee\");\n }\n\n if (attendee.commonName) {\n xmlAttendee.setAttribute(\"valueString\", attendee.commonName);\n }\n\n if (attendeeStatusMap[attendee.role]) {\n let attendeeTypeElement = addElemNS(gdNS, \"attendeeType\", xmlAttendee);\n let attendeeTypeValue = kEVENT_SCHEMA + attendeeStatusMap[attendee.role];\n attendeeTypeElement.setAttribute(\"value\", attendeeTypeValue);\n }\n\n if (attendeeStatusMap[attendee.participationStatus]) {\n let attendeeStatusElement = addElemNS(gdNS, \"attendeeStatus\", xmlAttendee);\n let attendeeStatusValue = kEVENT_SCHEMA + attendeeStatusMap[attendee.participationStatus];\n attendeeStatusElement.setAttribute(\"value\", attendeeStatusValue);\n }\n }\n }\n\n // Don't notify attendees by default. Use a preference in case the user\n // wants this to be turned on.\n let notify = cal.getPrefSafe(\"calendar.google.sendEventNotifications\", false);\n addElemNS(gcalNS, \"sendEventNotifications\").setAttribute(\"value\", notify ? \"true\" : \"false\");\n\n // gd:when\n let duration = aItem.endDate.subtractDate(aItem.startDate);\n let whenElement;\n if (!aItem.recurrenceInfo) {\n // gd:when isn't allowed for recurring items where gd:recurrence is set\n whenElement = addElemNS(gdNS, \"when\");\n whenElement.setAttribute(\"startTime\", cal.toRFC3339(aItem.startDate));\n whenElement.setAttribute(\"endTime\", cal.toRFC3339(aItem.endDate));\n }\n\n // gd:reminder\n let alarms = aItem.getAlarms({});\n let actionMap = {\n DISPLAY: \"alert\",\n EMAIL: \"email\",\n SMS: \"sms\"\n };\n if (selfIsOrganizer) {\n for (let i = 0; i < 5 && i < alarms.length; i++) {\n let alarm = alarms[i];\n let gdReminder;\n if (aItem.recurrenceInfo) {\n // On recurring items, set the reminder directly in the <entry> tag.\n gdReminder = addElemNS(gdNS, \"reminder\");\n } else {\n // Otherwise, its a child of the gd:when element\n gdReminder = addElemNS(gdNS, \"reminder\", whenElement);\n }\n if (alarm.related == alarm.ALARM_RELATED_ABSOLUTE) {\n // Setting an absolute date can be done directly. Google will take\n // care of calculating the offset.\n gdReminder.setAttribute(\"absoluteTime\", cal.toRFC3339(alarm.alarmDate));\n } else {\n let alarmOffset = alarm.offset;\n if (alarm.related == alarm.ALARM_RELATED_END) {\n // Google always uses an alarm offset related to the start time\n // for relative alarms.\n alarmOffset = alarmOffset.clone();\n alarmOffset.addDuration(duration);\n }\n\n gdReminder.setAttribute(\"minutes\", -alarmOffset.inSeconds / 60);\n gdReminder.setAttribute(\"method\", actionMap[alarm.action] || \"alert\");\n }\n }\n } else if (alarms.length) {\n // We need to reset this so the item gets returned correctly.\n aItem.clearAlarms();\n }\n\n // gd:extendedProperty (alarmLastAck)\n addExtendedProperty(\"X-MOZ-LASTACK\", cal.toRFC3339(aItem.alarmLastAck));\n\n // XXX While Google now supports multiple alarms and alarm values, we still\n // need to fix bug 353492 first so we can better take care of finding out\n // what alarm is used for snoozing.\n\n // gd:extendedProperty (snooze time)\n let itemSnoozeTime = aItem.getProperty(\"X-MOZ-SNOOZE-TIME\");\n let icalSnoozeTime = null;\n if (itemSnoozeTime) {\n // The propery is saved as a string, translate back to calIDateTime.\n icalSnoozeTime = cal.createDateTime();\n icalSnoozeTime.icalString = itemSnoozeTime;\n }\n addExtendedProperty(\"X-MOZ-SNOOZE-TIME\", cal.toRFC3339(icalSnoozeTime));\n\n // gd:extendedProperty (snooze recurring alarms)\n let snoozeValue = \"\";\n if (aItem.recurrenceInfo) {\n // This is an evil workaround since we don't have a really good system\n // to save the snooze time for recurring alarms or even retrieve them\n // from the event. This should change when we have multiple alarms\n // support.\n let snoozeObj = {};\n let enumerator = aItem.propertyEnumerator;\n while (enumerator.hasMoreElements()) {\n let prop = enumerator.getNext().QueryInterface(Components.interfaces.nsIProperty);\n if (prop.name.substr(0, 18) == \"X-MOZ-SNOOZE-TIME-\") {\n // We have a snooze time for a recurring event, add it to our object\n snoozeObj[prop.name.substr(18)] = prop.value;\n }\n }\n snoozeValue = JSON.stringify(snoozeObj);\n }\n // Now save the snooze object in source format as an extended property. Do\n // so always, since its currently impossible to unset extended properties.\n addExtendedProperty(\"X-GOOGLE-SNOOZE-RECUR\", snoozeValue);\n\n // gd:visibility\n let privacy = aItem.privacy || \"default\";\n addElemNS(gdNS, \"visibility\").setAttribute(\"value\", kEVENT_SCHEMA + privacy.toLowerCase());\n\n // categories\n // Google does not support categories natively, but allows us to store data\n // as an \"extendedProperty\", so we do here\n addExtendedProperty(\"X-MOZ-CATEGORIES\",\n categoriesArrayToString(aItem.getCategories({})));\n\n // gd:recurrence\n if (aItem.recurrenceInfo) {\n try {\n const kNEWLINE = \"\\r\\n\";\n let icalString;\n let recurrenceItems = aItem.recurrenceInfo.getRecurrenceItems({});\n\n // Dates of the master event\n let startTZID = aItem.startDate.timezone.tzid;\n let endTZID = aItem.endDate.timezone.tzid;\n icalString = \"DTSTART;TZID=\" + startTZID\n + \":\" + aItem.startDate.icalString + kNEWLINE\n + \"DTEND;TZID=\" + endTZID\n + \":\" + aItem.endDate.icalString + kNEWLINE;\n\n // Add all recurrence items to the ical string\n for each (let ritem in recurrenceItems) {\n let prop = ritem.icalProperty;\n if (calInstanceOf(ritem, Components.interfaces.calIRecurrenceDate)) {\n // EXDATES require special casing, since they might contain\n // a TZID. To avoid the need for conversion of TZID strings,\n // convert to UTC before serialization.\n prop.valueAsDatetime = ritem.date.getInTimezone(UTC());\n }\n icalString += prop.icalString;\n }\n\n // Put the ical string in a <gd:recurrence> tag\n addElemNS(gdNS, \"recurrence\").textContent = icalString + kNEWLINE;\n } catch (e) {\n cal.ERROR(\"[calGoogleCalendar] Error: \" + e);\n }\n }\n\n // gd:originalEvent\n if (aItem.recurrenceId) {\n let originalEvent = addElemNS(gdNS, \"originalEvent\");\n originalEvent.setAttribute(\"id\", aItem.parentItem.id);\n\n let origWhen = addElemNS(gdNS, \"when\", originalEvent)\n origWhen.setAttribute(\"startTime\", cal.toRFC3339(aItem.recurrenceId.getInTimezone(cal.UTC())));\n }\n\n // While it may sometimes not work out, we can always try to set the uid and\n // sequence properties\n let sequence = aItem.getProperty(\"SEQUENCE\");\n if (sequence) {\n addElemNS(gcalNS, \"sequence\").setAttribute(\"value\", sequence);\n }\n addElemNS(gcalNS, \"uid\").setAttribute(\"value\", aItem.id || \"\");\n\n // XXX Google currently has no priority support. See\n // http://code.google.com/p/google-gdata/issues/detail?id=52\n // for details.\n\n return document;\n}", "get parentItem()\n\t{\n\t\t//dump(\"get parentItem: title:\"+this.title);\n\t\tif ((!this._parentItem) && (!this._newParentItem)) {\n\t\t\tthis._parenItem = this;\n\t\t\tthis._calEvent.parentItem = this;\n\t\t}\n\t\treturn this._calEvent.parentItem;\n\t}", "function ViewItem(viewItemDescription){\n inflateViewItem(this, viewItemDescription);\n}", "async handleOrderItemCreatedEvent(data={}) {\n let {orderItem,trackId} = data,\n logger = Logger.create(\"handleOrderItemCreatedEvent\", trackId);\n\n logger.info(\"enter\", {orderItem});\n\n // @WARNING : We do not modify stock for orders items generated\n // from list subscriptions.\n if(orderItem.listSubscription) {return;}\n\n // Decrement product stock.\n logger.debug(\"decrement stock for product\", orderItem.product);\n\n this.collection.findOneAndUpdate({\n _id: Mongo.toObjectID(orderItem.product),\n deletedAt: {$type: \"null\"}\n }, {$inc: {stock: -(orderItem.quantity)}}, {returnOriginal: false})\n .then((result) => {\n let product = result.value;\n\n logger.debug(\"product stock updated\", product);\n\n // Emit to users\n Socket.shared.emit(\"product:updated\", {\n result: FindHandler.Model.format(product),\n updatedKeys: [\"stock\"]\n });\n });\n }", "function Item(idName, idAliases, deText, plText, itemGet, itemAct, uses, reacts)\n{\n\tthis.ident = idName;\n\tthis.alias = idAliases;\n\tthis.descText = deText;\n\tthis.placeText = plText;\n\tthis.canGet = itemGet;\n\tthis.canUse = itemAct;\n\tthis.itemUse = uses;\n\tthis.itemReaction = reacts;\n}", "function Item () {\n\tthis.name = \"\";\n\tthis.relatedItems = [];\n\tthis.relationTypes = [];\n}", "function handleEditItem() {\n $('.js-shopping-list').on('input', '.js-shopping-item', function(event) {\n let itemIndex = getItemIndexFromElement(event.currentTarget); //assigning the index of the the editted item to itemIndex\n let updatedItem = STORE.items[itemIndex];\n updatedItem.name = event.currentTarget.innerHTML;\n $(event.currentTarget).blur(renderShoppingList())\n //renderShoppingList();\n });\n}", "function addNewItem(product) {\n var item = orderItemType.createInstance();\n item.order = this;\n item.product = product;\n this.orderItems.push(item);\n return item;\n }", "function myAgendaDropHandler(eventObj) {\n // Get ID of the agenda item from the event object\n var agendaId = eventObj.data.agendaId;\n // date agenda item was dropped onto\n var date = eventObj.data.calDayDate;\n // Pull agenda item from calendar\n var agendaItem = jfcalplugin.getAgendaItemById(\"#mycal\", agendaId);\n alert(\"You dropped agenda item \" + agendaItem.title +\n \" onto \" + date.toString() + \". Here is where you can make an AJAX call to update your database.\");\n }", "function onClickOid(e)\n{\n\tvar row = this.data[0];\n\tvar item = convertOid(row[0],row[1]);\n\t//if (item)\n\t{\n\t\titemlist.appendData(item);\n\t\tEvent.element(e).setStyle('background-color: #ACCEDE');\n\t}\n}", "function eventDropped(date, externalEvent) {\n var event_object;\n var copiedEventObject;\n var duration = 60;\n var newId = getNewID();\n maxEventID += 1;\n var endDate = date.clone().add(1, 'h');\n event_object = $(externalEvent).data('event');\n event_object.description = $('#txtExternalEventDescription').val();\n event_object.title = $('#txtExternalEventTitle').val();\n copiedEventObject = $.extend({}, event_object);\n copiedEventObject.start = date;\n copiedEventObject.id = maxEventID;\n copiedEventObject.end = endDate;\n copiedEventObject.allDay = false;\n copiedEventObject.placeID = place.place_id;\n copiedEventObject.topic = event_object.topic;\n copiedEventObject.description = event_object.description;\n console.log(copiedEventObject);\n addNewEvent(copiedEventObject);\n place = \"\";\n}", "emitCreatedPublishingItem(publishingItem) {\n publishNamespace.emit(createdPublishingItemEvent, publishingItem);\n }", "function Item ( db, id, description, equipType, strength ) {\n Thing.call( this, db, \"items\", id, description );\n this.equipType = equipType || \"none\";\n this.strength = strength || 0;\n this.name = id;\n}", "function addItem(item) {\n item.order = this;\n var items = this.orderItems;\n if (items.indexOf(item) == -1) {\n items.push(item);\n }\n }", "onDropItem(aItem) {\n // method that may be overridden by derived bindings...\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates the end date based on the event that is passed in
updateEnd(event) { this.setState({ startDate: this.state.startDate, endDate: event.target.value }); this.props.updateDate(event.target.value, 'end'); }
[ "function recurrencend(event)\r\n{\r\n var rec_end = a.valueof(\"$comp.rec_end\");\r\n\r\n // Automatische Erkennung, was gewollt ist\r\n if (rec_end == \"\")\r\n {\r\n if (a.valueofObj(\"$comp.rec_end_count\") != \"\")\r\n rec_end = \"Endet nach Anzahl Terminen\";\r\n else if (a.valueofObj(\"$comp.rec_end_date\") != \"\")\r\n rec_end = \"Endet am\";\r\n }\r\n\r\n if (rec_end == \"\" || rec_end == \"Kein Enddatum\")\r\n {\r\n // Nichts\r\n }\r\n else if (rec_end == \"Endet nach Anzahl Terminen\")\r\n {\r\n event[calendar.RRULE][0] += (\";COUNT=\" + a.valueofObj(\"$comp.rec_end_count\"));\r\n }\r\n else if (rec_end == \"Endet am\")\r\n {\r\n var dat = a.valueofObj(\"$comp.rec_end_date\");\r\n var start = a.valueofObj(\"$comp.start_date\");\r\n var localTime = date.longToDate(dat, \"yyyyMMdd\") + date.longToDate(start, \"HHmmss\");\r\n var utcTime = date.dateToLong(localTime, \"yyyyMMddHHmmss\");\r\n event[calendar.RRULE][0] += (\";UNTIL=\" + date.longToDate(utcTime, \"yyyyMMdd\\'T\\'HHmmss\\'Z\\'\", \"UTC\"));\r\n }\r\n\r\n}", "function edit(event){\n\n // format the start and end dates\n start = event.start.format('YYYY-MM-DD HH:mm:ss');\n if(event.end){\n end = event.end.format('YYYY-MM-DD HH:mm:ss');\n }else{\n end = start;\t// when start and end dates are the same\n }\n\n // package the data to be sent to the DB for update\n id = event.id;\n\n Event = [];\n Event[0] = id;\n Event[1] = start;\n Event[2] = end;\n\n // AJAX call to DB\n $.ajax({\n url: 'editTrainingDate.php',\n type: \"POST\",\n data: {Event:Event},\n success: function(res) {\n if(res == 'OK'){\n alert('Saved');\n }else{\n alert(res);\n alert('Could not be saved. try again.');\n }\n }\n });\n}", "function setProjectEndDate(a_date)\r\n{\r\n\tdocument.getElementById(\"project_end_date\").innerHTML = a_date;\r\n}", "updateStart(event) {\n this.setState({\n startDate: event.target.value,\n endDate: this.state.endDate\n });\n this.props.updateDate(event.target.value, 'start');\n }", "function usfEventDateString(objStartDate, objEndDate) {\n\t\tvar eventDateString = \"\";\n\t\t\n\t\tvar intEndDayNumber = objEndDate.dayNumber();\n\t\tvar intStartDayNumber = objStartDate.dayNumber();\n\t\t\n\t\tif (intEndDayNumber > intStartDayNumber) {\n\t\t\teventDateString += usfEventDateSingle(objStartDate);\n\t\t\teventDateString += ' - ';\n\t\t\teventDateString += usfEventDateSingle(objEndDate);\n\t\t} else {\n\t\t\teventDateString = usfEventDateSingle(objStartDate);\n\t\t}\n\t\treturn eventDateString;\n\t}", "function bookingAfter(e) {\n // Do not allow viewing bookings in the past\n var now = Math.ceil(new Date().getTime() / 1000);\n if(closeDateTime - 86400 < now)\n document.getElementById(\"bookingBefore\").classList.add(\"show\");\n\n // Advance the unix time by one day\n openDateTime += 86400;\n closeDateTime += 86400;\n vmMainScreen.now = new Date(vmMainScreen.now.getFullYear(), vmMainScreen.now.getMonth(), vmMainScreen.now.getDate() + 1, vmMainScreen.now.getHours(), vmMainScreen.now.getMinutes());\n refreshBooking();\n}", "function setCalendarAppts() {\n\n var data = getCalendarData();\n var columnHeaders = getColumnHeaders();\n\n // column headers \n var isCompleteColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_DONE);\n var taskColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_TASK);\n var dateColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_DUEDATE);\n var googleCalColumnId = columnHeaders.indexOf(CONFIG_COLUMNS_GOOGLECALENDARID); \n\n // find events with dates\n for (var i = 1; i < data.length; i++) {\n\n\n // if date but not google calendar entry, add it\n if (!data[i][isCompleteColumnId]) {\n var event;\n if (data[i][dateColumnId] && !data[i][googleCalColumnId]) {\n\n Logger.log('Add Task: ' + data[i][taskColumnId]);\n \n var eventDate = data[i][dateColumnId];\n var eventTimeHour = Utilities.formatDate(eventDate, CONFIG_TIMEZONE, 'HH');\n var eventTimeMinute = Utilities.formatDate(eventDate, CONFIG_TIMEZONE, 'mm');\n\n // always add \"today\" if less than today\n var isOverdue = false;\n if (eventDate.getDate() < new Date().getDate()) {\n eventDate.setDate(new Date().getDate());\n isOverdue = true;\n }\n\n // create event\n event = CalendarApp.getDefaultCalendar().createAllDayEvent(\"TASK: \" + data[i][taskColumnId], eventDate);\n \n // if event is overdue\n if (isOverdue && CONFIG_GCAL_OVERDUE_COLOUR != null) {\n event.setColor(CONFIG_GCAL_OVERDUE_COLOUR);\n }\n \n // WIP - set time if time exists in entry\n if (eventTimeHour + \":\" + eventTimeMinute != \"00:00\") {\n eventDate.setHours(eventTimeHour);\n eventDate.setMinutes(eventTimeMinute);\n event.setTime(eventDate, eventDate); // set correct time here\n }\n \n // add the event ID to the spreadsheet\n SpreadsheetApp.openById(CONFIG_SHEETID).getSheetByName(CONFIG_SHEET_TODO).getRange(i + 1, googleCalColumnId + 1).setValue(event.getId());\n\n }\n else if (data[i][dateColumnId] && data[i][googleCalColumnId]) {\n\n Logger.log('Modify Task: ' + data[i][taskColumnId]);\n \n // fetch the event using the ID\n event = CalendarApp.getDefaultCalendar().getEventById(data[i][googleCalColumnId]);\n\n // update time if time is set in due date \n var eventSheetDate = data[i][dateColumnId];\n var eventTimeHour = Utilities.formatDate(eventSheetDate, CONFIG_TIMEZONE, 'HH');\n var eventTimeMinute = Utilities.formatDate(eventSheetDate, CONFIG_TIMEZONE, 'mm');\n \n // auto-advance to today in CALENDAR (not sheet)\n if (eventSheetDate < new Date()) {\n event.setAllDayDate(new Date());\n \n // change color if event is overdue\n if (CONFIG_GCAL_OVERDUE_COLOUR != null) {\n event.setColor(CONFIG_GCAL_OVERDUE_COLOUR);\n }\n\n }\n else\n {\n // update calendar date to revised sheet date\n event.setAllDayDate(eventSheetDate);\n }\n\n // update title\n event.setTitle(data[i][taskColumnId]);\n eventDate = event.getStartTime();\n if (eventTimeHour + \":\" + eventTimeMinute != \"00:00\") {\n eventDate.setHours(eventTimeHour);\n eventDate.setMinutes(eventTimeMinute);\n event.setTime(eventDate, eventDate); // set correct time here\n }\n\n\n\n }\n\n }\n\n }\n\n}", "function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }", "_getSearchEndTime() {\n const now = new Date();\n const endDate = new Date();\n endDate.setHours(12);\n endDate.setMinutes(0);\n\n if (endDate < now) {\n endDate.setHours(now.getHours() + 1);\n endDate.setMinutes(now.getMinutes());\n }\n return endDate;\n }", "function stOrderRealRecptEndDateQuery(dp){\r\n\t$(\"#realRecptDateEnd\").attr('title','');\r\n\t$(\"#realRecptDateEnd\").removeClass('errorInput');\r\n\tvar realRecptBeginDate=$(\"#realRecptDateBegin\").val();\r\n\tvar realRecptEndDate= dp.cal.getNewDateStr();\r\n\tif(realRecptBeginDate){\t\t\r\n\t\tvar subDays=getSubDays(realRecptBeginDate,realRecptEndDate);\r\n\t\tif(subDays<0){\r\n\t\t\t$(\"#realRecptDateEnd\").attr('title','结束日期小于开始日期');\r\n\t\t\t$(\"#realRecptDateEnd\").addClass('errorInput');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t} \r\n}", "_addDate() {\n const valueLink = this.props.valueLink;\n const value = valueLink.value || {};\n const slots = (value.slots || []).slice();\n const start = this.state.start.getTime();\n const end = start + this.state.duration;\n\n // Store the timeslot state as seconds, not ms\n slots.push([start / 1000, end / 1000]);\n\n value.slots = slots;\n valueLink.requestChange(value);\n }", "function trackMapGotoLastEventDate()\n{\n _resetCalandarDates();\n trackMapClickedUpdateAll();\n}", "function DoorEventPeriod(start_event, end_event) {\n this.startEvent = start_event; \n this.endEvent = end_event;\n}", "function handleDiliveryDateChange(e) {\n setDeliveryDate(e.target.value)\n setDrawer(false)\n }", "updateEventDate(date) {\n let currentData = cloneDeep(this.state.scenarioData);\n currentData[this.state.activeEntry].date = date;\n this.setState({ scenarioData: currentData });\n\n // Running plugin methods\n this.runPluginFunc(\"onUpdateEventDate\", [date]);\n }", "adjustAllEndTimes(index) {\n while(index >= 0) {\n this.adjustTaskEndTime(index);\n index--;\n }\n }", "function editEvent(){\n for(var i = 0; i < eventInput.length; i++){\n eventInput[i].addEventListener(\"change\", function(){\n this.previousElementSibling.lastElementChild.previousElementSibling.innerHTML = this.value;\n for(var i = 0; i < currentMonth.days.length; i++){\n if(clickedCell.firstChild.textContent === currentMonth.days[i].cell.firstChild.textContent){\n currentMonth.days[i].events.push(this.value);\n break;\n };\n }\n });\n }\n}", "function updateSuccess(shift) {\n var tempId = parseInt($('#shift_id').val());\n\n var eventlist = $(\"#calendar\").fullCalendar('clientEvents', tempId);\n\n event = eventlist[0];\n\n event.title = shift.position_title;\n event.description = shift.description;\n event.assigned_member = shift.assigned_member;\n event.assigned_member_id = shift.assigned_member_id;\n event.position_id = shift.position_id;\n event.start = shift.start;\n event.end = shift.end;\n event.id = shift.id;\n\n $('#calendar').fullCalendar('updateEvent', event);\n $('#shiftModal').modal('hide');\n }", "function populateCalPageEvents() {\n upcomingEvents.reverse();\n \n // Builds the array of Weekly Events that will later have the upcoming events pushed into it.\n // Setting the condition number (i <= 10) will change how many weekly events are added\n // to the cal. Special events will still display if they occur after this cut off.\n for (i = 0; i <= 90; i++) {\n\n var calEndDate = new Date();\n var weeklyCalEntry = calEndDate.setDate(calEndDate.getDate() + i);\n var weeklyCalEntryString = new Date(weeklyCalEntry);\n\n if (weeklyCalEntryString.getDay() === 1) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[0].eventName, 'eventDesc' : weeklyEvents[0].eventDesc, 'eventImgWide' : weeklyEvents[0].eventImgWide, 'eventTime' : weeklyEvents[0].eventTime, 'eventLink' : weeklyEvents[0].eventLink});\n }\n /*\n else if (weeklyCalEntryString.getDay() === 4) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[1].eventName, 'eventDesc' : weeklyEvents[1].eventDesc, 'eventImgWide' : weeklyEvents[1].eventImgWide, 'eventTime' : weeklyEvents[1].eventTime, 'eventLink' : weeklyEvents[1].eventLink});\n }\n */\n else if (weeklyCalEntryString.getDay() === 5) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[2].eventName, 'eventDesc' : weeklyEvents[2].eventDesc, 'eventImgWide' : weeklyEvents[2].eventImgWide, 'eventTime' : weeklyEvents[2].eventTime, 'eventLink' : weeklyEvents[2].eventLink});\n }\n\n else if (weeklyCalEntryString.getDay() === 6) {\n calWeeklyEventsList.push({'eventDate' : weeklyCalEntryString.toDateString(), 'eventName' : weeklyEvents[3].eventName, 'eventDesc' : weeklyEvents[3].eventDesc, 'eventImgWide' : weeklyEvents[3].eventImgWide, 'eventTime' : weeklyEvents[3].eventTime, 'eventLink' : weeklyEvents[3].eventLink});\n }\n }\n\n // Adds upcoming events to the weekly events\n for (i = 0; i <= upcomingEvents.length - 1; i++) {\n calWeeklyEventsList.push(upcomingEvents[i]);\n }\n\n // Sorts the cal events\n calWeeklyEventsList.sort(function(a,b){var c = new Date(a.eventDate); var d = new Date(b.eventDate); return c-d;});\n\n // Pushes Cal events into the cal page\n function buildCal(a) {\n calendarEvents.innerHTML = a;\n }\n\n // Removes Weekly if a special event is set to overide\n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n \n // If a Special Event is set to Override, remove the previous weekly entry\n if (calWeeklyEventsList[i].eventWklOvrd === 1) {\n calWeeklyEventsList.splice(i-1, 1);\n }\n // Else, Do nothing\n else {\n\n }\n }\n\n // Fixes the Special Event Dates for the cal and builds the Event entry. Push to the buildCal function.\n var formatedDate;\n var formatedTime;\n \n for (i = 0; i <= calWeeklyEventsList.length - 1; i++) {\n\n if (calWeeklyEventsList[i].eventTix !== undefined) {\n \n if (calWeeklyEventsList[i].eventTix != 'none') {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}); \n\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-4-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-4-xs\">REQUEST VIP</a><a href=\"' + calWeeklyEventsList[i].eventTix + '\" onclick=\"trackOutboundLink(' + \"'\" + calWeeklyEventsList[i].eventTix + \"'\" + '); return true;\" class=\"col col-4-xs \">BUY TICKETS</a></div></div><br><br>');\n }\n\n else {\n formatedDate = calWeeklyEventsList[i].eventDate.toDateString();\n formatedTime = calWeeklyEventsList[i].eventDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + formatedDate + ', ' + formatedTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"An event poster for ' + calWeeklyEventsList[i].eventArtist + ' performing at the Necto Nightclub in Ann Arbor, Michigan on ' + (calWeeklyEventsList[i].eventDate.getMonth() + 1) + '/' + calWeeklyEventsList[i].eventDate.getDate() + '/' + calWeeklyEventsList[i].eventDate.getFullYear() + '.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n\n else {\n buildCal(calendarEvents.innerHTML + '<div class=\"home-page-event-content fix\"><h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><span class=\"event-day\">' + calWeeklyEventsList[i].eventDate + ', ' + calWeeklyEventsList[i].eventTime + '</span><br><span class=\"event-name\">' + calWeeklyEventsList[i].eventName + '</span></a></h3><a href=\"' + calWeeklyEventsList[i].eventLink + '\"><img src=\"' + calWeeklyEventsList[i].eventImgWide + '\" alt=\"A image of ' + calWeeklyEventsList[i].eventName + ', a weekly event at the Necto Nightclub in Ann Arbor, Michigan.\"></a><p>' + calWeeklyEventsList[i].eventDesc + '</p><div class=\"row event-nav\"><a href=\"' + calWeeklyEventsList[i].eventLink + '\"class=\"col col-6-xs\">VIEW EVENT</a><a href=\"bottle-service-vip-reservations.html?=calpagelink\" class=\"col col-6-xs \">REQUEST VIP</a></div></div><br><br>');\n }\n }\n \n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
move the task from the tasks done list back to the to do list
moveTaskBack(task) { const index = this.state.tasksDone.indexOf(task); this.state.tasksDone.splice(index, 1); this.state.toDoTasks.unshift(task); this.setState({toDoTasks: this.state.toDoTasks, tasksDone: this.state.tasksDone }) }
[ "moveToTasksDone(task) {\n if (task !== \"\") {\n this.state.tasksDone.push(task);\n const index = this.state.toDoTasks.indexOf(task);\n this.state.toDoTasks.splice(index,1);\n this.setState({\n toDoTasks: this.state.toDoTasks,\n tasksDone: this.state.tasksDone\n })\n }\n }", "function moveTask(index, task, value) {\n $scope.schedule[$scope.currentUserId].splice(index, 1);\n if (value == 1) {\n $scope.schedule[$scope.currentUserId].splice(index - 1, 0, task);\n } else {\n $scope.schedule[$scope.currentUserId].splice(index + 1, 0, task);\n }\n saveUserSchedule();\n }", "removeFront() {\n this._taskArr.shift();\n /*\n if(this._taskArr.length === 1) {\n \n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[0];\n let next = this._taskArr[1];\n next.setStartTime(curr.startTime);\n this._taskArr.shift();\n }\n */\n }", "function reorderList(taskLists, destination, source) {\n const {sourceTasks, otherTasks} = taskLists\n const taskInUse = sourceTasks.splice(source.index, 1)\n sourceTasks.splice(destination.index, 0, taskInUse[0])\n sourceTasks.forEach(function(item, i) {\n item.index = i\n })\n props.getTasksNoDB([...otherTasks, ...sourceTasks])\n }", "removeBack() {\n this._taskArr.pop();\n /*\n if(this._taskArr.length === 1) {\n this._taskArr.pop();\n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[this._taskArr.length - 1];\n let prev = this._taskArr[this._taskArr.length - 2];\n prev.setEndTime(curr.endTime);\n }\n */\n }", "addToFront(task) {\n this._taskArr.unshift(task);\n if(this._taskArr.length > 1) {\n this.adjustAllStartTimes(1);\n }\n }", "function removeCompletedTasks() {\n let completedIds = [];\n for (let node of currentTaskHTML.childNodes) {\n if (node.completed) {\n completedIds.push(node.task.id);\n node.hide();\n setTimeout(() => {\n currentTaskHTML.removeChild(node);\n }, 200);\n \n }\n }\n\n for (let node of taskListHTML.childNodes) {\n if (node.completed) {\n completedIds.push(node.task.id);\n node.hide();\n setTimeout(() => {\n taskListHTML.removeChild(node);\n }, 200);\n \n }\n }\n completedIds.forEach((id) => {\n currentPomoSession.completeTask(id);\n });\n storePomoSession(currentPomoSession);\n\n }", "markAsDone(state, todoIndex) {\n let markedTodo = null;\n const markAndMove = () => {\n state.todos[todoIndex].isDone = !state.todos[todoIndex].isDone;\n markedTodo = state.todos.splice(todoIndex, 1);\n };\n\n let insertIndex = null;\n for (let i = 0; i < state.todos.length; i++) {\n if (state.todos[i].isDone) {\n insertIndex = i;\n break;\n }\n }\n\n if (!state.todos[todoIndex].isDone) {\n markAndMove();\n state.todos.push(...markedTodo);\n } else {\n markAndMove();\n if (insertIndex === 0) {\n state.todos.unshift(...markedTodo);\n } else if (insertIndex) {\n state.todos.splice(insertIndex, 0, ...markedTodo);\n } else {\n state.todos.push(...markedTodo);\n }\n } \n }", "function toTaskList() {\n $state.go('main.tasklist');\n }", "function deleteTask(){\n //DECLARE THE VARIABLE FOR THE POSITION OF THE TASK TO BE REMOVED\n var position;\n //LOOP THROUGH, GET POSITION, SPLICE FROM LIST\n for(var i = 0; i < this.tasks.length; i++){\n if(this.tasks[i]._id == id){\n position = this.tasks[i].position;\n this.tasks.splice(tasks[i], 1);\n }\n }\n\n //REMOVE THE ITEM FROM TASK LIST\n //IT IS ASYNC, NO WORRIES\n Task.remove({_id: id}, function(err){\n if(err) {\n console.log(err);\n res.render('error', {message: \"Could not update tasks\", error: err});\n }\n });\n\n //LOOP THROUGH, UPDATE THE TASKS WITH POSITION GREATER THAN DELETED\n for(var i = 0; i < this.tasks.length; i++){\n //IF THE POSITION IS GREATER THAN THE ONE DELETED\n if(this.tasks[i].position > position){\n\n //SUBTRACT ONE FROM THE POSITION TO MAKE UP FOR THE MISSING ONE\n var newPos = this.tasks[i].position - 1;\n\n //UPDATE EACH TASK\n Task.update({_id: this.tasks[i]._id }, { position: newPos }, function(err){\n if(err){\n console.log(err);\n res.render('error', {message: \"Could not update tasks\", error: err});\n }\n });\n }\n }\n\n //REDIRECT TO /\n res.redirect('/');\n }", "decrementTasksCompleted() {\n if (this.tasksCompleted > 0) {\n this.tasksCompleted -= 1;\n this.updateMinorLocalStorage();\n } // else I'm interested to see how you got there\n }", "function settasks() {\n\tvar nodeactivetasks = document.getElementById(\"main_middle_activetasks\");\n\tvar nodecompletedtasks = document.getElementById(\"main_middle_completedtasks\");\n\tremovechildren(nodeactivetasks);\n\tremovechildren(nodecompletedtasks);\n\n\tlistactivetasks.forEach(function(element) {\n\t\tnodeactivetasks.appendChild(element);\t\n\t})\n\n\tlistcompletedtasks.forEach(function(element) {\n\t\tnodecompletedtasks.appendChild(element);\n\t})\n\n\n}", "function deleteTask(){\n // get indx of tasks\n let mainTaskIndx = tasksIndxOf(delTask['colName'], delTask['taskId']);\n // del item\n tasks.splice(mainTaskIndx, 1);\n // close modal\n closeModal();\n // update board\n updateBoard();\n // update backend\n updateTasksBackend();\n}", "function removeCompleted(n){\n //get id of task element(input) from parent elements\n taskElement = n.parentElement.parentElement.parentElement;\n taskId = taskElement.childNodes[0].id;\n //find task instance using the array and the id(index)\n curr = Task.ALLTASKS[taskId]; \n curr.complete();\n taskElement.style.display = 'none';\n addCompletedToDisplay() \n drawPercentage();\n updateReward();\n}", "addToBack(task) {\n this._taskArr.push(task);\n }", "moveTodo(state, moveInfo) {\n const i = moveInfo.index;\n const iShift = moveInfo.direction === 'up' ? -1 : 1;\n\n const todoMover = () => {\n state.todos[i].isMoved = true;\n setTimeout(() => {\n state.todos[i + iShift].isMoved = false;\n }, 400);\n const todoToMove = state.todos.splice(i, 1);\n state.todos.splice(i + iShift, 0, ...todoToMove);\n };\n\n if (moveInfo.direction === 'up') {\n if (i > 0) {\n todoMover(); \n }\n } else if (i < state.todos.length - 1 && !state.todos[i + 1].isDone) {\n todoMover(); \n }\n }", "function delete_finished_todos(jquery_obj) {\n\tjquery_obj.find(\"div.project-content div.single-todo div.done\").parent().remove();\n\tsave_projects();\n}", "function handleDoneList(e) {\n const li = e.target.parentNode.parentNode;\n finishNoList.style.display = \"none\";\n handleCreateFinished(li.innerText);\n\n handleDelToDos(e);\n}", "addAtIndex(task, index) {\n if(index === 0) {\n this.addToFront(task);\n } else if(index === this._taskArr.length) {\n this.addToBack(task);\n } else if(index < this._taskArr.length) {\n this._taskArr.splice(index,0, task);\n this.adjustTaskStartTime(index + 1);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The canvas where the pages are drawn When the application is opened, creates the thumbnails for every file and renders them on the main page
async function createThumbnails() { //Hide thumbnails to show all of them at the same time and display loading icon document.getElementById('thumbnails').style.visibility = "hidden"; document.getElementById('loading').style.display = "block"; for (let fileIdx = 0; fileIdx < files.length; fileIdx++) { //Create a canvas for the file document.getElementById('thumbnails').innerHTML += `<canvas class="tempcanvas" id="canvas${fileIdx}"></canvas>`; //Defines the file path and download the file const filePath = PDF_FILES_DIRECTORY + files[fileIdx]; let pdf = await pdfjsLib.getDocument(filePath).promise; //Gets the title, date and filesize of the file let data = await pdf.getMetadata(); let title = data.info.Title; if (title.length > 17) { title = title.substr(0, 14) + '...'; } let creationDate = data.info.CreationDate; let filesize = ''; if (data.contentLength) filesize = getFilesize(data.contentLength); creationDate = `${creationDate.substr(2, 4)}/${creationDate.substr(6, 2)}/${creationDate.substr(4, 2)}` //Gets the first page of the file let page = await pdf.getPage(1); //Defines the page rendering settings let viewport = page.getViewport({ scale: 1 }); let canvasElement = document.getElementById(`canvas${fileIdx}`); let ctx = canvasElement.getContext('2d'); //Sets canvas dimensions canvasElement.height = viewport.height; canvasElement.width = viewport.width; let renderContext = { canvasContext: ctx, viewport: viewport }; //Renders the page on the canvas await page.render(renderContext).promise; //Makes an image of the canvas and creates a thumbnail of it let imgSrc = canvasElement.toDataURL(); let img = `<div class="thumbnail popup-open" data-popup="#pdf-popup" data-file-path="${filePath}"> <img class="thumbnail-img" src="${imgSrc}"></img> <p class="thumbnail-title">${title}</p> <div class="thumbnail-txt"> <p>${creationDate}</p> <p>${filesize}</p> </div> </div>`; document.getElementById('thumbnails').innerHTML += img; //Removes the canvas as it was used only for creating the thumbnail image document.getElementById(`canvas${fileIdx}`).remove(); } //Hide the loading icon and show the thumbnails document.getElementById('loading').style.display = "none"; document.getElementById('thumbnails').style.visibility = "visible"; }
[ "function renderImages() {\n\t\t$('.landing-page').addClass('hidden');\n\t\t$('.img-round').removeClass('hidden');\n\t\tupdateSrcs();\n\t\tcurrentOffset+=100;\n\t}", "function paginateCanvas(){\n\tcreateDev=\"\";\n\t$(\"#configContent\"+pageCanvas).css(\"cursor\",\"default\");\n $(\"#Magnify\").attr(\"title\",\"Zoom\");\n \tzoomButtonStatus = \"inactive\";\n\n//\tif(globalDeviceType != \"Mobile\"){\n autoResizeCanvas();\n// }\n\tfor(var i = 0;i < dynamicVar.length; i++){\n\t\tvar page = dynamicVar[i].split('_')[1];\n\t\tif(parseInt(page) == pageCanvas){\n\t\t\t$('#a'+page).addClass('active');\n\t\t\t$('#configContent'+page).show('slide', {direction: 'left'}, 1000);\n\t\t\t$('#miniMap'+page).show('slide', {direction: 'left'}, 1000);\n\t\t}else{\n\t\t\t$('#a'+page).removeClass('active');\n\t\t\t$('#configContent'+page).hide('slide', {direction: 'left'}, 1000);\n\t\t\t$('#miniMap'+page).hide('slide', {direction: 'left'}, 1000);\n\t\t}\n\t}\n\tif(globalInfoType != \"XML\"){\n\t\tsetJSONData();\n\t}\n\t/*-----kmmabignay-history global-----*/\n\tif(window['variableHistory'+pageCanvas]==undefined){\n\t\twindow['variableHistory'+pageCanvas] = new Array();\n\t}\n\t/*-----kmmabignay-configuration name global-----*/\n\tif(window['variableConfigName'+pageCanvas]==undefined){\n\t\twindow['variableConfigName'+pageCanvas] = new Array();\n\t}\n\t/*-------------------------------------------*/\n\tif(globalInfoType == \"JSON\"){\n\t\tvar devices = getDevicesNodeJSON();\n\t}else{\n\t\tvar devices = devicesArr;\n\t}\n\tif(devices != undefined || devices != null || devices != '' ){\n\t\tif(devices.length > 0){\n\t\t\t$(\"#trashBin\").show();\n\t\t}else{\n\t\t\t$(\"#trashBin\").hide();\n\t\t}\n\t}else{\n\t\t$(\"#trashBin\").hide();\n\t}\n\treCreateDock();\n\tdrawImage();\n//\tgreenRoulette2();\n}", "function displayImagesThumbnail()\n\t{\n\t\t// Stored action to know if user act during the process\n\t\tvar actionID = _actionID + 0;\n\n\t\tfunction cleanUp()\n\t\t{\n\t\t\tURL.revokeObjectURL(this.src);\n\t\t}\n\n\t\tfunction process()\n\t\t{\n\t\t\t// Stop here if we change page.\n\t\t\tif (actionID !== _actionID) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar nodes = jQuery('.img:lt(5)');\n\t\t\tvar load = 0;\n\t\t\tvar total = nodes.length;\n\n\t\t\t// All thumbnails are already rendered\n\t\t\tif (!total) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Work with current loaded files\n\t\t\tnodes.each(function(){\n\t\t\t\tvar self = jQuery(this);\n\n\t\t\t\tClient.getFile( self.data('path'), function( data ) {\n\t\t\t\t\t// Clean from memory...\n\t\t\t\t\tMemory.remove(self.data('path'));\n\t\t\t\t\tself.removeClass('img').addClass('thumb');\n\n\t\t\t\t\tvar url = getImageThumbnail( self.data('path'), data );\n\n\t\t\t\t\t// Display image\n\t\t\t\t\tif (url) {\n\t\t\t\t\t\tvar img = self.find('img:first').get(0);\n\t\t\t\t\t\tif (url.match(/^blob\\:/)){\n\t\t\t\t\t\t\timg.onload = img.onerror = img.onabort = cleanUp;\n\t\t\t\t\t\t}\n\t\t\t\t\t\timg.src = url;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Fetch next range.\n\t\t\t\t\tif ((++load) >= total) {\n\t\t\t\t\t\tsetTimeout( process, 4 );\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tprocess();\n\t}", "renderFileThumb() {\n if (!this.renderPreview) {\n this.resetFileThumb();\n return;\n }\n const fileThumb = this.dom.querySelector(\".file-details-thumbnail\");\n const fileType = this.dom.querySelector(\".file-details-type\");\n const fileBuffer = new Uint8Array(this.buffer);\n const type = isImage(fileBuffer);\n\n if (type && type !== \"image/tiff\" && fileBuffer.byteLength <= 512000) {\n // Most browsers don't support displaying TIFFs, so ignore them\n // Don't render images over 512,000 bytes\n const blob = new Blob([fileBuffer], {type: type}),\n url = URL.createObjectURL(blob);\n fileThumb.src = url;\n } else {\n this.resetFileThumb();\n }\n fileType.textContent = type ? type : detectFileType(fileBuffer)[0]?.mime ?? \"unknown\";\n }", "function setUpSingleViewHandler() {\r\n const temp = document.querySelector(\"#template\")\r\n document.querySelector('#paintTable').addEventListener('click', function (e) {\r\n if (e.target.getAttribute('id') == 'title') {\r\n document.querySelector(\".galleryList\").style.display = \"none\"\r\n document.querySelector(\".singleView\").style.display = \"block\"\r\n document.querySelector(\".galleryInfo\").style.display = \"none\"\r\n document.querySelector(\"#map\").style.display = \"none\"\r\n document.querySelector(\".paintings\").style.display = \"none\"\r\n document.querySelector(\"#plus\").style.display = \"none\"\r\n document.querySelector(\"#minus\").style.display = \"none\"\r\n temp.innerHTML = \"\"\r\n for (let p of paintings) {\r\n if (e.target.getAttribute('alt') == p.Title && e.target.getAttribute('class') == p.LastName) {\r\n //first populates the single painting\r\n const fig = document.createElement(\"figure\");\r\n const img = document.createElement(\"img\");\r\n img.setAttribute('src', \"https://res.cloudinary.com/funwebdev/image/upload/w_800/art/paintings/\" + p.ImageFileName);\r\n img.setAttribute('id', \"bigimage\")\r\n fig.appendChild(img);\r\n temp.appendChild(fig)\r\n //creates the large version of the painting view \r\n mod = document.querySelector('#large')\r\n mod.innerHTML = \"\"\r\n const modImg = document.createElement(\"img\");\r\n modImg.setAttribute('src', \"https://res.cloudinary.com/funwebdev/image/upload/w_1500/art/paintings/\" + p.ImageFileName);\r\n modImg.setAttribute('id', \"biggestImage\")\r\n mod.appendChild(modImg)\r\n //creates the figure caption for the single image \r\n const figCap = document.createElement(\"figcaption\");\r\n figCap.setAttribute(\"id\", \"info\")\r\n const title = document.createElement(\"h2\");\r\n title.textContent = p.Title;\r\n figCap.appendChild(title);\r\n const artist = document.createElement(\"h3\");\r\n if (p.FirstName == null) {\r\n artist.textContent = p.LastName;\r\n }\r\n else if (p.LastName == null) {\r\n artist.textContent = p.FirstName;\r\n }\r\n else {\r\n artist.textContent = p.FirstName + \" \" + p.LastName;\r\n }\r\n figCap.appendChild(artist);\r\n //populates the figure caption with all the painting info\r\n const ul = document.createElement(\"ul\")\r\n const l1 = document.createElement(\"li\");\r\n const l2 = document.createElement(\"li\");\r\n const l3 = document.createElement(\"li\");\r\n const l4 = document.createElement(\"li\");\r\n const l5 = document.createElement(\"li\");\r\n const l6 = document.createElement(\"li\");\r\n const l7 = document.createElement(\"li\");\r\n const l8 = document.createElement(\"li\");\r\n const a = document.createElement(\"a\");\r\n const l9 = document.createElement(\"li\");\r\n l1.textContent = \"Year of work: \" + p.YearOfWork;\r\n l2.textContent = \"Medium: \" + p.Medium;\r\n l3.textContent = \"Width: \" + p.Width;\r\n l4.textContent = \"Height: \" + p.Height;\r\n l5.textContent = \"Copyright: \" + p.CopyrightText;\r\n l6.textContent = \"Gallery Name: \" + p.GalleryName;\r\n l7.textContent = \"Gallery city: \" + p.GalleryCity;\r\n a.textContent = p.MuseumLink;\r\n a.setAttribute('href', p.MuseumLink)\r\n l8.setAttribute('id', 'link')\r\n l9.textContent = p.Description;\r\n l9.setAttribute('id', 'des')\r\n\r\n l8.appendChild(a)\r\n ul.appendChild(l1)\r\n ul.appendChild(l2)\r\n ul.appendChild(l3)\r\n ul.appendChild(l4)\r\n ul.appendChild(l5)\r\n ul.appendChild(l6)\r\n ul.appendChild(l7)\r\n ul.appendChild(l8)\r\n ul.appendChild(l9)\r\n //populates the primary colors in the fig caption\r\n figCap.appendChild(ul)\r\n for (let c of p.JsonAnnotations.dominantColors) {\r\n span = document.createElement('span')\r\n console.log(c.color.red)\r\n span.style.backgroundColor = \"rgb(\" + c.color.red + \",\" + c.color.green + \",\" + c.color.blue + \")\"\r\n span.setAttribute('title', \"Name: \" + c.name + \" HEX: \" + c.web)\r\n figCap.appendChild(span)\r\n }\r\n fig.appendChild(figCap)\r\n temp.appendChild(fig)\r\n\r\n }\r\n }\r\n }\r\n\r\n\r\n })\r\n }", "function setImagePage(){\r\n setPage('image-page');\r\n }", "function initScreenShotGallery(data)\n{\n\tif(!data.screenshots || !data.screenshots.length)\n\t\treturn;\n\n\tvar el=document.querySelector(\"#screenshot img\");\n\tvar screenIndex=0;\n\tel.classList.add('loading');\n\tel.src=data.screenshots[0].original_url;\n\tel.onload=function()\n\t{\n\t\tel.classList.add('fixed');\n\t\tel.classList.remove('loading');\n\t\tel.style=\"max-width:\"+pesSettings.max_screenshot_width+'px';\n\t}\n\n\tif (data.screenshots.length == 1)\n\t\treturn;\n\n\tvar gallery=document.getElementById('screenshot');\n\tgallery.classList.add('gallery');\n\tvar prev = document.createElement('span');\n\tprev.classList.add('prev');\n\tprev.innerHTML = '<span class=\"icon-left\"></span>';\n\tvar next = document.createElement('span');\n\tnext.classList.add('next');\n\tnext.innerHTML = '<span class=\"icon-right\"></span>';\n\tgallery.appendChild(prev);\n\tgallery.appendChild(next);\n\n\tvar indicator=document.createElement('div');\n\tgallery.appendChild(indicator);\n\tindicator.append.apply(indicator, data.screenshots.map(function(s)\n\t{\n\t\tvar a = document.createElement('a');\n\t\ta.href = s.original_url;\n\t\treturn a;\n\t}));\n\tindicator.children[0].classList.add('active');\n\tindicator.classList.add('indicator');\n\n\tprev.onclick=\n\tnext.onclick=function()\n\t{\n\t\tif(this.classList.contains('prev'))\n\t\t{\n\n\t\t\tif(screenIndex==0)\n\t\t\t\tscreenIndex=data.screenshots.length-1;\n\t\t\telse\n\t\t\t\tscreenIndex--;\n\t\t}\n\t\telse\n\t\t\tscreenIndex=(++screenIndex)%data.screenshots.length;\n\n\t\tArray.prototype.forEach.call(indicator.children,function(i)\n\t\t{\n\t\t\ti.classList.remove('active');\n\t\t});\n\t\tindicator.children[screenIndex].classList.add('active');\n\t\tel.classList.add('loading');\n\t\tel.src=data.screenshots[screenIndex].original_url;\n\t}\n}", "function setFigure(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\tvar mediaObj = element.data();\n\n\t\t\t\t$.each(mediaObj, function(media, path){\n\n\t\t\t\t\tvar num;\n\n\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\n\t\t\t\t\tif(!num)\n\t\t\t\t\t\tnum = 0;\n\n\t\t\t\t\tsizes[num] = path;\n\n\t\t\t\t});\n\n\t\t\t\tif(element.find('img').length == 0){\n\n\t\t\t\t\tvar prep = '<img src=\"' + sizes[currentMedia] + '\" alt=\"' + element.attr('title') + '\">';\n\n\t\t\t\t\tif($('>a', element).length == 0){\n\n\t\t\t\t\t\telement.append(prep);\n\n\t\t\t\t\t}else{\n\n\t\t\t\t\t\t$('>a', element).append(prep);\n\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}", "function createProcessingWindow(canvas) {\n\n }", "initializeThumbnails_() {\n const thumbnails = [];\n this.manager_\n .getThumbnails(this.currentLightboxGroupId_)\n .forEach((thumbnail) => {\n // Don't include thumbnails for ads, this may be subject to\n // change pending user feedback or ux experiments after launch\n if (thumbnail.element.tagName == 'AMP-AD') {\n return;\n }\n const thumbnailElement = this.createThumbnailElement_(thumbnail);\n thumbnails.push(thumbnailElement);\n });\n this.mutateElement(() =>\n thumbnails.forEach((thumbnailElement) =>\n this.gallery_.appendChild(thumbnailElement)\n )\n );\n }", "function mCreateCanvas() {\n createCanvas(...[...arguments]);\n pixelDensity(1);\n mPage = createGraphics(width, height, WEBGL);\n\tmPage.pixelDensity(1);\n}", "function photographersPage() {\n // RAZ of the tag's filters on logo's click\n const logo = document.getElementsByClassName(\"logo--photographer\")[0];\n logo.addEventListener(\"click\", function() {\n localStorage.removeItem(\"id\");\n }, true);\n // Redirect to home page, if there is no photographer's id in the local storage\n const id = localStorage.getStorage(\"id\");\n if (id === null) window.location.href = \"./index.html\";\n // Instanciate the pages renderer with the values\n const photographerPage = new PhotographersPage(getArraysJsonElement(photographers, \"id\", id)[0]);\n // Render the clickable tags list in the header\n photographerPage.renderPhotographerTags();\n // Render the header information\n photographerPage.renderHeaderInformation();\n // Render all the photographers's photos\n photographerPage.renderPhotographersCards(0);\n // Render the photographer's further information\n photographerPage.renderPhotographersFurtherInformations();\n // Prepare the contact modal\n photographerPage.initializeContactForm();\n // Prepare the photo modal\n photographerPage.initializePhotoLightboxModal();\n}", "function initPreviews()\r\n {\r\n // remove all previous events\r\n removeEventHandlers();\r\n\r\n // attach click events\r\n var $prev = $qtip.find(\".ilPreviewTooltipPrev\");\r\n var $next = $qtip.find(\".ilPreviewTooltipNext\");\r\n var $items = $qtip.find(\".ilPreviewItem\");\r\n var itemCount = $items.length;\r\n\r\n var currentIdx = -1;\r\n var previewSize = self.previewSize + 2; // add 2 because the image has a border\r\n\r\n /**\r\n * Show the preview image at the specified index.\r\n */\r\n function showIndex(index)\r\n {\r\n log(\"Preview.showIndex(): current=%s, idx=%s\", currentIdx, index);\r\n\r\n // same index as before?\r\n if (index == currentIdx)\r\n return;\r\n\r\n log(\"Preview.showIndex(%s)\", index);\r\n\r\n $items.hide();\r\n\r\n $item = $items.eq(index);\r\n var height = $item.children().height();\r\n $item.css(\"margin-top\", ((previewSize - height) / 2) + \"px\");\r\n $item.show();\r\n\r\n // more than one item?\r\n if (itemCount > 1)\r\n {\r\n $tooltip.qtip(\"api\").set(\"content.title\", self.texts.preview + \" \" + (index + 1) + \" / \" + itemCount);\r\n if (index < 1)\r\n $prev.addClass(\"ilPreviewDisabled\");\r\n else\r\n $prev.removeClass(\"ilPreviewDisabled\");\r\n\r\n if (index >= itemCount - 1)\r\n $next.addClass(\"ilPreviewDisabled\");\r\n else\r\n $next.removeClass(\"ilPreviewDisabled\");\r\n }\r\n else\r\n {\r\n $tooltip.qtip(\"api\").set(\"content.title\", self.texts.preview);\r\n }\r\n\r\n currentIdx = index;\r\n }\r\n\r\n /**\r\n * Show the next preview image.\r\n */\r\n function showNext()\r\n {\r\n if (currentIdx < itemCount - 1)\r\n showIndex(currentIdx + 1);\r\n }\r\n\r\n /**\r\n * Show the previous preview image.\r\n */\r\n function showPrevious()\r\n {\r\n if (currentIdx > 0)\r\n showIndex(currentIdx - 1);\r\n }\r\n\r\n /**\r\n * Handles the events when a key was released.\r\n */\r\n function handleKeyUp(e)\r\n {\r\n // key already pressed? only execute once\r\n if (e.type == \"keydown\")\r\n {\r\n if (isKeyPressed)\r\n {\r\n // prevent default if up or down arrow\r\n if (e.which == 38 || e.which == 40)\r\n e.preventDefault();\r\n\r\n return;\r\n }\r\n\r\n isKeyPressed = true;\r\n\r\n // which key was pressed?\r\n switch (e.which)\r\n {\r\n case 38: // up arrow key\r\n e.preventDefault();\r\n showPreviousPreview();\r\n break;\r\n\r\n case 40: // down arrow key\r\n e.preventDefault();\r\n showNextPreview();\r\n break;\r\n }\r\n }\r\n else\r\n {\r\n isKeyPressed = false;\r\n\r\n // which key was pressed?\r\n switch (e.which)\r\n {\r\n case 37: // left arrow key\r\n e.preventDefault();\r\n showPrevious();\r\n break;\r\n\r\n case 39: // right arrow key\r\n e.preventDefault();\r\n showNext();\r\n break;\r\n\r\n case 36: // HOME\r\n e.preventDefault();\r\n showIndex(0);\r\n break;\r\n\r\n case 35: // END\r\n e.preventDefault();\r\n showIndex(itemCount - 1);\r\n break;\r\n\r\n case 27: // ESC\r\n e.preventDefault();\r\n $tooltip.qtip(\"hide\");\r\n hideTooltip();\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles the events when the mouse wheel was rotated.\r\n */\r\n function handleMouseWheel(e, delta, deltaX, deltaY)\r\n {\r\n if (deltaY != 0)\r\n {\r\n e.preventDefault();\r\n if (deltaY < 0)\r\n showNext();\r\n else\r\n showPrevious();\r\n }\r\n }\r\n\r\n // more than one item?\r\n if (itemCount > 1)\r\n {\r\n // set number\r\n $items.each(function (index, elem)\r\n {\r\n $(elem).attr(\"data-index\", index);\r\n });\r\n\r\n // click events\r\n $prev.click(showPrevious);\r\n $next.click(showNext);\r\n\r\n $prev.show();\r\n $next.show();\r\n\r\n // attach mouse wheel\r\n // (assign to variable is important that it can be removed later on)\r\n mouseWheelHandler = handleMouseWheel;\r\n $qtip.bind(\"mousewheel\", mouseWheelHandler);\r\n $label.bind(\"mousewheel\", mouseWheelHandler);\r\n }\r\n else\r\n {\r\n $prev.hide();\r\n $next.hide();\r\n }\r\n\r\n // key handlers\r\n // (assign to variable is important that it can be removed later on)\r\n keyHandler = handleKeyUp;\r\n $(document).bind(\"keydown keyup\", keyHandler);\r\n\r\n // hide items and show first\r\n showIndex(0);\r\n }", "function draw() {\n\n for (var i = 0; i < document.images.length; i++) {\n if (document.images[i].getAttribute('id') != 'frame') {\n canvas = document.createElement('canvas');\n canvas.className = \"canvas-room-basic\"\n canvas.setAttribute('width', 400);\n canvas.setAttribute('height', 300);\n\n document.images[i].parentNode.insertBefore(canvas,document.images[i]);\n\n ctx = canvas.getContext('2d');\n\n ctx.drawImage(document.images[i], 35, 37, 325, 225);\n ctx.drawImage(document.getElementById('frame'), 0, 0, 400, 300);\n }\n }\n}", "render(rootElement) {\n let newImageElement = document.createElement('img');\n newImageElement.src = 'img/' + this.product.imageName;\n newImageElement.style.height = '200px';\n rootElement.appendChild (newImageElement);\n newImageElement.addEventListener('click', () => {\n this.handlePictureClicked(this.product);\n });\n }", "function displayProjects(){\n gallery.innerHTML = '';\n relevantProjects().forEach(function (project){\n gallery.appendChild(project.thumbnail);\n })\n}", "function loadContentViewer(imageId,position,rotation) {\r\n\t// When a RHS thumbnail is clicked, this function is called. \r\n\t// Because of that, and the fact we know if the page has already been loaded, we can reset the pageBeginLoadTime if needed.\r\n\t// Only Perform when debug = p.\r\n\t\r\n\tif (pageLoadDebug != -1 && initialPageLoad == false) {\r\n\t\tpageStartLoadTime = new Date();\r\n\t}\r\n\tinitialPageLoad = false;\r\n\t\r\n\t// Load the active page object into a global variable.\r\n\tobjPage = window.opener.objCase.pages[window.opener.activePageJsonId];\r\n\t\r\n\t// Clear the content viewer so we do not have non-used DOM elements on the page.\r\n\tclearContentViewer();\r\n\t\r\n\t// Get the image path from the spContentId field.\r\n\tcontentId = objPage.spContentID;\r\n\timagePath = 'ucm/getFile?contentId=' + contentId + '&rendition=web';\r\n\r\n\t// Load the preview image objects and set the preview image src attributes. \r\n\t// These are used for the 8 zoom levels.\r\n\t$('#content_preview_image1').attr('src', imagePath);\r\n\t$('#content_preview_image2').attr('src', imagePath);\r\n\t$('#content_preview_image3').attr('src', imagePath);\r\n\t$('#content_preview_image4').attr('src', imagePath);\r\n\t$('#content_preview_image5').attr('src', imagePath);\r\n\t$('#content_preview_image6').attr('src', imagePath);\r\n\t$('#content_preview_image7').attr('src', imagePath);\r\n\t$('#content_preview_image8').attr('src', imagePath);\r\n\t$('#content_preview_image9').attr('src', imagePath);\r\n\t\r\n\t// Set the names to the thumbnail id so we can retrive when rotating the images.\r\n\t$('#content_preview_image1').attr('name', imageId);\r\n\t\r\n\t// Initialize the map/zooming functionality\r\n\t$(\"#map-1\").mapz({\r\n\t\tzoom : true,\r\n\t\tcreatemaps : true,\r\n\t\tmousewheel : false\r\n\t});\r\n\r\n\t// Check which position the active document is within the thumbnail sequence and set the navigation controls appropriately.\r\n\tswitch(position) {\r\n\t\tcase 'first':\r\n\t\t\t$(\"#nav_prev_content\").attr('disabled','disabled');\r\n\t\t\t$(\"#nav_next_content\").removeAttr('disabled');\r\n\t\t\tbreak;\r\n\t\tcase 'last':\r\n\t\t\t$(\"#nav_prev_content\").removeAttr('disabled');\r\n\t\t\t$(\"#nav_next_content\").attr('disabled','disabled');\r\n\t\t\tbreak;\r\n\t\tcase 'only':\r\n\t\t\t$(\"#nav_prev_content\").attr('disabled','disabled');\r\n\t\t\t$(\"#nav_next_content\").attr('disabled','disabled');\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\t$(\"#nav_prev_content\").removeAttr('disabled');\r\n\t\t\t$(\"#nav_next_content\").removeAttr('disabled');\r\n\t}\r\n\t\r\n\t// If we are in step 2, display the grid lines\r\n\tif (step == 2) {\r\n\t\t$('#map-1').griddy({height:1350});\r\n\t\t$('.griddy').toggle(); \r\n\t}\r\n\t\r\n\t// Update sequencing information based on the current step.\r\n\tif (step == 1) {\r\n\t\t// Update the active page and final page number.\r\n\t\tupdateActivePageNumber();\r\n\t\tupdateActiveDocumentPageFinalNumber();\r\n\t\tupdateActiveDocumentPageDocDateAndType();\r\n\t} else if (step == 2) {\r\n\t\t// Update sequencing display data.\r\n\t\tupdateActiveDocumentNumber();\r\n\t\tupdateActiveDocumentPageNumber();\r\n\t\tupdateActiveDocumentPageFinalNumber();\r\n\t\tupdateActiveDocumentPageDocDateAndType();\r\n\t\tupdateDocumentCount();\r\n\t\tupdateDocumentPageCount();\r\n\t\t\r\n\t\t// Update sequencing controls.\r\n\t\tupdateDocumentControls();\r\n\t\tupdatePageControls();\r\n\t}\r\n\t\r\n\t/*IWS-357 : Not all the thumbnail image is showing, thumbnails are off center and far to the right*/\r\n\t\r\n\t/* Recommended Resolution - 1920 x 1080(Landscape) or 1080 x 1920(Portrait) \r\n\t To make the images to the center of screen \r\n\t if screen having resolution - 1080 x 1920(Portrait) */\r\n\tif($(screen)[0].width!='1920' || $(screen)[0].height!='1080'){\r\n\t\t$(\"#content_preview_image1\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image2\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image3\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image4\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image5\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image6\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image7\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image8\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image9\").addClass('removeMargin');\r\n\t}else{\r\n\t\t$(\"#content_preview_image1\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image2\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image3\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image4\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image5\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image6\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image7\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image8\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image9\").removeClass('removeMargin');\r\n\t}\r\n\t// To load the gridding to 100%\r\n\tvar stageId = window.opener.qsStageId;\r\n\tif(stageId == 4 || stageId == 5){ // stageId = 4 & stageId = 5 is for step1-OP and Step1-QA respectively\r\n\t\t$(\"#map-1\").css({ left : '0', width: '100%' });\r\n\t}else{\r\n\t\t$(\"#map-1\").addClass('map-override');\r\n\t}\r\n\t\r\n\t// Update the rotation.\r\n\t$(\"#content_preview_image1\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image2\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image3\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image4\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image5\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image6\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image7\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image8\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image9\").rotate({angle: rotation});\r\n\t\r\n\t// Postioining the image if rotation angle is 90/270 degrees\r\n\tif(rotation == '90' || rotation == '270'){\r\n\t\t$('#content_preview_image2').addClass('landscapeImg2Zoom');\r\n\t\t$('#content_preview_image3').addClass('landscapeImg3Zoom');\r\n\t\t$('#content_preview_image4').addClass('landscapeImg4Zoom');\r\n\t\t$('#content_preview_image5').addClass('landscapeImg5Zoom');\r\n\t\t$('#content_preview_image6').addClass('landscapeImg6Zoom');\r\n\t\t$('#content_preview_image7').addClass('landscapeImg7Zoom');\r\n\t\t$('#content_preview_image8').addClass('landscapeImg8Zoom');\r\n\t\t$('#content_preview_image9').addClass('landscapeImg9Zoom');\r\n\t}else{\r\n\t\t$('#content_preview_image2').removeClass('landscapeImg2Zoom');\r\n\t\t$('#content_preview_image3').removeClass('landscapeImg3Zoom');\r\n\t\t$('#content_preview_image4').removeClass('landscapeImg4Zoom');\r\n\t\t$('#content_preview_image5').removeClass('landscapeImg5Zoom');\r\n\t\t$('#content_preview_image6').removeClass('landscapeImg6Zoom');\r\n\t\t$('#content_preview_image7').removeClass('landscapeImg7Zoom');\r\n\t\t$('#content_preview_image8').removeClass('landscapeImg8Zoom');\r\n\t\t$('#content_preview_image9').removeClass('landscapeImg9Zoom');\r\n\t}\r\n\t// Only show the rotation controls if the page is not complete, suspended or excluded.\r\n\tpgCompleted = objPage.completed;\r\n\tpgDeleted = objPage.deleted;\r\n\tif (pgCompleted != true && pgCompleted != 'true' && pgDeleted != true && pgDeleted != 'true') {\r\n\t\tdisplayRotationControls();\r\n\t} else {\r\n\t\thideRotationControls();\r\n\t}\r\n}", "function displayPictures(){\n leftPicture.src = allPictures[threePictures[0]].filepath;\n leftPicture.alt = allPictures[threePictures[0]].name;\n leftPicture.title = allPictures[threePictures[0]];\n centerPicture.src = allPictures[threePictures[1]].filepath;\n centerPicture.alt = allPictures[threePictures[1]].name;\n centerPicture.title = allPictures[threePictures[1]];\n rightPicture.src = allPictures[threePictures[2]].filepath;\n rightPicture.alt = allPictures[threePictures[2]].name;\n rightPicture.title = allPictures[threePictures[2]];\n}", "loadPreviews () {\n this.files.map(file => {\n if (!file.previewData && window && window.FileReader && /^image\\//.test(file.file.type)) {\n const reader = new FileReader()\n reader.onload = e => Object.assign(file, { previewData: e.target.result })\n reader.readAsDataURL(file.file)\n }\n })\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search for a role by query input
findByq(req, res) { return Role .findAll({ where: { $or: [ { role: { $ilike: `%${req.query.q}%` } } ] } }) .then(response => res.status(200).send(response)) .catch(error => res.status(400).send(error)); }
[ "function findRole(roleID) {\n let cost = 0;\n let roleName = \"\";\n\n db.findOne({ guildID: guildID, buyableRanks: { $elemMatch: { roleID: roleID } } }, (err, exists) => {\n if (err) console.log(err)\n if (exists) {\n cost = (exists.buyableRanks[exists.buyableRanks.map(role => role.roleID).indexOf(roleID)].cost);\n roleName = (exists.buyableRanks[exists.buyableRanks.map(role => role.roleID).indexOf(roleID)].roleName);\n sell(cost, roleName, roleID)\n } else return message.reply(\"This rank is not able to be bought or sold\").then(m => del(m, 7500));\n })\n }", "function searchRoom (handlerInput, roomName) {\n \n console.log(\"Searching for room \" + roomName);\n \n const ROOMS = handlerInput.attributesManager.getSessionAttributes().ROOMS;\n var roomSearched = null;\n \n // check each room in ROOMS Object\n Object.keys(ROOMS).forEach(function(key,index) {\n // key: the name of the object key\n // index: the ordinal position of the key within the object \n \n if (ROOMS[key].name == roomName){\n \troomSearched = ROOMS[key]\n }\n });\n \n console.log(\"roomFound \" + JSON.stringify(roomSearched));\n \n return roomSearched;\n}", "function roleExists(roleName){\r\n for (i = 0; i < Z_ROLES.length; i++) {\r\n var z_userrole = Z_ROLES[i].toString().substring(0,25).trim();\r\n\t if(z_userrole.toUpperCase() == roleName.toUpperCase()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}", "function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}", "getRole (roleId) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n return this._apiRequest(`/role/${roleId}`)\n }", "visitRole_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "searchUserByName(name) {\n const users = this.getUsers(); //Returns the collection of Users\n\n //Filter each user name based on the name we are interested in.\n const results = users.filter(\n user => user.firstName === name || user.lastName === name\n );\n\n return results.length === 0 ? false : results; //Returns false if no result found else returns true\n }", "findRoomby(query) {\n let res = this.db.get(tablename).filter(query).value();\n return res;\n }", "function retrieveRoleByName(name) {\n return new Promise(function(resolve, reject) {\n Role.findOne({ name })\n .lean()\n .then(function(role) {\n resolve(role);\n })\n .catch(function(err) {\n reject(err);\n });\n });\n}", "function modifyRoleRoleSel(empl) {\n const employee = empl;\n db.query(\"SELECT id, title FROM role\", function (err, res) {\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"And what will be their new role be?\",\n name: \"modifyRoleChangedR\",\n choices: function () {\n const choiceArrayRole = [];\n for (let i = 0; i < res.length; i++) {\n choiceArrayRole.push(`${res[i].id} | ${res[i].title}`);\n }\n return choiceArrayRole;\n },\n },\n ])\n .then(function (role) {\n const newRole = parseInt(role.modifyRoleChangedR.slice(0, 5));\n const changingEmpl = role.employee;\n let query = db.query(\n \"UPDATE employee SET role_id = ? WHERE id = ?\",\n [newRole, employee],\n function (err, res) {\n if (err) {\n } else {\n console.log(\"All set!\");\n firstQ();\n }\n }\n );\n });\n });\n}", "function checkVariables(values, roles, i){ // Take in a role ID and see if it matches any of the IDs in the provided array of values, if it does, return the name, otherwise return undefined\n const result = values.find( ({ id }) => id === roles[i] );\n if (result === undefined) {\n } else { \n return result.name\n }\n }", "function getBySkillName(req, res) {\n const query = {};\n let name = '';\n\n // Players can search for skills with multiple words in the name, but\n // these skills must be entered as with '-' instead of spaces, so\n // this code replaces the '-' with ' '\n if (req.params.skillName) {\n name = req.params.skillName;\n name.replace('-', ' ');\n }\n\n searchBySkillNamePrefix(query, name, res);\n }", "function searchCourse(name) {\n var menu = JSON.parse(localStorage.getItem('menu'));\n for (let i = 0; i < menu.length; i++) {\n if (menu[i].name == name) {\n return i;\n }\n }\n return -1;\n}", "static async findCollege(string){\n const result=await pool.query('SELECT *,LOWER(collegename),INSTR(LOWER(collegename),?) FROM college WHERE INSTR(LOWER(collegename),?)>0 ORDER BY INSTR(LOWER(collegename),?)',[string,string,string]);\n return result;\n }", "function seperateRole(){\n\n}", "function addRole() {\n inquirer\n .prompt([\n {\n type: \"input\",\n message: \"What is the name of the new employee role?\",\n name: \"title\"\n },\n {\n type: \"input\",\n message: \"How much is the new salary of the employee's role?\",\n name: \"salary\"\n },\n {\n type: \"list\",\n message: \"In which department is the new role?\",\n name: \"id\",\n choices: showdepartments\n }\n ])\n .then(function (response) {\n \n addEmployeeRole(response);\n })\n }", "async function getAdmin(email) {\n let sql = `SELECT name FROM family WHERE email = ? AND role = ?`;\n return await db.query(sql, [email, \"admin\"]);\n}", "function showAllRoles() {\n query = 'SELECT * FROM role;';\n connection.query(query, (err, results) => {\n if (err) throw err;\n console.table(results);\n // return to main menu\n askUser();\n });\n}", "function getRole(roleIndex) {\n\tif (jQuery.type(roleIndex) == 'string') {\n\t\troleIndex = stripLeadingURL(roleIndex);\n\t\troleIndex = parseInt(roleIndex);\n\t}\n\treturn roles[roleIndex];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a new instrument
function createNewInstrument(name){ // make new oscillator and gain nodes var newGain = new initGain(); var newOscillator = new initOscillator(newGain); newGain.connect(context.destination); // create new instrument with oscillator var newInstrument = new Instrument("new_instrument", newOscillator, newGain, []); instruments.push(newInstrument); }
[ "function Instrument (options) {\n\tvar i, waveForm, array, mod;\n\toptions = options || {};\n\n\tif (options.context) {\n\t\tthis.context = options.context;\n\t} else if (options.destination) {\n\t\tthis.context = options.destination.context;\n\t} else {\n\t\tthis.context = new AudioContext();\n\t}\n\tthis.mainGain = this.context.createGain();\n\tthis.mainGain.connect(options.destination || this.context.destination);\n\tthis.nextTime = 0;\n\n\twaveForm = options.waveForm;\n\tif (Array.isArray(waveForm)) {\n\t\twaveForm = {r: waveForm};\n\t}\n\tif (waveForm && (Array.isArray(waveForm.r) || Array.isArray(waveForm.i))) {\n\t\tif (waveForm.r) {\n\t\t\tarray = waveForm.r.slice();\n\t\t\tarray.unshift(0);\n\t\t\twaveForm.r = new Float32Array(array);\n\t\t}\n\t\tif (waveForm.i) {\n\t\t\tarray = waveForm.i.slice();\n\t\t\tarray.unshift(0);\n\t\t\twaveForm.i = new Float32Array(array);\n\t\t}\n\t\tif (!waveForm.r) {\n\t\t\twaveForm.r = new Float32Array(waveForm.i.length);\n\t\t}\n\t\tif (!waveForm.i) {\n\t\t\twaveForm.i = new Float32Array(waveForm.r.length);\n\t\t}\n\t\twaveForm = this.context.createPeriodicWave(waveForm.r, waveForm.i);\n\t}\n\n\tmod = this.context.createOscillator();\n\tmod.frequency.value = 5;\n\tmod.start();\n\tthis.mod = this.context.createGain();\n\tthis.mod.gain.value = 5;\n\tmod.connect(this.mod);\n\n\tthis.nodes = [];\n\tfor (i = 0; i < (options.c || 2); i++) {\n\t\tthis.nodes.push(this.createNode(waveForm, 5));\n\t}\n\tthis.currentNode = 0;\n\n\tthis.baseVolume = options.baseVolume || 1;\n\tthis.duration = options.duration || 0.5;\n\tthis.envelope = options.envelope || [0.3, 0.6, 1.2];\n}", "function Musician(instrumentName) {\n this.uuid = uuidv4();\n this.instrumentName = instrumentName;\n this.instrumentSound = correspondingSound(this.instrumentName);\n\n /*\n * We will simulate instrument changes on a regular basis. That is something that\n * we implement in a class method (via the prototype)\n */\n // eslint-disable-next-line func-names\n Musician.prototype.update = function () {\n /*\n * Let's create the measure as a dynamic javascript object, \n * add the 2 properties (uuid and instrument), auditor will handle activeSince\n * and serialize the object to a JSON string\n */\n const musicianInfo = {\n uuid: this.uuid,\n sound: this.instrumentSound,\n };\n const payload = JSON.stringify(musicianInfo);\n\n /*\n* Finally, let's encapsulate the payload in a UDP datagram, which we publish on\n* the multicast address. All subscribers to this address will receive the message.\n*/\n const message = Buffer.from(payload);\n s.send(message, 0, message.length, protocol.PROTOCOL_PORT,\n protocol.PROTOCOL_MULTICAST_ADDRESS, () => {\n console.log(`Sending payload: ${payload} via port ${s.address().port}`);\n });\n };\n\n /*\n* Let's take and send a measure every 1 s (1000 ms)\n*/\n setInterval(this.update.bind(this), 1000);\n\n\n}", "newRecord() {}", "withSequenceNumber(t) {\n return new si(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);\n }", "function create_new_activity(descript, time) {\n let new_activity = {\n id: generateHexString(50),\n description: descript,\n time: acquire_date.import_date(time)\n };\n\n return new_activity;\n}", "static createInstance(lotNumber, component, containerID, manufacturer, createdTime, weight, temperature, expectedProduct) {\n return new ProcessLine({ lotNumber, component, containerID, manufacturer, createdTime, weight, temperature, expectedProduct });\n }", "function changeInstrument() {\n instrument = (instrument + 1) % instruments.length;\n console.log('change instrument');\n }", "create() {\n const uuid = `urn:uuid:${uuidv4()}`;\n\n this.metadata = new PackageMetadata();\n this.manifest = new PackageManifest();\n this.spine = new PackageSpine();\n this.setUniqueIdentifier(uuid);\n }", "function newNote () {\n\tvar note = new Note();\n\tnote.id = ++highestId;\n\tnote.timestamp = new Date().getTime();\n\tnote.left = Math.round(Math.random() * 400) + 'px';\n\tnote.top = Math.round(Math.random() * 500) + 'px';\n\tnote.zIndex = ++highestZ;\n\tnote.saveAsNew();\n}", "captureInstrumentation() {\n setInterval(() => {\n this.instrumentation.pushMetrics();\n setMetrics();\n }, config.instrumentationTimer);\n }", "function setupInstruments(){\n // set at which octave each voice will play\n syn1.oct=12;\n syn3.oct=-24;\n syn2.oct=0;\n // assign phrasesto each synth\n syn2.notes=phrase1;\n syn1.notes=phrase2;\n syn3.notes=phrase3;\n loadAnInstrument(syn2);\n loadAnInstrument(syn1);\n loadAnInstrument(syn3);\n}", "addSignal (SampleTarget, options){\n var newSignal = new Signal(\n SampleTarget,\n this.noPltPoints,\n options ) ;\n this.signals.push( newSignal ) ;\n this.noSignals ++ ;\n this.yticks.min = newSignal.minValue ;\n this.yticks.max = newSignal.maxValue ;\n this.timeWindow = newSignal.timeWindow ;\n this.xticks.max = this.timeWindow ;\n this.initBackground() ;\n return newSignal ;\n }", "function instrumentRegCreateKey(opts) {\n\tif(opts.ex) {\n\t\tvar pRegCreateKey = opts.unicode ? Module.findExportByName(null, \"RegCreateKeyExW\")\n : Module.findExportByName(null, \"RegCreateKeyExA\");\n } else {\n\t\tvar pRegCreateKey = opts.unicode ? Module.findExportByName(null, \"RegCreateKeyW\")\n : Module.findExportByName(null, \"RegCreateKeyA\"); \t\n }\n\tInterceptor.attach(pRegCreateKey, {\n\t\tonEnter: function(args) {\n\t\t\tthis.regkey = opts.unicode ? args[1].readUtf16String() : args[1].readUtf8String();\n\t\t\tvar regclass = REG_KEYS[args[0].toInt32()>>>0];\n\t\t\tif(regclass != undefined)\n\t\t\t\tthis.regkey = regclass + \"\\\\\" + this.regkey;\n\t\t\telse\n\t\t\t\tthis.regkey = \"\\\\\" + this.regkey;\n\n\t\t\tthis.handle = opts.ex ? args[7] : args[2];\n\t\t},\n\t\tonLeave: function(retval) {\n\t\t\tsend({\n\t\t\t\t'hook': 'RegCreateKey',\n\t\t\t\t'regkey': this.regkey,\n\t\t\t\t'handle': this.handle.readPointer().toInt32()\n\t\t\t});\n\t\t}\n\t});\n}", "function createNextWave () {\r\n\tcreateEnemies();\r\n waveTimer = game.time.now + 5000;\r\n}", "generateInitialNoteData() {\n for (let i = 0; i<this.numberOfNotes; i++) {\n this.noteData.push({\n clef: this.instrumentClef,\n keys: [RESTNOTE[this.instrumentClef]],\n duration: `${this.noteLength}r`});\n }\n }", "createSquads(numberOfUnits) {\n for (let i = 0; i < this.numberOfSquads; i++) {\n console.log(`Created squad ${i}`);\n this.squads.push(new Squad(numberOfUnits));\n }\n }", "constructor () {\r\n this.context = new AudioContext(); //AudioContext for Oscillators to generate tones\r\n this.debug = false;\r\n this.duration = Piano2.DEFAULT_DURATION;\r\n this.toneType = Piano2.DEFAULT_TONE;\r\n }", "function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }", "changeTrackInstrument(trackID, instrumentID) {\n let track = this.tracks[trackID];\n let new_instr = instrumentArray[instrumentID];\n track.instrument = new_instr;\n track.instrumentID = instrumentID;\n let trackName = this.generateTrackName(trackID, new_instr);\n this.trackNames[trackID] = trackName;\n this.controls.tracksElement.options[trackID] = new Option(trackName, trackName);\n this.controls.tracksElement.selectedIndex = trackID; //tracksElementを変更するとインデックスが変化するので元に戻す\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
opposingPlayer Params: player 1 or 2, whoever's turn it is Returns 1 or 2, the opposing player's number
__opposingPlayer (player) { if (player === 1) { return 2; } else { return 1; } }
[ "switchPlayers(){\n if(this.currentPlayer == this.player1){\n this.currentPlayer = this.player2;\n }\n else this.currentPlayer = this.player1;\n }", "function updateNumberOfPlayers(){\n\n // this is the real number of players\n numberOfPlayers = inPlayerId - 1;\n}", "function winnerIs(player) {\n\tconsole.log(player == \"player1\" ? \"Player 1 wins\" : \"Player 2 wins\");\n\tshowMessege(player == \"player1\" ? \"#\" + player1.short + \"-hits\" : \"#\" + player2.short + \"-hits\");\n\tif(player == \"player1\") {\n\t\tsetStamina(player1, \"player-1-stamina\", \"add\");\n\t\tsetStamina(player2, \"player-2-stamina\", \"subtract\");\n\t} else {\n\t\tsetStamina(player1, \"player-1-stamina\", \"subtract\");\n\t\tsetStamina(player2, \"player-2-stamina\", \"add\");\t\t\n\t}\n\tplayer == \"player1\" ? decreaseHealth(player2, \"player2\") : decreaseHealth(player1, \"player1\");\n\t$(\"#player-1-health\").html(player1.health);\n\t$(\"#player-2-health\").html(player2.health);\n\tif(player == \"player1\" && player2.health == 0) {\n\t\tplayer2.dead = true;\n\t} else if(player1.health == 0) {\n\t\tplayer1.dead = true;\n\t}\n}", "function secondPlayerWins() {\n secondPlayerScore.innerHTML = parseInt(secondPlayerScore.innerHTML) + 1;\n gameIsWon = true;\n }", "function winOrLose() {\n if (playerScore === randomNum) {\n winsCounter++;\n $(\"#wins\").html(\" \" + winsCounter);\n startGame();\n } else if (playerScore > randomNum) {\n lossCounter++;\n $(\"#losses\").html(\" \" + lossCounter);\n startGame();\n }\n }", "getPlayer2ID() {\n\t\treturn this.idPlayer2;\n\t}", "function turnIs() {\n if (turn == player2) {\n turn = player1;\n symbol = \"o\";\n } else {\n turn = player2;\n symbol = \"x\";\n }\n\n }", "getPlayerType() {\n if (this.currentPlayer === 'blacks') return this.player1.type \n else return this.player2.type\n }", "function pointsTwos(player) {\n\n var diceCount = countDices(player);\n return diceCount[1] * 2; \n}", "function roundResult(playerWin, playerSelection, computerSelection) {\n if (playerWin) return \"You win! \" + playerSelection + \" beats \" +\n computerSelection;\n else return \"You lose! \" + computerSelection + \" beats \" + playerSelection;\n}", "function getPiece(player){\n player = player.toLowerCase();\n if(player === \"x\"){\n //updates the current turn\n turn = \"o\";\n return cross;\n }else{\n //updates the current turn\n turn = \"x\";\n return circle;\n }\n}", "function whoIsActive() {\n if (player1Active) {\n activePlayer = 2;\n notActivePlayer = 1;\n setActivePlayer(player2, player1, damage2);\n setActiveBoard(notActivePlayer, activePlayer);\n } else {\n activePlayer = 1; \n notActivePlayer = 2;\n setActivePlayer(player1, player2, damage1);\n setActiveBoard(notActivePlayer, activePlayer,);\n }\n}", "switchUser() {\n this.currentPlayer = this.currentPlayer == 1 ? 0 : 1;\n this.io.to(this.id).emit('g-startTurn', this.players[this.currentPlayer]);\n }", "function currentJavamon(){\n current1Javamon=player1Javamon[randomNum];\n current2Javamon=player2Javamon[randomNum];\n}", "function whoPlaysFirst() {\n //generate random number between 1 and 2\n const random = Math.ceil(Math.random()*2)\n if(random === 2) {\n p1Turn = false\n playerTurn.innerHTML = `${player2.name}, à toi de jouer !`\n playerTurn.classList.add('text-red-700')\n } else {\n playerTurn.innerHTML = `${player1.name}, à toi de jouer !`\n playerTurn.classList.add('text-blue-700')\n return p1Turn\n }\n }", "getPlayer1ID() {\n\t\treturn this.idPlayer1;\n\t}", "function switchTurn() {\n if (turn === \"player 2\") {\n turn = \"player 1\";\n setMessage(turn + \"'s turn\");\n document.getElementById(\"playerTurn\").style.color =\"hotpink\";\n } else {\n turn = \"player 2\";\n setMessage(turn + \"'s turn\");\n document.getElementById(\"playerTurn\").style.color =\"gold\";\n }\n }", "function pointsTwoPairs(player) {\n \n var diceCount = countDices(player); \n var points = 0;\n var pair1 = 0;\n var pair2 = 0;\n \n for (var i = 0; i < 6; i++) {\n if (diceCount[i] > 1) {\n pair1 = i + 1;\n }\n }\n \n if (pair1 > 0) {\n diceCount[pair1 - 1] = diceCount[pair1 - 1] - 2;\n for (var i = 0; i < 6; i++) {\n if (diceCount[i] > 1) {\n pair2 = i + 1;\n }\n }\n if (pair2 > 0) {\n points = (2 * pair1) + (2 * pair2);\n }\n }\n \n return points;\n}", "getPlayerDifficulty() {\n if (this.currentPlayer === 'blacks') return this.player1.difficulty \n else return this.player2.difficulty\n }", "function opponentTurn(){\n\t\tif(matchProceed)\n\t\t{\n\t\t\tattack(enemyP, playerC);\n\t\t}\n\t\telse {\n\t\t\tcheckGame();\n\t\t\tconsole.log(\"Game is over.\");\n\t\t}\n\t\topponentLock = false;\n\t\t\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates a random character image based on gender, race, class.
function randomImage() { // plugs in to the local storage var gender = localStorage.getItem('charGender'); var race = localStorage.getItem('charRace'); var classDisplay = localStorage.getItem('charClass'); // display which plugs into var results var currentpicture; // sets the image equal to the ID in the html var result = document.getElementById('centerVidImg'); // human if then statements "Male" if (gender === 'Male' && race === 'Human' && classDisplay === 'Fighter') { currentpicture = mhf[randomNumber(0, mhf.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Human' && classDisplay === 'Ranger' ) { currentpicture = mhra[randomNumber(0, mhra.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Human' && classDisplay === 'Wizard' ) { currentpicture = mhm[randomNumber(0, mhra.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Human' && classDisplay === 'Cleric' ) { currentpicture = mhc[randomNumber(0, mhra.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Human' && classDisplay === 'Rogue' ) { currentpicture = mhro[randomNumber(0, mhra.length)]; result.src = currentpicture; // human if then statements "Female" } else if ( gender === 'Female' && race === 'Human' && classDisplay === 'Fighter' ) { currentpicture = fhf[randomNumber(0, fhf.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Human' && classDisplay === 'Ranger' ) { currentpicture = fhra[randomNumber(0, fhra.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Human' && classDisplay === 'Wizard' ) { currentpicture = fhm[randomNumber(0, fhm.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Human' && classDisplay === 'Cleric' ) { currentpicture = fhc[randomNumber(0, fhc.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Human' && classDisplay === 'Rogue' ) { currentpicture = fhro[randomNumber(0, fhro.length)]; result.src = currentpicture; // elf if then statements "Male" } else if ( gender === 'Male' && race === 'Elf' && classDisplay === 'Fighter' ) { currentpicture = mef[randomNumber(0, mef.length)]; result.src = currentpicture; } else if (gender === 'Male' && race === 'Elf' && classDisplay === 'Ranger') { currentpicture = mera[randomNumber(0, mera.length)]; result.src = currentpicture; } else if (gender === 'Male' && race === 'Elf' && classDisplay === 'Wizard') { currentpicture = mem[randomNumber(0, mera.length)]; result.src = currentpicture; } else if (gender === 'Male' && race === 'Elf' && classDisplay === 'Cleric') { currentpicture = mec[randomNumber(0, mera.length)]; result.src = currentpicture; } else if (gender === 'Male' && race === 'Elf' && classDisplay === 'Rogue') { currentpicture = mero[randomNumber(0, mera.length)]; result.src = currentpicture; // elf if then statements "Female" } else if ( gender === 'Female' && race === 'Elf' && classDisplay === 'Fighter' ) { currentpicture = fef[randomNumber(0, fef.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Elf' && classDisplay === 'Ranger' ) { currentpicture = fera[randomNumber(0, fera.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Elf' && classDisplay === 'Wizard' ) { currentpicture = fem[randomNumber(0, fem.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Elf' && classDisplay === 'Cleric' ) { currentpicture = fec[randomNumber(0, fec.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Elf' && classDisplay === 'Rogue' ) { currentpicture = fero[randomNumber(0, fero.length)]; result.src = currentpicture; // dwarf if then statements "Male" } else if ( gender === 'Male' && race === 'Dwarf' && classDisplay === 'Fighter' ) { currentpicture = mdf[randomNumber(0, mdf.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Dwarf' && classDisplay === 'Ranger' ) { currentpicture = mdra[randomNumber(0, mdra.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Dwarf' && classDisplay === 'Wizard' ) { currentpicture = mdm[randomNumber(0, mdra.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Dwarf' && classDisplay === 'Cleric' ) { currentpicture = mdc[randomNumber(0, mdra.length)]; result.src = currentpicture; } else if ( gender === 'Male' && race === 'Dwarf' && classDisplay === 'Rogue' ) { currentpicture = mdro[randomNumber(0, mdra.length)]; result.src = currentpicture; // dwarf if then statements "Female" } else if ( gender === 'Female' && race === 'Dwarf' && classDisplay === 'Fighter' ) { currentpicture = fdf[randomNumber(0, fdf.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Dwarf' && classDisplay === 'Ranger' ) { currentpicture = fdra[randomNumber(0, fdra.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Dwarf' && classDisplay === 'Wizard' ) { currentpicture = fdm[randomNumber(0, fdm.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Dwarf' && classDisplay === 'Cleric' ) { currentpicture = fdc[randomNumber(0, fdc.length)]; result.src = currentpicture; } else if ( gender === 'Female' && race === 'Dwarf' && classDisplay === 'Rogue' ) { currentpicture = fdro[randomNumber(0, fdro.length)]; result.src = currentpicture; } //updates the src.URL to equal the image $('#centerVidImg').attr('src', result.src); }
[ "function generateGender() {\n\tvar rand = Math.random();\n\tvar gender;\n\tif (rand < .5) {\n\t\tgender = 'F';\n\t}\n\telse {\n\t\tgender = 'M';\n\t}\n\treturn gender;\n}", "function gen_character(params) {\n\t//add character generation code here\n}", "function randomAvatar() {\n currentColor = floor(random(0, COLORS.length));\n currentAvatar = floor(random(0, avatars.length));\n}", "function generateRandomPlayerName() {\n // for example, 'green baboon' or 'porcelain bison'\n return `${COLOR_WORDS[Math.floor(Math.random()*COLOR_WORDS.length)]} ${ANIMAL_WORDS[Math.floor(Math.random()*ANIMAL_WORDS.length)]}`\n}", "function generateImage(targetImage) {\n if (generateImage){\n var img = document.createElement('img');\n img.setAttribute('src', targetImage);\n var characterAvatar = document.getElementById('bigCharacter');\n characterAvatar.appendChild(img);\n }\n}", "function prepCharacter(race) {\n if (race === \"Aarakocra\") {\n character.Race = aaracokra.Race;\n character.AdultAge = aaracokra.AdultAge;\n character.MaxAge = aaracokra.MaxAge;\n character.BaseHeight = aaracokra.BaseHeight;\n character.HeightModifier = aaracokra.HeightModifier;\n character.BaseWeight = aaracokra.BaseWeight;\n character.WeightModifier = aaracokra.WeightModifier;\n } else if (\n race === \"Aasimar, Fallen\" ||\n race === \"Aasimar, Protector\" ||\n race === \"Aasimar, Scourge\" ||\n race === \"Aasimar, Variant\"\n ) {\n character.Race = aasimar.Race;\n character.AdultAge = aasimar.AdultAge;\n character.MaxAge = aasimar.MaxAge;\n character.BaseHeight = aasimar.BaseHeight;\n character.HeightModifier = aasimar.HeightModifier;\n character.BaseWeight = aasimar.BaseWeight;\n character.WeightModifier = aasimar.WeightModifier;\n } else if (race === \"Bugbear\") {\n character.Race = bugbear.Race;\n character.AdultAge = bugbear.AdultAge;\n character.MaxAge = bugbear.MaxAge;\n character.BaseHeight = bugbear.BaseHeight;\n character.HeightModifier = bugbear.HeightModifier;\n character.BaseWeight = bugbear.BaseWeight;\n character.WeightModifier = bugbear.WeightModifier;\n } else if (race === \"Centaur\") {\n character.Race = centaur.Race;\n character.AdultAge = centaur.AdultAge;\n character.MaxAge = centaur.MaxAge;\n character.BaseHeight = centaur.BaseHeight;\n character.HeightModifier = centaur.HeightModifier;\n character.BaseWeight = centaur.BaseWeight;\n character.WeightModifier = centaur.WeightModifier;\n } else if (race === \"Changeling\") {\n character.Race = changeling.Race;\n character.AdultAge = changeling.AdultAge;\n character.MaxAge = changeling.MaxAge;\n character.BaseHeight = changeling.BaseHeight;\n character.HeightModifier = changeling.HeightModifier;\n character.BaseWeight = changeling.BaseWeight;\n character.WeightModifier = changeling.WeightModifier;\n } else if (\n race === \"Dragonborn\" ||\n race === \"Dragonborn, Draconblood\" ||\n race === \"Dragonborn, Ravenite\"\n ) {\n character.Race = dragonborn.Race;\n character.AdultAge = dragonborn.AdultAge;\n character.MaxAge = dragonborn.MaxAge;\n character.BaseHeight = dragonborn.BaseHeight;\n character.HeightModifier = dragonborn.HeightModifier;\n character.BaseWeight = dragonborn.BaseWeight;\n character.WeightModifier = dragonborn.WeightModifier;\n } else if (\n race === \"Dwarf, Gray (Duergar)\" ||\n race === \"Dwarf, Hill\" ||\n race === \"Dwarf, Mark of Warding\"\n ) {\n character.Race = dwarf.Race;\n character.AdultAge = dwarf.AdultAge;\n character.MaxAge = dwarf.MaxAge;\n character.BaseHeight = dwarf.BaseHeight;\n character.HeightModifier = dwarf.HeightModifier;\n character.BaseWeight = dwarf.BaseWeight;\n character.WeightModifier = dwarf.WeightModifier;\n } else if (race === \"Dwarf, Mountain\") {\n character.Race = dwarf_mountain.Race;\n character.AdultAge = dwarf_mountain.AdultAge;\n character.MaxAge = dwarf_mountain.MaxAge;\n character.BaseHeight = dwarf_mountain.BaseHeight;\n character.HeightModifier = dwarf_mountain.HeightModifier;\n character.BaseWeight = dwarf_mountain.BaseWeight;\n character.WeightModifier = dwarf_mountain.WeightModifier;\n } else if (race === \"Elf, Dark (Drow)\") {\n character.Race = elf_dark.Race;\n character.AdultAge = elf_dark.AdultAge;\n character.MaxAge = elf_dark.MaxAge;\n character.BaseHeight = elf_dark.BaseHeight;\n character.HeightModifier = elf_dark.HeightModifier;\n character.BaseWeight = elf_dark.BaseWeight;\n character.WeightModifier = elf_dark.WeightModifier;\n } else if (\n race === \"Elf, Eladrin\" ||\n race === \"Elf, Eladrin Variant\"\n ) {\n character.Race = elf_eladrin.Race;\n character.AdultAge = elf_eladrin.AdultAge;\n character.MaxAge = elf_eladrin.MaxAge;\n character.BaseHeight = elf_eladrin.BaseHeight;\n character.HeightModifier = elf_eladrin.HeightModifier;\n character.BaseWeight = elf_eladrin.BaseWeight;\n character.WeightModifier = elf_eladrin.WeightModifier;\n } else if (\n race === \"Elf, High\" ||\n race === \"Elf, Aereni High\" ||\n race === \"Elf, Valenar High\" ||\n race === \"Elf, Pallid\" ||\n race === \"Elf, Sea\"\n ) {\n character.Race = elf_high.Race;\n character.AdultAge = elf_high.AdultAge;\n character.MaxAge = elf_high.MaxAge;\n character.BaseHeight = elf_high.BaseHeight;\n character.HeightModifier = elf_high.HeightModifier;\n character.BaseWeight = elf_high.BaseWeight;\n character.WeightModifier = elf_high.WeightModifier;\n } else if (\n race === \"Elf, Shadar-kai\" ||\n race === \"Elf, Mark of Shadow\"\n ) {\n character.Race = elf_shadar_kai.Race;\n character.AdultAge = elf_shadar_kai.AdultAge;\n character.MaxAge = elf_shadar_kai.MaxAge;\n character.BaseHeight = elf_shadar_kai.BaseHeight;\n character.HeightModifier = elf_shadar_kai.HeightModifier;\n character.BaseWeight = elf_shadar_kai.BaseWeight;\n character.WeightModifier = elf_shadar_kai.WeightModifier;\n } else if (\n race === \"Elf, Wood\" ||\n race === \"Elf, Aereni Wood\" ||\n race === \"Elf, Valenar Wood\"\n ) {\n character.Race = elf_wood.Race;\n character.AdultAge = elf_wood.AdultAge;\n character.MaxAge = elf_wood.MaxAge;\n character.BaseHeight = elf_wood.BaseHeight;\n character.HeightModifier = elf_wood.HeightModifier;\n character.BaseWeight = elf_wood.BaseWeight;\n character.WeightModifier = elf_wood.WeightModifier;\n } else if (race === \"Firbolg\") {\n character.Race = firbolg.Race;\n character.AdultAge = firbolg.AdultAge;\n character.MaxAge = firbolg.MaxAge;\n character.BaseHeight = firbolg.BaseHeight;\n character.HeightModifier = firbolg.HeightModifier;\n character.BaseWeight = firbolg.BaseWeight;\n character.WeightModifier = firbolg.WeightModifier;\n } else if (\n race === \"Genasi, Air\" ||\n race === \"Genasi, Earth\" ||\n race === \"Genasi, Fire\" ||\n race === \"Genasi, Water\"\n ) {\n character.Race = genasi.Race;\n character.AdultAge = genasi.AdultAge;\n character.MaxAge = genasi.MaxAge;\n character.BaseHeight = genasi.BaseHeight;\n character.HeightModifier = genasi.HeightModifier;\n character.BaseWeight = genasi.BaseWeight;\n character.WeightModifier = genasi.WeightModifier;\n } else if (race === \"Gith, Githyanki\") {\n character.Race = gith_githyanki.Race;\n character.AdultAge = gith_githyanki.AdultAge;\n character.MaxAge = gith_githyanki.MaxAge;\n character.BaseHeight = gith_githyanki.BaseHeight;\n character.HeightModifier = gith_githyanki.HeightModifier;\n character.BaseWeight = gith_githyanki.BaseWeight;\n character.WeightModifier = gith_githyanki.WeightModifier;\n } else if (race === \"Gith, Githzerai\") {\n character.Race = gith_githzerai.Race;\n character.AdultAge = gith_githzerai.AdultAge;\n character.MaxAge = gith_githzerai.MaxAge;\n character.BaseHeight = gith_githzerai.BaseHeight;\n character.HeightModifier = gith_githzerai.HeightModifier;\n character.BaseWeight = gith_githzerai.BaseWeight;\n character.WeightModifier = gith_githzerai.WeightModifier;\n } else if (race === \"Gnome, Deep (Svirfneblin)\") {\n character.Race = gnome_deep.Race;\n character.AdultAge = gnome_deep.AdultAge;\n character.MaxAge = gnome_deep.MaxAge;\n character.BaseHeight = gnome_deep.BaseHeight;\n character.HeightModifier = gnome_deep.HeightModifier;\n character.BaseWeight = gnome_deep.BaseWeight;\n character.WeightModifier = gnome_deep.WeightModifier;\n } else if (\n race === \"Gnome, Forest\" ||\n race === \"Gnome, Mark of Scribing\" ||\n race === \"Gnome, Rock\"\n ) {\n character.Race = gnome.Race;\n character.AdultAge = gnome.AdultAge;\n character.MaxAge = gnome.MaxAge;\n character.BaseHeight = gnome.BaseHeight;\n character.HeightModifier = gnome.HeightModifier;\n character.BaseWeight = gnome.BaseWeight;\n character.WeightModifier = gnome.WeightModifier;\n } else if (race === \"Goblin\") {\n character.Race = goblin.Race;\n character.AdultAge = goblin.AdultAge;\n character.MaxAge = goblin.MaxAge;\n character.BaseHeight = goblin.BaseHeight;\n character.HeightModifier = goblin.HeightModifier;\n character.BaseWeight = goblin.BaseWeight;\n character.WeightModifier = goblin.WeightModifier;\n } else if (race === \"Goliath\") {\n character.Race = goliath.Race;\n character.AdultAge = goliath.AdultAge;\n character.MaxAge = goliath.MaxAge;\n character.BaseHeight = goliath.BaseHeight;\n character.HeightModifier = goliath.HeightModifier;\n character.BaseWeight = goliath.BaseWeight;\n character.WeightModifier = goliath.WeightModifier;\n } else if (race === \"Grung\") {\n character.Race = grung.Race;\n character.AdultAge = grung.AdultAge;\n character.MaxAge = grung.MaxAge;\n character.BaseHeight = grung.BaseHeight;\n character.HeightModifier = grung.HeightModifier;\n character.BaseWeight = grung.BaseWeight;\n character.WeightModifier = grung.WeightModifier;\n } else if (\n race === \"Half-Elf\" ||\n race === \"Half-Elf, Aquatic\" ||\n race === \"Half-Elf, Drow\" ||\n race === \"Half-Elf, High\" ||\n race === \"Half-Elf, Mark of Detection\" ||\n race === \"Half-Elf, Mark of Storm\" ||\n race === \"Half-Elf, Wood\"\n ) {\n character.Race = half_elf.Race;\n character.AdultAge = half_elf.AdultAge;\n character.MaxAge = half_elf.MaxAge;\n character.BaseHeight = half_elf.BaseHeight;\n character.HeightModifier = half_elf.HeightModifier;\n character.BaseWeight = half_elf.BaseWeight;\n character.WeightModifier = half_elf.WeightModifier;\n } else if (\n race === \"Halfling, Ghostwise\" ||\n race === \"Halfling, Lightfoot\" ||\n race === \"Halfling, Lotusden\" ||\n race === \"Halfling, Mark of Healing\" ||\n race === \"Halfling, Mark of Hospitality\" ||\n race === \"Halfling, Stout\"\n ) {\n character.Race = halfling.Race;\n character.AdultAge = halfling.AdultAge;\n character.MaxAge = halfling.MaxAge;\n character.BaseHeight = halfling.BaseHeight;\n character.HeightModifier = halfling.HeightModifier;\n character.BaseWeight = halfling.BaseWeight;\n character.WeightModifier = halfling.WeightModifier;\n } else if (\n race === \"Half-Orc\" ||\n race === \"Half-Orc, Mark of Finding\"\n ) {\n character.Race = half_orc.Race;\n character.AdultAge = half_orc.AdultAge;\n character.MaxAge = half_orc.MaxAge;\n character.BaseHeight = half_orc.BaseHeight;\n character.HeightModifier = half_orc.HeightModifier;\n character.BaseWeight = half_orc.BaseWeight;\n character.WeightModifier = half_orc.WeightModifier;\n } else if (race === \"Hobgoblin\") {\n character.Race = hobgoblin.Race;\n character.AdultAge = hobgoblin.AdultAge;\n character.MaxAge = hobgoblin.MaxAge;\n character.BaseHeight = hobgoblin.BaseHeight;\n character.HeightModifier = hobgoblin.HeightModifier;\n character.BaseWeight = hobgoblin.BaseWeight;\n character.WeightModifier = hobgoblin.WeightModifier;\n } else if (\n race === \"Human\" ||\n race === \"Human, Mark of Finding\" ||\n race === \"Human, Mark of Handling\" ||\n race === \"Human, Mark of Making\" ||\n race === \"Human, Mark of Passage\" ||\n race === \"Human, Mark of Sentinel\" ||\n race === \"Human, Variant\"\n ) {\n character.Race = human.Race;\n character.AdultAge = human.AdultAge;\n character.MaxAge = human.MaxAge;\n character.BaseHeight = human.BaseHeight;\n character.HeightModifier = human.HeightModifier;\n character.BaseWeight = human.BaseWeight;\n character.WeightModifier = human.WeightModifier;\n } else if (race === \"Kalashtar\") {\n character.Race = kalashtar.Race;\n character.AdultAge = kalashtar.AdultAge;\n character.MaxAge = kalashtar.MaxAge;\n character.BaseHeight = kalashtar.BaseHeight;\n character.HeightModifier = kalashtar.HeightModifier;\n character.BaseWeight = kalashtar.BaseWeight;\n character.WeightModifier = kalashtar.WeightModifier;\n } else if (race === \"Kenku\") {\n character.Race = kenku.Race;\n character.AdultAge = kenku.AdultAge;\n character.MaxAge = kenku.MaxAge;\n character.BaseHeight = kenku.BaseHeight;\n character.HeightModifier = kenku.HeightModifier;\n character.BaseWeight = kenku.BaseWeight;\n character.WeightModifier = kenku.WeightModifier;\n } else if (race === \"Kobold\") {\n character.Race = kobold.Race;\n character.AdultAge = kobold.AdultAge;\n character.MaxAge = kobold.MaxAge;\n character.BaseHeight = kobold.BaseHeight;\n character.HeightModifier = kobold.HeightModifier;\n character.BaseWeight = kobold.BaseWeight;\n character.WeightModifier = kobold.WeightModifier;\n } else if (race === \"Leonin\") {\n character.Race = leonin.Race;\n character.AdultAge = leonin.AdultAge;\n character.MaxAge = leonin.MaxAge;\n character.BaseHeight = leonin.BaseHeight;\n character.HeightModifier = leonin.HeightModifier;\n character.BaseWeight = leonin.BaseWeight;\n character.WeightModifier = leonin.WeightModifier;\n } else if (race === \"Lizardfolk\") {\n character.Race = lizardfolk.Race;\n character.AdultAge = lizardfolk.AdultAge;\n character.MaxAge = lizardfolk.MaxAge;\n character.BaseHeight = lizardfolk.BaseHeight;\n character.HeightModifier = lizardfolk.HeightModifier;\n character.BaseWeight = lizardfolk.BaseWeight;\n character.WeightModifier = lizardfolk.WeightModifier;\n } else if (race === \"Locathah\") {\n character.Race = locathah.Race;\n character.AdultAge = locathah.AdultAge;\n character.MaxAge = locathah.MaxAge;\n character.BaseHeight = locathah.BaseHeight;\n character.HeightModifier = locathah.HeightModifier;\n character.BaseWeight = locathah.BaseWeight;\n character.WeightModifier = locathah.WeightModifier;\n } else if (race === \"Loxodon\") {\n character.Race = loxodon.Race;\n character.AdultAge = loxodon.AdultAge;\n character.MaxAge = loxodon.MaxAge;\n character.BaseHeight = loxodon.BaseHeight;\n character.HeightModifier = loxodon.HeightModifier;\n character.BaseWeight = loxodon.BaseWeight;\n character.WeightModifier = loxodon.WeightModifier;\n } else if (race === \"Minotaur\") {\n character.Race = minotaur.Race;\n character.AdultAge = minotaur.AdultAge;\n character.MaxAge = minotaur.MaxAge;\n character.BaseHeight = minotaur.BaseHeight;\n character.HeightModifier = minotaur.HeightModifier;\n character.BaseWeight = minotaur.BaseWeight;\n character.WeightModifier = minotaur.WeightModifier;\n } else if (\n race === \"Orc\" ||\n race === \"Orc of Eberron\" ||\n race === \"Orc of Exandria\"\n ) {\n character.Race = orc.Race;\n character.AdultAge = orc.AdultAge;\n character.MaxAge = orc.MaxAge;\n character.BaseHeight = orc.BaseHeight;\n character.HeightModifier = orc.HeightModifier;\n character.BaseWeight = orc.BaseWeight;\n character.WeightModifier = orc.WeightModifier;\n } else if (race === \"Satyr\") {\n character.Race = satyr.Race;\n character.AdultAge = satyr.AdultAge;\n character.MaxAge = satyr.MaxAge;\n character.BaseHeight = satyr.BaseHeight;\n character.HeightModifier = satyr.HeightModifier;\n character.BaseWeight = satyr.BaseWeight;\n character.WeightModifier = satyr.WeightModifier;\n } else if (\n race === \"Shifter, Beasthide\" ||\n race === \"Shifter, Longtooth\" ||\n race === \"Shifter, Swiftstride\" ||\n race === \"Shifter, Wildhunt\"\n ) {\n character.Race = shifter.Race;\n character.AdultAge = shifter.AdultAge;\n character.MaxAge = shifter.MaxAge;\n character.BaseHeight = shifter.BaseHeight;\n character.HeightModifier = shifter.HeightModifier;\n character.BaseWeight = shifter.BaseWeight;\n character.WeightModifier = shifter.WeightModifier;\n } else if (race === \"Simic Hybrid Elf\") {\n character.Race = simic_hybrid_elf.Race;\n character.AdultAge = simic_hybrid_elf.AdultAge;\n character.MaxAge = simic_hybrid_elf.MaxAge;\n character.BaseHeight = simic_hybrid_elf.BaseHeight;\n character.HeightModifier = simic_hybrid_elf.HeightModifier;\n character.BaseWeight = simic_hybrid_elf.BaseWeight;\n character.WeightModifier = simic_hybrid_elf.WeightModifier;\n } else if (race === \"Simic Hybrid Human\") {\n character.Race = simic_hybrid_human.Race;\n character.AdultAge = simic_hybrid_human.AdultAge;\n character.MaxAge = simic_hybrid_human.MaxAge;\n character.BaseHeight = simic_hybrid_human.BaseHeight;\n character.HeightModifier = simic_hybrid_human.HeightModifier;\n character.BaseWeight = simic_hybrid_human.BaseWeight;\n character.WeightModifier = simic_hybrid_human.WeightModifier;\n } else if (race === \"Simic Hybrid Vedalken\") {\n character.Race = simic_hybrid_vedalken.Race;\n character.AdultAge = simic_hybrid_vedalken.AdultAge;\n character.MaxAge = simic_hybrid_vedalken.MaxAge;\n character.BaseHeight = simic_hybrid_vedalken.BaseHeight;\n character.HeightModifier = simic_hybrid_vedalken.HeightModifier;\n character.BaseWeight = simic_hybrid_vedalken.BaseWeight;\n character.WeightModifier = simic_hybrid_vedalken.WeightModifier;\n } else if (race === \"Tabaxi\") {\n character.Race = tabaxi.Race;\n character.AdultAge = tabaxi.AdultAge;\n character.MaxAge = tabaxi.MaxAge;\n character.BaseHeight = tabaxi.BaseHeight;\n character.HeightModifier = tabaxi.HeightModifier;\n character.BaseWeight = tabaxi.BaseWeight;\n character.WeightModifier = tabaxi.WeightModifier;\n } else if (\n race === \"Tiefling\" ||\n race === \"Tiefling, Baalzebul\" ||\n race === \"Tiefling, Dispater\" ||\n race === \"Tiefling, Feral\" ||\n race === \"Tiefling, Feral Variant\" ||\n race === \"Tiefling, Fierna\" ||\n race === \"Tiefling, Glasya\" ||\n race === \"Tiefling, Levistus\" ||\n race === \"Tiefling, Mammon\" ||\n race === \"Tiefling, Mephistopheles\" ||\n race === \"Tiefling, Variant\" ||\n race === \"Tiefling, Zariel\"\n ) {\n character.Race = tiefling.Race;\n character.AdultAge = tiefling.AdultAge;\n character.MaxAge = tiefling.MaxAge;\n character.BaseHeight = tiefling.BaseHeight;\n character.HeightModifier = tiefling.HeightModifier;\n character.BaseWeight = tiefling.BaseWeight;\n character.WeightModifier = tiefling.WeightModifier;\n } else if (race === \"Tortle\") {\n character.Race = tortle.Race;\n character.AdultAge = tortle.AdultAge;\n character.MaxAge = tortle.MaxAge;\n character.BaseHeight = tortle.BaseHeight;\n character.HeightModifier = tortle.HeightModifier;\n character.BaseWeight = tortle.BaseWeight;\n character.WeightModifier = tortle.WeightModifier;\n } else if (race === \"Triton\") {\n character.Race = triton.Race;\n character.AdultAge = triton.AdultAge;\n character.MaxAge = triton.MaxAge;\n character.BaseHeight = triton.BaseHeight;\n character.HeightModifier = triton.HeightModifier;\n character.BaseWeight = triton.BaseWeight;\n character.WeightModifier = triton.WeightModifier;\n } else if (race === \"Vedalken\") {\n character.Race = vedalken.Race;\n character.AdultAge = vedalken.AdultAge;\n character.MaxAge = vedalken.MaxAge;\n character.BaseHeight = vedalken.BaseHeight;\n character.HeightModifier = vedalken.HeightModifier;\n character.BaseWeight = vedalken.BaseWeight;\n character.WeightModifier = vedalken.WeightModifier;\n } else if (race === \"Verdan (small)\") {\n character.Race = verdan_small.Race;\n character.AdultAge = verdan_small.AdultAge;\n character.MaxAge = verdan_small.MaxAge;\n character.BaseHeight = verdan_small.BaseHeight;\n character.HeightModifier = verdan_small.HeightModifier;\n character.BaseWeight = verdan_small.BaseWeight;\n character.WeightModifier = verdan_small.WeightModifier;\n } else if (race === \"Verdan (medium)\") {\n character.Race = verdan_medium.Race;\n character.AdultAge = verdan_medium.AdultAge;\n character.MaxAge = verdan_medium.MaxAge;\n character.BaseHeight = verdan_medium.BaseHeight;\n character.HeightModifier = verdan_medium.HeightModifier;\n character.BaseWeight = verdan_medium.BaseWeight;\n character.WeightModifier = verdan_medium.WeightModifier;\n } else if (\n race === \"Warforged\"\n ) {\n character.Race = warforged.Race;\n character.AdultAge = warforged.AdultAge;\n character.MaxAge = warforged.MaxAge;\n character.BaseHeight = warforged.BaseHeight;\n character.HeightModifier = warforged.HeightModifier;\n character.BaseWeight = warforged.BaseWeight;\n character.WeightModifier = warforged.WeightModifier;\n } else if (race === \"Warforged, Juggernaut\") {\n character.Race = warforged_juggernaut.Race;\n character.AdultAge = warforged_juggernaut.AdultAge;\n character.MaxAge = warforged_juggernaut.MaxAge;\n character.BaseHeight = warforged_juggernaut.BaseHeight;\n character.HeightModifier = warforged_juggernaut.HeightModifier;\n character.BaseWeight = warforged_juggernaut.BaseWeight;\n character.WeightModifier = warforged_juggernaut.WeightModifier;\n } else if (race === \"Yuan-ti Pureblood\") {\n character.Race = yuan_ti_pureblood.Race;\n character.AdultAge = yuan_ti_pureblood.AdultAge;\n character.MaxAge = yuan_ti_pureblood.MaxAge;\n character.BaseHeight = yuan_ti_pureblood.BaseHeight;\n character.HeightModifier = yuan_ti_pureblood.HeightModifier;\n character.BaseWeight = yuan_ti_pureblood.BaseWeight;\n character.WeightModifier = yuan_ti_pureblood.WeightModifier;\n }\n}", "function createCharacters() {\n _case_ = new character('_case_', 110, 4, 20);\n acid = new character('acid', 120, 2, 10);\n brute = new character('Brüte', 170, 1, 15);\n fdat = new character('f.dat', 150, 1, 12);\n }", "function mix() {\n const characterNum = randomNum(10);\n const characterNum2 = randomNum(10);\n const character = characters[characterNum];\n const quotedCharacter = characters[characterNum2];\n const quoteListLength = content[quotedCharacter].quotes.length;\n const quoteNum = randomNum(quoteListLength);\n const quotation = content[quotedCharacter].quotes[quoteNum];\n const image = content[character].image;\n monoImage.src = image;\n monoImage.alt = \"image of \" + character;\n monoQuote.innerHTML = quotation;\n\n}", "function getRace(){\n\tvar races = ['human', 'elf', 'half-elf', 'drow', 'half-orc', 'tiefling', 'gnome',\n\t'dwarf', 'dragonborn', 'halfling'];\n\treturn races[Math.floor((Math.random() * races.length) + 1)-1];\n}", "function getRandomNumCrystals() {\n // Crystals object.\nreturn { \n red: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/red.png\"\n },\n blue: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/blue.jpeg\"\n },\n yellow: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/yellow.jpg\"\n },\n green: {\n points: Math.floor(Math.random()*12) + 1,\n imageUrl: \"assets/images/green.jpg\"\n },\n\n }\n}", "function makeName() {\n let prefixArr = [];\n let suffixArr = [];\n let name;\n\n if (mySpecies.length < 1) return; // Don't make a name if there are no traits\n // Populate the prefix and suffix arrays\n for ( let i = 0; i < mySpecies.length; i ++ ) {\n for ( let j = 0; j < mySpecies[i].prefixes.length; j ++ ) {\n prefixArr.push(mySpecies[i].prefixes[j]);\n }\n for ( let k = 0; k < mySpecies[i].suffixes.length; k ++ ) {\n suffixArr.push(mySpecies[i].suffixes[k]);\n }\n }\n // Get random values from the prefix and suffix arrays\n let pre1 = getRandom(prefixArr);\n let pre2;\n let suf = getRandom(suffixArr);\n if (mySpecies.length <= 2) {\n name = pre1 + suf;\n } else {\n let pre2 = getRandom(prefixArr);\n // Ensure unique prefixes\n while ( pre2 == pre1 ) {\n pre2 = getRandom(prefixArr);\n }\n name = pre1 + pre2 + suf;\n }\n name = name.charAt(0).toUpperCase() + name.slice(1);\n document.getElementById(\"name\").innerHTML = name;\n}", "function makeChar() {\n\tvar probability=points(0,\"\")/hardness;//according to hardness of game\n\tif(typeof alphabets === 'undefined' || alphabets === \"\"){\n\t\tvar index=Math.floor(Math.random() * 5)+2;\n\t\talphabets=words[index][Math.floor(Math.random() * words[index].length)];\n\t\tif(points(0,\"\")===0){\n\t\t\t//showing Hint only for new players\n\t\t\tif(typeof(Storage) !== \"undefined\") {\n\t\t\t\tif(localStorage.getItem(\"score\")===null){\n\t\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\thint(alphabets);//help player to learn game\n\t\t\t}\n\t\t}\n\t\ttext = alphabets.charAt(0);\n\t\talphabets = alphabets.slice(1);\t\n\t}else if(points(0,\"\") >=bombPoint){\n\t\t\ttext = 'B';\n\t\t\tbombPoint*=3;\n\t}else if(points(0,\"\") >=blockPoint){\n\t\t\ttext = 'N';\n\t\t\tblockPoint*=3;\n\t}else{\n\t\tif(Math.random() <= probability){\n\t\t\t//if propability goes up, game gets harder\n\t\t\ttext = randomChar();\n\t\t}else{\n\t\t\ttext = alphabets.charAt(0);\n\t\t\talphabets = alphabets.slice(1);\n\t\t}\n\t}\n\treturn text;\n}", "function createCrystals() {\n $(\"#crystals\").empty();\n for (var i=0; i < 4; i++) {\n var imageCrystal = $(\"<img>\");\n imageCrystal.addClass(\"crystal-image\");\n imageCrystal.attr(\"src\", \"assets/images/crystal.png\");\n imageCrystal.attr(\"data-crystalvalue\", Math.floor(Math.random() * 12) + 1);\n $(\"#crystals\").append(imageCrystal);\n }\n }", "function getCharImage(characterValue) { \r\n \r\n var filmValue = $StarWarsFilms.val();\r\n \r\n if (characterValue === '87'){\r\n return '<img src=\"Images/char' + characterValue + '.png\" />';\r\n }\r\n else if (filmValue === '7' && characterValue === '14')\r\n {\r\n return '<img src=\"Images/HanForceAwakens.jpg\" />';\r\n } \r\n else {\r\n return '<img src=\"Images/char' + characterValue + '.jpg\" />';\r\n } \r\n }", "function genCompInput() {\n let x = Math.floor(Math.random() * 3);\n switch (x) {\n case 0:\n return 'rock';\n break;\n case 1:\n return 'paper';\n break;\n case 2:\n return 'scissors';\n break;\n default:\n break;\n }\n}", "async function generateImages() {\n clear();\n console.log(chalk.magentaBright(figlet.textSync('profile-scraper'))+\"\\n\");\n throbber.start(\"Starting...\");\n for (let index = 1; index < 26; index++) {\n const fileName = `agent-profile-${(index + \"\").padStart(3, \"0\")}.jpg`;\n await sleep(5000);\n await fetchAndWriteImage(fileName)\n }\n throbber.success(\"Finished, all files written!\")\n}", "function randomizeCards() {\n\tvar imgArr = ['0 0', '0 0', '0 160px', '0 160px', \t\t\t\t\t//array of images\n\t\t\t\t '0 360px', '0 360px', '200px 190px', '200px 190px',\n\t\t\t\t '200px 360px', '200px 360px', '420px 360px', '420px 360px', \n\t\t\t\t '200px 600px', '200px 600px', '420px 590px', '420px 590px', \n\t\t\t\t '410px 160px', '410px 160px'];\n\tvar i = 0;\n\t\n\tfor ( i ; i < cardsArr.length ; i++ ) {\n\t\tvar elCard = cardsArr[i];\n\t\trandomIndex = Math.floor(Math.random() * (imgArr.length));\n\t\telCard.style.background = 'url(monetliliestiles.jpg) ' + imgArr[randomIndex];\n\t\timgArr.splice(randomIndex,1);\n\t\telCard.className = 'card assigned';\n\t}\n}", "function generateRandomGoats() {\n\n // randomIndex from our array\n var leftIndex = Math.floor(Math.random() * GoatImage.allImages.length);\n\n var rightIndex = Math.floor(Math.random() * GoatImage.allImages.length);\n\n while (rightIndex === leftIndex) {\n rightIndex = Math.floor(Math.random() * GoatImage.allImages.length);\n }\n\n var leftGoat = GoatImage.allImages[leftIndex];\n var rightGoat = GoatImage.allImages[rightIndex];\n\n return [leftGoat, rightGoat];\n}", "function genChar(arr){\n\n var rand = Math.random()\n var l = arr.length;\n var i = Math.floor(l * rand); //generate random index\n var char = arr[i]; //select random character from array\n var c = char.toString()\n\n return c\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2. Write a function called starWarsString, which accepts a number. You should then make an AJAX call to the Star Wars API ( ) to search for a specific character by the number passed to the function. Your function should return a promise that when resolved will console.log the name of the character.
function starWarsString(num) { return new Promise(async function(resolve, reject) { var characterData = await $.getJSON(`https://swapi.co/api/people/${num}`); // return data of character var filmData = await $.getJSON(characterData.films[0]); // return data of first film they starred in var planetData = await $.getJSON(filmData.planets[0]); resolve(`${characterData.name} is featured in the ${filmData.title}, directed by ${filmData.director} and it takes place on ${planetData.name}`); }); }
[ "async function fetchCharacter() { //async permet un comport. asynchrone basé sur des promesses, évitant ainsi les chaînes de promesses.\n try {\n const api = await fetch('https://character-database.becode.xyz/characters');\n const data = await api.json();\n console.log(data);\n return data;\n\n } catch (error) {\n console.error(error);\n }\n }", "function findSpecialAbilityTemplatesQuery(str, callback) {\n var result;\n var suggestions;\n\n if (window.XMLHttpRequest) {\n xmlhttp=new XMLHttpRequest();\n } else {\n xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n xmlhttp.onreadystatechange=function() {\n if (xmlhttp.readyState==4 && xmlhttp.status==200) {\n result = xmlhttp.responseText;\n suggestions = JSON.parse(result);\n callback(suggestions);\n }\n }\n\n var params = \"get_special_abilities_suggestions=\".concat(str);\n xmlhttp.open(\"POST\", \"create-character.php\", true);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.send(params);\n}", "function searchCards(response, numItems, offset, name) {\n let sql = \"SELECT * FROM cards WHERE card_name LIKE '%\" + name + \"%';\";\n\n if (numItems != undefined && offset != undefined) {\n sql += \" ORDER BY id LIMIT \" + numItems + \" OFFSET \" + offset;\n }\n\n connectionPool.query(sql, function(err, result) {\n\n if (err) {\n response.status(HTTP_STATUS.INTERNAL_SERVER_ERROR)\n response.json({ 'error': true, 'message': +err })\n return;\n\n }\n\n let returnObject = { data: result }\n\n response.json(returnObject.data);\n });\n}", "async function getWordFromAPI() {\n // fetch\n const response = await fetch(\"https://random-word-api.herokuapp.com/word?number=1&swear=0\");\n // get data\n const data = await response.json();\n // return\n return data;\n}", "function getCharacterByName (req, res) {\n characterDataModel.getCharacterCollection()\n .then(function(collection){\n collection.find({\n name: req.query.characterName\n })\n .toArray(function(err, items) {\n if(err) {\n res.send(err);\n } else {\n res.send(items);\n }\n })\n })\n .catch(console.error.bind(this));\n}", "function get_letter(passed_id) {\n // loop to iterate through the 7 pieces on the rack\n for(var i = 0; i < 7; i++) {\n// console.log(\"Passing; \" + passed_id);\n // case to check if the letter was found\n if(scrabble_tiles[i].id == passed_id) {\n return scrabble_tiles[i].letter;\n }\n }\n // error to indicate if something went wrong.\n return -1;\n}", "function getBySkillName(req, res) {\n const query = {};\n let name = '';\n\n // Players can search for skills with multiple words in the name, but\n // these skills must be entered as with '-' instead of spaces, so\n // this code replaces the '-' with ' '\n if (req.params.skillName) {\n name = req.params.skillName;\n name.replace('-', ' ');\n }\n\n searchBySkillNamePrefix(query, name, res);\n }", "function marvelWikiSearch(msg, characterName){\n\n // add the character name to the Marvel wiki search url\n marvelWikiUrl = \"http://marvel.com/universe3zx/index.php?ns0=1&search=\" + characterName + \"&title=Special%3ASearch&fulltext=Advanced+search\";\n request(marvelWikiUrl, function (error, response, html) {\n // if no errors and good status code\n // else send an error message because the Marvel sites may be down\n if (!error && response.statusCode < 300){\n // load the page html with cheerio\n $ = cheerio.load(html);\n\n // if a character was found and a result comes back, get the title of the character and url\n // else character might not exist or suggest spelling is checked and try again\n if($('#Page_title_matches + h2 + ul.mw-search-results li:first-of-type').length > 0){\n $('#Page_title_matches + h2 + ul.mw-search-results li:first-of-type').filter(function(){\n marvelWikiPageLink = $(this).find('a').attr('href');\n marvelWikiPageTitle = $(this).find('a').attr('title');\n msg.send(\"I had to do some digging, but I found \" + marvelWikiPageTitle + \" on http://www.marvel.com\" + marvelWikiPageLink + \" . Hope that's the right character.\");\n });\n }else{\n msg.send(\"I couldn't find anything for \"+ characterName +\". Are you sure they are a Marvel character? Can you check the spelling and try again?\");\n }\n }else{\n msg.send(\"Marvel's sites might be down right now, please try again later.\");\n }\n return false;\n }); // end of request\n}", "function apiCall(yourChoice){\n // API Key from NU Bootcamp\n var apiKey = \"dc6zaTOxFJmzC\";\n // Construct query URL, using paramaters apiKey, q=search term, and limit= how many results you want returned\n var URL= \"http://api.giphy.com/v1/gifs/search?api_key=\" + apiKey + \"&q=\" + yourChoice + \"&limit=10\";\n // getJSON, similar to .ajax, but simpler \n $.getJSON(URL, function(response){\n // Iterate over entire response object \n for (var index = 0; index < response.data.length; index++) {\n // Get still URL, fixed_height, see API docs \n var stillURL = response.data[index].images[\"fixed_height_still\"].url;\n // get full movement GIF URL, fixed_height, see API docs \n var gifURL = response.data[index].images[\"fixed_height\"].url;\n // get rating, see API docs \n var rating = response.data[index].rating;\n // Pass above variables to print the images and rating to the page\n printToPage(stillURL, gifURL, rating);\n };\n });\n}", "function getNamePiece(){\n\tvar pieces = ['el', 'li', 'tat', 'io', 'on', 'fa', 'ill', 'eg', 'aer', 'shi', 'lys', 'and',\n\t'whi', 'dus', 'ney', 'bal', 'kri', 'ten', 'dev', 'ep', 'tin', 'ton', 'ri', 'mynn', 'ben', 'la', 'sam',\n\t'hag', 'is', 'ya', 'tur', 'pli', 'ble', 'cro', 'stru', 'pa', 'sing', 'rew', 'lynn', 'lou', 'ie', 'zar',\n\t'an', 'ise', 'tho', 'vag', 'bi', 'en', 'fu', 'dor', 'nor', 'ei', 'zen', 'is', 'val', 'zon',\n\t'lu', 'tur', 'op', 'sto', 'ep', 'tha', 'dre', 'ac', 'ron'];\n\treturn pieces[Math.floor((Math.random() * pieces.length) + 1)-1];\n}", "function getWeatherCode(){\n\n var weather = $.ajax({\n url: \"http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20weather.forecast%20WHERE%20location%3D%2710001%27&format=json\",\n dataType: \"jsonp\",\n contentType: \"application/json; charset=utf-8\"\n }).done( function() {\n // debugger;\n var weatherCodeString = weather.responseJSON.query.results.channel.item.condition.code;\n weatherCode = parseInt( weatherCodeString, 10 );\n console.log(\" hey i'm working at least \");\n });\n\n}", "function showSearch(request, response) {\n let SQL = 'SELECT * FROM species ';\n\n if (request.body.pages === undefined) { SQL += 'LIMIT 50' }\n if (request.body.pages) { SQL += `ORDER BY national_dex_id OFFSET ${parseInt(request.body.pages) * 50} FETCH NEXT 50 ROWS ONLY` }\n\n // Get the random Pokemon object\n return getRandomPokemon()\n .then((randomMon) => {\n\n return client.query(SQL)\n .then(result => {\n response.render('./pages/search', { result: result.rows, types: ['none', 'normal', 'fighting', 'flying', 'poison', 'ground', 'rock', 'bug', 'ghost', 'steel', 'fire', 'water', 'grass', 'electric', 'psychic', 'ice', 'dragon', 'dark', 'fairy'], random: randomMon })\n })\n })\n .catch(err => handleError(err, response))\n}", "async function getNameFromGenreId(genreId) {\n // api url info\n type = \"genre/movie/list\";\n let url = apiUrl + type + apiKey;\n\n fetch(url).then(response => response.json())\n .then(function(obj) {\n\n for (let i = 0; i < obj.genres.length; i++) {\n if (obj.genres[i].id === genreId) {\n genreName = obj.genres[i].name;\n return genreName;\n\n }\n\n }\n\n\n\n }).catch(function(error) {\n console.error(\"Something went wrong\");\n console.error(error);\n })\n\n}", "function lookup_knowledge(c) {\n for(var i = 0; i < character_knowledge.length; i++) {\n if(character_knowledge[i].character == c) {\n return character_knowledge[i].knowledge;\n }\n }\n console.log(\"Couldn't find knowledge for character \" + c);\n return undefined;\n}", "function fetchWord() {\n\n return fetch('assets/word_list.txt')\n .then(response => response.text().then(text => text.split(\"\\n\")))\n .then(arr => {\n document.getElementById(\"word\").innerHTML = arr[numr];\n });\n}", "function nameFind() {\n inquirer.prompt({\n type: \"input\",\n name: \"planet\",\n message: \"Search for: \"\n }).then(function (answers) {\n // LIKE % * % used for more search flexibility\n var planetName = \"SELECT * FROM planets WHERE fpl_name LIKE '%\" + answers.planet + \"%'\";\n // query planets table for search string\n connection.query(planetName, function (error, response) {\n if (error) throw error;\n if (response == 0) {\n // each search query function has the potential of generating this message and rerunning\n console.log(\"--------------------------------\");\n console.log(\" No results. Try again. \");\n console.log(\"--------------------------------\");\n nameFind();\n } else {\n // returns a small subset of the planetary data available at\n // https://exoplanetarchive.ipac.caltech.edu/cgi-bin/TblView/nph-tblView?app=ExoTbls&config=compositepars\n // a smaller subset of these results is used for arbitrary cost calculation\n console.log(\"------------------------------------------------\");\n console.log(\" Planetary Data Results for '\" + answers.planet + \"'\");\n console.log(\"------------------------------------------------\");\n // loop through the query response and show matches\n for (var i = 0; i < response.length; i++) {\n console.log(\" Planet name: \" + response[i].fpl_name\n + \"\\n Discovery Method: \" + response[i].fpl_discmethod\n + \"\\n Discovery Year: \" + response[i].fpl_disc\n + \"\\n Orbital Period [days]: \" + response[i].fpl_orbper\n + \"\\n Eccentricity: \" + response[i].fpl_eccen\n + \"\\n Planet Mass [Earth mass]: \" + response[i].fpl_bmasse\n + \"\\n Planet Mass [Jupiter mass]: \" + response[i].fpl_bmassj\n + \"\\n Planet Radius [Earth radii]: \" + response[i].fpl_rade\n // converted temperature from Kelvin to Fahrenheit\n + \"\\n Equilibrium Temperature [K]: \" + response[i].fpl_eqt\n + \" (\" + ((((parseFloat(response[i].fpl_eqt) * 9 / 5) * 10000) - (459.67 * 10000)) / 10000) + decoder.write(deg) + \"F)\"\n + \"\\n Number of Stars in System: \" + response[i].fpl_snum\n + \"\\n Distance [pc (parsec)]: \" + response[i].fst_dist\n + \"\\nStellar Age [Gyr (gigayear)]: \" + response[i].fst_age\n + \"\\n Purchased (0=no, 1=yes): \" + response[i].rmk_cust);\n console.log(\"------------------------------------------------\");\n }\n // after each search the buyNow function runs\n buyNow();\n }\n });\n });\n}", "async search() {\n if (this.#selected !== \"\") {\n this.#name.value = this.#name.value.trim();\n\n const query = {\n type: this.#selected,\n };\n\n if (this.#rarity.value !== \"\") {\n query.rarity = this.#rarity.value;\n }\n\n let result = await DataBase.search(\"armor\", query, {\n id: \"true\",\n name: \"true\",\n rarity: \"true\",\n defense: {\n base: \"true\",\n },\n \"resistances.fire\": \"true\",\n \"resistances.water\": \"true\",\n \"resistances.ice\": \"true\",\n \"resistances.thunder\": \"true\",\n \"resistances.dragon\": \"true\",\n });\n\n //Matches exist\n if (result !== undefined && result.length !== 0) {\n this.clearSearch();\n\n console.log(result);\n\n result.forEach((record) => {\n if (\n record.name.toLowerCase().includes(this.#name.value.toLowerCase())\n ) {\n let card = this.#createMiniCard(record);\n this.#result.appendChild(card);\n }\n });\n } else {\n this.#result.innerHTML = this.#createWarnCard(\"No results\");\n }\n } else {\n alert(\"Select an armor slot\");\n }\n }", "async function FindEmoji() {\n let emojiService = new emoji.EmojiService(process.env.MICRO_API_TOKEN);\n let rsp = await emojiService.find({\n alias: \":beer:\",\n });\n console.log(rsp);\n}", "getUser() { \n const min = 1;\n const max = 10;\n const userNumber = Math.floor (Math.random () * (max - min)) + min;\n console.log(userNumber);\n fetch(`https://jsonplaceholder.typicode.com/users/${userNumber}`)\n .then(response => response.json())\n .then(json =>{username = json.username;\n console.log(username)} )\n .catch(error => {\n console.log (error);\n usernameP.innerHTML = 'No';\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
========================================================================== Insert string s in the dictionary and set match_head to the previous head of the hash chain (the most recent string with same hash key). Return the previous length of the hash chain. IN assertion: all calls to to INSERT_STRING are made with consecutive input characters and the first MIN_MATCH bytes of s are valid (except for the last MIN_MATCH1 bytes of the input file).
function INSERT_STRING() { ins_h = ((ins_h << H_SHIFT) ^ (window[strstart + MIN_MATCH - 1] & 0xff)) & HASH_MASK; hash_head = head1(ins_h); prev[strstart & WMASK] = hash_head; head2(ins_h, strstart); }
[ "findInsertIndexInLine(char, line) {\n let left = 0;\n let right = line.length - 1;\n let mid, compareNum;\n\n if (line.length === 0 || char.compareTo(line[left]) < 0) {\n return left;\n } else if (char.compareTo(line[right]) > 0) {\n return this.struct.length;\n }\n\n while (left + 1 < right) {\n mid = Math.floor(left + (right - left) / 2);\n compareNum = char.compareTo(line[mid]);\n\n if (compareNum === 0) {\n return mid;\n } else if (compareNum > 0) {\n left = mid;\n } else {\n right = mid;\n }\n }\n\n if (char.compareTo(line[left]) === 0) {\n return left;\n } else {\n return right;\n }\n }", "function hasher(data) {\n var pre_string = data.lastname + data.firstname + data.gender + data.dob + data.drug;\n var hash = '', curr_str;\n\n hash = Sha1.hash(pre_string);\n\n /**\n // Increment 5 characters at a time\n for (var i = 0, len = pre_string.length; i < len; i += 5) {\n curr_str = '';\n\n // Extract 5 characters at a time\n for (var j = 0; j < 5; j++) {\n if (pre_string[i + j]) {\n curr_str += pre_string[i + j]\n }\n }\n\n // Hash the characters and append to hash\n var temp = mini_hash(curr_str); // Get number from the string\n var fromCode = String.fromCharCode(mini_hash(curr_str));\n hash += fromCode;\n\n } */\n\n\n return hash;\n}", "insert(key, value) {\n let index = this.hashFn(key);\n let bucket = this.storage[index];\n let item = new CollisionNode(key, value);\n\n // Create a new bucket if none exist\n if (!bucket) {\n bucket = new CollisionList(item);\n this.storage[index] = bucket;\n bucket.count++; // count here refers to linked list count; pass by reference\n this.count++; // count here refers to hashtable's count\n\n return 'New bucket created';\n }\n else {\n let current = bucket.head;\n\n // If the head has null next it is there is only one node in the collisionlist\n if (!current.next) {\n current.next = item;\n }\n else {\n // move to the end of the collisionlist\n while (current.next) {\n current = current.next;\n }\n\n current.next = item;\n }\n bucket.count++;\n this.count++;\n\n return 'New item placed in bucket at position ' + bucket.count;\n }\n }", "function AlignSHA1(str) {\n\t\t\t\t\t\t\tvar nblk = ((str.length + 8) >> 6) + 1,\n\t\t\t\t\t\t\t\tblks = new Array(nblk * 16);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (var i = 0; i < nblk * 16; i++)\n\t\t\t\t\t\t\t\tblks[i] = 0;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (i = 0; i < str.length; i++)\n\t\t\t\t\t\t\t\tblks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tblks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);\n\t\t\t\t\t\t\tblks[nblk * 16 - 1] = str.length * 8;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treturn blks;\n\t\t\t\t\t\t}", "_match(predecessor, suc, stringMatch) {\n\t\t/*\n\t\t[\n\t\t\t{\n\t\t\t\tstartIndex: 1, //Inclusive\n\t\t\t\tendIndex: 2, //Exclusive\n\t\t\t\tsuccessor: \"some string\"\n\t\t\t},\n\t\t\t{\n\t\t\t\tstartIndex: 2,\n\t\t\t\tendIndex, 4,\n\t\t\t\tsuccessor: \"other string\"\n\t\t\t}\n\t\t]\n\t\t*/\t\t\n\t\t//NOTE - predecessors have 2 restricted characters; '<' and '>' - These are used for context sensative predecessors\n\t\tlet successorList = this._buildSuccessorList(predecessor);\n\t\tlet contextSensative = false;\n\t\tlet context = [];\n\t\tlet matchPredecessor = predecessor\n\t\tif(predecessor.indexOf('>') >= 0 || predecessor.indexOf('<') >= 0) {\n\t\t\t//We know that this will be context sensative\n\t\t\tcontextSensative = true;\n\t\t\tcontext = predecessor.split(/[<>]+/);\n\t\t\tmatchPredecessor = context[1]; //This assumes there is a forward and backward context TODO: fix this\n\t\t}\n\t\t\n\t\t//Find all matches for the predecessor in the axiom\n\t\tlet returnValue = [];\n\t\tlet sIndex = this._matchPredecessor(stringMatch, matchPredecessor, contextSensative, context[0], context[2], 0);\n\t\twhile(sIndex >= 0) {\n\t\t\tlet chosenSuc = this._chooseSuccessor(successorList);\n\t\t\tlet object = {\n\t\t\t\tstartIndex: sIndex,\n\t\t\t\tendIndex: sIndex + 1, //TODO: how do this NOTE - this currently assumes only one character is getting replaced. For the scope of this project that is probably fine, but if I want to make this more generic, I should find a better way to do this. \n\t\t\t\tsuccessor: chosenSuc\n\t\t\t}\n\t\t\treturnValue.push(object);\n\t\t\tsIndex = this._matchPredecessor(stringMatch, matchPredecessor, contextSensative, context[0], context[2], sIndex + 1);\n\t\t}\n\t\t//Return a list of the index's that match\n\t\treturn returnValue;\n\t}", "function rstr_sha1(s)\n\t\t{\n\t\t return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));\n\t\t}", "function AlignSHA1(str) {\n\n\t\tvar nblk = ((str.length + 8) >> 6) + 1, blks = new Array(nblk * 16);\n\n\t\tfor (var i = 0; i < nblk * 16; i++)\n\t\t\tblks[i] = 0;\n\n\t\tfor (i = 0; i < str.length; i++)\n\n\t\t\tblks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);\n\n\t\tblks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);\n\n\t\tblks[nblk * 16 - 1] = str.length * 8;\n\n\t\treturn blks;\n\n\t}", "function longest_substring_with_k_distinct(str, k) {\n if( k === 0 || str.length === 0) return 0;\n // TODO: Write code here\n let windowStart = 0,\n windowEnd = 0,\n maxLen = 0,\n frequency = {};\n\n \n for(windowEnd; windowEnd < str.length; windowEnd++){\n if(!(str[windowEnd] in frequency)){\n frequency[str[windowEnd]] = 0;\n }\n frequency[str[windowEnd]] += 1;\n // console.log(frequency[]);\n }\n console.log(frequency['a']);\n maxLen = Math.max(maxLen, windowEnd - windowStart);\n\n return maxLen;\n}", "function getEditDistance(string1, string2){\n\n var dist = 0; \n var a1 = string1.toLowerCase().split(\"\");\n var a2 = string2.toLowerCase().split(\"\");\n var smaller = a2;\n \n if (a1.length < a2.length){\n dist += a2.length - a1.length;\n smaller = a1;\n } else {\n dist += a1.length - a2.length; \n }\n \n for (index in smaller){\n if(a1[index] != a2[index]){\n dist++;\n }\n }\n\n return dist; \n}", "function countingSort(stringArr, pfxlen){\n if(pfxlen === undefined){ pfxlen = 1; }\n\n var i, k, p, counts, sortedArr;\n\n /* For a given item, reuturn its 0-based array index integer key.\n * This should be a constant-time function mapping an item/prefix\n * to its array index.\n */\n var _keyfn = function(idx, itm){\n return punycode.ucs2.decode(itm[idx])[0];\n };\n\n // Prefix block method:\n // idx, start, end\n var prefixBlocks = [[0, 0, stringArr.length - 1]];\n var block, keyfn, idx, pfx, curPfx, curStart, start, end;\n\n while(prefixBlocks.length > 0){\n sortedArr = [];\n block = prefixBlocks.pop();\n idx = block[0]; start = block[1]; end = block[2];\n if(idx > pfxlen){ break; }\n if(start === end){ continue; }\n\n keyfn = partial(_keyfn, [idx]);\n counts = countItems(stringArr, keyfn, start, end);\n counts = init0(counts);\n counts = accumulate(counts);\n\n for(i=start; i<=end; i++){\n k = keyfn(stringArr[i]);\n sortedArr[counts[k]] = stringArr[i];\n counts[k]++;\n }\n\n // copy sorted items back to original array (sub-range now sorted)\n for(i=0; i<sortedArr.length; i++){\n stringArr[i+start] = sortedArr[i];\n }\n\n if(idx < pfxlen){\n curStart = start;\n curPfx = stringArr[start].slice(0, idx+1);\n for(i=start; i<=end; i++){\n pfx = stringArr[i].slice(0, idx+1);\n if(pfx !== curPfx){\n if(curStart !== i-1){ // don't add a 1-element sub-range\n prefixBlocks.push([idx+1, curStart, i-1]);\n }\n curStart = i;\n curPfx = stringArr[i].slice(0, idx+1);\n }\n }\n if(curStart !== end){ // don't add a 1-element sub-range\n prefixBlocks.push([idx+1, curStart, end]);\n }\n }\n\n }\n\n return stringArr;\n}", "write(str) {\n Files.write(nodePath.join(Files.gitletPath(), 'objects', Util.hash(str)), str);\n return Util.hash(str);\n }", "function compression(str){\n \n let output = '';\n let count = 0;\n for(let i = 0; i < str.length; i++) {\n count++;\n if(str[i] != str[i + 1]) {\n output += str[i] + count;\n count = 0;\n }\n }\n return output; \n }", "insert (data, size = data.length) {\n for (let i = 0; i < this.nHashes; i++) {\n const idx = hash(i, this.nHashes, data, size) % this.nBits\n if (this.bfCntr) {\n let num = bfGet(this.bfCntr, idx)\n num++\n bfSet(this.bfCntr, idx, num)\n }\n if (this.bfMask)\n this.bfMask.set(idx, true)\n }\n return this\n }", "function getMinPartition(s, i=0, j=s.length-1)\n{\n let ans = Number.MAX_VALUE\n let count = 0\n\n if (isPalindrome(s.substring(i, j + 1)) || s==='')\n return 0\n \n for(let k = i; k < j; k++)\n {\n count = getMinPartition(s, i, k) + getMinPartition(s, k + 1, j) + 1;\n ans = Math.min(ans, count);\n }\n return ans\n}", "function calculatelpstable(substr) {\n let i=1;\n let j=0;\n let lps = new Array(substr.length).fill(0); // [0,0,0,0,0,0,0]\n while(i<substr.length) {\n if(substr[i] === substr[j]){\n lps[i]=j+1;\n i++;j++;\n } else {\n if(j!==0){\n j=lps[j-1];\n } else{\n i++;\n }\n }\n }\n return lps;\n}", "function getMatches(stringObject) {\n// For each word in a string...\n for (r = 0; r < stringObject.firstStringWords.length; r++) {\n // Compare it to each word in the next string in the array.\n for (j = 0; j <= stringObject.secondStringWords.length; j++) {\n if (stringObject.firstStringWords[r] === stringObject.secondStringWords[j]) {\n stringObject.matchedPhrases.push(stringObject.firstStringWords[r])\n }\n }\n }\n // Removes smaller matches and just keeps the largest match found.\n stringObject.matchedPhrases = reduceMatches(stringObject.matchedPhrases)\n\n // Count matches.\n stringObject.count = stringObject.matchedPhrases.length\n\n // Calculate a percentage that each string is similar to one another.\n let matchedWordCount = 0\n if (stringObject.matchedPhrases.length !== 0) {\n matchedWordCount = stringObject.matchedPhrases.join(\" \").split(\" \").length\n }\n const allWordCount = stringObject.firstString.split(\" \").length\n stringObject.percentMatch = (Math.round((matchedWordCount/allWordCount) * 100) / 100)\n\n // Remove properties from the comparison that we don't want to output.\n delete stringObject.firstStringWords\n delete stringObject.secondStringWords\n\n return stringObject\n}", "function generateHash(string) {\n\treturn crypto.createHash('sha256').update(string + configuration.encryption.salt).digest('hex');\n}", "async insert (entry) {\n try {\n console.log('entry: ', entry)\n\n // Add the entry to the Oribit DB.\n const hash = await _this.orbit.db.put(entry.key, entry.value)\n console.log('hash: ', hash)\n\n return hash\n } catch (err) {\n console.error('Error in p2wdb.js/insert()')\n throw err\n }\n }", "insert(key, value) {\n // const strKey = typeof key === 'number' ? key.toString() : key;\n const index = getIndexBelowMax(key, this.limit);\n const bucket = this.storage;\n\n if (bucket.get(index) === undefined) { // No bucket at index yet\n bucket.set(index, [[key, value]]); // Create bucket containing a k/v pair\n return; // Completely done. Exit the insert function.\n }\n\n let keyFound = false; // flag to hold state: key present in bucket?\n bucket.get(index).forEach((kvPair) => {\n if (kvPair[0] === key) { // Check to see if bucket already has key\n kvPair[1] = value; // Found; set kvPair value to new value\n keyFound = true; // Set flag true so kvPair won't be added again at end\n return;\n }\n });\n if (!keyFound) bucket.get(index).push([key, value]); // If key wasn't found in bucket, add k/v pair\n }", "add(key, value) {\n let index = Hash.hash(key, this.sizeLimit);\n let inserted = false;\n\n if (this.hashTable[index] === undefined) {\n this.hashTable[index] = [[key, value]];\n inserted = true;\n } else {\n for (let i = 0; i < this.hashTable[index].length; i++) {\n if (this.hashTable[index][i][0] === key) {\n this.hashTable[index][i][1] = value;\n inserted = true;\n }\n }\n }\n\n if (inserted === false) {\n this.hashTable[index].push([key, value]);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Base interface for progress events.
function HttpProgressEvent() { }
[ "function onProgress(e) {\n if (video.buffered.length > 0)\n {\n var end = video.buffered.end(0),\n start = video.buffered.start(0);\n load_bar.setAttribute(\"width\", Math.ceil((end - start) / video.duration * 100).toString());\n }\n}", "seek(position) {\r\n if (this.isSeeking)\r\n this.progress = position * 100;\r\n }", "_updateHandleAndProgress(newValue) {\n const max = this._effectiveMax;\n const min = this._effectiveMin;\n\n // The progress (completed) percentage of the slider.\n this._progressPercentage = (newValue - min) / (max - min);\n // How many pixels from the left end of the slider will be the placed the affected by the user action handle\n this._handlePositionFromStart = this._progressPercentage * 100;\n }", "onAudioProgress(audioInfo) {\n // console.log('audio progress', audioInfo)\n }", "PrintProgress() {\n process.stdout.clearLine()\n process.stdout.cursorTo(0) \n process.stdout.write('Progress: '+this.folIter+' from '+this.totalFol)\n }", "function ProgressBar(fraction, size_arg = new ImVec2(-1, 0), overlay = null) {\r\n bind.ProgressBar(fraction, size_arg, overlay);\r\n }", "sendProgress() {\n // compute number of tests if not done so already\n if (!this.testCount) {\n this.testCount = 0;\n this.frameworks.forEach(framework => {\n framework.tests.forEach(test => {\n this.testCount++;\n });\n });\n }\n\n var percentage = (this.testsComplete / this.testCount) * 100;\n this.socket.emit('benchmark_progress', {'percent' : percentage});\n }", "function logProgress(msg, err) {\n if (err) {\n console.log(msg, err);\n } else {\n process.stdout.write(msg);\n }\n\n // send progress message to browser client\n if (sio) {\n sio.sockets.emit('status_data', {\n msg: msg\n });\n }\n}", "notifyLoading(isloading) {\n \n if (isloading) {\n this.dispatchEvent(new CustomEvent('loading'));\n } else {\n this.dispatchEvent(CustomEvent('doneloading'));\n }\n \n\n }", "streamModeProgressFunction(dltotal, dlnow, ultotal, ulnow) {\n if (this.streamError)\n throw this.streamError;\n const ret = this.streamUserSuppliedProgressFunction\n ? this.streamUserSuppliedProgressFunction.call(this.handle, dltotal, dlnow, ultotal, ulnow)\n : 0;\n return ret;\n }", "#updateFormProgress() {\n if (this.#steps?.length) {\n let activeStepIndex = this.#steps.findIndex(\n ({ name }) => name === this.activeStep\n );\n let activeStepCount = activeStepIndex + 1;\n let progress =\n Math.ceil((activeStepIndex / (this.#steps.length - 1)) * 100) || 10;\n let indicator = this.#progressBar.querySelector(\".indicator\");\n indicator.style.setProperty(\"--progress\", progress + \"%\");\n // Ensure progressbar starts translated at -100% before we\n // set --progress to avoid a layout race.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n indicator.toggleAttribute(\"ready\", true);\n });\n });\n this.#progressBar.setAttribute(\"aria-valuenow\", activeStepCount);\n this.#progressBar.setAttribute(\n \"aria-label\",\n interpolate(gettext(\"Step %s of %s\"), [\n activeStepCount,\n this.#steps.length,\n ])\n );\n }\n }", "getProgress(execution){\n return {\n total: 1,\n current: execution.status === JOB_STATUS.COMPLETED ? 1 : 0\n }\n }", "function startProgessBar() {\r\n\tgProgressBar = new ProgressBar(\"Applying Simple Dissolve...\",\"Simple Dissolve\",'');\r\n\tgProgressBar.open()\r\n\tdispatchEvent(\"com.adobe.event.createDissolveFile\",\"\")\r\n}", "function progressUpdate() {\n // the percentage loaded based on the tween's progress\n loadingProgress = Math.round(progressTl.progress() * 100);\n // we put the percentage in the screen\n $('.txt-perc').text(`${loadingProgress}%`);\n}", "_completeWith(t) {\n this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(), this._taskCompletionResolver.resolve(t);\n }", "init(e) {\n const t = this;\n import(\"nprogress\").then((r) => {\n let n = 0;\n document.addEventListener(\"splade:internal:request\", (s) => {\n n++, n === 1 && t.start(s, e.delay, r.default);\n });\n const i = (s) => {\n n--, n === 0 ? t.stop(s, r.default) : n < 0 && (n = 0);\n };\n document.addEventListener(\"splade:internal:request-progress\", (s) => t.progress(s, r.default)), document.addEventListener(\"splade:internal:request-response\", (s) => i(s)), document.addEventListener(\"splade:internal:request-error\", (s) => i(s)), r.default.configure({ showSpinner: e.spinner }), e.css && this.injectCSS(e.color);\n });\n }", "function onSeek(event) {\n var seekTime = parseInt(event.data.currentTime);\n if (seekTime >= duration - 1) {\n seekTime = (duration > 1) ? duration - 1 : 0;\n }\n event.data.currentTime = seekTime;\n printDebugMessage(\"onSeek\", event);\n player.mb.publish(OO.EVENTS.SEEK, seekTime);\n window.mediaManager.onSeekOrig(event);\n window.mediaManager.sendStatus(event.senderId, event.data.requestId, true);\n}", "static async updateProgressBar (process = \"\", subProcess = \"\", total = 1, step = 1) {\n\n let widthPreparation = 0.10\n let widthParsing = 0.60\n let widthEntities = 0.20\n let widthFlags = 0.05\n let widthPreview = 0.05\n\n let progressBar = $( \"#sbcProgressBar\" )\n let progressBarValue = $( \"#sbcProgressValue\" )\n let increment = 100 / total\n\n let newWidth = 0\n let progressBarText = \"\"\n\n switch (process.toLowerCase()) {\n case \"preparation\":\n progressBar.removeClass(\"ready\")\n newWidth = Math.floor( widthPreparation * increment * step )\n progressBarText = process + \": \" + subProcess\n break\n case \"parsing\":\n newWidth = Math.floor( 100 * ( widthPreparation ) + widthParsing * increment * step )\n progressBarText = process + \": \" + subProcess\n break\n case \"entities\":\n newWidth = Math.floor( 100 * ( widthParsing + widthPreparation ) + widthEntities * increment * step )\n progressBarText = subProcess\n break\n case \"flags\":\n newWidth = Math.floor( 100 * ( widthEntities + widthParsing + widthPreparation ) + widthFlags * increment * step )\n progressBarText = subProcess\n break\n case \"preview\":\n newWidth = Math.floor( 100 * ( widthFlags + widthEntities + widthParsing + widthPreparation ) + widthPreview * increment * step )\n progressBarText = subProcess\n break\n case \"actor\":\n newWidth = 100\n progressBarText = subProcess\n progressBar.addClass(\"ready\")\n default:\n break\n }\n\n progressBar.css(\"width\", newWidth + \"%\")\n progressBarValue.empty().append(progressBarText)\n }", "function completedProcess(self) {\n\t//console.log('completedProcess called');\n\tself.emit('completedProcess', self.file, self.fileObjectList.getAll());\n\tconsole.log(\"FeedFileProcessor : Finished processing \", self.file);\n\t//console.log(\"Contents are \", self.fileObjectList.getAll());\n\n}", "function adjustProgress() {\n\tvar current = shell.currPageNum;\n\tvar total = totalPageNum;\n\t//alert(\"current: \" + current + \" total: \" + total);\n\tif (shell.progress.type == 'text' || shell.progress.type == 'both') {\n\t\tada$(shell.progress.textDiv).innerHTML = current + \" of \" + total;\n\t} \n\tif (shell.progress.type == 'bar' || shell.progress.type == 'both') {\n\t\tvar minWidth = shell.progress.barMinWidth;\n\t\tvar ratio = current/total;\n\t\tvar pbWidth = shell.progress.barWidth*ratio;\n\t\tif (pbWidth < minWidth+4) pbWidth+= minWidth;\n\t\tvar myEl = ada$(shell.progress.barDiv);\n\t\tvar myEl2 = ada$(shell.progress.barInner);\n\t\tmyEl.style.width = pbWidth+'px';\n\t\tmyEl2.style.width = pbWidth+'px';\n\t\t// If it's only the progress bar, hide the text div\n\t\tif (shell.progress.type == 'bar') {\n\t\t\t$('#'+shell.progress.textDiv).addClass('off');\n\t\t}\n\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
spreadStr(spread: object) Returns a clean string with the spread's stats Format: HP / ATK / DEF / SPA / SPD / SPE
function spreadStr(spread) { return spread[0] + '/' + spread[1] + '/' + spread[2] + '/' + spread[3] + '/' + spread[4] + '/' + spread[5]; }
[ "function format(string, vars) {\n\tif (vars) {\n\t\tfor (var k in vars) {\n\t\t\tstring = string.replace(new RegExp('\\\\{' + k + '\\\\}', 'g'), vars[k]);\n\t\t}\n\t}\n\treturn string;\n}", "function stirvify(string) {\n // let newString = string.slice(0,7) === \"Strive\"? string: \"Strive \"+ string\n\n return string.startsWith(\"Strive\") ? string : \"Strive\" + string;\n}", "function format(str, formats) {\n\tlet cachedFormats = formats;\n\n\tif (!Ember.isArray(cachedFormats) || arguments.length > 2) {\n\t\tcachedFormats = new Array(arguments.length - 1);\n\n\t\tfor (let i = 1, l = arguments.length; i < l; i++) {\n\t\t\tcachedFormats[i - 1] = arguments[i];\n\t\t}\n\t}\n\n\tlet idx = 0;\n\treturn str.replace(/%@([0-9]+)?/g, function(s, argIndex) {\n\t\targIndex = (argIndex) ? parseInt(argIndex, 10) - 1 : idx++;\n\t\ts = cachedFormats[argIndex];\n\t\treturn (s === null) ? '(null)' : (s === undefined) ? '' : Ember.inspect(s);\n\t});\n}", "function makeStr(str) {\n\tif(str.length <= 35){\n\t\treturn str;\n\t} else {\n\t\tvar index = 35;\n\t\twhile(index >= 0) {\n\t\t\tif(str.charAt(index) === \" \") {\n\t\t\t\treturn str.substr(0, index+1) + \"...\";\n\t\t\t} else {\n\t\t\t\tindex--;\n\t\t\t}\n\t\t}\n\t\treturn str.substr(0, 36) + \" ...\";\n\t}\n}", "function parseActFormatMaxHit(str, data) {\n function formatMaxHitString(maxHitString) {\n return maxHitString.replace(/-/g, \" - \").replace(\",\", \"\").replace(\" \", \"\");\n }\n var result = \"\";\n\n var currentIndex = 0;\n\n var userMaxHitFlag;\n var userMaxHitValue = 0;\n var userMaxHitString = \"\";\n if (str.indexOf(\"{myMaxHitCustom}\") > 0) {\n userMaxHitFlag = 1;\n var userMaxHit = \"\";\n var combatant = data.Combatant[\"YOU\"];\n if (typeof combatant !== 'undefined') {\n userMaxHitString = combatant[\"maxhit\"];\n var hitValueString = userMaxHitString.slice(userMaxHitString.lastIndexOf(\"-\")+1);\n var hitValue = parseInt(hitValueString.replace(/,/g, \"\"));\n if (!isNaN(hitValue)) {\n userMaxHitValue = hitValue;\n }\n userMaxHitString = formatMaxHitString(userMaxHitString);\n }\n } else {\n userMaxHitFlag = 0;\n }\n\n var partyMaxHitFlag;\n var partyMaxHitValue = 0;\n var partyMaxHitString = \"\";\n if (str.indexOf(\"{maxHitCustom}\") > 0) {\n partyMaxHitFlag = 1;\n for (var combatantName in data.Combatant) {\n if (noLBInPartyMaxHit == 1 && combatantName == \"Limit Break\") {\n continue;\n }\n if (noMyMaxHitInPartyMaxHit == 1 && combatantName == \"YOU\") {\n continue;\n }\n var combatant = data.Combatant[combatantName];\n\n if (typeof combatant === 'undefined') {\n continue;\n }\n var maxHitForCombatant = combatant[\"maxhit\"];\n if (maxHitForCombatant !== 'undefined') {\n var hitValueString = maxHitForCombatant.slice(maxHitForCombatant.lastIndexOf(\"-\")+1);\n var hitValue = parseInt(hitValueString.replace(/,/g, \"\"));\n if (!isNaN(hitValue)) {\n if (hitValue > partyMaxHitValue) {\n partyMaxHitValue = hitValue;\n if (combatantName == \"YOU\") {\n partyMaxHitString = PLAYER_NAME+\"-\"+maxHitForCombatant;\n } else {\n partyMaxHitString = combatantName+\"-\"+maxHitForCombatant;\n }\n }\n partyMaxHitString = formatMaxHitString(partyMaxHitString);\n }\n }\n }\n } else {\n partyMaxHitFlag = 0;\n }\n\n if (colorHigherMaxHit == 1 && partyMaxHitFlag == 1 && userMaxHitFlag == 1) {\n if (userMaxHitValue >= partyMaxHitValue) {\n userMaxHitString = \"<font style='color:#ffcdd2;text-shadow:-1px 0 3px #fc5161, 0 1px 3px #fc5161, 1px 0 3px #fc5161, 0 -1px 3px #fc5161;font-weight:100;'>\" + userMaxHitString + \"</font>\";\n } else {\n partyMaxHitString = \"<font style='color:#ffcdd2;text-shadow:-1px 0 3px #fc5161, 0 1px 3px #fc5161, 1px 0 3px #fc5161, 0 -1px 3px #fc5161;font-weight:100;'>\" + partyMaxHitString + \"</font>\";\n }\n }\n\n do {\n var openBraceIndex = str.indexOf('{', currentIndex);\n if (openBraceIndex < 0) {\n result += str.slice(currentIndex);\n break;\n } else {\n result += str.slice(currentIndex, openBraceIndex);\n var closeBraceIndex = str.indexOf('}', openBraceIndex);\n if (closeBraceIndex < 0) {\n // parse error!\n console.log(\"parseActFormat: Parse error: missing close-brace for \" + openBraceIndex.toString() + \".\");\n return \"ERROR\";\n } else {\n var tag = str.slice(openBraceIndex + 1, closeBraceIndex);\n if (tag == \"maxHitCustom\") {\n result += partyMaxHitString;\n } else if (tag == \"myMaxHitCustom\") {\n result += userMaxHitString;\n } else if (typeof data.Encounter[tag] !== 'undefined') {\n result += data.Encounter[tag];\n } else {\n console.log(\"parseActFormat: Unknown tag: \" + tag);\n result += \"ERROR\";\n }\n currentIndex = closeBraceIndex + 1;\n }\n }\n } while (currentIndex < str.length);\n\n return result;\n}", "shifter(str) {\n\t\tlet newString = '';\n\t\tfor (const char of str) {\n\t\t\tnewString += /[a-z]/.test(char) ? String.fromCharCode(((char.charCodeAt(0) - 18) % 26) + 97) : char;\n\t\t}\n\t\treturn newString;\n\t}", "function splitDefenseData(stringDefenseData) {\n if(DEBUG==true) { console.log(\"sbc-pf1 | Parsing defense data\") };\n \n stringDefenseData = stringDefenseData.replace(/^ | $|^\\n*/,\"\");\n \n // Clean up the Input if there are extra linebreaks (often when copy and pasted from pdfs)\n // Remove linebreaks in parenthesis\n stringDefenseData = stringDefenseData.replace(/(\\([^(.]+?)(?:\\n)([^(.]+?\\))+?/mi, \"$1 $2\");\n \n let splitDefenseData = stringDefenseData.split(/\\n/);\n \n // Get all AC Boni included in Input (everything in parenthesis in splitDefenseData[0]) and split them into separate strings\n let splitACBonusTypes = {};\n if (splitDefenseData[0].search(/\\([\\s\\S]*?\\)/) !== -1) {\n splitACBonusTypes = JSON.stringify(splitDefenseData[0].match(/\\([\\s\\S]*?\\)/)).split(/,/);\n \n // Loop through the found AC Boni and set changes accordingly\n splitACBonusTypes.forEach( function ( item, index) {\n\n // get the bonus type\n let foundBonusType = item.match(/([a-zA-Z]+)/i)[0];\n let foundBonusValue = item.match(/(\\+[\\d]*)|(-[\\d]*)/i)[0].replace(/\\+/,\"\");\n\n formattedInput.ac_bonus_types[foundBonusType] = +foundBonusValue;\n\n });\n formattedInput.acNotes = JSON.parse(splitACBonusTypes)[0];\n }\n\n // Extract AC, Touch AC and Flat-Footed AC\n splitDefenseData[0] = splitDefenseData[0].replace(/\\([\\s\\S]*?\\)/,\"\");\n let splitArmorClasses = splitDefenseData[0].split(/[,;]/g);\n \n splitArmorClasses.forEach( function (item, index) {\n if (this[index].match(/(\\bAC\\b)/gmi)) {\n let splitAC = this[index].replace(/(\\bAC\\b)/gmi,\"\").replace(/^ *| *$|^\\n*/g,\"\");\n formattedInput.ac = splitAC;\n } else if (this[index].match(/(\\bTouch\\b)/gmi)) {\n let splitTouch = this[index].replace(/(\\btouch\\b)/gmi,\"\").replace(/^ *| *$|^\\n*/g,\"\");\n formattedInput.touch = splitTouch;\n } else if (this[index].match(/(\\bflat-footed\\b)/gmi)) {\n let splitFlatFooted = this[index].replace(/(\\bflat-footed\\b)/gmi,\"\").replace(/^ *| *$|^\\n*/g,\"\");\n formattedInput.flat_footed = splitFlatFooted;\n }\n }, splitArmorClasses);\n \n // Extract Number and Size of Hit Dies as well as HP\n // Hit dice\n \n let splitHPTotal = splitDefenseData[1].split(/(?:hp\\s*)([\\d]*)/)[1];\n formattedInput.hp.total = splitHPTotal;\n \n \n let stringHitDice = JSON.parse(JSON.stringify(splitDefenseData[1].match(/\\([\\s\\S]*?\\)/)));\n\n // If available, extract Regeneration\n if (splitDefenseData[1].search(/Regeneration/i) !== -1) {\n let tempRegen = splitDefenseData[1].match(/(?:Regeneration )([\\s\\S]+?)(?:\\n|$|;)/i);\n formattedInput.regeneration = tempRegen[1];\n }\n // If available, extract Fast Healing\n if (splitDefenseData[1].search(/Fast Healing/i) !== -1) {\n let tempFastHealing = splitDefenseData[1].match(/(?:Fast Healing )([\\s\\S]+?)(?:\\n|$|;)/i);\n formattedInput.fast_healing = tempFastHealing[1];\n }\n \n // Calculate HP and HD for Class and Race Items\n\n // Get different DicePools, e.g. XdY combinations, mostly for combinations of racial and class hitDice\n let hitDicePool = JSON.stringify(stringHitDice).match(/(\\d+?d\\d+)/gi);\n \n // Get the total HD\n let totalHD = 0;\n let totalClassHD = 0;\n // Loop over the available XdY Combinations\n hitDicePool.forEach ( function (hitDiceItem, hitDiceIndex) {\n // Increment the totalHD Counter\n totalHD += +hitDiceItem.match(/(\\d+)(?:d\\d+)/i)[1];\n });\n \n // Get the total HD of classHD\n let classKeys = Object.keys(formattedInput.classes);\n classKeys.forEach( function (classKey, classKeyIndex) {\n let numberOfClassLevels = formattedInput.classes[classKey].level;\n totalClassHD += +numberOfClassLevels;\n });\n \n // If there are no classes, all HD are racialHD\n if (totalClassHD === 0) {\n // ONLY RACIALHD \n let hitDicePoolKey = Object.keys(hitDicePool);\n for (let i = 0; i < hitDicePoolKey.length; i++) {\n \n // Set HP for RacialHDItem \n let tempDiceSize = hitDicePool[i].match(/(?:d)(\\d+)/)[1];\n \n // Set HP, HD.Racial and HD.Total\n formattedInput.hp.racial = Math.floor(+totalHD * +getDiceAverage(tempDiceSize));\n formattedInput.hit_dice.hd.racial = +totalHD;\n formattedInput.hit_dice.hd.total = +totalHD;\n }\n \n } else if (totalHD - totalClassHD === 0) {\n // ONLY CLASSHD \n // Loop over the dicePool\n let hitDicePoolKey = Object.keys(hitDicePool);\n for (let i = 0; i < hitDicePoolKey.length; i++) {\n \n let tempNumberOfHD = hitDicePool[i].match(/(\\d+)(?:d\\d+)/)[1];\n let tempHDSize = hitDicePool[i].match(/(?:\\d+d)(\\d+)/)[1];\n \n // Loop over the classes\n let classKeys = Object.keys(formattedInput.classes);\n for (let j = 0; j < classKeys.length; j++) {\n \n let classLevel = formattedInput.classes[classKeys[j]].level;\n \n \n \n // THIS IS NOT WORKING WHEN BOTH DICE POOLS HAVE THE SAME NUMBER OF DICE, e.g. 1d6 + 1d8\n \n \n \n \n if (tempNumberOfHD == classLevel) { \n // Set HP, HD.Racial and HD.Total\n formattedInput.hp.class[j] = Math.floor(+classLevel * +getDiceAverage(tempHDSize));\n formattedInput.hit_dice.hd.class[j] = +tempNumberOfHD;\n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n }\n \n \n }\n \n }\n \n } else if (totalHD - totalClassHD !== 0) {\n // CLASSHD AND RACIALHD\n // Loop for as long as not all ClassHD are matched\n let numberOfClasses = Object.keys(formattedInput.classes).length;\n let numberOfMatchedHD = Object.keys(hitDicePool).length;\n \n \n let counterOfMatchedHD = 0;\n let counterOfMatchedClasses = 0;\n \n while (counterOfMatchedHD < numberOfMatchedHD) {\n\n // Loop over the classKeys\n classKeys.forEach( function (classKey, classKeyIndex) {\n \n // Loop over the hitDicePool searching for matches\n hitDicePool.forEach ( function (hitDiceItem, hitDiceIndex) {\n \n let tempNumberOfHD = +hitDiceItem.match(/(\\d+)(?:d\\d+)/i)[1];\n let tempHDSize = +hitDiceItem.match(/(?:d)(\\d+)/i)[1];\n let tempClassLevel = formattedInput.classes[classKey].level;\n \n if ( (tempNumberOfHD == tempClassLevel) && (+counterOfMatchedHD !== +numberOfMatchedHD) && (counterOfMatchedClasses !== numberOfClasses) ) {\n // IF ITS THE A DIRECT MATCH BETWEEN CLASS LEVEL AND NUMBER OF HITDICE\n \n formattedInput.hp.class[classKey] = Math.floor(+tempClassLevel * +getDiceAverage(tempHDSize));\n formattedInput.hit_dice.hd.class[classKey] = +tempNumberOfHD;\n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n counterOfMatchedHD++;\n counterOfMatchedClasses++;\n \n } else if ( (tempNumberOfHD !== tempClassLevel) && (+counterOfMatchedHD == +(numberOfMatchedHD-1)) && (counterOfMatchedClasses !== numberOfClasses) ) {\n // IF ITS THE LAST HD POSSIBLE AND THERE IS STILL A CLASS LEFT TO MATCH\n \n formattedInput.hp.class[classKey] = Math.floor(+tempClassLevel * +getDiceAverage(tempHDSize));\n formattedInput.hp.racial = Math.floor( (+tempNumberOfHD - +tempClassLevel) * +getDiceAverage(tempHDSize));\n formattedInput.hit_dice.hd.class[classKey] = +tempNumberOfHD;\n formattedInput.hit_dice.hd.racial = +tempNumberOfHD - +tempClassLevel;\n \n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n counterOfMatchedHD++;\n counterOfMatchedClasses++;\n \n } else if ( (counterOfMatchedHD == (numberOfMatchedHD-1)) && (counterOfMatchedClasses == numberOfClasses) ) {\n // IF ITS THE LAST HD POSSIBLE AND THERE IS NO CLASS LEFT \n formattedInput.hp.racial = Math.floor( +tempNumberOfHD * +getDiceAverage(tempHDSize) );\n formattedInput.hit_dice.hd.racial = +tempNumberOfHD;\n formattedInput.hit_dice.hd.total += +tempNumberOfHD;\n \n counterOfMatchedHD++;\n }\n \n \n }); // End of Loop over the classKeys\n \n \n }); // End of Loop over the hitDicePool\n \n \n }\n \n\n }\n \n \n //let hitDiceBonusPool = JSON.stringify(stringHitDice).match(/[^d+\\(](\\d+)/gi);\n let hitDiceBonusPool = stringHitDice[0].replace(/(\\d+d\\d+)/gi,\"\").match(/\\d+/g);\n \n let hitDiceBonus = 0;\n \n // Get the sum of all the additional bonus hp, denoted for example by \"+XX\" and / or \"plus XX\"\n if (hitDiceBonusPool !== null) {\n \n for (let i = 0; i < hitDiceBonusPool.length; i++) {\n hitDiceBonus += +hitDiceBonusPool[i];\n }\n \n }\n \n // Extract Saves \n let splitSaves;\n \n for (var i = 0; i < splitDefenseData.length; i++) {\n if (splitDefenseData[i].search(/Fort/i) !== -1) {\n splitSaves = splitDefenseData[i].split(/,|;/);\n }\n }\n \n //let splitSaves = splitDefenseData[2].split(/,/); \n splitSaves.forEach( function (item, index) {\n \n item = item.replace(/,/g, \"\");\n \n if (this[index].search(/(fort)/i) !== -1) {\n let splitFort = item.match(/(\\+\\d+|\\-\\d+|\\d+)/ig)[0];\n formattedInput.fort_save.total = splitFort.replace(/\\+/,\"\");\n } else if (this[index].search(/(ref)/i) !== -1) {\n let splitRef = item.match(/(\\+\\d+|\\-\\d+|\\d+)/ig)[0];\n formattedInput.ref_save.total = splitRef.replace(/\\+/,\"\");\n } else if (this[index].search(/(will)/i) !== -1) {\n let splitWill = item.match(/(\\+\\d+|\\-\\d+|\\d+)/ig)[0];\n formattedInput.will_save.total = splitWill.replace(/\\+/,\"\");\n } else {\n formattedInput.save_notes = item;\n }\n }, splitSaves);\n \n // Check if there is a forth line\n /// then extract Damage Reduction, Resistances, Immunities, Weaknesses and Spell Resistance \n \n // REWORKED\n let searchableDefenseData = JSON.stringify(stringDefenseData).replace(/\\\\n/g, \";\").replace(/Offense;|Offenses/i, \"\");\n \n // Damage Reduction\n if (searchableDefenseData.search(/\\bDR\\b/) !== -1) {\n let splitDRValue = searchableDefenseData.match(/(?:\\bDR\\b )(\\d+)/)[0].replace(/\\bDR\\b /, \"\");\n let splitDRType = searchableDefenseData.match(/(?:\\bDR\\b \\d+\\/)([\\w\\s]*)/)[1];\n formattedInput.damage_reduction.dr_value = splitDRValue;\n formattedInput.damage_reduction.dr_type = splitDRType;\n }\n \n // Immunities\n if (searchableDefenseData.search(/\\bImmune\\b|\\bImmunities\\b/i) !== -1) {\n let splitImmunities = searchableDefenseData.match(/(?:\\bImmune\\b |\\bImmunities\\b )(.*?)(?:;)/i)[0].replace(/\\bimmune\\b |\\bimmunities\\b /i, \"\");\n formattedInput.immunities = splitImmunities;\n }\n \n // Resistances\n if (searchableDefenseData.search(/\\bResist\\b|\\bResistances\\b/i) !== -1) {\n let splitResistances = searchableDefenseData.match(/(?:\\bResist\\b |\\bResistance\\b )(.*?)(?:;)/i)[0].replace(/\\bResist\\b |\\bResistances\\b /i, \"\");\n formattedInput.resistances = splitResistances;\n }\n \n // Weaknesses\n if (searchableDefenseData.search(/\\bWeakness\\b|\\bWeaknesses\\b/i) !== -1) {\n let splitWeaknesses = searchableDefenseData.match(/(?:\\bWeakness\\b |\\bWeaknesses\\b )(.*?)(?:;)/i)[0].replace(/\\bWeakness\\b |\\bWeaknesses\\b /i, \"\");\n // Remove the phrase \"Vulnerable to\" if thats there\n splitWeaknesses = splitWeaknesses.replace(/vulnerability to |vulnerable to | and /gi, \"\")\n formattedInput.weaknesses = splitWeaknesses;\n }\n \n // Spell Resistance\n if (searchableDefenseData.search(/\\bSR\\b/i) !== -1) {\n let splitSR = searchableDefenseData.match(/(?:\\bSR\\b )(.*?)(?:;)/i)[0].replace(/\\bSR\\b /i, \"\");\n splitSR = splitSR.replace(/;|,| |\\n/g, \"\");\n formattedInput.spell_resistance.total = splitSR.match(/(^\\d+)/)[0];\n if (splitSR.search(/\\(([^)]+)\\)/) !== -1) {\n formattedInput.spell_resistance.context = splitSR.match(/\\(([^)]+)\\)/)[0];\n }\n }\n \n // Defensive Abilities\n // Spell Resistance\n if (searchableDefenseData.search(/\\bDefensive Abilities\\b/i) !== -1) {\n let splitDefensiveAbilities = searchableDefenseData.match(/(?:\\bDefensive Abilities\\b )(.*?)(?:;)/i)[0].replace(/\\bDefensive Abilities\\b /i, \"\");\n splitDefensiveAbilities = splitDefensiveAbilities.replace(/;|,|\\n/g, \",\").replace(/,\\s+$|,$/g, \"\");\n splitDefensiveAbilities = splitDefensiveAbilities.split(/,/g);\n formattedInput.defensive_abilities = splitDefensiveAbilities;\n }\n\n if(DEBUG==true) { console.log(\"sbc-pf1 | DONE parsing defense data\") };\n}", "function genhov(d, t, c) { // if just d's given let it be ambiguous \n c = c.replace(/\\\"/g, '&quot;')\n var s\n if (!d && !t) { s = '' }\n else if (!d && t) { s = 'Tweeted '+t }\n else if (d && !t) { s = ''+d }\n else if (d === t) { s = 'Deployed & tweeted '+d }\n else { s = 'Deployed '+d+', tweeted '+t }\n if (c && s) { s += '\\n'+c }\n else if (c) { s = c }\n return s\n}", "function profileInfo(object) {\nreturn `${object.name.charAt(0).toUpperCase()}${object.name.slice(1)} is a ${object.species.charAt(0).toUpperCase()}${object.species.slice(1)}`;\n}", "function format(s) {\n var positional = undefined;\n if (arguments.length > 2) {\n positional = true;\n }\n var args = Array.apply(null, arguments).slice(1);\n var position = 0;\n\n var re = /%(\\(([\\w\\$]+)\\))?([^])?/g;\n function replacer(all, p, varname, formatchar) {\n var val;\n switch (formatchar) {\n case \"%\":\n return \"%\";\n case \"s\":\n if (varname == \"\") {\n positional = check(positional, true);\n if (args.length <= position) {\n throw Error(\"Not enough format arguments\");\n }\n val = args[position];\n position++;\n return String(val);\n }\n if (isInteger(varname)) {\n varname = Number(varname);\n positional = check(positional, true);\n if (args.length <= varname) {\n throw Error(\"Not enough arguments\");\n }\n return String(args[varname]);\n } \n positional = check(positional, false);\n if (args.length != 1) {\n throw Error(\"Named arguments require a single object.\");\n }\n return String(args[0][varname]);\n default:\n throw Error(\"Unexpected format char: \" + formatchar);\n }\n }\n return s.replace(re, replacer);\n}", "function starWarsString(num) {\n\treturn new Promise(async function(resolve, reject) {\n\t\tvar characterData = await $.getJSON(`https://swapi.co/api/people/${num}`); // return data of character\n\t\tvar filmData = await $.getJSON(characterData.films[0]); // return data of first film they starred in\n\t\tvar planetData = await $.getJSON(filmData.planets[0]);\n\t\tresolve(`${characterData.name} is featured in the ${filmData.title}, directed by ${filmData.director} and it takes place on ${planetData.name}`);\n\t});\n}", "function formatString(nameIngredient) {\n let formatedName = \"\";\n let splitString = nameIngredient.split(\" \");\n\n for (let i = 0; i < splitString.length; i++) {\n for (let j = 0; j < splitString[i].length; j++) {\n {\n if (j == 0) {\n formatedName += splitString[i][j].toUpperCase();\n }\n else {\n formatedName += splitString[i][j].toLowerCase();\n }\n }\n }\n if (i != splitString.length - 1) {\n {\n formatedName += \" \";\n }\n }\n }\n //console.log(formatedName);\n\n return formatedName;\n}", "function calcTech(fleet, bonus, ccs, tac, def)\r\n{\r\n var TechLevel = {};\r\n//GM_log(ccs) \r\n for (var tech in techName) {\r\n TechLevel[tech] = 0;\r\n }\r\n for (var i = 0; i < fleet.length; i++) {\r\n var d = fleet[i];\r\n if (d.shielding > 0) {\r\n var sh = (d.shielding / d.stats.shielding - 1) / 0.05;\r\n TechLevel[\"SH\"] = Math.round(sh);\r\n }\r\n if (d.unit) {\r\n var a = (d.armor / (1+bonus) / d.stats.armor - 1) / 0.05;\r\n TechLevel[\"A\"] = Math.round(a);\r\n var w = (d.power / (1+bonus) / d.stats.power /\r\n\t (1 + ccs*0.05 + tac*0.01) - 1) / 0.05;\r\n TechLevel[d.stats.weapon] = Math.round(w);\r\n }\r\n else {\r\n var a = (d.armor / d.stats.armor / (1+def*0.01) - 1) / 0.05;\r\n TechLevel[\"A\"] = Math.round(a);\r\n var w = (d.power / d.stats.power / (1+def*0.01) - 1) / 0.05;\r\n TechLevel[d.stats.weapon] = Math.round(w);\r\n }\r\n }\r\n \r\n var playerTech = [];\r\n for (var t in TechLevel) {\r\n playerTech.push(t + TechLevel[t]);\r\n }\r\n return playerTech.join(\" \");\r\n\r\n}", "function CreateTakenSeatMessage( strRowSeat )\n{\n var strTakenSeatsMessage = '';\n var intIndexOfDash = 0;\n\n intIndexOfDash = strRowSeat.indexOf('-', 0);\n\n strTakenSeatsMessage += '\\nRow #'\n + strRowSeat.substring(0, intIndexOfDash)\n + ' Seat #'\n + strRowSeat.substring(intIndexOfDash + 1, 22);\n\n return strTakenSeatsMessage;\n}", "function returnAttackOutcomes(attack, selfStr, oppStr) {\n\t\ttry {\n\t\t\tif (!FS_Object.prop(attack)) {\n\t\t\t\tconsole.error(\"🔢 BattleMath.returnAttackOutcomes() attack is required!\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// get stats\n\t\t\tlet self = Stats.get(selfStr),\n\t\t\t\topp = Stats.get(oppStr),\n\t\t\t\tselfLevel = 1,\n\t\t\t\toppLevel = 1,\n\t\t\t\tnoEffect = true,\n\t\t\t\tstat = \"\",\n\t\t\t\taffectsStat = \"\",\n\t\t\t\tattackOutcomes = [], // track the outcome(s) of the attack to log them\n\t\t\t\toutcome = {}; // default outcome\n\n\t\t\tif (selfStr == \"monster\") {\n\t\t\t\tselfLevel = Monster.current().level;\n\t\t\t\toppLevel = T.tally_user.level;\n\t\t\t} else if (selfStr == \"tally\") {\n\t\t\t\tselfLevel = T.tally_user.level;\n\t\t\t\toppLevel = Monster.current().level;\n\t\t\t}\n\n\n\t\t\t// ************** STAMINA FIRST **************\n\n\t\t\t// COMPUTE STAMINA COST FIRST\n\t\t\tif (FS_Object.prop(attack.staminaCost)) {\n\t\t\t\tstat = \"stamina\";\n\t\t\t\taffectsStat = \"staminaCost\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round(self[stat].max * attack[affectsStat], 1));\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\t//attackOutcomes.push(outcome); // don't log stamina\n\t\t\t\t// if (!DEBUG) console.log(\"self[stat].val=\" + self[stat].val, \"attack[affectsStat]=\" + attack[affectsStat],\n\t\t\t\t// \t\"self[stat].max * attack[affectsStat]=\", (self[stat].max * attack[affectsStat]));\n\t\t\t\t// logOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\n\t\t\t// if not a defense, check to see if there is a miss\n\t\t\tif (attack.type !== \"defense\" && !didHit(attack, self, opp)) {\n\t\t\t\t// allow two tally misses total\n\t\t\t\tif (selfStr == \"tally\" && ++tallyMisses < 2)\n\t\t\t\t\treturn \"missed\";\n\t\t\t\telse\n\t\t\t\t\treturn \"missed\";\n\t\t\t}\n\t\t\t// was it a special attack?\n\t\t\telse if (FS_Object.prop(attack.special)) {\n\t\t\t\tif (DEBUG) console.log(\"🔢 BattleMath.returnAttackOutcomes() SPECIAL ATTACK !\", attack.special);\n\t\t\t\toutcome = outcomeData[attack.special]; // get data\n\t\t\t\t// make sure its defined\n\t\t\t\tif (outcome) {\n\t\t\t\t\tattackOutcomes.push(outcome); // store outcome\n\t\t\t\t\tlogOutcome(attack.special, outcome); // log\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (DEBUG) console.log(\"🔢 BattleMath.returnAttackOutcomes()\", selfStr + \" 🧨 \" + oppStr, attack,\n\t\t\t\t\"\\n --> self=\", self,\n\t\t\t\t\"\\n --> self=\", JSON.stringify(self),\n\t\t\t\t\"\\n --> opp=\", opp,\n\t\t\t\t\"\\n --> opp=\", JSON.stringify(opp)\n\t\t\t);\n\n\n\n\t\t\t// ************** HEALTH **************\n\n\t\t\t// SELF +HEALTH\n\t\t\tif (FS_Object.prop(attack.selfHealth)) {\n\t\t\t\tstat = \"health\";\n\t\t\t\taffectsStat = \"selfHealth\";\n\t\t\t\toutcome = outcomeData[affectsStat]; // get data\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1); // get change\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change); // set new val\n\t\t\t\tattackOutcomes.push(outcome); // store outcome\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self); // log\n\t\t\t}\n\t\t\t// OPP -HEALTH\n\t\t\tif (FS_Object.prop(attack.oppHealth)) {\n\t\t\t\tstat = \"health\";\n\t\t\t\taffectsStat = \"oppHealth\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\n\t\t\t\t// original\n\t\t\t\t// change = (max opp stat * the normalized attack stat)\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\t// e.g. tally (lvl24) v. monster (lvl3),\n\t\t\t\t// change = -(opp[stat].max (26) * attack[affectsStat] (0.15)) = -3.9\n\t\t\t\t// change = -(opp[stat].max (26) * attack[affectsStat] (0.15) * (24 - 23 * .1) = .1) = -4 (not much change)\n\t\t\t\t// change = -(opp[stat].max (26) * attack[affectsStat] (0.15) * (24 - 3 * .1) = 2.1) = -8.19 (big change)\n\t\t\t\t// change = -(opp[stat].max (4) * attack[affectsStat] (0.15) * (3 - 24 * .1) = -1.26) = -8.19 (big change)\n\n// outcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]) * Math.max(((selfLevel - oppLevel) * 0.1), 0.1), 3));\n\n\n\t\t\t\t// Daniel\n\t\t\t\t// I just changed this to be based on ATK and DEF values rather than as a proportion of level\n\t\t\t\t// outcome.change = -(FS_Number.round((1 + attack[affectsStat]) * Math.max((self.attack.val - opp.defense.val), 2.0), 3));\n\n\n\t\t\t\tif (DEBUG) console.log(\n\t\t\t\t\t\"outcome.change [\" + outcome.change + \"] = -(FS_Number.round(\" +\n\t\t\t\t\t\"opp[stat].max [\" + opp[stat].max + \"] *\", \"attack[affectsStat] [\" + attack[affectsStat] + \"] + \" +\n\t\t\t\t\t\"selfLevel [\" + selfLevel + \"] * attack[affectsStat] [\" + attack[affectsStat] + \"] , 3))\"\n\t\t\t\t);\n\t\t\t\tif (DEBUG) console.log(\"opp[stat].val [\" + opp[stat].val + \"] + outcome.change [\" + outcome.change + \"] = \" +\n\t\t\t\t\t(opp[stat].val + outcome.change));\n\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\n\t\t\t// ************** ATTACK **************\n\n\t\t\t// INCREASE SELF ATTACK\n\t\t\tif (FS_Object.prop(attack.selfAtk)) {\n\t\t\t\tstat = \"attack\";\n\t\t\t\taffectsStat = \"selfAtk\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\t//if (outcome.change != 0)\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP ATTACK\n\t\t\tif (FS_Object.prop(attack.oppAtk)) {\n\t\t\t\tstat = \"attack\";\n\t\t\t\taffectsStat = \"oppAtk\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\t// ************** ACCURACY **************\n\n\t\t\t// INCREASE SELF ACCURACY\n\t\t\tif (FS_Object.prop(attack.selfAcc)) {\n\t\t\t\tstat = \"accuracy\";\n\t\t\t\taffectsStat = \"selfAcc\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP ACCURACY\n\t\t\tif (FS_Object.prop(attack.oppAcc)) {\n\t\t\t\tstat = \"accuracy\";\n\t\t\t\taffectsStat = \"oppAcc\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\t// ************** EVASION **************\n\n\t\t\t// INCREASE SELF EVASION\n\t\t\tif (FS_Object.prop(attack.selfEva)) {\n\t\t\t\tstat = \"evasion\";\n\t\t\t\taffectsStat = \"selfEva\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP EVASION\n\t\t\tif (FS_Object.prop(attack.oppEva)) {\n\t\t\t\tstat = \"evasion\";\n\t\t\t\taffectsStat = \"oppEva\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\t// ************** DEFENSE **************\n\n\t\t\t// INCREASE SELF DEFENSE\n\t\t\tif (FS_Object.prop(attack.selfDef)) {\n\t\t\t\tstat = \"defense\";\n\t\t\t\taffectsStat = \"selfDef\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP DEFENSE\n\t\t\tif (FS_Object.prop(attack.oppDef)) {\n\t\t\t\tstat = \"defense\";\n\t\t\t\taffectsStat = \"oppDef\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\tif (DEBUG) console.log(\"🔢 BattleMath.returnAttackOutcomes() final stats = \",\n\t\t\t\tselfStr + \" 🧨 \" + oppStr, attack\n\t\t\t\t// ,\"\\n --> self=\", JSON.stringify(self),\n\t\t\t\t// \"\\n --> opp=\", JSON.stringify(opp)\n\t\t\t);\n\n\t\t\t// check to make sure there was an effect\n\t\t\tfor (let i = 0; i < attackOutcomes.length; i++) {\n\t\t\t\t//console.log(\"outcome\", outcome);\n\t\t\t\t// if change is not zero then there was an effect\n\t\t\t\tif (outcome.change > 0 || outcome.change < 0) {\n\t\t\t\t\tnoEffect = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (noEffect === true)\n\t\t\t\treturn \"noEffect\";\n\t\t\telse\n\t\t\t\treturn attackOutcomes; // return data\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t}", "function SGTimeToString(theTime) {\n var theHours, theMinutes, theSeconds;\n if (theTime == null || theTime == \"\" || !(theTime instanceof Date))\n return \"\";\n theHours = theTime.getHours();\n if (theHours >= 22) { //we have an under par SG to par score between -0:01 and -59:59...\n theSeconds = theTime.getSeconds();\n if (theSeconds > 0) {\n theMinutes = (theHours == 23 ? 60 - theTime.getMinutes() - 1 : 120 - theTime.getMinutes() - 1);\n theSeconds = 60 - theSeconds;\n } else {\n theMinutes = (theHours == 23 ? 60 - theTime.getMinutes() : 120 - theTime.getMinutes());\n }\n return \"-\" + theMinutes + \":\" + zeroPad(theSeconds);\n } else { //assume above par\n theMinutes = theTime.getMinutes() + (theHours * 60);\n theSeconds = theTime.getSeconds();\n return theMinutes + \":\" + zeroPad(theSeconds);\n } \n }", "function clearFog(str) {\n\treturn str.match(/fog/gi) ? str.match(/[^fog]/gi).join(\"\") : \"It's a clear day!\";\n}", "function str(sslice) /* (sslice : sslice) -> string */ {\n return sslice.str;\n}", "function define(style, string) {\n var split = string.split(' ');\n for (var i = 0; i < split.length; i++) {\n words[split[i]] = style;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CONTROLS SECTION / Update the maze style from light to dark
function updateMazeStyle(isLight) { clearCanvas(); /* Clear the Canvas first */ if (isLight) { lineClr = 'rgba(0,0,0,0.5)'; } else { lineClr = 'rgba(255,255,255,0.5)'; } drawcells(); /* Redraw the cells */ }
[ "function resolveMaze(){\n tryMaze(positionFixe);\n traceRoad(chemin_parcouru,\"color2\");\n traceRoad(tabVisite);\n\n}", "function updateStyle() {\r\n\tif (settings.darkThemeSettings) {\r\n\t\t//dark theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#0F0F0F\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#a53737\");\r\n\t} else {\r\n\t\t//light theme colors\r\n\t\troot.style.setProperty(\"--background-color\", \"#FFFFFF\");\r\n\t\troot.style.setProperty(\"--foreground-color\", \"#000000\");\r\n\t\troot.style.setProperty(\"--red-color\", \"#f55555\");\r\n\t}\r\n}", "setAlphas() {\n this.r3a1_exitDoor.alpha = 1.0;\n this.character.alpha = 1.0;\n this.r3a1_char_north.alpha = 0.0;\n this.r3a1_char_south.alpha = 0.0;\n this.r3a1_char_west.alpha = 0.0;\n this.r3a1_char_east.alpha = 0.0;\n this.r3a1_map.alpha = 0.0;\n this.r3a1_notebook.alpha = 0.0;\n this.r3a1_activityLocked.alpha = 0.0;\n this.r3a1_E_KeyImg.alpha = 0.0;\n this.r3a1_help_menu.alpha = 0.0;\n this.r3a1_redX.alpha = 0.0;\n this.r3a1_greenCheck.alpha = 0.0;\n //this.r3a1_hole.alpha = 0.0;\n this.hideActivities();\n this.profile.alpha = 0.0;\n }", "function Maze($where, size) {\n\t\n\tvar $canvas = $where.find('canvas')\n\t$canvas.attr({width:size, height:size})\n\tthis.$log = $where.find('#moves').eq(0)\n\tthis.$description = $where.find('#description').eq(0)\n\tthis.canvas = $canvas[0]\n\tvar ctx = this.ctx = this.canvas.getContext('2d')\n\tthis.definePaths()\n\tthis.reset()\n\n\tthis.drawThread = setInterval(new function(maze) { return function() {\n\t\tif(undefined == maze.lockdraw)\n\t\tif(maze.drawaction) {\n\t\t\tmaze.drawaction()\n\t\t\tmaze.drawaction = null\n\t\t}\n\t}}(this), $.browser.msie ? 1000/2 : 1000/60)\n\tthis.drawUpdateThread = setInterval(new function(maze) { \n\t\tfunction zoom(maze, level, t) {\n\t\t\tvar target = maze.offset(level.box)\n\t\t\tvar old_scale = maze.scale\n\n\t\t\tctx.save()\n\t\t\t\tmaze.scale = old_scale * (t*t*4+1)\n\t\t\t\tctx.scale(t*t*4+1,t*t*4+1)\n\t\t\t\tctx.translate(-t*(target[0]),-t*(target[1]))\n\t\t\t\tmaze.draw(level.up)\n\t\t\t\tctx.translate(target[0],target[1])\n\t\t\t\tctx.scale(1/5,1/5)\n\t\t\t\tmaze.scale *= 1/5\n\t\t\t\tctx.globalAlpha = 1*t + 0.25*(1-t)\n\t\t\t\tmaze.drawMaze(maze.ctx, level)\n\t\t\tctx.restore()\n\t\t\tmaze.scale = old_scale\n\t\t}\n\t\treturn function() {\n\t\t\tvar camera = maze.camera\n\t\t\twhile(camera.target[1] == camera.target[0]) {\n\t\t\t\tcamera.target.shift()\n\t\t\t}\n\t\t\tif(camera.target.length > 1 && camera.interp >= 1) {\n\t\t\t\tif(!(maze.replay && camera.target.length == 2 && camera.target[1].up == camera.target[0])) {\n\t\t\t\t\tcamera.interp = 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(camera.interp < 1) {\n\t\t\t\tif(camera.interp < 0) camera.interp = 0\n\t\t\t\tif(camera.target[2] == camera.target[0] \n\t\t\t\t\t&& camera.target[2].depth < camera.target[1].depth) {\n\t\t\t\t\tcamera.target.shift()\n\t\t\t\t\tcamera.interp = 1-camera.interp\n\t\t\t\t}\n\t\t\t\tvar level = camera.target[1]\n\t\t\t\tvar t = camera.interp\n\t\t\t\tvar speed = 0.03\n\t\t\t\tif(camera.target[1] == camera.target[0].up) {\n\t\t\t\t\tt = 1-t\n\t\t\t\t\tlevel = camera.target[0]\n\t\t\t\t}\n\t\t\t\tif(camera.target[1].depth <= camera.target[0].depth)\n\t\t\t\t\tspeed = 0.08\n\t\t\t\tmaze.drawaction = new function(level,t) { return function() { \n\t\t\t\t\tzoom(maze, level, t) } } (level,t)\n\t\t\t\tcamera.interp += speed*(camera.target.length-1)\n\t\t\t\tif(camera.interp >= 1) {\n\t\t\t\t\tcamera.interp = 1\n\t\t\t\t\tcamera.target.shift()\n\t\t\t\t}\n\t\t\t\tmaze.redraw = true\n\t\t\t} else if(maze.redraw) {\n\t\t\t\tmaze.drawaction = function() { maze.draw(camera.target[0]) }\n\t\t\t\tmaze.redraw = 0\n\t\t\t}\n\t\t}\n\t}(this), 1000/30)\n}", "function updateView() {\n // For every square on the board.\n console.log(MSBoard.rows);\n\n for (var x = 0; x < MSBoard.columns; x++) {\n for (var y = 0; y < MSBoard.rows; y++) {\n squareId = \"#\" + x + \"-\" + y;\n // Removes the dynamic classes from the squares before adding appropiate ones back to it.\n $(squareId).removeClass(\"closed open flagged warning\");\n\n square = MSBoard.squares[x][y];\n\n // These questions determine how a square should appear.\n // If no other text is put into a square, a &nbsp; is inserted because otherwise it disturbs the grid.\n // If a square is open, it should be themed as so and also display the number of nearby mines.\n if (square.open && !square.mine) {\n $(squareId).addClass(\"open\");\n $(squareId).html(square.nearbyMines);\n } \n // Flags are displayed only if the square is still closed.\n else if (square.flag && !square.open) {\n $(squareId).addClass(\"closed\");\n $(squareId).html(\"<img src='redFlag.png' class='boardImg flag' />&nbsp;\")\n } \n // Mines are displayed either if they're open (Either from opening one and losing or during validating) or while the cheat control is pressed.\n else if (square.mine && (square.open || cheating)) {\n $(squareId).addClass(\"warning\");\n $(squareId).html(\"<img src='mine.png' class='boardImg mine' />&nbsp;\")\n } \n // The HTML is set to a blank space in case there is nothing else to put in the space. \n else if (!square.open && !square.flag) {\n $(squareId).addClass(\"closed\"); \n $(squareId).html(\"&nbsp;\")\n }\n\n }\n }\n\n if (startMenuOn) {\n $(\"#newGameSettings\").css(\"display\", \"block\");\n } else {\n $(\"#newGameSettings\").css(\"display\", \"none\"); \n }\n\n}", "function setPathStyles( stateMap, pathmap, type ) {\n\tfor ( var row = 0; row < MAP_SIZE; row++ ) {\n\t\tfor ( var col = 0; col < MAP_SIZE; col++ ) {\n\t\t\tif ( pathmap[row][col] == 0 ) continue;\n\t\t\tif ( type == \"free\" ) {\n\t\t\t\tif ( stateMap[row][col].type != \"path\" ) {\n\t\t\t\t\tstateMap[row][col].type = \"grass\";\n\t\t\t\t\tstateMap[row][col].style = 0;\n\t\t\t\t\tstateMap[row][col].solid = false;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Figure out style\n\t\t\tvar style = 0;\n\t\t\tif ( col < MAP_SIZE-1 && row < MAP_SIZE-1\n\t\t\t && pathmap[row][col+1] && pathmap[row+1][col] ) // ╔\n\t\t\t\tstyle = 1;\n\t\t\tif ( col > 0 && col < MAP_SIZE-1\n\t\t\t && pathmap[row][col-1] && pathmap[row][col+1] ) // ═\n\t\t\t\tstyle = 2;\n\t\t\tif ( col > 0 && row < MAP_SIZE-1\n\t\t\t && pathmap[row][col-1] && pathmap[row+1][col] ) // ╗\n\t\t\t\tstyle = 3;\n\t\t\tif ( row > 0 && row < MAP_SIZE-1\n\t\t\t && pathmap[row-1][col] && pathmap[row+1][col] ) // ║\n\t\t\t\tstyle = 4;\n\t\t\tif ( row > 0 && col < MAP_SIZE-1\n\t\t\t && pathmap[row-1][col] && pathmap[row][col+1] ) // ╚\n\t\t\t\tstyle = 6;\n\t\t\tif ( col > 0 && row > 0\n\t\t\t && pathmap[row][col-1] && pathmap[row-1][col] ) // ╝\n\t\t\t\tstyle = 8;\n\t\t\tif ( col < MAP_SIZE-1 && row > 0 && row < MAP_SIZE-1\n\t\t\t && pathmap[row-1][col] && pathmap[row+1][col] && pathmap[row][col+1] ) // ╠\n\t\t\t\tstyle = 9;\n\t\t\tif ( col > 0 && row > 0 && row < MAP_SIZE-1\n\t\t\t && pathmap[row-1][col] && pathmap[row+1][col] && pathmap[row][col-1] ) // ╣\n\t\t\t\tstyle = 10;\n\t\t\tif ( col > 0 && row > 0 && col < MAP_SIZE-1\n\t\t\t && pathmap[row][col-1] && pathmap[row-1][col] && pathmap[row][col+1] ) // ╩\n\t\t\t\tstyle = 11;\n\t\t\tif ( col > 0 && row < MAP_SIZE-1 && col < MAP_SIZE-1\n\t\t\t && pathmap[row][col-1] && pathmap[row+1][col] && pathmap[row][col+1] ) // ╦\n\t\t\t\tstyle = 12;\n\t\t\tif ( col > 0 && row > 0 && col < MAP_SIZE-1 && row < MAP_SIZE-1\n\t\t\t && pathmap[row][col-1] && pathmap[row-1][col] && pathmap[row][col+1] && pathmap[row+1][col] ) // ╬\n\t\t\t\tstyle = 0;\n\n\t\t\t// update map\n\t\t\tstateMap[row][col].style = style;\n\t\t\tstateMap[row][col].type = type;\n\t\t\tstateMap[row][col].solid = (type == \"river\" || type == \"wall\" );\n\t\t}\n\t}\n\n\treturn stateMap;\n}", "ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }", "function resetVisibleBoard() {\n\t$(\".tile\").text(\"\");\n\n\t$(\".horizontal-line\").each(function() {\n\t\tvar el = $(this);\n\t\tsetLineState(el, \"dormant\");\n\t});\n\n\t$(\".vertical-line\").each(function() {\n\t\tvar el = $(this);\n\t\tsetLineState(el, \"dormant\");\n\t});\n}", "function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}", "function setupNewColorsMeshs() {\n cubeMeshs.forEach(object => {\n object.children[0].children[0].material[1].color = colorScene;\n object.children[0].children[0].material[1].emissive = colorScene;\n });\n\n torusMesh.forEach(object => {\n switch (countTic > 2) {\n case true:\n object.children[0].material[1].emissive = new THREE.Color(0xffffff);\n object.children[0].material[1].color = new THREE.Color(0xffffff);\n object.children[0].material[4].emissive = colorScene;\n object.children[0].material[4].color = colorScene;\n break;\n case false:\n object.children[0].material[1].emissive = colorScene;\n object.children[0].material[1].color = colorScene;\n object.children[0].material[4].emissive = new THREE.Color(0xffffff);\n object.children[0].material[4].color = new THREE.Color(0xffffff);\n break;\n }\n });\n}", "function showMoodLevel() {\n\t\tvar positiveOrNegative = moodLevel > 0 ? 1 : -1;\n\t\tvar startingColor = 242;\n\t\tvar blueStep = 242 / 100;\n\t\tvar redStep = moodLevel > 0 ? 242 / 100 : 142 / 100;\n\t\tvar greenStep = moodLevel < 0 ? 242 / 100 : 142 / 100;\n\n\t\tvar newRed = startingColor - redStep * moodLevel * positiveOrNegative;\n\t\tvar newGreen = startingColor - greenStep * moodLevel * positiveOrNegative;\n\t\tvar newBlue = startingColor - blueStep * moodLevel * positiveOrNegative;\n\n\t\ttextField.style.background = \"rgb(\" + newRed + \", \" + newGreen + \", \" + newBlue + \")\";\n\t}", "setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}", "function resetDrawingHighlights() {\n abEamTcController.resetDrawingHighlights();\n}", "colorGrid() {\n for(let i = 0; i < this.columnSize * this.rowSize; i++) {\n if(this.gridArray[i].state == blank) {\n this.gridDOM.children[i].style.backgroundColor = \"#f2f2f2\";\n this.gridDOM.children[i].style.borderColor = \"#959595\";\n } else if(this.gridArray[i].state == unvisited) {\n this.gridDOM.children[i].style.backgroundColor = \"#88FFD1\";\n this.gridDOM.children[i].style.borderColor = \"#3FE1B0\";\n } else if(this.gridArray[i].state == visited) { \n this.gridDOM.children[i].style.backgroundColor = \"#FF848C\";\n this.gridDOM.children[i].style.borderColor = \"#FF505F\";\n } else if(this.gridArray[i].state == start) {\n this.gridDOM.children[i].style.backgroundColor = \"#00DDFF\";\n this.gridDOM.children[i].style.borderColor = \"#0290EE\";\n } else if(this.gridArray[i].state == goal) {\n this.gridDOM.children[i].style.backgroundColor = \"#C588FF\";\n this.gridDOM.children[i].style.borderColor = \"#9059FF\";\n } else if (this.gridArray[i].state == wall) {\n this.gridDOM.children[i].style.backgroundColor = \"black\";\n } else;\n }\n }", "function update() {\n\n //cast ray to go through objects\n raycaster.setFromCamera(mouse, camera);\n //array of targeted objects, ordered by distance - near to far\n var intersects = raycaster.intersectObjects( scene.children );\n //black out targeted partition of sunburst\n if (intersects.length > 0) {\n\n var targetedObject = intersects[0];\n\n //color out targeted node\n setColorHighlight(targetedObject.object.material.color);\n\n\n var targetedObjectNode = getSceneObjectNodeById(subtree.root, targetedObject.object);\n document.getElementById(\"latinWindow\").innerHTML = targetedObjectNode.latin;\n //get node of blacked out object\n var lastAccessedObjectNode = getSceneObjectNodeById(subtree.root, lastAccessedObject);\n\n //create new color by force - #000000 format to 0x000000 format\n var colors = lastAccessedObjectNode.color.split(\"#\");\n var color = (\"0x\" + colors[1]);\n \n //if I moved on another object\n if(targetedObject.object != lastAccessedObject) {\n //apply the original color\n if (lastAccessedObjectNode != null) {\n lastAccessedObjectNode.sceneObject.material.color.setHex(color);\n }\n }\n\n lastAccessedObject = targetedObject.object;\n }\n //if you run down from a node, remove highlighting and innerHTML\n else{\n var lastAccessedObjectNode = getSceneObjectNodeById(subtree.root, lastAccessedObject);\n var colors = lastAccessedObjectNode.color.split(\"#\");\n var color = (\"0x\" + colors[1]);\n if (lastAccessedObjectNode != null) {\n lastAccessedObjectNode.sceneObject.material.color.setHex(color);\n }\n //clear the display of latin name\n document.getElementById(\"latinWindow\").innerHTML = \"\";\n }\n}", "function changeTileCorrect () {\n console.log('Executing changeTileCorrect');\n let tileList = document.getElementsByTagName('span');\n tileList[currentCharIndex].style.backgroundColor = 'lightgreen';\n console.log('Changed tile color');\n}", "function drawMaze(){\n\t//xy offsets so that the map is centered in the canvas\n\toffsetx = (canvas.width/2)-(width*imgSize)/2;\n\toffsety = (canvas.height/2)-(height*imgSize)/2;\n\t\n\t//Drawing coloured background, and then setting draw colour back to black.\n\tcontext.fillStyle=\"#D1FFF0\";\n\tcontext.fillRect( 0 , 0 , canvas.width, canvas.height );/*Clearing canvas*/\t\n\tcontext.fillStyle=\"#000000\";\n\t\n\t\n\tfor(var i=0; i<height; i++){\n\t\tfor(var j=0; j<width; j++){\n\t\t\t\n\t\t\t//If they can see the whole map, or the position is located directly next to the player.\n\t\t\tif(!limitedSight||\n\t\t\t((j>=playerPositionx-1&&j<=playerPositionx+1\n\t\t\t&&i>=playerPositiony-1&&i<=playerPositiony+1)&&!isPaused)){\n\t\t\t\t\n\t\t\t\tif(map[j][i]=='.'){/*Wall*/\n\t\t\t\t\tcontext.drawImage(wall, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t} else if(map[j][i]=='P'&&solutionVisible){/*Path*/\n\t\t\t\t\tcontext.drawImage(path, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t}else {/*Ground*/\n\t\t\t\t\tcontext.drawImage(floor, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(j==playerPositionx&&i==playerPositiony)/*player*/\n\t\t\t\t\tcontext.drawImage(character, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t\t\n\t\t\t\tif(j==targetx&&i==targety)/*toilet (maze end)*/\n\t\t\t\t\tcontext.drawImage(toiletGraphic, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t\t\n\t\t\t\tif(showDistances)/*showing movement distance from the player to this tile*/\n\t\t\t\t\tcontext.fillText(distanceMap[j][i], offsetx+j*imgSize, offsety+(i+1)*imgSize);\n\t\t\t\t\t\n\t\t\t}else{\n\t\t\t\t//if it isnt a tile the player can see, draw a black square.\n\t\t\t\tcontext.drawImage(darkSquareGraphic, offsetx+j*imgSize, offsety+i*imgSize, imgSize, imgSize);\n\t\t\t}\n\t\t\t\n\t\t\tif(isPaused)context.drawImage(pausedTextGraphic, canvas.width/2-pausedTextGraphic.width/2, canvas.height/2-pausedTextGraphic.height/2);\n\t\t\t\n\t\t\t//Drawing lower background panel\n\t\t\tcontext.drawImage(lowerBackgroundGraphic, 0, canvas.height-40, canvas.width, 40);\n\t\t\t//Drawing hint button\n\t\t\tcontext.drawImage(hintButtonGraphic, hintButtonX, hintButtonY, 50, 20);\n\t\t\t//Drawing mute button\n\t\t\tif(isMuted){\n\t\t\t\tcontext.drawImage(mutedGraphic, muteButtonX, muteButtonY);\n\t\t\t}else{\n\t\t\t\tcontext.drawImage(speakerGraphic, muteButtonX, muteButtonY);\n\t\t\t}\n\t\t\t\n\t\t\t//Drawing upper buttons\n\t\t\tcontext.drawImage(trophyGraphic, muteButtonX-20, muteButtonY);\n\t\t\tcontext.drawImage(pauseGraphic, muteButtonX-40, muteButtonY);\n\t\t\t\n\t\t\t//Drawing guide graphics for first level\n\t\t\tif(gameLevel==1){\n\t\t\t\tcontext.drawImage(leftArrowGraphic, 10, (canvas.height/2)-(leftArrowGraphic.height/2));\n\t\t\t\tcontext.drawImage(rightArrowGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2));\t\t\t\n\t\t\t\tcontext.drawImage(upArrowGraphic, (canvas.width/2)-(upArrowGraphic.width/2), 10);\n\t\t\t\tcontext.drawImage(downArrowGraphic, (canvas.width/2)-(downArrowGraphic.width/2), canvas.height-40-downArrowGraphic.height);\n\t\t\t}\t\t\n\t\t\t//Text portion of guide graphics\n\t\t\tif(controlVisualVisible){\n\t\t\t\tcontext.font = \"17px Arial\";\n\t\t\t\tcontext.fillText(\"Memorize this path to the toilet\", offsetx-32, offsety-12);\n\t\t\t\tcontext.fillText(\"Then retrace it as fast as you can!\", offsetx-50, offsety+width*imgSize+16);\n\t\t\t\t\n\t\t\t\tif(fingerGraphicDown){/*Checking if the finger graphic is up or down*/\n\t\t\t\t\tcontext.drawImage(fingerGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2));\n\t\t\t\t}else{\n\t\t\t\t\tcontext.drawImage(fingerGraphic, canvas.width-10-rightArrowGraphic.width, (canvas.height/2)-(rightArrowGraphic.height/2)-20);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//Drawing graphic for achievement menu window\n\t\t\tif(isAchievementMenu){\n\t\t\t\tcontext.drawImage(achievementsWindowGraphic, canvas.width/2-achievementsWindowGraphic.width/2, canvas.height/2-achievementsWindowGraphic.height/2);\t\t\t\t\n\t\t\t\tif(firstPlayAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+44);\n\t\t\t\tif(firstLevelAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+74);\n\t\t\t\tif(firstHintAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+104);\n\t\t\t\tif(fifthLevelAchievement)context.drawImage(checkMarkGraphic, canvas.width/2-achievementsWindowGraphic.width/2+20, canvas.height/2-achievementsWindowGraphic.height/2+136);\n\t\t\t}\n\t\t\t\n\t\t\t//draw achievement window if its currently being displayed\n\t\t\tif(isShowingMessage)displayAchievement();\n\t\t}\n\t}\n\t//prints score and time at the bottom of the screen\n\ttestingOutput();\n}", "function showred() {\r\n var o_panel_info = document.getElementById(\"outputpanel\").classList\r\n if(o_panel_info.length > 1){\r\n o_panel_info.remove(\"greenbg\", \"darkbg\", \"lightbg\");\r\n }\r\n o_panel_info.add(\"redbg\");\r\n}", "function resetDraw() {\n\tfor (var i=0; i<=currentTournament.numberMatches*2;i++) { \n\t\t\t$(\"#p\" + i).css(\"color\", \"#000\");\n\t\t}\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to adjust time when time warping and taking courses in school
function adjtime(tim) { if (player.STEALTH) player.updateStealth(-tim); if (player.UNDEADPRO) player.updateUndeadPro(-tim); if (player.SPIRITPRO) player.updateSpiritPro(-tim); if (player.CHARMCOUNT) player.updateCharmCount(-tim); // stop time if (player.HOLDMONST) player.updateHoldMonst(-tim); if (player.GIANTSTR) player.updateGiantStr(-tim); if (player.FIRERESISTANCE) player.updateFireResistance(-tim); if (player.DEXCOUNT) player.updateDexCount(-tim); if (player.STRCOUNT) player.updateStrCount(-tim); if (player.SCAREMONST) player.updateScareMonst(-tim); if (player.HASTESELF) player.updateHasteSelf(-tim); if (player.CANCELLATION) player.updateCancellation(-tim); if (player.INVISIBILITY) player.updateInvisibility(-tim); if (player.ALTPRO) player.updateAltPro(-tim); if (player.PROTECTIONTIME) player.updateProtectionTime(-tim); if (player.WTW) player.updateWTW(-tim); player.HERO = player.HERO > 0 ? Math.max(1, player.HERO - tim) : 0; player.GLOBE = player.GLOBE > 0 ? Math.max(1, player.GLOBE - tim) : 0; player.AWARENESS = player.AWARENESS > 0 ? Math.max(1, player.AWARENESS - tim) : 0; player.SEEINVISIBLE = player.SEEINVISIBLE > 0 ? Math.max(1, player.SEEINVISIBLE - tim) : 0; player.AGGRAVATE = player.AGGRAVATE > 0 ? Math.max(1, player.AGGRAVATE - tim) : 0; player.HASTEMONST = player.HASTEMONST > 0 ? Math.max(1, player.HASTEMONST - tim) : 0; player.HALFDAM = player.HALFDAM > 0 ? Math.max(1, player.HALFDAM - tim) : 0; player.ITCHING = player.ITCHING > 0 ? Math.max(1, player.ITCHING - tim) : 0; player.CLUMSINESS = player.CLUMSINESS > 0 ? Math.max(1, player.CLUMSINESS - tim) : 0; // confusion? // blindness? regen(); }
[ "calcTime() {\n const numIng = this.ingredients.length;\n const periods = Math.ceil(numIng/3);\n this.time = periods * 15;\n }", "_addTime () {\r\n this._totalTime += (this._limit - this._timeLeft)\r\n }", "function updateScore() {\n\t\t\t// Score rule: pass level n in t seconds get ((100 * n) + (180 - t)) points \n\tlevelScore = (levelTime + 100) + Math.floor(levelTime * (currentLevel-1));\n\t// Set original \"levelScore\" to extraLevelScore for testing purpose\n\tfinalScore += levelScore + extraLevelScore;\t\t\n\t// Add finalTime\n\tfinalTime += startLevelTime - levelTime;\n}", "addTime() {\n var level = this.calcLevel();\n if (level == 1) {\n this.endTime += 2000;\n } else if (level == 2) {\n this.endtime += 1500;\n } else if (level == 3) {\n this.endtime += 1200;\n } else if (level == 4) {\n this.endtime += 900;\n } else if (level == 5) {\n this.endtime += 700;\n } else {\n this.endtime += 500;\n };\n }", "function _updateTimer(){\n _timeNow = Date.now();\n var $dt = (_timeNow-_timeThen);\n\n _delta = _delta + $dt; // accumulate delta time between trips, but not more than trip window\n _now = _now+_delta; // accumulate total time since start of timer\n _timeThen = _timeNow;\n\n // record the number of trip windows passed since last reset\n _passedTrips = Math.floor(_delta / _trip);\n\n // determine if timer tripped\n if(_delta > _trip){\n _isTripped = true;\n _timeNow = Date.now();\n // assign current value to the excess amount beyond tripping point,\n // reset the accumulation to whatever is less than the trip window\n _delta = _delta % _trip;\n _timeThen = Date.now();\n }\n }", "function updateTimeElapsed() {\n var time = formatTime(Math.round(video.currentTime));\n timeElapsed.innerText = formatTimeHumanize(time);\n timeElapsed.setAttribute('datetime', `${time.hours}h ${time.minutes}m ${time.seconds}s`);\n }", "calculate() {\n this.times.miliseconds += 1;\n if (this.times.miliseconds >= 100) {\n this.times.seconds += 1;\n this.times.miliseconds = 0;\n }\n if (this.times.seconds >= 60) {\n this.times.minutes += 1;\n this.times.seconds = 0;\n }\n }", "function passTime()\n{\n\t// To begin, we clear whatever the precious entityDesc was.\n\tclearEntText();\n\t// For every entity in the game:\n\tfor (var ent in entityArray)\n\t{\n\t\t// If that entity belongs to the array and not to the prototype:\n\t\tif (entityArray.hasOwnProperty(ent))\n\t\t{\n\t\t\t// Call that entity's AI function. It will take over from here.\n\t\t\tentityArray[ent].brain();\n\t\t}\n\t}\n\t// Finally, we print the new entityDesc (which may have changed due to entities' AI functions).\n\tdisplayEntText();\n}", "subtractTime() {\n this.endTime -= 2000;\n }", "function updateTime() {\n const datetime = tizen.time.getCurrentDateTime();\n const hour = datetime.getHours();\n const minute = datetime.getMinutes();\n const second = datetime.getSeconds();\n\n const separator = second % 2 === 0 ? \":\" : \" \";\n\n $(\"#time-text\").html(padStart(hour.toString()) + separator + padStart(minute.toString()));\n\n // Update the hour/minute/second hands\n rotateElements((hour + (minute / 60) + (second / 3600)) * 30, \"#hands-hr-needle\");\n rotateElements((minute + second / 60) * 6, \"#hands-min-needle\");\n clearInterval(interval);\n if (!isAmbientMode) {\n let anim = 0.1;\n rotateElements(second * 6, \"#hands-sec-needle\");\n interval = setInterval(() => {\n rotateElements((second + anim) * 6, \"#hands-sec-needle\");\n anim += 0.1;\n }, 100);\n }\n }", "async function timeTravelToTransition() {\n let startTimeOfNextPhaseTransition = await stakingHbbft.startTimeOfNextPhaseTransition.call();\n\n await validatorSetHbbft.setCurrentTimestamp(startTimeOfNextPhaseTransition);\n const currentTS = await validatorSetHbbft.getCurrentTimestamp.call();\n currentTS.should.be.bignumber.equal(startTimeOfNextPhaseTransition);\n await callReward(false);\n }", "calcRemainingTime() {\n return (Math.round((currentGame.endTime - Date.now()) / 100));\n }", "function calcRunPace(time, dist) {\n let totalSeconds = time.hours * 60 * 60;\n totalSeconds += (time.minutes * 60);\n totalSeconds += time.seconds;\n const secondsPerUnit = totalSeconds / dist;\n const mins = Math.floor(secondsPerUnit/60);\n let secs = (secondsPerUnit % 60).toFixed(2); \n if(secs < 10)\n secs = `0${secs}`;\n const pace = (mins + ':' + secs);\n return {pace, totalSeconds};\n}", "function scoreTimer() {\n secondsLeft = originalTimerValue; // set the secondsLeft var the independently set global var for the timer value\n spanTime.textContent = Math.floor(secondsLeft); // display the initial time state on-screen as 60\n var timerInterval = setInterval(function () {\n // create a setInterval loop to a var called timerInterval\n secondsLeft = secondsLeft - timePenalty - 1; // on each interval, decrease secondsLeft by 1 and subtract answer penalty;\n timePenalty = \"\"; // Reset timePenalty so only applied once per wrong answer\n spanTime.textContent = Math.floor(secondsLeft); // update time readout in the header to the current sec.s remaining\n // If the current screen/div being viewed is NOT a question (in other words, the user isn't in mid-quiz)\n if (\n !qz0Div.classList.contains(\"hidden\") ||\n !qz11Div.classList.contains(\"hidden\") ||\n !scoresDiv.classList.contains(\"hidden\")\n ) {\n clearInterval(timerInterval); // stop the timer\n // else, if questions are currently being answered/quiz is in progress, AND if the seconds run out...\n } else if (secondsLeft < 1) {\n secondsLeft = 0; // reset the secondsLeft variable\n clearInterval(timerInterval); // stop the timer\n // alert(\"Time's up!\"); // alert the user that time is up\n // startingPoint(); // reset the time and div visibilities to the starting point...\n qz0Div.classList.add(\"hidden\"); // ...then hide the quiz question divs...\n qz1Div.classList.add(\"hidden\");\n qz2Div.classList.add(\"hidden\");\n qz3Div.classList.add(\"hidden\");\n qz3Div.classList.add(\"hidden\");\n qz4Div.classList.add(\"hidden\");\n qz5Div.classList.add(\"hidden\");\n qz6Div.classList.add(\"hidden\");\n qz7Div.classList.add(\"hidden\");\n qz8Div.classList.add(\"hidden\");\n qz9Div.classList.add(\"hidden\");\n qz10Div.classList.add(\"hidden\");\n qz11Div.classList.remove(\"hidden\"); // ...then show the tally page...\n scoreTitle.textContent = \"You have run out of time.\"; // ...and then change scoring div title to note time ran out\n }\n finalTimeRemaining = secondsLeft; // sets the finalTimeRemaining global variable on the clock to however many seconds are left\n spanTime.textContent = finalTimeRemaining; // set the countdown timer readout to be the remaining time on the clock.\n }, 1000); // interval timer loops every 1000 milliseconds aka every second\n}", "function refreshMainTimeView() {\n setText(document.querySelector(\"#text-main-hour\"),\n addLeadingZero(Math.floor(setting.timeSet / 3600), 2));\n setText(document.querySelector(\"#text-main-minute\"),\n addLeadingZero(Math.floor(setting.timeSet / 60) % 60, 2));\n setText(document.querySelector(\"#text-main-second\"),\n addLeadingZero(setting.timeSet % 60, 2));\n applyStyleTransition(document.querySelector(\"#box-hand-hour\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 43200) / 43200);\n applyStyleTransition(document.querySelector(\"#box-hand-minute\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 3600) / 3600);\n applyStyleTransition(document.querySelector(\"#box-hand-second\"),\n ROTATE_DATA_HAND, \"START\", \"END\", (setting.timeSet % 60) / 60);\n }", "function time() {\n\tif(arguments[0] == \"all\") { \n for(i = 0; i < play_num; i++){\n pl[i].message(\"timestretch\", arguments[1]);\n }\n\t} else if (typeof arguments[0] == \"number\"){ \n\t\tpl[(arguments[0]-1)].message(\"timestretch\", arguments[1]);\n\t}\n}", "function updateScore(elapsedTime){\r\n\t\tif(!myShip.getSpecs().hit && !myShip.getSpecs().invincible){\r\n\t\t\tvar oldCounter = Math.floor(updateScoreCounter);\r\n\t\t\tupdateScoreCounter += elapsedTime/1000;\r\n\t\t\tvar newCounter = Math.floor(updateScoreCounter);\r\n\r\n\t\t\tif(newCounter == oldCounter + 1){\r\n\t\t\t\taddToScore(10);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function defineDayCapacities(){\n\tvar l = dateSpan.length;\n\t\n\tvar workSchedule = [];\n\tworkSchedule[0] = U.profiles[Profile].workSchedule.su;\n\tworkSchedule[1] = U.profiles[Profile].workSchedule.mo;\n\tworkSchedule[2] = U.profiles[Profile].workSchedule.tu;\n\tworkSchedule[3] = U.profiles[Profile].workSchedule.we;\n\tworkSchedule[4] = U.profiles[Profile].workSchedule.th;\n\tworkSchedule[5] = U.profiles[Profile].workSchedule.fr;\n\tworkSchedule[6] = U.profiles[Profile].workSchedule.sa;\n\t\n\tvar vacationDays = U.profiles[Profile].vacationDays;\n\tvar numberOfVacationDays = vacationDays.length;\n\n\tfor(i=0;i<l;i++){\n\t\tdateSpan[i].capacity = workSchedule[dateSpan[i].dayNumber];\n\t\t\n\t\tif(i == 0){\n\t\t\t//The first day being set is today; see how much time remains before today is over\n\t\t\tvar timeRemainingBeforeMidnight = (new Date(today.toDateString()).getTime() + 86400000) - (new Date().getTime());\n\t\t\t//Floor milliseconds to nearest full minute amount\n\t\t\ttimeRemainingBeforeMidnight = Math.ceil(timeRemainingBeforeMidnight/60000);\n\t\t\t//Translate minutes to hours\n\t\t\ttimeRemainingBeforeMidnight = timeRemainingBeforeMidnight/60;\n\t\t\t\n\t\t\tif(timeRemainingBeforeMidnight + totalTimeSpentToday < dateSpan[i].capacity){\n\t\t\t\t/*If the timeRemainingBeforeMidnight plus the totalTimeSpentToday is less than the day's capacity \n\t\t\t\t(as defined in the workSchedule), it means there is not enough time left in the day to fit in a \n\t\t\t\tfull work day, so the day's capacity is reduced accordingly.*/\n\t\t\t\tif(!dayCapacityAdjustmentMessageShown && U.hasHadTour == true){ //We don't want to show this when someone first signs up\n\t\t\t\t\tshowMessageBar(1,\"Today's Work Schedule has been altered according to the remaining hours in the day.\");\n\t\t\t\t\tdayCapacityAdjustmentMessageShown = true;\n\t\t\t\t}\n\t\t\t\t//console.log(\"Today's workSchedule says we should have \" + dateSpan[i].capacity + \" hours to work, but there are only \" + timeRemainingBeforeMidnight + \" hours left in the day.\");\n\t\t\t\tdateSpan[i].capacity = timeRemainingBeforeMidnight + totalTimeSpentToday;\n\t\t\t\tconsole.log(\"Today's capacity has been adjusted to \" + Math.floor(dateSpan[i].capacity) + \":\" + dateSpan[i].capacity*60 %60);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t//Check if it is a vacationDay and if so, set its capacity to 0\n\t\tfor(a=0;a<numberOfVacationDays;a++){\n\t\t\tuntestedDate = dateSpan[i].date.toDateString();\n\t\t\tvacationDayToTest = new Date(vacationDays[a]).toDateString();\n\t\t\tif(untestedDate == vacationDayToTest){\n\t\t\t\tdateSpan[i].vacationDay = true;\n\t\t\t\tdateSpan[i].capacity = 0;\n\t\t\t\tbreak;\n\t\t\t}else{\n\t\t\t\tdateSpan[i].vacationDay = false;\n\t\t\t}\n\t\t}\n\t}\n\t//Once the Day Capacities and VacationDay projectStatus are set, flow the projects into the Days\n\t//console.log(\"+ capacity and vacationDay for each Day in the dateSpan has been defined. Now calling flowProjectsIntoDays().\");\n\tflowProjectsIntoDays();\n}", "function get_time_left() {\n return (total_paid / price_per_second) - time_spent;\n}", "function _updateCurrHours(employeeID, newEmployeeSchDuration, oldEmployeeSchDuration) {\r\n var $newlyAssignedEmployee = $(\"#\" + employeeID + \"> .hour-wrapper > .eligible-hours\");\r\n var oldHours = $newlyAssignedEmployee.text();\r\n var newHours = parseFloat(oldHours) + newEmployeeSchDuration;\r\n $newlyAssignedEmployee.text(newHours);\r\n var $previousAssignedEmployee = $(\".curr-assigned-employee\");\r\n if ($previousAssignedEmployee.length) {\r\n var $previousEmployeeHours = $previousAssignedEmployee.find(\".eligible-hours\");\r\n var oldHours = $previousEmployeeHours.text();\r\n var newHours = parseFloat(oldHours) - oldEmployeeSchDuration;\r\n $previousEmployeeHours.text(newHours);\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will clear Filter Panel
function clearFilterPanel() { "use strict"; // Clear Search term $(".filterSearchText").val(""); // Clear Clients $(".refinerClient .refinerRowLink:last a").click(); $(".refinerClient .filterOkButton:first > .tileOk").click(); // Clear PG $(".refinerPG .refinerRowLink:last a").click(); $(".refinerPG .filterOkButton:first > .tileOk").click(); // Clear AOL $(".filterSearchAOL .refinerRowLink:last a").click(); $(".refinerAOL .filterOkButton:first> .tileOk").click(); // Clear DOC Author $(".filterSearchAdvance .filterSearchAuthor .refinerRight .filterSearchRefinerText").val(""); // Clear From Date $(".filterSearchAdvance .filterSearchDate .refinerRight #refinerFromText").val(""); // Clear To Date $(".filterSearchAdvance .filterSearchDate .refinerRight #refinerToText").val(""); // Clear global filter object if (oGridConfig.isMatterView) { oSearchGlobal.oFilterData = { AOLList: "", PGList: "", ClientsList: [], FromDate: "", ToDate: "", DocumentAuthor: "", FilterByMe: oSearchGlobal.searchOption }; } else { oSearchGlobal.oFilterData = { ClientsList: [], FromDate: "", ToDate: "", DocumentAuthor: "", FilterByMe: oSearchGlobal.searchOption }; } oSearchGlobal.sSearchTerm = ""; }
[ "function clearConditionFilter(){ \n\t\tconditionFilter = true;\n\t\tdocument.getElementById(\"filterField\").value = \"\"; \n\t}", "function clearFilters() {\n tbody.html(\"\");\n init(data)\n}", "clearAllFilters() {\n this.currentFilters = []\n\n each(this.filters, filter => {\n filter.value = ''\n })\n }", "function resetFilters(){\n \n console.log(\"resetFilters()\");\n d3.selectAll(\".mainFilterCheckbox\").property('checked', false);\n \n resetZoom();\n \n updateVis();\n }", "function clearSearchFilter()\r\n{\r\n\tinnerHTML=document.forms.itemfilter.elements['namesearch'].value = \"\";\r\n\t//innerHTML=document.forms.itemfilter.elements['goldsearch'].value = \"\";\r\n\tinnerHTML=document.forms.itemfilter.elements['recipeclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['auraclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['disassembleclear'].checked = true;\r\n\r\n\tfilterItems();\r\n\treturn;\r\n}", "function clearFilter(context) { \n // iterate over all the nodes in the graph and show them (unhide)\n var self = context;\n if (self && self.GraphVis) {\n self.GraphVis.showAll(true);\n }\n \n self.GraphVis.gv.fit();\n}", "function clearShopFilter()\r\n{\r\n\tinnerHTML=document.forms.itemfilter.elements['LSpartclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['LSallclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['SSpartclear'].checked = true;\r\n\tinnerHTML=document.forms.itemfilter.elements['SSallclear'].checked = true;\r\n\r\n\tfilterItems();\r\n\treturn;\r\n}", "function clearGoldFilter()\r\n{\r\n\tinnerHTML=document.forms.itemfilter.elements['goldsearch'].value = \"0\";\r\n\r\n\tfilterItems();\r\n\treturn;\r\n}", "function resetFilters() {\n Filters.distance = 10;\n Filters.minPrice = 0.0;\n Filters.maxPrice = 100.0;\n Filters.itemQuality = 0;\n Filters.gender = 'all';\n Filters.type = 'all';\n Filters.size = 'all';\n Filters.color = 'all';\n Filters.freeOnly = false;\n}", "function clearNameFilter(){ \n\t\tnameFilter = \"\";\n\t\tdocument.getElementById(\"formField\").value = \"\"; \n\t}", "function resetInformationFilter() {\n let input = document.getElementById(\"information-filter\");\n input.value = \"\";\n filterInformations();\n}", "function ResetFilterRows() { // PR2019-10-26 PR2020-06-20 PR2022-05-19\n console.log( \"===== ResetFilterRows ========= \");\n\n setting_dict.sel_exam_pk = null;\n selected.map_id = null; //PR2023-05-16 added\n\n filter_dict = {};\n\n\n t_reset_filterrow(tblHead_datatable);\n t_tbody_selected_clear(tblBody_datatable);\n// --- show total in sidebar\n t_set_sbr_itemcount_txt();\n\n t_Filter_TableRows(tblBody_datatable, filter_dict, selected, loc.Exam, loc.Exams);\n\n //Filter_TableRows(tblBody_datatable);\n //FillTblRows();\n } // function ResetFilterRows", "function removeFilter(){\r\n \t\r\n \tvar idx = -1;\r\n \tangular.forEach( ctrl.filters, function(filter,index){ if( filter === ctrl.currentFilter ) idx = index; });\r\n \tif( idx >=0 ){ \r\n \t\tctrl.filters.splice( idx,1 ); \t \r\n \t\tctrl.currentFilter = (ctrl.filters.length >= 0 )? ctrl.filters[0] : null;\r\n \t\tapplyFilterChange();\r\n \t}\r\n }", "function clearCanvas() {\n elements.gridCanvas.innerHTML = '';\n }", "function resetFilters() {\n refinedTable = tableData;\n dataTable(tableData);\n}", "function clearHtml() {\n $(\"#searchChart\").remove();\n}", "function clearInputs() {\n var i;\n controlElem.value = '';\n for (i = 0; i < dilutions.length; i += 1) {\n dilElems[i].value = '';\n }\n updateResults();\n }", "unfilter() {\n if (!this._filtered)\n return;\n this._player.setFilter(null);\n this._player.filter();\n this._filtered = false;\n }", "function clearMainSearch() {\n document.getElementById(\"filter-recipe-input\").value = \"\"\n updateRecipeListDOM()\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function validates interest rate field
function validateIntRate(errorMsg) { var tempIntRate = document.mortgage.intRate.value; tempIntRate = tempIntRate.trim(); var tempIntRateLength = tempIntRate.length; var tempIntRateMsg = "Please enter Interest Rate!"; if (tempIntRateLength == 0) { errorMsg += "<p><mark>Interest rate field: </mark>Field is empty <br />" + tempIntRateMsg + "</p>"; } else { if (isNaN(tempIntRate) == true) { errorMsg += "<p><mark>Interest rate field: </mark>Must be numeric <br />" + tempIntRateMsg + "</p>"; } else { if (parseFloat(tempIntRate) < 2.000 || parseFloat(tempIntRate) > 11.000) { errorMsg += "<p><mark>Interest rate field: </mark>Must be values: 2.000 thru 11.000 inclusive <br />" + tempIntRateMsg + "</p>"; } } } return errorMsg; }
[ "function validateTaxableIncome() {\n var taxableIncome = document.TaxCalculator.taxableIncome.value;\n var regex = /[0-9]|\\./;\n \n if (taxableIncome === \"\" || taxableIncome === \"0.00\" || taxableIncome === \"0\") {\n errorMessage += \"Please Enter your Taxable Income. \\n\";\n document.getElementById(\"taxableIncome\").style.backgroundColor=\"red\";\n return false;\n } else if (!regex.test(taxableIncome)) {\n errorMessage += \"Please Enter Only a Numberic Value As your Taxable Income. \\n\";\n document.getElementById(\"taxableIncome\").style.backgroundColor=\"red\";\n return false;\n } else {\n document.getElementById(\"taxableIncome\").style.backgroundColor=\"\";\n return true;\n }\n}", "function validRating(rating){\n try {\n let numRate = parseInt(rating)\n if(numRate < 1 || numRate > 5){\n return false;\n } else {\n return true;\n }\n } catch (e){\n return false;\n }\n}", "function validateInput() {\n\tvar valid = false;\n\tvar maxPins = 0;\n\tif (!((pins==0)||(pins==\"1\")||(pins==2)||(pins==3)||(pins==4)||(pins==5)||(pins==6)||(pins==7)||(pins==8)||(pins==9)||(pins==10))) {\n\t\talert('The number of pins must be between 0 and 10.');\n\t\t$scope.pins = '';\n\t} else if ((ball == 1) && (frame != 9) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\t} else if ((ball == 1) && (frame == 9) && (parseInt(line[frame][0]) != 10) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\n\t} else {\n\t\tvalid = true;\n\t\tconsole.log('valid input');\n\t}\n\treturn valid;\n}", "function isValidInsurer(insurerCode) {\n\t\t\t\t\t\tvar premiumDetailsForTheInsurer = premiumDetailsForAll.premium[insurerCode];\n\t\t\t\t\t\tif (angular.isDefined(premiumDetailsForTheInsurer)) {\n\t\t\t\t\t\t\tvar status = premiumDetailsForTheInsurer.status;\n\t\t\t\t\t\t\tif (angular.isDefined(status)\n\t\t\t\t\t\t\t\t\t&& status === RatingConstants.SUCCESS) {\n\t\t\t\t\t\t\t\tvar selectedCovers = CoverageService\n\t\t\t\t\t\t\t\t\t\t.getSelectedCovers();\n\t\t\t\t\t\t\t\tif (angular.isDefined(selectedCovers)\n\t\t\t\t\t\t\t\t\t\t&& !angular.equals({}, selectedCovers)) {\n\t\t\t\t\t\t\t\t\tvar noOfCovers = 0;\n\t\t\t\t\t\t\t\t\tvar noOfApplicableCovers = 0;\n\t\t\t\t\t\t\t\t\tangular\n\t\t\t\t\t\t\t\t\t\t\t.forEach(\t\n\t\t\t\t\t\t\t\t\t\t\t\t\tselectedCovers,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(value, key) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (value.coverType === RatingConstants.ADDITIONAL || value.coverType === RatingConstants.DISCOUNTS || value.coverType === RatingConstants.ADDON) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnoOfCovers = noOfCovers + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar coverValues = premiumDetailsForTheInsurer.coverDetails[value.code];\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (angular\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.isDefined(coverValues)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&& !angular\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.equals(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcoverValues)) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (coverValues.rateType === RatingConstants.RATE) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (coverValues.rate != RatingConstants.RATE_NA)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnoOfApplicableCovers = noOfApplicableCovers + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else if (coverValues.rateType === RatingConstants.FLAT) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (coverValues.flat != RatingConstants.RATE_NA)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnoOfApplicableCovers = noOfApplicableCovers + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} else if (coverValues.rateType === RatingConstants.BOTH) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (coverValues.rate != RatingConstants.RATE_NA\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t&& coverValues.flat != RatingConstants.RATE_NA)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnoOfApplicableCovers = noOfApplicableCovers + 1;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tif (noOfCovers === noOfApplicableCovers) {\n\t\t\t\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treturn false;\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\treturn true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}", "static isValidReview(review) {\r\n // {\r\n // \"restaurant_id\": <restaurant_id>,\r\n // \"name\": <reviewer_name>,\r\n // \"rating\": <rating>,\r\n // \"comments\": <comment_text>\r\n // }\r\n let isValid = true;\r\n if (\r\n !review ||\r\n !Number.isInteger(Number(review.restaurant_id)) ||\r\n !Number.isInteger(Number(review.rating)) ||\r\n !(review.rating > 0 && review.rating < 6) ||\r\n !validator.isAlpha(review.name) ||\r\n !validator.isLength(review.comments, { min: 1, max: 140 })\r\n ) {\r\n isValid = false;\r\n }\r\n return isValid;\r\n }", "validateInputs() {\n\t\tif(isNaN(this.billAmount) || this.billAmount <= 0 || this.totalPerson == 0) return false;\n\t\treturn true;\n\t}", "static validateValuationCodeEntered(pageClientAPI, dict) {\n let error = false;\n let message = '';\n //Code group is not empty\n if (!libThis.evalCodeGroupIsEmpty(dict)) {\n //Characteristic is blank\n if (libThis.evalIsCodeOnly(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('field_is_required');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n } else {\n //Code sufficient is set and reading is empty\n if (libThis.evalIsCodeSufficient(dict) && libThis.evalIsReadingEmpty(dict)) {\n error = (libThis.evalValuationCodeIsEmpty(dict));\n if (error) {\n message = pageClientAPI.localizeText('validation_valuation_code_or_reading_must_be_selected');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ValuationCodeLstPkr'), message);\n }\n }\n }\n }\n if (error) {\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n } else {\n return Promise.resolve(true);\n }\n }", "function isValidAmount(sender) {\n var id = $(sender).attr('id');\n var elementValue = $('#' + id).val();\n var expamount = /^(?:\\d*\\.\\d{1,2}|\\d+)$/;\n\n if (elementValue.length > 0)\n return expamount.test(elementValue)\n else\n return true;\n}", "function validatePounds() {\n\tvar ptr = $(\"numItemWeightLb\"); \t\t//Pointer to pounds input field\n\tvar err = $(\"errItemWeightLb\");\t\t//Pointer to error marker for pounds\n\tvar input;\t\t\t\t\t\t\t\t\t//Contents of the pounds text box\n\t\n\terr.style.visibility = \"hidden\";\n\tif(ptr.value == \"\") {\n\t\terr.style.visibility = \"visible\";\n\t\terr.title = \"You must enter the number of pounds.\";\n\t} else {\n\t\tinput = FormatNumber(ptr.value, \"G\"); //Unformat it (remove commas\n\t\tinput = parseInt(input);\n\t\tif(input<0) { \n\t\t\terr.style.visibility = \"visible\";\n\t\t\terr.title = \"Pounds must be at least 0\";\n\t\t} else {\n\t\t\tptr.value = FormatNumber(input, \"N0\");\n\t\t} //end if\n\t}//end if\n\n\treturn err.style.visibility == \"hidden\";\n\n}", "function checkPrice(field, rules, i, options) {\r\n\t\tvar price = parseInt(field.val().replace(/[^0-9]/g, '')); //Strip off the decimal\r\n\t\tvar priceRegex = /^\\d+(\\.\\d{2})?$/;\r\n\t\t\r\n\t\tif (price >= 0 && price <= 99999 && priceRegex.test(field.val())) {\r\n\t\t\t//No problem!\r\n\t\t} else {\r\n\t\t\treturn '* Valid prices range from $0.00 to $999.99';\r\n\t\t}\r\n\t}", "static validateReadingIsNumeric(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n //New reading must be a number\n if (libLocal.isNumber(pageClientAPI, dict.ReadingSim)) { \n return Promise.resolve(true);\n } else {\n let message = pageClientAPI.localizeText('validation_reading_is_numeric');\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }", "function validateAmortization(errorMsg) {\n var tempAmortization = document.mortgage.amortization.value;\n tempAmortization = tempAmortization.trim();\n var tempAmortizationLength = tempAmortization.length;\n var tempAmortizationMsg = \"Please enter Amortization!\";\n\n if (tempAmortizationLength == 0) {\n errorMsg += \"<p><mark>No. of years field: </mark>Field is empty <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (isNaN(tempAmortization) == true) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be numeric <br />\" + tempAmortizationMsg + \"</p>\";\n } else {\n if (tempAmortization < 5 || tempAmortization > 20) {\n errorMsg += \"<p><mark>No. of years field: </mark>Must be values: 5 thru 20 inclusive <br />\" + tempAmortizationMsg + \"</p>\";\n }\n }\n }\n return errorMsg;\n}", "function validate_visualize_inputs(){\n\n // \"Term Count\"\n if(!validate_number($(\"#term-count-input\").val(), 1, 1000)){\n error(\"Invalid term count.\", \"#term-count-input\");\n return false;\n }\n\n return true;\n}", "function validateMarginCostForm(frm)\n{ \n if(frm.frmMarginCost.value==''){\n alert(MARGIN_COST_REQ);\n frm.frmMarginCost.focus();\n return false;\n }else if(AcceptDecimal(frm.frmMarginCost.value)==false){\n alert(ENTER_NUMRIC);\n frm.frmMarginCost.focus();\n return false; \n }else return true;\n \n}", "function guessValidation () {\n if (+($(\"#userGuess\").val()) > 100 || +($(\"#userGuess\").val()) < 1) {\n alert(\"Please enter a number between 1 - 100\");\n }\n }", "function isValidAmount(element){\n\t\n\t\t// user's amount\n\t\tvar amount = element.value;\t\n\t\t\n\t\t// parse amount as float\n\t\tamount = parseFloat(amount);\n\t\t\n\t\t// if amount is number, parse amount\n\t\tif(!isNaN(amount) && amount > 0.0 && amount < 100000){\n\t\t\n\t\t\t// test passed\n\t\t\treturn true;\n\t\t\t\n\t\t}else{\n\t\t\n\t\t\t// alert user of error\n\t\t\talert(\"Amount has to be in range: 0 to 100,000.\");\n\t\t\t\n\t\t\t// shift focus to failed webpage field\n\t\t\telement.focus();\n\t\t\t\n\t\t\t// test failed\n\t\t\treturn false;\n\t\t}\n\t}", "function inputValidation(item){\n const inputSchema = {\n Name: Joi.string().min(4).max(125).required(),\n Description:Joi.string().min(4).max(1024).required(),\n Price: Joi.number().min(5).required(),\n Categery: Joi.string().max(20).required().required(),\n SellingBy: Joi.string(),\n }\n \n return Joi.validate(item, inputSchema)\n}", "function validateShippingCostForm(formID)\n{\n if(validateForm(formID, 'frmCountry', 'Country Name', 'R','frmShippingCostState','State Name','R','frmShippingCost','Shipping Cost','R'))\n { \n if($('#frmShippingCostType').val() == 'Percentage')\n {\n if($('#frmShippingCost').val() > 100)\n {\n alert(SHIPP_COST_PERCEN);\n $('#frmShippingCost').focus();\n return false;\n }\n }\n\t\t\n return true;\n } \n else \n {\n return false;\n }\n}", "function skillValuesValidation() {\r\n // get TOTAL_FORMS element from Django management_form of Skill formset\r\n let totalSkillForms = document.getElementById(\"id_skill-TOTAL_FORMS\");\r\n let skillValues = [];\r\n // iterate Skill value fields and collect valid values\r\n for (i = 0; i < totalSkillForms.value; i++) {\r\n let skillDeleteFlag = document.getElementById(`id_skill-${i}-DELETE`).checked;\r\n let skillValue = document.getElementById(`id_skill-${i}-value`).value;\r\n if (!skillDeleteFlag && skillValue !== \"\") {\r\n skillValues.push(parseInt(skillValue));\r\n }\r\n }\r\n // sum up Skill values\r\n const valuesSum = skillValues.reduce((a, b) => a + b, 0);\r\n // calculate remaining Skill Points\r\n const remainingPoints = 400 - valuesSum;\r\n let skillPointsRemaining = document.getElementById(\"skill-points-remaining\");\r\n // adapt Frontend message\r\n skillPointsRemaining.innerHTML = `Remaining Skill Points: ${remainingPoints}`;\r\n // handle Submit Button state\r\n if (remainingPoints !== 0) {\r\n document.getElementById(\"characterSubmit\").disabled = true;\r\n } else {\r\n document.getElementById(\"characterSubmit\").disabled = false;\r\n }\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
failureReporter inputs the arguments to the property that failed tries number of times inputs were tested before Failure
function failureReporter(inputs, tries) { var self = getInstance(this, failureReporter); self.inputs = inputs; self.tries = tries; return self; }
[ "function failureReporter(inputs, tries) {\n const self = getInstance(this, failureReporter);\n self.inputs = inputs;\n self.tries = tries;\n return self;\n}", "errorMsg (title, expected, actual) {\n console.log(colors.red(`FAILED ${title.toUpperCase()}`))\n\n if (arguments.length === 4) {\n expected = JSON.stringify(expected)\n actual = JSON.stringify(actual)\n console.log(` Expected ${expected}\\n but got ${actual}`)\n }\n }", "static failRetry(){\r\n let fatus = Fatusjs.instance;\r\n fatus.getFailSize(function onGet(err,count){\r\n if(count && count >0){\r\n console.log(MODULE_NAME + ': adding fail worker');\r\n fatus.addFailWorker();\r\n }\r\n });\r\n fatus.getQueueSize(function onGet(err,count){\r\n if(count && count >0){\r\n console.log(MODULE_NAME + ': adding collector' )\r\n fatus.addCollector();\r\n }\r\n })\r\n }", "get numPasses() {\n return 1\n }", "function testIncreasing() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"increasing\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const numbers of parameters[0].values) {\n const functionCall = `increasing(${format(numbers)})`;\n const expected = staff.increasing(numbers);\n const actual = student.increasing(numbers);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`increasing -- passed ${pass} out of ${tc} test cases.`);\n}", "function failure(change) {\n return metric(\"Failure\", change);\n }", "function passedFailed(expectation, message1, message2) {\n\treturn result(expectation.isNot, message1, message2);\n}", "testAssertResultLength() {\n \n }", "_onJobFailure(...args) {\n const onJobFailure = this.options.onJobFailure;\n if (isFunction(onJobFailure)) {\n onJobFailure(...args);\n } else if (!this.options.mute) {\n this.log.error('');\n this.log.error('--------------- RDB JOB ERROR/FAILURE ---------------');\n this.log.error(`Job: ${args[0].options.runs}` || args[0].queue);\n args[1].stack = args[2].join('\\n');\n this.log.error(args[1]);\n this.log.error('------------------------------------------------------');\n this.log.error('');\n }\n }", "function failedTestFn() {\n throw new Error('test failed');\n }", "static Failure(failureMessage) {\n\t\tif (failureMessage === null) {\n\t\t\t\tconsole.log(\"Test Failure\");\n\t\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (typeof failureMessage === 'object')\n\t\t\tfailureMessage = JSON.stringify(failureMessage);\n console.error(`Test Failure: ${failureMessage}`);\n }", "function testMax() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"max\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const numbers of parameters[0].values) {\n const functionCall = `max(${format(numbers)})`;\n const expected = staff.max(numbers);\n const actual = student.max(numbers);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`max -- passed ${pass} out of ${tc} test cases.`);\n}", "function resetFailFountain(){\n runFail = false;\n failFountain.reset(failParticle);\n coordinates = [];\n}", "function failure() {\n return { solution: false };\n}", "function testClumps() {\n const { parameters } = tests.exercises.find((exercise) => {\n return exercise.name === \"clumps\";\n });\n\n let tc = 0;\n let pass = 0;\n for (const values of parameters[0].values) {\n const functionCall = `clumps(${format(values)})`;\n const expected = staff.clumps(values);\n const actual = student.clumps(values);\n\n if (expected !== actual) {\n console.log(`Test Case ${tc + 1} -- Fail.`);\n console.log(` - call: ${functionCall}`);\n console.log(` - expected: ${expected}`);\n console.log(` - actual: ${actual}\\n`);\n } else {\n pass++;\n }\n\n tc++;\n }\n console.log(`clumps -- passed ${pass} out of ${tc} test cases.`);\n}", "function trials (test, minSuccess = 10) {\n let success = 0\n for (let t = 0; t < 10; t++) {\n success += test() ? 1 : 0\n }\n assert(success >= minSuccess)\n }", "get numberOfResultsIsValid() {\n return this._isPositiveNumber(this.state.numberOfResults);\n }", "incrementAttempts (job) {\n\n job.attempts++;\n\n return job;\n\n }", "function fail() {\n putstr(padding_left(\" FAILED\", seperator, sndWidth));\n putstr(\"\\n\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes unwanted formatting from Hue chat messages
function hue_clean_chat_message(message) { return message.replace(/\=?\[dummy\-space\]\=?/gm, ''); }
[ "function messageData(user, text){\n text = text.replace(':)', '\\uD83D\\uDE00')\n text = text.replace(':(', '\\uD83D\\uDE41')\n text = text.replace(':o', '\\uD83D\\uDE2E')\n return{\n user, \n text,\n time: moment().format('h:mm a')\n }\n}", "function convertMessages(data) {\n let slice = data.slice(2, data.length)\n let fixedresult = \"[\" + slice + \"]\";\n return JSON.parse(fixedresult);\n}", "_renderChatMessage(message, html, _data) {\r\n\t\tif (html.find('.narrator-span').length) {\r\n\t\t\thtml.find('.message-sender').text('');\r\n\t\t\thtml.find('.message-metadata')[0].style.display = 'none';\r\n\t\t\thtml[0].classList.add('narrator-chat');\r\n\t\t\tif (html.find('.narration').length) {\r\n\t\t\t\thtml[0].classList.add('narrator-narrative');\r\n\t\t\t\tconst timestamp = new Date().getTime();\r\n\t\t\t\tif (message.data.timestamp + 2000 > timestamp) {\r\n\t\t\t\t\tconst content = $(message.data.content)[0].textContent;\r\n\t\t\t\t\tlet duration = this.messageDuration(content.length);\r\n\t\t\t\t\tclearTimeout(this._timeouts.narrationCloses);\r\n\t\t\t\t\tthis.elements.content[0].style.opacity = '0';\r\n\t\t\t\t\tthis._timeouts.narrationOpens = setTimeout(this._narrationOpen.bind(this, content, duration), 500);\r\n\t\t\t\t\tthis._timeouts.narrationCloses = setTimeout(this._narrationClose.bind(this), duration);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\thtml[0].classList.add('narrator-description');\r\n\t\t\t}\r\n\t\t}\r\n\t}", "createChatMessage(type, message) {\r\n\t\t// Patch the chat appearance to conform with specific modules\r\n\t\tlet csspatches = '';\r\n\t\tif (game.modules.get('pathfinder-ui') !== undefined && game.modules.get('pathfinder-ui').active) {\r\n\t\t\tcsspatches += 'sasmira-uis-fix';\r\n\t\t} else if (game.modules.get('dnd-ui') !== undefined && game.modules.get('dnd-ui').active) {\r\n\t\t\tcsspatches += 'sasmira-uis-fix';\r\n\t\t}\r\n\t\tconst chatData = {\r\n\t\t\tcontent: `<span class=\"narrator-span ${type == 'narrate' ? 'narration' : 'description'} ${csspatches}\">${message.replace(\r\n\t\t\t\t/\\\\n|<br>/g,\r\n\t\t\t\t'\\n'\r\n\t\t\t)}</span>`,\r\n\t\t\ttype: this._msgtype,\r\n\t\t\tspeaker: {\r\n\t\t\t\talias: game.i18n.localize('NT.Narrator'),\r\n\t\t\t\tscene: game.user.viewedScene,\r\n\t\t\t},\r\n\t\t};\r\n\t\tChatMessage.create(chatData, {});\r\n\t}", "function sendChatMessege()\n{\n var chat = cleanInput($(\"#chat-box\").val().substring(0, 100));\n\n if($.isBlank(chat))\n return;\n\n socket.emit('chat', chat);\n setPlayerMessege(player, chat);\n $(\"#chat-box\").val(\"\");\n}", "function cleanInput(data) {\n return data.toString().replace(/(\\r\\n|\\n|\\r)/gm, \"\");\n }", "function stripInternalStacks(message) {\n message = message.replace(\n /^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s\\)]*(\\n|$)/gm,\n \"\"\n );\n return message;\n}", "function clearPlayerOneChat(i) {\n if (i.toLowerCase() == \"clear\") {\n for (var j = 0; j < self.playerOneMessages.length + 1; j++) {\n self.playerOneMessages.$remove(j);\n }\n }\n }", "function formatPostSlackMessage(message) {\n //title\n var title = message[0];\n var titleToString = title.toString();\n var titleAndValue = titleToString.split(': ');\n postTitle = titleAndValue[1];\n\n //subtitle\n var subtitle = message[1];\n var subtitleToString = subtitle.toString();\n var subtitleAndValue = subtitleToString.split(': ');\n postSubTitle = subtitleAndValue[1];\n\n //paragraph 1\n var para = message[2];\n var paraToString = para.toString();\n var paraValue = paraToString.split(': ');\n postParagraph1 = paraValue[1];\n\n //paragraph 2\n var para2 = message[2];\n var para2ToString = para2.toString();\n var paraValue2 = para2ToString.split(': ');\n postParagraph2 = paraValue2[1];\n\n //paragraph 3\n var para3 = message[2];\n var para3ToString = para3.toString();\n var paraValue3 = para3ToString.split(': ');\n postParagraph3 = paraValue3[1];\n\n //paragraph 4\n var para4 = message[2];\n var para4ToString = para4.toString();\n var paraValue4 = para4ToString.split(': ');\n postParagraph4 = paraValue4[1];\n}", "function removeWinningMessage() {\n winningMessage.textContent = \"\";\n boardElement.classList.remove(\"hidden\");\n winningMessage.classList.remove(\"visible\");\n winningMessage.classList.add(\"hidden\");\n }", "function removeMessages(){\n\t//remove note message\n\tdocument.getElementById(\"notePopup1\").classList.remove(\"notePopup1\");\n\tdocument.getElementById(\"notePopup2\").classList.remove(\"notePopup2\");\n\n\t//remove win/lose/draw message\n\tvar status = Session.get(\"onMessage\");\n\tif(status == \"lock\"){\n\t\tSession.set(\"onMessage\", \"hold\");\n\t}else if(status == \"hold\" || status == \"free\"){ //should not include 'free', but hardcoded to solve a bug(rare though). look forward a better solution.\n\tdocument.getElementById(\"winPopup1\").classList.remove(\"winPopup1\");\n\tdocument.getElementById(\"winPopup2\").classList.remove(\"winPopup2\");\n\tdocument.getElementById(\"drawPopup\").classList.remove(\"drawPopup\");\n\tdocument.getElementById(\"losePopup1\").classList.remove(\"losePopup1\");\n\tdocument.getElementById(\"losePopup2\").classList.remove(\"losePopup2\");\n\n\tSession.set(\"onMessage\", \"free\");\n}\n}", "refreshMentions()\n {\n this.mentions = this.messageRaw.match(/<@(?:\\d){13}>/g) === null ? [] : new Array(...this.messageRaw.match(/<@(?:\\d){13}>/g));\n if (this.mentions.includes(`<@${thisUser.id}>`) && !this.msg.classList.contains('mention'))\n {\n $(this.msg).addClass('mention');\n if (document.visibilityState === 'hidden')\n {\n document.title = `${document.title.match(/\\d+/) === null ? 1 : parseInt(document.title.match(/\\d+/)[0]) + 1}🔴 🅱️iscord`;\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible')\n {\n document.title = '🅱️iscord';\n }\n }, { once: true });\n }\n }\n else if (!this.mentions.includes(`<@${thisUser.id}>`) && this.msg.classList.contains('mention'))\n {\n $(this.msg).removeClass('mention');\n document.title = `${document.title.match(/\\d+/) === null ? '' : parseInt(document.title.match(/\\d+/)[0]) - 1 <= 0 ? '' : `${parseInt(document.title.match(/\\d+/)[0]) - 1}🔴 `}🅱️iscord`;\n }\n }", "function renderMessage(info) {\n let m = sanitizeHTML(info);\n let parsed = reader.parse(m);\n let message = writer.render(parsed);\n \n return `${message}`;\n}", "function chatTimestamp(timestamp) {\n var date = new Date(timestamp);\n var deltaHours = Math.floor((Date.now() - date) / (1000*60*60));\n if (deltaHours < 24) {\n return date.toLocaleTimeString();\n } else {\n return date.toLocaleString();\n }\n}", "function formatGroupMessage(user_idFrom, text) {\n\treturn {\n\t\tfrom: user_idFrom,\n\t\ttext: text,\n\t\tcreatedAt: moment()\n\t}\n}", "rawHTML(html) {\n this.$messages.html(this.$messages.html() + html);\n return this.$messagesContainer.restoreScrollPosition();\n }", "function clearChat(){\n\tdatabase.ref().child(\"chat\").set({line:\"\"});\n}", "function trim()\n{\n if (maxMessages !== null)\n {\n while(messages.length > maxMessages)\n {\n messages.shift();\n }\n }\n}", "function clearPlayerTwoChat(i) {\n if (i.toLowerCase() == \"clear\") {\n for (var j = 0; j < self.playerTwoMessages.length + 1; j++) {\n self.playerTwoMessages.$remove(j);\n }\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: extUtils.getLoopVarNestLevel DESCRIPTION: Retrieve the level of nested loops in which variable occurs ARGUMENTS: param param name levelToParamList hash table to match loop parameters with associated nested loop. RETURNS: numbered level or 1 if not found
function extUtils_getLoopVarNestLevel(param, levelToParamList) { for (var level in levelToParamList) { // Note levelToParamList[level] may have been emptied or made null to clean // out the parameter list for the associated level. for (var i = 0; levelToParamList[level] && i < levelToParamList[level].length; ++i) { if (levelToParamList[level][i] == param) return level; } } return -1; }
[ "get depth() {\n let d = 0;\n for (let p = this.parent; p; p = p.parent)\n d++;\n return d;\n }", "function getDepth(page_id) {\n\t\t\tif(!page_id || page_id < 1) return 0;\n\t\t\tconsole.log(page_id);\n\t\t\tvar depth = 0;\n\t\t\tvar parent_id = parents[page_id];\n\t\t\twhile (parent_id != 0 && depth < 3) {\n\t\t\t\tconsole.log(depth);\n\t\t\t\tdepth++;\n\t\t\t\tparent_id = parents[parent_id];\n\t\t\t}\n\t\t\treturn depth;\n\t\t}", "function checkLayerDepth(num) {\n var string = '';\n // Start counting at 1 - base layers are 1, and do\n // not need to be indented.\n for (var i = 1; i < num; i++) {\n // A clean way to indent layers based on depth is to add an 'em'\n // element for each step a layer is in relation to the root. The\n // 'em' elements have a fixed width of 12px, so the layer will be\n // indented (12px * distance from root layer).\n string += '<em></em>';\n }\n return string;\n}", "function getFoldLevel(editor) {\n\t\tfunction nestLevel(node) {\n\t\t\tvar level = 0;\n\t\t\twhile (node.parent) {\n\t\t\t\tlevel++;\n\t\t\t\tnode = node.parent;\n\t\t\t}\n\t\t\treturn level;\n\t\t}\n\t\t// what folds have we got ?\n\t\tvar tree = editor.tree(), folds = editor.folds(),\n\t\t\tlstLevels = [], i=0, lngFolds = folds.length, lngLine;\n\n\t\t// and how deep is the shallowest fold ?\n\t\tfor (i=0; i < lngFolds; i++) {\n\t\t\tlngLine = folds[i].range().startLine();\n\t\t\tlstLevels.push(nestLevel(tree.lineNumberToNode(lngLine)));\n\t\t}\n\t\t// null if no folds\n\t\treturn lstLevels.sort()[0];\n\t}", "function getLvlID() {\n return `${gridSize}x${gridSize}_nr${lvlNumber}`;\n}", "function regex_for_depth( depth ) {\n\t\n\t return new RegExp(\n\t // m[1] = indent, m[2] = list_type\n\t \"(?:^(\" + indent_re + \"{0,\" + depth + \"} {0,3})(\" + any_list + \")\\\\s+)|\" +\n\t // m[3] = cont\n\t \"(^\" + indent_re + \"{0,\" + (depth-1) + \"}[ ]{0,4})\"\n\t );\n\t }", "function allFlatIndexesAboveLevel(namesByLevel, currentLevel) {\n let count = 0;\n let list = [];\n _.each(namesByLevel, function (l, i) {\n if (i > currentLevel) {\n _.each(l, function (item, i) {\n list.push(count + i);\n });\n }\n count += l.length;\n });\n return list;\n}", "function parseLevel(num) {\n // check if that level exists\n if (num > levels.length) {\n throw Error(\"Invalid level.\");\n }\n return parseConfig(levels[num]);\n}", "function wordNest(word, nest) {\n\treturn (nest.length / word.length) - 1;\n}", "function getDepth(element, depth)\n{\n\t// Initliazing our output to just be an empty string at first\n\tvar output = \"\";\n\n\t// Retrieving all the children of the element we are looking at\n\tvar children = element.childNodes;\n\n\t// If we are looking at the HTML element, we will treat it as a special case\n\tif (element.nodeName == \"HTML\")\n\t{\n\t\toutput += element.nodeName + \"\\n\";\n\t}\n\t// Adding event listeners for click events to all the elements. Click on an element will output,\n\t// via an alert box, its name preceded by its depth (in dashes), followed by its parent element,\n\t// and so on until it outputs the root element (<html>).\n\telement.addEventListener(\"click\", function()\n\t{\n\t\tvar text = \"\";\n\t\tvar level = \"-\".repeat(depth);\n\t\ttext += level + element.nodeName;\n\t\twindow.alert(text);\n\t});\n\n\t// Going through each child element one by one\n\tfor (var i = 0; i < children.length; i++)\n\t{\t\n\t\t// Skipping all text nodes\n\t\tif (children[i].nodeType != 3)\n\t\t{\n\t\t\t// Creating a dash, using depth+1 here because just depth returns the incorrect number\n\t\t\tvar dash = \"-\".repeat(depth+1);\n\n\t\t\t// Adding on the dash and the name of the child, plus a newline character\n\t\t\toutput += dash + children[i].nodeName + \"\\n\";\n\n\t\t\t// Recursively calling getDepth with the element we are looking at, plus its depth\n\t\t\toutput += getDepth(children[i], depth+1);\n\t\t}\n\t}\n\n\t// Returning the output string\n\treturn output;\n}", "function depth(x) {\n var txt = '';\n\n for (var i=0, max = x.length; i < max; i++){\n var name = x[i].tagName;\n var dashes = $(name).parents().length;\n txt += '-'.repeat(dashes) + name + '\\n';\n console.log('-'.repeat(dashes), name);\n }\n return txt;\n }", "function get_recursive_integer_lookup(tblRow) {\n // PR2021-09-08 debug: don't use b_get_mapdict_from_datarows with field 'mapid'.\n // It doesn't lookup mapid correctly: school_rows is sorted by id, therefore school_100 comes after school_99\n // instead b_recursive_integer_lookup with field 'id'.\n\n// --- lookup data_dict in data_rows, search by id\n const pk_int = get_attr_from_el_int(tblRow, \"data-pk\");\n const data_rows = (selected_btn === \"btn_result\") ? student_rows : null;\n const [index, found_dict, compare] = b_recursive_integer_lookup(data_rows, \"id\", pk_int);\n\n return found_dict;\n }", "assignLevel(node, level) {\n node.level = level;\n if (level+1 > this.depth) {\n this.depth++;\n } \n for (let i = 0; i < node.children.length; i++) { \n this.assignLevel(node.children[i], level+1);\n }\n }", "async function findHashDirectoryDepth(root) {\n const helper = async (rootPath) => {\n const subDirs = await utilities_ts_1.files.readdir(rootPath);\n if (subDirs.length === 0)\n return 0;\n const subDir = subDirs[0];\n if (isNumerical(subDir))\n return 1;\n const depth = await helper(path.join(rootPath, subDir));\n return depth + 1;\n };\n // use a helper to find the \"numerical\" paths\n // these are the run numbers, and should come just after the hash path\n // subtract 1 from the run number depth to retrieve the hash depth\n const depth = await helper(root);\n return depth - 1;\n}", "function createLegacyLoopSpecMap() {\n // The loopsJSON is structure like user loop hierarchy\n let loopSpeculationDict = {};\n let loopsToVisitQueue = [];\n if (loopsJSON.hasOwnProperty('children')) {\n // Top most children is the function\n loopsJSON['children'].forEach(function (funcNode) {\n if (funcNode.hasOwnProperty('children')) {\n // Push all the highest level loop into the queue\n funcNode['children'].forEach(function (loopNode) {\n loopsToVisitQueue.push(loopNode);\n });\n }\n });\n while (loopsToVisitQueue.length > 0) {\n let curLoop = loopsToVisitQueue.shift();\n if (curLoop.data[0] !== \"n/a\") {\n // Ignore non-real loop. Real loop would Pipeline is either \"Yes\" or \"No\"\n loopSpeculationDict[curLoop.name] = curLoop.data[2];\n }\n if (curLoop.hasOwnProperty('children')) {\n curLoop['children'].forEach(function (subloop) {\n loopsToVisitQueue.push(subloop);\n });\n }\n }\n }\n return loopSpeculationDict;\n}", "function levels(stat) {\n\treturn parseInt(document.getElementById(stat + \"_levels\").value);\n}", "assignLevel(node, level) {\n node.level = level;\n for (let n of node.children) {\n this.assignLevel(n, level+1);\n }\n }", "function recursiveFunction(someParam) {\n recursiveFunction(someParam)\n}", "function changeLevel() {\n const inputFieldLvlNr = document.getElementById('lvl_nr_input_field');\n const lvl_nr_input = parseInt(inputFieldLvlNr.value);\n if (lvl_nr_input >= 1 && lvl_nr_input <= nLevels) {\n lvlNumber = lvl_nr_input;\n toggleLevelBox();\n createGrid();\n loadLevel();\n resetGame();\n } else alert(`Puzzle number should be between 1 and ${nLevels}.`);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 77 Create a function that filters out an array to include numbers who only have a certain number of digits.
function filterDigitLength(arr, num) { const a = arr.filter(x => x.toString().length === num); return a; }
[ "function filterNumbers(inputArray) { //step one\n var numberBucket = []; //step two\n\n inputArray.forEach(function(item) { //step three for each loop\n if (typeof item === \"number\"){ //step four, conditional statement\n numberBucket.push(item)\n }\n });\n return numberBucket.sort(function(a, b){ //step 6 & 7\n return a - b;\n });\n}", "function unlucky13(nums) {\n return nums.filter(num => num % 13);\n}", "function subsetNum() {\n return numbers.slice(3,7);\n}", "function multiFour(array){\n var result =array.filter(num =>num%4===0)\n \n return result\n}", "function numberNotContains(){\n for(let i=0; i<myArray.length; i++){\n return (myArray[i]!=1 || myArray[i]!=3) ? true : false\n }\n }", "function differentDigitsNumberSearch(inputArray) {\n let currentNumber;\n let hasUniqueDigits = false;\n \n for(let i = 0; i < inputArray.length; i++) {\n currentNumber = inputArray[i]+'';\n \n for(let digit of currentNumber) {\n if(currentNumber.indexOf(digit) === currentNumber.lastIndexOf(digit)) {\n hasUniqueDigits = true;\n } else {\n hasUniqueDigits = false;\n }\n }\n \n if(hasUniqueDigits) {\n return +currentNumber;\n }\n hasUniqueDigits = false;\n }\n return -1;\n}", "function returnPrimeNumbers() {\n const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];\n const primeNumbers = [2, 3, 5, 7, 11, 13];\n\n return numbers.filter((number) => primeNumbers.includes(number));\n}", "function luckySevens(num) {\n\n let newArr = [];\n \n for (let i = 1; i < num; i++){\n if (i % 7 === 0) {\n newArr.push(i)\n }\n }\n return newArr;\n }", "function removeNumericStrings(arr) {\n\tvar arrLen = arr.length;\n\tvar nonNumericArr = [];\n\n\tfor (var i=0; i < arrLen; i++) {\n\t\tif (!checkNumeric(arr[i])) {\n\t\t\tnonNumericArr.push(arr[i]);\n\t\t}\n\t}\n\n\treturn nonNumericArr;\n}", "function isPrime(numberArray){\n prime = numberArray.filter((number) => {\n for (var i = 2; i <= number/2; i++) {\n if (number % i === 0) {\n return false;\n }\n }\n return true;\n });\n document.writeln(prime + \"<br>\");\n}", "function missingNum(arr) {\n\tfor (let number=1; number<=10; number++) {\n\t\tif (! arr.includes(number)) return number;\n\t}\n}", "function multiFour(arr){\n \t\treturn arr.filter(a => a%4==0);\n }", "function allEvenNumbersReject(array) {\n\t\n}", "function contains(num, digits) {\n return num.toString().includes(digits)\n}", "function iqTest(numbers) {\n const inputArray = numbers.split(' ');\n const even = [];\n const odd = []\n\n inputArray.map((elm) => elm % 2 == 0 ? even.push(elm) : odd.push(elm));\n\n return inputArray.indexOf(even.length > odd.length ? odd[0] : even[0]) + 1;\n}", "function roboNumbers(number) {\n const numbersArray = [];\n for(let i = 0; i <= number; i++){\n if (checkIfContains3(i)){\n numbersArray.push(\"Won't you be my neighbor?\");\n } else if(checkIfContains2(i)) {\n numbersArray.push(\"Boop!\");\n } else if(checkIfContains1(i)) {\n numbersArray.push(\"Beep!\");\n } else {\n numbersArray.push(i);\n }\n }\n return fixFormatting(numbersArray);\n}", "function retainNumberChars(str) {\n if (_.isString(str)) {\n return Array.prototype.slice.call(str)\n .filter(function (char) {\n // Only keep the chars that are numerical digits\n return char.charCodeAt(0) >= \"0\".charCodeAt(0) && char.charCodeAt(0) <= \"9\".charCodeAt(0);\n })\n .join('');\n }\n\n return str;\n }", "function DigitsInArry (number) \n{ \n let arryOfdigits = [];\n while (number !== 0) \n {\n let units = number % 10;\n arryOfdigits.unshift(units);\n number = Math.floor(number / 10)\n }\n return arryOfdigits;\n}", "function evenDigitsOnly(n) {\n const digits = n.toString().split(\"\");\n // console.log(digits);\n\n return digits.every((dig) => parseInt(dig) % 2 === 0);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create funcion "record" to store to db on pending with readwrite
function saveRecord(record) { const transaction = db.transaction(["pending"], "readwrite"); // object store for pending db data to be accessed const store = transaction.objectStore("pending"); console.log("store") // adds the record with the store store.add(record); }
[ "newRecord() {}", "createRecord(store, type, record) {\n this.logToConsole(OP_CREATE_RECORD, [store, type, record]);\n let data = {};\n let serializer = store.serializerFor(type.modelName);\n serializer.serializeIntoHash(data, type, record, { includeId: true });\n return this.asyncRequest(OP_CREATE_RECORD, type.modelName, null, data);\n }", "function record(type, args){\n var insert_index = history_index;\n\n //when history_length is not zero, enforce ring history\n if(configs.history_length !== 0){\n insert_index = history_index % configs.history_length;\n }\n\n history[insert_index] = {\n type: type\n ,args: args\n };\n\n history_index++;\n }", "function pushToDb() {\n setInterval(function () {\n while(global.instruObj.length){\n // Until the global instruObj is empty, add data to the indexedDb\n let chunks = global.instruObj.splice(0,CHUNCK_LENGTH_TO_DB);\n dbFns.set(shortid.generate(),chunks).then(()=>{\n //console.log(\"Successfully wrote to db\",chunks)\n }).catch((err)=>{\n console.error(\" Error writing to db:\",err)\n });\n }\n },WRITE_TO_DB_INTERVAL)\n}", "function writeLivestockDatabaseAndServer(id, birthday, color, number, place, created, user, tagged, guid) {\n db.transaction(function (transaction) {\n var executeQuery =\n \"INSERT INTO livestock (id, birthday, color, number, place, created, user, tagged, guid) VALUES (?,?,?,?,?,?,?,?,?)\";\n transaction.executeSql(executeQuery, [id, birthday, color, number, place, created, user, tagged, guid],\n function (tx, result) {\n //if data is successfully stored in DB and Networkconnection is valid --> write Data to Server DB\n if (networkConnection == true) {\n RESTAddLivestock(birthday, color, number, place, created, email, guid)\n }\n },\n function (error) {\n alert('Error: ' + error.message + ' code: ' + error.code);\n });\n });\n}", "function recordTableRecords()\n{\n ula.ul.pushOne(CF.mongo.db.colles.table.name,\n {\n // updateTime: new Date().toISOString(),\n updateTime: new Date(),\n // records: _.extend([], tableRecords)\n records: _merge([], tableRecords)\n },\n ()=>{});\n}", "function createCallInfoEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO call_info (patient, assessed, attendant1, attendant1_other, attendant2, attendant2_other, driver, driver_other, ' +\r\n\t\t\t\t' unit_nb, run_nb, respond, milage_start, milage_end, ' + //13\r\n\t\t\t\t' code_en_route, code_return, transported_to, transported_position, time_notified, time_route, time_on_scene, ' + //20\r\n\t\t\t\t' time_depart, time_destination, time_transfer, time_back_service, time_patient_contact, ppe_gloves, ppe_eyes, ppe_reflective, ' +\r\n\t\t\t\t' ppe_isolation, ppe_mask, det1, det2, det3, assistance, other, time)' + //36\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '0', '', '0', '', '', '', '', '', '', '', '',\r\n\t\t\t\t'', '0', '', '', '', '', '', '', '', '', 'negative', //23\r\n\t\t\t\t'negative', 'negative', 'negative', 'negative', '', '0', '', '0', '', getSystemTime()], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}", "static insertDataIDB(tableName, data) {\n\n return DBHelper.openDB().then(function(db) {\n\n let tx = db.transaction(tableName, 'readwrite');\n let store = tx.objectStore(tableName);\n //console.log(store);\n //console.log('Inserting in IDB: ' + data);\n store.put(data);\n\n return tx.complete;\n }).catch((err) => {\n console.log(\"error inserting something into the idb\", err);\n return;\n });\n }", "function addLevelDBData(key, value) {\n //console.log(\"Current key value is \" + key)\n db.put(key, JSON.stringify(value), function(err) {\n if (err) return console.log('Block ' + key + ' submission failed', err);\n });\n}", "addLevelDBData(key, value) {\n let self = this;\n return new Promise(function(resolve, reject) {\n // Add your code here, remember in Promises you need to resolve() or reject()\n // Add to the LevelDB database using the level put() function\n self.db.put(key, value, function(err) {\n if (err) {\n console.log('Block ' + key + ' submission failed', err);\n reject(err);\n }\n resolve(value);\n });\n });\n }", "function doCreateNewRecord() {\n Ext.Ajax.request({\n\t\t\turl: filename,\n\t\t\tmethod: 'GET',\n\t\t\tcallback: function(options, isSuccess, resp) {\n\t\t\t var xml = resp.responseText;\n\t\t\t srchResults = (new DOMParser()).parseFromString(xml, \"text/xml\");\n\t\t\t\tvar currRecord = srchResults.getElementsByTagName('record')[0];\n\t\t\t\tvar recordAsString = (new XMLSerializer().serializeToString(currRecord));\n\t\t\t\tif(bibliosdebug){ console.info('newrecord: got xml: ' + recordAsString);}\n\t\t\t\ttry {\n\t\t\t\tdb.execute('insert into Records (id, xml, status, date_added, date_modified, server, savefile) values (null, ?, ?, date(\"now\", \"localtime\"), date(\"now\", \"localtime\"), ?, null)', [recordAsString, '', 'none']);\n\t\t\t\tif(bibliosdebug == 1 ) {\n\t\t\t\t\tvar title = $('[@tag=\"245\"]/subfield[@code=\"a\"]', srchResults).text();\n\t\t\t\t\tif(bibliosdebug){console.info('inserting record with title: ' + title);}\n\t\t\t\t}\n\t\t\t\t} catch(ex) {\n\t\t\t\tExt.Msg.alert('Error', 'db error: ' + ex.message);\n\t\t\t\t}\n\t\t\t\tvar lastId = getLastRecId();\n\t\t\t\tshowStatusMsg('Opening record...');\n\t\t\t\tvar xml = getLocalXml(lastId);\n\t\t\t\topenRecord(xml);\n\t\t\t\tclearStatusMsg();\n\t\t\t\tcurrOpenRecord = lastId;\n }\n });\n}", "create(cols, value, callBack) {\n orm.insertOne(\"burgers\", cols, value, res => {\n callBack(res);\n });\n }", "static dbget(block) {\n this.dbopen((db) => {\n let tx = db.transaction(\"pending\", \"readonly\");\n let store = tx.objectStore(\"pending\");\n let request = store.get(\"pending\");\n request.onerror = event => console.log(\"no pending data\");\n\n request.onsuccess = event => (\n request.result && request.result.agenda === date ? block(request.result.value) : block({})\n )\n })\n }", "async function Create() {\n const HistoricalQR = await getDB();\n let result = null;\n\n const date = new Date();\n const expireTime = 15;\n\n try {\n result = await new HistoricalQR({\n secret: btoa(\n btoa(date.valueOf()) +\n Math.random() * 555 +\n date.valueOf().toString().substr(0, 5).split('').reverse().join('')\n ),\n created: date.valueOf(),\n expire: new Date(date.getTime() + expireTime * 60000).valueOf(),\n }).save();\n } catch (err) {\n console.log(err);\n }\n\n return result;\n}", "recordTransaction({transaction_arr}) {\n console.log(\"Record transaction for the transaction array : %s\", transaction_arr.toString());\n return knex(\"transactions\").insert(transaction_arr);\n }", "function createFieldDeliveryEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO field_delivery (patient, assessed, presentation, delivery_time, meconium, cord_length, apgar1, apgar5, stimulation, ' +\r\n\t\t\t\t' stimulation_type, placenta, placenta_time, placenta_intact, time )' +\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '', '', '1 Minute', '5 Minutes', 'false', '', 'true', '',\r\n\t\t\t\t'true', getSystemTime()],\r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}", "function storeTrainInfo() {\n database.ref(\"/trainData\").push({\n trainName: trainName\n ,destination: destination\n ,firstTrain: firstTrain\n ,frequency: freq\n })\n}", "function saveData(route, item){\r\n\t\t// save model with \"all\" data\r\n\t\tvar insertData, collection;\r\n\t\tif(monitor[route][item]){\r\n\t\t\tmonitor[route][item](function(err,data){\r\n\t\t\t\tif(err){\r\n\t\t\t\t\tconsole.error(\"err in saveData() : \", data);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcollection = db.collection(route+\"\"+item);\r\n\t\t\t\tinsertData = {};\r\n\t\t\t\t// insertData[item] = {};\r\n\t\t\t\tinsertData[\"data\"] = data.data;\r\n\t\t\t\tinsertData.created_at = Date.now();\r\n\t\t\t\tinsertData.updated_at = Date.now();\r\n\r\n\t\t\t\tcollection.insert(insertData, function(err, docs){\r\n\t\t\t\t\tif(err){\r\n\t\t\t\t\t\tconsole.error(\"err :\", err);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t});\r\n\t\t}\r\n\t}", "function add_medication(db, p_id, med) {\n return new Promise((resolve, reject) => {\n return db.get(p_id)\n .then((doc) => {\n patient = new pmodel.Patient(doc)\n patient.medications.push(med);\n return db.put(patient)\n .then(result => {\n resolve(console.log(result));\n })\n .catch(err => {\n console.log(\"error in addVisitID\", err);\n reject(err);\n });\n })\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter the AMI instances we want.
instanceFilters() { const filters = [ { Name: "instance-state-name", Values: ["running", "stopped"] } ]; return filters; }
[ "function queryBuoyInstances() {\n server.getBuoyInstances().then(function(res) {\n vm.buoyInstances = res.data.buoyInstances;\n formatBuoys();\n }, function(res) {\n gui.alertBadResponse(res);\n });\n }", "async function listInstances() {\n const instancesClient = new compute.InstancesClient();\n\n const [instanceList] = await instancesClient.list({\n project: projectId,\n zone,\n });\n\n console.log(`Instances found in zone ${zone}:`);\n\n for (const instance of instanceList) {\n console.log(` - ${instance.name} (${instance.machineType})`);\n }\n }", "function filterItems() {\n //console.log(inspections)\n return inspections.filter(function(inspection) {\n return inspection.address.toLowerCase().indexOf(search.toLowerCase()) !== -1 || inspection.permit_id.toLowerCase().indexOf(search.toLowerCase()) !== -1\n })\n }", "function filterPersons() {\n const personsFiltered = [];\n for (const person of persons) {\n if (person.id.startsWith(filterIdentifier) || filterIdentifier.startsWith(person.id))\n personsFiltered.push(person);\n }\n persons = personsFiltered;\n}", "function cleanInstances(instances, allowMerge, allowZeroGaps) {\n // if (!allowMerge) throw new Error(`TODO: cleanInstances: allowMerge is temorarily removed`)\n if (allowZeroGaps === void 0) { allowZeroGaps = false; }\n var events = [];\n // let i: number = 1\n _.each(instances, function (instance) {\n // const id = 'i' + (i++)\n events.push({\n time: instance.start,\n value: true,\n data: { instance: instance },\n references: instance.references\n });\n if (instance.end !== null) {\n events.push({\n time: instance.end,\n value: false,\n data: { instance: instance },\n references: instance.references\n });\n }\n });\n return convertEventsToInstances(events, allowMerge, allowZeroGaps);\n}", "static instsOf(name, mode) {\n const insts = isa.query(name);\n return !mode ? insts : insts.filter(function(inst) { return inst.arch === mode; });\n }", "function filterByAgeGroup(response) {\n response['centers'] = response['centers'].filter(center => {\n for (let sessionIndex = 0; sessionIndex < center['sessions'].length; sessionIndex++) {\n if (center['sessions'][sessionIndex].min_age_limit == document.querySelector('#age').value) {\n return center;\n }\n \n }\n })\n return response['centers'];\n }", "filterAll (iterator) {\n return this.getAllModels().filter(iterator)\n }", "function filterPosts(tag) {\n $('#posts-list .post').each(function() {\n var post = $(this);\n var tags = getTags(post);\n if(findOne(tagSearchFilters, tags)) {\n post.show();\n } else {\n post.hide();\n }\n });\n }", "_filterMounts(mounts) {\n const filteredMounts = [\"sys\", \"html5\"];\n this._mounts = [];\n \n for (let mount of mounts) {\n if (filteredMounts.includes(mount.name)) continue;\n \n this._mounts.push(mount);\n }\n }", "resetFilters() {\n this.findAll();\n }", "function filterPhotos(photos,min,max) {\n return photos.filter(function(x) {\n var ratio = x.height_z / x.width_z;\n return ratio > min && ratio < max;\n });\n }", "function idFilter() {\n }", "function filterByDistance() {\r\n //filter by Distance will only show \"pins\" within 1 mile of users location\r\n }", "getFilterEvents() {\n\n let events = this.state.events;\n\n // Include Filtered Events\n if (this.state.filtering) {\n const eventHashes = events.map(function(e) {return e.hash;});\n const isNotCurrentEvent = (e) => eventHashes.indexOf(e.hash) === -1;\n const filteredEvents = this.state.filteredEvents.filter(isNotCurrentEvent);\n events = events.concat(filteredEvents);\n }\n\n // Remove Addressed Events\n const hiddenEvents = this.state.hiddenEvents;\n const hiddenLeads = this.state.hiddenLeads;\n const isNotHiddenEvent = (e) => hiddenEvents.indexOf(e.hash) === -1 && hiddenLeads.indexOf(e.data.lead.id) === -1; \n return events.filter(isNotHiddenEvent);\n }", "function filterDataByRangeAge(minAge, maxAge) {\n emptyUITable();\n let result = originalData.filter(animal => animal.age >= minAge && animal.age <= maxAge);\n displayArray(result);\n }", "function filtro1(){\n $('#foto').html( '<img src=\"'+im+'\" id=\"foto_filtro\"/>');\n Caman('#foto_filtro', function () {\n this.greyscale();\n this.contrast(5);\n this.noise(3);\n this.sepia(100);\n this.channels({red:8,blue:2,green:4});\n this.gamma(0.87);\n this.render();\n });\n}", "apply_filters() {\n return this.data\n .filter(d => this.selected_towns[d.town])\n .filter(d => this.selected_categories[d.object_category])\n .filter(d => d.date_full >= this.selected_start && d.date_full <= this.selected_end);\n }", "renderFilters() {\n console.info('this.props.amenities', this.props.amenities);\n return this.props.amenities.map(filter => (\n <FilterListDetail disabled={false} key={filter.name} filter={filter.name} />\n ));\n }", "filter(items) {\n return items.filter( (item) => {\n return item.getName().toLowerCase().includes(this.filterTemplate);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update resourse list order query from filter
updateResourceOrder(filter) { let orderQuery = `&ordering=${filter}`; if (filter === 'most_likes' || filter === 'most_tried') { orderQuery = `&${filter}=-resource`; } this.setState( { ordering: orderQuery, activeFilter: filter }, this.updateResourceList ); }
[ "refreshData(newSearchTerm, newSortBy, newIsAscending) {\n this.updateDataFilters(newSearchTerm, newSortBy, newIsAscending);\n const { searchTerm, sortBy, isAscending } = this.dataFilters;\n const data = this.state.transactions.filtered(\n 'serialNumber BEGINSWITH[c] $0',\n searchTerm,\n );\n let sortDataType;\n switch (sortBy) {\n case 'serialNumber':\n case 'numberOfItems':\n sortDataType = 'number';\n break;\n default:\n sortDataType = 'realm';\n }\n this.setState({ data: sortDataBy(data, sortBy, sortDataType, isAscending) });\n }", "update_results() {\n this.selected_item = '';\n var obj = this.filters;\n Object.getOwnPropertyNames(obj).forEach(key => {\n this.results = this.results.filter(e => e[key] === obj[key]);\n });\n }", "function updateOrderAndDate() {\n let date = new Date();\n date.setHours(0, 0, 0, 0);\n let lastDate = new Date(playlist[playlist.length - 1]['date']);\n let offset = 1;\n let newList = playlist.slice();\n\n // All dates in playlist already passed\n if (lastDate < date) {\n lastDate = new Date();\n offset = 0;\n }\n\n for (let item of playlist) {\n if (date > new Date(item['date'])) {\n let putLast = newList.splice(0, 1)[0];\n lastDate.setDate(lastDate.getDate() + offset);\n putLast['date'] = lastDate.toISOString().substr(0, 10);\n newList.push(putLast);\n offset++;\n }\n }\n playlist = newList;\n logger.info('Updated date and order');\n}", "function updateRestList() {\n let currRanking = Object.keys(ranking).sort(function(a,b){return ranking[a]-ranking[b]});\n let restListToSend = [];\n for(i= 4; i >= 0; i--) {\n let id = currRanking[i];\n let restaurant = restaurants[id];\n restListToSend.push(restaurant);\n }\n allRests = restListToSend;\n sendRestUpdateMsg(restListToSend);\n}", "function getPersOrderBySearchFilterModel(req, res) {\n persOrdersModel.find({ order_id: req.params.orderId }).exec()\n .then(function(orderStatusList) {\n res.json(orderStatusList);\n })\n .catch(function() {\n console.log(\"Error on retrieving\");\n });\n}", "function updateList(results) {\n var meta = _.get(results, 'meta');\n $log.info('Loaded', (meta.count + meta.offset), '/', meta.total, 'comics which title starts with `' +\n vm.filter + '`');\n // Update list of comics\n vm.comics = meta.offset === 0 ? results : _.unionBy(vm.comics, results, 'id');\n // Update meta\n meta = vm.comics.meta = results.meta;\n // Update boolean to know instantly if there is more\n vm.hasMoreData = meta && (meta.count + meta.offset) < meta.total;\n }", "function reorderFeatureRequestPriority(req_body, cb, next) {\n // get saveing client request priority\n FeatureRequest.find({ client: req_body.client }).exec(function(err, data) {\n if (!err) {\n // get all feature request for same client \n var sameFeaturePriority = data.filter(function(v, i) {\n return v.client_priority === req_body.client_priority;\n });\n // check feature request length\n // on update time don't reorder feature when user has not changed there client priority\n if (sameFeaturePriority.length && (!req_body._id && req_body.client_priority !== sameFeaturePriority[0].client_priority)) {\n // sort feature request by client priority\n var sortedFeaturePriority = data.sort(function(a, b) {\n return a.client_priority - b.client_priority;\n });\n // get indexOf of same feature request by id\n var indexPos = sortedFeaturePriority.map(function(x) {\n return x._id;\n }).indexOf(sameFeaturePriority[0]._id);\n\n // update and reorder all feature request by increasing there client priority \n // compare to current one\n sortedFeaturePriority.slice(Number(indexPos)).forEach(function(priorityReorder, i) {\n priorityReorder.client_priority++;\n priorityReorder.save(function(saveErr, data) {\n if (saveErr) return next(saveErr);\n });\n });\n }\n cb();\n } else {\n return next(err);\n }\n });\n}", "setQueryAndSort(newQuery, newSort) {\n this.setState({\n query: newQuery,\n sort: newSort\n }, function() {\n this.setArticles();\n })\n }", "function sortTable(criteria) {\n const nameFilterValue = getById('filter-bar').value;\n let url;\n if (order === 'asc') {\n order = 'desc';\n } else {\n order = 'asc'\n }\n if (nameFilterValue) {\n url = `${server}?action=sort&criteria=${criteria}&order=${order}&name=${nameFilterValue}`;\n } else {\n url = `${server}?action=sort&criteria=${criteria}&order=${order}`\n }\n fetch(url, {\n headers: {\n 'Accept': 'application/json'\n },\n mode: \"no-cors\"\n })\n .then(r => r.json())\n .then(data => insertNewDataIntoTable(data));\n}", "UPDATE_SORT(store,sort){\n // only update sort store if different sort is selected\n // I noticed clicking on sort buttons multiple times was messing with sort so I added this extra check\n if (store.selectedSort !== sort){\n store.selectedSort = sort\n store.weatherData = sortArray(store.weatherData, store.selectedSort)\n } \n }", "function filterizer (e) {\n setCurrentPage(1)\n let filteredRecipeList = recipes\n for (const [k] of Object.entries(filter)) {\n if(k === \"style\") {filter.style !== \"All\" && (filteredRecipeList = filteredRecipeList.filter(r => r.styles[0].id === parseInt(filter.style)))}\n if(k === \"fermentable\") {filter.fermentable !== \"All\" && (filteredRecipeList = filteredRecipeList.filter(r => r.recipe_fermentables.some(re => re.fermentable_id === parseInt(filter.fermentable))))}\n if(k === \"hop\") {filter.hop !== \"All\" && (filteredRecipeList = filteredRecipeList.filter(r => r.recipe_hops.some(re => re.hop_id === parseInt(filter.hop))))}\n if(k === \"yeast\") {filter.yeast !== \"All\" && (filteredRecipeList = filteredRecipeList.filter(r => r.recipe_yeasts.some(re => re.yeast_id === parseInt(filter.yeast))))} \n }\n switch (e) {\n case \"oldest\":\n const sortedOld = filteredRecipeList.sort((a,b) => Date.parse(a.created_at) - Date.parse(b.created_at))\n setFilteredRecipes(sortedOld)\n setCurrentRecipes(sortedOld.slice(indexOfFirstPost, indexOfLastPost))\n break;\n case \"rated\":\n const sortedRated = filteredRecipeList.sort((a,b) => b.average_rating - a.average_rating) \n setFilteredRecipes(sortedRated)\n setCurrentRecipes(sortedRated.slice(indexOfFirstPost, indexOfLastPost))\n break;\n case \"abv\":\n const sortedAbv = filteredRecipeList.sort((a,b) => b.abv - a.abv) \n setFilteredRecipes(sortedAbv)\n setCurrentRecipes(sortedAbv.slice(indexOfFirstPost, indexOfLastPost))\n break;\n case \"recent\":\n const sortedRecent = filteredRecipeList.sort((a,b) => Date.parse(b.created_at) - Date.parse(a.created_at))\n setFilteredRecipes(sortedRecent)\n setCurrentRecipes(sortedRecent.slice(indexOfFirstPost, indexOfLastPost))\n break;\n default:\n break;\n }\n setTimeout(() => {\n \n }, 500);\n }", "addFilterToQuery(filter) {\n const query = {};\n if (filter.mode === 'exactly' && !filter.value) {\n query[this.paths.first] = query[this.paths.last] = filter.inverted ? { $nin: ['', null] } : { $in: ['', null] };\n return query;\n }\n let value = utils.escapeRegExp(filter.value);\n if (filter.mode === 'beginsWith') {\n value = '^' + value;\n }\n else if (filter.mode === 'endsWith') {\n value = value + '$';\n }\n else if (filter.mode === 'exactly') {\n value = '^' + value + '$';\n }\n value = new RegExp(value, filter.caseSensitive ? '' : 'i');\n if (filter.inverted) {\n query[this.paths.first] = query[this.paths.last] = { $not: value };\n }\n else {\n const first = {};\n first[this.paths.first] = value;\n const last = {};\n last[this.paths.last] = value;\n query.$or = [first, last];\n }\n return query;\n }", "function reportActivity() {\n console.log(\"The sort order has changed\");\n\n document.querySelectorAll(\".sortOption\").forEach((el, index) => {\n $(el)\n .parents(\"div.input-group\")\n .find(\"div input\")\n .val(index + 1);\n $(el)\n .parents(\"div.input-group\")\n .find(\"div span\")\n .html(index + 1);\n });\n }", "function search(term, order){\n\t\n\t// If the current order is ascending then it should be changed to descending.\n\tif(order == \"ASC\"){\n\t\torder = \"DESC\";\n\t}\n\t// If the current order is descending then it should be changed to ascending.\n\telse{\n\t\torder = \"ASC\";\n\t}\n\t\n\t// This obtains the current web address.\n\tcurrentURL = document.URL;\n\t\n\t// This gets the address up to but not including sortTerm (and sortOrder which follows afterward). \n\tcutoff = currentURL.indexOf(\"&sortTerm=\");\n\t\n\t// This changes the address to include the new sortTerm and new sortOrder.\n\tnewURL = currentURL.slice(0, cutoff) + \"&sortTerm=\" + term + \"&sortOrder=\" + order;\n\t\n\t// This changes the current web address to the newly defined address.\n\twindow.location.href = newURL;\n\t\n\treturn true;\n}", "function updateFromFilters(){\n\n //$(\"input\").prop('disabled', true);\n\n var newList = _(elements)\n .forEach(function(d){ map.removeLayer(d.marker) })\n .filter(computeFilter)\n .forEach(function(d){ d.marker.addTo(map) })\n .value();\n\n updateList(newList);\n updateFromMap();\n }", "function getTempForUnAssignedOpportunitySort(oppresp)\n{\n \n\nvar tempArrayOpp=[];\n//From the response we fill filter json array .Beacause for sort we need data in array.\n//tempArray is the array [json array]\nfor(var i=0;i<oppresp.taskList.length;i++)\n{\n\n tempArrayOpp.push(oppresp.taskList[i].TasksDTO);\n\n}\n \n tempArrayOpp.sort(custom_sort);\n//console.log(JSON.stringify(tempArrayOpp));\n\n//once we get sorted array we need to make the sorted response in json format.Below steps are done for the same\nvar sortedresp={};\nsortedresp.taskList=[];\nfor(var j=0;j<tempArrayOpp.length;j++)\n{\n var testobj={\"Request\":tempArrayOpp[j]};\n sortedresp.taskList.push(testobj);\n}\n//sortedresp is the final sorted json response\n//alert(JSON.stringify(sortedresp));\n gblTaskResponse =sortedresp;\n}", "updateQuery(query) {\n this.setState(() => ({\n cursor: null\n }));\n this.props.queryFilter(query.trim());\n }", "reArrangeForAdmin(messages, meta) {\n const _sort = (a, b) => (b.id < a.id ? -1 : 1);\n const { location, putMessagesInRedux } = this.props;\n const { state } = location || {};\n const ids = (state && state.ids) || [];\n const result = separate(ids, messages);\n const { notFound, itemObjects, remainder } = result;\n var data = [...itemObjects, ...remainder];\n data.sort(_sort);\n\n putMessagesInRedux(data);\n if (!notFound.length) return; // If all items are found locally, dont go to the B.E\n\n apiCall(\"/messages.listForCommunityAdmin\", {\n message_ids: notFound,\n }).then((response) => {\n if (response.success) data = [...response.data, ...data];\n //-- Messages that were not found, have now been loaded from the B.E!\n data.sort(_sort);\n putMessagesInRedux(data);\n });\n }", "function updateSortedRows(){\r\n\t\tvar $allRows = $(\".newRow\");\r\n\t\tlocalStorage.setItem(\"storedData\", JSON.stringify($storedData));\r\n\t\t$allRows.each(function(i,el){\r\n\t\t\t$(el).children().slice(0,2).empty();\r\n\t\t\t$(el).children().eq(0).text($storedData[i].show);\r\n\t\t \t$(el).children().eq(1).text($storedData[i].rating);\r\n\t\t});\r\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the active crown fire spread rate at head [Ractive] (ft+1 min1) given the corresponding standard fuel model 10 spread rate at head. This is the crown fire spread rate per Rothermel (1991), and which Scott & Reinhardt term `Ractive`
function rActive (fm10ros) { return 3.34 * fm10ros }
[ "function backingSpreadRate (rosHead, eccent) {\n return rosHead * divide(1 - eccent, 1 + eccent)\n}", "function betaSpreadRate (betaHead, rosHead, eccent) {\n let rosBeta = rosHead // Calculate the fire spread rate in this azimuth\n // if it deviates more than a tenth degree from the maximum azimuth\n\n if (Math.abs(betaHead) > 0) {\n const rad = radians(betaHead)\n rosBeta = rosHead * (1 - eccent) / (1 - eccent * Math.cos(rad))\n }\n\n return rosBeta\n}", "function radiatorEffect(getState, ms_since_update) {\n if (getState().radiator.on) {\n\n var btus = getState().radiator.BTUs;\n var mass = massOfAirInBuilding(getState().building);\n var capacity = /* approx. heat capacity of air, kcal/C */ 0.239\n\n return degreesFChangeOverInterval(btus, ms_since_update, mass, capacity);\n\n } else {\n return 0;\n }\n\n}", "function fuelRequired(crewArray){\n let massOfCrew = crewMass(crewArray);\n let fuel = (75000+massOfCrew)*9.5;\n for (i=0; i<crewArray.length; i++){\n if (crewArray[i].species === 'dog' || crewArray[i].species === 'cat'){\n fuel += 200;\n } else {\n fuel += 100;\n }\n }\n return Math.ceil(fuel);\n }", "function powerOfTheWind (wspd20, rActive) {\n // Difference must be in ft+1 s-1\n const diff = positive((wspd20 - rActive) / 60)\n return 0.00106 * diff * diff * diff\n}", "updateThrust() {\n this._thrust = this.fuel * 0.04;\n }", "crotonWeight(state) {\n var crotonWeight = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n var weight = state.recordsList[i].weight;\n crotonWeight += weight;\n }\n }\n return crotonWeight;\n }", "function openWindSpeedAdjustmentFactor (fuelDepth) {\n const f = Math.min(6, Math.max(fuelDepth, 0.1))\n return 1.83 / Math.log((20 + 0.36 * f) / (0.13 * f))\n}", "function caloriesBurned() {\n let calburnt = 0;\n var currentUser = JSON.parse(localStorage.getItem(\"userProfile\"));\n calburnt =\n (currentUser.weight / 2.205) *\n getmetValues(workoutType) *\n 0.0175 *\n parseInt(workoutLength);\n return Math.floor(calburnt);\n}", "function crowningIndex (oActive) {\n return oActive / 54.680665 // CI in km/h\n}", "function powerOfTheFire (fliActive) {\n return fliActive / 129\n}", "get railScore() {\n var comfort = this.normalizedUserComfort;\n var efficiency = this.normalizedEfficiency;\n return weightedAverage2(comfort, efficiency, COMFORT_IMPORTANCE);\n }", "function maximumSpreadRate (ros0, phiEw) {\n return ros0 * (1 + phiEw)\n}", "function mrt_delta_from_erf(erf, fract_efficiency=0.725, rad_trans_coeff=6.012){\n return erf / (fract_efficiency * rad_trans_coeff)\n}", "function calc_solar_lum(R, T) {\n return calc_lum(R / 1000, T) / SOLAR_LUMINOSITY;\n}", "function erf_from_body_solar_flux(solar_flux, body_absorptivity=0.7, body_emissivity=0.95){\n return solar_flux * (body_absorptivity / body_emissivity)\n}", "calculate(initialAmount) {\n let total = 0.0;\n let options = {\n initialAmount: initialAmount, // initial amount assigned\n daysRented: this._rental.getDaysRented(), // get number of days the car rented\n mileage: this._rental.getMileage() // get mileage\n };\n //calculate default car rental according to its type\n total = this._rental._vehicle.calculateRentalFees(options);\n\n // apply mileage rule\n total = this._applyMileAgeRule(total);\n\n //apply late rule\n total = this._applyLateRule(total);\n\n this._rental.assignRentalFees(total);\n\n return total;\n }", "function calcShockRatios(gam,mach) {\n\tvar stemp = 0;\n\tvar sdens = 0;\n\tvar spress = 0;\n\tstemp = calcShockTemperature(gam,mach,1.0);\n\tsdens = calcShockDensity(gam,mach,1.0);\n\tspress = calcShockPressure(gam,mach,1.0);\n\treturn [stemp,sdens,spress];\n}", "drive(miles) {\n let gallonsConsumed = miles/this.mpg\n let milesMax = this.gasTankCapacity * this.mpg\n\n this.fuelLevel = this.fuelLevel - gallonsConsumed\n if(this.fuelLevel < 0) { //can't drive more miles than available fuel\n this.fuelLevel = 0\n }\n\n if(miles > milesMax) {\n this.odometer = this.odometer + milesMax\n } else {\n this.odometer = this.odometer + miles\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Title: drawSymbol Arguments: ctx Canvas element symbol Character to draw fc offset cx x coordinate cy y coordinate ch Character size Purpose: Draws a specific symbol
function drawSymbol( ctx, symbol, fc, cx, cy, cw, ch ) { ctx.beginPath(); switch ( symbol ) { case "0": ctx.moveTo(cx+fc,cy+(ch*0.333333)); ctx.arc(cx+(cw/2),cy+(cw/2),(cw/2)-fc,deg2rad(180),0, false); ctx.arc(cx+(cw/2),(cy+ch)-(cw/2),(cw/2)-fc,0,deg2rad(180), false); ctx.closePath(); break; case "1": ctx.moveTo(cx+(cw*0.1)+fc,cy+ch-fc); ctx.lineTo(cx+cw-fc,cy+ch-fc); ctx.moveTo(cx+(cw*0.666666),cy+ch-fc); ctx.lineTo(cx+(cw*0.666666),cy+fc); ctx.lineTo(cx+(cw*0.25),cy+(ch*0.25)); break; case "2": ctx.moveTo(cx+cw-fc,cy+(ch*0.8)); ctx.lineTo(cx+cw-fc,cy+ch-fc); ctx.lineTo(cx+fc,cy+ch-fc); ctx.arc(cx+(cw/2),cy+(cw*0.425),(cw*0.425)-fc,deg2rad(45),deg2rad(-180), true); break; case "3": ctx.moveTo(cx+(cw*0.1)+fc,cy+fc); ctx.lineTo(cx+(cw*0.9)-fc,cy+fc); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(-90),deg2rad(180), false); break; case "4": ctx.moveTo(cx+(cw*0.75),cy+ch-fc); ctx.lineTo(cx+(cw*0.75),cy+fc); ctx.moveTo(cx+cw-fc,cy+(ch*0.666666)); ctx.lineTo(cx+fc,cy+(ch*0.666666)); ctx.lineTo(cx+(cw*0.75),cy+fc); ctx.moveTo(cx+cw-fc,cy+ch-fc); ctx.lineTo(cx+(cw*0.5),cy+ch-fc); break; case "5": ctx.moveTo(cx+(cw*0.9)-fc,cy+fc); ctx.lineTo(cx+(cw*0.1)+fc,cy+fc); ctx.lineTo(cx+(cw*0.1)+fc,cy+(ch*0.333333)); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(-80),deg2rad(180), false); break; case "6": ctx.moveTo(cx+fc,cy+ch-(cw*0.5)-fc); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(-180),deg2rad(180), false); ctx.bezierCurveTo(cx+fc,cy+fc,cx+fc,cy+fc,cx+(cw*0.9)-fc,cy+fc); ctx.moveTo(cx+(cw*0.9)-fc,cy+fc); break; case "7": ctx.moveTo(cx+(cw*0.5),cy+ch-fc); ctx.lineTo(cx+cw-fc,cy+fc); ctx.lineTo(cx+(cw*0.1)+fc,cy+fc); ctx.lineTo(cx+(cw*0.1)+fc,cy+(ch*0.25)-fc); break; case "8": ctx.moveTo(cx+(cw*0.92)-fc,cy+(cw*0.59)); ctx.arc(cx+(cw/2),cy+(cw*0.45),(cw*0.45)-fc,deg2rad(25),deg2rad(-205), true); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(-135),deg2rad(-45), true); ctx.closePath(); ctx.moveTo(cx+(cw*0.79),cy+(ch*0.47)); ctx.lineTo(cx+(cw*0.21),cy+(ch*0.47)); break; case "9": ctx.moveTo(cx+cw-fc,cy+(cw*0.5)); ctx.arc(cx+(cw/2),cy+(cw*0.5),(cw*0.5)-fc,deg2rad(0),deg2rad(360), false); ctx.bezierCurveTo(cx+cw-fc,cy+ch-fc,cx+cw-fc,cy+ch-fc,cx+(cw*0.1)+fc,cy+ch-fc); break; case "%": ctx.moveTo(cx+fc,cy+(ch*0.75)); ctx.lineTo(cx+cw-fc,cy+(ch*0.25)); ctx.moveTo(cx+(cw*0.505),cy+(cw*0.3)); ctx.arc(cx+(cw*0.3),cy+(cw*0.3),(cw*0.3)-fc,deg2rad(0),deg2rad(360), false); ctx.moveTo(cx+(cw*0.905),cy+ch-(cw*0.3)); ctx.arc(cx+(cw*0.7),cy+ch-(cw*0.3),(cw*0.3)-fc,deg2rad(0),deg2rad(360), false); break; case ".": ctx.moveTo(cx+(cw*0.25),cy+ch-fc-fc); ctx.arc(cx+(cw*0.25),cy+ch-fc-fc,fc,deg2rad(0),deg2rad(360), false); ctx.closePath(); break; case "M": ctx.moveTo(cx+(cw*0.083),cy+ch-fc); ctx.lineTo(cx+(cw*0.083),cy+fc); ctx.moveTo(cx+(cw*0.083),cy+fc); ctx.lineTo(cx+(cw*0.4167),cy+ch-fc); ctx.moveTo(cx+(cw*0.4167),cy+ch-fc); ctx.lineTo(cx+(cw*0.75),cy+fc); ctx.moveTo(cx+(cw*0.75),cy+ch-fc); ctx.lineTo(cx+(cw*0.75),cy+fc); break; case "G": ctx.moveTo(cx+fc,cy+(ch*0.333333)); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(180),deg2rad(-15), true); ctx.moveTo(cx+fc,cy+(ch*0.333333)); ctx.bezierCurveTo(cx+fc,cy+fc,cx+fc,cy+fc,cx+(cw*0.9)-fc,cy+fc); ctx.moveTo(cx+(cw*1.00),cy+(ch*0.5)); ctx.lineTo(cx+(cw*0.60),cy+(ch*0.5)); break; case "b": ctx.moveTo(cx+fc,cy+ch-(cw*0.5)-fc); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(-180),deg2rad(180), false); ctx.bezierCurveTo(cx+fc,cy+fc,cx+fc,cy+fc,cx+(cw*0.2)-fc,cy+fc); ctx.moveTo(cx+(cw*0.9)-fc,cy+fc); break; case "B": ctx.moveTo(cx+(cw*0.92)-fc,cy+(cw*0.59)); ctx.arc(cx+(cw/2),cy+(cw*0.45),(cw*0.45)-fc,deg2rad(25),deg2rad(-165), true); ctx.arc(cx+(cw/2),cy+ch-(cw*0.5),(cw*0.5)-fc,deg2rad(-215),deg2rad(-45), true); ctx.closePath(); ctx.moveTo(cx+(cw*0.79),cy+(ch*0.47)); ctx.lineTo(cx+(cw*0.21),cy+(ch*0.47)); break; default: break; } ctx.stroke(); }
[ "function drawSymbol(p2, dist, dip, dipaz)\n{\n\n\t//draw the point with dip/dip azimuth\n\tvar dipF = Math.floor(dip);\n\tvar dipAzF = Math.floor(dipaz);\n\n\tdipF = dipF.toString();\n\tdipAzF = dipAzF.toString();\n\n\tif(dipF.length == 1)\n\t{\n\t\tdipF = \"0\" + dipF.toString();\t\n\t}\n\tif(dipAzF.length == 2)\n\t{\n\t\tdipAzF = \"0\" + dipAzF.toString();\t\n\t}\n\tif(dipAzF.length == 1)\n\t{\n\t\tdipAzF = \"00\" + dipAzF.toString();\t\n\t}\n\n\t//console.log(dipF.length);\n\tplotPoint(\"\" + dipF + \"/\" + dipAzF, p2[0], p2[1]);\n\n\t//Get the selected option from the dropdown\n\tsymbolCount++;\n\tvar option = ($(\"#sel\")[0].selectedOptions); \n\n\n\t// Placemark\n\tvar placemark = ge.createPlacemark(option.item(0).value + \"\" + symbolCount);\n\tplacemark.setName(option.item(0).value + \"\" + symbolCount);\n\n\n\n\t// Placemark/Model (geometry)\n\tvar model = ge.createModel('');\n\tplacemark.setGeometry(model);\n\n\t// Placemark/Model/Link\n\tvar link = ge.createLink('');\n\tlink.setHref('https://dl.dropboxusercontent.com/u/89445333/GEsymbols/' + option.item(0).value + '.dae');\n\tmodel.setLink(link);\n\n\t// Placemark/Model/Location\n\tvar loc = ge.createLocation('');\n\tloc.setLatitude(p2[0]);\n\tloc.setLongitude(p2[1]);\n\n\tmodel.setLocation(loc);\n\n\tvar scale = ge.createScale('');\n\tvar orient = ge.createOrientation('');\n\n\t//If the symbol is a circle we need to set some extra options\n\tif(option.item(0).value == \"5-m-Wcircle\" || option.item(0).value == \"5-m-Bcircle\" || option.item(0).value == \"5-m-Pcircle\" || option.item(0).value == \"5-m-Ocircle\" \n\t|| option.item(0).value == \"5-m-LBcircle\" || option.item(0).value == \"5-m-Gcircle\" || option.item(0).value == \"5-m-BLcircle\")\n\t{\n\t\torient.set(dipaz, dip, 0);\n\t\tmodel.setOrientation(orient);\n\t\t//console.log($('#scalex').val().length);\n\t\tif($('#scalex').val().length < 1 || $('#scaley').val().length < 1)\n\t\t{\n\t\t\tscale.set(dist/5 , dist/5, 1.0);\n\n\t\t}\n\t\telse scale.set(Number($('#scalex').val())/10 ,Number($('#scaley').val())/10, 1.0);\n\t}\n\telse\n\t{\n\t\torient.set(dipaz, 0, 0);\n\t\tmodel.setOrientation(orient);\n\t\tscale.set(dist/5 , dist/5, 1.0);\n\t\t//loc.setAltitude(p2[2] + 1000);//Trying to fix the altitude, doesn't seem to do anything.\n\t}\n\n\tmodel.setScale(scale);\n\n\t// add the model placemark to Earth and the model folder\n\tmodelFolder.getFeatures().appendChild(placemark);\n\tge.getFeatures().appendChild(modelFolder);\n}", "function drawChar(line, col, ch) {\r\n if (line < 0 || line >= LINES || col < 0 || col >= COLUMNS)\r\n return;\r\n //\r\n // attributes\r\n const a = line * COLUMNS + col\r\n const attr = makeAttribute(my.ink, my.paper)\r\n displayColours[a] = attr\r\n //\r\n // index of the first byte of the character in the character set\r\n const chAt = (ch.charCodeAt(0) - 0x20) * CHARSIZE\r\n //\r\n // copy pixel data\r\n for (let i = 0; i < CHARSIZE; i++) {\r\n const at = (line * CHARSIZE + i) * COLUMNS + col\r\n displayPixels[at] = CHARSET[chAt + i]\r\n }\r\n}", "function drawX() {\n box.style.backgroundColor = '#fb5181'\n ctx.beginPath()\n ctx.moveTo(15, 15)\n ctx.lineTo(85, 85)\n ctx.moveTo(85, 15)\n ctx.lineTo(15, 85)\n ctx.lineWidth = 21\n ctx.lineCap = \"round\"\n ctx.strokeStyle = 'white'\n ctx.stroke()\n ctx.closePath()\n\n symbol[num - 1] = human\n }", "RenderChar(draw_list, size, pos, col, c) {\r\n this.native.RenderChar(draw_list.native, size, pos, col, c);\r\n }", "drawCircle(cx, cy, radius, name, color, just_fill) {\n // this.ctx.beginPath();\n var previous = this.ctx.fillStyle;\n this.ctx.moveTo(cx + radius, cy);\n this.ctx.fillStyle = color;\n this.ctx.beginPath();\n this.ctx.arc(cx, cy, radius, 0, 2*Math.PI);\n this.ctx.closePath();\n this.ctx.fill();\n this.ctx.fillStyle = previous;\n this.ctx.fillText(name, cx, cy+7);\n if (!just_fill) {\n this.ctx.stroke();\n }\n // this.ctx.closePath();\n }", "function draw_cir(x,y,color,size){\n ctxMap.fillStyle=color;\n ctxMap.beginPath();\n ctxMap.moveTo(x, y);\n ctxMap.lineTo(x+size,y);\n ctxMap.lineTo(x+size,y+size);\n ctxMap.lineTo(x,y+size);\n ctxMap.lineTo(x,y);\n ctxMap.closePath();\n ctxMap.fill();\n\n}", "ctxDrawText (ctx, string, x, y, cssColor) {\n this.setIdentity(ctx)\n ctx.fillStyle = cssColor\n ctx.fillText(string, x, y)\n ctx.restore()\n }", "function drawCharset() {\r\n let chars = \"\"\r\n for (let ch = 0x20; ch <= 0x7F; ch++)\r\n chars += String.fromCharCode(ch)\r\n drawText(21, 0, chars)\r\n}", "key(x, y, squareSize, font) {\n this.ctx.font = font;\n for (let i = 0; i < this.data.length; i++) {\n this.ctx.fillStyle = this.data[i].color;\n this.ctx.textBaseline = \"top\";\n this.ctx.textAlign = \"left\";\n this.ctx.fillRect(x, y + i * squareSize * 1.5, squareSize, squareSize);\n this.ctx.fillText(`${this.data[i].label}, ${this.data[i].unit}`, x + squareSize * 1.5, y + squareSize * i * 1.5);\n }\n }", "function canvas_set_font(ctx, size, monospaced) {\n var s = window.getComputedStyle(onscreen_canvas);\n // First set something that we're certain will work. Constructing\n // the font string from the computed style is a bit fragile, so\n // this acts as a fallback.\n ctx.font = `${size}px ` + (monospaced ? \"monospace\" : \"sans-serif\");\n // In CSS Fonts Module Level 4, \"font-stretch\" gets serialised as\n // a percentage, which can't be used in\n // CanvasRenderingContext2d.font, so we omit it.\n ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` +\n (monospaced ? \"monospace\" : s.fontFamily);\n}", "function animateSymbol(s) {\n // create a white outline and explode it\n var c = map.paper.circle().attr(s.path.attrs);\n c.insertBefore(s.path);\n c.attr({ fill: false });\n c.animate({ r: c.attrs.r * 3, 'stroke-width': 7, opacity: 0 }, 2500,\n 'linear', function () { c.remove(); });\n // ..and pop the bubble itself\n var col = s.path.attrs.fill,\n rad = s.path.attrs.r;\n s.path.show();\n s.path.attr({ fill: symbolAnimateFill, r: 0.1, opacity: 1 });\n s.path.animate({ fill: col, r: rad }, 700, 'bounce');\n\n }", "function printCreek(x, y, color) {\n if(!color)\n color =\"#FF0000\"\n printCircle(x, y, tile_size/2, color);\n}", "function givePlayerSymbol(){\r\n\tif (player){\r\n\t\treturn \"X\";\r\n\t}else {\r\n\t\treturn \"O\";\r\n\t}\r\n\r\n}", "function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}", "draw () {\r\n this.icon.x = this.x\r\n this.icon.y = this.y\r\n const canvas = document.getElementById('editor')\r\n const ctx = canvas.getContext('2d')\r\n const button = new Path2D()\r\n // ctx.moveTo(this.x,this.y)\r\n button.moveTo(this.x, this.y + 10)\r\n button.lineTo(this.x, this.y + this.size - 10)\r\n button.quadraticCurveTo(this.x, this.y + this.size, this.x + 10, this.y + this.size)\r\n button.lineTo(this.x + this.size - 10, this.y + this.size)\r\n button.quadraticCurveTo(this.x + this.size, this.y + this.size, this.x + this.size, this.y + this.size - 10)\r\n button.lineTo(this.x + this.size, this.y + 10)\r\n button.quadraticCurveTo(this.x + this.size, this.y, this.x + this.size - 10, this.y)\r\n button.lineTo(this.x + 10, this.y)\r\n button.quadraticCurveTo(this.x, this.y, this.x, this.y + 10)\r\n if (this.ischosen !== true) {\r\n ctx.fillstyle = this.chosen()\r\n ctx.fill(button)\r\n ctx.save()\r\n ctx.translate(3, 3)\r\n const shadow = new Path2D(button)\r\n ctx.fillStyle = '#1d232f'\r\n ctx.fill(shadow)\r\n ctx.restore()\r\n ctx.fillStyle = this.chosen()\r\n ctx.fill(button)\r\n this.icon.draw()\r\n } else {\r\n ctx.save()\r\n ctx.translate(2, 2)\r\n ctx.fillStyle = this.chosen()\r\n ctx.fill(button)\r\n this.icon.draw()\r\n ctx.restore()\r\n }\r\n }", "function drawControl_SS(ypos_in)\r\n{\r\n // draw the rectangle outline to stand out\r\n Hcontext.fillStyle = 'rgb(255,255,255)';\r\n //Hcontext.lineWidth = 12;\r\n Hcontext.fillRect(control_margin,ypos_in-320+326,button_width,65*4+33);\r\n \r\n // set up fonts\r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = 'bold ' + (40.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'center';\r\n // draw the main text\r\n Hcontext.fillText (\"Touch the\" , control_margin+(control_width-control_margin-2)/2, ypos_in-335+390);\r\n Hcontext.fillText (\"Screen to\" , control_margin+(control_width-control_margin-2)/2, ypos_in-335+455);\r\n Hcontext.fillText (\"Explore the\" , control_margin+(control_width-control_margin-2)/2, ypos_in+520-335);\r\n Hcontext.fillText (\"Tree of Life\" , control_margin+(control_width-control_margin-2)/2, ypos_in+585-335);\r\n \r\n \r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = (18.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'left';\r\n \r\n skipper = 22\r\n \r\n \r\n header_ypos = myHeader.height-450;\r\n \r\n \r\n temp_txt = [\" \",\r\n \"Each leaf respresents a species.\",\r\n \"Branches show evolutionary\",\r\n \"links between these species,\",\r\n \"connecting them to common\",\r\n \"ancestors. The colours\",\r\n \"show extinction risk.\",\r\n \" \",\r\n \"Pinch two fingers together\",\r\n \"or apart on the screen to\",\r\n \"zoom in and out and explore\",\r\n \"the tree like you would a map.\",\r\n \"You can also tap areas of\",\r\n \"the screen to zoom in there.\",\r\n \" \",\r\n \"For more information press\",\r\n \"the 'Introduction' button.\",\r\n \"Or just start exploring\",\r\n \"and experiment with the\",\r\n \"other buttons above.\"];\r\n \r\n \r\n for (var iii = 0 ; iii < temp_txt.length ; iii ++)\r\n {\r\n //Hcontext.fillText (temp_txt[iii] , control_margin+(control_width-control_margin-2)/2, header_ypos+skipper*iii);\r\n Hcontext.fillText (temp_txt[iii] , control_margin, header_ypos+skipper*iii);\r\n }\r\n \r\n \r\n \r\n \r\n}", "function Smiley(size, linePixelColor, fillPixelColor) {\n // TODO: Solve your exercise here\n}", "function getPieceSymbol(coloredPiece, pieceStyle) {\n\t\tswitch(pieceStyle) {\n\t\t\tcase 'figurine':\n\t\t\t\treturn bt$3.figurineToString(coloredPiece);\n\t\t\tcase 'standard':\n\t\t\tdefault:\n\t\t\t\treturn bt$3.pieceToString(Math.floor(coloredPiece / 2)).toUpperCase();\n\t\t}\n\t}", "function draw_help() {\n ctx.font = 'bold 1em sans-serif';\n ctx.globalAlpha = 0.5;\n ctx.fillText('esc to exit', canvas.width/dpi - 13, 20);\n ctx.fillText('up/down arrows change speed', canvas.width/dpi - 13, 40);\n ctx.fillText('left/right arrows change spread', canvas.width/dpi - 13, 60);\n ctx.fillText('scroll to scrub through time', canvas.width/dpi - 13, 80);\n ctx.fillText('mouse to move camera', canvas.width/dpi - 13, 100);\n ctx.fillText('space to pause', canvas.width/dpi - 13, 120);\n ctx.textAlign = \"left\";\n}", "function drawPt(x, y, color,isFill,radius) {\n \n\tctx.fillStyle = color;\n ctx.beginPath();\n \n\tctx.arc(x, y, radius, 0, 2*Math.PI);\n ctx.closePath();\n ctx.stroke();\n if(isFill)\n {\n \tctx.fill();\n }\n ctx.fillStyle = \"black\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a DAQ changes out, there signals that disappear and get recreated. Technically they're not the same as previous. However, sometimes it makes sense to reattach plotted signals to underlying signal objects by using the referenced name.
rectifySignalReferencesByName(){ this.plottedSignalsMap.forEach((ps, sigName) => { var newSig = this.signalFromNameCallback(sigName); if(newSig != null){ ps.signal = newSig; } }); }
[ "signal() {\n const active = this.combiner.shouldBeActive(this.emitters);\n this._setIsActive(active);\n }", "function optionChanged(subjectid) {\n barPlot(subjectid);\n bubblePlot(subjectid);\n updateinfo(subjectid);\n gaugeplot(subjectid);\n \n}", "swapChart() {\n swapElements(this.data_plot, this.simulator);\n\n if(!this.canvas_in_leftbar) {\n this.data_plot.classList.add('visable');\n this.canvas.elt.classList.remove('visable');\n } else {\n this.data_plot.classList.remove('visable');\n this.canvas.elt.classList.add('visable');\n }\n\n this.canvas_size_multiple = (this.canvas_in_leftbar) ? 0.65 : 0.35;\n this.canvas_in_leftbar = !this.canvas_in_leftbar;\n\n this.sim.resize();\n\n if (helpPage.style.display != 'none') {\n help.clear();\n help.initialize();\n help.resize();\n }\n }", "restore() {\n this.emit(\"addDependencies\", Object.keys(this.componentPathsByDependentAssetId));\n }", "function updateTillNow() {\r\n\tfor(var j = 0; j < activeGraphs.length; j++) {\r\n\t\tif(activeGraphs[j].keepUpdated) {\r\n\t\t\tactiveGraphs[j].canvas.data.datasets = [];\r\n\t\t\tactiveGraphs[j].canvas.update();\r\n\r\n\t\t\tfor(var i = 0; i < activeGraphs[j].graphs.length; i++) {\r\n\t\t\t\tpushGraphData(activeGraphs[j].id, i)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function NameChanged()\n\t\t{\n\t\t\tnameChanged = 1;\n\t\t}", "static of (a) {\n return new Signal(emit => {\n emit.next(a)\n emit.complete()\n })\n }", "subscription() {\n const currState = this.store.getState();\n const schema = _store.getIfChanged(\"schema\");\n if (schema) {\n this.visualization1.setSchema(JSON.parse(schema));\n this.visualization2.setSchema(JSON.parse(schema));\n }\n this.visualization1.setViewOptions({\n ...currState\n });\n this.visualization2.setViewOptions({\n ...currState\n });\n }", "removeAll(signal) {\n delete this._events[signal];\n }", "removePlot(symbol) {\n if (this.data.hasOwnProperty(symbol)) {\n this.g.select('.plot-line-' + symbol)\n .remove();\n\n this.g.selectAll('.price-point-' + symbol)\n .remove();\n\n // Finally, add the used color back, and remove symbol data\n var color = this.data[symbol].color;\n this.colors.push(color);\n delete this.data[symbol];\n\n // Scale y-values with existing plots\n this.minY = this.ctrl.getGlobalMinY(this.data);\n this.maxY = this.ctrl.getGlobalMaxY(this.data);\n\n this.rescaleY(this.minY, this.maxY, true);\n\n var symbols = Object.keys(this.data);\n symbols.forEach( (sym) => {\n if (sym !== symbol) {\n this.redrawPlot(sym);\n }\n });\n\n }\n else {\n console.error('No symbol. Cannot remove ' + symbol);\n }\n\n }", "dirty() {\n this.signal();\n }", "function updateSelectorSvg() {\n const currentDateIndex = getCurrentDateIndex() - 1;\n miniSvg.selectAll('.date-bar').attr('fill', '#dee2e6');\n miniSvg.selectAll('.date-bar-alt').attr('fill', '#343a40');\n miniSvg.select(`#date-bar-${currentDateIndex}`).attr('fill', '#007bff')\n miniSvg.select(`#date-bar-alt-${currentDateIndex}`).attr('fill', '#515961')\n}", "function removeAmChart(id) {\n var tmp_am = getAmChart(id);\n if(tmp_am){\n tmp_am.clear();\n }\n}", "function optionChanged(industry_name) {\n build_industry_dynamic_plot(industry_name);\n get_industry_name(industry_name);\n}", "get __seriesEventNames() {\n return {\n /**\n * Fired when the series has finished its initial animation.\n * @event series-after-animate\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n afterAnimate: 'series-after-animate',\n\n /**\n * Fired when the checkbox next to the series' name in the legend is clicked.\n * @event series-checkbox-click\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n checkboxClick: 'series-checkbox-click',\n\n /**\n * Fired when the series is clicked.\n * @event series-click\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n click: 'series-click',\n\n /**\n * Fired when the series is hidden after chart generation time.\n * @event series-hide\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n hide: 'series-hide',\n\n /**\n * Fired when the legend item belonging to the series is clicked.\n * @event series-legend-item-click\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n legendItemClick: 'series-legend-item-click',\n\n /**\n * Fired when the mouses leave the graph.\n * @event series-mouse-out\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n mouseOut: 'series-mouse-out',\n\n /**\n * Fired when the mouse enters the graph.\n * @event series-mouse-over\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n mouseOver: 'series-mouse-over',\n\n /**\n * Fired when the series is show after chart generation time.\n * @event series-show\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} series Series object where the event was sent from\n */\n show: 'series-show'\n };\n }", "function objectChanged(_o) {\n replace(ka.objs, o, _o);\n recalc(ka);\n }", "function optionChanged(newSample) {\n // Fetch new data each time a new sample is selected\n buildPlots(newSample);\n Demographics(newSample);\n }", "get __chartEventNames() {\n return {\n /**\n * Fired when a new series is added.\n * @event chart-add-series\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n addSeries: 'chart-add-series',\n\n /**\n * Fired after a chart is exported.\n * @event chart-after-export\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n afterExport: 'chart-after-export',\n\n /**\n * Fired after a chart is printed.\n * @event chart-after-print\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n afterPrint: 'chart-after-print',\n\n /**\n * Fired before a chart is exported.\n * @event chart-before-export\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n beforeExport: 'chart-before-export',\n\n /**\n * Fired before a chart is printed.\n * @event chart-before-print\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n beforePrint: 'chart-before-print',\n\n /**\n * Fired when clicking on the plot background.\n * @event chart-click\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n click: 'chart-click',\n\n /**\n * Fired when drilldown point is clicked.\n * @event chart-drilldown\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n drilldown: 'chart-drilldown',\n\n /**\n * Fired when drilling up from a drilldown series.\n * @event chart-drillup\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n drillup: 'chart-drillup',\n\n /**\n * Fired after all the series has been drilled up if chart has multiple drilldown series.\n * @event chart-drillupall\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n drillupall: 'chart-drillupall',\n\n /**\n * Fired when the chart is finished loading.\n * @event chart-load\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n load: 'chart-load',\n\n /**\n * Fired when the chart is redraw. Can be called after a `Chart.configuration.redraw()`\n * or after an axis, series or point is modified with the `redraw` option set to `true`.\n * @event chart-redraw\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n redraw: 'chart-redraw',\n\n /**\n * Fired when an area of the chart has been selected.\n * @event chart-selection\n * @param {Object} detail.originalEvent object with details about the event sent\n * @param {Object} chart Chart object where the event was sent from\n */\n selection: 'chart-selection'\n };\n }", "function identify_plots_to_update (i) {\r\n\r\n\t// make a list of plots to update\r\n\tvar plots_to_update = [0, 0, 0];\r\n\tif (link_plots[i] == 0) {\r\n\r\n\t\t// zoomed plot is not linked\r\n\t\tplots_to_update[i] = 1;\r\n\r\n\t} else {\r\n\r\n\t\t// zoomed plot is linked\r\n\t\tplots_to_update = link_plots;\r\n\t}\r\n\r\n\treturn plots_to_update;\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps the data from a Testcase object to the UI. The UI currently uses jQuery and Bootstrap to display the data.
function mapCaseJsonToUi(data){ // // This gives me ONE object - The root for test cases // The step tag is the basis for each step in the Steps data array object. // var items = []; var xdata = data['step']; if (!jQuery.isArray(xdata)) xdata = [xdata]; // convert singleton to array //console.log("xdata =" + xdata); katana.$activeTab.find("#tableOfTestStepsForCase").html(""); // Start with clean slate items.push('<table class="case_configuration_table table-striped" id="Step_table_display" width="100%" >'); items.push('<thead>'); items.push('<tr id="StepRow"><th>#</th><th>Driver</th><th>Keyword</th><th>Description</th><th>Arguments</th>\ <th>OnError</th><th>Execute</th><th>Run Mode</th><th>Context</th><th>Impact</th><th>Other</th></tr>'); items.push('</thead>'); items.push('<tbody>'); for (var s=0; s<Object.keys(xdata).length; s++ ) { // for s in xdata var oneCaseStep = xdata[s]; // for each step in case //console.log(oneCaseStep['path']); var showID = parseInt(s)+1; items.push('<tr data-sid="'+s+'"><td>'+showID+'</td>'); // ID // ------------------------------------------------------------------------- // Validation and default assignments // Create empty elements with defaults if none found. ;-) // ------------------------------------------------------------------------- fillStepDefaults(oneCaseStep); items.push('<td>'+oneCaseStep['@Driver'] +'</td>'); var outstr; items.push('<td>'+oneCaseStep['@Keyword'] + "<br>TS=" +oneCaseStep['@TS']+'</td>'); outstr = oneCaseStep['Description']; items.push('<td>'+outstr+'</td>'); var arguments = oneCaseStep['Arguments']['argument']; var out_array = [] var ta = 0; for (xarg in arguments) { if (!arguments[xarg]) { continue; } var argvalue = arguments[xarg]['@value']; console.log("argvalue", argvalue); if (argvalue) { if (argvalue.length > 1) { var xstr = arguments[xarg]['@name']+" = "+arguments[xarg]['@value'] + "<br>"; //console.log(xstr); out_array.push(xstr); } ta = ta + 1; } } outstr = out_array.join(""); //console.log("Arguments --> "+outstr); items.push('<td>'+outstr+'</td>'); outstr = oneCaseStep['onError']['@action'] //"Value=" + oneCaseStep['onError']['@value']+"<br>"; items.push('<td>'+oneCaseStep['onError']['@action'] +'</td>'); oneCaseStep['Execute']['@ExecType'] = jsUcfirst( oneCaseStep['Execute']['@ExecType']); outstr = "ExecType=" + oneCaseStep['Execute']['@ExecType'] + "<br>"; if (oneCaseStep['Execute']['@ExecType'] == 'If' || oneCaseStep['Execute']['@ExecType'] == 'If Not') { outstr = outstr + "Condition="+oneCaseStep['Execute']['Rule']['@Condition']+ "<br>" + "Condvalue="+oneCaseStep['Execute']['Rule']['@Condvalue']+ "<br>" + "Else="+oneCaseStep['Execute']['Rule']['@Else']+ "<br>" + "Elsevalue="+oneCaseStep['Execute']['Rule']['@Elsevalue']; } items.push('<td>'+outstr+'</td>'); items.push('<td>'+oneCaseStep['runmode']['@type']+'</td>'); items.push('<td>'+oneCaseStep['context']+'</td>'); items.push('<td>'+oneCaseStep['impact']+'</td>'); var bid = "deleteTestStep-"+s+"-id-" items.push('<td><i title="Delete" class="fa fa-trash" theSid="'+s+'" id="'+bid+'" katana-click="deleteCaseFromLine()" key="'+bid+'"/>'); bid = "editTestStep-"+s+"-id-"; items.push('<i title="Edit" class="fa fa-pencil" theSid="'+s+'" value="Edit/Save" id="'+bid+'" katana-click="editCaseFromLine()" key="'+bid+'"/>'); bid = "addTestStepAbove-"+s+"-id-"; items.push('<i title="Insert" class="fa fa-plus" theSid="'+s+'" value="Insert" id="'+bid+'" katana-click="addCaseFromLine()" key="'+bid+'"/>'); bid = "dupTestStepAbove-"+s+"-id-"; items.push('<i title="Insert" class="fa fa-copy" theSid="'+s+'" value="Duplicate" id="'+bid+'" katana-click="duplicateCaseFromLine()" key="'+bid+'"/>'); } items.push('</tbody>'); items.push('</table>'); // katana.$activeTab.find("#tableOfTestStepsForCase").html( items.join("")); katana.$activeTab.find('#Step_table_display tbody').sortable( { stop: testCaseSortEventHandler}); fillCaseDefaultGoto(); katana.$activeTab.find('#default_onError').on('change',fillCaseDefaultGoto ); /* if (jsonCaseDetails['Datatype'] == 'Custom') { $(".arguments-div").hide(); } else { $(".arguments-div").show(); } */ } // end of function
[ "function testcasePopulateTestcaseList(projectId){\n $('.field-project-id').val(projectId);\n $.ajax({\n url : endpoint+'?action=testcases&subaction=getallbyprojectid&id='+projectId,\n method: 'GET'\n }).done(function(response){\n // console.log(response);\n if(response != undefined){\n response = JSON.parse(response);\n if(response.success == true){\n $('.testcase-list-table tbody').html('');\n for(var i=0; i< response.items.length; i++){\n var item = response.items[i];\n var id = item.id;\n var name = item.name;\n var action = item.action;\n var status = item.status;\n var currentUserId = item.currentUserId;\n testcaseUpdateCurrentUserCell(currentUserId);\n if(currentLoggedInUser.privilege == 'Developer'){\n var hideForDeveloper = 'hidden';\n }else{\n var hideForDeveloper = '';\n }\n var row = '<tr data-id=\"'+id+'\"><td>'+id+'</td><td>'+name+'</td><td>'+action+'</td><td>'+status+'</td><td class=\"current-user-cell\" data-current-user-id=\"'+currentUserId+'\">'+currentUserId+'</td><td><span class=\"btn btn-primary button testcase-edit-button\">Edit</span></td><td class=\"'+hideForDeveloper+'\"><span class=\"btn btn-primary button testcase-delete-button\">Delete</span></td></tr>';\n $('.testcase-list-table tbody').append(row);\n }\n }\n }\n })\n}", "constructor(caseviewData: ModularUIResponse) {\n super(caseviewData);\n\n this._panelCollection = new PanelCollection();\n this._taskGroupCollection = new TaskGroupCollection();\n\n const casename =\n this.casename === null || this.casename.value === null\n ? \"\"\n : this.casename.value;\n\n this._context = this.casename\n ? new ContextModel(this.key, this.selfhref, casename)\n : null;\n }", "function /*void*/ mapTestSectionTest() {\n\tvar testSectionId = 0; \t//e.g. testSectionId = 7 (set testSectionId to get all tests for the specified test section)\n new Ajax.Request (\n 'ajaxXML', // url\n { // options\n method: 'get', // http method\n parameters: 'provider=TestSectionTestMapProvider&testSectionId=' + testSectionId, // request parameters\n //indicator: 'throbbing'\n onSuccess: processTestSectionTestMapSuccess,\n onFailure: processFailure\n }\n );\n}", "_setDataToUI() {\n const data = this._data;\n if (data === undefined) return;\n console.log('View#_setDataToUI', this);\n\n if (data instanceof Object) {\n eachEntry(data, ([name, val]) => this._setFieldValue(name, val));\n } else {\n this._setVal(this.el, data);\n }\n }", "function showTesting() {\n console.log('showTesting');\n selectAllH().append(function() {\n // Let's see the tag names (for testing)\n return ' (' + $(this).prop('tagName') + ', ' + $(this).prop('id') + ')';\n });\n }", "function testcaseProjectList(){\n $.ajax({\n url : endpoint+'?action=projects&subaction=getall',\n method: 'GET'\n }).done(function(response){\n if(response != undefined){\n response = JSON.parse(response);\n if(response.success == true){\n $('.project-list-table tbody').html('');\n for(var i=0; i< response.items.length; i++){\n var item = response.items[i];\n var id = item.id;\n var name = item.name;\n var description = item.description;\n var row = '<tr data-id=\"'+id+'\"><td>'+id+'</td><td>'+name+'</td><td>'+description+'</td><td><span class=\"btn btn-primary button testcase-project-view-button\">View</span></td></tr>';\n $('.project-list-table tbody').append(row);\n }\n }\n }\n })\n}", "function testcasePopulateEditFormById(id){\n if(currentLoggedInUser.privilege == 'Developer'){\n $('.field-testcase-name').attr('disabled',true);\n $('.field-testcase-action').attr('disabled',true);\n $('.field-testcase-expectedResult').attr('disabled',true);\n $('.field-testcase-actualResult').attr('disabled',true);\n }\n $.ajax({\n url : endpoint+'?action=testcases&subaction=getbyid&id='+id,\n method: 'GET'\n }).done(function(response){\n if(response != undefined){\n response = JSON.parse(response);\n if(response.success == true){\n $('.field-testcase-id').val(response.item.id);\n $('.field-testcase-name').val(response.item.name);\n $('.field-testcase-action').val(response.item.action);\n $('.field-testcase-expectedResult').val(response.item.expectedResult);\n $('.field-testcase-actualResult').val(response.item.actualResult);\n $('.field-testcase-status').val(response.item.status);\n $('.field-testcase-currentUserId').val(response.item.currentUserId);\n }\n }\n })\n}", "function listAllTests() {\n for (const suite in objekt) {\n if (objekt.hasOwnProperty(suite)) {\n objekt[suite].forEach(element => {\n document.querySelector('#tests').innerHTML += `<div class=\"custom-control custom-checkbox\">\n <input type=\"checkbox\" class=\"custom-control-input\" id=\"${element}\">\n <label class=\"custom-control-label\" for=\"${element}\">${element}</label>\n </div>`;\n });\n }\n }\n }", "static init()\n {\n let aeTest = Component.getElementsByClass(document, PCx86.APPCLASS, \"testctl\");\n for (let iTest = 0; iTest < aeTest.length; iTest++) {\n let eTest = aeTest[iTest];\n let parms = Component.getComponentParms(eTest);\n let test = new TestController(parms);\n Component.bindComponentControls(test, eTest, PCx86.APPCLASS);\n }\n }", "function runTestCase(object){\n var path = '../testCasesExecutables/' + object.filename;\n var testCase = require(path);\n var result = testCase.test(object.inputs);\n resultsObject[object.number] = createHTMLResultTable(object.number, object.requirement, object.component, object.method, object.inputs, object.outcomes, result)\n if(Object.keys(resultsObject).length === 25){\n writeToHTMLFile();\n }\n}", "async function createUI() {\n const infectedHosts = await getInfectedHosts();\n infectedHosts.forEach(async (host) => {\n const payloads = await getPayloads(host);\n\n const hostDiv = createHostDiv();\n const hostLink = createHostLink(host);\n\n hostDiv.append(hostLink);\n $(\"#infected_hosts\").append(hostDiv);\n\n payloads.forEach(async (payloadObject) => {\n const userPayloadsDiv = createUserPayloadsDiv();\n const userPayloadsLink = createUserPayloadsLink(payloadObject);\n\n userPayloadsDiv.append(userPayloadsLink);\n\n const payload = await getPayload(host, payloadObject['payload_id']);\n\n const payloadDataDiv = $(\"<pre class=\\\"payload\\\"></pre>\");\n payloadDataDiv.append(payload);\n const containerDiv = $(\"<div class=\\\"container\\\"></div>\");\n containerDiv.css(\"display\", \"none\");\n containerDiv.append(userPayloadsDiv);\n containerDiv.append(payloadDataDiv);\n hostDiv.append(containerDiv);\n });\n });\n }", "function loadSampleScreen(pattern) \n{\n // URL to connect to\n var url = api+'/?service=info&pattern='+pattern;\n\n // Connecting via AJAX\n $.getJSON(url, function( data ) {\n // Repsonse loaded\n clearSpinner();\n $('#demo').append( \"<h2>Sampling \"+pattern+\"</h2>\");\n $('#demo').append( \"<p>You can sample measurements or options with the links below.</p>\");\n $('#demo').append( '<form class=\"form\" id=\"form\"></form>');\n $('#form').append( \"<h3>Sample measurements</h3><ul id='mesul'></ul>\");\n $.each( data['models']['groups'], function( key, val ) {\n $('#mesul').append( '<li><a href=\"#\" class=\"demo-trigger\" data-method=\"sample-pattern\" data-type=\"measurements\" data-option=\"'+key+'\" data-pattern=\"'+pattern+'\">'+key+'</a> ('+val.length+' models)</li>');\n });\n $('#form').append( \"<h3>Sample options</h3><ul id='opsul'></ul>\");\n $.each( data['options'], function( key, val ) {\n $('#opsul').append( '<li><a class=\"demo-trigger\" href=\"#\" data-method=\"sample-pattern\" data-type=\"options\" data-option=\"'+key+'\" data-pattern=\"'+pattern+'\">'+key+'</a></li>');\n });\n scrollTo('#demo');\n });\n}", "function Steps (dataSteps){ \n // this.$el = \"\"; // this will hold the stepsContainer html element\n // this.dots.$el = '';\n // this.titles.$el = '';\n // this.descriptions.$el = '';\n this.data = dataSteps;\n this.dotsArr = [];\n this.titlesArr = [];\n\n this.init = function (){ \n this.dotsInit (this.data.dots , \".stepsDotsContainer--js\"); // create a steps object , append into the html tag.\n this.titlesInit (this.data.titles, \".stepsTitlesContainer--js\"); // create a titles object , append into the html tag.\n // steps.descriptions.init (stepsDescriptionsData, \".stepsDescriptionsContainer\"); // create a titles object , append into the html tag.ta\n // setStepsDefaults (this.data); \n }\n\n this.dotsInit = function (dataStepsDots , stepsDotsHtmlEL){ //when creating a new Steps object we need to define the html element to connect it to \n // for loop, create the steps according to dataStepsDots\n var output = '';\n for (var i in dataStepsDots){\n var stepDot = new StepDot();\n stepDot.init (dataStepsDots[i] , i);\n output += stepDot.snippet; //adds to output var (a holder var) the html element of this new step\n this.dotsArr.push(stepDot);\n };\n // the birth of the stepsDots into the UI\n $(stepsDotsHtmlEL).append(output);\n\n // after the elements are appended, set the $el for each dot\n for (var i in dataStepsDots){\n this.dotsArr[i].$el = $('#stepDot-' + i) \n }\n }\n\n // ** Titles ------------------------------------------------------------------------------------\n this.titlesInit = function (dataStepsTitles , stepsTitlesHtmlEL){ //when creating a new Titles object we need to define the html element to connect it to \n // for loop, create the steps according to dataSteps\n var output = '';\n for (var i in dataStepsTitles){\n var stepTitle = new StepTitle();\n stepTitle.init (dataStepsTitles[i] , i);\n output += stepTitle.snippet; //adds to output var (a holder var) the html element of this new step\n this.titlesArr.push(stepTitle);\n };\n // append the steps into $el. this will actually place the steps object (which include each of the step object inside it) into the ui. \n this.$el = $(stepsTitlesHtmlEL).append(output);\n \n // after the elements are appended, set the $el for each titles\n for (var i in dataStepsTitles){\n this.titlesArr[i].$el = $('#stepTitle-' + i) \n }\n\n this.removeAllTitles();\n this.titlesArr[0].showTitle()\n }\n // define init descriptions\n // set defaults\n\n // Steps FUNCTIONS -------------------------------------\n // \n\n this.setSelectedStep = function (index){\n this.removeAllSelectedDots();\n this.dotsArr[index].setSelected(); \n this.removeAllTitles();\n this.titlesArr[index].showTitle();\n // this.descriptionsArr[index].setDescription();\n }\n\n this.removeAllSelectedDots = function (){\n for (var i in this.dotsArr) {\n this.dotsArr[i].removeSelected()\n }\n }\n this.pauseAllDots = function () {\n for (var i in this.dotsArr) {\n this.dotsArr[i].setPause()\n }\n }\n this.removeAllTitles = function (){\n for (i in this.titlesArr){\n this.titlesArr[i].displayNone();\n }\n }\n this.next = function (currentStepIndex){\n if(currentStepIndex !== this.dotsArr.length){\n setSelectedStep(currentStepIndex+1)\n }\n };\n\n this.prev = function (currentStepIndex){\n if(currentStepIndex !== 0){\n setSelectedStep(currentStepIndex-1)\n }\n };\n \n this.toggleDotIcon = function (index) {\n switch(true){\n case (this.dotsArr[index].$el.find(\".stepDot__icon\").hasClass(\"stepDot__icon--pause\")) :\n this.pauseAllDots();\n break; \n case (this.dotsArr[index].$el.find(\".stepDot__icon\").hasClass(\"stepDot__icon--play\")) :\n this.pauseAllDots(); \n this.dotsArr[index].togglePlayPause();\n }\n }\n\n // function setSelectedStep (index){\n // selectDot (index)\n // showTitle (index);\n // }\n \n\n\n // function setStepsDefaults (dataSteps){\n // this.removeAllTitles();\n // dataSteps.titlesArr[0].showTitle() ;\n // }\n\n function selectDot (index) {\n for (var i in this.dotsArr){\n $('#stepDot-' + i).addClass('displayNone') \n }\n $('#stepDot-' + index).removeClass('displayNone') \n }\n\n\n\n \n\n}", "function generateUIForJSON(data){\n return `\n <div class=\"quarter\">\n <div class=\"image\">\n <img src=\"${data.picture}\"/>\n </div>\n <div class=\"info\">\n <h3>${data.name}</h3>\n <h4>${data.gender}</h3>\n <h5>${data.email}</h5>\n </div>\n </div>\n `\n}", "function loadProject() {\n\t\t/*\n\t\t//use temp project stubs here \n\t\tvar project = project1;\n\t\tfor (var i = 0; i <= project.tasks.length - 1; i++) { \n\t\t\taddTableRow(project.tasks[i]);\n\t\t\tgenerateTaskDetailsModal(project.tasks[i]);\t\n\t\t};\n\t\t*/\n\t\tgenerateLeftTable();\n\t\tgenerateRightDayTable();\n\t\tgenerateRightWeekTable();\n\t\tgenerateRightMonthTable();\n\t\tgenerateRightQuarterTable();\n\t}", "createUI() {\n var title = panelTitle;\n this.panel = new PanelClass(this.viewer, title);\n var button1 = new Autodesk.Viewing.UI.Button(panelTitle);\n\n button1.onClick = (e) => {\n if (!this.panel.isVisible()) {\n this.panel.setVisible(true);\n } else {\n this.panel.setVisible(false);\n }\n };\n\n button1.addClass('fa');\n button1.addClass('fa-child');\n button1.addClass('fa-2x');\n button1.setToolTip(onMouseOver);\n\n this.subToolbar = this.viewer.toolbar.getControl(\"spinalcom-sample\");\n if (!this.subToolbar) {\n this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('spinalcom-sample');\n this.viewer.toolbar.addControl(this.subToolbar);\n }\n this.subToolbar.addControl(button1);\n this.initialize();\n }", "function refreshEditRecordingTestDropdown() {\r\n //get the tests data from the database so we can have recordings linked to tests\r\n StorageUtils.getAllObjectsInDatabaseTable('recordings.js', 'tests')\r\n //once we have the array then we can start populating the new recording form tests dropdoqn by looping through the array\r\n .then((testStorageArray) => {\r\n //filter tests for default project by fetching from local storage\r\n const defaultProjectId = Number(localStorage.getItem('DefaultProject'));\r\n //if we have any number greater than zero, which indicates no default, then filter\r\n defaultProjectId > 0\r\n ? (testStorageArray = testStorageArray.filter((test) => test.testProjectId == defaultProjectId))\r\n : null;\r\n\r\n //get a reference to the drop down in thee edit recording form\r\n var editRecordingDropDownMenu = $('.ui.fluid.selection.editRecording.test.dropdown .menu');\r\n //empty the dropdown of existing items\r\n editRecordingDropDownMenu.empty();\r\n //use for-of loop as execution order is maintained to insert all the tests, with references, in the dropdown\r\n for (let test of testStorageArray) {\r\n //we are not going to use templates here as we are not dealing with complex html structures\r\n editRecordingDropDownMenu.append(`<div class=\"item\" data-value=${test.id}>${test.testName}</div>`);\r\n }\r\n //then after the entire loop has been executed we need to initialise the dropdown with the updated items\r\n $('.ui.fluid.selection.editRecording.test.dropdown').dropdown({\r\n direction: 'upward',\r\n });\r\n });\r\n}", "function displayDataInfo(e){\n let newApiService, quotes, randomQuoteEl;\n randomQuoteEl = document.querySelector(selectors.randomQuote);\n\n //1. Make instance of ApiService\n newApiService = new QuotesService('http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1');\n \n //2. Invoke apiData method\n quotes = newApiService.getApiData();\n \n \n //3.Pass recieved data from service to UIController\n console.log(quotes);\n UICtrl.show(quotes);\n\n //4.Create Random color\n UICtrl.displayRandomColor();\n\n e.preventDefault();\n }", "function setUpTests()\n {\n// var fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n var fullInteractionData;\n if(app.scorm.scormProcessGetValue('cmi.suspend_data') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.suspend_data'));\n }\n else if(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response') !== ''){\n fullInteractionData = $.parseJSON(app.scorm.scormProcessGetValue('cmi.interactions.0.learner_response'));\n }\n else{\n console.log('There is a problem with test submission.');\n }\n \n // Inject the CMI DB data into the questionBank on first load\n if (fullInteractionData) {\n $.each(fullInteractionData, function (index, value)\n {\n if (!app.questionBank[index]) {\n app.questionBank[index] = value;\n }\n }); \n }\n \n // Setup the current test's question bank\n if (!app.questionBank[testID]) {\n app.questionBank[testID] = [];\n }\n \n return fullInteractionData;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a specific version of a badge by name.
getVersion(name) { return new ChatBadgeVersion_1.ChatBadgeVersion(this._data.versions[name]); }
[ "async getVersionInfo({ state, getters, commit }, {\n repoType, repoName, chartName, versionName\n }) {\n const key = `${ repoType }/${ repoName }/${ chartName }/${ versionName }`;\n let info = state.versionInfos[key];\n\n if ( !info ) {\n const repo = getters['repo']({ repoType, repoName });\n\n if ( !repo ) {\n throw new Error('Repo not found');\n }\n\n info = await repo.followLink('info', {\n url: addParams(repo.links.info, {\n chartName,\n version: versionName\n })\n });\n\n commit('cacheVersion', { key, info });\n }\n\n return info;\n }", "function extGroup_getVersion(groupName)\n{\n var retrievedVersion = parseFloat(dw.getExtDataValue(groupName, \"version\"));\n if (isNaN(retrievedVersion))\n retrievedVersion = 0;\n return retrievedVersion;\n}", "function gongGetVersion(gong) {\n if (gong == null || !gong.isActive()) return \"Gong Applet is not ready.\";\n\n if (useXML) {\n var request = \"<GetVersionRequest xmlns=\\\"\" + GASI_NAMESPACE_URI + \"\\\"/>\";\n if (gong != null) {\n var response = gong.sendGongRequest(request);\n if (isFault(response)) return getFaultReason(response);\n return getParameter(response, \"Version\");\n }\n return null;\n }\n else if (gong != null) return gong.sendGongRequest(\"GetVersion\", \"\");\n}", "function generateBadge(data){\n return licenseBadge[data.license]; \n}", "function tag_version(){\n\treturn new Promise((resolve, reject)=>{\n\t\tconst pkg = reload('../../package.json');\n const tag = `v${pkg.version}`;\n gutil.log('Tagging as: '+gutil.colors.cyan(tag));\n git.tag(tag, `Tagging as ${tag}`, (err)=>{\n\t\t\tcheckError(err);\n\t\t\tresolve(tag);\n })\n\t})\n}", "async function getPkgReleases({ lookupName }) {\n logger.debug({ lookupName }, 'orb.getPkgReleases()');\n const cacheNamespace = 'orb';\n const cacheKey = lookupName;\n const cachedResult = await renovateCache.get(cacheNamespace, cacheKey);\n // istanbul ignore if\n if (cachedResult) {\n return cachedResult;\n }\n const url = 'https://circleci.com/graphql-unstable';\n const body = {\n query: `{orb(name:\"${lookupName}\"){name, homeUrl, versions {version, createdAt}}}`,\n variables: {},\n };\n try {\n const res = (await got.post(url, {\n body,\n json: true,\n retry: 5,\n })).body.data.orb;\n if (!res) {\n logger.info({ lookupName }, 'Failed to look up orb');\n return null;\n }\n // Simplify response before caching and returning\n const dep = {\n name: lookupName,\n versions: {},\n };\n if (res.homeUrl && res.homeUrl.length) {\n dep.homepage = res.homeUrl;\n }\n dep.homepage =\n dep.homepage || `https://circleci.com/orbs/registry/orb/${lookupName}`;\n dep.releases = res.versions.map(v => v.version);\n dep.releases = dep.releases.map(version => ({\n version,\n }));\n logger.trace({ dep }, 'dep');\n const cacheMinutes = 15;\n await renovateCache.set(cacheNamespace, cacheKey, dep, cacheMinutes);\n return dep;\n } catch (err) /* istanbul ignore next */ {\n logger.debug({ err }, 'CircleCI Orb lookup error');\n if (err.statusCode === 404 || err.code === 'ENOTFOUND') {\n logger.info({ lookupName }, `CircleCI Orb lookup failure: not found`);\n return null;\n }\n logger.warn({ lookupName }, 'CircleCI Orb lookup failure: Unknown error');\n return null;\n }\n}", "function getModuleByVersion(modulename, version) {\n version = parseInt(version);\n while (version > 1 && !checkIfVersionExists(modulename, version)) {\n version--;\n }\n return instantiate(modulename, version); //return new modulename.v + version;\n}", "async function getLatestRevision() {\n const result = await getFileRevision({ accessToken, path });\n return result;\n }", "function extPart_getVersion(partName)\n{\n var retrievedVersion = parseFloat(dw.getExtDataValue(partName, \"version\"));\n if (isNaN(retrievedVersion))\n retrievedVersion = 0;\n return retrievedVersion;\n}", "function version(){\n var xmlReq = new XMLHttpRequest(); \n xmlReq.open(\"GET\", \"Info.plist\", false); \n xmlReq.send(null); \n \n var xml = xmlReq.responseXML; \n var keys = xml.getElementsByTagName(\"key\");\n var ver = \"0.0\";\n\n for (i=0; i<keys.length; ++i) {\n if (\"CFBundleVersion\" == keys[i].firstChild.data) {\n ver = keys[i].nextSibling.nextSibling.firstChild.data;\n break;\n }\n }\n\n return ver; \n}", "function getLobbyWithName(name)\n{\n const found = lobbies.find(lobby => lobby.name == name);\n\n if (found)\n return found;\n else\n throw 'There is no lobby with that name.';\n}", "function getFontAwesomeVersion() {\n return new Promise((resolve, reject) => {\n fs.readFile('node_modules/@fortawesome/fontawesome-pro/less/_variables.less', (e, data) => {\n if (e) {\n reject(e);\n } else {\n const match = data.toString().match(/fa-version:\\s+\"(.+)\";/);\n if (match) {\n resolve(match[1]);\n } else {\n reject('Pattern not found');\n }\n }\n });\n });\n}", "function checkForLatestVersion() {\n return new Promise((resolve, reject) => {\n https\n .get('https://registry.npmjs.org/-/package/init-node-server/dist-tags', res => {\n if (res.statusCode === 200) {\n let body = '';\n res.on('data', data => (body += data));\n res.on('end', () => {\n resolve(JSON.parse(body).latest);\n });\n } else {\n reject();\n }\n })\n .on('error', () => {\n reject();\n });\n });\n}", "function rewardBadge(codename, params){\n // Remove from checkers.\n delete params._userCheckers[codename];\n\n // Add badge to user.\n User.findOne({_id:params.user.id}, function(err, user){\n if(err || !user) return;\n\n // Add badge.\n user.badges.push(params.badge._id);\n user.markModified('badges');\n\n // Save\n user.save();\n });\n\n // Notify user!\n params._socket.emit('reward', params.badge);\n}", "async getBuild(buildId) {\n validateBuildId(buildId);\n this.log.debug(`Get build ${buildId}`);\n return this.get(`builds/${buildId}`);\n }", "async function fetchLatestRelease (repo) {\n return await new Promise((resolve, reject) => {\n https.get({\n auth: this.credentials.login + ':' + this.credentials.password,\n headers: {'User-Agent': this.credentials.login},\n host: 'api.github.com',\n path: '/repos/' + repo + '/releases/latest',\n port: '443'\n }, (res) => {\n // explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)\n res.setEncoding('utf8');\n\n // incrementally capture the incoming response body\n var data = '';\n res.on('data', function (d) {\n data += d;\n });\n\n try {\n res.on('end', async () => {\n try {\n // console.log(res);\n var parsed = JSON.parse(data);\n } catch (err) {\n console.error(res.headers);\n console.error('Unable to parse response as JSON');\n return {};\n }\n\n resolve({tag_name: parsed.tag_name, published_at: parsed.published_at});\n });\n } catch (err) {\n console.log(err);\n reject(new Error());\n }\n });\n });\n}", "getUrl (name) {\n name = name.name ? name.name : name\n return this.urls[name]\n }", "getReleaseChanges(version) {\n return this._changes[version];\n }", "function findByName(name) {\n return db.oneOrNone(`SELECT * FROM bands WHERE name = $1;`, [name]);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a predecessor and a string, find the required matches we only need the successor as a parameter so that we can add it to the return value without that, we can't be certain which replacement goes with which successors
_match(predecessor, suc, stringMatch) { /* [ { startIndex: 1, //Inclusive endIndex: 2, //Exclusive successor: "some string" }, { startIndex: 2, endIndex, 4, successor: "other string" } ] */ //NOTE - predecessors have 2 restricted characters; '<' and '>' - These are used for context sensative predecessors let successorList = this._buildSuccessorList(predecessor); let contextSensative = false; let context = []; let matchPredecessor = predecessor if(predecessor.indexOf('>') >= 0 || predecessor.indexOf('<') >= 0) { //We know that this will be context sensative contextSensative = true; context = predecessor.split(/[<>]+/); matchPredecessor = context[1]; //This assumes there is a forward and backward context TODO: fix this } //Find all matches for the predecessor in the axiom let returnValue = []; let sIndex = this._matchPredecessor(stringMatch, matchPredecessor, contextSensative, context[0], context[2], 0); while(sIndex >= 0) { let chosenSuc = this._chooseSuccessor(successorList); let object = { startIndex: sIndex, endIndex: sIndex + 1, //TODO: how do this NOTE - this currently assumes only one character is getting replaced. For the scope of this project that is probably fine, but if I want to make this more generic, I should find a better way to do this. successor: chosenSuc } returnValue.push(object); sIndex = this._matchPredecessor(stringMatch, matchPredecessor, contextSensative, context[0], context[2], sIndex + 1); } //Return a list of the index's that match return returnValue; }
[ "function getFront(mainStr,searchStr)\r\n{\r\n var foundOffset=mainStr.indexOf(searchStr);\r\n if(foundOffset==-1)\r\n return null;\r\n return mainStr.substring(0,foundOffset);\r\n}", "function getAutoComplete(sub,stringlist) {\n if (stringlist.length===0) { return \"-1\"; }\n var res=stringlist[0].substr(sub.length);\n for (var i=1;i<stringlist.length;++i) {\n if (res===\"\") {break;}\n var tail=stringlist[i].substr(sub.length);\n var len=res.length>tail.length ? tail.length : res.length;\n for (var j=0; j<len; ++j) {\n if (res.charAt(j)!==tail.charAt(j)) {\n res=res.substr(0,j);\n break;\n }\n }\n }\n return res;\n}", "function secondIndexOf(s1, s2) {\n // Use indexOf twice.\n // const s1Low = s1.toLowerCase();\n // const s2Low = s2.toLowerCase();\n const indexOfFirst = s1.indexOf(s2); \n // console.log(`The index of the first \"${s2}\" from the beginning is ${indexOfFirst}`); \n // console.log(`The index of the secound \"${s2}\" is ${s1.indexOf(s2, (indexOfFirst + 1))}`); \n const a = s1.indexOf(s2, (indexOfFirst + 1));\n console.log(a);\n}", "function trim_left_1(s, sub) /* (s : string, sub : string) -> string */ { tailcall: while(1)\n{\n if (empty_ques__1(sub)) {\n return s;\n }\n else {\n var _x34 = starts_with(s, sub);\n if (_x34 != null) {\n {\n // tail call\n var _x35 = (string_3(_x34.value));\n s = _x35;\n continue tailcall;\n }\n }\n else {\n return s;\n }\n }\n}}", "function starts_with(s, pre) /* (s : string, pre : string) -> maybe<sslice> */ {\n if ((s.substr(0,pre.length) === pre)) {\n return Just(Sslice(s, pre.length, (((s.length) - (pre.length))|0)));\n }\n else {\n return Nothing;\n }\n}", "replaceSubstring(s1, s2, array){\n var result = Array();\n for (var el of array) {\n if(typeof el !== \"undefined\"){\n // Non solo la stringa deve essere contenuta, ma dato che si tratta di una sositutzione\n // dell'intero percorso fino a quella cartella mi assicuro che l'inclusione parta\n // dal primo carattere\n var eln = el;\n if(el.substring(0,s1.length).includes(s1)){\n eln = s2+el.substring(s1.length)\n }\n result.push(eln);\n }\n }\n return result;\n }", "function RegexGrapher(regex, nfa) {\n this.nfa = nfa;\n var p = regex.rtype;\n\n if(p == 'p') { // Primitive\n this.start = new Node(\"\");\n this.end = new Node(\"\");\n nfa.add_node(this.start);\n nfa.add_node(this.end);\n this.start.add_next_edge(new Edge(this.start, regex.c, this.end));\n }\n else if(p == 's') { // Sequence\n var first = new RegexGrapher(regex.first, nfa);\n var second = new RegexGrapher(regex.second, nfa);\n this.start = first.start;\n this.end = second.end;\n var edgesToUpdate = second.start.nextEdges;\n for (var i = edgesToUpdate.length - 1; i >= 0; i--) {\n // Update outgoing edges to start at first.end\n edgesToUpdate[i].prev_node = first.end;\n };\n // Replace outgoing edges at first.end\n // (There should be none to begin with)\n first.end.nextEdges = edgesToUpdate;\n // Remove the extra node from the graph\n nfa.nodes.splice(nfa.nodes.indexOf(second.start), 1);\n }\n else if(p == 'c') { // Choice\n var thisOne = new RegexGrapher(regex.thisOne, nfa);\n var thatOne = new RegexGrapher(regex.thatOne, nfa);\n this.start = new Node(\"\");\n this.end = new Node(\"\");\n nfa.add_node(this.start);\n nfa.add_node(this.end);\n this.start.add_next_edge(new Edge(this.start, \"eps\", thisOne.start));\n this.start.add_next_edge(new Edge(this.start, \"eps\", thatOne.start));\n thisOne.end.add_next_edge(new Edge(thisOne.end, \"eps\", this.end));\n thatOne.end.add_next_edge(new Edge(thatOne.end, \"eps\", this.end));\n }\n else if(p == 'r') { // Repetition\n var internal = new RegexGrapher(regex.internal, nfa);\n this.start = new Node(\"\");\n this.end = new Node(\"\");\n nfa.add_node(this.start);\n nfa.add_node(this.end);\n this.start.add_next_edge(new Edge(this.start, \"eps\", internal.start));\n this.start.add_next_edge(new Edge(this.start, \"eps\", this.end));\n internal.end.add_next_edge(new Edge(internal.end, \"eps\", internal.start));\n internal.end.add_next_edge(new Edge(internal.end, \"eps\", this.end));\n }\n else throw \"Regex type not found\";\n}", "function reverse_history_search(next) {\n\t var history_data = history.data();\n\t var regex, save_string;\n\t var len = history_data.length;\n\t if (next && reverse_search_position > 0) {\n\t len -= reverse_search_position;\n\t }\n\t if (rev_search_str.length > 0) {\n\t for (var j = rev_search_str.length; j > 0; j--) {\n\t save_string = $.terminal.escape_regex(rev_search_str.substring(0, j));\n\t regex = new RegExp(save_string);\n\t for (var i = len; i--;) {\n\t if (regex.test(history_data[i])) {\n\t reverse_search_position = history_data.length - i;\n\t self.position(history_data[i].indexOf(save_string));\n\t self.set(history_data[i], true);\n\t redraw();\n\t if (rev_search_str.length !== j) {\n\t rev_search_str = rev_search_str.substring(0, j);\n\t draw_reverse_prompt();\n\t }\n\t return;\n\t }\n\t }\n\t }\n\t }\n\t rev_search_str = ''; // clear if not found any\n\t }", "function matchBeginningStringPattern(string, target) {\n // This will find target only in the beginning of the string.\n let regex = new RegExp(\"^\" + target);\n return string.match(regex);\n}", "getSuccessor()\n {\n let curNode = this;\n let lagNode = this;\n\n if (curNode.right !== null)\n {\n curNode = curNode.right;\n\n while (curNode.left !== null)\n {\n curNode = curNode.left;\n }\n\n return curNode;\n }\n\n else\n {\n if (curNode.parent === null)\n {\n // // alert('No successor in tree');\n return null;\n }\n curNode = curNode.parent;\n while (curNode !== null)\n {\n if (curNode.left !== null && curNode.left.data === lagNode.data)\n {\n return curNode;\n }\n curNode = curNode.parent;\n lagNode = lagNode.parent;\n }\n // // alert('No successor in tree');\n return null;\n }\n }", "function isPrefix(sub,str) {\n return str.lastIndexOf(sub,0)===0;\n}", "function calculatelpstable(substr) {\n let i=1;\n let j=0;\n let lps = new Array(substr.length).fill(0); // [0,0,0,0,0,0,0]\n while(i<substr.length) {\n if(substr[i] === substr[j]){\n lps[i]=j+1;\n i++;j++;\n } else {\n if(j!==0){\n j=lps[j-1];\n } else{\n i++;\n }\n }\n }\n return lps;\n}", "function createStartsWithFilter(startsWith) {\n // YOUR CODE BELOW HERE //\n // I = string character\n // O = function that returns Boolean\n // if else conditional to see if first letter of string === startsWith arg\n // find value of first letter of newString using charAt() method\n // use .toLowerCase string method on both arguments so that strict equality gives desired result\n return function(newString) {\n if (newString.charAt(0).toLowerCase() === startsWith.toLowerCase()) {\n return true;\n } else {\n return false;\n }\n \n }\n \n // YOUR CODE ABOVE HERE //\n}", "function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}", "function InStr(start, srchStr, fndStr, cmp) {\n if (!fndStr || fndStr==null || fndStr==\"\") {\n\t\tfndStr += \"\";\n if (fndStr.length == 0) {\n if (!start || start==null || !isNumeric(start) || start=='' || start < 1 ) { start=1; }\n start=Math.floor(start);\n if (!srchStr || srchStr==null) { srchStr=''; }\n if (start > srchStr.toString().length) { return 0; }\n return start;\n }\n\t\tcmp=0;\n fndStr=srchStr;\n srchStr=start;\n start=1;\n }\n\tif (!isNumeric(Math.floor(start))) {\n cmp=fndStr;\n\t\tfndStr=srchStr;\n srchStr=start;\n start=1;\n\t}\n if (!start || start==null || !isNumeric(start) || start=='' || start < 1 ) { start=1; }\n if (!srchStr || srchStr==null) { srchStr=''; }\n if (!fndStr || fndStr==null) { fndStr=''; }\n start=Math.floor(start);\n\n if (srchStr == \"\") { return 0; }\n var osrchStr=srchStr.toString();\n if (start > osrchStr.length) { return 0; }\n if (fndStr == \"\") { return start; }\n\n srchStr=osrchStr;\n fndStr=fndStr.toString();\n if (start>1) { srchStr=srchStr.substr(start-1); }\n\tcmp = cmp + \"\";\n\tvar loc=0;\n\tif (cmp=='1') { //insensitive\n\t\tvar osrchStr=srchStr.toLowerCase();\n\t\tvar ofndStr=fndStr.toLowerCase();\n\t\tif (osrchStr.indexOf(ofndStr) == -1) { return 0; }\n\t\tloc=osrchStr.indexOf(ofndStr)+1+(start-1);\n\t} else {\n\t\tif (srchStr.indexOf(fndStr) == -1) { return 0; }\n\t\tloc=srchStr.indexOf(fndStr)+1+(start-1);\n\t}\n return loc;\n}", "function segmentMatch(mr) {\n const { matches, index, groups, input } = mr;\n const segments = [];\n let p = index;\n for (let groupNum = 0; groupNum < matches.length; ++groupNum) {\n const m = matches[groupNum];\n if (!m)\n continue;\n // Look forwards for the next best match.\n const idx0 = input.indexOf(m, p);\n // try looking backwards if forwards does not work.\n const idx = idx0 >= p ? idx0 : input.lastIndexOf(m, p);\n if (idx < 0)\n continue;\n segments.push({ match: m, index: idx, groupNum, groupName: undefined });\n p = idx;\n }\n const textToSeg = new Map(segments.map((s) => [s.match, s]));\n for (const [name, value] of Object.entries(groups)) {\n const s = value && textToSeg.get(value);\n if (!s)\n continue;\n s.groupName = s.groupName\n ? Array.isArray(s.groupName)\n ? s.groupName.concat([name])\n : [s.groupName, name]\n : name;\n }\n return segments;\n}", "function InStrRev(srchStr, fndStr, start, cmp) {\n if (!fndStr || fndStr==null) {fndStr=\"\";}\n if (!cmp) {cmp=0;}\n srchStr.toString();\n if (cmp==1) {\n srchStr=srchStr.toLowerCase();\n fndStr=fndStr.toLowerCase();\n }\n if (!start || !isNumeric(start)) {start=-1;}\n if (start>-1) {\n srchStr=srchStr.substr(0,start);\n }\n var loc;\n if (fndStr == \"\" ) {\n loc=srchStr.length;\n } else {\n loc=srchStr.lastIndexOf(fndStr)+1;\n }\n return loc;\n}", "function findMatch(node, params) {\n\n var nodeValue = node.nodeValue.trim();\n var nodeIndex = params.nodeIndex;\n var searchTerm = params.searchTerm;\n var searchElements = params.searchElements;\n var field = params.field;\n var total = params.total;\n var count = params.count;\n var text = params.text;\n var currentIndex = params.currentIndex;\n\n if (text === \"\") {\n text = nodeValue;\n } else {\n text += \" \" + nodeValue;\n }\n console.log(\"nodeIndex: \" + nodeIndex + \" - \" + nodeValue);\n console.log(textNodes[nodeIndex]);\n\n // if searchTerm is found, current text node is the end node for one count\n var index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n\n // if there is multiple instances of searchTerm in text (loops through while loop), use oldStartIndex to calculate startIndex\n var oldStartIndex, startNodeIndex;\n\n // stores the number of characters the start of searchTerm is from the end of text\n var charactersFromEnd = text.length - index;\n //console.log(\"charactersFromEnd: \" + charactersFromEnd);\n\n // loop through text node in case there is more than one searchTerm instance in text\n while (index !== -1) {\n currentIndex = index;\n\n // remember how many text nodes before current node we are pulling from textNodes\n var textNodesBackIndex = nodeIndex - 1;\n console.log(textNodesBackIndex);\n\n // textSelection will contain a combined string of all text nodes where current searchTerm spans over\n var textSelection = nodeValue;\n var startNode;\n\n // set textSelection to contain prevSibling text nodes until the current searchTerm matches\n while (textSelection.length < charactersFromEnd) {\n console.log(\"textSelection.length: \" + textSelection.length + \" < \" + charactersFromEnd);\n //console.log(\"old textSelection: \" + textSelection);\n console.log(\"textnodesback index: \" + textNodesBackIndex + \" \" + textNodes[textNodesBackIndex].nodeValue);\n\n textSelection = textNodes[textNodesBackIndex].nodeValue.trim() + \" \" + textSelection;\n //console.log(\"space added: \" + textSelection);\n textNodesBackIndex--;\n }\n\n // use old startNodeIndex value before re-calculating it if its the same as new startNodeIndex\n // startIndex needs to ignore previous instances of text\n var startIndex;\n if (startNodeIndex != null && startNodeIndex === textNodesBackIndex + 1) {\n // find index searchTerm starts on in text node (or prevSibling)\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase(), oldStartIndex + 1);\n } else {\n startIndex = textSelection.toLowerCase().indexOf(searchTerm.toLowerCase());\n }\n oldStartIndex = startIndex;\n\n // startNode contains beginning of searchTerm and node contains end of searchTerm\n var startNodeIndex = textNodesBackIndex + 1;\n // possibly null parentNode because highlighted text before, adding MARK tag and then removed it\n startNode = textNodes[startNodeIndex];\n //console.log(\"final textSelection: \" + textSelection);\n\n if (startIndex !== -1) {\n // set parent as first element parent of textNode\n console.log(\"end parent\");\n console.log(node);\n var endParent = node.parentNode;\n\n console.log(\"start parent\");\n console.log(startNode);\n var startParent = startNode.parentNode;\n\n var targetParent;\n // start and end parents are the same\n if (startParent === endParent) {\n console.log(\"start parent is end parent\");\n targetParent = startParent;\n }\n // start parent is target parent element\n else if ($.contains(startParent, endParent)) {\n console.log(\"start parent is larger\");\n targetParent = startParent;\n }\n // end parent is target parent element\n else if ($.contains(endParent, startParent)) {\n console.log(\"end parent is larger\");\n targetParent = endParent;\n }\n // neither parents contain one another\n else {\n console.log(\"neither parent contains the other\");\n // iterate upwards until startParent contains endParent\n while (!$.contains(startParent, endParent) && startParent !== endParent) {\n startParent = startParent.parentNode;\n //console.log(startParent);\n }\n targetParent = startParent;\n }\n\n // set startNode to node before the parent we are calculating with\n if (textNodesBackIndex !== -1) {\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n\n var startElement = startNode.parentNode;\n\n // continue adding text length to startIndex until parent elements are not contained in targetParent\n while (($.contains(targetParent, startElement) || targetParent === startElement) && textNodesBackIndex !== -1) {\n startIndex += startNode.nodeValue.trim().length + 1;\n startNode = textNodes[textNodesBackIndex];\n textNodesBackIndex--;\n startElement = startNode.parentNode;\n }\n }\n\n // find index searchTerm ends on in text node\n var endIndex = startIndex + searchTerm.length;\n /*console.log(\"start index: \" + startIndex);\n console.log(\"end index: \" + endIndex);*/\n\n // if a class for field search already exists, use that instead\n var dataField = \"data-tworeceipt-\" + field + \"-search\";\n if ($(targetParent).attr(dataField) != null) {\n console.log(\"EXISTING SEARCH ELEMENT\");\n console.log($(targetParent).attr(dataField));\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: parseInt($(targetParent).attr(dataField)),\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n } else {\n searchElements[count] = {\n start: startIndex,\n end: endIndex,\n data: count,\n startNodeIndex: startNodeIndex,\n endNodeIndex: nodeIndex\n };\n console.log(\"NEW SEARCH ELEMENT\");\n $(targetParent).attr(dataField, count);\n console.log($(targetParent));\n }\n\n console.log(searchElements[count]);\n\n count++;\n } else {\n console.log(textSelection);\n console.log(searchTerm);\n }\n\n index = text.toLowerCase().indexOf(searchTerm.toLowerCase(), currentIndex + 1);\n charactersFromEnd = text.length - index;\n //console.log(\"characters from end: \" + charactersFromEnd);\n\n if (total != null && count === total) {\n console.log(\"Completed calculations for all matched searchTerms\");\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: false\n };\n }\n }\n nodeIndex++;\n return {\n nodeIndex: nodeIndex,\n searchTerm: searchTerm,\n searchElements: searchElements,\n field: field,\n total: total,\n count: count,\n text: text,\n currentIndex: currentIndex,\n result: true\n };\n}", "matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos)\n let start = Math.max(line.from, this.pos - 250)\n let str = line.text.slice(start - line.from, this.pos - line.from)\n let found = str.search(ensureAnchor(expr, false))\n return found < 0\n ? null\n : { from: start + found, to: this.pos, text: str.slice(found) }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
AVE SCORES This function will go through all the unique playerIDs in the main scoreboardhistory and calculate the average score and store the pair of ID and aveScore in a object within the array. hopefully this won't blow up this time but I promise it will work... don't give me that look I've learned from my mistakes! we are not sorting the list only making it
function aveScores(){ uniquePlayerIDCheck(); /* Yes yes I know this is a bad way to do it, but for now we just want to make sure we are not adding to the list again and this is quite a light program so we don't care too much about recalcuating the whole list again. So for now, we clear out the list and start over. */ scoreAveHistory = []; //next we are going to itterate through all the given ID's for(var i in uniquePlayers){ //next we need a variable for the score total and a variable for game total var scTotal=0; var gmTotal=0; for(var j in scoreBoardHistory){ //and if the ID we find is the same.. if(scoreBoardHistory[j].playerID == uniquePlayers[i]){ scTotal += parseInt(scoreBoardHistory[j].score); gmTotal ++; } } if(gmTotal == 0){ gmTotal =1; } //now we need to make an object and add it to the list var ave = scTotal / gmTotal; /* ADDED GAME TOTAL TO THE OBJECT!!! CHECK IF THIS WORKS */ var playerAve = {"playerID": uniquePlayers[i], "aveScore": ave, "gameTotal": gmTotal}; //and add the scores to the list scoreAveHistory.push(playerAve); } compareFunction(); for(var k in scoreAveHistory){ console.log(scoreAveHistory[k].playerID + ", " + scoreAveHistory[k].aveScore); } }
[ "function removePlayer(){\n\n\tvar exiledPlayer = document.getElementById(\"deletePlayer\").value;\n\nvar i = scoreBoardHistory.length\n\nwhile(i--){\n\tif (scoreBoardHistory[i].playerID == exiledPlayer){\n\t\tscoreBoardHistory.splice(i,1);\n\t}\n}\n//scoreBoardHistory.push({\"playerID\": exiledPlayer, \"score\": -1})\n\n\nfor(var j in scoreAveHistory){\n\tif(scoreAveHistory[j].playerID == exiledPlayer){\n\t\t//scoreAveHistory[j].aveScore = 0;\n\t\t//scoreAveHistory.splice(j,1); \n\t}\n}\n\naveScores();\n\ndrawTable();\ndrawTableAve();\ndocument.getElementById(\"totalNumOfScores\").innerHTML = countScores();\n}", "function averageTestScore(testScores) {\n let average = 0;\n for (const score of testScores) {\n average += score;\n }\n return average / testScores.length;\n}", "function analyze() {\n var highest = 0,\n lowest = 1000000000,\n averageQA = 0,\n averageAuton = 0,\n averageFouls = 0,\n totalNulls = 0,\n averagePlayoff = 0,\n totalPlayoffs = 0;\n\n for (var matchNum = 0; matchNum < matches.length; matchNum++) {\n\n var currentMatch = matches[matchNum];\n var currentMatchAlliances = currentMatch.alliances;\n var alliance = \"\";\n\n if (currentMatchAlliances.red.teams.indexOf(teamNumber) >= 0) {\n alliance = \"red\";\n } else {\n alliance = \"blue\";\n }\n\n if (currentMatchAlliances[alliance].score >= 0) {\n if (currentMatchAlliances[alliance].score > highest) {\n highest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatchAlliances[alliance].score < lowest) {\n lowest = currentMatchAlliances[alliance].score;\n }\n\n if (currentMatch.comp_level === 'qm') {\n averageQA += currentMatchAlliances[alliance].score;\n } else {\n averagePlayoff += currentMatchAlliances[alliance].score;\n totalPlayoffs++;\n }\n\n averageAuton += matches[matchNum].score_breakdown[alliance].atuo;\n\n averageFouls += matches[matchNum].score_breakdown[alliance].foul;\n\n } else {\n totalNulls++;\n }\n }\n\n if (totalPlayoffs !== 0) {\n averagePlayoff /= totalPlayoffs;\n }\n\n averageQA /= matches.length - totalNulls - totalPlayoffs;\n averageFouls /= matches.length - totalNulls;\n averageAuton /= matches.length - totalNulls;\n\n console.log('Analytics');\n console.log('Team Name: ' + teamName);\n console.log(\"Highest Number of points: \" + highest);\n console.log(\"Lowest Number of points: \" + lowest);\n console.log(\"Average QA: \" + averageQA);\n console.log(\"Average Playoff Points (If Applicable): \" + averagePlayoff);\n console.log(\"Average Auton points: \" + averageAuton);\n console.log(\"Average Foul points: \" + averageFouls);\n}", "function five_match_average(array_of_scores){\n five_match_score=array_of_scores.slice(0,5)\n total=0\n for(var x in five_match_score){\n total+=five_match_score[x]\n }\n console.log(total/5)\n}", "function getMatch() {\n var bestMatch = {\n scoreDifference:40,\n playerIndex:0\n };\n \n //Sum Recently Added User Score Array\n var recentScore = sumArray(friendsData[friendsData.length - 1].scores);\n\n //Compare userScore to other player scores\n for (var i=0; i<friendsData.length-1; i++ ) {\n\n //Get difference between userScore and score from player on list\n var difference = Math.abs(recentScore-sumArray(friendsData[i].scores));\n\n if (difference<bestMatch.scoreDifference) {\n bestMatch.scoreDifference = difference;\n playerIndex = i;\n }\n };\n\nconsole.log(friendsData[bestMatch.playerIndex]);\n}", "function calculateAverage(){\n\t// combined_average_video_confidence = 0\n\taverage_confidence_list = []\n\tfor(i = 0; i < grid.array.length; i++) {\n\t\tcurr_video = grid.array[i]\n\t\tsum_video_confidence = 0\n\t\tfor(j = 0; j < curr_video.grades.length; j++) {\n\t\t\tgrade = curr_video.grades[j]\n\t\t\tsum_video_confidence += grade.confidence\n\t\t}\n\t\taverage_video_confidence = sum_video_confidence / curr_video.grades.length\n\t\taverage_confidence_list.push(average_video_confidence)\n\t}\t\t\n\t// return combined_average_video_confidence /= grid.array.length\n\t// return calculateAverage\n\treturn average_confidence_list\n}", "function calculateAverage(){\n var sum = 0;\n for(var i = 0; i < self.video.ratings.length; i++){\n sum += parseInt(self.video.ratings[i], 10);\n }\n\n self.avg = sum/self.video.ratings.length;\n }", "function updateAverage($teams) {\n\tfor (var i = 0; i < $teams.length; i++) {\n\t\t$team = $($teams[i]);\n\t\tvar $players = $team.find('.player');\n\t\tvar n = 0;\n\t\tvar total = 0.0;\n\t\tvar nExp = 0;\n\t\tvar totalExp = 0.0;\n\t\tfor (var j = 0; j < $players.length; j++) {\n\t\t\tvar rating = parseInt($players.eq(j).attr('data-rating'));\n\t\t\tif (!isNaN(rating)) {\n\t\t\t\tn += 1;\n\t\t\t\ttotal += rating;\n\t\t\t}\n\t\t\tvar ratingExp = parseInt($players.eq(j).attr('data-exp-rating'));\n\t\t\tif (!isNaN(ratingExp)) {\n\t\t\t\tnExp += 1;\n\t\t\t\ttotalExp += ratingExp;\n\t\t\t}\n\t\t}\n\t\tif (n > 0) {\n\t\t\t$team.find('.average-rating').text((total / n).toFixed(2));\n\t\t} else {\n\t\t\t$team.find('.average-rating').text('');\n\t\t}\n\t\tif (nExp > 0) {\n\t\t\t$team.find('.average-exp-rating').text((totalExp / nExp).toFixed(2));\n\t\t} else {\n\t\t\t$team.find('.average-exp-rating').text('');\n\t\t}\n\t}\n}", "function getTotalScore() {\n\n let ai = 0;\n let human = 0;\n\n //Calculate pawn penalties\n //Number of pawns in each file\n let human_pawns = [];\n let ai_pawns = [];\n\n for (let x = 0; x < 8; x++) {\n\n let h_cnt = 0;\n let a_cnt = 0;\n\n for (let y = 0; y < 8; y++) {\n\n let chk_piece = board[y][x];\n\n if (chk_piece != null && chk_piece instanceof Pawn) {\n\n if (chk_piece.player == 'human') h_cnt++;\n else a_cnt++;\n\n //Pawn rank bonuses\n if (x > 1 && x < 6) {\n\n //Normalize y to chess rank 1 - 8\n let rank = (chk_piece.player == 'human') ? Math.abs(y - 7) + 1 : y + 1;\n\n switch (x) {\n\n case 2:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 3.9 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 3.9 * (rank - 2);\n break;\n\n case 3:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 5.4 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 5.4 * (rank - 2);\n break;\n\n case 4:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 7.0 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 7.0 * (rank - 2);\n break;\n\n case 5:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 2.3 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 2.3 * (rank - 2);\n break;\n\n }\n\n }\n\n }\n\n }\n\n human_pawns.push(h_cnt);\n ai_pawns.push(a_cnt);\n\n }\n\n for (let i = 0; i < 8; i++) {\n\n //Doubled pawn penalty\n if (human_pawns[i] > 1) human -= (8 * human_pawns[i]);\n if (ai_pawns[i] > 1) ai += (8 * ai_pawns[i]);\n\n //Isolated pawn penalties\n if (i == 0) {\n if (human_pawns[i] > 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else if (i == 7) {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n\n }\n\n //Get material score\n for (let y = 0; y < 8; y++) {\n\n for (let x = 0; x < 8; x++) {\n\n if (board[y][x] != null) {\n\n let piece = board[y][x];\n\n //Material\n if (piece.player == 'human') human += piece.score;\n else ai += piece.score; \n\n //Knight bonuses/penalties \n if (piece instanceof Knight) {\n\n //Center tropism\n let c_dx = Math.abs(3.5 - x);\n let c_dy = Math.abs(3.5 - y);\n\n let c_sum = 1.6 * (6 - 2 * (c_dx + c_dy));\n\n if (piece.player == 'human') human += c_sum;\n else ai -= c_sum;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n ai -= k_sum;\n\n }\n\n }\n\n //Rook bonuses/penalties\n else if (piece instanceof Rook) {\n\n //Seventh rank bonus\n if (piece.player == 'human' && y == 1) human += 22;\n else if (piece.player == 'ai' && y == 6) ai -= 22;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n //Doubled rook bonus\n //Check rank\n let left_chk = true;\n let right_chk = true;\n let up_chk = true;\n let down_chk = true;\n for (let i = 1; i < 8; i++) {\n\n if (!left_chk && !right_chk && !down_chk && !up_chk) break;\n\n //Check left side\n if (x - i >= 0 && left_chk) {\n\n let chk_piece = board[y][x - i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else left_chk = false;\n }\n\n } else left_chk = false;\n\n //Check right side\n if (x + i < 8 && right_chk) {\n\n let chk_piece = board[y][x + i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else right_chk = false;\n }\n\n } else right_chk = false;\n\n //Check up side\n if (y - i >= 0 && up_chk) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else up_chk = false;\n }\n\n } else up_chk = false;\n\n //Check down side\n if (y + i < 8 && down_chk) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else down_chk = false;\n }\n\n } else down_chk = false;\n\n }\n\n //Doubled rook found\n if (left_chk || right_chk || down_chk || up_chk) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n //Open file bonus\n let open_file = true;\n\n for (let i = 1; i < 8; i++) {\n\n //Check up\n if (y - i >= 0) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n //Check down\n if (y + i < 8) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n }\n\n if (open_file) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n\n }\n\n //Queen bonuses/penalties\n else if (piece instanceof Queen) {\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n }\n\n //King bonuses/penalties\n else if (piece instanceof King) {\n\n //Cant castle penalty\n if (!piece.hasCastled) {\n\n //Castling no longer possible as king has moved at least once\n if (!piece.firstMove) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n\n } else {\n\n //Rooks\n let q_rook;\n let k_rook;\n\n //Check flags, true if castling is available\n let q_rook_chk = false;\n let k_rook_chk = false;\n\n if (piece.player == 'human') {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n }\n\n } else {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n }\n\n }\n\n q_rook_chk = q_rook != null && q_rook.firstMove;\n k_rook_chk = k_rook != null && k_rook.firstMove;\n\n //Castling no longer available\n if (!q_rook_chk && !k_rook_chk) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n \n }\n //Queen side castling not available\n else if (!q_rook_chk) {\n\n if (piece.player == 'human') human -= 8;\n else ai += 8;\n\n }\n //King side castling not available\n else if (!k_rook_chk) {\n\n if (piece.player == 'human') human -= 12;\n else ai += 12;\n\n }\n\n }\n\n //Check kings quadrant\n let enemy_pieces = 0;\n let friendly_pieces = 0;\n\n //Find quadrant\n //Top/Left\n if (y < 4 && x < 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Top/Right\n else if (y < 4 && x >= 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Left\n else if (y >= 4 && x < 4) {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Right\n else {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n if (enemy_pieces > friendly_pieces) {\n\n let diff = enemy_pieces - friendly_pieces;\n\n if (piece.player == 'human') human -= (5 * diff);\n else ai += (5 * diff);\n\n }\n\n }\n\n }\n\n //Bishop bonuses/penalties\n if (piece instanceof Bishop) {\n\n //Back rank penalty\n if (piece.player == 'human' && y == 7) human -= 11;\n else if (piece.player == 'ai' && y == 0) ai += 11;\n\n //Bishop pair bonus\n let pair = false;\n\n for (let i = 0; i < 8; i++) {\n\n for (let j = 0; j < 8; j++) {\n\n if (i == y && j == x) continue;\n\n let chk_piece = board[i][j];\n\n if (chk_piece != null && chk_piece.player == piece.player && chk_piece instanceof Bishop) {\n pair = true;\n break;\n }\n\n }\n\n }\n\n if (pair && piece.player == 'human') human += 50;\n else if (pair && piece.player == 'ai') ai -= 50;\n\n //Pawn penalties\n let p_cntr = 0;\n\n //Top left\n if (x - 1 >= 0 && y - 1 >= 0 && board[y - 1][x - 1] != null && board[y - 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Top right\n if (x + 1 < 8 && y - 1 >= 0 && board[y - 1][x + 1] != null && board[y - 1][x + 1] instanceof Pawn) p_cntr++;\n\n //Bottom left\n if (x - 1 >= 0 && y + 1 < 8 && board[y + 1][x - 1] != null && board[y + 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Bottom right\n if (x + 1 < 8 && y + 1 < 8 && board[y + 1][x + 1] != null && board[y + 1][x + 1] instanceof Pawn) p_cntr++;\n\n if (piece.player == 'human') human -= (p_cntr * 3);\n else ai += (p_cntr * 3);\n\n }\n\n\n \n }\n\n }\n\n }\n\n return ai + human;\n\n}", "function addScore() {\n var input = nameInput.value;\n\n var user = {name: input, score: timer};\n // add new score to array\n leaderboardArr.push({name: input, score: timer});\n\n // updates array in local storage\n localStorage.setItem(\"leaderboard\", JSON.stringify(leaderboardArr));\n\n hideElement(endPageDiv);\n displayLeaderboard();\n highlightUserScore(user);\n}", "function printAverageGrade(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) { //iterates through students\n // console.log(students[i][\"name\"],students[i][\"grades\"] );\n let student = students[i];\n let grades = student.grades;\n // let bestGrade = grades[0].score;\n // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one\n //so we then need to compare all the grades in that array\n let sum = 0;\n for (let j = 0; j < grades.length; j++) { //iterates through grades\n sum += grades[j].score;\n\n }\n let avgScore = sum / grades.length;\n console.log(student.name, avgScore);\n }\n}", "function runGame() {\n numOfFrames = 10;\n var frames = [];\n var totScore = 0;\n\n for (var i = 0; i < numOfFrames; i++) {\n frames.push(scores(0, 11, i, frames));\n totScore += addCurrentScore(frames[i]);\n }\n console.log(frames);\n console.log(totScore);\n\n // console.log(frames[9][0]);\n}", "UPDATE_OPP_ATHLETE_STATISTICS(state) {\n let result = [];\n\n for (let athlete in state.oppRoster) {\n result.push(\n {\n name: state.oppRoster[athlete].name,\n number: state.oppRoster[athlete].number,\n points:0,\n freethrow: 0,\n freethrowAttempt: 0,\n freethrowPercentage:0,\n twopoints: 0,\n twopointsAttempt: 0,\n twopointsPercentage:0,\n threepoints: 0,\n threepointsAttempt: 0,\n threepointsPercentage:0,\n assists: 0,\n blocks: 0,\n rebounds: 0,\n steals: 0,\n turnovers: 0,\n foul: 0\n }\n );\n }\n\n // For each game action, update athlete statistics accordingly.\n for (let index in state.gameActions) {\n let currentAction = state.gameActions[index];\n if (currentAction.team !== \"opponent\") {\n continue;\n }\n let athlete_index = -1;\n for (let athlete in state.oppRoster) {\n if (state.oppRoster[athlete].key == \"athlete-\" + currentAction.athlete_id) {\n athlete_index = athlete;\n break;\n }\n }\n\n // Continue when an athlete has been removed.\n if (athlete_index === -1) {\n continue;\n }\n\n switch (currentAction.action_type) {\n case \"Freethrow\":\n result[athlete_index].freethrow++;\n result[athlete_index].freethrowAttempt++;\n result[athlete_index].points++;\n result[athlete_index].freethrowPercentage=result[athlete_index].freethrow/result[athlete_index].freethrowAttempt*100;\n result[athlete_index].freethrowPercentage=parseFloat(result[athlete_index].freethrowPercentage).toFixed(1);\n break;\n\n case \"FreethrowMiss\":\n result[athlete_index].freethrowAttempt++;\n result[athlete_index].freethrowPercentage=result[athlete_index].freethrow/result[athlete_index].freethrowAttempt*100;\n result[athlete_index].freethrowPercentage=parseFloat(result[athlete_index].freethrowPercentage).toFixed(1);\n break;\n\n case \"2Points\":\n result[athlete_index].twopoints++;\n result[athlete_index].twopointsAttempt++;\n result[athlete_index].points+2;\n result[athlete_index].twopointsPercentage=result[athlete_index].twopoints/result[athlete_index].twopointsAttempt*100;\n result[athlete_index].twopointsPercentage=parseFloat(result[athlete_index].twopointsPercentage).toFixed(1);\n break;\n\n case \"2PointsMiss\":\n result[athlete_index].twopointsAttempt++;\n result[athlete_index].twopointsPercentage=result[athlete_index].twopoints/result[athlete_index].twopointsAttempt*100;\n result[athlete_index].twopointsPercentage=parseFloat(result[athlete_index].twopointsPercentage).toFixed(1);\n break;\n\n case \"3Points\":\n result[athlete_index].threepoints++;\n result[athlete_index].threepointsAttempt++;\n result[athlete_index].points+3;\n result[athlete_index].threepointsPercentage=result[athlete_index].threepoints/result[athlete_index].threepointsAttempt*100;\n result[athlete_index].threepointsPercentage=parseFloat(result[athlete_index].threepointsPercentage).toFixed(1);\n break;\n \n case \"3PointsMiss\":\n result[athlete_index].threepointsAttempt++;\n result[athlete_index].threepointsPercentage=result[athlete_index].threepoints/result[athlete_index].threepointsAttempt*100;\n result[athlete_index].threepointsPercentage=parseFloat(result[athlete_index].threepointsPercentage).toFixed(1);\n break;\n\n case \"Assist\":\n result[athlete_index].assists++;\n break;\n\n case \"Blocks\":\n result[athlete_index].blocks++;\n break;\n\n case \"Steals\":\n result[athlete_index].steals++;\n break;\n\n case \"Rebound\":\n result[athlete_index].rebounds++;\n break;\n\n case \"Turnover\":\n result[athlete_index].turnovers++;\n break;\n\n case \"Foul\":\n result[athlete_index].foul++;\n break;\n\n default:\n break;\n }\n }\n\n state.oppAthleteStatistics = result;\n }", "function printBestStudent(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) { //iterates through students\n // console.log(students[i][\"name\"],students[i][\"grades\"] );\n let student = students[i];\n let grades = student.grades;\n // let bestGrade = grades[0].score;\n // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one\n //so we then need to compare all the grades in that array\n let sum = 0;\n for (let j = 0; j < grades.length; j++) { //iterates through grades\n sum += grades[j].score;\n\n }\n let avgScore = sum / grades.length;\n console.log(\"Test \"+ student.id+\": \"+student.name);\n }\n}", "function average() {\n\tvar total = 0;\n\tfor (var i = 0; i < this.grades.length; ++i) {\n\t\ttotal += this.grades[i];\n\t}//end for\n\treturn print(total / this.grades.length);\n}//end average function", "function calculateAverage(ratings){\n var sum = 0;\n for(var i = 0; i < ratings.length; i++){\n sum += parseInt(ratings[i], 10);\n }\n\n var avg = sum/ratings.length;\n\n return avg;\n }", "function calculateScore() {\n for (var i = 0; i < quizLength; i++){\n if (userAnswers[i][1]) {\n quiz[\"questions\"][i][\"global_correct\"]+=1;\n score++;\n }\n quiz[\"questions\"][i][\"global_total\"]+=1;\n }\n}", "function updateScore(cardArr) {\n var aces = 0,\n sum = 0;\n \n sum = cardArr.reduce(function(score, card) {\n if (!card.back) score += card.value;\n if (card.value == 11) aces += 1;\n return score;\n }, 0);\n\n for (var i = 0; i < aces; i += 1) {\n if (sum > 21) sum -= 10;\n }\n\n console.log('[ jack ] updated score: ' + sum );\n return sum;\n}", "sortLeaderboard () {\n // Build the array to be sorted that will contain all the leaderboard information\n let sortedLeaderboard = []\n const leaderboard = this.state.leaderboard\n\n for (var key in leaderboard) {\n if (leaderboard.hasOwnProperty(key)) {\n if (this.checkFilters(leaderboard[key])) {\n sortedLeaderboard.push(leaderboard[key])\n }\n }\n }\n\n sortedLeaderboard.sort((a, b) => b.score - a.score)\n\n for (var i in sortedLeaderboard) {\n sortedLeaderboard[i].position = parseInt(i, 10) + 1\n }\n if (!this.state.showAll) {\n sortedLeaderboard = this.snipTableData(sortedLeaderboard)\n }\n return sortedLeaderboard\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of attached views.
get viewCount() { return this._views.length; }
[ "getNumberOfImagesLoaded(){\n\t\treturn this.loadedImages.length;\n\t}", "function getNumberOfTablegroups(){\n // Take the contents of the view\n var originalView = tabsFrame.fileContents;\n \n // Convert it into an object\n var myView = new Ab.ViewDef.View();\n var myConverter = new Ab.ViewDef.Convert(originalView, \"myView\");\n myConverter.convertDo();\n \n // Extract the relevant pieces\n var convertedContents = myConverter.getConvertedContentsAsJavascript();\n eval(convertedContents);\n \n // Get the number of tableGroups\n var numberOfTableGroups = myView.tableGroups.length;\n \n return numberOfTableGroups\n}", "getViews() {\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_16__[\"default\"])(this.viewManager);\n return this.viewManager.views;\n }", "function getAliveCount() {\n\tvar count = 0;\n\tcells.map(function(alive) {\n\t\tif (alive) count++;\n\t});\n\treturn count;\n}", "function numberOfElements(){\n var count = document.getElementsByTagName('div').length;\n console.log('There are ' + count + ' DIVs. in the HTML page');\n}", "function getNumberOfLayers() {\r\n\tvar desc = getDocumentPropertyDescriptor(TID.numberOfLayers);\r\n\tvar numberOfLayers = desc.getInteger(TID.numberOfLayers);\r\n\treturn numberOfLayers;\r\n}", "numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }", "function countElements() {\n var theCount = $(\"*\").css(\"padding\", \"1px\").length;\n console.log(\"There are \" + theCount + \" elements\");\n }", "function countImages() {\r\n // console.log('Init images count');\r\n var $galleryTiles = $('.gallery-tile');\r\n var imagesLength = $galleryTiles.length;\r\n var $currentImg = $('#imagelightbox');\r\n var currentImageNumber = 1;\r\n for (var i = 0; i < imagesLength; i++) {\r\n if ($galleryTiles[i].href === $curentImageContainer[0].href) {\r\n currentImageNumber = i + 1;\r\n };\r\n };\r\n $imagesCounter.text(currentImageNumber + '/' + imagesLength);\r\n }", "count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }", "getNumTasks() {\n return Tasks.find({owner:Meteor.userId()}).count();\n }", "getSelectedCount()\n {\n return Object.keys(this._selectedItems).length;\n }", "function count_controls() {\n\t\tvar count = 0,\n\t\t\t\tid;\n\t\tfor (id in controls.lookup) {\n\t\t\tif (controls.lookup.hasOwnProperty(id)) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}", "function numOfTotalEnemies() {\n\tconst totalEnemies = gameState.enemies.getChildren().length;\n return totalEnemies;\n}", "function countFrames () {\n\treturn $(\".frame\").length - 1;\n}", "function refCount(pubs) {\n var total = 0;\n if (pubs) {\n pubs.forEach(function(pub) {\n total += pub.references ? pub.references.length : 0;\n });\n }\n return total;\n}", "function getPatientNumber() {\r\n return Object.keys(self.patients).length;\r\n }", "function countDOMElements(node) {\r\n return (node && node.getElementsByTagName('*').length) || 0;\r\n }", "function getCurrentVisitorCount () {\n console.log(\"current visitor count requested\", connectionCount)\n return connectionCount;\n }", "get depth() {\n let d = 0;\n for (let p = this.parent; p; p = p.parent)\n d++;\n return d;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the pomodoro items ,that has status 'none', status 'failed'
fillRemainedPomodoros(){ for(let i = 0; i < this.data.pomodoros.length; i++){ if(this.data.pomodoros[i].status === "none") this.data.pomodoros[i].status = "failed"; } this.data.estimationUsed = this.data.estimationTotal; this.data.isActive = false; Firebase.updateValue(this.data).then(() => { Notification().showMessage("success", "You completed task!"); }).catch((err) => { Notification().showMessage("error", "Oops! Error was occurred!" + err.message); }); }
[ "completeAllItems() {\n this.items.forEach(item => {\n item.status = 'Completed';\n item.finishedAt = Date.now;\n });\n }", "setEstimation(data){\r\n let index;\r\n\r\n this.data.pomodoros.find((pomodoro, i) => {\r\n if(pomodoro.status === \"none\"){\r\n index = i;\r\n return pomodoro;\r\n }\r\n });\r\n\r\n this.data.pomodoros[index].status = data.status;\r\n this.data.estimationUsed++;\r\n\r\n Firebase.updateValue(this.data).catch((err) => {\r\n Notification().showMessage(\"error\", \"Oops! Error was occurred! \" + err.message);\r\n });\r\n }", "function setBuzzerStatus(){\n $interval.cancel(contdownDecreaseInterval);\n\n if (!checkIfExcluded()) {\n if (self.buzzerEnabled) {\n self.buzzerState = buzzerState.enabled;\n self.buzzerText = 'BUZZ!!!!!!';\n } else {\n self.buzzerState = buzzerState.disabled;\n self.buzzerText = 'DISABLED';\n }\n } else {\n self.buzzerState = buzzerState.excluded;\n self.buzzerText = 'EXCLUDED';\n self.buzzerEnabled = false;\n }\n }", "updateListItemStatus(number) {\n this.setState({\n listItems: this.state.listItems.filter(\n function(c, i) {\n if (i == number) {\n c.done = c.done ? false : true;\n }\n return c;\n })\n });\n }", "checkPomodoros(){\r\n return this.data.pomodoros.every((pomodoro) => {\r\n return pomodoro.status !== \"none\";\r\n });\r\n }", "async function setItemState(state) {\n switch (itemType) {\n case ItemType.issue:\n await client.rest.issues.update({\n owner: item.owner,\n repo: item.repo,\n issue_number: item.number,\n state: state,\n });\n break;\n\n case ItemType.pr:\n await client.rest.pulls.update({\n owner: item.owner,\n repo: item.repo,\n pull_number: item.number,\n state: state,\n });\n break;\n }\n}", "function setNewPresence() {\n // Select a random activity\n const settings = names[Math.floor(Math.random()*names.length)];\n\n // Set the status\n client.user.setPresence(settings);\n }", "function updateStatus() {\n\tfor (let i = 0; i < inputs.length; i++) {\n\t\tif (inputs[i].checked === true) {\n\t\t\tlistItems[i].classList.add('completed');\n\t\t\ttasks[i].completed = true;\n\t\t} else {\n\t\t\tlistItems[i].classList.remove('completed');\n\t\t\ttasks[i].completed = false;\n\t\t}\n\t}\n\n\t// d) Tareas totales. Cada vez que una tarea se marque/desmarque deberíamos actualizar esta información.\n\n\tlet message = document.querySelector('.message');\n\n\tlet completedTasks = document.querySelectorAll('input:checked').length;\n\n\tlet incompleteTasks = parseInt(tasks.length) - parseInt(completedTasks);\n\n\t// Actualizamos mensaje\n\tmessage.innerHTML = `Tienes ${tasks.length} tareas. ${completedTasks} completadas y ${incompleteTasks} por realizar.`;\n}", "function set_game_status(s) {\n current_status = s;\n // additional options\n switch(s) {\n case status.game_over: {\n set_action_zone(zone.game_over);\n toggle_menu_action(\"both\", true);\n clearInterval(gamer.timer.interval);\n set_menu_item_text(menu_items.game_control, \"Restart\");\n } break;\n case status.done: {\n set_action_zone(zone.complete);\n toggle_menu_action(\"both\", true);\n clearInterval(gamer.timer.interval);\n\n // Convert to unused moves into score\n set_stat(stat_types.score, gamer.score + gamer.shoots * map.shoot_score);\n global_score = gamer.score;\n\n // change the Complete zone stats\n $(\"#congratulation-level-span\").text(gamer.level);\n $(\"#congratulation-score-span\").text(gamer.score);\n $(\"#congratulation-time-span\").text(gamer.timer.minute + \" min \" + gamer.timer.second + \" sec\");\n\n set_menu_item_text(menu_items.game_control, \"Next Level\");\n } break;\n case status.fail: {\n set_stat(stat_types.lives, gamer.lives - 1);\n if(gamer.lives <= 0) {\n global_score = gamer.score;\n setTimeout(function() {\n set_game_status(status.game_over);\n\n // change the game over stats\n $(\"#failed-level-span\").text(gamer.level);\n $(\"#failed-score-span\").text(gamer.score);\n $(\"#failed-time-span\").text(gamer.timer.minute + \" min \" + gamer.timer.second + \" sec\");\n\n db_insert_new_item();\n }, 300);\n } else {\n set_action_zone(zone.oops);\n\n // Pretend a good positioned shot\n set_stat(stat_types.shoots, gamer.shoots - 1);\n load_next_planet();\n\n // RESET THE LEVEL\n reset_current_level();\n\n // Get back to the game after one sec\n setTimeout(function(){\n set_action_zone(zone.game);\n set_game_status(status.running);\n }, 1000);\n }\n } break;\n }\n }", "function setAllPipeElementsStatuses(status) {\n\t\tstatus = status.toLowerCase();\n\t\tRED.nodes.eachNode(function(node) {\n\t\t\tnode.deployStatus = status;\n\t\t\tnode.dirty = true;\n\t\t});\n\t}", "function changeTodoAsIncomplete(index) {\n var obj = todos[index];\n obj.isDone = false;\n storeTodos();\n displayTodoItems(todos);\n }", "function resetDialogueValues() {\n var i, resourceInstance,\n listResources = Variable.findByName(gm, 'resources');\n for (i = 0; i < listResources.items.size(); i++) {\n resourceInstance = listResources.items.get(i).getInstance(self);\n resourceInstance.setProperty('isAdvised', false);\n resourceInstance.setProperty('isConsidered', false);\n resourceInstance.setProperty('bonusInducement', 0);\n }\n}", "function fillInEmptyBlocks() {\n vm.numberOfRealPlayers = vm.competition.players.length;\n for (var i = vm.competition.players.length; i < vm.numberOfBlocks; i++) {\n vm.competition.players.push({\n firstName: 'Empty',\n lastName: 'Spot',\n displayName: 'Empty Spot',\n position: 99,\n class: 'empty',\n _id: 'XX'\n });\n }\n // We have to give levels to the new empty spots\n assignLevelsToPlayers();\n }", "function LimpaCamposCadastraTime() {\n $('#CadastraTime_Nome').val(\"\");\n $('.NumeroParaCriterioDeChaveDeClassificacao').val(\"\");\n $('#BotaoCadastraTime').prop('disabled', true);\n\n var Modalidades = $('.CadastraTime_Modalidades').find('.CadastraTime_ModalidadeItem');\n Modalidades.each(function () {\n this.checked = false;\n }); \n }", "function changeStatus() {\t\n\t\tseatNum = this.querySelector(\".seat-number\").innerHTML;\n\t\t\n\t\tif (this.className === \"empty\") {\n\t\t\t//if this seat is empty do dis\n\t\t\t\n\t\t\tgetForm();\n\n\t\t\tthis.setAttribute(\"class\", \"full\");\n\t\t\tseatImage = this.querySelector(\".chair-image\");\n\t\t\tseatImage.setAttribute(\"src\", \"images/chair-full.jpg\");\n\n\t\t} else {\n\t\t\t// if full uncheck :(\n\n\t\t\tthis.setAttribute(\"class\", \"empty\");\n\t\t\tseatImage = this.querySelector(\".chair-image\");\n\t\t\tseatImage.setAttribute(\"src\", \"images/chair-empty.jpg\");\n\n\t\t}\n\t}", "set_status_code(status_code, reason){\n if(status_code === this.status_code) {} //no change, do nothing\n else if (Job.status_codes.includes(status_code)){ //valid status code\n this.status_code = status_code\n if ([\"waiting\", \"suspended\"].includes(status_code)) {\n if(reason !== undefined){\n this.wait_reason = reason\n }\n this.stop_reason = null\n }\n else if (this.is_done()) {\n if(reason !== undefined){\n this.wait_reason = null\n this.stop_reason = reason\n }\n }\n else if (status_code === \"stopping\") { //see Dexter.\n\n }\n else if (status_code === \"running_when_stopped\"){\n\n }\n else { //\"not_started\", \"starting\", \"running\"\n //these status codes don't have reasons so any passed in reason is ignored.\n this.wait_reason = null\n this.stop_reason = null\n }\n this.color_job_button() //the main call to color_job_button\n }\n else {\n shouldnt(\"set_status_code passed illegal status_code of: \" + status_code +\n \"<br/>The valid status codes are:</br/>\" +\n Job.status_codes)\n }\n }", "function toggleTodoCompleted(item_li) {\n var item = get_li_item(item_li);\n var id = item.get(\"id\");\n if (item.get(\"state\") == \"completed\") {\n // Mark as active\n item.set({state:\"active\", completed_at:null});\n item.save();\n console.log(\"item id \" + id + \" marked as open.\");\n }\n else {\n // Mark as completed\n item.set({state:\"completed\", completed_at:new Date().toISOString()});\n item.save();\n console.log(\"item id \" + id + \" marked as completed.\");\n }\n}", "function massactionsChangeMessagePoke()\n\t{\n\t\t// Daten sammeln\n\t\tvar group_id \t\t\t= \t$('#selectMessagePokeGroup').val();\n\t\tvar who\t\t\t\t\t=\t$(\"#selectMessagePokeGroup\").find(':selected').attr('group');\n\t\tvar channel\t\t\t\t=\t$('#selectMessagePokeChannel').val();\n\t\tvar group\t\t\t\t=\t'none';\n\t\tvar res \t\t\t\t= \tgroup_id.split(\"-\");\t// res[3]\n\t\t\n\t\tif(who != 'all')\n\t\t{\n\t\t\tgroup\t\t=\tres[3];\n\t\t};\n\t\t\n\t\t// Daten in Funktion übergeben\n\t\tmassactionsMassInfo(who, group, channel, 'msg');\n\t}", "function populateModal(){\n //add options in alarm\n addOption($(\"#hpick\").empty(), isAmPm ? 12 : 23);\n addOption($(\"#mpick\").empty(), 60);\n addOption($(\"#spick\").empty(), 60);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CODING CHALLENGE 417 Create a function that takes an array of students and returns an array of their top notes. If student does not have notes then let's assume their top note is equal to 0.
function getStudentTopNotes(students) { return students.map(x => Math.max(...x.notes, 0)); }
[ "function leader (array){\n\tvar max = array[0];\n\tvar newarr=[];\n\tfor ( var i =0 ; i<array.length;i++){\n\t\tif (max>array[i+1]){\n\t\t\tnewarr.push(array[i])\n\t\t}\n\t\ti++\n\t\tif(array[i]>array[i+1]){\n\t\t\ti++\n\t\tnewarr.push(array[i+1])\n\t}\n\t}\n\t\treturn newarr\n}", "function mostProlificAuthor(authors) {\n // Your code goes here\n\n let x = bookCountsByAuthor(authors);\n // console.log(x);\n\n const compare = (a, b) => {\n let comparison = 0;\n if (a.bookCount > b.bookCount) {\n comparison = 1;\n } else if (a.bookCount < b.bookCount) {\n comparison = -1;\n }\n return comparison;\n };\n let y = x.sort(compare);\n console.log(y);\n\n return y.pop();\n\n // let x = authors.map(author => author.books.length);\n // console.log(x);\n // // let y = Math.max(...x);\n // // return authors.forEach(author => {\n // // if (author.books.length === y) {\n // // console.log(author.name);\n // // }\n // // });\n\n // if (bookCountsByAuthor(authors).bookCount)\n}", "highestMarks(marks) {\n let mark = Object.values(marks[0]).map(element => {\n return parseInt(element);\n });\n return Math.max(...mark);\n }", "function extractMax(table, studentArray, houseName) {\n let currentRank = table.getRank(houseName, studentArray[0]);\n let newRank = 0;\n // the highest rank \"bubbles\" to the end of the array\n for (let i = 0; i < studentArray.length - 1; i++) {\n newRank = table.getRank(houseName, studentArray[i + 1]);\n if (currentRank > newRank) {\n let temp = studentArray[i];\n studentArray[i] = studentArray[i + 1];\n studentArray[i + 1] = temp;\n } else {\n currentRank = newRank;\n }\n }\n let student = studentArray.pop();\n return student;\n}", "function top(array, compare, n) {\n if (n === 0) {\n return [];\n }\n var result = array.slice(0, n).sort(compare);\n topStep(array, compare, result, n, array.length);\n return result;\n}", "function tallestPerson (array) {\n return reduce (array , function (tallest , element) {\n if (tallest < element) { \n tallest = element } ;\n return tallest ;\n }) ;\n}", "sortMarkUsers(users)\n {\n return users.sort((a, b) => b.final_mark - a.final_mark);\n }", "function majorityElement(nums) {\n nums.sort()\n return nums[Math.floor(nums.length / 2)]\n}", "function greaterThanSecond(arr) {}", "function printBestGrade(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) { //iterates through students\n // console.log(students[i][\"name\"],students[i][\"grades\"] );\n let student = students[i];\n let grades = student.grades;\n let bestGrade = grades[0].score;\n // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one\n //so we then need to compare all the grades in that array\n\n for (let j = 0; j < grades.length; j++) { //iterates through grades\n let score = grades[j].score;\n //now check and see if bestGrade < score\n //if yes then bestGrade = score\n if (bestGrade < score) {\n bestGrade = score;\n }\n\n }\n console.log(student.name, bestGrade);\n }\n}", "function printBestStudent(students) {\n //your code here...\n for (let i = 0; i < students.length; i++) { //iterates through students\n // console.log(students[i][\"name\"],students[i][\"grades\"] );\n let student = students[i];\n let grades = student.grades;\n // let bestGrade = grades[0].score;\n // console.log(bestGrade); //This is how we index down to one specific grade, in this case it ill be the first one\n //so we then need to compare all the grades in that array\n let sum = 0;\n for (let j = 0; j < grades.length; j++) { //iterates through grades\n sum += grades[j].score;\n\n }\n let avgScore = sum / grades.length;\n console.log(\"Test \"+ student.id+\": \"+student.name);\n }\n}", "function highestGrade() {\n let sortOrderArray = scores.sort(function(a, b) \n { return b - a});\n console.log(\"Highest Grade: \", sortOrderArray[0]);\n}", "function printBestStudents(students) {\n var bestScores = {};\n\n for (var i = 0; i < students.length; i++) {\n var student = students[i];\n\n for(var j = 0; j < student.grades.length; j ++){\n var grade = student.grades[j];\n\n if(bestScores[grade.id] === undefined){\n bestScores[grade.id] = {name: student.name, score: grade.score};\n }\n else if (bestScores[grade.id].score < grade.score) {\n bestScores[grade.id] = {name: student.name, score: grade.score};\n }\n }\n }\n\n for(var id in bestScores){\n console.log(\"Test\", id, \":\", bestScores[id].name);\n }\n}", "function largestEvenNum(arr) {\n return arr.filter((x) => x % 2 === 0).reduce((a, b) => (a > b ? a : b));\n}", "function sweetestIcecream(arr) {\n\treturn arr.map(x => {\n\t\tif (x.flavor === 'Plain') return 0 + x.numSprinkles;\n\t\tif (x.flavor === 'Vanilla') return 5 + x.numSprinkles;\n\t\tif (x.flavor === 'ChocolateChip') return 5 + x.numSprinkles;\n\t\tif (x.flavor === 'Strawberry') return 10 + x.numSprinkles;\n\t\tif (x.flavor === 'Chocolate') return 10 + x.numSprinkles;\t\n\t}).sort((a, b) => b - a)[0];\n}", "function GetTopBooks(n, criterion) {\n\n}", "function lowestGrade() {\n let sortOrderArray = scores.sort(function(a, b) \n { return a - b});\n console.log(\"Lowest Grade: \", sortOrderArray[0]);\n}", "function firstLastKNums (arr) {\n let countNums = arr[0];\n console.log(arr.slice(1, countNums + 1).join(' '));\n console.log(arr.slice(arr.length - countNums, arr.length).join(' '));\n}", "function incrementToTop(arr) {\n let biggestElem = Math.max(...arr);\n return arr.reduce((a,b) => { return a + (biggestElem - b) },0 );\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check whether a task is ready (does it pass all the checks)
function testReady(task) { return (task.checks || []).reduce(function(memo, check) { return memo && check(pc, task); }, true); }
[ "__isReady() {\n return this.allRequiredStanzasProcessed;\n }", "function checkTasksState() {\n var i, j, k, listTasks = Variable.findByName(gm, 'tasks'), taskDescriptor, taskInstance,\n newWeek = Variable.findByName(gm, 'week').getInstance(self), inProgress = false,\n listResources = Variable.findByName(gm, 'resources'), resourceInstance, assignment,\n newclientsSatisfaction = Variable.findByName(gm, 'clientsSatisfaction').getInstance(self);\n for (i = 0; i < listTasks.items.size(); i++) {\n inProgress = false;\n taskDescriptor = listTasks.items.get(i);\n taskInstance = taskDescriptor.getInstance(self);\n for (j = 0; j < listResources.items.size(); j++) {\n resourceInstance = listResources.items.get(j).getInstance(self);\n if (resourceInstance.getActive() == true) {\n for (k = 0; k < resourceInstance.getAssignments().size(); k++) {\n assignment = resourceInstance.getAssignments().get(k);\n if (assignment.getTaskDescriptorId() == taskInstance.getDescriptorId() && taskInstance.getActive() == true) {\n inProgress = true;\n }\n }\n }\n }\n if (inProgress ||\n (newWeek.getValue() >= taskDescriptor.getProperty('appearAtWeek') &&\n newWeek.getValue() < taskDescriptor.getProperty('disappearAtWeek') &&\n newclientsSatisfaction.getValue() >= taskDescriptor.getProperty('clientSatisfactionMinToAppear') &&\n newclientsSatisfaction.getValue() <= taskDescriptor.getProperty('clientSatisfactionMaxToAppear') &&\n taskInstance.getDuration() > 0\n )\n ) {\n taskInstance.setActive(true);\n }\n else {\n taskInstance.setActive(false);\n }\n }\n}", "function waitReady() {\n ready = getStore().getState().blocksSaveDataGet.contextListReady.hasAll();\n if (!ready) {\n window.setTimeout(waitReady, 50);\n return false;\n }\n resolve(true);\n return true;\n }", "isBusy() {\n return this.totalTasks() >= this.options.maxPoolSize;\n }", "function isReady(){\n if( events.length > 1 ){\n alert(\"Bitte nur eine auswählen\");\n return\n }\n \n if( selectedEvent.status === \"disabled\" ){\n alert(\"Eintrag ist disabled und kann nicht erstellt werden\");\n return\n }\n \n if( selectedEvent.status != \"\" ){\n alert(\"Eintrag hat bereits einen Status und kann deshalb nicht neu erstellt werden.\");\n return\n }\n \n return true\n }", "function checkTasksEnd() {\n var i, j, k, assignment, taskWorkers = new Array(),\n listValidResource = this.getValideResources(), resourceInstance,\n listWorkedTasks = this.getWorkedTasks(listValidResource), taskInstance;\n for (i = 0; i < listWorkedTasks.length; i++) {\n taskWorkers.length = 0;\n taskInstance = listWorkedTasks[i].getInstance(self);\n for (j = 0; j < listValidResource.length; j++) {\n resourceInstance = listValidResource[j].getInstance(self);\n for (k = 0; k < resourceInstance.getAssignments().size(); k++) {\n assignment = resourceInstance.getAssignments().get(k);\n if (assignment.getTaskDescriptorId() == taskInstance.getDescriptorId()) {\n taskWorkers.push(listValidResource[j]);\n }\n }\n }\n taskInstance.setDuration(taskInstance.getDuration() - taskWorkers.length);\n if (taskInstance.getDuration() <= 0) {\n this.doTaskEnd(taskWorkers, listWorkedTasks[i]);\n }\n }\n}", "needsReschedule() {\n if (!this.currentTask || !this.currentTask.isRunnable) {\n return true;\n }\n // check if there's another, higher priority task available\n let nextTask = this.peekNextTask();\n if (nextTask && nextTask.priority > this.currentTask.priority) {\n return true;\n }\n return false;\n }", "function checkState() {\n \n \n if(currentState.running == false) {\n return;\n }\n \n // get request of the job information\n $.ajax({\n url: \"job?id=\" + currentState.currentId\n , type: \"GET\"\n\n , success: function (data) {\n \n currentState.running = data.finished !== true;\n currentState.ready = data.finished;\n currentState.status = data.status;\n currentState.fileName = data.fileName;\n if (currentState.running) {\n setTimeout(checkState, 1000);\n }\n updateView();\n } \n });\n}", "async isBusy() {\n return new Promise((resolve, reject) => {\n this.rpc.stdin.write('busy' + os.EOL);\n this.rpc.stdout.once('data', (data) => {\n data = data.toString().trim();\n if ((typeof data == 'boolean' && data) || data == \"true\") {\n resolve(true)\n } else {\n resolve(false)\n }\n });\n });\n\n }", "function moduleCanExecute(module) {\n return modulesAreReady(module.requiring.items);\n }", "_checkGeneratorIsAlive() {\n this._log('Checking generator is alive...');\n this._client.existsAsync(LAST_GENERATOR_TIME).then((reply) => {\n if (reply === 0) {\n this._client.watch(LAST_GENERATOR_TIME);\n const multiQuery = this._client.multi()\n .set(LAST_GENERATOR_TIME, 1)\n .expire(LAST_GENERATOR_TIME, 10);\n return multiQuery.execAsync()\n } else {\n Promise.resolve(null);\n }\n }).then((reply) => {\n if (reply == null) {\n this._getMessages();\n } else {\n this._isGenerator = true;\n this._generateMessage();\n }\n }).catch((err) => { throw err });\n }", "function checkTaskCompleted(item) {\n if(item == 'apple') {\n appleCompleted = 'completed'\n } else if (item === 'match') {\n matchCompleted = 'completed'\n }\n // activate tunnel if both tasks completed\n if (matchCompleted === 'completed' && appleCompleted === 'completed') {\n let tunnel = document.querySelector('#Tunnel')\n tunnel.style.pointerEvents = 'visible'\n tunnel.style.animation = 'keyStepGlow 2s infinite'\n }\n}", "function checkProgress() {\n\tvar finished = true;\n\tfor (var key in network.usersAwaiting) {\n\t\tif (network.usersAwaiting.hasOwnProperty(key)) {\n\t\t\tfinished = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (var key in network.friendsAwaiting) {\n\t\tif (network.friendsAwaiting.hasOwnProperty(key)) {\n\t\t\tfinished = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor (var key in network.followersAwaiting) {\n\t\tif (network.followersAwaiting.hasOwnProperty(key)) {\n\t\t\tfinished = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t// there are no network requests waited for\n\tif (finished) {\n\t\t// stop timers\n\t\tclearInterval(network.timers['users']);\n\t\tclearInterval(network.timers['friends']);\n\t\tclearInterval(network.timers['followers']);\n\t\tclearInterval(network.timers['execution']);\n\t\t\n\t\t// return the built network\n\t\tnetwork.callback(network.users);\n\t}\n}", "function checkComplete() {\r\n if (sectionLoaderState.filesLoaded >= sectionLoaderState.filesToLoad.length) complete();\r\n}", "ready() {\n\t\tif ( this.player.isReady ) {\n\t\t\tthrow new Error( 'You are ready already.' );\n\t\t}\n\n\t\tif ( !this.player.isInGame ) {\n\t\t\tthrow new Error( 'You need to join the game first.' );\n\t\t}\n\n\t\tconst { isCollision, shipsCollection } = this.player.battlefield;\n\n\t\tif ( isCollision ) {\n\t\t\tthrow new Error( 'Invalid ships configuration.' );\n\t\t}\n\n\t\tthis.player.isReady = true;\n\n\t\tthis[ _connection ].request( 'ready', shipsCollection.toJSON() )\n\t\t\t.catch( error => this._handleServerError( error ) );\n\t}", "function isFileReady ( state ) {\n\t\treturn ( !state || state === 'loaded' || state === 'complete' || state === 'uninitialized' );\n\t}", "function checkStatus() {\n var allDone = true;\n\n for (var _i2 = 0; _i2 < layers.length; _i2++) {\n if (layers[_i2].loaded === false) {\n allDone = false;\n break;\n }\n }\n\n if (allDone) finish();else setTimeout(checkStatus, 500);\n }", "function krnCheckExecution()\n{\n return _Scheduler.processEnqueued;\n}", "function waitFor(test, onReady, timeOutMillis, onTimeout) {\n var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30001, //< Default Max Timeout is 30s\n start = new Date().getTime(),\n condition = false,\n interval = setInterval(\n function() {\n if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {\n // If not time-out yet and condition not yet fulfilled\n condition = (typeof(test) === \"string\" ? eval(test) : test()); // defensive code\n } else {\n if(!condition) {\n // If condition still not fulfilled (timeout but condition is 'false')\n typeof(onTimeout) === \"string\" ? eval(onTimeout) : onTimeout();\n } else {\n // Condition fulfilled (condition is 'true')\n typeof(onReady) === \"string\" ? eval(onReady) : onReady(); // Do what it's supposed to do once the condition is fulfilled\n }\n clearInterval(interval); // Stop this interval\n }\n },\n 100\n ); // repeat check every 100ms\n}", "async function waitForZokrates() {\n logger.info('checking for zokrates_worker');\n try {\n while (\n // eslint-disable-next-line no-await-in-loop\n (await axios.get(`${config.PROTOCOL}${config.ZOKRATES_WORKER_HOST}/healthcheck`)).status !==\n 200\n ) {\n logger.warn(\n `No response from zokratesworker yet. That's ok. We'll wait three seconds and try again...`,\n );\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, 3000));\n }\n } catch (err) {\n logger.error(err);\n process.exit(1);\n }\n logger.info('zokrates_worker reports that it is healthy');\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the examplebegin indices; shuffle them randomly.
generateExampleBeginIndices_() { // Prepare beginning indices of examples. this.exampleBeginIndices_ = []; for (let i = 0; i < this.textLen_ - this.sampleLen_ - 1; i += this.sampleStep_) { this.exampleBeginIndices_.push(i); } // Randomly shuffle the beginning indices. tf.util.shuffle(this.exampleBeginIndices_); this.examplePosition_ = 0; }
[ "generateExampleBeginIndices_() {\n // Prepare beginning indices of examples.\n this.exampleBeginIndices_ = [];\n for (\n let i = 0;\n i < this.textLen_ - this.sampleLen_ - 1;\n i += this.sampleStep_\n ) {\n this.exampleBeginIndices_.push(i);\n }\n console.log('exampleBeginIndices_');\n console.log(this.exampleBeginIndices_);\n\n // Randomly shuffle the beginning indices.\n // tf.util.shuffle(this.exampleBeginIndices_);\n this.examplePosition_ = 0;\n }", "shuffle() {\n \n for (let i = 0; i < this._individuals.length; i++) {\n let index = getRandomInt( i + 1 );\n let a = this._individuals[index];\n this._individuals[index] = this._individuals[i];\n this._individuals[i] = a;\n }\n }", "function shuffle_filler_quest(shuffled_indices) {\n q_list = [];\n for (var i = 0; i < shuffled_indices.length; i++) {\n index = shuffled_indices[i];\n q_list = _.concat(q_list, filler_question[index])\n }\n return q_list;\n}", "function genSeeds() {\r\n analyser.getByteTimeDomainData(dataArray);\r\n sliceSize = Math.floor(bufferLength / 5);\r\n\r\n var sum = 0;\r\n var scaleFactor = 138.0;\r\n\r\n // Seed A\r\n for (var i = 0; i < sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedA = sum / (bufferLength/5)\r\n sum = 0;\r\n\r\n // Seed B\r\n for (var i = sliceSize; i < 2*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedB = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed C\r\n for (var i = 2*sliceSize; i < 3*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedC = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed D\r\n for (var i = 3*sliceSize; i < 4*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedD = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed E\r\n for (var i = 4*sliceSize; i < 5*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedE = sum / sliceSize\r\n sum = 0;\r\n\r\n console.log(`A: ${seedA}, B: ${seedB}, C: ${seedC}, D: ${seedD}, E: ${seedE}`);\r\n}", "function shuffle_filler_conc(shuffled_indices) {\n c_list = [];\n for (var i = 0; i < shuffled_indices.length; i++) {\n index = shuffled_indices[i];\n c_list = _.concat(c_list, filler_conclusion[index])\n }\n return c_list;\n}", "function elementLocations() {\n let choice;\n let transferArray = [];\n let newShuffle = [];\n\n for (let i = 0; i < cols; i++) {\n for (let j = 0; j < rows; j++) {\n choice = floor(random(allElements.length - 1));\n transferArray.push([allElements[choice], 0, 0]);\n allElements.splice(choice, 1);\n }\n newShuffle.push(transferArray);\n transferArray = [];\n }\n return newShuffle;\n}", "function randomSequence(){\n\t\t\tvar sequence = [];\n\t\t\tfor(var i = 0; i < 20; i++){\n\t\t\t\tsequence.push(Math.floor((Math.random()*100)%4)+1);\n\t\t\t}\n\t\t\treturn sequence;\n\t\t}", "function generateRandomIndex(min, max) {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}", "function setUp() {\n canvasCreate.start();\n createRandomIntArray();\n updateCanvas();\n}", "function testInit_PersistentIndices() {\n asyncTestCase.waitForAsync('testInit_PersistentIndices');\n\n var tableSchema = env.schema.table('tableA');\n var rows = getSampleRows(tableSchema, 10, 0);\n\n simulatePersistedIndices(tableSchema, rows).then(\n function() {\n var prefetcher = new lf.cache.Prefetcher(lf.Global.get());\n return prefetcher.init(env.schema);\n }).then(\n function() {\n // Check that RowId index has been properly reconstructed.\n var rowIdIndex = env.indexStore.get(tableSchema.getRowIdIndexName());\n assertTrue(rowIdIndex instanceof lf.index.RowId);\n assertEquals(rows.length, rowIdIndex.getRange().length);\n\n // Check that remaining indices have been properly reconstructed.\n var indices = env.indexStore.getTableIndices(\n tableSchema.getName()).slice(1);\n indices.forEach(function(index) {\n assertTrue(index instanceof lf.index.BTree);\n assertEquals(rows.length, index.getRange().length);\n });\n\n asyncTestCase.continueTesting();\n }, fail);\n}", "function randSampleOutPlace(collection, numSample) {\n var n = collection.length\n var s = Math.min(n, numSample)\n var result = new Array(s)\n for (var i = 0; i < s; i++) {\n result[i] = collection[i]\n }\n for (var i = s; i < n; i++) {\n var j = randomIntBetweenInclusive(0, i)\n if (j < s) {\n // swap in\n result[j] = collection[i]\n }\n }\n return result\n}", "getRandomPhrase () {\n\t\tlet newIndex;\n\t\tdo {\n\t\t\tnewIndex = Math.floor(Math.random() * this.phrases.length);\n\t\t} while (this.usedIndexes.indexOf(newIndex) !== -1);\n\t\tthis.usedIndexes.push(newIndex);\n\t\tdocument.body.style.background = this.getRandomColor();\n\t\treturn this.phrases[newIndex];\n\t}", "function setUpRandomizer() {\n\trandConstSpan = document.getElementById(\"rand_const\");\n\talreadyFoundP = document.getElementById(\"already_found\");\n}", "function randSampleInPlace(collection, numSample) {\n var n = collection.length\n var s = Math.min(n, numSample)\n for (var i = n - 1; i >= n - s; i--) {\n var j = randomIntBetweenInclusive(0, i)\n if (i !== j) {\n // swap\n var temp = collection[j]\n collection[j] = collection[i]\n collection[i] = temp\n }\n }\n return collection.slice(n - s, n)\n}", "function getRandomIndex(allShorts) {\n // A random number between 0 and len(allShorts)\n let rIndex = Math.floor(Math.random() * allShorts.length);\n // returning the random index\n return rIndex;\n}", "assignTilesEx(excludedIndexes)\n {\n let indices = [];\n while(indices.length<7){\n let pickedIndex =Math.floor((Math.random()*100)%28);\n if(indices.indexOf(pickedIndex)<0 && excludedIndexes.indexOf(pickedIndex)<0)\n {\n indices.push(pickedIndex);\n }\n }\n this.unassignedTilePositions = this.unassignedTilePositions.filter(pos=>indices.indexOf(pos)<0);\n return indices;\n }", "function indcpaGenMatrix(seed, transposed, paramsK) {\r\n var a = new Array(3);\r\n var output = new Array(3 * 168);\r\n const xof = new SHAKE(128);\r\n var ctr = 0;\r\n var buflen, offset;\r\n for (var i = 0; i < paramsK; i++) {\r\n\r\n a[i] = polyvecNew(paramsK);\r\n var transpose = new Array(2);\r\n\r\n for (var j = 0; j < paramsK; j++) {\r\n\r\n // set if transposed matrix or not\r\n transpose[0] = j;\r\n transpose[1] = i;\r\n if (transposed) {\r\n transpose[0] = i;\r\n transpose[1] = j;\r\n }\r\n\r\n // obtain xof of (seed+i+j) or (seed+j+i) depending on above code\r\n // output is 504 bytes in length\r\n xof.reset();\r\n const buffer1 = Buffer.from(seed);\r\n const buffer2 = Buffer.from(transpose);\r\n xof.update(buffer1).update(buffer2);\r\n var buf_str = xof.digest({ buffer: Buffer.alloc(504), format: 'hex' });\r\n // convert hex string to array\r\n for (var n = 0; n < 504; n++) {\r\n output[n] = hexToDec(buf_str[2 * n] + buf_str[2 * n + 1]);\r\n }\r\n\r\n // run rejection sampling on the output from above\r\n outputlen = 3 * 168; // 504\r\n var result = new Array(2);\r\n result = indcpaRejUniform(output, outputlen);\r\n a[i][j] = result[0]; // the result here is an NTT-representation\r\n ctr = result[1]; // keeps track of index of output array from sampling function\r\n\r\n while (ctr < paramsN) { // if the polynomial hasnt been filled yet with mod q entries\r\n var outputn = output.slice(0, 168); // take first 168 bytes of byte array from xof\r\n var result1 = new Array(2);\r\n result1 = indcpaRejUniform(outputn, 168); // run sampling function again\r\n var missing = result1[0]; // here is additional mod q polynomial coefficients\r\n var ctrn = result1[1]; // how many coefficients were accepted and are in the output\r\n\r\n // starting at last position of output array from first sampling function until 256 is reached\r\n for (var k = ctr; k < paramsN - ctr; k++) {\r\n a[i][j][k] = missing[k - ctr]; // fill rest of array with the additional coefficients until full\r\n }\r\n ctr = ctr + ctrn; // update index\r\n }\r\n\r\n }\r\n }\r\n return a;\r\n}", "function getPivotIndex(startIndex, endIndex) {\n return startIndex + Math.floor(Math.random() * (endIndex - startIndex));\n}", "function shuffle() {\n var parent = document.querySelector(\"#container\");\n for (var i = 0; i < parent.children.length; i++) {\n parent.appendChild(parent.children[Math.random() * i | 0]);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets squares attacked or defended by a bishop on `square`, given `occupied` squares.
function bishopAttacks(square, occupied) { const bit = SquareSet.fromSquare(square); return hyperbola(bit, DIAG_RANGE[square], occupied).xor(hyperbola(bit, ANTI_DIAG_RANGE[square], occupied)); }
[ "function revealSquare(classList) {\n // Set selected square\n const enemySquare = computerGrid.querySelector(`div[data-id='${shotFired}']`);\n const obj = Object.values(classList);\n // If selected square's class list contains \"explosion\" or \"miss\" and the game is not over already ->\n if (!enemySquare.classList.contains('explosion') && currentPlayer == 'user' && !isGameOver) {\n // See if the square's class includes any of the ship classes and add to the hit count of that ship class ->\n if (obj.includes('destroyer')) destroyerCount++;\n if (obj.includes('submarine')) submarineCount++;\n if (obj.includes('cruiser')) cruiserCount++;\n if (obj.includes('battleship')) battleshipCount++;\n if (obj.includes('carrier')) carrierCount++;\n }\n // If the sqaure's class includes \"taken\" ->\n if (obj.includes('taken')) {\n // Add class \"explosion\" to the class list of the square to designate you have hit a target at that location\n enemySquare.classList.add('explosion');\n // Change the info display to inform the user\n infoDisplay.innerHTML = `Confirmed Hit!`;\n } else {\n // Add class \"miss\" to the class list of the square to designate that you have missed at that location\n enemySquare.classList.add('miss');\n // Change the info display to inform the user\n infoDisplay.innerHTML = `Target Missed!`;\n }\n // Check to see if anyone has won yet\n checkForWins();\n // Set current player to \"enemy\" to inform client that it is the enemy's turn\n currentPlayer = 'enemy';\n if (gameMode == 'singlePlayer') playGameSingle();\n }", "function worthAttacking(gameMap, ship, oship) {\n let possibleCollisonPos = oship.position;\n \n //attempt to detect where collision will occur;\n //Usually, the first direction is where it will occur. The times when this won't happen is when there are collisions with friendly ships detected, of which this will be off a little.\n let collisionDirections = gameMap.getUnsafeMoves(ship.position, oship.position);\n if (collisionDirections.length > 0) {\n possibleCollisonPos = ship.position.directionalOffset(collisionDirections[0]);\n }\n\n if(1.5 * ship.haliteAmount < oship.haliteAmount) {\n let shipsNearby = search.numShipsInRadius(gameMap, ship.owner, possibleCollisonPos, 2);\n let friendlyNearby = shipsNearby.friendly;\n if (friendlyNearby >= 2 && friendlyNearby > shipsNearby.enemy){\n logging.info(`Ship-${ship.id} is going to try to collide with at least 2 other friends nearby f:${shipsNearby.friendly}, e:${shipsNearby.enemy} at ${possibleCollisonPos}`)\n return true;\n }\n }\n return false;\n \n}", "shootBFSWeapon(player) {\n let damageCells = [];\n let exploredCells = {};\n let [initRow, initCol] = player.getTopLeftRowCol();\n let remainingDistance = gameSettings.WEAPON_RANGE;\n let tileQueue = [[initRow, initCol]];\n while (remainingDistance > 0 && tileQueue.length !== 0) {\n let [row, col] = tileQueue.shift();\n damageCells.push([row, col]);\n exploredCells[[row, col]] = true; // so we won't duplicate damage cells\n // push its neighbor tiles to the queue\n let neighborTiles = this.board.getNeighborTiles(row, col);\n neighborTiles.forEach(([tileRow, tileCol]) => {\n if (exploredCells[[tileRow, tileCol]] === undefined) {\n // hasn't been explored yet\n tileQueue.push([tileRow, tileCol]);\n }\n });\n remainingDistance--;\n }\n\n return damageCells;\n }", "function getAttackers(toRow, toCol, atkColor)\r\n\r\n{\r\n\r\n\tvar atkSquare = new Array();\r\n\r\n\r\n\r\n\t/* check for knights first */\r\n\r\n\tfor (var i = 0; i < 8; i++) {\t// Check all eight possible knight moves\r\n\r\n\t\tvar fromRow = toRow + knightMove[i][0];\r\n\r\n\t\tvar fromCol = toCol + knightMove[i][1];\r\n\r\n\t\tif (isInBoard(fromRow, fromCol))\r\n\r\n\t\t\tif (board[fromRow][fromCol] == (KNIGHT | atkColor))\t// Enemy knight found\r\n\r\n\t\t\t\t\tatkSquare[atkSquare.length] = [fromRow, fromCol];\r\n\r\n\t}\r\n\r\n\t/* tactic: start at test square and check all 8 directions for an attacking piece */\r\n\r\n\t/* directions:\r\n\r\n\t\t0 1 2\r\n\r\n\t\t7 * 3\r\n\r\n\t\t6 5 4\r\n\r\n\t*/\r\n\r\n\r\n\r\n\tfor (var j = 0; j < 8; j++)\t\t// Look in all directions\r\n\r\n\t{\r\n\r\n\t\tvar fromRow = toRow;\r\n\r\n\t\tvar fromCol = toCol;\r\n\r\n\t\tfor (var i = 1; i < 8; i++)\t// Distance from thePiece\r\n\r\n\t\t{\r\n\r\n\t\t\tfromRow += direction[j][0];\r\n\r\n\t\t\tfromCol += direction[j][1];\r\n\r\n\t\t\tif (isInBoard(fromRow, fromCol))\r\n\r\n\t\t\t{\r\n\r\n\t\t\t\tif (board[fromRow][fromCol] != 0)\r\n\r\n\t\t\t\t{\t// We found the first piece in this direction\r\n\r\n\t\t\t\t\tif((board[fromRow][fromCol] & BLACK) == atkColor)\t// It is an enemy piece\r\n\r\n\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\tif(isAttacking(board[fromRow][fromCol], fromRow, fromCol, getPieceColor(board[fromRow][fromCol]), toRow, toCol))\r\n\r\n\t\t\t\t\t\t\tatkSquare[atkSquare.length] = [fromRow, fromCol];\t// An attacker found\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tbreak;\t\t// No need to look further in this direction\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\r\n\t\t\telse\r\n\r\n\t\t\t\tbreak;\r\n\r\n\t\t}\r\n\r\n\t}\r\n\r\n\treturn atkSquare;\r\n\r\n}", "function findHQ(player) {\n for (var row = 0; row < ySize; row++) {\n for (var col = 0; col < xSize; col++) {\n var square = board[row][col];\n if (square.player == player && square.HQ) {\n return square;\n }\n }\n }\n}", "function checkIfPathFree(square) {\n let row = square.row\n let col = square.column\n\n let north = row - 1\n let south = row + 1\n let east = col + 1\n let west = col - 1\n\n function isNorth(obj) {\n return obj.row === north && obj.column === col\n }\n function isSouth(obj) {\n return obj.row === south && obj.column === col\n }\n function isEast(obj) {\n return obj.row === row && obj.column === east\n }\n function isWest(obj) {\n return obj.row === row && obj.column === west\n }\n /* at least 3 adjacent squares have to be unblocked for a square to be considered free */\n if (\n square.row === 1 ||\n square.column === 1 ||\n square.row === 10 ||\n square.column === 10\n ) {\n return true\n } else {\n if (\n square.state === 'free' &&\n ((squaresArray.find(isNorth).state === 'blocked' &&\n squaresArray.find(isEast).state === 'blocked' &&\n squaresArray.find(isWest).state === 'blocked') ||\n (squaresArray.find(isNorth).state === 'blocked' &&\n squaresArray.find(isWest).state === 'blocked' &&\n squaresArray.find(isSouth).state === 'blocked') ||\n (squaresArray.find(isNorth).state === 'blocked' &&\n squaresArray.find(isEast).state === 'blocked' &&\n squaresArray.find(isSouth).state === 'blocked') ||\n (squaresArray.find(isSouth).state === 'blocked' &&\n squaresArray.find(isWest).state === 'blocked' &&\n squaresArray.find(isEast).state === 'blocked'))\n ) {\n return true\n } else if (\n (squaresArray.find(isNorth).state === 'playerOne') ||\n (squaresArray.find(isSouth).state === 'playerOne') ||\n (squaresArray.find(isEast).state === 'playerOne') ||\n (squaresArray.find(isWest).state === 'playerOne')) {\n return true\n } else {\n return false\n }\n }\n}", "onObstacle(x, y, size) {\n\t\tfor (var i = 0; i < this.obstacles.length; i++) {\n\t\t\tvar squareTopLeft = new Pair(x, y);\n\t\t\tvar squareBottomRight = new Pair(x+size, y+size);\n\t\t\tvar obstacleRect = this.obstacles[i].rectangle;\n\t\t\tvar overlap = this.getOverlap(squareTopLeft, squareBottomRight, obstacleRect.top_left, obstacleRect.bottom_right);\n\t\t\tif (overlap) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}", "function squareThatWasJumped(aMove) {\r\n\tlet x = (aMove.from.row + aMove.to.row) / 2;\r\n\tlet y = (aMove.from.col + aMove.to.col) / 2;\r\n\treturn board[x][y];\r\n}", "playPiece(x,y) {\r\n if (!this.isOccupied(x, y)) {\r\n if (this.playerTurn === 1) {\r\n this.setBlack(x, y);\r\n board[x][y].style.backgroundColor = '#000000'\r\n }\r\n else {\r\n this.setWhite(x, y);\r\n board[x][y].style.backgroundColor = '#FFFFFF'\r\n }\r\n this.updateBoard();\r\n }\r\n else{\r\n console.log(\"That square is already occupied.\");\r\n }\r\n }", "function viableDirections(gameMap, ship, targetPos, avoid) {\n \n //Gets directions that move towards the target position\n let directions = gameMap.getUnsafeMoves(ship.position, targetPos);\n \n if (directions.length === 0){\n //If there are no directions to the targetPosition, set still as a direction\n directions = [new Direction(0, 0)];\n }\n else {\n //doing nothing is always an option and an better option than moving in a direction not towards target position\n directions.push(new Direction(0, 0));\n }\n let absoluteSafeDirections = []; //all absolute safe directions. It is absolutely safe if there isn't any enemy ship adjacent to the tile this ship reaches by taking that direction\n let safeDirections = []; //all safe directions that don't have an enemy directly on the tile this ship might move to.\n let attackDirections = []; //directions in which the ship can take to try and attack an enemy\n \n let allDirections = [Direction.Still, Direction.North, Direction.South, Direction.East, Direction.West ] //all directions the ship can take\n \n //go through directions and check surrounding squares to avoid\n \n //Goes through all directions and checks surrounding squares if there is an enemy on it to see which directions are absolutely safe and which are just safe only if we are trying to avoid enemies\n \n if (avoid === true){\n for (let i = 0; i < allDirections.length; i++) {\n //position in searched direction\n let possiblePosition = ship.position.directionalOffset(allDirections[i]);\n \n //Find all adjacent positions to the position in the searched direction\n let possiblePositionsNearby = search.circle(gameMap, possiblePosition, 1);\n \n let isThisAbsoluteSafe = true; //whether possiblePosition is absolutely safe\n let isThisSafe = true; //whether possiblePosition is safe\n let numEnemies = 0;\n for (let j = 0; j < possiblePositionsNearby.length; j++) {\n let possiblePositionNearbyTile = gameMap.get(possiblePositionsNearby[j]);\n let oship = possiblePositionNearbyTile.ship;\n if (oship !== null && oship.owner !== ship.owner) {\n //if there is a ship on the adjacent tile and the owner of the ship isn't the same owner as this ship (enemy)\n numEnemies += 1;\n //Set this direction as not safe.\n isThisAbsoluteSafe = false;\n if (j === 0) {\n //The way search.circle works is it performs a BFS search for the closest squares in radius 1 (although a little cheated as we use a sorted look up table). The first element of possiblePositions is then always the original square that was searched around.\n isThisSafe = false;\n }\n }\n }\n if (isThisAbsoluteSafe === true) {\n let distanceAway = gameMap.calculateDistance(possiblePosition,targetPos);\n //logging.info(`Ship-${ship.id} at ${ship.position} has absolute safe direction: ${allDirections[i]} ${distanceAway} away`);\n absoluteSafeDirections.push({dir:allDirections[i], dist:distanceAway, enemies: numEnemies});\n }\n if (isThisSafe === true) {\n safeDirections.push({dir:allDirections[i], dist:gameMap.calculateDistance(possiblePosition,targetPos), enemies: numEnemies})\n }\n }\n //Sort absolute safe directions by which is closer to target position\n let sortedAbsoluteSafeDirections = [];\n absoluteSafeDirections.sort(function(a,b){\n return a.dist - b.dist;\n });\n if (absoluteSafeDirections.length >= 2){\n if (absoluteSafeDirections[0].dist === absoluteSafeDirections[1].dist) {\n if (ship.id % 2 === 1) {\n let tempASD = absoluteSafeDirections[0];\n absoluteSafeDirections[0] = absoluteSafeDirections[1];\n absoluteSafeDirections[1] = tempASD;\n //logging.info(`Ship-${ship.id} switched directions from ${tempASD.dir} to ${absoluteSafeDirections[0].dir}`);\n }\n }\n }\n \n }\n \n //If trying to avoid enemy ships but there are no absolutely safe directions, then choose safe directions with least enemies around and out of those, find the closest to target\n if (avoid === true) {\n if (absoluteSafeDirections.length === 0) {\n if (safeDirections.length === 0) {\n //if there are 0 safe directions\n directions = [Direction.Still];\n }\n else {\n //If there are some safe directions, look through them\n let possibleSafeDirections = [];\n let leastEnemyCount = 1000;\n for (let j = 0; j < safeDirections.length; j++) {\n if (safeDirections[j].enemies < leastEnemyCount) {\n //reset that array as a direction with less enemies was found\n possibleSafeDirections = [safeDirections[j]];\n }\n else if (safeDirections[j].enemies === leastEnemyCount) {\n //Add safe direction that has the least enemies nearby\n possibleSafeDirections.push(safeDirections[j]);\n }\n }\n //sort the directions with the least enemies nearby by distance\n possibleSafeDirections.sort(function(a,b){\n return a.dist - b.dist;\n })\n directions = possibleSafeDirections.map(function(a){\n return a.dir;\n });\n }\n }\n else {\n directions = absoluteSafeDirections.map(function(a){\n return a.dir;\n });\n }\n }\n //By now, directions will include the safest directions possible that also are the closest to the targetPos\n //Add remaining directions to allow flexibility in movement in case of conflicts\n let diffDir = [];\n for (let i = 0; i < allDirections.length; i++) {\n let isItThere = false;\n for (let j = 0; j < directions.length; j++) {\n if (allDirections[i].equals(directions[j])){\n isItThere = true;\n }\n }\n if (isItThere === false) {\n diffDir.push(allDirections[i]);\n }\n }\n for (let i = 0; i < diffDir.length; i++){\n directions.push(diffDir[i])\n }\n //logging.info(`Ship-${ship.id} at ${ship.position} direction order: ${directions}`);\n return directions;\n}", "function getSurroundCells(y,x) {\n var arr1 = [[y-1,x-1],[y-1,x],[y-1,x+1],[y,x-1],[y,x+1],[y+1,x-1],[y+1,x],[y+1,x+1]];\n var arr2 = [];\n for (ai=0; ai<arr1.length; ai++) {\n if (arr1[ai][0]<height && arr1[ai][1]<width && 0<=arr1[ai][0] && 0<=arr1[ai][1]) {\n arr2.push(arr1[ai]);\n }\n }\n return arr2;\n}", "function returnAttackOutcomes(attack, selfStr, oppStr) {\n\t\ttry {\n\t\t\tif (!FS_Object.prop(attack)) {\n\t\t\t\tconsole.error(\"🔢 BattleMath.returnAttackOutcomes() attack is required!\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// get stats\n\t\t\tlet self = Stats.get(selfStr),\n\t\t\t\topp = Stats.get(oppStr),\n\t\t\t\tselfLevel = 1,\n\t\t\t\toppLevel = 1,\n\t\t\t\tnoEffect = true,\n\t\t\t\tstat = \"\",\n\t\t\t\taffectsStat = \"\",\n\t\t\t\tattackOutcomes = [], // track the outcome(s) of the attack to log them\n\t\t\t\toutcome = {}; // default outcome\n\n\t\t\tif (selfStr == \"monster\") {\n\t\t\t\tselfLevel = Monster.current().level;\n\t\t\t\toppLevel = T.tally_user.level;\n\t\t\t} else if (selfStr == \"tally\") {\n\t\t\t\tselfLevel = T.tally_user.level;\n\t\t\t\toppLevel = Monster.current().level;\n\t\t\t}\n\n\n\t\t\t// ************** STAMINA FIRST **************\n\n\t\t\t// COMPUTE STAMINA COST FIRST\n\t\t\tif (FS_Object.prop(attack.staminaCost)) {\n\t\t\t\tstat = \"stamina\";\n\t\t\t\taffectsStat = \"staminaCost\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round(self[stat].max * attack[affectsStat], 1));\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\t//attackOutcomes.push(outcome); // don't log stamina\n\t\t\t\t// if (!DEBUG) console.log(\"self[stat].val=\" + self[stat].val, \"attack[affectsStat]=\" + attack[affectsStat],\n\t\t\t\t// \t\"self[stat].max * attack[affectsStat]=\", (self[stat].max * attack[affectsStat]));\n\t\t\t\t// logOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\n\t\t\t// if not a defense, check to see if there is a miss\n\t\t\tif (attack.type !== \"defense\" && !didHit(attack, self, opp)) {\n\t\t\t\t// allow two tally misses total\n\t\t\t\tif (selfStr == \"tally\" && ++tallyMisses < 2)\n\t\t\t\t\treturn \"missed\";\n\t\t\t\telse\n\t\t\t\t\treturn \"missed\";\n\t\t\t}\n\t\t\t// was it a special attack?\n\t\t\telse if (FS_Object.prop(attack.special)) {\n\t\t\t\tif (DEBUG) console.log(\"🔢 BattleMath.returnAttackOutcomes() SPECIAL ATTACK !\", attack.special);\n\t\t\t\toutcome = outcomeData[attack.special]; // get data\n\t\t\t\t// make sure its defined\n\t\t\t\tif (outcome) {\n\t\t\t\t\tattackOutcomes.push(outcome); // store outcome\n\t\t\t\t\tlogOutcome(attack.special, outcome); // log\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (DEBUG) console.log(\"🔢 BattleMath.returnAttackOutcomes()\", selfStr + \" 🧨 \" + oppStr, attack,\n\t\t\t\t\"\\n --> self=\", self,\n\t\t\t\t\"\\n --> self=\", JSON.stringify(self),\n\t\t\t\t\"\\n --> opp=\", opp,\n\t\t\t\t\"\\n --> opp=\", JSON.stringify(opp)\n\t\t\t);\n\n\n\n\t\t\t// ************** HEALTH **************\n\n\t\t\t// SELF +HEALTH\n\t\t\tif (FS_Object.prop(attack.selfHealth)) {\n\t\t\t\tstat = \"health\";\n\t\t\t\taffectsStat = \"selfHealth\";\n\t\t\t\toutcome = outcomeData[affectsStat]; // get data\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1); // get change\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change); // set new val\n\t\t\t\tattackOutcomes.push(outcome); // store outcome\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self); // log\n\t\t\t}\n\t\t\t// OPP -HEALTH\n\t\t\tif (FS_Object.prop(attack.oppHealth)) {\n\t\t\t\tstat = \"health\";\n\t\t\t\taffectsStat = \"oppHealth\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\n\t\t\t\t// original\n\t\t\t\t// change = (max opp stat * the normalized attack stat)\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\t// e.g. tally (lvl24) v. monster (lvl3),\n\t\t\t\t// change = -(opp[stat].max (26) * attack[affectsStat] (0.15)) = -3.9\n\t\t\t\t// change = -(opp[stat].max (26) * attack[affectsStat] (0.15) * (24 - 23 * .1) = .1) = -4 (not much change)\n\t\t\t\t// change = -(opp[stat].max (26) * attack[affectsStat] (0.15) * (24 - 3 * .1) = 2.1) = -8.19 (big change)\n\t\t\t\t// change = -(opp[stat].max (4) * attack[affectsStat] (0.15) * (3 - 24 * .1) = -1.26) = -8.19 (big change)\n\n// outcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]) * Math.max(((selfLevel - oppLevel) * 0.1), 0.1), 3));\n\n\n\t\t\t\t// Daniel\n\t\t\t\t// I just changed this to be based on ATK and DEF values rather than as a proportion of level\n\t\t\t\t// outcome.change = -(FS_Number.round((1 + attack[affectsStat]) * Math.max((self.attack.val - opp.defense.val), 2.0), 3));\n\n\n\t\t\t\tif (DEBUG) console.log(\n\t\t\t\t\t\"outcome.change [\" + outcome.change + \"] = -(FS_Number.round(\" +\n\t\t\t\t\t\"opp[stat].max [\" + opp[stat].max + \"] *\", \"attack[affectsStat] [\" + attack[affectsStat] + \"] + \" +\n\t\t\t\t\t\"selfLevel [\" + selfLevel + \"] * attack[affectsStat] [\" + attack[affectsStat] + \"] , 3))\"\n\t\t\t\t);\n\t\t\t\tif (DEBUG) console.log(\"opp[stat].val [\" + opp[stat].val + \"] + outcome.change [\" + outcome.change + \"] = \" +\n\t\t\t\t\t(opp[stat].val + outcome.change));\n\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\n\t\t\t// ************** ATTACK **************\n\n\t\t\t// INCREASE SELF ATTACK\n\t\t\tif (FS_Object.prop(attack.selfAtk)) {\n\t\t\t\tstat = \"attack\";\n\t\t\t\taffectsStat = \"selfAtk\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\t//if (outcome.change != 0)\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP ATTACK\n\t\t\tif (FS_Object.prop(attack.oppAtk)) {\n\t\t\t\tstat = \"attack\";\n\t\t\t\taffectsStat = \"oppAtk\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\t// ************** ACCURACY **************\n\n\t\t\t// INCREASE SELF ACCURACY\n\t\t\tif (FS_Object.prop(attack.selfAcc)) {\n\t\t\t\tstat = \"accuracy\";\n\t\t\t\taffectsStat = \"selfAcc\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP ACCURACY\n\t\t\tif (FS_Object.prop(attack.oppAcc)) {\n\t\t\t\tstat = \"accuracy\";\n\t\t\t\taffectsStat = \"oppAcc\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\t// ************** EVASION **************\n\n\t\t\t// INCREASE SELF EVASION\n\t\t\tif (FS_Object.prop(attack.selfEva)) {\n\t\t\t\tstat = \"evasion\";\n\t\t\t\taffectsStat = \"selfEva\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP EVASION\n\t\t\tif (FS_Object.prop(attack.oppEva)) {\n\t\t\t\tstat = \"evasion\";\n\t\t\t\taffectsStat = \"oppEva\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\t// ************** DEFENSE **************\n\n\t\t\t// INCREASE SELF DEFENSE\n\t\t\tif (FS_Object.prop(attack.selfDef)) {\n\t\t\t\tstat = \"defense\";\n\t\t\t\taffectsStat = \"selfDef\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = FS_Number.round(self[stat].max * attack[affectsStat], 1);\n\t\t\t\tself[stat].val = Stats.setVal(selfStr, outcome.stat, self[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"self\", self);\n\t\t\t}\n\t\t\t// DAMAGE OPP DEFENSE\n\t\t\tif (FS_Object.prop(attack.oppDef)) {\n\t\t\t\tstat = \"defense\";\n\t\t\t\taffectsStat = \"oppDef\";\n\t\t\t\toutcome = outcomeData[affectsStat];\n\t\t\t\toutcome.change = -(FS_Number.round((opp[stat].max * attack[affectsStat]), 3));\n\t\t\t\topp[stat].val = Stats.setVal(oppStr, outcome.stat, opp[stat].val + outcome.change);\n\t\t\t\tattackOutcomes.push(outcome);\n\t\t\t\tlogOutcome(affectsStat, outcome, \"opp\", opp);\n\t\t\t}\n\n\n\t\t\tif (DEBUG) console.log(\"🔢 BattleMath.returnAttackOutcomes() final stats = \",\n\t\t\t\tselfStr + \" 🧨 \" + oppStr, attack\n\t\t\t\t// ,\"\\n --> self=\", JSON.stringify(self),\n\t\t\t\t// \"\\n --> opp=\", JSON.stringify(opp)\n\t\t\t);\n\n\t\t\t// check to make sure there was an effect\n\t\t\tfor (let i = 0; i < attackOutcomes.length; i++) {\n\t\t\t\t//console.log(\"outcome\", outcome);\n\t\t\t\t// if change is not zero then there was an effect\n\t\t\t\tif (outcome.change > 0 || outcome.change < 0) {\n\t\t\t\t\tnoEffect = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (noEffect === true)\n\t\t\t\treturn \"noEffect\";\n\t\t\telse\n\t\t\t\treturn attackOutcomes; // return data\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t}", "function zombie_shootout(zombies, range, ammo) {\n let killed = 0;\nwhile (ammo > 0){\n ammo--;\n killed++;\n zombies--;\n range -= .5;\n if(zombies == 0){\n return \"You shot all \" + killed + \" zombies.\"\n }else if(range == 0){\n return \"You shot \" + killed + \" zombies before being eaten: overwhelmed.\"\n }else if(ammo == 0){\n return \"You shot \" + killed + \" zombies before being eaten: ran out of ammo.\"\n}\n}\n}", "function findReachablePositions(player, position) { // PARAMETERS : player, position\n\n reachs = []; // vider le tableau des cases atteignables\n\n var surrounds = findSurroundingPositions(position); // create a variable to define surrounding positions\n var range = 0; // set distance tested to zero\n\n // Define reachable positions : top\n\n while ( // WHILE...\n (surrounds[1] !== null) && // ...the position above exist (not outside of the board)\n (squares[surrounds[1]].player === 0) && // ... AND the position above is not occupied by a player\n (squares[surrounds[1]].obstacle === 0) && // ... AND the position above is not occupied by an obstacle\n (range < 3) // ... AND the tested position distance from player position is below 3\n ) { // THEN\n var reach = Object.create(Reach); // create an object reach\n reachFight = isLeadingToFight(player, surrounds[1]); // define is the reachable position is a fighting position\n reach.initReach(player, surrounds[1], -10, (range + 1), reachFight); // set properties\n reachs.push(reach); // push object in array\n range++; // increase range of position tested\n surrounds = findSurroundingPositions(position - (10 * range)); // move forward the test\n }\n\n // Define reachable positions : right\n\n range = 0; // reset range for next test\n surrounds = findSurroundingPositions(position); // reset surrounds for next test\n\n while (\n (surrounds[4] !== null) &&\n (squares[surrounds[4]].player === 0) &&\n (squares[surrounds[4]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[4]);\n reach.initReach(player, surrounds[4], +1, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position + (1 * range));\n }\n\n // Define reachable positions : bottom\n\n range = 0;\n surrounds = findSurroundingPositions(position);\n\n while (\n (surrounds[6] !== null) &&\n (squares[surrounds[6]].player === 0) &&\n (squares[surrounds[6]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[6]);\n reach.initReach(player, surrounds[6], +10, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position + (10 * range));\n }\n\n // Define reachable positions : left\n\n range = 0;\n surrounds = findSurroundingPositions(position);\n\n while (\n (surrounds[3] !== null) &&\n (squares[surrounds[3]].player === 0) &&\n (squares[surrounds[3]].obstacle === 0) &&\n (range < 3)\n ) {\n var reach = Object.create(Reach);\n reachFight = isLeadingToFight(player, surrounds[3]);\n reach.initReach(player, surrounds[3], -1, (range + 1), reachFight);\n reachs.push(reach);\n range++;\n surrounds = findSurroundingPositions(position - (1 * range));\n }\n\n return reachs; // return array\n\n}", "function battle(x, y) {\n var alphabeth = {\"A\":1, \"B\":2, \"C\":3, \"D\":4, \"E\":5, \"F\":6, \"G\":7, \"H\":8, \"I\": 9, \"J\": 10, \"K\":11, \"L\":12, \"M\":13, \"N\":14, \"O\":15, \"P\":16, \"Q\":17, \"R\":18, \"S\":19, \"T\": 20, \"U\":21, \"V\":22, \"W\":23, \"X\":24, \"Y\":25, \"Z\":26} \n xSplit = x.split(\"\");\n var sum1 = 0, sum2 = 0\n for (var i = 0; i < xSplit.length; i++) {\n sum1 += alphabeth[xSplit[i]];\n }\n ySplit = y.split(\"\");\n for (var j = 0; j < ySplit.length; j++) {\n sum2 += alphabeth[ySplit[j]];\n } \n if (sum1 === sum2) {\n return \"Tie!\";\n } else if (sum1 > sum2) {\n return x;\n } else {\n return y;\n }\n}", "cpuAttack(gameboard){\n let row, column;\n let attackHit = null;\n if(this.lastHit.coords != null){\n if(this.enemyShipsRemaining.slice(-1) == this.lastHit.coords.length){\n this.lastHit.backtracked = true;\n } else {\n [row, column] = this.lastHit.coords[0].split(' ');\n row = parseInt(row);\n column = parseInt(column);\n if(this.lastHit.horizontal || this.lastHit.horizontal === null){\n // Try attacking the left if you haven't already\n if(!(column == 0 || this.playHistory.includes([row, column - 1].join(\"\")))){\n attackHit = this.sendAttack(row, column - 1, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row, column - 1].join(' '));\n this.lastHit.horizontal = true;\n }\n // otherwise try attacking to the right if you haven't already\n } else if(!(column + 1 == gameboard.height || this.playHistory.includes([row, column + 1].join(\"\")))){\n attackHit = this.sendAttack(row, column + 1, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row, column + 1].join(' '));\n this.lastHit.horizontal = true;\n }\n } else if(this.lastHit.horizontal && this.lastHit.backtracked === false){\n // This branch handles the event where you KNOW the current ship is horizontal\n // and you have reached a dead end.\n // Here backTrackColumn is used to find the next end that is still in the grid and has not been\n // attacked.\n // First checks left, then checks right.\n\n // This is pretty darn ugly, but it guarantees that the CPU will finish every ship it starts\n // attacking.\n\n // However, it also guarantees it will always fire an extra shot for every ship.\n let backTrackColumn = column - 1;\n // If the tile to the left of the current tile was a hit, that means your most recent shot\n // was to the right and was a miss.\n // So you want to access this.lastHit.coords to find the first shot from the sequence and shoot to\n // the left.\n // If the tile to the left is not in lastHit.coords at all, that means you want to check all the way\n // to the right\n this.lastHit.backtracked = true;\n if(this.lastHit.coords.includes([row, backTrackColumn].join(' '))){\n backTrackColumn = parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[1]) - 1;\n } else {\n backTrackColumn = parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[1]) + 1;\n }\n // If the opposite side's tile is already attacked, this ship is sunk, so you want to move on\n if(backTrackColumn >= 0 && backTrackColumn < gameboard.width && !this.playHistory.includes([row, backTrackColumn].join(\"\"))){\n attackHit = this.sendAttack(row, backTrackColumn, gameboard);\n if(attackHit){\n this.lastHit.coords.push([row, backTrackColumn].join(' '));\n this.lastHit.coords.reverse();\n }\n }\n }\n }\n // If the current target is not horizontally placed AND you have not fired an attack yet\n if(!this.lastHit.horizontal && attackHit === null){\n // Try attacking above if you haven't already\n if(!(row == 0 || this.playHistory.includes([row - 1, column].join(\"\")))){\n attackHit = this.sendAttack(row - 1, column, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row - 1, column].join(' '));\n this.lastHit.horizontal = false;\n }\n // otherwise try attacking below if you haven't already\n } else if(!(row + 1 == gameboard.height || this.playHistory.includes([row + 1, column].join(\"\")))){\n attackHit = this.sendAttack(row + 1, column, gameboard);\n if(attackHit){\n this.lastHit.coords.unshift([row + 1, column].join(' '));\n this.lastHit.horizontal = false;\n }\n } else if(this.lastHit.horizontal === false && this.lastHit.backtracked === false){\n // If you cannot attack directly above or below, try attacking the opposite end of the current line.\n // If it is a miss, then you know that the ship targeted by lastHit is fully sunk.\n this.lastHit.backtracked = true;\n let backTrackRow = row - 1;\n if(this.lastHit.coords.includes([backTrackRow, column].join(' '))){\n backTrackRow = parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[0]) - 1;\n } else {\n backTrackRow =parseInt(this.lastHit.coords.slice(-1)[0].split(' ')[0]) + 1;\n }\n if(backTrackRow >= 0 && backTrackRow < gameboard.height && \n !this.playHistory.includes([backTrackRow, column].join(\"\"))){\n attackHit = this.sendAttack(backTrackRow, column, gameboard);\n if(attackHit){\n this.lastHit.coords.push([backTrackRow, column].join(' '));\n this.lastHit.coords.reverse();\n }\n }\n }\n }\n }\n }\n // If you made it through the code above and attackHit is still null, attack randomly.\n if(attackHit === null){\n if(this.lastHit.backtracked){\n this.enemyShipsRemaining.splice(this.enemyShipsRemaining.indexOf(this.lastHit.coords.length), 1);\n }\n // For now, if you make it through the 4 previous and can't take a shot, that means you have already\n // shot all of the surrounding tiles.\n // Reset lastHit\n this.lastHit.coords = null;\n this.lastHit.horizontal = null;\n this.lastHit.backtracked = false;\n attackHit = this.randomAttack(gameboard);\n }\n return attackHit;\n }", "function findKing(squares, color) {\n for (let j=0; j < 64; j++) {\n if (squares[j].piece === \"King\" && squares[j].color === color) {\n return (j);\n }\n }\n}", "function findVulnerability(areas_black, areas_white, chess) {\n\n areas_white = [\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n ];\n\n areas_black = [\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n ];\n\n\n console.log(\"areas_black\");\n console.log(areas_black);\n console.log(\"areas_white\");\n console.log(areas_white);\n\n chess.forEach(function (chesspiece, i) {\n chesspiece.forEach(function (item, j) {\n if (chesspiece != 0) {\n switch (item) {\n case 1:\n areas_white = pawn({color: \"white\"}, chess, areas_white, i,j);\n break;\n case 2:\n areas_white = knight(chess, i, j, areas_white, false);\n break;\n\n case 3:\n areas_white = bishop(chess, i, j, areas_white, false);\n break;\n\n case 4:\n areas_white = rook(chess, i, j, areas_white, false);\n break;\n\n case 5:\n areas_white = bishop(chess, i, j, areas_white, false);\n areas_white = rook(chess, i, j, areas_white, false);\n break;\n\n case 6:\n //King\n areas_white = king(chess, i, j, areas_white, false);\n break;\n\n case 7:\n areas_black = pawn({color: \"black\"}, chess, areas_black, i,j);\n break;\n\n case 8:\n areas_black = knight(chess, i, j, areas_black, true);\n break;\n\n case 9:\n areas_black = bishop(chess, i, j, areas_black, true);\n break;\n\n case 10:\n areas_black = rook(chess, i, j, areas_black, true);\n break;\n\n case 11:\n areas_black = bishop(chess, i, j, areas_black, true);\n areas_black = rook(chess, i, j, areas_black, true);\n\n break;\n\n case 12:\n //King\n areas_black = king(chess, i, j, areas_black, true);\n break;\n }\n }\n });\n });\n\n return {\n white: areas_white,\n black: areas_black,\n };\n}", "function hover(event, empty_coords) {\n var xy = empty_coords.split(\"/\");\n var x = xy[0]; // x,y coords of empty square\n var y = xy[1];\n var empty_x = x / 100; // which square x and y it is (0, 1, 2, 3)\n var empty_y = y / 100;\n // get (possible) neighbors:\n var neighbors = getNeighbors(empty_x, empty_y);\n var up = neighbors[0];\n var down = neighbors[1];\n var right = neighbors[2];\n var left = neighbors[3];\n\n // if the square the mouse is on is neighbors with the empty square, then change text and border color to red\n if ((up != \"none\") && (event.target == up)) {\n event.target.classList.toggle(\"movablepiece\");\n } else if ((down != \"none\") && (event.target == down)) {\n event.target.classList.toggle(\"movablepiece\");\n } else if ((right != \"none\") && (event.target == right)) {\n event.target.classList.toggle(\"movablepiece\");\n } else if ((left != \"none\") && (event.target == left)) {\n event.target.classList.toggle(\"movablepiece\");\n }\n }", "function getPiece(x, y) {\n return board[y][x];\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register the given Angular Service Worker script. If `enabled` is set to `false` in the given options, the module will behave as if service workers are not supported by the browser, and the service worker will not be registered.
static register(script, options = {}) { return { ngModule: ServiceWorkerModule, providers: [provideServiceWorker(script, options)], }; }
[ "function initServiceWorker() {\n if ('serviceWorker' in navigator) {\n navigator.serviceWorker\n .register('../service-worker.js')\n .then(function() { console.log('ServiceWorker Registered');\n }, function(err) {\n console.log('ServiceWorker registration failed: ', err);\n });\n }\n}", "async register_service_worker() {\n\n\t\t// Solicita la aceptación de notificaciones\n\t\tconst push_permission = (reg) => {\n\t\t\tif (Notification.permission == 'default' || navigator.serviceWorker.controller) this.sw_notification_permission(reg);\n\t\t}\n\n\t\t// Callback al recibir un mensaje desde el service worker\n\t\tconst on_message = (e) => {\n\t\t\t// console.log('[CLIENT] Message:', e);\n\t\t\tif (e.data.cache_clear != undefined) {\n\t\t\t\tswitch (e.data.cache_clear) {\n\t\t\t\t\tcase 'done':\n\t\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'error':\n\t\t\t\t\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (e.data.msg != undefined) {\n\t\t\t\tswitch (e.data.msg) {\n\t\t\t\t\tcase 'reload': location.reload(); break;\n\t\t\t\t\tdefault: this.app_version = e.data.msg; break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\n\t\tthis.worker = navigator.serviceWorker.register('/service-worker')\n\t\t.then(async (e) => { push_permission(e); return e; })\n\t\t.catch(err => console.error('[SW] Registering failed', err));\n\n\t\tnavigator.serviceWorker.addEventListener('message', (e) => on_message(e));\n\t\tnavigator.serviceWorker.ready.then(async (reg) => reg.active.postMessage({ lang: this.lang }));\n\t}", "function createWebWorker(opts) {\n return webWorker_js_1.createWebWorker(standaloneServices_js_1.StaticServices.modelService.get(), opts);\n }", "function ManageServiceWorker() {\n\n\tthis.registerServiceWorker = function() {\n\t\tlet manageServiceWorker = this;\n\n\t\tnavigator.serviceWorker.register('/sw.js')\n\t\t\t.then(function(reg) {\n\t\t\t\tif (!navigator.serviceWorker.controller) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (reg.waiting) {\n\t\t\t\t\tmanageServiceWorker.updateReady(reg.waiting);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (reg.installing) {\n\t\t\t\t\tmanageServiceWorker.trackInstalling(reg.installing);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\treg.addEventListener('updatefound', function() {\n\t\t\t\t\t// If updatefound is fired, it means that there's\n\t\t\t\t\t// a new service worker being installed.\n\t\t\t\t\tmanageServiceWorker.trackInstalling(reg.installing);\n\t\t\t\t});\n\n\t\t\t\treturn reg.sync.register('syncOfflineData');\n\t\t\t})\n\t\t\t.catch(function(err) {\n\t\t\t\tconsole.log('Service worker registration failed:', err);\n\t\t\t});\n\n\t\t// Listen for the controlling service worker changing and reload the page\n\t\tnavigator.serviceWorker.addEventListener('controllerchange', function() {\n\t\t\twindow.location.reload();\n\t\t});\n\t};\n\n\tthis.trackInstalling = function(worker) {\n\t\tlet manageServiceWorker = this;\n\t\tworker.addEventListener('statechange', function() {\n\t\t\tif (worker.state == 'installed') {\n\t\t\t\tmanageServiceWorker.updateReady(worker);\n\t\t\t}\n\t\t});\n\t};\n\n\tthis.updateReady = function(worker) {\n\t\tlet confirmDialog = window.confirm('New Service Worker version available. Would you like to update?');\n\t\tif (confirmDialog == true) {\n\t\t\tworker.postMessage({action: 'skipWaiting'});\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t};\n}", "async function send() {\n console.log('Registering service worker...')\n const register = await navigator.serviceWorker.register('/serviceWorker.js', {\n // this worker is applied to the home page/index\n scope: '/'\n })\n console.log('Service worker registered')\n\n console.log('Registering push...')\n // register is the variable when we registered the service worker (all of this code can be found on the web-push Github page)\n const subscription = await register.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: urlBase64ToUint8Array(publicVapidKey),\n });\n console.log('Push registered')\n\n console.log('Sending push notification...')\n // Send the subscription obejct to our backend (see index.js)\n await fetch('/subscribe', {\n method: 'POST',\n body: JSON.stringify(subscription),\n headers: {\n 'content-type': 'application/json'\n }\n });\n console.log('Push sent')\n}", "registerAutoWorker(){\r\n var functionPtr = Fatusjs.autoWorker;\r\n if(!this.autoInterval) {\r\n this.autoInterval = setInterval(\r\n functionPtr,\r\n 30000\r\n );\r\n }\r\n }", "addWorker(){\r\n if(this.workerPool.length<FATUS_MAX_WORKER){\r\n let worker = new FatusWorker(this);\r\n this.initWorker(worker);\r\n this.workerPool.push(worker);\r\n console.log(MODULE_NAME + ': new worker created %s',worker.name);\r\n worker.run();\r\n }else{\r\n console.log(MODULE_NAME + ': workerpool full, skip adding');\r\n }\r\n }", "async createWorkers () {\n\n let worker;\n if ( !this.fallback ) {\n\n let workerBlob = new Blob( this.functions.dependencies.code.concat( this.workers.code ), { type: 'application/javascript' } );\n let objectURL = window.URL.createObjectURL( workerBlob );\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new TaskWorker( i, objectURL );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n else {\n\n for ( let i = 0; i < this.workers.instances.length; i ++ ) {\n\n worker = new MockedTaskWorker( i, this.functions.init, this.functions.execute );\n this.workers.instances[ i ] = worker;\n\n }\n\n }\n\n }", "function subscribe() {\n navigator.serviceWorker.ready\n .then(registration => {\n return registration.pushManager.subscribe({userVisibleOnly: true})\n })\n .then(subscription => {\n console.log('Subscribed ', subscription.endpoint)\n return fetch('http://localhost:4040/register', \n {\n method: 'post',\n headers: {'Content-Type': 'application/json'},\n body: JSON.stringify({\n endpoint: subscription.endpoint\n })\n })\n }).then(setUnsubscribeButton)\n}", "function Workers () {\n if (!(this instanceof Workers)) {\n return new Workers()\n }\n if (!pool) {\n if (!process.browser) {\n pool = workerpool.pool(__dirname + '/worker.js')\n } else {\n pool = workerpool.pool(process.env.DATT_NODE_JS_BASE_URL + process.env.DATT_NODE_JS_WORKER_FILE)\n }\n }\n}", "async function injectNamedScript(cdp, code, url, extra) {\n const {\n frame, // puppeteer Frame object; if given, create isolated world in here\n exeCtx // puppeteer ExecutionContext object; if given, use that isolated world\n } = extra || {};\n\n let xcid = null;\n if (frame) {\n const { executionContextId } = await cdp.send('Page.createIsolatedWorld', {\n frameId: frame._id, // EEEK implementation detail\n worldName: \"fuelInjector\",\n grantUniversalAccess: false\n });\n xcid = executionContextId;\n } else if (exeCtx) {\n xcid = exeCtx._contextId; // EEEK implementation detail\t\n }\n\n if (typeof code === \"function\") {\n code = `(${code.toString()})();`;\n }\n let params = {\n expression: code,\n sourceURL: url,\n persistScript: true,\n };\n if (xcid) {\n params.executionContextId = xcid;\n }\n const { scriptId, exceptionDetails } = await cdp.send('Runtime.compileScript', params);\n\n if (exceptionDetails) {\n throw exceptionDetails;\n }\n\n params = {\n scriptId: scriptId,\n silent: true,\n returnByValue: true,\n };\n if (xcid) {\n params.executionContextId = xcid;\n }\n return await cdp.send('Runtime.runScript', params);\n}", "function injectReportDialog(options) {\n if (options === void 0) { options = {}; }\n if (!global.document) {\n return;\n }\n if (!options.eventId) {\n _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error(\"Missing eventId option in showReportDialog call\");\n return;\n }\n if (!options.dsn) {\n _sentry_utils__WEBPACK_IMPORTED_MODULE_4__.logger.error(\"Missing dsn option in showReportDialog call\");\n return;\n }\n var script = global.document.createElement('script');\n script.async = true;\n script.src = new _sentry_core__WEBPACK_IMPORTED_MODULE_5__.API(options.dsn).getReportDialogEndpoint(options);\n if (options.onLoad) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n script.onload = options.onLoad;\n }\n var injectionPoint = global.document.head || global.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n }\n}", "registerServiceWithInterface(serviceType, supportedInterface) {\n const serviceFactory = new TypeServiceFactory_1.TypeServiceFactory(serviceType, [supportedInterface]);\n this.registerFactory(serviceFactory);\n }", "function createWorker(worker) {\n\t if (typeof worker === 'string') {\n\t return new Worker(worker);\n\t }\n\t else {\n\t var blob = new Blob(['self.onmessage = ', worker.toString()], { type: 'text/javascript' });\n\t var url = URL.createObjectURL(blob);\n\t return new Worker(url);\n\t }\n\t}", "addPriorityWorker(){\r\n if(this.priorityWorkerPool.length<10) {\r\n console.log(MODULE_NAME + ': adding priority worker');\r\n let worker = new FatusPriorityWorker(this);\r\n this.initWorker(worker);\r\n worker.setStackProtection(3);\r\n this.priorityWorkerPool.push(worker);\r\n worker.run();\r\n }\r\n }", "createDataLayer(options) {\n return this._zone.runOutsideAngular(() => {\n return this._map.then(m => {\n let data = new google.maps.Data(options);\n data.setMap(m);\n return data;\n });\n });\n }", "function WebWorkerSource(worker){\n this._worker = worker;\n}", "function setAnalyticsCollectionEnabled(analyticsId, enabled) {\r\n window[\"ga-disable-\" + analyticsId] = !enabled;\r\n }", "get _worker() {\n delete this._worker;\n this._worker = new ChromeWorker(\"resource://gre/modules/PageThumbsWorker.js\");\n this._worker.addEventListener(\"message\", this);\n return this._worker;\n }", "function startWorker(url, method, bodydata, msgFunc, errFunc) {\n\t//start worker\n\tworker = new Worker(\"worker.js\");\n\t//Function to call on worker success\n\tworker.onmessage = msgFunc;\n\t//Function called on worker error\n\tworker.onmessageerror = errFunc;\n\tworker.postMessage({\n\t\turl: url,\n\t\tmethod: method,\n\t\tbodydata: bodydata,\n\t});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOT FINISHED Dictionary iterator: work your way through the entries of my custom dictionary object. DictionaryIterator constructor: takes errors object and the dictionary to iterate through.
function DictionaryIterator(objErrors, objDictionary) { if (objErrors != gstrPrototype) { //Set up error-handling: this.module = "Iterator"; var strRoutine = "DictionaryIterator"; var strAction = ""; setErrorsObj(this, objErrors, strRoutine); try { //Dictionaries are really just smart arrays, so //call the array function of the dictionary to get all the items, //and then just use an array iterator } //end try catch (e) { this.errors.add(this.module, strRoutine, strAction, e); throw new Error(strRoutine + " failed"); } //end catch } //end if this isn't a prototype } //end constructor DictionaryIterator
[ "function PostorderIterator(objErrors, objRoot) {\n\tif (objErrors != gstrPrototype) {\n\t\t//Set up error-handling:\n\t\tthis.module = \"Iterator\";\n\t\tthis.init(objErrors, objRoot);\n\t} //end if this isn't a prototype\n} //end constructor PostorderIterator", "function PreorderIterator(objErrors, objRoot) {\n\tif (objErrors != gstrPrototype) {\n\t\t//Set up error-handling:\n\t\tthis.module = \"Iterator\";\n\t\tthis.init(objErrors, objRoot);\n\t} //end if this isn't a prototype\n} //end constructor PreorderIterator", "function printIteratorEntries(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iterator, config, indentation, depth, refs, printer, \n // Too bad, so sad that separator for ECMAScript Map has been ' => '\n // What a distracting diff if you change a data structure to/from\n // ECMAScript Object or Immutable.Map/OrderedMap which use the default.\n separator = \": \") {\n let result = \"\";\n let current = iterator.next();\n if (!current.done) {\n result += config.spacingOuter;\n const indentationNext = indentation + config.indent;\n while (!current.done) {\n const name = printer(current.value[0], config, indentationNext, depth, refs);\n const value = printer(current.value[1], config, indentationNext, depth, refs);\n result += indentationNext + name + separator + value;\n current = iterator.next();\n if (!current.done) {\n result += \",\" + config.spacingInner;\n }\n else if (!config.min) {\n result += \",\";\n }\n }\n result += config.spacingOuter + indentation;\n }\n return result;\n }", "function OrderIterator(objErrors, objRoot) {\n\tif (objErrors != gstrPrototype) {\n\t\t//Set up error-handling:\n\t\tthis.module = \"Iterator\";\n\t\tthis.init(objErrors, objRoot);\n\t} //end if this isn't a prototype\n} //end constructor PreorderIterator", "*[Symbol.iterator]() {\n for (let wo of this.worldObjects.values())\n yield wo;\n }", "function PostIt_init(objErrors, objRoot) {\n\tvar strRoutine = \"PreorderIterator\";\n\tvar strAction = \"\";\n\tsetErrorsObj(this, objErrors, strRoutine);\n\n\ttry {\n\t\tstrAction = \"calling the init of PostorderIterator's superclass (OrderIterator) to set up inherited properties\";\n\t\tPostorderIterator.superclass.init.call(this, objErrors, objRoot);\n\t} //end try\n\tcatch (e) {\n\t\tthis.errors.add(this.module, strRoutine, strAction, e);\n\t\tthrow new Error(strRoutine + \" failed\");\n\t} //end catch\n} //end constructor PreorderIterator", "parseEntries() {}", "function ArrayIterator(objErrors, objArray) {\n\tif (objErrors != gstrPrototype) {\n\t\t//Set up error-handling:\n\t\tthis.module = \"Iterator\";\n\t\tvar strRoutine = \"ArrayIterator\";\n\t\tvar strAction = \"\";\n\t\tsetErrorsObj(this, objErrors, strRoutine);\n\n\t\ttry {\n\t\t\tstrAction = \"creating properties\";\n\t\t\tthis.currentIndex = undefined;\n\t\t\tthis.currentArray = objArray;\n\t\t} //end try\n\t\tcatch (e) {\n\t\t\tthis.errors.add(this.module, strRoutine, strAction, e);\n\t\t\tthrow new Error(strRoutine + \" failed\");\n\t\t} //end catch\n\t} //end if this isn't a prototype\n} //end constructor ArrayIterator", "getIterator(obj) {\n for (var item = this._head; item; item = item.next) {\n if (item.data === obj) {\n return new Iterator(this, item);\n }\n }\n }", "function icalrecur_iterator(options) {\n this.fromData(options);\n }", "* entries () {\n for (var i = 0; i < this._order.length; i++) {\n var key = this._order[i]\n yield [key, this._entries[key]]\n }\n }", "function NullIterator(objErrors) {\n\tif (objErrors != gstrPrototype) {\n\t\t//Set up error-handling:\n\t\tthis.module = \"Iterator\";\n\t\tvar strRoutine = \"NullIterator\";\n\t\tvar strAction = \"\";\n\t\tsetErrorsObj(this, objErrors, strRoutine);\n\n\t\ttry {\n\t\t\t//since NullIterator has only methods, and all those are defined in its prototype\n\t\t\t//nothing goes here :)\n\t\t} //end try\n\t\tcatch (e) {\n\t\t\tthis.errors.add(this.module, strRoutine, strAction, e);\n\t\t\tthrow new Error(strRoutine + \" failed\");\n\t\t} //end catch\n\t} //end if this isn't a prototype\n} //end constructor NullIterator", "[Symbol.iterator]() {\n let i = 0\n let ids = null\n return {\n next: () => {\n if (ids === null) {\n ids = []\n for (let id in safari.extension.settings) {\n if (id.substr(0, 5) == 'rule_') {\n ids.push(id.substr(5))\n }\n }\n ids.sort().reverse()\n }\n if (i >= ids.length) {\n return {done: true}\n } else {\n return {done: false, value: this.get(ids[i++])}\n }\n }\n }\n }", "function forInObjectLoop() {\n\n var employee = {\n name: \"Joe Bloggs\",\n age: 25,\n title: \"Data analyst\"\n }\n\n for (var property in employee) {\n \n // log is the key\n Logger.log(property); // e.g. name\n \n // log the corresponding value\n Logger.log(employee[property]);\n \n }\n \n}", "function actualRehashValues() {\n var oldBuckets = currentHashTable.buckets;\n\n actualRehash();\n\n currentHashTable.slots = slots;\n currentHashTable.size = size;\n currentHashTable.buckets = buckets;\n\n //console.log(JSON.stringify(currentHashTable, null, 4));\n\n oldBuckets.map((linkedList) => {\n var node = linkedList.getHead();\n //console.log(node);\n\n while(node !== null) {\n const {key, value} = node.getValue();\n this.set(key, value, false);\n\n node = node.getNext();\n }\n });\n }", "_doubleEntriesSizeAndRehashEntries() {\n const entries = this._entries;\n const oldLength = this._entryRange;\n const newLength = oldLength * 2;\n //Reset the values\n this._entries = new Array(newLength);\n this._entryRange = newLength;\n this._spaceTaken = 0;\n for (let entry of entries) {\n if(!entry) {\n //Make sure we skip empty entries\n continue;\n }\n //Re-insert each entry back into the map\n this.addEntry(entry.key, entry.value);\n }\n }", "function TestGeneratorObjectMethods() {\n function* g() { yield 1; }\n var iter = g();\n\n function TestNonGenerator(non_generator) {\n assertThrows(function() { iter.next.call(non_generator); }, TypeError);\n assertThrows(function() { iter.next.call(non_generator, 1); }, TypeError);\n assertThrows(function() { iter.throw.call(non_generator, 1); }, TypeError);\n }\n\n TestNonGenerator(1);\n TestNonGenerator({});\n TestNonGenerator(function(){});\n TestNonGenerator(g);\n TestNonGenerator(g.prototype);\n}", "function SearchIterator(sequence) {\n // current page of results\n this.search = sequence.search\n this.slice = []\n this.currentPage = 0\n this.currentIndex = 0\n this.isLastPage = false\n this.sliceSize = 1000\n }", "constructor(count,begin,end){\n super();\n this.count=count;\n this.begin=begin;\n this.localJournal=new Map();\n this.end=end;\n this.countEval=null;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Functions dealing with OnScreens check if feed from myURL is present on screen
function checkOnScreen(myURL){ HeadingArray = getOnScreenHeadingArray(); URLArray = getOnScreenURLArray(); var i = URLArray.indexOf(myURL); if( i != -1 ){ alert("Already exists OnScreen with heading: "+HeadingArray[i]+" ."); return true; } }
[ "function loadOnScreen(){\n\tHeadingArray = getOnScreenHeadingArray();\n URLArray = getOnScreenURLArray();\n\t\n\tfor(var i = 0; i<HeadingArray.length; i++)\n\t getFeed(HeadingArray[i],URLArray[i]);\n}", "function checkURL()\n{\n if (/\\bfull\\b/.test(location.search)) toggleMode();\n if (/\\bstatic\\b/.test(location.search)) interactive = false;\n}", "function isViewed(display_frame_name) \n{ \n for (i = 0; i < active_displays_l.length; i++) \n { \n if (active_displays_l[i] == display_frame_name) \n { \n return true; \n } \n } \n return false; \n}", "function hasGoogleFeedAPILoaded(evt) {\n\t\tlog('Google Feed API has loaded..');\n\t\t$('footer > button').button('loading');\n\t\tvar items = fetchFeedItems(FEED_URL, CURSOR, 20, hasFeedItemsLoaded);\n\t}", "function scanCheck() {\n let isScaning = GM_getValue(\"isScaning\");\n if (isScaning === undefined) {\n isScaning = false;\n }\n\n if (isScaning) {\n scanPosts();\n }\n}", "function displayFeedsUrlList() {\n const message = document.getElementById(\"feedsUrlMessage\");\n const headers = {\"Authorization\": getToken()};\n apiRequest(\"GET\", \"get_feeds_url.php\", null, headers, res => {\n const jsonRes = JSON.parse(res.responseText);\n for (const feed of jsonRes.feeds)\n addFeedUrlToList(feed.id, feed.url);\n message.innerHTML = \"\";\n message.className = \"\";\n }, err => handleRequestError(err.status, \"Erreur lors de la récupération des flux.\", message)\n );\n}", "function CheckForHNews () {\n\tvar hNewsContainer = document.getElementsByClassName('hnews hentry');\n\tif (hNewsContainer.length > 0) {\n\t\tvar hnews = new hNews(hNewsContainer[0]);\n\t\tconsole.log(hnews);\n\n\t\t// AP's News Registry beacon\n\t\tvar beacon = null;\n\t\tvar beaconSnapshots = document.evaluate(\".//img[contains(@src, 'http://analytics.apnewsregistry.com/analytics/v2/image.svc')]\", hNewsContainer[0], null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);\n\t\tif (beaconSnapshots.snapshotLength > 0) {\n\t\t\tbeacon = new apBeacon(beaconSnapshots.snapshotItem(0).getAttribute('src'));\n\t\t\tconsole.log(beacon);\n\t\t}\n\n\t\t// Send the data along...\n\t\tchrome.extension.sendMessage({hNews: hnews, apBeacon: beacon});\n\t}\n}", "function retrieveStatus(){\n request(icecastUrl, function (error, response, body) {\n // If error, log it\n var mountpointList = JSON.parse(body).icestats.source;\n // Check for all three mountpoints\n checkStatus(mountpointList, 'listen');\n checkStatus(mountpointList, 'hub');\n checkStatus(mountpointList, 'harrow');\n });\n}", "function checkStatus() {\n if (supportsAvif !== null && supportsWebp !== null) {\n showOverlay();\n return;\n }\n }", "function isUrlAffected() {\n let urlType = getUrlType()\n\n if(urlType === 'playlist' && AFFECTED_URL_TYPES.includes('playlists'))\n return true\n\n if(urlType === 'album' && AFFECTED_URL_TYPES.includes('albums'))\n return true\n\n if(urlType === 'collection' && AFFECTED_URL_TYPES.includes('collection'))\n return true\n\n return false\n}", "function checkXML(page,metrics){\n\n //! No Internet\n if (internet.networkStatus !== \"Connected\" && internet.networkStatus !== \"Home Network\")\n {\n // Only if live\n metrics = false;\n }\n\n //! Check if metrics was met\n if(metrics == true)\n {\n\n if(page === \"main\")\n {listView.footer = footerNull; }\n\n refresh.start();\n }\n\n\n if(page === \"main\")\n { Storage.readMovies(databaseModel,movieId);\n listView.footer = footer;\n }\n else if (page === \"theaters\")\n {\n Storage.readTheaters(databaseModel,near)\n }\n else if (page === \"theater\")\n {\n Storage.readTheater(databaseModel,near,theaterTitle)\n }\n else if (page === \"showtimes\")\n {\n Storage.readShowtimes(databaseModel,near,movieTitle)\n }\n else if (page === \"reviews\")\n {\n Storage.readReviews(databaseModel,movieTitle)\n }\n\n databaseLoaded = true;\n loaded = true;\n}", "async isCorrectPageOpened() {\n let currentURL = await PageUtils.getURL()\n return currentURL.indexOf(this.pageUrl)!== -1\n }", "function GADGET_RSS_Entry_Open(Entry)\n{\t\n\t//>> Clear Timers\n\tif (Timer_Interval)\n\t\tclearTimeout(Timer_Interval);\n\t\n\tif (Timer_Auto_Scroll)\n\t\tclearTimeout(Timer_Auto_Scroll);\n\n\t//>> Get Variables\n\t\t\n\tvar\tDisplay = \"Browser\";\n\tvar\tEntry_Disp = \"5\";\n\t\t\n\tvar Size = System.Gadget.Settings.read(\"Size\");\n\t\n\tSystem.Gadget.Settings.write(\"Entry_Open\", Entry);\n\t\n\t//>> Reset Current Entry Styles\n\t//var Entry_Count = parseInt(System.Gadget.document.getElementById(\"Entry_Count\").innerHTML);\n\tvar Entry_Count = parseInt(noOfFeeds);\n\tvar Page = System.Gadget.Settings.read(\"Page\");\n\t\n\tvar i = (Page * Entry_Disp) - Entry_Disp;\n\tvar Limit = Page * Entry_Disp;\n\tif (Limit > Entry_Count)\n\t\tLimit = Entry_Count;\n\t\t\n\twhile (i < Limit)\n\t{\n\t\tSystem.Gadget.document.getElementById(\"Feed_Entry_\" + i).className = Size + \"-Feed-Entry\";\n\t\tSystem.Gadget.document.getElementById(\"Feed_Entry_\" + i + \"_Close\").style.display = \"none\";\n\t\ti++;\n\t}\n\t\n\n\t\tvar xURL = System.Gadget.document.getElementById(\"Entry_\" + Entry + \"_Link\").innerHTML;\n\t\t\n\t\tvar\tInterval = 60;\n\t\t\t\n\t\tif (Interval != '' && Interval != \"Off\")\n\t\t{\n\t\t\tInterval = Interval * 60000;\n\t\t\tTimer_Interval = setTimeout(GADGET_RSS_Feed_Start, Interval);\n\t\t}\n\t\t\n\t\tvar Auto_Scroll = System.Gadget.Settings.read(\"Auto_Scroll\");\n\t\tif (Auto_Scroll == '')\n\t\t\tAuto_Scroll = 20;\n\t\t\n\t\tif (Auto_Scroll != '' && Auto_Scroll != \"Off\")\n\t\t{\n\t\t\tAuto_Scroll = Auto_Scroll * 1000;\n\t\t\tTimer_Auto_Scroll = setTimeout(GADGET_RSS_Auto_Scroll, Auto_Scroll);\n\t\t}\n\t\t\n\t\tShell.Run(xURL);\t\t\n\t//}\n}", "function checkurl() {\n\tvar sub = window.location.hash, //gets the hash varible we built up earlyer\n\tsubreddits = sub.replace('#', ' ').trimLeft(),//removes the hash and trims it up\n\turl;\n console.log(subreddits);//logging dis bitch\n\tif (localStorage.getItem(\"includepics\") === 'true') {\n\t\tif (window.location.hash) {\n\t\t\turl = \"http://www.reddit.com/r/pics+\" + subreddits + \".json\"; //sets url to /r/pics + other subreddits\n\t\t\t$('.alert').remove(); //removes the \"add subreddits\" text\n\t\t\timgload(url);\n\t\t} else {\n\t\t\turl = \"http://www.reddit.com/r/pics.json\";//sets url to the default only /r/pics \n\t\t\t$('.alert').remove(); //removes the \"add subreddits\" text\n\t\t\timgload(url);\n\t\t}\n\t} else if (localStorage.getItem(\"includepics\") === 'false' && window.location.hash) {\n\t\turl = \"http://www.reddit.com/r/\" + subreddits + \".json\"; //sets url to just other subreddits\n\t\t$('.alert').remove(); //removes the \"add subreddits\" text\n\t\t$(\".pics\").remove(); //removes all /r/pics images\n\t\timgload(url);\n\t} else {\n\t\t$('.images').append('<div class=\"image alert\" id=\"plz\"><h1>Add Subreddits Plz</h1></div>'); //appends a nice alert... lol\n\t}\n}", "function gadgetFirstRun(){\r\n \r\n var profileStates = prefs.getArray('profiles');\r\n if(!profileStates || profileStates=='') return true;\r\n else return false;\r\n }", "async function updateData() {\n urlForVideo = document.location.href;\n \n if (urlForVideo != lastURL) {\n lastURL = urlForVideo;\n startTimeStamp = Math.floor(Date.now() / 1000);\n }\n \n //* If page has all required propertys\n if($('.roomName.on').get(0) != undefined) {\n\n videoTitle = $('.roomName.on')[0].innerHTML\n videoAuthor = $('.sessionsCount')[0].innerHTML.match(\"[0-9]*\")[0] + \" \" + await getString(\"presence.watching\")\n playbackBoolean = true\n\n var data = {\n clientID: '516742299355578380',\n presenceData: {\n details: $('<div/>').html(videoTitle).text(),\n state: $('<div/>').html(videoAuthor).text(),\n largeImageKey: 'rt_lg',\n largeImageText: chrome.runtime.getManifest().name + ' V' + chrome.runtime.getManifest().version,\n startTimestamp: startTimeStamp\n },\n trayTitle: $('<div/>').html(videoTitle).text(),\n playback: playbackBoolean,\n service: 'Rabb.it'\n }\n\n } else if(document.location.pathname == \"/\") {\n data = {\n clientID: '516742299355578380',\n presenceData: {\n details: await getString(\"presence.browsing\"),\n largeImageKey: 'rt_lg',\n largeImageText: chrome.runtime.getManifest().name + ' V' + chrome.runtime.getManifest().version,\n startTimestamp: startTimeStamp\n },\n trayTitle: \"\",\n service: 'Rabbit',\n playback: true\n }\n }\n chrome.runtime.sendMessage({presence: data})\n}", "async function screenShare() {\n // if we're already sharing, then stop\n if (my_screen_stream) {\n // unpublish\n await bandwidthRtc.unpublish(my_screen_stream.endpointId);\n\n // stop the tracks locally\n var tracks = my_screen_stream.getTracks();\n tracks.forEach(function (track) {\n console.log(`stopping stream`);\n console.log(track);\n track.stop();\n });\n document.getElementById(\"screen_share\").innerHTML = \"Screen Share\";\n\n my_screen_stream = null;\n document.getElementById(\"share\").style.display = \"none\";\n } else {\n video_constraints = {\n frameRate: 30,\n };\n // getDisplayMedia is the magic function for screen/window/tab sharing\n try {\n my_screen_stream = await navigator.mediaDevices.getDisplayMedia({\n audio: false,\n video: video_constraints,\n });\n } catch (err) {\n if (err.name != \"NotAllowedError\") {\n console.error(`getDisplayMedia error: ${err}`);\n }\n }\n\n if (my_screen_stream != undefined) {\n // we're now sharing, so start, and update the text of the link\n document.getElementById(\"screen_share\").innerHTML = \"Stop Sharing\";\n\n // start the share and save the endPointId so we can unpublish later\n var resp = await bandwidthRtc.publish(\n my_screen_stream,\n undefined,\n \"screenshare\"\n );\n my_screen_stream.endpointId = resp.endpointId;\n document.getElementById(\"share\").style.display = \"inline-block\";\n document.getElementById(\"share\").onClick = fullScreenShare();\n }\n }\n}", "function checkLiveData(teamUrl, scoreUrl){\n if ( teamDataDate === \"\" || Date.parse(teamDataDate) + 12*60*60*1000 < new Date ){\n refreshTeamData(teamUrl)\n }\n if( teamDataDate !== \"\" ){\n refreshLiveData(scoreUrl)\n }\n //add liveDataTimestamp comparison after timestamp has been set\n if( liveData.lastModified ){\n createTickerData(liveData)\n }\n}", "function showScreen(screenId) {\n const allScreens = document.getElementsByClassName(\"screen\");\n let shownScreen = undefined;\n for (const screen of allScreens) {\n if (screen.id === screenId) {\n screen.classList.remove(\"hidden\");\n shownScreen = screen;\n }\n else {\n screen.classList.add(\"hidden\");\n }\n }\n if (shownScreen === undefined) {\n throw new Error(\"Cannot find screen \" + screenId);\n }\n return shownScreen;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public: Registers new middleware middleware A generic pipeline component function Returns nothing.
register (middleware) { this.stack.add(middleware) }
[ "function registerMiddleware(middleware, options) {\n if (typeof middleware === 'string') {\n middleware = restify[middleware](options);\n }\n else {\n middleware = middleware.bind(virgilio);\n }\n this.log.trace('Adding middleware.');\n server.use(middleware);\n }", "getMiddleware() {\n var ref;\n const manifest = this.getMiddlewareManifest();\n const middleware = manifest == null ? void 0 : (ref = manifest.middleware) == null ? void 0 : ref[\"/\"];\n if (!middleware) {\n return;\n }\n return {\n match: getMiddlewareMatcher(middleware),\n page: \"/\"\n };\n }", "use(pattern, fn) {\n this.handlerChain = this.handlerChain.concat([{ pattern, fn }]);\n this.setMiddlewares();\n }", "$registerMiddlewareStore() {\n this.$container.bind('Adonis/Core/MiddlewareStore', () => MiddlewareStore_1.MiddlewareStore);\n }", "function globalMiddlewareTest(req, res, next){\n console.log(\"Global Middleware running!\");\n next();\n}", "static create() {\n return new FastHttpMiddlewareHandler();\n }", "function _middleware(req, res, next) {\n if (req._redis_source) {\n if (chain) {\n next();\n } else {\n res.end(req.model);\n }\n return;\n }\n if (req.method.match(/create|update|delete/)) {\n publisher.publishJSON(_chan, { model: req.model, method:req.method, _redis_source:_client_id});\n }\n next();\n }", "function middlewares() {\n app.middlewares = {}\n const basePath = path.join(app.root, '/middlewares')\n let middlewares = app.config.get('express').middlewares\n if (middlewares && Array.isArray(middlewares) && middlewares.length) {\n for (let m of middlewares) {\n let middleware = require(path.join(basePath, m.dest))(app)\n app.middlewares[m.dest.toLowerCase()] = middleware\n\n if (middleware.length == 4) { //error handler\n errorHandlers.push(middleware)\n continue\n }\n\n if (m.src)\n server.use(m.src, wrapper(middleware))\n else\n server.use(wrapper(middleware))\n }\n if (middlewares.length)\n app.drivers.logger.success('Middleware', 'initialized')\n }\n }", "function compose() {\n var handlers = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n handlers[_i] = arguments[_i];\n }\n var middleware = generate(handlers);\n return function (req, res, done) { return middleware(null, req, res, done); };\n}", "initializeMiddleware() {\n if (this.hasInitialized) throw new Error('authenticated view middleware already initialized');\n this.hasInitialized = true;\n\n const {\n htmlDirectory,\n htmlFilename,\n } = this.configuration;\n\n const trshcmpctrClientRouter = express.Router();\n\n trshcmpctrClientRouter.get('/', [\n handleRenderAuthenticated.bind(null, htmlDirectory, htmlFilename),\n // Redirect to login if not authenticated\n handleRedirect.bind(null, '/login')\n ]);\n\n // Serve application static assets\n trshcmpctrClientRouter.use(express.static(htmlDirectory));\n trshcmpctrClientRouter.use(handleError);\n\n this.router = trshcmpctrClientRouter;\n }", "function initMiddleware() {\n app.use(express.compress());\n app.use(express.static(__dirname + '/public'));\n app.use(express.logger());\n app.use(express.bodyParser());\n\n /**\n * Rendr routes are attached with `app.get()`, which adds them to the\n * `app.router` middleware.\n */\n app.use(app.router);\n\n /**\n * Error handler goes last.\n */\n app.use(mw.errorHandler());\n}", "function createMiddleware(config) {\n // Get the basePath for all spec versions.\n const basePaths = {};\n _.map(config.swaggerVersions, function(spec) {\n basePaths[spec.info.version] = spec.basePath;\n })\n\n // Build a swagger spec parameter that can be used to validate the version\n // header value. This approach results in consistent error messages.\n const versionHeaderParameter = {\n name: 'X-Api-Version',\n in: 'header',\n description: 'API version header',\n type: 'string',\n enum: _.keys(basePaths)\n };\n\n // Prepends the relevant basePath when a version header is found.\n return function*(next) {\n const version = this.headers['x-api-version'];\n if (version !== undefined) {\n const validationError = validate(version, versionHeaderParameter);\n if (validationError === undefined) {\n const basePath = basePaths[version];\n this.path = basePath + this.path;\n } else {\n this.status = 400;\n this.body = {\n error: 'Validation Failed',\n error_name: 'VALIDATION_FAILED',\n details: [validationError]\n };\n }\n }\n yield next;\n };\n}", "function setHttpMiddleware(middleware) {\n\tconst cmfMiddlewareIndex = middlewares.indexOf(cmfMiddleware);\n\tmiddlewares.splice(cmfMiddlewareIndex - 1, 0, middleware);\n\tdefaultHttpMiddlewareOverwrite = true;\n}", "head(route, ...middleware) {\n return this._addRoute(route, middleware, \"HEAD\");\n }", "register() {\n this._container.instance('expressApp', require('express')())\n\n //TODO: add Socket.io here @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n\n this._container.register('httpServing', require(FRAMEWORK_PATH + '/lib/HTTPServing'))\n .dependencies('config', 'expressApp')\n .singleton()\n\n this._container.instance('expressRouterFactory', () => {\n return require('express').Router()\n })\n\n this._container.register('RoutesResolver', require(FRAMEWORK_PATH + '/lib/RoutesResolver'))\n .dependencies('logger', 'app', 'expressRouterFactory')\n\n this._container.register('httpErrorHandler', require(FRAMEWORK_PATH + '/lib/HTTPErrorHandler'))\n .dependencies('logger')\n .singleton()\n\n //TODO: add WS the serving @url https://trello.com/c/KFCXzYom/71-socketio-adapter\n }", "function middlewareInitialiser(req, res, next, config) {\n // Get request start time\n var startTime = +new Date();\n\n // Listen to response object's 'finish' event and generate log + fire log events\n res.on('finish', function () {\n var log = generateLog(req, res, startTime, config),\n format = utils.getLogFormat(config),\n spacing = utils.getFormatSpacing(config);\n\n // Write to specified file streams\n if (config.streams.length) logToStream(utils.stringifyLog(log, format, spacing), config);\n\n // Write request log to stdout if option is present\n config.logToConsole ? logToStdOut(log, format, spacing, config) : null;\n\n // Fire woodlot middleware events\n fireMiddlewareEvents(res, log);\n });\n\n next();\n}", "function getDefaultMiddleware(options) {\n if (options === void 0) {\n options = {};\n }\n\n var _options = options,\n _options$thunk = _options.thunk,\n thunk$1 = _options$thunk === void 0 ? true : _options$thunk,\n _options$immutableChe = _options.immutableCheck,\n immutableCheck = _options$immutableChe === void 0 ? true : _options$immutableChe,\n _options$serializable = _options.serializableCheck,\n serializableCheck = _options$serializable === void 0 ? true : _options$serializable;\n var middlewareArray = new MiddlewareArray();\n\n if (thunk$1) {\n if (isBoolean(thunk$1)) {\n middlewareArray.push(thunk);\n } else {\n middlewareArray.push(thunk.withExtraArgument(thunk$1.extraArgument));\n }\n }\n\n {\n if (immutableCheck) {\n /* PROD_START_REMOVE_UMD */\n var immutableOptions = {};\n\n if (!isBoolean(immutableCheck)) {\n immutableOptions = immutableCheck;\n }\n\n middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n /* PROD_STOP_REMOVE_UMD */\n }\n\n if (serializableCheck) {\n var serializableOptions = {};\n\n if (!isBoolean(serializableCheck)) {\n serializableOptions = serializableCheck;\n }\n\n middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n }\n }\n\n return middlewareArray;\n}", "put(route, ...middleware) {\n return this._addRoute(route, middleware, \"PUT\");\n }", "getMiddlewareByName (middlewareName) {\n if (!check.isDefined(this.middlewares, middlewareName)) {\n throw new MiddlewareNotFoundException(middlewareName)\n }\n\n return this.middlewares[middlewareName]\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fenetre javascript de confirmation de suppression d'un compte
function confirme_suppression_compte(objet,id) { if (confirm("Souhaitez vous supprimer cet identifiant : "+objet)) window.location="comptes_del.php?id="+id; }
[ "function confirmerSuppression() {\n let n = new Noty({\n text: 'Confirmer la demande de suppression ',\n layout: 'center', theme: 'sunset', modal: true, type: 'info',\n animation: {\n open: 'animated lightSpeedIn',\n close: 'animated lightSpeedOut'\n },\n buttons: [\n Noty.button('Oui', 'btn btn-sm btn-success marge ', function () {\n supprimer();\n n.close();\n }),\n Noty.button('Non', 'btn btn-sm btn-danger', function () { n.close(); })\n ]\n }).show();\n}", "function onSupprime(qui){\n var n = qui.replace(\"supprime\", \"\");\n var nom = document.getElementById(\"compte\" + n).innerText;\n var supprime = window.confirm(\"Supprimer le compte : \\n \" + nom)\n if (supprime) {\n $.get('/getSupprimeCompte?compte=' + nom, function (data, status) { \n document.getElementById(n).remove();\n });\n } \n }", "function alertSecurity() {\n var txt;\n if (confirm(\"Are you sure to notify Security?\")) {\n alert(\"Already notified Security.\");\n } else {\n alert(\"Canceled to notify Security!\");\n }\n }", "function revokeCustomConfirmationPopup() {\n\thideModel('confermPopUp');\n}", "formNotOK() {\n alert(\"verifiez les champs en rouge\");\n }", "function confirmar() {\n if ($('#v_estado').val() === \"\") {\n alert('Seleccione un pedido.!');\n } else {\n if ($('#v_estado').val() === 'PENDIENTE') {\n var opcion = confirm('Desea confirmar el pedido.??');\n if (opcion === true) {\n\n }\n } else {\n if ($('#v_estado').val() === 'CONFIRMADO') {\n alert('El pedido ya fue confirmado..');\n }\n }\n }\n\n\n}", "function askDNTConfirmation() {\n var r = confirm(\"La signal DoNotTrack de votre navigateur est activé, confirmez vous activer \\\n la fonction DoNotTrack?\")\n return r;\n }", "function desactiveAfficheErreur(){\n\tvar afficheErreur=document.getElementById('afficheErreur');\n\tafficheErreur.style.display = ' none' ;\t\n}", "function adminConfirmation(){\n\tvar x = confirm(\"Are you sure you want to delete this user's account?\");\n\tif (x){\n return true;\n\t}else{\n\t return false;\n\t}\n}//end of confirmation", "function con() {\n var txt;\n if (confirm(\"precione el boton deceado\")) {\n txt = \"seguir \";\n } else {\n txt = \"cancelar\";\n }\n document.getElementById(\"confirmar\").innerHTML = txt;\n}", "function cancelMentorship() {\n return confirm(\"Are you sure you want to cancel mentorship?\");\n}", "function confirmPlant(){\n\n}", "function confirmReset() {\n return confirm(\"Are you sure you want to erase the form?\");\n}", "function alertarResultadoDeEliminacion(resultado) {\n let alertCloseButton = '<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">' +\n '<span aria-hidden=\"true\">&times;</span></button>';\n let htmlAlert = (resultado) ?\n '<div class=\"p-4 alert alert-success alert-dismissible fade show\" role=\"alert\">' +\n '<strong>EXITO</strong> El lote se eliminó correctamente' + alertCloseButton + '</div> '\n :\n '<div class=\"p-4 alert alert-warning alert-dismissible fade show\" role=\"alert\">' +\n '<strong>ERROR</strong> El lote no pudo ser eliminado' + alertCloseButton + '</div> ';\n document.getElementById(\"alertContainer\").innerHTML = htmlAlert;\n}", "function mensaje_advertencia(titulo, mensaje){\n swal({ title: titulo, text: mensaje, type: \"error\", confirmButtonText: \"Aceptar\" });\n }", "function confirmarBuscarTodos(campo, op) {\n submeter(op);\n\n /*if ((trim(campo.value) == '') || (campo.value == null)) {\n if (op == 1) {\n alert(\"Selecione um tipo para ser pesquisado!\");\n return false;\n }\n if(confirm(\"Tem certeza que deseja pesquisar todos os registros?\\nEsta operacao pode ser demorada devido a quantidade de registros.\")) {\n submeter(op);\n return true;\n }\n else {\n return false;\n }\n }\n else {\n submeter(op);\n return true;\n }*/\n}", "_checkConfirmationPrompt(aCommand) {\n const kDontAskAgainPref = \"mailnews.\" + aCommand + \".dontAskAgain\";\n // default to ask user if the pref is not set\n if (!Services.prefs.getBoolPref(kDontAskAgainPref, false)) {\n let checkbox = {value: false};\n let choice = Services.prompt.confirmEx(\n window,\n gMessengerBundle.getString(aCommand + \"Title\"),\n gMessengerBundle.getString(aCommand + \"Message\"),\n Services.prompt.STD_YES_NO_BUTTONS,\n null, null, null,\n gMessengerBundle.getString(aCommand + \"DontAsk\"),\n checkbox);\n if (checkbox.value)\n Services.prefs.setBoolPref(kDontAskAgainPref, true);\n\n if (choice != 0)\n return false;\n }\n return true;\n }", "function notiflixConfirm() {\n let amstedOrGreenbrier = Array.from(document.querySelector(\"body\").classList).includes(\"theme-am\") ? \"#0C134F\" : \"#32c682\";\n Notiflix.Confirm.init({\n titleColor: amstedOrGreenbrier,\n okButtonColor: '#f8f8f8',\n okButtonBackground: amstedOrGreenbrier,\n });\n}", "function ConfirmAction() \n{\n if (confirm('Are you sure you want to do this!? ')) {\n return true;\n } else {\n return false;\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the font on a CanvasRenderingContext2d based on the CSS font for the canvas, the requested size, and whether we want something monospaced.
function canvas_set_font(ctx, size, monospaced) { var s = window.getComputedStyle(onscreen_canvas); // First set something that we're certain will work. Constructing // the font string from the computed style is a bit fragile, so // this acts as a fallback. ctx.font = `${size}px ` + (monospaced ? "monospace" : "sans-serif"); // In CSS Fonts Module Level 4, "font-stretch" gets serialised as // a percentage, which can't be used in // CanvasRenderingContext2d.font, so we omit it. ctx.font = `${s.fontStyle} ${s.fontWeight} ${size}px ` + (monospaced ? "monospace" : s.fontFamily); }
[ "setFont(font) {\n this.ctx.font = font;\n }", "_restyleCanvas() {\n this._canvas.getContext('2d').font = \"\".concat(BubbleStyle.FONT_SIZE, \"px \").concat(BubbleStyle.FONT, \", sans-serif\");\n }", "function _loadFont(fontname){\n var canvas = document.createElement(\"canvas\");\n //Setting the height and width is not really required\n canvas.width = 16;\n canvas.height = 16;\n var ctx = canvas.getContext(\"2d\");\n\n //There is no need to attach the canvas anywhere,\n //calling fillText is enough to make the browser load the active font\n\n //If you have more than one custom font, you can just draw all of them here\n ctx.font = \"4px \"+fontname;\n ctx.fillText(\"text\", 0, 8);\n}", "ctxDrawText (ctx, string, x, y, cssColor) {\n this.setIdentity(ctx)\n ctx.fillStyle = cssColor\n ctx.fillText(string, x, y)\n ctx.restore()\n }", "function styleText(text){ \n\t//console.log(\"style text called\");\n\ttext.style.fontFamily = getFont();\n\ttext.style.color = getColor(0); \n\ttext.style.backgroundColor = getColor(1);\n\tif (border) {\n\t\ttext.style.border = \"solid \"+ getBorder() + \"px\";\n\t\t//console.log(\"solid\"+ getBorder() + \"px\");\n\t\ttext.style.borderColor = getColor(2);\n\t};\n\ttext.style.fontSize = getSize() + \"px\"; \n}", "function drawText(txt,x,y,maxWidth,fontHeight,center) {\n if (center === undefined) {\n center = false;\n }\n\n // we need to scale the coordinate space in order to obtain the correct\n // max width and font height (i.e. sizes)\n var sx = canvas.width / 2;\n var sy = canvas.height / currentBlock.getHeight();\n\n if (center) {\n ctx.textAlign = \"center\";\n }\n else {\n ctx.textAlign = \"start\";\n }\n ctx.textBaseline = \"middle\"; // thank God for this\n\n // scale the context to undo the initial transformations; make sure\n // the scaling doesn't affect the specified text position\n ctx.save();\n ctx.scale(1/sx,1/sy);\n x *= sx; y *= sy;\n maxWidth *= sx; // this value converted to \"scaled pixels\"\n\n // the font is specified in pixels that are scaled; the transformations\n // take the font height from the calling context's coordinate space and\n // transforms it into units of \"scaled pixels\"\n var fontSz = fontHeight * sy;\n ctx.font = fontSz + \"px \" + DEFAULT_FONT;\n ctx.fillText(txt,x,y,maxWidth);\n\n ctx.restore();\n }", "function loadFontAndWrite(font,text,x,y) {\r\n document.fonts.load(font).then(function () {\r\n ctx.font = font\r\n ctx.fillText(text, x, y)\r\n });\r\n }", "useFontScaling(scale) {\n this.element.value = this.fontSizeScale.indexOf(scale);\n document.documentElement.style.fontSize = scale * this.baseSize + 'px';\n this.update(this.element.value);\n }", "function changeFont(){\n\tvar new_font = $('#font').val();\n\teditor.setFontSize(parseInt(new_font));\n}", "function setFontMetrics(fontName, metrics) {\n metricMap[fontName] = metrics;\n }", "function increaseFontSize() {\n gMeme.currText.size += 3\n}", "setTextParams (obj, font, align = 'center', baseline = 'middle') {\n obj.font = font; obj.textAlign = align; obj.textBaseline = baseline\n }", "function fontSize(d) {\n d.fontsize = Math.floor(d.radius/3);\n return d.fontsize + \"px\";\n }", "key(x, y, squareSize, font) {\n this.ctx.font = font;\n for (let i = 0; i < this.data.length; i++) {\n this.ctx.fillStyle = this.data[i].color;\n this.ctx.textBaseline = \"top\";\n this.ctx.textAlign = \"left\";\n this.ctx.fillRect(x, y + i * squareSize * 1.5, squareSize, squareSize);\n this.ctx.fillText(`${this.data[i].label}, ${this.data[i].unit}`, x + squareSize * 1.5, y + squareSize * i * 1.5);\n }\n }", "function drawText() {\n push();\n textAlign(CENTER);\n fill(this.color);\n textSize(this.size);\n text(this.txt, this.x, this.y);\n pop();\n}", "function decreaseFont(){\r\n\tbody = document.getElementById('fontChange');\r\n\tstyle = window.getComputedStyle(body, null).getPropertyValue('font-size');\r\n\tsettSize = parseFloat(style);\r\n\tbody.style.fontSize = (setSize -3) + 'px'; //decreases the current font size of the page by 3px \r\n}", "function canvasSize({\n textStyle = 0,\n size = 300,\n primaryText = \"\",\n secondaryText = \"\",\n displaySize = false,\n }) {\n let scale = size / 300;\n let scaledWidth = 890;\n let scaledHeight = 300;\n\n switch (textStyle) {\n case 1:\n scaledWidth = Math.max(getTextWidth(primaryText, \"bold 120px Metropolis,Arial\"), getTextWidth(secondaryText, \"bold 120px Metropolis,Arial\"));\n if (scaledWidth < 800) {\n scaledWidth = 800;\n }\n if (secondaryText === \"\") {\n scaledHeight = 450;\n } else {\n scaledHeight = 600;\n }\n break;\n\n default:\n scaledWidth = 800;\n scaledHeight = 300;\n }\n\n let width = Math.round(scaledWidth * scale);\n let height = Math.round(scaledHeight * scale);\n if (width % 2 !== 0) {\n width += 1;\n }\n if (height % 2 !== 0) {\n height += 1;\n }\n\n if (displaySize) {\n let dimension_icon = document.getElementById('dimensions-icon');\n dimension_icon.textContent = \"(Size: \" + size + \"x\" + size + \") \";\n\n let dimension_symbol = document.getElementById('dimensions-symbol');\n dimension_symbol.textContent += \"(Size: \" + height + \"x\" + width + \") \";\n }\n\n return [height, width]\n}", "updateFabricTextObject (feature, changes) {\n\n const canvas = this.get('canvas');\n const fabricObj = canvas.featureFabObjs[feature.get('id')];\n const doesFontSizeChange = Object\n .keys(changes)\n .reduce((acc, key) => {\n canvas.update_texttopath(fabricObj, key, changes[key]);\n return acc || key === 'fontSize';\n }, false);\n\n [ 'top', 'left' ]\n .forEach((attrName) =>\n canvas.update_texttopath(fabricObj, attrName, feature.get(attrName))\n );\n\n const newFabricObj = canvas.replace_texttopath(fabricObj);\n\n if (newFabricObj) {\n canvas.container.offsetObject(newFabricObj);\n }\n\n canvas.setZIndexPosition();\n canvas.render();\n\n if (!doesFontSizeChange) {\n // #bug465\n this.updateFabricTextObject(feature, { 'fontSize': feature.get('fontSize') });\n }\n }", "text(...args) {\n let opts = args[args.length - 1];\n\n if (typeof opts !== 'object') {\n opts = {};\n }\n\n if (!opts.lineGap) {\n opts.lineGap = lineGap;\n }\n\n if (opts.font) {\n this.doc.font(opts.font);\n } else {\n this.doc.font(lightFont);\n }\n\n if (opts.color) {\n this.doc.fillColor(opts.color);\n } else {\n this.doc.fillColor('black');\n }\n\n if (opts.size) {\n this.doc.fontSize(opts.size);\n } else {\n this.doc.fontSize(10);\n }\n\n return this.doc.text(...args);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calls the openCalendar function, but providing the id of the iFrame so that the objects may be correctly initialized. The name of the calendar instance object is assumed to be unchanged in the iFrame
function atgCalendar_openCalendarIFrame(iFrameId) { var iFrameObject = atgCalendar_findElementById(iFrameId); if (iFrameObject != null) { iFrameObject.contentWindow.atgCalendar_openIFrame(iFrameId); } }
[ "function openCalendarAtPosition( xpos, ypos, contextString ) {\n\n var calwindow = window.open( \"html/calendar.htm?context=\"+contextString , \"cdccalendar\", \"toolbar=no,status=yes,top=\"+ypos+\",left=\"+xpos+\",outerWidth=203,outerHeight=236,width=190,height=183,scrollbars=auto,resizable=yes,menubar=no,locationbar=no\");\n calwindow.focus();\n}", "function TSWFormCalendar(id)\n{\n\tvar d = new Date;\n\tthis.id = id;\n\t\n\t//The div element of the popup calendar\n\tthis.popUpDiv = null;\n\t\n\t//The current year and month being displayed on the popup calendar\n\tthis.currentYear = d.getFullYear();\n\tthis.currentMonth = d.getMonth();\n\tthis.dateFormat = 'MM/dd/yyyy';\n\t\n\t//Start week on Monday;\n\tthis.startWeekOnMonday = false;\n\t\n\t//Array of names to show for days of week\n\tthis.dayNames = null;\n\t\n\t//A Date object that represents the currently selected date in the calendar;\n\t//null if there is no selected date.\n\tthis.selectedDate = null;\n\t\n\t//initialization code\n\tthis.init(this);\n}", "function tswFormCalendarGetForId(id)\n{\n\tvar formCalendar = tswFormCalendarMap[id];\n\tif(formCalendar == null)\n\t{\n\t\tformCalendar = new TSWFormCalendar(id);\n\t\ttswFormCalendarMap[id] = formCalendar;\n\t}\n\treturn formCalendar;\n}", "function igcal_getCalendarById(id, e)\r\n{\r\n\tvar o,i1=-2;\r\n\tif(e!=null)\r\n\t{\r\n\t\twhile(true)\r\n\t\t{\r\n\t\t\tif(e==null) return null;\r\n\t\t\ttry{if(e.getAttribute!=null)id=e.getAttribute(\"calID\");}catch(ex){}\r\n\t\t\tif(!ig_csom.isEmpty(id)) break;\r\n\t\t\tif(++i1>1)return null;\r\n\t\t\te=e.parentNode;\r\n\t\t}\r\n\t\tvar ids=id.split(\",\");\r\n\t\tif(ig_csom.isEmpty(ids))return null;\r\n\t\tid=ids[0];\r\n\t\ti1=(ids.length>1)?parseInt(ids[1]):-1;\r\n\t}\r\n\tif((o=igcal_all[id])==null)\r\n\t\tfor(var i in igcal_all)if((o=igcal_all[i])!=null)\r\n\t\t\tif(o.ID==id || o.ID_==id || o.uniqueId==id)break;\r\n\t\t\telse o=null;\r\n\tif(o!=null && i1>-2)o.elemID=i1;\r\n\treturn o;\r\n}", "function addId(){ //Add ID to events, calendar and list\n var cal = document.getElementsByClassName(\"JScal\");\n var eventList = document.getElementsByClassName(\"JSeventList\");\n\n for (i = 0, length = eventList.length; i < length; i++) { //eventList or cal.lenght\n cal[i].href= \"#JSeventID_\" + (i + 1); //Add link to calendar\n eventList[i].id= \"JSeventID_\" + (i + 1); //Add id to list\n }\n }", "function openCalendarAtMousePosition(e, contextString ) {\n\n\t// get the current mouse position\n\tvar mouseY = 0;\n\tvar mouseX = 0;\n\tif( document.all ) {\n\t\tmouseY = event.screenY;\n\t\tmouseX = event.screenX;\n\t} else if( document.getElementById ) {\n\t\tmouseY = e.screenY;\n\t\tmouseX = e.screenX;\n\t} else if( document.layers ) {\n\t\tmouseY = e.screenY;\n\t\tmouseX = e.screenX;\n\t}\n\topenCalendarAtPosition( mouseX, mouseY, contextString );\n}", "function show_cal(id){\n\t\t//Add functionality to show selected date(month) if date was previously selected when a hidden calendar is shown\n\t\tsetTimeout(function(){\n\t\t\tif (!cal_showing){\n\t\t\t\t$('#'+id).select();\n\t\t\n\t\t\t\t$('#calendar').css({\n\t\t\t\t\t'margin-left':mouseX+'px',\n\t\t\t\t\t'margin-top':mouseY+'px'\n\t\t\t\t});\n\t\t\n\t\t\t\t$('#dogcal_popup').show();\n\t\t\t\tcal_showing = true;\t\t\t\n\t\t\t}\n\t\t},1);\n\t}", "function buildTopCalFrame() {\n\n \n // CREATE THE TOP FRAME OF THE CALENDAR\n var calDoc = \"\";\n var _parent = \"\";\n if(!is_safari)\n {\n _parent = \"parent.\";\n calDoc += \"<html>\" +\n \"<head>\" +\n \"</head>\" +\n \"<body bgcolor=\\\"\" + topBackground + \"\\\">\";\n } \n \n calDoc += \"<form name=\\\"calControl\\\" onSubmit=\\\"return false;\\\">\" +\n \"<center>\" +\n \"<table cellpadding=0 cellspacing=1 border=0>\" +\n \"<tr><td colspan=7>\" +\n \"<center>\" +\n getMonthSelect() +\n \"<input name=\\\"year\\\" value=\\\"\" + calDate.getFullYear() + \"\\\"type=text size=4 maxlength=4 onChange=\\\"\" + _parent + \"opener.setYear()\\\">\" +\n \"</center>\" +\n \"</td>\" +\n \"</tr>\" +\n \"<tr>\" +\n \"<td colspan=7>\" +\n \"<input \" +\n \"type=button name=\\\"previousYear\\\" value=\\\"<<\\\" onClick=\\\"\" + _parent + \"opener.setPreviousYear()\\\"/><input \" +\n \"type=button name=\\\"previousMonth\\\" value=\\\" < \\\" onClick=\\\"\" + _parent + \"opener.setPreviousMonth()\\\"/><input \" +\n \"type=button name=\\\"today\\\" value=\\\"Today\\\" onClick=\\\"\" + _parent + \"opener.setToday()\\\"/><input \" +\n \"type=button name=\\\"nextMonth\\\" value=\\\" > \\\" onClick=\\\"\" + _parent + \"opener.setNextMonth()\\\"/><input \" +\n \"type=button name=\\\"nextYear\\\" value=\\\">>\\\" onClick=\\\"\" + _parent + \"opener.setNextYear()\\\"/>&nbsp;\" +\n \"</td>\" +\n \"</tr>\" ;\n if(timeflag==\"1\")\n {\n\tcalDoc +=\n \t \"<tr>\" +\n\t \"<td colspan=7>\" +\n\t \"<center>\" +\n\t getTimeSelect() +\n\t \"</center>\" +\n\t \"</td>\" +\n\t \"</tr>\";\n }\n calDoc +=\n \"</table>\" +\n \"</center>\" +\n \"</form>\";\n \n if(!is_safari)\n {\n calDoc += \"</body>\" +\n \"</html>\";\n } \n\n return calDoc;\n}", "function openEvent() {\n var event = new Event('open-interface');\n document.dispatchEvent(event);\n}", "function openModal(self) {\n\n console.log(self.bloqueEdit.data.title, this);\n self.controladorHTML.modalEdit.container.className = 'dia-show dia dia-nuevo-evento-container dia-defecto-container';\n self.controladorHTML.modalEdit.title.value = self.bloqueEdit.data.title;\n self.controladorHTML.modalEdit.id.value = self.bloqueEdit.id;\n\n function returnHoraFormat(hh) {\n var hh = new Fecha(hh);\n var anio = hh.getFullYear();\n var dia = hh.getDate();\n var mes = hh.getMonth() < 9 ? \"0\" + (hh.getMonth() + 1) : hh.getMonth() + 1;\n var fullAnio = mes + \"/\" + dia + \"/\" + anio;\n var startMinute = hh.getMinutes();\n startMinute = startMinute <= 9 ? \"0\" + startMinute : startMinute;\n var startHour = hh.getHours();\n startHour = startHour <= 9 ? \"0\" + startHour : startHour;\n return fullAnio + ' ' + startHour + ':' + startMinute;\n }\n self.controladorHTML.modalEdit.start.value = returnHoraFormat(self.bloqueEdit.start);\n self.controladorHTML.modalEdit.end.value = returnHoraFormat(self.bloqueEdit.end);\n }", "function onClickCalendarDate(e)\n{\n//JBARDIN\n var button = this;\n var date = button.getAttribute(\"title\");\n var dat = new Date(date.substr(6,4), date.substr(3,2)-1, date.substr(0, 2));\n\n date = dat.formatString(config.macros.calendar.tiddlerformat);\n var popup = createTiddlerPopup(this);\n popup.className = \"newReminderPopup\";\n popup.appendChild(document.createTextNode(date));\n var newReminder = function() {\n var t = store.tiddlers[date];\n displayTiddler(null, date, 2, null, null, false, false);\n if(t) {\n document.getElementById(\"editorBody\" + date).value += \"\\n<<reminder day:\" + dat.getDate() +\n \" month:\" + (dat.getMonth()+1) +\n \" year:\" + (dat.getYear()+1900) + \" title: >>\";\n } else {\n document.getElementById(\"editorBody\" + date).value = \"<<reminder day:\" + dat.getDate() +\n \" month:\" + (dat.getMonth()+1) +\n \" year:\" + (dat.getYear()+1900) + \" title: >>\";\n }\n };\n var link = createTiddlyButton(popup, \"New reminder\", null, newReminder, \"newReminderButton\"); \n popup.appendChild(document.createElement(\"hr\"));\n\n var t = findTiddlersWithReminders(dat, 0, null, null);\n for(var i = 0; i < t.length; i++) {\n link = createTiddlyLink(popup, t[i].tiddler, false);\n link.appendChild(document.createTextNode(t[i].tiddler));\n }\n\n}", "function checkCalendarwidget() {\r\n\r\n\r\n var inlineCalendarViewElement=document.getElementsByName(\"calendar_inline\");\r\n\r\n // Verify if the inline view is\r\n if(inlineCalendarViewElement)\r\n {\r\n for(var i=0;i<inlineCalendarViewElement.length;i++)\r\n {\r\n var id= inlineCalendarViewElement[i].getAttribute( \"id\");\r\n\r\n var crid= id.split(\"_\")[0];\r\n var caldtxtfld=crid+\"_inlinemode\";\r\n var calmnt=crid+\"_inline_month\";\r\n var calday=crid+\"_inline_day\";\r\n var calyer=crid+\"_inline_year\";\r\n var caltxtfldnode = document.getElementById(caldtxtfld);\r\n var tmpmn = document.getElementById(calmnt);\r\n var tmpyr = document.getElementById(calyer);\r\n var tmpdy = document.getElementById(calday);\r\n\r\n var format=caltxtfldnode.getAttribute(\"format\");\r\n var frmt=format.split(\"/\",2);\r\n var valuer = caltxtfldnode.value;\r\n var value=valuer.split(\"/\",3);\r\n if(frmt[0]==\"mm\")\r\n {\r\n tmpdy.selectedIndex=parseInt(value[1],10)-1;\r\n tmpyr.selectedIndex=parseInt(value[2],10)-1900;\r\n tmpmn.selectedIndex=parseInt(value[0],10)-1;\r\n }\r\n else\r\n {\r\n tmpdy.selectedIndex=parseInt(value[0],10)-1;\r\n tmpyr.selectedIndex=parseInt(value[2],10)-1900;\r\n tmpmn.selectedIndex=parseInt(value[1],10)-1;\r\n }\r\n updateDaysforInlineMode(crid);\r\n }\r\n }\r\n\r\n }", "function updateIFrame(value) {\n iDoc().open();\n iDoc().close();\n iDoc().location.hash = value;\n }", "function DrawFullCalendar(){\nLoadCalendarScript(DrawCalendar);\n}", "function openVideo(video_id) {\n $(modal.replace(\"{VIDEO_ID}\", video_id)).appendTo('body').modal();\n}", "function initCal() {\n const cal = document.querySelector('#calendar');\n const datepicker = new Datepicker(cal, {\n autohide: true\n });\n \n cal.addEventListener('changeDate', updatePlaykit);\n}", "function evtRoutine1( sender, parms )\n {\n var rtn = Lansa.evtRoutine( this, COM_OWNER, \"#DIYSchedule.Click\", 149 );\n\n //\n // EVTROUTINE Handling(#DIYSchedule.Click)\n //\n rtn.Line( 149 );\n {\n\n //\n // #sys_web.Navigate( \"/images/lansatools/DIY-Workshops-Schedule.pdf\" New )\n //\n rtn.Line( 152 );\n Lansa.WEB().mthNAVIGATE( \"/images/lansatools/DIY-Workshops-Schedule.pdf\", \"NEW\" );\n\n }\n\n //\n // ENDROUTINE\n //\n rtn.Line( 154 );\n rtn.end();\n }", "async createIframeURL(fid) {\n this.setOrgID(fid);\n // var iframe_url = this.state.iframe_url + \"?orgID=\" + this.state.oid;\n // console.log(iframe_url);\n // var iframe_copy_text =\n // '<iframe src=\"' + iframe_url + '\" width=\"100%\" height=\"450\"></iframe>';\n //this.setState({ iframe_url });\n //this.setState({ iframe_copy_text });\n }", "function OpenFrame(options) {\n OpenFrame.super_.call(this);\n this.channel = 0;\n if (options instanceof DescribedType) {\n this.fromDescribedType(options);\n return;\n }\n\n u.assertArguments(options, ['containerId', 'hostname']);\n this.id = options.containerId;\n u.defaults(this, options, {\n maxFrameSize: constants.defaultMaxFrameSize,\n channelMax: constants.defaultChannelMax,\n idleTimeout: constants.defaultIdleTimeout,\n outgoingLocales: constants.defaultOutgoingLocales,\n incomingLocales: constants.defaultIncomingLocales,\n offeredCapabilities: null,\n desiredCapabilities: null,\n properties: {}\n });\n}", "function openPreview(name, url){\n console.log(name, url);\n var modal = '<div class=\"modal fade\" id=\"bookPreview\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"bookPreviewLabel\" aria-hidden=\"true\">' +\n '<div class=\"modal-dialog\" role=\"document\">' +\n '<div class=\"modal-content\">' +\n '<div class=\"modal-header\">' +\n '<h5 class=\"modal-title\" id=\"bookPreviewLabel\">'+ name +'</h5>' +\n '<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\">' +\n '<span aria-hidden=\"true\">&times;</span>' +\n '</button>' +\n '</div>' +\n '<div class=\"modal-body\">' +\n '<iframe src=\"'+ url +'&output=embed\" frameborder=\"0\">' +\n '</iframe>' +\n '</div>' +\n '</div>' +\n '</div>' +\n '</div>';\n $('body').prepend(modal);\n $('#bookPreview').modal('show');\n $('#bookPreview').on('hidden.bs.modal', function(e){\n $('#bookPreview').remove();\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This sample demonstrates how to Creates or updates a network security group in the specified resource group.
async function createNetworkSecurityGroupWithRule() { const subscriptionId = process.env["NETWORK_SUBSCRIPTION_ID"] || "subid"; const resourceGroupName = process.env["NETWORK_RESOURCE_GROUP"] || "rg1"; const networkSecurityGroupName = "testnsg"; const parameters = { securityRules: [ { name: "rule1", access: "Allow", destinationAddressPrefix: "*", destinationPortRange: "80", direction: "Inbound", priority: 130, sourceAddressPrefix: "*", sourcePortRange: "*", protocol: "*", }, ], }; const credential = new DefaultAzureCredential(); const client = new NetworkManagementClient(credential, subscriptionId); const result = await client.networkSecurityGroups.beginCreateOrUpdateAndWait( resourceGroupName, networkSecurityGroupName, parameters ); console.log(result); }
[ "async function createNetworkSecurityGroup() {\n const subscriptionId = process.env[\"NETWORK_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"NETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const networkSecurityGroupName = \"testnsg\";\n const parameters = {};\n const credential = new DefaultAzureCredential();\n const client = new NetworkManagementClient(credential, subscriptionId);\n const result = await client.networkSecurityGroups.beginCreateOrUpdateAndWait(\n resourceGroupName,\n networkSecurityGroupName,\n parameters\n );\n console.log(result);\n}", "createGroup() {\n this.errorMsg = null;\n this.group.parent = this.selectedSymbolGroup == null ? null : this.selectedSymbolGroup.id;\n\n this.SymbolGroupResource.create(this.project.id, this.group)\n .then(createdGroup => {\n this.ToastService.success('Symbol group <strong>' + createdGroup.name + '</strong> created');\n this.close({$value: createdGroup});\n this.dismiss();\n })\n .catch(response => {\n this.errorMsg = response.data.message;\n });\n }", "createGroup (title, description = '') {\n assert.equal(typeof title, 'string', 'title must be string')\n assert.equal(typeof description, 'string', 'description must be string')\n return this._apiRequest('/group', 'POST', {\n title,\n description\n })\n }", "async function createSubGroup(user, group, name, users) {\n // Make sure the user is the owner of the group\n const role = await getRole(user, group);\n if (role !== 'owner') {\n throw new RequestError('only owners can create sub-groups');\n }\n\n // Create a set of user ID strings to include in the group\n const userSet = new Set();\n userSet.add(user);\n for (const user of users) {\n userSet.add(user.id);\n }\n\n // Create an array of ObjectIds for each user\n const userArray = [];\n for (const user of userSet) {\n userArray.push(ObjectId(user));\n }\n\n // Get the existing info of the group\n const groupInfo = await db.collection(\"Groups\")\n .findOne({ _id: ObjectId(group) }, { projection: { _id: 0, grpUsers: 1, requireApproval: 1 } });\n\n // Filter to only include the specified users\n const grpUsers = groupInfo.grpUsers.filter(u => userSet.has(u.user.toHexString()));\n\n // Create a new group with only the specified users\n const result = await db.collection(\"Groups\").insertOne({\n name,\n grpUsers,\n requireApproval: groupInfo.requireApproval,\n modDate: Date.now(),\n modules: [],\n });\n\n // Get the ID of the new group\n const id = result.insertedId;\n\n // Add the group to all of the users\n await db.collection(\"Users\")\n .updateMany({ _id: { $in: userArray } }, { $push: { groups: id } });\n\n return id.toHexString();\n}", "function createGroup(id) {\n let templateGroup = JSON.parse(fs.readFileSync(schemaPath + \"group.json\", \"utf8\"));\n templateGroup.id = id;\n writeGroup(id, templateGroup);\n}", "function updateGroup(oContext) {\n\t\t\t\tvar oNewGroup = oBinding.getGroup(oContext);\n\t\t\t\tif (oNewGroup.key !== sGroup) {\n\t\t\t\t\tvar oGroupHeader;\n\t\t\t\t\t//If factory is defined use it\n\t\t\t\t\tif (oBindingInfo.groupHeaderFactory) {\n\t\t\t\t\t\toGroupHeader = oBindingInfo.groupHeaderFactory(oNewGroup);\n\t\t\t\t\t}\n\t\t\t\t\tthat[sGroupFunction](oNewGroup, oGroupHeader);\n\t\t\t\t\tsGroup = oNewGroup.key;\n\t\t\t\t}\n\t\t\t}", "async function createFirewallPolicyRuleCollectionGroup() {\n const subscriptionId = process.env[\"NETWORK_SUBSCRIPTION_ID\"] || \"subid\";\n const resourceGroupName = process.env[\"NETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const firewallPolicyName = \"firewallPolicy\";\n const ruleCollectionGroupName = \"ruleCollectionGroup1\";\n const parameters = {\n priority: 100,\n ruleCollections: [\n {\n name: \"Example-Filter-Rule-Collection\",\n action: { type: \"Deny\" },\n priority: 100,\n ruleCollectionType: \"FirewallPolicyFilterRuleCollection\",\n rules: [\n {\n name: \"network-rule1\",\n destinationAddresses: [\"*\"],\n destinationPorts: [\"*\"],\n ipProtocols: [\"TCP\"],\n ruleType: \"NetworkRule\",\n sourceAddresses: [\"10.1.25.0/24\"],\n },\n ],\n },\n ],\n };\n const credential = new DefaultAzureCredential();\n const client = new NetworkManagementClient(credential, subscriptionId);\n const result = await client.firewallPolicyRuleCollectionGroups.beginCreateOrUpdateAndWait(\n resourceGroupName,\n firewallPolicyName,\n ruleCollectionGroupName,\n parameters\n );\n console.log(result);\n}", "async function setGroupResourceAccess(resource, group, access, options = internal_defaultFetchOptions) {\n return await setActorAccess(resource, group, access, getGroupAccess$2, setGroupResourceAccess$1, options);\n}", "function SecurityGroup(props) {\n return __assign({ Type: 'AWS::ElastiCache::SecurityGroup' }, props);\n }", "addGroup() {\n this._insertItem(FdEditformGroup.create({\n caption: `${this.get('i18n').t('forms.fd-editform-constructor.new-group-caption').toString()} #${this.incrementProperty('_newGroupIndex')}`,\n rows: A(),\n }), this.get('selectedItem') || this.get('controlsTree'));\n }", "async function insertGroup(newGroup) {\r\n const result = await client.db(\"RandomData\").collection(\"RandomCollection\").insertOne(newGroup);\r\n}", "function BindWeChatGroup(token, group_id, suc_func, error_func) {\n let api_url = 'bnd_group.php',\n post_data = {\n 'token': token,\n 'group_id': group_id\n };\n CallApi(api_url, post_data, suc_func, error_func);\n}", "async function createFirewallPolicyRuleCollectionGroupWithWebCategories() {\n const subscriptionId =\n process.env[\"NETWORK_SUBSCRIPTION_ID\"] || \"e747cc13-97d4-4a79-b463-42d7f4e558f2\";\n const resourceGroupName = process.env[\"NETWORK_RESOURCE_GROUP\"] || \"rg1\";\n const firewallPolicyName = \"firewallPolicy\";\n const ruleCollectionGroupName = \"ruleCollectionGroup1\";\n const parameters = {\n priority: 110,\n ruleCollections: [\n {\n name: \"Example-Filter-Rule-Collection\",\n action: { type: \"Deny\" },\n ruleCollectionType: \"FirewallPolicyFilterRuleCollection\",\n rules: [\n {\n name: \"rule1\",\n description: \"Deny inbound rule\",\n protocols: [{ port: 443, protocolType: \"Https\" }],\n ruleType: \"ApplicationRule\",\n sourceAddresses: [\"216.58.216.164\", \"10.0.0.0/24\"],\n webCategories: [\"Hacking\"],\n },\n ],\n },\n ],\n };\n const credential = new DefaultAzureCredential();\n const client = new NetworkManagementClient(credential, subscriptionId);\n const result = await client.firewallPolicyRuleCollectionGroups.beginCreateOrUpdateAndWait(\n resourceGroupName,\n firewallPolicyName,\n ruleCollectionGroupName,\n parameters\n );\n console.log(result);\n}", "function putGroupInCanvas(myGroupStr, myContext, clipX, clipY, clipW, clipH, canvX, canvY, canvW, canvH, noRect) {\n\t// prepend and append svg open and close tag constants\n\t// use given flag to determine if using svgPrepent (has white rect)\n\t// or svgMinPrepent (does not have white rect)\n\tif (noRect) {\n\t\tmyGroupStr = svgMinPrepend + myGroupStr + svgAppend;\n\t} else {\n\t\tmyGroupStr = svgPrepend + myGroupStr + svgAppend;\n\t}\n\t// debug message\n\tif (verboseDebugging) {\n\t\tconsole.log(myGroupStr);\n\t}\n\t// use a blob to put the SVG into the context\n\t// adapted from http://stackoverflow.com/questions/27230293/\n\tvar blobSvg = new Blob([myGroupStr],{type:\"image/svg+xml;charset=utf-8\"}),\n\t\tdomURL = self.URL || self.webkitURL || self,\n\t\turl = domURL.createObjectURL(blobSvg),\n\t\timg = new Image;\n\t\timg.onload = function(){\n\t\t\t// clear the given canvas\n\t\t\t// ??? still hard-coded to hiddenCanvas.width and height... oops\n\t\t\t// but seems to work b/c those are maximum for all the canvases\n\t\t\tmyContext.clearRect(0, 0, hiddenCanvas.width, hiddenCanvas.height);\n\t\t\t// draw the new image\n\t\t\tmyContext.drawImage(img, clipX, clipY, clipW, clipH, canvX, canvY, canvW, canvH);\n\t\t}\n\t\timg.src = url;\n}", "addDisplayTemplateGroup (title, parentGroup) {\n console.log('addDisplayTemplateGroup:', title, parentGroup);\n let user = Auth.requireAuthentication();\n \n // Validate the data is complete\n check(title, String);\n \n // Validate that the current user is an administrator\n if (user.isAdmin()) {\n let payload = {\n title: title,\n };\n \n if (parentGroup) {\n payload.parentGroup = parentGroup\n }\n \n // Insert the project percent\n DisplayTemplateGroups.insert(payload);\n } else {\n console.error('Non-admin user tried to add an integration display template group:', user.username, title);\n throw new Meteor.Error(403);\n }\n }", "function add_group_response() {\n var group_number = $groups.children().length + 1;\n var button = '<input type=\"button\" class=\"btn btn-md btn-primary \" style=\"margin: 0em 1em 1em 0em\" id=\"grp' + group_number + '\" value=\"Group ';\n button += group_number + ' - '+ 0;\n button += '\" />';\n $groups.append(button);\n}", "editDisplayTemplateGroup (groupId, key, value) {\n console.log('editDisplayTemplateGroup:', groupId, key);\n let user = Auth.requireAuthentication();\n \n // Validate the data is complete\n check(groupId, String);\n check(key, String);\n check(value, Match.Any);\n \n // Get the display template group record to make sure this is authorized\n let displayTemplate = DisplayTemplateGroups.findOne(groupId);\n \n // Validate that the current user is an administrator\n if (user.isAdmin()) {\n if (displayTemplate) {\n let update = {};\n update[ key ] = value;\n \n // Update the contributor\n DisplayTemplateGroups.update(groupId, { $set: update });\n } else {\n throw new Meteor.Error(404);\n }\n } else {\n console.error('Non-admin user tried to edit an integration display template group:', user.username, key, groupId);\n throw new Meteor.Error(403);\n }\n }", "function dwscripts_applyGroup(groupName, paramObj)\n{\n // queue the group edits\n dwscripts.queueDocEditsForGroup(groupName, paramObj);\n\n // Commit all scheduled edits\n dwscripts.applyDocEdits();\n}", "function groupappend_response(req)\n{\n appending = false;\n if(req.status != 200 ) {\n pnshowajaxerror(req.responseText);\n return;\n }\n var json = pndejsonize(req.responseText);\n\n pnupdateauthids(json.authid);\n $('groupsauthid').value = json.authid;\n\n // copy new group li from permission_1.\n var newgroup = $('group_'+firstgroup).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newgroup.id = 'group_' + json.gid;\n $A(newgroup.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; node.value = ''; });\n $A(newgroup.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + json.gid; });\n $A(newgroup.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + json.gid; });\n\n // append new group to the group list\n $('grouplist').appendChild(newgroup);\n\n // set initial values in input, hidden and select\n $('name_' + json.gid).value = json.name;\n $('description_' + json.gid).value = json.description;\n $('editgroupnbumax_' + json.gid).value = json.nbumax;\n $('members_' + json.gid).href = json.membersurl;\n\n pnsetselectoption('state_' + json.gid, json.statelbl);\n pnsetselectoption('gtype_' + json.gid, json.gtypelbl);\n\n // hide cancel icon for new groups\n// Element.addClassName('groupeditcancel_' + json.gid, 'z-hide');\n // update delete icon to show cancel icon \n// Element.update('groupeditdelete_' + json.gid, canceliconhtml);\n\n // update some innerHTML\n Element.update('groupnbuser_' + json.gid, json.nbuser);\n Element.update('groupnbumax_' + json.gid, json.nbumax);\n Element.update('groupgid_' + json.gid, json.gid);\n Element.update('groupname_' + json.gid, json.name);\n Element.update('groupgtype_' + json.gid, json.gtypelbl);\n Element.update('groupdescription_' + json.gid, json.description) + '&nbsp;';\n Element.update('groupstate_' + json.gid, json.statelbl);\n //Element.update('members_' + json.gid, json.membersurl);\n\n // add events\n Event.observe('modifyajax_' + json.gid, 'click', function(){groupmodifyinit(json.gid)}, false);\n Event.observe('groupeditsave_' + json.gid, 'click', function(){groupmodify(json.gid)}, false);\n Event.observe('groupeditdelete_' + json.gid, 'click', function(){groupdelete(json.gid)}, false);\n Event.observe('groupeditcancel_' + json.gid, 'click', function(){groupmodifycancel(json.gid)}, false);\n\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + json.gid, 'z-hide');\n Event.observe('modifyajax_' + json.gid, 'click', function(){groupmodifyinit(json.gid)}, false);\n\n // turn on edit mode\n enableeditfields(json.gid);\n\n // we are ready now, make it visible\n Element.removeClassName('group_' + json.gid, 'z-hide');\n new Effect.Highlight('group_' + json.gid, { startcolor: '#ffff99', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new group\n adding[json.gid] = 1;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the checkboxes dynamically
createCheckboxes() { const checkboxes = []; for (const option in this.props.const.option) { checkboxes.push( <Checkbox key={this.props.const.option[option]} name={this.props.const.option[option]} activeCheckbox={this.state.activeCheckbox} onclick={this.checkboxSelection.bind(this)} /> ); } return checkboxes; }
[ "function addCheckboxes() {\r\n\r\n //table ids where to find clickabe elements\r\n var tableIds = ['#ID-macroTable', '#ID-conditionTable', '#ID-tagTable'];\r\n //corresponding click element classes (different in each table)\r\n var clickClasses = ['.ACTION-clickMacro', '.ACTION-clickCondition', '.ACTION-clickTag'];\r\n\r\n for (var i = 0; i < tableIds.length; i++) {\r\n if ($(tableIds[i]).find('.cb_export').length == 0) {\r\n $(tableIds[i]).find(clickClasses[i]).each(function(index, element) {\r\n\r\n var matches = $(element).attr('class').match(/TARGET-(\\d+)/);\r\n var tid = matches ? matches[1] : '';\r\n\r\n $(element).before('<input type=\"checkbox\" data-tid=\"' + tid + '\" class=\"cb_export\"/>');\r\n });\r\n }\r\n }\r\n }", "function installCheckboxes(){\n\t\tvar form = \"<form name=conferences>\\n\";\n\t\tfor (confName in conferences){\n\t\t\tform += \"<label><input type=\\\"checkbox\\\" \";\n\t\t\tform += \"id=\\\"\" + confName + \"\\\" \";\n\t\t\tform += \"checked onclick='pcminer.confSelected(\\\"\" + confName + \"\\\")'> \";\n\t\t\tform += \"<font id=\\\"\" + confName + \"color\\\" \";\n\t\t\tform += \"class=\\\"conf\\\">\" + confName + \"</font></label>\\n\";\n\t\t}\n\t\tform += \"</form>\\n\";\n\t\tdocument.getElementById(\"checkboxes\").innerHTML = form;\n\t\tfor (conf in confColors){\n\t\t\tdocument.getElementById(conf + \"color\").style.color = confColors[conf];\n\t\t}\n\t\t\n\t}", "createLightCheckboxes() {\n this.lights = this.gui.addFolder(\"Lights\");\n \n this.lights.add(this.scene, 'displayLights').name('Display Lights');\n\n var data = {}; // Used to store lights for building checkboxes\n\n for (let [id, light] of this.scene.graph.lights) {\n data[`light_${id}`] = light[0];\n this.lightControllers[id] = this.lights.add(data, `light_${id}`).name(`Light ${id}`).listen().onChange(val => {this.scene.toggleLight(id, val);});\n }\n }", "createSelectUser() {\n console.log(\"createSelectUser:\")\n let items = [];\n this.state.group_users_list.forEach((T) => {\n items.push(\n <div key={T.user_name + \"user_list\"}>\n <label>\n <input type=\"checkbox\" key={T.user_name} defaultChecked={T.isChecked} name={T.user_name} onChange={this.handleCheckboxListChange}/>\n {T.user_name}\n </label>\n </div>\n );\n })\n return items;\n }", "checkBox(x, y, label, value) {\n return this.appendChild(new CheckBox(x, y, label, value));\n }", "function addChecks(){\n var el = document.getElementById(\"foobar\"), i = 1, j = 0;\n while(i < 3){\n var link = document.createElement(\"a\");\n if(i === 1){\n link.innerText = \"check all\";\n $(link).click(function(){\n $(\".checkbox\").prop(\"checked\", true);\n });\n } else {\n link.innerText = \"uncheck all\";\n $(link).click(function(){\n $(\".checkbox\").prop(\"checked\", false);\n });\n }\n link.style.cssText = \"display: block; margin: 5px;\";\n el.appendChild(link);\n i++;\n }\n while(j < 9){\n var checkbox = document.createElement(\"input\");\n checkbox.setAttribute(\"type\", \"checkbox\");\n checkbox.className = \"checkbox\";\n checkbox.style.cssText = \"display: block; margin: 5px;\";\n el.appendChild(checkbox);\n j++;\n }\n}", "initializeCheckboxValues(data) {\n let numCheckboxes = Object.keys(data).length;\n // create list of checkbox values (initialized to true)\n let checkbox_values = []; // value to be stored in showSequence (the state values are true/false)\n for (let i = 0; i < numCheckboxes; i++) {\n let length = checkbox_values.push(true);\n }\n return checkbox_values;\n }", "function checkboxTemplate(name, value, label){\n var $tpl=\"<li>\";\n $tpl+=\"<input type='checkbox' name='\"+name+\"' value='\"+value+\"' />\";\n $tpl+=label;\n $tpl+=\"</li>\";\n return $tpl;\n }", "render() {\n const checkboxes = this.props.form.value.contents.map(content => {\n const childPath = this.props.form.path + \".\" + content.value\n content.checked = get(childPath, \"toggle\")\n\n return <div key={childPath}>\n <input\n type=\"checkbox\"\n className=\"k-checkbox\"\n id={childPath}\n defaultChecked={content.checked}\n onClick={(event) => this.props.updateState(childPath, event.target.checked)} />\n <label className=\"k-checkbox-label\" htmlFor={childPath}>{content.text}</label>\n </div>\n })\n\n return <div className=\"k-form-field\">\n <LabelTooltip form={this.props.form} />\n {checkboxes}\n </div>\n }", "function initCheckbox() {\n $(checkbox).each(function () {\n if ($(this).is(':checked')) {\n var id = $(this).attr(\"value\");\n certificationRadio($(this), id);\n }\n });\n }", "function addCheckbox() {\n //Add the checkbox the to all the products in the list on a pricewatch page\n for (i = 0; i < pricewatchItems.length; i++) {\n\n //Define some properties and variables and remove old label\n let itemName = pricewatchItems[i].querySelector('.itemname');\n let compareLabel = pricewatchItems[i].querySelector('label');\n let product = allProducts.filter(product => product.id === allProducts[i].id)[0];\n itemName.removeChild(compareLabel);\n\n //Add checkboxes Mijn Producten\n if (mijnProductenCheckboxes) {\n //Create a new label and set the innerHTML of the checkbox(es)\n let mijnProductenLabel = document.createElement('label');\n mijnProductenLabel.classList.add(`mijn-producten-label${product.id}`);\n mijnProductenLabel.innerHTML = `<input type=\"checkbox\" name=\"products[] value=\"${product.id}\"\"><span>Mijn Producten</span>`;\n let checkbox1 = mijnProductenLabel.querySelector('input')\n itemName.appendChild(mijnProductenLabel);\n //Add an eventlistener to the label button\n mijnProductenLabel.addEventListener('click', () => {\n if (!checkbox1.classList.contains('added')) {\n addToMPO(product);\n topNotification(product);\n } else {\n deleteFromMPO(product);\n }\n })\n } else {\n //nothing\n }\n\n //Add checkbox vergelijk\n if (vergelijkCheckboxes) {\n let vergelijkLabel = document.createElement('label');\n vergelijkLabel.classList.add(`vergelijk-label${product.id}`);\n vergelijkLabel.style.marginLeft = '5px';\n vergelijkLabel.innerHTML = `<input type=\"checkbox\" name=\"products[] value=\"${product.id}\"\"><span>Vergelijk</span>`;\n let checkbox2 = vergelijkLabel.querySelector('input');\n itemName.appendChild(vergelijkLabel);\n\n //Add an eventlistener to the label button\n vergelijkLabel.addEventListener('click', () => {\n if (!checkbox2.classList.contains('added')) {\n addToCompare(product);\n } else {\n deleteFromCompare(product);\n }\n });\n } else {\n //nothing\n }\n }\n}", "function createCheckBox(createElement, enableRipple = false, options = {}) {\n let wrapper = createElement('div', { className: 'e-checkbox-wrapper e-css' });\n if (options.cssClass) {\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"addClass\"])([wrapper], options.cssClass.split(' '));\n }\n if (options.enableRtl) {\n wrapper.classList.add('e-rtl');\n }\n if (enableRipple) {\n let rippleSpan = createElement('span', { className: 'e-ripple-container' });\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"rippleEffect\"])(rippleSpan, { isCenterRipple: true, duration: 400 });\n wrapper.appendChild(rippleSpan);\n }\n let frameSpan = createElement('span', { className: 'e-frame e-icons' });\n if (options.checked) {\n frameSpan.classList.add('e-check');\n }\n wrapper.appendChild(frameSpan);\n if (options.label) {\n let labelSpan = createElement('span', { className: 'e-label', innerHTML: options.label });\n wrapper.appendChild(labelSpan);\n }\n return wrapper;\n}", "function checkboxes() {\n\t\t\treturn $('#' + self.id + ' .check > :checkbox');\n\t\t}", "function addCheckBox(table){\n\tvar rows = table.find('tbody tr');\n\tfor (var i = 0; i < rows.length; i++) {\n\t\tvar current = rows[i];\n\t\tvar temp = \"<td><input type='checkbox' class='selection' /></td>\";\n\t\tvar html = current.innerHTML+temp;\n\t\trows[i].innerHTML = html;\n\t}\n}", "function newCheckbox() {\n\tvar checkbox = $(document.createElement(\"INPUT\"));\n\tcheckbox.attr(\"type\", \"checkbox\")\n\tcheckbox.bind(\"change\", function() {\n\t\tcheckbox.parent().toggleClass(\"checked\");\n\t});\n\treturn checkbox;\n}", "function markCheckboxes() {\n let check = (id) => {\n if (settings[id] == 'true') {\n $('#' + id).prop('checked', true);\n }\n }\n check('hide-hr-value');\n check('hide-upgrade-log');\n check('value-with-quantity');\n check('only-show-equipped');\n }", "function changeStateCheckBox() {\n checkedElements = [];\n // add items which are checked\n for (id of CHECKBOX_NAMES) {\n if (isChecked(id)) {\n checkedElements.push(id);\n }\n }\n updateBoard();\n}", "function makeCheckList ( list_name, options, ui_action )\n {\n\tvar content = '';\n\t\n\tif ( options == undefined || ! options.length )\n\t{\n\t console.log(\"ERROR: no options specified for checklist '\" + list_name + \"'\");\n\t return content;\n\t}\n\t\n\tfor ( var i=0; i < options.length / 2; i++ )\n\t{\n\t var code = options[2*i];\n\t var label = options[2*i+1];\n\t var attrs = '';\n\t var checked = false;\n\t \n\t if ( code.substr(0,1) == '+' )\n\t {\n\t\tcode = code.substr(1);\n\t\tchecked = true;\n\t }\n\t \n\t content += '<span class=\"dlCheckBox\"><input type=\"checkbox\" name=\"' + list_name + '\" value=\"' + code + '\" ';\n\t if ( checked ) content += 'checked=\"1\" ';\n\t content += attrs + 'onClick=\"' + ui_action + '\">' + label + \"</span>\\n\";\n\t}\n\t\n\treturn content;\n }", "function createMenuLabel(grammarRule, initChecked) {\n const checkboxLabel = document.createElement('label');\n checkboxLabel.classList.add(\"checkbox-label\");\n\n const checkbox = document.createElement('input');\n checkbox.setAttribute('type', 'checkbox');\n checkbox.checked = initChecked;\n CommandIde.addEventListener(checkbox, 'change', () => $ctrl.api.changeDefaultRulePreferences(grammarRule.name, checkbox.checked));\n checkboxLabel.append(checkbox);\n\n const checkmark = document.createElement('span');\n checkmark.classList.add(\"checkmark\");\n checkboxLabel.append(checkmark);\n\n const labelText = document.createElement('span');\n labelText.classList.add(\"label-text\");\n labelText.textContent = grammarRule.descriptiveName;\n checkboxLabel.append(labelText);\n\n return checkboxLabel;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if reached target position
reachedTargetPosition() { if (this.target !== undefined) { let targetCenter = this.getTargetCenter(); let ownCenter = this.getCenter(); // console.log(ownCenter); // console.log(targetCenter); var distance = Phaser.Math.Distance.Between( ownCenter.x, ownCenter.y, targetCenter.x, targetCenter.y ); if (distance < 10) { return true; } // console.log(distance); } return false; }
[ "hasReachedDestination() {\r\n\t\tvar destinationTiles = this.levelGrid.getDestination();\r\n\t\tfor (var i = 0; i < destinationTiles.length; i++) {\r\n\t\t\tvar destinationRow = destinationTiles[i].row;\r\n\t\t\tvar destinationColumn = destinationTiles[i].column;\r\n\t\t\tif ( this.currentTileRow === destinationRow\r\n\t\t\t\t && this.currentTileColumn === destinationColumn ) {\r\n\t\t\t\tthis.speed = 0;\r\n\t\t\t\treturn true;\r\n\t\t\t} \t\t\r\n\t\t}\r\n\t\treturn false;\r\n\t}", "checkRange() {\n if (!this.target)\n return;\n if (this.timeToNextAttack < 0)\n return;\n const dist = this.target.position.distanceTo(this.bot.entity.position);\n if (dist > this.viewDistance) {\n this.stop();\n return;\n }\n const inRange = dist <= this.attackRange;\n if (!this.wasInRange && inRange)\n this.timeToNextAttack = 0;\n this.wasInRange = inRange;\n }", "function eachSpaceAround(target, callback) {\n let pos = target.pos;\n for(let xDir = -1; xDir <= 1; xDir++) {\n for(let yDir = -1; yDir <= 1; yDir++) {\n let x = pos.x + xDir;\n let y = pos.y + yDir;\n if((xDir != 0 || yDir != 0) && target.room.lookForAt(LOOK_TERRAIN, x, y) != \"wall\") {\n if(callback({ x: x, y: y })) {\n return true;\n }\n }\n }\n }\n}", "__moveThresholdReached(clientX, clientY) {\n return Math.abs(clientX - this.data.startMouseX) >= this.moveThreshold || Math.abs(clientY - this.data.startMouseY) >= this.moveThreshold;\n }", "static isExit(pos) {\n return pos.x === 0 || pos.y === 0 || pos.x === 49 || pos.y === 49;\n }", "function getClosestElement() {\n var $list = sections\n , wt = contTop\n , wh = contentBlockHeight\n , refY = wh\n , wtd = wt + refY - 1\n ;\n\n if (direction == 'down') {\n $list.each(function() {\n var st = $(this).position().top;\n if ((st > wt) && (st <= wtd)) {\n target = $(this);\n //console.log($target);\n return false; // just to break the each loop\n }\n });\n } else {\n wtd = wt - refY + 1;\n $list.each(function() {\n var st = $(this).position().top;\n if ((st < wt) && (st >= wtd)) {\n target = $(this);\n //console.log($target);\n return false; // just to break the each loop\n }\n });\n }\n\n return target;\n\n}", "function checkHitTopBottom(ball) {\n\t\tif (ball.offsetTop <= 0 || ball.offsetTop >= 475) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "function isNear(value, target, maxDistance) {\n if (target === void 0) { target = 0; }\n if (maxDistance === void 0) { maxDistance = 0.01; }\n return (0,popmotion__WEBPACK_IMPORTED_MODULE_1__.distance)(value, target) < maxDistance;\n}", "has_next_frame() {\n if(this.frame_idx >= this.frames.length-1) return false;\n else return true;\n }", "canMakeStep() {\n const nextHeadPoint = this.snake.getNextStepHeadPoint();\n\n return !this.snake.isOnPoint(nextHeadPoint) &&\n nextHeadPoint.x < this.config.getColsCount() &&\n nextHeadPoint.y < this.config.getRowsCount() &&\n nextHeadPoint.x >= 0 &&\n nextHeadPoint.y >= 0;\n }", "function isNextCardOnScreen() {\n\n var nextCardNum = activeCardNum + 1;\n\n if (activeCardNum == cardData.length - 1) {\n return false;\n }\n // Adapted from https://docs.mapbox.com/mapbox-gl-js/example/scroll-fly-to/\n var element = document.querySelector(\"div[data-index='\" + String(nextCardNum) + \"']\")\n var bounds = element.getBoundingClientRect();\n\n return bounds.top < window.innerHeight / 2;\n}", "function didPlayerMove (loc) {\n\t\t\tvar lastMove = game.prevMoveId;\n\t\t\tif (typeof loc === 'string') {\n\t\t\t\treturn loc === lastMove;\n\t\t\t} else {\n\t\t\t\tfor (var key in loc) {\n\t\t\t\t\tif (loc[key] === lastMove) {\n\t\t\t\t\t\tconsole.log('from didPlayerMove : ' + loc[key]);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}", "function moveToTarget() {\n if (targetEntity == null) return;\n\n var path = bot.navigate.findPathSync(targetEntity.position, {\n timeout: 1 * 1000,\n endRadius: 2\n });\n bot.navigate.walk(path.path, function() {\n if (targetEntity != null) { bot.lookAt(targetEntity.position.plus(vec3(0, 1.62, 0))); }\n });\n\n checkNearestEntity();\n\n timeoutId = setTimeout(moveToTarget, 1 * 1000); // repeat call after 1 second\n}", "includes(range, target) {\n if (Range.isRange(target)) {\n if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {\n return true;\n }\n\n var [rs, re] = Range.edges(range);\n var [ts, te] = Range.edges(target);\n return Point.isBefore(rs, ts) && Point.isAfter(re, te);\n }\n\n var [start, end] = Range.edges(range);\n var isAfterStart = false;\n var isBeforeEnd = false;\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0;\n isBeforeEnd = Point.compare(target, end) <= 0;\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0;\n isBeforeEnd = Path.compare(target, end.path) <= 0;\n }\n\n return isAfterStart && isBeforeEnd;\n }", "walkBackWhile(startingPosition, condition) {\n let currentPos = startingPosition;\n let currentChar = this.getChar(currentPos);\n while (condition(currentChar)) {\n currentPos = this.getPrev(currentPos);\n currentChar = this.getChar(currentPos);\n if (currentPos.line === 0 && currentPos.character === 0)\n break;\n }\n return currentPos;\n }", "isAlive() {\n if (this.hitPoints = 0){\n \n }\n }", "checkEat() {\n let x = convert(this.snake[0].style.left);\n let y = convert(this.snake[0].style.top);\n\n let check = false;\n if (x === this.bait.x && y === this.bait.y) check = true;\n\n return check;\n }", "function is_captured() {\n if (Math.abs(hero.pos.x - zombie.pos.x) < char_size) {\n if (Math.abs(hero.pos.y - zombie.pos.y) < char_size) {\n return true;\n }\n }\n return false;\n }", "function isLeadingToFight(player, position) { // PARAMETERS : player, position\n\n var leadToFight = 0; // create a variable set to 0\n var surrounds = findSurroundingPositions(position); // find surrouding positions\n\n for (var i = 0; i < surrounds.length; i++) { // FOR each surrouding position\n if (surrounds[i] !== null) { // IF the position existe\n if ((squares[surrounds[i]].player === 1) && // IF a player is into it\n (i === 1 || i === 3 || i === 4 || i === 6) && // AND if the position is at top, bottom, left or right (not diagonal)\n (squares[surrounds[i]].position !== players[player].position)) { // // AND is not the position where the player himself is\n leadToFight = 1; // set variable value to 1\n }\n }\n }\n\n return leadToFight; // return variable value (0 = not leading ; 1 = leading)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of brands from list of products
function getBrandsFromProducts (products) { return [...new Set(products.map(product => product.brand))]; }
[ "function requestUniqueBrands(req, res){\n Product.distinct(\"brandName\", function(err, response){\n res.send(JSON.stringify(response));\n });\n}", "function compareBrandsToCatalog(popularItems, catalogItems) {\n // get string values from catalog brands\n var brandsInCatalog = [];\n for (var j = 0; j < catalogItems.length; j++) {\n \tconsole.log(catalogItems[j].brand_name.S);\n \tbrandsInCatalog.push(catalogItems[j].brand_name.S.toLowerCase());\n }\n console.log(brandsInCatalog);\n // get string values from brands mentioned on twitter\n var brandsOnTwitter = [];\n for (var i = 0; i < popularItems.length; i++) {\n \tconsole.log(popularItems[i].Brand.S);\n \tbrandsOnTwitter.push(popularItems[i].Brand.S.toLowerCase());\n };\n console.log(brandsOnTwitter);\n // make a list of items on twitter missing from catalog\n var recommendedBrands = [];\n for (var k = 0; k < brandsOnTwitter.length; k++) {\n \tconsole.log(brandsOnTwitter[k]);\n \tconsole.log(brandsInCatalog.indexOf(brandsOnTwitter[k]));\n \tvar index = brandsInCatalog.indexOf(brandsOnTwitter[k]);\n \tif (index != -1) {\n \t\trecommendedBrands.push(brandsOnTwitter[k]);\n \t}\n }\n console.log(recommendedBrands);\n updateTableDisplay(recommendedBrands);\n}", "function getAllProductsinCurrentOptiongroups(a, b, c){\n // return a list of bundle product Id's. based on flag provided.\n var res = [];\n _.each(a, function (group) {\n res.push(_.pluck(group[b], c));\n });\n\t\t\tres = _.flatten(res);// Flattens a nested array.\n res = _.filter(res, function(prodId){return !_.isUndefined(prodId)});\n\t\t\treturn res;\n }", "function getAllBerries(){\n\n}", "async function getProductList() {\n\n await fetch('http://52.26.193.201:3000/products/list')\n .then(response => response.json())\n .then(response => setProductList([...response]))\n }", "function getAllProducts(parent, args) {\n if (args.inStock) {\n return productList.filter(product => product.inventory_count > 0);\n } else {\n return productList\n }\n}", "function find_available_suppliers(product_id)\n{\n\t//iterate through available suppliers and prices and put filtered ones into a available list in the order_list \n\t//Empty the available suppliers list \n\tif (typeof(order_list[product_id].available_suppliers)!= 'undefined') while(order_list[product_id].available_suppliers.length>0) order_list[product_id].available_suppliers.pop();\n\t//Iterate through all Suppliers \n\tfor (var supplier_id in products_list[product_id].pricing_list)\n\t{\n\t\t//supplier_id = order_list[product_id].pricing_list[].supplierid;\n\t\tif (supplier_id in order_list[product_id].supplier_settings)\n\t\t\torder_list[product_id].available_suppliers[supplier_id] = true;\n\t}\n}", "function getProducts() {\n var params = getParams();\n params[\"categoryID\"] = $scope.categoryId;\n categoryApiService.getProductsByCategoryId(params).$promise.then(function(response) {\n var result = response.result || [];\n $scope.productsList = result;\n });\n }", "async function _extract_related_product_variant_ids (products, line_item_variants){\n let all_product_variants = [];\n \n for (let i = 0; i < products.length; i++){\n for (let j = 0; j < line_item_variants.length; j++){\n if (products[i].variant_ids.includes(line_item_variants[j])){\n all_product_variants.push(products[i].variant_ids);\n }\n }\n }\n \n return all_product_variants;\n}", "function getProduct(identifier, filter) {\n var productsFiltered = [];\n $(\".productlist\").empty();\n\n//uit 'products' worden de key en de value gehaald (key = 1 record en value de waarden die erin zitten)\n//als de array met de meegegeven 'soort' gelijk is aan de filter 'soortnaam' wordt de decorateProduct functie uitgevoerd\n $.each(products, function(key, val) {\n if(val[identifier] === filter) {\n decorateProduct(productsFiltered, val);\n }\n });\n\n $( \"<ul/>\", {\n \"class\": \"myUL\",\n html: productsFiltered.join(\"\")\n }).appendTo( \"#lijst\" );\n}", "function getVariantsByProduct(req, res) {\n\n\tlet { getVariantValuesByProduct } = query.variant_values\n\tlet { product_id } = req.params\n\n\tdb.query(getVariantValuesByProduct, product_id, (err, data) => {\n\n\t\tif (err) return res.status(500).send({ message: `Error from server: ${err}` })\n\t\telse if (!data) return res.status(404).send({ message: `Variant values not found for product_id: ${product_id}` })\n\n\t\tlet variantValues = data // Assign retrieved data from database\n\t\tlet groupVariants = [] // Array to group variants of the same product\n\t\tlet isEqual = true // Determine if enters the condition of differente variant_id\n\n\t\t// Manipulate database result set\n\t\t// Join variant values according to certain conditions\n\t\t// Validate product_id and variant_id to set variant values as one group.\n\t\t// Final result: [{'12oz', 'vainilla'}, {'12oz', 'normal'}]\n\t\tfor (let i = 0; i < variantValues.length; i++) { // Loop result set starting from position 0\n\t\t\tfor (let j = 1; j <= variantValues.length - 1; j++) { // Loop result set starting from position 1\n\n\t\t\t\t// In case product_id from first loop is equal to product_id from second loop and variant_id from first loop is different to variant_id from second loop\n\t\t\t\tif (variantValues[i].product_id == variantValues[j].product_id && variantValues[i].variant_id != variantValues[j].variant_id) {\n\t\t\t\t\t// Multiple variable declaration\n\t\t\t\t\tlet variantId1 = variantValues[i].variant_id, valueName1 = variantValues[i].value_name, variantId2 = variantValues[j].variant_id, valueName2 = variantValues[j].value_name\n\t\t\t\t\tlet manyVariants = { [variantId1]: valueName1, [variantId2]: valueName2 } // Create an object with the variant_id as property name and value name as property value\n\t\t\t\t\tgroupVariants.push(manyVariants)\n\t\t\t\t\tisEqual = false\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (isEqual) {\n\t\t\t\tlet oneVariant = { [variantValues[i].variant_id]: variantValues[i].value_name }\n\t\t\t\tgroupVariants.push(oneVariant) // Add oneVariant object\n\t\t\t}\n\t\t}\n\t\treturn res.status(200).send({ variants: groupVariants })\n\t})\n}", "function addProductLists(product){\n productLists.push(product);\n}", "static async list(req, res) {\n const variations = _.filter(\n req.product.variations,\n variation => !variation.deleted,\n );\n\n return res.products_with_additional_prices(variations);\n }", "function getPlateList(inWeight) {\n let remainingWeight = inWeight / 2;\n const availablePlates = allAvailablePlates.slice().sort((a, b) => {\n return (+a) - (+b) < 0;\n });\n const result = [];\n while(availablePlates.length > 0 && remainingWeight > 0) {\n const thisWeight = availablePlates.shift();\n if (remainingWeight >= thisWeight) {\n remainingWeight -= thisWeight;\n result.push(thisWeight);\n }\n }\n\n if (remainingWeight > 0) return ['MAXXED OUTTTTTT!!!'];\n return result.length > 0 ? result : ['no plates'];\n}", "function getBreweriesToRender(breweryList) {\n const filteredBreweries = applyUserFilters(breweryList);\n if (filteredBreweries.length > 10) {\n return filteredBreweries.slice(0, 10);\n }\n\n return filteredBreweries;\n }", "filterShops(prod) {\n if(!prod.length) {\n this.shops = this.shops.map(el => { \n el.active = true;\n return el;\n });\n return this.shops;\n }\n\n const filteredShops = this.shops.filter(el => prod.every(product => el.productsids.find(i => product === i)));\n \n this.shops = this.shops.map(el => {\n if(filteredShops.indexOf(el) === -1) { \n el.active = false;\n return el;\n }\n el.active = true;\n return el;\n });\n return this.shops;\n }", "async function _list_variants (products, ids, sizes={}, email=false, only_soh=true ){\n if (typeof ids === 'undefined' || ids === null){\n throw new VError(`ids parameter not usable`);\n }\n if (typeof ids === 'undefined' || ids === null){\n throw new VError(`products parameter not usable`);\n }\n\n let ret = await tradegecko.tradegecko_get_product_variants({\"ids\": ids});\n\n const available = [];\n\n /*\n * If only_soh is true then we only want to return stock on hand.\n */\n \n if (only_soh){\n for (let i = 0; i < ret.length; i++){\n const soh = ret[i].stock_on_hand - ret[i].committed_stock;\n if (soh > 0){\n available.push(ret[i]);\n }\n }\n\n ret = available;\n }\n \n /*\n * If email parameter is not false, then filter out variants already sent to \n * customer associated with this email\n */\n \n if (email){\n ret = await _filter_out_already_shipped_variants(products, ret, email);\n }\n \n /*\n * Filter out all variants that don't match the received sixe values\n */\n \n ret = await _filter_for_sizes(ret, sizes);\n \n return ret;\n}", "function getAllProducts () {\r\n return db.query(`SELECT * from products`).then(result => {\r\n return result.rows\r\n })\r\n}", "function inventoryBuckets(env, fc, productList, options) {\n return new Promise((resolve, reject) => {\n /*\n {\n \"productId\": product.id,\n \"mapping\" : {},\n \"quantity\" : product.quantity * deal.quantity,\n \"wmf\": deal.defaultWhId,\n \"dealId\": deal._id\n } \n */\n var config = _getConfig(env);\n\n var skuList = [];\n\n productList.map(p => {\n if (p.mapping && p.mapping.sku) {\n skuList.push(p.mapping.sku);\n }\n });\n\n var walmartProductPromise = new Promise((resolve, reject) => {\n Promise.all(productList.map(p => {\n return new Promise((_resolve, _reject) => {\n\n var url = `${config.basePath}/Product/Information/${config.MerchantId}/${p.mapping.productId}`;\n\n _fire(config, url, 'GET', null).then(result => {\n _resolve(result);\n }).catch(e => {\n _reject(e);\n });\n\n });\n })).then(walmartProducts => {\n if (walmartProducts && walmartProducts.length) {\n resolve(walmartProducts);\n } else {\n reject(new Error(`Could not get walmart products....`));\n }\n }).catch(e => reject(e));\n });\n\n\n var volumetricPromise = new Promise((resolve, reject) => {\n Promise.all(productList.map(p => {\n return new Promise((_resolve, _reject) => {\n\n const url = `${config.frontApi}/VolumetricPricing/${config.MerchantId}`;\n\n const options = {\n query: {\n productid: productId,\n storeId: fc.partner.locationId\n }\n }\n\n\n _fire(config, url, 'GET', options).then(result => {\n _resolve(result);\n }).catch(e => {\n _resolve();\n });\n //Here add productid to the response;\n });\n })).then(volumes => {\n resolve();\n }).catch(e => reject(e));\n });\n\n Promise.all([walmartProductPromise, volumetricPromise]).then(result => {\n\n var walmartProductList = result[0];\n var volumeList = result[1];\n var sortedGroup = {};\n\n if (!walmartProductList || !walmartProductList.length) {\n reject(new Error(`Could not get walmart product list.....`));\n return;\n }\n //Convert to bucket format;\n productList.map(p => {\n\n // var walmartProduct = _.find(walmartProductList, { \"Product.ProductId\": parseInt(p.mapping.productId) });\n\n var walmartProduct = _.find(walmartProductList, (pr => {\n if (pr.Product.ProductId === parseInt(p.mapping.productId)) {\n return true;\n }\n }));\n\n if (walmartProduct) {\n\n if (!sortedGroup[p.whId]) {\n\n sortedGroup[p.whId] = [];\n\n sortedGroup[p.whId].push({\n \"productId\": p.productId,\n \"totalQty\": 0,\n \"snapShots\": [{\n whId: p.whId,\n productId: p.productId,\n mappedProductId: walmartProduct.Product.ProductId,\n mrp: walmartProduct.Product.MRP,\n transferPrice: walmartProduct.Product.WebPrice,\n stock: parseInt(walmartProduct.Product.Inventory),\n onHold: 0,\n key: walmartProduct.Product.MRP,\n snapShotIds: []\n }],\n \"buckets\": {},\n \"bucketKeys\": []\n });\n\n } else {\n //if wmf key exists , then check if in that wmf this productId exists; If not then add;\n var exisiting = _.find(sortedGroup[p.whId], { productId: p.productId, whId: p.whId });\n\n if (!exisiting) {\n sortedGroup[p.whId].push({\n \"productId\": p.productId,\n \"totalQty\": 0,\n \"snapShots\": [{\n whId: p.whId,\n productId: p.productId,\n mappedProductId: walmartProduct.Product.ProductId,\n mrp: walmartProduct.Product.MRP,\n transferPrice: walmartProduct.Product.WebPrice,\n stock: parseInt(walmartProduct.Product.Inventory),\n onHold: 0,\n key: walmartProduct.Product.MRP,\n snapShotIds: []\n }],\n \"buckets\": {},\n \"bucketKeys\": []\n });\n }\n\n }\n\n }\n });\n\n Object.keys(sortedGroup).map(whId => {\n var whGroup = sortedGroup[whId]; // List of product snapshots;\n whGroup.map(product => {\n product.totalQty = _.sumBy(product.snapShots, \"stock\");\n var group = _.groupBy(product.snapShots, \"key\");\n product.buckets = group;\n Object.keys(product.buckets).map(mrpKey => {\n var _list = product.buckets[mrpKey];\n var count = _.sumBy(_list, \"stock\");\n product.buckets[mrpKey] = {\n \"whId\": _list[0].whId,\n \"productId\": _list[0].productId,\n \"mappedProductId\": _list[0].mappedProductId,\n \"mrp\": _list[0].mrp,\n \"transferPrice\": _list[0].transferPrice,\n \"stock\": count,\n \"onHold\": 0,\n \"snapShotIds\": []\n }\n })\n /* product.buckets[product.key] = {\n \"whId\": _list[0].whId,\n \"productId\": _list[0].productId,\n \"mappedProductId\": walmartProduct.Product.ProductId,\n \"mrp\": _list[0].mrp,\n \"transferPrice\": _list[0].WebPrice,\n \"stock\": count,\n \"onHold\": 0,\n \"snapShotIds\": []\n } */\n product.bucketKeys = Object.keys(group);\n delete product.snapShots;\n });\n\n })\n\n if (options && options.bucketsOnly) {\n resolve({ buckets: sortedGroup });\n } else {\n var products = walmartProductList.map(p => p.Product);\n resolve({ buckets: sortedGroup, productList: products });\n }\n\n }).catch(e => reject(e));\n\n // Sample response format to send;\n /* var mock = {\n \"WMF3\": [\n {\n productId: \"PR10964\",\n totalQty: 10,\n snapShots: [],\n buckets: {\n \"10_Walmart Offer\": {\n whId: \"WMF3\",\n productId: \"PR10964\",\n mrp: 60,\n transferPrice: _list[0].WebPrice,\n stock: 10,\n onHold: 0,\n snapShotIds: []\n }\n },\n bucketKeys: [\"10_Walmart Offer\"]\n }\n ]\n }; */\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
for error prompt when wrong pin entered
function errorPrompt(msg) { $('#oldPin').val(''); $('#pinError').show(); $('#pinError').html(msg); setTimeout(() => { $('#pinError').hide(); }, 3000); }
[ "function isValid(){\n if((''+pin) === userInput && tries !== 0){\n reset('all');\n triesLeft.innerText = '';\n notifyMatched.display = 'block';\n }\n else if(tries === 0){\n triesLeft.innerText = 'No more tries left';\n reset('all');\n notifyNotMatched.display = 'block';\n }\n else{\n reset();\n notifyNotMatched.display = 'block';\n triesLeft.innerText = `${tries} tries left`;\n }\n}", "function cpsh_onTryAgain(evt) {\n evt.preventDefault();\n pin.focus();\n authFailureConfirmDialog.hidden = true;\n }", "function inputPin(){\n let correctPin = validatePin();\n if (correctPin === true)mainMenu(); //ternary\n else return inputPin();\n}", "function validatePinLunh(pin) {\n\tvar doubled = [];\n\tfor ( var i = pin.length - 2; i >= 0; i = i - 2) {\n\t\tdoubled.push(2 * pin[i]);\n\t}\n\tvar total = 0;\n\tfor ( var i = ((pin.length % 2) == 0 ? 1 : 0); i < pin.length; i = i + 2) {\n\t\ttotal += parseInt(pin[i]);\n\t}\n\tfor ( var i = 0; i < doubled.length; i++) {\n\t\tvar num = doubled[i];\n\t\tvar digit;\n\t\twhile (num != 0) {\n\t\t\tdigit = num % 10;\n\t\t\tnum = parseInt(num / 10);\n\t\t\ttotal += digit;\n\t\t}\n\t}\n\tif (total % 10 == 0) {\n\t\treturn (true);\n\t} else {\n\t\t$(\"#pinOuterSection\").addClass(\"error_red_border\");\n\t\thideOrShowCashErrorMessage(\"blueBoxCnt1\", \"blueBoxMsgDiv1\",\tmessages[\"checkout.validation.validPin\"]);\n\t\t\n\t\t$(\"#saveBtnOfEvolve\").removeClass(\"bg_green\");\n\t\tdisableButton('saveBtnOfEvolve');\n\t\treturn (false);\n\t}\n}", "function pwUpdateError(){\n\tdisplayMessage(\"There was an error updating the password. The previous\\npassword will still be used to access the tile edit feature\\nand any edits you have made have been saved. Try to reset\\nthe password for this tile again later\", removePrompt(),\n\t\t\t\t\tremovePrompt(),false,false);\n}", "function check(pinCode,guess){\n var numCode = Number(pinCode);\n var numGuess = Number(guess);\n var found = false;\n\n if (numCode == numGuess){\n found = true;\n console.log(\"Got Lucky!\")\n alert(\"You got lucky, that is the Pin Code!\")\n } else {\n alert(\"Sorry, that is not the Pin Code...\")\n }\n return found;\n }", "function askPassword(ok, fail) {\r\n let password = prompt(\"Password?\", '');\r\n if (password === \"rockstar\") ok();\r\n else fail();\r\n}", "function secretNum() {\n var ip = parseInt(prompt(\"Enter number\",\"\"));\n var random = ((Math.random()*10)+1);\n if(ip == random) {\n document.write(\"Congo! you guess it write\");\n } else {\n document.write(\"Try again\");\n }\n}", "function validateInput() {\n\tvar valid = false;\n\tvar maxPins = 0;\n\tif (!((pins==0)||(pins==\"1\")||(pins==2)||(pins==3)||(pins==4)||(pins==5)||(pins==6)||(pins==7)||(pins==8)||(pins==9)||(pins==10))) {\n\t\talert('The number of pins must be between 0 and 10.');\n\t\t$scope.pins = '';\n\t} else if ((ball == 1) && (frame != 9) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\t} else if ((ball == 1) && (frame == 9) && (parseInt(line[frame][0]) != 10) && (pins > (10 - parseInt(line[frame][0])))) {\n\t\tmaxPins = (10 - parseInt(line[frame][0]));\n\t\talert('Number of pins must be in the range of 0 to ' + maxPins + '.');\n\t\t$scope.pins = '';\n\n\n\t} else {\n\t\tvalid = true;\n\t\tconsole.log('valid input');\n\t}\n\treturn valid;\n}", "function cpsh_onCancelQuit(evt) {\n evt.preventDefault();\n pin.focus();\n quitAppConfirmDialog.hidden = true;\n }", "function alert(guess) {\n\n if (guess < 0 || guess > 9) {\n\n console.log(`ERROR: ${guess} is out of range 0 - 9.`);\n }\n\n}", "function handleMonitorRequest(pin) \n{\n // save the argument value pin into a variable pin1\n pin1 = pin;\n \n // save state variable that indicates that a pin monitor is requested\n monitorRequested = true;\n}", "function passwordEvent(){\n //Find out if password is valid \n if(isPasswordValid()) {\n //Hide hint if valid\n $password.next().hide();\n } else {\n //else show hint\n let msgLen = validLength(8,100, $password, 'password').msg;\n let msgReg = regexCheck($password, 'password').msg;\n let eleLen = `<span>${msgLen}</span>`;\n let eleReg = `<span>${msgReg}</span>`;\n let ele = msgLen?msgReg?eleLen+eleReg:eleLen:eleReg\n\n $('#passwordMsg').html(ele).show();\n }\n}", "function onWrongInputRun(command) {\n let lang = Libs.Lang.get();\n Bot.sendMessage(lang.wrongInput);\n Bot.runCommand(command);\n}", "function keypadError(message) {\n\tvar temp = keypadScreen.textContent;\n\tkeypadScreen.textContent = message || \"ERROR\";\n\tkeypadDisabled = true;\n\tsetTimeout(\"keypadRestore('\" + temp + \"')\", KEYPAD_LOCK_TIME);\n}", "function askNaps(){\n var naps = prompt(questionsArr[4]).toLowerCase();\n if (naps === 'yes' || isiOSDev === 'y') {\n userPoints += 1;\n alertPrefixString = 'Correct! ';\n console.log('The user answered question 5 correctly');\n } else {\n alertPrefixString = 'Sorry! ';\n console.log('The user answered question 5 incorrectly');\n }\n var napsAlert = alert(alertPrefixString + responsesArr[4]);\n askBirthYear();\n}", "function LookupOASCapableFailed(result, context) {\n var action='', msf='', oldZipcode='', question='';\n if (context!=null && context!='') {\n\t var qs = context.split('|')\n oldZipcode = qs[2];\n }\n document.getElementById('zip_code').value = oldZipcode;\n\n alert('LookupOASCapable Failed: ' + result.status + ' ' + result.statusText);\n //there needs to be more than an alert\n}", "function newPasswordPrompt(xcoord,ycoord,pw){\n\tif (verboseDebugging){\n\t\tconsole.log(\"we in new pw prompt nao\");\n\t\tconsole.log(\"pw is: \");\n\t\tconsole.log(pw);\n\t}\n\tmessageDiv.style.display = \"none\";\n\t//Gather prompt arguments and pass them along to handler.\n\tvar initCoords = {};\n\tinitCoords.xcoord = xcoord;\n\tinitCoords.ycoord = ycoord;\n\n\t//set up new prompt in HTML DOM. Make sure that defaults are reset.\n\tdisplayPassword(\"If you wish to set a new password, enter it and confirm.\\nIf you wish to keep the previous password, press Don't Change\\nIf you wish to keep the tile public, press Make Public\",\n\t\t\t\t\tcheckPasswordMatch,pw,initCoords);\n\n}", "function incorrectCityName(error) {\n alert(\"Error finding city, please try again\");\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over the arrows collection hiding each arrow
hide () { foreach(arrow => arrow.hide(), this.arrows) }
[ "show () {\n foreach(arrow => arrow.show(), this.arrows)\n }", "fadeIn () {\n foreach(arrow => arrow.fadeIn(), this.arrows)\n }", "positionate () {\n foreach(arrow => arrow.positionate(), this.arrows)\n }", "clear () {\n this.arrows = []\n }", "function updateArrows() {\n game.globals.arrows.children.forEach(function(arrow) {\n if(arrow.checkWorldBounds) {\n arrow.destroy();\n }\n }, this);\n}", "function getArrows(parameters) {\n\t// Just return all the arrows, the view will take those in the range\n\treturn tgArrows.getList();\n}", "pollForArrowsChanges () {\n let brokenReference = false\n foreach(arrow => {\n if (arrow.hasChanged()) {\n arrow.positionate()\n }\n if (arrow.onceVisible && !isVisible(arrow.target.$el)) {\n brokenReference = true\n }\n }, this.arrows)\n\n if (brokenReference) {\n this.recreateDOMReferences()\n }\n }", "function setArrows(hideAll) {\n let nextIcon = document.getElementById(\"next-icon\");\n let prevIcon = document.getElementById(\"prev-icon\");\n nextIcon.style.display = \"block\";\n prevIcon.style.display = \"block\";\n //If the file has only one page, don't show buttons\n if (pdfDoc.numPages === 1 || hideAll) {\n nextIcon.style.display = \"none\";\n prevIcon.style.display = \"none\";\n } else if (pageNum <= 1) {\n //If the first page is shown, don't show the previous-button\n prevIcon.style.display = \"none\";\n } else if (pageNum >= pdfDoc.numPages) {\n //If the the last page is shown, don't show the next-button\n nextIcon.style.display = \"none\";\n }\n}", "function initArrows() {\n\n\t\tvar arrowNumber = $scope.round.arrowNumber,\n\t\t\tendNumber = $scope.round.endNumber;\n\n\t\tfor (var i = 0, j = 0;\n\t\t\ti < endNumber && j < arrowNumber;\n\t\t\tj++, i = (j === arrowNumber) ? i + 1 : i, j = (j === arrowNumber) ? j = 0 : j)\n\t\t{\n\n\t\t\tif (j === 0) {\n\n\t\t\t\t$scope.round.ends[i].active = (i === $scope.curEnd);\n\t\t\t\t$scope.round.ends[i].draggable = isEnabled;\n\t\t\t\t$scope.round.ends[i].style = {};\n\t\t\t\tdelete $scope.round.ends[i].radius;\n\n\t\t\t}\n\n\t\t\t$scope.round.ends[i].data[j].active = false;\n\n\t\t}\n\n\t}", "reverseVisibility(){\n for(let i = 0; i < this.children[2].children.length; i++){\n this.children[2].children[i].visible = !this.children[2].children[i].visible;\n }\n }", "function updateArrows(stateIdx) {\n if (stateIdx == 0) {\n d3.select('#left-arrow')\n .attr('disabled', true);\n } else if (stateIdx == states.length - 1) {\n d3.select('#right-arrow')\n .attr('disabled', true);\n } else {\n d3.select('#left-arrow')\n .attr('disabled', null);\n d3.select('#right-arrow')\n .attr('disabled', null);\n }\n }", "invisible()\n {\n for (let container of this.containers)\n {\n container.children.forEach(object => object[this.visible] = false)\n }\n }", "unbind() {\n\t\t\tthis.arrow.unbind();\n\t\t}", "fadeOut () {\n foreach(registerFadeOut, this.arrows)\n\n function registerFadeOut (arrow) {\n arrow.fadeOut(() => {\n arrow.destroy()\n })\n }\n }", "render (arrowPosition = 'top') {\n const fragment = document.createDocumentFragment()\n foreach(arrow => {\n arrow.position = arrowPosition\n fragment.appendChild(arrow.render())\n }, this.arrows)\n return fragment\n }", "function removeArrows(index) {\n let slideNum = index;\n if (slideNum == 1 && firstPageLoad == true) {\n leftButton.style.display = \"none\";\n rightButton.style.display = \"none\";\n firstPageLoad = false;\n } else {\n leftButton.style.display = \"block\";\n rightButton.style.display = \"block\";\n }\n}", "function hideDescendants($node) {\n var $temp = $node.closest('tr').siblings();\n if ($temp.last().find('.spinner').length) {\n $node.closest('.orgchart').data('inAjax', false);\n }\n var $visibleNodes = $temp.last().find('.node:visible');\n var $lines = $visibleNodes.closest('table').closest('tr').prevAll('.lines').css('visibility', 'hidden');\n $visibleNodes.addClass('slide slide-up').eq(0).one('transitionend', function() {\n $visibleNodes.removeClass('slide');\n $lines.removeAttr('style').addClass('hidden').siblings('.nodes').addClass('hidden');\n if (isInAction($node)) {\n switchVerticalArrow($node.children('.bottomEdge'));\n }\n });\n }", "function changeArrowIcon(){\n let prev = $(\".home-4 .gdz-slider-wrapper .prev\");\n let next = $(\".home-4 .gdz-slider-wrapper .next\");\n let newPrev = $('<svg width=\"25\" height=\"60\" viewBox=\"0 0 25 60\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M23.375 1.5L1.625 30L23.375 58.5\" stroke=\"#BEBEBE\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>');\n let newNext = $('<svg width=\"25\" height=\"60\" viewBox=\"0 0 25 60\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M1.625 58.5L23.375 30L1.625 1.5\" stroke=\"#BEBEBE\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>');\n prev.empty();\n prev.html(newPrev);\n next.empty();\n next.html(newNext);\n}", "function stripIcons(){\n\t\t\tvm.historyPoints = _.map(vm.historyPoints, function(data) { return _.omit(data, 'icon'); });\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal functions / Minify directory
function minifyDir(from, to) { // init `to` directory del.sync(to, {force:true}); mkdir(to); // process iterateFiles(from, function (filename) { var extname = filename.match('\.[a-zA-Z0-9]*$')[0]; var basename = path.basename(filename); var destdir = path.join(to, path.dirname(filename.replace(from, ''))); var destname = path.join(destdir, basename); mkdir(destdir, function(err) { if (err && err.code !== 'EEXIST') { console.log('[ERROR] mkdir:', destdir, ':', err); } else { switch(extname) { case '.css': processCSS(filename, destname); break; case '.lua': processLUA(filename, destname); break; case '.div': case '.html': case '.xhtml': processHTML(filename, destname); break; default: fs.createReadStream(filename).pipe(fs.createWriteStream(destname)); break; } } }); }, function (err) { if (err) { console.log('sorry, fatal error found:', err) } }); }
[ "function optimizeMore() {\r\n recursive(buildDir, function (err, files) {\r\n files.forEach(function(file) {\r\n if(/.css$/.test(file)) {\r\n fs.writeFileSync(file, new CleanCSS().minify(fs.readFileSync(file).toString()).styles);\r\n } else if(/.handlebars/.test(file)) {\r\n fs.unlinkSync(file);\r\n }\r\n });\r\n });\r\n}", "function compress_dist() {\n try {\n fs.accessSync(DIST_DIR, fs.constants.R_OK);\n } catch (err) {\n return console.log(`Cannot compress. Directory ${DIST_DIR} not found.\\n`);\n }\n\n return gulp.src(`${DIST_DIR}/**`).pipe(tar(`${DIST_DIR}.tar`)).pipe(gzip()).pipe(gulp.dest(\".\"));\n}", "function addMin(path) {\n path.basename += '.min'\n }", "function min_and_rename() {\n return src(\"./css/final.css\")\n .pipe(pleeease())\n .pipe(\n rename({\n suffix: \".min\",\n extname: \".css\"\n })\n )\n .pipe(dest(\"./css/\"));\n}", "function buildNormalize() {\n return src(paths.normalize)\n .pipe(cleanCSS())\n .pipe(size({ showFiles: true }))\n .pipe(dest(paths.prodCSS));\n}", "static minify (sourcePath, targetPath, onComplete) {\n const ext = path.extname(sourcePath).toLowerCase();\n const minifyType = minifyTypes[ext] || null;\n\n if (minifyType !== null) {\n compressor.minify({\n compressor: minifyType.compressor,\n input: sourcePath,\n output: targetPath,\n options: minifyType.options,\n callback: function (err) {\n if (err) {\n return logging.logger.error(`AssetManager: Minification failed for ${sourcePath}, reason: ${err.message}`, err);\n }\n logging.logger.info(`AssetManager: Minified ${sourcePath} to ${targetPath}`);\n if (onComplete) onComplete();\n }\n });\n } else {\n logging.logger.error(`AssetManager: Could not minify file with type ${ext} for path ${sourcePath}`);\n }\n }", "function DistClean(){\n\t// return del([delHtml,delStatic]);\n}", "function concatPackages (packages, outDir, minified) {\n if (! outDir) outDir = path.join('.', 'build');\n\n if (!fs.existsSync(outDir)) fs.mkdirSync(outDir);\n var jsFileName = path.join(outDir, 'build.js');\n if (fs.existsSync(jsFileName)){\n fs.truncateSync(jsFileName, 0);\n }\n var cssFileName = path.join(outDir, 'build.css');\n if (fs.existsSync(cssFileName)){\n fs.truncateSync(cssFileName, 0);\n }\n _.each(packages, function (pack, i, l) {\n concatPackage(pack, outDir, minified);\n });\n}", "function constructFileList (dir, mains, minified) {\n var files = fs.readdirSync(dir);\n\n files = _.map(files, function (f) {\n return path.join(dir, f);\n });\n\n _.each(files, function (f, i, l) {\n if (fs.statSync(f).isDirectory())\n files = files.concat(constructFileList(f, mains, minified));\n });\n\n files = _.filter(files, function (f) {\n if (fs.statSync(f).isDirectory()) return false;\n\n var fname = path.basename(f).split('.').slice(0, -1).join('.');\n\n var include = _.some(mains, function (m) {\n m = path.basename(m).split('.').slice(0, -1).join('.');\n return m === fname;\n });\n\n if (minified)\n include = f.indexOf('.min.js') === (f.length - 7)\n || f.indexOf('.min.css') === (f.length - 8);\n\n return include;\n });\n\n if (minified && files.length === 0) {\n return constructFileList(dir, mains, false);\n }\n\n return files;\n}", "function CleanUpHerokuDistFolder(){\n del.sync(`${deploymentPaths.HEROKU_DIST_FOLDER}/**`);\n}", "function copyTargets(buildInfo) {\n buildInfo.builtTargets.forEach(function (target) {\n var isMerged = target.match(/merged\\./),\n isBeauty = target.match(/beauty\\.html$/),\n basename = path.basename(target),\n src = path.join(rootDir, target),\n dst = \"\",\n sub = basename.split(\".\"),\n replaceFiles = [],\n version = (new Date()).getTime();\n \n if(!isMerged && !isBeauty) {\n return true;\n }\n \n if(isBeauty) {\n basename = basename.replace('.beauty',''); \n replaceFiles.push(path.join(rootDir, 'dist', basename));\n }\n \n dst = path.join(rootDir, 'dist', basename);\n \n if(isMerged) {\n basename = basename.replace('.dist','');\n subDir = sub[sub.length-1];\n dst = path.join(rootDir, 'dist/' + subDir, basename);\n \n if(basename.match(/merged\\..*?css$/)) {\n replaceFiles.push(dst);\n }\n }\n\n fse.copySync(src, dst);\n \n // изменение путей к стилям и скриптам\n replaceFiles.forEach(function( file ) {\n fs.readFile(file, function(err, content){\n if(!err) {\n content = content.toString();\n content = content.split(\"../merged/merged.css\").join(\"css/merged.css?v\"+version)\n .split(\"../merged/merged.js\").join(\"js/merged.js?v\"+version) \n .split(\"../../images/\").join(\"img/\")\n .split(\"../../dist/\").join(\"../\")\n .split(\"../../css/\").join(\"css/\")\n .split(\"../../js/\").join(\"js/\");\n \n fs.open(file, \"w\", 0644, function(err, handle) {\n if(!err) {\n fs.write(handle, content);\n }\n })\n }\n });\n });\n \n // копирование шрифтов и js библиотек\n var copyFiles = [\n {\n src : path.join(rootDir, 'fonts'),\n dst : path.join(rootDir, 'dist/fonts')\n },\n {\n src : path.join(rootDir, 'css/fonts.css'),\n dst : path.join(rootDir, 'dist/css/fonts.css')\n },\n {\n src : path.join(rootDir, 'js/libs'),\n dst : path.join(rootDir, 'dist/js/libs')\n },\n {\n src : path.join(rootDir, 'images'),\n dst : path.join(rootDir, 'dist/img')\n }\n ];\n \n copyFiles.forEach( function( copy ){\n fse.copySync(copy.src, copy.dst);\n });\n \n });\n }", "function concatPackage (pack, outDir, minified) {\n if (_.contains(concatedPkgs, path.basename(pack))) return;\n\n var bowerFile = 'bower.json';\n\n if (! fs.existsSync(path.join(pack, bowerFile)))\n bowerFile = '.bower.json';\n\n var regularJSON = JSON.parse(\n fs.readFileSync(path.join(pack, bowerFile))\n );\n var bowerJSON = json.normalize(regularJSON);\n var deps = bowerJSON.dependencies || {};\n var mains = bowerJSON.main || [];\n\n concatedPkgs.push(path.basename(pack));\n\n _.each(Object.keys(deps), function (pkg, i, l) {\n var components = pack.split(path.sep);\n var pkgpath = components.slice(0, -1).join(path.sep);\n\n concatPackage(path.join(pkgpath, pkg), outDir, minified);\n });\n\n debug('concatenating package ' + path.basename(pack) + '...');\n\n var files = constructFileList(pack, mains, minified);\n var concatJS = '', concatCSS = '';\n\n _.each(files, function (filepath, i, l) {\n var contents = fs.readFileSync(filepath) + '\\n';\n var ext = filepath.split('.')[filepath.split('.').length - 1];\n\n if (ext === 'js' || ext === 'css')\n debug('including file ' + filepath + '...');\n\n if (ext === 'js')\n concatJS += contents;\n else if (ext === 'css')\n concatCSS += contents;\n });\n\n if (concatJS !== '' || concatCSS !== '')\n debug('writing files...');\n\n if (concatJS !== '')\n fs.appendFileSync(path.join(outDir, 'build.js'), concatJS);\n\n if (concatCSS !== '')\n fs.appendFileSync(path.join(outDir, 'build.css'), concatCSS);\n}", "function copyVendorFilesFn () {\n var\n asset_group_table = pkgMatrix.xhiVendorAssetGroupTable || [],\n dev_dependency_map = pkgMatrix.devDependencies || {},\n asset_group_count = asset_group_table.length,\n promise_list = [],\n\n idx, asset_group_map, asset_list, asset_count,\n fq_dest_dir_str, dest_ext_str, do_dir_copy,\n\n idj, asset_map, src_asset_name, src_dir_str,\n src_pkg_name, dest_vers_str, dest_name,\n fq_src_path_list, fq_src_path_str,\n fq_dest_path_str, promise_obj\n ;\n\n for ( idx = 0; idx < asset_group_count; idx++ ) {\n asset_group_map = asset_group_table[ idx ] || {};\n\n asset_list = asset_group_map.asset_list || [];\n asset_count = asset_list.length;\n\n dest_ext_str = asset_group_map.dest_ext_str;\n do_dir_copy = asset_group_map.do_dir_copy;\n fq_dest_dir_str = fqProjDirname + '/' + asset_group_map.dest_dir_str;\n\n\n mkdirpFn.sync( fq_dest_dir_str );\n ASSET_MAP: for ( idj = 0; idj < asset_count; idj++ ) {\n asset_map = asset_list[ idj ];\n src_asset_name = asset_map.src_asset_name;\n src_dir_str = asset_map.src_dir_str || '';\n src_pkg_name = asset_map.src_pkg_name;\n\n dest_vers_str = dev_dependency_map[ src_pkg_name ];\n\n if ( ! dest_vers_str ) {\n logFn( 'WARN: package ' + src_pkg_name + ' not found.');\n continue ASSET_MAP;\n }\n dest_name = asset_map.dest_name || src_pkg_name;\n\n fq_dest_path_str = fq_dest_dir_str\n + '/' + dest_name + '-' + dest_vers_str;\n fq_src_path_list = [ fqModuleDirname, src_pkg_name, src_asset_name ];\n if ( src_dir_str ) { fq_src_path_list.splice( 2, 0, src_dir_str ); }\n\n fq_src_path_str = fq_src_path_list.join( '/' );\n\n if ( ! do_dir_copy ) {\n fq_dest_path_str += '.' + dest_ext_str;\n }\n promise_obj = copyPathFn( fq_src_path_str, fq_dest_path_str, do_dir_copy );\n promise_list.push( promise_obj );\n }\n }\n\n promiseObj.all( promise_list )\n .then( function () { eventObj.emit( '04PatchFiles' ); } )\n .catch( abortFn );\n }", "async function build(){\n\n let imgSrc = './dev/assets/img/*.+(png|jpg|gif|svg)',\n imgDst = './build/assets/img',\n jscopy = gulp.src(['./dev/assets/js/**/*.js']).pipe(uglify()).pipe(gulp.dest('./build/assets/js')),\n csscopy = gulp.src(['./dev/assets/css/**/*.css']).pipe(cleanCSS()).pipe(gulp.dest('./build/assets/css')),\n htmlcopy = gulp.src(['./dev/*.html']).pipe(gulp.dest('./build')),\n optimages = gulp.src(imgSrc).pipe(changed(imgDst)).pipe(imagemin()).pipe(gulp.dest(imgDst));\n\n}", "function fixTagPages(){\n var tagFolder = \"static/tag/\";\n var fileTempSufix = \"_TMP\";\n\n fs.readdirSync( tagFolder ).forEach(function(file){\n if( file[0] == \".\")\n return;\n\n fs.renameSync( tagFolder + file , tagFolder + file + fileTempSufix )\n fs.mkdirSync( tagFolder + file );\n fs.renameSync( tagFolder + file + fileTempSufix, tagFolder + file + \"/index.html\" );\n })\n}", "function imagesTask(){\n return src(files.imgToMinify)\n .pipe(image())\n .pipe(dest(files.distToDistImg));\n}", "function jsTask() {\n return src(files.jsPath)\n .pipe(concat(\"all.js\"))\n .pipe(minify())\n .pipe(dest(\"dist\"));\n}", "gruntRename() {\n let assets = [];\n if (this.images.length > 0) {\n assets = assets.concat(this.images);\n }\n if (this.scripts.length > 0) {\n assets = assets.concat(this.scripts);\n }\n if (this.styles.length > 0) {\n assets = assets.concat(this.styles);\n }\n if (assets.length > 0) {\n const files = {};\n assets.forEach((asset, index, arry) => {\n const name = path.basename(asset.dest);\n const dest = asset.dest.replace(name, asset.reved);\n files[dest] = asset.dest;\n });\n return {\n files: files\n };\n }\n return undefined;\n }", "function source() {\n return project.splitSource()\n // Add your own build tasks here!\n .pipe(gulpif('**/*.{png,gif,jpg,svg}', images.minify()))\n .pipe(project.rejoin()); // Call rejoin when you're finished\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the toast by id, given it's in the DOM, otherwise returns null
function getToast(toastId, _ref) { var containerId = _ref.containerId; var container = getContainer(containerId); if (!container) return null; var toast = container.collection[toastId]; if (typeof toast === 'undefined') return null; return toast; }
[ "function getEl(id) {\n return document.getElementById(id) || document.getElementsByClassName(id)[0] || document.getElementsByTagName(id)[0] || null;\n}", "function GetElement(id) {\n\treturn document.getElementById(id);\n}", "function fltFindNativeElement(id) {\n //getElementsByTagName('flt-platform-view')[0].shadowRoot.getElementById(t.elementID)\n let fltPlatformViews = document.getElementsByTagName('flt-platform-view');\n for(var i = 0; i < fltPlatformViews.length; i++)\n if (fltPlatformViews[i].shadowRoot.getElementById(id) !== null)\n return fltPlatformViews[i].shadowRoot.getElementById(id);\n return null;\n}", "function getElementIDJumlahPesanan (id)\r\n {\r\n var el = \"\";\r\n switch (id)\r\n {\r\n case 0: el = \"ket1\"; break;\r\n case 1: el = \"ket2\"; break;\r\n case 2: el = \"ket3\"; break;\r\n case 3: el = \"ket4\"; break;\r\n case 4: el = \"ket5\"; break;\r\n case 5: el = \"ket6\"; break;\r\n }\r\n return el; \r\n }", "function getNotifyName(id){\r\n\tvar names = getNotifyNames();\r\n\tif(!names) return false;\r\n\treturn names[id];\r\n}", "function showToastMessage() {\n const toast = localStorage.getItem('showToast');\n if (localStorage.length <= 0) return;\n if (data.shouldShowToast === false) return;\n\n switch (toast) {\n case 'profile-info':\n new Toast('Updated profile info');\n localStorage.removeItem('showToast');\n break;\n case 'profile-password':\n new Toast('Updated profile password');\n localStorage.removeItem('showToast');\n break;\n default:\n localStorage.removeItem('showToast');\n }\n }", "static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'get', kparams);\n\t}", "function getValidIndex () {\n return $toasts.get().findIndex(toast => toast.key === toastId)\n }", "presentToast(texto) {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(this, void 0, void 0, function* () {\n const toast = yield this.toastController.create({\n message: texto,\n duration: 2000\n });\n toast.present();\n });\n }", "function get_xml_node(which_doc, which_id){\r\n\ttry {\r\n\t\treturn which_doc.getElementsByTagName(which_id)[0];\r\n\t}\r\n\tcatch(err) {\r\n\t\treturn null;\r\n\t}\r\n}", "function getMasteryInfo(id)\n {\n if (id in mastery)\n return mastery[id]\n else\n throw new Error (\"No mastery with id \" + id)\n }", "buildToast_() {\n const toastDurationSeconds = 7;\n return this.activityPorts_\n .openIframe(this.iframe_, this.src_, this.args_)\n .then((port) => {\n return port.whenReady();\n })\n .then(() => {\n resetStyles(this.iframe_, ['height']);\n\n this.animate_(() => {\n setImportantStyles(this.iframe_, {\n 'transform': 'translateY(100%)',\n 'opactiy': 1,\n 'visibility': 'visible',\n });\n return transition(\n this.iframe_,\n {\n 'transform': 'translateY(0)',\n 'opacity': 1,\n 'visibility': 'visible',\n },\n 400,\n 'ease-out'\n );\n });\n\n // Close the Toast after the specified duration.\n this.doc_.getWin().setTimeout(() => {\n this.close();\n }, (toastDurationSeconds + 1) * 1000);\n });\n }", "findItem(id) {\n if (this.manifest && id) {\n return this.manifest.items.find((item) => {\n if (item.id !== id) {\n return false;\n }\n return true;\n });\n }\n return null;\n }", "function showToast(message, duration){\n Materialize.toast(message, duration, 'rounded');\n }", "function getElementByIdInDocs(id, docs) {\n for (let key in docs) {\n let elem = docs[key].getElementById(id);\n if (elem) {\n //console.info(\"[ainfo] found element with id \" + id + \" in docs[\" + key + \"]\");\n return elem;\n }\n }\n return null;\n }", "getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }", "getById(id) {\n return spPost(TimeZones(this, `GetById(${id})`));\n }", "function getStateBarElement(id){\n\t\treturn document.getElementById(id).nextElementSibling.childNodes[3].childNodes[1];\n\t}", "function getBeatBox() {\n\tvar len = swf_tags.tags.length;\n\tvar i = 0;\n\tvar elm = null;\n\t\n\tfor(i = 0; i < len; i++) {\n\t\telm = swf_tags.tags[i];\n\t\tif(elm.header.code == SWFTags.DOACTION)\n\t\t\treturn elm;\n\t}\n\t\n\treturn null;\n}", "getContentFor(id) {\n return this._content[id] || \"\";\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The AspectRatio component provides a `ratio` prop that will be used to specify the aspect ratio that the children you provide will be displayed in. This is often useful alongside our grid components, or for media assets like images or videos.
function AspectRatio({ as: BaseComponent = 'div', className: containerClassName, children, ratio = '1x1', ...rest }) { const className = cx( containerClassName, `${prefix}--aspect-ratio`, `${prefix}--aspect-ratio--${ratio}` ); return ( <BaseComponent className={className} {...rest}> {children} </BaseComponent> ); }
[ "applyAspectRatioAttributes_() {\n if (!this.element.hasAttribute('aspect-ratio')) {\n return;\n }\n setImportantStyles(this.element, {\n '--aspect-ratio': this.element\n .getAttribute('aspect-ratio')\n .replace(':', '/'),\n });\n }", "setCanvasRatio() {\n const canvasElement = this.getCanvasElement();\n const cssWidth = parseInt(canvasElement.style.width, 10);\n const originWidth = canvasElement.width;\n const ratio = originWidth / cssWidth;\n\n this._ratio = ratio;\n }", "static calculateScaledWidth(height, aspectRatio) {\n return Math.floor(height * aspectRatio);\n }", "function circleDiameter(ratio) {\n return ratio * 2;\n}", "stretchToMatch(ratio, integer = true) {\n let width = this.width;\n let height = this.height;\n let round = (x) => x;\n\n // To get integers, each dimension must at least be divisible by its ratio.\n if (integer) {\n round = Math.ceil;\n width += (ratio.width - width % ratio.width) % ratio.width;\n height += (ratio.height - height % ratio.height) % ratio.height;\n }\n\n // Stretch relatively smaller dimension to fit relatively larger one.\n width = Math.max(width, height * ratio.width / ratio.height);\n height = Math.max(height, width * ratio.height / ratio.width);\n\n // Create new Border, distributing extra width and height evenly.\n const widthDelta = width - this.width;\n const heightDelta = height - this.height;\n\n return this.shift(\n round(heightDelta / 2 * -1),\n round(heightDelta / 2),\n round(widthDelta / 2),\n round(widthDelta / 2 * -1)\n );\n }", "function aspectScale() {\n $(\".media-container\").each(function () {\n var container = $(this);\n container.find(\"img, video\").each(function () {\n var dims = {\n w: this.naturalWidth || this.videoWidth || this.clientWidth,\n h: this.naturalHeight || this.videoHeight || this.clientHeight\n },\n space = {\n w: container.width(),\n h: container.height()\n };\n if (dims.w > space.w || dims.h > space.h) {\n $(this).css({width: \"\", height: \"\"}); // Let CSS handle the downscale\n } else {\n if (dims.w / dims.h > space.w / space.h) {\n $(this).css({width: \"100%\", height: \"auto\"});\n } else {\n $(this).css({width: \"auto\", height: \"100%\"});\n }\n }\n });\n });\n }", "fitToRatio(pixelHeight, pixelWidth, ratio) {\n const zoom = this.calculateMinimumZoom(pixelHeight, pixelWidth, lockRatio);\n const pixelBorder =\n this.convert(coordinate => Pixel.from(coordinate, zoom)).round();\n return pixelBorder.stretchToMatch(ratio);\n }", "function set_player_aspect(aspect, theater_default=false) {\n debug_log(\"Setting player aspect to \" + aspect + \".\")\n \n // We need to set overflow to hidden on the movie-player otherwise the video\n // overhangs in miniplayer mode. Get it by class name rather than id, for\n // compatibility with embedded videos\n document.getElementsByClassName(\"html5-video-player\")[0].style.setProperty(\"overflow\", \"hidden\")\n \n // For embedded videos, we don't need to do anything.\n \n // For default view\n if(document.getElementsByTagName(\"ytd-watch-flexy\")[0]) {\n var ytdwfs = document.getElementsByTagName(\"ytd-watch-flexy\")[0].style\n ytdwfs.setProperty(\"--ytd-watch-flexy-width-ratio\", aspect)\n ytdwfs.setProperty(\"--ytd-watch-flexy-height-ratio\", 1)\n }\n \n // For theater mode\n var ptc = document.getElementById(\"player-theater-container\")\n \n if(in_theater_mode() && !theater_default) {\n debug_log(\"Setting theater mode height.\")\n // 56px for masthead; --ytd-masthead-height is not always set, so can't use\n // that unfortunately\n ptc.style.setProperty(\"max-height\", \"calc(100vh - 56px)\")\n ptc.style.setProperty(\"height\", \"calc((\" + (1/aspect) + \") * 100vw)\")\n } else {\n debug_log(\"Unsetting theater mode height.\")\n if(ptc) {\n ptc.style.removeProperty(\"max-height\")\n ptc.style.removeProperty(\"height\")\n }\n }\n}", "function matchHeight()\n {\n obj.width(Math.round( obj.outerWidth( ) * \n obj.parent().height()/obj.outerHeight( ) - \n (obj.outerWidth( ) - obj.width())));\n obj.height(Math.round( obj.parent().height() - \n (obj.outerHeight( ) - obj.height()) ));\n }", "function aspectChange(e) {\n\t\t//Get the index from the id, which is of format 'aspect.1'\n\t\tlet ind= this.id.substring( this.id.indexOf('.')+1 );\n\t\taAspects[ind] = this.value;\n\t}", "setupEmbed() {\n Object.keys(this.videoEmbeds).forEach((key) => {\n const embed = this.videoEmbeds[key];\n\n embed.iframe.setAttribute(\n 'data-aspect-ratio',\n `${embed.iframe.height / embed.iframe.width}`\n );\n embed.iframe.removeAttribute('height');\n embed.iframe.removeAttribute('width');\n });\n\n this.resizeEmbed();\n window.addEventListener('resize', this.resizeEmbed);\n }", "function renderCompareImage(src, height, alt, className, parentQuery) {\n\n var imgDiv = document.createElement(\"div\")\n imgDiv.className = className\n\n var img = document.createElement(\"img\");\n \t\t\timg.src = src;\n \t\t\timg.style.height = height*5 + \"px\";\n \t\t\timg.alt = alt;\n\n \t\t\timgDiv.appendChild(img)\n\n \t\t\tvar parent = document.querySelector(parentQuery)\n \t\t\tparent.appendChild(imgDiv)\n }", "function Percent() {\n Ratio.apply(this, arguments);\n this.cssType = PERCENT;\n }", "makeAspect() {\n return new Aspect();\n }", "resizeEmbed() {\n Object.keys(this.videoEmbeds).forEach((key) => {\n const embed = this.videoEmbeds[key];\n\n fastdom.measure(() => {\n const newWidth = embed.floated ?\n embed.parent.offsetWidth :\n this.element.offsetWidth;\n fastdom.mutate(() => {\n embed.iframe.setAttribute(\n 'height',\n newWidth * embed.iframe.dataset.aspectRatio\n );\n embed.iframe.setAttribute('width', newWidth);\n });\n });\n });\n }", "function matchWidth()\n {\n obj.height(Math.round( obj.outerHeight( ) * \n obj.parent().width()/obj.outerWidth( ) - \n (obj.outerHeight( ) - obj.height()) ));\n obj.width(Math.round( obj.parent().width() - \n (obj.outerWidth( ) - obj.width())));\n }", "applyScale(aspect) {\n let pos = aspect.get(Component.Position);\n let tr = aspect.get(Component.TextRenderable);\n // scale pos\n this.cachePos.copyFrom_(pos.p).scale_(this.gameScale);\n // if the obj is in the world coordinate system, figure out the\n // world coordinates that correspond to the desired HUD coordinates\n if (tr.displayData.stageTarget === StageTarget.World) {\n this.translator.HUDtoWorld(this.cachePos);\n }\n aspect.dobj.position.set(this.cachePos.x, this.cachePos.y);\n aspect.dobj.rotation = angleFlip(pos.angle);\n // style\n let textRenderable = aspect.get(Component.TextRenderable);\n let base = textRenderable.textData.style;\n let target = aspect.dobj.style;\n let props = ['fontSize', 'dropShadowDistance'];\n for (let prop of props) {\n if (base[prop] != null && (typeof base[prop] === 'number')) {\n target[prop] = base[prop] * this.gameScale;\n }\n }\n }", "render() {\n return Children.only(this.props.children);\n }", "#getParentSize() {\n const comp_style = window.getComputedStyle(this.#canvas.parentNode);\n\n this.#parent_width = parseInt(comp_style.width.slice(0, -2));\n this.#parent_height = parseInt(comp_style.height.slice(0, -2));\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given partial request, fill it in from defaults, and return request and signature to send. if nonce is not explicitly specified, read it from forwarder
async function makeRequest(web3, req, defaultRequest, chainId, forwarderInstance) { var _a; const filledRequest = { request: Object.assign(Object.assign({}, defaultRequest.request), req.request), relayData: Object.assign(Object.assign({}, defaultRequest.relayData), req.relayData) }; // unless explicitly set, read nonce from network. if (((_a = filledRequest.request.nonce) !== null && _a !== void 0 ? _a : '0') === '0') { filledRequest.request.nonce = (await forwarderInstance.getNonce(filledRequest.request.from)).toString(); } const sig = await Utils_1.getEip712Signature(web3, new TypedRequestData_1.default(chainId, filledRequest.relayData.forwarder, filledRequest)); return { req: filledRequest, sig }; }
[ "function NewCredRequest(sk , IssuerNonce , ipk , rng ) {\n\t// Set Nym as h_{sk}^{sk}\n\tlet HSk = ipk.HSk\n\tlet Nym = HSk.mul(sk)\n\n\t// generate a zero-knowledge proof of knowledge (ZK PoK) of the secret key\n\n\t// Sample the randomness needed for the proof\n\tlet rSk = RandModOrder(rng)\n\n\t// Step 1: First message (t-values)\n\tlet t = HSk.mul(rSk) // t = h_{sk}^{r_{sk}}, cover Nym\n\n\t// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\t// proofData is the data being hashed, it consists of:\n\t// the credential request label\n\t// 3 elements of G1 each taking 2*FieldBytes+1 bytes\n\t// hash of the issuer public key of length FieldBytes\n // issuer nonce of length FieldBytes\n \n let proofData = new ArrayBuffer(credRequestLabel.length+3*(2*FieldBytes+1)+2*FieldBytes);\n let v = new Uint8Array(proofData);\n\tlet index = 0\n\n\tindex = appendBytesString(v, index, credRequestLabel)\n\tindex = appendBytesG1(proofData, index, t)\n\tindex = appendBytesG1(proofData, index, HSk)\n\tindex = appendBytesG1(proofData, index, Nym)\n index = appendBytes(v, index, IssuerNonce)\n v.set(BigToBytes(ipk.Hash),index)\n\tlet proofC = HashModOrder(v)\n\n\t// Step 3: reply to the challenge message (s-values)\n\tlet proofS = Modadd(FP256BN.BIG.modmul(proofC, sk, GroupOrder), rSk, GroupOrder) // s = r_{sk} + C \\cdot sk\n\n\t// Done\n\treturn {\n\t\tNym: Nym,\n\t\tIssuerNonce: IssuerNonce,\n\t\tProofC: proofC,\n ProofS: proofS\n }\n}", "function requestCardNonce(event) {\n\n // Don't submit the form until SqPaymentForm returns with a nonce\n event.preventDefault();\n\n payMess.classList.add('is-hidden');\n clearResults(payMessCont);\n // Request a nonce from the SqPaymentForm object\n showLoadingButton(paySubmit, true);\n paymentForm.requestCardNonce();\n }", "postValidationRequest() {\n this.server.route({\n method: 'POST',\n path: '/requestValidation',\n handler: (request, h) => {\n let address = request.payload.address;\n // THrow error if there is no address in paylaod\n if (!address) {\n throw Boom.badRequest(\"Must submit a Bitcoin address!\");\n }\n // Associate request timestamp with address in backend\n let timestamp = new Date().getTime().toString().slice(0,-3);\n let validationWindow = 300\n\n // If request exists for address, update validationWindow, or renew if expired\n if (this.validationRequests[address]) {\n validationWindow = 300 - (Number(timestamp) - Number(this.validationRequests[address].requestTimeStamp));\n if (validationWindow < 0) {\n this.validationRequests[address].requestTimeStamp = timestamp;\n }\n }\n // If no request exists for address, add to memory\n else {\n this.validationRequests[address] = {\n \"requestTimeStamp\": timestamp,\n \"registerStar\": false\n }\n }\n\n // return the request with the message to sign\n return {\n \"address\": address,\n \"requestTimeStamp\": this.validationRequests[address].requestTimeStamp,\n \"message\": address + \":\" + this.validationRequests[address].requestTimeStamp + \":starRegistry\",\n \"validationWindow\": validationWindow\n };\n }\n });\n }", "function GenericRequest() {}", "function getRequest(event) {\n //code\n return request = {\n headers: event.headers,\n body: JSON.parse(event.body)\n };\n}", "addARequestToMempool(request){\r\n let self = this;\r\n\r\n //we use an array to hold the request index in mempool array based on the wallet address\r\n let indexToFind = this.walletList[request.walletAddress];\r\n let validInWalletList = this.validWalletList[request.walletAddress];\r\n\r\n //if user already validated the request sends an error\r\n if(validInWalletList){\r\n throw Boom.badRequest(\"There is a valid signature request already made and verified, you can now add star\");\r\n return;\r\n }\r\n\r\n //if this is the first request\r\n if(indexToFind == null){\r\n //calculates time left\r\n let timeElapse = this.getCurrentTimestamp()-request.requestTimeStamp;\r\n let timeLeft = (this.TimeoutRequestWindowTime/1000)-timeElapse;\r\n request.validationWindow = timeLeft;\r\n\r\n //add the request to the mempool\r\n indexToFind = this.mempool.push(request)-1;\r\n console.log(\"New index added: \"+indexToFind+\" - address: \"+request.walletAddress);\r\n this.walletList[request.walletAddress] = indexToFind;\r\n\r\n //sets a timeout of 5 minutes to remove the request\r\n this.timeoutRequests[request.walletAddress] = setTimeout(function (){self.removeValidationRequest(request.walletAddress)},self.TimeoutRequestWindowTime);\r\n return request; \r\n } else{ //if request is already in memory\r\n //gets the existent request\r\n let existentRequest = this.mempool[indexToFind];\r\n \r\n //calculates time left\r\n existentRequest.requestTimeStamp = this.mempool[indexToFind].requestTimeStamp;\r\n let timeElapse = (this.getCurrentTimestamp())-existentRequest.requestTimeStamp;\r\n let timeLeft = (this.TimeoutRequestWindowTime/1000) - timeElapse;\r\n existentRequest.validationWindow = timeLeft;\r\n\r\n return existentRequest;\r\n }\r\n }", "function buildStepFunctionRequest(arn, request, name) {\n const stateMachineArn = `arn:aws:states:${arn.region}:${arn.account}:function:${arn.appName}-${arn.fn}`;\n let input;\n if (request.headers) {\n request.headers[\"X-Correlation-Id\"] = state_1.getCorrelationId();\n request.headers[\"x-calling-function\"] = state_1.getContext().functionName;\n request.headers[\"x-calling-request-id\"] = state_1.getContext().requestId;\n input = JSON.stringify(request);\n }\n else {\n input = JSON.stringify(Object.assign(Object.assign({}, request), {\n headers: {\n \"X-Correlation-Id\": state_1.getCorrelationId(),\n \"x-calling-function\": state_1.getContext().functionName,\n \"x-calling-request-id\": state_1.getContext().requestId\n }\n }));\n }\n // if(!name) {\n // name =\n // }\n return {\n stateMachineArn,\n input,\n name\n };\n}", "function requestIdOf(request) {\n const hashed = Object.entries(request)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => {\n const hashedKey = hashString(key);\n const hashedValue = hashValue(value);\n return [hashedKey, hashedValue];\n });\n const traversed = hashed;\n const sorted = traversed.sort(([k1], [k2]) => {\n return buffer.Buffer.compare(buffer.Buffer.from(k1), buffer.Buffer.from(k2));\n });\n const concatenated = concat(sorted.map(concat));\n const requestId = hash(concatenated);\n return requestId;\n}", "function nnsParamsInterceptor($httpProvider) {\n $httpProvider.interceptors.push(['$q', '$injector', '$log', function ($q, $injector) {\n return {\n request: function (config) {\n var profileService = $injector.get('profileService'),\n stbService = $injector.get('stbService'),\n locationService = $injector.get('locationService'),\n appConfig = $injector.get('config');\n\n if (!config.ignoreNNSParams && (config.url.indexOf(appConfig.nnsApi) > -1 ||\n config.url.indexOf(appConfig.vod.globalBookmarks) > -1 ||\n config.url.indexOf(appConfig.watchlist) > -1)) {\n\n return $q.all([profileService.isTVODRentEnabled(),\n profileService.isTVODWatchEnabled(),\n profileService.isCdvrEnabled(),\n stbService.getCurrentStbPromise(),\n profileService.getCapabilities(),\n locationService.getLocation(),\n profileService.isRdvrHidden()]).then(([tvodRentEnabled, tvodWatchEnabled, cdvrEnabled,\n currentStb, capabilities, location, rdvrHidden]) => {\n config.params = config.params || {};\n\n angular.extend(config.params, {\n tvodRent: tvodRentEnabled,\n tvodWatch: tvodWatchEnabled\n });\n if (cdvrEnabled) {\n angular.extend(config.params, {\n cdvrEnabled: cdvrEnabled\n });\n } else if (currentStb) {\n angular.extend(config.params, {\n flickable: currentStb.flickable,\n dvr: currentStb.isDvr,\n macaddress: currentStb.macAddressNormalized,\n dvrManager: !rdvrHidden // whether RDVR view is available or not\n });\n\n if (currentStb.isDvr) {\n angular.extend(config.params, {rdvrVersion: currentStb.rdvrVersion});\n }\n\n if (currentStb.tuneLinear) {\n angular.extend(config.params, {tuneToChannel: true});\n }\n }\n\n angular.extend(config.params, {\n displayOutOfHomeOnly: !location.behindOwnModem,\n deviceOutOfHome: !location.behindOwnModem\n });\n\n if (capabilities.watchondemand && capabilities.watchondemand.authorized) {\n angular.extend(config.params, {watchOnDemand: true});\n }\n if (capabilities.tunetochannel && capabilities.tunetochannel.authorized) {\n angular.extend(config.params, {tuneToChannel: true});\n }\n if (capabilities.watchlive && capabilities.watchlive.authorized) {\n angular.extend(config.params, {watchLive: true});\n }\n\n return config;\n });\n } else {\n return $q.resolve(config);\n }\n }\n };\n }]);\n }", "postValidationSignature() {\n this.server.route({\n method: 'POST',\n path: '/message-signature/validate',\n handler: (request, h) => {\n let address = request.payload.address;\n let signature = request.payload.signature;\n let timestamp = new Date().getTime().toString().slice(0,-3);\n\n // Verify that the payload has an address and signature\n if (!address) {\n throw Boom.badRequest(\"Must submit a Bitcoin address!\");\n }\n if (!signature) {\n throw Boom.badRequest(\"Must submit a signed message to validate the Bitcoin address!\");\n }\n\n // Get the stored validation request for this address\n let validationRequest = this.validationRequests[address];\n if (!validationRequest) {\n throw Boom.badRequest(\"Submit a validation request for this address first via /requestValidation\");\n }\n\n // Check if the validation window has passed\n let validationWindow = 300 - (Number(timestamp) - Number(validationRequest.requestTimeStamp));\n // If window expired, remove validation request from memory and throw error\n if (validationWindow < 0) {\n this.validationRequests = this.validationRequests.splice(this.validationRequests.indexOf(address), 1);\n throw Boom.badRequest(\"The time limit for the request has expired. Please submit a new request.\");\n }\n\n // Check signed message against validation request\n let message = address + \":\" + validationRequest.requestTimeStamp + \":starRegistry\";\n let validSignature = bitcoinMessage.verify(message, address, signature);\n if (!validSignature) {\n throw Boom.badRequest(\"The signature cannot be verified for this address and message.\");\n }\n\n // Grant permission to register a star\n this.validationRequests[address].registerStar = true\n\n\n return {\n \"registerStar\": true,\n \"status\": {\n \"address\": address,\n \"requestTimeStamp\": validationRequest.requestTimeStamp,\n \"message\": message,\n \"validationWindow\": validationWindow,\n \"messageSignatureStatus\": \"valid\",\n }\n }\n }\n });\n }", "async function signOwnInput () {\n try {\n // console.log(`Tx: ${JSON.stringify(unsignedTx, null, 2)}`)\n // Convert the hex string version of the transaction into a Buffer.\n const paymentFileBuffer = Buffer.from(unsignedTx, 'hex')\n\n const allAddresses = [aliceAddr, bobAddr, samAddr]\n\n // Simulate signing own inputs for every individual address\n allAddresses.forEach(function (address) {\n const wif = wifForAddress(address)\n const ecPair = bchjs.ECPair.fromWIF(wif)\n\n // Generate a Transaction object from the transaction binary data.\n const csTransaction = Bitcoin.Transaction.fromBuffer(paymentFileBuffer)\n // console.log(`payments tx: ${JSON.stringify(csTransaction, null, 2)}`)\n\n // Instantiate the Transaction Builder.\n const csTransactionBuilder = Bitcoin.TransactionBuilder.fromTransaction(\n csTransaction,\n 'mainnet'\n )\n // console.log(`builder: ${JSON.stringify(csTransactionBuilder, null, 2)}`)\n\n // find index of the input for that address\n const inputIdx = inputForAddress(address, csTransactionBuilder.tx.ins)\n\n // TODO: user should check also if his own Outputs presents\n // in csTransactionBuilder.tx.outs[]\n\n const addressUTXO = utxoForAddress(address)\n let redeemScript\n csTransactionBuilder.sign(\n inputIdx,\n ecPair,\n redeemScript,\n Bitcoin.Transaction.SIGHASH_ALL,\n addressUTXO.value\n )\n // build tx\n const csTx = csTransactionBuilder.buildIncomplete()\n // output rawhex\n const csTxHex = csTx.toHex()\n // console.log(`Partially signed Tx hex: ${csTxHex}`)\n\n // 'Send' partialially signed Tx to the server\n fs.writeFileSync(`signed_tx_${inputIdx}.json`, JSON.stringify(csTxHex, null, 2))\n })\n\n console.log('signed txs for every user written successfully.')\n } catch (err) {\n console.error(`Error in signOwnInput(): ${err}`)\n throw err\n }\n}", "verifyManifoldRequest(req, res, next) {\n verifier.test(req, req._buffer.toString('utf8')).then(next, err => {\n // Verification issue\n logger.warn(`Failed to verify manifold request: %s`, err);\n // Response taken from ruby-sinatra-example:\n res.status(401).send({\n message: 'bad signature'\n });\n });\n }", "getRequestSerializer() {\n return ((req) => {\n let returnVal = null;\n if (!req)\n returnVal = req;\n else if (!req.connection)\n returnVal = { custom: JSON.stringify(req, undefined, 4) };\n else {\n returnVal = {\n method: req.method,\n url: req.url,\n headers: JSON.stringify(req.headers, undefined, 4),\n remoteAddress: req.connection.remoteAddress,\n remotePort: req.connection.remotePort,\n body: JSON.stringify(req.body, undefined, 4),\n };\n }\n return returnVal;\n // Trailers: Skipping for speed. If you need trailers in your app, then uncomment\n //if (Object.keys(trailers).length > 0) {\n // obj.trailers = req.trailers;\n //}\n });\n }", "function allow(request, reply) {\n //JWT includes a recorderID\n if (!request.jwt.recorder_id) {\n reply.fail({\n status: '401',\n detail: 'Auth token is not valid for any recorder',\n });\n return;\n }\n //JWT includes an accountID\n if (!request.jwt.account_id) {\n reply.fail({\n status: '401',\n detail: 'Auth token is not valid for any account',\n });\n return;\n }\n //path param accountID matches JWT's accountID\n if (request.account_id !== request.jwt.account_id) {\n reply.fail({\n status: '403',\n detail: 'Auth token is not valid for account ' + request.account_id,\n });\n return;\n }\n //JWT's recorderID matches the body's recorderID\n if (request.jwt.recorder_id !== request.body.data[0].id) {\n reply.fail({\n status: '403',\n detail: 'Auth token is not valid for recorder ' + request.body.data[0].id,\n });\n return;\n }\n reply.succeed(request);\n}", "function getRequest(event) {\n\n return {\n headers: event.headers,\n body: JSON.parse(event.body)\n };\n}", "function hit_endpoint(form) {\n // Determine the url of the endpoint we're hitting.\n var action = form.action.indexOf('file://') != -1 ? form.action.substr('file://'.length) : form.action;\n var endpoint_location = action;\n\n // Gather all the fields and their values\n var $inputs = $(form).find(':input');\n var fields = {};\n $inputs.each(function() {\n if (this.name && this.name != '') {\n fields[this.name] = $(this).val();\n $(this).val('');\n }\n });\n\n console.log(fields);\n\n var account_id = $('#account_id').val();\n var account_key = $('#account_key').val();\n var headers = {};\n if (account_id && account_key) {\n headers['X-PITA-ACCOUNT-ID'] = account_id;\n headers['X-PITA-SECRET'] = account_key;\n }\n\n var completion_handler = function(resp, http_status) {\n var endpoint_cont = $(form).closest('.endpoint');\n $(endpoint_cont).find('.status_code .code').text(http_status);\n if (resp.responseJSON) {\n // We got json back. Prettify it before displaying it.\n var pretty = JSON.stringify(resp.responseJSON, undefined, 2);\n $(endpoint_cont).find('.endpoint-response pre').text(pretty);\n } else {\n $(endpoint_cont).find('.endpoint-response pre').text(resp.responseText);\n }\n };\n\n $.ajax(endpoint_location, {\n type: form.method,\n data: fields,\n complete: completion_handler,\n headers: headers\n });\n console.log('Hitting endpoint: ' + form.method.toUpperCase() + ' ' + endpoint_location);\n}", "async permitProxySendTokens (owner, relayerAddress, amount) {\n const web3 = this.ethWeb3Manager.getWeb3()\n const myPrivateKey = this.web3Manager.getOwnerWalletPrivateKey()\n const chainId = await new Promise(resolve => web3.eth.getChainId((_, chainId) => resolve(chainId)))\n const name = await this.ethContracts.AudiusTokenClient.name()\n const tokenAddress = this.ethContracts.AudiusTokenClient.contractAddress\n\n // Submit permit request to give address approval, via relayer\n let nonce = await this.ethContracts.AudiusTokenClient.nonces(owner)\n const currentBlockNumber = await web3.eth.getBlockNumber()\n const currentBlock = await web3.eth.getBlock(currentBlockNumber)\n // 1 hour, sufficiently far in future\n let deadline = currentBlock.timestamp + (60 * 60 * 1)\n\n let digest = getPermitDigest(\n web3,\n name,\n tokenAddress,\n chainId,\n { owner: owner, spender: relayerAddress, value: amount },\n nonce,\n deadline\n )\n let result = sign(digest, myPrivateKey)\n const tx = await this.ethContracts.AudiusTokenClient.permit(\n owner,\n relayerAddress,\n amount,\n deadline,\n result.v,\n result.r,\n result.s,\n { from: owner }\n )\n return tx\n }", "requestInvite(){\n let ic = new iCrypto()\n ic.createNonce(\"n\")\n .bytesToHex(\"n\", \"nhex\");\n let request = new Message(self.version);\n let myNickNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.nickname,\n this.session.metadata.topicAuthority.publicKey);\n let topicNameEncrypted = ChatUtility.encryptStandardMessage(this.session.settings.topicName,\n this.session.metadata.topicAuthority.publicKey);\n request.headers.command = \"request_invite\";\n request.headers.pkfpSource = this.session.publicKeyFingerprint;\n request.headers.pkfpDest = this.session.metadata.topicAuthority.pkfp;\n request.body.nickname = myNickNameEncrypted;\n request.body.topicName = topicNameEncrypted;\n request.signMessage(this.session.privateKey);\n this.chatSocket.emit(\"request\", request);\n }", "function get_signed_request(file, ifLast){\n\t\tvar username;\n\t\tif(document.getElementById('username') != null){\n\t\t\tusername = document.getElementById('username').value;\n\t\t}\n\t\telse{\n\t\t\tusername = 'username';\n\t\t}\n\t\t\n\t var xhr = new XMLHttpRequest();\n\t xhr.open(\"GET\", \"/sign_s3?file_name=\"+file.name+\"&file_type=\"+file.type+\"&username=\"+username);\n\t xhr.onreadystatechange = function(){\n\t if(xhr.readyState === 4){\n\t if(xhr.status === 200){\n\t var response = JSON.parse(xhr.responseText);\n\t upload_file(file, response.signed_request, response.url, ifLast);\n\t }\n\t else{\n\t alert(\"Could not get signed URL.\");\n\t }\n\t }\n\t };\n\t xhr.send();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Comparaison de deux objets TimeRanges
function compareTimeRanges(t1, t2) { if (!t1 || !t2 || t1.length != t2.length) { //Si l'un des objets n'existe pas ou si leurs longueurs diffèrent, on renvoie false return false; } else { for (let i = 0; i < t1.length; i++) { //Comparaison de chacun des éléments contenus dans les TimeRanges //Si on trouve une différence, on arrete et on renvoie false if (t1.start(i) != t2.start(i) || t1.end(i) != t2.end(i)) { i = t1.length; return false; } } } return true; } //Si le timeRanges renvoyé par la propriété buffered du média est différent de celui déjà enregistré
[ "function handleTimeRanges() {\n //Calculate extent of each time scale.\n defineFullTimeRanges.call(this);\n\n //Set initial range of each time scale.\n defineInitialTimeRanges.call(this);\n\n //Sync time range variables given initial time scale.\n syncTimeRanges.call(this);\n }", "function timePlanner(a, b, duration) {\n let aCount = 0;\n let bCount = 0;\n \n while (aCount < a.length && bCount < b.length) {\n const start = Math.max(a[aCount][0], b[bCount][0]);\n const end = Math.min(a[aCount][1], b[bCount][1]);\n\n if (start + duration <= end) {\n return [start, start + duration];\n }\n \n if (a[aCount][1] < b[bCount][1]) {\n aCount++;\n } else {\n bCount++;\n }\n }\n \n return [];\n }", "mergeIntervals(basicIntervals, complexIntervals){\n\n let cmp = (int1, int2) => {\n return int1.start - int2.start;\n };\n\n // sort intervals by start index\n basicIntervals = basicIntervals.sort(cmp);\n complexIntervals = complexIntervals.sort(cmp);\n\n let eliminateDuplication = sortedArr => {\n return sortedArr.filter( ( currVal, currIndex ) => {\n let compPrev = () => {\n let prevVal = sortedArr[ currIndex - 1 ];\n\n return currVal.start === prevVal.start && currVal.end === prevVal.end;\n };\n\n return currIndex === 0 || !compPrev();\n } );\n };\n\n // same intervals would be repeated based on text mining results\n // handle such cases by removing any duplication of intervals\n basicIntervals = eliminateDuplication( basicIntervals );\n complexIntervals = eliminateDuplication( complexIntervals );\n\n let basicIndex = 0;\n let complexIndex = 0;\n let retVal = [];\n\n while ( basicIndex < basicIntervals.length && complexIndex < complexIntervals.length ) {\n let basicInt = basicIntervals[basicIndex];\n let complexInt = complexIntervals[complexIndex];\n\n // push a complex object for the part of complex interval that intersects no basic interval\n if ( basicInt.start > complexInt.start ) {\n let complexObj = {\n start: complexInt.start,\n end: Math.min(basicInt.start, complexInt.end),\n classes: [ complexInt.class ]\n };\n\n retVal.push(complexObj);\n\n // update the beginining of complex interval since we just covered some\n complexInt.start = complexObj.end;\n\n // if the whole complex interval is covered pass to the next one\n // this would happen if complex interval does not include any basic interval\n if ( complexInt.end === complexObj.end ) {\n complexIndex++;\n continue;\n }\n }\n\n let basicObj = {\n start: basicInt.start,\n end: basicInt.end,\n classes: [ basicInt.class ]\n };\n\n // if basic interval is covered by complex interval it makes an intersection\n // so it should have the complex class as well\n if ( basicInt.start >= complexInt.start && basicInt.end <= complexInt.end ) {\n basicObj.classes.push( complexInt.class );\n complexInt.start = basicInt.end;\n\n // we are done with this intersection pass to the next one\n if ( complexInt.start >= complexInt.end ) {\n complexIndex++;\n }\n }\n\n retVal.push(basicObj);\n\n // pass to next basic interval\n basicIndex++;\n }\n\n let iterateRemaningIntervals = ( index, intervals ) => {\n while ( index < intervals.length ) {\n let interval = intervals[index];\n retVal.push({\n start: interval.start,\n end: interval.end,\n classes: [ interval.class ]\n });\n index++;\n }\n };\n\n // iterate through the remaining intervals\n iterateRemaningIntervals( basicIndex, basicIntervals );\n iterateRemaningIntervals( complexIndex, complexIntervals );\n\n return retVal;\n }", "static compare(first, second) {\n\t\tif(first.time>second.time) return 1;\n\t\telse if(first.time<second.time) return -1;\n\t\telse return 0;\n\t}", "function getOverlaps(schedules) {\n var res = [];\n \n return schedules.reduce((openSlots, schedule) => {\n var open = getOpenSlots(schedule);\n \n return intersectSchedules(openSlots, open);\n }, [['09:00', '20:00']]);\n \n }", "getTimesBetween(start, end, day) {\n var times = [];\n // First check if the time is a period\n if (this.data.periods[day].indexOf(start) >= 0) {\n // Check the day given and return the times between those two\n // periods on that given day.\n var periods = Data.gunnSchedule[day];\n for (\n var i = periods.indexOf(start); i <= periods.indexOf(end); i++\n ) {\n times.push(periods[i]);\n }\n } else {\n var timeStrings = this.data.timeStrings;\n // Otherwise, grab every 30 min interval from the start and the end\n // time.\n for (\n var i = timeStrings.indexOf(start); i <= timeStrings.indexOf(end); i += 30\n ) {\n times.push(timeStrings[i]);\n }\n }\n return times;\n }", "function sortBandsByTime(a, b) {\r\n if (a.time !== b.time) {\r\n return b.time - a.time;\r\n } else {\r\n return a.name.localeCompare(b.name);\r\n }\r\n }", "function noteCompareByTime(note1 , note2) {\n\n\tvar first_time = parseInt(note1.note_time);\n\tvar second_time = parseInt(note2.note_time);\n\n\tif (first_time < second_time) {\n\t\treturn -1;\n\t}\n\tif (first_time > second_time) {\n\t\treturn 1;\n\t}\n\treturn 0;\n\n}", "function getEqualRanges_(arr) {\n var equalRanges = [];\n var start = -1;\n var startVal = 0;\n for (var i = 0; i < arr.length; i++) {\n if (start < 0) {\n start = i;\n startVal = arr[i];\n } else if (arr[i] != startVal) {\n if (start != i - 1) {\n equalRanges.push({start: start, length: i - start});\n }\n\n start = i;\n startVal = arr[i];\n }\n }\n if (start != arr.length - 1) {\n equalRanges.push({start: start, length: arr.length - start});\n }\n return equalRanges.sort(function(x, y){ return y.length - x.length; });\n}", "function conflicted(course1, course2){\n \treturn (shareDays(course1, course2) && (course1.start_time <= course2.end_time && course1.start_time >= course2.start_time ||\n\t course2.start_time <= course1.end_time && course2.start_time >= course1.start_time ||\n\t course1.start_time <= course2.start_time && course1.end_time >= course2.end_time ||\n\t course2.start_time <= course1.start_time && course2.end_time >= course1.end_time));\n }", "function duration_within_display_range(range_start, range_end, event_start, event_end) {\n if (event_start < range_start) {\n return duration_seconds_to_minutes(event_end - range_start);\n } else if (event_end > range_end) {\n return duration_seconds_to_minutes(range_end - event_start);\n } else {\n return duration_seconds_to_minutes(event_end - event_start);\n } \n }", "function areDatesDifferent(ts0, ts1) {\n\t\tvar d0 = new Date(ts0 - dateBoundaryOffsetMs);\n\t\tvar d1 = new Date(ts1 - dateBoundaryOffsetMs);\n\t\treturn d0.getFullYear() != d1.getFullYear() || d0.getMonth() != d1.getMonth() || d0.getDate() != d1.getDate();\n\t}", "equals(range, another) {\n return Point.equals(range.anchor, another.anchor) && Point.equals(range.focus, another.focus);\n }", "function sortByDuration(a, b) {\n var durA = a.get(\"end\").getTime() - a.get(\"start\").getTime();\n var durB = b.get(\"end\").getTime() - b.get(\"start\").getTime();\n return durA - durB;\n }", "function parseTimeBounds(args)\n{\n\tvar timeBefore, timeAfter;\n\n\t/*\n\t * Check the \"before\" and \"after\" fields. Because of the way we iterate\n\t * them, we can only support neither or both.\n\t */\n\tif (args.timeAfter) {\n\t\tif (!args.timeBefore) {\n\t\t\treturn (new VError(\n\t\t\t '\"after\" requires specifying \"before\" too'));\n\t\t}\n\n\t\ttimeAfter = new Date(args.timeAfter);\n\t\tif (isNaN(timeAfter.getTime()))\n\t\t\treturn (new VError('\"after\": not a valid date: \"%s\"',\n\t\t\t args.timeAfter));\n\n\t\ttimeBefore = new Date(args.timeBefore);\n\t\tif (isNaN(timeBefore.getTime()))\n\t\t\treturn (new VError('\"before\": not a valid date: \"%s\"',\n\t\t\t args.timeBefore));\n\n\t\tif (timeAfter.getTime() > timeBefore.getTime())\n\t\t\treturn (new VError('\"after\" timestamp may not ' +\n\t\t\t 'come after \"before\"'));\n\t} else if (args.timeBefore) {\n\t\treturn (new VError('\"before\" requires specifying \"after\" too'));\n\t}\n\n\treturn ({\n\t 'timeAfter': timeAfter,\n\t 'timeBefore': timeBefore\n\t});\n}", "checkStartTimes() {\n if (Object.keys(this.startTimes).length > 0) { // Are there any startTimes to check?\n let thisDate = new Date();\n for (var i=0, keys=Object.keys(this.startTimes); i < keys.length; i++) {\n let startDate = this.startTimes[keys[i]], endDate = this.endTimes[keys[i]];\n if (!this.groupStatus[keys[i]].collecting) { // Is the group already collecting then skip check.\n if (thisDate > startDate && (!endDate || (endDate && startDate < endDate)) ) this.toggle(keys[i]);\n } else { // Group is collecting and has a start time so check end time\n if (!endDate) { delete this.startTimes[keys[i]]; delete this.endTimes[keys[i]]; }\n else if (endDate && endDate < thisDate) { this.toggle(keys[i]); delete this.startTimes[keys[i]]; delete this.endTimes[keys[i]]; }\n }\n startDate = null; endDate = null;\n }\n thisDate = null;\n }\n }", "function compareByInterval(node, otherNode) {\n return node.source.startIdx - otherNode.source.startIdx\n}", "isElementShowing(e) {\n return this.props.time >= e.start_time &&\n this.props.time <= e.end_time;\n }", "function meetingRooms(arr) {\n //GOAL is to find overlaping elements\n //1. sort the meeting by starting time\n arr.sort((a, b) => a[0] - b[0]);\n\n //2. need to keep track of our end times\n //assign the end interval to be the first end interval(1st el from arr)\n //while looping it might change\n\n let end = arr[0][1];\n\n for (let i = 1; i < arr.length; i++) {\n if (end > arr[i][0]) return false; //means that there's an overlap(the next meeting starts before the previous one finishes)\n if (end < arr[i][1]) end = arr[i][1]; //check if the current end interval is less then the next end =>if so reassign it to a new end\n }\n return true;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
output: the number of friday the 13ths in that year. loop through all 12 months of the year and count how many times the the 13th day of the month is a friday. algorithm: 1. create a count variable set to 0 2.iterate through the months of the year, start with 0, go to 11 3.get the day of the month that falls on the 13th. 4.increment the count for each friday. 5.return the count
function fridayThe13ths(year) { var date = new Date(year, 0, 13); var count = 0; var i; for (i = 0; i < 12; i++) { date.setMonth(i); if (date.getDay() === 5) { count += 1; } } return count; }
[ "function lastDayIsFriday(initialYear, endYear = initialYear) {\n let count = 0;\n // if(endYear < initialYear || !endYear|| !initialYear){\n // initialYear === endYear;\n // }\n for (let year = initialYear; year <= endYear; year++) {\n for (let months = 0; months <= 11; months++) {\n let date = new Date(year, months + 1, 0);\n console.log(date.getDay())\n if (date.getDay() === 5) {\n\n count++\n }\n }\n }\n\n return count\n}", "function getWeekNo(dayInMonth){\n let numberOfDays = (new Date(2019, month, dayInMonth+2).getTime() - startDate.getTime())/(24*60*60*1000)\n let weekNo = Math.ceil(numberOfDays/7)\n if (weekNo > 0 && weekNo <=12){\n return weekNo\n }\n }", "function summerJamCount(songs) {\n let months = [6,7,8];\n let counter = 0;\n songs.forEach(song =>{\n if (months.includes(song.month)) counter++\n })\n return counter;\n}", "function weeks_in_month(month, year) {\n var first_day_of_month = new Date(year, month, 1);\n var last_day_of_month = new Date(year, month + 1, 0);\n\n// console.log(first_day_of_month + ':' + last_day_of_month);\n\n var used = first_day_of_month.getDay() + 6 + last_day_of_month.getDate();\n\n return Math.ceil(used / 7);\n}", "function days_this_month() {\n r = new Date()\n return daysInMonth(r.getMonth() + 1, r.getYear())\n}", "function monthToDays(monthNum)\n{\n var month;\n var days;\n switch(monthNum)\n {\n case 1:\n month = months[0];\n break;\n case 2:\n month = months[1];\n break;\n case 3:\n month = months[2];\n break;\n case 4:\n month = months[3];\n break;\n case 5:\n month = months[4];\n break;\n case 6:\n month = months[5];\n break;\n case 7:\n month = months[6];\n break;\n case 8:\n month = months[7];\n break;\n case 9:\n month = months[8];\n break;\n case 10:\n month = months[9];\n break;\n case 11:\n month = months[10];\n break;\n case 12:\n month = months[11];\n }\n console.log(month);\n switch(month)\n {\n case \"January\":\n days = 31;\n break;\n case \"February\":\n days = 28;\n break;\n case \"March\":\n days = 31;\n break;\n case \"April\":\n days = 30;\n break;\n case \"May\":\n days = 31;\n break;\n case \"June\":\n days = 30;\n break;\n case \"Julie\":\n days = 31;\n break;\n case \"August\":\n days = 31;\n break;\n case \"September\":\n days = 30;\n break;\n case \"October\":\n days=31;\n break;\n case \"November\":\n days = 30;\n break;\n case \"December\":\n days = 31; \n }\n console.log(\"There were \"+days+\" days, in \"+month+\" of 2017.\")\n}", "function beautifulDays(i, j, k) {\n let beautifulDaysCount = 0\n for (let day = i; day <= j; day++) {\n //by checking modulus if the remainder is 0\n // const isDayDivisibleByk = Math.abs(day - reverseNumber(day)) % k === 0\n //by checking if remainder is integer (actual problem)\n const isDayDivisibleByk = Number.isInteger(Math.abs(day - reverseNumber(day)) / k)\n if (isDayDivisibleByk) {\n beautifulDaysCount++\n continue\n }\n }\n return beautifulDaysCount\n}", "function totalDayWorked(numOfDays,dailyWage){\n if(dailyWage>0) return numOfDays+1;\n return numOfDays;\n}", "function calcDayOfYear(mn, dy, lpyr) {\n var k = (lpyr ? 1 : 2);\n var doy = Math.floor((275 * mn)/9) - k * Math.floor((mn + 9)/12) + dy -30;\n return doy;\n}", "repeatCount(startGoal, endGoal) {\n var rule = 'FREQ=DAILY;COUNT=';\n var startday = startGoal.slice(3, 5);\n var endday = endGoal.slice(3, 5);\n var days = parseInt(endday, 10) - parseInt(startday, 10) + 1 ;\n rule = rule + days.toString();\n console.log(\"math\", startday, endday, days);\n return rule;\n }", "function getDaysInMonth()\n{\n var daysArray = new Array(12);\n \n for (var i = 1; i <= 12; i++)\n {\n daysArray[i] = 31;\n\tif (i==4 || i==6 || i==9 || i==11)\n {\n daysArray[i] = 30;\n }\n\tif (i==2)\n {\n daysArray[i] = 29;\n }\n }\n return daysArray;\n}", "populateDaysInMonth() {\n var daysInMonth = [];\n //first day of this.state.monthNumber\n var date = new Date(this.state.year, this.state.monthNumber);\n while (date.getMonth() === this.state.monthNumber) {\n daysInMonth.push(new Date(date));\n //Increment to next day\n date.setDate(date.getDate() + 1)\n }\n return daysInMonth\n }", "function dateFashion(you, date){\n if ((you >= 8 && date > 2) || (date >= 8 && you > 2))\n return 2;\n if (you <= 2 || date <= 2)\n return 0;\n else\n return 1;\n }", "function getDates(year) {\n\tvar dates = [];\n\tfor (var i = 1; i <= 12; i++) {\n\t\tdates.push(getSecondToLastThursday(i, year));\n\t}\n\treturn dates;\n}", "function numLeapYears(years) {\n\tlet a = 0;\n\tfor (let i = +years.split(\"-\")[0]; i <= +years.split(\"-\")[1]; i++) {\n\t\tif (new Date(i, 1, 29).getMonth() === 1) a++;\n\t}\n\treturn a;\n}", "function leapYear() {\r\n var y = 2021\r\n var i = 0\r\n while (i < 20) {\r\n if ((y % 4 === 0) && (y % 100 !== 0) || (y % 400 === 0)) {\r\n document.write(y + \"\\n\");\r\n y++\r\n i++\r\n }\r\n else {\r\n y++\r\n }\r\n }\r\n\r\n}", "function fullDate(dayNum)\n{\n var month;\n var monthDay;\n var weekdayNum;\n var day;\n if (dayNum > 7)\n {\n for(var i = dayNum; i >=1; i-=7)\n {\n if(i >0 && i < 8)\n {\n weekdayNum = i;\n break;\n }\n }\n }\n else\n {\n weekdayNum = dayNum;\n }\n switch (weekdayNum) {\n case 1:\n day = \"Sunday\";\n break;\n case 2:\n day = \"Monday\";\n break;\n case 3:\n day = \"Tuesday\";\n break;\n case 4:\n day = \"Wednesday\";\n break;\n case 5:\n day = \"Thursday\";\n break;\n case 6:\n day = \"Friday\";\n break;\n case 7:\n day = \"Saturday\";\n }\n switch(true)\n {\n case (dayNum <= 31):\n monthDay = dayNum;\n month = months[0];\n break;\n case (dayNum > 31 && dayNum <= 59):\n monthDay = dayNum - 31;\n month = months[1];\n break;\n case (dayNum > 59 && dayNum <= 90):\n monthDay = dayNum - 59;\n month = months[2];\n break;\n case (dayNum > 90 && dayNum <= 120):\n monthDay = dayNum - 90;\n month = months[3];\n break;\n case (dayNum > 120 && dayNum <= 151):\n monthDay = dayNum - 120;\n month = months[4];\n break;\n case (dayNum > 151 && dayNum <= 181):\n monthDay = dayNum - 151;\n month = months[5];\n break;\n case (dayNum > 181 && dayNum <= 212):\n monthDay = dayNum - 181;\n month = months[6];\n break;\n case (dayNum > 212 && dayNum <= 243):\n month = months[7];\n break;\n case (dayNum > 243 && dayNum <= 273):\n monthDay = dayNum - 243;\n month = months[8];\n break;\n case (dayNum > 273 && dayNum <= 304):\n monthDay = dayNum - 273;\n month = months[9];\n break;\n case (dayNum > 304 && dayNum <= 334):\n monthDay = dayNum - 304;\n month = months[10];\n break;\n case (dayNum > 334 && dayNum <= 365):\n monthDay = dayNum - 334;\n month = months[11];\n }\n console.log(day+\", \"+ month +\" \"+ monthDay + \", 2017\")\n}", "function season_sales_days_list(start_date, end_date, frequency, rpt_on, hrs) {\n\t//define local variables\n\t//var frequency_hash = { \"never\":0 , \"every_week\": 1, \"every_2_weeks\": 2, \"every_3_weeks\": 3, \"every_4_weeks\": 4, \"every_5_weeks\": 5, \"every_6_weeks\": 6, \"every_7_weeks\": 7, \"every_8_weeks\": 8 };\n\n}", "function getDayCount(day) {\n currentDayCount = day.split(\"-\")[1];\n daysInEmoji = \"\";\n if (!currentDayCount) {\n var result = \"\";\n currentDayCount.split(\"\").forEach(function(letter) {\n console.log(letter);\n if (\"0123456789\".includes(letter)) result = result + \"\" + letter;\n });\n dayCount = parseInt(result) + 1 + \"\"; //day counter\n\n dayCount.split(\"\").forEach(function(letter) {\n daysInEmoji += numberMap[letter];\n });\n } else {\n daysInEmoji = numberMap[0] + numberMap[1];\n }\n\n return daysInEmoji;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }